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
@@ -11,6 +11,8 @@ dist
|
|||||||
# through the offline delivery package, never copied into an image layer.
|
# through the offline delivery package, never copied into an image layer.
|
||||||
**/.env
|
**/.env
|
||||||
**/.env.*
|
**/.env.*
|
||||||
|
**/.worker-pool
|
||||||
|
**/worker-control
|
||||||
offline-backend-20260512/backend/.deer-flow
|
offline-backend-20260512/backend/.deer-flow
|
||||||
offline-backend-20260512/backend/logs
|
offline-backend-20260512/backend/logs
|
||||||
offline-backend-20260512/backend/docker-data
|
offline-backend-20260512/backend/docker-data
|
||||||
|
|||||||
@@ -85,12 +85,28 @@ offline-backend-20260512/backend/.deer-flow/*
|
|||||||
|
|
||||||
# Per-user skill_evolution overrides — runtime data written by the API
|
# Per-user skill_evolution overrides — runtime data written by the API
|
||||||
offline-backend-20260512/backend/skill_evolution.json
|
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/
|
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/
|
hermes-agent-main/
|
||||||
.gitignore
|
.gitignore
|
||||||
offline-backend-20260512/backend/tests/*
|
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_large_file_safety.py
|
||||||
!offline-backend-20260512/backend/tests/test_account_authentication.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
|
# Seeder-owned Agent Skills are product source; keep them out of the broad
|
||||||
# runtime `skills/` ignore above.
|
# runtime `skills/` ignore above.
|
||||||
!offline-backend-20260512/backend/app/gateway/routers/_*_seed_assets/skills/
|
!offline-backend-20260512/backend/app/gateway/routers/_*_seed_assets/skills/
|
||||||
@@ -101,7 +117,15 @@ offline-backend-20260512/backend/tests/*
|
|||||||
!offline-backend-20260512/backend/tests/test_query_slowdown_diagnosis_seed.py
|
!offline-backend-20260512/backend/tests/test_query_slowdown_diagnosis_seed.py
|
||||||
!offline-backend-20260512/backend/tests/test_elasticsearch_offline_ops_seed.py
|
!offline-backend-20260512/backend/tests/test_elasticsearch_offline_ops_seed.py
|
||||||
!offline-backend-20260512/backend/tests/test_task_report_convert.py
|
!offline-backend-20260512/backend/tests/test_task_report_convert.py
|
||||||
|
!offline-backend-20260512/backend/tests/test_task_deeplink_details.py
|
||||||
|
!offline-backend-20260512/backend/tests/test_offline_docs.py
|
||||||
!offline-backend-20260512/backend/tests/test_migration_compatibility.py
|
!offline-backend-20260512/backend/tests/test_migration_compatibility.py
|
||||||
|
# Keep the admin catalog hidden-switch (agent / business chain) store regressions versioned.
|
||||||
|
!offline-backend-20260512/backend/tests/test_roundtable_chain_hidden.py
|
||||||
|
# Keep the business-chain seat enrichment (available/live_name) regressions versioned.
|
||||||
|
!offline-backend-20260512/backend/tests/test_roundtable_chain_seat_enrichment.py
|
||||||
|
# Keep the dedicated taskId + goPath history Gateway contract versioned.
|
||||||
|
!offline-backend-20260512/backend/tests/test_task_deeplink_threads_api.py
|
||||||
!offline-backend-20260512/backend/tests/test_thread_clear.py
|
!offline-backend-20260512/backend/tests/test_thread_clear.py
|
||||||
# Keep project-scoped cross-conversation memory regressions versioned.
|
# Keep project-scoped cross-conversation memory regressions versioned.
|
||||||
!offline-backend-20260512/backend/tests/test_analysis_project_memory.py
|
!offline-backend-20260512/backend/tests/test_analysis_project_memory.py
|
||||||
@@ -140,6 +164,8 @@ offline-backend-20260512/backend/tests/*
|
|||||||
# Keep the model configuration regression coverage versioned even though
|
# Keep the model configuration regression coverage versioned even though
|
||||||
# this deployment repository otherwise ignores newly added backend tests.
|
# this deployment repository otherwise ignores newly added backend tests.
|
||||||
!offline-backend-20260512/backend/tests/test_model_management.py
|
!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.
|
# Keep the forced-research agent runtime gate and sandbox-policy regressions versioned.
|
||||||
!offline-backend-20260512/backend/tests/test_forced_research_agent.py
|
!offline-backend-20260512/backend/tests/test_forced_research_agent.py
|
||||||
# Keep strategy-selection built-in agent seed and safety-contract regressions versioned.
|
# Keep strategy-selection built-in agent seed and safety-contract regressions versioned.
|
||||||
@@ -171,6 +197,10 @@ offline-backend-20260512/backend/tests/*
|
|||||||
# Keep database-backed upload-policy, enforcement and bounded-preview regressions versioned.
|
# 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_upload_policy.py
|
||||||
!offline-backend-20260512/backend/tests/test_uploads_policy_enforcement.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
|
!offline-backend-20260512/backend/tests/test_artifact_preview.py
|
||||||
# Independent enterprise-research persistence, HTTP and race regressions.
|
# Independent enterprise-research persistence, HTTP and race regressions.
|
||||||
!offline-backend-20260512/backend/tests/test_enterprise_research_tasks.py
|
!offline-backend-20260512/backend/tests/test_enterprise_research_tasks.py
|
||||||
@@ -242,12 +272,23 @@ offline-backend-20260512/backend/skills/*
|
|||||||
offline-backend-20260512/backend/skills/public/*
|
offline-backend-20260512/backend/skills/public/*
|
||||||
!offline-backend-20260512/backend/skills/public/analysis-mindmap/
|
!offline-backend-20260512/backend/skills/public/analysis-mindmap/
|
||||||
!offline-backend-20260512/backend/skills/public/analysis-mindmap/SKILL.md
|
!offline-backend-20260512/backend/skills/public/analysis-mindmap/SKILL.md
|
||||||
|
# Built-in skill-creator ported from bytedance/deer-flow (product source too).
|
||||||
|
!offline-backend-20260512/backend/skills/public/skill-creator/
|
||||||
|
!offline-backend-20260512/backend/skills/public/skill-creator/**
|
||||||
|
|
||||||
# uv lockfile (not tracked per project preference)
|
# uv lockfile (not tracked per project preference)
|
||||||
offline-backend-20260512/backend/uv.lock
|
offline-backend-20260512/backend/uv.lock
|
||||||
|
|
||||||
!offline-backend-20260512/backend/tests/test_wiki_package_roundtrip.py
|
!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_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
|
||||||
|
!offline-backend-20260512/backend/tests/test_worker_deferred_admission.py
|
||||||
|
!offline-backend-20260512/backend/tests/test_db_loop_isolation.py
|
||||||
|
!offline-backend-20260512/backend/tests/test_chat_archive_postgres_integration.py
|
||||||
|
|
||||||
# Local-only scratch directory (not committed)
|
# Local-only scratch directory (not committed)
|
||||||
0622/
|
0622/
|
||||||
@@ -257,3 +298,4 @@ __pycache__/
|
|||||||
|
|
||||||
# misc
|
# misc
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
.worker-pool/
|
||||||
@@ -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 套风格的暗色变体;发送一条消息进入会话态,确认消息流恢复全局主题、页头胶囊保留专属色、输入框描边过渡正常。
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# 业务链选链去掉每次 `listAgents()` 查询
|
||||||
|
|
||||||
|
## 背景与思路
|
||||||
|
|
||||||
|
选链各环节展示只用到 seat 的 `agent_id + name`(快照已随链条落库,编辑器保存时刷新),额外全量拉 `/api/agents` 只为两件事:**席位存活判断**(existingIds)和**最新改名**(nameById)。存活是实时状态、无法落库保鲜,因此方案是:
|
||||||
|
|
||||||
|
- **后端**在返回链条(list/get 等)时,用一次批量 SQL(`agent_store.list_by_ids`,与 `/api/agents` 同一套可见性过滤)给每个 seat 附带 `available: bool` + `live_name: string | null` 两个**只读计算字段**(不落库,seats JSON 存储结构零变化、零迁移);
|
||||||
|
- **前端**选链全链路改用这两个字段,删除所有选链路径上的 `listAgents()` 调用;左栏点选一条链变为**零网络请求**(链条数据本就在内存里);选链弹窗打开只剩 1 个 `listChains` 小请求。
|
||||||
|
|
||||||
|
「只映射目前展示的这些」:仅 name + 存活状态,其他智能体字段一概不存(description 等快照维持现状,运行期配置由后端按 agent_id 自取,本就不依赖前端传参)。
|
||||||
|
|
||||||
|
## 后端改动
|
||||||
|
|
||||||
|
### 1. `offline-backend-20260512/backend/app/gateway/routers/roundtable_chains.py`
|
||||||
|
|
||||||
|
- 新增常量 `_FUNCTIONAL_AGENT_EXCLUSIONS`(`roundtable-intent` / `roundtable-recommender` / `roundtable-coordinator` / `roundtable-report` + 前缀 `roundtable-coordinator-`,与前端 `api/recommend.ts` 的 `filterRecommendCandidates` 排除集逐字对齐,保持"功能型内置智能体不可作席位"语义不变)。
|
||||||
|
- 新增纯函数 `_compute_seat_enrichment(chains, live_records) -> None`:对每条链每个 seat 写入 `available`(live 存在且不在排除集 → True)与 `live_name`(无则 None);配套薄异步封装 `_enrich_chain_seats(request, chains, user_id)`:收集去重小写 agent_id → `get_agent_store(request).list_by_ids(ids, user_id)` 一次查询(router 已 import `get_agent_store`,参照 `multi_agent.py` 的 `_get_agents_batch_direct` 写法)。
|
||||||
|
- 新增**响应专用** `ChainSeatResponseSchema(ChainSeatSchema)`,加 `available: bool | None`、`live_name: str | None`;`ChainResponse.seats` 改用之。创建/更新请求 schema 不动 → 富化字段永不被持久化(避免 create/update `model_dump()` 把默认值写进 seats JSON)。
|
||||||
|
- 在所有返回 `ChainResponse`(列表/单条/更新等)的出口调用富化。可见性语义与现状完全一致(`_listing_filter`:本人 / 内置 / 已发布、非私享、非管理员隐藏)。
|
||||||
|
|
||||||
|
### 2. 测试 `tests/test_roundtable_chain_seat_enrichment.py`(新建)
|
||||||
|
|
||||||
|
镜像 `test_roundtable_chain_stages.py` 的风格:纯函数用 dict 直接测(存活/缺失/排除集/改名刷新/混合多条链);`list_by_ids` 交互用同名小写归一化断言(stub store)。
|
||||||
|
|
||||||
|
## 前端改动(frontend-web)
|
||||||
|
|
||||||
|
### 3. `src/roundtable-planning/lib/business-chain.ts`
|
||||||
|
|
||||||
|
- `ChainSeat` 增加可选 `available?: boolean`(undefined = 旧后端未标注 → 视为存活,与现有"查询失败不判删"降级语义一致)和 `live_name?: string | null`,附注释说明来源与回退顺序。
|
||||||
|
- `buildChainSeatSelection(chain, candidates?)`:`candidates` 改**可选**;不传时存活 = `seat.available !== false`、名称 = `live_name ?? name ?? agent_id`;传入时保持现行为(测试兼容)。
|
||||||
|
|
||||||
|
### 4. `src/roundtable-planning/components/BusinessChainPicker.tsx`
|
||||||
|
|
||||||
|
加载 effect 只留 `listChains(scope)`;删 `listAgents()`、`filterRecommendCandidates` 及 `existingIds`/`nameById` state——存活判断用 `seat.available !== false`,tag 名称用 `live_name ?? seat.name ?? agent_id`;已删置灰/删除线/「存活不足 2 个」等 UI 保持不变(改由 `available` 驱动)。`handleUse` 的 `nameOf` 同步改。
|
||||||
|
|
||||||
|
### 5. `src/roundtable-planning/components/BusinessChainListDialog.tsx`
|
||||||
|
|
||||||
|
`BusinessChainListBody` 删除挂载时的 `listAgents()` effect 与 `nameById` map;`ChainSeatsFlow` 的 seatTag 标签改 `seat.live_name ?? seat.name ?? agentId`。
|
||||||
|
|
||||||
|
### 6. `src/roundtable-planning/pages/RoundtablePlanningPage.tsx`(3 处调用点)
|
||||||
|
|
||||||
|
- **L486 固定链 effect(8BF 等)**:`Promise.all([getChain, listAgents])` → 仅 `getChain`;席位不足提示改为按 `seat.available === false` 计算(文案不变)。
|
||||||
|
- **L1356 `handleSelectChainFromSidebar`(左栏点选,本次体验痛点核心)**:删 `listAgents()`,直接 `buildChainSeatSelection(chain)` —— 点选零请求。
|
||||||
|
- **L1503 C3 深链自动选链**:删 `listAgents()` 分支。
|
||||||
|
- 清理不再使用的 `listAgents` / `filterRecommendCandidates` import(编辑器页与「智能推荐」tab 的 `listAgents` 是选智能体池所必需,保留不动)。
|
||||||
|
|
||||||
|
### 7. 测试 `src/roundtable-planning/lib/business-chain.test.ts`(新建,node:test 风格同 `chain-stages.test.ts`)
|
||||||
|
|
||||||
|
覆盖无 candidates 分支:`available` 缺省视为存活、`available:false` 过滤、不足 2 席返回 null、`live_name` 优先于快照名、dag 分支不受影响;package.json 加 `test:business-chain` 脚本。
|
||||||
|
|
||||||
|
### 8. 文档 `frontend-web/docs/multi-agent-business-chain-dev.md`
|
||||||
|
|
||||||
|
补一段:链条响应 seat 附带 `available`/`live_name`(后端读时计算、不落库);选链前端不再调 `listAgents()`。
|
||||||
|
|
||||||
|
## 兼容性
|
||||||
|
|
||||||
|
- 新后端 + 旧前端:响应多两个字段,旧代码忽略,无影响。
|
||||||
|
- 旧后端 + 新前端:`available` undefined → 全按存活处理,行为等于现在"agents 查询失败"的降级路径;若智能体真被删,Step 2 init 的后端 404 硬校验仍兜底(现状即有)。
|
||||||
|
- 存量链条 seats JSON 无需迁移;8BF / 岗位协同 / official-task-analysis 等消费 seat 快照的模块零改动。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
- 后端:`PYTHONPATH=. uv run pytest tests/test_roundtable_chain_seat_enrichment.py tests/test_roundtable_chain_stages.py tests/test_roundtable_chain_hidden.py -v` + `make lint`(ruff)。
|
||||||
|
- 前端:`pnpm typecheck` + `node --experimental-strip-types --test src/roundtable-planning/lib/business-chain.test.ts`。
|
||||||
@@ -88,9 +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`
|
- **Routing**: React Router v7; top-level routes in `src/pages/PageRoutes.tsx`, workspace sub-routes in `src/pages/WorkspaceRoutes.tsx`
|
||||||
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
|
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
|
||||||
- **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`.
|
- **智能体对话跳转**: 创建页、智能体管理编辑框和问答页详情面板都可以给智能体配置「对话跳转」链接、打开方式(新窗口 / 当前窗口)和路由参数(登录参数、主题参数,解析方式与应用管理相同)。配置保存在该智能体 `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`. **素材检索技能池限定白名单**:`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).
|
- **轻应用中心 (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.
|
- **菜单管理 (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/`。
|
- **舆情分析智能体(前端虚拟智能体)**: 智能体管理页新增「舆情分析」类型 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 等侧栏宽度过渡稳定后再测量高亮框。
|
- **简洁模式用户引导 (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>` 窗口事件强制重放(忽略已看过记忆)。
|
- **智能体使用引导 (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>` 窗口事件强制重放(忽略已看过记忆)。
|
||||||
@@ -98,12 +121,15 @@ 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 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/`。
|
- **技能地址管理 (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`.
|
- **按钮管理 (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`.
|
||||||
- **上下文近 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`。
|
- **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` 只建表、**不迁移/回填旧数据**。
|
||||||
|
- **上下文与对话轮数(管理员全局设置)**: 「设置 → 上下文管理」可开启 `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`
|
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes`
|
||||||
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
|
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
|
||||||
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
|
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
|
||||||
- **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
|
- **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
|
||||||
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A inside a **任务工作区** (resolved via `/api/business-mapping`; `resolveTaskDeeplinkTarget` calls `persistTaskContext({taskId, agentId, openingText})` and navigates to the `…/chats` **index**, which opens the latest task conversation or 新建 — a 1:N task↔对话 workspace, NOT `pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. **xdfx's deep-link `?taskId=` is actually an 行动id, not a 任务id** — `resolveDeeplinkTaskId(goPath, rawId)` (called in `LoginPage` before everything) detects `xdfx`/`xdfx-A` and resolves it via `GET {action_detail_url}/{actionId}` → `data.taskId` (`fetchTaskIdFromAction`; `action_test`+`mock.action_detail` for offline testing); the resolved 任务id then drives `cop-task-detail`, the purpose tree, and the 1:N binding (other businesses pass the id through unchanged). **xdfx additionally partitions its chat records by 行动id (action_id), NOT by task_id**: `resolveTaskDeeplinkTarget` sets `partitionByAction:true` + keeps the raw action_id as `TaskContext.actionId`, so new threads are tagged `metadata.{taskId,actionId}` (taskId kept only to preserve the backend「任务深链对话全局共享」semantics, which keys off `metadata.taskId`) and the conversation list filters by `actionId` (+`agent_id`) — different actions of the same task get separate lists. xdfx's first-question opening text also appends `行动id(action_id)为…` (see `buildOpeningText` / `taskThreadMetadata`). goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. The roundtable target also threads the URL `taskId` into `roundtablePrefill.taskId` (`resolveTaskDeeplinkTarget(goPath, detail, taskId)`), which turns on two taskId-scoped behaviors: (1) **separate, unpartitioned per-task storage** — taskId 会商聊天记录 live in their **own** store/table (`roundtable_task_drafts`), keyed **only by `task_id`** (one taskId = many records, shared across users, **no user 分权** at all; `created_by` is audit-only), kept entirely out of the per-user personal store (`roundtable_drafts`, now strictly per-user) so the two never mix. Backend router `/api/roundtable-task-drafts` (`GET /by-task/{id}` + `/by-task/{id}/latest`, `POST`, `GET/PUT/DELETE /{id}` — all user-agnostic); frontend client `roundtable-planning/api/task-drafts.ts`, and `useDraftPersistence`/`useRoundtableDrafts` route **all** CRUD to it when a `taskId` is present (else the personal `drafts.ts`). The matching **background jobs** are shared by task too: `roundtable_jobs.task_id` marks a task job; reads/dedup/stream/resume/cancel pass `?task_id=` so any user opening the task sees the same running 研讨 (progress/flowchart), and the executor writes the final report back to the task-draft store. Existing rows are moved over by `scripts/migrate_roundtable_task_drafts.py` (migration `20260618_01`). The history dropdown filters to the task and 新建 keeps the binding; (2) **Step-3 auto structured output** — after the `roundtable-summary` agent writes the Markdown report it automatically runs a second round emitting a `flow-json` flowchart (`useStep3Summary` `autoFlow`+`chainLevels`), whose hierarchy follows the business chain's stage goals (任务 → 目的 → 行为体 → …; coordinatorPrompt-specified hierarchy wins) and whose nodes never carry 阶段编号/阶段名 (the prior bug). **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. **All three single-agent businesses share `TaskFxWorkspace`** (`task-components/TaskFxWorkspace.tsx`): left = a「当前任务」card (`readCopTaskDetail()` 任务名称 + 简介, desensitized, 留存 above 新建对话) + per-task 1:N conversation list (`useTaskThreads(taskId, agentId, actionId?)` — filtered by **both** `metadata.taskId` AND `metadata.agent_id` so the three businesses' conversations staLine truncated
|
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent/taskType`; opening text maps `taskType` 1/2/3 to 打击/塑势/防御) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A inside a **任务工作区** (resolved via `/api/business-mapping`; `resolveTaskDeeplinkTarget` calls `persistTaskContext({taskId, agentId, openingText})` and navigates to the `…/chats` **index**, which opens the latest task conversation or 新建 — a 1:N task↔对话 workspace, NOT `pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. **xdfx's deep-link `?taskId=` is actually an 行动id, not a 任务id** — `resolveDeeplinkTaskId(goPath, rawId)` (called in `LoginPage` before everything) detects `xdfx`/`xdfx-A` and resolves it via `GET {action_detail_url}/{actionId}` → `data.taskId` (`fetchTaskIdFromAction`; `action_test`+`mock.action_detail` for offline testing); the resolved 任务id then drives `cop-task-detail`, the purpose tree, and the 1:N binding (other businesses pass the id through unchanged). **xdfx additionally partitions its chat records by 行动id (action_id), NOT by task_id**: `resolveTaskDeeplinkTarget` sets `partitionByAction:true` + keeps the raw action_id as `TaskContext.actionId`, so new threads are tagged `metadata.{taskId,actionId}` (taskId kept only to preserve the backend「任务深链对话全局共享」semantics, which keys off `metadata.taskId`) and the conversation list filters by `actionId` (+`agent_id`) — different actions of the same task get separate lists. xdfx's first-question opening text also appends `行动id(action_id)为…` (see `buildOpeningText` / `taskThreadMetadata`). goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. The roundtable target also threads the URL `taskId` into `roundtablePrefill.taskId` (`resolveTaskDeeplinkTarget(goPath, detail, taskId)`), which turns on two taskId-scoped behaviors: (1) **separate, unpartitioned per-task storage** — taskId 会商聊天记录 live in their **own** store/table (`roundtable_task_drafts`), keyed **only by `task_id`** (one taskId = many records, shared across users, **no user 分权** at all; `created_by` is audit-only), kept entirely out of the per-user personal store (`roundtable_drafts`, now strictly per-user) so the two never mix. Backend router `/api/roundtable-task-drafts` (`GET /by-task/{id}` + `/by-task/{id}/latest`, `POST`, `GET/PUT/DELETE /{id}` — all user-agnostic); frontend client `roundtable-planning/api/task-drafts.ts`, and `useDraftPersistence`/`useRoundtableDrafts` route **all** CRUD to it when a `taskId` is present (else the personal `drafts.ts`). The matching **background jobs** are shared by task too: `roundtable_jobs.task_id` marks a task job; reads/dedup/stream/resume/cancel pass `?task_id=` so any user opening the task sees the same running 研讨 (progress/flowchart), and the executor writes the final report back to the task-draft store. Existing rows are moved over by `scripts/migrate_roundtable_task_drafts.py` (migration `20260618_01`). The history dropdown filters to the task and 新建 keeps the binding; (2) **Step-3 auto structured output** — after the `roundtable-summary` agent writes the Markdown report it automatically runs a second round emitting a `flow-json` flowchart (`useStep3Summary` `autoFlow`+`chainLevels`), whose hierarchy follows the business chain's stage goals (任务 → 目的 → 行为体 → …; coordinatorPrompt-specified hierarchy wins) and whose nodes never carry 阶段编号/阶段名 (the prior bug). **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. **All three single-agent businesses share `TaskFxWorkspace`** (`task-components/TaskFxWorkspace.tsx`): left = a「当前任务」card (`readCopTaskDetail()` 任务名称 + 简介, desensitized, 留存 above 新建对话) + per-task 1:N conversation list (`useTaskThreads(taskId, agentId, actionId?)` — filtered by **both** `metadata.taskILine truncated
|
||||||
- **agentfx 任务深链(新系统 iframe 嵌入的智能体问答,3qfx 单智能体 lite 模式的独立复制)**: goPath=`agentfx`(`${loginBase}?password=…&taskId=…&goPath=agentfx&embed=1&hideJump=1&theme=dark-blue`)。与 3qfx 的差异:①任务详情不走外部 consumer,改调**本系统 Gateway** `GET {backend}/taskAnalyseSearch/cop-task-detail?taskId=`(`apiFetch` 带刚登录的 DeerFlow 态;任务数据来自 TaskCOP 任务表,与任务列表/报告导入同一份);②**固定使用内置智能体** `agentfx-analyst`(不走业务映射);③路由 `task-management/plan-task-agentfx/agent/:agent_id/chats`,页面为独立复制的 `AgentFxWorkspace.tsx`(`AgentFxWorkspace`/`AgentFxIndexResolver`/`AgentFxChat` —— 左「当前任务」卡 + 1:N 对话列表 + 新建对话,`AgentChatPage taskBind` 自动发开场白;无 TaskJumpBar/清除记录/闸门/xdfx 行动卡)。模块 `core/auth/agentfx-deeplink.ts`(`isAgentfxGoPath`/`fetchAgentfxTaskDetail`/`resolveAgentfxDeeplinkTarget`);任务详情整包仍存共享键 `login.copTaskDetail`(按标签页隔离),`AgentChatPage` 的 taskBind 自恢复对 agentfx 生效。`LoginPage` 在既有深链分支前用 `isAgentfxGoPath` 分流。**内置「任务研判报告助手」**:后端 seeder `app/gateway/routers/_agentfx_seed.py` + `_agentfx_seed_assets/`(config.yaml + SOUL.md,目录存在不覆盖;app.py lifespan 在 `_sync_legacy_agents` 之前调用,自动进 agents 表 user_id IS NULL)——SOUL 规定工作流「搜集信息(`web_search`,**首步不可跳过**)→ 每次检索 JSON 原样落盘 `/mnt/user-data/workspace/hits/qN.json` → **一条命令** `task-report-build`(group `all`)技能函数转换成 14 类 `task-reports.json`(模型禁止手写该 JSON;分页技能 `task-report-{enemy,our,env,judge}` 仅用于事后补跑单页;五者都是共享引擎 `task-report-lib/convert_lib.py` 的瘦 CLI,`resolve_hit_files` 对虚拟绝对路径读空的情况自动回退到相对写法并在 `warnings` 里列出尝试过的路径,免得智能体自己写脚本排查)→ `write_file` 生成 `/mnt/user-data/outputs/report.md` → 聊天总结 → 引导入库」,硬性约束:categoryType 逐字用 14 个全称(禁缩写自造如「DQ关键事件」)、JSON 直接写汉字禁 `\uXXXX` 转义、每类必须有实质内容不许空数组/纯占位、文件一律用 `/mnt/user-data/...` 虚拟路径(防宿主路径泄漏进 tool args)。**检索依赖 `config.yaml tools.web_search`(DDG,enabled 已开;内网需换 configurable_search 时改回并填 endpoint)**。任务工作区输入框在 `taskCtxOn` 时隐藏「写作/记忆/参考文献」(InputBox `hideContextTools` prop)与「知识空间」(不传 knowledgeSelector);消息流里 write_file 文件卡片只显示文件名(`artifactDisplayName` 收敛宿主/虚拟路径)。**入库两条路径**:(a) **前端协助卡** —— `AgentChatPage`(taskBind 且非 taskGate)检测线程 artifacts 出现 `task-reports.json`(按文件名后缀匹配,兼容本地沙箱记录的宿主路径)且流式结束时,向 displayThread 尾部注入 `additional_kwargs.task_report_import_approval` 虚拟 ai 消息(`core/messages/utils.ts` 分组 `assistant:task-report-import` + `MessageList` 的 `taskReportImportSlot` 插槽渲染 `TaskReportImportCard`),点「开始入库」前端校验(`strategy-components/lib/agentfx-report-schema.ts`,14 类 + contentJson 合法 JSON + **\u 转义归一化还原为汉字**,与技能脚本同规则)后 `importTaskReport`(`strategy-components/api/task-reports.ts`)POST 导入接口整体替换;任务已有详情**不抑制**卡片(入库即整体替换,卡片文案说明覆盖语义),导入成功按 thread 记 sessionStorage(刷新不重复询问)、「暂不入库」为会话内记忆;(b) **入库技能** `task-report-import`(seeder 一并复制到 `skills/public/`,public 类技能 extensions_config 缺省即启用)—— 用户聊天里说「入库」时智能体按 SKILL.md 用 bash 跑 `scripts/task_report_import.py`(纯标准库:同样的校验规则 + 转义归一化;**默认关闭 SSL 证书校验** `ssl._create_unverified_context` + 忽略代理,适配内网自签证书;鉴权 `--token`/env `AGENTFX_IMPORT_TOKEN`→`DEERFLOW_AUTH_TOKEN`→`TOOLS_TOKEN` 优先,缺省经公共端点 `POST /api/parallel-agents/auth/token` 以 `agentfx-import` 用户现签 token——内网既有鉴权旁路;gateway 地址 env `AGENTFX_GATEWAY_URL` 或 `http://127.0.0.1:{DEER_FLOW_GATEWAY_PORT}`);`--strict` 可要求 14 类齐全,默认允许部分导入并在 stdout JSON 的 `missing_categories` 里列缺。入库成功后任务 TaskCOP 状态自动置 25(已完成分析)。**入库成功通知宿主**(iframe 嵌入场景):两条路径成功后都会 `window.top.postMessage({source: "magent-web", type: "Line truncated
|
- **agentfx 任务深链(新系统 iframe 嵌入的智能体问答,3qfx 单智能体 lite 模式的独立复制)**: goPath=`agentfx`(`${loginBase}?password=…&taskId=…&goPath=agentfx&embed=1&hideJump=1&theme=dark-blue`)。与 3qfx 的差异:①任务详情不走外部 consumer,改调**本系统 Gateway** `GET {backend}/taskAnalyseSearch/cop-task-detail?taskId=`(`apiFetch` 带刚登录的 DeerFlow 态;任务数据来自 TaskCOP 任务表,与任务列表/报告导入同一份);②**固定使用内置智能体** `agentfx-analyst`(不走业务映射);③路由 `task-management/plan-task-agentfx/agent/:agent_id/chats`,页面为独立复制的 `AgentFxWorkspace.tsx`(`AgentFxWorkspace`/`AgentFxIndexResolver`/`AgentFxChat` —— 左「当前任务」卡 + 1:N 对话列表 + 新建对话,`AgentChatPage taskBind` 自动发开场白;无 TaskJumpBar/清除记录/闸门/xdfx 行动卡)。模块 `core/auth/agentfx-deeplink.ts`(`isAgentfxGoPath`/`fetchAgentfxTaskDetail`/`resolveAgentfxDeeplinkTarget`);任务详情整包仍存共享键 `login.copTaskDetail`(按标签页隔离),`AgentChatPage` 的 taskBind 自恢复对 agentfx 生效。`LoginPage` 在既有深链分支前用 `isAgentfxGoPath` 分流。**内置「任务研判报告助手」**:后端 seeder `app/gateway/routers/_agentfx_seed.py` + `_agentfx_seed_assets/`(config.yaml + SOUL.md,目录存在不覆盖;app.py lifespan 在 `_sync_legacy_agents` 之前调用,自动进 agents 表 user_id IS NULL)——SOUL 规定工作流「搜集信息(`web_search`,**首步不可跳过**)→ 每次检索 JSON 原样落盘 `/mnt/user-data/workspace/hits/qN.json` → **一条命令** `task-report-build`(group `all`)技能函数转换成 14 类 `task-reports.json`(模型禁止手写该 JSON;分页技能 `task-report-{enemy,our,env,judge}` 仅用于事后补跑单页;五者都是共享引擎 `task-report-lib/convert_lib.py` 的瘦 CLI,`resolve_hit_files` 对虚拟绝对路径读空的情况自动回退到相对写法并在 `warnings` 里列出尝试过的路径,免得智能体自己写脚本排查)→ `write_file` 生成 `/mnt/user-data/outputs/report.md` → 聊天总结 → 引导入库」,硬性约束:categoryType 逐字用 14 个全称(禁缩写自造如「DQ关键事件」)、JSON 直接写汉字禁 `\uXXXX` 转义、每类必须有实质内容不许空数组/纯占位、文件一律用 `/mnt/user-data/...` 虚拟路径(防宿主路径泄漏进 tool args)。**检索依赖 `config.yaml tools.web_search`(DDG,enabled 已开;内网需换 configurable_search 时改回并填 endpoint)**。任务工作区输入框在 `taskCtxOn` 时隐藏「写作/记忆/参考文献」(InputBox `hideContextTools` prop)与「知识空间」(不传 knowledgeSelector);消息流里 write_file 文件卡片只显示文件名(`artifactDisplayName` 收敛宿主/虚拟路径)。**入库两条路径**:(a) **前端协助卡** —— `AgentChatPage`(taskBind 且非 taskGate)检测线程 artifacts 出现 `task-reports.json`(按文件名后缀匹配,兼容本地沙箱记录的宿主路径)且流式结束时,向 displayThread 尾部注入 `additional_kwargs.task_report_import_approval` 虚拟 ai 消息(`core/messages/utils.ts` 分组 `assistant:task-report-import` + `MessageList` 的 `taskReportImportSlot` 插槽渲染 `TaskReportImportCard`),点「开始入库」前端校验(`strategy-components/lib/agentfx-report-schema.ts`,14 类 + contentJson 合法 JSON + **\u 转义归一化还原为汉字**,与技能脚本同规则)后 `importTaskReport`(`strategy-components/api/task-reports.ts`)POST 导入接口整体替换;任务已有详情**不抑制**卡片(入库即整体替换,卡片文案说明覆盖语义),导入成功按 thread 记 sessionStorage(刷新不重复询问)、「暂不入库」为会话内记忆;(b) **入库技能** `task-report-import`(seeder 一并复制到 `skills/public/`,public 类技能 extensions_config 缺省即启用)—— 用户聊天里说「入库」时智能体按 SKILL.md 用 bash 跑 `scripts/task_report_import.py`(纯标准库:同样的校验规则 + 转义归一化;**默认关闭 SSL 证书校验** `ssl._create_unverified_context` + 忽略代理,适配内网自签证书;鉴权 `--token`/env `AGENTFX_IMPORT_TOKEN`→`DEERFLOW_AUTH_TOKEN`→`TOOLS_TOKEN` 优先,缺省经公共端点 `POST /api/parallel-agents/auth/token` 以 `agentfx-import` 用户现签 token——内网既有鉴权旁路;gateway 地址 env `AGENTFX_GATEWAY_URL` 或 `http://127.0.0.1:{DEER_FLOW_GATEWAY_PORT}`);`--strict` 可要求 14 类齐全,默认允许部分导入并在 stdout JSON 的 `missing_categories` 里列缺。入库成功后任务 TaskCOP 状态自动置 25(已完成分析)。**入库成功通知宿主**(iframe 嵌入场景):两条路径成功后都会 `window.top.postMessage({source: "magent-web", type: "Line truncated
|
||||||
- **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。第三个开关 `?isolate=1`(**独立登录会话**)把同一套**登录用户隔离**单独提供给**普通(带 chrome)标签页**——只切换鉴权存储、不去 chrome / 不强制主题 / 不动跳转栏:`authStorage()` 的条件从「仅嵌入」放宽为 `isEmbedActive() || isIsolatedSession()`,`AuthSyncWatcher` 的跨标签监听对嵌入态**或**独立态都即时忽略(handler 内实时判,运行时开关也即刻生效)。除 URL 参数外,**设置 → 外观 →「登录会话」** 有一个 Switch「独立登录会话(本标签页)」运行时切换(`setIsolatedSession`,`appearance-settings-page.tsx`):**开启时先 `migrateAuthToSession()`**(`scoped-storage.ts`,把 localStorage 的受保护键 `deerflow.auth`/`userInfo`/`userId`/`tools_token` + `login.*` 前缀快照搬进 sessionStorage)再翻标志,故无感不登出;此后本标签页登录态独立——别处登录/换号影响不到它,它换号也影响不到别人,但关掉该标签即结束(需重登)。开启给 toast 提示。
|
- **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。第三个开关 `?isolate=1`(**独立登录会话**)把同一套**登录用户隔离**单独提供给**普通(带 chrome)标签页**——只切换鉴权存储、不去 chrome / 不强制主题 / 不动跳转栏:`authStorage()` 的条件从「仅嵌入」放宽为 `isEmbedActive() || isIsolatedSession()`,`AuthSyncWatcher` 的跨标签监听对嵌入态**或**独立态都即时忽略(handler 内实时判,运行时开关也即刻生效)。除 URL 参数外,**设置 → 外观 →「登录会话」** 有一个 Switch「独立登录会话(本标签页)」运行时切换(`setIsolatedSession`,`appearance-settings-page.tsx`):**开启时先 `migrateAuthToSession()`**(`scoped-storage.ts`,把 localStorage 的受保护键 `deerflow.auth`/`userInfo`/`userId`/`tools_token` + `login.*` 前缀快照搬进 sessionStorage)再翻标志,故无感不登出;此后本标签页登录态独立——别处登录/换号影响不到它,它换号也影响不到别人,但关掉该标签即结束(需重登)。开启给 toast 提示。
|
||||||
|
|
||||||
|
|||||||
@@ -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`
|
- **Routing**: React Router v7; top-level routes in `src/pages/PageRoutes.tsx`, workspace sub-routes in `src/pages/WorkspaceRoutes.tsx`
|
||||||
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
|
- **Pages**: `ChatPage` (thread chat), `AgentChatPage` (custom agent chat), `AgentsPage`/`NewAgentPage` (agent management), `ScheduledTasksPage`/`ScheduledTaskRunDetailPage` (scheduled tasks), `LightAppManagementPage`/`LightAppListPage`/`LightAppIframeView` (轻应用中心 — register/list/embed mini-apps)
|
||||||
- **普通问答地图可视化**: 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.
|
- **智能体对话跳转**: 创建页、智能体管理编辑框和问答页详情面板都可以给智能体配置「对话跳转」链接、打开方式(新窗口 / 当前窗口)和路由参数(登录参数、主题参数,解析方式与应用管理相同)。配置保存在该智能体 `config.yaml` 的 `chat_link`,并镜像到 `agent_extras.chat_link` 供列表读取。留空时智能体管理的「对话」按钮仍进入本系统问答;填了地址后,按钮按解析后的链接跳转。
|
||||||
- **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。
|
- **普通问答地图可视化**: 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.
|
- **定时任务「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`.
|
- **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`.
|
- **策略优选**: 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`.
|
||||||
@@ -133,11 +135,12 @@ The frontend (`frontend-web/`) is a React 19 + Vite SPA:
|
|||||||
- **会话冲突与模型工具流恢复**: when a user submits a new question while the previous turn is still streaming, the backend's `RunManager.create_or_reject` rejects with HTTP 409 (`services.py` returns the Chinese detail「当前对话还在生成回答…」). `core/threads/hooks.ts` detects the conflict and routes it through `confirmOrRejoin`. Run-creation SSE responses expose `Content-Location` plus the SDK `Location` reconnect endpoint; `core/api/api-client.ts` records the last consumed event id, so an in-page rejoin resumes after that cursor instead of replaying tool arguments from `-1`. `write_file` argument updates carried by `messages-tuple` count as business activity. A known active run is probed only after 90 seconds without a business frame; the watchdog hides `lg:stream`, stops only the old browser reader, and rejoins without cancelling the backend run. Clean EOF, transport errors, 409 and watchdog recovery share one single-flight Promise to prevent duplicate joins/finalization. The backend `PatchedChatOpenAI` separately normalizes confirmed cumulative argument snapshots and bounded compatible response shapes while preserving standard deltas; its content-free diagnostics never log prompts, arguments or file bodies.
|
- **会话冲突与模型工具流恢复**: when a user submits a new question while the previous turn is still streaming, the backend's `RunManager.create_or_reject` rejects with HTTP 409 (`services.py` returns the Chinese detail「当前对话还在生成回答…」). `core/threads/hooks.ts` detects the conflict and routes it through `confirmOrRejoin`. Run-creation SSE responses expose `Content-Location` plus the SDK `Location` reconnect endpoint; `core/api/api-client.ts` records the last consumed event id, so an in-page rejoin resumes after that cursor instead of replaying tool arguments from `-1`. `write_file` argument updates carried by `messages-tuple` count as business activity. A known active run is probed only after 90 seconds without a business frame; the watchdog hides `lg:stream`, stops only the old browser reader, and rejoins without cancelling the backend run. Clean EOF, transport errors, 409 and watchdog recovery share one single-flight Promise to prevent duplicate joins/finalization. The backend `PatchedChatOpenAI` separately normalizes confirmed cumulative argument snapshots and bounded compatible response shapes while preserving standard deltas; its content-free diagnostics never log prompts, arguments or file bodies.
|
||||||
- **React #185 与流式刷新保护**: every direct LangGraph `useStream` surface (main/agent chat, AI writing, Canvas and Studio notebook) uses shared `STREAM_RENDER_BATCHING = true`. The installed SDK implements numeric `throttle: 16` as a trailing debounce, which can indefinitely postpone UI updates during a continuous fast stream; `true` retains asynchronous next-task batching without requiring 16ms silence. `stream-error-classification.ts` detects `Maximum update depth exceeded` / production `#185` through bounded, cycle-safe wrappers. Main chat filters the SDK's stored error and duplicate submit rejection; `react-ui-error.ts` gives each send at most one automatic UI recovery, then pauses rejoin without cancelling the server run. Token activity must not reset that budget. The top-level `ReactUiErrorBoundary` catches only this render/commit error, shows a static friendly reload panel, and never automatically remounts the failing tree. Other errors are not swallowed. Shared toasts are deduplicated for 30 seconds; diagnostics retain error type, recovery phase, thread/run identifiers and component stack but never message/tool content. Real SDK SSE replay covers partial reasoning and write_file Markdown before generation ends; the browser boundary check triggers a real production React layout-effect loop and requires manual reload to recover. These safeguards do not prove the unknown production component loop is fixed.
|
- **React #185 与流式刷新保护**: every direct LangGraph `useStream` surface (main/agent chat, AI writing, Canvas and Studio notebook) uses shared `STREAM_RENDER_BATCHING = true`. The installed SDK implements numeric `throttle: 16` as a trailing debounce, which can indefinitely postpone UI updates during a continuous fast stream; `true` retains asynchronous next-task batching without requiring 16ms silence. `stream-error-classification.ts` detects `Maximum update depth exceeded` / production `#185` through bounded, cycle-safe wrappers. Main chat filters the SDK's stored error and duplicate submit rejection; `react-ui-error.ts` gives each send at most one automatic UI recovery, then pauses rejoin without cancelling the server run. Token activity must not reset that budget. The top-level `ReactUiErrorBoundary` catches only this render/commit error, shows a static friendly reload panel, and never automatically remounts the failing tree. Other errors are not swallowed. Shared toasts are deduplicated for 30 seconds; diagnostics retain error type, recovery phase, thread/run identifiers and component stack but never message/tool content. Real SDK SSE replay covers partial reasoning and write_file Markdown before generation ends; the browser boundary check triggers a real production React layout-effect loop and requires manual reload to recover. These safeguards do not prove the unknown production component loop is fixed.
|
||||||
- **流式游标作用域**: resumable cursors belong to the current SDK message accumulator, not a module-global map. `createStreamAPIClient` isolates same-reader recovery; newly mounted chats and real thread switches must replay the retained prefix instead of borrowing another reader's consumed position. Clearing replaces the cursor map so late old-reader events cannot pollute the new scope. The shared `getAPIClient` does not rewrite replay-from-start cursors. `stream-cursor-replay.test.ts` uses the real SDK to protect against both duplicate tool arguments on reconnect and missing prefixes on reopening.
|
- **流式游标作用域**: resumable cursors belong to the current SDK message accumulator, not a module-global map. `createStreamAPIClient` isolates same-reader recovery; newly mounted chats and real thread switches must replay the retained prefix instead of borrowing another reader's consumed position. Clearing replaces the cursor map so late old-reader events cannot pollute the new scope. The shared `getAPIClient` does not rewrite replay-from-start cursors. `stream-cursor-replay.test.ts` uses the real SDK to protect against both duplicate tool arguments on reconnect and missing prefixes on reopening.
|
||||||
|
- **单智能体任务深链聊天记录(2026-10-19)**: `3qfx` / `rwfx` / `xdfx` 已不再通过 `useTaskThreads` 扫描、过滤通用 `threads_meta` 列表;`TaskFxWorkspace` / `TaskFxIndexResolver` 统一调用 `useTaskDeeplinkThreads` → `GET /api/task-deeplink-threads?task_id=&go_path=`,读取独立表 `task_deeplink_threads` 的 `(task_id, go_path)` 索引,再按 `thread_id` 关联 canonical `threads_meta` 标题/状态(消息与 checkpoint 仍由 LangGraph 管理)。新会话 metadata 写 `taskRecordId`、`taskGoPath`、`thread_type=task_deeplink` 并由 thread-meta 仓储同事务登记;`3qfx/rwfx` 的 `taskRecordId` 是任务 id,`xdfx` 是 URL 原始行动 id(真实任务 id 仍保留在 `metadata.taskId` 维持共享访问语义)。普通聊天记录默认隐藏该 thread type;显式 taskId 查询仍可读取。迁移 `20261019_01` **只建表、不回填旧数据**,因此上线前旧深链会话不会出现在新列表。`/api/open/3qfx/ask` 同样写专用索引。Tests: `packages/harness/tests/test_task_deeplink_threads.py`, `src/core/auth/task-purpose-metadata.test.ts`, `src/core/threads/hidden-chats.test.ts`。
|
||||||
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes`
|
- **State**: TanStack Query for server state, context providers (`SubtasksProvider`, `ArtifactsProvider`, `PromptInputProvider`) scoped to `WorkspaceRoutes`
|
||||||
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
|
- **LLM streaming**: `@langchain/langgraph-sdk` streams messages from the backend via SSE
|
||||||
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
|
- **UI**: Radix UI primitives + TailwindCSS v4 + shadcn-style components in `src/components/ui/`
|
||||||
- **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
|
- **Shims**: `src/shims/` provides `next/link` and `next/navigation` polyfills (original code was Next.js)
|
||||||
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent`) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A inside a **任务工作区** (resolved via `/api/business-mapping`; `resolveTaskDeeplinkTarget` calls `persistTaskContext({taskId, agentId, openingText})` and navigates to the `…/chats` **index**, which opens the latest task conversation or 新建 — a 1:N task↔对话 workspace, NOT `pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. **xdfx's deep-link `?taskId=` is actually an 行动id, not a 任务id** — `resolveDeeplinkTaskId(goPath, rawId)` (called in `LoginPage` before everything) detects `xdfx`/`xdfx-A` and resolves it via `GET {action_detail_url}/{actionId}` → `data.taskId` (`fetchTaskIdFromAction`; `action_test`+`mock.action_detail` for offline testing); the resolved 任务id then drives `cop-task-detail`, the purpose tree, and the 1:N binding (other businesses pass the id through unchanged). **xdfx additionally partitions its chat records by 行动id (action_id), NOT by task_id**: `resolveTaskDeeplinkTarget` sets `partitionByAction:true` + keeps the raw action_id as `TaskContext.actionId`, so new threads are tagged `metadata.{taskId,actionId}` (taskId kept only to preserve the backend「任务深链对话全局共享」semantics, which keys off `metadata.taskId`) and the conversation list filters by `actionId` (+`agent_id`) — different actions of the same task get separate lists. xdfx's first-question opening text also appends `行动id(action_id)为…` (see `buildOpeningText` / `taskThreadMetadata`). goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. The roundtable target also threads the URL `taskId` into `roundtablePrefill.taskId` (`resolveTaskDeeplinkTarget(goPath, detail, taskId)`), which turns on two taskId-scoped behaviors: (1) **separate, unpartitioned per-task storage** — taskId 会商聊天记录 live in their **own** store/table (`roundtable_task_drafts`), keyed **only by `task_id`** (one taskId = many records, shared across users, **no user 分权** at all; `created_by` is audit-only), kept entirely out of the per-user personal store (`roundtable_drafts`, now strictly per-user) so the two never mix. Backend router `/api/roundtable-task-drafts` (`GET /by-task/{id}` + `/by-task/{id}/latest`, `POST`, `GET/PUT/DELETE /{id}` — all user-agnostic); frontend client `roundtable-planning/api/task-drafts.ts`, and `useDraftPersistence`/`useRoundtableDrafts` route **all** CRUD to it when a `taskId` is present (else the personal `drafts.ts`). The matching **background jobs** are shared by task too: `roundtable_jobs.task_id` marks a task job; reads/dedup/stream/resume/cancel pass `?task_id=` so any user opening the task sees the same running 研讨 (progress/flowchart), and the executor writes the final report back to the task-draft store. Existing rows are moved over by `scripts/migrate_roundtable_task_drafts.py` (migration `20260618_01`). The history dropdown filters to the task and 新建 keeps the binding; (2) **Step-3 auto structured output** — after the `roundtable-summary` agent writes the Markdown report it automatically runs a second round emitting a `flow-json` flowchart (`useStep3Summary` `autoFlow`+`chainLevels`), whose hierarchy follows the business chain's stage goals (任务 → 目的 → 行为体 → …; coordinatorPrompt-specified hierarchy wins) and whose nodes never carry 阶段编号/阶段名 (the prior bug). **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. **All three single-agent businesses share `TaskFxWorkspace`** (`task-components/TaskFxWorkspace.tsx`): left = a「当前任务」card (`readCopTaskDetail()` 任务名称 + 简介, desensitized, 留存 above 新建对话) + per-task 1:N conversation list (`useTaskThreads(taskId, agentId, actionId?)` — filtered by **both** `metadata.taskId` AND `metadata.agent_id` so the three businesses' conversations staLine truncated
|
- **Login URL params** (`LoginPage.tsx`, frontend-only — the backend never sees these): besides the auth params (`ticket`/`userId`/`env`/`theme`/`yUserId`/`token`/`access_token`/`authToken`/`password`), the page supports a **task deep-link** via `?taskId=&goPath=`. After login it calls the consumer API `GET {VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail?taskId=` (header `Authorization: Bearer admin`, auto-injected by `utils/request.ts`), stashes the full `data` (`id/overview/taskDirection/taskName/taskContent/taskType`; opening text maps `taskType` 1/2/3 to 打击/塑势/防御) into `sessionStorage["login.copTaskDetail"]`, then routes by `goPath`: base codes `3qfx`/`rwfx`/`xdfx` → that business's configured **single agent** Q&A inside a **任务工作区** (resolved via `/api/business-mapping`; `resolveTaskDeeplinkTarget` calls `persistTaskContext({taskId, agentId, openingText})` and navigates to the `…/chats` **index**, which opens the latest task conversation or 新建 — a 1:N task↔对话 workspace, NOT `pendingAgentMessage`); the `-A` suffix (`3qfx-A`/…) → **multi-agent roundtable** with `roundtablePrefill.businessCode` so the page auto-selects the configured 业务链条. **xdfx's deep-link `?taskId=` is actually an 行动id, not a 任务id** — `resolveDeeplinkTaskId(goPath, rawId)` (called in `LoginPage` before everything) detects `xdfx`/`xdfx-A` and resolves it via `GET {action_detail_url}/{actionId}` → `data.taskId` (`fetchTaskIdFromAction`; `action_test`+`mock.action_detail` for offline testing); the resolved 任务id then drives `cop-task-detail`, the purpose tree, and the 1:N binding (other businesses pass the id through unchanged). **xdfx additionally partitions its chat records by 行动id (action_id), NOT by task_id**: `resolveTaskDeeplinkTarget` sets `partitionByAction:true` + keeps the raw action_id as `TaskContext.actionId`, so new threads are tagged `metadata.{taskId,actionId}` (taskId kept only to preserve the backend「任务深链对话全局共享」semantics, which keys off `metadata.taskId`) and the conversation list filters by `actionId` (+`agent_id`) — different actions of the same task get separate lists. xdfx's first-question opening text also appends `行动id(action_id)为…` (see `buildOpeningText` / `taskThreadMetadata`). goPath→businessCode: `3qfx`→`3Q`, `rwfx`→`6BF`, `xdfx`→`7BF`. The roundtable target also threads the URL `taskId` into `roundtablePrefill.taskId` (`resolveTaskDeeplinkTarget(goPath, detail, taskId)`), which turns on two taskId-scoped behaviors: (1) **separate, unpartitioned per-task storage** — taskId 会商聊天记录 live in their **own** store/table (`roundtable_task_drafts`), keyed **only by `task_id`** (one taskId = many records, shared across users, **no user 分权** at all; `created_by` is audit-only), kept entirely out of the per-user personal store (`roundtable_drafts`, now strictly per-user) so the two never mix. Backend router `/api/roundtable-task-drafts` (`GET /by-task/{id}` + `/by-task/{id}/latest`, `POST`, `GET/PUT/DELETE /{id}` — all user-agnostic); frontend client `roundtable-planning/api/task-drafts.ts`, and `useDraftPersistence`/`useRoundtableDrafts` route **all** CRUD to it when a `taskId` is present (else the personal `drafts.ts`). The matching **background jobs** are shared by task too: `roundtable_jobs.task_id` marks a task job; reads/dedup/stream/resume/cancel pass `?task_id=` so any user opening the task sees the same running 研讨 (progress/flowchart), and the executor writes the final report back to the task-draft store. Existing rows are moved over by `scripts/migrate_roundtable_task_drafts.py` (migration `20260618_01`). The history dropdown filters to the task and 新建 keeps the binding; (2) **Step-3 auto structured output** — after the `roundtable-summary` agent writes the Markdown report it automatically runs a second round emitting a `flow-json` flowchart (`useStep3Summary` `autoFlow`+`chainLevels`), whose hierarchy follows the business chain's stage goals (任务 → 目的 → 行为体 → …; coordinatorPrompt-specified hierarchy wins) and whose nodes never carry 阶段编号/阶段名 (the prior bug). **Both targets render embedded under the 任务管理 layout** — nested routes under `task-management/<business-path>/{roundtable,agent/:agent_id/chats}` in `StrategyRoutes.tsx` (`<business-path>` = `plan-task-sentiment` / `plan-task/plan-task-fx` / `plan-task/plan-task-action`, matching the COH中任务 menu paths in `sidebar-menu.ts`) so the global sidebar keeps 任务管理 → COH中任务 → the matching business highlighted. **All three single-agent businesses share `TaskFxWorkspace`** (`task-components/TaskFxWorkspace.tsx`): left = a「当前任务」card (`readCopTaskDetail()` 任务名称 + 简介, desensitized, 留存 above 新建对话) + per-task 1:N conversation list (`useTaskThreads(taskId, agentId, actionId?)` — filtered by **both** `metadata.taskILine truncated
|
||||||
- **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(2.5) **`?hideChrome=1`** — **仅**去全局 chrome(Header 导航栏 + PageSidebar 侧边栏),**不**强制主题、**不**隔离鉴权(区别于 `embed`:只想要一个干净全屏页面,如「大屏绘制」`/page/strategy/dashboard-agent?taskId=…&hideChrome=1`)。新增 `EmbedSession.hideChrome` 字段 + `readHideChromeParam()` + `isChromeHidden()`(取 `embed || hideChrome` 之并),与 `hideJump` 完全对称;`PageRoutes.tsx` 的 `PageLayout` 把 `chromeHidden`(`isChromeHidden() || readHideChromeParam(location.search)==="on"`)并入 `pageSidebarAllowed`,且其**优先级高于** dashboard-agent 路由原本的强制全局 chrome(`forceChromeForDashboardAgent`)。`hideChrome=0` 可显式关闭。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。第三个开关 `?isolate=1`(**独立登录会话**)把同一套**登录用户隔离**单独提供给**普通(带 chrome)标签页**——只切换鉴权存储、不去 chrome / 不强制主题 / 不动跳转栏:`authStorage()` 的条件从「仅嵌入」放宽为 `isEmbedActive() || isIsolatedSession()`,`AuthSyncWatcher` 的跨标签监听对嵌入态**或**独立态都即时忽略(handler 内实时判,运行时开关也即刻生效)。除 URL 参数外,**设置 → 外观 →「登录会话」** 有一个 Switch「独立登录会话(本标签页)」运行时切换(`setIsolatedSession`,`appearance-settings-page.tsx`):**开启时先 `migrateAuthToSession()`**(`scoped-storage.ts`,把 localStorage 的受保护键 `deerflow.auth`/`userInfo`/`userId`/`tools_token` + `login.*` 前缀快照搬进 sessionStorage)再翻标志,故无感不登出;此后本标签页登录态独立——别处登录/换号影响不到它,它换号也影响不到别人,但关掉该标签即结束(需重登)。开启给 toast 提示。
|
- **iframe 嵌入模式 (外部系统用 iframe 套用深链问答/会商)** — 三个**按标签页**开关,全部由深链 URL 参数开启、存进同一份 `sessionStorage` 会话(`embed.session`,键名常量在 `core/embed/embed-session.ts`),跨登录跳转/刷新/页内导航存活,**绝不跨标签污染**同浏览器另开的正常系统页。核心隔离手法:用 `sessionStorage`(按标签页/浏览上下文隔离,iframe 即便同源也有独立一份)而非 `localStorage`(跨标签共享)。开关:(1) **`?embed=1`(可带 `&theme=`)** — 去全局 chrome(`PageLayout` 的 `pageSidebarAllowed && !isEmbedActive()` → 隐藏 Header + PageSidebar)+ 按外部主题色**强制**明/暗:走 next-themes 的 `forcedTheme`(`App.tsx` `AppProviders` 调 `resolveForcedEmbedTheme`,**不写** localStorage `strategy-theme`),离散映射 `dark-blue`/`dark`→深、其余→浅;嵌入侧**绝不**调 `setTheme`/`persistSidebarEnabled`(那俩落 localStorage 跨标签污染,`LoginPage` 据 `readEmbedParam` 跳过)。(2) **`?hideJump=1`** — 隐藏深链底部「快捷跳转」栏 `TaskJumpBar` 的两部分(底部「下一步」等按钮 + 右侧垂直居中悬浮菜单),单智能体问答 + 会商共用该栏,`isJumpBarHidden()` 为真时整条 `return null`。(2.5) **`?hideChrome=1`** — **仅**去全局 chrome(Header 导航栏 + PageSidebar 侧边栏),**不**强制主题、**不**隔离鉴权(区别于 `embed`:只想要一个干净全屏页面,如「大屏绘制」`/page/strategy/dashboard-agent?taskId=…&hideChrome=1`)。新增 `EmbedSession.hideChrome` 字段 + `readHideChromeParam()` + `isChromeHidden()`(取 `embed || hideChrome` 之并),与 `hideJump` 完全对称;`PageRoutes.tsx` 的 `PageLayout` 把 `chromeHidden`(`isChromeHidden() || readHideChromeParam(location.search)==="on"`)并入 `pageSidebarAllowed`,且其**优先级高于** dashboard-agent 路由原本的强制全局 chrome(`forceChromeForDashboardAgent`)。`hideChrome=0` 可显式关闭。(3) **登录用户隔离** — 嵌入态下鉴权/身份键(`deerflow.auth` token、`userInfo`、`login.*`、`tools_token`、maxkey/userDetail token)全部经 `core/auth/scoped-storage.ts` 的 `authStorage()`(嵌入→sessionStorage / 正常→localStorage)读写,使 iframe 里登录的用户与正常登录用户**完全隔离**、互不覆盖;所有 token 读取都过 `getStoredAuth()`/`getAuthorizationHeaderValue()`(API 客户端 `core/api/*` 全走这俩),改中心函数即让全体调用方自动隔离;跨标签账号变更监听 `AuthSyncWatcher`(`core/auth/sync.tsx`)在嵌入态禁用。嵌入会话在 `main.tsx` 渲染前 `syncEmbedSessionFromCurrentUrl()` 同步启用(早于任何鉴权写入,避免首帧 effect 顺序漏写 localStorage);`AppProviders` 的 effect 再按 SPA 导航同步。`embed=0`/`hideJump=0` 可显式关闭。正常(非嵌入)标签页所有 `isXxx()` 恒 false,行为**零变化**。第三个开关 `?isolate=1`(**独立登录会话**)把同一套**登录用户隔离**单独提供给**普通(带 chrome)标签页**——只切换鉴权存储、不去 chrome / 不强制主题 / 不动跳转栏:`authStorage()` 的条件从「仅嵌入」放宽为 `isEmbedActive() || isIsolatedSession()`,`AuthSyncWatcher` 的跨标签监听对嵌入态**或**独立态都即时忽略(handler 内实时判,运行时开关也即刻生效)。除 URL 参数外,**设置 → 外观 →「登录会话」** 有一个 Switch「独立登录会话(本标签页)」运行时切换(`setIsolatedSession`,`appearance-settings-page.tsx`):**开启时先 `migrateAuthToSession()`**(`scoped-storage.ts`,把 localStorage 的受保护键 `deerflow.auth`/`userInfo`/`userId`/`tools_token` + `login.*` 前缀快照搬进 sessionStorage)再翻标志,故无感不登出;此后本标签页登录态独立——别处登录/换号影响不到它,它换号也影响不到别人,但关掉该标签即结束(需重登)。开启给 toast 提示。
|
||||||
- **操作日志(Y-Log)上报** — 用户的关键操作(登录登出/查询/查看/增删改/启停/导入导出/问答等)成功后,**前端直连**外部接口 `POST {write_url}`(默认 `https://ch1.b.uat.4.cn/api/y-log/write`)记一条审计日志。核心模块 `src/core/log/`:`y-log.ts`(`writeYLog(params)` + `OptType` 枚举 0/1/3..12;**异步即发即忘、永不 await、永不抛错、失败静默**,自动把完整 url 转相对路径去 ip/host、对象入参/返回自动 `JSON.stringify` + 50k 裁剪、`optResult` 恒 0 只报成功),`y-log-config.ts`(从公开只读 `GET /api/public/config/y-log` 拉 `{enabled, writeUrl}`,模块级缓存 + 去重 + 默认兜底;`App.tsx` `AppProviders` 启动预热 `fetchYLogConfig()`),`y-log-token.ts`(token1 = token 登录的 `?authToken=`,经 [[scoped-storage]] 的 `authStorage*` 存取,嵌入态自动隔离)。**双门控**:仅当①存在 token1(即用 token 登录,`LoginPage` 成功后 `persistYLogToken(authToken)`,登出 `account-settings-page.tsx` 先报后清 token1)且②配置 `enabled && writeUrl` 才上报;否则一律不发。`optDetail` 统一「CM助手-全量-…」(**禁内部框架名**)。埋点**广覆盖**各 API client 的成功路径——原则是「一个用户操作(查看/查询/新增/编辑/删除/启停/导入导出)= 一条日志」,每个 API client 的**单条详情 GET(查看→view 4)/ 列表查询 GET(search 3)/ 新增 POST(create 9)/ 改 PUT·PATCH(edit 5)/ 删 DELETE(delete 6)/ 启停(enabled 11 / disabled 10)/ 导入导出(import 7 / export 8)**都各落一条,仅跳过高频 typeahead/状态轮询/纯 bootstrap config 读。覆盖文件:`strategy-components/api/{sensitive-words,menu-overrides,task-buttons,skill-addresses,light-apps,business-mapping}.ts`、`roundtable-planning/api/{drafts,task-drafts,roundtable-jobs,recommend,chains,multi-agent,dashboard-sessions}.ts`、`core/{agents,scheduled-tasks,knowledge,positions,tags,studio,system-settings,memory,mcp,models,custom-prompts,user-preferences,notifications,recommended-questions,user-qa,curator,admin,thread-shares,roundtable-draft-shares,tool-metrics,llm-metrics,note,artifacts}/api.ts`、`core/api/markdown-docx-export.ts`。**问答(Q&A)改为「一次大模型调用 = 一条日志」**:在共享的 `core/threads/hooks.ts` `useThreadStream` 的 `onLangChainEvent` 里监听 `on_chat_model_end`,每次模型调用结束就上报一条(optType 12,`reqParam` 取本次 input 的最后一条 user 文本 + 模型名,`returnParam` 取本次输出文本)——一个问答轮次里 lead agent / 子代理的**每次** LLM 调用都各记一条,覆盖所有走 `useThreadStream` 的页面(`ChatPage`/`AgentChatPage`/创建智能体/iframe/会商等);`ChatPage`/`AgentChatPage` 的 `onFinish` 仍额外保留一条轮次汇总。后端仅新增公开只读配置:`deerflow/config/y_log_config.py`(`YLogConfig{enabled,write_url}`)挂到 `AppConfig.y_log`,`app/gateway/routers/public_config.py` 加 `GET /api/public/config/y-log`,地址写在 `config.yaml` 的 `y_log` 段(mtime 热重载,前端无需重建);**不做后端代理**。Tests:`tests/test_y_log_config.py`。
|
- **操作日志(Y-Log)上报** — 用户的关键操作(登录登出/查询/查看/增删改/启停/导入导出/问答等)成功后,**前端直连**外部接口 `POST {write_url}`(默认 `https://ch1.b.uat.4.cn/api/y-log/write`)记一条审计日志。核心模块 `src/core/log/`:`y-log.ts`(`writeYLog(params)` + `OptType` 枚举 0/1/3..12;**异步即发即忘、永不 await、永不抛错、失败静默**,自动把完整 url 转相对路径去 ip/host、对象入参/返回自动 `JSON.stringify` + 50k 裁剪、`optResult` 恒 0 只报成功),`y-log-config.ts`(从公开只读 `GET /api/public/config/y-log` 拉 `{enabled, writeUrl}`,模块级缓存 + 去重 + 默认兜底;`App.tsx` `AppProviders` 启动预热 `fetchYLogConfig()`),`y-log-token.ts`(token1 = token 登录的 `?authToken=`,经 [[scoped-storage]] 的 `authStorage*` 存取,嵌入态自动隔离)。**双门控**:仅当①存在 token1(即用 token 登录,`LoginPage` 成功后 `persistYLogToken(authToken)`,登出 `account-settings-page.tsx` 先报后清 token1)且②配置 `enabled && writeUrl` 才上报;否则一律不发。`optDetail` 统一「CM助手-全量-…」(**禁内部框架名**)。埋点**广覆盖**各 API client 的成功路径——原则是「一个用户操作(查看/查询/新增/编辑/删除/启停/导入导出)= 一条日志」,每个 API client 的**单条详情 GET(查看→view 4)/ 列表查询 GET(search 3)/ 新增 POST(create 9)/ 改 PUT·PATCH(edit 5)/ 删 DELETE(delete 6)/ 启停(enabled 11 / disabled 10)/ 导入导出(import 7 / export 8)**都各落一条,仅跳过高频 typeahead/状态轮询/纯 bootstrap config 读。覆盖文件:`strategy-components/api/{sensitive-words,menu-overrides,task-buttons,skill-addresses,light-apps,business-mapping}.ts`、`roundtable-planning/api/{drafts,task-drafts,roundtable-jobs,recommend,chains,multi-agent,dashboard-sessions}.ts`、`core/{agents,scheduled-tasks,knowledge,positions,tags,studio,system-settings,memory,mcp,models,custom-prompts,user-preferences,notifications,recommended-questions,user-qa,curator,admin,thread-shares,roundtable-draft-shares,tool-metrics,llm-metrics,note,artifacts}/api.ts`、`core/api/markdown-docx-export.ts`。**问答(Q&A)改为「一次大模型调用 = 一条日志」**:在共享的 `core/threads/hooks.ts` `useThreadStream` 的 `onLangChainEvent` 里监听 `on_chat_model_end`,每次模型调用结束就上报一条(optType 12,`reqParam` 取本次 input 的最后一条 user 文本 + 模型名,`returnParam` 取本次输出文本)——一个问答轮次里 lead agent / 子代理的**每次** LLM 调用都各记一条,覆盖所有走 `useThreadStream` 的页面(`ChatPage`/`AgentChatPage`/创建智能体/iframe/会商等);`ChatPage`/`AgentChatPage` 的 `onFinish` 仍额外保留一条轮次汇总。后端仅新增公开只读配置:`deerflow/config/y_log_config.py`(`YLogConfig{enabled,write_url}`)挂到 `AppConfig.y_log`,`app/gateway/routers/public_config.py` 加 `GET /api/public/config/y-log`,地址写在 `config.yaml` 的 `y_log` 段(mtime 热重载,前端无需重建);**不做后端代理**。Tests:`tests/test_y_log_config.py`。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,739 @@
|
|||||||
|
# DeerFlow 接口卡顿独立诊断脚本使用说明
|
||||||
|
|
||||||
|
配套脚本:[`diagnose_deerflow_latency.py`](./diagnose_deerflow_latency.py)
|
||||||
|
|
||||||
|
## 0. 最简单的用法(推荐)
|
||||||
|
|
||||||
|
把脚本复制到 DeerFlow 所在服务器,然后直接运行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 diagnose_deerflow_latency.py
|
||||||
|
```
|
||||||
|
|
||||||
|
脚本会显示中文向导。你只需要:
|
||||||
|
|
||||||
|
1. 粘贴卡顿接口 URL;
|
||||||
|
2. 选择普通 GET、登录 POST 或 Agent SSE;
|
||||||
|
3. 登录/Agent POST 时再提供请求 JSON 文件;
|
||||||
|
4. 根据提示选择是否需要 Bearer Token 或 Cookie。
|
||||||
|
5. 确认脚本是否运行在实际部署服务器上,避免把个人电脑的 CPU/内存误认为服务器指标。
|
||||||
|
|
||||||
|
脚本会显示 `[1/5]` 到 `[5/5]` 的进度,最后直接输出“**一键判断**”,告诉你当前证据更偏向:
|
||||||
|
|
||||||
|
- Nginx/入口代理;
|
||||||
|
- MySQL/数据库;
|
||||||
|
- DeerFlow 并发或热点路径;
|
||||||
|
- CPU、内存、磁盘等服务器资源;
|
||||||
|
- DNS、TCP、TLS 等网络问题。
|
||||||
|
|
||||||
|
如果只是普通 GET,也可以一行执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 diagnose_deerflow_latency.py 'https://你的域名/卡顿接口'
|
||||||
|
```
|
||||||
|
|
||||||
|
一行模式只请求目标接口一次,不自动压测、不跟随重定向、不复制请求到本机直连地址。需要登录态时,可使用专门的诊断环境变量:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export DEERFLOW_DIAG_TOKEN='你的测试 Token'
|
||||||
|
export DEERFLOW_DIAG_ON_SERVER=1
|
||||||
|
python3 diagnose_deerflow_latency.py 'https://你的域名/api/skills?sort=time_desc'
|
||||||
|
unset DEERFLOW_DIAG_TOKEN DEERFLOW_DIAG_ON_SERVER
|
||||||
|
```
|
||||||
|
|
||||||
|
Token 值不会显示或写入报告。不要使用生产管理员的长期 Token。
|
||||||
|
|
||||||
|
## 1. 工具定位
|
||||||
|
|
||||||
|
这是一个可以单独复制、单独运行的诊断脚本,不是 DeerFlow 后端补丁。
|
||||||
|
|
||||||
|
- 不需要重新发布或替换后端。
|
||||||
|
- 不需要把脚本放进 DeerFlow 源码目录。
|
||||||
|
- 不需要安装 Python 第三方包。
|
||||||
|
- 不会修改 Nginx、MySQL、Docker 或 DeerFlow 配置。
|
||||||
|
- 默认只进行 HTTP 测量和只读状态采集。
|
||||||
|
- 支持 Python 3.9 及以上版本。
|
||||||
|
|
||||||
|
建议把脚本复制到发生卡顿的 Linux 服务器,在卡顿正在发生时运行。只有从服务器本机运行,才能同时采集 CPU、内存、磁盘、连接队列、Nginx、Docker 等现场信息。
|
||||||
|
|
||||||
|
> 登录接口和 Agent 接口通常是 POST,请求本身可能创建会话或任务。脚本默认只发送一次,不会自动压测。请使用测试账号和测试数据。
|
||||||
|
|
||||||
|
## 2. 能排查什么
|
||||||
|
|
||||||
|
脚本从以下层次收集证据:
|
||||||
|
|
||||||
|
1. **网络和 HTTPS**
|
||||||
|
- DNS 解析时间
|
||||||
|
- TCP 建连时间
|
||||||
|
- HTTP 代理 CONNECT 时间
|
||||||
|
- TLS 握手时间
|
||||||
|
- 请求上传时间
|
||||||
|
- 请求发完到首响应的等待时间
|
||||||
|
- 响应体读取时间
|
||||||
|
|
||||||
|
2. **Nginx 和系统连接容量**
|
||||||
|
- 公网入口与 `127.0.0.1:8001` 直连的耗时差异
|
||||||
|
- 监听队列与 TCP 状态
|
||||||
|
- Nginx worker 数量、`worker_connections` 和文件句柄限制
|
||||||
|
- 可选的 Nginx `stub_status`
|
||||||
|
- 502、503、504、upstream timeout、too many open files 等日志模式
|
||||||
|
|
||||||
|
3. **MySQL**
|
||||||
|
- TCP 建连
|
||||||
|
- 多次新连接执行 `SELECT 1` 的耗时
|
||||||
|
- `Threads_connected`、`max_connections` 等状态
|
||||||
|
- 活动时间较长的会话数量
|
||||||
|
- 数据锁、元数据锁等待
|
||||||
|
- performance schema 聚合信息
|
||||||
|
|
||||||
|
MySQL 检查仅执行预置的只读查询,不保存 SQL 正文。
|
||||||
|
|
||||||
|
4. **DeerFlow 请求排队和热点路径**
|
||||||
|
- `/api/health`
|
||||||
|
- `/api/v1/auth/options`
|
||||||
|
- 登录态下的 `auth/me`、Agents、Skills 接口
|
||||||
|
- 慢接口执行期间健康接口是否同时变慢
|
||||||
|
- 可选的管理员活动运行数和模型并发限制
|
||||||
|
- Agent SSE 首包时间
|
||||||
|
|
||||||
|
5. **服务器和容器容量**
|
||||||
|
- CPU、load、iowait、steal
|
||||||
|
- 内存、Swap、Linux PSI
|
||||||
|
- 磁盘忙碌度和剩余空间
|
||||||
|
- 进程 CPU、RSS、线程数、FD 使用率
|
||||||
|
- cgroup/Docker CPU 和内存限制
|
||||||
|
- Docker OOM、重启次数
|
||||||
|
|
||||||
|
## 3. 准备脚本
|
||||||
|
|
||||||
|
把单个 Python 文件复制到目标服务器:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
scp diagnose_deerflow_latency.py user@server:/tmp/
|
||||||
|
```
|
||||||
|
|
||||||
|
登录服务器后检查 Python:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 --version
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py --help
|
||||||
|
```
|
||||||
|
|
||||||
|
脚本可以在任意目录执行。只有使用 `--config` 时才需要知道 DeerFlow 的 `config.yaml` 路径。
|
||||||
|
|
||||||
|
## 4. 第一次运行:只测一个接口
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/health' \
|
||||||
|
--count 5 \
|
||||||
|
--server-checks \
|
||||||
|
--output /tmp/deerflow-latency.json
|
||||||
|
```
|
||||||
|
|
||||||
|
终端会显示中文摘要,完整脱敏结果写入 `/tmp/deerflow-latency.json`。
|
||||||
|
|
||||||
|
Linux 上默认会自动启用服务器检查;显式写上 `--server-checks` 更清楚。普通用户权限不足时,部分 Nginx、Docker 或进程信息会显示为“未完成检查”,但不会导致整个诊断失败。
|
||||||
|
|
||||||
|
默认还会对目标 origin 的 `/health`、`/api/health` 和 `/api/langgraph/health` 各进行一次安全 GET 探测。如果不希望产生这些额外请求,增加 `--no-health-baselines`。
|
||||||
|
|
||||||
|
## 5. 推荐排查顺序
|
||||||
|
|
||||||
|
### 第一步:测公网入口
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/skills?sort=time_desc' \
|
||||||
|
--count 5 \
|
||||||
|
--server-checks \
|
||||||
|
--output /tmp/01-public.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### 第二步:同时对比 Gateway 本机直连
|
||||||
|
|
||||||
|
确保两条 URL 的路径、查询参数和业务行为一致:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/skills?sort=time_desc' \
|
||||||
|
--compare-url 'http://127.0.0.1:8001/api/skills?sort=time_desc' \
|
||||||
|
--count 5 \
|
||||||
|
--server-checks \
|
||||||
|
--output /tmp/02-public-vs-direct.json
|
||||||
|
```
|
||||||
|
|
||||||
|
如果请求带 Token、Cookie、任意自定义 header、`--query-env`、请求体,或使用 POST,向不同 origin 发送这些内容前必须明确增加:
|
||||||
|
|
||||||
|
```text
|
||||||
|
--allow-cross-origin-compare
|
||||||
|
```
|
||||||
|
|
||||||
|
该参数意味着你已经确认比较地址可信。POST 登录和 Agent 请求不建议使用 `--compare-url`,应分两次各运行一次,避免重复创建状态。
|
||||||
|
|
||||||
|
### 第三步:增加 DeerFlow 基线接口
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/skills?sort=time_desc' \
|
||||||
|
--count 5 \
|
||||||
|
--deerflow-suite \
|
||||||
|
--server-checks \
|
||||||
|
--output /tmp/03-deerflow-suite.json
|
||||||
|
```
|
||||||
|
|
||||||
|
未提供登录凭据时,只检查公开的 health 和 auth/options。提供 Bearer Token 或 Cookie 后,才会增加 `auth/me`、Agents、Skills 等登录态基线。
|
||||||
|
|
||||||
|
### 第四步:安全 GET 接口使用干扰探针
|
||||||
|
|
||||||
|
下面的命令会在慢接口执行期间,每 0.25 秒探测一次 `/api/health`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/skills?sort=time_desc' \
|
||||||
|
--count 5 \
|
||||||
|
--deerflow-suite \
|
||||||
|
--interference \
|
||||||
|
--server-checks \
|
||||||
|
--output /tmp/04-interference.json
|
||||||
|
```
|
||||||
|
|
||||||
|
如果慢接口执行时 health 也明显变慢,更偏向 Gateway worker、事件循环、CPU 或 IO 被阻塞。如果 health 始终很快,更偏向该请求自身的数据库、模型或下游服务等待。
|
||||||
|
|
||||||
|
`--interference` 会额外请求一次目标接口,仅建议用于 GET/HEAD/OPTIONS 等无副作用接口。
|
||||||
|
|
||||||
|
### 第五步:检查 MySQL
|
||||||
|
|
||||||
|
先做不带账号的 TCP 连通性检查:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/health' \
|
||||||
|
--server-checks \
|
||||||
|
--mysql-host '10.0.0.20' \
|
||||||
|
--mysql-port 3306 \
|
||||||
|
--output /tmp/05-mysql-tcp.json
|
||||||
|
```
|
||||||
|
|
||||||
|
若需查询连接、锁和 performance schema,请参见“经过认证的 MySQL 只读检查”。
|
||||||
|
|
||||||
|
### 第六步:卡顿时再运行一次
|
||||||
|
|
||||||
|
间歇性问题恢复后再执行,只能反映恢复后的状态。最好在下面任一现象出现时立即运行:
|
||||||
|
|
||||||
|
- 登录等待很久;
|
||||||
|
- Skills/Agents 页面一直转圈;
|
||||||
|
- Agent 长时间没有返回 SSE 响应实体字节;
|
||||||
|
- 出现 429、502、503 或 504;
|
||||||
|
- 所有页面同时变慢。
|
||||||
|
|
||||||
|
## 6. 鉴权接口
|
||||||
|
|
||||||
|
### 6.1 Bearer Token
|
||||||
|
|
||||||
|
不要把 Token 直接写进命令行。使用环境变量:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
read -rsp 'Bearer Token: ' DF_TOKEN
|
||||||
|
export DF_TOKEN
|
||||||
|
echo
|
||||||
|
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/skills?sort=time_desc' \
|
||||||
|
--bearer-env DF_TOKEN \
|
||||||
|
--count 5 \
|
||||||
|
--deerflow-suite \
|
||||||
|
--server-checks \
|
||||||
|
--output /tmp/skills-auth.json
|
||||||
|
|
||||||
|
unset DF_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
Token 值不会写入报告。
|
||||||
|
|
||||||
|
### 6.2 Cookie
|
||||||
|
|
||||||
|
```bash
|
||||||
|
read -rsp 'Cookie header value: ' DF_COOKIE
|
||||||
|
export DF_COOKIE
|
||||||
|
echo
|
||||||
|
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/protected/path' \
|
||||||
|
--cookie-env DF_COOKIE \
|
||||||
|
--count 5 \
|
||||||
|
--output /tmp/cookie-request.json
|
||||||
|
|
||||||
|
unset DF_COOKIE
|
||||||
|
```
|
||||||
|
|
||||||
|
环境变量值应为 Cookie header 的值,例如 `session=...; other=...`,不要包含 `Cookie:` 前缀,也不要把真实值发给其他人。
|
||||||
|
|
||||||
|
### 6.3 自定义请求头
|
||||||
|
|
||||||
|
普通非敏感头:
|
||||||
|
|
||||||
|
```text
|
||||||
|
--header 'Accept: application/json'
|
||||||
|
```
|
||||||
|
|
||||||
|
敏感头使用环境变量:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
read -rsp 'API key: ' DF_API_KEY
|
||||||
|
export DF_API_KEY
|
||||||
|
echo
|
||||||
|
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/path' \
|
||||||
|
--header-env 'X-API-Key=DF_API_KEY'
|
||||||
|
|
||||||
|
unset DF_API_KEY
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.4 URL 查询参数中的敏感值
|
||||||
|
|
||||||
|
不要把 ticket、token、password 等直接写进 URL。使用:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
read -rsp 'Ticket: ' DF_TICKET
|
||||||
|
export DF_TICKET
|
||||||
|
echo
|
||||||
|
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/login/callback' \
|
||||||
|
--query-env 'ticket=DF_TICKET' \
|
||||||
|
--count 1 \
|
||||||
|
--output /tmp/ticket-request.json
|
||||||
|
|
||||||
|
unset DF_TICKET
|
||||||
|
```
|
||||||
|
|
||||||
|
报告中的 URL 查询参数值会统一脱敏。
|
||||||
|
|
||||||
|
## 7. 登录 POST 接口
|
||||||
|
|
||||||
|
登录请求可能创建登录会话,所以默认只发送一次。先准备请求体文件,并限制权限:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
umask 077
|
||||||
|
vi /tmp/login-request.json
|
||||||
|
chmod 600 /tmp/login-request.json
|
||||||
|
```
|
||||||
|
|
||||||
|
例如请求体可能是:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"username": "diagnosis-user",
|
||||||
|
"password": "请填写测试账号密码"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
实际字段应以你的登录接口为准。运行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/v1/auth/login' \
|
||||||
|
--method POST \
|
||||||
|
--header 'Content-Type: application/json' \
|
||||||
|
--data-file /tmp/login-request.json \
|
||||||
|
--count 1 \
|
||||||
|
--read-mode full \
|
||||||
|
--first-byte-timeout 60 \
|
||||||
|
--total-timeout 90 \
|
||||||
|
--server-checks \
|
||||||
|
--output /tmp/login-diagnosis.json
|
||||||
|
```
|
||||||
|
|
||||||
|
完成后删除临时请求体:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rm -f /tmp/login-request.json
|
||||||
|
```
|
||||||
|
|
||||||
|
注意:
|
||||||
|
|
||||||
|
- 请求体内容不会写入 JSON 报告。
|
||||||
|
- 不要为登录 POST 增加 `--interference`。
|
||||||
|
- 不要同时使用 `--compare-url`,公网和直连应分别执行一次。
|
||||||
|
- 不要增加 `--count` 或 `--concurrency`,除非确认可以重复登录并明确加上 `--allow-unsafe-replay`。
|
||||||
|
|
||||||
|
如果 HTTP 状态很快返回 401/403,这仍然说明链路和服务响应很快;它不代表登录业务验证成功。请结合 `status_counts` 判断。
|
||||||
|
|
||||||
|
## 8. Agent SSE 首包诊断
|
||||||
|
|
||||||
|
Agent 请求通常是 POST,并返回 `text/event-stream`。使用 `first-byte` 模式,只等待首个响应实体字节,不等待整个 Agent 任务结束:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
read -rsp 'Bearer Token: ' DF_TOKEN
|
||||||
|
export DF_TOKEN
|
||||||
|
echo
|
||||||
|
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/实际Agent流式接口' \
|
||||||
|
--method POST \
|
||||||
|
--header 'Content-Type: application/json' \
|
||||||
|
--header 'Accept: text/event-stream' \
|
||||||
|
--bearer-env DF_TOKEN \
|
||||||
|
--data-file /tmp/agent-request.json \
|
||||||
|
--count 1 \
|
||||||
|
--read-mode first-byte \
|
||||||
|
--first-byte-timeout 180 \
|
||||||
|
--total-timeout 240 \
|
||||||
|
--server-checks \
|
||||||
|
--output /tmp/agent-first-byte.json
|
||||||
|
|
||||||
|
unset DF_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
请使用测试会话。客户端在收到首个响应实体字节后会关闭连接,但服务端任务是否继续运行取决于实际接口实现。
|
||||||
|
|
||||||
|
`first-byte` 不解析 SSE 协议边界,因此这个字节不等于一个完整 SSE 事件,也不一定代表模型已经开始生成。它可能来自 SSE 注释、心跳、代理填充,甚至 JSON/HTML 错误正文;必须同时检查 HTTP 状态码和响应 `Content-Type`。
|
||||||
|
|
||||||
|
重点看:
|
||||||
|
|
||||||
|
- `response_wait` 很高:服务端迟迟没有返回响应头,可能在排队、鉴权、数据库、worker 或上游连接阶段等待;
|
||||||
|
- 响应头很快,但首个响应实体字节很慢:可能在 Agent、模型并发或模型供应商阶段等待;
|
||||||
|
- 返回 429:优先检查 DeerFlow 模型并发限制或上游配额;
|
||||||
|
- 返回 502/503/504:结合 Nginx error log 和本机直连结果。
|
||||||
|
|
||||||
|
首个响应实体字节的精确耗时位于 JSON 单样本的 `hops[].timings_ms.first_body_after_upload`;`response_wait` 表示请求上传完成到收到首个响应字节,通常对应响应头开始返回。
|
||||||
|
|
||||||
|
## 9. Skills 接口专项诊断
|
||||||
|
|
||||||
|
```bash
|
||||||
|
read -rsp 'Bearer Token: ' DF_TOKEN
|
||||||
|
export DF_TOKEN
|
||||||
|
echo
|
||||||
|
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/skills?sort=time_desc' \
|
||||||
|
--compare-url 'http://127.0.0.1:8001/api/skills?sort=time_desc' \
|
||||||
|
--allow-cross-origin-compare \
|
||||||
|
--bearer-env DF_TOKEN \
|
||||||
|
--count 5 \
|
||||||
|
--deerflow-suite \
|
||||||
|
--interference \
|
||||||
|
--server-checks \
|
||||||
|
--config '/实际路径/config.yaml' \
|
||||||
|
--output /tmp/skills-diagnosis.json
|
||||||
|
|
||||||
|
unset DF_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
该组合可以同时判断:
|
||||||
|
|
||||||
|
- 公网/Nginx 是否比 Gateway 直连慢;
|
||||||
|
- Skills 是否比 health、auth 和 Agents 更慢;
|
||||||
|
- Skills 执行期间 health 是否也被拖慢;
|
||||||
|
- 技能目录文件量和仅元数据遍历是否异常;
|
||||||
|
- CPU、iowait、磁盘是否同时出现压力。
|
||||||
|
|
||||||
|
## 10. Nginx 连接数专项诊断
|
||||||
|
|
||||||
|
脚本在 Linux 上会尝试执行只读的 `nginx -T`、`ss` 和 `/proc` 检查。如果已经配置仅本机可访问的 `stub_status`,可增加:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/health' \
|
||||||
|
--server-checks \
|
||||||
|
--nginx-status-url 'http://127.0.0.1/nginx_status' \
|
||||||
|
--output /tmp/nginx-diagnosis.json
|
||||||
|
```
|
||||||
|
|
||||||
|
主要证据:
|
||||||
|
|
||||||
|
- `active_connections` 接近 `worker_processes × worker_connections`;
|
||||||
|
- `Recv-Q` 接近监听 backlog;
|
||||||
|
- 大量 `SYN-RECV`;
|
||||||
|
- Nginx 日志命中 `worker_connections are not enough`;
|
||||||
|
- 进程 FD 使用率接近上限;
|
||||||
|
- 公网明显慢于 `127.0.0.1:8001` 直连。
|
||||||
|
|
||||||
|
仅看到大量 ESTABLISHED 或 Waiting 连接,不能单独证明连接数耗尽。SSE 和 keepalive 本身就会保持连接,应结合理论槽位、FD、队列和错误日志判断。
|
||||||
|
|
||||||
|
## 11. 经过认证的 MySQL 只读检查
|
||||||
|
|
||||||
|
服务器需要安装 `mysql` 命令行客户端。建议为诊断创建权限受限的只读账号,并使用单独的 client 配置文件:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[client]
|
||||||
|
host=10.0.0.20
|
||||||
|
port=3306
|
||||||
|
user=diagnosis_ro
|
||||||
|
password=替换为诊断账号密码
|
||||||
|
database=deerflow
|
||||||
|
protocol=TCP
|
||||||
|
ssl-mode=REQUIRED
|
||||||
|
```
|
||||||
|
|
||||||
|
保存后限制权限:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chmod 600 /secure/path/diagnosis.cnf
|
||||||
|
```
|
||||||
|
|
||||||
|
运行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/health' \
|
||||||
|
--server-checks \
|
||||||
|
--mysql-defaults-file '/secure/path/diagnosis.cnf' \
|
||||||
|
--mysql-probes 3 \
|
||||||
|
--output /tmp/mysql-diagnosis.json
|
||||||
|
```
|
||||||
|
|
||||||
|
TCP 认证要求配置 `ssl-mode=REQUIRED`、`VERIFY_CA` 或 `VERIFY_IDENTITY`。如果 MySQL 只允许本机 Unix Socket,可使用:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[client]
|
||||||
|
user=diagnosis_ro
|
||||||
|
password=替换为诊断账号密码
|
||||||
|
database=deerflow
|
||||||
|
protocol=SOCKET
|
||||||
|
socket=/var/run/mysqld/mysqld.sock
|
||||||
|
```
|
||||||
|
|
||||||
|
普通业务库只读权限通常足以执行 `SELECT 1`,但查看完整 processlist、全局状态以及 `performance_schema` 的锁和 digest 聚合可能需要额外的只读可见权限。权限不足时脚本会保留已完成的检查,并把其余项目标记为部分不可用;请查看报告的 `coverage.unavailable` 和 `server.mysql` 错误字段。不要为了消除这些提示授予写权限或管理员权限,应由 DBA 按最小权限补充所需的监控可见性。
|
||||||
|
|
||||||
|
也可以把 MySQL URL 放入环境变量:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
read -rsp 'MySQL URL: ' DF_MYSQL_URL
|
||||||
|
export DF_MYSQL_URL
|
||||||
|
echo
|
||||||
|
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/health' \
|
||||||
|
--server-checks \
|
||||||
|
--mysql \
|
||||||
|
--mysql-url-env DF_MYSQL_URL \
|
||||||
|
--output /tmp/mysql-diagnosis.json
|
||||||
|
|
||||||
|
unset DF_MYSQL_URL
|
||||||
|
```
|
||||||
|
|
||||||
|
TCP URL 必须带 `ssl-mode=REQUIRED`、`VERIFY_CA` 或 `VERIFY_IDENTITY`。不要把数据库密码直接写到命令行。
|
||||||
|
用户名、密码、数据库名中的特殊字符需要按 URL 规则进行 percent-encoding。
|
||||||
|
|
||||||
|
## 12. DeerFlow 活动运行数和并发限制
|
||||||
|
|
||||||
|
如果当前账号具有管理员权限,可以读取活动运行数和模型并发配置:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
read -rsp 'Admin JWT: ' DF_ADMIN_TOKEN
|
||||||
|
export DF_ADMIN_TOKEN
|
||||||
|
echo
|
||||||
|
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/health' \
|
||||||
|
--admin-token-env DF_ADMIN_TOKEN \
|
||||||
|
--server-checks \
|
||||||
|
--output /tmp/concurrency-diagnosis.json
|
||||||
|
|
||||||
|
unset DF_ADMIN_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
如果管理员 API 使用另一个可信 origin:
|
||||||
|
|
||||||
|
```text
|
||||||
|
--admin-origin 'https://gateway.example.com' --allow-cross-origin-admin
|
||||||
|
```
|
||||||
|
|
||||||
|
报告只保存活动数量、最长运行时间、模型聚合及并发限制,不保存任务正文。
|
||||||
|
|
||||||
|
## 13. 小规模并发退化测试
|
||||||
|
|
||||||
|
`--concurrency` 是主动并发请求,会增加生产压力。应先使用单并发建立基线:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/skills?sort=time_desc' \
|
||||||
|
--count 10 \
|
||||||
|
--concurrency 1 \
|
||||||
|
--output /tmp/concurrency-1.json
|
||||||
|
```
|
||||||
|
|
||||||
|
在经过确认的低峰窗口,最多先升到 2:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py \
|
||||||
|
--url 'https://example.com/api/skills?sort=time_desc' \
|
||||||
|
--count 10 \
|
||||||
|
--concurrency 2 \
|
||||||
|
--output /tmp/concurrency-2.json
|
||||||
|
```
|
||||||
|
|
||||||
|
不要对登录、创建任务、发送消息等 POST 接口进行并发测试。脚本会拒绝重复或并发执行有副作用的方法,除非显式增加 `--allow-unsafe-replay`。
|
||||||
|
|
||||||
|
## 14. 如何读报告
|
||||||
|
|
||||||
|
### 14.1 HTTP 时间字段
|
||||||
|
|
||||||
|
| 字段 | 含义 | 主要怀疑方向 |
|
||||||
|
|---|---|---|
|
||||||
|
| `dns` | DNS 解析 | DNS 服务器、解析链路 |
|
||||||
|
| `tcp_connect` | TCP 建连 | 网络、防火墙、SYN/backlog、连接压力 |
|
||||||
|
| `proxy_connect` | HTTP 代理建立隧道 | 前向代理 |
|
||||||
|
| `tls_handshake` | TLS 握手 | TLS 终止层、证书链、中间设备、CPU |
|
||||||
|
| `request_upload` | 发送请求头和请求体 | 客户端到服务器上传链路 |
|
||||||
|
| `response_wait` | 请求发完到收到首个响应字节 | Nginx 上游排队、Gateway、DB、文件扫描、下游服务 |
|
||||||
|
| `headers_complete_after_upload` | 请求发完到响应头完整 | 响应头返回阶段 |
|
||||||
|
| `body_read` | 读取响应体 | 大响应、SSE、网络吞吐、代理缓冲 |
|
||||||
|
| `total` | 单次总耗时 | 整体体验 |
|
||||||
|
|
||||||
|
脚本使用新的 HTTP/1.1 连接测量,不等同于浏览器复用 HTTP/2/keepalive 的真实行为。
|
||||||
|
|
||||||
|
### 14.2 四类怀疑的判断矩阵
|
||||||
|
|
||||||
|
| 观察结果 | 更可能的方向 |
|
||||||
|
|---|---|
|
||||||
|
| 公网慢,本机 `127.0.0.1:8001` 快 | Nginx、负载均衡、TLS、入口网络 |
|
||||||
|
| 公网和直连都慢,health 也同时慢 | Gateway worker/事件循环、CPU、内存、磁盘 IO、整机压力 |
|
||||||
|
| health 快,但 auth/me、Agents 等多个 DB 路径慢 | MySQL、连接池、锁、数据库磁盘 |
|
||||||
|
| 只有 Skills 慢,且执行时 health 也慢 | 同步技能目录扫描、慢盘/NFS、单 worker 阻塞 |
|
||||||
|
| Agent 首包慢,但 health 快 | 模型并发、模型供应商、工具调用或该请求下游 |
|
||||||
|
| 429 | DeerFlow 并发限制、上游配额或其他限流 |
|
||||||
|
| 502/503/504 | Nginx 到上游失败、上游超时或服务不可用 |
|
||||||
|
| TCP 慢且监听队列/SYN-RECV 高 | 连接洪峰、backlog 或处理能力不足 |
|
||||||
|
| Nginx active 接近理论槽位,FD 也高 | Nginx 连接/文件句柄容量风险 |
|
||||||
|
| MySQL `Threads_connected` 接近 `max_connections` | DB 连接容量或连接泄漏 |
|
||||||
|
| MySQL 存在锁等待/长会话 | 锁、长事务或慢 SQL |
|
||||||
|
| CPU busy/load/PSI 高 | 服务器算力不足或进程热点 |
|
||||||
|
| iowait/磁盘 util 高 | MySQL、SQLite、技能目录或日志所在存储慢 |
|
||||||
|
| MemAvailable 很低、Swap/OOM 明显 | 内存不足或容器限制过低 |
|
||||||
|
|
||||||
|
单个指标不能直接定根因。脚本的“优先结论”会把多项证据组合起来,并给出下一步建议。
|
||||||
|
|
||||||
|
`successful_transport` 只表示 HTTP 传输流程完成。HTTP 401、403、429、500、502 等仍可能计入传输成功,必须同时检查 `status_counts` 和报告中的优先结论。
|
||||||
|
|
||||||
|
## 15. 常用参数
|
||||||
|
|
||||||
|
| 参数 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `--url URL` | 目标地址,可重复 |
|
||||||
|
| `--url-env ENV` | 从环境变量读取目标 URL |
|
||||||
|
| `--compare-url URL` | 同一请求的另一路径,例如 Gateway 直连 |
|
||||||
|
| `--method GET/POST` | HTTP 方法 |
|
||||||
|
| `--bearer-env ENV` | 从环境变量读取 Bearer Token |
|
||||||
|
| `--cookie-env ENV` | 从环境变量读取 Cookie |
|
||||||
|
| `--header-env HEADER=ENV` | 从环境变量读取敏感请求头 |
|
||||||
|
| `--query-env KEY=ENV` | 从环境变量读取查询参数值 |
|
||||||
|
| `--data-file PATH` | 请求体文件,`-` 表示 stdin |
|
||||||
|
| `--count N` | 请求次数;GET 默认 5,POST 默认 1 |
|
||||||
|
| `--concurrency N` | 并发数,默认 1 |
|
||||||
|
| `--read-mode MODE` | `auto`、`headers`、`first-byte`、`full` |
|
||||||
|
| `--connect-timeout SEC` | DNS/TCP/TLS 相关连接超时 |
|
||||||
|
| `--first-byte-timeout SEC` | 等待响应头或首个响应实体字节的超时 |
|
||||||
|
| `--read-timeout SEC` | 正文空闲读取超时 |
|
||||||
|
| `--total-timeout SEC` | 单请求硬性总超时 |
|
||||||
|
| `--deerflow-suite` | 检查 DeerFlow 基线接口 |
|
||||||
|
| `--interference` | 慢 GET 执行期间持续测 health |
|
||||||
|
| `--server-checks` | 收集 Linux/Nginx/Docker/日志/数据库状态 |
|
||||||
|
| `--config PATH` | DeerFlow `config.yaml` 路径 |
|
||||||
|
| `--log PATH` | 增加一个待扫描日志,可重复 |
|
||||||
|
| `--nginx-status-url URL` | Nginx stub_status 地址 |
|
||||||
|
| `--mysql-host HOST` | 只做 MySQL TCP 测量 |
|
||||||
|
| `--mysql-defaults-file PATH` | 进行 MySQL 认证只读检查 |
|
||||||
|
| `--admin-token-env ENV` | 管理员只读并发检查 |
|
||||||
|
| `--output PATH` | JSON 报告路径 |
|
||||||
|
| `--no-output` | 不生成 JSON 文件 |
|
||||||
|
| `--json-stdout` | 将完整 JSON 输出到终端 |
|
||||||
|
|
||||||
|
查看全部参数:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 /tmp/diagnose_deerflow_latency.py --help
|
||||||
|
```
|
||||||
|
|
||||||
|
## 16. TLS、代理和重定向
|
||||||
|
|
||||||
|
- HTTPS 默认校验证书。
|
||||||
|
- 内部 CA 使用 `--ca-file /path/to/ca.pem`。
|
||||||
|
- `--insecure` 会关闭证书校验,仅用于明确了解风险的临时诊断,报告会记录安全警告。
|
||||||
|
- 默认不使用系统 `HTTP_PROXY`/`HTTPS_PROXY`,需要时显式增加 `--use-env-proxy`。
|
||||||
|
- 也可以使用 `--proxy` 或更安全的 `--proxy-env`。
|
||||||
|
- 默认不跟随重定向;`--follow-redirects` 只允许同 origin 跳转,跨 origin 会被拒绝。
|
||||||
|
- 带凭据、环境变量查询值或请求体时,非本机明文 HTTP 会被拒绝。优先使用 HTTPS,不建议使用 `--allow-insecure-http`。
|
||||||
|
|
||||||
|
`--allow-unsafe-replay`、`--allow-cross-origin-compare`、`--allow-cross-origin-admin`、`--allow-insecure-http` 和 `--insecure` 都是明确的风险开关,不应放进日常默认命令。
|
||||||
|
|
||||||
|
## 17. 日志和权限
|
||||||
|
|
||||||
|
脚本会尝试自动发现常见的 Nginx、Gateway 和运行日志,也可以显式提供:
|
||||||
|
|
||||||
|
```text
|
||||||
|
--log /var/log/nginx/error.log --log /path/to/gateway.log
|
||||||
|
```
|
||||||
|
|
||||||
|
报告只保存错误模式的命中次数,不保存完整日志行,避免把业务内容带入报告。
|
||||||
|
|
||||||
|
建议先以普通部署用户运行。权限不足时,报告会明确列出缺失项。不要为了方便直接把数据库密码或 Token 写进 `sudo` 命令行;如确需更高权限读取 Nginx/进程信息,应在受控 shell 中重新设置所需环境变量。
|
||||||
|
|
||||||
|
## 18. 报告安全
|
||||||
|
|
||||||
|
脚本不会保存:
|
||||||
|
|
||||||
|
- 请求体和响应体;
|
||||||
|
- Token、Cookie、密码或敏感请求头值;
|
||||||
|
- URL 查询参数值;
|
||||||
|
- MySQL SQL 正文;
|
||||||
|
- 原始日志行。
|
||||||
|
|
||||||
|
报告仍可能包含:
|
||||||
|
|
||||||
|
- IP、端口和路径;
|
||||||
|
- 容器名、模型名、数据库主机名;
|
||||||
|
- Nginx 和系统容量信息;
|
||||||
|
- 接口路径和状态码。
|
||||||
|
|
||||||
|
把报告发给其他人之前仍应人工检查和脱敏。不要公开上传到互联网。
|
||||||
|
|
||||||
|
## 19. 常见问题
|
||||||
|
|
||||||
|
### 报告显示“未完成检查”
|
||||||
|
|
||||||
|
通常是权限不足、命令不存在或功能未配置。例如:
|
||||||
|
|
||||||
|
- 没有 `ss`;
|
||||||
|
- 当前用户无法运行 `nginx -T`;
|
||||||
|
- 没有 Docker socket 权限;
|
||||||
|
- 没有安装 mysql client;
|
||||||
|
- 没有配置 Nginx stub_status;
|
||||||
|
- 管理员 Token 权限不足。
|
||||||
|
|
||||||
|
这不会使已经采集到的其他证据失效。
|
||||||
|
|
||||||
|
### 接口返回 401 或 403
|
||||||
|
|
||||||
|
检查 Bearer/Cookie 是否正确,以及接口是否需要特殊请求头。401/403 是 HTTP 响应,不属于 DNS/TCP/TLS 传输失败。
|
||||||
|
|
||||||
|
### 公网和直连业务不一致
|
||||||
|
|
||||||
|
某些 Nginx 配置依赖原始 `Host`。如果直接访问 `127.0.0.1:8001` 与公网执行的不是同一业务,则两者耗时不能直接比较。可根据实际配置增加非敏感 Host header:
|
||||||
|
|
||||||
|
```text
|
||||||
|
--header 'Host: example.com' --allow-cross-origin-compare
|
||||||
|
```
|
||||||
|
|
||||||
|
仅在确认后端确实需要该 Host 时使用。自定义 `Host` 会同时应用到公网目标和直连目标;不同 origin 的比较存在任意自定义 header 时,脚本要求显式使用 `--allow-cross-origin-compare`。
|
||||||
|
|
||||||
|
### 脚本没有抓到问题
|
||||||
|
|
||||||
|
间歇性卡顿通常需要在问题发生时运行。可以保留同一套命令,在用户反馈卡顿时立即执行,并同时记录准确时间,之后与 Nginx、Gateway、MySQL 监控对齐。
|
||||||
|
|
||||||
|
## 20. 提交结果供分析
|
||||||
|
|
||||||
|
建议提供以下信息:
|
||||||
|
|
||||||
|
1. 脱敏后的 JSON 报告;
|
||||||
|
2. 卡顿发生的准确时间和时区;
|
||||||
|
3. 目标 URL 路径,不需要 Token、Cookie 或密码;
|
||||||
|
4. 请求方法 GET/POST;
|
||||||
|
5. 是否经过 Nginx、负载均衡或网关;
|
||||||
|
6. 后端是否为 Docker 部署;
|
||||||
|
7. 公网和本机直连是否都慢;
|
||||||
|
8. 当时大约同时在线或执行 Agent 的人数。
|
||||||
|
|
||||||
|
不要提供真实账号密码、Token、Cookie、数据库密码或未经检查的完整业务日志。
|
||||||
@@ -1,6 +1,13 @@
|
|||||||
importScripts("config.js", "shared.js");
|
importScripts("config.js", "shared.js");
|
||||||
|
|
||||||
const ALARM_NAME = "deer-browser-task-poll";
|
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_API_BASE_URL = "http://localhost:8001";
|
||||||
const LEGACY_LOCAL_WEB_BASE_URL = "http://localhost:5174";
|
const LEGACY_LOCAL_WEB_BASE_URL = "http://localhost:5174";
|
||||||
let pollTimer = null;
|
let pollTimer = null;
|
||||||
@@ -18,6 +25,9 @@ async function getSettings() {
|
|||||||
const discovered = await chrome.storage.local.get({
|
const discovered = await chrome.storage.local.get({
|
||||||
discoveredApiBaseUrl: "",
|
discoveredApiBaseUrl: "",
|
||||||
discoveredWebBaseUrl: "",
|
discoveredWebBaseUrl: "",
|
||||||
|
lastServiceSyncAt: "",
|
||||||
|
lastServiceSyncSource: "",
|
||||||
|
lastServiceSyncContext: "",
|
||||||
});
|
});
|
||||||
if (settings.autoDiscoverServiceUrl) {
|
if (settings.autoDiscoverServiceUrl) {
|
||||||
settings.apiBaseUrl = discovered.discoveredApiBaseUrl || settings.apiBaseUrl;
|
settings.apiBaseUrl = discovered.discoveredApiBaseUrl || settings.apiBaseUrl;
|
||||||
@@ -33,6 +43,9 @@ async function getSettings() {
|
|||||||
if (!settings.workerId) {
|
if (!settings.workerId) {
|
||||||
updates.workerId = deerMakeWorkerId();
|
updates.workerId = deerMakeWorkerId();
|
||||||
}
|
}
|
||||||
|
settings.lastServiceSyncAt = discovered.lastServiceSyncAt || "";
|
||||||
|
settings.lastServiceSyncSource = discovered.lastServiceSyncSource || "";
|
||||||
|
settings.lastServiceSyncContext = discovered.lastServiceSyncContext || "";
|
||||||
if (Object.keys(updates).length > 0) {
|
if (Object.keys(updates).length > 0) {
|
||||||
await chrome.storage.sync.set(updates);
|
await chrome.storage.sync.set(updates);
|
||||||
Object.assign(settings, updates);
|
Object.assign(settings, updates);
|
||||||
@@ -100,28 +113,77 @@ function apiCandidatesForWebBase(webBase, currentApiBase) {
|
|||||||
return candidates;
|
return candidates;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function browserContextStatus(apiBaseUrl) {
|
async function serviceCacheKey(settings, apiBaseUrl, webBaseUrl = "") {
|
||||||
try {
|
const cookie = await getCookieToken({ ...settings, apiBaseUrl });
|
||||||
const response = await fetch(`${apiBaseUrl}/api/browser-context/status`, {
|
const auth = JSON.stringify([settings.accessToken || "", cookie?.token || ""]);
|
||||||
credentials: "include",
|
// Persist only a credential fingerprint with the discovery timestamp. A new
|
||||||
});
|
// login or cookie must not reuse another account's cached status/backoff.
|
||||||
// The gateway may enforce authentication globally before this otherwise
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(auth));
|
||||||
// public discovery endpoint is reached. A 401/403 still proves that this
|
const fingerprint = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||||
// candidate is the zncm API paired with the open frontend tab.
|
return JSON.stringify([normalizeServiceBase(apiBaseUrl), normalizeServiceBase(webBaseUrl), fingerprint]);
|
||||||
if (response.status === 401 || response.status === 403) {
|
}
|
||||||
return { enabled: true, authenticationRequired: true };
|
|
||||||
}
|
function statusRetryMs(response) {
|
||||||
if (!response.ok) {
|
const value = response.headers?.get("Retry-After");
|
||||||
return null;
|
if (!value) return STATUS_RETRY_MS;
|
||||||
}
|
const seconds = Number(value);
|
||||||
const data = await response.json().catch(() => null);
|
const delay = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now();
|
||||||
if (data && typeof data.enabled === "boolean") {
|
return Number.isFinite(delay) ? Math.max(STATUS_RETRY_MS, Math.min(delay, 60 * 60 * 1000)) : STATUS_RETRY_MS;
|
||||||
return data;
|
}
|
||||||
}
|
|
||||||
} catch {
|
async function browserContextStatus(apiBaseUrl, settings = {}, force = false) {
|
||||||
return null;
|
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(`${base}/api/browser-context/status`, {
|
||||||
|
credentials: "include",
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
const data = await response.json().catch(() => null);
|
||||||
|
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 {
|
||||||
|
// 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) {
|
function tabLooksLikeZncm(tab) {
|
||||||
@@ -173,9 +235,37 @@ async function findOpenZncmTabs(settings) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function discoverServiceBases(settings, force = false) {
|
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) {
|
if (!settings.autoDiscoverServiceUrl && !force) {
|
||||||
return settings;
|
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 < discoveryTtl
|
||||||
|
) {
|
||||||
|
return settings;
|
||||||
|
}
|
||||||
|
|
||||||
let webBaseUrl = normalizeServiceBase(settings.webBaseUrl || DEER_CLIPPER_DEFAULTS.webBaseUrl);
|
let webBaseUrl = normalizeServiceBase(settings.webBaseUrl || DEER_CLIPPER_DEFAULTS.webBaseUrl);
|
||||||
let discoveredWebBaseUrl = webBaseUrl;
|
let discoveredWebBaseUrl = webBaseUrl;
|
||||||
@@ -192,7 +282,7 @@ async function discoverServiceBases(settings, force = false) {
|
|||||||
let apiBaseUrl = normalizeServiceBase(settings.apiBaseUrl || DEER_CLIPPER_DEFAULTS.apiBaseUrl);
|
let apiBaseUrl = normalizeServiceBase(settings.apiBaseUrl || DEER_CLIPPER_DEFAULTS.apiBaseUrl);
|
||||||
let verified = false;
|
let verified = false;
|
||||||
for (const candidate of apiCandidatesForWebBase(discoveredWebBaseUrl, apiBaseUrl)) {
|
for (const candidate of apiCandidatesForWebBase(discoveredWebBaseUrl, apiBaseUrl)) {
|
||||||
const status = await browserContextStatus(candidate);
|
const status = await browserContextStatus(candidate, settings, force);
|
||||||
if (status) {
|
if (status) {
|
||||||
apiBaseUrl = candidate;
|
apiBaseUrl = candidate;
|
||||||
webBaseUrl = discoveredWebBaseUrl;
|
webBaseUrl = discoveredWebBaseUrl;
|
||||||
@@ -201,7 +291,7 @@ async function discoverServiceBases(settings, force = false) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!verified && force) {
|
if (!verified) {
|
||||||
source = `${source}:api_not_verified`;
|
source = `${source}:api_not_verified`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,22 +303,16 @@ async function discoverServiceBases(settings, force = false) {
|
|||||||
lastServiceSyncSource: source,
|
lastServiceSyncSource: source,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (
|
next.lastServiceSyncContext = await serviceCacheKey(next, next.apiBaseUrl, next.webBaseUrl);
|
||||||
force ||
|
// Refresh the timestamp even when the address/source did not change. Without
|
||||||
settings.apiBaseUrl !== next.apiBaseUrl ||
|
// this write the first expired TTL causes status probes on every later poll.
|
||||||
settings.webBaseUrl !== next.webBaseUrl ||
|
await chrome.storage.local.set({
|
||||||
settings.lastServiceSyncSource !== next.lastServiceSyncSource
|
discoveredApiBaseUrl: next.apiBaseUrl,
|
||||||
) {
|
discoveredWebBaseUrl: next.webBaseUrl,
|
||||||
// Discovered endpoints are runtime state, not user-authored preferences.
|
lastServiceSyncAt: next.lastServiceSyncAt,
|
||||||
// Keep them in storage.local so Chrome sync write quotas cannot break task
|
lastServiceSyncSource: next.lastServiceSyncSource,
|
||||||
// polling. The options page may still persist explicit user choices.
|
lastServiceSyncContext: next.lastServiceSyncContext,
|
||||||
await chrome.storage.local.set({
|
});
|
||||||
discoveredApiBaseUrl: next.apiBaseUrl,
|
|
||||||
discoveredWebBaseUrl: next.webBaseUrl,
|
|
||||||
lastServiceSyncAt: next.lastServiceSyncAt,
|
|
||||||
lastServiceSyncSource: next.lastServiceSyncSource,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return next;
|
return next;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,12 +3,18 @@ const fs = require("node:fs");
|
|||||||
const path = require("node:path");
|
const path = require("node:path");
|
||||||
const test = require("node:test");
|
const test = require("node:test");
|
||||||
const vm = require("node:vm");
|
const vm = require("node:vm");
|
||||||
|
const { webcrypto } = require("node:crypto");
|
||||||
|
|
||||||
const BACKGROUND_PATH = path.join(__dirname, "background.js");
|
const BACKGROUND_PATH = path.join(__dirname, "background.js");
|
||||||
|
|
||||||
function createHarness() {
|
function createHarness(options = {}) {
|
||||||
let storageChangedListener;
|
let storageChangedListener;
|
||||||
let alarmCreateCount = 0;
|
let alarmCreateCount = 0;
|
||||||
|
let clock = options.now ?? Date.now();
|
||||||
|
let fetchHandler = options.fetch;
|
||||||
|
let cookieToken = "";
|
||||||
|
const localData = options.localData || {};
|
||||||
|
const fetchUrls = [];
|
||||||
const settings = {
|
const settings = {
|
||||||
apiBaseUrl: "http://localhost:8001",
|
apiBaseUrl: "http://localhost:8001",
|
||||||
webBaseUrl: "http://localhost:5174",
|
webBaseUrl: "http://localhost:5174",
|
||||||
@@ -18,6 +24,7 @@ function createHarness() {
|
|||||||
taskPollingEnabled: true,
|
taskPollingEnabled: true,
|
||||||
workerId: "test-worker",
|
workerId: "test-worker",
|
||||||
taskPollIntervalSeconds: 5,
|
taskPollIntervalSeconds: 5,
|
||||||
|
...options.settings,
|
||||||
};
|
};
|
||||||
|
|
||||||
const chrome = {
|
const chrome = {
|
||||||
@@ -28,7 +35,7 @@ function createHarness() {
|
|||||||
},
|
},
|
||||||
onAlarm: { addListener: () => {} },
|
onAlarm: { addListener: () => {} },
|
||||||
},
|
},
|
||||||
cookies: { get: async () => null },
|
cookies: { get: async () => cookieToken ? { value: cookieToken } : null },
|
||||||
runtime: {
|
runtime: {
|
||||||
onInstalled: { addListener: () => {} },
|
onInstalled: { addListener: () => {} },
|
||||||
onMessage: { addListener: () => {} },
|
onMessage: { addListener: () => {} },
|
||||||
@@ -36,8 +43,8 @@ function createHarness() {
|
|||||||
},
|
},
|
||||||
storage: {
|
storage: {
|
||||||
local: {
|
local: {
|
||||||
get: async (defaults) => ({ ...defaults }),
|
get: async (defaults) => ({ ...defaults, ...localData }),
|
||||||
set: async () => {},
|
set: async (updates) => Object.assign(localData, updates),
|
||||||
},
|
},
|
||||||
session: { get: async () => ({ actSessions: {} }), set: async () => {} },
|
session: { get: async () => ({ actSessions: {} }), set: async () => {} },
|
||||||
sync: {
|
sync: {
|
||||||
@@ -56,13 +63,26 @@ function createHarness() {
|
|||||||
const context = {
|
const context = {
|
||||||
chrome,
|
chrome,
|
||||||
console,
|
console,
|
||||||
fetch: async () => {
|
fetch: async (url, init) => {
|
||||||
throw new Error("offline test");
|
fetchUrls.push(String(url));
|
||||||
|
if (fetchHandler) return fetchHandler(url, init);
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({ enabled: true }),
|
||||||
|
};
|
||||||
},
|
},
|
||||||
importScripts: () => {},
|
importScripts: () => {},
|
||||||
setTimeout: () => 1,
|
setTimeout: () => 1,
|
||||||
clearTimeout: () => {},
|
clearTimeout: () => {},
|
||||||
URL,
|
URL,
|
||||||
|
AbortController,
|
||||||
|
TextEncoder,
|
||||||
|
crypto: webcrypto,
|
||||||
|
Date: class extends Date {
|
||||||
|
constructor(...args) { super(...(args.length ? args : [clock])); }
|
||||||
|
static now() { return clock; }
|
||||||
|
},
|
||||||
DEER_CLIPPER_DEFAULTS: settings,
|
DEER_CLIPPER_DEFAULTS: settings,
|
||||||
deerNormalizeBaseUrl: (value) => String(value || "").replace(/\/+$/, ""),
|
deerNormalizeBaseUrl: (value) => String(value || "").replace(/\/+$/, ""),
|
||||||
deerMakeWorkerId: () => "test-worker",
|
deerMakeWorkerId: () => "test-worker",
|
||||||
@@ -79,6 +99,17 @@ function createHarness() {
|
|||||||
storageChangedListener(changes, "sync");
|
storageChangedListener(changes, "sync");
|
||||||
},
|
},
|
||||||
getAlarmCreateCount: () => alarmCreateCount,
|
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: () => {
|
resetAlarmCreateCount: () => {
|
||||||
alarmCreateCount = 0;
|
alarmCreateCount = 0;
|
||||||
},
|
},
|
||||||
@@ -128,3 +159,120 @@ test("service discovery prefers the API paired with the open zncm tab", async ()
|
|||||||
].filter((value, index, values) => values.indexOf(value) === index),
|
].filter((value, index, values) => values.indexOf(value) === index),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("automatic service discovery checks status once per ten minutes, not on every task poll", async () => {
|
||||||
|
const harness = createHarness();
|
||||||
|
const settings = await harness.getSettings();
|
||||||
|
settings.autoDiscoverServiceUrl = true;
|
||||||
|
|
||||||
|
await harness.discoverServiceBases(settings);
|
||||||
|
assert.equal(harness.getFetchUrls().length, 1);
|
||||||
|
|
||||||
|
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,620 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<!--
|
||||||
|
社交信息流 · 布局样式复刻 Demo(无品牌标识版)
|
||||||
|
------------------------------------------------
|
||||||
|
- 版式/布局参考主流社交平台桌面端信息流(顶栏 + 三栏 + 信息流卡片)
|
||||||
|
- 不包含任何真实平台的商标 / Logo / 品牌元素,可放心二次修改
|
||||||
|
- 所有展示数据集中在 <script> 顶部的「数据区」,替换字段即可换数据
|
||||||
|
- 双击直接用浏览器打开,无任何外部依赖
|
||||||
|
-->
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>社交信息流 · 布局样式 Demo</title>
|
||||||
|
<style>
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
html { color-scheme: light; }
|
||||||
|
body {
|
||||||
|
background: #f0f2f5;
|
||||||
|
color: #050505;
|
||||||
|
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue",
|
||||||
|
"PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
button { font: inherit; border: 0; background: none; cursor: pointer; color: inherit; }
|
||||||
|
svg { display: block; }
|
||||||
|
|
||||||
|
/* ============ 顶栏 ============ */
|
||||||
|
.topbar {
|
||||||
|
position: fixed; inset: 0 0 auto 0; height: 56px; z-index: 100;
|
||||||
|
background: #fff; box-shadow: 0 1px 2px rgba(0,0,0,.1);
|
||||||
|
display: flex; align-items: center; justify-content: space-between;
|
||||||
|
padding: 0 16px;
|
||||||
|
}
|
||||||
|
.tb-left, .tb-right { display: flex; align-items: center; gap: 8px; min-width: 280px; }
|
||||||
|
.tb-right { justify-content: flex-end; }
|
||||||
|
.logo-mark {
|
||||||
|
width: 40px; height: 40px; border-radius: 50%;
|
||||||
|
background: #1877f2; color: #fff; display: grid; place-items: center; flex: none;
|
||||||
|
}
|
||||||
|
.search-pill {
|
||||||
|
display: flex; align-items: center; gap: 8px;
|
||||||
|
background: #f0f2f5; border-radius: 20px; padding: 9px 14px;
|
||||||
|
width: 240px; color: #65676b;
|
||||||
|
}
|
||||||
|
.tb-center { display: flex; gap: 6px; }
|
||||||
|
.tb-tab {
|
||||||
|
width: 108px; height: 56px; border-radius: 8px;
|
||||||
|
display: grid; place-items: center; color: #65676b; position: relative;
|
||||||
|
}
|
||||||
|
.tb-tab:hover { background: #f2f2f2; }
|
||||||
|
.tb-tab.active { color: #1877f2; }
|
||||||
|
.tb-tab.active::after {
|
||||||
|
content: ""; position: absolute; left: 12px; right: 12px; bottom: 0;
|
||||||
|
height: 3px; border-radius: 3px 3px 0 0; background: #1877f2;
|
||||||
|
}
|
||||||
|
.icon-btn {
|
||||||
|
width: 40px; height: 40px; border-radius: 50%;
|
||||||
|
background: #e4e6eb; display: grid; place-items: center; position: relative;
|
||||||
|
}
|
||||||
|
.icon-btn:hover { background: #d8dadf; }
|
||||||
|
.notif-badge {
|
||||||
|
position: absolute; top: -3px; right: -3px;
|
||||||
|
background: #e41e3f; color: #fff; font-size: 11px; font-weight: 600;
|
||||||
|
line-height: 1; border-radius: 10px; padding: 3px 5px; border: 2px solid #fff;
|
||||||
|
}
|
||||||
|
.create-btn {
|
||||||
|
display: flex; align-items: center; gap: 6px;
|
||||||
|
background: #e4e6eb; border-radius: 8px; padding: 10px 14px; font-weight: 600;
|
||||||
|
}
|
||||||
|
.create-btn:hover { background: #d8dadf; }
|
||||||
|
|
||||||
|
/* ============ 三栏布局 ============ */
|
||||||
|
.layout {
|
||||||
|
display: flex; justify-content: center; gap: 16px;
|
||||||
|
max-width: 1240px; margin: 0 auto; padding: 72px 12px 32px;
|
||||||
|
}
|
||||||
|
.side {
|
||||||
|
width: 300px; flex: none;
|
||||||
|
position: sticky; top: 72px; align-self: flex-start;
|
||||||
|
max-height: calc(100vh - 80px); overflow-y: auto;
|
||||||
|
}
|
||||||
|
.feed { width: 590px; flex: none; }
|
||||||
|
@media (max-width: 1160px) { .side.right { display: none; } }
|
||||||
|
@media (max-width: 980px) { .side.left { display: none; } }
|
||||||
|
|
||||||
|
/* ============ 左侧导航 ============ */
|
||||||
|
.side-item {
|
||||||
|
display: flex; align-items: center; gap: 12px;
|
||||||
|
padding: 8px 12px; margin: 0 8px; border-radius: 8px;
|
||||||
|
font-size: 15px; font-weight: 500;
|
||||||
|
}
|
||||||
|
.side-item:hover { background: #e4e6eb; }
|
||||||
|
.side-item .si-ic { width: 36px; height: 36px; flex: none; color: #3a4a5c; display: grid; place-items: center; }
|
||||||
|
.side-sep { height: 1px; background: #e4e6eb; margin: 10px 16px; }
|
||||||
|
.side-title { color: #65676b; font-size: 17px; font-weight: 600; margin: 14px 16px 4px; }
|
||||||
|
.see-more { color: #65676b; }
|
||||||
|
|
||||||
|
/* ============ 快拍 ============ */
|
||||||
|
.stories { display: flex; gap: 8px; overflow-x: auto; padding: 4px 2px 12px; }
|
||||||
|
.story {
|
||||||
|
width: 112px; height: 200px; flex: none; border-radius: 12px;
|
||||||
|
position: relative; overflow: hidden; box-shadow: 0 1px 2px rgba(0,0,0,.15);
|
||||||
|
}
|
||||||
|
.story-create {
|
||||||
|
background: #fff; display: flex; flex-direction: column; justify-content: flex-end;
|
||||||
|
}
|
||||||
|
.story-create .sc-img { height: 148px; display: grid; place-items: center; color: #a8b3c4; }
|
||||||
|
.story-create .sc-label {
|
||||||
|
padding: 10px 8px 12px; text-align: center; font-size: 13px; font-weight: 600;
|
||||||
|
border-top: 1px solid #e4e6eb;
|
||||||
|
}
|
||||||
|
.story-create .sc-plus {
|
||||||
|
position: absolute; left: 50%; top: 124px; transform: translateX(-50%);
|
||||||
|
width: 36px; height: 36px; border-radius: 50%; background: #1877f2; color: #fff;
|
||||||
|
display: grid; place-items: center; border: 3px solid #fff;
|
||||||
|
}
|
||||||
|
.story-meta { position: absolute; left: 8px; right: 8px; bottom: 8px; color: #fff; }
|
||||||
|
.story-meta .sm-name {
|
||||||
|
font-size: 13px; font-weight: 600; text-shadow: 0 1px 2px rgba(0,0,0,.6);
|
||||||
|
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||||
|
}
|
||||||
|
.story-meta .avatar { border: 2px solid #fff; margin-bottom: 6px; }
|
||||||
|
|
||||||
|
/* ============ 卡片通用 ============ */
|
||||||
|
.card {
|
||||||
|
background: #fff; border-radius: 8px;
|
||||||
|
box-shadow: 0 1px 2px rgba(0,0,0,.1); margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.avatar {
|
||||||
|
width: 40px; height: 40px; border-radius: 50%; flex: none;
|
||||||
|
display: grid; place-items: center; color: #fff; font-weight: 600; font-size: 16px;
|
||||||
|
user-select: none; background: #1877f2;
|
||||||
|
}
|
||||||
|
.avatar.sm { width: 32px; height: 32px; font-size: 13px; }
|
||||||
|
|
||||||
|
/* ============ 发帖框 ============ */
|
||||||
|
.composer-top { display: flex; align-items: center; gap: 10px; padding: 12px 16px; }
|
||||||
|
.composer-input {
|
||||||
|
flex: 1; background: #f0f2f5; border-radius: 20px; padding: 10px 16px;
|
||||||
|
color: #65676b; font-size: 16px;
|
||||||
|
}
|
||||||
|
.composer-actions { display: flex; border-top: 1px solid #e4e6eb; margin: 2px 12px 0; }
|
||||||
|
.c-action {
|
||||||
|
flex: 1; display: flex; justify-content: center; align-items: center; gap: 8px;
|
||||||
|
padding: 10px; border-radius: 6px; font-weight: 600; color: #65676b;
|
||||||
|
}
|
||||||
|
.c-action:hover { background: #f2f2f2; }
|
||||||
|
.ic-video { color: #f3425f; } .ic-photo { color: #45bd62; } .ic-emoji { color: #f7b928; }
|
||||||
|
|
||||||
|
/* ============ 帖子 ============ */
|
||||||
|
.post-head { display: flex; align-items: center; gap: 10px; padding: 12px 16px 0; }
|
||||||
|
.ph-meta { flex: 1; min-width: 0; }
|
||||||
|
.ph-name { font-weight: 600; display: flex; align-items: center; gap: 4px; }
|
||||||
|
.ph-sub { color: #65676b; font-size: 13px; display: flex; align-items: center; gap: 4px; margin-top: 2px; }
|
||||||
|
.ph-more { color: #65676b; }
|
||||||
|
.post-text { padding: 12px 16px; line-height: 1.55; white-space: pre-wrap; }
|
||||||
|
.post-media { display: grid; gap: 2px; background: #fff; }
|
||||||
|
.post-media.n1 { grid-template-columns: 1fr; }
|
||||||
|
.post-media.n2 { grid-template-columns: 1fr 1fr; }
|
||||||
|
.post-media.n3 { grid-template-columns: 2fr 1fr; }
|
||||||
|
.post-media.n4 { grid-template-columns: 1fr 1fr; }
|
||||||
|
.tile { position: relative; overflow: hidden; aspect-ratio: 1.8; background: #dfe7f5; }
|
||||||
|
.post-media.n3 .tile:first-child { grid-row: span 2; aspect-ratio: auto; }
|
||||||
|
.tile img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||||
|
.img-ph {
|
||||||
|
position: absolute; inset: 0; display: grid; place-items: center;
|
||||||
|
color: rgba(255,255,255,.9);
|
||||||
|
}
|
||||||
|
.tile-more {
|
||||||
|
position: absolute; inset: 0; background: rgba(0,0,0,.45); color: #fff;
|
||||||
|
display: grid; place-items: center; font-size: 26px; font-weight: 600;
|
||||||
|
}
|
||||||
|
.link-card {
|
||||||
|
margin: 0 16px 12px; border: 1px solid #e4e6eb; border-radius: 8px;
|
||||||
|
overflow: hidden; display: flex;
|
||||||
|
}
|
||||||
|
.link-img { width: 140px; flex: none; min-height: 120px; position: relative; background: #dfe7f5; }
|
||||||
|
.link-img .img-ph { color: rgba(255,255,255,.9); }
|
||||||
|
.link-body { padding: 10px 14px; min-width: 0; }
|
||||||
|
.link-domain { color: #65676b; font-size: 12px; text-transform: uppercase; letter-spacing: .04em; }
|
||||||
|
.link-title { font-weight: 600; font-size: 15px; margin: 3px 0 4px; }
|
||||||
|
.link-desc { color: #65676b; font-size: 13px; line-height: 1.4; }
|
||||||
|
|
||||||
|
.stats { display: flex; align-items: center; gap: 6px; padding: 10px 16px 6px; color: #65676b; }
|
||||||
|
.stats .grow { flex: 1; }
|
||||||
|
.rx {
|
||||||
|
width: 20px; height: 20px; border-radius: 50%; background: #fff;
|
||||||
|
display: grid; place-items: center; box-shadow: 0 0 0 1px rgba(0,0,0,.05);
|
||||||
|
}
|
||||||
|
.post-actions { display: flex; border-top: 1px solid #e4e6eb; margin: 4px 12px 4px; }
|
||||||
|
.p-action {
|
||||||
|
flex: 1; display: flex; justify-content: center; align-items: center; gap: 8px;
|
||||||
|
padding: 9px; border-radius: 6px; font-weight: 600; color: #65676b;
|
||||||
|
}
|
||||||
|
.p-action:hover { background: #f2f2f2; }
|
||||||
|
.p-action.liked { color: #1877f2; }
|
||||||
|
|
||||||
|
.comments { padding: 2px 16px 12px; }
|
||||||
|
.comment { display: flex; gap: 8px; margin-top: 8px; }
|
||||||
|
.c-bubble { background: #f0f2f5; border-radius: 16px; padding: 8px 12px; min-width: 0; }
|
||||||
|
.c-name { font-weight: 600; font-size: 13px; }
|
||||||
|
.c-text { font-size: 15px; line-height: 1.45; }
|
||||||
|
.c-foot { padding-left: 40px; color: #65676b; font-size: 13px; font-weight: 600; display: flex; gap: 12px; margin-top: 2px; }
|
||||||
|
|
||||||
|
/* ============ 右侧栏 ============ */
|
||||||
|
.sponsored { display: flex; gap: 12px; padding: 8px 12px; margin: 0 8px; border-radius: 8px; }
|
||||||
|
.sponsored:hover { background: #e4e6eb; }
|
||||||
|
.sq {
|
||||||
|
width: 96px; height: 96px; flex: none; border-radius: 8px; overflow: hidden;
|
||||||
|
position: relative; background: #dfe7f5;
|
||||||
|
}
|
||||||
|
.sp-title { font-weight: 500; }
|
||||||
|
.sp-domain { color: #65676b; font-size: 13px; margin-top: 2px; }
|
||||||
|
.birthday {
|
||||||
|
display: flex; gap: 10px; padding: 4px 16px; font-size: 14px; line-height: 1.45;
|
||||||
|
}
|
||||||
|
.contact-row {
|
||||||
|
display: flex; align-items: center; gap: 10px;
|
||||||
|
padding: 6px 12px; margin: 0 8px; border-radius: 8px; font-weight: 500;
|
||||||
|
}
|
||||||
|
.contact-row:hover { background: #e4e6eb; }
|
||||||
|
.contact-av { position: relative; flex: none; }
|
||||||
|
.online-dot {
|
||||||
|
position: absolute; right: 0; bottom: 0; width: 10px; height: 10px;
|
||||||
|
border-radius: 50%; background: #31a24c; border: 2px solid #fff;
|
||||||
|
}
|
||||||
|
.contacts-head {
|
||||||
|
display: flex; align-items: center; justify-content: space-between;
|
||||||
|
padding: 6px 16px 2px;
|
||||||
|
}
|
||||||
|
.contacts-head .ch-actions { display: flex; gap: 8px; color: #65676b; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<!-- ================= 顶栏 ================= -->
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="tb-left">
|
||||||
|
<div class="logo-mark" title="示例 Logo(替换成你们自己的标识)">
|
||||||
|
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M21 11.5a8.5 8.5 0 0 1-8.5 8.5c-1.5 0-2.9-.4-4.1-1L3 20l1-5.4A8.5 8.5 0 1 1 21 11.5z"/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="search-pill">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><line x1="16.5" y1="16.5" x2="21" y2="21"/></svg>
|
||||||
|
搜索
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<nav class="tb-center">
|
||||||
|
<button class="tb-tab active" title="首页">
|
||||||
|
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="tb-tab" title="视频">
|
||||||
|
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="13" height="12" rx="2.5"/><path d="M15.5 10.5 21.5 7v10l-6-3.5"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="tb-tab" title="市场">
|
||||||
|
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9.5 5.2 4h13.6L20 9.5"/><path d="M4 9.5V20h16V9.5"/><path d="M10 20v-5.5h4V20"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="tb-tab" title="群组">
|
||||||
|
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8.5" r="3"/><path d="M3 20c0-3.2 2.7-5 6-5s6 1.8 6 5"/><circle cx="17" cy="9.5" r="2.3"/><path d="M16 15.3c2.9.2 5 1.8 5 4.7"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="tb-tab" title="游戏">
|
||||||
|
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="7.5" width="19" height="10" rx="4"/><path d="M7 10.5v4M5 12.5h4"/><circle cx="16" cy="11" r=".6" fill="currentColor"/><circle cx="18.5" cy="13.5" r=".6" fill="currentColor"/></svg>
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="tb-right">
|
||||||
|
<button class="create-btn">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
|
||||||
|
创建
|
||||||
|
</button>
|
||||||
|
<button class="icon-btn" title="菜单">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="5" r="1.7"/><circle cx="12" cy="5" r="1.7"/><circle cx="19" cy="5" r="1.7"/><circle cx="5" cy="12" r="1.7"/><circle cx="12" cy="12" r="1.7"/><circle cx="19" cy="12" r="1.7"/><circle cx="5" cy="19" r="1.7"/><circle cx="12" cy="19" r="1.7"/><circle cx="19" cy="19" r="1.7"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="icon-btn" title="消息">
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.5 8.5 0 0 1-8.5 8.5c-1.5 0-2.9-.4-4.1-1L3 20l1-5.4A8.5 8.5 0 1 1 21 11.5z"/><path d="M12.8 8 9.3 13h2.6l-.6 3.3 3.5-5.1h-2.6z"/></svg>
|
||||||
|
</button>
|
||||||
|
<button class="icon-btn" title="通知">
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M18 16v-5a6 6 0 1 0-12 0v5l-1.6 1.8h15.2z"/><path d="M10 20.2a2.1 2.1 0 0 0 4 0"/></svg>
|
||||||
|
<span class="notif-badge">3</span>
|
||||||
|
</button>
|
||||||
|
<div class="avatar" style="background:#45bd62">我</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- ================= 三栏 ================= -->
|
||||||
|
<div class="layout">
|
||||||
|
|
||||||
|
<!-- ---- 左侧导航 ---- -->
|
||||||
|
<aside class="side left">
|
||||||
|
<div class="side-item">
|
||||||
|
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8.5" r="3"/><path d="M3 20c0-3.2 2.7-5 6-5s6 1.8 6 5"/><circle cx="17" cy="9.5" r="2.3"/><path d="M16 15.3c2.9.2 5 1.8 5 4.7"/></svg></div>
|
||||||
|
好友
|
||||||
|
</div>
|
||||||
|
<div class="side-item">
|
||||||
|
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7.5V12l3 2"/></svg></div>
|
||||||
|
回忆动态
|
||||||
|
</div>
|
||||||
|
<div class="side-item">
|
||||||
|
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5.5A2.5 2.5 0 0 1 7.5 3h9a2.5 2.5 0 0 1 2.5 2.5z"/></svg></div>
|
||||||
|
已保存
|
||||||
|
</div>
|
||||||
|
<div class="side-item">
|
||||||
|
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8.5" r="3"/><path d="M3 20c0-3.2 2.7-5 6-5s6 1.8 6 5"/><circle cx="17" cy="9.5" r="2.3"/><path d="M16 15.3c2.9.2 5 1.8 5 4.7"/></svg></div>
|
||||||
|
群组
|
||||||
|
</div>
|
||||||
|
<div class="side-item">
|
||||||
|
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="13" height="12" rx="2.5"/><path d="M15.5 10.5 21.5 7v10l-6-3.5"/></svg></div>
|
||||||
|
视频
|
||||||
|
</div>
|
||||||
|
<div class="side-item">
|
||||||
|
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9.5 5.2 4h13.6L20 9.5"/><path d="M4 9.5V20h16V9.5"/><path d="M10 20v-5.5h4V20"/></svg></div>
|
||||||
|
市场
|
||||||
|
</div>
|
||||||
|
<div class="side-item">
|
||||||
|
<div class="si-ic"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M16 3v4M8 3v4M3 11h18"/></svg></div>
|
||||||
|
活动
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="side-sep"></div>
|
||||||
|
<div class="side-title">你的捷径</div>
|
||||||
|
<div class="side-item"><div class="avatar sm" style="background:#7c5cff">登</div>周末登山小队</div>
|
||||||
|
<div class="side-item"><div class="avatar sm" style="background:#12b5cb">摄</div>城市摄影交流</div>
|
||||||
|
<div class="side-item"><div class="avatar sm" style="background:#f3425f">书</div>读书会</div>
|
||||||
|
|
||||||
|
<div class="side-item see-more">
|
||||||
|
<div class="si-ic"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9l6 6 6-6"/></svg></div>
|
||||||
|
查看更多
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<!-- ---- 中间信息流 ---- -->
|
||||||
|
<main class="feed">
|
||||||
|
<!-- 快拍 -->
|
||||||
|
<div class="stories" id="stories"></div>
|
||||||
|
|
||||||
|
<!-- 发帖框 -->
|
||||||
|
<div class="card">
|
||||||
|
<div class="composer-top">
|
||||||
|
<div class="avatar" style="background:#45bd62">我</div>
|
||||||
|
<div class="composer-input">有什么新鲜事?</div>
|
||||||
|
</div>
|
||||||
|
<div class="composer-actions">
|
||||||
|
<button class="c-action ic-video">
|
||||||
|
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="13" height="12" rx="2.5"/><path d="M15.5 10.5 21.5 7v10l-6-3.5"/></svg>
|
||||||
|
直播视频
|
||||||
|
</button>
|
||||||
|
<button class="c-action ic-photo">
|
||||||
|
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10" r="1.5"/><path d="M21 15.5l-5-5-9 8"/></svg>
|
||||||
|
照片/视频
|
||||||
|
</button>
|
||||||
|
<button class="c-action ic-emoji">
|
||||||
|
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M8.5 14.5s1.3 1.8 3.5 1.8 3.5-1.8 3.5-1.8"/><circle cx="9" cy="9.5" r=".6" fill="currentColor"/><circle cx="15" cy="9.5" r=".6" fill="currentColor"/></svg>
|
||||||
|
感受/活动
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 帖子(由下方数据区渲染) -->
|
||||||
|
<div id="posts"></div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<!-- ---- 右侧栏 ---- -->
|
||||||
|
<aside class="side right">
|
||||||
|
<div class="side-title" style="margin-top:4px">赞助内容</div>
|
||||||
|
<div id="sponsored"></div>
|
||||||
|
|
||||||
|
<div class="side-sep"></div>
|
||||||
|
<div class="birthday">
|
||||||
|
<span style="font-size:24px">🎂</span>
|
||||||
|
<div><b>小林</b> 和 <b>赵敏</b> 今天过生日</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="side-sep"></div>
|
||||||
|
<div class="contacts-head">
|
||||||
|
<span style="color:#65676b;font-weight:600">联络人</span>
|
||||||
|
<span class="ch-actions">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><line x1="16.5" y1="16.5" x2="21" y2="21"/></svg>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="13" height="12" rx="2.5"/><path d="M15.5 10.5 21.5 7v10l-6-3.5"/></svg>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div id="contacts"></div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
/* ============================================================
|
||||||
|
数据区 —— 换数据只改这里
|
||||||
|
------------------------------------------------------------
|
||||||
|
FEED 帖子字段:
|
||||||
|
name 作者名 verified 是否显示认证标
|
||||||
|
time 发布时间文案 audience "公开" / "好友"
|
||||||
|
text 正文(\n 换行)
|
||||||
|
images 配图数组:"" = 灰色占位图;填图片 URL 则显示真实图片
|
||||||
|
数量 1-4 张,布局自动变化(1 大图 / 2 / 3 / 4 宫格)
|
||||||
|
link 可选链接卡片 { domain, title, desc }
|
||||||
|
likes 点赞数 shares 分享数
|
||||||
|
comments 评论数组 [{ name, text, time, likes }]
|
||||||
|
============================================================ */
|
||||||
|
const FEED = [
|
||||||
|
{
|
||||||
|
name: "张伟", time: "5 小时", audience: "公开",
|
||||||
|
text: "连续加班两周终于把项目收尾了,今天准点下班,\n路上顺手拍了一张晚霞。生活还是需要一点仪式感 🙂",
|
||||||
|
images: [""],
|
||||||
|
likes: 128, shares: 6,
|
||||||
|
comments: [
|
||||||
|
{ name: "赵敏", text: "恭喜收尾!这张晚霞拍得真好", time: "4 小时", likes: 12 },
|
||||||
|
{ name: "孙鹏", text: "下次组个饭局庆祝一下", time: "3 小时", likes: 3 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "城市天气指南", verified: true, time: "3 小时", audience: "公开",
|
||||||
|
text: "本周天气提示:周三起冷空气过境,气温下降 6–8℃,早晚温差加大,提醒大家适当添衣。详细预报见评论区链接。",
|
||||||
|
images: ["", "", ""],
|
||||||
|
likes: 402, shares: 36,
|
||||||
|
comments: [
|
||||||
|
{ name: "吴倩", text: "收到,已经把薄羽绒翻出来了", time: "2 小时", likes: 8 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "王强", time: "9 小时", audience: "好友",
|
||||||
|
text: "求推荐一条周末适合新手的徒步路线,最好单程 10 公里以内、交通方便的。打算这周就走,谢谢大家!",
|
||||||
|
images: [],
|
||||||
|
likes: 17, shares: 0,
|
||||||
|
comments: [
|
||||||
|
{ name: "陈晨", text: "西郊森林公园的环线不错,全程约 8 公里,坡度平缓", time: "8 小时", likes: 5 },
|
||||||
|
{ name: "周婷", text: "记得带够水,最近天气比较干", time: "7 小时", likes: 2 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "陈晨", time: "1 天", audience: "公开",
|
||||||
|
text: "整理了一篇新手徒步装备清单,有需要的朋友自取~",
|
||||||
|
images: [],
|
||||||
|
link: { domain: "example-outdoor.com", title: "2026 秋季徒步装备清单(新手向)", desc: "从鞋服到导航设备,一份可以照着买的入门清单。" },
|
||||||
|
likes: 54, shares: 9,
|
||||||
|
comments: [],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const STORIES = ["赵敏", "孙鹏", "周婷", "吴倩", "林芳"];
|
||||||
|
|
||||||
|
const SPONSORED = [
|
||||||
|
{ title: "云端笔记 Pro", domain: "cloudnote.example.com" },
|
||||||
|
{ title: "户外装备精选", domain: "outdoor.example.com" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const CONTACTS = ["刘洋", "赵敏", "孙鹏", "周婷", "吴倩", "郑凯", "林芳"];
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
以下为渲染逻辑,一般不用动
|
||||||
|
============================================================ */
|
||||||
|
const AV_COLORS = ["#1877f2", "#f3425f", "#45bd62", "#f7b928", "#7c5cff", "#12b5cb"];
|
||||||
|
const PH_GRADIENTS = [
|
||||||
|
"linear-gradient(135deg,#a8c5f0,#dfe7f5)",
|
||||||
|
"linear-gradient(135deg,#f8d3c5,#f7ebe4)",
|
||||||
|
"linear-gradient(135deg,#c9e5d3,#eaf5ee)",
|
||||||
|
"linear-gradient(135deg,#e2d8f7,#f0eaf9)",
|
||||||
|
"linear-gradient(135deg,#f6e3b0,#faf2df)",
|
||||||
|
];
|
||||||
|
const STORY_GRADIENTS = [
|
||||||
|
"linear-gradient(165deg,#5b8def,#8f6ee8)",
|
||||||
|
"linear-gradient(165deg,#f5a623,#ec5e8f)",
|
||||||
|
"linear-gradient(165deg,#2ec3a6,#3f8ee8)",
|
||||||
|
"linear-gradient(165deg,#8f6ee8,#5b8def)",
|
||||||
|
"linear-gradient(165deg,#ec5e8f,#f5a623)",
|
||||||
|
];
|
||||||
|
|
||||||
|
const esc = s => String(s).replace(/[&<>"]/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c]));
|
||||||
|
const colorOf = name => AV_COLORS[[...name].reduce((a, c) => a + c.charCodeAt(0), 0) % AV_COLORS.length];
|
||||||
|
const avatarHtml = (name, cls = "") =>
|
||||||
|
`<div class="avatar ${cls}" style="background:${colorOf(name)}">${esc(name.slice(0, 1))}</div>`;
|
||||||
|
|
||||||
|
const ICONS = {
|
||||||
|
like: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.3a2 2 0 0 0 2-1.7l1.4-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"/></svg>',
|
||||||
|
likeFilled: '<svg width="14" height="14" viewBox="0 0 24 24" fill="#1877f2" stroke="#1877f2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.3a2 2 0 0 0 2-1.7l1.4-9a2 2 0 0 0-2-2.3z"/><path d="M7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"/></svg>',
|
||||||
|
heart: '<svg width="14" height="14" viewBox="0 0 24 24" fill="#f3425f"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1-1.1a5.5 5.5 0 0 0-7.8 7.8l1 1L12 21.2l7.8-7.8 1-1a5.5 5.5 0 0 0 0-7.8z"/></svg>',
|
||||||
|
comment: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>',
|
||||||
|
share: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.59 13.51l6.83 3.98M15.41 6.51l-6.82 3.98"/></svg>',
|
||||||
|
globe: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a13.5 13.5 0 0 1 0 18 13.5 13.5 0 0 1 0-18z"/></svg>',
|
||||||
|
friends: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="9" cy="8.5" r="3"/><path d="M3 20c0-3.2 2.7-5 6-5s6 1.8 6 5"/><circle cx="17" cy="9.5" r="2.3"/></svg>',
|
||||||
|
dots: '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.8"/><circle cx="12" cy="12" r="1.8"/><circle cx="19" cy="12" r="1.8"/></svg>',
|
||||||
|
mountain: '<svg width="46" height="46" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10" r="1.5"/><path d="M21 15.5l-5-5-9 8"/></svg>',
|
||||||
|
link: '<svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>',
|
||||||
|
check: '<svg width="14" height="14" viewBox="0 0 24 24" fill="#1877f2"><circle cx="12" cy="12" r="10"/><path d="M17.5 9.5 10.7 16 7 12.3l1.4-1.4 2.3 2.3 5.4-5.2z" fill="#fff"/></svg>',
|
||||||
|
plus: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>',
|
||||||
|
};
|
||||||
|
|
||||||
|
const audienceIcon = a => (a === "好友" ? ICONS.friends : ICONS.globe);
|
||||||
|
const isImg = v => /^(https?:|data:|\.?\/)/.test(v);
|
||||||
|
|
||||||
|
function tileHtml(v, i) {
|
||||||
|
const inner = isImg(v)
|
||||||
|
? `<img src="${esc(v)}" alt="">`
|
||||||
|
: `<div class="img-ph" style="background:${PH_GRADIENTS[i % PH_GRADIENTS.length]}">${ICONS.mountain}</div>`;
|
||||||
|
return `<div class="tile">${inner}</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mediaHtml(images) {
|
||||||
|
if (!images || !images.length) return "";
|
||||||
|
const shown = images.slice(0, 4);
|
||||||
|
const cls = `n${Math.min(shown.length, 4)}`;
|
||||||
|
let html = shown.map((v, i) => tileHtml(v, i)).join("");
|
||||||
|
if (images.length > 4) {
|
||||||
|
html = html.replace(/<div class="tile">[\s\S]*<\/div>$/, m =>
|
||||||
|
m + `<div class="tile-more">+${images.length - 3}</div>`);
|
||||||
|
}
|
||||||
|
return `<div class="post-media ${cls}">${html}</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function linkCardHtml(link) {
|
||||||
|
if (!link) return "";
|
||||||
|
return `
|
||||||
|
<div class="link-card">
|
||||||
|
<div class="link-img"><div class="img-ph" style="background:linear-gradient(135deg,#a8c5f0,#dfe7f5)">${ICONS.link}</div></div>
|
||||||
|
<div class="link-body">
|
||||||
|
<div class="link-domain">${esc(link.domain)}</div>
|
||||||
|
<div class="link-title">${esc(link.title)}</div>
|
||||||
|
<div class="link-desc">${esc(link.desc || "")}</div>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function commentHtml(c) {
|
||||||
|
return `
|
||||||
|
<div class="comment">
|
||||||
|
${avatarHtml(c.name, "sm")}
|
||||||
|
<div style="min-width:0">
|
||||||
|
<div class="c-bubble">
|
||||||
|
<div class="c-name">${esc(c.name)}</div>
|
||||||
|
<div class="c-text">${esc(c.text)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="c-foot">
|
||||||
|
<span>赞 ${c.likes}</span><span>回复</span><span>${esc(c.time)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function postHtml(p) {
|
||||||
|
const comments = (p.comments || []).map(commentHtml).join("");
|
||||||
|
const commentCount = p.comments.length;
|
||||||
|
return `
|
||||||
|
<article class="card post">
|
||||||
|
<div class="post-head">
|
||||||
|
${avatarHtml(p.name)}
|
||||||
|
<div class="ph-meta">
|
||||||
|
<div class="ph-name">${esc(p.name)}${p.verified ? ICONS.check : ""}</div>
|
||||||
|
<div class="ph-sub">${audienceIcon(p.audience)} ${esc(p.time)}</div>
|
||||||
|
</div>
|
||||||
|
<button class="ph-more">${ICONS.dots}</button>
|
||||||
|
</div>
|
||||||
|
${p.text ? `<div class="post-text">${esc(p.text)}</div>` : ""}
|
||||||
|
${mediaHtml(p.images)}
|
||||||
|
${linkCardHtml(p.link)}
|
||||||
|
<div class="stats">
|
||||||
|
<span class="rx">${ICONS.likeFilled}</span><span class="rx">${ICONS.heart}</span>
|
||||||
|
<span class="like-count" data-base="${p.likes}">${p.likes}</span>
|
||||||
|
<span class="grow"></span>
|
||||||
|
${commentCount ? `<span>${commentCount} 条评论</span>` : ""}
|
||||||
|
${p.shares ? `<span>· ${p.shares} 次分享</span>` : ""}
|
||||||
|
</div>
|
||||||
|
<div class="post-actions">
|
||||||
|
<button class="p-action act-like">${ICONS.like}<span>赞</span></button>
|
||||||
|
<button class="p-action">${ICONS.comment}<span>评论</span></button>
|
||||||
|
<button class="p-action">${ICONS.share}<span>分享</span></button>
|
||||||
|
</div>
|
||||||
|
${comments ? `<div class="comments">${comments}</div>` : ""}
|
||||||
|
</article>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function storiesHtml() {
|
||||||
|
const items = STORIES.map((n, i) => `
|
||||||
|
<div class="story" style="background:${STORY_GRADIENTS[i % STORY_GRADIENTS.length]}">
|
||||||
|
<div class="story-meta">
|
||||||
|
<div class="avatar sm" style="background:${colorOf(n)}">${esc(n.slice(0, 1))}</div>
|
||||||
|
<div class="sm-name">${esc(n)}</div>
|
||||||
|
</div>
|
||||||
|
</div>`).join("");
|
||||||
|
return `
|
||||||
|
<div class="story story-create">
|
||||||
|
<div class="sc-img">${ICONS.mountain}</div>
|
||||||
|
<div class="sc-plus">${ICONS.plus}</div>
|
||||||
|
<div class="sc-label">创建快拍</div>
|
||||||
|
</div>${items}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
document.getElementById("posts").innerHTML = FEED.map(postHtml).join("");
|
||||||
|
document.getElementById("stories").innerHTML = storiesHtml();
|
||||||
|
document.getElementById("sponsored").innerHTML = SPONSORED.map(s => `
|
||||||
|
<div class="sponsored">
|
||||||
|
<div class="sq"><div class="img-ph" style="background:linear-gradient(135deg,#c9d8ef,#e9eff8)">${ICONS.mountain}</div></div>
|
||||||
|
<div style="min-width:0">
|
||||||
|
<div class="sp-title">${esc(s.title)}</div>
|
||||||
|
<div class="sp-domain">${esc(s.domain)}</div>
|
||||||
|
</div>
|
||||||
|
</div>`).join("");
|
||||||
|
document.getElementById("contacts").innerHTML = CONTACTS.map(n => `
|
||||||
|
<div class="contact-row">
|
||||||
|
<div class="contact-av">${avatarHtml(n, "sm")}<span class="online-dot"></span></div>
|
||||||
|
${esc(n)}
|
||||||
|
</div>`).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 点赞按钮可点击切换(纯前端演示) */
|
||||||
|
document.addEventListener("click", e => {
|
||||||
|
const btn = e.target.closest(".act-like");
|
||||||
|
if (!btn) return;
|
||||||
|
const count = btn.closest(".post").querySelector(".like-count");
|
||||||
|
const base = Number(count.dataset.base);
|
||||||
|
const liked = btn.classList.toggle("liked");
|
||||||
|
count.textContent = base + (liked ? 1 : 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
render();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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 三种文件传输适配提示词均位于管理员提示词之前。测试不访问真实上游模型。
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# 单机动态在线 Worker
|
||||||
|
|
||||||
|
## 范围与入口
|
||||||
|
|
||||||
|
管理员「设置 → 执行节点管理」配置 SSH 主机/IP、端口、账号、密码、SSH 主机指纹、源容器、Docker 网络、镜像内 Python/后端目录、节点数量、并发、队列和资源预算。也支持已有 Docker socket 挂载的本机连接,无需填写 SSH 密码。
|
||||||
|
|
||||||
|
本实现将 `/api/threads/{id}/runs`、`runs/stream`、`runs/wait` 的普通/智能体问答分发到固定会话所属的在线 Worker。分配后,该会话的状态、历史、停止、重连等 `/api/threads/{id}/…` 请求也转发到同一节点。鉴权及原有任务共享、用户隔离检查仍然执行。搜索、计数和未启用时沿用主服务。
|
||||||
|
|
||||||
|
定时任务、任务分析、研究、会商、工作流以及系统内部会话仍由唯一主服务执行;不在在线 Worker 启动它们的扫描、恢复或调度循环。无状态 `/api/runs/*`、专用写作接口等未纳入在线池。后台任务池尚未实现,不应将此版本描述为全业务分布式任务队列。
|
||||||
|
|
||||||
|
## 存储与并发
|
||||||
|
|
||||||
|
- 业务库与聊天存储独立:保留 MySQL/PostgreSQL 业务库,聊天存储支持 PostgreSQL 或 SQLite。SQLite 必须使用同机共享持久目录(不能单文件挂载或网络文件系统),开启 WAL、30 秒锁等待及跨进程初始化锁;内存存储拒绝开启。
|
||||||
|
- Worker 的运行事件使用共享业务数据库;聊天检查点沿用已有 PG/SQLite 配置,不迁移聊天记录。
|
||||||
|
- 控制器私有目录保存加密 SSH 凭证、加密密钥、实例标识和 SQLite 会话归属表。该表只保存路由,不存聊天正文。目录必须独立持久化,不能挂载给 Worker。实例标识和归属表不能单独删除或在旧容器运行时重建。
|
||||||
|
- Worker 池默认关闭。关闭时不启动控制器轮询、不申请单实例锁、不连接 Docker/SSH,也不创建亲和性或诊断数据库;原部署方式与多进程服务按原样运行。只有管理员启用 Worker 池后,控制器才申请单实例锁并开始管理容器;启用期间主服务需使用单个 Uvicorn 进程。同机同套部署的启用中主服务必须共用控制器卷。
|
||||||
|
- 执行额度绑定真实运行 Task 的生命周期;HTTP 请求结束或后台返回不提前释放额度。排队有数量和时间上限;超限返回 429/Retry-After。
|
||||||
|
- 每节点业务库连接池不允许额外溢出;检查点和 LangGraph Store 各有单独的 PG 连接池。系统按 `节点数 ×(业务库池大小 + 2 × PG 池大小)` 校验 Worker 连接预算。该预算须预先扣除主服务及其他应用的连接额度。
|
||||||
|
- Worker 在新运行开始前检查共享技能扩展配置,启停变更会刷新本进程缓存;技能文件变更按最多五秒的检查间隔刷新目录提示。CPU、模型配置等需要重启的配置仍应先排空 Worker 后更新。
|
||||||
|
- 会话归属在扩容后保持。缩容节点停止接收新运行,等待执行、排队和代理请求结束后停止,再释放归属。不自动重放失败请求。节点失联时返回 503;可确认进程停止后才允许后续重新分配。
|
||||||
|
- 重启后的旧运行读取为中断错误,不自动重试带外部副作用的工具。系统保留存储中已完成的检查点,不能承诺从任意工具执行位置无损恢复。
|
||||||
|
|
||||||
|
## 部署要求
|
||||||
|
|
||||||
|
发布仓库 `deerflow-offline-deployment` 已为标准模板增加控制器独立卷和 SSH/加密依赖清单。必须按该仓库既有流程构建包含全部依赖的离线包并部署新前后端源码。
|
||||||
|
|
||||||
|
1. Worker 池关闭时保留原部署进程数即可;启用 Worker 池后主容器使用单个 Uvicorn 进程。固定 `AUTH_JWT_SECRET` 必须在容器环境变量中。
|
||||||
|
2. 使用用户自定义 Docker 网络,主容器和新 Worker 均在该网络。数据库地址不能指向容器自身的 `localhost`。
|
||||||
|
3. 挂载全部运行目录、上传文件、技能、配置及必要的源码覆盖目录。Worker 复用其挂载,保留 ExtraHosts/DNS;不继承宿主机端口、Docker socket或特权模式。
|
||||||
|
4. `DEER_FLOW_WORKER_CONTROL_HOME` 指向独立持久卷,如 `/var/lib/deerflow-worker-control`。该卷会被自动排除,不传给 Worker;控制目录嵌在其他共享卷内时拒绝创建。
|
||||||
|
5. 当前支持不依赖 Docker socket 的执行沙箱。若业务配置需要 Worker 自行创建 Docker 沙箱,须先接入独立受控沙箱服务,不得直接复制 socket 权限。
|
||||||
|
6. 设置中默认保持关闭;填写连接参数和测试连接不会启动容器。管理员明确开启后才创建 Worker。标准离线镜像 Python 为 `/opt/venv/bin/python`,工作目录为 `/app/backend`;其他镜像按实际路径填写。
|
||||||
|
7. SSH 主机指纹可在页面读取并由管理员确认;账号需具备运行 Docker 的权限。不接受未知指纹,也不自动安装服务器软件。
|
||||||
|
|
||||||
|
容器使用源容器的精确镜像 ID,执行源码覆盖挂载与主容器相同。升级前数量设为 0,等待节点退出后升级主服务,再恢复数量;不会自动替换仍在执行的旧容器。
|
||||||
|
|
||||||
|
## 验证与容量
|
||||||
|
|
||||||
|
`tests/test_worker_pool.py` 包含凭证脱敏、模板限制、排队取消/超时、后台任务额度、归属持久化、失联不重放、缩容等待、双主进程拒绝、管理员授权,以及 70 个 HTTP 客户端分配到四个模拟 Worker 并返回 SSE 的回归。
|
||||||
|
|
||||||
|
这些是功能与模拟并发测试,不等同于真实模型、PostgreSQL、Docker 和服务器硬件的 70 人容量验收。部署后应在测试环境同时运行普通问答、文件工具和定时任务,观察首字延迟、完成时间、数据库连接数、模型限流和资源峰值;执行中的关闭浏览器、停止生成、节点重启、缩容都要验证。每节点并发数乘以节点数只是顶层运行上限,工具/子智能体仍可能产生额外模型调用,应配置模型服务总额度。
|
||||||
|
|
||||||
|
回退:将期望数量改为 0,等待全部节点消失后关闭池。主服务重新处理普通问答,聊天记录和运行目录继续保留。节点不能正常退出时不要直接删除控制器卷或归属表。
|
||||||
|
|
||||||
|
## 本次开发验证(2026-10-23)
|
||||||
|
|
||||||
|
- Worker 专项、账户鉴权、运行记录回收、执行线程池、完成超时和运行争用相关回归合计 **136 项通过**。
|
||||||
|
- 70 个模拟 HTTP 客户端进入四个模拟执行节点,分配为 18 / 18 / 17 / 17,全部收到 SSE 结束事件;另测执行额度、超时、取消及后台运行不提前释放额度。这不包含真实模型耗时。
|
||||||
|
- Python 静态检查、编译检查、改动空白检查通过;Linux 离线发布配置生成/校验通过。
|
||||||
|
- 新增前端页面及设置入口语法检查通过。全量 TypeScript 检查仍有其他模块错误,不能将前端全量检查标记为通过。
|
||||||
|
- 119 服务器检测为 32 核 CPU、128806 MB 内存;8008 实例已启动 4 个实际 Docker Worker,每节点 2 CPU / 2048 MB / 4 个同时执行额度;业务库保持 MySQL,既有聊天 SQLite 配置不变。
|
||||||
|
- 实际模型短问答:同一管理员下 70 个独立会话同时发起,70/70 完成,流式阶段约 59.59 秒;随后 70/70 历史记录读取确认回答已保存。这是短问答突发负载,不代表 70 个不同用户的复杂工具任务容量。
|
||||||
|
- Linux 上分别用 SQLite 和 PostgreSQL 执行 4 个进程各 25 次检查点/写入/Store 读写验证,各 100 次成功;PG 使用独立验收实例,未迁移业务库。
|
||||||
|
- 4→0→4 缩扩容与主服务重启后发现原有 4 个节点已验证(未重启整台服务器)。Worker 不启动定时任务调度器。
|
||||||
|
- 新增服务器探测和资源推荐:页面先读取 SSH 指纹,管理员确认后才发送密码登录;检测 Docker CPU/内存总量和其他容器资源上限,保留至少半台服务器资源,建议最多 4 个起步节点。不是实时空闲内存测量。
|
||||||
|
- 密码经 Fernet 加密保存在控制器持久卷;页面/API 不返回密码。更换服务器身份后必须重新填写密码,不能复用原服务器密码。配置和密钥卷需一起保留。
|
||||||
|
- Worker/聊天存储/跨线程数据库/资源推荐专项回归 37 项通过。
|
||||||
|
|
||||||
|
|
||||||
|
### 管理页面验收补充
|
||||||
|
|
||||||
|
2026-10-23 23:06 在 119:8008 实际页面完成保存并应用、测试已保存连接、读取服务器资源,三个请求均成功。截取资源推荐与四个就绪节点页面,保存在本次 `.runtime/worker-deploy-119/` 验收目录。前端生产构建成功。
|
||||||
|
|
||||||
|
当前运行池使用本机 Docker Socket。SSH 指纹读取已在服务器内网地址实测;SSH 账号密码认证尚需管理员在页面填写实际凭证验证。密码密文持久化、读取不回显、更换主机不复用密码、错误指纹拒绝连接均有测试覆盖。重启验证指主服务重启,未重启宿主机。
|
||||||
|
|
||||||
|
## 服务器诊断与并发验收补充(2026-10-24)
|
||||||
|
|
||||||
|
管理员诊断页 `/page/workspace/admin/server-diagnostics` 提供按开关采集的宿主机资源、MySQL/PG 连接、HTTP/SSE 分段耗时、主容器和 Worker 状态、日志读取与归档。主后端挂载 Docker Socket 和只读 `/proc`、`/sys`,Worker 不继承这些挂载。主服务日志轮转为 20 MB × 5,Worker 为 10 MB × 3;节点删除前保存有界日志归档。采样和请求摘要保存在控制器私有卷,接口不记录聊天正文、查询参数或鉴权头。
|
||||||
|
|
||||||
|
修复 Worker 执行队列阻塞流首次连接:先注册真实运行、建立流,再等待执行额度;保留额度上限和取消、超时语义。新线程默认只写元数据,首次运行再初始化检查点,保留显式初始化兼容参数;历史查询缩短 SQLite 游标持有时间。
|
||||||
|
|
||||||
|
本轮相关回归 133 项通过。119 实际 2 节点、4 节点各执行 70 路冷启动和 70 路第二轮,共 280/280 成功,两组各 70 个会话历史和状态回读通过。4 节点冷/热整轮耗时 68.851/46.287 秒,响应头 P95 为 18.141/11.548 秒;2 节点冷/热整轮耗时 115.026/74.151 秒。此为同一管理员的独立客户端短问答,不代表复杂工具容量。验收后恢复原先保存的 2 个节点。
|
||||||
|
|
||||||
|
页面实际验证了采集开关、资源和数据库卡片、主服务/Worker/归档日志,浏览器无脚本错误。119 当时 CPU 100%,独立采样 steal 约 24.6%,内存和 MySQL 连接仍有余量;需同时排查宿主机 CPU 争抢。PG/SQLite 兼容性在独立实例验证,业务 MySQL 和原聊天配置不变。
|
||||||
|
|
||||||
|
Linux AMD64/Python 3.12 增量交付包和部署说明保存在离线发版仓库;文档 `deploy/linux-docker-offline-deerflow-only/docs/14-Worker池与服务器诊断更新部署.md` 包含 Docker Socket 挂载、更新排空、依赖、资源建议和回退。交付源代码基于本次 119 验收版本,配置与数据不打入包。
|
||||||
@@ -0,0 +1,539 @@
|
|||||||
|
# Thread 创建慢与回答结束后 History 等待:优化方案
|
||||||
|
|
||||||
|
日期:2026-10-22
|
||||||
|
配套文档:[完整排查手册](./线程创建与History等待慢-排查手册.md)
|
||||||
|
|
||||||
|
## 1. 优化目标与结论
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- 降低 `POST /api/threads` 的 `checkpoint_create` 延迟;
|
||||||
|
- 降低 SSE 结束后 `/history` 的延迟;
|
||||||
|
- 避免慢 history 长时间占用全局 saver 锁并阻塞其他 thread;
|
||||||
|
- 处理 RunManager 内存 registry 持续增长;
|
||||||
|
- 保留对话 checkpoint 和历史记录,不通过直接删数据解决问题。
|
||||||
|
|
||||||
|
建议分四层实施:
|
||||||
|
|
||||||
|
| 优先级 | 动作 | 是否重启 | 风险 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| P0 | 基于 EXPLAIN 在线补建 history 组合索引 | 否 | 低;增加少量写放大和磁盘占用 |
|
||||||
|
| P1 | History 明确主 namespace,缩短 alist 持锁范围并补计时 | 是 | 中;需要 history/subgraph 回归 |
|
||||||
|
| P1 | 修复 `RunManager.cleanup()` 未调用 | 是 | 低到中;需要重连/终态回归 |
|
||||||
|
| P2 | 让 PG saver 真正支持并发读写,或拆出独立 history reader | 是 | 中到高;需要并发与一致性测试 |
|
||||||
|
| P3 | 根据 dead tuples、I/O 和保留策略做维护/归档 | 视操作而定 | 中到高 |
|
||||||
|
|
||||||
|
最快的低风险止血方案是:先确认跨 namespace History 执行计划确实有 Sort,然后在线创建 `(thread_id, checkpoint_id DESC)` 索引。该索引只能缩短 SQL 和持锁时间,不能消除 saver 实例级串行。
|
||||||
|
|
||||||
|
## 2. P0:在线补建 History 组合索引
|
||||||
|
|
||||||
|
### 2.1 适用条件
|
||||||
|
|
||||||
|
同时满足以下条件时执行:
|
||||||
|
|
||||||
|
1. 线上 `/history` 当前需要跨 `checkpoint_ns` 返回最新 checkpoint;或者短期内不能发布代码来限定 namespace。
|
||||||
|
2. 慢 thread 的执行计划出现 per-thread Sort、扫描候选行较多或执行时间明显高于限定 `checkpoint_ns=''` 的版本。
|
||||||
|
3. 已确认目标表 schema;以下示例假设是 `public`。
|
||||||
|
|
||||||
|
如果每个 thread 只有极少 checkpoint,EXPLAIN 已是亚毫秒级且无明显扫描/Sort,建索引不会解决应用层 saver lock 排队,应直接转向 P1/P2。
|
||||||
|
|
||||||
|
### 2.2 建索引前检查
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT current_database(), current_schema(), current_schemas(true);
|
||||||
|
|
||||||
|
SELECT
|
||||||
|
schemaname,
|
||||||
|
tablename,
|
||||||
|
indexname,
|
||||||
|
indexdef
|
||||||
|
FROM pg_indexes
|
||||||
|
WHERE tablename = 'checkpoints'
|
||||||
|
ORDER BY indexname;
|
||||||
|
```
|
||||||
|
|
||||||
|
确认没有等价的 `(thread_id, checkpoint_id)` 索引。已有单列 `checkpoints_thread_id_idx(thread_id)` 不等价:它可以过滤 thread,但不能直接提供跨 namespace 的 `checkpoint_id` 顺序。
|
||||||
|
|
||||||
|
保存变更前基线:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS, SETTINGS)
|
||||||
|
SELECT checkpoint_id, checkpoint_ns
|
||||||
|
FROM public.checkpoints
|
||||||
|
WHERE thread_id = '<THREAD_ID>'
|
||||||
|
ORDER BY checkpoint_id DESC
|
||||||
|
LIMIT 1;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 在线创建
|
||||||
|
|
||||||
|
`CREATE INDEX CONCURRENTLY` 必须作为独立语句执行,不能放在显式事务块中。确认数据库客户端没有自动把整段脚本包在一个事务里。
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SET lock_timeout = '5s';
|
||||||
|
SET statement_timeout = '0';
|
||||||
|
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS
|
||||||
|
checkpoints_thread_checkpoint_id_desc_idx
|
||||||
|
ON public.checkpoints (thread_id, checkpoint_id DESC);
|
||||||
|
|
||||||
|
RESET lock_timeout;
|
||||||
|
RESET statement_timeout;
|
||||||
|
```
|
||||||
|
|
||||||
|
然后更新统计:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
ANALYZE public.checkpoints;
|
||||||
|
```
|
||||||
|
|
||||||
|
不要把 `checkpoint` 或 `metadata` JSONB 加进 `INCLUDE`;它们较大,会显著扩大索引且不能解决此排序问题。
|
||||||
|
|
||||||
|
### 2.4 验证索引有效
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
i.relname AS index_name,
|
||||||
|
x.indisvalid,
|
||||||
|
x.indisready,
|
||||||
|
pg_size_pretty(pg_relation_size(i.oid)) AS index_size,
|
||||||
|
pg_get_indexdef(i.oid) AS indexdef
|
||||||
|
FROM pg_class t
|
||||||
|
JOIN pg_index x ON x.indrelid = t.oid
|
||||||
|
JOIN pg_class i ON i.oid = x.indexrelid
|
||||||
|
JOIN pg_namespace n ON n.oid = t.relnamespace
|
||||||
|
WHERE n.nspname = 'public'
|
||||||
|
AND t.relname = 'checkpoints'
|
||||||
|
AND i.relname = 'checkpoints_thread_checkpoint_id_desc_idx';
|
||||||
|
```
|
||||||
|
|
||||||
|
必须看到:
|
||||||
|
|
||||||
|
```text
|
||||||
|
indisvalid = true
|
||||||
|
indisready = true
|
||||||
|
```
|
||||||
|
|
||||||
|
重跑执行计划:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS, SETTINGS)
|
||||||
|
SELECT checkpoint_id, checkpoint_ns
|
||||||
|
FROM public.checkpoints
|
||||||
|
WHERE thread_id = '<THREAD_ID>'
|
||||||
|
ORDER BY checkpoint_id DESC
|
||||||
|
LIMIT 1;
|
||||||
|
```
|
||||||
|
|
||||||
|
预期:
|
||||||
|
|
||||||
|
- 使用 `checkpoints_thread_checkpoint_id_desc_idx`;
|
||||||
|
- 不再出现额外 Sort;
|
||||||
|
- 扫描行数接近 1;
|
||||||
|
- buffer read 和实际执行时间明显下降。
|
||||||
|
|
||||||
|
### 2.5 上线观察
|
||||||
|
|
||||||
|
至少对比变更前后:
|
||||||
|
|
||||||
|
- `/history` p50/p95/p99;
|
||||||
|
- `POST /threads` 的 `checkpoint_create` p50/p95/p99;
|
||||||
|
- checkpoint INSERT/UPSERT 的平均与最大耗时;
|
||||||
|
- 新索引大小;
|
||||||
|
- `pg_stat_user_indexes.idx_scan`;
|
||||||
|
- checkpoint 写入吞吐与 WAL/磁盘增长。
|
||||||
|
|
||||||
|
索引使用统计:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
schemaname,
|
||||||
|
relname,
|
||||||
|
indexrelname,
|
||||||
|
idx_scan,
|
||||||
|
idx_tup_read,
|
||||||
|
idx_tup_fetch
|
||||||
|
FROM pg_stat_user_indexes
|
||||||
|
WHERE relname = 'checkpoints'
|
||||||
|
ORDER BY indexrelname;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.6 回滚
|
||||||
|
|
||||||
|
如果索引导致不可接受的写放大、磁盘占用,或代码发布后已经不再需要跨 namespace 查询,可在线删除:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
DROP INDEX CONCURRENTLY IF EXISTS
|
||||||
|
public.checkpoints_thread_checkpoint_id_desc_idx;
|
||||||
|
```
|
||||||
|
|
||||||
|
同样不要放在显式事务块内。
|
||||||
|
|
||||||
|
如果在线创建被中断,先查询 `indisvalid/indisready`。若留下 invalid 索引,低峰执行上面的 `DROP INDEX CONCURRENTLY` 后再重新创建,不要假设 `IF NOT EXISTS` 会修复 invalid 索引。
|
||||||
|
|
||||||
|
## 3. P1:让普通 History 明确查询主 namespace
|
||||||
|
|
||||||
|
### 3.1 为什么这是长期更优方案
|
||||||
|
|
||||||
|
普通聊天主图状态使用:
|
||||||
|
|
||||||
|
```text
|
||||||
|
checkpoint_ns = ''
|
||||||
|
```
|
||||||
|
|
||||||
|
`checkpoints` 现有主键:
|
||||||
|
|
||||||
|
```text
|
||||||
|
(thread_id, checkpoint_ns, checkpoint_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
如果 History 的业务语义就是“普通聊天主图历史”,限定 `checkpoint_ns=''` 后,PostgreSQL 可以直接利用现有主键倒序取最新 checkpoint:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
WHERE thread_id = $1
|
||||||
|
AND checkpoint_ns = ''
|
||||||
|
ORDER BY checkpoint_id DESC
|
||||||
|
LIMIT 1
|
||||||
|
```
|
||||||
|
|
||||||
|
这样不需要为同一访问模式长期维护额外索引,也避免误把 subgraph namespace 中较新的 checkpoint 当作主聊天最新状态。
|
||||||
|
|
||||||
|
### 3.2 建议代码改动
|
||||||
|
|
||||||
|
当前:
|
||||||
|
|
||||||
|
```python
|
||||||
|
config: dict[str, Any] = {"configurable": {"thread_id": thread_id}}
|
||||||
|
```
|
||||||
|
|
||||||
|
建议:
|
||||||
|
|
||||||
|
```python
|
||||||
|
config: dict[str, Any] = {
|
||||||
|
"configurable": {
|
||||||
|
"thread_id": thread_id,
|
||||||
|
"checkpoint_ns": "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
位置:
|
||||||
|
|
||||||
|
```text
|
||||||
|
offline-backend-20260512/backend/app/gateway/routers/threads.py:1886
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 发布前必须验证
|
||||||
|
|
||||||
|
- 普通 lead agent 首轮和多轮历史恢复;
|
||||||
|
- 自定义 agent 历史恢复;
|
||||||
|
- subagent/subgraph 事件不应错误覆盖主图历史;
|
||||||
|
- interrupt/HITL 恢复;
|
||||||
|
- checkpoint `before` 分页;
|
||||||
|
- 页面刷新、重新打开会话、断流重连;
|
||||||
|
- `fetchStateHistory: { limit: 1 }` 返回的 messages、title、thread_data 正确。
|
||||||
|
|
||||||
|
如果某些 API 消费者明确要求跨 namespace 历史,不要直接全局改变语义。可以为普通聊天与诊断/调试接口拆分不同路径。
|
||||||
|
|
||||||
|
### 3.4 与 P0 索引的关系
|
||||||
|
|
||||||
|
- 紧急止血可以先建 P0 索引,再发布 namespace 修复。
|
||||||
|
- namespace 修复稳定运行一段时间后,通过 `pg_stat_user_indexes` 确认 P0 索引已不再需要,再在线删除。
|
||||||
|
- 不要在代码上线同一时刻立刻删索引,保留可快速回退窗口。
|
||||||
|
|
||||||
|
## 4. P1:缩短 `/history` 持有 saver lock 的时间
|
||||||
|
|
||||||
|
### 4.1 当前问题
|
||||||
|
|
||||||
|
当前 route 在下面的 `async for` 内处理并序列化每个 checkpoint:
|
||||||
|
|
||||||
|
```python
|
||||||
|
async for checkpoint_tuple in checkpointer.alist(config, limit=body.limit):
|
||||||
|
# 读取 checkpoint
|
||||||
|
# 序列化 messages
|
||||||
|
# 构造 HistoryEntry
|
||||||
|
```
|
||||||
|
|
||||||
|
PostgreSQL saver 的 `alist()` 在 `_cursor()` context 内 fetchall 后逐条 yield。调用方在处理 yielded tuple 时,generator 尚未退出,因此 saver lock 可能覆盖业务层消息序列化时间。
|
||||||
|
|
||||||
|
### 4.2 低风险 quick win
|
||||||
|
|
||||||
|
先完整、快速消费 bounded 结果,让 generator 退出并释放 saver cursor/lock,再在锁外做响应序列化:
|
||||||
|
|
||||||
|
```python
|
||||||
|
checkpoint_tuples = [
|
||||||
|
item
|
||||||
|
async for item in checkpointer.alist(config, limit=body.limit)
|
||||||
|
]
|
||||||
|
|
||||||
|
for checkpoint_tuple in checkpoint_tuples:
|
||||||
|
# 原来的 HistoryEntry/messages 序列化逻辑
|
||||||
|
```
|
||||||
|
|
||||||
|
当前普通前端请求 `limit=1`,额外内存可以忽略。接口模型允许更大 limit 时,仍需保留现有上限并测试大 checkpoint payload。
|
||||||
|
|
||||||
|
该改动不会解除 saver 内部对 SQL/反序列化的串行,但能避免 route 的 Python 序列化继续占着 saver lock。
|
||||||
|
|
||||||
|
### 4.3 同时增加 History 分段计时
|
||||||
|
|
||||||
|
建议记录无内容的阶段指标:
|
||||||
|
|
||||||
|
```text
|
||||||
|
history_checkpoint_fetch_ms
|
||||||
|
history_serialize_ms
|
||||||
|
history_total_ms
|
||||||
|
thread_id(清洗后)
|
||||||
|
limit
|
||||||
|
checkpointer 类型
|
||||||
|
```
|
||||||
|
|
||||||
|
这样可以区分:
|
||||||
|
|
||||||
|
- saver lock + SQL + checkpoint load;
|
||||||
|
- Gateway 消息序列化;
|
||||||
|
- route 外的鉴权/代理等待。
|
||||||
|
|
||||||
|
不要在日志中记录消息正文、checkpoint JSON、数据库 URL 或 token。
|
||||||
|
|
||||||
|
## 5. P1:修复 RunManager 内存 registry 增长
|
||||||
|
|
||||||
|
### 5.1 当前问题
|
||||||
|
|
||||||
|
`RunManager.cleanup()` 已存在:
|
||||||
|
|
||||||
|
```text
|
||||||
|
packages/harness/deerflow/runtime/runs/manager.py:318-324
|
||||||
|
```
|
||||||
|
|
||||||
|
但 worker finally 当前只调:
|
||||||
|
|
||||||
|
```python
|
||||||
|
asyncio.create_task(bridge.cleanup(run_id, delay=60))
|
||||||
|
```
|
||||||
|
|
||||||
|
这只删除 stream bridge 中的流缓存,不删除 `RunManager._runs`。因此一个进程运行越久,`create_or_reject()` 在 manager lock 内扫描的对象越多。
|
||||||
|
|
||||||
|
### 5.2 建议改动
|
||||||
|
|
||||||
|
在 run 已完成、终态已持久化并发布 SSE end 后,调度 run registry 清理:
|
||||||
|
|
||||||
|
```python
|
||||||
|
asyncio.create_task(bridge.cleanup(run_id, delay=60))
|
||||||
|
asyncio.create_task(run_manager.cleanup(run_id, delay=300))
|
||||||
|
```
|
||||||
|
|
||||||
|
延迟值可以结合重连窗口调整,但不要无限保留。
|
||||||
|
|
||||||
|
### 5.3 必须验证
|
||||||
|
|
||||||
|
- 完成后 60 秒内 SSE join/reconnect 行为不变;
|
||||||
|
- 内存记录删除后,`GET run` 能从持久化 store fallback;
|
||||||
|
- 已完成 run 的 join 能返回干净终态,而不是 404;
|
||||||
|
- cancel/rollback 与正在运行的任务不会被提前删除;
|
||||||
|
- 管理员并发监控只展示真实 active run;
|
||||||
|
- 进程内 `_runs` 数量在稳定负载下有上限,不随总历史永久增长。
|
||||||
|
|
||||||
|
这项修复与数据库 `runs` 保留策略无关,不会删除持久化历史记录。
|
||||||
|
|
||||||
|
## 6. P2:解除单 saver 实例的全局串行
|
||||||
|
|
||||||
|
### 6.1 不能采用的“优化”
|
||||||
|
|
||||||
|
仅提高:
|
||||||
|
|
||||||
|
```text
|
||||||
|
DEER_FLOW_PG_POOL_MAX
|
||||||
|
```
|
||||||
|
|
||||||
|
不会解决问题,因为 saver 在 pool checkout 前先获取实例锁。连接池容量只有在多个可并发 saver 操作真正进入 checkout 时才有意义。
|
||||||
|
|
||||||
|
### 6.2 可评估的实现方向
|
||||||
|
|
||||||
|
按风险从低到高:
|
||||||
|
|
||||||
|
1. 为只读 History 建立独立 saver/reader 实例,与 graph 写入 saver 使用同一个连接池但不同实例锁。
|
||||||
|
2. 将 History 改为专用、只读、受支持的 PostgreSQL repository,明确复用 LangGraph schema 与序列化协议。
|
||||||
|
3. 升级到确认支持 pool 并发且兼容当前 schema/serializer 的 checkpointer 版本。
|
||||||
|
4. 维护受控 patch,使 pool 场景不再用一个实例锁包住所有连接,但必须保留单连接/pipeline 模式所需的互斥。
|
||||||
|
|
||||||
|
不要直接删除第三方 saver 的 lock。该 lock 还保护单连接、pipeline、cursor 和 setup 等行为,粗暴移除可能造成事务/cursor 并发错误。
|
||||||
|
|
||||||
|
### 6.3 并发回归要求
|
||||||
|
|
||||||
|
至少覆盖:
|
||||||
|
|
||||||
|
- 一个慢 history 与一个新 thread `aput` 并发;
|
||||||
|
- history 与 graph `aput_writes` 并发;
|
||||||
|
- 20 个不同 thread 同时读/写;
|
||||||
|
- 同一个 thread 的顺序和 checkpoint parent 关系;
|
||||||
|
- PostgreSQL 重启、断开连接、pool 替换坏连接;
|
||||||
|
- cancellation 不泄漏 cursor/connection/lock;
|
||||||
|
- setup migration 只安全执行一次或可幂等执行;
|
||||||
|
- 回答正文、最终 state 和历史 reopen 一致。
|
||||||
|
|
||||||
|
现有回归入口:
|
||||||
|
|
||||||
|
```text
|
||||||
|
offline-backend-20260512/backend/packages/harness/tests/test_thread_operation_timing.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## 7. 前端结束态优化
|
||||||
|
|
||||||
|
### 7.1 当前行为
|
||||||
|
|
||||||
|
SDK 将结束后的 history refresh 放在 stream 的成功收尾内等待,因此 `/history` 延迟会直接延长 `thread.isLoading`。
|
||||||
|
|
||||||
|
30 秒 control/history timeout 只是防止永久挂死,不是性能优化。
|
||||||
|
|
||||||
|
### 7.2 可选方向
|
||||||
|
|
||||||
|
如果后端已经保证 SSE 最终 state 足够完整,可以评估:
|
||||||
|
|
||||||
|
- SSE `end` 到达后立即结束输入区 loading;
|
||||||
|
- `/history` 改为后台刷新;
|
||||||
|
- 刷新失败不丢弃已经流式到达的答案;
|
||||||
|
- 后台 history 成功后再校准 checkpoint id、title、thread_data 和 messages。
|
||||||
|
|
||||||
|
不要只把 `fetchStateHistory` 改成 `false`。当前 `onFinish(state, runMeta)` 依赖最终 state,直接关闭会改变回调语义,并可能影响标题、消息状态、listener 和断流恢复。
|
||||||
|
|
||||||
|
发布前至少验证:
|
||||||
|
|
||||||
|
- 最后一条 assistant message 不闪退、不重复;
|
||||||
|
- 首轮 thread id 和 URL 更新正确;
|
||||||
|
- interrupt/HITL 与 resume 正确;
|
||||||
|
- 页面刷新能从 checkpoint 恢复;
|
||||||
|
- SSE 丢失终态时仍能通过后台 history 校准;
|
||||||
|
- 用户不会在后端 run 尚未真正结束时误发下一轮。
|
||||||
|
|
||||||
|
因此前端解耦建议放在数据库索引、namespace 和 saver 持锁优化之后。
|
||||||
|
|
||||||
|
## 8. runs 表的针对性优化
|
||||||
|
|
||||||
|
### 8.1 先确认实际索引
|
||||||
|
|
||||||
|
当前 ORM 声明包括:
|
||||||
|
|
||||||
|
```text
|
||||||
|
runs_pkey(run_id)
|
||||||
|
ix_runs_thread_status(thread_id, status)
|
||||||
|
ix_runs_created_user_status(created_at, user_id, status)
|
||||||
|
ix_runs_user_created(user_id, created_at)
|
||||||
|
ix_runs_thread_created(thread_id, created_at)
|
||||||
|
ix_runs_created_assistant_user(created_at, assistant_id, user_id)
|
||||||
|
ix_runs_created_model_user(created_at, model_name, user_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
生产库是否实际存在必须用 `pg_indexes` 验证。
|
||||||
|
|
||||||
|
### 8.2 不要为普通 INSERT/PK UPDATE 盲目加索引
|
||||||
|
|
||||||
|
普通 run 创建是 INSERT,结束是 `WHERE run_id = ?` 的 UPDATE。已有主键时,额外索引不会让这两个操作更快,反而增加每次 INSERT/UPDATE 的索引维护成本。
|
||||||
|
|
||||||
|
只有某个明确查询的 EXPLAIN 证明缺索引时才补建。例如:
|
||||||
|
|
||||||
|
- `WHERE thread_id=? ORDER BY created_at DESC LIMIT 100` 缺少 `(thread_id, created_at)`;
|
||||||
|
- pending 恢复查询成为已确认慢点时,才评估 partial index:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_runs_pending_created
|
||||||
|
ON public.runs (created_at)
|
||||||
|
WHERE status = 'pending';
|
||||||
|
```
|
||||||
|
|
||||||
|
该 partial index不在普通 `/threads` 或 `/history` 路径上,不能作为本次问题的默认修复。
|
||||||
|
|
||||||
|
### 8.3 维护与膨胀
|
||||||
|
|
||||||
|
只有 `pg_stat_user_tables` 显示 runs/checkpoint 表死元组高、autovacuum 长期未运行时,才安排:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
VACUUM (ANALYZE) public.runs;
|
||||||
|
VACUUM (ANALYZE) public.checkpoints;
|
||||||
|
VACUUM (ANALYZE) public.checkpoint_blobs;
|
||||||
|
VACUUM (ANALYZE) public.checkpoint_writes;
|
||||||
|
```
|
||||||
|
|
||||||
|
普通 `VACUUM (ANALYZE)` 与 `VACUUM FULL` 不同,但仍会产生 I/O,应低峰执行并监控。不要在线直接使用 `VACUUM FULL`。
|
||||||
|
|
||||||
|
autovacuum 参数应根据写入速率、表大小、死元组和数据库资源制定,不在没有现场指标时给所有表套固定值。
|
||||||
|
|
||||||
|
## 9. 数据保留和归档
|
||||||
|
|
||||||
|
归档不是本次 6 秒问题的第一优先级。确有长期容量压力时,另行设计:
|
||||||
|
|
||||||
|
- 明确保留期限与可恢复 SLA;
|
||||||
|
- 只归档真正终态且超过保留期的 thread;
|
||||||
|
- `checkpoints`、`checkpoint_blobs`、`checkpoint_writes` 必须按同一批 thread 完整处理;
|
||||||
|
- 停止相关 writer 或使用经过验证的一致性流程;
|
||||||
|
- 先 dry-run,导出候选 thread,备份并演练恢复;
|
||||||
|
- 同库 archive schema 不一定立即回收磁盘;
|
||||||
|
- 旧会话入口与正文恢复策略要一起设计。
|
||||||
|
|
||||||
|
不要只删除 `checkpoints` 主表而留下 blob/write,也不要只按全局时间无视仍活跃 thread。
|
||||||
|
|
||||||
|
## 10. 建议实施顺序
|
||||||
|
|
||||||
|
### 阶段 A:当天可做
|
||||||
|
|
||||||
|
1. 用配套排查文档采集一轮完整证据。
|
||||||
|
2. 确认 6 秒集中在 `checkpoint_create` 或 `/history`。
|
||||||
|
3. 对慢 thread 跑两条 EXPLAIN。
|
||||||
|
4. 如果跨 namespace 查询有 Sort/大量扫描,低峰在线创建 P0 索引。
|
||||||
|
5. `ANALYZE checkpoints`,重跑 EXPLAIN。
|
||||||
|
6. 对比变更前后 `/history` 与 `checkpoint_create`。
|
||||||
|
|
||||||
|
### 阶段 B:下一次应用发布
|
||||||
|
|
||||||
|
1. 确认普通 history 的 namespace 语义并限定 `checkpoint_ns=''`。
|
||||||
|
2. 先完整消费 `alist`,在 saver lock 释放后序列化响应。
|
||||||
|
3. 增加 history fetch/serialize 分段计时。
|
||||||
|
4. 调用 `RunManager.cleanup()`,限制内存 registry 增长。
|
||||||
|
5. 补单元、集成和并发回归。
|
||||||
|
|
||||||
|
### 阶段 C:压测后实施
|
||||||
|
|
||||||
|
1. 评估独立 history saver/reader 或兼容升级。
|
||||||
|
2. 验证多 checkpoint 操作真实并发。
|
||||||
|
3. 再根据新架构调整 pool 大小。
|
||||||
|
4. 基于真实容量与保留期制定归档策略。
|
||||||
|
|
||||||
|
## 11. 验收标准
|
||||||
|
|
||||||
|
不要只看一次“变快了”,至少记录一段稳定流量下的分位数。
|
||||||
|
|
||||||
|
| 指标 | 验收方式 |
|
||||||
|
| --- | --- |
|
||||||
|
| `/threads` 总耗时 | 浏览器/APM p50、p95、p99 |
|
||||||
|
| `checkpoint_create` | `Server-Timing`/日志 p50、p95、p99 |
|
||||||
|
| `/history` 总耗时 | Gateway/APM p50、p95、p99 |
|
||||||
|
| History SQL | `pg_stat_statements` mean/max,EXPLAIN 实际时间 |
|
||||||
|
| saver 排队 | 应用分段计时中 lock/fetch 与 serialize 分离后观察 |
|
||||||
|
| 正确性 | 首轮、多轮、刷新、重连、interrupt、subagent 历史一致 |
|
||||||
|
| 资源 | PG CPU、I/O、WAL、连接数、新索引大小 |
|
||||||
|
| 内存 registry | `_runs` 数量不再随累计历史永久增长 |
|
||||||
|
|
||||||
|
成功信号:
|
||||||
|
|
||||||
|
- History 计划使用目标组合索引,或限定 namespace 后使用现有主键;
|
||||||
|
- `/history` 不再出现秒级长尾;
|
||||||
|
- 同期 history 不再让新 thread 的 `checkpoint_create` 出现同等长尾;
|
||||||
|
- 回答正文结束到 UI 可再次输入之间的间隔显著下降;
|
||||||
|
- 对话刷新、历史恢复和重连行为无回归。
|
||||||
|
|
||||||
|
如果 History SQL 已稳定在毫秒级,但 `checkpoint_create` 仍有秒级长尾,应停止继续堆索引,转向 saver 实例锁和事件循环排队的 P1/P2 优化。
|
||||||
|
|
||||||
|
## 12. 变更与回滚清单
|
||||||
|
|
||||||
|
```text
|
||||||
|
[ ] 保存部署 commit、配置和指标基线
|
||||||
|
[ ] 保存目标 thread 的 EXPLAIN
|
||||||
|
[ ] 核对 schema 和现有等价索引
|
||||||
|
[ ] CREATE INDEX CONCURRENTLY(不在事务中)
|
||||||
|
[ ] 检查 indisvalid/indisready
|
||||||
|
[ ] ANALYZE checkpoints
|
||||||
|
[ ] 重跑 EXPLAIN
|
||||||
|
[ ] 观察 API、PG、WAL、磁盘指标
|
||||||
|
[ ] 准备 DROP INDEX CONCURRENTLY 回滚语句
|
||||||
|
[ ] 代码变更补 history/subgraph/reconnect 回归
|
||||||
|
[ ] 先发布代码并观察,再决定是否删除临时索引
|
||||||
|
```
|
||||||
@@ -0,0 +1,916 @@
|
|||||||
|
# Thread 创建慢与回答结束后 History 等待:完整排查手册
|
||||||
|
|
||||||
|
日期:2026-10-22
|
||||||
|
适用范围:DeerFlow Gateway、LangGraph `useStream`、PostgreSQL 业务库与 PostgreSQL checkpointer。
|
||||||
|
|
||||||
|
## 1. 先说结论
|
||||||
|
|
||||||
|
当前代码证据表明:
|
||||||
|
|
||||||
|
1. `POST /api/threads` **不查询 `runs` 表**。它查询/写入 `threads_meta`,然后同步写入一个空 checkpoint。
|
||||||
|
2. 创建 run 时,持久化层主要执行 `INSERT INTO runs (...)`;run 结束时主要执行 `UPDATE runs ... WHERE run_id = ?`。`run_id` 是主键,`runs` 有 5 万行本身通常不足以造成 6 秒延迟。
|
||||||
|
3. 回答流结束后出现 `POST /api/threads/{thread_id}/history` 是前端 SDK 的正常行为。当前前端配置 `fetchStateHistory: { limit: 1 }`,SDK 会等待这个请求完成后才结束 `isLoading`,因此会出现“回答文字已经显示完,但页面仍在等待中”。
|
||||||
|
4. `/history` 实际查询 `checkpoints`、`checkpoint_blobs`、`checkpoint_writes`,不是查询 `runs`。
|
||||||
|
5. 当前 `/history` 只传 `thread_id`,核心查询是:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
WHERE thread_id = $1
|
||||||
|
ORDER BY checkpoint_id DESC
|
||||||
|
LIMIT 1
|
||||||
|
```
|
||||||
|
|
||||||
|
`checkpoints` 主键为 `(thread_id, checkpoint_ns, checkpoint_id)`。当不限定 `checkpoint_ns` 时,主键不能直接提供跨 namespace 的 `checkpoint_id` 顺序,可能需要扫描该 thread 的候选行并做 top-N Sort。
|
||||||
|
6. 当前进程只创建一个全局 `AsyncPostgresSaver`。该 saver 在取得连接池连接之前先获取实例级 `asyncio.Lock`,所以 checkpoint 的 `aget/alist/aput/aput_writes` 在一个 Gateway 进程内实际是串行的。慢 `/history` 会延长持锁时间,并阻塞新 thread 的空 checkpoint 写入。
|
||||||
|
|
||||||
|
最符合当前现象的候选链路是:
|
||||||
|
|
||||||
|
```text
|
||||||
|
回答正文已经通过 SSE 到达浏览器
|
||||||
|
-> 后端完成 run 收尾并发送 SSE end
|
||||||
|
-> 前端 SDK 同步请求 /history
|
||||||
|
-> /history 查询或反序列化 checkpoint,期间占用 saver 实例锁
|
||||||
|
-> SDK 的 isLoading 仍为 true,页面继续显示等待
|
||||||
|
-> 同期创建新 thread 时,checkpoint_create 等待同一把 saver 锁
|
||||||
|
-> POST /threads 偶发耗时数秒
|
||||||
|
```
|
||||||
|
|
||||||
|
这只是代码层面的高概率根因。最终必须使用同一次线上复现的 `Server-Timing`、Gateway 日志和 PostgreSQL 活动快照闭环确认。
|
||||||
|
|
||||||
|
## 2. 两类 PostgreSQL 数据不要混淆
|
||||||
|
|
||||||
|
系统存在两类持久化访问。即使它们使用同一个 PostgreSQL DSN,也有不同的连接池和代码路径。
|
||||||
|
|
||||||
|
| 类型 | 主要表 | 主要用途 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 应用 ORM 数据 | `threads_meta`、`runs` | 会话元数据、run 状态、统计字段 |
|
||||||
|
| LangGraph checkpointer | `checkpoints`、`checkpoint_blobs`、`checkpoint_writes`、`checkpoint_migrations` | 对话状态、消息、通道值、pending writes |
|
||||||
|
|
||||||
|
排查前先记录:
|
||||||
|
|
||||||
|
```text
|
||||||
|
部署 commit:
|
||||||
|
前端构建版本:
|
||||||
|
Gateway worker 数:
|
||||||
|
database.backend:
|
||||||
|
database PostgreSQL 主机/库名(脱敏):
|
||||||
|
checkpointer 实际后端:
|
||||||
|
checkpointer PostgreSQL 主机/库名(脱敏):
|
||||||
|
langgraph-checkpoint-postgres 版本:
|
||||||
|
```
|
||||||
|
|
||||||
|
注意:
|
||||||
|
|
||||||
|
- 仅确认 `database.backend=postgres` 不等于已经确认 `/history` 使用 PostgreSQL checkpointer。
|
||||||
|
- 当前运行时可能由统一 `database.postgres_url` 提供业务 ORM 与 checkpointer,也可能使用兼容配置中的独立 `checkpointer` 段。
|
||||||
|
- 若 legacy 配置为 `checkpointer.type=postgres` 但 `use_postgres=false`,checkpointer 会回退 SQLite。
|
||||||
|
- 当前 live run 与 SSE bridge 是进程内状态,正常部署要求 `GATEWAY_WORKERS=1`。不要用盲目增加 worker 的方式绕过该问题。
|
||||||
|
|
||||||
|
## 3. 浏览器看到的完整请求时间线
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
participant UI as 浏览器 / useStream
|
||||||
|
participant API as Gateway
|
||||||
|
participant APPDB as 业务 PostgreSQL
|
||||||
|
participant CP as Checkpointer PostgreSQL
|
||||||
|
|
||||||
|
UI->>API: POST /api/threads
|
||||||
|
API->>APPDB: SELECT/INSERT threads_meta
|
||||||
|
API->>CP: UPSERT 初始 checkpoint
|
||||||
|
API-->>UI: thread_id
|
||||||
|
UI->>API: POST /api/threads/{id}/runs/stream
|
||||||
|
API->>APPDB: INSERT runs
|
||||||
|
API-->>UI: SSE 正文/工具事件
|
||||||
|
API->>CP: 持续写 checkpoint/blob/write
|
||||||
|
API->>APPDB: UPDATE runs 终态
|
||||||
|
API-->>UI: SSE end
|
||||||
|
UI->>API: POST /api/threads/{id}/history limit=1
|
||||||
|
API->>CP: 最新 checkpoint + blob/write
|
||||||
|
API-->>UI: history
|
||||||
|
Note over UI: history 完成后 isLoading 才结束
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.1 创建新会话
|
||||||
|
|
||||||
|
前端 SDK 在没有 `threadId` 时,会先 `await client.threads.create(...)`,成功后才发起 `runs.stream(...)`。因此 `POST /api/threads` 慢 6 秒,会直接表现为点击发送后 6 秒才开始回答流。
|
||||||
|
|
||||||
|
后端调用位置:
|
||||||
|
|
||||||
|
- `app/gateway/routers/threads.py:853-927`
|
||||||
|
- 前端使用点:`frontend-web/src/core/threads/hooks.ts:702-711`
|
||||||
|
- SDK 等待 thread create:安装包 `dist/react/stream.lgp.js:318-327`
|
||||||
|
|
||||||
|
### 3.2 回答结束后的 History
|
||||||
|
|
||||||
|
当前前端配置:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
fetchStateHistory: { limit: 1 }
|
||||||
|
```
|
||||||
|
|
||||||
|
SDK 在 SSE 成功结束后执行:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const lastHead = (await history.mutate(threadId))?.at(0);
|
||||||
|
```
|
||||||
|
|
||||||
|
之后才调用 `onFinish` 并结束当前 stream loading 状态。当前项目的 `onFinish(state, runMeta)` 还显式接收最终 state,所以 SDK 也需要拿到 history state。
|
||||||
|
|
||||||
|
相关位置:
|
||||||
|
|
||||||
|
- `frontend-web/src/core/threads/hooks.ts:711`
|
||||||
|
- `frontend-web/src/core/threads/hooks.ts:976-1038`
|
||||||
|
- SDK `dist/react/stream.lgp.js:379-388`
|
||||||
|
- 页面最终暴露的 loading:`frontend-web/src/core/threads/hooks.ts:1920`
|
||||||
|
- 普通控制/history 请求超时保护:`frontend-web/src/core/api/api-client.ts:96-101`,当前为 30 秒
|
||||||
|
|
||||||
|
结论:最后看到 `/history` 并不表示模型还在生成;它可能只是 SDK 在做结束后的最终状态刷新。
|
||||||
|
|
||||||
|
## 4. 每个阶段实际执行什么 SQL
|
||||||
|
|
||||||
|
以下为当前代码和 `langgraph-checkpoint-postgres==3.1.2` 对应的等价 SQL。SQLAlchemy/psycopg 最终的占位符和列顺序可能略有差异,但访问表、过滤条件和索引需求一致。
|
||||||
|
|
||||||
|
### 4.1 `POST /api/threads`
|
||||||
|
|
||||||
|
调用链:
|
||||||
|
|
||||||
|
```text
|
||||||
|
threads.create_thread
|
||||||
|
-> ThreadMetaRepository.get
|
||||||
|
-> ThreadMetaRepository.create(仅新 thread)
|
||||||
|
-> AsyncPostgresSaver.aput(empty_checkpoint)
|
||||||
|
```
|
||||||
|
|
||||||
|
第一步,幂等查询:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT ...
|
||||||
|
FROM threads_meta
|
||||||
|
WHERE thread_id = $1;
|
||||||
|
```
|
||||||
|
|
||||||
|
`threads_meta.thread_id` 应为主键。
|
||||||
|
|
||||||
|
新 thread 写元数据:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO threads_meta (...)
|
||||||
|
VALUES (...);
|
||||||
|
```
|
||||||
|
|
||||||
|
同步写入初始 checkpoint:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO checkpoints (
|
||||||
|
thread_id,
|
||||||
|
checkpoint_ns,
|
||||||
|
checkpoint_id,
|
||||||
|
parent_checkpoint_id,
|
||||||
|
checkpoint,
|
||||||
|
metadata
|
||||||
|
)
|
||||||
|
VALUES ($1, '', $2, NULL, $3, $4)
|
||||||
|
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id)
|
||||||
|
DO UPDATE SET
|
||||||
|
checkpoint = EXCLUDED.checkpoint,
|
||||||
|
metadata = EXCLUDED.metadata;
|
||||||
|
```
|
||||||
|
|
||||||
|
初始 checkpoint 的 `new_versions={}`,通常不会同时写 `checkpoint_blobs`。
|
||||||
|
|
||||||
|
该接口分阶段计时:
|
||||||
|
|
||||||
|
| `Server-Timing` 字段 | 实际内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| `metadata_lookup` | `threads_meta` 按 `thread_id` 查询 |
|
||||||
|
| `metadata_create` | 新建 `threads_meta` 并提交事务 |
|
||||||
|
| `checkpoint_create` | 等待 saver 锁、取得连接、写 checkpoint、提交/同步 pipeline |
|
||||||
|
| `handler_total` | 进入 route handler 后的总时间 |
|
||||||
|
|
||||||
|
关键点:该接口的整条路径不读取或写入 `runs`。
|
||||||
|
|
||||||
|
### 4.2 `POST /api/threads/{thread_id}/runs/stream`
|
||||||
|
|
||||||
|
调用链:
|
||||||
|
|
||||||
|
```text
|
||||||
|
thread_runs.stream_run
|
||||||
|
-> services.start_run
|
||||||
|
-> RunManager.create_or_reject
|
||||||
|
-> RunRepository.put
|
||||||
|
-> 创建后台 run_agent task
|
||||||
|
```
|
||||||
|
|
||||||
|
`RunManager.create_or_reject` 先在 Python 进程内的全局 manager lock 下扫描 `_runs.values()`,检查同 thread、同模型以及同用户模型并发。该步骤不是 SQL。
|
||||||
|
|
||||||
|
然后持久化 run:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO runs (
|
||||||
|
run_id,
|
||||||
|
thread_id,
|
||||||
|
assistant_id,
|
||||||
|
user_id,
|
||||||
|
status,
|
||||||
|
model_name,
|
||||||
|
multitask_strategy,
|
||||||
|
metadata_json,
|
||||||
|
kwargs_json,
|
||||||
|
error,
|
||||||
|
follow_up_to_run_id,
|
||||||
|
created_at,
|
||||||
|
updated_at,
|
||||||
|
...
|
||||||
|
)
|
||||||
|
VALUES (...);
|
||||||
|
```
|
||||||
|
|
||||||
|
随后会查询或更新 `threads_meta`,再启动后台 agent。Gateway 在慢路径输出:
|
||||||
|
|
||||||
|
```text
|
||||||
|
[start-run-timing] thread=... total=...s enforce_access=...s run_create=...s thread_upsert=...s build_payload=...s
|
||||||
|
```
|
||||||
|
|
||||||
|
其中 `run_create` 包含:
|
||||||
|
|
||||||
|
- 进程内 `_runs` 扫描;
|
||||||
|
- `INSERT INTO runs`;
|
||||||
|
- 数据库 COMMIT。
|
||||||
|
|
||||||
|
### 4.3 graph 执行期间
|
||||||
|
|
||||||
|
LangGraph 会反复调用:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO checkpoint_blobs (...)
|
||||||
|
VALUES (...)
|
||||||
|
ON CONFLICT (thread_id, checkpoint_ns, channel, version)
|
||||||
|
DO NOTHING;
|
||||||
|
```
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO checkpoints (...)
|
||||||
|
VALUES (...)
|
||||||
|
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id)
|
||||||
|
DO UPDATE SET checkpoint = EXCLUDED.checkpoint,
|
||||||
|
metadata = EXCLUDED.metadata;
|
||||||
|
```
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO checkpoint_writes (...)
|
||||||
|
VALUES (...)
|
||||||
|
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
||||||
|
DO UPDATE SET channel = EXCLUDED.channel,
|
||||||
|
type = EXCLUDED.type,
|
||||||
|
blob = EXCLUDED.blob;
|
||||||
|
```
|
||||||
|
|
||||||
|
因此 checkpoint 数据量一般会明显大于 runs 数量:一个 run 可以产生多个 checkpoint、blob 和 write。
|
||||||
|
|
||||||
|
### 4.4 回答正文结束到 SSE `end`
|
||||||
|
|
||||||
|
graph 流结束后,后端仍会执行终态检查与收尾:
|
||||||
|
|
||||||
|
1. 第一次读取主 namespace 最新 checkpoint,用于确认 graph 已留下 terminal state:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT ...
|
||||||
|
FROM checkpoints
|
||||||
|
WHERE thread_id = $1
|
||||||
|
AND checkpoint_ns = ''
|
||||||
|
ORDER BY checkpoint_id DESC
|
||||||
|
LIMIT 1;
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 更新 run 状态:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
UPDATE runs
|
||||||
|
SET status = $2,
|
||||||
|
updated_at = $3,
|
||||||
|
error = COALESCE($4, error)
|
||||||
|
WHERE run_id = $1;
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 更新 run completion/token/message 统计,仍然是:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
UPDATE runs
|
||||||
|
SET ...
|
||||||
|
WHERE run_id = $1;
|
||||||
|
```
|
||||||
|
|
||||||
|
4. 收尾阶段再次读取主 namespace 最新 checkpoint,用于同步标题和最终元数据。
|
||||||
|
5. 更新 `threads_meta` 状态/标题等信息。
|
||||||
|
6. 最后发布 SSE `end`。
|
||||||
|
|
||||||
|
两次 checkpoint 读取都会争用同一个 saver 实例锁。因此实际等待链可能是“正文已经生成 → terminal checkpoint 读取等锁 → completion 更新 → finalize checkpoint 读取再次等锁 → SSE end → 前端 `/history` 再次读 checkpoint”。
|
||||||
|
|
||||||
|
`runs` 的上述 UPDATE 按 `run_id` 主键定位。若该阶段慢,应该检查锁等待、连接池、事务提交和死元组,而不是仅凭总行数判断。
|
||||||
|
|
||||||
|
后端为终态收尾设置了 10 秒预算,相关日志包括:
|
||||||
|
|
||||||
|
```text
|
||||||
|
RUN_COMPLETION_TIMEOUT run_id=... phase=terminal_checkpoint
|
||||||
|
RUN_COMPLETION_TIMEOUT run_id=... phase=terminal_status
|
||||||
|
RUN_COMPLETION_TIMEOUT run_id=... phase=metadata_cleanup
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.5 `POST /api/threads/{thread_id}/history`
|
||||||
|
|
||||||
|
路由当前构造的 config 只有 `thread_id`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
config = {"configurable": {"thread_id": thread_id}}
|
||||||
|
```
|
||||||
|
|
||||||
|
前端当前传 `limit=1`。saver 生成的核心 SQL 形态为:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
thread_id,
|
||||||
|
checkpoint,
|
||||||
|
checkpoint_ns,
|
||||||
|
checkpoint_id,
|
||||||
|
parent_checkpoint_id,
|
||||||
|
metadata,
|
||||||
|
(
|
||||||
|
SELECT array_agg(...)
|
||||||
|
FROM jsonb_each_text(checkpoint -> 'channel_versions')
|
||||||
|
JOIN checkpoint_blobs bl
|
||||||
|
ON bl.thread_id = checkpoints.thread_id
|
||||||
|
AND bl.checkpoint_ns = checkpoints.checkpoint_ns
|
||||||
|
AND bl.channel = jsonb_each_text.key
|
||||||
|
AND bl.version = jsonb_each_text.value
|
||||||
|
) AS channel_values,
|
||||||
|
(
|
||||||
|
SELECT array_agg(...)
|
||||||
|
FROM checkpoint_writes cw
|
||||||
|
WHERE cw.thread_id = checkpoints.thread_id
|
||||||
|
AND cw.checkpoint_ns = checkpoints.checkpoint_ns
|
||||||
|
AND cw.checkpoint_id = checkpoints.checkpoint_id
|
||||||
|
) AS pending_writes
|
||||||
|
FROM checkpoints
|
||||||
|
WHERE thread_id = $1
|
||||||
|
ORDER BY checkpoint_id DESC
|
||||||
|
LIMIT 1;
|
||||||
|
```
|
||||||
|
|
||||||
|
其中 blob/write 的相关子查询可以使用各自组合主键;最值得核对的是最外层 `checkpoints` 的跨 namespace 排序。
|
||||||
|
|
||||||
|
## 5. 为什么连接池最大 10 仍可能串行
|
||||||
|
|
||||||
|
当前 provider 创建:
|
||||||
|
|
||||||
|
```text
|
||||||
|
AsyncConnectionPool(min_size=1, max_size=10)
|
||||||
|
-> 一个 AsyncPostgresSaver(pool)
|
||||||
|
-> 挂到 app.state,供所有 thread/run/history 共用
|
||||||
|
```
|
||||||
|
|
||||||
|
`langgraph-checkpoint-postgres==3.1.2` 的 `_cursor()` 关键实现是:
|
||||||
|
|
||||||
|
```python
|
||||||
|
async with self.lock, get_connection(self.conn) as conn:
|
||||||
|
```
|
||||||
|
|
||||||
|
这意味着:
|
||||||
|
|
||||||
|
- saver 先拿实例锁,再去连接池 checkout;
|
||||||
|
- 同一个 saver 的所有 checkpoint 读写一次只能有一个进入 `_cursor()`;
|
||||||
|
- 把 `DEER_FLOW_PG_POOL_MAX` 从 10 调到更大,不能解除这个实例锁;
|
||||||
|
- 等待 saver 锁的 coroutine 尚未进入 PostgreSQL,因此 `pg_stat_activity` 可能只看到一个活动连接,看不到应用中其余等待者;
|
||||||
|
- `alist()` 在 cursor context 内 `fetchall()` 后逐项 `yield`,调用方处理 yielded tuple 时 generator 尚未退出,实例锁仍可能保持占用。
|
||||||
|
|
||||||
|
仓库已有 characterization test:
|
||||||
|
|
||||||
|
```text
|
||||||
|
packages/harness/tests/test_thread_operation_timing.py:204-247
|
||||||
|
```
|
||||||
|
|
||||||
|
它验证了 pool 场景下第二个 saver cursor 会等待第一个 cursor 释放。
|
||||||
|
|
||||||
|
## 6. `runs` 5 万行到底会不会慢
|
||||||
|
|
||||||
|
### 6.1 数据库中的 5 万条 runs
|
||||||
|
|
||||||
|
正常创建/完成路径主要是:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO runs (...);
|
||||||
|
UPDATE runs SET ... WHERE run_id = $1;
|
||||||
|
```
|
||||||
|
|
||||||
|
`run_id` 是主键,5 万行对 PostgreSQL 很小。只要:
|
||||||
|
|
||||||
|
- `runs_pkey` 存在且有效;
|
||||||
|
- 没有严重锁等待;
|
||||||
|
- 死元组和表/索引膨胀不严重;
|
||||||
|
- 数据库连接与存储 I/O 正常;
|
||||||
|
|
||||||
|
就不应仅因为 5 万行产生 6 秒延迟。
|
||||||
|
|
||||||
|
### 6.2 进程内 `_runs` 与数据库 `runs` 不是一回事
|
||||||
|
|
||||||
|
代码中存在一个独立问题:
|
||||||
|
|
||||||
|
- `RunManager.cleanup()` 能从 `_runs` 字典删除已结束记录;
|
||||||
|
- 当前 worker finally 只调用 `StreamBridge.cleanup()`;
|
||||||
|
- 全仓当前没有调用 `run_manager.cleanup(...)`;
|
||||||
|
- 因此同一个 Gateway 进程生命周期内完成的 run 会一直留在 `_runs`;
|
||||||
|
- 每次 `create_or_reject()` 会在 manager lock 内对 `_runs.values()` 做 1~3 次 O(N) 扫描。
|
||||||
|
|
||||||
|
数据库的 5 万条 runs 不会在启动时自动全部加载到 `_runs`。只有当当前进程自身长期运行并累计大量 run 时,这个问题才会放大。它是应该修复的增长性缺陷,但通常不是单独造成 6 秒的首要解释。
|
||||||
|
|
||||||
|
## 7. 一次完整的线上复现怎么采集
|
||||||
|
|
||||||
|
### 7.1 浏览器 Network
|
||||||
|
|
||||||
|
打开 DevTools → Network:
|
||||||
|
|
||||||
|
1. 勾选 `Preserve log`。
|
||||||
|
2. 过滤 `threads`。
|
||||||
|
3. 从创建新对话开始完整复现一次。
|
||||||
|
4. 记录以下请求:
|
||||||
|
|
||||||
|
| 阶段 | 请求 |
|
||||||
|
| --- | --- |
|
||||||
|
| 创建会话 | `POST /api/threads` |
|
||||||
|
| 问答流 | `POST /api/threads/{thread_id}/runs/stream` |
|
||||||
|
| 结束刷新 | `POST /api/threads/{thread_id}/history` |
|
||||||
|
|
||||||
|
记录:
|
||||||
|
|
||||||
|
```text
|
||||||
|
thread_id:
|
||||||
|
run_id:
|
||||||
|
请求开始时间:
|
||||||
|
HTTP 状态:
|
||||||
|
Waiting/TTFB:
|
||||||
|
Content Download:
|
||||||
|
响应大小:
|
||||||
|
请求结束时间:
|
||||||
|
```
|
||||||
|
|
||||||
|
另外记录:
|
||||||
|
|
||||||
|
- `runs/stream` 最后一个可见正文 chunk 的时间;
|
||||||
|
- SSE 真正结束时间;
|
||||||
|
- `/history` 开始和完成时间;
|
||||||
|
- 页面退出“等待中”的时间;
|
||||||
|
- `POST /api/threads` 响应头中的 `Server-Timing`。
|
||||||
|
|
||||||
|
导出 HAR 前删除 Authorization、Cookie、token 和业务正文。
|
||||||
|
|
||||||
|
### 7.2 `POST /threads` 的 `Server-Timing`
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```http
|
||||||
|
Server-Timing: metadata_lookup;dur=18.20, metadata_create;dur=25.10, checkpoint_create;dur=5880.30, handler_total;dur=5930.10
|
||||||
|
```
|
||||||
|
|
||||||
|
判断:
|
||||||
|
|
||||||
|
| 结果 | 优先结论 |
|
||||||
|
| --- | --- |
|
||||||
|
| `checkpoint_create` 约等于总耗时 | saver 锁等待、checkpointer 连接获取或 checkpoint PG 写入 |
|
||||||
|
| `metadata_lookup` 慢 | 业务 PG 的 `threads_meta` 主键查询、连接池或锁 |
|
||||||
|
| `metadata_create` 慢 | 业务 PG 插入/提交、索引维护或锁 |
|
||||||
|
| 所有 phase 很快但 `handler_total` 慢 | phase 外逻辑或事件循环调度竞争 |
|
||||||
|
| `handler_total` 很快但浏览器 TTFB 慢 | 鉴权、中间件、反向代理、进入 handler 前排队 |
|
||||||
|
| 没有 `Server-Timing` | 线上版本不包含该诊断,或请求没有进入预期 route |
|
||||||
|
|
||||||
|
`checkpoint_create` 包含 saver lock 和 pool 等待,不只是 SQL 执行时间。
|
||||||
|
|
||||||
|
### 7.3 Gateway 日志
|
||||||
|
|
||||||
|
本地脚本部署:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
rg -n "GATEWAY_OPERATION_TIMING|start-run-timing|RUN_COMPLETION_TIMEOUT|completion metadata exceeded|Failed to finalize run|Checkpointer|pool timeout|OperationalError" .runtime/logs
|
||||||
|
```
|
||||||
|
|
||||||
|
容器部署:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker logs --since 15m <gateway-container> 2>&1 \
|
||||||
|
| rg "GATEWAY_OPERATION_TIMING|start-run-timing|RUN_COMPLETION_TIMEOUT|completion metadata exceeded|Failed to finalize run|Checkpointer|pool timeout|OperationalError"
|
||||||
|
```
|
||||||
|
|
||||||
|
将同一个 `thread_id`、`run_id` 整理成时间线:
|
||||||
|
|
||||||
|
```text
|
||||||
|
T0 POST /threads 开始
|
||||||
|
T1 thread_create 分阶段日志
|
||||||
|
T2 run 开始
|
||||||
|
T3 最后正文事件
|
||||||
|
T4 run 标记 success/error
|
||||||
|
T5 SSE end
|
||||||
|
T6 /history 开始
|
||||||
|
T7 /history 完成
|
||||||
|
T8 UI 退出等待
|
||||||
|
```
|
||||||
|
|
||||||
|
## 8. PostgreSQL 只读排查 SQL
|
||||||
|
|
||||||
|
以下查询默认当前连接就是目标数据库。若应用使用非 `public` schema,先确认实际 schema,再修改后续 SQL。`<THREAD_ID>` 和 `<RUN_ID>` 必须替换成真实值。
|
||||||
|
|
||||||
|
### 8.1 确认 schema、版本和现有索引
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT current_database(), current_schema(), current_schemas(true);
|
||||||
|
|
||||||
|
SELECT max(v) AS checkpoint_schema_version
|
||||||
|
FROM checkpoint_migrations;
|
||||||
|
|
||||||
|
SELECT
|
||||||
|
schemaname,
|
||||||
|
tablename,
|
||||||
|
indexname,
|
||||||
|
indexdef
|
||||||
|
FROM pg_indexes
|
||||||
|
WHERE tablename IN (
|
||||||
|
'runs',
|
||||||
|
'threads_meta',
|
||||||
|
'checkpoints',
|
||||||
|
'checkpoint_blobs',
|
||||||
|
'checkpoint_writes'
|
||||||
|
)
|
||||||
|
ORDER BY tablename, indexname;
|
||||||
|
```
|
||||||
|
|
||||||
|
`langgraph-checkpoint-postgres 3.1.2` 正常 setup 应包含三张 checkpoint 表的组合主键以及:
|
||||||
|
|
||||||
|
```text
|
||||||
|
checkpoints_thread_id_idx
|
||||||
|
checkpoint_blobs_thread_id_idx
|
||||||
|
checkpoint_writes_thread_id_idx
|
||||||
|
```
|
||||||
|
|
||||||
|
不要因为模型代码声明了索引就假设生产库一定存在,最终以 `pg_indexes`/`pg_index` 为准。
|
||||||
|
|
||||||
|
确认索引是否 valid/ready:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
n.nspname AS schema_name,
|
||||||
|
t.relname AS table_name,
|
||||||
|
i.relname AS index_name,
|
||||||
|
x.indisvalid,
|
||||||
|
x.indisready,
|
||||||
|
pg_get_indexdef(i.oid) AS indexdef
|
||||||
|
FROM pg_class t
|
||||||
|
JOIN pg_namespace n ON n.oid = t.relnamespace
|
||||||
|
JOIN pg_index x ON x.indrelid = t.oid
|
||||||
|
JOIN pg_class i ON i.oid = x.indexrelid
|
||||||
|
WHERE t.relname IN (
|
||||||
|
'runs',
|
||||||
|
'threads_meta',
|
||||||
|
'checkpoints',
|
||||||
|
'checkpoint_blobs',
|
||||||
|
'checkpoint_writes'
|
||||||
|
)
|
||||||
|
ORDER BY t.relname, i.relname;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 表规模、死元组和维护情况
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
schemaname,
|
||||||
|
relname,
|
||||||
|
n_live_tup,
|
||||||
|
n_dead_tup,
|
||||||
|
round(
|
||||||
|
100.0 * n_dead_tup /
|
||||||
|
greatest(n_live_tup + n_dead_tup, 1),
|
||||||
|
2
|
||||||
|
) AS dead_pct,
|
||||||
|
last_vacuum,
|
||||||
|
last_autovacuum,
|
||||||
|
last_analyze,
|
||||||
|
last_autoanalyze
|
||||||
|
FROM pg_stat_user_tables
|
||||||
|
WHERE relname IN (
|
||||||
|
'runs',
|
||||||
|
'threads_meta',
|
||||||
|
'checkpoints',
|
||||||
|
'checkpoint_blobs',
|
||||||
|
'checkpoint_writes'
|
||||||
|
)
|
||||||
|
ORDER BY relname;
|
||||||
|
```
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
schemaname,
|
||||||
|
relname,
|
||||||
|
pg_size_pretty(
|
||||||
|
pg_total_relation_size(
|
||||||
|
format('%I.%I', schemaname, relname)::regclass
|
||||||
|
)
|
||||||
|
) AS total_size
|
||||||
|
FROM pg_stat_user_tables
|
||||||
|
WHERE relname IN (
|
||||||
|
'runs',
|
||||||
|
'threads_meta',
|
||||||
|
'checkpoints',
|
||||||
|
'checkpoint_blobs',
|
||||||
|
'checkpoint_writes'
|
||||||
|
)
|
||||||
|
ORDER BY pg_total_relation_size(
|
||||||
|
format('%I.%I', schemaname, relname)::regclass
|
||||||
|
) DESC;
|
||||||
|
```
|
||||||
|
|
||||||
|
统计值是估算值,足以用于判断规模和维护异常;不必先执行昂贵的全表 `count(*)`。
|
||||||
|
|
||||||
|
### 8.3 故障 thread 的 checkpoint 分布
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
checkpoint_ns,
|
||||||
|
count(*) AS checkpoint_rows,
|
||||||
|
min(checkpoint_id) AS oldest_checkpoint_id,
|
||||||
|
max(checkpoint_id) AS newest_checkpoint_id
|
||||||
|
FROM checkpoints
|
||||||
|
WHERE thread_id = '<THREAD_ID>'
|
||||||
|
GROUP BY checkpoint_ns
|
||||||
|
ORDER BY checkpoint_rows DESC;
|
||||||
|
```
|
||||||
|
|
||||||
|
如果单个 thread 有大量 checkpoint 或多个 namespace,当前 `/history` 的跨 namespace 排序更值得关注。
|
||||||
|
|
||||||
|
### 8.4 对比 History 与主 namespace 的执行计划
|
||||||
|
|
||||||
|
只对一个已知慢 thread 在低峰执行:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS, SETTINGS)
|
||||||
|
SELECT checkpoint_id, checkpoint_ns
|
||||||
|
FROM checkpoints
|
||||||
|
WHERE thread_id = '<THREAD_ID>'
|
||||||
|
ORDER BY checkpoint_id DESC
|
||||||
|
LIMIT 1;
|
||||||
|
```
|
||||||
|
|
||||||
|
对比限定主 namespace:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS, SETTINGS)
|
||||||
|
SELECT checkpoint_id, checkpoint_ns
|
||||||
|
FROM checkpoints
|
||||||
|
WHERE thread_id = '<THREAD_ID>'
|
||||||
|
AND checkpoint_ns = ''
|
||||||
|
ORDER BY checkpoint_id DESC
|
||||||
|
LIMIT 1;
|
||||||
|
```
|
||||||
|
|
||||||
|
重点看:
|
||||||
|
|
||||||
|
- 第一条是否出现 `Sort` / `top-N heapsort`;
|
||||||
|
- `Rows Removed by Filter`;
|
||||||
|
- 实际扫描行数;
|
||||||
|
- shared buffer read/hit;
|
||||||
|
- 第二条是否使用 `checkpoints_pkey` 的 backward index scan;
|
||||||
|
- 两条的实际耗时差异。
|
||||||
|
|
||||||
|
`EXPLAIN ANALYZE` 会真实执行 SELECT。这里的 SELECT 是只读的,但仍应对一个明确 thread 在低峰执行,不要直接对完整大型历史查询做无界分析。
|
||||||
|
|
||||||
|
### 8.5 验证 runs 的关键查询
|
||||||
|
|
||||||
|
按 run id:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS)
|
||||||
|
SELECT run_id, status
|
||||||
|
FROM runs
|
||||||
|
WHERE run_id = '<RUN_ID>';
|
||||||
|
```
|
||||||
|
|
||||||
|
预期使用 `runs_pkey`。
|
||||||
|
|
||||||
|
按 thread 列表:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS)
|
||||||
|
SELECT run_id, status, created_at
|
||||||
|
FROM runs
|
||||||
|
WHERE thread_id = '<THREAD_ID>'
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT 100;
|
||||||
|
```
|
||||||
|
|
||||||
|
预期使用 `(thread_id, created_at)` 组合索引,例如 ORM 当前声明的 `ix_runs_thread_created`。如果生产库没有该索引,先核对部署 migration/自动补列逻辑,再决定是否补建;不要建立重复索引。
|
||||||
|
|
||||||
|
### 8.6 卡顿正在发生时查看 PostgreSQL 活动
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
pid,
|
||||||
|
application_name,
|
||||||
|
usename,
|
||||||
|
state,
|
||||||
|
wait_event_type,
|
||||||
|
wait_event,
|
||||||
|
xact_start,
|
||||||
|
query_start,
|
||||||
|
now() - query_start AS query_age,
|
||||||
|
pg_blocking_pids(pid) AS blocking_pids,
|
||||||
|
left(query, 500) AS query
|
||||||
|
FROM pg_stat_activity
|
||||||
|
WHERE datname = current_database()
|
||||||
|
AND pid <> pg_backend_pid()
|
||||||
|
AND (state <> 'idle' OR wait_event IS NOT NULL)
|
||||||
|
ORDER BY query_start;
|
||||||
|
```
|
||||||
|
|
||||||
|
阻塞关系:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
blocked.pid AS blocked_pid,
|
||||||
|
now() - blocked.query_start AS blocked_for,
|
||||||
|
blocked.wait_event_type,
|
||||||
|
blocked.wait_event,
|
||||||
|
left(blocked.query, 300) AS blocked_query,
|
||||||
|
blocker.pid AS blocker_pid,
|
||||||
|
blocker.state AS blocker_state,
|
||||||
|
now() - blocker.xact_start AS blocker_xact_age,
|
||||||
|
left(blocker.query, 300) AS blocker_query
|
||||||
|
FROM pg_stat_activity AS blocked
|
||||||
|
JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid) ON true
|
||||||
|
JOIN pg_stat_activity AS blocker ON blocker.pid = b.pid
|
||||||
|
ORDER BY blocked.query_start;
|
||||||
|
```
|
||||||
|
|
||||||
|
注意:如果请求在 Python saver lock 上等待,它还没有 checkout PostgreSQL 连接,因此 PostgreSQL 里可能看不到对应 blocked session。
|
||||||
|
|
||||||
|
### 8.7 如果启用了 `pg_stat_statements`
|
||||||
|
|
||||||
|
先确认扩展:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT extname, extversion
|
||||||
|
FROM pg_extension
|
||||||
|
WHERE extname = 'pg_stat_statements';
|
||||||
|
```
|
||||||
|
|
||||||
|
checkpoint 查询:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
calls,
|
||||||
|
round(mean_exec_time::numeric, 2) AS mean_ms,
|
||||||
|
round(max_exec_time::numeric, 2) AS max_ms,
|
||||||
|
rows,
|
||||||
|
shared_blks_hit,
|
||||||
|
shared_blks_read,
|
||||||
|
temp_blks_written,
|
||||||
|
left(query, 700) AS query
|
||||||
|
FROM pg_stat_statements
|
||||||
|
WHERE dbid = (
|
||||||
|
SELECT oid
|
||||||
|
FROM pg_database
|
||||||
|
WHERE datname = current_database()
|
||||||
|
)
|
||||||
|
AND query ILIKE '%checkpoints%'
|
||||||
|
ORDER BY max_exec_time DESC
|
||||||
|
LIMIT 30;
|
||||||
|
```
|
||||||
|
|
||||||
|
runs 查询:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
calls,
|
||||||
|
round(mean_exec_time::numeric, 2) AS mean_ms,
|
||||||
|
round(max_exec_time::numeric, 2) AS max_ms,
|
||||||
|
rows,
|
||||||
|
shared_blks_hit,
|
||||||
|
shared_blks_read,
|
||||||
|
temp_blks_written,
|
||||||
|
left(query, 700) AS query
|
||||||
|
FROM pg_stat_statements
|
||||||
|
WHERE dbid = (
|
||||||
|
SELECT oid
|
||||||
|
FROM pg_database
|
||||||
|
WHERE datname = current_database()
|
||||||
|
)
|
||||||
|
AND query ILIKE '%runs%'
|
||||||
|
ORDER BY max_exec_time DESC
|
||||||
|
LIMIT 30;
|
||||||
|
```
|
||||||
|
|
||||||
|
## 9. 证据如何判定
|
||||||
|
|
||||||
|
| 现场证据 | 结论/下一步 |
|
||||||
|
| --- | --- |
|
||||||
|
| `/threads` 的 `checkpoint_create` 接近 6 秒 | 优先排查 saver 锁排队或 checkpoint PG 写入 |
|
||||||
|
| `checkpoint_create` 很慢,但 `pg_stat_activity` 没有相应慢 SQL/锁 | 强烈支持请求仍在进程内 saver lock 上排队 |
|
||||||
|
| History EXPLAIN 出现大量候选扫描 + Sort | 为 `(thread_id, checkpoint_id DESC)` 建候选索引,或让接口限定 `checkpoint_ns=''` |
|
||||||
|
| History SQL 自身毫秒级,但接口仍数秒 | 重点查 saver lock wait、反序列化、消息序列化和事件循环阻塞 |
|
||||||
|
| 最后正文已到但 SSE 未结束,日志出现 `terminal_checkpoint` | run 收尾在 checkpoint 读取处等待 |
|
||||||
|
| 日志出现 `terminal_status` | `runs` 终态 UPDATE/COMMIT、业务 PG 连接或锁等待 |
|
||||||
|
| 日志出现 `metadata_cleanup` | journal、completion、标题或 thread 元数据收尾超时 |
|
||||||
|
| SSE 已结束,只有 `/history` pending | SDK 结束后 history 刷新卡住,不是模型还在生成 |
|
||||||
|
| `/history` 已 200,页面仍 loading | 再查前端构建版本、状态恢复和渲染逻辑 |
|
||||||
|
| `runs_pkey` 命中,dead tuples 低,无 DB wait | 5 万 runs 不是该故障的主要原因 |
|
||||||
|
| `runs` dead tuples 高、autovacuum 长期不工作 | 可能拖慢 UPDATE/COMMIT,但仍不能解释 `/history` 路径 |
|
||||||
|
| PG 出现 `wait_event_type='Lock'` 和 blocking pid | 已确认数据库锁等待,先处理 blocker |
|
||||||
|
| PG 出现明显 I/O wait 或大量 shared reads | 检查存储、缓存命中、膨胀及查询计划 |
|
||||||
|
| checkpoint migration 或必要索引缺失/invalid | 修复 schema/setup,再评估应用层锁 |
|
||||||
|
|
||||||
|
## 10. 不建议直接做的操作
|
||||||
|
|
||||||
|
- 不要因为有 5 万条 runs 就直接删除 runs。
|
||||||
|
- 不要在生产直接执行 `VACUUM FULL`,它会对表获取强锁。
|
||||||
|
- 不要先增加大量重复索引;每个索引都会增加 checkpoint 写放大。
|
||||||
|
- 不要只增大 `DEER_FLOW_PG_POOL_MAX`;单 saver 的实例锁仍会串行。
|
||||||
|
- 不要通过增加 Gateway worker 临时绕过;当前 run registry 与 SSE bridge 是进程内状态。
|
||||||
|
- 不要在未确认 history namespace 语义前直接把所有查询改成 `checkpoint_ns=''`。
|
||||||
|
- 不要把 checkpoint 归档作为本次 6 秒问题的第一步;归档涉及停写、备份、恢复演练,并不能消除 saver 实例锁。
|
||||||
|
|
||||||
|
## 11. 单次事故记录模板
|
||||||
|
|
||||||
|
```text
|
||||||
|
部署 commit:
|
||||||
|
前端构建版本:
|
||||||
|
Gateway worker:
|
||||||
|
database backend/host/db:
|
||||||
|
checkpointer backend/host/db:
|
||||||
|
发生时间:
|
||||||
|
thread_id:
|
||||||
|
run_id:
|
||||||
|
|
||||||
|
POST /threads:
|
||||||
|
- 浏览器总耗时:
|
||||||
|
- Server-Timing:
|
||||||
|
- HTTP 状态:
|
||||||
|
|
||||||
|
runs/stream:
|
||||||
|
- 开始时间:
|
||||||
|
- 最后正文时间:
|
||||||
|
- SSE end 时间:
|
||||||
|
- 是否收到 end:
|
||||||
|
|
||||||
|
history:
|
||||||
|
- 开始时间:
|
||||||
|
- TTFB:
|
||||||
|
- 完成/取消时间:
|
||||||
|
- HTTP 状态:
|
||||||
|
- 响应大小:
|
||||||
|
|
||||||
|
Gateway 日志:
|
||||||
|
- GATEWAY_OPERATION_TIMING:
|
||||||
|
- start-run-timing:
|
||||||
|
- RUN_COMPLETION_TIMEOUT:
|
||||||
|
- pool/DB 异常:
|
||||||
|
|
||||||
|
PostgreSQL:
|
||||||
|
- activity/wait_event:
|
||||||
|
- blocking_pids:
|
||||||
|
- checkpoint migration:
|
||||||
|
- 索引缺失/invalid:
|
||||||
|
- live/dead tuples:
|
||||||
|
- History EXPLAIN:
|
||||||
|
|
||||||
|
初步判定:
|
||||||
|
已经排除:
|
||||||
|
尚缺证据:
|
||||||
|
下一步:
|
||||||
|
```
|
||||||
|
|
||||||
|
## 12. 关键代码位置
|
||||||
|
|
||||||
|
| 位置 | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| `offline-backend-20260512/backend/app/gateway/routers/threads.py:853-927` | 创建 thread、分阶段计时、同步写初始 checkpoint |
|
||||||
|
| `offline-backend-20260512/backend/app/gateway/routers/threads.py:1873-1944` | History config、alist 和消息序列化 |
|
||||||
|
| `offline-backend-20260512/backend/app/gateway/operation_timing.py:14-60` | `Server-Timing` 和 `GATEWAY_OPERATION_TIMING` |
|
||||||
|
| `offline-backend-20260512/backend/app/gateway/routers/thread_runs.py:98-133` | run 创建与 SSE 路由 |
|
||||||
|
| `offline-backend-20260512/backend/app/gateway/services.py:1374-1976` | `start_run` 和 `[start-run-timing]` |
|
||||||
|
| `offline-backend-20260512/backend/packages/harness/deerflow/persistence/run/sql.py:66-206` | runs INSERT/UPDATE |
|
||||||
|
| `offline-backend-20260512/backend/packages/harness/deerflow/persistence/run/model.py:14-56` | runs 主键和 ORM 索引声明 |
|
||||||
|
| `offline-backend-20260512/backend/packages/harness/deerflow/runtime/runs/manager.py:211-324` | `_runs` 扫描与未被调用的 cleanup |
|
||||||
|
| `offline-backend-20260512/backend/packages/harness/deerflow/runtime/runs/worker.py:479-501` | run 收尾后仅清理 stream bridge |
|
||||||
|
| `offline-backend-20260512/backend/packages/harness/deerflow/runtime/checkpointer/async_provider.py:93-123` | PG pool 与单 saver |
|
||||||
|
| `.venv/Lib/site-packages/langgraph/checkpoint/postgres/base.py:43-150` | checkpoint schema、索引和 SQL |
|
||||||
|
| `.venv/Lib/site-packages/langgraph/checkpoint/postgres/aio.py:119-179` | alist 查询、fetchall 与持锁 yield |
|
||||||
|
| `.venv/Lib/site-packages/langgraph/checkpoint/postgres/aio.py:363-403` | saver 实例锁先于 pool checkout |
|
||||||
|
| `frontend-web/src/core/threads/hooks.ts:702-711` | `fetchStateHistory: { limit: 1 }` |
|
||||||
|
| `frontend-web/src/core/threads/hooks.ts:976-1038` | onFinish 依赖最终 state |
|
||||||
|
| `frontend-web/src/core/api/api-client.ts:96-101` | 控制/history 请求 30 秒超时 |
|
||||||
|
|
||||||
|
## 13. 推荐排查顺序
|
||||||
|
|
||||||
|
按下面顺序执行,通常一次复现就能缩小范围:
|
||||||
|
|
||||||
|
1. 浏览器保存 `/threads`、`runs/stream`、`history` 时间线。
|
||||||
|
2. 查看 `/threads` 的 `Server-Timing`。
|
||||||
|
3. 用同一 `thread_id/run_id` 对齐 Gateway 日志。
|
||||||
|
4. 卡顿发生时立即保存 `pg_stat_activity` 和 blocker 快照。
|
||||||
|
5. 查询实际索引与表统计,不依赖代码声明猜测生产 schema。
|
||||||
|
6. 对慢 thread 比较两条 History EXPLAIN。
|
||||||
|
7. 只有证据显示查询计划问题时才加索引;只有 SQL 已很快而接口仍等待时,才优先改 saver/应用锁路径。
|
||||||
@@ -0,0 +1,831 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>数据广场 DataFeed · 仿 Facebook 风格数据展示</title>
|
||||||
|
<style>
|
||||||
|
:root{
|
||||||
|
--fb-blue:#1877f2; --fb-blue-dark:#166fe5; --bg:#f0f2f5;
|
||||||
|
--card:#fff; --text:#1c1e21; --sub:#65676b; --weak:#8a8d91;
|
||||||
|
--divider:#e4e6eb; --hover:#f0f2f5; --hover2:#e4e6eb;
|
||||||
|
--green:#31a24c; --red:#e41e3f; --yellow:#f7b928;
|
||||||
|
--shadow:0 1px 2px rgba(0,0,0,.2);
|
||||||
|
}
|
||||||
|
*{box-sizing:border-box;margin:0;padding:0}
|
||||||
|
html{scrollbar-gutter:stable}
|
||||||
|
body{
|
||||||
|
background:var(--bg);color:var(--text);
|
||||||
|
font-family:"Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",Helvetica,Arial,sans-serif;
|
||||||
|
font-size:15px;-webkit-font-smoothing:antialiased;
|
||||||
|
}
|
||||||
|
a{color:inherit;text-decoration:none}
|
||||||
|
button{font-family:inherit}
|
||||||
|
|
||||||
|
/* ============ 顶部导航(Facebook 蓝条) ============ */
|
||||||
|
.topbar{
|
||||||
|
position:fixed;top:0;left:0;right:0;height:56px;z-index:100;
|
||||||
|
background:var(--fb-blue);display:flex;align-items:center;justify-content:space-between;
|
||||||
|
padding:0 16px;gap:8px;
|
||||||
|
}
|
||||||
|
.tb-left{display:flex;align-items:center;gap:10px;flex:1;min-width:0}
|
||||||
|
.logo{
|
||||||
|
width:40px;height:40px;border-radius:50%;flex:none;
|
||||||
|
background:#fff;color:var(--fb-blue);font-size:22px;font-weight:800;
|
||||||
|
display:grid;place-items:center;cursor:pointer;
|
||||||
|
}
|
||||||
|
.search{position:relative}
|
||||||
|
.search svg{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--sub);pointer-events:none}
|
||||||
|
.search input{
|
||||||
|
width:250px;max-width:44vw;height:40px;border:none;border-radius:20px;outline:none;
|
||||||
|
background:rgba(255,255,255,.96);padding:0 14px 0 38px;font-size:15px;color:var(--text);
|
||||||
|
}
|
||||||
|
.search input::placeholder{color:var(--weak)}
|
||||||
|
.tb-center{display:flex;gap:4px;flex:none}
|
||||||
|
.tb-nav{
|
||||||
|
width:48px;height:48px;border-radius:10px;display:grid;place-items:center;
|
||||||
|
color:#dfe9fb;position:relative;cursor:pointer;
|
||||||
|
}
|
||||||
|
.tb-nav svg{width:26px;height:26px}
|
||||||
|
.tb-nav:hover,.tb-nav.active{background:rgba(255,255,255,.18);color:#fff}
|
||||||
|
.tb-right{display:flex;align-items:center;gap:8px;flex:1;justify-content:flex-end}
|
||||||
|
.icon-btn{
|
||||||
|
width:40px;height:40px;border-radius:50%;position:relative;flex:none;
|
||||||
|
background:rgba(255,255,255,.18);display:grid;place-items:center;color:#fff;cursor:pointer;
|
||||||
|
}
|
||||||
|
.icon-btn:hover{background:rgba(255,255,255,.28)}
|
||||||
|
.icon-btn svg{width:22px;height:22px}
|
||||||
|
.badge{
|
||||||
|
position:absolute;top:-3px;right:-3px;min-width:18px;height:18px;padding:0 4px;
|
||||||
|
border-radius:9px;background:var(--red);color:#fff;font-size:11px;font-weight:700;
|
||||||
|
display:grid;place-items:center;border:2px solid var(--fb-blue);
|
||||||
|
}
|
||||||
|
.me{
|
||||||
|
width:40px;height:40px;border-radius:50%;border:none;flex:none;cursor:pointer;
|
||||||
|
background:linear-gradient(135deg,#42a5f5,#0d47a1);color:#fff;font-weight:600;font-size:15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============ 三栏布局 ============ */
|
||||||
|
.layout{
|
||||||
|
max-width:1284px;margin:0 auto;display:grid;gap:16px;
|
||||||
|
grid-template-columns:280px minmax(0,680px) 300px;
|
||||||
|
padding:72px 12px 40px;align-items:start;
|
||||||
|
}
|
||||||
|
.side{position:sticky;top:72px;max-height:calc(100vh - 88px);overflow-y:auto;padding:4px 2px}
|
||||||
|
.side::-webkit-scrollbar{width:8px}
|
||||||
|
.side::-webkit-scrollbar-thumb{background:#cfd2d6;border-radius:4px}
|
||||||
|
.side::-webkit-scrollbar-thumb:hover{background:#b6b9be}
|
||||||
|
|
||||||
|
/* ---- 左栏 ---- */
|
||||||
|
.profile-row{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;cursor:pointer}
|
||||||
|
.profile-row:hover{background:var(--hover)}
|
||||||
|
.profile-row b{font-size:15px}
|
||||||
|
.profile-row .sub{font-size:12.5px;color:var(--sub)}
|
||||||
|
.menu{margin-top:4px}
|
||||||
|
.mi{
|
||||||
|
display:flex;align-items:center;gap:12px;padding:7px 10px;border-radius:8px;
|
||||||
|
font-weight:600;font-size:15px;cursor:pointer;user-select:none;
|
||||||
|
}
|
||||||
|
.mi:hover{background:var(--hover)}
|
||||||
|
.mi .ic{width:36px;height:36px;border-radius:50%;display:grid;place-items:center;color:var(--fb-blue);flex:none}
|
||||||
|
.mi .ic svg{width:22px;height:22px}
|
||||||
|
.mi .cnt{
|
||||||
|
margin-left:auto;background:#d8dadf;color:var(--text);font-size:12px;font-weight:700;
|
||||||
|
border-radius:10px;padding:1px 8px;
|
||||||
|
}
|
||||||
|
.sq{width:36px;height:36px;border-radius:10px;display:grid;place-items:center;font-size:18px;flex:none}
|
||||||
|
.sq-blue{background:#e7f3ff}.sq-green{background:#e6f7ea}.sq-orange{background:#fff3d6}.sq-purple{background:#f0e9ff}
|
||||||
|
.hr{border:none;border-top:1px solid var(--divider);margin:10px 12px}
|
||||||
|
.side-title{font-weight:700;color:var(--weak);font-size:17px;padding:6px 12px 2px}
|
||||||
|
.side-foot{font-size:12px;color:var(--weak);padding:12px 12px 4px;line-height:1.7}
|
||||||
|
|
||||||
|
/* ---- 通用卡片 / 头像 ---- */
|
||||||
|
.card{background:var(--card);border-radius:8px;box-shadow:var(--shadow)}
|
||||||
|
.avatar{
|
||||||
|
width:40px;height:40px;border-radius:50%;display:grid;place-items:center;
|
||||||
|
color:#fff;font-weight:600;font-size:15px;flex:none;cursor:pointer;
|
||||||
|
}
|
||||||
|
.avatar.sm{width:32px;height:32px;font-size:13px}
|
||||||
|
.av-blue{background:linear-gradient(135deg,#1877f2,#0c56c0)}
|
||||||
|
.av-green{background:linear-gradient(135deg,#45bd62,#1a7a3a)}
|
||||||
|
.av-orange{background:linear-gradient(135deg,#f7a325,#d97b06)}
|
||||||
|
.av-purple{background:linear-gradient(135deg,#8b5cf6,#5b21b6)}
|
||||||
|
.av-teal{background:linear-gradient(135deg,#14b8a6,#0f766e)}
|
||||||
|
.sub{color:var(--sub)}
|
||||||
|
|
||||||
|
/* ---- 发布器 ---- */
|
||||||
|
.composer{padding:12px 16px 10px;margin-bottom:16px}
|
||||||
|
.composer-top{display:flex;gap:10px;align-items:center}
|
||||||
|
.composer-top input{
|
||||||
|
flex:1;height:42px;border-radius:21px;border:none;outline:none;
|
||||||
|
background:var(--hover);padding:0 16px;font-size:15px;color:var(--text);transition:box-shadow .15s,background .15s;
|
||||||
|
}
|
||||||
|
.composer-top input:focus{background:#fff;box-shadow:inset 0 0 0 2px var(--fb-blue)}
|
||||||
|
.composer-actions{display:flex;border-top:1px solid var(--divider);margin-top:10px;padding-top:6px}
|
||||||
|
.ca{
|
||||||
|
flex:1;display:flex;align-items:center;justify-content:center;gap:8px;
|
||||||
|
padding:9px 4px;border-radius:8px;font-weight:600;font-size:14.5px;color:var(--sub);
|
||||||
|
cursor:pointer;user-select:none;background:none;border:none;
|
||||||
|
}
|
||||||
|
.ca:hover{background:var(--hover)}
|
||||||
|
.ca svg{width:22px;height:22px}
|
||||||
|
.ca.c-blue{color:var(--fb-blue)}.ca.c-green{color:var(--green)}.ca.c-orange{color:#f0940a}
|
||||||
|
|
||||||
|
/* ---- 数据专题(Stories) ---- */
|
||||||
|
.stories{display:flex;gap:8px;overflow-x:auto;padding:12px;margin-bottom:16px;scrollbar-width:none}
|
||||||
|
.stories::-webkit-scrollbar{display:none}
|
||||||
|
.story{
|
||||||
|
flex:0 0 110px;height:190px;border-radius:14px;position:relative;overflow:hidden;
|
||||||
|
cursor:pointer;color:#fff;display:flex;flex-direction:column;justify-content:flex-end;
|
||||||
|
padding:10px;transition:transform .15s;
|
||||||
|
}
|
||||||
|
.story:hover{transform:scale(1.02)}
|
||||||
|
.story .big{position:absolute;top:44px;left:0;right:0;text-align:center;font-size:40px}
|
||||||
|
.story .av{position:absolute;top:8px;left:8px;width:30px;height:30px;border-radius:50%;border:2px solid rgba(255,255,255,.9)}
|
||||||
|
.story .nm{font-size:12.5px;font-weight:700;text-shadow:0 1px 3px rgba(0,0,0,.45);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||||
|
.story.create{background:#fff;align-items:center;justify-content:flex-start;color:var(--text);padding-top:14px}
|
||||||
|
.story.create:hover{background:var(--hover)}
|
||||||
|
.story.create .plus{
|
||||||
|
width:44px;height:44px;border-radius:50%;background:var(--fb-blue);color:#fff;
|
||||||
|
display:grid;place-items:center;font-size:26px;font-weight:300;margin-bottom:8px;
|
||||||
|
}
|
||||||
|
.story.create span{font-size:13px;font-weight:600}
|
||||||
|
|
||||||
|
/* ---- 帖子(数据卡片) ---- */
|
||||||
|
.post{margin-bottom:16px}
|
||||||
|
.post-hd{display:flex;align-items:center;gap:10px;padding:12px 16px 0}
|
||||||
|
.post-hd .meta{min-width:0;flex:1}
|
||||||
|
.post-hd .meta b{font-size:15px;cursor:pointer}
|
||||||
|
.post-hd .meta b:hover{text-decoration:underline}
|
||||||
|
.post-hd .meta .sub{font-size:13px;display:flex;align-items:center;gap:4px}
|
||||||
|
.post-hd .more{color:var(--sub);cursor:pointer;padding:4px 8px;border-radius:50%;font-weight:700}
|
||||||
|
.post-hd .more:hover{background:var(--hover)}
|
||||||
|
.post-txt{padding:10px 16px 12px;line-height:1.55;font-size:15px}
|
||||||
|
.post-txt a{color:var(--fb-blue);font-weight:600}
|
||||||
|
.chart-wrap{padding:0 16px}
|
||||||
|
.chart-head{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;padding:0 16px 6px}
|
||||||
|
.chart-title{font-size:15px;font-weight:700}
|
||||||
|
.legend{display:flex;gap:14px;font-size:13px;color:var(--sub);align-items:center;flex-wrap:wrap}
|
||||||
|
.dot{width:10px;height:10px;border-radius:3px;display:inline-block;margin-right:5px;vertical-align:-1px}
|
||||||
|
.pills{display:flex;gap:6px}
|
||||||
|
.pill{
|
||||||
|
border:none;cursor:pointer;padding:4px 14px;border-radius:20px;
|
||||||
|
background:var(--hover);color:var(--sub);font-size:13px;font-weight:600;
|
||||||
|
}
|
||||||
|
.pill.active{background:#e7f3ff;color:var(--fb-blue)}
|
||||||
|
.summary{font-size:13px;color:var(--sub);padding:6px 16px 4px}
|
||||||
|
|
||||||
|
/* KPI 四宫格 */
|
||||||
|
.kpis{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;padding:2px 16px 14px}
|
||||||
|
.kpi{background:#f7f8fa;border:1px solid var(--divider);border-radius:10px;padding:10px 12px}
|
||||||
|
.kpi .lab{font-size:12.5px;color:var(--sub);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||||
|
.kpi .num{font-size:20px;font-weight:800;letter-spacing:-.3px;margin:3px 0 2px;white-space:nowrap}
|
||||||
|
.delta{font-size:12px;font-weight:700;display:inline-flex;align-items:center;gap:2px}
|
||||||
|
.up{color:var(--green)}.down{color:var(--red)}
|
||||||
|
.spark{width:100%;height:26px;display:block;margin-top:4px}
|
||||||
|
|
||||||
|
/* 柱状图 */
|
||||||
|
.bars{display:flex;align-items:flex-end;gap:14px;height:175px;padding:0 6px;margin-top:4px}
|
||||||
|
.bcol{flex:1;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:6px}
|
||||||
|
.bval{font-size:12px;font-weight:700;color:var(--sub)}
|
||||||
|
.bar{
|
||||||
|
width:100%;max-width:44px;border-radius:6px 6px 2px 2px;cursor:pointer;
|
||||||
|
background:linear-gradient(180deg,#4b95f5,#1877f2);transition:filter .15s;
|
||||||
|
}
|
||||||
|
.bar:hover{filter:brightness(1.12)}
|
||||||
|
.bar.top{background:linear-gradient(180deg,#1877f2,#0a4bb3)}
|
||||||
|
.bname{font-size:12px;color:var(--sub);white-space:nowrap}
|
||||||
|
|
||||||
|
/* 环形图 + 图例 */
|
||||||
|
.split{display:grid;grid-template-columns:210px 1fr;gap:8px;align-items:center;padding:2px 16px 14px}
|
||||||
|
.donut{width:180px;height:180px;margin:0 auto;display:block}
|
||||||
|
.lg-row{display:flex;align-items:center;gap:10px;padding:7px 0;font-size:14px;border-bottom:1px dashed #f0f2f5}
|
||||||
|
.lg-row:last-child{border-bottom:none}
|
||||||
|
.lg-row .nm{flex:1}
|
||||||
|
.lg-row .v{font-weight:700}
|
||||||
|
.lg-row .pc{color:var(--sub);font-size:13px;width:44px;text-align:right}
|
||||||
|
|
||||||
|
/* 表格 */
|
||||||
|
.tbl-wrap{overflow-x:auto}
|
||||||
|
.tbl{width:100%;border-collapse:collapse;font-size:14px;min-width:440px}
|
||||||
|
.tbl th{
|
||||||
|
text-align:left;font-size:13px;font-weight:600;color:var(--sub);
|
||||||
|
padding:8px 16px;border-bottom:1px solid var(--divider);white-space:nowrap;
|
||||||
|
}
|
||||||
|
.tbl td{padding:10px 16px;border-bottom:1px solid #f0f2f5;white-space:nowrap}
|
||||||
|
.tbl tr:last-child td{border-bottom:none}
|
||||||
|
.tbl tbody tr:hover{background:#f7f9fc}
|
||||||
|
.rank{width:22px;height:22px;border-radius:6px;display:grid;place-items:center;font-size:12px;font-weight:800;color:#fff}
|
||||||
|
.r1{background:#f7b928}.r2{background:#aeb3ba}.r3{background:#d08a4e}.rx{background:#e4e6eb;color:var(--sub)}
|
||||||
|
|
||||||
|
/* 互动条 */
|
||||||
|
.post-stats{display:flex;align-items:center;justify-content:space-between;padding:10px 16px 6px;color:var(--sub);font-size:14.5px}
|
||||||
|
.react{
|
||||||
|
width:20px;height:20px;border-radius:50%;background:#fff;box-shadow:0 0 0 1px var(--divider);
|
||||||
|
display:inline-grid;place-items:center;font-size:12px;margin-right:5px;vertical-align:-4px;
|
||||||
|
}
|
||||||
|
.actions{display:flex;border-top:1px solid var(--divider);padding:4px 6px}
|
||||||
|
.act{
|
||||||
|
flex:1;display:flex;align-items:center;justify-content:center;gap:8px;
|
||||||
|
padding:9px 4px;border-radius:8px;color:var(--sub);font-weight:600;font-size:14.5px;
|
||||||
|
cursor:pointer;user-select:none;background:none;border:none;
|
||||||
|
}
|
||||||
|
.act:hover{background:var(--hover)}
|
||||||
|
.act svg{width:20px;height:20px}
|
||||||
|
.act.liked{color:var(--fb-blue)}
|
||||||
|
|
||||||
|
/* 评论 */
|
||||||
|
.comments{padding:2px 16px 14px}
|
||||||
|
.cmt-more{color:var(--sub);font-size:14px;font-weight:600;padding:4px 0 8px;cursor:pointer}
|
||||||
|
.cmt-more:hover{text-decoration:underline}
|
||||||
|
.cmt{display:flex;gap:8px;margin-bottom:10px}
|
||||||
|
.cmt-bubble{background:var(--hover);border-radius:18px;padding:8px 13px;font-size:14px;line-height:1.45;max-width:100%}
|
||||||
|
.cmt-name{font-weight:700;font-size:13px;display:block;margin-bottom:1px}
|
||||||
|
.cmt-meta{font-size:12.5px;color:var(--sub);padding:3px 13px 0;display:flex;gap:8px}
|
||||||
|
.cmt-meta a{cursor:pointer}
|
||||||
|
.cmt-meta a:hover{text-decoration:underline;color:var(--text)}
|
||||||
|
.cmt-input{display:flex;gap:8px;align-items:center;margin-top:4px}
|
||||||
|
.cmt-input input{
|
||||||
|
flex:1;height:38px;border-radius:19px;border:none;outline:none;background:var(--hover);
|
||||||
|
padding:0 14px;font-size:14px;
|
||||||
|
}
|
||||||
|
.cmt-input input:focus{background:#fff;box-shadow:inset 0 0 0 2px var(--fb-blue)}
|
||||||
|
|
||||||
|
/* ---- 右栏 ---- */
|
||||||
|
.rc{padding:14px 12px;margin-bottom:16px}
|
||||||
|
.rc h4{font-size:16.5px;font-weight:700;color:var(--weak);margin:0 4px 8px;letter-spacing:.2px}
|
||||||
|
.rc-item{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;cursor:pointer}
|
||||||
|
.rc-item:hover{background:var(--hover)}
|
||||||
|
.rc-item .tt{font-size:14px;font-weight:600;line-height:1.3}
|
||||||
|
.rc-item .dd{font-size:12.5px;color:var(--sub)}
|
||||||
|
.rc-thumb{
|
||||||
|
width:96px;height:66px;border-radius:8px;flex:none;display:grid;place-items:center;
|
||||||
|
font-size:26px;color:#fff;
|
||||||
|
}
|
||||||
|
.rc-status{width:9px;height:9px;border-radius:50%;flex:none}
|
||||||
|
.on{background:var(--green)}.off{background:#bcc0c4}.pulse{background:var(--green);animation:pu 1.4s infinite}
|
||||||
|
@keyframes pu{0%{box-shadow:0 0 0 0 rgba(49,162,76,.5)}70%{box-shadow:0 0 0 7px rgba(49,162,76,0)}100%{box-shadow:0 0 0 0 rgba(49,162,76,0)}}
|
||||||
|
.rc-row{display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:8px;cursor:pointer}
|
||||||
|
.rc-row:hover{background:var(--hover)}
|
||||||
|
.rc-row b{font-size:14.5px;font-weight:600}
|
||||||
|
.rc-row .sub{font-size:12.5px}
|
||||||
|
.rc-row .tail{margin-left:auto;font-size:12.5px;color:var(--sub);white-space:nowrap}
|
||||||
|
|
||||||
|
/* 空结果 / Toast */
|
||||||
|
.noresult{display:none;text-align:center;color:var(--sub);padding:40px 0;font-size:15px}
|
||||||
|
.toast{
|
||||||
|
position:fixed;left:50%;bottom:28px;transform:translateX(-50%) translateY(90px);
|
||||||
|
background:#1c1e21;color:#fff;padding:11px 22px;border-radius:10px;font-size:14px;
|
||||||
|
opacity:0;transition:all .25s;z-index:300;pointer-events:none;box-shadow:0 4px 14px rgba(0,0,0,.3);
|
||||||
|
}
|
||||||
|
.toast.show{transform:translateX(-50%);opacity:1}
|
||||||
|
|
||||||
|
/* ---- 响应式 ---- */
|
||||||
|
@media (max-width:1160px){
|
||||||
|
.layout{grid-template-columns:240px minmax(0,1fr)}
|
||||||
|
.side-r{display:none}
|
||||||
|
}
|
||||||
|
@media (max-width:920px){
|
||||||
|
.layout{grid-template-columns:minmax(0,1fr);padding-top:64px}
|
||||||
|
.side-l{display:none}
|
||||||
|
.tb-center{display:none}
|
||||||
|
}
|
||||||
|
@media (max-width:600px){
|
||||||
|
.kpis{grid-template-columns:repeat(2,1fr)}
|
||||||
|
.split{grid-template-columns:1fr}
|
||||||
|
.stories{padding:10px}
|
||||||
|
.composer-actions .ca span{display:none}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<!-- ================= 顶部导航 ================= -->
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="tb-left">
|
||||||
|
<a class="logo" title="DataFeed 数据广场">数</a>
|
||||||
|
<div class="search">
|
||||||
|
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><line x1="16.5" y1="16.5" x2="21" y2="21"/></svg>
|
||||||
|
<input id="globalSearch" type="text" placeholder="搜索数据、指标、报表…" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<nav class="tb-center">
|
||||||
|
<a class="tb-nav active" title="首页"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3.1 3 10.2V21h6.2v-6h5.6v6H21V10.2z"/></svg></a>
|
||||||
|
<a class="tb-nav" title="实时看板"><svg viewBox="0 0 24 24" fill="currentColor"><rect x="2.3" y="5" width="19.4" height="14" rx="4" fill="none" stroke="currentColor" stroke-width="2"/><path d="M10 9.1v5.8L15.4 12z"/></svg></a>
|
||||||
|
<a class="tb-nav" title="数据集市"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 4h3l2.5 11a1.6 1.6 0 0 0 1.6 1.3h8.2a1.6 1.6 0 0 0 1.6-1.3L21 8H6.2"/><circle cx="10" cy="20" r="1.5" fill="currentColor"/><circle cx="17.2" cy="20" r="1.5" fill="currentColor"/></svg></a>
|
||||||
|
<a class="tb-nav" title="数据小组"><svg viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="8.6" r="3.3"/><path d="M3 19.2c.5-3.1 3-4.9 6-4.9s5.5 1.8 6 4.9z"/><circle cx="16.9" cy="7.8" r="2.5"/><path d="M15.6 13.7c2.7.2 4.8 1.9 5.3 4.5h-4.4a7 7 0 0 0-.9-4.5z"/></svg></a>
|
||||||
|
</nav>
|
||||||
|
<div class="tb-right">
|
||||||
|
<a class="icon-btn" title="功能菜单"><svg viewBox="0 0 24 24" fill="currentColor"><circle cx="6" cy="6" r="1.9"/><circle cx="12" cy="6" r="1.9"/><circle cx="18" cy="6" r="1.9"/><circle cx="6" cy="12" r="1.9"/><circle cx="12" cy="12" r="1.9"/><circle cx="18" cy="12" r="1.9"/><circle cx="6" cy="18" r="1.9"/><circle cx="12" cy="18" r="1.9"/><circle cx="18" cy="18" r="1.9"/></svg></a>
|
||||||
|
<a class="icon-btn" title="消息"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.7 3 2.5 6.8 2.5 11.4c0 2.6 1.4 5 3.6 6.6L5.2 22l4.2-2.1c.8.2 1.7.3 2.6.3 5.3 0 9.5-3.8 9.5-8.5S17.3 3 12 3z"/></svg><span class="badge">3</span></a>
|
||||||
|
<a class="icon-btn" title="通知"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3a5.8 5.8 0 0 0-5.8 5.8v3.6L4.6 15a1 1 0 0 0 .9 1.5h13a1 1 0 0 0 .9-1.5l-1.6-2.6V8.8A5.8 5.8 0 0 0 12 3z"/><path d="M9.8 19a2.3 2.3 0 0 0 4.4 0z"/></svg><span class="badge">5</span></a>
|
||||||
|
<button class="me" title="张分析 · 数据分析师">张</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="layout">
|
||||||
|
|
||||||
|
<!-- ================= 左栏 ================= -->
|
||||||
|
<aside class="side side-l">
|
||||||
|
<div class="profile-row">
|
||||||
|
<div class="avatar av-blue">张</div>
|
||||||
|
<div><b>张分析</b><div class="sub">数据分析师 · 增长中心</div></div>
|
||||||
|
</div>
|
||||||
|
<nav class="menu">
|
||||||
|
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3.5" y="3.5" width="7.5" height="7.5" rx="2"/><rect x="13" y="3.5" width="7.5" height="7.5" rx="2"/><rect x="3.5" y="13" width="7.5" height="7.5" rx="2"/><rect x="13" y="13" width="7.5" height="7.5" rx="2"/></svg></span>数据概览</a>
|
||||||
|
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 13h3.2l2-5.2 3.5 9 2.2-7 1.5 3.2H21"/></svg></span>实时监控<span class="cnt">3</span></a>
|
||||||
|
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M6 2.5h8L19 8v13.5H6z"/><path d="M14 2.5V8h5M9 12.5h7M9 16h7"/></svg></span>报表中心</a>
|
||||||
|
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><ellipse cx="12" cy="5.5" rx="7.5" ry="3"/><path d="M4.5 5.5v13c0 1.7 3.4 3 7.5 3s7.5-1.3 7.5-3v-13"/><path d="M4.5 12c0 1.7 3.4 3 7.5 3s7.5-1.3 7.5-3"/></svg></span>数据源管理</a>
|
||||||
|
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.8l2.6 5.6 6.1.7-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.1l6.1-.7z"/></svg></span>我的收藏</a>
|
||||||
|
<a class="mi"><span class="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4.5 6.5h15M9.5 6V4.2A1.2 1.2 0 0 1 10.7 3h2.6a1.2 1.2 0 0 1 1.2 1.2V6"/><path d="M7 6.5l.8 13a1.5 1.5 0 0 0 1.5 1.4h5.4a1.5 1.5 0 0 0 1.5-1.4l.8-13"/></svg></span>回收站</a>
|
||||||
|
</nav>
|
||||||
|
<hr class="hr">
|
||||||
|
<div class="side-title">快捷方式</div>
|
||||||
|
<nav class="menu">
|
||||||
|
<a class="mi"><span class="sq sq-blue">🛒</span>电商大促</a>
|
||||||
|
<a class="mi"><span class="sq sq-green">📈</span>用户增长</a>
|
||||||
|
<a class="mi"><span class="sq sq-orange">📣</span>营销投放</a>
|
||||||
|
<a class="mi"><span class="sq sq-purple">🎧</span>客服质量</a>
|
||||||
|
</nav>
|
||||||
|
<hr class="hr">
|
||||||
|
<div class="side-title">我的小组</div>
|
||||||
|
<nav class="menu">
|
||||||
|
<a class="mi"><span class="sq sq-blue">👥</span>增长数据组</a>
|
||||||
|
<a class="mi"><span class="sq sq-green">🧪</span>实验平台组</a>
|
||||||
|
</nav>
|
||||||
|
<div class="side-foot">隐私 · 条款 · 广告 · Cookie<br>DataFeed © 2026 · 仿 Facebook 风格演示页</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<!-- ================= 中间信息流 ================= -->
|
||||||
|
<section class="feed">
|
||||||
|
|
||||||
|
<!-- 发布器(顶部搜索/筛选) -->
|
||||||
|
<div class="card composer">
|
||||||
|
<div class="composer-top">
|
||||||
|
<div class="avatar av-blue">张</div>
|
||||||
|
<input id="feedFilter" type="text" placeholder="筛选下方数据卡片,如:趋势 / 渠道 / 排行 / KPI…" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
<div class="composer-actions">
|
||||||
|
<button class="ca c-blue" data-toast="演示页面:实时看板未接入"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2.3" y="5" width="19.4" height="14" rx="4"/><path d="M10 9.1v5.8L15.4 12z" fill="currentColor" stroke="none"/></svg><span>实时看板</span></button>
|
||||||
|
<button class="ca c-green" data-toast="演示页面:导入报表未接入"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="6.5" width="18" height="13.5" rx="3"/><circle cx="12" cy="13" r="3.6"/><path d="M8 6.5 9.3 4h5.4L16 6.5"/></svg><span>导入报表</span></button>
|
||||||
|
<button class="ca c-orange" data-toast="演示页面:智能分析未接入"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="8.5"/><circle cx="9" cy="10" r="1.1" fill="currentColor" stroke="none"/><circle cx="15" cy="10" r="1.1" fill="currentColor" stroke="none"/><path d="M8.5 14.5c1 1.2 2.1 1.8 3.5 1.8s2.5-.6 3.5-1.8"/></svg><span>智能分析</span></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 数据专题(Stories) -->
|
||||||
|
<div class="card stories" id="stories">
|
||||||
|
<div class="story create"><div class="plus">+</div><span>创建专题</span></div>
|
||||||
|
<div class="story" style="background:linear-gradient(165deg,#166fe5,#0a3d91)"><span class="av avatar av-orange">促</span><div class="big">🛒</div><div class="nm">双 11 作战室</div></div>
|
||||||
|
<div class="story" style="background:linear-gradient(165deg,#f7b928,#dd7d0a)"><span class="av avatar av-blue">渠</span><div class="big">📣</div><div class="nm">渠道复盘</div></div>
|
||||||
|
<div class="story" style="background:linear-gradient(165deg,#45bd62,#177a37)"><span class="av avatar av-green">像</span><div class="big">👥</div><div class="nm">用户画像</div></div>
|
||||||
|
<div class="story" style="background:linear-gradient(165deg,#fa383e,#a80f26)"><span class="av avatar av-teal">留</span><div class="big">📈</div><div class="nm">留存专题</div></div>
|
||||||
|
<div class="story" style="background:linear-gradient(165deg,#8b5cf6,#4c1d95)"><span class="av avatar av-purple">实</span><div class="big">🧪</div><div class="nm">A/B 实验</div></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 卡片 1:今日核心指标 KPI -->
|
||||||
|
<article class="card post" data-key="kpi 核心指标 概览 活跃用户 注册 订单 gmv dashboard">
|
||||||
|
<div class="post-hd">
|
||||||
|
<div class="avatar av-blue">数</div>
|
||||||
|
<div class="meta">
|
||||||
|
<b>数据中心</b>
|
||||||
|
<div class="sub">12 分钟前 · <svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor"><path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm-1 5h2v6h-2zm0 8h2v2h-2z" opacity=".9"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm0 18.2c-4.5 0-8.2-3.7-8.2-8.2S7.5 3.8 12 3.8 20.2 7.5 20.2 12 16.5 20.2 12 20.2z"/></svg> 公开</div>
|
||||||
|
</div>
|
||||||
|
<span class="more">···</span>
|
||||||
|
</div>
|
||||||
|
<div class="post-txt">📊 <b>今日核心指标速览</b>(截至今日 16:00):活跃与 GMV 延续双位数增长,订单量小幅回落,详见 <a>#每日简报</a></div>
|
||||||
|
<div class="kpis">
|
||||||
|
<div class="kpi">
|
||||||
|
<div class="lab">今日活跃用户</div>
|
||||||
|
<div class="num">42.8 万</div>
|
||||||
|
<span class="delta up">▲ 12.5%</span>
|
||||||
|
<svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><polyline points="0,22 14,19 28,21 42,15 56,17 70,11 84,13 100,6" fill="none" stroke="#31a24c" stroke-width="2"/></svg>
|
||||||
|
</div>
|
||||||
|
<div class="kpi">
|
||||||
|
<div class="lab">新增注册</div>
|
||||||
|
<div class="num">8,642</div>
|
||||||
|
<span class="delta up">▲ 3.2%</span>
|
||||||
|
<svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><polyline points="0,20 14,21 28,16 42,17 56,14 70,15 84,9 100,7" fill="none" stroke="#31a24c" stroke-width="2"/></svg>
|
||||||
|
</div>
|
||||||
|
<div class="kpi">
|
||||||
|
<div class="lab">订单量</div>
|
||||||
|
<div class="num">15,237</div>
|
||||||
|
<span class="delta down">▼ 2.4%</span>
|
||||||
|
<svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><polyline points="0,8 14,12 28,10 42,15 56,14 70,18 84,17 100,21" fill="none" stroke="#e41e3f" stroke-width="2"/></svg>
|
||||||
|
</div>
|
||||||
|
<div class="kpi">
|
||||||
|
<div class="lab">GMV(成交总额)</div>
|
||||||
|
<div class="num">¥382.6 万</div>
|
||||||
|
<span class="delta up">▲ 8.1%</span>
|
||||||
|
<svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><polyline points="0,18 14,20 28,16 42,17 56,12 70,14 84,8 100,4" fill="none" stroke="#31a24c" stroke-width="2"/></svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="post-stats">
|
||||||
|
<div><span class="react">👍</span><span class="like-num" data-count="1286">1,286</span></div>
|
||||||
|
<div><span class="cmt-num" data-count="86">86 条评论</span> · <span>42 次分享</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
|
||||||
|
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
|
||||||
|
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
|
||||||
|
</div>
|
||||||
|
<div class="comments">
|
||||||
|
<div class="cmt-more">查看全部 <span class="cmt-total">86</span> 条评论</div>
|
||||||
|
<div class="cmt">
|
||||||
|
<div class="avatar av-orange sm">王</div>
|
||||||
|
<div>
|
||||||
|
<div class="cmt-bubble"><span class="cmt-name">运营小王</span>GMV 涨势不错,双 11 前继续冲 🚀</div>
|
||||||
|
<div class="cmt-meta"><a>赞</a><a>回复</a><span>42 分钟前</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="cmt">
|
||||||
|
<div class="avatar av-blue sm">数</div>
|
||||||
|
<div>
|
||||||
|
<div class="cmt-bubble"><span class="cmt-name">数据中心</span>回复<span style="color:var(--fb-blue);font-weight:600">@运营小王</span>:建议同步关注订单量下滑,可能是支付成功率波动</div>
|
||||||
|
<div class="cmt-meta"><a>赞</a><a>回复</a><span>35 分钟前</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="cmt-input">
|
||||||
|
<div class="avatar av-blue sm">张</div>
|
||||||
|
<input type="text" placeholder="撰写评论…(回车发送)">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<!-- 卡片 2:流量趋势折线图 -->
|
||||||
|
<article class="card post" data-key="趋势 流量 访问 折线 7天 30天 trend">
|
||||||
|
<div class="post-hd">
|
||||||
|
<div class="avatar av-green">增</div>
|
||||||
|
<div class="meta">
|
||||||
|
<b>增长分析组</b>
|
||||||
|
<div class="sub">1 小时前 · 内部可见</div>
|
||||||
|
</div>
|
||||||
|
<span class="more">···</span>
|
||||||
|
</div>
|
||||||
|
<div class="post-txt">📈 <b>平台访问量趋势</b>:今日访问创近期新高,较昨日同期 +22%,大促预热流量开始释放 <a>#流量监控</a></div>
|
||||||
|
<div class="chart-head">
|
||||||
|
<div class="legend">
|
||||||
|
<span><span class="dot" style="background:#1877f2"></span>今日</span>
|
||||||
|
<span><span class="dot" style="background:#b6bcc4"></span>昨日</span>
|
||||||
|
</div>
|
||||||
|
<div class="pills">
|
||||||
|
<button class="pill active" data-range="7">近 7 天</button>
|
||||||
|
<button class="pill" data-range="30">近 30 天</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="chart-wrap">
|
||||||
|
<svg id="trendSvg" viewBox="0 0 640 264" style="width:100%;height:auto;display:block"></svg>
|
||||||
|
</div>
|
||||||
|
<div class="summary" id="trendSummary">单位:万次访问</div>
|
||||||
|
<div class="post-stats">
|
||||||
|
<div><span class="react">👍</span><span class="like-num" data-count="642">642</span></div>
|
||||||
|
<div><span>38 条评论</span> · <span>17 次分享</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
|
||||||
|
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
|
||||||
|
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<!-- 卡片 3:渠道转化率柱状图 -->
|
||||||
|
<article class="card post" data-key="渠道 转化率 柱状 对比 营销 channel bar">
|
||||||
|
<div class="post-hd">
|
||||||
|
<div class="avatar av-orange">营</div>
|
||||||
|
<div class="meta">
|
||||||
|
<b>营销实验室</b>
|
||||||
|
<div class="sub">3 小时前 · 公开</div>
|
||||||
|
</div>
|
||||||
|
<span class="more">···</span>
|
||||||
|
</div>
|
||||||
|
<div class="post-txt">🎯 <b>各渠道转化率对比</b>(本周 vs 上周):付费广告转化率升至 6.2% 领跑各渠道,邮件营销持续垫底,建议调整预算配比 <a>#渠道分析</a></div>
|
||||||
|
<div class="chart-head"><div class="chart-title">转化率(%)· 本周</div><div class="legend"><span>最深色为本周最优渠道</span></div></div>
|
||||||
|
<div class="chart-wrap" style="padding-bottom:14px">
|
||||||
|
<div class="bars">
|
||||||
|
<div class="bcol"><span class="bval">4.8</span><div class="bar" style="height:62%" title="自然搜索 4.8%"></div><span class="bname">自然搜索</span></div>
|
||||||
|
<div class="bcol"><span class="bval">6.2</span><div class="bar top" style="height:80%" title="付费广告 6.2%"></div><span class="bname">付费广告</span></div>
|
||||||
|
<div class="bcol"><span class="bval">3.9</span><div class="bar" style="height:50%" title="社交媒体 3.9%"></div><span class="bname">社交媒体</span></div>
|
||||||
|
<div class="bcol"><span class="bval">5.5</span><div class="bar" style="height:71%" title="直接访问 5.5%"></div><span class="bname">直接访问</span></div>
|
||||||
|
<div class="bcol"><span class="bval">2.1</span><div class="bar" style="height:27%" title="邮件营销 2.1%"></div><span class="bname">邮件营销</span></div>
|
||||||
|
<div class="bcol"><span class="bval">3.4</span><div class="bar" style="height:44%" title="联盟推广 3.4%"></div><span class="bname">联盟推广</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="post-stats">
|
||||||
|
<div><span class="react">👍</span><span class="like-num" data-count="318">318</span></div>
|
||||||
|
<div><span>21 条评论</span> · <span>9 次分享</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
|
||||||
|
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
|
||||||
|
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<!-- 卡片 4:访问来源占比(环形图) -->
|
||||||
|
<article class="card post" data-key="来源 分布 占比 环形 donut 用户画像">
|
||||||
|
<div class="post-hd">
|
||||||
|
<div class="avatar av-teal">像</div>
|
||||||
|
<div class="meta">
|
||||||
|
<b>用户画像中心</b>
|
||||||
|
<div class="sub">5 小时前 · 公开</div>
|
||||||
|
</div>
|
||||||
|
<span class="more">···</span>
|
||||||
|
</div>
|
||||||
|
<div class="post-txt">🍩 <b>今日访问来源分布</b>:付费广告占比升至 31%(+4pt),自然流量份额被稀释,SEO 侧需要关注 <a>#来源分析</a></div>
|
||||||
|
<div class="chart-head"><div class="chart-title">访问来源占比 · 今日</div></div>
|
||||||
|
<div class="split">
|
||||||
|
<svg class="donut" viewBox="0 0 160 160">
|
||||||
|
<g transform="rotate(-90 80 80)">
|
||||||
|
<circle cx="80" cy="80" r="60" fill="none" stroke="#f0f2f5" stroke-width="26"/>
|
||||||
|
<circle cx="80" cy="80" r="60" fill="none" stroke="#1877f2" stroke-width="26" stroke-dasharray="155.3 377" stroke-dashoffset="0"/>
|
||||||
|
<circle cx="80" cy="80" r="60" fill="none" stroke="#45bd62" stroke-width="26" stroke-dasharray="113.9 377" stroke-dashoffset="-158.3"/>
|
||||||
|
<circle cx="80" cy="80" r="60" fill="none" stroke="#f7b928" stroke-width="26" stroke-dasharray="64.9 377" stroke-dashoffset="-275.2"/>
|
||||||
|
<circle cx="80" cy="80" r="60" fill="none" stroke="#fa383e" stroke-width="26" stroke-dasharray="30.9 377" stroke-dashoffset="-343.1"/>
|
||||||
|
</g>
|
||||||
|
<text x="80" y="76" text-anchor="middle" font-size="19" font-weight="700" fill="#1c1e21">128.4万</text>
|
||||||
|
<text x="80" y="96" text-anchor="middle" font-size="12" fill="#65676b">总访问量</text>
|
||||||
|
</svg>
|
||||||
|
<div>
|
||||||
|
<div class="lg-row"><span class="dot" style="background:#1877f2"></span><span class="nm">自然流量</span><span class="v">53.9 万</span><span class="pc">42%</span></div>
|
||||||
|
<div class="lg-row"><span class="dot" style="background:#45bd62"></span><span class="nm">付费广告</span><span class="v">39.8 万</span><span class="pc">31%</span></div>
|
||||||
|
<div class="lg-row"><span class="dot" style="background:#f7b928"></span><span class="nm">社交媒体</span><span class="v">23.1 万</span><span class="pc">18%</span></div>
|
||||||
|
<div class="lg-row"><span class="dot" style="background:#fa383e"></span><span class="nm">直接访问</span><span class="v">11.6 万</span><span class="pc">9%</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="post-stats">
|
||||||
|
<div><span class="react">👍</span><span class="like-num" data-count="205">205</span></div>
|
||||||
|
<div><span>12 条评论</span> · <span>6 次分享</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
|
||||||
|
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
|
||||||
|
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<!-- 卡片 5:热销商品 TOP5 -->
|
||||||
|
<article class="card post" data-key="商品 排行 榜单 top 销量 销售额 电商 rank table">
|
||||||
|
<div class="post-hd">
|
||||||
|
<div class="avatar av-purple">电</div>
|
||||||
|
<div class="meta">
|
||||||
|
<b>电商运营组</b>
|
||||||
|
<div class="sub">8 小时前 · 公开</div>
|
||||||
|
</div>
|
||||||
|
<span class="more">···</span>
|
||||||
|
</div>
|
||||||
|
<div class="post-txt">🏆 <b>今日热销商品 TOP5</b>:降噪耳机 Pro 稳居榜首,便携榨汁机环比 +24.8% 增速最快 <a>#电商日报</a></div>
|
||||||
|
<div class="tbl-wrap" style="padding-bottom:8px">
|
||||||
|
<table class="tbl">
|
||||||
|
<thead><tr><th>#</th><th>商品</th><th>销量</th><th>销售额</th><th>环比</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><td><span class="rank r1">1</span></td><td><b>无线降噪耳机 Pro</b></td><td>3,286 件</td><td>¥482.6 万</td><td class="up" style="color:var(--green);font-weight:700">▲ 18.2%</td></tr>
|
||||||
|
<tr><td><span class="rank r2">2</span></td><td><b>智能手表 S6</b></td><td>2,941 件</td><td>¥398.2 万</td><td style="color:var(--green);font-weight:700">▲ 9.6%</td></tr>
|
||||||
|
<tr><td><span class="rank r3">3</span></td><td><b>便携榨汁机</b></td><td>2,733 件</td><td>¥96.3 万</td><td style="color:var(--green);font-weight:700">▲ 24.8%</td></tr>
|
||||||
|
<tr><td><span class="rank rx">4</span></td><td><b>机械键盘 K87</b></td><td>2,158 件</td><td>¥172.9 万</td><td style="color:var(--red);font-weight:700">▼ 3.1%</td></tr>
|
||||||
|
<tr><td><span class="rank rx">5</span></td><td><b>桌面升降支架</b></td><td>1,986 件</td><td>¥119.5 万</td><td style="color:var(--green);font-weight:700">▲ 5.4%</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="post-stats">
|
||||||
|
<div><span class="react">❤️</span><span class="like-num" data-count="521">521</span></div>
|
||||||
|
<div><span>45 条评论</span> · <span>28 次分享</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="act act-like"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8.5 21H5.2a1.2 1.2 0 0 1-1.2-1.2v-8.6c0-.7.5-1.2 1.2-1.2h3.3zM9.7 10.2 13 3.5c1.4.2 2.2 1.2 2.2 2.7V9h4.4c1.3 0 2.2 1.1 1.9 2.3l-1.5 6.7c-.3 1.2-1.1 3-2.5 3H9.7z"/></svg>赞</button>
|
||||||
|
<button class="act act-comment"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.9 2 11.7c0 2.8 1.4 5.3 3.7 7L5 22l4.3-2c.9.2 1.8.4 2.7.4 5.5 0 10-3.9 10-8.7S17.5 3 12 3z"/></svg>评论</button>
|
||||||
|
<button class="act act-share"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 4.5 21 11l-7.5 6.5v-3.9C8 13.7 5.2 15.6 3.5 19.5c.2-6.7 4-10.5 10-11.4z"/></svg>分享</button>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<div class="noresult card" id="noResult" style="padding:40px 0">🔍 没有匹配的数据卡片,换个关键词试试(如:趋势 / 渠道 / 排行)</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ================= 右栏 ================= -->
|
||||||
|
<aside class="side side-r">
|
||||||
|
<div class="card rc">
|
||||||
|
<h4>推荐看板</h4>
|
||||||
|
<div class="rc-item">
|
||||||
|
<div class="rc-thumb" style="background:linear-gradient(140deg,#166fe5,#0a3d91)">🛒</div>
|
||||||
|
<div><div class="tt">双 11 作战室</div><div class="dd">datafeed.cn/board/d11</div></div>
|
||||||
|
</div>
|
||||||
|
<div class="rc-item">
|
||||||
|
<div class="rc-thumb" style="background:linear-gradient(140deg,#f7b928,#dd7d0a)">📣</div>
|
||||||
|
<div><div class="tt">渠道 ROI 分析</div><div class="dd">datafeed.cn/board/roi</div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card rc">
|
||||||
|
<h4>数据更新计划</h4>
|
||||||
|
<div class="rc-row"><span class="rc-status on"></span><div><b>T+1 销售宽表</b><div class="sub">每日 02:00 · 已完成</div></div><span class="tail">2h 前</span></div>
|
||||||
|
<div class="rc-row"><span class="rc-status on"></span><div><b>用户标签计算</b><div class="sub">每日 03:30 · 已完成</div></div><span class="tail">40m 前</span></div>
|
||||||
|
<div class="rc-row"><span class="rc-status pulse"></span><div><b>实时埋点流</b><div class="sub">持续写入 · 运行中</div></div><span class="tail" style="color:var(--green);font-weight:700">正常</span></div>
|
||||||
|
<div class="rc-row"><span class="rc-status off"></span><div><b>周报快照</b><div class="sub">每周一 09:00 · 待执行</div></div><span class="tail">2d 后</span></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card rc">
|
||||||
|
<h4>值班分析师</h4>
|
||||||
|
<div class="rc-row"><div class="avatar sm av-green">李</div><div><b>李雷</b><div class="sub">主值班 · 增长数据</div></div></div>
|
||||||
|
<div class="rc-row"><div class="avatar sm av-blue">韩</div><div><b>韩梅梅</b><div class="sub">副值班 · 电商数据</div></div></div>
|
||||||
|
<div class="rc-row"><div class="avatar sm av-orange">陈</div><div><b>陈晨</b><div class="sub">渠道数据 · 离线</div></div></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card rc">
|
||||||
|
<h4>你的小组</h4>
|
||||||
|
<div class="rc-row"><div class="avatar sm av-blue">增</div><div><b>增长数据组</b><div class="sub">12 位成员 · 3 条新动态</div></div></div>
|
||||||
|
<div class="rc-row"><div class="avatar sm av-green">实</div><div><b>实验平台组</b><div class="sub">8 位成员 · 1 条新动态</div></div></div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
/* ================= 折线图(平滑曲线,Catmull-Rom → 贝塞尔) ================= */
|
||||||
|
const SVGNS = 'http://www.w3.org/2000/svg';
|
||||||
|
const PAD = {l:44, r:628, t:16, b:222}; // 640 x 264 绘图区
|
||||||
|
|
||||||
|
function smoothPath(pts){
|
||||||
|
if(pts.length < 2) return '';
|
||||||
|
let d = `M ${pts[0][0].toFixed(1)} ${pts[0][1].toFixed(1)}`;
|
||||||
|
for(let i = 0; i < pts.length - 1; i++){
|
||||||
|
const p0 = pts[Math.max(0, i-1)], p1 = pts[i], p2 = pts[i+1], p3 = pts[Math.min(pts.length-1, i+2)];
|
||||||
|
const c1x = p1[0] + (p2[0]-p0[0])/6, c1y = p1[1] + (p2[1]-p0[1])/6;
|
||||||
|
const c2x = p2[0] - (p3[0]-p1[0])/6, c2y = p2[1] - (p3[1]-p1[1])/6;
|
||||||
|
d += ` C ${c1x.toFixed(1)} ${c1y.toFixed(1)}, ${c2x.toFixed(1)} ${c2y.toFixed(1)}, ${p2[0].toFixed(1)} ${p2[1].toFixed(1)}`;
|
||||||
|
}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
function gen30(){ // 近 30 天(确定性伪随机,演示用)
|
||||||
|
const labels=[], today=[], yest=[];
|
||||||
|
for(let i = 29; i >= 0; i--){
|
||||||
|
const d = new Date(2026, 9, 25 - i);
|
||||||
|
labels.push(`${d.getMonth()+1}/${d.getDate()}`);
|
||||||
|
const v = 55 + 16*Math.sin(i/3.4) + 9*Math.cos(i/1.7) + (i%7===6 ? 9 : 0) - (i%7===0 ? 5 : 0);
|
||||||
|
today.push(Math.round(v*10)/10);
|
||||||
|
yest.push(Math.round((v - 6 + 4*Math.cos(i/2.2))*10)/10);
|
||||||
|
}
|
||||||
|
return {labels, today, yesterday:yest};
|
||||||
|
}
|
||||||
|
|
||||||
|
const DATASETS = {
|
||||||
|
'7': {labels:['10/19','10/20','10/21','10/22','10/23','10/24','10/25'],
|
||||||
|
today:[52.4,61.2,58.6,73.1,66.4,81.2,88.5],
|
||||||
|
yesterday:[48.9,55.3,60.2,64.5,59.1,70.6,72.3]},
|
||||||
|
'30': gen30()
|
||||||
|
};
|
||||||
|
|
||||||
|
function el(name, attrs){
|
||||||
|
const n = document.createElementNS(SVGNS, name);
|
||||||
|
for(const k in attrs) n.setAttribute(k, attrs[k]);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildTrend(range){
|
||||||
|
const ds = DATASETS[range];
|
||||||
|
const svg = document.getElementById('trendSvg');
|
||||||
|
svg.innerHTML = '';
|
||||||
|
const peak = Math.max(...ds.today, ...ds.yesterday);
|
||||||
|
const step = Math.max(10, Math.ceil(peak/4/5)*5);
|
||||||
|
const maxT = step*4;
|
||||||
|
const n = ds.today.length;
|
||||||
|
const X = i => PAD.l + (PAD.r-PAD.l)*i/(n-1);
|
||||||
|
const Y = v => PAD.b - (v/maxT)*(PAD.b-PAD.t);
|
||||||
|
|
||||||
|
// 渐变
|
||||||
|
const defs = el('defs');
|
||||||
|
const grad = el('linearGradient', {id:'gBlue', x1:0, y1:0, x2:0, y2:1});
|
||||||
|
grad.appendChild(el('stop', {offset:'0%', 'stop-color':'#1877f2', 'stop-opacity':.22}));
|
||||||
|
grad.appendChild(el('stop', {offset:'100%', 'stop-color':'#1877f2', 'stop-opacity':0}));
|
||||||
|
defs.appendChild(grad); svg.appendChild(defs);
|
||||||
|
|
||||||
|
// 网格 + Y 轴刻度
|
||||||
|
for(let i = 0; i <= 4; i++){
|
||||||
|
const v = step*i, y = Y(v);
|
||||||
|
svg.appendChild(el('line', {x1:PAD.l, x2:PAD.r, y1:y, y2:y, stroke:'#e4e6eb', 'stroke-dasharray': i? '3 5' : '0'}));
|
||||||
|
const t = el('text', {x:PAD.l-8, y:y+4, 'text-anchor':'end', 'font-size':11, fill:'#8a8d91'});
|
||||||
|
t.textContent = v; svg.appendChild(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pt = arr => arr.map((v,i)=>[X(i), Y(v)]);
|
||||||
|
const pToday = pt(ds.today), pYest = pt(ds.yesterday);
|
||||||
|
|
||||||
|
// 面积(今日)
|
||||||
|
const area = smoothPath(pToday) + ` L ${pToday[n-1][0]} ${PAD.b} L ${pToday[0][0]} ${PAD.b} Z`;
|
||||||
|
svg.appendChild(el('path', {d:area, fill:'url(#gBlue)'}));
|
||||||
|
// 昨日(灰虚线)
|
||||||
|
svg.appendChild(el('path', {d:smoothPath(pYest), fill:'none', stroke:'#b6bcc4', 'stroke-width':2, 'stroke-dasharray':'5 6'}));
|
||||||
|
// 今日(蓝)
|
||||||
|
svg.appendChild(el('path', {d:smoothPath(pToday), fill:'none', stroke:'#1877f2', 'stroke-width':3, 'stroke-linecap':'round'}));
|
||||||
|
// 端点
|
||||||
|
svg.appendChild(el('circle', {cx:pToday[n-1][0], cy:pToday[n-1][1], r:4.5, fill:'#1877f2', stroke:'#fff', 'stroke-width':2}));
|
||||||
|
|
||||||
|
// X 轴标签 & 悬停提示
|
||||||
|
const labelStep = Math.max(1, Math.ceil(n/7));
|
||||||
|
for(let i = 0; i < n; i++){
|
||||||
|
if(n <= 8){
|
||||||
|
svg.appendChild(el('circle', {cx:X(i), cy:Y(ds.today[i]), r:2.6, fill:'#1877f2'}));
|
||||||
|
}
|
||||||
|
const hit = el('circle', {cx:X(i), cy:Y(ds.today[i]), r:11, fill:'transparent', style:'cursor:pointer'});
|
||||||
|
const ti = el('title'); ti.textContent = `${ds.labels[i]} · 今日 ${ds.today[i]} 万 / 昨日 ${ds.yesterday[i]} 万`;
|
||||||
|
hit.appendChild(ti); svg.appendChild(hit);
|
||||||
|
if(i % labelStep === 0 || i === n-1){
|
||||||
|
const t = el('text', {x:X(i), y:244, 'text-anchor':'middle', 'font-size':11, fill:'#8a8d91'});
|
||||||
|
t.textContent = ds.labels[i]; svg.appendChild(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const mx = Math.max(...ds.today), mn = Math.min(...ds.today);
|
||||||
|
const avg = (ds.today.reduce((a,b)=>a+b,0)/n).toFixed(1);
|
||||||
|
document.getElementById('trendSummary').textContent =
|
||||||
|
`单位:万次访问 · 峰值 ${mx} 万 · 谷值 ${mn} 万 · 均值 ${avg} 万`;
|
||||||
|
}
|
||||||
|
buildTrend('7');
|
||||||
|
|
||||||
|
document.querySelectorAll('.pill[data-range]').forEach(p => {
|
||||||
|
p.addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.pill[data-range]').forEach(x => x.classList.remove('active'));
|
||||||
|
p.classList.add('active');
|
||||||
|
buildTrend(p.dataset.range);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ================= 点赞 ================= */
|
||||||
|
document.querySelectorAll('.act-like').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
const post = btn.closest('.post');
|
||||||
|
const num = post.querySelector('.like-num');
|
||||||
|
const on = btn.classList.toggle('liked');
|
||||||
|
num.dataset.count = +num.dataset.count + (on ? 1 : -1);
|
||||||
|
const c = +num.dataset.count;
|
||||||
|
num.textContent = c >= 1000 ? (c/1000).toFixed(1).replace(/\.0$/,'') + 'k' : c.toLocaleString('zh-CN');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ================= 评论(回车发送) ================= */
|
||||||
|
const cmtInput = document.querySelector('.cmt-input input');
|
||||||
|
cmtInput.addEventListener('keydown', e => {
|
||||||
|
if(e.key !== 'Enter' || !e.target.value.trim()) return;
|
||||||
|
const post = e.target.closest('.post');
|
||||||
|
const wrap = e.target.closest('.comments');
|
||||||
|
const txt = e.target.value.trim();
|
||||||
|
e.target.value = '';
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'cmt';
|
||||||
|
div.innerHTML = `<div class="avatar av-blue sm">张</div>
|
||||||
|
<div><div class="cmt-bubble"><span class="cmt-name">张分析</span>${txt.replace(/</g,'<')}</div>
|
||||||
|
<div class="cmt-meta"><a>赞</a><a>回复</a><span>刚刚</span></div></div>`;
|
||||||
|
wrap.insertBefore(div, e.target.closest('.cmt-input'));
|
||||||
|
const cn = post.querySelector('.cmt-num'), total = post.querySelector('.cmt-total');
|
||||||
|
cn.dataset.count = +cn.dataset.count + 1;
|
||||||
|
cn.textContent = cn.dataset.count + ' 条评论';
|
||||||
|
total.textContent = cn.dataset.count;
|
||||||
|
});
|
||||||
|
document.querySelectorAll('.act-comment').forEach(btn => {
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
const input = btn.closest('.post').querySelector('.cmt-input input');
|
||||||
|
if(input){ input.focus(); } else { showToast('该卡片暂未开放评论(演示)'); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ================= 分享 / 演示按钮 Toast ================= */
|
||||||
|
const toast = document.getElementById('toast');
|
||||||
|
let toastTimer;
|
||||||
|
function showToast(msg){
|
||||||
|
toast.textContent = msg;
|
||||||
|
toast.classList.add('show');
|
||||||
|
clearTimeout(toastTimer);
|
||||||
|
toastTimer = setTimeout(() => toast.classList.remove('show'), 1800);
|
||||||
|
}
|
||||||
|
document.querySelectorAll('.act-share').forEach(b => b.addEventListener('click', () => showToast('看板链接已复制(演示)')));
|
||||||
|
document.querySelectorAll('[data-toast]').forEach(b => b.addEventListener('click', () => showToast(b.dataset.toast)));
|
||||||
|
document.querySelectorAll('.story').forEach(s => s.addEventListener('click', () => showToast('演示页面:数据专题未接入')));
|
||||||
|
|
||||||
|
/* ================= 搜索 / 筛选(顶栏 + 发布器共用) ================= */
|
||||||
|
function filterPosts(q){
|
||||||
|
q = q.trim().toLowerCase();
|
||||||
|
let visible = 0;
|
||||||
|
document.querySelectorAll('.feed .post').forEach(p => {
|
||||||
|
const hit = !q || (p.dataset.key + ' ' + p.textContent).toLowerCase().includes(q);
|
||||||
|
p.style.display = hit ? '' : 'none';
|
||||||
|
if(hit) visible++;
|
||||||
|
});
|
||||||
|
document.getElementById('noResult').style.display = visible ? 'none' : 'block';
|
||||||
|
}
|
||||||
|
['globalSearch','feedFilter'].forEach(id => {
|
||||||
|
document.getElementById(id).addEventListener('input', e => {
|
||||||
|
filterPosts(e.target.value);
|
||||||
|
if(id === 'globalSearch'){ const f = document.getElementById('feedFilter'); if(f.value !== e.target.value) f.value = e.target.value; }
|
||||||
|
else { const g = document.getElementById('globalSearch'); if(g.value !== e.target.value) g.value = e.target.value; }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ================= 顶部导航高亮 ================= */
|
||||||
|
document.querySelectorAll('.tb-nav').forEach(n => {
|
||||||
|
n.addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.tb-nav').forEach(x => x.classList.remove('active'));
|
||||||
|
n.classList.add('active');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -62,6 +62,9 @@
|
|||||||
# 问答页「极速」模式:true=在模式菜单显示并直连大模型;false 或未设=隐藏。
|
# 问答页「极速」模式:true=在模式菜单显示并直连大模型;false 或未设=隐藏。
|
||||||
# 部署后优先改 dist/runtime-config.js 的 VITE_TURBO_MODE_VISIBLE,刷新即可。
|
# 部署后优先改 dist/runtime-config.js 的 VITE_TURBO_MODE_VISIBLE,刷新即可。
|
||||||
# VITE_TURBO_MODE_VISIBLE=false
|
# 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=
|
# VITE_GITHUB_OAUTH_TOKEN=
|
||||||
|
|
||||||
# --- 官方 DeerFlow 风格页面入口(仅 Vite,不引入 Next.js)---
|
# --- 官方 DeerFlow 风格页面入口(仅 Vite,不引入 Next.js)---
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ VITE_AIPI_MOPECHAT_URL=https://ch1.b.uat.4.cn/likun_b1_mope
|
|||||||
# 工作室/空间后端接口(侧边栏“工作室”列表、空间详情等都走这里,不是 VITE_NOTE_API_BASE_URL)
|
# 工作室/空间后端接口(侧边栏“工作室”列表、空间详情等都走这里,不是 VITE_NOTE_API_BASE_URL)
|
||||||
VITE_AIPI_BACKENP_URL=https://knowledgetoolserver.b.uat.4.cn
|
VITE_AIPI_BACKENP_URL=https://knowledgetoolserver.b.uat.4.cn
|
||||||
# 我的空间前端
|
# 我的空间前端
|
||||||
VITE_AIPI_FRONTEND_URL= xxx
|
VITE_AIPI_FRONTEND_URL= https://knowledgetoolweb.b.uat.4.cn
|
||||||
VITE_AIPI_CONSUMER_URL=https://ch1.b.uat.4.cn/consumer
|
VITE_AIPI_CONSUMER_URL=https://ch1.b.uat.4.cn/consumer
|
||||||
# A 系统跳转地址(人物/组织/事件等列表项打开链接)
|
# A 系统跳转地址(人物/组织/事件等列表项打开链接)
|
||||||
VITE_AIPI_PRESENT_URL=https://present.a.uat.4.cn/present/domain
|
VITE_AIPI_PRESENT_URL=https://present.a.uat.4.cn/present/domain
|
||||||
|
|||||||
@@ -889,7 +889,7 @@ Step 2(chat 步骤)
|
|||||||
| `@tanstack/react-query` | - | 服务端状态缓存 |
|
| `@tanstack/react-query` | - | 服务端状态缓存 |
|
||||||
| `@langchain/langgraph-sdk` | - | LangGraph WebSocket 连接 |
|
| `@langchain/langgraph-sdk` | - | LangGraph WebSocket 连接 |
|
||||||
| `next-themes` | - | 主题管理 |
|
| `next-themes` | - | 主题管理 |
|
||||||
| `sonner` | - | Toast 通知 |
|
| `tdesign-react` | - | 全局消息、确认对话框与输入提示 |
|
||||||
| `lucide-react` | - | 图标库 |
|
| `lucide-react` | - | 图标库 |
|
||||||
| `tailwindcss` | - | CSS 框架 |
|
| `tailwindcss` | - | CSS 框架 |
|
||||||
| `rehype` 系列 | - | Markdown 渲染 |
|
| `rehype` 系列 | - | Markdown 渲染 |
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
|
|
||||||
| 事实 | 位置 |
|
| 事实 | 位置 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| Step2 编排循环(leader → 顺序派 special → leader … 直到 `dispatched===[]` 共识 / `MAX_CYCLES=8`)**完全由前端 hook 驱动** | `src/roundtable-planning/hooks/useStep2Orchestration.ts:992-1204`(recommend)、`1228-1439`(chain) |
|
| Step2 编排循环(leader → special → leader …;到全局 `roundtable_room_limit.max_cycles` 配置轮次进入无工具的总控正文收口)**完全由前端 hook 驱动** | `src/roundtable-planning/hooks/useStep2Orchestration.ts`(recommend / chain / dag) |
|
||||||
| 循环由 `currentStep===2` 的 `useEffect` 启停;离开 Step2 的 cleanup 会 `orchestrationCancelRef.current=true` + `abortAllInFlight()` 中断 | `useStep2Orchestration.ts:1468-1541`(尤其 cleanup `1534-1537`、`1471-1477`) |
|
| 循环由 `currentStep===2` 的 `useEffect` 启停;离开 Step2 的 cleanup 会 `orchestrationCancelRef.current=true` + `abortAllInFlight()` 中断 | `useStep2Orchestration.ts:1468-1541`(尤其 cleanup `1534-1537`、`1471-1477`) |
|
||||||
| 共识判定:`leaderRes.dispatched.length===0` → `setHasConsensus(true)` | `useStep2Orchestration.ts:1091-1099` |
|
| 共识判定:`leaderRes.dispatched.length===0` → `setHasConsensus(true)` | `useStep2Orchestration.ts:1091-1099` |
|
||||||
| 进入 Step3:手动点按钮,前置 `hasConsensus===true` | `Step2Panel.tsx:370-381`、`RoundtablePlanningPage.tsx:586-595` |
|
| 进入 Step3:手动点按钮,前置 `hasConsensus===true` | `Step2Panel.tsx:370-381`、`RoundtablePlanningPage.tsx:586-595` |
|
||||||
@@ -456,7 +456,7 @@ checkpoint,一路跑到 Step3 绘制完成。
|
|||||||
只有「查看」进去才能回答(或在弹窗里直接给一个回答框,调用 `resumeJob`)。
|
只有「查看」进去才能回答(或在弹窗里直接给一个回答框,调用 `resumeJob`)。
|
||||||
3. **取消**:流程图弹窗/Step2 提供「停止后台」→ `cancelJob`,`status→cancelled`,前端可恢复本地编辑。
|
3. **取消**:流程图弹窗/Step2 提供「停止后台」→ `cancelJob`,`status→cancelled`,前端可恢复本地编辑。
|
||||||
4. **错误恢复**:`error` 事件展示 detail;允许「重试」= 重新 `startJob`(沿用已建 threadIds)。
|
4. **错误恢复**:`error` 事件展示 detail;允许「重试」= 重新 `startJob`(沿用已建 threadIds)。
|
||||||
5. **MAX_CYCLES / 预算**:后台图内兜底(对齐前端 `MAX_CYCLES=8`),到顶强制收敛并照常进 Step3。
|
5. **max_cycles / 预算**:后台与前端统一读取全局 `roundtable_room_limit.max_cycles`(默认 8,2..100),一次会商启动时锁定;到达配置轮次调用 `finalize_only=True`,关闭全部工具并要求总控输出最终总结正文。不能把到顶表现成“已停止”,也不能跳过总结直接进入 Step3。
|
||||||
6. **多 worker**:严格遵守 Phase 3 的「状态进 DB+checkpointer、SSE 走 loopback」;部署若多 worker
|
6. **多 worker**:严格遵守 Phase 3 的「状态进 DB+checkpointer、SSE 走 loopback」;部署若多 worker
|
||||||
需 sticky 或全靠 DB 态(推荐后者)。
|
需 sticky 或全靠 DB 态(推荐后者)。
|
||||||
7. **清理**:`roundtable_jobs` cleanup cron(活跃保护、先删 CP 再删 DB),与 draft 生命周期对齐。
|
7. **清理**:`roundtable_jobs` cleanup cron(活跃保护、先删 CP 再删 DB),与 draft 生命周期对齐。
|
||||||
|
|||||||
@@ -290,7 +290,7 @@ chain 模式的 Step 2 init **完全复用** `initMultiAgent`:`agentNames = ch
|
|||||||
**目标**:能创建/编辑/保存/删除链条。
|
**目标**:能创建/编辑/保存/删除链条。
|
||||||
- [x] 路由:`WorkspaceRoutes.tsx` 注册 `roundtable/chains`(套 `WorkspaceLayout`;本页**不需要** `ChatRuntime`,无沙箱依赖)。
|
- [x] 路由:`WorkspaceRoutes.tsx` 注册 `roundtable/chains`(套 `WorkspaceLayout`;本页**不需要** `ChatRuntime`,无沙箱依赖)。
|
||||||
- [x] 页面 `roundtable-planning/pages/BusinessChainEditorPage.tsx`:
|
- [x] 页面 `roundtable-planning/pages/BusinessChainEditorPage.tsx`:
|
||||||
- [x] 顶部:链条列表下拉(`<select>` 列出已存链条 + 新建项)/ 新建按钮 / 标题+描述输入 / 保存 / 删除(`window.confirm`)。
|
- [x] 顶部:链条列表下拉(`<select>` 列出已存链条 + 新建项)/ 新建按钮 / 标题+描述输入 / 保存 / 删除(TDesign 确认对话框)。
|
||||||
- [x] **左栏**:候选智能体(`listAgents()` + `filterRecommendCandidates`),竖排卡片,可拖、可点「+」快捷加入;已加入的置灰「已加入」。
|
- [x] **左栏**:候选智能体(`listAgents()` + `filterRecommendCandidates`),竖排卡片,可拖、可点「+」快捷加入;已加入的置灰「已加入」。
|
||||||
- [x] **右栏**:有序长条卡片(序号 tag + 名称 + 描述 + 移除),`SortableContext` 内拖拽排序;空态有占位提示。
|
- [x] **右栏**:有序长条卡片(序号 tag + 名称 + 描述 + 移除),`SortableContext` 内拖拽排序;空态有占位提示。
|
||||||
- [x] 拖拽用 `@dnd-kit`:左栏 `useDraggable`,右栏 `useDroppable` + `SortableContext`/`useSortable`,`onDragEnd` 计算插入 index(pool→右栏按落点插入;seat→seat `arrayMove`);`DragOverlay` 跟手卡片。
|
- [x] 拖拽用 `@dnd-kit`:左栏 `useDraggable`,右栏 `useDroppable` + `SortableContext`/`useSortable`,`onDragEnd` 计算插入 index(pool→右栏按落点插入;seat→seat `arrayMove`);`DragOverlay` 跟手卡片。
|
||||||
@@ -311,13 +311,13 @@ chain 模式的 Step 2 init **完全复用** `initMultiAgent`:`agentNames = ch
|
|||||||
|
|
||||||
### 阶段 3 · 业务链条选择卡片列表(1.5 天) ✅ 已完成
|
### 阶段 3 · 业务链条选择卡片列表(1.5 天) ✅ 已完成
|
||||||
**目标**:弹窗「业务链条」面板里选链条。新增 `components/BusinessChainPicker.tsx`,替换阶段 2 的占位。
|
**目标**:弹窗「业务链条」面板里选链条。新增 `components/BusinessChainPicker.tsx`,替换阶段 2 的占位。
|
||||||
- [x] 进入该 Tab 时 `listChains()` 拉本人链条 + `listAgents()` 取存活 id/名称,渲染**卡片列表**:
|
- [x] 进入该 Tab 时 `listChains()` 拉本人链条渲染**卡片列表**(席位存活/名称用链条响应自带的读时计算富化字段 `seat.available`/`seat.live_name`,**不再实时拉 `listAgents()`**,见 §11):
|
||||||
- [x] 卡片标题(链条 title)+ 「N 席」徽章 + 选中 ✓;描述行。
|
- [x] 卡片标题(链条 title)+ 「N 席」徽章 + 选中 ✓;描述行。
|
||||||
- [x] 标题下一排**智能体名 tag**:按链条顺序**从左到右**、不同颜色(`getAvatarTypeFor`→`chainTagClasses`),tag 之间插 `→`(`ArrowRightIcon`)箭头连接(`seats[0]` 最左、先发言)。
|
- [x] 标题下一排**智能体名 tag**:按链条顺序**从左到右**、不同颜色(`getAvatarTypeFor`→`chainTagClasses`),tag 之间插 `→`(`ArrowRightIcon`)箭头连接(`seats[0]` 最左、先发言)。
|
||||||
- [x] 底部「配置链条」按钮(跳 `roundtable/chains`)。
|
- [x] 底部「配置链条」按钮(跳 `roundtable/chains`)。
|
||||||
- [x] 空态:无链条时引导「去配置页面创建第一条业务链条」+ 按钮。
|
- [x] 空态:无链条时引导「去配置页面创建第一条业务链条」+ 按钮。
|
||||||
- [x] 选中一条 → 高亮(`ring-primary`);底部「进入研讨」`onConfirm({ agents: 存活席位有序, mode:"chain", chain:{id,title} })`。
|
- [x] 选中一条 → 高亮(`ring-primary`);底部「进入研讨」`onConfirm({ agents: 存活席位有序, mode:"chain", chain:{id,title} })`。
|
||||||
- [x] 链条里有 agent 已不存在(被删)→ 该 tag 置灰删除线 + `title` 提示 + 卡片下方 amber 警告;confirm 按**存活席位**过滤;存活 < `CHAIN_MIN_SEATS` 则禁用「进入研讨」并提示。agent 列表加载失败时 `existingIds=null` → 不误判删除。
|
- [x] 链条里有 agent 已不存在(被删)→ 该 tag 置灰删除线 + `title` 提示 + 卡片下方 amber 警告;confirm 按**存活席位**过滤;存活 < `CHAIN_MIN_SEATS` 则禁用「进入研讨」并提示。存活判定改读 `seat.available`(undefined = 旧后端未标注 → 不误判删除)。
|
||||||
- **验收**:✅ typecheck 0 新增错误(总数仍 76)。卡片渲染标题 + 彩色 tag + ← 箭头;选链 → `onConfirm(mode:"chain")` → `handleConfirmAgents` 按链条顺序 `setSelectedAgents` → Step 2 左侧「参与角色」顺序 = 链条顺序(**按顺序派活在阶段 4**)。**人工 UI 验收待跑**。
|
- **验收**:✅ typecheck 0 新增错误(总数仍 76)。卡片渲染标题 + 彩色 tag + ← 箭头;选链 → `onConfirm(mode:"chain")` → `handleConfirmAgents` 按链条顺序 `setSelectedAgents` → Step 2 左侧「参与角色」顺序 = 链条顺序(**按顺序派活在阶段 4**)。**人工 UI 验收待跑**。
|
||||||
- **箭头方向**(已确认):tag 左→右排列、`→`(`ArrowRightIcon`)连接,`seats[0]` 最左、先发言,箭头顺读即链条研讨顺序。
|
- **箭头方向**(已确认):tag 左→右排列、`→`(`ArrowRightIcon`)连接,`seats[0]` 最左、先发言,箭头顺读即链条研讨顺序。
|
||||||
|
|
||||||
@@ -396,5 +396,42 @@ chain 模式的 Step 2 init **完全复用** `initMultiAgent`:`agentNames = ch
|
|||||||
| 后端链条持久化 | `offline-backend-20260512/backend/packages/harness/deerflow/persistence/roundtable_chains/` | 新增 |
|
| 后端链条持久化 | `offline-backend-20260512/backend/packages/harness/deerflow/persistence/roundtable_chains/` | 新增 |
|
||||||
| 后端链条路由 | `offline-backend-20260512/backend/app/gateway/routers/roundtable_chains.py` | 新增 |
|
| 后端链条路由 | `offline-backend-20260512/backend/app/gateway/routers/roundtable_chains.py` | 新增 |
|
||||||
| 后端 store 接线 | `offline-backend-20260512/backend/app/gateway/deps.py`(`app.state.roundtable_chain_store`)+ `app.py` | 改 |
|
| 后端 store 接线 | `offline-backend-20260512/backend/app/gateway/deps.py`(`app.state.roundtable_chain_store`)+ `app.py` | 改 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 席位富化:选链不再实时拉智能体列表(2026-10-23)
|
||||||
|
|
||||||
|
**背景**:选链全链路(弹窗打开 / 左栏点选 / 深链自动选链)此前每次都额外全量拉
|
||||||
|
`GET /api/agents`,只为两件事——席位**存活判断**(existingIds)与**最新改名**
|
||||||
|
(nameById)。慢网下这个大请求严重拖慢选链体验。
|
||||||
|
|
||||||
|
**方案**:席位展示所需信息(name 快照本就随链条落库、编辑器保存时刷新)之外,
|
||||||
|
「存活 + 最新名」由**后端在返回链条时读时计算**:
|
||||||
|
|
||||||
|
- `GET /api/roundtable-chains`(list/get/update 等)对每条链每个 seat 附带两个
|
||||||
|
**只读计算字段**(`ChainSeatResponseSchema`,不落库、create/update 请求 schema
|
||||||
|
不收,存量 seats JSON 零迁移):
|
||||||
|
- `available: bool` —— 席位智能体当前对请求用户可见(本人/内置/已发布、非私享、
|
||||||
|
非管理员隐藏,`agent_store.list_by_ids` 一次批量 SQL)且不是功能型内置
|
||||||
|
(`roundtable-intent/recommender/coordinator/report` + `roundtable-coordinator-*`
|
||||||
|
前缀,与前端 `filterRecommendCandidates` 排除集逐字对齐);
|
||||||
|
- `live_name: string | null` —— 智能体当前名称,查不到为 null。
|
||||||
|
- best-effort:agent store 不可用时跳过富化(字段缺省),前端按存活处理。
|
||||||
|
- 前端 `ChainSeat` 增加可选 `available` / `live_name`;`buildChainSeatSelection(chain,
|
||||||
|
candidates?)` 的 `candidates` 变为可选——不传时存活 = `seat.available !== false`
|
||||||
|
(undefined = 旧后端 → 视为存活,与旧版「拉取失败不判删」降级语义一致)、名称 =
|
||||||
|
`live_name ?? name ?? agent_id`。
|
||||||
|
- 去掉选链路径上的全部 `listAgents()`:`BusinessChainPicker`(打开只剩 1 个
|
||||||
|
`listChains` 请求)、`BusinessChainListDialog`(列表弹窗)、主页左栏点选
|
||||||
|
(**零网络请求**)、固定链(8BF 等)与深链自动选链。
|
||||||
|
- 「智能推荐」Tab 与链条编辑器的智能体池**保留** `listAgents()`——那两处真的需要
|
||||||
|
完整候选列表。
|
||||||
|
|
||||||
|
**兜底**:智能体在选链之后、进 Step 2 之前被删,`/api/multi-agent/init` 的后端
|
||||||
|
404 硬校验照旧兜底(现状即有,非本次引入)。
|
||||||
|
|
||||||
|
**测试**:后端 `tests/test_roundtable_chain_seat_enrichment.py`(纯函数 + schema
|
||||||
|
不落库 + store 往返);前端 `src/roundtable-planning/lib/business-chain.test.ts`
|
||||||
|
(`pnpm run test:business-chain`,esbuild 打包后 node:test)。
|
||||||
</content>
|
</content>
|
||||||
</invoke>
|
</invoke>
|
||||||
@@ -394,8 +394,8 @@ while !cancelled && cycles < MAX_CYCLES:
|
|||||||
setConsensusPercentage(prev => min(95, prev + 8))
|
setConsensusPercentage(prev => min(95, prev + 8))
|
||||||
nextLeaderTask = "各子智能体已就上一轮派活完成交付,请你结合最新结论..."
|
nextLeaderTask = "各子智能体已就上一轮派活完成交付,请你结合最新结论..."
|
||||||
|
|
||||||
if cycles >= MAX_CYCLES:
|
if cycles == configuredMaxCycles:
|
||||||
toast("⏱️ 已达到最大研讨轮次,自动停止以避免循环")
|
leader(finalizeOnly: true, tools: [], prompt: "直接综合已有交付并输出最终正文")
|
||||||
|
|
||||||
clearAllStreamingSpeakers()
|
clearAllStreamingSpeakers()
|
||||||
isOrchestrating = false
|
isOrchestrating = false
|
||||||
@@ -591,7 +591,7 @@ isOrchestrating = false
|
|||||||
| Step 2 干预 | 底部输入框 → `runOrchestration` 新 seed,wrap 进「用户人工干预新指令:...」 prompt |
|
| Step 2 干预 | 底部输入框 → `runOrchestration` 新 seed,wrap 进「用户人工干预新指令:...」 prompt |
|
||||||
| Step 2 Persona | 点圆桌头像打开抽屉;保存后下一轮该席位使用所选模型 |
|
| Step 2 Persona | 点圆桌头像打开抽屉;保存后下一轮该席位使用所选模型 |
|
||||||
| 新建任务 | `handleStartNewTask`:abort 全部、清 state、`runStep1Init`,与 Step 3「重新起草」共用 |
|
| 新建任务 | `handleStartNewTask`:abort 全部、清 state、`runStep1Init`,与 Step 3「重新起草」共用 |
|
||||||
| 历史草稿 | 顶栏下拉:加载 / 重命名 / 删除(删除带 `window.confirm`) |
|
| 历史草稿 | 顶栏下拉:加载 / 重命名 / 删除(删除使用 TDesign 确认对话框) |
|
||||||
| Step 3 预览 | 文本类 → 模态预览;其它 → 新窗口下载 |
|
| Step 3 预览 | 文本类 → 模态预览;其它 → 新窗口下载 |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -695,7 +695,7 @@ window.__MULTI_AGENT_DEBUG__ = true; // stream 帧计数(默认开)
|
|||||||
|
|
||||||
### 12.3 调整 Step 2 编排上限
|
### 12.3 调整 Step 2 编排上限
|
||||||
|
|
||||||
`RoundtablePlanningPage.tsx` 内 `MAX_CYCLES = 8`,超出会 toast「⏱️ 已达到最大研讨轮次,自动停止以避免循环」。若放宽:注意 `step2RoundtableDialogues` 数组会线性增长,超长讨论需要考虑虚拟滚动。
|
收口轮数来自全局设置 `roundtable_room_limit.max_cycles`(管理员设置弹窗「会商并发与收口」,默认 8、范围 2..100),旧服务端或读取失败时回退 `DEFAULT_MAX_CYCLES=8`。一次编排启动时锁定当时值;到达该轮不是停止,而是切换为 `finalizeOnly` 纯正文收口:总控禁用全部工具,综合已经取得的席位交付并输出最终方案;个别席位失败时如实标明缺口。前后台执行路径必须保持一致。
|
||||||
|
|
||||||
### 12.4 把 special 改回并行
|
### 12.4 把 special 改回并行
|
||||||
|
|
||||||
|
|||||||
@@ -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 后端约定一致。
|
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"] })`,让侧边栏「最近会话」自动刷新。
|
6. **TanStack Query 失效**:流式完成或新建会话时调用 `queryClient.invalidateQueries({ queryKey: ["threads", "search"] })`,让侧边栏「最近会话」自动刷新。
|
||||||
7. **错误降级**:`onError` 弹 sonner toast;`getStreamErrorMessage(error)` 兜底解析对象/嵌套字段。
|
7. **错误降级**:`onError` 通过项目反馈层弹出 TDesign Message;`getStreamErrorMessage(error)` 兜底解析对象/嵌套字段。
|
||||||
|
|
||||||
### 7.4 重要回调事件
|
### 7.4 重要回调事件
|
||||||
|
|
||||||
@@ -423,7 +423,7 @@ LocalSettings = {
|
|||||||
|
|
||||||
### 9.1 `src/components/ui/`
|
### 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 视觉效果
|
- `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
|
### 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 })` |
|
| 发起 GET/POST | `apiFetch(`${getBackendBaseURL()}/api/...`, { method, body })` |
|
||||||
| 发起 SSE 聊天 | `useThreadStream({ threadId, context, ... })` |
|
| 发起 SSE 聊天 | `useThreadStream({ threadId, context, ... })` |
|
||||||
| 跨标签同步偏好 | `useLocalSettings()` / `useThreadSettings(threadId)` |
|
| 跨标签同步偏好 | `useLocalSettings()` / `useThreadSettings(threadId)` |
|
||||||
| 弹 toast | `import { toast } from "sonner"; toast.success("done")` |
|
| 弹全局消息 | `import { toast } from "@/core/ui/feedback"; toast.success("done")` |
|
||||||
| 弹浏览器通知 | `useNotification().showNotification(title, { body })` |
|
| 弹浏览器通知 | `useNotification().showNotification(title, { body })` |
|
||||||
| 国际化 | `const { t } = useI18n(); t.common.loading` |
|
| 国际化 | `const { t } = useI18n(); t.common.loading` |
|
||||||
| 合并 className | `cn("base", cond && "x-y")` |
|
| 合并 className | `cn("base", cond && "x-y")` |
|
||||||
|
|||||||
@@ -76,9 +76,25 @@
|
|||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<script>
|
||||||
|
// 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 === "/" || /\/$/.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" />
|
||||||
<title>CM 助手</title>
|
<title>CM 助手</title>
|
||||||
<script src="/runtime-config.js" data-runtime-config></script>
|
<script src="%BASE_URL%runtime-config.js" data-runtime-config></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -88,7 +88,6 @@
|
|||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"remark-math": "^6.0.0",
|
"remark-math": "^6.0.0",
|
||||||
"shiki": "3.15.0",
|
"shiki": "3.15.0",
|
||||||
"sonner": "^2.0.7",
|
|
||||||
"streamdown": "1.4.0",
|
"streamdown": "1.4.0",
|
||||||
"tailwind-merge": "^3.4.0",
|
"tailwind-merge": "^3.4.0",
|
||||||
"tdesign-react": "^1.12.3",
|
"tdesign-react": "^1.12.3",
|
||||||
@@ -9743,14 +9742,6 @@
|
|||||||
"@types/hast": "^3.0.4"
|
"@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": {
|
"node_modules/sortablejs": {
|
||||||
"version": "1.15.7",
|
"version": "1.15.7",
|
||||||
"resolved": "https://registry.npmjs.org/sortablejs/-/sortablejs-1.15.7.tgz",
|
"resolved": "https://registry.npmjs.org/sortablejs/-/sortablejs-1.15.7.tgz",
|
||||||
|
|||||||
@@ -11,16 +11,24 @@
|
|||||||
"build:network": "node --max-old-space-size=8192 ./node_modules/vite/bin/vite.js build --mode network",
|
"build:network": "node --max-old-space-size=8192 ./node_modules/vite/bin/vite.js build --mode network",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
|
"test:thread-history": "node scripts/test-thread-history.mjs",
|
||||||
"test:input-mode": "node --experimental-strip-types --test src/components/workspace/input-mode.test.ts",
|
"test:input-mode": "node --experimental-strip-types --test src/components/workspace/input-mode.test.ts",
|
||||||
"test:answer-feedback": "node --experimental-strip-types --test src/components/workspace/agents/agent-feedback-visibility.test.ts src/components/workspace/messages/answer-feedback-eligibility.test.ts src/strategy-components/api/answer-feedback-batching.test.ts",
|
"test:answer-feedback": "node --experimental-strip-types --test src/components/workspace/agents/agent-feedback-visibility.test.ts src/components/workspace/messages/answer-feedback-eligibility.test.ts src/strategy-components/api/answer-feedback-batching.test.ts",
|
||||||
"test:retrieval-debug": "node --experimental-strip-types --test src/core/llmwiki/retrieval-debug.test.ts",
|
"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: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: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: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",
|
"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: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": {
|
"dependencies": {
|
||||||
"@codemirror/lang-css": "^6.3.1",
|
"@codemirror/lang-css": "^6.3.1",
|
||||||
@@ -104,7 +112,6 @@
|
|||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"remark-math": "^6.0.0",
|
"remark-math": "^6.0.0",
|
||||||
"shiki": "3.15.0",
|
"shiki": "3.15.0",
|
||||||
"sonner": "^2.0.7",
|
|
||||||
"streamdown": "1.4.0",
|
"streamdown": "1.4.0",
|
||||||
"tailwind-merge": "^3.4.0",
|
"tailwind-merge": "^3.4.0",
|
||||||
"tdesign-react": "^1.12.3",
|
"tdesign-react": "^1.12.3",
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ window.__CM_RUNTIME_CONFIG__ = {
|
|||||||
|
|
||||||
// 地图瓦片地址模板:仅供普通问答消息列表中的交互地图使用。
|
// 地图瓦片地址模板:仅供普通问答消息列表中的交互地图使用。
|
||||||
// 后续接入内网瓦片服务时,只需替换此项并保留 {z}/{x}/{y} 占位符。
|
// 后续接入内网瓦片服务时,只需替换此项并保留 {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。
|
// routeKey 短路由的用户名直登口令:例如 #/login/admin?routeKey=a。
|
||||||
// 填值时优先使用这里的 password;留空时使用 URL 中的 ?password=。
|
// 填值时优先使用这里的 password;留空时使用 URL 中的 ?password=。
|
||||||
@@ -112,6 +112,9 @@ window.__CM_RUNTIME_CONFIG__ = {
|
|||||||
// A 系统跳转地址:人物、组织、事件等列表项打开链接使用。
|
// A 系统跳转地址:人物、组织、事件等列表项打开链接使用。
|
||||||
VITE_AIPI_PRESENT_URL: "http://present.a.uat.4.cn/present/domain",
|
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 根地址。
|
// B 系统 knowes 根地址。
|
||||||
VITE_AIPI_KNOWES_URL: "http://ch1.b.uat.4.cn/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",
|
VITE_USE_REAL_DATA: "true",
|
||||||
|
|
||||||
// 登录深链任务详情是否使用本地 mock:false=真实接口;true=本地 mock。
|
// 登录深链任务详情是否使用本地 mock:false=真实接口;true=本地 mock。
|
||||||
|
// 为 true 时同时拦截 xdfx 的 task-action/actionDetail 与 mainnets/narratives-by-name。
|
||||||
VITE_MOCK_COP_TASK_DETAIL: "false",
|
VITE_MOCK_COP_TASK_DETAIL: "false",
|
||||||
|
|
||||||
// 岗位会商完整演示数据:true=启动时幂等写入后端;后端不可用时直接使用前端 JSON 兜底。
|
// 岗位会商完整演示数据:true=启动时幂等写入后端;后端不可用时直接使用前端 JSON 兜底。
|
||||||
@@ -143,6 +147,10 @@ window.__CM_RUNTIME_CONFIG__ = {
|
|||||||
// 静态站点模式开关;一般部署业务系统时保持 false。
|
// 静态站点模式开关;一般部署业务系统时保持 false。
|
||||||
VITE_STATIC_WEBSITE_ONLY: "false",
|
VITE_STATIC_WEBSITE_ONLY: "false",
|
||||||
|
|
||||||
|
// 知识库页面是否显示“列表 / 卡片”视图切换。默认 false:固定使用紧凑列表;
|
||||||
|
// 改为 true 并刷新页面后,才允许用户切换到卡片视图。
|
||||||
|
VITE_KNOWLEDGE_VIEW_SWITCH_ENABLED: "false",
|
||||||
|
|
||||||
// 紧凑导航开关:true 时固定使用简洁布局,工作台左侧栏收起为菜单图标,
|
// 紧凑导航开关:true 时固定使用简洁布局,工作台左侧栏收起为菜单图标,
|
||||||
// 隐藏系统 Logo、换肤按钮以及“全量/简洁模式”切换。修改后刷新页面即可生效。
|
// 隐藏系统 Logo、换肤按钮以及“全量/简洁模式”切换。修改后刷新页面即可生效。
|
||||||
VITE_FORCE_COLLAPSED_SIDEBAR: "false",
|
VITE_FORCE_COLLAPSED_SIDEBAR: "false",
|
||||||
|
|||||||
@@ -93,6 +93,21 @@ const requiredLegacyFallbacks = [
|
|||||||
pattern: /AbortSignal\.timeout = function/,
|
pattern: /AbortSignal\.timeout = function/,
|
||||||
description: "Chrome 102 needs AbortSignal.timeout before any module loads",
|
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",
|
file: "src/styles/globals.css",
|
||||||
pattern: /\.workspace-chat-bg,\s*\n\s*\.canvas-writing-bg\s*\{\s*background-color:\s*var\(--background\);/,
|
pattern: /\.workspace-chat-bg,\s*\n\s*\.canvas-writing-bg\s*\{\s*background-color:\s*var\(--background\);/,
|
||||||
|
|||||||
@@ -9,13 +9,19 @@ const require = createRequire(import.meta.url);
|
|||||||
// transitive esbuild binary in node_modules/.bin, and tests must run offline.
|
// transitive esbuild binary in node_modules/.bin, and tests must run offline.
|
||||||
const viteRequire = createRequire(require.resolve("vite/package.json"));
|
const viteRequire = createRequire(require.resolve("vite/package.json"));
|
||||||
const { build, stop } = viteRequire("esbuild");
|
const { build, stop } = viteRequire("esbuild");
|
||||||
const testNames = ["login-entry", "session-validation"];
|
const testEntries = {
|
||||||
|
"login-attempt": "src/core/auth/login-attempt.test.ts",
|
||||||
|
"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");
|
const outputDirectory = path.join(root, ".runtime/unit-tests");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await build({
|
await build({
|
||||||
absWorkingDir: root,
|
absWorkingDir: root,
|
||||||
entryPoints: testNames.map((name) => `src/core/auth/${name}.test.ts`),
|
entryPoints: testEntries,
|
||||||
outdir: outputDirectory,
|
outdir: outputDirectory,
|
||||||
outExtension: { ".js": ".mjs" },
|
outExtension: { ".js": ".mjs" },
|
||||||
bundle: true,
|
bundle: true,
|
||||||
@@ -26,7 +32,7 @@ try {
|
|||||||
stop();
|
stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = spawnSync(process.execPath, ["--test", ...testNames.map((name) => path.join(outputDirectory, `${name}.test.mjs`))], {
|
const result = spawnSync(process.execPath, ["--test", ...Object.keys(testEntries).map((name) => path.join(outputDirectory, `${name}.mjs`))], {
|
||||||
cwd: root,
|
cwd: root,
|
||||||
stdio: "inherit",
|
stdio: "inherit",
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { createRequire } from "node:module";
|
||||||
|
import { dirname, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
|
||||||
|
// Use Vite's installed bundler, including pnpm layouts without a root esbuild bin.
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const viteRequire = createRequire(require.resolve("vite/package.json"));
|
||||||
|
const { build } = viteRequire("esbuild");
|
||||||
|
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||||
|
const suites = [
|
||||||
|
"src/core/threads/background-history.test.ts",
|
||||||
|
"src/core/api/stream-cursor-replay.test.ts",
|
||||||
|
"src/core/threads/stream-display.test.ts",
|
||||||
|
"src/core/threads/stream-recovery.test.ts",
|
||||||
|
"src/core/threads/stream-terminal-recovery.test.ts",
|
||||||
|
"src/core/threads/stream-reasoning-replay.test.ts",
|
||||||
|
"src/core/threads/project-metadata.test.ts",
|
||||||
|
];
|
||||||
|
const outdir = resolve(root, ".runtime/unit-tests/thread-history");
|
||||||
|
await build({
|
||||||
|
absWorkingDir: root, entryPoints: suites, outbase: "src/core", outdir,
|
||||||
|
bundle: true, platform: "node", format: "esm", define: { "import.meta.env": "{}" }, logLevel: "warning",
|
||||||
|
});
|
||||||
|
const files = suites.map((suite) => resolve(outdir, suite.replace("src/core/", "").replace(/\.ts$/, ".js")));
|
||||||
|
const result = spawnSync(process.execPath, ["--test", ...files], { cwd: root, stdio: "inherit" });
|
||||||
|
if (result.error) throw result.error;
|
||||||
|
process.exitCode = result.status ?? 1;
|
||||||
@@ -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" });
|
||||||
|
});
|
||||||
@@ -1,16 +1,18 @@
|
|||||||
import { useEffect, useMemo } from "react";
|
import { lazy, Suspense, useEffect, useMemo } from "react";
|
||||||
import { Navigate, Route, Routes } from "react-router-dom";
|
import { Navigate, Route, Routes } from "react-router-dom";
|
||||||
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
||||||
|
|
||||||
import { DesensitizeWordsLoader } from "@/components/desensitize-words-loader";
|
import { DesensitizeWordsLoader } from "@/components/desensitize-words-loader";
|
||||||
import { FontScaleApplier } from "@/components/font-scale";
|
import { FontScaleApplier } from "@/components/font-scale";
|
||||||
import { QueryClientProvider } from "@/components/query-client-provider";
|
import { QueryClientProvider } from "@/components/query-client-provider";
|
||||||
|
import { RouteLoadingFallback } from "@/components/route-loading";
|
||||||
import { AuthSyncWatcher } from "@/core/auth/sync";
|
import { AuthSyncWatcher } from "@/core/auth/sync";
|
||||||
import { RequireAccount } from "@/core/auth/require-account";
|
import { RequireAccount } from "@/core/auth/require-account";
|
||||||
import { I18nProvider } from "@/core/i18n/context";
|
import { I18nProvider } from "@/core/i18n/context";
|
||||||
import { fetchYLogConfig } from "@/core/log/y-log-config";
|
import { fetchYLogConfig } from "@/core/log/y-log-config";
|
||||||
import { detectLocale } from "@/core/i18n/locale";
|
import { detectLocale } from "@/core/i18n/locale";
|
||||||
import { resolveForcedThemeForPath } from "@/core/page-layout/chats-iframe-route";
|
import { resolveForcedThemeForPath } from "@/core/page-layout/chats-iframe-route";
|
||||||
|
import { resolveB51ForcedTheme } from "@/core/auth/b5-1-theme";
|
||||||
import { ChatProvider } from "@/contexts/ChatContext";
|
import { ChatProvider } from "@/contexts/ChatContext";
|
||||||
import { ThemeProvider } from "@/contexts/ThemeContext";
|
import { ThemeProvider } from "@/contexts/ThemeContext";
|
||||||
import {
|
import {
|
||||||
@@ -26,29 +28,47 @@ import {
|
|||||||
|
|
||||||
import { HashRouter, useLocation } from "react-router-dom";
|
import { HashRouter, useLocation } from "react-router-dom";
|
||||||
|
|
||||||
import LandingPage from "./pages/LandingPage";
|
|
||||||
import LoginPage from "./pages/LoginPage";
|
|
||||||
import RegisterPage from "./pages/RegisterPage";
|
|
||||||
import PageRoutes from "./pages/PageRoutes";
|
|
||||||
import PublicScheduledTaskPage, {
|
|
||||||
PublicScheduledTaskFullscreenPage,
|
|
||||||
} from "./pages/PublicScheduledTaskPage";
|
|
||||||
import PublicSharePage from "./pages/PublicSharePage";
|
|
||||||
import PublicLeaderboardPage from "./pages/PublicLeaderboardPage";
|
|
||||||
import PublicRoundtableSharePage from "./pages/PublicRoundtableSharePage";
|
|
||||||
import EmbedChatPage from "./pages/EmbedChatPage";
|
|
||||||
import EmbedRoundtablePage from "./pages/EmbedRoundtablePage";
|
|
||||||
import SiteStudioPage from "./pages/site-studio/SiteStudioPage";
|
|
||||||
import DashboardStandalonePage from "@/roundtable-planning/pages/DashboardStandalonePage";
|
|
||||||
import PositionRoundtablePage from "@/position-roundtable/pages/PositionRoundtablePage";
|
|
||||||
import WeKnoraWikiPageView from "@/strategy-components/components/resource-management/llmwiki/WeKnoraWikiPageView";
|
|
||||||
import {
|
import {
|
||||||
isPositionRoundtableStandaloneMode,
|
isPositionRoundtableStandaloneMode,
|
||||||
POSITION_ROUNDTABLE_ROUTE,
|
POSITION_ROUNDTABLE_ROUTE,
|
||||||
} from "@/position-roundtable/demo/position-roundtable-demo-config";
|
} from "@/position-roundtable/demo/position-roundtable-demo-config";
|
||||||
import { ChatRuntime } from "./pages/WorkspaceRoutes";
|
|
||||||
import { NotFoundPage } from "./pages/NotFoundPage";
|
const LandingPage = lazy(() => import("./pages/LandingPage"));
|
||||||
import OfficialDeerFlowEntry from "./pages/OfficialDeerFlowEntry";
|
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) => ({
|
||||||
|
default: module.PublicScheduledTaskFullscreenPage,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
const PublicSharePage = lazy(() => import("./pages/PublicSharePage"));
|
||||||
|
const PublicLeaderboardPage = lazy(() => import("./pages/PublicLeaderboardPage"));
|
||||||
|
const PublicRoundtableSharePage = lazy(() => import("./pages/PublicRoundtableSharePage"));
|
||||||
|
const EmbedChatPage = lazy(() => import("./pages/EmbedChatPage"));
|
||||||
|
const EmbedRoundtablePage = lazy(() => import("./pages/EmbedRoundtablePage"));
|
||||||
|
const SiteStudioPage = lazy(() => import("./pages/site-studio/SiteStudioPage"));
|
||||||
|
const DashboardStandalonePage = lazy(
|
||||||
|
() => import("@/roundtable-planning/pages/DashboardStandalonePage"),
|
||||||
|
);
|
||||||
|
const PositionRoundtablePage = lazy(
|
||||||
|
() => import("@/position-roundtable/pages/PositionRoundtablePage"),
|
||||||
|
);
|
||||||
|
const WeKnoraWikiPageView = lazy(
|
||||||
|
() => import("@/strategy-components/components/resource-management/llmwiki/WeKnoraWikiPageView"),
|
||||||
|
);
|
||||||
|
const ChatRuntime = lazy(() =>
|
||||||
|
import("@/components/workspace/chat-runtime").then((module) => ({
|
||||||
|
default: module.ChatRuntime,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
const NotFoundPage = lazy(() =>
|
||||||
|
import("./pages/NotFoundPage").then((module) => ({
|
||||||
|
default: module.NotFoundPage,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
const OfficialDeerFlowEntry = lazy(() => import("./pages/OfficialDeerFlowEntry"));
|
||||||
|
|
||||||
const PUBLIC_EMBED_PREFIXES = [
|
const PUBLIC_EMBED_PREFIXES = [
|
||||||
"/share/",
|
"/share/",
|
||||||
@@ -62,6 +82,7 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
|||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const publicEmbedTheme = usePublicEmbedTheme();
|
const publicEmbedTheme = usePublicEmbedTheme();
|
||||||
const positionStandaloneMode = isPositionRoundtableStandaloneMode();
|
const positionStandaloneMode = isPositionRoundtableStandaloneMode();
|
||||||
|
const markdownToolMode = location.pathname.replace(/\/+$/, "") === "/tools/md-to-word";
|
||||||
// iframe 嵌入会话(按标签页 sessionStorage)集中在此同步:任何带 `&embed=1` 的入口(深链登录页
|
// iframe 嵌入会话(按标签页 sessionStorage)集中在此同步:任何带 `&embed=1` 的入口(深链登录页
|
||||||
// 或直接深链路由)一进来就启用、`embed=0` 关闭,后续干净路由靠会话维持去 chrome + 强制主题。
|
// 或直接深链路由)一进来就启用、`embed=0` 关闭,后续干净路由靠会话维持去 chrome + 强制主题。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -70,10 +91,14 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
|||||||
// 操作日志(Y-Log):启动早期预热上报配置,使 writeYLog 同步读缓存即可工作
|
// 操作日志(Y-Log):启动早期预热上报配置,使 writeYLog 同步读缓存即可工作
|
||||||
// (刷新后 module 缓存清空,token 登录用户也能继续上报)。失败静默。
|
// (刷新后 module 缓存清空,token 登录用户也能继续上报)。失败静默。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (positionStandaloneMode) return;
|
if (positionStandaloneMode || markdownToolMode) return;
|
||||||
void fetchYLogConfig();
|
void fetchYLogConfig();
|
||||||
}, [positionStandaloneMode]);
|
}, [positionStandaloneMode, markdownToolMode]);
|
||||||
const forcedTheme = useMemo(() => {
|
const forcedTheme = useMemo(() => {
|
||||||
|
// b5-1 任务分析深链最高优先:接入方传 ?theme= 用传入值,不传默认深蓝。
|
||||||
|
// 先于 embed 判定,避免 embed=1 缺省 light 盖掉本页的深蓝默认。
|
||||||
|
const b51Theme = resolveB51ForcedTheme(location.pathname, location.search);
|
||||||
|
if (b51Theme) return b51Theme;
|
||||||
// iframe 嵌入模式(外部系统 `&embed=1`)最高优先:按本标签页的嵌入主题强制明/暗。
|
// iframe 嵌入模式(外部系统 `&embed=1`)最高优先:按本标签页的嵌入主题强制明/暗。
|
||||||
// 走 next-themes forcedTheme(不写 localStorage)→ 同浏览器另开的正常系统页不受影响。
|
// 走 next-themes forcedTheme(不写 localStorage)→ 同浏览器另开的正常系统页不受影响。
|
||||||
const embedTheme = resolveForcedEmbedTheme(location.search);
|
const embedTheme = resolveForcedEmbedTheme(location.search);
|
||||||
@@ -112,15 +137,17 @@ function AppProviders({ children }: { children: React.ReactNode }) {
|
|||||||
forcedTheme={forcedTheme}
|
forcedTheme={forcedTheme}
|
||||||
>
|
>
|
||||||
<QueryClientProvider>
|
<QueryClientProvider>
|
||||||
<AuthSyncWatcher disabled={positionStandaloneMode}>
|
<AuthSyncWatcher disabled={positionStandaloneMode || markdownToolMode}>
|
||||||
<I18nProvider initialLocale={locale}>
|
<I18nProvider initialLocale={locale}>
|
||||||
<ThemeProvider>
|
{markdownToolMode ? children : (
|
||||||
<ChatProvider>
|
<ThemeProvider>
|
||||||
{!positionStandaloneMode && <DesensitizeWordsLoader />}
|
<ChatProvider>
|
||||||
<FontScaleApplier />
|
{!positionStandaloneMode && <DesensitizeWordsLoader />}
|
||||||
{children}
|
<FontScaleApplier />
|
||||||
</ChatProvider>
|
{children}
|
||||||
</ThemeProvider>
|
</ChatProvider>
|
||||||
|
</ThemeProvider>
|
||||||
|
)}
|
||||||
</I18nProvider>
|
</I18nProvider>
|
||||||
</AuthSyncWatcher>
|
</AuthSyncWatcher>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
@@ -143,6 +170,9 @@ function RootRedirect() {
|
|||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
const positionStandaloneMode = isPositionRoundtableStandaloneMode();
|
const positionStandaloneMode = isPositionRoundtableStandaloneMode();
|
||||||
|
const standaloneLoginRedirect = (
|
||||||
|
<Navigate to={POSITION_ROUNDTABLE_ROUTE} replace />
|
||||||
|
);
|
||||||
const pageElement = positionStandaloneMode ? (
|
const pageElement = positionStandaloneMode ? (
|
||||||
<RequireAccount allowLegacyAnonymous>
|
<RequireAccount allowLegacyAnonymous>
|
||||||
<ChatRuntime>
|
<ChatRuntime>
|
||||||
@@ -156,66 +186,77 @@ export function App() {
|
|||||||
return (
|
return (
|
||||||
<HashRouter>
|
<HashRouter>
|
||||||
<AppProviders>
|
<AppProviders>
|
||||||
<Routes>
|
<Suspense fallback={<RouteLoadingFallback />}>
|
||||||
<Route path="/" element={<RootRedirect />} />
|
<Routes>
|
||||||
<Route
|
<Route path="/" element={<RootRedirect />} />
|
||||||
path="/login"
|
<Route
|
||||||
element={<LoginPage />}
|
path="/login"
|
||||||
/>
|
element={
|
||||||
<Route
|
positionStandaloneMode ? standaloneLoginRedirect : <LoginPage />
|
||||||
path="/login/:username"
|
}
|
||||||
element={<LoginPage />}
|
/>
|
||||||
/>
|
<Route
|
||||||
<Route
|
path="/login/:username"
|
||||||
path="/register"
|
element={
|
||||||
element={<RegisterPage />}
|
positionStandaloneMode ? standaloneLoginRedirect : <LoginPage />
|
||||||
/>
|
}
|
||||||
<Route path="/landing" element={<LandingPage />} />
|
/>
|
||||||
<Route path="/share/:shareCode" element={<PublicSharePage />} />
|
<Route path="/landing" element={<LandingPage />} />
|
||||||
<Route path="/public/leaderboard" element={<PublicLeaderboardPage />} />
|
{/* Anonymous standalone tool: no workspace navigation or login gate. */}
|
||||||
<Route
|
<Route
|
||||||
path="/roundtable-share/:shareCode"
|
path="/tools/md-to-word"
|
||||||
element={<PublicRoundtableSharePage view="landing" />}
|
element={
|
||||||
/>
|
<div className="h-dvh overflow-hidden">
|
||||||
<Route
|
<MarkdownDocxEditorPage />
|
||||||
path="/roundtable-share/:shareCode/report"
|
</div>
|
||||||
element={<PublicRoundtableSharePage view="report" />}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route path="/share/:shareCode" element={<PublicSharePage />} />
|
||||||
path="/roundtable-share/:shareCode/dashboard"
|
<Route path="/public/leaderboard" element={<PublicLeaderboardPage />} />
|
||||||
element={<PublicRoundtableSharePage view="dashboard" />}
|
<Route
|
||||||
/>
|
path="/roundtable-share/:shareCode"
|
||||||
<Route
|
element={<PublicRoundtableSharePage view="landing" />}
|
||||||
path="/public/scheduled-tasks/:taskId"
|
/>
|
||||||
element={<PublicScheduledTaskPage />}
|
<Route
|
||||||
/>
|
path="/roundtable-share/:shareCode/report"
|
||||||
<Route
|
element={<PublicRoundtableSharePage view="report" />}
|
||||||
path="/public/scheduled-tasks/:taskId/runs/:runId/fullscreen"
|
/>
|
||||||
element={<PublicScheduledTaskFullscreenPage />}
|
<Route
|
||||||
/>
|
path="/roundtable-share/:shareCode/dashboard"
|
||||||
<Route
|
element={<PublicRoundtableSharePage view="dashboard" />}
|
||||||
path="/embed/chats/:thread_id"
|
/>
|
||||||
element={
|
<Route
|
||||||
<ChatRuntime>
|
path="/public/scheduled-tasks/:taskId"
|
||||||
<EmbedChatPage />
|
element={<PublicScheduledTaskPage />}
|
||||||
</ChatRuntime>
|
/>
|
||||||
}
|
<Route
|
||||||
/>
|
path="/public/scheduled-tasks/:taskId/runs/:runId/fullscreen"
|
||||||
<Route path="/embed/roundtable" element={<EmbedRoundtablePage />} />
|
element={<PublicScheduledTaskFullscreenPage />}
|
||||||
<Route
|
/>
|
||||||
path="/embed/knowledge/:noteId"
|
<Route
|
||||||
element={<WeKnoraWikiPageView publicEmbed />}
|
path="/embed/chats/:thread_id"
|
||||||
/>
|
element={
|
||||||
<Route
|
<ChatRuntime>
|
||||||
path="/roundtable-dashboard"
|
<EmbedChatPage />
|
||||||
element={<RequireAccount><DashboardStandalonePage /></RequireAccount>}
|
</ChatRuntime>
|
||||||
/>
|
}
|
||||||
<Route path="/official/*" element={<RequireAccount><OfficialDeerFlowEntry /></RequireAccount>} />
|
/>
|
||||||
{/* Web App 站点预览工作室:独立路由 + 独立视觉风格(无主应用 chrome) */}
|
<Route path="/embed/roundtable" element={<EmbedRoundtablePage />} />
|
||||||
<Route path="/sites/:threadId/:siteName" element={<RequireAccount><SiteStudioPage /></RequireAccount>} />
|
<Route
|
||||||
<Route path="/page/*" element={pageElement} />
|
path="/embed/knowledge/:noteId"
|
||||||
<Route path="*" element={<NotFoundPage />} />
|
element={<WeKnoraWikiPageView publicEmbed />}
|
||||||
</Routes>
|
/>
|
||||||
|
<Route
|
||||||
|
path="/roundtable-dashboard"
|
||||||
|
element={<RequireAccount><DashboardStandalonePage /></RequireAccount>}
|
||||||
|
/>
|
||||||
|
<Route path="/official/*" element={<RequireAccount><OfficialDeerFlowEntry /></RequireAccount>} />
|
||||||
|
{/* Web App 站点预览工作室:独立路由 + 独立视觉风格(无主应用 chrome) */}
|
||||||
|
<Route path="/sites/:threadId/:siteName" element={<RequireAccount><SiteStudioPage /></RequireAccount>} />
|
||||||
|
<Route path="/page/*" element={pageElement} />
|
||||||
|
<Route path="*" element={<NotFoundPage />} />
|
||||||
|
</Routes>
|
||||||
|
</Suspense>
|
||||||
</AppProviders>
|
</AppProviders>
|
||||||
</HashRouter>
|
</HashRouter>
|
||||||
);
|
);
|
||||||
|
|||||||
|
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,
|
useRef,
|
||||||
useState,
|
useState,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Provider Context & Types
|
// Provider Context & Types
|
||||||
@@ -998,11 +998,24 @@ export const PromptInputTextarea = ({
|
|||||||
|
|
||||||
// Chrome 109 ignores field-sizing: content. Preserve the same 4rem–12rem
|
// 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
|
// 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";
|
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.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
|
// onInput does not run for a controlled value filled by a suggested question
|
||||||
@@ -1212,7 +1225,7 @@ export const PromptInputButton = ({
|
|||||||
}: PromptInputButtonProps) => {
|
}: PromptInputButtonProps) => {
|
||||||
return (
|
return (
|
||||||
<InputGroupButton
|
<InputGroupButton
|
||||||
className={cn(className)}
|
className={cn("agent-composer-tool", className)}
|
||||||
size="sm"
|
size="sm"
|
||||||
type="button"
|
type="button"
|
||||||
variant={variant}
|
variant={variant}
|
||||||
@@ -1293,9 +1306,10 @@ export const PromptInputSubmit = ({
|
|||||||
<InputGroupButton
|
<InputGroupButton
|
||||||
aria-label={ariaLabel}
|
aria-label={ariaLabel}
|
||||||
className={cn(
|
className={cn(
|
||||||
"transition-all duration-300",
|
// 皮肤本体在 globals.css 的 .agent-composer-send(主题色扁平渐变
|
||||||
status === "streaming" &&
|
// 圆钮);流式态切 .agent-composer-send--stop 低对比停止钮。
|
||||||
"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",
|
"agent-composer-send transition-all duration-300",
|
||||||
|
status === "streaming" && "agent-composer-send--stop",
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
size={size}
|
size={size}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { FileOutput } from "lucide-react";
|
import { FileOutput } from "lucide-react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import responsibilityIcon from "@/assets/position-roundtable/责任岗位.svg";
|
import responsibilityIcon from "@/assets/position-roundtable/责任岗位.svg";
|
||||||
import resultTimeIcon 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,13 +24,19 @@ import {
|
|||||||
Trash2,
|
Trash2,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { readRuntimeEnv } from "@/env";
|
import { readRuntimeEnv } from "@/env";
|
||||||
|
import "./document-upload-popup.css";
|
||||||
import { queryClient } from "@/components/query-client-provider";
|
import { queryClient } from "@/components/query-client-provider";
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import Empty from "./empty";
|
import Empty from "./empty";
|
||||||
import { NetworkActor } from "./network-actor";
|
import { NetworkActor } from "./network-actor";
|
||||||
|
import {
|
||||||
|
normalizeV2UploadSources,
|
||||||
|
type StudioUploadSource,
|
||||||
|
type V2UploadResponse,
|
||||||
|
} from "@/core/studio/document-upload";
|
||||||
|
|
||||||
// ── 适配层 ─────────────────────────────────────────────────
|
// ── 适配层 ─────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -86,22 +92,7 @@ interface DocumentUploadDialogContextType {
|
|||||||
data?: { query: string; mode: string }
|
data?: { query: string; mode: string }
|
||||||
) => Promise<void>;
|
) => Promise<void>;
|
||||||
// 上传成功回调,返回上传的来源信息
|
// 上传成功回调,返回上传的来源信息
|
||||||
onUploadComplete?: (sources: Array<{ id?: number; title: string; task_id?: string; status: string }>) => void;
|
onUploadComplete?: (sources: StudioUploadSource[]) => void;
|
||||||
}
|
|
||||||
|
|
||||||
// ── 任务轮询类型 ─────────────────────────────────────────────
|
|
||||||
interface TaskSource {
|
|
||||||
task_id: string;
|
|
||||||
title: string;
|
|
||||||
status: 'processing' | 'success' | 'error';
|
|
||||||
source_type: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UploadResponse {
|
|
||||||
status: string;
|
|
||||||
uploaded: number;
|
|
||||||
skipped: number;
|
|
||||||
sources: TaskSource[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface listDataItem {
|
interface listDataItem {
|
||||||
@@ -224,7 +215,7 @@ export const DocumentUploadDialogProvider: FC<{
|
|||||||
) => void | Promise<void>;
|
) => void | Promise<void>;
|
||||||
searchSpace: { id: number | string;[key: string]: unknown };
|
searchSpace: { id: number | string;[key: string]: unknown };
|
||||||
onUploadSuccess?: () => void;
|
onUploadSuccess?: () => void;
|
||||||
onUploadComplete?: (sources: Array<{ id?: number; title: string; task_id?: string; status: string }>) => void;
|
onUploadComplete?: (sources: StudioUploadSource[]) => void;
|
||||||
}> = ({ children, onClose, searchSpace, onUploadSuccess, onUploadComplete }) => {
|
}> = ({ children, onClose, searchSpace, onUploadSuccess, onUploadComplete }) => {
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const [initialSearchText, setInitialSearchText] = useState("");
|
const [initialSearchText, setInitialSearchText] = useState("");
|
||||||
@@ -353,27 +344,23 @@ const DocumentUploadPopupContent: FC<{
|
|||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
formData.append("files", file);
|
formData.append("files", file);
|
||||||
}
|
}
|
||||||
const res = await fetch(`${backendUrl}/api/v1/documents/fileupload`, {
|
const res = await fetch(`${backendUrl}/api/v1/documents/fileupload-v2`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
body: formData,
|
body: formData,
|
||||||
});
|
});
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const data = await res.json() as UploadResponse;
|
const data = await res.json() as V2UploadResponse;
|
||||||
// 调用上传完成回调,传递来源信息
|
// 调用上传完成回调,传递来源信息
|
||||||
if (data.sources && data.sources.length > 0) {
|
if (data.sources && data.sources.length > 0) {
|
||||||
onUploadComplete?.(data.sources.map(s => ({
|
onUploadComplete?.(normalizeV2UploadSources(data));
|
||||||
id: undefined, // 后端返回的数据中暂时没有 id
|
|
||||||
title: s.title,
|
|
||||||
task_id: s.task_id,
|
|
||||||
status: s.status,
|
|
||||||
})));
|
|
||||||
}
|
}
|
||||||
toast.success(`上传成功 ${data.uploaded || files.length} 个文件`);
|
toast.success(`上传成功 ${data.uploaded || files.length} 个文件`);
|
||||||
// 只关闭上传弹窗
|
// 只关闭上传弹窗
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
} else {
|
} else {
|
||||||
toast.error("上传失败,请重试");
|
const payload = await res.json().catch(() => null) as { detail?: string } | null;
|
||||||
|
toast.error(payload?.detail || `上传失败(HTTP ${res.status})`);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
toast.error("上传失败,请重试");
|
toast.error("上传失败,请重试");
|
||||||
@@ -410,7 +397,6 @@ const DocumentUploadPopupContent: FC<{
|
|||||||
selectedSearchSources.map((s) => ({
|
selectedSearchSources.map((s) => ({
|
||||||
id: undefined,
|
id: undefined,
|
||||||
title: s.title,
|
title: s.title,
|
||||||
task_id: undefined,
|
|
||||||
status: "success" as const,
|
status: "success" as const,
|
||||||
}))
|
}))
|
||||||
);
|
);
|
||||||
@@ -614,11 +600,13 @@ const DocumentUploadPopupContent: FC<{
|
|||||||
};
|
};
|
||||||
|
|
||||||
const yUserId = getYUserId();
|
const yUserId = getYUserId();
|
||||||
|
const notebookToken = getNotebookToken();
|
||||||
|
const iframeTokenParam = notebookToken ? `&token=${encodeURIComponent(notebookToken)}` : "";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||||
<DialogContent
|
<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()}
|
onPointerDownOutside={(e) => e.preventDefault()}
|
||||||
onInteractOutside={(e) => e.preventDefault()}
|
onInteractOutside={(e) => e.preventDefault()}
|
||||||
>
|
>
|
||||||
@@ -628,7 +616,7 @@ const DocumentUploadPopupContent: FC<{
|
|||||||
<div className="h-full overflow-y-auto">
|
<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="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
|
<Textarea
|
||||||
placeholder="搜索资料..."
|
placeholder="搜索资料..."
|
||||||
value={searchText}
|
value={searchText}
|
||||||
@@ -639,24 +627,24 @@ const DocumentUploadPopupContent: FC<{
|
|||||||
searchDataChange();
|
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}
|
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} />
|
<Search className="h-4 w-4" strokeWidth={1.5} />
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={searchDataChange}
|
onClick={searchDataChange}
|
||||||
disabled={isSearching || !searchText.trim()}
|
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>}
|
{isSearching ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <span>搜索</span>}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tab 标签页 */}
|
{/* 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">
|
<div className="flex flex-nowrap overflow-x-auto">
|
||||||
{(
|
{(
|
||||||
[
|
[
|
||||||
@@ -670,12 +658,12 @@ const DocumentUploadPopupContent: FC<{
|
|||||||
<button
|
<button
|
||||||
key={key}
|
key={key}
|
||||||
onClick={() => void searchActiveChange(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}
|
{label}
|
||||||
{activeTab === key && (
|
{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>
|
</button>
|
||||||
))}
|
))}
|
||||||
@@ -687,7 +675,7 @@ const DocumentUploadPopupContent: FC<{
|
|||||||
{activeTab === "search" && !isSearching && (
|
{activeTab === "search" && !isSearching && (
|
||||||
<iframe
|
<iframe
|
||||||
className="w-full h-[calc(100vh-200px)]"
|
className="w-full h-[calc(100vh-200px)]"
|
||||||
src={`${knowesUrl}/fromB1?yUserId=${yUserId}&processType=searchMode&bookChatId=${searchSpaceId}&inputValue=${searchValue}`}
|
src={`${knowesUrl}/fromB1?yUserId=${yUserId}&processType=searchMode&bookChatId=${searchSpaceId}&inputValue=${searchValue}${iframeTokenParam}`}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -695,7 +683,7 @@ const DocumentUploadPopupContent: FC<{
|
|||||||
{activeTab === "Y" && !isSearching && (
|
{activeTab === "Y" && !isSearching && (
|
||||||
<iframe
|
<iframe
|
||||||
className="w-full h-[calc(100vh-200px)]"
|
className="w-full h-[calc(100vh-200px)]"
|
||||||
src={`${knowledgeUrl}/#/sousou?chatType=new-chat&bookChatId=${searchSpaceId}&inputValue=${searchText}`}
|
src={`${knowledgeUrl}/#/sousou?chatType=new-chat&bookChatId=${searchSpaceId}&inputValue=${searchText}${iframeTokenParam}`}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
useState,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
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 { Button } from "@/components/ui/button";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { authenticatedFetch } from "@/components/assistant-ui/document-upload-popup";
|
import { authenticatedFetch } from "@/components/assistant-ui/document-upload-popup";
|
||||||
import { readRuntimeEnv } from "@/env";
|
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 {
|
interface NetworkActorProps {
|
||||||
@@ -22,7 +43,6 @@ interface NetworkActorProps {
|
|||||||
|
|
||||||
interface platformItem {
|
interface platformItem {
|
||||||
title: string;
|
title: string;
|
||||||
icon: string;
|
|
||||||
checked: boolean;
|
checked: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,6 +51,14 @@ interface languageItem {
|
|||||||
checked: boolean;
|
checked: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ActorSearchFilters {
|
||||||
|
platforms: string[];
|
||||||
|
languages: string[];
|
||||||
|
direction: string;
|
||||||
|
sortBy: string;
|
||||||
|
sortDirection: "asc" | "desc";
|
||||||
|
}
|
||||||
|
|
||||||
interface PoliticsDirItem {
|
interface PoliticsDirItem {
|
||||||
地区: string;
|
地区: string;
|
||||||
语言: 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 {
|
interface UserDataItem {
|
||||||
comment_count: number;
|
comment_count: number;
|
||||||
country: string | null;
|
country: string | null;
|
||||||
@@ -114,9 +222,9 @@ interface UserDataItem {
|
|||||||
birthday: string | null;
|
birthday: string | null;
|
||||||
is_virtual: number;
|
is_virtual: number;
|
||||||
isMedia: number;
|
isMedia: number;
|
||||||
hx_info: hx_info;
|
hx_info?: hx_info | null;
|
||||||
gender: string | null;
|
gender: string | null;
|
||||||
agentInfo: PoliticsDirItem;
|
agentInfo?: PoliticsDirItem | null;
|
||||||
profile_url: string | null;
|
profile_url: string | null;
|
||||||
tagId: string[];
|
tagId: string[];
|
||||||
user_name: string;
|
user_name: string;
|
||||||
@@ -152,15 +260,15 @@ interface UserDataItem {
|
|||||||
|
|
||||||
export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkActorProps) {
|
export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkActorProps) {
|
||||||
const [platforms, setPlatforms] = useState<platformItem[]>([
|
const [platforms, setPlatforms] = useState<platformItem[]>([
|
||||||
{ title: 'X', icon: 'x.png', checked: false },
|
{ title: 'X', checked: false },
|
||||||
{ title: 'Facebook', icon: 'facebook.png', checked: false },
|
{ title: 'Facebook', checked: false },
|
||||||
{ title: 'Reddit', icon: 'reddit.png', checked: false },
|
{ title: 'Reddit', checked: false },
|
||||||
{ title: 'PTT', icon: 'ptt.png', checked: false },
|
{ title: 'PTT', checked: false },
|
||||||
{ title: 'YouTube', icon: 'youtube.png', checked: false },
|
{ title: 'YouTube', checked: false },
|
||||||
{ title: 'Dcard', icon: 'dcard.png', checked: false },
|
{ title: 'Dcard', checked: false },
|
||||||
{ title: 'Mobile01', icon: 'mobile01.png', checked: false },
|
{ title: 'Mobile01', checked: false },
|
||||||
{ title: 'Threads', icon: 'threads.png', checked: false },
|
{ title: 'Threads', checked: false },
|
||||||
{ title: 'Instagram', icon: 'ins.png', checked: false },
|
{ title: 'Instagram', checked: false },
|
||||||
]);
|
]);
|
||||||
const platformList = useRef<string[]>([]);
|
const platformList = useRef<string[]>([]);
|
||||||
const [languages, setLanguages] = useState<languageItem[]>([
|
const [languages, setLanguages] = useState<languageItem[]>([
|
||||||
@@ -188,25 +296,37 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
|||||||
const [directionType, setDirectionType] = useState<string>('TW');
|
const [directionType, setDirectionType] = useState<string>('TW');
|
||||||
const directionValue = useRef<string>('TW');
|
const directionValue = useRef<string>('TW');
|
||||||
const consumerUrl = readRuntimeEnv("VITE_AIPI_CONSUMER_URL") || 'https://ch1.b.uat.4.cn/consumer';
|
const consumerUrl = readRuntimeEnv("VITE_AIPI_CONSUMER_URL") || 'https://ch1.b.uat.4.cn/consumer';
|
||||||
const backendUrl = typeof window !== 'undefined'
|
const minioProxyUrl = readRuntimeEnv("VITE_AIPI_MINIO_PROXY_URL") || 'http://minio-proxy.b.sit.4.cn/facebook-proxy';
|
||||||
? (readRuntimeEnv("VITE_BACKEND_BASE_URL") || 'http://localhost:8001')
|
const actorBaseUrl = readRuntimeEnv("VITE_AIPI_B2ACTOR_URL") || 'http://ty.b.uat.4.cn';
|
||||||
: 'http://localhost:8001';
|
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 [selectedSearchSources, setSelectedSearchSources] = useState<UserDataItem[]>([]);
|
||||||
const [isImporting, setIsImporting] = useState(false);
|
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);
|
setIsSearching(true);
|
||||||
|
const filters = resolveSearchFilters(overrides);
|
||||||
if (searchValue.current === 'network') {
|
if (searchValue.current === 'network') {
|
||||||
await agentUserSearch();
|
await agentUserSearch(filters);
|
||||||
} else {
|
} else {
|
||||||
await agentGroupSearch();
|
await agentGroupSearch(filters);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const setDirectionChange = async (type: string) => {
|
const setDirectionChange = async (type: string) => {
|
||||||
setDirectionType(type);
|
setDirectionType(type);
|
||||||
directionValue.current = type;
|
directionValue.current = type;
|
||||||
await searchChange();
|
await searchChange({ direction: type });
|
||||||
};
|
};
|
||||||
|
|
||||||
const searchTypeChange = async (value: string) => {
|
const searchTypeChange = async (value: string) => {
|
||||||
@@ -216,135 +336,128 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
|||||||
};
|
};
|
||||||
|
|
||||||
const allPlatformChange = async () => {
|
const allPlatformChange = async () => {
|
||||||
|
const nextPlatforms = platforms.map((item) => ({ ...item, checked: false }));
|
||||||
setAllPlatforms(true);
|
setAllPlatforms(true);
|
||||||
setPlatforms((prev) => prev.map((item) => ({ ...item, checked: false })));
|
setPlatforms(nextPlatforms);
|
||||||
platformList.current = [];
|
platformList.current = [];
|
||||||
await searchChange();
|
await searchChange({ platforms: [] });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleTogglePlatform = async (index: number) => {
|
const handleTogglePlatform = async (index: number) => {
|
||||||
setPlatforms((prev) => {
|
const nextPlatforms = platforms.map((item, itemIndex) => (
|
||||||
const newPlatforms = prev.map((item, i) =>
|
itemIndex === index ? { ...item, checked: !item.checked } : item
|
||||||
i === index ? { ...item, checked: !item.checked } : item
|
));
|
||||||
);
|
const checkedTitles = nextPlatforms.filter((item) => item.checked).map((item) => item.title);
|
||||||
const checkedTitles = newPlatforms.filter((item) => item.checked).map((item) => item.title);
|
setPlatforms(nextPlatforms);
|
||||||
platformList.current = checkedTitles;
|
platformList.current = checkedTitles;
|
||||||
setAllPlatforms(newPlatforms.every((item) => !item.checked));
|
setAllPlatforms(checkedTitles.length === 0);
|
||||||
return newPlatforms;
|
await searchChange({ platforms: checkedTitles });
|
||||||
});
|
|
||||||
await searchChange();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const allLanguageChange = async () => {
|
const allLanguageChange = async () => {
|
||||||
|
const nextLanguages = languages.map((item) => ({ ...item, checked: false }));
|
||||||
setAllLanguage(true);
|
setAllLanguage(true);
|
||||||
setLanguages((prev) => prev.map((item) => ({ ...item, checked: false })));
|
setLanguages(nextLanguages);
|
||||||
languageList.current = [];
|
languageList.current = [];
|
||||||
await searchChange();
|
await searchChange({ languages: [] });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleToggleLanguage = async (index: number) => {
|
const handleToggleLanguage = async (index: number) => {
|
||||||
setLanguages((prev) => {
|
const nextLanguages = languages.map((item, itemIndex) => (
|
||||||
const newItems = prev.map((item, i) =>
|
itemIndex === index ? { ...item, checked: !item.checked } : item
|
||||||
i === index ? { ...item, checked: !item.checked } : item
|
));
|
||||||
);
|
const checkedTitles = nextLanguages.filter((item) => item.checked).map((item) => item.title);
|
||||||
const checkedTitles = newItems.filter((item) => item.checked).map((item) => item.title);
|
setLanguages(nextLanguages);
|
||||||
languageList.current = checkedTitles;
|
languageList.current = checkedTitles;
|
||||||
setAllLanguage(newItems.every((item) => !item.checked));
|
setAllLanguage(checkedTitles.length === 0);
|
||||||
return newItems;
|
await searchChange({ languages: checkedTitles });
|
||||||
});
|
|
||||||
await searchChange();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const sortTypeChange = async (type: string) => {
|
const sortTypeChange = async (type: string) => {
|
||||||
|
const nextSortDirection = (sortValue.current === 'desc' ? 'asc' : 'desc') as ActorSearchFilters["sortDirection"];
|
||||||
setSortType(type);
|
setSortType(type);
|
||||||
sortTypeValue.current = type;
|
sortTypeValue.current = type;
|
||||||
sortValue.current = sortValue.current === 'desc' ? 'asc' : 'desc';
|
sortValue.current = nextSortDirection;
|
||||||
if (type === 'fans_count') setFansSort(sortValue.current);
|
if (type === 'fans_count') setFansSort(nextSortDirection);
|
||||||
else if (type === '_score') setRelevanceSort(sortValue.current);
|
else if (type === '_score') setRelevanceSort(nextSortDirection);
|
||||||
await searchChange();
|
await searchChange({ sortBy: type, sortDirection: nextSortDirection });
|
||||||
};
|
};
|
||||||
|
|
||||||
const agentUserSearch = async () => {
|
const agentUserSearch = async (filters: ActorSearchFilters) => {
|
||||||
try {
|
try {
|
||||||
const response = await authenticatedFetch(`${consumerUrl}/portrait/agentUser`, {
|
const response = await authenticatedFetch(`${consumerUrl}/portrait/agentUser`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer admin' },
|
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer admin' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
historyKey: [],
|
historyKey: ['党政要员'],
|
||||||
historyTitle: '',
|
historyTitle: '',
|
||||||
keyword: searchText,
|
keyword: searchText,
|
||||||
language: languageList.current,
|
language: filters.languages,
|
||||||
page: 1,
|
page: 1,
|
||||||
limit: 12,
|
limit: 12,
|
||||||
platform: platformList.current,
|
platform: filters.platforms,
|
||||||
politicalStand: directionValue.current,
|
politicalStand: filters.direction,
|
||||||
sort: sortTypeValue.current,
|
sort: filters.sortBy,
|
||||||
asc: sortValue.current,
|
asc: filters.sortDirection,
|
||||||
typeKeyword: 9,
|
typeKeyword: 9,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (response.ok) {
|
if (!response.ok) return;
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setIsSearching(false);
|
const result: UserDataItem[] = Array.isArray(data?.data?.list) ? data.data.list : [];
|
||||||
const result: UserDataItem[] = data.data.list;
|
result.forEach((item) => {
|
||||||
result.forEach((item) => {
|
item.profile_image = avatarUrl(item.profile_image);
|
||||||
item.profile_image = item.profile_image
|
item.classification = `${item.political_stand ?? ''}-${item.history_key ?? ''}-${item.history_title ?? ''}`;
|
||||||
? `http://minio-proxy.b.sit.4.cn/facebook-proxy?url=${item.profile_image}&is_avatar=true`
|
item.title = item.user_name || item.screen_name || item.user_id;
|
||||||
: 'http://ty.b.uat.4.cn/manage/img/default.png';
|
item.content = item.agentInfo?.['账号描述'] || item.hx_info?.['用户画像']?.['账号描述'] || '';
|
||||||
item.classification = `${item.political_stand}-${item.history_key}-${item.history_title}`;
|
item.url = `http://ty.b.uat.4.cn/fromB/toDetail?user_id=${item.user_id}&platform=${item.platform}`;
|
||||||
item.title = item.user_name || item.screen_name || item.user_id;
|
});
|
||||||
item.content = item.agentInfo['账号描述'];
|
setUserList(result);
|
||||||
item.url = `http://ty.b.uat.4.cn/fromB/toDetail?user_id=${item.user_id}&platform=${item.platform}`;
|
setSelNetCount(data?.data?.total ?? 0);
|
||||||
});
|
setActorCount(data?.data?.zs_total ?? 0);
|
||||||
setUserList(result);
|
|
||||||
setSelNetCount(data.data.total);
|
|
||||||
setActorCount(data.data.zs_total);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Search error:', error);
|
console.error('Search error:', error);
|
||||||
|
} finally {
|
||||||
|
setIsSearching(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const agentGroupSearch = async () => {
|
const agentGroupSearch = async (filters: ActorSearchFilters) => {
|
||||||
try {
|
try {
|
||||||
const response = await authenticatedFetch(`${consumerUrl}/portrait/agentGroup`, {
|
const response = await authenticatedFetch(`${consumerUrl}/portrait/agentGroup`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer admin' },
|
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer admin' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
historyKey: [],
|
historyKey: ['党政要员'],
|
||||||
historyTitle: '',
|
historyTitle: '',
|
||||||
keyword: searchText,
|
keyword: searchText,
|
||||||
language: languageList.current,
|
language: filters.languages,
|
||||||
page: 1,
|
page: 1,
|
||||||
limit: 12,
|
limit: 12,
|
||||||
platform: platformList.current,
|
platform: filters.platforms,
|
||||||
politicalStand: directionValue.current,
|
politicalStand: filters.direction,
|
||||||
sort: sortTypeValue.current,
|
sort: filters.sortBy,
|
||||||
asc: sortValue.current,
|
asc: filters.sortDirection,
|
||||||
typeKeyword: 9,
|
typeKeyword: 9,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (response.ok) {
|
if (!response.ok) return;
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setIsSearching(false);
|
const result: UserDataItem[] = Array.isArray(data?.data?.data) ? data.data.data : [];
|
||||||
const result: UserDataItem[] = data.data.data;
|
result.forEach((item) => {
|
||||||
result.forEach((item) => {
|
item.hobbies = item.groupDiscussTags || [];
|
||||||
item.hobbies = item.groupDiscussTags || [];
|
item.profile_image = avatarUrl(item.profile_image);
|
||||||
item.profile_image = item.profile_image
|
item.classification = `${item.political_stand ?? ''}`;
|
||||||
? `http://minio-proxy.b.sit.4.cn/facebook-proxy?url=${item.profile_image}&is_avatar=true`
|
item.title = item.group_name || item.groupName;
|
||||||
: 'http://ty.b.uat.4.cn/manage/img/default.png';
|
item.content = item.hx_info?.['用户画像']?.['账号描述'] || item.agentInfo?.['账号描述'] || '';
|
||||||
item.classification = `${item.political_stand}`;
|
item.url = '';
|
||||||
item.title = item.group_name || item.groupName;
|
});
|
||||||
if (item.hx_info?.['用户画像']) {
|
setUserList(result);
|
||||||
item.content = item.hx_info['用户画像']['账号描述'];
|
setActorCount(data?.data?.total ?? 0);
|
||||||
}
|
|
||||||
item.url = '';
|
|
||||||
});
|
|
||||||
setUserList(result);
|
|
||||||
setActorCount(data.data.total);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Search error:', error);
|
console.error('Search error:', error);
|
||||||
|
} finally {
|
||||||
|
setIsSearching(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -411,122 +524,128 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="network-actor">
|
||||||
<div className="bg-white rounded-[5px] p-[10px]">
|
<div className="network-actor__filter-surface bg-white rounded-[5px] p-[10px]">
|
||||||
<div className="border border-[#e8e8e8] rounded-[5px] p-[10px]">
|
<div className="network-actor__filter-panel border border-[#e8e8e8] rounded-[5px] p-[10px]">
|
||||||
<div className="mb-[10px] flex">
|
<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-1 min-w-0">
|
||||||
<span className="flex items-center gap-[10px] flex-wrap">
|
<span className="flex items-center gap-[10px] flex-wrap">
|
||||||
<span
|
<button
|
||||||
className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${allPlatforms ? 'platform-active' : ''}`}
|
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()}
|
onClick={() => void allPlatformChange()}
|
||||||
>全部</span>
|
>全部</button>
|
||||||
{platforms.map((item, index) => (
|
{platforms.map((item, index) => (
|
||||||
<span
|
<button
|
||||||
|
type="button"
|
||||||
key={index}
|
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)}
|
onClick={() => void handleTogglePlatform(index)}
|
||||||
>
|
>
|
||||||
<img src={`/platform/${item.icon}`} className="w-[24px]" alt="" />
|
<PlatformIcon platform={item.title} className="h-5 w-5" />
|
||||||
<span className="w-[2px] h-[12px] ml-[5px] mr-[5px] bg-[#dbdbdb]"></span>
|
<span className="network-actor__platform-divider mx-2 h-3 w-px bg-[#dbdbdb]" aria-hidden="true"></span>
|
||||||
<span className="ml-[5px]">{item.title}</span>
|
<span>{item.title}</span>
|
||||||
</span>
|
</button>
|
||||||
))}
|
))}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-[10px] flex">
|
<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-1 min-w-0">
|
||||||
<span className="flex items-center gap-[10px] flex-wrap">
|
<span className="flex items-center gap-[10px] flex-wrap">
|
||||||
<span
|
<button
|
||||||
className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${allLanguage ? 'platform-active' : ''}`}
|
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()}
|
onClick={() => void allLanguageChange()}
|
||||||
>全部</span>
|
>全部</button>
|
||||||
{languages.map((item, index) => (
|
{languages.map((item, index) => (
|
||||||
<span
|
<button
|
||||||
|
type="button"
|
||||||
key={index}
|
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)}
|
onClick={() => void handleToggleLanguage(index)}
|
||||||
>
|
>
|
||||||
<span>{item.title}</span>
|
<span>{item.title}</span>
|
||||||
</span>
|
</button>
|
||||||
))}
|
))}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-[10px] flex">
|
<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-1 min-w-0">
|
||||||
<span className="flex items-center gap-[10px] flex-wrap">
|
<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>
|
<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>
|
||||||
<span className={`flex items-center cursor-pointer border border-[transparent] pl-[10px] pr-[10px] ${directionType === 'US' ? 'platform-active' : ''}`} onClick={() => void setDirectionChange('US')}>U方向</span>
|
<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>
|
||||||
<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 === '其他'} 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>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-[10px] flex">
|
<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-1 min-w-0">
|
||||||
<span className="flex items-center gap-[10px] flex-wrap">
|
<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>
|
<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>
|
||||||
<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 === '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>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="bg-white rounded-[5px] pt-[15px] mt-[10px]">
|
<div className="network-actor__results-surface 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-header flex items-center justify-between pb-[10px] mb-[10px] border-b border-b-[#f1f3f5]">
|
||||||
<div className="flex items-center ml-[10px]">
|
<div className="flex items-center ml-[10px]">
|
||||||
<div className="title-bar mr-[8px]"></div>
|
<div className="network-actor__title-accent mr-2 h-5 w-1 rounded-full bg-[#cf1322]"></div>
|
||||||
<div className="text-[#454859]">用户表格管理</div>
|
<div className="network-actor__section-title text-[#454859]">用户表格管理</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
<div
|
<button
|
||||||
className={`relative flex items-center cursor-pointer border ${sortType === 'fans_count' ? 'border-[#cf1322]' : ''} p-[7px] pl-[10px] pr-[20px] rounded-[5px]`}
|
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')}
|
onClick={() => void sortTypeChange('fans_count')}
|
||||||
>
|
>
|
||||||
<span className="leading-[16px]">粉丝数排序</span>
|
<span className="leading-[16px]">粉丝数排序</span>
|
||||||
<div className="ml-[10px]">
|
<span className="ml-2"><SortDirectionIcon direction={fansSort as "asc" | "desc"} active={sortType === 'fans_count'} /></span>
|
||||||
<div className={`sort-up ${fansSort === 'asc' ? 'sort-up-active' : ''}`}></div>
|
</button>
|
||||||
<div className={`mt-[4px] sort-down ${fansSort === 'desc' ? 'sort-down-active' : ''}`}></div>
|
<button
|
||||||
</div>
|
type="button"
|
||||||
</div>
|
aria-label={`按相关度排序,当前${relevanceSort === 'asc' ? '升序' : '降序'}`}
|
||||||
<div
|
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'}`}
|
||||||
className={`relative flex items-center ml-[10px] cursor-pointer border ${sortType === '_score' ? 'border-[#cf1322]' : ''} p-[7px] pl-[10px] pr-[20px] rounded-[5px]`}
|
|
||||||
onClick={() => void sortTypeChange('_score')}
|
onClick={() => void sortTypeChange('_score')}
|
||||||
>
|
>
|
||||||
<span className="leading-[16px]">相关度排序</span>
|
<span className="leading-[16px]">相关度排序</span>
|
||||||
<div className="ml-[10px]">
|
<span className="ml-2"><SortDirectionIcon direction={relevanceSort as "asc" | "desc"} active={sortType === '_score'} /></span>
|
||||||
<div className={`sort-up ${relevanceSort === 'asc' ? 'sort-up-active' : ''}`}></div>
|
</button>
|
||||||
<div className={`mt-[4px] sort-down ${relevanceSort === 'desc' ? 'sort-down-active' : ''}`}></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{searchType === 'network' && (
|
{searchType === 'network' && (
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center ml-[35px]">
|
<div className="network-actor__metric flex items-center ml-[35px]">
|
||||||
<img className="w-[24px] h-[24px]" src="/icon/group-yellow-logo.svg" alt="" />
|
<MetaIcon type="network" className="h-6 w-6 text-[#d97b00]" />
|
||||||
<div className="ml-[5px]">
|
<div className="ml-[5px]">
|
||||||
<div className="text-[#454859] leading-[16px]">当前选中网络XWT数</div>
|
<div className="network-actor__metric-label text-[#454859] leading-[16px]">当前选中网络XWT数</div>
|
||||||
<div className="text-[#d97b00] leading-[16px] mt-[5px]">{selNetCount}</div>
|
<div className="network-actor__metric-value network-actor__metric-value--selected text-[#d97b00] leading-[16px] mt-[5px]">{selNetCount}</div>
|
||||||
</div>
|
</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]`}>
|
<div className={`network-actor__metric flex items-center ${searchType === 'network' ? 'ml-[5px]' : 'ml-[20px]'} mr-[25px]`}>
|
||||||
<img className="w-[24px] h-[24px]" src="/icon/group-red-logo.svg" alt="" />
|
<MetaIcon type="network" className="h-6 w-6 text-[#cf1322]" />
|
||||||
<div className="ml-[5px]">
|
<div className="ml-[5px]">
|
||||||
<div className="text-[#454859] leading-[16px]">网络XWT总数</div>
|
<div className="network-actor__metric-label text-[#454859] leading-[16px]">网络XWT总数</div>
|
||||||
<div className="text-[#cf1322] leading-[16px] mt-[5px]">{actorCount}</div>
|
<div className="network-actor__metric-value network-actor__metric-value--total text-[#cf1322] leading-[16px] mt-[5px]">{actorCount}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{selectedSearchSources.length > 0 && (
|
{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>
|
<span className="text-sm text-gray-600">已选中 {selectedSearchSources.length} 项</span>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Button size="sm" variant="outline" onClick={handleBatchDelete} className="h-8 px-3 text-sm">
|
<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" />
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : 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) => (
|
{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]">
|
<div className="absolute top-[5px] right-[10px]">
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
@@ -563,21 +686,21 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center mb-[10px] cursor-pointer" onClick={() => linkToB2(item)}>
|
<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="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="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 justify-between mb-[10px]">
|
||||||
<div className="flex items-center">
|
<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>
|
<span>粉丝数:{item.fans_count || '-'}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center">
|
<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>
|
<span>{item.platform}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center">
|
<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>
|
<span>实体人:{item.name}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -585,29 +708,29 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
|
|||||||
<div className="cursor-pointer" onClick={() => linkToB2(item)}>
|
<div className="cursor-pointer" onClick={() => linkToB2(item)}>
|
||||||
<div className="flex items-center mb-[10px]">
|
<div className="flex items-center mb-[10px]">
|
||||||
<div className="w-[70px] flex items-center">
|
<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>
|
<span>分类:</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<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>
|
</div>
|
||||||
<div className="flex items-center mb-[10px]">
|
<div className="flex items-center mb-[10px]">
|
||||||
<div className="w-[70px] flex items-center">
|
<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>
|
<span>标签:</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex flex-wrap items-center gap-[5px]">
|
<div className="flex flex-wrap items-center gap-[5px]">
|
||||||
{(item.hobbies ?? []).map((hobbie) => (
|
{(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>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-baseline mb-[10px]">
|
<div className="flex items-baseline mb-[10px]">
|
||||||
<div className="w-[70px] flex items-center">
|
<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>
|
<span>简介:</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ export function HtmlPreviewFrame({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<iframe
|
<iframe
|
||||||
|
key={url ?? "html-preview"}
|
||||||
title="HTML 预览"
|
title="HTML 预览"
|
||||||
sandbox="allow-scripts allow-forms"
|
sandbox="allow-scripts allow-forms"
|
||||||
src={url}
|
src={url}
|
||||||
|
|||||||
@@ -443,6 +443,25 @@
|
|||||||
background-size: 152px 42px;
|
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 {
|
.third-submenu-bar {
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 34;
|
z-index: 34;
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/** Lightweight, dependency-free fallback used while a route chunk loads. */
|
||||||
|
export function RouteLoadingFallback() {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="text-muted-foreground flex size-full min-h-32 items-center justify-center gap-2 bg-background"
|
||||||
|
role="status"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="border-muted-foreground/30 border-t-foreground size-4 animate-spin rounded-full border-2"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<span className="text-sm">正在加载页面…</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -52,6 +52,7 @@ function ResizablePanel({
|
|||||||
function ResizableHandle({
|
function ResizableHandle({
|
||||||
withHandle,
|
withHandle,
|
||||||
className,
|
className,
|
||||||
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof ResizablePrimitive.Separator> & {
|
}: React.ComponentProps<typeof ResizablePrimitive.Separator> & {
|
||||||
withHandle?: boolean;
|
withHandle?: boolean;
|
||||||
@@ -70,6 +71,7 @@ function ResizableHandle({
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
|
{children}
|
||||||
{withHandle && (
|
{withHandle && (
|
||||||
<div className="bg-border z-10 flex h-8 w-4 items-center justify-center rounded-sm border shadow-sm">
|
<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" />
|
<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 { Plus, Trash2 } from "lucide-react";
|
||||||
import { useEffect, useMemo, useState } from "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 { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -136,7 +136,12 @@ export function FolderManageDialog({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleRename = async (folderId: string, current: string) => {
|
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;
|
if (next === null) return;
|
||||||
try {
|
try {
|
||||||
await rename.mutateAsync({ folderId, path: next });
|
await rename.mutateAsync({ folderId, path: next });
|
||||||
@@ -147,7 +152,11 @@ export function FolderManageDialog({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = async (folderId: string, path: string) => {
|
const handleDelete = async (folderId: string, path: string) => {
|
||||||
if (!window.confirm(`删除目录「${path}」?其中的知识将变为未归类(不会被删除)。`)) return;
|
if (!(await confirmAction(`删除目录「${path}」?其中的知识将变为未归类(不会被删除)。`, {
|
||||||
|
title: "删除目录?",
|
||||||
|
confirmText: "删除",
|
||||||
|
danger: true,
|
||||||
|
}))) return;
|
||||||
try {
|
try {
|
||||||
await remove.mutateAsync({ folderId });
|
await remove.mutateAsync({ folderId });
|
||||||
toast.success("目录已删除");
|
toast.success("目录已删除");
|
||||||
@@ -292,7 +301,11 @@ export function ExtractTemplateManageDialog({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = async (t: KnowledgeExtractTemplate) => {
|
const handleDelete = async (t: KnowledgeExtractTemplate) => {
|
||||||
if (!window.confirm(`删除模板「${t.name}」?`)) return;
|
if (!(await confirmAction(`删除模板「${t.name}」?`, {
|
||||||
|
title: "删除模板?",
|
||||||
|
confirmText: "删除",
|
||||||
|
danger: true,
|
||||||
|
}))) return;
|
||||||
try {
|
try {
|
||||||
await remove.mutateAsync(t.id);
|
await remove.mutateAsync(t.id);
|
||||||
if (selectedId === t.id) setSelectedId(null);
|
if (selectedId === t.id) setSelectedId(null);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
|||||||
import { languages } from "@codemirror/language-data";
|
import { languages } from "@codemirror/language-data";
|
||||||
import { basicLightInit } from "@uiw/codemirror-theme-basic";
|
import { basicLightInit } from "@uiw/codemirror-theme-basic";
|
||||||
import { monokaiInit } from "@uiw/codemirror-theme-monokai";
|
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 { useTheme } from "next-themes";
|
||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
|
|
||||||
@@ -29,13 +29,13 @@ export function MarkdownCodeEditor({
|
|||||||
}) {
|
}) {
|
||||||
const { resolvedTheme } = useTheme();
|
const { resolvedTheme } = useTheme();
|
||||||
const extensions = useMemo(
|
const extensions = useMemo(
|
||||||
() => [markdown({ base: markdownLanguage, codeLanguages: languages })],
|
() => [markdown({ base: markdownLanguage, codeLanguages: languages }), EditorView.lineWrapping],
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("grid min-h-[46vh] overflow-hidden rounded-lg border bg-background lg:grid-cols-2", className)}>
|
<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-h-0 flex-col border-b lg:border-r lg:border-b-0">
|
<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">
|
<div className="flex h-9 shrink-0 items-center border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground">
|
||||||
Markdown 编辑
|
Markdown 编辑
|
||||||
</div>
|
</div>
|
||||||
@@ -50,14 +50,14 @@ export function MarkdownCodeEditor({
|
|||||||
highlightActiveLineGutter: false,
|
highlightActiveLineGutter: false,
|
||||||
lineNumbers: true,
|
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>
|
||||||
<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 className="flex h-9 shrink-0 items-center border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground">
|
||||||
实时渲染
|
实时渲染
|
||||||
</div>
|
</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
|
<MarkdownContent
|
||||||
content={value || "*暂无正文*"}
|
content={value || "*暂无正文*"}
|
||||||
isLoading={false}
|
isLoading={false}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ExternalLink, Sparkles } from "lucide-react";
|
import { ExternalLink, Sparkles } from "lucide-react";
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -45,6 +45,8 @@ function HeaderButton({
|
|||||||
|
|
||||||
/** Light 56px wiki header: plain page title on the left, action entries on the right. */
|
/** Light 56px wiki header: plain page title on the left, action entries on the right. */
|
||||||
export function WikiHeader({
|
export function WikiHeader({
|
||||||
|
title = "知识库管理",
|
||||||
|
description,
|
||||||
onToggleSidebar,
|
onToggleSidebar,
|
||||||
onImportFile,
|
onImportFile,
|
||||||
onBatchImport,
|
onBatchImport,
|
||||||
@@ -55,6 +57,8 @@ export function WikiHeader({
|
|||||||
onManageTemplates,
|
onManageTemplates,
|
||||||
extraActions,
|
extraActions,
|
||||||
}: {
|
}: {
|
||||||
|
title?: string;
|
||||||
|
description?: string;
|
||||||
onToggleSidebar: () => void;
|
onToggleSidebar: () => void;
|
||||||
onImportFile: () => void;
|
onImportFile: () => void;
|
||||||
onBatchImport: () => void;
|
onBatchImport: () => void;
|
||||||
@@ -66,8 +70,13 @@ export function WikiHeader({
|
|||||||
extraActions?: ReactNode;
|
extraActions?: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
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">
|
<header
|
||||||
<div className="flex items-center gap-3">
|
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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onToggleSidebar}
|
onClick={onToggleSidebar}
|
||||||
@@ -76,8 +85,15 @@ export function WikiHeader({
|
|||||||
>
|
>
|
||||||
<Menu className="size-5" />
|
<Menu className="size-5" />
|
||||||
</button>
|
</button>
|
||||||
<div className="text-base font-semibold tracking-tight text-slate-900 dark:text-slate-100">
|
<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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Check, Loader2, Pencil, Plus, Trash2, X } from "lucide-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 { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ function UserInfoPanel({ user }: { user: UserListItem }) {
|
|||||||
<Badge variant="secondary">普通用户</Badge>
|
<Badge variant="secondary">普通用户</Badge>
|
||||||
)}
|
)}
|
||||||
</dd>
|
</dd>
|
||||||
<dt className="text-muted-foreground font-medium">问答次数</dt>
|
<dt className="text-muted-foreground font-medium">近30天问答次数</dt>
|
||||||
<dd className="tabular-nums">{user.qa_count}</dd>
|
<dd className="tabular-nums">{user.qa_count}</dd>
|
||||||
<dt className="text-muted-foreground font-medium">Skills</dt>
|
<dt className="text-muted-foreground font-medium">Skills</dt>
|
||||||
<dd className="tabular-nums">{user.skill_count}</dd>
|
<dd className="tabular-nums">{user.skill_count}</dd>
|
||||||
@@ -304,7 +304,7 @@ export function AdminUserHub() {
|
|||||||
const [userQuery, setUserQuery] = useState("");
|
const [userQuery, setUserQuery] = useState("");
|
||||||
// 活动审计 放到前面 → 默认进入审计标签页。
|
// 活动审计 放到前面 → 默认进入审计标签页。
|
||||||
const [activeTab, setActiveTab] = useState<"audit" | "info" | "memory">("audit");
|
const [activeTab, setActiveTab] = useState<"audit" | "info" | "memory">("audit");
|
||||||
// 是否按问答次数(降序)排序用户列表。
|
// 是否按近 30 天问答次数(降序)排序用户列表。
|
||||||
const [sortByQa, setSortByQa] = useState(false);
|
const [sortByQa, setSortByQa] = useState(false);
|
||||||
|
|
||||||
const filteredUsers = useMemo(() => {
|
const filteredUsers = useMemo(() => {
|
||||||
@@ -332,7 +332,7 @@ export function AdminUserHub() {
|
|||||||
<div className="border-b px-6 py-4">
|
<div className="border-b px-6 py-4">
|
||||||
<h1 className="text-xl font-semibold">Admin 用户中心</h1>
|
<h1 className="text-xl font-semibold">Admin 用户中心</h1>
|
||||||
<p className="text-muted-foreground mt-0.5 text-sm">
|
<p className="text-muted-foreground mt-0.5 text-sm">
|
||||||
管理用户信息、审计历史问答、编辑用户记忆。
|
管理用户信息、审计近 30 天问答、编辑用户记忆。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -357,10 +357,10 @@ export function AdminUserHub() {
|
|||||||
? "border-primary/40 bg-primary/5 text-primary"
|
? "border-primary/40 bg-primary/5 text-primary"
|
||||||
: "text-muted-foreground hover:bg-muted",
|
: "text-muted-foreground hover:bg-muted",
|
||||||
)}
|
)}
|
||||||
title="按问答次数从高到低排序"
|
title="按近 30 天问答次数从高到低排序"
|
||||||
>
|
>
|
||||||
<ArrowDownWideNarrow className="size-3.5" />
|
<ArrowDownWideNarrow className="size-3.5" />
|
||||||
{sortByQa ? "按问答次数排序中" : "按问答次数排序"}
|
{sortByQa ? "按近30天问答排序中" : "按近30天问答排序"}
|
||||||
</button>
|
</button>
|
||||||
<ScrollArea className="min-h-0 flex-1">
|
<ScrollArea className="min-h-0 flex-1">
|
||||||
{usersLoading && (
|
{usersLoading && (
|
||||||
@@ -395,7 +395,7 @@ export function AdminUserHub() {
|
|||||||
)}
|
)}
|
||||||
<span
|
<span
|
||||||
className="text-muted-foreground shrink-0 tabular-nums text-xs"
|
className="text-muted-foreground shrink-0 tabular-nums text-xs"
|
||||||
title="问答次数"
|
title="近 30 天问答次数"
|
||||||
>
|
>
|
||||||
{u.qa_count ?? 0}
|
{u.qa_count ?? 0}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -3,18 +3,15 @@
|
|||||||
import {
|
import {
|
||||||
Activity,
|
Activity,
|
||||||
Gauge,
|
Gauge,
|
||||||
Loader2,
|
|
||||||
OctagonX,
|
OctagonX,
|
||||||
RefreshCw,
|
RefreshCw,
|
||||||
Square,
|
Square,
|
||||||
Zap,
|
Zap,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useId, useMemo, useState } from "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 {
|
import type {
|
||||||
ActiveRunItem,
|
ActiveRunItem,
|
||||||
ConcurrencyPoint,
|
ConcurrencyPoint,
|
||||||
@@ -35,6 +32,9 @@ import { cn } from "@/lib/utils";
|
|||||||
/** lookback window (hours) per granularity. */
|
/** lookback window (hours) per granularity. */
|
||||||
const LOOKBACK: Record<Granularity, number> = { minute: 3, hour: 48 };
|
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 {
|
function fmtBucket(iso: string, granularity: Granularity): string {
|
||||||
const date = new Date(iso);
|
const date = new Date(iso);
|
||||||
if (Number.isNaN(date.getTime())) return iso;
|
if (Number.isNaN(date.getTime())) return iso;
|
||||||
@@ -103,7 +103,11 @@ function latestOf(values: (number | null)[]): number | null {
|
|||||||
return 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({
|
function LineChart({
|
||||||
labels,
|
labels,
|
||||||
series,
|
series,
|
||||||
@@ -119,6 +123,7 @@ function LineChart({
|
|||||||
note?: string;
|
note?: string;
|
||||||
emptyHint: string;
|
emptyHint: string;
|
||||||
}) {
|
}) {
|
||||||
|
const [hoverIdx, setHoverIdx] = useState<number | null>(null);
|
||||||
const gradId = `cm-area-${useId().replace(/:/g, "")}`;
|
const gradId = `cm-area-${useId().replace(/:/g, "")}`;
|
||||||
const width = 760;
|
const width = 760;
|
||||||
const height = 220;
|
const height = 220;
|
||||||
@@ -132,17 +137,25 @@ function LineChart({
|
|||||||
const ticks = buildTicks(dataMax, integer);
|
const ticks = buildTicks(dataMax, integer);
|
||||||
const axisMax = ticks[ticks.length - 1] || 1;
|
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.
|
// Legend always renders (even with no data) so the lines are self-explanatory.
|
||||||
const legend = (
|
const legend = (
|
||||||
<div className="mb-2 flex flex-wrap items-center gap-x-4 gap-y-1">
|
<div className="mb-2 flex flex-wrap items-center gap-x-4 gap-y-1">
|
||||||
{series.map((s) => {
|
{series.map((s) => {
|
||||||
const latest = latestOf(s.values);
|
const latest = latestOf(s.values);
|
||||||
return (
|
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 }} />
|
<span className="inline-block h-[3px] w-4 rounded-full" style={{ backgroundColor: s.color }} />
|
||||||
{s.name}
|
{s.name}
|
||||||
{latest != null && (
|
{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)}
|
{Number.isInteger(latest) ? latest : latest.toFixed(1)}
|
||||||
{unit}
|
{unit}
|
||||||
</span>
|
</span>
|
||||||
@@ -154,14 +167,14 @@ function LineChart({
|
|||||||
);
|
);
|
||||||
|
|
||||||
const caption = note ? (
|
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;
|
) : null;
|
||||||
|
|
||||||
if (n === 0) {
|
if (n === 0) {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{legend}
|
{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}
|
{emptyHint}
|
||||||
</div>
|
</div>
|
||||||
{caption}
|
{caption}
|
||||||
@@ -194,92 +207,152 @@ 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`;
|
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));
|
const labelStep = Math.max(1, Math.ceil(n / 7));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{legend}
|
{legend}
|
||||||
<svg viewBox={`0 0 ${width} ${height}`} className="w-full" role="img" aria-label="时序折线图">
|
<div
|
||||||
<defs>
|
className="relative"
|
||||||
<linearGradient id={gradId} x1="0" x2="0" y1="0" y2="1">
|
onMouseMove={handleMove}
|
||||||
<stop offset="0%" stopColor={first?.color ?? "#C1121F"} stopOpacity="0.18" />
|
onMouseLeave={() => setHoverIdx(null)}
|
||||||
<stop offset="100%" stopColor={first?.color ?? "#C1121F"} stopOpacity="0.02" />
|
>
|
||||||
</linearGradient>
|
<svg viewBox={`0 0 ${width} ${height}`} className="w-full" role="img" aria-label="时序折线图">
|
||||||
</defs>
|
<defs>
|
||||||
{ticks.map((t) => {
|
<linearGradient id={gradId} x1="0" x2="0" y1="0" y2="1">
|
||||||
const y = yFor(t);
|
<stop offset="0%" stopColor={first?.color ?? BRAND_COLOR} stopOpacity="0.14" />
|
||||||
return (
|
<stop offset="100%" stopColor={first?.color ?? BRAND_COLOR} stopOpacity="0.01" />
|
||||||
<g key={t}>
|
</linearGradient>
|
||||||
<line
|
</defs>
|
||||||
x1={pad.left}
|
{ticks.map((t) => {
|
||||||
x2={width - pad.right}
|
const y = yFor(t);
|
||||||
y1={y}
|
return (
|
||||||
y2={y}
|
<g key={t}>
|
||||||
stroke="currentColor"
|
<line
|
||||||
className="text-[#E5E7EB] dark:text-[#3F3F46]"
|
x1={pad.left}
|
||||||
strokeWidth="1"
|
x2={width - pad.right}
|
||||||
|
y1={y}
|
||||||
|
y2={y}
|
||||||
|
stroke="currentColor"
|
||||||
|
className="text-border/70"
|
||||||
|
strokeWidth="1"
|
||||||
|
strokeDasharray="4 4"
|
||||||
|
/>
|
||||||
|
<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})`} />}
|
||||||
|
{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
|
||||||
|
d={linePath(s.values)}
|
||||||
|
fill="none"
|
||||||
|
stroke={s.color}
|
||||||
|
strokeWidth="2"
|
||||||
|
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` }}
|
||||||
/>
|
/>
|
||||||
<text x={pad.left - 6} y={y + 3} textAnchor="end" className="fill-[#9CA3AF] text-[10px]">
|
|
||||||
{fmtAxis(t, integer)}
|
|
||||||
</text>
|
|
||||||
</g>
|
</g>
|
||||||
);
|
))}
|
||||||
})}
|
{hoverIdx != null &&
|
||||||
{areaPath && <path d={areaPath} fill={`url(#${gradId})`} />}
|
series.map((s) => {
|
||||||
{series.map((s) => (
|
const v = s.values[hoverIdx];
|
||||||
<path
|
if (v == null) return null;
|
||||||
key={s.name}
|
return (
|
||||||
d={linePath(s.values)}
|
<circle
|
||||||
fill="none"
|
key={`${s.name}-hover`}
|
||||||
stroke={s.color}
|
cx={xFor(hoverIdx)}
|
||||||
strokeWidth="2"
|
cy={yFor(v)}
|
||||||
strokeLinecap="round"
|
r="4"
|
||||||
strokeLinejoin="round"
|
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]">
|
{labels.map((label, i) => {
|
||||||
{label}
|
if (i !== 0 && i !== n - 1 && i % labelStep !== 0) return null;
|
||||||
</text>
|
return (
|
||||||
);
|
<text key={`${label}-${i}`} x={xFor(i)} y={height - 8} textAnchor="middle" className="fill-muted-foreground text-[10px]">
|
||||||
})}
|
{label}
|
||||||
{series.map((s) =>
|
</text>
|
||||||
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}>
|
</svg>
|
||||||
<title>{`${labels[i]} · ${s.name}: ${v}${unit}`}</title>
|
{hoverIdx != null && (
|
||||||
</circle>
|
<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>
|
||||||
)}
|
)}
|
||||||
</svg>
|
</div>
|
||||||
{caption}
|
{caption}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function ChartCard({
|
/** 浅红 UI 规范的「▎标题」小节头(面板内使用)。 */
|
||||||
icon: Icon,
|
function ChartSection({
|
||||||
title,
|
title,
|
||||||
subtitle,
|
icon: Icon,
|
||||||
|
extra,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
icon: typeof Activity;
|
|
||||||
title: string;
|
title: string;
|
||||||
subtitle: string;
|
icon?: typeof Activity;
|
||||||
|
extra?: React.ReactNode;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<section className="rounded-lg border border-[#F1D6D6] bg-white p-4 shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]">
|
<div className="rounded-[5px] bg-muted/30 p-4">
|
||||||
<div className="mb-3 flex items-center gap-2">
|
<div className="mb-3 flex items-center gap-2.5">
|
||||||
<Icon className="size-4 text-[#C1121F] dark:text-[#7FACF2]" />
|
<span className="h-3.5 w-[3px] shrink-0 rounded-full bg-primary" aria-hidden />
|
||||||
<h3 className="font-semibold text-[#231815] dark:text-white">{title}</h3>
|
{Icon ? <Icon className="size-4 shrink-0 text-muted-foreground" /> : null}
|
||||||
<span className="ml-auto text-xs text-[#8B6B6B] dark:text-[#7FACF2]">{subtitle}</span>
|
<h3 className="text-sm font-semibold text-card-foreground">{title}</h3>
|
||||||
|
<span className="ml-auto text-xs text-muted-foreground">{extra}</span>
|
||||||
</div>
|
</div>
|
||||||
{children}
|
{children}
|
||||||
</section>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,36 +366,35 @@ function ActiveRunRow({
|
|||||||
stopping: boolean;
|
stopping: boolean;
|
||||||
}) {
|
}) {
|
||||||
return (
|
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="min-w-0">
|
||||||
<div className="truncate font-medium text-[#202124] dark:text-white">{run.user_name || "未知用户"}</div>
|
<div className="truncate font-medium text-card-foreground">{run.user_name || "未知用户"}</div>
|
||||||
<div className="truncate text-xs text-[#5F6368] dark:text-slate-400" title={run.thread_title}>
|
<div className="truncate text-xs text-muted-foreground" title={run.thread_title}>
|
||||||
{run.thread_title || run.thread_id}
|
{run.thread_title || run.thread_id}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0 truncate text-[#202124] dark:text-slate-100">{run.agent_name}</div>
|
<div className="min-w-0 truncate text-card-foreground">{run.agent_name}</div>
|
||||||
<Badge variant="outline" className="justify-center">
|
<Tag variant="outline" size="small" className="justify-center">
|
||||||
{run.kind}
|
{run.kind}
|
||||||
</Badge>
|
</Tag>
|
||||||
<span
|
<span className="text-center">
|
||||||
className={cn(
|
{run.status === "running" ? (
|
||||||
"text-center text-xs font-medium",
|
<Tag theme="success" variant="light" size="small">运行中</Tag>
|
||||||
run.status === "running" ? "text-[#0F766E] dark:text-teal-300" : "text-[#B45309] dark:text-amber-300",
|
) : (
|
||||||
|
<Tag theme="warning" variant="light" size="small">排队中</Tag>
|
||||||
)}
|
)}
|
||||||
>
|
|
||||||
{run.status === "running" ? "运行中" : "排队中"}
|
|
||||||
</span>
|
</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)}
|
{fmtElapsed(run.elapsed_seconds)}
|
||||||
</span>
|
</span>
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="small"
|
||||||
variant="outline"
|
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}
|
disabled={stopping}
|
||||||
|
icon={<Square className="size-3.5" />}
|
||||||
onClick={() => onStop(run.run_id)}
|
onClick={() => onStop(run.run_id)}
|
||||||
>
|
>
|
||||||
{stopping ? <Loader2 className="size-3.5 animate-spin" /> : <Square className="size-3.5" />}
|
|
||||||
停止
|
停止
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -363,8 +435,8 @@ export function ConcurrencyMonitorPanel() {
|
|||||||
return {
|
return {
|
||||||
labels: points.map((p) => fmtBucket(p.bucket, granularity)),
|
labels: points.map((p) => fmtBucket(p.bucket, granularity)),
|
||||||
series: [
|
series: [
|
||||||
{ name: "平均速度", color: "#2563EB", values: points.map((p) => p.avg_tokens_per_sec) },
|
{ name: "平均速度", color: "#2F6BFF", values: points.map((p) => p.avg_tokens_per_sec) },
|
||||||
{ name: "最慢", color: "#9333EA", values: points.map((p) => p.min_tokens_per_sec) },
|
{ name: "最慢", color: "#7C3AED", values: points.map((p) => p.min_tokens_per_sec) },
|
||||||
] as LineSeries[],
|
] as LineSeries[],
|
||||||
};
|
};
|
||||||
}, [tokenSpeed.data, granularity]);
|
}, [tokenSpeed.data, granularity]);
|
||||||
@@ -383,7 +455,11 @@ export function ConcurrencyMonitorPanel() {
|
|||||||
|
|
||||||
const handleStopAll = async () => {
|
const handleStopAll = async () => {
|
||||||
if (runs.length === 0) return;
|
if (runs.length === 0) return;
|
||||||
if (!window.confirm(`确定要停止当前全部 ${count} 个并发调用吗?这会中断这些用户正在生成的回答。`)) return;
|
if (!(await confirmAction(`确定要停止当前全部 ${count} 个并发调用吗?这会中断这些用户正在生成的回答。`, {
|
||||||
|
title: "停止全部调用?",
|
||||||
|
confirmText: "全部停止",
|
||||||
|
danger: true,
|
||||||
|
}))) return;
|
||||||
try {
|
try {
|
||||||
const res = await cancelAll.mutateAsync();
|
const res = await cancelAll.mutateAsync();
|
||||||
toast.success(`已停止 ${res.cancelled_count} 个调用`);
|
toast.success(`已停止 ${res.cancelled_count} 个调用`);
|
||||||
@@ -402,52 +478,56 @@ export function ConcurrencyMonitorPanel() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
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 */}
|
{/* header */}
|
||||||
<div className="flex flex-wrap items-center gap-3">
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
<div className="flex items-center gap-2">
|
<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" />
|
<Activity className="size-5" />
|
||||||
</span>
|
</span>
|
||||||
<div>
|
<div>
|
||||||
<div className="font-semibold text-[#231815] dark:text-white">实时并发监控</div>
|
<div className="font-semibold text-card-foreground">实时并发监控</div>
|
||||||
<div className="text-xs text-[#8B6B6B] dark:text-[#7FACF2]">
|
<div className="text-xs text-muted-foreground">
|
||||||
监控大模型并发压力,可直接停止任意对话调用
|
监控大模型并发压力,可直接停止任意对话调用
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="ml-auto flex flex-wrap items-center gap-3">
|
<div className="ml-auto flex h-8 flex-wrap items-center gap-2">
|
||||||
<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]">
|
<div className="flex h-8 items-center gap-2 rounded-[5px] bg-muted/40 px-3">
|
||||||
<span className="text-xs text-[#5F6368] dark:text-slate-300">当前并发</span>
|
<span className="text-xs text-muted-foreground">当前并发</span>
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"text-2xl font-semibold tabular-nums",
|
"text-lg font-semibold leading-none tabular-nums",
|
||||||
count > 0 ? "text-[#C1121F] dark:text-[#7FACF2]" : "text-[#202124] dark:text-white",
|
count > 0 ? "text-primary" : "text-card-foreground",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{count}
|
{count}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</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]">
|
<div className="flex h-8 items-center gap-2 rounded-[5px] bg-muted/40 px-3">
|
||||||
<span className="text-xs text-[#5F6368] dark:text-slate-300">后台采样</span>
|
<span className="text-xs text-muted-foreground">后台采样</span>
|
||||||
<Switch checked={samplerOn} onCheckedChange={handleToggleSampler} disabled={updateSettings.isPending} />
|
<Switch value={samplerOn} onChange={handleToggleSampler} loading={updateSettings.isPending} />
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" size="sm" onClick={() => refetch()} disabled={isRefetching}>
|
<Button
|
||||||
<RefreshCw className={cn("mr-1 size-4", isRefetching && "animate-spin")} />
|
variant="outline"
|
||||||
|
theme="default"
|
||||||
|
icon={<RefreshCw className={cn("size-4", isRefetching && "animate-spin")} />}
|
||||||
|
onClick={() => refetch()}
|
||||||
|
disabled={isRefetching}
|
||||||
|
>
|
||||||
刷新
|
刷新
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
theme="danger"
|
||||||
className="border-[#C1121F]/50 text-[#C1121F] hover:bg-[#FFF1F1] dark:border-rose-400/40 dark:text-rose-200"
|
icon={<OctagonX className="size-4" />}
|
||||||
onClick={handleStopAll}
|
onClick={handleStopAll}
|
||||||
disabled={cancelAll.isPending || runs.length === 0}
|
disabled={cancelAll.isPending || runs.length === 0}
|
||||||
>
|
>
|
||||||
<OctagonX className="mr-1 size-4" />
|
|
||||||
全部停止
|
全部停止
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="sm" onClick={() => setOpen((v) => !v)}>
|
<Button variant="text" theme="default" onClick={() => setOpen((v) => !v)}>
|
||||||
{open ? "收起" : "展开"}
|
{open ? "收起" : "展开"}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -456,36 +536,38 @@ export function ConcurrencyMonitorPanel() {
|
|||||||
{open && (
|
{open && (
|
||||||
<>
|
<>
|
||||||
{!samplerOn && (
|
{!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>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* granularity toggle */}
|
{/* granularity toggle */}
|
||||||
<div className="flex items-center gap-2">
|
<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>
|
||||||
{(["minute", "hour"] as Granularity[]).map((g) => (
|
<div className="lb-pill-group flex items-center gap-1.5">
|
||||||
<Button
|
{(["minute", "hour"] as Granularity[]).map((g) => (
|
||||||
key={g}
|
<Button
|
||||||
size="sm"
|
key={g}
|
||||||
variant={granularity === g ? "default" : "outline"}
|
size="small"
|
||||||
className={cn("h-7", granularity === g && "bg-[#C1121F] hover:bg-[#A50F1A] dark:bg-[#2563EB]")}
|
variant={granularity === g ? "base" : "outline"}
|
||||||
onClick={() => setGranularity(g)}
|
theme={granularity === g ? "primary" : "default"}
|
||||||
>
|
onClick={() => setGranularity(g)}
|
||||||
{g === "minute" ? "按分钟" : "按小时"}
|
>
|
||||||
</Button>
|
{g === "minute" ? "按分钟" : "按小时"}
|
||||||
))}
|
</Button>
|
||||||
<span className="text-xs text-[#8B6B6B] dark:text-[#7FACF2]">
|
))}
|
||||||
|
</div>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
{granularity === "minute" ? "近 3 小时" : "近 48 小时"}
|
{granularity === "minute" ? "近 3 小时" : "近 48 小时"}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* charts */}
|
{/* charts */}
|
||||||
<div className="grid gap-3 xl:grid-cols-2">
|
<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 ? (
|
{concurrency.isLoading ? (
|
||||||
<div className="flex h-[220px] items-center justify-center text-sm text-[#5F6368] dark:text-slate-400">
|
<div className="flex h-[220px] items-center justify-center text-sm text-muted-foreground">
|
||||||
<Loader2 className="mr-2 size-4 animate-spin" /> 加载中
|
加载中…
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<LineChart
|
<LineChart
|
||||||
@@ -497,11 +579,11 @@ export function ConcurrencyMonitorPanel() {
|
|||||||
emptyHint="暂无并发采样数据(需打开「后台采样」开关后才开始记录)"
|
emptyHint="暂无并发采样数据(需打开「后台采样」开关后才开始记录)"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</ChartCard>
|
</ChartSection>
|
||||||
<ChartCard icon={Zap} title="大模型出字速度" subtitle={`每${granularity === "hour" ? "小时" : "分钟"}一个点`}>
|
<ChartSection icon={Zap} title="大模型出字速度" extra={`每${granularity === "hour" ? "小时" : "分钟"}一个点`}>
|
||||||
{tokenSpeed.isLoading ? (
|
{tokenSpeed.isLoading ? (
|
||||||
<div className="flex h-[220px] items-center justify-center text-sm text-[#5F6368] dark:text-slate-400">
|
<div className="flex h-[220px] items-center justify-center text-sm text-muted-foreground">
|
||||||
<Loader2 className="mr-2 size-4 animate-spin" /> 加载中
|
加载中…
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<LineChart
|
<LineChart
|
||||||
@@ -512,23 +594,24 @@ export function ConcurrencyMonitorPanel() {
|
|||||||
emptyHint="暂无大模型调用记录"
|
emptyHint="暂无大模型调用记录"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</ChartCard>
|
</ChartSection>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* active run list */}
|
{/* active run list */}
|
||||||
<section className="rounded-lg border border-[#F1D6D6] bg-white dark:border-[#213D5E] dark:bg-[#02244C]">
|
<section className="overflow-hidden rounded-[5px] bg-muted/20">
|
||||||
<div className="flex items-center gap-2 border-b border-[#F1D6D6] px-3 py-2 dark:border-[#213D5E]">
|
<div className="flex items-center gap-2 border-b border-border/70 px-3 py-2">
|
||||||
<span className="font-semibold text-[#231815] dark:text-white">正在进行的调用</span>
|
<span className="h-3.5 w-[3px] rounded-full bg-primary" aria-hidden />
|
||||||
<Badge variant="outline">{count}</Badge>
|
<span className="text-sm font-semibold text-card-foreground">正在进行的调用</span>
|
||||||
{liveLoading && <Loader2 className="size-3.5 animate-spin text-[#8B6B6B]" />}
|
<Tag variant="outline" size="small">{count}</Tag>
|
||||||
|
{liveLoading && <span className="text-xs text-muted-foreground">加载中…</span>}
|
||||||
</div>
|
</div>
|
||||||
{runs.length === 0 ? (
|
{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>
|
<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>智能体</span>
|
<span>智能体</span>
|
||||||
<span className="text-center">类型</span>
|
<span className="text-center">类型</span>
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
UsersIcon,
|
UsersIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useEffect, useMemo, useState } from "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 { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -391,7 +391,11 @@ export function PositionManagementPage() {
|
|||||||
}, [positions, selectedId]);
|
}, [positions, selectedId]);
|
||||||
|
|
||||||
const handleDelete = async (p: Position) => {
|
const handleDelete = async (p: Position) => {
|
||||||
if (!window.confirm(`确认删除岗位「${p.name}」?其成员将回退到默认岗位。`)) return;
|
if (!(await confirmAction(`确认删除岗位「${p.name}」?其成员将回退到默认岗位。`, {
|
||||||
|
title: "删除岗位?",
|
||||||
|
confirmText: "删除",
|
||||||
|
danger: true,
|
||||||
|
}))) return;
|
||||||
try {
|
try {
|
||||||
await deletePosition.mutateAsync(p.id);
|
await deletePosition.mutateAsync(p.id);
|
||||||
if (selectedId === p.id) setSelectedId(null);
|
if (selectedId === p.id) setSelectedId(null);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { Loader2, PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
|
import { Loader2, PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { confirmAction, toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -172,7 +172,11 @@ export function TagManagementPage() {
|
|||||||
setDialogOpen(true);
|
setDialogOpen(true);
|
||||||
};
|
};
|
||||||
const handleDelete = async (tag: Tag) => {
|
const handleDelete = async (tag: Tag) => {
|
||||||
if (!window.confirm(t.adminTags.deleteConfirm)) return;
|
if (!(await confirmAction(t.adminTags.deleteConfirm, {
|
||||||
|
title: "删除标签?",
|
||||||
|
confirmText: "删除",
|
||||||
|
danger: true,
|
||||||
|
}))) return;
|
||||||
try {
|
try {
|
||||||
await deleteTag.mutateAsync(tag.id);
|
await deleteTag.mutateAsync(tag.id);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { AlertCircle,CheckCircle2, Download, Loader2 } from "lucide-react";
|
import { AlertCircle,CheckCircle2, Download, Loader2 } from "lucide-react";
|
||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
type ToolMetric,
|
type ToolMetric,
|
||||||
type ToolMetricsFilters,
|
type ToolMetricsFilters,
|
||||||
} from "@/core/tool-metrics/api";
|
} from "@/core/tool-metrics/api";
|
||||||
|
import { getAdminQueryDateTimeBounds } from "@/core/admin/query-window";
|
||||||
import { useToolMetrics, useToolMetricsSummary } from "@/core/tool-metrics/hooks";
|
import { useToolMetrics, useToolMetricsSummary } from "@/core/tool-metrics/hooks";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { useTheme } from "@/contexts/ThemeContext";
|
import { useTheme } from "@/contexts/ThemeContext";
|
||||||
@@ -68,6 +69,7 @@ function categoryLabel(category?: string | null): string {
|
|||||||
|
|
||||||
export function ToolMetricsPanel() {
|
export function ToolMetricsPanel() {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
|
const queryDateTimeBounds = getAdminQueryDateTimeBounds();
|
||||||
const [page, setPage] = useState(0);
|
const [page, setPage] = useState(0);
|
||||||
const [tool, setTool] = useState("");
|
const [tool, setTool] = useState("");
|
||||||
const [user, setUser] = useState("");
|
const [user, setUser] = useState("");
|
||||||
@@ -77,8 +79,8 @@ export function ToolMetricsPanel() {
|
|||||||
const [kind, setKind] = useState<KindFilter>("skill");
|
const [kind, setKind] = useState<KindFilter>("skill");
|
||||||
const [status, setStatus] = useState<StatusFilter>("all");
|
const [status, setStatus] = useState<StatusFilter>("all");
|
||||||
const [category, setCategory] = useState<string>("all");
|
const [category, setCategory] = useState<string>("all");
|
||||||
const [since, setSince] = useState("");
|
const [since, setSince] = useState(() => getAdminQueryDateTimeBounds().min);
|
||||||
const [until, setUntil] = useState("");
|
const [until, setUntil] = useState(() => getAdminQueryDateTimeBounds().max);
|
||||||
const [exporting, setExporting] = useState(false);
|
const [exporting, setExporting] = useState(false);
|
||||||
const [detailRow, setDetailRow] = useState<ToolMetric | null>(null);
|
const [detailRow, setDetailRow] = useState<ToolMetric | null>(null);
|
||||||
/** 成功 toast:仅暗色模式,浅色走 Sonner 默认 */
|
/** 成功 toast:仅暗色模式,浅色走 Sonner 默认 */
|
||||||
@@ -153,14 +155,15 @@ const errorToastDarkOptions = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const resetFilters = () => {
|
const resetFilters = () => {
|
||||||
|
const nextBounds = getAdminQueryDateTimeBounds();
|
||||||
setTool("");
|
setTool("");
|
||||||
setUser("");
|
setUser("");
|
||||||
setSkill("");
|
setSkill("");
|
||||||
setKind("skill");
|
setKind("skill");
|
||||||
setStatus("all");
|
setStatus("all");
|
||||||
setCategory("all");
|
setCategory("all");
|
||||||
setSince("");
|
setSince(nextBounds.min);
|
||||||
setUntil("");
|
setUntil(nextBounds.max);
|
||||||
setPage(0);
|
setPage(0);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -180,7 +183,7 @@ const errorToastDarkOptions = {
|
|||||||
<h2 className="text-lg font-semibold">工具调用统计</h2>
|
<h2 className="text-lg font-semibold">工具调用统计</h2>
|
||||||
<p className="text-muted-foreground mt-1 text-sm">
|
<p className="text-muted-foreground mt-1 text-sm">
|
||||||
记录每一次工具 / 技能 / MCP 调用,并对失败进行归类:检索为空、IP
|
记录每一次工具 / 技能 / MCP 调用,并对失败进行归类:检索为空、IP
|
||||||
被封、限流、超时、鉴权失败等。后台无条件记录。
|
被封、限流、超时、鉴权失败等。后台无条件记录,默认仅查询最近 30 天。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button onClick={handleExport} disabled={exporting}>
|
<Button onClick={handleExport} disabled={exporting}>
|
||||||
@@ -391,8 +394,10 @@ const errorToastDarkOptions = {
|
|||||||
<Input
|
<Input
|
||||||
type="datetime-local"
|
type="datetime-local"
|
||||||
value={since}
|
value={since}
|
||||||
|
min={queryDateTimeBounds.min}
|
||||||
|
max={until || queryDateTimeBounds.max}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setSince(e.target.value);
|
setSince(e.target.value || queryDateTimeBounds.min);
|
||||||
setPage(0);
|
setPage(0);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -402,8 +407,10 @@ const errorToastDarkOptions = {
|
|||||||
<Input
|
<Input
|
||||||
type="datetime-local"
|
type="datetime-local"
|
||||||
value={until}
|
value={until}
|
||||||
|
min={since || queryDateTimeBounds.min}
|
||||||
|
max={queryDateTimeBounds.max}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setUntil(e.target.value);
|
setUntil(e.target.value || queryDateTimeBounds.max);
|
||||||
setPage(0);
|
setPage(0);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,11 +1,33 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { BotIcon } from "lucide-react";
|
import {
|
||||||
|
BotIcon,
|
||||||
|
BrainIcon,
|
||||||
|
CompassIcon,
|
||||||
|
MessagesSquareIcon,
|
||||||
|
SparklesIcon,
|
||||||
|
WorkflowIcon,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
import { type Agent } from "@/core/agents";
|
import { type Agent } from "@/core/agents";
|
||||||
import { desensitize } from "@/lib/desensitize";
|
import { desensitize } from "@/lib/desensitize";
|
||||||
import { cn } from "@/lib/utils";
|
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
|
* Landing (home) hero shown above the input box before the first message of an
|
||||||
* agent conversation: centered avatar, a "Hi,我是{name}" greeting and the
|
* 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
|
* (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
|
* fold. The agent's 常用问题 are rendered by the page as a list beside the
|
||||||
* input box, not here.
|
* 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({
|
export function AgentWelcome({
|
||||||
className,
|
className,
|
||||||
agent,
|
agent,
|
||||||
agentName,
|
agentName,
|
||||||
|
styleIndex,
|
||||||
}: {
|
}: {
|
||||||
className?: string;
|
className?: string;
|
||||||
agent: Agent | null | undefined;
|
agent: Agent | null | undefined;
|
||||||
agentName: string;
|
agentName: string;
|
||||||
|
/** 仅自定义业务深链入口传入(风格分配完成后的档位;未分配完成时为
|
||||||
|
* undefined):启用按风格轮换的头像图标;缺省保持全局原样的 BotIcon。 */
|
||||||
|
styleIndex?: number;
|
||||||
}) {
|
}) {
|
||||||
const displayName = desensitize(agent?.name ?? agentName);
|
const displayName = desensitize(agent?.name ?? agentName);
|
||||||
const description = agent?.description
|
const description = agent?.description
|
||||||
? desensitize(agent.description)
|
? desensitize(agent.description)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
const styleIcon =
|
||||||
|
styleIndex === undefined
|
||||||
|
? BotIcon
|
||||||
|
: (STYLE_ICONS[styleIndex % STYLE_ICONS.length] ?? BotIcon);
|
||||||
|
const StyleIcon = styleIcon;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -35,15 +70,15 @@ export function AgentWelcome({
|
|||||||
className,
|
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">
|
<div className="agent-avatar rounded-3xl mb-2 flex h-[72px] w-[72px] items-center justify-center">
|
||||||
<BotIcon className="text-primary h-9 w-9" />
|
<StyleIcon className="h-9 w-9" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-3xl font-bold tracking-tight">
|
<div className="agent-welcome-name text-3xl font-bold tracking-tight">
|
||||||
Hi,我是{displayName}
|
Hi,我是{displayName}
|
||||||
</div>
|
</div>
|
||||||
{description && (
|
{description && (
|
||||||
<p
|
<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}
|
title={description}
|
||||||
>
|
>
|
||||||
{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,13 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
BotIcon,
|
|
||||||
ClockIcon,
|
ClockIcon,
|
||||||
CopyIcon,
|
CopyIcon,
|
||||||
|
EyeIcon,
|
||||||
EyeOffIcon,
|
EyeOffIcon,
|
||||||
GlobeIcon,
|
GlobeIcon,
|
||||||
LockIcon,
|
LockIcon,
|
||||||
MessageSquareIcon,
|
MessageSquareIcon,
|
||||||
|
MoreHorizontalIcon,
|
||||||
PinIcon,
|
PinIcon,
|
||||||
ShieldIcon,
|
ShieldIcon,
|
||||||
SparklesIcon,
|
SparklesIcon,
|
||||||
@@ -26,7 +27,7 @@ import {
|
|||||||
useState,
|
useState,
|
||||||
type ReactNode,
|
type ReactNode,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { toast } from "sonner";
|
import { confirmAction, toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -46,6 +47,13 @@ import {
|
|||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
@@ -59,6 +67,7 @@ import { Textarea } from "@/components/ui/textarea";
|
|||||||
import { usePublishSquares } from "@/core/system-settings/hooks";
|
import { usePublishSquares } from "@/core/system-settings/hooks";
|
||||||
import { PublishSquarePickerDialog } from "@/components/workspace/publish-square-picker-dialog";
|
import { PublishSquarePickerDialog } from "@/components/workspace/publish-square-picker-dialog";
|
||||||
import { SkillDetailDialog } from "@/components/workspace/skills/skill-detail-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 { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor";
|
||||||
import { SkillTransferSelector } from "@/components/workspace/agents/skill-transfer-selector";
|
import { SkillTransferSelector } from "@/components/workspace/agents/skill-transfer-selector";
|
||||||
import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
||||||
@@ -75,7 +84,15 @@ import {
|
|||||||
useUpdateAgent,
|
useUpdateAgent,
|
||||||
} from "@/core/agents";
|
} from "@/core/agents";
|
||||||
import { getAgent } from "@/core/agents/api";
|
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 { getStoredAuth } from "@/core/auth";
|
||||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
@@ -84,6 +101,8 @@ import { formatDateTime } from "@/core/utils/datetime";
|
|||||||
import { desensitize } from "@/lib/desensitize";
|
import { desensitize } from "@/lib/desensitize";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
import { AgentBrandIcon } from "./agent-brand-icon";
|
||||||
|
|
||||||
interface AgentCardProps {
|
interface AgentCardProps {
|
||||||
agent: Agent;
|
agent: Agent;
|
||||||
/** "card" (default) renders the full gallery card; "list" renders a compact
|
/** "card" (default) renders the full gallery card; "list" renders a compact
|
||||||
@@ -92,6 +111,11 @@ interface AgentCardProps {
|
|||||||
/** Click the 发布者 line to filter the gallery to that publisher. Receives the
|
/** Click the 发布者 line to filter the gallery to that publisher. Receives the
|
||||||
* owner user_id + its desensitized display label. */
|
* owner user_id + its desensitized display label. */
|
||||||
onPublisherClick?: (publisher: { id: string; label: string }) => void;
|
onPublisherClick?: (publisher: { id: string; label: string }) => void;
|
||||||
|
/** Admin console (智能体管理) only: renders the hide/restore eye button.
|
||||||
|
* Undefined everywhere else, so the gallery never shows it. */
|
||||||
|
onToggleHidden?: (next: boolean) => void | Promise<void>;
|
||||||
|
/** Disable the eye button while the admin toggle request is in flight. */
|
||||||
|
toggleHiddenPending?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface BadgeItem {
|
interface BadgeItem {
|
||||||
@@ -203,7 +227,13 @@ function ClampedBadgeRow({ items }: { items: BadgeItem[] }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCardProps) {
|
export function AgentCard({
|
||||||
|
agent,
|
||||||
|
layout = "card",
|
||||||
|
onPublisherClick,
|
||||||
|
onToggleHidden,
|
||||||
|
toggleHiddenPending = false,
|
||||||
|
}: AgentCardProps) {
|
||||||
const isList = layout === "list";
|
const isList = layout === "list";
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -214,9 +244,11 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
const setPrivate = useSetAgentPrivate();
|
const setPrivate = useSetAgentPrivate();
|
||||||
const toggleFavorite = useToggleAgentFavorite();
|
const toggleFavorite = useToggleAgentFavorite();
|
||||||
const togglePin = useToggleAgentPin();
|
const togglePin = useToggleAgentPin();
|
||||||
const { skills, isLoading: isSkillsLoading } = useSkills();
|
|
||||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
|
// The full skill catalog is only needed by the edit dialog. Cards render
|
||||||
|
// Chinese names from `agent.skill_labels` on the list response.
|
||||||
|
const { skills, isLoading: isSkillsLoading } = useSkills({ enabled: editOpen });
|
||||||
const [tagPickerOpen, setTagPickerOpen] = useState(false);
|
const [tagPickerOpen, setTagPickerOpen] = useState(false);
|
||||||
const [editName, setEditName] = useState(agent.name);
|
const [editName, setEditName] = useState(agent.name);
|
||||||
const [editDescription, setEditDescription] = useState(agent.description ?? "");
|
const [editDescription, setEditDescription] = useState(agent.description ?? "");
|
||||||
@@ -234,6 +266,12 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
const [editSeatSkillDirective, setEditSeatSkillDirective] = useState(
|
const [editSeatSkillDirective, setEditSeatSkillDirective] = useState(
|
||||||
agent.seat_skill_directive ?? false,
|
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 [editSquareId, setEditSquareId] = useState(agent.square_id ?? "");
|
||||||
const [publishPickerOpen, setPublishPickerOpen] = useState(false);
|
const [publishPickerOpen, setPublishPickerOpen] = useState(false);
|
||||||
const { data: publishSquares } = usePublishSquares();
|
const { data: publishSquares } = usePublishSquares();
|
||||||
@@ -282,6 +320,8 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
setSelectedSkills(agent.skills ?? []);
|
setSelectedSkills(agent.skills ?? []);
|
||||||
setEditCommonQuestions(normalizeAgentQuestions(agent.common_questions));
|
setEditCommonQuestions(normalizeAgentQuestions(agent.common_questions));
|
||||||
setEditSeatSkillDirective(agent.seat_skill_directive ?? false);
|
setEditSeatSkillDirective(agent.seat_skill_directive ?? false);
|
||||||
|
setEditModelPromptSuffixEnabled(agent.model_prompt_suffix_enabled ?? true);
|
||||||
|
setEditChatLink(agent.chat_link ?? emptyAgentChatLink());
|
||||||
}, [
|
}, [
|
||||||
agent.common_questions,
|
agent.common_questions,
|
||||||
agent.description,
|
agent.description,
|
||||||
@@ -291,6 +331,8 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
agent.square_id,
|
agent.square_id,
|
||||||
agent.skills,
|
agent.skills,
|
||||||
agent.seat_skill_directive,
|
agent.seat_skill_directive,
|
||||||
|
agent.model_prompt_suffix_enabled,
|
||||||
|
agent.chat_link,
|
||||||
editOpen,
|
editOpen,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -306,12 +348,28 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
setEditCommonQuestions(normalizeAgentQuestions(agentDetail.common_questions));
|
setEditCommonQuestions(normalizeAgentQuestions(agentDetail.common_questions));
|
||||||
// 列表响应不带 config 额外字段(seat_skill_directive 为 null),详情才有真值。
|
// 列表响应不带 config 额外字段(seat_skill_directive 为 null),详情才有真值。
|
||||||
setEditSeatSkillDirective(agentDetail.seat_skill_directive ?? false);
|
setEditSeatSkillDirective(agentDetail.seat_skill_directive ?? false);
|
||||||
|
setEditModelPromptSuffixEnabled(agentDetail.model_prompt_suffix_enabled ?? true);
|
||||||
|
setEditChatLink(agentDetail.chat_link ?? emptyAgentChatLink());
|
||||||
} else {
|
} else {
|
||||||
setEditSoul(agent.soul ?? "");
|
setEditSoul(agent.soul ?? "");
|
||||||
}
|
}
|
||||||
}, [agent.soul, agentDetail, editOpen]);
|
}, [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`);
|
router.push(`/page/workspace/agents/${agent.id}/chats/new`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,9 +392,11 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
// row to carry the source agent's personality into the copy. Fall back
|
// 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.
|
// to whatever the list happened to include if the detail fetch fails.
|
||||||
let soul = agent.soul ?? "";
|
let soul = agent.soul ?? "";
|
||||||
|
let chatLink = canonicalAgentChatLink(agent.chat_link);
|
||||||
try {
|
try {
|
||||||
const detail = await getAgent(agent.id);
|
const detail = await getAgent(agent.id);
|
||||||
soul = detail.soul ?? soul;
|
soul = detail.soul ?? soul;
|
||||||
|
chatLink = canonicalAgentChatLink(detail.chat_link);
|
||||||
} catch {
|
} catch {
|
||||||
// keep the list fallback
|
// keep the list fallback
|
||||||
}
|
}
|
||||||
@@ -347,6 +407,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
skills: agent.skills ?? [],
|
skills: agent.skills ?? [],
|
||||||
model: agent.model ?? null,
|
model: agent.model ?? null,
|
||||||
tool_groups: agent.tool_groups ?? null,
|
tool_groups: agent.tool_groups ?? null,
|
||||||
|
chat_link: chatLink,
|
||||||
// A copy starts as a private, unpublished draft the owner can refine
|
// A copy starts as a private, unpublished draft the owner can refine
|
||||||
// before sharing — never inherit the source's published/private state.
|
// before sharing — never inherit the source's published/private state.
|
||||||
published: false,
|
published: false,
|
||||||
@@ -399,6 +460,24 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
request.common_questions = nextQuestions;
|
request.common_questions = nextQuestions;
|
||||||
if (editSeatSkillDirective !== ((agentDetail?.seat_skill_directive ?? agent.seat_skill_directive) ?? false))
|
if (editSeatSkillDirective !== ((agentDetail?.seat_skill_directive ?? agent.seat_skill_directive) ?? false))
|
||||||
request.seat_skill_directive = editSeatSkillDirective;
|
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) {
|
if (Object.keys(request).length === 0) {
|
||||||
setEditOpen(false);
|
setEditOpen(false);
|
||||||
@@ -427,7 +506,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
setPublishPickerOpen(true);
|
setPublishPickerOpen(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!warnIfAccountSwitched()) {
|
if (!(await warnIfAccountSwitched())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -445,18 +524,22 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
|
|
||||||
// 发布操作以实时 token 执行。若会话中途账号被切换(常见于另一标签页登录了别的
|
// 发布操作以实时 token 执行。若会话中途账号被切换(常见于另一标签页登录了别的
|
||||||
// 账号),先弹一次确认 —— 避免误以本人之外的账号执行发布。返回 false = 用户取消。
|
// 账号),先弹一次确认 —— 避免误以本人之外的账号执行发布。返回 false = 用户取消。
|
||||||
function warnIfAccountSwitched(): boolean {
|
function warnIfAccountSwitched(): boolean | Promise<boolean> {
|
||||||
if (!live.switched) {
|
if (!live.switched) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return window.confirm(
|
return confirmAction(
|
||||||
`当前登录账号已从「${live.mountDisplayName}」切换为「${live.displayName}」。\n` +
|
`当前登录账号已从「${live.mountDisplayName}」切换为「${live.displayName}」。\n` +
|
||||||
`本次发布将以「${live.displayName}」执行。如需以「${live.mountDisplayName}」操作,请取消并刷新页面。\n\n仍要继续吗?`,
|
`本次发布将以「${live.displayName}」执行。如需以「${live.mountDisplayName}」操作,请取消并刷新页面。`,
|
||||||
|
{
|
||||||
|
title: "登录账号已切换",
|
||||||
|
confirmText: "继续发布",
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handlePublishToSquare(squareId: string) {
|
async function handlePublishToSquare(squareId: string) {
|
||||||
if (!warnIfAccountSwitched()) {
|
if (!(await warnIfAccountSwitched())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -538,6 +621,12 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
// both the card header and the compact list row.
|
// both the card header and the compact list row.
|
||||||
const statusBadges = (
|
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 && (
|
{isBuiltin && (
|
||||||
<Badge variant="secondary" className="text-xs">
|
<Badge variant="secondary" className="text-xs">
|
||||||
内置
|
内置
|
||||||
@@ -590,6 +679,16 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
私密
|
私密
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
|
{agent.hidden && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-zinc-500/40 bg-zinc-500/10 text-zinc-600 dark:text-zinc-300 text-xs"
|
||||||
|
title="已被管理员隐藏:除本管理页外不再展示,但仍可正常使用"
|
||||||
|
>
|
||||||
|
<EyeOffIcon className="size-3" />
|
||||||
|
已隐藏
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
{agent.featured_order != null && (
|
{agent.featured_order != null && (
|
||||||
<Badge
|
<Badge
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -646,20 +745,16 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
</div>
|
</div>
|
||||||
) : null;
|
) : null;
|
||||||
|
|
||||||
// 技能英文名 → 中文名映射,用于把智能体的技能徽章显示为中文(agent.skills 只存英文名)。
|
|
||||||
const skillNameZhMap = useMemo(() => {
|
|
||||||
const map = new Map<string, string>();
|
|
||||||
for (const s of skills) {
|
|
||||||
if (s.name_zh?.trim()) map.set(s.name, s.name_zh.trim());
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
}, [skills]);
|
|
||||||
|
|
||||||
const skillBadgeItems = [
|
const skillBadgeItems = [
|
||||||
...(agent.tool_groups ?? []).map((group) => ({
|
...(agent.tool_groups ?? []).map((group) => ({
|
||||||
key: `tg:${group}`,
|
key: `tg:${group}`,
|
||||||
node: (
|
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)}
|
{desensitize(group)}
|
||||||
</Badge>
|
</Badge>
|
||||||
),
|
),
|
||||||
@@ -669,15 +764,15 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
node: (
|
node: (
|
||||||
<Badge
|
<Badge
|
||||||
key={`sk:${skill}`}
|
key={`sk:${skill}`}
|
||||||
variant="secondary"
|
variant="outline"
|
||||||
className="hover:bg-secondary/70 cursor-pointer text-xs"
|
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}
|
title={t.settings.skills.viewDetailAction}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
setDetailSkillName(skill);
|
setDetailSkillName(skill);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{skillNameZhMap.get(skill) ?? desensitize(skill)}
|
{agent.skill_labels?.[skill]?.trim() || desensitize(skill)}
|
||||||
</Badge>
|
</Badge>
|
||||||
),
|
),
|
||||||
})),
|
})),
|
||||||
@@ -783,6 +878,31 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
<ShieldIcon className="h-3.5 w-3.5" />
|
<ShieldIcon className="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
{onToggleHidden && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-8 shrink-0",
|
||||||
|
agent.hidden
|
||||||
|
? "text-zinc-500 hover:text-zinc-600 dark:text-zinc-400"
|
||||||
|
: "text-zinc-400 hover:text-zinc-500",
|
||||||
|
)}
|
||||||
|
onClick={() => void onToggleHidden(!agent.hidden)}
|
||||||
|
disabled={toggleHiddenPending}
|
||||||
|
title={
|
||||||
|
agent.hidden
|
||||||
|
? "取消隐藏:恢复在广场等列表中展示"
|
||||||
|
: "隐藏:除本管理页外不再展示,智能体仍可正常使用"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{agent.hidden ? (
|
||||||
|
<EyeIcon className="h-3.5 w-3.5" />
|
||||||
|
) : (
|
||||||
|
<EyeOffIcon className="h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<Button
|
<Button
|
||||||
size="icon"
|
size="icon"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -820,71 +940,193 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
|
|
||||||
const chatButton = (
|
const chatButton = (
|
||||||
<Button
|
<Button
|
||||||
|
variant={isList ? "default" : "outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
className={cn(isList ? "shrink-0" : "w-full")}
|
className={cn(
|
||||||
onClick={handleChat}
|
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" />
|
<MessageSquareIcon className="mr-1.5 h-3.5 w-3.5" />
|
||||||
{t.agents.chat}
|
{isList ? t.agents.chat : "开始对话"}
|
||||||
</Button>
|
</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 = (
|
const cardLayout = (
|
||||||
<Card
|
<Card
|
||||||
className="group flex min-w-0 flex-col transition-shadow hover:shadow-md"
|
className={cn(
|
||||||
|
"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"
|
data-agent-guide="agent-card"
|
||||||
>
|
>
|
||||||
<CardHeader className="min-w-0 pb-2">
|
<CardHeader className="min-w-0 gap-0 px-5 pb-2 pt-5">
|
||||||
<div className="flex min-w-0 items-start justify-between gap-2">
|
{(isPinned || agent.featured_order != null) && (
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
|
<div className="mb-2 flex h-7 items-center justify-between">
|
||||||
<div className="agent-avatar bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
<BotIcon className="h-5 w-5" />
|
{isPinned && (
|
||||||
</div>
|
<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">
|
||||||
<div className="min-w-0 flex-1 overflow-hidden">
|
<PinIcon className="mr-1 size-3.5 fill-current" />
|
||||||
<CardTitle
|
置顶
|
||||||
className="block w-full min-w-0 overflow-hidden text-base text-ellipsis whitespace-nowrap"
|
</Badge>
|
||||||
title={desensitize(agent.name)}
|
)}
|
||||||
>
|
{agent.featured_order != null && (
|
||||||
{desensitize(agent.name)}
|
<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">
|
||||||
</CardTitle>
|
<SparklesIcon className="mr-1 size-3.5 fill-current" />
|
||||||
{agent.model && (
|
推荐
|
||||||
<Badge variant="secondary" className="mt-0.5 text-xs">
|
|
||||||
{desensitize(agent.model)}
|
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{cardActionsMenu}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex shrink-0 flex-wrap items-center justify-end gap-1">
|
)}
|
||||||
{statusBadges}
|
{/* 标题与 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="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>
|
||||||
</div>
|
</div>
|
||||||
|
{!isPinned && agent.featured_order == null && cardActionsMenu}
|
||||||
</div>
|
</div>
|
||||||
{agent.description && (
|
{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)}
|
{desensitize(agent.description)}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
)}
|
)}
|
||||||
{publisherNode && <div className="mt-2">{publisherNode}</div>}
|
{(agent.tags?.length ?? 0) > 0 && (
|
||||||
{createdAtNode && <div className="mt-1">{createdAtNode}</div>}
|
<div className="mt-2.5">
|
||||||
|
<TagChipList tags={agent.tags!} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
{(agent.tags?.length ?? 0) > 0 && (
|
|
||||||
<CardContent className="pt-0 pb-2">
|
|
||||||
<TagChipList tags={agent.tags!} />
|
|
||||||
</CardContent>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{hasSkillsOrTools && (
|
{hasSkillsOrTools && (
|
||||||
<CardContent className="pt-0 pb-2">
|
<CardContent className="px-5 pb-2 pt-0">
|
||||||
<ClampedBadgeRow items={skillBadgeItems} />
|
<ClampedBadgeRow items={skillBadgeItems} />
|
||||||
</CardContent>
|
</CardContent>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<CardFooter className="mt-auto flex flex-col items-stretch gap-2 pt-2">
|
<CardFooter className="mt-auto flex flex-col items-stretch gap-4 px-5 pb-4 pt-2">
|
||||||
{showActionRow && (
|
<div className="flex min-w-0 items-center gap-3">
|
||||||
<div className="flex flex-wrap items-center justify-end gap-1">
|
{cardStatusBadge}
|
||||||
{actionButtons}
|
<span
|
||||||
</div>
|
className="min-w-0 truncate text-xs text-slate-400"
|
||||||
)}
|
title={updatedAtText ? `更新于 ${updatedAtText}` : undefined}
|
||||||
|
>
|
||||||
|
{updatedAtText ? `更新于 ${updatedAtText}` : ""}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
{chatButton}
|
{chatButton}
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -892,12 +1134,15 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
|
|
||||||
const listLayout = (
|
const listLayout = (
|
||||||
<div
|
<div
|
||||||
className="group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]"
|
className={cn(
|
||||||
|
"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"
|
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">
|
<AgentBrandIcon size="md" className="agent-avatar" />
|
||||||
<BotIcon className="h-5 w-5" />
|
|
||||||
</div>
|
|
||||||
<div className="min-w-0 flex-1 overflow-hidden">
|
<div className="min-w-0 flex-1 overflow-hidden">
|
||||||
<div className="flex min-w-0 items-center gap-2">
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
<span
|
<span
|
||||||
@@ -994,6 +1239,19 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
onChange={setEditCommonQuestions}
|
onChange={setEditCommonQuestions}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center justify-between gap-3 rounded-md border p-3">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium">使用模型追加提示词</p>
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
默认开启。关闭后,该智能体的问答不会附加管理员为所选模型设置的全局提示词。
|
||||||
|
</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 className="flex items-center justify-between gap-3 rounded-md border p-3">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm font-medium">会商技能识别强化</p>
|
<p className="text-sm font-medium">会商技能识别强化</p>
|
||||||
@@ -1074,6 +1332,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
{/* <AgentChatLinkFields value={editChatLink} onChange={setEditChatLink} /> */}
|
||||||
</div>
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button
|
<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 Link from "next/link";
|
||||||
import { useParams, usePathname, useRouter } from "next/navigation";
|
import { useParams, usePathname, useRouter } from "next/navigation";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
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 { agentColor } from "@/components/workspace/agent-icon-color";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
|||||||
@@ -6,7 +6,9 @@ import {
|
|||||||
CheckIcon,
|
CheckIcon,
|
||||||
DatabaseIcon,
|
DatabaseIcon,
|
||||||
GlobeIcon,
|
GlobeIcon,
|
||||||
|
GripVertical,
|
||||||
InfoIcon,
|
InfoIcon,
|
||||||
|
// Link2Icon,
|
||||||
Loader2Icon,
|
Loader2Icon,
|
||||||
LockIcon,
|
LockIcon,
|
||||||
MessageCircleQuestionIcon,
|
MessageCircleQuestionIcon,
|
||||||
@@ -22,9 +24,19 @@ import {
|
|||||||
XIcon,
|
XIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
import {
|
||||||
import { toast } from "sonner";
|
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 { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -59,9 +71,16 @@ import {
|
|||||||
useSetAgentFeatured,
|
useSetAgentFeatured,
|
||||||
useUpdateAgent,
|
useUpdateAgent,
|
||||||
type Agent,
|
type Agent,
|
||||||
|
type AgentChatLink,
|
||||||
type AgentQuestion,
|
type AgentQuestion,
|
||||||
type UpdateAgentRequest,
|
type UpdateAgentRequest,
|
||||||
} from "@/core/agents";
|
} from "@/core/agents";
|
||||||
|
import {
|
||||||
|
agentChatLinksEqual,
|
||||||
|
canonicalAgentChatLink,
|
||||||
|
isAllowedAgentChatUrl,
|
||||||
|
} from "@/core/agents/chat-link";
|
||||||
|
import { emptyAgentChatLink } from "@/core/agents/types";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||||
import { isAgentSkillCandidate } from "@/core/skills";
|
import { isAgentSkillCandidate } from "@/core/skills";
|
||||||
@@ -70,6 +89,30 @@ import { usePublishSquares } from "@/core/system-settings/hooks";
|
|||||||
import { desensitize } from "@/lib/desensitize";
|
import { desensitize } from "@/lib/desensitize";
|
||||||
import { cn } from "@/lib/utils";
|
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 保存. */
|
/** Local edit-mode draft — committed in one `updateAgent` call on 保存. */
|
||||||
interface AgentDraft {
|
interface AgentDraft {
|
||||||
@@ -81,9 +124,11 @@ interface AgentDraft {
|
|||||||
published: boolean;
|
published: boolean;
|
||||||
featured: boolean;
|
featured: boolean;
|
||||||
templateName: string;
|
templateName: string;
|
||||||
|
modelPromptSuffixEnabled: boolean;
|
||||||
/** 会商席位「技能识别强化」开关。 */
|
/** 会商席位「技能识别强化」开关。 */
|
||||||
seatSkillDirective: boolean;
|
seatSkillDirective: boolean;
|
||||||
knowledgeBaseIds: string[];
|
knowledgeBaseIds: string[];
|
||||||
|
chatLink: AgentChatLink;
|
||||||
}
|
}
|
||||||
|
|
||||||
function draftFromAgent(agent: Agent): AgentDraft {
|
function draftFromAgent(agent: Agent): AgentDraft {
|
||||||
@@ -96,8 +141,10 @@ function draftFromAgent(agent: Agent): AgentDraft {
|
|||||||
published: agent.published,
|
published: agent.published,
|
||||||
featured: agent.featured_order != null,
|
featured: agent.featured_order != null,
|
||||||
templateName: agent.template_name ?? "",
|
templateName: agent.template_name ?? "",
|
||||||
|
modelPromptSuffixEnabled: agent.model_prompt_suffix_enabled ?? true,
|
||||||
seatSkillDirective: agent.seat_skill_directive ?? false,
|
seatSkillDirective: agent.seat_skill_directive ?? false,
|
||||||
knowledgeBaseIds: agent.llmwiki_knowledge_base_ids ?? [],
|
knowledgeBaseIds: agent.llmwiki_knowledge_base_ids ?? [],
|
||||||
|
chatLink: agent.chat_link ?? emptyAgentChatLink(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +162,7 @@ function Section({
|
|||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
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">
|
<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">
|
<h4 className="text-foreground flex items-center gap-1.5 text-sm font-semibold">
|
||||||
{icon}
|
{icon}
|
||||||
@@ -212,6 +259,109 @@ export function AgentDetailPanel({
|
|||||||
if (collapsedProp === undefined) setInternalCollapsed(next);
|
if (collapsedProp === undefined) setInternalCollapsed(next);
|
||||||
onCollapsedChange?.(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 [mobileOpen, setMobileOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState(false);
|
const [editing, setEditing] = useState(false);
|
||||||
const [draft, setDraft] = useState<AgentDraft | null>(null);
|
const [draft, setDraft] = useState<AgentDraft | null>(null);
|
||||||
@@ -367,8 +517,22 @@ export function AgentDetailPanel({
|
|||||||
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
|
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
|
||||||
if (draft.templateName.trim() !== (agent.template_name ?? ""))
|
if (draft.templateName.trim() !== (agent.template_name ?? ""))
|
||||||
request.template_name = draft.templateName.trim();
|
request.template_name = draft.templateName.trim();
|
||||||
|
if (draft.modelPromptSuffixEnabled !== (agent.model_prompt_suffix_enabled ?? true))
|
||||||
|
request.model_prompt_suffix_enabled = draft.modelPromptSuffixEnabled;
|
||||||
if (draft.seatSkillDirective !== (agent.seat_skill_directive ?? false))
|
if (draft.seatSkillDirective !== (agent.seat_skill_directive ?? false))
|
||||||
request.seat_skill_directive = draft.seatSkillDirective;
|
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 (
|
if (
|
||||||
JSON.stringify(draft.knowledgeBaseIds) !==
|
JSON.stringify(draft.knowledgeBaseIds) !==
|
||||||
JSON.stringify(agent.llmwiki_knowledge_base_ids ?? [])
|
JSON.stringify(agent.llmwiki_knowledge_base_ids ?? [])
|
||||||
@@ -417,7 +581,7 @@ export function AgentDetailPanel({
|
|||||||
setPublishPickerOpen(true);
|
setPublishPickerOpen(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!warnIfAccountSwitched()) {
|
if (!(await warnIfAccountSwitched())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -435,19 +599,23 @@ export function AgentDetailPanel({
|
|||||||
|
|
||||||
// 发布以实时 token 执行。会话中途账号被切换(常见于另一标签页登录了别的账号)时
|
// 发布以实时 token 执行。会话中途账号被切换(常见于另一标签页登录了别的账号)时
|
||||||
// 先弹确认,避免误以本人之外的账号执行发布。返回 false = 用户取消。
|
// 先弹确认,避免误以本人之外的账号执行发布。返回 false = 用户取消。
|
||||||
function warnIfAccountSwitched(): boolean {
|
function warnIfAccountSwitched(): boolean | Promise<boolean> {
|
||||||
if (!live.switched) {
|
if (!live.switched) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return window.confirm(
|
return confirmAction(
|
||||||
`当前登录账号已从「${live.mountDisplayName}」切换为「${live.displayName}」。\n` +
|
`当前登录账号已从「${live.mountDisplayName}」切换为「${live.displayName}」。\n` +
|
||||||
`本次发布将以「${live.displayName}」执行。如需以「${live.mountDisplayName}」操作,请取消并刷新页面。\n\n仍要继续吗?`,
|
`本次发布将以「${live.displayName}」执行。如需以「${live.mountDisplayName}」操作,请取消并刷新页面。`,
|
||||||
|
{
|
||||||
|
title: "登录账号已切换",
|
||||||
|
confirmText: "继续发布",
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handlePublishToSquare(squareId: string) {
|
async function handlePublishToSquare(squareId: string) {
|
||||||
if (!agent) return;
|
if (!agent) return;
|
||||||
if (!warnIfAccountSwitched()) {
|
if (!(await warnIfAccountSwitched())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -598,7 +766,7 @@ export function AgentDetailPanel({
|
|||||||
) : (
|
) : (
|
||||||
<div className="space-y-4 px-4 py-4">
|
<div className="space-y-4 px-4 py-4">
|
||||||
{/* ── Identity / 基础信息 ─────────────────────────────────────────── */}
|
{/* ── 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="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">
|
<div className="agent-avatar bg-primary/10 ring-primary/15 flex size-12 shrink-0 items-center justify-center rounded-2xl ring-1">
|
||||||
{avatarSrc ? (
|
{avatarSrc ? (
|
||||||
@@ -619,7 +787,7 @@ export function AgentDetailPanel({
|
|||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<div
|
<div
|
||||||
className="truncate text-base font-bold"
|
className="agent-detail-name truncate text-base font-bold"
|
||||||
title={displayName}
|
title={displayName}
|
||||||
>
|
>
|
||||||
{displayName}
|
{displayName}
|
||||||
@@ -654,7 +822,7 @@ export function AgentDetailPanel({
|
|||||||
className="min-h-16 text-sm"
|
className="min-h-16 text-sm"
|
||||||
/>
|
/>
|
||||||
) : agent.description ? (
|
) : 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)}
|
{desensitize(agent.description)}
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
@@ -663,6 +831,13 @@ export function AgentDetailPanel({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 入库模板名 — view mode shows a hint row when configured. */}
|
{/* 入库模板名 — 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() && (
|
{!editing && agent.template_name?.trim() && (
|
||||||
<div className="text-muted-foreground mt-2 flex items-center gap-1 text-xs">
|
<div className="text-muted-foreground mt-2 flex items-center gap-1 text-xs">
|
||||||
<UploadCloudIcon className="size-3 shrink-0" />
|
<UploadCloudIcon className="size-3 shrink-0" />
|
||||||
@@ -702,6 +877,21 @@ export function AgentDetailPanel({
|
|||||||
}
|
}
|
||||||
variant="panel"
|
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="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
|
||||||
<div className="pr-3">
|
<div className="pr-3">
|
||||||
<p className="text-sm font-medium">会商技能识别强化</p>
|
<p className="text-sm font-medium">会商技能识别强化</p>
|
||||||
@@ -806,7 +996,7 @@ export function AgentDetailPanel({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={beginEdit}
|
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]" />
|
<PlusIcon className="mr-1 inline size-3.5 align-[-2px]" />
|
||||||
添加常用问题
|
添加常用问题
|
||||||
@@ -818,7 +1008,7 @@ export function AgentDetailPanel({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={index}
|
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 ? (
|
{isEditingThis ? (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -948,6 +1138,13 @@ export function AgentDetailPanel({
|
|||||||
/>
|
/>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
|
{/* {editing && draft && (
|
||||||
|
<AgentChatLinkFields
|
||||||
|
value={draft.chatLink}
|
||||||
|
onChange={(chatLink) => setDraft({ ...draft, chatLink })}
|
||||||
|
/>
|
||||||
|
)} */}
|
||||||
|
|
||||||
{/* ── 技能列表下方插槽(8BF 产物提交 position 等)────────────────── */}
|
{/* ── 技能列表下方插槽(8BF 产物提交 position 等)────────────────── */}
|
||||||
{belowSkillsSlot}
|
{belowSkillsSlot}
|
||||||
|
|
||||||
@@ -989,25 +1186,64 @@ export function AgentDetailPanel({
|
|||||||
header「新对话」按钮右侧。 */
|
header「新对话」按钮右侧。 */
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"hidden h-full shrink-0 overflow-hidden transition-[width] duration-300 ease-in-out lg:block",
|
"relative hidden h-full shrink-0 lg:block",
|
||||||
collapsed ? "w-0" : "w-[360px]",
|
isResizingPanel ? "transition-none" : "transition-[width] duration-300 ease-in-out",
|
||||||
|
collapsed && "pointer-events-none",
|
||||||
)}
|
)}
|
||||||
|
style={{ width: collapsed ? 0 : panelWidth }}
|
||||||
>
|
>
|
||||||
<aside className="bg-card/40 flex h-full w-[360px] flex-col border-l">
|
<div className="h-full overflow-hidden">
|
||||||
{panelChrome(
|
<aside
|
||||||
<Tooltip content="收起">
|
className="bg-card/40 flex h-full flex-col border-l"
|
||||||
<Button
|
style={{ width: panelWidth }}
|
||||||
variant="ghost"
|
>
|
||||||
size="icon-sm"
|
{panelChrome(
|
||||||
onClick={() => setCollapsed(true)}
|
<Tooltip content="收起">
|
||||||
aria-label="收起智能体信息"
|
<Button
|
||||||
aria-expanded={true}
|
variant="ghost"
|
||||||
|
size="icon-sm"
|
||||||
|
onClick={() => setCollapsed(true)}
|
||||||
|
aria-label="收起智能体信息"
|
||||||
|
aria-expanded={true}
|
||||||
|
>
|
||||||
|
<PanelRightCloseIcon className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</Tooltip>,
|
||||||
|
)}
|
||||||
|
</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",
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
<PanelRightCloseIcon className="size-4" />
|
<GripVertical className="size-3.5" />
|
||||||
</Button>
|
</span>
|
||||||
</Tooltip>,
|
</div>
|
||||||
)}
|
</div>
|
||||||
</aside>
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : collapsed ? (
|
) : collapsed ? (
|
||||||
<div className="hidden shrink-0 items-start border-l px-2 pt-3 lg:flex">
|
<div className="hidden shrink-0 items-start border-l px-2 pt-3 lg:flex">
|
||||||
|
|||||||
@@ -1,24 +1,32 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { ArrowDownUpIcon, BotIcon, Compass, Loader2, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";
|
import { ArrowDownUpIcon, BotIcon, Compass, Loader2, LockIcon, PlusIcon, RefreshCwIcon, ShieldIcon, XIcon } from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar";
|
import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar";
|
||||||
import { ViewModeToggle } from "@/components/workspace/view-mode-toggle";
|
import { ViewModeToggle } from "@/components/workspace/view-mode-toggle";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { useAgentsPaginated, usePrivateAgentsPaginated } from "@/core/agents";
|
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 type { Agent, AgentSort } from "@/core/agents";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
import { useRouteBase } from "@/core/route-base";
|
import { useRouteBase } from "@/core/route-base";
|
||||||
import { isSentimentAgentVisible } from "@/core/sentiment-agent/config";
|
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 {
|
import {
|
||||||
WX_RESTRICTED_TAB_DEFAULT_SQUARE,
|
WX_RESTRICTED_TAB_DEFAULT_SQUARE,
|
||||||
WX_RESTRICTED_TAB_NANJING_DB,
|
WX_RESTRICTED_TAB_NANJING_DB,
|
||||||
@@ -51,9 +59,12 @@ export function AgentGallery({
|
|||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const routeBase = useRouteBase();
|
const routeBase = useRouteBase();
|
||||||
|
const pageDescriptions = usePageDescriptionsSettings();
|
||||||
|
const pageDescription = pageDescriptions.data?.agents;
|
||||||
const sentimentAgentVisible = isSentimentAgentVisible();
|
const sentimentAgentVisible = isSentimentAgentVisible();
|
||||||
// 「内置智能体」筛选仅管理员可见(后端 scope=builtin 也做了 admin 闸门兜底)。
|
// 「内置智能体」筛选仅管理员可见(后端 scope=builtin 也做了 admin 闸门兜底)。
|
||||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||||
|
const syncDirectory = useSyncAgentDirectory();
|
||||||
const [viewMode, setViewMode] = useViewMode("agent");
|
const [viewMode, setViewMode] = useViewMode("agent");
|
||||||
const [activeTab, setActiveTab] = useState<string>("mine");
|
const [activeTab, setActiveTab] = useState<string>("mine");
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
@@ -256,10 +267,20 @@ export function AgentGallery({
|
|||||||
const handlePublisherClick = (p: { id: string; label: string }) =>
|
const handlePublisherClick = (p: { id: string; label: string }) =>
|
||||||
setPublisher(p);
|
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[]) =>
|
const renderGrid = (list: Agent[]) =>
|
||||||
viewMode === "list" ? (
|
viewMode === "list" ? (
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
{list.map((agent) => (
|
{pinFirst(list).map((agent) => (
|
||||||
<AgentCard
|
<AgentCard
|
||||||
key={agent.id}
|
key={agent.id}
|
||||||
agent={agent}
|
agent={agent}
|
||||||
@@ -268,9 +289,29 @@ export function AgentGallery({
|
|||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</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">
|
<div
|
||||||
{list.map((agent) => (
|
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
|
<AgentCard
|
||||||
key={agent.id}
|
key={agent.id}
|
||||||
agent={agent}
|
agent={agent}
|
||||||
@@ -331,11 +372,12 @@ export function AgentGallery({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<Pagination
|
<TPagination
|
||||||
page={pages[tab] ?? 1}
|
current={pages[tab] ?? 1}
|
||||||
pageSize={PAGE_SIZE}
|
pageSize={PAGE_SIZE}
|
||||||
total={total}
|
total={total}
|
||||||
onPageChange={(p) => setTabPage(tab, p)}
|
showJumper
|
||||||
|
onChange={(pageInfo) => setTabPage(tab, pageInfo.current)}
|
||||||
className="pt-2"
|
className="pt-2"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -359,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"
|
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}
|
onClick={handleNewAgent}
|
||||||
>
|
>
|
||||||
<PlusIcon className="mr-1.5 h-4 w-4" />
|
<PlusIcon className="mr-2.5 h-4 w-4" />
|
||||||
{t.agents.newAgent}
|
{t.agents.newAgent}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
@@ -450,19 +492,59 @@ export function AgentGallery({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
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 */}
|
{/* 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>
|
<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">
|
<p className="text-muted-foreground mt-0.5 text-sm">
|
||||||
{t.agents.description}
|
{pageDescription?.description || t.agents.description}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-1.5">
|
||||||
|
{isAdmin && (
|
||||||
|
<Button
|
||||||
|
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={() => {
|
||||||
|
void syncDirectory.mutateAsync().then(
|
||||||
|
(result) => {
|
||||||
|
toast.success(
|
||||||
|
result.scanned > 0
|
||||||
|
? `已扫描并同步 ${result.scanned} 个目录智能体`
|
||||||
|
: "目录里没有可同步的智能体",
|
||||||
|
);
|
||||||
|
},
|
||||||
|
(err: unknown) => {
|
||||||
|
toast.error(err instanceof Error ? err.message : "扫描智能体目录失败");
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<RefreshCwIcon
|
||||||
|
className={`h-4 w-4 ${syncDirectory.isPending ? "animate-spin" : ""}`}
|
||||||
|
/>
|
||||||
|
{syncDirectory.isPending ? "扫描中…" : "重新扫描智能体目录"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
className="h-9 rounded-[5px] px-3 text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||||
title="打开智能体广场视图"
|
title="打开智能体广场视图"
|
||||||
onClick={() => router.push(`${routeBase}/agents/plaza`)}
|
onClick={() => router.push(`${routeBase}/agents/plaza`)}
|
||||||
>
|
>
|
||||||
@@ -471,18 +553,23 @@ export function AgentGallery({
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
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="重新播放智能体使用引导"
|
title="重新播放智能体使用引导"
|
||||||
onClick={() => startAgentGuide("list")}
|
onClick={() => startAgentGuide("list")}
|
||||||
>
|
>
|
||||||
<Compass className="mr-1.5 h-4 w-4" />
|
<Compass className="h-4 w-4" />
|
||||||
使用引导
|
使用引导
|
||||||
</Button>
|
</Button>
|
||||||
<Button onClick={handleNewAgent} data-agent-guide="new-agent-btn">
|
<Button
|
||||||
<PlusIcon className="mr-1.5 h-4 w-4" />
|
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}
|
{t.agents.newAgent}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
Trash2Icon,
|
Trash2Icon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -53,8 +53,8 @@ export function AgentManageDialog({
|
|||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
}: AgentManageDialogProps) {
|
}: AgentManageDialogProps) {
|
||||||
const { agents, isLoading } = useAgentSelector();
|
const { agents, isLoading } = useAgentSelector({ enabled: open });
|
||||||
const { agents: allAgents } = useAgents();
|
const { agents: allAgents } = useAgents({ enabled: open });
|
||||||
const setFeaturedMutation = useSetAgentFeatured();
|
const setFeaturedMutation = useSetAgentFeatured();
|
||||||
const reorderMutation = useReorderFeaturedAgents();
|
const reorderMutation = useReorderFeaturedAgents();
|
||||||
const [pickerOpen, setPickerOpen] = useState(false);
|
const [pickerOpen, setPickerOpen] = useState(false);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { Bot, Loader2 } from "lucide-react";
|
import { Bot, Loader2 } from "lucide-react";
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
import { Select } from "tdesign-react";
|
import { Select } from "tdesign-react";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import {
|
|||||||
import { PromptInputButton } from "@/components/ai-elements/prompt-input";
|
import { PromptInputButton } from "@/components/ai-elements/prompt-input";
|
||||||
import { AgentManageDialog } from "@/components/workspace/agents/agent-manage-dialog";
|
import { AgentManageDialog } from "@/components/workspace/agents/agent-manage-dialog";
|
||||||
import { Tooltip } from "@/components/workspace/tooltip";
|
import { Tooltip } from "@/components/workspace/tooltip";
|
||||||
import { useAgentSelector, useAgentsPaginated } from "@/core/agents";
|
import { useAgent, useAgentSelector } from "@/core/agents";
|
||||||
import type { Agent } from "@/core/agents";
|
import type { Agent } from "@/core/agents";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { desensitize } from "@/lib/desensitize";
|
import { desensitize } from "@/lib/desensitize";
|
||||||
@@ -59,22 +59,19 @@ export function AgentSelector({
|
|||||||
}: AgentSelectorProps) {
|
}: AgentSelectorProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [manageOpen, setManageOpen] = useState(false);
|
const [manageOpen, setManageOpen] = useState(false);
|
||||||
const { agents, isLoading } = useAgentSelector();
|
const { agents, isLoading } = useAgentSelector({ enabled: open });
|
||||||
// 弹窗列表只展示管理弹窗里配置的 agent(agents);但「已选中 agent」的名称解析要更宽——
|
// Resolve a remembered personal agent with a single detail lookup instead of
|
||||||
// 侧边栏「常用智能体」可以选中未配置进管理弹窗的 agent(如用户自己的智能体),
|
// preloading both complete homepage gallery pages.
|
||||||
// 这些 agent 也要能在胶囊上显示名称,故额外用「我的 / 广场」列表兜底解析(缓存与侧边栏共享)。
|
const { agent: selectedAgentDetail } = useAgent(selectedAgentId, {
|
||||||
const { agents: mineAgents } = useAgentsPaginated({ scope: "mine", page: 1, pageSize: 20 });
|
enabled: !!selectedAgentId,
|
||||||
const { agents: squareAgents } = useAgentsPaginated({ scope: "square", page: 1, pageSize: 20 });
|
retry: false,
|
||||||
|
});
|
||||||
const isAdmin = useMemo(() => getStoredAuth()?.system_role === "admin", []);
|
const isAdmin = useMemo(() => getStoredAuth()?.system_role === "admin", []);
|
||||||
|
|
||||||
const selectedAgent = useMemo<Agent | null>(() => {
|
const selectedAgent = useMemo<Agent | null>(() => {
|
||||||
if (!selectedAgentId) return null;
|
if (!selectedAgentId) return null;
|
||||||
return (
|
return agents.find((a) => a.id === selectedAgentId) ?? selectedAgentDetail;
|
||||||
[...agents, ...mineAgents, ...squareAgents].find(
|
}, [agents, selectedAgentDetail, selectedAgentId]);
|
||||||
(a) => a.id === selectedAgentId,
|
|
||||||
) ?? null
|
|
||||||
);
|
|
||||||
}, [agents, mineAgents, squareAgents, selectedAgentId]);
|
|
||||||
|
|
||||||
const handleSelect = (agent: Agent) => {
|
const handleSelect = (agent: Agent) => {
|
||||||
onAgentChange(agent.id);
|
onAgentChange(agent.id);
|
||||||
|
|||||||
@@ -87,12 +87,12 @@ export function EnabledSkillList({
|
|||||||
<div
|
<div
|
||||||
key={name}
|
key={name}
|
||||||
className={cn(
|
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",
|
onViewDetail && "hover:border-primary/40 hover:bg-accent/40",
|
||||||
offline && "bg-muted/60 border-dashed dark:bg-[#071D36]",
|
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) : "?"}
|
{skill ? skillInitial(skill) : "?"}
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
XIcon,
|
XIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useMemo, useRef, useState } from "react";
|
import { useMemo, useRef, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ const triggerToneClass = (tone: AppearanceControlTone) =>
|
|||||||
tone === "banner-dark"
|
tone === "banner-dark"
|
||||||
? "text-slate-400 hover:bg-slate-800/50 hover:text-slate-400"
|
? "text-slate-400 hover:bg-slate-800/50 hover:text-slate-400"
|
||||||
: tone === "banner-light"
|
: 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"
|
: tone === "banner-custom"
|
||||||
? "text-[var(--navigation-foreground)] hover:bg-white/20 hover:text-[var(--navigation-foreground)] active:bg-white/30"
|
? "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";
|
: "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 { useNavigate } from "react-router-dom";
|
||||||
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||||
import type { AnchorHTMLAttributes, HTMLAttributes, ReactNode } 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 { defaultUrlTransform } from "react-markdown";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -362,11 +362,27 @@ export function ArtifactFileDetail({
|
|||||||
isMock,
|
isMock,
|
||||||
writeFileInFlight,
|
writeFileInFlight,
|
||||||
]);
|
]);
|
||||||
/** write_file 流式预览走 tool args 文本;图片等二进制产物始终走 artifacts API;
|
const isVirtualHtmlArtifact = useMemo(() => {
|
||||||
* 圆桌结束后可编辑的 md(editVirtualMarkdown)亦回到真实 API(可加载 + PATCH 保存)。 */
|
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(() => {
|
const useWriteFileStreaming = useMemo(() => {
|
||||||
return isWriteFileVirtual && !isImageFile(filepath) && !editVirtualMarkdown;
|
return (
|
||||||
}, [filepath, isWriteFileVirtual, editVirtualMarkdown]);
|
isWriteFileVirtual &&
|
||||||
|
!isImageFile(filepath) &&
|
||||||
|
!editVirtualMarkdown &&
|
||||||
|
(!isVirtualHtmlArtifact || writeFileInFlight)
|
||||||
|
);
|
||||||
|
}, [
|
||||||
|
filepath,
|
||||||
|
isWriteFileVirtual,
|
||||||
|
editVirtualMarkdown,
|
||||||
|
isVirtualHtmlArtifact,
|
||||||
|
writeFileInFlight,
|
||||||
|
]);
|
||||||
const { isCodeFile, language } = useMemo(() => {
|
const { isCodeFile, language } = useMemo(() => {
|
||||||
if (useWriteFileStreaming) {
|
if (useWriteFileStreaming) {
|
||||||
let nextLanguage =
|
let nextLanguage =
|
||||||
@@ -398,11 +414,10 @@ export function ArtifactFileDetail({
|
|||||||
refetch: refetchArtifactContent,
|
refetch: refetchArtifactContent,
|
||||||
} = useArtifactContent({
|
} = useArtifactContent({
|
||||||
threadId,
|
threadId,
|
||||||
// editVirtualMarkdown:用解码后的真实路径走 artifacts API(而非 write-file 虚拟
|
// 流式结束后统一用解码后的真实路径走 artifacts API(而非 write-file 虚拟
|
||||||
// URL),这样保存后 useUpdateArtifactContent 写入的查询缓存才能命中,编辑内容
|
// URL)。HTML 可能已被后续渲染脚本覆盖;Markdown 保存后的查询缓存也需要
|
||||||
// 不会被旧的内存 stub 值覆盖回退。
|
// 命中真实路径,不能继续读取旧的内存 stub。
|
||||||
filepath:
|
filepath: useWriteFileStreaming ? filepathFromProps : filepath,
|
||||||
editVirtualMarkdown || !isWriteFileVirtual ? filepath : filepathFromProps,
|
|
||||||
enabled: isCodeFile && !useWriteFileStreaming,
|
enabled: isCodeFile && !useWriteFileStreaming,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -458,9 +473,10 @@ export function ArtifactFileDetail({
|
|||||||
const sandboxDisplayText = useMemo(() => {
|
const sandboxDisplayText = useMemo(() => {
|
||||||
const raw = displayContent ?? "";
|
const raw = displayContent ?? "";
|
||||||
if (disableDesensitize) return raw;
|
if (disableDesensitize) return raw;
|
||||||
|
if (language === "html") return raw;
|
||||||
if (streamPerfEnabled && isLiveStreaming) return raw;
|
if (streamPerfEnabled && isLiveStreaming) return raw;
|
||||||
return desensitize(raw);
|
return desensitize(raw);
|
||||||
}, [disableDesensitize, displayContent, isLiveStreaming, streamPerfEnabled]);
|
}, [disableDesensitize, displayContent, isLiveStreaming, language, streamPerfEnabled]);
|
||||||
const artifactContentPending =
|
const artifactContentPending =
|
||||||
isCodeFile &&
|
isCodeFile &&
|
||||||
!useWriteFileStreaming &&
|
!useWriteFileStreaming &&
|
||||||
@@ -1690,8 +1706,16 @@ export function ArtifactFileDetail({
|
|||||||
)}
|
)}
|
||||||
<ArtifactAction
|
<ArtifactAction
|
||||||
icon={DownloadIcon}
|
icon={DownloadIcon}
|
||||||
label={t.common.download}
|
label={
|
||||||
tooltip={t.common.download}
|
language === "html" && !useWriteFileStreaming && !onDownloadClick
|
||||||
|
? "下载离线包"
|
||||||
|
: t.common.download
|
||||||
|
}
|
||||||
|
tooltip={
|
||||||
|
language === "html" && !useWriteFileStreaming && !onDownloadClick
|
||||||
|
? "下载包含网页运行库的 ZIP 离线包"
|
||||||
|
: t.common.download
|
||||||
|
}
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (onDownloadClick) {
|
if (onDownloadClick) {
|
||||||
onDownloadClick();
|
onDownloadClick();
|
||||||
@@ -2205,6 +2229,7 @@ export function ArtifactFilePreview({
|
|||||||
if (language === "html") {
|
if (language === "html") {
|
||||||
return (
|
return (
|
||||||
<iframe
|
<iframe
|
||||||
|
key={htmlPreviewUrl ?? "html-preview"}
|
||||||
className={cn(
|
className={cn(
|
||||||
"size-full bg-white",
|
"size-full bg-white",
|
||||||
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
|
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { DownloadIcon, LoaderIcon, PackageIcon } from "lucide-react";
|
import { DownloadIcon, LoaderIcon, PackageIcon } from "lucide-react";
|
||||||
import { useCallback, useState, type ReactNode } from "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 { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -130,7 +130,9 @@ export function ArtifactFileList({
|
|||||||
) : (
|
) : (
|
||||||
<DownloadIcon className="size-4" />
|
<DownloadIcon className="size-4" />
|
||||||
)}
|
)}
|
||||||
{t.common.download}
|
{!onDownloadArtifact && /\.(?:html?|xhtml)$/i.test(getFileName(file))
|
||||||
|
? "下载离线包"
|
||||||
|
: t.common.download}
|
||||||
</Button>
|
</Button>
|
||||||
</CardAction>
|
</CardAction>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
useState,
|
useState,
|
||||||
type ReactNode,
|
type ReactNode,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { useSidebarSafe } from "@/components/ui/sidebar";
|
import { useSidebarSafe } from "@/components/ui/sidebar";
|
||||||
import { env } from "@/env";
|
import { env } from "@/env";
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { AlertCircleIcon, Loader2Icon, PackageIcon } from "lucide-react";
|
import { AlertCircleIcon, Loader2Icon, PackageIcon } from "lucide-react";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
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]!;
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
import { PromptInputProvider } from "@/components/ai-elements/prompt-input";
|
||||||
|
import { ArtifactsProvider } from "@/components/workspace/artifacts";
|
||||||
|
import { DocumentRewritePresentationProvider } from "@/core/document-rewrite/context";
|
||||||
|
import { SubtasksProvider } from "@/core/tasks/context";
|
||||||
|
import { useUploadPolicy } from "@/core/uploads";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared providers required by every full chat surface.
|
||||||
|
*
|
||||||
|
* Keep this in a small standalone module: importing it from a route must not
|
||||||
|
* eagerly evaluate the complete WorkspaceRoutes tree and all of its pages.
|
||||||
|
*/
|
||||||
|
export function ChatRuntime({ children }: { children: ReactNode }) {
|
||||||
|
const { data: uploadPolicy } = useUploadPolicy();
|
||||||
|
return (
|
||||||
|
<SubtasksProvider>
|
||||||
|
<DocumentRewritePresentationProvider>
|
||||||
|
<ArtifactsProvider>
|
||||||
|
<PromptInputProvider uploadPolicy={uploadPolicy}>
|
||||||
|
{children}
|
||||||
|
</PromptInputProvider>
|
||||||
|
</ArtifactsProvider>
|
||||||
|
</DocumentRewritePresentationProvider>
|
||||||
|
</SubtasksProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { Message } from "@langchain/langgraph-sdk";
|
import type { Message } from "@langchain/langgraph-sdk";
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
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 { usePathname, useSearchParams } from "next/navigation";
|
||||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||||
import type { GroupImperativeHandle } from "react-resizable-panels";
|
import type { GroupImperativeHandle } from "react-resizable-panels";
|
||||||
@@ -171,7 +171,14 @@ const ChatBox: React.FC<{
|
|||||||
const referencesEnabled = ragModeEnabled || hasFrontendRag;
|
const referencesEnabled = ragModeEnabled || hasFrontendRag;
|
||||||
const shouldFetchBackendReferenceBatches =
|
const shouldFetchBackendReferenceBatches =
|
||||||
referencesEnabled && !hasFrontendRag && !!threadId && threadId !== "new";
|
referencesEnabled && !hasFrontendRag && !!threadId && threadId !== "new";
|
||||||
const { skills } = useSkills();
|
const hasThreadMessages = (thread.values.messages?.length ?? 0) > 0;
|
||||||
|
const { skills } = useSkills({
|
||||||
|
enabled:
|
||||||
|
referencesEnabled &&
|
||||||
|
!!threadId &&
|
||||||
|
threadId !== "new" &&
|
||||||
|
(hasThreadMessages || thread.isLoading),
|
||||||
|
});
|
||||||
|
|
||||||
const canScanArtifactDirectory =
|
const canScanArtifactDirectory =
|
||||||
(artifactDirectoryModeEnabled || !!requestedArtifact || !!preferredArtifact) &&
|
(artifactDirectoryModeEnabled || !!requestedArtifact || !!preferredArtifact) &&
|
||||||
@@ -852,13 +859,48 @@ const ChatBox: React.FC<{
|
|||||||
</ResizablePanel>
|
</ResizablePanel>
|
||||||
<ResizableHandle
|
<ResizableHandle
|
||||||
id={`${resizableIdBase}-separator`}
|
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(
|
className={cn(
|
||||||
"opacity-33 hover:opacity-100",
|
"group/split z-20",
|
||||||
stackArtifactPanel &&
|
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",
|
? "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",
|
!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
|
<ResizablePanel
|
||||||
className={cn(
|
className={cn(
|
||||||
"bg-background transition-all duration-300 ease-in-out",
|
"bg-background transition-all duration-300 ease-in-out",
|
||||||
|
|||||||
@@ -1,26 +1,40 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
|
|
||||||
import { useTheme } from "@/contexts/ThemeContext";
|
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 { readRuntimeFlag } from "@/env";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { useDisplayDesensitizer } from "@/core/sensitive-words/use-display-desensitizer";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 紧凑模式(正常 App)新对话落地页的品牌欢迎块 —— 按 CM-assistant 参考图重画。
|
* 紧凑模式(正常 App)新对话落地页的品牌欢迎块 —— 按 CM-assistant 参考图重画。
|
||||||
* 仅展示,无交互。配色走主题 token(--workspace-brand / --primary),红/蓝/深蓝主题自适应。
|
* 仅展示,无交互。配色走主题 token(--workspace-brand / --primary),红/蓝/深蓝主题自适应。
|
||||||
* 非紧凑模式仍用 <Welcome/>,本组件不参与。
|
* 非紧凑模式仍用 <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 desensitizeText = useDisplayDesensitizer();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const brandTheme = theme;
|
const systemName = useAppSystemName("");
|
||||||
const welcomeLogo = getWelcomeBrandAsset(brandTheme);
|
const { data: pageDescriptions } = usePageDescriptionsSettings();
|
||||||
const [failedWelcomeLogo, setFailedWelcomeLogo] = useState<string | null>(null);
|
const configured = pageDescription ?? pageDescriptions?.general_qa.compact;
|
||||||
const shouldShowWelcomeLogo =
|
const welcomeTitle =
|
||||||
Boolean(welcomeLogo) && failedWelcomeLogo !== welcomeLogo;
|
configured?.welcome_title ||
|
||||||
|
(systemName ? `欢迎使用${systemName}` : "欢迎使用CM助手");
|
||||||
|
const welcomeDescription =
|
||||||
|
configured?.welcome_description ||
|
||||||
|
"基于先进深度推理模型,为您提供高效的市场分析、专业报告撰写、调研设计与协同脑暴支持。";
|
||||||
const isWelcomeLogoVisible = readRuntimeFlag("VITE_WELCOME_LOGO_VISIBLE");
|
const isWelcomeLogoVisible = readRuntimeFlag("VITE_WELCOME_LOGO_VISIBLE");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -30,47 +44,27 @@ export function CompactWelcome({ className }: { className?: string }) {
|
|||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{/* CM logo:浅底圆环 + 主色渐变圆角方块 */}
|
{/* 与全量模式共用同一套系统 Logo;简洁模式仅保留欢迎区的展示容器。 */}
|
||||||
{/* Controlled by VITE_WELCOME_LOGO_VISIBLE in runtime-config.js. */}
|
{/* Controlled by VITE_WELCOME_LOGO_VISIBLE in runtime-config.js. */}
|
||||||
{isWelcomeLogoVisible && (
|
{isWelcomeLogoVisible && (
|
||||||
<div
|
<div
|
||||||
className="mb-3.5 inline-flex items-center justify-center rounded-full p-3"
|
className="mb-3.5 inline-flex items-center justify-center rounded-full p-3"
|
||||||
style={{
|
style={{
|
||||||
backgroundColor:
|
backgroundColor:
|
||||||
"rgb(var(--legacy-workspace-brand-rgb) / 5%)",
|
"rgb(var(--legacy-workspace-brand-rgb) / 5%)",
|
||||||
border:
|
border:
|
||||||
"1px solid rgb(var(--legacy-workspace-brand-rgb) / 12%)",
|
"1px solid rgb(var(--legacy-workspace-brand-rgb) / 12%)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{shouldShowWelcomeLogo && welcomeLogo ? (
|
<AppBrandImage theme={theme} className="size-16 object-contain" />
|
||||||
<img
|
</div>
|
||||||
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>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<h1 className="flex items-center justify-center text-2xl font-bold tracking-tight text-foreground/90">
|
<h1 className="flex items-center justify-center text-2xl font-bold tracking-tight text-foreground/90">
|
||||||
{desensitizeText("欢迎使用CM助手")}
|
{desensitizeText(welcomeTitle)}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-muted-foreground mx-auto mt-2 max-w-sm text-xs leading-relaxed">
|
<p className="text-muted-foreground mx-auto mt-2 max-w-sm text-xs leading-relaxed">
|
||||||
基于先进深度推理模型,为您提供高效的市场分析、专业报告撰写、调研设计与协同脑暴支持。
|
{desensitizeText(welcomeDescription)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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 { CheckIcon, CopyIcon } from "lucide-react";
|
||||||
import { useCallback, useState, type ComponentProps } from "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 { Button } from "@/components/ui/button";
|
||||||
import { copyTextToClipboard } from "@/core/clipboard";
|
import { copyTextToClipboard } from "@/core/clipboard";
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
Trash2Icon,
|
Trash2Icon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useRef, useState } from "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 { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -162,7 +162,7 @@ export function CustomPromptBar({
|
|||||||
type="button"
|
type="button"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
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="管理常用提示词"
|
title="管理常用提示词"
|
||||||
aria-label="管理常用提示词"
|
aria-label="管理常用提示词"
|
||||||
onClick={() => setManageOpen(true)}
|
onClick={() => setManageOpen(true)}
|
||||||
@@ -194,7 +194,7 @@ function ManagePromptsDialog({
|
|||||||
const createPrompt = useCreateCustomPrompt();
|
const createPrompt = useCreateCustomPrompt();
|
||||||
const updatePrompt = useUpdateCustomPrompt();
|
const updatePrompt = useUpdateCustomPrompt();
|
||||||
const deletePrompt = useDeleteCustomPrompt();
|
const deletePrompt = useDeleteCustomPrompt();
|
||||||
const { agents } = useAgentSelector();
|
const { agents } = useAgentSelector({ enabled: open });
|
||||||
const preferences = useUserPreferences();
|
const preferences = useUserPreferences();
|
||||||
const updatePreferences = useUpdateUserPreferences();
|
const updatePreferences = useUpdateUserPreferences();
|
||||||
const [editingId, setEditingId] = useState<string | null>(null);
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { Download, FileJson, FileText, FileType2 } from "lucide-react";
|
import { Download, FileJson, FileText, FileType2 } from "lucide-react";
|
||||||
import { useCallback } from "react";
|
import { useCallback } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
import { Bot, ChevronRight } from "lucide-react";
|
import { Bot, ChevronRight } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { useMemo } from "react";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
SidebarGroup,
|
SidebarGroup,
|
||||||
@@ -13,12 +12,10 @@ import {
|
|||||||
SidebarMenuButton,
|
SidebarMenuButton,
|
||||||
SidebarMenuItem,
|
SidebarMenuItem,
|
||||||
} from "@/components/ui/sidebar";
|
} from "@/components/ui/sidebar";
|
||||||
import { useAgentsPaginated } from "@/core/agents";
|
import { useSidebarAgents } from "@/core/agents";
|
||||||
import type { Agent } from "@/core/agents";
|
|
||||||
import { desensitize } from "@/lib/desensitize";
|
import { desensitize } from "@/lib/desensitize";
|
||||||
|
|
||||||
/** 常用智能体最多展示个数(需求 1.2 ②)。 */
|
/** 常用智能体最多展示个数(需求 1.2 ②)。 */
|
||||||
const MAX_FREQUENT = 3;
|
|
||||||
|
|
||||||
/** 「更多」跳转目标:智能体管理页(需求 1.3)。 */
|
/** 「更多」跳转目标:智能体管理页(需求 1.3)。 */
|
||||||
const MORE_HREF = "/page/strategy/agents";
|
const MORE_HREF = "/page/strategy/agents";
|
||||||
@@ -40,33 +37,7 @@ function agentHomeHref(agentId: string): string {
|
|||||||
*/
|
*/
|
||||||
export function FrequentAgentsList() {
|
export function FrequentAgentsList() {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const { agents: mine } = useAgentsPaginated({
|
const { agents: frequent } = useSidebarAgents();
|
||||||
scope: "mine",
|
|
||||||
page: 1,
|
|
||||||
pageSize: 20,
|
|
||||||
});
|
|
||||||
const { agents: square } = useAgentsPaginated({
|
|
||||||
scope: "square",
|
|
||||||
page: 1,
|
|
||||||
pageSize: 20,
|
|
||||||
});
|
|
||||||
|
|
||||||
const frequent = useMemo<Agent[]>(() => {
|
|
||||||
const out: Agent[] = [];
|
|
||||||
const seen = new Set<string>();
|
|
||||||
const add = (agent: Agent | undefined) => {
|
|
||||||
if (!agent || out.length >= MAX_FREQUENT || seen.has(agent.id)) return;
|
|
||||||
seen.add(agent.id);
|
|
||||||
out.push(agent);
|
|
||||||
};
|
|
||||||
// 1. 置顶组优先(够 3 个则下面我的/广场都不再补)。
|
|
||||||
[...mine, ...square].filter((a) => a.is_pinned).forEach(add);
|
|
||||||
// 2. 我的智能体补足。
|
|
||||||
mine.forEach(add);
|
|
||||||
// 3. 广场默认推荐补足。
|
|
||||||
square.forEach(add);
|
|
||||||
return out;
|
|
||||||
}, [mine, square]);
|
|
||||||
|
|
||||||
if (frequent.length === 0) {
|
if (frequent.length === 0) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import {
|
|||||||
FileJson,
|
FileJson,
|
||||||
FileText,
|
FileText,
|
||||||
Loader2,
|
Loader2,
|
||||||
MessageSquare,
|
|
||||||
MoreHorizontal,
|
MoreHorizontal,
|
||||||
Pencil,
|
Pencil,
|
||||||
Pin,
|
Pin,
|
||||||
@@ -39,7 +38,7 @@ import Link from "next/link";
|
|||||||
import { useParams, usePathname, useRouter, useSearchParams } from "next/navigation";
|
import { useParams, usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { toast } from "sonner";
|
import { toast } from "@/core/ui/feedback";
|
||||||
import { Select } from "tdesign-react";
|
import { Select } from "tdesign-react";
|
||||||
|
|
||||||
import { useTheme } from "@/contexts/ThemeContext";
|
import { useTheme } from "@/contexts/ThemeContext";
|
||||||
@@ -68,7 +67,7 @@ import {
|
|||||||
MyProjectThreadBadge,
|
MyProjectThreadBadge,
|
||||||
MyProjectThreadIcon,
|
MyProjectThreadIcon,
|
||||||
} from "@/components/workspace/my-project-thread-indicator";
|
} from "@/components/workspace/my-project-thread-indicator";
|
||||||
import { useAgentsPaginated, type Agent } from "@/core/agents";
|
import { useAgentsPaginated, useSidebarAgents, type Agent } from "@/core/agents";
|
||||||
import { getAPIClient } from "@/core/api";
|
import { getAPIClient } from "@/core/api";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
import {
|
import {
|
||||||
@@ -106,15 +105,14 @@ import { cn } from "@/lib/utils";
|
|||||||
import { strategyProjectWorkbenchPath } from "@/strategy-selection/project-routes";
|
import { strategyProjectWorkbenchPath } from "@/strategy-selection/project-routes";
|
||||||
import {
|
import {
|
||||||
mergeRecentWorkspaceItems,
|
mergeRecentWorkspaceItems,
|
||||||
|
type RecentWorkspaceItem,
|
||||||
useRecentStrategyProjects,
|
useRecentStrategyProjects,
|
||||||
} from "@/strategy-selection/recent-projects";
|
} from "@/strategy-selection/recent-projects";
|
||||||
|
|
||||||
import { agentColor } from "./agent-icon-color";
|
import { agentColor } from "./agent-icon-color";
|
||||||
|
import { historyAvatarForThread } from "./chat-history-avatar";
|
||||||
import { SidebarCollapseButton } from "./workspace-header";
|
import { SidebarCollapseButton } from "./workspace-header";
|
||||||
|
|
||||||
/** 常用智能体最多展示个数。 */
|
|
||||||
const MAX_FREQUENT = 4;
|
|
||||||
|
|
||||||
// 智能体图标配色(按 id 稳定散列、分主题)抽到共享模块 ./agent-icon-color,
|
// 智能体图标配色(按 id 稳定散列、分主题)抽到共享模块 ./agent-icon-color,
|
||||||
// 与 zzJC/zzXD 模块左栏(AgentModuleSidebar)共用,保证彩色卡片配色完全一致。
|
// 与 zzJC/zzXD 模块左栏(AgentModuleSidebar)共用,保证彩色卡片配色完全一致。
|
||||||
|
|
||||||
@@ -156,7 +154,7 @@ function SectionLabel({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type CommonAgent = Pick<Agent, "id" | "name" | "description">;
|
type CommonAgent = Pick<Agent, "id" | "name"> & { description?: string };
|
||||||
|
|
||||||
/** wx 左栏固定的智能体类型;南京-db 广场尚未创建时筛空列表。 */
|
/** wx 左栏固定的智能体类型;南京-db 广场尚未创建时筛空列表。 */
|
||||||
const WX_AGENT_TYPE_MINE = "mine";
|
const WX_AGENT_TYPE_MINE = "mine";
|
||||||
@@ -253,19 +251,9 @@ export function GeneralQaSidebar({
|
|||||||
return !v;
|
return !v;
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── 常用智能体取数:wx 走类型筛选;其它页面仍是置顶 → 我的 → 广场 ──
|
// The ordinary full-page sidebar only needs three id/name rows. WX-specific
|
||||||
const { agents: mine } = useAgentsPaginated({
|
// catalog pages keep their richer, filtered result below.
|
||||||
scope: "mine",
|
const { agents: sidebarAgents } = useSidebarAgents({ enabled: !wxCommonAgents });
|
||||||
page: 1,
|
|
||||||
pageSize: 20,
|
|
||||||
enabled: !wxCommonAgents,
|
|
||||||
});
|
|
||||||
const { agents: square } = useAgentsPaginated({
|
|
||||||
scope: "square",
|
|
||||||
page: 1,
|
|
||||||
pageSize: 20,
|
|
||||||
enabled: !wxCommonAgents,
|
|
||||||
});
|
|
||||||
const {
|
const {
|
||||||
agents: wxAgents,
|
agents: wxAgents,
|
||||||
total: wxTotal,
|
total: wxTotal,
|
||||||
@@ -283,18 +271,8 @@ export function GeneralQaSidebar({
|
|||||||
if (wxCommonAgents) {
|
if (wxCommonAgents) {
|
||||||
return wxFetchEnabled ? wxAgents : [];
|
return wxFetchEnabled ? wxAgents : [];
|
||||||
}
|
}
|
||||||
const out: Agent[] = [];
|
return sidebarAgents;
|
||||||
const seen = new Set<string>();
|
}, [sidebarAgents, wxAgents, wxCommonAgents, wxFetchEnabled]);
|
||||||
const add = (agent: Agent | undefined) => {
|
|
||||||
if (!agent || out.length >= MAX_FREQUENT || seen.has(agent.id)) return;
|
|
||||||
seen.add(agent.id);
|
|
||||||
out.push(agent);
|
|
||||||
};
|
|
||||||
[...mine, ...square].filter((a) => a.is_pinned).forEach(add);
|
|
||||||
mine.forEach(add);
|
|
||||||
square.forEach(add);
|
|
||||||
return out;
|
|
||||||
}, [mine, square, wxAgents, wxCommonAgents, wxFetchEnabled]);
|
|
||||||
const wxEmptyHint =
|
const wxEmptyHint =
|
||||||
wxAgentType === WX_AGENT_TYPE_NANJING_DB && !wxSquareId
|
wxAgentType === WX_AGENT_TYPE_NANJING_DB && !wxSquareId
|
||||||
? "该类型暂无智能体"
|
? "该类型暂无智能体"
|
||||||
@@ -401,7 +379,6 @@ export function GeneralQaSidebar({
|
|||||||
// 未搜索时与旧版一致:最多展示 10 条
|
// 未搜索时与旧版一致:最多展示 10 条
|
||||||
return q ? list : list.slice(0, 10);
|
return q ? list : list.slice(0, 10);
|
||||||
}, [query, recentItems, t.pages.newChat]);
|
}, [query, recentItems, t.pages.newChat]);
|
||||||
|
|
||||||
const handleNewChatClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
|
const handleNewChatClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
|
||||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.button === 1) return;
|
if (event.metaKey || event.ctrlKey || event.shiftKey || event.button === 1) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -474,6 +451,176 @@ export function GeneralQaSidebar({
|
|||||||
|
|
||||||
const isStatic = env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true";
|
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 (
|
return (
|
||||||
// 背景走 sidebar token(浅主题=白、浅蓝主题=浅蓝);深蓝(.dark)主题下由 gq-sidebar
|
// 背景走 sidebar token(浅主题=白、浅蓝主题=浅蓝);深蓝(.dark)主题下由 gq-sidebar
|
||||||
// 改为「深蓝主题底图 + 半透明蓝罩」玻璃面板(见 globals.css),与右侧 workspace-chat-bg
|
// 改为「深蓝主题底图 + 半透明蓝罩」玻璃面板(见 globals.css),与右侧 workspace-chat-bg
|
||||||
@@ -641,7 +788,7 @@ export function GeneralQaSidebar({
|
|||||||
: "text-muted-foreground",
|
: "text-muted-foreground",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{agent.description ? desensitize(agent.description) : "智能体助手"}
|
{wxCommonAgents && agent.description ? desensitize(agent.description) : "智能体助手"}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
{isActive && (
|
{isActive && (
|
||||||
@@ -733,191 +880,7 @@ export function GeneralQaSidebar({
|
|||||||
{query ? "没有匹配的会话" : t.chats.noChats}
|
{query ? "没有匹配的会话" : t.chats.noChats}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
filteredRecentItems.map((item) => {
|
filteredRecentItems.map(renderRecentHistoryItem)
|
||||||
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>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
)}
|
||||||
{!query && (
|
{!query && (
|
||||||
<Link
|
<Link
|
||||||
|
|||||||