Merge remote-tracking branch 'origin/master' into xuhd
# Conflicts: # offline-backend-20260512/backend/config.yaml
This commit is contained in:
commit
bd0eceda61
267 files changed
+41209
-14541
No files matched your search
@@ -4,7 +4,8 @@
|
|||||||
"PowerShell(uv --version)",
|
"PowerShell(uv --version)",
|
||||||
"PowerShell(netstat -ano)",
|
"PowerShell(netstat -ano)",
|
||||||
"PowerShell(Get-NetTCPConnection -LocalPort 8001 -ErrorAction SilentlyContinue)",
|
"PowerShell(Get-NetTCPConnection -LocalPort 8001 -ErrorAction SilentlyContinue)",
|
||||||
"PowerShell(Get-Process -Id 20560 -ErrorAction SilentlyContinue | Select-Object Id,ProcessName,Path,StartTime; try { \\(Invoke-WebRequest -Uri \"http://127.0.0.1:8001/health\" -UseBasicParsing -TimeoutSec 5\\).Content } catch { \"health check failed: $_\" })"
|
"PowerShell(Get-Process -Id 20560 -ErrorAction SilentlyContinue | Select-Object Id,ProcessName,Path,StartTime; try { \\(Invoke-WebRequest -Uri \"http://127.0.0.1:8001/health\" -UseBasicParsing -TimeoutSec 5\\).Content } catch { \"health check failed: $_\" })",
|
||||||
|
"Bash(curl -s -X POST -H \"Content-Type: application/json\" -d '{\"username\":\"demo\"}' http://localhost:8001/api/v1/auth/login/username)"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,7 +29,7 @@ VITE_AUTH_BASE_URL=https://auth.y.uat.4.cn
|
|||||||
VITE_AIPI_PGLINKTO_URL=https://pg.b.uat.4.cn
|
VITE_AIPI_PGLINKTO_URL=https://pg.b.uat.4.cn
|
||||||
VITE_AIPI_XKLINKTO_URL=https://kz.b.uat.4.cn
|
VITE_AIPI_XKLINKTO_URL=https://kz.b.uat.4.cn
|
||||||
# 工作室/笔记本前端地址(用于 auth/callback 等跳转)
|
# 工作室/笔记本前端地址(用于 auth/callback 等跳转)
|
||||||
VITE_AIPI_FRONTEND_URL=https://knowledgetoolserver.b.uat.4.cn
|
VITE_AIPI_FRONTEND_URL=https://knowledgetoolweb.b.uat.4.cn
|
||||||
# 工作室侧边栏显示开关;仅控制入口显示,展开内容仍依赖 notebook 接口成功返回数据
|
# 工作室侧边栏显示开关;仅控制入口显示,展开内容仍依赖 notebook 接口成功返回数据
|
||||||
VITE_STUDIO_ENABLED=true
|
VITE_STUDIO_ENABLED=true
|
||||||
|
|
||||||
|
|||||||
@@ -107,7 +107,7 @@ http://localhost:5173/#/embed/chats/new?sessionId=...&message=...&username=guest
|
|||||||
|
|
||||||
## 4. 公开 HTTP API(无需鉴权)
|
## 4. 公开 HTTP API(无需鉴权)
|
||||||
|
|
||||||
前缀:`/api/public/embed/`(走 Gateway,与 `VITE_BACKEND_BASE_URL` 一致,默认 `http://127.0.0.1:8001`)。
|
前缀:`/api/public/embed/`(走 Gateway,与 `VITE_BACKEND_BASE_URL` 一致,默认 `http://47.88.25.99:7001/`)。
|
||||||
|
|
||||||
CSRF / Auth 中间件对 `/api/public/` 放行;请求 **不需要** Cookie。
|
CSRF / Auth 中间件对 `/api/public/` 放行;请求 **不需要** Cookie。
|
||||||
|
|
||||||
@@ -315,7 +315,7 @@ document.getElementById("deerflow-embed").src =
|
|||||||
### 5.2 轮询直到结束
|
### 5.2 轮询直到结束
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
const API = "http://127.0.0.1:8001"; // VITE_BACKEND_BASE_URL
|
const API = "http://47.88.25.99:7001/"; // VITE_BACKEND_BASE_URL
|
||||||
|
|
||||||
async function pollUntilFinished(sessionId) {
|
async function pollUntilFinished(sessionId) {
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
@@ -348,7 +348,7 @@ const timer = setInterval(async () => {
|
|||||||
|
|
||||||
### 5.3 跨域注意
|
### 5.3 跨域注意
|
||||||
|
|
||||||
父页面从浏览器 `fetch` Gateway(如 `http://127.0.0.1:8001`)时,**Origin 必须是后端 CORS 白名单里的完整地址**(含协议、主机、端口),与 API 地址是否写 `localhost` / `127.0.0.1` 无关。
|
父页面从浏览器 `fetch` Gateway(如 `http://47.88.25.99:7001/`)时,**Origin 必须是后端 CORS 白名单里的完整地址**(含协议、主机、端口),与 API 地址是否写 `localhost` / `127.0.0.1` 无关。
|
||||||
|
|
||||||
**本地开发**(前端默认 `5174`)请在 Gateway 环境变量中配置:
|
**本地开发**(前端默认 `5174`)请在 Gateway 环境变量中配置:
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
# 多智能体「后台挂起」—— 当前状态、遗留问题与下次继续指南
|
||||||
|
|
||||||
|
> 配套设计文档:`multi-agent-background-run-dev.md`(分 Phase 0-9 的总方案)。
|
||||||
|
> 本文记录**截至本次会话的实际进展 + 还没解决的遗留问题**,方便下次直接续接。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、整体状态:跑通到哪了
|
||||||
|
|
||||||
|
「后台挂起」= Step2 把研讨交给后端**进程内驱动真模型**(leader→各席位→共识→报告),
|
||||||
|
survive 刷新/关页,对话与报告作为一个 **run 写进草稿**(和手动跑同一存取),可在历史回看。
|
||||||
|
|
||||||
|
**真网关已在本地验证可跑通**(2026-06-04 日志确认:roundtable-coordinator + 各席位 +
|
||||||
|
roundtable-report 真调 deepseek、真搜索、跑到 report run success)。但还有几个**内容/产物层面的遗留问题**(见第三节)。
|
||||||
|
|
||||||
|
### 已完成(可用)
|
||||||
|
- ✅ 后端持久化:`roundtable_jobs` 表(迁移 `20260604_01` / `20260605_01` dialogues / `20260605_02` step3)。
|
||||||
|
- ✅ 编排引擎 `packages/harness/deerflow/agents/roundtable_orchestrator/`(recommend + chain + 报告,纯逻辑可单测)。
|
||||||
|
- ✅ 控制面 `app/gateway/routers/roundtable_jobs.py`:start/get/by-draft/stream(SSE)/resume/cancel/admin-cleanup。
|
||||||
|
- ✅ 执行器 `app/gateway/roundtable_job_executor.py`:后台任务 + `set_current_user` + 生命周期 + **每轮把对话作为 `job-<id>` run 写进 `draft.step2.runs[]`(同手动存取)** + done 写 step3。
|
||||||
|
- ✅ 真网关 `app/gateway/roundtable_inprocess_gateway.py`:`SimpleNamespace(app)` + `start_run` 进程内驱动 agent;复用 `multi_agent._extract_dispatch` 解析派活;checkpointer 读最终 messages。
|
||||||
|
- ✅ 模拟网关 `roundtable_orchestrator/simulated_gateway.py`(不调真模型,前端联调用)。
|
||||||
|
- ✅ 前端:`api/roundtable-jobs.ts`、`lib/job-types.ts`、Step2「后台挂起」按钮、历史下拉 loading、`DispatchChainModal`/`DispatchChainJobModal`(流程图 + 对话面板 markdown + 加宽 + 澄清作答 + 取消 + 查看)。
|
||||||
|
- ✅ 上下文「广播」(inline):席位/总控 prompt 带上「任务背景 + 前序各席位交付 + 别提问」约束(修「席位拿不到关键信息、反问用户、总控瞎编」)。
|
||||||
|
- ✅ 后端测试:`tests/test_roundtable_jobs.py` / `test_roundtable_orchestrator.py` / `test_roundtable_job_executor.py` / `test_roundtable_jobs_api.py` 全过。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、怎么启动 / 验证(每次开工先做)
|
||||||
|
|
||||||
|
1. **开真网关**(默认是模拟网关):已写进 `offline-backend-20260512/.env`:
|
||||||
|
```
|
||||||
|
ROUNDTABLE_JOB_GATEWAY=inprocess
|
||||||
|
```
|
||||||
|
启动日志应出现 `[roundtable-jobs] gateway = inprocess (real models)`。
|
||||||
|
|
||||||
|
2. **必须用 `make gateway`(不带 --reload)跑后端!**
|
||||||
|
`make dev` 的 `--reload` 监视 `backend/` 目录,agent 运行时往 `.deer-flow/` 写文件
|
||||||
|
(memory.json / checkpoint / 沙箱输出)会触发热重载,**把长时后台任务杀掉**。
|
||||||
|
(改进项:给 uvicorn 加 `--reload-exclude '.deer-flow/*'`,或始终用 `make gateway`。)
|
||||||
|
|
||||||
|
3. **直接查库验证**(最有效,PowerShell 控制台是 GBK,导出到文件看中文):
|
||||||
|
```bash
|
||||||
|
cd offline-backend-20260512/backend
|
||||||
|
# 查最新作业的 dialogues / step3
|
||||||
|
PYTHONPATH=. uv run python -c "import sqlite3,json; con=sqlite3.connect('.deer-flow/data/deerflow.db'); ..."
|
||||||
|
```
|
||||||
|
- 作业表:`.deer-flow/data/deerflow.db` → 表 `roundtable_jobs`(`dialogues`/`step3` 列)。
|
||||||
|
- 草稿表:`roundtable_drafts` → `step2` 列里应有 `runs[ {id:"job-<jobId>", jobId, jobStatus, step2RoundtableDialogues:[...], step3:{...}} ]`。
|
||||||
|
|
||||||
|
4. **前端验证**:后台挂起 → 等跑完 → 从历史加载该草稿 → Step2 应显示后台研讨完整对话(走现有 `normalizeStep2Runs`/`hydrateStep2Run`)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、遗留问题(下次重点,已按优先级排)
|
||||||
|
|
||||||
|
### P0 —— 报告 agent 不写 HTML 文件(结果绘制拿不到产物)
|
||||||
|
- **现象**:后台报告 run 跑完,日志 `report html: no .html found in ...threads/<id>/user-data/outputs`;
|
||||||
|
`run.step3.html` 回退成报告 agent 的**纯文字**(不含 `<html>`),第3步画不出东西。
|
||||||
|
- **已做**:`build_report_prompt`(`roundtable_orchestrator/engine.py`)已对齐前端
|
||||||
|
`useStep3Report.buildReportPrompt`,明确「用 write_file 写入 /mnt/user-data/outputs/方案总览.html」;
|
||||||
|
`_read_report_html`(`roundtable_inprocess_gateway.py`)已改为扫 outputs 目录任意 `.html`。
|
||||||
|
- **仍没解决**:报告 agent(deepseek-chat)还是没调 `write_file`。
|
||||||
|
- **下次怎么查**:
|
||||||
|
1. 对比**前端那条能写出 HTML 的报告 run** 的确切调用(`useStep3Report.ts` 里 `streamMultiAgent`
|
||||||
|
调 `/api/multi-agent/run/stream` 的 body:`agent_type`/`excluded_tools`/`context` 等),
|
||||||
|
和后台 `_run_agent_turn`(`roundtable_inprocess_gateway.py`,agent_name=roundtable-report,
|
||||||
|
`excluded_tools=_REPORT_EXCLUDED`)逐项比对,找出差异(怀疑 reasoning_effort / thinking /
|
||||||
|
某个 context 字段 / recursion 步数导致它没走到 write_file)。
|
||||||
|
2. 看报告 run 的最终 messages(checkpoint)里有没有 write_file 的 tool_call(被 dangling 截断?)。
|
||||||
|
3. 报告 agent 的 SOUL:`app/gateway/routers/_roundtable_seed/roundtable-report/SOUL.md`——确认它默认行为。
|
||||||
|
|
||||||
|
### P1 —— 内容质量(本次刚加 inline 广播,待真机验证)
|
||||||
|
- **已做**:席位/总控 prompt 注入「任务背景 + 前序交付 + 别提问」。
|
||||||
|
- **待验证**:真机跑一次,看席位是否基于真实上下文产出(不再反问/凭记忆瞎编)。
|
||||||
|
- **若 inline 不够**:考虑实现**真·thread 广播**(像 `multi_agent._append_thread_message` 那样把
|
||||||
|
「用户意图 / 派活 / 各席位交付」追加进各 thread 历史)。进程内要避开 HTTP loopback 鉴权,
|
||||||
|
得用 checkpointer 直接 append human 消息(参考 `threads` 路由 POST `/state` 的内部逻辑)。这块较重,先看 inline 够不够。
|
||||||
|
|
||||||
|
### P2 —— 对话「没有步骤(steps)」
|
||||||
|
- **现象**:手动跑的气泡带工具调用步骤卡(`onPhaseChange` → `appendStepIfNew` → `Step2Dialogue.steps`);
|
||||||
|
后台对话只存了最终正文,没有 steps。
|
||||||
|
- **下次怎么做**:后台 `_run_agent_turn` 跑完后,从 checkpoint 的 messages 里抽出 tool_calls,
|
||||||
|
映射成 `Step2Dialogue.steps`(`{id,key,label,ts,args}`),在执行器 `_to_step2_dialogue` 里带上。
|
||||||
|
纯展示增强,不影响内容/报告。
|
||||||
|
|
||||||
|
### P3 —— 双跑浪费 + --reload 坑(工程健壮性)
|
||||||
|
- 进 Step2 时前端会自动跑一遍本地研讨(真模型、真线程);点后台挂起后前端那条 run 在后端还会跑完
|
||||||
|
(`stopOrchestration` 只断客户端、停不了后端 run)→ 和后台作业短暂双跑、双倍 token。
|
||||||
|
- 优化方向:进 Step2 改成「显式开始」而非自动跑;或后台挂起时真正 cancel 前端那条 run。
|
||||||
|
- `make dev` 的 `--reload` 会杀后台任务(见第二节);改进项:`--reload-exclude '.deer-flow/*'`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、关键文件清单(下次定位用)
|
||||||
|
|
||||||
|
**后端**
|
||||||
|
| 文件 | 作用 |
|
||||||
|
|------|------|
|
||||||
|
| `app/gateway/roundtable_inprocess_gateway.py` | 真网关:进程内驱动 leader/seat/re 编排循环 + `build_report_prompt` + inline 广播(`_seat_message`/`_deliveries_block`) |
|
||||||
|
| `.../roundtable_orchestrator/progress.py` | 进度落库 + `on_dialogue` 每轮回调 |
|
||||||
|
| `.../persistence/roundtable_jobs/` | job 表 model/sql |
|
||||||
|
| `app/gateway/deps.py` | `ROUNDTABLE_JOB_GATEWAY` 选网关 + 注入 executor(draft_store) |
|
||||||
|
|
||||||
|
**前端**
|
||||||
|
| 文件 | 作用 |
|
||||||
|
|------|------|
|
||||||
|
| `src/roundtable-planning/api/roundtable-jobs.ts` | 作业 API + SSE |
|
||||||
|
| `src/roundtable-planning/lib/job-types.ts` | 类型(RoundtableJob/JobDialogue/...) |
|
||||||
|
| `src/roundtable-planning/components/DispatchChainModal.tsx` / `DispatchChainJobModal.tsx` | 流程图弹窗 + 对话面板 |
|
||||||
|
| `src/roundtable-planning/pages/RoundtablePlanningPage.tsx` | 后台挂起按钮、历史下拉、**runs[] 多运行模型**(`hydrateStep2Run`/`getStep2SnapshotWithRuns`/`normalizeStep2Runs`) |
|
||||||
|
| `src/roundtable-planning/api/drafts.ts` | `DraftStep2RunSnapshot`(带 jobId/jobStatus/step3) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、关键架构事实(避免重复踩坑)
|
||||||
|
|
||||||
|
1. **真网关进程内驱动**:`start_run(body, thread_id, SimpleNamespace(app=app))` + `set_current_user`,
|
||||||
|
不走 HTTP(loopback 调 `/api/multi-agent/*` 不可行:`_auth_headers` 只转发用户 token + owner check)。
|
||||||
|
2. **后台作业首启自建全新线程**(`StartParams.is_resume`),绝不复用前端本地研讨的线程(会撞 409)。
|
||||||
|
3. **存取统一**:后台作业 = `draft.step2.runs[]` 里一个带 jobId 的 run,和手动跑同一存取/hydrate 路径,
|
||||||
|
**不要再开 observe/回显分支**(之前试过,被否)。
|
||||||
|
4. **聊天记录确实存上了**(job.dialogues + draft 的 run);之前"没存上"是测了旧代码 / 看的是前端本地残缺数据。
|
||||||
|
5. 多 worker / SSE:状态进 DB、SSE 走 DB 轮询;真网关进程内无 loopback。
|
||||||
@@ -0,0 +1,404 @@
|
|||||||
|
# 多智能体会商 Step2 多结果线方案
|
||||||
|
|
||||||
|
## 背景
|
||||||
|
|
||||||
|
当前「多智能体会商 / 多智能体规划」里,一个历史草稿只保存一份 `step2` 快照。用户从历史记录加载草稿后,如果再次点击「智能体推荐」并在弹窗里点击「进入研讨」,新的 Step2 研讨会继续写入同一份 `draft.step2`,结果是第一次生成内容会被第二次生成内容覆盖,或者页面只能展示最新一次结果。
|
||||||
|
|
||||||
|
产品期望是:
|
||||||
|
|
||||||
|
- 用户从历史记录进入已有草稿时,进入第二步后,左下角能看到第一次生成结果。
|
||||||
|
- 用户再次点击「智能体推荐」并点击「进入研讨」时,要开启一条新的研讨结果线。
|
||||||
|
- 第二次生成结果显示在左下角,但不能影响第一次生成结果。
|
||||||
|
- 用户之后再次查看同一个历史草稿时,可以分别查看第一次生成结果和第二次生成结果。
|
||||||
|
|
||||||
|
因此,这个需求的核心不是简单增加一个展示区域,而是把 Step2 从「单结果」升级为「一个草稿下多条研讨 run」。
|
||||||
|
|
||||||
|
## 现状
|
||||||
|
|
||||||
|
相关位置:
|
||||||
|
|
||||||
|
- `src/roundtable-planning/api/drafts.ts`
|
||||||
|
- `src/roundtable-planning/pages/RoundtablePlanningPage.tsx`
|
||||||
|
- `src/roundtable-planning/hooks/useStep2Orchestration.ts`
|
||||||
|
- `src/roundtable-planning/components/Step2Panel.tsx`
|
||||||
|
- `src/roundtable-planning/components/RecommendAgentsDialog.tsx`
|
||||||
|
|
||||||
|
当前 `DraftStep2Snapshot` 结构大致是:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export interface DraftStep2Snapshot {
|
||||||
|
selectedAgents?: Array<{ agent_id: string; name: string }>;
|
||||||
|
threadIds: ThreadIdMap | null;
|
||||||
|
coordinatorName: string | null;
|
||||||
|
step2RoundtableDialogues: unknown[];
|
||||||
|
lastLeaderContent: string;
|
||||||
|
hasConsensus: boolean;
|
||||||
|
consensusPercentage: number;
|
||||||
|
budgetLimit: number;
|
||||||
|
seatStubMessages?: Record<string, unknown[]>;
|
||||||
|
orchestrationMode?: "recommend" | "chain";
|
||||||
|
chain?: { id: string; title: string } | null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
这意味着一个草稿只有一份:
|
||||||
|
|
||||||
|
- 参会智能体
|
||||||
|
- 多智能体 thread 映射
|
||||||
|
- 研讨气泡
|
||||||
|
- 总控最终内容
|
||||||
|
- 共识状态
|
||||||
|
- 沙箱产物 stub
|
||||||
|
- 编排模式和业务链条
|
||||||
|
|
||||||
|
当前 `RoundtablePlanningPage.tsx` 里的 `handleConfirmAgents` 在用户点击「进入研讨」后会:
|
||||||
|
|
||||||
|
1. 规范化选中的 agents。
|
||||||
|
2. 写入 `step2.selectedAgents`。
|
||||||
|
3. 调用 `step2.resetInitGate()`。
|
||||||
|
4. 设置 `orchestrationMode` / `chainMeta`。
|
||||||
|
5. 切到 `currentStep = 2`。
|
||||||
|
|
||||||
|
它没有先把当前 Step2 结果归档成「第一次生成结果」,也没有为新的研讨创建独立 run。因此第二次研讨天然会复用同一个 `draft.step2` 写入位置。
|
||||||
|
|
||||||
|
## 目标模型
|
||||||
|
|
||||||
|
建议引入 Step2 run 概念:一个草稿可以有多条 Step2 结果线,每条结果线保存一份完整的 Step2 快照。
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface Step2RunSnapshot {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
createdAt: string;
|
||||||
|
source: "initial" | "recommend" | "chain" | "manual";
|
||||||
|
selectedAgents?: Array<{ agent_id: string; name: string }>;
|
||||||
|
threadIds: ThreadIdMap | null;
|
||||||
|
coordinatorName: string | null;
|
||||||
|
step2RoundtableDialogues: unknown[];
|
||||||
|
lastLeaderContent: string;
|
||||||
|
hasConsensus: boolean;
|
||||||
|
consensusPercentage: number;
|
||||||
|
budgetLimit: number;
|
||||||
|
seatStubMessages?: Record<string, unknown[]>;
|
||||||
|
orchestrationMode?: "recommend" | "chain";
|
||||||
|
chain?: { id: string; title: string } | null;
|
||||||
|
step3?: DraftStep3Snapshot | null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`DraftStep2Snapshot` 保留现有字段作为当前激活 run 的镜像,同时新增 `runs` 和 `activeRunId`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export interface DraftStep2Snapshot {
|
||||||
|
activeRunId?: string;
|
||||||
|
runs?: Step2RunSnapshot[];
|
||||||
|
|
||||||
|
selectedAgents?: Array<{ agent_id: string; name: string }>;
|
||||||
|
threadIds: ThreadIdMap | null;
|
||||||
|
coordinatorName: string | null;
|
||||||
|
step2RoundtableDialogues: unknown[];
|
||||||
|
lastLeaderContent: string;
|
||||||
|
hasConsensus: boolean;
|
||||||
|
consensusPercentage: number;
|
||||||
|
budgetLimit: number;
|
||||||
|
seatStubMessages?: Record<string, unknown[]>;
|
||||||
|
orchestrationMode?: "recommend" | "chain";
|
||||||
|
chain?: { id: string; title: string } | null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
这样做的好处:
|
||||||
|
|
||||||
|
- 老代码仍然可以从 `draft.step2.step2RoundtableDialogues` 读取当前结果。
|
||||||
|
- 新 UI 可以从 `draft.step2.runs` 展示第一次、第二次、第三次生成结果。
|
||||||
|
- 老草稿没有 `runs` 时,可以在 hydrate 时把原来的 `step2` 包装成一条默认 run。
|
||||||
|
- 暂时不需要改数据库表结构,因为 `step2` 本身就是 JSON 快照。
|
||||||
|
|
||||||
|
## 行为设计
|
||||||
|
|
||||||
|
### 1. 历史记录加载
|
||||||
|
|
||||||
|
用户点击历史记录加载草稿时:
|
||||||
|
|
||||||
|
1. 拉取完整草稿。
|
||||||
|
2. 如果 `draft.step2.runs` 存在,使用 `activeRunId` 找到当前结果线。
|
||||||
|
3. 如果 `draft.step2.runs` 不存在,但旧字段里有 `step2RoundtableDialogues`,自动包装成一条 run:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
id: "legacy-run",
|
||||||
|
title: "第一次生成结果",
|
||||||
|
createdAt: draft.updatedAt,
|
||||||
|
source: "initial",
|
||||||
|
...draft.step2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. hydrate 当前 active run 到 Step2 runtime。
|
||||||
|
5. 左下角展示 run 列表。
|
||||||
|
|
||||||
|
### 2. 再次点击智能体推荐进入研讨
|
||||||
|
|
||||||
|
用户在已有历史草稿中再次点击「智能体推荐」并确认进入研讨时:
|
||||||
|
|
||||||
|
1. 先把当前页面里的 Step2 状态保存为当前 active run。
|
||||||
|
2. 创建一条新的 run:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
title: `第 ${runs.length + 1} 次生成结果`,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
source: result.mode,
|
||||||
|
selectedAgents: normalizedAgents,
|
||||||
|
threadIds: null,
|
||||||
|
coordinatorName: null,
|
||||||
|
step2RoundtableDialogues: [],
|
||||||
|
lastLeaderContent: "",
|
||||||
|
hasConsensus: false,
|
||||||
|
consensusPercentage: 0,
|
||||||
|
budgetLimit: DEFAULT_BUDGET,
|
||||||
|
seatStubMessages: {},
|
||||||
|
orchestrationMode: result.mode,
|
||||||
|
chain: result.mode === "chain" ? result.chain ?? null : null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 将 `activeRunId` 切到新 run。
|
||||||
|
4. 清空 Step2 runtime。
|
||||||
|
5. 设置新选中的 agents / mode / chain。
|
||||||
|
6. `resetInitGate()`,进入 Step2 后重新创建一组独立 thread。
|
||||||
|
7. 自动保存草稿。
|
||||||
|
|
||||||
|
关键点:第二次 run 必须使用新的 `threadIds`,不能沿用第一次 run 的 `threadIds`,否则后端 thread 历史会混在一起。
|
||||||
|
|
||||||
|
### 3. 左下角结果列表
|
||||||
|
|
||||||
|
左下角建议展示一个「生成结果」区域:
|
||||||
|
|
||||||
|
- 第一次生成结果
|
||||||
|
- 第二次生成结果
|
||||||
|
- 第三次生成结果
|
||||||
|
|
||||||
|
每条展示:
|
||||||
|
|
||||||
|
- 标题
|
||||||
|
- 创建时间
|
||||||
|
- 状态:研讨中 / 已达成共识 / 未完成 / 已生成报告
|
||||||
|
- 使用模式:智能体推荐 / 业务链条
|
||||||
|
|
||||||
|
点击某条结果时:
|
||||||
|
|
||||||
|
1. 保存当前 active run。
|
||||||
|
2. 切换 `activeRunId`。
|
||||||
|
3. hydrate 被点击的 run。
|
||||||
|
4. 中间 Step2 对话区显示该 run 的研讨气泡。
|
||||||
|
5. 如果该 run 已有 `step3`,进入 Step3 时展示对应报告。
|
||||||
|
|
||||||
|
### 4. Step3 结果归属
|
||||||
|
|
||||||
|
目前 `draft.step3` 是草稿级别的一份报告。如果只保留这一份,第二次结果生成报告后仍会覆盖第一次报告。
|
||||||
|
|
||||||
|
建议:
|
||||||
|
|
||||||
|
- `draft.step3` 继续作为当前 active run 的镜像,兼容现有 Step3 页面。
|
||||||
|
- 每条 `Step2RunSnapshot.step3` 保存自己的报告。
|
||||||
|
- `onReportSaved` 时同时写入当前 active run 的 `step3`。
|
||||||
|
|
||||||
|
这样用户切换到第一次生成结果时,可以看到第一次的 Step3 报告;切换到第二次生成结果时,可以看到第二次的 Step3 报告。
|
||||||
|
|
||||||
|
## 建议改动点
|
||||||
|
|
||||||
|
### 1. `api/drafts.ts`
|
||||||
|
|
||||||
|
扩展类型:
|
||||||
|
|
||||||
|
- 新增 `Step2RunSnapshot`。
|
||||||
|
- `DraftStep2Snapshot` 增加 `activeRunId?: string` 和 `runs?: Step2RunSnapshot[]`。
|
||||||
|
|
||||||
|
同时保留旧字段,避免影响现有保存、加载和 Step3。
|
||||||
|
|
||||||
|
### 2. `useStep2Orchestration.ts`
|
||||||
|
|
||||||
|
新增或暴露两个能力:
|
||||||
|
|
||||||
|
- `getCurrentRunSnapshot()`:从当前 Step2 runtime 生成一条 run 快照。
|
||||||
|
- `hydrateRunSnapshot(run)`:把某条 run 恢复到 Step2 runtime。
|
||||||
|
|
||||||
|
`hydrateFromDraft` 继续存在,但内部可以优先选择 active run 来 hydrate。
|
||||||
|
|
||||||
|
### 3. `RoundtablePlanningPage.tsx`
|
||||||
|
|
||||||
|
新增页面级状态:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const [step2Runs, setStep2Runs] = useState<Step2RunSnapshot[]>([]);
|
||||||
|
const [activeStep2RunId, setActiveStep2RunId] = useState<string | null>(null);
|
||||||
|
```
|
||||||
|
|
||||||
|
调整几个流程:
|
||||||
|
|
||||||
|
- `getStep2Snapshot` 输出 `runs` 和 `activeRunId`。
|
||||||
|
- `hydrateStep2` 兼容旧草稿并恢复 runs。
|
||||||
|
- `handleConfirmAgents` 在新建研讨前先归档当前 active run,再创建新 run。
|
||||||
|
- `onReportSaved` 把 Step3 报告写回当前 active run。
|
||||||
|
|
||||||
|
### 4. `Step2Panel.tsx`
|
||||||
|
|
||||||
|
新增左下角结果列表展示。建议作为一个独立组件,避免 Step2Panel 继续变大:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Step2RunSwitcher
|
||||||
|
runs={step2Runs}
|
||||||
|
activeRunId={activeStep2RunId}
|
||||||
|
onSelect={handleSelectStep2Run}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
组件职责只做展示和选择,不直接读写 draft。
|
||||||
|
|
||||||
|
### 5. `Step3Panel.tsx`
|
||||||
|
|
||||||
|
传入当前 active run 的报告:
|
||||||
|
|
||||||
|
- 如果当前 run 有 `step3`,展示它。
|
||||||
|
- 如果没有,按现有逻辑生成新报告。
|
||||||
|
- 生成完成后通过 `onReportSaved` 写回 run。
|
||||||
|
|
||||||
|
## 兼容策略
|
||||||
|
|
||||||
|
老草稿没有 `runs` 字段时,不做数据迁移,前端加载时即时包装。
|
||||||
|
|
||||||
|
判断规则:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
function normalizeStep2Runs(step2: DraftStep2Snapshot): {
|
||||||
|
runs: Step2RunSnapshot[];
|
||||||
|
activeRunId: string | null;
|
||||||
|
} {
|
||||||
|
if (step2.runs?.length) {
|
||||||
|
return {
|
||||||
|
runs: step2.runs,
|
||||||
|
activeRunId: step2.activeRunId ?? step2.runs[0].id,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasLegacyContent =
|
||||||
|
step2.step2RoundtableDialogues?.length > 0 ||
|
||||||
|
Boolean(step2.threadIds) ||
|
||||||
|
Boolean(step2.lastLeaderContent);
|
||||||
|
|
||||||
|
if (!hasLegacyContent) {
|
||||||
|
return { runs: [], activeRunId: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const legacyRun: Step2RunSnapshot = {
|
||||||
|
id: "legacy-run",
|
||||||
|
title: "第一次生成结果",
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
source: step2.orchestrationMode ?? "initial",
|
||||||
|
selectedAgents: step2.selectedAgents,
|
||||||
|
threadIds: step2.threadIds,
|
||||||
|
coordinatorName: step2.coordinatorName,
|
||||||
|
step2RoundtableDialogues: step2.step2RoundtableDialogues,
|
||||||
|
lastLeaderContent: step2.lastLeaderContent,
|
||||||
|
hasConsensus: step2.hasConsensus,
|
||||||
|
consensusPercentage: step2.consensusPercentage,
|
||||||
|
budgetLimit: step2.budgetLimit,
|
||||||
|
seatStubMessages: step2.seatStubMessages,
|
||||||
|
orchestrationMode: step2.orchestrationMode,
|
||||||
|
chain: step2.chain,
|
||||||
|
};
|
||||||
|
|
||||||
|
return { runs: [legacyRun], activeRunId: legacyRun.id };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 风险点
|
||||||
|
|
||||||
|
### 1. 自动保存覆盖
|
||||||
|
|
||||||
|
Step2 现在会在每个气泡收尾时自动保存。如果引入多 run,自动保存必须先把当前 runtime 合并回 active run,再写入 `draft.step2.runs`。
|
||||||
|
|
||||||
|
否则会出现 UI 切到第二次结果,但保存时仍更新第一次 run 的情况。
|
||||||
|
|
||||||
|
### 2. threadIds 混用
|
||||||
|
|
||||||
|
每条 run 必须拥有自己的 `threadIds`。新建 run 时要清空 `threadIds` 并让 Step2 重新 init。
|
||||||
|
|
||||||
|
如果复用旧 thread,会导致两次研讨的后端上下文互相污染。
|
||||||
|
|
||||||
|
### 3. Step3 报告覆盖
|
||||||
|
|
||||||
|
如果只保存草稿级 `step3`,多 run 的报告无法分别查看。
|
||||||
|
|
||||||
|
建议把报告写入当前 run,同时保留草稿级 `step3` 作为 active run 镜像。
|
||||||
|
|
||||||
|
### 4. 正在运行中的 run
|
||||||
|
|
||||||
|
如果配合后台任务能力,run 还需要带 job 信息:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
jobId?: string | null;
|
||||||
|
jobStatus?: JobStatus | null;
|
||||||
|
```
|
||||||
|
|
||||||
|
这样左下角可以显示「第二次生成结果正在运行」,并打开派活链路弹窗。
|
||||||
|
|
||||||
|
## 分阶段实现建议
|
||||||
|
|
||||||
|
### P0:纯前端多 run 快照
|
||||||
|
|
||||||
|
目标:先解决“第一次 / 第二次结果分别可查看”。
|
||||||
|
|
||||||
|
- 扩展 `DraftStep2Snapshot` 类型。
|
||||||
|
- 页面维护 `step2Runs` / `activeStep2RunId`。
|
||||||
|
- `handleConfirmAgents` 新建 run。
|
||||||
|
- 左下角展示 run 列表。
|
||||||
|
- 切换 run 能恢复不同 Step2 对话。
|
||||||
|
|
||||||
|
不改后端表结构。
|
||||||
|
|
||||||
|
### P1:Step3 绑定 run
|
||||||
|
|
||||||
|
目标:每次研讨结果对应自己的报告。
|
||||||
|
|
||||||
|
- `Step2RunSnapshot.step3` 保存报告。
|
||||||
|
- `onReportSaved` 写回 active run。
|
||||||
|
- 切换 run 时同步 Step3 显示。
|
||||||
|
|
||||||
|
### P2:后台任务绑定 run
|
||||||
|
|
||||||
|
目标:和后台挂起执行方案打通。
|
||||||
|
|
||||||
|
- run 增加 `jobId` / `jobStatus`。
|
||||||
|
- 历史列表和左下角都能显示某条 run 正在执行。
|
||||||
|
- 点击正在执行的 run 打开派活链路弹窗。
|
||||||
|
|
||||||
|
### P3:后端 run 表
|
||||||
|
|
||||||
|
如果后续一个草稿下 run 数量很多,或者需要服务端按 run 查询、删除、重命名,再考虑新增后端表:
|
||||||
|
|
||||||
|
- `roundtable_runs`
|
||||||
|
- `draft_id`
|
||||||
|
- `run_id`
|
||||||
|
- `title`
|
||||||
|
- `status`
|
||||||
|
- `step2_snapshot`
|
||||||
|
- `step3_snapshot`
|
||||||
|
- `created_at`
|
||||||
|
- `updated_at`
|
||||||
|
|
||||||
|
短期不建议一开始就上表,先用现有 `step2` JSON 快照落地更快。
|
||||||
|
|
||||||
|
## 验收清单
|
||||||
|
|
||||||
|
- 从历史记录加载旧草稿时,左下角出现「第一次生成结果」。
|
||||||
|
- 点击「第一次生成结果」能看到原来的 Step2 研讨气泡。
|
||||||
|
- 在历史草稿中重新点击「智能体推荐」并「进入研讨」后,左下角新增「第二次生成结果」。
|
||||||
|
- 第二次研讨开始时,Step2 对话区为空或只显示新 run 初始化内容。
|
||||||
|
- 第二次 run 使用新的 `threadIds`,不会复用第一次 run 的后端线程。
|
||||||
|
- 切回「第一次生成结果」时,第一次的对话、共识状态、沙箱产物仍可查看。
|
||||||
|
- 切回「第二次生成结果」时,第二次的对话继续显示。
|
||||||
|
- 刷新页面后再次加载该历史草稿,两条结果线都还在。
|
||||||
|
- 如果两次都生成了 Step3 报告,切换不同结果线时能看到各自对应的报告。
|
||||||
@@ -0,0 +1,610 @@
|
|||||||
|
# 圆桌 DAG 编排 + 并行执行显示 —— 分步实现需求文档
|
||||||
|
|
||||||
|
> 目标读者:实现本功能的前端 / 后端工程师。
|
||||||
|
> 本文是**可逐步落地**的需求 + 设计文档,每个 Phase 都能独立交付、独立验收。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 背景与目标
|
||||||
|
|
||||||
|
### 0.1 现状
|
||||||
|
|
||||||
|
Step 2 圆桌目前有两种编排模式(`orchestrationMode`,见 `hooks/useStep2Orchestration.ts`):
|
||||||
|
|
||||||
|
- **`free`(自由模式)**:总控(leader)自由决定派活给谁,`runOrchestration` 循环驱动。
|
||||||
|
- **`chain`(线性链条)**:用户把席位排成一条**线性**链 `A → B → C`,`runChainOrchestration` 按顺序逐个派活,最后总控收口。链路用 `DispatchChainModal.tsx` 的**横向流程图**展示(总控 → 席位1 → 席位2 → … → 共识 → 报告)。
|
||||||
|
|
||||||
|
链条数据现在只是一个**有序数组** `selectedAgents`(线性),节点状态类型见 `lib/job-types.ts`(`ChainNodeState = pending | active | done`)。
|
||||||
|
|
||||||
|
### 0.2 目标(本次新增)
|
||||||
|
|
||||||
|
1. **DAG 编排**:用户可视化指定**智能体之间的直接依赖关系**——有的串行(`A → B → C`),有的并行(`A B C` 同时跑)。编排结果是一张**流程图(DAG)**。
|
||||||
|
2. **并行执行**:DAG 里同一层(互不依赖)的智能体**并行**跑,墙钟时间从「串行求和」降到「并行取最慢」。
|
||||||
|
3. **并行禁止写文件**:并行的智能体**禁用文件写入 / 沙箱命令**,避免它们同时打开沙箱互相打架。产物以消息正文交付;落文件留给串行 / 收口阶段。
|
||||||
|
4. **并行高性能显示**:并行时收起左侧、顶部头像条切换、主区同时显示 2 个智能体的消息流,其余**只接流不渲染**,避免页面卡死。
|
||||||
|
|
||||||
|
### 0.3 设计总原则
|
||||||
|
|
||||||
|
- **复用** 现有 special run / leader run / rollback 抢占 / 轻量交付状态接口(`GET /threads/{id}/last-ai-message`),不另起炉灶。
|
||||||
|
- **线性链是 DAG 的特例**:`chain` 模式可平滑迁移成"每层 1 个节点"的 DAG,老数据不破坏。
|
||||||
|
- **分层(Stage)优先于自由连线**:编辑交互首选「分层」模型(每个 stage 放若干并行席位,stage 间串行),实现成本低、覆盖 95% 的"串 / 并"诉求;自由连线画布作为后续可选增强(见 §2.3)。
|
||||||
|
|
||||||
|
### 0.4 已确认的设计决策(✅ 本期按这些实现)
|
||||||
|
|
||||||
|
> 以下三项已与需求方确认锁定,实现时直接按此,不再二选一。
|
||||||
|
|
||||||
|
1. **✅ 编排模型 = 分层 Stage**:本期只做分层(每个 stage 放若干并行席位、stage 间串行)。**自由连线画布本期不做**,仅在数据模型层预留(§1.2)以免将来返工。
|
||||||
|
2. **✅ 并行跳过 leader、前端直派**:DAG 由用户显式指定,执行时前端**直接**对 stage 内席位发起 special run,**不**每个 stage 再跑一轮总控派活;只在最后 `finalSynthesis` 跑一轮 leader 综合(即 §3.2 的方案 B)。
|
||||||
|
3. **✅ 主区固定 2 列,窄屏降 1 列**:并行时主区最多并排显示 2 个被选中智能体的消息流;窄屏(断点见 §5.3)降为 1 列 + 头像条横向滚动。不做 3+ 列。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 数据模型
|
||||||
|
|
||||||
|
### 1.1 DAG 的「分层」表示(推荐,主模型)
|
||||||
|
|
||||||
|
把 DAG 表示成**有序的 stage 列表**,每个 stage 内的席位并行、stage 之间串行:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// lib/dag-types.ts (新建)
|
||||||
|
|
||||||
|
/** 一个并行批次:stage 内所有席位并行执行。 */
|
||||||
|
export interface OrchestrationStage {
|
||||||
|
/** stage 稳定 id(拖拽重排 / diff 用)。 */
|
||||||
|
id: string;
|
||||||
|
/** 本 stage 并行执行的席位(agent_id 列表)。1 个 = 退化为串行节点。 */
|
||||||
|
agentIds: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 用户编排出的执行计划。stages 顺序即串行顺序。 */
|
||||||
|
export interface OrchestrationPlan {
|
||||||
|
/** 编排模式标识,持久化进 step2。 */
|
||||||
|
mode: "dag";
|
||||||
|
/** 串行执行的批次;每批内并行。 */
|
||||||
|
stages: OrchestrationStage[];
|
||||||
|
/** 收口:是否在所有 stage 完成后由总控综合(默认 true)。 */
|
||||||
|
finalSynthesis: boolean;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **串行** `A → B → C` = `stages: [{agentIds:[A]}, {agentIds:[B]}, {agentIds:[C]}]`。
|
||||||
|
- **并行** `A B C` = `stages: [{agentIds:[A,B,C]}]`。
|
||||||
|
- **混合** `A →(B C)→ D` = `stages: [{[A]}, {[B,C]}, {[D]}]`。
|
||||||
|
|
||||||
|
> 为什么用分层而不是「邻接表 / 边」:执行调度本就是「拓扑分批」,分层就是分批的结果,前端不必再做拓扑排序,也天然避免环;编辑器交互更直观(拖卡片进 stage)。真正的自由连线 DAG 见 §2.3(可选)。
|
||||||
|
|
||||||
|
### 1.2 通用 DAG 表示(§2.3 自由连线时才需要)
|
||||||
|
|
||||||
|
若将来做自由连线画布,再引入边表示,并在执行前做一次**拓扑排序 → 分层**,落回 §1.1 的 stages 结构给调度器用:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export interface DagEdge { from: string; to: string } // from 完成后才能跑 to
|
||||||
|
export interface DagGraph { nodes: string[]; edges: DagEdge[] }
|
||||||
|
// 执行前:toposortToStages(graph) -> OrchestrationStage[]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.3 持久化
|
||||||
|
|
||||||
|
- 复用 `roundtable_drafts.step2` JSON(见后端 `app.gateway.routers` roundtable-drafts + `hooks/useStep2Orchestration.ts` 里对 `step2` 的读写)。
|
||||||
|
- 在 `step2` 增加字段:`orchestrationPlan: OrchestrationPlan | null`。
|
||||||
|
- `orchestrationMode` 扩展为 `"free" | "chain" | "dag"`;`chain` 旧数据读取时即时转换为单节点-stage 的 `dag`(兼容层,不改老 draft)。
|
||||||
|
|
||||||
|
### 1.4 校验(纯函数,可单测)
|
||||||
|
|
||||||
|
`lib/dag-types.ts` 内提供:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
validatePlan(plan: OrchestrationPlan, selectedAgentIds: string[]): {
|
||||||
|
ok: boolean;
|
||||||
|
errors: string[]; // 面向用户的中文提示
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
校验项:
|
||||||
|
- 每个 `agentId` 必须在本次选定席位 `selectedAgents` 内(防止编排了不存在的席位 → 复用后端 `_partition_dispatch` 同思路的"必须在 roster 内")。
|
||||||
|
- 不允许空 stage;不允许同一席位出现在多个 stage(一个席位只跑一次)。
|
||||||
|
- 至少 1 个 stage。
|
||||||
|
- (可选)单 stage 并行度上限提示(如 > 6 并行给 warning:远程模型并发 + 沙箱压力)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 编排编辑器(流程图构建)交互
|
||||||
|
|
||||||
|
### 2.1 入口与整体布局
|
||||||
|
|
||||||
|
- 在 Step 2 顶部模式切换里新增 **「依赖编排」**(`dag`)模式(与现有 自由 / 链条 并列)。
|
||||||
|
- 选择 `dag` 后弹出 / 进入**编排编辑器**(复用 Dialog 大弹窗,参考 `DispatchChainModal` 的尺寸 `w-[94vw] max-w-[1240px]`)。
|
||||||
|
|
||||||
|
### 2.2 推荐交互:分层(Stage)编辑器(Phase 2 实现)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌ 依赖编排 ───────────────────────────────────────── [校验✓] [保存] ┐
|
||||||
|
│ 可选席位(点/拖加入某个 stage) │
|
||||||
|
│ [情报收集] [环境评估] [方案设计] [风险审查] [执行规划] [前端实现] │
|
||||||
|
│ ─────────────────────────────────────────────────────────────── │
|
||||||
|
│ Stage 1(并行) Stage 2(并行) Stage 3 │
|
||||||
|
│ ┌──────────┐ ─────▶ ┌──────────┐ ┌────────┐ ─▶ ┌──────────┐ │
|
||||||
|
│ │ 情报收集 │ │ 方案设计 │ │风险审查│ │ 执行规划 │ │
|
||||||
|
│ └──────────┘ └──────────┘ └────────┘ └──────────┘ │
|
||||||
|
│ [+ 拖席位到此] [+] [+] │
|
||||||
|
│ [+ 新建 Stage(串在最后)] │
|
||||||
|
│ ─────────────────────────────────────────────────────────────── │
|
||||||
|
│ 说明:同一 Stage 内的席位会**并行**执行;Stage 之间**串行** │
|
||||||
|
│ (后一个 Stage 能看到前面所有 Stage 的交付摘要)。 │
|
||||||
|
└───────────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
交互要点:
|
||||||
|
- **加入 stage**:从顶部可选席位**拖拽**到某个 stage,或点席位 →「加入 Stage N」。
|
||||||
|
- **移动 / 重排**:席位可在 stage 间拖动;stage 可整体左右拖动重排(改串行顺序)。
|
||||||
|
- **删除**:席位 / 空 stage 可删。
|
||||||
|
- **并行度提示**:stage 内 ≥2 席位即标「并行」徽标;过多给 warning。
|
||||||
|
- **实时校验**:`validatePlan` 实时跑,错误在顶部红条提示,「保存」在校验通过前禁用。
|
||||||
|
- **预览流程图**:编辑区下方实时渲染只读流程图缩略(复用 §7 的 DAG 流程图组件)。
|
||||||
|
|
||||||
|
> 拖拽可用现成轻量方案(HTML5 DnD 或 `@dnd-kit`,看项目是否已有依赖;没有就先用「点选 + 加入/移出按钮」的无拖拽版,Phase 2 先上无拖拽、Phase 2.5 再加拖拽)。
|
||||||
|
|
||||||
|
### 2.3 可选增强:自由连线画布(后续,非本期必须)
|
||||||
|
|
||||||
|
- 节点自由摆放 + 拉线建边 → `DagGraph`(§1.2)。
|
||||||
|
- 实现成本高(画布 / 连线 / 命中检测 / 自动布局),且分层模型已覆盖绝大多数诉求。**本期不做**,仅在数据模型上预留 §1.2,避免将来返工。
|
||||||
|
|
||||||
|
### 2.4 验收(Phase 2)
|
||||||
|
|
||||||
|
- 能拖 / 点把席位分配到多个 stage,保存进 `step2.orchestrationPlan`。
|
||||||
|
- 刷新 / 重进 draft 能恢复编排。
|
||||||
|
- 非法编排(空 stage / 席位重复 / 席位不在 roster)有明确中文提示且无法保存。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 执行调度(前端编排循环 + 后端复用)
|
||||||
|
|
||||||
|
### 3.1 新增 `runDagOrchestration`(`useStep2Orchestration.ts`)
|
||||||
|
|
||||||
|
与现有 `runOrchestration` / `runChainOrchestration` 并列,逻辑:
|
||||||
|
|
||||||
|
```
|
||||||
|
for (stageIndex, stage of plan.stages):
|
||||||
|
if isStale() break // 复用现有 epoch 抢占(人工干预/暂停)
|
||||||
|
// 1) 总控按本 stage 的席位并行派活(一轮 leader,dispatched = stage.agentIds)
|
||||||
|
// —— 或跳过 leader,前端直接对 stage 内每个席位发起 special run(见 3.2)
|
||||||
|
// 2) 并行跑 stage 内所有席位
|
||||||
|
await Promise.all(stage.agentIds.map(seat =>
|
||||||
|
streamMultiAgent({ agentType:"special", agentName:seat,
|
||||||
|
newMessage: buildStageTask(seat, plan, stageIndex),
|
||||||
|
parallelNoFile: stage.agentIds.length > 1, // §4
|
||||||
|
... })))
|
||||||
|
// 3) 等本 stage 全部 ✅(Promise.all 天然 barrier)再进入下一 stage
|
||||||
|
// 4) finalSynthesis:最后一轮 leader(synthesisMode=true)综合所有 stage 交付
|
||||||
|
```
|
||||||
|
|
||||||
|
要点:
|
||||||
|
- **批内并行**:`Promise.all`(不是现在的 `for await` 串行)。
|
||||||
|
- **批间串行**:`Promise.all` 即 barrier,自动等齐。
|
||||||
|
- **依赖可见性**:进入 stage N 的席位时,把**前面所有 stage 已交付席位的摘要**拼进它的 `newMessage`(复用 §交付状态:网关 `_collect_delivery_status` / `GET last-ai-message?max_chars=N`,前端也可在 stage 边界拉一次摘要拼进 task)。这样 `(B C)` 能看到 `A` 的产出。
|
||||||
|
- **抢占 / 干预 / 暂停**:每个 stage 边界检查 `isStale()`(epoch),与现有自由 / 链条模式一致。
|
||||||
|
- **rollback**:special run 已统一 `multitask_strategy=rollback`,并行多席位各自不同 thread,互不冲突。
|
||||||
|
|
||||||
|
### 3.2 是否每 stage 都走 leader? — ✅ 已定:前端直派(方案 B)
|
||||||
|
|
||||||
|
**本期采用方案 B**:DAG 由用户**显式**指定,不需要 leader 再"决定派给谁"。前端**直接**对 stage 内每个席位发起 special run,省掉每 stage 的 leader LLM 往返(更快、更可控);只在所有 stage 完成后、`finalSynthesis` 为真时跑**一轮** leader(`synthesisMode=true`)综合所有交付。
|
||||||
|
|
||||||
|
> (备选方案 A:每 stage 跑一轮 leader 派活——更贴现有架构但每 stage 多一次 leader LLM、更慢。**本期不采用**,留档备查。)
|
||||||
|
|
||||||
|
### 3.3 后端改动
|
||||||
|
|
||||||
|
- **基本不需要新接口**:special run(`POST /api/multi-agent/run/stream` agent_type=special)、leader run、轻量交付读(`GET /threads/{id}/last-ai-message`)、轻量追加(`POST /threads/{id}/messages/append`)都已就绪。
|
||||||
|
- 仅需 §4 的「并行禁写文件」run policy 开关。
|
||||||
|
|
||||||
|
### 3.4 验收(Phase 3)
|
||||||
|
|
||||||
|
- `(B C)` 两席位**同时**出现在执行(后端日志两条 special run 时间重叠;前端两个流并行增长)。
|
||||||
|
- stage 间严格串行(stage 2 不早于 stage 1 全部完成)。
|
||||||
|
- stage N 席位的输入里能看到 stage <N 的交付摘要。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 并行时禁止写文件(防沙箱打架)
|
||||||
|
|
||||||
|
### 4.1 后端 run policy
|
||||||
|
|
||||||
|
`app/gateway/roundtable_run_policy.py` 现有角色:`leader` / `seat` / `report`。新增一个角色或开关:
|
||||||
|
|
||||||
|
- 方案:给 `seat` 增加一个「并行变体」`seat_parallel`,其 `excluded_tools` 在 `seat` 基础上**再禁** `write_file` / `bash` / `str_replace` / `present_files`(与 `report` 角色禁写的思路一致)。
|
||||||
|
- `_special_run`(`multi_agent.py`)按请求里的一个新 flag(如 `no_file: true`)选择 `seat_parallel` policy。
|
||||||
|
|
||||||
|
### 4.2 前端传参
|
||||||
|
|
||||||
|
- `streamMultiAgent` 请求体新增 `parallel_no_file?: boolean`(或复用 `no_file`)。
|
||||||
|
- `runDagOrchestration` 在 `stage.agentIds.length > 1`(真并行)时置 `true`;单节点 stage(实际串行)不限制,可正常写文件。
|
||||||
|
|
||||||
|
### 4.3 产物归属
|
||||||
|
|
||||||
|
- 并行席位的产物 = **消息正文**(被 `_collect_delivery_status` / 综合块读取)。
|
||||||
|
- 需要落文件 / 画图的(如 Step3 报告、`roundtable-report`)放在**串行的收口阶段**单独跑,不在并行批次里。
|
||||||
|
|
||||||
|
### 4.4 验收(Phase 4)
|
||||||
|
|
||||||
|
- 并行 stage 的席位 run 日志显示 `Excluded ... ['write_file','bash','str_replace','present_files', ...]`。
|
||||||
|
- 并行期间不再出现多个席位抢同一沙箱 / 写文件冲突。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 并行执行的前端显示
|
||||||
|
|
||||||
|
### 5.1 布局总览(并行进行时)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌ 多智能体圆桌会商中心 ─────────────────────────────────────────────┐
|
||||||
|
│ [头像条:进行中的并行智能体] [模型选择 ▾] [暂停会商] │
|
||||||
|
│ (情报)● (方案)● (风险)● (执行) … │
|
||||||
|
│ ↑选中 ↑选中 loading hidden │
|
||||||
|
│ ───────────────────────────────────────────────────────────────── │
|
||||||
|
│ ┌─ 方案设计(选中)──────────┐ ┌─ 风险审查(选中)──────────┐ │
|
||||||
|
│ │ 一、整体架构…(流式渲染) │ │ 1. 合规风险 IDFA/OAID… │ │
|
||||||
|
│ │ … │ │ … │ │
|
||||||
|
│ └────────────────────────────┘ └────────────────────────────┘ │
|
||||||
|
└───────────────────────────────────────────────────────────────────┘
|
||||||
|
(左侧"参与角色"栏在并行时整体收起,腾出横向空间放两列消息)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 关键交互(与需求逐条对齐)
|
||||||
|
|
||||||
|
1. **收起左侧**:并行执行时把左侧「参与角色 / 人工参与」栏整体折叠(一个 `isParallelRunning` 状态控制;非并行恢复)。
|
||||||
|
2. **头像条**:位置在**消息列表上方、模型选择器左侧**。展示**当前并行批次的所有进行中智能体头像**:
|
||||||
|
- **进行中** → 头像加 loading 动画(复用 `DispatchChainModal` 的 `animate-ping` 光环 + `Loader2Icon animate-spin` 角标)。
|
||||||
|
- **已完成** → 打勾(复用现有 `CheckIcon` 角标)。
|
||||||
|
- **选中** → 高亮描边(当前正在主区显示的那 2 个)。
|
||||||
|
3. **主区同时显示 2 个**:被选中的 2 个智能体的消息列表**并排两列**渲染。
|
||||||
|
4. **多于 2 个先隐藏**:未选中的智能体**不渲染 DOM**(见 §6 性能)。
|
||||||
|
5. **点头像切换**:点击未选中的头像 → 把它设为选中之一(替换当前 2 个里的一个,或按"最近点击保留 2 个"的 LRU 策略);被换下的智能体**停止渲染但继续接流**。
|
||||||
|
|
||||||
|
### 5.3 选中策略 — ✅ 固定 2 列,窄屏降 1 列
|
||||||
|
|
||||||
|
- 维护 `selectedParallelSeats: string[]`,**最多 2**(固定 2 列)。**不做 3+ 列**。
|
||||||
|
- **响应式**:宽屏 2 列并排;窄屏(建议断点 `< 1024px` / `lg`)降为**1 列**,头像条横向滚动切换;此时 `selectedParallelSeats` 仍可存 2 个,但主区只渲染当前 1 个(点头像切换哪个在前)。
|
||||||
|
- 默认选中本批次**最先开始**的(宽屏 2 个 / 窄屏 1 个)。
|
||||||
|
- 点头像:若已选中则取消;未选中则加入(超过上限时按 LRU 踢掉最早选中的)。被换下的席位**停止渲染但继续接流**(§6)。
|
||||||
|
|
||||||
|
### 5.4 验收(Phase 5)
|
||||||
|
|
||||||
|
- 并行时左侧收起、出现头像条、主区两列。
|
||||||
|
- 进行中头像有 loading;完成打勾;选中有高亮。
|
||||||
|
- 点头像能切换主区显示的智能体,且切换是**即时**的(数据已在内存,见 §6)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 流式高性能策略(避免页面卡死)
|
||||||
|
|
||||||
|
> 核心矛盾:N 个并行席位同时高频 `onTextDelta`,若都 setState + Markdown 渲染会卡死。
|
||||||
|
|
||||||
|
### 6.1 全接收、惰性渲染
|
||||||
|
|
||||||
|
- **所有**并行 run 的流都正常订阅(不丢数据):每个席位的增量文本**累积进 store / ref**(`Map<agentId, { text, status, charCount }>`)。
|
||||||
|
- **只有被选中(主区显示)的席位**才把累积文本挂到 DOM 渲染(Markdown)。
|
||||||
|
- **未选中**席位:只更新内存 + 头像条上的轻量进度(字数 / loading),**不挂载消息 DOM**。
|
||||||
|
- 切换选中时:把该席位已累积的全文一次性渲染 + 继续接增量。
|
||||||
|
|
||||||
|
### 6.2 渲染节流
|
||||||
|
|
||||||
|
- 选中席位的流式渲染**节流/合帧**:用 `requestAnimationFrame` 或 ~50–100ms 批量 flush 累积的 token,而不是每个 token 一次 setState。
|
||||||
|
- Markdown 渲染对"流式中"可降级(纯文本 / 轻量渲染),**完成后**再做完整 Markdown(现有 `MessageBubble` 的 `streaming` 标志可复用:streaming 时简渲、done 后全渲)。
|
||||||
|
|
||||||
|
### 6.3 头像条进度
|
||||||
|
|
||||||
|
- 头像条只显示**廉价**信息:loading 动画 + 可选字数(`charCount`,从内存 Map 取,节流更新,例如每 500ms 刷一次)。不触发消息体渲染。
|
||||||
|
|
||||||
|
### 6.4 数据流(建议结构)
|
||||||
|
|
||||||
|
```
|
||||||
|
streamMultiAgent(seat).onTextDelta(text) →
|
||||||
|
parallelStore.append(seatId, text) // 纯内存累积,O(1)
|
||||||
|
if seatId ∈ selectedParallelSeats: // 仅选中的进 React state(节流)
|
||||||
|
scheduleFlush(seatId) // rAF / 节流 setState
|
||||||
|
else:
|
||||||
|
bumpCharCount(seatId) // 仅更新头像条进度(节流)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.5 验收(Phase 6)
|
||||||
|
|
||||||
|
- 6+ 席位并行时页面不卡(输入 / 滚动 / 切换流畅)。
|
||||||
|
- 切到一个之前隐藏的席位,能立刻看到它**到目前为止的全部**输出(证明流没丢、只是没渲染)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 流程图执行态可视化(DAG 版)
|
||||||
|
|
||||||
|
- 把现有 `DispatchChainModal.tsx`(横向**线性**流程图)扩展 / 复刻成 **DAG 流程图**:
|
||||||
|
- 按 stage 分**列**,stage 内席位**纵向并列**,stage 间用连接线。
|
||||||
|
- 节点状态复用 `ChainNodeState`(pending / active / done)+ 现有动画(`animate-ping` / `Loader2Icon` / `CheckIcon`)。
|
||||||
|
- 末尾接 `共识 → 结果绘制` 里程碑(沿用现有)。
|
||||||
|
- 用途:编辑器里的只读预览(§2.2 底部)+ 执行时的总览(可选小窗 / 顶部缩略)。
|
||||||
|
|
||||||
|
```
|
||||||
|
总控 ─▶ ┌ Stage1 ┐ ─▶ ┌ Stage2 ┐ ─▶ ┌ Stage3 ┐ ─▶ 🤝共识 ─▶ 📊报告
|
||||||
|
│ 情报● │ │ 方案✓ │ │ 执行○ │
|
||||||
|
└────────┘ │ 风险● │ └────────┘
|
||||||
|
└────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.1 验收(Phase 7)
|
||||||
|
|
||||||
|
- 编辑器底部 / 执行时能看到 DAG 流程图,节点状态随执行实时更新(active/done)。
|
||||||
|
|
||||||
|
### 7.2 实施结论(2026-06-07,✅ 已完成)
|
||||||
|
|
||||||
|
- **新组件** `components/DagFlowChart.tsx`:纯展示组件,复刻 `DispatchChainModal` 的节点 / 连线 / 里程碑视觉(`animate-ping` 光环 + `Loader2Icon` 转圈 + `CheckIcon` 打勾 + `rt-chain-connector` 连线动画),但按 **stage 分列**:总控 ─▶ ┌Stage1┐ ─▶ ┌Stage2┐ ─▶ 🤝共识 ─▶ 📊结果绘制,stage 内席位**纵向并列**。`compact` 紧凑模式给缩略图用。所有状态由 props 传入(`stages` / `resolveSeat` / `seatStates` / `coordinatorState` / `consensusState` / `reportState`);不传 `seatStates` → 全 pending(只读预览)。`aggregateStageState` 把 stage 内席位聚合成列状态(任一 active→active、全 done→done)驱动 stage 间连线。
|
||||||
|
- **编辑器只读预览**(§2.2 底部):`BusinessChainEditorPage` 底部加「编排预览」section,把 `stageGroups`(去空 stage) 映射成 `DagFlowChart` 的 stages + `resolvePreviewSeat`(席位名/配色),`compact`、全 pending、随编辑实时变。
|
||||||
|
- **执行态总览**(Step 2 顶部缩略):`useStep2Orchestration` 新增 `dagNodeStates: Record<agentId, ChainNodeState>`,`runDagOrchestration` 跨 stage 维护(进入 stage→该批 active、席位终态→done、`resetStep2State` 清空);经 `RoundtablePlanningPage` 把 `orchestrationMode/orchestrationPlan/dagNodeStates` 传到 `Step2Panel`,dag 模式下会话区顶部 `compact` 渲染 DagFlowChart。总控/共识里程碑状态由 `Step2Panel` 从节点状态 + `isOrchestrating`/`hasConsensus` 派生(中转轮时无席位 active + isOrchestrating → 总控 active)。
|
||||||
|
- 改动文件:`components/DagFlowChart.tsx`(新)、`pages/BusinessChainEditorPage.tsx`、`hooks/useStep2Orchestration.ts`、`components/Step2Panel.tsx`、`pages/RoundtablePlanningPage.tsx`。typecheck 零新增(基线 65)。
|
||||||
|
- **下次实地验收**:①编辑器底部随分层编辑实时画出流程图;②Step2 dag 模式顶部出现缩略流程图,跑起来后当前 stage 列点亮(active 转圈)、完成打勾、中转时总控亮、最后共识亮。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 分步实现计划(每步可独立交付 + 验收)
|
||||||
|
|
||||||
|
| Phase | 内容 | 主要文件 | 依赖 | 可独立验收 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| **1** | DAG 数据模型 + 校验 + 持久化字段 | `lib/dag-types.ts`(新)、draft step2 读写 | — | 纯函数单测:`validatePlan` / `chain→dag` 兼容转换 |
|
||||||
|
| **2** | 分层编排编辑器(先无拖拽:点选加入/移出) | `components/DagPlanEditor.tsx`(新)、Step2 模式切换 | P1 | 能编排并保存/恢复,非法编排有提示 |
|
||||||
|
| **2.5** | 编辑器拖拽 | 同上 + `@dnd-kit`(若引入) | P2 | 拖拽分配/重排 |
|
||||||
|
| **3** | `runDagOrchestration`:批内并行 + 批间串行 + 依赖摘要注入 | `hooks/useStep2Orchestration.ts`、`api/multi-agent.ts` | P1 | 后端日志并行 special run 时间重叠;stage 严格串行 |
|
||||||
|
| **4** | 并行禁写文件 run policy | `roundtable_run_policy.py`、`multi_agent.py`、`api/multi-agent.ts` | P3 | 并行 run 的 excluded_tools 含 write_file/bash/... |
|
||||||
|
| **5** | 并行显示骨架:收起左侧 + 头像条 + 两列 + 选中切换 | `components/Step2Panel.tsx`、`components/ParallelSeatStrip.tsx`(新) | P3 | 见 §5.4 |
|
||||||
|
| **6** | 流式高性能:全接收 / 惰性渲染 / 节流 | `hooks/useStep2Orchestration.ts`(parallelStore)、`Step2Panel` | P5 | 见 §6.5(6+ 并行不卡) |
|
||||||
|
| **7** | DAG 流程图执行态可视化 | `components/DagFlowChart.tsx`(复刻自 `DispatchChainModal`) | P2、P3 | 见 §7.1 |
|
||||||
|
| **8** | 边界 / 异常 | 各处 | 全部 | 见 §9 |
|
||||||
|
|
||||||
|
> 落地顺序建议:**P1 → P3 → P4 → P5 → P6**(先把"能并行跑 + 能看 + 不卡"打通),**P2 编辑器**可与 P3 并行开发(先用一份 hardcode/简单 UI 的 plan 驱动 P3 联调),**P7 / P2.5 / 2.3** 作为增强后置。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 边界与异常(Phase 8)
|
||||||
|
|
||||||
|
- **某并行节点失败 / 超时**:单个席位失败不拖垮整 stage;标该节点 error,stage 其余 ✅ 仍推进;收口时把"X 失败"如实告知总控(复用交付状态 ⬜ + 失败标记)。
|
||||||
|
- **依赖未满足**:调度器保证 stage 串行,理论不会发生;防御性校验 stage N 启动前 stage <N 必须全部终态(done/failed)。
|
||||||
|
- **人工干预 / 暂停 / 恢复**:在 stage 边界检查 `isStale()`(epoch);干预指令插入后,从"下一个未开始的 stage"继续(已完成 stage 不重跑)。
|
||||||
|
- **并行禁写文件 vs 席位本想写文件**:在席位 SOUL / 派活提示里说明"本轮为并行研讨,产出请直接写在回复正文,不要写文件",降低模型困惑。
|
||||||
|
- **窄屏**:主区两列降为一列 + 头像条横向滚动。
|
||||||
|
- **单 stage 全并行(一次性 N 个)**:给并行度 warning(远程模型并发限流 / 成本)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 与现有代码的衔接点速查
|
||||||
|
|
||||||
|
- 编排循环:`hooks/useStep2Orchestration.ts`(`runOrchestration` / `runChainOrchestration` 旁新增 `runDagOrchestration`;复用 `isStale()` epoch、`abortAllInFlight`、`appendStreamingDialogue` / `appendToDialogue`)。
|
||||||
|
- 流式 API:`api/multi-agent.ts`(`streamMultiAgent`,新增 `parallel_no_file` 入参;`onTextDelta(text, messageId)` 已是按席位回调,天然支持并行分流)。
|
||||||
|
- 显示:`components/Step2Panel.tsx`(消息列表 `step2RoundtableDialogues.map`;新增头像条 `ParallelSeatStrip` + 两列容器 + 折叠左侧)。
|
||||||
|
- 流程图:`components/DispatchChainModal.tsx` / `lib/job-types.ts` / `lib/business-chain.ts`(复刻成 DAG 版)。
|
||||||
|
- 常量 / 元数据:`lib/roundtable-constants.ts`(`BUILTIN_AGENT_META` 头像/中文名、`buildAgentNameToRole`)。
|
||||||
|
- 后端 run policy:`app/gateway/roundtable_run_policy.py`(新增 `seat_parallel`)、`app/gateway/routers/multi_agent.py`(`_special_run` 读 `no_file` flag)。
|
||||||
|
- 交付摘要:`GET /api/threads/{id}/last-ai-message?max_chars=N`(依赖注入 stage N 输入用)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 一句话总结
|
||||||
|
|
||||||
|
把「线性链条」升级为「分层 DAG」:**编辑器**用分层 stage(拖卡片)表达串/并;**调度**用 `Promise.all` 批内并行、批间 barrier 串行,依赖摘要在 stage 边界注入;**并行禁写文件**避免沙箱打架;**显示**收起左侧、头像条切换、主区两列、未选中只接流不渲染(rAF 节流)保证不卡。全部建立在现有 special/leader run + 轻量交付接口之上,后端几乎零新接口。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. 已知问题与排查记录(2026-06-06)
|
||||||
|
|
||||||
|
### 12.1 ❗并行席位「步骤条」不显示 —— 根因:`seat_parallel` 工具面禁得过多
|
||||||
|
|
||||||
|
**现象**:并行两列里的席位气泡看不到步骤条(`MessageStepsCard`),而串行席位有。
|
||||||
|
|
||||||
|
**排查结论(已定位,待修)**:
|
||||||
|
|
||||||
|
1. **步骤条只渲染「工具调用」步骤**。`MessageStepsCard` 的 `isToolStep` 只认 `tool_calling:<toolName>` 的步骤进折叠卡;纯阶段步骤(`connecting:` / `streaming:` 这类 reasoning)只渲染成**底部一行小灯泡**,不出大卡(见 `MessageStepsCard.tsx` L80-100)。
|
||||||
|
2. **并行席位几乎调不动任何会产生步骤的工具**。后端 `app/gateway/roundtable_run_policy.py`:
|
||||||
|
- `_SEAT_EXCLUDED = [web_search, ask_clarification, present_files, view_image, agent_orchestration]` —— **注意 `web_search` 对所有席位(串行也)就禁了**(注释「圆桌研讨里联网搜索一律禁用」)。
|
||||||
|
- `_SEAT_PARALLEL_EXCLUDED = _SEAT_EXCLUDED + [write_file, bash, str_replace]`。
|
||||||
|
- 于是并行席位可用工具几乎只剩 `read_file / ls / task / write_todos / memory / hindsight_*`,研究/分析类席位基本一个都不会调 → **没有任何 `tool_calling` 步骤** → 步骤条(大卡)不出现。
|
||||||
|
3. **对比串行为何「有步骤条」**:串行席位(`seat` policy)**能 `write_file`**,会产生 `tool_calling:write_file` 步骤 → 大卡出现。并行被禁了 write_file + 又没有 search,所以一个工具步都没有。
|
||||||
|
|
||||||
|
**用户诉求**:并行时**只禁真正会冲突的写操作**,搜索信息 / 调用技能等**必要操作不要禁**。
|
||||||
|
|
||||||
|
**关键事实(影响方案选择)**:圆桌每个席位是**独立 thread = 独立 sandbox**(后端 per-thread 隔离 `.deer-flow/users/{uid}/threads/{tid}/`)。所以并行席位写文件**在后端并不会互相冲突**;当初 §4「并行禁写文件」的「打架」其实主要是**前端单沙箱预览**(`activeArtifactThreadId` 只能同时显示一个)+ 产物归集到正文的简化考量,并非后端真冲突。→ 这意味着「并行禁写」的必要性比原设想弱,可放宽。
|
||||||
|
|
||||||
|
**✅ 决策:选 A(2026-06-06 已实施)**:把 `seat_parallel` 放宽到**只禁 `write_file / bash / str_replace`**(防前端单沙箱预览串台 + 产物走正文)+ 仍禁 `ask_clarification / present_files / view_image / agent_orchestration`(打断/越权类),但**放开 `web_search` 与技能**(搜索不碰 sandbox;技能靠 `read_file`)。改在 `app/gateway/roundtable_run_policy.py` 的 `_SEAT_PARALLEL_EXCLUDED`(**不再继承** seat 的 web_search 禁用,显式列举),测试 `tests/test_roundtable_run_policy.py` 同步更新(`test_seat_parallel_allows_web_search_and_skills`)。
|
||||||
|
→ 并行席位现在能联网搜索/用技能 → 产生 `tool_calling` 步骤 → 步骤条显示。
|
||||||
|
|
||||||
|
> 备选 B(连写文件也放开,沙箱按 thread 隔离)/ C(重新评估「圆桌串行也一律禁 web_search」)**本期不做**,留档。串行席位目前仍禁搜索(`seat` policy 不变)。
|
||||||
|
|
||||||
|
### 12.2 其它已修(本轮反馈)
|
||||||
|
|
||||||
|
- 最左侧**全局工作区侧栏**并行时收起:改用与「打开沙箱」同一路径 `useSidebarSafe()?.setOpen(false)`(之前只收了圆桌「参与角色」栏 `step2SidebarExpanded`)。并行结束**不自动展开**(与沙箱收起不回弹一致)。
|
||||||
|
- 并行两列改回**完整 Markdown**(撤销 §6.2 流式纯文本降级 `plainWhileStreaming`),与串行同款 `Step2Message`。
|
||||||
|
- 头像条**不再显示字数**(去掉 charCount 徽标 + 字段)。
|
||||||
|
- **致命 bug 已修**:用户干预 / 并行跑完后**不再重跑整张 DAG**。`dagPlanExecutedRef` 闸门 + DAG 各阶段跑完后释放锁 `await runOrchestration(handoff)` 交回总控继续派活/收口;后续干预/恢复一律走 leader 自由派活。
|
||||||
|
- **并行两列宽表溢出已修(2026-06-07)**:模型输出的 Markdown **表格**(如「法律免责条款」表)没有宽度约束 / 横向滚动容器,在并行两列的窄列里会**超出左列、盖到相邻列**。修法:`MessageBubble.sharedMarkdownComponents.table`(+ `markdown-components.tsx`)把 `<table>` 套进 `<div class="max-w-full overflow-x-auto">`——表格保持自然宽度、超出时**列内横向滚动**而非撑破列宽。`min-w-0` 链(grid `minmax(0,1fr)` → 列 `min-w-0` → 气泡 `flex-1 min-w-0`)本就齐全,只差 table 这一层。
|
||||||
|
- **关于「并行席位无步骤条」**:步骤条(`MessageStepsCard` 大卡)只在席位产生 `tool_calling` 步骤时出现(§12.1)。纯分析型席位若本轮**直接写分析正文、没调用任何工具**(web_search 等),就只显示一行「正在输出」思考指示、不出大卡——这是设计使然,非解析失败。要确认是否真调了工具:浏览器 devtools 设 `window.__MULTI_AGENT_DEBUG__=true` 看 `frame# event=messages` 里有无 tool_calls,或查后端 special run 日志。
|
||||||
|
|
||||||
|
### 12.3 ✅需求变更:Stage 间「经总控中转 + 广播」(2026-06-06 提出,2026-06-07 已实施)
|
||||||
|
|
||||||
|
**当前实现(方案 B,§3.2)**:DAG 各 stage 由前端**直接**派活,stage 间不跑 leader,靠前端把 `buildDependencySummary` 拼进下一 stage 的 task(`priorSummary`)。各 stage 跑完后才 `await runOrchestration` 交回总控收口。
|
||||||
|
|
||||||
|
**新诉求**:业务链条调用时,**每一轮 stage 之间都要经总控中转 + 广播**,而不是前端直接串下去。具体:
|
||||||
|
|
||||||
|
1. 第 1 轮并行调用 stage1 的 A、B、C;
|
||||||
|
2. A/B/C **全部完成后**,把这一批的**输出广播出来**(广播给其它席位 + 总控 thread);
|
||||||
|
3. **总控(leader)接收**这批交付 → 再**往下继续派活**(派 stage2 的 D、E);
|
||||||
|
4. 派活时把(承上的)消息**广播给下一轮的 D、E**;
|
||||||
|
5. 以此类推,直到所有 stage 跑完再收口。
|
||||||
|
|
||||||
|
> 即把 §3.2 的「方案 B 前端直派」改成 **「方案 A' = 计划约束下的总控中转」**:stage 边界插入一轮 leader,由它综合上一批交付并驱动下一批(下一批席位仍由编排计划**钉死**为 D、E,不是 leader 自由乱派——leader 负责「承上启下 + 广播上下文」,计划负责「派给谁」)。
|
||||||
|
|
||||||
|
**实施要点(下次会话)**:
|
||||||
|
|
||||||
|
- **每个 stage 完成 → 广播该批输出**:后端 `_special_run` 已对每个 seat 做 detached 后广播(「子智能体X完成…交付内容为:…」→ 其它席位 + 总控)。但它是 **detached/best-effort + 截断**;要让总控**可靠**地在下一轮前看到,需在 stage barrier 处**等广播落地**(或前端在 stage 边界用 `GET /threads/{id}/last-ai-message` 主动收齐各席位交付再喂给 leader)。
|
||||||
|
- **插入 leader 中转轮**:`runDagOrchestration` 在进入下一 stage 前,跑一轮 leader(`synthesisMode=true` 让后端注入上一批**完整**交付),让总控产出一段「承上启下」说明;把这段说明(而非机械 `priorSummary`)作为下一 stage 席位 task 的上下文 / 或广播给下一批席位 thread(复用 `POST /threads/{id}/messages/append`)。
|
||||||
|
- **下一批仍由计划钉死**:leader 中转轮**不**自由决定派给谁(计划已定 D、E);可参考 `buildChainLeaderTask` 的「约束 leader 只派给指定席位」思路,或干脆 leader 只做综合、前端照计划派 D、E 并把 leader 综合 + 广播注入其 task。
|
||||||
|
- **与「并行禁写」「§12.1 放开搜索」并存**:中转/广播不影响工具面。
|
||||||
|
- **与致命 bug 修复并存**:最后一个 stage 跑完仍走「交回总控(`runOrchestration`)收口/继续派活」;用户干预仍走 leader、不重跑 DAG。
|
||||||
|
|
||||||
|
**影响文件(预估)**:`hooks/useStep2Orchestration.ts`(`runDagOrchestration` 的 stage 循环里加 leader 中转 + 广播收齐)、可能复用后端 `_leader_run`(synthesisMode 注入全文)/ `/messages/append`(广播)/ `/last-ai-message`(收齐交付)。后端基本无需新接口。
|
||||||
|
|
||||||
|
**✅ 实施结论(2026-06-07)**:后端**零改动**,全部在前端 `runDagOrchestration` 内完成,复用既有「传摘要按需传全文」优化链路:
|
||||||
|
|
||||||
|
1. **中转轮位置**:每个**非最后**的 stage barrier 到达后(`Promise.all` 收齐本批交付),插入**一轮 leader**「中转轮」,展示为「总控协调(承上启下)」气泡。最后一个 stage 后**不**插中转,综合/收口仍交给末尾的 `runOrchestration` 接管(与致命 bug 修复一致)。
|
||||||
|
2. **可靠收齐交付(传摘要)**:中转轮跑 `streamMultiAgent({agentType:"leader", synthesisMode:false})`。后端 `_leader_run` 本就在每轮 leader 前用 `_collect_delivery_status`(走**轻量 `GET /last-ai-message?max_chars=600` 接口**)**客观核对**各席位真实交付并把**摘要**注入总控输入(`_build_seat_status_block`)——比 detached 广播可靠(直接实读各席位 thread,不依赖 best-effort 广播是否落地)。故中转轮传 `synthesisMode:false`:只综合本批、**不收口**,只注入摘要;**完整交付正文**留到末尾收口的 synthesis 轮(`_build_full_deliverables_block`,全 ✅ 才注入)按需读取——即「**传摘要按需传全文**」。
|
||||||
|
3. **承上启下驱动下一批**:中转轮产出的综合说明存进 `leaderBridge`,作为**下一 stage** 席位 task 的上下文(`buildStageTask({priorSummary: leaderBridge, priorIsBridge:true})`,措辞为「承上启下综合说明」而非机械「交付摘要」),替代原来的 `buildDependencySummary(deliveries)`。中转失败/无产出时回退机械依赖摘要,不阻断。
|
||||||
|
4. **下一批由计划钉死**:中转轮提示(`buildDagTransitTask`)明确告知总控「下一阶段席位已由编排计划钉死为 X、Y,你**不要**自行 `agent_orchestration` 派活、**不要**收口」,前端仍照计划直派下一批;即便弱模型仍派了活,前端忽略其 `dispatched`、只取 `content` 当 bridge。
|
||||||
|
5. **广播**:本批输出广播给其它席位 + 总控 = 后端 `_special_run` 既有 detached 后广播(截断摘要);承上消息给下一批 = 注入其 task `new_message`(席位 run 输入必见,比 `/messages/append` 更可靠,省一次写盘)。
|
||||||
|
6. **澄清/抢占/失败**:中转轮触发澄清 → 暂停 DAG(回复后走 leader 自由派活、不重跑 DAG,沿用 `dagPlanExecutedRef` 闸门);被 `isStale()`/abort 抢占 → 静默收尾;异常 → 该气泡标错误、清空 bridge 继续。
|
||||||
|
|
||||||
|
**纯函数**:`lib/dag-types.ts` 新增 `buildDagTransitTask`(中转轮提示)+ `buildStageTask` 加 `priorIsBridge` 形参;`lib/dag-types.test.ts` 加 4 个单测(共 27 个全过)。
|
||||||
|
|
||||||
|
> ⚠️ **§12.3 的「单独中转轮 + 前端直派」已被 §12.4 取代**(2026-06-07 同日):见下。`buildDagTransitTask` / `buildStageTask` / `buildDependencySummary` 仍保留在 lib(带单测),但 `runDagOrchestration` 不再调用它们。
|
||||||
|
|
||||||
|
### 12.4 ✅ 需求再变更:DAG 改成「总控驱动每 stage 派活」(2026-06-07,§3.2 方案 A)
|
||||||
|
|
||||||
|
**新诉求(用户原话)**:把并行(DAG)逻辑改得和串行一样——串行时总控给多个智能体派活、它们完成后汇报给总控、总控再继续往下派活;并行也改成「由总控判断要执行哪些步骤,这些步骤完成后再汇报给总控,总控继续往下派活」。
|
||||||
|
|
||||||
|
**已确认的两个关键决策**:
|
||||||
|
1. **每批「派给谁」**:✅ **计划钉死成员,但走总控派活**(不是总控自由乱派)。即 stage 成员仍由编排计划定死,但改成总控每轮**真正** `agent_orchestration` 派活给这些席位(约束只派给它们、且每个都派到)。= §3.2「方案 A」+ 批内并行。
|
||||||
|
2. **适用范围**:✅ **只改 dag 模式**(recommend 仍串行逐个、chain 不动)。
|
||||||
|
|
||||||
|
**实现(后端零改动,全在 `runDagOrchestration`)**:每个 stage 两步——
|
||||||
|
- **(a) 总控派活轮**:跑一轮 `leader`,提示 `buildDagStageLeaderTask`(首 stage 带任务背景;后续 stage 靠后端注入的此前交付摘要承上;列出本 stage 钉死席位的 `agent_name`,要求逐个派到、不派清单外、不收口)。`synthesisMode:false` → 后端 `_build_seat_status_block` 走轻量 `last-ai-message` 注入各席位**摘要**(传摘要按需传全文)。
|
||||||
|
- **(b) 批内并行**:本 stage 席位并行跑总控派给各自的 task——`pickDagSeatTask(leaderRes.dispatched, content, agentId, name)` 命中其 `agent_name`;总控漏派/写偏则回退总控正文/模板,**不借用别席位 task**(多席位并行避免张冠李戴)。完成后交付经后端 `_special_run` detached 后广播回总控;下一 stage 的派活轮即可看到。
|
||||||
|
- barrier 后进入下一 stage,总控再派下一批。全部 stage 跑完 → 交回 `runOrchestration` 收口(synthesisMode 按需注入全文)。
|
||||||
|
|
||||||
|
**相比 §12.3 的变化**:§12.3 是「前端直派 + stage 间单独插一轮只综合的中转轮」;§12.4 把**每个 stage 本身**就改成「总控派活轮 + 批内并行」——总控既承上(注入的摘要)又派活,不再需要单独的中转轮。与 chain 模式同构,区别是一次钉死一批、批内并行。
|
||||||
|
|
||||||
|
**纯函数**:`lib/dag-types.ts` 新增 `buildDagStageLeaderTask`(每 stage 派活提示)+ `pickDagSeatTask`(取某席位 task,多席位不张冠李戴);`lib/dag-types.test.ts` 加 5 个单测(共 32 个全过)。`runDagOrchestration` 不再用 `buildStageTask/buildDependencySummary/buildDagTransitTask`(保留在 lib)。
|
||||||
|
|
||||||
|
**Phase 7 流程图兼容**:总控派活轮无席位 active + `isOrchestrating` → 流程图「总控」节点显示 active(承上派活中),随后该 stage 列点亮,无缝衔接。
|
||||||
|
|
||||||
|
**下次实地验收**:①每个 stage 前出现「总控协调(派活中/承上派活中)」气泡,内容是总控对本 stage 席位的派活说明;②后端日志该轮 leader 的 `_partition_dispatch` 派给的正是本 stage 钉死席位;③这些席位并行跑(special 日志时间重叠);④完成后下一 stage 总控派活轮能看到上一批交付摘要(`[leader-roster]` 日志)。
|
||||||
|
|
||||||
|
### 12.5 ✅ 流程图弹窗化 + DAG「快速/沙箱」执行子模式(2026-06-07)
|
||||||
|
|
||||||
|
三个改动一起做:
|
||||||
|
|
||||||
|
**(1) 流程图改成弹窗**:Step2 顶部不再内联 `DagFlowChart`(挤占两列消息高度,截图 `样式优化-1.png`)。改成一条细栏「分层编排执行中 · 共 N 个阶段 + [查看编排流程图]」按钮,点开 `Dialog` 看**全尺寸**流程图(非 compact)。编辑器(`BusinessChainEditorPage`)底部预览保持内联不变。改 `Step2Panel.tsx`(加 `dagFlowOpen` state + Dialog)。
|
||||||
|
|
||||||
|
**(2) 推荐弹窗新增 DAG 执行子模式(快速/沙箱)**:`BusinessChainPicker` 在选中链条**有分层并行**(走 dag)时,「进入研讨」旁出现「执行方式:快速·双列禁写 / 沙箱·单列可写」二选一(只 dag 时出现,§已确认)。
|
||||||
|
- **快速(`fast`,默认)**:同 stage 席位**并行**、主区**双列**、`parallelNoFile=true`(seat_parallel **禁写文件**)。= 之前的行为。
|
||||||
|
- **沙箱(`sandbox`)**:同 stage 席位**仍并行**,但主区**单列**(`selectedParallelSeats` 最多 1)、`parallelNoFile=false`(seat policy **允许写文件**);点头像切换查看,沙箱跟随当前席位。
|
||||||
|
- 数据流:`SeatSelectionResult.dagExecMode` → `RoundtablePlanningPage` state(持久化进 `DraftStep2(Run)Snapshot.dagExecMode`,mirror orchestrationPlan)→ `useStep2Orchestration` option → `runDagOrchestration`。
|
||||||
|
|
||||||
|
**(3) 沙箱跟随当前显示席位(防 bug 重点,用户特别强调)**:`useStep2Orchestration`
|
||||||
|
- `sandboxFollowThreadIdRef` = 当前显示席位的 thread;`openSeatVirtualArtifact` 的 auto 守卫:sandbox 模式下,**后台并行席位**写文件时若不是当前显示席位,**不自动打开**(否则沙箱内容和主区列表错位)。
|
||||||
|
- 切换显示席位的 effect(keyed on `selectedParallelSeats` + `dagExecMode`):该席位**有产物**(stub 里有 write_file/str_replace)→ `openSeatLatestArtifact` 强制打开它最新的文件;**无产物**→ 关闭沙箱面板(`setActiveArtifactThreadId(null)` + `deselectArtifact` + `setArtifactsOpen(false)`)。
|
||||||
|
- 当前显示席位 live 写文件 → `handleArtifactToolPhase` auto-open,守卫放行(follow===该席位)。后台席位写 → 守卫拦掉、只缓存 stub;切到它时 effect 再打开。
|
||||||
|
- `toggleParallelSeat`:sandbox 单列 = 点头像切换(始终保留 1 个,不取消到空);fast 双列 = 原 LRU 2 个。
|
||||||
|
|
||||||
|
**改动文件**:`lib/business-chain.ts`(SeatSelectionResult.dagExecMode)、`components/BusinessChainPicker.tsx`(子模式 UI)、`api/drafts.ts`(快照 dagExecMode)、`pages/RoundtablePlanningPage.tsx`(state/snapshot/hydrate/confirm/reset 全链)、`hooks/useStep2Orchestration.ts`(option + parallelNoFile/单列 + 沙箱跟随 + toggle cap)、`components/Step2Panel.tsx`(流程图弹窗 + 单列 grid)。typecheck 零新增(基线 65),dag-types 32 单测全过。
|
||||||
|
|
||||||
|
**下次实地验收(沙箱跟随是重点)**:①推荐弹窗选有并行的链条 → 出现「快速/沙箱」二选一;②快速=双列禁写(无沙箱);③沙箱=单列、席位能写文件、点头像切换列表时沙箱内容**同步**切换:有产物显示、无产物关闭;④后台席位写文件不会把沙箱抢到非当前列表;⑤流程图点按钮弹窗、全尺寸、节点随执行点亮。
|
||||||
|
|
||||||
|
### 12.6 ✅ 修:并行席位「跟着派活」(2026-06-07)
|
||||||
|
|
||||||
|
**现象**(截图 `bug-1.png`):总控派活后,并行席位的气泡里显示的是**总控的整段派活叙述**(「我来调度各智能体…第1阶段任务清单:席位1…席位2…」),还去调 `skill_list` 找 `agent_orchestration`——席位在**模仿派活**。
|
||||||
|
|
||||||
|
**根因**:总控这轮**没真正调用 `agent_orchestration` 工具**(弱模型 deepseek 用文字罗列了派活计划)→ 后端解析的 `dispatched=[]` → 前端 `pickDagSeatTask` 回退把**总控整段叙述**喂给**每个**席位 → 席位照抄叙述、模仿派活。(席位本就被 run policy 禁了 `agent_orchestration`,**派不了活**,只是空转一轮叙述 + 调 `skill_list`。)
|
||||||
|
|
||||||
|
**修 v1(护栏,效果不足)**:`pickDagSeatTask` 加角色边界护栏 + 回退措辞改「挑出属于你的那份」;`buildDagStageLeaderTask` 加「必须真正调用工具」。→ **没拦住**:总控对 deepseek 仍只写文字不调工具(`dispatched` 还是空),席位拿到的**任务正文本身**就是那段「我来调度…席位1/2/3」,护栏被淹没;3/4 席位仍模仿派活,有的甚至绕道 `bash`+`python requests.get('/api/agents')` 调内部接口派活(bug-1~4)。
|
||||||
|
|
||||||
|
**✅ 修 v2(根治:回退绝不注入派活叙述)**:`pickDagSeatTask` 去掉 `leaderContent` 入参——
|
||||||
|
- **命中**总控结构化派活(真调了工具)→ `请你作为「X」,完成总控派给你的本阶段任务:<dispatched task>` + 护栏;
|
||||||
|
- **未命中 / `dispatched` 空**(总控只写文字)→ **绝不**把总控派活叙述喂给席位,改给**干净本职任务**:「请你作为「X」,从你的专业职责出发,独立完成本阶段属于你的分析与交付。任务背景与此前各阶段交付已在你的会话上下文里(后端广播注入),据此承接」+ 护栏。护栏强化到「不要用 bash/python/脚本访问内部接口(/api/agents、agent_orchestration)派活、不要复述『我来调度』总控口吻」。
|
||||||
|
- `buildDagStageLeaderTask` 的「必须真正调用工具」保留(让命中率更高、尽量走 exact-match)。
|
||||||
|
- `dag-types.test.ts` 改 2 单测(共 33 过)。typecheck 65。
|
||||||
|
|
||||||
|
> ⚠️ **残留次要污染源(若仍复发再处理)**:DAG 每个 stage 的 leader 轮,后端 `_leader_run` 会把 leader 的输入(含「请你作为总控…派活」)**预广播**进所有席位线程(`总控智能体收到用户消息:…`)。席位的**当轮任务**已干净(修 v2),这条只是历史上下文,理论上被「最新的干净任务 + 护栏」压制。若实测仍模仿派活,下一步:后端给 DAG leader 轮加 `suppress_pre_broadcast` / 或广播一条**净化**过的背景(去掉派活措辞)。
|
||||||
|
|
||||||
|
### 12.7 ✅ 修 4 项(2026-06-07):席位仍派活(v3 后端)+ 沙箱关不掉 + 并行不自动下滑 + 流程图只到 Step2
|
||||||
|
|
||||||
|
实测 §12.6 仍有席位派活(视觉设计师 `skill_manage` 找 agent-orchestration、列 dispatch all 4)——**坐实**了「残留次要污染源」:后端 leader 预广播把派活 prompt 推进席位线程,弱模型从历史里捡到派活意图。一起修了 4 项:
|
||||||
|
|
||||||
|
1. **席位仍派活(根治·后端)**:`_leader_run` 加 `suppress_pre_broadcast` 参数;DAG「每 stage 派活轮」前端传 `suppressPreBroadcast: true`(`api/multi-agent.ts` → `suppress_pre_broadcast`,run/stream 读取)。为真时:**不**把总控派活 prompt 预广播给席位、**也不**把「总控给 X 派活」detached 广播给兄弟席位。recommend/chain 不传该 flag,行为不变。配套:`pickDagSeatTask` 加 `seedMessage` 入参——预广播抑制后席位线程没有用户原始消息了,把**任务背景**直接写进席位 task(此前各阶段交付仍由 special 完成后广播注入)。→ 席位线程里**任何地方都没有派活语句**,根治模仿。
|
||||||
|
2. **沙箱关闭按钮关不掉**:沙箱跟随 effect 之前每次 render(deps 身份变)都重跑 → 把用户刚关的沙箱强制重开。加 `lastReconciledSeatRef` 守卫:**只在显示席位真正变化时**才开/关沙箱;用户手动关闭(席位没变)时 effect 早退,不再回弹。
|
||||||
|
3. **并行时自动下滑失效**:平铺列表 ↔ 网格(两列/单列)切换时 `scrollHeight` 突变、`scrollTop` 被浏览器 clamp → `useAutoScroll` 误判「用户上滚」而停跟随。`Step2Panel` 加 effect:`isParallelRunning` / `selectedParallelSeats` 变化时 `scrollStep2ToBottom()` 重新拉到底 + 恢复跟随。
|
||||||
|
4. **流程图只展示 Step2**:`DagFlowChart` 加 `showReportMilestone`(默认 true);Step2 弹窗 + 编辑器预览传 `false` —— 只到「共识」(Step2 终点),去掉「结果绘制」(那是 Step3)。
|
||||||
|
|
||||||
|
**改动**:后端 `multi_agent.py`(`_leader_run` suppress 两处广播 + run/stream 读 flag);前端 `api/multi-agent.ts`、`lib/dag-types.ts`(pickDagSeatTask + seedMessage)、`hooks/useStep2Orchestration.ts`(传 flag + seed + 沙箱跟随守卫)、`components/Step2Panel.tsx`(自动下滑 effect + showReportMilestone)、`components/DagFlowChart.tsx`、`pages/BusinessChainEditorPage.tsx`。`dag-types.test.ts` 共 **34 单测过**;前端 tsc 65 基线零新增;后端 `py_compile` OK。
|
||||||
|
|
||||||
|
### 12.8 ✅ 席位产出 md 文件 + 禁写 .py(2026-06-07)
|
||||||
|
|
||||||
|
**现象**:某次 7 席位**全都没产出 md 文件**;且一直有的问题——席位**有时写 .py 脚本**(用户要求:不写 .py,其它格式可以)。
|
||||||
|
|
||||||
|
**根因(没 md)**:两层都堵了——(a)**快速模式** `seat_parallel` policy 禁了 `write_file`(原「产物走正文」设计);(b)DAG 席位**提示词**写的是「直接输出你的交付正文」,即使沙箱模式(允许写)也不会去写文件。
|
||||||
|
|
||||||
|
**修**:
|
||||||
|
1. **后端 policy 放开写文件、统一禁 bash**(`roundtable_run_policy.py`):
|
||||||
|
- `seat_parallel`:去掉 `write_file` / `str_replace` 禁用(**可写 md**),保留禁 `bash` + 打断/越权类;仍放开 `web_search`。
|
||||||
|
- `seat`:新增禁 `bash`(原来允许)——圆桌席位是「文档产出者」,不该跑 shell/python 脚本(弱模型爱写 .py 再跑生成产物,乱且抓不到预览);改为**直接 write_file 写成品文档**。
|
||||||
|
- `report`:`bash` 已随 `seat` 禁,改为 `[*_SEAT_EXCLUDED, "str_replace"]`(集合不变)。
|
||||||
|
- 测试 `test_roundtable_run_policy.py`:`test_seats_can_write_files_but_not_run_bash`(seat / seat_parallel 都可写文件、都禁 bash),6 用例过。
|
||||||
|
2. **前端提示词**(`pickDagSeatTask`)加「产物要求」:**把完整交付写成一个 .md 文件**(write_file 到 outputs)+ 正文给摘要;**禁写 .py 或任何脚本文件**,.md/.html/.txt 等其它格式都可以,唯独不要 .py。
|
||||||
|
3. **快速模式(双列)不自动开沙箱**(`openSeatVirtualArtifact` 新增守卫):放开写文件后,双列里多席位并发写文件会让单沙箱预览反复串台——fast 模式 DAG 并行批次**完全不自动开沙箱**(文件仍写盘,Step3/文件卡可查看);沙箱模式(单列)仍按「沙箱跟随当前席位」预览。
|
||||||
|
|
||||||
|
**关于 .py 的强度**:`write_file` 是全局工具(所有 agent 共用),无法在网关层按扩展名硬拦,故 .py 禁止走**提示词**(强约束)+ **禁 bash**(写了也跑不了,脚本生成产物的动机被掐断)。若实测仍偶发写 .py 且需**硬拦**,下一步:给 lead_agent 的 `write_file` 工具加一个「按 run context 禁某些扩展名」的开关,网关 `_run_payload` 对圆桌席位置 `[".py"]`(只影响圆桌 run,不动其它 agent)。
|
||||||
|
|
||||||
|
**改动**:`roundtable_run_policy.py`、`test_roundtable_run_policy.py`、`lib/dag-types.ts`、`lib/dag-types.test.ts`(35 过)、`hooks/useStep2Orchestration.ts`。前端 tsc 65、后端 py_compile OK + 6 policy 单测过。⚠️ **改了后端,需重启 Gateway**。
|
||||||
|
|
||||||
|
### 12.9 ✅ 席位「按需取前序全文」只读工具 read_peer_delivery(2026-06-07)
|
||||||
|
|
||||||
|
**诉求**:A,B,C → D,E 时,D,E 默认拿 A,B,C 的**摘要**,但识别到需要**全文**时也能取到。之前只有总控(leader)能「摘要默认+按需全文」(跨 thread 读),下游席位**不能**(席位间 thread 隔离、只有 1500 字截断广播)。
|
||||||
|
|
||||||
|
**实现**(真·按需,全文只在调用工具时才进 LLM 上下文):
|
||||||
|
1. **新 harness 只读工具** `read_peer_delivery(seat_name)`(`packages/harness/deerflow/tools/builtins/roundtable_peers_tool.py`):从 `runtime.context["roundtable_peer_deliveries"]`(网关注入的 `[{name,content}]`)按席位名取全文;空名→列出可取席位;非圆桌场景→「无」。只读 context dict,**不跨 thread、不碰 sandbox、无网络**,纯 `deerflow.*`(不违反 harness→app 防火墙)。注册进 `tools/tools.py` 的 builtin(始终在,只读无副作用)。
|
||||||
|
2. **网关注入 context**:`_run_payload` 加 `extra_context`;`_special_run` 收 `peer_deliveries` → 注入 `context.roundtable_peer_deliveries`;run/stream 读 `peer_deliveries`(规整 `[{name,content}]`)。**不进 prompt → 不调工具就不耗 token**。
|
||||||
|
3. **run policy**:`read_peer_delivery` 从 `leader`(总控自己跨 thread 读,不需要)+ `report`(Step3 不读前序)排除;**席位(seat/seat_parallel)保留**。
|
||||||
|
4. **前端**:`runDagOrchestration` 跨 stage 累积**完整交付** `priorDeliveries`,stage>0 席位的 special run 带 `peerDeliveries`(`api/multi-agent.ts` → `peer_deliveries`);`pickDagSeatTask` 加 `hasPeers` 形参,有前序时在 task 里提示「需要某前序席位全文时调用 read_peer_delivery('<名>'),平时用摘要」。
|
||||||
|
|
||||||
|
**最终语义**:D、E 默认看 A、B、C 的**摘要**(1500 字广播);识别到不够 → 调 `read_peer_delivery('情报收集')` 取**全文**。总控仍是摘要默认+综合轮全文。**= 用户要的「摘要默认、按需全文」对席位也成立了。**
|
||||||
|
|
||||||
|
**改动**:后端 `roundtable_peers_tool.py`(新)、`tools/tools.py`、`roundtable_run_policy.py`、`multi_agent.py`;前端 `api/multi-agent.ts`、`lib/dag-types.ts`、`lib/dag-types.test.ts`(36 过)、`hooks/useStep2Orchestration.ts`。前端 tsc 65;后端 py_compile OK + 6 policy 单测过 + 工具导入/行为 smoke 通过。⚠️ **改了后端 + 新增 harness 工具,需重启 Gateway**。
|
||||||
|
|
||||||
|
### 12.10 ✅ 修:沙箱模式第一个席位不自动开沙箱(2026-06-07,前端)
|
||||||
|
|
||||||
|
**现象**:沙箱(单列)模式并行时,**第一个**席位的消息列表不自动打开沙箱(要手动开);切换到其它席位时正常自动打开。
|
||||||
|
|
||||||
|
**根因**:沙箱跟随 effect(§12.5)在选中席位**还没写产物**时走「关闭沙箱」分支,里面同时调了 `deselectArtifact()` **和** `setArtifactsOpen(false)`。后者是 context 的 **wrapped setOpen**(`context.tsx:73`):`关闭时若 autoOpen 为真 → 把 autoOpen 置 false`。于是第一个席位刚选中(还没写文件)→ autoOpen 被关 → 该席位**随后 live 写文件**时,`openSeatVirtualArtifact` 的 `!flags.autoOpen` 守卫拦掉自动打开。切换到**已写过**文件的席位能开,是因为那条路走 `openSeatLatestArtifact`(force,auto=false,绕过 autoOpen 守卫)。
|
||||||
|
|
||||||
|
**修**(一行):关闭分支只保留 `deselectArtifact()`(它走 raw `setOpen(false)`,**不**动 autoOpen),删掉多余的 `setArtifactsOpen(false)`。这样面板关掉、但 autoOpen 仍为真 → 第一个席位 live 写文件时正常自动开沙箱。(若用户**手动**关过沙箱,autoOpen 本就为 false,不会自动重开 —— 尊重用户。)改 `hooks/useStep2Orchestration.ts` 沙箱跟随 effect。tsc 65。
|
||||||
|
|
||||||
|
### 12.11 ✅ 修:快速模式又生成文件了 + Fragment 警告(2026-06-07);记录无关 404
|
||||||
|
|
||||||
|
1. **快速模式不应生成文件(回退 §12.8 的过度放开)**:§12.8 为「让席位产 md」把 `seat_parallel`(快速模式)也放开了 write_file —— 但**快速模式(双列)的设计就是产物走正文、不写文件**,写文件归**沙箱模式**(单列 + 沙箱预览)。修:
|
||||||
|
- `roundtable_run_policy.py`:`seat_parallel` 重新**禁 write_file / str_replace**(保留禁 bash);`seat`(沙箱模式)仍可写。
|
||||||
|
- `useStep2Orchestration.ts`:`parallelNoFile = dagExecMode !== "sandbox"`(快速模式一律禁写,含单节点 stage;沙箱模式放开)。
|
||||||
|
- `pickDagSeatTask` 加 `allowFiles` 形参:沙箱(true)=写 .md 文件 + 禁 .py;快速(false)=产物走正文、不写文件。hook 按 `dagExecMode === "sandbox"` 传。
|
||||||
|
- 测试:`test_sandbox_seat_writes_files_fast_parallel_does_not`(6 过);`dag-types.test.ts` 拆成沙箱/快速两个产物要求用例(37 过)。
|
||||||
|
- **语义**:快速=双列、产物走正文、不写文件;沙箱=单列、写 .md、沙箱跟随预览。
|
||||||
|
2. **`Invalid prop data-lov-id supplied to React.Fragment`**:`DagFlowChart` 的 stage 循环用了具名 `<Fragment key>`,dev 代码标注插件(lovable-tagger)给它注入 `data-lov-id`,而 Fragment 只接受 key/children → React 警告。修:换成 `<div className="contents" key=...>`(display:contents 不生成盒子,Connector/StageColumn 仍是外层 flex 直接子项,布局不变,且能接收 data-*)。移除 `Fragment` import。
|
||||||
|
3. **(无关,非本期引入)`/api/getTokenByEmail?email=…%40local.deerflow` 404 ×60**:来自 `src/core/studio/api.ts` 的 `fetchStudioToken`(studio/expert-auth 引导),用户邮箱被映射到 legacy `@local.deerflow` 域、后端 `getTokenByEmail` 不认 → 404,React Query 跨多个 `useStudioToken` 调用点重试 → 重复多次。**与圆桌 DAG 改动无关**(圆桌头像是本地 SVG,本期未新增任何前端 GET)。需要的话单独排查 studio token 链路。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. 实施进度(截至 2026-06-06,下次会话续)
|
||||||
|
|
||||||
|
| Phase | 内容 | 状态 |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | DAG 数据模型 + 校验 + 持久化字段(`lib/dag-types.ts`,24 单测) | ✅ 完成 |
|
||||||
|
| 2 | 分层编辑器(**做进业务链条页**):链条加 `stages` 字段(前后端 + alembic `20260607_03` + 11 后端单测);`BusinessChainEditorPage` 竖列分组 Stage(DnD + 按钮);纯逻辑 `lib/chain-stages.ts`(19 单测) | ✅ 完成 |
|
||||||
|
| 3 | `runDagOrchestration`:批内 `Promise.all` 并行 + 批间 barrier 串行 + 依赖摘要注入(方案 B 前端直派) | ✅ 完成 |
|
||||||
|
| 4 | 并行 run policy `seat_parallel`(`roundtable_run_policy.py` + `multi_agent.py` 读 `parallel_no_file`,6 后端单测);**§12.1 方案 A 已放开 web_search/技能** | ✅ 完成 |
|
||||||
|
| 5 | 并行显示:收起左侧 + 头像条 + 两列 + 选中切换 | ✅ 完成(本轮修了侧栏/Markdown/字数) |
|
||||||
|
| 6 | 流式高性能:ref 全量累积 + 节流 flush(仅选中渲染) | ✅ 完成 |
|
||||||
|
| 7 | DAG 流程图执行态可视化(`DispatchChainModal` 复刻成按 stage 分列;后改成**弹窗**见 §12.5) | ✅ 完成(2026-06-07) |
|
||||||
|
|
||||||
|
**端到端闭环已通**:链条页编排分层 → 存库 → 选链条进 Step2 → `runDagOrchestration` 并行直派 → 各阶段完交回总控派活/收口。
|
||||||
|
|
||||||
|
**✅ §12.3 已实施(2026-06-07)**:见 §12.3「实施结论」。`runDagOrchestration` 在每个非末尾 stage barrier 后插入 leader 中转轮(`synthesisMode:false` 走轻量 `last-ai-message` 注入摘要、收口轮才按需全文),承上启下驱动下一批;后端零改动;`dag-types.ts` 加 `buildDagTransitTask` + `buildStageTask.priorIsBridge`,27 单测全过。
|
||||||
|
|
||||||
|
**下次会话 TODO(优先级从高到低)**:
|
||||||
|
1. **运行时实地验收 §12.3**:①每个 stage 之间出现「总控协调(承上启下)」气泡,内容是对上一批的综合;②后端日志中转轮 `[leader-roster] ... 注入席位交付状态` 显示上一批 ✅、未跑的 ⬜;③下一 stage 席位 task 里带的是总控承上说明(非机械摘要);④中转轮不应真的派活(即使派了前端也忽略)。
|
||||||
|
2. 运行时实地验收(旧):①§12.1 后并行席位能搜索、步骤条显示;②并行 special 日志时间重叠 + `Excluded` 不含 web_search 含 write_file;③用户干预后是「总控派活」而非重跑 DAG;④最左全局侧栏 + 参与角色栏并行收起且不回弹。
|
||||||
|
3. **✅ Phase 7 DAG 流程图可视化已完成(2026-06-07)**:见 §7.2。`DagFlowChart` 组件 + 编辑器只读预览 + Step2 执行态缩略(`dagNodeStates` 实时驱动)。
|
||||||
|
4. (可选)串行也确定性注入上一轮交付摘要。
|
||||||
|
|
||||||
|
**关键文件速查**:
|
||||||
|
- 前端:`hooks/useStep2Orchestration.ts`(`runDagOrchestration` / `dagPlanExecutedRef` / 并行 store+flush)、`components/Step2Panel.tsx`(两列+头像条)、`components/ParallelSeatStrip.tsx`、`lib/dag-types.ts`、`lib/chain-stages.ts`、`pages/BusinessChainEditorPage.tsx`、`pages/RoundtablePlanningPage.tsx`(侧栏收起 effect + handleConfirmAgents dag 分支)、`components/BusinessChainPicker.tsx`(链条→dag)。
|
||||||
|
- 后端:`app/gateway/roundtable_run_policy.py`(`seat_parallel`,**待放宽**)、`app/gateway/routers/multi_agent.py`(`_special_run` 读 `parallel_no_file`)、`persistence/roundtable_chains/`(`stages` 列)、`migrations/versions/20260607_03_chain_stages.py`。
|
||||||
|
- 测试:`frontend-web` 用 esbuild 转译 `.test.ts` 后 `node --test`(项目无 vitest);后端 `PYTHONPATH=. uv run pytest tests/test_roundtable_chain_stages.py tests/test_roundtable_run_policy.py`。
|
||||||
|
|
||||||
@@ -13,7 +13,8 @@
|
|||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<title>CM 助手</title>
|
<title>CM 助手</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
Generated
+10540
-10140
File diff suppressed because it is too large.
Load diff
@@ -22,6 +22,7 @@
|
|||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"@fontsource/noto-sans-sc": "^5.2.9",
|
||||||
"@langchain/core": "^1.1.15",
|
"@langchain/core": "^1.1.15",
|
||||||
"@langchain/langgraph-sdk": "^1.5.3",
|
"@langchain/langgraph-sdk": "^1.5.3",
|
||||||
"@radix-ui/react-avatar": "^1.1.11",
|
"@radix-ui/react-avatar": "^1.1.11",
|
||||||
@@ -55,6 +56,7 @@
|
|||||||
"@uiw/react-codemirror": "^4.25.4",
|
"@uiw/react-codemirror": "^4.25.4",
|
||||||
"@xyflow/react": "^12.10.0",
|
"@xyflow/react": "^12.10.0",
|
||||||
"ai": "^6.0.33",
|
"ai": "^6.0.33",
|
||||||
|
"axios": "1.16.1",
|
||||||
"best-effort-json-parser": "^1.2.1",
|
"best-effort-json-parser": "^1.2.1",
|
||||||
"canvas-confetti": "^1.9.4",
|
"canvas-confetti": "^1.9.4",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="智能助手中心">
|
||||||
|
<defs>
|
||||||
|
<!-- 品牌玫红渐变填充的圆角磁贴 -->
|
||||||
|
<linearGradient id="tile" x1="6" y1="4" x2="58" y2="60" gradientUnits="userSpaceOnUse">
|
||||||
|
<stop stop-color="#FB7185"/>
|
||||||
|
<stop offset="1" stop-color="#E11D48"/>
|
||||||
|
</linearGradient>
|
||||||
|
<!-- 气泡内 AI 闪光星:玫红渐变,与白色气泡形成对比 -->
|
||||||
|
<linearGradient id="spark" x1="24" y1="18" x2="40" y2="36" gradientUnits="userSpaceOnUse">
|
||||||
|
<stop stop-color="#FB7185"/>
|
||||||
|
<stop offset="1" stop-color="#E11D48"/>
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<!-- 磁贴背景 -->
|
||||||
|
<rect width="64" height="64" rx="15" fill="url(#tile)"/>
|
||||||
|
|
||||||
|
<!-- 辅助小闪光,点出「多种智能工具」 -->
|
||||||
|
<path fill="#FFFFFF" fill-opacity="0.85"
|
||||||
|
d="M47 43 Q47.6 46.4 50.5 47 Q47.6 47.6 47 51 Q46.4 47.6 43.5 47 Q46.4 46.4 47 43 Z"/>
|
||||||
|
|
||||||
|
<!-- 助手对话气泡(白色)+ 尾巴 -->
|
||||||
|
<rect x="12" y="13" width="40" height="28" rx="10" fill="#FFFFFF"/>
|
||||||
|
<path fill="#FFFFFF" d="M21 40 H31 L19 49 Z"/>
|
||||||
|
|
||||||
|
<!-- 气泡内的 AI 闪光星 -->
|
||||||
|
<path fill="url(#spark)"
|
||||||
|
d="M32 17.5 Q33.2 25.8 41.5 27 Q33.2 28.2 32 36.5 Q30.8 28.2 22.5 27 Q30.8 25.8 32 17.5 Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -17,6 +17,7 @@ import LoginPage from "./pages/LoginPage";
|
|||||||
import PageRoutes from "./pages/PageRoutes";
|
import PageRoutes from "./pages/PageRoutes";
|
||||||
import PublicScheduledTaskPage from "./pages/PublicScheduledTaskPage";
|
import PublicScheduledTaskPage from "./pages/PublicScheduledTaskPage";
|
||||||
import PublicSharePage from "./pages/PublicSharePage";
|
import PublicSharePage from "./pages/PublicSharePage";
|
||||||
|
import PublicRoundtableSharePage from "./pages/PublicRoundtableSharePage";
|
||||||
import EmbedChatPage from "./pages/EmbedChatPage";
|
import EmbedChatPage from "./pages/EmbedChatPage";
|
||||||
import { ChatRuntime } from "./pages/WorkspaceRoutes";
|
import { ChatRuntime } from "./pages/WorkspaceRoutes";
|
||||||
import { NotFoundPage } from "./pages/NotFoundPage";
|
import { NotFoundPage } from "./pages/NotFoundPage";
|
||||||
@@ -63,6 +64,15 @@ export function App() {
|
|||||||
<Route path="/landing" element={<LandingPage />} />
|
<Route path="/landing" element={<LandingPage />} />
|
||||||
{/* Public read-only conversation viewer — no authentication. */}
|
{/* Public read-only conversation viewer — no authentication. */}
|
||||||
<Route path="/share/:shareCode" element={<PublicSharePage />} />
|
<Route path="/share/:shareCode" element={<PublicSharePage />} />
|
||||||
|
{/* Public read-only roundtable share — landing + full result report. */}
|
||||||
|
<Route
|
||||||
|
path="/roundtable-share/:shareCode"
|
||||||
|
element={<PublicRoundtableSharePage />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/roundtable-share/:shareCode/report"
|
||||||
|
element={<PublicRoundtableSharePage report />}
|
||||||
|
/>
|
||||||
{/* Public read-only scheduled-task runs viewer — no authentication. */}
|
{/* Public read-only scheduled-task runs viewer — no authentication. */}
|
||||||
<Route
|
<Route
|
||||||
path="/public/scheduled-tasks/:taskId"
|
path="/public/scheduled-tasks/:taskId"
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
import { injectInPageAnchorHandler } from "@/core/utils/markdown";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sandboxed preview of a generated HTML document.
|
||||||
|
*
|
||||||
|
* Renders via a `blob:` URL rather than `srcDoc`. A srcDoc document's base URL
|
||||||
|
* is `about:srcdoc`, so clicking an in-page anchor (`<a href="#section">`)
|
||||||
|
* navigates the frame to `about:blank#section` and BLANKS it. A `blob:` URL is
|
||||||
|
* a real document URL, so fragment links scroll within the frame as expected —
|
||||||
|
* all without enabling scripts (the sandbox stays script-free for security; the
|
||||||
|
* server already sanitizes script vectors and this is defense-in-depth).
|
||||||
|
*
|
||||||
|
* The `charset=utf-8` on the blob type is required: a blob: URL whose
|
||||||
|
* Content-Type omits the charset is decoded with the OS default (GBK/Latin-1 on
|
||||||
|
* Chinese Windows), garbling CJK text when the HTML lacks a `<meta charset>`.
|
||||||
|
*/
|
||||||
|
export function HtmlPreviewFrame({
|
||||||
|
html,
|
||||||
|
className = "h-[70vh] w-full rounded-md border bg-white",
|
||||||
|
}: {
|
||||||
|
html: string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
const [url, setUrl] = useState<string>();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const blob = new Blob([injectInPageAnchorHandler(html ?? "")], {
|
||||||
|
type: "text/html;charset=utf-8",
|
||||||
|
});
|
||||||
|
const objectUrl = URL.createObjectURL(blob);
|
||||||
|
setUrl(objectUrl);
|
||||||
|
return () => URL.revokeObjectURL(objectUrl);
|
||||||
|
}, [html]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<iframe
|
||||||
|
title="HTML 预览"
|
||||||
|
sandbox="allow-scripts allow-forms"
|
||||||
|
src={url}
|
||||||
|
className={className}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
.sidebar-contnet {
|
.sidebar-contnet {
|
||||||
position: fixed;
|
position: absolute;
|
||||||
left: 0;
|
left: 0;
|
||||||
top: 4rem;
|
top: 4rem;
|
||||||
z-index: 40;
|
z-index: 40;
|
||||||
|
|||||||
@@ -55,14 +55,6 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
|
|||||||
}, 180);
|
}, 180);
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeNavPanel = () => {
|
|
||||||
if (hoverCloseTimerRef.current !== null) {
|
|
||||||
window.clearTimeout(hoverCloseTimerRef.current);
|
|
||||||
hoverCloseTimerRef.current = null;
|
|
||||||
}
|
|
||||||
setHoveredTopId(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const hasActiveChild = (item: MenuItem): boolean => {
|
const hasActiveChild = (item: MenuItem): boolean => {
|
||||||
if (item.path && pathname === item.path) {
|
if (item.path && pathname === item.path) {
|
||||||
return true;
|
return true;
|
||||||
@@ -83,7 +75,9 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
|
|||||||
if (matchedTopItem) {
|
if (matchedTopItem) {
|
||||||
setActiveTopId(matchedTopItem.id);
|
setActiveTopId(matchedTopItem.id);
|
||||||
}
|
}
|
||||||
closeNavPanel();
|
// 不在导航时强制关闭 flyout:flyout 绝对定位在 group 盒子之外,强制关闭后鼠标
|
||||||
|
// 仍停在 flyout 区域却收不到 group 的 mouseenter,导致连续点击第二个任务时面板
|
||||||
|
// 消失且不回来。开合只交给 hover(mouseleave 有 180ms 宽限),即可连续点选。
|
||||||
}, [pathname, visibleMenuItems]);
|
}, [pathname, visibleMenuItems]);
|
||||||
|
|
||||||
const toggleExpanded = (id: string) => {
|
const toggleExpanded = (id: string) => {
|
||||||
@@ -122,14 +116,12 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
|
|||||||
if (item.children?.length) {
|
if (item.children?.length) {
|
||||||
const firstPath = findFirstRoutePath(item.children);
|
const firstPath = findFirstRoutePath(item.children);
|
||||||
if (firstPath) {
|
if (firstPath) {
|
||||||
closeNavPanel();
|
|
||||||
navigate(firstPath);
|
navigate(firstPath);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (item.path) {
|
if (item.path) {
|
||||||
closeNavPanel();
|
|
||||||
navigate(item.path);
|
navigate(item.path);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -141,7 +133,6 @@ export function PageSidebarDark({ collapsed, onToggleCollapsed }: PageSidebarDar
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (item.path) {
|
if (item.path) {
|
||||||
closeNavPanel();
|
|
||||||
navigate(item.path);
|
navigate(item.path);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
/** Compute the page-number window to render, inserting -1 sentinels for gaps.
|
||||||
|
* Always shows first/last and a window around the current page. */
|
||||||
|
function buildPageItems(current: number, totalPages: number): number[] {
|
||||||
|
if (totalPages <= 7) {
|
||||||
|
return Array.from({ length: totalPages }, (_, i) => i + 1);
|
||||||
|
}
|
||||||
|
const items = new Set<number>([1, totalPages, current]);
|
||||||
|
for (const d of [1, 2]) {
|
||||||
|
if (current - d >= 1) items.add(current - d);
|
||||||
|
if (current + d <= totalPages) items.add(current + d);
|
||||||
|
}
|
||||||
|
const sorted = [...items].sort((a, b) => a - b);
|
||||||
|
const out: number[] = [];
|
||||||
|
let prev = 0;
|
||||||
|
for (const p of sorted) {
|
||||||
|
if (prev && p - prev > 1) out.push(-1); // gap sentinel
|
||||||
|
out.push(p);
|
||||||
|
prev = p;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaginationProps {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
total: number;
|
||||||
|
onPageChange: (page: number) => void;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Controlled, compact pagination control. Renders nothing when a single page. */
|
||||||
|
export function Pagination({
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total,
|
||||||
|
onPageChange,
|
||||||
|
className,
|
||||||
|
}: PaginationProps) {
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / Math.max(pageSize, 1)));
|
||||||
|
if (totalPages <= 1) return null;
|
||||||
|
|
||||||
|
const items = buildPageItems(page, totalPages);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<nav
|
||||||
|
className={cn("flex items-center justify-center gap-1", className)}
|
||||||
|
aria-label="分页"
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon-sm"
|
||||||
|
disabled={page <= 1}
|
||||||
|
onClick={() => onPageChange(page - 1)}
|
||||||
|
aria-label="上一页"
|
||||||
|
>
|
||||||
|
<ChevronLeftIcon className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
{items.map((p, idx) =>
|
||||||
|
p === -1 ? (
|
||||||
|
<span
|
||||||
|
key={`gap-${idx}`}
|
||||||
|
className="text-muted-foreground px-1 text-sm select-none"
|
||||||
|
>
|
||||||
|
…
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
key={p}
|
||||||
|
variant={p === page ? "default" : "outline"}
|
||||||
|
size="icon-sm"
|
||||||
|
onClick={() => onPageChange(p)}
|
||||||
|
aria-current={p === page ? "page" : undefined}
|
||||||
|
>
|
||||||
|
{p}
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon-sm"
|
||||||
|
disabled={page >= totalPages}
|
||||||
|
onClick={() => onPageChange(page + 1)}
|
||||||
|
aria-label="下一页"
|
||||||
|
>
|
||||||
|
<ChevronRightIcon className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -22,10 +22,31 @@ function ResizablePanelGroup({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// react-resizable-panels v4 changed size semantics: a bare *number* is now
|
||||||
|
// interpreted as PIXELS, while a unit-less *string* is a percentage. Every call
|
||||||
|
// site in this app passes sizes as percentages (the v2/v3 convention), so a
|
||||||
|
// value like `maxSize={60}` would otherwise pin a panel to 60px and freeze the
|
||||||
|
// layout/drag. Normalize numbers to "<n>%" to preserve the intended percentage.
|
||||||
|
const asPercent = (v: number | string | undefined) =>
|
||||||
|
typeof v === "number" ? `${v}%` : v;
|
||||||
|
|
||||||
function ResizablePanel({
|
function ResizablePanel({
|
||||||
|
defaultSize,
|
||||||
|
minSize,
|
||||||
|
maxSize,
|
||||||
|
collapsedSize,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
|
}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
|
||||||
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />;
|
return (
|
||||||
|
<ResizablePrimitive.Panel
|
||||||
|
data-slot="resizable-panel"
|
||||||
|
defaultSize={asPercent(defaultSize)}
|
||||||
|
minSize={asPercent(minSize)}
|
||||||
|
maxSize={asPercent(maxSize)}
|
||||||
|
collapsedSize={asPercent(collapsedSize)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function ResizableHandle({
|
function ResizableHandle({
|
||||||
@@ -39,14 +60,19 @@ function ResizableHandle({
|
|||||||
<ResizablePrimitive.Separator
|
<ResizablePrimitive.Separator
|
||||||
data-slot="resizable-handle"
|
data-slot="resizable-handle"
|
||||||
className={cn(
|
className={cn(
|
||||||
"bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",
|
// Thin visible divider, but a generous invisible hit area on both sides
|
||||||
|
// (after:w-4 → 16px) so the handle is easy to grab and drag. Hovering /
|
||||||
|
// dragging tints the divider so it's obvious it's interactive.
|
||||||
|
"bg-border hover:bg-primary/60 active:bg-primary relative flex w-px items-center justify-center transition-colors",
|
||||||
|
"after:absolute after:inset-y-0 after:left-1/2 after:w-4 after:-translate-x-1/2 after:cursor-col-resize",
|
||||||
|
"focus-visible:ring-ring focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden",
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{withHandle && (
|
{withHandle && (
|
||||||
<div className="bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border">
|
<div className="bg-border z-10 flex h-8 w-4 items-center justify-center rounded-sm border shadow-sm">
|
||||||
<GripVerticalIcon className="size-2.5" />
|
<GripVerticalIcon className="size-3.5" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ResizablePrimitive.Separator>
|
</ResizablePrimitive.Separator>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Loader2, MessageSquareIcon, SearchIcon, UserIcon } from "lucide-react";
|
import { ArrowDownWideNarrow, Loader2, MessageSquareIcon, SearchIcon, UserIcon } from "lucide-react";
|
||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
@@ -83,6 +83,8 @@ function UserInfoPanel({ user }: { user: UserListItem }) {
|
|||||||
<Badge variant="secondary">普通用户</Badge>
|
<Badge variant="secondary">普通用户</Badge>
|
||||||
)}
|
)}
|
||||||
</dd>
|
</dd>
|
||||||
|
<dt className="text-muted-foreground font-medium">问答次数</dt>
|
||||||
|
<dd className="tabular-nums">{user.qa_count}</dd>
|
||||||
<dt className="text-muted-foreground font-medium">Skills</dt>
|
<dt className="text-muted-foreground font-medium">Skills</dt>
|
||||||
<dd className="tabular-nums">{user.skill_count}</dd>
|
<dd className="tabular-nums">{user.skill_count}</dd>
|
||||||
<dt className="text-muted-foreground font-medium">Agents</dt>
|
<dt className="text-muted-foreground font-medium">Agents</dt>
|
||||||
@@ -300,21 +302,29 @@ export function AdminUserHub() {
|
|||||||
const { data: users, isLoading: usersLoading } = useAllUsers(true);
|
const { data: users, isLoading: usersLoading } = useAllUsers(true);
|
||||||
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
|
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
|
||||||
const [userQuery, setUserQuery] = useState("");
|
const [userQuery, setUserQuery] = useState("");
|
||||||
const [activeTab, setActiveTab] = useState<"info" | "audit" | "memory">("info");
|
// 活动审计 放到前面 → 默认进入审计标签页。
|
||||||
|
const [activeTab, setActiveTab] = useState<"audit" | "info" | "memory">("audit");
|
||||||
|
// 是否按问答次数(降序)排序用户列表。
|
||||||
|
const [sortByQa, setSortByQa] = useState(false);
|
||||||
|
|
||||||
const filteredUsers = useMemo(() => {
|
const filteredUsers = useMemo(() => {
|
||||||
const needle = userQuery.trim().toLowerCase();
|
const needle = userQuery.trim().toLowerCase();
|
||||||
const list = users ?? [];
|
let list = users ?? [];
|
||||||
return needle
|
if (needle) {
|
||||||
? list.filter((u) => u.email.toLowerCase().includes(needle))
|
list = list.filter((u) => u.email.toLowerCase().includes(needle));
|
||||||
: list;
|
}
|
||||||
}, [users, userQuery]);
|
if (sortByQa) {
|
||||||
|
// Copy before sorting so we never mutate the query cache array.
|
||||||
|
list = [...list].sort((a, b) => (b.qa_count ?? 0) - (a.qa_count ?? 0));
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}, [users, userQuery, sortByQa]);
|
||||||
|
|
||||||
const selectedUser = users?.find((u) => u.id === selectedUserId) ?? null;
|
const selectedUser = users?.find((u) => u.id === selectedUserId) ?? null;
|
||||||
|
|
||||||
function selectUser(id: string) {
|
function selectUser(id: string) {
|
||||||
setSelectedUserId(id);
|
setSelectedUserId(id);
|
||||||
setActiveTab("info");
|
setActiveTab("audit");
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -338,6 +348,20 @@ export function AdminUserHub() {
|
|||||||
className="pl-8"
|
className="pl-8"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSortByQa((v) => !v)}
|
||||||
|
className={cn(
|
||||||
|
"mx-2 mb-1 flex items-center justify-center gap-1 rounded-md border px-2 py-1 text-xs",
|
||||||
|
sortByQa
|
||||||
|
? "border-primary/40 bg-primary/5 text-primary"
|
||||||
|
: "text-muted-foreground hover:bg-muted",
|
||||||
|
)}
|
||||||
|
title="按问答次数从高到低排序"
|
||||||
|
>
|
||||||
|
<ArrowDownWideNarrow className="size-3.5" />
|
||||||
|
{sortByQa ? "按问答次数排序中" : "按问答次数排序"}
|
||||||
|
</button>
|
||||||
<ScrollArea className="min-h-0 flex-1">
|
<ScrollArea className="min-h-0 flex-1">
|
||||||
{usersLoading && (
|
{usersLoading && (
|
||||||
<div className="text-muted-foreground flex items-center justify-center gap-2 py-8 text-sm">
|
<div className="text-muted-foreground flex items-center justify-center gap-2 py-8 text-sm">
|
||||||
@@ -369,6 +393,12 @@ export function AdminUserHub() {
|
|||||||
管理员
|
管理员
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
|
<span
|
||||||
|
className="text-muted-foreground shrink-0 tabular-nums text-xs"
|
||||||
|
title="问答次数"
|
||||||
|
>
|
||||||
|
{u.qa_count ?? 0}
|
||||||
|
</span>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -388,8 +418,8 @@ export function AdminUserHub() {
|
|||||||
>
|
>
|
||||||
<div className="border-b px-4 pt-3 shrink-0">
|
<div className="border-b px-4 pt-3 shrink-0">
|
||||||
<TabsList variant="line">
|
<TabsList variant="line">
|
||||||
<TabsTrigger value="info">用户信息</TabsTrigger>
|
|
||||||
<TabsTrigger value="audit">活动审计</TabsTrigger>
|
<TabsTrigger value="audit">活动审计</TabsTrigger>
|
||||||
|
<TabsTrigger value="info">用户信息</TabsTrigger>
|
||||||
<TabsTrigger value="memory">记忆管理</TabsTrigger>
|
<TabsTrigger value="memory">记忆管理</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
InfoIcon,
|
InfoIcon,
|
||||||
LockIcon,
|
LockIcon,
|
||||||
MessageSquareIcon,
|
MessageSquareIcon,
|
||||||
|
PinIcon,
|
||||||
ShieldIcon,
|
ShieldIcon,
|
||||||
SparklesIcon,
|
SparklesIcon,
|
||||||
SquarePenIcon,
|
SquarePenIcon,
|
||||||
@@ -15,7 +16,14 @@ import {
|
|||||||
Trash2Icon,
|
Trash2Icon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import {
|
||||||
|
useEffect,
|
||||||
|
useLayoutEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
@@ -49,6 +57,7 @@ import {
|
|||||||
useSetAgentFeatured,
|
useSetAgentFeatured,
|
||||||
useSetAgentPrivate,
|
useSetAgentPrivate,
|
||||||
useToggleAgentFavorite,
|
useToggleAgentFavorite,
|
||||||
|
useToggleAgentPin,
|
||||||
useUpdateAgent,
|
useUpdateAgent,
|
||||||
} from "@/core/agents";
|
} from "@/core/agents";
|
||||||
import { getAgent } from "@/core/agents/api";
|
import { getAgent } from "@/core/agents/api";
|
||||||
@@ -61,9 +70,122 @@ import { cn } from "@/lib/utils";
|
|||||||
|
|
||||||
interface AgentCardProps {
|
interface AgentCardProps {
|
||||||
agent: Agent;
|
agent: Agent;
|
||||||
|
/** "card" (default) renders the full gallery card; "list" renders a compact
|
||||||
|
* single-row layout for the list view. All dialogs/actions are shared. */
|
||||||
|
layout?: "card" | "list";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AgentCard({ agent }: AgentCardProps) {
|
interface BadgeItem {
|
||||||
|
key: string;
|
||||||
|
node: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Minimum number of skill/tool badges to always render before collapsing the
|
||||||
|
// remainder into the "+N" chip.
|
||||||
|
const MIN_VISIBLE_BADGES = 3;
|
||||||
|
|
||||||
|
/** Render skill/tool-group badges clamped to at most two rows. Overflow is
|
||||||
|
* collapsed into a clickable "+N" chip that opens a dialog listing the full
|
||||||
|
* badge set (the visible rows stay as-is — only the chip is interactive).
|
||||||
|
*
|
||||||
|
* Badge widths are variable, so the cutoff is measured rather than assumed: an
|
||||||
|
* off-screen mirror of the full badge set is laid out at the real container
|
||||||
|
* width, and we keep only the badges that land within the first two rows
|
||||||
|
* (reserving one slot for the "+N" chip). A ResizeObserver recomputes when the
|
||||||
|
* responsive grid changes the card width.
|
||||||
|
*/
|
||||||
|
function ClampedBadgeRow({ items }: { items: BadgeItem[] }) {
|
||||||
|
const measureRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [visible, setVisible] = useState(items.length);
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false);
|
||||||
|
const sig = items.map((i) => i.key).join("|");
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const el = measureRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const compute = () => {
|
||||||
|
const kids = Array.from(el.children) as HTMLElement[];
|
||||||
|
if (kids.length === 0) {
|
||||||
|
setVisible(0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const top0 = kids[0].offsetTop;
|
||||||
|
const rowH = kids[0].offsetHeight;
|
||||||
|
// +2px fudge so the second row's badges (which may sit a hair lower due
|
||||||
|
// to line-box rounding) are not falsely treated as a third row.
|
||||||
|
const maxBottom = top0 + rowH * 2 + 2;
|
||||||
|
let count = 0;
|
||||||
|
for (const k of kids) {
|
||||||
|
if (k.offsetTop + k.offsetHeight <= maxBottom) count += 1;
|
||||||
|
else break;
|
||||||
|
}
|
||||||
|
// Reserve one slot for the "+N" chip when anything overflows so the chip
|
||||||
|
// itself never spills onto a third row.
|
||||||
|
if (count < kids.length && count > 0) count -= 1;
|
||||||
|
// Always surface a few badges before collapsing into "+N", even when the
|
||||||
|
// card is narrow enough that two rows barely fit anything (otherwise a
|
||||||
|
// skinny column could show just "+N" with no skills at all). Keeps at
|
||||||
|
// least one badge hidden so the chip still makes sense.
|
||||||
|
if (count < kids.length) {
|
||||||
|
count = Math.max(count, Math.min(MIN_VISIBLE_BADGES, kids.length - 1));
|
||||||
|
}
|
||||||
|
setVisible(count);
|
||||||
|
};
|
||||||
|
compute();
|
||||||
|
const ro = new ResizeObserver(compute);
|
||||||
|
ro.observe(el);
|
||||||
|
return () => ro.disconnect();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [sig]);
|
||||||
|
|
||||||
|
const hidden = items.length - visible;
|
||||||
|
const showChip = hidden > 0;
|
||||||
|
const shown = items.slice(0, visible);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative">
|
||||||
|
{/* Off-screen full-width mirror used only for measuring row breaks. */}
|
||||||
|
<div
|
||||||
|
ref={measureRef}
|
||||||
|
aria-hidden
|
||||||
|
className="pointer-events-none invisible absolute inset-x-0 top-0 flex flex-wrap gap-1"
|
||||||
|
>
|
||||||
|
{items.map((i) => i.node)}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
{shown.map((i) => i.node)}
|
||||||
|
{showChip && (
|
||||||
|
<Badge
|
||||||
|
variant="secondary"
|
||||||
|
className="hover:bg-secondary/70 cursor-pointer text-xs"
|
||||||
|
title="查看全部"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setDialogOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
+{hidden}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||||
|
<DialogContent className="sm:max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>全部技能与工具</DialogTitle>
|
||||||
|
<DialogDescription>共 {items.length} 项</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="flex max-h-[60vh] flex-wrap gap-1.5 overflow-y-auto py-1">
|
||||||
|
{items.map((i) => i.node)}
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AgentCard({ agent, layout = "card" }: AgentCardProps) {
|
||||||
|
const isList = layout === "list";
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const deleteAgent = useDeleteAgent();
|
const deleteAgent = useDeleteAgent();
|
||||||
@@ -72,6 +194,7 @@ export function AgentCard({ agent }: AgentCardProps) {
|
|||||||
const setFeatured = useSetAgentFeatured();
|
const setFeatured = useSetAgentFeatured();
|
||||||
const setPrivate = useSetAgentPrivate();
|
const setPrivate = useSetAgentPrivate();
|
||||||
const toggleFavorite = useToggleAgentFavorite();
|
const toggleFavorite = useToggleAgentFavorite();
|
||||||
|
const togglePin = useToggleAgentPin();
|
||||||
const { skills, isLoading: isSkillsLoading } = useSkills();
|
const { skills, isLoading: isSkillsLoading } = useSkills();
|
||||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
@@ -110,6 +233,7 @@ export function AgentCard({ agent }: AgentCardProps) {
|
|||||||
// already own, so only offer it on built-in / others' agents.
|
// already own, so only offer it on built-in / others' agents.
|
||||||
const canFavorite = !isOwned;
|
const canFavorite = !isOwned;
|
||||||
const isFavorite = !!agent.is_favorite;
|
const isFavorite = !!agent.is_favorite;
|
||||||
|
const isPinned = !!agent.is_pinned;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!editOpen) {
|
if (!editOpen) {
|
||||||
@@ -273,6 +397,16 @@ export function AgentCard({ agent }: AgentCardProps) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleTogglePin() {
|
||||||
|
const next = !isPinned;
|
||||||
|
try {
|
||||||
|
await togglePin.mutateAsync({ id: agent.id, pinned: next });
|
||||||
|
toast.success(next ? "已置顶" : "已取消置顶");
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handleToggleFeatured() {
|
async function handleToggleFeatured() {
|
||||||
// One-click on/off — ordering is handled by the dedicated 管理 Agent 列表
|
// One-click on/off — ordering is handled by the dedicated 管理 Agent 列表
|
||||||
// dialog. Featured agents get appended to the end on add (Date.now() is a
|
// dialog. Featured agents get appended to the end on add (Date.now() is a
|
||||||
@@ -304,252 +438,326 @@ export function AgentCard({ agent }: AgentCardProps) {
|
|||||||
|
|
||||||
const enabledSkills = skills.filter((skill) => skill.enabled);
|
const enabledSkills = skills.filter((skill) => skill.enabled);
|
||||||
|
|
||||||
return (
|
// Status badges (内置 / 我的 / 来自他人 / 已发布 / 私密 / 首页推荐) — shared by
|
||||||
|
// both the card header and the compact list row.
|
||||||
|
const statusBadges = (
|
||||||
<>
|
<>
|
||||||
<Card className="group flex min-w-0 flex-col transition-shadow hover:shadow-md">
|
{isBuiltin && (
|
||||||
<CardHeader className="min-w-0 pb-3">
|
<Badge variant="secondary" className="text-xs">
|
||||||
<div className="flex min-w-0 items-start justify-between gap-2">
|
内置
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
|
</Badge>
|
||||||
<div className="bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
)}
|
||||||
<BotIcon className="h-5 w-5" />
|
{isOwned && (
|
||||||
</div>
|
<Badge
|
||||||
<div className="min-w-0 flex-1 overflow-hidden">
|
variant="default"
|
||||||
<CardTitle
|
className="bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-300 text-xs"
|
||||||
className="block w-full min-w-0 overflow-hidden text-base text-ellipsis whitespace-nowrap"
|
>
|
||||||
title={desensitize(agent.name)}
|
我的
|
||||||
>
|
</Badge>
|
||||||
{desensitize(agent.name)}
|
)}
|
||||||
</CardTitle>
|
{isFromOthers && (
|
||||||
{agent.model && (
|
<Badge
|
||||||
<Badge variant="secondary" className="mt-0.5 text-xs">
|
variant="outline"
|
||||||
{desensitize(agent.model)}
|
className="border-blue-500/30 text-blue-700 dark:text-blue-300 text-xs"
|
||||||
</Badge>
|
title={agent.user_id ? `来自用户 ${agent.user_id}` : "已发布"}
|
||||||
)}
|
>
|
||||||
</div>
|
来自他人
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{isOwned && agent.published && !agent.is_private && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
|
||||||
|
title="该智能体已对所有用户可见"
|
||||||
|
>
|
||||||
|
<GlobeIcon className="size-3" />
|
||||||
|
已发布
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{agent.is_private && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-purple-500/30 text-purple-700 dark:text-purple-300 text-xs"
|
||||||
|
title="该智能体位于私密广场,需要密码才能查看"
|
||||||
|
>
|
||||||
|
<ShieldIcon className="size-3" />
|
||||||
|
私密
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{agent.featured_order != null && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-amber-500/40 text-amber-700 dark:text-amber-300 text-xs"
|
||||||
|
title="已加入首页选择器"
|
||||||
|
>
|
||||||
|
<SparklesIcon className="size-3" />
|
||||||
|
首页推荐
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
const skillBadgeItems = [
|
||||||
|
...(agent.tool_groups ?? []).map((group) => ({
|
||||||
|
key: `tg:${group}`,
|
||||||
|
node: (
|
||||||
|
<Badge key={`tg:${group}`} variant="outline" className="text-xs">
|
||||||
|
{desensitize(group)}
|
||||||
|
</Badge>
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
...(agent.skills ?? []).map((skill) => ({
|
||||||
|
key: `sk:${skill}`,
|
||||||
|
node: (
|
||||||
|
<Badge
|
||||||
|
key={`sk:${skill}`}
|
||||||
|
variant="secondary"
|
||||||
|
className="hover:bg-secondary/70 cursor-pointer text-xs"
|
||||||
|
title={t.settings.skills.viewDetailAction}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setDetailSkillName(skill);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{desensitize(skill)}
|
||||||
|
</Badge>
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
const hasSkillsOrTools =
|
||||||
|
(agent.tool_groups?.length ?? agent.skills?.length ?? 0) > 0;
|
||||||
|
|
||||||
|
const showActionRow =
|
||||||
|
canEdit || canDelete || isOwned || isAdmin || canFavorite;
|
||||||
|
|
||||||
|
// The icon action buttons, shared by both layouts.
|
||||||
|
const actionButtons = (
|
||||||
|
<>
|
||||||
|
{canFavorite && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-8 shrink-0",
|
||||||
|
!isList && "mr-auto",
|
||||||
|
isFavorite && "text-amber-500 hover:text-amber-600",
|
||||||
|
)}
|
||||||
|
onClick={() => void handleToggleFavorite()}
|
||||||
|
disabled={toggleFavorite.isPending}
|
||||||
|
title={isFavorite ? "取消收藏" : "收藏到「我的」"}
|
||||||
|
>
|
||||||
|
<StarIcon
|
||||||
|
className={cn("h-3.5 w-3.5", isFavorite && "fill-current")}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-8 shrink-0",
|
||||||
|
isPinned && "text-emerald-600 hover:text-emerald-700",
|
||||||
|
!isList && !canFavorite && "mr-auto",
|
||||||
|
)}
|
||||||
|
onClick={() => void handleTogglePin()}
|
||||||
|
disabled={togglePin.isPending}
|
||||||
|
title={isPinned ? "取消置顶" : "置顶"}
|
||||||
|
>
|
||||||
|
<PinIcon className={cn("h-3.5 w-3.5", isPinned && "fill-current")} />
|
||||||
|
</Button>
|
||||||
|
{isAdmin && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-8 shrink-0",
|
||||||
|
agent.featured_order != null &&
|
||||||
|
"text-amber-600 hover:text-amber-700",
|
||||||
|
)}
|
||||||
|
onClick={() => void handleToggleFeatured()}
|
||||||
|
disabled={setFeatured.isPending}
|
||||||
|
title={
|
||||||
|
agent.featured_order != null
|
||||||
|
? "从首页选择器移除"
|
||||||
|
: "加入首页选择器"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<SparklesIcon className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 shrink-0"
|
||||||
|
onClick={() => setTagPickerOpen(true)}
|
||||||
|
title={t.adminTags.manageTags}
|
||||||
|
>
|
||||||
|
<TagsIcon className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
{isOwned && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 shrink-0"
|
||||||
|
onClick={() => void handleTogglePublished()}
|
||||||
|
disabled={updateAgent.isPending}
|
||||||
|
title={agent.published ? "取消发布" : "发布"}
|
||||||
|
>
|
||||||
|
{agent.published ? (
|
||||||
|
<LockIcon className="h-3.5 w-3.5" />
|
||||||
|
) : (
|
||||||
|
<GlobeIcon className="h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{(isOwned || isAdmin) && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-8 shrink-0",
|
||||||
|
agent.is_private && "text-purple-600 hover:text-purple-700",
|
||||||
|
)}
|
||||||
|
onClick={() => void handleTogglePrivate()}
|
||||||
|
disabled={updateAgent.isPending || setPrivate.isPending}
|
||||||
|
title={agent.is_private ? "移出私密广场" : "放入私密广场"}
|
||||||
|
>
|
||||||
|
<ShieldIcon className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 shrink-0"
|
||||||
|
onClick={() => void handleDuplicate()}
|
||||||
|
disabled={createAgent.isPending}
|
||||||
|
title="复制为新智能体"
|
||||||
|
>
|
||||||
|
<CopyIcon className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
{canEdit && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 shrink-0"
|
||||||
|
onClick={() => setEditOpen(true)}
|
||||||
|
title="编辑智能体"
|
||||||
|
>
|
||||||
|
<SquarePenIcon className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{canDelete && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
|
||||||
|
onClick={() => setDeleteOpen(true)}
|
||||||
|
title={t.agents.delete}
|
||||||
|
>
|
||||||
|
<Trash2Icon className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
const chatButton = (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
className={cn(isList ? "shrink-0" : "w-full")}
|
||||||
|
onClick={handleChat}
|
||||||
|
>
|
||||||
|
<MessageSquareIcon className="mr-1.5 h-3.5 w-3.5" />
|
||||||
|
{t.agents.chat}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
|
||||||
|
const cardLayout = (
|
||||||
|
<Card className="group flex min-w-0 flex-col transition-shadow hover:shadow-md">
|
||||||
|
<CardHeader className="min-w-0 pb-2">
|
||||||
|
<div className="flex min-w-0 items-start justify-between gap-2">
|
||||||
|
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
|
||||||
|
<div className="bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
||||||
|
<BotIcon className="h-5 w-5" />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex shrink-0 items-center gap-1">
|
<div className="min-w-0 flex-1 overflow-hidden">
|
||||||
{isBuiltin && (
|
<CardTitle
|
||||||
<Badge variant="secondary" className="text-xs">
|
className="block w-full min-w-0 overflow-hidden text-base text-ellipsis whitespace-nowrap"
|
||||||
内置
|
title={desensitize(agent.name)}
|
||||||
</Badge>
|
>
|
||||||
)}
|
{desensitize(agent.name)}
|
||||||
{isOwned && (
|
</CardTitle>
|
||||||
<Badge
|
{agent.model && (
|
||||||
variant="default"
|
<Badge variant="secondary" className="mt-0.5 text-xs">
|
||||||
className="bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-300 text-xs"
|
{desensitize(agent.model)}
|
||||||
>
|
|
||||||
我的
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isFromOthers && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-blue-500/30 text-blue-700 dark:text-blue-300 text-xs"
|
|
||||||
title={agent.user_id ? `来自用户 ${agent.user_id}` : "已发布"}
|
|
||||||
>
|
|
||||||
来自他人
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isOwned && agent.published && !agent.is_private && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
|
|
||||||
title="该智能体已对所有用户可见"
|
|
||||||
>
|
|
||||||
<GlobeIcon className="size-3" />
|
|
||||||
已发布
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{agent.is_private && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-purple-500/30 text-purple-700 dark:text-purple-300 text-xs"
|
|
||||||
title="该智能体位于私密广场,需要密码才能查看"
|
|
||||||
>
|
|
||||||
<ShieldIcon className="size-3" />
|
|
||||||
私密
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{agent.featured_order != null && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-amber-500/40 text-amber-700 dark:text-amber-300 text-xs"
|
|
||||||
title="已加入首页选择器"
|
|
||||||
>
|
|
||||||
<SparklesIcon className="size-3" />
|
|
||||||
首页推荐
|
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{agent.description && (
|
<div className="flex shrink-0 flex-wrap items-center justify-end gap-1">
|
||||||
<CardDescription className="mt-2 line-clamp-2 text-sm">
|
{statusBadges}
|
||||||
{desensitize(agent.description)}
|
</div>
|
||||||
</CardDescription>
|
</div>
|
||||||
)}
|
{agent.description && (
|
||||||
</CardHeader>
|
<CardDescription className="mt-2 line-clamp-2 text-sm">
|
||||||
|
{desensitize(agent.description)}
|
||||||
{(agent.tags?.length ?? 0) > 0 && (
|
</CardDescription>
|
||||||
<CardContent className="pt-0 pb-2">
|
|
||||||
<TagChipList tags={agent.tags!} />
|
|
||||||
</CardContent>
|
|
||||||
)}
|
)}
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
{(agent.tool_groups?.length ?? agent.skills?.length ?? 0) > 0 && (
|
{(agent.tags?.length ?? 0) > 0 && (
|
||||||
<CardContent className="pt-0 pb-3">
|
<CardContent className="pt-0 pb-2">
|
||||||
<div className="flex flex-wrap gap-1">
|
<TagChipList tags={agent.tags!} />
|
||||||
{agent.tool_groups?.map((group) => (
|
</CardContent>
|
||||||
<Badge
|
)}
|
||||||
key={`tg:${group}`}
|
|
||||||
variant="outline"
|
{hasSkillsOrTools && (
|
||||||
className="text-xs"
|
<CardContent className="pt-0 pb-2">
|
||||||
>
|
<ClampedBadgeRow items={skillBadgeItems} />
|
||||||
{desensitize(group)}
|
</CardContent>
|
||||||
</Badge>
|
)}
|
||||||
))}
|
|
||||||
{agent.skills?.map((skill) => (
|
<CardFooter className="mt-auto flex flex-col items-stretch gap-2 pt-2">
|
||||||
<Badge
|
{showActionRow && (
|
||||||
key={`sk:${skill}`}
|
<div className="flex flex-wrap items-center justify-end gap-1">
|
||||||
variant="secondary"
|
{actionButtons}
|
||||||
className="hover:bg-secondary/70 cursor-pointer text-xs"
|
</div>
|
||||||
title={t.settings.skills.viewDetailAction}
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
setDetailSkillName(skill);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{desensitize(skill)}
|
|
||||||
</Badge>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
)}
|
)}
|
||||||
|
{chatButton}
|
||||||
|
</CardFooter>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
|
||||||
<CardFooter className="mt-auto flex flex-col items-stretch gap-2 pt-3">
|
const listLayout = (
|
||||||
{(canEdit || canDelete || isOwned || isAdmin || canFavorite) && (
|
<div className="group flex min-w-0 items-center gap-3 rounded-lg border p-2.5 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C]">
|
||||||
<div className="flex flex-wrap items-center justify-end gap-1">
|
<div className="bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
||||||
{canFavorite && (
|
<BotIcon className="h-5 w-5" />
|
||||||
<Button
|
</div>
|
||||||
size="icon"
|
<div className="min-w-0 flex-1 overflow-hidden">
|
||||||
variant="ghost"
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
className={cn(
|
<span
|
||||||
"mr-auto h-8 w-8 shrink-0",
|
className="min-w-0 truncate text-sm font-medium"
|
||||||
isFavorite && "text-amber-500 hover:text-amber-600",
|
title={desensitize(agent.name)}
|
||||||
)}
|
>
|
||||||
onClick={() => void handleToggleFavorite()}
|
{desensitize(agent.name)}
|
||||||
disabled={toggleFavorite.isPending}
|
</span>
|
||||||
title={isFavorite ? "取消收藏" : "收藏到「我的」"}
|
<div className="flex shrink-0 items-center gap-1">{statusBadges}</div>
|
||||||
>
|
</div>
|
||||||
<StarIcon
|
{agent.description && (
|
||||||
className={cn("h-3.5 w-3.5", isFavorite && "fill-current")}
|
<p className="text-muted-foreground mt-0.5 truncate text-xs">
|
||||||
/>
|
{desensitize(agent.description)}
|
||||||
</Button>
|
</p>
|
||||||
)}
|
)}
|
||||||
{isAdmin && (
|
</div>
|
||||||
<Button
|
<div className="flex shrink-0 items-center gap-1">
|
||||||
size="icon"
|
{showActionRow && actionButtons}
|
||||||
variant="ghost"
|
{chatButton}
|
||||||
className={cn(
|
</div>
|
||||||
"h-8 w-8 shrink-0",
|
</div>
|
||||||
agent.featured_order != null &&
|
);
|
||||||
"text-amber-600 hover:text-amber-700",
|
|
||||||
)}
|
return (
|
||||||
onClick={() => void handleToggleFeatured()}
|
<>
|
||||||
disabled={setFeatured.isPending}
|
{isList ? listLayout : cardLayout}
|
||||||
title={
|
|
||||||
agent.featured_order != null
|
|
||||||
? "从首页选择器移除"
|
|
||||||
: "加入首页选择器"
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<SparklesIcon className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{isAdmin && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
onClick={() => setTagPickerOpen(true)}
|
|
||||||
title={t.adminTags.manageTags}
|
|
||||||
>
|
|
||||||
<TagsIcon className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{isOwned && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
onClick={() => void handleTogglePublished()}
|
|
||||||
disabled={updateAgent.isPending}
|
|
||||||
title={agent.published ? "取消发布" : "发布"}
|
|
||||||
>
|
|
||||||
{agent.published ? (
|
|
||||||
<LockIcon className="h-3.5 w-3.5" />
|
|
||||||
) : (
|
|
||||||
<GlobeIcon className="h-3.5 w-3.5" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{(isOwned || isAdmin) && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className={cn(
|
|
||||||
"h-8 w-8 shrink-0",
|
|
||||||
agent.is_private &&
|
|
||||||
"text-purple-600 hover:text-purple-700",
|
|
||||||
)}
|
|
||||||
onClick={() => void handleTogglePrivate()}
|
|
||||||
disabled={updateAgent.isPending || setPrivate.isPending}
|
|
||||||
title={
|
|
||||||
agent.is_private ? "移出私密广场" : "放入私密广场"
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<ShieldIcon className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
onClick={() => void handleDuplicate()}
|
|
||||||
disabled={createAgent.isPending}
|
|
||||||
title="复制为新智能体"
|
|
||||||
>
|
|
||||||
<CopyIcon className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
{canEdit && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
onClick={() => setEditOpen(true)}
|
|
||||||
title="编辑智能体"
|
|
||||||
>
|
|
||||||
<SquarePenIcon className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{canDelete && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
|
|
||||||
onClick={() => setDeleteOpen(true)}
|
|
||||||
title={t.agents.delete}
|
|
||||||
>
|
|
||||||
<Trash2Icon className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button size="sm" className="w-full" onClick={handleChat}>
|
|
||||||
<MessageSquareIcon className="mr-1.5 h-3.5 w-3.5" />
|
|
||||||
{t.agents.chat}
|
|
||||||
</Button>
|
|
||||||
</CardFooter>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Dialog open={editOpen} onOpenChange={setEditOpen}>
|
<Dialog open={editOpen} onOpenChange={setEditOpen}>
|
||||||
<DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
|
<DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
|
||||||
@@ -726,15 +934,13 @@ export function AgentCard({ agent }: AgentCardProps) {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
{isAdmin && (
|
<TagPickerDialog
|
||||||
<TagPickerDialog
|
open={tagPickerOpen}
|
||||||
open={tagPickerOpen}
|
onOpenChange={setTagPickerOpen}
|
||||||
onOpenChange={setTagPickerOpen}
|
targetType="agent"
|
||||||
targetType="agent"
|
targetId={agent.id}
|
||||||
targetId={agent.id}
|
currentTags={agent.tags ?? []}
|
||||||
currentTags={agent.tags ?? []}
|
/>
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
|
|
||||||
<SkillDetailDialog
|
<SkillDetailDialog
|
||||||
|
|||||||
@@ -1,23 +1,26 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { BotIcon, LockIcon, PlusIcon, ShieldIcon } from "lucide-react";
|
import { ArrowDownUpIcon, BotIcon, LockIcon, PlusIcon, ShieldIcon } from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
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 { 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 { useAgents, usePrivateAgents } from "@/core/agents";
|
import { ViewModeToggle } from "@/components/workspace/view-mode-toggle";
|
||||||
import type { Agent } from "@/core/agents";
|
import { useAgentsPaginated, usePrivateAgentsPaginated } from "@/core/agents";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import type { Agent, AgentSort } from "@/core/agents";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
import { usePrivateSquareStatus } from "@/core/system-settings/hooks";
|
import { usePrivateSquareStatus, useViewMode } from "@/core/system-settings/hooks";
|
||||||
import { desensitize } from "@/lib/desensitize";
|
|
||||||
|
|
||||||
import { AgentCard } from "./agent-card";
|
import { AgentCard } from "./agent-card";
|
||||||
|
|
||||||
|
const PAGE_SIZE = 12;
|
||||||
|
|
||||||
// Within a single tab the verified password is kept in sessionStorage so a
|
// Within a single tab the verified password is kept in sessionStorage so a
|
||||||
// refresh / route navigation does not re-prompt. Cleared on tab close, so the
|
// refresh / route navigation does not re-prompt. Cleared on tab close, so the
|
||||||
// password never persists beyond the browsing session.
|
// password never persists beyond the browsing session.
|
||||||
@@ -26,24 +29,26 @@ const PRIVATE_SQUARE_PASSWORD_KEY = "deer-flow.private-square-password";
|
|||||||
export function AgentGallery() {
|
export function AgentGallery() {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const [viewMode, setViewMode] = useViewMode("agent");
|
||||||
const [activeTab, setActiveTab] = useState<"all" | "mine" | "private">(
|
const [activeTab, setActiveTab] = useState<"all" | "mine" | "private">(
|
||||||
"mine",
|
"mine",
|
||||||
);
|
);
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
const [tagIds, setTagIds] = useState<string[]>([]);
|
const [tagIds, setTagIds] = useState<string[]>([]);
|
||||||
// Tag filtering stays server-side; name search must run on the *desensitized*
|
const [sort, setSort] = useState<AgentSort>("time_desc");
|
||||||
// form because that's what the user sees on the card. If we sent the search
|
// Per-tab 1-based page index, preserved while switching tabs.
|
||||||
// string to the backend it would compare against the raw stored name and
|
const [pages, setPages] = useState<{ all: number; mine: number; private: number }>(
|
||||||
// miss every desensitized hit (e.g. typing "TS分析" wouldn't match the
|
{ all: 1, mine: 1, private: 1 },
|
||||||
// stored "态势分析").
|
);
|
||||||
const { agents, isLoading } = useAgents({ tagIds });
|
|
||||||
|
|
||||||
const needle = search.trim().toLowerCase();
|
// Search + tag filtering are both server-side now. The backend mirrors the
|
||||||
const matchesSearch = (a: Agent) =>
|
// frontend's desensitize map, so typing the displayed abbreviation (e.g.
|
||||||
!needle || desensitize(a.name).toLowerCase().includes(needle);
|
// "TS") still matches the stored raw name (e.g. "态势分析"). Whenever the
|
||||||
|
// filters change, every tab returns to its first page.
|
||||||
const storedAuth = useMemo(() => getStoredAuth(), []);
|
const tagKey = tagIds.join(",");
|
||||||
const currentUserId = storedAuth?.user_id ?? null;
|
useEffect(() => {
|
||||||
|
setPages({ all: 1, mine: 1, private: 1 });
|
||||||
|
}, [search, tagKey, sort]);
|
||||||
|
|
||||||
const { data: privateStatus } = usePrivateSquareStatus();
|
const { data: privateStatus } = usePrivateSquareStatus();
|
||||||
const privateFeatureAvailable = !!privateStatus?.enabled;
|
const privateFeatureAvailable = !!privateStatus?.enabled;
|
||||||
@@ -56,11 +61,37 @@ export function AgentGallery() {
|
|||||||
});
|
});
|
||||||
const [passwordInput, setPasswordInput] = useState("");
|
const [passwordInput, setPasswordInput] = useState("");
|
||||||
|
|
||||||
|
// Only the active tab fetches. "广场" maps to the server "square" scope
|
||||||
|
// (built-in/published, never private), "我的" to "mine" (owned + favorited).
|
||||||
|
const mainScope = activeTab === "mine" ? "mine" : "square";
|
||||||
|
const mainPage = activeTab === "mine" ? pages.mine : pages.all;
|
||||||
|
const {
|
||||||
|
agents: mainAgents,
|
||||||
|
total: mainTotal,
|
||||||
|
isLoading: mainLoading,
|
||||||
|
} = useAgentsPaginated({
|
||||||
|
scope: mainScope,
|
||||||
|
search,
|
||||||
|
tagIds,
|
||||||
|
sort,
|
||||||
|
page: mainPage,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
enabled: activeTab !== "private",
|
||||||
|
});
|
||||||
|
|
||||||
const {
|
const {
|
||||||
agents: privateAgents,
|
agents: privateAgents,
|
||||||
|
total: privateTotal,
|
||||||
isLoading: isPrivateLoading,
|
isLoading: isPrivateLoading,
|
||||||
error: privateError,
|
error: privateError,
|
||||||
} = usePrivateAgents(privatePassword);
|
} = usePrivateAgentsPaginated(privatePassword, {
|
||||||
|
search,
|
||||||
|
tagIds,
|
||||||
|
sort,
|
||||||
|
page: pages.private,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
enabled: activeTab === "private",
|
||||||
|
});
|
||||||
|
|
||||||
// If the server reports the stored password no longer works (likely the
|
// If the server reports the stored password no longer works (likely the
|
||||||
// admin rotated it), drop it from session storage and re-prompt.
|
// admin rotated it), drop it from session storage and re-prompt.
|
||||||
@@ -72,49 +103,9 @@ export function AgentGallery() {
|
|||||||
}
|
}
|
||||||
}, [privateError, privatePassword]);
|
}, [privateError, privatePassword]);
|
||||||
|
|
||||||
// The "广场" tab must never surface private-square agents, even to their
|
const activeTotal = activeTab === "private" ? privateTotal : mainTotal;
|
||||||
// own owner — moving an agent into the private square is supposed to hide
|
const setTabPage = (tab: "all" | "mine" | "private", page: number) =>
|
||||||
// it from the public square entirely. (The backend listing endpoint
|
setPages((prev) => ({ ...prev, [tab]: page }));
|
||||||
// already filters them out for non-owners; this extra clause covers the
|
|
||||||
// owner's own private agents, which still come back in the unified list
|
|
||||||
// because owners always see their own.)
|
|
||||||
const allAgents = useMemo(
|
|
||||||
() =>
|
|
||||||
agents.filter(
|
|
||||||
(a) => (a.builtin || a.published) && !a.is_private && matchesSearch(a),
|
|
||||||
),
|
|
||||||
// matchesSearch closes over `needle`; depending on `search` is sufficient
|
|
||||||
// and avoids re-running on every render via the function reference.
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
[agents, search],
|
|
||||||
);
|
|
||||||
|
|
||||||
// "我的" shows the user's own agents plus any agent they've favorited (收藏)
|
|
||||||
// from the square — favorited public agents have a different user_id but a
|
|
||||||
// truthy is_favorite flag.
|
|
||||||
const myAgents = useMemo(
|
|
||||||
() =>
|
|
||||||
agents.filter(
|
|
||||||
(a) =>
|
|
||||||
((a.user_id !== null && a.user_id === currentUserId) ||
|
|
||||||
a.is_favorite) &&
|
|
||||||
matchesSearch(a),
|
|
||||||
),
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
[agents, currentUserId, search],
|
|
||||||
);
|
|
||||||
|
|
||||||
const filteredPrivateAgents = useMemo(() => {
|
|
||||||
const wanted = new Set(tagIds);
|
|
||||||
return privateAgents.filter((a) => {
|
|
||||||
if (!matchesSearch(a)) return false;
|
|
||||||
if (wanted.size > 0) {
|
|
||||||
if (!(a.tags ?? []).some((tg) => wanted.has(tg.id))) return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [privateAgents, search, tagIds]);
|
|
||||||
|
|
||||||
const handleNewAgent = () => {
|
const handleNewAgent = () => {
|
||||||
router.push("/page/workspace/agents/new");
|
router.push("/page/workspace/agents/new");
|
||||||
@@ -136,13 +127,56 @@ export function AgentGallery() {
|
|||||||
setPrivatePassword(null);
|
setPrivatePassword(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderGrid = (list: typeof agents) => (
|
const renderGrid = (list: Agent[]) =>
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
viewMode === "list" ? (
|
||||||
{list.map((agent) => (
|
<div className="flex flex-col gap-2">
|
||||||
<AgentCard key={agent.id} agent={agent} />
|
{list.map((agent) => (
|
||||||
))}
|
<AgentCard key={agent.id} agent={agent} layout="list" />
|
||||||
</div>
|
))}
|
||||||
);
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
|
{list.map((agent) => (
|
||||||
|
<AgentCard key={agent.id} agent={agent} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Loading / empty / (grid + pagination) for one paginated tab. */
|
||||||
|
const renderListBody = (opts: {
|
||||||
|
list: Agent[];
|
||||||
|
total: number;
|
||||||
|
isLoading: boolean;
|
||||||
|
tab: "all" | "mine" | "private";
|
||||||
|
emptyDescription: string;
|
||||||
|
showNewButton?: boolean;
|
||||||
|
}) => {
|
||||||
|
const { list, total, isLoading, tab, emptyDescription, showNewButton } = opts;
|
||||||
|
// keepPreviousData keeps the old page visible while a new page loads, so
|
||||||
|
// only show the spinner on the very first load (no rows yet).
|
||||||
|
if (isLoading && list.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
|
||||||
|
{t.common.loading}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (list.length === 0) {
|
||||||
|
return renderEmpty(emptyDescription, showNewButton);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
{renderGrid(list)}
|
||||||
|
<Pagination
|
||||||
|
page={pages[tab]}
|
||||||
|
pageSize={PAGE_SIZE}
|
||||||
|
total={total}
|
||||||
|
onPageChange={(p) => setTabPage(tab, p)}
|
||||||
|
className="pt-2"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const renderEmpty = (description: string, showNewButton = false) => (
|
const renderEmpty = (description: string, showNewButton = false) => (
|
||||||
<div className="flex h-64 flex-col items-center justify-center gap-3 text-center">
|
<div className="flex h-64 flex-col items-center justify-center gap-3 text-center">
|
||||||
@@ -218,6 +252,15 @@ export function AgentGallery() {
|
|||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === "Enter") handleSubmitPassword();
|
if (e.key === "Enter") handleSubmitPassword();
|
||||||
}}
|
}}
|
||||||
|
// This is a one-off access code, not a login credential. Tell
|
||||||
|
// browsers / password managers not to save or autofill it (which
|
||||||
|
// would also stop them from spilling a saved account into the
|
||||||
|
// name search box on this page).
|
||||||
|
name="private-square-access-code"
|
||||||
|
autoComplete="off"
|
||||||
|
data-1p-ignore
|
||||||
|
data-lpignore="true"
|
||||||
|
data-form-type="other"
|
||||||
/>
|
/>
|
||||||
<Button onClick={handleSubmitPassword}>进入私密广场</Button>
|
<Button onClick={handleSubmitPassword}>进入私密广场</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -225,19 +268,13 @@ export function AgentGallery() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isPrivateLoading) {
|
return renderListBody({
|
||||||
return (
|
list: privateAgents,
|
||||||
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
|
total: privateTotal,
|
||||||
{t.common.loading}
|
isLoading: isPrivateLoading,
|
||||||
</div>
|
tab: "private",
|
||||||
);
|
emptyDescription: "私密广场暂时还没有智能体。",
|
||||||
}
|
});
|
||||||
|
|
||||||
if (filteredPrivateAgents.length === 0) {
|
|
||||||
return renderEmpty("私密广场暂时还没有智能体。");
|
|
||||||
}
|
|
||||||
|
|
||||||
return renderGrid(filteredPrivateAgents);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -276,48 +313,70 @@ export function AgentGallery() {
|
|||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
)}
|
)}
|
||||||
</TabsList>
|
</TabsList>
|
||||||
{activeTab === "private" && privatePassword && (
|
<div className="flex items-center gap-3">
|
||||||
<Button
|
<span className="text-muted-foreground text-sm whitespace-nowrap">
|
||||||
variant="outline"
|
共 {activeTotal} 个
|
||||||
size="sm"
|
</span>
|
||||||
onClick={handleLockPrivate}
|
<ViewModeToggle value={viewMode} onChange={setViewMode} />
|
||||||
title="锁定私密广场,下次需要重新输入密码"
|
{activeTab === "private" && privatePassword && (
|
||||||
>
|
<Button
|
||||||
<LockIcon className="mr-1.5 h-3.5 w-3.5" />
|
variant="outline"
|
||||||
锁定
|
size="sm"
|
||||||
</Button>
|
onClick={handleLockPrivate}
|
||||||
)}
|
title="锁定私密广场,下次需要重新输入密码"
|
||||||
|
>
|
||||||
|
<LockIcon className="mr-1.5 h-3.5 w-3.5" />
|
||||||
|
锁定
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<TagSearchBar
|
<TagSearchBar
|
||||||
targetType="agent"
|
targetType="agent"
|
||||||
onSearchChange={setSearch}
|
onSearchChange={setSearch}
|
||||||
tagIds={tagIds}
|
tagIds={tagIds}
|
||||||
onTagIdsChange={setTagIds}
|
onTagIdsChange={setTagIds}
|
||||||
|
actions={
|
||||||
|
<Select value={sort} onValueChange={(v) => setSort(v as AgentSort)}>
|
||||||
|
<SelectTrigger
|
||||||
|
className="h-9 w-full gap-2 px-3 text-xs sm:w-[148px]"
|
||||||
|
title="排序"
|
||||||
|
>
|
||||||
|
<ArrowDownUpIcon className="text-muted-foreground size-3.5" />
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent position="popper" side="bottom" sideOffset={4}>
|
||||||
|
<SelectItem value="time_desc">最新创建</SelectItem>
|
||||||
|
<SelectItem value="time_asc">最早创建</SelectItem>
|
||||||
|
<SelectItem value="updated_desc">最近更新</SelectItem>
|
||||||
|
<SelectItem value="updated_asc">最早更新</SelectItem>
|
||||||
|
<SelectItem value="name_asc">名称 A-Z</SelectItem>
|
||||||
|
<SelectItem value="name_desc">名称 Z-A</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<TabsContent value="all" className="flex-1 overflow-y-auto p-6 mt-0">
|
<TabsContent value="all" className="flex-1 overflow-y-auto p-6 mt-0">
|
||||||
{isLoading ? (
|
{renderListBody({
|
||||||
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
|
list: mainAgents,
|
||||||
{t.common.loading}
|
total: mainTotal,
|
||||||
</div>
|
isLoading: mainLoading,
|
||||||
) : allAgents.length === 0 ? (
|
tab: "all",
|
||||||
renderEmpty(t.agents.emptyDescription)
|
emptyDescription: t.agents.emptyDescription,
|
||||||
) : (
|
})}
|
||||||
renderGrid(allAgents)
|
|
||||||
)}
|
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="mine" className="flex-1 overflow-y-auto p-6 mt-0">
|
<TabsContent value="mine" className="flex-1 overflow-y-auto p-6 mt-0">
|
||||||
{isLoading ? (
|
{renderListBody({
|
||||||
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
|
list: mainAgents,
|
||||||
{t.common.loading}
|
total: mainTotal,
|
||||||
</div>
|
isLoading: mainLoading,
|
||||||
) : myAgents.length === 0 ? (
|
tab: "mine",
|
||||||
renderEmpty(t.agents.emptyDescription, true)
|
emptyDescription: t.agents.emptyDescription,
|
||||||
) : (
|
showNewButton: true,
|
||||||
renderGrid(myAgents)
|
})}
|
||||||
)}
|
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
{privateFeatureAvailable && (
|
{privateFeatureAvailable && (
|
||||||
|
|||||||
@@ -136,21 +136,21 @@ export function AgentManageDialog({
|
|||||||
{agents.map((agent, index) => (
|
{agents.map((agent, index) => (
|
||||||
<div
|
<div
|
||||||
key={agent.id}
|
key={agent.id}
|
||||||
className="flex items-center gap-2 px-3 py-2 hover:bg-accent/30"
|
className="flex min-w-0 items-start gap-2 px-3 py-2 hover:bg-accent/30"
|
||||||
>
|
>
|
||||||
<span className="text-muted-foreground w-6 shrink-0 text-center text-xs tabular-nums">
|
<span className="text-muted-foreground w-6 shrink-0 text-center text-xs tabular-nums">
|
||||||
{index + 1}
|
{index + 1}
|
||||||
</span>
|
</span>
|
||||||
<BotIcon className="text-muted-foreground size-4 shrink-0" />
|
<BotIcon className="text-muted-foreground mt-0.5 size-4 shrink-0" />
|
||||||
<div className="flex min-w-0 flex-1 flex-col">
|
<div className="flex min-w-0 flex-1 flex-col">
|
||||||
<span className="truncate text-sm">{agent.name}</span>
|
<span className="truncate text-sm">{agent.name}</span>
|
||||||
{agent.description && (
|
{agent.description && (
|
||||||
<span className="truncate text-[11px] text-muted-foreground">
|
<span className="line-clamp-2 whitespace-normal break-words text-[11px] leading-snug text-muted-foreground">
|
||||||
{agent.description}
|
{agent.description}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-0.5">
|
<div className="flex shrink-0 items-center gap-0.5">
|
||||||
<Tooltip content="上移">
|
<Tooltip content="上移">
|
||||||
<Button
|
<Button
|
||||||
size="icon"
|
size="icon"
|
||||||
@@ -222,12 +222,13 @@ export function AgentManageDialog({
|
|||||||
key={agent.id}
|
key={agent.id}
|
||||||
value={`${agent.name} ${agent.description ?? ""}`}
|
value={`${agent.name} ${agent.description ?? ""}`}
|
||||||
onSelect={() => void add(agent)}
|
onSelect={() => void add(agent)}
|
||||||
|
className="flex w-full min-w-0 items-start overflow-hidden"
|
||||||
>
|
>
|
||||||
<BotIcon className="text-muted-foreground mr-2 size-4 shrink-0" />
|
<BotIcon className="text-muted-foreground mr-2 mt-0.5 size-4 shrink-0" />
|
||||||
<div className="flex min-w-0 flex-1 flex-col">
|
<div className="flex min-w-0 flex-1 flex-col">
|
||||||
<span className="truncate text-sm">{agent.name}</span>
|
<span className="truncate text-sm">{agent.name}</span>
|
||||||
{agent.description && (
|
{agent.description && (
|
||||||
<span className="truncate text-[10px] text-muted-foreground">
|
<span className="line-clamp-2 whitespace-normal break-words text-[10px] leading-snug text-muted-foreground">
|
||||||
{agent.description}
|
{agent.description}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -120,15 +120,15 @@ export function AgentSelector({
|
|||||||
value={`${agent.name} ${agent.description ?? ""}`}
|
value={`${agent.name} ${agent.description ?? ""}`}
|
||||||
onSelect={() => handleSelect(agent)}
|
onSelect={() => handleSelect(agent)}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex items-center gap-2",
|
"flex w-full min-w-0 items-start gap-2 overflow-hidden",
|
||||||
agent.id === selectedAgentId && "bg-accent",
|
agent.id === selectedAgentId && "bg-accent",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<BotIcon className="text-muted-foreground size-4 shrink-0" />
|
<BotIcon className="text-muted-foreground mt-0.5 size-4 shrink-0" />
|
||||||
<div className="flex min-w-0 flex-1 flex-col">
|
<div className="flex min-w-0 flex-1 flex-col">
|
||||||
<span className="truncate text-sm">{agent.name}</span>
|
<span className="truncate text-sm">{agent.name}</span>
|
||||||
{agent.description && (
|
{agent.description && (
|
||||||
<span className="truncate text-[10px] text-muted-foreground">
|
<span className="line-clamp-2 whitespace-normal break-words text-[10px] leading-snug text-muted-foreground">
|
||||||
{agent.description}
|
{agent.description}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
XIcon,
|
XIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import type { AnchorHTMLAttributes, HTMLAttributes, ReactNode } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { Streamdown } from "streamdown";
|
import { Streamdown } from "streamdown";
|
||||||
|
|
||||||
@@ -43,7 +44,7 @@ import {
|
|||||||
useArtifactContent,
|
useArtifactContent,
|
||||||
useUpdateArtifactContent,
|
useUpdateArtifactContent,
|
||||||
} from "@/core/artifacts/hooks";
|
} from "@/core/artifacts/hooks";
|
||||||
import { urlOfArtifact } from "@/core/artifacts/utils";
|
import { resolveArtifactURL, urlOfArtifact } from "@/core/artifacts/utils";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx";
|
import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx";
|
||||||
import { installSkill } from "@/core/skills/api";
|
import { installSkill } from "@/core/skills/api";
|
||||||
@@ -53,8 +54,19 @@ import {
|
|||||||
getFileName,
|
getFileName,
|
||||||
isImageFile,
|
isImageFile,
|
||||||
} from "@/core/utils/files";
|
} from "@/core/utils/files";
|
||||||
|
import {
|
||||||
|
downloadMermaidSvgFile,
|
||||||
|
isMermaidFile,
|
||||||
|
openMermaidSvgInNewTab,
|
||||||
|
renderMermaidToSvg,
|
||||||
|
} from "@/core/utils/mermaid";
|
||||||
|
import {
|
||||||
|
createMarkdownAnchorResolver,
|
||||||
|
injectInPageAnchorHandler,
|
||||||
|
isInPageAnchor,
|
||||||
|
scrollToInPageAnchor,
|
||||||
|
} from "@/core/utils/markdown";
|
||||||
import { getBackendBaseURL } from "@/core/config";
|
import { getBackendBaseURL } from "@/core/config";
|
||||||
import { resolveArtifactURL } from "@/core/artifacts/utils";
|
|
||||||
import { env } from "@/env";
|
import { env } from "@/env";
|
||||||
import { desensitize } from "@/lib/desensitize";
|
import { desensitize } from "@/lib/desensitize";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -67,6 +79,12 @@ import { useArtifacts } from "./context";
|
|||||||
|
|
||||||
const SANDBOX_RESUME_EVENT = "workspace:sandbox-resume-autoscroll";
|
const SANDBOX_RESUME_EVENT = "workspace:sandbox-resume-autoscroll";
|
||||||
|
|
||||||
|
function extractTextFromChildren(children: ReactNode): string {
|
||||||
|
if (typeof children === "string" || typeof children === "number") return String(children);
|
||||||
|
if (Array.isArray(children)) return children.map(extractTextFromChildren).join("");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
function findScrollableArtifactElement(root: HTMLElement | null) {
|
function findScrollableArtifactElement(root: HTMLElement | null) {
|
||||||
if (!root) {
|
if (!root) {
|
||||||
return null;
|
return null;
|
||||||
@@ -131,7 +149,11 @@ export function ArtifactFileDetail({
|
|||||||
return checkCodeFile(filepath);
|
return checkCodeFile(filepath);
|
||||||
}, [filepath, useWriteFileStreaming, isSkillFile]);
|
}, [filepath, useWriteFileStreaming, isSkillFile]);
|
||||||
const isSupportPreview = useMemo(() => {
|
const isSupportPreview = useMemo(() => {
|
||||||
return language === "html" || language === "markdown";
|
return (
|
||||||
|
language === "html" ||
|
||||||
|
language === "markdown" ||
|
||||||
|
language === "mermaid"
|
||||||
|
);
|
||||||
}, [language]);
|
}, [language]);
|
||||||
const { content, isApplyingEdit } = useArtifactContent({
|
const { content, isApplyingEdit } = useArtifactContent({
|
||||||
threadId,
|
threadId,
|
||||||
@@ -152,6 +174,7 @@ export function ArtifactFileDetail({
|
|||||||
const hasMultipleArtifacts = (artifacts?.length ?? 0) > 1;
|
const hasMultipleArtifacts = (artifacts?.length ?? 0) > 1;
|
||||||
const fileTypeLabel = useMemo(() => {
|
const fileTypeLabel = useMemo(() => {
|
||||||
if (isImageFile(filepath)) return "IMG";
|
if (isImageFile(filepath)) return "IMG";
|
||||||
|
if (isMermaidFile(filepath) || language === "mermaid") return "MMD";
|
||||||
if (language === "html") return "HTML";
|
if (language === "html") return "HTML";
|
||||||
if (language === "markdown") return "MD";
|
if (language === "markdown") return "MD";
|
||||||
if (isSkillFile) return "SKILL";
|
if (isSkillFile) return "SKILL";
|
||||||
@@ -423,6 +446,13 @@ export function ArtifactFileDetail({
|
|||||||
toast.error("文件内容为空,暂时无法打开");
|
toast.error("文件内容为空,暂时无法打开");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (language === "mermaid") {
|
||||||
|
void openMermaidSvgInNewTab(source).catch((error) => {
|
||||||
|
console.error("Failed to open mermaid artifact:", error);
|
||||||
|
toast.error(error instanceof Error ? error.message : "Failed to open artifact");
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
const blobType =
|
const blobType =
|
||||||
language === "html"
|
language === "html"
|
||||||
? "text/html;charset=utf-8"
|
? "text/html;charset=utf-8"
|
||||||
@@ -441,6 +471,13 @@ export function ArtifactFileDetail({
|
|||||||
toast.error("文件内容为空,暂时无法下载");
|
toast.error("文件内容为空,暂时无法下载");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (language === "mermaid") {
|
||||||
|
void downloadMermaidSvgFile(source, filepath).catch((error) => {
|
||||||
|
console.error("Failed to download mermaid artifact:", error);
|
||||||
|
toast.error(error instanceof Error ? error.message : "Download failed");
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
const blobType =
|
const blobType =
|
||||||
language === "html"
|
language === "html"
|
||||||
? "text/html;charset=utf-8"
|
? "text/html;charset=utf-8"
|
||||||
@@ -567,6 +604,19 @@ export function ArtifactFileDetail({
|
|||||||
handleOpenWriteFileInNewTab();
|
handleOpenWriteFileInNewTab();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (language === "mermaid") {
|
||||||
|
try {
|
||||||
|
await openMermaidSvgInNewTab(displayContent ?? "");
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
toast.error(
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Failed to open artifact",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
await openArtifactInNewTab({
|
await openArtifactInNewTab({
|
||||||
filepath,
|
filepath,
|
||||||
@@ -619,6 +669,19 @@ export function ArtifactFileDetail({
|
|||||||
handleDownloadWriteFile();
|
handleDownloadWriteFile();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (language === "mermaid") {
|
||||||
|
try {
|
||||||
|
await downloadMermaidSvgFile(displayContent ?? "", filepath);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
toast.error(
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Download failed",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
await downloadArtifactFile({
|
await downloadArtifactFile({
|
||||||
filepath,
|
filepath,
|
||||||
@@ -669,7 +732,9 @@ export function ArtifactFileDetail({
|
|||||||
)}
|
)}
|
||||||
{isSupportPreview &&
|
{isSupportPreview &&
|
||||||
viewMode === "preview" &&
|
viewMode === "preview" &&
|
||||||
(language === "markdown" || language === "html") && (
|
(language === "markdown" ||
|
||||||
|
language === "html" ||
|
||||||
|
language === "mermaid") && (
|
||||||
<ArtifactFilePreview
|
<ArtifactFilePreview
|
||||||
content={desensitize(displayContent ?? "")}
|
content={desensitize(displayContent ?? "")}
|
||||||
language={language ?? "text"}
|
language={language ?? "text"}
|
||||||
@@ -770,6 +835,66 @@ export function ArtifactFilePreview({
|
|||||||
activeCursor?: boolean;
|
activeCursor?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [htmlPreviewUrl, setHtmlPreviewUrl] = useState<string>();
|
const [htmlPreviewUrl, setHtmlPreviewUrl] = useState<string>();
|
||||||
|
const [mermaidSvg, setMermaidSvg] = useState<string | null>(null);
|
||||||
|
const [mermaidError, setMermaidError] = useState<string | null>(null);
|
||||||
|
const markdownComponents = useMemo(() => {
|
||||||
|
const anchorResolver = createMarkdownAnchorResolver(content ?? "");
|
||||||
|
const heading = (level: 1 | 2 | 3 | 4 | 5 | 6) => {
|
||||||
|
const Tag = `h${level}` as const;
|
||||||
|
return ({ children, id, ...props }: HTMLAttributes<HTMLHeadingElement>) => (
|
||||||
|
<Tag id={id ?? anchorResolver.getHeadingId(level, extractTextFromChildren(children))} {...props}>
|
||||||
|
{children}
|
||||||
|
</Tag>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
h1: heading(1),
|
||||||
|
h2: heading(2),
|
||||||
|
h3: heading(3),
|
||||||
|
h4: heading(4),
|
||||||
|
h5: heading(5),
|
||||||
|
h6: heading(6),
|
||||||
|
a: (props: AnchorHTMLAttributes<HTMLAnchorElement>) => {
|
||||||
|
if (typeof props.children === "string" && /^citation:(.+)$/.test(props.children)) {
|
||||||
|
return <ArtifactLink {...props} />;
|
||||||
|
}
|
||||||
|
const { className, ...rest } = props;
|
||||||
|
const resolvedHref = anchorResolver.resolveHref(
|
||||||
|
props.href,
|
||||||
|
extractTextFromChildren(props.children),
|
||||||
|
);
|
||||||
|
if (resolvedHref === null) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"text-primary/80 decoration-dotted underline underline-offset-2 cursor-not-allowed",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
title="未在当前 Markdown 中找到对应章节"
|
||||||
|
>
|
||||||
|
{props.children}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const finalHref = resolvedHref ?? props.href;
|
||||||
|
return (
|
||||||
|
<ArtifactLink
|
||||||
|
{...rest}
|
||||||
|
className={className}
|
||||||
|
href={finalHref}
|
||||||
|
onClick={(event) => {
|
||||||
|
if (isInPageAnchor(finalHref)) {
|
||||||
|
event.preventDefault();
|
||||||
|
scrollToInPageAnchor(event.currentTarget, finalHref);
|
||||||
|
}
|
||||||
|
rest.onClick?.(event);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}, [content]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (language !== "html") {
|
if (language !== "html") {
|
||||||
@@ -780,7 +905,11 @@ export function ArtifactFilePreview({
|
|||||||
// 必须带 charset=utf-8:blob: URL 的 Content-Type 不含 charset 时,iframe 会按
|
// 必须带 charset=utf-8:blob: URL 的 Content-Type 不含 charset 时,iframe 会按
|
||||||
// 系统默认编码(中文 Windows 常为 GBK/Latin-1)解码,模型生成的 HTML 若没写
|
// 系统默认编码(中文 Windows 常为 GBK/Latin-1)解码,模型生成的 HTML 若没写
|
||||||
// <meta charset> 就会中文乱码。与下方下载/新窗口打开的 blobType 保持一致。
|
// <meta charset> 就会中文乱码。与下方下载/新窗口打开的 blobType 保持一致。
|
||||||
const blob = new Blob([content ?? ""], { type: "text/html;charset=utf-8" });
|
// Intercept in-page anchor clicks so they scroll within the iframe instead
|
||||||
|
// of navigating the sandboxed blob: document (which blanks the frame).
|
||||||
|
const blob = new Blob([injectInPageAnchorHandler(content ?? "")], {
|
||||||
|
type: "text/html;charset=utf-8",
|
||||||
|
});
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
setHtmlPreviewUrl(url);
|
setHtmlPreviewUrl(url);
|
||||||
|
|
||||||
@@ -789,10 +918,42 @@ export function ArtifactFilePreview({
|
|||||||
};
|
};
|
||||||
}, [content, language]);
|
}, [content, language]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (language !== "mermaid") {
|
||||||
|
setMermaidSvg(null);
|
||||||
|
setMermaidError(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cancelled = false;
|
||||||
|
setMermaidSvg(null);
|
||||||
|
setMermaidError(null);
|
||||||
|
|
||||||
|
void renderMermaidToSvg(content ?? "")
|
||||||
|
.then((svg) => {
|
||||||
|
if (!cancelled) {
|
||||||
|
setMermaidSvg(svg);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error("Failed to render mermaid preview:", error);
|
||||||
|
if (!cancelled) {
|
||||||
|
setMermaidError(
|
||||||
|
error instanceof Error ? error.message : "Mermaid 渲染失败",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [content, language]);
|
||||||
|
|
||||||
if (language === "markdown") {
|
if (language === "markdown") {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-artifact-preview-scroll
|
data-artifact-preview-scroll
|
||||||
|
data-markdown-anchor-root
|
||||||
className={cn(
|
className={cn(
|
||||||
"size-full overflow-auto px-5 py-4",
|
"size-full overflow-auto px-5 py-4",
|
||||||
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
|
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
|
||||||
@@ -802,7 +963,7 @@ export function ArtifactFilePreview({
|
|||||||
className="size-full"
|
className="size-full"
|
||||||
{...streamdownPlugins}
|
{...streamdownPlugins}
|
||||||
components={{
|
components={{
|
||||||
a: ArtifactLink,
|
...markdownComponents,
|
||||||
img: (props) => (
|
img: (props) => (
|
||||||
<SandboxPreviewImage
|
<SandboxPreviewImage
|
||||||
{...props}
|
{...props}
|
||||||
@@ -835,5 +996,38 @@ export function ArtifactFilePreview({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (language === "mermaid") {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-artifact-preview-scroll
|
||||||
|
className={cn(
|
||||||
|
"size-full overflow-auto bg-[#fcfdfc] px-5 py-4",
|
||||||
|
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{mermaidSvg ? (
|
||||||
|
<div
|
||||||
|
className="mx-auto flex min-h-full items-start justify-center rounded-2xl border border-slate-200 bg-white p-4 shadow-sm"
|
||||||
|
dangerouslySetInnerHTML={{ __html: mermaidSvg }}
|
||||||
|
/>
|
||||||
|
) : mermaidError ? (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
|
||||||
|
{mermaidError}
|
||||||
|
</div>
|
||||||
|
<pre className="whitespace-pre-wrap break-words rounded-xl bg-slate-100 p-4 text-xs text-slate-700">
|
||||||
|
{content ?? ""}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-muted-foreground flex size-full items-center justify-center gap-2 text-sm">
|
||||||
|
<LoaderIcon className="size-5 animate-spin" />
|
||||||
|
正在生成图表预览
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -19,32 +19,43 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { useAgentSelector } from "@/core/agents/hooks";
|
||||||
import {
|
import {
|
||||||
useCreateCustomPrompt,
|
useCreateCustomPrompt,
|
||||||
useCustomPrompts,
|
useCustomPrompts,
|
||||||
useDeleteCustomPrompt,
|
useDeleteCustomPrompt,
|
||||||
useUpdateCustomPrompt,
|
useUpdateCustomPrompt,
|
||||||
} from "@/core/custom-prompts";
|
} from "@/core/custom-prompts";
|
||||||
|
import {
|
||||||
|
useUpdateUserPreferences,
|
||||||
|
useUserPreferences,
|
||||||
|
} from "@/core/user-preferences";
|
||||||
|
import { desensitize } from "@/lib/desensitize";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
/**
|
|
||||||
* Bar above the chat input showing the user's saved prompts as centered,
|
|
||||||
* clickable chips. When there are too many to fit, they become a horizontal
|
|
||||||
* carousel (arrows appear). A gear pinned to the far right opens the manage
|
|
||||||
* dialog. Prompts are bound to the account (server-backed), and this coexists
|
|
||||||
* with the admin-configured global prompt prefix.
|
|
||||||
*/
|
|
||||||
export function CustomPromptBar({
|
export function CustomPromptBar({
|
||||||
onInsert,
|
onInsert,
|
||||||
className,
|
className,
|
||||||
|
currentAgentId,
|
||||||
}: {
|
}: {
|
||||||
onInsert: (content: string) => void;
|
onInsert: (content: string) => void;
|
||||||
className?: string;
|
className?: string;
|
||||||
|
currentAgentId?: string | null;
|
||||||
}) {
|
}) {
|
||||||
const prompts = useCustomPrompts();
|
const allPrompts = useCustomPrompts();
|
||||||
|
const prompts = allPrompts.filter(
|
||||||
|
(prompt) => !prompt.agent_id || prompt.agent_id === currentAgentId,
|
||||||
|
);
|
||||||
const [manageOpen, setManageOpen] = useState(false);
|
const [manageOpen, setManageOpen] = useState(false);
|
||||||
|
|
||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
const scrollRef = useRef<HTMLDivElement>(null);
|
||||||
const [canLeft, setCanLeft] = useState(false);
|
const [canLeft, setCanLeft] = useState(false);
|
||||||
const [canRight, setCanRight] = useState(false);
|
const [canRight, setCanRight] = useState(false);
|
||||||
@@ -60,7 +71,7 @@ export function CustomPromptBar({
|
|||||||
updateArrows();
|
updateArrows();
|
||||||
window.addEventListener("resize", updateArrows);
|
window.addEventListener("resize", updateArrows);
|
||||||
return () => window.removeEventListener("resize", updateArrows);
|
return () => window.removeEventListener("resize", updateArrows);
|
||||||
}, [updateArrows, prompts]);
|
}, [prompts, updateArrows]);
|
||||||
|
|
||||||
const scrollByDir = (dir: 1 | -1) => {
|
const scrollByDir = (dir: 1 | -1) => {
|
||||||
scrollRef.current?.scrollBy({ left: dir * 220, behavior: "smooth" });
|
scrollRef.current?.scrollBy({ left: dir * 220, behavior: "smooth" });
|
||||||
@@ -70,7 +81,7 @@ export function CustomPromptBar({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className={cn("flex items-center gap-1", className)}>
|
<div className={cn("flex min-w-0 items-center gap-1", className)}>
|
||||||
{prompts.length > 0 && (
|
{prompts.length > 0 && (
|
||||||
<>
|
<>
|
||||||
{overflowing && (
|
{overflowing && (
|
||||||
@@ -89,7 +100,7 @@ export function CustomPromptBar({
|
|||||||
<div
|
<div
|
||||||
ref={scrollRef}
|
ref={scrollRef}
|
||||||
onScroll={updateArrows}
|
onScroll={updateArrows}
|
||||||
className="flex-1 overflow-x-auto [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
className="min-w-0 flex-1 overflow-x-auto [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||||
>
|
>
|
||||||
<div className="mx-auto flex w-max items-center gap-1.5 px-0.5 py-0.5">
|
<div className="mx-auto flex w-max items-center gap-1.5 px-0.5 py-0.5">
|
||||||
{prompts.map((prompt) => (
|
{prompts.map((prompt) => (
|
||||||
@@ -123,7 +134,7 @@ export function CustomPromptBar({
|
|||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{prompts.length === 0 && <div className="flex-1" />}
|
{prompts.length === 0 && <div className="min-w-0 flex-1" />}
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -153,16 +164,26 @@ function ManagePromptsDialog({
|
|||||||
const createPrompt = useCreateCustomPrompt();
|
const createPrompt = useCreateCustomPrompt();
|
||||||
const updatePrompt = useUpdateCustomPrompt();
|
const updatePrompt = useUpdateCustomPrompt();
|
||||||
const deletePrompt = useDeleteCustomPrompt();
|
const deletePrompt = useDeleteCustomPrompt();
|
||||||
|
const { agents } = useAgentSelector();
|
||||||
|
const preferences = useUserPreferences();
|
||||||
|
const updatePreferences = useUpdateUserPreferences();
|
||||||
const [editingId, setEditingId] = useState<string | null>(null);
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
const [title, setTitle] = useState("");
|
const [title, setTitle] = useState("");
|
||||||
const [content, setContent] = useState("");
|
const [content, setContent] = useState("");
|
||||||
|
const [agentId, setAgentId] = useState<string | undefined>(undefined);
|
||||||
|
|
||||||
const saving = createPrompt.isPending || updatePrompt.isPending;
|
const saving = createPrompt.isPending || updatePrompt.isPending;
|
||||||
|
|
||||||
|
const selectableAgents = agents;
|
||||||
|
|
||||||
|
const agentNameById = (id?: string | null) =>
|
||||||
|
id ? agents.find((agent) => agent.id === id)?.name ?? null : null;
|
||||||
|
|
||||||
const resetForm = () => {
|
const resetForm = () => {
|
||||||
setEditingId(null);
|
setEditingId(null);
|
||||||
setTitle("");
|
setTitle("");
|
||||||
setContent("");
|
setContent("");
|
||||||
|
setAgentId(undefined);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
@@ -171,15 +192,24 @@ function ManagePromptsDialog({
|
|||||||
toast.error("提示词内容不能为空");
|
toast.error("提示词内容不能为空");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!agentId) {
|
||||||
|
toast.error("请选择关联智能体");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (editingId) {
|
if (editingId) {
|
||||||
await updatePrompt.mutateAsync({
|
await updatePrompt.mutateAsync({
|
||||||
id: editingId,
|
id: editingId,
|
||||||
input: { title: trimmedTitle, content },
|
input: { title: trimmedTitle, content, agent_id: agentId },
|
||||||
});
|
});
|
||||||
toast.success("提示词已更新");
|
toast.success("提示词已更新");
|
||||||
} else {
|
} else {
|
||||||
await createPrompt.mutateAsync({ title: trimmedTitle, content });
|
await createPrompt.mutateAsync({
|
||||||
|
title: trimmedTitle,
|
||||||
|
content,
|
||||||
|
agent_id: agentId,
|
||||||
|
});
|
||||||
toast.success("提示词已添加");
|
toast.success("提示词已添加");
|
||||||
}
|
}
|
||||||
resetForm();
|
resetForm();
|
||||||
@@ -189,17 +219,31 @@ function ManagePromptsDialog({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleEdit = (id: string) => {
|
const handleEdit = (id: string) => {
|
||||||
const target = prompts.find((p) => p.id === id);
|
const target = prompts.find((prompt) => prompt.id === id);
|
||||||
if (!target) return;
|
if (!target) return;
|
||||||
setEditingId(id);
|
setEditingId(id);
|
||||||
setTitle(target.title);
|
setTitle(target.title);
|
||||||
setContent(target.content);
|
setContent(target.content);
|
||||||
|
setAgentId(
|
||||||
|
target.agent_id && selectableAgents.some((agent) => agent.id === target.agent_id)
|
||||||
|
? target.agent_id
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleHideAdmin = async (next: boolean) => {
|
||||||
|
try {
|
||||||
|
await updatePreferences.mutateAsync({ hide_admin_prompt_prefix: next });
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = async (id: string) => {
|
const handleDelete = async (id: string) => {
|
||||||
try {
|
try {
|
||||||
await deletePrompt.mutateAsync(id);
|
await deletePrompt.mutateAsync(id);
|
||||||
if (editingId === id) resetForm();
|
if (editingId === id) resetForm();
|
||||||
|
toast.success("提示词已删除");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
toast.error(err instanceof Error ? err.message : String(err));
|
toast.error(err instanceof Error ? err.message : String(err));
|
||||||
}
|
}
|
||||||
@@ -217,25 +261,73 @@ function ManagePromptsDialog({
|
|||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>管理常用提示词</DialogTitle>
|
<DialogTitle>管理常用提示词</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
保存常用的提示词,保存后会以小标签形式显示在输入框上方,点击即可填入。提示词与你的账号绑定,可跨设备使用。
|
保存常用提示词后,会显示在输入框上方。提示词与账号绑定,可跨设备使用。
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="flex items-start justify-between gap-3 rounded-md border p-3">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-sm font-medium">只用我自己的提示词</p>
|
||||||
|
<p className="text-muted-foreground mt-0.5 text-xs">
|
||||||
|
开启后,输入框不再显示管理员配置的提示词前缀开关,本账号仅使用自己保存的提示词。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={preferences.hide_admin_prompt_prefix}
|
||||||
|
disabled={updatePreferences.isPending}
|
||||||
|
onCheckedChange={(value) => void handleToggleHideAdmin(value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-3 rounded-md border p-3">
|
<div className="space-y-3 rounded-md border p-3">
|
||||||
<Input
|
<Input
|
||||||
value={title}
|
value={title}
|
||||||
onChange={(e) => setTitle(e.target.value)}
|
onChange={(event) => setTitle(event.target.value)}
|
||||||
placeholder="名称(可选,例如:周报总结)"
|
placeholder="名称(可选,例如:周报总结)"
|
||||||
/>
|
/>
|
||||||
<Textarea
|
<Textarea
|
||||||
value={content}
|
value={content}
|
||||||
onChange={(e) => setContent(e.target.value)}
|
onChange={(event) => setContent(event.target.value)}
|
||||||
placeholder="提示词内容"
|
placeholder="提示词内容"
|
||||||
className="min-h-28"
|
className="min-h-28"
|
||||||
/>
|
/>
|
||||||
|
<div className="flex min-w-0 flex-col gap-1">
|
||||||
|
<p className="text-muted-foreground text-xs">关联智能体</p>
|
||||||
|
<Select value={agentId} onValueChange={setAgentId}>
|
||||||
|
<SelectTrigger className="w-full min-w-0 max-w-full overflow-hidden [&>span]:min-w-0 [&>span]:flex-1 [&>span]:truncate [&>span]:text-left">
|
||||||
|
<SelectValue placeholder="请选择已配置的智能体" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent
|
||||||
|
position="popper"
|
||||||
|
className="max-h-[40vh] w-[var(--radix-select-trigger-width)] max-w-[var(--radix-select-trigger-width)] overflow-hidden"
|
||||||
|
>
|
||||||
|
{selectableAgents.map((agent) => (
|
||||||
|
<SelectItem
|
||||||
|
key={agent.id}
|
||||||
|
value={agent.id}
|
||||||
|
className="max-w-full pr-8"
|
||||||
|
>
|
||||||
|
<span className="block max-w-full truncate">
|
||||||
|
{desensitize(agent.name)}
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
{selectableAgents.length === 0
|
||||||
|
? "当前账号还没有已配置的智能体。"
|
||||||
|
: "关联后,仅在选中该智能体的对话里显示此提示词。"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
{editingId && (
|
{editingId && (
|
||||||
<Button variant="outline" size="sm" onClick={resetForm} disabled={saving}>
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={resetForm}
|
||||||
|
disabled={saving}
|
||||||
|
>
|
||||||
取消编辑
|
取消编辑
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
@@ -260,6 +352,11 @@ function ManagePromptsDialog({
|
|||||||
<p className="truncate text-sm font-medium">
|
<p className="truncate text-sm font-medium">
|
||||||
{prompt.title || "未命名提示词"}
|
{prompt.title || "未命名提示词"}
|
||||||
</p>
|
</p>
|
||||||
|
{prompt.agent_id && (
|
||||||
|
<p className="mt-0.5 truncate text-[11px] text-sky-600 dark:text-sky-400">
|
||||||
|
仅 {desensitize(agentNameById(prompt.agent_id) || "未知智能体")} 可见
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
<p className="text-muted-foreground mt-0.5 line-clamp-2 text-xs whitespace-pre-wrap">
|
<p className="text-muted-foreground mt-0.5 line-clamp-2 text-xs whitespace-pre-wrap">
|
||||||
{prompt.content}
|
{prompt.content}
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -86,7 +86,8 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "../ui/dropdown-menu";
|
} from "../ui/dropdown-menu";
|
||||||
|
|
||||||
import { useRecommendedQuestions } from "@/core/recommended-questions/hooks";
|
import { useRecommendedQuestions } from "@/core/recommended-questions/hooks";
|
||||||
|
import { useUserPreferences } from "@/core/user-preferences";
|
||||||
import {
|
import {
|
||||||
isThreadRagModeLocked,
|
isThreadRagModeLocked,
|
||||||
lockThreadRagMode,
|
lockThreadRagMode,
|
||||||
@@ -131,6 +132,7 @@ export function InputBox({
|
|||||||
onStop,
|
onStop,
|
||||||
promptPrefix,
|
promptPrefix,
|
||||||
agentSelector,
|
agentSelector,
|
||||||
|
assistantId,
|
||||||
...props
|
...props
|
||||||
}: Omit<ComponentProps<typeof PromptInput>, "onSubmit"> & {
|
}: Omit<ComponentProps<typeof PromptInput>, "onSubmit"> & {
|
||||||
assistantId?: string | null;
|
assistantId?: string | null;
|
||||||
@@ -203,7 +205,11 @@ export function InputBox({
|
|||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
|
|
||||||
const { questions: recommendedQuestions } = useRecommendedQuestions();
|
const { questions: recommendedQuestions } = useRecommendedQuestions();
|
||||||
|
const userPreferences = useUserPreferences();
|
||||||
|
const showAdminRecommendedQuestions =
|
||||||
|
!userPreferences.hide_admin_prompt_prefix &&
|
||||||
|
recommendedQuestions.length > 0;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (models.length === 0) {
|
if (models.length === 0) {
|
||||||
@@ -510,7 +516,7 @@ export function InputBox({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isNewThread && searchParams.get("mode") !== "skill" && recommendedQuestions.length > 0 && (
|
{isNewThread && searchParams.get("mode") !== "skill" && showAdminRecommendedQuestions && (
|
||||||
<div className="flex flex-wrap justify-center gap-2.5 px-4 mb-[10px]">
|
<div className="flex flex-wrap justify-center gap-2.5 px-4 mb-[10px]">
|
||||||
{recommendedQuestions.map((q) => (
|
{recommendedQuestions.map((q) => (
|
||||||
<button
|
<button
|
||||||
@@ -564,6 +570,7 @@ export function InputBox({
|
|||||||
{isNewThread && (
|
{isNewThread && (
|
||||||
<CustomPromptBar
|
<CustomPromptBar
|
||||||
className="px-1"
|
className="px-1"
|
||||||
|
currentAgentId={agentSelector?.selectedAgentId ?? assistantId ?? null}
|
||||||
onInsert={(content) => {
|
onInsert={(content) => {
|
||||||
const current = textInput.value?.trim() ?? "";
|
const current = textInput.value?.trim() ?? "";
|
||||||
textInput.setInput(current ? `${current}\n${content}` : content);
|
textInput.setInput(current ? `${current}\n${content}` : content);
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { Trash2Icon } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
|
import { useDeleteMessage } from "@/core/threads/hooks";
|
||||||
|
|
||||||
|
import { Tooltip } from "../tooltip";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hover affordance that deletes a conversation turn (a user question together
|
||||||
|
* with its answer) after a confirmation step. The actual removal is persisted
|
||||||
|
* server-side; `onDeleted` receives the ids the server removed so the parent
|
||||||
|
* can hide those bubbles immediately without waiting for the stream cache to
|
||||||
|
* refresh.
|
||||||
|
*/
|
||||||
|
export function DeleteMessageButton({
|
||||||
|
threadId,
|
||||||
|
messageId,
|
||||||
|
onDeleted,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
threadId: string;
|
||||||
|
messageId: string;
|
||||||
|
onDeleted?: (deletedIds: string[]) => void;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
const { t } = useI18n();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const deleteMessage = useDeleteMessage();
|
||||||
|
|
||||||
|
const handleConfirm = async () => {
|
||||||
|
try {
|
||||||
|
const deletedIds = await deleteMessage.mutateAsync({
|
||||||
|
threadId,
|
||||||
|
messageId,
|
||||||
|
});
|
||||||
|
onDeleted?.(deletedIds);
|
||||||
|
setOpen(false);
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(
|
||||||
|
error instanceof Error ? error.message : "删除消息失败。",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Tooltip content={t.inputBox.deleteMessage}>
|
||||||
|
<Button
|
||||||
|
size="icon-sm"
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
className={className}
|
||||||
|
onClick={() => setOpen(true)}
|
||||||
|
>
|
||||||
|
<Trash2Icon size={12} />
|
||||||
|
</Button>
|
||||||
|
</Tooltip>
|
||||||
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
|
<DialogContent className="sm:max-w-sm">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{t.inputBox.deleteMessageConfirmTitle}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{t.inputBox.deleteMessageConfirmDescription}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
disabled={deleteMessage.isPending}
|
||||||
|
>
|
||||||
|
{t.common.cancel}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => void handleConfirm()}
|
||||||
|
disabled={deleteMessage.isPending}
|
||||||
|
>
|
||||||
|
{t.common.delete}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,79 +1,136 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import type { AnchorHTMLAttributes } from "react";
|
import type { AnchorHTMLAttributes, HTMLAttributes, ReactNode } from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
MessageResponse,
|
MessageResponse,
|
||||||
type MessageResponseProps,
|
type MessageResponseProps,
|
||||||
} from "@/components/ai-elements/message";
|
} from "@/components/ai-elements/message";
|
||||||
import { streamdownPlugins } from "@/core/streamdown";
|
import { streamdownPlugins } from "@/core/streamdown";
|
||||||
import { cn } from "@/lib/utils";
|
import {
|
||||||
|
createMarkdownAnchorResolver,
|
||||||
import { CitationLink } from "../citations/citation-link";
|
isInPageAnchor,
|
||||||
|
scrollToInPageAnchor,
|
||||||
function isExternalUrl(href: string | undefined): boolean {
|
} from "@/core/utils/markdown";
|
||||||
return !!href && /^https?:\/\//.test(href);
|
import { cn } from "@/lib/utils";
|
||||||
}
|
|
||||||
|
import { CitationLink } from "../citations/citation-link";
|
||||||
export type MarkdownContentProps = {
|
|
||||||
content: string;
|
function isExternalUrl(href: string | undefined): boolean {
|
||||||
isLoading: boolean;
|
return !!href && /^https?:\/\//.test(href);
|
||||||
rehypePlugins: MessageResponseProps["rehypePlugins"];
|
}
|
||||||
className?: string;
|
|
||||||
remarkPlugins?: MessageResponseProps["remarkPlugins"];
|
function extractTextFromChildren(children: ReactNode): string {
|
||||||
components?: MessageResponseProps["components"];
|
if (typeof children === "string" || typeof children === "number") return String(children);
|
||||||
};
|
if (Array.isArray(children)) return children.map(extractTextFromChildren).join("");
|
||||||
|
return "";
|
||||||
/** Renders markdown content. */
|
}
|
||||||
export function MarkdownContent({
|
|
||||||
content,
|
export type MarkdownContentProps = {
|
||||||
rehypePlugins,
|
content: string;
|
||||||
className,
|
isLoading: boolean;
|
||||||
remarkPlugins = streamdownPlugins.remarkPlugins,
|
rehypePlugins: MessageResponseProps["rehypePlugins"];
|
||||||
components: componentsFromProps,
|
className?: string;
|
||||||
}: MarkdownContentProps) {
|
remarkPlugins?: MessageResponseProps["remarkPlugins"];
|
||||||
const components = useMemo(() => {
|
components?: MessageResponseProps["components"];
|
||||||
return {
|
};
|
||||||
a: (props: AnchorHTMLAttributes<HTMLAnchorElement>) => {
|
|
||||||
if (props.href?.startsWith("#reference-")) {
|
/** Renders markdown content. */
|
||||||
return <CitationLink {...props} />;
|
export function MarkdownContent({
|
||||||
}
|
content,
|
||||||
if (typeof props.children === "string") {
|
rehypePlugins,
|
||||||
const match = /^citation:(.+)$/.exec(props.children);
|
className,
|
||||||
if (match) {
|
remarkPlugins = streamdownPlugins.remarkPlugins,
|
||||||
const [, text] = match;
|
components: componentsFromProps,
|
||||||
return <CitationLink {...props}>{text}</CitationLink>;
|
}: MarkdownContentProps) {
|
||||||
}
|
const anchorResolver = useMemo(() => createMarkdownAnchorResolver(content), [content]);
|
||||||
}
|
const components = useMemo(() => {
|
||||||
const { className, target, rel, ...rest } = props;
|
const heading = (level: 1 | 2 | 3 | 4 | 5 | 6) => {
|
||||||
const external = isExternalUrl(props.href);
|
const Tag = `h${level}` as const;
|
||||||
return (
|
return ({ children, id, ...props }: HTMLAttributes<HTMLHeadingElement>) => (
|
||||||
<a
|
<Tag id={id ?? anchorResolver.getHeadingId(level, extractTextFromChildren(children))} {...props}>
|
||||||
{...rest}
|
{children}
|
||||||
className={cn(
|
</Tag>
|
||||||
"text-primary decoration-primary/30 hover:decoration-primary/60 underline underline-offset-2 transition-colors",
|
);
|
||||||
className,
|
};
|
||||||
)}
|
|
||||||
target={target ?? (external ? "_blank" : undefined)}
|
return {
|
||||||
rel={rel ?? (external ? "noopener noreferrer" : undefined)}
|
h1: heading(1),
|
||||||
/>
|
h2: heading(2),
|
||||||
);
|
h3: heading(3),
|
||||||
},
|
h4: heading(4),
|
||||||
...componentsFromProps,
|
h5: heading(5),
|
||||||
};
|
h6: heading(6),
|
||||||
}, [componentsFromProps]);
|
a: (props: AnchorHTMLAttributes<HTMLAnchorElement>) => {
|
||||||
|
if (props.href?.startsWith("#reference-")) {
|
||||||
if (!content) return null;
|
return <CitationLink {...props} />;
|
||||||
|
}
|
||||||
return (
|
if (typeof props.children === "string") {
|
||||||
<MessageResponse
|
const match = /^citation:(.+)$/.exec(props.children);
|
||||||
className={className}
|
if (match) {
|
||||||
remarkPlugins={remarkPlugins}
|
const [, text] = match;
|
||||||
rehypePlugins={rehypePlugins}
|
return <CitationLink {...props}>{text}</CitationLink>;
|
||||||
components={components}
|
}
|
||||||
>
|
}
|
||||||
{content}
|
const { className, target, rel, ...rest } = props;
|
||||||
</MessageResponse>
|
const external = isExternalUrl(props.href);
|
||||||
);
|
const resolvedHref = anchorResolver.resolveHref(
|
||||||
}
|
props.href,
|
||||||
|
extractTextFromChildren(props.children),
|
||||||
|
);
|
||||||
|
if (resolvedHref === null) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"text-primary/80 decoration-dotted underline underline-offset-2 cursor-not-allowed",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
title="未在当前 Markdown 中找到对应章节"
|
||||||
|
>
|
||||||
|
{props.children}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const finalHref = resolvedHref ?? props.href;
|
||||||
|
return (
|
||||||
|
<a
|
||||||
|
{...rest}
|
||||||
|
href={finalHref}
|
||||||
|
className={cn(
|
||||||
|
"text-primary decoration-primary/30 hover:decoration-primary/60 underline underline-offset-2 transition-colors",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
target={target ?? (external ? "_blank" : undefined)}
|
||||||
|
rel={rel ?? (external ? "noopener noreferrer" : undefined)}
|
||||||
|
onClick={(event) => {
|
||||||
|
// HashRouter would turn a `#section` click into a route change → 404.
|
||||||
|
// Scroll to the heading ourselves instead.
|
||||||
|
if (isInPageAnchor(finalHref)) {
|
||||||
|
event.preventDefault();
|
||||||
|
scrollToInPageAnchor(event.currentTarget, finalHref);
|
||||||
|
}
|
||||||
|
rest.onClick?.(event);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
...componentsFromProps,
|
||||||
|
};
|
||||||
|
}, [anchorResolver, componentsFromProps]);
|
||||||
|
|
||||||
|
if (!content) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div data-markdown-anchor-root className="contents">
|
||||||
|
<MessageResponse
|
||||||
|
className={className}
|
||||||
|
remarkPlugins={remarkPlugins}
|
||||||
|
rehypePlugins={rehypePlugins}
|
||||||
|
components={components}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</MessageResponse>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -57,6 +57,7 @@ import { CopyButton } from '../copy-button';
|
|||||||
import { Tooltip } from '../tooltip';
|
import { Tooltip } from '../tooltip';
|
||||||
import { SkillDisplayBlock } from '../skill-display-block';
|
import { SkillDisplayBlock } from '../skill-display-block';
|
||||||
import { ThreadContext } from './context';
|
import { ThreadContext } from './context';
|
||||||
|
import { DeleteMessageButton } from './delete-message-button';
|
||||||
import { DownloadWordButton } from './download-word-button';
|
import { DownloadWordButton } from './download-word-button';
|
||||||
import { MarkdownContent, type MarkdownContentProps } from './markdown-content';
|
import { MarkdownContent, type MarkdownContentProps } from './markdown-content';
|
||||||
import { MessageTokenUsage } from './message-token-usage';
|
import { MessageTokenUsage } from './message-token-usage';
|
||||||
@@ -135,6 +136,7 @@ export function MessageListItem({
|
|||||||
displaySources = [],
|
displaySources = [],
|
||||||
extraRehypePlugins,
|
extraRehypePlugins,
|
||||||
onEditResubmit,
|
onEditResubmit,
|
||||||
|
onMessageDeleted,
|
||||||
}: {
|
}: {
|
||||||
className?: string;
|
className?: string;
|
||||||
fitRowToContent?: boolean;
|
fitRowToContent?: boolean;
|
||||||
@@ -145,6 +147,7 @@ export function MessageListItem({
|
|||||||
displaySources?: RuntimeDisplaySource[];
|
displaySources?: RuntimeDisplaySource[];
|
||||||
extraRehypePlugins?: ReturnType<typeof useRehypeSplitWordsIntoSpans>;
|
extraRehypePlugins?: ReturnType<typeof useRehypeSplitWordsIntoSpans>;
|
||||||
onEditResubmit?: (text: string) => void;
|
onEditResubmit?: (text: string) => void;
|
||||||
|
onMessageDeleted?: (deletedIds: string[]) => void;
|
||||||
}) {
|
}) {
|
||||||
const isHuman = message.type === 'human';
|
const isHuman = message.type === 'human';
|
||||||
const messageMarkdown =
|
const messageMarkdown =
|
||||||
@@ -170,6 +173,7 @@ export function MessageListItem({
|
|||||||
displaySources={displaySources}
|
displaySources={displaySources}
|
||||||
extraRehypePlugins={extraRehypePlugins}
|
extraRehypePlugins={extraRehypePlugins}
|
||||||
onEditResubmit={onEditResubmit}
|
onEditResubmit={onEditResubmit}
|
||||||
|
onMessageDeleted={onMessageDeleted}
|
||||||
/>
|
/>
|
||||||
{/*
|
{/*
|
||||||
Human messages carry their own inline copy/edit toolbar inside
|
Human messages carry their own inline copy/edit toolbar inside
|
||||||
@@ -214,6 +218,7 @@ function HumanMessageBlock({
|
|||||||
messageTime,
|
messageTime,
|
||||||
components,
|
components,
|
||||||
onEditResubmit,
|
onEditResubmit,
|
||||||
|
deleteButton,
|
||||||
}: {
|
}: {
|
||||||
text: string;
|
text: string;
|
||||||
pageContext?: EmbeddedPageContext | null;
|
pageContext?: EmbeddedPageContext | null;
|
||||||
@@ -221,6 +226,7 @@ function HumanMessageBlock({
|
|||||||
messageTime: { label: string; full: string } | null;
|
messageTime: { label: string; full: string } | null;
|
||||||
components: MarkdownContentProps["components"];
|
components: MarkdownContentProps["components"];
|
||||||
onEditResubmit?: (text: string) => void;
|
onEditResubmit?: (text: string) => void;
|
||||||
|
deleteButton?: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const [editing, setEditing] = useState(false);
|
const [editing, setEditing] = useState(false);
|
||||||
@@ -298,10 +304,10 @@ function HumanMessageBlock({
|
|||||||
)}
|
)}
|
||||||
<MessageTimeStamp time={messageTime} align="right" />
|
<MessageTimeStamp time={messageTime} align="right" />
|
||||||
{pageContext && <EmbeddedPageContextCard pageContext={pageContext} />}
|
{pageContext && <EmbeddedPageContextCard pageContext={pageContext} />}
|
||||||
{text && (
|
{(text || deleteButton) && (
|
||||||
<div className="flex items-center gap-0.5 opacity-0 transition-opacity duration-200 group-hover/conversation-message:opacity-100">
|
<div className="flex items-center gap-0.5 opacity-0 transition-opacity duration-200 group-hover/conversation-message:opacity-100">
|
||||||
<CopyButton clipboardData={text} className="size-6" />
|
{text && <CopyButton clipboardData={text} className="size-6" />}
|
||||||
{onEditResubmit && (
|
{text && onEditResubmit && (
|
||||||
<Tooltip content={t.inputBox.editQuestion}>
|
<Tooltip content={t.inputBox.editQuestion}>
|
||||||
<Button
|
<Button
|
||||||
size="icon-sm"
|
size="icon-sm"
|
||||||
@@ -314,6 +320,7 @@ function HumanMessageBlock({
|
|||||||
</Button>
|
</Button>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
|
{deleteButton}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -360,6 +367,7 @@ function MessageContent_({
|
|||||||
displaySources = [],
|
displaySources = [],
|
||||||
extraRehypePlugins,
|
extraRehypePlugins,
|
||||||
onEditResubmit,
|
onEditResubmit,
|
||||||
|
onMessageDeleted,
|
||||||
}: {
|
}: {
|
||||||
className?: string;
|
className?: string;
|
||||||
message: Message;
|
message: Message;
|
||||||
@@ -369,6 +377,7 @@ function MessageContent_({
|
|||||||
displaySources?: RuntimeDisplaySource[];
|
displaySources?: RuntimeDisplaySource[];
|
||||||
extraRehypePlugins?: ReturnType<typeof useRehypeSplitWordsIntoSpans>;
|
extraRehypePlugins?: ReturnType<typeof useRehypeSplitWordsIntoSpans>;
|
||||||
onEditResubmit?: (text: string) => void;
|
onEditResubmit?: (text: string) => void;
|
||||||
|
onMessageDeleted?: (deletedIds: string[]) => void;
|
||||||
}) {
|
}) {
|
||||||
const baseRehypePlugins = useRehypeSplitWordsIntoSpans(isLoading);
|
const baseRehypePlugins = useRehypeSplitWordsIntoSpans(isLoading);
|
||||||
|
|
||||||
@@ -500,6 +509,11 @@ function MessageContent_({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isHuman) {
|
if (isHuman) {
|
||||||
|
// Only the user's own question carries a delete affordance, and only once
|
||||||
|
// it exists server-side (real, non-optimistic id). Deleting it cascades to
|
||||||
|
// its answer on the backend.
|
||||||
|
const canDelete =
|
||||||
|
!!onMessageDeleted && !!message.id && !message.id.startsWith('opt-');
|
||||||
return (
|
return (
|
||||||
<HumanMessageBlock
|
<HumanMessageBlock
|
||||||
text={parsedHumanContent.content}
|
text={parsedHumanContent.content}
|
||||||
@@ -508,6 +522,16 @@ function MessageContent_({
|
|||||||
messageTime={messageTime}
|
messageTime={messageTime}
|
||||||
components={components}
|
components={components}
|
||||||
onEditResubmit={onEditResubmit}
|
onEditResubmit={onEditResubmit}
|
||||||
|
deleteButton={
|
||||||
|
canDelete ? (
|
||||||
|
<DeleteMessageButton
|
||||||
|
threadId={threadId}
|
||||||
|
messageId={message.id!}
|
||||||
|
onDeleted={(ids) => onMessageDeleted?.(ids)}
|
||||||
|
className="size-6"
|
||||||
|
/>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { Message } from "@langchain/langgraph-sdk";
|
import type { Message } from "@langchain/langgraph-sdk";
|
||||||
import type { BaseStream } from "@langchain/langgraph-sdk/react";
|
import type { BaseStream } from "@langchain/langgraph-sdk/react";
|
||||||
import { CheckIcon, SendIcon, XIcon } from "lucide-react";
|
import { CheckIcon, SendIcon, XIcon } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Conversation,
|
Conversation,
|
||||||
@@ -37,6 +37,7 @@ import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
|||||||
import { ArtifactFileList } from "../artifacts/artifact-file-list";
|
import { ArtifactFileList } from "../artifacts/artifact-file-list";
|
||||||
import { StreamingIndicator } from "../streaming-indicator";
|
import { StreamingIndicator } from "../streaming-indicator";
|
||||||
|
|
||||||
|
import { ThreadContext } from "./context";
|
||||||
import { MarkdownContent } from "./markdown-content";
|
import { MarkdownContent } from "./markdown-content";
|
||||||
import { MessageGroup } from "./message-group";
|
import { MessageGroup } from "./message-group";
|
||||||
import { MessageListItem } from "./message-list-item";
|
import { MessageListItem } from "./message-list-item";
|
||||||
@@ -88,7 +89,38 @@ export function MessageList({
|
|||||||
);
|
);
|
||||||
const updateSubtask = useUpdateSubtask();
|
const updateSubtask = useUpdateSubtask();
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const messages = thread.messages;
|
const threadContext = useContext(ThreadContext);
|
||||||
|
// Read-only contexts (public share, mock previews) must not offer deletion.
|
||||||
|
const allowDelete = !threadContext?.publicShareCode && !threadContext?.isMock;
|
||||||
|
|
||||||
|
// Locally hide messages the user just deleted. The server-side checkpoint is
|
||||||
|
// trimmed immediately, but the live `useStream` cache still holds the message
|
||||||
|
// until the next refetch — filtering by id here makes the removal instant and
|
||||||
|
// keeps it hidden for the rest of the session (a reload reads the trimmed
|
||||||
|
// state). Reset whenever the active thread changes.
|
||||||
|
const [hiddenMessageIds, setHiddenMessageIds] = useState<Set<string>>(
|
||||||
|
() => new Set(),
|
||||||
|
);
|
||||||
|
useEffect(() => {
|
||||||
|
setHiddenMessageIds(new Set());
|
||||||
|
}, [threadId]);
|
||||||
|
const handleMessageDeleted = useCallback((deletedIds: string[]) => {
|
||||||
|
if (deletedIds.length === 0) return;
|
||||||
|
setHiddenMessageIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
for (const id of deletedIds) next.add(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const allMessages = thread.messages;
|
||||||
|
const messages = useMemo(
|
||||||
|
() =>
|
||||||
|
hiddenMessageIds.size === 0
|
||||||
|
? allMessages
|
||||||
|
: allMessages.filter((m) => !m.id || !hiddenMessageIds.has(m.id)),
|
||||||
|
[allMessages, hiddenMessageIds],
|
||||||
|
);
|
||||||
|
|
||||||
// Stamp a wall-clock time onto every question/answer the first time it is
|
// Stamp a wall-clock time onto every question/answer the first time it is
|
||||||
// seen, in a single batched commit. Questions sent this session already carry
|
// seen, in a single batched commit. Questions sent this session already carry
|
||||||
@@ -259,6 +291,9 @@ export function MessageList({
|
|||||||
displaySources={displaySources}
|
displaySources={displaySources}
|
||||||
extraRehypePlugins={extraRehypePlugins}
|
extraRehypePlugins={extraRehypePlugins}
|
||||||
onEditResubmit={onEditResubmit}
|
onEditResubmit={onEditResubmit}
|
||||||
|
onMessageDeleted={
|
||||||
|
allowDelete ? handleMessageDeleted : undefined
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,266 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
|
import { ChevronDown, Loader2, MoreHorizontal, Pencil, Share2, Trash2 } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
SidebarGroup,
|
||||||
|
SidebarGroupContent,
|
||||||
|
SidebarGroupLabel,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuAction,
|
||||||
|
SidebarMenuItem,
|
||||||
|
SidebarMenuButton,
|
||||||
|
} from "@/components/ui/sidebar";
|
||||||
|
import { ShareRoundtableDraftDialog } from "@/components/workspace/roundtable-draft-share-dialogs";
|
||||||
|
import { formatRelative } from "@/open-canvas/components/ai-writing/AIWritingHistoryDropdown";
|
||||||
|
import { useRoundtableDrafts } from "@/roundtable-planning/hooks/useRoundtableDrafts";
|
||||||
|
import type { DraftMeta } from "@/roundtable-planning/api/drafts";
|
||||||
|
import { isIMEComposing } from "@/lib/ime";
|
||||||
|
|
||||||
|
const ROUNDTABLE_PATH = "/page/workspace/roundtable/planning";
|
||||||
|
|
||||||
|
function openDraft(
|
||||||
|
draft: DraftMeta,
|
||||||
|
isOnPage: boolean,
|
||||||
|
router: ReturnType<typeof useRouter>,
|
||||||
|
) {
|
||||||
|
if (isOnPage) {
|
||||||
|
// 已在会商页面:直接派事件让页面加载该草稿(仿 AI 写作的 open-session)。
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent("roundtable:open-draft", { detail: draft.id }),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// 不在该页面:把草稿 id 暂存到 sessionStorage,跳转后由页面消费。
|
||||||
|
sessionStorage.setItem("roundtable:pending-draft", draft.id);
|
||||||
|
router.push(ROUNDTABLE_PATH);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把草稿的后台作业状态 / 步骤映射成侧边栏小标签(仿页面内 HistoryDropdown)。 */
|
||||||
|
function StatusBadge({ draft }: { draft: DraftMeta }) {
|
||||||
|
if (draft.status === "running") {
|
||||||
|
return (
|
||||||
|
<span className="inline-flex items-center gap-1 text-[10px] font-medium text-primary">
|
||||||
|
<Loader2 className="w-2.5 h-2.5 animate-spin" />
|
||||||
|
进行中
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (draft.status === "awaiting_input") {
|
||||||
|
return <span className="text-[10px] font-medium text-amber-500">待澄清</span>;
|
||||||
|
}
|
||||||
|
if (draft.status === "error") {
|
||||||
|
return <span className="text-[10px] font-medium text-rose-500">出错</span>;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span className="text-[10px] font-medium text-muted-foreground">
|
||||||
|
第 {draft.furthestStep} 步
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RecentRoundtableList() {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const { drafts, loading, refresh, rename, remove } = useRoundtableDrafts();
|
||||||
|
const [collapsed, setCollapsed] = useState(
|
||||||
|
() => localStorage.getItem("sidebar:recent-roundtable-collapsed") === "true",
|
||||||
|
);
|
||||||
|
|
||||||
|
// 重命名对话框状态。
|
||||||
|
const [renameId, setRenameId] = useState<string | null>(null);
|
||||||
|
const [renameValue, setRenameValue] = useState("");
|
||||||
|
// 分享对话框 —— 正在分享的草稿 id。
|
||||||
|
const [shareId, setShareId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const toggleCollapsed = () => {
|
||||||
|
const next = !collapsed;
|
||||||
|
setCollapsed(next);
|
||||||
|
localStorage.setItem("sidebar:recent-roundtable-collapsed", String(next));
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void refresh();
|
||||||
|
}, [refresh]);
|
||||||
|
|
||||||
|
const handleRenameSubmit = useCallback(async () => {
|
||||||
|
const id = renameId;
|
||||||
|
const title = renameValue.trim();
|
||||||
|
if (!id || !title) {
|
||||||
|
setRenameId(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await rename(id, title);
|
||||||
|
toast.success("✏️ 已重命名");
|
||||||
|
} catch {
|
||||||
|
toast.error("重命名失败,请重试");
|
||||||
|
} finally {
|
||||||
|
setRenameId(null);
|
||||||
|
setRenameValue("");
|
||||||
|
}
|
||||||
|
}, [renameId, renameValue, rename]);
|
||||||
|
|
||||||
|
const handleDelete = useCallback(
|
||||||
|
async (draft: DraftMeta) => {
|
||||||
|
if (!window.confirm("确定删除这条会商记录吗?此操作不可恢复。")) return;
|
||||||
|
try {
|
||||||
|
await remove(draft.id);
|
||||||
|
toast.success("🗑 已删除会商记录");
|
||||||
|
} catch {
|
||||||
|
toast.error("删除失败,请重试");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[remove],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!loading && drafts.length === 0) return null;
|
||||||
|
|
||||||
|
const isOnPage = pathname === ROUNDTABLE_PATH;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<SidebarGroup className="px-2 pt-3 mt-0 border-t border-sidebar-border/60">
|
||||||
|
<SidebarGroupLabel
|
||||||
|
className="text-muted-foreground/70 px-3 mb-1 text-[10px] font-semibold tracking-[0.12em] uppercase cursor-pointer select-none flex items-center justify-between hover:text-muted-foreground transition-colors"
|
||||||
|
onClick={toggleCollapsed}
|
||||||
|
>
|
||||||
|
<span>多智能体会商</span>
|
||||||
|
<ChevronDown
|
||||||
|
className={`w-3 h-3 shrink-0 transition-transform duration-200 ${collapsed ? "-rotate-90" : ""}`}
|
||||||
|
/>
|
||||||
|
</SidebarGroupLabel>
|
||||||
|
<SidebarGroupContent
|
||||||
|
className={`group-data-[collapsible=icon]:pointer-events-none group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 overflow-hidden transition-all duration-200 ${
|
||||||
|
collapsed ? "max-h-0 opacity-0 pointer-events-none" : "max-h-[600px] opacity-100"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<SidebarMenu>
|
||||||
|
<div className="flex w-full flex-col gap-0.5">
|
||||||
|
{loading && drafts.length === 0 ? (
|
||||||
|
<p className="px-3 py-1 text-[12px] text-muted-foreground">加载中…</p>
|
||||||
|
) : (
|
||||||
|
drafts.slice(0, 10).map((draft) => (
|
||||||
|
<SidebarMenuItem key={draft.id} className="group/side-menu-item">
|
||||||
|
<SidebarMenuButton
|
||||||
|
className={
|
||||||
|
"rounded-lg h-auto py-1.5 px-3 text-muted-foreground " +
|
||||||
|
"hover:text-foreground hover:bg-sidebar-accent/60"
|
||||||
|
}
|
||||||
|
onClick={() => openDraft(draft, isOnPage, router)}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col items-start min-w-0 w-full">
|
||||||
|
<span className="text-[13px] truncate w-full leading-snug">
|
||||||
|
{draft.title || "未命名草稿"}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1 mt-0.5">
|
||||||
|
<StatusBadge draft={draft} />
|
||||||
|
<span className="text-[10px] text-muted-foreground">·</span>
|
||||||
|
<span className="text-[10px] text-muted-foreground">
|
||||||
|
{formatRelative(draft.updatedAt)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<SidebarMenuAction
|
||||||
|
showOnHover
|
||||||
|
className="bg-background/50 hover:bg-background top-2"
|
||||||
|
>
|
||||||
|
<MoreHorizontal />
|
||||||
|
<span className="sr-only">更多</span>
|
||||||
|
</SidebarMenuAction>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent
|
||||||
|
className="w-44 rounded-lg"
|
||||||
|
side="right"
|
||||||
|
align="start"
|
||||||
|
>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onSelect={() => {
|
||||||
|
setRenameId(draft.id);
|
||||||
|
setRenameValue(draft.title || "");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Pencil className="text-muted-foreground" />
|
||||||
|
<span>重命名</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onSelect={() => setShareId(draft.id)}>
|
||||||
|
<Share2 className="text-muted-foreground" />
|
||||||
|
<span>分享</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem onSelect={() => void handleDelete(draft)}>
|
||||||
|
<Trash2 className="text-muted-foreground" />
|
||||||
|
<span>删除</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarGroupContent>
|
||||||
|
</SidebarGroup>
|
||||||
|
|
||||||
|
{/* 重命名对话框 */}
|
||||||
|
<Dialog open={renameId !== null} onOpenChange={(o) => !o && setRenameId(null)}>
|
||||||
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>重命名会商</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="py-4">
|
||||||
|
<Input
|
||||||
|
autoFocus
|
||||||
|
value={renameValue}
|
||||||
|
onChange={(e) => setRenameValue(e.target.value)}
|
||||||
|
placeholder="输入新名称"
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter" && !isIMEComposing(e)) {
|
||||||
|
e.preventDefault();
|
||||||
|
void handleRenameSubmit();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setRenameId(null)}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => void handleRenameSubmit()}>保存</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* 分享对话框 */}
|
||||||
|
<ShareRoundtableDraftDialog
|
||||||
|
draftId={shareId}
|
||||||
|
open={shareId !== null}
|
||||||
|
onOpenChange={(o) => {
|
||||||
|
if (!o) setShareId(null);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CheckIcon,
|
||||||
|
CopyIcon,
|
||||||
|
DownloadIcon,
|
||||||
|
ExternalLinkIcon,
|
||||||
|
Loader2,
|
||||||
|
Trash2Icon,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import type { DraftShare, DraftShareMode, DraftSharePreview } from "@/core/roundtable-draft-shares/api";
|
||||||
|
import { buildPublicDraftShareUrl, extractShareCode } from "@/core/roundtable-draft-shares/api";
|
||||||
|
import {
|
||||||
|
useCreateDraftShare,
|
||||||
|
useImportDraftShare,
|
||||||
|
usePreviewDraftShare,
|
||||||
|
useRevokeDraftShare,
|
||||||
|
} from "@/core/roundtable-draft-shares/hooks";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
function errorMessage(err: unknown): string {
|
||||||
|
return err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dialog that produces a share link for a single roundtable draft. Two modes:
|
||||||
|
*
|
||||||
|
* - `view` — mints a public, read-only link that anyone can open without logging
|
||||||
|
* in; it renders the draft's Step 3 result report (方案总览).
|
||||||
|
* - `import` — mints a short code; a recipient enters it in the import dialog to
|
||||||
|
* copy the whole 会商 draft into their own account.
|
||||||
|
*/
|
||||||
|
export function ShareRoundtableDraftDialog({
|
||||||
|
draftId,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
}: {
|
||||||
|
draftId: string | null;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const createShare = useCreateDraftShare();
|
||||||
|
const revokeShare = useRevokeDraftShare();
|
||||||
|
const [mode, setMode] = useState<DraftShareMode>("view");
|
||||||
|
const [share, setShare] = useState<DraftShare | null>(null);
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
|
// Reset to the default mode (read-only link) every time the dialog opens.
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) setMode("view");
|
||||||
|
}, [open, draftId]);
|
||||||
|
|
||||||
|
// Mint / reuse the link whenever the dialog opens or the mode changes.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || !draftId) return;
|
||||||
|
setShare(null);
|
||||||
|
setCopied(false);
|
||||||
|
createShare
|
||||||
|
.mutateAsync({ draftId, mode })
|
||||||
|
.then(setShare)
|
||||||
|
.catch((err) => toast.error(errorMessage(err)));
|
||||||
|
// createShare is stable enough; re-running only on open/draftId/mode is intended.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open, draftId, mode]);
|
||||||
|
|
||||||
|
const isView = mode === "view";
|
||||||
|
const publicUrl = isView && share ? buildPublicDraftShareUrl(share.share_code) : "";
|
||||||
|
|
||||||
|
async function handleCopy() {
|
||||||
|
if (!share) return;
|
||||||
|
const text = isView ? publicUrl : share.share_code;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
setCopied(true);
|
||||||
|
toast.success(isView ? "链接已复制" : "分享码已复制");
|
||||||
|
setTimeout(() => setCopied(false), 1500);
|
||||||
|
} catch {
|
||||||
|
toast.error("复制到剪贴板失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRevoke() {
|
||||||
|
if (!share || !window.confirm("撤销后此分享立即失效,确定吗?")) return;
|
||||||
|
try {
|
||||||
|
await revokeShare.mutateAsync(share.share_code);
|
||||||
|
toast.success("已撤销分享");
|
||||||
|
onOpenChange(false);
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(errorMessage(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>分享会商</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{isView
|
||||||
|
? "生成一个只读链接,任何人无需登录都能查看这次会商生成的结果报告。"
|
||||||
|
: "生成一个分享码,对方在「导入会商」里输入它即可把这份会商复制到自己的账号继续研讨。"}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{/* Mode selector */}
|
||||||
|
<div className="bg-muted flex gap-1 rounded-lg p-1">
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
{ value: "view" as const, label: "只读链接" },
|
||||||
|
{ value: "import" as const, label: "导入副本" },
|
||||||
|
]
|
||||||
|
).map((option) => (
|
||||||
|
<button
|
||||||
|
key={option.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setMode(option.value)}
|
||||||
|
className={cn(
|
||||||
|
"flex-1 rounded-md px-3 py-1.5 text-sm transition-colors",
|
||||||
|
mode === option.value
|
||||||
|
? "bg-background text-foreground shadow-sm"
|
||||||
|
: "text-muted-foreground hover:text-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!share ? (
|
||||||
|
<div className="text-muted-foreground flex items-center gap-2 py-8 text-sm">
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
正在生成分享…
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground mb-1 text-xs">
|
||||||
|
{isView ? "只读链接" : "分享码"}
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{isView ? (
|
||||||
|
<Input
|
||||||
|
readOnly
|
||||||
|
value={publicUrl}
|
||||||
|
onFocus={(e) => e.currentTarget.select()}
|
||||||
|
className="flex-1 font-mono text-xs"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<code className="bg-muted flex-1 rounded-md px-3 py-2 text-center font-mono text-lg tracking-[0.3em]">
|
||||||
|
{share.share_code}
|
||||||
|
</code>
|
||||||
|
)}
|
||||||
|
<Button variant="outline" onClick={() => void handleCopy()}>
|
||||||
|
{copied ? (
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
) : (
|
||||||
|
<CopyIcon className="size-4" />
|
||||||
|
)}
|
||||||
|
{isView ? "复制链接" : "复制码"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{isView ? (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
拿到链接的人都能查看这次会商的结果报告(只读)。若会商尚未生成结果报告,对方会看到提示。撤销后链接立即失效。
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => window.open(publicUrl, "_blank", "noopener")}
|
||||||
|
>
|
||||||
|
<ExternalLinkIcon className="size-3.5" />
|
||||||
|
在新标签页打开
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
把这个分享码发给对方,他们在「导入会商」里输入即可复制一份。撤销后分享码立即失效。
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-destructive hover:text-destructive"
|
||||||
|
disabled={revokeShare.isPending}
|
||||||
|
onClick={() => void handleRevoke()}
|
||||||
|
>
|
||||||
|
<Trash2Icon className="size-3.5" />
|
||||||
|
撤销分享
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dialog where a user pastes a share code to import someone's roundtable draft. */
|
||||||
|
export function ImportRoundtableDraftDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
onImported,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
/** Called with the new local draft id after a successful import. */
|
||||||
|
onImported?: (draftId: string | null) => void;
|
||||||
|
}) {
|
||||||
|
const [input, setInput] = useState("");
|
||||||
|
const [preview, setPreview] = useState<DraftSharePreview | null>(null);
|
||||||
|
const previewShare = usePreviewDraftShare();
|
||||||
|
const importShare = useImportDraftShare();
|
||||||
|
|
||||||
|
// Reset state whenever the dialog closes.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) {
|
||||||
|
setInput("");
|
||||||
|
setPreview(null);
|
||||||
|
}
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
async function handlePreview() {
|
||||||
|
const code = extractShareCode(input);
|
||||||
|
if (!code) {
|
||||||
|
toast.error("请输入分享码");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
setPreview(await previewShare.mutateAsync(code));
|
||||||
|
} catch (err) {
|
||||||
|
setPreview(null);
|
||||||
|
toast.error(errorMessage(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleImport() {
|
||||||
|
const code = preview?.share_code ?? extractShareCode(input);
|
||||||
|
if (!code) {
|
||||||
|
toast.error("请输入分享码");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await importShare.mutateAsync(code);
|
||||||
|
if (result.imported > 0) {
|
||||||
|
toast.success("导入成功,已加入「多智能体会商」历史");
|
||||||
|
} else {
|
||||||
|
toast.info("这份会商之前已导入过");
|
||||||
|
}
|
||||||
|
onImported?.(result.draft_id);
|
||||||
|
onOpenChange(false);
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(errorMessage(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>导入会商</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
输入对方分享的「导入副本」分享码,把这份会商复制到你自己的账号。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
value={input}
|
||||||
|
onChange={(e) => {
|
||||||
|
setInput(e.target.value);
|
||||||
|
setPreview(null);
|
||||||
|
}}
|
||||||
|
placeholder="粘贴分享码或链接"
|
||||||
|
className="font-mono"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => void handlePreview()}
|
||||||
|
disabled={previewShare.isPending || !input.trim()}
|
||||||
|
>
|
||||||
|
{previewShare.isPending && <Loader2 className="size-4 animate-spin" />}
|
||||||
|
预览
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{preview && (
|
||||||
|
<div className="space-y-2 rounded-lg border p-3 text-sm">
|
||||||
|
<p className="font-medium">{preview.title || "未命名会商"}</p>
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
来自用户 {preview.shared_by}
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
className="w-full"
|
||||||
|
onClick={() => void handleImport()}
|
||||||
|
disabled={importShare.isPending}
|
||||||
|
>
|
||||||
|
{importShare.isPending ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<DownloadIcon className="size-4" />
|
||||||
|
)}
|
||||||
|
{importShare.isPending ? "正在导入…" : "导入到我的账号"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { MoonIcon, SunIcon } from "lucide-react";
|
import { LayoutGridIcon, ListIcon, MoonIcon, SunIcon } from "lucide-react";
|
||||||
import { useMemo, type ComponentType, type SVGProps } from "react";
|
import { useMemo, type ComponentType, type SVGProps } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
@@ -48,6 +48,8 @@ export function AppearanceSettingsPage() {
|
|||||||
const { data: citationDisplay } = useCitationDisplaySettings();
|
const { data: citationDisplay } = useCitationDisplaySettings();
|
||||||
const updateCitationDisplay = useUpdateCitationDisplaySettings();
|
const updateCitationDisplay = useUpdateCitationDisplaySettings();
|
||||||
const globalDefault = appearance?.default_theme ?? "light";
|
const globalDefault = appearance?.default_theme ?? "light";
|
||||||
|
const globalSkillView = appearance?.default_skill_view ?? "list";
|
||||||
|
const globalAgentView = appearance?.default_agent_view ?? "card";
|
||||||
const cleanupWords =
|
const cleanupWords =
|
||||||
citationDisplay?.cleanup_words ?? settings.display.citationCleanupWords ?? [];
|
citationDisplay?.cleanup_words ?? settings.display.citationCleanupWords ?? [];
|
||||||
|
|
||||||
@@ -65,6 +67,27 @@ export function AppearanceSettingsPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleSetDefaultView = async (
|
||||||
|
kind: "skill" | "agent",
|
||||||
|
value: "card" | "list",
|
||||||
|
) => {
|
||||||
|
const current = kind === "skill" ? globalSkillView : globalAgentView;
|
||||||
|
if (value === current) return;
|
||||||
|
try {
|
||||||
|
await updateAppearance.mutateAsync(
|
||||||
|
kind === "skill"
|
||||||
|
? { default_skill_view: value }
|
||||||
|
: { default_agent_view: value },
|
||||||
|
);
|
||||||
|
const label = kind === "skill" ? "技能" : "智能体";
|
||||||
|
toast.success(
|
||||||
|
`已将${label}默认展示模式设置为${value === "card" ? "卡片" : "列表"}`,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(e instanceof Error ? e.message : "保存失败");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const themeOptions = useMemo(
|
const themeOptions = useMemo(
|
||||||
() => [
|
() => [
|
||||||
{
|
{
|
||||||
@@ -146,6 +169,52 @@ export function AppearanceSettingsPage() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{isAdmin && (
|
||||||
|
<>
|
||||||
|
<Separator />
|
||||||
|
<SettingsSection
|
||||||
|
title="默认展示模式(管理员)"
|
||||||
|
description="技能与智能体列表对所有还没有手动切换过的用户的默认展示模式;已经自己切换过的用户保留其个人选择不受影响。"
|
||||||
|
>
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
{ kind: "skill", label: "技能", current: globalSkillView },
|
||||||
|
{ kind: "agent", label: "智能体", current: globalAgentView },
|
||||||
|
] as const
|
||||||
|
).map(({ kind, label, current }) => (
|
||||||
|
<div key={kind} className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="w-14 text-sm font-medium">{label}</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={current === "card" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => void handleSetDefaultView(kind, "card")}
|
||||||
|
disabled={updateAppearance.isPending}
|
||||||
|
>
|
||||||
|
<LayoutGridIcon className="mr-1.5 size-4" />
|
||||||
|
卡片
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={current === "list" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => void handleSetDefaultView(kind, "list")}
|
||||||
|
disabled={updateAppearance.isPending}
|
||||||
|
>
|
||||||
|
<ListIcon className="mr-1.5 size-4" />
|
||||||
|
列表
|
||||||
|
</Button>
|
||||||
|
<p className="text-muted-foreground ml-2 text-xs">
|
||||||
|
当前系统默认:{current === "card" ? "卡片" : "列表"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</SettingsSection>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
<SettingsSection
|
<SettingsSection
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
import {
|
import {
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
ArchiveIcon,
|
ArchiveIcon,
|
||||||
|
ArrowDownUpIcon,
|
||||||
|
BookmarkIcon,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
ChevronLeftIcon,
|
ChevronLeftIcon,
|
||||||
ChevronRightIcon,
|
ChevronRightIcon,
|
||||||
@@ -14,7 +16,6 @@ import {
|
|||||||
Loader2,
|
Loader2,
|
||||||
LockIcon,
|
LockIcon,
|
||||||
PinIcon,
|
PinIcon,
|
||||||
PinOffIcon,
|
|
||||||
RefreshCwIcon,
|
RefreshCwIcon,
|
||||||
SparklesIcon,
|
SparklesIcon,
|
||||||
TagsIcon,
|
TagsIcon,
|
||||||
@@ -28,13 +29,6 @@ import { toast } from "sonner";
|
|||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
|
||||||
Card,
|
|
||||||
CardDescription,
|
|
||||||
CardFooter,
|
|
||||||
CardHeader,
|
|
||||||
CardTitle,
|
|
||||||
} from "@/components/ui/card";
|
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
@@ -45,7 +39,6 @@ import {
|
|||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import {
|
import {
|
||||||
Empty,
|
Empty,
|
||||||
EmptyContent,
|
|
||||||
EmptyDescription,
|
EmptyDescription,
|
||||||
EmptyHeader,
|
EmptyHeader,
|
||||||
EmptyMedia,
|
EmptyMedia,
|
||||||
@@ -60,11 +53,13 @@ import {
|
|||||||
ItemDescription,
|
ItemDescription,
|
||||||
} from "@/components/ui/item";
|
} from "@/components/ui/item";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { SkillDetailDialog } from "@/components/workspace/skills/skill-detail-dialog";
|
import { SkillDetailDialog } from "@/components/workspace/skills/skill-detail-dialog";
|
||||||
import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
||||||
import { TagPickerDialog } from "@/components/workspace/tags/tag-picker-dialog";
|
import { TagPickerDialog } from "@/components/workspace/tags/tag-picker-dialog";
|
||||||
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 { useTheme } from "@/contexts/ThemeContext";
|
import { useTheme } from "@/contexts/ThemeContext";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
@@ -74,11 +69,13 @@ import {
|
|||||||
useDuplicateSkill,
|
useDuplicateSkill,
|
||||||
useInstallSkillUpload,
|
useInstallSkillUpload,
|
||||||
useReconcileCustomSkills,
|
useReconcileCustomSkills,
|
||||||
|
useSetSkillFeatured,
|
||||||
useSetSkillPinned,
|
useSetSkillPinned,
|
||||||
useSetSkillPublished,
|
useSetSkillPublished,
|
||||||
useSkills,
|
useSkills,
|
||||||
useValidateSkillUpload,
|
useValidateSkillUpload,
|
||||||
} from "@/core/skills/hooks";
|
} from "@/core/skills/hooks";
|
||||||
|
import { useViewMode } from "@/core/system-settings/hooks";
|
||||||
import type { Skill } from "@/core/skills/type";
|
import type { Skill } from "@/core/skills/type";
|
||||||
import { env } from "@/env";
|
import { env } from "@/env";
|
||||||
import { desensitize } from "@/lib/desensitize";
|
import { desensitize } from "@/lib/desensitize";
|
||||||
@@ -100,6 +97,15 @@ export function SkillSettingsPage({ onClose }: { onClose?: () => void } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const PAGE_SIZE = 10;
|
const PAGE_SIZE = 10;
|
||||||
|
type SkillSort =
|
||||||
|
| "time_desc"
|
||||||
|
| "time_asc"
|
||||||
|
| "activity_desc"
|
||||||
|
| "activity_asc"
|
||||||
|
| "usage_desc"
|
||||||
|
| "usage_asc"
|
||||||
|
| "name_asc"
|
||||||
|
| "name_desc";
|
||||||
|
|
||||||
/** 重新扫描成功 toast:仅暗色模式使用,浅色走 Sonner 默认样式 */
|
/** 重新扫描成功 toast:仅暗色模式使用,浅色走 Sonner 默认样式 */
|
||||||
const rescanSuccessToastDarkOptions = {
|
const rescanSuccessToastDarkOptions = {
|
||||||
@@ -144,10 +150,12 @@ function SkillSettingsList({ onClose }: { onClose?: () => void }) {
|
|||||||
const [archiveSheetOpen, setArchiveSheetOpen] = useState(false);
|
const [archiveSheetOpen, setArchiveSheetOpen] = useState(false);
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
const [tagIds, setTagIds] = useState<string[]>([]);
|
const [tagIds, setTagIds] = useState<string[]>([]);
|
||||||
|
const [sort, setSort] = useState<SkillSort>("time_desc");
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
|
const [viewMode, setViewMode] = useViewMode("skill");
|
||||||
const reconcileMutation = useReconcileCustomSkills();
|
const reconcileMutation = useReconcileCustomSkills();
|
||||||
// Name + tag filtering is resolved server-side via the /api/skills query.
|
// Name + tag filtering is resolved server-side via the /api/skills query.
|
||||||
const { skills, isLoading, error } = useSkills({ search, tagIds });
|
const { skills, isLoading, error } = useSkills({ search, tagIds, sort });
|
||||||
|
|
||||||
const storedAuth = useMemo(() => getStoredAuth(), []);
|
const storedAuth = useMemo(() => getStoredAuth(), []);
|
||||||
const currentUserId = storedAuth?.user_id ?? null;
|
const currentUserId = storedAuth?.user_id ?? null;
|
||||||
@@ -193,25 +201,36 @@ function SkillSettingsList({ onClose }: { onClose?: () => void }) {
|
|||||||
}, [skills, currentUserId]);
|
}, [skills, currentUserId]);
|
||||||
|
|
||||||
const filteredSkills = filter === "mine" ? activeMine : activeAll;
|
const filteredSkills = filter === "mine" ? activeMine : activeAll;
|
||||||
|
const orderedSkills = useMemo(
|
||||||
|
() =>
|
||||||
|
filteredSkills
|
||||||
|
.map((skill, index) => ({ skill, index }))
|
||||||
|
.sort((a, b) => {
|
||||||
|
// 置顶(featured)决定排序;钉选(pinned)只管防归档,不影响顺序。
|
||||||
|
const featuredDelta =
|
||||||
|
Number(!!b.skill.featured) - Number(!!a.skill.featured);
|
||||||
|
return featuredDelta || a.index - b.index;
|
||||||
|
})
|
||||||
|
.map(({ skill }) => skill),
|
||||||
|
[filteredSkills],
|
||||||
|
);
|
||||||
const staleCount = staleVisible.length;
|
const staleCount = staleVisible.length;
|
||||||
const archivedCount = archivedVisible.length;
|
const archivedCount = archivedVisible.length;
|
||||||
|
|
||||||
const totalPages = Math.max(1, Math.ceil(filteredSkills.length / PAGE_SIZE));
|
const totalPages = Math.max(1, Math.ceil(orderedSkills.length / PAGE_SIZE));
|
||||||
// Filter / search / tag changes may shrink the result set — pull the page
|
// Filter / search / tag changes may shrink the result set — pull the page
|
||||||
// back into range without forcing a reset on every keystroke.
|
// back into range without forcing a reset on every keystroke.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (page > totalPages) setPage(totalPages);
|
if (page > totalPages) setPage(totalPages);
|
||||||
}, [page, totalPages]);
|
}, [page, totalPages]);
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1);
|
||||||
|
}, [search, tagIds, sort]);
|
||||||
const pagedSkills = useMemo(
|
const pagedSkills = useMemo(
|
||||||
() => filteredSkills.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE),
|
() => orderedSkills.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE),
|
||||||
[filteredSkills, page],
|
[orderedSkills, page],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleCreateSkill = () => {
|
|
||||||
onClose?.();
|
|
||||||
router.push("/?mode=skill");
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRescan = async () => {
|
const handleRescan = async () => {
|
||||||
try {
|
try {
|
||||||
const result = await reconcileMutation.mutateAsync();
|
const result = await reconcileMutation.mutateAsync();
|
||||||
@@ -311,10 +330,6 @@ function SkillSettingsList({ onClose }: { onClose?: () => void }) {
|
|||||||
<Upload className="size-4" />
|
<Upload className="size-4" />
|
||||||
{t.settings.skills.installSkill}
|
{t.settings.skills.installSkill}
|
||||||
</Button>
|
</Button>
|
||||||
<Button size="sm" onClick={handleCreateSkill}>
|
|
||||||
<SparklesIcon className="size-4" />
|
|
||||||
{t.settings.skills.createSkill}
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<TagSearchBar
|
<TagSearchBar
|
||||||
@@ -322,36 +337,53 @@ function SkillSettingsList({ onClose }: { onClose?: () => void }) {
|
|||||||
onSearchChange={setSearch}
|
onSearchChange={setSearch}
|
||||||
tagIds={tagIds}
|
tagIds={tagIds}
|
||||||
onTagIdsChange={setTagIds}
|
onTagIdsChange={setTagIds}
|
||||||
|
actions={
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<ViewModeToggle value={viewMode} onChange={setViewMode} />
|
||||||
|
<Select value={sort} onValueChange={(v) => setSort(v as SkillSort)}>
|
||||||
|
<SelectTrigger
|
||||||
|
className="h-9 w-full gap-2 px-3 text-xs sm:w-[148px]"
|
||||||
|
title="排序"
|
||||||
|
>
|
||||||
|
<ArrowDownUpIcon className="text-muted-foreground size-3.5" />
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent position="popper" side="bottom" sideOffset={4}>
|
||||||
|
<SelectItem value="time_desc">最新创建</SelectItem>
|
||||||
|
<SelectItem value="time_asc">最早创建</SelectItem>
|
||||||
|
<SelectItem value="activity_desc">最近使用</SelectItem>
|
||||||
|
<SelectItem value="activity_asc">最早使用</SelectItem>
|
||||||
|
<SelectItem value="usage_desc">使用最多</SelectItem>
|
||||||
|
<SelectItem value="usage_asc">使用最少</SelectItem>
|
||||||
|
<SelectItem value="name_asc">名称 A-Z</SelectItem>
|
||||||
|
<SelectItem value="name_desc">名称 Z-A</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<div className="text-muted-foreground text-sm">{t.common.loading}</div>
|
<div className="text-muted-foreground text-sm">{t.common.loading}</div>
|
||||||
)}
|
)}
|
||||||
{error && <div className="text-destructive text-sm">Error: {error.message}</div>}
|
{error && <div className="text-destructive text-sm">Error: {error.message}</div>}
|
||||||
{!isLoading && !error && filteredSkills.length === 0 && (
|
{!isLoading && !error && filteredSkills.length === 0 && (
|
||||||
<EmptySkill onCreateSkill={handleCreateSkill} />
|
<EmptySkill />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* —— 原纵向列表布局(保留备查)——
|
|
||||||
{!isLoading && !error &&
|
|
||||||
filteredSkills.length > 0 &&
|
|
||||||
pagedSkills.map((skill) => (
|
|
||||||
<SkillRow
|
|
||||||
key={skill.name}
|
|
||||||
skill={skill}
|
|
||||||
currentUserId={currentUserId}
|
|
||||||
isAdmin={isAdmin}
|
|
||||||
/>
|
|
||||||
))} */}
|
|
||||||
{/* card */}
|
|
||||||
{!isLoading && !error && filteredSkills.length > 0 && (
|
{!isLoading && !error && filteredSkills.length > 0 && (
|
||||||
<div className="grid grid-cols-1 items-stretch gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
<div
|
||||||
|
className={cn(
|
||||||
|
viewMode === "card"
|
||||||
|
? "grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3"
|
||||||
|
: "flex flex-col gap-3",
|
||||||
|
)}
|
||||||
|
>
|
||||||
{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}
|
||||||
className="h-full"
|
layout={viewMode === "card" ? "card" : "row"}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -408,16 +440,19 @@ export function SkillRow({
|
|||||||
skill,
|
skill,
|
||||||
currentUserId,
|
currentUserId,
|
||||||
isAdmin,
|
isAdmin,
|
||||||
className,
|
layout = "row",
|
||||||
}: {
|
}: {
|
||||||
skill: Skill;
|
skill: Skill;
|
||||||
currentUserId: string | null;
|
currentUserId: string | null;
|
||||||
isAdmin: boolean;
|
isAdmin: boolean;
|
||||||
className?: string;
|
/** "row" = full-width horizontal item (default); "card" = grid card cell. */
|
||||||
|
layout?: "row" | "card";
|
||||||
}) {
|
}) {
|
||||||
|
const isCard = layout === "card";
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const setPublished = useSetSkillPublished();
|
const setPublished = useSetSkillPublished();
|
||||||
const setPinned = useSetSkillPinned();
|
const setPinned = useSetSkillPinned();
|
||||||
|
const setFeatured = useSetSkillFeatured();
|
||||||
const deleteSkill = useDeleteCustomSkill();
|
const deleteSkill = useDeleteCustomSkill();
|
||||||
const duplicateSkillMutation = useDuplicateSkill();
|
const duplicateSkillMutation = useDuplicateSkill();
|
||||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||||
@@ -497,376 +532,251 @@ export function SkillRow({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleToggleFeatured() {
|
||||||
|
const next = !skill.featured;
|
||||||
|
try {
|
||||||
|
await setFeatured.mutateAsync({ skillName: skill.name, featured: next });
|
||||||
|
toast.success(
|
||||||
|
next
|
||||||
|
? t.settings.skills.featureSuccess
|
||||||
|
: t.settings.skills.unfeatureSuccess,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const badgeGroup = (
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className={cn(isCard && "truncate font-medium")}>
|
||||||
|
{desensitize(skill.name)}
|
||||||
|
</span>
|
||||||
|
{isBuiltin && (
|
||||||
|
<Badge variant="secondary" className="text-xs">
|
||||||
|
{t.settings.skills.badgeBuiltin}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{isOwned && (
|
||||||
|
<Badge
|
||||||
|
variant="default"
|
||||||
|
className="bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-300 text-xs"
|
||||||
|
>
|
||||||
|
{t.settings.skills.badgeMine}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{isFromOthers && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-blue-500/30 text-blue-700 dark:text-blue-300 text-xs"
|
||||||
|
title={
|
||||||
|
skill.owner_user_id
|
||||||
|
? t.settings.skills.badgeFromOthersTitle.replace(
|
||||||
|
"{user_id}",
|
||||||
|
skill.owner_user_id,
|
||||||
|
)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t.settings.skills.badgeFromOthers}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{isOwned && skill.published && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
|
||||||
|
title={t.settings.skills.badgePublishedTitle}
|
||||||
|
>
|
||||||
|
<GlobeIcon className="size-3" />
|
||||||
|
{t.settings.skills.badgePublished}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{isCustom && !isBuiltin && skill.source === "agent" && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-cyan-500/30 text-cyan-700 dark:text-cyan-300 text-xs"
|
||||||
|
title={t.settings.skills.badgeSourceAgentTitle}
|
||||||
|
>
|
||||||
|
{t.settings.skills.badgeSourceAgent}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{isCustom && !isBuiltin && skill.source === "upload" && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-zinc-400/40 text-zinc-600 dark:text-zinc-400 text-xs"
|
||||||
|
title={t.settings.skills.badgeSourceUploadTitle}
|
||||||
|
>
|
||||||
|
{t.settings.skills.badgeSourceUpload}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{skill.featured && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-amber-500/30 text-amber-700 dark:text-amber-300 text-xs"
|
||||||
|
title={t.settings.skills.badgeFeaturedTitle}
|
||||||
|
>
|
||||||
|
{t.settings.skills.badgeFeatured}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{skill.pinned && (
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="border-purple-500/30 text-purple-700 dark:text-purple-300 text-xs"
|
||||||
|
title={t.settings.skills.badgePinnedTitle}
|
||||||
|
>
|
||||||
|
{t.settings.skills.badgePinned}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const metaNodes = (
|
||||||
|
<>
|
||||||
|
{skill.use_count !== undefined && (
|
||||||
|
<div className="text-muted-foreground mt-1 text-xs">
|
||||||
|
{skill.use_count > 0
|
||||||
|
? t.settings.skills.useCountInline.replace(
|
||||||
|
"{count}",
|
||||||
|
String(skill.use_count),
|
||||||
|
)
|
||||||
|
: t.settings.skills.useCountInlineZero}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{(skill.tags?.length ?? 0) > 0 && (
|
||||||
|
<TagChipList tags={skill.tags!} className="mt-2" />
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
const actionButtons = (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 shrink-0"
|
||||||
|
onClick={() => setTagPickerOpen(true)}
|
||||||
|
title={t.adminTags.manageTags}
|
||||||
|
>
|
||||||
|
<TagsIcon className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
{canManage && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-8 shrink-0",
|
||||||
|
skill.featured && "text-amber-600 hover:text-amber-700",
|
||||||
|
)}
|
||||||
|
disabled={setFeatured.isPending}
|
||||||
|
onClick={() => void handleToggleFeatured()}
|
||||||
|
title={
|
||||||
|
skill.featured
|
||||||
|
? t.settings.skills.unfeatureAction
|
||||||
|
: t.settings.skills.featureAction
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<PinIcon
|
||||||
|
className={cn("size-3.5", skill.featured && "fill-current")}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{canManage && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-8 shrink-0",
|
||||||
|
skill.pinned && "text-emerald-600 hover:text-emerald-700",
|
||||||
|
)}
|
||||||
|
disabled={setPinned.isPending}
|
||||||
|
onClick={() => void handleTogglePinned()}
|
||||||
|
title={
|
||||||
|
skill.pinned
|
||||||
|
? t.settings.skills.unpinAction
|
||||||
|
: t.settings.skills.pinAction
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<BookmarkIcon
|
||||||
|
className={cn("size-3.5", skill.pinned && "fill-current")}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{canTogglePublish && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 shrink-0"
|
||||||
|
disabled={setPublished.isPending}
|
||||||
|
onClick={() => void handleTogglePublished(!skill.published)}
|
||||||
|
title={
|
||||||
|
skill.published
|
||||||
|
? t.settings.skills.unpublishAction
|
||||||
|
: t.settings.skills.publishAction
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{skill.published ? (
|
||||||
|
<LockIcon className="size-3.5" />
|
||||||
|
) : (
|
||||||
|
<GlobeIcon className="size-3.5" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 shrink-0"
|
||||||
|
disabled={duplicateSkillMutation.isPending}
|
||||||
|
onClick={handleOpenDuplicate}
|
||||||
|
title="复制为新技能"
|
||||||
|
>
|
||||||
|
<CopyIcon className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
{canManage && (
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
|
||||||
|
onClick={() => setConfirmDeleteOpen(true)}
|
||||||
|
title={t.settings.skills.deleteAction}
|
||||||
|
>
|
||||||
|
<Trash2Icon className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
{isCard ? (
|
||||||
{/* —— 原 Item 列表行布局(保留备查)——
|
<div className="flex h-full min-w-0 flex-col rounded-lg border p-3 transition-shadow hover:shadow-sm dark:border-[#213D5E] dark:bg-[#02244C] dark:text-white">
|
||||||
<Item className="w-full dark:border-[#213D5E] dark:bg-[#02244C] dark:text-white" variant="outline">
|
|
||||||
<ItemContent
|
|
||||||
className="cursor-pointer"
|
|
||||||
onClick={() => setDetailOpen(true)}
|
|
||||||
>
|
|
||||||
<ItemTitle>
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
<span>{desensitize(skill.name)}</span>
|
|
||||||
{isBuiltin && (
|
|
||||||
<Badge variant="secondary" className="text-xs">
|
|
||||||
{t.settings.skills.badgeBuiltin}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isOwned && (
|
|
||||||
<Badge
|
|
||||||
variant="default"
|
|
||||||
className="bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-300 text-xs"
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgeMine}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isFromOthers && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-blue-500/30 text-blue-700 dark:text-blue-300 text-xs"
|
|
||||||
title={
|
|
||||||
skill.owner_user_id
|
|
||||||
? t.settings.skills.badgeFromOthersTitle.replace(
|
|
||||||
"{user_id}",
|
|
||||||
skill.owner_user_id,
|
|
||||||
)
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgeFromOthers}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isOwned && skill.published && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
|
|
||||||
title={t.settings.skills.badgePublishedTitle}
|
|
||||||
>
|
|
||||||
<GlobeIcon className="size-3" />
|
|
||||||
{t.settings.skills.badgePublished}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isCustom && !isBuiltin && skill.source === "agent" && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-cyan-500/30 text-cyan-700 dark:text-cyan-300 text-xs"
|
|
||||||
title={t.settings.skills.badgeSourceAgentTitle}
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgeSourceAgent}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isCustom && !isBuiltin && skill.source === "upload" && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-zinc-400/40 text-zinc-600 dark:text-zinc-400 text-xs"
|
|
||||||
title={t.settings.skills.badgeSourceUploadTitle}
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgeSourceUpload}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{skill.pinned && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-purple-500/30 text-purple-700 dark:text-purple-300 text-xs"
|
|
||||||
title={t.settings.skills.badgePinnedTitle}
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgePinned}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</ItemTitle>
|
|
||||||
<ItemDescription className="line-clamp-4">
|
|
||||||
{desensitize(skill.description ?? "")}
|
|
||||||
</ItemDescription>
|
|
||||||
{skill.use_count !== undefined && (
|
|
||||||
<div className="text-muted-foreground mt-1 text-xs">
|
|
||||||
{skill.use_count > 0
|
|
||||||
? t.settings.skills.useCountInline.replace(
|
|
||||||
"{count}",
|
|
||||||
String(skill.use_count),
|
|
||||||
)
|
|
||||||
: t.settings.skills.useCountInlineZero}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{(skill.tags?.length ?? 0) > 0 && (
|
|
||||||
<TagChipList tags={skill.tags!} className="mt-2" />
|
|
||||||
)}
|
|
||||||
</ItemContent>
|
|
||||||
<ItemActions>
|
|
||||||
{isAdmin && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
onClick={() => setTagPickerOpen(true)}
|
|
||||||
title={t.adminTags.manageTags}
|
|
||||||
>
|
|
||||||
<TagsIcon className="size-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{canManage && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
disabled={setPinned.isPending}
|
|
||||||
onClick={() => void handleTogglePinned()}
|
|
||||||
title={
|
|
||||||
skill.pinned
|
|
||||||
? t.settings.skills.unpinAction
|
|
||||||
: t.settings.skills.pinAction
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{skill.pinned ? (
|
|
||||||
<PinOffIcon className="size-3.5" />
|
|
||||||
) : (
|
|
||||||
<PinIcon className="size-3.5" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{canTogglePublish && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
disabled={setPublished.isPending}
|
|
||||||
onClick={() => void handleTogglePublished(!skill.published)}
|
|
||||||
title={
|
|
||||||
skill.published
|
|
||||||
? t.settings.skills.unpublishAction
|
|
||||||
: t.settings.skills.publishAction
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{skill.published ? (
|
|
||||||
<LockIcon className="size-3.5" />
|
|
||||||
) : (
|
|
||||||
<GlobeIcon className="size-3.5" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
disabled={duplicateSkillMutation.isPending}
|
|
||||||
onClick={handleOpenDuplicate}
|
|
||||||
title="复制为新技能"
|
|
||||||
>
|
|
||||||
<CopyIcon className="size-3.5" />
|
|
||||||
</Button>
|
|
||||||
{canManage && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
|
|
||||||
onClick={() => setConfirmDeleteOpen(true)}
|
|
||||||
title={t.settings.skills.deleteAction}
|
|
||||||
>
|
|
||||||
<Trash2Icon className="size-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</ItemActions>
|
|
||||||
</Item> */}
|
|
||||||
|
|
||||||
<Card
|
|
||||||
className={cn(
|
|
||||||
"group flex h-full min-w-0 cursor-pointer flex-col transition-shadow hover:shadow-md dark:!border-[#213D5E] dark:bg-[#02244C] dark:text-white",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
onClick={() => setDetailOpen(true)}
|
|
||||||
>
|
|
||||||
<CardHeader className="min-w-0 flex flex-col gap-0">
|
|
||||||
<div className="flex min-w-0 items-center gap-2">
|
|
||||||
<div className="bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
|
||||||
<SparklesIcon className="h-5 w-5" />
|
|
||||||
</div>
|
|
||||||
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-2 overflow-hidden">
|
|
||||||
<CardTitle
|
|
||||||
className="min-w-0 flex-1 overflow-hidden text-base text-ellipsis whitespace-nowrap"
|
|
||||||
title={desensitize(skill.name)}
|
|
||||||
>
|
|
||||||
{desensitize(skill.name)}
|
|
||||||
</CardTitle>
|
|
||||||
<Badge variant="secondary" className="shrink-0 text-xs">
|
|
||||||
{isBuiltin
|
|
||||||
? t.settings.skills.badgeBuiltin
|
|
||||||
: skill.category}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-4 mb-1.5 flex min-h-5 flex-wrap items-center gap-1">
|
|
||||||
{isOwned && (
|
|
||||||
<Badge
|
|
||||||
variant="default"
|
|
||||||
className="bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-300 text-xs"
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgeMine}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isFromOthers && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-blue-500/30 text-blue-700 dark:text-blue-300 text-xs"
|
|
||||||
title={
|
|
||||||
skill.owner_user_id
|
|
||||||
? t.settings.skills.badgeFromOthersTitle.replace(
|
|
||||||
"{user_id}",
|
|
||||||
skill.owner_user_id,
|
|
||||||
)
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgeFromOthers}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isOwned && skill.published && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
|
|
||||||
title={t.settings.skills.badgePublishedTitle}
|
|
||||||
>
|
|
||||||
<GlobeIcon className="size-3" />
|
|
||||||
{t.settings.skills.badgePublished}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isCustom && !isBuiltin && skill.source === "agent" && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-cyan-500/30 text-cyan-700 dark:text-cyan-300 text-xs"
|
|
||||||
title={t.settings.skills.badgeSourceAgentTitle}
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgeSourceAgent}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{isCustom && !isBuiltin && skill.source === "upload" && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-zinc-400/40 text-zinc-600 dark:text-zinc-400 text-xs"
|
|
||||||
title={t.settings.skills.badgeSourceUploadTitle}
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgeSourceUpload}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{skill.pinned && (
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="border-purple-500/30 text-purple-700 dark:text-purple-300 text-xs"
|
|
||||||
title={t.settings.skills.badgePinnedTitle}
|
|
||||||
>
|
|
||||||
{t.settings.skills.badgePinned}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="mt-1.5 min-h-10 mb-3">
|
|
||||||
{skill.description ? (
|
|
||||||
<CardDescription className="line-clamp-2 text-sm">
|
|
||||||
{desensitize(skill.description)}
|
|
||||||
</CardDescription>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
<div className="text-muted-foreground mt-0.5 min-h-4 text-xs leading-tight">
|
|
||||||
{skill.use_count !== undefined && skill.use_count > 0
|
|
||||||
? t.settings.skills.useCountInline.replace(
|
|
||||||
"{count}",
|
|
||||||
String(skill.use_count),
|
|
||||||
)
|
|
||||||
: t.settings.skills.useCountInlineZero}
|
|
||||||
</div>
|
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className="min-w-0 flex-1 cursor-pointer"
|
||||||
"min-w-0 max-w-full overflow-hidden pb-0",
|
onClick={() => setDetailOpen(true)}
|
||||||
(skill.tags?.length ?? 0) > 0 ? "pt-2.5" : "min-h-4",
|
|
||||||
)}
|
|
||||||
>
|
>
|
||||||
{(skill.tags?.length ?? 0) > 0 && (
|
{badgeGroup}
|
||||||
<TagChipList tags={skill.tags!} className="w-full" />
|
<p className="text-muted-foreground mt-1 line-clamp-3 text-sm">
|
||||||
)}
|
{desensitize(skill.description ?? "")}
|
||||||
|
</p>
|
||||||
|
{metaNodes}
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
<div className="mt-2 flex flex-wrap items-center justify-end gap-1 border-t pt-2 dark:border-[#213D5E]">
|
||||||
|
{actionButtons}
|
||||||
<CardFooter
|
</div>
|
||||||
className="cursor-default py-0 pt-1.5"
|
</div>
|
||||||
onClick={(e) => e.stopPropagation()}
|
) : (
|
||||||
|
<Item className="w-full dark:border-[#213D5E] dark:bg-[#02244C] dark:text-white" variant="outline">
|
||||||
|
<ItemContent
|
||||||
|
className="cursor-pointer"
|
||||||
|
onClick={() => setDetailOpen(true)}
|
||||||
>
|
>
|
||||||
<div className="flex w-full flex-wrap items-center justify-end gap-1">
|
<ItemTitle>{badgeGroup}</ItemTitle>
|
||||||
{isAdmin && (
|
<ItemDescription className="line-clamp-4">
|
||||||
<Button
|
{desensitize(skill.description ?? "")}
|
||||||
size="icon"
|
</ItemDescription>
|
||||||
variant="ghost"
|
{metaNodes}
|
||||||
className="h-8 w-8 shrink-0"
|
</ItemContent>
|
||||||
onClick={() => setTagPickerOpen(true)}
|
<ItemActions>{actionButtons}</ItemActions>
|
||||||
title={t.adminTags.manageTags}
|
</Item>
|
||||||
>
|
)}
|
||||||
<TagsIcon className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{canManage && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
disabled={setPinned.isPending}
|
|
||||||
onClick={() => void handleTogglePinned()}
|
|
||||||
title={
|
|
||||||
skill.pinned
|
|
||||||
? t.settings.skills.unpinAction
|
|
||||||
: t.settings.skills.pinAction
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{skill.pinned ? (
|
|
||||||
<PinOffIcon className="h-3.5 w-3.5" />
|
|
||||||
) : (
|
|
||||||
<PinIcon className="h-3.5 w-3.5" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{canTogglePublish && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
disabled={setPublished.isPending}
|
|
||||||
onClick={() => void handleTogglePublished(!skill.published)}
|
|
||||||
title={
|
|
||||||
skill.published
|
|
||||||
? t.settings.skills.unpublishAction
|
|
||||||
: t.settings.skills.publishAction
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{skill.published ? (
|
|
||||||
<LockIcon className="h-3.5 w-3.5" />
|
|
||||||
) : (
|
|
||||||
<GlobeIcon className="h-3.5 w-3.5" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0"
|
|
||||||
disabled={duplicateSkillMutation.isPending}
|
|
||||||
onClick={handleOpenDuplicate}
|
|
||||||
title="复制为新技能"
|
|
||||||
>
|
|
||||||
<CopyIcon className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
{canManage && (
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
|
|
||||||
onClick={() => setConfirmDeleteOpen(true)}
|
|
||||||
title={t.settings.skills.deleteAction}
|
|
||||||
>
|
|
||||||
<Trash2Icon className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</CardFooter>
|
|
||||||
</Card>
|
|
||||||
<Dialog open={duplicateOpen} onOpenChange={setDuplicateOpen}>
|
<Dialog open={duplicateOpen} onOpenChange={setDuplicateOpen}>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
@@ -932,15 +842,13 @@ export function SkillRow({
|
|||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
{isAdmin && (
|
<TagPickerDialog
|
||||||
<TagPickerDialog
|
open={tagPickerOpen}
|
||||||
open={tagPickerOpen}
|
onOpenChange={setTagPickerOpen}
|
||||||
onOpenChange={setTagPickerOpen}
|
targetType="skill"
|
||||||
targetType="skill"
|
targetId={skill.name}
|
||||||
targetId={skill.name}
|
currentTags={skill.tags ?? []}
|
||||||
currentTags={skill.tags ?? []}
|
/>
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<SkillDetailDialog
|
<SkillDetailDialog
|
||||||
skillName={skill.name}
|
skillName={skill.name}
|
||||||
open={detailOpen}
|
open={detailOpen}
|
||||||
@@ -950,7 +858,7 @@ export function SkillRow({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function EmptySkill({ onCreateSkill }: { onCreateSkill: () => void }) {
|
function EmptySkill() {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
return (
|
return (
|
||||||
<Empty>
|
<Empty>
|
||||||
@@ -963,9 +871,6 @@ function EmptySkill({ onCreateSkill }: { onCreateSkill: () => void }) {
|
|||||||
{t.settings.skills.emptyDescription}
|
{t.settings.skills.emptyDescription}
|
||||||
</EmptyDescription>
|
</EmptyDescription>
|
||||||
</EmptyHeader>
|
</EmptyHeader>
|
||||||
<EmptyContent>
|
|
||||||
<Button onClick={onCreateSkill}>{t.settings.skills.emptyButton}</Button>
|
|
||||||
</EmptyContent>
|
|
||||||
</Empty>
|
</Empty>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,8 +133,7 @@ export function SkillDetailDialog({
|
|||||||
return stripYamlFrontmatter(contentData?.content ?? "");
|
return stripYamlFrontmatter(contentData?.content ?? "");
|
||||||
}, [contentData]);
|
}, [contentData]);
|
||||||
|
|
||||||
const defaultTab: "detail" | "source" =
|
const defaultTab: "detail" = "detail";
|
||||||
skill && !skill.detail ? "source" : "detail";
|
|
||||||
const selectedTab = activeTab ?? defaultTab;
|
const selectedTab = activeTab ?? defaultTab;
|
||||||
|
|
||||||
function startEditing() {
|
function startEditing() {
|
||||||
@@ -234,10 +233,6 @@ export function SkillDetailDialog({
|
|||||||
{tx.filesSectionTitle}
|
{tx.filesSectionTitle}
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
)}
|
)}
|
||||||
<TabsTrigger value="source" className="text-xs">
|
|
||||||
<FileCode2Icon className="mr-1 size-3.5" />
|
|
||||||
{tx.contentSectionTitle}
|
|
||||||
</TabsTrigger>
|
|
||||||
</TabsList>
|
</TabsList>
|
||||||
|
|
||||||
<div className="flex shrink-0 items-center gap-1">
|
<div className="flex shrink-0 items-center gap-1">
|
||||||
@@ -337,13 +332,9 @@ export function SkillDetailDialog({
|
|||||||
<div className="text-muted-foreground rounded-lg border border-dashed px-4 py-8 text-center">
|
<div className="text-muted-foreground rounded-lg border border-dashed px-4 py-8 text-center">
|
||||||
<FileTextIcon className="mx-auto mb-2 size-6 opacity-40" />
|
<FileTextIcon className="mx-auto mb-2 size-6 opacity-40" />
|
||||||
<p className="text-sm">{tx.detailEmpty}</p>
|
<p className="text-sm">{tx.detailEmpty}</p>
|
||||||
{isOwner ? (
|
{isOwner && canManage ? (
|
||||||
<p className="mt-1 text-xs">
|
|
||||||
Open the SKILL.md tab to view the skill source.
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<p className="mt-1 text-xs">{tx.detailAdminOnlyHint}</p>
|
<p className="mt-1 text-xs">{tx.detailAdminOnlyHint}</p>
|
||||||
)}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|||||||
@@ -20,9 +20,9 @@ import { cn } from "@/lib/utils";
|
|||||||
import { resolveTagColor } from "./tag-colors";
|
import { resolveTagColor } from "./tag-colors";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Admin-only dialog to set the tags on one resource. Clicking a tag binds or
|
* Dialog to set the tags on one resource. Clicking a tag binds or unbinds it
|
||||||
* unbinds it immediately (no separate save step). Only tags of ``targetType``
|
* immediately (no separate save step). Only tags of ``targetType`` are offered,
|
||||||
* are offered, enforcing "a tag may only tag its own type".
|
* enforcing "a tag may only tag its own type".
|
||||||
*/
|
*/
|
||||||
export function TagPickerDialog({
|
export function TagPickerDialog({
|
||||||
open,
|
open,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon, SearchIcon } from "lucide-react";
|
import { CheckIcon, ChevronDownIcon, ChevronUpIcon, SearchIcon } from "lucide-react";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||||
|
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
@@ -31,12 +31,14 @@ export function TagSearchBar({
|
|||||||
tagIds,
|
tagIds,
|
||||||
onTagIdsChange,
|
onTagIdsChange,
|
||||||
className,
|
className,
|
||||||
|
actions,
|
||||||
}: {
|
}: {
|
||||||
targetType: TagType;
|
targetType: TagType;
|
||||||
onSearchChange: (value: string) => void;
|
onSearchChange: (value: string) => void;
|
||||||
tagIds: string[];
|
tagIds: string[];
|
||||||
onTagIdsChange: (value: string[]) => void;
|
onTagIdsChange: (value: string[]) => void;
|
||||||
className?: string;
|
className?: string;
|
||||||
|
actions?: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const { data: tags } = useTags(targetType);
|
const { data: tags } = useTags(targetType);
|
||||||
@@ -67,14 +69,31 @@ export function TagSearchBar({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex flex-col gap-2.5", className)}>
|
<div className={cn("flex flex-col gap-2.5", className)}>
|
||||||
<div className="relative">
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||||
<SearchIcon className="text-muted-foreground dark:text-[#60a5fa]/90 absolute left-2.5 top-1/2 size-4 -translate-y-1/2" />
|
<div className="relative min-w-0 flex-1">
|
||||||
<Input
|
<SearchIcon className="text-muted-foreground dark:text-[#60a5fa]/90 absolute left-2.5 top-1/2 size-4 -translate-y-1/2" />
|
||||||
value={input}
|
<Input
|
||||||
onChange={(e) => setInput(e.target.value)}
|
value={input}
|
||||||
placeholder={t.adminTags.searchPlaceholder}
|
onChange={(e) => setInput(e.target.value)}
|
||||||
className="pl-8"
|
placeholder={t.adminTags.searchPlaceholder}
|
||||||
/>
|
className="pl-8"
|
||||||
|
name="tag-search"
|
||||||
|
// A `type="password"` field elsewhere on the page (e.g. the private
|
||||||
|
// square access gate) makes browsers / password managers pick the
|
||||||
|
// nearest text input as the "username" and autofill the account into
|
||||||
|
// it. Mark this search box so it is never treated as a credential
|
||||||
|
// field.
|
||||||
|
autoComplete="off"
|
||||||
|
data-1p-ignore
|
||||||
|
data-lpignore="true"
|
||||||
|
data-form-type="other"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{actions && (
|
||||||
|
<div className="flex w-full shrink-0 justify-end sm:w-auto">
|
||||||
|
{actions}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{allTags.length > 0 && (
|
{allTags.length > 0 && (
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { LayoutGridIcon, ListIcon } from "lucide-react";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import type { ViewMode } from "@/core/system-settings/api";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compact card/list switch shown in the header of the skills and agents lists.
|
||||||
|
* Purely presentational — the parent owns the `value` (resolved from the user's
|
||||||
|
* local override or the admin default via `useViewMode`) and persists changes.
|
||||||
|
*/
|
||||||
|
export function ViewModeToggle({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
value: ViewMode;
|
||||||
|
onChange: (mode: ViewMode) => void;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"bg-muted/60 inline-flex items-center gap-0.5 rounded-md p-0.5",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
role="group"
|
||||||
|
aria-label="展示模式"
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="icon"
|
||||||
|
variant={value === "card" ? "default" : "ghost"}
|
||||||
|
className="size-7"
|
||||||
|
onClick={() => onChange("card")}
|
||||||
|
title="卡片模式"
|
||||||
|
aria-pressed={value === "card"}
|
||||||
|
>
|
||||||
|
<LayoutGridIcon className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="icon"
|
||||||
|
variant={value === "list" ? "default" : "ghost"}
|
||||||
|
className="size-7"
|
||||||
|
onClick={() => onChange("list")}
|
||||||
|
title="列表模式"
|
||||||
|
aria-pressed={value === "list"}
|
||||||
|
>
|
||||||
|
<ListIcon className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,10 +6,12 @@ import {
|
|||||||
BrainIcon,
|
BrainIcon,
|
||||||
CalendarClockIcon,
|
CalendarClockIcon,
|
||||||
ChevronsUpDown,
|
ChevronsUpDown,
|
||||||
|
DatabaseZapIcon,
|
||||||
GaugeIcon,
|
GaugeIcon,
|
||||||
HistoryIcon,
|
HistoryIcon,
|
||||||
MessageSquareCodeIcon,
|
MessageSquareCodeIcon,
|
||||||
MessageSquarePlusIcon,
|
MessageSquarePlusIcon,
|
||||||
|
ScrollTextIcon,
|
||||||
Settings2Icon,
|
Settings2Icon,
|
||||||
SettingsIcon,
|
SettingsIcon,
|
||||||
ShieldCheckIcon,
|
ShieldCheckIcon,
|
||||||
@@ -36,6 +38,10 @@ import {
|
|||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
import { useUnreadCount } from "@/core/notifications";
|
import { useUnreadCount } from "@/core/notifications";
|
||||||
|
import {
|
||||||
|
loadLogSystemSettings,
|
||||||
|
type LogSystemSettings,
|
||||||
|
} from "@/core/system-settings/api";
|
||||||
|
|
||||||
import { NotificationDialog } from "./notification-dialog";
|
import { NotificationDialog } from "./notification-dialog";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
@@ -71,6 +77,7 @@ export function WorkspaceNavMenu() {
|
|||||||
>("appearance");
|
>("appearance");
|
||||||
const [notificationOpen, setNotificationOpen] = useState(false);
|
const [notificationOpen, setNotificationOpen] = useState(false);
|
||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
|
const [logSystem, setLogSystem] = useState<LogSystemSettings | null>(null);
|
||||||
const { open: isSidebarOpen } = useSidebar();
|
const { open: isSidebarOpen } = useSidebar();
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const { data: unreadCount = 0 } = useUnreadCount();
|
const { data: unreadCount = 0 } = useUnreadCount();
|
||||||
@@ -79,6 +86,21 @@ export function WorkspaceNavMenu() {
|
|||||||
setMounted(true);
|
setMounted(true);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isAdmin) return;
|
||||||
|
let cancelled = false;
|
||||||
|
loadLogSystemSettings()
|
||||||
|
.then((settings) => {
|
||||||
|
if (!cancelled) setLogSystem(settings);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!cancelled) setLogSystem(null);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [isAdmin]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SettingsDialog
|
<SettingsDialog
|
||||||
@@ -166,6 +188,16 @@ export function WorkspaceNavMenu() {
|
|||||||
大模型调用统计
|
大模型调用统计
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
|
{isAdmin && (
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() =>
|
||||||
|
navigate("/page/workspace/settings/checkpoint-migration")
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<DatabaseZapIcon />
|
||||||
|
Checkpoint 迁移
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
{isAdmin && (
|
{isAdmin && (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={() => navigate("/page/workspace/admin")}
|
onClick={() => navigate("/page/workspace/admin")}
|
||||||
@@ -200,12 +232,24 @@ export function WorkspaceNavMenu() {
|
|||||||
技能管理
|
技能管理
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
{isAdmin && (
|
<DropdownMenuItem
|
||||||
|
onClick={() => navigate("/page/workspace/admin/tags")}
|
||||||
|
>
|
||||||
|
<TagsIcon />
|
||||||
|
{t.adminTags.title}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
{isAdmin && logSystem?.enabled && logSystem.url && (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={() => navigate("/page/workspace/admin/tags")}
|
onClick={() =>
|
||||||
|
window.open(
|
||||||
|
logSystem.url,
|
||||||
|
"_blank",
|
||||||
|
"noopener,noreferrer",
|
||||||
|
)
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<TagsIcon />
|
<ScrollTextIcon />
|
||||||
{t.adminTags.title}
|
{logSystem.label || "日志系统"}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
</DropdownMenuGroup>
|
</DropdownMenuGroup>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { useTheme } from "@/contexts/ThemeContext";
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
import { RecentChatList } from "./recent-chat-list";
|
import { RecentChatList } from "./recent-chat-list";
|
||||||
|
import { RecentRoundtableList } from "./recent-roundtable-list";
|
||||||
import { RecentWritingList } from "./recent-writing-list";
|
import { RecentWritingList } from "./recent-writing-list";
|
||||||
import { WorkspaceHeader } from "./workspace-header";
|
import { WorkspaceHeader } from "./workspace-header";
|
||||||
import { WorkspaceNavChatList } from "./workspace-nav-chat-list";
|
import { WorkspaceNavChatList } from "./workspace-nav-chat-list";
|
||||||
@@ -46,6 +47,7 @@ export function WorkspaceSidebar({
|
|||||||
<SidebarContent>
|
<SidebarContent>
|
||||||
<WorkspaceNavChatList showCollapseTrigger={compactChrome} />
|
<WorkspaceNavChatList showCollapseTrigger={compactChrome} />
|
||||||
{isSidebarOpen && <RecentChatList />}
|
{isSidebarOpen && <RecentChatList />}
|
||||||
|
{isSidebarOpen && <RecentRoundtableList />}
|
||||||
{isSidebarOpen && <RecentWritingList />}
|
{isSidebarOpen && <RecentWritingList />}
|
||||||
</SidebarContent>
|
</SidebarContent>
|
||||||
{!compactChrome && (
|
{!compactChrome && (
|
||||||
|
|||||||
@@ -184,6 +184,21 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
|
|||||||
: 'light'
|
: 'light'
|
||||||
: readPersistedTheme();
|
: readPersistedTheme();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof document === 'undefined') return;
|
||||||
|
|
||||||
|
const root = document.documentElement;
|
||||||
|
|
||||||
|
if (theme === 'dark') {
|
||||||
|
root.setAttribute('theme-mode', 'dark');
|
||||||
|
root.classList.add('dark');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
root.removeAttribute('theme-mode');
|
||||||
|
root.classList.remove('dark');
|
||||||
|
}, [theme]);
|
||||||
|
|
||||||
const toggleTheme = () => {
|
const toggleTheme = () => {
|
||||||
setNextTheme(theme === 'dark' ? 'light' : 'dark');
|
setNextTheme(theme === 'dark' ? 'light' : 'dark');
|
||||||
markExplicitChoice();
|
markExplicitChoice();
|
||||||
|
|||||||
@@ -35,6 +35,144 @@ export interface AdminMemoryResponse {
|
|||||||
buckets: AdminMemoryBucket[];
|
buckets: AdminMemoryBucket[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AdminUserQaItem {
|
||||||
|
run_id: string;
|
||||||
|
thread_id: string;
|
||||||
|
thread_title: string;
|
||||||
|
assistant_id: string;
|
||||||
|
status: string;
|
||||||
|
model_name: string;
|
||||||
|
question: string;
|
||||||
|
answer: string;
|
||||||
|
total_tokens: number;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminUserQaPageResponse {
|
||||||
|
user_id: string;
|
||||||
|
page: number;
|
||||||
|
page_size: number;
|
||||||
|
total: number;
|
||||||
|
items: AdminUserQaItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminLeaderboardUser {
|
||||||
|
user_id: string;
|
||||||
|
email: string;
|
||||||
|
system_role: string;
|
||||||
|
thread_count: number;
|
||||||
|
run_count: number;
|
||||||
|
qa_count: number;
|
||||||
|
llm_call_count: number;
|
||||||
|
tool_call_count: number;
|
||||||
|
skill_call_count: number;
|
||||||
|
total_tokens: number;
|
||||||
|
input_tokens: number;
|
||||||
|
output_tokens: number;
|
||||||
|
last_active_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminLeaderboardSkill {
|
||||||
|
name: string;
|
||||||
|
call_count: number;
|
||||||
|
user_count: number;
|
||||||
|
success_count: number;
|
||||||
|
error_count: number;
|
||||||
|
avg_duration_ms: number;
|
||||||
|
last_used_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminLeaderboardDimension {
|
||||||
|
name: string;
|
||||||
|
count: number;
|
||||||
|
user_count: number;
|
||||||
|
success_count: number;
|
||||||
|
error_count: number;
|
||||||
|
total_tokens: number;
|
||||||
|
last_seen_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminLeaderboardQuestion {
|
||||||
|
text: string;
|
||||||
|
user_id: string;
|
||||||
|
email: string;
|
||||||
|
thread_id: string;
|
||||||
|
run_id: string;
|
||||||
|
asked_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminLeaderboardTrendPoint {
|
||||||
|
date: string;
|
||||||
|
runs: number;
|
||||||
|
questions: number;
|
||||||
|
tokens: number;
|
||||||
|
users: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminLeaderboardOverview {
|
||||||
|
total_users: number;
|
||||||
|
active_users: number;
|
||||||
|
total_threads: number;
|
||||||
|
total_runs: number;
|
||||||
|
total_questions: number;
|
||||||
|
total_tokens: number;
|
||||||
|
total_skill_calls: number;
|
||||||
|
total_tool_calls: number;
|
||||||
|
error_runs: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminLeaderboardResponse {
|
||||||
|
range_days: number;
|
||||||
|
since: string;
|
||||||
|
until: string;
|
||||||
|
status?: "ready" | "running" | "refreshing";
|
||||||
|
generated_at?: string;
|
||||||
|
message?: string;
|
||||||
|
overview: AdminLeaderboardOverview;
|
||||||
|
users_by_activity: AdminLeaderboardUser[];
|
||||||
|
users_by_questions: AdminLeaderboardUser[];
|
||||||
|
users_by_tokens: AdminLeaderboardUser[];
|
||||||
|
skills: AdminLeaderboardSkill[];
|
||||||
|
tools: AdminLeaderboardSkill[];
|
||||||
|
models: AdminLeaderboardDimension[];
|
||||||
|
agents: AdminLeaderboardDimension[];
|
||||||
|
run_statuses: AdminLeaderboardDimension[];
|
||||||
|
recent_questions: AdminLeaderboardQuestion[];
|
||||||
|
frequent_questions: AdminLeaderboardQuestion[];
|
||||||
|
trends: AdminLeaderboardTrendPoint[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminUserAnalyticsResponse {
|
||||||
|
range_days: number;
|
||||||
|
since: string;
|
||||||
|
until: string;
|
||||||
|
user: AdminLeaderboardUser;
|
||||||
|
overview: AdminLeaderboardOverview;
|
||||||
|
skills: AdminLeaderboardSkill[];
|
||||||
|
tools: AdminLeaderboardSkill[];
|
||||||
|
models: AdminLeaderboardDimension[];
|
||||||
|
agents: AdminLeaderboardDimension[];
|
||||||
|
run_statuses: AdminLeaderboardDimension[];
|
||||||
|
recent_questions: AdminLeaderboardQuestion[];
|
||||||
|
trends: AdminLeaderboardTrendPoint[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminLeaderboardReportResponse {
|
||||||
|
report: string;
|
||||||
|
generated_at: string;
|
||||||
|
cached?: boolean;
|
||||||
|
model_name?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AdminLeaderboardReportStreamEvent =
|
||||||
|
| { event: "meta"; data: { cached?: boolean; model_name?: string | null } }
|
||||||
|
| { event: "cached"; data: { report: string; generated_at?: string | null; model_name?: string | null } }
|
||||||
|
| { event: "thinking"; data: { chunk: string } }
|
||||||
|
| { event: "text"; data: { chunk: string } }
|
||||||
|
| { event: "done"; data: { cached?: boolean; generated_at?: string | null; model_name?: string | null; report?: string } }
|
||||||
|
| { event: "error"; data: { message: string } };
|
||||||
|
|
||||||
const base = () => `${getBackendBaseURL()}/api/admin/users`;
|
const base = () => `${getBackendBaseURL()}/api/admin/users`;
|
||||||
|
|
||||||
async function parse<T>(res: Response, what: string): Promise<T> {
|
async function parse<T>(res: Response, what: string): Promise<T> {
|
||||||
@@ -64,6 +202,22 @@ export async function listUserThreadMessages(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function listUserQa(
|
||||||
|
userId: string,
|
||||||
|
params: { page?: number; pageSize?: number; q?: string } = {},
|
||||||
|
): Promise<AdminUserQaPageResponse> {
|
||||||
|
const search = new URLSearchParams({
|
||||||
|
page: String(params.page ?? 1),
|
||||||
|
page_size: String(params.pageSize ?? 20),
|
||||||
|
});
|
||||||
|
const query = (params.q ?? "").trim();
|
||||||
|
if (query) search.set("q", query);
|
||||||
|
return parse(
|
||||||
|
await apiFetch(`${base()}/${encodeURIComponent(userId)}/qa?${search}`),
|
||||||
|
"Failed to load user Q&A",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export async function getUserMemory(
|
export async function getUserMemory(
|
||||||
userId: string,
|
userId: string,
|
||||||
): Promise<AdminMemoryResponse> {
|
): Promise<AdminMemoryResponse> {
|
||||||
@@ -73,6 +227,133 @@ export async function getUserMemory(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getUserLeaderboard(
|
||||||
|
range: {
|
||||||
|
since: string;
|
||||||
|
until: string;
|
||||||
|
days?: number;
|
||||||
|
},
|
||||||
|
limit = 20,
|
||||||
|
): Promise<AdminLeaderboardResponse> {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
days: String(range.days ?? 30),
|
||||||
|
since: range.since,
|
||||||
|
until: range.until,
|
||||||
|
limit: String(limit),
|
||||||
|
});
|
||||||
|
return parse(
|
||||||
|
await apiFetch(`${base()}/leaderboard?${params}`),
|
||||||
|
"Failed to load leaderboard",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserAnalytics(
|
||||||
|
userId: string,
|
||||||
|
range: { since: string; until: string; days?: number },
|
||||||
|
limit = 20,
|
||||||
|
): Promise<AdminUserAnalyticsResponse> {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
days: String(range.days ?? 30),
|
||||||
|
since: range.since,
|
||||||
|
until: range.until,
|
||||||
|
limit: String(limit),
|
||||||
|
});
|
||||||
|
return parse(
|
||||||
|
await apiFetch(`${base()}/${encodeURIComponent(userId)}/analytics?${params}`),
|
||||||
|
"Failed to load user analytics",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateUserLeaderboardReport(
|
||||||
|
range: { since: string; until: string; days?: number },
|
||||||
|
limit = 30,
|
||||||
|
modelName?: string,
|
||||||
|
): Promise<AdminLeaderboardReportResponse> {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
days: String(range.days ?? 30),
|
||||||
|
since: range.since,
|
||||||
|
until: range.until,
|
||||||
|
limit: String(limit),
|
||||||
|
});
|
||||||
|
if (modelName) params.set("model_name", modelName);
|
||||||
|
return parse(
|
||||||
|
await apiFetch(`${base()}/leaderboard/report?${params}`, {
|
||||||
|
method: "POST",
|
||||||
|
}),
|
||||||
|
"Failed to generate leaderboard report",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseSseFrame(frame: string): AdminLeaderboardReportStreamEvent | null {
|
||||||
|
let event = "message";
|
||||||
|
const dataLines: string[] = [];
|
||||||
|
for (const rawLine of frame.split(/\r?\n/)) {
|
||||||
|
const line = rawLine.trimEnd();
|
||||||
|
if (!line || line.startsWith(":")) continue;
|
||||||
|
if (line.startsWith("event:")) {
|
||||||
|
event = line.slice("event:".length).trim();
|
||||||
|
} else if (line.startsWith("data:")) {
|
||||||
|
dataLines.push(line.slice("data:".length).trimStart());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!dataLines.length) return null;
|
||||||
|
const data = JSON.parse(dataLines.join("\n")) as AdminLeaderboardReportStreamEvent["data"];
|
||||||
|
return { event, data } as AdminLeaderboardReportStreamEvent;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function streamUserLeaderboardReport({
|
||||||
|
range,
|
||||||
|
limit = 30,
|
||||||
|
modelName,
|
||||||
|
signal,
|
||||||
|
onEvent,
|
||||||
|
}: {
|
||||||
|
range: { since: string; until: string; days?: number };
|
||||||
|
limit?: number;
|
||||||
|
modelName?: string;
|
||||||
|
signal?: AbortSignal;
|
||||||
|
onEvent: (event: AdminLeaderboardReportStreamEvent) => void;
|
||||||
|
}) {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
days: String(range.days ?? 30),
|
||||||
|
since: range.since,
|
||||||
|
until: range.until,
|
||||||
|
limit: String(limit),
|
||||||
|
});
|
||||||
|
if (modelName) params.set("model_name", modelName);
|
||||||
|
const response = await apiFetch(`${base()}/leaderboard/report/stream?${params}`, {
|
||||||
|
method: "POST",
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const err = (await response.json().catch(() => ({}))) as { detail?: string };
|
||||||
|
throw new Error(err.detail ?? `Failed to stream leaderboard report (HTTP ${response.status})`);
|
||||||
|
}
|
||||||
|
if (!response.body) {
|
||||||
|
throw new Error("当前浏览器不支持流式报告读取");
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder("utf-8");
|
||||||
|
let buffer = "";
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });
|
||||||
|
const frames = buffer.split(/\r?\n\r?\n/);
|
||||||
|
buffer = frames.pop() ?? "";
|
||||||
|
for (const frame of frames) {
|
||||||
|
const parsed = parseSseFrame(frame);
|
||||||
|
if (parsed) onEvent(parsed);
|
||||||
|
}
|
||||||
|
if (done) break;
|
||||||
|
}
|
||||||
|
const tail = buffer.trim();
|
||||||
|
if (tail) {
|
||||||
|
const parsed = parseSseFrame(tail);
|
||||||
|
if (parsed) onEvent(parsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function addAdminMemoryEntry(
|
export async function addAdminMemoryEntry(
|
||||||
userId: string,
|
userId: string,
|
||||||
content: string,
|
content: string,
|
||||||
|
|||||||
@@ -5,7 +5,11 @@ import {
|
|||||||
addAdminV1Fact,
|
addAdminV1Fact,
|
||||||
deleteAdminMemoryEntry,
|
deleteAdminMemoryEntry,
|
||||||
deleteAdminV1Fact,
|
deleteAdminV1Fact,
|
||||||
|
generateUserLeaderboardReport,
|
||||||
getUserMemory,
|
getUserMemory,
|
||||||
|
getUserAnalytics,
|
||||||
|
getUserLeaderboard,
|
||||||
|
listUserQa,
|
||||||
listUserThreadMessages,
|
listUserThreadMessages,
|
||||||
listUserThreads,
|
listUserThreads,
|
||||||
replaceAdminMemoryEntry,
|
replaceAdminMemoryEntry,
|
||||||
@@ -13,6 +17,56 @@ import {
|
|||||||
updateAdminV1Section,
|
updateAdminV1Section,
|
||||||
} from "./api";
|
} from "./api";
|
||||||
|
|
||||||
|
export function useUserLeaderboard(
|
||||||
|
range: {
|
||||||
|
since: string;
|
||||||
|
until: string;
|
||||||
|
days?: number;
|
||||||
|
},
|
||||||
|
limit = 20,
|
||||||
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: [
|
||||||
|
"admin-activity",
|
||||||
|
"leaderboard",
|
||||||
|
range.since,
|
||||||
|
range.until,
|
||||||
|
limit,
|
||||||
|
],
|
||||||
|
queryFn: () => getUserLeaderboard(range, limit),
|
||||||
|
refetchInterval: (query) => {
|
||||||
|
const status = query.state.data?.status;
|
||||||
|
return status === "running" || status === "refreshing" ? 3000 : false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUserAnalytics(
|
||||||
|
userId: string | null,
|
||||||
|
range: { since: string; until: string; days?: number },
|
||||||
|
limit = 20,
|
||||||
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["admin-activity", "analytics", userId, range.since, range.until, limit],
|
||||||
|
queryFn: () => getUserAnalytics(userId!, range, limit),
|
||||||
|
enabled: !!userId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGenerateUserLeaderboardReport() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({
|
||||||
|
range,
|
||||||
|
limit,
|
||||||
|
modelName,
|
||||||
|
}: {
|
||||||
|
range: { since: string; until: string; days?: number };
|
||||||
|
limit?: number;
|
||||||
|
modelName?: string;
|
||||||
|
}) => generateUserLeaderboardReport(range, limit ?? 30, modelName),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** Threads owned by a given user. Disabled until a user is picked. */
|
/** Threads owned by a given user. Disabled until a user is picked. */
|
||||||
export function useUserThreads(userId: string | null) {
|
export function useUserThreads(userId: string | null) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
@@ -22,6 +76,17 @@ export function useUserThreads(userId: string | null) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useUserQa(
|
||||||
|
userId: string | null,
|
||||||
|
params: { page: number; pageSize: number; q?: string },
|
||||||
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["admin-activity", "qa", userId, params.page, params.pageSize, params.q ?? ""],
|
||||||
|
queryFn: () => listUserQa(userId!, params),
|
||||||
|
enabled: !!userId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** Messages of a given thread. Disabled until a thread is picked. */
|
/** Messages of a given thread. Disabled until a thread is picked. */
|
||||||
export function useUserThreadMessages(
|
export function useUserThreadMessages(
|
||||||
userId: string | null,
|
userId: string | null,
|
||||||
|
|||||||
@@ -2,11 +2,13 @@ import { getBackendBaseURL } from "@/core/config";
|
|||||||
import { apiFetch } from "@/core/api";
|
import { apiFetch } from "@/core/api";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
Agent,
|
Agent,
|
||||||
AgentSelectorResponse,
|
AgentSelectorResponse,
|
||||||
CreateAgentRequest,
|
AgentSort,
|
||||||
UpdateAgentRequest,
|
CreateAgentRequest,
|
||||||
} from "./types";
|
PaginatedAgents,
|
||||||
|
UpdateAgentRequest,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
const BACKEND_UNAVAILABLE_STATUSES = new Set([502, 503, 504]);
|
const BACKEND_UNAVAILABLE_STATUSES = new Set([502, 503, 504]);
|
||||||
|
|
||||||
@@ -23,13 +25,27 @@ export class AgentNameCheckError extends Error {
|
|||||||
export interface ListAgentsParams {
|
export interface ListAgentsParams {
|
||||||
search?: string;
|
search?: string;
|
||||||
tagIds?: string[];
|
tagIds?: string[];
|
||||||
}
|
/** Pagination scope. Omit for the legacy combined-visibility list. */
|
||||||
|
scope?: "mine" | "square";
|
||||||
|
/** 1-based page index. Providing this (or scope) enables server-side pagination. */
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
sort?: AgentSort;
|
||||||
|
}
|
||||||
|
|
||||||
export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]> {
|
function buildAgentsQuery(params: ListAgentsParams): string {
|
||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
if (params.search) qs.set("search", params.search);
|
if (params.search) qs.set("search", params.search);
|
||||||
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
|
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
|
||||||
const query = qs.toString();
|
if (params.scope) qs.set("scope", params.scope);
|
||||||
|
if (params.page != null) qs.set("page", String(params.page));
|
||||||
|
if (params.pageSize != null) qs.set("page_size", String(params.pageSize));
|
||||||
|
if (params.sort) qs.set("sort", params.sort);
|
||||||
|
return qs.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]> {
|
||||||
|
const query = buildAgentsQuery(params);
|
||||||
const res = await apiFetch(
|
const res = await apiFetch(
|
||||||
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
|
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
|
||||||
);
|
);
|
||||||
@@ -38,6 +54,29 @@ export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]
|
|||||||
return data.agents;
|
return data.agents;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Like {@link listAgents} but returns the pagination envelope (total/page). */
|
||||||
|
export async function listAgentsPaginated(
|
||||||
|
params: ListAgentsParams = {},
|
||||||
|
): Promise<PaginatedAgents> {
|
||||||
|
const query = buildAgentsQuery(params);
|
||||||
|
const res = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
|
||||||
|
);
|
||||||
|
if (!res.ok) throw new Error(`Failed to load agents: ${res.statusText}`);
|
||||||
|
const data = (await res.json()) as {
|
||||||
|
agents: Agent[];
|
||||||
|
total?: number;
|
||||||
|
page?: number;
|
||||||
|
page_size?: number;
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
agents: data.agents,
|
||||||
|
total: data.total ?? data.agents.length,
|
||||||
|
page: data.page ?? params.page ?? 1,
|
||||||
|
pageSize: data.page_size ?? params.pageSize ?? data.agents.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function listAllAgentsAdmin(): Promise<Agent[]> {
|
export async function listAllAgentsAdmin(): Promise<Agent[]> {
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/agents?admin=true`);
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents?admin=true`);
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -90,13 +129,13 @@ export async function deleteAgent(id: string): Promise<void> {
|
|||||||
if (!res.ok) throw new Error(`Failed to delete agent: ${res.statusText}`);
|
if (!res.ok) throw new Error(`Failed to delete agent: ${res.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAgentSelector(): Promise<AgentSelectorResponse> {
|
export async function getAgentSelector(): Promise<AgentSelectorResponse> {
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/selector`);
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/selector`);
|
||||||
if (!res.ok) throw new Error(`Failed to load agent selector: ${res.statusText}`);
|
if (!res.ok) throw new Error(`Failed to load agent selector: ${res.statusText}`);
|
||||||
return res.json() as Promise<AgentSelectorResponse>;
|
return res.json() as Promise<AgentSelectorResponse>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function favoriteAgent(id: string): Promise<void> {
|
export async function favoriteAgent(id: string): Promise<void> {
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/favorite`, {
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/favorite`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
});
|
});
|
||||||
@@ -106,15 +145,35 @@ export async function favoriteAgent(id: string): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function unfavoriteAgent(id: string): Promise<void> {
|
export async function unfavoriteAgent(id: string): Promise<void> {
|
||||||
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/favorite`, {
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/favorite`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||||
throw new Error(err.detail ?? `Failed to unfavorite agent: ${res.statusText}`);
|
throw new Error(err.detail ?? `Failed to unfavorite agent: ${res.statusText}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function pinAgent(id: string): Promise<void> {
|
||||||
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/pin`, {
|
||||||
|
method: "POST",
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||||
|
throw new Error(err.detail ?? `Failed to pin agent: ${res.statusText}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function unpinAgent(id: string): Promise<void> {
|
||||||
|
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/pin`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||||
|
throw new Error(err.detail ?? `Failed to unpin agent: ${res.statusText}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function reorderFeaturedAgents(agentIds: string[]): Promise<void> {
|
export async function reorderFeaturedAgents(agentIds: string[]): Promise<void> {
|
||||||
const res = await apiFetch(
|
const res = await apiFetch(
|
||||||
@@ -152,6 +211,54 @@ export async function listPrivateAgents(password: string): Promise<Agent[]> {
|
|||||||
return data.agents;
|
return data.agents;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ListPrivateAgentsParams {
|
||||||
|
password: string;
|
||||||
|
search?: string;
|
||||||
|
tagIds?: string[];
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
sort?: AgentSort;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Paginated private-square listing (password-gated). */
|
||||||
|
export async function listPrivateAgentsPaginated(
|
||||||
|
params: ListPrivateAgentsParams,
|
||||||
|
): Promise<PaginatedAgents> {
|
||||||
|
const res = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/agents/private-square/list`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
password: params.password,
|
||||||
|
search: params.search || undefined,
|
||||||
|
tag_ids: params.tagIds && params.tagIds.length ? params.tagIds : undefined,
|
||||||
|
page: params.page,
|
||||||
|
page_size: params.pageSize,
|
||||||
|
sort: params.sort,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||||
|
throw new Error(
|
||||||
|
err.detail ?? `Failed to load private agents: ${res.statusText}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const data = (await res.json()) as {
|
||||||
|
agents: Agent[];
|
||||||
|
total?: number;
|
||||||
|
page?: number;
|
||||||
|
page_size?: number;
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
agents: data.agents,
|
||||||
|
total: data.total ?? data.agents.length,
|
||||||
|
page: data.page ?? params.page ?? 1,
|
||||||
|
pageSize: data.page_size ?? params.pageSize ?? data.agents.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function setAgentPrivate(
|
export async function setAgentPrivate(
|
||||||
id: string,
|
id: string,
|
||||||
isPrivate: boolean,
|
isPrivate: boolean,
|
||||||
|
|||||||
@@ -3,25 +3,55 @@ import {
|
|||||||
useMutation,
|
useMutation,
|
||||||
useQuery,
|
useQuery,
|
||||||
useQueryClient,
|
useQueryClient,
|
||||||
} from "@tanstack/react-query";
|
} from "@tanstack/react-query";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
adminSyncAgentSkills,
|
adminSyncAgentSkills,
|
||||||
createAgent,
|
createAgent,
|
||||||
deleteAgent,
|
deleteAgent,
|
||||||
favoriteAgent,
|
favoriteAgent,
|
||||||
getAgent,
|
getAgent,
|
||||||
getAgentSelector,
|
getAgentSelector,
|
||||||
listAgents,
|
listAgents,
|
||||||
listAllAgentsAdmin,
|
listAgentsPaginated,
|
||||||
listPrivateAgents,
|
listAllAgentsAdmin,
|
||||||
reorderFeaturedAgents,
|
listPrivateAgents,
|
||||||
setAgentFeatured,
|
listPrivateAgentsPaginated,
|
||||||
setAgentPrivate,
|
pinAgent,
|
||||||
unfavoriteAgent,
|
reorderFeaturedAgents,
|
||||||
updateAgent,
|
setAgentFeatured,
|
||||||
} from "./api";
|
setAgentPrivate,
|
||||||
import type { Agent, CreateAgentRequest, UpdateAgentRequest } from "./types";
|
unfavoriteAgent,
|
||||||
|
unpinAgent,
|
||||||
|
updateAgent,
|
||||||
|
} from "./api";
|
||||||
|
import type {
|
||||||
|
Agent,
|
||||||
|
AgentSort,
|
||||||
|
CreateAgentRequest,
|
||||||
|
PaginatedAgents,
|
||||||
|
UpdateAgentRequest,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
|
/** A cached agent listing is either a plain ``Agent[]`` (legacy ``useAgents``)
|
||||||
|
* or the paginated ``{ agents, total, ... }`` envelope. Mutators patch both. */
|
||||||
|
type CachedAgents = Agent[] | PaginatedAgents | undefined;
|
||||||
|
|
||||||
|
function isPaginated(value: CachedAgents): value is PaginatedAgents {
|
||||||
|
return !!value && !Array.isArray(value) && Array.isArray(value.agents);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Apply ``map`` to every agent inside whatever listing shape is cached. */
|
||||||
|
function mapCachedAgents(
|
||||||
|
queryClient: ReturnType<typeof useQueryClient>,
|
||||||
|
map: (a: Agent) => Agent,
|
||||||
|
) {
|
||||||
|
queryClient.setQueriesData<CachedAgents>({ queryKey: ["agents"] }, (old) => {
|
||||||
|
if (Array.isArray(old)) return old.map(map);
|
||||||
|
if (isPaginated(old)) return { ...old, agents: old.agents.map(map) };
|
||||||
|
return old;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** Patch an updated agent into every cached agent listing immediately so
|
/** Patch an updated agent into every cached agent listing immediately so
|
||||||
* cards re-render before the background refetch finishes. Without this the
|
* cards re-render before the background refetch finishes. Without this the
|
||||||
@@ -32,13 +62,7 @@ function applyAgentToCache(
|
|||||||
queryClient: ReturnType<typeof useQueryClient>,
|
queryClient: ReturnType<typeof useQueryClient>,
|
||||||
next: Agent,
|
next: Agent,
|
||||||
) {
|
) {
|
||||||
queryClient.setQueriesData<Agent[] | undefined>(
|
mapCachedAgents(queryClient, (a) => (a.id === next.id ? { ...a, ...next } : a));
|
||||||
{ queryKey: ["agents"] },
|
|
||||||
(old) => {
|
|
||||||
if (!Array.isArray(old)) return old;
|
|
||||||
return old.map((a) => (a.id === next.id ? { ...a, ...next } : a));
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAgents(params: { search?: string; tagIds?: string[] } = {}) {
|
export function useAgents(params: { search?: string; tagIds?: string[] } = {}) {
|
||||||
@@ -52,6 +76,45 @@ export function useAgents(params: { search?: string; tagIds?: string[] } = {}) {
|
|||||||
return { agents: data ?? [], isLoading, error };
|
return { agents: data ?? [], isLoading, error };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Server-side paginated agent listing for one gallery tab (scope). Returns
|
||||||
|
* the page of agents plus the total count for the "共 N 个" header. */
|
||||||
|
export function useAgentsPaginated(params: {
|
||||||
|
scope: "mine" | "square";
|
||||||
|
search?: string;
|
||||||
|
tagIds?: string[];
|
||||||
|
sort?: AgentSort;
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
enabled?: boolean;
|
||||||
|
}) {
|
||||||
|
const { scope, page, pageSize, enabled = true } = params;
|
||||||
|
const search = params.search ?? "";
|
||||||
|
const tagIds = params.tagIds ?? [];
|
||||||
|
const sort = params.sort ?? "time_desc";
|
||||||
|
const { data, isLoading, error } = useQuery({
|
||||||
|
queryKey: [
|
||||||
|
"agents",
|
||||||
|
"paginated",
|
||||||
|
scope,
|
||||||
|
search,
|
||||||
|
[...tagIds].sort(),
|
||||||
|
sort,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
],
|
||||||
|
queryFn: () =>
|
||||||
|
listAgentsPaginated({ scope, search, tagIds, sort, page, pageSize }),
|
||||||
|
enabled,
|
||||||
|
placeholderData: keepPreviousData,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
agents: data?.agents ?? [],
|
||||||
|
total: data?.total ?? 0,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Admin-only listing — returns every agent including unpublished agents owned
|
* Admin-only listing — returns every agent including unpublished agents owned
|
||||||
* by other users and private-square entries. Caller must be ``system_role
|
* by other users and private-square entries. Caller must be ``system_role
|
||||||
@@ -117,20 +180,14 @@ export function useDeleteAgent() {
|
|||||||
/** Toggle a user's favorite (收藏) on an agent, with an optimistic flip of
|
/** Toggle a user's favorite (收藏) on an agent, with an optimistic flip of
|
||||||
* ``is_favorite`` across every cached agent listing + detail so the star
|
* ``is_favorite`` across every cached agent listing + detail so the star
|
||||||
* reacts instantly before the round-trip completes. */
|
* reacts instantly before the round-trip completes. */
|
||||||
export function useToggleAgentFavorite() {
|
export function useToggleAgentFavorite() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({ id, favorite }: { id: string; favorite: boolean }) =>
|
mutationFn: ({ id, favorite }: { id: string; favorite: boolean }) =>
|
||||||
favorite ? favoriteAgent(id) : unfavoriteAgent(id),
|
favorite ? favoriteAgent(id) : unfavoriteAgent(id),
|
||||||
onMutate: ({ id, favorite }) => {
|
onMutate: ({ id, favorite }) => {
|
||||||
queryClient.setQueriesData<Agent[] | undefined>(
|
mapCachedAgents(queryClient, (a) =>
|
||||||
{ queryKey: ["agents"] },
|
a.id === id ? { ...a, is_favorite: favorite } : a,
|
||||||
(old) =>
|
|
||||||
Array.isArray(old)
|
|
||||||
? old.map((a) =>
|
|
||||||
a.id === id ? { ...a, is_favorite: favorite } : a,
|
|
||||||
)
|
|
||||||
: old,
|
|
||||||
);
|
);
|
||||||
queryClient.setQueryData<Agent | undefined>(["agents", id], (old) =>
|
queryClient.setQueryData<Agent | undefined>(["agents", id], (old) =>
|
||||||
old ? { ...old, is_favorite: favorite } : old,
|
old ? { ...old, is_favorite: favorite } : old,
|
||||||
@@ -139,10 +196,30 @@ export function useToggleAgentFavorite() {
|
|||||||
onSettled: () => {
|
onSettled: () => {
|
||||||
void queryClient.invalidateQueries({ queryKey: ["agents"] });
|
void queryClient.invalidateQueries({ queryKey: ["agents"] });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAgentSelector() {
|
export function useToggleAgentPin() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ id, pinned }: { id: string; pinned: boolean }) =>
|
||||||
|
pinned ? pinAgent(id) : unpinAgent(id),
|
||||||
|
onMutate: ({ id, pinned }) => {
|
||||||
|
mapCachedAgents(queryClient, (a) =>
|
||||||
|
a.id === id ? { ...a, is_pinned: pinned } : a,
|
||||||
|
);
|
||||||
|
queryClient.setQueryData<Agent | undefined>(["agents", id], (old) =>
|
||||||
|
old ? { ...old, is_pinned: pinned } : old,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
onSuccess: async () => {
|
||||||
|
await queryClient.invalidateQueries({ queryKey: ["agents"] });
|
||||||
|
await queryClient.refetchQueries({ queryKey: ["agents"], type: "active" });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAgentSelector() {
|
||||||
const { data, isLoading, error } = useQuery({
|
const { data, isLoading, error } = useQuery({
|
||||||
queryKey: ["agents", "selector"],
|
queryKey: ["agents", "selector"],
|
||||||
queryFn: () => getAgentSelector(),
|
queryFn: () => getAgentSelector(),
|
||||||
@@ -153,9 +230,9 @@ export function useAgentSelector() {
|
|||||||
isLoading,
|
isLoading,
|
||||||
error,
|
error,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function invalidateAgentQueries(queryClient: ReturnType<typeof useQueryClient>) {
|
function invalidateAgentQueries(queryClient: ReturnType<typeof useQueryClient>) {
|
||||||
void queryClient.invalidateQueries({ queryKey: ["agents"] });
|
void queryClient.invalidateQueries({ queryKey: ["agents"] });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,6 +273,58 @@ export function usePrivateAgents(password: string | null) {
|
|||||||
return { agents: data ?? [], isLoading, error, refetch };
|
return { agents: data ?? [], isLoading, error, refetch };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Paginated variant of {@link usePrivateAgents} — one page of the
|
||||||
|
* password-gated private square plus the total count. */
|
||||||
|
export function usePrivateAgentsPaginated(
|
||||||
|
password: string | null,
|
||||||
|
params: {
|
||||||
|
search?: string;
|
||||||
|
tagIds?: string[];
|
||||||
|
sort?: AgentSort;
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
enabled?: boolean;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const { page, pageSize, enabled = true } = params;
|
||||||
|
const search = params.search ?? "";
|
||||||
|
const tagIds = params.tagIds ?? [];
|
||||||
|
const sort = params.sort ?? "time_desc";
|
||||||
|
const { data, isLoading, error, refetch } = useQuery({
|
||||||
|
queryKey: [
|
||||||
|
"agents",
|
||||||
|
"private-square",
|
||||||
|
password ?? "",
|
||||||
|
"paginated",
|
||||||
|
search,
|
||||||
|
[...tagIds].sort(),
|
||||||
|
sort,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
],
|
||||||
|
queryFn: () =>
|
||||||
|
listPrivateAgentsPaginated({
|
||||||
|
password: password!,
|
||||||
|
search,
|
||||||
|
tagIds,
|
||||||
|
sort,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
}),
|
||||||
|
enabled: !!password && enabled,
|
||||||
|
staleTime: 30_000,
|
||||||
|
retry: false,
|
||||||
|
placeholderData: keepPreviousData,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
agents: data?.agents ?? [],
|
||||||
|
total: data?.total ?? 0,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
refetch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function useSetAgentPrivate() {
|
export function useSetAgentPrivate() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { Tag } from "@/core/tags";
|
import type { Tag } from "@/core/tags";
|
||||||
|
|
||||||
export interface Agent {
|
export interface Agent {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
description: string;
|
description: string;
|
||||||
@@ -17,11 +17,22 @@ export interface Agent {
|
|||||||
tags?: Tag[];
|
tags?: Tag[];
|
||||||
featured_order?: number | null;
|
featured_order?: number | null;
|
||||||
/** Whether the current user has favorited (收藏) this agent. */
|
/** Whether the current user has favorited (收藏) this agent. */
|
||||||
is_favorite?: boolean;
|
is_favorite?: boolean;
|
||||||
}
|
is_pinned?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AgentSort = "time_desc" | "time_asc" | "updated_desc" | "updated_asc" | "name_asc" | "name_desc";
|
||||||
|
|
||||||
|
export interface AgentSelectorResponse {
|
||||||
|
agents: Agent[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface AgentSelectorResponse {
|
/** Pagination envelope returned by the server-side paginated agent listings. */
|
||||||
|
export interface PaginatedAgents {
|
||||||
agents: Agent[];
|
agents: Agent[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateAgentRequest {
|
export interface CreateAgentRequest {
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import { getAuthorizationHeaderValue } from "@/core/auth";
|
import {
|
||||||
|
clearStoredAuth,
|
||||||
|
getAuthorizationHeaderValue,
|
||||||
|
getStoredAuth,
|
||||||
|
} from "@/core/auth";
|
||||||
import { withCsrfHeaders } from "./csrf";
|
import { withCsrfHeaders } from "./csrf";
|
||||||
|
|
||||||
function withAuthHeaders(headers?: HeadersInit): Headers {
|
function withAuthHeaders(headers?: HeadersInit): Headers {
|
||||||
@@ -8,13 +12,40 @@ function withAuthHeaders(headers?: HeadersInit): Headers {
|
|||||||
next.set("Authorization", authHeader);
|
next.set("Authorization", authHeader);
|
||||||
}
|
}
|
||||||
return next;
|
return next;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
|
function requestUrl(input: RequestInfo | URL): string {
|
||||||
return fetch(input, {
|
if (typeof input === "string") return input;
|
||||||
|
if (input instanceof URL) return input.href;
|
||||||
|
return (input as Request).url ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
|
||||||
|
const response = await fetch(input, {
|
||||||
...init,
|
...init,
|
||||||
credentials: init?.credentials ?? "include",
|
credentials: init?.credentials ?? "include",
|
||||||
headers: withAuthHeaders(init?.headers),
|
headers: withAuthHeaders(init?.headers),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Session is considered lost ONLY when the backend actually answers 401.
|
||||||
|
// (Previously a stray localStorage change could log the user out client-side
|
||||||
|
// even though the session was still valid.) Auth endpoints are excluded so a
|
||||||
|
// failed/transient login attempt never wipes state, and we only act when we
|
||||||
|
// believed we were logged in — avoiding redirect loops on the login page.
|
||||||
|
if (response.status === 401) {
|
||||||
|
const url = requestUrl(input);
|
||||||
|
const isAuthEndpoint = url.includes("/api/v1/auth/");
|
||||||
|
if (!isAuthEndpoint && getStoredAuth()) {
|
||||||
|
clearStoredAuth();
|
||||||
|
if (
|
||||||
|
typeof window !== "undefined" &&
|
||||||
|
!window.location.hash.startsWith("#/login")
|
||||||
|
) {
|
||||||
|
window.location.replace("#/login");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -9,6 +9,8 @@ export interface UserListItem {
|
|||||||
system_role: "admin" | "user";
|
system_role: "admin" | "user";
|
||||||
skill_count: number;
|
skill_count: number;
|
||||||
agent_count: number;
|
agent_count: number;
|
||||||
|
/** 问答次数:用户提问的次数(一次提问算一次)。 */
|
||||||
|
qa_count: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function listAllUsers(): Promise<UserListItem[]> {
|
export async function listAllUsers(): Promise<UserListItem[]> {
|
||||||
|
|||||||
@@ -6,13 +6,7 @@ import { toast } from "sonner";
|
|||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
|
|
||||||
const AUTH_STORAGE_KEY = "deerflow.auth";
|
const AUTH_STORAGE_KEY = "deerflow.auth";
|
||||||
|
|
||||||
// 防抖窗口:跨标签页登录/重写 auth 常常在极短时间内连发多个 storage 事件
|
|
||||||
// (例如先写 token、再写用户信息)。等它"落定"再判断,避免抖动期的中间态
|
|
||||||
// (短暂 null / 半写状态)误触发动作。
|
|
||||||
const SETTLE_DELAY_MS = 1200;
|
const SETTLE_DELAY_MS = 1200;
|
||||||
|
|
||||||
// 提示 toast 的稳定 id —— 同一次身份变化只保留一条,避免连发事件刷屏。
|
|
||||||
const IDENTITY_TOAST_ID = "auth-identity-changed";
|
const IDENTITY_TOAST_ID = "auth-identity-changed";
|
||||||
|
|
||||||
function readUserId(): string | null {
|
function readUserId(): string | null {
|
||||||
@@ -20,23 +14,8 @@ function readUserId(): string | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mount once at the app root. Watches `localStorage["deerflow.auth"]` for
|
* Mount once at the app root. Watches localStorage auth changes from other
|
||||||
* cross-tab changes.
|
* tabs and lets the user decide when to refresh on account switches.
|
||||||
*
|
|
||||||
* 背景:`deerflow.auth` 在同源所有标签页之间共享。某个标签页登录/重写它时,
|
|
||||||
* 其它标签页仍持有旧用户的内存态(会话列表、thread id、以及多智能体会商这类
|
|
||||||
* 纯内存的页面状态),与新 token 不一致,可能在"新对话"等操作上 404。
|
|
||||||
*
|
|
||||||
* 旧实现:只要检测到 user_id 变化就 `window.location.reload()`。这会把**正在
|
|
||||||
* 使用的标签页**(例如正在跑多智能体会商第二步的那个)整页刷新,内存态全丢、
|
|
||||||
* 步骤回到第一步 —— 用户复制链接到新标签页打开(新标签页可能以不同/默认用户
|
|
||||||
* 重新登录并改写共享 auth)就会触发,体验很差。
|
|
||||||
*
|
|
||||||
* 现实现(方案 1,收敛粗暴刷新):
|
|
||||||
* - **真·退出登录**(auth 变为 null)→ 仍然跳登录页并刷新(本就该重新登录)。
|
|
||||||
* - **出现不同的非空用户**(另一个标签页登录成别的身份)→ **不再自动整页刷新**,
|
|
||||||
* 改为弹一条常驻提示,把"是否刷新同步"的决定权交给用户,避免冲掉正在进行的工作。
|
|
||||||
* - 防抖 + 落定后二次校验,过滤掉同用户重写 / 抖动中间态带来的误触发。
|
|
||||||
*/
|
*/
|
||||||
export function AuthSyncWatcher() {
|
export function AuthSyncWatcher() {
|
||||||
const lastUserIdRef = useRef<string | null>(readUserId());
|
const lastUserIdRef = useRef<string | null>(readUserId());
|
||||||
@@ -44,26 +23,18 @@ export function AuthSyncWatcher() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let settleTimer: ReturnType<typeof setTimeout> | null = null;
|
let settleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
// storage 事件落定后再判断当前的真实身份并决定动作。
|
|
||||||
function evaluateSettledIdentity() {
|
function evaluateSettledIdentity() {
|
||||||
const nextUserId = readUserId();
|
const nextUserId = readUserId();
|
||||||
if (nextUserId === lastUserIdRef.current) {
|
if (nextUserId === lastUserIdRef.current) {
|
||||||
// 同用户重写,或抖动后又回到原身份 —— 无需任何动作。
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lastUserIdRef.current = nextUserId;
|
||||||
|
|
||||||
if (nextUserId === null) {
|
if (nextUserId === null) {
|
||||||
// 另一个标签页退出登录(或清空了 auth)→ 本标签页也该回到登录页。
|
|
||||||
lastUserIdRef.current = null;
|
|
||||||
window.location.replace("#/login");
|
|
||||||
window.location.reload();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 出现了不同的非空用户。共享 auth 已被改成别的身份,继续在本标签页发请求
|
|
||||||
// 可能 404 / 鉴权失败,但**不**强制刷新 —— 用户可能正在本标签页干活
|
|
||||||
// (如多智能体会商),由用户自己决定何时刷新同步。
|
|
||||||
lastUserIdRef.current = nextUserId;
|
|
||||||
toast.warning("检测到账号在其它标签页发生变化", {
|
toast.warning("检测到账号在其它标签页发生变化", {
|
||||||
id: IDENTITY_TOAST_ID,
|
id: IDENTITY_TOAST_ID,
|
||||||
description: "当前标签页仍是原会话。如需与新账号同步,请刷新页面。",
|
description: "当前标签页仍是原会话。如需与新账号同步,请刷新页面。",
|
||||||
@@ -76,8 +47,9 @@ export function AuthSyncWatcher() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleStorage(event: StorageEvent) {
|
function handleStorage(event: StorageEvent) {
|
||||||
// 只关心 auth 键的变化;event.key === null 表示 localStorage 被整体清空。
|
// Ignore unrelated keys and localStorage.clear(). Backend session loss is
|
||||||
if (event.key !== null && event.key !== AUTH_STORAGE_KEY) {
|
// handled centrally through 401 responses.
|
||||||
|
if (event.key !== AUTH_STORAGE_KEY) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (settleTimer) {
|
if (settleTimer) {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ const CONSUMER_URL = import.meta.env.VITE_AIPI_CONSUMER_URL || "";
|
|||||||
export const TOOLS_TOKEN_STORAGE_KEY = "tools_token";
|
export const TOOLS_TOKEN_STORAGE_KEY = "tools_token";
|
||||||
export const EXTERNAL_USER_ID_STORAGE_KEY = "userId";
|
export const EXTERNAL_USER_ID_STORAGE_KEY = "userId";
|
||||||
export const EXTERNAL_USER_INFO_STORAGE_KEY = "userInfo";
|
export const EXTERNAL_USER_INFO_STORAGE_KEY = "userInfo";
|
||||||
export const GENERAL_QA_ROUTE = "/page/strategy/qa/general";
|
export const GENERAL_QA_ROUTE = "/page/workspace/chats/new";
|
||||||
|
|
||||||
type UserDetailResponse = {
|
type UserDetailResponse = {
|
||||||
data?: {
|
data?: {
|
||||||
|
|||||||
@@ -9,6 +9,12 @@ export interface CustomPrompt {
|
|||||||
title: string;
|
title: string;
|
||||||
content: string;
|
content: string;
|
||||||
sort_order?: number;
|
sort_order?: number;
|
||||||
|
/**
|
||||||
|
* Optional association to a single agent. ``null``/absent = global (shown for
|
||||||
|
* every agent); otherwise the prompt only surfaces when that agent is
|
||||||
|
* selected.
|
||||||
|
*/
|
||||||
|
agent_id?: string | null;
|
||||||
created_at?: string | null;
|
created_at?: string | null;
|
||||||
updated_at?: string | null;
|
updated_at?: string | null;
|
||||||
}
|
}
|
||||||
@@ -27,6 +33,7 @@ async function listUserPrompts(): Promise<CustomPrompt[]> {
|
|||||||
async function createUserPrompt(input: {
|
async function createUserPrompt(input: {
|
||||||
title: string;
|
title: string;
|
||||||
content: string;
|
content: string;
|
||||||
|
agent_id?: string | null;
|
||||||
}): Promise<CustomPrompt> {
|
}): Promise<CustomPrompt> {
|
||||||
const res = await apiFetch(baseUrl(), {
|
const res = await apiFetch(baseUrl(), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -42,7 +49,7 @@ async function createUserPrompt(input: {
|
|||||||
|
|
||||||
async function updateUserPrompt(
|
async function updateUserPrompt(
|
||||||
id: string,
|
id: string,
|
||||||
input: { title?: string; content?: string },
|
input: { title?: string; content?: string; agent_id?: string | null },
|
||||||
): Promise<CustomPrompt> {
|
): Promise<CustomPrompt> {
|
||||||
const res = await apiFetch(`${baseUrl()}/${encodeURIComponent(id)}`, {
|
const res = await apiFetch(`${baseUrl()}/${encodeURIComponent(id)}`, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
@@ -93,7 +100,7 @@ export function useUpdateCustomPrompt() {
|
|||||||
input,
|
input,
|
||||||
}: {
|
}: {
|
||||||
id: string;
|
id: string;
|
||||||
input: { title?: string; content?: string };
|
input: { title?: string; content?: string; agent_id?: string | null };
|
||||||
}) => updateUserPrompt(id, input),
|
}) => updateUserPrompt(id, input),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
void queryClient.invalidateQueries({ queryKey: QUERY_KEY });
|
void queryClient.invalidateQueries({ queryKey: QUERY_KEY });
|
||||||
|
|||||||
@@ -82,6 +82,10 @@ export const enUS: Translations = {
|
|||||||
inputBox: {
|
inputBox: {
|
||||||
placeholder: "How can I assist you today?",
|
placeholder: "How can I assist you today?",
|
||||||
editQuestion: "Edit question",
|
editQuestion: "Edit question",
|
||||||
|
deleteMessage: "Delete question and answer",
|
||||||
|
deleteMessageConfirmTitle: "Delete this question and its answer?",
|
||||||
|
deleteMessageConfirmDescription:
|
||||||
|
"The question and its answer will both be removed. This cannot be undone.",
|
||||||
createSkillPrompt:
|
createSkillPrompt:
|
||||||
"We're going to build a new skill step by step with `skill-creator`. To start, what do you want this skill to do?",
|
"We're going to build a new skill step by step with `skill-creator`. To start, what do you want this skill to do?",
|
||||||
addAttachments: "Add attachments",
|
addAttachments: "Add attachments",
|
||||||
@@ -472,6 +476,8 @@ export const enUS: Translations = {
|
|||||||
badgeArchivedTitle: "Archived — recoverable from the archive drawer",
|
badgeArchivedTitle: "Archived — recoverable from the archive drawer",
|
||||||
badgePinned: "Pinned",
|
badgePinned: "Pinned",
|
||||||
badgePinnedTitle: "Pinned — the curator will never auto-archive this skill",
|
badgePinnedTitle: "Pinned — the curator will never auto-archive this skill",
|
||||||
|
badgeFeatured: "Top",
|
||||||
|
badgeFeaturedTitle: "Pinned to the top of the list",
|
||||||
badgeSourceAgent: "Agent-created",
|
badgeSourceAgent: "Agent-created",
|
||||||
badgeSourceAgentTitle: "Auto-generated by an agent during a conversation",
|
badgeSourceAgentTitle: "Auto-generated by an agent during a conversation",
|
||||||
badgeSourceUpload: "Uploaded",
|
badgeSourceUpload: "Uploaded",
|
||||||
@@ -490,6 +496,10 @@ export const enUS: Translations = {
|
|||||||
unpinAction: "Unpin",
|
unpinAction: "Unpin",
|
||||||
pinSuccess: "Pinned",
|
pinSuccess: "Pinned",
|
||||||
unpinSuccess: "Unpinned",
|
unpinSuccess: "Unpinned",
|
||||||
|
featureAction: "Pin to top",
|
||||||
|
unfeatureAction: "Unpin from top",
|
||||||
|
featureSuccess: "Pinned to top",
|
||||||
|
unfeatureSuccess: "Unpinned from top",
|
||||||
deleteAction: "Delete skill",
|
deleteAction: "Delete skill",
|
||||||
deleteConfirm:
|
deleteConfirm:
|
||||||
"Delete skill \"{name}\"? This cannot be undone and the skill will be removed from any agent that referenced it.",
|
"Delete skill \"{name}\"? This cannot be undone and the skill will be removed from any agent that referenced it.",
|
||||||
|
|||||||
@@ -79,6 +79,9 @@ export interface Translations {
|
|||||||
inputBox: {
|
inputBox: {
|
||||||
placeholder: string;
|
placeholder: string;
|
||||||
editQuestion: string;
|
editQuestion: string;
|
||||||
|
deleteMessage: string;
|
||||||
|
deleteMessageConfirmTitle: string;
|
||||||
|
deleteMessageConfirmDescription: string;
|
||||||
createSkillPrompt: string;
|
createSkillPrompt: string;
|
||||||
addAttachments: string;
|
addAttachments: string;
|
||||||
mode: string;
|
mode: string;
|
||||||
@@ -406,6 +409,8 @@ export interface Translations {
|
|||||||
badgeArchivedTitle: string;
|
badgeArchivedTitle: string;
|
||||||
badgePinned: string;
|
badgePinned: string;
|
||||||
badgePinnedTitle: string;
|
badgePinnedTitle: string;
|
||||||
|
badgeFeatured: string;
|
||||||
|
badgeFeaturedTitle: string;
|
||||||
badgeSourceAgent: string;
|
badgeSourceAgent: string;
|
||||||
badgeSourceAgentTitle: string;
|
badgeSourceAgentTitle: string;
|
||||||
badgeSourceUpload: string;
|
badgeSourceUpload: string;
|
||||||
@@ -424,6 +429,10 @@ export interface Translations {
|
|||||||
unpinAction: string;
|
unpinAction: string;
|
||||||
pinSuccess: string;
|
pinSuccess: string;
|
||||||
unpinSuccess: string;
|
unpinSuccess: string;
|
||||||
|
featureAction: string;
|
||||||
|
unfeatureAction: string;
|
||||||
|
featureSuccess: string;
|
||||||
|
unfeatureSuccess: string;
|
||||||
deleteAction: string;
|
deleteAction: string;
|
||||||
deleteConfirm: string;
|
deleteConfirm: string;
|
||||||
deleteSuccess: string;
|
deleteSuccess: string;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {
|
import {
|
||||||
CompassIcon,
|
CompassIcon,
|
||||||
GraduationCapIcon,
|
GraduationCapIcon,
|
||||||
ImageIcon,
|
ImageIcon,
|
||||||
@@ -82,6 +82,9 @@ export const zhCN: Translations = {
|
|||||||
inputBox: {
|
inputBox: {
|
||||||
placeholder: "今天我能为你做些什么?",
|
placeholder: "今天我能为你做些什么?",
|
||||||
editQuestion: "编辑问题",
|
editQuestion: "编辑问题",
|
||||||
|
deleteMessage: "删除提问及回答",
|
||||||
|
deleteMessageConfirmTitle: "删除该提问及其回答?",
|
||||||
|
deleteMessageConfirmDescription: "该提问及对应的回答都会被删除,且无法恢复。",
|
||||||
createSkillPrompt:
|
createSkillPrompt:
|
||||||
"我们一起用 skill-creator 技能来创建一个技能吧。先问问我希望这个技能能做什么。",
|
"我们一起用 skill-creator 技能来创建一个技能吧。先问问我希望这个技能能做什么。",
|
||||||
addAttachments: "添加附件",
|
addAttachments: "添加附件",
|
||||||
@@ -453,6 +456,8 @@ export const zhCN: Translations = {
|
|||||||
badgeArchivedTitle: "已被归档,可在归档抽屉中恢复",
|
badgeArchivedTitle: "已被归档,可在归档抽屉中恢复",
|
||||||
badgePinned: "钉选",
|
badgePinned: "钉选",
|
||||||
badgePinnedTitle: "已钉选,策展程序不会自动归档此技能",
|
badgePinnedTitle: "已钉选,策展程序不会自动归档此技能",
|
||||||
|
badgeFeatured: "置顶",
|
||||||
|
badgeFeaturedTitle: "已置顶,固定显示在列表顶部",
|
||||||
badgeSourceAgent: "Agent 创建",
|
badgeSourceAgent: "Agent 创建",
|
||||||
badgeSourceAgentTitle: "在对话中由 Agent 自动生成",
|
badgeSourceAgentTitle: "在对话中由 Agent 自动生成",
|
||||||
badgeSourceUpload: "用户上传",
|
badgeSourceUpload: "用户上传",
|
||||||
@@ -471,6 +476,10 @@ export const zhCN: Translations = {
|
|||||||
unpinAction: "取消钉选",
|
unpinAction: "取消钉选",
|
||||||
pinSuccess: "已钉选",
|
pinSuccess: "已钉选",
|
||||||
unpinSuccess: "已取消钉选",
|
unpinSuccess: "已取消钉选",
|
||||||
|
featureAction: "置顶",
|
||||||
|
unfeatureAction: "取消置顶",
|
||||||
|
featureSuccess: "已置顶",
|
||||||
|
unfeatureSuccess: "已取消置顶",
|
||||||
deleteAction: "删除技能",
|
deleteAction: "删除技能",
|
||||||
deleteConfirm: "确认删除技能 “{name}”?该操作不可恢复,且会从引用它的所有智能体中自动移除。",
|
deleteConfirm: "确认删除技能 “{name}”?该操作不可恢复,且会从引用它的所有智能体中自动移除。",
|
||||||
deleteSuccess: "技能已删除",
|
deleteSuccess: "技能已删除",
|
||||||
|
|||||||
@@ -54,15 +54,13 @@ export const sidebarMenuItems: MenuItem[] = [
|
|||||||
icon: HelpCircle,
|
icon: HelpCircle,
|
||||||
children: [
|
children: [
|
||||||
{ id: "general-qa", label: "通用问答", icon: CircleHelp, path: "/page/workspace/chats/new" },
|
{ id: "general-qa", label: "通用问答", icon: CircleHelp, path: "/page/workspace/chats/new" },
|
||||||
{ id: "expert-qa", label: "专家问答", icon: Brain, path: "/page/strategy/qa/expert-qa" },
|
{
|
||||||
// 「圆桌规划」入口暂时隐藏 —— 功能仍在 /page/roundtable/planning,只是不在侧边栏出现。
|
id: "multi-agent-roundtable",
|
||||||
// 需要重新开放时取消注释即可。
|
label: "多智能体会商",
|
||||||
// {
|
icon: Users,
|
||||||
// id: "qa-roundtable",
|
path: "/page/strategy/qa/multi-agent-roundtable",
|
||||||
// label: "圆桌规划",
|
},
|
||||||
// icon: Bot,
|
// { id: "expert-qa", label: "专家问答", icon: Brain, path: "/page/strategy/qa/expert-qa" },
|
||||||
// path: "/page/roundtable/planning",
|
|
||||||
// },
|
|
||||||
{ id: "qa-zzjc", label: "zzjc支持", icon: Bot },
|
{ id: "qa-zzjc", label: "zzjc支持", icon: Bot },
|
||||||
{ id: "qa-zzxd", label: "zzXD应用", icon: Layout },
|
{ id: "qa-zzxd", label: "zzXD应用", icon: Layout },
|
||||||
{ id: "qa-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
|
{ id: "qa-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import { apiFetch } from "@/core/api";
|
||||||
|
import { getBackendBaseURL } from "@/core/config";
|
||||||
|
// Share codes share the same alphabet/shape as conversation shares, so reuse the
|
||||||
|
// extractor instead of duplicating the regex.
|
||||||
|
export { extractShareCode } from "@/core/thread-shares/api";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Roundtable-draft share modes:
|
||||||
|
* - `import` — recipient (a logged-in user) copies the 会商 draft into their own
|
||||||
|
* account and can keep working on the copy.
|
||||||
|
* - `view` — a public, read-only page anyone can open without logging in; it
|
||||||
|
* renders the draft's Step 3 result report (方案总览 HTML).
|
||||||
|
*/
|
||||||
|
export type DraftShareMode = "import" | "view";
|
||||||
|
|
||||||
|
export interface DraftShare {
|
||||||
|
share_code: string;
|
||||||
|
owner_user_id: string;
|
||||||
|
draft_id: string;
|
||||||
|
revoked: boolean;
|
||||||
|
mode: DraftShareMode;
|
||||||
|
created_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One sub-agent's final delivery from the Step 2 roundtable. */
|
||||||
|
export interface PublicDraftSeatDelivery {
|
||||||
|
sender: string;
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read-only roundtable-result snapshot returned by the public view-share endpoint. */
|
||||||
|
export interface PublicDraftShareSnapshot {
|
||||||
|
share_code: string;
|
||||||
|
title: string;
|
||||||
|
mode: string;
|
||||||
|
/** 总控最终结论 (markdown). */
|
||||||
|
consensus_text: string;
|
||||||
|
/** 各席位最终交付. */
|
||||||
|
seat_deliveries: PublicDraftSeatDelivery[];
|
||||||
|
/** Self-contained Step 3 result report HTML (empty when no report exists). */
|
||||||
|
html: string;
|
||||||
|
summary: string | null;
|
||||||
|
generated_at: string | null;
|
||||||
|
has_report: boolean;
|
||||||
|
created_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DraftSharePreview {
|
||||||
|
share_code: string;
|
||||||
|
shared_by: string;
|
||||||
|
title: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DraftImportResult {
|
||||||
|
imported: number;
|
||||||
|
skipped: number;
|
||||||
|
draft_id: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseUrl = () => `${getBackendBaseURL()}/api/roundtable-draft-shares`;
|
||||||
|
|
||||||
|
async function parseError(response: Response, fallback: string): Promise<Error> {
|
||||||
|
const data = (await response.json().catch(() => ({}))) as { detail?: unknown };
|
||||||
|
const detail = data.detail;
|
||||||
|
const message =
|
||||||
|
typeof detail === "string" && detail
|
||||||
|
? detail
|
||||||
|
: `${fallback} (HTTP ${response.status})`;
|
||||||
|
return new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Create (or reuse) a share code for one roundtable draft in the given mode. */
|
||||||
|
export async function createDraftShare(
|
||||||
|
draftId: string,
|
||||||
|
mode: DraftShareMode = "import",
|
||||||
|
): Promise<DraftShare> {
|
||||||
|
const response = await apiFetch(baseUrl(), {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ draft_id: draftId, mode }),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw await parseError(response, "创建分享失败");
|
||||||
|
return response.json() as Promise<DraftShare>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** List the current user's own roundtable-draft share links. */
|
||||||
|
export async function listDraftShares(): Promise<DraftShare[]> {
|
||||||
|
const response = await apiFetch(baseUrl());
|
||||||
|
if (!response.ok) throw await parseError(response, "加载分享列表失败");
|
||||||
|
const json = (await response.json()) as { shares: DraftShare[] };
|
||||||
|
return json.shares;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Revoke a share link so it can no longer be previewed, imported, or viewed. */
|
||||||
|
export async function revokeDraftShare(shareCode: string): Promise<void> {
|
||||||
|
const response = await apiFetch(`${baseUrl()}/${encodeURIComponent(shareCode)}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
if (!response.ok) throw await parseError(response, "撤销分享失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Preview a share link before importing it. */
|
||||||
|
export async function previewDraftShare(shareCode: string): Promise<DraftSharePreview> {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${baseUrl()}/${encodeURIComponent(shareCode)}/preview`,
|
||||||
|
);
|
||||||
|
if (!response.ok) throw await parseError(response, "无法读取该分享");
|
||||||
|
return response.json() as Promise<DraftSharePreview>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Import the roundtable draft behind a share link into the current account. */
|
||||||
|
export async function importDraftShare(shareCode: string): Promise<DraftImportResult> {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${baseUrl()}/${encodeURIComponent(shareCode)}/import`,
|
||||||
|
{ method: "POST" },
|
||||||
|
);
|
||||||
|
if (!response.ok) throw await parseError(response, "导入失败");
|
||||||
|
return response.json() as Promise<DraftImportResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch the public read-only snapshot of a `view`-mode roundtable share.
|
||||||
|
*
|
||||||
|
* Uses a plain `fetch` (no auth header) — the `/api/public/` endpoint is
|
||||||
|
* intentionally world-readable so anyone with the link can open it.
|
||||||
|
*/
|
||||||
|
export async function getPublicDraftShareSnapshot(
|
||||||
|
shareCode: string,
|
||||||
|
): Promise<PublicDraftShareSnapshot> {
|
||||||
|
const response = await fetch(
|
||||||
|
`${getBackendBaseURL()}/api/public/roundtable-shares/${encodeURIComponent(shareCode)}`,
|
||||||
|
);
|
||||||
|
if (!response.ok) throw await parseError(response, "无法打开该分享");
|
||||||
|
return response.json() as Promise<PublicDraftShareSnapshot>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build the shareable public URL for a `view`-mode roundtable share code. */
|
||||||
|
export function buildPublicDraftShareUrl(shareCode: string): string {
|
||||||
|
// The app uses HashRouter, so the public viewer lives at `#/roundtable-share/<code>`.
|
||||||
|
return `${window.location.origin}${window.location.pathname}#/roundtable-share/${shareCode}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createDraftShare,
|
||||||
|
importDraftShare,
|
||||||
|
listDraftShares,
|
||||||
|
previewDraftShare,
|
||||||
|
revokeDraftShare,
|
||||||
|
type DraftShareMode,
|
||||||
|
} from "./api";
|
||||||
|
|
||||||
|
export function useDraftShares(enabled = true) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["roundtable-draft-shares"],
|
||||||
|
queryFn: listDraftShares,
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCreateDraftShare() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({
|
||||||
|
draftId,
|
||||||
|
mode = "import",
|
||||||
|
}: {
|
||||||
|
draftId: string;
|
||||||
|
mode?: DraftShareMode;
|
||||||
|
}) => createDraftShare(draftId, mode),
|
||||||
|
onSuccess: () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["roundtable-draft-shares"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRevokeDraftShare() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (shareCode: string) => revokeDraftShare(shareCode),
|
||||||
|
onSuccess: () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["roundtable-draft-shares"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePreviewDraftShare() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (shareCode: string) => previewDraftShare(shareCode),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useImportDraftShare() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (shareCode: string) => importDraftShare(shareCode),
|
||||||
|
onSuccess: () => {
|
||||||
|
// Imported drafts show up in the user's roundtable history sidebar.
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["roundtable-drafts"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -26,6 +26,14 @@ export type HtmlPageConfig = {
|
|||||||
|
|
||||||
export type ScheduledTaskExecutionContext = {
|
export type ScheduledTaskExecutionContext = {
|
||||||
require_markdown?: boolean;
|
require_markdown?: boolean;
|
||||||
|
/**
|
||||||
|
* The unified "必须生成 HTML" switch. The task form no longer splits "普通任务 /
|
||||||
|
* HTML 页面" into separate kinds — instead ``require_html`` and
|
||||||
|
* ``require_markdown`` are two independent toggles that may both be on. Legacy
|
||||||
|
* tasks created under the old two-tab UI still carry ``task_kind`` and are
|
||||||
|
* treated as HTML tasks by the backend for backward compatibility.
|
||||||
|
*/
|
||||||
|
require_html?: boolean;
|
||||||
task_kind?: ScheduledTaskKind;
|
task_kind?: ScheduledTaskKind;
|
||||||
html_config?: HtmlPageConfig;
|
html_config?: HtmlPageConfig;
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
|
|||||||
@@ -55,6 +55,13 @@ export interface LocalSettings {
|
|||||||
* app sizes text/spacing in rem, the whole UI scales proportionally.
|
* app sizes text/spacing in rem, the whole UI scales proportionally.
|
||||||
*/
|
*/
|
||||||
fontScale: number;
|
fontScale: number;
|
||||||
|
/**
|
||||||
|
* Per-user override for the skill / agent list display mode (card vs list).
|
||||||
|
* `undefined` = follow the admin-configured system default. Set when the
|
||||||
|
* user flips the card/list toggle on the skills or agents page.
|
||||||
|
*/
|
||||||
|
skillViewMode?: "card" | "list";
|
||||||
|
agentViewMode?: "card" | "list";
|
||||||
};
|
};
|
||||||
context: Omit<
|
context: Omit<
|
||||||
AgentThreadContext,
|
AgentThreadContext,
|
||||||
|
|||||||
@@ -6,12 +6,14 @@ import type { Skill, SkillDisplayConfig, SkillState } from "./type";
|
|||||||
export interface ListSkillsParams {
|
export interface ListSkillsParams {
|
||||||
search?: string;
|
search?: string;
|
||||||
tagIds?: string[];
|
tagIds?: string[];
|
||||||
|
sort?: "time_desc" | "time_asc" | "activity_desc" | "activity_asc" | "usage_desc" | "usage_asc" | "name_asc" | "name_desc";
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadSkills(params: ListSkillsParams = {}) {
|
export async function loadSkills(params: ListSkillsParams = {}) {
|
||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
if (params.search) qs.set("search", params.search);
|
if (params.search) qs.set("search", params.search);
|
||||||
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
|
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
|
||||||
|
if (params.sort) qs.set("sort", params.sort);
|
||||||
const query = qs.toString();
|
const query = qs.toString();
|
||||||
const skills = await apiFetch(
|
const skills = await apiFetch(
|
||||||
`${getBackendBaseURL()}/api/skills${query ? `?${query}` : ""}`,
|
`${getBackendBaseURL()}/api/skills${query ? `?${query}` : ""}`,
|
||||||
@@ -296,6 +298,24 @@ export async function setSkillPinned(
|
|||||||
return response.json() as Promise<Skill>;
|
return response.json() as Promise<Skill>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function setSkillFeatured(
|
||||||
|
skillName: string,
|
||||||
|
featured: boolean,
|
||||||
|
): Promise<Skill> {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/skills/custom/${encodeURIComponent(skillName)}/featured`,
|
||||||
|
{
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ featured }),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw await parseDetailedError(response, "Failed to update skill featured state");
|
||||||
|
}
|
||||||
|
return response.json() as Promise<Skill>;
|
||||||
|
}
|
||||||
|
|
||||||
export interface SkillContentResponse {
|
export interface SkillContentResponse {
|
||||||
name: string;
|
name: string;
|
||||||
category: string;
|
category: string;
|
||||||
|
|||||||
@@ -19,23 +19,32 @@ import {
|
|||||||
setSkillDetail,
|
setSkillDetail,
|
||||||
setSkillDisplay,
|
setSkillDisplay,
|
||||||
setSkillPinned,
|
setSkillPinned,
|
||||||
|
setSkillFeatured,
|
||||||
setSkillPublished,
|
setSkillPublished,
|
||||||
setSkillState,
|
setSkillState,
|
||||||
validateSkillUpload,
|
validateSkillUpload,
|
||||||
} from "./api";
|
} from "./api";
|
||||||
|
import type { ListSkillsParams } from "./api";
|
||||||
import type { Skill, SkillState } from "./type";
|
import type { Skill, SkillState } from "./type";
|
||||||
|
|
||||||
import { loadAllSkillsAdmin, loadSkills } from ".";
|
import { loadAllSkillsAdmin, loadSkills } from ".";
|
||||||
|
|
||||||
export function useSkills(params: { search?: string; tagIds?: string[] } = {}) {
|
// Stable empty fallback. Returning `data ?? []` inline would hand out a fresh
|
||||||
|
// array reference on every render while the query is loading/errored, which
|
||||||
|
// makes downstream `useMemo([skills])` / `useEffect([skills])` consumers churn
|
||||||
|
// forever (observed as a "Maximum update depth exceeded" loop on NewAgentPage).
|
||||||
|
const EMPTY_SKILLS: Skill[] = [];
|
||||||
|
|
||||||
|
export function useSkills(params: ListSkillsParams = {}) {
|
||||||
const search = params.search ?? "";
|
const search = params.search ?? "";
|
||||||
const tagIds = params.tagIds ?? [];
|
const tagIds = params.tagIds ?? [];
|
||||||
|
const sort = params.sort ?? "time_desc";
|
||||||
const { data, isLoading, error } = useQuery({
|
const { data, isLoading, error } = useQuery({
|
||||||
queryKey: ["skills", search, [...tagIds].sort()],
|
queryKey: ["skills", search, [...tagIds].sort(), sort],
|
||||||
queryFn: () => loadSkills({ search, tagIds }),
|
queryFn: () => loadSkills({ search, tagIds, sort }),
|
||||||
placeholderData: keepPreviousData,
|
placeholderData: keepPreviousData,
|
||||||
});
|
});
|
||||||
return { skills: data ?? [], isLoading, error };
|
return { skills: data ?? EMPTY_SKILLS, isLoading, error };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -50,7 +59,7 @@ export function useAllSkillsAdmin(enabled: boolean) {
|
|||||||
enabled,
|
enabled,
|
||||||
staleTime: 30_000,
|
staleTime: 30_000,
|
||||||
});
|
});
|
||||||
return { skills: data ?? [], isLoading, error };
|
return { skills: data ?? EMPTY_SKILLS, isLoading, error };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useSkillContent(skillName: string | null) {
|
export function useSkillContent(skillName: string | null) {
|
||||||
@@ -193,6 +202,17 @@ export function useSetSkillPinned() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useSetSkillFeatured() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ skillName, featured }: { skillName: string; featured: boolean }) =>
|
||||||
|
setSkillFeatured(skillName, featured),
|
||||||
|
onSuccess: () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["skills"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function useDuplicateSkill() {
|
export function useDuplicateSkill() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
|
|||||||
@@ -60,9 +60,12 @@ export interface Skill {
|
|||||||
// so stale / archived skills appear in dedicated drawers instead.
|
// so stale / archived skills appear in dedicated drawers instead.
|
||||||
state?: SkillState;
|
state?: SkillState;
|
||||||
pinned?: boolean;
|
pinned?: boolean;
|
||||||
|
// 置顶 —— 仅影响列表排序,与 pinned(防自动归档)正交。
|
||||||
|
featured?: boolean;
|
||||||
// Provenance — distinguishes skills created by an agent during a chat
|
// Provenance — distinguishes skills created by an agent during a chat
|
||||||
// (``agent``) from skills the user uploaded / authored manually (``upload``).
|
// (``agent``) from skills the user uploaded / authored manually (``upload``).
|
||||||
source?: SkillSource;
|
source?: SkillSource;
|
||||||
|
created_at?: string | null;
|
||||||
last_activity_at?: string | null;
|
last_activity_at?: string | null;
|
||||||
use_count?: number;
|
use_count?: number;
|
||||||
view_count?: number;
|
view_count?: number;
|
||||||
|
|||||||
@@ -61,6 +61,22 @@ export interface CitationDisplayUpdate {
|
|||||||
cleanup_words?: string[];
|
cleanup_words?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface LeaderboardSettings {
|
||||||
|
exclude_user_ids: string[];
|
||||||
|
include_scheduled: boolean;
|
||||||
|
include_admins: boolean;
|
||||||
|
include_failed: boolean;
|
||||||
|
cleanup_system_questions: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LeaderboardSettingsUpdate {
|
||||||
|
exclude_user_ids?: string[];
|
||||||
|
include_scheduled?: boolean;
|
||||||
|
include_admins?: boolean;
|
||||||
|
include_failed?: boolean;
|
||||||
|
cleanup_system_questions?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export async function loadPrivateSquareStatus(): Promise<PrivateSquareStatus> {
|
export async function loadPrivateSquareStatus(): Promise<PrivateSquareStatus> {
|
||||||
const response = await apiFetch(
|
const response = await apiFetch(
|
||||||
`${getBackendBaseURL()}/api/system-settings/private-square`,
|
`${getBackendBaseURL()}/api/system-settings/private-square`,
|
||||||
@@ -74,13 +90,18 @@ export async function loadPrivateSquareStatus(): Promise<PrivateSquareStatus> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type ThemeMode = "light" | "dark";
|
export type ThemeMode = "light" | "dark";
|
||||||
|
export type ViewMode = "card" | "list";
|
||||||
|
|
||||||
export interface AppearanceSettings {
|
export interface AppearanceSettings {
|
||||||
default_theme: ThemeMode;
|
default_theme: ThemeMode;
|
||||||
|
default_skill_view: ViewMode;
|
||||||
|
default_agent_view: ViewMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AppearanceUpdate {
|
export interface AppearanceUpdate {
|
||||||
default_theme?: ThemeMode;
|
default_theme?: ThemeMode;
|
||||||
|
default_skill_view?: ViewMode;
|
||||||
|
default_agent_view?: ViewMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadAppearanceSettings(): Promise<AppearanceSettings> {
|
export async function loadAppearanceSettings(): Promise<AppearanceSettings> {
|
||||||
@@ -127,6 +148,36 @@ export async function loadCitationDisplaySettings(): Promise<CitationDisplaySett
|
|||||||
return (await response.json()) as CitationDisplaySettings;
|
return (await response.json()) as CitationDisplaySettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function loadLeaderboardSettings(): Promise<LeaderboardSettings> {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/system-settings/leaderboard`,
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to load leaderboard settings: ${response.status}`);
|
||||||
|
}
|
||||||
|
return (await response.json()) as LeaderboardSettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateLeaderboardSettings(
|
||||||
|
body: LeaderboardSettingsUpdate,
|
||||||
|
): Promise<LeaderboardSettings> {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/system-settings/leaderboard`,
|
||||||
|
{
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
const detail = await response
|
||||||
|
.json()
|
||||||
|
.catch(() => ({ detail: "Failed to update leaderboard settings" }));
|
||||||
|
throw new Error(detail.detail ?? "Failed to update leaderboard settings");
|
||||||
|
}
|
||||||
|
return (await response.json()) as LeaderboardSettings;
|
||||||
|
}
|
||||||
|
|
||||||
export async function updateCitationDisplaySettings(
|
export async function updateCitationDisplaySettings(
|
||||||
body: CitationDisplayUpdate,
|
body: CitationDisplayUpdate,
|
||||||
): Promise<CitationDisplaySettings> {
|
): Promise<CitationDisplaySettings> {
|
||||||
@@ -147,6 +198,22 @@ export async function updateCitationDisplaySettings(
|
|||||||
return (await response.json()) as CitationDisplaySettings;
|
return (await response.json()) as CitationDisplaySettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface LogSystemSettings {
|
||||||
|
enabled: boolean;
|
||||||
|
url: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadLogSystemSettings(): Promise<LogSystemSettings> {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/system-settings/log-system`,
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to load log system settings: ${response.status}`);
|
||||||
|
}
|
||||||
|
return (await response.json()) as LogSystemSettings;
|
||||||
|
}
|
||||||
|
|
||||||
export async function updatePrivateSquareSettings(
|
export async function updatePrivateSquareSettings(
|
||||||
body: PrivateSquareUpdate,
|
body: PrivateSquareUpdate,
|
||||||
): Promise<PrivateSquareStatus> {
|
): Promise<PrivateSquareStatus> {
|
||||||
|
|||||||
@@ -1,24 +1,31 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
import { useLocalSettings } from "@/core/settings";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
loadAppearanceSettings,
|
loadAppearanceSettings,
|
||||||
loadCitationDisplaySettings,
|
loadCitationDisplaySettings,
|
||||||
|
loadLeaderboardSettings,
|
||||||
loadPrivateSquareStatus,
|
loadPrivateSquareStatus,
|
||||||
loadPromptPrefixSettings,
|
loadPromptPrefixSettings,
|
||||||
updateAppearanceSettings,
|
updateAppearanceSettings,
|
||||||
updateCitationDisplaySettings,
|
updateCitationDisplaySettings,
|
||||||
|
updateLeaderboardSettings,
|
||||||
updatePrivateSquareSettings,
|
updatePrivateSquareSettings,
|
||||||
updatePromptPrefixSettings,
|
updatePromptPrefixSettings,
|
||||||
type AppearanceUpdate,
|
type AppearanceUpdate,
|
||||||
type CitationDisplayUpdate,
|
type CitationDisplayUpdate,
|
||||||
|
type LeaderboardSettingsUpdate,
|
||||||
type PrivateSquareUpdate,
|
type PrivateSquareUpdate,
|
||||||
type PromptPrefixUpdate,
|
type PromptPrefixUpdate,
|
||||||
|
type ViewMode,
|
||||||
} from "./api";
|
} from "./api";
|
||||||
|
|
||||||
const PROMPT_PREFIX_KEY = ["systemSettings", "promptPrefix"] as const;
|
const PROMPT_PREFIX_KEY = ["systemSettings", "promptPrefix"] as const;
|
||||||
const PRIVATE_SQUARE_KEY = ["systemSettings", "privateSquare"] as const;
|
const PRIVATE_SQUARE_KEY = ["systemSettings", "privateSquare"] as const;
|
||||||
const APPEARANCE_KEY = ["systemSettings", "appearance"] as const;
|
const APPEARANCE_KEY = ["systemSettings", "appearance"] as const;
|
||||||
const CITATION_DISPLAY_KEY = ["systemSettings", "citationDisplay"] as const;
|
const CITATION_DISPLAY_KEY = ["systemSettings", "citationDisplay"] as const;
|
||||||
|
const LEADERBOARD_KEY = ["systemSettings", "leaderboard"] as const;
|
||||||
|
|
||||||
export function usePromptPrefixSettings() {
|
export function usePromptPrefixSettings() {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
@@ -82,6 +89,31 @@ export function useUpdateAppearanceSettings() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Effective card/list display mode for the skill or agent list. A user's own
|
||||||
|
* choice (persisted in local settings) wins; otherwise the admin-configured
|
||||||
|
* system default applies; otherwise a built-in fallback (skills → list,
|
||||||
|
* agents → card, matching the historical layout of each page). `setMode`
|
||||||
|
* persists the user's override locally.
|
||||||
|
*/
|
||||||
|
export function useViewMode(
|
||||||
|
kind: "skill" | "agent",
|
||||||
|
): [ViewMode, (mode: ViewMode) => void] {
|
||||||
|
const [settings, setSettings] = useLocalSettings();
|
||||||
|
const { data: appearance } = useAppearanceSettings();
|
||||||
|
const overrideKey = kind === "skill" ? "skillViewMode" : "agentViewMode";
|
||||||
|
const userOverride = settings.display[overrideKey];
|
||||||
|
const adminDefault =
|
||||||
|
kind === "skill"
|
||||||
|
? appearance?.default_skill_view
|
||||||
|
: appearance?.default_agent_view;
|
||||||
|
const fallback: ViewMode = kind === "skill" ? "list" : "card";
|
||||||
|
const mode: ViewMode = userOverride ?? adminDefault ?? fallback;
|
||||||
|
const setMode = (next: ViewMode) =>
|
||||||
|
setSettings("display", { [overrideKey]: next });
|
||||||
|
return [mode, setMode];
|
||||||
|
}
|
||||||
|
|
||||||
export function useCitationDisplaySettings() {
|
export function useCitationDisplaySettings() {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: CITATION_DISPLAY_KEY,
|
queryKey: CITATION_DISPLAY_KEY,
|
||||||
@@ -102,3 +134,25 @@ export function useUpdateCitationDisplaySettings() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useLeaderboardSettings() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: LEADERBOARD_KEY,
|
||||||
|
queryFn: () => loadLeaderboardSettings(),
|
||||||
|
staleTime: 60_000,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
retry: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdateLeaderboardSettings() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (body: LeaderboardSettingsUpdate) =>
|
||||||
|
updateLeaderboardSettings(body),
|
||||||
|
onSuccess: (data) => {
|
||||||
|
queryClient.setQueryData(LEADERBOARD_KEY, data);
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["admin-activity", "leaderboard"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -350,12 +350,12 @@ export function useThreadStream({
|
|||||||
// agent thread URL — otherwise fall back to the global new chat.
|
// agent thread URL — otherwise fall back to the global new chat.
|
||||||
const hash = typeof window !== "undefined" ? window.location.hash : "";
|
const hash = typeof window !== "undefined" ? window.location.hash : "";
|
||||||
const agentMatch = hash.match(/#\/page\/workspace\/agents\/([^/]+)\//);
|
const agentMatch = hash.match(/#\/page\/workspace\/agents\/([^/]+)\//);
|
||||||
const iframeMatch = hash.match(/#\/page\/workspace\/chats_iframe\//);
|
const iframeMatch = hash.match(/#\/page\/workspace\/chats_iframe\//);
|
||||||
const target = agentMatch
|
const target = agentMatch
|
||||||
? `/page/workspace/agents/${agentMatch[1]}/chats/new`
|
? `/page/workspace/agents/${agentMatch[1]}/chats/new`
|
||||||
: iframeMatch
|
: iframeMatch
|
||||||
? "/page/workspace/chats_iframe/new"
|
? "/page/workspace/chats_iframe/new"
|
||||||
: "/page/workspace/chats/new";
|
: "/page/workspace/chats/new";
|
||||||
// First navigate to a safe URL so the post-reload page lands on a
|
// First navigate to a safe URL so the post-reload page lands on a
|
||||||
// valid route. Then full-reload so TanStack Query cache, context
|
// valid route. Then full-reload so TanStack Query cache, context
|
||||||
// providers and any other state captured under the previous user's
|
// providers and any other state captured under the previous user's
|
||||||
@@ -810,6 +810,49 @@ export function useDeleteThread() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a conversation turn (a user question together with its answer) from a
|
||||||
|
* thread. Hits the Gateway endpoint that removes the question and every
|
||||||
|
* following message up to the next question from the latest checkpoint, and
|
||||||
|
* returns the ids that were actually removed. The live `useStream` cache is not
|
||||||
|
* auto-refreshed by this call — callers hide the returned ids locally (see
|
||||||
|
* `MessageList`) so the removal shows immediately; a reload then reads the
|
||||||
|
* persisted, already-trimmed state.
|
||||||
|
*/
|
||||||
|
export function useDeleteMessage() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async ({
|
||||||
|
threadId,
|
||||||
|
messageId,
|
||||||
|
}: {
|
||||||
|
threadId: string;
|
||||||
|
messageId: string;
|
||||||
|
}): Promise<string[]> => {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(
|
||||||
|
threadId,
|
||||||
|
)}/messages/${encodeURIComponent(messageId)}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response
|
||||||
|
.json()
|
||||||
|
.catch(() => ({ detail: "删除消息失败。" }));
|
||||||
|
throw new Error(error.detail ?? "删除消息失败。");
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = (await response.json().catch(() => ({}))) as {
|
||||||
|
deleted_ids?: string[];
|
||||||
|
};
|
||||||
|
// Fall back to the requested id so the caller can always hide something.
|
||||||
|
return body.deleted_ids?.length ? body.deleted_ids : [messageId];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function useRenameThread() {
|
export function useRenameThread() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const apiClient = getAPIClient();
|
const apiClient = getAPIClient();
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
import { apiFetch } from "@/core/api";
|
||||||
|
import { getBackendBaseURL } from "@/core/config";
|
||||||
|
|
||||||
|
/** Per-user UI preferences, bound to the account (stored server-side). */
|
||||||
|
export interface UserPreferences {
|
||||||
|
/**
|
||||||
|
* When true, the chat input hides the admin-configured prompt-prefix switch
|
||||||
|
* and never applies the prefix — the user uses only their own prompts.
|
||||||
|
*/
|
||||||
|
hide_admin_prompt_prefix: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const QUERY_KEY = ["user-preferences"] as const;
|
||||||
|
const DEFAULT_PREFS: UserPreferences = { hide_admin_prompt_prefix: false };
|
||||||
|
const baseUrl = () => `${getBackendBaseURL()}/api/user-preferences`;
|
||||||
|
|
||||||
|
async function getUserPreferences(): Promise<UserPreferences> {
|
||||||
|
const res = await apiFetch(baseUrl());
|
||||||
|
if (!res.ok) throw new Error(`Failed to load preferences: ${res.statusText}`);
|
||||||
|
const data = (await res.json()) as Partial<UserPreferences>;
|
||||||
|
return { hide_admin_prompt_prefix: !!data.hide_admin_prompt_prefix };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function updateUserPreferences(
|
||||||
|
input: Partial<UserPreferences>,
|
||||||
|
): Promise<UserPreferences> {
|
||||||
|
const res = await apiFetch(baseUrl(), {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||||
|
throw new Error(err.detail ?? `Failed to update preferences: ${res.statusText}`);
|
||||||
|
}
|
||||||
|
const data = (await res.json()) as Partial<UserPreferences>;
|
||||||
|
return { hide_admin_prompt_prefix: !!data.hide_admin_prompt_prefix };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reactive current-user preferences (server-backed, follows the account). */
|
||||||
|
export function useUserPreferences(): UserPreferences {
|
||||||
|
const { data } = useQuery({
|
||||||
|
queryKey: QUERY_KEY,
|
||||||
|
queryFn: getUserPreferences,
|
||||||
|
});
|
||||||
|
return data ?? DEFAULT_PREFS;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUserPreferencesQuery() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: QUERY_KEY,
|
||||||
|
queryFn: getUserPreferences,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdateUserPreferences() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: updateUserPreferences,
|
||||||
|
// Optimistically flip the cached preference so the switch — and every
|
||||||
|
// surface that reacts to it (e.g. the chat input's admin prompt-prefix
|
||||||
|
// toggle) — updates instantly instead of waiting for the round-trip,
|
||||||
|
// which made the toggle look like it "didn't take effect / didn't refresh".
|
||||||
|
onMutate: async (input) => {
|
||||||
|
await queryClient.cancelQueries({ queryKey: QUERY_KEY });
|
||||||
|
const previous = queryClient.getQueryData<UserPreferences>(QUERY_KEY);
|
||||||
|
queryClient.setQueryData<UserPreferences>(QUERY_KEY, (old) => ({
|
||||||
|
...(old ?? DEFAULT_PREFS),
|
||||||
|
...input,
|
||||||
|
}));
|
||||||
|
return { previous };
|
||||||
|
},
|
||||||
|
onError: (_err, _input, context) => {
|
||||||
|
// Roll back to the pre-toggle value if the server rejected the change.
|
||||||
|
if (context?.previous) {
|
||||||
|
queryClient.setQueryData(QUERY_KEY, context.previous);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onSuccess: (data) => {
|
||||||
|
queryClient.setQueryData(QUERY_KEY, data);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -94,10 +94,11 @@ const extensionMap: Record<string, string> = {
|
|||||||
ini: "ini",
|
ini: "ini",
|
||||||
env: "dotenv",
|
env: "dotenv",
|
||||||
|
|
||||||
// Markdown & Docs
|
// Markdown & Docs
|
||||||
md: "markdown",
|
md: "markdown",
|
||||||
mdx: "mdx",
|
mdx: "mdx",
|
||||||
rst: "rst",
|
mmd: "mermaid",
|
||||||
|
rst: "rst",
|
||||||
|
|
||||||
// SQL
|
// SQL
|
||||||
sql: "sql",
|
sql: "sql",
|
||||||
|
|||||||
@@ -1,10 +1,196 @@
|
|||||||
export function extractTitleFromMarkdown(markdown: string) {
|
export function extractTitleFromMarkdown(markdown: string) {
|
||||||
if (markdown.startsWith("# ")) {
|
if (markdown.startsWith("# ")) {
|
||||||
let title = markdown.split("\n")[0]!.trim();
|
let title = markdown.split("\n")[0]!.trim();
|
||||||
if (title.startsWith("# ")) {
|
if (title.startsWith("# ")) {
|
||||||
title = title.slice(2).trim();
|
title = title.slice(2).trim();
|
||||||
}
|
}
|
||||||
return title;
|
return title;
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type MarkdownHeadingAnchor = {
|
||||||
|
level: number;
|
||||||
|
text: string;
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type MarkdownAnchorResolver = {
|
||||||
|
headings: MarkdownHeadingAnchor[];
|
||||||
|
getHeadingId: (level: number, text: string) => string | undefined;
|
||||||
|
resolveHref: (href: string | undefined, label?: string) => string | null | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
const HEADING_RE = /^(#{1,6})\s+(.+?)\s*#*\s*$/;
|
||||||
|
const PROTOCOL_RE = /^[a-z][a-z\d+.-]*:/i;
|
||||||
|
|
||||||
|
function stripInlineMarkdown(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1")
|
||||||
|
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
|
||||||
|
.replace(/[`*_~]/g, "")
|
||||||
|
.replace(/<[^>]+>/g, "")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function markdownSlug(value: string): string {
|
||||||
|
const cleaned = stripInlineMarkdown(value)
|
||||||
|
.normalize("NFKC")
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^\p{L}\p{N}\s._-]+/gu, "")
|
||||||
|
.trim()
|
||||||
|
.replace(/[\s._-]+/g, "-")
|
||||||
|
.replace(/^-+|-+$/g, "");
|
||||||
|
return cleaned || "section";
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeLinkPart(value: string): string {
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(value);
|
||||||
|
} catch {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True for hrefs that point to an anchor within the current document (`#section`). */
|
||||||
|
export function isInPageAnchor(href: string | undefined | null): href is string {
|
||||||
|
return !!href && href.startsWith("#") && !href.startsWith("#reference-");
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeAttrValue(value: string): string {
|
||||||
|
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scrolls to an in-page anchor by id without mutating `window.location.hash`.
|
||||||
|
*
|
||||||
|
* The app runs under a HashRouter, so letting an `<a href="#...">` click change
|
||||||
|
* the hash would be interpreted as a route change and 404. We resolve the target
|
||||||
|
* element ourselves and scroll to it instead. Scoped to the nearest
|
||||||
|
* `[data-markdown-anchor-root]` so headings in other messages don't collide.
|
||||||
|
*/
|
||||||
|
export function scrollToInPageAnchor(anchor: HTMLElement, href: string | undefined | null): void {
|
||||||
|
if (!isInPageAnchor(href)) return;
|
||||||
|
const id = decodeLinkPart(href.slice(1)).trim();
|
||||||
|
if (!id) return;
|
||||||
|
const scope = anchor.closest<HTMLElement>("[data-markdown-anchor-root]");
|
||||||
|
const selector = `[id="${escapeAttrValue(id)}"]`;
|
||||||
|
const target =
|
||||||
|
(scope?.querySelector<HTMLElement>(selector) ?? null) ??
|
||||||
|
document.getElementById(id) ??
|
||||||
|
document.querySelector<HTMLElement>(selector);
|
||||||
|
target?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLookupKey(value: string): string {
|
||||||
|
return markdownSlug(decodeLinkPart(value).replace(/^#+/, ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isExternalOrSpecialHref(href: string): boolean {
|
||||||
|
if (href.startsWith("//")) return true;
|
||||||
|
if (PROTOCOL_RE.test(href)) return true;
|
||||||
|
return href.startsWith("/") || href.startsWith("?");
|
||||||
|
}
|
||||||
|
|
||||||
|
function candidateTextFromHref(href: string): string {
|
||||||
|
const withoutQuery = href.split(/[?#]/)[0] ?? href;
|
||||||
|
const lastSegment = withoutQuery.split("/").filter(Boolean).pop() ?? withoutQuery;
|
||||||
|
return decodeLinkPart(lastSegment).replace(/\.(md|markdown)$/i, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injects a small runtime script into generated HTML so that clicking an
|
||||||
|
* in-page anchor (`<a href="#section">`) scrolls within the iframe instead of
|
||||||
|
* navigating it. The preview iframe loads from a sandboxed `blob:` URL, where a
|
||||||
|
* fragment navigation blanks the frame; intercepting the click avoids that.
|
||||||
|
*/
|
||||||
|
export function injectInPageAnchorHandler(html: string): string {
|
||||||
|
const script = `<script>(function(){
|
||||||
|
function decode(v){try{return decodeURIComponent(v);}catch(e){return v;}}
|
||||||
|
function bySelector(id){
|
||||||
|
if(!document.querySelector)return null;
|
||||||
|
var esc=window.CSS&&CSS.escape?CSS.escape(id):id.replace(/["\\\\]/g,"\\\\$&");
|
||||||
|
try{return document.querySelector("#"+esc+",[name=\\""+esc+"\\"]");}catch(e){return null;}
|
||||||
|
}
|
||||||
|
document.addEventListener("click",function(e){
|
||||||
|
var el=e.target;
|
||||||
|
while(el&&el.tagName!=="A"){el=el.parentElement;}
|
||||||
|
if(!el)return;
|
||||||
|
var href=el.getAttribute("href");
|
||||||
|
if(!href||href.charAt(0)!=="#"||href.length<2)return;
|
||||||
|
e.preventDefault();
|
||||||
|
var id=decode(href.slice(1));
|
||||||
|
var raw=href.slice(1);
|
||||||
|
var target=
|
||||||
|
document.getElementById(id)||
|
||||||
|
document.getElementById(raw)||
|
||||||
|
document.getElementsByName(id)[0]||
|
||||||
|
document.getElementsByName(raw)[0]||
|
||||||
|
bySelector(id)||
|
||||||
|
bySelector(raw);
|
||||||
|
if(target){target.scrollIntoView({behavior:"smooth",block:"start"});}
|
||||||
|
},true);
|
||||||
|
})();</script>`;
|
||||||
|
if (/<\/body>/i.test(html)) {
|
||||||
|
return html.replace(/<\/body>/i, `${script}</body>`);
|
||||||
|
}
|
||||||
|
return html + script;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createMarkdownAnchorResolver(markdown: string): MarkdownAnchorResolver {
|
||||||
|
const headings: MarkdownHeadingAnchor[] = [];
|
||||||
|
const idsByLookup = new Map<string, string>();
|
||||||
|
const seen = new Map<string, number>();
|
||||||
|
let inFence = false;
|
||||||
|
|
||||||
|
for (const rawLine of markdown.split(/\r?\n/)) {
|
||||||
|
const line = rawLine.trim();
|
||||||
|
if (/^(```|~~~)/.test(line)) {
|
||||||
|
inFence = !inFence;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (inFence) continue;
|
||||||
|
|
||||||
|
const match = HEADING_RE.exec(rawLine);
|
||||||
|
if (!match) continue;
|
||||||
|
|
||||||
|
const level = match[1]!.length;
|
||||||
|
const text = stripInlineMarkdown(match[2]!);
|
||||||
|
const baseId = markdownSlug(text);
|
||||||
|
const count = seen.get(baseId) ?? 0;
|
||||||
|
seen.set(baseId, count + 1);
|
||||||
|
const id = count === 0 ? baseId : `${baseId}-${count}`;
|
||||||
|
|
||||||
|
headings.push({ level, text, id });
|
||||||
|
idsByLookup.set(normalizeLookupKey(text), id);
|
||||||
|
idsByLookup.set(normalizeLookupKey(id), id);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
headings,
|
||||||
|
getHeadingId: (level: number, text: string) => {
|
||||||
|
void level;
|
||||||
|
return idsByLookup.get(normalizeLookupKey(text));
|
||||||
|
},
|
||||||
|
resolveHref: (href: string | undefined, label?: string) => {
|
||||||
|
if (!href) return href;
|
||||||
|
const trimmed = href.trim();
|
||||||
|
if (!trimmed || isExternalOrSpecialHref(trimmed)) return href;
|
||||||
|
|
||||||
|
const hash = trimmed.includes("#") ? trimmed.slice(trimmed.indexOf("#") + 1) : "";
|
||||||
|
const candidates = [
|
||||||
|
hash,
|
||||||
|
trimmed.startsWith("#") ? trimmed.slice(1) : "",
|
||||||
|
candidateTextFromHref(trimmed),
|
||||||
|
label ?? "",
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const id = idsByLookup.get(normalizeLookupKey(candidate));
|
||||||
|
if (id) return `#${id}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return trimmed.startsWith("#") ? null : null;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { getFileName } from "./files";
|
||||||
|
|
||||||
|
let mermaidInitialized = false;
|
||||||
|
|
||||||
|
export function isMermaidFile(filepath: string): boolean {
|
||||||
|
return /\.mmd$/i.test(filepath);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMermaidImageFileName(filepath: string, extension = "svg"): string {
|
||||||
|
return getFileName(filepath).replace(/\.mmd$/i, `.${extension}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getMermaidModule() {
|
||||||
|
const mod = await import("mermaid");
|
||||||
|
const mermaid = mod.default;
|
||||||
|
if (!mermaidInitialized) {
|
||||||
|
mermaid.initialize({
|
||||||
|
startOnLoad: false,
|
||||||
|
securityLevel: "strict",
|
||||||
|
});
|
||||||
|
mermaidInitialized = true;
|
||||||
|
}
|
||||||
|
return mermaid;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function renderMermaidToSvg(source: string): Promise<string> {
|
||||||
|
const text = source.trim();
|
||||||
|
if (!text) {
|
||||||
|
throw new Error("Mermaid 内容为空,无法生成图片");
|
||||||
|
}
|
||||||
|
|
||||||
|
const mermaid = await getMermaidModule();
|
||||||
|
const renderId = `mermaid-preview-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
|
const host = document.createElement("div");
|
||||||
|
host.style.position = "fixed";
|
||||||
|
host.style.left = "-10000px";
|
||||||
|
host.style.top = "-10000px";
|
||||||
|
host.style.pointerEvents = "none";
|
||||||
|
host.style.opacity = "0";
|
||||||
|
document.body.appendChild(host);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { svg, bindFunctions } = await mermaid.render(renderId, text);
|
||||||
|
host.innerHTML = svg;
|
||||||
|
bindFunctions?.(host);
|
||||||
|
return host.innerHTML;
|
||||||
|
} finally {
|
||||||
|
host.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openMermaidSvgInNewTab(source: string): Promise<void> {
|
||||||
|
const svg = await renderMermaidToSvg(source);
|
||||||
|
const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
|
||||||
|
const objectUrl = URL.createObjectURL(blob);
|
||||||
|
const win = window.open(objectUrl, "_blank", "noopener,noreferrer");
|
||||||
|
if (win) {
|
||||||
|
win.opener = null;
|
||||||
|
}
|
||||||
|
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 120_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function downloadMermaidSvgFile(source: string, filepath: string): Promise<void> {
|
||||||
|
const svg = await renderMermaidToSvg(source);
|
||||||
|
const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
|
||||||
|
const objectUrl = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = objectUrl;
|
||||||
|
a.download = getMermaidImageFileName(filepath);
|
||||||
|
a.rel = "noopener";
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 30_000);
|
||||||
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
import "./styles/globals.css";
|
import "@fontsource/noto-sans-sc/chinese-simplified-400.css";
|
||||||
import "tdesign-react/es/style/index.css";
|
import "@fontsource/noto-sans-sc/chinese-simplified-500.css";
|
||||||
import "katex/dist/katex.min.css";
|
import "@fontsource/noto-sans-sc/chinese-simplified-600.css";
|
||||||
|
import "@fontsource/noto-sans-sc/chinese-simplified-700.css";
|
||||||
|
import "./styles/globals.css";
|
||||||
|
import "tdesign-react/es/style/index.css";
|
||||||
|
import "katex/dist/katex.min.css";
|
||||||
|
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import ReactDOM from "react-dom/client";
|
import ReactDOM from "react-dom/client";
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
Download,
|
Download,
|
||||||
Edit3,
|
Edit3,
|
||||||
@@ -71,6 +72,7 @@ const emptyForm = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function AdminScheduledTasksPage() {
|
export default function AdminScheduledTasksPage() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [searchParams] = useSearchParams();
|
const [searchParams] = useSearchParams();
|
||||||
@@ -178,8 +180,15 @@ export default function AdminScheduledTasksPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const triggerTask = async (task: ScheduledTask) => {
|
const triggerTask = async (task: ScheduledTask) => {
|
||||||
|
setSelectedTaskId(task.task_id);
|
||||||
try {
|
try {
|
||||||
await actions.trigger.mutateAsync(task.task_id);
|
await actions.trigger.mutateAsync(task.task_id);
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: ["scheduled-tasks", "admin", task.task_id, "runs"],
|
||||||
|
});
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: ["scheduled-tasks", "admin", "list"],
|
||||||
|
});
|
||||||
toast.success("已触发执行");
|
toast.success("已触发执行");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.error(error instanceof Error ? error.message : "触发失败");
|
toast.error(error instanceof Error ? error.message : "触发失败");
|
||||||
@@ -208,23 +217,24 @@ export default function AdminScheduledTasksPage() {
|
|||||||
<WorkspaceContainer>
|
<WorkspaceContainer>
|
||||||
<WorkspaceHeader />
|
<WorkspaceHeader />
|
||||||
<WorkspaceBody>
|
<WorkspaceBody>
|
||||||
<div className="grid size-full min-h-0 grid-cols-1 gap-4 p-4 xl:grid-cols-[460px_minmax(0,1fr)]">
|
<div className="grid size-full min-h-0 grid-cols-1 grid-rows-[minmax(0,1fr)_minmax(0,1fr)] gap-4 p-4 xl:grid-cols-[460px_minmax(0,1fr)] xl:grid-rows-1">
|
||||||
<Card className="flex min-h-0 flex-col">
|
<Card className="flex min-h-0 min-w-0 flex-col">
|
||||||
<CardHeader className="gap-3">
|
<CardHeader className="gap-3">
|
||||||
<div>
|
<div className="min-w-0">
|
||||||
<CardTitle>定时任务管理</CardTitle>
|
<CardTitle>定时任务管理</CardTitle>
|
||||||
<p className="text-muted-foreground mt-1 text-sm">
|
<p className="text-muted-foreground mt-1 text-sm">
|
||||||
管理员视图:查看、编辑、删除全部用户的定时任务
|
管理员视图:查看、编辑、删除全部用户的定时任务
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<form
|
<form
|
||||||
className="flex gap-2"
|
className="flex min-w-0 gap-2"
|
||||||
onSubmit={(event) => {
|
onSubmit={(event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
setSearch(searchInput.trim());
|
setSearch(searchInput.trim());
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Input
|
<Input
|
||||||
|
className="min-w-0"
|
||||||
value={searchInput}
|
value={searchInput}
|
||||||
onChange={(event) => setSearchInput(event.target.value)}
|
onChange={(event) => setSearchInput(event.target.value)}
|
||||||
placeholder="按任务名称搜索"
|
placeholder="按任务名称搜索"
|
||||||
@@ -268,7 +278,7 @@ export default function AdminScheduledTasksPage() {
|
|||||||
onClick={() => setSelectedTaskId(task.task_id)}
|
onClick={() => setSelectedTaskId(task.task_id)}
|
||||||
>
|
>
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="truncate font-medium">
|
<div className="truncate font-medium">
|
||||||
{task.name}
|
{task.name}
|
||||||
</div>
|
</div>
|
||||||
@@ -348,10 +358,10 @@ export default function AdminScheduledTasksPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="flex min-h-0 flex-col">
|
<Card className="flex min-h-0 min-w-0 flex-col">
|
||||||
<CardHeader className="gap-2">
|
<CardHeader className="gap-2">
|
||||||
<CardTitle>执行记录</CardTitle>
|
<CardTitle>执行记录</CardTitle>
|
||||||
<p className="text-muted-foreground text-sm">
|
<p className="text-muted-foreground min-w-0 truncate text-sm">
|
||||||
{selectedTask ? selectedTask.name : "请选择左侧任务"}
|
{selectedTask ? selectedTask.name : "请选择左侧任务"}
|
||||||
</p>
|
</p>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
@@ -379,11 +389,11 @@ export default function AdminScheduledTasksPage() {
|
|||||||
className="rounded-md border p-4 transition-colors hover:bg-accent/40"
|
className="rounded-md border p-4 transition-colors hover:bg-accent/40"
|
||||||
>
|
>
|
||||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="truncate font-medium">
|
<div className="truncate font-medium">
|
||||||
{run.result?.title || formatDate(run.scheduled_for)}
|
{run.result?.title || formatDate(run.scheduled_for)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-muted-foreground mt-1 text-xs">
|
<div className="text-muted-foreground mt-1 break-words text-xs">
|
||||||
计划:{formatDate(run.scheduled_for)} · 开始:
|
计划:{formatDate(run.scheduled_for)} · 开始:
|
||||||
{formatDate(run.started_at)}
|
{formatDate(run.started_at)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,46 +1,21 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Loader2, MessageSquareIcon, SearchIcon, UserIcon } from "lucide-react";
|
import { Loader2, MessageSquareIcon, SearchIcon, UserIcon, XIcon } from "lucide-react";
|
||||||
import { useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { useSearchParams } from "react-router-dom";
|
||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
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 { ScrollArea } from "@/components/ui/scroll-area";
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { useUserMemory, useUserThreadMessages, useUserThreads } from "@/core/admin/hooks";
|
import { useUserMemory, useUserQa, useUserThreads } from "@/core/admin/hooks";
|
||||||
import type { AdminMemoryBucket, AdminMessage } from "@/core/admin/api";
|
import type { AdminMemoryBucket, AdminUserQaItem } from "@/core/admin/api";
|
||||||
import { useAllUsers } from "@/core/auth/hooks";
|
import { useAllUsers } from "@/core/auth/hooks";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
/** Flatten a langchain message dump (or raw string / block list) into text. */
|
const QA_PAGE_SIZE = 20;
|
||||||
function extractText(content: unknown): string {
|
|
||||||
if (content == null) return "";
|
|
||||||
if (typeof content === "string") return content;
|
|
||||||
if (Array.isArray(content)) {
|
|
||||||
return content
|
|
||||||
.map((block) => {
|
|
||||||
if (typeof block === "string") return block;
|
|
||||||
if (block && typeof block === "object") {
|
|
||||||
const text = (block as Record<string, unknown>).text;
|
|
||||||
if (typeof text === "string") return text;
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
})
|
|
||||||
.join("");
|
|
||||||
}
|
|
||||||
if (typeof content === "object") {
|
|
||||||
const inner = (content as Record<string, unknown>).content;
|
|
||||||
if (inner !== undefined) return extractText(inner);
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
function roleOf(message: AdminMessage): "user" | "assistant" | null {
|
|
||||||
const type = (message.type ?? "").toLowerCase();
|
|
||||||
if (type === "human") return "user";
|
|
||||||
if (type === "ai" || type === "aimessagechunk") return "assistant";
|
|
||||||
return null; // tool results and system messages are hidden from the Q&A view
|
|
||||||
}
|
|
||||||
|
|
||||||
function fmtTime(iso: string): string {
|
function fmtTime(iso: string): string {
|
||||||
if (!iso) return "";
|
if (!iso) return "";
|
||||||
@@ -48,24 +23,39 @@ function fmtTime(iso: string): string {
|
|||||||
return Number.isNaN(d.getTime()) ? iso : d.toLocaleString();
|
return Number.isNaN(d.getTime()) ? iso : d.toLocaleString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A single Q&A bubble. */
|
function fmtNumber(value: number): string {
|
||||||
function MessageRow({ message }: { message: AdminMessage }) {
|
return new Intl.NumberFormat("zh-CN").format(value || 0);
|
||||||
const role = roleOf(message);
|
}
|
||||||
if (!role) return null;
|
|
||||||
const text = extractText(message.content).trim();
|
function QaItemCard({ item }: { item: AdminUserQaItem }) {
|
||||||
if (!text) return null; // skip empty AI turns (e.g. tool-call-only responses)
|
const isError = item.status === "error" || item.status === "timeout";
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex flex-col gap-1", role === "user" ? "items-start" : "items-end")}>
|
<div className="rounded-md border bg-background p-4">
|
||||||
<span className="text-muted-foreground text-xs">
|
<div className="mb-3 flex flex-wrap items-center gap-2">
|
||||||
{role === "user" ? "用户提问" : "AI 回答"}
|
<span className="text-muted-foreground text-xs">{fmtTime(item.created_at)}</span>
|
||||||
</span>
|
<Badge variant={isError ? "destructive" : "secondary"}>{item.status || "unknown"}</Badge>
|
||||||
<div
|
{item.model_name && <Badge variant="outline">{item.model_name}</Badge>}
|
||||||
className={cn(
|
{item.assistant_id && <Badge variant="outline">{item.assistant_id}</Badge>}
|
||||||
"max-w-[85%] whitespace-pre-wrap rounded-lg border px-3 py-2 text-sm",
|
<span className="text-muted-foreground text-xs">{fmtNumber(item.total_tokens)} tokens</span>
|
||||||
role === "user" ? "bg-muted" : "bg-primary/5 border-primary/20",
|
</div>
|
||||||
)}
|
{(item.thread_title || item.thread_id) && (
|
||||||
>
|
<div className="text-muted-foreground mb-3 truncate text-xs">
|
||||||
{text}
|
{item.thread_title || "未命名会话"} · {item.thread_id}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="text-muted-foreground mb-1 text-xs font-medium">用户提问</div>
|
||||||
|
<div className="bg-muted whitespace-pre-wrap rounded-md px-3 py-2 text-sm">
|
||||||
|
{item.question || "空问题"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-muted-foreground mb-1 text-xs font-medium">AI 回答</div>
|
||||||
|
<div className="border-primary/20 bg-primary/5 max-h-64 overflow-auto whitespace-pre-wrap rounded-md border px-3 py-2 text-sm">
|
||||||
|
{item.answer || "暂无回答"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -109,19 +99,38 @@ function MemoryBucketView({ bucket }: { bucket: AdminMemoryBucket }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function AdminUserActivityPage() {
|
export default function AdminUserActivityPage() {
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
const { data: users, isLoading: usersLoading } = useAllUsers(true);
|
const { data: users, isLoading: usersLoading } = useAllUsers(true);
|
||||||
const [userId, setUserId] = useState<string | null>(null);
|
const [userId, setUserId] = useState<string | null>(null);
|
||||||
const [threadId, setThreadId] = useState<string | null>(null);
|
const [threadId, setThreadId] = useState<string | null>(null);
|
||||||
const [userQuery, setUserQuery] = useState("");
|
const [userQuery, setUserQuery] = useState("");
|
||||||
|
const [qaQuery, setQaQuery] = useState("");
|
||||||
|
const [qaPage, setQaPage] = useState(1);
|
||||||
const [tab, setTab] = useState<"qa" | "memory">("qa");
|
const [tab, setTab] = useState<"qa" | "memory">("qa");
|
||||||
|
const targetUserId = searchParams.get("user");
|
||||||
|
|
||||||
const { data: threads, isLoading: threadsLoading } = useUserThreads(userId);
|
const { data: threads, isLoading: threadsLoading } = useUserThreads(userId);
|
||||||
const { data: messages, isLoading: messagesLoading } = useUserThreadMessages(
|
const { data: qaData, isLoading: qaLoading, isFetching: qaFetching } = useUserQa(userId, {
|
||||||
userId,
|
page: qaPage,
|
||||||
threadId,
|
pageSize: QA_PAGE_SIZE,
|
||||||
);
|
q: qaQuery,
|
||||||
|
});
|
||||||
const { data: memory, isLoading: memoryLoading } = useUserMemory(userId);
|
const { data: memory, isLoading: memoryLoading } = useUserMemory(userId);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (targetUserId) {
|
||||||
|
setUserId(targetUserId);
|
||||||
|
setThreadId(null);
|
||||||
|
setQaQuery("");
|
||||||
|
setQaPage(1);
|
||||||
|
setTab("qa");
|
||||||
|
}
|
||||||
|
}, [targetUserId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setQaPage(1);
|
||||||
|
}, [userId, qaQuery]);
|
||||||
|
|
||||||
const filteredUsers = useMemo(() => {
|
const filteredUsers = useMemo(() => {
|
||||||
const needle = userQuery.trim().toLowerCase();
|
const needle = userQuery.trim().toLowerCase();
|
||||||
const list = users ?? [];
|
const list = users ?? [];
|
||||||
@@ -133,9 +142,17 @@ export default function AdminUserActivityPage() {
|
|||||||
const selectUser = (id: string) => {
|
const selectUser = (id: string) => {
|
||||||
setUserId(id);
|
setUserId(id);
|
||||||
setThreadId(null);
|
setThreadId(null);
|
||||||
|
setQaQuery("");
|
||||||
|
setQaPage(1);
|
||||||
setTab("qa");
|
setTab("qa");
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const clearQaFilter = () => {
|
||||||
|
setThreadId(null);
|
||||||
|
setQaQuery("");
|
||||||
|
setQaPage(1);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex size-full flex-col">
|
<div className="flex size-full flex-col">
|
||||||
<div className="border-b px-6 py-4">
|
<div className="border-b px-6 py-4">
|
||||||
@@ -192,8 +209,19 @@ export default function AdminUserActivityPage() {
|
|||||||
|
|
||||||
{/* Pane 2: threads */}
|
{/* Pane 2: threads */}
|
||||||
<div className="flex w-72 shrink-0 flex-col border-r">
|
<div className="flex w-72 shrink-0 flex-col border-r">
|
||||||
<div className="text-muted-foreground border-b px-3 py-2 text-xs font-medium">
|
<div className="flex items-center justify-between gap-2 border-b px-3 py-2">
|
||||||
会话列表{threads ? `(${threads.length})` : ""}
|
<span className="text-muted-foreground text-xs font-medium">
|
||||||
|
会话列表{threads ? `(${threads.length})` : ""}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
disabled={!userId || (!threadId && !qaQuery)}
|
||||||
|
onClick={clearQaFilter}
|
||||||
|
>
|
||||||
|
全部
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<ScrollArea className="min-h-0 flex-1">
|
<ScrollArea className="min-h-0 flex-1">
|
||||||
{!userId && (
|
{!userId && (
|
||||||
@@ -218,6 +246,8 @@ export default function AdminUserActivityPage() {
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setThreadId(thread.thread_id);
|
setThreadId(thread.thread_id);
|
||||||
|
setQaQuery(thread.thread_id);
|
||||||
|
setQaPage(1);
|
||||||
setTab("qa");
|
setTab("qa");
|
||||||
}}
|
}}
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -259,28 +289,63 @@ export default function AdminUserActivityPage() {
|
|||||||
|
|
||||||
<ScrollArea className="min-h-0 flex-1">
|
<ScrollArea className="min-h-0 flex-1">
|
||||||
{tab === "qa" && (
|
{tab === "qa" && (
|
||||||
<div className="p-4">
|
<div className="flex flex-col gap-4 p-4">
|
||||||
{!threadId && (
|
<div className="flex flex-col gap-2">
|
||||||
<div className="text-muted-foreground flex flex-col items-center gap-2 py-16 text-sm">
|
<div className="flex items-center gap-2">
|
||||||
<MessageSquareIcon className="size-6" />
|
<div className="relative min-w-0 flex-1">
|
||||||
请从中间列选择一个会话
|
<SearchIcon className="text-muted-foreground absolute left-3 top-1/2 size-4 -translate-y-1/2" />
|
||||||
|
<Input
|
||||||
|
value={qaQuery}
|
||||||
|
onChange={(event) => {
|
||||||
|
setQaQuery(event.target.value);
|
||||||
|
setThreadId(null);
|
||||||
|
setQaPage(1);
|
||||||
|
}}
|
||||||
|
placeholder="搜索问题、回答、运行 ID 或会话 ID"
|
||||||
|
className="pl-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{qaQuery && (
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={clearQaFilter}>
|
||||||
|
<XIcon className="size-4" />
|
||||||
|
清空
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
<div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">
|
||||||
{threadId && messagesLoading && (
|
<span>共 {fmtNumber(qaData?.total ?? 0)} 条问答</span>
|
||||||
|
{threadId && <Badge variant="outline">已按会话过滤</Badge>}
|
||||||
|
{qaFetching && !qaLoading && (
|
||||||
|
<span className="inline-flex items-center gap-1">
|
||||||
|
<Loader2 className="size-3 animate-spin" /> 更新中
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{qaLoading && (
|
||||||
<div className="text-muted-foreground flex items-center justify-center gap-2 py-16 text-sm">
|
<div className="text-muted-foreground flex items-center justify-center gap-2 py-16 text-sm">
|
||||||
<Loader2 className="size-4 animate-spin" /> 加载中
|
<Loader2 className="size-4 animate-spin" /> 加载中
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{threadId && !messagesLoading && (
|
{!qaLoading && (qaData?.items.length ?? 0) === 0 && (
|
||||||
|
<div className="text-muted-foreground flex flex-col items-center gap-2 py-16 text-sm">
|
||||||
|
<MessageSquareIcon className="size-6" />
|
||||||
|
暂无匹配的问答记录
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{!qaLoading && (qaData?.items.length ?? 0) > 0 && (
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
{(messages ?? []).map((m, i) => (
|
{(qaData?.items ?? []).map((item) => (
|
||||||
<MessageRow key={m.id ?? i} message={m} />
|
<QaItemCard key={item.run_id} item={item} />
|
||||||
))}
|
))}
|
||||||
{(messages ?? []).every((m) => !roleOf(m)) && (
|
<Pagination
|
||||||
<div className="text-muted-foreground py-12 text-center text-sm">
|
page={qaPage}
|
||||||
该会话暂无问答记录
|
pageSize={QA_PAGE_SIZE}
|
||||||
</div>
|
total={qaData?.total ?? 0}
|
||||||
)}
|
onPageChange={setQaPage}
|
||||||
|
className="pt-2"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,204 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ArrowLeft, Save, Search, ShieldOff, SlidersHorizontal, X } from "lucide-react";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import type { UserListItem } from "@/core/auth/api";
|
||||||
|
import { useAllUsers } from "@/core/auth/hooks";
|
||||||
|
import {
|
||||||
|
useLeaderboardSettings,
|
||||||
|
useUpdateLeaderboardSettings,
|
||||||
|
} from "@/core/system-settings/hooks";
|
||||||
|
|
||||||
|
function userLabel(user?: UserListItem) {
|
||||||
|
return user?.email || user?.id || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminUserLeaderboardSettingsPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { data: users = [] } = useAllUsers(true);
|
||||||
|
const { data: settings, isLoading } = useLeaderboardSettings();
|
||||||
|
const updateSettings = useUpdateLeaderboardSettings();
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
|
||||||
|
const excludedIds = settings?.exclude_user_ids ?? [];
|
||||||
|
const selectedUsers = useMemo(
|
||||||
|
() => excludedIds.map((id) => users.find((user) => user.id === id) ?? ({ id, email: id, system_role: "user" } as UserListItem)),
|
||||||
|
[excludedIds, users],
|
||||||
|
);
|
||||||
|
const candidates = useMemo(() => {
|
||||||
|
const needle = query.trim().toLowerCase();
|
||||||
|
if (!needle) return [];
|
||||||
|
return users
|
||||||
|
.filter((user) => !excludedIds.includes(user.id))
|
||||||
|
.filter((user) => `${user.email} ${user.id}`.toLowerCase().includes(needle))
|
||||||
|
.slice(0, 8);
|
||||||
|
}, [excludedIds, query, users]);
|
||||||
|
|
||||||
|
const patch = async (body: Record<string, unknown>) => {
|
||||||
|
try {
|
||||||
|
await updateSettings.mutateAsync(body);
|
||||||
|
toast.success("排行榜设置已保存");
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : "保存失败");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const addUser = (userId: string) => {
|
||||||
|
void patch({ exclude_user_ids: [...excludedIds, userId] });
|
||||||
|
setQuery("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeUser = (userId: string) => {
|
||||||
|
void patch({ exclude_user_ids: excludedIds.filter((id) => id !== userId) });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex size-full min-h-0 bg-[#FFF7F7] text-[#231815] dark:bg-[#19090A] dark:text-white">
|
||||||
|
<main className="flex min-w-0 flex-1 flex-col">
|
||||||
|
<div className="border-b border-[#F1D6D6] bg-white px-6 py-5 dark:border-[#462123] dark:bg-[#230D0F]">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="mb-2 flex items-center gap-2 text-sm text-[#9F343A]">
|
||||||
|
<SlidersHorizontal className="size-4" />
|
||||||
|
管理员设置
|
||||||
|
</div>
|
||||||
|
<h1 className="text-2xl font-semibold">排行榜设置</h1>
|
||||||
|
<p className="mt-1 text-sm text-[#7A5A5A] dark:text-[#D8B8B8]">
|
||||||
|
这里的规则会影响用户排行榜、趋势、技能、模型、问题与个人详情统计。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button variant="outline" onClick={() => navigate("/page/strategy/admin/user-leaderboard")}>
|
||||||
|
<ArrowLeft className="mr-1 size-4" />
|
||||||
|
返回排行榜
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ScrollArea className="min-h-0 flex-1">
|
||||||
|
<div className="mx-auto max-w-6xl space-y-5 p-6">
|
||||||
|
<section className="rounded-lg border border-[#F1D6D6] bg-white p-5 shadow-sm dark:border-[#462123] dark:bg-[#230D0F]">
|
||||||
|
<div className="mb-4 flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2 font-semibold">
|
||||||
|
<ShieldOff className="size-4 text-[#C1121F]" />
|
||||||
|
统计排除名单
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-sm text-[#7A5A5A] dark:text-[#D8B8B8]">
|
||||||
|
名单中的账号不会进入排行榜、趋势、问题、模型和技能统计。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{excludedIds.length > 0 && (
|
||||||
|
<Button size="sm" variant="outline" onClick={() => void patch({ exclude_user_ids: [] })}>
|
||||||
|
清空名单
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 lg:grid-cols-[340px_minmax(0,1fr)]">
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-[#A87575]" />
|
||||||
|
<Input
|
||||||
|
value={query}
|
||||||
|
onChange={(event) => setQuery(event.target.value)}
|
||||||
|
placeholder="搜索账号邮箱或 ID"
|
||||||
|
className="h-10 border-[#F1D6D6] bg-white pl-9"
|
||||||
|
/>
|
||||||
|
{query.trim() && candidates.length > 0 && (
|
||||||
|
<div className="absolute z-20 mt-2 max-h-72 w-full overflow-hidden rounded-lg border border-[#F1D6D6] bg-white shadow-lg dark:border-[#462123] dark:bg-[#230D0F]">
|
||||||
|
<ScrollArea className="max-h-72">
|
||||||
|
{candidates.map((user) => (
|
||||||
|
<button
|
||||||
|
key={user.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => addUser(user.id)}
|
||||||
|
className="flex w-full items-center justify-between gap-3 border-b border-[#F8EAEA] px-3 py-2 text-left text-sm last:border-b-0 hover:bg-[#FFF1F1] dark:border-[#462123] dark:hover:bg-[#361315]"
|
||||||
|
>
|
||||||
|
<span className="min-w-0">
|
||||||
|
<span className="block truncate font-medium">{user.email}</span>
|
||||||
|
<span className="block truncate text-xs text-[#8B6B6B]">{user.id}</span>
|
||||||
|
</span>
|
||||||
|
<Badge variant="outline">{user.system_role === "admin" ? "管理员" : "用户"}</Badge>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</ScrollArea>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="min-h-10 rounded-lg bg-[#FFF7F7] p-3 dark:bg-[#19090A]">
|
||||||
|
{selectedUsers.length === 0 ? (
|
||||||
|
<span className="text-sm text-[#8B6B6B]">暂无排除账号</span>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{selectedUsers.map((user) => (
|
||||||
|
<span
|
||||||
|
key={user.id}
|
||||||
|
className="inline-flex max-w-[280px] items-center gap-1.5 rounded-full border border-[#F1D6D6] bg-white px-3 py-1.5 text-xs text-[#7A1F25] shadow-sm dark:border-[#462123] dark:bg-[#230D0F] dark:text-[#F2B8BB]"
|
||||||
|
title={userLabel(user)}
|
||||||
|
>
|
||||||
|
<span className="truncate">{userLabel(user)}</span>
|
||||||
|
<button type="button" onClick={() => removeUser(user.id)} aria-label={`移除 ${userLabel(user)}`}>
|
||||||
|
<X className="size-3.5" />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="rounded-lg border border-[#F1D6D6] bg-white p-5 shadow-sm dark:border-[#462123] dark:bg-[#230D0F]">
|
||||||
|
<div className="mb-4 flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2 font-semibold">
|
||||||
|
<Save className="size-4 text-[#C1121F]" />
|
||||||
|
统计规则
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-sm text-[#7A5A5A] dark:text-[#D8B8B8]">
|
||||||
|
关闭某项后,该类数据会从榜单、趋势、问题列表和个人统计中移除。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{isLoading && <Badge variant="outline">加载中</Badge>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-3 md:grid-cols-2">
|
||||||
|
{[
|
||||||
|
["include_scheduled", "统计定时任务", "关闭后,定时任务产生的运行、问答、Token、模型调用、最新问题都不统计。"],
|
||||||
|
["include_admins", "统计管理员账号", "关闭后,管理员账号不参与排行和整体指标。"],
|
||||||
|
["include_failed", "统计失败运行", "关闭后,失败运行和失败模型调用不进入榜单。"],
|
||||||
|
["cleanup_system_questions", "隐藏系统标签问题", "开启后,<uploaded_files> 等附件/系统标签不会出现在问题列表。"],
|
||||||
|
].map(([key, title, desc]) => (
|
||||||
|
<label
|
||||||
|
key={key}
|
||||||
|
className="flex min-h-28 cursor-pointer items-start justify-between gap-4 rounded-lg border border-[#F1D6D6] bg-[#FFF7F7] p-4 dark:border-[#462123] dark:bg-[#19090A]"
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
<span className="block font-medium">{title}</span>
|
||||||
|
<span className="mt-1 block text-sm leading-6 text-[#7A5A5A] dark:text-[#D8B8B8]">{desc}</span>
|
||||||
|
</span>
|
||||||
|
<Switch
|
||||||
|
checked={Boolean(settings?.[key as keyof typeof settings])}
|
||||||
|
disabled={!settings || updateSettings.isPending}
|
||||||
|
onCheckedChange={(checked) => void patch({ [key]: checked })}
|
||||||
|
aria-label={title}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -131,8 +131,8 @@ export default function AgentChatPage() {
|
|||||||
const pendingMessageHandled = useRef(false);
|
const pendingMessageHandled = useRef(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (pendingMessageHandled.current) return;
|
if (pendingMessageHandled.current) return;
|
||||||
if (!agent_id || !isNewThread || hasStartedConversation) return;
|
if (!agent_id) return;
|
||||||
let pending: { agentId?: string; text?: string } | null = null;
|
let pending: { agentId?: string; threadId?: string; text?: string } | null = null;
|
||||||
try {
|
try {
|
||||||
const raw = sessionStorage.getItem("pendingAgentMessage");
|
const raw = sessionStorage.getItem("pendingAgentMessage");
|
||||||
if (raw) pending = JSON.parse(raw);
|
if (raw) pending = JSON.parse(raw);
|
||||||
@@ -140,10 +140,15 @@ export default function AgentChatPage() {
|
|||||||
pending = null;
|
pending = null;
|
||||||
}
|
}
|
||||||
if (!pending || pending.agentId !== agent_id || !pending.text) return;
|
if (!pending || pending.agentId !== agent_id || !pending.text) return;
|
||||||
|
if (pending.threadId) {
|
||||||
|
if (pending.threadId !== threadId) return;
|
||||||
|
} else if (!isNewThread) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
pendingMessageHandled.current = true;
|
pendingMessageHandled.current = true;
|
||||||
sessionStorage.removeItem("pendingAgentMessage");
|
sessionStorage.removeItem("pendingAgentMessage");
|
||||||
handleSubmit({ text: pending.text, files: [] });
|
handleSubmit({ text: pending.text, files: [] });
|
||||||
}, [agent_id, isNewThread, hasStartedConversation, handleSubmit]);
|
}, [agent_id, threadId, isNewThread, handleSubmit]);
|
||||||
|
|
||||||
const handleClarificationSubmit = useCallback(
|
const handleClarificationSubmit = useCallback(
|
||||||
(answer: string) => {
|
(answer: string) => {
|
||||||
@@ -250,6 +255,7 @@ export default function AgentChatPage() {
|
|||||||
className="w-full"
|
className="w-full"
|
||||||
isNewThread={isLandingState}
|
isNewThread={isLandingState}
|
||||||
threadId={threadId}
|
threadId={threadId}
|
||||||
|
assistantId={agent_id}
|
||||||
autoFocus={isLandingState}
|
autoFocus={isLandingState}
|
||||||
status={
|
status={
|
||||||
thread.error
|
thread.error
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
import { type PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
import { type PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
||||||
|
import { getAPIClient } from "@/core/api";
|
||||||
import { usePromptPrefixSettings } from "@/core/system-settings/hooks";
|
import { usePromptPrefixSettings } from "@/core/system-settings/hooks";
|
||||||
|
import { useUserPreferencesQuery } from "@/core/user-preferences";
|
||||||
import { ArtifactTrigger, useArtifacts } from "@/components/workspace/artifacts";
|
import { ArtifactTrigger, useArtifacts } from "@/components/workspace/artifacts";
|
||||||
import {
|
import {
|
||||||
ChatBox,
|
ChatBox,
|
||||||
@@ -50,8 +53,15 @@ export default function ChatPage() {
|
|||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
const { tokenUsageEnabled } = useModels();
|
const { tokenUsageEnabled } = useModels();
|
||||||
const { data: promptPrefixSettings } = usePromptPrefixSettings();
|
const { data: promptPrefixSettings } = usePromptPrefixSettings();
|
||||||
|
// Personal opt-out: when set, hide the admin prompt-prefix switch entirely and
|
||||||
|
// never apply the prefix — the user uses only their own prompts.
|
||||||
|
const { data: userPreferences, isLoading: preferencesLoading } =
|
||||||
|
useUserPreferencesQuery();
|
||||||
|
const hideAdminPrompt = userPreferences?.hide_admin_prompt_prefix === true;
|
||||||
const [promptPrefixOn, setPromptPrefixOn] = useState(false);
|
const [promptPrefixOn, setPromptPrefixOn] = useState(false);
|
||||||
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
|
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
|
||||||
|
const [agentHandoffPending, setAgentHandoffPending] = useState(false);
|
||||||
|
const agentHandoffPendingRef = useRef(false);
|
||||||
const { agents: selectorAgents, isLoading: selectorLoading } =
|
const { agents: selectorAgents, isLoading: selectorLoading } =
|
||||||
useAgentSelector();
|
useAgentSelector();
|
||||||
const { selectedArtifact } = useArtifacts();
|
const { selectedArtifact } = useArtifacts();
|
||||||
@@ -142,15 +152,37 @@ export default function ChatPage() {
|
|||||||
message.text &&
|
message.text &&
|
||||||
(!message.files || message.files.length === 0)
|
(!message.files || message.files.length === 0)
|
||||||
) {
|
) {
|
||||||
try {
|
if (agentHandoffPendingRef.current) return;
|
||||||
sessionStorage.setItem(
|
const text = message.text.trim();
|
||||||
"pendingAgentMessage",
|
agentHandoffPendingRef.current = true;
|
||||||
JSON.stringify({ agentId: selectedAgentId, text: message.text }),
|
setAgentHandoffPending(true);
|
||||||
);
|
setHasStartedConversation(true);
|
||||||
} catch {
|
void (async () => {
|
||||||
// sessionStorage may be unavailable in private mode; fall through.
|
try {
|
||||||
}
|
const created = await getAPIClient(isMock).threads.create({
|
||||||
router.push(`/page/workspace/agents/${selectedAgentId}/chats/new`);
|
metadata: { agent_id: selectedAgentId },
|
||||||
|
});
|
||||||
|
sessionStorage.setItem(
|
||||||
|
"pendingAgentMessage",
|
||||||
|
JSON.stringify({
|
||||||
|
agentId: selectedAgentId,
|
||||||
|
threadId: created.thread_id,
|
||||||
|
text,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
saveLastAgentId(selectedAgentId);
|
||||||
|
router.push(
|
||||||
|
`/page/workspace/agents/${selectedAgentId}/chats/${created.thread_id}`,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
agentHandoffPendingRef.current = false;
|
||||||
|
setAgentHandoffPending(false);
|
||||||
|
setHasStartedConversation(false);
|
||||||
|
toast.error(
|
||||||
|
err instanceof Error ? err.message : "创建智能体对话失败",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,6 +191,8 @@ export default function ChatPage() {
|
|||||||
isNewThread &&
|
isNewThread &&
|
||||||
!hasStartedConversation &&
|
!hasStartedConversation &&
|
||||||
promptPrefixOn &&
|
promptPrefixOn &&
|
||||||
|
!preferencesLoading &&
|
||||||
|
!hideAdminPrompt &&
|
||||||
promptPrefixSettings?.enabled === true;
|
promptPrefixSettings?.enabled === true;
|
||||||
setHasStartedConversation(true);
|
setHasStartedConversation(true);
|
||||||
window.dispatchEvent(
|
window.dispatchEvent(
|
||||||
@@ -189,7 +223,11 @@ export default function ChatPage() {
|
|||||||
hasStartedConversation,
|
hasStartedConversation,
|
||||||
promptPrefixOn,
|
promptPrefixOn,
|
||||||
promptPrefixSettings,
|
promptPrefixSettings,
|
||||||
|
hideAdminPrompt,
|
||||||
|
preferencesLoading,
|
||||||
selectedAgentId,
|
selectedAgentId,
|
||||||
|
agentHandoffPending,
|
||||||
|
isMock,
|
||||||
router,
|
router,
|
||||||
settings.context.writing_mode,
|
settings.context.writing_mode,
|
||||||
writingArtifactPath,
|
writingArtifactPath,
|
||||||
@@ -217,6 +255,9 @@ export default function ChatPage() {
|
|||||||
|
|
||||||
const promptPrefixProp = useMemo(() => {
|
const promptPrefixProp = useMemo(() => {
|
||||||
if (!promptPrefixSettings?.enabled) return undefined;
|
if (!promptPrefixSettings?.enabled) return undefined;
|
||||||
|
if (preferencesLoading) return undefined;
|
||||||
|
// Personal opt-out hides the admin prompt-prefix switch entirely.
|
||||||
|
if (hideAdminPrompt) return undefined;
|
||||||
// The prefix toggle is offered only on the opening turn of a new thread.
|
// The prefix toggle is offered only on the opening turn of a new thread.
|
||||||
if (!isNewThread || hasStartedConversation) return undefined;
|
if (!isNewThread || hasStartedConversation) return undefined;
|
||||||
return {
|
return {
|
||||||
@@ -224,7 +265,14 @@ export default function ChatPage() {
|
|||||||
on: promptPrefixOn,
|
on: promptPrefixOn,
|
||||||
onToggle: () => setPromptPrefixOn((v) => !v),
|
onToggle: () => setPromptPrefixOn((v) => !v),
|
||||||
};
|
};
|
||||||
}, [promptPrefixSettings, isNewThread, hasStartedConversation, promptPrefixOn]);
|
}, [
|
||||||
|
promptPrefixSettings,
|
||||||
|
hideAdminPrompt,
|
||||||
|
preferencesLoading,
|
||||||
|
isNewThread,
|
||||||
|
hasStartedConversation,
|
||||||
|
promptPrefixOn,
|
||||||
|
]);
|
||||||
|
|
||||||
const messageListPaddingBottom = showFollowups
|
const messageListPaddingBottom = showFollowups
|
||||||
? MESSAGE_LIST_DEFAULT_PADDING_BOTTOM +
|
? MESSAGE_LIST_DEFAULT_PADDING_BOTTOM +
|
||||||
@@ -325,7 +373,8 @@ export default function ChatPage() {
|
|||||||
context={settings.context}
|
context={settings.context}
|
||||||
disabled={
|
disabled={
|
||||||
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" ||
|
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" ||
|
||||||
isUploading
|
isUploading ||
|
||||||
|
agentHandoffPending
|
||||||
}
|
}
|
||||||
onContextChange={(context) =>
|
onContextChange={(context) =>
|
||||||
setSettings("context", context)
|
setSettings("context", context)
|
||||||
|
|||||||
@@ -0,0 +1,257 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { DatabaseZap, Loader2Icon, RefreshCwIcon } from "lucide-react";
|
||||||
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { apiFetch } from "@/core/api";
|
||||||
|
import { getBackendBaseURL } from "@/core/config";
|
||||||
|
|
||||||
|
interface CheckpointMigrationSources {
|
||||||
|
source_paths: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CheckpointMigrationTask {
|
||||||
|
task_id: string;
|
||||||
|
status: "queued" | "running" | "completed" | "failed";
|
||||||
|
start_at: string;
|
||||||
|
end_at: string;
|
||||||
|
source_paths: string[];
|
||||||
|
total_threads: number;
|
||||||
|
copied_threads: number;
|
||||||
|
skipped_threads: number;
|
||||||
|
failed_threads: number;
|
||||||
|
skipped_ranges: number;
|
||||||
|
message: string;
|
||||||
|
error?: string | null;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSources(): Promise<CheckpointMigrationSources> {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/admin/checkpoint-migration/sources`,
|
||||||
|
);
|
||||||
|
if (!response.ok) throw new Error("加载 SQLite 来源失败");
|
||||||
|
return (await response.json()) as CheckpointMigrationSources;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startMigration(body: {
|
||||||
|
start_at: string;
|
||||||
|
end_at: string;
|
||||||
|
}): Promise<CheckpointMigrationTask> {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/admin/checkpoint-migration/tasks`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
const detail = await response.json().catch(() => ({ detail: "启动迁移失败" }));
|
||||||
|
throw new Error(detail.detail ?? "启动迁移失败");
|
||||||
|
}
|
||||||
|
return (await response.json()) as CheckpointMigrationTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTask(taskId: string): Promise<CheckpointMigrationTask> {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`${getBackendBaseURL()}/api/admin/checkpoint-migration/tasks/${taskId}`,
|
||||||
|
);
|
||||||
|
if (!response.ok) throw new Error("加载迁移任务失败");
|
||||||
|
return (await response.json()) as CheckpointMigrationTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toLocalInputValue(date: Date): string {
|
||||||
|
const pad = (n: number) => String(n).padStart(2, "0");
|
||||||
|
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusVariant(status?: string) {
|
||||||
|
if (status === "failed") return "destructive" as const;
|
||||||
|
if (status === "completed") return "default" as const;
|
||||||
|
if (status === "queued" || status === "running") return "secondary" as const;
|
||||||
|
return "outline" as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function CheckpointMigrationPage() {
|
||||||
|
const now = useMemo(() => new Date(), []);
|
||||||
|
const weekAgo = useMemo(
|
||||||
|
() => new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000),
|
||||||
|
[now],
|
||||||
|
);
|
||||||
|
const [startAt, setStartAt] = useState(toLocalInputValue(weekAgo));
|
||||||
|
const [endAt, setEndAt] = useState(toLocalInputValue(now));
|
||||||
|
const [taskId, setTaskId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const { data: sources, isLoading: sourcesLoading, refetch } = useQuery({
|
||||||
|
queryKey: ["checkpointMigration", "sources"],
|
||||||
|
queryFn: loadSources,
|
||||||
|
staleTime: 60_000,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
});
|
||||||
|
const startMutation = useMutation({ mutationFn: startMigration });
|
||||||
|
const { data: task } = useQuery({
|
||||||
|
queryKey: ["checkpointMigration", "task", taskId],
|
||||||
|
queryFn: () => loadTask(taskId as string),
|
||||||
|
enabled: !!taskId,
|
||||||
|
refetchInterval: (query) => {
|
||||||
|
const status = query.state.data?.status;
|
||||||
|
return status === "queued" || status === "running" ? 2000 : false;
|
||||||
|
},
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const running =
|
||||||
|
startMutation.isPending ||
|
||||||
|
task?.status === "queued" ||
|
||||||
|
task?.status === "running";
|
||||||
|
|
||||||
|
async function handleStart() {
|
||||||
|
const start = new Date(startAt);
|
||||||
|
const end = new Date(endAt);
|
||||||
|
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
|
||||||
|
toast.error("请选择有效的开始和结束时间");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (end <= start) {
|
||||||
|
toast.error("结束时间必须晚于开始时间");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const created = await startMutation.mutateAsync({
|
||||||
|
start_at: start.toISOString(),
|
||||||
|
end_at: end.toISOString(),
|
||||||
|
});
|
||||||
|
setTaskId(created.task_id);
|
||||||
|
toast.success("迁移任务已启动");
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "启动迁移失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex w-full max-w-3xl flex-col gap-6 px-6 py-10">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-xl font-semibold">Checkpoint 迁移</h1>
|
||||||
|
<p className="text-muted-foreground mt-1 text-sm">
|
||||||
|
按时间段把 SQLite 旧聊天 checkpoint 同步到 Postgres。同一来源、同一时间段完成后再次执行会跳过。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section className="rounded-lg border bg-white p-5 dark:border-[#213D5E] dark:bg-[#02244C]">
|
||||||
|
<div className="mb-4 flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2 text-sm font-medium">
|
||||||
|
<DatabaseZap className="size-4" />
|
||||||
|
SQLite 来源
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => refetch()}
|
||||||
|
disabled={sourcesLoading}
|
||||||
|
title="刷新"
|
||||||
|
>
|
||||||
|
<RefreshCwIcon className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{sourcesLoading ? (
|
||||||
|
<div className="text-muted-foreground flex items-center gap-2 text-sm">
|
||||||
|
<Loader2Icon className="size-4 animate-spin" />
|
||||||
|
加载中
|
||||||
|
</div>
|
||||||
|
) : (sources?.source_paths.length ?? 0) > 0 ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{sources?.source_paths.map((path) => (
|
||||||
|
<div
|
||||||
|
key={path}
|
||||||
|
className="rounded border bg-muted/40 px-3 py-2 font-mono text-xs break-all"
|
||||||
|
>
|
||||||
|
{path}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-muted-foreground rounded border border-dashed px-3 py-6 text-center text-sm">
|
||||||
|
未配置 SQLite 来源路径
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="rounded-lg border bg-white p-5 dark:border-[#213D5E] dark:bg-[#02244C]">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<label className="flex flex-col gap-1.5 text-sm">
|
||||||
|
<span className="font-medium">开始时间</span>
|
||||||
|
<Input
|
||||||
|
type="datetime-local"
|
||||||
|
value={startAt}
|
||||||
|
onChange={(e) => setStartAt(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="flex flex-col gap-1.5 text-sm">
|
||||||
|
<span className="font-medium">结束时间</span>
|
||||||
|
<Input
|
||||||
|
type="datetime-local"
|
||||||
|
value={endAt}
|
||||||
|
onChange={(e) => setEndAt(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="mt-5 flex justify-end">
|
||||||
|
<Button
|
||||||
|
onClick={handleStart}
|
||||||
|
disabled={running || !(sources?.source_paths.length ?? 0)}
|
||||||
|
>
|
||||||
|
{running && <Loader2Icon className="size-4 animate-spin" />}
|
||||||
|
开始同步
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{task && (
|
||||||
|
<section className="rounded-lg border bg-white p-5 dark:border-[#213D5E] dark:bg-[#02244C]">
|
||||||
|
<div className="mb-4 flex items-center justify-between">
|
||||||
|
<div className="text-sm font-medium">任务状态</div>
|
||||||
|
<Badge variant={statusVariant(task.status)}>{task.status}</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-3 text-sm sm:grid-cols-4">
|
||||||
|
<div className="rounded border p-3">
|
||||||
|
<div className="text-muted-foreground text-xs">总线程</div>
|
||||||
|
<div className="mt-1 text-lg font-semibold tabular-nums">
|
||||||
|
{task.total_threads}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded border p-3">
|
||||||
|
<div className="text-muted-foreground text-xs">已复制</div>
|
||||||
|
<div className="mt-1 text-lg font-semibold tabular-nums">
|
||||||
|
{task.copied_threads}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded border p-3">
|
||||||
|
<div className="text-muted-foreground text-xs">已跳过</div>
|
||||||
|
<div className="mt-1 text-lg font-semibold tabular-nums">
|
||||||
|
{task.skipped_threads}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded border p-3">
|
||||||
|
<div className="text-muted-foreground text-xs">跳过时间段</div>
|
||||||
|
<div className="mt-1 text-lg font-semibold tabular-nums">
|
||||||
|
{task.skipped_ranges}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{(task.message || task.error) && (
|
||||||
|
<div className="mt-4 rounded border bg-muted/40 px-3 py-2 text-sm">
|
||||||
|
{task.error || task.message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
} from "@/components/workspace/messages";
|
} from "@/components/workspace/messages";
|
||||||
import { ThreadContext } from "@/components/workspace/messages/context";
|
import { ThreadContext } from "@/components/workspace/messages/context";
|
||||||
import { TodoList } from "@/components/workspace/todo-list";
|
import { TodoList } from "@/components/workspace/todo-list";
|
||||||
|
import { getAccessToken } from "@/core/auth";
|
||||||
import { useI18n } from "@/core/i18n/hooks";
|
import { useI18n } from "@/core/i18n/hooks";
|
||||||
import { useModels } from "@/core/models/hooks";
|
import { useModels } from "@/core/models/hooks";
|
||||||
import { useNotification } from "@/core/notification/hooks";
|
import { useNotification } from "@/core/notification/hooks";
|
||||||
@@ -33,6 +34,13 @@ import {
|
|||||||
} from "./iframe-chat-submit";
|
} from "./iframe-chat-submit";
|
||||||
|
|
||||||
type BrainyChatStatus = "started" | "finished";
|
type BrainyChatStatus = "started" | "finished";
|
||||||
|
type BrainyAuthTokenMessage = {
|
||||||
|
source: "brainy-iframe";
|
||||||
|
type: "brainy:auth-token";
|
||||||
|
payload: {
|
||||||
|
accessToken: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
type BrainyChatInterruptMessage = {
|
type BrainyChatInterruptMessage = {
|
||||||
source?: string;
|
source?: string;
|
||||||
type?: string;
|
type?: string;
|
||||||
@@ -57,6 +65,18 @@ function postBrainyChatStatus(status: BrainyChatStatus, requestId: string) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function postBrainyAuthToken(accessToken: string) {
|
||||||
|
const message: BrainyAuthTokenMessage = {
|
||||||
|
source: "brainy-iframe",
|
||||||
|
type: "brainy:auth-token",
|
||||||
|
payload: {
|
||||||
|
accessToken,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
window.parent?.postMessage(message, "*");
|
||||||
|
}
|
||||||
|
|
||||||
export default function IframeChatPage() {
|
export default function IframeChatPage() {
|
||||||
const routeBase = useRouteBase();
|
const routeBase = useRouteBase();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -79,6 +99,28 @@ export default function IframeChatPage() {
|
|||||||
setMounted(true);
|
setMounted(true);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let lastToken: string | undefined;
|
||||||
|
|
||||||
|
const emitAccessToken = () => {
|
||||||
|
const accessToken = getAccessToken();
|
||||||
|
if (!accessToken || accessToken === lastToken) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lastToken = accessToken;
|
||||||
|
postBrainyAuthToken(accessToken);
|
||||||
|
};
|
||||||
|
|
||||||
|
emitAccessToken();
|
||||||
|
window.addEventListener("focus", emitAccessToken);
|
||||||
|
window.addEventListener("storage", emitAccessToken);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("focus", emitAccessToken);
|
||||||
|
window.removeEventListener("storage", emitAccessToken);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isNewThread) {
|
if (isNewThread) {
|
||||||
setHasStartedConversation(false);
|
setHasStartedConversation(false);
|
||||||
|
|||||||
@@ -310,7 +310,7 @@ const errorToastDarkOptions = {
|
|||||||
<label className="text-muted-foreground text-xs dark:text-white">用户名</label>
|
<label className="text-muted-foreground text-xs dark:text-white">用户名</label>
|
||||||
<Input
|
<Input
|
||||||
value={user}
|
value={user}
|
||||||
placeholder="按用户名匹配(@ 前部分)"
|
placeholder="按用户名模糊搜索(@ 前部分)"
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setUser(e.target.value);
|
setUser(e.target.value);
|
||||||
setPage(0);
|
setPage(0);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ArrowLeftIcon,
|
ArrowLeftIcon,
|
||||||
@@ -19,6 +19,11 @@ import {
|
|||||||
} from "@/components/ai-elements/prompt-input";
|
} from "@/components/ai-elements/prompt-input";
|
||||||
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 {
|
||||||
|
ResizableHandle,
|
||||||
|
ResizablePanel,
|
||||||
|
ResizablePanelGroup,
|
||||||
|
} from "@/components/ui/resizable";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -361,8 +366,19 @@ export default function NewAgentPage() {
|
|||||||
) : null}
|
) : null}
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main className="grid min-h-0 flex-1 grid-cols-1 md:grid-cols-[minmax(0,1fr)_420px]">
|
<ResizablePanelGroup
|
||||||
<section className="flex min-h-0 flex-col border-r">
|
id="new-agent-config-panels"
|
||||||
|
orientation="horizontal"
|
||||||
|
defaultLayout={{ chat: 62, config: 38 }}
|
||||||
|
className="min-h-0 flex-1"
|
||||||
|
>
|
||||||
|
<ResizablePanel
|
||||||
|
id="chat"
|
||||||
|
defaultSize={62}
|
||||||
|
minSize={40}
|
||||||
|
className="min-h-0"
|
||||||
|
>
|
||||||
|
<section className="flex size-full min-h-0 flex-col">
|
||||||
<div className="min-h-0 flex-1">
|
<div className="min-h-0 flex-1">
|
||||||
<MessageList
|
<MessageList
|
||||||
className="size-full"
|
className="size-full"
|
||||||
@@ -428,8 +444,18 @@ export default function NewAgentPage() {
|
|||||||
</PromptInput>
|
</PromptInput>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
</ResizablePanel>
|
||||||
|
|
||||||
<aside className="bg-background min-h-0 overflow-y-auto">
|
<ResizableHandle withHandle />
|
||||||
|
|
||||||
|
<ResizablePanel
|
||||||
|
id="config"
|
||||||
|
defaultSize={38}
|
||||||
|
minSize={24}
|
||||||
|
maxSize={60}
|
||||||
|
className="min-h-0"
|
||||||
|
>
|
||||||
|
<aside className="bg-background size-full min-h-0 overflow-y-auto">
|
||||||
<div className="space-y-5 p-4">
|
<div className="space-y-5 p-4">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-sm font-semibold">智能体配置</h2>
|
<h2 className="text-sm font-semibold">智能体配置</h2>
|
||||||
@@ -606,7 +632,8 @@ export default function NewAgentPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
</main>
|
</ResizablePanel>
|
||||||
|
</ResizablePanelGroup>
|
||||||
</div>
|
</div>
|
||||||
</ArtifactsProvider>
|
</ArtifactsProvider>
|
||||||
</ThreadContext.Provider>
|
</ThreadContext.Provider>
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
BarChart3,
|
||||||
|
CheckCircle,
|
||||||
|
ChevronDown,
|
||||||
|
ChevronRight,
|
||||||
|
ExternalLink,
|
||||||
|
FileText,
|
||||||
|
Loader2,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import ReactMarkdown from "react-markdown";
|
||||||
|
import { useParams } from "react-router-dom";
|
||||||
|
import remarkGfm from "remark-gfm";
|
||||||
|
|
||||||
|
import {
|
||||||
|
getPublicDraftShareSnapshot,
|
||||||
|
type PublicDraftSeatDelivery,
|
||||||
|
} from "@/core/roundtable-draft-shares/api";
|
||||||
|
import { markdownComponents } from "@/roundtable-planning/components/markdown-components";
|
||||||
|
|
||||||
|
/** 各席位最终交付 —— 折叠手风琴(仿 HighFidelityReport 第二区块)。 */
|
||||||
|
function SeatDeliveries({ seats }: { seats: PublicDraftSeatDelivery[] }) {
|
||||||
|
const [expanded, setExpanded] = useState<Set<number>>(() => new Set());
|
||||||
|
const toggle = (i: number) =>
|
||||||
|
setExpanded((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (next.has(i)) next.delete(i);
|
||||||
|
else next.add(i);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (seats.length === 0) {
|
||||||
|
return (
|
||||||
|
<p className="text-[11px] text-slate-400 italic">本次会商暂无子智能体交付。</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{seats.map((seat, idx) => {
|
||||||
|
const open = expanded.has(idx);
|
||||||
|
return (
|
||||||
|
<div key={`${seat.sender}-${idx}`} className="border border-slate-200 rounded-xl overflow-hidden">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => toggle(idx)}
|
||||||
|
className="w-full flex items-center justify-between gap-2 px-3 py-2.5 bg-slate-50 hover:bg-slate-100 transition text-left"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
|
{open ? (
|
||||||
|
<ChevronDown className="w-3.5 h-3.5 text-slate-500 shrink-0" />
|
||||||
|
) : (
|
||||||
|
<ChevronRight className="w-3.5 h-3.5 text-slate-500 shrink-0" />
|
||||||
|
)}
|
||||||
|
<span className="text-[11.5px] font-bold text-slate-800 truncate">
|
||||||
|
{seat.sender || "未命名席位"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-[10px] text-slate-400 font-mono shrink-0">
|
||||||
|
{seat.content.length} 字
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
{open && (
|
||||||
|
<div className="px-4 py-3 text-xs text-slate-700 leading-relaxed border-t border-slate-100 bg-white">
|
||||||
|
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||||
|
{seat.content || "(空)"}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public, read-only roundtable-result viewer.
|
||||||
|
*
|
||||||
|
* Reachable at `#/roundtable-share/<code>` with NO authentication — anyone with
|
||||||
|
* the link can open it. Two views, driven by the `report` prop / route:
|
||||||
|
*
|
||||||
|
* - landing (`#/roundtable-share/<code>`): a read-only result page mirroring the
|
||||||
|
* in-app Step 3「最终方案展示」— 总控最终结论 + 各席位最终交付 + a 「查看结果绘制」
|
||||||
|
* button that opens the full report in a NEW TAB (when one was generated).
|
||||||
|
* - report (`#/roundtable-share/<code>/report`): the Step 3 report (a
|
||||||
|
* self-contained HTML document) rendered full-screen inside a sandboxed
|
||||||
|
* `iframe` (no `allow-scripts`), so the agent-generated HTML can never execute
|
||||||
|
* code in the app origin.
|
||||||
|
*/
|
||||||
|
export default function PublicRoundtableSharePage({
|
||||||
|
report = false,
|
||||||
|
}: {
|
||||||
|
report?: boolean;
|
||||||
|
}) {
|
||||||
|
const { shareCode } = useParams<{ shareCode: string }>();
|
||||||
|
|
||||||
|
const { data, isLoading, isError } = useQuery({
|
||||||
|
queryKey: ["public-roundtable-share", shareCode],
|
||||||
|
queryFn: () => getPublicDraftShareSnapshot(shareCode!),
|
||||||
|
enabled: !!shareCode,
|
||||||
|
retry: false,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="bg-background text-muted-foreground flex h-screen items-center justify-center gap-2 text-sm">
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
正在加载分享内容…
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isError || !data) {
|
||||||
|
return (
|
||||||
|
<div className="bg-background flex h-screen flex-col items-center justify-center gap-2 px-6 text-center">
|
||||||
|
<p className="text-lg font-medium">分享不可用</p>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
该分享链接不存在、已被撤销,或不是只读分享。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 报告页:整页沙箱 iframe 展示第 3 步结果绘制 ──────────────────────────────
|
||||||
|
if (report) {
|
||||||
|
return (
|
||||||
|
<div className="bg-background flex h-screen flex-col">
|
||||||
|
<header className="flex shrink-0 items-center gap-2 border-b px-6 py-3">
|
||||||
|
<h1 className="truncate text-base font-semibold">
|
||||||
|
{data.title || "未命名会商"}
|
||||||
|
</h1>
|
||||||
|
<span className="bg-muted text-muted-foreground shrink-0 rounded-full px-2 py-0.5 text-xs">
|
||||||
|
结果绘制 · 只读
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
<main className="min-h-0 flex-1">
|
||||||
|
{data.has_report ? (
|
||||||
|
<iframe
|
||||||
|
// No `allow-scripts` — the report is self-contained (inline CSS +
|
||||||
|
// inline SVG charts) and must never run as a script in the app origin.
|
||||||
|
sandbox=""
|
||||||
|
title={data.title || "会商结果报告"}
|
||||||
|
srcDoc={data.html}
|
||||||
|
className="size-full border-0 bg-white"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="text-muted-foreground flex h-full flex-col items-center justify-center gap-2 px-6 text-center text-sm">
|
||||||
|
<p className="text-base font-medium text-foreground">暂无结果报告</p>
|
||||||
|
<p>这次会商还没有生成第三步「结果绘制」的方案报告。</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 落地页:总控最终结论 + 各席位最终交付 + 查看结果绘制(新标签打开报告页)─────
|
||||||
|
const reportUrl = `${window.location.origin}${window.location.pathname}#/roundtable-share/${shareCode}/report`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-[#fef6f6] flex h-screen flex-col text-slate-800">
|
||||||
|
<header className="flex shrink-0 flex-col gap-1 border-b border-slate-100 bg-white px-6 py-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<h1 className="truncate text-base font-semibold">
|
||||||
|
{data.title || "未命名会商"}
|
||||||
|
</h1>
|
||||||
|
<span className="bg-slate-100 text-slate-500 shrink-0 rounded-full px-2 py-0.5 text-xs">
|
||||||
|
只读分享
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-slate-400 text-xs">
|
||||||
|
这是一份多智能体会商的结果分享(只读)。
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main className="min-h-0 flex-1 overflow-y-auto">
|
||||||
|
<div className="mx-auto w-full max-w-6xl space-y-6 p-6">
|
||||||
|
{/* 1. 结果绘制 —— 新标签打开报告页 */}
|
||||||
|
<section className="bg-white border border-slate-200 rounded-2xl p-5 shadow-[0_2px_8px_rgba(0,0,0,0.02)]">
|
||||||
|
<h4 className="text-xs font-black text-slate-900 uppercase tracking-widest mb-3 flex items-center gap-2">
|
||||||
|
<BarChart3 className="w-4 h-4 text-primary" />
|
||||||
|
结果绘制
|
||||||
|
</h4>
|
||||||
|
{data.has_report ? (
|
||||||
|
<a
|
||||||
|
href={reportUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="bg-primary text-white hover:bg-[var(--brand-900)] inline-flex items-center gap-2 rounded-xl px-5 py-2.5 text-sm font-semibold transition shadow-sm shadow-primary/10"
|
||||||
|
>
|
||||||
|
<BarChart3 className="size-4" />
|
||||||
|
查看结果绘制
|
||||||
|
<ExternalLink className="size-3.5 opacity-80" />
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<p className="text-[11px] text-slate-400 italic">
|
||||||
|
这次会商还没有生成第三步「结果绘制」的方案报告。
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* 2. 总控最终结论 */}
|
||||||
|
<section className="bg-white border border-slate-200 rounded-2xl p-5 shadow-[0_2px_8px_rgba(0,0,0,0.02)]">
|
||||||
|
<h4 className="text-xs font-black text-slate-900 uppercase tracking-widest mb-3 flex items-center gap-2">
|
||||||
|
<CheckCircle className="w-4 h-4 text-emerald-500 shrink-0" />
|
||||||
|
总控最终结论
|
||||||
|
</h4>
|
||||||
|
{data.consensus_text ? (
|
||||||
|
<div className="text-xs text-slate-700 leading-relaxed">
|
||||||
|
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||||
|
{data.consensus_text}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-[11px] text-slate-400 italic">暂无总控结论。</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* 3. 各席位最终交付 */}
|
||||||
|
<section className="bg-white border border-slate-200 rounded-2xl p-5 shadow-[0_2px_8px_rgba(0,0,0,0.02)]">
|
||||||
|
<h4 className="text-xs font-black text-slate-900 uppercase tracking-widest mb-3 flex items-center gap-2">
|
||||||
|
<FileText className="w-4 h-4 text-primary" />
|
||||||
|
各席位最终交付
|
||||||
|
<span className="text-[10px] font-mono font-semibold text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded">
|
||||||
|
{data.seat_deliveries.length}
|
||||||
|
</span>
|
||||||
|
</h4>
|
||||||
|
<SeatDeliveries seats={data.seat_deliveries} />
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,14 +3,18 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
Check,
|
Check,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
Download,
|
Download,
|
||||||
FileText,
|
FileText,
|
||||||
|
List,
|
||||||
Loader2,
|
Loader2,
|
||||||
Pencil,
|
Pencil,
|
||||||
Trash2,
|
Trash2,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import type { PointerEvent as ReactPointerEvent } from "react";
|
||||||
import { useParams } from "react-router-dom";
|
import { useParams } from "react-router-dom";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
@@ -35,6 +39,7 @@ import {
|
|||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from "@/components/ui/tooltip";
|
} from "@/components/ui/tooltip";
|
||||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||||
|
import { HtmlPreviewFrame } from "@/components/html-preview-frame";
|
||||||
import { getBackendBaseURL } from "@/core/config";
|
import { getBackendBaseURL } from "@/core/config";
|
||||||
import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx";
|
import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx";
|
||||||
import { reasoningPlugins } from "@/core/streamdown";
|
import { reasoningPlugins } from "@/core/streamdown";
|
||||||
@@ -253,6 +258,11 @@ function stripTimestampSuffix(title: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const BODY_TAB_VALUE = "__body__";
|
const BODY_TAB_VALUE = "__body__";
|
||||||
|
const HTML_TAB_VALUE = "__html__";
|
||||||
|
const RUN_LIST_COLLAPSED_WIDTH = 56;
|
||||||
|
const RUN_LIST_DEFAULT_WIDTH = 380;
|
||||||
|
const RUN_LIST_MIN_WIDTH = 280;
|
||||||
|
const RUN_LIST_MAX_WIDTH = 560;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Public, unauthenticated scheduled-task viewer.
|
* Public, unauthenticated scheduled-task viewer.
|
||||||
@@ -269,6 +279,9 @@ export default function PublicScheduledTaskPage() {
|
|||||||
const { taskId } = useParams<{ taskId: string }>();
|
const { taskId } = useParams<{ taskId: string }>();
|
||||||
const [selectedRunId, setSelectedRunId] = useState<string | null>(null);
|
const [selectedRunId, setSelectedRunId] = useState<string | null>(null);
|
||||||
const [pendingDeleteRun, setPendingDeleteRun] = useState<{ id: string; title: string } | null>(null);
|
const [pendingDeleteRun, setPendingDeleteRun] = useState<{ id: string; title: string } | null>(null);
|
||||||
|
const [runListExpanded, setRunListExpanded] = useState(false);
|
||||||
|
const [runListWidth, setRunListWidth] = useState(RUN_LIST_DEFAULT_WIDTH);
|
||||||
|
const dragStateRef = useRef<{ startX: number; startWidth: number } | null>(null);
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const { data, isLoading, isError, error } = useQuery({
|
const { data, isLoading, isError, error } = useQuery({
|
||||||
@@ -332,6 +345,58 @@ export default function PublicScheduledTaskPage() {
|
|||||||
}
|
}
|
||||||
}, [runs, selectedRunId]);
|
}, [runs, selectedRunId]);
|
||||||
|
|
||||||
|
const task = data?.task;
|
||||||
|
const visibleRunListWidth = runListExpanded ? runListWidth : RUN_LIST_COLLAPSED_WIDTH;
|
||||||
|
|
||||||
|
const expandRunList = useCallback(() => {
|
||||||
|
setRunListExpanded(true);
|
||||||
|
setRunListWidth((width) =>
|
||||||
|
Math.min(RUN_LIST_MAX_WIDTH, Math.max(RUN_LIST_MIN_WIDTH, width)),
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const collapseRunList = useCallback(() => {
|
||||||
|
setRunListExpanded(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleRunListDragStart = useCallback(
|
||||||
|
(event: ReactPointerEvent<HTMLDivElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
dragStateRef.current = {
|
||||||
|
startX: event.clientX,
|
||||||
|
startWidth: visibleRunListWidth,
|
||||||
|
};
|
||||||
|
document.body.style.cursor = "col-resize";
|
||||||
|
document.body.style.userSelect = "none";
|
||||||
|
|
||||||
|
const handlePointerMove = (moveEvent: PointerEvent) => {
|
||||||
|
const drag = dragStateRef.current;
|
||||||
|
if (!drag) return;
|
||||||
|
const nextWidth = drag.startWidth + moveEvent.clientX - drag.startX;
|
||||||
|
if (nextWidth <= RUN_LIST_COLLAPSED_WIDTH + 28) {
|
||||||
|
setRunListExpanded(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setRunListExpanded(true);
|
||||||
|
setRunListWidth(
|
||||||
|
Math.min(RUN_LIST_MAX_WIDTH, Math.max(RUN_LIST_MIN_WIDTH, nextWidth)),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePointerUp = () => {
|
||||||
|
dragStateRef.current = null;
|
||||||
|
document.body.style.cursor = "";
|
||||||
|
document.body.style.userSelect = "";
|
||||||
|
window.removeEventListener("pointermove", handlePointerMove);
|
||||||
|
window.removeEventListener("pointerup", handlePointerUp);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("pointermove", handlePointerMove);
|
||||||
|
window.addEventListener("pointerup", handlePointerUp);
|
||||||
|
},
|
||||||
|
[visibleRunListWidth],
|
||||||
|
);
|
||||||
|
|
||||||
if (!taskId) {
|
if (!taskId) {
|
||||||
return (
|
return (
|
||||||
<div className="text-muted-foreground flex h-screen items-center justify-center text-sm">
|
<div className="text-muted-foreground flex h-screen items-center justify-center text-sm">
|
||||||
@@ -357,12 +422,15 @@ export default function PublicScheduledTaskPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const task = data?.task;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TooltipProvider delayDuration={150}>
|
<TooltipProvider delayDuration={150}>
|
||||||
<div className="bg-muted/20 grid h-screen min-h-0 grid-cols-1 gap-4 p-4 xl:grid-cols-[380px_minmax(0,1fr)]">
|
<div className="bg-muted/20 flex h-screen min-h-0 overflow-hidden p-4">
|
||||||
<Card className="flex min-h-0 flex-col">
|
<div
|
||||||
|
className="relative flex min-h-0 shrink-0 transition-[width] duration-200 ease-out"
|
||||||
|
style={{ width: visibleRunListWidth }}
|
||||||
|
>
|
||||||
|
{runListExpanded ? (
|
||||||
|
<Card className="flex min-h-0 w-full flex-col overflow-hidden">
|
||||||
<CardHeader className="gap-1">
|
<CardHeader className="gap-1">
|
||||||
<div className="flex items-start justify-between gap-2">
|
<div className="flex items-start justify-between gap-2">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
@@ -377,9 +445,21 @@ export default function PublicScheduledTaskPage() {
|
|||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
)}
|
)}
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<Badge variant={task?.enabled ? "default" : "secondary"} className="shrink-0">
|
<div className="flex shrink-0 items-center gap-1">
|
||||||
{task?.enabled ? "启用" : "暂停"}
|
<Badge variant={task?.enabled ? "default" : "secondary"}>
|
||||||
</Badge>
|
{task?.enabled ? "启用" : "暂停"}
|
||||||
|
</Badge>
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="text-muted-foreground hover:text-primary size-7"
|
||||||
|
onClick={collapseRunList}
|
||||||
|
title="收起执行记录列表"
|
||||||
|
aria-label="收起执行记录列表"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{task?.description && task.description.trim() && (
|
{task?.description && task.description.trim() && (
|
||||||
<p className="text-muted-foreground line-clamp-3 text-xs leading-relaxed break-all whitespace-pre-wrap">
|
<p className="text-muted-foreground line-clamp-3 text-xs leading-relaxed break-all whitespace-pre-wrap">
|
||||||
@@ -481,9 +561,36 @@ export default function PublicScheduledTaskPage() {
|
|||||||
</div>
|
</div>
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
) : (
|
||||||
|
<Card className="flex min-h-0 w-full flex-col items-center overflow-hidden py-3">
|
||||||
|
<Button
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="text-muted-foreground hover:text-primary"
|
||||||
|
onClick={expandRunList}
|
||||||
|
title="展开执行记录列表"
|
||||||
|
aria-label="展开执行记录列表"
|
||||||
|
>
|
||||||
|
<List className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
<div
|
||||||
|
role="separator"
|
||||||
|
aria-orientation="vertical"
|
||||||
|
title="拖拽调整列表宽度"
|
||||||
|
className="group absolute top-0 -right-3 z-20 flex h-full w-6 cursor-col-resize items-center justify-center"
|
||||||
|
onPointerDown={handleRunListDragStart}
|
||||||
|
>
|
||||||
|
<div className="bg-border group-hover:bg-primary/70 h-full w-px transition-colors" />
|
||||||
|
<div className="bg-background text-muted-foreground group-hover:text-primary absolute top-1/2 flex size-5 -translate-y-1/2 items-center justify-center rounded-full border shadow-sm transition-colors">
|
||||||
|
<ChevronRight className="size-3" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Card className="flex min-h-0 flex-col">
|
<Card className="ml-4 flex min-h-0 flex-1 flex-col">
|
||||||
{selectedRun ? (
|
{selectedRun ? (
|
||||||
<RunDetailPane key={selectedRun.id} run={selectedRun} taskId={taskId} />
|
<RunDetailPane key={selectedRun.id} run={selectedRun} taskId={taskId} />
|
||||||
) : (
|
) : (
|
||||||
@@ -546,12 +653,14 @@ export default function PublicScheduledTaskPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ContentTab = {
|
type ContentTab = {
|
||||||
/** Stable tab identifier — `__body__` for inline content, `file-<index>` for files. */
|
/** Stable tab identifier — `__html__` for the HTML preview, `__body__` for
|
||||||
|
* inline content, `file-<index>` for files. */
|
||||||
value: string;
|
value: string;
|
||||||
/** Short label rendered in the TabsTrigger. */
|
/** Short label rendered in the TabsTrigger. */
|
||||||
label: string;
|
label: string;
|
||||||
/** Distinguishes body vs MD attachment so the editor knows which PUT to call. */
|
/** Distinguishes the HTML preview vs body vs MD attachment so the renderer /
|
||||||
kind: "body" | "file";
|
* editor knows what to show and which PUT to call. */
|
||||||
|
kind: "body" | "file" | "html";
|
||||||
/** File index (when `kind === "file"`). */
|
/** File index (when `kind === "file"`). */
|
||||||
fileIndex?: number;
|
fileIndex?: number;
|
||||||
/** Filename for downloads (defaults to the run title for body). */
|
/** Filename for downloads (defaults to the run title for body). */
|
||||||
@@ -592,17 +701,27 @@ function RunDetailPane({ run, taskId }: { run: PublicRun; taskId: string }) {
|
|||||||
[run.result?.files],
|
[run.result?.files],
|
||||||
);
|
);
|
||||||
|
|
||||||
// Tabs: every MD file first (priority per spec), then the inline body.
|
// Tabs: HTML preview first (when present), then every MD file, then the
|
||||||
|
// inline body. For an HTML run that also produced a Markdown file, this keeps
|
||||||
|
// the page preview AND surfaces the .md instead of hiding it. The generated
|
||||||
|
// HTML document itself is never listed as a downloadable "file" tab — it has
|
||||||
|
// its own preview.
|
||||||
const tabs: ContentTab[] = useMemo(() => {
|
const tabs: ContentTab[] = useMemo(() => {
|
||||||
const list: ContentTab[] = markdownFiles.map((file, idx) => ({
|
const list: ContentTab[] = [];
|
||||||
value: `file-${file.index}`,
|
if (isHtmlRun) {
|
||||||
// Show the actual filename without the `.md` suffix — the user explicitly
|
list.push({ value: HTML_TAB_VALUE, label: "HTML 预览", kind: "html" });
|
||||||
// asked for "no '文件' label, just the name without extension".
|
}
|
||||||
label: stripExtension(file.name) || `文件 ${idx + 1}`,
|
list.push(
|
||||||
kind: "file",
|
...markdownFiles.map((file, idx) => ({
|
||||||
fileIndex: file.index,
|
value: `file-${file.index}`,
|
||||||
fileName: file.name,
|
// Show the actual filename without the `.md` suffix — the user explicitly
|
||||||
}));
|
// asked for "no '文件' label, just the name without extension".
|
||||||
|
label: stripExtension(file.name) || `文件 ${idx + 1}`,
|
||||||
|
kind: "file" as const,
|
||||||
|
fileIndex: file.index,
|
||||||
|
fileName: file.name,
|
||||||
|
})),
|
||||||
|
);
|
||||||
list.push({
|
list.push({
|
||||||
value: BODY_TAB_VALUE,
|
value: BODY_TAB_VALUE,
|
||||||
label: "正文",
|
label: "正文",
|
||||||
@@ -610,7 +729,7 @@ function RunDetailPane({ run, taskId }: { run: PublicRun; taskId: string }) {
|
|||||||
fileName: run.result?.title || "scheduled-task-result",
|
fileName: run.result?.title || "scheduled-task-result",
|
||||||
});
|
});
|
||||||
return list;
|
return list;
|
||||||
}, [markdownFiles, run.result?.title]);
|
}, [isHtmlRun, markdownFiles, run.result?.title]);
|
||||||
|
|
||||||
const [activeTab, setActiveTab] = useState<string>(tabs[0]?.value ?? BODY_TAB_VALUE);
|
const [activeTab, setActiveTab] = useState<string>(tabs[0]?.value ?? BODY_TAB_VALUE);
|
||||||
|
|
||||||
@@ -751,13 +870,13 @@ function RunDetailPane({ run, taskId }: { run: PublicRun; taskId: string }) {
|
|||||||
下载原文件
|
下载原文件
|
||||||
</a>
|
</a>
|
||||||
)}
|
)}
|
||||||
{!isHtmlRun && (
|
{activeTabMeta?.kind !== "html" && (
|
||||||
<Button size="sm" variant="outline" onClick={handleDownloadWord}>
|
<Button size="sm" variant="outline" onClick={handleDownloadWord}>
|
||||||
<FileText className="size-4" />
|
<FileText className="size-4" />
|
||||||
下载 Word
|
下载 Word
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{!isHtmlRun &&
|
{activeTabMeta?.kind !== "html" &&
|
||||||
(isEditing ? (
|
(isEditing ? (
|
||||||
<>
|
<>
|
||||||
<Button
|
<Button
|
||||||
@@ -803,22 +922,7 @@ function RunDetailPane({ run, taskId }: { run: PublicRun; taskId: string }) {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent className="min-h-0 flex-1 overflow-hidden p-0">
|
<CardContent className="min-h-0 flex-1 overflow-hidden p-0">
|
||||||
{isHtmlRun ? (
|
{tabs.length === 0 ? (
|
||||||
<div className="h-full p-4">
|
|
||||||
{htmlContent ? (
|
|
||||||
<iframe
|
|
||||||
title="HTML 预览"
|
|
||||||
sandbox="allow-same-origin"
|
|
||||||
srcDoc={htmlContent}
|
|
||||||
className="h-full min-h-[60vh] w-full rounded-md border bg-white"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<div className="text-muted-foreground rounded-md border p-3 text-sm">
|
|
||||||
HTML 页面尚未生成或正在生成中。
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : tabs.length === 0 ? (
|
|
||||||
<div className="text-muted-foreground p-6 text-sm">无可用内容。</div>
|
<div className="text-muted-foreground p-6 text-sm">无可用内容。</div>
|
||||||
) : (
|
) : (
|
||||||
<Tabs
|
<Tabs
|
||||||
@@ -848,7 +952,18 @@ function RunDetailPane({ run, taskId }: { run: PublicRun; taskId: string }) {
|
|||||||
{run.error}
|
{run.error}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{fileIsLoading ? (
|
{activeTabMeta?.kind === "html" ? (
|
||||||
|
htmlContent ? (
|
||||||
|
<HtmlPreviewFrame
|
||||||
|
html={htmlContent}
|
||||||
|
className="min-h-[60vh] w-full flex-1 rounded-md border bg-white"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="text-muted-foreground rounded-md border p-3 text-sm">
|
||||||
|
HTML 页面尚未生成或正在生成中。
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
) : fileIsLoading ? (
|
||||||
<div className="text-muted-foreground flex items-center gap-2 text-sm">
|
<div className="text-muted-foreground flex items-center gap-2 text-sm">
|
||||||
<Loader2 className="size-4 animate-spin" />
|
<Loader2 className="size-4 animate-spin" />
|
||||||
正在加载文件内容...
|
正在加载文件内容...
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { Activity, ChevronDown, ChevronLeft, Download, Edit3, FileText, Heart, Loader2, Save, Code2, Trash2, X } from "lucide-react";
|
import { Activity, ChevronDown, ChevronLeft, Download, Edit3, FileText, Heart, Loader2, Maximize2, Save, Code2, Trash2, X } from "lucide-react";
|
||||||
import { useParams, useSearchParams } from "react-router-dom";
|
import { useParams, useSearchParams } from "react-router-dom";
|
||||||
import { useRouteNavigate as useNavigate } from "@/core/route-base";
|
import { useRouteNavigate as useNavigate } from "@/core/route-base";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
@@ -9,6 +9,7 @@ import { toast } from "sonner";
|
|||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
@@ -18,6 +19,7 @@ import {
|
|||||||
WorkspaceHeader,
|
WorkspaceHeader,
|
||||||
} from "@/components/workspace/workspace-container";
|
} from "@/components/workspace/workspace-container";
|
||||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||||
|
import { HtmlPreviewFrame } from "@/components/html-preview-frame";
|
||||||
import {
|
import {
|
||||||
downloadScheduledTaskRun,
|
downloadScheduledTaskRun,
|
||||||
downloadScheduledTaskRunFile,
|
downloadScheduledTaskRunFile,
|
||||||
@@ -97,23 +99,33 @@ function RenderPreview({ file }: { file: ScheduledTaskResultFileContent }) {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return <pre className="whitespace-pre-wrap text-sm">{file.content}</pre>;
|
return <pre className="whitespace-pre-wrap break-words text-sm">{file.content}</pre>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
type FullscreenPreview =
|
||||||
* Sandboxed preview of a generated HTML document. The iframe has no
|
| { mode: "html"; title: string; html: string }
|
||||||
* ``allow-scripts`` token, so embedded JS cannot run — defense-in-depth on top
|
| { mode: "markdown"; title: string; content: string }
|
||||||
* of the server-side sanitization that already stripped script vectors.
|
| { mode: "text"; title: string; content: string }
|
||||||
*/
|
| { mode: "file"; title: string; file: ScheduledTaskResultFileContent };
|
||||||
function HtmlPreviewFrame({ html }: { html: string }) {
|
|
||||||
return (
|
function FullscreenPreviewContent({ preview }: { preview: FullscreenPreview }) {
|
||||||
<iframe
|
if (preview.mode === "html") {
|
||||||
title="HTML 预览"
|
return <HtmlPreviewFrame html={preview.html} className="h-full w-full border-0 bg-white" />;
|
||||||
sandbox="allow-same-origin"
|
}
|
||||||
srcDoc={html}
|
if (preview.mode === "markdown") {
|
||||||
className="h-[70vh] w-full rounded-md border bg-white"
|
return (
|
||||||
/>
|
<MarkdownContent
|
||||||
);
|
className="max-w-none"
|
||||||
|
content={preview.content || "无正文内容"}
|
||||||
|
isLoading={false}
|
||||||
|
rehypePlugins={[]}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (preview.mode === "file") {
|
||||||
|
return <RenderPreview file={preview.file} />;
|
||||||
|
}
|
||||||
|
return <pre className="whitespace-pre-wrap break-words text-sm">{preview.content || "无正文内容"}</pre>;
|
||||||
}
|
}
|
||||||
|
|
||||||
type EditState = { draft: string; saving: boolean };
|
type EditState = { draft: string; saving: boolean };
|
||||||
@@ -162,9 +174,9 @@ function ExecutionMessage({ message }: { message: ScheduledTaskRunMessage }) {
|
|||||||
const isAi = message.event_type === "llm.ai.response";
|
const isAi = message.event_type === "llm.ai.response";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="rounded-md border">
|
<div className="min-w-0 rounded-md border">
|
||||||
<div className="flex items-center gap-2 border-b px-3 py-1.5">
|
<div className="flex min-w-0 flex-wrap items-center gap-2 border-b px-3 py-1.5">
|
||||||
<span className={cn("rounded px-1.5 py-0.5 text-xs font-medium", role.tone)}>
|
<span className={cn("max-w-full break-all rounded px-1.5 py-0.5 text-xs font-medium", role.tone)}>
|
||||||
{role.label}
|
{role.label}
|
||||||
{toolName ? ` · ${toolName}` : ""}
|
{toolName ? ` · ${toolName}` : ""}
|
||||||
</span>
|
</span>
|
||||||
@@ -233,6 +245,7 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
const [filesLoading, setFilesLoading] = useState(false);
|
const [filesLoading, setFilesLoading] = useState(false);
|
||||||
const [showMeta, setShowMeta] = useState(false);
|
const [showMeta, setShowMeta] = useState(false);
|
||||||
const [edits, setEdits] = useState<Record<number, EditState | null>>({});
|
const [edits, setEdits] = useState<Record<number, EditState | null>>({});
|
||||||
|
const [fullscreenPreview, setFullscreenPreview] = useState<FullscreenPreview | null>(null);
|
||||||
const canEditRun = run?.can_edit === true;
|
const canEditRun = run?.can_edit === true;
|
||||||
const canDeleteRun = canEditRun;
|
const canDeleteRun = canEditRun;
|
||||||
|
|
||||||
@@ -270,7 +283,16 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const resultFiles = useMemo(() => result?.files ?? [], [result]);
|
// The generated HTML document is already shown in the dedicated "HTML 预览"
|
||||||
|
// tab, so it is excluded from the "结果文件" list — that list surfaces the
|
||||||
|
// Markdown (and any other non-HTML artifact) only.
|
||||||
|
const resultFiles = useMemo(
|
||||||
|
() =>
|
||||||
|
(result?.files ?? []).filter(
|
||||||
|
(f) => !(f.kind === "html" || (f.name ?? "").toLowerCase().endsWith(".html")),
|
||||||
|
),
|
||||||
|
[result],
|
||||||
|
);
|
||||||
const fileCount = resultFiles.length;
|
const fileCount = resultFiles.length;
|
||||||
const resultMetadata = useMemo(() => {
|
const resultMetadata = useMemo(() => {
|
||||||
if (!result) return "";
|
if (!result) return "";
|
||||||
@@ -295,18 +317,28 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
}
|
}
|
||||||
setFilesLoading(true);
|
setFilesLoading(true);
|
||||||
try {
|
try {
|
||||||
const loaded = await Promise.all(
|
// Load each file independently. A single failing file (e.g. an archive
|
||||||
|
// that 404s) must NOT blank the whole panel — otherwise the tab shows
|
||||||
|
// "结果文件(2)" while the body says "没有生成文件". Render every file
|
||||||
|
// that loads and skip the ones that don't.
|
||||||
|
const settled = await Promise.allSettled(
|
||||||
resultFiles.map((f) => {
|
resultFiles.map((f) => {
|
||||||
const index = result.files.indexOf(f);
|
const index = result.files.indexOf(f);
|
||||||
return getScheduledTaskRunFileContent(run.id, index);
|
return getScheduledTaskRunFileContent(run.id, index);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
|
const loaded = settled
|
||||||
|
.filter(
|
||||||
|
(r): r is PromiseFulfilledResult<ScheduledTaskResultFileContent> =>
|
||||||
|
r.status === "fulfilled",
|
||||||
|
)
|
||||||
|
.map((r) => r.value);
|
||||||
setFileContents(loaded);
|
setFileContents(loaded);
|
||||||
}
|
const failed = settled.length - loaded.length;
|
||||||
} catch (error) {
|
if (failed > 0 && loaded.length === 0) {
|
||||||
if (!cancelled) {
|
toast.error("结果文件已不可用(可能已被清理)");
|
||||||
toast.error(error instanceof Error ? error.message : "加载文件内容失败");
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
@@ -424,13 +456,33 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<WorkspaceContainer>
|
<>
|
||||||
|
<Dialog open={fullscreenPreview !== null} onOpenChange={(open) => !open && setFullscreenPreview(null)}>
|
||||||
|
<DialogContent className="flex h-[96vh] w-[96vw] max-w-none flex-col gap-0 p-0 sm:max-w-none">
|
||||||
|
<DialogHeader className="shrink-0 border-b px-4 py-3 pr-12">
|
||||||
|
<DialogTitle className="truncate text-base">
|
||||||
|
{fullscreenPreview?.title ?? "预览"}
|
||||||
|
</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
{fullscreenPreview && (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"min-h-0 flex-1",
|
||||||
|
fullscreenPreview.mode === "html" ? "" : "overflow-auto p-4",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<FullscreenPreviewContent preview={fullscreenPreview} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
<WorkspaceContainer>
|
||||||
<WorkspaceHeader />
|
<WorkspaceHeader />
|
||||||
<WorkspaceBody>
|
<WorkspaceBody>
|
||||||
<div className="flex size-full min-h-0 flex-col p-3">
|
<div className="flex size-full min-h-0 flex-col p-3">
|
||||||
<Card className="flex min-h-0 flex-1 flex-col">
|
<Card className="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||||
{/* 工具栏 */}
|
{/* 工具栏 */}
|
||||||
<div className="flex flex-wrap items-center gap-2 border-b px-3 py-2">
|
<div className="flex min-w-0 flex-wrap items-center gap-2 border-b px-3 py-2">
|
||||||
<div className="mr-auto flex min-w-0 items-center gap-2">
|
<div className="mr-auto flex min-w-0 items-center gap-2">
|
||||||
<span className="truncate text-sm font-medium">
|
<span className="truncate text-sm font-medium">
|
||||||
{result?.title || (isLoading ? "正在加载..." : "执行结果详情")}
|
{result?.title || (isLoading ? "正在加载..." : "执行结果详情")}
|
||||||
@@ -470,15 +522,15 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
{/* 执行信息(可折叠) */}
|
{/* 执行信息(可折叠) */}
|
||||||
{showMeta && run && (
|
{showMeta && run && (
|
||||||
<div className="border-b px-3 py-2">
|
<div className="border-b px-3 py-2">
|
||||||
<div className="text-muted-foreground grid gap-x-4 gap-y-1 text-xs md:grid-cols-3 xl:grid-cols-5">
|
<div className="text-muted-foreground grid min-w-0 gap-x-4 gap-y-1 text-xs md:grid-cols-3 xl:grid-cols-5">
|
||||||
<div>ID:{run.id}</div>
|
<div className="min-w-0 break-all">ID:{run.id}</div>
|
||||||
<div>计划:{formatDate(run.scheduled_for)}</div>
|
<div>计划:{formatDate(run.scheduled_for)}</div>
|
||||||
<div>开始:{formatDate(run.started_at)}</div>
|
<div>开始:{formatDate(run.started_at)}</div>
|
||||||
<div>结束:{formatDate(run.finished_at)}</div>
|
<div>结束:{formatDate(run.finished_at)}</div>
|
||||||
<div>耗时:{formatDuration(run)}</div>
|
<div>耗时:{formatDuration(run)}</div>
|
||||||
</div>
|
</div>
|
||||||
{run.error && (
|
{run.error && (
|
||||||
<div className="text-destructive mt-2 rounded border border-destructive/30 bg-destructive/5 p-2 text-xs">
|
<div className="text-destructive mt-2 break-words rounded border border-destructive/30 bg-destructive/5 p-2 text-xs">
|
||||||
{run.error}
|
{run.error}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -502,8 +554,8 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
}
|
}
|
||||||
className="flex min-h-0 flex-1 flex-col"
|
className="flex min-h-0 flex-1 flex-col"
|
||||||
>
|
>
|
||||||
<div className="border-b px-3 pt-1">
|
<div className="min-w-0 overflow-x-auto border-b px-3 pt-1">
|
||||||
<TabsList className="h-8">
|
<TabsList className="h-8 w-max">
|
||||||
{result && isHtmlRun && (
|
{result && isHtmlRun && (
|
||||||
<TabsTrigger value="html" className="text-xs">
|
<TabsTrigger value="html" className="text-xs">
|
||||||
<Code2 className="mr-1 size-3" />
|
<Code2 className="mr-1 size-3" />
|
||||||
@@ -540,6 +592,23 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
{isHtmlRun && (
|
{isHtmlRun && (
|
||||||
<TabsContent value="html" className="m-0 p-4">
|
<TabsContent value="html" className="m-0 p-4">
|
||||||
<div className="mb-3 flex flex-wrap items-center justify-end gap-2">
|
<div className="mb-3 flex flex-wrap items-center justify-end gap-2">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
htmlContent &&
|
||||||
|
setFullscreenPreview({
|
||||||
|
mode: "html",
|
||||||
|
title: result.title || "HTML 预览",
|
||||||
|
html: htmlContent,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
disabled={!htmlContent}
|
||||||
|
title="全屏查看 HTML"
|
||||||
|
>
|
||||||
|
<Maximize2 className="size-4" />
|
||||||
|
全屏
|
||||||
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -565,6 +634,24 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
</TabsContent>
|
</TabsContent>
|
||||||
)}
|
)}
|
||||||
<TabsContent value="body" className="m-0 p-4">
|
<TabsContent value="body" className="m-0 p-4">
|
||||||
|
<div className="mb-3 flex justify-end">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
setFullscreenPreview({
|
||||||
|
mode: result.format === "markdown" || result.format === "mixed" ? "markdown" : "text",
|
||||||
|
title: result.title || "正文预览",
|
||||||
|
content: result.content || "无正文内容",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
disabled={!result.content}
|
||||||
|
title="全屏查看正文"
|
||||||
|
>
|
||||||
|
<Maximize2 className="size-4" />
|
||||||
|
全屏
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
{result.format === "markdown" || result.format === "mixed" ? (
|
{result.format === "markdown" || result.format === "mixed" ? (
|
||||||
<MarkdownContent
|
<MarkdownContent
|
||||||
className="max-w-none"
|
className="max-w-none"
|
||||||
@@ -573,7 +660,7 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
rehypePlugins={[]}
|
rehypePlugins={[]}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<pre className="whitespace-pre-wrap text-sm">
|
<pre className="whitespace-pre-wrap break-words text-sm">
|
||||||
{result.content || "无正文内容"}
|
{result.content || "无正文内容"}
|
||||||
</pre>
|
</pre>
|
||||||
)}
|
)}
|
||||||
@@ -584,7 +671,9 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
)}
|
)}
|
||||||
{!filesLoading && fileContents.length === 0 && (
|
{!filesLoading && fileContents.length === 0 && (
|
||||||
<div className="text-muted-foreground rounded-md border p-3 text-sm">
|
<div className="text-muted-foreground rounded-md border p-3 text-sm">
|
||||||
本次执行没有生成文件。
|
{fileCount > 0
|
||||||
|
? `本次执行生成了 ${fileCount} 个文件,但当前无法读取(文件可能已被清理或移动)。可尝试「下载全部」。`
|
||||||
|
: "本次执行没有生成文件。"}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
@@ -594,9 +683,9 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
const editState = edits[file.index] ?? null;
|
const editState = edits[file.index] ?? null;
|
||||||
const isEditing = editState !== null;
|
const isEditing = editState !== null;
|
||||||
return (
|
return (
|
||||||
<div key={file.index} className="rounded-md border">
|
<div key={file.index} className="min-w-0 rounded-md border">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-2 border-b p-2">
|
<div className="flex flex-wrap items-center justify-between gap-2 border-b p-2">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="truncate text-sm font-medium">{file.name}</div>
|
<div className="truncate text-sm font-medium">{file.name}</div>
|
||||||
<div className="text-muted-foreground text-xs">
|
<div className="text-muted-foreground text-xs">
|
||||||
{file.mime_type || file.kind || "附件"}
|
{file.mime_type || file.kind || "附件"}
|
||||||
@@ -604,6 +693,24 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{file.previewable && !isEditing && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
setFullscreenPreview({
|
||||||
|
mode: "file",
|
||||||
|
title: file.name,
|
||||||
|
file,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
disabled={!file.content}
|
||||||
|
title="全屏查看文件"
|
||||||
|
>
|
||||||
|
<Maximize2 className="size-4" />
|
||||||
|
全屏
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
{isMarkdown && (
|
{isMarkdown && (
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
@@ -679,7 +786,7 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
<TabsContent value="meta" className="m-0 p-3">
|
<TabsContent value="meta" className="m-0 p-3">
|
||||||
<pre className="bg-muted overflow-auto rounded-md p-3 text-xs">
|
<pre className="bg-muted overflow-auto whitespace-pre-wrap break-words rounded-md p-3 text-xs">
|
||||||
{resultMetadata}
|
{resultMetadata}
|
||||||
</pre>
|
</pre>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
@@ -714,6 +821,7 @@ export default function ScheduledTaskRunDetailPage() {
|
|||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</WorkspaceBody>
|
</WorkspaceBody>
|
||||||
</WorkspaceContainer>
|
</WorkspaceContainer>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
BellOff,
|
BellOff,
|
||||||
@@ -44,7 +45,6 @@ import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
|||||||
import { TagPickerDialog } from "@/components/workspace/tags/tag-picker-dialog";
|
import { TagPickerDialog } from "@/components/workspace/tags/tag-picker-dialog";
|
||||||
import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar";
|
import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar";
|
||||||
import { useAgents } from "@/core/agents";
|
import { useAgents } from "@/core/agents";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
|
||||||
import { useModels } from "@/core/models/hooks";
|
import { useModels } from "@/core/models/hooks";
|
||||||
import {
|
import {
|
||||||
downloadScheduledTaskRun,
|
downloadScheduledTaskRun,
|
||||||
@@ -113,13 +113,15 @@ const emptyForm = {
|
|||||||
timezone: "Asia/Shanghai",
|
timezone: "Asia/Shanghai",
|
||||||
prompt: "",
|
prompt: "",
|
||||||
execution_agent_name: "",
|
execution_agent_name: "",
|
||||||
|
// Two independent output switches (may both be on): require a Markdown file
|
||||||
|
// and/or render an HTML page. The form no longer splits into "普通任务 / HTML
|
||||||
|
// 页面" tabs.
|
||||||
require_markdown: false,
|
require_markdown: false,
|
||||||
// HTML page task fields. ``task_kind`` "agent" keeps the original behavior.
|
require_html: false,
|
||||||
// Data gathering is delegated to the agent's own search skills — no explicit
|
// HTML-only extra fields, shown when ``require_html`` is on. The main
|
||||||
// search query / data source. ``html_model_name`` empty means "use the first
|
// ``prompt`` above doubles as the page requirement, so there is no separate
|
||||||
// available model" — never a hardcoded GLM-5.
|
// page-prompt field. ``html_model_name`` empty means "use the first available
|
||||||
task_kind: "agent" as "agent" | "html_page",
|
// model" — never a hardcoded GLM-5.
|
||||||
html_page_prompt: "",
|
|
||||||
html_negative_prompt: "",
|
html_negative_prompt: "",
|
||||||
html_reference_favorite_id: "",
|
html_reference_favorite_id: "",
|
||||||
html_model_name: "",
|
html_model_name: "",
|
||||||
@@ -133,6 +135,7 @@ const DESCRIPTION_TEXTAREA_ROWS = 4;
|
|||||||
const PROMPT_TEXTAREA_ROWS = 10;
|
const PROMPT_TEXTAREA_ROWS = 10;
|
||||||
|
|
||||||
export default function ScheduledTasksPage() {
|
export default function ScheduledTasksPage() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const darkToastOpts =
|
const darkToastOpts =
|
||||||
theme === "dark"
|
theme === "dark"
|
||||||
@@ -184,7 +187,6 @@ export default function ScheduledTasksPage() {
|
|||||||
const [subscribeTarget, setSubscribeTarget] = useState<PublishedScheduledTask | null>(null);
|
const [subscribeTarget, setSubscribeTarget] = useState<PublishedScheduledTask | null>(null);
|
||||||
const [subscribeNotify, setSubscribeNotify] = useState(false);
|
const [subscribeNotify, setSubscribeNotify] = useState(false);
|
||||||
const [tagPickerTask, setTagPickerTask] = useState<ScheduledTask | null>(null);
|
const [tagPickerTask, setTagPickerTask] = useState<ScheduledTask | null>(null);
|
||||||
const isAdmin = useMemo(() => getStoredAuth()?.system_role === "admin", []);
|
|
||||||
|
|
||||||
const sortedTasks = useMemo(
|
const sortedTasks = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -242,11 +244,15 @@ export default function ScheduledTasksPage() {
|
|||||||
description: task.description ?? "",
|
description: task.description ?? "",
|
||||||
schedule: task.schedule_text,
|
schedule: task.schedule_text,
|
||||||
timezone: task.timezone,
|
timezone: task.timezone,
|
||||||
prompt: task.prompt,
|
// The main prompt doubles as the HTML page requirement; legacy HTML tasks
|
||||||
|
// stored that under ``html_config.page_prompt``, so prefer it on edit.
|
||||||
|
prompt: html.page_prompt || task.prompt,
|
||||||
execution_agent_name: task.execution_agent_name ?? "",
|
execution_agent_name: task.execution_agent_name ?? "",
|
||||||
require_markdown: !!task.execution_context?.require_markdown,
|
require_markdown: !!task.execution_context?.require_markdown,
|
||||||
task_kind: task.execution_context?.task_kind === "html_page" ? "html_page" : "agent",
|
// Backward compatible: legacy HTML tasks only carry ``task_kind``.
|
||||||
html_page_prompt: html.page_prompt ?? "",
|
require_html:
|
||||||
|
!!task.execution_context?.require_html ||
|
||||||
|
task.execution_context?.task_kind === "html_page",
|
||||||
html_negative_prompt: html.negative_prompt ?? "",
|
html_negative_prompt: html.negative_prompt ?? "",
|
||||||
html_reference_favorite_id: html.reference_favorite_id ?? "",
|
html_reference_favorite_id: html.reference_favorite_id ?? "",
|
||||||
html_model_name: html.model_name ?? "",
|
html_model_name: html.model_name ?? "",
|
||||||
@@ -268,20 +274,26 @@ export default function ScheduledTasksPage() {
|
|||||||
setScheduleConfig(DEFAULT_SCHEDULE_CONFIG);
|
setScheduleConfig(DEFAULT_SCHEDULE_CONFIG);
|
||||||
};
|
};
|
||||||
|
|
||||||
const isHtmlTask = form.task_kind === "html_page";
|
const isHtmlTask = form.require_html;
|
||||||
// The model actually shown/used: the user's choice, else the first configured
|
// The model actually shown/used: the user's choice, else the first configured
|
||||||
// model. Never a hardcoded GLM-5 — it follows config order and the selection.
|
// model. Never a hardcoded GLM-5 — it follows config order and the selection.
|
||||||
const effectiveHtmlModel = form.html_model_name || availableModels[0]?.name || "";
|
const effectiveHtmlModel = form.html_model_name || availableModels[0]?.name || "";
|
||||||
|
|
||||||
// Build the execution_context for the current form. HTML tasks persist their
|
// Build the execution_context for the current form. ``require_html`` and
|
||||||
// config under ``html_config``; regular tasks send an explicit ``agent`` kind
|
// ``require_markdown`` are independent toggles (both may be on). HTML tasks
|
||||||
// so switching a task back from HTML clears the old config.
|
// persist their extra config under ``html_config`` and reuse the main prompt
|
||||||
|
// as the page requirement; ``task_kind`` is kept in sync only for backward
|
||||||
|
// compatibility with older readers.
|
||||||
const buildExecutionContext = (): ScheduledTaskExecutionContext => {
|
const buildExecutionContext = (): ScheduledTaskExecutionContext => {
|
||||||
if (!isHtmlTask) return { task_kind: "agent", html_config: undefined };
|
if (!isHtmlTask) {
|
||||||
|
return { require_html: false, task_kind: "agent", html_config: undefined };
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
|
require_html: true,
|
||||||
task_kind: "html_page",
|
task_kind: "html_page",
|
||||||
html_config: {
|
html_config: {
|
||||||
page_prompt: form.html_page_prompt.trim() || null,
|
// The main prompt doubles as the page requirement.
|
||||||
|
page_prompt: form.prompt.trim() || null,
|
||||||
negative_prompt: form.html_negative_prompt.trim() || null,
|
negative_prompt: form.html_negative_prompt.trim() || null,
|
||||||
reference_favorite_id: form.html_reference_favorite_id || null,
|
reference_favorite_id: form.html_reference_favorite_id || null,
|
||||||
// Send the user's selection; fall back to the first configured model,
|
// Send the user's selection; fall back to the first configured model,
|
||||||
@@ -295,11 +307,10 @@ export default function ScheduledTasksPage() {
|
|||||||
try {
|
try {
|
||||||
const cronSchedule = buildCron(scheduleConfig);
|
const cronSchedule = buildCron(scheduleConfig);
|
||||||
const executionContext = buildExecutionContext();
|
const executionContext = buildExecutionContext();
|
||||||
// HTML tasks may leave the agent prompt empty — fall back to the page
|
// The (non-null) prompt column always needs something useful; HTML tasks
|
||||||
// prompt so the (non-null) prompt column always has something useful.
|
// may leave it sparse, so fall back to a generic instruction.
|
||||||
const effectivePrompt = isHtmlTask
|
const effectivePrompt =
|
||||||
? form.prompt.trim() || form.html_page_prompt.trim() || "生成 HTML 页面"
|
form.prompt.trim() || (isHtmlTask ? "生成 HTML 页面" : form.prompt);
|
||||||
: form.prompt;
|
|
||||||
if (creating) {
|
if (creating) {
|
||||||
const task = await actions.create.mutateAsync({
|
const task = await actions.create.mutateAsync({
|
||||||
name: form.name || "定时任务",
|
name: form.name || "定时任务",
|
||||||
@@ -307,8 +318,8 @@ export default function ScheduledTasksPage() {
|
|||||||
schedule: cronSchedule,
|
schedule: cronSchedule,
|
||||||
timezone: form.timezone || "Asia/Shanghai",
|
timezone: form.timezone || "Asia/Shanghai",
|
||||||
prompt: effectivePrompt,
|
prompt: effectivePrompt,
|
||||||
execution_agent_name: isHtmlTask ? null : form.execution_agent_name || null,
|
execution_agent_name: form.execution_agent_name || null,
|
||||||
require_markdown: isHtmlTask ? false : form.require_markdown,
|
require_markdown: form.require_markdown,
|
||||||
execution_context: executionContext,
|
execution_context: executionContext,
|
||||||
});
|
});
|
||||||
setSelectedTaskId(task.task_id);
|
setSelectedTaskId(task.task_id);
|
||||||
@@ -322,8 +333,8 @@ export default function ScheduledTasksPage() {
|
|||||||
schedule: cronSchedule,
|
schedule: cronSchedule,
|
||||||
timezone: form.timezone,
|
timezone: form.timezone,
|
||||||
prompt: effectivePrompt,
|
prompt: effectivePrompt,
|
||||||
execution_agent_name: isHtmlTask ? null : form.execution_agent_name || null,
|
execution_agent_name: form.execution_agent_name || null,
|
||||||
require_markdown: isHtmlTask ? false : form.require_markdown,
|
require_markdown: form.require_markdown,
|
||||||
execution_context: executionContext,
|
execution_context: executionContext,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -361,15 +372,35 @@ export default function ScheduledTasksPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleTriggerTask = async (task: ScheduledTask) => {
|
||||||
|
setSelectedTaskId(task.task_id);
|
||||||
|
setRunsTimeFilter("all");
|
||||||
|
try {
|
||||||
|
await actions.trigger.mutateAsync(task.task_id);
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: ["scheduled-tasks", task.task_id, "runs"],
|
||||||
|
});
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: ["scheduled-tasks", "list"],
|
||||||
|
});
|
||||||
|
toast.success("已触发执行", darkToastOpts.success);
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(
|
||||||
|
error instanceof Error ? error.message : "触发失败",
|
||||||
|
darkToastOpts.error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<WorkspaceContainer>
|
<WorkspaceContainer>
|
||||||
<WorkspaceHeader />
|
<WorkspaceHeader />
|
||||||
<WorkspaceBody>
|
<WorkspaceBody>
|
||||||
<div className="grid size-full min-h-0 grid-cols-1 gap-4 p-4 xl:grid-cols-[420px_minmax(0,1fr)]">
|
<div className="grid size-full min-h-0 grid-cols-1 grid-rows-[minmax(0,1fr)_minmax(0,1fr)] gap-4 p-4 xl:grid-cols-[420px_minmax(0,1fr)] xl:grid-rows-1">
|
||||||
<Card className="flex min-h-0 flex-col">
|
<Card className="flex min-h-0 min-w-0 flex-col">
|
||||||
<CardHeader className="gap-3">
|
<CardHeader className="gap-3">
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-3">
|
||||||
<div>
|
<div className="min-w-0">
|
||||||
<CardTitle>定时任务</CardTitle>
|
<CardTitle>定时任务</CardTitle>
|
||||||
<p className="text-muted-foreground mt-1 text-sm">
|
<p className="text-muted-foreground mt-1 text-sm">
|
||||||
选择任务后,在右侧查看全部执行记录
|
选择任务后,在右侧查看全部执行记录
|
||||||
@@ -480,7 +511,8 @@ export default function ScheduledTasksPage() {
|
|||||||
<Globe className="size-3" />已发布
|
<Globe className="size-3" />已发布
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
{task.execution_context?.task_kind === "html_page" && (
|
{(task.execution_context?.require_html ||
|
||||||
|
task.execution_context?.task_kind === "html_page") && (
|
||||||
<Badge
|
<Badge
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="shrink-0 border-sky-500/30 bg-sky-500/10 text-xs text-sky-600 dark:text-sky-400"
|
className="shrink-0 border-sky-500/30 bg-sky-500/10 text-xs text-sky-600 dark:text-sky-400"
|
||||||
@@ -518,19 +550,17 @@ export default function ScheduledTasksPage() {
|
|||||||
<TagChipList tags={task.tags!} className="mt-3" />
|
<TagChipList tags={task.tags!} className="mt-3" />
|
||||||
)}
|
)}
|
||||||
<div className="mt-3 flex flex-wrap gap-2">
|
<div className="mt-3 flex flex-wrap gap-2">
|
||||||
{isAdmin && (
|
<Button
|
||||||
<Button
|
size="icon"
|
||||||
size="icon"
|
variant="outline"
|
||||||
variant="outline"
|
title="编辑标签"
|
||||||
title="编辑标签"
|
onClick={(event) => {
|
||||||
onClick={(event) => {
|
event.stopPropagation();
|
||||||
event.stopPropagation();
|
setTagPickerTask(task);
|
||||||
setTagPickerTask(task);
|
}}
|
||||||
}}
|
>
|
||||||
>
|
<TagsIcon className="size-4" />
|
||||||
<TagsIcon className="size-4" />
|
</Button>
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{isOwner ? (
|
{isOwner ? (
|
||||||
<>
|
<>
|
||||||
<Button
|
<Button
|
||||||
@@ -563,8 +593,7 @@ export default function ScheduledTasksPage() {
|
|||||||
title="立即执行"
|
title="立即执行"
|
||||||
onClick={(event) => {
|
onClick={(event) => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
actions.trigger.mutate(task.task_id);
|
void handleTriggerTask(task);
|
||||||
toast.success("已触发执行", darkToastOpts.success);
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<RefreshCw className="size-4" />
|
<RefreshCw className="size-4" />
|
||||||
@@ -715,10 +744,27 @@ export default function ScheduledTasksPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="flex min-h-0 flex-col">
|
<Card className="flex min-h-0 min-w-0 flex-col">
|
||||||
<CardHeader className="gap-2">
|
<CardHeader className="gap-2">
|
||||||
<div className="flex items-center justify-between gap-2">
|
<div className="flex min-w-0 items-center justify-between gap-2">
|
||||||
<CardTitle>执行记录</CardTitle>
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
|
<CardTitle>执行记录</CardTitle>
|
||||||
|
{selectedTask && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
className="h-7 gap-1 px-2 text-xs"
|
||||||
|
title="在新标签打开该任务的公开页"
|
||||||
|
onClick={() => {
|
||||||
|
const url = `${window.location.origin}${window.location.pathname}#/public/scheduled-tasks/${encodeURIComponent(selectedTask.task_id)}`;
|
||||||
|
window.open(url, "_blank", "noopener,noreferrer");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Globe className="size-3.5" />
|
||||||
|
公开页
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<Select value={runsTimeFilter} onValueChange={(v) => setRunsTimeFilter(v as typeof runsTimeFilter)}>
|
<Select value={runsTimeFilter} onValueChange={(v) => setRunsTimeFilter(v as typeof runsTimeFilter)}>
|
||||||
<SelectTrigger className="h-7 w-28 text-xs">
|
<SelectTrigger className="h-7 w-28 text-xs">
|
||||||
<SelectValue />
|
<SelectValue />
|
||||||
@@ -731,7 +777,7 @@ export default function ScheduledTasksPage() {
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-muted-foreground text-sm">
|
<p className="text-muted-foreground min-w-0 truncate text-sm">
|
||||||
{selectedTask ? desensitize(selectedTask.name) : "请选择左侧任务"}
|
{selectedTask ? desensitize(selectedTask.name) : "请选择左侧任务"}
|
||||||
</p>
|
</p>
|
||||||
{selectedTask && (selectedTask.creator_email || selectedTask.creator_user_id) && (
|
{selectedTask && (selectedTask.creator_email || selectedTask.creator_user_id) && (
|
||||||
@@ -770,11 +816,11 @@ export default function ScheduledTasksPage() {
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="truncate font-medium">
|
<div className="truncate font-medium">
|
||||||
{run.result?.title ? desensitize(run.result.title) : formatDate(run.scheduled_for)}
|
{run.result?.title ? desensitize(run.result.title) : formatDate(run.scheduled_for)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-muted-foreground mt-1 text-xs">
|
<div className="text-muted-foreground mt-1 break-words text-xs">
|
||||||
计划:{formatDate(run.scheduled_for)} · 开始:
|
计划:{formatDate(run.scheduled_for)} · 开始:
|
||||||
{formatDate(run.started_at)}
|
{formatDate(run.started_at)}
|
||||||
</div>
|
</div>
|
||||||
@@ -932,20 +978,6 @@ export default function ScheduledTasksPage() {
|
|||||||
}
|
}
|
||||||
placeholder="任务描述(可选,将显示在公开页标题下方)"
|
placeholder="任务描述(可选,将显示在公开页标题下方)"
|
||||||
/>
|
/>
|
||||||
<div className="flex flex-col gap-1">
|
|
||||||
<p className="text-muted-foreground text-xs">任务类型</p>
|
|
||||||
<Tabs
|
|
||||||
value={form.task_kind}
|
|
||||||
onValueChange={(v) =>
|
|
||||||
setForm((value) => ({ ...value, task_kind: v as "agent" | "html_page" }))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<TabsList className="w-full">
|
|
||||||
<TabsTrigger value="agent" className="flex-1">普通任务</TabsTrigger>
|
|
||||||
<TabsTrigger value="html_page" className="flex-1">HTML 页面</TabsTrigger>
|
|
||||||
</TabsList>
|
|
||||||
</Tabs>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<p className="text-muted-foreground text-xs">执行频率</p>
|
<p className="text-muted-foreground text-xs">执行频率</p>
|
||||||
<ScheduleBuilder value={scheduleConfig} onChange={setScheduleConfig} />
|
<ScheduleBuilder value={scheduleConfig} onChange={setScheduleConfig} />
|
||||||
@@ -958,77 +990,83 @@ export default function ScheduledTasksPage() {
|
|||||||
placeholder="时区,例如:Asia/Shanghai"
|
placeholder="时区,例如:Asia/Shanghai"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{!isHtmlTask && (
|
<Select
|
||||||
<>
|
value={form.execution_agent_name || "__default__"}
|
||||||
<Select
|
onValueChange={(v) =>
|
||||||
value={form.execution_agent_name || "__default__"}
|
setForm((value) => ({
|
||||||
onValueChange={(v) =>
|
...value,
|
||||||
setForm((value) => ({
|
execution_agent_name: v === "__default__" ? "" : v,
|
||||||
...value,
|
}))
|
||||||
execution_agent_name: v === "__default__" ? "" : v,
|
}
|
||||||
}))
|
>
|
||||||
}
|
<SelectTrigger className="w-full min-w-0 max-w-full overflow-hidden [&>span]:min-w-0 [&>span]:flex-1 [&>span]:truncate">
|
||||||
>
|
<SelectValue placeholder="选择执行智能体" />
|
||||||
<SelectTrigger className="w-full min-w-0 max-w-full overflow-hidden [&>span]:min-w-0 [&>span]:flex-1 [&>span]:truncate">
|
</SelectTrigger>
|
||||||
<SelectValue placeholder="选择执行智能体" />
|
<SelectContent
|
||||||
</SelectTrigger>
|
position="popper"
|
||||||
<SelectContent
|
className="max-h-[40vh] w-[max(var(--radix-select-trigger-width),28rem)] max-w-[min(90vw,40rem)]"
|
||||||
position="popper"
|
>
|
||||||
className="w-[var(--radix-select-trigger-width)] max-w-[var(--radix-select-trigger-width)]"
|
<SelectItem value="__default__">默认助手(不指定)</SelectItem>
|
||||||
>
|
{agents.map((agent) => (
|
||||||
<SelectItem value="__default__">默认助手(不指定)</SelectItem>
|
<SelectItem key={agent.id} value={agent.id}>
|
||||||
{agents.map((agent) => (
|
<span className="block whitespace-normal break-words">
|
||||||
<SelectItem key={agent.id} value={agent.id}>
|
{desensitize(agent.name)}
|
||||||
<span className="block truncate">
|
{agent.description ? ` — ${desensitize(agent.description)}` : ""}
|
||||||
{desensitize(agent.name)}
|
</span>
|
||||||
{agent.description ? ` — ${desensitize(agent.description)}` : ""}
|
</SelectItem>
|
||||||
</span>
|
))}
|
||||||
</SelectItem>
|
</SelectContent>
|
||||||
))}
|
</Select>
|
||||||
</SelectContent>
|
<Textarea
|
||||||
</Select>
|
className="min-h-40"
|
||||||
<Textarea
|
value={form.prompt}
|
||||||
className="min-h-40"
|
onChange={(event) =>
|
||||||
value={form.prompt}
|
setForm((value) => ({ ...value, prompt: event.target.value }))
|
||||||
onChange={(event) =>
|
}
|
||||||
setForm((value) => ({ ...value, prompt: event.target.value }))
|
placeholder={
|
||||||
}
|
isHtmlTask
|
||||||
placeholder="任务 Prompt"
|
? "任务 / 页面生成要求,例如:检索新能源车最新舆情,生成适合领导快速浏览的态势页"
|
||||||
/>
|
: "任务 Prompt"
|
||||||
<div className="flex items-center justify-between rounded-md border p-3">
|
}
|
||||||
<div className="min-w-0 pr-3">
|
/>
|
||||||
<p className="text-sm font-medium">必须生成 Markdown 文件</p>
|
<div className="flex items-center justify-between rounded-md border p-3">
|
||||||
<p className="text-muted-foreground text-xs">
|
<div className="min-w-0 pr-3">
|
||||||
开启后会提示大模型生成 Markdown(.md) 文件;系统会校验本次是否生成了 .md 文件且文件正文超过 100 字,未达到则记为失败。
|
<p className="text-sm font-medium">必须生成 Markdown 文件</p>
|
||||||
</p>
|
<p className="text-muted-foreground text-xs">
|
||||||
</div>
|
开启后会提示大模型生成 Markdown(.md) 文件;系统会校验本次是否生成了 .md 文件且文件正文超过 100 字,未达到则记为失败。
|
||||||
<Switch
|
</p>
|
||||||
checked={form.require_markdown}
|
</div>
|
||||||
onCheckedChange={(v) =>
|
<Switch
|
||||||
setForm((value) => ({ ...value, require_markdown: v }))
|
checked={form.require_markdown}
|
||||||
}
|
onCheckedChange={(v) =>
|
||||||
/>
|
setForm((value) => ({ ...value, require_markdown: v }))
|
||||||
</div>
|
}
|
||||||
</>
|
/>
|
||||||
)}
|
</div>
|
||||||
|
<div className="flex items-center justify-between rounded-md border p-3">
|
||||||
|
<div className="min-w-0 pr-3">
|
||||||
|
<p className="text-sm font-medium">必须生成 HTML 页面</p>
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
开启后会先用智能体检索整理真实数据,再渲染为完整 HTML 页面(可在执行记录中预览)。可与“必须生成 Markdown”同时开启。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={form.require_html}
|
||||||
|
onCheckedChange={(v) =>
|
||||||
|
setForm((value) => ({ ...value, require_html: v }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{isHtmlTask && (
|
{isHtmlTask && (
|
||||||
<>
|
<>
|
||||||
<Textarea
|
|
||||||
className="min-h-24"
|
|
||||||
value={form.html_page_prompt}
|
|
||||||
onChange={(event) =>
|
|
||||||
setForm((value) => ({ ...value, html_page_prompt: event.target.value }))
|
|
||||||
}
|
|
||||||
placeholder="页面生成要求,例如:检索新能源车最新舆情,生成适合领导快速浏览的态势页"
|
|
||||||
/>
|
|
||||||
<Textarea
|
<Textarea
|
||||||
className="min-h-16"
|
className="min-h-16"
|
||||||
value={form.html_negative_prompt}
|
value={form.html_negative_prompt}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
setForm((value) => ({ ...value, html_negative_prompt: event.target.value }))
|
setForm((value) => ({ ...value, html_negative_prompt: event.target.value }))
|
||||||
}
|
}
|
||||||
placeholder="限制条件(可选),例如:不要使用深色背景,不要出现外部链接脚本"
|
placeholder="HTML 限制条件(可选),例如:不要使用深色背景,不要出现外部链接脚本"
|
||||||
/>
|
/>
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<p className="text-muted-foreground text-xs">参考收藏页面(可选)</p>
|
<p className="text-muted-foreground text-xs">参考收藏页面(可选)</p>
|
||||||
@@ -1106,14 +1144,6 @@ export default function ScheduledTasksPage() {
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<Textarea
|
|
||||||
className="min-h-16"
|
|
||||||
value={form.prompt}
|
|
||||||
onChange={(event) =>
|
|
||||||
setForm((value) => ({ ...value, prompt: event.target.value }))
|
|
||||||
}
|
|
||||||
placeholder="补充说明(可选):进一步约束智能体如何检索数据、页面包含哪些内容"
|
|
||||||
/>
|
|
||||||
<p className="text-muted-foreground text-xs">
|
<p className="text-muted-foreground text-xs">
|
||||||
执行流程:智能体运用自身检索技能整理真实数据 → 选定模型渲染为完整 HTML → 自动安全清洗与结构校验 → 可在执行记录中预览。
|
执行流程:智能体运用自身检索技能整理真实数据 → 选定模型渲染为完整 HTML → 自动安全清洗与结构校验 → 可在执行记录中预览。
|
||||||
</p>
|
</p>
|
||||||
@@ -1129,7 +1159,7 @@ export default function ScheduledTasksPage() {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
{isAdmin && tagPickerTask && (
|
{tagPickerTask && (
|
||||||
<TagPickerDialog
|
<TagPickerDialog
|
||||||
open={!!tagPickerTask}
|
open={!!tagPickerTask}
|
||||||
onOpenChange={(open) => !open && setTagPickerTask(null)}
|
onOpenChange={(open) => !open && setTagPickerTask(null)}
|
||||||
|
|||||||
@@ -1,44 +1,47 @@
|
|||||||
import { Navigate, Route, Routes } from "react-router-dom";
|
import { Navigate, Route, Routes } from "react-router-dom";
|
||||||
import { Toaster } from "sonner";
|
import { Toaster } from "sonner";
|
||||||
|
|
||||||
|
import { SidebarProvider } from "@/components/ui/sidebar";
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
import { RouteBaseProvider } from "@/core/route-base";
|
import { RouteBaseProvider } from "@/core/route-base";
|
||||||
import { SidebarProvider } from "@/components/ui/sidebar";
|
|
||||||
|
|
||||||
import GeneralQA from "@/strategy-components/components/chat-qa/GeneralQA";
|
import GeneralQA from "@/strategy-components/components/chat-qa/GeneralQA";
|
||||||
import { ChatRuntime } from "./WorkspaceRoutes";
|
import FanganTyPage from "@/strategy-components/components/task-components/FanganTy";
|
||||||
import AgentsPage from "./AgentsPage";
|
import SentimentAnalyzes from "@/strategy-components/components/task-components/SentimentAnalyzes";
|
||||||
import ChatsPage from "./ChatsPage";
|
import TaskManagement from "@/strategy-components/components/task-components/TaskManagement";
|
||||||
import ChatPage from "./ChatPage";
|
import TaskPgFrom from "@/strategy-components/components/task-components/TaskPgFrom";
|
||||||
import NewAgentPage from "./NewAgentPage";
|
import TaskXkFrom from "@/strategy-components/components/task-components/TaskXkFrom";
|
||||||
|
import TaskAnalyzes from "@/strategy-components/components/task-components/TaskAnalyzes";
|
||||||
|
import XingdongTyPage from "@/strategy-components/components/task-components/XingdongTy";
|
||||||
|
import XXTyPage from "@/strategy-components/components/task-components/XXTy";
|
||||||
|
import { ActionAnalyzes } from "@/strategy-components/components/task-components/ActionAnalyzes";
|
||||||
|
import KnowledgeBaseResourceManagement from "@/strategy-components/components/resource-management/KnowledgeBaseResourceManagement";
|
||||||
|
import NetworkActorResourceManagement from "@/strategy-components/components/resource-management/NetworkActorResourceManagement";
|
||||||
|
import RoundtablePlanningPage from "@/roundtable-planning/pages/RoundtablePlanningPage";
|
||||||
|
import "@/roundtable-planning/styles/roundtable-planning.css";
|
||||||
import AgentChatPage from "./AgentChatPage";
|
import AgentChatPage from "./AgentChatPage";
|
||||||
import SkillsPage from "./SkillsPage";
|
import AgentsPage from "./AgentsPage";
|
||||||
import SkillEvolutionPage from "./SkillEvolutionPage";
|
import ChatPage from "./ChatPage";
|
||||||
import MemoryPage from "./MemoryPage";
|
import ChatsPage from "./ChatsPage";
|
||||||
import ScheduledTasksPage from "./ScheduledTasksPage";
|
import AdminUserLeaderboardPage from "./AdminUserLeaderboardPage";
|
||||||
import ScheduledTaskRunDetailPage from "./ScheduledTaskRunDetailPage";
|
import AdminUserLeaderboardSettingsPage from "./AdminUserLeaderboardSettingsPage";
|
||||||
import RecommendedQuestionsPage from "./RecommendedQuestionsPage";
|
|
||||||
import PromptPrefixSettingsPage from "./PromptPrefixSettingsPage";
|
|
||||||
import PrivateSquareSettingsPage from "./PrivateSquareSettingsPage";
|
|
||||||
import LlmMetricsPage from "./LlmMetricsPage";
|
|
||||||
import UsersPage from "./UsersPage";
|
|
||||||
import AdminScheduledTasksPage from "./AdminScheduledTasksPage";
|
|
||||||
import AdminUserActivityPage from "./AdminUserActivityPage";
|
|
||||||
import TagsPage from "./TagsPage";
|
|
||||||
import LightAppNewNotePage from "./LightAppNewNotePage";
|
import LightAppNewNotePage from "./LightAppNewNotePage";
|
||||||
import LightAppNoteListPage from "./LightAppNoteListPage";
|
import LightAppNoteListPage from "./LightAppNoteListPage";
|
||||||
import LightAppNoteQAPage from "./LightAppNoteQAPage";
|
import LightAppNoteQAPage from "./LightAppNoteQAPage";
|
||||||
import TaskXkFrom from "@/strategy-components/components/task-components/TaskXkFrom";
|
import MemoryPage from "./MemoryPage";
|
||||||
import TaskManagement from "@/strategy-components/components/task-components/TaskManagement";
|
import NewAgentPage from "./NewAgentPage";
|
||||||
import TaskPgFrom from "@/strategy-components/components/task-components/TaskPgFrom";
|
import PromptPrefixSettingsPage from "./PromptPrefixSettingsPage";
|
||||||
import FanganTyPage from "@/strategy-components/components/task-components/FanganTy";
|
import PrivateSquareSettingsPage from "./PrivateSquareSettingsPage";
|
||||||
import XingdongTyPage from "@/strategy-components/components/task-components/XingdongTy";
|
import RecommendedQuestionsPage from "./RecommendedQuestionsPage";
|
||||||
import XXTyPage from "@/strategy-components/components/task-components/XXTy";
|
import ScheduledTaskRunDetailPage from "./ScheduledTaskRunDetailPage";
|
||||||
import SentimentAnalyzes from "@/strategy-components/components/task-components/SentimentAnalyzes";
|
import ScheduledTasksPage from "./ScheduledTasksPage";
|
||||||
import TaskAnalyzes from "@/strategy-components/components/task-components/TaskAnalyzes";
|
import SkillEvolutionPage from "./SkillEvolutionPage";
|
||||||
import { ActionAnalyzes } from "@/strategy-components/components/task-components/ActionAnalyzes";
|
import SkillsPage from "./SkillsPage";
|
||||||
import NetworkActorResourceManagement from "@/strategy-components/components/resource-management/NetworkActorResourceManagement";
|
import TagsPage from "./TagsPage";
|
||||||
import KnowledgeBaseResourceManagement from "@/strategy-components/components/resource-management/KnowledgeBaseResourceManagement";
|
import UsersPage from "./UsersPage";
|
||||||
|
import LlmMetricsPage from "./LlmMetricsPage";
|
||||||
|
import AdminScheduledTasksPage from "./AdminScheduledTasksPage";
|
||||||
|
import AdminUserActivityPage from "./AdminUserActivityPage";
|
||||||
|
import { ChatRuntime } from "./WorkspaceRoutes";
|
||||||
|
|
||||||
export default function StrategyRoutes() {
|
export default function StrategyRoutes() {
|
||||||
return (
|
return (
|
||||||
@@ -48,21 +51,27 @@ export default function StrategyRoutes() {
|
|||||||
<Routes>
|
<Routes>
|
||||||
<Route index element={<Navigate to="qa/general" replace />} />
|
<Route index element={<Navigate to="qa/general" replace />} />
|
||||||
|
|
||||||
{/* 问答中心 */}
|
|
||||||
<Route path="qa/general" element={<GeneralQA />} />
|
<Route path="qa/general" element={<GeneralQA />} />
|
||||||
<Route
|
<Route
|
||||||
path="qa/expert-qa"
|
path="qa/expert-qa"
|
||||||
element={
|
element={
|
||||||
<GeneralQA
|
<GeneralQA
|
||||||
chatHeadTitle="专家问答"
|
chatHeadTitle="æ¶“æ’³î†é—‚瓟"
|
||||||
chatDesign="支持单轮RAG、多轮RAG、深度检索及结果对比"
|
chatDesign="é€îˆ›å¯”é—æ›¡ç–†RAG銆佸æžç”ŠAGéŠ†ä½¹ç¹æ´ï¸½î—…ç»±ãˆ å¼·ç¼æ’´ç‰ç€µè§„瘮"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{/* 任务管理 */}
|
<Route
|
||||||
|
path="qa/multi-agent-roundtable"
|
||||||
|
element={
|
||||||
|
<ChatRuntime>
|
||||||
|
<RoundtablePlanningPage />
|
||||||
|
</ChatRuntime>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
<Route path="task-management" element={<TaskManagement />}>
|
<Route path="task-management" element={<TaskManagement />}>
|
||||||
<Route index element={<Navigate to="xk-task-jc" replace />} />
|
<Route index element={<Navigate to="xk-task-jc" replace />} />
|
||||||
{/* XK任务 */}
|
|
||||||
<Route
|
<Route
|
||||||
path="xk-task-jc"
|
path="xk-task-jc"
|
||||||
element={<TaskXkFrom gopath="#/pageIndie/pageHome/pageSwrw" />}
|
element={<TaskXkFrom gopath="#/pageIndie/pageHome/pageSwrw" />}
|
||||||
@@ -71,7 +80,6 @@ export default function StrategyRoutes() {
|
|||||||
path="xk-task-dispatch"
|
path="xk-task-dispatch"
|
||||||
element={<TaskXkFrom gopath="#/pageIndie/pageJczl" />}
|
element={<TaskXkFrom gopath="#/pageIndie/pageJczl" />}
|
||||||
/>
|
/>
|
||||||
{/* pg中任务 */}
|
|
||||||
<Route
|
<Route
|
||||||
path="effect-task-pg"
|
path="effect-task-pg"
|
||||||
element={<TaskPgFrom gopath="task" />}
|
element={<TaskPgFrom gopath="task" />}
|
||||||
@@ -84,12 +92,11 @@ export default function StrategyRoutes() {
|
|||||||
path="effect-info-pg"
|
path="effect-info-pg"
|
||||||
element={<TaskPgFrom gopath="info" />}
|
element={<TaskPgFrom gopath="info" />}
|
||||||
/>
|
/>
|
||||||
{/* COH中任务 */}
|
|
||||||
<Route
|
<Route
|
||||||
path="plan-task-sentiment"
|
path="plan-task-sentiment"
|
||||||
element={
|
element={
|
||||||
<SentimentAnalyzes
|
<SentimentAnalyzes
|
||||||
title="3QFX"
|
title="三情分析"
|
||||||
category="规划任务"
|
category="规划任务"
|
||||||
subCategory="规划任务"
|
subCategory="规划任务"
|
||||||
/>
|
/>
|
||||||
@@ -99,7 +106,7 @@ export default function StrategyRoutes() {
|
|||||||
path="plan-task/plan-task-fx"
|
path="plan-task/plan-task-fx"
|
||||||
element={
|
element={
|
||||||
<TaskAnalyzes
|
<TaskAnalyzes
|
||||||
title="任务FX"
|
title="任务分析"
|
||||||
category="规划任务"
|
category="规划任务"
|
||||||
subCategory="规划任务"
|
subCategory="规划任务"
|
||||||
/>
|
/>
|
||||||
@@ -110,17 +117,16 @@ export default function StrategyRoutes() {
|
|||||||
element={
|
element={
|
||||||
<ActionAnalyzes
|
<ActionAnalyzes
|
||||||
title="xdfx"
|
title="xdfx"
|
||||||
category="规划任务"
|
category="ç‘™å‹«åžæµ 诲姟"
|
||||||
subCategory="规划任务"
|
subCategory="ç‘™å‹«åžæµ 诲姟"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{/* MNTY任务 */}
|
|
||||||
<Route path="mnty-task-mechanism" element={<XingdongTyPage />} />
|
<Route path="mnty-task-mechanism" element={<XingdongTyPage />} />
|
||||||
<Route path="mnty-task-plan" element={<FanganTyPage />} />
|
<Route path="mnty-task-plan" element={<FanganTyPage />} />
|
||||||
<Route path="mnty-task-zsty" element={<XXTyPage />} />
|
<Route path="mnty-task-zsty" element={<XXTyPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
{/* 资源管理 */}
|
|
||||||
<Route
|
<Route
|
||||||
path="resource-management/resource-network-actor"
|
path="resource-management/resource-network-actor"
|
||||||
element={<NetworkActorResourceManagement />}
|
element={<NetworkActorResourceManagement />}
|
||||||
@@ -131,16 +137,13 @@ export default function StrategyRoutes() {
|
|||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="resource-management/resource-evaluation-index"
|
path="resource-management/resource-evaluation-index"
|
||||||
element={
|
element={<TaskXkFrom gopath="#/pageIndie/pageZyjc/pageZyzl" />}
|
||||||
<TaskXkFrom gopath="#/pageIndie/pageZyjc/pageZyzl" />
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
{/* 轻应用 */}
|
|
||||||
<Route path="light-app/new-note" element={<LightAppNewNotePage />} />
|
<Route path="light-app/new-note" element={<LightAppNewNotePage />} />
|
||||||
<Route path="light-app/notes" element={<LightAppNoteListPage />} />
|
<Route path="light-app/notes" element={<LightAppNoteListPage />} />
|
||||||
<Route path="light-app/note-qa" element={<LightAppNoteQAPage />} />
|
<Route path="light-app/note-qa" element={<LightAppNoteQAPage />} />
|
||||||
|
|
||||||
{/* 对话 */}
|
|
||||||
<Route path="chats" element={<ChatsPage />} />
|
<Route path="chats" element={<ChatsPage />} />
|
||||||
<Route
|
<Route
|
||||||
path="chats/:thread_id"
|
path="chats/:thread_id"
|
||||||
@@ -151,7 +154,6 @@ export default function StrategyRoutes() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 智能体管理 */}
|
|
||||||
<Route path="agents" element={<AgentsPage />} />
|
<Route path="agents" element={<AgentsPage />} />
|
||||||
<Route path="agents/new" element={<NewAgentPage />} />
|
<Route path="agents/new" element={<NewAgentPage />} />
|
||||||
<Route
|
<Route
|
||||||
@@ -167,12 +169,10 @@ export default function StrategyRoutes() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 技能 / 记忆 */}
|
|
||||||
<Route path="skills" element={<SkillsPage />} />
|
<Route path="skills" element={<SkillsPage />} />
|
||||||
<Route path="skills/evolution" element={<SkillEvolutionPage />} />
|
<Route path="skills/evolution" element={<SkillEvolutionPage />} />
|
||||||
<Route path="memory" element={<MemoryPage />} />
|
<Route path="memory" element={<MemoryPage />} />
|
||||||
|
|
||||||
{/* 定时任务 */}
|
|
||||||
<Route
|
<Route
|
||||||
path="scheduled"
|
path="scheduled"
|
||||||
element={<Navigate to="/page/strategy/scheduled/tasks" replace />}
|
element={<Navigate to="/page/strategy/scheduled/tasks" replace />}
|
||||||
@@ -183,7 +183,6 @@ export default function StrategyRoutes() {
|
|||||||
element={<ScheduledTaskRunDetailPage />}
|
element={<ScheduledTaskRunDetailPage />}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 设置 / 管理 — 权限与 workspace 侧一致,非 admin 重定向到 chats/new */}
|
|
||||||
<Route
|
<Route
|
||||||
path="settings/recommended-questions"
|
path="settings/recommended-questions"
|
||||||
element={
|
element={
|
||||||
@@ -244,6 +243,26 @@ export default function StrategyRoutes() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route
|
||||||
|
path="admin/user-leaderboard"
|
||||||
|
element={
|
||||||
|
getStoredAuth()?.system_role === "admin" ? (
|
||||||
|
<AdminUserLeaderboardPage />
|
||||||
|
) : (
|
||||||
|
<Navigate to="/page/workspace/chats/new" replace />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="admin/user-leaderboard/settings"
|
||||||
|
element={
|
||||||
|
getStoredAuth()?.system_role === "admin" ? (
|
||||||
|
<AdminUserLeaderboardSettingsPage />
|
||||||
|
) : (
|
||||||
|
<Navigate to="/page/workspace/chats/new" replace />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="admin/user-activity"
|
path="admin/user-activity"
|
||||||
element={
|
element={
|
||||||
@@ -256,13 +275,7 @@ export default function StrategyRoutes() {
|
|||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="admin/tags"
|
path="admin/tags"
|
||||||
element={
|
element={<TagsPage />}
|
||||||
getStoredAuth()?.system_role === "admin" ? (
|
|
||||||
<TagsPage />
|
|
||||||
) : (
|
|
||||||
<Navigate to="/page/workspace/chats/new" replace />
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
</Routes>
|
</Routes>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import AdminSkillsPage from './AdminSkillsPage';
|
|||||||
import ScheduledTaskRunDetailPage from './ScheduledTaskRunDetailPage';
|
import ScheduledTaskRunDetailPage from './ScheduledTaskRunDetailPage';
|
||||||
import ScheduledTasksPage from './ScheduledTasksPage';
|
import ScheduledTasksPage from './ScheduledTasksPage';
|
||||||
import LlmMetricsPage from './LlmMetricsPage';
|
import LlmMetricsPage from './LlmMetricsPage';
|
||||||
|
import CheckpointMigrationPage from './CheckpointMigrationPage';
|
||||||
import MemoryPage from './MemoryPage';
|
import MemoryPage from './MemoryPage';
|
||||||
import PromptPrefixSettingsPage from './PromptPrefixSettingsPage';
|
import PromptPrefixSettingsPage from './PromptPrefixSettingsPage';
|
||||||
import PrivateSquareSettingsPage from './PrivateSquareSettingsPage';
|
import PrivateSquareSettingsPage from './PrivateSquareSettingsPage';
|
||||||
@@ -419,13 +420,9 @@ export default function WorkspaceRoutes({
|
|||||||
<Route
|
<Route
|
||||||
path="admin/tags"
|
path="admin/tags"
|
||||||
element={
|
element={
|
||||||
getStoredAuth()?.system_role === 'admin' ? (
|
<WorkspaceLayout {...layoutProps}>
|
||||||
<WorkspaceLayout {...layoutProps}>
|
<TagsPage />
|
||||||
<TagsPage />
|
</WorkspaceLayout>
|
||||||
</WorkspaceLayout>
|
|
||||||
) : (
|
|
||||||
<Navigate to="/page/workspace/chats/new" replace />
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
@@ -476,6 +473,18 @@ export default function WorkspaceRoutes({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route
|
||||||
|
path="settings/checkpoint-migration"
|
||||||
|
element={
|
||||||
|
getStoredAuth()?.system_role === 'admin' ? (
|
||||||
|
<WorkspaceLayout {...layoutProps}>
|
||||||
|
<CheckpointMigrationPage />
|
||||||
|
</WorkspaceLayout>
|
||||||
|
) : (
|
||||||
|
<Navigate to="/page/workspace/chats/new" replace />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
</Routes>
|
</Routes>
|
||||||
</RouteBaseProvider>
|
</RouteBaseProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -100,3 +100,37 @@ test("maps iframe model selection into stream context model_name", () => {
|
|||||||
model_name: "OpenAI3",
|
model_name: "OpenAI3",
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("maps externally uploaded files into stream additional_kwargs.files", () => {
|
||||||
|
const result = parseBrainyChatSubmitMessage({
|
||||||
|
source: "brainy-extension",
|
||||||
|
type: "brainy:chat-submit",
|
||||||
|
requestId: "iframe-789",
|
||||||
|
payload: {
|
||||||
|
text: "网摘",
|
||||||
|
prompt: "网摘",
|
||||||
|
uploadedFiles: [
|
||||||
|
{
|
||||||
|
filename: "LLM Wiki 接口说明.md",
|
||||||
|
size: "7002",
|
||||||
|
path: "/mnt/user-data/uploads/LLM Wiki 接口说明.md",
|
||||||
|
status: "uploaded",
|
||||||
|
artifact_url:
|
||||||
|
"/api/threads/445ca7a7-9737-44f0-8eea-6887776f4f9c/artifacts/mnt/user-data/uploads/LLM%20Wiki%20%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E.md",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.submitText, "网摘");
|
||||||
|
assert.deepEqual(result.additionalKwargs?.files, [
|
||||||
|
{
|
||||||
|
filename: "LLM Wiki 接口说明.md",
|
||||||
|
size: "7002",
|
||||||
|
path: "/mnt/user-data/uploads/LLM Wiki 接口说明.md",
|
||||||
|
status: "uploaded",
|
||||||
|
artifact_url:
|
||||||
|
"/api/threads/445ca7a7-9737-44f0-8eea-6887776f4f9c/artifacts/mnt/user-data/uploads/LLM%20Wiki%20%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E.md",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -26,6 +26,14 @@ type BrainyModelSelection = {
|
|||||||
value?: string;
|
value?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type BrainyUploadedFile = {
|
||||||
|
filename?: string;
|
||||||
|
size?: string | number;
|
||||||
|
path?: string;
|
||||||
|
status?: string;
|
||||||
|
artifact_url?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type BrainyChatSubmitMessage = {
|
export type BrainyChatSubmitMessage = {
|
||||||
source?: string;
|
source?: string;
|
||||||
type?: string;
|
type?: string;
|
||||||
@@ -35,6 +43,7 @@ export type BrainyChatSubmitMessage = {
|
|||||||
pageContext?: BrainyPageContext;
|
pageContext?: BrainyPageContext;
|
||||||
screenshot?: BrainyScreenshot;
|
screenshot?: BrainyScreenshot;
|
||||||
model?: BrainyModelSelection;
|
model?: BrainyModelSelection;
|
||||||
|
uploadedFiles?: BrainyUploadedFile[];
|
||||||
};
|
};
|
||||||
requestId?: string;
|
requestId?: string;
|
||||||
};
|
};
|
||||||
@@ -253,6 +262,36 @@ function buildScreenshotFileParts(
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeUploadedFiles(
|
||||||
|
uploadedFiles: BrainyUploadedFile[] | undefined,
|
||||||
|
): Record<string, unknown>[] {
|
||||||
|
if (!Array.isArray(uploadedFiles)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return uploadedFiles
|
||||||
|
.map((file) => {
|
||||||
|
const filename = trimToUndefined(file.filename);
|
||||||
|
if (!filename) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const size = String(file.size ?? "0");
|
||||||
|
const path = trimToUndefined(file.path);
|
||||||
|
const status = trimToUndefined(file.status);
|
||||||
|
const artifactUrl = trimToUndefined(file.artifact_url);
|
||||||
|
|
||||||
|
return {
|
||||||
|
filename,
|
||||||
|
size,
|
||||||
|
...(path ? { path } : {}),
|
||||||
|
...(status ? { status } : {}),
|
||||||
|
...(artifactUrl ? { artifact_url: artifactUrl } : {}),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter((file): file is Record<string, unknown> => file !== null);
|
||||||
|
}
|
||||||
|
|
||||||
export function parseBrainyChatSubmitMessage(
|
export function parseBrainyChatSubmitMessage(
|
||||||
data: BrainyChatSubmitMessage,
|
data: BrainyChatSubmitMessage,
|
||||||
): ParsedBrainyChatSubmitMessage {
|
): ParsedBrainyChatSubmitMessage {
|
||||||
@@ -268,6 +307,7 @@ export function parseBrainyChatSubmitMessage(
|
|||||||
});
|
});
|
||||||
const requestId = trimToUndefined(data.requestId);
|
const requestId = trimToUndefined(data.requestId);
|
||||||
const modelName = trimToUndefined(data.payload?.model?.value);
|
const modelName = trimToUndefined(data.payload?.model?.value);
|
||||||
|
const uploadedFiles = normalizeUploadedFiles(data.payload?.uploadedFiles);
|
||||||
|
|
||||||
const iframeContext: Record<string, unknown> = {};
|
const iframeContext: Record<string, unknown> = {};
|
||||||
if (requestId) {
|
if (requestId) {
|
||||||
@@ -281,6 +321,13 @@ export function parseBrainyChatSubmitMessage(
|
|||||||
submitText,
|
submitText,
|
||||||
files,
|
files,
|
||||||
...(Object.keys(iframeContext).length > 0 ? { iframeContext } : {}),
|
...(Object.keys(iframeContext).length > 0 ? { iframeContext } : {}),
|
||||||
...(promptPrefix ? { additionalKwargs: { prompt_prefix: promptPrefix } } : {}),
|
...(promptPrefix || uploadedFiles.length > 0
|
||||||
|
? {
|
||||||
|
additionalKwargs: {
|
||||||
|
...(promptPrefix ? { prompt_prefix: promptPrefix } : {}),
|
||||||
|
...(uploadedFiles.length > 0 ? { files: uploadedFiles } : {}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -22,6 +22,12 @@ export interface ChainCreatePayload {
|
|||||||
title: string;
|
title: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
seats: ChainSeat[];
|
seats: ChainSeat[];
|
||||||
|
/** Optional layered orchestration (agent_id groups). null/absent = linear. */
|
||||||
|
stages?: string[][] | null;
|
||||||
|
/** Optional per-stage goals aligned to `stages` (dag-only). null = none. */
|
||||||
|
stageGoals?: (string | null)[] | null;
|
||||||
|
/** Optional coordinator orchestration prompt (dag-only). null/"" = none. */
|
||||||
|
coordinatorPrompt?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Partial update — send only what changed. */
|
/** Partial update — send only what changed. */
|
||||||
@@ -29,8 +35,19 @@ export interface ChainUpdatePayload {
|
|||||||
title?: string;
|
title?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
seats?: ChainSeat[];
|
seats?: ChainSeat[];
|
||||||
|
/** Send `null` to clear layering back to linear; omit to leave unchanged. */
|
||||||
|
stages?: string[][] | null;
|
||||||
|
/** Per-stage goals aligned to `stages`; send `null` to clear, omit to leave. */
|
||||||
|
stageGoals?: (string | null)[] | null;
|
||||||
|
/** 写给总控的编排提示;send `null`/"" to clear, omit to leave. */
|
||||||
|
coordinatorPrompt?: string | null;
|
||||||
|
/** 发布开关:true 发布为公共 / false 取消发布;omit 不改。仅 owner 生效。 */
|
||||||
|
isPublic?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 列表筛选范围:`mine` = 我的;`public` = 所有已发布的公共链条。 */
|
||||||
|
export type ChainScope = "mine" | "public";
|
||||||
|
|
||||||
const BASE = () => `${getBackendBaseURL()}/api/roundtable-chains`;
|
const BASE = () => `${getBackendBaseURL()}/api/roundtable-chains`;
|
||||||
|
|
||||||
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||||
@@ -50,6 +67,11 @@ interface ServerChain {
|
|||||||
title: string;
|
title: string;
|
||||||
description: string | null;
|
description: string | null;
|
||||||
seats: ChainSeat[];
|
seats: ChainSeat[];
|
||||||
|
stages?: string[][] | null;
|
||||||
|
stage_goals?: (string | null)[] | null;
|
||||||
|
coordinator_prompt?: string | null;
|
||||||
|
is_public?: boolean;
|
||||||
|
is_mine?: boolean;
|
||||||
created_at: string | null;
|
created_at: string | null;
|
||||||
updated_at: string | null;
|
updated_at: string | null;
|
||||||
}
|
}
|
||||||
@@ -60,6 +82,12 @@ function toChain(s: ServerChain): BusinessChain {
|
|||||||
title: s.title ?? "",
|
title: s.title ?? "",
|
||||||
description: s.description ?? undefined,
|
description: s.description ?? undefined,
|
||||||
seats: Array.isArray(s.seats) ? s.seats : [],
|
seats: Array.isArray(s.seats) ? s.seats : [],
|
||||||
|
stages: Array.isArray(s.stages) ? s.stages : null,
|
||||||
|
stageGoals: Array.isArray(s.stage_goals) ? s.stage_goals : null,
|
||||||
|
coordinatorPrompt: s.coordinator_prompt ?? null,
|
||||||
|
isPublic: s.is_public ?? false,
|
||||||
|
// 后端缺省时按「我的」处理(向后兼容旧响应)。
|
||||||
|
isMine: s.is_mine ?? true,
|
||||||
createdAt: s.created_at ?? undefined,
|
createdAt: s.created_at ?? undefined,
|
||||||
updatedAt: s.updated_at ?? undefined,
|
updatedAt: s.updated_at ?? undefined,
|
||||||
};
|
};
|
||||||
@@ -71,6 +99,9 @@ function fromCreate(p: ChainCreatePayload) {
|
|||||||
title: p.title,
|
title: p.title,
|
||||||
...(p.description !== undefined ? { description: p.description } : {}),
|
...(p.description !== undefined ? { description: p.description } : {}),
|
||||||
seats: p.seats,
|
seats: p.seats,
|
||||||
|
...(p.stages !== undefined ? { stages: p.stages } : {}),
|
||||||
|
...(p.stageGoals !== undefined ? { stage_goals: p.stageGoals } : {}),
|
||||||
|
...(p.coordinatorPrompt !== undefined ? { coordinator_prompt: p.coordinatorPrompt } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,18 +110,34 @@ function fromUpdate(p: ChainUpdatePayload) {
|
|||||||
if (p.title !== undefined) out.title = p.title;
|
if (p.title !== undefined) out.title = p.title;
|
||||||
if (p.description !== undefined) out.description = p.description;
|
if (p.description !== undefined) out.description = p.description;
|
||||||
if (p.seats !== undefined) out.seats = p.seats;
|
if (p.seats !== undefined) out.seats = p.seats;
|
||||||
|
// Forward stages even when explicitly null (clears layering server-side).
|
||||||
|
if (p.stages !== undefined) out.stages = p.stages;
|
||||||
|
// Forward stage goals even when explicitly null (clears goals server-side).
|
||||||
|
if (p.stageGoals !== undefined) out.stage_goals = p.stageGoals;
|
||||||
|
if (p.coordinatorPrompt !== undefined) out.coordinator_prompt = p.coordinatorPrompt;
|
||||||
|
if (p.isPublic !== undefined) out.is_public = p.isPublic;
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── CRUD ────────────────────────────────────────────────────────────────────
|
// ── CRUD ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
/** List the current user's chains, newest first. */
|
/**
|
||||||
export async function listChains(): Promise<BusinessChain[]> {
|
* List chains, newest first. `scope`:
|
||||||
const res = await apiFetch(BASE(), { method: "GET" });
|
* - `"mine"`(默认):当前用户自己的链条;
|
||||||
|
* - `"public"`:所有已发布的公共链条(任何账号可见 / 可选入研讨)。
|
||||||
|
*/
|
||||||
|
export async function listChains(scope: ChainScope = "mine"): Promise<BusinessChain[]> {
|
||||||
|
const url = scope === "public" ? `${BASE()}?scope=public` : BASE();
|
||||||
|
const res = await apiFetch(url, { method: "GET" });
|
||||||
const data = await readJson<{ chains: ServerChain[] }>(res, "list chains");
|
const data = await readJson<{ chains: ServerChain[] }>(res, "list chains");
|
||||||
return (data.chains ?? []).map(toChain);
|
return (data.chains ?? []).map(toChain);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 发布 / 取消发布一条链条(仅 owner 生效)。返回更新后的链条,404 返回 null。 */
|
||||||
|
export async function setChainPublic(id: string, isPublic: boolean): Promise<BusinessChain | null> {
|
||||||
|
return updateChain(id, { isPublic });
|
||||||
|
}
|
||||||
|
|
||||||
/** Fetch one chain. Returns null on 404. */
|
/** Fetch one chain. Returns null on 404. */
|
||||||
export async function getChain(id: string): Promise<BusinessChain | null> {
|
export async function getChain(id: string): Promise<BusinessChain | null> {
|
||||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "GET" });
|
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "GET" });
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { getBackendBaseURL } from "@/core/config";
|
|||||||
|
|
||||||
import type { IntentSummary } from "@/roundtable-planning/api/intent";
|
import type { IntentSummary } from "@/roundtable-planning/api/intent";
|
||||||
import type { ThreadIdMap } from "@/roundtable-planning/api/multi-agent";
|
import type { ThreadIdMap } from "@/roundtable-planning/api/multi-agent";
|
||||||
|
import type { OrchestrationPlan } from "@/roundtable-planning/lib/dag-types";
|
||||||
import type { JobStatus } from "@/roundtable-planning/lib/job-types";
|
import type { JobStatus } from "@/roundtable-planning/lib/job-types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -31,6 +32,8 @@ export interface DraftStep1Snapshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface DraftStep2Snapshot {
|
export interface DraftStep2Snapshot {
|
||||||
|
activeRunId?: string | null;
|
||||||
|
runs?: DraftStep2RunSnapshot[];
|
||||||
/**
|
/**
|
||||||
* The seats actually selected for this session. Restored on load so the
|
* The seats actually selected for this session. Restored on load so the
|
||||||
* Step 2/3 「参与角色」panel shows the chosen agents instead of the default 6.
|
* Step 2/3 「参与角色」panel shows the chosen agents instead of the default 6.
|
||||||
@@ -48,13 +51,50 @@ export interface DraftStep2Snapshot {
|
|||||||
seatStubMessages?: Record<string, unknown[]>;
|
seatStubMessages?: Record<string, unknown[]>;
|
||||||
/**
|
/**
|
||||||
* Step 2 orchestration mode (2026-06 business chains). recommend = leader
|
* Step 2 orchestration mode (2026-06 business chains). recommend = leader
|
||||||
* dispatches freely; chain = dispatch follows the saved business chain order.
|
* dispatches freely; chain = dispatch follows the saved business chain order;
|
||||||
* Optional — drafts saved before this won't carry it (hydrate defaults to
|
* dag = layered Stage DAG (stage-internal parallel, stage-to-stage serial,
|
||||||
* "recommend").
|
* see `lib/dag-types.ts`). Optional — drafts saved before this won't carry it
|
||||||
|
* (hydrate defaults to "recommend").
|
||||||
*/
|
*/
|
||||||
orchestrationMode?: "recommend" | "chain";
|
orchestrationMode?: "recommend" | "chain" | "dag";
|
||||||
/** Source business chain (display only), when `orchestrationMode === "chain"`. */
|
/** Source business chain (display only), when `orchestrationMode === "chain"`. */
|
||||||
chain?: { id: string; title: string } | null;
|
chain?: { id: string; title: string } | null;
|
||||||
|
/**
|
||||||
|
* Layered DAG plan, when `orchestrationMode === "dag"`. Persisted so a reloaded
|
||||||
|
* draft restores the编排. Optional — null/absent for non-dag drafts. Old `chain`
|
||||||
|
* drafts are converted on read via `chainToDagPlan` (compat, original draft
|
||||||
|
* untouched).
|
||||||
|
*/
|
||||||
|
orchestrationPlan?: OrchestrationPlan | null;
|
||||||
|
/**
|
||||||
|
* dag 执行子模式:fast(并行双列禁写)/ sandbox(并行单列可写、沙箱跟随)。
|
||||||
|
* 仅 `orchestrationMode === "dag"` 有意义;缺省 fast。
|
||||||
|
*/
|
||||||
|
dagExecMode?: "fast" | "sandbox";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DraftStep2RunSnapshot {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
createdAt: string;
|
||||||
|
source: "initial" | "recommend" | "chain" | "dag" | "manual";
|
||||||
|
selectedAgents?: Array<{ agent_id: string; name: string }>;
|
||||||
|
threadIds: ThreadIdMap | null;
|
||||||
|
coordinatorName: string | null;
|
||||||
|
step2RoundtableDialogues: unknown[];
|
||||||
|
lastLeaderContent: string;
|
||||||
|
hasConsensus: boolean;
|
||||||
|
consensusPercentage: number;
|
||||||
|
budgetLimit: number;
|
||||||
|
seatStubMessages?: Record<string, unknown[]>;
|
||||||
|
orchestrationMode?: "recommend" | "chain" | "dag";
|
||||||
|
chain?: { id: string; title: string } | null;
|
||||||
|
orchestrationPlan?: OrchestrationPlan | null;
|
||||||
|
/** dag 执行子模式:fast / sandbox(见 DraftStep2Snapshot.dagExecMode)。 */
|
||||||
|
dagExecMode?: "fast" | "sandbox";
|
||||||
|
step3?: DraftStep3Snapshot | null;
|
||||||
|
jobId?: string | null;
|
||||||
|
jobStatus?: JobStatus | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -203,6 +203,30 @@ export interface StreamMultiAgentRequest {
|
|||||||
newMessage: string;
|
newMessage: string;
|
||||||
model?: string;
|
model?: string;
|
||||||
skillStopNames?: string[];
|
skillStopNames?: string[];
|
||||||
|
/**
|
||||||
|
* 仅 leader 用。置 true 表示这是「派活后让总控判断继续/综合」的轮次:后端会把各已交付
|
||||||
|
* 席位的**完整交付正文**额外注入总控输入,供其写最终方案。派活决策轮(首轮等)传 false/省略,
|
||||||
|
* 后端只给摘要,使总控上下文精简、响应快。
|
||||||
|
*/
|
||||||
|
synthesisMode?: boolean;
|
||||||
|
/**
|
||||||
|
* 仅 leader 用。置 true 抑制「把总控本轮输入广播给各席位 thread」的预广播。DAG「每 stage
|
||||||
|
* 派活轮」置真——否则总控的派活 prompt 会进席位历史,弱模型据此模仿派活。后端缺省 false。
|
||||||
|
*/
|
||||||
|
suppressPreBroadcast?: boolean;
|
||||||
|
/**
|
||||||
|
* 仅 special 用。置 true 表示这是 DAG 并行批次里的席位:后端按 `seat_parallel`
|
||||||
|
* run policy **禁用** write_file / bash / str_replace / present_files 等写文件 /
|
||||||
|
* 沙箱工具(§4),避免同批多席位并发抢同一沙箱。产物以消息正文交付。后端缺失
|
||||||
|
* 该字段时按 false 处理(普通 seat policy),旧前端不受影响。
|
||||||
|
*/
|
||||||
|
parallelNoFile?: boolean;
|
||||||
|
/**
|
||||||
|
* 仅 special 用。前序席位的**完整交付** `[{name, content}]`。后端注入 run context
|
||||||
|
* (`roundtable_peer_deliveries`),席位用 `read_peer_delivery` 工具**按需**取全文
|
||||||
|
* (平时只看广播摘要)。不进 prompt → 不调工具就不耗 token。
|
||||||
|
*/
|
||||||
|
peerDeliveries?: Array<{ name: string; content: string }>;
|
||||||
signal?: AbortSignal;
|
signal?: AbortSignal;
|
||||||
/** Fires for every non-status data frame the upstream emits. */
|
/** Fires for every non-status data frame the upstream emits. */
|
||||||
onUpstreamFrame?: (frame: unknown) => void;
|
onUpstreamFrame?: (frame: unknown) => void;
|
||||||
@@ -415,6 +439,14 @@ export async function streamMultiAgent(
|
|||||||
new_message: req.newMessage,
|
new_message: req.newMessage,
|
||||||
model: req.model,
|
model: req.model,
|
||||||
skill_stop_names: req.skillStopNames ?? [],
|
skill_stop_names: req.skillStopNames ?? [],
|
||||||
|
// 仅 leader 用;综合轮让后端注入各席位完整交付正文。省略 → 后端按 false 处理。
|
||||||
|
synthesis_mode: req.synthesisMode ?? false,
|
||||||
|
// 仅 leader 用;DAG 派活轮抑制预广播,避免总控派活 prompt 污染席位 thread。省略 → false。
|
||||||
|
suppress_pre_broadcast: req.suppressPreBroadcast ?? false,
|
||||||
|
// 仅 special 用;DAG 并行批次禁写文件(seat_parallel policy)。省略 → 后端按 false 处理。
|
||||||
|
parallel_no_file: req.parallelNoFile ?? false,
|
||||||
|
// 仅 special 用;前序席位完整交付,后端注入 context 供 read_peer_delivery 按需取全文。
|
||||||
|
peer_deliveries: req.peerDeliveries ?? [],
|
||||||
}),
|
}),
|
||||||
signal: req.signal,
|
signal: req.signal,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
|||||||
import {
|
import {
|
||||||
isTerminalJobStatus,
|
isTerminalJobStatus,
|
||||||
type DispatchChainNode,
|
type DispatchChainNode,
|
||||||
|
type JobDialogue,
|
||||||
type RoundtableJob,
|
type RoundtableJob,
|
||||||
type StartJobPayload,
|
type StartJobPayload,
|
||||||
} from "../lib/job-types";
|
} from "../lib/job-types";
|
||||||
@@ -65,6 +66,8 @@ function mapJob(raw: Record<string, unknown>): RoundtableJob {
|
|||||||
orchestrationMode: (raw.orchestrationMode as RoundtableJob["orchestrationMode"]) ?? "recommend",
|
orchestrationMode: (raw.orchestrationMode as RoundtableJob["orchestrationMode"]) ?? "recommend",
|
||||||
chain: (raw.chain as RoundtableJob["chain"]) ?? null,
|
chain: (raw.chain as RoundtableJob["chain"]) ?? null,
|
||||||
error: (raw.error as string | null) ?? null,
|
error: (raw.error as string | null) ?? null,
|
||||||
|
dialogues: Array.isArray(raw.dialogues) ? (raw.dialogues as JobDialogue[]) : [],
|
||||||
|
step3: (raw.step3 as RoundtableJob["step3"]) ?? null,
|
||||||
createdAt: (raw.createdAt as string | null) ?? null,
|
createdAt: (raw.createdAt as string | null) ?? null,
|
||||||
updatedAt: (raw.updatedAt as string | null) ?? null,
|
updatedAt: (raw.updatedAt as string | null) ?? null,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
/**
|
||||||
|
* 智能体详情抽屉(右侧 Sheet)。
|
||||||
|
*
|
||||||
|
* 业务链条配置页:左栏候选卡片点击卡片本体、右栏席位点「查看详情」都打开这个抽屉,
|
||||||
|
* 展示该智能体的详情(与「智能体」详情页展示的内容差不多):名称 / 模型 / 描述 /
|
||||||
|
* 标签 / 技能 + 工具组 / 人设(SOUL.md)。
|
||||||
|
*
|
||||||
|
* 详情按需拉取:`useAgent(open ? agentId : null)` —— 抽屉打开时才请求 `GET /api/agents/{id}`
|
||||||
|
* (该接口才返回 soul),关闭不请求。字段渲染对齐 `components/workspace/agents/agent-card.tsx`。
|
||||||
|
*/
|
||||||
|
import { Bot, Globe, Loader2, Lock } from "lucide-react";
|
||||||
|
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import {
|
||||||
|
Sheet,
|
||||||
|
SheetContent,
|
||||||
|
SheetDescription,
|
||||||
|
SheetHeader,
|
||||||
|
SheetTitle,
|
||||||
|
} from "@/components/ui/sheet";
|
||||||
|
import { TagChipList } from "@/components/workspace/tags/tag-chip";
|
||||||
|
import { useAgent } from "@/core/agents";
|
||||||
|
import { desensitize } from "@/lib/desensitize";
|
||||||
|
|
||||||
|
export function AgentDetailSheet({
|
||||||
|
agentId,
|
||||||
|
/** 卡片/席位上的名称快照,详情还没拉回来时先用它占位。 */
|
||||||
|
fallbackName,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
}: {
|
||||||
|
agentId: string | null;
|
||||||
|
fallbackName?: string;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}) {
|
||||||
|
// 抽屉打开时才拉详情(含 soul);关闭传 null 让 useAgent 不发请求。
|
||||||
|
const { agent, isLoading } = useAgent(open ? agentId : null);
|
||||||
|
const name = agent?.name || fallbackName || agentId || "";
|
||||||
|
const skillItems = agent?.skills ?? [];
|
||||||
|
const toolGroups = agent?.tool_groups ?? [];
|
||||||
|
const hasSkillsOrTools = skillItems.length > 0 || toolGroups.length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||||
|
<SheetContent side="right" className="w-full gap-0 p-0 sm:max-w-md">
|
||||||
|
<SheetHeader className="border-b border-border px-5 py-4">
|
||||||
|
<SheetTitle className="flex items-center gap-2.5">
|
||||||
|
<span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">
|
||||||
|
<Bot className="size-4" />
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 flex-1 truncate text-base font-bold">{name}</span>
|
||||||
|
{agent?.model && (
|
||||||
|
<Badge variant="outline" className="shrink-0 text-[10px]">
|
||||||
|
{desensitize(agent.model)}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</SheetTitle>
|
||||||
|
<SheetDescription className="sr-only">智能体详情</SheetDescription>
|
||||||
|
</SheetHeader>
|
||||||
|
|
||||||
|
<div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4 text-sm">
|
||||||
|
{isLoading && !agent ? (
|
||||||
|
<div className="flex items-center gap-2 py-8 text-muted-foreground">
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
正在加载详情…
|
||||||
|
</div>
|
||||||
|
) : !agent ? (
|
||||||
|
<div className="py-8 text-center text-muted-foreground">
|
||||||
|
未找到该智能体的详情(可能已被删除)。
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* 状态徽标 */}
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
|
{agent.builtin && (
|
||||||
|
<Badge variant="secondary" className="text-[10px]">内置</Badge>
|
||||||
|
)}
|
||||||
|
{agent.published && (
|
||||||
|
<Badge variant="outline" className="gap-1 text-[10px]">
|
||||||
|
<Globe className="size-3" />
|
||||||
|
已发布
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{agent.is_private && (
|
||||||
|
<Badge variant="outline" className="gap-1 text-[10px]">
|
||||||
|
<Lock className="size-3" />
|
||||||
|
私密
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 描述 */}
|
||||||
|
<section className="space-y-1.5">
|
||||||
|
<h4 className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
|
||||||
|
描述
|
||||||
|
</h4>
|
||||||
|
<p className="whitespace-pre-wrap leading-relaxed text-foreground">
|
||||||
|
{agent.description?.trim() || "(无描述)"}
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* 标签 */}
|
||||||
|
{agent.tags && agent.tags.length > 0 && (
|
||||||
|
<section className="space-y-1.5">
|
||||||
|
<h4 className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
|
||||||
|
标签
|
||||||
|
</h4>
|
||||||
|
<TagChipList tags={agent.tags} />
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 技能 / 工具组 */}
|
||||||
|
{hasSkillsOrTools && (
|
||||||
|
<section className="space-y-1.5">
|
||||||
|
<h4 className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
|
||||||
|
技能与工具
|
||||||
|
</h4>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{toolGroups.map((group) => (
|
||||||
|
<Badge key={`tg:${group}`} variant="outline" className="text-xs">
|
||||||
|
{desensitize(group)}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
{skillItems.map((skill) => (
|
||||||
|
<Badge key={`sk:${skill}`} variant="secondary" className="text-xs">
|
||||||
|
{desensitize(skill)}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 人设(SOUL.md) */}
|
||||||
|
{agent.soul?.trim() && (
|
||||||
|
<section className="space-y-1.5">
|
||||||
|
<h4 className="text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
|
||||||
|
人设
|
||||||
|
</h4>
|
||||||
|
<pre className="whitespace-pre-wrap break-words rounded-md border border-border bg-muted/30 p-3 text-[12px] leading-relaxed text-foreground">
|
||||||
|
{agent.soul}
|
||||||
|
</pre>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,20 @@
|
|||||||
import React, { useCallback, useEffect, useState } from "react";
|
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
import ReactMarkdown from "react-markdown";
|
import ReactMarkdown from "react-markdown";
|
||||||
import remarkGfm from "remark-gfm";
|
import remarkGfm from "remark-gfm";
|
||||||
import { Download, FileText, Loader2, X } from "lucide-react";
|
import { Download, FileText, Loader2, X } from "lucide-react";
|
||||||
|
|
||||||
import { apiFetch } from "@/core/api/fetch-client";
|
import { apiFetch } from "@/core/api/fetch-client";
|
||||||
|
import {
|
||||||
|
downloadMermaidSvgFile,
|
||||||
|
isMermaidFile,
|
||||||
|
renderMermaidToSvg,
|
||||||
|
} from "@/core/utils/mermaid";
|
||||||
|
import {
|
||||||
|
createMarkdownAnchorResolver,
|
||||||
|
isInPageAnchor,
|
||||||
|
scrollToInPageAnchor,
|
||||||
|
} from "@/core/utils/markdown";
|
||||||
import { buildArtifactDownloadUrl } from "@/roundtable-planning/api/multi-agent";
|
import { buildArtifactDownloadUrl } from "@/roundtable-planning/api/multi-agent";
|
||||||
|
|
||||||
interface ArtifactPreviewModalProps {
|
interface ArtifactPreviewModalProps {
|
||||||
@@ -18,15 +29,32 @@ interface ArtifactPreviewModalProps {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MARKDOWN_COMPONENTS = {
|
function extractTextFromChildren(children: ReactNode): string {
|
||||||
|
if (typeof children === "string" || typeof children === "number") return String(children);
|
||||||
|
if (Array.isArray(children)) return children.map(extractTextFromChildren).join("");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMarkdownComponents(content: string) {
|
||||||
|
const anchorResolver = createMarkdownAnchorResolver(content);
|
||||||
|
const heading = (level: 1 | 2 | 3 | 4 | 5 | 6, className: string) => {
|
||||||
|
const Tag = `h${level}` as const;
|
||||||
|
return ({ children, id }: any) => (
|
||||||
|
<Tag id={id ?? anchorResolver.getHeadingId(level, extractTextFromChildren(children))} className={className}>
|
||||||
|
{children}
|
||||||
|
</Tag>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
p: ({ children }: any) => <p className="my-1.5 whitespace-pre-wrap leading-relaxed">{children}</p>,
|
p: ({ children }: any) => <p className="my-1.5 whitespace-pre-wrap leading-relaxed">{children}</p>,
|
||||||
ul: ({ children }: any) => <ul className="list-disc pl-5 my-1.5 space-y-1">{children}</ul>,
|
ul: ({ children }: any) => <ul className="list-disc pl-5 my-1.5 space-y-1">{children}</ul>,
|
||||||
ol: ({ children }: any) => <ol className="list-decimal pl-5 my-1.5 space-y-1">{children}</ol>,
|
ol: ({ children }: any) => <ol className="list-decimal pl-5 my-1.5 space-y-1">{children}</ol>,
|
||||||
li: ({ children }: any) => <li className="leading-snug">{children}</li>,
|
li: ({ children }: any) => <li className="leading-snug">{children}</li>,
|
||||||
h1: ({ children }: any) => <h1 className="text-base font-bold mt-3 mb-2">{children}</h1>,
|
h1: heading(1, "text-base font-bold mt-3 mb-2 scroll-mt-4"),
|
||||||
h2: ({ children }: any) => <h2 className="text-sm font-bold mt-3 mb-1.5">{children}</h2>,
|
h2: heading(2, "text-sm font-bold mt-3 mb-1.5 scroll-mt-4"),
|
||||||
h3: ({ children }: any) => <h3 className="text-xs font-bold mt-2 mb-1">{children}</h3>,
|
h3: heading(3, "text-xs font-bold mt-2 mb-1 scroll-mt-4"),
|
||||||
h4: ({ children }: any) => <h4 className="text-xs font-bold mt-1.5 mb-1">{children}</h4>,
|
h4: heading(4, "text-xs font-bold mt-1.5 mb-1 scroll-mt-4"),
|
||||||
strong: ({ children }: any) => <strong className="font-bold text-slate-900">{children}</strong>,
|
strong: ({ children }: any) => <strong className="font-bold text-slate-900">{children}</strong>,
|
||||||
em: ({ children }: any) => <em className="italic">{children}</em>,
|
em: ({ children }: any) => <em className="italic">{children}</em>,
|
||||||
code: ({ children, className }: any) => {
|
code: ({ children, className }: any) => {
|
||||||
@@ -43,24 +71,56 @@ const MARKDOWN_COMPONENTS = {
|
|||||||
blockquote: ({ children }: any) => (
|
blockquote: ({ children }: any) => (
|
||||||
<blockquote className="border-l-2 border-slate-300 pl-3 my-2 text-slate-600 italic">{children}</blockquote>
|
<blockquote className="border-l-2 border-slate-300 pl-3 my-2 text-slate-600 italic">{children}</blockquote>
|
||||||
),
|
),
|
||||||
a: ({ children, href }: any) => (
|
a: ({ children, href }: any) => {
|
||||||
<a href={href} target="_blank" rel="noopener noreferrer" className="text-primary underline hover:opacity-80">
|
const resolvedHref = anchorResolver.resolveHref(href, extractTextFromChildren(children));
|
||||||
{children}
|
if (resolvedHref === null) {
|
||||||
</a>
|
return (
|
||||||
),
|
<span
|
||||||
|
className="text-primary/80 underline decoration-dotted underline-offset-2 cursor-not-allowed"
|
||||||
|
title="未在当前 Markdown 中找到对应章节"
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const finalHref = resolvedHref ?? href;
|
||||||
|
const isExternal = typeof href === "string" && /^https?:\/\//i.test(href);
|
||||||
|
return (
|
||||||
|
<a
|
||||||
|
href={finalHref}
|
||||||
|
target={isExternal ? "_blank" : undefined}
|
||||||
|
rel={isExternal ? "noopener noreferrer" : undefined}
|
||||||
|
className="text-primary underline hover:opacity-80"
|
||||||
|
onClick={(event) => {
|
||||||
|
if (isInPageAnchor(finalHref)) {
|
||||||
|
event.preventDefault();
|
||||||
|
scrollToInPageAnchor(event.currentTarget, finalHref);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
},
|
||||||
table: ({ children }: any) => <table className="my-2 border-collapse text-[12px] w-full">{children}</table>,
|
table: ({ children }: any) => <table className="my-2 border-collapse text-[12px] w-full">{children}</table>,
|
||||||
th: ({ children }: any) => (
|
th: ({ children }: any) => (
|
||||||
<th className="border border-slate-300 px-2 py-1 bg-slate-50 font-bold text-left">{children}</th>
|
<th className="border border-slate-300 px-2 py-1 bg-slate-50 font-bold text-left">{children}</th>
|
||||||
),
|
),
|
||||||
td: ({ children }: any) => <td className="border border-slate-200 px-2 py-1">{children}</td>,
|
td: ({ children }: any) => <td className="border border-slate-200 px-2 py-1">{children}</td>,
|
||||||
hr: () => <hr className="my-3 border-slate-200" />,
|
hr: () => <hr className="my-3 border-slate-200" />,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function isMarkdown(mimeType: string | null, name: string): boolean {
|
function isMarkdown(mimeType: string | null, name: string): boolean {
|
||||||
if (mimeType === "text/markdown") return true;
|
if (mimeType === "text/markdown") return true;
|
||||||
return /\.(md|markdown)$/i.test(name);
|
return /\.(md|markdown)$/i.test(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isMermaid(mimeType: string | null, name: string): boolean {
|
||||||
|
if (mimeType === "text/vnd.mermaid") return true;
|
||||||
|
return isMermaidFile(name);
|
||||||
|
}
|
||||||
|
|
||||||
export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
|
export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
|
||||||
threadId,
|
threadId,
|
||||||
path,
|
path,
|
||||||
@@ -71,6 +131,7 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
|
|||||||
const [content, setContent] = useState<string | null>(null);
|
const [content, setContent] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState<boolean>(true);
|
const [loading, setLoading] = useState<boolean>(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [mermaidSvg, setMermaidSvg] = useState<string | null>(null);
|
||||||
|
|
||||||
// Esc closes the modal. Attached once per mount.
|
// Esc closes the modal. Attached once per mount.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -116,11 +177,42 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
|
|||||||
|
|
||||||
const handleDownload = useCallback(() => {
|
const handleDownload = useCallback(() => {
|
||||||
if (typeof window === "undefined") return;
|
if (typeof window === "undefined") return;
|
||||||
|
if (isMermaid(mimeType, name) && content) {
|
||||||
|
void downloadMermaidSvgFile(content, name).catch((err) => {
|
||||||
|
setError((err as Error).message);
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
const url = buildArtifactDownloadUrl(threadId, path, { download: true });
|
const url = buildArtifactDownloadUrl(threadId, path, { download: true });
|
||||||
window.open(url, "_blank", "noopener,noreferrer");
|
window.open(url, "_blank", "noopener,noreferrer");
|
||||||
}, [threadId, path]);
|
}, [content, mimeType, name, path, threadId]);
|
||||||
|
|
||||||
const renderAsMarkdown = isMarkdown(mimeType, name);
|
const renderAsMarkdown = isMarkdown(mimeType, name);
|
||||||
|
const renderAsMermaid = isMermaid(mimeType, name);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!renderAsMermaid || !content) {
|
||||||
|
setMermaidSvg(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cancelled = false;
|
||||||
|
void renderMermaidToSvg(content)
|
||||||
|
.then((svg) => {
|
||||||
|
if (!cancelled) setMermaidSvg(svg);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
if (!cancelled) setError((err as Error).message);
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [content, renderAsMermaid]);
|
||||||
|
const markdownComponents = useMemo(
|
||||||
|
() => createMarkdownComponents(content ?? ""),
|
||||||
|
[content],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -160,7 +252,10 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Body */}
|
{/* Body */}
|
||||||
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4 text-sm text-slate-700">
|
<div
|
||||||
|
data-markdown-anchor-root
|
||||||
|
className="flex-1 min-h-0 overflow-y-auto px-5 py-4 text-sm text-slate-700"
|
||||||
|
>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex items-center justify-center gap-2 py-12 text-slate-400">
|
<div className="flex items-center justify-center gap-2 py-12 text-slate-400">
|
||||||
<Loader2 className="w-4 h-4 animate-spin text-primary" />
|
<Loader2 className="w-4 h-4 animate-spin text-primary" />
|
||||||
@@ -170,8 +265,21 @@ export const ArtifactPreviewModal: React.FC<ArtifactPreviewModalProps> = ({
|
|||||||
<div className="text-rose-600 text-xs py-6 text-center">
|
<div className="text-rose-600 text-xs py-6 text-center">
|
||||||
加载失败:{error}
|
加载失败:{error}
|
||||||
</div>
|
</div>
|
||||||
) : content === null ? null : renderAsMarkdown ? (
|
) : content === null ? null : renderAsMermaid ? (
|
||||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={MARKDOWN_COMPONENTS}>
|
mermaidSvg ? (
|
||||||
|
<div
|
||||||
|
className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm"
|
||||||
|
dangerouslySetInnerHTML={{ __html: mermaidSvg }}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center justify-center gap-2 py-12 text-slate-400">
|
||||||
|
<Loader2 className="w-4 h-4 animate-spin text-primary" />
|
||||||
|
<span className="text-xs">正在生成图表预览</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
) : renderAsMarkdown ? (
|
||||||
|
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||||
|
|
||||||
{content}
|
{content}
|
||||||
</ReactMarkdown>
|
</ReactMarkdown>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -9,9 +9,10 @@
|
|||||||
* 卡片席位名直接用落库快照(`seat.name`),无需实时校验,点「设置」进编辑页后
|
* 卡片席位名直接用落库快照(`seat.name`),无需实时校验,点「设置」进编辑页后
|
||||||
* 会看到实时数据。
|
* 会看到实时数据。
|
||||||
*/
|
*/
|
||||||
import { Fragment, useEffect, useState } from "react";
|
import { Fragment, useCallback, useEffect, useState } from "react";
|
||||||
import {
|
import {
|
||||||
ArrowRightIcon,
|
ArrowRightIcon,
|
||||||
|
GlobeIcon,
|
||||||
LayersIcon,
|
LayersIcon,
|
||||||
Loader2Icon,
|
Loader2Icon,
|
||||||
SettingsIcon,
|
SettingsIcon,
|
||||||
@@ -28,7 +29,7 @@ import {
|
|||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
import { listChains } from "../api/chains";
|
import { listChains, setChainPublic, type ChainScope } from "../api/chains";
|
||||||
import { chainTagClasses, type BusinessChain } from "../lib/business-chain";
|
import { chainTagClasses, type BusinessChain } from "../lib/business-chain";
|
||||||
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
||||||
|
|
||||||
@@ -47,16 +48,32 @@ export function BusinessChainListDialog({
|
|||||||
const [chains, setChains] = useState<BusinessChain[]>([]);
|
const [chains, setChains] = useState<BusinessChain[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
// 筛选:我的 / 公共(已发布)。
|
||||||
|
const [scope, setScope] = useState<ChainScope>("mine");
|
||||||
|
const [publishingId, setPublishingId] = useState<string | null>(null);
|
||||||
|
|
||||||
// 每次打开都重新拉一次,保证配置页改动后回来看到的是最新列表。
|
const refresh = useCallback(async (s: ChainScope) => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const list = await listChains(s);
|
||||||
|
setChains(list);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 每次打开 / 切换筛选都重新拉,保证配置页改动后回来看到的是最新列表。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
setLoading(true);
|
|
||||||
setError(null);
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const list = await listChains();
|
const list = await listChains(scope);
|
||||||
if (!cancelled) setChains(list);
|
if (!cancelled) setChains(list);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
|
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
|
||||||
@@ -67,7 +84,22 @@ export function BusinessChainListDialog({
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [open]);
|
}, [open, scope]);
|
||||||
|
|
||||||
|
const handleTogglePublic = useCallback(
|
||||||
|
async (chain: BusinessChain) => {
|
||||||
|
setPublishingId(chain.id);
|
||||||
|
try {
|
||||||
|
await setChainPublic(chain.id, !chain.isPublic);
|
||||||
|
await refresh(scope);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : String(err));
|
||||||
|
} finally {
|
||||||
|
setPublishingId(null);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[refresh, scope],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
@@ -78,10 +110,29 @@ export function BusinessChainListDialog({
|
|||||||
业务链条
|
业务链条
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
可复用的有序智能体编排。点击卡片「设置」可进入配置页编辑该链条。
|
可复用的有序智能体编排。点击卡片「设置」可进入配置页编辑该链条;「发布」后所有账号都能在「公共」里查看 / 选用。
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
|
{/* 筛选:我的 / 公共 */}
|
||||||
|
<div className="shrink-0 flex items-center gap-1 rounded-lg border border-border bg-muted/40 p-0.5 self-start">
|
||||||
|
{(["mine", "public"] as const).map((s) => (
|
||||||
|
<button
|
||||||
|
key={s}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setScope(s)}
|
||||||
|
className={cn(
|
||||||
|
"rounded-md px-3 py-1 text-xs font-medium transition",
|
||||||
|
scope === s
|
||||||
|
? "bg-primary text-primary-foreground shadow-sm"
|
||||||
|
: "text-muted-foreground hover:text-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{s === "mine" ? "我的" : "公共"}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="custom-scrollbar -mr-1 min-h-0 flex-1 overflow-y-auto py-3 pr-1">
|
<div className="custom-scrollbar -mr-1 min-h-0 flex-1 overflow-y-auto py-3 pr-1">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex items-center gap-2 px-1 py-10 text-sm text-muted-foreground">
|
<div className="flex items-center gap-2 px-1 py-10 text-sm text-muted-foreground">
|
||||||
@@ -95,9 +146,13 @@ export function BusinessChainListDialog({
|
|||||||
) : chains.length === 0 ? (
|
) : chains.length === 0 ? (
|
||||||
<div className="flex flex-col items-center justify-center gap-3 px-6 py-12 text-center">
|
<div className="flex flex-col items-center justify-center gap-3 px-6 py-12 text-center">
|
||||||
<LayersIcon className="size-10 text-primary/40" />
|
<LayersIcon className="size-10 text-primary/40" />
|
||||||
<div className="text-sm font-semibold">还没有业务链条</div>
|
<div className="text-sm font-semibold">
|
||||||
|
{scope === "public" ? "还没有公共链条" : "还没有业务链条"}
|
||||||
|
</div>
|
||||||
<p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
|
<p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
|
||||||
业务链条是可复用的有序智能体编排。点击下方「配置」去创建第一条链条。
|
{scope === "public"
|
||||||
|
? "公共链条是其他账号(或你自己)发布出来、所有人可见的链条。去「我的」里发布一条试试。"
|
||||||
|
: "业务链条是可复用的有序智能体编排。点击下方「配置」去创建第一条链条。"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -106,7 +161,9 @@ export function BusinessChainListDialog({
|
|||||||
<ChainRow
|
<ChainRow
|
||||||
key={chain.id}
|
key={chain.id}
|
||||||
chain={chain}
|
chain={chain}
|
||||||
|
publishing={publishingId === chain.id}
|
||||||
onSettings={() => onConfigure(chain.id)}
|
onSettings={() => onConfigure(chain.id)}
|
||||||
|
onTogglePublic={() => handleTogglePublic(chain)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -128,28 +185,61 @@ export function BusinessChainListDialog({
|
|||||||
|
|
||||||
function ChainRow({
|
function ChainRow({
|
||||||
chain,
|
chain,
|
||||||
|
publishing,
|
||||||
onSettings,
|
onSettings,
|
||||||
|
onTogglePublic,
|
||||||
}: {
|
}: {
|
||||||
chain: BusinessChain;
|
chain: BusinessChain;
|
||||||
|
publishing: boolean;
|
||||||
onSettings: () => void;
|
onSettings: () => void;
|
||||||
|
onTogglePublic: () => void;
|
||||||
}) {
|
}) {
|
||||||
|
const isMine = chain.isMine !== false;
|
||||||
return (
|
return (
|
||||||
<div className="rounded-2xl border border-border bg-card p-5 transition-colors hover:border-primary/40">
|
<div className="rounded-2xl border border-border bg-card p-5 transition-colors hover:border-primary/40">
|
||||||
{/* 标题行 + 设置按钮 */}
|
{/* 标题行 + 公共徽标 + 发布/设置按钮 */}
|
||||||
<div className="flex items-center gap-2.5">
|
<div className="flex items-center gap-2.5">
|
||||||
<div className="truncate text-base font-semibold">{chain.title || "未命名链条"}</div>
|
<div className="truncate text-base font-semibold">{chain.title || "未命名链条"}</div>
|
||||||
<span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs font-medium tabular-nums text-muted-foreground">
|
<span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs font-medium tabular-nums text-muted-foreground">
|
||||||
{chain.seats.length} 席
|
{chain.seats.length} 席
|
||||||
</span>
|
</span>
|
||||||
<Button
|
{chain.isPublic && (
|
||||||
variant="ghost"
|
<span className="shrink-0 inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-xs font-medium text-emerald-600 dark:text-emerald-400">
|
||||||
size="sm"
|
<GlobeIcon className="size-3" />
|
||||||
onClick={onSettings}
|
公共
|
||||||
className="ml-auto h-8 shrink-0 gap-1.5 px-3 text-sm"
|
</span>
|
||||||
>
|
)}
|
||||||
<SettingsIcon className="size-4" />
|
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||||
设置
|
{/* 发布 / 取消发布:仅本人的链条可操作。 */}
|
||||||
</Button>
|
{isMine && (
|
||||||
|
<Button
|
||||||
|
variant={chain.isPublic ? "secondary" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
onClick={onTogglePublic}
|
||||||
|
disabled={publishing}
|
||||||
|
className="h-8 gap-1.5 px-3 text-sm"
|
||||||
|
>
|
||||||
|
{publishing ? (
|
||||||
|
<Loader2Icon className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<GlobeIcon className="size-4" />
|
||||||
|
)}
|
||||||
|
{chain.isPublic ? "取消发布" : "发布"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{/* 设置(编辑):仅本人的链条;公共里别人的链条只读浏览。 */}
|
||||||
|
{isMine && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={onSettings}
|
||||||
|
className="h-8 gap-1.5 px-3 text-sm"
|
||||||
|
>
|
||||||
|
<SettingsIcon className="size-4" />
|
||||||
|
设置
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{chain.description && (
|
{chain.description && (
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
*
|
*
|
||||||
* 详见 `docs/multi-agent-business-chain-dev.md` §6.2 / §7 阶段 3。
|
* 详见 `docs/multi-agent-business-chain-dev.md` §6.2 / §7 阶段 3。
|
||||||
*/
|
*/
|
||||||
import { Fragment, useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||||
import {
|
import {
|
||||||
ArrowRightIcon,
|
ArrowRightIcon,
|
||||||
CheckIcon,
|
CheckIcon,
|
||||||
@@ -29,13 +29,14 @@ import { cn } from "@/lib/utils";
|
|||||||
import { listAgents } from "@/core/agents";
|
import { listAgents } from "@/core/agents";
|
||||||
|
|
||||||
import { filterRecommendCandidates } from "../api/recommend";
|
import { filterRecommendCandidates } from "../api/recommend";
|
||||||
import { listChains } from "../api/chains";
|
import { listChains, type ChainScope } from "../api/chains";
|
||||||
import {
|
import {
|
||||||
CHAIN_MIN_SEATS,
|
CHAIN_MIN_SEATS,
|
||||||
chainTagClasses,
|
chainTagClasses,
|
||||||
type BusinessChain,
|
type BusinessChain,
|
||||||
type SeatSelectionResult,
|
type SeatSelectionResult,
|
||||||
} from "../lib/business-chain";
|
} from "../lib/business-chain";
|
||||||
|
import { buildPlanFromStages } from "../lib/dag-types";
|
||||||
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
||||||
|
|
||||||
export interface BusinessChainPickerProps {
|
export interface BusinessChainPickerProps {
|
||||||
@@ -54,16 +55,21 @@ export function BusinessChainPicker({
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||||
|
// 筛选:我的 / 公共(已发布)。
|
||||||
|
const [scope, setScope] = useState<ChainScope>("mine");
|
||||||
// null = 候选池未知(agent 列表加载失败)→ 不把任何席位判成「已删除」。
|
// null = 候选池未知(agent 列表加载失败)→ 不把任何席位判成「已删除」。
|
||||||
const [existingIds, setExistingIds] = useState<Set<string> | null>(null);
|
const [existingIds, setExistingIds] = useState<Set<string> | null>(null);
|
||||||
const [nameById, setNameById] = useState<Map<string, string>>(new Map());
|
const [nameById, setNameById] = useState<Map<string, string>>(new Map());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
setSelectedId(null); // 切换筛选后清空选中(旧选中可能不在新列表里)。
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const [chainList, agents] = await Promise.all([
|
const [chainList, agents] = await Promise.all([
|
||||||
listChains(),
|
listChains(scope),
|
||||||
listAgents().catch(() => null), // agent 列表失败不阻断链条展示
|
listAgents().catch(() => null), // agent 列表失败不阻断链条展示
|
||||||
]);
|
]);
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
@@ -85,7 +91,7 @@ export function BusinessChainPicker({
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, []);
|
}, [scope]);
|
||||||
|
|
||||||
const isExisting = useMemo(
|
const isExisting = useMemo(
|
||||||
() => (agentId: string) => existingIds === null || existingIds.has(agentId),
|
() => (agentId: string) => existingIds === null || existingIds.has(agentId),
|
||||||
@@ -102,22 +108,68 @@ export function BusinessChainPicker({
|
|||||||
);
|
);
|
||||||
const canUse = !!selectedChain && survivingSeats.length >= CHAIN_MIN_SEATS;
|
const canUse = !!selectedChain && survivingSeats.length >= CHAIN_MIN_SEATS;
|
||||||
|
|
||||||
|
// 选中链条若有分层、且过滤到存活席位后**仍含并行 stage,或任一 stage 带「本阶段目标」**
|
||||||
|
// → 走 dag。并行要 dag 才能并行调度;带目标也要 dag —— 目标靠总控**逐阶段派活**注入
|
||||||
|
// (buildDagStageLeaderTask),chain 模式不消费目标,故串行带目标链同样走 dag。此时让用户在
|
||||||
|
// 「快速(并行双列禁写) / 沙箱(并行单列可写、沙箱跟随)」之间二选一(§DAG 执行子模式)。
|
||||||
|
const dagPlan = useMemo(() => {
|
||||||
|
if (!selectedChain?.stages || selectedChain.stages.length === 0) return null;
|
||||||
|
const surviveIds = survivingSeats.map((s) => s.agent_id);
|
||||||
|
const plan = buildPlanFromStages(
|
||||||
|
selectedChain.stages,
|
||||||
|
surviveIds,
|
||||||
|
true,
|
||||||
|
selectedChain.stageGoals,
|
||||||
|
selectedChain.coordinatorPrompt,
|
||||||
|
);
|
||||||
|
const hasParallel = plan.stages.some((st) => st.agentIds.length > 1);
|
||||||
|
const hasGoal = plan.stages.some((st) => (st.goal?.trim() ?? "") !== "");
|
||||||
|
const hasCoord = (plan.coordinatorPrompt?.trim() ?? "") !== "";
|
||||||
|
return hasParallel || hasGoal || hasCoord ? plan : null;
|
||||||
|
}, [selectedChain, survivingSeats]);
|
||||||
|
const [dagExecMode, setDagExecMode] = useState<"fast" | "sandbox">("fast");
|
||||||
|
|
||||||
const handleUse = () => {
|
const handleUse = () => {
|
||||||
if (!canUse || !selectedChain) return;
|
if (!canUse || !selectedChain) return;
|
||||||
const agents = survivingSeats.map((s) => ({
|
const chainMeta = { id: selectedChain.id, title: selectedChain.title };
|
||||||
agent_id: s.agent_id,
|
const seatNameById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.name]));
|
||||||
name: nameById.get(s.agent_id) ?? s.name,
|
const nameOf = (id: string) => nameById.get(id) ?? seatNameById.get(id) ?? id;
|
||||||
}));
|
|
||||||
onConfirm({
|
// 链条带分层、过滤存活后仍并行 → dag 编排(携带快速/沙箱子模式);否则退回线性 chain。
|
||||||
agents,
|
if (dagPlan) {
|
||||||
mode: "chain",
|
// dag:席位顺序按 stage 展平(与 plan 一致)。
|
||||||
chain: { id: selectedChain.id, title: selectedChain.title },
|
const agents = dagPlan.stages
|
||||||
});
|
.flatMap((st) => st.agentIds)
|
||||||
|
.map((id) => ({ agent_id: id, name: nameOf(id) }));
|
||||||
|
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id) }));
|
||||||
|
onConfirm({ agents, mode: "chain", chain: chainMeta });
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className="flex-1 min-h-0 flex flex-col overflow-hidden">
|
<section className="flex-1 min-h-0 flex flex-col overflow-hidden">
|
||||||
|
{/* 筛选:我的 / 公共 */}
|
||||||
|
<div className="mb-2 flex shrink-0 items-center gap-1 self-start rounded-lg border border-border bg-muted/40 p-0.5">
|
||||||
|
{(["mine", "public"] as const).map((s) => (
|
||||||
|
<button
|
||||||
|
key={s}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setScope(s)}
|
||||||
|
className={cn(
|
||||||
|
"rounded-md px-3 py-1 text-xs font-medium transition",
|
||||||
|
scope === s
|
||||||
|
? "bg-primary text-primary-foreground shadow-sm"
|
||||||
|
: "text-muted-foreground hover:text-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{s === "mine" ? "我的" : "公共"}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
<div className="min-h-0 flex-1 overflow-y-auto custom-scrollbar pr-1 -mr-1">
|
<div className="min-h-0 flex-1 overflow-y-auto custom-scrollbar pr-1 -mr-1">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex items-center gap-2 px-1 py-8 text-sm text-muted-foreground">
|
<div className="flex items-center gap-2 px-1 py-8 text-sm text-muted-foreground">
|
||||||
@@ -131,15 +183,20 @@ export function BusinessChainPicker({
|
|||||||
) : chains.length === 0 ? (
|
) : chains.length === 0 ? (
|
||||||
<div className="flex h-full flex-col items-center justify-center gap-3 px-6 py-10 text-center">
|
<div className="flex h-full flex-col items-center justify-center gap-3 px-6 py-10 text-center">
|
||||||
<LayersIcon className="size-10 text-primary/40" />
|
<LayersIcon className="size-10 text-primary/40" />
|
||||||
<div className="text-sm font-semibold">还没有业务链条</div>
|
<div className="text-sm font-semibold">
|
||||||
|
{scope === "public" ? "还没有公共链条" : "还没有业务链条"}
|
||||||
|
</div>
|
||||||
<p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
|
<p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
|
||||||
业务链条是可复用的有序智能体编排。先去配置页面创建第一条链条,
|
{scope === "public"
|
||||||
之后即可在这里选择使用。
|
? "公共链条是别人(或你自己)发布出来、所有账号可选用的链条。可在「我的」里发布一条。"
|
||||||
|
: "业务链条是可复用的有序智能体编排。先去配置页面创建第一条链条,之后即可在这里选择使用。"}
|
||||||
</p>
|
</p>
|
||||||
<Button variant="outline" size="sm" onClick={onGoConfig} className="gap-1.5">
|
{scope === "mine" && (
|
||||||
<SettingsIcon className="size-4" />
|
<Button variant="outline" size="sm" onClick={onGoConfig} className="gap-1.5">
|
||||||
去配置业务链条
|
<SettingsIcon className="size-4" />
|
||||||
</Button>
|
去配置业务链条
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-2.5 py-0.5">
|
<div className="space-y-2.5 py-0.5">
|
||||||
@@ -163,6 +220,40 @@ export function BusinessChainPicker({
|
|||||||
<SettingsIcon className="size-3.5" />
|
<SettingsIcon className="size-3.5" />
|
||||||
配置链条
|
配置链条
|
||||||
</Button>
|
</Button>
|
||||||
|
{/* dag 分层并行 → 选执行子模式(快速双列禁写 / 沙箱单列可写)。 */}
|
||||||
|
{dagPlan && (
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span className="text-xs font-medium text-muted-foreground">执行方式</span>
|
||||||
|
<div className="flex items-center gap-0.5 rounded-lg border border-border bg-muted/40 p-0.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setDagExecMode("fast")}
|
||||||
|
title="同 stage 席位并行执行,主区双列同时显示两个;并行期间禁止写文件(产物走正文)"
|
||||||
|
className={cn(
|
||||||
|
"rounded-md px-2.5 py-1 text-xs font-medium transition",
|
||||||
|
dagExecMode === "fast"
|
||||||
|
? "bg-primary text-primary-foreground shadow-sm"
|
||||||
|
: "text-muted-foreground hover:text-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
快速 · 双列禁写
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setDagExecMode("sandbox")}
|
||||||
|
title="同 stage 席位仍并行执行,但主区单列显示、允许写文件;点上方头像切换查看,沙箱跟随当前席位"
|
||||||
|
className={cn(
|
||||||
|
"rounded-md px-2.5 py-1 text-xs font-medium transition",
|
||||||
|
dagExecMode === "sandbox"
|
||||||
|
? "bg-primary text-primary-foreground shadow-sm"
|
||||||
|
: "text-muted-foreground hover:text-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
沙箱 · 单列可写
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{selectedChain && !canUse && (
|
{selectedChain && !canUse && (
|
||||||
<span className="text-xs text-destructive">存活席位不足 {CHAIN_MIN_SEATS} 个</span>
|
<span className="text-xs text-destructive">存活席位不足 {CHAIN_MIN_SEATS} 个</span>
|
||||||
@@ -217,6 +308,11 @@ function ChainCard({
|
|||||||
<CheckIcon className="size-3" />
|
<CheckIcon className="size-3" />
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
{chain.stages && chain.stages.length > 0 && (
|
||||||
|
<span className="shrink-0 rounded-full border border-amber-400/40 bg-amber-400/10 px-1.5 py-0.5 text-[10px] font-semibold text-amber-600 dark:text-amber-300">
|
||||||
|
分层并行
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
<span className="ml-auto shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground">
|
<span className="ml-auto shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground">
|
||||||
{chain.seats.length} 席
|
{chain.seats.length} 席
|
||||||
</span>
|
</span>
|
||||||
@@ -228,27 +324,35 @@ function ChainCard({
|
|||||||
|
|
||||||
{/* 智能体名 tag(按顺序,← 箭头连接) */}
|
{/* 智能体名 tag(按顺序,← 箭头连接) */}
|
||||||
<div className="mt-2 flex flex-wrap items-center gap-1">
|
<div className="mt-2 flex flex-wrap items-center gap-1">
|
||||||
{chain.seats.map((seat, i) => {
|
{chain.seats.flatMap((seat, i) => {
|
||||||
const alive = isExisting(seat.agent_id);
|
const alive = isExisting(seat.agent_id);
|
||||||
const label = nameById.get(seat.agent_id) ?? seat.name ?? seat.agent_id;
|
const label = nameById.get(seat.agent_id) ?? seat.name ?? seat.agent_id;
|
||||||
return (
|
// 不用 <Fragment>:dev 期 tagger 会往 Fragment 注入 data-lov-id 触发 React 警告,
|
||||||
<Fragment key={seat.agent_id}>
|
// 这里改成带 key 的扁平数组(箭头 + tag),注入落到真实元素上即可。
|
||||||
{i > 0 && (
|
const nodes: ReactNode[] = [];
|
||||||
<ArrowRightIcon className="size-3 shrink-0 text-muted-foreground/50" />
|
if (i > 0) {
|
||||||
|
nodes.push(
|
||||||
|
<ArrowRightIcon
|
||||||
|
key={`arrow-${seat.agent_id}`}
|
||||||
|
className="size-3 shrink-0 text-muted-foreground/50"
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
nodes.push(
|
||||||
|
<span
|
||||||
|
key={`tag-${seat.agent_id}`}
|
||||||
|
className={cn(
|
||||||
|
"rounded border px-1.5 py-0.5 text-[11px] font-medium",
|
||||||
|
alive
|
||||||
|
? chainTagClasses(getAvatarTypeFor(seat.agent_id, i))
|
||||||
|
: "border-dashed border-border bg-muted text-muted-foreground/60 line-through",
|
||||||
)}
|
)}
|
||||||
<span
|
title={alive ? undefined : "该智能体已不存在"}
|
||||||
className={cn(
|
>
|
||||||
"rounded border px-1.5 py-0.5 text-[11px] font-medium",
|
{label}
|
||||||
alive
|
</span>,
|
||||||
? chainTagClasses(getAvatarTypeFor(seat.agent_id, i))
|
|
||||||
: "border-dashed border-border bg-muted text-muted-foreground/60 line-through",
|
|
||||||
)}
|
|
||||||
title={alive ? undefined : "该智能体已不存在"}
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</span>
|
|
||||||
</Fragment>
|
|
||||||
);
|
);
|
||||||
|
return nodes;
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,360 @@
|
|||||||
|
/**
|
||||||
|
* 分层 DAG 流程图(Phase 7,§7)。
|
||||||
|
*
|
||||||
|
* 把 `DispatchChainModal` 的**线性**流程图复刻成 **DAG 版**:
|
||||||
|
* 总控 ─▶ ┌Stage1┐ ─▶ ┌Stage2┐ ─▶ … ─▶ 🤝共识 ─▶ 📊结果绘制
|
||||||
|
* │情报● │ │方案✓ │
|
||||||
|
* └风险● ┘ └──────┘
|
||||||
|
* - 按 stage 分**列**,stage 内席位**纵向并列**(并行批次),stage 间用连接线(串行)。
|
||||||
|
* - 节点状态复用 {@link ChainNodeState}(pending / active / done)+ 同款动画
|
||||||
|
* (`animate-ping` 光环 / `Loader2Icon` 转圈 / `CheckIcon` 打勾)。
|
||||||
|
* - 末尾接「共识 → 结果绘制」里程碑(沿用 `DispatchChainModal`)。
|
||||||
|
*
|
||||||
|
* 纯展示组件:所有状态由 props 传入。两种用途:
|
||||||
|
* 1) **编辑器只读预览**(`BusinessChainEditorPage` 底部):不传 `seatStates` → 全 pending,
|
||||||
|
* 仅展示编排结构。
|
||||||
|
* 2) **执行态总览**(Step 2 顶部缩略):`runDagOrchestration` 维护的 `dagNodeStates`
|
||||||
|
* 传进 `seatStates`,节点随执行实时 active/done。
|
||||||
|
*
|
||||||
|
* 节点视觉/连线 CSS 与 `DispatchChainModal` 同源(`rt-chain-connector` 在
|
||||||
|
* `styles/roundtable-planning.css` 全局段);此处自带紧凑版节点渲染,不改动既有 modal。
|
||||||
|
*/
|
||||||
|
import { CheckIcon, ChevronRightIcon, Loader2Icon } from "lucide-react";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
import { getAvatar } from "./Avatars";
|
||||||
|
import { chainTagClasses } from "../lib/business-chain";
|
||||||
|
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
||||||
|
import type { ChainNodeState } from "../lib/job-types";
|
||||||
|
|
||||||
|
/** 单个席位的展示元数据(名称 + 头像配色)。 */
|
||||||
|
export interface DagFlowSeatMeta {
|
||||||
|
name: string;
|
||||||
|
avatarType: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DagFlowChartProps {
|
||||||
|
/** 分层计划的 stages(`OrchestrationStage[]` 同形,只取 agentIds)。 */
|
||||||
|
stages: ReadonlyArray<{ id?: string; agentIds: string[] }>;
|
||||||
|
/**
|
||||||
|
* 把 `agentId`(小写)+ 全局序号解析成 {name, avatarType}。
|
||||||
|
* 缺省回退:name=agentId、avatarType=getAvatarTypeFor(agentId, order)。
|
||||||
|
*/
|
||||||
|
resolveSeat?: (agentId: string, order: number) => DagFlowSeatMeta;
|
||||||
|
/** `agentId`(小写)→ 节点状态。缺省 / 未命中 = pending(只读预览即全 pending)。 */
|
||||||
|
seatStates?: Record<string, ChainNodeState>;
|
||||||
|
/** 总控节点状态(默认 pending)。 */
|
||||||
|
coordinatorState?: ChainNodeState;
|
||||||
|
/** 共识里程碑状态(默认 pending)。 */
|
||||||
|
consensusState?: ChainNodeState;
|
||||||
|
/** 结果绘制里程碑状态(默认 pending)。 */
|
||||||
|
reportState?: ChainNodeState;
|
||||||
|
/** 是否显示末尾里程碑(共识 / 结果绘制)。默认 true。 */
|
||||||
|
showMilestones?: boolean;
|
||||||
|
/**
|
||||||
|
* 是否显示「结果绘制」里程碑。`结果绘制` 属于 **Step 3**;Step 2 的流程图只到「共识」即可,
|
||||||
|
* 故 Step 2 / 编辑器预览传 false,只展示 Step 2 流程(总控 → stages → 共识)。默认 true。
|
||||||
|
*/
|
||||||
|
showReportMilestone?: boolean;
|
||||||
|
/** 紧凑模式(顶部缩略 / 底部预览用更小的节点)。默认 false。 */
|
||||||
|
compact?: boolean;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 一个 stage 的聚合状态:任一 active → active;全 done → done;否则 pending。 */
|
||||||
|
function aggregateStageState(
|
||||||
|
agentIds: string[],
|
||||||
|
seatStates: Record<string, ChainNodeState> | undefined,
|
||||||
|
): ChainNodeState {
|
||||||
|
if (!seatStates || agentIds.length === 0) return "pending";
|
||||||
|
let anyActive = false;
|
||||||
|
let allDone = true;
|
||||||
|
for (const id of agentIds) {
|
||||||
|
const st = seatStates[id.toLowerCase()] ?? "pending";
|
||||||
|
if (st === "active") anyActive = true;
|
||||||
|
if (st !== "done") allDone = false;
|
||||||
|
}
|
||||||
|
if (anyActive) return "active";
|
||||||
|
return allDone ? "done" : "pending";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DagFlowChart({
|
||||||
|
stages,
|
||||||
|
resolveSeat,
|
||||||
|
seatStates,
|
||||||
|
coordinatorState = "pending",
|
||||||
|
consensusState = "pending",
|
||||||
|
reportState = "pending",
|
||||||
|
showMilestones = true,
|
||||||
|
showReportMilestone = true,
|
||||||
|
compact = false,
|
||||||
|
className,
|
||||||
|
}: DagFlowChartProps) {
|
||||||
|
const resolve = (agentId: string, order: number): DagFlowSeatMeta =>
|
||||||
|
resolveSeat?.(agentId, order) ?? {
|
||||||
|
name: agentId,
|
||||||
|
avatarType: getAvatarTypeFor(agentId, order),
|
||||||
|
};
|
||||||
|
|
||||||
|
// 全局序号:跨 stage 连续递增(getAvatarTypeFor 兜底配色 + 节点编号)。
|
||||||
|
let runningOrder = 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"custom-scrollbar overflow-x-auto overflow-y-hidden",
|
||||||
|
compact ? "py-3" : "py-6",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className={cn("flex min-w-max items-center", compact ? "gap-0 px-2" : "gap-0 px-4")}>
|
||||||
|
{/* 总控节点 */}
|
||||||
|
<FlowNode label="总控协调" avatarType="human" state={coordinatorState} compact={compact} />
|
||||||
|
|
||||||
|
{stages.map((stage, stageIdx) => {
|
||||||
|
const stageState = aggregateStageState(stage.agentIds, seatStates);
|
||||||
|
const isParallel = stage.agentIds.length > 1;
|
||||||
|
return (
|
||||||
|
// 用 display:contents 的包裹 div(而非 <Fragment key>):dev 代码标注插件会给具名
|
||||||
|
// <Fragment> 注入 data-lov-id,而 Fragment 只接受 key/children → React 报
|
||||||
|
// 「Invalid prop data-lov-id supplied to React.Fragment」。div.contents 不生成盒子,
|
||||||
|
// Connector / StageColumn 仍作为外层 flex 的直接子项,布局不变,且能正常接收 data-*。
|
||||||
|
<div className="contents" key={stage.id ?? `stage-${stageIdx}`}>
|
||||||
|
<Connector active={stageState === "active"} done={stageState === "done"} compact={compact} />
|
||||||
|
<StageColumn
|
||||||
|
index={stageIdx}
|
||||||
|
isParallel={isParallel}
|
||||||
|
compact={compact}
|
||||||
|
>
|
||||||
|
{stage.agentIds.map((agentId) => {
|
||||||
|
const order = runningOrder++;
|
||||||
|
const meta = resolve(agentId, order);
|
||||||
|
const state = seatStates?.[agentId.toLowerCase()] ?? "pending";
|
||||||
|
return (
|
||||||
|
<FlowNode
|
||||||
|
key={agentId}
|
||||||
|
label={meta.name}
|
||||||
|
avatarType={meta.avatarType}
|
||||||
|
state={state}
|
||||||
|
compact={compact}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</StageColumn>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{showMilestones && (
|
||||||
|
<>
|
||||||
|
<Connector
|
||||||
|
active={consensusState === "active"}
|
||||||
|
done={consensusState === "done"}
|
||||||
|
compact={compact}
|
||||||
|
/>
|
||||||
|
<MilestoneNode label="共识达成" emoji="🤝" state={consensusState} compact={compact} />
|
||||||
|
{showReportMilestone && (
|
||||||
|
<>
|
||||||
|
<Connector
|
||||||
|
active={reportState === "active"}
|
||||||
|
done={reportState === "done"}
|
||||||
|
compact={compact}
|
||||||
|
/>
|
||||||
|
<MilestoneNode label="结果绘制" emoji="📊" state={reportState} compact={compact} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Stage 列(纵向并列若干席位)────────────────────────────────────────────
|
||||||
|
|
||||||
|
function StageColumn({
|
||||||
|
index,
|
||||||
|
isParallel,
|
||||||
|
compact,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
index: number;
|
||||||
|
isParallel: boolean;
|
||||||
|
compact: boolean;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center gap-1.5">
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"select-none rounded-full px-2 py-0.5 font-semibold text-muted-foreground",
|
||||||
|
compact ? "text-[10px]" : "text-[11px]",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
Stage {index + 1}
|
||||||
|
{isParallel && (
|
||||||
|
<span className="ml-1 rounded bg-primary/10 px-1 text-primary">并行</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col items-center rounded-xl border border-dashed border-border/70 bg-muted/20",
|
||||||
|
compact ? "gap-2 p-1.5" : "gap-3 p-2.5",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 席位 / 总控节点 ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function FlowNode({
|
||||||
|
label,
|
||||||
|
avatarType,
|
||||||
|
state,
|
||||||
|
compact,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
avatarType: string;
|
||||||
|
state: ChainNodeState;
|
||||||
|
compact: boolean;
|
||||||
|
}) {
|
||||||
|
const tag = chainTagClasses(avatarType);
|
||||||
|
const ringSize = compact ? "size-10" : "size-14";
|
||||||
|
const avatarSize = compact ? "h-9 w-9" : "h-12 w-12";
|
||||||
|
return (
|
||||||
|
<div className={cn("flex shrink-0 flex-col items-center gap-1.5 text-center", compact ? "w-16" : "w-24")}>
|
||||||
|
<div className={cn("relative flex items-center justify-center", ringSize)}>
|
||||||
|
{state === "active" && (
|
||||||
|
<span className="absolute inset-0 animate-ping rounded-full bg-primary/30" />
|
||||||
|
)}
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"relative flex items-center justify-center rounded-full border-2 transition-all",
|
||||||
|
ringSize,
|
||||||
|
state === "active" && "border-primary shadow-[0_0_0_4px_rgba(22,119,255,0.12)]",
|
||||||
|
state === "done" && "border-emerald-400/70",
|
||||||
|
state === "pending" && "border-border opacity-45 grayscale",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{getAvatar(avatarType, avatarSize)}
|
||||||
|
{state === "done" && (
|
||||||
|
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-emerald-500 text-white shadow">
|
||||||
|
<CheckIcon className="size-2.5" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{state === "active" && (
|
||||||
|
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-primary text-primary-foreground shadow">
|
||||||
|
<Loader2Icon className="size-2.5 animate-spin" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"max-w-full truncate rounded border px-1.5 py-0.5 font-medium",
|
||||||
|
compact ? "text-[10px]" : "text-[11px]",
|
||||||
|
state === "pending" ? "border-border bg-muted text-muted-foreground" : tag,
|
||||||
|
)}
|
||||||
|
title={label}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 里程碑节点(共识 / 结果绘制)────────────────────────────────────────────
|
||||||
|
|
||||||
|
function MilestoneNode({
|
||||||
|
label,
|
||||||
|
emoji,
|
||||||
|
state,
|
||||||
|
compact,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
emoji: string;
|
||||||
|
state: ChainNodeState;
|
||||||
|
compact: boolean;
|
||||||
|
}) {
|
||||||
|
const ringSize = compact ? "size-10" : "size-14";
|
||||||
|
return (
|
||||||
|
<div className={cn("flex shrink-0 flex-col items-center gap-1.5 text-center", compact ? "w-16" : "w-24")}>
|
||||||
|
<div className={cn("relative flex items-center justify-center", ringSize)}>
|
||||||
|
{state === "active" && (
|
||||||
|
<span className="absolute inset-0 animate-ping rounded-full bg-primary/30" />
|
||||||
|
)}
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"relative flex items-center justify-center rounded-full border-2 transition-all",
|
||||||
|
ringSize,
|
||||||
|
compact ? "text-lg" : "text-2xl",
|
||||||
|
state === "active" && "border-primary bg-primary/5 shadow-[0_0_0_4px_rgba(22,119,255,0.12)]",
|
||||||
|
state === "done" && "border-emerald-400/70 bg-emerald-500/5",
|
||||||
|
state === "pending" && "border-border bg-muted opacity-45 grayscale",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{emoji}
|
||||||
|
{state === "done" && (
|
||||||
|
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-emerald-500 text-white shadow">
|
||||||
|
<CheckIcon className="size-2.5" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{state === "active" && (
|
||||||
|
<span className="absolute -right-0.5 -top-0.5 flex size-4 items-center justify-center rounded-full bg-primary text-primary-foreground shadow">
|
||||||
|
<Loader2Icon className="size-2.5 animate-spin" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"rounded border px-1.5 py-0.5 font-semibold",
|
||||||
|
compact ? "text-[10px]" : "text-[11px]",
|
||||||
|
state === "pending"
|
||||||
|
? "border-border bg-muted text-muted-foreground"
|
||||||
|
: state === "active"
|
||||||
|
? "border-primary/40 bg-primary/10 text-primary"
|
||||||
|
: "border-emerald-400/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 连接线(带流动动画,复用 DispatchChainModal 的 rt-chain-connector CSS)────
|
||||||
|
|
||||||
|
function Connector({
|
||||||
|
active,
|
||||||
|
done,
|
||||||
|
compact,
|
||||||
|
}: {
|
||||||
|
active: boolean;
|
||||||
|
done: boolean;
|
||||||
|
compact: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className={cn("flex shrink-0 items-center justify-center", compact ? "h-10 w-10" : "h-14 w-14")}>
|
||||||
|
<div className="relative flex w-full items-center">
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"rt-chain-connector",
|
||||||
|
active && "rt-chain-connector--active",
|
||||||
|
done && !active && "rt-chain-connector--done",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<ChevronRightIcon
|
||||||
|
className={cn(
|
||||||
|
"absolute -right-1 size-4 transition-colors",
|
||||||
|
active ? "text-primary" : done ? "text-primary/70" : "text-muted-foreground/40",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -67,6 +67,7 @@ export function DispatchChainJobModal({
|
|||||||
consensusPercentage={job?.consensusPercentage ?? 0}
|
consensusPercentage={job?.consensusPercentage ?? 0}
|
||||||
onView={job && onView ? () => onView(job) : undefined}
|
onView={job && onView ? () => onView(job) : undefined}
|
||||||
error={job?.error}
|
error={job?.error}
|
||||||
|
dialogues={job?.dialogues}
|
||||||
pendingClarification={job?.pendingClarification}
|
pendingClarification={job?.pendingClarification}
|
||||||
onResume={
|
onResume={
|
||||||
jobId
|
jobId
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
* (business-chain.ts)。连线动画 CSS 在 `styles/roundtable-planning.css` 全局段
|
* (business-chain.ts)。连线动画 CSS 在 `styles/roundtable-planning.css` 全局段
|
||||||
* (Radix Dialog portal 到 body,不在 .roundtable-planning 作用域内,故用全局类 + 语义 token)。
|
* (Radix Dialog portal 到 body,不在 .roundtable-planning 作用域内,故用全局类 + 语义 token)。
|
||||||
*/
|
*/
|
||||||
import { Fragment, useState } from "react";
|
import { Fragment, useEffect, useRef, useState } from "react";
|
||||||
import { CheckIcon, ChevronRightIcon, EyeIcon, Loader2Icon, SendIcon } from "lucide-react";
|
import { CheckIcon, ChevronRightIcon, EyeIcon, Loader2Icon, SendIcon } from "lucide-react";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -29,10 +29,13 @@ import {
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
import { getAvatar } from "./Avatars";
|
import { getAvatar } from "./Avatars";
|
||||||
|
import { MarkdownContent } from "./MessageBubble";
|
||||||
import { chainTagClasses } from "../lib/business-chain";
|
import { chainTagClasses } from "../lib/business-chain";
|
||||||
|
import { getAvatarTypeFor } from "../lib/roundtable-constants";
|
||||||
import type {
|
import type {
|
||||||
ChainNodeState,
|
ChainNodeState,
|
||||||
DispatchChainNode,
|
DispatchChainNode,
|
||||||
|
JobDialogue,
|
||||||
JobPhase,
|
JobPhase,
|
||||||
JobStatus,
|
JobStatus,
|
||||||
} from "../lib/job-types";
|
} from "../lib/job-types";
|
||||||
@@ -62,6 +65,8 @@ export interface DispatchChainModalProps {
|
|||||||
onCancel?: () => void;
|
onCancel?: () => void;
|
||||||
/** 出错详情(status==='error')。 */
|
/** 出错详情(status==='error')。 */
|
||||||
error?: string | null;
|
error?: string | null;
|
||||||
|
/** 研讨对话记录(leader 说明 + 各席位交付)。 */
|
||||||
|
dialogues?: JobDialogue[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const _NON_TERMINAL: ReadonlySet<JobStatus> = new Set<JobStatus>(["queued", "running", "awaiting_input"]);
|
const _NON_TERMINAL: ReadonlySet<JobStatus> = new Set<JobStatus>(["queued", "running", "awaiting_input"]);
|
||||||
@@ -99,8 +104,24 @@ export function DispatchChainModal({
|
|||||||
onResume,
|
onResume,
|
||||||
onCancel,
|
onCancel,
|
||||||
error,
|
error,
|
||||||
|
dialogues,
|
||||||
}: DispatchChainModalProps) {
|
}: DispatchChainModalProps) {
|
||||||
const [answer, setAnswer] = useState("");
|
const [answer, setAnswer] = useState("");
|
||||||
|
const convoRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// 新对话进来时自动滚到底部。
|
||||||
|
const dialogueCount = dialogues?.length ?? 0;
|
||||||
|
useEffect(() => {
|
||||||
|
const el = convoRef.current;
|
||||||
|
if (el) el.scrollTop = el.scrollHeight;
|
||||||
|
}, [dialogueCount]);
|
||||||
|
|
||||||
|
// 对话气泡的头像配色:总控固定蓝;席位优先取流程图节点色,回退按 agentId 派生。
|
||||||
|
const avatarForDialogue = (d: JobDialogue): string => {
|
||||||
|
if (d.role === "leader") return "blue";
|
||||||
|
const node = nodes.find((n) => n.agentId === d.agentId);
|
||||||
|
return node?.avatarType || (d.agentId ? getAvatarTypeFor(d.agentId, node?.order ? node.order - 1 : 0) : "blue");
|
||||||
|
};
|
||||||
// 总控节点:初始化 / 决策派活阶段高亮
|
// 总控节点:初始化 / 决策派活阶段高亮
|
||||||
const coordinatorState: ChainNodeState =
|
const coordinatorState: ChainNodeState =
|
||||||
phase === "initializing" || phase === "leader_thinking" ? "active" : "done";
|
phase === "initializing" || phase === "leader_thinking" ? "active" : "done";
|
||||||
@@ -120,7 +141,7 @@ export function DispatchChainModal({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
<DialogContent className="flex max-h-[88vh] flex-col gap-0 sm:max-w-5xl">
|
<DialogContent className="flex max-h-[90vh] w-[94vw] flex-col gap-0 sm:max-w-[1240px]">
|
||||||
<DialogHeader className="shrink-0">
|
<DialogHeader className="shrink-0">
|
||||||
<DialogTitle className="flex items-center gap-2">
|
<DialogTitle className="flex items-center gap-2">
|
||||||
{status === "running" && (
|
{status === "running" && (
|
||||||
@@ -147,7 +168,7 @@ export function DispatchChainModal({
|
|||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
{/* 横向流程图(横向滚动) */}
|
{/* 横向流程图(横向滚动) */}
|
||||||
<div className="custom-scrollbar min-h-0 flex-1 overflow-x-auto overflow-y-hidden py-10">
|
<div className="custom-scrollbar shrink-0 overflow-x-auto overflow-y-hidden py-8">
|
||||||
<div className="flex min-w-max items-start gap-0 px-6">
|
<div className="flex min-w-max items-start gap-0 px-6">
|
||||||
{/* 总控节点 */}
|
{/* 总控节点 */}
|
||||||
<FlowNode
|
<FlowNode
|
||||||
@@ -192,6 +213,28 @@ export function DispatchChainModal({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* 研讨对话(leader 说明 + 各席位交付,真网关下即真模型真实对话) */}
|
||||||
|
{dialogues && dialogues.length > 0 && (
|
||||||
|
<div
|
||||||
|
ref={convoRef}
|
||||||
|
className="custom-scrollbar min-h-0 flex-1 overflow-y-auto border-t px-1 py-3"
|
||||||
|
>
|
||||||
|
<div className="space-y-3.5">
|
||||||
|
{dialogues.map((d) => (
|
||||||
|
<div key={d.id} className="flex gap-2.5">
|
||||||
|
<div className="shrink-0">{getAvatar(avatarForDialogue(d), "h-7 w-7")}</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="mb-0.5 text-xs font-semibold text-foreground/80">{d.name}</div>
|
||||||
|
<div className="prose prose-sm max-w-none break-words text-sm leading-relaxed text-foreground/80 dark:prose-invert">
|
||||||
|
<MarkdownContent>{d.content || "…"}</MarkdownContent>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* 出错详情 */}
|
{/* 出错详情 */}
|
||||||
{status === "error" && error && (
|
{status === "error" && error && (
|
||||||
<div className="shrink-0 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
|
<div className="shrink-0 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
|
||||||
@@ -247,10 +290,15 @@ export function DispatchChainModal({
|
|||||||
停止
|
停止
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<Button onClick={onView} disabled={!onView} className="gap-1.5">
|
{/* 只对「运行中」任务隐藏入口——它正在后台真跑,进入会暂停前端编排、
|
||||||
<EyeIcon className="size-4" />
|
与后台作业双跑或借此重跑。其它状态(排队 / 待澄清 / 已完成 / 已取消 /
|
||||||
{status === "done" ? "查看报告" : "查看"}
|
出错)都不是正在跑的后台作业,可正常查看。 */}
|
||||||
</Button>
|
{status !== "running" && (
|
||||||
|
<Button onClick={onView} disabled={!onView} className="gap-1.5">
|
||||||
|
<EyeIcon className="size-4" />
|
||||||
|
{status === "done" ? "查看报告" : "查看"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
Eye,
|
Eye,
|
||||||
FileText,
|
FileText,
|
||||||
Loader2,
|
Loader2,
|
||||||
Printer,
|
|
||||||
RefreshCw,
|
RefreshCw,
|
||||||
Sparkles,
|
Sparkles,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
@@ -335,16 +334,6 @@ export const HighFidelityReport: React.FC<HighFidelityReportProps> = ({
|
|||||||
<Sparkles className="w-3.5 h-3.5" />
|
<Sparkles className="w-3.5 h-3.5" />
|
||||||
结果绘制
|
结果绘制
|
||||||
</button>
|
</button>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
if (typeof window !== "undefined") window.print();
|
|
||||||
}}
|
|
||||||
className="bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 text-[10.5px] font-bold px-3 py-1.5 rounded-xl flex items-center gap-1 transition cursor-pointer"
|
|
||||||
>
|
|
||||||
<Printer className="w-3.5 h-3.5 text-slate-500" />
|
|
||||||
打印 / 另存 PDF
|
|
||||||
</button>
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setReloadKey((k) => k + 1)}
|
onClick={() => setReloadKey((k) => k + 1)}
|
||||||
|
|||||||
@@ -52,16 +52,23 @@ export function MessageBubble({
|
|||||||
<div className="flex-1 min-w-0 space-y-1">
|
<div className="flex-1 min-w-0 space-y-1">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className={cn("text-xs font-extrabold text-slate-900", senderNameClassName)}>
|
<span
|
||||||
|
className={cn(
|
||||||
|
"roundtable-chat-message font-extrabold text-slate-900",
|
||||||
|
senderNameClassName,
|
||||||
|
)}
|
||||||
|
>
|
||||||
{senderName}
|
{senderName}
|
||||||
</span>
|
</span>
|
||||||
{badge && (
|
{badge && (
|
||||||
<span className="text-[calc(9px*var(--ui-font-scale,1))] font-mono font-black uppercase text-[var(--brand-900)] bg-[var(--brand-200)] border border-red-200 px-1.5 py-0.2 rounded">
|
<span className="roundtable-chat-meta font-mono font-black uppercase text-[var(--brand-900)] bg-[var(--brand-200)] border border-red-200 px-1.5 py-0.2 rounded">
|
||||||
{badge}
|
{badge}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[calc(10px*var(--ui-font-scale,1))] text-slate-400 font-mono font-medium shrink-0">{time}</span>
|
<span className="roundtable-chat-meta text-slate-400 font-mono font-medium shrink-0">
|
||||||
|
{time}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
@@ -75,7 +82,7 @@ export function MessageBubble({
|
|||||||
*/
|
*/
|
||||||
export function MessageLoadingPlaceholder({ label }: { label?: string }) {
|
export function MessageLoadingPlaceholder({ label }: { label?: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2 py-1.5 text-xs text-slate-600">
|
<div className="roundtable-chat-message flex items-center gap-2 py-1.5 text-slate-600">
|
||||||
<Loader2 className="w-4 h-4 animate-spin text-primary" />
|
<Loader2 className="w-4 h-4 animate-spin text-primary" />
|
||||||
<span className="font-medium">{label ?? "正在连接智能体..."}</span>
|
<span className="font-medium">{label ?? "正在连接智能体..."}</span>
|
||||||
<span className="inline-flex items-center gap-0.5">
|
<span className="inline-flex items-center gap-0.5">
|
||||||
@@ -112,16 +119,16 @@ export const sharedMarkdownComponents = {
|
|||||||
<li className="leading-snug">{children}</li>
|
<li className="leading-snug">{children}</li>
|
||||||
),
|
),
|
||||||
h1: ({ children }: { children?: React.ReactNode }) => (
|
h1: ({ children }: { children?: React.ReactNode }) => (
|
||||||
<h1 className="text-sm font-bold mt-2 mb-1">{children}</h1>
|
<h1 className="text-lg font-bold mt-2 mb-1">{children}</h1>
|
||||||
),
|
),
|
||||||
h2: ({ children }: { children?: React.ReactNode }) => (
|
h2: ({ children }: { children?: React.ReactNode }) => (
|
||||||
<h2 className="text-sm font-bold mt-2 mb-1">{children}</h2>
|
<h2 className="text-base font-bold mt-2 mb-1">{children}</h2>
|
||||||
),
|
),
|
||||||
h3: ({ children }: { children?: React.ReactNode }) => (
|
h3: ({ children }: { children?: React.ReactNode }) => (
|
||||||
<h3 className="text-xs font-bold mt-1.5 mb-0.5">{children}</h3>
|
<h3 className="roundtable-chat-message font-bold mt-1.5 mb-0.5">{children}</h3>
|
||||||
),
|
),
|
||||||
h4: ({ children }: { children?: React.ReactNode }) => (
|
h4: ({ children }: { children?: React.ReactNode }) => (
|
||||||
<h4 className="text-xs font-bold mt-1 mb-0.5">{children}</h4>
|
<h4 className="roundtable-chat-message font-bold mt-1 mb-0.5">{children}</h4>
|
||||||
),
|
),
|
||||||
strong: ({ children }: { children?: React.ReactNode }) => (
|
strong: ({ children }: { children?: React.ReactNode }) => (
|
||||||
<strong className="font-bold text-slate-900">{children}</strong>
|
<strong className="font-bold text-slate-900">{children}</strong>
|
||||||
@@ -139,13 +146,13 @@ export const sharedMarkdownComponents = {
|
|||||||
const isBlock = /language-/.test(className ?? "");
|
const isBlock = /language-/.test(className ?? "");
|
||||||
if (isBlock) {
|
if (isBlock) {
|
||||||
return (
|
return (
|
||||||
<pre className="bg-slate-100 text-slate-800 rounded-md p-2 my-1 overflow-x-auto text-[calc(11px*var(--ui-font-scale,1))] font-mono">
|
<pre className="roundtable-chat-message bg-slate-100 text-slate-800 rounded-md p-2 my-1 overflow-x-auto font-mono">
|
||||||
<code>{children}</code>
|
<code>{children}</code>
|
||||||
</pre>
|
</pre>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<code className="bg-slate-100 text-slate-800 rounded px-1 py-0.5 text-[calc(11px*var(--ui-font-scale,1))] font-mono">
|
<code className="roundtable-chat-message bg-slate-100 text-slate-800 rounded px-1 py-0.5 font-mono">
|
||||||
{children}
|
{children}
|
||||||
</code>
|
</code>
|
||||||
);
|
);
|
||||||
@@ -160,8 +167,13 @@ export const sharedMarkdownComponents = {
|
|||||||
{children}
|
{children}
|
||||||
</a>
|
</a>
|
||||||
),
|
),
|
||||||
|
// 宽表在并行两列 / 窄气泡里会超出容器(模型常输出多列表格,如「法律免责条款」表)。
|
||||||
|
// 套一层 max-w-full + overflow-x-auto 的块级容器:表格保持自然宽度,超出时容器内**横向
|
||||||
|
// 滚动**而不是撑破列宽 / 盖到相邻列。table 不设 max-w,否则单元格会被挤到错乱换行。
|
||||||
table: ({ children }: { children?: React.ReactNode }) => (
|
table: ({ children }: { children?: React.ReactNode }) => (
|
||||||
<table className="my-1 border-collapse text-[calc(11px*var(--ui-font-scale,1))]">{children}</table>
|
<div className="my-1 max-w-full overflow-x-auto">
|
||||||
|
<table className="roundtable-chat-message border-collapse">{children}</table>
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
th: ({ children }: { children?: React.ReactNode }) => (
|
th: ({ children }: { children?: React.ReactNode }) => (
|
||||||
<th className="border border-slate-300 px-1.5 py-0.5 bg-slate-50 font-bold text-left">
|
<th className="border border-slate-300 px-1.5 py-0.5 bg-slate-50 font-bold text-left">
|
||||||
@@ -254,7 +266,7 @@ export function ReasoningBlock({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleToggle}
|
onClick={handleToggle}
|
||||||
className="inline-flex items-center gap-1.5 text-[calc(11.5px*var(--ui-font-scale,1))] text-slate-500 hover:text-slate-700 transition-colors cursor-pointer"
|
className="roundtable-chat-message inline-flex items-center gap-1.5 text-slate-500 hover:text-slate-700 transition-colors cursor-pointer"
|
||||||
>
|
>
|
||||||
<BrainIcon className={cn("size-3.5", streaming && "text-primary animate-pulse")} />
|
<BrainIcon className={cn("size-3.5", streaming && "text-primary animate-pulse")} />
|
||||||
<span className={cn(streaming && "animate-pulse")}>{headerLabel}</span>
|
<span className={cn(streaming && "animate-pulse")}>{headerLabel}</span>
|
||||||
@@ -265,7 +277,7 @@ export function ReasoningBlock({
|
|||||||
{open && (
|
{open && (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"rounded-md border border-slate-200 bg-slate-50/60 px-3 py-2 text-[calc(11.5px*var(--ui-font-scale,1))] text-slate-600 leading-relaxed",
|
"roundtable-chat-message rounded-md border border-slate-200 bg-slate-50/60 px-3 py-2 text-slate-600",
|
||||||
contentClassName,
|
contentClassName,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -86,10 +86,15 @@ export function MessageStepsCard({
|
|||||||
const display = getStepDisplay(lastReasoning.key, lastReasoning.label, lastReasoning.args);
|
const display = getStepDisplay(lastReasoning.key, lastReasoning.label, lastReasoning.args);
|
||||||
const Icon = display.icon;
|
const Icon = display.icon;
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex items-center gap-2 text-[calc(11.5px*var(--ui-font-scale,1))] text-slate-500 py-0.5", className)}>
|
<div
|
||||||
|
className={cn(
|
||||||
|
"roundtable-chat-message flex items-center gap-2 text-slate-500 py-0.5",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
<Icon className="size-3.5 text-slate-400" />
|
<Icon className="size-3.5 text-slate-400" />
|
||||||
<span>{display.label}</span>
|
<span>{display.label}</span>
|
||||||
<span className="text-[calc(10px*var(--ui-font-scale,1))] text-slate-400 font-mono">{lastReasoning.ts}</span>
|
<span className="roundtable-chat-meta text-slate-400 font-mono">{lastReasoning.ts}</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -108,7 +113,7 @@ export function MessageStepsCard({
|
|||||||
>
|
>
|
||||||
<ChainOfThoughtStep
|
<ChainOfThoughtStep
|
||||||
label={
|
label={
|
||||||
<span className="text-[calc(11.5px*var(--ui-font-scale,1))] opacity-60">
|
<span className="roundtable-chat-message opacity-60">
|
||||||
{showAbove ? "隐藏步骤" : `查看其他 ${priorToolSteps.length} 个步骤`}
|
{showAbove ? "隐藏步骤" : `查看其他 ${priorToolSteps.length} 个步骤`}
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
@@ -189,9 +194,9 @@ function ToolStep({
|
|||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
label={
|
label={
|
||||||
<span className="text-[calc(12px*var(--ui-font-scale,1))] text-slate-700">
|
<span className="roundtable-chat-message text-slate-700">
|
||||||
<span className="font-medium">{display.label}</span>
|
<span className="font-medium">{display.label}</span>
|
||||||
<span className="ml-2 text-[calc(10px*var(--ui-font-scale,1))] text-slate-400 font-mono">{step.ts}</span>
|
<span className="roundtable-chat-meta ml-2 text-slate-400 font-mono">{step.ts}</span>
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
@@ -204,10 +209,10 @@ function ReasoningStep({ step, streaming }: { step: BubbleStep; streaming: boole
|
|||||||
const display = getStepDisplay(step.key, step.label, step.args);
|
const display = getStepDisplay(step.key, step.label, step.args);
|
||||||
const Icon = display.icon;
|
const Icon = display.icon;
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2 text-[calc(11.5px*var(--ui-font-scale,1))] text-slate-500">
|
<div className="roundtable-chat-message flex items-center gap-2 text-slate-500">
|
||||||
<Icon className={cn("size-3.5", streaming ? "text-primary animate-pulse" : "text-slate-400")} />
|
<Icon className={cn("size-3.5", streaming ? "text-primary animate-pulse" : "text-slate-400")} />
|
||||||
<span>{display.label}</span>
|
<span>{display.label}</span>
|
||||||
<span className="text-[calc(10px*var(--ui-font-scale,1))] text-slate-400 font-mono">{step.ts}</span>
|
<span className="roundtable-chat-meta text-slate-400 font-mono">{step.ts}</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Loaded 100 of 267 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user