WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
feat: consolidate 1.2.9 account session and CodeBuddy updates
[email protected]4ed7410c5301
diff --git a/README.md b/README.mdindex 95c8919..edca152 100644--- a/README.md+++ b/README.md@@ -2,21 +2,21 @@**语言:** [简体中文](README.md) · [English](README_en.md)-> **WorkDaddy 是 WorkBuddy 桌面端增强助手:多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;自动化任务按事件或定时执行;暂存/快捷提示词;毛玻璃主题与更多实用功能,账号与配置全部留在本机。**+> **WorkDaddy 是 WorkBuddy 和 CodeBuddy 桌面端增强助手:多账号独立备份、点切即用,跨账号会话迁移、模型管理与自动化任务。WorkBuddy 还支持免打扰、异常中断自动续接、暂存/快捷提示词和五种主题。账号与配置全部留在本机。**> 本机回环 CDP 注入 · 不改官方安装包。-一个基于 **Chrome DevTools Protocol (CDP)** 的 [WorkBuddy](https://www.workbuddy.cn/)、[WorkBuddy AI](https://www.workbuddy.ai/) 桌面端增强工具。-零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。+一个基于 **Chrome DevTools Protocol (CDP)** 的 [WorkBuddy](https://www.workbuddy.cn/)、[WorkBuddy AI](https://www.workbuddy.ai/)、[CodeBuddy CN](https://www.codebuddy.cn/) 和 [CodeBuddy](https://www.codebuddy.ai/) 桌面端增强工具。+CodeBuddy 支持范围为 **Electron 智能体窗口**,不包含 VS Code 编辑器模式的增强面板。通过本机调试接口连接运行中的客户端,不修改官方安装包或签名。-+---#### 它能做什么-- **方便切换账号**:每个 WorkBuddy 账号独立备份,点一下就切,再也不用每次扫码。+- **方便切换账号**:每个客户端的账号独立备份,点一下就切,再也不用每次扫码。- **无感登录新账号**:「登录新账号」支持免退出 OAuth 授权——不退出 WorkBuddy,在浏览器完成扫码后新账号自动加入列表;也可选传统的「假退出」方式回登录页扫码。- **账号导入导出**:把全部账号备份加密导出,在另一台电脑安装 WorkDaddy 后一键导入,方便电脑之间迁移账号。- **成长计划与活跃状态**:国内版账号页查询成长任务进度、当日签到和活跃状态、连续活跃天数,以及 Buddy 解锁和旅行状态。@@ -26,7 +26,7 @@- **自动化任务**:从 GitHub / Gitee 公开仓库发现并导入任务,或用自然语言让 WorkBuddy 创建任务;支持编辑、手动、事件和定时触发,以及运行日志、停止任务和 JSON / ZIP 导出。- **权限弹窗免打扰**:真正的零决策弹窗弹出,可以放心开启任务后睡觉。- **暂存提示词**:输入框边上一键把草稿「暂存」到待发送队列——图片 / 文件 / 引用原样保留,择机发送。-- **切换精美主题**:内置毛玻璃官方主题,多套预设壁纸,支持自定义壁纸。+- **切换精美主题**:WorkBuddy 的「接管主题」提供浅色、深色、护眼绿、赛博紫、毛玻璃五种外观;毛玻璃支持预设和自定义壁纸,关闭接管后恢复客户端原生主题。- **账号间会话迁移**:自动或手动跨账号复制会话,跨账号继续接龙。- **会话分支**:在「增强」页开启后,任意一条回复都能从此处开始新会话——复制到该条回复为止的聊天内容,原会话保持不变,可在当前工作区继续聊。- **模型切换更便捷**:解决 WorkBuddy 不支持添加多个同名模型的问题。@@ -34,9 +34,21 @@- **异常中断会话自动继续**:AI 回复因网络波动、超时等原因中断时,自动让异常中断任务继续执行。- **快捷短语**:常用语存进面板,输入框操作栏一键点发;----+## 客户端与功能范围++| 官方客户端 | 对应安装包品牌 | profile |+| -------------------------- | ------------ | ---------------- |+| WorkBuddy 国内版 | WorkDaddy | workbuddy-cn |+| WorkBuddy AI 国际版 | WorkDaddy AI | `workbuddy-ai` |+| CodeBuddy CN 国内版(Electron) | CodeDaddy CN | `codebuddy-cn` |+| CodeBuddy 国际版(Electron) | CodeDaddy | `codebuddy-intl` |++- 请注意:CodeBuddy 不展示「增强」页;「主题」页仅提供悬浮机器人设置。+++## 演示<img src="docs/images/accounts-light.jpg" width="600">@@ -54,14 +66,13 @@## 安装-> - 国内版 [WorkBuddy](https://www.workbuddy.cn/) 请下载 `WorkDaddy` 安装包-> - 国际版 [WorkBuddy AI](https://www.workbuddy.ai/) 请下载 `WorkDaddy AI` 安装包+先安装并登录上表对应的官方客户端,再下载匹配的增强工具。四款包独立安装、使用各自的账号备份目录;安装包名称中的空格使用连字符。### macOS-1. 在 [Releases](../../releases) 下载最新 `WorkDaddy-x.y.z.dmg`+1. 在 [Releases](../../releases) 下载对应的 `WorkDaddy-x.y.z.dmg`、`WorkDaddy-AI-x.y.z.dmg`、`CodeDaddy-CN-x.y.z.dmg` 或 `CodeDaddy-x.y.z.dmg`-2. 打开 dmg,把 `WorkDaddy.app` 拖进 **应用程序** 文件夹+2. 打开 DMG,把里面对应的 `.app` 拖进 **应用程序** 文件夹3. 第一次打开如果遇到「无法打开,因为 Apple 无法检查恶意软件」:@@ -70,7 +81,7 @@3. 输入开机密码确认-4. 双击 `WorkDaddy.app` 启动:它会自带守护进程并把组件注入到 WorkBuddy+4. 双击对应的 WorkDaddy / CodeDaddy 应用:它会启动本地守护进程,并把面板注入匹配的客户端。macOS 启动器使用本机 Node.js,建议安装 Node.js 22.13 或更新版本。5. 看到机器人按钮?**搞定**。@@ -87,15 +98,15 @@ node scripts/workbuddy-target.js --configure --platform darwin \### Windows-1. 在 [Releases](../../releases) 下载对应客户端的 `WorkDaddy-Setup-x.y.z.exe` 或 `WorkDaddy-AI-Setup-x.y.z.exe`+1. 在 [Releases](../../releases) 下载对应客户端的 `WorkDaddy-Setup-x.y.z.exe`、`WorkDaddy-AI-Setup-x.y.z.exe`、`CodeDaddy-CN-Setup-x.y.z.exe` 或 `CodeDaddy-Setup-x.y.z.exe`2. 双击安装器完成安装-3. 双击打开 `WorkDaddy` 或 `WorkDaddy AI` 桌面快捷方式+3. 双击打开对应品牌的桌面快捷方式#### Windows 便携版 ZIP-不想安装时,可以使用对应的 `WorkDaddy-Portable-x.y.z.zip` 或 `WorkDaddy-AI-Portable-x.y.z.zip`:+不想安装时,可以使用对应的 `<品牌>-Portable-x.y.z.zip`:品牌为 `WorkDaddy`、`WorkDaddy-AI`、`CodeDaddy-CN` 或 `CodeDaddy`。-1. 先安装并登录对应的 WorkBuddy 客户端。+1. 先安装并登录对应的 WorkBuddy / CodeBuddy 客户端。2. 将 ZIP 解压到一个有写入权限的目录,不要直接在压缩包内运行。3. 双击解压目录顶层的 `Start-WorkDaddy.cmd`;也可以直接运行 `WorkDaddyLauncher.exe`。4. 需要停止后台服务时,运行同目录的 `Stop-WorkDaddy.cmd`。@@ -110,62 +121,41 @@ node scripts/workbuddy-target.js --configure --platform darwin \### Linux-Linux 发布包面向 Ubuntu / Debian `amd64` 和 `arm64`。安装前请先安装并登录同架构的 WorkBuddy 客户端;WorkDaddy 通过 CDP 连接客户端,不会替换或修改 WorkBuddy 本体。+Linux 发布包面向 Ubuntu / Debian `amd64` 和 `arm64`,内置对应架构的 Node.js。请先安装并登录同架构的官方客户端;增强工具通过本机调试接口连接,不修改客户端本体。-1. 在 [Releases](../../releases) 下载对应客户端和机器架构的安装包:国内版是 `WorkDaddy_x.y.z_<arch>.deb`,国际版是 `WorkDaddy-AI_x.y.z_<arch>.deb`,其中 `<arch>` 为 `amd64` 或 `arm64`。+| 品牌 | DEB 文件 | 安装目录 / Debian 包名 |+| ------------ | ------------------------------- | ------------------------------------ |+| WorkDaddy | `WorkDaddy_x.y.z_<arch>.deb` | `/opt/workdaddy` / `workdaddy` |+| WorkDaddy AI | `WorkDaddy-AI_x.y.z_<arch>.deb` | `/opt/workdaddy-ai` / `workdaddy-ai` |+| CodeDaddy CN | `CodeDaddy-CN_x.y.z_<arch>.deb` | `/opt/codedaddy-cn` / `codedaddy-cn` |+| CodeDaddy | `CodeDaddy_x.y.z_<arch>.deb` | `/opt/codedaddy` / `codedaddy` |-2. 在下载目录执行:-- ```bash- sudo apt install ./WorkDaddy_x.y.z_<arch>.deb- ```+1. 从 [Releases](../../releases) 下载对应文件,`<arch>` 为 `amd64` 或 `arm64`。- 如果安装 WorkBuddy AI 国际版,请改用:+2. 在下载目录安装选中的包,例如:```bash- sudo apt install ./WorkDaddy-AI_x.y.z_<arch>.deb+ sudo apt install ./CodeDaddy-CN_1.2.9_amd64.deb```-3. 从应用菜单启动 **WorkDaddy**(国内版)或 **WorkDaddy AI**(国际版)。首次启动会准备本地数据目录并启动后台服务;随后按提示重启 WorkBuddy 以开启 CDP 面板。--国内版安装到 `/opt/workdaddy`,国际版安装到 `/opt/workdaddy-ai`。两个包可以同时安装,互不覆盖;都不默认设置开机自启。需要手动启动选择器时,可运行:--```bash-bash /opt/workdaddy/scripts/launch-gui-linux.sh-```--国际版对应路径为:--```bash-bash /opt/workdaddy-ai/scripts/launch-gui-linux.sh ai-```+3. 从应用菜单启动对应品牌的应用。首次启动会准备数据目录并启动后台服务;随后按提示开启客户端 CDP。CodeBuddy 请进入 Electron 智能体窗口。-如果系统没有应用菜单,也可以直接运行 `cn`、`ai`、`both` 或 `services` 参数选择启动方式:+四款包可以同时安装,互不覆盖,默认不设置开机自启。没有应用菜单时,可运行对应入口:```bashbash /opt/workdaddy/scripts/launch-gui-linux.sh cn+bash /opt/workdaddy-ai/scripts/launch-gui-linux.sh ai+bash /opt/codedaddy-cn/scripts/launch-gui-linux.sh codebuddy-cn+bash /opt/codedaddy/scripts/launch-gui-linux.sh codebuddy-intl```-需要开机自动启动后台服务时,再按 profile 启用可选的 systemd 用户服务:--```bash-WBSWITCH_PROFILE=workbuddy-cn bash /opt/workdaddy/scripts/systemd-install-linux.sh-WBSWITCH_PROFILE=workbuddy-ai bash /opt/workdaddy/scripts/systemd-install-linux.sh-```--卸载 Debian 包:--```bash-sudo apt remove workdaddy-```--卸载国际版:+需要开机启动后台服务时,按对应 profile 启用 systemd 用户服务,例如:```bash-sudo apt remove workdaddy-ai+WBSWITCH_PROFILE=codebuddy-cn bash /opt/codedaddy-cn/scripts/systemd-install-linux.sh```-卸载软件包不会删除账号备份和运行数据;如需清理数据,请先确认对应的 `~/.config/WorkDaddy` 内容后再手动处理。+用 `sudo apt remove <包名>` 卸载。卸载不会删除账号备份和运行数据;需要清理时,先确认 `~/.config/WorkDaddy` 中对应 profile 的数据。Linux 暂不支持面板内自动更新,请安装新版 DEB 升级。#### 从源码安装 Linux 版本@@ -196,16 +186,24 @@ bash scripts/install.sh # 创建备份目录 + 启动守护进程bash scripts/relaunch-with-cdp.sh # 把 WorkBuddy 切换到调试模式(端口 9222)```-WorkBuddy 国内版和 WorkBuddy AI 使用同一套 daemon,通过 profile 绑定客户端,不靠“第一个 CDP 端口”猜测目标:+四款客户端使用同一套 daemon,通过 profile 绑定客户端,不靠“第一个 CDP 端口”猜测目标:```bashWBSWITCH_PROFILE=workbuddy-cn bash scripts/relaunch-with-cdp.shWBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh+WBSWITCH_PROFILE=codebuddy-cn bash scripts/relaunch-with-cdp.sh+WBSWITCH_PROFILE=codebuddy-intl bash scripts/relaunch-with-cdp.sh```-暂存提示词和主题功能在两个 WorkBuddy profile 开启。CodeBuddy profile 的适配暂缓,不进入当前发布包。+macOS 发布四款 DMG;Linux 为四款客户端分别提供 `amd64`、`arm64` DEB;Windows 构建脚本为四款客户端生成 Setup.exe 和 Portable ZIP。具体可下载的平台与版本以 [Releases](../../releases) 中的资产为准。++```bash+WORKDADDY_BUILD_VERSION=1.2.9 bash scripts/build-mac-dmg.sh+WORKDADDY_BUILD_VERSION=1.2.9 WORKDADDY_BUILD_ARCH=amd64 bash scripts/build-linux-deb.sh+WORKDADDY_BUILD_VERSION=1.2.9 WORKDADDY_BUILD_ARCH=arm64 bash scripts/build-linux-deb.sh+```-当前发布脚本打包两个 WorkBuddy 客户端:Windows 每个客户端发布 Setup.exe 与便携版 ZIP 两个包:`WorkDaddy-Setup-<version>.exe` / `WorkDaddy-Portable-<version>.zip`、`WorkDaddy-AI-Setup-<version>.exe` / `WorkDaddy-AI-Portable-<version>.zip`;macOS 发布两个 DMG;Linux 为 `amd64` 和 `arm64` 分别发布 `WorkDaddy_<version>_<arch>.deb` 和 `WorkDaddy-AI_<version>_<arch>.deb`。macOS 构建时传 `WORKDADDY_BUILD_PROFILE=workbuddy-cn` 或 `workbuddy-ai` 可单独重打一个客户端;Linux 构建时传 `WORKDADDY_BUILD_ARCH=amd64` 或 `arm64`。Windows 便携版 ZIP 与 Setup.exe 同源生成,顶层只有启动和停止入口。+macOS 可用 `WORKDADDY_BUILD_PROFILE` 指定上表中的单个 profile。Windows Portable ZIP 可直接使用;`*-win64.zip` 仅为安装器构建的临时输入,不作为发布包。`install.sh` 做了:@@ -234,11 +232,13 @@ WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh└─────────────┘ └──────────────┘```+以下示意图以 WorkBuddy 国内版为例;四个 profile 的默认本地 API 端口依次为 `47832`、`47833`、`47834`、`47835`,渲染器 CDP 端口依次为 `9222`、`9223`、`9224`、`9225`。CodeBuddy 另用本机主进程调试端口 `9244` / `9245` 访问原生登录态与会话存储。+1. **不修改 WorkBuddy 二进制**:用 `launcher` 启动 WorkBuddy 时多带一个 `--remote-debugging-port=9222` 参数,**二进制与签名原封不动**。2. **守护进程通过 CDP 连接 WorkBuddy**:监听登录/认证网络事件 + 文件监听兜底,每次登录/刷新令牌都把当前登录信息按 `account.uid` 备份到稳定目录。-3. **注入界面组件**:`Runtime.evaluate` 把 `inject.js` 推到渲染进程执行,在右下角渲染机器人按钮和多标签页面板(账号 / 主题 / 会话 / 模型 / 增强 / 自动化 / 电脑 / 关于 / 设置)。+3. **注入界面组件**:`Runtime.evaluate` 把 `inject.js` 推到渲染进程执行,在右下角渲染机器人按钮和多标签页面板(账号 / 主题 / 会话 / 模型 / 增强 / 自动化 / 电脑 / 关于 / 设置),按客户端能力显示,CodeBuddy 隐藏「增强」。4. **本地 HTTP API**:daemon 在 `127.0.0.1:47832` 起服务,组件通过 fetch 调用(账号切换、主题应用、成长进度查询、决策弹窗开关、休眠控制等)。-5. **数据边界清晰**:账号备份和本地配置保存在本机;按功能访问 WorkBuddy 官方 API(登录、积分)和 GitHub Releases(更新检查),显式执行模型连通测试时会向你配置的模型服务发送请求及对应 API Key;脱敏错误诊断默认开启,可在「关于」页关闭。+5. **数据边界清晰**:账号备份和本地配置保存在本机;按功能访问 WorkBuddy 官方 API 或 CodeBuddy 官方 API(登录、积分)和 GitHub Releases(更新检查),显式执行模型连通测试时会向你配置的模型服务发送请求及对应 API Key;脱敏错误诊断默认开启,可在「关于」页关闭。> 为什么用 CDP 而不是官方插件机制:直接面向运行中的应用实例,事件级感知登录变化,> 主动注入界面与样式补丁,**官方升级 WorkBuddy 后只要界面没大改就照常工作**。@@ -249,21 +249,21 @@ WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh### 面板-WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:+WorkBuddy / CodeBuddy Electron 窗口右下角的机器人按钮 → 弹出面板 → 选你要的操作:-| Tab | 能做什么 |-| ------- | ----------------------------------------------------------------- |+| Tab | 能做什么 |+| ------- | ------------------------------------------------------------------------------- || **账号** | 查看账号数、积分、模型频率限制与预计解封时间、当日签到状态、连续活跃天数、成长任务进度及 Buddy 旅行状态;切换、删除或登录新账号,并加密导入导出账号备份 |-| **主题** | 切换默认 / WorkDaddy 主题,选择或上传壁纸、更换头像,调整毛玻璃和背景蒙版 |-| **会话** | 按账号和时间筛选会话,批量复制或删除,并设置会话 / 工作空间在切换账号时自动复制 |-| **模型** | 管理当前模型和备选模型,支持备份、复制、编辑、启用、连通测试及批量删除 |-| **增强** | 配置权限免打扰、异常中断自动续接、会话分支、暂存提示词和快捷短语 |-| **自动化** | 从 GitHub / Gitee 发现并导入任务、让 WorkBuddy 创建任务,管理触发方式与运行日志,以及 JSON / ZIP 导出 |-| **电脑** | 允许或持续禁止休眠,也可在所有 AI 任务结束后自动恢复休眠 |-| **关于** | 查看版本和项目说明、检查并安装更新、控制脱敏错误诊断 |-| **设置** | 选择中文或英语;首次打开按系统语言匹配,未匹配时使用英语 |--**输入框插件**:在「增强」页分别开启「暂存提示词」和「快捷短语」后,输入框操作栏会显示对应按钮。+| **主题** | WorkBuddy:接管主题并选择五种外观,管理壁纸、头像和背景;CodeBuddy:黑白悬浮机器人设置 |+| **会话** | 按账号和时间筛选会话,批量复制或删除,并设置会话 / 工作空间在切换账号时自动复制 |+| **模型** | 管理当前模型和备选模型,支持备份、复制、编辑、启用、连通测试及批量删除 |+| **增强** | 配置权限免打扰、异常中断自动续接、会话分支、暂存提示词和快捷短语 |+| **自动化** | 从 GitHub / Gitee 发现并导入任务、让 WorkBuddy 创建任务,管理触发方式与运行日志,以及 JSON / ZIP 导出 |+| **电脑** | 允许或持续禁止休眠,也可在所有 AI 任务结束后自动恢复休眠 |+| **关于** | 查看版本和项目说明、检查并安装更新、控制脱敏错误诊断 |+| **设置** | 选择中文或英语;首次打开按系统语言匹配,未匹配时使用英语 |++**输入框插件(仅 WorkBuddy / WorkBuddy AI)**:在「增强」页分别开启「暂存提示词」和「快捷短语」后,输入框操作栏会显示对应按钮。暂存提示词可把当前草稿(文字、图片、文件、引用等**完整原样**)加入 WorkBuddy 自带的待发送队列,并暂停自动发送;入队后输入框自动清空,内容按会话独立保存,可随时发送、编辑或删除。快捷短语可在增强页新增、编辑和批量管理,并从输入框操作栏一键发送,发送后不会自动删除。@@ -288,7 +288,6 @@ WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:符合约定的仓库会在下一次刷新后出现在「发现任务」列表中(搜索结果有 10 分钟缓存)。导入只读取文件并做兼容性检查,不会执行任务;导入后保持停用,相同 ID 的已有任务不会被覆盖。-任务定义保存在本机,由 WorkDaddy 本地服务执行;定时和事件触发需要服务保持运行,涉及页面交互的步骤还需要对应 WorkBuddy 客户端可用。任务导出不包含账号备份或运行日志;自动化页不提供本地 JSON / ZIP 文件导入。### 账号迁移到其他电脑@@ -303,7 +302,7 @@ WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:## 安全与隐私-- **本地数据优先**:账号备份、主题和本地配置不会在后台上传;登录、积分等功能会访问 WorkBuddy 官方 API,自动更新会访问 GitHub Releases;显式执行模型连通测试时,会向你配置的第三方模型地址发送请求及对应 API Key。+- **本地数据优先**:账号备份、主题和本地配置不会在后台上传;登录、积分等功能会访问 WorkBuddy 官方 API 或 CodeBuddy 官方 API,自动更新会访问 GitHub Releases;显式执行模型连通测试时,会向你配置的第三方模型地址发送请求及对应 API Key。- **发送错误诊断默认开启**:关于页的「发送错误诊断」开关同时控制 Sentry 远程错误诊断和本地脱敏渲染器日志,帮助定位版本和兼容性问题;处理内容经过脱敏、截断,远程上报不包含账号、会话内容、Token 或 API Key。随时可以在关于页关闭;`WORKDADDY_TELEMETRY=0`/`1` 可作为启动时的明确关闭/开启覆盖。独立的 `SECURITY.md` 可补充完整威胁模型;未提供时,本节即为安全与隐私说明。@@ -314,8 +313,8 @@ WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:本项目采用 **[GNU Affero General Public License v3.0](LICENSE)** 开源(`SPDX-License-Identifier: AGPL-3.0-or-later`)。-- 本项目仅面向本机运行的 WorkBuddy 桌面端做界面与体验增强,**与 WorkBuddy 官方无隶属关系**。-- WorkBuddy、其商标、官方资源归其权利人所有;本项目未获得其官方授权或认可。+- 本项目面向本机运行的 WorkBuddy / CodeBuddy 桌面端做界面与体验增强,**与两者官方无隶属关系**。+- WorkBuddy、CodeBuddy 及其商标、官方资源归其权利人所有;本项目未获得其官方授权或认可。- 第三方主题、壁纸、背景图等素材仅作演示,商用前请自行确认权利。---diff --git a/README_en.md b/README_en.mdindex e7104e2..9e466cc 100644--- a/README_en.md+++ b/README_en.md@@ -2,18 +2,29 @@**Language:** [简体中文](README.md) · [English](README_en.md)-> **WorkDaddy enhances the WorkBuddy desktop app: keep separate account backups and switch with a click; run unattended AI tasks with quiet approval mode; migrate sessions between accounts and resume interrupted tasks; run automations on events or schedules; stash prompts, send quick phrases, and customize frosted-glass themes. Accounts and configuration stay on your computer.**+> **WorkDaddy / CodeDaddy enhance WorkBuddy and CodeBuddy desktop clients with separate account backups, account switching, session migration, model management, and automations. WorkBuddy also supports quiet approvals, auto-continue, prompt stashing, quick phrases, and five themes. Accounts and configuration stay on your computer.**> Local loopback CDP injection · the official installation is never modified.-A desktop enhancement tool for [WorkBuddy](https://www.workbuddy.cn/) and [WorkBuddy AI](https://www.workbuddy.ai/), built on **Chrome DevTools Protocol (CDP)**.-It injects UI components into the running WorkBuddy renderer without patching or re-signing the official app.+A desktop enhancement tool for [WorkBuddy](https://www.workbuddy.cn/), [WorkBuddy AI](https://www.workbuddy.ai/), [CodeBuddy CN](https://www.codebuddy.cn/), and [CodeBuddy](https://www.codebuddy.ai/), built on **Chrome DevTools Protocol (CDP)**.+CodeBuddy support targets its **Electron agent window**, not the VS Code editor mode. Local debugging interfaces connect to the running client without modifying its official installation or signature.--++---+## Clients and feature scope++| Official client | Package brand | Profile |+| --- | --- | --- |+| WorkBuddy mainland | WorkDaddy | `workbuddy-cn` |+| WorkBuddy AI international | WorkDaddy AI | `workbuddy-ai` |+| CodeBuddy CN mainland (Electron) | CodeDaddy CN | `codebuddy-cn` |+| CodeBuddy international (Electron) | CodeDaddy | `codebuddy-intl` |++- Note: CodeBuddy does not show the Enhance page; its Theme page only provides floating robot settings.+## Preview<img src="docs/images/accounts-light.jpg" width="600">@@ -31,17 +42,17 @@ It injects UI components into the running WorkBuddy renderer without patching or## What it does-- **Fast account switching:** each WorkBuddy account has a separate backup, so you can switch without scanning a QR code every time.+- **Fast account switching:** each client keeps separate account backups, so you can switch without scanning a QR code every time.- **Add an account without quitting:** authorize through OAuth in your browser while WorkBuddy stays open. The new account joins the list automatically. A traditional soft logout flow is also available.- **Encrypted account import/export:** move account backups between computers using a password-protected file.-- **Daily credits:** daily check-in automation is disabled by default. On the first panel opening, a risk notice lets you enable the task or cancel. Either choice is saved locally and dismisses future notices; you can later enable or disable the task under Automations.+- **Growth and activity:** mainland editions show growth-task progress, daily check-in and activity status, consecutive active days, and Buddy unlock and travel status.- **Token and credit usage pages:** review daily token and credit consumption, filter by account, and view usage rankings by model and account.- **Credit-aware account suggestions:** when an account is running low on credits, WorkDaddy suggests another account you can use.- **Model rate limits and reset estimates:** when a model rate limit is detected, the Accounts page shows the affected model and its estimated reset time. If no reset time is provided, it displays “Time unknown.”- **Automation tasks:** discover and import tasks from public GitHub and Gitee repositories, or describe what you need and let WorkBuddy create a task. Supports manual, event, and scheduled triggers, run logs, stopping tasks, and JSON / ZIP export.- **Quiet approval mode:** automatically handle supported permission prompts while you are away.- **Stash prompts:** send drafts to WorkBuddy's pending message queue while preserving images, files, and quotes for later use.-- **Themes:** use the built-in frosted-glass theme, preset wallpapers, or your own backgrounds.+- **Themes:** WorkBuddy’s Manage theme switch offers Light, Dark, Eye-care green, Cyber purple, and Frosted glass. Frosted glass supports preset and custom wallpapers; turning management off restores the client’s native appearance.- **Session migration:** copy sessions between accounts automatically or manually and continue working where you left off.- **Session branching:** once enabled under Enhance, any reply can start a new conversation that keeps the chat up to that reply, while the original conversation stays untouched.- **Model tools:** manage and switch models more easily, including multiple configurations with the same model name.@@ -53,19 +64,18 @@ It injects UI components into the running WorkBuddy renderer without patching or## Installation-- For the mainland [WorkBuddy](https://www.workbuddy.cn/) client, download **WorkDaddy**.-- For the international [WorkBuddy AI](https://www.workbuddy.ai/) client, download **WorkDaddy AI**.+Install and sign in to the official client first, then choose the matching package brand from the table above. All four packages have separate installations and account backup directories. Spaces in package names are written as hyphens.### macOS-1. Download the latest `WorkDaddy-x.y.z.dmg` or `WorkDaddy-AI-x.y.z.dmg` from [Releases](../../releases).+1. Download `WorkDaddy-x.y.z.dmg`, `WorkDaddy-AI-x.y.z.dmg`, `CodeDaddy-CN-x.y.z.dmg`, or `CodeDaddy-x.y.z.dmg` for your client from [Releases](../../releases).2. Open the DMG and drag the app into **Applications**.3. If macOS says Apple cannot check the app for malicious software:1. Open **System Settings → Privacy & Security**.2. Find the blocked WorkDaddy app and choose **Open Anyway**.3. Confirm with your login password.-4. Launch the app. It starts its local daemon and injects the panel into WorkBuddy.+4. Launch the matching WorkDaddy / CodeDaddy app. It starts its local daemon and injects the panel into your client. The macOS launcher uses your local Node.js installation; Node.js 22.13 or newer is recommended.5. Once the robot button appears, you are ready to go.#### Enterprise / VPC clients@@ -81,9 +91,15 @@ node scripts/workbuddy-target.js --configure --platform darwin \### Windows-1. Download `WorkDaddy-Setup-x.y.z.exe` or `WorkDaddy-AI-Setup-x.y.z.exe` for your client from [Releases](../../releases).+1. Download `WorkDaddy-Setup-x.y.z.exe`, `WorkDaddy-AI-Setup-x.y.z.exe`, `CodeDaddy-CN-Setup-x.y.z.exe`, or `CodeDaddy-Setup-x.y.z.exe` for your client from [Releases](../../releases).2. Run the installer.-3. Launch **WorkDaddy** or **WorkDaddy AI** from the desktop shortcut.+3. Launch the matching brand from its desktop shortcut.++#### Windows portable ZIPs++Use the matching `<brand>-Portable-x.y.z.zip`, where `<brand>` is `WorkDaddy`, `WorkDaddy-AI`, `CodeDaddy-CN`, or `CodeDaddy`. Extract it to a writable directory, then run `Start-WorkDaddy.cmd` or `WorkDaddyLauncher.exe`. Run `Stop-WorkDaddy.cmd` before replacing it with a newer ZIP.++Portable packages do not create shortcuts or uninstall entries. Backups remain under the current user’s `%APPDATA%\WorkDaddy`, not inside the ZIP. Do not run installed and portable copies of the same profile together. Portable editions do not use the panel’s installer updater.#### Enterprise / VPC clients@@ -91,6 +107,45 @@ Install the WorkDaddy or WorkDaddy AI edition that most closely matches your cliThe selection is saved in WorkDaddy's personal data directory and preserved during updates. Run the installer again to change it or return to the detected official client. WorkDaddy pins the selected client version, so use the installer to confirm the client again after it is upgraded or moved.+### Linux++Ubuntu / Debian packages are available for `amd64` and `arm64`, with a matching Node.js runtime included. Install and sign in to the official client for the same architecture first.++| Brand | DEB file | Installation directory / Debian package name |+| --- | --- | --- |+| WorkDaddy | `WorkDaddy_x.y.z_<arch>.deb` | `/opt/workdaddy` / `workdaddy` |+| WorkDaddy AI | `WorkDaddy-AI_x.y.z_<arch>.deb` | `/opt/workdaddy-ai` / `workdaddy-ai` |+| CodeDaddy CN | `CodeDaddy-CN_x.y.z_<arch>.deb` | `/opt/codedaddy-cn` / `codedaddy-cn` |+| CodeDaddy | `CodeDaddy_x.y.z_<arch>.deb` | `/opt/codedaddy` / `codedaddy` |++1. Download the matching file from [Releases](../../releases), choosing `amd64` or `arm64` for `<arch>`.+2. Install it from your download directory, for example:++ ```bash+ sudo apt install ./CodeDaddy-CN_1.2.9_amd64.deb+ ```++3. Launch the matching brand from the application menu and follow the instructions to enable CDP. For CodeBuddy, open its Electron agent window.++All four packages can coexist and do not enable login autostart by default. Without an application menu, use the matching entry point:++```bash+bash /opt/workdaddy/scripts/launch-gui-linux.sh cn+bash /opt/workdaddy-ai/scripts/launch-gui-linux.sh ai+bash /opt/codedaddy-cn/scripts/launch-gui-linux.sh codebuddy-cn+bash /opt/codedaddy/scripts/launch-gui-linux.sh codebuddy-intl+```++Optionally enable a systemd user service for your profile, for example:++```bash+WBSWITCH_PROFILE=codebuddy-cn bash /opt/codedaddy-cn/scripts/systemd-install-linux.sh+```++Uninstall with `sudo apt remove <package-name>`. Account backups and runtime data under `~/.config/WorkDaddy` are retained. Linux does not currently support updates from the panel; install the newer DEB to upgrade.++For Linux source installation, use `scripts/install-linux.sh` and `scripts/relaunch-with-cdp-linux.sh` with the appropriate `WBSWITCH_PROFILE`. WorkBuddy AI can use `scripts/workbuddy-ai-linux.sh install` and `scripts/workbuddy-ai-linux.sh relaunch` for its isolated environment. Set `WBSWITCH_WORKBUDDY_BIN=/path/to/client` when you need to select a client executable explicitly.+### Run from source (developers)```bash@@ -100,16 +155,24 @@ bash scripts/install.sh # Create the backup directory and start the dabash scripts/relaunch-with-cdp.sh # Launch WorkBuddy with CDP on port 9222```-WorkBuddy and WorkBuddy AI share the same daemon code. Profiles bind it to the intended client rather than guessing from the first available CDP port:+All four clients share the same daemon code. Profiles bind it to the intended client rather than guessing from the first available CDP port:```bashWBSWITCH_PROFILE=workbuddy-cn bash scripts/relaunch-with-cdp.shWBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh+WBSWITCH_PROFILE=codebuddy-cn bash scripts/relaunch-with-cdp.sh+WBSWITCH_PROFILE=codebuddy-intl bash scripts/relaunch-with-cdp.sh```-Prompt stashing and themes are enabled for both WorkBuddy profiles. CodeBuddy profile support is on hold and is outside the current release scope.+The release scripts build four DMGs for macOS, four DEBs per architecture for Linux, and a Setup.exe plus a Portable ZIP per client for Windows. Available downloads depend on the assets attached to each [Release](../../releases).++```bash+WORKDADDY_BUILD_VERSION=1.2.9 bash scripts/build-mac-dmg.sh+WORKDADDY_BUILD_VERSION=1.2.9 WORKDADDY_BUILD_ARCH=amd64 bash scripts/build-linux-deb.sh+WORKDADDY_BUILD_VERSION=1.2.9 WORKDADDY_BUILD_ARCH=arm64 bash scripts/build-linux-deb.sh+```-The release scripts produce packages for both WorkBuddy clients: `WorkDaddy-<version>.dmg` and `WorkDaddy-AI-<version>.dmg` on macOS; `WorkDaddy-Setup-<version>.exe` / `WorkDaddy-Portable-<version>.zip` and `WorkDaddy-AI-Setup-<version>.exe` / `WorkDaddy-AI-Portable-<version>.zip` on Windows; and `WorkDaddy_<version>_<arch>.deb` / `WorkDaddy-AI_<version>_<arch>.deb` for Linux `amd64` and `arm64`. For macOS builds, set `WORKDADDY_BUILD_PROFILE=workbuddy-cn` or `workbuddy-ai` to build only one client. For Linux, set `WORKDADDY_BUILD_ARCH=amd64` or `arm64`. Windows ZIPs are temporary installer build inputs, not release downloads.+For macOS, use `WORKDADDY_BUILD_PROFILE` with any profile from the table above to build a single client. Windows Portable ZIPs are usable release downloads; `*-win64.zip` files are temporary installer build inputs.`install.sh`:@@ -139,11 +202,13 @@ The release scripts produce packages for both WorkBuddy clients: `WorkDaddy-<ver└─────────────┘ └──────────────┘```+The diagram uses mainland WorkBuddy as an example. In the profile order shown above, local API ports default to `47832`, `47833`, `47834`, and `47835`; renderer CDP ports default to `9222`, `9223`, `9224`, and `9225`. CodeBuddy additionally uses local main-process debugging ports `9244` / `9245` for native authentication and session storage.+1. **Unmodified WorkBuddy binaries:** the launcher adds `--remote-debugging-port=9222` when starting WorkBuddy. Its binary and signature remain intact.2. **CDP connection:** the daemon watches login and authentication network events, with a file watcher as a fallback. Login and token refresh events back up the current account to a stable local directory using `account.uid`.-3. **Injected UI:** `Runtime.evaluate` runs `inject.js` in the renderer, adding the robot button and the Accounts, Theme, Sessions, Models, Enhance, Automation, Computer, About, and Settings pages.+3. **Injected UI:** `Runtime.evaluate` runs `inject.js` in the renderer, adding the robot button and the Accounts, Theme, Sessions, Models, Enhance, Automation, Computer, About, and Settings pages according to client capabilities. CodeBuddy hides Enhance.4. **Local HTTP API:** the daemon listens on `127.0.0.1:47832`. The panel uses it for account switching, themes, check-ins, permission prompts, sleep control, and other features.-5. **Data boundaries:** account backups and configuration stay local. Login and credit features call WorkBuddy's official APIs; update checks call GitHub Releases. Explicit model connectivity tests send requests and the corresponding API key to the model service you configured. Redacted error diagnostics are enabled by default and can be turned off in **About**.+5. **Data boundaries:** account backups and configuration stay local. Login and credit features call the corresponding client’s official APIs; update checks call GitHub Releases. Explicit model connectivity tests send requests and the corresponding API key to the model service you configured. Redacted error diagnostics are enabled by default and can be turned off in **About**.> Why CDP instead of an official plugin system? It connects directly to the running app, detects authentication changes, and injects the panel and style patches. WorkBuddy updates generally remain compatible as long as its interface does not change substantially.@@ -153,12 +218,12 @@ The release scripts produce packages for both WorkBuddy clients: `WorkDaddy-<ver### Panel-Click the robot button in the lower-right corner of WorkBuddy and choose a tab:+Click the robot button in the lower-right corner of WorkBuddy or the CodeBuddy Electron window and choose a tab:| Tab | Purpose || -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |-| **Accounts** | View account counts, credits, model rate limits and estimated reset times, check-ins, and login status; switch, delete, or add accounts; import/export encrypted backups |-| **Theme** | Switch between the default and WorkDaddy themes, choose or upload wallpapers, change avatars, and adjust blur and background overlays |+| **Accounts** | View account counts, credits, model rate limits and estimated reset times, daily check-in status, consecutive active days, growth progress, and Buddy travel status; switch, delete, or add accounts; import/export encrypted backups |+| **Theme** | WorkBuddy: manage five themes, wallpapers, avatars, blur, and overlays. CodeBuddy: black or white floating robot settings || **Sessions** | Filter by account and date, copy or delete in bulk, and configure automatic session or workspace copying when switching accounts || **Models** | Manage current and alternative models, including backups, copying, editing, enabling, connectivity tests, and bulk deletion || **Enhance** | Configure quiet approvals, auto-continue, session branching, prompt stashing, and quick phrases |@@ -167,7 +232,7 @@ Click the robot button in the lower-right corner of WorkBuddy and choose a tab:| **About** | View version and project information, check for and install updates, and control redacted error diagnostics || **Settings** | Choose Chinese or English; the first launch follows the system language and falls back to English |-**Composer tools:** enable **Stash prompts** and **Quick phrases** separately in **Enhance** to show their composer toolbar buttons. Stashing adds the current draft to WorkBuddy's own message queue with text, images, files, and quotes **preserved**, and pauses automatic sending. The composer is then cleared. Queued content is kept per conversation and can be sent, edited, or deleted. Quick phrases can be created, edited, and managed in bulk in Enhance, then sent from the composer toolbar; sending does not delete them.+**Composer tools (WorkBuddy / WorkBuddy AI only):** enable **Stash prompts** and **Quick phrases** separately in **Enhance** to show their composer toolbar buttons. Stashing adds the current draft to WorkBuddy's own message queue with text, images, files, and quotes **preserved**, and pauses automatic sending. The composer is then cleared. Queued content is kept per conversation and can be sent, edited, or deleted. Quick phrases can be created, edited, and managed in bulk in Enhance, then sent from the composer toolbar; sending does not delete them.### Automation@@ -204,7 +269,7 @@ Current exports use your password, a fresh random salt, and AES-256-GCM encrypti## Security and privacy-- **Local data first:** account backups, themes, and local configuration are not uploaded in the background. Login and credit features access WorkBuddy's official APIs, and updates access GitHub Releases. Explicit model connectivity tests send requests and the corresponding API key to the third-party model service you configured.+- **Local data first:** account backups, themes, and local configuration are not uploaded in the background. Login and credit features access the corresponding client’s official APIs, and updates access GitHub Releases. Explicit model connectivity tests send requests and the corresponding API key to the third-party model service you configured.- **Error diagnostics are enabled by default:** the **Send error diagnostics** switch in About controls both remote Sentry error reporting and local redacted renderer logs to help diagnose version and compatibility issues. Reports are redacted and truncated; remote reports exclude accounts, session contents, tokens, and API keys. Turn diagnostics off at any time in About, or use `WORKDADDY_TELEMETRY=0` / `1` as an explicit startup override.A separate `SECURITY.md` may provide an expanded threat model; when it is not included, this section serves as the privacy and security overview.@@ -215,8 +280,8 @@ A separate `SECURITY.md` may provide an expanded threat model; when it is not inThis project is licensed under the **[GNU Affero General Public License v3.0](LICENSE)** (`SPDX-License-Identifier: AGPL-3.0-or-later`).-- WorkDaddy provides local UI and usability enhancements for the WorkBuddy desktop app and **is not affiliated with WorkBuddy**.-- WorkBuddy, its trademarks, and official assets belong to their respective owners. This project is not officially authorized or endorsed by WorkBuddy.+- WorkDaddy / CodeDaddy provide local UI and usability enhancements for WorkBuddy and CodeBuddy and **are not affiliated with either official product**.+- WorkBuddy, CodeBuddy, their trademarks, and official assets belong to their respective owners. This project is not officially authorized or endorsed by either product.- Third-party themes, wallpapers, and background images are provided for demonstration; check their rights before commercial use.---diff --git a/scripts/apply-update.ps1 b/scripts/apply-update.ps1index c68819d..47aa5df 100644--- a/scripts/apply-update.ps1+++ b/scripts/apply-update.ps1@@ -26,14 +26,14 @@ try { . (Join-Path $PSScriptRoot 'windows-process-boundary.ps1') } catch {exit 5}if ([string]::IsNullOrWhiteSpace($Profile) -or $Profile -eq '__WBS_DEFAULT_PROFILE__') { $Profile = 'workbuddy-cn' }-if ($Profile -ne 'workbuddy-ai') { $Profile = 'workbuddy-cn' }-$productName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy AI' } else { 'WorkDaddy' }+if ($Profile -notin @('workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl')) { throw 'Unknown client profile' }+$productName = (@{'workbuddy-cn'='WorkDaddy'; 'workbuddy-ai'='WorkDaddy AI'; 'codebuddy-cn'='CodeDaddy CN'; 'codebuddy-intl'='CodeDaddy'})[$Profile]if ([string]::IsNullOrWhiteSpace($AppDir)) { $AppDir = Join-Path $env:LOCALAPPDATA (Join-Path 'Programs' $productName) }if (-not (Test-SameWindowsPath -Left $PSScriptRoot -Right (Join-Path $AppDir 'scripts'))) {throw '更新脚本位置与目标安装目录不一致,拒绝替换'}$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'-$DataDir = if ($Profile -eq 'workbuddy-ai') { Join-Path $dataRoot 'profiles\workbuddy-ai' } else { $dataRoot }+$DataDir = if ($Profile -eq 'workbuddy-cn') { $dataRoot } else { Join-Path $dataRoot ('profiles\' + $Profile) }$LogDir = Join-Path $DataDir 'update'New-Item -ItemType Directory -Force -Path $LogDir | Out-Nullif ([string]::IsNullOrWhiteSpace($LogPath)) { $LogPath = Join-Path $LogDir 'apply.log' }@@ -66,7 +66,7 @@ function Stop-WatchdogAndPort {}function Stop-WorkBuddyForUpdate {- $processName = if ($Profile -eq 'workbuddy-ai') { 'WorkBuddyAI.exe' } else { 'WorkBuddy.exe' }+ $processName = (@{'workbuddy-cn'='WorkBuddy.exe'; 'workbuddy-ai'='WorkBuddyAI.exe'; 'codebuddy-cn'='CodeBuddy CN.exe'; 'codebuddy-intl'='CodeBuddy.exe'})[$Profile]$stopped = Stop-VerifiedWorkBuddyProcesses -ProcessName $processNameif ($stopped -gt 0) { Write-ApplyLog "已停止 $processName 进程数=$stopped,释放安装目录文件锁" }}diff --git a/scripts/automation-discovery.js b/scripts/automation-discovery.jsindex be0c559..5e2aac8 100644--- a/scripts/automation-discovery.js+++ b/scripts/automation-discovery.js@@ -329,7 +329,13 @@ function createAutomationDiscovery(options) {};}+ function adoptSharedCache() {+ const latest = readCache(cacheFile);+ if (Number(latest.checkedAt) >= Number(state.checkedAt)) state = latest;+ }+async function refresh() {+ adoptSharedCache();const errors = [];const search = await Promise.allSettled([searchGitHub(fetchImpl, marker, pageSize), searchGitee(fetchImpl, marker, pageSize)]);const providers = { github: state.providers.github || [], gitee: state.providers.gitee || [] };@@ -365,6 +371,7 @@ function createAutomationDiscovery(options) {}async function getCatalog(options = {}) {+ if (!inFlight) adoptSharedCache();if (!options.force && now() - Number(state.checkedAt || 0) < CACHE_TTL_MS) return publicCatalog();if (!inFlight) inFlight = refresh().finally(() => { inFlight = null; });return inFlight;diff --git a/scripts/automation.js b/scripts/automation.jsindex 88b2bc6..16a8670 100644--- a/scripts/automation.js+++ b/scripts/automation.js@@ -288,8 +288,22 @@ function builtinContentHash(task) {return crypto.createHash('sha256').update(JSON.stringify(content)).digest('hex');}-function installBuiltinTask(dataDir, file) {- const task = validateTask(JSON.parse(fs.readFileSync(file, 'utf8')));+function installBuiltinTask(dataDir, file, profile) {+ const preset = JSON.parse(fs.readFileSync(file, 'utf8'));+ // Reuse the shipped task while keeping authenticated requests on the+ // selected client's official origin. Imported/user-edited tasks are untouched.+ if (profile && profile.kind === 'codebuddy') {+ const adapt = value => {+ if (!value || typeof value !== 'object') return;+ if (value.op === 'http.requestAsAccount' && typeof value.url === 'string') {+ const url = new URL(value.url);+ if (url.origin === 'https://www.workbuddy.cn') value.url = profile.apiHost + url.pathname + url.search + url.hash;+ }+ Object.values(value).forEach(adapt);+ };+ adapt(preset);+ }+ const task = validateTask(preset);const markerFile = path.join(dataDir, 'automation-builtins.json');let markers = {};try { markers = JSON.parse(fs.readFileSync(markerFile, 'utf8')); } catch (_) {}@@ -340,6 +354,20 @@ function installBuiltinTask(dataDir, file) {return { status: 'upgraded', revision };}+// Retire only presets installed by us. Keep imports with the same id and retain+// markers so a removed preset cannot be reinstalled during a later migration.+function removeBuiltinTasks(dataDir, ids) {+ let markers;+ try { markers = JSON.parse(fs.readFileSync(path.join(dataDir, 'automation-builtins.json'), 'utf8')); }+ catch (_) { return; }+ const tasks = readAutomations(dataDir);+ const remaining = tasks.filter(task => {+ const marker = markers && markers[task.id];+ return (ids && !ids.includes(task.id)) || !(marker === true || marker && marker.managed === true);+ });+ if (remaining.length !== tasks.length) writeAutomations(dataDir, remaining);+}+function validateLocator(locator) {if (!locator || typeof locator !== 'object') throw new Error('缺少 locator');const kind = String(locator.kind || '').trim();@@ -1033,6 +1061,7 @@ module.exports = {stepsContainCheckin,taskIsPassiveCleanup,installBuiltinTask,+ removeBuiltinTasks,SCHEMA_VERSION,CAPABILITIES,SUPPORTED_OPS,diff --git a/scripts/build-linux-deb.sh b/scripts/build-linux-deb.shindex e468bc2..c8b893c 100644--- a/scripts/build-linux-deb.sh+++ b/scripts/build-linux-deb.sh@@ -139,13 +139,14 @@ NODEbuild_package() {local profile="$1" package_name="$2" install_root="$3" display_name="$4" output_name="$5"+ if [ -n "${WORKDADDY_BUILD_PROFILE:-}" ] && [ "$WORKDADDY_BUILD_PROFILE" != "$profile" ]; then return; filocal stage="$TEMP/stage-$profile"local scripts="$stage$install_root/scripts"mkdir -p "$scripts" "$stage/DEBIAN" "$stage/usr/share/applications" \"$stage/usr/share/icons/hicolor/1024x1024/apps"cp -R "$COMMON/opt/workdaddy/scripts/." "$scripts/"cp "$COMMON/usr/share/icons/hicolor/1024x1024/apps/workdaddy.png" \- "$stage/usr/share/icons/hicolor/1024x1024/apps/workdaddy-$profile.png"+ "$stage/usr/share/icons/hicolor/1024x1024/apps/$package_name.png"chmod 755 "$scripts/"*-linux.shcat > "$stage/DEBIAN/control" <<EOF@@ -160,13 +161,13 @@ Description: $display_name desktop enhancement for WorkBuddyLocal CDP integration for the separately installed $display_name client.EOF- cat > "$stage/usr/share/applications/workdaddy-$profile.desktop" <<EOF+ cat > "$stage/usr/share/applications/$package_name.desktop" <<EOF[Desktop Entry]Type=ApplicationName=$display_nameExec=$install_root/scripts/launch-gui-linux.sh $profileTryExec=$install_root/scripts/launch-gui-linux.sh-Icon=workdaddy-$profile+Icon=$package_nameTerminal=falseCategories=Utility;EOF@@ -277,3 +278,6 @@ PYbuild_package cn workdaddy /opt/workdaddy 'WorkDaddy' "WorkDaddy_${VERSION}_${DEB_ARCH}.deb"build_package ai workdaddy-ai /opt/workdaddy-ai 'WorkDaddy AI' "WorkDaddy-AI_${VERSION}_${DEB_ARCH}.deb"++build_package codebuddy-cn codedaddy-cn /opt/codedaddy-cn 'CodeDaddy CN' "CodeDaddy-CN_${VERSION}_${DEB_ARCH}.deb"+build_package codebuddy-intl codedaddy /opt/codedaddy 'CodeDaddy' "CodeDaddy_${VERSION}_${DEB_ARCH}.deb"diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex 3fa784f..c242499 100644--- a/scripts/build-mac-dmg.sh+++ b/scripts/build-mac-dmg.sh@@ -28,20 +28,29 @@ DMG_BACKGROUND_SVG="$DIR/scripts/assets/macos-dmg-background.svg"SKIP_FINDER="${WORKDADDY_SKIP_FINDER:-}"PROFILE="${WORKDADDY_BUILD_PROFILE:-}"if [ -z "$PROFILE" ]; then- for profile in workbuddy-cn workbuddy-ai; do+ for profile in workbuddy-cn workbuddy-ai codebuddy-cn codebuddy-intl; doWORKDADDY_BUILD_PROFILE="$profile" bash "$0" || exit $?doneexit 0ficase "$PROFILE" inworkbuddy-ai) PACKAGE_APP_NAME="WorkDaddy AI"; OUT="release/macos/WorkDaddy-AI-${VERSION}.dmg" ;;- *) PROFILE="workbuddy-cn"; PACKAGE_APP_NAME="WorkDaddy"; OUT="release/macos/WorkDaddy-${VERSION}.dmg" ;;+ codebuddy-cn) PACKAGE_APP_NAME="CodeDaddy CN"; OUT="release/macos/CodeDaddy-CN-${VERSION}.dmg" ;;+ codebuddy-intl) PACKAGE_APP_NAME="CodeDaddy"; OUT="release/macos/CodeDaddy-${VERSION}.dmg" ;;+ workbuddy-cn) PACKAGE_APP_NAME="WorkDaddy"; OUT="release/macos/WorkDaddy-${VERSION}.dmg" ;;+ *) echo "未知 profile: $PROFILE" >&2; exit 2 ;;esacecho "==> profile: ${PROFILE}"echo "==> 版本: ${VERSION}"echo "==> 产物: ${OUT}"+# Synchronize source into a temporary shell; keep the reusable app untouched.+SHELL_STAGE="$(mktemp -d)"+cp -R "$APP" "$SHELL_STAGE/WorkDaddy.app"+APP="$SHELL_STAGE/WorkDaddy.app"+trap 'rm -rf -- "$SHELL_STAGE"' EXIT+# 1) 壳完整性自检:launcher 必须有可执行位(1.0.3 原版为 -rwxr-xr-x)chmod 755 "$APP/Contents/MacOS/launcher"echo "==> launcher 可执行位已保证: $(stat -f '%Sp' "$APP/Contents/MacOS/launcher")"@@ -56,7 +65,7 @@ chmod 644 "$APP/Contents/Resources/AppIcon.icns"echo "==> 应用图标已同步(背景 #e1e1e1)"# 2) 覆盖运行时代码和主题配置,保留 launcher/Info.plist/壁纸/node_modules/theme-audit.js。-for f in daemon.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do+for f in daemon.js renderer-api-bridge.js codebuddy-native.js codebuddy-session-store.js codebuddy-files.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"done# Theme tokens are source code too; the reusable shell may contain older colors.@@ -129,7 +138,7 @@ cleanup_dmg_build() {if [ -n "$DMG_DEVICE" ]; thenhdiutil detach "$DMG_DEVICE" -force >/dev/null 2>&1 || truefi- rm -rf -- "$STAGE" "$DMG_TEMP_DIR"+ rm -rf -- "$STAGE" "$DMG_TEMP_DIR" "$SHELL_STAGE"}trap cleanup_dmg_build EXIT@@ -207,6 +216,8 @@ discover_workdaddy_workbuddy_app || trueraise SystemExit('macOS launcher 缺少 profile case')insert_at = case_index + len('esac')source = source[:insert_at] + '\n' + function + source[insert_at:]+# Historical HelloBuddy processes belong to the WorkDaddy profile only.+source = source.replace('cleanup_legacy() {', 'cleanup_legacy() {\n [ "$PROFILE" = workbuddy-cn ] || return 0')source = source.replace('workbuddy-target.js" --profile="$PROFILE"', 'workbuddy-target.js" --resolve --profile="$PROFILE"')# 官方安装不应把自身路径作为 custom target 传给 daemon。仅在用户配置了# workbuddy-target.json 时设置 override,并让 launchd plist 保持相同边界。@@ -292,8 +303,17 @@ replacement = r'''is_workbuddy_cdp() {printf '%s' "$body" | grep -qi 'WorkBuddy' &&! printf '%s' "$body" | grep -qiE 'WorkBuddy[[:space:]]*AI|WorkBuddyAI';;+ codebuddy-cn|codebuddy-intl)+ local native_port=9244+ [ "$PROFILE" = codebuddy-intl ] && native_port=9245+ curl -fsS --max-time 1 "http://127.0.0.1:$native_port/json/list" >/dev/null 2>&1 || return 1+ body="$(curl -fsS --max-time 1 "http://127.0.0.1:${p}/json/list" 2>/dev/null || true)"+ local expected="$APP_NAME"+ expected="${expected// /%20}"+ printf '%s' "$body" | grep -Fqi "/${expected}.app/"+ ;;*)- printf '%s' "$body" | grep -qiE 'WorkBuddy|CodeBuddy'+ return 1;;esac}'''@@ -303,10 +323,33 @@ if count != 1:with open(path, 'w', encoding='utf-8', newline='') as f:f.write(updated)PY-if [ "$PROFILE" = "workbuddy-ai" ]; then- perl -0pi -e 's/<string>WorkDaddy<\/string>/<string>WorkDaddy AI<\/string>/g' "$PACKAGE_APP/Contents/Info.plist"- perl -0pi -e 's/<string>com\.workdaddy\.launcher<\/string>/<string>com.workdaddy.ai.launcher<\/string>/g' "$PACKAGE_APP/Contents/Info.plist"+python3 - "$PACKAGE_APP/Contents/MacOS/launcher" "$PACKAGE_APP_NAME" <<'PYBRAND'+from pathlib import Path+import sys+file, brand = Path(sys.argv[1]), sys.argv[2]+text = file.read_text()+if brand.startswith('CodeDaddy'):+ marker = '# VPC/便携版可把 app 路径写到数据目录的 workbuddy-target.json;环境变量优先。'+ guard = '''if ! "$NODE_BIN" -e "require('node:sqlite')" >/dev/null 2>&1; then+ notify "WorkDaddy" "需要支持 SQLite 的 Node.js 22.13 或更新版本,请升级 Node.js 后重试"+ exit 1fi+'''+ if marker not in text:+ raise SystemExit('macOS launcher 缺少 Node.js 能力检查插入点')+ text = text.replace(marker, guard + marker, 1)+text = text.replace('notify "WorkDaddy"', 'notify "' + brand + '"').replace('with title "WorkDaddy"', 'with title "' + brand + '"')+file.write_text(text)+PYBRAND+/usr/libexec/PlistBuddy -c "Set :CFBundleName $PACKAGE_APP_NAME" "$PACKAGE_APP/Contents/Info.plist"+/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName $PACKAGE_APP_NAME" "$PACKAGE_APP/Contents/Info.plist" 2>/dev/null || /usr/libexec/PlistBuddy -c "Add :CFBundleDisplayName string $PACKAGE_APP_NAME" "$PACKAGE_APP/Contents/Info.plist"+case "$PROFILE" in+ workbuddy-cn) BUNDLE_ID=com.workdaddy.launcher ;;+ workbuddy-ai) BUNDLE_ID=com.workdaddy.ai.launcher ;;+ codebuddy-cn) BUNDLE_ID=com.codedaddy.cn.launcher ;;+ codebuddy-intl) BUNDLE_ID=com.codedaddy.launcher ;;+esac+/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier $BUNDLE_ID" "$PACKAGE_APP/Contents/Info.plist"# LaunchServices must own the target app identity, rather than inheriting the shell launcher.python3 - "$PACKAGE_APP/Contents/MacOS/launcher" <<'PY'import sys@@ -319,7 +362,12 @@ if [ "$TARGET_APP_BUNDLE" = "$APP_BIN" ] || [ ! -d "$TARGET_APP_BUNDLE" ]; thennotify "WorkDaddy" "WorkBuddy 应用路径无效,启动失败"exit 1fi-if ! /usr/bin/open -a "$TARGET_APP_BUNDLE" --args "--remote-debugging-port=$PORT"; then+NATIVE_ARGS=()+case "$PROFILE" in+ codebuddy-cn) NATIVE_ARGS=(--inspect=127.0.0.1:9244) ;;+ codebuddy-intl) NATIVE_ARGS=(--inspect=127.0.0.1:9245) ;;+esac+if ! /usr/bin/open -a "$TARGET_APP_BUNDLE" --args "--remote-debugging-port=$PORT" "${NATIVE_ARGS[@]}"; thennotify "WorkDaddy" "无法启动 WorkBuddy,请重试"exit 1fi'''diff --git a/scripts/build-win-installer.ps1 b/scripts/build-win-installer.ps1index 573534e..a61cc00 100644--- a/scripts/build-win-installer.ps1+++ b/scripts/build-win-installer.ps1@@ -2,7 +2,7 @@param([string]$OutputDirectory = '',[string]$IsccPath = '',- [ValidateSet('workbuddy-cn', 'workbuddy-ai')][string]$Profile = 'workbuddy-cn',+ [ValidateSet('workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl')][string]$Profile = 'workbuddy-cn',[string]$Version = '')@@ -17,10 +17,14 @@ if (-not $versionMatch.Success) { throw 'daemon.js does not contain DAEMON_VERSI$version = if ([string]::IsNullOrWhiteSpace($Version)) { $versionMatch.Groups[1].Value } else { $Version.Trim() }if ($version -notmatch '^\d+\.\d+\.\d+$') { throw "Invalid daemon version: $version" }-$productName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy AI' } else { 'WorkDaddy' }-$packageName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy-AI' } else { 'WorkDaddy' }-$startDescription = if ($Profile -eq 'workbuddy-ai') { '立即打开 WorkDaddy AI' } else { '立即打开 WorkDaddy' }-$appGuid = if ($Profile -eq 'workbuddy-ai') {+$productName = (@{'workbuddy-cn'='WorkDaddy'; 'workbuddy-ai'='WorkDaddy AI'; 'codebuddy-cn'='CodeDaddy CN'; 'codebuddy-intl'='CodeDaddy'})[$Profile]+$packageName = (@{'workbuddy-cn'='WorkDaddy'; 'workbuddy-ai'='WorkDaddy-AI'; 'codebuddy-cn'='CodeDaddy-CN'; 'codebuddy-intl'='CodeDaddy'})[$Profile]+$startDescription = ('立即打开 ' + $productName)+$appGuid = if ($Profile -eq 'codebuddy-cn') {+ '{{563ABF72-E1F4-4C60-8C6A-B485CC4C5561}'+} elseif ($Profile -eq 'codebuddy-intl') {+ '{{399D058D-D944-4333-9935-0CD38C12B44C}'+} elseif ($Profile -eq 'workbuddy-ai') {'{{D1A8A90C-1F55-4E56-8BB2-7F12A39B9D12}'} else {'{{4B857D52-8C5A-4A9A-A17D-0EE8A34A12C7}'diff --git a/scripts/build-win-release.ps1 b/scripts/build-win-release.ps1index 40a8a09..aff0692 100644--- a/scripts/build-win-release.ps1+++ b/scripts/build-win-release.ps1@@ -101,7 +101,7 @@ function Invoke-WindowsInstallerBuild {if ($LASTEXITCODE -ne 0) {throw "$Profile Setup.exe 生成失败(退出码 $LASTEXITCODE)。"}- $packageName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy-AI' } else { 'WorkDaddy' }+ $packageName = (@{'workbuddy-cn'='WorkDaddy'; 'workbuddy-ai'='WorkDaddy-AI'; 'codebuddy-cn'='CodeDaddy-CN'; 'codebuddy-intl'='CodeDaddy'})[$Profile]$setup = Join-Path $OutputDirectory "$packageName-Setup-$ReleaseVersion.exe"$portable = Join-Path $OutputDirectory "$packageName-Portable-$ReleaseVersion.zip"if (-not (Test-Path -LiteralPath $setup -PathType Leaf)) {@@ -161,7 +161,7 @@ try {New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null$packages = @()- foreach ($profile in @('workbuddy-cn', 'workbuddy-ai')) {+ foreach ($profile in @('workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl')) {Invoke-WindowsZipBuild -Bash $bash -Profile $profile -ReleaseVersion $Version -CachedPython $PythonPath -GoExecutable $GoPath$packages += Invoke-WindowsInstallerBuild -Profile $profile -ReleaseVersion $Version -Compiler $iscc}diff --git a/scripts/build-win-zip.sh b/scripts/build-win-zip.shindex f448848..80bf506 100644--- a/scripts/build-win-zip.sh+++ b/scripts/build-win-zip.sh@@ -39,14 +39,17 @@ if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; thenfiPROFILE="${WORKDADDY_BUILD_PROFILE:-}"if [ -z "$PROFILE" ]; then- for profile in workbuddy-cn workbuddy-ai; do+ for profile in workbuddy-cn workbuddy-ai codebuddy-cn codebuddy-intl; doWORKDADDY_BUILD_PROFILE="$profile" bash "$0"doneexit 0ficase "$PROFILE" inworkbuddy-ai) PACKAGE_NAME="WorkDaddy AI"; OUT="release/windows/WorkDaddy-AI-${VERSION}-win64.zip" ;;- *) PROFILE="workbuddy-cn"; PACKAGE_NAME="WorkDaddy"; OUT="release/windows/WorkDaddy-${VERSION}-win64.zip" ;;+ codebuddy-cn) PACKAGE_NAME="CodeDaddy CN"; OUT="release/windows/CodeDaddy-CN-${VERSION}-win64.zip" ;;+ codebuddy-intl) PACKAGE_NAME="CodeDaddy"; OUT="release/windows/CodeDaddy-${VERSION}-win64.zip" ;;+ workbuddy-cn) PACKAGE_NAME="WorkDaddy"; OUT="release/windows/WorkDaddy-${VERSION}-win64.zip" ;;+ *) echo "未知 profile: $PROFILE" >&2; exit 2 ;;esacecho "==> profile: ${PROFILE}"@@ -358,6 +361,27 @@ patch('scripts/verify-win.cmd', [print('==> 品牌化替换完成(Start/Stop/install-win/launcher/verify-win + base64 提示)')PYfi+# CodeDaddy keeps stable internal launcher filenames; visible labels follow the package.+if [[ "$PROFILE" == codebuddy-* ]]; then+ "$PYTHON_BIN" - "$(winpath "$STAGE")" "$PACKAGE_NAME" <<'PYCODE'+from pathlib import Path+import sys+stage, brand = Path(sys.argv[1]), sys.argv[2]+client = 'CodeBuddy CN' if brand == 'CodeDaddy CN' else 'CodeBuddy'+for name in ['Start-WorkDaddy.cmd', 'Stop-WorkDaddy.cmd', 'scripts/launcher.cmd', 'scripts/verify-win.cmd']:+ file = stage / name+ if not file.exists(): continue+ raw = file.read_bytes()+ text = raw.decode('utf-8-sig')+ for old, new in [('WorkDaddy launcher', brand + ' launcher'), ('WorkDaddy stopped.', brand + ' stopped.'),+ ('WorkDaddy lifecycle', brand + ' lifecycle'), ('WorkDaddy Windows', brand + ' Windows'),+ ('WorkDaddy 安装包', brand + ' 安装包'), ('WorkDaddy is ready', brand + ' is ready'),+ ('WorkDaddy Node runtime', brand + ' Node runtime'), ('Close WorkBuddy', 'Close ' + client),+ ('Desktop\\WorkDaddy.lnk', 'Desktop\\' + brand + '.lnk')]:+ text = text.replace(old, new)+ file.write_bytes((b'\xef\xbb\xbf' if raw.startswith(b'\xef\xbb\xbf') else b'') + text.encode('utf-8'))+PYCODE+fi# 3.3.5) 非 ASCII 文件名守护:Windows 安装包路径必须保持 ASCII。# macOS 自带 Info-ZIP 会使用 UTF-8 条目写入;安装/更新脚本本身仍全部使用 ASCII 路径。NON_ASCII_PATHS="$(find "$STAGE" -not -path '*/node_modules/*' 2>/dev/null | LC_ALL=C grep '[^ -~]' || true)"diff --git a/scripts/cdp-targets.js b/scripts/cdp-targets.jsindex 8904ad1..332b746 100644--- a/scripts/cdp-targets.js+++ b/scripts/cdp-targets.js@@ -127,7 +127,12 @@ function isTargetForProfile(target, profile) {* window shares the same app URL and must not become the CDP session target.*/function selectPageTarget(targets, profile) {- const candidates = (Array.isArray(targets) ? targets : []).filter((target) => isTargetForProfile(target, profile));+ const candidates = (Array.isArray(targets) ? targets : []).filter((target) => {+ if (!isTargetForProfile(target, profile)) return false;+ // CodeBuddy's standalone Agents window is distinct from the IDE and its+ // extension webviews. Wait for that window instead of attaching to the IDE.+ return profile.kind !== 'codebuddy' || /\/agentManager\.html(?:[?#]|$)/i.test(String(target.url || ''));+ });const score = (target) => {const url = String(target && target.url || '');if (/windowAppId=settings|windowKind=settings|windowPreset=utility/i.test(url)) return 20;diff --git a/scripts/codebuddy-files.js b/scripts/codebuddy-files.jsnew file mode 100644index 0000000..c012d92--- /dev/null+++ b/scripts/codebuddy-files.js@@ -0,0 +1,278 @@+'use strict';+const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');+const hash = value => crypto.createHash('sha256').update(value).digest('hex');+const identityKeys = new Set(['conversationId','sessionId','conversation_id','session_id','ownerConversationId']);+const validId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,200}$/.test(value);++// CodeBuddy's extension owns per-account history trees. Expose their files in+// the existing archive/snapshot vocabulary so panel and sync transactions stay+// shared; never synthesize an empty WorkBuddy transcript for a native session.+function createCodeBuddyFiles({root, sync}) {+ const rows = new Map();+ function parseIndex(text) {+ try { return JSON.parse(text); } catch (_) { throw Error('CodeBuddy 会话索引格式不兼容'); }+ }+ function register(row) {+ if (!row || !validId(row.id) || !validId(row.user_id) || typeof row.cwd !== 'string' || !path.isAbsolute(row.cwd)) throw Error('CodeBuddy 会话归属或工作区无效');+ rows.set(row.id, row);+ }+ function bases(id) {+ const row=rows.get(id);+ if(!row) throw Error('未找到 CodeBuddy 会话归属');+ const workspace=crypto.createHash('md5').update(path.normalize(row.cwd)).digest('hex');+ const base=[row.user_id,'CodeBuddyIDE',row.user_id];+ return [+ ['workspace/sessions', [...base,'history',workspace,id].join('/')],+ ['tasks', [...base,'plan-task',workspace,id].join('/')],+ ['file-history', [...base,'check-point',workspace,id].join('/')],+ ['codebuddy-file-tree', [...base,'file-tree',workspace,id].join('/')],+ ];+ }+ function safe(relative) {+ const parts=relative.split('/');+ if(parts.some(p=>!p || p==='.' || p==='..' || /[\\\x00]/.test(p))) throw Error('无效的会话文件路径');+ let target=path.resolve(root);+ for(const part of parts) {+ target=path.join(target,part);+ try {if(fs.lstatSync(target).isSymbolicLink()) throw Error('会话目录包含符号链接');}+ catch(e){if(e.code!=='ENOENT')throw e;}+ }+ return target;+ }+ function relativeFor(key,id) {+ for(const [prefix,relative] of bases(id)) {+ const lead=prefix+'/__session__/';+ if(key.startsWith(lead)) return relative+'/'+key.slice(lead.length);+ }+ throw Error('CodeBuddy 会话归档格式不兼容');+ }+ function normalize(value,aliases) {+ if(Array.isArray(value)) return value.map(v=>normalize(v,aliases));+ if(value && typeof value==='object') return Object.fromEntries(Object.keys(value).sort().map(k=>[k,identityKeys.has(k)&&aliases.includes(value[k])?'__session__':normalize(value[k],aliases)]));+ return value;+ }+ function snapshot(_root,id,aliases=[]) {+ const known=Array.from(new Set([id,...aliases])), files=new Map();let totalBytes=0;+ function visit(relative,key) {+ const file=safe(relative);let stat;+ try{stat=fs.lstatSync(file);}catch(e){if(e.code==='ENOENT')return;throw e;}+ if(stat.isDirectory()) {for(const name of fs.readdirSync(file).sort()) {+ if(name.startsWith('.') || /\.(?:lock|tmp|bak)$/.test(name))continue;+ visit(relative+'/'+name,key+'/'+name);+ }return;}+ if(!stat.isFile())throw Error('不支持的会话文件类型');+ const bytes=fs.readFileSync(file),after=fs.statSync(file);+ if(bytes.length!==stat.size || stat.mtimeMs!==after.mtimeMs || stat.ctimeMs!==after.ctimeMs)throw Error('会话文件正在变化');+ let semantic=hash(bytes);+ if(key.startsWith('workspace/sessions/') && file.endsWith('.json')) {+ let json;try{json=JSON.parse(bytes);}catch{throw Error('CodeBuddy 会话文件未写完或已损坏');}+ semantic=hash(JSON.stringify(normalize(json,known)));+ }+ files.set(key,{relative,sourcePath:file,bytes,hash:hash(bytes),semantic,size:stat.size,mode:stat.mode&0o777,mtimeMs:stat.mtimeMs,ctimeMs:stat.ctimeMs});totalBytes+=stat.size;+ }+ for(const [prefix,relative] of bases(id)) visit(relative,prefix+'/__session__');+ const indexKey='workspace/sessions/__session__/index.json',indexFile=files.get(indexKey);+ let records=null;+ if(indexFile) {+ const index=JSON.parse(indexFile.bytes);+ if(!Array.isArray(index.messages))throw Error('CodeBuddy 消息索引格式不兼容');+ records=index.messages.map(entry=>{+ if(!validId(entry.id))throw Error('CodeBuddy 消息标识无效');+ const file=files.get('workspace/sessions/__session__/messages/'+entry.id+'.json');+ if(!file)throw Error('CodeBuddy 会话缺少消息文件');+ return file.semantic;+ });+ if(!records.length)throw Error('会话消息文件没有消息,未同步');+ } else if(files.size) throw Error('CodeBuddy 会话缺少消息索引');+ const result={root:path.resolve(root),id,aliases:known,files,totalBytes,records,transcriptKey:indexFile?indexKey:null};+ result.reread=()=>snapshot(null,id,known);+ result.resolveRelative=key=>relativeFor(key,id);+ result.rewriteBytes=(key,file,target)=>{+ if(!key.startsWith('workspace/sessions/') || !key.endsWith('.json')) return null;+ const rewrite=value=>{+ if(Array.isArray(value))return value.map(rewrite);+ if(value && typeof value==='object')return Object.fromEntries(Object.entries(value).map(([k,v])=>[k,identityKeys.has(k)&&known.includes(v)?target.id:rewrite(v)]));+ return value;+ };+ return Buffer.from(JSON.stringify(rewrite(JSON.parse(file.bytes))));+ };+ return result;+ }+ async function fileMarkers(id) {+ const markers=[];let totalBytes=0;+ async function visit(relative) {+ const file=safe(relative);let stat;+ try {stat=await fs.promises.lstat(file);}catch(error){if(error.code==='ENOENT')return;throw error;}+ if(stat.isSymbolicLink())throw Error('会话目录包含符号链接');+ markers.push([relative,stat.size,stat.mtimeMs,stat.ctimeMs]);+ if(stat.isDirectory()) {+ for(const name of (await fs.promises.readdir(file)).sort()) {+ if(name.startsWith('.') || /\.(?:lock|tmp|bak)$/.test(name))continue;+ await visit(relative+'/'+name);+ }+ } else if(stat.isFile())totalBytes+=stat.size;+ else throw Error('不支持的会话文件类型');+ }+ for(const [,relative] of bases(id))await visit(relative);+ return {totalBytes,fingerprint:hash(JSON.stringify(markers))};+ }+ function tokenOptions(ids) {+ const owners=new Map();+ for(const id of ids) {+ if(!rows.has(id))continue;+ const file=safe(bases(id)[0][1]+'/index.json');+ if(fs.existsSync(file))owners.set(file,id);+ }+ return {files:[...owners.keys()],source:'local-codebuddy-requests',+ sourceSession:file=>owners.get(file),+ readRecords:text=>{const index=parseIndex(text);return Array.isArray(index.requests)?index.requests:[];}};+ }+ function collect(id) {+ return [...snapshot(null,id).files].map(([key,file])=>({path:key.replace('/__session__/','/'+id+'/'),source:file.sourcePath,size:file.size}));+ }+ async function restore(archive,newId,staged) {+ const oldId=String(archive.record?.id || '');if(!validId(oldId))throw Error('会话归档 ID 无效');+ const targets=new Set();const written=[];+ try {+ for(const entry of archive.files || []) {+ if(typeof entry.path!=='string')throw Error('会话归档路径无效');+ const key=entry.path.replace('/'+oldId+'/','/__session__/');+ const target=safe(relativeFor(key,newId));+ if(targets.has(target))throw Error('会话归档路径重复');targets.add(target);+ fs.mkdirSync(path.dirname(target),{recursive:true,mode:0o700});+ if(staged)await fs.promises.copyFile(entry.source,target,fs.constants.COPYFILE_EXCL);+ else {+ if(typeof entry.data!=='string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(entry.data))throw Error('会话归档数据无效');+ await fs.promises.writeFile(target,Buffer.from(entry.data,'base64'),{flag:'wx',mode:0o600});+ }+ written.push(target);await fs.promises.chmod(target,0o600);+ if(key.startsWith('workspace/sessions/') && key.endsWith('.json')) {+ const rewrite=value=>{+ if(Array.isArray(value))return value.map(rewrite);+ if(value && typeof value==='object')return Object.fromEntries(Object.entries(value).map(([k,v])=>[k,identityKeys.has(k)&&v===oldId?newId:rewrite(v)]));+ return value;+ };+ let json;try{json=JSON.parse(await fs.promises.readFile(target,'utf8'));}catch{throw Error('CodeBuddy 会话归档格式不兼容');}+ await fs.promises.writeFile(target,JSON.stringify(rewrite(json)),{mode:0o600});+ }+ }+ snapshot(null,newId);+ }catch(e){for(const file of written)await fs.promises.unlink(file).catch(()=>{});throw e;}+ }+ async function publish(id,sourceId,metadata) {+ const row=rows.get(id);if(!row)throw Error('未找到会话归属');+ const indexFile=safe(path.posix.dirname(bases(id)[0][1])+'/index.json');+ fs.mkdirSync(path.dirname(indexFile),{recursive:true,mode:0o700});+ // Match the official proper-lockfile directory lock; never replace a+ // workspace index while its HistoryManager is updating it.+ const lock=indexFile+'.lock';+ try{fs.mkdirSync(lock,{mode:0o700});}catch(e){if(e.code==='EEXIST')throw Error('工作区会话索引正在更新,请稍后重试');throw e;}+ let created;+ try {+ let index={conversations:[],current:''};+ if(fs.existsSync(indexFile)) index=parseIndex(fs.readFileSync(indexFile,'utf8'));+ if(!Array.isArray(index.conversations))throw Error('工作区会话索引格式不兼容');+ if(index.conversations.some(c=>c.id===id))return async()=>{};+ let original=metadata;+ if(!original && sourceId && rows.has(sourceId)) {+ const sourceIndex=safe(path.posix.dirname(bases(sourceId)[0][1])+'/index.json');+ if(fs.existsSync(sourceIndex)) original=parseIndex(fs.readFileSync(sourceIndex,'utf8')).conversations?.find(c=>c.id===sourceId);+ }+ const now=new Date().toISOString();+ created={...original,id,type:original?.type || 'craft',name:row.custom_title || row.title || original?.name || '',createdAt:original?.createdAt || now,lastMessageAt:original?.lastMessageAt || now,originalId:id};+ index.conversations.push(created);+ const temp=indexFile+'.codedaddy-'+crypto.randomUUID();+ try{fs.writeFileSync(temp,JSON.stringify(index),{flag:'wx',mode:0o600});fs.renameSync(temp,indexFile);}finally{if(fs.existsSync(temp))fs.unlinkSync(temp);}+ }finally{fs.rmdirSync(lock);}+ return async()=>{+ fs.mkdirSync(lock,{mode:0o700});+ try{const index=parseIndex(fs.readFileSync(indexFile,'utf8'));const i=index.conversations.findIndex(c=>c.id===id && JSON.stringify(c)===JSON.stringify(created));+ if(i>=0){index.conversations.splice(i,1);const temp=indexFile+'.codedaddy-'+crypto.randomUUID();fs.writeFileSync(temp,JSON.stringify(index),{flag:'wx',mode:0o600});fs.renameSync(temp,indexFile);}+ }finally{fs.rmdirSync(lock);}+ };+ }+ function removeIndex(id) {+ const indexFile=safe(path.posix.dirname(bases(id)[0][1])+'/index.json');+ if(!fs.existsSync(indexFile))return ()=>{};+ const lock=indexFile+'.lock';fs.mkdirSync(lock,{mode:0o700});+ let before,after;+ try {+ before=fs.readFileSync(indexFile,'utf8');const index=parseIndex(before);+ if(!Array.isArray(index.conversations))throw Error('工作区会话索引格式不兼容');+ index.conversations=index.conversations.filter(c=>c.id!==id);+ if(index.current===id)index.current='';+ after=JSON.stringify(index);const temp=indexFile+'.codedaddy-'+crypto.randomUUID();+ fs.writeFileSync(temp,after,{flag:'wx',mode:0o600});fs.renameSync(temp,indexFile);+ } finally {fs.rmdirSync(lock);}+ return ()=>{+ fs.mkdirSync(lock,{mode:0o700});+ try {+ if(fs.readFileSync(indexFile,'utf8')!==after)throw Error('会话索引已变化,恢复未确认');+ const temp=indexFile+'.codedaddy-'+crypto.randomUUID();fs.writeFileSync(temp,before,{flag:'wx',mode:0o600});fs.renameSync(temp,indexFile);+ }finally{fs.rmdirSync(lock);}+ };+ }+ async function commit(changes,write) {+ const undo=[];+ try {+ for(const change of changes) {+ if(!change.before || !change.after || change.before.userId===change.after.userId)continue;+ const before={...change.before,id:change.id,user_id:change.before.userId,cwd:change.before.cwd};+ const after={...change.after,id:change.id,user_id:change.after.userId,cwd:change.after.cwd};+ register(before);const sourceBases=bases(change.id);+ const sourceIndex=safe(path.posix.dirname(sourceBases[0][1])+'/index.json');+ let metadata;+ if(fs.existsSync(sourceIndex))metadata=parseIndex(fs.readFileSync(sourceIndex,'utf8')).conversations?.find(c=>c.id===change.id);+ const restoreIndex=removeIndex(change.id);undo.push(restoreIndex);+ register(after);undo.push(()=>register(before));const targets=bases(change.id);+ for(let i=0;i<sourceBases.length;i++) {+ const source=safe(sourceBases[i][1]),target=safe(targets[i][1]);+ if(!fs.existsSync(source))continue;+ if(fs.existsSync(target))throw Error('目标账号已有同名会话文件,未覆盖');+ fs.mkdirSync(path.dirname(target),{recursive:true,mode:0o700});+ fs.renameSync(source,target);undo.push(()=>fs.renameSync(target,source));+ }+ undo.push(await publish(change.id,null,metadata));+ }+ return await write();+ } catch(error) {+ for(const restore of undo.reverse())await restore();+ throw error;+ }+ }+ async function deleteSessions(ids,write) {+ const undo=[],staged=[];+ try {+ for(const id of ids) {+ undo.push(removeIndex(id));+ for(const [,relative] of bases(id)) {+ const original=safe(relative);+ if(!fs.existsSync(original))continue;+ const temporary=original+'.codedaddy-delete-'+crypto.randomUUID();+ fs.renameSync(original,temporary);staged.push(temporary);+ undo.push(()=>fs.renameSync(temporary,original));+ }+ }+ await write();+ } catch(error) {+ let failed=false;+ for(const restore of undo.reverse()) {try {await restore();}catch(_){failed=true;}}+ if(failed)throw Error('会话删除失败,文件恢复未确认');+ throw error;+ }+ // Metadata has committed. Cleanup failure must not roll back only the files.+ for(const file of staged)await fs.promises.rm(file,{recursive:true,force:true}).catch(()=>{});+ return staged.length;+ }+ function remove(id) {removeIndex(id);let count=0;for(const [,relative] of bases(id)){const file=safe(relative);if(fs.existsSync(file)){fs.rmSync(file,{recursive:true});count++;}}return count;}+ return {register,collect,tokenOptions,restore,remove,snapshot,publish,commit,deleteSessions,+ sync:{...sync,readSnapshot:snapshot,readSnapshotAsync:async(...args)=>snapshot(...args),+ readSessionSizes:async(_root,ids)=>{const result=new Map();for(const id of ids){try{result.set(id,(await fileMarkers(id)).totalBytes);}catch{result.set(id,null);}}return result;},+ readSessionFingerprintAsync:async(_root,id)=>(await fileMarkers(id)).fingerprint,+ readSessionQuickFingerprintAsync:async(_root,id)=>(await fileMarkers(id)).fingerprint,+ },+ };+}+module.exports={createCodeBuddyFiles};diff --git a/scripts/codebuddy-native.js b/scripts/codebuddy-native.jsnew file mode 100644index 0000000..bb8d85f--- /dev/null+++ b/scripts/codebuddy-native.js@@ -0,0 +1,247 @@+'use strict';+const path = require('node:path');+const fs = require('node:fs');+const {isCodeBuddyBinary} = require('./profiles');++// Run on the official authentication service. Persist using Electron's own+// encryption service before publishing to windows; never patch app.asar or+// pretend that renderer-only state changes switch the account.+async function replaceNativeSession(session) {+ await this.initialized;+ if (this.refreshInFlight || this.loginInProgress || this.logoutInProgress) throw new Error('登录状态正在更新,请稍后重试');+ if (session !== null && (!session || !session.account || !session.account.uid || !session.auth || typeof session.auth.accessToken !== 'string' || !session.auth.accessToken)) throw new Error('账号备份无效');+ const previous = this.currentSession;+ // Reserve the official guards before the first await. A refresh or logout+ // must not overwrite this transaction while encrypted storage is pending.+ let unlock;+ this.loginInProgress = new Promise(resolve => { unlock = resolve; });+ this.refreshInFlight = true;+ this.logoutInProgress = true;+ if (this.refreshTimer) { clearTimeout(this.refreshTimer); this.refreshTimer = undefined; }+ const persist = async value => {+ if (value) await this.storeSession(value);+ else await this.storageService.remove(this.getStorageKey(), -1);+ };+ let succeeded = false;+ try {+ await persist(session);+ this.currentSession = session || undefined;+ this.refreshFailureRetryCount = 0;+ this._onDidChangeSession.fire(this.currentSession);+ this.scheduleRefresh();+ succeeded = true;+ return {uid:session ? String(session.account.uid) : null};+ } catch (_) {+ try {+ await persist(previous);+ this.currentSession = previous;+ this._onDidChangeSession.fire(previous);+ this.scheduleRefresh();+ } catch (_) {+ throw new Error('账号切换失败,原登录态恢复未确认');+ }+ throw new Error('账号切换失败,已恢复原登录态');+ } finally {+ this.refreshInFlight = false;+ this.logoutInProgress = false;+ this.loginInProgress = undefined;+ unlock(succeeded);+ }+}++async function findNativeService(send, channel, predicate) {+ const root = await send('Runtime.evaluate', {+ expression:"process.getBuiltinModule('module').createRequire(process.execPath)('electron').ipcMain._invokeHandlers.get(" + JSON.stringify(channel) + ")",+ objectGroup:'codedaddy-auth',+ });+ if (root.exceptionDetails || root.result?.type !== 'function') throw new Error('当前 CodeBuddy 版本未找到原生认证入口');+ const seen = new Set();+ async function visit(objectId, depth) {+ if (!objectId || depth > 4 || seen.has(objectId) || seen.size > 24) return null;+ seen.add(objectId);+ const props = await send('Runtime.getProperties', {objectId,ownProperties:true});+ const scopes = props.internalProperties?.find(p=>p.name==='[[Scopes]]');+ if (!scopes?.value?.objectId) return null;+ const list = await send('Runtime.getProperties',{objectId:scopes.value.objectId,ownProperties:true});+ for (const scope of list.result.filter(p=>/^\d+$/.test(p.name) && /Closure/.test(p.value?.description || ''))) {+ const members = await send('Runtime.getProperties',{objectId:scope.value.objectId,ownProperties:true});+ // Do not scan the whole main-process module, global object or heap.+ if (members.result.length > 24) continue;+ for (const member of members.result.filter(p=>p.value?.type==='object' && p.value.objectId)) {+ const check = await send('Runtime.callFunctionOn',{objectId:member.value.objectId,+ functionDeclaration:predicate.toString(),returnByValue:true});+ if (check.result?.value===true) return member.value.objectId;+ }+ for (const member of members.result.filter(p=>p.value?.type==='function')) {+ const found=await visit(member.value.objectId,depth+1); if(found)return found;+ }+ }+ return null;+ }+ const objectId=await visit(root.result.objectId,0);+ if(!objectId) throw new Error('当前 CodeBuddy 版本的认证服务结构不兼容');+ return objectId;+}++function findAuthService(send) {+ return findNativeService(send, 'vscode:genie:auth:getSession', function () {+ return typeof this.getCurrentSessionAsync === 'function' && typeof this.storeSession === 'function' &&+ typeof this.scheduleRefresh === 'function' && typeof this._onDidChangeSession?.fire === 'function';+ });+}++// The public upsert drops metadata and cannot restore tombstones. Execute the+// shared SQL diff through the owning main service, with a revision check, its+// write queue, encrypted-client-independent storage and official notifications.+// This also keeps pending sessions and v2 subscribers in sync (no DB file edits).+async function writeNativeSessions(changes) {+ return this.enqueueV2Write(async () => {+ if (!this._db || !(this._sessions instanceof Map)) throw new Error('会话存储尚未就绪');+ const updates = new Map();+ for (const change of changes) {+ const current = this._sessions.get(change.id);+ if (current && ['Working','Planning'].includes(current.status)) throw new Error('会话正在运行,请完成后重试');+ if (JSON.stringify(current || null) !== JSON.stringify(change.before || null)) throw new Error('会话已变化,请刷新后重试');+ const value = change.after ? {...current, ...change.after} : {...current, deletedAt:Date.now(), updatedAt:Date.now()};+ if (change.after && change.after.deletedAt == null) delete value.deletedAt;+ value.conversationId = change.id;+ if (typeof this.nextV2Revision === 'function') value.revision = this.nextV2Revision();+ updates.set('session:' + change.id, JSON.stringify(value));+ }+ await this._db.updateItems({insert:updates});+ for (const change of changes) {+ const value = JSON.parse(updates.get('session:' + change.id));+ this._sessions.set(change.id,value);+ this._newSessions.delete(change.id);+ // Persisted data is authoritative. A closed window must not make callers+ // roll back files after the metadata transaction has already committed.+ try { if (typeof this.broadcastV2 === 'function') this.broadcastV2(value.deletedAt == null ? 'upsert' : 'delete', value, 'codedaddy', value.revision); } catch (_) {}+ try { this.notifyAgentManager(value.deletedAt == null ? 'upsert' : 'delete', value.deletedAt == null ? value : {conversationId:change.id}); } catch (_) {}+ }+ return {changed:changes.length};+ });+}++async function findSessionService(send, onPause) {+ const handler=await send('Runtime.evaluate',{expression:"process.getBuiltinModule('module').createRequire(process.execPath)('electron').ipcMain._invokeHandlers.get('codebuddy:getSession')"});+ if(handler.result?.type !== 'function') throw new Error('未找到会话服务入口');+ const props=await send('Runtime.getProperties',{objectId:handler.result.objectId,ownProperties:true});+ const scopes=props.internalProperties?.find(p=>p.name==='[[Scopes]]');+ if(!scopes?.value?.objectId) throw new Error('会话服务入口不兼容');+ const list=await send('Runtime.getProperties',{objectId:scopes.value.objectId,ownProperties:true});+ let callback;+ for(const scope of list.result.filter(p=>/Closure/.test(p.value?.description || ''))) {+ const members=await send('Runtime.getProperties',{objectId:scope.value.objectId,ownProperties:true});+ if(members.result.length > 8) continue;+ const functions=members.result.filter(p=>p.value?.type==='function');+ if(functions.length===1) {callback=functions[0].value.objectId;break;}+ }+ if(!callback) throw new Error('会话服务回调不兼容');+ // V8 omits lexical `this` from arrow-function scopes. Briefly stop only our+ // harmless getSession call to retain that receiver, then resume immediately.+ // Never pause arbitrary application code, scan the heap or patch a prototype.+ let breakpoint, timer;+ await send('Debugger.enable');+ try {+ breakpoint=await send('Debugger.setBreakpointOnFunctionCall',{objectId:callback});+ const paused=new Promise((resolve,reject)=>{+ onPause(event=>{if(event.hitBreakpoints?.includes(breakpoint.breakpointId))resolve(event);});+ timer=setTimeout(()=>{send('Debugger.resume').catch(()=>{});reject(new Error('会话服务发现超时'));},1000);+ });+ const invocation=send('Runtime.callFunctionOn',{objectId:callback,functionDeclaration:"function(){return this(null,'__codedaddy_readonly_probe__');}",awaitPromise:true});+ invocation.catch(()=>{}); // Timeout cleanup may run before the invocation settles.+ const event=await paused;+ const owner=await send('Debugger.evaluateOnCallFrame',{callFrameId:event.callFrames[0].callFrameId,expression:'this',objectGroup:'codedaddy-sessions'});+ await send('Debugger.resume');+ clearTimeout(timer);+ await invocation;+ const objectId=owner.result?.objectId;+ if(!objectId) throw new Error('会话服务对象不可用');+ const check=await send('Runtime.callFunctionOn',{objectId,functionDeclaration:"function(){return this._sessions instanceof Map && this._newSessions instanceof Set && typeof this.enqueueV2Write==='function' && typeof this.notifyAgentManager==='function';}",returnByValue:true});+ if(check.result?.value!==true) throw new Error('会话服务版本不兼容');+ return objectId;+ } finally {+ clearTimeout(timer);onPause(null);+ await send('Debugger.resume').catch(()=>{});+ if(breakpoint?.breakpointId) await send('Debugger.removeBreakpoint',{breakpointId:breakpoint.breakpointId}).catch(()=>{});+ await send('Debugger.disable').catch(()=>{});+ }+}++function createCodeBuddyNative({profile,WebSocketCtor}) {+ let ws, service, sessionService, sessionConnecting, connecting, pauseListener, serial=0;+ const pending=new Map();+ function send(method,params={}) {+ return new Promise((resolve,reject)=>{+ if(!ws || ws.readyState!==1) return reject(new Error('CodeBuddy 主进程尚未连接'));+ const id=++serial;+ const timer=setTimeout(()=>{pending.delete(id);reject(new Error('CodeBuddy 主进程请求超时'));},15000);+ pending.set(id,{resolve,reject,timer});+ ws.send(JSON.stringify({id,method,params}));+ });+ }+ function close() {+ const old=ws; ws=null; service=null; sessionService=null;+ for(const p of pending.values()){clearTimeout(p.timer);p.reject(new Error('CodeBuddy 主进程连接已关闭'));}+ pending.clear(); if(old) old.close();+ }+ async function connect() {+ if(ws?.readyState===1 && service) return;+ if(connecting) return connecting;+ connecting=(async()=>{+ const list=await (await fetch('http://127.0.0.1:'+profile.nativeDebugPort+'/json/list',{signal:AbortSignal.timeout(3000)})).json();+ const target=list.find(p=>p.type==='node');+ if(!target) throw new Error('未发现 CodeBuddy 主进程调试入口');+ const url=new URL(target.webSocketDebuggerUrl);+ if(url.protocol!=='ws:' || url.hostname!=='127.0.0.1' || Number(url.port)!==profile.nativeDebugPort) throw new Error('主进程调试地址无效');+ ws=new WebSocketCtor(url.href);+ await new Promise((resolve,reject)=>{+ const timer=setTimeout(()=>reject(new Error('主进程连接超时')),3000);+ ws.onopen=()=>{clearTimeout(timer);resolve();};+ ws.onerror=()=>{clearTimeout(timer);reject(new Error('主进程连接失败'));};+ });+ const socket = ws;+ ws.onclose=()=>{if(ws !== socket)return; ws=null; service=null; sessionService=null; for(const p of pending.values()){clearTimeout(p.timer);p.reject(new Error('CodeBuddy 已关闭'));}pending.clear();};+ ws.onmessage=event=>{+ let msg; try{msg=JSON.parse(event.data);}catch(_){return;}+ if(msg.method==='Debugger.paused' && pauseListener) pauseListener(msg.params);+ const p=pending.get(msg.id);if(!p)return;+ pending.delete(msg.id);clearTimeout(p.timer);+ msg.error?p.reject(new Error('CodeBuddy 调试请求失败')):p.resolve(msg.result);+ };+ const identity=await send('Runtime.evaluate',{expression:"(()=>{const e=process.getBuiltinModule('module').createRequire(process.execPath)('electron');return {exe:process.execPath,userData:e.app.getPath('userData')};})()",returnByValue:true});+ const found=identity.result?.value;+ const normalize=p=>{+ let resolved=path.resolve(p || '');+ try { resolved=fs.realpathSync(resolved); } catch (_) {}+ return process.platform==='win32' ? resolved.toLowerCase() : resolved;+ };+ const expectedExe=process.platform==='darwin'?path.join(profile.appPath,'Contents/MacOS/Electron'):profile.appPath;+ if(!found || !(process.platform==='win32' ? isCodeBuddyBinary(found.exe,profile.id) : normalize(found.exe)===normalize(expectedExe)) || normalize(found.userData)!==normalize(profile.userDataRoot)) throw new Error('主进程不属于当前 CodeBuddy 安装或用户目录');+ service=await findAuthService(send);+ })().catch(error=>{close();throw new Error('无法连接 CodeBuddy 认证服务:'+error.message);}).finally(()=>{connecting=null;});+ return connecting;+ }+ async function call(fn,args=[],kind='auth') {+ await connect();+ if (kind === 'sessions' && !sessionService) {+ if(!sessionConnecting) sessionConnecting=findSessionService(send, listener=>{pauseListener=listener;})+ .then(id=>{sessionService=id;}).finally(()=>{sessionConnecting=null;});+ await sessionConnecting;+ }+ const result=await send('Runtime.callFunctionOn',{objectId:kind==='sessions'?sessionService:service,functionDeclaration:fn.toString(),arguments:args.map(value=>({value})),awaitPromise:true,returnByValue:true});+ // Never include exception descriptions: official errors can embed auth data.+ if(result.exceptionDetails) throw new Error('CodeBuddy 认证操作失败,原生服务未确认成功');+ return result.result?.value;+ }+ return {+ connect,close,+ sessionItems:()=>call(function(){return Array.from(this._sessions, ([id,value])=>({key:'session:'+id,value:JSON.stringify(value)}));},[],'sessions'),+ writeSessions:changes=>call(writeNativeSessions,[changes],'sessions'),+ read:()=>call(async function(){return (await this.getCurrentSessionAsync()) || null;}),+ replace:session=>call(replaceNativeSession,[session]),+ // Fake logout preserves the backed-up token; official logout may revoke it.+ logout:async()=>{await call(replaceNativeSession,[null]);return true;},+ };+}+module.exports={createCodeBuddyNative,findAuthService,replaceNativeSession,writeNativeSessions};diff --git a/scripts/codebuddy-session-store.js b/scripts/codebuddy-session-store.jsnew file mode 100644index 0000000..0a033e3--- /dev/null+++ b/scripts/codebuddy-session-store.js@@ -0,0 +1,80 @@+'use strict';++// Present the existing sessions contract to shared handlers. SQL runs against+// an in-memory view, never against CodeBuddy's incompatible ItemTable schema.+// Writes go through its main-process service so the official cache/UI update.+const fields = {+ id:'conversationId',cwd:'cwd',user_id:'userId',title:'title',custom_title:'customTitle',status:'status',+ created_at:'createdAt',updated_at:'updatedAt',last_activity_at:'updatedAt',deleted_at:'deletedAt',+ is_playground:'isPlayground',source_mode:'sourceMode',is_background_automation:'isBackgroundAutomation',+ mode:'mode',model:'model',expert_id:'expertId',expert_locale:'expertLocale',expert_runtime_identity:'expertRuntimeIdentity',+ expert_marketplace:'expertMarketplace',permission_mode:'permissionMode',use_sandbox_cli:'useSandboxCli',project_id:'projectId',+};+const numeric = new Set(['created_at','updated_at','last_activity_at','deleted_at','is_playground','is_background_automation','use_sandbox_cli']);+function sessionRow(value) {+ const row = {};+ for (const [key, source] of Object.entries(fields)) {+ const cell = value[source];+ row[key] = cell == null ? (key === 'deleted_at' || numeric.has(key) ? null : '') :+ numeric.has(key) ? Number(cell) : String(cell);+ }+ return row;+}+function createCodeBuddySessionStore({readItems, writeChanges}) {+ async function view() {+ const { DatabaseSync } = require('node:sqlite');+ const db = new DatabaseSync(':memory:');+ try {+ db.exec('CREATE TABLE sessions (' + Object.keys(fields).map(key => key + (numeric.has(key) ? ' NUMERIC' : ' TEXT') + (key==='id' ? ' PRIMARY KEY' : '')).join(',') + ')');+ const insert = db.prepare('INSERT INTO sessions VALUES (' + Object.keys(fields).map(() => '?').join(',') + ')');+ const originals = new Map();+ for (const item of await readItems()) {+ let value;+ try { value = JSON.parse(item.value); } catch (_) { continue; }+ if (!value || typeof value !== 'object') continue;+ value.conversationId = value.conversationId || String(item.key).slice('session:'.length);+ originals.set(value.conversationId, value);+ insert.run(...Object.values(sessionRow(value)));+ }+ db.originals = originals;+ return db;+ } catch (error) { db.close(); throw error; }+ }+ let writes = Promise.resolve();+ return {+ async all(sql, params=[]) {+ await writes.catch(() => {});+ const db=await view();+ try { return db.prepare(sql).all(...params).map(row=>({...row})); }+ finally { db.close(); }+ },+ run(sql, params=[]) {+ const work = writes.catch(() => {}).then(async () => {+ const db=await view();+ try {+ const before=new Map(db.prepare('SELECT * FROM sessions').all().map(row=>[row.id,row]));+ const result=db.prepare(sql).run(...params);+ const after=new Map(db.prepare('SELECT * FROM sessions').all().map(row=>[row.id,row]));+ const changes=[];+ for (const [id, row] of after) {+ const old=before.get(id);+ if (old && JSON.stringify(old)===JSON.stringify(row)) continue;+ const update={...db.originals.get(id)};+ for (const [key, target] of Object.entries(fields)) if(key!=='last_activity_at') {+ if (row[key] == null) delete update[target]; else update[target]=row[key];+ }+ changes.push({id,before:db.originals.get(id) || null,after:update});+ }+ for (const id of before.keys()) if(!after.has(id)) changes.push({id,before:db.originals.get(id),after:null});+ if(changes.length) {+ const saved=await writeChanges(changes);+ if(saved?.changed!==changes.length) throw new Error('CodeBuddy 未确认会话写入');+ }+ return result;+ } finally { db.close(); }+ });+ writes=work; return work;+ },+ };+}+module.exports={createCodeBuddySessionStore,sessionRow};diff --git a/scripts/daemon.js b/scripts/daemon.jsindex c44c9db..aebd9c5 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -28,7 +28,8 @@ const path = require('path');const os = require('os');const crypto = require('crypto');const net = require('net');-const sessionSync = require('./session-sync.js');+let sessionSync = require('./session-sync.js');+const {createCodeBuddyFiles} = require('./codebuddy-files.js');const { createAccountCreditCache } = require('./account-credit-cache.js');const { spawn, spawnSync } = require('child_process');const {@@ -156,9 +157,12 @@ const {telemetryEnvironmentOverride,} = require('./sentry-report.js');const { createUsageReporter } = require('./usage-report.js');-const { getProfile, profileDataDir, listInstalledModelSources } = require('./profiles.js');+const { getProfile, profileDataDir, listInstalledModelSources, sharedDataDir } = require('./profiles.js');const plat = require('./platform.js');const { readWorkBuddyTarget } = require('./workbuddy-target.js');+const { BINDING, createRendererApiBridge, rendererBridgeSource } = require('./renderer-api-bridge.js');+const { createCodeBuddyNative } = require('./codebuddy-native.js');+const { createCodeBuddySessionStore } = require('./codebuddy-session-store.js');const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget } = require('./cdp-targets.js');const { createSessionDb, normalizeSessionIdBatch, parameterCount } = require('./session-db.js');const { createDirtyIndex } = require('./session-dirty.js');@@ -198,6 +202,7 @@ const {isTaskCompatible,configureAutomationRuntime,installBuiltinTask,+ removeBuiltinTasks,} = require('./automation.js');const { assertAccountRequestUrl, createTaskState, cancellableWait, createRendererGate, probeSessionReceipt, receiptComplete } = require('./automation-runtime.js');@@ -216,6 +221,9 @@ const { runCompletionReport, probeAccountCompletion } = require('./completion-reconst { createPrimaryAccountStore } = require('./primary-account.js');const PROFILE = getProfile();const DATA_DIR = defaultDataDir();+const codeBuddyFiles = PROFILE.kind === 'codebuddy' ? createCodeBuddyFiles({root: PROFILE.historyRoot, sync:sessionSync}) : null;+if (codeBuddyFiles) sessionSync = codeBuddyFiles.sync;+const codeBuddyNative = PROFILE.kind === 'codebuddy' ? createCodeBuddyNative({profile: PROFILE, WebSocketCtor}) : null;const accountCreditCache = createAccountCreditCache(DATA_DIR);const thirdPartyModels = createThirdPartyImport({ targetFile: workbuddyModelsFile(), dataDir: DATA_DIR });const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.existsSync(accountBackupFile(uid)));@@ -423,12 +431,14 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 刷新结果不把解密后的 token 写回加密备份。// 1.2.188:关闭主题接管时跟随 WorkBuddy AI 的原生 agent-ui-theme,避免旧快照覆盖官方浅色/深色选择。// 1.2.189:毛玻璃底色等待移至 daemon,避免后台页面定时器节流拖延开关和壁纸加载。-const DAEMON_VERSION = '1.2.189';-const DAEMON_BUILD_ID = 'release-1.2.189-20260927-wallpaper-loading';+// 1.2.191:CodeDaddy 共用完整面板,通过本机 CDP 适配通信、原生登录态和会话缓存。+const DAEMON_VERSION = '1.2.205';+const DAEMON_BUILD_ID = 'release-1.2.205-20260929-codebuddy-cn-executable';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({- dataDir: DATA_DIR,+ // Public source metadata is shared; compatibility and installed tasks stay profile-specific.+ dataDir: sharedDataDir(),runtime: { version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform },});const automationLikes = createAutomationLikesClient({@@ -442,7 +452,7 @@ const IS_WIN = process.platform === 'win32';const IS_MAC = process.platform === 'darwin';const IS_LINUX = process.platform === 'linux';// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app-const WORKDADDY_INSTALL_NAME = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy AI' : 'WorkDaddy';+const WORKDADDY_INSTALL_NAME = PROFILE.appName || (PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy AI' : 'WorkDaddy');const sessionExportJobs = createSessionExportJobs({prepare: prepareSessionExport,directory: () => path.join(process.env.WBSWITCH_LAUNCH_HOME || os.homedir(), 'Downloads', WORKDADDY_INSTALL_NAME),@@ -507,6 +517,7 @@ function loadApiToken() {}const API_TOKEN = loadApiToken();+const handleRendererApiBinding = createRendererApiBridge({token: API_TOKEN, port: () => ACTUAL_PORT, send: cdpSend});// 遥测开关统一控制远程 Sentry 与本地脱敏渲染器诊断;每次读取都能响应关于页的即时修改。let diagnosticsState = { value: null, checkedAt: 0 };@@ -832,21 +843,14 @@ function selectUpdateAsset(source, rel) {typeof a.browser_download_url === 'string' &&a.browser_download_url.startsWith(source.downloadRoot + '/'));- const profileAsset = PROFILE.id === 'workbuddy-ai'- ? /^(?:WorkDaddy-AI-Setup-|WorkDaddy-AI-).*\.(?:exe|zip|dmg)$/i- : /^WorkDaddy-(?!AI-)(?:Setup-|).*\.(?:exe|zip|dmg)$/i;- const profileSetup = PROFILE.id === 'workbuddy-ai'- ? /^WorkDaddy-AI-Setup-\d+\.\d+\.\d+\.exe$/i- : /^WorkDaddy-Setup-\d+\.\d+\.\d+\.exe$/i;- const profileZip = PROFILE.id === 'workbuddy-ai'- ? /^WorkDaddy-AI-\d+\.\d+\.\d+-win64\.zip$/i- : /^WorkDaddy-\d+\.\d+\.\d+-win64\.zip$/i;+ const packageName = PROFILE.packageName || ({'workbuddy-cn':'WorkDaddy','workbuddy-ai':'WorkDaddy-AI','codebuddy-cn':'CodeDaddy-CN','codebuddy-intl':'CodeDaddy'})[PROFILE.id];+ if (!packageName) return null;+ const matches = (asset, suffix) => asset.name.startsWith(packageName + '-') &&+ new RegExp('^' + packageName + '-' + suffix + '$', 'i').test(asset.name);return IS_WIN- ? (assets.find((a) => profileSetup.test(a.name || '')) ||- assets.find((a) => profileZip.test(a.name || '')) ||- assets.find((a) => profileAsset.test(a.name || '') && /\.(?:exe|zip)$/i.test(a.name || '')) || null)- : (assets.find((a) => profileAsset.test(a.name || '') && /\.dmg$/i.test(a.name || '')) ||- assets.find((a) => /\.dmg$/i.test(a.name || '') && (PROFILE.id !== 'workbuddy-ai' || !/WorkDaddy-AI-/i.test(a.name || ''))) || null);+ ? (assets.find(a=>matches(a, 'Setup-\\d+\\.\\d+\\.\\d+\\.exe')) ||+ assets.find(a=>matches(a, '\\d+\\.\\d+\\.\\d+-win64\\.zip')) || null)+ : (assets.find(a=>matches(a, '\\d+\\.\\d+\\.\\d+\\.dmg')) || null);}function makeUpdateCandidate(source, rel, order) {@@ -969,7 +973,7 @@ function downloadUpdateInternal() {updateState.downloadRate = 0;updateState.etaSeconds = null;const ext = IS_WIN ? (/\.exe$/i.test(updateState.assetName || '') ? '.exe' : '.zip') : '.dmg';- const updatePrefix = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI-' : 'WorkDaddy-';+ const updatePrefix = (PROFILE.packageName || (PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI' : 'WorkDaddy')) + '-';const target = path.join(UPDATE_DIR, updatePrefix + updateState.latest + ext);const tempTarget = target + '.part.' + process.pid + '.' + crypto.randomBytes(8).toString('hex');const expectSha = expectedUpdateSha256();@@ -1187,7 +1191,7 @@ function validateUpdateArtifact(file, expectSha = null) {// 各客户端 API host 与 auth.domain 一致:国内版 www.workbuddy.cn / codebuddy.cn,// 国际版(WorkBuddy AI / CodeBuddy 国际版)为 www.workbuddy.ai / www.codebuddy.ai。// 签到、积分查询、无感登录必须打到自己对应域名的接口,不能复用国内 host。-const WB_API_ENDPOINT = PROFILE.apiHost || 'https://www.workbuddy.cn';+const WB_API_ENDPOINT = PROFILE.authApiHost || PROFILE.apiHost || 'https://www.workbuddy.cn';const WB_API_PREFIX = '/v2/plugin';const OAUTH_TIMEOUT_SECONDS = 600;const OAUTH_RESULT_RETENTION_SECONDS = 300;@@ -1378,7 +1382,7 @@ async function oauthPollOnce(loginId) {// 从 dmg 中解出 WorkDaddy.app 到 UPDATE_DIR(挂载→拷贝→卸载),返回 app 目录function extractAppFromDmg(dmgPath) {- const mountPoint = '/Volumes/WorkDaddy-update';+ const mountPoint = '/Volumes/' + WORKDADDY_INSTALL_NAME.replace(/ /g, '-') + '-update';const appPackageName = WORKDADDY_INSTALL_NAME + '.app';const appDest = path.join(UPDATE_DIR, appPackageName);return new Promise((resolve, reject) => {@@ -1465,7 +1469,7 @@ function applyUpdate() {// Windows 更新只负责打开已经过 SHA-256 校验的可见 Setup.exe。// 文件替换、WorkBuddy 退出确认和新版启动全部由 Inno Setup 接管;// daemon/watchdog 在安装器真正开始复制前保持运行,因此 UI 不会失联。- const updatePrefix = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI-' : 'WorkDaddy-';+ const updatePrefix = (PROFILE.packageName || (PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI' : 'WorkDaddy')) + '-';const packageExt = /\.exe$/i.test(updateState.assetName || '') ? '.exe' : '.zip';const srcPackage = path.join(UPDATE_DIR, updatePrefix + updateState.latest + packageExt);if (!fs.existsSync(srcPackage)) {@@ -1478,9 +1482,7 @@ function applyUpdate() {markAttemptFailure(error, 'unsupported-artifact');return Promise.reject(error);}- const expectedAsset = PROFILE.id === 'workbuddy-ai'- ? `WorkDaddy-AI-Setup-${updateState.latest}.exe`- : `WorkDaddy-Setup-${updateState.latest}.exe`;+ const expectedAsset = updatePrefix + `Setup-${updateState.latest}.exe`;if (String(updateState.assetName || '').toLowerCase() !== expectedAsset.toLowerCase()) {const error = new Error('安装包名称与目标 profile 或版本不一致');markAttemptFailure(error, 'artifact-identity');@@ -1526,7 +1528,7 @@ function applyUpdate() {return Promise.reject(error);}// 解出新应用:下载阶段只落了 .dmg,这里才把 WorkDaddy.app 从 dmg 解到 UPDATE_DIR(幂等:已解出则复用)- const updatePrefix = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI-' : 'WorkDaddy-';+ const updatePrefix = (PROFILE.packageName || (PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI' : 'WorkDaddy')) + '-';const dmgPath = path.join(UPDATE_DIR, updatePrefix + updateState.latest + '.dmg');const cachedArtifact = fs.existsSync(srcApp) ? inspectPackagedApp(srcApp) : null;const cachedMatches = Boolean(@@ -1726,11 +1728,51 @@ function releaseDaemonLock() {/* ================= 自动备份(双层触发:CDP 事件 + 文件监听兜底) ================= */let backupTimer = null;+let nativeAuthSyncTail = Promise.resolve();+function syncCodeBuddyAuth() {+ const work = nativeAuthSyncTail.catch(() => {}).then(async () => {+ const session = await codeBuddyNative.read();+ if (!session || !session.account || !session.auth) {+ if (fs.existsSync(AUTH_FILE)) fs.unlinkSync(AUTH_FILE);+ return null;+ }+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(String(session.account.uid || ''))) throw new Error('原生账号标识无效');+ const content = JSON.stringify(session);+ fs.mkdirSync(path.dirname(AUTH_FILE), {recursive:true, mode:0o700});+ let previous = ''; try { previous = fs.readFileSync(AUTH_FILE, 'utf8'); } catch (_) {}+ if (previous !== content) {+ const temp = AUTH_FILE + '.tmp';+ fs.writeFileSync(temp, content, {mode:0o600});+ fs.renameSync(temp, AUTH_FILE);+ fs.chmodSync(AUTH_FILE, 0o600);+ }+ return session;+ });+ nativeAuthSyncTail = work;+ return work;+}+async function switchAccountForProfile(uid) {+ if (!codeBuddyNative) return switchTo(DATA_DIR, uid, log);+ await syncCodeBuddyAuth();+ if (fs.existsSync(AUTH_FILE)) backupCurrent(DATA_DIR, log);+ const file = accountBackupFile(uid);+ const session = JSON.parse(fs.readFileSync(file, 'utf8'));+ if (!parseAuthJson(session, {strict:true})) throw new Error('账号备份无效或不属于当前地区');+ if (String(session.account && session.account.uid) !== String(uid)) throw new Error('账号备份标识不匹配');+ const result = await codeBuddyNative.replace(session);+ if (!result || result.uid !== String(uid)) throw new Error('CodeBuddy 未确认账号切换');+ const current = await syncCodeBuddyAuth();+ if (!current || String(current.account.uid) !== String(uid)) throw new Error('CodeBuddy 账号复核失败');+ backupCurrent(DATA_DIR, log);+ return {uid:String(uid),nickname:wdCompatText(current.account.nickname),nativeSwitched:true};+}+function scheduleBackup(reason) {if (backupTimer) clearTimeout(backupTimer);- backupTimer = setTimeout(() => {+ backupTimer = setTimeout(async () => {backupTimer = null;try {+ if (codeBuddyNative) await syncCodeBuddyAuth();backupCurrent(DATA_DIR, log);} catch (e) {log(`[sync] ${reason} 触发备份失败: ${e.message}`);@@ -2142,6 +2184,7 @@ function waitForPageReadyThenDispatch(pageSessionId, attempt = 0) {}function dispatchAutomationEvent(type, detail = {}) {+ if (PROFILE.capabilities.automations === false) return;const eventType = String(type || '').trim();if (!['pageReady', 'pageLoaded', 'accountSwitched', 'panelOpened'].includes(eventType)) return;const canonicalType = eventType === 'pageReady' ? 'pageReady' : eventType;@@ -2176,6 +2219,10 @@ function dispatchAutomationEvent(type, detail = {}) {function onCdpEvent(method, params) {switch (method) {+ case 'Runtime.bindingCalled': {+ if (PROFILE.kind === 'codebuddy') handleRendererApiBinding(params).catch(() => {});+ break;+ }case 'Network.requestWillBeSent': {const url = (params.request && params.request.url) || '';if (/auth|realms|login|token/i.test(url)) scheduleBackup('cdp-auth');@@ -2738,7 +2785,7 @@ function relaunchWorkBuddy() {const launcherHome = resolveLauncherHome(command);if (launcherHome) childEnv.HOME = launcherHome;}- const child = spawn(command, environmentMode ? [] : [`--remote-debugging-port=${port}`], {+ const child = spawn(command, environmentMode ? [] : [`--remote-debugging-port=${port}`, ...(PROFILE.nativeDebugPort ? [`--inspect=127.0.0.1:${PROFILE.nativeDebugPort}`] : [])], {detached: true,stdio: 'ignore',windowsHide: true,@@ -2772,7 +2819,7 @@ function relaunchWorkBuddy() {throw new Error(`未找到 WorkBuddy 可执行文件: ${WORKBUDDY_BINARY}`);}log(`[logout] 未找到 WorkDaddy.app,直接重新启动 WorkBuddy(带 CDP 端口 ${port})`);- const child = spawn(WORKBUDDY_BINARY, [`--remote-debugging-port=${port}`], {+ const child = spawn(WORKBUDDY_BINARY, [`--remote-debugging-port=${port}`, ...(PROFILE.nativeDebugPort ? [`--inspect=127.0.0.1:${PROFILE.nativeDebugPort}`] : [])], {detached: true,stdio: 'ignore',});@@ -3171,6 +3218,11 @@ function isIgnorableAutomationSyncFailure(job) {return failed.length > 0 && failed.every(item => item.error === '会话消息文件没有消息,未同步');}async function assertSessionSyncIdle(sessionIds = []) {+ if (PROFILE.kind === 'codebuddy') {+ const sessions=(await codeBuddyNative.sessionItems()).map(item=>JSON.parse(item.value));+ if(sessions.some(s=>(!sessionIds.length || sessionIds.includes(s.conversationId)) && ['Working','Planning'].includes(s.status))) throw new Error('当前账号有会话仍在运行,请等待完成或停止后再同步');+ return;+ }if (PROFILE.kind !== 'workbuddy') return;if (!cdp.connected) throw new Error('无法确认会话状态,请连接 WorkBuddy 后重试');const ids = Array.isArray(sessionIds) ? sessionIds.map((id) => String(id || '').trim()).filter(Boolean) : [];@@ -3272,7 +3324,7 @@ function automationSwitchAccount(account, options = {}) {releaseRendererReload = beginRendererReloadPriority();await preserveAccountSwitchTheme(uid);if (options.isCancelled && options.isCancelled()) throw new Error('任务已停止');- const acct = switchTo(DATA_DIR, uid, log);+ const acct = await switchAccountForProfile(uid);pendingAutomationAccountSwitch = { account: { uid: acct.uid, nickname: acct.nickname } };await reloadWorkBuddyPage();if (pendingAutomationAccountSwitch) {@@ -3738,7 +3790,11 @@ async function performAccountCheckin(uid) {}/** 通过 CDP 把右下角组件注入到 WorkBuddy 渲染进程(幂等,可反复调用) */-function injectWidget(reason, executionContextId) {+async function injectWidget(reason, executionContextId) {+ // CodeBuddy replaces its bootstrap body while loading agentManager. Mounting+ // at executionContextCreated leaves a live widget guard without any DOM.+ // The existing page-load path owns injection for this client.+ if (PROFILE.kind === 'codebuddy' && reason === 'reload-context') return {mounted:false};if (!cdp.connected) {return Promise.reject(new Error('CDP 未连接,无法注入组件'));}@@ -3772,6 +3828,7 @@ function injectWidget(reason, executionContextId) {lastInjectTs = now;let script;try {+ if (PROFILE.kind === 'codebuddy') await cdpSend('Runtime.addBinding', {name: BINDING});script = buildInjectScript();} catch (e) {return Promise.reject(new Error('读取注入脚本失败: ' + e.message));@@ -3870,14 +3927,35 @@ function buildInjectScript() {injectScript = injectScript.replace(anchor, pickerCode + '\n' + anchor);}// 组件内通过 fetch 调用本机 API,注入时写入实际端口- return (toastScript + '\n' + compatScript + '\n' + injectScript)+ // Only WorkDaddy's source uses this private HTML sink. Never replace the+ // host's innerHTML setter: official DOM keeps its Trusted Types enforcement.+ const trustedTypesBootstrap = PROFILE.kind === 'codebuddy' ? `(function(){+ var d=Object.getOwnPropertyDescriptor(Element.prototype,'innerHTML');+ var p=window.__wbsTrustedHtmlPolicy;+ if(!p && typeof trustedTypes!=='undefined') {+ p=trustedTypes.createPolicy('notebookChatEditController',{createHTML:function(v){return String(v);}});+ window.__wbsTrustedHtmlPolicy=p;+ }+ function html(v){return p?p.createHTML(v):v;}+ Object.defineProperty(Element.prototype,'__wbsHTML',{configurable:true,get:d.get,+ set:function(v){return d.set.call(this,html(v));}});+ var outer=Object.getOwnPropertyDescriptor(Element.prototype,'outerHTML');+ Object.defineProperty(Element.prototype,'__wbsOuterHTML',{configurable:true,get:outer.get,+ set:function(v){return outer.set.call(this,html(v));}});+ var adjacent=Element.prototype.insertAdjacentHTML;+ Object.defineProperty(Element.prototype,'__wbsInsertAdjacentHTML',{configurable:true,+ value:function(position,v){return adjacent.call(this,position,html(v));}});+ })();\n` : '';+ let source = (PROFILE.kind === 'codebuddy' ? rendererBridgeSource() : '') + toastScript + '\n' + compatScript + '\n' + injectScript;+ if (PROFILE.kind === 'codebuddy') source = source.replace(/\.innerHTML\b/g, '.__wbsHTML').replace(/\binnerHTML\s*:/g, '__wbsHTML:').replace(/\.outerHTML\b/g, '.__wbsOuterHTML').replace(/\.insertAdjacentHTML\b/g, '.__wbsInsertAdjacentHTML');+ return (trustedTypesBootstrap + source).replace(/__WBS_API__/g, `http://${HOST}:${ACTUAL_PORT}`).replace(/__WBS_VERSION__/g, DAEMON_VERSION)// 注入本地 API 能力凭证;旧版面板不会携带该 header,但新版 daemon 会在启动时重新注入新版面板。.replace(/__WBS_API_TOKEN__/g, API_TOKEN).replace(/__WBS_DIAGNOSTICS_ENABLED__/g, diagnosticsEnabled() ? 'true' : 'false').replace(/__WBS_PROFILE__/g, PROFILE.id)- .replace(/__WBS_CAPS__/g, JSON.stringify(PROFILE.capabilities))+ .replace(/__WBS_CAPS__/g, () => JSON.stringify({...PROFILE.capabilities, appName: PROFILE.appName})).replace(/__WBS_AVATAR_LOGO__/g, 'data:image/svg+xml;base64,' + fs.readFileSync(path.join(__dirname, 'assets', 'workdaddy-app-icon-source.svg')).toString('base64')).replace(/__WBS_LOGO__/g, 'data:image/svg+xml;base64,' + fs.readFileSync(path.join(__dirname, 'assets', 'workdaddy-logo.svg')).toString('base64')).replace(/__WBS_BUDDY_MARK__/g, 'data:image/svg+xml;base64,' + fs.readFileSync(path.join(__dirname, 'assets', 'workbuddy-buddy-mark.svg')).toString('base64'))@@ -3959,70 +4037,29 @@ async function writeDiagnosticsSnapshot(reason) {// ===== SESSIONS_API_MARK:会话管理(读 WorkBuddy workbuddy.db)=====const SESSIONS_DB = PROFILE.sessionDb;const SESSION_DB = createSessionDb({ dbPath: SESSIONS_DB });+const CODEBUDDY_SESSIONS = PROFILE.kind === 'codebuddy' ? createCodeBuddySessionStore({+ readItems: async () => {+ const items=await codeBuddyNative.sessionItems();+ for(const item of items) {const r=JSON.parse(item.value);if(r.userId && r.cwd)codeBuddyFiles.register({id:r.conversationId,user_id:r.userId,cwd:r.cwd});}+ return items;+ },+ writeChanges: async changes => {+ await assertSessionSyncIdle(changes.map(change=>change.id));+ return codeBuddyFiles.commit(changes, () => codeBuddyNative.writeSessions(changes));+ },+}) : null;function sqliteRun(sql, params = []) {- if (PROFILE.kind === 'codebuddy') {- return Promise.reject(new Error(`${PROFILE.name} 会话库暂只支持读取`));- }- return SESSION_DB.run(sql, params);-}-function codeBuddySessionRows() {- return SESSION_DB.all("SELECT key, value FROM ItemTable WHERE key LIKE 'session:%'")- .then((items) => items.map((item) => {- let value = {};- try { value = typeof item.value === 'string' ? JSON.parse(item.value) : (item.value || {}); } catch (_) {}- const id = String(value.conversationId || String(item.key || '').replace(/^session:/, ''));- return {- id, cwd: value.cwd || '', user_id: value.userId || '', title: value.title || '', custom_title: value.title || '',- status: value.status || '', created_at: value.createdAt || null, updated_at: value.updatedAt || null,- last_activity_at: value.updatedAt || null, is_playground: value.isPlayground ? 1 : 0,- deleted_at: null, source_mode: value.mode || 'agents', mode: value.mode || 'agents', model: value.model || '',- };- }))- .catch((e) => { throw new Error('CodeBuddy 会话库读取失败: ' + e.message); });+ return (CODEBUDDY_SESSIONS || SESSION_DB).run(sql, params);}function sqlParamAt(textSql, params, questionIndex) {return params[parameterCount(textSql.slice(0, questionIndex + 1)) - 1];}async function sqliteQuery(sql, params = []) {const expectedParams = parameterCount(sql);- if (expectedParams !== params.length) {- throw new Error(`sqlite 参数数量不匹配: SQL 需要 ${expectedParams} 个,实际收到 ${params.length} 个`);- }- if (PROFILE.kind === 'codebuddy') {- const rows = await codeBuddySessionRows();- const textSql = String(sql || '');- const uidMatch = /user_id\s*=\s*\?/i.exec(textSql);- const idMatch = /id\s+IN\s*\(([^)]*)\)/i.exec(textSql);- const singleIdMatch = /\bid\s*=\s*\?/i.exec(textSql);- let filtered = rows;- if (uidMatch) {- const questionIndex = textSql.indexOf('?', uidMatch.index);- const uid = sqlParamAt(textSql, params, questionIndex);- filtered = filtered.filter((r) => String(r.user_id) === String(uid));- }- if (idMatch) {- const questionIndex = textSql.indexOf('?', idMatch.index);- const start = parameterCount(textSql.slice(0, questionIndex + 1)) - 1;- const ids = new Set(params.slice(start, start + parameterCount(idMatch[1])).map(String));- filtered = filtered.filter((r) => ids.has(String(r.id)));- }- if (singleIdMatch) {- const questionIndex = textSql.indexOf('?', singleIdMatch.index);- const id = sqlParamAt(textSql, params, questionIndex);- filtered = filtered.filter((r) => String(r.id) === String(id));- }- if (/SELECT\s+DISTINCT\s+cwd/i.test(textSql)) return Array.from(new Set(filtered.map((r) => r.cwd).filter(Boolean))).map((cwd) => ({ cwd }));- if (/SELECT\s+user_id/i.test(textSql) && /LIMIT\s+1/i.test(textSql)) return filtered.slice(0, 1).map((r) => ({ user_id: r.user_id }));- return filtered;- }- const rows = await SESSION_DB.all(sql, params);- // Keep the existing API contract (SQLite cells were strings, NULL was empty)- // while avoiding the delimiter/newline corruption of the former text parser.- return rows.map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [- key,- value === null || value === undefined ? '' : String(value).trim(),- ])));+ if (expectedParams !== params.length) throw new Error(`sqlite 参数数量不匹配: SQL 需要 ${expectedParams} 个,实际收到 ${params.length} 个`);+ const rows = await (CODEBUDDY_SESSIONS || SESSION_DB).all(sql, params);+ return rows.map(row => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, value == null ? '' : String(value).trim()])));}// WorkBuddy 将会话正文保存在 ~/.workbuddy*/projects 等系统目录,同时在 sessions.cwd@@ -4259,6 +4296,7 @@ function archiveRelativePath(wbHome, target) {}function collectSessionArchiveFiles(wbHome, sessionId) {+ if (codeBuddyFiles) return codeBuddyFiles.collect(sessionId);if (!isValidSessionId(sessionId)) throw new Error('无效的会话 ID');const files = [];const collect = (target) => {@@ -4325,6 +4363,7 @@ function ensureArchiveParentNoFollow(wbHome, target) {}function restoreSessionArchiveFiles(wbHome, sessionArchive, newId) {+ if (codeBuddyFiles) return codeBuddyFiles.restore(sessionArchive,newId,false);const oldId = String(sessionArchive && sessionArchive.record && sessionArchive.record.id || '');if (!isValidSessionId(oldId) || !isValidSessionId(newId)) throw new Error('会话归档包含无效 ID');const sourceFiles = Array.isArray(sessionArchive.files) ? sessionArchive.files : [];@@ -4348,6 +4387,7 @@ function restoreSessionArchiveFiles(wbHome, sessionArchive, newId) {// Only readSessionTransfer creates these private staging paths. Never accept them// from a JSON API payload or an unverified archive entry.async function restoreStagedSessionArchiveFiles(wbHome, archive, newId) {+ if (codeBuddyFiles) return codeBuddyFiles.restore(archive,newId,true);const oldId = String(archive.record.id);const targets = new Set();for (const entry of archive.files) {@@ -4379,6 +4419,11 @@ function sqlPlaceholders(values) {}async function insertCopiedSession(src, targetUid, newId) {+ let rollbackNativeIndex = null;+ if (codeBuddyFiles) {+ codeBuddyFiles.register({...src,id:newId,user_id:targetUid});+ rollbackNativeIndex = await codeBuddyFiles.publish(newId,src.id);+ }const updatedAt = Date.now();const lastActivityAt = Number(src.last_activity_at || src.updated_at || updatedAt);const vals = [@@ -4404,10 +4449,15 @@ async function insertCopiedSession(src, targetUid, newId) {src.use_sandbox_cli === null || src.use_sandbox_cli === undefined || src.use_sandbox_cli === '' ? null : Number(src.use_sandbox_cli),src.project_id || null,];+ try {await sqliteRun('INSERT INTO sessions (' + SESSION_COPY_COLUMNS.join(',') + ') VALUES (' + sqlPlaceholders(vals) + ');',vals);+ } catch(error) {+ if(rollbackNativeIndex) await rollbackNativeIndex();+ throw error;+ }// The inserted row intentionally gets a fresh updated_at. Persisting the// source revision here would make every later switch look dirty.return Object.assign({}, src, {@@ -4506,8 +4556,9 @@ async function importSessionArchives(payload, targetUid, staged = false) {catch (error) { errors.push(error.message); continue; }const newId = crypto.randomUUID();try {+ if (codeBuddyFiles) codeBuddyFiles.register({...record,id:newId,user_id:ownerUid});if (staged) await restoreStagedSessionArchiveFiles(PROFILE.dataRoot, archive, newId);- else restoreSessionArchiveFiles(PROFILE.dataRoot, archive, newId);+ else await restoreSessionArchiveFiles(PROFILE.dataRoot, archive, newId);await insertCopiedSession(record, ownerUid, newId);imported.push({ sourceId: oldId, id: newId, uid: ownerUid });} catch (error) {@@ -4798,6 +4849,11 @@ async function copySessionRecord(src, targetUid, options = {}) {} catch (_) {}}const targetIds = candidates.length ? candidates.map(row => row.id) : [crypto.randomUUID()];+ // Native history paths require ownership even before a destination row exists.+ if (codeBuddyFiles) {+ codeBuddyFiles.register(sourceRow);+ for (const id of targetIds) codeBuddyFiles.register(candidates.find(row => row.id === id) || {...sourceRow,id,user_id:targetUid});+ }const aliases = getAutoCopySessionMemberRecords(DATA_DIR, lineageId).map(member => member.id).concat(targetIds);const syncCache = getSessionSyncCache();const existingMappingTarget = mapping && mapping.targetId ? candidates.find(row => row.id === mapping.targetId) : null;@@ -4836,7 +4892,10 @@ async function copySessionRecord(src, targetUid, options = {}) {// content and do not create another copy on every switch.const branched = selection.comparison.kind === 'conflict';const targetId = branched ? crypto.randomUUID() : selection.targetId;- if (branched) aliases.push(targetId);+ if (branched) {+ aliases.push(targetId);+ if (codeBuddyFiles) codeBuddyFiles.register({...sourceRow,id:targetId,user_id:targetUid});+ }const existing = candidates.find(row => row.id === targetId) || null;// An equal selection needs no writes: the trimmed selection snapshot is// enough to skip, and the next sync re-reads everything anyway. Avoid the@@ -5438,6 +5497,7 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {}};await Promise.all(Array.from({ length: concurrency }, () => processNext()));+ await refreshCopiedSessionList(job);job.details = job.details.filter(Boolean);job.status = job.conflicts ? 'conflict' : (job.failed || job.partial ? 'partial' : 'done');job.finishedAt = Date.now();@@ -5455,6 +5515,41 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {return job;}+async function refreshCopiedSessionList(job) {+ // WorkBuddy copies commit SQLite directly, bypassing its list-change bus.+ // Its first post-switch snapshot can therefore predate this batch. Use the+ // official collection refresh (including grouped folders), never navigation+ // or a second renderer reload. CodeBuddy already publishes native upserts;+ // it has a different store and must not enter this SDK path.+ if (PROFILE.kind !== 'workbuddy' || !(job.copied || job.partial || job.conflicts)) return;+ if (!cdp.connected || String((currentAccount() || {}).uid || '') !== String(job.targetUid)) return;+ let timer;+ try {+ const response = await Promise.race([+ cdpSend('Runtime.evaluate', {+ expression: `(async function () {+ var conversations = window.wb && window.wb.conversations;+ if (!conversations || typeof conversations.ensureList !== 'function') return false;+ await conversations.ensureList('local', { view: 'active', page: 1, size: 100000 });+ return true;+ })()`,+ awaitPromise: true,+ returnByValue: true,+ }),+ // The official SDK publishes local rows first, then optionally waits for+ // cloud folders. A slow cloud response must not hold the copy queue or+ // delay restoring the selected conversation indefinitely.+ new Promise(resolve => { timer = setTimeout(() => resolve(null), 2000); }),+ ]);+ log('[sessions-auto-copy] 列表刷新' + (response && response.result && response.result.value === true ? '已完成' : '未确认;复制结果已保留'));+ } catch (_) {+ // A disconnected renderer cannot invalidate already committed files/rows.+ log('[sessions-auto-copy] 列表刷新暂不可用;复制结果已保留');+ } finally {+ clearTimeout(timer);+ }+}+function publicAutoCopyJob(job) {if (!job) return null;const copiedBytes = typeof job.copiedBytes === 'number' && Number.isFinite(job.copiedBytes) ? Math.max(0, job.copiedBytes) : null;@@ -5594,6 +5689,7 @@ function removeSessionAppCache(wbHome, id) {// 真实删除会话的消息文件:projects/<项目>/<id>.jsonl + <id>/、workspace/sessions/<id>/、// tasks/<id>/、file-history/<id>/、artifact-index/<id>.json(全部按会话 id 精确删除,不可恢复)function deleteSessionFiles(wbHome, id) {+ if (codeBuddyFiles) return codeBuddyFiles.remove(id);if (!isValidSessionId(id)) throw new Error('无效的会话 ID');// 配置的数据根允许是 Windows junction;仅解析这一层,内部 managed parent 仍逐级拒绝链接。try { wbHome = fs.realpathSync(wbHome); }@@ -6140,7 +6236,9 @@ function readSessionState() {}}}- return sessBuild(st, phrases);+ const result = sessBuild(st, phrases);+ if (PROFILE.capabilities.themeTakeover === false) result.themeTakeoverEnabled = false;+ return result;}function writeSessionState(state) {const s = readWorkbuddySettings();@@ -6154,6 +6252,7 @@ function writeSessionState(state) {writeWorkbuddySettings(s);}function setSessionSwitch(name, enabled) {+ if (name === 'themeTakeoverEnabled' && enabled && PROFILE.capabilities.themeTakeover === false) throw new Error('CodeBuddy 暂不支持毛玻璃主题');if (SESS_SWITCHES.indexOf(name) === -1) throw new Error('未知开关: ' + name);const st = readSessionState();st[name] = !!enabled;@@ -6627,7 +6726,7 @@ function builtinWallpaperSource(baseDir, fileName) {* nebula 主题和背景仅在缺失时安装,避免覆盖用户后来选择的主题配色或背景。*/function initBuiltinAssets() {- if (!PROFILE.capabilities.theme) return;+ if (!PROFILE.capabilities.theme || PROFILE.capabilities.themeTakeover === false) return;try {const src = builtinAssetsDir();if (!src) {@@ -6964,7 +7063,7 @@ function accountSwitchThemeExpression(targetUid) {}async function preserveAccountSwitchTheme(targetUid) {- if (!PROFILE.capabilities.theme || !cdp.connected) return false;+ if (!PROFILE.capabilities.theme || PROFILE.capabilities.themeTakeover === false || !cdp.connected) return false;try {const result = await cdpSend('Runtime.evaluate', {expression: accountSwitchThemeExpression(targetUid), returnByValue: true, awaitPromise: true, timeout: 1500,@@ -7147,18 +7246,24 @@ async function restoreNativeAppearanceByCdp() {} catch (_) {}}+function readSavedThemeId() {+ try {+ const id = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'current-theme.json'), 'utf8')).id;+ if (typeof id === 'string' && (id === 'default' || getTheme(id))) return id;+ } catch (_) {}+ return 'default';+}+/** 恢复已保存的主题(CDP 连接/页面刷新后调用):读取 current-theme.json 重新应用,保证深浅色在重启/刷新后仍生效 */async function restoreSavedTheme() {- if (!PROFILE.capabilities.theme) return;+ if (!PROFILE.capabilities.theme || PROFILE.capabilities.themeTakeover === false) return;if (!cdp.connected) return;if (readSessionState().themeTakeoverEnabled === false) {// 重载/重连时保留官方选择,不能再次触发关闭开关的一次性浅色重置。await startNativeAppearanceSyncByCdp();return;}- // WorkDaddy 主题接管固定为毛玻璃;官方浅色/深色由关闭接管后的 WorkBuddy 自己管理。- let id = 'nebula';- await applyThemeByCdp(id, { automatic: true });+ await applyThemeByCdp(readSavedThemeId(), { automatic: true });}/** 应用主题:通过 CDP 注入主题样式。@@ -7271,7 +7376,7 @@ function readBackgroundBlur() {}async function applyThemeByCdp(id, options = {}) {- if (!PROFILE.capabilities.theme) throw new Error(`${PROFILE.name} 暂不支持主题功能`);+ if (!PROFILE.capabilities.theme || PROFILE.capabilities.themeTakeover === false) throw new Error(`${PROFILE.name} 暂不支持毛玻璃主题`);if (options.release && readSessionState().themeTakeoverEnabled !== false) return { applied: false, takeover: true };if (options.automatic && readSessionState().themeTakeoverEnabled === false) return { applied: false, takeover: false };if (!options.automatic && !options.nativeOnly && !options.release) themeApplyGeneration++;@@ -7912,7 +8017,38 @@ async function sendStashToComposer(record) {const clrV = clr.result && clr.result.value;if (!clrV || !clrV.ok) throw new Error((clrV && clrV.error) || '无法聚焦输入框');if (record.requireEmpty && clrV.hasContent) throw new Error('会话输入框非空,未覆盖草稿、未发送');- if (clrV.hasContent) {+ // CodeBuddy's Slate editor must be changed through its imperative ref. CDP+ // Input events can update the rendered DOM while leaving the Slate model+ // empty, which greys out Send and makes Backspace appear ineffective.+ let nativeTextInserted = false;+ if (typeof PROFILE !== 'undefined' && PROFILE &&+ (PROFILE.id === 'codebuddy-cn' || PROFILE.id === 'codebuddy-intl')) {+ const nativeInsertExpr = `(async function(){try{+ var ed=document.querySelector('[data-slate-editor="true"]'), f=ed&&ed[Object.keys(ed).find(function(k){return k.indexOf('__reactFiber')===0;})], ref=null;+ for(var i=0;f&&i<40;i++,f=f.return){if(f.ref&&f.ref.current&&typeof f.ref.current.replace==='function'&&typeof f.ref.current.prepareBeforeSubmit==='function'){ref=f.ref.current;break;}}+ if(ref){+ ref.replace([{type:'text',text:${JSON.stringify(text)}}]);+ if(typeof ref.flushPendingContentChange==='function') ref.flushPendingContentChange();+ return {ok:true,length:typeof ref.string==='function'?ref.string().length:${JSON.stringify(text)}.length,mode:'ref'};+ }+ var adapter=window.__wbsAdapter;+ if(adapter&&typeof adapter.requestInsertContentBlocks==='function'){+ // The renderer callback is intentionally fire-and-forget; awaiting its+ // return value can hang the CDP evaluation even though the edit landed.+ try { adapter.requestInsertContentBlocks({contentBlocks:[],clearFirst:true}); } catch (_) {}+ await new Promise(function(resolve){setTimeout(resolve,120)});+ try { adapter.requestInsertContentBlocks({contentBlocks:[{type:'text',text:${JSON.stringify(text)}}],promptText:${JSON.stringify(text)},clearFirst:false}); } catch (_) {}+ await new Promise(function(resolve){setTimeout(resolve,120)});+ return {ok:true,length:${JSON.stringify(text)}.length,mode:'adapter'};+ }+ return {ok:false,error:'未找到 CodeBuddy 编辑器接口'};+ }catch(e){return {ok:false,error:String(e)}}})()`;+ const nr = await guardedSend('Runtime.evaluate', { expression: nativeInsertExpr, returnByValue: true, awaitPromise: true });+ const nv = nr.result && nr.result.value;+ if (!nv || !nv.ok) throw new Error((nv && nv.error) || 'CodeBuddy 输入框同步失败');+ nativeTextInserted = true;+ }+ if (!nativeTextInserted && clrV.hasContent) {// 直接执行 renderer 编辑命令,不经过 macOS 原生菜单快捷键。// 旧 Cmd+A 把 Windows 的 65 当作 macOS 原生键码,会误弹“关于 WorkBuddy”并阻塞 CDP。await guardedSend('Input.dispatchKeyEvent', { type: 'rawKeyDown', commands: ['selectAll'] });@@ -7926,7 +8062,7 @@ async function sendStashToComposer(record) {// 真实键入文本:逐行 insertText,行间 Shift+Enter 换行(trusted 键盘事件,Slate 生成段落;// 不能一次 insertText 整个文本——其中的 \n 不会在 Slate 中变成段落)const lines = text.split('\n');- for (let li = 0; li < lines.length; li++) {+ for (let li = 0; !nativeTextInserted && li < lines.length; li++) {if (lines[li]) {const CHUNK = 4000;for (let i = 0; i < lines[li].length; i += CHUNK) {@@ -8044,6 +8180,21 @@ async function sendStashToComposer(record) {var r = button.getBoundingClientRect(), s = getComputedStyle(button);return r.width >= 16 && r.height >= 16 && r.bottom > 0 && s.display !== 'none' && s.visibility !== 'hidden';}+ // Native CodeBuddy has square, unlabelled IconButtons. Its submit+ // callback prepares/flushed Slate content; resolve that exact control.+ if (document.querySelector('#codebuddy-agents-container')) {+ var compat = window.__wbsWorkBuddyCompat;+ var nativeSend = compat && compat.findCodeBuddySendButton(document);+ if (!nativeSend || !visible(nativeSend)) return { ok: false, retryable: true, error: '未找到 CodeBuddy 发送按钮' };+ var nativeStyle = getComputedStyle(nativeSend);+ if (nativeSend.disabled || nativeSend.getAttribute('aria-disabled') === 'true' ||+ /(?:^|\\s)_disabled_/.test(nativeSend.className) || nativeStyle.pointerEvents === 'none') {+ return { ok: false, retryable: true, error: '发送按钮禁用(输入内容未被识别)' };+ }+ nativeSend.scrollIntoView({ block: 'center', inline: 'center' });+ var nativeRect = nativeSend.getBoundingClientRect();+ return { ok: true, x: nativeRect.x + nativeRect.width / 2, y: nativeRect.y + nativeRect.height / 2, selector: 'codebuddy-official-send-button' };+ }var active = document.activeElement;var inputBox = active && active.closest ? active.closest('.cr-input-box') : null;if (!inputBox) {@@ -8080,7 +8231,7 @@ async function sendStashToComposer(record) {var buttons = document.querySelectorAll('button,[role="button"]'), candidates = [];for (var bi = 0; bi < buttons.length; bi++) {var b0 = buttons[bi];- if (b0.closest && b0.closest('.wbs-root')) continue;+ if (b0.closest && b0.closest('.wbs-root,.wbs-stash-inline')) continue;var br0 = b0.getBoundingClientRect(), cs0 = getComputedStyle(b0);var click0 = b0.tagName === 'BUTTON' || b0.getAttribute('role') === 'button';var circ0 = /%/.test(cs0.borderRadius || '') || parseFloat(cs0.borderRadius || '0') >= Math.min(br0.width, br0.height) / 2 - 3;@@ -8125,7 +8276,28 @@ async function sendStashToComposer(record) {if (!sv || !sv.ok) throw new Error((sv && sv.error) || '未找到发送按钮');if (record.guard) await record.guard();if (record.beforeSubmit) await record.beforeSubmit();- await cdpMouseClick('automation:sendPhrase', sv.x, sv.y, { textLen: text.length, button: sv });+ if (sv.selector === 'codebuddy-official-send-button') {+ // CodeBuddy's official onClick prepares and flushes Slate itself and does+ // not inspect isTrusted. Dispatch on that control once: CDP mouse ACKs can+ // stall after the phrase popup closes, and toolbar positions can also move.+ const submitted = await guardedSend('Runtime.evaluate', { expression: `(function(){/* codebuddy-submit-once */+ var compat = window.__wbsWorkBuddyCompat;+ var button = compat && compat.findCodeBuddySendButton(document);+ if (!button) return { ok: false, error: '未找到 CodeBuddy 发送按钮' };+ var rect = button.getBoundingClientRect(), style = getComputedStyle(button);+ if (button.disabled || button.getAttribute('aria-disabled') === 'true' ||+ /(?:^|\\s)_disabled_/.test(button.className) || style.pointerEvents === 'none' ||+ style.display === 'none' || style.visibility === 'hidden' || !rect.width || !rect.height) {+ return { ok: false, error: 'CodeBuddy 发送按钮不可用,未发送' };+ }+ button.click();+ return { ok: true };+ })()`, returnByValue: true });+ const value = submitted.result && submitted.result.value;+ if (!value || !value.ok) throw new Error((value && value.error) || 'CodeBuddy 未确认点击发送');+ } else {+ await cdpMouseClick('automation:sendPhrase', sv.x, sv.y, { textLen: text.length, button: sv });+ }const submittedComposerExpr = `(function(){/* composer-after-submit */try {var editors = document.querySelectorAll('[contenteditable="true"],textarea'), ed = null, bestBottom = -Infinity;@@ -8861,7 +9033,7 @@ function handleApi(req, res) {const state = setSessionSwitch(body.name, body.enabled);if (body.name === 'themeTakeoverEnabled') {themeApplyGeneration++;- if (state.themeTakeoverEnabled) await applyThemeByCdp('nebula');+ if (state.themeTakeoverEnabled) await applyThemeByCdp(readSavedThemeId());else await releaseThemeByCdp();}return json(res, 200, { ok: true, ...state });@@ -8972,6 +9144,13 @@ function handleApi(req, res) {// 「假退出登录」:先退出 WorkBuddy,再删除当前登录文件(备份的 accounts/<uid>.info// 仍保留,token 未过期),最后重新打开,让应用回到登录页,方便登录新账号。if (req.method === 'POST' && p === '/api/logout') {+ if (codeBuddyNative) return (async () => {+ await syncCodeBuddyAuth();+ if (fs.existsSync(AUTH_FILE)) backupCurrent(DATA_DIR, log);+ if (!await codeBuddyNative.logout()) throw new Error('CodeBuddy 未确认退出');+ await syncCodeBuddyAuth();+ return json(res, 200, {ok:true,quit:false,relaunched:false});+ })().catch(error => json(res, 500, {ok:false,error:error.message}));return (async () => {let quit = false;let relaunched = false;@@ -9010,7 +9189,7 @@ function handleApi(req, res) {if (req.method === 'POST' && p === '/api/oauth/start') {return (async () => {try {- const oauthPlatform = PROFILE.id === 'workbuddy-ai' ? 'workbuddy-ai' : 'workbuddy';+ const oauthPlatform = PROFILE.oauthPlatform || (PROFILE.id === 'workbuddy-ai' ? 'workbuddy-ai' : 'workbuddy');const resp = await httpJson(`${WB_API_ENDPOINT}${WB_API_PREFIX}/auth/state?platform=${oauthPlatform}`,'POST',@@ -9366,14 +9545,15 @@ function handleApi(req, res) {}if (req.method === 'GET' && p === '/api/token-stats') {- if (PROFILE.kind !== 'workbuddy') return json(res, 400, { ok: false, error: '当前客户端不支持 Token 统计' });- if (url.searchParams.get('cacheStatus') === '1') return json(res, 200, { ok: true, cacheReady: tokenStatsCacheReady(PROFILE.dataRoot) });++ if (url.searchParams.get('cacheStatus') === '1') return json(res, 200, { ok: true, cacheReady: tokenStatsCacheReady(PROFILE.dataRoot, codeBuddyFiles ? {cacheFile:path.join(DATA_DIR,'token-stats-cache.json')} : {}) });const days = Math.max(1, Math.min(90, Number(url.searchParams.get('days') || 7)));const accounts = listAccounts(DATA_DIR);return sqliteQuery('SELECT id, user_id FROM sessions WHERE deleted_at IS NULL;').then((rows) => {const sessionAccounts = Object.fromEntries(rows.map((row) => [String(row.id || ''), String(row.user_id || '')]).filter((item) => item[0] && item[1]));const stats = scanTokenStatsCached(PROFILE.dataRoot, {+ ...(codeBuddyFiles ? {...codeBuddyFiles.tokenOptions(rows.map(row=>row.id)),cacheFile:path.join(DATA_DIR,'token-stats-cache.json')} : {}),days,account: url.searchParams.get('account') || '',model: url.searchParams.get('model') || '',@@ -9390,8 +9570,7 @@ function handleApi(req, res) {}if (req.method === 'GET' && p === '/api/credit-stats') {- if (PROFILE.kind !== 'workbuddy') return json(res, 400, { ok: false, error: '当前客户端不支持积分历史查询' });- try {+ try {const range = historyRange(url.searchParams.get('days') || 7);const accounts = listAccounts(DATA_DIR);const uid = url.searchParams.get('account') || '';@@ -9406,8 +9585,7 @@ function handleApi(req, res) {return json(res, 200, { ok: true, job: creditHistorySync.status() });}if (req.method === 'POST' && p === '/api/credit-stats') {- if (PROFILE.kind !== 'workbuddy') return json(res, 400, { ok: false, error: '当前客户端不支持积分历史查询' });- return readBody(req).then((body) => {+ return readBody(req).then((body) => {const range = historyRange(body && body.days !== undefined ? body.days : 7);const requested = body && body.uids;const accounts = listAccounts(DATA_DIR);@@ -9465,7 +9643,7 @@ function handleApi(req, res) {return readBody(req).then(async (body) => {const uid = String(body && body.uid || '').trim();if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return json(res, 400, { ok: false, error: 'uid 格式无效' });- if (PROFILE.id !== 'workbuddy-cn') return json(res, 400, { ok: false, error: '当前客户端不支持成长活跃查询' });+ if (PROFILE.capabilities.growthDaily !== true) return json(res, 400, { ok: false, error: '当前客户端不支持成长活跃查询' });if (!fs.existsSync(accountBackupFile(uid))) return json(res, 404, { ok: false, error: '账号备份不存在' });const activityStreak = await growthStreakCache.get(uid);return json(res, 200, { ok: true, uid, activityStreak });@@ -9658,9 +9836,7 @@ function handleApi(req, res) {// 主题列表(内置 + 用户自定义)if (req.method === 'GET' && p === '/api/themes') {try {- const current = fs.existsSync(path.join(DATA_DIR, 'current-theme.json'))- ? JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'current-theme.json'), 'utf8')).id- : 'default';+ const current = readSavedThemeId();return json(res, 200, { ok: true, themes: listThemes(), current });} catch (e) {return json(res, 500, { ok: false, error: e.message });@@ -10388,7 +10564,8 @@ function handleApi(req, res) {// 1) 先完成可重试的文件与规则清理;失败时保留 DB 记录作为重试锚点。const wbHome = PROFILE.dataRoot;let filesRemoved = 0;- for (const id of matchedIds) filesRemoved += deleteSessionFiles(wbHome, id);+ if (codeBuddyFiles) await assertSessionSyncIdle(matchedIds);+ else for (const id of matchedIds) filesRemoved += deleteSessionFiles(wbHome, id);let rulesRemoved = 0;for (const row of matchedRows) {try {@@ -10400,10 +10577,12 @@ function handleApi(req, res) {}// 2) 最后真实删除 DB 记录(非软删)。若此步失败,重复请求可安全重试。if (matchedIds.length) {- await sqliteRun(+ const removeRecords = () => sqliteRun("DELETE FROM sessions WHERE id IN (" + sqlPlaceholders(matchedIds) + ");",matchedIds);+ if (codeBuddyFiles) filesRemoved = await codeBuddyFiles.deleteSessions(matchedIds, removeRecords);+ else await removeRecords();}const cascaded = matchedIds.filter((id) => !requestedSet.has(String(id))).length;log(`[sessions-delete] 已真实删除 ${matchedIds.length} 个会话(DB + ${filesRemoved} 项文件,级联副本 ${cascaded})`);@@ -10957,8 +11136,8 @@ function handleApi(req, res) {}}if (sourceUid !== uid) await preserveAccountSwitchTheme(uid);- const acct = switchTo(DATA_DIR, uid, log);- const hint = '登录文件已切换,请重启 WorkBuddy 使新账号生效';+ const acct = await switchAccountForProfile(uid);+ const hint = acct.nativeSwitched ? '原生登录态已切换,无需重启客户端' : '登录文件已切换,请刷新窗口使新账号生效';let reloaded = false;if (body.reload) {try {@@ -11347,22 +11526,28 @@ log(`登录信息文件: ${currentAuthFile() || '(未唯一确认)'}`);log(`备份目录: ${DATA_DIR}`);updateDebug('daemon-start', { authFile: currentAuthFile(), dataDir: DATA_DIR, appPath: IS_WIN ? WORKDADDY_DIR_WIN : macWorkDaddyAppPath(), apiPort: UI_PORT_BASE });-for (const preset of ['close-buddy-popups.json', ...(PROFILE.capabilities.accounts ? ['keep-accounts-active.json'] : []), ...(PROFILE.id === 'workbuddy-cn' ? ['buddy-travel.json', 'daily-account-checkin.json'] : [])]) {- try {- const result = installBuiltinTask(DATA_DIR, path.join(__dirname, 'builtin/automations', preset));- if (result && result.status === 'upgraded') log(`[automation] 内置任务已升级: ${preset} (revision ${result.revision})`);+if (PROFILE.capabilities.builtinAutomations === false) {+ removeBuiltinTasks(DATA_DIR);+} else {+ for (const preset of ['close-buddy-popups.json', ...(PROFILE.capabilities.accounts ? ['keep-accounts-active.json'] : []), ...(PROFILE.id === 'workbuddy-cn' || PROFILE.id === 'codebuddy-cn' ? ['buddy-travel.json', 'daily-account-checkin.json'] : [])]) {+ try {+ const result = installBuiltinTask(DATA_DIR, path.join(__dirname, 'builtin/automations', preset), PROFILE);+ if (result && result.status === 'upgraded') log(`[automation] 内置任务已升级: ${preset} (revision ${result.revision})`);+ }+ catch (_) { log('[automation] 初始化内置任务失败: ' + preset); }}- catch (_) { log('[automation] 初始化内置任务失败: ' + preset); }}restoreSleepMode();startServer();cdpLoop();+if (codeBuddyNative) setInterval(() => { if (!accountSwitchInProgress) scheduleBackup('native-auth'); }, 15000);// Migrate legacy target row baselines off the switch hot path. This is a// metadata-only repair and does not read any session payload files.setTimeout(() => { migrateAutoCopyTargetRevisionBaselines().catch(() => {}); }, 0);// All automatic check-in entry points are owned by the visible automation task.const tickAutomationSchedules = createScheduleTicker(DATA_DIR);function runAutomationSchedules() {+ if (PROFILE.capabilities.automations === false) return;tickAutomationSchedules(readAutomations(DATA_DIR), startAutomationRun,(id) => Array.from(automationRuns.values()).some((run) => run.taskId === id && run.status === 'running'));}diff --git a/scripts/inject.js b/scripts/inject.jsindex 43eedb8..5c58279 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -241,12 +241,13 @@ function createBrandClickAction(options) {}function createFabAppearance(options) {- var styles = ['theme', 'white', 'black', 'glass'];- var current = 'theme';+ var styles = options.allowedStyles || ['theme', 'white', 'black', 'glass'];+ var current = options.defaultStyle || 'theme';try {var saved = options.storage.getItem(options.key);if (styles.indexOf(saved) >= 0) current = saved;} catch (_) {}+ if (styles.indexOf(current) < 0) current = styles[0] || 'black';function apply() {options.fab.setAttribute('data-wbs-robot-style', current);if (options.root) options.root.setAttribute('data-wbs-robot-style', current);@@ -1041,6 +1042,39 @@ if (typeof module !== 'undefined' && module.exports) {findLatestManualAutomationRun: findLatestManualAutomationRun,};}+// CodeBuddy can replace the bootstrap body after load. Observe only direct+// children: conversation mutations must not trigger whole-document scans.+function preserveNativePanelMount(doc, root, Observer) {+ var stopped = false;+ var body = null;+ var mounts = [root];+ var bodyObserver = new Observer(restore);+ var documentObserver = new Observer(restore);+ function restore() {+ if (stopped) return;+ if (body !== doc.body) {+ bodyObserver.disconnect();+ body = doc.body;+ if (body) bodyObserver.observe(body, { childList: true });+ }+ if (body) mounts.forEach(function (node) { if (!node.isConnected) body.appendChild(node); });+ }+ documentObserver.observe(doc.documentElement, { childList: true });+ restore();+ function dispose() {+ stopped = true;+ bodyObserver.disconnect();+ documentObserver.disconnect();+ mounts = [];+ }+ dispose.keep = function (node) {+ if (stopped) return;+ if (mounts.indexOf(node) < 0) mounts.push(node);+ restore();+ };+ return dispose;+}+if (typeof window !== 'undefined' && typeof document !== 'undefined') {(function () {// 兜底清理:移除任何历史版本注入的残留节点,并清除旧守卫。@@ -1092,7 +1126,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var AC_SUPPORTED = true;// 客户端身份只控制真实的 profile 差异;DOM 与队列能力由 WBS_COMPAT 独立判断。var WBS_PROFILE_IS_AI = PROFILE_ID === 'workbuddy-ai';- var WBS_BRAND = WBS_PROFILE_IS_AI ? 'WorkDaddy AI' : 'WorkDaddy';+ var WBS_BRAND = CAPS.appName || (WBS_PROFILE_IS_AI ? 'WorkDaddy AI' : 'WorkDaddy');+ var WBS_PANEL_TITLE = CAPS.apiTransport === 'cdp' ? 'WorkDaddy' : WBS_BRAND;// User-facing strings are translated at the injected root so dynamically-built// panes and toasts follow the same language without touching WorkBuddy's DOM.@@ -1281,7 +1316,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'分支到新会话': 'Start a new conversation here', '从这里开始新会话': 'Start a new conversation here', '复制到这条回复为止的聊天内容,在当前工作区继续聊;原会话不变。': 'Copy the conversation up to this reply into a new conversation in the current workspace. The original stays unchanged.', '正在创建分支会话…': 'Creating branch session…', '分支会话已创建,正在打开…': 'Branch created. Opening…', '分支会话已创建,但无法自动打开,请在会话列表中查找。': 'Branch created but could not open automatically. Check the sessions list.', '新会话未出现在列表中,请在会话列表中查找。': 'The new session is not listed yet. Check the sessions list.', '无法确认所选消息的分支位置,请稍后重试': 'Cannot confirm this reply position. Try again shortly.', '分支失败: ': 'Branch failed: ','账号汇总': 'Account summary', '账号数': 'Accounts', '总积分': 'Total credits', '手机': 'Phone', '有效期至': 'Expires', '当前使用中': 'Currently active', '隐藏敏感信息': 'Mask sensitive info', '显示明文': 'Show plaintext', '登录新账号': 'Log in a new account', '没有可导出的账号备份': 'No account backups to export', '还没有备份账号。打开/登录一次 WorkBuddy 后会自动备份,稍后再来查看。': 'No account backups yet. Open or log in to WorkBuddy once and check again later.','语言': 'Language', '中文': 'Chinese', '英语': 'English', 'English': 'English', '跟随系统': 'Follow system', '设置语言': 'Language', '首次打开时自动跟随系统语言;未匹配时使用英语。': 'The first launch follows your system language. English is used when no match is found.', '语言设置已更新': 'Language updated',- '默认': 'Default', 'WorkDaddy 主题': 'WorkDaddy theme', '毛玻璃': 'Frosted glass', '护眼绿': 'Eye-care green', '赛博紫': 'Cyber purple', '主题外观': 'Theme appearance', '壁纸': 'Wallpaper', '头像': 'Avatar', '自定义壁纸': 'Custom wallpaper', '背景蒙版': 'Background overlay', '背景毛玻璃': 'Background blur', '恢复默认': 'Restore default', '恢复官方头像': 'Restore official avatar',+ 'CodeBuddy 暂不支持毛玻璃主题': 'Frosted glass theme is not yet supported in CodeBuddy', '默认': 'Default', 'WorkDaddy 主题': 'WorkDaddy theme', '毛玻璃': 'Frosted glass', '护眼绿': 'Eye-care green', '赛博紫': 'Cyber purple', '主题外观': 'Theme appearance', '壁纸': 'Wallpaper', '头像': 'Avatar', '自定义壁纸': 'Custom wallpaper', '背景蒙版': 'Background overlay', '背景毛玻璃': 'Background blur', '恢复默认': 'Restore default', '恢复官方头像': 'Restore official avatar','加载中…': 'Loading…', '读取中…': 'Reading…', '正在读取设置…': 'Reading settings…', '查询中…': 'Checking…', '暂无快捷短语': 'No quick phrases', '暂无快捷短语,点击「+ 新增」添加': 'No quick phrases. Click “+ Add” to create one.', '当前还未添加模型': 'No models added yet', '还没有模型备份': 'No model backups yet', '当前筛选下没有会话': 'No sessions match the current filter', '暂无进行中的会话': 'No active sessions', '暂无官方壁纸': 'No built-in wallpapers', '还没有自定义壁纸,先上传一张': 'No custom wallpapers yet. Upload one to start.', '壁纸加载中…': 'Loading wallpapers…', '壁纸加载失败(daemon 不可达)': 'Wallpaper loading failed (daemon unavailable)','发送失败: ': 'Send failed: ', '发送失败': 'Send failed', '打开面板失败: ': 'Could not open panel: ', '设置失败: ': 'Settings failed: ', '设置失败': 'Settings failed', '请求失败': 'Request failed', '操作失败': 'Operation failed', '读取文件失败': 'Could not read file', '复制失败': 'Copy failed', '复制失败: ': 'Copy failed: ', '删除失败: ': 'Delete failed: ', '删除失败': 'Delete failed', '切换失败: ': 'Switch failed: ', '应用主题失败: ': 'Could not apply theme: ', '蒙版设置失败: ': 'Overlay setting failed: ', '毛玻璃设置失败: ': 'Blur setting failed: ', '诊断设置保存失败: ': 'Could not save diagnostics setting: ', '无法连接本地服务: ': 'Cannot connect to local service: ', '请确认守护进程已运行': 'Make sure the daemon is running','执行中': 'Running', '已停用': 'Disabled', '示例': 'Examples', '手动触发': 'Manual trigger', '等待触发': 'Waiting for trigger', '上次已完成': 'Last completed', '上次失败': 'Last failed', '上次已停止': 'Last stopped', '停止本次执行': 'Stop this run', '手动任务无需自动触发': 'Manual tasks do not need automatic triggers', '启用自动触发': 'Enable automatic triggers', '成长计划连续活跃天数': 'Consecutive active days in Growth Plan', '活跃天数读取失败': 'Unable to read active days', '正在读取活跃天数': 'Loading active days', '活跃 ': 'Active ', '此任务由事件或定时自动触发,无需手动运行': 'This task runs automatically on its event or schedule', '当前客户端不支持成长活跃查询': 'Growth activity is unavailable in this client',@@ -1337,12 +1372,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'会话同步完成': 'Session sync complete', '会话同步完成,已保留分叉': 'Session sync complete with conflicts', '会话同步完成,部分项目失败': 'Session sync complete with some failures', '会话同步等待中': 'Session sync waiting', '正在同步会话': 'Syncing session', '会话同步失败': 'Session sync failed', '同步等待中': 'Sync waiting', '同步失败': 'Sync failed', '同步': 'Sync', '已同步': 'Synced', ' · 新同步': ' · Newly synced ', ' · 有': ' · ', ' 项需要留意': ' item(s) need attention', ' · 请稍后重试': ' · Try again later', '会话同步进度': 'Session sync progress', ' 个会话已分叉,已保留双方内容': ' session(s) were changed on both sides; neither side was overwritten', '其他账号': 'Other account', '同步完成': 'Sync complete', '同步完成,已保留分叉': 'Sync complete with conflicts', '同步完成,部分失败': 'Sync complete with some failures', '正在把已标记的会话同步到「': 'Syncing marked sessions to “', ' 个未变化会话': ' unchanged session(s)', '同步任务未完成,请稍后重试': 'Sync did not finish. Try again later',' · 跳过': ' · Skipped', ' · 分叉': ' · Conflicts', '成功': 'Succeeded', '跳过': 'Skipped', '已跳过': 'Skipped', '部分失败': 'Partial failure', '分叉': 'Conflict', '处理中': 'Processing', '会话已分叉,已保留双方内容': 'Changed on both sides; neither side was overwritten', '部分文件失败': 'Some files failed', '当前任务未记录逐项明细。': 'No per-session details were recorded for this task.', '会话同步明细': 'Session sync details', '会话同步结果筛选': 'Filter session sync results', '当前分类没有会话。': 'No sessions in this category.', '正在把已标记的会话从「': 'Syncing marked sessions from “', '」同步到「': '” to “', '查看明细': 'View details', ' 个候选会话': ' candidate session(s)', ' 秒后自动关闭': ' seconds until automatic close','收录 GitHub 和 Gitee 公开仓库。参考 ': 'Public GitHub and Gitee repositories are indexed. See ', '。': '.', '克隆示例仓库:': 'Clone the example repository: ', '删除 ': 'Delete ', ' 目录中不需要的示例任务。': ' directory tasks you do not need.', '把你的自动化任务 JSON 放进 ': 'Put your automation task JSON in ', ' 目录。': ' directory.', '提交改动并推送到 GitHub 或 Gitee。': 'Commit and push changes to GitHub or Gitee.', '在仓库简介中加入关键词 ': 'Add the keyword ',- '导出账号': 'Export accounts', '导入账号': 'Import accounts', '导出会话': 'Export sessions', '导入会话': 'Import sessions', '导出快捷短语': 'Export quick phrases', '导入快捷短语': 'Import quick phrases', '同步选中到其他账号': 'Sync selected to another account', '删除选中': 'Delete selected', '操作会话': 'Session actions', '连通测试': 'Test connection', '编辑模型': 'Edit model', '模型已保存': 'Model saved', '模型已启用': 'Model enabled', '模型已复制': 'Model copied', '模型配置已共用': 'Model configuration shared', '当前模型': 'Current model', '备选模型': 'Backup models', '模型加载失败:': 'Failed to load models: ', '保存模型失败:': 'Failed to save model: ', '删除当前模型失败:': 'Failed to delete current model: ', '启用模型失败:': 'Failed to enable model: ', '连通测试失败:': 'Connection test failed: ',+ '导出账号': 'Export accounts', '导入账号': 'Import accounts', '导出会话': 'Export sessions', '导入会话': 'Import sessions', '导出快捷短语': 'Export quick phrases', '导入快捷短语': 'Import quick phrases', '同步选中到其他账号': 'Sync selected to another account', '删除选中': 'Delete selected', '操作会话': 'Session actions', '连通测试': 'Test connection', '编辑模型': 'Edit model', '模型已保存': 'Model saved', '模型已启用': 'Model enabled', '模型已复制': 'Model copied', '模型配置已共用': 'Model configuration shared', '与 {name} 共用模型配置': 'Model configuration shared with {name}', '当前模型': 'Current model', '备选模型': 'Backup models', '模型加载失败:': 'Failed to load models: ', '保存模型失败:': 'Failed to save model: ', '删除当前模型失败:': 'Failed to delete current model: ', '启用模型失败:': 'Failed to enable model: ', '连通测试失败:': 'Connection test failed: ','选择要查看的账号': 'Choose an account to view', '选择账号并输入密码后导出备份': 'Choose accounts and enter a password to export backups', '从加密导出文件导入账号备份': 'Import account backups from an encrypted export', '使用密码导出选中会话': 'Export selected sessions with a password', '使用密码导出选中快捷短语': 'Export selected quick phrases with a password', '从加密文件导入会话': 'Import sessions from an encrypted file', '从加密文件导入快捷短语': 'Import quick phrases from an encrypted file', '仅支持 PNG / JPG / WebP': 'PNG / JPG / WebP only', '点击或拖拽上传壁纸': 'Click or drag to upload a wallpaper', '点击选择图片,或拖拽到此处': 'Click to choose an image, or drag it here', '支持 PNG / JPG / WebP,自动压缩;可添加多张': 'PNG / JPG / WebP supported; images are compressed automatically','未命名账号': 'Unnamed account', '未命名模型': 'Unnamed model', '未命名': 'Unnamed', '未知错误': 'Unknown error', '未知': 'Unknown', '有效期未知': 'Expiry unknown', '未找到输入框': 'Composer not found', '输入框内容为空': 'Composer is empty', '当前输入框暂不支持引用插入': 'The current composer does not support quote insertion', '引用插入失败,请重试': 'Could not insert quote. Please try again', '短语不能为空': 'Quick phrase cannot be empty', '请输入快捷短语': 'Enter a quick phrase', '删除快捷短语': 'Delete quick phrase', '编辑快捷短语': 'Edit quick phrase', '新增快捷短语': 'Add quick phrase', '确定删除': 'Confirm deletion', '确认永久删除': 'Confirm permanent deletion','本机回环 CDP 注入 · 不改官方安装包': 'Local CDP injection · official app untouched', '一个基于 ': 'A ', ' 的 WorkBuddy 桌面端增强工具。零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。': ' WorkBuddy desktop enhancement tool using Chrome DevTools Protocol (CDP). No intrusion or re-signing; UI components are injected into the running renderer.', '问题反馈': 'Report an issue',// —— 覆盖度补齐(分区域,模板条目支持 {name} 占位,匹配时最长优先)——- '(无标题)': 'Untitled', 'GitHub 仓库': 'GitHub repository', '去 GitHub Issues 反馈问题': 'Report an issue on GitHub', '在 GitHub 上给 WorkDaddy 点 Star': 'Star WorkDaddy on GitHub', 'WorkDaddy,点击打开面板,可拖动': 'WorkDaddy – click to open the panel, draggable', '如果 WorkDaddy 对你有帮助,欢迎在 GitHub 点个 Star。你的支持会让这个小项目持续更新。': 'If WorkDaddy helps you, please star it on GitHub. Your support keeps this small project alive.',+ '(无标题)': 'Untitled', 'GitHub 仓库': 'GitHub repository', '去 GitHub Issues 反馈问题': 'Report an issue on GitHub', '在 GitHub 上给 WorkDaddy 点 Star': 'Star WorkDaddy on GitHub', ',点击打开面板,可拖动': ' – click to open the panel, draggable', 'WorkDaddy,点击打开面板,可拖动': 'WorkDaddy – click to open the panel, draggable', '如果 WorkDaddy 对你有帮助,欢迎在 GitHub 点个 Star。你的支持会让这个小项目持续更新。': 'If WorkDaddy helps you, please star it on GitHub. Your support keeps this small project alive.','元素检查': 'Inspect element', '元素检查不可用:内部模块未加载': 'Element inspector unavailable: internal module not loaded', '元素拾取器尚未加载': 'Element picker is not loaded','DOM 元素检查器': 'DOM element inspector', '复制元素': 'Copy element', '关闭元素检查器': 'Close element inspector', '已复制元素': 'Element copied', '未找到可检查元素': 'No inspectable element found', '检查失败:': 'Inspection failed: ', '拾取模式:移动鼠标高亮元素,点击选中(Esc 退出)': 'Pick mode: move to highlight an element, click to select (Esc to exit)','到期时间': 'Expiry', '剩余': 'Remaining', '剩余时间计算中': 'Calculating remaining time', '积分': 'Credits', '积分节点': 'Credit node', '积分查询超时': 'Credit query timed out', '个人版': 'Personal', '企业': 'Enterprise', '基础用量': 'Base usage', '赠送与加量包': 'Gift & bonus packs', '其他积分': 'Other credits', '即将过期': 'Expiring soon', '已过期': 'Expired',@@ -1368,7 +1403,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'正在解包新应用…': 'Unpacking new app…', '挂载 dmg 失败:': 'Failed to mount dmg:', '缺少解包后的新应用': 'Unpacked new app missing', '解包应用失败': 'Failed to unpack app', '缺少 apply-update.sh': 'apply-update.sh missing', '(仓库暂无 Release)': ' (no Releases in the repository yet)', 'auth/state 响应缺少 state': 'auth/state response is missing state','WBSWITCH_WORKBUDDY_BIN 不是可验证的当前 profile 主程序;登录信息未修改': 'WBSWITCH_WORKBUDDY_BIN is not a verified main program for the current profile; login info unchanged', '无法以普通用户权限安全退出 WorkBuddy。请手动关闭该程序;若它以管理员身份运行,请先退出后再重试。登录信息未修改': 'Cannot safely quit WorkBuddy at standard user privilege. Please close it manually; if it runs as admin, quit it first and retry. Login info unchanged', '未找到 WorkBuddy 可执行文件,无法安全退出;登录信息未修改': 'WorkBuddy executable not found; cannot quit safely. Login info unchanged', 'workbuddy-target.json 指定的路径不是可验证的当前 profile 主程序;登录信息未修改': 'The path in workbuddy-target.json is not a verified main program for the current profile; login info unchanged', '存在当前 profile 进程,但没有进程属于已验证安装目录;登录信息未修改': 'A current profile process exists, but none belongs to a verified install directory; login info unchanged', '检测到当前 profile 正从另一安装目录运行,登录信息未修改': 'The current profile is running from another install directory; login info unchanged', '检测到多个 dormant WorkBuddy 安装目录,按发现优先级选择:': 'Multiple dormant WorkBuddy installs found; selecting by discovery priority:', 'WorkBuddy 数据目录不是受管目录': 'WorkBuddy data directory is not managed', 'WorkBuddy 页面尚未完成加载': 'WorkBuddy page has not finished loading', '刷新 WorkBuddy 页面': 'Refresh WorkBuddy page', '注入脚本页面抛错': 'Injected script page threw an error', '读取注入脚本失败:': 'Failed to read the injected script:', '运行时桥接文件未生成': 'Runtime bridge file was not created',// —— 第三批:daemon 端口/路径校验/发送链路错误(可能进入 toast/API 返回)——- '9222-9232、9333 均被占用,无法为 WorkBuddy 分配 CDP 端口': 'Ports 9222-9232 and 9333 are all occupied; cannot allocate a CDP port for WorkBuddy', 'cwd 不是绝对路径': 'cwd is not an absolute path', 'cwd 路径包含符号链接或普通文件': 'cwd path contains a symlink or regular file', '发送按钮禁用(输入内容未被识别)': 'Send button disabled (input not recognized)', '无法清空输入框': 'Could not clear the composer', '无法聚焦输入框': 'Could not focus the composer', '未找到发送按钮': 'Send button not found', '未找到操作栏': 'Toolbar not found', 'Agent 提示词为空或过长': 'Agent prompt is empty or too long', 'Agent 提示词未发送,请重试': 'Agent prompt was not sent; try again',+ '9222-9232、9333 均被占用,无法为 WorkBuddy 分配 CDP 端口': 'Ports 9222-9232 and 9333 are all occupied; cannot allocate a CDP port for WorkBuddy', 'cwd 不是绝对路径': 'cwd is not an absolute path', 'cwd 路径包含符号链接或普通文件': 'cwd path contains a symlink or regular file', '发送按钮禁用(输入内容未被识别)': 'Send button disabled (input not recognized)', '无法清空输入框': 'Could not clear the composer', '无法聚焦输入框': 'Could not focus the composer', '未找到发送按钮': 'Send button not found', '未找到 CodeBuddy 发送按钮': 'CodeBuddy send button not found', '未找到操作栏': 'Toolbar not found', 'Agent 提示词为空或过长': 'Agent prompt is empty or too long', 'Agent 提示词未发送,请重试': 'Agent prompt was not sent; try again','发送内容为空': 'Message is empty',// —— 第四批:真机扫描发现的整句/半动态拼接(杜绝中英混合)——'全部开': 'Enable all', '一键批量开启/关闭全部免打扰开关': 'Toggle all quiet-mode switches at once',@@ -1465,7 +1500,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'会话将导入到「': 'Importing sessions into “', '会话将保留导出时的账号归属。': 'Sessions keep the account ownership from export.',' 个会话': ' session(s)', ' 个会话(已加密)': ' session(s) (encrypted)', ' 个会话及其本地消息附件。': ' session(s) and their local message attachments.', ' 个会话到…': ' session(s) to…', ' 个会话?': ' session(s)?',' 个模型': ' model(s)', ' 个当前模型': ' current model(s)', ' 个模型备份': ' model backup(s)',- '两个 WorkBuddy 客户端共用同一份模型配置,无需导入,切换客户端即可看到模型': 'Both WorkBuddy clients share one model config; no import needed, switch clients to see models',+ '两个客户端共用同一份模型配置,无需导入,切换客户端即可看到模型': 'Both clients share one model config; no import needed, switch clients to see models','只导入当前不存在的模型,同名模型保留当前配置': 'Only import models that do not exist; same-name models keep the current config','未找到模型配置文件': 'Model config file not found', '模型已备份到「': 'Model backed up to “', '模型备份失败:': 'Model backup failed:','两个客户端共用同一份模型配置,无需导入': 'Both clients share one model config; no import needed',@@ -1914,6 +1949,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var EXPLORE_SVG ='<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">' +'<path fill="currentColor" d="M19 3a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H7.333L4 21.5c-.824.618-2 .03-2-1V6a3 3 0 0 1 3-3h14Zm-8 9H8a1 1 0 1 0 0 2h3a1 1 0 1 0 0-2Zm5-4H8a1 1 0 0 0-.117 1.993L8 10h8a1 1 0 0 0 .117-1.993L16 8Z"/></svg>';+ // CodeBuddy 的工具栏使用细线图标,保留原有标签和对话气泡的含义。+ var NATIVE_STASH_SVG =+ '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' ++ '<path d="M3 4a1 1 0 0 1 1-1h7l10 10a1.4 1.4 0 0 1 0 2l-6 6a1.4 1.4 0 0 1-2 0L3 11Z"/><circle cx="7.5" cy="7.5" r="1.5"/></svg>';+ var NATIVE_EXPLORE_SVG =+ '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' ++ '<path d="M5 3h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H8l-5 3V5a2 2 0 0 1 2-2Z"/><path d="M7 8h10M7 13h6"/></svg>';var EXPLORE_PREMIUM_SVG ='<svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>';var EXPLORE_CHECK_SVG =@@ -2044,7 +2086,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function checkinHtml(a) {- if (WBS_PROFILE_IS_AI) return '';+ if (WBS_PROFILE_IS_AI || CAPS.checkin === false) return '';var c = a && a.checkin;var checked = !!(c && c.ok && !c.inactive);return '<span class="wbs-ck wbs-checkin-tag ' + (checked ? 'ok' : 'pending') + '" title="' + (checked ? '今日已签到' : '今日未签到') + '">' + (checked ? '今日已签到' : '今日未签到') + '</span>';@@ -2105,7 +2147,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {headers['X-WorkDaddy-Token'] = WBS_API_TOKEN;request.headers = headers;delete request.responseType;- return fetch(API + path, request).then(function (r) {+ var response = CAPS.apiTransport === 'cdp' ? window.__wbsApiFetch(path, request, WBS_API_TOKEN) : fetch(API + path, request);+ return response.then(function (r) {if (r.ok && opts.responseType === 'blob') return r.blob().then(function (blob) {return { content: blob, mimeType: 'application/octet-stream', count: Number(r.headers.get('X-WorkDaddy-Count') || 0) };});@@ -2291,6 +2334,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function build() {var lifecycle = createBuildLifecycle();var registerDisposer = lifecycle.registerDisposer;+ var nativePanelMount = null;+ function mountPersistentOverlay(node) {+ node.setAttribute('data-wbs-panel-overlay', '');+ if (CAPS.panelAppearance === 'light') node.setAttribute('data-wbs-appearance', 'light');+ document.body.appendChild(node);+ if (nativePanelMount) nativePanelMount.keep(node);+ }var usageActivity = createUsageActivity({ document: document, window: window,now: Date.now,send: function () { return api('/api/usage', { method: 'POST' }); } });@@ -3202,6 +3252,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var root = el('div', 'wbs-root');root.setAttribute('data-wbs-profile', PROFILE_ID);+ if (CAPS.panelAppearance === 'light') root.classList.add('wbs-panel-light');if (!CAPS.theme) root.classList.add('wbs-no-theme');if (!CAPS.stashPrompt) root.classList.add('wbs-no-stash');root.innerHTML = [@@ -3212,7 +3263,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<rect width="82" height="64" fill="white"/><rect class="wbs-robot-cutout" x="22" y="23" width="12" height="18" rx="6" fill="black"/><rect class="wbs-robot-cutout" x="48" y="23" width="12" height="18" rx="6" fill="black"/>','</mask></defs></svg>','<div class="click">',- '<button class="button up" type="button" aria-label="WorkDaddy,点击打开面板,可拖动">',+ '<button class="button up" type="button" aria-label="' + WBS_BRAND + ',点击打开面板,可拖动">','<span class="wbs-fab-antenna" aria-hidden="true"></span>','<span class="wbs-fab-antenna-dot" id="wbs-fab-sleep-light" title="允许电脑休眠(默认)"></span>','<div class="speak dblink"><div class="wrap"><div class="eye double-blink"></div><div class="eye double-blink"></div></div></div>',@@ -3224,7 +3275,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-head-left">','<div class="wbs-title-wrap"><div class="wbs-title-row">','<button class="wbs-brand" id="wbs-title" type="button" title="点击打开官网">',- '<span class="wbs-brand-copy"><span class="wbs-title">' + WBS_BRAND + '</span><span class="wbs-version-line" id="wbs-version-line"></span></span>',+ '<span class="wbs-brand-copy"><span class="wbs-title">' + WBS_PANEL_TITLE + '</span><span class="wbs-version-line" id="wbs-version-line"></span></span>','</button>','<button class="wbs-pick-btn" id="wbs-pick-btn" type="button" style="display:none" title="元素检查">🔍</button>','<span class="wbs-health-status" id="wbs-health-status" aria-live="polite"></span>',@@ -3255,11 +3306,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'</div>',].join('');document.body.appendChild(root);+ if (CAPS.apiTransport === 'cdp') {+ nativePanelMount = preserveNativePanelMount(document, root, MutationObserver);+ registerDisposer(nativePanelMount);+ }var versionLine = root.querySelector('#wbs-version-line');if (versionLine) {var wbVersion = wbsClientVersion(navigator.userAgent);var pluginVersion = WBS_VERSION && WBS_VERSION.indexOf('__WBS_') !== 0 ? WBS_VERSION : '';- versionLine.textContent = wbVersion ? wbVersion + (pluginVersion ? ' (' + pluginVersion + ')' : '') : (pluginVersion ? '(' + pluginVersion + ')' : '');+ versionLine.textContent = CAPS.apiTransport === 'cdp' ? '(v' + pluginVersion + ' for ' + WBS_BRAND + ')' : wbVersion ? wbVersion + (pluginVersion ? ' (' + pluginVersion + ')' : '') : (pluginVersion ? '(' + pluginVersion + ')' : '');}listen(window, 'workdaddy:automation-toast', function (event) {var detail = event && event.detail && typeof event.detail === 'object' ? event.detail : {};@@ -3309,30 +3364,38 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (sessionsPane) sessionsPane.classList.add('active');}+ if (CAPS.enhance === false) {+ var enhanceTab = root.querySelector('[data-tab="enhance"]');+ var enhancePane = root.querySelector('[data-pane="enhance"]');+ if (enhanceTab) enhanceTab.remove();+ if (enhancePane) enhancePane.remove();+ }+// ===== 暂存提示词:内联到「发送按钮」左侧,尺寸与发送按钮一致 =====// 显隐策略:直接监听 WorkBuddy 自己的「发送按钮」禁用态——输入框为空时发送按钮被禁用,// 此时隐藏暂存按钮;有内容(文字/图片/附件)时发送按钮可用,暂存按钮出现。// 这样无需自己去扫描 Slate 编辑器,和官方发送按钮行为完全一致。var stashBtn = document.createElement('div');- stashBtn.className = 'wbs-stash-inline';+ stashBtn.className = 'wbs-stash-inline' + (CAPS.nativeComposer ? ' wbs-composer-native' : '');stashBtn.style.display = 'none';stashBtn.setAttribute('role', 'button');stashBtn.setAttribute('tabindex', '0');stashBtn.title = '暂存提示词';- stashBtn.innerHTML = '<span class="wbs-stash-ico">' + STASH_SVG + '</span><span class="wbs-stash-txt">暂存提示词</span>';+ stashBtn.innerHTML = '<span class="wbs-stash-ico">' + (CAPS.nativeComposer ? NATIVE_STASH_SVG : STASH_SVG) + '</span><span class="wbs-stash-txt">暂存提示词</span>';applyI18n(stashBtn);// 防输入框失焦:点击按钮时不把焦点从输入框抢走(退格/打字持续有效)stashBtn.addEventListener('mousedown', function (e) { e.preventDefault(); });+ listen(stashBtn, 'mouseenter', syncNativeStashLabelWidth);if (!CAPS.stashPrompt) stashBtn.style.display = 'none';// 探索菜单按钮:复用暂存提示词按钮的样式类(同款圆钮),hover 不变宽;悬浮弹出菜单var exploreBtn = document.createElement('div');- exploreBtn.className = 'wbs-stash-inline wbs-explore-inline';+ exploreBtn.className = 'wbs-stash-inline wbs-explore-inline' + (CAPS.nativeComposer ? ' wbs-composer-native' : '');exploreBtn.setAttribute('role', 'button');exploreBtn.setAttribute('tabindex', '0');exploreBtn.addEventListener('mousedown', function (e) { e.preventDefault(); }); // 防输入框失焦exploreBtn.innerHTML =- '<span class="wbs-explore-ico">' + EXPLORE_SVG + '</span>' ++ '<span class="wbs-explore-ico">' + (CAPS.nativeComposer ? NATIVE_EXPLORE_SVG : EXPLORE_SVG) + '</span>' +'<div class="wbs-explore-pop" role="tooltip">' +'<div class="wbs-explore-card">' +'<div class="wbs-explore-list" id="wbs-explore-list"></div>' +@@ -3387,7 +3450,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {try {var a = document.activeElement;var r = a && a.getBoundingClientRect ? a.getBoundingClientRect() : null;- var payload = { event: event, href: location.href, title: document.title, active: a ? { tag: a.tagName, id: a.id || '', cls: typeof a.className === 'string' ? a.className.slice(0, 160) : '', text: (a.innerText || a.textContent || '').trim().slice(0, 100), rect: r ? { x: r.x, y: r.y, w: r.width, h: r.height } : null } : null };+ var payload = { event: event, href: location.href, title: document.title, active: a ? { tag: a.tagName, id: a.id || '', cls: typeof a.className === 'string' ? a.className.slice(0, 160) : '', rect: r ? { x: r.x, y: r.y, w: r.width, h: r.height } : null } : null };if (extra) payload.extra = extra;console.log('[quick-phrase-diagnostics]', JSON.stringify(payload));fetch(API + '/api/breadcrumb', { method: 'POST', headers: { 'content-type': 'application/json', 'X-WorkDaddy-Token': WBS_API_TOKEN }, body: JSON.stringify({ msg: '[quick-phrase-diagnostics] ' + JSON.stringify(payload) }) }).catch(function () {});@@ -3396,7 +3459,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// Only the popup leaves the official toolbar. Its body-level stacking context// keeps it above the usage summary even when the composer creates its own layer.function mountExplorePopover(button, popup) {- document.body.appendChild(popup);+ if (CAPS.enhance === false) return { close: function () {}, open: function () {}, destroy: function () {} };+ mountPersistentOverlay(popup);var timer = null;var listeners = [];function listen(target, name, handler, options) {@@ -3470,7 +3534,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {usageSummary: conversationUsageEnabled,fork: readForkEnabled(),phrase: true,- themeTakeover: true,+ themeTakeover: CAPS.themeTakeover !== false,phrases: [],qpBatch: false,qpSel: {},@@ -3481,7 +3545,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!d || !d.ok) return;sessState.stash = !!d.stashEnabled;sessState.phrase = !!d.phraseEnabled;- sessState.themeTakeover = d.themeTakeoverEnabled !== false;+ sessState.themeTakeover = CAPS.themeTakeover !== false && d.themeTakeoverEnabled !== false;sessState.phrases = Array.isArray(d.phrases) ? d.phrases : [];// 同步 UI:会话开关 + 快捷短语列表区显隐var pane0 = enhancePane;@@ -3500,7 +3564,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (themeSwitch) themeSwitch.checked = sessState.themeTakeover;syncThemeTakeoverVisibility(sessState.themeTakeover);// 开关确认和异步设置回填也要启动图库加载,不能只在切换主题页时加载。- syncWallpaperCardVisibility('nebula');+ syncWallpaperCardVisibility(currentThemeId);if (area) area.style.display = sessState.phrase ? '' : 'none';renderQpList();renderExploreOptions();@@ -3857,11 +3921,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {exploreBtn.style.top = stashBtn.style.top || '0px';}// 使用实时主题变量,颜色变化由 CSS 继承处理,无需监听深浅色属性。+ function syncNativeStashLabelWidth() {+ if (!CAPS.nativeComposer) return;+ var label = stashBtn.querySelector('.wbs-stash-txt');+ var width = label && Math.ceil(label.scrollWidth);+ if (width > 0 && stashBtn.style.getPropertyValue('--wbs-stash-text-width') !== width + 'px') {+ stashBtn.style.setProperty('--wbs-stash-text-width', width + 'px');+ }+ }function applyThemeButtonColors() {- stashBtn.style.background = 'var(--wb-button-primary-bg)';- stashBtn.style.color = 'var(--wb-button-primary-fg)';- exploreBtn.style.background = 'var(--wb-button-primary-bg)';- exploreBtn.style.color = 'var(--wb-button-primary-fg)';+ var bg = CAPS.nativeComposer ? 'var(--cb-button-primary)' : 'var(--wb-button-primary-bg)';+ var fg = CAPS.nativeComposer ? 'var(--cb-button-primary-foreground)' : 'var(--wb-button-primary-fg)';+ stashBtn.style.background = exploreBtn.style.background = bg;+ stashBtn.style.color = exploreBtn.style.color = fg;}function positionStash() {// 新版布局没有 voice-mic-wrap:操作栏按钮行位于输入框正下方(与输入框同祖先容器)。@@ -3952,6 +4024,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var stashSyncThrottle;function syncStash() {if (!alive) return;+ if (CAPS.enhance === false) {+ stashBtn.remove();+ exploreBtn.remove();+ exploreMenu.close();+ return;+ }clearTimeout(stashSyncThrottle);// 节流 30ms:比 120ms 响应更快(接近原生 React 按钮的体感),仍能合并快速连续触发stashSyncThrottle = setBuildTimeout(function () {@@ -3971,6 +4049,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 暂存按钮:仍按输入框是否有内容显隐,且「暂存提示词」开关需开着if (shouldShowStash() && sessState.stash) {stashBtn.style.display = 'flex';+ syncNativeStashLabelWidth();} else {stashBtn.style.display = 'none';}@@ -3979,7 +4058,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 监听发送按钮自身的属性变化(class/disabled/aria-disabled 任一改变都重算显隐)var sendObserver = null, watchedSend = null;function watchSend() {- if (!alive) return;+ if (!alive || CAPS.enhance === false) return;var send = findSendButton();if (send === watchedSend) return;if (sendObserver) { sendObserver.disconnect(); sendObserver = null; }@@ -3993,7 +4072,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 操作栏出现 / 子元素被替换时,重新定位发送按钮并绑定监听var rowObserver = null, watchedRow = null, bodyObserver = null;function watchRow() {- if (!alive) return;+ if (!alive || CAPS.enhance === false) return;var row = findActionRow();if (!row || typeof MutationObserver === 'undefined') {if (rowObserver) { rowObserver.disconnect(); rowObserver = null; }@@ -4491,7 +4570,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {forkTooltip.setAttribute('role', 'tooltip');forkTooltip.appendChild(el('span', 'wbs-fork-tooltip-title', '分支到新会话'));forkTooltip.appendChild(el('span', 'wbs-fork-tooltip-description', '复制到这条回复为止的聊天内容,在当前工作区继续聊;原会话不变。'));- document.body.appendChild(forkTooltip);+ mountPersistentOverlay(forkTooltip);applyI18n(forkTooltip);function hideForkTooltip() { forkTooltip.classList.remove('is-visible'); }function showForkTooltip(button) {@@ -4632,13 +4711,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {syncThemeAuditRoot();if (themeAudit) setBuildInterval(syncThemeAuditRoot, 1200);// 暂存项暂停守护:600ms 周期轮询,保证暂存提示词绝不被自动发送(见 guardStashedPause 注释)- setBuildInterval(guardStashedPause, 600);+ if (CAPS.enhance !== false) setBuildInterval(guardStashedPause, 600);watchRow();watchSend();// 输入框输入/粘贴/中文合成结束也直接触发,覆盖 React 仅改内部状态、不动属性的情况- listen(document, 'input', onInputSync);- listen(document, 'compositionend', onInputSync);- listen(document, 'keyup', onInputSync);+ if (CAPS.enhance !== false) {+ listen(document, 'input', onInputSync);+ listen(document, 'compositionend', onInputSync);+ listen(document, 'keyup', onInputSync);+ }listen(window, 'scroll', onInputSync, true);listen(window, 'resize', onInputSync);// 暂存项禁拖:捕获阶段拦截 dragstart(只 preventDefault/stopPropagation,不改 React 管理的 draggable 属性,@@ -4970,12 +5051,23 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return window.__wbsAdapter;}function bootstrapModernQueueBridge() {+ if (CAPS.enhance === false) return;try {var adapter = findWbsAdapter();if (!WBS_COMPAT.isModernQueueAdapter(adapter)) return;var sessionId = adapter && adapter.currentActiveSessionId;if (!sessionId || typeof adapter.getConversationMessageQueue !== 'function') return;- Promise.resolve(adapter.getConversationMessageQueue(sessionId)).catch(function () {});+ Promise.resolve(adapter.getConversationMessageQueue(sessionId)).then(function (snapshot) {+ var items = snapshot && Array.isArray(snapshot.items) ? snapshot.items : [];+ var ids = stashIds(sessionId);+ items.forEach(function (item) {+ var blocks = item && (item.contentBlocks || item.blocks || item.content);+ if (item && item.id != null && Array.isArray(blocks) && blocks.some(function (b) {+ return b && b._meta && b._meta.workdaddyStash === true;+ }) && ids.indexOf(String(item.id)) < 0) ids.push(String(item.id));+ });+ if (ids.length) { syncQueueDomIds(sessionId, snapshot); syncQueueTags(); }+ }).catch(function () {});} catch (e) {}}@@ -5010,7 +5102,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 后台预热只做只读查找,不触碰用户操作;点击路径随后直接复用缓存。function warmModernQueueAdapter() {- if (!alive || window.__wbsAdapter) return;+ if (!alive || CAPS.enhance === false || window.__wbsAdapter) return;try { findWbsAdapter(); } catch (e) {}}setBuildTimeout(warmModernQueueAdapter, 0);@@ -5081,6 +5173,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}if (candidate) {ids.push(String(candidate.id));+ // The queue row may already be mounted when the RPC resolves, so do a+ // synchronous tag pass instead of waiting for a later mutation.+ syncQueueDomIds(sessionId, snapshot);+ syncQueueTags();return;}// Only use text fallback when the returned queue has no stable ids at all.@@ -5090,6 +5186,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (wanted) {var arr = stashSigs(sessionId);if (arr.indexOf(wanted) < 0) arr.push(wanted);+ syncQueueDomIds(sessionId, snapshot);+ syncQueueTags();}}// 判断一个 queue item 是否为「暂存提示词」消息(按文本签名匹配,仅当前会话)@@ -5102,6 +5200,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {} catch (_) {}if (domId) return ids.indexOf(String(domId)) >= 0;var contentEl = it.querySelector('.content');+ // Future renderer refreshes can recover the marker from official queue+ // blocks even when the in-memory id/signature registry was recreated.+ try {+ var markerBlocks = it.__wbsQueueBlocks;+ if (Array.isArray(markerBlocks) && markerBlocks.some(function (b) { return b && b._meta && b._meta.workdaddyStash === true; })) return true;+ } catch (_) {}var txt = (contentEl && (contentEl.getAttribute('title') || contentEl.textContent) || '').replace(/\s+/g, ' ').trim();if (!txt || ids.length) return false;return arr.some(function (s) { return normalizeQueueText(s) === txt; });@@ -5128,12 +5232,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var index = seen[text] || 0;seen[text] = index + 1;var match = candidates[index];- if (match && match.id != null) domItem.setAttribute('data-queue-item-id', String(match.id));+ if (match && match.id != null) {+ domItem.setAttribute('data-queue-item-id', String(match.id));+ try { domItem.__wbsQueueBlocks = match.contentBlocks || match.blocks || match.content || null; } catch (_) {}+ }else domItem.removeAttribute('data-queue-item-id');});}// 同步标签(仅当前会话的暂存签名)。只做幂等 DOM 插入/移除,不改 React 属性。function syncQueueTags() {+ if (CAPS.enhance === false) return;var sessionId = (window.__wbsAdapter && window.__wbsAdapter.currentActiveSessionId);var arr = stashSigs(sessionId), ids = stashIds(sessionId);if (!alive || (!arr.length && !ids.length)) return;@@ -5188,7 +5296,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return !isStashQueueItem(pendings[0], ids, arr);}function guardStashedPause() {- if (!alive) return;+ if (!alive || CAPS.enhance === false) return;var adapter = window.__wbsAdapter;if (!adapter || typeof adapter.getConversationMessageQueue !== 'function' ||typeof adapter.pauseConversationMessageQueue !== 'function' ||@@ -5355,6 +5463,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var cur = node[fk], seen = 0;while (cur && seen < 120) {var p = cur.memoizedProps;+ // CodeBuddy exposes the live Slate imperative handle on the+ // ChatInput ref. Its clear() updates Slate's model and DOM together;+ // direct execCommand deletion leaves a visible orphan text node.+ var nativeRef = cur.ref && cur.ref.current;+ if (CAPS.nativeComposer && nativeRef && typeof nativeRef.clear === 'function' &&+ typeof nativeRef.prepareBeforeSubmit === 'function') {+ try { nativeRef.clear(); } catch (_) { return false; }+ return true;+ }var store = p && p.store;if (WBS_COMPAT.isComposerStore(store, sessionId)) {try { store.api.clear(); } catch (_) { return false; }@@ -5499,6 +5616,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {try {var blocks = contentToBlocks(content);if (!blocks.length) return Promise.reject(new Error('输入框内容为空'));+ // Keep a non-visible marker in the official block metadata. This lets+ // the label survive reinjection/session remounts without matching user+ // text or treating an ordinary queue item as a stash item.+ blocks = blocks.map(function (block, index) {+ var copy = Object.assign({}, block);+ copy._meta = Object.assign({}, block && block._meta || {}, { workdaddyStash: true });+ return copy;+ });var cachedAdapter = window.__wbsAdapter || findWbsAdapter();var modernQueue = WBS_COMPAT.isModernQueueAdapter(cachedAdapter) || WBS_COMPAT.hasModernQueueSurface(document);var ready = modernQueue@@ -5519,12 +5644,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var enqueueSnapshot = null;// 关键事务顺序:先暂停,再入队。新版 5.4 的 dispatcher 会在 enqueue RPC// 返回前继续 activate(),旧的“先入队后暂停”会把已有普通项全部发送掉。- var pauseWait = modernAdapter+ var pauseWait = (modernAdapter || CAPS.nativeComposer)? withQueueTimeout(adapter.pauseConversationMessageQueue(sessionId, 'manual'), 5000): Promise.resolve(null);return pauseWait.then(function () { crumb('pause:ok'); })- .catch(function () { crumb('pause:fail'); return null; })+ .catch(function (error) { crumb('pause:fail'); throw error; }).then(function () {// 立即把暂存项镜像到新版官方队列 store,避免 RPC 冷启动时 UI 空等数秒。// 真实快照返回后会整体替换该临时项;临时项不参与任何官方操作。@@ -5704,7 +5829,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {setBuildInterval(syncAutomationStopPosition, 250);setBuildTimeout(refreshAutomationStop, 700);}- var fabAppearance = createFabAppearance({ fab: fab, root: root, storage: localStorage, key: 'wbs-fab-style-' + PROFILE_ID });+ var fabAppearance = createFabAppearance({+ fab: fab, root: root, storage: localStorage, key: 'wbs-fab-style-' + PROFILE_ID,+ defaultStyle: CAPS.nativeComposer ? 'black' : CAPS.robotStyle,+ allowedStyles: CAPS.nativeComposer ? ['white', 'black'] : undefined,+ });var panel = root.querySelector('.wbs-panel');var body = root.querySelector('.wbs-body');var accountsPane = root.querySelector('[data-pane="account"]');@@ -5747,7 +5876,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {statusPopover.className = 'wbs-status-popover wbs-daily-popover';statusPopover.setAttribute('role', 'tooltip');statusPopover.hidden = true;- document.body.appendChild(statusPopover);+ mountPersistentOverlay(statusPopover);return statusPopover;}@@ -6080,7 +6209,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {popup.setAttribute('role', 'region'); popup.setAttribute('aria-label', '按剩余天数汇总积分');popup.hidden = true;button.setAttribute('aria-controls', popup.id);- document.body.appendChild(popup);+ mountPersistentOverlay(popup);var hideTimer;function hide() { clearTimeout(hideTimer); popup.hidden = true; button.setAttribute('aria-expanded', 'false'); }function deferHide() { clearTimeout(hideTimer); hideTimer = setBuildTimeout(hide, 160); }@@ -6166,7 +6295,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {popup.innerHTML = '<div class="wbs-account-note-head"><label for="wbs-account-note-input">账号备注</label><button type="button" class="wbs-icon-btn" data-note-close title="关闭" aria-label="关闭"><svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.5"><path d="m4 4 8 8m0-8-8 8"/></svg></button></div>' +'<textarea id="wbs-account-note-input" maxlength="2000" placeholder="暂无备注,点击添加…" rows="4"></textarea>' +'<div class="wbs-account-note-footer"><span role="status" aria-live="polite"></span><button type="button" class="wbs-modal-btn" data-note-cancel>取消</button><button type="button" class="wbs-modal-btn primary" data-note-save>保存</button></div>';- document.body.appendChild(popup);+ mountPersistentOverlay(popup);var input = popup.querySelector('textarea');var save = popup.querySelector('[data-note-save]');var cancel = popup.querySelector('[data-note-cancel]');@@ -7473,7 +7602,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {for (var j = 0; j < panes.length; j++) panes[j].classList.toggle('active', panes[j].getAttribute('data-pane') === name);if (name === 'theme') {if (themePane && !themePane.dataset.built) buildThemePane();- syncWallpaperCardVisibility('nebula');+ syncWallpaperCardVisibility(currentThemeId);}if (name === 'sessions' && sessionsPane && !sessionsPane.dataset.built) buildSessionsPane();if (name === 'models' && modelsPane && !modelsPane.dataset.built) buildModelsPane();@@ -9166,14 +9295,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var imports = modelsPane.querySelector('#wbs-model-imports');if (imports) {imports.style.display = modelsState.tab === 'official' && !modelsState.batch ? '' : 'none';- imports.innerHTML = modelsState.imports.map(function (source) {+ imports.innerHTML = '<span class="wbs-model-client-import"><button class="wbs-sess-bbtn" id="wbs-model-client-import" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="wbs-model-client-menu">导入</button><span class="wbs-model-source-menu" id="wbs-model-client-menu" role="menu" style="display:none">' + modelsState.imports.filter(function (source) { return source.profileId !== PROFILE_ID; }).map(function (source) {var disabled = source.shared ? ' disabled' : (source.available ? '' : ' disabled');var title = source.shared- ? '两个 WorkBuddy 客户端共用同一份模型配置,无需导入,切换客户端即可看到模型'+ ? '两个客户端共用同一份模型配置,无需导入,切换客户端即可看到模型': (source.available ? '只导入当前不存在的模型,同名模型保留当前配置' : '未找到模型配置文件');- var label = source.shared ? '模型配置已共用' : '从 ' + esc(source.name) + ' 导入';- return '<button class="wbs-sess-bbtn wbs-model-import" type="button" data-model-import="' + escAttr(source.profileId) + '" title="' + escAttr(title) + '"' + disabled + '>' + label + '</button>';- }).join('') + '<span class="wbs-model-third-party"><button class="wbs-sess-bbtn" id="wbs-model-third-party" type="button" aria-haspopup="menu" aria-expanded="false">从第三方导入</button><span class="wbs-model-source-menu" id="wbs-model-source-menu" role="menu" style="display:none"><button type="button" role="menuitem" id="wbs-model-source-cc-switch">CC Switch</button></span></span>';+ return '<button class="wbs-model-import" type="button" role="menuitem" data-model-import="' + escAttr(source.profileId) + '" title="' + escAttr(title) + '"' + disabled + '>' + esc(source.name) + '</button>';+ }).join('') + '</span></span><span class="wbs-model-third-party"><button class="wbs-sess-bbtn" id="wbs-model-third-party" type="button" aria-haspopup="menu" aria-expanded="false">从第三方导入</button><span class="wbs-model-source-menu" id="wbs-model-source-menu" role="menu" style="display:none"><button type="button" role="menuitem" id="wbs-model-source-cc-switch">CC Switch</button></span></span>';}updateModelCounts();if (modelsState.tab === 'official') {@@ -9221,6 +9349,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {mask.onclick = function (event) { if (event.target === mask) close(); };ok.onclick = function () { close(); onConfirm(); };}+ function closeModelClientMenu() {+ var menu = modelsPane.querySelector('#wbs-model-client-menu');+ var button = modelsPane.querySelector('#wbs-model-client-import');+ if (menu) menu.style.display = 'none';+ if (button) button.setAttribute('aria-expanded', 'false');+ }function closeThirdPartyMenu() {var menu = modelsPane.querySelector('#wbs-model-source-menu');var button = modelsPane.querySelector('#wbs-model-third-party');@@ -9354,7 +9488,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function wireModelsPane() {listen(document, 'click', function (event) { if (!event.target.closest || !event.target.closest('.wbs-model-third-party')) closeThirdPartyMenu(); });+ listen(document, 'click', function (event) { if (!event.target.closest || !event.target.closest('.wbs-model-client-import')) closeModelClientMenu(); });modelsPane.addEventListener('keydown', function (event) {+ var clientMenu = modelsPane.querySelector('#wbs-model-client-menu');+ if (event.key === 'Escape' && clientMenu && clientMenu.style.display !== 'none') {+ event.preventDefault(); event.stopPropagation(); closeModelClientMenu();+ modelsPane.querySelector('#wbs-model-client-import').focus();+ }var menu = modelsPane.querySelector('#wbs-model-source-menu');if (event.key === 'Escape' && menu && menu.style.display !== 'none') {event.preventDefault(); event.stopPropagation(); closeThirdPartyMenu();@@ -9362,8 +9502,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}});modelsPane.addEventListener('click', function (event) {+ var clientImport = event.target.closest ? event.target.closest('#wbs-model-client-import') : null;+ if (clientImport && !clientImport.disabled) {+ var clientMenu = modelsPane.querySelector('#wbs-model-client-menu');+ if (clientMenu.style.display !== 'none') { closeModelClientMenu(); return; }+ closeThirdPartyMenu();+ clientMenu.style.display = '';+ clientImport.setAttribute('aria-expanded', 'true');+ var firstSource = clientMenu.querySelector('button:not(:disabled)');+ if (firstSource) firstSource.focus();+ return;+ }var third = event.target.closest ? event.target.closest('#wbs-model-third-party') : null;if (third && !third.disabled) {+ closeModelClientMenu();var menu = modelsPane.querySelector('#wbs-model-source-menu');if (menu.style.display !== 'none') { closeThirdPartyMenu(); return; }third.disabled = true;@@ -9394,6 +9546,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}var modelImport = event.target.closest ? event.target.closest('[data-model-import]') : null;if (modelImport && !modelImport.disabled) {+ closeModelClientMenu();var importProfileId = modelImport.getAttribute('data-model-import');modelImport.disabled = true;api('/api/models/import', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ profileId: importProfileId }) })@@ -9544,8 +9697,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function buildThemePane() {if (!themePane) return;themePane.dataset.built = '1';+ var codeBuddyTheme = CAPS.nativeComposer;themePane.innerHTML =- '<div class="wbs-pcard wbs-avatar-card">' ++ (codeBuddyTheme ? '' : '<div class="wbs-pcard wbs-avatar-card">' +'<div class="wbs-pcard-title">头像</div>' +'<div class="wbs-avatar-row">' +'<label class="wbs-avatar-option wbs-avatar-default-option" title="默认头像"><input type="radio" name="wbs-avatar-preset" value="default"><img class="wb-avatar__img" data-avatar-image="default" alt="默认头像"></label>' +@@ -9555,25 +9709,34 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<button class="wbs-avatar-add" id="wbs-avatar-upload" type="button" title="添加头像" aria-label="添加头像"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg></button>' +'<input type="file" id="wbs-avatar-file" accept="image/png,image/jpeg,image/webp" style="display:none">' +'</div>' +- '</div>' ++ '</div>') +'<div class="wbs-pcard wbs-fab-settings">' +'<div class="wbs-pcard-title">悬浮机器人</div>' +'<div class="wbs-theme-seg wbs-robot-seg" role="radiogroup" aria-label="机器人外观">' +- '<label class="wbs-theme-opt wbs-robot-option" title="跟随发送按钮的主题色"><input type="radio" name="wbs-robot-style" value="theme"><span>主题色</span></label>' ++ (codeBuddyTheme ? '' : '<label class="wbs-theme-opt wbs-robot-option" title="跟随发送按钮的主题色"><input type="radio" name="wbs-robot-style" value="theme"><span>主题色</span></label>') +'<label class="wbs-theme-opt wbs-robot-option" title="白底黑眼"><input type="radio" name="wbs-robot-style" value="white"><span>白色</span></label>' +'<label class="wbs-theme-opt wbs-robot-option" title="黑底白眼"><input type="radio" name="wbs-robot-style" value="black"><span>黑色</span></label>' +- '<label class="wbs-theme-opt wbs-robot-option" title="毛玻璃底与镂空眼睛"><input type="radio" name="wbs-robot-style" value="glass"><span>毛玻璃</span></label>' ++ (codeBuddyTheme ? '' : '<label class="wbs-theme-opt wbs-robot-option" title="毛玻璃底与镂空眼睛"><input type="radio" name="wbs-robot-style" value="glass"><span>毛玻璃</span></label>') +'</div>' +'<div class="wbs-ask-row">' +'<label class="wbs-ask-label" for="wbs-fab-auto-dock">自动贴边<span class="wbs-ask-hint">闲置 5 秒后收起,鼠标靠近即展开</span></label>' +'<label class="wbs-switch"><input type="checkbox" id="wbs-fab-auto-dock"><span class="wbs-switch-slider"></span></label>' +'</div></div>' +- '<div class="wbs-pcard">' ++ (codeBuddyTheme ? '' : '<div class="wbs-pcard">' +'<div class="wbs-theme-takeover-row">' +- '<div class="wbs-pcard-title">毛玻璃主题</div>' +- '<label class="wbs-switch"><input type="checkbox" id="wbs-theme-takeover" checked><span class="wbs-switch-slider"></span></label></div>' +- '</div>' +- '<div class="wbs-pcard wbs-wallpaper-card wbs-theme-managed" id="wbs-wallpaper-card" style="display:none">' ++ '<div class="wbs-pcard-title">接管主题</div>' ++ '<label class="wbs-switch"><input type="checkbox" id="wbs-theme-takeover" checked aria-label="接管主题"><span class="wbs-switch-slider"></span></label></div>' ++ '<div class="wbs-theme-managed" id="wbs-theme-appearance-options">' ++ '<div class="wbs-pcard-title">主题外观</div>' ++ '<div class="wbs-theme-seg" id="wbs-theme-seg" role="radiogroup" aria-label="主题外观">' ++ '<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="default"><span>浅色</span></label>' ++ '<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="dark"><span>深色</span></label>' ++ '<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="eye-care"><span>护眼绿</span></label>' ++ '<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="cyber-purple"><span>赛博紫</span></label>' ++ '<label class="wbs-theme-opt wbs-theme-option"><input type="radio" name="wbs-theme" value="nebula"><span>毛玻璃</span></label>' ++ '</div></div>' ++ '</div>') ++ (codeBuddyTheme ? '' : '<div class="wbs-pcard wbs-wallpaper-card wbs-theme-managed" id="wbs-wallpaper-card" style="display:none">' +'<div class="wbs-pcard-title">壁纸</div>' +'<div class="wbs-bg-source">' +'<button class="wbs-bg-src active" type="button" data-src="official">' + WBS_BRAND + ' 壁纸</button>' +@@ -9602,9 +9765,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-ask-row">' +'<label class="wbs-ask-label" for="wbs-text-shadow">消息文字阴影<span class="wbs-ask-hint">增强壁纸上的消息文字辨识度</span></label>' +'<label class="wbs-switch"><input type="checkbox" id="wbs-text-shadow" checked disabled><span class="wbs-switch-slider"></span></label>' +- '</div></div>';+ '</div></div>');wireThemePane();- applyAvatar();+ if (!codeBuddyTheme) applyAvatar();}// 增强 pane(构建:决策弹窗 + 开发者工具[默认隐藏,连点标题5次呼出])function buildEnhancePane() {@@ -9711,6 +9874,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<pre class="wbs-ac-log" id="wbs-ac-log">(未开启「会话异常中断」监控时无日志)</pre>' +'</div>' +'</div>';+ if (CAPS.enhance === 'composer') {+ // Reuse the shared controls and phrase list; only these two features+ // are enabled for CodeBuddy. Do not initialize hidden enhancements.+ Array.prototype.forEach.call(enhancePane.children, function (card) {+ if (card.id !== 'wbs-ac-card') card.remove();+ });+ Array.prototype.forEach.call(enhancePane.querySelectorAll('.wbs-nd-row'), function (row) {+ if (!row.querySelector('#wbs-sess-stash,#wbs-sess-phrase')) row.remove();+ });+ wireSessionControls();+ return;+ }wireEnhancePane();}@@ -10211,8 +10386,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!themePane) return;var card = themePane.querySelector('#wbs-wallpaper-card');if (!card) return;- // 主题页固定使用毛玻璃;开关只控制这组玻璃主题设置是否可见。- var visible = sessState.themeTakeover;+ var visible = sessState.themeTakeover && themeId === 'nebula';card.style.display = visible ? '' : 'none';var textCard = themePane.querySelector('#wbs-text-shadow-card');if (textCard) textCard.style.display = visible ? '' : 'none';@@ -10234,6 +10408,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var themeSwitch = themePane.querySelector('#wbs-theme-takeover');if (themeSwitch) {themeSwitch.checked = sessState.themeTakeover;+ if (CAPS.themeTakeover === false) { themeSwitch.disabled = true; themeSwitch.title = 'CodeBuddy 暂不支持毛玻璃主题'; }if (!themeSwitch.dataset.wbsWired) {themeSwitch.dataset.wbsWired = '1';themeSwitch.addEventListener('change', function () { setSessionSwitchWire('themeTakeoverEnabled', this); });@@ -10272,7 +10447,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {dockSwitch.checked = fabQuietMode.isEnabled();dockSwitch.addEventListener('change', function () { fabQuietMode.setEnabled(this.checked); });}- // 主题页只提供毛玻璃主题开关;壁纸仍通过下方来源按钮管理。+ // 壁纸通过下方来源按钮管理,主题单选项使用 change 事件。themePane.addEventListener('click', function (e) {var t = e.target;var srcBtn = t.closest ? t.closest('.wbs-bg-src') : null;@@ -10296,6 +10471,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});themePane.addEventListener('change', function (e) {var t = e.target;+ if (t && t.name === 'wbs-theme' && t.checked) {+ selectTheme(t.value);+ return;+ }if (t && t.name === 'wbs-avatar-preset') {try { avatarLibrary.select(t.value); }catch (_) { toast('头像保存失败,请清理存储空间后重试', true, root); }@@ -10696,6 +10875,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});root.querySelector('[data-act="close"]').addEventListener('click', function () { setOpen(false); });+ function closePanelOnOutsidePointerDown(event) {+ if (!state.open || (event.button !== undefined && event.button !== 0)) return;+ // Popovers can be portaled to body. Treat those and modal masks as part+ // of the panel, including controls inside a shadow root's composed path.+ var path = typeof event.composedPath === 'function' ? event.composedPath() : [event.target];+ for (var i = 0; i < path.length; i++) {+ var node = path[i];+ if (!node) continue;+ if (node === root || (node.nodeType && root.contains(node))) return;+ if (node.closest && node.closest('[data-wbs-panel-overlay],.wbs-modal-mask,.wbs-panel-modal-mask')) return;+ }+ setOpen(false);+ }+ listen(document, 'pointerdown', closePanelOnOutsidePointerDown, true);+// 供 daemon 程序化开合面板:等价于「点机器人按钮/点关闭按钮」,复用同一 setOpen,// 保证 DOM(.show/.hidden) 与 state.open 始终一致、完全可逆,不做任何 display 硬改。// daemon 经 CDP dispatch: window.dispatchEvent(new CustomEvent('workdaddy:panel-open',{detail:{open:boolean}}))@@ -10708,7 +10902,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {registerDisposer(function () { try { window.removeEventListener('workdaddy:panel-open', panelOpenBridge); } catch (_) {} });// 登录新账号:弹窗二选一 —— 方法一 假退出当前账号 / 方法二 无感登录- logoutBtn.addEventListener('click', function () {+ if (logoutBtn) logoutBtn.addEventListener('click', function () {if (this.disabled) return;openLoginChoice();});@@ -10874,16 +11068,42 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// ===== 主题系统(WorkDaddy 换肤):segmented 切换 =====// 主题 = CSS 变量覆盖(--wb-* / --dc-*),daemon 通过 CDP 注入 <style>。- // 只提供四个入口:官方主题(default) 与 WorkDaddy 官方主题(nebula)、官方内置深色主题(eye-care/cyber-purple)- // 默认选中「WorkBuddy 默认主题」(default):未设置/异常时回退到 default 而非 nebula(用户要求)+ // 五种外观共用主题接管;只有毛玻璃使用壁纸、蒙版和背景模糊。var ALLOWED_THEMES = ['default', 'dark', 'nebula', 'eye-care', 'cyber-purple'];+ var currentThemeId = 'default';+ var themeSelectionSerial = 0;+ function syncThemeSelection(id) {+ currentThemeId = ALLOWED_THEMES.indexOf(id) >= 0 ? id : 'default';+ if (themePane) themePane.querySelectorAll('#wbs-theme-seg input[name="wbs-theme"]').forEach(function (input) {+ input.checked = input.value === currentThemeId;+ input.closest('.wbs-theme-opt').classList.toggle('active', input.checked);+ });+ syncWallpaperCardVisibility(currentThemeId);+ }function loadThemes() {- api('/api/themes')+ var serial = themeSelectionSerial;+ return api('/api/themes').then(function (d) {- syncWallpaperCardVisibility('nebula');+ if (serial === themeSelectionSerial) syncThemeSelection(d.current);}).catch(function () {});}+ function selectTheme(id) {+ if (!sessState.themeTakeover || CAPS.themeTakeover === false || ALLOWED_THEMES.indexOf(id) < 0) return;+ var previous = currentThemeId;+ var serial = ++themeSelectionSerial;+ syncThemeSelection(id);+ return applyTheme(id).then(function () {+ if (serial !== themeSelectionSerial) return;+ var names = { 'default': '浅色', 'dark': '深色', 'eye-care': '护眼绿', 'cyber-purple': '赛博紫', 'nebula': '毛玻璃' };+ toast('已应用主题「' + names[id] + '」', false, root);+ }).catch(function (error) {+ if (serial !== themeSelectionSerial) return;+ syncThemeSelection(previous);+ toast('应用主题失败: ' + (error.message || error), true, root);+ loadThemes();+ });+ }function applyTheme(id) {return api('/api/theme-apply', {method: 'POST',@@ -10891,12 +11111,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {body: JSON.stringify({ id: id }),});}- // 当前主题 id(壁纸切换目标):segmented 激活项;无则 nebula+ // 壁纸控件仅在毛玻璃下显示;保留默认主题下上传壁纸的兼容目标。function themeSelectValue() {- var seg = root.querySelector('#wbs-theme-seg');- var act = seg ? seg.querySelector('.wbs-theme-opt.active') : null;- var id = act ? act.getAttribute('data-wbs-theme-option') : null;- return id && id !== 'default' && id !== 'dark' ? id : 'nebula';+ return currentThemeId !== 'default' && currentThemeId !== 'dark' ? currentThemeId : 'nebula';}// 页面主题由 daemon 在早期注入/加载时恢复;不要延迟 POST 旧主题,// 否则旧页面的异步请求可能覆盖用户刚选择的主题。@@ -11003,7 +11220,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {applyAvatar();});function applyAvatar() {- if (!avatarLibrary) return;+ if (CAPS.nativeComposer || !avatarLibrary) return;var saved = avatarLibrary.snapshot();var customList = root.querySelector('#wbs-avatar-custom-list');if (customList) {@@ -11621,6 +11838,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var acMonitorLogFrame = null;function acScheduleMonitorLogRender() {+ if (CAPS.enhance === false || CAPS.enhance === 'composer') return;if (acMonitorLogFrame != null) return;var raf = window.requestAnimationFrame || function (fn) { return setTimeout(fn, 40); };acMonitorLogFrame = raf(function () {@@ -12482,6 +12700,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// window (the SDK emits that transient state during a switch).if (conversations && 'currentId' in conversations) return '';} catch (e) {}+ if (PROFILE_ID === 'codebuddy-cn' || PROFILE_ID === 'codebuddy-intl') {+ // CodeBuddy has no wb SDK, and disabling composer enhancements also+ // disables their adapter warmup. Read the mounted official adapter+ // without caching it or enabling any queue/composer behavior.+ try {+ var nativeAdapter = WBS_COMPAT.findQueueAdapter(document);+ var nativeId = nativeAdapter && nativeAdapter.adapter && nativeAdapter.adapter.currentActiveSessionId;+ if (nativeId) return String(nativeId);+ } catch (_) {}+ try { return String(WBS_COMPAT.getSelectedConversationId(document) || ''); } catch (_) {}+ return '';+ }try {var a = window.__wbsAdapter;if (a && a.currentActiveSessionId) return a.currentActiveSessionId;@@ -13696,6 +13926,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}/** 按 daemon 状态启动/停止监控(注入后、增强页构建时、开关切换时都会调用) */function syncAutoContinueMonitor(d) {+ if (CAPS.enhance === false || CAPS.enhance === 'composer') return;if (!d) return;if (!d.platformSupported || !AC_SUPPORTED) {if (acRunning) { acRunning = false; acLog('monitor-stop-by-state', { reason: 'unsupported' }); acStopMonitor(); }@@ -13706,12 +13937,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}/** 注入后无条件检查一次开关状态(不依赖打开增强页),根除"开关开着但监控没跑" */function ensureAutoContinueMonitor() {+ if (CAPS.enhance === false || CAPS.enhance === 'composer') return;api('/api/auto-continue').then(function (d) {if (d && d.ok) syncAutoContinueMonitor(d);}).catch(function () {});}/** 每次打开面板时校验:开关开着但本地自定义指令块已丢失(外部重写/误删)→ 请求 daemon 补写(不弹 toast) */function acCheckPromptOnOpen() {+ if (CAPS.enhance === false || CAPS.enhance === 'composer') return;api('/api/auto-continue').then(function (d) {if (!d || !d.ok) return;if (d.enabled && !d.promptBlockPresent) {@@ -15024,7 +15257,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var activationApi = null;try {activationApi = WBS_COMPAT && typeof WBS_COMPAT.findConversationActivationApi === 'function'- ? WBS_COMPAT.findConversationActivationApi(document) : null;+ ? WBS_COMPAT.findConversationActivationApi(document, {profileId:PROFILE_ID}) : null;} catch (_) {}function confirmActivation() {setBuildTimeout(function () {@@ -15838,7 +16071,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var debugPanel = document.createElement('div');debugPanel.id = 'wbs-debug-panel';debugPanel.style.cssText = 'display:none;position:fixed;right:8px;top:8px;z-index:2147483647;background:rgba(0,0,0,.86);color:#fff;font:11px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;padding:9px 12px;border-radius:6px;max-width:420px;white-space:pre-wrap;box-shadow:0 6px 18px rgba(0,0,0,.4);border:1px solid rgba(255,255,255,.1);';- document.body.appendChild(debugPanel);+ mountPersistentOverlay(debugPanel);function updateDebugPanel() {if (!alive) return;try {@@ -16121,10 +16354,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'html[data-wbs-theme-id="nebula"] .wbs-message-nav-marker:not(:hover):not(:focus-visible){box-shadow:none}','@media (prefers-reduced-motion:reduce){.wbs-message-nav-marker,.wbs-message-nav-dot,.wbs-message-nav-tooltip{transition:none!important}.wbs-message-nav-highlight{animation:none!important}}',/* 官网演示机器人:尺寸按 2 倍绘制,保留现有 0.5 缩放与停靠/拖动坐标。 */- '.wbs-fab[data-wbs-robot-style="theme"],.wbs-root[data-wbs-robot-style="theme"] .wbs-automation-stop{--wbs-robot-shell:var(--wb-button-primary-bg);--wbs-robot-eye:var(--wb-button-primary-fg);--wbs-robot-rim:var(--wb-border-subtle)}',+ // CodeBuddy Agents 不提供 --wb-*;优先沿用客户端按钮色,最终回退到现有黑白机器人。+ '.wbs-fab[data-wbs-robot-style="theme"],.wbs-root[data-wbs-robot-style="theme"] .wbs-automation-stop{--wbs-robot-shell:var(--wb-button-primary-bg,var(--vscode-button-background,#111));--wbs-robot-eye:var(--wb-button-primary-fg,var(--vscode-button-foreground,#fff));--wbs-robot-rim:var(--wb-border-subtle,rgba(255,255,255,.55))}','.wbs-fab[data-wbs-robot-style="black"]{--wbs-robot-shell:#111;--wbs-robot-eye:#fff;--wbs-robot-rim:rgba(255,255,255,.14)}','.wbs-fab[data-wbs-robot-style="glass"]{--wbs-robot-shell:color-mix(in srgb,var(--wb-bg-popover,#fff) 42%,transparent);--wbs-robot-eye:transparent;--wbs-robot-blur:blur(14px) saturate(1.3);--wbs-robot-rim:color-mix(in srgb,var(--wb-color-text-primary,#222) 18%,transparent)}',- '.wbs-fab[data-wbs-robot-style="white"]{--wbs-robot-shell:#fff;--wbs-robot-eye:#111;--wbs-robot-rim:rgba(255,255,255,.55)}',+ '.wbs-fab[data-wbs-robot-style="white"]{--wbs-robot-shell:#fff;--wbs-robot-eye:#111;--wbs-robot-rim:rgba(0,0,0,.14)}','.wbs-root[data-wbs-robot-style="black"] .wbs-automation-stop{--wbs-robot-shell:#111;--wbs-robot-eye:#fff;--wbs-robot-rim:rgba(255,255,255,.14)}.wbs-root[data-wbs-robot-style="glass"] .wbs-automation-stop{--wbs-robot-shell:color-mix(in srgb,var(--wb-bg-popover,#fff) 42%,transparent);--wbs-robot-eye:var(--wb-color-text-primary,#222);--wbs-robot-rim:color-mix(in srgb,var(--wb-color-text-primary,#222) 18%,transparent)}.wbs-root[data-wbs-robot-style="white"] .wbs-automation-stop{--wbs-robot-shell:#fff;--wbs-robot-eye:#111;--wbs-robot-rim:rgba(0,0,0,.12)}','.wbs-automation-stop{position:fixed;z-index:2147483647;box-sizing:border-box;min-width:94px;height:32px;padding:0 11px;border:1px solid var(--wbs-robot-rim,rgba(255,255,255,.14));border-radius:8px;background:var(--wbs-robot-shell,#111);color:var(--wbs-robot-eye,#fff);box-shadow:0 3px 10px rgba(0,0,0,.18);display:flex;align-items:center;justify-content:center;gap:6px;cursor:pointer;font:inherit;font-size:12px;line-height:1;letter-spacing:0;white-space:nowrap;transition:opacity .15s,box-shadow .15s}.wbs-automation-stop[hidden]{display:none}.wbs-automation-stop:hover{box-shadow:0 4px 12px rgba(0,0,0,.24);opacity:.88}.wbs-automation-stop:focus-visible{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:3px}.wbs-automation-stop:disabled{cursor:default;opacity:.68}.wbs-automation-stop svg{flex:0 0 auto}.wbs-automation-stop-label{display:block}.wbs-automation-stop.is-stopping svg{opacity:.7}@keyframes wbs-auto-stopping{to{transform:rotate(360deg)}}','.wbs-fab{--wbs-robot-shell:#111;--wbs-robot-eye:#fff;--wbs-robot-blur:none;--wbs-robot-rim:rgba(255,255,255,.55);position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;will-change:transform;transition:transform .22s cubic-bezier(.22,1,.36,1)}',@@ -16142,6 +16376,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-fab .click > span:not(.wbs-fab-antenna){display:none}','.wbs-fab .button.shadow{display:none}','.wbs-fab .button{position:relative;left:0;top:0;transform:none;cursor:pointer;border:0;background:var(--wbs-robot-shell);box-shadow:inset 0 2px 0 var(--wbs-robot-rim),0 8px 10px rgba(0,0,0,.12);backdrop-filter:var(--wbs-robot-blur);-webkit-backdrop-filter:var(--wbs-robot-blur);border-radius:22px;display:flex;align-items:center;justify-content:center;width:82px;height:64px;box-sizing:content-box;padding:0;margin:0;outline:none;transition:box-shadow .2s}',+ '.wbs-fab[data-wbs-robot-style="white"] .button{box-shadow:none;filter:drop-shadow(0 0 1px rgba(0,0,0,.08)) drop-shadow(0 0 7px rgba(0,0,0,.16))}',/* 贴消息队列时(queue 上方)保持纯色背景(与默认黑色一致,逻辑保留) */'.wbs-fab.fab--solid .button{background:var(--wbs-robot-shell)}','.wbs-fab .button:before,.wbs-fab .button:after{display:none}',@@ -16187,6 +16422,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'html[data-wbs-theme-id="nebula"] .wbs-panel,html[data-wbs-theme-id="nebula"] .wbs-modal,html[data-wbs-theme-id="nebula"] .wbs-account-note-popover,html[data-wbs-theme-id="nebula"] .wbs-status-popover,html[data-wbs-theme-id="nebula"] .wbs-credit-rotation-notice{--wb-button-primary-bg:var(--wb-palette-white-90);--wb-button-primary-fg:var(--wb-bg-primary)}','.wbs-panel{position:absolute;right:0;bottom:0;width:720px;max-width:94vw;height:650px;max-height:calc(100vh - 110px);background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden;backdrop-filter:blur(28px) saturate(1.25);-webkit-backdrop-filter:blur(28px) saturate(1.25)}','.wbs-panel.show{display:flex}',+ '.wbs-root.wbs-panel-light,[data-wbs-appearance="light"]{color-scheme:light;--wb-bg-primary:#fff;--wb-bg-secondary:#fff;--wb-bg-tertiary:#f2f2f2;--wb-bg-popover:#fff;--wb-bg-input:#fff;--wb-bg-hover:#f5f5f5;--wb-bg-active:#eee;--wb-border-subtle:#f0f0f0;--wb-border-default:#e5e5e5;--wb-border-hover:#ccc;--wb-border-strong:#ccc;--wb-color-text-primary:#1f1f1f;--wb-color-text-secondary:#666;--wb-color-text-tertiary:#999;--wb-icon-secondary:#666;--wb-icon-tertiary:#999;--wb-button-primary-bg:#1f1f1f;--wb-button-primary-fg:#fff;--wb-button-primary-bg-hover:#333;--wb-button-primary-bg-disabled:#eee;--wb-button-primary-fg-disabled:#999}',+ '.wbs-panel-light .wbs-panel{background:var(--wb-bg-popover);color:var(--wb-color-text-primary)}',// 英文文案更长:英文面板额外加宽,配合 label 自适应避免挤压'html[data-wbs-language="en"] .wbs-panel{width:880px}',// EN 下固定宽度 label 容易溢出:phone/credit/token 列的 label 释放为自适应宽度@@ -16203,7 +16440,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-title-wrap{display:flex;flex-direction:column;align-items:flex-start;min-width:0}','.wbs-title-row{display:flex;align-items:center;flex-wrap:wrap;gap:6px 9px;min-width:0}','.wbs-title{font-family:"Avenir Next",Avenir,"Segoe UI Variable Display","Segoe UI",sans-serif;font-size:15px;line-height:1.15;font-weight:750;letter-spacing:-.55px;color:var(--wb-color-text-primary,#1f1f1f);white-space:nowrap;user-select:none}',- '.wbs-version-line{margin:0;color:var(--wb-color-text-tertiary,#a3a6ad);font-size:10px;font-weight:400;line-height:1.2;letter-spacing:0;font-variant-numeric:tabular-nums;white-space:nowrap}',+ '.wbs-model-shared-hint{align-self:center;font-size:11px;color:var(--wb-color-text-secondary,#666);line-height:1.5}',+ '.wbs-version-line{margin:0;color:var(--wb-color-text-tertiary,#a3a6ad);font-size:9px;font-weight:400;line-height:1.2;letter-spacing:0;font-variant-numeric:tabular-nums;white-space:nowrap}',/* 元素检查拾取按钮(隐藏入口,连点标题 5 次显示) */'.wbs-pick-btn{flex:0 0 auto;width:22px;height:22px;border:none;border-radius:7px;background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 14%,transparent);color:var(--wb-accent-blue,#4f86ff);font-size:12px;line-height:1;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:background .15s}','.wbs-pick-btn:hover{background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 24%,transparent)}',@@ -16376,9 +16614,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-theme-takeover-row:has(#wbs-theme-takeover:not(:checked)){margin-bottom:0;padding-bottom:0;border-bottom:0}','.wbs-explore-inline{position:fixed;left:auto;display:flex;align-items:center;justify-content:center;cursor:pointer;flex-shrink:0;z-index:auto;top:0;right:0;overflow:visible;padding:0 8px}',/* 复用暂存按钮视觉(wbs-stash-inline 提供 32px 圆形/背景/阴影),但 hover 不变宽 */- '.wbs-stash-inline.wbs-explore-inline:hover,.wbs-stash-inline.wbs-explore-inline.wbs-stash-inline-inline:hover{width:32px!important;min-width:32px!important;height:32px!important;border-radius:50%;padding:0 8px}',+ '.wbs-stash-inline.wbs-explore-inline:not(.wbs-composer-native):hover,.wbs-stash-inline.wbs-explore-inline.wbs-stash-inline-inline:not(.wbs-composer-native):hover{width:32px!important;min-width:32px!important;height:32px!important;border-radius:50%;padding:0 8px}',/* 图标常显;hover 无任何自身动画 */'.wbs-explore-ico{display:flex;align-items:center;justify-content:center}',+ // CodeBuddy 原生 IconButton:24px 方形、4px 圆角;仅暂存按钮保留展开文案。+ '.wbs-stash-inline.wbs-composer-native,.wbs-stash-inline.wbs-composer-native:hover{box-sizing:border-box;width:24px!important;min-width:24px!important;max-width:24px;height:24px!important;border-radius:4px!important;padding:0!important;justify-content:center;box-shadow:none;transition:background .15s}',+ '.wbs-stash-inline.wbs-composer-native:not(.wbs-explore-inline){max-width:none;padding:0 4px!important;justify-content:flex-start;transition:width .18s,background .15s}',+ '.wbs-stash-inline.wbs-composer-native:not(.wbs-explore-inline):hover{width:calc(39px + var(--wbs-stash-text-width,65px))!important;padding-right:12px!important}',+ '.wbs-composer-native .wbs-stash-ico svg,.wbs-composer-native .wbs-explore-ico svg{width:16px;height:16px}','.wbs-explore-inline.wbs-stash-inline-inline{position:relative;z-index:99999}','.wbs-explore-inline:active{transform:none}','.wbs-explore-pop{position:fixed;bottom:0;left:0;transform:translateY(6px);width:280px;max-width:84vw;opacity:0;visibility:hidden;transition:opacity .18s ease,transform .18s ease,visibility 0s linear .18s;z-index:22;pointer-events:none;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif}',@@ -16572,7 +16815,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-model-toolbar-spacer{flex:1}','.wbs-model-imports{display:flex;align-items:center;gap:5px;flex-wrap:wrap}','.wbs-model-import:disabled{opacity:.5;cursor:not-allowed}',- '.wbs-model-third-party{position:relative;display:inline-flex}',+ '.wbs-model-third-party,.wbs-model-client-import{position:relative;display:inline-flex}','.wbs-model-source-menu{position:absolute;right:0;top:calc(100% + 4px);z-index:10;min-width:120px;padding:4px;border:1px solid var(--wb-border-default,#ddd);border-radius:8px;background:var(--wb-bg-popover,#fff);box-shadow:0 6px 20px rgba(0,0,0,.16)}','.wbs-model-source-menu button{width:100%;padding:8px;text-align:left;border:0;border-radius:5px;background:transparent;color:var(--wb-color-text-primary,#222);font:inherit;font-size:12px;cursor:pointer}','.wbs-model-source-menu button:hover,.wbs-model-source-menu button:focus-visible{background:var(--wb-bg-hover,#f3f3f3)}',@@ -16832,6 +17075,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-wp-custom .wbs-wp-badge{background:rgba(0,0,0,.35)}',/* 主题切换 segmented(默认 / WorkDaddy / 官方内置深色主题):样式与下方壁纸来源切换按钮统一 */'.wbs-theme-seg{display:flex;background:var(--wb-bg-tertiary,#f0f0f0);border-radius:10px;padding:3px;gap:3px;margin-bottom:8px}',+ '.wbs-theme-option{position:relative;text-align:center;line-height:normal}.wbs-theme-option input{position:absolute;opacity:0;width:1px;height:1px}.wbs-theme-option:has(input:focus-visible){outline:2px solid var(--wb-icon-secondary);outline-offset:1px}','.wbs-theme-opt{flex:1;min-width:0;padding:6px 4px;border:none;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;font-family:inherit;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}','.wbs-theme-opt:hover{color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-theme-opt.active{background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.2)}',diff --git a/scripts/install-win.ps1 b/scripts/install-win.ps1index 47f4e32..a9a2852 100644--- a/scripts/install-win.ps1+++ b/scripts/install-win.ps1@@ -25,14 +25,14 @@ try { . (Join-Path $PSScriptRoot 'windows-process-boundary.ps1') } catch {}$ErrorActionPreference = 'Continue'if ([string]::IsNullOrWhiteSpace($Profile) -or $Profile -eq '__WBS_DEFAULT_PROFILE__') { $Profile = 'workbuddy-cn' }-if ($Profile -ne 'workbuddy-ai') { $Profile = 'workbuddy-cn' }+if ($Profile -notin @('workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl')) { throw 'Unknown client profile' }$env:WBSWITCH_PROFILE = $Profile-$productName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy AI' } else { 'WorkDaddy' }+$productName = (@{'workbuddy-cn'='WorkDaddy'; 'workbuddy-ai'='WorkDaddy AI'; 'codebuddy-cn'='CodeDaddy CN'; 'codebuddy-intl'='CodeDaddy'})[$Profile]if ([string]::IsNullOrWhiteSpace($AppDir)) { $AppDir = Join-Path $env:LOCALAPPDATA (Join-Path 'Programs' $productName) }$targetScripts = Join-Path $AppDir 'scripts'$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'-$dataDir = if ($Profile -eq 'workbuddy-ai') { Join-Path $dataRoot 'profiles\workbuddy-ai' } else { $dataRoot }-$uiPort = if ($Profile -eq 'workbuddy-ai') { 47833 } else { 47832 }+$dataDir = if ($Profile -eq 'workbuddy-cn') { $dataRoot } else { Join-Path $dataRoot ('profiles\' + $Profile) }+$uiPort = (@{'workbuddy-cn'=47832; 'workbuddy-ai'=47833; 'codebuddy-cn'=47834; 'codebuddy-intl'=47835})[$Profile]$env:WBSWITCH_PORT = [string]$uiPort$sentryReporter = Join-Path $SrcDir 'sentry-report.js'$nodeBin = $nulldiff --git a/scripts/install.sh b/scripts/install.shindex 8f3d030..a74f29e 100644--- a/scripts/install.sh+++ b/scripts/install.sh@@ -95,7 +95,7 @@ if ! "$NODE" "$DIR/scripts/sync.js"; thenfiecho "==> 清理旧 launchd 注册(WorkDaddy / WorkDaddy AI 不再登录自启)"-for old_profile in workbuddy-cn workbuddy-ai codebuddy-cn codebuddy-intl; do+for old_profile in "$PROFILE"; doold_label="com.workbuddy.workdaddy.${old_profile}"old_plist="$HOME/Library/LaunchAgents/${old_label}.plist"launchctl bootout "gui/$(id -u)" "$old_plist" 2>/dev/null || truediff --git a/scripts/launch-gui-linux.sh b/scripts/launch-gui-linux.shindex 29fcd39..c31ce58 100755--- a/scripts/launch-gui-linux.sh+++ b/scripts/launch-gui-linux.sh@@ -220,6 +220,16 @@ main_menu() {# 用法: bash scripts/launch-gui-linux.sh [cn|ai|both|services|info]# 不带参数 = 弹出选择框;带参数 = 直接执行对应动作(供独立桌面快捷方式使用)REQUEST="${1:-}"+case "$REQUEST" in+ codebuddy-cn|codebuddy-intl)+ CODE_NAME="CodeBuddy"; [ "$REQUEST" = codebuddy-cn ] && CODE_NAME="CodeBuddy CN"+ CODE_STATUS="$(env WBSWITCH_PROFILE="$REQUEST" bash "$REL" --status 2>/dev/null)"+ if [ "$(field "$CODE_STATUS" app)" = running ] && [ "$(field "$CODE_STATUS" cdp_ready)" != yes ]; then+ confirm_restart "$CODE_NAME" || exit 0+ fi+ run_action "正在启动 $CODE_NAME" env WBSWITCH_PROFILE="$REQUEST" bash "$REL" --ensure+ exit $? ;;+esaccase "$REQUEST" in""|cn|ai|both|services|info) ;;-h|--help)diff --git a/scripts/lib.js b/scripts/lib.jsindex 4cab5f2..7a0de47 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -223,7 +223,7 @@ const AUTH_FILE = process.env.WBSWITCH_AUTH_FILE !== undefinedconst LOGOUT_MARKER = `${AUTH_FILE}.logged-out`;const EXPLICIT_AUTH_FILE = process.env.WBSWITCH_AUTH_FILE !== undefined;-const DYNAMIC_AUTH_DISCOVERY = !EXPLICIT_AUTH_FILE && !!ACTIVE_PROFILE.authFile && !!ACTIVE_PROFILE.capabilities.accounts;+const DYNAMIC_AUTH_DISCOVERY = ACTIVE_PROFILE.kind !== 'codebuddy' && !EXPLICIT_AUTH_FILE && !!ACTIVE_PROFILE.authFile && !!ACTIVE_PROFILE.capabilities.accounts;function authDir(file = AUTH_FILE) {return file ? path.dirname(path.resolve(file)) : null;diff --git a/scripts/prepare-win-install.ps1 b/scripts/prepare-win-install.ps1index df61523..cf9809d 100644--- a/scripts/prepare-win-install.ps1+++ b/scripts/prepare-win-install.ps1@@ -1,7 +1,7 @@param([Parameter(Mandatory = $true)][string]$BoundaryPath,[Parameter(Mandatory = $true)][string]$AppDir,- [ValidateSet('workbuddy-cn', 'workbuddy-ai')][string]$Profile = 'workbuddy-cn',+ [ValidateSet('workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl')][string]$Profile = 'workbuddy-cn',[Parameter(Mandatory = $true)][string]$ExpectedVersion)@@ -25,8 +25,8 @@ try {(New-Object Text.UTF8Encoding($false))). $BoundaryPath$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'- $dataDir = if ($Profile -eq 'workbuddy-ai') { Join-Path $dataRoot 'profiles\workbuddy-ai' } else { $dataRoot }- $uiPort = if ($Profile -eq 'workbuddy-ai') { 47833 } else { 47832 }+ $dataDir = if ($Profile -eq 'workbuddy-cn') { $dataRoot } else { Join-Path $dataRoot ('profiles\' + $Profile) }+ $uiPort = (@{'workbuddy-cn'=47832; 'workbuddy-ai'=47833; 'codebuddy-cn'=47834; 'codebuddy-intl'=47835})[$Profile]Stop-VerifiedWorkDaddyLifecycle `-DataDir $dataDir `-Port $uiPort `diff --git a/scripts/profiles.js b/scripts/profiles.jsindex 95187e8..717401a 100644--- a/scripts/profiles.js+++ b/scripts/profiles.js@@ -37,13 +37,29 @@ const appPath = (name, winExec, winDir) =>? plat.linuxAppBinary(LINUX_APP_KIND[name] || 'workbuddy'): `/Applications/${name}.app`;+// Current CN builds use "CodeBuddy CN.exe" while international builds use+// "CodeBuddy.exe". Older CN builds used the international filename, so product+// metadata remains the final identity check before selecting or stopping one.+function isCodeBuddyBinary(binary, profileId) {+ if (!['codebuddy-cn','codebuddy-intl'].includes(profileId)) return false;+ try {+ const name = path.basename(binary).toLowerCase();+ const validName = profileId === 'codebuddy-cn'+ ? name === 'codebuddy cn.exe' || name === 'codebuddy.exe'+ : name === 'codebuddy.exe';+ if (!validName) return false;+ const product = JSON.parse(fs.readFileSync(path.join(path.dirname(binary),'resources','app','product.json'),'utf8'));+ return product.applicationName === (profileId === 'codebuddy-cn' ? 'buddycn' : 'buddy');+ } catch (_) { return false; }+}+function sharedDataDir() {return path.join(appSupport, 'WorkDaddy');}const PROFILES = {'workbuddy-cn': {- id: 'workbuddy-cn', name: 'WorkBuddy', appName: 'WorkDaddy', region: 'cn', kind: 'workbuddy', mode: 'agents',+ id: 'workbuddy-cn', name: 'WorkBuddy', appName: 'WorkDaddy', packageName: 'WorkDaddy', region: 'cn', kind: 'workbuddy', mode: 'agents',appPath: appPath('WorkBuddy'),dataRoot: path.join(home, '.workbuddy'),authFile: path.join(extensionAuth, 'workbuddy-desktop.info'),@@ -55,7 +71,7 @@ const PROFILES = {targetHints: ['workbuddy'],},'workbuddy-ai': {- id: 'workbuddy-ai', name: 'WorkBuddy AI', appName: 'WorkDaddy AI', region: 'intl', kind: 'workbuddy', mode: 'agents',+ id: 'workbuddy-ai', name: 'WorkBuddy AI', appName: 'WorkDaddy AI', packageName: 'WorkDaddy-AI', region: 'intl', kind: 'workbuddy', mode: 'agents',// Windows 安装目录无空格:%LOCALAPPDATA%\Programs\WorkBuddyAI\WorkBuddyAI.exe(PR#8 实机确认)appPath: appPath('WorkBuddy AI', 'WorkBuddyAI.exe', 'WorkBuddyAI'),dataRoot: path.join(home, '.workbuddy-ai'),@@ -65,29 +81,37 @@ const PROFILES = {// 两者独立(勿改共用)。“从 XX 导入”即把另一端文件中的模型合并进本端文件。modelsFile: path.join(home, '.workbuddy-ai', 'models.json'),apiHost: 'https://www.workbuddy.ai',- capabilities: { accounts: true, sessions: true, models: true, stashPrompt: true, theme: true, checkin: true, growthDaily: false },+ capabilities: { accounts: true, sessions: true, models: true, stashPrompt: true, theme: true, checkin: true, growthDaily: false, builtinAutomations: false },targetHints: ['workbuddy ai', 'workbuddy'],},'codebuddy-cn': {- id: 'codebuddy-cn', name: 'CodeBuddy CN', region: 'cn', kind: 'codebuddy', mode: 'auto',- appPath: appPath('CodeBuddy CN'),- dataRoot: path.join(appSupport, 'CodeBuddy CN'),- authFile: null,+ id: 'codebuddy-cn', name: 'CodeBuddy CN', appName: 'CodeDaddy CN', packageName: 'CodeDaddy-CN', nativeDebugPort: 9244, oauthPlatform:'ide', authApiHost:'https://copilot.tencent.com', region: 'cn', kind: 'codebuddy', mode: 'auto',+ appPath: appPath('CodeBuddy CN', 'CodeBuddy CN.exe'),+ binaryNames: ['CodeBuddy CN.exe', 'CodeBuddy.exe'],+ historyRoot: path.dirname(path.dirname(extensionAuth)),+ userDataRoot: path.join(appSupport, 'CodeBuddy CN'),+ dataRoot: path.join(home, '.codebuddy'),+ authFile: path.join(sharedDataDir(), 'profiles', 'codebuddy-cn', 'native-current.info'),sessionDb: path.join(appSupport, 'CodeBuddy CN', 'codebuddy-sessions.vscdb'),- modelsFile: path.join(appSupport, 'CodeBuddy CN', 'User', 'globalStorage', 'state.vscdb'),+ // CodeBuddy 的自定义模型配置由 Electron 主进程写入用户目录;+ // User/globalStorage/state.vscdb 只保存 VS Code 状态,不是模型配置。+ modelsFile: path.join(home, '.codebuddy', 'models.json'),apiHost: 'https://www.codebuddy.cn',- capabilities: { accounts: false, sessions: true, models: false, stashPrompt: false, theme: false, checkin: true },+ capabilities: { accounts: true, sessions: true, models: true, stashPrompt: false, nativeComposer: true, theme: true, themeTakeover: false, enhance: false, panelAppearance: 'light', robotStyle: 'black', apiTransport: 'cdp', checkin: true, growthDaily: true },targetHints: ['codebuddy cn'],},'codebuddy-intl': {- id: 'codebuddy-intl', name: 'CodeBuddy', region: 'intl', kind: 'codebuddy', mode: 'auto',+ id: 'codebuddy-intl', name: 'CodeBuddy', appName: 'CodeDaddy', packageName: 'CodeDaddy', nativeDebugPort: 9245, oauthPlatform:'ide', authApiHost:'https://www.codebuddy.ai', region: 'intl', kind: 'codebuddy', mode: 'auto',appPath: appPath('CodeBuddy'),- dataRoot: path.join(appSupport, 'CodeBuddy'),- authFile: null,+ binaryNames: ['CodeBuddy.exe'],+ historyRoot: path.dirname(path.dirname(extensionAuth)),+ userDataRoot: path.join(appSupport, 'CodeBuddy'),+ dataRoot: path.join(home, '.codebuddy'),+ authFile: path.join(sharedDataDir(), 'profiles', 'codebuddy-intl', 'native-current.info'),sessionDb: path.join(appSupport, 'CodeBuddy', 'codebuddy-sessions.vscdb'),- modelsFile: path.join(appSupport, 'CodeBuddy', 'User', 'globalStorage', 'state.vscdb'),+ modelsFile: path.join(home, '.codebuddy', 'models.json'),apiHost: 'https://www.codebuddy.ai',- capabilities: { accounts: false, sessions: true, models: false, stashPrompt: false, theme: false, checkin: true },+ capabilities: { accounts: true, sessions: true, models: true, stashPrompt: false, nativeComposer: true, theme: true, themeTakeover: false, enhance: false, panelAppearance: 'light', robotStyle: 'black', apiTransport: 'cdp', checkin: false, builtinAutomations: false },targetHints: ['codebuddy'],},};@@ -143,7 +167,7 @@ function listProfiles() { return Object.values(PROFILES).map((p) => ({ ...p, capfunction listInstalledModelSources(activeId) {const active = PROFILES[activeId];- return ['workbuddy-cn', 'workbuddy-ai']+ return Object.keys(PROFILES).filter((id) => id !== activeId).map((id) => PROFILES[id]).map((profile) => {@@ -161,8 +185,7 @@ function listInstalledModelSources(activeId) {available,shared,};- })- .filter((source) => source.installed || source.available || source.shared);+ });}function profileDataDir(profile, configured) {@@ -171,4 +194,4 @@ function profileDataDir(profile, configured) {return path.join(sharedDataDir(), 'profiles', profile.id);}-module.exports = { PROFILES, applyWorkBuddyTarget, getProfile, listProfiles, listInstalledModelSources, profileDataDir, sharedDataDir };+module.exports = { isCodeBuddyBinary, PROFILES, applyWorkBuddyTarget, getProfile, listProfiles, listInstalledModelSources, profileDataDir, sharedDataDir };diff --git a/scripts/relaunch-with-cdp-linux.sh b/scripts/relaunch-with-cdp-linux.shindex 27ea32f..9aa6915 100755--- a/scripts/relaunch-with-cdp-linux.sh+++ b/scripts/relaunch-with-cdp-linux.sh@@ -30,6 +30,11 @@ fiDIR="$(cd "$(dirname "$0")/.." && pwd)"PROFILE="${WBSWITCH_PROFILE:-workbuddy-cn}"+NATIVE_ARGS=()+case "$PROFILE" in+ codebuddy-cn) NATIVE_ARGS=(--inspect=127.0.0.1:9244) ;;+ codebuddy-intl) NATIVE_ARGS=(--inspect=127.0.0.1:9245) ;;+esacXDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"case "$PROFILE" in@@ -176,6 +181,10 @@ is_workbuddy_cdp() {# 这里改用「应用安装目录」作为归属标记 —— CN 是 /opt/WorkBuddy,# AI 是 ~/.local/share/workbuddy-ai/app,两者页面 URL 互不含对方目录。is_profile_cdp() {+ case "$PROFILE" in+ codebuddy-cn) curl_local http://127.0.0.1:9244/json/list >/dev/null 2>&1 || return 1 ;;+ codebuddy-intl) curl_local http://127.0.0.1:9245/json/list >/dev/null 2>&1 || return 1 ;;+ esaclocal port="$1" list dirlist="$(curl_local "http://127.0.0.1:$port/json/list" 2>/dev/null)" || return 1[ -n "$list" ] || return 1@@ -183,13 +192,14 @@ is_profile_cdp() {# 必须校验 dir 形态:APP_BIN 为空时 dirname 会给出 ".",# 而 grep -F "." 能匹配任何内容 → 变成"人人都算自己人"。if [ -n "$dir" ] && [ "${#dir}" -gt 1 ] && [ "${dir#/}" != "$dir" ] \- && printf '%s' "$list" | grep -qF "$dir"; then+ && { printf '%s' "$list" | grep -qF "$dir/" || printf '%s' "$list" | grep -qF "${dir// /%20}/"; }; thenreturn 0fi# 回退:按端专属字样判断(安装目录非默认时仍可用)case "$PROFILE" inworkbuddy-ai) printf '%s' "$list" | grep -qi 'workbuddy-ai' ;;workbuddy-cn) printf '%s' "$list" | grep -qi 'workbuddy\.cn\|WorkBuddy/resources' ;;+ codebuddy-cn|codebuddy-intl) return 1 ;;*) printf '%s' "$list" | grep -qiE 'WorkBuddy|CodeBuddy' ;;esac}@@ -398,7 +408,7 @@ launch_plugin() {echo " 环境: HOME=${launch_home}(启动器需按真实家目录推导,不能传隔离 HOME)"fi# setsid:脱离当前会话,避免终端关闭时连带杀掉 WorkBuddy- setsid nohup env HOME="$launch_home" "$LAUNCH_TARGET" --remote-debugging-port="$PORT" >/dev/null 2>&1 < /dev/null &+ setsid nohup env HOME="$launch_home" "$LAUNCH_TARGET" --remote-debugging-port="$PORT" "${NATIVE_ARGS[@]}" >/dev/null 2>&1 < /dev/null &disown 2>/dev/null || trueecho "==> 等待 CDP 端口开放(并确认是本 profile 的实例)"diff --git a/scripts/relaunch-with-cdp.sh b/scripts/relaunch-with-cdp.shindex 4e18b38..4cc22d6 100644--- a/scripts/relaunch-with-cdp.sh+++ b/scripts/relaunch-with-cdp.sh@@ -16,6 +16,11 @@ set -uo pipefailPORT="${WBSWITCH_CDP_PORT:-${1:-}}"DIR="$(cd "$(dirname "$0")/.." && pwd)"PROFILE="${WBSWITCH_PROFILE:-workbuddy-cn}"+NATIVE_ARGS=()+case "$PROFILE" in+ codebuddy-cn) NATIVE_ARGS=(--inspect=127.0.0.1:9244) ;;+ codebuddy-intl) NATIVE_ARGS=(--inspect=127.0.0.1:9245) ;;+esaccase "$PROFILE" inworkbuddy-ai) APP_NAME="WorkBuddy AI"; APP_BIN="/Applications/WorkBuddy AI.app/Contents/MacOS/Electron"; DEFAULT_DATA_DIR="$HOME/Library/Application Support/WorkDaddy/profiles/workbuddy-ai"; DEFAULT_UI_PORT=47833; DEFAULT_CDP_PORT=9223; AUTH_DEFAULT="$HOME/Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop-ai.info" ;;codebuddy-cn) APP_NAME="CodeBuddy CN"; APP_BIN="/Applications/CodeBuddy CN.app/Contents/MacOS/Electron"; DEFAULT_DATA_DIR="$HOME/Library/Application Support/WorkDaddy/profiles/codebuddy-cn"; DEFAULT_UI_PORT=47834; DEFAULT_CDP_PORT=9224; AUTH_DEFAULT="" ;;@@ -106,7 +111,21 @@ valid_port() { [ "${1:-0}" -ge 1024 ] 2>/dev/null && [ "${1:-0}" -le 65535 ] 2>/port_in_use() {if command -v nc >/dev/null 2>&1; then nc -z -w 1 127.0.0.1 "$1" >/dev/null 2>&1; else curl -s --max-time 1 "http://127.0.0.1:$1/" >/dev/null 2>&1; fi}-is_workbuddy_cdp() { curl -fsS --max-time 1 "http://127.0.0.1:$1/json/version" 2>/dev/null | grep -qiE 'WorkBuddy|CodeBuddy'; }+is_workbuddy_cdp() {+ case "$PROFILE" in+ codebuddy-cn|codebuddy-intl)+ local native_port=9244 expected body+ [ "$PROFILE" = codebuddy-intl ] && native_port=9245+ curl -fsS --max-time 1 "http://127.0.0.1:$native_port/json/list" >/dev/null 2>&1 || return 1+ body="$(curl -fsS --max-time 1 "http://127.0.0.1:$1/json/list" 2>/dev/null)" || return 1+ expected="${APP_BIN%/Contents/MacOS/*}/"+ [ "$expected" != / ] && [ "$expected" != "$APP_BIN/" ] || return 1+ printf '%s' "$body" | grep -Fq "$expected" ||+ printf '%s' "$body" | grep -Fq "${expected// /%20}"+ ;;+ *) curl -fsS --max-time 1 "http://127.0.0.1:$1/json/version" 2>/dev/null | grep -qiE 'WorkBuddy|CodeBuddy' ;;+ esac+}resolve_cdp_port() {local saved="" pif [ -f "$CDP_PORT_FILE" ]; then saved="$(sed -n 's/.*"port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$CDP_PORT_FILE" | head -1)"; fi@@ -177,16 +196,18 @@ APPLESCRIPTfi# 清理旧版常驻服务和旧 profile 自启项,但保留账号数据;daemon 仅由本次手动执行启动。-for old_profile in workbuddy-cn workbuddy-ai codebuddy-cn codebuddy-intl; do+for old_profile in "$PROFILE"; doold_label="com.workbuddy.workdaddy.${old_profile}"old_plist="$HOME/Library/LaunchAgents/${old_label}.plist"launchctl bootout "gui/$(id -u)" "$old_plist" 2>/dev/null || truelaunchctl remove "$old_label" 2>/dev/null || truerm -f "$old_plist"done+if [ "$PROFILE" = workbuddy-cn ]; thenlaunchctl bootout "gui/$(id -u)" "$LEGACY_PLIST" 2>/dev/null || truelaunchctl remove "$LEGACY_LABEL" 2>/dev/null || truerm -f "$LEGACY_PLIST"+fi"$NODE_BIN" -e "const lib = require(process.argv[1]); const r = lib.migrateLegacyDataDir(process.argv[2]); if (r.migrated) console.log('已迁移 ' + r.migrated + ' 个旧版账号备份');" "$DIR/scripts/lib.js" "$DATA_DIR" 2>/dev/null || true# ---------- 功能函数(必须先于调用定义) ----------@@ -300,7 +321,7 @@ launch_plugin() {echo " 错误:未找到 $APP_BIN"exit 1fi- nohup "$APP_BIN" --remote-debugging-port="$PORT" >/dev/null 2>&1 &+ nohup "$APP_BIN" --remote-debugging-port="$PORT" "${NATIVE_ARGS[@]}" >/dev/null 2>&1 &disown 2>/dev/null || true# ---------- 4. 验证 ----------@@ -308,7 +329,7 @@ launch_plugin() {OK=0for i in $(seq 1 60); dosleep 1- if curl -s -m 2 "http://127.0.0.1:${PORT}/json/version" | grep -qiE 'WorkBuddy|CodeBuddy'; then+ if is_workbuddy_cdp "$PORT"; thenOK=1breakfidiff --git a/scripts/renderer-api-bridge.js b/scripts/renderer-api-bridge.jsnew file mode 100644index 0000000..c16f357--- /dev/null+++ b/scripts/renderer-api-bridge.js@@ -0,0 +1,160 @@+'use strict';++// CDP transport for sandboxed Electron pages. Routes still pass through the+// daemon's existing authentication, validation and handlers; no CSP changes.+const http = require('node:http');+const crypto = require('node:crypto');+const BINDING = '__wbsLocalApiRequest';+const MAX_BYTES = 64 * 1024 * 1024;++function createRendererApiBridge({ token, port, send }) {+ let active = 0;+ const uploads = new Map();+ function openRequest(path, method, contentType, size) {+ let req;+ const result = new Promise((resolve, reject) => {+ req = http.request({hostname:'127.0.0.1',port:port(),path,method,+ headers:{'X-WorkDaddy-Token':token,'Content-Type':contentType,'Content-Length':size}}, res => {+ const chunks=[]; let received=0;+ res.on('data', chunk => {+ received+=chunk.length;+ if(received>MAX_BYTES) {res.destroy();reject(new Error('本地 API 响应过大'));}+ else chunks.push(chunk);+ });+ res.on('error',reject);+ res.on('end',()=>resolve({status:res.statusCode,body:Buffer.concat(chunks).toString('base64'),+ contentType:String(res.headers['content-type'] || ''),count:Number(res.headers['x-workdaddy-count'] || 0)}));+ });+ req.setTimeout(120000,()=>req.destroy(new Error('本地 API 请求超时')));+ req.on('error',reject);+ });+ result.catch(()=>{});+ return {req,result};+ }+ function closeUpload(id) {+ const upload=uploads.get(id);+ if(!upload)return;+ uploads.delete(id);clearTimeout(upload.timer);active--;+ upload.req.destroy();+ }+ return async function handleBinding(params) {+ if (params.name !== BINDING || !Number.isInteger(params.executionContextId)) return;+ let request;+ try { request = JSON.parse(params.payload); } catch (_) { return; }+ if (!request || typeof request.id !== 'string' || !/^[\w:-]{1,100}$/.test(request.id)) return;+ const supplied = Buffer.from(String(request.token || ''));+ const expected = Buffer.from(token);+ if (supplied.length !== expected.length || !crypto.timingSafeEqual(supplied, expected)) return;+ const reply = value => send('Runtime.evaluate', {+ contextId: params.executionContextId,+ expression: 'window.__wbsApiBridgeReply && window.__wbsApiBridgeReply(' + JSON.stringify({id:request.id,...value}) + ')',+ returnByValue: false,+ }).catch(() => {}); // navigation destroys pending calls with their old context+ if (['upload-chunk','upload-end','upload-cancel'].includes(request.kind)) {+ const upload=uploads.get(request.uploadId);+ if(!upload || upload.context!==params.executionContextId || upload.writing) {await reply({error:'上传任务不存在或正在处理'});return;}+ try {+ upload.writing=true;+ if(request.kind==='upload-cancel') {closeUpload(request.uploadId);await reply({status:204});return;}+ if(request.kind==='upload-end') {+ if(upload.offset!==upload.total)throw new Error('上传长度不匹配');+ upload.req.end();+ const result=await upload.result;+ await reply(result);closeUpload(request.uploadId);return;+ }+ if(request.offset!==upload.offset || typeof request.body!=='string' || request.body.length>350000 ||+ !/^[A-Za-z0-9+/]*={0,2}$/.test(request.body))throw new Error('上传分片无效');+ const chunk=Buffer.from(request.body,'base64');+ if(!chunk.length || chunk.length>262144 || upload.offset+chunk.length>upload.total)throw new Error('上传分片过大');+ await new Promise((resolve,reject)=>upload.req.write(chunk,error=>error?reject(error):resolve()));+ upload.offset+=chunk.length;upload.writing=false;+ clearTimeout(upload.timer);upload.timer=setTimeout(()=>closeUpload(request.uploadId),120000);upload.timer.unref();+ await reply({status:204});+ } catch (_) {closeUpload(request.uploadId);await reply({error:'会话上传失败,请重新导入'});}+ return;+ }+ const path = request.path;+ const method = request.method || 'GET';+ const encoded = request.body == null ? '' : request.body;+ const contentType = request.contentType || 'application/json';+ const validEncoding = request.encoding == null || request.encoding === 'base64';+ const body = typeof encoded === 'string' ? Buffer.from(encoded, request.encoding === 'base64' ? 'base64' : 'utf8') : null;+ let url;+ try { url = new URL(path, 'http://127.0.0.1'); } catch (_) {}+ if (typeof path !== 'string' || !/^\/api\/[A-Za-z0-9_/-]+(?:\?[^#\r\n]*)?$/.test(path) ||+ !url || url.origin !== 'http://127.0.0.1' || !url.pathname.startsWith('/api/') ||+ !['GET','POST','DELETE'].includes(method) || !body || !validEncoding ||+ !['application/json','application/octet-stream'].includes(contentType) || encoded.length > MAX_BYTES * 1.4 || body.length > MAX_BYTES || active >= 32) {+ await reply({error:'本地 API 请求无效或过多'}); return;+ }+ if (request.kind==='upload-start') {+ if(path!=='/api/sessions/import' || method!=='POST' || contentType!=='application/octet-stream' ||+ typeof request.uploadId!=='string' || !/^[\w:-]{1,100}$/.test(request.uploadId) || uploads.has(request.uploadId) ||+ !Number.isSafeInteger(request.totalBytes) || request.totalBytes<=0) {await reply({error:'上传请求无效'});return;}+ const opened=openRequest(path,method,contentType,request.totalBytes);+ const upload={...opened,total:request.totalBytes,offset:0,writing:false,context:params.executionContextId};+ upload.timer=setTimeout(()=>closeUpload(request.uploadId),120000);upload.timer.unref();+ active++;uploads.set(request.uploadId,upload);+ await reply({status:204});return;+ }+ if(request.kind) {await reply({error:'请求类型无效'});return;}+ active++;+ try {+ const opened=openRequest(path,method,contentType,body.length);+ opened.req.end(body);+ await reply(await opened.result);+ } catch (_) { await reply({error:'本地 API 请求失败'}); }+ finally { active--; }+ };+}++function installRendererBridge(binding) {+ if (window.__wbsApiBridgeDispose) window.__wbsApiBridgeDispose();+ var pending = new Map(), serial = 0, prefix = crypto.randomUUID();+ window.__wbsApiBridgeDispose = function () {+ pending.forEach(function (entry) { clearTimeout(entry.timer); entry.reject(new Error('面板已重新加载')); });+ pending.clear();+ };+ window.__wbsApiBridgeReply = function (reply) {+ var entry = pending.get(reply.id);+ if (!entry) return;+ pending.delete(reply.id); clearTimeout(entry.timer);+ if (reply.error) { entry.reject(new Error(reply.error)); return; }+ var bytes = Uint8Array.from(atob(reply.body || ''), function (ch) { return ch.charCodeAt(0); });+ var blob = new Blob([bytes], {type:reply.contentType || 'application/octet-stream'});+ entry.resolve({ok:reply.status >= 200 && reply.status < 300,+ json:function () { return blob.text().then(JSON.parse); }, blob:function () { return Promise.resolve(blob); },+ headers:{get:function (key) { return key.toLowerCase() === 'x-workdaddy-count' ? String(reply.count || 0) : null; }}});+ };+ function transmit(request, token) {+ return new Promise(function (resolve,reject) {+ var id=prefix+':'+(++serial);+ var timer=setTimeout(function(){pending.delete(id);reject(new Error('本地 API 请求超时'));},125000);+ pending.set(id,{resolve:resolve,reject:reject,timer:timer});+ try {window[binding](JSON.stringify(Object.assign({},request,{id:id,token:token})));}+ catch (_) {pending.delete(id);clearTimeout(timer);reject(new Error('本地 API 尚未连接'));}+ });+ }+ window.__wbsApiFetch = async function (path, options, token) {+ options=options || {};+ var body=options.body;+ var contentType=options.headers && (options.headers['content-type'] || options.headers['Content-Type']);+ var request={path:path,method:options.method || 'GET',contentType:contentType};+ if(body instanceof Blob && path==='/api/sessions/import') {+ var uploadId=prefix+':upload:'+(++serial);+ await transmit(Object.assign({},request,{kind:'upload-start',uploadId:uploadId,totalBytes:body.size}),token);+ try {+ for(var offset=0;offset<body.size;offset+=262144) {+ var bytes=new Uint8Array(await body.slice(offset,offset+262144).arrayBuffer()),parts=[];+ for(var i=0;i<bytes.length;i+=16384)parts.push(String.fromCharCode.apply(null,bytes.subarray(i,i+16384)));+ await transmit({kind:'upload-chunk',uploadId:uploadId,offset:offset,body:btoa(parts.join(''))},token);+ }+ return await transmit({kind:'upload-end',uploadId:uploadId},token);+ } catch(error) {transmit({kind:'upload-cancel',uploadId:uploadId},token).catch(function(){});throw error;}+ }+ return transmit(Object.assign({},request,{body:body}),token);+ };+}++function rendererBridgeSource() { return '(' + installRendererBridge.toString() + ')(' + JSON.stringify(BINDING) + ');\n'; }+module.exports = { BINDING, createRendererApiBridge, rendererBridgeSource };diff --git a/scripts/secure-transfer.js b/scripts/secure-transfer.jsindex ccd50de..53346e0 100644--- a/scripts/secure-transfer.js+++ b/scripts/secure-transfer.js@@ -118,7 +118,7 @@ function remapSessionArchivePath(relativePath, oldId, newId) {const mappings = [[new RegExp('^projects/([^/]+)/' + escaped + '\\.jsonl$'), (match) => `projects/${match[1]}/${targetId}.jsonl`],[new RegExp('^projects/([^/]+)/' + escaped + '/(.+)$'), (match) => `projects/${match[1]}/${targetId}/${match[2]}`],- [new RegExp('^(workspace/sessions|tasks|file-history)/' + escaped + '/(.+)$'), (match) => `${match[1]}/${targetId}/${match[2]}`],+ [new RegExp('^(workspace/sessions|tasks|file-history|codebuddy-file-tree)/' + escaped + '/(.+)$'), (match) => `${match[1]}/${targetId}/${match[2]}`],[new RegExp('^artifact-index/' + escaped + '\\.json$'), () => `artifact-index/${targetId}.json`],];for (const [pattern, build] of mappings) {diff --git a/scripts/session-sync.js b/scripts/session-sync.jsindex 9481a0f..1bee5d5 100644--- a/scripts/session-sync.js+++ b/scripts/session-sync.js@@ -896,12 +896,13 @@ async function applySnapshot(source, target, options) {}async function unchangedAsync(snapshot) {- const now = await readSnapshotAsync(snapshot.root, snapshot.id, snapshot.aliases, snapshot.cache || null);+ const now = snapshot.reread ? await snapshot.reread() : await readSnapshotAsync(snapshot.root, snapshot.id, snapshot.aliases, snapshot.cache || null);return now.files.size === snapshot.files.size &&[...snapshot.files].every(([key, file]) => now.files.get(key)?.hash === file.hash);}async function targetBytesAsync(key, file, source, target) {+ if (source.rewriteBytes) return source.rewriteBytes(key, file, target);if (key !== 'artifact-index/__session__.json') return null;const bytes = await readStableBytesAsync(file);const index = JSON.parse(bytes.toString('utf8'));@@ -929,7 +930,7 @@ async function applySnapshotAsync(source, target, options) {const hash = bytes ? digest(bytes) : file.hash;if (target.files.get(key)?.hash === hash) continue;changes.push({- key, relative: targetRelative(key, target.id), bytes, sourceFile: file,+ key, relative: target.resolveRelative ? target.resolveRelative(key) : targetRelative(key, target.id), bytes, sourceFile: file,hash, size: bytes ? bytes.length : file.size, mode: file.mode, mtimeMs: file.mtimeMs,});}@@ -965,7 +966,7 @@ async function applySnapshotAsync(source, target, options) {let totalBytes = 0;const verifyPublished = async () => {if (!await unchangedAsync(source)) throw Error('源会话正在变化,已停止同步');- const now = await readSnapshotAsync(target.root, target.id, target.aliases, target.cache || null);+ const now = target.reread ? await target.reread() : await readSnapshotAsync(target.root, target.id, target.aliases, target.cache || null);if (now.files.size !== expected.size || [...expected].some(([key, hash]) => now.files.get(key)?.hash !== hash)) {throw Error('目标会话正在变化,已停止同步');}diff --git a/scripts/token-stats.js b/scripts/token-stats.jsindex 58fd79b..477b3e7 100644--- a/scripts/token-stats.js+++ b/scripts/token-stats.js@@ -7,8 +7,8 @@ const { createHash } = require('node:crypto');const TOKEN_FIELDS = {input: ['input_tokens', 'prompt_tokens', 'inputTokens', 'promptTokens'],output: ['output_tokens', 'completion_tokens', 'outputTokens', 'completionTokens'],- cacheRead: ['cache_read_input_tokens', 'cache_read_tokens', 'cacheReadTokens', 'cached_tokens'],- cacheWrite: ['cache_creation_input_tokens', 'cache_write_tokens', 'cacheWriteTokens'],+ cacheRead: ['cache_read_input_tokens', 'cache_read_tokens', 'cacheReadTokens', 'cached_tokens', 'cacheTokens'],+ cacheWrite: ['cache_creation_input_tokens', 'cache_write_tokens', 'cacheWriteTokens', 'cachedWriteTokens'],};function numberField(value, fields) {@@ -128,7 +128,10 @@ function parseRecords(root, options = {}) {let text;try { text = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }const occurrences = new Map();- for (const line of text.split(/\r?\n/)) {+ let lines;+ try { lines = options.readRecords ? options.readRecords(text).map(record => JSON.stringify(record)) : text.split(/\r?\n/); }+ catch (_) { parseErrors++; parseErrorFiles.add(relative); continue; }+ for (const line of lines) {if (!line.trim()) continue;let record;try { record = JSON.parse(line); } catch (_) {@@ -144,7 +147,7 @@ function parseRecords(root, options = {}) {if (!record || typeof record !== 'object' || record.isSnapshotUpdate) continue;const usage = findUsage(record.message && record.message.usage) || findUsage(record.providerData && record.providerData.usage) || findUsage(record);if (!usage) continue;- const timestamp = timestampValue(record.timestamp || record.created_at || record.createdAt || usage.timestamp, now);+ const timestamp = timestampValue(record.timestamp || record.created_at || record.createdAt || record.startedAt || usage.timestamp, now);if (!Number.isFinite(timestamp) || timestamp < lowerBound || timestamp > upperBound) continue;const input = numberField(usage, TOKEN_FIELDS.input);const output = numberField(usage, TOKEN_FIELDS.output);@@ -164,7 +167,7 @@ function parseRecords(root, options = {}) {key: digest + ':' + occurrence,file: relative,sourceSession: (['sessionId', 'conversationId', 'session_id', 'conversation_id']- .map(field => record[field]).find(value => typeof value === 'string' && value.trim()) || '').trim(),+ .map(field => record[field]).find(value => typeof value === 'string' && value.trim()) || (options.sourceSession && options.sourceSession(file)) || '').trim(),timestamp,model: model || '',account: account || '',@@ -291,7 +294,7 @@ function aggregateRecords(records, options = {}) {else if (account.nickname) byAccount.get(uid).nickname = account.nickname;}return {- source: 'local-workbuddy-jsonl',+ source: options.source || 'local-workbuddy-jsonl',since: bounds.from,until: bounds.until,totals,@@ -369,7 +372,7 @@ function aggregateCachedBuckets(buckets, options = {}) {else if (account.nickname) byAccount.get(uid).nickname = account.nickname;}return {- source: 'local-workbuddy-jsonl', since: bounds.from, until: bounds.until, totals,+ source: options.source || 'local-workbuddy-jsonl', since: bounds.from, until: bounds.until, totals,daily: Array.from(byDay.values()).sort((a, b) => a.day.localeCompare(b.day)),dailyBreakdown: dailyBreakdown.sort((a, b) => a.day.localeCompare(b.day) || a.account.localeCompare(b.account) || a.model.localeCompare(b.model)),models: Array.from(byModel.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),@@ -386,7 +389,7 @@ function scanTokenStatsCached(root, options = {}) {const file = cacheFile(root, options);const cache = readCache(file);const hadValidCache = usableCache(cache, now);- const currentFiles = walkJsonl(root, options.maxFiles || 5000);+ const currentFiles = Array.isArray(options.files) ? options.files : walkJsonl(root, options.maxFiles || 5000);const todayFiles = {};let parsedLines = 0, parseErrors = 0;const parseErrorFiles = new Set();diff --git a/scripts/uninstall-win.ps1 b/scripts/uninstall-win.ps1index 6539b68..ccc99c2 100644--- a/scripts/uninstall-win.ps1+++ b/scripts/uninstall-win.ps1@@ -25,15 +25,15 @@ try { . (Join-Path $PSScriptRoot 'windows-process-boundary.ps1') } catch {}$ErrorActionPreference = 'Continue'if ([string]::IsNullOrWhiteSpace($Profile) -or $Profile -eq '__WBS_DEFAULT_PROFILE__') { $Profile = 'workbuddy-cn' }-if ($Profile -ne 'workbuddy-ai') { $Profile = 'workbuddy-cn' }-$productName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy AI' } else { 'WorkDaddy' }+if ($Profile -notin @('workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl')) { throw 'Unknown client profile' }+$productName = (@{'workbuddy-cn'='WorkDaddy'; 'workbuddy-ai'='WorkDaddy AI'; 'codebuddy-cn'='CodeDaddy CN'; 'codebuddy-intl'='CodeDaddy'})[$Profile]if ([string]::IsNullOrWhiteSpace($AppDir)) { $AppDir = Join-Path $env:LOCALAPPDATA (Join-Path 'Programs' $productName) }if (-not (Test-SameWindowsPath -Left $PSScriptRoot -Right (Join-Path $AppDir 'scripts'))) {throw '卸载脚本位置与目标安装目录不一致,拒绝删除'}$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'-$dataDir = if ($Profile -eq 'workbuddy-ai') { Join-Path $dataRoot 'profiles\workbuddy-ai' } else { $dataRoot }-$port = if ($Profile -eq 'workbuddy-ai') { 47833 } else { 47832 }+$dataDir = if ($Profile -eq 'workbuddy-cn') { $dataRoot } else { Join-Path $dataRoot ('profiles\' + $Profile) }+$port = (@{'workbuddy-cn'=47832; 'workbuddy-ai'=47833; 'codebuddy-cn'=47834; 'codebuddy-intl'=47835})[$Profile]Write-Host ('卸载 ' + $productName + '...')diff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex efcda48..3abf9f2 100644--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -3,11 +3,17 @@# 用法: bash scripts/uninstall.shset -euo pipefail+PROFILE="${WBSWITCH_PROFILE:-workbuddy-cn}"+case "$PROFILE" in+ workbuddy-cn|workbuddy-ai|codebuddy-cn|codebuddy-intl) ;;+ *) echo "未知客户端配置: $PROFILE"; exit 1 ;;+esacLABEL="com.workbuddy.workdaddy"PLIST="$HOME/Library/LaunchAgents/${LABEL}.plist"LEGACY_LABEL="com.workbuddy.hellobuddy"LEGACY_PLIST="$HOME/Library/LaunchAgents/${LEGACY_LABEL}.plist"DEFAULT_DATA_DIR="$HOME/Library/Application Support/WorkDaddy"+if [ "$PROFILE" != workbuddy-cn ]; then DEFAULT_DATA_DIR="$DEFAULT_DATA_DIR/profiles/$PROFILE"; fiLEGACY_DATA_DIR="$HOME/Library/Application Support/HelloBuddy"if [ "${WBSWITCH_DATA_DIR:-}" = "$LEGACY_DATA_DIR" ]; thenDATA_DIR="$DEFAULT_DATA_DIR"@@ -16,18 +22,20 @@ elsefiecho "==> 停止并移除 launchd 守护进程"-for old_profile in workbuddy-cn workbuddy-ai codebuddy-cn codebuddy-intl; do+for old_profile in "$PROFILE"; doold_label="com.workbuddy.workdaddy.${old_profile}"old_plist="$HOME/Library/LaunchAgents/${old_label}.plist"launchctl bootout "gui/$(id -u)" "$old_plist" 2>/dev/null || truelaunchctl remove "$old_label" 2>/dev/null || truerm -f "$old_plist"done+if [ "$PROFILE" = workbuddy-cn ]; thenlaunchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || truerm -f "$PLIST"launchctl bootout "gui/$(id -u)" "$LEGACY_PLIST" 2>/dev/null || truelaunchctl remove "$LEGACY_LABEL" 2>/dev/null || truerm -f "$LEGACY_PLIST"+fiecho "==> 完成"echo " 备份数据保留在: $DATA_DIR"diff --git a/scripts/watchdog.js b/scripts/watchdog.jsindex 97f4666..0b255b0 100644--- a/scripts/watchdog.js+++ b/scripts/watchdog.js@@ -20,7 +20,7 @@ const DATA_DIR = process.env.WBSWITCH_DATA_DIR || profileDataDir(PROFILE);const PID_FILE = path.join(DATA_DIR, 'watchdog.pid');const LOG_FILE = path.join(DATA_DIR, 'watchdog.log');const DAEMON_FILE = path.join(__dirname, 'daemon.js');-const LOCK_PORT = PROFILE.id === 'workbuddy-ai' ? 47933 : 47932;+const LOCK_PORT = ({'workbuddy-cn':47932,'workbuddy-ai':47933,'codebuddy-cn':47934,'codebuddy-intl':47935})[PROFILE.id];let child = null;let stopping = false;diff --git a/scripts/win-launcher.js b/scripts/win-launcher.jsindex e51e52d..5bfab63 100644--- a/scripts/win-launcher.js+++ b/scripts/win-launcher.js@@ -48,7 +48,7 @@ if (process.platform === 'win32') {}}const { captureMessage, captureException } = require('./sentry-report.js');-const { getProfile, profileDataDir } = require('./profiles.js');+const { getProfile, profileDataDir, isCodeBuddyBinary } = require('./profiles.js');const { isTargetForProfile } = require('./cdp-targets.js');const { replaceFileWithRetry } = require('./atomic-file-write.js');const { parseUiPortState, profileUiPortCandidates } = require('./ui-port.js');@@ -332,6 +332,10 @@ async function isWorkBuddyCdp() {}async function isWorkBuddyCdpAt(port, binary = null) {+ if (PROFILE.nativeDebugPort) {+ const native = await httpGet(PROFILE.nativeDebugPort, '/json/list');+ if (!native || native.status !== 200) return false;+ }const [version, targets] = await Promise.all([httpGet(port, '/json/version'),httpGet(port, '/json/list'),@@ -421,7 +425,7 @@ function getWorkBuddyProcesses() {requireCurrentOwner: true,requireNativeArguments: true,allowTransientNotFound: true,- });+ }).filter(row => PROFILE.kind !== 'codebuddy' || isCodeBuddyBinary(row.ExecutablePath,PROFILE.id));}// 仅保留为本地端口诊断;daemon 启动成功必须走 exactDaemonStatus 完整身份校验。@@ -587,7 +591,8 @@ function findWorkBuddy() {const candidate = String(p || '').trim().replace(/^"(.*)"(?:,\d+)?$/, '$1').replace(/,\d+$/, '');if (!candidate || !fs.existsSync(candidate)) return null;const resolved = resolveWindowsExecutable(candidate);- return PROFILE_BINARY_NAMES.has(path.win32.basename(resolved).toLowerCase()) ? resolved : null;+ return PROFILE_BINARY_NAMES.has(path.win32.basename(resolved).toLowerCase()) &&+ (PROFILE.kind !== 'codebuddy' || isCodeBuddyBinary(resolved,PROFILE.id)) ? resolved : null;} catch (_) {}return null;};@@ -1139,6 +1144,7 @@ async function quitWorkBuddy(binary) {function launchWorkBuddy(wb) {const environmentMode = !!(PROFILE.cdp && PROFILE.cdp.mode === 'environment');const args = environmentMode ? [] : ['--remote-debugging-port=' + CDP_PORT];+ if (PROFILE.nativeDebugPort) args.push('--inspect=127.0.0.1:' + PROFILE.nativeDebugPort);const env = environmentMode? { ...process.env, WORKBUDDY_REMOTE_DEBUGGING_PORT: String(CDP_PORT) }: process.env;@@ -1390,7 +1396,7 @@ function findWorkBuddyNative() {if (process.env.WBSWITCH_WORKBUDDY_DIR) {for (const name of expectedNames) add(path.join(process.env.WBSWITCH_WORKBUDDY_DIR, name), 'explicit');}- const appPathNames = PROFILE.customTarget ? [] : (PROFILE.id === 'workbuddy-ai' ? ['WorkBuddyAI.exe'] : ['WorkBuddy.exe']);+ const appPathNames = PROFILE.customTarget ? [] : (PROFILE.kind === 'codebuddy' ? ['CodeBuddy.exe'] : (PROFILE.id === 'workbuddy-ai' ? ['WorkBuddyAI.exe'] : ['WorkBuddy.exe']));const appPathKeys = [];for (const name of appPathNames) {appPathKeys.push(`HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\${name}`);@@ -1398,9 +1404,11 @@ function findWorkBuddyNative() {}const appPathCommand = "$k=@(" + appPathKeys.map(powershellLiteral).join(',') + "); Get-ItemProperty $k -ErrorAction SilentlyContinue | ForEach-Object { if ($_.'(default)') { $_.'(default)' } elseif ($_.Path) { Join-Path $_.Path " + powershellLiteral(expectedName) + " } }";for (const candidate of bestEffortPowerShellLines(appPathCommand, 'App Paths')) add(candidate, 'registered');- const uninstallCommand = "$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy' } | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation " + powershellLiteral(expectedName) + " } }";+ const uninstallCommand = "$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy|CodeBuddy' } | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation " + powershellLiteral(expectedName) + " } }";for (const candidate of bestEffortPowerShellLines(uninstallCommand, '卸载注册表')) add(candidate, 'registered');- if (PROFILE.id === 'workbuddy-ai') {+ if (PROFILE.kind === 'codebuddy') {+ for(const root of [path.join(local,'Programs'),programFiles,programFilesX86]) add(path.join(root,PROFILE.name,'CodeBuddy.exe'),'portable');+ } else if (PROFILE.id === 'workbuddy-ai') {add(path.join(local, 'Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'), 'portable');add(path.join(local, 'Programs', 'WorkBuddy AI', 'WorkBuddyAI.exe'), 'portable');add(path.join(programFiles, 'WorkBuddyAI', 'WorkBuddyAI.exe'), 'portable');@@ -1417,7 +1425,9 @@ function findWorkBuddyNative() {add(path.join(root, 'Software', PROFILE.id === 'workbuddy-ai' ? 'workbuddy-ai' : 'workbuddy', expectedName), 'portable');add(path.join(root, PROFILE.id === 'workbuddy-ai' ? 'WorkBuddyAI' : 'WorkBuddy', expectedName), 'portable');}- const scanDirs = PROFILE.id === 'workbuddy-ai'+ const scanDirs = PROFILE.kind === 'codebuddy'+ ? [path.join(local,'Programs',PROFILE.name),path.join(local,PROFILE.name),path.join(programFiles,PROFILE.name)]+ : PROFILE.id === 'workbuddy-ai'? [path.join(local, 'Programs', 'WorkBuddyAI'), path.join(local, 'Programs', 'WorkBuddy AI'), path.join(local, 'WorkBuddyAI')]: [path.join(local, 'Programs', 'WorkBuddy'), path.join(local, 'WorkBuddy'), path.join(process.env.APPDATA || '', 'WorkBuddy')];const scanCommand = [@@ -1432,6 +1442,7 @@ function findWorkBuddyNative() {try {if (!fs.statSync(item.path).isFile()) continue;if (!PROFILE_BINARY_NAMES.has(path.win32.basename(item.path).toLowerCase())) continue;+ if (PROFILE.kind === 'codebuddy' && !isCodeBuddyBinary(item.path,PROFILE.id)) continue;if (PROFILE.configuredTarget &&!sameWindowsPath(path.win32.dirname(item.path), path.win32.dirname(PROFILE.appPath))) continue;summary.validCandidateCount += 1;diff --git a/scripts/win/workdaddy.iss b/scripts/win/workdaddy.issindex 3f66b85..ab40adf 100644--- a/scripts/win/workdaddy.iss+++ b/scripts/win/workdaddy.iss@@ -148,24 +148,57 @@ begin);end;-function ExpectedWorkBuddyName(): String;+function ExpectedClientDisplayName(): String;+begin+ if '{#ProfileId}' = 'codebuddy-cn' then+ Result := 'CodeBuddy CN'+ else if '{#ProfileId}' = 'codebuddy-intl' then+ Result := 'CodeBuddy'+ else if '{#ProfileId}' = 'workbuddy-ai' then+ Result := 'WorkBuddy AI'+ else+ Result := 'WorkBuddy';+end;++function ExpectedClientExecutableName(): String;begin- if '{#ProfileId}' = 'workbuddy-ai' then+ if '{#ProfileId}' = 'codebuddy-cn' then+ Result := 'CodeBuddy CN.exe'+ else if '{#ProfileId}' = 'codebuddy-intl' then+ Result := 'CodeBuddy.exe'+ else if '{#ProfileId}' = 'workbuddy-ai' thenResult := 'WorkBuddyAI.exe'elseResult := 'WorkBuddy.exe';end;+function ClientExecutableNameMatches(const Candidate: String): Boolean;+var+ Name: String;+begin+ Name := ExtractFileName(Candidate);+ Result := CompareText(Name, ExpectedClientExecutableName()) = 0;+ if (not Result) and ('{#ProfileId}' = 'codebuddy-cn') then+ Result := CompareText(Name, 'CodeBuddy.exe') = 0;+end;+function UsableClientFile(const Candidate: String): Boolean;beginResult := (Candidate <> '') and FileExists(Candidate) and(CompareText(ExtractFileExt(Candidate), '.exe') = 0);end;+function SelectedClientFile(const Candidate: String): Boolean;+begin+ Result := UsableClientFile(Candidate);+ if Result and (Pos('codebuddy', Lowercase('{#ProfileId}')) = 1) then+ Result := ClientExecutableNameMatches(Candidate);+end;+function OfficialClientFile(const Candidate: String): Boolean;beginResult := UsableClientFile(Candidate) and- (CompareText(ExtractFileName(Candidate), ExpectedWorkBuddyName()) = 0);+ ClientExecutableNameMatches(Candidate);end;function NextVersionComponent(const Version: String; var Offset: Integer): Integer;@@ -299,7 +332,7 @@ beginif RegQueryStringValue(RootKey, Key, 'DisplayIcon', Value) thenbeginCandidate := ExecutableFromDisplayIcon(Value);- if Pos(Lowercase(ExpectedWorkBuddyName()), Lowercase(Value)) > 0 then+ if Pos(Lowercase(ExpectedClientExecutableName()), Lowercase(Value)) > 0 thenbeginif FileExists(Candidate) thenLog('WorkDaddy installer parsed uninstall DisplayIcon: ' + Candidate)@@ -310,7 +343,7 @@ beginif not OfficialClientFile(Candidate) thenbeginif RegQueryStringValue(RootKey, Key, 'InstallLocation', Value) then- Candidate := AddBackslash(Trim(Value)) + ExpectedWorkBuddyName()+ Candidate := AddBackslash(Trim(Value)) + ExpectedClientExecutableName()elseCandidate := '';end;@@ -358,7 +391,7 @@ varIndex: Integer;beginResult := False;- Name := ExpectedWorkBuddyName();+ Name := ExpectedClientExecutableName();Candidate := '';ConsiderUninstallClients(HKCU,@@ -378,7 +411,23 @@ beginConsiderClientCandidate(Value, Candidate);SetArrayLength(Candidates, 5);- if '{#ProfileId}' = 'workbuddy-ai' then+ if '{#ProfileId}' = 'codebuddy-cn' then+ begin+ Candidates[0] := ExpandConstant('{localappdata}\Programs\CodeBuddy CN\' + Name);+ Candidates[1] := ExpandConstant('{localappdata}\CodeBuddy CN\' + Name);+ Candidates[2] := ExpandConstant('{pf}\CodeBuddy CN\' + Name);+ Candidates[3] := ExpandConstant('{pf32}\CodeBuddy CN\' + Name);+ Candidates[4] := ExpandConstant('{userappdata}\CodeBuddy CN\' + Name);+ end+ else if '{#ProfileId}' = 'codebuddy-intl' then+ begin+ Candidates[0] := ExpandConstant('{localappdata}\Programs\CodeBuddy\' + Name);+ Candidates[1] := ExpandConstant('{localappdata}\CodeBuddy\' + Name);+ Candidates[2] := ExpandConstant('{pf}\CodeBuddy\' + Name);+ Candidates[3] := ExpandConstant('{pf32}\CodeBuddy\' + Name);+ Candidates[4] := ExpandConstant('{userappdata}\CodeBuddy\' + Name);+ end+ else if '{#ProfileId}' = 'workbuddy-ai' thenbeginCandidates[0] := ExpandConstant('{localappdata}\Programs\WorkBuddyAI\' + Name);Candidates[1] := ExpandConstant('{localappdata}\Programs\WorkBuddy AI\' + Name);@@ -447,9 +496,9 @@ end;function ValidateClientSelection(const ShowError: Boolean): Boolean;beginSelectedWorkBuddyPath := Trim(ClientPage.Values[0]);- Result := UsableClientFile(SelectedWorkBuddyPath);+ Result := SelectedClientFile(SelectedWorkBuddyPath);if (not Result) and ShowError then- MsgBox('请选择要连接的 WorkBuddy .exe 主程序。', mbError, MB_OK);+ MsgBox('请选择要连接的 ' + ExpectedClientDisplayName() + ' .exe 主程序。', mbError, MB_OK);if Result thenUpdateClientDetails();end;@@ -464,11 +513,11 @@ varbeginClientPage := CreateInputFilePage(wpSelectDir,- 'WorkBuddy 客户端',- '确认 WorkDaddy 要连接的客户端',+ ExpectedClientDisplayName() + ' 客户端',+ '确认 {#ProductName} 要连接的客户端','安装程序会自动识别客户端。企业专享版或其他安装位置可以点击“浏览”修改。');- ClientPage.Add('客户端主程序:', '可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*', '.exe');+ ClientPage.Add(ExpectedClientDisplayName() + ' 主程序:', '可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*', '.exe');ClientSourceLabel := TNewStaticText.Create(ClientPage);ClientSourceLabel.Parent := ClientPage.Surface;@@ -548,6 +597,14 @@ varResultCode: Integer;beginResult := False;+ { CodeBuddy has a fixed native profile path and does not use the+ WorkBuddy enterprise-target configuration file. The selected executable+ is still used for lifecycle checks during this install. }+ if Pos('codebuddy', Lowercase('{#ProfileId}')) = 1 then+ begin+ Result := True;+ exit;+ end;NodePath := ExpandConstant('{app}\scripts\runtime\node\node.exe');ScriptPath := ExpandConstant('{app}\scripts\workbuddy-target.js');DataDir := ExpandConstant('{userappdata}\WorkDaddy');@@ -632,7 +689,7 @@ beginif CurStep = ssPostInstall thenbeginif not SaveSelectedClient() then- RaiseException('无法保存 WorkBuddy 客户端选择,安装已停止。');+ RaiseException('无法保存 ' + ExpectedClientDisplayName() + ' 客户端选择,安装已停止。');RenameUninstallerAndFixEntries();end;end;@@ -662,7 +719,7 @@ varbeginDialog := CreateCustomForm(ScaleX(480), ScaleY(196), False, False);try- Dialog.Caption := '请先退出 WorkBuddy';+ Dialog.Caption := '请先退出 ' + ExpectedClientDisplayName();Dialog.ClientWidth := ScaleX(480);Dialog.ClientHeight := ScaleY(196);Dialog.Position := poScreenCenter;@@ -676,7 +733,7 @@ beginMessageLabel.AutoSize := False;MessageLabel.WordWrap := True;MessageLabel.Font.Style := [fsBold];- MessageLabel.Caption := '安装前需要完全退出当前的 WorkBuddy。';+ MessageLabel.Caption := '安装前需要完全退出当前的 ' + ExpectedClientDisplayName() + '。';DetailLabel := TNewStaticText.Create(Dialog);DetailLabel.Parent := Dialog;@@ -727,13 +784,15 @@ function EnsureWorkBuddyClosed(): Boolean;varResultCode: Integer;Choice: Integer;+ ClientName: String;beginResult := False;+ ClientName := ExpectedClientDisplayName();while True dobeginif not RunNativeHelper('--check-workbuddy --binary "' + SelectedWorkBuddyPath + '"', ResultCode) thenbegin- MsgBox('无法启动 WorkBuddy 进程检测。请检查安全软件是否拦截安装程序。', mbError, MB_OK);+ MsgBox('无法启动 ' + ClientName + ' 进程检测。请检查安全软件是否拦截安装程序。', mbError, MB_OK);exit;end;if ResultCode = 0 then@@ -743,10 +802,12 @@ beginend;if ResultCode <> 10 thenbegin- if ResultCode = 12 then- MsgBox('无法确认 WorkBuddy 是否已退出(错误码 12)。检测到多个同名进程,或进程路径与刚才选择的客户端不一致。为避免误关其他客户端,安装已停止。请重启 Windows 后重新打开安装包,并在客户端选择页面确认 .exe 路径。', mbError, MB_OK)+ if ResultCode = 20 then+ MsgBox('所选路径不适用于当前安装包。请重新选择 ' + ClientName + ' 的 ' + ExpectedClientExecutableName() + ' 主程序。', mbError, MB_OK)+ else if ResultCode = 12 then+ MsgBox('无法确认 ' + ClientName + ' 是否已退出(错误码 12)。检测到多个同名进程,或进程路径与刚才选择的客户端不一致。为避免误关其他客户端,安装已停止。请重启 Windows 后重新打开安装包,并在客户端选择页面确认 .exe 路径。', mbError, MB_OK)else- MsgBox('无法确认 WorkBuddy 是否已退出(错误码 ' + IntToStr(ResultCode) + ')。系统没有返回可靠的进程信息,安装已停止。请重启 Windows,暂时退出安全软件的拦截功能后,再直接双击安装包重试。', mbError, MB_OK);+ MsgBox('无法确认 ' + ClientName + ' 是否已退出(错误码 ' + IntToStr(ResultCode) + ')。系统没有返回可靠的进程信息,安装已停止。请重启 Windows,暂时退出安全软件的拦截功能后,再直接双击安装包重试。', mbError, MB_OK);exit;end;Choice := ShowWorkBuddyCloseDialog();@@ -756,17 +817,17 @@ beginbeginif not RunNativeHelper('--terminate-workbuddy --binary "' + SelectedWorkBuddyPath + '" --app-dir "' + ExpandConstant('{app}') + '"', ResultCode) thenbegin- MsgBox('无法启动 WorkBuddy 结束进程操作。请检查安全软件是否拦截安装程序。', mbError, MB_OK);+ MsgBox('无法启动 ' + ClientName + ' 结束进程操作。请检查安全软件是否拦截安装程序。', mbError, MB_OK);exit;end;if ResultCode <> 0 thenbeginif ResultCode = 11 then- MsgBox('无法安全结束当前 WorkBuddy 进程(错误码 11)。普通安装器不会跨权限强行结束进程。请点击“取消”,打开任务管理器(Ctrl+Shift+Esc),结束你刚才选择的 WorkBuddy;如果它是用“以管理员身份运行”启动的,请先用相同方式退出。然后直接双击安装包,再点击“重新检测”。', mbError, MB_OK)+ MsgBox('无法安全结束当前 ' + ClientName + ' 进程(错误码 11)。普通安装器不会跨权限强行结束进程。请点击“取消”,打开任务管理器(Ctrl+Shift+Esc),结束你刚才选择的 ' + ClientName + ';如果它是用“以管理员身份运行”启动的,请先用相同方式退出。然后直接双击安装包,再点击“重新检测”。', mbError, MB_OK)else if ResultCode = 12 then- MsgBox('无法安全结束当前 WorkBuddy 进程(错误码 12)。检测到多个同名进程或安装路径不一致,为避免误关其他客户端,安装已停止。请重启 Windows 后重新选择正确的 WorkBuddy .exe,再次安装。', mbError, MB_OK)+ MsgBox('无法安全结束当前 ' + ClientName + ' 进程(错误码 12)。检测到多个同名进程或安装路径不一致,为避免误关其他客户端,安装已停止。请重启 Windows 后重新选择正确的 ' + ClientName + ' .exe,再次安装。', mbError, MB_OK)else- MsgBox('无法安全结束当前 WorkBuddy 进程(错误码 ' + IntToStr(ResultCode) + ')。请重启 Windows,确认没有 WorkBuddy 窗口或后台进程后,再直接双击安装包重试。', mbError, MB_OK);+ MsgBox('无法安全结束当前 ' + ClientName + ' 进程(错误码 ' + IntToStr(ResultCode) + ')。请重启 Windows,确认没有 ' + ClientName + ' 窗口或后台进程后,再直接双击安装包重试。', mbError, MB_OK);end;end;end;@@ -777,9 +838,13 @@ varDialog: TSetupForm;Description: TNewStaticText;ContinueButton, CancelButton: TNewButton;+ ClientName: String;+ ProductName: String;beginDialog := CreateCustomForm(ScaleX(500), ScaleY(265), False, False);try+ ClientName := ExpectedClientDisplayName();+ ProductName := '{#ProductName}';Dialog.Caption := '管理员会话兼容安装';Dialog.ClientWidth := ScaleX(500);Dialog.ClientHeight := ScaleY(265);@@ -794,7 +859,7 @@ beginDescription.WordWrap := True;Description.Caption :='这台电脑的 Windows 桌面本身使用管理员权限,无法通过桌面切换到普通权限。常见于内建 Administrator 账户或关闭 UAC 的电脑。' + #13#10 + #13#10 +- '继续后,WorkDaddy 和由它启动的 WorkBuddy 将以管理员权限运行。WorkBuddy 中的命令、插件和自动操作也会拥有更高权限,误操作可能影响系统文件和设置。' + #13#10 + #13#10 ++ '继续后,' + ProductName + ' 和由它启动的 ' + ClientName + ' 将以管理员权限运行。' + ClientName + ' 中的命令、插件和自动操作也会拥有更高权限,误操作可能影响系统文件和设置。' + #13#10 + #13#10 +'更稳妥的做法是使用普通权限桌面后重新安装。若仍要继续,此选择仅保存到当前用户、当前客户端和安装目录,之后双击快捷方式也会沿用。恢复普通权限桌面后会自动按普通权限启动。';Description.AdjustHeight();ContinueButton := TNewButton.Create(Dialog);@@ -827,7 +892,11 @@ end;function ConfirmElevatedInstall(): Boolean;varResultCode: Integer;+ ProductName: String;+ ClientName: String;begin+ ProductName := '{#ProductName}';+ ClientName := ExpectedClientDisplayName();if ElevatedInstallConfirmed or ElevatedSessionConfirmed thenbeginResult := True;@@ -873,7 +942,7 @@ beginexit;Result := MsgBox('当前安装程序是以管理员权限运行的。' + #13#10 + #13#10 +- '仍可继续安装,但安装器不会自动启动或结束 WorkDaddy/WorkBuddy。请先手动退出它们,安装完成后再双击桌面快捷方式。' + #13#10 + #13#10 ++ '仍可继续安装,但安装器不会自动启动或结束 ' + ProductName + '/' + ClientName + '。请先手动退出它们,安装完成后再双击桌面快捷方式。' + #13#10 + #13#10 +'是否仍然继续安装?',mbConfirmation,MB_YESNO@@ -885,11 +954,15 @@ end;function PrepareToInstall(var NeedsRestart: Boolean): String;varResultCode: Integer;+ ClientName: String;+ ProductName: String;beginResult := '';+ ClientName := ExpectedClientDisplayName();+ ProductName := '{#ProductName}';if not ValidateClientSelection(False) thenbegin- Result := '没有可用的 WorkBuddy 客户端路径。请返回“WorkBuddy 客户端”页面选择 .exe 主程序。';+ Result := '没有可用的 ' + ClientName + ' 客户端路径。请返回“' + ClientName + ' 客户端”页面选择 .exe 主程序。';exit;end;if IsAdmin and not ConfirmElevatedInstall then@@ -901,7 +974,7 @@ beginexit;if not EnsureWorkBuddyClosed() thenbegin- Result := '无法确认 WorkBuddy 已退出。可能原因是客户端仍有后台进程、进程权限高于当前用户、系统正在退出客户端,或安全软件阻止了进程检测。请手动结束当前客户端后重新运行安装程序。';+ Result := '无法确认 ' + ClientName + ' 已退出。可能原因是客户端仍有后台进程、进程权限高于当前用户、系统正在退出客户端,或安全软件阻止了进程检测。请手动结束当前客户端后重新运行安装程序。';exit;end;@@ -910,7 +983,7 @@ beginResultCode) thenbegin- Result := '无法启动 WorkDaddy 后台进程清理。可能原因是安装器原始用户权限不可用、安全软件拦截了临时 helper,或临时目录不可写。请点击“取消”,关闭安装程序后直接双击安装包重新运行;不要选择“以管理员身份运行”。UAC 无需关闭。';+ Result := '无法启动 ' + ProductName + ' 后台进程清理。可能原因是安装器原始用户权限不可用、安全软件拦截了临时 helper,或临时目录不可写。请点击“取消”,关闭安装程序后直接双击安装包重新运行;不要选择“以管理员身份运行”。UAC 无需关闭。';exit;end;if ResultCode = 13 then@@ -918,13 +991,13 @@ begin// API 身份凭证证明),保留它并继续安装;runtime\node 跳过本次替换。PreserveExistingLifecycle := Trueelse if ResultCode = 11 then- Result := '无法安全停止 WorkDaddy 后台进程:安装无法继续。检测到 WorkDaddy 或 WorkDaddyLauncher 仍在运行,但当前安装器没有结束它的权限(错误码 11)。请按以下步骤操作:' + #13#10 ++ Result := '无法安全停止 ' + ProductName + ' 后台进程:安装无法继续。检测到 ' + ProductName + ' 或 WorkDaddyLauncher 仍在运行,但当前安装器没有结束它的权限(错误码 11)。请按以下步骤操作:' + #13#10 +'1. 点击“取消”;' + #13#10 +- '2. 按 Ctrl+Shift+Esc 打开任务管理器,结束 WorkDaddy 和 WorkDaddyLauncher;' + #13#10 +- '3. 如果 WorkDaddy 是用“以管理员身份运行”启动的,请先用相同权限退出;' + #13#10 ++ '2. 按 Ctrl+Shift+Esc 打开任务管理器,结束 ' + ProductName + ' 和 WorkDaddyLauncher;' + #13#10 ++ '3. 如果 ' + ProductName + ' 是用“以管理员身份运行”启动的,请先用相同权限退出;' + #13#10 +'4. 确认 UAC 已开启并重启 Windows,然后直接双击安装包重试。不要选择“以管理员身份运行”。'else if ResultCode = 12 then- Result := '安装无法继续:旧版 WorkDaddy 的状态文件与实际程序不一致,或发现多个同名进程(错误码 12)。为避免误关其他程序,安装器没有强行处理。请重启 Windows,确认 WorkBuddy 已完全退出,并直接双击安装包重试;不要手动删除 WorkDaddy 数据目录。'+ Result := '安装无法继续:旧版 ' + ProductName + ' 的状态文件与实际程序不一致,或发现多个同名进程(错误码 12)。为避免误关其他程序,安装器没有强行处理。请重启 Windows,确认 ' + ClientName + ' 已完全退出,并直接双击安装包重试;不要手动删除 ' + ProductName + ' 数据目录。'else if ResultCode <> 0 then- Result := '安装无法完成 WorkDaddy 后台清理(错误码 ' + IntToStr(ResultCode) + ')。系统没有返回可靠的进程信息,可能是安全软件拦截或文件仍被占用。请重启 Windows,确认 WorkBuddy 和 WorkDaddy 都已退出后,直接双击安装包重试。';+ Result := '安装无法完成 ' + ProductName + ' 后台清理(错误码 ' + IntToStr(ResultCode) + ')。系统没有返回可靠的进程信息,可能是安全软件拦截或文件仍被占用。请重启 Windows,确认 ' + ClientName + ' 和 ' + ProductName + ' 都已退出后,直接双击安装包重试。';end;diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.goindex 20e8f7d..9f4e683 100644--- a/scripts/windows-native/main.go+++ b/scripts/windows-native/main.go@@ -20,8 +20,10 @@ import ()const (- profileCN = "workbuddy-cn"- profileAI = "workbuddy-ai"+ profileCN = "workbuddy-cn"+ profileAI = "workbuddy-ai"+ profileCodeCN = "codebuddy-cn"+ profileCodeIntl = "codebuddy-intl"exitFailure = 4exitElevated = 5@@ -468,8 +470,13 @@ func executableDir() (string, error) {}func normalizeProfile(profile string) string {- if strings.EqualFold(strings.TrimSpace(profile), profileAI) {+ switch strings.ToLower(strings.TrimSpace(profile)) {+ case profileAI:return profileAI+ case profileCodeCN:+ return profileCodeCN+ case profileCodeIntl:+ return profileCodeIntl}return profileCN}@@ -512,13 +519,19 @@ func dataDir(profile string) (string, error) {return "", errors.New("APPDATA is not available")}root = filepath.Join(root, "WorkDaddy")- if profile == profileAI {- return filepath.Join(root, "profiles", profileAI), nil+ if profile != profileCN {+ return filepath.Join(root, "profiles", profile), nil}return root, nil}func productName(profile string) string {+ if profile == profileCodeCN {+ return "CodeDaddy CN"+ }+ if profile == profileCodeIntl {+ return "CodeDaddy"+ }if profile == profileAI {return "WorkDaddy AI"}@@ -566,7 +579,55 @@ func configuredTarget(profile string) workBuddyTarget {return target}+func codeBuddyFileNameMatches(profile, binary string) bool {+ name := filepath.Base(binary)+ if profile == profileCodeCN {+ return strings.EqualFold(name, "CodeBuddy CN.exe") || strings.EqualFold(name, "CodeBuddy.exe")+ }+ if profile == profileCodeIntl {+ return strings.EqualFold(name, "CodeBuddy.exe")+ }+ return false+}++func codeBuddyBinaryMatches(profile, binary string) bool {+ if profile != profileCodeCN && profile != profileCodeIntl {+ return true+ }+ if !codeBuddyFileNameMatches(profile, binary) {+ return false+ }+ data, err := os.ReadFile(filepath.Join(filepath.Dir(binary), "resources", "app", "product.json"))+ if err != nil {+ return false+ }+ var product struct {+ ApplicationName string `json:"applicationName"`+ }+ if json.Unmarshal(data, &product) != nil {+ return false+ }+ expected := "buddy"+ if profile == profileCodeCN {+ expected = "buddycn"+ }+ return product.ApplicationName == expected+}++func codeBuddyExplicitBinaryMatches(profile, binary string) bool {+ if profile == profileCodeCN && strings.EqualFold(filepath.Base(binary), "CodeBuddy CN.exe") {+ return true+ }+ return codeBuddyBinaryMatches(profile, binary)+}+func workBuddyImage(profile string) string {+ if profile == profileCodeCN {+ return "CodeBuddy CN.exe"+ }+ if profile == profileCodeIntl {+ return "CodeBuddy.exe"+ }if target := configuredTarget(profile); len(target.ProcessNames) > 0 {return target.ProcessNames[0]}@@ -603,7 +664,7 @@ func processNamesForBinary(binary string) []string {func targetForBinary(profile, binary string) workBuddyTarget {binary = strings.TrimSpace(binary)- if (profile != profileCN && profile != profileAI) || !filepath.IsAbs(binary) ||+ if (profile != profileCN && profile != profileAI && profile != profileCodeCN && profile != profileCodeIntl) || !filepath.IsAbs(binary) ||!strings.EqualFold(filepath.Ext(binary), ".exe") || strings.ContainsAny(binary, "\r\n") {return workBuddyTarget{}}@@ -611,6 +672,10 @@ func targetForBinary(profile, binary string) workBuddyTarget {if err != nil || info.IsDir() {return workBuddyTarget{}}+ if (profile == profileCodeCN || profile == profileCodeIntl) &&+ !codeBuddyExplicitBinaryMatches(profile, binary) {+ return workBuddyTarget{}+ }return workBuddyTarget{ProfileID: profile, Binary: filepath.Clean(binary), ProcessNames: processNamesForBinary(binary)}}@@ -687,7 +752,8 @@ func matchingWorkBuddyProcessesForTarget(profile string, target workBuddyTarget)pathMatches := target.Binary == "" || (record.Path != "" &&samePath(filepath.Dir(record.Path), filepath.Dir(target.Binary)) &&strings.EqualFold(filepath.Base(record.Path), record.Name))- if nameMatches && pathMatches {+ identityMatches := target.Binary != "" || codeBuddyBinaryMatches(profile, record.Path)+ if nameMatches && pathMatches && identityMatches {matched = append(matched, record)}}@@ -1036,6 +1102,12 @@ func stopLifecycle(profile, appDir string, elevated bool) int {// profileUiPorts returns the fixed UI-port candidates for a profile in// preference order. They mirror scripts/ui-port.js PROFILE_UI_PORTS.func profileUiPorts(profile string) []int {+ if profile == profileCodeCN {+ return []int{47834, 17834, 27834, 37834}+ }+ if profile == profileCodeIntl {+ return []int{47835, 17835, 27835, 37835}+ }if profile == profileAI {return []int{47833, 17833, 27833, 37833}}diff --git a/scripts/workbuddy-compat.js b/scripts/workbuddy-compat.jsindex 5a662da..ccf9899 100644--- a/scripts/workbuddy-compat.js+++ b/scripts/workbuddy-compat.js@@ -361,14 +361,42 @@return null;}+ // CodeBuddy 4.12 uses square IconButton controls without an aria-label.+ // Identify the official submit handler by its editor preparation contract,+ // never by geometry or position (our composer buttons share that toolbar).+ function findCodeBuddySendButton(doc) {+ if (!doc) return null;+ var selector = '[class*="_inputBox_"]';+ var active = doc.activeElement;+ var box = active && active.closest ? active.closest(selector) : null;+ if (!box) {+ var boxes = Array.from(doc.querySelectorAll(selector)).filter(function (el) {+ return !el.getBoundingClientRect || el.getBoundingClientRect().width > 0;+ });+ if (boxes.length !== 1) return null;+ box = boxes[0];+ }+ var matches = Array.from(box.querySelectorAll('[role="button"],button')).filter(function (el) {+ if (el.closest('.wbs-root,.wbs-stash-inline')) return false;+ var key = Object.keys(el).find(function (k) { return k.indexOf('__reactProps') === 0; });+ var handler = key && el[key] && el[key].onClick;+ if (typeof handler !== 'function') return false;+ var source = Function.prototype.toString.call(handler);+ return source.indexOf('prepareBeforeSubmit') >= 0 && source.indexOf('flushPendingContentChange') >= 0;+ });+ return matches.length === 1 ? matches[0] : null;+ }+function findQueueAdapter(doc) {return findModernQueueAdapter(doc) || findLegacyQueueAdapter(doc);}- function functionLooksLikeConversationNavigation(value) {+ function functionLooksLikeConversationNavigation(value, nativeCodeBuddy) {if (typeof value !== 'function') return false;try {var source = Function.prototype.toString.call(value);+ if (nativeCodeBuddy && source.indexOf('SessionLoadCancelledError') >= 0 &&+ source.indexOf('getPendingMessageTracker') >= 0 && source.indexOf('getInitialMessages') >= 0) return true;return source.indexOf('dismissHoverPeek') >= 0 &&source.indexOf('syncTaskRouteFromClick') >= 0;} catch (_) {@@ -376,13 +404,14 @@}}- function findConversationNavigationHandler(doc) {+ function findConversationNavigationHandler(doc, nativeCodeBuddy) {if (!doc || typeof doc.querySelector !== 'function') return null;var roots = [doc.querySelector('#root > div'),doc.querySelector('.conversation-list'),doc.querySelector('.conversation-shell'),doc.querySelector('.conversation-item'),+ nativeCodeBuddy ? doc.querySelector('[data-conversation-id]') : null,];for (var ri = 0; ri < roots.length; ri++) {var root = roots[ri];@@ -394,8 +423,8 @@while (hook && hookSeen++ < 700) {var state = hook.memoizedState;var candidate = state && typeof state === 'object' ? state.current : null;- if (functionLooksLikeConversationNavigation(candidate)) return candidate;- if (functionLooksLikeConversationNavigation(state)) return state;+ if (functionLooksLikeConversationNavigation(candidate, nativeCodeBuddy)) return candidate;+ if (functionLooksLikeConversationNavigation(state, nativeCodeBuddy)) return state;hook = hook.next;}fiber = fiber.return;@@ -421,11 +450,12 @@// WorkBuddy's conversation list owns the real navigation path. Prefer the// official SDK/navigation handler; adapter.emit is retained for older builds// whose list did not expose the handler through React hooks.- function findConversationActivationApi(doc) {+ function findConversationActivationApi(doc, options) {+ var nativeCodeBuddy = !!(options && /^codebuddy-(cn|intl)$/.test(options.profileId));var found = findQueueAdapter(doc);var adapter = found && found.adapter;var resource = findSessionsResource(doc);- var handler = findConversationNavigationHandler(doc);+ var handler = findConversationNavigationHandler(doc, nativeCodeBuddy);var sdkNavigate = null;var sdkNavigateKind = '';try {@@ -441,7 +471,7 @@sdkNavigateKind = 'setCurrentConversation';}} catch (_) {}- if (!handler && !sdkNavigate && (!adapter || typeof adapter.emit !== 'function')) return null;+ if (!handler && !sdkNavigate && (nativeCodeBuddy || !adapter || typeof adapter.emit !== 'function')) return null;return {authoritative: !!(handler || sdkNavigate),hasSession: function (sessionId) {@@ -466,7 +496,7 @@if (!id) return false;try {if (handler) {- Promise.resolve(handler(id, '', false, false, {})).catch(function () {});+ Promise.resolve(handler(id, '', false, false, nativeCodeBuddy ? undefined : {})).catch(function () {});} else if (sdkNavigate) {var conversationsApi = (typeof window !== 'undefined' && window.wb && window.wb.conversations) || null;Promise.resolve(sdkNavigate.call(conversationsApi, id, sdkNavigateKind === 'navigateToSession' ? { ensureLoaded: true } : undefined)).catch(function () {});@@ -552,6 +582,7 @@draftStorageKey: draftStorageKey,collectMessageNavigationTurnsFromMessages: collectMessageNavigationTurnsFromMessages,findComposerToolbar: findComposerToolbar,+ findCodeBuddySendButton: findCodeBuddySendButton,findLegacyQueueAdapter: findLegacyQueueAdapter,findModernQueueAdapter: findModernQueueAdapter,findQueueAdapter: findQueueAdapter,diff --git a/test/account-switch-session-rules.test.js b/test/account-switch-session-rules.test.jsindex a9259f3..c47c407 100644--- a/test/account-switch-session-rules.test.js+++ b/test/account-switch-session-rules.test.js@@ -19,7 +19,7 @@ function harness(rules, owner = 'source') {currentAccount: () => ({ uid: 'source' }),preserveAccountSwitchTheme: async uid => { assert.equal(uid, 'target'); events.push('preserve-theme'); },sqliteQuery: async () => owner ? [{ user_id: owner, cwd: '/current-workspace' }] : [],- switchTo: (_, uid) => { events.push('switch'); return { uid }; },+ switchAccountForProfile: (uid) => { events.push('switch'); return { uid }; },reloadWorkBuddyPage: async () => { events.push('reload'); },mainFrameNavigationSerial: 1, setTimeout() {},getAutoCopyRules: () => rules,@@ -35,7 +35,7 @@ function harness(rules, owner = 'source') {const routeStart = source.indexOf(" if (req.method === 'POST' && p === '/api/switch')");const routeEnd = source.indexOf('\n return json(res, 404', routeStart);vm.runInContext('async function switchRoute(req, res) { const p = "/api/switch";\n' + source.slice(routeStart, routeEnd) + '\n}', ctx);- return { jobs, events, run: () => ctx.switchRoute({ method: 'POST', body: { uid: 'target', reload: true, currentConversationId: 'open' } }, {}) };+ return { jobs, events, run: (currentConversationId = 'open') => ctx.switchRoute({ method: 'POST', body: { uid: 'target', reload: true, currentConversationId } }, {}) };}test('switch route reloads without syncing when no rule is enabled', async () => {@@ -81,3 +81,56 @@ for (const owner of ['', 'other-account']) {assert.equal(h.jobs[0].openSessionId, '');});}++const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+const captureSource = inject.slice(inject.indexOf(' function acActiveConversationId()'), inject.indexOf(' /** 会话身份签名:'));+const compat = require('../scripts/workbuddy-compat');++function rendererCapture(profileId, adapter, window = {}) {+ const node = { __reactFiber$test: { memoizedProps: { adapter }, return: null } };+ const context = vm.createContext({+ PROFILE_ID: profileId, CAPS: { enhance: false }, window,+ WBS_COMPAT: compat, URL, location: { href: 'https://client.invalid/agentManager.html' },+ document: { querySelector: selector => selector === '.chat-container' ? node : null, querySelectorAll: () => [] },+ });+ vm.runInContext(captureSource, context);+ return context;+}++for (const profile of ['codebuddy-cn', 'codebuddy-intl']) {+ test(profile + ': switch captures the live conversation without composer enhancement initialization', async () => {+ let queueCalls = 0;+ const adapter = { currentActiveSessionId: 'open',+ enqueueConversationMessageQueueItem() { queueCalls++; }, pauseConversationMessageQueue() { queueCalls++; } };+ const renderer = rendererCapture(profile, adapter);+ const h = harness({ allSessions: true, sessionIds: [], workspaces: [] });+ const result = await h.run(renderer.acSwitchConversationId());+ assert.equal(result.status, 200);+ assert.equal(h.jobs[0].openSessionId, 'open', 'the actual switch request must carry the source conversation');+ adapter.currentActiveSessionId = 'copied-target';+ assert.equal(renderer.acActiveConversationId(), 'copied-target', 'activation confirmation reads the live destination');+ adapter.currentActiveSessionId = '';+ renderer.window.__wbsAdapter = { currentActiveSessionId: 'stale-source' };+ assert.equal(renderer.acSwitchConversationId(), '', 'welcome page must not reuse a stale enhancement cache');+ assert.equal(queueCalls, 0, 'session capture must not mutate the composer or queue');+ });+}++for (const profile of ['workbuddy-cn', 'workbuddy-ai']) {+ test(profile + ': SDK, hydration fallback and legacy cache keep their switch behavior', async () => {+ const renderer = rendererCapture(profile, null, { wb: { conversations: { currentId: 'open' } }, __wbsAdapter: { currentActiveSessionId: 'stale' } });+ let nativeLookups = 0;+ renderer.WBS_COMPAT = { findQueueAdapter() { nativeLookups++; }, getSelectedConversationId() { nativeLookups++; } };+ assert.equal(renderer.acActiveConversationId(), 'open');+ const h = harness({ allSessions: true, sessionIds: [], workspaces: [] });+ await h.run(renderer.acSwitchConversationId());+ assert.equal(h.jobs[0].openSessionId, 'open');+ renderer.window.wb.conversations.currentId = '';+ renderer.document.querySelector = selector => selector === '.cr-document[data-root-id]' ? { getAttribute: () => 'mounted-session' } : null;+ assert.equal(renderer.acActiveConversationId(), '', 'SDK hydration remains authoritative for monitors');+ assert.equal(renderer.acSwitchConversationId(), 'mounted-session', 'switch keeps its mounted-document fallback');+ delete renderer.window.wb;+ assert.equal(renderer.acActiveConversationId(), 'stale', 'legacy WorkBuddy cache path is unchanged');+ assert.equal(nativeLookups, 0, 'CodeBuddy discovery must never run for WorkBuddy');+ });+}diff --git a/test/automation-checkin.test.js b/test/automation-checkin.test.jsindex 2692a43..439023a 100644--- a/test/automation-checkin.test.js+++ b/test/automation-checkin.test.js@@ -98,7 +98,7 @@ test('legacy implicit triggers and pending UI are removed; panel event is explicassert.doesNotMatch(ui,/签到中|watchCheckin|stopCheckinPolling/);assert.match(ui,/\/api\/automations\/events/);const html=ui.slice(ui.indexOf('function checkinHtml'),ui.indexOf('function el(tag'));- const ctx={WBS_PROFILE_IS_AI:false};vm.createContext(ctx);vm.runInContext(html,ctx);+ const ctx={WBS_PROFILE_IS_AI:false,CAPS:{checkin:true}};vm.createContext(ctx);vm.runInContext(html,ctx);assert.match(ctx.checkinHtml({}),/pending.*今日未签到/);assert.match(ctx.checkinHtml({checkin:{ok:true}}),/tag ok.*今日已签到/);assert.doesNotMatch(ctx.checkinHtml({checkin:{ok:false,message:'bad'}}),/bad/);@@ -159,23 +159,69 @@ test('automation editor assigns remaining height to the code field without an ouassert.doesNotMatch(rules,/height:calc\(100% - 164px\)|min-height:190px/);});-test('fresh CN receives Buddy travel and check-in disabled while AI keeps the two existing presets', () => {- const init = source.slice(source.indexOf("for (const preset of ['close-buddy-popups.json'"), source.indexOf('\nrestoreSleepMode();'));+test('international profiles retire all old builtins and never install new ones; domestic profiles keep theirs', () => {+ const start = source.indexOf('if (PROFILE.capabilities.builtinAutomations === false) {');+ assert.ok(start >= 0);+ const init = source.slice(start, source.indexOf('\nrestoreSleepMode();'));const { PROFILES } = require('../scripts/profiles');- for (const id of ['workbuddy-cn', 'workbuddy-ai']) {+ for (const id of ['workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl']) {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-presets-'));try {- const context = { PROFILE: PROFILES[id], DATA_DIR: dir, path, __dirname: path.join(__dirname, '../scripts'), installBuiltinTask: automation.installBuiltinTask, log() {} };+ if (PROFILES[id].region === 'intl') {+ for (const preset of ['close-buddy-popups.json', 'keep-accounts-active.json', 'buddy-travel.json', 'daily-account-checkin.json']) automation.installBuiltinTask(dir, path.join(__dirname, '../scripts/builtin/automations', preset), PROFILES[id]);+ }+ const context = { PROFILE: PROFILES[id], DATA_DIR: dir, path, __dirname: path.join(__dirname, '../scripts'), installBuiltinTask: automation.installBuiltinTask, removeBuiltinTasks: automation.removeBuiltinTasks, log() {} };vm.runInNewContext(init, context);- assert.deepEqual(automation.readAutomations(dir).map(t => t.id).sort(), id === 'workbuddy-cn'+ const domestic = id === 'workbuddy-cn' || id === 'codebuddy-cn';+ assert.deepEqual(automation.readAutomations(dir).map(t => t.id).sort(), domestic? ['buddy-fuel-station-close-on-account-switch', 'daily-account-checkin', 'daily-growth-and-buddy', 'keep-accounts-active-1-plus-1']- : ['buddy-fuel-station-close-on-account-switch', 'keep-accounts-active-1-plus-1']);- if (id === 'workbuddy-cn') for (const taskId of ['daily-growth-and-buddy', 'daily-account-checkin']) {+ : []);+ if (domestic) for (const taskId of ['daily-growth-and-buddy', 'daily-account-checkin']) {assert.equal(automation.readAutomations(dir).find(t => t.id === taskId).enabled, false);}+ const travel = automation.readAutomations(dir).find(t => t.id === 'daily-growth-and-buddy');+ if (travel) {+ const urls = [];+ const walk = value => {+ if (!value || typeof value !== 'object') return;+ if (value.op === 'http.requestAsAccount') urls.push(new URL(value.url).origin);+ Object.values(value).forEach(walk);+ };+ walk(travel.steps);+ assert.ok(urls.length > 0);+ const expectedOrigin = PROFILES[id].kind === 'codebuddy' ? PROFILES[id].apiHost : 'https://www.workbuddy.cn';+ assert.ok(urls.every(origin => origin === expectedOrigin), id + ': preserve WorkBuddy endpoints and isolate CodeBuddy origins');+ }automation.writeAutomations(dir, []);vm.runInNewContext(init, context);assert.equal(automation.readAutomations(dir).length, 0);} finally { fs.rmSync(dir, { recursive: true, force: true }); }}});++test('retiring unsupported builtins preserves imported tasks and unrelated automation settings', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-retire-'));+ try {+ const file = path.join(__dirname, '../scripts/builtin/automations/daily-account-checkin.json');+ automation.writeAutomations(dir, [automation.validateTask(JSON.parse(fs.readFileSync(file, 'utf8')))]);+ automation.installBuiltinTask(dir, file); // Existing imported id is unmanaged.+ const before = automation.readAutomations(dir);+ automation.removeBuiltinTasks(dir);+ assert.deepEqual(automation.readAutomations(dir), before);+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }+});++test('CodeBuddy international has no check-in badge; domestic profiles keep theirs', () => {+ const ui = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const start = ui.indexOf(' function checkinHtml(a) {');+ const badge = ui.slice(start, ui.indexOf('\n function activityStreakHtml', start));+ const { PROFILES } = require('../scripts/profiles');+ for (const id of Object.keys(PROFILES)) {+ const ctx = { WBS_PROFILE_IS_AI: id === 'workbuddy-ai', CAPS: PROFILES[id].capabilities };+ vm.runInNewContext(badge, ctx);+ if (id === 'codebuddy-intl' || id === 'workbuddy-ai') {+ assert.equal(ctx.checkinHtml({}), '');+ assert.equal(ctx.checkinHtml({ checkin: { ok: true } }), '');+ } else assert.match(ctx.checkinHtml({}), /今日未签到/);+ }+});diff --git a/test/automation-discovery.test.js b/test/automation-discovery.test.jsindex fe3ba56..eb86b68 100644--- a/test/automation-discovery.test.js+++ b/test/automation-discovery.test.js@@ -279,3 +279,15 @@ test('daemon includes a disabled check-in preset without a risk prompt', () => {assert.match(daemon, /daily-account-checkin\.json/);assert.doesNotMatch(inject, /showCheckinRiskOnOpen/);});++test('separate clients reuse the newest public catalog while retaining their own compatibility', async t => {+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-discovery-shared-'));+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));+ const f=fixture();+ const offline=createAutomationDiscovery({dataDir:dir,now:f.now,runtime:{...runtime,profileId:'codebuddy-cn'},fetchImpl:async()=>{throw Error('offline');}});+ const workbuddy=createAutomationDiscovery({dataDir:dir,now:f.now,runtime,fetchImpl:f.fetchImpl,pageSize:2});+ const first=await workbuddy.getCatalog({force:true});assert.ok(first.tasks.length);+ const second=await offline.getCatalog();assert.equal(second.tasks.length,first.tasks.length);+ const failedRefresh=await offline.getCatalog({force:true});assert.equal(failedRefresh.tasks.length,first.tasks.length);+ assert.equal(failedRefresh.stale,true);+});diff --git a/test/automation-popup-dismiss.test.js b/test/automation-popup-dismiss.test.jsindex f948e84..eb0c868 100644--- a/test/automation-popup-dismiss.test.js+++ b/test/automation-popup-dismiss.test.js@@ -18,6 +18,7 @@ function runPopupTask(appearAt, failedConfirmations = 0) {return selector;};const context = {+ PROFILE: { capabilities: {} },require: require('node:module').createRequire(path.join(__dirname, '../scripts/automation.js')), module: { exports: {} },setTimeout: (callback, ms) => { now += ms; callback(); },};@@ -113,6 +114,7 @@ test('a newer navigation supersedes a running opt-in task instead of dropping itconst end = source.indexOf('\nfunction onCdpEvent(', start);const running = { taskId: 'popup', status: 'running', navigationSerial: 1 };const context = {+ PROFILE: { capabilities: {} },taskMatchesEvent: require('../scripts/automation').taskMatchesEvent,automationEventKeys: new Set(), mainFrameNavigationSerial: 2, cdpPageSessionId: 'renderer-a',automationRuns: new Map([['run', running]]), DATA_DIR: '/test',@@ -133,6 +135,7 @@ test('pageReady is deduplicated per renderer page rather than per CDP connectionconst end = source.indexOf('\nfunction onCdpEvent(', start);const launched = [];const context = {+ PROFILE: { capabilities: {} },taskMatchesEvent: () => true,automationEventKeys: new Set(), mainFrameNavigationSerial: 7, cdpPageSessionId: 'renderer-a',automationRuns: new Map(), DATA_DIR: '/test',@@ -175,6 +178,7 @@ test('a running cleanup stops before the next navigation begins its own cleanup'const executions = [], restored = [];const noop = () => {};const context = {+ PROFILE: { capabilities: {} },taskIsPassiveCleanup: require('../scripts/automation').taskIsPassiveCleanup, taskMatchesEvent: require('../scripts/automation').taskMatchesEvent, taskNeedsPanelClosed: require('../scripts/automation').taskNeedsPanelClosed,...require('../scripts/automation-runtime'),acquireAutomationInput: require('../scripts/automation-runtime').createRendererGate(),@@ -229,6 +233,7 @@ test('automation DOM click dispatches the located button without undefined requeconst clicks = [];const found = { x: 10, y: 20, w: 20, h: 30, visible: true };const context = {+ PROFILE: { capabilities: {} },cdp: { connected: true },automationDeepLocatorExpression: () => 'null',cdpSend: async () => ({ result: { value: found } }),@@ -254,6 +259,7 @@ test('popup clicks bypass mouse-move acknowledgement while normal clicks retainconst end = source.indexOf('\nfunction cdpSend(', start);const events = [];const context = {+ PROFILE: { capabilities: {} },cdp: {}, log() {}, cdpFocusDiagnostics: async () => {},cdpSend: async (_, params) => events.push(params.type),};@@ -270,6 +276,7 @@ test('waiting for a dismissed button succeeds immediately when its DOM node wasconst start = source.indexOf('async function automationDomAction(');const end = source.indexOf('\nasync function automationHttpRequest(', start);const context = {+ PROFILE: { capabilities: {} },cdp: { connected: true },automationDeepLocatorExpression: () => 'null',cdpSend: async () => ({ result: { value: null } }),diff --git a/test/automation-switch-sync.test.js b/test/automation-switch-sync.test.jsindex f1b2bdc..0053d66 100644--- a/test/automation-switch-sync.test.js+++ b/test/automation-switch-sync.test.js@@ -14,7 +14,7 @@ function harness() {PROFILE: { kind: 'workbuddy' }, DATA_DIR: '/synthetic', log() {},cdp: { connected: true }, cdpSend: async () => ({ result: { value: false } }),preserveAccountSwitchTheme: async uid => { themeTargets.push(uid); },- currentAccount: () => active, switchTo: (_dir, uid) => { assert.equal(themeTargets.at(-1), uid, 'appearance is prepared before replacing the account'); switches.push(uid); return (active = { uid }); },+ currentAccount: () => active, switchAccountForProfile: (uid) => { assert.equal(themeTargets.at(-1), uid, 'appearance is prepared before replacing the account'); switches.push(uid); return (active = { uid }); },reloadWorkBuddyPage: async () => {}, pendingAutomationAccountSwitch: null,dispatchAutomationEvent() {}, mainFrameNavigationSerial: 1,beginRendererReloadPriority: () => { reloadPriority++; return () => { reloadPriority--; }; },diff --git a/test/cdp-targets.test.js b/test/cdp-targets.test.jsindex 736f7c5..32b7d9e 100644--- a/test/cdp-targets.test.js+++ b/test/cdp-targets.test.js@@ -143,3 +143,17 @@ test('looksLikeWbFamilyTarget 把四客户端页面都视为同族(不清理// 任意其他 Chromium 应用不算同族(允许清理历史误注入)assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: 'file:///Applications/Antigravity.app/Contents/index.html', title: 'Antigravity' }), false);});++test('CodeBuddy selects only its Agents window regardless of target order', () => {+ for (const id of ['codebuddy-cn', 'codebuddy-intl']) {+ const app = id === 'codebuddy-cn' ? 'CodeBuddy%20CN' : 'CodeBuddy';+ const base = 'vscode-file://vscode-app/Applications/' + app + '.app/Contents/Resources/app/out/vs/code/electron-browser/workbench/';+ const ide = {type: 'page', url: base + 'workbench.html'};+ const agents = {type: 'page', url: base + 'agentManager.html'};+ assert.equal(selectPageTarget([ide], PROFILES[id]), null);+ assert.equal(selectPageTarget([ide, agents], PROFILES[id]), agents);+ assert.equal(selectPageTarget([agents, ide], PROFILES[id]), agents);+ const other = id === 'codebuddy-cn' ? 'codebuddy-intl' : 'codebuddy-cn';+ assert.equal(selectPageTarget([agents], PROFILES[other]), null);+ }+});diff --git a/test/codebuddy-compat.test.js b/test/codebuddy-compat.test.jsnew file mode 100644index 0000000..38b922e--- /dev/null+++ b/test/codebuddy-compat.test.js@@ -0,0 +1,160 @@+ 'use strict';+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const vm = require('node:vm');+const test = require('node:test');+const {PROFILES}=require('../scripts/profiles');+const {rendererBridgeSource}=require('../scripts/renderer-api-bridge');+const inject=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');+const daemon=fs.readFileSync(path.join(__dirname,'../scripts/daemon.js'),'utf8');+test('CodeBuddy keeps accounts, sessions and models but disables composer enhancements and glass takeover',()=>{+ for(const id of ['codebuddy-cn','codebuddy-intl']) {+ const c=PROFILES[id].capabilities;+ for(const key of ['accounts','sessions','models','theme']) assert.equal(c[key],true);+ assert.equal(c.themeTakeover,false);assert.equal(c.enhance,false);assert.equal(c.nativeComposer,true);assert.equal(c.stashPrompt,false);+ assert.equal(c.sessionsReadOnly,undefined);assert.equal(c.modelsReadOnly,undefined);+ assert.equal(c.apiTransport,'cdp');assert.equal(c.panelAppearance,'light');assert.equal(c.robotStyle,'black');+ }+ assert.doesNotMatch(inject,/WBS_CODEBUDDY_BOOTSTRAP|CAPS\.sessionsReadOnly|CAPS\.modelsReadOnly/);+ assert.match(inject,/CAPS\.enhance === false/);+ assert.match(inject,/themeSwitch\.disabled = true/);+ assert.match(inject,/window\.__wbsApiFetch\(path, request, WBS_API_TOKEN\)/);+});+test('CodeBuddy injection compiles with all shared pages and the CSP-compatible bridge',()=>{+ const start=daemon.indexOf('function buildInjectScript()');+ const end=daemon.indexOf('function injectWidgetManual()',start);+ const ctx=vm.createContext({fs,path,__dirname:path.join(__dirname,'../scripts'),PROFILE:PROFILES['codebuddy-cn'],rendererBridgeSource,+ HOST:'127.0.0.1',ACTUAL_PORT:47834,DAEMON_VERSION:'test',API_TOKEN:'fixture',diagnosticsEnabled:()=>false,process});+ vm.runInContext(daemon.slice(start,end),ctx);+ const script=ctx.buildInjectScript();new vm.Script(script);+ assert.ok(script.includes('CodeDaddy CN'));assert.ok(script.includes('root.__wbsHTML ='));+ assert.ok(script.includes('__wbsLocalApiRequest'));+});+test('CodeBuddy HTML compatibility keeps the official innerHTML sink unchanged', () => {+ const start = daemon.indexOf(" const trustedTypesBootstrap =");+ const end = daemon.indexOf(" let source =", start);+ const bootstrap = new Function('PROFILE', daemon.slice(start, end) + 'return trustedTypesBootstrap;')(PROFILES['codebuddy-cn']);+ class Element {}+ const nativeSet = function (html) { if (!html || !html.trusted) throw Error('TrustedHTML required'); this.html = html.value; };+ const adjacent = function (position, html) { nativeSet.call(this,html); this.position=position; };+ Element.prototype.insertAdjacentHTML=adjacent;+ Object.defineProperty(Element.prototype, 'outerHTML', {configurable:true,set:nativeSet,get(){return this.html;}});+ Object.defineProperty(Element.prototype, 'innerHTML', {configurable: true, set: nativeSet, get() {return this.html;}});+ const ctx = vm.createContext({Element, window: {}, trustedTypes: {createPolicy: () => ({createHTML:value=>({trusted:true,value})})}});+ vm.runInContext(bootstrap, ctx);+ vm.runInContext(bootstrap, ctx);+ assert.equal(Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML').set, nativeSet);+ const el = new Element(); el.__wbsHTML = '<b>escaped template</b>';+ assert.equal(el.innerHTML, '<b>escaped template</b>');+ el.__wbsOuterHTML='<span>updated</span>'; assert.equal(el.outerHTML,'<span>updated</span>');+ el.__wbsInsertAdjacentHTML('beforeend','<span>inserted</span>'); assert.equal(el.position,'beforeend');+ assert.equal(Element.prototype.insertAdjacentHTML,adjacent);+ assert.throws(()=>{el.innerHTML='raw';},/TrustedHTML/);+ assert.throws(()=>{el.outerHTML='raw';},/TrustedHTML/);+ assert.throws(()=>el.insertAdjacentHTML('beforeend','raw'),/TrustedHTML/);+});+++test('updates select only the matching brand and prefer Setup over historical ZIP',()=>{+ const start=daemon.indexOf('function selectUpdateAsset('),end=daemon.indexOf('function makeUpdateCandidate(',start);+ const source={downloadRoot:'https://example.test/releases'};+ const names=['WorkDaddy','WorkDaddy-AI','CodeDaddy-CN','CodeDaddy'];+ const assets=names.flatMap(n=>[n+'-1.2.191.dmg',n+'-1.2.191-win64.zip',n+'-Setup-1.2.191.exe']).map(name=>({name,browser_download_url:source.downloadRoot+'/'+name}));+ for(const profile of Object.values(PROFILES))for(const windows of [true,false]){+ const context={PROFILE:profile,IS_WIN:windows};vm.runInNewContext(daemon.slice(start,end),context);+ assert.equal(context.selectUpdateAsset(source,{assets}).name,profile.packageName+(windows?'-Setup-1.2.191.exe':'-1.2.191.dmg'));+ assert.equal(context.selectUpdateAsset(source,{assets:assets.filter(a=>a.name!==profile.packageName+'-1.2.191.dmg' && !a.name.startsWith(profile.packageName+'-Setup-') && a.name!==profile.packageName+'-1.2.191-win64.zip')}),null);+ }+});++test('CodeBuddy Windows binaries support the current CN name and separate editions by product metadata',t=>{+ const {isCodeBuddyBinary}=require('../scripts/profiles');+ const os=require('node:os');+ const root=fs.mkdtempSync(path.join(os.tmpdir(),'codedaddy-product-'));+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));+ fs.mkdirSync(path.join(root,'resources','app'),{recursive:true});+ const cnExe=path.join(root,'CodeBuddy CN.exe');fs.writeFileSync(cnExe,'fixture');+ const legacyExe=path.join(root,'CodeBuddy.exe');fs.writeFileSync(legacyExe,'fixture');+ assert.equal(isCodeBuddyBinary(cnExe,'codebuddy-cn'),false);+ fs.writeFileSync(path.join(root,'resources','app','product.json'),JSON.stringify({applicationName:'buddycn'}));+ assert.equal(isCodeBuddyBinary(cnExe,'codebuddy-cn'),true);+ assert.equal(isCodeBuddyBinary(legacyExe,'codebuddy-cn'),true);+ assert.equal(isCodeBuddyBinary(cnExe,'codebuddy-intl'),false);+ assert.equal(isCodeBuddyBinary(legacyExe,'codebuddy-intl'),false);+ const expectedPathName = process.platform === 'win32' ? 'CodeBuddy CN.exe' : 'CodeBuddy CN.app';+ assert.equal(path.basename(PROFILES['codebuddy-cn'].appPath), expectedPathName);+});++test('CodeBuddy waits for page load rather than mounting into the disposable bootstrap body',async()=>{+ const start=daemon.indexOf('async function injectWidget(reason, executionContextId)');+ const end=daemon.indexOf('\nfunction buildInjectScript()',start);+ const inject=vm.runInNewContext('('+daemon.slice(start,end)+')',{PROFILE:{kind:'codebuddy'},cdp:{connected:true}});+ const result=await inject('reload-context',1);+ assert.equal(result.mounted,false);+});++test('CodeBuddy relaunch helpers accept only the matching installation, including encoded spaces', () => {+ const {spawnSync} = require('node:child_process');+ for (const [file, name, binary, own, sibling] of [+ ['relaunch-with-cdp.sh', 'is_workbuddy_cdp', '/Applications/CodeBuddy CN.app/Contents/MacOS/Electron', '/Applications/CodeBuddy%20CN.app/Contents/Resources/app/agentManager.html', '/Applications/CodeBuddy.app/Contents/Resources/app/agentManager.html'],+ ['relaunch-with-cdp-linux.sh', 'is_profile_cdp', '/opt/CodeBuddy CN/codebuddy', '/opt/CodeBuddy%20CN/resources/app/agentManager.html', '/opt/CodeBuddy/resources/app/agentManager.html'],+ ]) {+ const source = fs.readFileSync(path.join(__dirname, '../scripts', file), 'utf8');+ const fn = source.slice(source.indexOf(name + '() {')).split('\n}\n')[0] + '\n}';+ for (const [url, expected] of [[own, 0], [sibling, 1]]) {+ const shell = `PROFILE=codebuddy-cn\nAPP_BIN='${binary}'\nAPP_NAME='CodeBuddy CN'\ncurl() { printf '%s' '${JSON.stringify([{url}])}'; }\ncurl_local() { curl; }\n${fn}\n${name} 9224`;+ assert.equal(spawnSync('bash', ['-c', shell]).status, expected, file + ': ' + url);+ }+ }+});++test('macOS uninstall limits launchd removal to selected profile and legacy cleanup to WorkBuddy CN', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/uninstall.sh'), 'utf8');+ assert.match(source, /for old_profile in "\$PROFILE"/);+ assert.match(source, /if \[ "\$PROFILE" = workbuddy-cn \]; then/);+});++test('native panel mount survives body replacement, restores the same node, and disposes observers', () => {+ const match=inject.match(/function preserveNativePanelMount\(doc, root, Observer\) \{[\s\S]*?\n\}/);+ assert.ok(match, 'mount lifecycle helper exists');+ const preserve=vm.runInNewContext('('+match[0]+')');+ const observers=[];+ class Observer { constructor(fn){this.fn=fn;this.targets=[];observers.push(this);} observe(target,options){assert.equal(options.subtree,undefined);this.targets.push(target);} disconnect(){this.targets=[];} }+ const root={isConnected:true};+ const body=()=>({appendChild(node){assert.equal(node,root);node.isConnected=true;this.count=(this.count||0)+1;}});+ const doc={documentElement:{},body:body()};+ const dispose=preserve(doc,root,Observer);+ root.isConnected=false;observers[0].fn();assert.equal(doc.body.count,1);+ doc.body=body();root.isConnected=false;observers[1].fn();assert.equal(doc.body.count,1);+ assert.ok(observers[0].targets.includes(doc.body));+ observers[1].fn();assert.equal(doc.body.count,1);+ dispose();root.isConnected=false;observers[1].fn();assert.equal(root.isConnected,false);+ assert.ok(observers.every(x=>x.targets.length===0));+});++test('native overlay mounts restore prebuilt account popovers along with the panel', () => {+ const match=inject.match(/function preserveNativePanelMount\(doc, root, Observer\) \{[\s\S]*?\n\}/);+ const preserve=vm.runInNewContext('('+match[0]+')');const observers=[];+ class Observer {constructor(fn){this.fn=fn;observers.push(this);}observe(){}disconnect(){}}+ const body=()=>({appendChild(n){n.isConnected=true;}});+ const doc={body:body(),documentElement:{}},root={isConnected:true},popup={isConnected:false};+ const dispose=preserve(doc,root,Observer);assert.equal(typeof dispose.keep,'function');dispose.keep(popup);+ root.isConnected=false;popup.isConnected=false;doc.body=body();observers[1].fn();+ assert.ok(root.isConnected&&popup.isConnected);+ dispose();popup.isConnected=false;observers[0].fn();assert.equal(popup.isConnected,false);+});++test('CN retains real growth and streak controls and panel identity is separate from package branding', () => {+ assert.equal(PROFILES['codebuddy-cn'].capabilities.growthDaily,true);+ assert.match(inject,/WBS_PANEL_TITLE/);+ assert.match(inject,/' for ' \+ WBS_BRAND/);+});++test('CN streak refresh uses the same capability as the account growth panel', async () => {+ const start=daemon.indexOf(" if (req.method === 'POST' && p === '/api/growth/streak')");+ const end=daemon.indexOf(' // 查询指定账号今日是否活跃',start);+ const handle=new Function('req','p','res','readBody','PROFILE','fs','accountBackupFile','growthStreakCache','json',daemon.slice(start,end));+ const result=await handle({method:'POST'},'/api/growth/streak',{},async()=>({uid:'fixture'}),PROFILES['codebuddy-cn'],{existsSync:()=>true},()=>'/fixture',{get:async()=>({days:2})},(_,status,body)=>({status,body}));+ assert.equal(result.status,200);assert.equal(result.body.activityStreak.days,2);+});diff --git a/test/codebuddy-files.test.js b/test/codebuddy-files.test.jsnew file mode 100644index 0000000..0a58628--- /dev/null+++ b/test/codebuddy-files.test.js@@ -0,0 +1,97 @@+'use strict';+const test=require('node:test'),assert=require('node:assert/strict');+const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),crypto=require('node:crypto');+const sync=require('../scripts/session-sync');+const {createCodeBuddyFiles}=require('../scripts/codebuddy-files');+function fixture(t) {+ const root=fs.mkdtempSync(path.join(os.tmpdir(),'codedaddy-files-'));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));+ const files=createCodeBuddyFiles({root,sync}),cwd='/fixture';+ files.register({id:'source',user_id:'user-a',cwd,title:'Fixture'});+ files.register({id:'target',user_id:'user-b',cwd,title:'Fixture'});+ const base=path.join(root,'user-a','CodeBuddyIDE','user-a','history',crypto.createHash('md5').update(path.normalize(cwd)).digest('hex'));+ fs.mkdirSync(path.join(base,'source','messages'),{recursive:true});+ fs.writeFileSync(path.join(base,'index.json'),JSON.stringify({conversations:[{id:'source',type:'craft',name:'Fixture',createdAt:'2026-01-01',lastMessageAt:'2026-01-01'}],current:'source'}));+ fs.writeFileSync(path.join(base,'source','index.json'),JSON.stringify({messages:[{id:'message',role:'user'}],requests:[]}));+ fs.writeFileSync(path.join(base,'source','messages','message.json'),JSON.stringify({id:'message',role:'user',message:'fixture',extra:{conversationId:'source'}}));+ return {root,files,base};+}+test('native history copy uses the shared guarded transaction and publishes a complete workspace index',async t=>{+ const {root,files}=fixture(t);+ const source=files.snapshot(null,'source',['target']),target=files.snapshot(null,'target',['source']);+ assert.equal(source.records.length,1);assert.equal(target.records,null);+ const result=await sync.applySnapshotAsync(source,target,{backupRoot:path.join(root,'backups'),commit:async verify=>{await verify();await files.publish('target','source');}});+ assert.ok(result.copiedBytes>0);+ assert.equal(sync.compareSnapshots(files.snapshot(null,'source',['target']),files.snapshot(null,'target',['source'])).kind,'equal');+ const copied=files.collect('target');assert.equal(copied.length,2);+ const message=JSON.parse(fs.readFileSync(copied.find(f=>f.path.includes('/messages/')).source));assert.equal(message.extra.conversationId,'target');assert.equal(message.message,'fixture');+ const index=JSON.parse(fs.readFileSync(path.join(path.dirname(path.dirname(copied[0].source)),'index.json')));assert.equal(index.conversations[0].id,'target');+});+test('native history copy rolls files back when metadata commit fails',async t=>{+ const {root,files}=fixture(t);+ await assert.rejects(sync.applySnapshotAsync(files.snapshot(null,'source'),files.snapshot(null,'target'),{backupRoot:path.join(root,'backups'),commit:async()=>{throw Error('fixture failure');}}),/fixture failure/);+ assert.equal(files.snapshot(null,'target').files.size,0);+});+test('native history rejects partial messages, unknown owners, traversal and symlink paths',async t=>{+ const {files,base}=fixture(t);+ assert.throws(()=>files.snapshot(null,'unknown'),/归属/);+ assert.throws(()=>files.register({id:'x',user_id:'../escape',cwd:'/fixture'}),/无效/);+ fs.unlinkSync(path.join(base,'source','messages','message.json'));+ assert.throws(()=>files.snapshot(null,'source'),/缺少消息/);+ await assert.rejects(files.restore({record:{id:'source'},files:[{path:'workspace/sessions/source/../../escape',data:'eA=='}]},'target',false),/路径/);+});++test('ownership migration moves all native paths and rolls back on a failed native commit',async t=>{+ const {files}=fixture(t);+ const before={conversationId:'source',userId:'user-a',cwd:'/fixture'},after={...before,userId:'user-b'};+ const original=files.collect('source').map(f=>f.source);+ await assert.rejects(files.commit([{id:'source',before,after}],async()=>{throw Error('denied');}),/denied/);+ assert.deepEqual(files.collect('source').map(f=>f.source),original);+ await files.commit([{id:'source',before,after}],async()=>({changed:1}));+ assert.ok(files.collect('source').every(f=>f.source.includes(path.join('user-b','CodeBuddyIDE','user-b'))));+});++test('encrypted-transfer file mapping restores messages under a new owner and session identity',async t=>{+ const {files}=fixture(t);+ const archive={record:{id:'source'},files:files.collect('source').map(f=>({path:f.path,data:fs.readFileSync(f.source).toString('base64')}))};+ await files.restore(archive,'target',false);+ const copy=files.collect('target');const message=JSON.parse(fs.readFileSync(copy.find(f=>f.path.includes('/messages/')).source));+ assert.equal(message.extra.conversationId,'target');assert.equal(message.message,'fixture');+});++test('native deletion rolls files and workspace index back when the service rejects a running session',async t=>{+ const {files,base}=fixture(t);+ const index=fs.readFileSync(path.join(base,'index.json'),'utf8');+ await assert.rejects(files.deleteSessions(['source'],async()=>{throw Error('busy');}),/busy/);+ assert.equal(files.snapshot(null,'source').records.length,1);+ assert.equal(fs.readFileSync(path.join(base,'index.json'),'utf8'),index);+ await files.deleteSessions(['source'],async()=>({changed:1}));+ assert.equal(files.snapshot(null,'source').files.size,0);+});++test('workspace parse failures do not disclose stored text',async t=>{+ const {files,base}=fixture(t);+ fs.writeFileSync(path.join(base,'index.json'),'{private fixture');+ await assert.rejects(files.publish('target','source'),e=>!e.message.includes('private fixture') && /索引/.test(e.message));+});++test('native file-tree attachments survive the real encrypted archive codec',async t=>{+ const {root,files,base}=fixture(t);+ const tree=path.join(path.dirname(path.dirname(base)),'file-tree',path.basename(base),'source');+ fs.mkdirSync(tree,{recursive:true});fs.writeFileSync(path.join(tree,'snapshot.bin'),Buffer.from([0,1,255]));+ const {writeSessionTransfer,readSessionTransfer}=require('../scripts/session-transfer');+ const archive=path.join(root,'export.wds');+ await writeSessionTransfer(archive,[{record:{id:'source'},files:files.collect('source')}],'fixture-password');+ const decoded=await readSessionTransfer(archive,'fixture-password',path.join(root,'decoded'));+ await files.restore(decoded.sessions[0],'target',true);+ const copied=files.collect('target').find(f=>f.path.startsWith('codebuddy-file-tree/'));+ assert.ok(copied);assert.deepEqual(fs.readFileSync(copied.source),Buffer.from([0,1,255]));+});++test('size and invalidation probes use metadata without reading conversation bodies',async t=>{+ const {files}=fixture(t);+ const read=fs.readFileSync;fs.readFileSync=()=>{throw Error('content read forbidden');};+ try {+ const sizes=await files.sync.readSessionSizes(null,['source']);assert.ok(sizes.get('source')>0);+ assert.match(await files.sync.readSessionQuickFingerprintAsync(null,'source'),/^[a-f0-9]{64}$/);+ }finally{fs.readFileSync=read;}+});diff --git a/test/codebuddy-native.test.js b/test/codebuddy-native.test.jsnew file mode 100644index 0000000..efbe1ed--- /dev/null+++ b/test/codebuddy-native.test.js@@ -0,0 +1,61 @@+'use strict';+const test=require('node:test');+const assert=require('node:assert/strict');+const {replaceNativeSession}=require('../scripts/codebuddy-native.js');+const original={account:{uid:'old'},auth:{accessToken:'fixture-old'}};+const next={account:{uid:'new'},auth:{accessToken:'fixture-new'}};+function service(){const events=[];return {events,currentSession:original,initialized:Promise.resolve(),storeSession:async function(s){events.push('store:'+s.account.uid);},_onDidChangeSession:{fire:s=>events.push('notify:'+s.account.uid)},scheduleRefresh:()=>events.push('schedule')};}+test('native switch persists, publishes and schedules without quitting or relaunching',async()=>{+ const s=service();assert.deepEqual(await replaceNativeSession.call(s,next),{uid:'new'});+ assert.deepEqual(s.events,['store:new','notify:new','schedule']);assert.equal(s.currentSession,next);+});+test('native switch rolls back a failed publish and refuses refresh races',async()=>{+ const s=service();s._onDidChangeSession.fire=x=>{if(x===next)throw Error('fail');s.events.push('notify:old');};+ await assert.rejects(replaceNativeSession.call(s,next),/原登录态/);+ assert.equal(s.currentSession,original);assert.deepEqual(s.events,['store:new','store:old','notify:old','schedule']);+ s.refreshInFlight=true;await assert.rejects(replaceNativeSession.call(s,next),/正在更新/);+});+test('invalid backups never reach native storage',async()=>{+ const s=service();await assert.rejects(replaceNativeSession.call(s,{account:{uid:'x'}}),/无效/);assert.deepEqual(s.events,[]);+});++test('a failed switch from logged-out state removes the new encrypted identity', async () => {+ const s = service(); s.currentSession = undefined;+ s.storageService = {remove:async () => s.events.push('remove')};+ s.getStorageKey = () => 'fixture';+ s._onDidChangeSession.fire = value => { if(value) throw Error('fail'); };+ await assert.rejects(replaceNativeSession.call(s,next), /已恢复/);+ assert.equal(s.currentSession, undefined);+ assert.deepEqual(s.events, ['store:new','remove','schedule']);+ assert.equal(s.refreshInFlight, false);+});+test('native switching excludes a concurrent transaction and fake logout never revokes tokens', async () => {+ const s = service(); let finish;+ s.storeSession = () => new Promise(resolve => { finish = resolve; });+ const first = replaceNativeSession.call(s, next);+ await Promise.resolve();+ await assert.rejects(replaceNativeSession.call(s, original), /正在更新/);+ finish(); await first;+ s.storageService = {remove:async () => s.events.push('remove')};+ s.getStorageKey = () => 'fixture';+ s._onDidChangeSession.fire = value => s.events.push(value ? 'login' : 'logout');+ await replaceNativeSession.call(s, null);+ assert.equal(s.currentSession, undefined);+ assert.ok(s.events.includes('remove'));+});++test('native session changes persist before notifying both renderer generations, reject stale/running sessions',async()=>{+ const {writeNativeSessions}=require('../scripts/codebuddy-native');+ const before={conversationId:'fixture',userId:'u1',updatedAt:1,deletedAt:2};+ const events=[];+ const s={_sessions:new Map([['fixture',before]]),_newSessions:new Set(),enqueueV2Write:fn=>fn(),+ _db:{updateItems:async()=>events.push('persist')},nextV2Revision:()=>3,+ broadcastV2:()=>events.push('v2'),notifyAgentManager:()=>events.push('legacy')};+ const next={...before,deletedAt:null,updatedAt:4};+ await writeNativeSessions.call(s,[{id:'fixture',before,after:next}]);+ assert.equal(s._sessions.get('fixture').deletedAt,undefined);+ assert.deepEqual(events,['persist','v2','legacy']);+ await assert.rejects(writeNativeSessions.call(s,[{id:'fixture',before,after:next}]),/已变化/);+ s._sessions.set('fixture',{...next,status:'Working'});+ await assert.rejects(writeNativeSessions.call(s,[{id:'fixture',before:s._sessions.get('fixture'),after:null}]),/正在运行/);+});diff --git a/test/codebuddy-session-store.test.js b/test/codebuddy-session-store.test.jsnew file mode 100644index 0000000..4ad0e2b--- /dev/null+++ b/test/codebuddy-session-store.test.js@@ -0,0 +1,43 @@+'use strict';+const test=require('node:test');+const assert=require('node:assert/strict');+const {createCodeBuddySessionStore}=require('../scripts/codebuddy-session-store.js');+function harness() {+ const rows=new Map([['a',{conversationId:'a',userId:'u1',cwd:'/workspace',title:'title',customTitle:'custom',createdAt:1,updatedAt:10}],['b',{conversationId:'b',userId:'u2',cwd:'/other',updatedAt:20,deletedAt:21}]]);+ const calls=[];+ const store=createCodeBuddySessionStore({readItems:async()=>Array.from(rows,([id,row])=>({key:'session:'+id,value:JSON.stringify(row)})),writeChanges:async changes=>{+ for(const c of changes) {calls.push(c);rows.set(c.id,c.after || {...rows.get(c.id),deletedAt:30});}+ return {changed:changes.length};+ }});+ return {rows,calls,store};+}+test('shared SQL filters, sorting, custom titles and tombstones remain correct',async()=>{+ const {store}=harness();+ assert.deepEqual(await store.all('SELECT id, custom_title FROM sessions WHERE user_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC',['u1']),[{id:'a',custom_title:'custom'}]);+ assert.deepEqual(await store.all('SELECT COUNT(*) AS count FROM sessions WHERE deleted_at IS NULL'),[{count:1}]);+ assert.deepEqual(await store.all('SELECT id FROM sessions WHERE updated_at > ? AND deleted_at IS NULL',[11]),[]);+});+test('copy, migrate and delete update native service instead of writing its database',async()=>{+ const {store,rows,calls}=harness();+ await store.run('INSERT INTO sessions (id,user_id,cwd,title) VALUES (?,?,?,?)',['new','u2','/workspace','copy']);+ assert.equal(rows.get('new').userId,'u2');+ assert.equal(calls[0].before,null);+ await store.run('UPDATE sessions SET user_id = ? WHERE id IN (?)',['u3','a']);+ assert.equal(rows.get('a').userId,'u3');+ await store.run('DELETE FROM sessions WHERE id IN (?)',['a']);+ assert.equal(rows.get('a').deletedAt,30);+ assert.deepEqual(await store.all('SELECT id FROM sessions WHERE deleted_at IS NULL'),[{id:'new'}]);+});+test('native write failures are reported and later requests can retry',async()=>{+ const store=createCodeBuddySessionStore({readItems:async()=>[],writeChanges:async()=>{throw Error('offline');}});+ await assert.rejects(store.run('INSERT INTO sessions (id) VALUES (?)',['new']),/offline/);+ assert.deepEqual(await store.all('SELECT * FROM sessions'),[]);+});++test('restoring a tombstone preserves exact metadata and timestamps',async()=>{+ const {store,rows}=harness();+ await store.run('UPDATE sessions SET deleted_at = NULL, updated_at = ? WHERE id = ?',[25,'b']);+ assert.equal(rows.get('b').deletedAt,undefined);+ assert.equal(rows.get('b').updatedAt,25);+ assert.deepEqual(await store.all('SELECT id FROM sessions WHERE deleted_at IS NULL ORDER BY updated_at DESC'),[{id:'b'},{id:'a'}]);+});diff --git a/test/composer-button-visibility.test.js b/test/composer-button-visibility.test.jsindex a9a19b2..ee6bfd0 100644--- a/test/composer-button-visibility.test.js+++ b/test/composer-button-visibility.test.js@@ -38,7 +38,7 @@ function harness() {querySelectorAll() { return []; },};const context = vm.createContext({- document, window: { innerWidth: 1000, innerHeight: 800 }, WBS_COMPAT: compat,+ document, window: { innerWidth: 1000, innerHeight: 800 }, WBS_COMPAT: compat, CAPS: {},stashBtn: element(), exploreBtn: element(), exploreMenu: { close() {} }, alive: true,sessState: { phrase: true, stash: true },findComposer: () => page.editor,diff --git a/test/linux-release-script.test.js b/test/linux-release-script.test.jsindex 4362c33..1a4f097 100644--- a/test/linux-release-script.test.js+++ b/test/linux-release-script.test.js@@ -33,8 +33,8 @@ test('Linux release builds a versioned, self-contained Debian package without roassert.match(source, /WorkDaddy-AI_\$\{VERSION\}_\$\{DEB_ARCH\}\.deb/);assert.match(source, /Architecture: \$DEB_ARCH/);assert.match(source, /Exec=\$install_root\/scripts\/launch-gui-linux\.sh \$profile/);- assert.match(source, /workdaddy-\$profile\.png/);- assert.match(source, /Icon=workdaddy-\$profile/);+ assert.match(source, /\$package_name\.png/);+ assert.match(source, /Icon=\$package_name/);assert.match(source, /const DAEMON_VERSION =/);assert.match(source, /\['DAEMON_BUILD_ID', `release-\$\{version\}-linux-deb`\]/);assert.doesNotMatch(source, /DEBIAN\/(?:preinst|postinst|prerm|postrm)/);@@ -60,10 +60,12 @@ test('Linux file-manager action does not invoke the macOS open command', () => {test('built Linux packages have matching metadata and isolated payloads', { skip: process.platform !== 'linux' || !process.env.WORKDADDY_LINUX_DEBS }, () => {const debs = process.env.WORKDADDY_LINUX_DEBS.split(path.delimiter).filter(Boolean);- assert.equal(debs.length, 2);+ assert.ok(debs.length > 0);const expected = new Map([- ['WorkDaddy_', { packageName: 'workdaddy', root: 'opt/workdaddy', desktop: 'workdaddy-cn.desktop', filePattern: /^WorkDaddy_\d+\.\d+\.\d+_(?:amd64|arm64)\.deb$/ }],+ ['WorkDaddy_', { packageName: 'workdaddy', root: 'opt/workdaddy', desktop: 'workdaddy.desktop', filePattern: /^WorkDaddy_\d+\.\d+\.\d+_(?:amd64|arm64)\.deb$/ }],['WorkDaddy-AI_', { packageName: 'workdaddy-ai', root: 'opt/workdaddy-ai', desktop: 'workdaddy-ai.desktop', filePattern: /^WorkDaddy-AI_\d+\.\d+\.\d+_(?:amd64|arm64)\.deb$/ }],+ ['CodeDaddy-CN_', { packageName: 'codedaddy-cn', root: 'opt/codedaddy-cn', desktop: 'codedaddy-cn.desktop', filePattern: /^CodeDaddy-CN_\d+\.\d+\.\d+_(?:amd64|arm64)\.deb$/ }],+ ['CodeDaddy_', { packageName: 'codedaddy', root: 'opt/codedaddy', desktop: 'codedaddy.desktop', filePattern: /^CodeDaddy_\d+\.\d+\.\d+_(?:amd64|arm64)\.deb$/ }],]);for (const deb of debs) {const fileName = path.basename(deb);@@ -108,7 +110,7 @@ test('cross-built Debian archives expose standard member names and control metadassert.equal(control.status, 0, String(control.stderr));const metadata = spawnSync('tar', ['-xOJf', '-', './control'], { input: control.stdout, encoding: 'utf8' });assert.equal(metadata.status, 0, metadata.stderr);- const match = path.basename(deb).match(/^(?:WorkDaddy|WorkDaddy-AI)_(\d+\.\d+\.\d+)_(amd64|arm64)\.deb$/);+ const match = path.basename(deb).match(/^(?:WorkDaddy|WorkDaddy-AI|CodeDaddy-CN|CodeDaddy)_(\d+\.\d+\.\d+)_(amd64|arm64)\.deb$/);assert.ok(match);const [, version, architecture] = match;assert.ok(metadata.stdout.split('\n').includes(`Version: ${version}`));diff --git a/test/logout-route.test.js b/test/logout-route.test.jsindex d11b29b..928f662 100644--- a/test/logout-route.test.js+++ b/test/logout-route.test.js@@ -6,7 +6,7 @@ const test = require('node:test');const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const begin = source.indexOf(" if (req.method === 'POST' && p === '/api/logout')");const end = source.indexOf(' // /api/batch-claim', begin);-const route = new Function('req', 'p', 'res', 'resolveLogoutAuth', 'quitWorkBuddy', 'relaunchWorkBuddy', 'fs', 'log', 'json', source.slice(begin, end));+const route = new Function('req', 'p', 'res', 'resolveLogoutAuth', 'quitWorkBuddy', 'relaunchWorkBuddy', 'fs', 'log', 'json', 'const codeBuddyNative = null;\n' + source.slice(begin, end));async function run(resolution, exists, quitError) {const actions = [];const result = await route({ method: 'POST' }, '/api/logout', {}, () => resolution,diff --git a/test/panel-brand-robot.test.js b/test/panel-brand-robot.test.jsindex 91e093e..412d9c7 100644--- a/test/panel-brand-robot.test.js+++ b/test/panel-brand-robot.test.js@@ -103,15 +103,37 @@ test('composer controls use live primary button tokens with no dark glass overriconst source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');const start = source.indexOf(' function applyThemeButtonColors()');const end = source.indexOf(' function positionStash()', start);- const context = { stashBtn: { style: {} }, exploreBtn: { style: {} } };+ const context = { CAPS: {}, stashBtn: { style: {} }, exploreBtn: { style: {} } };vm.runInNewContext(source.slice(start, end), context);context.applyThemeButtonColors();for (const button of [context.stashBtn, context.exploreBtn]) {assert.equal(button.style.background, 'var(--wb-button-primary-bg)');assert.equal(button.style.color, 'var(--wb-button-primary-fg)');}+ context.CAPS.nativeComposer = true;+ context.applyThemeButtonColors();+ for (const button of [context.stashBtn, context.exploreBtn]) {+ assert.equal(button.style.background, 'var(--cb-button-primary)');+ assert.equal(button.style.color, 'var(--cb-button-primary-foreground)');+ }const patches = require('../scripts/theme-patches.js');assert.ok(!patches.some(patch => patch.css.includes('.wbs-stash-inline')));assert.match(source, /value="theme"><span>主题色<\/span>/);- assert.match(source, /data-wbs-robot-style="theme"[^\n]*--wbs-robot-shell:var\(--wb-button-primary-bg\)/);+ assert.match(source, /data-wbs-robot-style="theme"[^\n]*--wbs-robot-shell:var\(--wb-button-primary-bg,/);+});++test('theme robot stays visible when CodeBuddy omits WorkBuddy color tokens', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const rule = source.split('\n').find(line => line.includes('.wbs-fab[data-wbs-robot-style="theme"]'));+ assert.ok(rule.includes('--wbs-robot-shell:var(--wb-button-primary-bg,var(--vscode-button-background,#111))'));+ assert.ok(rule.includes('--wbs-robot-eye:var(--wb-button-primary-fg,var(--vscode-button-foreground,#fff))'));+ assert.ok(rule.includes('--wbs-robot-rim:var(--wb-border-subtle,rgba(255,255,255,.55))'));+});++test('legacy quick phrase hover dimensions cannot override native CodeBuddy buttons', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const rules = source.split('\n').filter(line => line.includes('wbs-explore-inline') && line.includes('min-width:32px!important'));+ assert.equal(rules.length, 1);+ const selectors = rules[0].slice(rules[0].indexOf("'") + 1, rules[0].indexOf('{')).split(',');+ for (const selector of selectors) assert.ok(selector.includes(':not(.wbs-composer-native)'), selector);});diff --git a/test/panel-outside-dismiss.test.js b/test/panel-outside-dismiss.test.jsnew file mode 100644index 0000000..dad1fd6--- /dev/null+++ b/test/panel-outside-dismiss.test.js@@ -0,0 +1,43 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const vm = require('node:vm');+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');++function harness() {+ const handlers = new Map(), disposers = [], calls = [];+ const root = { contains: node => node === inside || node === fab };+ const inside = { nodeType: 1 }, fab = { nodeType: 1 };+ const portal = { closest: () => ({}) };+ const document = { addEventListener: (type, fn, capture) => { assert.equal(capture, true); handlers.set(type, fn); }, removeEventListener: type => handlers.delete(type) };+ const context = { root, document, state: { open: true }, registerDisposer: fn => disposers.push(fn), setOpen: open => { calls.push(open); context.state.open = open; } };+ const listenStart = source.indexOf(' function listen(target, type, handler, options)');+ vm.runInNewContext(source.slice(listenStart, source.indexOf('\n }', listenStart) + 6), context);+ const start = source.indexOf(' function closePanelOnOutsidePointerDown(event)');+ assert.ok(start >= 0, 'outside-dismiss handler is wired into the shared panel');+ vm.runInNewContext(source.slice(start, source.indexOf('\n // 供 daemon', start)), context);+ return { context, inside, fab, portal, calls, handlers, disposers, down: event => handlers.get('pointerdown')(event) };+}++test('a primary outside press closes the panel without blocking the client click', () => {+ const h = harness();+ h.down({ button: 0, target: {}, preventDefault() { assert.fail('must not eat the client click'); }, stopPropagation() { assert.fail('must not eat the client click'); } });+ assert.deepEqual(h.calls, [false]);+ h.down({ button: 0, target: {} });+ assert.deepEqual(h.calls, [false], 'closed panels do not repeat close side effects');+});++test('inside controls, robot, portaled overlays and shadow descendants keep the panel open', () => {+ const h = harness();+ for (const target of [h.inside, h.fab, h.portal]) h.down({ button: 0, target });+ h.down({ button: 0, target: {}, composedPath: () => [{}, h.inside] });+ h.down({ button: 2, target: {} });+ assert.deepEqual(h.calls, []);+});++test('reinjection removes the document listener', () => {+ const h = harness();+ h.disposers.forEach(dispose => dispose());+ assert.equal(h.handlers.size, 0);+});diff --git a/test/panel-theme-controls.test.js b/test/panel-theme-controls.test.jsindex 94b8462..731ca65 100644--- a/test/panel-theme-controls.test.js+++ b/test/panel-theme-controls.test.js@@ -7,11 +7,11 @@ const vm = require('node:vm');const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const section = (a,b) => source.slice(source.indexOf(a),source.indexOf(b,source.indexOf(a)));-test('frosted glass takeover is visible above wallpaper controls and retains the saved setting', () => {+test('theme takeover is visible above the five appearance choices and retains the saved setting', () => {const theme = section('function buildThemePane()', 'function buildEnhancePane()');const sessions = section('function buildSessionsPane()', 'function wireSessionsPane()');assert.match(theme, /id="wbs-theme-takeover"/);- assert.match(theme, /<div class="wbs-pcard-title">毛玻璃主题<\/div>/);+ assert.match(theme, /<div class="wbs-pcard-title">接管主题<\/div>/);assert.doesNotMatch(theme, /关闭后,加载和切换账号时保留 WorkBuddy 的主题/);assert.match(source, /\.wbs-theme-takeover-row>\.wbs-pcard-title\{[^}]*flex:1/);assert.ok(theme.indexOf('id="wbs-theme-takeover"') < theme.indexOf('wbs-wallpaper-card'));@@ -23,7 +23,7 @@ test('frosted glass takeover is visible above wallpaper controls and retains theassert.match(wire, /syncSessionModule\(\)/);const apply = section('function applySessionModule(', 'function syncSessionModule()');assert.match(apply, /themePane && themePane.querySelector\('#wbs-theme-takeover'\)/);- assert.doesNotMatch(theme, /id="wbs-theme-appearance-options"/);+ assert.match(theme, /id="wbs-theme-appearance-options"/);assert.match(theme, /class="wbs-pcard wbs-avatar-card"/);assert.ok(theme.indexOf('wbs-avatar-card') < theme.indexOf('wbs-fab-settings'));assert.ok(theme.indexOf('wbs-fab-settings') < theme.indexOf('id="wbs-theme-takeover"'));@@ -35,8 +35,8 @@ test('frosted glass takeover is visible above wallpaper controls and retains thetest('theme choices do not activate official data-theme scopes and robot radios reuse their visual component', () => {const pane = section('function buildThemePane()', 'function buildEnhancePane()');assert.doesNotMatch(pane, /data-theme="/);- assert.doesNotMatch(pane, /id="wbs-theme-seg"|data-wbs-theme-option=/);- assert.match(pane, /毛玻璃主题/);+ assert.match(pane, /id="wbs-theme-seg"/);+ assert.match(pane, /接管主题/);assert.match(pane, /class="wbs-theme-seg wbs-robot-seg"/);assert.match(pane, /class="wbs-theme-opt wbs-robot-option"/);assert.doesNotMatch(source, /closest\('#wbs-theme-seg \.wbs-theme-opt'\)/);@@ -44,13 +44,13 @@ test('theme choices do not activate official data-theme scopes and robot radiosassert.match(pane, /value="default"/);});-test('theme pane exposes only the frosted glass takeover switch', () => {+test('theme pane restores five radio choices and enabling takeover restores the saved theme', () => {const pane = section('function buildThemePane()', 'function buildEnhancePane()');- assert.match(pane, /<div class="wbs-pcard-title">毛玻璃主题<\/div>/);- assert.doesNotMatch(pane, /<div class="wbs-pcard-title">主题外观<\/div>/);- assert.doesNotMatch(pane, /data-wbs-theme-option=/);- assert.match(daemon, /if \(state\.themeTakeoverEnabled\) await applyThemeByCdp\('nebula'\)/);- assert.match(daemon, /let id = 'nebula';/);+ for (const id of ['default', 'dark', 'eye-care', 'cyber-purple', 'nebula']) {+ assert.ok(pane.includes('name="wbs-theme" value="' + id + '"'));+ }+ assert.match(pane, /<div class="wbs-pcard-title">接管主题<\/div>/);+ assert.match(daemon, /if \(state\.themeTakeoverEnabled\) await applyThemeByCdp\(readSavedThemeId\(\)\)/);});test('account order is centered in the panel and always shows names without numbered rows', () => {const modal = section('function openAccountOrderModal()', 'function setupCreditSummary()');@@ -98,7 +98,7 @@ test('theme takeover off hides every managed theme module and blocks custom themassert.match(visibility, /querySelectorAll\('\.wbs-theme-managed'\)/);assert.match(visibility, /node\.style\.display = visible \? '' : 'none'/);assert.match(source, /var visible = sessState\.themeTakeover/);- assert.doesNotMatch(source, /if \(!sessState\.themeTakeover\) return;\s+var id = segBtn/);+ assert.match(source, /if \(!sessState\.themeTakeover/);});@@ -132,19 +132,28 @@ test('glass panel controls keep opaque primary colors without changing composerassert.doesNotMatch(rule, /\.wbs-root|\.wbs-stash-inline|\.wbs-fab/);});-test('theme refresh preserves robot radio selection while keeping the glass wallpaper visible', async () => {- const robot = { active: true, getAttribute: () => null };- robot.classList = { toggle: (_, selected) => { robot.active = selected; } };- const group = buttons => ({ querySelectorAll: () => buttons, querySelector: () => buttons.find(b => b.active) });- let synced = null;- const root = { querySelector: () => group([robot]) };- const context = { root, api: () => Promise.resolve({current:'cyber-purple'}), syncWallpaperCardVisibility: theme => { synced = theme; } };- vm.runInNewContext(section(' function loadThemes()', ' // 页面主题由 daemon'), context);- context.loadThemes();- await new Promise(resolve => setImmediate(resolve));- assert.equal(robot.active, true, 'appearance refresh must not clear the robot highlight');- assert.equal(synced, 'nebula');- assert.equal(context.themeSelectValue(), 'nebula');+test('theme refresh restores only theme radios and ignores a response older than a user selection', async () => {+ const radios = ['default', 'dark', 'eye-care', 'cyber-purple', 'nebula'].map(value => ({ value, checked: false, closest: () => ({classList: { toggle() {} }}) }));+ const robot = { checked: true };+ let resolve, synced;+ const themePane = { querySelectorAll(selector) {+ assert.equal(selector, '#wbs-theme-seg input[name="wbs-theme"]');+ return radios;+ }};+ const context = { themePane, api: () => new Promise(r => { resolve = r; }), syncWallpaperCardVisibility: id => { synced = id; } };+ vm.runInNewContext(section(' var ALLOWED_THEMES =', ' // 页面主题由 daemon'), context);+ const loading = context.loadThemes();+ resolve({current:'cyber-purple'});+ await loading;+ assert.equal(radios.find(r=>r.checked).value, 'cyber-purple');+ assert.equal(robot.checked, true);+ assert.equal(synced, 'cyber-purple');+ const stale = context.loadThemes();+ context.themeSelectionSerial++;+ context.syncThemeSelection('dark');+ resolve({current:'nebula'});+ await stale;+ assert.equal(radios.find(r=>r.checked).value, 'dark');});test('all panel switches share themed track, thumb and keyboard focus colors', () => {@@ -173,7 +182,7 @@ for (const trigger of ['switch', 'settings refresh']) test('frosted wallpaper stconst requests = [];let resolveWallpapers;const context = {- sessState: {}, enhancePane: null, conversationUsageEnabled: false,+ CAPS: {}, currentThemeId: 'nebula', sessState: {}, enhancePane: null, conversationUsageEnabled: false,themePane: { querySelector: selector => nodes[selector] || null, querySelectorAll: () => [card] },root: { querySelector: selector => nodes[selector] || null },API: 'http://127.0.0.1:47833',@@ -227,3 +236,44 @@ test('primary actions use native button tokens in every interaction state', () =assert.match(glass, /\.wbs-account-note-popover/);assert.match(glass, /\.wbs-status-popover/);});++for (const nativeComposer of [false, true]) test('theme controls are rendered only for WorkBuddy: nativeComposer=' + nativeComposer, () => {+ const context = { CAPS: {nativeComposer}, WBS_BRAND: 'WorkDaddy', themePane: {dataset:{}}, wireThemePane() {}, applyAvatar() {} };+ vm.runInNewContext(section('function buildThemePane()', ' // 增强 pane'), context);+ context.buildThemePane();+ assert.equal((context.themePane.innerHTML.match(/name="wbs-theme"/g) || []).length, nativeComposer ? 0 : 5);+ assert.equal(context.themePane.innerHTML.includes('接管主题'), !nativeComposer);+});++test('rapid theme selections ignore stale failures and disabled takeover prevents writes', async () => {+ const requests = [], notices = [];+ const context = {+ CAPS: {}, sessState: {themeTakeover:true}, themePane:null, root:{},+ syncWallpaperCardVisibility() {}, toast: message => notices.push(message),+ api: (route, options) => new Promise((resolve,reject) => requests.push({route, options, resolve, reject})),+ };+ vm.runInNewContext(section(' var ALLOWED_THEMES =', ' // 页面主题由 daemon'), context);+ const first = context.selectTheme('eye-care');+ const second = context.selectTheme('cyber-purple');+ requests[1].resolve({ok:true}); await second;+ requests[0].reject(new Error('cancelled')); await first;+ assert.equal(context.currentThemeId, 'cyber-purple');+ assert.deepEqual(requests.map(r=>JSON.parse(r.options.body).id), ['eye-care','cyber-purple']);+ assert.equal(notices.length, 1, 'an older rejection must not roll back or show a false error');+ context.sessState.themeTakeover = false;+ await context.selectTheme('default');+ assert.equal(requests.length, 2);+});++test('wallpaper controls are exclusive to the selected frosted theme', () => {+ const wallpaper = {style:{}}, shadow = {style:{}};+ let loads=0;+ const context = {sessState:{themeTakeover:true}, loadWallpapers:()=>loads++, themePane:{querySelector: selector => selector==='#wbs-wallpaper-card'?wallpaper:shadow}};+ vm.runInNewContext(section('function syncWallpaperCardVisibility(', ' // 关闭接管后'),context);+ for(const id of ['default','dark','eye-care','cyber-purple','nebula']) {+ context.syncWallpaperCardVisibility(id);+ assert.equal(wallpaper.style.display, id==='nebula'?'':'none');+ assert.equal(shadow.style.display, wallpaper.style.display);+ }+ assert.equal(loads,1);+});diff --git a/test/panel-version.test.js b/test/panel-version.test.jsindex 534b0a8..19bc7e8 100644--- a/test/panel-version.test.js+++ b/test/panel-version.test.js@@ -21,11 +21,13 @@ test('header reads running client version instead of Chrome or Electron versionstest('header writes version subtitle as text with a safe unknown-version fallback', () => {const begin = source.indexOf("var versionLine = root.querySelector('#wbs-version-line')");const finish = source.indexOf(" listen(window, 'workdaddy:automation-toast'", begin);- const render = new Function('root', 'navigator', 'WBS_VERSION', 'wbsClientVersion', source.slice(begin, finish));+ const render = new Function('root', 'navigator', 'WBS_VERSION', 'wbsClientVersion', 'CAPS = {}', 'WBS_BRAND = "WorkDaddy"', source.slice(begin, finish));const label = { textContent: '' };const root = { querySelector: () => label };render(root, { userAgent: 'WorkBuddy/5.5.3' }, '1.2.0', clientVersion);assert.equal(label.textContent, '5.5.3 (1.2.0)');render(root, { userAgent: 'Chrome/138.0.0.0' }, '1.2.0', clientVersion);assert.equal(label.textContent, '(1.2.0)');+ render(root,{userAgent:'CodeBuddy/4.12.1'},'1.2.192',clientVersion,{apiTransport:'cdp'},'CodeDaddy CN');+ assert.equal(label.textContent,'(v1.2.192 for CodeDaddy CN)');});diff --git a/test/profiles.test.js b/test/profiles.test.jsindex 5f2d434..bccf4f6 100644--- a/test/profiles.test.js+++ b/test/profiles.test.js@@ -3,24 +3,38 @@const test = require('node:test');const assert = require('node:assert/strict');const path = require('node:path');-const { PROFILES, getProfile, profileDataDir } = require('../scripts/profiles.js');+const { PROFILES, getProfile, profileDataDir, listInstalledModelSources } = require('../scripts/profiles.js');++test('模型导入始终列出其他三个客户端,未安装的来源保留为不可用选项', (t) => {+ t.mock.method(require('node:fs'), 'existsSync', () => false);+ for (const id of Object.keys(PROFILES)) {+ const sources = listInstalledModelSources(id);+ assert.deepEqual(sources.map(source => source.profileId).sort(), Object.keys(PROFILES).filter(other => other !== id).sort());+ assert.ok(sources.every(source => !source.available && !source.installed));+ }+});test('四个客户端 profile 使用独立数据源和能力开关', () => {assert.deepEqual(Object.keys(PROFILES).sort(), ['codebuddy-cn', 'codebuddy-intl', 'workbuddy-ai', 'workbuddy-cn']);assert.equal(getProfile('workbuddy-ai').sessionDb.endsWith(path.join('.workbuddy-ai', 'workbuddy.db')), true);assert.equal(getProfile('codebuddy-cn').sessionDb.endsWith(path.join('CodeBuddy CN', 'codebuddy-sessions.vscdb')), true);assert.equal(getProfile('codebuddy-intl').sessionDb.endsWith(path.join('CodeBuddy', 'codebuddy-sessions.vscdb')), true);+ assert.equal(getProfile('codebuddy-cn').modelsFile.endsWith(path.join('.codebuddy', 'models.json')), true);+ assert.equal(getProfile('codebuddy-intl').modelsFile.endsWith(path.join('.codebuddy', 'models.json')), true);assert.equal(getProfile('workbuddy-cn').capabilities.theme, true);assert.equal(getProfile('workbuddy-ai').capabilities.theme, true);assert.equal(getProfile('codebuddy-cn').capabilities.stashPrompt, false);- assert.equal(getProfile('codebuddy-cn').authFile, null);+ assert.match(getProfile('codebuddy-cn').authFile, /native-current\.info$/);+ assert.equal(getProfile('codebuddy-cn').capabilities.accounts, true);+ assert.equal(getProfile('codebuddy-cn').capabilities.models, true);+ assert.equal(getProfile('codebuddy-cn').capabilities.enhance, false);});test('WorkBuddy AI enables the theme capability alongside domestic WorkBuddy', () => {assert.equal(PROFILES['workbuddy-cn'].capabilities.theme, true);assert.equal(PROFILES['workbuddy-ai'].capabilities.theme, true);- assert.equal(PROFILES['codebuddy-cn'].capabilities.theme, false);- assert.equal(PROFILES['codebuddy-intl'].capabilities.theme, false);+ assert.equal(PROFILES['codebuddy-cn'].capabilities.theme, true);+ assert.equal(PROFILES['codebuddy-intl'].capabilities.theme, true);});test('各 profile 的 API host 与 auth.domain 一致(签到/积分/无感登录)', () => {diff --git a/test/quick-phrase-composer.test.js b/test/quick-phrase-composer.test.jsindex 4e2ddd2..2607d4e 100644--- a/test/quick-phrase-composer.test.js+++ b/test/quick-phrase-composer.test.js@@ -193,7 +193,7 @@ function delayedButtonHarness({ enableAfter = 3, cancelAfter = Infinity, disableprobes++; probeTimes.push(clock); clock += probeCost;const foreign = { ...button, disabled: false, hasAttribute: () => false, getAttribute: () => null };const dom = {- document: { activeElement: scoped ? { closest: () => box } : null, querySelector: () => button, querySelectorAll: selector => selector === '.cr-input-box' ? [] : scoped ? [foreign] : [button] },+ document: { activeElement: scoped ? { closest: () => box } : null, querySelector: selector => selector === '#codebuddy-agents-container' ? null : button, querySelectorAll: selector => selector === '.cr-input-box' ? [] : scoped ? [foreign] : [button] },getComputedStyle: () => ({ display: 'block', visibility: 'visible', borderRadius: '50%' }),};return { result: { value: vm.runInNewContext(params.expression, dom) } };@@ -256,3 +256,55 @@ test('the five-second deadline includes slow CDP probes and rejects a late readyassert.equal(h.calls.filter(m => m === 'Input.insertText').length, 1);assert.ok(h.probeTimes.every(at => at < 5000));});++test('native CodeBuddy send expression uses the square official button and fails closed if absent', () => {+ const exprStart = source.indexOf(' const sendExpr = `', start) + ' const sendExpr = `'.length;+ const exprEnd = source.indexOf('`;', exprStart);+ const expression = vm.runInNewContext('`' + source.slice(exprStart,exprEnd) + '`');+ const compat = require('../scripts/workbuddy-compat');+ const native = {className:'_icon_fixture _active_fixture',closest:()=>null,+ __reactProps$x:{onClick:function(){ editor.prepareBeforeSubmit?.();editor.flushPendingContentChange(); }},+ getAttribute:()=>null,getBoundingClientRect:()=>({x:400,y:100,width:24,height:24,bottom:124}),scrollIntoView(){}};+ const plugin={className:'wbs-explore-inline',closest:()=>({})};+ const box={querySelectorAll:()=>[plugin,native]};+ const dom={window:{__wbsWorkBuddyCompat:compat},document:{activeElement:{closest:()=>box},querySelector:()=>({})},getComputedStyle:()=>({display:'flex',visibility:'visible',pointerEvents:'auto'})};+ let result=vm.runInNewContext(expression,dom);+ assert.equal(result.ok,true);assert.equal(result.x,412);assert.equal(result.selector,'codebuddy-official-send-button');+ native.className='_icon_fixture _disabled_fixture';+ assert.equal(vm.runInNewContext(expression,dom).ok,false);+ box.querySelectorAll=()=>[plugin];+ result=vm.runInNewContext(expression,dom);assert.equal(result.ok,false);assert.equal(result.retryable,true);+});++test('CodeBuddy submits the native control once without compositor-dependent mouse ACKs', async () => {+ for (const disabled of [false, true]) {+ let evaluations = 0, submits = 0, mouseClicks = 0;+ const button = { disabled, className: '_icon_fixture', getAttribute: () => null,+ getBoundingClientRect: () => ({ width: 24, height: 24 }), click: () => submits++ };+ const dom = { document: {}, window: { __wbsWorkBuddyCompat: { findCodeBuddySendButton: () => button } },+ getComputedStyle: () => ({ display: 'flex', visibility: 'visible', pointerEvents: 'auto' }) };+ const context = { cdp: { connected: true }, log() {}, waitAiIdle: async () => true, setTimeout: fn => fn(),+ cdpSend: async (method, params) => {+ if (method !== 'Runtime.evaluate') return {};+ evaluations++;+ if (params.expression.includes('codebuddy-submit-once')) return { result: { value: vm.runInNewContext(params.expression, dom) } };+ return { result: { value: evaluations <= 2 ? { ok: true, hasContent: false } :+ params.expression.includes('composer-after-submit') ? { ok: true, hasContent: false } :+ { ok: true, x: 1180, y: 778, selector: 'codebuddy-official-send-button' } } };+ },+ cdpMouseClick: async () => mouseClicks++,+ };+ vm.runInNewContext(source.slice(start, end), context);+ const sending = context.sendStashToComposer({ content: { text: 'fixture', items: [] } });+ if (disabled) await assert.rejects(sending, /发送按钮/);+ else assert.equal((await sending).sent, true);+ assert.equal(submits, disabled ? 0 : 1);+ assert.equal(mouseClicks, 0);+ }+});++test('CodeBuddy quick phrase insertion has a non-blocking official adapter fallback', () => {+ assert.match(source, /requestInsertContentBlocks\(\{contentBlocks:\[\],clearFirst:true\}\)/);+ assert.match(source, /requestInsertContentBlocks\(\{contentBlocks:\[\{type:'text',text:/);+ assert.match(source, /fire-and-forget/);+});diff --git a/test/quick-phrase-popover.test.js b/test/quick-phrase-popover.test.jsindex bf311d3..0ebf4b7 100644--- a/test/quick-phrase-popover.test.js+++ b/test/quick-phrase-popover.test.js@@ -20,7 +20,7 @@ test('quick phrase popup escapes composer stacking, bridges hover, and cleans upconst document = Object.assign(element(), { body: element() });const button = element({ left: 320, top: 660, width: 32, height: 32 });const popup = element(); popup.parentElement = button;- const context = { document, window, setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; }, clearTimeout: id => timers.delete(id) };+ const context = { CAPS: {}, document, window, mountPersistentOverlay: node=>document.body.appendChild(node), setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; }, clearTimeout: id => timers.delete(id) };const start = source.indexOf(' function mountExplorePopover(');vm.runInNewContext(source.slice(start, source.indexOf(' function acMenuClose()', start)), context);const menu = context.mountExplorePopover(button, popup);diff --git a/test/renderer-api-bridge.test.js b/test/renderer-api-bridge.test.jsnew file mode 100644index 0000000..3579162--- /dev/null+++ b/test/renderer-api-bridge.test.js@@ -0,0 +1,106 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const http = require('node:http');+const vm = require('node:vm');+const { createRendererApiBridge, rendererBridgeSource, BINDING } = require('../scripts/renderer-api-bridge.js');++test('bridge forwards authenticated API reads/writes and binary exports to loopback only', async t => {+ const requests = [];+ const server = http.createServer((req, res) => {+ const chunks = [];+ req.on('data', c => chunks.push(c));+ req.on('end', () => {+ requests.push({url:req.url, method:req.method, token:req.headers['x-workdaddy-token'], body:Buffer.concat(chunks).toString()});+ res.writeHead(200, {'content-type':'application/octet-stream', 'x-workdaddy-count':'2'});+ res.end(Buffer.from([0,255,42]));+ });+ });+ await new Promise(r => server.listen(0, '127.0.0.1', r));+ t.after(() => server.close());+ const replies=[];+ const bridge=createRendererApiBridge({token:'secret',port:()=>server.address().port,send:async (method,params)=>replies.push(params)});+ const call = payload => bridge({name:BINDING,executionContextId:7,payload:JSON.stringify(payload)});+ await call({id:'a:1',token:'secret',path:'/api/models/backup',method:'POST',body:'{"index":0}'});+ assert.deepEqual(requests,[{url:'/api/models/backup',method:'POST',token:'secret',body:'{"index":0}'}]);+ let response;+ vm.runInNewContext(replies[0].expression,{window:{__wbsApiBridgeReply:r=>response=r}});+ assert.equal(replies[0].contextId,7);+ assert.equal(response.body,'AP8q');+ assert.equal(response.count,2);+ for (const path of ['https://example.com/api/x','//example.com/api/x','/api/../secret','/api/%2e%2e/secret','/api/x#fragment']) {+ await call({id:'a:2',token:'secret',path,method:'GET'});+ }+ await call({id:'a:3',token:'wrong',path:'/api/models',method:'GET'});+ assert.equal(requests.length,1);+});++test('renderer transport handles errors/binary and rejects outstanding work on reinjection', async () => {+ let sent;+ const timers=new Map(); let next=0;+ const win={ [BINDING]:value=>{sent=JSON.parse(value);} };+ const ctx={window:win,Map,Promise,Error,Uint8Array,Blob,atob,btoa,crypto:require('node:crypto').webcrypto,+ setTimeout:fn=>{timers.set(++next,fn);return next;},clearTimeout:id=>timers.delete(id)};+ vm.runInNewContext(rendererBridgeSource(),ctx);+ const pending=win.__wbsApiFetch('/api/models',{method:'GET'},'secret');+ win.__wbsApiBridgeReply({id:sent.id,status:403,body:Buffer.from('{"ok":false,"error":"denied"}').toString('base64')});+ const res=await pending;+ assert.equal(res.ok,false);+ assert.equal((await res.json()).error,'denied');+ const old=win.__wbsApiFetch('/api/models',{},'secret');+ const rejected=assert.rejects(old,/重新加载/);+ vm.runInNewContext(rendererBridgeSource(),ctx);+ await rejected;+ assert.equal(timers.size,0);+});++test('bridge accepts binary imports and DELETE while rejecting unexpected headers or verbs', async t => {+ const requests = [];+ const server = http.createServer((req,res) => {+ const chunks=[]; req.on('data',c=>chunks.push(c));+ req.on('end',()=>{requests.push({method:req.method,type:req.headers['content-type'],body:Buffer.concat(chunks)});res.end('{}');});+ });+ await new Promise(r=>server.listen(0,'127.0.0.1',r)); t.after(()=>server.close());+ const bridge=createRendererApiBridge({token:'fixture',port:()=>server.address().port,send:async()=>{}});+ const call=x=>bridge({name:BINDING,executionContextId:1,payload:JSON.stringify({id:'a',token:'fixture',path:'/api/sessions/import',...x})});+ await call({method:'POST',body:'AP8q',encoding:'base64',contentType:'application/octet-stream'});+ await call({method:'DELETE',path:'/api/custom-wallpapers?name=fixture'});+ await call({method:'CONNECT'}); await call({method:'POST',contentType:'x\r\nevil:yes'});+ assert.equal(requests.length,2);+ assert.deepEqual(requests[0].body,Buffer.from([0,255,42]));+ assert.equal(requests[0].type,'application/octet-stream');assert.equal(requests[1].method,'DELETE');+});++test('binary imports stream bounded chunks and reject a different renderer context',async t=>{+ let received=0;+ const server=http.createServer((req,res)=>{req.on('data',b=>received+=b.length);req.on('end',()=>res.end('{"ok":true}'));});+ await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>server.close());+ const replies=[];+ const bridge=createRendererApiBridge({token:'fixture',port:()=>server.address().port,send:async(_,p)=>vm.runInNewContext(p.expression,{window:{__wbsApiBridgeReply:r=>replies.push(r)}})});+ let serial=0;+ const call=(payload,context=1)=>bridge({name:BINDING,executionContextId:context,payload:JSON.stringify({id:'chunk:'+(++serial),token:'fixture',...payload})});+ await call({kind:'upload-start',uploadId:'upload',path:'/api/sessions/import',method:'POST',contentType:'application/octet-stream',totalBytes:6});+ assert.equal(replies.at(-1).status,204);+ await call({kind:'upload-chunk',uploadId:'upload',offset:0,body:'YWJj'},2);+ assert.ok(replies.at(-1).error);+ await call({kind:'upload-chunk',uploadId:'upload',offset:0,body:'YWJj'});+ await call({kind:'upload-chunk',uploadId:'upload',offset:3,body:'ZGVm'});+ await call({kind:'upload-end',uploadId:'upload'});+ assert.equal(received,6);assert.equal(replies.at(-1).status,200);+ assert.deepEqual(JSON.parse(Buffer.from(replies.at(-1).body,'base64')), {ok:true});+});++test('renderer Blob import never loads the whole archive and returns the real route response',async t=>{+ let received=0;+ const server=http.createServer((req,res)=>{req.on('data',c=>received+=c.length);req.on('end',()=>res.end('{"imported":1}'));});+ await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>server.close());+ const win={},ctx={window:win,Map,Promise,Error,Uint8Array,Blob,atob,btoa,crypto:require('node:crypto').webcrypto,setTimeout,clearTimeout};+ const chunks=[];+ const bridge=createRendererApiBridge({token:'fixture',port:()=>server.address().port,send:async(_,p)=>vm.runInNewContext(p.expression,ctx)});+ win[BINDING]=payload=>{const request=JSON.parse(payload);if(request.kind==='upload-chunk')chunks.push(Buffer.from(request.body,'base64').length);bridge({name:BINDING,executionContextId:1,payload});};+ vm.runInNewContext(rendererBridgeSource(),ctx);+ const blob=new Blob([new Uint8Array(600000)]);blob.arrayBuffer=()=>{throw Error('must slice');};+ const response=await win.__wbsApiFetch('/api/sessions/import',{method:'POST',headers:{'Content-Type':'application/octet-stream'},body:blob},'fixture');+ assert.equal((await response.json()).imported,1);assert.equal(received,600000);+ assert.ok(chunks.length===3 && chunks.every(size=>size<=262144));+});diff --git a/test/session-conflict-reset.test.js b/test/session-conflict-reset.test.jsindex 1a9b67a..1fbf5cd 100644--- a/test/session-conflict-reset.test.js+++ b/test/session-conflict-reset.test.js@@ -17,6 +17,7 @@ function harness(t) {lib.setAutoCopyMapping(dataDir, lineage, 'other', { targetId: 'session-other' });const jobs = [];const ctx = {+ PROFILE: { kind: 'workbuddy' },...lib, URL, HOST: '127.0.0.1', DATA_DIR: dataDir,isApiRequestAuthorized: () => true,readBody: async req => req.body,diff --git a/test/session-copy-list-refresh.test.js b/test/session-copy-list-refresh.test.jsnew file mode 100644index 0000000..78e85c3--- /dev/null+++ b/test/session-copy-list-refresh.test.js@@ -0,0 +1,74 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const vm = require('node:vm');+const crypto = require('node:crypto');+const source = fs.readFileSync(require.resolve('../scripts/daemon.js'), 'utf8');++function harness({ kind = 'workbuddy', owner = 'target', connected = true, reject = false, status = 'copied' } = {}) {+ const stored = new Set(), visible = new Set(), calls = [];+ let activeSession = 'existing-session';+ const ctx = { crypto, Date, PROFILE: { kind }, cdp: { connected },+ currentAccount: () => ({ uid: owner }),+ autoCopyJobs: new Map(), autoCopyQueue: [],+ yieldAutoCopyToRenderer: async () => {},+ buildAutoCopyPlan: async () => [{ id: 'a' }, { id: 'b' }],+ copySessionRecord: async row => {+ await Promise.resolve();+ if (status === 'copied') stored.add(row.id);+ return { status, sourceId: row.id, targetId: row.id };+ },+ cdpSend: async (method, params) => {+ calls.push(method);+ assert.equal(stored.size, 2, 'refresh must follow the whole batch, not the first worker');+ assert.equal([...ctx.autoCopyJobs.values()][0].status, 'running');+ if (reject) throw Error('renderer disconnected');+ const value = await vm.runInNewContext(params.expression, {+ window: { wb: { conversations: {+ ensureList: async (space, filter) => {+ assert.equal(space, 'local');+ assert.equal(filter.view, 'active');+ for (const id of stored) visible.add(id);+ },+ setCurrentConversation() { activeSession = 'wrong'; },+ } } },+ setTimeout, clearTimeout,+ });+ return { result: { value } };+ },+ setTimeout, clearTimeout, log() {}, pruneAutoCopyJobs() {}, runAutoCopyQueue() {},+ };+ const start = source.indexOf('function startAutoCopyJob(');+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);+ return { stored, visible, calls, active: () => activeSession, run: async () => {+ const job = ctx.startAutoCopyJob('source', 'target', []);+ await ctx.autoCopyQueue[0].run();+ return job;+ } };+}++test('completed copy batches publish the new WorkBuddy list before reporting done without navigating', async () => {+ const h = harness();+ const job = await h.run();+ assert.equal(job.status, 'done');+ assert.deepEqual([...h.visible], [...h.stored], 'committed sessions must also reach the official list');+ assert.equal(h.calls.length, 1);+ assert.equal(h.active(), 'existing-session');+});++for (const options of [{ kind: 'codebuddy' }, { owner: 'other-account' }, { connected: false }, { status: 'skipped' }]) {+ test('list refresh respects profile, account, connection and unchanged-copy boundaries: ' + JSON.stringify(options), async () => {+ const h = harness(options);+ assert.equal((await h.run()).status, 'done');+ assert.equal(h.calls.length, 0);+ });+}++test('an unavailable renderer never turns a committed session copy into failure', async () => {+ const h = harness({ reject: true });+ const job = await h.run();+ assert.equal(job.status, 'done');+ assert.equal(job.copied, 2);+ assert.equal(job.failed, 0);+});diff --git a/test/session-delete-confinement.test.js b/test/session-delete-confinement.test.jsindex 4975ec3..a276d67 100644--- a/test/session-delete-confinement.test.js+++ b/test/session-delete-confinement.test.js@@ -15,7 +15,7 @@ function loadSessionDeleteHelpers(fsImpl = fs) {const end = source.indexOf('\nfunction json(', start);assert.notEqual(start, -1, 'daemon must define the session ID validation boundary');assert.notEqual(end, -1, 'session deletion helpers must remain before json()');- const context = { fs: fsImpl, path, log() {} };+ const context = { codeBuddyFiles: null, fs: fsImpl, path, log() {} };vm.runInNewContext(source.slice(start, end) +'\nthis.helpers = { isValidSessionId, matchedSessionIds, resolveManagedSessionTarget, deleteSessionFiles };',@@ -266,7 +266,7 @@ test('delete route accepts more than 100 session IDs in one request', async (t)const source = fs.readFileSync(daemonPath, 'utf8');const start = source.indexOf(" if (req.method === 'POST' && p === '/api/sessions/delete')");const end = source.indexOf(' // 恢复会话:', start);- const ctx = vm.createContext({+ const ctx = vm.createContext({codeBuddyFiles:null,...loadSessionDeleteHelpers(),normalizeSessionIdBatch,collectLineageMembersForDelete: (_dataDir, requested) => requested.map((id) => ({ id })),@@ -311,7 +311,7 @@ test('delete route removes recorded copies across accounts from both DB and fileconst source = fs.readFileSync(daemonPath, 'utf8');const start = source.indexOf(" if (req.method === 'POST' && p === '/api/sessions/delete')");const end = source.indexOf(' // 恢复会话:', start);- const ctx = vm.createContext({+ const ctx = vm.createContext({codeBuddyFiles:null,...loadSessionDeleteHelpers(),normalizeSessionIdBatch,collectLineageMembersForDelete: lib.collectLineageMembersForDelete,diff --git a/test/session-size-filter.test.js b/test/session-size-filter.test.jsindex 64d85a3..e99fb6f 100644--- a/test/session-size-filter.test.js+++ b/test/session-size-filter.test.js@@ -9,6 +9,7 @@ function harness() {const controls = {};const control = id => controls[id] ||= { innerHTML: '', textContent: '', style: {}, disabled: false, addEventListener(type, callback) { this[type] = callback; }, querySelectorAll: () => [] };const ctx = vm.createContext({+ CAPS: {},sessionsState: { list: [{ id: 'small', totalBytes: 10 * 1024 ** 2, title: 'small' }, { id: 'large', totalBytes: 100 * 1024 ** 2 + 1, title: '<unsafe>', is_playground: 1 }, { id: 'unknown', totalBytes: null }], selected: {}, wsExpanded: {}, totalBytes: 2 * 1024 ** 3, minBytes: 10 * 1024 ** 2 },sessionsPane: { querySelector: id => id === '#wbs-sess-export-progress' ? null : control(id), querySelectorAll: () => [] },sessState: { themeTakeover: true }, syncSessionModule() {},diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.jsindex 5ada616..8a363ea 100644--- a/test/session-sync-daemon.test.js+++ b/test/session-sync-daemon.test.js@@ -24,7 +24,7 @@ function harness(t) {}const syncCacheMap = new Map();const dirtyIndex = createDirtyIndex(); dirtyIndex.markBaseline('one');- const ctx = { ...lib, sessionSync, fs, path, crypto, DATA_DIR: root, PROFILE: { dataRoot: root, kind: 'workbuddy' }, createDirtyIndex,+ const ctx = { codeBuddyFiles: null, ...lib, sessionSync, fs, path, crypto, DATA_DIR: root, PROFILE: { dataRoot: root, kind: 'workbuddy' }, createDirtyIndex,sessionCopyRowRevision: row => JSON.stringify([String(row && row.id || ''), String(row && row.user_id || ''),Number(row && row.updated_at || 0), Number(row && row.last_activity_at || 0),@@ -116,7 +116,7 @@ test('stale active-session lifecycle markers are cleared after an equal payloadsourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),targetRevision: revision(targetRow),});- const ctx = {+ const ctx = { codeBuddyFiles: null,...lib, fs, path, DATA_DIR: root, PROFILE: { dataRoot: root }, sessionSync,createDirtyIndex, getSessionSyncCache: () => new Map(),setTimeout, clearTimeout,@@ -249,7 +249,7 @@ test('initialized clean mappings ignore legacy source revision drift', async t =sourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),targetRevision: revision(targetRow),});- const ctx = { ...lib, fs, path, DATA_DIR: root, createDirtyIndex,+ const ctx = { codeBuddyFiles: null, ...lib, fs, path, DATA_DIR: root, createDirtyIndex,SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],sessionCopyRowRevision: revision,sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }],@@ -276,7 +276,7 @@ test('automatic copy planning reuses a stable cross-account mapping without a wolib.setAutoCopyMapping(root, lineage, 'two', {targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(previousSource), targetRevision: revision(target),});- const ctx = { ...lib, DATA_DIR: root, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,+ const ctx = { codeBuddyFiles: null, ...lib, DATA_DIR: root, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...target }] };const start = source.indexOf('function sessionCopyContentRevision(');vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);@@ -304,7 +304,7 @@ test('automatic copy planning ignores target activation lifecycle drift', asynclib.setAutoCopyMapping(root, lineage, 'two', {targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision({ ...sourceRow, id: 'b', user_id: 'two' }),});- const ctx = { ...lib, fs, path, DATA_DIR: root, createDirtyIndex,+ const ctx = { codeBuddyFiles: null, ...lib, fs, path, DATA_DIR: root, createDirtyIndex,SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],sessionCopyRowRevision: revision,sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? sourceRow : targetRow],@@ -335,7 +335,7 @@ test('source activation-only updated_at drift clears dirty state without a snapstargetRevision: revision(targetRow),});let snapshotReads = 0;- const ctx = {+ const ctx = { codeBuddyFiles: null,...lib, fs, path, DATA_DIR: root, PROFILE: { dataRoot: root }, createDirtyIndex,setTimeout, clearTimeout, getSessionSyncCache: () => new Map(),SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],@@ -355,7 +355,7 @@ test('source activation-only updated_at drift clears dirty state without a snapstest('active sync status ignores a recent job for another target account', () => {const start = source.indexOf('function activeAutoCopyJob(');- const ctx = {+ const ctx = { codeBuddyFiles: null,Date: { now: () => 10000 },autoCopyJobs: new Map([['other', { id: 'other', targetUid: 'two', status: 'done', finishedAt: 9900, startedAt: 9000 }],@@ -375,7 +375,7 @@ test('explicitly requested open session is planned without regular auto-copy rulcustom_title: '', status: 'completed', created_at: 1, updated_at: 7, last_activity_at: 7,};const targetRow = { ...sourceRow, id: 'other-session', user_id: 'two' };- const ctx = {+ const ctx = { codeBuddyFiles: null,...lib, fs, path, DATA_DIR: root,SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],sessionCopyRowRevision: row => JSON.stringify([@@ -415,7 +415,7 @@ test('requested unchanged open session resolves its mapping without entering thesourceRevision: revision(sourceRow), targetRevision: revision(targetRow),});let targetQueries = 0;- const ctx = {+ const ctx = { codeBuddyFiles: null,...lib, fs, path, DATA_DIR: root, createDirtyIndex,SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],sessionCopyRowRevision: revision,@@ -441,7 +441,7 @@ test('stable mappings clear legacy lifecycle dirty markers before planning', asyconst targetRow = { ...sourceRow, id: 'b', user_id: 'two' };const revision = row => JSON.stringify([String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0), String(row.status || ''), String(row.title || ''), String(row.custom_title || '')]);lib.setAutoCopyMapping(root, lineage, 'two', { targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision(targetRow) });- const ctx = { ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision, sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }] };+ const ctx = { codeBuddyFiles: null, ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision, sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }] };const start = source.indexOf('function sessionCopyContentRevision(');vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0);@@ -497,7 +497,7 @@ test('manual and automatic switching bypass session activity while retaining opeconst start = source.indexOf('async function assertSessionSyncIdle(');const end = source.indexOf('let automationAccountSwitchTail', start);assert.ok(start >= 0 && end > start);- const ctx = { accountSwitchInProgress: false, cdp: { connected: true }, PROFILE: { kind: 'workbuddy' }, autoCopyWorkerRunning: false, autoCopyQueue: [], sessionCopyLocks: new Map(),+ const ctx = { codeBuddyFiles: null, accountSwitchInProgress: false, cdp: { connected: true }, PROFILE: { kind: 'workbuddy' }, autoCopyWorkerRunning: false, autoCopyQueue: [], sessionCopyLocks: new Map(),cdpSend: async () => ({ result: { value: true } }) };vm.runInNewContext(source.slice(start, end), ctx);await assert.rejects(ctx.assertSessionSyncIdle(['source', 'target']), /会话仍在运行/);@@ -520,13 +520,13 @@ test('manual and automatic switching bypass session activity while retaining ope(await ctx.assertAccountSwitchIdle())();}for (const block of [source.slice(source.indexOf('function automationSwitchAccount('), source.indexOf('function startAutomationRun(')), source.slice(source.indexOf("if (req.method === 'POST' && p === '/api/switch')"))]) {- assert.ok(/await (assertAccountSwitchIdle|acquireAutomationAccountSwitch)\(/.test(block) && block.search(/await (assertAccountSwitchIdle|acquireAutomationAccountSwitch)\(/) < block.indexOf('switchTo(DATA_DIR, uid, log)'));+ assert.ok(/await (assertAccountSwitchIdle|acquireAutomationAccountSwitch)\(/.test(block) && block.search(/await (assertAccountSwitchIdle|acquireAutomationAccountSwitch)\(/) < block.indexOf('await switchAccountForProfile(uid)'));}});test('mixed sync jobs continue after divergence and report every result', async () => {const results = ['conflict', 'copied', 'skipped', 'error'];let sizeReads = 0;- const ctx = { crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,+ const ctx = { codeBuddyFiles: null, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => results.map((_, i) => ({ id: String(i) })),copySessionRecord: async row => { const status = results[Number(row.id)]; if (status === 'error') throw Error('fixture failure'); return { status, branched: status === 'copied', copiedBytes: status === 'copied' ? 123456 : 0, totalBytes: 123456, warning: status === 'copied' ? 'large session advisory' : '' }; },sessionSync: { readSessionSizes: async () => { sizeReads++; return new Map(); } },@@ -558,7 +558,7 @@ test('mixed sync jobs continue after divergence and report every result', asynctest('active session copy retries transient file races and preserves its target id', async () => {let attempts = 0;- const ctx = {+ const ctx = { codeBuddyFiles: null,crypto,DATA_DIR: 'fixture-data',PROFILE: { dataRoot: 'fixture-root' },@@ -585,7 +585,7 @@ test('active session copy retries transient file races and preserves its targettest('active session copy keeps waiting through a longer renderer flush', async () => {let attempts = 0;- const ctx = {+ const ctx = { codeBuddyFiles: null,crypto,PROFILE: { dataRoot: 'fixture-root' },autoCopyJobs: new Map(), autoCopyQueue: [], Date,@@ -612,7 +612,7 @@ test('active session copy keeps waiting through a longer renderer flush', asynctest('unchanged requested session resolves its target without entering the copy worker', async () => {let copies = 0;- const ctx = {+ const ctx = { codeBuddyFiles: null,crypto,PROFILE: { dataRoot: 'fixture-root' },autoCopyJobs: new Map(), autoCopyQueue: [], Date,@@ -633,7 +633,7 @@ test('unchanged requested session resolves its target without entering the copytest('empty message sessions are skipped instead of shown as sync failures', async () => {let cleared = 0;- const ctx = {+ const ctx = { codeBuddyFiles: null,crypto,PROFILE: { dataRoot: 'fixture-root' },autoCopyJobs: new Map(), autoCopyQueue: [], Date,@@ -658,7 +658,7 @@ test('empty message sessions are skipped instead of shown as sync failures', asytest('an empty automatic copy plan does not wait for renderer injection', async () => {const planningYields = [];let rendererWaits = 0;- const ctx = { crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,+ const ctx = { codeBuddyFiles: null, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,yieldAutoCopyToRenderer: async options => {planningYields.push(options);if (!options || options.waitForInjection !== false) rendererWaits++;@@ -679,7 +679,7 @@ test('an empty automatic copy plan does not wait for renderer injection', asynctest('automatic session sync uses a bounded worker pool', async () => {let running = 0;let peak = 0;- const ctx = { crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,+ const ctx = { codeBuddyFiles: null, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => Array.from({ length: 8 }, (_, id) => ({ id: String(id) })),copySessionRecord: async row => {running++;@@ -701,7 +701,7 @@ test('automatic session sync uses a bounded worker pool', async () => {});test('automatic session sync aggregates copied bytes independently across workers', async () => {- const ctx = { crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,+ const ctx = { codeBuddyFiles: null, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => Array.from({ length: 8 }, (_, id) => ({ id: String(id) })),copySessionRecord: async () => {await new Promise(resolve => setTimeout(resolve, 2));@@ -870,3 +870,19 @@ test('failed branch insertion leaves no visible row or copied files and a retryassert.equal((await h.copy()).status, 'skipped');assert.equal(h.rows.size, 4);});++test('native automatic first copy registers destination ownership before selecting its snapshot', async t => {+ const h=harness(t);+ lib.removeAutoCopySessionMember(h.root,h.lineage,'two','b'); h.rows.delete('b');+ const files=require('../scripts/codebuddy-files').createCodeBuddyFiles({root:path.join(h.root,'native'),sync:sessionSync});+ const row=h.rows.get('a'); row.cwd='/fixture'; files.register(row);+ const base=path.join(h.root,'native','one','CodeBuddyIDE','one','history',crypto.createHash('md5').update('/fixture').digest('hex'),'a');+ fs.mkdirSync(path.join(base,'messages'),{recursive:true});+ fs.writeFileSync(path.join(base,'index.json'),JSON.stringify({messages:[{id:'message'}]}));+ fs.writeFileSync(path.join(base,'messages','message.json'),JSON.stringify({id:'message',conversationId:'a',role:'user',message:'fixture'}));+ h.ctx.codeBuddyFiles=files;h.ctx.sessionSync=files.sync;+ const result=await h.copy();+ assert.equal(result.status,'copied');+ assert.ok(files.collect(result.targetId).every(f=>f.source.includes(path.join('two','CodeBuddyIDE','two'))));+ assert.equal((await h.copy()).status,'skipped');+});diff --git a/test/session-transfer.test.js b/test/session-transfer.test.jsindex c437881..9f51b65 100644--- a/test/session-transfer.test.js+++ b/test/session-transfer.test.js@@ -74,7 +74,7 @@ test('real session export/import routes round-trip binary archives and retain owconst source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const stored = [], records = [{ id, user_id: 'original-owner', title: 'fixture' }];const opened = [];- const ctx = { fs, path, os, crypto, Buffer, URL, IS_WIN: false, IS_LINUX: false, runCommand: async (command, args) => { opened.push(args); return {code:0}; }, ...require('../scripts/secure-transfer'),+ const ctx = { codeBuddyFiles: null, fs, path, os, crypto, Buffer, URL, IS_WIN: false, IS_LINUX: false, runCommand: async (command, args) => { opened.push(args); return {code:0}; }, ...require('../scripts/secure-transfer'),writeSessionTransfer, readSessionTransfer, receiveSessionUpload,transferPipeline: require('node:stream/promises').pipeline,PROFILE: { dataRoot: home }, MAX_SESSION_ID_LENGTH: 200,diff --git a/test/stash-queue.test.js b/test/stash-queue.test.jsindex 09c7e02..210176b 100644--- a/test/stash-queue.test.js+++ b/test/stash-queue.test.js@@ -158,6 +158,9 @@ test('stash cleanup clears the official composer store and persistent conversaticonst end = inject.indexOf('\n // 队列操作超时包装', start);assert.match(inject.slice(start, end), /var modernDraftCleared = clearModernComposerDraft\(ed, stashSessionAtClick\)/);assert.match(inject.slice(start, end), /if \(modernDraftCleared\) return/);+ assert.match(inject, /CAPS\.nativeComposer && nativeRef[\s\S]*nativeRef\.clear\(\)/);+ assert.match(inject, /workdaddyStash: true/);+ assert.match(inject, /syncQueueDomIds\(sessionId, snapshot\);\s*syncQueueTags\(\)/);});test('theme tab is capability-gated and available to WorkBuddy AI', () => {@@ -217,7 +220,7 @@ test('modern queue path uses the top-level notifying adapter and clears stale adassert.match(inject, /function handleModernQueueActionClick\(event\)/);assert.match(inject, /listen\(document, 'click', handleModernQueueActionClick, true\)/);assert.match(inject, /function waitForModernQueueAdapter\(maxMs\)/);- assert.match(inject, /var pauseWait = modernAdapter\s*\?/);+ assert.match(inject, /var pauseWait = \(modernAdapter \|\| CAPS\.nativeComposer\)\s*\?/);assert.match(inject, /WBS_COMPAT\.isModernQueueAdapter\(adapter\)/);assert.match(inject, /enqueue:not-ready-no-fallback/);assert.match(inject, /function warmModernQueueAdapter\(\)/);@@ -257,3 +260,44 @@ test('modern stash pauses before enqueue and refreshes incomplete snapshots', ()assert.match(inject, /dropModernOptimisticItem\(stashSessionAtClick\)/);assert.match(inject, /queueItems\.length === 0[\s\S]*currentItems\.length > 0[\s\S]*snapshot\.runtime == null/);});++// CodeBuddy 4.12.1 enqueue calls the orchestrator immediately; a legacy DOM+// does not imply the old WorkBuddy queue semantics.+function nativeStashHarness(pauseFailure) {+ const vm = require('node:vm');+ const src = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const start = src.indexOf('function enqueueToWorkBuddyQueue(content)');+ const end = src.indexOf('\n var stashBusy = false;', start);+ const calls = [];+ let paused = false, sent = false;+ const adapter = {+ currentActiveSessionId: 'fixture-session',+ pauseConversationMessageQueue: async () => {+ calls.push('pause');+ if (pauseFailure) throw new Error('pause unavailable');+ paused = true;+ return {runtime: {paused}};+ },+ enqueueConversationMessageQueueItem: async () => {+ calls.push('enqueue'); sent = !paused;+ return {items:[{id:'fixture-item',status:'pending'}],runtime:{paused}};+ },+ };+ const context = {+ CAPS: {nativeComposer:true}, window:{__wbsAdapter:adapter}, document:{},+ WBS_COMPAT: {isModernQueueAdapter:()=>false,hasModernQueueSurface:()=>false},+ contentToBlocks, withQueueTimeout:p=>p, crumb:()=>{},+ getModernQueueSnapshot:async(a,s,q)=>q, recordStashQueueItem:()=>{}, guardStashedPause:()=>{},+ };+ vm.runInNewContext(src.slice(start,end),context);+ return {calls, sent:()=>sent, run:()=>context.enqueueToWorkBuddyQueue({text:'fixture',items:[]})};+}+test('CodeBuddy legacy-shaped renderer pauses before its auto-dispatching enqueue', async () => {+ const h=nativeStashHarness(false); await h.run();+ assert.deepEqual(h.calls,['pause','enqueue']); assert.equal(h.sent(),false);+});+test('CodeBuddy pause failure never falls through to enqueue', async () => {+ const h=nativeStashHarness(true);+ await assert.rejects(h.run(),/pause unavailable/);+ assert.deepEqual(h.calls,['pause']); assert.equal(h.sent(),false);+});diff --git a/test/theme-blur.test.js b/test/theme-blur.test.jsindex d8072ef..66e1abf 100644--- a/test/theme-blur.test.js+++ b/test/theme-blur.test.js@@ -29,7 +29,7 @@ test('theme pane keeps avatar controls visible and gates wallpaper controls to fassert.match(inject, /<div class="wbs-pcard wbs-wallpaper-card wbs-theme-managed" id="wbs-wallpaper-card" style="display:none">/);assert.match(inject, /function syncWallpaperCardVisibility\(themeId\)/);assert.match(inject, /var visible = sessState\.themeTakeover/);- assert.match(inject, /syncWallpaperCardVisibility\('nebula'\)/);+ assert.match(inject, /syncWallpaperCardVisibility\(currentThemeId\)/);});test('wallpaper loading leaves the loading state on daemon timeout and can retry', () => {@@ -40,8 +40,8 @@ test('wallpaper loading leaves the loading state on daemon timeout and can retryassert.match(load, /壁纸加载失败(daemon 不可达)/);});-test('theme pane uses the requested blur labels and frosted glass switch', () => {- assert.match(inject, /<div class="wbs-pcard-title">毛玻璃主题<\/div>/);+test('theme pane uses the requested blur labels and theme takeover switch', () => {+ assert.match(inject, /<div class="wbs-pcard-title">接管主题<\/div>/);assert.doesNotMatch(inject, /data-wbs-theme-option=/);assert.match(inject, /'毛玻璃': 'Frosted glass'/);assert.doesNotMatch(inject, /背景毛玻璃<span class="wbs-blur-hint">0% 不调节背景图<\/span>/);diff --git a/test/theme-restore-stability.test.js b/test/theme-restore-stability.test.jsindex 57f32ce..00f5e2e 100644--- a/test/theme-restore-stability.test.js+++ b/test/theme-restore-stability.test.js@@ -7,20 +7,24 @@ const path = require('node:path');const vm = require('node:vm');const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');-test('theme takeover always restores the frosted theme after navigation', async () => {- const start = source.indexOf('async function restoreSavedTheme()');- const end = source.indexOf('\n/**', start);- const applied = [];- const context = {- PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },- readSessionState: () => ({ themeTakeoverEnabled: true }),- DATA_DIR: '/test', path, fs: { existsSync: () => true, readFileSync: () => '{"id":"default"}' },- applyThemeByCdp: async id => applied.push(id),- };- vm.runInNewContext(source.slice(start, end), context);- await context.restoreSavedTheme();- assert.deepEqual(applied, ['nebula']);-});+for (const saved of ['default', 'dark', 'eye-care', 'cyber-purple', 'nebula', 'missing', null]) {+ test('theme takeover restores the saved choice after navigation: ' + saved, async () => {+ const start = source.indexOf('function readSavedThemeId()');+ const restore = source.indexOf('async function restoreSavedTheme()');+ const end = source.indexOf('\n/**', restore);+ const applied = [];+ const context = {+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },+ readSessionState: () => ({ themeTakeoverEnabled: true }),+ DATA_DIR: '/test', path, fs: { readFileSync: () => saved === null ? '{invalid' : JSON.stringify({id:saved}) },+ getTheme: id => ['default','dark','eye-care','cyber-purple','nebula'].includes(id),+ applyThemeByCdp: async id => applied.push(id),+ };+ vm.runInNewContext(source.slice(start, end), context);+ await context.restoreSavedTheme();+ assert.deepEqual(applied, [saved === null || saved === 'missing' ? 'default' : saved]);+ });+}async function themeExpression(id, takeover = true, accountUid = null, options = {}) {const start = source.indexOf('async function applyThemeByCdp(id, options = {})');@@ -182,7 +186,7 @@ test('theme takeover opt-out follows native appearance on reload without forcingtest('session settings default to takeover and retain opt-out when editing other switches', () => {let settings = { wbs: { session: { seeded: true, state: {}, phrases: [] } } };const context = {- readWorkbuddySettings: () => structuredClone(settings),+ PROFILE: {capabilities:{}}, readWorkbuddySettings: () => structuredClone(settings),writeWorkbuddySettings: value => { settings = value; }, log() {},};const start = source.indexOf("const SESS_NS = 'session';");diff --git a/test/token-stats-import.test.js b/test/token-stats-import.test.jsindex d8ac204..c722bd8 100644--- a/test/token-stats-import.test.js+++ b/test/token-stats-import.test.js@@ -34,7 +34,7 @@ function fixture(t) {// no running daemon, real account, model request or renderer is involved.function transferHelpers(root, sessionAccounts) {const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');- const context = { fs, path, crypto, Buffer, ...transfer, PROFILE: { dataRoot: root },+ const context = { codeBuddyFiles: null, fs, path, crypto, Buffer, ...transfer, PROFILE: { dataRoot: root },MAX_SESSION_ID_LENGTH: 200, log: () => {}, currentAccount: () => ({ uid: 'account-A' }),sqliteRun: async (sql, values) => { sessionAccounts[values[0]] = values[2]; },deleteSessionFiles: () => { throw new Error('Unexpected import rollback'); } };diff --git a/test/token-stats.test.js b/test/token-stats.test.jsindex 7fa92fb..b081e91 100644--- a/test/token-stats.test.js+++ b/test/token-stats.test.js@@ -255,3 +255,17 @@ test('seven-day totals match calendar dates and ignore diagnostic copies', t =>assert.equal(stats.totals.input, 32);assert.deepEqual(stats.daily.map(x => x.day), ['2026-09-07', '2026-09-12', '2026-09-13']);});++test('native request indexes count usage once across copies and cache no message content',t=>{+ const root=fs.mkdtempSync(path.join(os.tmpdir(),'codedaddy-stats-'));+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));+ const now=Date.now(),files=['a.json','b.json'].map(name=>path.join(root,name));+ const request={id:'request',startedAt:now-1000,messages:['private-content'],usage:{inputTokens:9,outputTokens:4,cacheTokens:2,cachedWriteTokens:1}};+ for(const file of files)fs.writeFileSync(file,JSON.stringify({requests:[request]},null,2));+ const options={now,files,readRecords:text=>JSON.parse(text).requests,sourceSession:()=> 'source',sessionAccounts:{source:'account'}};+ const result=scanTokenStatsCached(root,options);+ assert.deepEqual(result.totals,{input:9,output:4,cacheRead:2,cacheWrite:1,calls:1});+ assert.equal(result.accounts[0].account,'account');+ assert.equal(scanTokenStatsCached(root,options).totals.calls,1);+ assert.ok(!fs.readFileSync(path.join(root,'.workdaddy-token-stats-cache.json'),'utf8').includes('private-content'));+});diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 8acdf79..82b98e4 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -22,9 +22,7 @@ test('Windows updater launches the installed scripts launcher', () => {test('Windows updater prefers profile Setup.exe and keeps ZIP compatibility', () => {const daemon = read('daemon.js');const update = read('apply-update.ps1');- assert.match(daemon, /profileSetup/);- assert.match(daemon, /profileZip/);- assert.ok(daemon.indexOf('profileSetup.test') < daemon.indexOf('profileZip.test'), 'Setup.exe must win when both assets exist');+ assert.ok(daemon.indexOf("matches(a, 'Setup-") < daemon.indexOf('-win64'), 'Setup.exe must win when both assets exist');assert.match(daemon, /assetName.*\.exe/);assert.match(daemon, /packageExt/);assert.match(update, /Alias\('SrcZip'\)/);@@ -161,7 +159,7 @@ test('account switching refreshes WorkBuddy after replacing auth without restartconst routeStart = script.indexOf("if (req.method === 'POST' && p === '/api/switch')");assert.notEqual(routeStart, -1);const route = script.slice(routeStart, routeStart + 5200);- const copy = route.indexOf('switchTo(DATA_DIR, uid, log)');+ const copy = route.indexOf('await switchAccountForProfile(uid)');assert.notEqual(copy, -1);assert.match(route, /await reloadWorkBuddyPage\(\{ waitForInjection: false \}\)/);assert.doesNotMatch(route, /await quitWorkBuddy\(\)/);@@ -188,7 +186,7 @@ test('account switching carries the active conversation and opens its copied tarassert.match(inject, /currentConversationId: acSwitchConversationId\(\)/);assert.match(inject, /function acSwitchConversationId()/);assert.match(inject, /openCopiedSession/);- assert.match(compat, /function findConversationActivationApi\(doc\)/);+ assert.match(compat, /function findConversationActivationApi\(doc, options\)/);assert.match(compat, /setCurrentConversation/);assert.match(compat, /sdkNavigateKind/);assert.match(compat, /adapter\.emit\('jump-to-conversation'/);@@ -239,6 +237,7 @@ test('copied-session activation trusts the official handler even when projectionconsole: { log: (...args) => logs.push(args.join(' ')) },setBuildTimeout: setTimeout,acActiveConversationId: () => activeId,+ PROFILE_ID: 'workbuddy-cn',WBS_COMPAT: {findConversationActivationApi() {return {@@ -279,6 +278,7 @@ test('copied-session activation retries an unverified official dispatch', asyncconsole: { log: (...args) => logs.push(args.join(' ')) },setBuildTimeout: setTimeout,acActiveConversationId: () => activeId,+ PROFILE_ID: 'workbuddy-cn',WBS_COMPAT: {findConversationActivationApi() {return {@@ -339,7 +339,7 @@ test('WorkDaddy-triggered reload injects on the new main execution context beforconst switchStart = script.indexOf("if (req.method === 'POST' && p === '/api/switch')");const switchRoute = script.slice(switchStart, switchStart + 9000);- const switchWrite = switchRoute.indexOf('switchTo(DATA_DIR, uid, log)');+ const switchWrite = switchRoute.indexOf('await switchAccountForProfile(uid)');assert.notEqual(switchWrite, -1);assert.doesNotMatch(switchRoute.slice(0, switchWrite), /buildAutoCopyPlan\(/, 'session planning must not delay auth replacement and renderer reload');assert.ok(switchRoute.indexOf('await reloadWorkBuddyPage({ waitForInjection: false })') < switchRoute.indexOf('startAutoCopyJob('), 'renderer reload must precede the background auto-copy queue');@@ -543,7 +543,7 @@ test('session module read remains usable when first-run seed persistence fails',assert.match(reader, /try\s*\{[\s\S]*writeWorkbuddySettings\(s\)/);assert.match(reader, /catch \(error\)/);assert.match(reader, /session-seed-persist/);- assert.match(reader, /return sessBuild\(st, phrases\)/);+ assert.match(reader, /const result = sessBuild\(st, phrases\)/);});test('macOS updater validates a cached/downloaded DMG before mounting it', () => {@@ -566,13 +566,16 @@ test('Windows launcher scopes process discovery to the active profile and recordassert.match(launcher, /processDiagnostics/);});-test('release scripts package only WorkDaddy and WorkDaddy AI', () => {+test('release scripts package all four independently branded profiles', () => {const win = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-win-zip.sh'), 'utf8');const mac = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');const installer = read('install-win.ps1');for (const script of [win, mac]) {assert.match(script, /for profile in workbuddy-cn workbuddy-ai/);- assert.doesNotMatch(script, /codebuddy-cn|codebuddy-intl/);+ assert.match(script, /codebuddy-cn/);+ assert.match(script, /codebuddy-intl/);+ assert.match(script, /CodeDaddy-CN/);+ assert.match(script, /CodeDaddy/);}assert.match(win, /WorkDaddy AI\.lnk|PACKAGE_NAME="WorkDaddy AI"/);assert.match(win, /OUT="release\/windows\/WorkDaddy/);@@ -836,7 +839,7 @@ test('Windows Setup waits for WorkBuddy and stops only a native-verified profileassert.match(installer, /ResultCode <> 10/);assert.match(installer, /ResultCode = 11/);assert.match(installer, /runtime\\node\\\*/);- assert.match(installer, /无法安全停止 WorkDaddy 后台进程/);+ assert.match(installer, /无法安全停止 ' \+ ProductName \+ ' 后台进程/);assert.match(installer, /function ConfirmElevatedInstall/);assert.match(installer, /if IsAdmin and not ConfirmElevatedInstall/);assert.match(installer, /MB_YESNO/);@@ -849,8 +852,8 @@ test('Windows Setup waits for WorkBuddy and stops only a native-verified profileassert.match(installer, /function ShouldAutoLaunch[\s\S]*Result := not IsAdmin/);assert.match(installer, /普通安装器不会跨权限强行结束/);assert.match(installer, /按 Ctrl\+Shift\+Esc 打开任务管理器/);- assert.match(installer, /旧版 WorkDaddy 的状态文件与实际程序不一致/);- assert.match(installer, /不要手动删除 WorkDaddy 数据目录/);+ assert.match(installer, /旧版 ' \+ ProductName \+ ' 的状态文件与实际程序不一致/);+ assert.match(installer, /不要手动删除 ' \+ ProductName \+ ' 数据目录/);assert.doesNotMatch(installer, /旧版 WorkDaddy 正以管理员权限运行/);assert.doesNotMatch(installer, /prepare-win-install|windows-process-boundary|PowerShell/i);});@@ -1030,7 +1033,7 @@ test('quick-phrase layering does not reposition WorkBuddy native chat toolbar',const script = read('inject.js');assert.match(script, /\.wbs-explore-inline\.wbs-stash-inline-inline\{position:relative;z-index:99999\}/);assert.match(script, /\.wbs-explore-pop\{position:fixed;[^}]*z-index:22/);- assert.match(script, /document\.body\.appendChild\(popup\)/);+ assert.match(script, /mountPersistentOverlay\(popup\)/);assert.match(script, /html\[data-wbs-theme-id="nebula"\] \.wbs-explore-card\{[^}]*background:color-mix\(in srgb,var\(--wb-bg-popover/);assert.match(script, /html\[data-wbs-theme-id="nebula"\] \.wbs-explore-tip\{[^}]*background:color-mix\(in srgb,var\(--wb-bg-popover/);assert.doesNotMatch(script, /_chatMessageBottomToolbarWrapper_\}\{position:relative;z-index:68/);diff --git a/test/windows-launcher-boundary-repair.test.js b/test/windows-launcher-boundary-repair.test.jsindex 0508967..bbcd748 100644--- a/test/windows-launcher-boundary-repair.test.js+++ b/test/windows-launcher-boundary-repair.test.js@@ -361,7 +361,7 @@ test('Windows installer uses the bundled Simplified Chinese wizard and profile bassert.match(installerSource, /\[Languages\][\s\S]*ChineseSimplified\.isl/);assert.match(installerSource, /AppPublisher=\{#ProductName\} 团队/);assert.match(installerSource, /Description: "\{#StartDescription\}"/);- assert.match(fs.readFileSync(path.join(root, 'scripts', 'build-win-installer.ps1'), 'utf8'), /立即打开 WorkDaddy AI/);+ assert.match(fs.readFileSync(path.join(root, 'scripts', 'build-win-installer.ps1'), 'utf8'), /立即打开 '\s*\+\s*\$productName/);assert.match(chineseLanguageSource, /LanguageName=简体中文/);});diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.jsindex fc49ad5..6b489ec 100644--- a/test/windows-native-flow.test.js+++ b/test/windows-native-flow.test.js@@ -133,6 +133,55 @@ test('installer prefers the newest registered official client without replacingassert.match(native, /target\.Binary\+"\\r\\n"\+version\+"\\r\\n"\+clientType/);});+test('CodeDaddy installer page targets CodeBuddy instead of WorkBuddy', () => {+ const installer = read('scripts/win/workdaddy.iss');+ assert.match(installer, /function ExpectedClientDisplayName\(\)/);+ assert.match(installer, /if '\{#ProfileId\}' = 'codebuddy-cn' then[\s\S]*Result := 'CodeBuddy CN'/);+ assert.match(installer, /function ExpectedClientExecutableName\(\)/);+ assert.match(installer, /if '\{#ProfileId\}' = 'codebuddy-cn' then[\s\S]*Result := 'CodeBuddy CN\.exe'/);+ assert.match(installer, /else if '\{#ProfileId\}' = 'codebuddy-intl' then[\s\S]*Result := 'CodeBuddy\.exe'/);+ assert.match(installer, /ClientPage := CreateInputFilePage\([\s\S]*ExpectedClientDisplayName\(\)/);+ assert.match(installer, /ClientPage\.Add\(ExpectedClientDisplayName\(\) \+ ' 主程序:'/);+ assert.match(installer, /Programs\\CodeBuddy CN/);+ assert.match(installer, /Programs\\CodeBuddy/);+ assert.match(installer, /Dialog\.Caption := '请先退出 ' \+ ExpectedClientDisplayName\(\)/);+ assert.match(installer, /MessageLabel\.Caption := '安装前需要完全退出当前的 ' \+ ExpectedClientDisplayName\(\)/);+ assert.doesNotMatch(installer, /Dialog\.Caption := '请先退出 WorkBuddy'/);+ assert.doesNotMatch(installer, /MessageLabel\.Caption := '安装前需要完全退出当前的 WorkBuddy'/);+ assert.doesNotMatch(installer, /function ExpectedWorkBuddyName\(\)/);+});++test('the current CodeBuddy CN installer path uses exact-path checks without requiring product metadata', () => {+ const native = read('scripts/windows-native/main.go');+ const targetStart = native.indexOf('func targetForBinary(');+ const targetEnd = native.indexOf('\nfunc enumerateProcesses(', targetStart);+ const targetSource = native.slice(targetStart, targetEnd);+ assert.match(targetSource, /profile == profileCodeCN \|\| profile == profileCodeIntl/);+ assert.match(targetSource, /codeBuddyExplicitBinaryMatches\(profile, binary\)/);+ assert.doesNotMatch(targetSource, /codeBuddyBinaryMatches/);++ const explicitStart = native.indexOf('func codeBuddyExplicitBinaryMatches(');+ const explicitEnd = native.indexOf('\nfunc workBuddyImage(', explicitStart);+ const explicitSource = native.slice(explicitStart, explicitEnd);+ assert.match(explicitSource, /profile == profileCodeCN[\s\S]*"CodeBuddy CN\.exe"/);+ assert.match(explicitSource, /return codeBuddyBinaryMatches\(profile, binary\)/);++ const matchStart = native.indexOf('func matchingWorkBuddyProcessesForTarget(');+ const matchEnd = native.indexOf('\nfunc matchingWorkBuddyProcesses(', matchStart);+ const matchSource = native.slice(matchStart, matchEnd);+ assert.match(matchSource, /target\.Binary != "" \|\| codeBuddyBinaryMatches\(profile, record\.Path\)/);+});++test('CodeDaddy installer rejects a wrong executable before native process inspection', () => {+ const installer = read('scripts/win/workdaddy.iss');+ assert.match(installer, /function SelectedClientFile\(const Candidate: String\): Boolean/);+ assert.match(installer, /Pos\('codebuddy', Lowercase\('\{#ProfileId\}'\)\) = 1/);+ assert.match(installer, /function ClientExecutableNameMatches\(const Candidate: String\): Boolean/);+ assert.match(installer, /ClientExecutableNameMatches\(Candidate\)/);+ assert.match(installer, /Result := SelectedClientFile\(SelectedWorkBuddyPath\)/);+ assert.match(installer, /if ResultCode = 20 then[\s\S]*所选路径不适用于当前安装包/);+});+test('Windows update opens the verified Setup visibly and keeps daemon alive', () => {const daemon = read('scripts/daemon.js');const inject = read('scripts/inject.js');diff --git a/test/windows-privilege-boundary.test.js b/test/windows-privilege-boundary.test.jsindex de938d8..d3978ea 100644--- a/test/windows-privilege-boundary.test.js+++ b/test/windows-privilege-boundary.test.js@@ -204,7 +204,7 @@ test('Windows installer stops the verified profile lifecycle before replacing orassert.ok(stopIndex >= 0, 'installer must stop an existing verified lifecycle');assert.ok(stopIndex < copyIndex, 'lifecycle must stop before files are replaced');assert.ok(stopIndex < launchIndex, 'lifecycle must stop before the new launcher starts');- assert.match(installerSource, /\$uiPort\s*=\s*if \(\$Profile -eq 'workbuddy-ai'\) \{ 47833 \} else \{ 47832 \}/);+ assert.match(installerSource, /'workbuddy-cn'=47832; 'workbuddy-ai'=47833; 'codebuddy-cn'=47834; 'codebuddy-intl'=47835/);assert.match(installerSource, /-ExpectedWatchdogScript \(Join-Path \$AppDir 'scripts\\watchdog\.js'\)/);assert.match(installerSource, /-ExpectedDaemonScript \(Join-Path \$AppDir 'scripts\\daemon\.js'\)/);assert.match(installerSource, /\$preserveExistingLifecycle/);@@ -251,7 +251,7 @@ test('PowerShell lifecycle scopes daemon discovery to a verified watchdog parent});test('watchdog uses an OS-managed profile lock and no process scanner', () => {- assert.match(watchdogSource, /const LOCK_PORT = PROFILE\.id === 'workbuddy-ai' \? 47933 : 47932/);+ assert.match(watchdogSource, /'workbuddy-cn':47932,'workbuddy-ai':47933,'codebuddy-cn':47934,'codebuddy-intl':47935/);assert.match(watchdogSource, /const lockServer = net\.createServer\(\)/);assert.match(watchdogSource, /lockServer\.listen\(\{ host: '127\.0\.0\.1', port: LOCK_PORT, exclusive: true \}/);assert.match(watchdogSource, /error\.code === 'EADDRINUSE'/);diff --git a/test/windows-release-script.test.js b/test/windows-release-script.test.jsindex 5437104..889d6fe 100644--- a/test/windows-release-script.test.js+++ b/test/windows-release-script.test.js@@ -19,7 +19,7 @@ test('Windows release script interactively builds both profiles for one version'assert.deepEqual([...scriptBytes.subarray(0, 3)], [0xef, 0xbb, 0xbf], 'Windows PowerShell 5.1 needs a UTF-8 BOM for Chinese prompts');assert.match(source, /Read-Host\s+"[^"]*版本号/);assert.match(source, /\$Version -notmatch '\^\\d\+\\\.\\d\+\\\.\\d\+\$'/);- assert.match(source, /foreach \(\$profile in @\('workbuddy-cn', 'workbuddy-ai'\)\)/);+ assert.match(source, /foreach \(\$profile in @\('workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl'\)\)/);assert.match(source, /build-win-zip\.sh/);assert.match(source, /build-win-installer\.ps1/);assert.match(source, /-IsccPath \$Compiler \| Out-Host/);@@ -47,7 +47,7 @@ test('Windows standard relaunch falls back to the Explorer Shell object by executest('Windows watchdog uses an OS-managed profile lock and keeps restart backoff', () => {const watchdog = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'watchdog.js'), 'utf8');assert.match(watchdog, /net\.createServer\(\)/);- assert.match(watchdog, /const LOCK_PORT = PROFILE\.id === 'workbuddy-ai' \? 47933 : 47932/);+ assert.match(watchdog, /'workbuddy-cn':47932,'workbuddy-ai':47933,'codebuddy-cn':47934,'codebuddy-intl':47935/);assert.match(watchdog, /exclusive:\s*true/);assert.match(watchdog, /restartDelay = Math\.min\(restartDelay \* 2, 60000\)/);assert.doesNotMatch(watchdog, /pending\.json|updateProcessIsActive|powershell|Get-CimInstance|taskkill/i);diff --git a/test/workbuddy-compat.test.js b/test/workbuddy-compat.test.jsindex 3a6c76b..95ec9af 100644--- a/test/workbuddy-compat.test.js+++ b/test/workbuddy-compat.test.js@@ -225,3 +225,36 @@ test('injected compatibility is packaged and AI theme access is no longer profilassert.doesNotMatch(inject, /if \(!CAPS\.theme \|\| WBS_PROFILE_IS_AI\)/);assert.doesNotMatch(inject, /migrateWorkBuddyAiThemeOnce/);});++test('CodeBuddy activation uses its official guarded navigation handler with the native signature', async()=>{+ const calls=[];+ const navigate=async function(id,cwd,skip,preserve,title){+ const SessionLoadCancelledError='SessionLoadCancelledError';+ function getPendingMessageTracker(){} function getInitialMessages(){}+ calls.push([id,cwd,skip,preserve,title]);+ };+ const root=visibleElement();+ root.__reactFiber$native={memoizedState:{memoizedState:{current:navigate}},return:null};+ const doc={querySelector:s=>s==='[data-conversation-id]'?root:null};+ assert.equal(compat.findConversationActivationApi(doc),null);+ const api=compat.findConversationActivationApi(doc,{profileId:'codebuddy-cn'});+ assert.equal(api.authoritative,true);assert.equal(api.activate('native-session'),true);+ await new Promise(r=>setImmediate(r));+ assert.deepEqual(calls,[['native-session','',false,false,undefined]]);+});+++test('CodeBuddy send lookup selects official submit handler and excludes plugin buttons', () => {+ const compat = require('../scripts/workbuddy-compat');+ const plugin={className:'wbs-explore-inline',closest:()=>({})};+ const enhance={className:'_icon_hash',closest:()=>null,__reactProps$x:{onClick:()=>{}}};+ const send={className:'_icon_hash _active_hash',closest:()=>null,+ __reactProps$x:{onClick:function(){ editor.prepareBeforeSubmit?.(); editor.flushPendingContentChange(); }}};+ const box={querySelectorAll:()=>[plugin,enhance,send]};+ const doc={activeElement:{closest:()=>box},querySelectorAll:()=>[box]};+ assert.equal(compat.findCodeBuddySendButton(doc),send);+ box.querySelectorAll=()=>[plugin,enhance];+ assert.equal(compat.findCodeBuddySendButton(doc),null);+ doc.activeElement=null;doc.querySelectorAll=()=>[box,box];+ assert.equal(compat.findCodeBuddySendButton(doc),null);+});