WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
兼容 WorkBuddy AI,修复问题
[email protected]7c1021ab40a1
diff --git a/README.md b/README.mdindex 51ae135..2f17aea 100644--- a/README.md+++ b/README.md@@ -3,13 +3,14 @@> **WorkBuddy 的多账号 · 主题 · 增强工具集**> 本机回环 CDP 注入 · 不改官方安装包-一个基于 **Chrome DevTools Protocol (CDP)** 的 [WorkBuddy](https://www.workbuddy.cn/) 桌面端增强工具。+一个基于 **Chrome DevTools Protocol (CDP)** 的 [WorkBuddy](https://www.workbuddy.cn/)、[WorkBuddy AI](https://www.workbuddy.ai/) 桌面端增强工具。零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。+---## 演示@@ -42,6 +43,9 @@ v1.0.3 演示图(非最新版)## 安装+>- 国内版 [WorkBuddy](https://www.workbuddy.cn/) 请下载 `WorkDaddy` 安装包+>- 国际版 [WorkBuddy AI](https://www.workbuddy.ai/) 请下载 `WorkDaddy AI` 安装包+### macOS1. 在 [Releases](../../releases) 下载最新 `WorkDaddy-x.y.z.dmg`@@ -73,21 +77,27 @@ bash scripts/install.sh # 创建备份目录 + 启动守护进程bash scripts/relaunch-with-cdp.sh # 把 WorkBuddy 切换到调试模式(端口 9222)```+WorkBuddy 国内版和 WorkBuddy AI 使用同一套 daemon,通过 profile 绑定客户端,不靠“第一个 CDP 端口”猜测目标:++```bash+WBSWITCH_PROFILE=workbuddy-cn bash scripts/relaunch-with-cdp.sh+WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh+```++暂存提示词和主题功能在两个 WorkBuddy profile 开启。CodeBuddy profile 的适配暂缓,不进入当前发布包。++当前发布脚本只打包两个 WorkBuddy 客户端,共 4 个包:`WorkDaddy-<version>.dmg`、`WorkDaddy-AI-<version>.dmg`,以及对应的 `-win64.zip`;传 `WORKDADDY_BUILD_PROFILE=workbuddy-cn` 或 `workbuddy-ai` 可单独重打一个客户端。CodeBuddy profile 代码暂不进入发布包。+`install.sh` 做了:- 创建 `~/Library/Application Support/WorkDaddy` 备份目录- 首次启动自动兼容迁移旧版 `~/Library/Application Support/HelloBuddy/accounts` 账号备份(旧目录保留不删除)- 首次备份当前 WorkBuddy 账号-- 注册 launchd 守护进程(登录自启、崩溃拉起)+- 清理旧 launchd 注册并手动启动守护进程(不再登录自启)- 立即启动后台守护进程- 打开管理界面 `http://127.0.0.1:47832`-> 若从 WorkBuddy 应用内执行安装,launchd 注册可能失败——这属正常。-> 此时守护进程已在后台运行;如需开机自启在「终端」手动执行:->-> ```bash-> launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.workbuddy.workdaddy.plist-> ```+> 守护进程会在安装结束时手动启动;需要使用时手动启动对应的 WorkDaddy 端即可。---@@ -167,12 +177,6 @@ WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:----## 兼容性说明--- macOS 11+(Big Sur 起),Apple Silicon 与 Intel 均支持-- Windows 10/11 64 位(需 WorkBuddy Windows 版;node 使用 WorkBuddy 自带托管运行时或 PATH 中的 Node 18+)-- WorkBuddy 桌面端 0.6.6+(daemon 与 inject 同步升级后覆盖更新)-## 社区支持-[Linux](https://linux.do/)+[Linux.do](https://linux.do/)diff --git a/docs/four-client-integration-research.md b/docs/four-client-integration-research.mdnew file mode 100644index 0000000..12ba3d6--- /dev/null+++ b/docs/four-client-integration-research.md@@ -0,0 +1,143 @@+# 四客户端集成探测任务++## 目的++WorkDaddy 后续计划支持四个客户端,先由 WorkBuddy agent 做本机只读探测,确认各客户端的真实路径、运行方式、数据格式、接口和页面元素。此次任务只产出事实和证据,不修改 WorkBuddy/CodeBuddy 的安装文件、`app.asar`、登录文件或会话数据,也不实现 WorkDaddy 代码。++## 目标客户端++macOS 当前安装目标如下:++| profile | 客户端 | 当前路径 | 备注 |+| --- | --- | --- | --- |+| `workbuddy-cn` | WorkBuddy 国内版 | `/Applications/WorkBuddy.app` | 支持主题功能 |+| `workbuddy-ai` | WorkBuddy AI 国际版 | `/Applications/WorkBuddy AI.app` | 暂存提示词开放 |+| `codebuddy-cn` | CodeBuddy CN | `/Applications/CodeBuddy CN.app` | 支持 Agents/编辑器模式切换 |+| `codebuddy-intl` | CodeBuddy 国际版 | `/Applications/CodeBuddy.app` | 支持 Agents/编辑器模式切换 |++Windows 路径、进程名和安装方式不要猜测,请从正在运行的进程、快捷方式、注册表或安装目录中记录真实值。++CodeBuddy 的 Agents 模式和编辑器模式属于同一个客户端的两个运行界面,必须分别探测;不要把它们当作两个独立产品 profile。++## 探测顺序++### 1. 客户端身份与进程++对每个 profile 记录:++- 应用版本、构建号、bundle/app/exe 路径;+- 主进程和 renderer 进程名;+- 应用启动参数,特别是是否已有 `--remote-debugging-port`;+- 窗口标题、窗口数量,以及主窗口和辅助窗口如何区分;+- 当前是否能通过 CDP 连接,CDP 端口如何发现;+- `GET /json/version` 和 `GET /json/list` 的脱敏结果:`Browser`、`webSocketDebuggerUrl` 是否存在、target 的 `type/title/url`。++需要确认:四端能否同时运行、是否共用端口、是否会复用已有 Electron 进程。不能用“最近修改的登录文件”推断当前连接的客户端。++### 2. 登录信息文件++在不输出 token、cookie、密钥和完整认证内容的前提下,记录每端:++- 登录文件的绝对路径和文件名;+- 文件是否存在、权限、顶层 JSON key;+- `account`、`accounts`、`allAccounts` 的存在情况、数组/对象类型和字段名;+- `uid`、昵称、域名字段的类型和示例格式(值需要脱敏);+- 认证文件是否包含 `auth.domain`,国内版和国际版的域名分别是什么;+- 登录、刷新 token 或切换账号时文件是否会被重写,mtime 是否变化。++只展示字段名、类型、长度和脱敏后的短样例,例如 `uid: "***1234"`。禁止把整个 `.info` 文件复制到报告或日志。++### 3. 用户数据、Space 和对话++对 WorkBuddy CN、WorkBuddy AI、CodeBuddy CN、CodeBuddy 国际版分别确认:++- 用户数据根目录;+- 会话数据库/JSON/JSONL/目录的真实路径;+- 数据库类型、文件名、表名、列名和主键类型;+- Space(空间)与 conversation(对话)的关系、ID 字段和时间字段;+- 一次已有 Space 和一次已有对话是否能读到;+- 消息正文、附件、workspace、任务和文件历史分别存在哪里;+- 删除、复制或迁移一条会话需要涉及哪些关联文件。++当前已知 WorkBuddy AI 有 `~/.workbuddy-ai/models.json`,并且已经存在一个 Space 和一个对话。必须明确报告这两项是否查到,以及它们的 ID 和名称是否能与界面对应。正文和路径中的私人信息需要脱敏。++请比较四端格式,而不是只报告“能读取”。输出一张兼容性表,逐项标记 `相同`、`字段不同`、`存储不同` 或 `未确认`。++### 4. 模型配置++记录每端模型配置的路径和格式:++- `models.json` 或等价文件的绝对路径;+- 顶层结构、模型列表字段、当前模型字段;+- 模型 ID、名称、provider、endpoint、API key 字段的类型;+- 官方模型和本地模型是否使用不同结构;+- CodeBuddy 是否使用 VS Code `globalStorage`、SQLite 或其他存储。++API key 只能报告是否存在、长度和脱敏形式,禁止输出明文。++### 5. 接口与网络请求++优先通过 CDP Network 事件、应用已有请求或静态资源观察接口,不要为了探测而执行签到、切换账号、退出登录等有副作用操作。++按客户端和功能记录:++| 功能 | 需要记录 |+| --- | --- |+| OAuth/无感登录 | host、method、path、必要 header 名、请求/响应字段结构 |+| 当前账号 | host、path、响应字段和 uid 对应关系 |+| 积分查询 | host、path、分页/时间字段和响应结构 |+| 每日签到 | host、path、是否幂等、响应码;不要实际调用 |+| Space/会话 | 是否走本地数据库、CDP RPC 或 HTTP |+| 模型列表 | 本地读取还是网络请求 |++域名、路径和 header 名可以记录;所有 Authorization、cookie、refresh token、API key 和响应中的隐私字段必须删除或替换为 `<redacted>`。如果四端实际共用接口,只记录证据,不要先下结论。++### 6. 页面元素与模式++分别在 WorkBuddy 的主界面、欢迎页和 WorkBuddy AI 界面,以及 CodeBuddy 的 Agents 模式、编辑器模式中记录:++- 输入框类型:`textarea`、`contenteditable`、iframe 或其他;+- 稳定的 selector、`data-*` 属性、aria-label、role 和可见文本;+- 发送按钮、附件按钮、模型选择器、Space/会话入口;+- 页面主题标记和深色主题 selector;+- 元素是否在 shadow DOM 或 iframe 中;+- 窗口尺寸变化、输入框不存在或页面切换时的可用锚点。++机器人按钮的定位要求:++1. 能可靠找到编辑框时,展示在编辑框附近;+2. 找不到编辑框时,固定展示在当前窗口右下角;+3. 不要依赖易变的 React class 或纯文本序号;+4. 记录窄窗口和 Agents/编辑器切换后的实际 DOM 差异。++需要给出每个模式至少一个推荐锚点、一个备用锚点和失效条件。可以截图,但截图中的账号、对话正文、邮箱和路径要打码。++## WorkDaddy 功能开关初始约束++探测结果需要能支持以下能力矩阵:++| 功能 | WorkBuddy CN | WorkBuddy AI | CodeBuddy CN | CodeBuddy 国际版 |+| --- | --- | --- | --- | --- |+| 账号备份/切换 | 待确认 | 待确认 | 待确认 | 待确认 |+| Space/会话读取 | 待确认 | 待确认 | 待确认 | 待确认 |+| 暂存提示词 | 开放 | 开放 | 暂不开放 | 暂不开放 |+| 主题 | 开放 | 暂不开放 | 暂不开放 | 暂不开放 |+| 机器人按钮 | 开放 | 开放 | 开放 | 开放 |+| 积分/签到 | 待确认接口是否共用 | 待确认接口是否共用 | 待确认接口是否共用 | 待确认接口是否共用 |++这里的“开放”只表示产品目标,不代表探测已经证明可用。不能确认的项必须标为 `未确认`,并写出下一步验证方式。++## 报告交付格式++请在报告中按以下顺序输出:++1. 探测时间、系统版本、应用版本;+2. 四个 profile 的身份/路径/进程/CDP 表;+3. 登录文件格式比较表;+4. 用户数据、Space、会话和模型路径比较表;+5. API host/path/method/字段表;+6. 四端两个 CodeBuddy 模式的 DOM selector 表;+7. 能力矩阵和已知风险;+8. 仍需人工确认的事项,以及每项的置信度。++最终报告不得包含任何 token、cookie、密钥、完整认证 JSON、完整消息正文或未脱敏截图。优先给出可复现的路径、字段名、selector 和证据来源。diff --git a/scripts/Install-WorkDaddy.cmd b/scripts/Install-WorkDaddy.cmdindex 14aba5a..250c9a9 100644--- a/scripts/Install-WorkDaddy.cmd+++ b/scripts/Install-WorkDaddy.cmd@@ -1,7 +1,7 @@@echo offrem ============================================================rem WorkDaddy 一键安装(zip 解压后的顶层入口,双击运行)-rem 作用:复制到 %LOCALAPPDATA%\Programs\WorkDaddy → 注册开机自启+rem 作用:复制到 %LOCALAPPDATA%\Programs\WorkDaddy → 清理旧开机自启 → 创建桌面快捷方式rem → 创建桌面快捷方式 → 启动守护进程并以调试模式拉起 WorkBuddyrem 提示:本插件为 WorkBuddy 的增强工具,需先安装 WorkBuddy 桌面端。rem 运行所需的 Node 运行时由 WorkBuddy 自带托管(.workbuddy\binaries\node),diff --git a/scripts/apply-update.ps1 b/scripts/apply-update.ps1index d15bebe..3b24b3b 100644--- a/scripts/apply-update.ps1+++ b/scripts/apply-update.ps1@@ -3,14 +3,20 @@[CmdletBinding()]param([Parameter(Mandatory = $true)][string]$SrcZip,- [string]$AppDir = (Join-Path $env:LOCALAPPDATA 'Programs\WorkDaddy'),+ [string]$AppDir = '',[string]$Port = '47832',[string]$LogPath = '',- [string]$AttemptId = 'unknown'+ [string]$AttemptId = 'unknown',+ [string]$Profile = '__WBS_DEFAULT_PROFILE__')$ErrorActionPreference = 'Stop'-$DataDir = Join-Path $env:APPDATA 'WorkDaddy'+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 ([string]::IsNullOrWhiteSpace($AppDir)) { $AppDir = Join-Path $env:LOCALAPPDATA (Join-Path 'Programs' $productName) }+$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'+$DataDir = if ($Profile -eq 'workbuddy-ai') { Join-Path $dataRoot 'profiles\workbuddy-ai' } else { $dataRoot }$LogDir = Join-Path $DataDir 'update'New-Item -ItemType Directory -Force -Path $LogDir | Out-Nullif ([string]::IsNullOrWhiteSpace($LogPath)) { $LogPath = Join-Path $LogDir 'apply.log' }diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex 4c0858b..5aa1bb4 100644--- a/scripts/build-mac-dmg.sh+++ b/scripts/build-mac-dmg.sh@@ -17,8 +17,20 @@ cd "$DIR"VERSION="${WORKDADDY_BUILD_VERSION:-$(grep -o "DAEMON_VERSION = '[^']*'" scripts/daemon.js | head -1 | cut -d"'" -f2)}"APP="WorkDaddy.app"-OUT="release/macos/WorkDaddy-${VERSION}.dmg"+PROFILE="${WORKDADDY_BUILD_PROFILE:-}"+if [ -z "$PROFILE" ]; then+ for profile in workbuddy-cn workbuddy-ai; do+ WORKDADDY_BUILD_PROFILE="$profile" bash "$0"+ done+ exit 0+fi+case "$PROFILE" in+ workbuddy-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" ;;+esac+VERSION_CODE="$(printf '%s' "$VERSION" | tr -d '.')"+echo "==> profile: ${PROFILE}"echo "==> 版本: ${VERSION}"echo "==> 产物: ${OUT}"@@ -27,7 +39,7 @@ chmod 755 "$APP/Contents/MacOS/launcher"echo "==> launcher 可执行位已保证: $(stat -f '%Sp' "$APP/Contents/MacOS/launcher")"# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)-for f in daemon.js inject.js theme-patches.js credit-segments.js lib.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do+for f in daemon.js inject.js theme-patches.js credit-segments.js lib.js profiles.js cdp-targets.js sentry-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# 恢复这些文件的壳权限(与 1.0.3 壳内一致:sh/lib/daemon 755,inject/theme-patches 644)@@ -44,10 +56,17 @@ echo "==> 前端代码已覆盖(权限按壳原样)"# 3) 打包:staging 放 WorkDaddy.app + Applications 软链(与 1.0.3 dmg 同构)STAGE="$(mktemp -d)"-cp -R "$APP" "$STAGE/WorkDaddy.app"+PACKAGE_APP="$STAGE/${PACKAGE_APP_NAME}.app"+cp -R "$APP" "$PACKAGE_APP"+sed -i.bak "s|^PROFILE=.*|PROFILE=\"${PROFILE}\"|" "$PACKAGE_APP/Contents/MacOS/launcher"+rm -f "$PACKAGE_APP/Contents/MacOS/launcher.bak"+if [ "$PROFILE" = "workbuddy-ai" ]; then+ perl -0pi -e 's/<string>WorkDaddy<\/string>/<string>WorkDaddy AI<\/string>/g' "$PACKAGE_APP/Contents/Info.plist"+fi+perl -0pi -e "s/<string>1\\.0\\.8<\\/string>/<string>${VERSION}<\\/string>/g; s/<string>108<\\/string>/<string>${VERSION_CODE}<\\/string>/g" "$PACKAGE_APP/Contents/Info.plist"if [ -n "${WORKDADDY_BUILD_VERSION:-}" ]; thenperl -0pi -e "s/(const DAEMON_VERSION = ')[^']+(';)/\${1}${VERSION}\${2}/" \- "$STAGE/WorkDaddy.app/Contents/Resources/scripts/daemon.js"+ "$PACKAGE_APP/Contents/Resources/scripts/daemon.js"filn -s /Applications "$STAGE/Applications"cat > "$STAGE/安装失败自主解决提示词.txt" <<'EOF'@@ -109,7 +128,7 @@ WorkDaddy macOS 安装失败自助修复如果测试仍未通过,不得伪造 fixed 状态;可以改用 status=unresolved 上报,并在报告中写清楚阻塞原因。EOFrm -f "$OUT"-hdiutil create -volname "WorkDaddy" -srcfolder "$STAGE" -ov -format UDZO -imagekey zlib-level=9 "$OUT" >/dev/null+hdiutil create -volname "$PACKAGE_APP_NAME" -srcfolder "$STAGE" -ov -format UDZO -imagekey zlib-level=9 "$OUT" >/dev/nullrm -rf "$STAGE"echo "==> 完成: $(ls -lh "$OUT" | awk '{print $5}')"diff --git a/scripts/build-win-zip.sh b/scripts/build-win-zip.shindex b878497..8ba2afe 100644--- a/scripts/build-win-zip.sh+++ b/scripts/build-win-zip.sh@@ -1,15 +1,34 @@#!/usr/bin/env bash# WorkDaddy Windows 发布包打包脚本(在 macOS/Linux 上运行即可产出 Windows zip)-# 产出:release/WorkDaddy-<ver>-win64.zip(顶层含 scripts\,供 install-win.cmd / apply-update.ps1 使用)+# 产出:release/windows/WorkDaddy-<profile>-<ver>-win64.zip(只发布 WorkDaddy / WorkDaddy AI)# 可选:内置 node_modules/ws(面板 DevTools 代理依赖;无则代理功能降级,其余功能不受影响)set -euo pipefailDIR="$(cd "$(dirname "$0")/.." && pwd)"cd "$DIR"+mkdir -p release/windows++# 兼容 Windows Git Bash:原生 python3 需要 Windows 风格路径(/c/... → C:\...)+if command -v cygpath >/dev/null 2>&1; then+ winpath() { cygpath -w "$1"; }+else+ winpath() { printf '%s\n' "$1"; }+fiVERSION="$(grep -o "DAEMON_VERSION = '[^']*'" scripts/daemon.js | head -1 | cut -d"'" -f2)"-OUT="release/WorkDaddy-${VERSION}-win64.zip"+PROFILE="${WORKDADDY_BUILD_PROFILE:-}"+if [ -z "$PROFILE" ]; then+ for profile in workbuddy-cn workbuddy-ai; do+ WORKDADDY_BUILD_PROFILE="$profile" bash "$0"+ done+ exit 0+fi+case "$PROFILE" in+ workbuddy-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" ;;+esac+echo "==> profile: ${PROFILE}"echo "==> 版本: ${VERSION}"echo "==> 产物: ${OUT}"@@ -38,7 +57,10 @@ fi# 3) 打包:staging 目录,把两个顶层入口文件 + scripts/ 一起打进 zip 根(解压即见一键安装/启动)# 注意 apply-update.ps1 复用本结构(需 zip 内存在 scripts\daemon.js 做 srcRoot 判定)STAGE="$(mktemp -d)"-rm -f "$OUT"+# 清理旧的同名输出(zip 打开 w 模式会覆盖,因此 rm 仅兜底已存在的旧文件;失败不再中断打包)+if [ -f "$OUT" ]; then+ rm -f "$OUT" || true+fi# 3.1) 顶层入口(zip 根):Install-WorkDaddy.cmd / Start-WorkDaddy.cmdcp scripts/Install-WorkDaddy.cmd "$STAGE/Install-WorkDaddy.cmd"cp scripts/Start-WorkDaddy.cmd "$STAGE/Start-WorkDaddy.cmd"@@ -48,6 +70,43 @@ if [ -f "$DIR/安装失败自主解决提示词.txt" ]; thenfi# 3.2) scripts\ 本体(含 node_modules/ws、builtin)cp -R scripts "$STAGE/scripts"+# 3.2a) 打包期 profile 替换(统一用 python3,mac/win 均可用):+# 1) win-launcher.js 默认 profile+# 2) 三个 ps1 仅替换 param 默认值处的占位符([string]$Profile = '...'),+# 绝不能全局替换 __WBS_DEFAULT_PROFILE__ —— 否则判断条件+# $Profile -eq '__WBS_DEFAULT_PROFILE__' 会被替换成 $Profile -eq 'workbuddy-ai',+# 让 AI 包默认 profile 自身触发"回退到 workbuddy-cn",桌面快捷方式名/安装目录全部错乱。+PROFILE="$PROFILE" python3 - "$(winpath "$STAGE/scripts")" <<'PY'+import os+import sys++scripts = sys.argv[1]+profile = os.environ['PROFILE']++# win-launcher.js:默认 profile(仅当源码仍是 || 'workbuddy-cn' 时替换)+wl = os.path.join(scripts, 'win-launcher.js')+with open(wl, encoding='utf-8') as f:+ s = f.read()+old = "process.env.WBSWITCH_PROFILE || 'workbuddy-cn'"+new = "process.env.WBSWITCH_PROFILE || '%s'" % profile+if old in s:+ s = s.replace(old, new, 1)+with open(wl, 'w', encoding='utf-8', newline='') as f:+ f.write(s)++# 三个 ps1:只替换 param 默认值([string]$Profile = '__WBS_DEFAULT_PROFILE__')。+# 写回必须用 utf-8-sig(保留 UTF-8 BOM):源 ps1 带 BOM,Windows PowerShell/ISE 依赖+# BOM 识别 UTF-8;一旦写成无 BOM 的 UTF-8,会被按 ANSI 代码页解析中文 → 乱码语法报错。+for name in ('install-win.ps1', 'uninstall-win.ps1', 'apply-update.ps1'):+ p = os.path.join(scripts, name)+ with open(p, encoding='utf-8-sig') as f:+ s = f.read()+ pat = "[string]$Profile = '__WBS_DEFAULT_PROFILE__'"+ if pat in s:+ s = s.replace(pat, "[string]$Profile = '%s'" % profile, 1)+ with open(p, 'w', encoding='utf-8-sig', newline='') as f:+ f.write(s)+PY# 3.2a) Logo 图标:放入 scripts\(install-win.ps1 从 SrcDir 同名找并复制到安装目录根)if [ -f "$DIR/release/WorkDaddy.ico" ]; thencp "$DIR/release/WorkDaddy.ico" "$STAGE/scripts/WorkDaddy.ico"@@ -62,6 +121,64 @@ rm -rf "$STAGE/scripts/win/probe" "$STAGE/scripts/win/probe/"* 2>/dev/null || trrm -f "$STAGE/scripts/Install-WorkDaddy.cmd" "$STAGE/scripts/Start-WorkDaddy.cmd" 2>/dev/null || truefind "$STAGE" -name '*.log' -delete 2>/dev/null || truefind "$STAGE" -name '.DS_Store' -delete 2>/dev/null || true+# 3.3a) AI 包品牌化:cmd 描述/桌面图标/安装目录名跟随工包显示为 WorkDaddy AI+# (仅 workbuddy-ai;CN 包保持 WorkDaddy。文件名 Install-WorkDaddy.cmd、+# 数据目录 %APPDATA%\WorkDaddy、WorkDaddy.ico 不随包变,保持原样。)+if [ "$PROFILE" = "workbuddy-ai" ]; then+ echo "==> AI 包品牌化:cmd 描述 / 桌面图标 / 安装目录名 → WorkDaddy AI"+ python3 - "$(winpath "$STAGE")" <<'PY'+import os+import sys++stage = sys.argv[1]++def patch(path, pairs):+ p = os.path.join(stage, path)+ if not os.path.exists(p):+ return+ with open(p, 'r', encoding='utf-8') as f:+ s = f.read()+ for old, new in pairs:+ if old in s:+ s = s.replace(old, new)+ with open(p, 'w', encoding='utf-8', newline='') as f:+ f.write(s)++# zip 根两个入口 cmd+patch('Install-WorkDaddy.cmd', [+ ('WorkDaddy 一键安装', 'WorkDaddy AI 一键安装'),+ (r'%LOCALAPPDATA%\Programs\WorkDaddy', r'%LOCALAPPDATA%\Programs\WorkDaddy AI'),+ ('extracted WorkDaddy zip', 'extracted WorkDaddy AI zip'),+])+patch('Start-WorkDaddy.cmd', [+ ('WorkDaddy 一键启动', 'WorkDaddy AI 一键启动'),+ ('「WorkDaddy」图标', '「WorkDaddy AI」图标'),+ ('WorkDaddy launcher starting', 'WorkDaddy AI launcher starting'),+])+# scripts\ 内安装/启动/自检脚本(%LOCALAPPDATA%\Programs\WorkDaddy → WorkDaddy AI;数据目录不替换)+patch('scripts/install-win.cmd', [+ ('WorkDaddy Windows 安装核心', 'WorkDaddy AI Windows 安装核心'),+ # 成功提示 base64(WorkDaddy → WorkDaddy AI、WorkBuddy → WorkBuddy AI)+ ('5a6J6KOF5a6M5oiQ44CCV29ya0J1ZGR5IOWNs+WwhuS7peiwg+ivleaooeW8j+mHjeWQr++8jOivt+eojeetieeJh+WIu+OAgg==',+ '5a6J6KOF5a6M5oiQ44CCV29ya0J1ZGR5IEFJIOWNs+WwhuS7peiwg+ivleaooeW8j+mHjeWQr++8jOivt+eojeetieeJh+WIu+OAgg=='),+ ('6K+35omL5Yqo5YWz6Zet5b2T5YmN56qX5Y+j77yM5bm25YmN5b6A5qGM6Z2i5Y+z6ZSuIFdvcmtEYWRkeSDlv6vmjbfmlrnlvI/vvIzngrnlh7vku6XnrqHnkIblkZjouqvku73ov5DooYzvvIzmhJ/osKLkvb/nlKjvvZ4=',+ '6K+35omL5Yqo5YWz6Zet5b2T5YmN56qX5Y+j77yM5bm25YmN5b6A5qGM6Z2i5Y+z6ZSuIFdvcmtEYWRkeSBBSSDlv6vmjbfmlrnlvI/vvIzngrnlh7vku6XnrqHnkIblkZjouqvku73ov5DooYzvvIzmhJ/osKLkvb/nlKjvvZ4='),+])+patch('scripts/launcher.cmd', [+ ('WorkDaddy Windows 启动器', 'WorkDaddy AI Windows 启动器'),+ ('WorkDaddy launcher starting', 'WorkDaddy AI launcher starting'),+ ('Done: WorkDaddy is ready', 'Done: WorkDaddy AI is ready'),+])+patch('scripts/verify-win.cmd', [+ ('WorkDaddy Windows 安装包自检', 'WorkDaddy AI Windows 安装包自检'),+ ('WorkDaddy 安装包自检', 'WorkDaddy AI 安装包自检'),+ (r'%LOCALAPPDATA%\Programs\WorkDaddy', r'%LOCALAPPDATA%\Programs\WorkDaddy AI'),+ (r'Desktop\WorkDaddy.lnk', r'Desktop\WorkDaddy AI.lnk'),+ ('桌面已有 WorkDaddy 图标', '桌面已有 WorkDaddy AI 图标'),+])+print('==> 品牌化替换完成(Install/Start/install-win/launcher/verify-win + base64 提示)')+PY+fi# 3.3.5) 非 ASCII 文件名守护:仅允许根目录的故障排查提示词,其余路径必须保持 ASCII。# macOS 自带 Info-ZIP 会使用 UTF-8 条目写入;安装/更新脚本本身仍全部使用 ASCII 路径。NON_ASCII_PATHS="$(find "$STAGE" -not -path '*/node_modules/*' 2>/dev/null | LC_ALL=C grep '[^ -~]' || true)"@@ -69,7 +186,7 @@ UNEXPECTED_NON_ASCII="$(printf '%s\n' "$NON_ASCII_PATHS" | LC_ALL=C grep -v '安if [ -n "$UNEXPECTED_NON_ASCII" ]; thenecho "==> ERROR: 发布包包含未批准的非 ASCII 文件路径,已终止打包!"printf '%s\n' "$UNEXPECTED_NON_ASCII" | head -20- rm -rf "$STAGE"+ rm -rf "$STAGE" 2>/dev/null || trueexit 3fiecho "==> 非 ASCII 文件名守护通过(仅包含批准的故障排查提示词)"@@ -77,7 +194,7 @@ echo "==> 非 ASCII 文件名守护通过(仅包含批准的故障排查提示# macOS 自带 zip 会把中文文件名按本地代码页写入,Windows/Python 解压后会出现乱码。# 没有 Python 且需要中文提示词时直接失败,避免生成名字损坏的发布包。if command -v python3 >/dev/null 2>&1; then- python3 - "$STAGE" "$DIR/$OUT" <<'PY'+ python3 - "$(winpath "$STAGE")" "$(winpath "$DIR/$OUT")" <<'PY'import osimport sysimport zipfile@@ -98,22 +215,25 @@ with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED) as archive:PYelif [ -f "$STAGE/安装失败自主解决提示词.txt" ]; thenecho "==> ERROR: 包含中文故障排查提示词,但当前环境没有 python3,无法生成 UTF-8 ZIP。"- rm -rf "$STAGE"+ rm -rf "$STAGE" 2>/dev/null || trueexit 4elif command -v zip >/dev/null 2>&1; then(cd "$STAGE" && zip -r -q "$DIR/$OUT" .)elsetar -a -cf "$DIR/$OUT" -C "$STAGE" .fi-rm -rf "$STAGE"+# 3.5) 清理 staging(Windows Git Bash 下 rm 可能触发安全删除钩子导致非零退出;改用 find -delete 兜底)+if [ -d "$STAGE" ]; then+ find "$STAGE" -depth -delete 2>/dev/null || rm -rf "$STAGE" || true+fi-# 4) 清理临时内置到 scripts/ 的 builtin(避免污染仓库)+# 4) 清理临时内置到 scripts/ 的 builtin(避免污染仓库);rm 可能触发安全删除钩子,失败不中断if [ -d "$BUILTIN_SRC" ] && [ -d scripts/builtin ]; then- rm -rf scripts/builtin+ rm -rf scripts/builtin 2>/dev/null || truefiecho "==> 完成: $(ls -lh "$OUT" | awk '{print $5}')"echo ""-echo "在 Windows 上:解压 zip 后,在顶层直接双击 Install-WorkDaddy.cmd 一键安装(自动建桌面图标+自启);"+echo "在 Windows 上:解压 zip 后,在顶层直接双击 Install-WorkDaddy.cmd 一键安装(自动建桌面图标并清理旧自启);"echo "日常启动双击 Start-WorkDaddy.cmd 或桌面 WorkDaddy 图标。"echo "每 6 小时自动检查更新(GitHub Releases 需同时上传 .dmg 与 -win64.zip 两个资产,Windows 自动静默升级)。"diff --git a/scripts/cdp-targets.js b/scripts/cdp-targets.jsnew file mode 100644index 0000000..2a56d91--- /dev/null+++ b/scripts/cdp-targets.js@@ -0,0 +1,102 @@+'use strict';++// CDP target 归属判定(纯函数,无副作用,便于单测)。+// 背景:WorkDaddy 现在支持四个客户端(WorkBuddy CN / WorkBuddy AI / CodeBuddy CN /+// CodeBuddy 国际版),每个客户端由独立 daemon(WBSWITCH_PROFILE 绑定)驱动。旧版未绑定+// profile 的 daemon 会扫描 9222-9232 全部 CDP 端口,仅凭 Browser 标识 + 页面标题判断+// "这是 WorkBuddy",容易把兄弟客户端的页面误认成自己的注入目标:+// - 对别人的页面执行注入(把组件送错端);+// - 注入失败后反复重试,每次先清理旧组件,把对方 daemon 注入好的组件也一并销毁。+// 本模块提供严格的归属判定:优先依据应用包路径 / 登录域名(强信号),拒绝一切明确属于+// 其他客户端的页面;无强信号时才按 profile 类型走宽松兜底。++/**+ * 归一化 URL:Electron file:// URL 中空格编码为 %20(如 WorkBuddy%20AI.app),+ * 统一替换为空格便于正则匹配。+ */+function normalizeTargetUrl(url) {+ return String(url || '').replace(/%20/g, ' ');+}++const APP_CN = /\/WorkBuddy\.app(?:\/|$)/i;+const APP_AI = /\/WorkBuddy AI\.app(?:\/|$)/i;+const APP_CBCN = /\/CodeBuddy CN\.app(?:\/|$)/i;+const APP_CBINTL = /\/CodeBuddy\.app(?:\/|$)/i;+const DOMAIN_WB_AI = /https?:\/\/(?:[^/]+\.)?workbuddy\.ai(?:\/|$)/i;+const DOMAIN_WB_CN = /https?:\/\/(?:[^/]+\.)?workbuddy\.cn(?:\/|$)/i;+const DOMAIN_CB_CN = /https?:\/\/(?:[^/]+\.)?codebuddy\.cn(?:\/|$)/i;+const DOMAIN_CB_AI = /https?:\/\/(?:[^/]+\.)?codebuddy\.ai(?:\/|$)/i;++/**+ * 依据目标页 URL / 标题判定它属于哪个 client profile。+ * 只返回强信号:明确命中某个客户端的 app 包路径或登录域名。+ * 无强信号返回 null(调用方按 profile 类型走宽松兜底)。+ * @returns {string|null} profile id(workbuddy-cn / workbuddy-ai / codebuddy-cn / codebuddy-intl)+ */+function classifyTarget(url, title, description) {+ const u = normalizeTargetUrl(url);+ if (APP_AI.test(u)) return 'workbuddy-ai';+ if (APP_CN.test(u)) return 'workbuddy-cn';+ if (APP_CBCN.test(u)) return 'codebuddy-cn';+ if (APP_CBINTL.test(u)) return 'codebuddy-intl';+ if (DOMAIN_WB_AI.test(u)) return 'workbuddy-ai';+ if (DOMAIN_WB_CN.test(u)) return 'workbuddy-cn';+ if (DOMAIN_CB_CN.test(u)) return 'codebuddy-cn';+ if (DOMAIN_CB_AI.test(u)) return 'codebuddy-intl';+ return null;+}++/**+ * 目标页是否属于 WorkDaddy 支持的四客户端之一(含 CodeBuddy Editor 的 vscode-file:// 页面)。+ * 用于「清理历史误注入」时区分:同族页面上可能存在其他 profile daemon 注入的合法组件,+ * 不得当作"误注入"清理;只有明显不属于任何客户端的页面(如任意 Chromium 应用)才清理。+ */+function looksLikeWbFamilyTarget(target) {+ if (!target) return false;+ const url = String(target.url || '');+ const title = String(target.title || '');+ const desc = String(target.description || '');+ if (classifyTarget(url, title, desc)) return true;+ const haystack = `${url} ${title} ${desc}`;+ const u = normalizeTargetUrl(url);+ return (+ /\/CodeBuddy(?: CN)?\.app(?:\/|$)/i.test(u) ||+ /^vscode-/i.test(url) ||+ /codebuddy/i.test(haystack) ||+ /^WorkBuddy(?:\s|$)/i.test(title)+ );+}++/**+ * 判定一个 CDP target 是否属于当前 daemon 的 profile。+ * @param {object} target CDP /json/list 中的 page target+ * @param {object} profile profiles.js 中的 profile 对象+ */+function isTargetForProfile(target, profile) {+ if (!target || target.type !== 'page') return false;+ const url = String(target.url || '');+ const title = String(target.title || '');+ const desc = String(target.description || '');+ const haystack = `${url} ${title} ${desc}`;++ // 强信号:页面明确属于某客户端 → 必须与当前 profile 一致,否则一律拒绝+ const cls = classifyTarget(url, title, desc);+ if (cls) return cls === profile.id;++ // CodeBuddy:Editor 模式的 target URL 通常是 vscode-file://,不包含产品名;+ // profile 已由启动器绑定到独立 CDP 端口,因此选第一个普通页面即可覆盖 Agents/Editor。+ if (profile.kind === 'codebuddy') {+ if (/^(devtools|chrome|about):/i.test(url)) return false;+ if (!/codebuddy/i.test(haystack) && !/^vscode-/i.test(url)) return false;+ if (profile.id === 'codebuddy-intl' && /codebuddy\s*cn|中文/i.test(haystack)) return false;+ return true;+ }++ // WorkBuddy 家族无强信号(罕见):+ // - 已绑定 profile(WBSWITCH_PROFILE 固定了 CDP 端口):标题兜底可以接受;+ // - 未绑定(旧式 CN daemon 扫描多端口):禁止裸标题匹配,避免误连兄弟客户端。+ if (process.env.WBSWITCH_PROFILE && /^WorkBuddy(?:\s|$)/i.test(title)) return true;+ return false;+}++module.exports = { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile };\ No newline at end of filediff --git a/scripts/daemon.js b/scripts/daemon.jsindex b8fe4c9..8a1c844 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -78,10 +78,15 @@ const {editModelBackup,deleteModelBackups,enableModelBackup,+ importModels,+ checkinDisplayValue,} = require('./lib.js');const { extractCreditSegments, sortCreditSegments } = require('./credit-segments.js');const { captureException, captureMessage } = require('./sentry-report.js');+const { getProfile, profileDataDir, listInstalledModelSources } = require('./profiles.js');+const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('./cdp-targets.js');+const PROFILE = getProfile();const DATA_DIR = defaultDataDir();// 版本号:改动 daemon/inject/theme-patches/builtin 资产后递增,launcher 检测到运行中版本不一致会强制用 app 内置代码重启// 0.6.6:品牌 HelloBuddy→WorkDaddy 期间版本号未递增,旧 HelloBuddy daemon 会被 launcher 误判为"同版本"而不重启,导致旧代码继续注入;递增后强制升级@@ -129,18 +134,22 @@ const DATA_DIR = defaultDataDir();// 1.0.19:官方模型批量删除、模型卡片稳定布局与固定 650px 面板// 1.0.20:模型卡片悬浮操作、官方连通测试、完整长度脱敏 API Key// 1.0.21:模型页改为当前/备选模型列表风格,去除刷新入口并优化字段排版-const DAEMON_VERSION = '1.0.8';-const DAEMON_BUILD_ID = 'release-1.0.8-20260822';+// 1.0.9:WorkBuddy / WorkBuddy AI profile 隔离;修复 Windows launcher 的本地端口探测、+// AI 端 CDP 误连国内端、watchdog 路径和退出确认问题。+const DAEMON_VERSION = '1.0.9';+const DAEMON_BUILD_ID = 'release-1.0.9-20260823-hotfix7';const HOST = '127.0.0.1';const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app+const WORKDADDY_INSTALL_NAME = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy AI' : 'WorkDaddy';const WORKDADDY_DIR_WIN = process.env.WBSWITCH_APP_DIR ||- path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Programs', 'WorkDaddy');+ path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Programs', WORKDADDY_INSTALL_NAME);const UI_PORT_BASE = parseInt(process.env.WBSWITCH_PORT || '47832', 10);let ACTUAL_PORT = UI_PORT_BASE; // 实际监听端口(被占用时 +1)+const PROFILE_CDP_PORT = { 'workbuddy-cn': 9222, 'workbuddy-ai': 9223, 'codebuddy-cn': 9224, 'codebuddy-intl': 9225 };const CDP_PORT_HINT = process.env.WBSWITCH_CDP_PORT? parseInt(process.env.WBSWITCH_CDP_PORT, 10)- : null;+ : (PROFILE_CDP_PORT[PROFILE.id] || null);const CDP_PORT_FILE = path.join(DATA_DIR, 'cdp-port.json');const WATCH_INTERVAL = 3000; // 文件监听兜底const BACKUP_DEBOUNCE = 1500; // CDP 事件触发的备份防抖@@ -258,7 +267,7 @@ function macWorkDaddyAppPath() {if (process.env.WBSWITCH_APP_PATH) return path.resolve(process.env.WBSWITCH_APP_PATH);const bundledInfo = path.resolve(__dirname, '../../..', 'Contents', 'Info.plist');if (fs.existsSync(bundledInfo)) return path.resolve(__dirname, '../../..');- return '/Applications/WorkDaddy.app';+ return `/Applications/${WORKDADDY_INSTALL_NAME}.app`;}// 简单 semver 比较:a > b → 1,a < b → -1,相等 → 0(忽略预发布后缀)@@ -318,10 +327,15 @@ function checkUpdate(force) {// 资产按平台选取:macOS 找 .dmg;Windows 优先官方便携包(-win64.zip),再回退任意 .zip,// 绝不选 Setup.exe(IExpress 自解压包,当 .zip 下载后 Expand-Archive 会失败 → 更新中断)const assets = rel.assets || [];+ const profileAsset = PROFILE.id === 'workbuddy-ai'+ ? /WorkDaddy-AI-.*(?:-win64)?\.(?:zip|dmg)$/i+ : /WorkDaddy-(?!AI-).*?(?:-win64)?\.(?:zip|dmg)$/i;const asset = IS_WIN- ? (assets.find((a) => /-win64\.zip$/i.test(a.name || '')) ||+ ? (assets.find((a) => profileAsset.test(a.name || '') && /\.zip$/i.test(a.name || '')) ||+ assets.find((a) => /-win64\.zip$/i.test(a.name || '') && (PROFILE.id !== 'workbuddy-ai' || !/WorkDaddy-AI-/i.test(a.name || ''))) ||assets.find((a) => /\.zip$/i.test(a.name || '')) || null)- : (assets.find((a) => /\.dmg$/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);updateState.dmgUrl = asset ? asset.browser_download_url : null;updateState.dmgSize = asset ? asset.size : 0;updateState.checkedAt = Date.now();@@ -342,6 +356,7 @@ function checkUpdate(force) {updateState.latest = c.latest;updateState.hasUpdate = !!c.hasUpdate;updateState.dmgUrl = c.dmgUrl;+ updateState.dmgSize = Number(c.dmgSize) || 0;updateState.notes = c.notes;updateState.checkedAt = c.checkedAt || Date.now();} catch (_) {}@@ -353,20 +368,23 @@ function checkUpdate(force) {function downloadUpdate() {if (!updateState.dmgUrl) return Promise.reject(new Error('无可用安装包'));fs.mkdirSync(UPDATE_DIR, { recursive: true });+ updateState.downloaded = false;+ updateState.error = null;const ext = IS_WIN ? '.zip' : '.dmg';- const target = path.join(UPDATE_DIR, 'WorkDaddy-' + updateState.latest + ext);+ const updatePrefix = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI-' : 'WorkDaddy-';+ const target = path.join(UPDATE_DIR, updatePrefix + updateState.latest + ext);if (fs.existsSync(target)) {- // 已有同版本文件:直接校验后复用- const digest = sha256File(target);const expect = parseSha256(updateState.notes);- if (!expect || digest === expect) {+ const checked = validateUpdateArtifact(target, expect);+ if (checked.ok) {updateState.downloaded = true;updateState.progress = 100;updateState.status = 'idle';updateState.message = '安装包已就绪';return Promise.resolve(target);}- fs.unlinkSync(target); // 校验失败删掉重下+ log(`[update] 丢弃缓存安装包 ${path.basename(target)}: ${checked.reason}`);+ try { fs.unlinkSync(target); } catch (_) {}}updateState.status = 'downloading';updateState.progress = 0;@@ -382,6 +400,15 @@ function downloadUpdate() {res.resume();return;}+ const contentType = String(res.headers['content-type'] || '').toLowerCase();+ if (!IS_WIN && /text\/html|application\/json/.test(contentType)) {+ res.resume();+ const error = new Error(`下载响应不是 DMG (content-type=${contentType})`);+ updateState.status = 'error';+ updateState.error = error.message;+ reject(error);+ return;+ }const total = parseInt(res.headers['content-length'] || '0', 10) || updateState.dmgSize;let received = 0;const out = fs.createWriteStream(target);@@ -396,19 +423,19 @@ function downloadUpdate() {updateState.progress = 100;updateState.status = 'verifying';updateState.message = '校验安装包…';- const digest = sha256File(target);const expect = parseSha256(updateState.notes);- if (expect && digest !== expect) {- fs.unlinkSync(target);+ const checked = validateUpdateArtifact(target, expect);+ if (!checked.ok) {+ try { fs.unlinkSync(target); } catch (_) {}updateState.status = 'error';- updateState.error = 'SHA-256 校验失败';- updateState.message = '校验失败,已删除损坏包';- return reject(new Error('SHA-256 mismatch: ' + digest + ' != ' + expect));+ updateState.error = checked.reason;+ updateState.message = '安装包校验失败,已删除损坏包';+ return reject(new Error(checked.reason));}updateState.downloaded = true;updateState.status = 'idle';- updateState.message = '安装包已就绪' + (expect ? '(校验通过)' : '(未校验)');- log(`[update] 下载完成 ${target} sha256=${digest}`);+ updateState.message = '安装包已就绪' + (expect ? '(校验通过)' : '(格式校验通过)');+ log(`[update] 下载完成 ${target} sha256=${checked.digest}`);resolve(target);});out.on('error', (e) => { try { fs.unlinkSync(target); } catch (_) {} reject(e); });@@ -421,6 +448,44 @@ function sha256File(file) {return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');}+// 文件存在或没有 Release notes 摘要都不能证明它是可挂载的 DMG:断流、代理错误页+// 和旧版残留文件都可能留下普通文件。hdiutil imageinfo 是 macOS UDIF 的确定性预检。+function validateUpdateArtifact(file, expectSha = null) {+ let stat;+ try {+ stat = fs.statSync(file);+ } catch (e) {+ return { ok: false, reason: '安装包文件不可读: ' + e.message };+ }+ if (!stat.isFile() || stat.size <= 0) return { ok: false, reason: '安装包为空或不是普通文件' };+ if (updateState.dmgSize > 0 && stat.size !== updateState.dmgSize) {+ return { ok: false, reason: `安装包大小不匹配 (${stat.size} != ${updateState.dmgSize})` };+ }+ if (!IS_WIN) {+ let probe;+ try {+ probe = spawnSync('hdiutil', ['imageinfo', file], {+ encoding: 'utf8', timeout: 20000, windowsHide: true,+ });+ } catch (e) {+ return { ok: false, reason: 'DMG 预检执行失败: ' + e.message };+ }+ if (probe.error || probe.status !== 0) {+ const detail = String(probe.stderr || probe.stdout || probe.error?.message || '未知 hdiutil 错误')+ .replace(/\s+/g, ' ').trim().slice(0, 240);+ return { ok: false, reason: '下载内容不是有效 DMG: ' + detail };+ }+ }+ let digest;+ try { digest = sha256File(file); } catch (e) {+ return { ok: false, reason: '安装包 SHA-256 读取失败: ' + e.message };+ }+ if (expectSha && digest !== expectSha) {+ return { ok: false, reason: `SHA-256 校验失败 (${digest} != ${expectSha})` };+ }+ return { ok: true, digest };+}+// ---------------------------------------------------------------------------// 无感登录(OAuth state 轮询采集,流程与 workbuddy-switch 一致):// 1. POST /v2/plugin/auth/state?platform=workbuddy 申请 state + 授权链接@@ -429,7 +494,10 @@ function sha256File(file) {// 4. GET /v2/plugin/login/account?state=... 拉账号信息,拼成官方认证文件结构入库// ----------------------------------------------------------------------------const WB_API_ENDPOINT = 'https://www.codebuddy.cn';+// 各客户端 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_PREFIX = '/v2/plugin';const OAUTH_TIMEOUT_SECONDS = 600;const OAUTH_RESULT_RETENTION_SECONDS = 300;@@ -620,17 +688,28 @@ async function oauthPollOnce(loginId) {// 从 dmg 中解出 WorkDaddy.app 到 UPDATE_DIR(挂载→拷贝→卸载),返回 app 目录function extractAppFromDmg(dmgPath) {const mountPoint = '/Volumes/WorkDaddy-update';- const appDest = path.join(UPDATE_DIR, 'WorkDaddy.app');+ const appPackageName = WORKDADDY_INSTALL_NAME + '.app';+ const appDest = path.join(UPDATE_DIR, appPackageName);return new Promise((resolve, reject) => {const exec = require('child_process').execFile;+ const checked = validateUpdateArtifact(dmgPath, parseSha256(updateState.notes));+ if (!checked.ok) {+ log(`[update] DMG 预检失败 ${path.basename(dmgPath)}: ${checked.reason}`);+ reject(new Error(`DMG 预检失败: ${checked.reason}`));+ return;+ }// 先清理可能残留的挂载点(上次更新失败/中断会遗留,direct attach -mountpoint 会报 Resource busy),// 再用只读 + 免校验挂载(只取包内容,不做写操作)exec('hdiutil', ['detach', mountPoint, '-force'], () => {exec('hdiutil', ['attach', '-nobrowse', '-readonly', '-noverify', '-mountpoint', mountPoint, dmgPath], (err) => {- if (err) return reject(new Error('挂载 dmg 失败: ' + err.message));- const src = path.join(mountPoint, 'WorkDaddy.app');+ if (err) {+ const detail = String(err.stderr || err.message || '未知 hdiutil 错误').replace(/\s+/g, ' ').trim().slice(0, 300);+ log(`[update] hdiutil attach 失败 ${path.basename(dmgPath)}: ${detail}`);+ return reject(new Error('挂载 dmg 失败: ' + detail));+ }+ const src = path.join(mountPoint, WORKDADDY_INSTALL_NAME + '.app');if (!fs.existsSync(src)) {- exec('hdiutil', ['detach', mountPoint, '-force'], () => reject(new Error('dmg 中未找到 WorkDaddy.app')));+ exec('hdiutil', ['detach', mountPoint, '-force'], () => reject(new Error(`dmg 中未找到 ${WORKDADDY_INSTALL_NAME}.app`)));return;}fs.rmSync(appDest, { recursive: true, force: true });@@ -683,7 +762,8 @@ function applyUpdate() {// Windows 安装位置由 install.ps1 铺好(%LOCALAPPDATA%\Programs\WorkDaddy)const scriptPath = path.join(__dirname, 'apply-update.ps1');const appDir = WORKDADDY_DIR_WIN;- const srcZip = path.join(UPDATE_DIR, 'WorkDaddy-' + updateState.latest + '.zip');+ const updatePrefix = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI-' : 'WorkDaddy-';+ const srcZip = path.join(UPDATE_DIR, updatePrefix + updateState.latest + '.zip');if (!fs.existsSync(scriptPath)) {const error = new Error('缺少 apply-update.ps1');markAttemptFailure(error, 'preflight-error');@@ -721,7 +801,7 @@ function applyUpdate() {const wscript = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'wscript.exe');const child = spawn(wscript,- ['//nologo', applyVbs, scriptPath, srcZip, appDir, String(ACTUAL_PORT), applyLog, attempt.id],+ ['//nologo', applyVbs, scriptPath, srcZip, appDir, String(ACTUAL_PORT), applyLog, attempt.id, PROFILE.id],{ detached: true, stdio: 'ignore', windowsHide: true });child.once('error', markSpawnFailure);@@ -744,14 +824,15 @@ function applyUpdate() {}const scriptPath = path.join(__dirname, 'apply-update.sh');const appPath = macWorkDaddyAppPath();- const srcApp = path.join(UPDATE_DIR, 'WorkDaddy.app');+ const srcApp = path.join(UPDATE_DIR, WORKDADDY_INSTALL_NAME + '.app');if (!fs.existsSync(scriptPath)) {const error = new Error('缺少 apply-update.sh');markAttemptFailure(error, 'preflight-error');return Promise.reject(error);}// 解出新应用:下载阶段只落了 .dmg,这里才把 WorkDaddy.app 从 dmg 解到 UPDATE_DIR(幂等:已解出则复用)- const dmgPath = path.join(UPDATE_DIR, 'WorkDaddy-' + updateState.latest + '.dmg');+ const updatePrefix = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI-' : 'WorkDaddy-';+ const dmgPath = path.join(UPDATE_DIR, updatePrefix + updateState.latest + '.dmg');const preUnpack = fs.existsSync(srcApp)? Promise.resolve(srcApp): (fs.existsSync(dmgPath)@@ -797,7 +878,7 @@ function rotateLogsIfNeeded() {}function log(...args) {- const line = `[${new Date().toISOString()}] ${args.join(' ')}\n`;+ const line = `[${new Date().toISOString()}] [client=${PROFILE.name}] [profile=${PROFILE.id}] ${args.join(' ')}\n`;// launchd/nohup 已把 stdout 重定向到同一个文件;只写一次,避免每条日志重复。try {rotateLogsIfNeeded();@@ -904,7 +985,7 @@ function scheduleBackup(reason) {}// 兜底:登录文件本身变化(每次打开/刷新 WorkBuddy 都会重写该文件)-fs.watchFile(AUTH_FILE, { interval: WATCH_INTERVAL }, (cur, prev) => {+if (AUTH_FILE) fs.watchFile(AUTH_FILE, { interval: WATCH_INTERVAL }, (cur, prev) => {// 文件被移走(如"假退出登录")时不应触发备份;仅当文件存在且 mtime 变化才备份if (!fs.existsSync(AUTH_FILE)) return;if (cur.mtimeMs !== prev.mtimeMs) scheduleBackup('file-change');@@ -917,6 +998,7 @@ const cdp = {connected: false,port: null,targetUrl: null,+ targetTitle: null,error: null,id: 0,pending: new Map(),@@ -939,7 +1021,11 @@ let lastInjectTs = 0;let injectRetryTimer = null; // 被节流跳过的自动注入的兜底补种定时器async function findCdpEndpoint() {- const ports = cdpPortCandidates();+ // profile 已由启动器绑定时不能扫描其他产品的端口;CodeBuddy Agents/Editor+ // 共用 Browser 标识,跨 profile 扫描会把注入发到另一端。+ const ports = process.env.WBSWITCH_PROFILE+ ? [CDP_PORT_HINT, readCdpPortFile()].filter((p, i, a) => validCdpPort(p) && a.indexOf(p) === i)+ : cdpPortCandidates();for (const p of ports) {try {const [versionRes, listRes] = await Promise.all([@@ -949,7 +1035,8 @@ async function findCdpEndpoint() {const version = await versionRes.json();const list = await listRes.json();const targets = Array.isArray(list) ? list : [];- const belongsToWorkBuddy = /workbuddy|codebuddy/i.test([version.Browser, version['User-Agent']].filter(Boolean).join(' '));+ const browserInfo = [version.Browser, version['User-Agent']].filter(Boolean).join(' ');+ const belongsToWorkBuddy = /workbuddy|codebuddy/i.test(browserInfo);if (belongsToWorkBuddy && targets.some(isWorkBuddyCdpTarget)) {if (readCdpPortFile() !== p) writeCdpPortFile(p);return p;@@ -965,12 +1052,9 @@ async function findCdpEndpoint() {}function isWorkBuddyCdpTarget(target) {- if (!target || target.type !== 'page') return false;- const url = String(target.url || '');- const title = String(target.title || '');- return /(?:^|\/)WorkBuddy\.app(?:\/|$)/i.test(url) ||- /https?:\/\/(?:[^/]+\.)?(?:workbuddy|codebuddy)\.cn(?:\/|$)/i.test(url) ||- /^WorkBuddy(?:\s|$)/i.test(title);+ // 严格归属判定(见 cdp-targets.js):页面明确属于其他客户端 → 一律拒绝,+ // 未绑定 profile 的旧 daemon 不会再靠标题 "WorkBuddy" 误连兄弟客户端页面。+ return isTargetForProfile(target, PROFILE);}async function getPageTarget(port) {@@ -988,6 +1072,12 @@ async function cleanupForeignInjectedTargets(targets) {}async function cleanupForeignInjectedTarget(target) {+ // 四客户端同族页面可能携带其他 profile daemon 注入的合法组件(如未绑定 CN daemon+ // 扫描到 WorkBuddy AI 页面),必须跳过,不能当作"历史误注入"清理。+ if (looksLikeWbFamilyTarget(target)) {+ log(`[cdp] 跳过同族页面清理: ${(target.title || target.url || 'unknown').slice(0, 80)}`);+ return;+ }await new Promise((resolve) => {let settled = false;const finish = () => {@@ -1085,6 +1175,7 @@ async function connectCdp() {cdp.connected = true;cdp.error = null;cdp.targetUrl = target.url || '';+ cdp.targetTitle = target.title || '';log(`[cdp] 已连接 WorkBuddy (port=${cdp.port}, target=${cdp.targetUrl})`);// 打开感兴趣的能力域cdpSend('Page.enable').catch(() => {});@@ -1192,8 +1283,9 @@ async function reloadWorkBuddyPage() {await cdpSend('Page.reload', { ignoreCache: false });}-const WORKBUDDY_APP = IS_WIN ? '' : '/Applications/WorkBuddy.app';+const WORKBUDDY_APP = IS_WIN ? '' : PROFILE.appPath;const WORKBUDDY_BINARY = IS_WIN ? '' : `${WORKBUDDY_APP}/Contents/MacOS/Electron`;+const WORKBUDDY_APP_NAME = path.basename(WORKBUDDY_APP).replace(/\.app$/i, '');// Windows:解析 WorkBuddy 可执行文件真实路径(安装盘可自定义,必须动态查)// 优先级:WBSWITCH_WORKBUDDY_BIN > 运行进程 Path > 注册表卸载项 > 常见路径@@ -1346,7 +1438,7 @@ async function quitWorkBuddy() {}// 先尝试正常退出(给 Electron 一次处理机会),再强制 kill 并验证。- await runCommand('osascript', ['-e', 'tell application "WorkBuddy" to quit']);+ await runCommand('osascript', ['-e', `tell application "${WORKBUDDY_APP_NAME}" to quit`]);if (await waitForWorkBuddyExit(2500)) return true;await runCommand('pkill', ['-f', WORKBUDDY_APP]);if (await waitForWorkBuddyExit(2500)) return true;@@ -1358,12 +1450,14 @@ async function quitWorkBuddy() {/** 探测 WorkDaddy.app 位置(macOS 专用:退出登录后打开它,由其 launcher 以 CDP 模式重启 WorkBuddy 并注入组件) */function findWorkDaddyApp() {if (IS_WIN) return null;+ const appPackageName = WORKDADDY_INSTALL_NAME + '.app';const cands = [- '/Applications/WorkDaddy.app',- path.join(os.homedir(), 'Applications', 'WorkDaddy.app'),- path.join(os.homedir(), 'Desktop', 'WorkDaddy.app'),+ path.join('/Applications', appPackageName),+ path.join(os.homedir(), 'Applications', appPackageName),+ path.join(os.homedir(), 'Desktop', appPackageName),+ path.join(__dirname, '..', appPackageName),path.join(__dirname, '..', 'WorkDaddy.app'),- path.join(__dirname, '..', '..', 'workbuddy-switch', 'WorkDaddy.app'),+ path.join(__dirname, '..', '..', 'workbuddy-switch', appPackageName),];for (const c of cands) {try {@@ -1546,11 +1640,23 @@ async function waitPageLoaded(timeoutMs = 6000) {*//* ================= 积分自动领取(直接调接口,带每日缓存) ================= */-const CHECKIN_ENDPOINTS = [- 'https://www.workbuddy.cn/billing/meter/daily-checkin',- 'https://www.workbuddy.cn/v2/billing/meter/daily-checkin',- 'https://www.codebuddy.cn/v2/billing/meter/daily-checkin',-];+// 签到接口按 profile 归属域名生成:国际版(WorkBuddy AI)命中 www.workbuddy.ai,+// 国内版保留多域名兜底(workbuddy.cn / codebuddy.cn 账号体系互通)。+function profileCheckinEndpoints() {+ const host = PROFILE.apiHost || 'https://www.workbuddy.cn';+ const eps = [+ `${host}/billing/meter/daily-checkin`,+ `${host}/v2/billing/meter/daily-checkin`,+ ];+ if (PROFILE.region === 'cn') {+ eps.push(+ 'https://www.codebuddy.cn/billing/meter/daily-checkin',+ 'https://www.codebuddy.cn/v2/billing/meter/daily-checkin'+ );+ }+ return Array.from(new Set(eps));+}+const CHECKIN_ENDPOINTS = profileCheckinEndpoints();const CHECKIN_CACHE_FILE = path.join(DATA_DIR, 'checkin-cache.json');const CHECKIN_REQUEST_TIMEOUT_MS = 12000;const CHECKIN_QUEUE_DELAY_MS = 250;@@ -1587,6 +1693,7 @@ function saveCheckinCache(cache) {* 成功 / 已签(code=10001)均视为当日已完成。*/async function dailyCheckin(accessToken) {+ const origin = PROFILE.apiHost || 'https://www.workbuddy.cn';let lastErr = null;for (const url of CHECKIN_ENDPOINTS) {const controller = new AbortController();@@ -1598,8 +1705,8 @@ async function dailyCheckin(accessToken) {accept: 'application/json, text/plain, */*','content-type': 'application/json','x-client-platform': 'web',- origin: 'https://www.workbuddy.cn',- referer: 'https://www.workbuddy.cn/profile/plans-usage',+ origin: origin,+ referer: origin + '/profile/plans-usage',authorization: 'Bearer ' + accessToken,'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36',},@@ -1654,6 +1761,7 @@ async function claimDailyForUid(uid) {/** 对所有账号执行每日签到(自动跳过今日已成功过的,带并发保护) */async function claimDailyForAll() {+ if (!PROFILE.capabilities.accounts) return { skipped: true, reason: 'profile-no-account-files' };if (claimInFlight) return { skipped: true, reason: 'in-flight', checkin: checkinSnapshot() };claimInFlight = true;try {@@ -1687,6 +1795,15 @@ function injectWidget(reason) {if (!cdp.connected) {return Promise.reject(new Error('CDP 未连接,无法注入组件'));}+ // 防御闸:绝不向其他客户端的页面注入。四客户端支持后,未绑定 profile 的旧 daemon+ // 可能扫到兄弟客户端页面;其余环节(归属判定/清理跳过)已拦截,这里作为最后一道保险。+ if (cdp.targetUrl) {+ const cls = classifyTarget(cdp.targetUrl, cdp.targetTitle || '');+ if (cls && cls !== PROFILE.id) {+ log(`[cdp] 目标页面属于 ${cls}(当前 profile=${PROFILE.id}),拒绝注入`);+ return Promise.reject(new Error(`目标页面 ${cls} 不属于当前 profile ${PROFILE.id}`));+ }+ }// 节流:仅抑制 connect 与 page-load 在 <1s 内连发的重复注入(避免闪烁)。// 关键:manual(launcher/用户显式 /api/inject)恒不等候、必须无条件注入——// 否则 WorkBuddy 重启后仅有的注入机会会被节流吞掉(多台机器 FAB 缺失的根因:@@ -1716,6 +1833,8 @@ function injectWidget(reason) {// 同步注入当前 daemon 版本号(inject.js 顶部的 __WBS_VERSION__ 占位符会在面板「关于」页直接展示,// 这样版本升级后不需要改 inject.js、面板永远显示 daemon 的真实版本)script = script.replace(/__WBS_VERSION__/g, DAEMON_VERSION);+ script = script.replace(/__WBS_PROFILE__/g, PROFILE.id);+ script = script.replace(/__WBS_CAPS__/g, JSON.stringify(PROFILE.capabilities));// 注入策略:不使用 addScriptToEvaluateOnNewDocument(它会在浏览器里持久化注册,// 多次重启会叠加旧版本;旧注册先执行并占住 window.__wbsWidget 守卫,导致新代码被拦截)。// 改为:先用 Runtime.evaluate 暴力清理任何历史残留(不依赖旧版本的 destroy,避免清不干净),@@ -1835,7 +1954,7 @@ async function writeDiagnosticsSnapshot(reason) {// ===== SESSIONS_API_MARK:会话管理(读 WorkBuddy workbuddy.db)=====-const SESSIONS_DB = path.join(os.homedir(), '.workbuddy', 'workbuddy.db');+const SESSIONS_DB = PROFILE.sessionDb;// Windows:无系统 sqlite3 CLI,优先用 Node 内置 node:sqlite(需 --experimental-sqlite 启动,launcher/install 已统一加)let NodeSqlite = null;if (IS_WIN) { try { NodeSqlite = require('node:sqlite'); } catch (_) { NodeSqlite = null; } }@@ -1845,6 +1964,9 @@ function sqliteIsWrite(sql) {return /^\s*(?:INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER|VACUUM|REINDEX|ANALYZE|BEGIN|COMMIT|ROLLBACK|ATTACH|DETACH)\b/i.test(String(sql || ''));}function sqliteRun(sql) {+ if (PROFILE.kind === 'codebuddy') {+ return Promise.reject(new Error(`${PROFILE.name} 会话库暂只支持读取`));+ }if (IS_WIN && NodeSqlite) {return new Promise((resolve, reject) => {let db = null;@@ -1883,7 +2005,57 @@ function sqliteRun(sql) {p.stdin.end(sql);});}+function codeBuddySessionRows() {+ if (NodeSqlite) {+ try {+ const db = new NodeSqlite.DatabaseSync(SESSIONS_DB, { readOnly: true });+ const items = db.prepare("SELECT key, value FROM ItemTable WHERE key LIKE 'session:%'").all();+ db.close();+ return Promise.resolve(items.map((item) => ({ key: item.key, value: item.value })));+ } catch (e) {+ return Promise.reject(new Error('CodeBuddy 会话库读取失败: ' + e.message));+ }+ }+ return new Promise((resolve, reject) => {+ const p = spawn('sqlite3', ['-json', SESSIONS_DB, 'SELECT key, value FROM ItemTable WHERE key LIKE \'session:%\';'], { stdio: ['ignore', 'pipe', 'pipe'] });+ let out = '', err = '';+ p.stdout.on('data', (d) => { out += d; });+ p.stderr.on('data', (d) => { err += d; });+ p.on('error', (e) => reject(new Error('sqlite3 不可用: ' + e.message)));+ p.on('close', (code) => {+ if (code !== 0) return reject(new Error('CodeBuddy 会话库读取失败: ' + err.slice(0, 200)));+ let items = [];+ try { items = JSON.parse(out || '[]'); } catch (e) { return reject(new Error('CodeBuddy 会话记录解析失败: ' + e.message)); }+ resolve(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 || '',+ };+ }));+ });+ });+}async function sqliteQuery(sql) {+ if (PROFILE.kind === 'codebuddy') {+ const rows = await codeBuddySessionRows();+ const textSql = String(sql || '');+ const uidMatch = textSql.match(/user_id\s*=\s*'([^']*)'/i);+ const idMatch = textSql.match(/id\s+IN\s*\(([^)]*)\)/i);+ let filtered = rows;+ if (uidMatch) filtered = filtered.filter((r) => String(r.user_id) === uidMatch[1]);+ if (idMatch) {+ const ids = new Set(Array.from(idMatch[1].matchAll(/'([^']*)'/g)).map((m) => m[1]));+ filtered = filtered.filter((r) => ids.has(String(r.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 out = await sqliteRun(sql);if (!out.trim()) return [];const lines = out.trim().split('\n');@@ -1995,7 +2167,7 @@ async function insertCopiedSession(src, targetUid, newId) {async function copySessionRecord(src, targetUid, options = {}) {const sourceUid = String(options.sourceUid || src.user_id || '').trim();const auto = !!options.auto;- const wbHome = path.join(os.homedir(), '.workbuddy');+ const wbHome = PROFILE.dataRoot;let lineageId = options.lineageId || null;const sourceLineage = sourceUid ? getAutoCopySession(DATA_DIR, sourceUid, src.id) : { lineageId: null, enabled: false };if (!lineageId && sourceLineage.enabled) lineageId = sourceLineage.lineageId;@@ -2261,7 +2433,7 @@ const ASK_MODE_RULE = [].join('\n');function workbuddySettingsPath() {- return path.join(os.homedir(), '.workbuddy', 'settings.json');+ return path.join(PROFILE.dataRoot, 'settings.json');}function readWorkbuddySettings() {@@ -2325,6 +2497,7 @@ function setAskMode(enabled) {/** 启动时调用:如已启用决策弹窗,把旧的 ASK_MODE_RULE 替换为最新版本(用 ASK_MODE_TAG_START/END 精确识别) */function refreshAskModeIfEnabled() {+ if (PROFILE.kind !== 'workbuddy') return;try {const state = getAskModeState();if (!state.enabled) return;@@ -2336,6 +2509,7 @@ function refreshAskModeIfEnabled() {}function currentAccount() {+ if (!PROFILE.capabilities.accounts || !AUTH_FILE) return null;try {const c = readAuthFile();const a = (c.raw && c.raw.auth) || {};@@ -2532,6 +2706,7 @@ function builtinAssetsDir() {* 不覆盖用户已有的自定义/删减内容(已存在的文件不动)。*/function initBuiltinAssets() {+ if (!PROFILE.capabilities.theme) return;try {const src = builtinAssetsDir();if (!src) {@@ -2801,6 +2976,7 @@ function getTheme(id) {/** 恢复已保存的主题(CDP 连接/页面刷新后调用):读取 current-theme.json 重新应用,保证深浅色在重启/刷新后仍生效 */async function restoreSavedTheme() {+ if (!PROFILE.capabilities.theme) return;if (!cdp.connected) return;let id = 'default';try {@@ -2863,6 +3039,7 @@ function themeExtrasCss() {}async function applyThemeByCdp(id) {+ if (!PROFILE.capabilities.theme) throw new Error(`${PROFILE.name} 暂不支持主题功能`);if (!cdp.connected) throw new Error('CDP 未连接');const theme = getTheme(id);const colors = (theme && theme.colors) || {};@@ -3267,14 +3444,16 @@ function formatLocalDateTime(d) {* 接口返回 Account 数组,累加每个 Account 的 CapacityRemainPrecise。*/async function fetchResource(accessToken, body, source) {- const r = await fetch('https://www.workbuddy.cn/billing/meter/get-user-resource', {+ // 积分查询与签到同源:按 profile 归属域名请求(国际版为 www.workbuddy.ai)+ const apiHost = PROFILE.apiHost || 'https://www.workbuddy.cn';+ const r = await fetch(`${apiHost}/billing/meter/get-user-resource`, {method: 'POST',headers: {accept: 'application/json, text/plain, */*','content-type': 'application/json','x-client-platform': 'web',- origin: 'https://www.workbuddy.cn',- referer: 'https://www.workbuddy.cn/profile/plans-usage',+ origin: apiHost,+ referer: `${apiHost}/profile/plans-usage`,authorization: `Bearer ${accessToken}`,'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36',},@@ -3613,6 +3792,7 @@ function handleApi(req, res) {ok: true,version: DAEMON_VERSION,buildId: DAEMON_BUILD_ID,+ profile: { id: PROFILE.id, name: PROFILE.name, kind: PROFILE.kind, mode: PROFILE.mode, capabilities: PROFILE.capabilities },cdp: {connected: cdp.connected,port: cdp.port,@@ -3649,10 +3829,11 @@ function handleApi(req, res) {const accounts = listAccounts(DATA_DIR);const cache = loadCheckinCache();const today = todayStr();+ const checkinPending = !!claimInFlight;const enriched = accounts.map((a) => {const c = cache[a.uid];return Object.assign({}, a, {- checkin: c && c.date === today ? { ok: c.ok, already: c.already, code: c.code, message: c.message } : null,+ checkin: checkinDisplayValue(c, today, checkinPending),});});return json(res, 200, { ok: true, current: currentAccount(), accounts: enriched, checkin: checkinSnapshot() });@@ -3988,7 +4169,24 @@ function handleApi(req, res) {} catch (e) {officialError = e.message;}- return json(res, 200, { ok: true, file: workbuddyModelsFile(), official, officialError, backups: listModelBackups(DATA_DIR) });+ return json(res, 200, { ok: true, file: workbuddyModelsFile(), official, officialError, backups: listModelBackups(DATA_DIR), imports: listInstalledModelSources(PROFILE.id) });+ }+ if (req.method === 'POST' && p === '/api/models/import') {+ return readBody(req).then((body) => {+ try {+ const profileId = String((body && body.profileId) || '').trim();+ const source = listInstalledModelSources(PROFILE.id).find((item) => item.profileId === profileId);+ if (profileId === PROFILE.id) return json(res, 400, { ok: false, error: '不能从当前客户端导入模型' });+ if (!source) return json(res, 404, { ok: false, error: '未找到可导入的客户端模型配置' });+ // 两个 WorkBuddy 桌面端共用同一 models.json:配置天然互通,无需导入+ if (source.shared) return json(res, 200, { ok: true, shared: true, imported: [], skipped: [] });+ if (!source.available) return json(res, 404, { ok: false, error: `未找到 ${source.name} 的模型配置文件` });+ const result = importModels(workbuddyModelsFile(), source.modelsFile);+ return json(res, 200, { ok: true, imported: result.imported, skipped: result.skipped, official: result.official });+ } catch (e) {+ return json(res, 400, { ok: false, error: e.message || String(e) });+ }+ });}if (req.method === 'POST' && p === '/api/models/backup') {return readBody(req).then((body) => {@@ -4054,7 +4252,7 @@ function handleApi(req, res) {const ids = Array.isArray(body && body.backupIds) ? body.backupIds : [];if (!ids.length) return json(res, 400, { ok: false, error: '未选择模型备份' });const deleted = deleteModelBackups(DATA_DIR, ids);- return json(res, 200, { ok: true, deleted, backups: listModelBackups(DATA_DIR) });+ return json(res, 200, { ok: true, requested: ids.length, deleted, backups: listModelBackups(DATA_DIR) });} catch (e) {return json(res, 400, { ok: false, error: e.message });}@@ -4157,7 +4355,7 @@ function handleApi(req, res) {// 1) 真实删除 DB 记录(非软删)await sqliteRun("DELETE FROM sessions WHERE id IN (" + esc + ");");// 2) 删除本地消息文件(jsonl/目录/workspace/tasks/file-history/artifact-index)- const wbHome = path.join(os.homedir(), '.workbuddy');+ const wbHome = PROFILE.dataRoot;let filesRemoved = 0;for (const id of ids) filesRemoved += deleteSessionFiles(wbHome, id);let rulesRemoved = 0;@@ -4363,15 +4561,15 @@ function handleApi(req, res) {} catch (_) { /* 解析失败忽略 */ }return json(res, 200, {ok: true,- name: 'WorkDaddy',- tagline: 'WorkBuddy 的多账号 · 主题 · 增强工具集',+ name: WORKDADDY_INSTALL_NAME,+ tagline: PROFILE.name + ' 的多账号 · 主题 · 增强工具集',version: build.version,appVersion: appVersion,license: 'AGPL-3.0',repository: 'https://github.com/babygoton/WorkDaddy',principle: '本机回环 CDP 注入 · 不改官方安装包',platform: IS_WIN ? 'Windows 10+(x64)' : 'macOS 11+',- author: 'WorkDaddy',+ author: WORKDADDY_INSTALL_NAME,nodeVersion: process.version,...platform,...build,@@ -4793,10 +4991,10 @@ function startServer() {const c = currentAccount();res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });return res.end(- '<!doctype html><html lang="zh"><meta charset="utf-8"><title>WorkDaddy</title>' ++ '<!doctype html><html lang="zh"><meta charset="utf-8"><title>' + WORKDADDY_INSTALL_NAME + '</title>' +'<body style="font-family:-apple-system,sans-serif;background:#0f1115;color:#e6e6e8;display:flex;align-items:center;justify-content:center;height:100vh;margin:0">' +- '<div style="text-align:center"><h1 style="margin:0 0 8px">WorkDaddy v' + DAEMON_VERSION + '</h1>' +- '<p style="color:#9a9aa0;margin:0">面板入口:WorkBuddy 右下角机器人按钮</p>' ++ '<div style="text-align:center"><h1 style="margin:0 0 8px">' + WORKDADDY_INSTALL_NAME + ' v' + DAEMON_VERSION + '</h1>' ++ '<p style="color:#9a9aa0;margin:0">面板入口:' + PROFILE.name + ' 右下角机器人按钮</p>' +'<p style="color:#555;font-size:12px;margin-top:16px">守护进程运行中 · CDP ' + (cdp.connected ? '已连接' : '未连接') +(c && c.nickname ? ' · 当前账号:' + String(c.nickname).replace(/</g, '<') : '') + '</p></div></body></html>');@@ -4937,7 +5135,7 @@ process.on('SIGTERM', () => {releaseDaemonLock();try { stopCaffeinate(); } catch (_) {}try {- fs.unwatchFile(AUTH_FILE);+ if (AUTH_FILE) fs.unwatchFile(AUTH_FILE);} catch (_) {}process.exit(0);});diff --git a/scripts/inject.js b/scripts/inject.jsindex 3078fbd..1b05185 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -76,6 +76,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {try { console.log('[WBS] inject.js 已执行于', location.href, 'body=', !!document.body); } catch (_) {}if (window.__wbsWidget) return; // 理论上 cleanup 已清除,保留为兜底var API = '__WBS_API__';+ var PROFILE_ID = '__WBS_PROFILE__';+ var CAPS = __WBS_CAPS__;+ // 面板品牌名跟随 profile:workbuddy-ai 显示 WorkDaddy AI,其余显示 WorkDaddy+ var WBS_BRAND = PROFILE_ID === 'workbuddy-ai' ? 'WorkDaddy AI' : 'WorkDaddy';// ===== 全局错误钩子:捕获渲染进程不可捕获的 error / unhandledrejection,把完整消息+栈// 打到 daemon 日志。渲染进程级崩溃(如 An object could not be cloned)虽非 try/catch 能拦,@@ -182,12 +186,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function checkinHtml(a) {+ // 国际版不开放签到活动:积分卡上的签到标签整体不展示(CN 版保留完整逻辑)+ if (PROFILE_ID === 'workbuddy-ai') return '';var c = a && a.checkin;if (!c) return '<span class="wbs-ck wbs-checkin-tag pending">签到中</span>';+ var msg = c.message || '';+ // 国际版/活动空窗期:接口 code 10001 且文案表明「活动未开启/未开始/已过期」时,+ // 并不是“今日已签到”,不应展示绿色成功标签,改为中性「无签到活动」。+ if (c.ok && /未开启|未开始|未开放|已过期|无.*活动|活动.*(结束|关闭|暂停)/i.test(msg)) {+ return '<span class="wbs-ck wbs-checkin-tag pending">无签到活动</span>';+ }// “本轮刚领取”和“今天已领取过”都是成功态,统一展示避免同一页面出现两套文案。if (c.ok) return '<span class="wbs-ck wbs-checkin-tag ok">今日已签到✓</span>';// 认证类错误(401/未授权)统一显示友好文案(daemon 已产出,缓存残留旧文案时兜底)- var msg = c.message || '失败';if (/401|Unauthorized|未授权|登录身份过期/.test(msg)) msg = '登录身份过期';return '<span class="wbs-ck wbs-checkin-tag fail">' + msg + '</span>';}@@ -314,7 +325,23 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 可编辑节点;否则取所有 contenteditable 中 y 距 voice-mic-wrap 最近且在其上方的节点(输入框紧贴操作栏上方)。function findComposer() {var mic = document.querySelector('.voice-mic-wrap');- if (!mic) return null;+ if (!mic) {+ // AI 端(无 voice-mic-wrap):输入框特征是 [contenteditable=true],且位于视口下半部、+ // 可见、有尺寸(消息历史是只读渲染,不是 contenteditable=true)。取最靠底部的那个。+ var all = document.querySelectorAll('[contenteditable="true"]');+ var best = null, bestCy = -Infinity;+ for (var i = 0; i < all.length; i++) {+ var el = all[i];+ if (!el.getBoundingClientRect) continue;+ var r = el.getBoundingClientRect();+ if (r.height <= 0 || r.width <= 0) continue;+ var cs = getComputedStyle(el);+ if (cs.visibility === 'hidden' || cs.display === 'none') continue;+ var cy = r.top + r.height / 2;+ if (cy > window.innerHeight * 0.45 && cy > bestCy) { bestCy = cy; best = el; }+ }+ return best || (all.length ? all[0] : null);+ }// 1) 在 voice-mic-wrap 祖先链(最多 6 层)内找可编辑节点var p = mic.parentElement;for (var up = 0; up < 6 && p; up++) {@@ -545,8 +572,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 根节点(fixed 右下角,面板 absolute 定位,右下角与按钮重合)var root = el('div', 'wbs-root');+ root.setAttribute('data-wbs-profile', PROFILE_ID);+ if (!CAPS.theme) root.classList.add('wbs-no-theme');+ if (!CAPS.stashPrompt) root.classList.add('wbs-no-stash');root.innerHTML = [- '<div class="wbs-fab" title="WorkDaddy">',+ '<div class="wbs-fab" title="' + WBS_BRAND + '">','<span class="wbs-fab-sleep-dot" title="防休眠未开启"></span>','<div class="click">','<span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span>',@@ -565,7 +595,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-panel">','<div class="wbs-head">','<div class="wbs-head-left">',- '<div class="wbs-title" id="wbs-title" title="连续点击 5 次呼出元素检查">WorkDaddy</div>',+ '<div class="wbs-title" id="wbs-title" title="连续点击 5 次呼出元素检查">' + WBS_BRAND + '</div>','<a class="wbs-ghbtn" href="https://github.com/babygoton/WorkDaddy" target="_blank" rel="noopener" title="GitHub 仓库">','<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M12 .3a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.03c-3.34.73-4.04-1.61-4.04-1.61-.55-1.39-1.33-1.76-1.33-1.76-1.09-.74.08-.73.08-.73 1.2.09 1.84 1.24 1.84 1.24 1.07 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.66-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.11-3.18 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 0 1 6.01 0c2.29-1.55 3.3-1.23 3.3-1.23.65 1.66.24 2.88.12 3.18.77.84 1.23 1.91 1.23 3.22 0 4.61-2.81 5.62-5.49 5.92.43.37.82 1.1.82 2.22v3.29c0 .32.22.7.83.58A12 12 0 0 0 12 .3z"/></svg>','</a>',@@ -592,6 +622,30 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {].join('');document.body.appendChild(root);+ // 不同客户端只开放明确支持的能力;保留统一面板结构可避免模式切换时布局抖动。+ if (!CAPS.theme) {+ var themeTab = root.querySelector('[data-tab="theme"]');+ var themePane = root.querySelector('[data-pane="theme"]');+ if (themeTab) themeTab.remove();+ if (themePane) themePane.remove();+ }+ if (!CAPS.models) {+ var modelsTab = root.querySelector('[data-tab="models"]');+ var modelsPane = root.querySelector('[data-pane="models"]');+ if (modelsTab) modelsTab.remove();+ if (modelsPane) modelsPane.remove();+ }+ if (!CAPS.accounts) {+ var accountTab = root.querySelector('[data-tab="account"]');+ var accountPane = root.querySelector('[data-pane="account"]');+ var sessionsTab = root.querySelector('[data-tab="sessions"]');+ var sessionsPane = root.querySelector('[data-pane="sessions"]');+ if (accountTab) accountTab.remove();+ if (accountPane) accountPane.remove();+ if (sessionsTab) sessionsTab.classList.add('active');+ if (sessionsPane) sessionsPane.classList.add('active');+ }+// ===== 暂存提示词:内联到「发送按钮」左侧,尺寸与发送按钮一致 =====// 显隐策略:直接监听 WorkBuddy 自己的「发送按钮」禁用态——输入框为空时发送按钮被禁用,// 此时隐藏暂存按钮;有内容(文字/图片/附件)时发送按钮可用,暂存按钮出现。@@ -602,11 +656,47 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {stashBtn.setAttribute('tabindex', '0');stashBtn.title = '暂存提示词';stashBtn.innerHTML = '<span class="wbs-stash-ico">' + STASH_SVG + '</span><span class="wbs-stash-txt">暂存提示词</span>';+ if (!CAPS.stashPrompt) stashBtn.style.display = 'none';// 定位输入框操作栏(含 voice-mic-wrap 的父容器)function findActionRow() {var mic = document.querySelector('.voice-mic-wrap');- return mic ? mic.parentElement : null;+ if (mic) return mic.parentElement;+ // AI 端(无 voice-mic-wrap):从输入框向上找最近的含按钮容器(操作栏),+ // 仅用于发送按钮状态监听,找不到不影响暂存按钮本身。+ var ed = findComposer();+ if (!ed) return null;+ var n = ed;+ for (var up = 0; up < 5 && n && n.parentElement; up++) {+ n = n.parentElement;+ if (!n.children || n.children.length < 2) continue;+ var hasBtn = false;+ for (var i = 0; i < n.children.length; i++) {+ var k0 = n.children[i];+ if (k0.tagName === 'BUTTON' || (k0.getAttribute && k0.getAttribute('role') === 'button')) { hasBtn = true; break; }+ }+ if (hasBtn) return n;+ }+ return null;+ }+ // AI 端输入框右下角按钮组。用户 DOM 路径:+ // ..._input-area-container_ > section._container_ > ... > div._spaceBetween_._inputBottom_ > div._item_._gapLarge_+ // 注意 _inputBottom_ 下有两个按钮组:左侧工具组(class 含 _selector_)、右侧发送按钮组(class 含 _gapLarge_,+ // x 更靠右)。必须命中右侧 _gapLarge_ 组,排除 _selector_ 组。+ function findAiToolbar() {+ var cands = document.querySelectorAll(+ '[class*="_inputBottom_"] > [class*="_gapLarge_"],' ++ '[class*="_inputBottom_"] > [class*="_gap_"]:not([class*="_selector_"]),' ++ '[class*="_inputBottom_"] > [class*="_item_"]:not([class*="_selector_"])'+ );+ var best = null, bestLeft = -Infinity;+ for (var i = 0; i < cands.length; i++) {+ var r = cands[i].getBoundingClientRect();+ if (r.width <= 0 || r.height <= 0) continue;+ // 同一行内取最靠右的按钮组(发送按钮组);行位置应贴近输入框底部+ if (r.left > bestLeft) { bestLeft = r.left; best = cands[i]; }+ }+ return best;}// 操作栏最右侧的「圆形可点击」元素才是发送按钮(左侧还可能有增强提示词/停止等圆形按钮)function findSendButton() {@@ -640,20 +730,83 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (/(^|[\s_])disabled($|[\s_])/.test(cls) || cls.indexOf('is-disabled') >= 0 || cls.indexOf('ant-btn-disabled') >= 0) return true;return false;}- // 关键:用 position: fixed 绝对定位到发送按钮坐标旁,挂在 document.body 下,+ // 关键:CN 端用 position: fixed 绝对定位到发送按钮坐标旁,挂在 document.body 下,// 不插入到操作栏 row.children 里——避开 React reconciliation 丢弃外部节点的问题。+ // AI 端(无 voice-mic-wrap):实测其按钮容器不清理外部插入节点,直接内联插入+ // 操作栏右侧按钮组的第一位(用户要求的摆放方式),fixed 定位由 CSS 类覆盖为静态参与 flex。function insertStash() {// 重新注入脚本时先移除旧版按钮(避免旧 SVG 图标/样式残留)var oldBtn = document.querySelector('.wbs-stash-inline');if (oldBtn && oldBtn !== stashBtn) oldBtn.remove();+ var mic0 = document.querySelector('.voice-mic-wrap');+ if (!mic0) {+ var row0 = findAiToolbar();+ if (row0) {+ stashBtn.classList.add('wbs-stash-inline-inline');+ if (stashBtn.parentElement !== row0) row0.insertBefore(stashBtn, row0.firstChild);+ } else {+ // 容器暂不可用:回落到 body + fixed 定位+ stashBtn.classList.remove('wbs-stash-inline-inline');+ if (!stashBtn.parentElement) document.body.appendChild(stashBtn);+ positionStash();+ }+ return;+ }if (!stashBtn.parentElement) document.body.appendChild(stashBtn);positionStash();}function positionStash() {+ // AI 端没有 voice-mic-wrap:操作栏按钮行位于输入框正下方(与输入框同祖先容器)。+ // 取该行最左按钮的左边为锚,top 与按钮行对齐——与 CN 端「操作栏最左」语义一致。+ var mic = document.querySelector('.voice-mic-wrap');+ if (!mic) {+ var ed0 = findComposer();+ if (!ed0) { stashBtn.style.display = 'none'; return false; }+ var er0 = ed0.getBoundingClientRect();+ if (er0.width <= 0 || er0.height <= 0) { stashBtn.style.display = 'none'; return false; }+ var rowLeft = Infinity, rowTop = Infinity, rowH = 0, found = false;+ var n0 = ed0, depth = 0;+ while (n0 && n0 !== document.body && depth++ < 6) {+ n0 = n0.parentElement;+ if (!n0 || !n0.querySelectorAll || !n0.children) continue;+ var btns = n0.querySelectorAll('button,[role="button"],[class*="_ringClickable_"],[class*="_iconButton_"]');+ var row = [];+ for (var i = 0; i < btns.length; i++) {+ var k0 = btns[i];+ if (k0.classList && (k0.classList.contains('wbs-fab') || k0.classList.contains('wbs-stash-inline'))) continue;+ var r0 = k0.getBoundingClientRect();+ if (r0.width < 16 || r0.height < 16) continue;+ var cs0 = getComputedStyle(k0);+ if (cs0.visibility === 'hidden' || cs0.display === 'none') continue;+ var circ = /%/.test(cs0.borderRadius) || parseFloat(cs0.borderRadius || '0') >= Math.min(r0.width, r0.height) / 2 - 3;+ if (!circ) continue;+ // 只要「输入框同高区域下方、紧贴输入框底部」的操作栏按钮行,排除消息区/侧栏按钮+ if (r0.top < er0.top - 8 || r0.bottom > er0.bottom + 120) continue;+ row.push(r0);+ }+ if (row.length >= 2) {+ for (var j = 0; j < row.length; j++) {+ if (row[j].left < rowLeft) rowLeft = row[j].left;+ if (row[j].top < rowTop) rowTop = row[j].top;+ if (row[j].height > rowH) rowH = row[j].height;+ }+ found = true;+ break;+ }+ }+ var gap0 = 6;+ if (found) {+ stashBtn.style.right = (window.innerWidth - (rowLeft - gap0)) + 'px';+ stashBtn.style.top = (rowTop + Math.max(0, (rowH - 32) / 2)) + 'px';+ } else {+ // 回落:以输入框左边界为锚+ stashBtn.style.right = (window.innerWidth - (er0.left - gap0)) + 'px';+ stashBtn.style.top = (er0.top - 1) + 'px';+ }+ return true;+ }// 锚点:操作栏最左元素(row.children[0]),定位到它的左边——整个操作栏最左。// 用 right 锚定(CSS left:auto):hover 时 width 增大 → 左边向左展开(参考 wbs-fab)。- var mic = document.querySelector('.voice-mic-wrap');- if (!mic) { stashBtn.style.display = 'none'; return false; }var row = mic.parentElement;if (!row || !row.children || !row.children.length) { stashBtn.style.display = 'none'; return false; }var firstChild = row.children[0]; // 操作栏最左元素("上下文用量"按钮)@@ -814,8 +967,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// WorkBuddy 首页 composer 的右上插槽存在时,按钮放回 WorkBuddy 窗口右下角,// 避免被首页输入区的内部定位挤到中间位置。var homeComposerCorner = document.querySelector('.wb-home-page [class*="_topRightSlotStandalone_"] > div:nth-child(1) > div:nth-child(3)');- if (homeComposerCorner) {- var cornerRect = homeComposerCorner.getBoundingClientRect();+ // WorkBuddy AI 欢迎页的右上插槽结构不同,第二个操作项出现时固定到窗口右下角。+ var aiHomeComposerCorner = PROFILE_ID === 'workbuddy-ai'+ ? document.querySelector('.wb-home-page [class*="_topRightSlotStandalone_"] > div:nth-child(1) > div:nth-child(2)')+ : null;+ if (homeComposerCorner || aiHomeComposerCorner) {+ var cornerRect = (aiHomeComposerCorner || homeComposerCorner).getBoundingClientRect();if (cornerRect.width > 0 && cornerRect.height > 0) {fab.classList.remove('fab--solid');fab.style.position = 'fixed';@@ -2041,7 +2198,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}// ===== 模型 pane(当前模型 + WorkDaddy 本地备份) =====- var modelsState = { tab: 'official', official: [], groups: [], selected: {}, batch: false, officialError: '' };+ var modelsState = { tab: 'official', official: [], groups: [], imports: [], selected: {}, batch: false, officialError: '' };function buildModelsPane() {if (!modelsPane) return;modelsPane.dataset.built = '1';@@ -2053,6 +2210,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'</div>' +'<div class="wbs-model-toolbar">' +'<span class="wbs-model-count" id="wbs-model-count"></span>' ++ '<span class="wbs-model-imports" id="wbs-model-imports"></span>' +'<span class="wbs-model-toolbar-spacer"></span>' +'<button class="wbs-sess-bbtn" type="button" id="wbs-model-batch" style="display:none">批量管理</button>' +'</div>' +@@ -2123,6 +2281,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {api('/api/models').then(function (data) {modelsState.official = data.official || [];modelsState.groups = data.backups || [];+ modelsState.imports = data.imports || [];modelsState.officialError = data.officialError || '';renderModels();}).catch(function (e) {@@ -2156,10 +2315,22 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (batchbar) batchbar.style.display = modelsState.batch ? '' : 'none';var tip = modelsPane.querySelector('#wbs-model-tip');if (tip) tip.style.display = modelsState.tab === 'mine' && !modelsState.batch ? '' : 'none';+ 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) {+ 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('');+ }updateModelCounts();if (modelsState.tab === 'official') {if (modelsState.officialError) { list.innerHTML = '<div class="wbs-empty">当前模型加载失败:' + esc(modelsState.officialError) + '</div>'; return; }- if (!modelsState.official.length) { list.innerHTML = '<div class="wbs-empty">没有找到当前模型配置</div>'; return; }+ if (!modelsState.official.length) { list.innerHTML = '<div class="wbs-empty">当前还未添加模型</div>'; return; }list.innerHTML = modelsState.official.map(function (model) { return modelRowHtml(model, { official: true, selectionKey: 'official:' + model.index }); }).join('');updateModelBatchState();return;@@ -2213,6 +2384,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {.catch(function (e) { toast('模型备份失败:' + (e.message || e), true, root); });return;}+ var modelImport = event.target.closest ? event.target.closest('[data-model-import]') : null;+ if (modelImport && !modelImport.disabled) {+ 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 }) })+ .then(function (data) {+ if (data && data.shared) {+ toast('两个客户端共用同一份模型配置,无需导入', false, root);+ } else {+ var imported = (data && data.imported || []).length;+ var skipped = (data && data.skipped || []).length;+ toast('已导入 ' + imported + ' 个模型' + (skipped ? ',跳过同名模型 ' + skipped + ' 个' : ''), false, root);+ }+ loadModels();+ })+ .catch(function (e) { toast('导入模型失败:' + (e.message || e), true, root); renderModels(); });+ return;+ }var modelTest = event.target.closest ? event.target.closest('[data-model-test]') : null;if (modelTest) {var testIndex = Number(modelTest.getAttribute('data-model-test'));@@ -2284,7 +2473,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {showModelConfirm('删除模型备份?', '删除后无法恢复,但不会影响官方 models.json。', function () {var backupIds = ids.map(function (id) { return id.slice('backup:'.length); });api('/api/models/delete', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ backupIds: backupIds }) })- .then(function () { toast('已删除 ' + backupIds.length + ' 个模型备份', false, root); modelsState.batch = false; modelsState.selected = {}; loadModels(); })+ .then(function (data) {+ var deleted = Number(data && data.deleted) || 0;+ var requested = Number(data && data.requested) || backupIds.length;+ toast('已删除 ' + deleted + ' 个模型备份' + (deleted < requested ? ',' + (requested - deleted) + ' 个已不存在' : ''), false, root);+ modelsState.batch = false; modelsState.selected = {}; loadModels();+ }).catch(function (e) { toast('删除模型备份失败:' + (e.message || e), true, root); });});}@@ -2345,13 +2539,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-pcard-title">主题外观</div>' +'<div class="wbs-theme-seg" id="wbs-theme-seg">' +'<button class="wbs-theme-opt active" type="button" data-theme="default">WorkBuddy 默认主题</button>' +- '<button class="wbs-theme-opt" type="button" data-theme="nebula">WorkDaddy 主题</button>' ++ '<button class="wbs-theme-opt" type="button" data-theme="nebula">' + WBS_BRAND + ' 主题</button>' +'</div>' +'</div>' +'<div class="wbs-pcard">' +'<div class="wbs-pcard-title">背景与头像</div>' +'<div class="wbs-bg-source">' +- '<button class="wbs-bg-src active" type="button" data-src="official">WorkDaddy 壁纸</button>' ++ '<button class="wbs-bg-src active" type="button" data-src="official">' + WBS_BRAND + ' 壁纸</button>' +'<button class="wbs-bg-src" type="button" data-src="custom">自定义壁纸</button>' +'</div>' +'<div class="wbs-bg-panel" data-src-panel="official">' +@@ -2415,7 +2609,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<button class="wbs-theme-devtools" id="wbs-theme-devtools" type="button" title="打开 Chrome DevTools(完整元素检查/控制台/网络调试)">打开 DevTools</button>' +'<button class="wbs-theme-inspect" id="wbs-theme-inspect" type="button" title="检查元素:点击页面任意组件,查看它的样式与颜色来源">元素检查</button>' +'</div>' +- '<div class="wbs-enh-tip">连续点击面板标题「WorkDaddy」5 次可隐藏/呼出本模块</div>' ++ '<div class="wbs-enh-tip">连续点击面板标题「' + WBS_BRAND + '」5 次可隐藏/呼出本模块</div>' +'</div>';wireEnhancePane();}@@ -2438,8 +2632,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-update-bar" id="wbs-update-bar" style="display:none;height:6px;border-radius:3px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 22%,transparent);overflow:hidden;margin-top:8px"><i id="wbs-update-bar-fill" style="display:block;height:100%;width:0;border-radius:3px;background:var(--wb-button-primary-bg,#1f1f1f);transition:width .6s ease"></i></div>' +'</div>' +'<div class="wbs-pcard wbs-about-hero">' +- '<div class="wbs-about-name" id="wbs-about-name">WorkDaddy</div>' +- '<div class="wbs-about-tag" id="wbs-about-tag">WorkBuddy 的多账号 · 主题 · 增强工具集</div>' ++ '<div class="wbs-about-name" id="wbs-about-name">' + WBS_BRAND + '</div>' ++ '<div class="wbs-about-tag" id="wbs-about-tag">' + (PROFILE_ID === 'workbuddy-ai' ? 'WorkBuddy AI 的多账号 · 主题 · 增强工具集' : 'WorkBuddy 的多账号 · 主题 · 增强工具集') + '</div>' +'<span class="wbs-about-badge" id="wbs-about-badge">本机回环 CDP 注入 · 不改官方安装包</span>' +'<div class="wbs-about-desc">一个基于 <b>Chrome DevTools Protocol (CDP)</b> 的 WorkBuddy 桌面端增强工具。零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。</div>' +'<div class="wbs-about-support">' +@@ -2542,12 +2736,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var bar = card ? card.querySelector('#wbs-update-bar') : null;var barFill = bar ? bar.querySelector('#wbs-update-bar-fill') : null;function renderRebootUi() {- var text = 'WorkDaddy 正在重启,更新即将完成,请稍候…';+ var text = WBS_BRAND + ' 正在重启,更新即将完成,请稍候…';var pct = 95;for (var i = 0; i < REBOOT_STEPS.length; i++) {if (rebootElapsed >= REBOOT_STEPS[i].t) { text = REBOOT_STEPS[i].text; pct = REBOOT_STEPS[i].pct; }}- if (rebootElapsed > 45000) { text = '启动较慢,请耐心等待…(也可双击桌面 WorkDaddy 图标手动启动)'; pct = 99; }+ if (rebootElapsed > 45000) { text = '启动较慢,请耐心等待…(也可双击桌面 ' + WBS_BRAND + ' 图标手动启动)'; pct = 99; }if (prog) prog.textContent = text;if (bar) bar.style.display = '';if (barFill) barFill.style.width = pct + '%';@@ -2630,7 +2824,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 不做 active 拦截:即使当前已是该主题也强制重新应用(保证「切换到默认主题=强制浅色 / 切换到 WorkDaddy 主题=强制深色」始终生效,面板状态与真实主题不一致时也能纠正)themePane.querySelectorAll('.wbs-theme-opt').forEach(function (b) { b.classList.toggle('active', b === segBtn); });applyTheme(id).then(function () {- toast('已应用主题「' + (id === 'default' ? 'WorkBuddy 默认主题' : 'WorkDaddy 主题') + '」', false, root);+ toast('已应用主题「' + (id === 'default' ? 'WorkBuddy 默认主题' : WBS_BRAND + ' 主题') + '」', false, root);}).catch(function (er) {toast('应用主题失败: ' + (er.message || er), true, root);});@@ -3773,7 +3967,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {dot.title = t;}var fab = root.querySelector('.wbs-fab');- if (fab) fab.setAttribute('title', 'WorkDaddy');+ if (fab) fab.setAttribute('title', WBS_BRAND);// until-done 模式:开启任务空闲检测;其他模式关闭if (d.mode === 'until-done') startUntilDoneCheck(); else stopUntilDoneCheck();}@@ -3924,10 +4118,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// token 过期状态:< 7 天 / 已过期 -> 红字高亮function tokenState(expiresAt, account) {- if (isIdentityExpired(account)) return { warn: true, expired: true, label: expiresAt ? fmtDateTime(expiresAt) : '-' };+ if (isIdentityExpired(account) && expiresAt) return { warn: true, expired: true, label: '已过期 ' + fmtDateTime(expiresAt) };if (!expiresAt) return { warn: false, label: '-' };var diff = expiresAt - Date.now();- if (diff < 0) return { warn: true, expired: true, label: fmtDateTime(expiresAt) };+ if (diff < 0) return { warn: true, expired: true, label: '已过期 ' + fmtDateTime(expiresAt) };if (diff < 24 * 3600 * 1000) return { warn: true, label: '即将过期 ' + fmtDateTime(expiresAt) };if (diff < 7 * 24 * 3600 * 1000) return { warn: true, label: fmtDateTime(expiresAt) };return { warn: false, label: fmtDateTime(expiresAt) };@@ -3960,12 +4154,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {(expired ? '' : '<button class="wbs-icon-btn wbs-acc-switch" type="button" title="切换" data-uid="' + a.uid + '" data-name="' + (a.nickname || '未命名') + '">' + SWITCH_SVG + '</button>') +'<button class="wbs-icon-btn wbs-del" type="button" title="删除" data-uid="' + a.uid + '" data-name="' + (a.nickname || '未命名') + '">' + TRASH_SVG + '</button>' +'</div>';+ // 国际版没有手机号:用 UIN(账号唯一数字标识)替代展示;国内版仍显示手机。+ // wbs-uin-cell 用于 UIN 模式下补齐标签与取值之间的间距(wbs-phone-cell 默认 gap:0 过于紧凑)。+ var isUinMode = !a.phone;+ var idLbl = a.phone ? '手机' : (a.uin ? 'UIN' : '账号');+ var idVal = a.phone ? esc(a.phone) : (a.uin ? esc(a.uin) : '-');card.innerHTML ='<div class="wbs-info">' +'<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + (a.nickname || '(未命名)') + '</span>' + badge + '</div>' + ops + '</div>' +'<div class="wbs-meta wbs-secondary-row">' +- '<div class="wbs-mi wbs-phone-cell"><span class="wbs-lbl">手机</span><span class="wbs-val">' + (a.phone || '-') + '</span></div>' +- '<div class="wbs-mi wbs-token-cell"><span class="wbs-lbl">登录过期于</span><span class="wbs-val' + (ts.warn ? ' wbs-warn' : '') + '">' + ts.label + '</span></div>' ++ '<div class="wbs-mi wbs-phone-cell' + (isUinMode ? ' wbs-uin-cell' : '') + '"><span class="wbs-lbl">' + idLbl + '</span><span class="wbs-val">' + idVal + '</span></div>' ++ '<div class="wbs-mi wbs-token-cell"><span class="wbs-lbl">有效期至</span><span class="wbs-val' + (ts.warn ? ' wbs-warn' : '') + '">' + ts.label + '</span></div>' +'</div>' +'<div class="wbs-credit-cell' + (isIdentityExpired(a) ? ' wbs-credit-hidden' : '') + '">' + creditBlockHtml(credits, a.creditSegments, a) + '</div>' +'</div>';@@ -4056,6 +4255,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function refresh() {+ if (!CAPS.accounts) {+ if (sessionsPane && !sessionsPane.dataset.built) buildSessionsPane();+ return;+ }stopCheckinPolling();state.creditRunId++;api('/api/accounts')@@ -4140,6 +4343,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {updateCheckinCells(data.accounts || []);if (data.checkin && data.checkin.running && state.open) {state.checkinPollId = setBuildTimeout(poll, 800);+ } else if (state.open) {+ // 签到请求完成后再查询积分,避免第一次打开面板显示签到前余额。+ fetchCreditsForAccounts();}}).catch(function () {@@ -4376,6 +4582,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {css.id = 'wbs-style';css.textContent = ['.wbs-root{position:fixed;right:22px;bottom:22px;z-index:2147483647;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;font-size:13px;color:#1f1f1f;-webkit-font-smoothing:antialiased}',+ '.wbs-root.wbs-no-stash .wbs-stash-inline{display:none !important}',/* 机器人悬浮按钮(bitter-dragon-16 移植):静态版 0.5 倍 · 无头顶尖角 · 眼睛双眨 */'.wbs-fab{position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:pointer}','.wbs-fab-sleep-dot{position:absolute;top:-4px;right:-4px;width:18px;height:18px;border-radius:50%;background:rgba(126,128,138,.55);border:2px solid #141416;box-shadow:0 1px 3px rgba(0,0,0,.5);transition:background .25s,box-shadow .25s;z-index:3}',@@ -4440,6 +4647,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-mi{display:flex;align-items:center;gap:6px;font-size:12px;line-height:1.4}','.wbs-phone-cell,.wbs-token-cell{flex:1;min-width:0}','.wbs-phone-cell{gap:0}',+ // UIN 模式(国际版无手机号时用 UIN 替代):标签与数字之间保留正常间距+ '.wbs-phone-cell.wbs-uin-cell{gap:8px}','.wbs-token-cell{justify-content:flex-end}','.wbs-phone-cell .wbs-lbl,.wbs-token-cell .wbs-lbl,.wbs-credit-label .wbs-lbl{width:auto}','.wbs-phone-cell .wbs-val,.wbs-token-cell .wbs-val{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',@@ -4560,6 +4769,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {/* 所见即所得定制器浮层 *//* 暂存提示词:position: fixed 用 right 锚定(left:auto),hover 时 width 增大 → 左边向左展开(参考 wbs-fab);默认隐藏,JS 控制 display */'.wbs-stash-inline{position:fixed;left:auto;display:flex;align-items:center;justify-content:flex-start;gap:0;width:32px;height:32px;border-radius:50%;background:var(--wb-button-primary-bg);cursor:pointer;flex-shrink:0;color:var(--wb-button-primary-fg);box-shadow:0 1px 3px rgba(0,0,0,.2);overflow:hidden;padding:0 8px;transition:width .18s,border-radius .18s,padding .15s,background .15s;z-index:auto;top:0;right:0}',+ // AI 端内联进操作栏按钮组(flex):取消 fixed 参与布局,保持与其他按钮一致的圆形+ '.wbs-stash-inline.wbs-stash-inline-inline{position:static;left:auto;right:auto;top:auto;border-radius:50%;box-shadow:none}',+ '.wbs-stash-inline.wbs-stash-inline-inline:hover{width:113px;border-radius:40px}','.wbs-stash-inline .wbs-stash-ico{display:flex;align-items:center;justify-content:center;flex-shrink:0}','.wbs-stash-inline .wbs-stash-ico svg{width:16px;height:16px;display:block}','.wbs-stash-inline .wbs-stash-txt{opacity:0;max-width:0;overflow:hidden;white-space:nowrap;font-size:13px;font-weight:500;margin-left:0;transition:opacity .2s,max-width .25s,margin-left .25s}',@@ -4632,6 +4844,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-model-tab-count{font-size:12px;opacity:.72;font-variant-numeric:tabular-nums}','.wbs-model-toolbar{display:flex;align-items:center;gap:6px;min-height:28px;margin-bottom:7px}','.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-count{font-size:13px;color:var(--wb-icon-tertiary,#888)}','.wbs-model-batchbar{display:flex;align-items:center;gap:6px;margin-bottom:7px;padding:6px 8px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 18%,transparent)}','.wbs-model-batch-count{font-size:11px;color:var(--wb-icon-tertiary,#999)}',diff --git a/scripts/install-win.ps1 b/scripts/install-win.ps1index 73c2640..f4c24c7 100644--- a/scripts/install-win.ps1+++ b/scripts/install-win.ps1@@ -1,13 +1,19 @@# WorkDaddy Windows 安装脚本(install.sh 的 Windows 对应物)# 用法:双击 install-win.cmd,或 powershell -ExecutionPolicy Bypass -File install-win.ps1-# 作用:复制到安装目录 → 初始化数据目录 → 注册登录自启(HKCU Run) → 启动 launcher(自动拉起 daemon + 以 CDP 模式重启 WorkBuddy)+# 作用:复制到安装目录 → 初始化数据目录 → 清理旧登录自启 → 启动 launcher(自动拉起 daemon + 以 CDP 模式重启 WorkBuddy)# 全程用户态,无需管理员权限。param([string]$SrcDir = $PSScriptRoot,- [string]$AppDir = (Join-Path $env:LOCALAPPDATA 'Programs\WorkDaddy')+ [string]$AppDir = '',+ [string]$Profile = '__WBS_DEFAULT_PROFILE__')$ErrorActionPreference = 'Continue'+if ([string]::IsNullOrWhiteSpace($Profile) -or $Profile -eq '__WBS_DEFAULT_PROFILE__') { $Profile = 'workbuddy-cn' }+if ($Profile -ne 'workbuddy-ai') { $Profile = 'workbuddy-cn' }+$env:WBSWITCH_PROFILE = $Profile+$productName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy AI' } else { 'WorkDaddy' }+if ([string]::IsNullOrWhiteSpace($AppDir)) { $AppDir = Join-Path $env:LOCALAPPDATA (Join-Path 'Programs' $productName) }$targetScripts = Join-Path $AppDir 'scripts'$sentryReporter = Join-Path $SrcDir 'sentry-report.js'$nodeBin = $null@@ -65,7 +71,7 @@ function Release-LockedLauncher {}Write-Host '=============================================================='-Write-Host ' WorkDaddy Windows 安装'+Write-Host (" " + $productName + " Windows 安装")Write-Host '=============================================================='Write-Host (" 源目录 : " + $SrcDir)Write-Host (" 安装目录 : " + $AppDir)@@ -99,8 +105,9 @@ if ([StringComparer]::OrdinalIgnoreCase.Equals($sourceFull, $targetFull)) {}}-# 2) 数据目录-$dataDir = Join-Path $env:APPDATA 'WorkDaddy'+# 2) profile 数据目录(与 profiles.js / watchdog.js 一致)+$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'+$dataDir = if ($Profile -eq 'workbuddy-ai') { Join-Path $dataRoot 'profiles\workbuddy-ai' } else { $dataRoot }New-Item -ItemType Directory -Force -Path (Join-Path $dataDir 'accounts') | Out-Null# 2.5) Logo 图标:随安装复制到安装目录根(桌面快捷方式用),源在 scripts 同级的 WorkDaddy.ico@@ -110,19 +117,22 @@ if (Test-Path $logoIcoSrc) {try { Copy-Item $logoIcoSrc $logoIco -Force; Write-Host (' 图标复制 : ' + $logoIco) } catch {}}-# 3) 登录自启(HKCU Run,登录时自动跑 launcher.cmd;崩溃自愈由 watchdog 负责)+# 3) 禁用登录自启:WorkDaddy / WorkDaddy AI 共存时由用户手动启动对应端。+# 同时清理旧版本可能留下的两个 Run 项;不要触碰其他应用的启动项。$runKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'-$launcher = Join-Path $targetScripts 'launcher.cmd'try {- Set-ItemProperty -Path $runKey -Name 'WorkDaddy' -Value ('"' + $launcher + '"')- Write-Host ' 自启注册:HKCU\...\Run\WorkDaddy = ' $launcher+ foreach ($runName in @('WorkDaddy', 'WorkDaddy AI')) {+ Remove-ItemProperty -Path $runKey -Name $runName -ErrorAction SilentlyContinue+ }+ Write-Host ' 自启:已禁用(已清理 WorkDaddy / WorkDaddy AI 登录启动项)'} catch {- Write-Host (' 自启注册失败(可忽略,之后手动双击 launcher.cmd 即可): ' + $_.Exception.Message)- Send-Sentry 'windows-install-autostart' ('注册登录自启失败: ' + $_.Exception.Message) 0+ Write-Host (' 自启清理失败(可忽略,之后手动双击 launcher.cmd 即可): ' + $_.Exception.Message)+ Send-Sentry 'windows-install-autostart-cleanup' ('清理登录自启失败: ' + $_.Exception.Message) 0}# 4) 启动(daemon + 以 CDP 模式重启 WorkBuddy + 注入)-Write-Host ' 正在启动 WorkDaddy(如果 WorkBuddy 正在运行,会重启它以开启调试模式)...'+$launcher = Join-Path $targetScripts 'launcher.cmd'+Write-Host (" 正在启动 " + $productName + "(如果 WorkBuddy 正在运行,会重启它以开启调试模式)...")$launcherVbs = Join-Path $targetScripts 'launcher-hidden.vbs'if (Test-Path $launcher) {if (Test-Path $launcherVbs) {@@ -134,12 +144,12 @@ if (Test-Path $launcher) {Write-Host ' 警告:launcher.cmd 不存在,跳过自动启动(请到安装目录手动双击)'}-# 5) 创建桌面快捷方式「WorkDaddy」+# 5) 创建桌面快捷方式(名称跟随安装包 profile)# 优先使用 wscript.exe 隐藏入口,避免 Windows Terminal 为管理员 cmd 创建空白窗口;# 缺少隐藏入口时回退到 cmd.exe,兼容旧包/手工安装目录。$desktopDir = [Environment]::GetFolderPath('Desktop')if (-not $desktopDir) { $desktopDir = Join-Path $env:USERPROFILE 'Desktop' }-$lnkPath = Join-Path $desktopDir 'WorkDaddy.lnk'+$lnkPath = Join-Path $desktopDir ($productName + '.lnk')# Logo 图标(macOS 版同款黑白的 WorkBuddy 机器人,打包时置于安装目录根)$logoIco = Join-Path $AppDir 'WorkDaddy.ico'try {@@ -153,7 +163,7 @@ try {$sc.Arguments = '/d /c call "' + $launcher + '"'}$sc.WorkingDirectory = (Split-Path $launcher)- $sc.Description = 'WorkDaddy – WorkBuddy 增强工具(请以管理员身份运行)'+ $sc.Description = ($productName + ' – WorkBuddy 增强工具(请以管理员身份运行)') # 描述跟随安装包 profile(WorkDaddy / WorkDaddy AI)if (Test-Path $logoIco) { $sc.IconLocation = $logoIco + ',0' } # 用官方 logo,而非 cmd 默认图标$sc.Save()Write-Host (' 桌面快捷方式 : ' + $lnkPath)@@ -165,6 +175,7 @@ try {Write-Host '=============================================================='Write-Host ' 安装完成!'+Write-Host (' profile : ' + $Profile)Write-Host (" 安装目录 : " + $AppDir)Write-Host (" 数据目录 : " + $dataDir)Write-Host (' 备份账号 : ' + (Join-Path $dataDir 'accounts'))diff --git a/scripts/install.sh b/scripts/install.shindex 2b4b4c8..8f3d030 100644--- a/scripts/install.sh+++ b/scripts/install.sh@@ -1,23 +1,30 @@#!/usr/bin/env bash# 安装 WorkBuddy 多账号切换器(CDP 版)# 1) 创建备份目录并首次同步当前账号-# 2) 注册 launchd 常驻守护进程(登录自启 + 崩溃自动拉起)+# 2) 清理旧 launchd 注册并手动启动守护进程(不再登录自启)# 用法: bash scripts/install.shset -euo pipefailDIR="$(cd "$(dirname "$0")/.." && pwd)"-LABEL="com.workbuddy.workdaddy"+PROFILE="${WBSWITCH_PROFILE:-workbuddy-cn}"+case "$PROFILE" in+ workbuddy-ai) DEFAULT_DATA_DIR="$HOME/Library/Application Support/WorkDaddy/profiles/workbuddy-ai"; DEFAULT_UI_PORT=47833 ;;+ codebuddy-cn) DEFAULT_DATA_DIR="$HOME/Library/Application Support/WorkDaddy/profiles/codebuddy-cn"; DEFAULT_UI_PORT=47834 ;;+ codebuddy-intl) DEFAULT_DATA_DIR="$HOME/Library/Application Support/WorkDaddy/profiles/codebuddy-intl"; DEFAULT_UI_PORT=47835 ;;+ *) PROFILE="workbuddy-cn"; DEFAULT_DATA_DIR="$HOME/Library/Application Support/WorkDaddy"; DEFAULT_UI_PORT=47832 ;;+esac+export WBSWITCH_PROFILE="$PROFILE"+LABEL="com.workbuddy.workdaddy.${PROFILE}"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"LEGACY_DATA_DIR="$HOME/Library/Application Support/HelloBuddy"if [ "${WBSWITCH_DATA_DIR:-}" = "$LEGACY_DATA_DIR" ]; thenDATA_DIR="$DEFAULT_DATA_DIR"elseDATA_DIR="${WBSWITCH_DATA_DIR:-$DEFAULT_DATA_DIR}"fi-UI_PORT="${WBSWITCH_PORT:-47832}"+UI_PORT="${WBSWITCH_PORT:-$DEFAULT_UI_PORT}"CDP_PORT="${WBSWITCH_CDP_PORT:-}"# 找一个可用的 node(优先 managed,其次 PATH)@@ -57,7 +64,29 @@ echo "==> 停止旧版 HelloBuddy 守护进程(保留旧备份,首次同步launchctl bootout "gui/$(id -u)" "$LEGACY_PLIST" 2>/dev/null || truelaunchctl remove "$LEGACY_LABEL" 2>/dev/null || truerm -f "$LEGACY_PLIST"-pkill -f "$DIR/scripts/daemon.js" 2>/dev/null || true+# 仅停止当前 profile 的旧 daemon,避免安装 WorkDaddy AI 时误杀另一个端。+if [ -f "$DATA_DIR/.daemon.lock" ]; then+ OLD_PID=$("$NODE" -e "try { const fs=require('fs'); const j=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); process.stdout.write(String(j.pid || '')); } catch (_) {}" "$DATA_DIR/.daemon.lock")+ if [ -n "$OLD_PID" ] && kill -0 "$OLD_PID" 2>/dev/null; then+ kill "$OLD_PID" 2>/dev/null || true+ for _ in $(seq 1 10); do+ kill -0 "$OLD_PID" 2>/dev/null || break+ sleep 0.2+ done+ fi+fi++# 迁移旧版「未绑定 profile」守护进程(com.workbuddy.workdaddy,未设置 WBSWITCH_PROFILE)。+# 旧版 daemon 会扫描 9222-9232 全部 CDP 端口,仅凭标题 "WorkBuddy" 判定注入目标,+# 会误连兄弟客户端(如 WorkBuddy AI)页面并反复清理对方组件,导致按钮消失。+# 新安装统一使用带 profile 后缀的 label(com.workbuddy.workdaddy.<profile>),+# 此处卸载并移除旧 plist,仅当安装的是它代表的 workbuddy-cn 时才做(其他 profile 由各自安装清理)。+if [ "$PROFILE" = "workbuddy-cn" ] && [ -f "$HOME/Library/LaunchAgents/com.workbuddy.workdaddy.plist" ]; then+ echo "==> 迁移旧版未绑定 profile 守护进程 com.workbuddy.workdaddy(新版本已按客户端拆分绑定)"+ launchctl bootout "gui/$(id -u)" "$HOME/Library/LaunchAgents/com.workbuddy.workdaddy.plist" 2>/dev/null || true+ launchctl remove "com.workbuddy.workdaddy" 2>/dev/null || true+ rm -f "$HOME/Library/LaunchAgents/com.workbuddy.workdaddy.plist"+fiecho "==> 首次同步当前登录账号"if ! "$NODE" "$DIR/scripts/sync.js"; then@@ -65,54 +94,20 @@ if ! "$NODE" "$DIR/scripts/sync.js"; thenecho " (首次同步失败,守护进程启动后会自动重试)"fi-echo "==> 注册 launchd 守护进程: $LABEL"-mkdir -p "$HOME/Library/LaunchAgents"-cat > "$PLIST" <<PLISTEOF-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>Label</key><string>${LABEL}</string>- <key>ProgramArguments</key>- <array>- <string>${NODE}</string>- <string>${DIR}/scripts/daemon.js</string>- </array>- <key>RunAtLoad</key><true/>- <key>KeepAlive</key><true/>- <key>StandardOutPath</key><string>${DATA_DIR}/daemon.log</string>- <key>StandardErrorPath</key><string>${DATA_DIR}/daemon.log</string>- <key>EnvironmentVariables</key>- <dict>- <key>WBSWITCH_DATA_DIR</key><string>${DATA_DIR}</string>- <key>WBSWITCH_PORT</key><string>${UI_PORT}</string>-PLISTEOF-if [ -n "$CDP_PORT" ]; then- cat >> "$PLIST" <<PLISTEOF- <key>WBSWITCH_CDP_PORT</key><string>${CDP_PORT}</string>-PLISTEOF-fi-cat >> "$PLIST" <<'PLISTEOF'- </dict>-</dict>-</plist>-PLISTEOF-+echo "==> 清理旧 launchd 注册(WorkDaddy / WorkDaddy AI 不再登录自启)"+for old_profile in workbuddy-cn workbuddy-ai codebuddy-cn codebuddy-intl; do+ old_label="com.workbuddy.workdaddy.${old_profile}"+ old_plist="$HOME/Library/LaunchAgents/${old_label}.plist"+ launchctl bootout "gui/$(id -u)" "$old_plist" 2>/dev/null || true+ launchctl remove "$old_label" 2>/dev/null || true+ rm -f "$old_plist"+donelaunchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true-LAUNCHD_OK=1-if ! launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/tmp/wbswitch-launchctl.err; then- LAUNCHD_OK=0- echo " ⚠️ launchd 注册失败(若你是从 WorkBuddy 应用内执行的安装,这是正常现象)。"- echo " 手动在【终端】中执行以下命令即可注册开机自启:"- echo " launchctl bootstrap gui/\$(id -u) \"$PLIST\""-fi-if [ "$LAUNCHD_OK" = "1" ]; then- sleep 1- launchctl kickstart -k "gui/$(id -u)/${LABEL}" 2>/dev/null || true-fi+launchctl remove "$LABEL" 2>/dev/null || true+rm -f "$PLIST"echo "==> 启动守护进程(后台)"-WBSWITCH_DATA_DIR="$DATA_DIR" nohup "$NODE" "$DIR/scripts/daemon.js" >> "$DATA_DIR/daemon.log" 2>&1 &+WBSWITCH_PROFILE="$PROFILE" WBSWITCH_DATA_DIR="$DATA_DIR" WBSWITCH_PORT="$UI_PORT" nohup "$NODE" "$DIR/scripts/daemon.js" >> "$DATA_DIR/daemon.log" 2>&1 &disown 2>/dev/null || trueecho " pid: $!"@@ -129,11 +124,7 @@ echo "✅ 安装完成!"echo " Web 界面 : http://127.0.0.1:${UI_PORT}"echo " 备份目录 : ${DATA_DIR}"echo " CDP 端口 : ${CDP_PORT:-自动选择 (9222-9232/9333,端口占用会自动切换)}"-if [ "$LAUNCHD_OK" = "1" ]; then- echo " 开机自启 : launchd 已注册 ✅"-else- echo " 开机自启 : 未注册 ⚠️(在终端执行 launchctl bootstrap 注册,见上方命令)"-fi+echo " 开机自启 : 已禁用(需要时手动启动对应 WorkDaddy 端)"echo ""echo "下一步:让 CDP 生效(可选但推荐)"echo " bash \"$DIR/scripts/relaunch-with-cdp.sh\""diff --git a/scripts/lib.js b/scripts/lib.jsindex 13ff596..f78e1e2 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -16,6 +16,7 @@ const fs = require('fs');const os = require('os');const path = require('path');const crypto = require('crypto');+const { getProfile, profileDataDir, sharedDataDir } = require('./profiles.js');const IS_WIN = process.platform === 'win32';@@ -39,9 +40,10 @@ function isLegacyDataDir(dataDir) {// macOS: ~/Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info// Windows: %LOCALAPPDATA%\CodeBuddyExtension\Data\Public\auth\workbuddy-desktop.info(真机已确认)-const AUTH_FILE =- process.env.WBSWITCH_AUTH_FILE ||- (IS_WIN+const ACTIVE_PROFILE = getProfile();+const AUTH_FILE = process.env.WBSWITCH_AUTH_FILE !== undefined+ ? process.env.WBSWITCH_AUTH_FILE+ : (ACTIVE_PROFILE.authFile === null ? null : (ACTIVE_PROFILE.authFile || (IS_WIN? path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'),'CodeBuddyExtension',@@ -53,7 +55,7 @@ const AUTH_FILE =: path.join(os.homedir(),'Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info'- ));+ ))));const LOGOUT_MARKER = `${AUTH_FILE}.logged-out`;@@ -61,7 +63,7 @@ function defaultDataDir() {// 旧版 launchd 可能把 WBSWITCH_DATA_DIR 设成 HelloBuddy;新版本始终落到 WorkDaddy,// 避免旧服务被新 daemon 拉起后继续写入旧目录。const configured = process.env.WBSWITCH_DATA_DIR;- return configured && !isLegacyDataDir(configured) ? configured : PLATFORM_DATA_DIR;+ return configured && !isLegacyDataDir(configured) ? configured : profileDataDir(ACTIVE_PROFILE);}function accountsDir(dataDir) {@@ -72,10 +74,47 @@ function metaFile(dataDir) {}function workbuddyModelsFile() {- return path.join(os.homedir(), '.workbuddy', 'models.json');+ return ACTIVE_PROFILE.modelsFile || path.join(os.homedir(), '.workbuddy', 'models.json');+}++function isManagedProfileDataDir(dataDir) {+ const root = path.resolve(sharedDataDir());+ const current = path.resolve(dataDir || '');+ return current === root || current.startsWith(root + path.sep + 'profiles' + path.sep);+}++function migrateLegacyModelBackups(dataDir) {+ if (!isManagedProfileDataDir(dataDir)) return;+ const root = sharedDataDir();+ const target = path.join(root, 'models');+ const marker = path.join(target, '.legacy-migrated-v1');+ fs.mkdirSync(target, { recursive: true, mode: 0o700 });+ // 迁移只允许发生一次。旧 profile 目录保留作兼容/恢复,但不能在用户删除+ // 共享备份后再次把同一个文件复制回来。+ if (fs.existsSync(marker)) return;+ let profileDirs = [];+ try { profileDirs = fs.readdirSync(path.join(root, 'profiles'), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path.join(root, 'profiles', entry.name, 'models')); } catch (_) {}+ for (const source of profileDirs) {+ let names = [];+ try { names = fs.readdirSync(source).filter((name) => /^[A-Za-z0-9_-]{8,100}\.json$/.test(name)); } catch (_) { continue; }+ for (const name of names) {+ const from = path.join(source, name);+ const to = path.join(target, name);+ if (fs.existsSync(to)) continue;+ try { fs.copyFileSync(from, to); fs.chmodSync(to, 0o600); } catch (_) {}+ }+ }+ try {+ fs.writeFileSync(marker, JSON.stringify({ version: 1, migratedAt: new Date().toISOString(), deleted: [] }) + '\n', { mode: 0o600 });+ fs.chmodSync(marker, 0o600);+ } catch (_) {}}function modelBackupsDir(dataDir) {+ if (isManagedProfileDataDir(dataDir)) {+ migrateLegacyModelBackups(dataDir);+ return path.join(sharedDataDir(), 'models');+ }return path.join(dataDir, 'models');}@@ -105,8 +144,15 @@ function sanitizeModel(model, opts) {};}+function checkinDisplayValue(record, today, pending) {+ if (pending || !record || record.date !== today) return null;+ return { ok: !!record.ok, already: !!record.already, code: record.code, message: record.message };+}+function readModelsFile(file = workbuddyModelsFile()) {- if (!fs.existsSync(file)) throw new Error(`未找到模型配置文件: ${file}`);+ // 文件不存在视为"还没有模型",返回空列表而不是抛错——模型页应显示+ // "当前还未添加模型"占位,而不是"当前模型加载失败: 未找到模型配置文件"。+ if (!fs.existsSync(file)) return { file, format: 'array', models: [] };let parsed;try {parsed = JSON.parse(fs.readFileSync(file, 'utf8'));@@ -256,10 +302,21 @@ function editModelBackup(dataDir, backupId, patch) {function deleteModelBackups(dataDir, backupIds) {const ids = Array.isArray(backupIds) ? backupIds : [];let deleted = 0;+ const removed = [];for (const id of ids) {try {const file = modelBackupPath(dataDir, id);- if (fs.existsSync(file)) { fs.unlinkSync(file); deleted++; }+ if (fs.existsSync(file)) { fs.unlinkSync(file); deleted++; removed.push(String(id)); }+ } catch (_) {}+ }+ if (removed.length && isManagedProfileDataDir(dataDir)) {+ const marker = path.join(sharedDataDir(), 'models', '.legacy-migrated-v1');+ try {+ const state = JSON.parse(fs.readFileSync(marker, 'utf8'));+ const deletedIds = new Set(Array.isArray(state.deleted) ? state.deleted : []);+ removed.forEach((id) => deletedIds.add(id));+ fs.writeFileSync(marker, JSON.stringify(Object.assign({}, state, { deleted: Array.from(deletedIds) })) + '\n', { mode: 0o600 });+ fs.chmodSync(marker, 0o600);} catch (_) {}}return deleted;@@ -285,6 +342,29 @@ function enableModelBackup(dataDir, backupId, file = workbuddyModelsFile()) {return { backupId, id: modelId, replaced: first >= 0, ...sanitizeModel(record.model) };}+function modelImportName(model) {+ return String(model && (model.name || model.id) || '').trim();+}++function importModels(targetFile, sourceFile) {+ const target = readModelsFile(targetFile);+ const source = readModelsFile(sourceFile);+ if (path.resolve(target.file) === path.resolve(source.file)) throw new Error('不能从当前客户端导入模型');+ const existing = new Set(target.models.map(modelImportName).filter(Boolean));+ const imported = [];+ const skipped = [];+ for (const model of source.models) {+ if (!model || typeof model !== 'object' || Array.isArray(model)) continue;+ const name = modelImportName(model);+ if (!name || existing.has(name)) { if (name) skipped.push(name); continue; }+ target.models.push(model);+ existing.add(name);+ imported.push(name);+ }+ if (imported.length) writeModelsFile(target, target.models);+ return { imported, skipped, official: target.models.map((model, index) => Object.assign({ index }, sanitizeModel(model, { revealKey: true }))) };+}+function readMeta(dataDir) {let meta = { accounts: {} };try {@@ -704,6 +784,9 @@ function ensureDirs(dataDir, log = () => {}) {/** 读取登录信息文件并抽取账号关键字段(不返回令牌内容) */function readAuthFile() {+ if (!ACTIVE_PROFILE.authFile && !process.env.WBSWITCH_AUTH_FILE) {+ throw new Error(`${ACTIVE_PROFILE.name} 没有可读取的明文认证文件`);+ }const raw = fs.readFileSync(AUTH_FILE, 'utf8');const json = JSON.parse(raw);if (!json || typeof json !== 'object') {@@ -742,6 +825,7 @@ function updateMeta(dataDir, info) {/** 把当前登录信息备份到 accounts/<uid>.info(原子写入,0600) */function backupCurrent(dataDir, log = () => {}) {+ if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号文件备份`);ensureDirs(dataDir, log);const info = readAuthFile();const dest = backupPath(dataDir, info.uid);@@ -758,6 +842,7 @@ function backupCurrent(dataDir, log = () => {}) {/** 列出所有已备份账号(直接读备份文件提取展示字段,按最近刷新时间倒序) */function listAccounts(dataDir) {+ if (!ACTIVE_PROFILE.capabilities.accounts) return [];migrateLegacyDataDir(dataDir);const dir = accountsDir(dataDir);let names = [];@@ -805,6 +890,7 @@ function listAccounts(dataDir) {/** 永久删除某个账号的备份文件(不影响当前登录) */function deleteAccount(dataDir, uid) {+ if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号切换`);migrateLegacyDataDir(dataDir);const file = backupPath(dataDir, uid);let deletedFile = false;@@ -827,6 +913,7 @@ function deleteAccount(dataDir, uid) {/** 切换登录账号:把备份文件复制回登录信息文件(先校验 uid 匹配) */function switchTo(dataDir, uid, log = () => {}) {+ if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号切换`);migrateLegacyDataDir(dataDir, log);const src = backupPath(dataDir, uid);if (!fs.existsSync(src)) {@@ -877,6 +964,7 @@ function switchTo(dataDir, uid, log = () => {}) {module.exports = {AUTH_FILE,+ ACTIVE_PROFILE,defaultDataDir,migrateLegacyDataDir,accountsDir,@@ -885,6 +973,7 @@ module.exports = {modelBackupsDir,maskApiKey,sanitizeModel,+ checkinDisplayValue,listOfficialModels,readOfficialModel,readModelBackup,@@ -895,6 +984,7 @@ module.exports = {editModelBackup,deleteModelBackups,enableModelBackup,+ importModels,logFile,backupPath,retireLogoutMarker,diff --git a/scripts/profiles.js b/scripts/profiles.jsnew file mode 100644index 0000000..de4801d--- /dev/null+++ b/scripts/profiles.js@@ -0,0 +1,117 @@+'use strict';++const fs = require('fs');+const os = require('os');+const path = require('path');++const home = os.homedir();+const IS_WIN = process.platform === 'win32';+const appSupport = IS_WIN+ ? (process.env.APPDATA || path.join(home, 'AppData', 'Roaming'))+ : path.join(home, 'Library', 'Application Support');+const localSupport = IS_WIN+ ? (process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'))+ : appSupport;+const extensionAuth = path.join(localSupport, 'CodeBuddyExtension', 'Data', 'Public', 'auth');+// Windows 可执行名与安装目录名不完全一致(AI 国际版 exe 为 WorkBuddyAI.exe,无空格;+// win-launcher 进程枚举与 PR#8 实机已确认)。winExec 缺省时用安装目录同名 .exe,找不到时+// win-launcher 仍有进程/注册表兜底。+const appPath = (name, winExec, winDir) =>+ IS_WIN+ ? path.join(localSupport, 'Programs', winDir || name, winExec || `${winDir || name}.exe`)+ : `/Applications/${name}.app`;++function sharedDataDir() {+ return path.join(appSupport, 'WorkDaddy');+}++const PROFILES = {+ 'workbuddy-cn': {+ id: 'workbuddy-cn', name: 'WorkBuddy', appName: 'WorkDaddy', region: 'cn', kind: 'workbuddy', mode: 'agents',+ appPath: appPath('WorkBuddy'),+ dataRoot: path.join(home, '.workbuddy'),+ authFile: path.join(extensionAuth, 'workbuddy-desktop.info'),+ sessionDb: path.join(home, '.workbuddy', 'workbuddy.db'),+ modelsFile: path.join(home, '.workbuddy', 'models.json'),+ // billing/积分/签到/无感登录 API host(与 auth.domain 一致;国际版为 www.workbuddy.ai)+ apiHost: 'https://www.codebuddy.cn',+ capabilities: { accounts: true, sessions: true, models: true, stashPrompt: true, theme: true, checkin: true },+ targetHints: ['workbuddy'],+ },+ 'workbuddy-ai': {+ id: 'workbuddy-ai', name: 'WorkBuddy AI', appName: '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'),+ authFile: path.join(extensionAuth, 'workbuddy-desktop-ai.info'),+ sessionDb: path.join(home, '.workbuddy-ai', 'workbuddy.db'),+ // 模型配置文件:国际版用 ~/.workbuddy-ai/models.json,国内版用 ~/.workbuddy/models.json,+ // 两者独立(勿改共用)。“从 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 },+ 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,+ sessionDb: path.join(appSupport, 'CodeBuddy CN', 'codebuddy-sessions.vscdb'),+ modelsFile: path.join(appSupport, 'CodeBuddy CN', 'User', 'globalStorage', 'state.vscdb'),+ apiHost: 'https://www.codebuddy.cn',+ capabilities: { accounts: false, sessions: true, models: false, stashPrompt: false, theme: false, checkin: true },+ targetHints: ['codebuddy cn'],+ },+ 'codebuddy-intl': {+ id: 'codebuddy-intl', name: 'CodeBuddy', region: 'intl', kind: 'codebuddy', mode: 'auto',+ appPath: appPath('CodeBuddy'),+ dataRoot: path.join(appSupport, 'CodeBuddy'),+ authFile: null,+ sessionDb: path.join(appSupport, 'CodeBuddy', 'codebuddy-sessions.vscdb'),+ modelsFile: path.join(appSupport, 'CodeBuddy', 'User', 'globalStorage', 'state.vscdb'),+ apiHost: 'https://www.codebuddy.ai',+ capabilities: { accounts: false, sessions: true, models: false, stashPrompt: false, theme: false, checkin: true },+ targetHints: ['codebuddy'],+ },+};++function getProfile(id = process.env.WBSWITCH_PROFILE || 'workbuddy-cn') {+ const key = String(id || '').trim().toLowerCase();+ if (PROFILES[key]) return PROFILES[key];+ throw new Error(`未知客户端 profile: ${id}`);+}++function listProfiles() { return Object.values(PROFILES).map((p) => ({ ...p, capabilities: { ...p.capabilities }, targetHints: [...p.targetHints] })); }++function listInstalledModelSources(activeId) {+ const active = PROFILES[activeId];+ return ['workbuddy-cn', 'workbuddy-ai']+ .filter((id) => id !== activeId)+ .map((id) => PROFILES[id])+ .map((profile) => {+ const installed = fs.existsSync(profile.appPath);+ const available = fs.existsSync(profile.modelsFile);+ // 防御:仅当两端模型文件实际指向同一路径时才视为共享(正常情况+ // CN/AI 各用各的 models.json,可互相导入;若未来某端路径缺失需容错)+ const shared = !!(active && active.modelsFile && profile.modelsFile &&+ path.resolve(active.modelsFile) === path.resolve(profile.modelsFile));+ return {+ profileId: profile.id,+ name: profile.name,+ modelsFile: profile.modelsFile,+ installed,+ available,+ shared,+ };+ })+ .filter((source) => source.installed || source.available || source.shared);+}++function profileDataDir(profile, configured) {+ if (configured) return configured;+ if (profile.id === 'workbuddy-cn') return sharedDataDir();+ return path.join(sharedDataDir(), 'profiles', profile.id);+}++module.exports = { PROFILES, getProfile, listProfiles, listInstalledModelSources, profileDataDir, sharedDataDir };diff --git a/scripts/relaunch-with-cdp.sh b/scripts/relaunch-with-cdp.shindex 420ae1b..444932f 100644--- a/scripts/relaunch-with-cdp.sh+++ b/scripts/relaunch-with-cdp.sh@@ -1,6 +1,6 @@#!/usr/bin/env bash-# 一键修复/启用 CDP 模式:-# 1) 把守护进程注册到 launchd(独立于 WorkBuddy 存活,重启应用/重启电脑都不影响)+# 一键修复/启用 CDP 模式(仅手动启动 daemon,不注册登录自启):+# 1) 清理旧的 launchd 注册并手动启动守护进程# 2) 彻底退出 WorkBuddy(注意:其进程名是 Electron,不能按 "WorkBuddy" 杀)# 3) 带 --remote-debugging-port 直接执行应用二进制启动(保证参数生效)# 4) 验证 CDP 端口开放@@ -15,19 +15,27 @@ set -uo pipefailPORT="${WBSWITCH_CDP_PORT:-${1:-}}"DIR="$(cd "$(dirname "$0")/.." && pwd)"-LABEL="com.workbuddy.workdaddy"+PROFILE="${WBSWITCH_PROFILE:-workbuddy-cn}"+case "$PROFILE" in+ workbuddy-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="" ;;+ codebuddy-intl) APP_NAME="CodeBuddy"; APP_BIN="/Applications/CodeBuddy.app/Contents/MacOS/Electron"; DEFAULT_DATA_DIR="$HOME/Library/Application Support/WorkDaddy/profiles/codebuddy-intl"; DEFAULT_UI_PORT=47835; DEFAULT_CDP_PORT=9225; AUTH_DEFAULT="" ;;+ *) PROFILE="workbuddy-cn"; APP_NAME="WorkBuddy"; APP_BIN="/Applications/WorkBuddy.app/Contents/MacOS/Electron"; DEFAULT_DATA_DIR="$HOME/Library/Application Support/WorkDaddy"; DEFAULT_UI_PORT=47832; DEFAULT_CDP_PORT=9222; AUTH_DEFAULT="$HOME/Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info" ;;+esac+export WBSWITCH_PROFILE="$PROFILE"+if [ -z "$PORT" ]; then PORT="$DEFAULT_CDP_PORT"; fi+LABEL="com.workbuddy.workdaddy.${PROFILE}"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"LEGACY_DATA_DIR="$HOME/Library/Application Support/HelloBuddy"if [ "${WBSWITCH_DATA_DIR:-}" = "$LEGACY_DATA_DIR" ]; thenDATA_DIR="$DEFAULT_DATA_DIR"elseDATA_DIR="${WBSWITCH_DATA_DIR:-$DEFAULT_DATA_DIR}"fi-AUTH_FILE="${WBSWITCH_AUTH_FILE:-$HOME/Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info}"-APP_BIN="/Applications/WorkBuddy.app/Contents/MacOS/Electron"+UI_PORT="${WBSWITCH_PORT:-$DEFAULT_UI_PORT}"+AUTH_FILE="${WBSWITCH_AUTH_FILE:-$AUTH_DEFAULT}"CDP_PORT_FILE="$DATA_DIR/cdp-port.json"# 统一使用的 node 路径(优先系统 PATH,兜底用 managed runtime)@@ -72,7 +80,14 @@ resolve_cdp_port() {}resolve_cdp_port-# 清理旧版常驻服务,但保留 HelloBuddy 数据目录;新 daemon 会在启动时迁移旧账号。+# 清理旧版常驻服务和旧 profile 自启项,但保留账号数据;daemon 仅由本次手动执行启动。+for old_profile in workbuddy-cn workbuddy-ai codebuddy-cn codebuddy-intl; do+ old_label="com.workbuddy.workdaddy.${old_profile}"+ old_plist="$HOME/Library/LaunchAgents/${old_label}.plist"+ launchctl bootout "gui/$(id -u)" "$old_plist" 2>/dev/null || true+ launchctl remove "$old_label" 2>/dev/null || true+ rm -f "$old_plist"+donelaunchctl bootout "gui/$(id -u)" "$LEGACY_PLIST" 2>/dev/null || truelaunchctl remove "$LEGACY_LABEL" 2>/dev/null || truerm -f "$LEGACY_PLIST"@@ -151,40 +166,32 @@ launch_plugin() {*) echo "已取消"; exit 0 ;;esac- # ---------- 1. 注册 launchd 守护进程(若尚未注册) ----------- if [ -f "$PLIST" ] && ! launchctl print "gui/$(id -u)/${LABEL}" >/dev/null 2>&1; then- echo "==> 注册 launchd 守护进程(使后台服务独立于 WorkBuddy 存活)"- # 先停掉可能存在的临时守护进程,避免双实例抢端口- pkill -f "scripts/daemon.js" 2>/dev/null || true- sleep 1- if launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null; then- echo " launchd 注册成功"- else- echo " 警告:launchd 注册失败,改用 nohup 方式启动守护进程(重启电脑后需重新执行本脚本)"- mkdir -p "$DATA_DIR/accounts"- WBSWITCH_DATA_DIR="$DATA_DIR" nohup "$NODE_BIN" "$DIR/scripts/daemon.js" >> "$DATA_DIR/daemon.log" 2>&1 &- disown 2>/dev/null || true- fi+ # ---------- 1. 手动启动 daemon(不注册 launchd,避免多个 profile 登录自启) ----------+ if ! curl -s -m 1 "http://127.0.0.1:${UI_PORT}/api/status" >/dev/null 2>&1; then+ echo "==> 手动启动 WorkDaddy 守护进程"+ mkdir -p "$DATA_DIR/accounts"+ WBSWITCH_PROFILE="$PROFILE" WBSWITCH_DATA_DIR="$DATA_DIR" WBSWITCH_PORT="$UI_PORT" nohup "$NODE_BIN" "$DIR/scripts/daemon.js" >> "$DATA_DIR/daemon.log" 2>&1 &+ disown 2>/dev/null || trueelse- echo "==> launchd 守护进程已注册,跳过"+ echo "==> WorkDaddy 守护进程已运行,跳过启动"fi# 等待守护进程就绪for i in $(seq 1 10); do- curl -s -m 1 "http://127.0.0.1:${PORT:-47832}/api/status" >/dev/null 2>&1 && { echo "==> 守护进程运行中"; break; }+ curl -s -m 1 "http://127.0.0.1:${UI_PORT}/api/status" >/dev/null 2>&1 && { echo "==> 守护进程运行中"; break; }sleep 1done# ---------- 2. 彻底退出 WorkBuddy ----------echo "==> 退出 WorkBuddy ..."- osascript -e 'quit app "WorkBuddy"' 2>/dev/null || true+ osascript -e "quit app \"${APP_NAME}\"" 2>/dev/null || truesleep 3# 兜底:按真实进程路径精确清理(进程名是 Electron,切勿 killall Electron 以免误伤其他应用)- pkill -f "/Applications/WorkBuddy.app/Contents/MacOS/Electron" 2>/dev/null || true+ pkill -f "$APP_BIN" 2>/dev/null || truesleep 2- if pgrep -f "/Applications/WorkBuddy.app/Contents/MacOS/Electron" >/dev/null 2>&1; then+ if pgrep -f "$APP_BIN" >/dev/null 2>&1; thenecho " 警告:WorkBuddy 仍在运行,强制结束"- pkill -9 -f "/Applications/WorkBuddy.app/Contents/MacOS/Electron" 2>/dev/null || true+ pkill -9 -f "$APP_BIN" 2>/dev/null || truesleep 2fidiff --git a/scripts/sentry-report.js b/scripts/sentry-report.jsindex e825fad..116ff1e 100644--- a/scripts/sentry-report.js+++ b/scripts/sentry-report.js@@ -16,9 +16,18 @@ const DEFAULT_DSN = 'https://6cc1bae83102c222717df3b6e74ae9d4@o4511947624939520.const CLIENT = 'workdaddy-sentry/1';const HOME = os.homedir();const IS_WIN = process.platform === 'win32';-const DATA_DIR = process.env.WBSWITCH_DATA_DIR || (IS_WIN+const PROFILE_ID = String(process.env.WBSWITCH_PROFILE || 'workbuddy-cn').trim().toLowerCase();+const CLIENT_VARIANT = PROFILE_ID === 'workbuddy-ai' ? 'workbuddy-ai'+ : PROFILE_ID === 'codebuddy-cn' ? 'codebuddy-cn'+ : PROFILE_ID === 'codebuddy-intl' ? 'codebuddy-intl' : 'workbuddy';+const CLIENT_NAME = CLIENT_VARIANT === 'workbuddy-ai' ? 'WorkBuddy AI'+ : CLIENT_VARIANT === 'codebuddy-cn' ? 'CodeBuddy CN'+ : CLIENT_VARIANT === 'codebuddy-intl' ? 'CodeBuddy' : 'WorkBuddy';+const SHARED_DATA_DIR = IS_WIN? path.join(process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming'), 'WorkDaddy')- : path.join(HOME, 'Library', 'Application Support', 'WorkDaddy'));+ : path.join(HOME, 'Library', 'Application Support', 'WorkDaddy');+const DATA_DIR = process.env.WBSWITCH_DATA_DIR || (PROFILE_ID === 'workbuddy-cn'+ ? SHARED_DATA_DIR : path.join(SHARED_DATA_DIR, 'profiles', PROFILE_ID));const OUTBOX_DIR = path.join(DATA_DIR, 'telemetry', 'outbox');const MAX_OUTBOX_FILES = 50;const MAX_FLUSH_FILES = 1;@@ -153,6 +162,9 @@ function makeEvent({ stage, message, level = 'error', tags = {}, extra = {}, exctags: sanitize({source: 'workdaddy',stage: stage || 'unknown',+ client: CLIENT_VARIANT,+ client_name: CLIENT_NAME,+ workbuddy_variant: CLIENT_VARIANT === 'workbuddy-ai' ? 'workbuddy-ai' : CLIENT_VARIANT === 'workbuddy' ? 'workbuddy' : 'other',os: process.platform,arch: process.arch,workdaddy_version: version,@@ -161,6 +173,7 @@ function makeEvent({ stage, message, level = 'error', tags = {}, extra = {}, exccontexts: {runtime: { name: 'node', version: process.version },os: { name: process.platform, version: os.release() },+ client: { name: CLIENT_NAME, profile: PROFILE_ID, variant: CLIENT_VARIANT },},extra: sanitize(extra),};diff --git a/scripts/uninstall-win.ps1 b/scripts/uninstall-win.ps1index aa1d44c..0078e5d 100644--- a/scripts/uninstall-win.ps1+++ b/scripts/uninstall-win.ps1@@ -3,17 +3,25 @@# 默认保留备份数据(%APPDATA%\WorkDaddy);加 -RemoveData 一并删除。param([switch]$RemoveData,- [string]$AppDir = (Join-Path $env:LOCALAPPDATA 'Programs\WorkDaddy')+ [string]$AppDir = '',+ [string]$Profile = '__WBS_DEFAULT_PROFILE__')$ErrorActionPreference = 'Continue'-$dataDir = Join-Path $env:APPDATA 'WorkDaddy'+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 ([string]::IsNullOrWhiteSpace($AppDir)) { $AppDir = Join-Path $env:LOCALAPPDATA (Join-Path 'Programs' $productName) }+$dataRoot = Join-Path $env:APPDATA 'WorkDaddy'+$dataDir = if ($Profile -eq 'workbuddy-ai') { Join-Path $dataRoot 'profiles\workbuddy-ai' } else { $dataRoot }-Write-Host '卸载 WorkDaddy...'+Write-Host ('卸载 ' + $productName + '...')-# 1) 移除登录自启+# 1) 移除登录自启(兼容 WorkDaddy / WorkDaddy AI 两个 profile)try {- Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name 'WorkDaddy' -ErrorAction SilentlyContinue+ foreach ($runName in @('WorkDaddy', 'WorkDaddy AI')) {+ Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name $runName -ErrorAction SilentlyContinue+ }Write-Host ' 已移除登录自启项'} catch {}@@ -50,4 +58,4 @@ if ($RemoveData) {Write-Host '卸载完成。'if (-not $RemoveData) {Write-Host '如需同时删除账号备份,请重新运行:uninstall-win.ps1 -RemoveData'-}\ No newline at end of file+}diff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex e8ccdea..efcda48 100644--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -16,6 +16,13 @@ elsefiecho "==> 停止并移除 launchd 守护进程"+for old_profile in workbuddy-cn workbuddy-ai codebuddy-cn codebuddy-intl; do+ old_label="com.workbuddy.workdaddy.${old_profile}"+ old_plist="$HOME/Library/LaunchAgents/${old_label}.plist"+ launchctl bootout "gui/$(id -u)" "$old_plist" 2>/dev/null || true+ launchctl remove "$old_label" 2>/dev/null || true+ rm -f "$old_plist"+donelaunchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || truerm -f "$PLIST"launchctl bootout "gui/$(id -u)" "$LEGACY_PLIST" 2>/dev/null || truediff --git a/scripts/verify-win.cmd b/scripts/verify-win.cmdindex 077f0a9..6eb79f6 100644--- a/scripts/verify-win.cmd+++ b/scripts/verify-win.cmd@@ -75,9 +75,9 @@ for %%F in (install-win.ps1) do ())-rem ---- 5) 自启注册表与安装目录回写测试(读态 + 安装目录可写性探测)----+rem ---- 5) 自启清理状态与安装目录回写测试(读态 + 安装目录可写性探测)----echo.-echo [5/6] 检查安装目标可写 + 自启状态...+echo [5/6] 检查安装目标可写 + 旧自启状态...set "APPDIR=%LOCALAPPDATA%\Programs\WorkDaddy"if exist "%APPDIR%\scripts\daemon.js" (echo 已安装版本: "%APPDIR%" 存在diff --git a/scripts/watchdog.js b/scripts/watchdog.jsindex ce73a58..92359a5 100644--- a/scripts/watchdog.js+++ b/scripts/watchdog.js@@ -15,11 +15,14 @@ const fs = require('fs');const path = require('path');const os = require('os');const { spawn } = require('child_process');+const { getProfile, profileDataDir } = require('./profiles.js');const SCRIPTS_DIR = __dirname;+const PROFILE_ID = process.env.WBSWITCH_PROFILE || 'workbuddy-cn';+const PROFILE = getProfile(PROFILE_ID);const DATA_DIR =process.env.WBSWITCH_DATA_DIR ||- path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'WorkDaddy');+ profileDataDir(PROFILE);const PID_FILE = path.join(DATA_DIR, 'watchdog.pid');const LOG_FILE = path.join(DATA_DIR, 'watchdog.log');const UPDATE_PENDING_FILE = path.join(DATA_DIR, 'update', 'pending.json'); // 自动更新进行中标记(update 目录由 apply 流程创建)@@ -117,4 +120,4 @@ function shutdown() {}, 800);}process.on('SIGTERM', shutdown);-process.on('SIGINT', shutdown);\ No newline at end of file+process.on('SIGINT', shutdown);diff --git a/scripts/win-launcher.js b/scripts/win-launcher.jsindex ebc0196..cf70b46 100644--- a/scripts/win-launcher.js+++ b/scripts/win-launcher.js@@ -19,22 +19,42 @@ const net = require('net');const http = require('http');const { spawn, spawnSync } = require('child_process');const { captureMessage, captureException } = require('./sentry-report.js');+const { getProfile, profileDataDir } = require('./profiles.js');+const { isTargetForProfile } = require('./cdp-targets.js');const SCRIPTS_DIR = __dirname;+const HOST = '127.0.0.1';+const PROFILE_ID = process.env.WBSWITCH_PROFILE || 'workbuddy-cn';+if (!process.env.WBSWITCH_PROFILE) process.env.WBSWITCH_PROFILE = PROFILE_ID;+const PROFILE = getProfile(PROFILE_ID);+const WBS_BRAND = PROFILE.appName || 'WorkDaddy'; // 品牌显示名跟随 profile(WorkDaddy AI / WorkDaddy)const DATA_DIR =process.env.WBSWITCH_DATA_DIR ||- path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'WorkDaddy');-const UI_PORT = parseInt(process.env.WBSWITCH_PORT || '47832', 10);+ profileDataDir(PROFILE);+const DEFAULT_UI_PORT = { 'workbuddy-cn': 47832, 'workbuddy-ai': 47833, 'codebuddy-cn': 47834, 'codebuddy-intl': 47835 }[PROFILE.id] || 47832;+const UI_PORT = parseInt(process.env.WBSWITCH_PORT || String(DEFAULT_UI_PORT), 10);+const PROFILE_CDP_PORTS = {+ 'workbuddy-cn': [9222, 9226, 9227, 9228, 9229, 9230, 9231, 9232],+ 'workbuddy-ai': [9223, 9233, 9234, 9235, 9236, 9237, 9238, 9239],+ 'codebuddy-cn': [9224],+ 'codebuddy-intl': [9225],+};+const DEFAULT_CDP_PORT = (PROFILE_CDP_PORTS[PROFILE.id] || [9222])[0];const cliCdpPort = process.argv.find((arg) => /^--cdp-port=\d+$/i.test(arg));-let CDP_PORT = parseInt(process.env.WBSWITCH_CDP_PORT || (cliCdpPort ? cliCdpPort.split('=')[1] : '') || '0', 10);+let CDP_PORT = parseInt(process.env.WBSWITCH_CDP_PORT || (cliCdpPort ? cliCdpPort.split('=')[1] : '') || String(DEFAULT_CDP_PORT), 10);const CDP_PORT_FILE = path.join(DATA_DIR, 'cdp-port.json');const ELEVATED_HELPER_MODE = process.argv.includes('--inject-helper');// 便携版/低速磁盘上的 WorkBuddy 首次启动可能超过 20 秒;超时只应在足够长的窗口后报告。const CDP_STARTUP_TIMEOUT_MS = 60000;-const WORKBUDDY_PROCESS_NAMES = new Set(['workbuddy.exe', 'codebuddy.exe', 'workbuddyai.exe']);+// PR#8 实机确认 WorkBuddy 两个版本分别使用 WorkBuddy.exe / WorkBuddyAI.exe。+// 两者都纳入探测和退出;路径过滤负责避免 CN launcher 误杀 AI 的同名族进程。+const PROFILE_PROCESS_NAMES = new Set(+ PROFILE.kind === 'workbuddy' ? ['workbuddy.exe', 'workbuddyai.exe'] :+ PROFILE.id === 'codebuddy-intl' ? ['codebuddy.exe'] : ['codebuddy.exe']+);function log(...args) {- const line = `[launcher] ${new Date().toISOString()} ${args.join(' ')}\n`;+ const line = `[launcher] ${new Date().toISOString()} [client=${PROFILE.name}] [profile=${PROFILE.id}] ${args.join(' ')}\n`;try { process.stdout.write(line); } catch (_) {}try { fs.appendFileSync(path.join(DATA_DIR, 'launcher.log'), line); } catch (_) {}}@@ -72,8 +92,7 @@ function cdpPortCandidates() {const add = (port) => { if (validCdpPort(port) && !result.includes(port)) result.push(port); };add(CDP_PORT);add(readCdpPortFile());- for (let port = 9222; port <= 9232; port++) add(port);- add(9333);+ for (const port of (PROFILE_CDP_PORTS[PROFILE.id] || [DEFAULT_CDP_PORT])) add(port);return result;}@@ -122,7 +141,7 @@ function spawnElevatedHelper() {function portOpen(port) {return new Promise((resolve) => {- const s = net.connect({ port, host: '127.0.0.1' });+ const s = net.connect({ port, host: HOST });const t = setTimeout(() => { s.destroy(); resolve(false); }, 1200);s.on('connect', () => { clearTimeout(t); s.destroy(); resolve(true); });s.on('error', () => { clearTimeout(t); resolve(false); });@@ -131,7 +150,7 @@ function portOpen(port) {function httpGet(port, p) {return new Promise((resolve) => {- const req = http.get({ host: '127.0.0.1', port, path: p, timeout: 1500 }, (res) => {+ const req = http.get({ host: HOST, port, path: p, timeout: 1500 }, (res) => {let body = '';res.on('data', (c) => (body += c));res.on('end', () => resolve({ status: res.statusCode, body }));@@ -143,7 +162,7 @@ function httpGet(port, p) {function httpPost(port, p) {return new Promise((resolve) => {- const req = http.request({ host: '127.0.0.1', port, path: p, method: 'POST', timeout: 1500 }, (res) => {+ const req = http.request({ host: HOST, port, path: p, method: 'POST', timeout: 1500 }, (res) => {res.resume();res.on('end', () => resolve({ status: res.statusCode }));});@@ -158,12 +177,16 @@ async function isWorkBuddyCdp() {}async function isWorkBuddyCdpAt(port, binary = null) {- const version = await httpGet(port, '/json/version');- if (!version || version.status !== 200) return false;+ const [version, targets] = await Promise.all([+ httpGet(port, '/json/version'),+ httpGet(port, '/json/list'),+ ]);+ if (!version || version.status !== 200 || !targets || targets.status !== 200) return false;try {const info = JSON.parse(version.body || '{}');- if (/workbuddy|codebuddy/i.test([info.Browser, info['User-Agent']].filter(Boolean).join(' '))) return true;- // 某些 WorkBuddy 版本隐藏 Electron 品牌;端口响应 + 同安装目录进程的精确参数仍可确认归属。+ const list = JSON.parse(targets.body || '[]');+ if (Array.isArray(list) && list.some((target) => isTargetForProfile(target, PROFILE))) return true;+ // 某些版本隐藏页面强信号;只有同安装目录进程的精确参数带着该端口时才允许兜底。return Boolean(binary && workBuddyProcesses(binary).some((p) => processCdpPort(p) === Number(port)));} catch (_) { return false; }}@@ -223,14 +246,48 @@ function sameWindowsPath(a, b) {function workBuddyProcesses(binary = null) {return getWorkBuddyProcesses().filter((p) => {- if (!WORKBUDDY_PROCESS_NAMES.has(String(p.Name || '').toLowerCase())) return false;- if (!binary || !p.ExecutablePath) return true;+ if (!PROFILE_PROCESS_NAMES.has(String(p.Name || '').toLowerCase())) return false;+ if (!binary) return true;+ // 缺少 ExecutablePath 时不能证明它属于当前安装目录;交给 tasklist 回退并记录为不确定。+ if (!p.ExecutablePath) return false;// WorkBuddy 可能把 Electron 主进程拆成同目录下的 CodeBuddy.exe/辅助宿主;按安装目录归组。return sameWindowsPath(p.ExecutablePath, binary) ||sameWindowsPath(path.dirname(p.ExecutablePath), path.dirname(binary));});}+function targetProcessNames(binary = null) {+ const names = new Set();+ const normalized = String(binary || '').toLowerCase();+ for (const p of getWorkBuddyProcesses()) {+ if (!PROFILE_PROCESS_NAMES.has(String(p.Name || '').toLowerCase())) continue;+ if (binary && p.ExecutablePath && !(+ sameWindowsPath(p.ExecutablePath, binary) ||+ sameWindowsPath(path.dirname(p.ExecutablePath), path.dirname(binary))+ )) continue;+ names.add(String(p.Name).toLowerCase());+ }+ if (names.size) return names;+ if (normalized.endsWith('workbuddyai.exe') || PROFILE.id === 'workbuddy-ai') return new Set(['workbuddyai.exe']);+ return new Set(['workbuddy.exe']);+}++function tasklistProcessIds(names = PROFILE_PROCESS_NAMES) {+ const ids = new Set();+ for (const name of names) {+ try {+ const r = spawnSync('tasklist', ['/FI', 'IMAGENAME eq ' + name, '/FO', 'CSV', '/NH'], {+ encoding: 'utf8', timeout: 5000, windowsHide: true,+ });+ for (const line of String(r.stdout || '').split(/\r?\n/)) {+ const m = line.match(/^"[^"]+","(\d+)"/);+ if (m) ids.add(m[1]);+ }+ } catch (_) {}+ }+ return ids;+}+function processCdpPort(process) {const commandLine = String(process && process.CommandLine || '');const match = commandLine.match(/(?:^|\s)--remote-debugging-port(?:=|\s+)(\d+)(?:\s|$)/i);@@ -299,6 +356,8 @@ function findWorkBuddy() {};const envBin = tryFile(process.env.WBSWITCH_WORKBUDDY_BIN);if (envBin) return (wbBinaryCache = envBin);+ const profileBin = tryFile(PROFILE.appPath);+ if (profileBin) return (wbBinaryCache = profileBin);try {const p = psOut('Get-Process WorkBuddy -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path').split(/\r?\n/).filter(Boolean).pop();const hit = tryFile(p);@@ -420,14 +479,23 @@ function stopDaemonByPort() {function workBuddyRunning(binary = null) {const processes = workBuddyProcesses(binary);if (processes.length) return true;+ if (binary) {+ // CIM 能看到同族进程但路径明确属于另一个安装目录时,不应把它当成当前客户端仍在运行。+ // 路径未知则保守认为仍在运行,后续 tasklist/PID 回退会尝试结束并写出诊断。+ const unknownPath = getWorkBuddyProcesses().some((p) =>+ PROFILE_PROCESS_NAMES.has(String(p.Name || '').toLowerCase()) && !p.ExecutablePath+ );+ if (!unknownPath) return false;+ }// CIM 失败时保守回退到 tasklist,避免误判为已退出后把启动参数交给旧实例。try {- const filters = Array.from(WORKBUDDY_PROCESS_NAMES).map((name) =>+ const names = binary ? targetProcessNames(binary) : PROFILE_PROCESS_NAMES;+ const filters = Array.from(names).map((name) =>spawnSync('tasklist', ['/FI', 'IMAGENAME eq ' + name, '/FO', 'CSV', '/NH'], {encoding: 'utf8', timeout: 5000, windowsHide: true,}));- return filters.some((r) => r.status === 0 && WORKBUDDY_PROCESS_NAMES.has(+ return filters.some((r) => r.status === 0 && names.has(String(r.stdout || '').match(/"([^"]+\.exe)"/i)?.[1]?.toLowerCase() || ''));} catch (_) {@@ -461,23 +529,62 @@ async function waitForWorkBuddyExit(timeoutMs, binary = null) {return !workBuddyRunning(binary);}+function exitSnapshot(binary = null) {+ return {+ binary: binary ? path.basename(binary) : null,+ processes: processDiagnostics(binary),+ tasklistPids: Array.from(tasklistProcessIds(targetProcessNames(binary))),+ };+}++async function killForExit(args, stage) {+ const result = await runTaskkill(args);+ const error = result.error ? result.error.message : '';+ log(`[exit] ${stage} taskkill=${args.join(' ')} code=${result.code == null ? 'null' : result.code}${error ? ' error=' + error : ''}`);+ return result;+}+async function quitWorkBuddy(binary) {const initial = workBuddyProcesses(binary);+ const targetNames = targetProcessNames(binary);if (!initial.length && !workBuddyRunning(binary)) return true;- // 按实际 PID 精确结束安装目录中的进程树,避免 /IM 只结束主进程而留下单实例宿主。+ log(`[exit] 开始确认退出 profile=${PROFILE.id} snapshot=${JSON.stringify(exitSnapshot(binary))}`);+ // 按实际 PID 精确结束安装目录中的进程树;CIM 不可用时退回 tasklist,避免+ // “检测到仍在运行但没有 PID”导致无条件等待后上报无法退出。const pids = new Set(initial.map((p) => String(Number(p.ProcessId))).filter((pid) => pid !== '0'));- if (!pids.size) pids.add('0');+ if (!pids.size) for (const pid of tasklistProcessIds(targetNames)) pids.add(pid);for (const pid of pids) {- if (pid !== '0') await runTaskkill(['/T', '/PID', pid]);+ await killForExit(['/T', '/PID', pid], '优雅结束进程树');}- if (await waitForWorkBuddyExit(2500, binary)) return true;- for (const pid of pids) {- if (pid !== '0') await runTaskkill(['/F', '/T', '/PID', pid]);+ if (await waitForWorkBuddyExit(2500, binary)) {+ log(`[exit] 已确认退出 profile=${PROFILE.id} snapshot=${JSON.stringify(exitSnapshot(binary))}`);+ return true;+ }++ // 单实例宿主可能在第一次 taskkill 后重新生成辅助进程;刷新 PID 集合再强杀两轮。+ for (let round = 1; round <= 2; round++) {+ const current = new Set(workBuddyProcesses(binary).map((p) => String(Number(p.ProcessId))).filter((pid) => pid !== '0'));+ if (!current.size) for (const pid of tasklistProcessIds(targetNames)) current.add(pid);+ log(`[exit] 强制结束第 ${round} 轮 snapshot=${JSON.stringify(exitSnapshot(binary))}`);+ for (const pid of current) await killForExit(['/F', '/T', '/PID', pid], `强制结束第${round}轮`);+ if (await waitForWorkBuddyExit(2500, binary)) {+ log(`[exit] 强制结束后已确认退出 profile=${PROFILE.id} snapshot=${JSON.stringify(exitSnapshot(binary))}`);+ return true;+ }+ }++ // CIM 无法返回 PID 时按 PR#8 的两个精确镜像名兜底;最终结果仍必须经过检测确认。+ for (const name of targetNames) await killForExit(['/F', '/T', '/IM', name], '镜像名兜底');+ if (await waitForWorkBuddyExit(5000, binary)) {+ log(`[exit] 镜像名兜底后已确认退出 profile=${PROFILE.id} snapshot=${JSON.stringify(exitSnapshot(binary))}`);+ return true;}- if (await waitForWorkBuddyExit(5500, binary)) return true;- logProcessDiagnostics(binary, '结束 WorkBuddy 后仍有进程');- throw new Error('无法确认 WorkBuddy 已退出');+ const final = exitSnapshot(binary);+ log(`[exit] 无法确认退出 profile=${PROFILE.id} final=${JSON.stringify(final)}`);+ const names = final.processes.map((p) => p.name).filter(Boolean).join(',') || 'unknown';+ const pidsLeft = final.processes.map((p) => p.pid).filter(Boolean).join(',') || final.tasklistPids.join(',') || 'unknown';+ throw new Error(`${PROFILE.name} 无法确认已退出(剩余镜像=${names}; PID=${pidsLeft})`);}function psQuote(value) {@@ -615,7 +722,7 @@ async function injectNow() {if (await isWorkBuddyCdp()) {await injectNow();log('WorkBuddy 已在调试模式(端口 ' + CDP_PORT + '),组件已注入');- console.log('WorkDaddy:WorkBuddy 已在调试模式,组件已注入 ✓');+ console.log(WBS_BRAND + ':WorkBuddy 已在调试模式,组件已注入 ✓');process.exit(0);}@@ -652,7 +759,7 @@ async function injectNow() {await sleep(1500);await injectNow();log('WorkBuddy 已启动(调试模式),组件已注入');- console.log('WorkDaddy:WorkBuddy 已启动(调试模式),组件已注入 ✓');+ console.log(WBS_BRAND + ':WorkBuddy 已启动(调试模式),组件已注入 ✓');} else {log('等待 ' + (CDP_STARTUP_TIMEOUT_MS / 1000) + ' 秒未检测到调试端口 ' + CDP_PORT);console.log('等待超时:未检测到调试端口 ' + CDP_PORT + '。可手动执行:cd /d ' + path.dirname(wb) + ' && "' + wb + '" --remote-debugging-port=' + CDP_PORT);@@ -664,6 +771,6 @@ async function injectNow() {process.exit(ok ? 0 : 3);})().catch((e) => {log('launcher 异常: ' + (e && e.stack || e));- console.error('WorkDaddy 启动异常: ' + (e && e.message || e));+ console.error(WBS_BRAND + ' 启动异常: ' + (e && e.message || e));captureException(e, { stage: 'windows-launcher-uncaught' }).catch(() => {}).finally(() => process.exit(4));});diff --git a/test/auto-copy-rules.test.js b/test/auto-copy-rules.test.jsindex df73a53..720cd95 100644--- a/test/auto-copy-rules.test.js+++ b/test/auto-copy-rules.test.js@@ -28,6 +28,8 @@ const {editModelBackup,deleteModelBackups,enableModelBackup,+ importModels,+ checkinDisplayValue,} = require('../scripts/lib.js');function tempDataDir() {@@ -177,6 +179,28 @@ test('official model batch deletion only changes official config and leaves backassert.equal(fs.existsSync(path.join(dataDir, 'models', backup.backupId + '.json')), true);});+test('model import appends new names and preserves current same-name configuration', () => {+ const dataDir = tempDataDir();+ const targetFile = path.join(dataDir, 'current.json');+ const sourceFile = path.join(dataDir, 'source.json');+ fs.writeFileSync(targetFile, JSON.stringify({ models: [+ { id: 'shared-id', name: 'Shared', apiKey: 'current-key', url: 'https://current.invalid' },+ ], metadata: { keep: true }}));+ fs.writeFileSync(sourceFile, JSON.stringify({ models: [+ { id: 'shared-id', name: 'Shared', apiKey: 'source-key', url: 'https://source.invalid' },+ { id: 'new-id', name: 'New model', apiKey: 'new-key' },+ ], metadata: { source: true }}));++ const result = importModels(targetFile, sourceFile);+ assert.deepEqual(result.imported, ['New model']);+ assert.deepEqual(result.skipped, ['Shared']);+ const saved = JSON.parse(fs.readFileSync(targetFile, 'utf8'));+ assert.equal(saved.metadata.keep, true);+ assert.equal(saved.models.length, 2);+ assert.equal(saved.models[0].apiKey, 'current-key');+ assert.equal(saved.models[1].id, 'new-id');+});+test('api keys keep their full masked length without exposing the middle', () => {const raw = 'sk-abcdefghijklmnopqrstuvwxyz0123456789-dlzj';const masked = maskApiKey(raw);@@ -185,3 +209,12 @@ test('api keys keep their full masked length without exposing the middle', () =>assert.equal(masked.slice(-4), 'dlzj');assert.equal(masked.includes('abcdef'), false);});++test('checkin display hides cached result while the current claim is still running', () => {+ const record = { date: '2026-08-23', ok: true, already: false, code: 0, message: 'ok' };+ assert.equal(checkinDisplayValue(record, '2026-08-23', true), null);+ assert.deepEqual(checkinDisplayValue(record, '2026-08-23', false), {+ ok: true, already: false, code: 0, message: 'ok',+ });+ assert.equal(checkinDisplayValue(record, '2026-08-22', false), null);+});diff --git a/test/cdp-targets.test.js b/test/cdp-targets.test.jsnew file mode 100644index 0000000..6c1f793--- /dev/null+++ b/test/cdp-targets.test.js@@ -0,0 +1,91 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const { PROFILES } = require('../scripts/profiles.js');+const { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('../scripts/cdp-targets.js');++const AI_URL = 'file:///Applications/WorkBuddy%20AI.app/Contents/Resources/app.asar/renderer/index.html';+const CN_URL = 'file:///Applications/WorkBuddy.app/Contents/Resources/app.asar/renderer/index.html';+const CB_CN_URL = 'file:///Applications/CodeBuddy%20CN.app/Contents/Resources/app/renderer/index.html';+const CB_INTL_URL = 'file:///Applications/CodeBuddy.app/Contents/Resources/app/renderer/index.html';+const VSCODE_URL = 'vscode-file://vscode-app/Applications/CodeBuddy.app/Contents/Resources/app/out/vs/code/electron-sandbox/workbench/workbench.html';++test('normalizeTargetUrl 把 %20 还原为空格', () => {+ assert.equal(normalizeTargetUrl(AI_URL), AI_URL.replace(/%20/g, ' '));+ assert.equal(normalizeTargetUrl('WorkBuddy AI.app'), 'WorkBuddy AI.app');+});++test('classifyTarget 依据 app 包路径识别四客户端(含 %20 编码)', () => {+ assert.equal(classifyTarget(AI_URL, 'WorkBuddy AI'), 'workbuddy-ai');+ assert.equal(classifyTarget(CN_URL, 'WorkBuddy'), 'workbuddy-cn');+ assert.equal(classifyTarget(CB_CN_URL, 'CodeBuddy'), 'codebuddy-cn');+ assert.equal(classifyTarget(CB_INTL_URL, 'CodeBuddy'), 'codebuddy-intl');+ // 标题兜底不得覆盖 app 路径强信号:AI 页面标题即使叫 "WorkBuddy",仍归属 workbuddy-ai+ assert.equal(classifyTarget(AI_URL, 'WorkBuddy'), 'workbuddy-ai');+});++test('classifyTarget 依据登录域名识别国际版/国内版', () => {+ assert.equal(classifyTarget('https://www.workbuddy.ai/profile/plans-usage', ''), 'workbuddy-ai');+ assert.equal(classifyTarget('https://www.workbuddy.cn/profile/plans-usage', ''), 'workbuddy-cn');+ assert.equal(classifyTarget('https://www.codebuddy.cn/v2/plugin/auth/state', ''), 'codebuddy-cn');+ assert.equal(classifyTarget('https://www.codebuddy.ai/v2/plugin/auth/state', ''), 'codebuddy-intl');+ assert.equal(classifyTarget('https://example.com/other', ''), null);+});++test('isTargetForProfile 强信号下拒绝所有异 profile 页面', () => {+ const ai = PROFILES['workbuddy-ai'];+ const cn = PROFILES['workbuddy-cn'];+ // AI daemon 只认 AI 页面+ assert.equal(isTargetForProfile({ type: 'page', url: AI_URL, title: 'WorkBuddy' }, ai), true);+ assert.equal(isTargetForProfile({ type: 'page', url: CN_URL, title: 'WorkBuddy' }, ai), false);+ // CN daemon 只认 CN 页面 —— 不再被 AI 页面标题 "WorkBuddy" 骗走+ assert.equal(isTargetForProfile({ type: 'page', url: CN_URL, title: 'WorkBuddy' }, cn), true);+ assert.equal(isTargetForProfile({ type: 'page', url: AI_URL, title: 'WorkBuddy' }, cn), false);+ // CodeBuddy 页面与 WorkBuddy 页面互不认领+ assert.equal(isTargetForProfile({ type: 'page', url: CB_INTL_URL, title: 'CodeBuddy' }, ai), false);+ assert.equal(isTargetForProfile({ type: 'page', url: AI_URL, title: 'WorkBuddy' }, PROFILES['codebuddy-intl']), false);+});++test('isTargetForProfile CodeBuddy 走宽松分支(vscode-file 目标)', () => {+ const intl = PROFILES['codebuddy-intl'];+ assert.equal(isTargetForProfile({ type: 'page', url: VSCODE_URL, title: 'CodeBuddy' }, intl), true);+ // 明确属于 CodeBuddy CN app 的路径不被国际版认领+ assert.equal(isTargetForProfile({ type: 'page', url: CB_CN_URL, title: 'CodeBuddy CN' }, intl), false);+ // devtools / chrome 内部页不算+ assert.equal(isTargetForProfile({ type: 'page', url: 'devtools://devtools/bundled/inspector.html', title: '' }, intl), false);+});++test('isTargetForProfile 未绑定 workbuddy daemon 禁止裸标题匹配(防误连 AI)', () => {+ const prev = process.env.WBSWITCH_PROFILE;+ delete process.env.WBSWITCH_PROFILE;+ try {+ const cn = PROFILES['workbuddy-cn'];+ // 无 URL 强信号(如远程 OAuth 页)+ 标题 "WorkBuddy":未绑定时必须拒绝,避免错杀/误连+ assert.equal(isTargetForProfile({ type: 'page', url: 'https://account.example.com/login', title: 'WorkBuddy' }, cn), false);+ // 有 URL 强信号时不受影响+ assert.equal(isTargetForProfile({ type: 'page', url: CN_URL, title: 'WorkBuddy' }, cn), true);+ } finally {+ if (prev) process.env.WBSWITCH_PROFILE = prev;+ }+});++test('isTargetForProfile 已绑定 profile 时允许标题兜底', () => {+ const prev = process.env.WBSWITCH_PROFILE;+ process.env.WBSWITCH_PROFILE = 'workbuddy-ai';+ try {+ const ai = PROFILES['workbuddy-ai'];+ assert.equal(isTargetForProfile({ type: 'page', url: 'file:///some/unknown/root.html', title: 'WorkBuddy AI' }, ai), true);+ } finally {+ if (prev) process.env.WBSWITCH_PROFILE = prev;+ }+});++test('looksLikeWbFamilyTarget 把四客户端页面都视为同族(不清理)', () => {+ assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: AI_URL, title: 'WorkBuddy' }), true);+ assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: CN_URL, title: 'WorkBuddy' }), true);+ assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: CB_CN_URL, title: '' }), true);+ assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: VSCODE_URL, title: 'CodeBuddy' }), true);+ // 任意其他 Chromium 应用不算同族(允许清理历史误注入)+ assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: 'file:///Applications/Antigravity.app/Contents/index.html', title: 'Antigravity' }), false);+});\ No newline at end of filediff --git a/test/profiles.test.js b/test/profiles.test.jsnew file mode 100644index 0000000..59af8ab--- /dev/null+++ b/test/profiles.test.js@@ -0,0 +1,37 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const { PROFILES, getProfile, profileDataDir } = require('../scripts/profiles.js');++test('四个客户端 profile 使用独立数据源和能力开关', () => {+ assert.deepEqual(Object.keys(PROFILES).sort(), ['codebuddy-cn', 'codebuddy-intl', 'workbuddy-ai', 'workbuddy-cn']);+ assert.equal(getProfile('workbuddy-ai').sessionDb.endsWith('.workbuddy-ai/workbuddy.db'), true);+ assert.equal(getProfile('codebuddy-cn').sessionDb.endsWith('CodeBuddy CN/codebuddy-sessions.vscdb'), true);+ assert.equal(getProfile('codebuddy-intl').sessionDb.endsWith('CodeBuddy/codebuddy-sessions.vscdb'), 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);+});++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);+});++test('各 profile 的 API host 与 auth.domain 一致(签到/积分/无感登录)', () => {+ assert.equal(getProfile('workbuddy-cn').apiHost, 'https://www.codebuddy.cn');+ assert.equal(getProfile('workbuddy-ai').apiHost, 'https://www.workbuddy.ai');+ assert.equal(getProfile('codebuddy-cn').apiHost, 'https://www.codebuddy.cn');+ assert.equal(getProfile('codebuddy-intl').apiHost, 'https://www.codebuddy.ai');+});++test('默认 WorkBuddy 数据目录保持兼容,其他 profile 隔离到子目录', () => {+ const cn = getProfile('workbuddy-cn');+ const ai = getProfile('workbuddy-ai');+ assert.equal(profileDataDir(cn).endsWith('Application Support/WorkDaddy'), true);+ assert.equal(profileDataDir(ai).endsWith('Application Support/WorkDaddy/profiles/workbuddy-ai'), true);+});diff --git a/test/sentry.test.js b/test/sentry.test.jsnew file mode 100644index 0000000..cb04db2--- /dev/null+++ b/test/sentry.test.js@@ -0,0 +1,34 @@+'use strict';++const assert = require('node:assert/strict');+const childProcess = require('node:child_process');+const path = require('node:path');+const test = require('node:test');++const repoRoot = path.resolve(__dirname, '..');+const reporter = path.join(repoRoot, 'scripts', 'sentry-report.js');++function dryRun(profile) {+ const result = childProcess.spawnSync(process.execPath, [reporter, '--dry-run', '--stage', 'test', '--message', 'profile test'], {+ cwd: repoRoot,+ env: { ...process.env, WBSWITCH_PROFILE: profile, WORKDADDY_TELEMETRY: '0' },+ encoding: 'utf8',+ });+ assert.equal(result.status, 0, result.stderr);+ return JSON.parse(result.stdout);+}++test('Sentry events identify WorkBuddy CN and WorkBuddy AI without account data', () => {+ const cn = dryRun('workbuddy-cn');+ assert.equal(cn.tags.client, 'workbuddy');+ assert.equal(cn.tags.client_name, 'WorkBuddy');+ assert.equal(cn.tags.workbuddy_variant, 'workbuddy');+ assert.deepEqual(cn.contexts.client, { name: 'WorkBuddy', profile: 'workbuddy-cn', variant: 'workbuddy' });++ const ai = dryRun('workbuddy-ai');+ assert.equal(ai.tags.client, 'workbuddy-ai');+ assert.equal(ai.tags.client_name, 'WorkBuddy AI');+ assert.equal(ai.tags.workbuddy_variant, 'workbuddy-ai');+ assert.deepEqual(ai.contexts.client, { name: 'WorkBuddy AI', profile: 'workbuddy-ai', variant: 'workbuddy-ai' });+ assert.doesNotMatch(JSON.stringify(ai), /accessToken|refreshToken|cookie|password/i);+});diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 0ee4bb2..fdece4d 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -133,6 +133,49 @@ test('Windows launcher tolerates slow WorkBuddy startup beyond the old 20 secondassert.match(launcher, /await sleep\(1000\)/);});+test('Windows launcher keeps local port probing and profile CDP candidates defined', () => {+ const launcher = read('win-launcher.js');+ assert.match(launcher, /const HOST\s*=\s*['"]127\.0\.0\.1['"]/);+ assert.match(launcher, /function portOpen\(port\)/);+ assert.match(launcher, /function daemonRunning\(\)\s*\{\s*return portOpen\(UI_PORT\);/);+ assert.match(launcher, /'workbuddy-cn': \[9222/);+ assert.match(launcher, /'workbuddy-ai': \[9223/);+ assert.match(launcher, /isTargetForProfile\(target, PROFILE\)/);+});++test('macOS updater validates a cached/downloaded DMG before mounting it', () => {+ const daemon = read('daemon.js');+ assert.match(daemon, /hdiutil['"],\s*\['imageinfo'/);+ assert.match(daemon, /validateUpdateArtifact|validateDmg|inspectDmg|isValidDmg/);+ assert.match(daemon, /下载内容不是有效 DMG|DMG 预检失败/);+ assert.match(daemon, /dmgSize/);+ assert.match(daemon, /Content-Type|content-type/);+});++test('Windows launcher covers both WorkBuddy images and records exit diagnostics', () => {+ const launcher = read('win-launcher.js');+ assert.match(launcher, /WorkBuddy\.exe/);+ assert.match(launcher, /WorkBuddyAI\.exe/);+ assert.match(launcher, /\[exit\]/);+ assert.match(launcher, /taskkill=/);+ assert.match(launcher, /tasklistProcessIds/);+ assert.match(launcher, /processDiagnostics/);+});++test('release scripts package only WorkDaddy and WorkDaddy AI', () => {+ 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(win, /WorkDaddy AI\.lnk|PACKAGE_NAME="WorkDaddy AI"/);+ assert.match(win, /OUT="release\/windows\/WorkDaddy/);+ assert.match(mac, /PACKAGE_APP_NAME="WorkDaddy AI"/);+ assert.match(installer, /\$lnkPath\s*=\s*Join-Path\s+\$desktopDir\s+\(\$productName\s+\+\s+'\.lnk'\)/);+});+test('Windows launcher verifies the real WorkBuddy process tree and launch arguments', () => {const launcher = read('win-launcher.js');assert.match(launcher, /Get-CimInstance Win32_Process/);@@ -190,7 +233,17 @@ test('account cards keep the compact three-row layout', () => {assert.match(script, /wbs-secondary-row/);assert.match(script, /剩余积分/);assert.match(script, /今日已签到/);- assert.match(script, /登录过期于/);+ // 登录有效期展示:国际版也将 token 有效截止时间展示为「有效期至」而非歧义的「登录过期于」+ assert.match(script, /有效期至/);+ assert.doesNotMatch(script, /登录过期于/);+ assert.match(script, /var isUinMode = !a\.phone;/);+ assert.match(script, /var idLbl = a\.phone \? '手机' : \(a\.uin \? 'UIN' : '账号'\)/);+ assert.match(script, /\.wbs-phone-cell\.wbs-uin-cell\{gap:8px\}/);+ // 国际版:签到标签不展示;暂存按钮内联进操作栏按钮组第一位(AI 端无 voice-mic-wrap)+ assert.match(script, /if \(PROFILE_ID === 'workbuddy-ai'\) return '';/);+ assert.match(script, /function findAiToolbar\(\)/);+ assert.match(script, /wbs-stash-inline-inline/);+ assert.match(script, /row0\.insertBefore\(stashBtn, row0\.firstChild\)/);assert.match(script, /wbs-credit-hidden/);assert.match(script, /var expired = isIdentityExpired\(a\)/);assert.match(script, /expired \? '' : '<button class="wbs-icon-btn wbs-acc-switch"/);@@ -244,6 +297,34 @@ test('home composer keeps the robot button at the WorkBuddy bottom-right', () =>assert.match(script, /fab\.style\.right = '22px';\s*fab\.style\.bottom = '22px';/);});+test('WorkBuddy AI welcome composer keeps the robot at the window bottom-right', () => {+ const script = read('inject.js');+ assert.match(script, /PROFILE_ID === 'workbuddy-ai'/);+ assert.match(script, /_topRightSlotStandalone_\"\] > div:nth-child\(1\) > div:nth-child\(2\)/);+ assert.match(script, /aiHomeComposerCorner/);+});++test('installers disable login auto-start and clean prior registrations', () => {+ const win = read('install-win.ps1');+ assert.doesNotMatch(win, /Set-ItemProperty\s+-Path\s+\$runKey/);+ assert.match(win, /Remove-ItemProperty[\s\S]*WorkDaddy AI/);+ assert.match(win, /Remove-ItemProperty[\s\S]*WorkDaddy/);++ const mac = read('install.sh');+ assert.doesNotMatch(mac, /<key>RunAtLoad<\/key>/);+ assert.doesNotMatch(mac, /launchctl bootstrap/);+ assert.match(mac, /开机自启\s*:\s*已禁用/);++ const relaunch = read('relaunch-with-cdp.sh');+ assert.doesNotMatch(relaunch, /launchctl bootstrap/);+ assert.match(relaunch, /手动启动(?: WorkDaddy)? 守护进程/);+});++test('daemon and Windows launcher logs identify the active WorkBuddy client', () => {+ assert.match(read('daemon.js'), /\[client=\$\{PROFILE\.name\}\] \[profile=\$\{PROFILE\.id\}\]/);+ assert.match(read('win-launcher.js'), /\[client=\$\{PROFILE\.name\}\] \[profile=\$\{PROFILE\.id\}\]/);+});+test('zero credits omit the empty-state label', () => {const script = read('inject.js');assert.match(script, /if \(!list\.length\) return Number\(credits\) === 0 \? '' : '<div class="wbs-credit-empty">暂无可用积分<\/div>'/);@@ -298,12 +379,16 @@ test('session summary counts effective sessions and models tab only exposes saniassert.match(inject, /data-model-tab="official"/);assert.match(inject, /data-model-tab="mine"/);assert.match(daemon, /GET' && p === '\/api\/models'/);+ assert.match(daemon, /POST' && p === '\/api\/models\/import'/);+ assert.match(daemon, /listInstalledModelSources/);assert.match(daemon, /POST' && p === '\/api\/models\/backup'/);assert.match(daemon, /POST' && p === '\/api\/models\/delete-official'/);assert.match(daemon, /POST' && p === '\/api\/models\/test'/);assert.match(daemon, /POST' && p === '\/api\/models\/copy'/);assert.match(daemon, /POST' && p === '\/api\/models\/edit'/);assert.match(daemon, /POST' && p === '\/api\/models\/delete'/);+ assert.match(daemon, /requested: ids\.length, deleted/);+ assert.match(read('lib.js'), /\.legacy-migrated-v1/);assert.match(daemon, /POST' && p === '\/api\/models\/enable'/);// 模型页 UI 明文展示 apiKey:列表走 sanitizeModel(model, { revealKey: true }),默认仍脱敏assert.match(read('lib.js'), /function sanitizeModel\(model, opts\)/);@@ -319,6 +404,12 @@ test('session summary counts effective sessions and models tab only exposes saniassert.match(inject, /小贴士.*解决 WorkBuddy 不支持多个同名模型的问题/);assert.match(inject, /data-model-tab="official">当前模型/);assert.match(inject, /data-model-tab="mine">备选模型/);+ assert.match(inject, /data-model-import=/);+ assert.match(inject, /\/api\/models\/import/);+ assert.match(inject, /签到请求完成后再查询积分/);+ assert.match(inject, /fetchCreditsForAccounts\(\);/);+ assert.match(read('lib.js'), /function checkinDisplayValue\(record, today, pending\)/);+ assert.match(daemon, /checkin: checkinDisplayValue\(c, today, checkinPending\)/);assert.doesNotMatch(inject, /id="wbs-model-refresh"/);assert.match(inject, /wbs-model-group-title/);assert.match(inject, /delete-official/);