sync update from LAN repo (source dhk-1 @ fc974e93)

This commit is contained in:
gozeros committed 2026-11-17 11:28:44 +08:00
1 parent a1fa13a238
commit e2fea6a801
432 files changed
+68707 -2270

No files matched your search

+3
View File
@@ -95,6 +95,9 @@ offline-backend-20260512/backend/packages/harness/deerflow/skills/*
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_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
@@ -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,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. 无公网网络下,项目缩略图、模板封面和默认瓦片可正常加载。
+1 -1
View File
@@ -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 渲染 |
@@ -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` 跟手卡片。
@@ -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 预览 | 文本类 → 模态预览;其它 → 新窗口下载 |
--- ---
+4 -4
View File
@@ -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")` |
-9
View File
@@ -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",
+1 -1
View File
@@ -24,6 +24,7 @@
"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 src/components/workspace/visualizations/map-style.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: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",
@@ -111,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",
-2
View File
@@ -6,7 +6,6 @@ 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 { RouteLoadingFallback } from "@/components/route-loading";
import { Toaster } from "@/components/ui/sonner";
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";
@@ -209,7 +208,6 @@ export function App() {
element={ element={
<div className="h-dvh overflow-hidden"> <div className="h-dvh overflow-hidden">
<MarkdownDocxEditorPage /> <MarkdownDocxEditorPage />
<Toaster />
</div> </div>
} }
/> />
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

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

@@ -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
@@ -1225,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}
@@ -1287,28 +1287,29 @@ export const PromptInputSubmit = ({
status, status,
children, children,
...props ...props
}: PromptInputSubmitProps) => { }: PromptInputSubmitProps) => {
let Icon = <ArrowUpIcon className="size-4" />; let Icon = <ArrowUpIcon className="size-4" />;
let ariaLabel = "发送消息"; let ariaLabel = "发送消息";
if (status === "submitted") { if (status === "submitted") {
Icon = <Loader2Icon className="size-4 animate-spin" />; Icon = <Loader2Icon className="size-4 animate-spin" />;
ariaLabel = "正在发送"; ariaLabel = "正在发送";
} else if (status === "streaming") { } else if (status === "streaming") {
Icon = <SquareIcon className="size-4" />; Icon = <SquareIcon className="size-4" />;
ariaLabel = "停止生成"; ariaLabel = "停止生成";
} else if (status === "error") { } else if (status === "error") {
Icon = <XIcon className="size-4" />; Icon = <XIcon className="size-4" />;
ariaLabel = "重新发送"; ariaLabel = "重新发送";
} }
return ( return (
<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";
@@ -24,7 +24,7 @@ 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 "./document-upload-popup.css";
@@ -20,7 +20,7 @@ import {
UsersRound, UsersRound,
} 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 { 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";
@@ -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" />
-40
View File
@@ -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);
@@ -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 {
@@ -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";
@@ -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";
@@ -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,7 +1,6 @@
"use client"; "use client";
import { import {
BotIcon,
ClockIcon, ClockIcon,
CopyIcon, CopyIcon,
EyeIcon, EyeIcon,
@@ -9,6 +8,7 @@ import {
GlobeIcon, GlobeIcon,
LockIcon, LockIcon,
MessageSquareIcon, MessageSquareIcon,
MoreHorizontalIcon,
PinIcon, PinIcon,
ShieldIcon, ShieldIcon,
SparklesIcon, SparklesIcon,
@@ -27,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";
@@ -47,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,
@@ -94,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
@@ -497,7 +506,7 @@ export function AgentCard({
setPublishPickerOpen(true); setPublishPickerOpen(true);
return; return;
} }
if (!warnIfAccountSwitched()) { if (!(await warnIfAccountSwitched())) {
return; return;
} }
try { try {
@@ -515,18 +524,22 @@ export function AgentCard({
// 发布操作以实时 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 {
@@ -608,6 +621,12 @@ export function AgentCard({
// 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">
内置 内置
@@ -730,7 +749,12 @@ export function AgentCard({
...(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>
), ),
@@ -740,8 +764,8 @@ export function AgentCard({
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();
@@ -916,74 +940,193 @@ export function AgentCard({
const chatButton = ( const chatButton = (
<Button <Button
variant={isList ? "default" : "outline"}
size="sm" size="sm"
className={cn(isList ? "shrink-0" : "w-full")} className={cn(
isList
? "shrink-0 rounded-xl bg-primary px-4 font-medium text-primary-foreground hover:bg-primary/90"
: "h-11 w-full rounded-lg border-primary/35 bg-background font-medium text-primary shadow-none hover:border-primary/55 hover:bg-primary/5 dark:bg-slate-900",
)}
onClick={() => void handleChat()} 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={cn( className={cn(
"group flex min-w-0 flex-col transition-shadow hover:shadow-md", "group flex min-h-[300px] min-w-0 flex-col gap-0 overflow-hidden rounded-[5px] border-0 bg-gradient-to-br from-primary/[0.04] via-card to-card py-0 shadow-[0_2px_8px_rgba(15,23,42,0.06)] transition-[background-color,border-color,box-shadow] duration-200 hover:!shadow-[0_4px_14px_rgba(15,23,42,0.10)] dark:from-primary/[0.07] dark:via-card dark:to-card",
(agent.featured_order != null || agent.is_pinned) && "ring-1 ring-primary/25",
agent.hidden && "opacity-60", 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>
@@ -992,14 +1135,14 @@ export function AgentCard({
const listLayout = ( const listLayout = (
<div <div
className={cn( className={cn(
"group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]", "group flex min-w-0 items-center gap-3 rounded-[5px] border-0 p-2.5 shadow-[0_2px_8px_rgba(15,23,42,0.06)] transition-shadow hover:shadow-[0_4px_14px_rgba(15,23,42,0.10)]",
"bg-gradient-to-br from-primary/[0.04] via-card to-card dark:from-primary/[0.07] dark:via-card dark:to-card",
agent.is_pinned && "ring-1 ring-primary/25",
agent.hidden && "opacity-60", 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
@@ -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,6 +6,7 @@ import {
CheckIcon, CheckIcon,
DatabaseIcon, DatabaseIcon,
GlobeIcon, GlobeIcon,
GripVertical,
InfoIcon, InfoIcon,
// Link2Icon, // Link2Icon,
Loader2Icon, Loader2Icon,
@@ -23,8 +24,17 @@ 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 { AgentChatLinkFields } from "@/components/workspace/agents/agent-chat-link-fields";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@@ -79,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 {
@@ -128,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}
@@ -225,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);
@@ -444,7 +581,7 @@ export function AgentDetailPanel({
setPublishPickerOpen(true); setPublishPickerOpen(true);
return; return;
} }
if (!warnIfAccountSwitched()) { if (!(await warnIfAccountSwitched())) {
return; return;
} }
try { try {
@@ -462,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 {
@@ -625,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 ? (
@@ -646,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}
@@ -681,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>
) : ( ) : (
@@ -855,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]" />
添加常用问题 添加常用问题
@@ -867,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">
@@ -1045,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">
@@ -3,17 +3,20 @@
import { ArrowDownUpIcon, BotIcon, Compass, Loader2, LockIcon, PlusIcon, RefreshCwIcon, 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, useSyncAgentDirectory } 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";
@@ -264,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}
@@ -276,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}
@@ -339,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>
@@ -367,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>
)} )}
@@ -458,22 +492,32 @@ 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"> <div className="flex items-center gap-2">
{pageDescription?.title || t.agents.title} <span className="h-4 w-[3px] rounded-full bg-primary" aria-hidden />
</h1> <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">
{pageDescription?.description || 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 && ( {isAdmin && (
<Button <Button
variant="outline" variant="ghost"
size="sm" 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 目录,把目录里的智能体同步进列表" title="扫描 .deer-flow/agents 目录,把目录里的智能体同步进列表"
disabled={syncDirectory.isPending} disabled={syncDirectory.isPending}
onClick={() => { onClick={() => {
@@ -492,14 +536,15 @@ export function AgentGallery({
}} }}
> >
<RefreshCwIcon <RefreshCwIcon
className={`mr-1.5 h-4 w-4 ${syncDirectory.isPending ? "animate-spin" : ""}`} className={`h-4 w-4 ${syncDirectory.isPending ? "animate-spin" : ""}`}
/> />
{syncDirectory.isPending ? "扫描中…" : "重新扫描智能体目录"} {syncDirectory.isPending ? "扫描中…" : "重新扫描智能体目录"}
</Button> </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`)}
> >
@@ -508,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 {
@@ -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";
@@ -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 {
@@ -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 {
@@ -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]!;
}
@@ -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";
@@ -859,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,7 +1,8 @@
"use client"; "use client";
import { FileSpreadsheet } from "lucide-react"; import { Download } from "lucide-react";
import { useCallback } from "react"; import { useCallback } from "react";
import { toast } from "@/core/ui/feedback";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { consumerThreadMaterialsDownloadUrl } from "@/core/threads/consumer-thread-values-client"; import { consumerThreadMaterialsDownloadUrl } from "@/core/threads/consumer-thread-values-client";
@@ -9,6 +10,33 @@ import { consumerThreadMaterialsDownloadUrl } from "@/core/threads/consumer-thre
import { useThread } from "./messages/context"; import { useThread } from "./messages/context";
import { Tooltip } from "./tooltip"; 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. */ /** Downloads the Consumer-maintained source-material workbook for this chat. */
export function ConsumerMaterialsExportTrigger({ export function ConsumerMaterialsExportTrigger({
threadId, threadId,
@@ -19,7 +47,13 @@ export function ConsumerMaterialsExportTrigger({
const downloadUrl = consumerThreadMaterialsDownloadUrl(threadId); const downloadUrl = consumerThreadMaterialsDownloadUrl(threadId);
const handleDownload = useCallback(() => { const handleDownload = useCallback(() => {
if (!downloadUrl) return; if (!downloadUrl) return;
window.open(downloadUrl, "_blank", "noopener,noreferrer");
// 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]); }, [downloadUrl]);
if (thread.messages.length === 0) return null; if (thread.messages.length === 0) return null;
@@ -35,7 +69,7 @@ export function ConsumerMaterialsExportTrigger({
disabled={!downloadUrl} disabled={!downloadUrl}
onClick={handleDownload} onClick={handleDownload}
> >
<FileSpreadsheet /> <Download className="size-4" aria-hidden="true" />
导出资料 导出资料
</Button> </Button>
</Tooltip> </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)}
@@ -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 {
@@ -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";
@@ -106,10 +105,12 @@ 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";
// 智能体图标配色(按 id 稳定散列、分主题)抽到共享模块 ./agent-icon-color, // 智能体图标配色(按 id 稳定散列、分主题)抽到共享模块 ./agent-icon-color,
@@ -378,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();
@@ -451,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
@@ -710,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
@@ -1,7 +1,7 @@
"use client"; "use client";
import type { ChatStatus } from "ai"; import type { ChatStatus } from "ai";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import { import {
BookMarkedIcon, BookMarkedIcon,
BrainCircuitIcon, BrainCircuitIcon,
@@ -144,6 +144,8 @@ export function InputBox({
assistantId, assistantId,
hideAdminRecommendedQuestions, hideAdminRecommendedQuestions,
compact, compact,
mirrorLandingFrame = false,
frameRadius = "default",
hideContextTools, hideContextTools,
composerHeightPercent, composerHeightPercent,
...props ...props
@@ -153,6 +155,13 @@ export function InputBox({
/** 紧凑模式(正常 App)新对话落地态:去掉旋转彩边、用 CM 参考图的白卡输入框, /** 紧凑模式(正常 App)新对话落地态:去掉旋转彩边、用 CM 参考图的白卡输入框,
* 并在推荐问题上方加「试试这些高频业务场景」标题。仅落地态生效,默认 false。 */ * 并在推荐问题上方加「试试这些高频业务场景」标题。仅落地态生效,默认 false。 */
compact?: boolean; compact?: boolean;
/**
* Reuse the non-compact new-chat visual frame for a conversation composer.
* This changes only the border shell; conversation behavior remains intact.
*/
mirrorLandingFrame?: boolean;
/** Visual-only radius variant for a mirrored landing frame. */
frameRadius?: "default" | "tight";
/** 隐藏输入框工具条上的「写作 / 参考文献」上下文开关按钮(任务深链工作区等 /** 隐藏输入框工具条上的「写作 / 参考文献」上下文开关按钮(任务深链工作区等
* 受控场景用;文件/模型等其他按钮不受影响)。 */ * 受控场景用;文件/模型等其他按钮不受影响)。 */
hideContextTools?: boolean; hideContextTools?: boolean;
@@ -727,6 +736,7 @@ export function InputBox({
maxHeight: `max(12rem, calc(${composerMinHeight} + 8rem))`, maxHeight: `max(12rem, calc(${composerMinHeight} + 8rem))`,
} }
: undefined; : undefined;
const usesGeminiFrame = !compact && (isNewThread || mirrorLandingFrame);
return ( return (
<div ref={promptRootRef} className="relative flex flex-col gap-6"> <div ref={promptRootRef} className="relative flex flex-col gap-6">
@@ -744,7 +754,7 @@ export function InputBox({
<button <button
key={question} key={question}
type="button" type="button"
className="max-w-full rounded-full border border-primary/20 bg-primary/5 px-4 py-2 text-left text-sm text-foreground transition-colors hover:bg-primary/10" className="agent-suggested-chip max-w-full rounded-full border px-4 py-2 text-left text-sm text-foreground transition-colors"
onClick={() => { onClick={() => {
fillPromptForEditing(question); fillPromptForEditing(question);
}} }}
@@ -820,26 +830,42 @@ export function InputBox({
}} }}
/> />
)} )}
<div className={cn(isNewThread && !compact && "gemini-gradient-border gemini-shadow")}> <div
className={cn(
usesGeminiFrame && "gemini-gradient-border gemini-shadow",
// 对话态(含紧凑会话):文心一言式外壳 —— 空闲主题色浅边白卡,
// 生成中主题色渐变流光描边(globals.css .composer-shell)。
// 落地态(Gemini 彩灯)与紧凑落地白卡维持各自形态。
!usesGeminiFrame &&
!(compact && isNewThread) &&
(composerStatus === "streaming"
? "composer-shell composer-shell--streaming"
: "composer-shell composer-shell--idle"),
)}
data-frame-radius={
usesGeminiFrame && frameRadius !== "default" ? frameRadius : undefined
}
>
<PromptInput <PromptInput
style={ style={
composerMinHeight ? { minHeight: composerMinHeight } : undefined composerMinHeight ? { minHeight: composerMinHeight } : undefined
} }
className={cn( className={cn(
"transition-all duration-300 ease-out", "transition-all duration-300 ease-out",
// 紧凑落地态(CM 参考图):表单作为白卡,内部 input-group 透明无边框, // 内部 input-group:紧凑落地白卡与对话态外壳都去掉自带描边/底色,
// 避免双层描边;圆角对齐 2xl。 // 只保留外层一层描边(Gemini 落地态维持现状的双层结构不动)。
compact && isNewThread compact && isNewThread
? "*:data-[slot='input-group']:rounded-2xl *:data-[slot='input-group']:border-0 *:data-[slot='input-group']:bg-transparent *:data-[slot='input-group']:shadow-none" ? "*:data-[slot='input-group']:rounded-2xl *:data-[slot='input-group']:border-0 *:data-[slot='input-group']:bg-transparent *:data-[slot='input-group']:shadow-none"
: "*:data-[slot='input-group']:rounded-3xl", : usesGeminiFrame
? "*:data-[slot='input-group']:rounded-3xl"
: "*:data-[slot='input-group']:rounded-3xl *:data-[slot='input-group']:border-0 *:data-[slot='input-group']:bg-transparent *:data-[slot='input-group']:shadow-none",
// 紧凑落地态(CM 参考图):白卡 + 细边 + 轻阴影 + 主色聚焦环(无旋转彩边) // 紧凑落地态(CM 参考图):白卡 + 细边 + 轻阴影 + 主色聚焦环(无旋转彩边)
compact && isNewThread compact && isNewThread
? "rounded-2xl border border-gray-200/70 bg-white overflow-hidden shadow-[0_4.5px_22px_rgba(0,0,0,0.025)] transition-all duration-300 focus-within:border-[rgb(var(--legacy-primary-rgb)/35%)] focus-within:ring-4 focus-within:ring-[rgb(var(--legacy-primary-rgb)/5%)] focus-within:shadow-[0_10px_35px_rgb(var(--legacy-primary-rgb)/4%)] dark:border-slate-700 dark:bg-slate-800" ? "rounded-2xl border border-gray-200/70 bg-white overflow-hidden shadow-[0_4.5px_22px_rgba(0,0,0,0.025)] transition-all duration-300 focus-within:border-[rgb(var(--legacy-primary-rgb)/35%)] focus-within:ring-4 focus-within:ring-[rgb(var(--legacy-primary-rgb)/5%)] focus-within:shadow-[0_10px_35px_rgb(var(--legacy-primary-rgb)/4%)] dark:border-slate-700 dark:bg-slate-800"
: // landing 态:透明,让外层 gemini-gradient-border 提供白卡 + 旋转描边 : // 表单本体一律透明:落地态由外层 gemini-gradient-border 供白卡 +
// 对话态:常规白卡 + 中性边框 + 轻阴影 // 旋转彩边,对话态由外层 composer-shell 供边框/底色/阴影,
isNewThread // 避免双层描边。
? "rounded-3xl bg-transparent border-0 shadow-none ring-0" "rounded-3xl bg-transparent border-0 shadow-none ring-0",
: "rounded-3xl bg-background border border-border shadow-sm transition-shadow hover:shadow-md focus-within:border-ring/40 focus-within:shadow-md focus-within:ring-1 focus-within:ring-ring/20 dark:bg-slate-800 dark:border-slate-700",
className, className,
)} )}
disabled={disabled} disabled={disabled}
@@ -1449,11 +1475,9 @@ export function InputBox({
</ModelSelectorContent> </ModelSelectorContent>
</ModelSelector>} </ModelSelector>}
<PromptInputSubmit <PromptInputSubmit
className={cn( // 皮肤(主题色扁平渐变圆钮 / 流式低对比停止钮)统一由 globals.css 的
"rounded-full border-border bg-background shadow-sm hover:bg-muted dark:bg-blue-500 dark:border-blue-500 dark:text-white dark:hover:bg-blue-400 dark:shadow-none", // .agent-composer-send 提供,这里只保留紧凑落地档的小尺寸。
compact && className={cn(compact && "size-7")}
"size-7 rounded-lg border-0 bg-[var(--primary)] text-[var(--button-foreground,var(--primary-foreground))] hover:opacity-90 disabled:bg-muted disabled:text-muted-foreground/40 dark:bg-[var(--primary)] dark:border-0 dark:text-[var(--button-foreground,var(--primary-foreground))] dark:hover:opacity-90 dark:disabled:bg-muted",
)}
disabled={disabled} disabled={disabled}
onClick={(event) => { onClick={(event) => {
if (composerStatus !== "streaming") return; if (composerStatus !== "streaming") return;
@@ -1462,7 +1486,6 @@ export function InputBox({
event.preventDefault(); event.preventDefault();
handleStopCurrentGeneration(); handleStopCurrentGeneration();
}} }}
variant="outline"
status={composerStatus} status={composerStatus}
{...(documentRewriteActive {...(documentRewriteActive
? { "aria-label": "停止 AI 全文改写" } ? { "aria-label": "停止 AI 全文改写" }
@@ -2,7 +2,7 @@
import { BookMarked } from "lucide-react"; import { BookMarked } from "lucide-react";
import { useState } from "react"; import { 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 { useKnowledgeActions } from "@/core/knowledge/hooks"; import { useKnowledgeActions } from "@/core/knowledge/hooks";
@@ -608,7 +608,7 @@ export function LlmWikiKnowledgeSelector({
variant="ghost" variant="ghost"
size="sm" size="sm"
className={cn( className={cn(
"h-8 max-w-52 gap-1.5 rounded-full border-0 bg-transparent px-2.5 text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground", "agent-composer-tool h-8 max-w-52 gap-1.5 rounded-full border-0 bg-transparent px-2.5 text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground",
selectedCount > 0 && "bg-primary/8 text-primary hover:bg-primary/12 hover:text-primary", selectedCount > 0 && "bg-primary/8 text-primary hover:bg-primary/12 hover:text-primary",
className, className,
)} )}
@@ -7,7 +7,7 @@ import {
ThumbsUpIcon, ThumbsUpIcon,
} from "lucide-react"; } from "lucide-react";
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 {
@@ -1,6 +1,6 @@
import { Trash2Icon } from "lucide-react"; import { Trash2Icon } from "lucide-react";
import { useState } from "react"; import { 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 {
@@ -12,7 +12,7 @@ import {
XCircleIcon, XCircleIcon,
} from "lucide-react"; } from "lucide-react";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { ArtifactFileList } from "@/components/workspace/artifacts/artifact-file-list"; import { ArtifactFileList } from "@/components/workspace/artifacts/artifact-file-list";
@@ -1,6 +1,6 @@
import { FileText, Loader2, MessagesSquare } from "lucide-react"; import { FileText, Loader2, MessagesSquare } from "lucide-react";
import { useState, type ComponentProps } from "react"; import { 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 { import {
@@ -1,6 +1,6 @@
import { ChevronDownIcon, DownloadIcon, EyeIcon, Loader2Icon } from "lucide-react"; import { ChevronDownIcon, DownloadIcon, EyeIcon, Loader2Icon } from "lucide-react";
import { useContext, useState } from "react"; import { useContext, 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 {
@@ -36,6 +36,11 @@ export function ModelNameSelect({
title?: string; title?: string;
}) { }) {
const { models } = useModels(); const { models } = useModels();
// 后端约定:配置顺序的第一个模型即默认对话模型(models[0])。
const defaultModel = models[0];
const defaultModelLabel = defaultModel
? `${defaultModel.display_name || defaultModel.name}(默认)`
: defaultLabel;
return ( return (
<Select <Select
value={value ?? DEFAULT_VALUE} value={value ?? DEFAULT_VALUE}
@@ -46,10 +51,10 @@ export function ModelNameSelect({
className={cn("h-8 gap-1.5 text-xs", triggerClassName, className)} className={cn("h-8 gap-1.5 text-xs", triggerClassName, className)}
title={title} title={title}
> >
<SelectValue placeholder={defaultLabel} /> <SelectValue placeholder={defaultModelLabel} />
</SelectTrigger> </SelectTrigger>
<SelectContent position="popper" side="bottom" sideOffset={4}> <SelectContent position="popper" side="bottom" sideOffset={4}>
<SelectItem value={DEFAULT_VALUE}>{defaultLabel}</SelectItem> <SelectItem value={DEFAULT_VALUE}>{defaultModelLabel}</SelectItem>
{models.map((m) => ( {models.map((m) => (
<SelectItem key={m.name} value={m.name}> <SelectItem key={m.name} value={m.name}>
{m.display_name || m.name} {m.display_name || m.name}
@@ -10,7 +10,7 @@ import {
XIcon, XIcon,
} from "lucide-react"; } from "lucide-react";
import { useState } from "react"; import { 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 {
@@ -7,19 +7,19 @@ import {
Download, Download,
FileJson, FileJson,
FileText, FileText,
MessageSquare,
MoreHorizontal, MoreHorizontal,
Pencil, Pencil,
Pin, Pin,
PinOff, PinOff,
Search,
Share2, Share2,
Star, Star,
Trash2, Trash2,
} from "lucide-react"; } from "lucide-react";
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, useState } from "react"; import { useCallback, 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 {
@@ -91,6 +91,8 @@ import {
useRecentStrategyProjects, useRecentStrategyProjects,
} from "@/strategy-selection/recent-projects"; } from "@/strategy-selection/recent-projects";
import { historyAvatarForThread } from "./chat-history-avatar";
export function RecentChatList({ export function RecentChatList({
compact = false, compact = false,
limit, limit,
@@ -137,6 +139,7 @@ export function RecentChatList({
// Share dialog state — the conversation whose share code is being shown. // Share dialog state — the conversation whose share code is being shown.
const [shareThreadId, setShareThreadId] = useState<string | null>(null); const [shareThreadId, setShareThreadId] = useState<string | null>(null);
const [query, setQuery] = useState("");
const handleDelete = useCallback( const handleDelete = useCallback(
(threadId: string) => { (threadId: string) => {
@@ -218,10 +221,27 @@ export function RecentChatList({
recentStrategyProjects, recentStrategyProjects,
); );
if (recentItems.length === 0) { const shownItems = useMemo(() => {
return null; const normalizedQuery = query.trim().toLowerCase();
} const matchingItems = normalizedQuery
const shownItems = limit != null ? recentItems.slice(0, limit) : recentItems; ? recentItems.filter((item) =>
(item.kind === "thread"
? titleOfThread(item.thread, t.pages.newChat)
: item.project.title
)
.toLowerCase()
.includes(normalizedQuery),
)
: recentItems;
return normalizedQuery || limit == null
? matchingItems
: matchingItems.slice(0, limit);
}, [limit, query, recentItems, t.pages.newChat]);
if (recentItems.length === 0) {
return null;
}
return ( return (
<> <>
<SidebarGroup <SidebarGroup
@@ -259,26 +279,42 @@ export function RecentChatList({
}`} }`}
> >
<SidebarMenu> <SidebarMenu>
<div className="relative mb-1.5 px-1">
<Search className="pointer-events-none absolute top-1/2 left-3.5 size-3.5 -translate-y-1/2 text-muted-foreground/60" />
<Input
type="search"
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="搜索历史会话…"
aria-label="搜索历史会话"
className="h-8 rounded-xl border-border bg-card pl-8 pr-2 text-[12px] shadow-none"
/>
</div>
<div className="flex w-full flex-col gap-0.5"> <div className="flex w-full flex-col gap-0.5">
{shownItems.map((item) => { {shownItems.length === 0 ? (
<div className="px-3 py-4 text-center text-[12px] text-muted-foreground/70">
没有匹配的会话
</div>
) : shownItems.map((item) => {
if (item.kind === "strategy-project") { if (item.kind === "strategy-project") {
const { project } = item; const { project } = item;
const href = strategyProjectWorkbenchPath( const href = strategyProjectWorkbenchPath(
"/page/strategy/qa/projects", "/page/strategy/qa/projects",
project.id, project.id,
); );
const isActive = href === pathname;
return ( return (
<SidebarMenuItem <SidebarMenuItem
key={`strategy-project:${project.id}`} key={`strategy-project:${project.id}`}
className="group/side-menu-item" className="group/side-menu-item"
> >
<SidebarMenuButton <SidebarMenuButton
isActive={href === pathname} isActive={isActive}
asChild asChild
className={cn( className={cn(
"h-auto min-h-11 rounded-lg px-3 py-1.5 text-[13px] text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground", "gq-history-item relative h-auto min-h-11 overflow-hidden rounded-xl px-3 py-1.5 text-[13px] text-foreground/80 transition-[background-color,color,box-shadow] duration-150 hover:bg-muted/80 hover:text-foreground hover:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/9%)]",
"data-[active=true]:bg-white data-[active=true]:text-foreground data-[active=true]:shadow-[0_1px_2px_rgba(15,23,42,0.05)]", isActive && "gq-history-item--active",
"dark:data-[active=true]:bg-slate-700/80 dark:data-[active=true]:text-slate-100 dark:data-[active=true]:shadow-none", "data-[active=true]:bg-primary/[0.11] data-[active=true]:font-medium data-[active=true]:text-primary data-[active=true]:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/22%),0_2px_8px_rgb(var(--legacy-primary-rgb)/7%)] data-[active=true]:hover:bg-primary/[0.15]",
compact && compact &&
"min-h-11 gap-2 rounded-md px-2.5 data-[active=true]:border data-[active=true]:border-border", "min-h-11 gap-2 rounded-md px-2.5 data-[active=true]:border data-[active=true]:border-border",
)} )}
@@ -292,7 +328,7 @@ export function RecentChatList({
> >
<MyProjectThreadIcon type="strategy" /> <MyProjectThreadIcon type="strategy" />
<span className="min-w-0 flex-1 flex flex-col items-start gap-0.5"> <span className="min-w-0 flex-1 flex flex-col items-start gap-0.5">
<span className="w-full truncate"> <span className="block w-full truncate">
{desensitize(project.title)} {desensitize(project.title)}
</span> </span>
<MyProjectThreadBadge <MyProjectThreadBadge
@@ -326,9 +362,9 @@ export function RecentChatList({
isActive={isActive} isActive={isActive}
asChild asChild
className={cn( className={cn(
"h-7 rounded-lg px-3 text-[13px] text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground", "gq-history-item relative h-9 overflow-hidden rounded-xl px-3 text-[13px] text-foreground/80 transition-[background-color,color,box-shadow] duration-150 hover:bg-muted/80 hover:text-foreground hover:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/9%)]",
"data-[active=true]:bg-white data-[active=true]:text-foreground data-[active=true]:shadow-[0_1px_2px_rgba(15,23,42,0.05)]", isActive && "gq-history-item--active",
"dark:data-[active=true]:bg-slate-700/80 dark:data-[active=true]:text-slate-100 dark:data-[active=true]:shadow-none", "data-[active=true]:bg-primary/[0.11] data-[active=true]:font-medium data-[active=true]:text-primary data-[active=true]:shadow-[inset_0_0_0_1px_rgb(var(--legacy-primary-rgb)/22%),0_2px_8px_rgb(var(--legacy-primary-rgb)/7%)] data-[active=true]:hover:bg-primary/[0.15]",
compact && compact &&
"h-9 gap-2 rounded-md px-2.5 data-[active=true]:border data-[active=true]:border-border", "h-9 gap-2 rounded-md px-2.5 data-[active=true]:border data-[active=true]:border-border",
projectInfo && "h-auto min-h-11 py-1.5", projectInfo && "h-auto min-h-11 py-1.5",
@@ -351,17 +387,14 @@ export function RecentChatList({
/> />
) : projectInfo ? ( ) : projectInfo ? (
<MyProjectThreadIcon type={projectInfo.type} /> <MyProjectThreadIcon type={projectInfo.type} />
) : ( ) : (
compact && ( <img
<MessageSquare src={historyAvatarForThread(thread.thread_id)}
className={ alt=""
"size-3.5 shrink-0 " + aria-hidden="true"
(isActive draggable={false}
? "text-[var(--primary)]" className="size-5 shrink-0 object-contain"
: "text-muted-foreground/70") />
}
/>
)
)} )}
{pinned && ( {pinned && (
<Pin className="size-3 shrink-0 text-muted-foreground/70" /> <Pin className="size-3 shrink-0 text-muted-foreground/70" />
@@ -372,7 +405,7 @@ export function RecentChatList({
projectInfo && "flex flex-col items-start gap-0.5", projectInfo && "flex flex-col items-start gap-0.5",
)} )}
> >
<span className="w-full truncate"> <span className="block w-full truncate">
{desensitize(titleOfThread(thread, t.pages.newChat))} {desensitize(titleOfThread(thread, t.pages.newChat))}
</span> </span>
{projectInfo && ( {projectInfo && (
@@ -485,7 +518,7 @@ export function RecentChatList({
</SidebarMenuItem> </SidebarMenuItem>
); );
})} })}
{moreHref && ( {moreHref && !query.trim() && (
<SidebarMenuItem> <SidebarMenuItem>
<SidebarMenuButton <SidebarMenuButton
asChild asChild
@@ -9,7 +9,7 @@ import {
Trash2Icon, Trash2Icon,
} from "lucide-react"; } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, 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 {
@@ -92,7 +92,11 @@ export function ShareRoundtableDraftDialog({
} }
async function handleRevoke() { async function handleRevoke() {
if (!share || !window.confirm("撤销后此分享立即失效,确定吗?")) return; if (!share || !(await confirmAction("撤销后此分享立即失效,确定吗?", {
title: "撤销分享?",
confirmText: "撤销分享",
danger: true,
}))) return;
try { try {
await revokeShare.mutateAsync(share.share_code); await revokeShare.mutateAsync(share.share_code);
toast.success("已撤销分享"); toast.success("已撤销分享");
@@ -1,7 +1,7 @@
"use client"; "use client";
import { CopyIcon, LogOutIcon, UserIcon } from "lucide-react"; import { CopyIcon, LogOutIcon, UserIcon } 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";
@@ -2,7 +2,7 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Clock3Icon, DatabaseIcon, GlobeIcon, RefreshCwIcon, SaveIcon, SearchIcon } from "lucide-react"; import { Clock3Icon, DatabaseIcon, GlobeIcon, RefreshCwIcon, SaveIcon, SearchIcon } 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";
@@ -9,7 +9,7 @@ import {
type ChangeEvent, type ChangeEvent,
type RefObject, type RefObject,
} from "react"; } from "react";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import defaultLightRedNavActive from "@/assets/img/nav-active-light-red.svg"; import defaultLightRedNavActive from "@/assets/img/nav-active-light-red.svg";
import defaultLightRedHeaderBackground from "@/assets/img/top-bg-light-red.svg"; import defaultLightRedHeaderBackground from "@/assets/img/top-bg-light-red.svg";
@@ -19,7 +19,7 @@ import {
} from "lucide-react"; } from "lucide-react";
import { useEffect, useMemo, useState, type ComponentType, type SVGProps } from "react"; import { useEffect, useMemo, useState, type ComponentType, type SVGProps } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import { useTheme, type ThemeType } from "@/contexts/ThemeContext"; import { useTheme, type ThemeType } from "@/contexts/ThemeContext";
@@ -42,6 +42,7 @@ import { isIsolatedSession, setIsolatedSession } from "@/core/embed/embed-sessio
import { enUS, isLocale, zhCN, type Locale } from "@/core/i18n"; import { enUS, isLocale, zhCN, type Locale } from "@/core/i18n";
import { useI18n } from "@/core/i18n/hooks"; import { useI18n } from "@/core/i18n/hooks";
import { useLocalSettings } from "@/core/settings"; import { useLocalSettings } from "@/core/settings";
import { resolveAgentGridLayout } from "@/core/settings/agent-grid";
import { import {
AGENT_COMPOSER_WIDTH_MAX, AGENT_COMPOSER_WIDTH_MAX,
AGENT_COMPOSER_WIDTH_MIN, AGENT_COMPOSER_WIDTH_MIN,
@@ -62,8 +63,8 @@ import {
useUpdateUserPreferences, useUpdateUserPreferences,
useUserPreferencesQuery, useUserPreferencesQuery,
} from "@/core/user-preferences"; } from "@/core/user-preferences";
import { import {
useAppearanceSettings, useAppearanceSettings,
useCitationDisplaySettings, useCitationDisplaySettings,
useHtmlMapSettings, useHtmlMapSettings,
useHtmlRuntimeSettings, useHtmlRuntimeSettings,
@@ -500,6 +501,13 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
const globalDefault = appearance?.default_theme ?? "light"; const globalDefault = appearance?.default_theme ?? "light";
const globalSkillView = appearance?.default_skill_view ?? "list"; const globalSkillView = appearance?.default_skill_view ?? "list";
const globalAgentView = appearance?.default_agent_view ?? "card"; const globalAgentView = appearance?.default_agent_view ?? "card";
const agentGrid = resolveAgentGridLayout(settings.display, appearance);
const agentGridSummary = agentGrid.adaptive
? "自适应(普通屏 4 列,3K 以上 5 列)"
: `固定每行 ${agentGrid.columns} 张`;
const adminGridSummary = agentGrid.adminAdaptive
? "自适应(普通屏 4 列,3K 以上 5 列)"
: `固定每行 ${agentGrid.adminColumns} 张`;
const globalLayoutMode = appearance?.default_layout_mode ?? "compact"; const globalLayoutMode = appearance?.default_layout_mode ?? "compact";
const globalDefaultLabel = useMemo(() => { const globalDefaultLabel = useMemo(() => {
const customTheme = (appearance?.custom_themes ?? []).find( const customTheme = (appearance?.custom_themes ?? []).find(
@@ -964,7 +972,7 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
</div> </div>
</SettingsSection> </SettingsSection>
{isAdmin && ( {isAdmin && (
<> <>
<Separator /> <Separator />
<SettingsSection <SettingsSection
@@ -1212,6 +1220,175 @@ export function AppearanceSettingsPage({ onClose }: { onClose?: () => void }) {
</p> </p>
</div> </div>
))} ))}
<div className="flex items-start justify-between gap-4 rounded-lg border p-4">
<div>
<div className="text-sm font-medium">智能体卡片每行数量(个人)</div>
<p className="text-muted-foreground mt-1 max-w-md text-xs leading-relaxed">
{agentGrid.followingAdmin
? `列表当前按管理员设置显示:${adminGridSummary}。只影响本浏览器。`
: `列表当前使用个人设置:${agentGridSummary},没有采用管理员的${adminGridSummary}。打开右侧开关后立即改回管理员设置。`}
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<span className="text-xs text-muted-foreground">跟随管理员</span>
<Switch
checked={agentGrid.followingAdmin}
onCheckedChange={(checked) => {
if (checked) {
setSettings("display", {
agentGridFollowAdmin: undefined,
agentGridAdaptive: undefined,
agentGridColumns: undefined,
});
return;
}
setSettings("display", {
agentGridFollowAdmin: false,
agentGridAdaptive: agentGrid.adminAdaptive,
agentGridColumns: agentGrid.adminAdaptive
? undefined
: agentGrid.adminColumns,
});
}}
aria-label="跟随管理员的智能体卡片列数"
/>
</div>
</div>
{!agentGrid.followingAdmin && (
<div className="flex items-start justify-between gap-4 rounded-lg border p-4">
<div>
<div className="text-sm font-medium">个人自适应</div>
<p className="text-muted-foreground mt-1 max-w-md text-xs leading-relaxed">
开启后按窗口宽度排列(普通屏 4 列、3K 以上 5 列)。关闭后使用下方固定列数。
</p>
</div>
<Switch
checked={agentGrid.adaptive}
onCheckedChange={(checked) =>
setSettings("display", {
agentGridFollowAdmin: false,
agentGridAdaptive: checked,
agentGridColumns: checked ? undefined : agentGrid.columns,
})
}
aria-label="个人自适应列数"
/>
</div>
)}
{!agentGrid.followingAdmin && !agentGrid.adaptive && (
<div className="flex items-start justify-between gap-4 rounded-lg border p-4">
<div>
<div className="text-sm font-medium">每行卡片数(个人固定)</div>
<p className="text-muted-foreground mt-1 max-w-md text-xs leading-relaxed">
卡片视图固定使用该列数(1-8),只影响本浏览器。
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<Button
variant="outline"
size="icon"
className="size-8"
aria-label="减少每行卡片数"
disabled={agentGrid.columns <= 1}
onClick={() =>
setSettings("display", {
agentGridFollowAdmin: false,
agentGridAdaptive: false,
agentGridColumns: Math.max(1, agentGrid.columns - 1),
})
}
>
-
</Button>
<span className="w-8 text-center text-sm font-semibold tabular-nums">
{agentGrid.columns}
</span>
<Button
variant="outline"
size="icon"
className="size-8"
aria-label="增加每行卡片数"
disabled={agentGrid.columns >= 8}
onClick={() =>
setSettings("display", {
agentGridFollowAdmin: false,
agentGridAdaptive: false,
agentGridColumns: Math.min(8, agentGrid.columns + 1),
})
}
>
+
</Button>
</div>
</div>
)}
{isAdmin && (
<div className="flex items-start justify-between gap-4 rounded-lg border border-primary/25 bg-primary/[0.03] p-4">
<div>
<div className="text-sm font-medium">智能体卡片网格默认值(管理员)</div>
<p className="text-muted-foreground mt-1 max-w-md text-xs leading-relaxed">
关闭自适应后,智能体卡片页按这里的固定列数排列。已经关掉「跟随管理员」的浏览器仍用自己的列数。
</p>
</div>
<div className="flex shrink-0 flex-col items-end gap-2">
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">自适应</span>
<Switch
checked={appearance?.default_agent_grid_adaptive ?? true}
disabled={updateAppearance.isPending}
onCheckedChange={(checked) =>
void updateAppearance.mutateAsync({
default_agent_grid_adaptive: checked,
})
}
aria-label="默认自适应列数"
/>
</div>
{!((appearance?.default_agent_grid_adaptive ?? true)) && (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">固定列数</span>
<Button
variant="outline"
size="icon"
className="size-8"
aria-label="减少默认每行卡片数"
disabled={(appearance?.default_agent_grid_columns ?? 4) <= 1 || updateAppearance.isPending}
onClick={() =>
void updateAppearance.mutateAsync({
default_agent_grid_columns: Math.max(
1,
(appearance?.default_agent_grid_columns ?? 4) - 1,
),
})
}
>
-
</Button>
<span className="w-8 text-center text-sm font-semibold tabular-nums">
{appearance?.default_agent_grid_columns ?? 4}
</span>
<Button
variant="outline"
size="icon"
className="size-8"
aria-label="增加默认每行卡片数"
disabled={(appearance?.default_agent_grid_columns ?? 4) >= 8 || updateAppearance.isPending}
onClick={() =>
void updateAppearance.mutateAsync({
default_agent_grid_columns: Math.min(
8,
(appearance?.default_agent_grid_columns ?? 4) + 1,
),
})
}
>
+
</Button>
</div>
)}
</div>
</div>
)}
</div> </div>
</SettingsSection> </SettingsSection>
</> </>
@@ -3,7 +3,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react"; import { 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 { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
@@ -1,7 +1,7 @@
"use client"; "use client";
import { BarChart3Icon, Loader2Icon } from "lucide-react"; import { BarChart3Icon, Loader2Icon } from "lucide-react";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { import {
@@ -10,6 +10,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { getStoredAuth } from "@/core/auth"; import { getStoredAuth } from "@/core/auth";
import { apiFetch } from "@/core/api"; import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config"; import { getBackendBaseURL } from "@/core/config";
import { confirmAction } from "@/core/ui/feedback";
import { import {
ACTIVE_ARCHIVE_JOB_STATUSES as ACTIVE, ACTIVE_ARCHIVE_JOB_STATUSES as ACTIVE,
archiveMonthDisplayStatus, archiveMonthDisplayStatus,
@@ -144,7 +145,11 @@ export function ChatArchiveSettingsPage() {
const confirmation = action === "purge" const confirmation = action === "purge"
? "确认清理该月已归档的 PostgreSQL 数据?系统会逐会话重新校验 SQLite 备份,只清理校验通过的会话;失败、未归档和正在运行的会话不会清理。" ? "确认清理该月已归档的 PostgreSQL 数据?系统会逐会话重新校验 SQLite 备份,只清理校验通过的会话;失败、未归档和正在运行的会话不会清理。"
: "确认回滚到 PostgreSQL?月度 SQLite 文件中的归档记录会保留。"; : "确认回滚到 PostgreSQL?月度 SQLite 文件中的归档记录会保留。";
if (action !== "archive" && !window.confirm(confirmation)) return; if (action !== "archive" && !(await confirmAction(confirmation, {
title: action === "purge" ? "清理 PostgreSQL 归档数据?" : "回滚归档数据?",
confirmText: action === "purge" ? "确认清理" : "确认回滚",
danger: action === "purge",
}))) return;
setBusyMonth(month.month); setBusyMonth(month.month);
setError(null); setError(null);
try { try {
@@ -2,7 +2,7 @@
import { ListOrderedIcon, Loader2Icon, ShrinkIcon } from "lucide-react"; import { ListOrderedIcon, Loader2Icon, ShrinkIcon } from "lucide-react";
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";
@@ -15,7 +15,7 @@ import {
} from "lucide-react"; } from "lucide-react";
import { useEffect, useId, useMemo, useState, type CSSProperties } from "react"; import { useEffect, useId, useMemo, useState, type CSSProperties } from "react";
import { ColorPickerPanel } from "tdesign-react"; import { ColorPickerPanel } from "tdesign-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";
@@ -2,7 +2,7 @@
import { AlertCircleIcon, Loader2Icon } from "lucide-react"; import { AlertCircleIcon, Loader2Icon } 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 {
@@ -1,7 +1,7 @@
"use client"; "use client";
import { Loader2Icon, SearchIcon } from "lucide-react"; import { Loader2Icon, SearchIcon } from "lucide-react";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
@@ -0,0 +1,150 @@
"use client";
import { DatabaseIcon, Loader2Icon, SaveIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { toast } from "@/core/ui/feedback";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import {
type LocalWikiAutoSyncSettings,
useLocalWikiAutoSyncSettings,
useLocalWikiAutoSyncSettingsActions,
} from "@/strategy-components/api/llmwiki";
import { SettingsSection } from "./settings-section";
const HOURS = Array.from({ length: 24 }, (_, hour) => hour);
function hourLabel(hour: number) {
return `${String(hour).padStart(2, "0")}:00`;
}
export function LocalWikiAutoSyncSettingsPage() {
const settings = useLocalWikiAutoSyncSettings();
const actions = useLocalWikiAutoSyncSettingsActions();
const [draft, setDraft] = useState<LocalWikiAutoSyncSettings | null>(null);
useEffect(() => {
if (settings.data) setDraft(settings.data);
}, [settings.data]);
const isDirty = useMemo(
() => !!draft && JSON.stringify(draft) !== JSON.stringify(settings.data),
[draft, settings.data],
);
const updateDraft = (patch: Partial<LocalWikiAutoSyncSettings>) => {
setDraft((current) => current ? { ...current, ...patch } : current);
};
const save = async () => {
if (!draft) return;
try {
await actions.save.mutateAsync(draft);
toast.success(draft.enabled ? "知识库自动同步设置已保存" : "知识库自动同步已关闭");
} catch (error) {
toast.error(error instanceof Error ? error.message : "保存失败,请稍后重试");
}
};
if (settings.isLoading || !draft) {
return (
<div className="flex min-h-36 items-center justify-center text-sm text-muted-foreground">
<Loader2Icon className="mr-2 size-4 animate-spin" />正在读取自动同步设置…
</div>
);
}
return (
<SettingsSection
title="本地 Wiki 自动同步"
description="设置 DeerFlow 本地 Wiki 镜像的后台同步时间。执行时间以服务器本地时间为准。"
>
<div className="space-y-4 rounded-lg border p-4">
<div className="flex items-start justify-between gap-6">
<div className="space-y-1">
<label className="flex items-center gap-2 font-medium" htmlFor="local-wiki-auto-sync-enabled">
<DatabaseIcon className="size-4" />自动同步
</label>
<p id="local-wiki-auto-sync-description" className="text-sm text-muted-foreground">
关闭后不再后台扫描所有知识库;单个知识库的手动同步和向量化不受影响。
</p>
</div>
<Switch
id="local-wiki-auto-sync-enabled"
aria-describedby="local-wiki-auto-sync-description"
checked={draft.enabled}
disabled={settings.isError || actions.save.isPending}
onCheckedChange={(enabled) => updateDraft({ enabled })}
/>
</div>
{draft.enabled && (
<div className="grid gap-4 border-t pt-4 sm:grid-cols-2">
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="local-wiki-auto-sync-schedule">
同步周期
</label>
<Select
value={draft.schedule}
disabled={actions.save.isPending}
onValueChange={(schedule: "hourly" | "daily") => updateDraft({ schedule })}
>
<SelectTrigger id="local-wiki-auto-sync-schedule">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="hourly">每小时整点</SelectItem>
<SelectItem value="daily">每天固定时间</SelectItem>
</SelectContent>
</Select>
</div>
{draft.schedule === "daily" && (
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="local-wiki-auto-sync-hour">
每日执行时间
</label>
<Select
value={String(draft.hour)}
disabled={actions.save.isPending}
onValueChange={(value) => updateDraft({ hour: Number(value) })}
>
<SelectTrigger id="local-wiki-auto-sync-hour">
<SelectValue />
</SelectTrigger>
<SelectContent>
{HOURS.map((hour) => (
<SelectItem key={hour} value={String(hour)}>{hourLabel(hour)}</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
</div>
)}
{settings.isError && (
<p className="text-destructive text-sm" role="alert">
无法读取自动同步设置,请刷新后重试。
</p>
)}
<div className="flex justify-end border-t pt-4">
<Button type="button" onClick={() => void save()} disabled={!isDirty || settings.isError || actions.save.isPending}>
{actions.save.isPending ? <Loader2Icon className="mr-2 size-4 animate-spin" /> : <SaveIcon className="mr-2 size-4" />}
保存设置
</Button>
</div>
</div>
</SettingsSection>
);
}
@@ -1,7 +1,7 @@
"use client"; "use client";
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 {
@@ -1,7 +1,7 @@
"use client"; "use client";
import { BrainIcon, Loader2Icon } from "lucide-react"; import { BrainIcon, Loader2Icon } from "lucide-react";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { import {
@@ -2,7 +2,7 @@
import { PenLineIcon, PlusIcon, SearchIcon, Trash2Icon, Heart, BookOpen, Map, Zap, Target, ShieldAlert, Briefcase, UserRound, Sparkles, Clock, History, Archive } from "lucide-react"; import { PenLineIcon, PlusIcon, SearchIcon, Trash2Icon, Heart, BookOpen, Map, Zap, Target, ShieldAlert, Briefcase, UserRound, Sparkles, Clock, History, Archive } 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 {
@@ -2,7 +2,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react"; import { 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 { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
@@ -2,7 +2,7 @@
import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState, type FormEvent } from "react"; import { useState, type FormEvent } 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";
@@ -1,7 +1,7 @@
"use client"; "use client";
import { HistoryIcon, Loader2Icon } from "lucide-react"; import { HistoryIcon, Loader2Icon } from "lucide-react";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { import {
@@ -2,7 +2,7 @@
import { Clock3Icon, FileOutputIcon, ListOrderedIcon, Loader2Icon, UsersIcon } from "lucide-react"; import { Clock3Icon, FileOutputIcon, ListOrderedIcon, Loader2Icon, UsersIcon } from "lucide-react";
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 { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
@@ -42,6 +42,7 @@ import { RoundtableRoomSettingsPage } from "@/components/workspace/settings/roun
import { RetryKeepPartialSettingsPage } from "@/components/workspace/settings/retry-keep-partial-settings-page"; import { RetryKeepPartialSettingsPage } from "@/components/workspace/settings/retry-keep-partial-settings-page";
import { KnowledgeRetrievalSettingsPage } from "@/components/workspace/settings/knowledge-retrieval-settings-page"; import { KnowledgeRetrievalSettingsPage } from "@/components/workspace/settings/knowledge-retrieval-settings-page";
import { KnowledgeBatchCreateSettingsPage } from "@/components/workspace/settings/knowledge-batch-create-settings-page"; import { KnowledgeBatchCreateSettingsPage } from "@/components/workspace/settings/knowledge-batch-create-settings-page";
import { LocalWikiAutoSyncSettingsPage } from "@/components/workspace/settings/local-wiki-auto-sync-settings-page";
import { MemoryRuntimeSettingsPage } from "@/components/workspace/settings/memory-runtime-settings-page"; import { MemoryRuntimeSettingsPage } from "@/components/workspace/settings/memory-runtime-settings-page";
import { ToolSettingsPage } from "@/components/workspace/settings/tool-settings-page"; import { ToolSettingsPage } from "@/components/workspace/settings/tool-settings-page";
import { UploadSettingsPage } from "@/components/workspace/settings/upload-settings-page"; import { UploadSettingsPage } from "@/components/workspace/settings/upload-settings-page";
@@ -64,6 +65,7 @@ type SettingsSection =
| "roundtable-rooms" | "roundtable-rooms"
| "knowledge-retrieval" | "knowledge-retrieval"
| "knowledge-batch-create" | "knowledge-batch-create"
| "local-wiki-auto-sync"
| "appIdentity" | "appIdentity"
| "memory" | "memory"
| "fileWriting" | "fileWriting"
@@ -117,6 +119,7 @@ export function SettingsDialog(props: SettingsDialogProps) {
{ id: "chat-archive", label: "聊天记录归档", icon: ArchiveIcon }, { id: "chat-archive", label: "聊天记录归档", icon: ArchiveIcon },
{ id: "roundtable-rooms", label: "会商并发", icon: UsersIcon }, { id: "roundtable-rooms", label: "会商并发", icon: UsersIcon },
{ id: "knowledge-retrieval", label: "知识检索", icon: SearchIcon }, { id: "knowledge-retrieval", label: "知识检索", icon: SearchIcon },
{ id: "local-wiki-auto-sync", label: "知识库同步", icon: DatabaseIcon },
{ id: "appIdentity", label: "系统名称", icon: TypeIcon }, { id: "appIdentity", label: "系统名称", icon: TypeIcon },
{ id: "memory", label: "问答记忆", icon: BrainIcon }, { id: "memory", label: "问答记忆", icon: BrainIcon },
{ id: "fileWriting", label: "文件流式兼容", icon: FileOutputIcon }, { id: "fileWriting", label: "文件流式兼容", icon: FileOutputIcon },
@@ -217,6 +220,9 @@ export function SettingsDialog(props: SettingsDialogProps) {
{activeSection === "knowledge-retrieval" && isAdmin && ( {activeSection === "knowledge-retrieval" && isAdmin && (
<KnowledgeRetrievalSettingsPage /> <KnowledgeRetrievalSettingsPage />
)} )}
{activeSection === "local-wiki-auto-sync" && isAdmin && (
<LocalWikiAutoSyncSettingsPage />
)}
{activeSection === "knowledge-batch-create" && ( {activeSection === "knowledge-batch-create" && (
<KnowledgeBatchCreateSettingsPage /> <KnowledgeBatchCreateSettingsPage />
)} )}
@@ -5,6 +5,10 @@ import {
Anchor, Anchor,
ArchiveIcon, ArchiveIcon,
ArrowDownUpIcon, ArrowDownUpIcon,
BarChart3Icon,
DatabaseIcon,
MessageSquareTextIcon,
MousePointerClickIcon,
BookmarkIcon, BookmarkIcon,
CheckCircle2, CheckCircle2,
ChevronLeftIcon, ChevronLeftIcon,
@@ -19,8 +23,8 @@ import {
LockIcon, LockIcon,
PinIcon, PinIcon,
PlusIcon, PlusIcon,
Power, Power,
PowerOff, PowerOff,
RefreshCwIcon, RefreshCwIcon,
SparklesIcon, SparklesIcon,
TagsIcon, TagsIcon,
@@ -28,13 +32,16 @@ import {
TrendingUpIcon, TrendingUpIcon,
Upload, Upload,
UserIcon, UserIcon,
WorkflowIcon,
XIcon, XIcon,
} from "lucide-react"; } from "lucide-react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import { import {
DateRangePicker, DateRangePicker,
Dialog as TDesignDialog,
MessagePlugin,
type DateRangePickerProps, type DateRangePickerProps,
type DateRangeValue, type DateRangeValue,
} from "tdesign-react"; } from "tdesign-react";
@@ -84,7 +91,7 @@ import {
useDeleteBuiltinSkill, useDeleteBuiltinSkill,
useDeleteCustomSkill, useDeleteCustomSkill,
useDuplicateSkill, useDuplicateSkill,
useEnableSkill, useEnableSkill,
useGenerateMissingSkillNameZh, useGenerateMissingSkillNameZh,
useGenerateSkillNameZh, useGenerateSkillNameZh,
useInstallSkillUpload, useInstallSkillUpload,
@@ -97,11 +104,11 @@ import {
useSkills, useSkills,
useValidateSkillUpload, useValidateSkillUpload,
} from "@/core/skills/hooks"; } from "@/core/skills/hooks";
import { import {
canToggleSkillAvailability, canToggleSkillAvailability,
isSkillOffline, isSkillOffline,
type SkillAvailabilityControl, type SkillAvailabilityControl,
} from "@/core/skill-availability"; } from "@/core/skill-availability";
import { import {
usePublishSquares, usePublishSquares,
useSkillCompressionSettings, useSkillCompressionSettings,
@@ -465,11 +472,11 @@ function SkillSettingsList({
} }
}; };
return ( return (
<div className="flex w-full flex-col gap-4"> <div className="lb-surface flex w-full flex-col gap-4">
<header className="flex flex-wrap items-center justify-between gap-3"> <header className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-3">
<Tabs value={filter} onValueChange={setFilter}> <Tabs value={filter} onValueChange={setFilter}>
<TabsList variant="line" className="flex-wrap"> <TabsList className="flex-wrap">
{restrictWxTypes ? ( {restrictWxTypes ? (
<> <>
<TabsTrigger value="mine">{t.settings.skills.tabMine}</TabsTrigger> <TabsTrigger value="mine">{t.settings.skills.tabMine}</TabsTrigger>
@@ -488,95 +495,110 @@ function SkillSettingsList({
)} )}
</TabsList> </TabsList>
</Tabs> </Tabs>
<Button {!isLoading && !error && (
size="sm" <span className="text-muted-foreground text-sm tabular-nums">
variant="outline" 共 {orderedSkills.length} 个技能
disabled={staleCount === 0} </span>
onClick={() => setStaleSheetOpen(true)} )}
title={t.settings.skills.badgeStaleTitle}
>
<ClockIcon className="size-4" />
{t.settings.skills.entryStale.replace("{count}", String(staleCount))}
</Button>
<Button
size="sm"
variant="outline"
disabled={archivedCount === 0}
onClick={() => setArchiveSheetOpen(true)}
title={t.settings.skills.badgeArchivedTitle}
>
<ArchiveIcon className="size-4" />
{t.settings.skills.entryArchived.replace(
"{count}",
String(archivedCount),
)}
</Button>
</div> </div>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap items-center justify-end gap-2">
<Button <div
size="sm" role="group"
variant="outline" aria-label="技能状态"
onClick={() => { className="flex items-center rounded-[6px] border border-border/80 bg-muted/35 p-0.5 shadow-xs"
onClose?.();
router.push("/page/workspace/skills/evolution");
}}
> >
<TrendingUpIcon className="size-4" /> <Button
{t.settings.skills.goToEvolution} size="sm"
</Button> variant="ghost"
<Button className="h-8 gap-1.5 rounded-[4px] px-2.5 text-muted-foreground hover:bg-background hover:text-foreground"
size="sm" disabled={staleCount === 0}
variant="outline" onClick={() => setStaleSheetOpen(true)}
onClick={() => void handleRescan()} title={t.settings.skills.badgeStaleTitle}
disabled={ >
reconcileMutation.isPending || <ClockIcon className="size-3.5" />
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" {t.settings.skills.entryStale.replace("{count}", String(staleCount))}
} </Button>
title={t.settings.skills.rescanSkills} <div aria-hidden="true" className="h-4 w-px bg-border/70" />
<Button
size="sm"
variant="ghost"
className="h-8 gap-1.5 rounded-[4px] px-2.5 text-muted-foreground hover:bg-background hover:text-foreground"
disabled={archivedCount === 0}
onClick={() => setArchiveSheetOpen(true)}
title={t.settings.skills.badgeArchivedTitle}
>
<ArchiveIcon className="size-3.5" />
{t.settings.skills.entryArchived.replace(
"{count}",
String(archivedCount),
)}
</Button>
</div>
<div
role="group"
aria-label="技能维护操作"
className="flex items-center rounded-[6px] border border-border/80 bg-background p-0.5 shadow-xs"
> >
{reconcileMutation.isPending ? ( <Button
<Loader2 className="size-4 animate-spin" /> size="sm"
) : ( variant="ghost"
<RefreshCwIcon className="size-4" /> className="h-8 gap-1.5 rounded-[4px] px-2.5 text-muted-foreground hover:bg-muted hover:text-foreground"
)} onClick={() => {
{reconcileMutation.isPending onClose?.();
? t.settings.skills.rescanSkillsRunning router.push("/page/workspace/skills/evolution");
: t.settings.skills.rescanSkills} }}
</Button> >
<TrendingUpIcon className="size-3.5" />
{t.settings.skills.goToEvolution}
</Button>
<div aria-hidden="true" className="h-4 w-px bg-border/70" />
<Button
size="sm"
variant="ghost"
className="h-8 gap-1.5 rounded-[4px] px-2.5 text-muted-foreground hover:bg-muted hover:text-foreground"
onClick={() => void handleRescan()}
disabled={
reconcileMutation.isPending ||
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"
}
title={t.settings.skills.rescanSkills}
>
{reconcileMutation.isPending ? (
<Loader2 className="size-3.5 animate-spin" />
) : (
<RefreshCwIcon className="size-3.5" />
)}
{reconcileMutation.isPending
? t.settings.skills.rescanSkillsRunning
: t.settings.skills.rescanSkills}
</Button>
</div>
{isAdmin && ( {isAdmin && (
<> <Button
<ModelNameSelect size="sm"
value={fillModel} variant="ghost"
onChange={setFillModel} className="h-9 gap-2 rounded-[6px] border border-violet-200/90 bg-violet-50 px-3 font-medium text-violet-700 shadow-xs hover:bg-violet-100 hover:text-violet-800 dark:border-violet-500/40 dark:bg-violet-500/15 dark:text-violet-300 dark:hover:bg-violet-500/25"
disabled={ onClick={() => void handleFillNames()}
fillNamesMutation.isPending || disabled={
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" fillNamesMutation.isPending ||
} env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"
triggerClassName="h-8 w-[9.5rem]" }
/> title="用所选大模型为所有尚未配置中文名称的技能自动生成中文名(仅管理员)"
<Button >
size="sm" {fillNamesMutation.isPending ? (
variant="outline" <Loader2 className="size-4 animate-spin" />
className="gap-1.5 border-violet-300 bg-violet-50 font-medium text-violet-700 hover:bg-violet-100 hover:text-violet-800 dark:border-violet-500/40 dark:bg-violet-500/15 dark:text-violet-300 dark:hover:bg-violet-500/25" ) : (
onClick={() => void handleFillNames()} <SparklesIcon className="size-4" />
disabled={ )}
fillNamesMutation.isPending || {fillNamesMutation.isPending ? "补充中…" : "一键补充中文名"}
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" </Button>
}
title="用所选大模型为所有尚未配置中文名称的技能自动生成中文名(仅管理员)"
>
{fillNamesMutation.isPending ? (
<Loader2 className="size-4 animate-spin" />
) : (
<SparklesIcon className="size-4" />
)}
{fillNamesMutation.isPending ? "补充中…" : "一键补充中文名"}
</Button>
</>
)} )}
<Button <Button
size="sm" size="sm"
variant="outline" variant="outline"
className="h-9 gap-2 rounded-[6px] border-border/80 bg-background px-3 shadow-xs hover:border-primary/30"
onClick={() => setInstallOpen(true)} onClick={() => setInstallOpen(true)}
disabled={env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"} disabled={env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"}
> >
@@ -585,6 +607,7 @@ function SkillSettingsList({
</Button> </Button>
<Button <Button
size="sm" size="sm"
className="h-9 gap-2 rounded-[6px] px-4 shadow-sm hover:shadow-md"
onClick={() => { onClick={() => {
onClose?.(); onClose?.();
router.push("/page/workspace/chats/new?mode=skill"); router.push("/page/workspace/chats/new?mode=skill");
@@ -606,7 +629,7 @@ function SkillSettingsList({
actions={ actions={
<div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto"> <div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
<DateRangePicker <DateRangePicker
className="w-full sm:w-[300px]" className="lb-h9 w-full sm:w-[300px]"
value={createdAtRange} value={createdAtRange}
valueType="YYYY-MM-DD" valueType="YYYY-MM-DD"
format="YYYY-MM-DD" format="YYYY-MM-DD"
@@ -618,10 +641,20 @@ function SkillSettingsList({
popupProps={{ overlayClassName: "skill-created-at-range-popup" }} popupProps={{ overlayClassName: "skill-created-at-range-popup" }}
onChange={setCreatedAtRange} onChange={setCreatedAtRange}
/> />
<ViewModeToggle value={viewMode} onChange={setViewMode} /> {isAdmin && (
<ModelNameSelect
value={fillModel}
onChange={setFillModel}
disabled={
fillNamesMutation.isPending ||
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"
}
triggerClassName="lb-h9 w-[9.5rem] rounded-[5px]"
/>
)}
<Select value={sort} onValueChange={(v) => setSort(v as SkillSort)}> <Select value={sort} onValueChange={(v) => setSort(v as SkillSort)}>
<SelectTrigger <SelectTrigger
className="h-9 w-full gap-2 px-3 text-xs sm:w-[148px]" className="h-9 w-full gap-2 rounded-[5px] px-3 text-xs sm:w-[148px]"
title="排序" title="排序"
> >
<ArrowDownUpIcon className="text-muted-foreground size-3.5" /> <ArrowDownUpIcon className="text-muted-foreground size-3.5" />
@@ -638,14 +671,10 @@ function SkillSettingsList({
<SelectItem value="name_desc">名称 Z-A</SelectItem> <SelectItem value="name_desc">名称 Z-A</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<ViewModeToggle value={viewMode} onChange={setViewMode} className="rounded-[5px]" />
</div> </div>
} }
/> />
{!isLoading && !error && (
<div className="text-muted-foreground flex justify-end text-sm tabular-nums">
共 {orderedSkills.length} 个技能
</div>
)}
{publisher && ( {publisher && (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="text-muted-foreground text-xs">筛选发布者:</span> <span className="text-muted-foreground text-xs">筛选发布者:</span>
@@ -671,18 +700,18 @@ function SkillSettingsList({
<div <div
className={cn( className={cn(
viewMode === "card" viewMode === "card"
? "grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3" ? "grid grid-cols-1 gap-5 sm:grid-cols-2 xl:grid-cols-3"
: "flex flex-col gap-3", : "flex flex-col gap-5",
)} )}
> >
{pagedSkills.map((skill) => ( {pagedSkills.map((skill) => (
<SkillRow <SkillRow
key={skill.name} key={skill.name}
skill={skill} skill={skill}
currentUserId={currentUserId} currentUserId={currentUserId}
isAdmin={isAdmin} isAdmin={isAdmin}
availabilityControl="owner" availabilityControl="owner"
layout={viewMode === "card" ? "card" : "row"} layout={viewMode === "card" ? "card" : "row"}
onPublisherClick={setPublisher} onPublisherClick={setPublisher}
/> />
))} ))}
@@ -737,19 +766,19 @@ function SkillSettingsList({
} }
export function SkillRow({ export function SkillRow({
skill, skill,
currentUserId, currentUserId,
isAdmin, isAdmin,
availabilityControl, availabilityControl,
layout = "row", layout = "row",
onPublisherClick, onPublisherClick,
knowledgeBindings = [], knowledgeBindings = [],
}: { }: {
skill: Skill; skill: Skill;
currentUserId: string | null; currentUserId: string | null;
isAdmin: boolean; isAdmin: boolean;
/** Which permission boundary exposes the global online/offline control. */ /** Which permission boundary exposes the global online/offline control. */
availabilityControl?: SkillAvailabilityControl; availabilityControl?: SkillAvailabilityControl;
/** "row" = full-width horizontal item (default); "card" = grid card cell. */ /** "row" = full-width horizontal item (default); "card" = grid card cell. */
layout?: "row" | "card"; layout?: "row" | "card";
/** Click the 发布者 line to filter the list to that publisher. Receives the /** Click the 发布者 line to filter the list to that publisher. Receives the
@@ -764,11 +793,11 @@ export function SkillRow({
const { data: cardPublishSquares } = usePublishSquares(); const { data: cardPublishSquares } = usePublishSquares();
const setPinned = useSetSkillPinned(); const setPinned = useSetSkillPinned();
const setFeatured = useSetSkillFeatured(); const setFeatured = useSetSkillFeatured();
const setAlwaysOn = useSetSkillAlwaysOn(); const setAlwaysOn = useSetSkillAlwaysOn();
const setEnabled = useEnableSkill(); const setEnabled = useEnableSkill();
const { data: compression } = useSkillCompressionSettings(); const { data: compression } = useSkillCompressionSettings();
const deleteCustom = useDeleteCustomSkill(); const deleteCustom = useDeleteCustomSkill();
const deleteBuiltin = useDeleteBuiltinSkill(); const deleteBuiltin = useDeleteBuiltinSkill();
const duplicateSkillMutation = useDuplicateSkill(); const duplicateSkillMutation = useDuplicateSkill();
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false); const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [tagPickerOpen, setTagPickerOpen] = useState(false); const [tagPickerOpen, setTagPickerOpen] = useState(false);
@@ -776,7 +805,7 @@ export function SkillRow({
const [duplicateOpen, setDuplicateOpen] = useState(false); const [duplicateOpen, setDuplicateOpen] = useState(false);
const [duplicateName, setDuplicateName] = useState(""); const [duplicateName, setDuplicateName] = useState("");
const [publishPickerOpen, setPublishPickerOpen] = useState(false); const [publishPickerOpen, setPublishPickerOpen] = useState(false);
const [confirmOfflineOpen, setConfirmOfflineOpen] = useState(false); const [confirmOfflineOpen, setConfirmOfflineOpen] = useState(false);
const isCustom = skill.category === "custom"; const isCustom = skill.category === "custom";
// Built-in flag falls back to "no DB owner" so legacy responses without // Built-in flag falls back to "no DB owner" so legacy responses without
@@ -791,27 +820,27 @@ export function SkillRow({
const canTogglePublish = canManage && !isBuiltin; const canTogglePublish = canManage && !isBuiltin;
// 常驻(免压缩):内置技能仅管理员可设;自定义技能其所有者或管理员可设(与后端一致)。 // 常驻(免压缩):内置技能仅管理员可设;自定义技能其所有者或管理员可设(与后端一致)。
const canSetAlwaysOn = isAdmin || isOwned; const canSetAlwaysOn = isAdmin || isOwned;
const canToggleAvailability = canToggleSkillAvailability({ const canToggleAvailability = canToggleSkillAvailability({
skill, skill,
currentUserId, currentUserId,
isAdmin, isAdmin,
control: availabilityControl, control: availabilityControl,
}); });
const isOffline = isSkillOffline(skill); const isOffline = isSkillOffline(skill);
async function handleSetEnabled(enabled: boolean) { async function handleSetEnabled(enabled: boolean) {
try { try {
await setEnabled.mutateAsync({ skillName: skill.name, enabled }); await setEnabled.mutateAsync({ skillName: skill.name, enabled });
toast.success( void MessagePlugin.success(
enabled enabled
? t.settings.skills.onlineSuccess ? t.settings.skills.onlineSuccess
: t.settings.skills.offlineSuccess, : t.settings.skills.offlineSuccess,
); );
setConfirmOfflineOpen(false); setConfirmOfflineOpen(false);
} catch (err) { } catch (err) {
toast.error(err instanceof Error ? err.message : String(err)); void MessagePlugin.error(err instanceof Error ? err.message : String(err));
} }
} }
async function handleToggleAlwaysOn(next: boolean) { async function handleToggleAlwaysOn(next: boolean) {
try { try {
@@ -926,7 +955,12 @@ export function SkillRow({
const badgeGroup = ( const badgeGroup = (
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<span className={cn(isCard && "truncate font-medium")}> <span
className={cn(
"min-w-0 text-[15px] font-semibold tracking-[-0.01em] text-card-foreground",
isCard && "truncate",
)}
>
{skill.name_zh?.trim() ? skill.name_zh : desensitize(skill.name)} {skill.name_zh?.trim() ? skill.name_zh : desensitize(skill.name)}
</span> </span>
{skill.name_zh?.trim() && ( {skill.name_zh?.trim() && (
@@ -1028,80 +1062,83 @@ export function SkillRow({
常驻 常驻
</Badge> </Badge>
)} )}
{knowledgeBindings.slice(0, 3).map((binding) => ( {knowledgeBindings.slice(0, 3).map((binding) => (
<Badge <Badge
key={binding.id} key={binding.id}
variant="outline" variant="outline"
className="border-indigo-500/30 text-indigo-700 dark:text-indigo-300 text-xs" className="border-indigo-500/30 text-indigo-700 dark:text-indigo-300 text-xs"
title={`${binding.target_name} · ${binding.status}${binding.remote_business_key ? ` · ${binding.remote_business_key}` : ""}`} title={`${binding.target_name} · ${binding.status}${binding.remote_business_key ? ` · ${binding.remote_business_key}` : ""}`}
> >
知识库:{binding.target_name || binding.target_id} 知识库:{binding.target_name || binding.target_id}
{binding.status === "stale" ? "(待更新)" : ""} {binding.status === "stale" ? "(待更新)" : ""}
</Badge> </Badge>
))} ))}
{knowledgeBindings.length > 3 && ( {knowledgeBindings.length > 3 && (
<Badge variant="secondary" className="text-xs">+{knowledgeBindings.length - 3}</Badge> <Badge variant="secondary" className="text-xs">+{knowledgeBindings.length - 3}</Badge>
)} )}
{isOffline && ( {isOffline && (
<Badge <Badge
variant="outline" variant="outline"
className="border-red-500/35 bg-red-500/5 text-red-700 dark:text-red-300 text-xs" className="border-red-500/35 bg-red-500/5 text-red-700 dark:text-red-300 text-xs"
title={t.settings.skills.badgeOfflineTitle} title={t.settings.skills.badgeOfflineTitle}
> >
<PowerOff className="size-3" /> <PowerOff className="size-3" />
{t.settings.skills.badgeOffline} {t.settings.skills.badgeOffline}
</Badge> </Badge>
)} )}
</div> </div>
); );
const metaNodes = ( const metaNodes = (
<> <>
{!isBuiltin && skill.owner_username && ( <div className="mt-1.5 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
<button {!isBuiltin && skill.owner_username && (
type="button" <button
disabled={!skill.owner_user_id || !onPublisherClick} type="button"
onClick={(e) => { disabled={!skill.owner_user_id || !onPublisherClick}
if (!skill.owner_user_id || !onPublisherClick) return; onClick={(e) => {
e.stopPropagation(); if (!skill.owner_user_id || !onPublisherClick) return;
onPublisherClick({ e.stopPropagation();
id: skill.owner_user_id, onPublisherClick({
label: desensitize(skill.owner_username!), id: skill.owner_user_id,
}); label: desensitize(skill.owner_username!),
}} });
className={cn( }}
"text-muted-foreground mt-1 flex max-w-full items-center gap-1 text-sm font-medium", className={cn(
skill.owner_user_id && onPublisherClick && "flex max-w-full items-center gap-1 text-xs font-medium",
"hover:text-primary cursor-pointer transition-colors hover:underline", skill.owner_user_id && onPublisherClick &&
)} "hover:text-primary cursor-pointer transition-colors hover:underline",
title={ )}
skill.owner_user_id && onPublisherClick title={
? `点击筛选发布者:${desensitize(skill.owner_username)}` skill.owner_user_id && onPublisherClick
: `发布者:${desensitize(skill.owner_username)}` ? `点击筛选发布者:${desensitize(skill.owner_username)}`
} : `发布者:${desensitize(skill.owner_username)}`
> }
<UserIcon className="size-3.5 shrink-0" /> >
<span className="truncate">发布者:{desensitize(skill.owner_username)}</span> <UserIcon className="size-3.5 shrink-0" />
</button> <span className="truncate">发布者:{desensitize(skill.owner_username)}</span>
)} </button>
{skill.use_count !== undefined && ( )}
<div className="text-muted-foreground mt-1 text-xs"> {skill.use_count !== undefined && (
{skill.use_count > 0 <div className="flex items-center gap-1">
? t.settings.skills.useCountInline.replace( <MousePointerClickIcon className="size-3.5 shrink-0" />
"{count}", <span>
String(skill.use_count), {skill.use_count > 0
) ? t.settings.skills.useCountInline.replace(
: t.settings.skills.useCountInlineZero} "{count}",
</div> String(skill.use_count),
)} )
{formatDateTime(skill.created_at) && ( : t.settings.skills.useCountInlineZero}
<div className="text-muted-foreground mt-1 flex items-center gap-1 text-xs"> </span>
<ClockIcon className="size-3.5 shrink-0" /> </div>
<span className="truncate"> )}
创建时间:{formatDateTime(skill.created_at)} {formatDateTime(skill.created_at) && (
</span> <div className="flex items-center gap-1">
</div> <ClockIcon className="size-3.5 shrink-0" />
)} <span>创建时间:{formatDateTime(skill.created_at)}</span>
</div>
)}
</div>
{(skill.tags?.length ?? 0) > 0 && ( {(skill.tags?.length ?? 0) > 0 && (
<TagChipList tags={skill.tags!} className="mt-2" /> <TagChipList tags={skill.tags!} className="mt-2" />
)} )}
@@ -1110,47 +1147,51 @@ export function SkillRow({
const actionButtons = ( const actionButtons = (
<> <>
{canToggleAvailability && ( {canToggleAvailability && (
<Button <Button
size="sm" size="icon"
variant={isOffline ? "default" : "outline"} variant="ghost"
className={cn( className={cn(
"h-8 shrink-0 gap-1.5 px-2.5", "h-8 w-8 shrink-0 rounded-[5px]",
!isOffline && "text-destructive hover:text-destructive", isOffline
)} ? "text-emerald-600 hover:bg-emerald-500/10 hover:text-emerald-600"
disabled={ : "text-muted-foreground hover:bg-destructive/10 hover:text-destructive",
setEnabled.isPending || )}
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" disabled={
} setEnabled.isPending ||
onClick={() => { env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"
if (isOffline) { }
void handleSetEnabled(true); onClick={() => {
} else { if (isOffline) {
setConfirmOfflineOpen(true); void handleSetEnabled(true);
} } else {
}} setConfirmOfflineOpen(true);
title={ }
isOffline }}
title={
isOffline
? t.settings.skills.onlineAction ? t.settings.skills.onlineAction
: t.settings.skills.offlineAction : t.settings.skills.offlineAction
} }
> aria-label={
{setEnabled.isPending ? ( isOffline
<Loader2 className="size-3.5 animate-spin" /> ? t.settings.skills.onlineAction
) : isOffline ? ( : t.settings.skills.offlineAction
<Power className="size-3.5" /> }
) : ( >
<PowerOff className="size-3.5" /> {setEnabled.isPending ? (
)} <Loader2 className="size-3.5 animate-spin" />
{isOffline ) : isOffline ? (
? t.settings.skills.onlineAction <Power className="size-3.5" />
: t.settings.skills.offlineAction} ) : (
</Button> <PowerOff className="size-3.5" />
)} )}
</Button>
)}
<Button <Button
size="icon" size="icon"
variant="ghost" variant="ghost"
className="h-8 w-8 shrink-0" className="h-8 w-8 shrink-0 rounded-[5px] text-muted-foreground hover:bg-muted hover:text-foreground"
onClick={() => setTagPickerOpen(true)} onClick={() => setTagPickerOpen(true)}
title={t.adminTags.manageTags} title={t.adminTags.manageTags}
> >
@@ -1161,7 +1202,7 @@ export function SkillRow({
size="icon" size="icon"
variant="ghost" variant="ghost"
className={cn( className={cn(
"h-8 w-8 shrink-0", "h-8 w-8 shrink-0 rounded-[5px] text-muted-foreground hover:bg-muted hover:text-foreground",
skill.featured && "text-amber-600 hover:text-amber-700", skill.featured && "text-amber-600 hover:text-amber-700",
)} )}
disabled={setFeatured.isPending} disabled={setFeatured.isPending}
@@ -1182,7 +1223,7 @@ export function SkillRow({
size="icon" size="icon"
variant="ghost" variant="ghost"
className={cn( className={cn(
"h-8 w-8 shrink-0", "h-8 w-8 shrink-0 rounded-[5px] text-muted-foreground hover:bg-muted hover:text-foreground",
skill.pinned && "text-emerald-600 hover:text-emerald-700", skill.pinned && "text-emerald-600 hover:text-emerald-700",
)} )}
disabled={setPinned.isPending} disabled={setPinned.isPending}
@@ -1203,7 +1244,7 @@ export function SkillRow({
size="icon" size="icon"
variant="ghost" variant="ghost"
className={cn( className={cn(
"h-8 w-8 shrink-0", "h-8 w-8 shrink-0 rounded-[5px] text-muted-foreground hover:bg-muted hover:text-foreground",
skill.always_on && "text-amber-600 hover:text-amber-700", skill.always_on && "text-amber-600 hover:text-amber-700",
)} )}
disabled={setAlwaysOn.isPending} disabled={setAlwaysOn.isPending}
@@ -1223,7 +1264,7 @@ export function SkillRow({
<Button <Button
size="icon" size="icon"
variant="ghost" variant="ghost"
className="h-8 w-8 shrink-0" className="h-8 w-8 shrink-0 rounded-[5px] text-muted-foreground hover:bg-muted hover:text-foreground"
disabled={setPublished.isPending} disabled={setPublished.isPending}
onClick={() => void handleTogglePublished(!skill.published)} onClick={() => void handleTogglePublished(!skill.published)}
title={ title={
@@ -1242,7 +1283,7 @@ export function SkillRow({
<Button <Button
size="icon" size="icon"
variant="ghost" variant="ghost"
className="h-8 w-8 shrink-0" className="h-8 w-8 shrink-0 rounded-[5px] text-muted-foreground hover:bg-muted hover:text-foreground"
disabled={duplicateSkillMutation.isPending} disabled={duplicateSkillMutation.isPending}
onClick={handleOpenDuplicate} onClick={handleOpenDuplicate}
title="复制为新技能" title="复制为新技能"
@@ -1253,7 +1294,7 @@ export function SkillRow({
<Button <Button
size="icon" size="icon"
variant="ghost" variant="ghost"
className="text-destructive hover:text-destructive h-8 w-8 shrink-0" className="h-8 w-8 shrink-0 rounded-[5px] text-destructive hover:bg-destructive/10 hover:text-destructive"
onClick={() => setConfirmDeleteOpen(true)} onClick={() => setConfirmDeleteOpen(true)}
title={t.settings.skills.deleteAction} title={t.settings.skills.deleteAction}
> >
@@ -1263,46 +1304,104 @@ export function SkillRow({
</> </>
); );
// 图标配色:柔和浅底 + 饱和前景(参考应用市场风格),不再使用实色重底。
// 图标多样化:按名称关键词匹配语义图标,未命中则按名称哈希从图标族轮换;
// 配色沿用柔和浅底 + 饱和前景(参考应用市场风格),同技能稳定不闪变。
const iconPalette = [
{ Icon: GlobeIcon, className: "bg-emerald-50 text-emerald-600 ring-1 ring-emerald-100 dark:bg-emerald-400/10 dark:text-emerald-300 dark:ring-emerald-400/20", card: "bg-gradient-to-br from-emerald-50/60 via-card to-card dark:from-emerald-400/[0.05] dark:via-card dark:to-card" },
{ Icon: FileArchive, className: "bg-violet-50 text-violet-600 ring-1 ring-violet-100 dark:bg-violet-400/10 dark:text-violet-300 dark:ring-violet-400/20", card: "bg-gradient-to-br from-violet-50/60 via-card to-card dark:from-violet-400/[0.05] dark:via-card dark:to-card" },
{ Icon: WorkflowIcon, className: "bg-sky-50 text-sky-600 ring-1 ring-sky-100 dark:bg-sky-400/10 dark:text-sky-300 dark:ring-sky-400/20", card: "bg-gradient-to-br from-sky-50/60 via-card to-card dark:from-sky-400/[0.05] dark:via-card dark:to-card" },
{ Icon: Upload, className: "bg-amber-50 text-amber-600 ring-1 ring-amber-100 dark:bg-amber-400/10 dark:text-amber-300 dark:ring-amber-400/20", card: "bg-gradient-to-br from-amber-50/60 via-card to-card dark:from-amber-400/[0.05] dark:via-card dark:to-card" },
{ Icon: BarChart3Icon, className: "bg-teal-50 text-teal-600 ring-1 ring-teal-100 dark:bg-teal-400/10 dark:text-teal-300 dark:ring-teal-400/20", card: "bg-gradient-to-br from-teal-50/60 via-card to-card dark:from-teal-400/[0.05] dark:via-card dark:to-card" },
{ Icon: MessageSquareTextIcon, className: "bg-rose-50 text-rose-600 ring-1 ring-rose-100 dark:bg-rose-400/10 dark:text-rose-300 dark:ring-rose-400/20", card: "bg-gradient-to-br from-rose-50/60 via-card to-card dark:from-rose-400/[0.05] dark:via-card dark:to-card" },
{ Icon: DatabaseIcon, className: "bg-indigo-50 text-indigo-600 ring-1 ring-indigo-100 dark:bg-indigo-400/10 dark:text-indigo-300 dark:ring-indigo-400/20", card: "bg-gradient-to-br from-indigo-50/60 via-card to-card dark:from-indigo-400/[0.05] dark:via-card dark:to-card" },
{ Icon: ClockIcon, className: "bg-orange-50 text-orange-600 ring-1 ring-orange-100 dark:bg-orange-400/10 dark:text-orange-300 dark:ring-orange-400/20", card: "bg-gradient-to-br from-orange-50/60 via-card to-card dark:from-orange-400/[0.05] dark:via-card dark:to-card" },
];
const iconKeywords: Array<{ match: RegExp; icon: number }> = [
{ match: /web|search|crawl|spider/i, icon: 0 },
{ match: /doc|file|archive|report|md/i, icon: 1 },
{ match: /workflow|agent|pipeline|flow/i, icon: 2 },
{ match: /upload|install|package/i, icon: 3 },
{ match: /chart|analysis|stat|visual/i, icon: 4 },
{ match: /chat|message|qa|对话|问答/i, icon: 5 },
{ match: /data|database|db|sql/i, icon: 6 },
{ match: /time|timing|schedule|cron/i, icon: 7 },
];
const nameHash = [...skill.name].reduce((acc, ch) => acc + ch.charCodeAt(0), 0);
const keywordIcon = iconKeywords.find(({ match }) => match.test(skill.name) || match.test(skill.description ?? ""));
const iconStyle = keywordIcon
? iconPalette[keywordIcon.icon]
: iconPalette[nameHash % iconPalette.length];
const SkillIcon = iconStyle.Icon;
return ( return (
<> <>
{isCard ? ( {isCard ? (
<div <div
className={cn( className={cn(
"flex h-full min-w-0 flex-col rounded-lg border p-3 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C] dark:text-white", "flex h-full min-w-0 flex-col rounded-[5px] p-4 shadow-[0_2px_8px_rgba(15,23,42,0.06)] transition-shadow hover:shadow-[0_4px_14px_rgba(15,23,42,0.10)]",
isOffline && "bg-muted/60 border-dashed dark:bg-[#071D36]", isOffline
)} ? "border border-dashed border-border/60 bg-muted/50"
> : iconStyle.card,
)}
>
<div <div
className="min-w-0 flex-1 cursor-pointer" className="min-w-0 flex-1 cursor-pointer"
onClick={() => setDetailOpen(true)} onClick={() => setDetailOpen(true)}
> >
{badgeGroup} <div className="flex items-start gap-3.5">
<p className="text-muted-foreground mt-1 line-clamp-3 text-sm"> <div
{desensitize(skill.description ?? "")} className={cn(
</p> "flex size-12 shrink-0 items-center justify-center rounded-full",
{metaNodes} iconStyle.className,
)}
>
<SkillIcon className="size-6" />
</div>
<div className="min-w-0 flex-1">
{badgeGroup}
<p className="text-muted-foreground mt-1.5 line-clamp-3 text-sm leading-6">
{desensitize(skill.description ?? "")}
</p>
</div>
</div>
<div className="mt-3">{metaNodes}</div>
</div> </div>
<div className="mt-2 flex flex-wrap items-center justify-end gap-1 border-t pt-2 dark:border-[#213D5E]"> <div className="mt-4 flex flex-wrap items-center justify-end gap-1 border-t border-border/70 pt-3">
{actionButtons} {actionButtons}
</div> </div>
</div> </div>
) : ( ) : (
<Item <Item
className={cn( className={cn(
"w-full dark:border-[#213D5E] dark:bg-[#02244C] dark:text-white", "group/skill-card w-full rounded-[5px] border-0 px-5 py-3 shadow-[0_2px_8px_rgba(15,23,42,0.06)] transition-shadow hover:shadow-[0_4px_14px_rgba(15,23,42,0.10)]",
isOffline && "bg-muted/60 border-dashed dark:bg-[#071D36]", isOffline
)} ? "border border-dashed border-border/60 bg-muted/50"
variant="outline" : iconStyle.card,
> )}
variant="outline"
>
<ItemContent <ItemContent
className="cursor-pointer" className="cursor-pointer"
onClick={() => setDetailOpen(true)} onClick={() => setDetailOpen(true)}
> >
<ItemTitle>{badgeGroup}</ItemTitle> <div className="flex min-w-0 items-center gap-4">
<ItemDescription className="line-clamp-4"> <div
{desensitize(skill.description ?? "")} className={cn(
</ItemDescription> "flex size-12 shrink-0 items-center justify-center rounded-full",
{metaNodes} iconStyle.className,
)}
>
<SkillIcon className="size-6" />
</div>
<div className="min-w-0 flex-1 pt-0.5">
<ItemTitle>{badgeGroup}</ItemTitle>
<ItemDescription className="mt-1.5 line-clamp-2 leading-5">
{desensitize(skill.description ?? "")}
</ItemDescription>
<div className="mt-2">{metaNodes}</div>
</div>
</div>
</ItemContent> </ItemContent>
<ItemActions>{actionButtons}</ItemActions> <ItemActions>{actionButtons}</ItemActions>
</Item> </Item>
@@ -1365,46 +1464,39 @@ export function SkillRow({
<Button <Button
variant="destructive" variant="destructive"
onClick={() => void handleDelete()} onClick={() => void handleDelete()}
disabled={deleteCustom.isPending || deleteBuiltin.isPending} disabled={deleteCustom.isPending || deleteBuiltin.isPending}
> >
{deleteCustom.isPending || deleteBuiltin.isPending {deleteCustom.isPending || deleteBuiltin.isPending
? t.common.loading ? t.common.loading
: t.common.delete} : t.common.delete}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={confirmOfflineOpen} onOpenChange={setConfirmOfflineOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t.settings.skills.offlineConfirmTitle}</DialogTitle>
<DialogDescription>
{t.settings.skills.offlineConfirmDescription.replace(
"{name}",
desensitize(skill.name),
)}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => setConfirmOfflineOpen(false)}
disabled={setEnabled.isPending}
>
{t.common.cancel}
</Button>
<Button
variant="destructive"
onClick={() => void handleSetEnabled(false)}
disabled={setEnabled.isPending}
>
{setEnabled.isPending
? t.common.loading
: t.settings.skills.offlineAction}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<TDesignDialog
visible={confirmOfflineOpen}
header={t.settings.skills.offlineConfirmTitle}
body={t.settings.skills.offlineConfirmDescription.replace(
"{name}",
desensitize(skill.name),
)}
theme="danger"
placement="center"
cancelBtn={{
children: t.common.cancel,
disabled: setEnabled.isPending,
}}
confirmBtn={{
children: t.settings.skills.offlineAction,
theme: "danger",
}}
confirmLoading={setEnabled.isPending}
closeBtn={!setEnabled.isPending}
closeOnEscKeydown={!setEnabled.isPending}
closeOnOverlayClick={!setEnabled.isPending}
onClose={() => setConfirmOfflineOpen(false)}
onConfirm={() => void handleSetEnabled(false)}
/>
<TagPickerDialog <TagPickerDialog
open={tagPickerOpen} open={tagPickerOpen}
onOpenChange={setTagPickerOpen} onOpenChange={setTagPickerOpen}
@@ -2,7 +2,7 @@
import { ArchiveIcon, ClockIcon, MoreHorizontalIcon, RotateCcwIcon, Trash2Icon } from "lucide-react"; import { ArchiveIcon, ClockIcon, MoreHorizontalIcon, RotateCcwIcon, Trash2Icon } 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";
@@ -2,7 +2,7 @@
import { Pencil, Plus, Trash2 } from "lucide-react"; import { Pencil, Plus, Trash2 } 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";
@@ -7,7 +7,7 @@ import {
UploadCloudIcon, UploadCloudIcon,
} from "lucide-react"; } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, 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 { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@@ -165,7 +165,10 @@ export function UploadSettingsPage() {
}; };
const restoreDefaults = async () => { const restoreDefaults = async () => {
if (!window.confirm("确定恢复系统默认上传策略吗?当前自定义设置会被覆盖。")) { if (!(await confirmAction("确定恢复系统默认上传策略吗?当前自定义设置会被覆盖。", {
title: "恢复默认设置?",
confirmText: "恢复默认",
}))) {
return; return;
} }
try { try {
@@ -1,6 +1,6 @@
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { useEffect, useRef, useState } from "react"; import { 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 { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@@ -1,7 +1,7 @@
"use client"; "use client";
import { FileOutputIcon, Loader2Icon } from "lucide-react"; import { FileOutputIcon, Loader2Icon } from "lucide-react";
import { toast } from "sonner"; import { toast } from "@/core/ui/feedback";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { import {
@@ -3,7 +3,7 @@
import { ExternalLinkIcon, Loader2, WandSparklesIcon } from "lucide-react"; import { ExternalLinkIcon, Loader2, WandSparklesIcon } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
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 { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@@ -1,12 +1,24 @@
import { CheckCircle2, Database, Loader2, RefreshCw, Search, Sparkles } from "lucide-react"; import {
CheckCircle2,
Database,
Link2Off,
ListChecks,
Loader2,
RefreshCw,
Search,
Sparkles,
SquareX,
Trash2,
} 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 { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox"; import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress"; import { Progress } from "@/components/ui/progress";
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
import { ScrollArea } from "@/components/ui/scroll-area"; import { ScrollArea } from "@/components/ui/scroll-area";
import { useAllSkillsAdmin, useSkills } from "@/core/skills/hooks"; import { useAllSkillsAdmin, useSkills } from "@/core/skills/hooks";
import { useLlmWikiKnowledgeBases, useLlmWikiRuntime } from "@/strategy-components/api/llmwiki"; import { useLlmWikiKnowledgeBases, useLlmWikiRuntime } from "@/strategy-components/api/llmwiki";
@@ -42,6 +54,25 @@ const STATUS_LABELS: Record<string, string> = {
canceled: "已取消", canceled: "已取消",
}; };
/** 归纳状态 → 徽章配色(浅色底 + 同系深字,跟随暗色模式)。 */
const STATUS_BADGE: Record<string, string> = {
queued: "border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-400/30 dark:bg-sky-400/10 dark:text-sky-300",
running: "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-400/30 dark:bg-blue-400/10 dark:text-blue-300",
awaiting_review: "border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-400/30 dark:bg-amber-400/10 dark:text-amber-300",
completed: "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-400/30 dark:bg-emerald-400/10 dark:text-emerald-300",
partial_failed: "border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-400/30 dark:bg-orange-400/10 dark:text-orange-300",
failed: "border-red-200 bg-red-50 text-red-700 dark:border-red-400/30 dark:bg-red-400/10 dark:text-red-300",
canceled: "border-slate-200 bg-slate-100 text-slate-600 dark:border-slate-400/30 dark:bg-slate-400/10 dark:text-slate-300",
};
function StatusBadge({ status }: { status: string }) {
return (
<Badge variant="outline" className={STATUS_BADGE[status] ?? ""}>
{STATUS_LABELS[status] || status}
</Badge>
);
}
export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean }) { export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean }) {
const visibleSkills = useSkills(); const visibleSkills = useSkills();
const allSkills = useAllSkillsAdmin(adminMode); const allSkills = useAllSkillsAdmin(adminMode);
@@ -142,10 +173,30 @@ export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean
} }
}; };
const detachBinding = async (id: string, deleteContributions: boolean) => {
const confirmed = await confirmAction(
deleteContributions
? "解除关联并删除此技能贡献?共享知识仍会保留其他来源。"
: "解除关联并保留目标知识内容?",
{
title: deleteContributions ? "删除技能贡献?" : "解除知识关联?",
confirmText: deleteContributions ? "删除贡献" : "解除关联",
danger: deleteContributions,
},
);
if (confirmed) {
actions.detach.mutate({ id, deleteContributions });
}
};
return ( return (
<div className="grid size-full min-h-0 gap-4 overflow-auto p-4 lg:grid-cols-[minmax(320px,0.9fr)_minmax(420px,1.1fr)] lg:overflow-hidden lg:p-6"> <ResizablePanelGroup
<section className="flex min-h-0 flex-col rounded-lg border bg-card"> orientation="horizontal"
<div className="border-b p-4"> className="size-full min-h-0 overflow-auto p-4 lg:overflow-hidden lg:p-6"
>
<ResizablePanel defaultSize={50} minSize={25} className="flex min-h-0 min-w-0 flex-col">
<section className="flex h-full min-h-0 flex-col rounded-[5px] bg-card shadow-[0_2px_8px_rgba(15,23,42,0.06)]">
<div className="border-b border-border/60 p-4">
<h2 className="font-semibold">归纳技能知识</h2> <h2 className="font-semibold">归纳技能知识</h2>
<p className="mt-1 text-xs leading-5 text-muted-foreground">选择技能和一个目标知识库后,系统会在后台提取 Markdown 等知识资料,忽略 Python 等代码文件,自动生成 Wiki、关系和向量索引。</p> <p className="mt-1 text-xs leading-5 text-muted-foreground">选择技能和一个目标知识库后,系统会在后台提取 Markdown 等知识资料,忽略 Python 等代码文件,自动生成 Wiki、关系和向量索引。</p>
</div> </div>
@@ -154,7 +205,8 @@ export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean
<div> <div>
<div className="mb-2 flex items-center justify-between"> <div className="mb-2 flex items-center justify-between">
<span className="text-sm font-medium">第一步:选择技能(已选 {selectedSkills.length})</span> <span className="text-sm font-medium">第一步:选择技能(已选 {selectedSkills.length})</span>
<Button variant="ghost" size="sm" onClick={toggleFilteredSkills}> <Button variant="ghost" size="sm" className="h-7 gap-2 rounded-[5px] px-2.5 text-primary hover:bg-primary/10 hover:text-primary" onClick={toggleFilteredSkills}>
{allFilteredSelected ? <SquareX className="size-3.5" /> : <ListChecks className="size-3.5" />}
{allFilteredSelected ? "清空当前结果" : "选择当前结果"} {allFilteredSelected ? "清空当前结果" : "选择当前结果"}
</Button> </Button>
</div> </div>
@@ -167,18 +219,26 @@ export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean
className="pl-8" className="pl-8"
/> />
</div> </div>
<div className="max-h-60 space-y-1 overflow-y-auto rounded-md border p-2"> <div className="max-h-60 space-y-1 overflow-y-auto rounded-[5px] bg-muted/30 p-2">
{isLoading ? <Loader2 className="m-4 size-5 animate-spin" /> : filteredSkills.map((skill) => ( {isLoading ? <Loader2 className="m-4 size-5 animate-spin" /> : filteredSkills.map((skill) => (
<label key={skill.name} className="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 hover:bg-muted"> <label key={skill.name} className="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 hover:bg-muted">
<Checkbox checked={selectedSkills.includes(skill.name)} onCheckedChange={() => toggle(selectedSkills, skill.name, setSelectedSkills)} /> <Checkbox checked={selectedSkills.includes(skill.name)} onCheckedChange={() => toggle(selectedSkills, skill.name, setSelectedSkills)} />
<span className="truncate text-sm">{skill.name_zh || skill.name}</span> <span className="truncate text-sm">{skill.name_zh || skill.name}</span>
<span className="ml-auto truncate text-xs text-muted-foreground">{skill.name}</span> <span className="ml-auto truncate text-xs text-muted-foreground">{skill.name}</span>
{(bindings.data ?? []).some((binding) => binding.skill_name === skill.name) && ( {(bindings.data ?? []).some((binding) => binding.skill_name === skill.name) && (
<Badge variant="secondary" className="shrink-0 text-[10px]"> (() => {
{(bindings.data ?? []).some((binding) => binding.skill_name === skill.name && `${binding.target_type}:${binding.target_id}` === selectedTargetKey) const inTarget = (bindings.data ?? []).some((binding) => binding.skill_name === skill.name && `${binding.target_type}:${binding.target_id}` === selectedTargetKey);
? "已在目标库" return (
: `已归纳 ${(bindings.data ?? []).filter((binding) => binding.skill_name === skill.name).length} 库`} <Badge
</Badge> variant="outline"
className={inTarget
? "shrink-0 border-emerald-200 bg-emerald-50 text-[10px] text-emerald-700 dark:border-emerald-400/30 dark:bg-emerald-400/10 dark:text-emerald-300"
: "shrink-0 border-violet-200 bg-violet-50 text-[10px] text-violet-700 dark:border-violet-400/30 dark:bg-violet-400/10 dark:text-violet-300"}
>
{inTarget ? "已在目标库" : `已归纳 ${(bindings.data ?? []).filter((binding) => binding.skill_name === skill.name).length} 库`}
</Badge>
);
})()
)} )}
</label> </label>
))} ))}
@@ -194,7 +254,7 @@ export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean
<div className="mb-2 flex items-center justify-between"> <div className="mb-2 flex items-center justify-between">
<span className="text-sm font-medium">第二步:选择一个目标知识库</span> <span className="text-sm font-medium">第二步:选择一个目标知识库</span>
</div> </div>
<div className="space-y-1 rounded-md border p-2"> <div className="space-y-1 rounded-[5px] bg-muted/30 p-2">
{targets.map((target) => { {targets.map((target) => {
const key = `${target.target_type}:${target.target_id}`; const key = `${target.target_type}:${target.target_id}`;
return ( return (
@@ -205,7 +265,7 @@ export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean
/> />
<Database className="size-4 text-muted-foreground" /> <Database className="size-4 text-muted-foreground" />
<span className="text-sm">{target.target_name}</span> <span className="text-sm">{target.target_name}</span>
<Badge variant="outline" className="ml-auto text-[10px]">普通 Wiki 库</Badge> <Badge variant="outline" className="ml-auto border-violet-200 bg-violet-50 text-[10px] text-violet-700 dark:border-violet-400/30 dark:bg-violet-400/10 dark:text-violet-300">普通 Wiki 库</Badge>
</label> </label>
); );
})} })}
@@ -225,7 +285,7 @@ export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean
)} )}
</div> </div>
</div> </div>
<div className="rounded-lg border bg-muted/30 p-3 text-xs leading-5 text-muted-foreground"> <div className="rounded-[5px] bg-muted/40 p-3 text-xs leading-5 text-muted-foreground">
第三步:提交后可离开本页。归纳、Wiki 生成、向量化及所需索引同步均在后台完成。 第三步:提交后可离开本页。归纳、Wiki 生成、向量化及所需索引同步均在后台完成。
</div> </div>
<Button className="w-full" disabled={actions.createJob.isPending || !selectedSkills.length || !selectedTargetKey} onClick={() => void submit()}> <Button className="w-full" disabled={actions.createJob.isPending || !selectedSkills.length || !selectedTargetKey} onClick={() => void submit()}>
@@ -235,14 +295,20 @@ export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean
</div> </div>
</ScrollArea> </ScrollArea>
</section> </section>
</ResizablePanel>
<section className="flex min-h-0 flex-col gap-4 overflow-hidden"> {/* 隐形拖拽热区:平时不显示分隔线,悬停交界处出现淡色提示条,按住拖动 */}
<div className="flex min-h-0 flex-1 flex-col rounded-lg border bg-card"> <ResizableHandle className="mx-1 w-1 bg-transparent hover:bg-transparent active:bg-transparent after:absolute after:inset-y-0 after:left-1/2 after:w-2 after:-translate-x-1/2 after:cursor-col-resize after:rounded-full after:transition-colors hover:after:bg-primary/25 active:after:bg-primary/25" />
<div className="flex items-center justify-between border-b p-4">
<ResizablePanel defaultSize={50} minSize={25} className="flex min-h-0 min-w-0 flex-col overflow-hidden">
<section className="flex h-full min-h-0 flex-col gap-4 overflow-hidden">
<div className="flex min-h-0 flex-1 flex-col rounded-[5px] bg-card shadow-[0_2px_8px_rgba(15,23,42,0.06)]">
<div className="flex items-center justify-between border-b border-border/60 p-4">
<div><h2 className="font-semibold">我的归纳任务</h2><p className="text-xs text-muted-foreground">任务会自动刷新,失败项可直接重试</p></div> <div><h2 className="font-semibold">我的归纳任务</h2><p className="text-xs text-muted-foreground">任务会自动刷新,失败项可直接重试</p></div>
<Button size="icon" variant="ghost" onClick={() => void jobs.refetch()}><RefreshCw className="size-4" /></Button> <Button size="icon" variant="ghost" onClick={() => void jobs.refetch()}><RefreshCw className="size-4" /></Button>
</div> </div>
<ScrollArea className="min-h-0 flex-1"> {/* 原生滚动:Radix ScrollArea 视口内容为 table 布局,长名会把卡片撑破 */}
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden">
<div className="space-y-3 p-4"> <div className="space-y-3 p-4">
{(jobs.data ?? []).map((job) => { {(jobs.data ?? []).map((job) => {
const countedDone = job.success_count + job.partial_failed_count + job.failed_count; const countedDone = job.success_count + job.partial_failed_count + job.failed_count;
@@ -252,15 +318,15 @@ export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean
const done = Math.max(countedDone, itemDone); const done = Math.max(countedDone, itemDone);
const progress = job.total_count ? Math.round((done / job.total_count) * 100) : 0; const progress = job.total_count ? Math.round((done / job.total_count) * 100) : 0;
return ( return (
<div key={job.id} className="rounded-md border p-3"> <div key={job.id} className="rounded-[5px] bg-muted/30 p-3">
<div className="flex items-center gap-2 text-sm"><Badge variant={job.status === "completed" ? "default" : "secondary"}>{STATUS_LABELS[job.status] || job.status}</Badge><span>{done}/{job.total_count} 项</span><span className="ml-auto text-xs text-muted-foreground">{new Date(job.created_at).toLocaleString()}</span></div> <div className="flex items-center gap-2 text-sm"><StatusBadge status={job.status} /><span>{done}/{job.total_count} 项</span><span className="ml-auto text-xs text-muted-foreground">{new Date(job.created_at).toLocaleString()}</span></div>
<Progress className="my-2" value={progress} /> <Progress className="my-2" value={progress} />
{job.items?.map((item) => ( {job.items?.map((item) => (
<div key={item.id} className="mt-2 flex items-center gap-2 border-t pt-2 text-xs"> <div key={item.id} className="mt-2 flex items-center gap-2 border-t border-border/60 pt-2 text-xs">
<span className="max-w-36 truncate font-medium">{item.skill_name}</span> <span className="min-w-0 flex-1 truncate font-medium" title={item.skill_name}>{item.skill_name}</span>
<span className="text-muted-foreground">{PHASE_LABELS[item.phase] || STATUS_LABELS[item.status] || item.phase}</span> <span className="shrink-0 text-muted-foreground">{PHASE_LABELS[item.phase] || STATUS_LABELS[item.status] || item.phase}</span>
<span className="ml-auto">{item.progress}%</span> <span className="shrink-0 tabular-nums">{item.progress}%</span>
{item.status === "failed" && <Button size="sm" variant="outline" onClick={() => actions.retry.mutate(item.id)}>重试</Button>} {item.status === "failed" && <Button size="sm" variant="outline" className="h-7 shrink-0 gap-2 rounded-[5px] px-2.5" onClick={() => actions.retry.mutate(item.id)}><RefreshCw className="size-3.5" />重试</Button>}
</div> </div>
))} ))}
</div> </div>
@@ -268,13 +334,25 @@ export function SkillKnowledgePanel({ adminMode = false }: { adminMode?: boolean
})} })}
{!jobs.data?.length && <p className="py-10 text-center text-sm text-muted-foreground">暂无归纳任务</p>} {!jobs.data?.length && <p className="py-10 text-center text-sm text-muted-foreground">暂无归纳任务</p>}
</div> </div>
</ScrollArea> </div>
</div> </div>
<div className="max-h-80 overflow-auto rounded-lg border bg-card p-3 text-xs"> <div className="max-h-80 overflow-auto rounded-[5px] bg-card p-3 text-xs shadow-[0_2px_8px_rgba(15,23,42,0.06)]">
<div className="mb-2 flex items-center gap-2 text-muted-foreground"><CheckCircle2 className="size-4 text-emerald-600" />已归纳关联:{bindings.data?.length ?? 0}</div> <div className="mb-2 flex items-center gap-2 text-muted-foreground"><CheckCircle2 className="size-4 text-emerald-600" />已归纳关联:{bindings.data?.length ?? 0}</div>
<div className="space-y-2">{bindings.data?.map((binding) => <div key={binding.id} className="flex flex-wrap items-center gap-2 rounded border p-2"><span className="max-w-40 truncate font-medium">{binding.skill_name}</span><span className="max-w-48 truncate text-muted-foreground">已归纳到 {binding.target_name}</span><Badge variant="outline">{STATUS_LABELS[binding.status] || binding.status}</Badge><Button size="sm" variant="outline" className="ml-auto" disabled={actions.resync.isPending} onClick={() => actions.resync.mutate(binding.id)}>重新归纳</Button><Button size="sm" variant="ghost" onClick={() => { if (window.confirm("解除关联并保留目标知识内容?")) actions.detach.mutate({ id: binding.id, deleteContributions: false }); }}>解除关联</Button>{adminMode && <Button size="sm" variant="destructive" onClick={() => { if (window.confirm("解除关联并删除此技能贡献?共享知识仍会保留其他来源。")) actions.detach.mutate({ id: binding.id, deleteContributions: true }); }}>删除贡献</Button>}</div>)}</div> <div className="space-y-2">
{bindings.data?.map((binding) => (
<div key={binding.id} className="flex flex-wrap items-center gap-2 rounded-[5px] bg-muted/30 p-2">
<span className="min-w-0 font-medium" title={binding.skill_name}>{binding.skill_name}</span>
<span className="min-w-0 text-muted-foreground">已归纳到 {binding.target_name}</span>
<StatusBadge status={binding.status} />
<Button size="sm" variant="outline" className="ml-auto h-7 gap-2 rounded-[5px] px-2.5" disabled={actions.resync.isPending} onClick={() => actions.resync.mutate(binding.id)}><RefreshCw className="size-3.5" />重新归纳</Button>
<Button size="sm" variant="ghost" className="h-7 gap-2 rounded-[5px] px-2.5 text-muted-foreground hover:bg-muted hover:text-foreground" onClick={() => void detachBinding(binding.id, false)}><Link2Off className="size-3.5" />解除关联</Button>
{adminMode && <Button size="sm" variant="destructive" className="h-7 gap-2 rounded-[5px] px-2.5" onClick={() => void detachBinding(binding.id, true)}><Trash2 className="size-3.5" />删除贡献</Button>}
</div>
))}
</div>
</div> </div>
</section> </section>
</div> </ResizablePanel>
</ResizablePanelGroup>
); );
} }
@@ -16,7 +16,7 @@ import {
XIcon, XIcon,
} from "lucide-react"; } 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 { Dialog as TDesignDialog } from "tdesign-react"; import { Dialog as TDesignDialog } from "tdesign-react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@@ -9,7 +9,7 @@ import {
} from "lucide-react"; } from "lucide-react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react"; import { useEffect, 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";
@@ -9,7 +9,7 @@ import {
XIcon, XIcon,
} 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 {
@@ -90,9 +90,12 @@ export function SkillFilePreviewDialog({
const dirty = editing && data?.content !== undefined && draft !== data.content; const dirty = editing && data?.content !== undefined && draft !== data.content;
function requestClose(next: boolean) { async function requestClose(next: boolean) {
if (!next && dirty) { if (!next && dirty) {
if (!window.confirm(tx.filesDiscardConfirm)) return; if (!(await confirmAction(tx.filesDiscardConfirm, {
title: "放弃未保存修改?",
confirmText: "放弃修改",
}))) return;
} }
onOpenChange(next); onOpenChange(next);
} }
@@ -103,8 +106,11 @@ export function SkillFilePreviewDialog({
setEditing(true); setEditing(true);
} }
function cancelEditing() { async function cancelEditing() {
if (dirty && !window.confirm(tx.filesDiscardConfirm)) return; if (dirty && !(await confirmAction(tx.filesDiscardConfirm, {
title: "放弃未保存修改?",
confirmText: "放弃修改",
}))) return;
setEditing(false); setEditing(false);
setDraft(""); setDraft("");
} }
@@ -122,7 +128,11 @@ export function SkillFilePreviewDialog({
async function handleDelete() { async function handleDelete() {
if (!skillName || !path) return; if (!skillName || !path) return;
if (!window.confirm(tx.filesDeleteConfirm.replace("{path}", path))) return; if (!(await confirmAction(tx.filesDeleteConfirm.replace("{path}", path), {
title: "删除技能文件?",
confirmText: "删除",
danger: true,
}))) return;
try { try {
await remove.mutateAsync({ skillName, path }); await remove.mutateAsync({ skillName, path });
toast.success(tx.filesDeleteSuccess); toast.success(tx.filesDeleteSuccess);
@@ -2,7 +2,7 @@
import { CheckIcon, Loader2 } from "lucide-react"; import { CheckIcon, Loader2 } from "lucide-react";
import { useState } from "react"; import { 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 {
@@ -2,7 +2,7 @@
import { CheckIcon, Loader2 } from "lucide-react"; import { CheckIcon, Loader2 } from "lucide-react";
import { useState } from "react"; import { 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 {
@@ -108,7 +108,7 @@ export function TagSearchBar({
} }
}} }}
placeholder={searchPlaceholder ?? t.adminTags.searchPlaceholder} placeholder={searchPlaceholder ?? t.adminTags.searchPlaceholder}
className={cn("pl-8", searching && "pr-9")} className={cn("rounded-[5px] bg-card pl-8", searching && "pr-9")}
name="tag-search" name="tag-search"
// A `type="password"` field elsewhere on the page (e.g. the private // A `type="password"` field elsewhere on the page (e.g. the private
// square access gate) makes browsers / password managers pick the // square access gate) makes browsers / password managers pick the
@@ -126,9 +126,8 @@ export function TagSearchBar({
</div> </div>
<Button <Button
type="button" type="button"
variant="outline"
onClick={flushSearch} onClick={flushSearch}
className="shrink-0 gap-1.5" className="h-9 shrink-0 gap-2.5 rounded-[5px] px-4"
title="搜索" title="搜索"
> >
{searching ? ( {searching ? (
@@ -153,8 +152,8 @@ export function TagSearchBar({
className={cn( className={cn(
"inline-flex items-center rounded-full border px-3 py-1 text-xs font-medium transition-all", "inline-flex items-center rounded-full border px-3 py-1 text-xs font-medium transition-all",
tagIds.length === 0 tagIds.length === 0
? "bg-foreground text-background border-foreground" ? "border-primary bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground border-transparent hover:opacity-80", : "border-border/60 bg-card text-muted-foreground hover:border-primary/30 hover:text-foreground",
)} )}
> >
{t.adminTags.allTags} {t.adminTags.allTags}
@@ -168,14 +167,20 @@ export function TagSearchBar({
type="button" type="button"
onClick={() => toggleTag(tag.id)} onClick={() => toggleTag(tag.id)}
className={cn( className={cn(
"inline-flex items-center gap-1 rounded-full border px-3 py-1 text-xs font-medium transition-all", "inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-all",
color.chip,
checked checked
? "ring-2 ring-offset-1 ring-foreground/40" ? "border-primary bg-primary/10 text-primary"
: "opacity-45 hover:opacity-90", : "border-border/60 bg-card text-muted-foreground hover:border-primary/30 hover:text-foreground",
)} )}
> >
{checked && <CheckIcon className="size-3" />} {checked ? (
<CheckIcon className="size-3" />
) : (
<span
className={cn("size-1.5 rounded-full", color.swatch)}
aria-hidden
/>
)}
{tag.name} {tag.name}
</button> </button>
); );
@@ -9,7 +9,7 @@ import {
Trash2Icon, Trash2Icon,
} from "lucide-react"; } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, 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 {
@@ -100,7 +100,11 @@ export function ShareConversationDialog({
} }
async function handleRevoke() { async function handleRevoke() {
if (!share || !window.confirm(tx.revokeConfirm)) return; if (!share || !(await confirmAction(tx.revokeConfirm, {
title: "撤销分享?",
confirmText: "撤销分享",
danger: true,
}))) return;
try { try {
await revokeShare.mutateAsync(share.share_code); await revokeShare.mutateAsync(share.share_code);
toast.success(tx.revokeSuccess); toast.success(tx.revokeSuccess);
Loaded 100 of 432 files, more files were not shown because too many files have changed in this diff. Show more