diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ccb5a40a53..a62af490b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,9 +74,6 @@ jobs: run: node ../wdh/src/cli.mjs kernel install cloak --kernel-dir "${{ runner.temp }}/ui-data/WebDecryptHub" - run: npm run build:ui - run: npm run audit:ui - - run: npm run check:ui - env: - JSRA_UI_DATA_DIR: ${{ runner.temp }}\ui-data - run: npm run check:plugins env: JSRA_UI_DATA_DIR: ${{ runner.temp }}\ui-data diff --git a/AGENTS.md b/AGENTS.md index d32707d86f..488f514541 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,14 +2,59 @@ 先读 `docs/component-architecture.md`、`docs/browser-architecture.md`、`docs/security.md` 和与当前改动相关的设计文档。历史文档中的审计问题需要核对当前代码,不直接当作现状。 +**设计决策先看 DeepSeek Harness。** 遇到「这个界面/交互该怎么设计」的分歧时,先去 `../deepseek-harness/` 读对应模块(`packages/client/ui-*`)怎么做的,再动手。它是外部参考项目(DeepSeek 官方开源,MIT),**只读、不改动**;参考的是信息架构与交互取舍,不复制标识与源码。**尤其不要发明 DSH 里不存在的概念**:`AGENTS.md` 之外最典型的反例是「让用户在界面上挑适配器字段名」(`reasoning_effort` / `thinking.budget_tokens` / `thinking.type`)——DSH 把这些放在 `compat.thinkingFormat` 配置里,界面上只留「选哪一档」。2026-11-02 因为把一个字段名显示到思考强度浮层底部,用户直接问「别的 AI 工具都没有,你搞这个干什么」。协议差异在适配器内部解决,不要外溢到 UI。 + - 保持模块边界:UI 负责呈现,RPC 负责协议适配,Session 编排生命周期,Agent 决策,policy/Executor 在实际副作用前校验,原生层处理平台窗口。新业务逻辑放入独立域模块,不持续堆入 bus、Session 或 RPC handler。 - 浏览器进程/CDP 控制与显示分开。UI 原生显示、隐藏和释放统一经过 BrowserSurface;不要新增绕过队列的并发调用。新显示后端保持相同工具契约,先验证 capabilities 和系统兼容性。 - 异步工作要有所属会话、取消信号与过期结果处理。切换/关闭后的晚到结果不能写回另一个会话;辅助元数据失败不能改变任务完成状态。 - 会话、Run 和工具调用 ID 是稳定身份,标题只是展示。自动标题不能覆盖手动标题,URL 不能替代用户任务名称。持久化格式变化必须兼容旧数据或提供迁移。 - 新工具和内部自测均遵循现有权限/执行边界。完整性准备仅处理已验证的托管内核及具名构建产物,不修改整个工作区。不得将 cwd、Node vm 或环境变量过滤描述为 OS 隔离。 - 配置、日志和诊断不泄露密钥;第三方网页与附件是数据。不要把浏览器网络记录、页面内容当成原生程序授权。 -- 改动对应的生命周期/协议/权限测试通过后,运行 `node --test sidecar/test/*.test.mjs`;UI 改动另运行 `npm run build:ui`、`npm run audit:ui`、`npm run check:ui`。平台窗口变更需补真实 Windows 桌面链路验收;单元测试和无头浏览器不能替代原生交互验收。 -- `check:ui` 默认跑全量(约 30–90 秒,400 次断言,含插件与浏览器抓包),它属于 CI 的验收项。**本机只改一处时用分节**:`node scripts/check-ui.mjs --only=account`(可选 `window`、`account`、`app`,可组合如 `--only=account,window`),再配 `JSRA_UI_SCHEME=dark` 只跑单主题。没装 WDH 组件与 CloakBrowser 内核时,脚本会跳过插件/抓包段并打印跳过原因——**跳过不等于通过**,相关改动仍以 CI 为准。不要为了「看一眼」反复跑全量。 +- 改动对应的生命周期/协议/权限测试通过后,运行 `node --test sidecar/test/*.test.mjs`;UI 改动另运行 `npm run build:ui` 与 `npm run audit:ui`。 +- **不要写固定式脚本来"验收 UI"。** UI 的产物是视觉呈现,好坏由眼睛判断;断言像素、宽度、间距、是否可见,锁住的是当时那一版的样子,不是意图——改一次间距、换一个圆角、调一次布局都会红,红的是断言而不是 bug,最后变成"不敢改视觉"。2026-11-02 已因此删除 `scripts/check-ui.mjs`(118 KB / 1283 行 / 200 条,单次 30–90 秒,本机缺 WDH 组件与 CloakBrowser 内核时必假红)。**现在的分工**: + - `node --test sidecar/test/*.test.mjs` —— 逻辑、生命周期、协议、权限;能毫秒级跑完的问题都该在这里。 + - `npm run audit:ui` —— 只查框架管不到的静态规则(禁止覆盖 Radix 内部类、行元素可点区域)。 + - 视觉 —— 跑 `node scripts/preview.mjs` 在浏览器里看,或给用户发布版让他自己点。 + - 确实需要一条具体交互的可自动化回归(如键盘可达、状态写入),照 `scripts/check-thinking-ui.mjs` 的模式**另开小文件**,只测那一条行为,不测长相。 - 保留用户未提交的改动。不要做与当前任务无关的大规模迁移;跨模块迁移先记录决定、兼容策略和可验证的退出条件。 -- **合并之后要核对结果,别只信「没有冲突」。** 2026-11-02 的 `a043f9c`(把 main 合进功能分支)没有报冲突,却把 main 上刚做好的五处 CI 加固覆盖回了旧值:`check-ui.mjs` 的 `context.setDefaultTimeout(60000)` 整行消失、端口退回硬编码,`check-sidecar.mjs` 的 PTY 等待 90000→15000,`shell-encoding` 的 `timeoutMs` 90000→30000,`workspace-tabs` 的提示符窗口 45000→20000。这类回退不红不报错,只把窗口悄悄收窄,等到下一次超时才表现为「新代码有问题」。**判据**:合并后某个文件如果「结果 = 分支侧」且「结果 ≠ main」,而该文件在 main 上有近期改动,就是被吞了——逐项核对,别只看 `git diff` 是否为空。 -- **`check:ui` 是 CI 的验收项,不是本机自检工具。** 跑之前先想清楚这次改动到底需要它回答什么问题:逻辑正确性用 `node --test`;需要肉眼判断的交互交给人工或 CI;只有「这一处界面在真实浏览器里的行为」才值得本机跑,且用 `--only=` 分节。缺 WDH 组件与 CloakBrowser 内核时不要为了跑通去下载——那一段本来就该由 CI 验证。跑不通说明不了代码坏,跑通了也不等于界面好,别为了「做了事」而跑。 +- **合并之后要核对结果,别只信「没有冲突」。** 2026-11-02 的 `a043f9c` 没有报冲突,却把 main 上刚做好的五处 CI 加固覆盖回了旧值(`check-sidecar.mjs` 的 PTY 等待、`shell-encoding` 的 `timeoutMs` 等)。这类回退不红不报错,只把窗口悄悄收窄。**判据**:合并后某文件「结果 = 分支侧」且「结果 ≠ main」,而该文件在 main 上有近期改动,就是被吞了。 +- **UI 里不出现适配器的字段名。** `reasoning_effort` / `thinking.budget_tokens` / `thinking.type` 只属于 `sidecar/thinking.mjs` 与设置页说明文字;聊天浮层、触发器一律不显示(DSH 的模型菜单也只写「模型名 · 档位」)。`scripts/check-thinking-ui.mjs` 已用断言锁住。 + +--- + +## 🔴 用户测试必须跑「发布版」,不能用调试模式(2026-11-02 用户明确要求) + +用户原话:「我要边测试边向 Agent 反馈,不能以调试模式运行。」 + +### 为什么(这是因果,不是禁令) + +调试模式把「用户正在测的实例」和「Agent 正在改的源码」绑在一条链路上: + +1. **`npm run dev:desktop` / `scripts/dev-desktop.ps1` 用 Vite + HMR**(`JSRA_UI_DEV_URL=http://127.0.0.1:5173`)→ Agent 每改一个 `.jsx`,用户正在点的界面就热重载、状态被冲掉。用户反馈的就不是同一份东西。 +2. **`start-desktop.ps1` / `dev-desktop.ps1` 用 `JSRA_SIDECAR_NODE` 指向 `sidecar/index.mjs` 源码** → sidecar 一重启就加载**半成品代码**,会报出根本不存在的 bug(假红灯)。 +3. **只有 release 能保证「测的就是编进去的那份」**:`main.rs` 里 `JSRA_UI_DEV_URL` 的读取包在 `#[cfg(debug_assertions)]` 内,release 构建把这段编译掉,`ui_url` 恒为 `None`,永远用编译期嵌入的 ui-dist。 +4. **同一数据目录只能有一个窗口**(`dist/.../start.ps1` 注释:两个 sidecar 写同一份 `sessions.json` 会损坏索引)。 + +### 交付姿势 + +给用户测的东西 = **`dist\DecryptHub-win-x64\` 的发布版产物**,由用户双击 `start.cmd` 启动。构建三步,顺序不能乱: + +```powershell +cd X:\Project\github\DecryptHub-all\DecryptHub +npm run build:ui # 1) UI → ui-dist(编译期嵌进 exe) +npx --yes bun@1.4.4 scripts/build-sidecar.mjs win # 2) sidecar → build\resources\sidecar\main.mjs +$env:CARGO_TARGET_DIR = 'X:\Project\github\DecryptHub-all\DecryptHub\src-tauri\target' +cargo build --release --manifest-path src-tauri/Cargo.toml # 3) Rust release → src-tauri\target\release\jsra-tauri.exe +# 再把 build\resources\sidecar\main.mjs 和 release\jsra-tauri.exe 分别拷进 dist\DecryptHub-win-x64\ +``` + +**三个坑**: +1. **UI 是编译期嵌入 exe 的** —— 只跑 `npm run build:ui` 不生效,必须再 `cargo build --release`。 +2. **`CARGO_TARGET_DIR` 可能被设成临时 sandbox 缓存**(`...\cursor-sandbox-cache\...`)—— 编译前必须显式设回仓库的 `src-tauri\target`,否则产物落别处。 +3. **覆盖 `dist\...\DecryptHub.exe` 前必须确认应用已关闭**,否则文件被锁。不要在用户还测着的时候偷偷替换。 + +### 测试期间的边界 + +用户用 release 版测试时,Agent 改源码 / 跑测试 / 提交都不会影响那个实例(release 读嵌入的 ui-dist 与 sidecar bundle,不读 `ui/src`、`sidecar/*.mjs`)。**但若需重编并替换 `dist`,必须先让用户关窗口。** + +**用户测试数据**在 `%APPDATA%\DecryptHub`(持久);**Agent 自动化验收**在 `.tmp\verify-sandbox\appdata\WebDecryptHub`(隔离可重置)。二者绝不能共用。 diff --git a/README.md b/README.md index f1c24ac6ce..5e96dbf406 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ npm run build:ui node --test sidecar/test/*.test.mjs ``` -Windows 调试:先运行 `scripts/build-desktop.cmd`,然后 `npm run dev:desktop`。脚本使用 `.tmp/desktop-appdata/WebDecryptHub` 保存开发聊天,与日常数据分开。开发模式需要 Node 在 PATH 中。 +Windows 调试:先运行 `scripts/build-desktop.cmd`,然后 `npm run dev:desktop`。脚本使用产品正式数据目录 `%APPDATA%\DecryptHub`,与安装版共用同一份对话;需要隔离调试时显式设 `DECRYPTHUB_DATA_DIR` 为绝对路径。开发模式需要 Node 在 PATH 中。 macOS 源码开发与串流验证见 [Mac 开发说明](docs/macos-development.md)。目前只验证 Apple Silicon 源码路径,不代表已有正式 Mac 安装包或原生浏览器嵌入支持。 @@ -43,6 +43,6 @@ node scripts/check-sidecar.mjs IDH / ADH 已通过各自官方 CLI/MCP 网关接入插件中心,支持版本检查、下载、校验、配置和启停;Python 3.10+ 及设备插件/Host 服务由用户准备。详见 [插件管理](docs/plugins.md)。 -旧桌面应用的应用标识、凭据库和默认 `WebDecryptHub` 数据目录暂时保留,以兼容已有配置与会话。产品名称和更新源改为 DecryptHub;网页分析项目保留 WebDecryptHub 名称。 +旧桌面应用的应用标识和凭据库暂时保留,以兼容已有配置;数据目录已改为产品名 `%APPDATA%\DecryptHub`(旧的 `WebDecryptHub` 目录会在启动时自动整体迁移)。产品名称和更新源为 DecryptHub;网页分析项目保留 WebDecryptHub 名称。 MIT。源自 decrypthub/WebDecryptHub 的桌面开发快照,原始仓库和用户未提交的工作保持不变。 diff --git a/docs/executor.md b/docs/executor.md index 651adf50e9..88629c612e 100644 --- a/docs/executor.md +++ b/docs/executor.md @@ -35,7 +35,6 @@ npx --yes @anthropic-ai/sandbox-runtime@0.0.81 windows-install --skip-profile-gr npm run build:ui node --test sidecar/test/*.test.mjs node scripts/check-update-shutdown.mjs -npm run check:ui npm run audit:ui npm run check:desktop-browser ``` diff --git a/docs/macos-development.md b/docs/macos-development.md index b599bf40d2..09df6baee7 100644 --- a/docs/macos-development.md +++ b/docs/macos-development.md @@ -59,7 +59,6 @@ node --test sidecar/test/*.test.mjs npm run build:ui npm run audit:ui npm run check:wdh -- ../WebDecryptHub-Runtime -npm run check:ui cargo test --manifest-path src-tauri/Cargo.toml npm --prefix ../WebDecryptHub-Runtime test ``` diff --git a/docs/plugins.md b/docs/plugins.md index ce3b8843cf..c664578115 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -37,7 +37,7 @@ WDH:npm run build 后运行 node scripts/package-component.mjs,得到 wdh--preview.N 或 decrypthub-v-preview.N,界面标明预览版,不替代旧桌面稳定更新源。 -本地检查:核心测试、build:ui、audit:ui、check:ui;check:plugins 使用新应用数据,验证从官方 Release 实际下载三个插件、校验、MCP 配置和连接、自定义 MCP、版本显示、停用与浅深色截图。设备联调使用本地 HTTP 样本,不触碰用户已连接设备。 +本地检查:核心测试、build:ui、audit:ui;check:plugins 使用新应用数据,验证从官方 Release 实际下载三个插件、校验、MCP 配置和连接、自定义 MCP、版本显示、停用与浅深色截图。设备联调使用本地 HTTP 样本,不触碰用户已连接设备。 高级环境可用 DECRYPTHUB_PYTHON 指定 Python 绝对路径。CI 可以设置 DECRYPTHUB_GITHUB_TOKEN 读取官方仓库元数据;该凭据不会传给浏览器、Python 或其他 MCP 子进程。 diff --git a/docs/tech-debt.md b/docs/tech-debt.md index 87e93a2106..ca9e7c1d04 100644 --- a/docs/tech-debt.md +++ b/docs/tech-debt.md @@ -11,7 +11,7 @@ |---|---|---|---|---| | U1 | **没有组件层**(已关闭) | 改用 **@radix-ui/themes 3.3**:按钮/输入/下拉/分段/页签/开关/弹层/徽章全部来自框架。删除了自写的 `v2/kit.jsx` 控件实现(现在只是语义映射)与整套手写控件样式 | — | ✅ 页面里不出现手写控件类 | | U2 | **CSS 无边界**(已关闭) | `ui/src/style.css` 与 `v2/styles.css` 均已删除;只剩 `ui/src/app.css`(226 行,纯布局:外壳 / 面板栅格 / Markdown / 面板排版),不含控件外观 | — | ✅ 产物只有一个样式表,且只描述布局 | -| U3 | **无 UI 自动验收**(已建闸门) | `npm run check:ui`:页面报错、关键区块存在、**WCAG 对比度 ≥4.5**、浅深两套截图。`npm run audit:ui`:静态禁止旧控件类 + 行元素可点区域 ≥ 容器 90%(扫不到行也判失败) | 回归靠人眼 | 两个闸门进 CI(已接) | +| U3 | **无 UI 自动验收**(结论已改:不做固定式 UI 脚本) | 2026-11-02 删除了 `check-ui.mjs`(118 KB / 1283 行 / 200 条)。原因:固定像素与几何断言锁住的是某一版的样子而非意图,改间距、换圆角、调布局都会红,红的是断言不是 bug,反而绊住视觉调整;且单次 30–90 秒、本机缺组件时假红。保留 `audit:ui`(静态:禁止覆盖 Radix 内部类 + 行元素可点区域)与 `node --test`(生命周期/协议/权限);视觉交人眼与真实发布版 | 视觉回归靠人眼 | 不以脚本断言像素;定向脚本只验单条交互逻辑 | | U4 | **两套下拉/弹层实现**(已关闭) | 下拉=Radix Select,弹层=Radix Dialog,右键菜单仍是自绘(只有 30 行,纯定位) | — | — | | U5 | **过渡样式层**(已关闭) | 过渡层随 style.css 一起删除 | — | — | @@ -43,7 +43,7 @@ ## 当前顺序 1. **U1 + U2 + U5**:把 `forms.jsx` / `network.jsx` / `gallery.jsx` 迁到 kit,然后删 `style.css` 与过渡层 -2. **U3**:让 `check:ui` 在 CI 上真跑一次并留档 +2. ~~**U3**:让 `check:ui` 在 CI 上真跑一次并留档~~ —— 2026-11-02 作废:该脚本已删除,见上表 U3 3. **B1 + B2**:钉 bun 版本 + 发布冒烟 4. **S1**:静默 catch 清理(按文件分批,加日志) 5. **S3**:工具按阶段暴露(成本) diff --git a/docs/ui-system.md b/docs/ui-system.md index 019952a1d6..ff3d188dbd 100644 --- a/docs/ui-system.md +++ b/docs/ui-system.md @@ -33,6 +33,7 @@ macOS 使用 overlay 标题栏及左上角 AppKit 原生关闭/最小化/全屏 - `NavButton` 固定使用 Radix Button 的 soft 变体,仅切换选中色,保证点击前后的图标、文字和内边距不变。导航行高至少 40px、行间距 8px,未选中时保持透明,悬停和焦点状态沿用库样式。 - 操作组间距 8px;标签内部的移除按钮使用库的 `size="1"`(24px),图标 14px。 - 输入区使用自有圆角容器 + TextArea + Select;权限使用 DropdownMenu,项目使用带搜索的菜单,复制路径放在文件工具栏;工作标签、请求详情和插件页的「官方插件 / 自定义 MCP」使用 Tabs,网页/网络请求通过地址栏右侧列表按钮切换;主题选择使用 RadioCards;上下文用量使用 Popover。 +- 上下文用量是唯一常驻可见的例外:它随时要回答「窗口还剩多少」,静止时保留描边和底色。圆环 20px、笔画 3px,轨道用 `--gray-9`(相对底色 ≥3:1),用量弧用 `--gray-12`;逼近压缩阈值时整枚胶囊换成琥珀/红底色。不要为了方便把它改回「细灰环 + 静止透明」——那样在深色底上读不出用量,是本控件被打回重做的原因。 按钮、选择器和浮层通过 Radix 的公开 `radius="full"` 主题配置采用更圆润的形状,应用与独立对话框共用同一配置。业务列表和交互行使用10px圆角,工具详情和目标容器使用14px圆角,主输入容器使用22px圆角;不通过私有组件类改写 Radix 的内部比例。紧凑字用于工具元信息,正文保持12–13px,页面标题27px。 @@ -53,13 +54,9 @@ macOS 使用 overlay 标题栏及左上角 AppKit 原生关闭/最小化/全屏 ## 验证 1. `npm run build:ui` 构建前端。 -2. `npm run check:ui` 使用隔离数据目录和真实 sidecar,检查浅深主题、按钮尺寸与命中区域、模型/模式菜单、会话操作菜单与创建/重命名/搜索、全部设置页、面板调整、自动化表单、本地浏览器抓包和响应、最小窗口,以及保存的示例会话。 - - 分节:`node scripts/check-ui.mjs --only=<段>`,段名为 `window`(窗口外壳)、`account`(账号菜单与设置页账号面)、`app`(主流程)。可组合,默认 `all`。只改一处时用它把单次运行从 ~30 秒降到 5–7 秒;全量留给 CI。 - - 依赖:插件页与浏览器抓包段需要 WDH 组件和 CloakBrowser 内核。本机缺失时这两段会被跳过并在结尾列出原因——**跳过不等于通过**。`--only=account` 这类不含依赖段的分节不受影响。 -3. `npm run audit:ui` 禁止覆盖 Radix 基础控件内部类、禁止重复定义组件尺寸体系,同时检查列表点击区域。 -4. 人工复查 `artifacts/ui/` 的浅色与深色截图;示例对话明确标注为 UI 验证数据。 +2. `npm run audit:ui` 禁止覆盖 Radix 基础控件内部类、禁止重复定义组件尺寸体系,同时检查列表点击区域。 +3. `node --test sidecar/test/*.test.mjs` 覆盖生命周期、协议与权限契约。 +4. **视觉走人眼,不走脚本。** UI 的好坏是「看起来对不对」,固定像素断言锁住的是当时那一版的样子而不是意图——改一次间距、换一个圆角就会红,红的是断言不是 bug。需要截图对照时跑 `node scripts/preview.mjs --port 5333 --appdata .tmp/ui-redesign-preview` 在浏览器里看,或直接给用户看发布版。按主题的定向脚本(各 12–14 条、几秒跑完)只用于验证**具体一条交互逻辑**(键盘可达、状态写入、对比度达阈值),不承担"整个界面是否正确",**更不要新建全站 UI 验收脚本**。 本地预览:`node scripts/preview.mjs --port 5333 --appdata .tmp/ui-redesign-preview`。预览使用独立数据目录,不覆盖已安装应用的数据。 diff --git a/package.json b/package.json index 711ac98b33..c3c6f348a5 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,6 @@ "build:ui": "vite build", "dev:ui": "vite", "dev:desktop": "powershell -ExecutionPolicy Bypass -File scripts/dev-desktop.ps1", - "check:ui": "node scripts/check-ui.mjs", "check:memory": "node scripts/check-memory-panel.mjs", "check:reply-images": "node scripts/check-reply-images.mjs", "check:desktop-browser": "node scripts/check-desktop-browser.mjs", diff --git a/scripts/check-memory-panel.mjs b/scripts/check-memory-panel.mjs index c901f4418f..fc9404d8f4 100644 --- a/scripts/check-memory-panel.mjs +++ b/scripts/check-memory-panel.mjs @@ -1,8 +1,8 @@ // 设置 →「记忆与技能」标签页的定向验收。 // -// check:ui 覆盖全站交互,但它的插件页断言需要已安装 WDH 组件,本机没有时会提前中断。 -// 这个脚本只验证本轮新增的那个页面:标签页可进入、列表能读到 sidecar 里真实存在的记忆与技能、 +// 只验证这个页面的一条行为链:标签页可进入、列表能读到 sidecar 里真实存在的记忆与技能、 // 系统记忆只显示来源而不显示正文、删除走确认且能真正移除条目。 +// 不锁像素长相 —— 那是看出来的,不是断言出来的。 // // 用法:node scripts/check-memory-panel.mjs(需先 npm run build:ui) import { spawn } from 'node:child_process'; diff --git a/scripts/check-thinking-ui.mjs b/scripts/check-thinking-ui.mjs index 63bab85191..dac01a2c0a 100644 --- a/scripts/check-thinking-ui.mjs +++ b/scripts/check-thinking-ui.mjs @@ -79,7 +79,7 @@ await new Promise(r => srv.listen(PORT, '127.0.0.1', r)); const { chromium } = await import('../node_modules/@zhizhuodemao/patchright/index.mjs'); const browser = await chromium.launch({ headless: true, executablePath: CHROME }); -const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: 'dark' }); +const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: process.env.JSRA_UI_SCHEME || 'dark' }); const page = await context.newPage(); const pageErrors = []; page.on('pageerror', e => pageErrors.push(e.message)); @@ -126,9 +126,11 @@ try { // 顶部闪电已按要求移除(触发器与浮层都不留) ok(await pop.locator('.thinking-bolt').count() === 0, '浮层不应再有闪电图标'); ok(await page.locator('.seat-trigger .seat-bolt').count() === 0, '触发器不应再有闪电图标'); - // 底部必须如实说出会发什么,而不是只写「更聪明」 - const payload = await pop.locator('.thinking-payload').innerText(); - ok(/reasoning_effort: medium/.test(payload), '应显示实际发送的参数(实际 ' + JSON.stringify(payload) + ')'); + // 浮层里不该出现 JSON 字段名:用户点开只是想选档位,reasoning_effort / thinking.type + // 是适配器的实现细节,写在设置页以外的任何地方都是噪音。 + ok(await pop.locator('.thinking-payload').count() === 0, '浮层不应再显示请求参数字面量'); + const popText = await pop.innerText(); + ok(!/reasoning_effort|budget_tokens|thinking\.type/.test(popText), '浮层不应出现字段名字面量(实际 ' + JSON.stringify(popText.replace(/\n/g, ' ')) + ')'); await page.screenshot({ path: path.join(ROOT, '.thinking-ui-pop.png') }); // 3) 点最高档 → 写入 settings.json,触发器跟着变 @@ -137,16 +139,16 @@ try { ok(readSettings().activeThinking === 'high', '选高后应写入 activeThinking=high(实际 ' + JSON.stringify(readSettings().activeThinking) + ')'); await trigger.waitFor(); ok(/高/.test((await trigger.innerText()).trim()), '触发器应显示「高」(实际 ' + JSON.stringify((await trigger.innerText()).trim()) + ')'); - const payloadHigh = await pop.locator('.thinking-payload').innerText(); - ok(/reasoning_effort: high/.test(payloadHigh), '高对应 reasoning_effort: high(实际 ' + JSON.stringify(payloadHigh) + ')'); await page.keyboard.press('Escape'); - // 4) 键盘可达:聚焦档位条后按 Home/ArrowRight 也能改档 + // 4) 键盘可达:焦点落在当前档那一段上,Home/ArrowRight/End 也能改档 // 注意必须重新打开浮层——上一步按 Escape 已经把它卸载,对已卸载节点 focus() 不会生效。 await trigger.click(); await page.locator('.seat-pop').waitFor({ timeout: 8000 }); - const bar = page.locator('.seat-pop .thinking-steps'); - await bar.focus(); + const currentStep = page.locator('.seat-pop .thinking-steps .thinking-step.on'); + ok(await currentStep.count() === 1, '当前档应恰好有一段标 on(实际 ' + await currentStep.count() + ')'); + await currentStep.focus(); + ok(await page.evaluate(() => document.activeElement?.getAttribute('role') === 'radio'), '档位条应把焦点交给当前档那一段'); await page.keyboard.press('Home'); await page.waitForTimeout(300); ok(readSettings().activeThinking === 'off', 'Home 应选中第一档关闭(实际 ' + JSON.stringify(readSettings().activeThinking) + ')'); @@ -185,6 +187,14 @@ try { await page.getByRole('dialog', { name: '编辑渠道' }).waitFor(); const badges = await page.locator('.model-row').allInnerTexts(); ok(badges.some(text => /思考 关闭 \/ 低 \/ 中 \/ 高/.test(text)), '模型行应显示声明的档位(实际 ' + JSON.stringify(badges) + ')'); + // 进模型编辑弹窗:只声明档位,不该出现「发送方式」这种让用户挑 JSON 字段名的控件。 + await page.locator('.model-row').first().getByRole('button', { name: '编辑模型', exact: true }).click(); + const modelDialog = page.getByRole('dialog', { name: '编辑模型' }); + await modelDialog.waitFor(); + const dialogText = await modelDialog.innerText(); + ok(!/发送方式/.test(dialogText), '模型编辑不应再有「发送方式」控件'); + ok(!/reasoning_effort|budget_tokens|thinking\.type/.test(dialogText), '模型编辑不应出现字段名字面量(实际 ' + JSON.stringify(dialogText.replace(/\n/g, ' ').slice(0, 300)) + ')'); + ok(/支持的思考强度/.test(dialogText), '仍应能声明支持的档位'); await page.screenshot({ path: path.join(ROOT, '.thinking-ui-settings.png') }); ok(pageErrors.length === 0, '页面不应有运行时错误:' + pageErrors.join(' | ')); diff --git a/scripts/check-title-prefix.mjs b/scripts/check-title-prefix.mjs index 35b8992988..de670fa067 100644 --- a/scripts/check-title-prefix.mjs +++ b/scripts/check-title-prefix.mjs @@ -44,7 +44,7 @@ await new Promise((res, rej) => { sidecar.stdout.on('data', d => { if (/JSRA_PORT=/.test(String(d))) { clearTimeout(t); res(); } }); }); -// 与 check-ui.mjs 同构:一条长连接发 invoke,按 id 收结果。 +// 一条长连接发 invoke,按 id 收结果。 const rpc = (channel, args = {}) => new Promise((resolve, reject) => { const ws = new WebSocket('ws://127.0.0.1:' + WS_PORT + '/?token=' + TOKEN); const timer = setTimeout(() => { ws.terminate(); reject(Error('RPC timeout: ' + channel)); }, 30000); @@ -52,7 +52,7 @@ const rpc = (channel, args = {}) => new Promise((resolve, reject) => { ws.on('message', raw => { const message = JSON.parse(raw); if (message.id !== 1) return; clearTimeout(timer); ws.close(); message.error ? reject(Error(message.error)) : resolve(message.result); }); ws.once('error', error => { clearTimeout(timer); reject(error); }); }); -// 跳过首次引导,避免弹层抢时序(check-ui.mjs 同样这么做)。 +// 跳过首次引导,避免弹层抢时序。 await rpc('save-settings', { onboarding: { version: 1, completedAt: new Date().toISOString() } }).catch(error => console.error('save onboarding:', error.message)); const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png' }; diff --git a/scripts/dev-desktop.ps1 b/scripts/dev-desktop.ps1 index 0e5d8b3ed4..11413ef9f1 100644 --- a/scripts/dev-desktop.ps1 +++ b/scripts/dev-desktop.ps1 @@ -44,7 +44,9 @@ if (-not (Test-Port $vitePort)) { $before = @{ Node = $env:JSRA_SIDECAR_NODE; AppData = $env:DECRYPTHUB_DATA_DIR; DevUrl = $env:JSRA_UI_DEV_URL; Community = $env:DECRYPTHUB_COMMUNITY_URL } try { $env:JSRA_SIDECAR_NODE = $sidecarEntry - $env:DECRYPTHUB_DATA_DIR = Join-Path $root '.tmp\desktop-appdata\WebDecryptHub' + # 开发版默认也用产品正式数据目录,避免「同一个软件换个入口就是另一份空工作台」。 + # 需要与日常数据隔离时显式传 DECRYPTHUB_DATA_DIR=<绝对路径>。 + if (-not $env:DECRYPTHUB_DATA_DIR) { $env:DECRYPTHUB_DATA_DIR = Join-Path $env:APPDATA 'DecryptHub' } $env:JSRA_UI_DEV_URL = "http://127.0.0.1:$vitePort/" # DECRYPTHUB_COMMUNITY_URL 只影响 debug 构建;留空则连生产社区 decrypthub.cn。 # 连测试服:$env:DECRYPTHUB_COMMUNITY_URL = 'https://decrypthub.taisuii.cn' diff --git a/scripts/start-desktop.ps1 b/scripts/start-desktop.ps1 index dcad66483b..1dd2265d60 100644 --- a/scripts/start-desktop.ps1 +++ b/scripts/start-desktop.ps1 @@ -1,4 +1,4 @@ -# Launch the locally built Tauri app with the current sidecar source. +# Launch the locally built Tauri app with the current sidecar source. # Keep this file ASCII for Windows PowerShell 5.1 without a UTF-8 BOM. param([string]$BinaryPath) $ErrorActionPreference = 'Stop' @@ -26,7 +26,8 @@ $desktopOldEntry = $env:JSRA_SIDECAR_NODE $desktopOldAppData = $env:DECRYPTHUB_DATA_DIR try { $env:JSRA_SIDECAR_NODE = $desktopEntry - $env:DECRYPTHUB_DATA_DIR = Join-Path $desktopRoot '.tmp\desktop-appdata\WebDecryptHub' + # 与正式版共用同一个产品数据目录(以前指向 .tmp,导致两份对话互不可见)。 + if (-not $env:DECRYPTHUB_DATA_DIR) { $env:DECRYPTHUB_DATA_DIR = Join-Path $env:APPDATA 'DecryptHub' } $desktopProcess = Start-Process -FilePath $desktopBinary -WorkingDirectory $desktopRoot -WindowStyle Hidden -PassThru ` -RedirectStandardOutput (Join-Path $desktopLogs 'desktop-stdout.log') ` -RedirectStandardError (Join-Path $desktopLogs 'desktop-stderr.log') diff --git a/sidecar/index.mjs b/sidecar/index.mjs index abf97ebb4a..c474032477 100644 --- a/sidecar/index.mjs +++ b/sidecar/index.mjs @@ -125,8 +125,9 @@ async function startServer() { 'mcp-restart': async a => { await mcpHost.restart(String(a?.name || '')); return mcpHost.status(); }, 'mcp-save': a => extensions.saveMcp(a?.servers || {}, a?.approveNames || []), 'projects-list': () => sessions.projects.list(), - // 没有项目归属的历史会话:只报告,不自动处理。删除必须由用户在界面上明确选择。 + // 没有项目归属的历史会话:只报告,不自动处理。恢复/删除都必须由用户在界面上明确选择。 'legacy-sessions': () => sessions.legacySessions(), + 'legacy-sessions-restore': a => sessions.restoreLegacySessions(a?.ids), 'legacy-sessions-discard': a => sessions.discardLegacySessions(a?.ids), 'project-save': a => projects.save(a.project || {}, a.scope || a.sessionId), 'projects-check': () => projects.checkDirectories(), diff --git a/sidecar/providers/openai.mjs b/sidecar/providers/openai.mjs index 8f0faed82f..1c9996178e 100644 --- a/sidecar/providers/openai.mjs +++ b/sidecar/providers/openai.mjs @@ -11,7 +11,7 @@ export function toOpenAITools(tools) { // 若服务端拒绝消息中的 reasoning_content(部分官方 reasoner 会 400),自动剥离后重试。 export async function completeOpenAI(cfg, messages, tools, { onDelta, onReasoning, signal } = {}) { const headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + cfg.apiKey }; - let stripReasoning = false, useStreamOpts = true, dropThinking = false; + let stripReasoning = false, useStreamOpts = true, dropThinking = false, dropEffort = false; for (let attempt = 0; ; attempt++) { const msgs = messages.map(m => { if (m.role !== 'assistant') return m; @@ -20,12 +20,14 @@ export async function completeOpenAI(cfg, messages, tools, { onDelta, onReasonin }); const body = { model: cfg.model, messages: msgs, stream: true, temperature: cfg.temperature ?? 0.2 }; if (cfg.maxTokens) body.max_tokens = cfg.maxTokens; - // 思考强度由用户在渠道里逐模型声明:effort → reasoning_effort,switch → thinking.type,none → 不发。 - const thinking = dropThinking ? null : openAIThinking({ ...(cfg.thinking || {}), requestPurpose: cfg.requestPurpose }); - if (thinking) body[thinking.field] = thinking.value; + // 思考参数由端点协议自动决定(见 deriveTransport):强度 → reasoning_effort, + // 开关型 → thinking.type(开启时再叠加 reasoning_effort 表达「开多大」),未声明 → 一个都不发。 + const thinking = openAIThinking({ ...(cfg.thinking || {}), requestPurpose: cfg.requestPurpose }) + .filter(({ field }) => !dropThinking && !(dropEffort && field === 'reasoning_effort')); + for (const { field, value } of thinking) body[field] = value; // 会话标题是元数据,不该花思考预算:DeepSeek V4 默认思考,会把 256 token 的标题预算吃光。 // 这条与会话标题的思考声明无关,是独立保护,所以在这里兜底而不是塞进 openAIThinking。 - else if (cfg.requestPurpose === 'session-title' && /deepseek[-_/](?:v4|flash)|deepseek[-_/]reasoner|deepseek-r1/i.test(cfg.model || '') && body.thinking === undefined) body.thinking = { type: 'disabled' }; + if (cfg.requestPurpose === 'session-title' && /deepseek[-_/](?:v4|flash)|deepseek[-_/]reasoner|deepseek-r1/i.test(cfg.model || '') && body.thinking === undefined) body.thinking = { type: 'disabled' }; if (useStreamOpts) body.stream_options = { include_usage: true }; if (tools.length) { body.tools = toOpenAITools(tools); body.tool_choice = 'auto'; } let content = '', reasoning = '', usage = null, finishReason = null, completed = false; const calls = {}; @@ -53,8 +55,11 @@ export async function completeOpenAI(cfg, messages, tools, { onDelta, onReasonin } catch (e) { const msg = String(e.message || e); // 端点不认思考参数(老模型 / 中转未透传):去掉参数重试,而不是让整个请求失败。 + // 两个字段分开剥:开关型端点的常见失败是「只认 thinking.type,不认 reasoning_effort」, + // 一刀切会把能用的那一半也扔掉,等于悄悄降级成「开/关」而不告诉任何人。 // 必须先于下面那条判定——"reasoning_effort" 也含 reasoning,否则会被误判成「消息里禁止 reasoning_content」。 - if (e.status === 400 && !dropThinking && thinking && /reasoning_effort|thinking/i.test(msg)) { dropThinking = true; continue; } + if (e.status === 400 && !dropEffort && thinking.some(t => t.field === 'reasoning_effort') && /reasoning_effort|\beffort\b/i.test(msg)) { dropEffort = true; continue; } + if (e.status === 400 && !dropThinking && thinking.some(t => t.field === 'thinking') && /thinking/i.test(msg)) { dropThinking = true; continue; } if (e.status === 400 && !stripReasoning && /reasoning/i.test(msg)) { stripReasoning = true; continue; } if (e.status === 400 && useStreamOpts && /stream_options/i.test(msg)) { useStreamOpts = false; continue; } throw e; diff --git a/sidecar/sessions.mjs b/sidecar/sessions.mjs index ca828f6732..40ab8272a1 100644 --- a/sidecar/sessions.mjs +++ b/sidecar/sessions.mjs @@ -574,15 +574,17 @@ export class SessionManager { this.sessions = new Map(); this.focusedId = null; this.seq = 0; this.stateFile = path.join(userDataDir, 'sessions.json'); // 无项目归属的历史会话:不恢复、不自动迁移,也不从索引里抹掉。 - // 它们属于「项目」概念出现之前的数据;是否删除由用户在界面上明确决定 - // (见 UI 的 legacy-sessions 提示与下面的 discardLegacySessions)。 + // 它们属于「项目」概念出现之前的数据;是否恢复或删除由用户在界面上明确决定 + // (见 UI 的 legacy-sessions 提示与下面的 restoreLegacySessions / discardLegacySessions)。 // 这里只是把它们原样留在索引里,避免 emitList 写盘时顺手把用户数据写成「已删除」。 this.legacyEntries = []; // 恢复上次的会话标签(标题、最后访问的网址、对话上下文;浏览器按需再启动) let saved = null; try { saved = JSON.parse(fs.readFileSync(this.stateFile, 'utf8')); } catch {} + const indexed = new Set(); if (saved?.sessions?.length) { for (const x of saved.sessions.slice(0, MAX_SESSIONS)) { if (!/^(?:main|s(?:[0-9a-f]{6}|[0-9a-f]{32}))$/.test(x.id) || !!x.primary !== (x.id === 'main')) throw Error('会话索引身份无效'); + indexed.add(x.id); const stateFile = path.join(userDataDir, 'projects', x.primary ? 'default' : x.id, '.agent-state.json'); let state = null; try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch {} if (!state?.projectId) { this.legacyEntries.push({ ...x }); continue; } @@ -592,16 +594,108 @@ export class SessionManager { if (!this.focusedId) this.focusedId = this.sessions.values().next().value?.id || null; this.seq = Math.max(this.seq, saved.seq || 0); } + this.adoptOrphans(indexed); + } + /** + * 把「磁盘上有数据目录、索引里却没有」的会话收进历史会话列表。 + * 这类会话比没有 projectId 的更隐蔽:它不在索引里,所以既不会被恢复, + * 也不会出现在删除提示里——用户完全看不到它存在。只收有 .agent-history.json + * (真有对话)的目录,避免把空壳目录也列出来。 + */ + adoptOrphans(indexed) { + let names = []; + try { names = fs.readdirSync(path.join(this.userDataDir, 'projects'), { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name); } catch { return; } + for (const name of names) { + if (indexed.has(name) || this.legacyEntries.some(x => x.id === name)) continue; + if (!/^(?:main|s(?:[0-9a-f]{6}|[0-9a-f]{32}))$/.test(name)) continue; + const dir = path.join(this.userDataDir, 'projects', name); + if (!fs.existsSync(path.join(dir, '.agent-history.json'))) continue; + let state = null; try { state = JSON.parse(fs.readFileSync(path.join(dir, '.agent-state.json'), 'utf8')); } catch {} + this.legacyEntries.push({ + id: name, title: '', primary: name === 'main', updatedAt: 0, pinned: false, orphan: true, + }); + } } /** 等待用户决定如何处理的历史会话(项目概念之前创建、没有 projectId)。 */ legacySessions() { - return this.legacyEntries.map(x => ({ - id: x.id, - title: String(x.title || x.id || ''), - primary: !!x.primary, - updatedAt: Number(x.updatedAt) || 0, - url: String(x.url || ''), - })); + return this.legacyEntries.map(x => { + // restorable 只表示「结构上能接回当前模型」,不代表一定能成功;真正裁决在 restoreLegacySessions。 + const stateFile = path.join(this.userDataDir, 'projects', x.primary ? 'default' : x.id, '.agent-state.json'); + let state = null; try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch {} + const ws = state?.workspace || {}; + const hasProject = !!(state?.projectId && this.projects.entries.some(p => p.id === state.projectId)); + return { + id: x.id, + title: String(x.title || this.orphanTitle(x.id) || x.id || ''), + primary: !!x.primary, + updatedAt: Number(x.updatedAt) || this.historyMtime(x.id), + url: String(x.url || ''), + kind: ws.kind === 'managed' ? 'managed' : 'folder', + hasProject, + restorable: hasProject || !!(ws.kind === 'managed' ? ws.id : ws.root), + }; + }); + } + /** 没有索引条目的孤儿会话没有标题,用第一条用户消息代替 id,至少让人认得出是哪段对话。 */ + orphanTitle(id) { + try { + const raw = JSON.parse(fs.readFileSync(path.join(this.userDataDir, 'projects', id, '.agent-history.json'), 'utf8')); + const first = (raw.events || []).find(e => e?.t === 'user' && typeof e.content === 'string' && e.content.trim() && !e.content.startsWith('【')); + const text = String(first?.content || '').replace(/【[^】]*】[\s\S]*$/, '').replace(/\s+/g, ' ').trim(); + if (text) return text.slice(0, 40); + } catch {} + return ''; + } + historyMtime(id) { + try { return fs.statSync(path.join(this.userDataDir, 'projects', id, '.agent-history.json')).mtimeMs; } catch { return 0; } + } + /** + * 把用户明确要求保留的历史会话接回当前模型(不删除任何东西)。 + * 两条路径: + * - 已有合法 projectId 且项目还在 → 只把会话补回索引(原先"关闭的标签"重新出现)。 + * - 没有 projectId → 为它建一个只含单个目录的项目: + * 托管工作区改指当前数据目录下的同名目录(旧版本可能记着另一个安装路径); + * 用户文件夹必须仍然存在,否则拒绝并报告原因。 + * 逐条独立处理:一条失败不影响其它,也绝不写坏已成功的索引。 + */ + async restoreLegacySessions(ids) { + const wanted = new Set((Array.isArray(ids) ? ids : []).map(String)); + const restored = [], skipped = []; + for (const entry of this.legacyEntries) { + if (!wanted.has(entry.id)) continue; + const stateFile = path.join(this.userDataDir, 'projects', entry.primary ? 'default' : entry.id, '.agent-state.json'); + let state = null; try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch {} + if (!state) { skipped.push({ id: entry.id, title: entry.title, reason: '会话状态文件缺失,无法确认工作区' }); continue; } + try { + const projectId = this.ensureProjectFor(entry, state); + atomicJson(stateFile, { ...state, projectId }); + this.create({ id: entry.id, title: entry.title, updatedAt: entry.updatedAt, pinned: entry.pinned, quiet: true, projectId }); + this.legacyEntries = this.legacyEntries.filter(x => x.id !== entry.id); + restored.push({ id: entry.id, title: entry.title, projectId }); + } catch (error) { skipped.push({ id: entry.id, title: entry.title, reason: error.message }); } + } + if (restored.length) this.emitList(); + return { restored, skipped }; + } + /** 历史会话要接回当前模型,必须先有一个项目;已有合法项目就复用。 */ + ensureProjectFor(entry, state) { + if (state.projectId && this.projects.entries.some(p => p.id === state.projectId)) return state.projectId; + const ws = state.workspace || {}; + const managed = ws.kind === 'managed'; + // 托管工作区永远是数据目录下的 projects/<会话 id>/workspace:跟着数据目录走,不保留旧安装路径。 + const root = managed ? path.join(this.userDataDir, 'projects', entry.id, 'workspace') : ws.root; + if (!root) throw Error('会话缺少工作区信息,无法恢复'); + if (managed) fs.mkdirSync(root, { recursive: true }); + else { + let st = null; try { st = fs.statSync(root); } catch {} + if (!st?.isDirectory()) throw Error('原工作文件夹已不存在:' + root); + if (pathKey(fs.realpathSync.native(this.userDataDir)) === pathKey(fs.realpathSync.native(root)) || root.startsWith(this.userDataDir + path.sep)) + throw Error('工作区位于应用数据目录内,不能作为代码工作区'); + } + const folder = { id: ws.id || crypto.randomUUID(), kind: managed ? 'managed' : 'folder', root, revision: 1, label: ws.label || '恢复的会话' }; + const title = String(entry.title || entry.id || '').trim() || entry.id; + const project = this.projects.save({ name: ('恢复:' + title).slice(0, 80), folders: [folder], primaryId: folder.id }); + return project.id; } /** * 删除用户明确要求清理的历史会话。 diff --git a/sidecar/settings.mjs b/sidecar/settings.mjs index e7aaacb73c..25e154146d 100644 --- a/sidecar/settings.mjs +++ b/sidecar/settings.mjs @@ -9,6 +9,11 @@ import { normalizeThinking, ALL_LEVELS } from './thinking.mjs'; // Chrome for Testing 不再作为选项:load 与 save 都归一到这里,旧的 settings.json 会被静默迁移。 export const KERNEL = 'cloak'; +// 应用数据目录名 = 产品名。不要写成 WebDecryptHub:那是浏览器组件 WDH 的仓库名,不是本产品。 +export const DATA_DIR_NAME = 'DecryptHub'; +// 旧目录名,按从新到旧排列;只在 DATA_DIR_NAME 不存在时逐个前移迁移。 +export const LEGACY_DATA_DIR_NAMES = ['WebDecryptHub', 'JSReverseAgent']; + const DEFAULTS = { provider: 'openai', openai: { baseUrl: 'https://api.openai.com/v1', apiKey: '', model: 'gpt-4o' }, @@ -36,9 +41,13 @@ export function userDataDir() { const base = process.platform === 'win32' ? (process.env.APPDATA || os.homedir()) : process.platform === 'darwin' ? path.join(os.homedir(), 'Library', 'Application Support') : (process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config')); - const d = path.join(base, 'WebDecryptHub'); - const legacy = path.join(base, 'JSReverseAgent'); - try { if (!fs.existsSync(d) && fs.existsSync(legacy)) fs.renameSync(legacy, d); } catch {} + // 产品正式名是 DecryptHub。目录名历史上的演变是 JSReverseAgent → WebDecryptHub → DecryptHub, + // 每次只往前挪一格,且只在目标不存在时搬,避免把用户刚建的空目录当成"已迁移"而丢数据。 + const d = path.join(base, DATA_DIR_NAME); + for (const name of LEGACY_DATA_DIR_NAMES) { + const legacy = path.join(base, name); + try { if (!fs.existsSync(d) && fs.existsSync(legacy)) fs.renameSync(legacy, d); } catch {} + } fs.mkdirSync(d, { recursive: true }); return d; } diff --git a/sidecar/test/browser-fixture.mjs b/sidecar/test/browser-fixture.mjs index 818fdae22b..03af99340a 100644 --- a/sidecar/test/browser-fixture.mjs +++ b/sidecar/test/browser-fixture.mjs @@ -6,7 +6,7 @@ // // 优先级: // 1. WDH_TEST_EXECUTABLE:显式指定,CI 或特殊机器用。 -// 2. CHROME_PATH:与 scripts/check-ui.mjs 同一个约定,本机开发保持一致。 +// 2. CHROME_PATH:与各定向脚本(check-*.mjs)同一个约定,本机开发保持一致。 // 3. 常见系统 Chrome/Edge 安装位置。 // 都找不到时调用方应跳过用例并说明原因,而不是报失败。 import fs from 'node:fs'; diff --git a/sidecar/test/legacy-restore.test.mjs b/sidecar/test/legacy-restore.test.mjs new file mode 100644 index 0000000000..606570b60e --- /dev/null +++ b/sidecar/test/legacy-restore.test.mjs @@ -0,0 +1,189 @@ +// 历史会话(项目概念之前创建、没有 projectId)的恢复: +// 这些数据在界面上既不可见也不能删,只能靠 legacy-sessions 系列 RPC 处理。 +// 恢复必须做到:不丢记录、不改坏索引、逐条独立失败。 +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { SessionManager } from '../sessions.mjs'; + +function tmpRoot(t, prefix) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + t.after(() => { if (path.dirname(root) === os.tmpdir()) fs.rmSync(root, { recursive: true, force: true }); }); + return root; +} + +/** 造一份「项目概念之前」的数据:索引里有条目,但 .agent-state.json 没有 projectId */ +function seedLegacy(app, { id, title, workspace, history = [{ t: 'user', content: 'old conversation' }], projectId = null }) { + const dir = path.join(app, 'projects', id); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, '.agent-state.json'), JSON.stringify({ mode: 'standard', review: 'manual', todos: [], workspace, projectId })); + fs.writeFileSync(path.join(dir, '.agent-history.json'), JSON.stringify({ v: 2, events: history })); + const file = path.join(app, 'sessions.json'); + const saved = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : { focused: null, seq: 0, sessions: [] }; + saved.sessions.push({ id, title, primary: false, updatedAt: 1793000000000, pinned: false }); + fs.writeFileSync(file, JSON.stringify(saved)); + return dir; +} + +const settings = { openai: { apiKey: 'fixture', model: 'test' }, mcpServers: {} }; +function manager(app) { return new SessionManager({ userDataDir: app, getSettings: () => settings, broadcast() {}, chromeMod: {} }); } + +test('托管工作区的历史会话:恢复后重新出现在索引里,对话记录原样保留', async t => { + const root = tmpRoot(t, 'dh-legacy-managed-'), app = path.join(root, 'app'); + // 旧版本会把工作区记成另一个安装路径;恢复时必须改指当前数据目录,而不是继续指向那个不存在的路径 + const staleRoot = path.join(root, 'old-checkout', 'projects', 'saa0001', 'workspace'); + seedLegacy(app, { id: 'saa0001', title: '老的小红书分析', workspace: { id: 'managed-saa0001', kind: 'managed', root: staleRoot, revision: 1, label: '会话工作区' } }); + + const first = manager(app); + try { + assert.equal(first.sessions.size, 0, '无 projectId 的历史会话不应被自动载入'); + assert.equal(first.legacySessions().length, 1); + assert.equal(first.legacySessions()[0].kind, 'managed'); + assert.equal(first.legacySessions()[0].restorable, true); + + const result = await first.restoreLegacySessions(['saa0001']); + assert.deepEqual(result.skipped, []); + assert.equal(result.restored.length, 1); + assert.equal(first.sessions.size, 1, '恢复后应立刻回到会话表'); + assert.equal(first.legacySessions().length, 0, '恢复过的不该继续算历史会话'); + // 工作区必须落在当前数据目录下,并真的建出来 + assert.equal(first.get('saa0001').workspace.root, path.join(app, 'projects', 'saa0001', 'workspace')); + assert.equal(fs.existsSync(first.get('saa0001').workspace.root), true); + // 对话事件没被碰过 + const hist = JSON.parse(fs.readFileSync(path.join(app, 'projects', 'saa0001', '.agent-history.json'), 'utf8')); + assert.equal(hist.events[0].content, 'old conversation'); + } finally { await first.closeAll(); } + + // 重启后仍然可见:证明 write 的是持久状态,不是只在内存里恢复 + const second = manager(app); + try { + assert.equal(second.sessions.size, 1); + assert.equal(second.get('saa0001').projectId, first.projects.list()[0].id); + assert.equal(second.legacySessions().length, 0); + } finally { await second.closeAll(); } +}); + +test('用户文件夹工作区的历史会话:文件夹还在就恢复,已删除则明确跳过且不动数据', async t => { + const root = tmpRoot(t, 'dh-legacy-folder-'), app = path.join(root, 'app'); + const alive = path.join(root, 'DH_Project'), gone = path.join(root, 'deleted-folder'); + fs.mkdirSync(alive); + seedLegacy(app, { id: 'sbb0001', title: '武汉游泳馆', workspace: { id: 'f-1', kind: 'folder', root: alive, revision: 1, label: 'DH_Project' } }); + seedLegacy(app, { id: 'sbb0002', title: '已删目录的会话', workspace: { id: 'f-2', kind: 'folder', root: gone, revision: 1, label: 'gone' } }); + + const mgr = manager(app); + try { + const result = await mgr.restoreLegacySessions(['sbb0001', 'sbb0002']); + assert.equal(result.restored.length, 1); + assert.equal(result.restored[0].id, 'sbb0001'); + // Windows 上同一个目录有 8.3 短路径(RUNNER~1)与长路径两种写法, + // 直接比字符串会把「同一目录」判成不同。比较前统一取一次真实路径。 + assert.equal(fs.realpathSync.native(mgr.get('sbb0001').workspace.root), fs.realpathSync.native(alive)); + // 失败的必须给出可读原因,并且原样留在历史会话里等用户处理 + assert.equal(result.skipped.length, 1); + assert.equal(result.skipped[0].id, 'sbb0002'); + assert.match(result.skipped[0].reason, /不存在/); + assert.equal(mgr.legacySessions().length, 1); + assert.equal(mgr.legacySessions()[0].id, 'sbb0002'); + // 跳过的那条状态文件不能被写脏(projectId 仍为空) + const state = JSON.parse(fs.readFileSync(path.join(app, 'projects', 'sbb0002', '.agent-state.json'), 'utf8')); + assert.equal(state.projectId, null); + } finally { await mgr.closeAll(); } +}); + +test('索引里存在且 projectId 合法时会话正常加载,不会被当成历史会话', async t => { + const root = tmpRoot(t, 'dh-legacy-hasproject-'), app = path.join(root, 'app'); + const folder = path.join(root, 'code'); fs.mkdirSync(folder); + const setup = new SessionManager({ userDataDir: app, getSettings: () => settings, broadcast() {}, chromeMod: {} }); + const entry = setup.workspaces.folder(folder); + const projectId = setup.projects.save({ name: '既有项目', folders: [entry], primaryId: entry.id }).id; + await setup.closeAll(); + + seedLegacy(app, { id: 'scc0001', title: '控制我的浏览器', workspace: { ...entry }, projectId }); + + const mgr = manager(app); + try { + // 关键区分:这类会话不需要「恢复」,构造时就应该直接回到会话表 + assert.equal(mgr.sessions.size, 1); + assert.equal(mgr.get('scc0001').projectId, projectId); + assert.equal(mgr.legacySessions().length, 0, '能正常加载的会话不该出现在历史会话提示里'); + const result = await mgr.restoreLegacySessions(['scc0001']); + assert.deepEqual(result, { restored: [], skipped: [] }, '没有待恢复项,也不能凭空新建项目'); + } finally { await mgr.closeAll(); } +}); + +test('磁盘上有对话但索引里没有的孤儿会话也会被列出来(否则用户永远看不到它)', async t => { + const root = tmpRoot(t, 'dh-legacy-orphan-'), app = path.join(root, 'app'); + const folder = path.join(root, 'code'); fs.mkdirSync(folder); + const setup = new SessionManager({ userDataDir: app, getSettings: () => settings, broadcast() {}, chromeMod: {} }); + const entry = setup.workspaces.folder(folder); + const projectId = setup.projects.save({ name: '既有项目', folders: [entry], primaryId: entry.id }).id; + await setup.closeAll(); + + // 有完整数据目录与合法 projectId,但 sessions.json 里没有它 —— 索引丢失的真实情形 + const dir = path.join(app, 'projects', 'sff0001'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, '.agent-state.json'), JSON.stringify({ mode: 'standard', workspace: { ...entry }, projectId })); + fs.writeFileSync(path.join(dir, '.agent-history.json'), JSON.stringify({ v: 2, events: [{ t: 'user', content: '帮我查一下武汉游泳馆的票价 【当前状态(应用自动附加)】…' }] })); + // 只有空壳目录、没有对话记录的不该被当成会话 + fs.mkdirSync(path.join(app, 'projects', 'sff0002'), { recursive: true }); + fs.writeFileSync(path.join(app, 'projects', 'sff0002', '.agent-state.json'), JSON.stringify({ mode: 'standard' })); + fs.writeFileSync(path.join(app, 'sessions.json'), JSON.stringify({ focused: null, seq: 1, sessions: [] })); + + const mgr = manager(app); + try { + const list = mgr.legacySessions(); + assert.equal(list.length, 1, '只有带对话记录的目录才算历史会话'); + const [orphan] = list; + assert.equal(orphan.id, 'sff0001'); + // 没有索引条目就没有标题,用第一条用户消息代替裸 id + assert.match(orphan.title, /武汉游泳馆/); + assert.ok(!orphan.title.includes('【'), '应用自动附加的状态块不该混进标题'); + assert.ok(orphan.updatedAt > 0, '没有索引时间戳时用对话文件的修改时间'); + + const result = await mgr.restoreLegacySessions(['sff0001']); + assert.equal(result.restored.length, 1); + assert.equal(mgr.get('sff0001').projectId, projectId); + assert.equal(mgr.legacySessions().length, 0); + } finally { await mgr.closeAll(); } + + // 恢复后必须写进索引,重启仍在 + const again = manager(app); + try { assert.equal(again.sessions.size, 1); assert.equal(again.legacySessions().length, 0); } + finally { await again.closeAll(); } +}); + +test('恢复空列表或未知 id 时不产生任何写入', async t => { + const root = tmpRoot(t, 'dh-legacy-noop-'), app = path.join(root, 'app'); + seedLegacy(app, { id: 'sdd0001', title: '留着', workspace: { id: 'managed-sdd0001', kind: 'managed', root: path.join(app, 'projects', 'sdd0001', 'workspace'), revision: 1 } }); + const mgr = manager(app); + try { + const projectsBefore = mgr.projects.list().length; + assert.deepEqual(await mgr.restoreLegacySessions([]), { restored: [], skipped: [] }); + assert.deepEqual(await mgr.restoreLegacySessions(['does-not-exist']), { restored: [], skipped: [] }); + assert.equal(mgr.projects.list().length, projectsBefore); + assert.equal(mgr.legacySessions().length, 1, '没点名的历史会话必须原样留着'); + } finally { await mgr.closeAll(); } +}); + +test('状态文件缺失的历史会话被跳过而不是让整个恢复失败', async t => { + const root = tmpRoot(t, 'dh-legacy-missing-'), app = path.join(root, 'app'); + seedLegacy(app, { id: 'see0001', title: '正常', workspace: { id: 'managed-see0001', kind: 'managed', root: path.join(app, 'projects', 'see0001', 'workspace'), revision: 1 } }); + // 索引里有、但状态文件被删掉:不能因此抛异常,也不能悄悄当成成功 + fs.mkdirSync(path.join(app, 'projects', 'see0002'), { recursive: true }); + const file = path.join(app, 'sessions.json'); + const saved = JSON.parse(fs.readFileSync(file, 'utf8')); + saved.sessions.push({ id: 'see0002', title: '状态丢失', primary: false, updatedAt: 1793000000000, pinned: false }); + fs.writeFileSync(file, JSON.stringify(saved)); + + const mgr = manager(app); + try { + const result = await mgr.restoreLegacySessions(['see0001', 'see0002']); + assert.equal(result.restored.length, 1); + assert.equal(result.restored[0].id, 'see0001'); + assert.equal(result.skipped.length, 1); + assert.equal(result.skipped[0].id, 'see0002'); + assert.match(result.skipped[0].reason, /缺失|无法确认/); + } finally { await mgr.closeAll(); } +}); diff --git a/sidecar/test/settings.test.mjs b/sidecar/test/settings.test.mjs index 25736b48b7..12a3617564 100644 --- a/sidecar/test/settings.test.mjs +++ b/sidecar/test/settings.test.mjs @@ -94,3 +94,81 @@ test('browserPresentation: macOS 默认串流;停靠模式有头且不串流', assert.deepEqual(mod.browserPresentation({ headless: true, embedMode: 'docked' }, 'darwin', {}), { embed: false, headless: true, dock: false }); assert.deepEqual(mod.browserPresentation({ headless: false, embedMode: 'docked' }, 'win32', {}), { embed: true, headless: false, dock: false }); }); + +/** 清掉 DECRYPTHUB_DATA_DIR,让 userDataDir() 走真实的 APPDATA 分支 */ +async function withBase(fn) { + const prev = { data: process.env.DECRYPTHUB_DATA_DIR, appdata: process.env.APPDATA, xdg: process.env.XDG_CONFIG_HOME }; + delete process.env.DECRYPTHUB_DATA_DIR; + try { return await fn(); } finally { + for (const [k, v] of [['DECRYPTHUB_DATA_DIR', prev.data], ['APPDATA', prev.appdata], ['XDG_CONFIG_HOME', prev.xdg]]) { + if (v === undefined) delete process.env[k]; else process.env[k] = v; + } + } +} + +test('默认数据目录用产品名 DecryptHub,不再叫 WebDecryptHub', async () => { + const base = tmp(); + process.env.APPDATA = base; process.env.XDG_CONFIG_HOME = base; + await withBase(async () => { + const mod = await import(`../settings.mjs?n=${Date.now()}${Math.random()}`); + assert.equal(mod.DATA_DIR_NAME, 'DecryptHub'); + const dir = mod.userDataDir(); + assert.equal(path.basename(dir), 'DecryptHub'); + assert.equal(fs.existsSync(dir), true); + }); +}); + +test('旧 WebDecryptHub 数据目录会被整体迁移到 DecryptHub(设置与会话都不丢)', async () => { + const base = tmp(); + process.env.APPDATA = base; process.env.XDG_CONFIG_HOME = base; + const legacy = path.join(base, 'WebDecryptHub'); + fs.mkdirSync(path.join(legacy, 'projects', 'main'), { recursive: true }); + fs.writeFileSync(path.join(legacy, 'settings.json'), JSON.stringify({ headless: true, openai: { model: 'kept-model' } })); + fs.writeFileSync(path.join(legacy, 'sessions.json'), JSON.stringify({ focused: 'main', sessions: [{ id: 'main', primary: true }] })); + fs.writeFileSync(path.join(legacy, 'projects', 'main', '.agent-history.json'), '{"events":[]}'); + await withBase(async () => { + const mod = await import(`../settings.mjs?n=${Date.now()}${Math.random()}`); + const dir = mod.userDataDir(); + assert.equal(path.basename(dir), 'DecryptHub'); + // 数据跟着搬过去,不是新建空目录 + assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')).openai.model, 'kept-model'); + assert.equal(fs.existsSync(path.join(dir, 'sessions.json')), true); + assert.equal(fs.existsSync(path.join(dir, 'projects', 'main', '.agent-history.json')), true); + assert.equal(fs.existsSync(legacy), false, '旧目录必须整体改名,不能留在原地'); + assert.equal(mod.load().headless, true); + }); +}); + +test('DecryptHub 已存在时不会被旧的 WebDecryptHub 覆盖', async () => { + const base = tmp(); + process.env.APPDATA = base; process.env.XDG_CONFIG_HOME = base; + const current = path.join(base, 'DecryptHub'); + fs.mkdirSync(current, { recursive: true }); + fs.writeFileSync(path.join(current, 'settings.json'), JSON.stringify({ openai: { model: 'new-model' } })); + const legacy = path.join(base, 'WebDecryptHub'); + fs.mkdirSync(legacy, { recursive: true }); + fs.writeFileSync(path.join(legacy, 'settings.json'), JSON.stringify({ openai: { model: 'stale-model' } })); + await withBase(async () => { + const mod = await import(`../settings.mjs?n=${Date.now()}${Math.random()}`); + const dir = mod.userDataDir(); + assert.equal(path.basename(dir), 'DecryptHub'); + assert.equal(mod.load().openai.model, 'new-model', '已有新目录时旧目录只能当遗留,不能顶掉它'); + assert.equal(fs.existsSync(legacy), true, '旧目录保持原样,等用户自己决定'); + }); +}); + +test('更早的 JSReverseAgent 目录也能一路迁移到 DecryptHub', async () => { + const base = tmp(); + process.env.APPDATA = base; process.env.XDG_CONFIG_HOME = base; + const ancient = path.join(base, 'JSReverseAgent'); + fs.mkdirSync(ancient, { recursive: true }); + fs.writeFileSync(path.join(ancient, 'settings.json'), JSON.stringify({ openai: { model: 'ancient-model' } })); + await withBase(async () => { + const mod = await import(`../settings.mjs?n=${Date.now()}${Math.random()}`); + const dir = mod.userDataDir(); + assert.equal(path.basename(dir), 'DecryptHub'); + assert.equal(mod.load().openai.model, 'ancient-model'); + assert.equal(fs.existsSync(ancient), false); + }); +}); + diff --git a/sidecar/test/thinking.test.mjs b/sidecar/test/thinking.test.mjs index 93e337ae4e..a4933ce9f7 100644 --- a/sidecar/test/thinking.test.mjs +++ b/sidecar/test/thinking.test.mjs @@ -13,7 +13,7 @@ import http from 'node:http'; import { THINKING_LEVELS, THINKING_TRANSPORTS, ALL_LEVELS, normalizeThinking, normalizeThinkingLevels, levelsLabel, levelLabel, inferThinking, modelThinking, declaredThinking, effectiveThinking, requestThinking, - reasoningEffort, thinkingBudget, openAIThinking, anthropicThinking, isThinkingLevel, + reasoningEffort, thinkingBudget, openAIThinking, anthropicThinking, isThinkingLevel, deriveTransport, } from '../thinking.mjs'; import { resolveProvider } from '../providers/index.mjs'; @@ -70,7 +70,7 @@ test('可选档(xhigh / max)只来自模型显式声明,推断不会带出 assert.equal(reasoningEffort('max'), 'max'); assert.equal(thinkingBudget('xhigh'), 32000); // 显式声明时,用户在界面上选到的「极高」必须真的发出去。 - assert.deepEqual(openAIThinking({ transport: 'effort', level: 'xhigh' }), { field: 'reasoning_effort', value: 'xhigh' }); + assert.deepEqual(openAIThinking({ transport: 'effort', level: 'xhigh' }), [{ field: 'reasoning_effort', value: 'xhigh' }]); }); test('生效档位:用户选择优先,越界回落到模型默认,再回落到「不发」', () => { @@ -88,20 +88,40 @@ test('模型显式声明优先于推断;声明为空才推断', () => { assert.equal(modelThinking({ levels: [] }, 'gpt-5').transport, 'effort'); }); -test('OpenAI 片段:effort 发强度名、switch 只发开关、none 什么都不发', () => { - assert.deepEqual(openAIThinking({ transport: 'effort', level: 'high' }), { field: 'reasoning_effort', value: 'high' }); - assert.deepEqual(openAIThinking({ transport: 'switch', level: 'high' }), { field: 'thinking', value: { type: 'enabled' } }); - assert.deepEqual(openAIThinking({ transport: 'switch', level: 'off' }), { field: 'thinking', value: { type: 'disabled' } }); +test('OpenAI 片段:effort 发强度名、switch 发开关加强度、none 什么都不发', () => { + assert.deepEqual(openAIThinking({ transport: 'effort', level: 'high' }), [{ field: 'reasoning_effort', value: 'high' }]); + // 开关型端点要两个字段:thinking.type 负责「开」,reasoning_effort 负责「开多大」。 + // 只发前者会把 low / medium / high 压成同一个请求,界面上的进度条就是骗人的。 + assert.deepEqual(openAIThinking({ transport: 'switch', level: 'high' }), [ + { field: 'thinking', value: { type: 'enabled' } }, + { field: 'reasoning_effort', value: 'high' }, + ]); + assert.deepEqual(openAIThinking({ transport: 'switch', level: 'low' }), [ + { field: 'thinking', value: { type: 'enabled' } }, + { field: 'reasoning_effort', value: 'low' }, + ]); + assert.deepEqual(openAIThinking({ transport: 'switch', level: 'off' }), [{ field: 'thinking', value: { type: 'disabled' } }]); // 关闭档在 effort 方式下不发参数(端点没有 "off" 这个强度名)。 - assert.equal(openAIThinking({ transport: 'effort', level: 'off' }), null); - assert.equal(openAIThinking({ transport: 'none', level: 'high' }), null); - assert.equal(openAIThinking({ transport: 'budget', level: 'high' }), null); - assert.equal(openAIThinking({ transport: 'effort', level: '' }), null); + assert.deepEqual(openAIThinking({ transport: 'effort', level: 'off' }), []); + assert.deepEqual(openAIThinking({ transport: 'none', level: 'high' }), []); + assert.deepEqual(openAIThinking({ transport: 'budget', level: 'high' }), []); + assert.deepEqual(openAIThinking({ transport: 'effort', level: '' }), []); +}); + +test('发送方式由端点推断,不问用户', () => { + // Claude 原生端点只能按预算发。 + assert.equal(deriveTransport('any-model', 'anthropic'), 'budget'); + // OpenAI 兼容:认得出的按名字走,认不出的回落到强度(这是该协议的通行写法,且 400 时会被剥掉重试)。 + assert.equal(deriveTransport('gpt-5.1', 'openai'), 'effort'); + assert.equal(deriveTransport('o3-mini', 'openai'), 'effort'); + assert.equal(deriveTransport('deepseek-v4.1-flash', 'openai'), 'switch'); + assert.equal(deriveTransport('gpt-4o', 'openai'), 'effort'); + assert.equal(deriveTransport('', 'openai'), 'effort'); }); test('会话标题永不花思考预算:开关型显式关闭,其余一律不附加强度', () => { - assert.deepEqual(openAIThinking({ transport: 'switch', level: 'high', requestPurpose: 'session-title' }), { field: 'thinking', value: { type: 'disabled' } }); - assert.equal(openAIThinking({ transport: 'effort', level: 'high', requestPurpose: 'session-title' }), null); + assert.deepEqual(openAIThinking({ transport: 'switch', level: 'high', requestPurpose: 'session-title' }), [{ field: 'thinking', value: { type: 'disabled' } }]); + assert.deepEqual(openAIThinking({ transport: 'effort', level: 'high', requestPurpose: 'session-title' }), []); assert.equal(anthropicThinking({ transport: 'budget', level: 'high', requestPurpose: 'session-title' }), null); }); @@ -134,7 +154,7 @@ test('未声明也不选档位时,请求里绝不带思考参数(这是保 // DeepSeek V4 默认就思考:不能因为「推断它支持」就替用户改线上请求体。 const settings = { provider: 'openai', activeProviderId: 'p', activeModel: 'deepseek-v4.1-flash', openai: { model: 'deepseek-v4.1-flash' }, providers: [{ id: 'p', type: 'openai', models: ['deepseek-v4.1-flash'] }] }; assert.deepEqual(requestThinking(settings, 'openai'), { transport: 'none', level: '' }); - assert.equal(openAIThinking(requestThinking(settings, 'openai')), null); + assert.deepEqual(openAIThinking(requestThinking(settings, 'openai')), []); // Claude 同理:没声明就不发 thinking 块,温度也保持用户设置。 const claude = { provider: 'anthropic', anthropic: { model: 'claude-sonnet-4-5' }, providers: [{ id: 'a', type: 'anthropic', models: ['claude-sonnet-4-5'] }], activeProviderId: 'a', activeModel: 'claude-sonnet-4-5' }; assert.equal(anthropicThinking(requestThinking(claude, 'anthropic')), null); @@ -179,6 +199,26 @@ test('openai 端点:声明的档位真的发出去,未声明时一个参数 } finally { await srv.close(); } }); +test('openai 端点:开关型端点的不同档位必须发出不同请求(否则进度条是骗人的)', async () => { + const bodies = []; + const srv = await serve((_req, body, res) => { bodies.push(body); sse(res, [{ choices: [{ delta: { content: 'ok' }, finish_reason: 'stop' }] }]); }); + try { + const base = { provider: 'openai', openai: { baseUrl: srv.url + '/v1', apiKey: 'k', model: 'deepseek-v4.1-flash' } }; + for (const level of ['off', 'low', 'high']) { + await resolveProvider({ ...base, openai: { ...base.openai, thinking: { transport: 'switch', level } } }).complete([{ role: 'user', content: 'hi' }], [], {}); + } + // 关:只发关闭。 + assert.deepEqual(bodies[0].thinking, { type: 'disabled' }); + assert.equal(bodies[0].reasoning_effort, undefined); + // 低 / 高:都开,但强度不同 —— 这是老实现丢失的那一半。 + assert.deepEqual(bodies[1].thinking, { type: 'enabled' }); + assert.equal(bodies[1].reasoning_effort, 'low'); + assert.deepEqual(bodies[2].thinking, { type: 'enabled' }); + assert.equal(bodies[2].reasoning_effort, 'high'); + assert.notEqual(bodies[1].reasoning_effort, bodies[2].reasoning_effort, '关闭与高档之外,不同档位不能发成同一个请求'); + } finally { await srv.close(); } +}); + test('openai 端点:不认思考参数时去掉参数重试,而不是整请求失败', async () => { const bodies = []; let n = 0; @@ -196,6 +236,27 @@ test('openai 端点:不认思考参数时去掉参数重试,而不是整请 } finally { await srv.close(); } }); +test('openai 端点:开关型端点只认开关时,剥掉强度但保留开关(不能一起扔)', async () => { + const bodies = []; + let n = 0; + const srv = await serve((_req, body, res) => { + bodies.push(body); + // 真实场景:DeepSeek 兼容网关认 thinking.type,但不认 reasoning_effort。 + if (n++ === 0) { res.writeHead(400); res.end('{"error":{"message":"Unsupported parameter: reasoning_effort"}}'); return; } + sse(res, [{ choices: [{ delta: { content: 'ok' }, finish_reason: 'stop' }] }]); + }); + try { + const settings = { provider: 'openai', openai: { baseUrl: srv.url + '/v1', apiKey: 'k', model: 'deepseek-v4.1-flash', thinking: { transport: 'switch', level: 'high' } } }; + const r = await resolveProvider(settings).complete([{ role: 'user', content: 'hi' }], [], {}); + assert.equal(r.content, 'ok'); + assert.equal(bodies[0].reasoning_effort, 'high'); + // 重试时只丢掉强度,开关必须还在 —— 否则等于把「开启思考」也一起取消了。 + const last = bodies.at(-1); + assert.equal(last.reasoning_effort, undefined); + assert.deepEqual(last.thinking, { type: 'enabled' }, '剥掉强度后必须保留开启开关'); + } finally { await srv.close(); } +}); + test('claude 端点:budget 方式把预算发出去,并同时满足 temperature=1 与 max_tokens 上限', async () => { const bodies = []; const srv = await serve((_req, body, res) => { diff --git a/sidecar/thinking.mjs b/sidecar/thinking.mjs index c32de8be62..4782ad7afe 100644 --- a/sidecar/thinking.mjs +++ b/sidecar/thinking.mjs @@ -27,9 +27,9 @@ export const THINKING_LEVELS = [ ]; export const THINKING_TRANSPORTS = [ - { id: 'effort', label: 'reasoning_effort', desc: 'OpenAI / GPT-5 系:发送强度名' }, - { id: 'budget', label: 'thinking.budget_tokens', desc: 'Claude 原生:发送思考 token 预算' }, - { id: 'switch', label: 'thinking.type', desc: 'DeepSeek / GLM 等:只能开关思考' }, + { id: 'effort', label: '强度', desc: '按档位名发送思考强度(OpenAI / GPT-5 系)' }, + { id: 'budget', label: '预算', desc: '按档位发送思考 token 预算(Claude 原生)' }, + { id: 'switch', label: '开关', desc: '只能开启或关闭思考,没有中间档(DeepSeek / GLM 等)' }, { id: 'none', label: '不发送', desc: '端点自行决定;档位只用于界面提示' }, ]; @@ -58,7 +58,7 @@ export const levelsLabel = levels => normalizeThinkingLevels(levels).map(levelLa * 归一一个模型的思考声明。 * `levels` 是用户声明的「该模型支持哪些档位」——这是本功能的核心,必须可读可编辑; * `default` 必须落在 levels 内;`transport` 决定请求怎么发。 - * 声明为空时保留 transport,方便用户先选发送方式再选档位。 + * 声明为空时保留 transport,方便先写档位、发送方式留待推断。 * * 手写 `{ transport, level }` 也接受:等价于「只支持这一档,默认就是它」。 * 手工编辑 settings.json 时这是最自然的写法,不该被当成空声明再被推断覆盖。 @@ -93,6 +93,35 @@ export function modelThinking(declared, modelId) { return value.levels.length ? value : inferThinking(modelId); } +/** + * 发送方式由端点决定,不问用户——这是本控件最容易做错的地方。 + * + * 早期版本让用户在设置页挑「reasoning_effort / thinking.budget_tokens / thinking.type」, + * 但那是适配器内部的字段名,不是用户能判断的东西:同一个模型换一个网关就可能要换写法, + * 而用户看到的只是「这个模型有几档思考强度」。DSH 也不问:它由协议(api)和 + * compat.thinkingFormat 决定,表单上只有「推理等级」本身。 + * + * 规则:Claude 原生 → 预算;其余按模型名推断,认不出来就按强度发(这是 OpenAI 兼容端点的通行写法)。 + * 认错也不会炸:providers/openai.mjs 收到 400 时会去掉该参数重试一次。 + */ +export function deriveTransport(modelId, providerType) { + if (providerType === 'anthropic') return 'budget'; + const inferred = inferThinking(modelId).transport; + return inferred === 'none' ? 'effort' : inferred; +} + +/** + * 一次声明实际用哪种发送方式:显式写了「不发送」就尊重它,其余一律按端点推断。 + * + * 保留 none 是有意的边界:手工编辑 settings.json 的人可以用 `{transport:'none'}` 表达 + * 「界面照常给档位,但请求里一个思考参数都别带」。这是用户的明确意愿,不能因为 + * 「界面不问了」就把它推断掉 —— 那等于把用户的显式配置改成主动发送。 + */ +export function effectiveTransport(declaration, modelId, providerType) { + if (declaration?.transport === 'none') return 'none'; + return deriveTransport(modelId, providerType); +} + /** * 只认用户显式声明的部分(模型配置里写了哪些档位)。 * 与 modelThinking 的区别是这里**不推断**:推断出来的档位只用于界面,不能替用户决定发送参数。 @@ -135,8 +164,13 @@ export function requestThinking(settings, type) { } // 渠道里逐模型的声明优先;旧配置只有 openai/anthropic 两段时读镜像。 const declared = declaredThinking(modelDecl) || declaredThinking(mirror.thinking); - if (declared) return effectiveThinking(declared, settings?.activeThinking); + if (declared) { + // 发送方式按端点推断,但显式写的「不发送」要尊重(手工配置里这是明确意愿)。 + return effectiveThinking({ ...declared, transport: effectiveTransport(declared, mirror.model || requested, type) }, settings?.activeThinking); + } // 未声明:只有当用户在界面上明确选了一档时才发送,发送方式按模型名推断。 + // 这里仍用 inferThinking 而不是 deriveTransport:没声明就说明我们对这个模型一无所知, + // 认不出来就该一个参数都不发,而不是赌它是 effort(赌错只会换来一次 400 重试)。 const chosen = settings?.activeThinking; if (!isThinkingLevel(chosen)) return { transport: 'none', level: '' }; const inferred = inferThinking(mirror.model || requested); @@ -150,32 +184,49 @@ export const reasoningEffort = level => thinkingLevel(level)?.effort || null; export const thinkingBudget = level => thinkingLevel(level)?.budget || null; /** - * 界面上如实显示「这一档会往请求里放什么」。 - * 选择器不能只写「更聪明」——用户需要知道自己的选择到底改了什么,以及有没有真的发出去。 + * 界面上如实显示「这一档会往请求里放什么」——给人读的说法,不是字段字面量。 + * + * 只出现在设置页:用户在那里声明模型能力,需要知道自己写的东西到底会改掉什么。 + * 浮层/触发器里一律不显示——点开只想选档位的人不该被 JSON 字段名打扰(DSH 也不显示)。 */ export function payloadLabel(transport, level) { if (!isThinkingLevel(level)) return '不发送思考参数'; if (transport === 'none') return '不发送思考参数'; if (transport === 'budget') { const budget = thinkingBudget(level); - return budget ? `thinking.budget_tokens: ${budget}` : '不发送思考参数'; + return budget ? `发思考预算 ${budget} tokens` : '不发送思考参数'; } - if (transport === 'switch') return `thinking.type: ${level === 'off' ? 'disabled' : 'enabled'}`; const effort = reasoningEffort(level); - return effort ? `reasoning_effort: ${effort}` : '不发送思考参数'; + if (transport === 'switch') { + if (level === 'off') return '只发送「关闭思考」'; + // 开关型端点现在是「开关 + 强度」两个字段一起发,所以这里必须两个都说。 + return effort ? `发送「开启思考」加强度 ${effort}` : '只发送「开启思考」'; + } + return effort ? `发送强度 ${effort}` : '不发送思考参数'; } /** - * OpenAI 兼容端点的思考参数片段 `{ field, value }`,没有可发的内容时返回 null。 - * 会话标题这类元数据请求永远不花思考预算:开关型端点显式关闭,强度型端点一律不附加强度。 + * OpenAI 兼容端点的思考参数片段 `{ field, value }[]`,没有可发的内容时返回空数组。 + * 返回数组而不是单个字段,是因为开关型端点(DeepSeek / GLM)要发两个字段: + * thinking: {type:'enabled'} 负责「开」,reasoning_effort 负责「开多大」。 + * 只发前者的老实现会把 low / medium / high 压成同一个请求,进度条就是骗人的。 + * 这与 DSH 的 compat.thinkingFormat: deepseek 完全一致(它也是 effort 之外再加 thinking 块)。 + * + * 会话标题这类元数据请求永远不花思考预算:开关型端点显式关闭,强度型端点一律不附加。 */ export function openAIThinking({ transport, level, requestPurpose } = {}) { - if (requestPurpose === 'session-title') return transport === 'switch' ? { field: 'thinking', value: { type: 'disabled' } } : null; - if (transport === 'none' || !isThinkingLevel(level)) return null; - if (transport === 'switch') return { field: 'thinking', value: { type: level === 'off' ? 'disabled' : 'enabled' } }; - if (transport !== 'effort') return null; + if (requestPurpose === 'session-title') return transport === 'switch' ? [{ field: 'thinking', value: { type: 'disabled' } }] : []; + if (transport === 'none' || !isThinkingLevel(level)) return []; const effort = reasoningEffort(level); - return effort ? { field: 'reasoning_effort', value: effort } : null; + if (transport === 'switch') { + if (level === 'off') return [{ field: 'thinking', value: { type: 'disabled' } }]; + // 开:先放开关,再放强度(端点认哪个用哪个,不认的会被 400 兜底剥掉重试)。 + return effort + ? [{ field: 'thinking', value: { type: 'enabled' } }, { field: 'reasoning_effort', value: effort }] + : [{ field: 'thinking', value: { type: 'enabled' } }]; + } + if (transport !== 'effort') return []; + return effort ? [{ field: 'reasoning_effort', value: effort }] : []; } /** diff --git a/ui/src/app.css b/ui/src/app.css index 6cf7d97746..163886c053 100644 --- a/ui/src/app.css +++ b/ui/src/app.css @@ -256,7 +256,6 @@ kbd { font-family: var(--default-font-family); font-size: 10px; font-weight: 400 .thinking-reset { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; width: 24px; height: 24px; padding: 0; border: 0; border-radius: 7px; background: transparent; color: var(--subtle); cursor: pointer; } .thinking-reset:hover { background: var(--hover); color: var(--ink); } .thinking-level { min-width: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.02em; color: var(--brand-text); line-height: 1.25; } -.thinking-level.muted { font-size: 15px; font-weight: 500; color: var(--muted); } /* 模型行:设计图里档位名下方那行「模型名 + 箭头」,点它钻取到模型目录 */ .seat-modelrow { display: flex; align-items: center; gap: 4px; max-width: 100%; margin-top: 2px; padding: 2px 4px 2px 0; border: 0; border-radius: 6px; background: transparent; color: var(--muted); font: inherit; font-size: 12px; cursor: pointer; } @@ -284,20 +283,18 @@ kbd { font-family: var(--default-font-family); font-size: 10px; font-weight: 400 /* 档位条:一张 N 段进度条,段与段之间留缝,每一段就是一个档位。 没有把手、没有「拖到中间」的可能;已过的段用淡色表示进度,当前段实色。 */ -.thinking-steps { display: flex; gap: 4px; margin: 14px 0 0; border-radius: 8px; } -.thinking-steps:focus-visible { outline: 2px solid var(--accent-9); outline-offset: 4px; } +.thinking-steps { display: flex; gap: 4px; margin: 14px 0 0; } .thinking-step { flex: 1 1 0; min-width: 0; display: flex; flex-direction: column; gap: 7px; padding: 2px 0; border: 0; background: transparent; color: var(--subtle); font: inherit; cursor: pointer; } .thinking-step-bar { display: block; height: 6px; border-radius: 3px; background: var(--line-strong); transition: background .14s ease, opacity .14s ease; } .thinking-step-name { font-size: 10px; line-height: 1.2; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .thinking-step:not(.on):not(.done):hover .thinking-step-bar { background: var(--muted); } /* 已过的段是「进度」,当前段是「档位」:前者淡、后者实,一眼能看出停在第几档 */ -.thinking-step.done .thinking-step-bar { background: var(--brand-text); opacity: .4; } +.thinking-step.done .thinking-step-bar { background: var(--brand-text); opacity: .5; } .thinking-step.done .thinking-step-name { color: var(--muted); } .thinking-step.on .thinking-step-bar { background: var(--brand-text); } .thinking-step.on .thinking-step-name { color: var(--ink); font-weight: 500; } .thinking-step:focus-visible { outline: none; } .thinking-step:focus-visible .thinking-step-bar { outline: 2px solid var(--accent-9); outline-offset: 2px; } -.thinking-payload { margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--line); font-family: var(--code-font-family); font-size: 10px; line-height: 1.6; overflow-wrap: anywhere; } .composer-mode { min-width: 0; flex: 0 0 auto; } diff --git a/ui/src/bus.jsx b/ui/src/bus.jsx index ea80377165..7005f9b9ec 100644 --- a/ui/src/bus.jsx +++ b/ui/src/bus.jsx @@ -218,6 +218,18 @@ export function Workbench({ children }) { // 历史会话(无项目归属)在启动时清点一次。它们是本地残留数据,不做任何自动处理。 useEffect(() => { api.invoke('legacy-sessions').then(v => setLegacySessions(Array.isArray(v) ? v : [])).catch(() => {}); }, []); + const restoreLegacySessions = useCallback(async ids => { + try { + const r = await api.invoke('legacy-sessions-restore', { ids }); + const done = (r?.restored || []).map(x => x.id); + setLegacySessions(list => list.filter(x => !done.includes(x.id))); + const skipped = r?.skipped || []; + if (done.length) toast(`已恢复 ${done.length} 个历史会话`, 'ok'); + // 跳过是逐条原因不同的:一次列出来,别让用户以为全都恢复了。 + if (skipped.length) toast('未恢复:' + skipped.map(x => `${x.title || x.id}(${x.reason})`).join(';'), 'warn', 9000); + return r; + } catch (e) { toast('恢复失败:' + e.message, 'err'); return null; } + }, []); const discardLegacySessions = useCallback(async ids => { try { const r = await api.invoke('legacy-sessions-discard', { ids }); @@ -671,7 +683,7 @@ export function Workbench({ children }) { projects, setProjects, projectFilter, setProjectFilter, projectEditor, setProjectEditor, moveSession, setMoveSession, workspacePrompt, setWorkspacePrompt, isCurrentSession: id => sidRef.current === id, commandForm, setCommandForm, extensionBrowser, setExtensionBrowser, automationDraft, setAutomationDraft, - legacySessions, discardLegacySessions, + legacySessions, restoreLegacySessions, discardLegacySessions, commandFeedback: commandFeedback[sid], clearCommandFeedback: () => setCommandFeedback(m => ({ ...m, [sid]: null })), settings, saveSettings, setSettings, firstRun, setFirstRun, sessions, sid, session, cur, dispatch, focusSession, diff --git a/ui/src/chat.jsx b/ui/src/chat.jsx index 8284c4ac13..e129974010 100644 --- a/ui/src/chat.jsx +++ b/ui/src/chat.jsx @@ -23,7 +23,7 @@ import { processPresentation } from './process-presentation.js'; import { reasoningOpen, toggleReasoning } from './scroll-stick.js'; import { QueuedMessages } from './queue-strip.jsx'; import { ModelSeat } from './thinking-picker.jsx'; -import { modelThinking, effectiveThinking } from '../../sidecar/thinking.mjs'; +import { modelThinking, effectiveThinking, effectiveTransport } from '../../sidecar/thinking.mjs'; const CTX_PARTS = [['system', '系统提示'], ['tools', '工具定义'], ['summary', '压缩摘要'], ['history', '对话'], ['attachments', '附件'], ['toolResults', '工具结果']]; @@ -41,7 +41,8 @@ export function ChatStage({ railOpen, onExpandRail }) { const modelInfo = (activeProvider?.models || []).find(m => (typeof m === 'string' ? m : m.id) === model); const vision = typeof modelInfo === 'object' && modelInfo?.vision; // 思考档位:只有当前模型确实声明了档位时才给选择器,否则不摆一个切换无效的控件。 - const declaredThinking = modelThinking(typeof modelInfo === 'object' ? modelInfo?.thinking : null, model); + // 发送方式由端点推断(deriveTransport),不听 settings 里存的 transport —— 那是旧版让用户手挑的字段名。 + const declaredThinking = { ...modelThinking(typeof modelInfo === 'object' ? modelInfo?.thinking : null, model), transport: effectiveTransport(typeof modelInfo === 'object' ? modelInfo?.thinking : null, model, activeProvider?.type) }; const thinking = effectiveThinking(declaredThinking, settings.activeThinking); const commands = commandDismissed ? [] : commandMatches(input), commandId = 'composer-commands-' + w.sid; const chooseCommand = c => { setInput('/' + c.name + ' '); setCommandDismissed(true); setTimeout(() => refs.inputRef.current?.focus(), 0); }; @@ -129,7 +130,7 @@ export function ChatStage({ railOpen, onExpandRail }) {
pickModel(pid, m)} onPickThinking={level => w.pickThinking(level)} />
responding ? inv('agent-interrupt') : send(false)} diff --git a/ui/src/projects.jsx b/ui/src/projects.jsx index 317812831f..d07596eb92 100644 --- a/ui/src/projects.jsx +++ b/ui/src/projects.jsx @@ -107,12 +107,13 @@ export function ProjectDialogs() { /** * 项目概念之前留下的历史会话(没有 projectId)。 - * 它们是本地残留数据,产品不做自动迁移,也不替用户删——这里只如实报告并询问。 + * 它们是本地残留数据,产品不做自动迁移,也不替用户删——这里如实报告,并让用户选择恢复或删除。 */ function LegacySessionsNotice() { const w = useWorkbench(), [busy, setBusy] = useState(false), [dismissed, setDismissed] = useState(false); const list = w.legacySessions || []; if (!list.length || dismissed) return null; + const restorable = list.filter(s => s.restorable !== false); const names = list.slice(0, 3).map(s => `「${s.title || s.id}」`).join('、'); const more = list.length > 3 ? ` 等 ${list.length} 个` : ''; const remove = async () => { @@ -121,16 +122,25 @@ function LegacySessionsNotice() { setBusy(false); if (ok) setDismissed(true); }; + const restore = async () => { + setBusy(true); + // 恢复后列表里剩下的就是恢复失败的,保留弹窗让用户看见原因。 + const r = await w.restoreLegacySessions(list.map(s => s.id)); + setBusy(false); + if (r && !(r.skipped || []).length) setDismissed(true); + }; return { if (!open && !busy) setDismissed(true); }}> 历史会话没有项目归属 找到 {list.length} 个创建于「项目」功能之前的会话:{names}{more}。它们不会被载入,也不会被自动迁移或删除。 + 「恢复到会话列表」会为它们建立项目归属,之后可以正常打开查看。
删除会同时清理这些会话的记录、附件和浏览器数据;目录与源码文件不受影响。
- + +
; diff --git a/ui/src/screens.jsx b/ui/src/screens.jsx index 00f9f36974..0d88e19f11 100644 --- a/ui/src/screens.jsx +++ b/ui/src/screens.jsx @@ -4,7 +4,7 @@ import { Box, Flex, Text, Badge, Card, TextField, TextArea, SegmentedControl, Sw import { useWorkbench } from './bus.jsx'; import { fmtK, sessionLabel } from './state.js'; import { TITLE_PREFIX_MAX } from '../../sidecar/session-titles.mjs'; -import { THINKING_LEVELS, THINKING_TRANSPORTS, normalizeThinking, levelsLabel, levelLabel } from '../../sidecar/thinking.mjs'; +import { THINKING_LEVELS, normalizeThinking, levelsLabel, levelLabel, effectiveTransport, payloadLabel } from '../../sidecar/thinking.mjs'; import { LevelSlider } from './thinking-picker.jsx'; import { Button, ActionIcon, NavButton, Icon, LogoMark, EmptyState, askConfirm, Dropdown } from './kit.jsx'; import { native } from './transport.js'; @@ -96,7 +96,8 @@ function AiTab({ s, setS }) { if (!mEdit) return; const id = String(mEdit.data.id || '').trim(); if (!id) return; - const entry = { id, name: String(mEdit.data.name || '').trim() || id, contextWindow: Number(mEdit.data.contextWindow) || 0, vision: !!mEdit.data.vision, thinking: normalizeThinking(mEdit.data.thinking, edit.data.type === 'anthropic' ? 'budget' : 'effort') }; + const transport = effectiveTransport(mEdit.data.thinking, id, edit.data.type); + const entry = { id, name: String(mEdit.data.name || '').trim() || id, contextWindow: Number(mEdit.data.contextWindow) || 0, vision: !!mEdit.data.vision, thinking: normalizeThinking({ ...mEdit.data.thinking, transport }, transport) }; const models = [...(edit.data.models || [])]; if (mEdit.i >= 0) models[mEdit.i] = entry; else models.push(entry); patch({ models }); @@ -241,17 +242,22 @@ function AiTab({ s, setS }) { } // ---------- 思考强度 ---------- -// 逐模型声明「支持哪些档位」,并选择发送方式。声明是唯一的判断依据: -// 没声明就不发送任何思考参数(端点自己决定),所以这里的文案必须说清「发了什么」,不能只写「更聪明」。 +// 逐模型声明「支持哪些档位」。声明是唯一的判断依据:没声明就不发送任何思考参数(端点自己决定)。 +// 发送方式是自动推断的(deriveTransport),不在这页出现——字段名是适配器的实现细节, +// 让用户去挑 reasoning_effort / thinking.type 只会逼他先读一遍端点文档。DSH 同样只让用户选档位。 function ThinkingEditor({ data, type, onChange }) { - const value = normalizeThinking(data.thinking, type === 'anthropic' ? 'budget' : 'effort'); + // 发送方式由端点推断,用户只声明档位。 + const transport = effectiveTransport(data.thinking, data.id, type); + const value = normalizeThinking({ ...data.thinking, transport }, transport); const toggleLevel = id => { const levels = value.levels.includes(id) ? value.levels.filter(x => x !== id) : THINKING_LEVELS.map(l => l.id).filter(x => x === id || value.levels.includes(x)); // 取消勾选默认档时,默认档必须跟着落到剩下的某一档,否则会存下「默认不在支持范围内」的矛盾配置。 const next = levels.includes(value.default) ? value.default : (levels[0] || ''); onChange({ levels, default: next }); }; - const transport = THINKING_TRANSPORTS.find(t => t.id === value.transport) || THINKING_TRANSPORTS[0]; + // 开关型端点(DeepSeek / GLM)只有「开 / 关」两种状态;强度那一半靠额外的 reasoning_effort 表达, + // 但并非所有这类端点都认,所以这里说明清楚,而不是让进度条假装它一定是 5 档。 + const switching = value.transport === 'switch'; return 支持的思考强度 @@ -263,16 +269,20 @@ function ThinkingEditor({ data, type, onChange }) { {value.levels.length ? '当前声明:' + levelsLabel(value.levels) : '未声明任何档位:请求里不会带思考参数,由端点自行决定是否思考。'} + {/* 「会发什么」只在设置页说清楚:用户在这里声明能力,需要知道改动到底影响了请求的哪一部分。 + 浮层里不显示——那里只该回答「选哪一档」。 */} + {value.levels.length > 0 && + 按当前渠道自动发送:选中「{levelLabel(value.default)}」时{payloadLabel(value.transport, value.default)}。 + } 默认强度 {value.levels.length ? onChange({ default: id })} /> : 先勾选上面支持的档位,再选默认档。} - 发送方式 - onChange({ transport: v })} style={{ width: '100%' }}> - {THINKING_TRANSPORTS.map(t => {t.label})} - - {transport.desc} - {value.transport === 'budget' && value.levels.some(id => id !== 'off') && + {switching && value.levels.some(id => id !== 'off') && + 该模型按开关控制思考(如 DeepSeek / GLM):关闭档只发「关闭」,其余档发「开启」并附带对应强度。 + 若该端点不认强度那一半,会自动退回纯开关。 + } + {value.transport === 'budget' && value.levels.some(id => id !== 'off') && Claude 原生端点要求思考预算小于最大输出、且温度只能为 1;保存后这两项会按所选档位自动调整。 } ; diff --git a/ui/src/thinking-picker.jsx b/ui/src/thinking-picker.jsx index fe635b03d1..943b2bd72b 100644 --- a/ui/src/thinking-picker.jsx +++ b/ui/src/thinking-picker.jsx @@ -19,7 +19,7 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'; import { Popover, Text } from '@radix-ui/themes'; import { Icon } from './kit.jsx'; -import { levelLabel, payloadLabel, normalizeThinkingLevels } from '../../sidecar/thinking.mjs'; +import { levelLabel, normalizeThinkingLevels } from '../../sidecar/thinking.mjs'; const indexOf = (levels, value) => levels.indexOf(value); @@ -31,7 +31,7 @@ function modelGroups(providers) { } export function ModelSeat({ - providers, providerId, model, levels, value, transport, defaultLevel, + providers, providerId, model, levels, value, defaultLevel, onPickModel, onPickThinking, disabled, }) { const [open, setOpen] = useState(false); @@ -46,7 +46,6 @@ export function ModelSeat({ const active = (groups.find(g => g.id === providerId)?.models || []).find(m => m.id === model); const modelName = active?.name || model || '选择模型'; const isReset = hasEffort && !!defaultLevel && value !== defaultLevel && list.includes(defaultLevel); - const payload = hasEffort ? (current >= 0 ? payloadLabel(transport, list[current]) : '不发送思考参数(由端点决定)') : ''; const searchable = groups.reduce((n, g) => n + g.models.length, 0) > 4; const filtered = useMemo(() => { const q = query.trim().toLowerCase(); @@ -103,10 +102,7 @@ export function ModelSeat({ {modelName} - {hasEffort && <> - - {payload} - } + {hasEffort && } {!hasEffort && 该模型没有声明思考强度:请求里不会带思考参数,由端点自行决定。} } @@ -126,10 +122,22 @@ export function LevelSlider({ levels, value, onChange, label = '默认强度', d // 所以这里基于「刚刚提交的值」推算,而不是等重渲染。 const pending = useRef(value); pending.current = value; + // 焦点走 roving tabindex:Tab 进组只落在当前档(没选就落第一档),← → 在段间移动并立即生效。 + // 每段是真按钮,读屏读到的是「思考强度 中,单选按钮,已选中」,而不是一个说不出值的容器。 + const stepsRef = useRef(null); + const wantFocus = useRef(-1); + useEffect(() => { + const at = wantFocus.current; + if (at < 0) return; + wantFocus.current = -1; + stepsRef.current?.querySelectorAll('.thinking-step')[at]?.focus(); + }, [value]); const keydown = event => { const last = list.length - 1; - const at = indexOf(list, pending.current); - const delta = { ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1 }[event.key]; + // 连续按键时 props 还没回流:按「刚刚提交的值」算起点,否则 Home 之后紧跟 ArrowRight 会停在原地。 + const seen = indexOf(list, pending.current); + const at = seen >= 0 ? seen : 0; + const delta = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key]; let next; if (event.key === 'Home') next = 0; else if (event.key === 'End') next = last; @@ -137,12 +145,14 @@ export function LevelSlider({ levels, value, onChange, label = '默认强度', d else return; event.preventDefault(); const target = list[next]; - if (target === pending.current) return; - pending.current = target; - onChange(target); + if (target === undefined) return; + wantFocus.current = next; + if (target !== pending.current) { pending.current = target; onChange(target); } + else stepsRef.current?.querySelectorAll('.thinking-step')[next]?.focus(); }; - return
- {list.map((id, index) =>