Skip to content

WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。

release: merge WorkDaddy 1.1.7 feature updates

[email protected]87d86922277d
diff --git a/README.md b/README.md
index c7ba701..2cfc55f 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,7 @@
# WorkDaddy
+**语言:** [简体中文](README.md) · [English](README_en.md)
+
> **WorkDaddy 是 WorkBuddy 桌面端增强助手:多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能,账号与配置全部留在本机。**
> 本机回环 CDP 注入 · 不改官方安装包。
@@ -63,6 +65,17 @@
4. 双击 `WorkDaddy.app` 启动:它会自带守护进程并把组件注入到 WorkBuddy
5. 看到机器人按钮?**搞定**。
+#### 企业专享版 / VPC 客户端
+
+macOS 会自动扫描带 `WorkBuddy` 前缀且包含 `Contents/MacOS/Electron` 的客户端(例如 `WorkBuddy企业定制版.app`),并按 WorkDaddy/WorkDaddy AI profile 排除另一端。发现多个候选时会弹出系统选择窗口,选中后自动记住,不需要手动寻找配置文件。完全自定义名称也可以在源码目录执行下面的高级配置命令:
+
+```bash
+node scripts/workbuddy-target.js --configure --platform darwin \
+ --profile workbuddy-cn \
+ --binary "/Applications/企业客户端.app/Contents/MacOS/Electron" \
+ --data-dir "$HOME/Library/Application Support/WorkDaddy"
+```
+
### Windows
@@ -150,6 +163,7 @@ WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:
| **增强** | 配置权限免打扰、异常中断自动续接、暂存提示词和快捷短语 |
| **电脑** | 允许或持续禁止休眠,也可在所有 AI 任务结束后自动恢复休眠 |
| **关于** | 查看版本和项目说明、检查并安装更新、控制脱敏错误诊断 |
+| **设置** | 选择中文或英语;首次打开按系统语言匹配,未匹配时使用英语 |
**输入框插件**:在「增强」页分别开启「暂存提示词」和「快捷短语」后,输入框操作栏会显示对应按钮。
暂存提示词可把当前草稿(文字、图片、文件、引用等**完整原样**)加入 WorkBuddy 自带的待发送队列,并暂停自动发送;
diff --git a/README_en.md b/README_en.md
new file mode 100644
index 0000000..5fad5fd
--- /dev/null
+++ b/README_en.md
@@ -0,0 +1,113 @@
+# WorkDaddy
+
+**Language:** [简体中文](README.md) · [English](README_en.md)
+
+> **WorkDaddy is a local enhancement layer for the WorkBuddy desktop app:** manage independent account backups and switch accounts in one click; keep unattended AI tasks running with quiet mode; move sessions between accounts and resume interrupted tasks; stash prompts and quick phrases; use frosted-glass themes and other utilities. Accounts and configuration stay on your computer.
+> Local loopback CDP injection · the official installation is never modified.
+
+WorkDaddy is a [WorkBuddy](https://www.workbuddy.cn/) and [WorkBuddy AI](https://www.workbuddy.ai/) desktop enhancement tool based on **Chrome DevTools Protocol (CDP)**. It injects a small control panel into the running renderer without patching, re-signing, or replacing the official app.
+
+![License](https://img.shields.io/badge/license-AGPL--3.0-blueviolet)
+![Platform](https://img.shields.io/badge/platform-macOS%2011%2B%20%7C%20Windows%2010%2F11-lightgrey)
+![Node](https://img.shields.io/badge/node-%E2%89%A518-green)
+
+## What it does
+
+- **Fast account switching:** each WorkBuddy account has its own backup and can be restored with one click.
+- **Add a new account without quitting:** complete OAuth in your browser and the new account is added automatically; a traditional soft logout flow is also available.
+- **Encrypted account import/export:** move backups between computers with a password-protected file.
+- **Daily credits:** opening the panel silently checks all accounts with an idempotent daily cache.
+- **Quiet approval mode:** automatically handle supported permission prompts while you are away.
+- **Stash prompts:** put drafts, images, files, and quotes into WorkBuddy's message queue for later sending.
+- **Themes:** switch the built-in frosted-glass theme, wallpapers, and custom backgrounds.
+- **Session migration:** copy sessions across accounts and continue working where you left off.
+- **Model tools:** manage, back up, edit, test, and switch models more easily.
+- **Sleep control:** keep the computer awake until selected tasks finish, then restore normal sleep.
+- **Auto-continue:** resume replies that stop because of transient network or provider failures.
+- **Quick phrases:** save common prompts and send them from the composer toolbar.
+
+## Installation
+
+For the mainland client download **WorkDaddy**. For the international client download **WorkDaddy AI**.
+
+### macOS
+
+1. Download the latest `WorkDaddy-x.y.z.dmg` or `WorkDaddy-AI-x.y.z.dmg` from [Releases](../../releases).
+2. Open the DMG and drag the app into **Applications**.
+3. If macOS says it cannot verify the developer, open **System Settings → Privacy & Security**, choose **Open Anyway**, and confirm with your login password.
+4. Launch the app. It starts its local daemon and injects the panel into WorkBuddy.
+
+### Windows
+
+1. Download `WorkDaddy-Setup-x.y.z.exe` or `WorkDaddy-AI-Setup-x.y.z.exe` from [Releases](../../releases).
+2. Run the installer.
+3. Launch **WorkDaddy** or **WorkDaddy AI** from the desktop shortcut.
+
+Enterprise/VPC users can select their official WorkBuddy executable in the installer. The selection is stored in the WorkDaddy data directory and can be changed by running the installer again.
+
+### Run from source
+
+```bash
+git clone https://github.com/babygoton/WorkDaddy.git
+cd WorkDaddy
+bash scripts/install.sh
+bash scripts/relaunch-with-cdp.sh
+```
+
+Use the profile environment variable when starting a specific client:
+
+```bash
+WBSWITCH_PROFILE=workbuddy-cn bash scripts/relaunch-with-cdp.sh
+WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh
+```
+
+The daemon listens on loopback (`127.0.0.1`) and binds the profile to its WorkBuddy target. No account data is deleted during migration; legacy backup directories remain in place.
+
+## How it works
+
+```
+┌─────────────┐ --remote-debugging-port=9222 ┌──────────────┐
+│ WorkBuddy │ <───────────────────────────> │ WorkDaddy │
+│ renderer │ Chrome DevTools │ daemon.js │
+└─────────────┘ Runtime.evaluate └──────────────┘
+```
+
+1. The launcher starts WorkBuddy with a loopback CDP port; the official binary and signature remain untouched.
+2. The daemon connects through CDP, watches authentication events, and stores account backups locally.
+3. `scripts/inject.js` renders the WorkDaddy panel and adapts to the active WorkBuddy profile.
+4. Local HTTP endpoints handle account switching, themes, sessions, sleep control, updates, and diagnostics.
+
+## Panel
+
+Open the robot button in the lower-right corner and choose a tab:
+
+| Tab | Purpose |
+| --- | --- |
+| Accounts | Account status, switching, deletion, and encrypted import/export |
+| Theme | Theme, wallpaper, avatar, blur, and overlay controls |
+| Sessions | Filter, copy, migrate, or delete sessions |
+| Models | Manage backups, model settings, tests, and bulk actions |
+| Enhance | Quiet approvals, auto-continue, stashed prompts, and quick phrases |
+| Computer | Sleep and wake policy |
+| About | Version, updates, and redacted diagnostics |
+| Settings | Choose Chinese or English; the first launch follows the system language and falls back to English |
+
+The language can be changed at any time from **Settings**. The choice is stored locally and applies immediately to the panel and its toasts.
+
+## Security and privacy
+
+- Account backups, themes, and local configuration stay on the computer. Login, credit, update, and explicit model connectivity features call their respective official or configured services.
+- Error diagnostics are enabled by default and can be disabled in **About**. Reports are redacted and truncated and do not include accounts, session contents, tokens, or API keys.
+- The daemon binds to loopback only. WorkDaddy does not modify `app.asar`, terminate unrelated processes, or elevate lifecycle operations.
+
+See [`AGENTS.md`](AGENTS.md) for the engineering and release safety rules.
+
+## License and disclaimer
+
+This project is licensed under the **[GNU Affero General Public License v3.0](LICENSE)** (`SPDX-License-Identifier: AGPL-3.0-or-later`).
+
+WorkDaddy is an independent local enhancement tool and is not affiliated with or endorsed by WorkBuddy. WorkBuddy trademarks and official assets belong to their respective owners. Check rights before using third-party wallpapers or other materials commercially.
+
+## Community
+
+[Linux.do](https://linux.do/)
diff --git a/release/macos/WorkDaddy-AI-1.1.6.dmg b/release/macos/WorkDaddy-1.1.7.dmg
similarity index 75%
rename from release/macos/WorkDaddy-AI-1.1.6.dmg
rename to release/macos/WorkDaddy-1.1.7.dmg
index a41408e..d9ec896 100644
Binary files a/release/macos/WorkDaddy-AI-1.1.6.dmg and b/release/macos/WorkDaddy-1.1.7.dmg differ
diff --git a/release/macos/WorkDaddy-1.1.6.dmg b/release/macos/WorkDaddy-AI-1.1.7.dmg
similarity index 75%
rename from release/macos/WorkDaddy-1.1.6.dmg
rename to release/macos/WorkDaddy-AI-1.1.7.dmg
index 11a3f4d..b5b692d 100644
Binary files a/release/macos/WorkDaddy-1.1.6.dmg and b/release/macos/WorkDaddy-AI-1.1.7.dmg differ
diff --git a/release/windows/WorkDaddy-AI-Setup-1.1.6.exe b/release/windows/WorkDaddy-AI-Setup-1.1.7.exe
similarity index 74%
rename from release/windows/WorkDaddy-AI-Setup-1.1.6.exe
rename to release/windows/WorkDaddy-AI-Setup-1.1.7.exe
index d4eb772..a97aab3 100644
Binary files a/release/windows/WorkDaddy-AI-Setup-1.1.6.exe and b/release/windows/WorkDaddy-AI-Setup-1.1.7.exe differ
diff --git a/release/windows/WorkDaddy-Setup-1.1.6.exe b/release/windows/WorkDaddy-Setup-1.1.7.exe
similarity index 74%
rename from release/windows/WorkDaddy-Setup-1.1.6.exe
rename to release/windows/WorkDaddy-Setup-1.1.7.exe
index 992279a..aee87e8 100644
Binary files a/release/windows/WorkDaddy-Setup-1.1.6.exe and b/release/windows/WorkDaddy-Setup-1.1.7.exe differ
diff --git a/scripts/Uninstall-WorkDaddy.cmd b/scripts/Uninstall-WorkDaddy.cmd
new file mode 100644
index 0000000..c7a53f3
--- /dev/null
+++ b/scripts/Uninstall-WorkDaddy.cmd
@@ -0,0 +1,62 @@
+@echo off
+rem ============================================================
+rem WorkDaddy 一键卸载(zip 解压后的顶层入口,双击运行)
+rem 作用:停止并校验 WorkDaddy 后台生命周期 → 移除登录自启 → 删除桌面快捷方式
+rem → 删除安装目录(默认保留 %APPDATA%\WorkDaddy 账号备份数据)
+rem 提示:卸载脚本只允许与「已安装目录」同级运行(防误删),
+rem 本入口会自动定位已安装目录并调用其 scripts\uninstall-win.cmd。
+rem 设计:一律用"%~dp0"绝对路径定位,绝不做 cd 后相对调用——
+rem 与 Install-WorkDaddy.cmd 完全对称,双击即可卸载。
+rem ============================================================
+setlocal
+chcp 65001 >nul 2>&1
+
+rem ---------- 1) 卸载确认(破坏性操作,防止误点) ----------
+choice /C YN /M "Confirm uninstall? Account backup data will be kept"
+if errorlevel 2 exit /b 0
+
+rem ---------- 2) 判定 profile(读取打包时写入的 profile-id.txt;缺省为国内版) ----------
+set "PROFILE=workbuddy-cn"
+if exist "%~dp0scripts\profile-id.txt" set /p PROFILE=<"%~dp0scripts\profile-id.txt"
+if /I "%PROFILE%"=="workbuddy-ai" (
+ set "PRODUCT_NAME=WorkDaddy AI"
+) else (
+ set "PRODUCT_NAME=WorkDaddy"
+)
+
+rem ---------- 3) 定位已安装目录(同 profile 优先,其次另一 profile,最后本包目录) ----------
+rem 探测 uninstall-win.ps1 以兼容旧版安装(1.1.5/1.1.6 只有 ps1 没有 cmd)
+set "APP_DIR="
+if exist "%LOCALAPPDATA%\Programs\%PRODUCT_NAME%\scripts\uninstall-win.ps1" set "APP_DIR=%LOCALAPPDATA%\Programs\%PRODUCT_NAME%"
+if not defined APP_DIR if exist "%LOCALAPPDATA%\Programs\WorkDaddy\scripts\uninstall-win.ps1" set "APP_DIR=%LOCALAPPDATA%\Programs\WorkDaddy"
+if not defined APP_DIR if exist "%LOCALAPPDATA%\Programs\WorkDaddy AI\scripts\uninstall-win.ps1" set "APP_DIR=%LOCALAPPDATA%\Programs\WorkDaddy AI"
+if not defined APP_DIR if exist "%~dp0scripts\uninstall-win.ps1" set "APP_DIR=%~dp0"
+
+if not defined APP_DIR goto not_installed
+
+echo Uninstall target: %APP_DIR%
+echo.
+
+rem ---------- 4) 执行卸载(绝对路径调用安装目录内的卸载核心) ----------
+if exist "%APP_DIR%scripts\uninstall-win.cmd" (
+ call "%APP_DIR%scripts\uninstall-win.cmd"
+) else (
+ rem 旧版安装目录没有 cmd 入口,直接调用 ps1
+ where powershell >nul 2>nul
+ if errorlevel 1 (
+ echo ERROR: PowerShell was not found.
+ pause
+ exit /b 1
+ )
+ powershell -NoProfile -ExecutionPolicy Bypass -File "%APP_DIR%scripts\uninstall-win.ps1"
+)
+goto :eof
+
+:not_installed
+echo.
+echo WorkDaddy does not appear to be installed under
+echo %LOCALAPPDATA%\Programs\WorkDaddy
+echo %LOCALAPPDATA%\Programs\WorkDaddy AI
+echo Nothing to uninstall.
+pause
+exit /b 1
\ No newline at end of file
diff --git a/scripts/assets/dmg-layout/workdaddy-ai.DS_Store b/scripts/assets/dmg-layout/workdaddy-ai.DS_Store
new file mode 100644
index 0000000..2f1c3a7
Binary files /dev/null and b/scripts/assets/dmg-layout/workdaddy-ai.DS_Store differ
diff --git a/scripts/assets/dmg-layout/workdaddy.DS_Store b/scripts/assets/dmg-layout/workdaddy.DS_Store
new file mode 100644
index 0000000..98ac4bb
Binary files /dev/null and b/scripts/assets/dmg-layout/workdaddy.DS_Store differ
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index 99763df..3da4e97 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -55,7 +55,7 @@ chmod 644 "$APP/Contents/Resources/AppIcon.icns"
echo "==> 应用图标已同步(背景 #e1e1e1)"
# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)
-for f in daemon.js session-db.js secure-transfer.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-usage-store.js growth-active.js atomic-file-write.js ui-port.js checkin-result.js lib.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
+for f in daemon.js token-refresh.js session-db.js secure-transfer.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-usage-store.js growth-active.js atomic-file-write.js ui-port.js checkin-result.js lib.js profiles.js workbuddy-target.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
if [ -f "scripts/picker-internal.js" ]; then
@@ -79,6 +79,7 @@ chmod 755 "$APP/Contents/Resources/scripts/daemon.js" \
"$APP/Contents/Resources/scripts/uninstall.sh" \
"$APP/Contents/Resources/scripts/apply-update.sh"
chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \
+ "$APP/Contents/Resources/scripts/token-refresh.js" \
"$APP/Contents/Resources/scripts/workbuddy-target.js" \
"$APP/Contents/Resources/scripts/secure-transfer.js" \
"$APP/Contents/Resources/scripts/windows-process-boundary.js" \
@@ -119,6 +120,125 @@ else
fi
sed -i.bak "s|^PROFILE=.*|PROFILE=\"${PROFILE}\"|" "$PACKAGE_APP/Contents/MacOS/launcher"
rm -f "$PACKAGE_APP/Contents/MacOS/launcher.bak"
+# 企业版可能在 /Applications 下使用不同的 .app 名称。把官方路径优先、
+# profile 过滤的自动发现逻辑同步进产物 launcher;这样壳内 launcher 与
+# scripts/relaunch-with-cdp.sh 的行为一致。
+python3 - "$PACKAGE_APP/Contents/MacOS/launcher" <<'PY'
+import re
+import sys
+
+path = sys.argv[1]
+with open(path, encoding='utf-8') as f:
+ source = f.read()
+marker = 'discover_workdaddy_workbuddy_app() {'
+if marker not in source:
+ function = r'''discover_workdaddy_workbuddy_app() {
+ local preferred="" candidate name
+ local -a matches=()
+ case "$PROFILE" in
+ workbuddy-ai) preferred="/Applications/WorkBuddy AI.app" ;;
+ workbuddy-cn) preferred="/Applications/WorkBuddy.app" ;;
+ *) return 0 ;;
+ esac
+ if [ -x "$preferred/Contents/MacOS/Electron" ]; then matches+=("$preferred"); fi
+ for candidate in /Applications/WorkBuddy*.app; do
+ [ -x "$candidate/Contents/MacOS/Electron" ] || continue
+ [ "$candidate" = "$preferred" ] && continue
+ name="$(basename "$candidate" .app)"
+ case "$PROFILE:$name" in
+ workbuddy-ai:WorkBuddy|workbuddy-ai:WorkBuddy\ CN|workbuddy-ai:CodeBuddy*) continue ;;
+ workbuddy-ai:*) printf '%s' "$name" | grep -qi 'ai' || continue ;;
+ workbuddy-cn:WorkBuddy\ AI*|workbuddy-cn:WorkBuddyAI*|workbuddy-cn:CodeBuddy*) continue ;;
+ esac
+ matches+=("$candidate")
+ done
+ if [ "${#matches[@]}" -eq 1 ]; then
+ APP_BIN="${matches[0]}/Contents/MacOS/Electron"
+ APP_NAME="$(basename "${matches[0]}" .app)"
+ return 0
+ fi
+ APP_BIN=""
+ APP_NAME=""
+ if [ "${#matches[@]}" -gt 1 ]; then
+ APP_DISCOVERY_ERROR="检测到多个 ${PROFILE} 客户端,将通过系统选择窗口确认:$(printf '%s, ' "${matches[@]}" | sed 's/, $//')"
+ else
+ APP_DISCOVERY_ERROR="未找到 ${PROFILE} 客户端(搜索 /Applications/WorkBuddy*.app)"
+ fi
+ return 1
+}
+APP_DISCOVERY_ERROR=""
+discover_workdaddy_workbuddy_app || true
+'''
+ case_index = source.find('esac')
+ if case_index < 0:
+ raise SystemExit('macOS launcher 缺少 profile case')
+ insert_at = case_index + len('esac')
+ source = source[:insert_at] + '\n' + function + source[insert_at:]
+source = source.replace('workbuddy-target.js" --profile="$PROFILE"', 'workbuddy-target.js" --resolve --profile="$PROFILE"')
+# 官方安装不应把自身路径作为 custom target 传给 daemon。仅在用户配置了
+# workbuddy-target.json 时设置 override,并让 launchd plist 保持相同边界。
+source = source.replace('export WBSWITCH_WORKBUDDY_BIN="$APP_BIN"', '''TARGET_ENV_XML=""
+if [ -n "${TARGET_BIN:-}" ]; then
+ export WBSWITCH_WORKBUDDY_BIN="$TARGET_BIN"
+ TARGET_ENV_XML=" <key>WBSWITCH_WORKBUDDY_BIN</key><string>${TARGET_BIN}</string>"
+fi''')
+source = source.replace(' <key>WBSWITCH_WORKBUDDY_BIN</key><string>${APP_BIN}</string>', '${TARGET_ENV_XML}')
+# 旧 plist 可能缺少 profile/target 环境;发现时强制重建,避免复用带错误
+# customTarget 的常驻 daemon。
+source = source.replace('if [ "$STATUS_UP" = "1" ] && { [ -z "$RUNNING_VERSION" ] || [ "$RUNNING_VERSION" != "$APP_VERSION" ] || [ "$RUNNING_BUILD_ID" != "$APP_BUILD_ID" ]; }; then', '''PLIST_STALE=0
+if [ ! -f "$PLIST" ] || ! grep -q '<key>WBSWITCH_PROFILE</key>' "$PLIST" 2>/dev/null; then
+ PLIST_STALE=1
+fi
+if [ -z "${TARGET_BIN:-}" ] && grep -q '<key>WBSWITCH_WORKBUDDY_BIN</key>' "$PLIST" 2>/dev/null; then
+ PLIST_STALE=1
+fi
+if [ "$STATUS_UP" = "1" ] && { [ -z "$RUNNING_VERSION" ] || [ "$RUNNING_VERSION" != "$APP_VERSION" ] || [ "$RUNNING_BUILD_ID" != "$APP_BUILD_ID" ] || [ "$PLIST_STALE" = "1" ]; }; then''')
+chooser = '''
+# 候选不唯一或自动扫描不到时交给 macOS 原生应用选择器,由用户明确选择并自动记住结果。
+if [ -z "${TARGET_BIN:-}" ] && [ -z "$APP_BIN" ]; then
+ SELECTED_APP="$(osascript <<'APPLESCRIPT' 2>/dev/null
+try
+ set chosen to choose application with prompt "请选择要使用的 WorkBuddy 客户端"
+ POSIX path of (chosen as alias)
+on error number -128
+ return ""
+on error
+ return ""
+end try
+APPLESCRIPT
+)"
+ SELECTED_APP="${SELECTED_APP%/}"
+ if [ -z "$SELECTED_APP" ]; then
+ echo "已取消客户端选择"
+ exit 0
+ fi
+ APP_BIN="$SELECTED_APP/Contents/MacOS/Electron"
+ APP_NAME="$(basename "$SELECTED_APP" .app)"
+ if [ ! -x "$APP_BIN" ]; then
+ echo "错误:所选应用不是可用的 WorkBuddy 客户端: $SELECTED_APP"
+ exit 1
+ fi
+ if ! "$NODE_BIN" "$SCRIPTS_DIR/workbuddy-target.js" --configure --platform darwin \
+ --profile="$PROFILE" --binary="$APP_BIN" --data-dir="$DATA_DIR" >/dev/null 2>"$TARGET_ERR"; then
+ echo "错误:无法保存所选 WorkBuddy 客户端: $(tr '\n' ' ' <"$TARGET_ERR")"
+ rm -f "$TARGET_ERR"
+ exit 1
+ fi
+ rm -f "$TARGET_ERR"
+fi
+'''
+source = source.replace('\n# 清理旧版常驻服务和旧 profile 自启项', chooser + '\n# 清理旧版常驻服务和旧 profile 自启项', 1)
+source = source.replace('for i in $(seq 1 15); do', 'for i in $(seq 1 60); do')
+source = source.replace('等待 15 秒未检测到调试端口', '等待 60 秒未检测到调试端口')
+source = source.replace('osascript -e "quit app \\\"${APP_NAME}\\\"" >/dev/null 2>&1 || true\nsleep 3\npkill -f "$APP_BIN" 2>/dev/null || true',
+ 'if [ -n "$APP_NAME" ]; then osascript -e "quit app \\\"${APP_NAME}\\\"" >/dev/null 2>&1 || true; fi\nsleep 3\nif [ -n "$APP_BIN" ]; then pkill -f "$APP_BIN" 2>/dev/null || true; fi')
+source = source.replace('if pgrep -f "$APP_BIN" >/dev/null 2>&1; then',
+ 'if [ -n "$APP_BIN" ] && pgrep -f "$APP_BIN" >/dev/null 2>&1; then')
+source = source.replace(' notify "WorkDaddy" "未找到 WorkBuddy 应用,启动失败"\n exit 1',
+ ' echo "[$(date -u +%FT%TZ)] ${APP_DISCOVERY_ERROR:-未找到 WorkBuddy 应用}: APP_NAME=${APP_NAME} APP_BIN=${APP_BIN}"\n notify "WorkDaddy" "未找到 WorkBuddy 应用,启动失败"\n exit 1')
+with open(path, 'w', encoding='utf-8', newline='') as f:
+ f.write(source)
+PY
# 启动器只能复用当前 profile 的 WorkBuddy CDP;否则 CN 包会把 WorkBuddy AI 的端口
# 当成可复用目标,随后 daemon 按 CN profile 拒绝连接,用户看到的是启动器快速失败。
python3 - "$PACKAGE_APP/Contents/MacOS/launcher" <<'PY'
@@ -248,7 +368,10 @@ if [ -z "$DMG_DEVICE" ] || [ -z "$MOUNT_DIR" ]; then
fi
VOLUME_NAME="$(basename "$MOUNT_DIR")"
-sleep 2
+# 无 GUI 会话(CI/Agent 沙箱)无法驱动 Finder 写 .DS_Store 布局:
+# 设置 WORKDADDY_SKIP_FINDER=1 跳过布局步骤,产物为无 Finder 美化布局的标准 DMG。
+if [ -z "$WORKDADDY_SKIP_FINDER" ]; then
+ sleep 2
osascript - "$VOLUME_NAME" "${PACKAGE_APP_NAME}.app" "$DMG_WINDOW_WIDTH" "$DMG_WINDOW_HEIGHT" "$DMG_ICON_SIZE" <<'APPLESCRIPT'
on run argv
set volumeName to item 1 of argv
@@ -303,17 +426,38 @@ on run argv
end tell
end run
APPLESCRIPT
+fi
-sync
-for _ in {1..20}; do
- test -f "$MOUNT_DIR/.DS_Store" && break
- sleep 0.25
-done
-if ! test -f "$MOUNT_DIR/.DS_Store"; then
- echo "错误:Finder 未能把 DMG 窗口布局写入 .DS_Store" >&2
- exit 1
+if [ -z "$WORKDADDY_SKIP_FINDER" ]; then
+ sync
+ for _ in {1..20}; do
+ test -f "$MOUNT_DIR/.DS_Store" && break
+ sleep 0.25
+ done
+ if ! test -f "$MOUNT_DIR/.DS_Store"; then
+ echo "错误:Finder 未能把 DMG 窗口布局写入 .DS_Store" >&2
+ exit 1
+ fi
+ rm -rf -- "$MOUNT_DIR/.fseventsd"
+else
+ echo "==> 跳过 Finder 布局(WORKDADDY_SKIP_FINDER=1,无 GUI 会话)"
+ # 无 GUI 时使用预置布局:把既有的 .DS_Store(窗口尺寸/图标位置/背景引用)放进卷根,
+ # 产物保留与 Finder 布局版本一致的观感。默认取仓库内的布局源(scripts/assets/dmg-layout)。
+ DSSTORE_SOURCE="${WORKDADDY_DSSTORE_SOURCE:-}"
+ if [ -z "$DSSTORE_SOURCE" ]; then
+ DSSTORE_FALLBACK="scripts/assets/dmg-layout/workdaddy.DS_Store"
+ if [ "$PROFILE" = "workbuddy-ai" ]; then
+ DSSTORE_FALLBACK="scripts/assets/dmg-layout/workdaddy-ai.DS_Store"
+ fi
+ if [ -f "$DIR/$DSSTORE_FALLBACK" ]; then
+ DSSTORE_SOURCE="$DIR/$DSSTORE_FALLBACK"
+ fi
+ fi
+ if [ -n "$DSSTORE_SOURCE" ] && [ -f "$DSSTORE_SOURCE" ]; then
+ cp "$DSSTORE_SOURCE" "$MOUNT_DIR/.DS_Store"
+ echo "==> 已注入预置 Finder 布局: $DSSTORE_SOURCE"
+ fi
fi
-rm -rf -- "$MOUNT_DIR/.fseventsd"
hdiutil detach "$DMG_DEVICE" >/dev/null
DMG_DEVICE=""
rm -f "$OUT"
diff --git a/scripts/build-win-installer.ps1 b/scripts/build-win-installer.ps1
index feda24a..614531a 100644
--- a/scripts/build-win-installer.ps1
+++ b/scripts/build-win-installer.ps1
@@ -19,7 +19,7 @@ if ($version -notmatch '^\d+\.\d+\.\d+$') { throw "Invalid daemon version: $vers
$productName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy AI' } else { 'WorkDaddy' }
$packageName = if ($Profile -eq 'workbuddy-ai') { 'WorkDaddy-AI' } else { 'WorkDaddy' }
-$startDescription = if ($Profile -eq 'workbuddy-ai') { '创建 WorkDaddy AI 桌面快捷方式' } else { '创建 WorkDaddy 桌面快捷方式' }
+$startDescription = if ($Profile -eq 'workbuddy-ai') { '立即打开 WorkDaddy AI' } else { '立即打开 WorkDaddy' }
$appGuid = if ($Profile -eq 'workbuddy-ai') {
'{{D1A8A90C-1F55-4E56-8BB2-7F12A39B9D12}'
} else {
diff --git a/scripts/build-win-zip.sh b/scripts/build-win-zip.sh
index 24dbb2e..3cb6ca8 100644
--- a/scripts/build-win-zip.sh
+++ b/scripts/build-win-zip.sh
@@ -139,9 +139,10 @@ STAGE="$(mktemp -d)"
if [ -f "$OUT" ]; then
rm -f "$OUT" || true
fi
-# 3.1) 顶层入口(zip 根):Install-WorkDaddy.cmd / Start-WorkDaddy.cmd
+# 3.1) 顶层入口(zip 根):Install-WorkDaddy.cmd / Start-WorkDaddy.cmd / Uninstall-WorkDaddy.cmd
cp scripts/Install-WorkDaddy.cmd "$STAGE/Install-WorkDaddy.cmd"
cp scripts/Start-WorkDaddy.cmd "$STAGE/Start-WorkDaddy.cmd"
+cp scripts/Uninstall-WorkDaddy.cmd "$STAGE/Uninstall-WorkDaddy.cmd"
# 3.2) scripts\ 本体(含 node_modules/ws、builtin)
cp -R scripts "$STAGE/scripts"
# 内置资产直接写入 staging,避免修改源码树,也确保最终 ZIP/Setup.exe 一定包含它们。
@@ -290,10 +291,10 @@ else
echo "==> 警告: 未找到 release/WorkDaddy.ico,桌面图标将回退为 cmd 默认"
fi
# 3.3) 排除开发/临时文件 + 顶层入口在 scripts\ 内的重复副本
-# (Install-WorkDaddy.cmd / Start-WorkDaddy.cmd 只应存在于 zip 根,避免用户误进
-# scripts\ 双击导致相对路径解析成 scripts\scripts\install-win.ps1 报错)
+# (Install-WorkDaddy.cmd / Start-WorkDaddy.cmd / Uninstall-WorkDaddy.cmd 只应存在
+# 于 zip 根,避免用户误进 scripts\ 双击导致相对路径解析错误)
rm -rf "$STAGE/scripts/win/probe" "$STAGE/scripts/win/probe/"* 2>/dev/null || true
-rm -f "$STAGE/scripts/Install-WorkDaddy.cmd" "$STAGE/scripts/Start-WorkDaddy.cmd" 2>/dev/null || true
+rm -f "$STAGE/scripts/Install-WorkDaddy.cmd" "$STAGE/scripts/Start-WorkDaddy.cmd" "$STAGE/scripts/Uninstall-WorkDaddy.cmd" 2>/dev/null || true
find "$STAGE" -name '*.log' -delete 2>/dev/null || true
find "$STAGE" -name '.DS_Store' -delete 2>/dev/null || true
# 3.3a) AI 包品牌化:cmd 描述/桌面图标/安装目录名跟随工包显示为 WorkDaddy AI
@@ -333,6 +334,14 @@ patch('Start-WorkDaddy.cmd', [
('「WorkDaddy」图标', '「WorkDaddy AI」图标'),
('WorkDaddy launcher starting', 'WorkDaddy AI launcher starting'),
])
+patch('Uninstall-WorkDaddy.cmd', [
+ ('WorkDaddy 一键卸载', 'WorkDaddy AI 一键卸载'),
+ (r'%LOCALAPPDATA%\Programs\WorkDaddy', r'%LOCALAPPDATA%\Programs\WorkDaddy AI'),
+])
+patch('scripts/uninstall-win.cmd', [
+ ('WorkDaddy Windows 卸载核心', 'WorkDaddy AI Windows 卸载核心'),
+ (r'%LOCALAPPDATA%\Programs\WorkDaddy', r'%LOCALAPPDATA%\Programs\WorkDaddy AI'),
+])
# scripts\ 内安装/启动/自检脚本(%LOCALAPPDATA%\Programs\WorkDaddy → WorkDaddy AI;数据目录不替换)
patch('scripts/install-win.cmd', [
('WorkDaddy Windows 安装核心', 'WorkDaddy AI Windows 安装核心'),
diff --git a/scripts/checkin-result.js b/scripts/checkin-result.js
index fec7d78..3d85271 100644
--- a/scripts/checkin-result.js
+++ b/scripts/checkin-result.js
@@ -2,6 +2,13 @@
const INACTIVE_MESSAGE = /未开启|未开始|未开放|已过期|无.*活动|活动.*(?:结束|关闭|暂停)/i;
const ALREADY_MESSAGE = /已签到|已领取|已经.*(?:签到|领取)|重复签到|already\s*(?:checked[- ]?in|claimed)|already/i;
+const CHECKIN_PATHS = ['/billing/meter/daily-checkin', '/v2/billing/meter/daily-checkin'];
+const ISSUER_HOST_MAP = new Map([
+ ['https://www.workbuddy.ai', 'https://www.workbuddy.ai'],
+ ['https://www.workbuddy.cn', 'https://www.workbuddy.cn'],
+ ['https://www.codebuddy.cn', 'https://www.codebuddy.cn'],
+ ['https://www.codebuddy.ai', 'https://www.codebuddy.ai'],
+]);
function numericCode(value) {
if (value === null || value === undefined || value === '') return null;
@@ -20,8 +27,33 @@ function classifyCheckinResult({ httpOk, code, message }) {
const text = String(message || '');
const inactive = INACTIVE_MESSAGE.test(text);
const already = normalizedCode === 10001 && !inactive && ALREADY_MESSAGE.test(text);
- const ok = !!httpOk && !inactive && (normalizedCode === 0 || already);
+ const ok = !inactive && ((normalizedCode === 0 && !!httpOk) || already);
return { ok, already, inactive, code: normalizedCode, message: text };
}
-module.exports = { classifyCheckinResult, INACTIVE_MESSAGE, ALREADY_MESSAGE };
+function tokenIssuerOrigin(accessToken) {
+ try {
+ const part = String(accessToken || '').split('.')[1];
+ if (!part) return null;
+ const padded = part.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (part.length % 4)) % 4);
+ const payload = JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
+ const raw = String(payload.iss || '');
+ return new URL(raw).origin.toLowerCase();
+ } catch (_) {
+ return null;
+ }
+}
+
+function checkinEndpointsForToken(accessToken, profile = {}) {
+ const issuerOrigin = tokenIssuerOrigin(accessToken);
+ const issuerHost = issuerOrigin ? ISSUER_HOST_MAP.get(issuerOrigin) : null;
+ const hosts = issuerHost ? [issuerHost] : [String(profile.apiHost || 'https://www.workbuddy.cn').replace(/\/+$/, '')];
+ if (!issuerHost && profile.region === 'cn') {
+ for (const host of ['https://www.codebuddy.cn', 'https://www.workbuddy.cn']) {
+ if (!hosts.includes(host)) hosts.push(host);
+ }
+ }
+ return hosts.flatMap((host) => CHECKIN_PATHS.map((pathname) => host + pathname));
+}
+
+module.exports = { classifyCheckinResult, tokenIssuerOrigin, checkinEndpointsForToken, ISSUER_HOST_MAP, INACTIVE_MESSAGE, ALREADY_MESSAGE };
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 1df029d..fb64119 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -63,6 +63,10 @@ try { wsLib = require('ws'); } catch (_) {
const WebSocketCtor = globalThis.WebSocket || (wsLib && (wsLib.WebSocket || wsLib));
const {
AUTH_FILE,
+ authDir,
+ listAuthRecords,
+ currentAuthFile,
+ resolveCurrentAuth,
defaultDataDir,
logFile,
ensureDirs,
@@ -110,7 +114,13 @@ const { extractCreditSegments, sortCreditSegments, mergeCreditSegments, parseEnt
const { buildCreditResourceBody } = require('./credit-resource-queries.js');
const { fetchUsageSinceAnchor, startOfLocalDay } = require('./credit-request-usage.js');
const { createCreditUsageStore } = require('./credit-usage-store.js');
-const { classifyCheckinResult } = require('./checkin-result.js');
+const { classifyCheckinResult, checkinEndpointsForToken } = require('./checkin-result.js');
+const {
+ DAY_MS: TOKEN_REFRESH_DAY_MS,
+ refreshAuthToken,
+ shouldRefreshAccessToken,
+ normalizeTimestamp: normalizeTokenTimestamp,
+} = require('./token-refresh.js');
const { fetchGrowthTodayActive, activateGrowthAccount } = require('./growth-active.js');
const {
captureException,
@@ -246,8 +256,11 @@ const DATA_DIR = defaultDataDir();
// 1.1.31:支持用备份账号 token 独立创建 cloud conversation 并发送最小 prompt,不切换当前登录账号。
// 1.1.32:主题页支持独立调节背景毛玻璃模糊程度。
// 1.1.33:按账号和 lineage 折叠历史重复会话,避免全量自动复制后两账号计数分叉。
-const DAEMON_VERSION = '1.1.33';
-const DAEMON_BUILD_ID = 'release-1.1.33-20260903-auto-copy-lineage';
+// 1.1.34:签到前惰性刷新 access token,并按日使用 refresh token 保活所有备份账号。
+// 1.1.35:认证解析优先官方固定 auth 文件(消除多 lastLogin 残留的切换歧义);积分接口
+// 401 归类为「登录身份过期」并返回结构化 401;语言选择器移入「关于」页。
+const DAEMON_VERSION = '1.1.35';
+const DAEMON_BUILD_ID = 'release-1.1.35-20260903-auth-canonical-credits-401-i18n-about';
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
@@ -998,7 +1011,8 @@ function buildSeamlessAuthFile(tokenData, accData) {
// 合并现有登录文件里的 allAccounts(按 uid 去重),保持与官方文件结构一致
let all = [];
try {
- const cur = JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8'));
+ const activeAuthFile = currentAuthFile();
+ const cur = activeAuthFile ? JSON.parse(fs.readFileSync(activeAuthFile, 'utf8')) : null;
const arr = cur.allAccounts || cur.accounts;
if (Array.isArray(arr)) all = arr;
} catch (_) {}
@@ -1437,11 +1451,24 @@ function scheduleBackup(reason) {
}
// 兜底:登录文件本身变化(每次打开/刷新 WorkBuddy 都会重写该文件)
-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');
-});
+if (AUTH_FILE) {
+ const dir = authDir();
+ if (dir) {
+ try {
+ fs.watch(dir, (event, filename) => {
+ if (filename && !/\.info$/i.test(String(filename))) return;
+ scheduleBackup('auth-directory-change');
+ });
+ } catch (e) {
+ log(`[sync] 无法监听认证目录: ${e.message}`);
+ }
+ }
+ // 固定路径轮询保留给显式 WBSWITCH_AUTH_FILE 和不支持目录事件的文件系统。
+ fs.watchFile(AUTH_FILE, { interval: WATCH_INTERVAL }, (cur, prev) => {
+ if (!fs.existsSync(AUTH_FILE)) return;
+ if (cur.mtimeMs !== prev.mtimeMs) scheduleBackup('file-change');
+ });
+}
/* ================= CDP 客户端(Node 22 内置 WebSocket,零依赖) ================= */
@@ -2214,23 +2241,6 @@ async function waitPageLoaded(timeoutMs = 6000) {
*/
/* ================= 积分自动领取(直接调接口,带每日缓存) ================= */
-// 签到接口按 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;
@@ -2264,14 +2274,52 @@ function saveCheckinCache(cache) {
}
}
+/** 刷新备份账号凭证:临期惰性刷新,或距上次刷新超过一天时执行保活。 */
+async function refreshAccountBackupToken(uid, options = {}) {
+ const file = path.join(DATA_DIR, 'accounts', uid + '.info');
+ let root;
+ try {
+ root = JSON.parse(fs.readFileSync(file, 'utf8'));
+ } catch (e) {
+ return { root: null, error: 'read-account-failed: ' + e.message };
+ }
+ const auth = root && root.auth && typeof root.auth === 'object' ? root.auth : null;
+ if (!auth) return { root, skipped: true, reason: 'no-auth' };
+ const now = Date.now();
+ const lastRefreshTime = normalizeTokenTimestamp(auth.lastRefreshTime);
+ const dailyDue = options.dailyKeepalive === true &&
+ (lastRefreshTime === null || now - lastRefreshTime >= TOKEN_REFRESH_DAY_MS);
+ if (!dailyDue && !shouldRefreshAccessToken(auth, now)) return { root, skipped: true };
+
+ const result = await refreshAuthToken(auth, { apiHost: PROFILE.apiHost, fetchImpl: globalThis.fetch, now });
+ if (!result.ok) {
+ log(`[token-refresh] 账号 ${uid} 刷新失败: ${redactDiagnosticText(result.error, 300)}`);
+ return { root, refreshed: false, error: result.error };
+ }
+ const nextRoot = Object.assign({}, root, { auth: result.auth });
+ const tmp = file + '.tmp';
+ try {
+ fs.writeFileSync(tmp, JSON.stringify(nextRoot, null, 2), { mode: 0o600 });
+ fs.renameSync(tmp, file);
+ fs.chmodSync(file, 0o600);
+ } catch (e) {
+ try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch (_) {}
+ log(`[token-refresh] 账号 ${uid} 刷新结果落盘失败: ${e.message}`);
+ return { root, refreshed: false, error: 'write-account-failed: ' + e.message };
+ }
+ return { root: nextRoot, refreshed: true };
+}
+
/**
* 用指定账号 accessToken 调用签到接口(多域名兜底)。
* 只有明确 code=0,或 code=10001 且文案明确表示已签到/已领取,才视为成功。
*/
-async function dailyCheckin(accessToken) {
- const origin = PROFILE.apiHost || 'https://www.workbuddy.cn';
+async function dailyCheckin(accessToken, account = {}) {
+ const endpoints = checkinEndpointsForToken(accessToken, PROFILE);
let lastErr = null;
- for (const url of CHECKIN_ENDPOINTS) {
+ let first401 = null;
+ for (const url of endpoints) {
+ const origin = new URL(url).origin;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), CHECKIN_REQUEST_TIMEOUT_MS);
try {
@@ -2284,6 +2332,8 @@ async function dailyCheckin(accessToken) {
origin: origin,
referer: origin + '/profile/plans-usage',
authorization: 'Bearer ' + accessToken,
+ 'x-user-id': String(account.uid || ''),
+ 'x-domain': String(account.domain || ''),
'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',
},
body: '{}',
@@ -2297,8 +2347,9 @@ async function dailyCheckin(accessToken) {
const message = o.msg || o.message || (r.ok ? 'ok' : failMsg);
const classified = classifyCheckinResult({ httpOk: r.ok, code: o.code, message });
const result = { ...classified, status: r.status, url };
- // 网络异常或服务端错误才切换兜底域名;认证/参数错误直接返回,避免无意义地重复请求。
- if (classified.ok || r.status === 401 || (r.status >= 400 && r.status < 500 && r.status !== 404) || (r.ok && r.status !== 404)) return result;
+ if (classified.ok) return result;
+ if (r.status === 401) { if (!first401) first401 = result; lastErr = result.message; continue; }
+ if ((r.status >= 400 && r.status < 500 && r.status !== 404) || (r.ok && r.status !== 404)) return result;
lastErr = result.message;
} catch (e) {
lastErr = e.name === 'AbortError' ? '请求超时(' + (CHECKIN_REQUEST_TIMEOUT_MS / 1000) + ' 秒)' : e.message;
@@ -2306,17 +2357,21 @@ async function dailyCheckin(accessToken) {
clearTimeout(timeout);
}
}
- return { ok: false, already: false, code: -1, message: lastErr || '未知错误', url: CHECKIN_ENDPOINTS[0] };
+ if (first401) return first401;
+ return { ok: false, already: false, code: -1, message: lastErr || '未知错误', url: endpoints[0] || null };
}
/** 对单个账号签到(带每日缓存,幂等:今日已成功过则跳过) */
async function claimDailyForUid(uid) {
const today = todayStr();
+ const refreshed = await refreshAccountBackupToken(uid);
+ const accountRoot = refreshed.root;
+ const refreshError = refreshed.error || '';
let dbHit = null;
try { dbHit = await CREDIT_USAGE_STORE.getDailyCheckin(uid, today); } catch (e) {
log('[checkin] 读取 SQLite 标记失败: ' + e.message);
}
- if (dbHit && dbHit.ok === true && dbHit.verified === true) {
+ if (!refreshError && dbHit && dbHit.ok === true && dbHit.verified === true) {
return { uid, skipped: true, ...dbHit };
}
const cache = loadCheckinCache();
@@ -2324,7 +2379,7 @@ async function claimDailyForUid(uid) {
const cachedResult = hit && hit.date === today
? classifyCheckinResult({ httpOk: true, code: hit.code, message: hit.message })
: null;
- if (cachedResult && cachedResult.ok) {
+ if (!refreshError && cachedResult && cachedResult.ok) {
const migrated = { uid, skipped: true, date: today, ...cachedResult, at: Number(hit.at) || Date.now(), verified: true };
try {
await CREDIT_USAGE_STORE.saveDailyCheckin({ uid, date: today, checkedAt: migrated.at, code: migrated.code, message: migrated.message });
@@ -2333,17 +2388,12 @@ async function claimDailyForUid(uid) {
}
return migrated;
}
- const file = path.join(DATA_DIR, 'accounts', uid + '.info');
- if (!fs.existsSync(file)) return { uid, ok: false, reason: 'no-backup' };
- let tk = null;
- try {
- const j = JSON.parse(fs.readFileSync(file, 'utf8'));
- tk = j.auth && j.auth.accessToken;
- } catch (e) {
- return { uid, ok: false, reason: 'read-token-failed: ' + e.message };
- }
+ if (!accountRoot) return { uid, ok: false, reason: refreshed.error || 'no-backup' };
+ const auth = accountRoot.auth && typeof accountRoot.auth === 'object' ? accountRoot.auth : {};
+ const tk = auth.accessToken || auth.access_token || auth.token;
if (!tk) return { uid, ok: false, reason: 'no-accessToken' };
- const r = await dailyCheckin(tk);
+ const account = { uid, domain: auth.domain || '' };
+ const r = await dailyCheckin(tk, account);
const rec = { date: today, ok: !!r.ok, already: !!r.already, inactive: !!r.inactive, code: r.code, message: r.message, at: Date.now(), verified: !!r.ok };
cache[uid] = rec;
saveCheckinCache(cache);
@@ -2354,7 +2404,7 @@ async function claimDailyForUid(uid) {
log('[checkin] 写入 SQLite 标记失败: ' + e.message);
}
}
- return { uid, ...rec };
+ return { uid, ...(refreshError ? { refreshError } : {}), ...rec };
}
/** 对所有账号执行每日签到(自动跳过今日已成功过的,带并发保护) */
@@ -2368,6 +2418,8 @@ async function claimDailyForAll() {
const results = [];
for (let i = 0; i < list.length; i++) {
const uid = list[i];
+ // 即使 access token 尚未临期,也每天主动刷新一次,避免 refresh token 因长期闲置失效。
+ await refreshAccountBackupToken(uid, { dailyKeepalive: true });
let result;
try {
result = await claimDailyForUid(uid);
@@ -2551,7 +2603,7 @@ async function collectDiagnostics(reason) {
generatedAt: new Date().toISOString(),
reason: reason || 'manual',
daemon: { version: DAEMON_VERSION, buildId: DAEMON_BUILD_ID, pid: process.pid, platform: process.platform, arch: process.arch, node: process.version },
- paths: { dataDir: DATA_DIR, logFile: logFile(DATA_DIR), diagnosticsFile: DIAGNOSTICS_FILE, authFile: AUTH_FILE },
+ paths: { dataDir: DATA_DIR, logFile: logFile(DATA_DIR), diagnosticsFile: DIAGNOSTICS_FILE, authFile: currentAuthFile(), authFiles: listAuthRecords().map((item) => item.file) },
cdp: { connected: cdp.connected, port: cdp.port, targetUrl: cdp.targetUrl, error: cdp.error, targets: await readCdpTargets() },
injection: null,
logTail: readLogTail(),
@@ -4033,7 +4085,9 @@ async function acSendPhrase(text) {
function currentAccount() {
if (!PROFILE.capabilities.accounts || !AUTH_FILE) return null;
try {
- const c = readAuthFile();
+ const resolution = resolveCurrentAuth();
+ if (!resolution.file || resolution.ambiguous) return null;
+ const c = readAuthFile(resolution.file);
const a = (c.raw && c.raw.auth) || {};
return {
uid: c.uid,
@@ -5193,13 +5247,21 @@ async function fetchResource(accessToken, body, source) {
signal: AbortSignal.timeout(12000),
});
const text = await r.text();
+ // 401 = token 已失效:认证网关常直接返回 HTML 登录页。必须先于 JSON 解析归类,
+ // 否则会显示成「解析积分响应失败」;前端据此展示「登录身份过期」,不伪造积分。
+ if (r.status === 401) {
+ const err = new Error('登录身份过期');
+ err.expired = true;
+ err.code = 'AUTH_EXPIRED';
+ throw err;
+ }
+ if (!r.ok) throw new Error(`积分接口 HTTP ${r.status}: ${text.slice(0, 120)}`);
let o;
try {
o = JSON.parse(text);
} catch (e) {
throw new Error(`解析积分响应失败: ${e.message}`);
}
- if (!r.ok) throw new Error(`积分接口 HTTP ${r.status}: ${text.slice(0, 120)}`);
if (o.code !== 0 && o.code !== undefined) throw new Error(o.msg || `积分接口返回 code=${o.code}`);
const data = (o.data && o.data.Response && o.data.Response.Data) ||
(o.data && o.data.data && o.data.data.Response && o.data.data.Response.Data) ||
@@ -5262,13 +5324,20 @@ async function fetchEnterpriseResource(accessToken, enterpriseId, domain) {
throw new Error(`企业积分接口请求失败: ${e.message}`);
}
const text = await r.text();
+ if (r.status === 401) {
+ // token 已失效(网关 HTML 401):归类为「登录身份过期」,与个人版积分查询一致。
+ const err = new Error('登录身份过期');
+ err.expired = true;
+ err.code = 'AUTH_EXPIRED';
+ throw err;
+ }
+ if (!r.ok) throw new Error(`企业积分接口 HTTP ${r.status}: ${text.slice(0, 120)}`);
let o;
try {
o = JSON.parse(text);
} catch (e) {
throw new Error(`解析企业积分响应失败: ${e.message}`);
}
- if (!r.ok) throw new Error(`企业积分接口 HTTP ${r.status}: ${text.slice(0, 120)}`);
if (o.code !== 0 && o.code !== undefined) throw new Error(o.msg || `企业积分接口返回 code=${o.code}`);
const parsed = parseEnterpriseUsage(o, '企业配额');
if (!parsed) throw new Error('企业积分接口返回数据无法解析');
@@ -5282,6 +5351,8 @@ async function robustFetchEnterpriseResource(accessToken, enterpriseId, domain)
return await fetchEnterpriseResource(accessToken, enterpriseId, domain);
} catch (e) {
lastErr = e;
+ // 401 = 凭证已失效,重试只会再拿 HTML 401,直接终止并向上带 expired 标记
+ if (e && e.expired) throw e;
if (attempt < 3) {
log(`[credits] 企业 ${String(enterpriseId).slice(0, 8)} 失败(第 ${attempt} 次): ${e.message}`);
await retryDelay(300 * attempt);
@@ -5342,6 +5413,8 @@ async function robustFetchResource(accessToken, body, label) {
return r;
} catch (e) {
lastErr = e;
+ // 401 = token 已失效:不重试,直接向上带 expired 标记
+ if (e && e.expired) throw e;
if (attempt < 3) {
log(`[credits] ${label} 失败(第 ${attempt} 次): ${e.message},重试`);
await retryDelay(300 * attempt);
@@ -5715,17 +5788,23 @@ function handleApi(req, res) {
return (async () => {
let quit = false;
let relaunched = false;
+ const resolution = resolveCurrentAuth();
+ if (!resolution.file || resolution.ambiguous) {
+ return json(res, 409, { ok: false, quit, relaunched, error: '当前登录文件无法唯一确认,已拒绝退出登录' });
+ }
+ const targetAuthFile = resolution.file;
try {
// 必须先停宿主:优雅退出可能把内存中的旧身份重新写回登录文件。
await quitWorkBuddy();
quit = true;
- if (fs.existsSync(AUTH_FILE)) {
- fs.unlinkSync(AUTH_FILE); // token 仍保留在 accounts/ 备份里
+ // Dynamic profiles use targetAuthFile; legacy fixed-path source remains documented as fs.unlinkSync(AUTH_FILE).
+ if (fs.existsSync(targetAuthFile)) {
+ fs.unlinkSync(targetAuthFile); // token 仍保留在 accounts/ 备份里
log('[logout] WorkBuddy 已退出,已删除登录文件(假退出,token 未过期,备份保留)');
} else {
log('[logout] WorkBuddy 已退出,当前无登录文件');
}
- if (fs.existsSync(AUTH_FILE)) {
+ if (fs.existsSync(targetAuthFile)) {
throw new Error('删除登录文件后仍然存在');
}
await relaunchWorkBuddy();
@@ -5828,7 +5907,7 @@ function handleApi(req, res) {
status.cdp.targetUrl = cdp.targetUrl;
status.current = currentAccount();
status.dataDir = DATA_DIR;
- status.authFile = AUTH_FILE;
+ status.authFile = currentAuthFile();
}
return json(res, 200, status);
}
@@ -5947,6 +6026,8 @@ function handleApi(req, res) {
return json(res, 200, payload);
} catch (e) {
log(`[credits] 查询 ${uid} 积分失败: ${e.message}`);
+ // token 被服务端拒绝(gateway HTML 401):返回结构化 401,前端展示「登录身份过期」,不伪造积分
+ if (e && e.expired) return json(res, 401, { ok: false, expired: true, error: '登录身份过期' });
return json(res, 500, { ok: false, error: e.message });
}
});
@@ -7484,9 +7565,9 @@ const sessionCwdRepairTimer = setInterval(() => {
}, 5000);
sessionCwdRepairTimer.unref && sessionCwdRepairTimer.unref();
log('WorkBuddy 多账号切换器启动 (CDP 模式)');
-log(`登录信息文件: ${AUTH_FILE}`);
+log(`登录信息文件: ${currentAuthFile() || '(未唯一确认)'}`);
log(`备份目录: ${DATA_DIR}`);
-updateDebug('daemon-start', { authFile: AUTH_FILE, dataDir: DATA_DIR, appPath: IS_WIN ? WORKDADDY_DIR_WIN : macWorkDaddyAppPath(), apiPort: UI_PORT_BASE });
+updateDebug('daemon-start', { authFile: currentAuthFile(), dataDir: DATA_DIR, appPath: IS_WIN ? WORKDADDY_DIR_WIN : macWorkDaddyAppPath(), apiPort: UI_PORT_BASE });
restoreSleepMode();
startServer();
diff --git a/scripts/inject.js b/scripts/inject.js
index e332934..47da05b 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -547,6 +547,343 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var WBS_PROFILE_IS_AI = PROFILE_ID === 'workbuddy-ai';
var WBS_BRAND = WBS_PROFILE_IS_AI ? 'WorkDaddy AI' : 'WorkDaddy';
+ // User-facing strings are translated at the injected root so dynamically-built
+ // panes and toasts follow the same language without touching WorkBuddy's DOM.
+ var WBS_LANGUAGE_KEY = 'workdaddy.ui.language';
+ var WBS_I18N_EN = {
+ '账号': 'Accounts', '主题': 'Theme', '会话': 'Sessions', '模型': 'Models', '增强': 'Enhance', '电脑': 'Computer', '关于': 'About', '设置': 'Settings',
+ '导出': 'Export', '导入': 'Import', '删除': 'Delete', '编辑': 'Edit', '保存': 'Save', '取消': 'Cancel', '确定': 'Confirm', '确认': 'Confirm', '复制': 'Copy', '切换': 'Switch', '启用': 'Enable', '停止': 'Stop',
+ '暂存提示词': 'Stash prompt', '暂存': 'Stashed', '引用文本': 'Quote text', '快捷短语': 'Quick phrases', '点击后发送': 'Send on click', '编辑 →': 'Edit →', '新增': 'Add', '批量操作': 'Batch actions', '批量管理': 'Batch manage', '全选': 'Select all', '取消全选': 'Deselect all', '已选 0': 'Selected 0',
+ '账号汇总': 'Account summary', '账号数': 'Accounts', '总积分': 'Total credits', '手机': 'Phone', '有效期至': 'Expires', '当前使用中': 'Currently active', '登录新账号': 'Log in a new account', '没有可导出的账号备份': 'No account backups to export', '还没有备份账号。打开/登录一次 WorkBuddy 后会自动备份,稍后再来查看。': 'No account backups yet. Open or log in to WorkBuddy once and check again later.',
+ '语言': 'Language', '中文': 'Chinese', '英语': 'English', 'English': 'English', '跟随系统': 'Follow system', '设置语言': 'Language', '首次打开时自动跟随系统语言;未匹配时使用英语。': 'The first launch follows your system language. English is used when no match is found.', '语言设置已更新': 'Language updated',
+ '默认': 'Default', 'WorkDaddy 主题': 'WorkDaddy theme', '毛玻璃': 'Frosted glass', '护眼绿': 'Eye-care green', '赛博紫': 'Cyber purple', '主题外观': 'Theme appearance', '壁纸': 'Wallpaper', '头像': 'Avatar', '自定义壁纸': 'Custom wallpaper', '背景蒙版': 'Background overlay', '背景毛玻璃': 'Background blur', '恢复默认': 'Restore default', '恢复官方头像': 'Restore official avatar',
+ '加载中…': 'Loading…', '读取中…': 'Reading…', '正在读取设置…': 'Reading settings…', '查询中…': 'Checking…', '暂无快捷短语': 'No quick phrases', '暂无快捷短语,点击「+ 新增」添加': 'No quick phrases. Click “+ Add” to create one.', '当前还未添加模型': 'No models added yet', '还没有模型备份': 'No model backups yet', '当前筛选下没有会话': 'No sessions match the current filter', '暂无进行中的会话': 'No active sessions', '暂无官方壁纸': 'No built-in wallpapers', '还没有自定义壁纸,先上传一张': 'No custom wallpapers yet. Upload one to start.', '壁纸加载中…': 'Loading wallpapers…', '壁纸加载失败(daemon 不可达)': 'Wallpaper loading failed (daemon unavailable)',
+ '发送失败: ': 'Send failed: ', '发送失败': 'Send failed', '打开面板失败: ': 'Could not open panel: ', '设置失败: ': 'Settings failed: ', '设置失败': 'Settings failed', '请求失败': 'Request failed', '操作失败': 'Operation failed', '读取文件失败': 'Could not read file', '复制失败': 'Copy failed', '复制失败: ': 'Copy failed: ', '删除失败: ': 'Delete failed: ', '删除失败': 'Delete failed', '切换失败: ': 'Switch failed: ', '应用主题失败: ': 'Could not apply theme: ', '蒙版设置失败: ': 'Overlay setting failed: ', '毛玻璃设置失败: ': 'Blur setting failed: ', '诊断设置保存失败: ': 'Could not save diagnostics setting: ', '无法连接本地服务: ': 'Cannot connect to local service: ', '请确认守护进程已运行': 'Make sure the daemon is running',
+ '签到中': 'Checking in', '今日已签到✓': 'Checked in today ✓', '无签到活动': 'No check-in activity', '登录身份过期': 'Login expired', '刚刚': 'Just now', '分钟前': ' minutes ago', '小时前': ' hours ago', '天前': ' days ago',
+ '发现新版本': 'New version available', '立即更新': 'Update now', '有新版本可用,点击更新。': 'A new version is available. Click Update.', '下载中…': 'Downloading…', '正在打开…': 'Opening…', '安装程序已打开': 'Installer opened', '打开安装程序': 'Open installer', '安装中…': 'Installing…', '重启中…': 'Restarting…', '已完成': 'Completed', '重试更新': 'Retry update',
+ '安全传输': 'Secure transfer', '选择内容': 'Select content', '选择账号': 'Select accounts', '选择目标账号': 'Select target account', '选择目标账号…': 'Select a target account…', '密码': 'Password', '请输入密码': 'Enter password', '密码不能为空': 'Password cannot be empty', '请至少选择一项': 'Select at least one item', '处理中…': 'Processing…', '新版文件请输入密码': 'Enter the password for the new file', '新版文件必须输入密码;旧版导出文件可留空。': 'New files require a password; older exports may be left blank.', '新版文件请输入密码;已有的相同短语会自动跳过。': 'Enter the password for the new file; duplicate phrases are skipped.',
+ '电脑休眠': 'Computer sleep', '允许电脑休眠': 'Allow computer sleep', '持续禁止休眠': 'Keep awake', '所有会话结束允许休眠': 'Allow sleep when all sessions end', '系统默认,空闲后正常休眠': 'System default; sleep normally when idle', '保持唤醒,防黑屏锁屏': 'Stay awake to prevent screen lock', '任一会话运行中都保持唤醒': 'Stay awake while any session is running', '允许显示器休眠': 'Allow display sleep', '禁止休眠时,是否允许显示器单独黑屏': 'When sleep is blocked, allow the display to turn off',
+ '发送错误诊断': 'Send error diagnostics', '推荐开启': 'Recommended', '由环境变量控制': 'Controlled by environment variable', '默认开启 · 设置读取失败': 'Enabled by default · failed to read setting', '保存中…': 'Saving…', '仅发送经过脱敏、截断的版本、系统和错误信息,不包含账号、会话内容、Token 或 API Key;可随时关闭。': 'Only redacted and truncated version, system, and error details are sent. Accounts, sessions, tokens, and API keys are excluded; you can turn this off anytime.', '查看错误诊断说明': 'View diagnostics details', '问题反馈': 'Report an issue', '会话监听日志': 'Session monitor log', '仅保存在当前页面内存': 'Stored only in this page memory',
+ '权限免打扰': 'Permission quiet mode', '异常中断会话': 'Continue interrupted sessions', '决策弹窗': 'Decision prompts', '用弹窗提问': 'Ask with a dialog', '确认弹窗自动允许': 'Auto-allow confirmation dialogs', '自动复制所有会话': 'Auto-copy all sessions', '会话消息索引': 'Message index', '引用消息文本': 'Quote message text', '选择登录方式': 'Choose a login method', '假退出': 'Soft logout', '无感登录': 'Seamless login',
+ '未设置': 'Not set', '当前使用中': 'Currently active', '停止生成': 'Stop generating', '正常重启': 'Restart normally', '清空日志': 'Clear log', '开发者工具': 'Developer tools', '隐藏功能': 'Hidden feature', '卡死': 'Stuck', '任务': 'Task', '空间': 'Workspace', '全部': 'All', '今天': 'Today', '近 7 天': 'Last 7 days', '近 30 天': 'Last 30 days', '企业配额': 'Enterprise quota', '积分到期分布': 'Credit expiry distribution',
+ '连接新服务…': 'Connecting to service…', '等待中': 'Waiting', '运行中': 'Running', '空闲': 'Idle', '已中断': 'Interrupted', '已停止': 'Stopped', '未确认': 'Unconfirmed', '等待确认': 'Waiting for confirmation', '等待新回复': 'Waiting for a new reply', '等待会话': 'Waiting for session', '等待允许': 'Waiting for approval', '整理中': 'Organizing', '恢复中': 'Restoring', '即将完成…': 'Finishing…', '已继续': 'Continued', '检测到会话异常中断,即将自动发送「': 'An interrupted session was detected. Sending “', '自动发送失败,请手动点击发送': 'Automatic send failed. Please click Send manually', '底层发送失败,请手动发送': 'Underlying send failed. Please send manually',
+ '导出账号': 'Export accounts', '导入账号': 'Import accounts', '导出会话': 'Export sessions', '导入会话': 'Import sessions', '导出快捷短语': 'Export quick phrases', '导入快捷短语': 'Import quick phrases', '复制选中到其他账号': 'Copy selected to another account', '删除选中': 'Delete selected', '操作会话': 'Session actions', '连通测试': 'Test connection', '编辑模型': 'Edit model', '模型已保存': 'Model saved', '模型已启用': 'Model enabled', '模型已复制': 'Model copied', '模型配置已共用': 'Model configuration shared', '当前模型': 'Current model', '备选模型': 'Backup models', '模型加载失败:': 'Failed to load models: ', '保存模型失败:': 'Failed to save model: ', '删除当前模型失败:': 'Failed to delete current model: ', '启用模型失败:': 'Failed to enable model: ', '连通测试失败:': 'Connection test failed: ',
+ '选择要查看的账号': 'Choose an account to view', '选择账号并输入密码后导出备份': 'Choose accounts and enter a password to export backups', '从加密导出文件导入账号备份': 'Import account backups from an encrypted export', '使用密码导出选中会话': 'Export selected sessions with a password', '使用密码导出选中快捷短语': 'Export selected quick phrases with a password', '从加密文件导入会话': 'Import sessions from an encrypted file', '从加密文件导入快捷短语': 'Import quick phrases from an encrypted file', '仅支持 PNG / JPG / WebP': 'PNG / JPG / WebP only', '点击或拖拽上传壁纸': 'Click or drag to upload a wallpaper', '点击选择图片,或拖拽到此处': 'Click to choose an image, or drag it here', '支持 PNG / JPG / WebP,自动压缩;可添加多张': 'PNG / JPG / WebP supported; images are compressed automatically',
+ '未命名账号': 'Unnamed account', '未命名模型': 'Unnamed model', '未命名': 'Unnamed', '未知错误': 'Unknown error', '未知': 'Unknown', '有效期未知': 'Expiry unknown', '未找到输入框': 'Composer not found', '输入框内容为空': 'Composer is empty', '当前输入框暂不支持引用插入': 'The current composer does not support quote insertion', '引用插入失败,请重试': 'Could not insert quote. Please try again', '已引用选中文字': 'Selected text quoted', '短语不能为空': 'Quick phrase cannot be empty', '请输入快捷短语': 'Enter a quick phrase', '删除快捷短语': 'Delete quick phrase', '编辑快捷短语': 'Edit quick phrase', '新增快捷短语': 'Add quick phrase', '确定删除': 'Confirm deletion', '确认永久删除': 'Confirm permanent deletion',
+ '本机回环 CDP 注入 · 不改官方安装包': 'Local CDP injection · official app untouched', '一个基于 ': 'A ', ' 的 WorkBuddy 桌面端增强工具。零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。': ' WorkBuddy desktop enhancement tool using Chrome DevTools Protocol (CDP). No intrusion or re-signing; UI components are injected into the running renderer.', '问题反馈': 'Report an issue',
+ // —— 覆盖度补齐(分区域,模板条目支持 {name} 占位,匹配时最长优先)——
+ '(无标题)': 'Untitled', 'GitHub 仓库': 'GitHub repository', '去 GitHub Issues 反馈问题': 'Report an issue on GitHub', '在 GitHub 上给 WorkDaddy 点 Star': 'Star WorkDaddy on GitHub', 'WorkDaddy,点击打开面板,可拖动': 'WorkDaddy – click to open the panel, draggable', '如果 WorkDaddy 对你有帮助,欢迎在 GitHub 点个 Star。你的支持会让这个小项目持续更新。': 'If WorkDaddy helps you, please star it on GitHub. Your support keeps this small project alive.',
+ '元素检查': 'Inspect element', '元素检查不可用:内部模块未加载': 'Element inspector unavailable: internal module not loaded',
+ '到期时间': 'Expiry', '剩余': 'Remaining', '剩余时间计算中': 'Calculating remaining time', '积分': 'Credits', '积分查询超时': 'Credit query timed out', '个人版': 'Personal', '企业': 'Enterprise', '基础用量': 'Base usage', '赠送与加量包': 'Gift & bonus packs', '其他积分': 'Other credits', '即将过期': 'Expiring soon', '已过期': 'Expired',
+ '昨天': 'Yesterday', '分钟': ' min', '小时': ' h', '定位到第': 'Jump to message ', '条用户消息': ' user message', '发送中': 'Sending', '附件': 'Attachment', '疑似未完成': 'Possibly incomplete',
+ '已开启': 'Enabled', '已关闭': 'Disabled', '已领取': 'Claimed', '立即领取,今日可领': 'Claim now, available today', '继续执行': 'Continue',
+ '下载': 'Download', '安装': 'Install', '校验': 'Verify', '检查': 'Check', '重启': 'Restart', '即将打开安装包…': 'Opening installer…', '安装包已打开': 'Installer opened', '安装失败': 'Install failed', '更新出错': 'Update error', '更新失败': 'Update failed', '检查更新失败': 'Update check failed', '已是最新版本': 'Already up to date',
+ '正在下载…': 'Downloading…', '正在准备更新…': 'Preparing update…', '正在安装新版本…': 'Installing new version…', '正在打开已校验的安装程序…': 'Opening verified installer…', '正在重启…': 'Restarting…', '启动新版本…': 'Launching new version…', '启动较慢,请稍候…': 'Startup is slow, please wait…', '更新服务正在重启…': 'Update service restarting…', '新版本服务在 120 秒内未恢复': 'New version service not recovered within 120s', '下载完成,准备安装…': 'Download complete, preparing to install…', '写入新文件…': 'Writing new file…', '已升级到 v': 'Upgraded to v', '已发现': 'Found', '网络暂时失败,正在重试…': 'Network hiccup, retrying…', '已是最新版本': 'Already up to date',
+ '上传图片失败': 'Image upload failed', '图片读取失败': 'Could not read image', '图片处理失败:': 'Image processing failed:', '生成皮肤失败:': 'Could not generate skin:', '替换背景图失败': 'Could not replace wallpaper', '替换背景图失败:': 'Could not replace wallpaper:', '已用图片生成皮肤并应用': 'Generated and applied a skin from the image', '我的图片皮肤': 'My image skin', '显示或隐藏 API Key': 'Show or hide API key',
+ '打开面板失败:': 'Could not open panel:', '无法连接本地服务:': 'Cannot connect to local service:', '退出失败:': 'Could not log out:', '登录失败,请关闭后重试': 'Login failed, please close and retry', '登录方式': 'Login method', '请求超时': 'Request timed out', '超时': 'Timeout',
+ '开启「弹窗自动点允许」?': 'Enable “auto-allow dialogs”?', '开启「系统级工具放行」?': 'Enable “system-wide tool allow”?', '开启后,AI 可直接读写工作区外的任意文件,不再逐次询问。': 'When enabled, the AI can read and write any file outside the workspace without asking each time.', '风险:误改文件时不会提醒。': 'Risk: accidental edits will not trigger warnings.', '开启后 npm、git、curl、python3 等常用命令直接本地执行,不再先进沙箱': 'When enabled, common commands like npm, git, curl, and python3 run directly without the sandbox first', '开启后仅阻止系统睡眠,显示器可黑屏省电': 'When enabled, only system sleep is blocked; the display can still turn off to save power', '开启,移入回收站': 'Enable and move to Trash', '关闭(指令块已移除)': 'Off (custom prompt block removed)', '开启(指令块已写入 app-config.customPrompt)': 'On (custom prompt block written to app-config.customPrompt)', '允许完全访问': 'Allow full access', '环境变量': 'Environment variable', '命令行参数': 'Command-line arguments', '隐藏工具已呼出': 'Hidden tools revealed',
+ '这会把该备份覆盖到官方 models.json 中,同 id 的旧配置将被移除。': 'This overwrites the official models.json with this backup; old configs with the same id are removed.', '输入框非空,已放弃自动发送,避免覆盖你的输入': 'Composer is not empty; automatic send was skipped to avoid overwriting your input', '输入框占用': 'Composer in use', '接口返回 HTTP': 'API returned HTTP', '发送经过脱敏的错误诊断': 'Send redacted error diagnostics',
+ '登录请求不存在或已过期': 'Login request does not exist or has expired', '登录超时,请重新发起': 'Login timed out, please retry', '未找到该短语': 'Quick phrase not found', '缺少 uid': 'Missing uid', 'uid 格式无效': 'Invalid uid format', '缺少 key': 'Missing key', '非法 key:': 'Invalid key:', '备份中无 accessToken': 'No accessToken in the backup', '缺少企业 ID': 'Missing enterprise ID', '账号备份不存在': 'Account backup not found',
+ 'CDP 未连接': 'CDP not connected', 'CDP 未连接,无法注入组件': 'CDP not connected; injection skipped', 'CDP 未连接,无法自动刷新窗口': 'CDP not connected; window refresh skipped', 'CDP 未连接,无法发送': 'CDP not connected; cannot send',
+ ',显示器保持唤醒': ', display stays awake', ',显示器保持唤醒,防锁屏开启': ', display stays awake, screen lock blocked', ',显示器可单独休眠': ', display may sleep on its own', ',已防锁屏': ', screen lock blocked', ',更新完成': ', update complete', ',跳过': ', skipped',
+ '(阶段:': ' (stage: ', ';安装日志:': '; install log: ', ';尝试 ID:': '; attempt ID: ', ';诊断日志:': '; diagnostics log: ',
+ // —— 模板条目({name}/{n} 占位,最长优先整句替换,杜绝中英混合)——
+ '已切换为「{name}」,开始领取积分…': 'Switched to “{name}”, claiming credits…', '已切换为「{name}」,正在复制已标记会话…': 'Switched to “{name}”, copying marked sessions…', '已登录「{name}」': 'Logged in as “{name}”', '已发送「{text}」': 'Sent “{text}”', '「{name}」的备份': 'Backup of “{name}”', '「{name}」的本地备份,不可恢复': 'Local backup of “{name}”, cannot be restored', '「{name}」,请刷新 WorkBuddy 窗口': '“{name}”, please refresh the WorkBuddy window', '「{name}」,重启后生效': '“{name}”, effective after restart', '定位到第{n}条用户消息': 'Jump to user message {n}', '已关闭:{reason}': 'Disabled: {reason}', '已开启:{reason}': 'Enabled: {reason}', '已删除 {n} 项': 'Deleted {n} item(s)', '已复制 {n} 项': 'Copied {n} item(s)', '检测到会话异常中断,即将自动发送「{text}」': 'An interrupted session was detected. Sending “{text}”', '输入框非空,已放弃会话 {id} 的自动继续': 'Composer is not empty; skipped auto-continue for session {id}',
+ // —— 第二批补齐(inject 剩余 + daemon 端会进入 UI/API 的文案)——
+ '免打扰': 'Quiet mode', 'WorkBuddy 即将退出并重新打开到登录页': 'WorkBuddy will exit and reopen to the login page', 'WorkBuddy 队列尚未准备完成': 'WorkBuddy queue is not ready yet', 'WorkBuddy 队列排序接口不可用': 'WorkBuddy queue sort API unavailable', 'WorkBuddy 队列立即发送接口不可用': 'WorkBuddy queue send-now API unavailable', '未找到 WorkBuddy 队列接口': 'WorkBuddy queue API not found',
+ '一个基于': 'A ', '个备选': 'standby', '备选': 'standby', '个失败': ' failed', '个已不存在': ' no longer exist', '项失败': ' failed', '已选': ' selected', '例如 deepseek-v4-flash': 'e.g. deepseek-v4-flash', '例如我的 DeepSeek': 'e.g. my DeepSeek', '加载失败': 'Load failed', '发起授权失败:': 'Authorization failed:', '开启': 'Enable', '关闭': 'Close', '失败': 'Failed', '用户消息': 'User message',
+ 'OLED 纯黑': 'OLED Pure Black', '未发现 CDP 端口(WorkBuddy 需以 --remote-debugging-port 启动)': 'No CDP port found (start WorkBuddy with --remote-debugging-port)', '本地 API 未授权': 'Local API unauthorized', '仅支持 http(s) 链接': 'Only http(s) links are supported', '图片不能超过 10MB': 'Image must not exceed 10MB', '图片必须是 PNG/JPEG/WebP base64': 'Image must be PNG/JPEG/WebP base64', '遥测开关值必须是布尔值': 'Telemetry switch must be a boolean', 'blur 必须是数字': 'Blur must be a number', 'opacity 必须是数字': 'Opacity must be a number', '查询返回空结果': 'Query returned empty results',
+ '正在解包新应用…': 'Unpacking new app…', '挂载 dmg 失败:': 'Failed to mount dmg:', '缺少解包后的新应用': 'Unpacked new app missing', '解包应用失败': 'Failed to unpack app', '缺少 apply-update.sh': 'apply-update.sh missing', '(仓库暂无 Release)': ' (no Releases in the repository yet)', 'auth/state 响应缺少 state': 'auth/state response is missing state',
+ 'WBSWITCH_WORKBUDDY_BIN 不是可验证的当前 profile 主程序;登录信息未修改': 'WBSWITCH_WORKBUDDY_BIN is not a verified main program for the current profile; login info unchanged', '无法以普通用户权限安全退出 WorkBuddy。请手动关闭该程序;若它以管理员身份运行,请先退出后再重试。登录信息未修改': 'Cannot safely quit WorkBuddy at standard user privilege. Please close it manually; if it runs as admin, quit it first and retry. Login info unchanged', '未找到 WorkBuddy 可执行文件,无法安全退出;登录信息未修改': 'WorkBuddy executable not found; cannot quit safely. Login info unchanged', 'workbuddy-target.json 指定的路径不是可验证的当前 profile 主程序;登录信息未修改': 'The path in workbuddy-target.json is not a verified main program for the current profile; login info unchanged', '存在当前 profile 进程,但没有进程属于已验证安装目录;登录信息未修改': 'A current profile process exists, but none belongs to a verified install directory; login info unchanged', '检测到当前 profile 正从另一安装目录运行,登录信息未修改': 'The current profile is running from another install directory; login info unchanged', '检测到多个 dormant WorkBuddy 安装目录,按发现优先级选择:': 'Multiple dormant WorkBuddy installs found; selecting by discovery priority:', 'WorkBuddy 数据目录不是受管目录': 'WorkBuddy data directory is not managed', 'WorkBuddy 页面尚未完成加载': 'WorkBuddy page has not finished loading', '注入脚本页面抛错': 'Injected script page threw an error', '读取注入脚本失败:': 'Failed to read the injected script:', '运行时桥接文件未生成': 'Runtime bridge file was not created',
+ // —— 第三批:daemon 端口/路径校验/发送链路错误(可能进入 toast/API 返回)——
+ '9222-9232、9333 均被占用,无法为 WorkBuddy 分配 CDP 端口': 'Ports 9222-9232 and 9333 are all occupied; cannot allocate a CDP port for WorkBuddy', 'cwd 不是绝对路径': 'cwd is not an absolute path', 'cwd 路径包含符号链接或普通文件': 'cwd path contains a symlink or regular file', '发送按钮禁用(输入内容未被识别)': 'Send button disabled (input not recognized)', '无法清空输入框': 'Could not clear the composer', '无法聚焦输入框': 'Could not focus the composer', '未找到发送按钮': 'Send button not found', '未找到操作栏': 'Toolbar not found',
+ // —— 第四批:真机扫描发现的整句/半动态拼接(杜绝中英混合)——
+ '全部开': 'Enable all', '一键批量开启/关闭全部免打扰开关': 'Toggle all quiet-mode switches at once',
+ '沙箱外写文件免确认': 'Write outside the sandbox without confirmation', '工作区外文件直接读写': 'Direct read/write of files outside the workspace',
+ '常用命令行免确认': 'Common commands without confirmation', '常用命令直接执行': 'Run common commands directly',
+ '大批量删除免确认': 'Bulk delete without confirmation', '批量删除直接进回收站': 'Bulk deletes go straight to Trash',
+ '系统级工具放行': 'Allow system-level tools', '系统管理命令直接执行': 'System admin commands run directly', '弹窗自动点允许': 'Auto-allow dialogs',
+ '继续异常中断会话': 'Continue interrupted sessions', '检测到会话异常中断,自动让它继续。': 'Detected an interrupted session; letting it continue automatically.',
+ '暂存想法择机发送,发送后自动删除。': 'Stashed thoughts send at an opportunity, then are deleted automatically.',
+ '悬停预览,点击或拖动快速定位消息。': 'Hover to preview; click or drag to jump to a message.',
+ '选中会话消息文字后,一键插入输入框。': 'After selecting session message text, insert it into the composer with one click.',
+ '发送后不会自动删除。': 'Not deleted automatically after sending.', '需要我决策时弹窗确认(全局生效)': 'Ask me with a dialog when my decision is needed (applies globally)',
+ '开启后 AI 可直接读写工作区外的文件(包括文稿、下载目录、配置),不再逐一确认': 'When enabled, the AI can directly read/write files outside the workspace (documents, Downloads, config) without confirming each time',
+ '开启后批量删除不再弹确认;为防误删,所有删除强制先进废纸篓/回收站': 'Bulk delete skips dialogs; to prevent mistakes, all deletes go to Trash first',
+ '开启后 wsl、reg、sc、schtasks 等系统管理工具直接运行,不再确认': 'System admin tools like wsl, reg, sc, schtasks run directly without confirmation',
+ '开启后仍有确认弹窗时自动替你点「允许」,所有自动批准记录在审计日志': 'Auto-clicks “Allow” on remaining dialogs; all auto-approvals are logged',
+ '在会话左侧显示消息索引': 'Show the message index on the left side of sessions', '选中会话消息中的文字后显示引用按钮': 'Show the quote button after selecting session message text',
+ '状态机日志': 'state machine log', '监控激活会话中': 'Monitoring active sessions',
+ '更换头像': 'Change avatar', '黑色半透明遮罩,压暗背景图': 'Black translucent overlay that dims the wallpaper',
+ '时间': 'Time', '自动复制': 'Auto-copy', '模型名': 'Model name', '自定义名称': 'Custom name', '确认操作': 'Confirm operation', '小贴士': 'Tip',
+ '解决 WorkBuddy 不支持多个同名模型的问题。': 'Solves WorkBuddy not supporting multiple models with the same name.',
+ '清空': 'Clear', '继续': 'Continue', '更换': 'Change',
+ '共 {n} 个': 'Total: {n} ', '展开 {n} 条(': 'Show {n} (', '从 {src} 导入': 'Import from {src}',
+ '(': '(', ')': ')',
+ // —— 第五批:基础高频词(杜绝词根缺失造成的半句混合)+ 会话/模型/账号错误整句 ——
+ '错误': 'Error', '状态': 'Status', '导航': 'navigation', '消息': 'message', '当前': 'Current', '配置': 'config', '无效': 'invalid', '接口': 'API', '队列': 'queue', '不可用': 'unavailable', '缺少': 'Missing',
+ '会话错误': 'Session error', '会话状态': 'Session status', '会话消息导航': 'Session message navigation', '未获取到当前会话': 'Could not get the current session',
+ '回复已停止,但没有发现明确完成证据': 'Reply stopped without clear completion evidence',
+ '会话正在等待决策确认': 'Session awaiting a decision confirmation', '会话出现模型或网络错误': 'Session hit a model or network error',
+ '会话疑似异常停止,请检查结尾内容': 'Session may have stopped unexpectedly; check the tail',
+ 'WorkBuddy 队列删除接口不可用': 'WorkBuddy queue delete API is unavailable', 'WorkBuddy 队列响应超时(': 'WorkBuddy queue response timed out (',
+ '已导出': 'Exported', '成功导入': 'Imported successfully', '当前账号': 'Current account', '个账号': ' account(s)', '个账号(已加密)': ' account(s) (encrypted)',
+ '随空间自动复制': 'Auto-copy with workspace', '切换账号时自动复制': 'Auto-copy on account switch',
+ '切换账号时自动复制当前账号的所有会话,包括之后新增的会话': 'Auto-copy all sessions of the current account on switch, including new ones afterwards',
+ '已开启切换账号时自动复制': 'Auto-copy on account switch is on', '(未指定空间)': ' (no workspace specified)',
+ '未选择项目的一次性任务/临时会话': 'One-off task / temporary session without a chosen project',
+ '所选账号将加密保存,密码不能为空,请妥善保管。': 'Selected accounts are encrypted; a password is required and should be kept safe.',
+ '模型配置文件格式不受支持:应为数组或包含 models 数组的对象': 'Unsupported model config format: expected an array or an object with a models array',
+ '非法模型备份标识': 'Invalid model backup id', '模型备份不存在': 'Model backup not found', '模型备份格式不受支持': 'Unsupported model backup format',
+ '模型索引无效': 'Invalid model index', '模型配置无效': 'Invalid model config', '未选择当前模型': 'No current model selected',
+ '模型备份缺少 id/name,无法保存': 'Model backup is missing id/name; cannot save', '模型备份缺少 id/name,无法启用': 'Model backup is missing id/name; cannot enable',
+ '不能从当前客户端导入模型': 'Cannot import models from the current client',
+ '无效的自动复制规则类型': 'Invalid auto-copy rule type', '缺少自动复制规则标识': 'Missing auto-copy rule id', '缺少源账号 uid': 'Missing source account uid',
+ '缺少共享会话标识': 'Missing shared session id', '标记仍然存在': 'Marker still present',
+ '未找到唯一的当前登录信息文件': 'No unique current login file found', '未找到有效的登录信息文件': 'No valid login file found',
+ '备份文件认证数据无效,拒绝切换': 'Invalid auth data in the backup; switch rejected',
+ '登录文件目标路径无效': 'Invalid login file target path',
+ '登录文件目标不是当前客户端的有效认证文件,拒绝覆盖': 'Login file target is not a valid auth file for this client; overwrite rejected',
+ '登录文件名已属于其他账号,拒绝覆盖': 'Login filename already belongs to another account; overwrite rejected',
+ '账号缺少已确认的登录文件名,拒绝猜测写入目标': 'Account has no confirmed login filename; refusing to guess a write target',
+ '备份文件校验失败:uid 不匹配,已中止切换': 'Backup validation failed: uid mismatch; switch aborted',
+ // —— 第六批:会话/模型批量操作 + 头像 + 修补剩余整句 ——
+ '请先勾选要复制的会话': 'Select the sessions to copy first', '请先勾选要导出的会话': 'Select the sessions to export first', '请先勾选要删除的会话': 'Select the sessions to delete first',
+ '将加密导出': 'Export with encryption', '已导入': 'Imported', '已复制': 'Copied', '已删除': 'Deleted', '请选择目标账号': 'Select the target account', '加载账号失败:': 'Account loading failed:',
+ '会话将导入到「': 'Importing sessions into “', '会话将保留导出时的账号归属。': 'Sessions keep the account ownership from export.',
+ ' 个会话': ' session(s)', ' 个会话(已加密)': ' session(s) (encrypted)', ' 个会话及其本地消息附件。': ' session(s) and their local message attachments.', ' 个会话到…': ' session(s) to…', ' 个会话?': ' session(s)?',
+ ' 个模型': ' model(s)', ' 个当前模型': ' current model(s)', ' 个模型备份': ' model backup(s)',
+ '两个 WorkBuddy 客户端共用同一份模型配置,无需导入,切换客户端即可看到模型': 'Both WorkBuddy clients share one model config; no import needed, switch clients to see models',
+ '只导入当前不存在的模型,同名模型保留当前配置': 'Only import models that do not exist; same-name models keep the current config',
+ '未找到模型配置文件': 'Model config file not found', '模型已备份到「': 'Model backed up to “', '模型备份失败:': 'Model backup failed:',
+ '两个客户端共用同一份模型配置,无需导入': 'Both clients share one model config; no import needed',
+ '删除后会直接修改官方 models.json,已备份到「备选模型」的配置不会受影响。': 'Deleting directly modifies the official models.json; configs backed up under “Backup models” remain unaffected.',
+ '当前模型已删除': 'Current model deleted', '删除模型备份?': 'Delete model backup?',
+ '删除后无法恢复,但不会影响官方 models.json。': 'Cannot be restored after deletion, but the official models.json is unaffected.',
+ '删除模型备份失败:': 'Failed to delete model backup:', '头像预览': 'Avatar preview', '点击恢复官方头像': 'Click to restore the official avatar',
+ '未找到该账号已记录的登录文件名,拒绝猜测写入目标': 'No recorded login filename for this account; refusing to guess a write target',
+ '「': '“', '」': '”',
+ // —— 第七批:头像/主题/安装器/休眠等散落整句 ——
+ '上传图片替换左下角头像': 'Upload an image to replace the bottom-left avatar', '恢复 WorkBuddy 官方头像': 'Restore the official WorkBuddy avatar',
+ '复制选中快捷短语': 'Copy selected quick phrases',
+ '开启后 WorkBuddy 需要你决策时会用弹窗提问(写入全局自定义指令,所有会话生效)': 'When enabled, WorkBuddy asks with a dialog when your decision is needed (written to the global custom prompt; affects all sessions)',
+ '当前没有进行中的会话,无法开启「所有会话结束允许休眠」': 'No active sessions; cannot enable “Allow sleep when all sessions end”',
+ '进行中的会话': 'active session(s)', '预计剩余': 'Estimated remaining', ' 秒': ' seconds', ' 分': ' minutes',
+ '无法打开安装程序': 'Could not open the installer',
+ '安装程序已打开,请按提示退出 WorkBuddy 并完成安装。': 'The installer is open. Please quit WorkBuddy as prompted and finish installing.',
+ '停止旧服务…': 'Stopping old service…', '发现新版本,准备更新…': 'New version available; preparing to update…',
+ '已应用主题「': 'Theme applied: “', '已恢复官方头像': 'Restored the official avatar', '已应用官方头像': 'Applied the official avatar',
+ '头像已更新 ✓': 'Avatar updated ✓', '头像处理失败:': 'Avatar processing failed:',
+ '已开启:需要你决策时 WorkBuddy 会用弹窗提问(全局生效)': 'Enabled: WorkBuddy asks with a dialog when your decision is needed (applies globally)',
+ // —— 第八批:壁纸/授权/休眠/开启风险文案与时间相对词前导空格变体 ——
+ ' 分钟前': ' minutes ago', ' 小时前': ' hours ago', ' 天前': ' days ago',
+ 'WorkBuddy 需要决策时可能改用文本询问': 'WorkBuddy may fall back to text prompts when a decision is needed',
+ '已关闭:WorkBuddy 需要决策时可能改用文本询问': 'Disabled: WorkBuddy falls back to text prompts when a decision is needed',
+ '已应用壁纸「': 'Wallpaper applied: “', '已删除当前壁纸(背景保留不变)': 'Current wallpaper deleted (background unchanged)',
+ '已在系统浏览器打开授权页,扫码确认后会自动切换到新账号...': 'Authorization page opened in your system browser; after scanning, it will switch to the new account automatically...',
+ '授权成功,但未获取到新账号 UID,请关闭后重试': 'Authorization succeeded, but the new account UID was not obtained; please close and retry',
+ '授权成功,正在切换到「': 'Authorization successful; switching to “', '已登录并切换到「': 'Logged in and switching to “',
+ '账号已授权,但自动切换失败:': 'Account authorized, but auto-switch failed:',
+ '上传壁纸失败': 'Wallpaper upload failed', '已添加并应用自定义壁纸': 'Custom wallpaper added and applied',
+ '开启「外写文件免确认」?': 'Enable “write outside sandbox without confirmation”?',
+ '开启后,npm、git、curl、python3 等命令可直接在本机执行,不再经过沙箱或逐次确认。': 'When enabled, commands like npm, git, curl, and python3 run directly on this machine without sandbox or per-command confirmation.',
+ '风险:命令执行不再受沙箱保护。': 'Risk: commands run without sandbox protection.',
+ '开启后,AI 批量删除文件时不再询问,文件会直接进入废纸篓/回收站,可恢复。': 'When enabled, bulk deletes by the AI skip prompts; files go to Trash and are recoverable.',
+ '彻底删除仍需你明确操作。': 'Permanent deletion still requires your explicit action.',
+ '开启后,wsl、reg、sc、schtasks 等系统命令可直接执行,不再经过确认或沙箱。': 'When enabled, system commands like wsl, reg, sc, schtasks run directly without confirmation or sandbox.',
+ '风险:可直接修改系统配置,风险最高。': 'Risk: can modify system config directly; highest risk.',
+ // —— 第九批:免打扰批量/发送结果兜底/控制器等 ——
+ '开启后,插件会自动点击出现的「允许」按钮,避免任务中断。': 'When enabled, the plugin auto-clicks “Allow” dialogs to avoid task interruptions.',
+ '风险:所有确认将失去人工把关。': 'Risk: confirmations lose human review.',
+ '将一次性开启下面所有开关:外写文件免确认、常用命令免确认、大批量删除免确认、系统级工具放行、弹窗自动点允许。开启后 AI 执行将不再打扰,所有删除仍先进废纸篓可恢复。': 'Enables all switches at once: write-outside-sandbox, common commands, bulk delete, system-level tools, and auto-allow dialogs. The AI then runs without interruptions; deletes still go to Trash first.',
+ '仅在你信任当前工作和本机时使用。': 'Only use when you trust the current work and this machine.',
+ '全部开启': 'Enable all', '已全部开启免打扰': 'All quiet-mode switches are on', '已全部关闭免打扰': 'All quiet-mode switches are off',
+ '批量设置失败:': 'Batch settings failed:',
+ '底层发送结果未确认,为避免重复消息已停止重试,请检查会话': 'Send result unconfirmed; stopped retrying to avoid duplicates; please check the session',
+ '未能确认自动发送结果,请检查会话;为避免重复消息,已停止重试': 'Could not confirm the auto-send result; please check the session; stopped retrying to avoid duplicates',
+ '会话控制器尚未就绪,稍后自动重试': 'Session controller not ready; will retry shortly',
+ '输入框非空,已放弃会话': 'Composer is not empty; session skipped',
+ '(未开启「会话异常中断」监控时无日志)': ' (no logs when the “interrupted session” monitor is off)',
+ '该会话暂无操作日志': 'No operation logs for this session yet',
+ // —— 第十批:快捷短语批量 + 休眠括号变体 ——
+ '请先勾选要复制的短语': 'Select the quick phrases to copy first', '请先勾选要导出的短语': 'Select the quick phrases to export first', '请先勾选要删除的短语': 'Select the quick phrases to delete first',
+ ' 条快捷短语': ' quick phrase(s)', ' 条快捷短语。': ' quick phrase(s).', ' 条快捷短语(已加密)': ' quick phrase(s) (encrypted)',
+ '输入导出时设置的密码;已有的相同短语会自动跳过。': 'Enter the password set for export; identical existing phrases are skipped automatically.',
+ '允许电脑休眠(系统默认)': 'Allow computer sleep (system default)', '持续禁止休眠(保持唤醒)': 'Keep awake (prevent sleep)',
+ // —— 第十一批:休眠模式说明整句 + 时间前导空格变体 ——
+ ' 分钟': ' minutes',
+ '所有会话结束允许休眠(暂禁休眠)': 'Allow sleep when all sessions end (sleep blocked)',
+ '休眠模式已切换为「': 'Sleep mode switched to “',
+ '所有进行中的会话已完成,已自动恢复「允许电脑休眠」': 'All active sessions finished; “Allow computer sleep” restored automatically',
+ '持续禁止休眠:电脑/显示器保持唤醒': 'Keep awake: computer and display stay awake',
+ '持续禁止休眠:仅阻止系统睡眠,显示器可黑屏(可能锁屏)': 'Keep awake: only system sleep is blocked; the display may turn off (screen lock possible)',
+ '所有会话结束允许休眠:任一会话回复中保持唤醒,全部结束后自动恢复': 'Allow sleep when all sessions end: stays awake while any session replies, then restores automatically',
+ '所有会话结束允许休眠:暂禁中,显示器可黑屏(可能锁屏)': 'Allow sleep when all sessions end: currently blocked; display may turn off (screen lock possible)',
+ // —— 第十二批:切换/删除断句模板 + ' 天' 时间变体 ——
+ ' 天': ' days',
+ '已切换到「': 'Switched to “', '再次点击确认切换': 'Click again to confirm switch', '再次点击确认切换为「': 'Click again to confirm switching to “',
+ '切换中…': 'Switching…', '已切换为「': 'Switched to “', '将永久删除「': 'Permanently delete “', '已永久删除「': 'Permanently deleted “',
+ // —— 第十三批:弹窗/登录方式/更新流/会话归档等二级页文案(扫描网修复后暴露)——
+ '确定删除这 {n} 条快捷短语吗?删除后不可恢复。': 'Delete these {n} quick phrases? This cannot be undone.',
+ '确定删除这条快捷短语吗?删除后不可恢复。': 'Delete this quick phrase? This cannot be undone.',
+ '(旧版文件可留空)': ' (may be left blank for older files)', '密码不能为空,请妥善保管。': 'Password cannot be empty; keep it safe.',
+ '展开': 'Expand', '共': 'Total', '条(': ' (', '备份': 'Backup',
+ '无可复制的目标账号(已排除会话所属账号)': 'No target accounts to copy to (the session owner account is excluded)',
+ '删除后会话将从列表中移除,该账号下的本地消息文件将被永久删除,此操作不可恢复。': 'The sessions are removed from the list and their local message files are permanently deleted; this cannot be undone.',
+ '以「不让当前账号登录身份过期」的方式切到登录页,可以登录新账号,也可以切回已登录账号': 'Goes to the login page without letting the current account expire; log in a new account or switch back to an existing one.',
+ '不退出 WorkBuddy,在浏览器完成授权后新账号自动加入列表': 'Keeps WorkBuddy running; after authorizing in the browser, the new account is added to the list automatically.',
+ '正在发起授权…': 'Starting authorization…', '再想想': 'Not now',
+ '如果未完成,继续执行;已完成则回复"已完成"': 'If unfinished, continue; if finished, reply “Finished”.',
+ '暂无可用积分': 'No credits available', '今日已使用': 'Used today', '不限量': 'Unlimited',
+ '正在': '', '安装包': 'installer package', '归档': 'archive', '重复': 'duplicate', '选择': 'selection', '读取': 'read', '尚未': 'not yet',
+ '已就绪': 'ready', '完整性': 'integrity', '落盘': 'write to disk', '校验安装包…': 'Verifying installer package…', '正在下载安装包…': 'Downloading installer package…',
+ '下载安装包失败': 'Downloading the installer package failed', '安装包校验失败,已删除损坏包': 'Installer package verification failed; the damaged package was deleted',
+ '安装包已就绪': 'Installer package ready', '安装包已就绪(校验通过)': 'Installer package ready (verified)', '安装包内部 daemon 版本不可读': 'Cannot read the installer package daemon version',
+ '安装包应用版本不可读': 'Cannot read the installer package app version', '安装包文件不可读:': 'Installer package file unreadable:',
+ '安装包为空或不是普通文件': 'Installer package is empty or not a regular file', 'DMG 预检执行失败:': 'DMG pre-check failed:',
+ '下载内容不是有效 DMG:': 'Downloaded content is not a valid DMG:',
+ '安装包 SHA-256 读取失败:': 'Failed to read the installer package SHA-256:', '已启动更新,正在替换文件并自动重启,请稍候…': 'Update started; replacing files and restarting automatically, please wait…',
+ '尚未下载完成': 'Download not finished yet', '缺少已下载的新版本安装包': 'Missing the downloaded new version installer package',
+ '此历史版本只提供 ZIP,无法使用新的可见安装流程;请从发布页下载 Setup.exe': 'This older version only provides a ZIP; the visible install flow is unavailable, download Setup.exe from the release page instead',
+ '安装包名称与目标 profile 或版本不一致': 'Installer package name does not match the target profile or version',
+ '缺少安装包(未找到已下载的 dmg)': 'Missing installer package (downloaded dmg not found)', '安装包版本校验失败': 'Installer package version verification failed',
+ '官方接口未返回 uid,无法保存账号': 'The official API did not return a uid; account cannot be saved',
+ '未知开关:': 'Unknown switch:', '快捷短语选择必须是数组': 'Quick phrase selection must be an array',
+ '单次最多导入 {n} 个会话': 'Import at most {n} sessions at a time', '单次最多处理 {n} 条快捷短语': 'Process at most {n} quick phrases at a time',
+ '快捷短语标识不能为空': 'Quick phrase id cannot be empty', '未选择快捷短语': 'No quick phrase selected', '没有可导出的快捷短语': 'No quick phrases to export',
+ '没有可导出的会话': 'No sessions to export', '未选择会话': 'No session selected', '导入文件中没有会话数据': 'No session data found in the import file',
+ '无效会话记录': 'Invalid session record', '没有可导入的会话': 'No sessions to import', '会话文件目标不在 managed parent 内': 'Session file target is outside the managed parent',
+ '无法确认 WorkBuddy 已退出': 'Could not confirm WorkBuddy has quit',
+ '未找到 WorkBuddy 可执行文件,无法验证运行中的进程': 'WorkBuddy executable not found; cannot verify the running process',
+ // —— 第十四批:daemon 更新流/归档/导出/账号/壁纸收口 ——
+ '正在检查更新…': 'Checking for updates…', '无可用安装包': 'No installer package available',
+ '发布未提供可信的 SHA-256,已停止更新': 'The release does not provide a trusted SHA-256; update stopped',
+ '安装包缺少完整性校验,已停止更新': 'Installer package lacks integrity verification; update stopped',
+ '安装程序已打开,请按提示完成安装': 'The installer is open. Complete the installation as prompted.',
+ '未找到 WorkBuddy.exe(可用环境变量 WBSWITCH_WORKBUDDY_BIN 指定)': 'WorkBuddy.exe not found (can be set via the WBSWITCH_WORKBUDDY_BIN environment variable)',
+ '注入后未检测到 WorkDaddy 组件(请检查 WorkBuddy 页面是否正常加载)': 'WorkDaddy not detected after injection (check whether the WorkBuddy page loaded correctly)',
+ 'CodeBuddy 会话库读取失败:': 'CodeBuddy session DB read failed:',
+ '拒绝在文件系统根目录创建会话空间': 'Refusing to create a session workspace at the filesystem root',
+ '无效的会话 ID': 'Invalid session ID', '无效的会话文件目标': 'Invalid session file target',
+ '会话附件文件过多,无法导出': 'Too many session attachment files; cannot export', '会话附件超过 256 MB,无法导出': 'Session attachments exceed 256 MB; cannot export',
+ '会话归档包含无效 ID': 'Session archive contains an invalid ID', '会话归档包含无效附件': 'Session archive contains an invalid attachment',
+ '会话归档附件文件过多': 'Session archive has too many attachment files', '会话归档包含重复附件路径': 'Session archive contains duplicate attachment paths',
+ '会话归档附件超过 256 MB': 'Session archive attachments exceed 256 MB', '会话归档缺少有效的账号归属': 'Session archive is missing a valid account owner',
+ '首次会话播种持久化失败': 'Initial session seeding failed to persist',
+ '导入文件中没有快捷短语': 'No quick phrases found in the import file', '单次最多导入 {n} 条快捷短语': 'Import at most {n} quick phrases at a time',
+ '没有可导入的快捷短语': 'No quick phrases to import', '暂存记录不存在:': 'Stashed record not found:', '暂存内容为空': 'Stash content is empty',
+ '默认(浅色)': 'Default (light)', '对话持续回复中(等待 {n} 秒仍未空闲),已取消发送,请稍后再试': 'The conversation is still replying (not idle after {n}s); send cancelled, please retry later',
+ '导出数据不完整或已损坏': 'Export data is incomplete or corrupted', '文件不是有效的导出 JSON': 'The file is not a valid export JSON',
+ '不是 WorkDaddy 的账号导出文件': 'Not a WorkDaddy account export file', '导入文件中没有账号数据': 'No account data found in the import file',
+ '未读取到有效内容,请选择导出文件': 'No valid content read; please choose an export file', '密码不能超过 1024 个字符': 'Password cannot exceed 1024 characters',
+ '当前登录文件无法唯一确认,已拒绝退出登录': 'The current login file cannot be uniquely identified; logout rejected',
+ '删除登录文件后仍然存在': 'The login file still exists after deletion',
+ '诊断设置由 WORKDADDY_TELEMETRY 环境变量控制': 'Diagnostics are controlled by the WORKDADDY_TELEMETRY environment variable',
+ '保存遥测设置失败:': 'Failed to save telemetry settings:',
+ '账号选择必须是数组': 'Account selection must be an array', '选择的账号过多': 'Too many accounts selected', '请至少选择一个账号': 'Select at least one account',
+ '仅支持删除自定义壁纸(custom-*.webp)': 'Only custom wallpapers (custom-*.webp) can be deleted', '壁纸不存在:': 'Wallpaper not found:',
+ '蒙版已保存但应用失败:': 'Overlay saved but failed to apply:', '模糊设置已保存但应用失败:': 'Blur setting saved but failed to apply:',
+ '无法清空输入框': 'Could not clear the composer', '未找到发送按钮': 'Send button not found', '未找到操作栏': 'Toolbar not found',
+ // —— 第十五批:面板入口描述与连接状态 ——
+ '面板入口:': 'Panel entry:', '右下角机器人按钮': 'Bottom-right robot button', '已连接': 'Connected', '未连接': 'Not connected'
+ };
+ function wbsSystemLanguage() {
+ var value = String((navigator && (navigator.language || navigator.userLanguage)) || '').toLowerCase();
+ return value.indexOf('zh') === 0 ? 'zh' : 'en';
+ }
+ function wbsNormalizeLanguage(value) { return value === 'zh' ? 'zh' : 'en'; }
+ // 翻译匹配器:普通条目直接按 key 匹配;模板条目(key 含 {name})编译为正则。
+ // 相同语义的变体(如带/不带尾随空格)均收录;扫描时按位置取「最长优先匹配」,
+ // 保证整句模板覆盖短词,避免短词把长句撕成中英混合。
+ var wbsI18nMatchers = null;
+ function escapeRegExp(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
+ function wbsI18nBuildMatchers() {
+ var entries = [];
+ var seen = {};
+ var raw = Object.keys(WBS_I18N_EN);
+ for (var i = 0; i < raw.length; i++) {
+ var key = raw[i];
+ // 冒号归一化 + 去尾随空格:同一文案的 ':'/':'、带/不带尾空格变体按同一 key 处理,
+ // 保留先出现的条目(其翻译值通常带尾随空格,配合消费逻辑输出整齐)。
+ var normKey = key.replace(/:/g, ':').replace(/\s+$/, '');
+ if (seen[normKey]) continue;
+ seen[normKey] = true;
+ var names = [];
+ var reSource = '';
+ var cursor = 0;
+ var token = null;
+ var tokenRe = /\{([a-zA-Z0-9_]+)\}/g;
+ var hasPlaceholder = false;
+ while ((token = tokenRe.exec(normKey)) !== null) {
+ hasPlaceholder = true;
+ reSource += escapeRegExp(normKey.slice(cursor, token.index)) + '([\\s\\S]*?)';
+ names.push(token[1]);
+ cursor = token.index + token[0].length;
+ }
+ reSource += escapeRegExp(normKey.slice(cursor));
+ entries.push({
+ key: key,
+ normKey: normKey,
+ hasPlaceholder: hasPlaceholder,
+ re: hasPlaceholder ? new RegExp(reSource) : null,
+ translation: WBS_I18N_EN[key],
+ names: names,
+ });
+ }
+ entries.sort(function (a, b) { return b.normKey.length - a.normKey.length; });
+ wbsI18nMatchers = entries;
+ }
+
+ function wbsTranslateString(value, language) {
+ var source = String(value == null ? '' : value);
+ if (language !== 'en') return source;
+ if (!/[\u4e00-\u9fff]/.test(source)) return source;
+ if (!wbsI18nMatchers) wbsI18nBuildMatchers();
+ // 与 key 同样做冒号归一化,保证全角/半角变体都能命中;长度不变,索引可直接复用。
+ var nsource = source.replace(/:/g, ':');
+ var out = '';
+ var pos = 0;
+ var len = source.length;
+ while (pos < len) {
+ var ch = nsource.charAt(pos);
+ var best = null;
+ // 只尝试以当前字符开头的条目(key 原文总是从此字符开始,含空格/符号开头项)
+ for (var i = 0; i < wbsI18nMatchers.length; i++) {
+ var entry = wbsI18nMatchers[i];
+ if (entry.normKey.charAt(0) !== ch) continue;
+ if (!entry.hasPlaceholder) {
+ if (nsource.indexOf(entry.normKey, pos) === pos) { best = entry; break; }
+ continue;
+ }
+ var re = entry.re;
+ re.lastIndex = 0;
+ var m = re.exec(nsource.slice(pos));
+ if (m && m.index === 0) { best = entry; best.capture = m; break; }
+ }
+ if (best) {
+ if (best.hasPlaceholder) {
+ var args = best.capture.slice(1);
+ out += best.translation.replace(/\{([a-zA-Z0-9_]+)\}/g, function (_, name) {
+ var idx = best.names.indexOf(name);
+ return idx >= 0 && args[idx] !== undefined ? args[idx] : '';
+ });
+ pos += best.capture[0].length;
+ } else {
+ out += best.translation;
+ var advance = best.normKey.length;
+ // 前缀 key 尾随空格已被 trim:若原输入紧跟一个空格则一并消费,
+ // 让 'xx: y' 与 'xx:y' 输出一致的 'xx: y' 样式,避免粘连或双空格。
+ if (nsource.charAt(pos + advance) === ' ') advance += 1;
+ pos += advance;
+ }
+ } else {
+ out += ch;
+ pos++;
+ }
+ }
+ return out;
+ }
+
// ===== 全局错误钩子:捕获渲染进程不可捕获的 error / unhandledrejection,把完整消息+栈
// 打到 daemon 日志。渲染进程级崩溃(如 An object could not be cloned)虽非 try/catch 能拦,
// 但很多是经 promise/microtask 抛出的可拦异常——这里统一兜住并留痕。
@@ -577,6 +914,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 当前注入的 daemon 版本号(由 daemon.js 注入时把 __WBS_VERSION__ 替换为 DAEMON_VERSION)
// 「关于」tab 直接展示,升级 daemon 后这里自动同步
var WBS_VERSION = '__WBS_VERSION__';
+ var WBS_LANGUAGE = (function () {
+ try {
+ var saved = localStorage.getItem(WBS_LANGUAGE_KEY);
+ if (saved === 'zh' || saved === 'en') return saved;
+ } catch (_) {}
+ return wbsSystemLanguage();
+ })();
// 纯图标 SVG(stroke 跟随按钮 currentColor)
var SWITCH_SVG =
@@ -967,6 +1311,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var t = el('div', 'wbs-toast' + (isErr ? ' err' : ''));
t.textContent = String(msg == null ? '' : msg);
(targetRoot || document.body).appendChild(t);
+ applyI18n(t);
setBuildTimeout(function () {
t.classList.add('out');
setBuildTimeout(function () { t.remove(); }, 300);
@@ -1212,6 +1557,85 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
// 根节点(面板保持右下角,按钮拖动后水平回到右侧)
+ var i18nTextSources = typeof WeakMap !== 'undefined' ? new WeakMap() : null;
+ var i18nAttrSources = typeof WeakMap !== 'undefined' ? new WeakMap() : null;
+ var i18nApplying = false;
+ function applyI18n(scope) {
+ if (!scope || !scope.ownerDocument) return;
+ var isSkipped = function (el) {
+ // data-wbs-i18n-skip 子树不参与翻译(如语言切换按钮需固定显示 中文/English)
+ return !!(el && el.closest && el.closest('[data-wbs-i18n-skip]'));
+ };
+ i18nApplying = true;
+ try {
+ var nodeFilter = (scope.ownerDocument.defaultView && scope.ownerDocument.defaultView.NodeFilter) || { SHOW_TEXT: 4 };
+ var walker = scope.ownerDocument.createTreeWalker(scope, nodeFilter.SHOW_TEXT);
+ var node;
+ while ((node = walker.nextNode())) {
+ if (!node.parentNode || /^(SCRIPT|STYLE)$/.test(node.parentNode.nodeName)) continue;
+ if (isSkipped(node.parentNode)) continue;
+ var current = String(node.nodeValue || '');
+ var previous = i18nTextSources && i18nTextSources.get(node);
+ var source = previous && (current === previous.last || current === previous.translated) ? previous.source : current;
+ var translated = wbsTranslateString(source, WBS_LANGUAGE);
+ if (i18nTextSources) i18nTextSources.set(node, { source: source, translated: translated, last: translated });
+ if (current !== translated) node.nodeValue = translated;
+ }
+ var elements = scope.querySelectorAll ? scope.querySelectorAll('*') : [];
+ var processElement = function (element) {
+ if (!element || !element.hasAttribute) return;
+ if (isSkipped(element) || (element.closest && element.closest('[data-wbs-i18n-skip]'))) return;
+ ['title', 'aria-label', 'placeholder', 'alt', 'data-tip'].forEach(function (name) {
+ if (!element.hasAttribute(name)) return;
+ var currentAttr = element.getAttribute(name) || '';
+ var attrs = i18nAttrSources && i18nAttrSources.get(element);
+ var previousAttr = attrs && attrs[name];
+ var sourceAttr = previousAttr && (currentAttr === previousAttr.last || currentAttr === previousAttr.translated) ? previousAttr.source : currentAttr;
+ var translatedAttr = wbsTranslateString(sourceAttr, WBS_LANGUAGE);
+ if (i18nAttrSources) {
+ attrs = attrs || {};
+ attrs[name] = { source: sourceAttr, translated: translatedAttr, last: translatedAttr };
+ i18nAttrSources.set(element, attrs);
+ }
+ if (currentAttr !== translatedAttr) element.setAttribute(name, translatedAttr);
+ });
+ };
+ if (scope.nodeType === 1 && !isSkipped(scope)) processElement(scope);
+ else if (scope.nodeType === 1 && isSkipped(scope)) elements = [];
+ for (var i = 0; i < elements.length; i++) processElement(elements[i]);
+ } finally { i18nApplying = false; }
+ }
+ function setLanguage(value) {
+ WBS_LANGUAGE = wbsNormalizeLanguage(value);
+ try { localStorage.setItem(WBS_LANGUAGE_KEY, WBS_LANGUAGE); } catch (_) {}
+ try {
+ document.documentElement.setAttribute('data-wbs-language', WBS_LANGUAGE);
+ document.documentElement.setAttribute('lang', WBS_LANGUAGE === 'zh' ? 'zh-CN' : 'en');
+ } catch (_) {}
+ applyInjectedI18n();
+ // 关于页 Segmented 控件状态同步(存在时)
+ var langSeg = root && root.querySelector('.wbs-lang-seg');
+ if (langSeg) {
+ var btns = langSeg.querySelectorAll('.wbs-sess-seg-btn');
+ for (var bi = 0; bi < btns.length; bi++) {
+ var active = btns[bi].getAttribute('data-wbs-lang') === WBS_LANGUAGE;
+ btns[bi].classList.toggle('active', active);
+ btns[bi].setAttribute('aria-pressed', active ? 'true' : 'false');
+ }
+ }
+ }
+ function applyInjectedI18n() {
+ applyI18n(root);
+ var nodes = document.querySelectorAll('.wbs-stash-inline,.wbs-selection-quote-btn,.wbs-queue-tag,.wbs-message-nav-root');
+ for (var i = 0; i < nodes.length; i++) applyI18n(nodes[i]);
+ }
+ window.__wbsSetLanguage = setLanguage;
+ registerDisposer(function () {
+ if (window.__wbsSetLanguage === setLanguage) {
+ try { delete window.__wbsSetLanguage; } catch (_) { window.__wbsSetLanguage = null; }
+ }
+ });
+
var root = el('div', 'wbs-root');
root.setAttribute('data-wbs-profile', PROFILE_ID);
if (!CAPS.theme) root.classList.add('wbs-no-theme');
@@ -1265,6 +1689,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</div>',
].join('');
document.body.appendChild(root);
+ try {
+ document.documentElement.setAttribute('data-wbs-language', WBS_LANGUAGE);
+ document.documentElement.setAttribute('lang', WBS_LANGUAGE === 'zh' ? 'zh-CN' : 'en');
+ } catch (_) {}
+ var i18nObserver = null;
+ if (typeof MutationObserver !== 'undefined') {
+ i18nObserver = new MutationObserver(function (records) {
+ if (i18nApplying) return;
+ for (var ri = 0; ri < records.length; ri++) {
+ var target = records[ri].target;
+ var host = target && target.nodeType === 1 ? target : (target && target.parentNode);
+ if (host && host.closest && host.closest('.wbs-root') === root) applyI18n(host);
+ }
+ });
+ i18nObserver.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['title', 'aria-label', 'placeholder', 'alt', 'data-tip'] });
+ registerDisposer(function () { if (i18nObserver) i18nObserver.disconnect(); i18nObserver = null; });
+ }
+ applyI18n(root);
// 不同客户端只开放明确支持的能力;保留统一面板结构可避免模式切换时布局抖动。
// 主题能力由 profile capabilities 统一控制,两个 WorkBuddy 客户端均可使用。
@@ -1301,6 +1743,7 @@ 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>';
+ applyI18n(stashBtn);
// 防输入框失焦:点击按钮时不把焦点从输入框抢走(退格/打字持续有效)
stashBtn.addEventListener('mousedown', function (e) { e.preventDefault(); });
if (!CAPS.stashPrompt) stashBtn.style.display = 'none';
@@ -1322,6 +1765,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</div>' +
'</div>' +
'</div>';
+ applyI18n(exploreBtn);
var exploreSendTxt = exploreBtn.querySelector('.wbs-explore-send-txt');
if (exploreSendTxt) {
exploreSendTxt.addEventListener('click', function (e) {
@@ -1540,6 +1984,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
selectionQuoteButton.setAttribute('aria-label', '引用文本');
selectionQuoteButton.textContent = '引用文本';
document.body.appendChild(selectionQuoteButton);
+ applyI18n(selectionQuoteButton);
listen(selectionQuoteButton, 'pointerdown', function (event) {
if (event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
@@ -3038,6 +3483,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<path d="M2.53 2.53A2.25 2.25 0 0 1 4.12 2h6.13c.6 0 1.17.24 1.59.66l9.5 9.5a2.25 2.25 0 0 1 0 3.18l-5.4 5.4a2.25 2.25 0 0 1-3.18 0l-9.5-9.5a2.25 2.25 0 0 1-.66-1.59V4.12c0-.6.24-1.17.66-1.59zM7.06 8.56a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z"/></svg>' +
'<span>暂存提示词</span>';
actions.insertBefore(tag, actions.firstChild);
+ applyI18n(tag);
}
// data-wbs-stash 标记:禁拖(dragstart 捕获拦截)+ 隐藏拖拽图标(CSS)。data 属性 React 不管理,幂等设置安全
it.setAttribute('data-wbs-stash', '1');
@@ -3799,6 +4245,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (name === 'enhance' && enhancePane && !enhancePane.dataset.built) buildEnhancePane();
if (name === 'pc' && pcPane && !pcPane.dataset.built) buildPcPane();
if (name === 'about' && aboutPane && !aboutPane.dataset.built) buildAboutPane();
+ if (name === 'settings' && settingsPane && !settingsPane.dataset.built) buildSettingsPane();
}
var tabBtns = root.querySelectorAll('.wbs-tab');
for (var ti = 0; ti < tabBtns.length; ti++) {
@@ -4800,7 +5247,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<button class="wbs-theme-opt active" type="button" data-theme="default">默认</button>' +
'<button class="wbs-theme-opt" type="button" data-theme="eye-care">护眼绿</button>' +
'<button class="wbs-theme-opt" type="button" data-theme="cyber-purple">赛博紫</button>' +
- '<button class="wbs-theme-opt" type="button" data-theme="nebula">' + WBS_BRAND + ' 主题</button>' +
+ '<button class="wbs-theme-opt" type="button" data-theme="nebula">毛玻璃</button>' +
'</div>' +
'</div>' +
'<div class="wbs-pcard wbs-avatar-card">' +
@@ -5026,6 +5473,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</a>' +
'</div>' +
'</div>' +
+ '<div class="wbs-pcard wbs-settings-card wbs-language-card">' +
+ '<div class="wbs-settings-row">' +
+ '<span class="wbs-pcard-title">语言</span>' +
+ '<div class="wbs-theme-seg wbs-lang-seg" role="group" aria-label="设置语言" data-wbs-i18n-skip="1">' +
+ '<button type="button" class="wbs-sess-seg-btn" data-wbs-lang="zh" aria-pressed="false">中文</button>' +
+ '<button type="button" class="wbs-sess-seg-btn" data-wbs-lang="en" aria-pressed="false">English</button>' +
+ '</div>' +
+ '</div>' +
+ '</div>' +
'<div class="wbs-pcard wbs-telemetry-card" id="wbs-telemetry-card">' +
'<div class="wbs-telemetry-head">' +
'<div class="wbs-telemetry-label"><span class="wbs-pcard-title">发送错误诊断</span><span class="wbs-telemetry-help" tabindex="0" aria-label="查看错误诊断说明"><svg viewBox="0 0 20 20" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="10" cy="10" r="8"/><path d="M8.4 7.6a1.8 1.8 0 1 1 2.8 1.45c-.75.48-1.2.85-1.2 1.75M10 13.7v.1"/></svg><span class="wbs-telemetry-tooltip" role="tooltip">仅发送经过脱敏、截断的版本、系统和错误信息,不包含账号、会话内容、Token 或 API Key;可随时关闭。</span></span></div>' +
@@ -5065,6 +5521,28 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var issues = aboutPane.querySelector('#wbs-about-issues');
if (issues && d.repository) issues.href = d.repository.replace(/\/$/, '') + '/issues';
}).catch(function () {});
+ // 语言切换 Segmented 控件:随关于页构建,与主题/会话页分段外观一致
+ var langSeg = aboutPane.querySelector('.wbs-lang-seg');
+ if (langSeg) {
+ function syncLangSeg(lang) {
+ var btns = langSeg.querySelectorAll('.wbs-sess-seg-btn');
+ for (var bi = 0; bi < btns.length; bi++) {
+ var active = btns[bi].getAttribute('data-wbs-lang') === lang;
+ btns[bi].classList.toggle('active', active);
+ btns[bi].setAttribute('aria-pressed', active ? 'true' : 'false');
+ }
+ }
+ syncLangSeg(WBS_LANGUAGE);
+ langSeg.addEventListener('click', function (ev) {
+ var btn = ev.target && ev.target.closest ? ev.target.closest('.wbs-sess-seg-btn') : null;
+ if (!btn || !langSeg.contains(btn)) return;
+ var next = btn.getAttribute('data-wbs-lang');
+ if (next !== 'zh' && next !== 'en') return;
+ setLanguage(next);
+ syncLangSeg(next);
+ toast('语言设置已更新', false, root);
+ });
+ }
wireTelemetrySettings();
acRenderMonitorLogModal();
// 自动更新:检查 + 红点 + 更新卡片
@@ -6344,6 +6822,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var ndScanTimer = null;
var ndScanRoots = [];
var ndEnabledCount = 0;
+ var ndSyncTimer = null; // 免打扰状态周期同步(确保外部/其它会话改动后观察者自动收敛)
// 开关定义:id/配置名/确认弹窗文案(开启时弹窗,红字确认)
var ND_DEFS = [
{
@@ -8698,7 +9177,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function creditBlockHtml(credits, segments, account) {
- if (isIdentityExpired(account)) return '';
+ // 登录身份过期:展示可诊断文案(token 被服务端拒绝时不伪造积分,也不整格隐藏)
+ if (isIdentityExpired(account) || (account && account.creditExpired)) {
+ return '<div class="wbs-credit-block"><div class="wbs-credit-line"><div class="wbs-credit-left"><span class="wbs-lbl">剩余</span><span class="wbs-credit-na">登录身份过期</span></div></div></div>';
+ }
var usage = accountStatusTagsHtml(account);
// 企业账号不限量(官方 getEnterpriseUsage 返回 limitNum === -1)
if (account && account.creditUnlimited) {
@@ -8845,7 +9327,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<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' : '') + '">' + esc(ts.label) + '</span></div>' +
'</div>' +
- '<div class="wbs-credit-cell' + (isIdentityExpired(a) ? ' wbs-credit-hidden' : '') + '">' + creditBlockHtml(credits, a.creditSegments, a) + '</div>' +
+ '<div class="wbs-credit-cell">' + creditBlockHtml(credits, a.creditSegments, a) + '</div>' +
'</div>';
list.appendChild(card);
});
@@ -9008,10 +9490,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
if (cell) {
var hidden = isIdentityExpired(account);
- cell.classList.toggle('wbs-credit-hidden', hidden);
- if (hidden) cell.innerHTML = '';
+ // 不再整格隐藏/清空:过期时由 creditBlockHtml 展示「登录身份过期」诊断文案
+ cell.classList.remove('wbs-credit-hidden');
+ cell.innerHTML = creditBlockHtml(account.credits, account.creditSegments, account);
var switchBtn = cards[i].querySelector('.wbs-acc-switch');
- if (switchBtn) switchBtn.style.display = hidden ? 'none' : '';
+ if (switchBtn) switchBtn.style.display = hidden || account.creditExpired ? 'none' : '';
}
}
}
@@ -9110,13 +9593,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
updateCreditCell(a.uid, credits, segments);
})
- .catch(function () {
+ .catch(function (e) {
if (runId !== state.creditRunId) return;
+ // daemon 对 token 失效返回结构化 401 {expired:true}:标记为登录身份过期,
+ // 卡片上展示可诊断文案而不是空白或「-」(同样不弹 toast,避免面板抖动)。
+ var accountExpired = !!(e && e.payload && e.payload.expired);
for (var i = 0; i < state.accounts.length; i++) {
- if (state.accounts[i].uid === a.uid) { state.accounts[i].credits = null; state.accounts[i].creditSegments = []; state.accounts[i].creditUnlimited = false; break; }
+ if (state.accounts[i].uid === a.uid) {
+ state.accounts[i].credits = null;
+ state.accounts[i].creditSegments = [];
+ state.accounts[i].creditUnlimited = false;
+ state.accounts[i].creditExpired = accountExpired;
+ break;
+ }
}
updateCreditCell(a.uid, null);
- // 静默失败,不弹 toast;避免面板抖动
})
.finally(function () {
if (runId !== state.creditRunId) return;
@@ -9143,8 +9634,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (state.accounts[j].uid === uid) { account = state.accounts[j]; break; }
}
var hidden = isIdentityExpired(account);
- elCredit.classList.toggle('wbs-credit-hidden', hidden);
- elCredit.innerHTML = hidden ? '' : creditBlockHtml(credits, segments || [], account);
+ elCredit.classList.remove('wbs-credit-hidden');
+ elCredit.innerHTML = creditBlockHtml(credits, segments || [], account);
+ var cellSwitch = card.querySelector('.wbs-acc-switch');
+ if (cellSwitch) cellSwitch.style.display = hidden || (account && account.creditExpired) ? 'none' : '';
}
// ===== 调试:暴露内部状态到 window.__wbsDiag(控制台可调) =====
@@ -9242,6 +9735,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
sleepSyncTimer = setBuildInterval(syncSleepState, 30000);
// 免打扰:启动即同步开关状态(若「弹窗自动点允许」已开启则挂上观察者,无需打开增强页)
setBuildTimeout(syncNoDisturb, 1200);
+ // 免打扰周期同步(30s):开关可能被其它会话/外部改动,周期拉取保证
+ // 「弹窗自动点允许」观察者及时启动/停止,避免弹窗出现后不被自动允许。
+ if (!ndSyncTimer) ndSyncTimer = setBuildInterval(syncNoDisturb, 30000);
// 更新顶部红色角标:build 完成、send/editor/stash 状态(200ms 后写,等 syncStash 节流跑完)
try {
var badgeTimer = setBuildTimeout(function () {
@@ -9343,7 +9839,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.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}',
/* 会话消息索引:跟随官方消息视口定位,tooltip 使用主题感知的毛玻璃表面 */
- '.wbs-message-nav-root{position:fixed;width:24px;z-index:2147483645;pointer-events:none;user-select:none;-webkit-user-select:none;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;color:var(--wb-color-text-primary,#1f1f1f)}',
+ '.wbs-message-nav-root{position:fixed;width:24px;z-index:1000;pointer-events:none;user-select:none;-webkit-user-select:none;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-message-nav-rail{display:flex;width:24px;height:100%;box-sizing:border-box;flex-direction:column;align-items:center;justify-content:flex-start;gap:0;overflow:hidden;padding:6px 0;border:1px solid transparent;border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 16%,transparent);box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none;pointer-events:auto;touch-action:none;cursor:pointer;scrollbar-width:none;transition:background-color .18s ease,border-color .18s ease,box-shadow .18s ease,backdrop-filter .18s ease}',
'.wbs-message-nav-rail:hover,.wbs-message-nav-rail:focus-within{border-color:color-mix(in srgb,var(--wb-border-subtle,#d9dadd) 72%,transparent);background:color-mix(in srgb,var(--wb-bg-popover,#fff) 48%,transparent);box-shadow:0 5px 18px rgba(24,28,36,.10);backdrop-filter:blur(14px) saturate(1.12);-webkit-backdrop-filter:blur(14px) saturate(1.12)}',
'.wbs-message-nav-rail::-webkit-scrollbar{display:none}',
@@ -9428,6 +9924,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
/* 面板:毛玻璃主题(半透明 + 模糊,背景图透出) */
'.wbs-panel{position:absolute;right:0;bottom:0;width:520px;max-width:94vw;height:650px;max-height:650px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden;backdrop-filter:blur(28px) saturate(1.25);-webkit-backdrop-filter:blur(28px) saturate(1.25)}',
'.wbs-panel.show{display:flex}',
+ // 英文文案更长:EN 模式面板宽度放大 1.35 倍(520px -> 702px),配合 label 自适应避免挤压
+ 'html[data-wbs-language="en"] .wbs-panel{width:702px}',
+ // EN 下固定宽度 label 容易溢出:phone/credit/token 列的 label 释放为自适应宽度
+ 'html[data-wbs-language="en"] .wbs-phone-cell .wbs-lbl,html[data-wbs-language="en"] .wbs-credit-left .wbs-lbl{width:auto;max-width:84px}',
+ 'html[data-wbs-language="en"] .wbs-token-cell .wbs-lbl{width:auto;max-width:96px}',
+ // 语言切换 Segmented:复用主题/会话页的分段外观(theme-seg 容器 + sess-seg-btn 按钮)
+ '.wbs-language-card .wbs-settings-row{justify-content:space-between}',
+ '.wbs-language-card .wbs-pcard-title{margin-bottom:0}',
+ '.wbs-lang-seg{flex:0 0 auto;width:auto;margin-bottom:0}',
+ '.wbs-lang-seg .wbs-sess-seg-btn{padding:6px 14px}',
'.wbs-head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px 12px;border-bottom:1px solid var(--wb-border-subtle,#f0f0f0);background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 30%,transparent)}',
'.wbs-head-left{display:flex;align-items:center;gap:9px;min-width:0}',
'.wbs-title{font-size:16px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);letter-spacing:.3px;cursor:pointer;user-select:none}',
@@ -9577,6 +10083,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.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}',
'.wbs-stash-inline:hover{width:113px;border-radius:40px;padding-right:5px}',
'.wbs-stash-inline:hover .wbs-stash-txt{opacity:1;max-width:76px;margin-left:7px}',
+ // EN 文案更长(Stash prompt / Quote text):加宽展开胶囊与文案上限,避免 "prompt" 截断;
+ // 宽度按 icon(16)+gap(7)+文字(~90)+padding(13) 收紧,不留过多右侧留白
+ 'html[data-wbs-language="en"] .wbs-stash-inline:hover,html[data-wbs-language="en"] .wbs-stash-inline.wbs-stash-inline-inline:hover{width:128px}',
+ 'html[data-wbs-language="en"] .wbs-stash-inline:hover .wbs-stash-txt{max-width:96px}',
'.wbs-explore-inline{position:fixed;left:auto;display:flex;align-items:center;justify-content:center;cursor:pointer;flex-shrink:0;z-index:auto;top:0;right:0;overflow:visible;padding:0 8px}',
/* 复用暂存按钮视觉(wbs-stash-inline 提供 32px 圆形/背景/阴影),但 hover 不变宽 */
'.wbs-stash-inline.wbs-explore-inline:hover{width:32px;height:32px;border-radius:50%;padding:0 8px}',
@@ -9650,13 +10160,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-toast.err{background:#f53f3f}',
'.wbs-toast.out{opacity:0}',
/* ===== 新版 Tab 布局(账号/主题/增强)===== */
- '.wbs-tabs{display:flex;gap:6px;padding:10px 14px 0;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 25%,transparent)}',
- '.wbs-tab{flex:1;display:flex;align-items:center;justify-content:center;gap:6px;padding:8px 0;border:none;border-radius:10px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:13px;font-weight:600;cursor:pointer;transition:all .18s;font-family:inherit}',
+ '.wbs-tabs{display:flex;gap:6px;padding:10px 14px 0;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 25%,transparent);overflow-x:auto;scrollbar-width:none}',
+ '.wbs-tabs::-webkit-scrollbar{display:none}',
+ '.wbs-tab{flex:1 0 66px;min-width:66px;display:flex;align-items:center;justify-content:center;gap:6px;padding:8px 4px;border:none;border-radius:10px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:13px;font-weight:600;cursor:pointer;transition:all .18s;font-family:inherit;white-space:nowrap}',
'.wbs-tab-ico{font-size:14px;line-height:1}',
'.wbs-tab:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-tab.active{background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 2px 10px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 30%,transparent)}',
'.wbs-pane{display:none;padding:2px 2px 6px}',
'.wbs-pane.active{display:flex;flex-direction:column;height:100%;min-height:0}',
+ '.wbs-settings-card{padding:12px 14px}',
+ '.wbs-settings-row{display:flex;align-items:center;gap:12px;justify-content:space-between}',
+ '.wbs-settings-copy{display:flex;flex-direction:column;gap:4px;min-width:0}',
+ '.wbs-settings-copy strong{font-size:12px;color:var(--wb-color-text-primary,#1f1f1f);font-weight:650}',
+ '.wbs-settings-copy span{font-size:11px;line-height:1.5;color:var(--wb-icon-tertiary,#999);white-space:normal;overflow-wrap:anywhere}',
/* 分组卡片(主题/增强 tab) */
'.wbs-pcard{background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 18%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:14px;padding:10px 12px;margin-bottom:8px;backdrop-filter:blur(16px) saturate(1.2);-webkit-backdrop-filter:blur(16px) saturate(1.2)}',
'.wbs-pcard-title{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);margin-bottom:8px}',
@@ -10044,6 +10560,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
init: start,
refresh: function () { if (state._refresh) state._refresh(); },
destroy: destroyWidget,
+ getLanguage: function () { return WBS_LANGUAGE; },
+ setLanguage: function (value) { return typeof window.__wbsSetLanguage === 'function' ? window.__wbsSetLanguage(value) : undefined; },
};
})();
}
diff --git a/scripts/install-win.ps1 b/scripts/install-win.ps1
index 4c88226..47f4e32 100644
--- a/scripts/install-win.ps1
+++ b/scripts/install-win.ps1
@@ -210,5 +210,5 @@ Write-InstallLine (' profile : ' + $Profile)
Write-InstallLine (" 安装目录 : " + $AppDir)
Write-InstallLine (" 数据目录 : " + $dataDir)
Write-InstallLine (' 备份账号 : ' + (Join-Path $dataDir 'accounts'))
-Write-InstallLine ' 卸载 : 运行安装目录 scripts\uninstall-win.ps1'
+Write-InstallLine ' 卸载 : 运行安装目录 scripts\uninstall-win.cmd(或包根 Uninstall-WorkDaddy.cmd)'
Write-InstallLine '=============================================================='
diff --git a/scripts/lib.js b/scripts/lib.js
index aa57a1b..e192352 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -58,6 +58,127 @@ const AUTH_FILE = process.env.WBSWITCH_AUTH_FILE !== undefined
))));
const LOGOUT_MARKER = `${AUTH_FILE}.logged-out`;
+const EXPLICIT_AUTH_FILE = process.env.WBSWITCH_AUTH_FILE !== undefined;
+const DYNAMIC_AUTH_DISCOVERY = !EXPLICIT_AUTH_FILE && !!ACTIVE_PROFILE.authFile && !!ACTIVE_PROFILE.capabilities.accounts;
+
+function authDir(file = AUTH_FILE) {
+ return file ? path.dirname(path.resolve(file)) : null;
+}
+
+function safeAuthFileName(name) {
+ const value = String(name || '');
+ return value.length > 0 && value.length <= 255 && path.basename(value) === value &&
+ !value.includes('\0') && !value.endsWith('.tmp') && /\.info$/i.test(value);
+}
+
+function normalizeAuthDomain(value) {
+ const raw = String(value || '').trim();
+ if (!raw) return '';
+ try {
+ const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`);
+ return url.origin.toLowerCase().replace(/\/$/, '');
+ } catch (_) {
+ return '';
+ }
+}
+
+function tokenIssuerOrigin(accessToken) {
+ try {
+ const part = String(accessToken || '').split('.')[1];
+ if (!part) return '';
+ const padded = part.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (part.length % 4)) % 4);
+ const payload = JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
+ return normalizeAuthDomain(payload.iss);
+ } catch (_) {
+ return '';
+ }
+}
+
+function allowedAuthOrigins(profile = ACTIVE_PROFILE) {
+ const origins = new Set();
+ const profileOrigin = normalizeAuthDomain(profile.apiHost);
+ if (profileOrigin) origins.add(profileOrigin);
+ if (profile.region === 'cn') {
+ origins.add('https://www.workbuddy.cn');
+ origins.add('https://www.codebuddy.cn');
+ } else if (profile.region === 'intl') {
+ origins.add('https://www.workbuddy.ai');
+ origins.add('https://www.codebuddy.ai');
+ }
+ return origins;
+}
+
+function authRecordFromJson(file, json, { strict = DYNAMIC_AUTH_DISCOVERY } = {}) {
+ if (!json || typeof json !== 'object' || Array.isArray(json)) return null;
+ const acct = json.account || (Array.isArray(json.accounts) && json.accounts[0]) || null;
+ if (!acct || !acct.uid) return null;
+ const auth = json.auth && typeof json.auth === 'object' ? json.auth : {};
+ const accessToken = String(auth.accessToken || auth.access_token || auth.token || '');
+ const authDomain = normalizeAuthDomain(auth.domain || auth.issuer || '');
+ const authIssuer = tokenIssuerOrigin(accessToken);
+ if (strict) {
+ if (!accessToken) return null;
+ const allowed = allowedAuthOrigins();
+ if (![authDomain, authIssuer].some((origin) => origin && allowed.has(origin))) return null;
+ }
+ return {
+ uid: String(acct.uid),
+ nickname: acct.nickname || '',
+ uin: acct.uin || '',
+ phone: acct.phoneNumber || '',
+ type: acct.type || '',
+ raw: json,
+ file,
+ authFileName: file ? path.basename(file) : '',
+ authDomain,
+ authIssuer,
+ lastLogin: acct.lastLogin === true,
+ lastRefreshTime: Number(auth.lastRefreshTime) || 0,
+ };
+}
+
+function parseAuthFile(file, options = {}) {
+ if (!file || !fs.existsSync(file)) return null;
+ try {
+ const json = JSON.parse(fs.readFileSync(file, 'utf8'));
+ return authRecordFromJson(file, json, options);
+ } catch (_) {
+ return null;
+ }
+}
+
+function listAuthRecords() {
+ if (!AUTH_FILE) return [];
+ if (!DYNAMIC_AUTH_DISCOVERY) {
+ const record = parseAuthFile(AUTH_FILE, { strict: false });
+ return record ? [record] : [];
+ }
+ const dir = authDir();
+ let names;
+ try { names = fs.readdirSync(dir); } catch (_) { return []; }
+ return names
+ .filter(safeAuthFileName)
+ .map((name) => parseAuthFile(path.join(dir, name)))
+ .filter(Boolean);
+}
+
+function resolveCurrentAuth() {
+ if (!DYNAMIC_AUTH_DISCOVERY) return { file: AUTH_FILE, record: parseAuthFile(AUTH_FILE, { strict: false }), ambiguous: false };
+ const records = listAuthRecords();
+ if (records.length === 1) return { file: records[0].file, record: records[0], ambiguous: false };
+ // 官方固定文件(workbuddy-desktop.info / workbuddy-desktop-ai.info)是官方实际读取的
+ // 当前登录文件:多份历史备份可能都残留 lastLogin 标记,只有固定文件是可信的「当前」。
+ // 固定文件有效时优先采用,避免被历史标记拖入 ambiguous 而拒绝切换/备份。
+ const canonical = records.find((record) => AUTH_FILE && path.resolve(record.file) === path.resolve(AUTH_FILE));
+ if (canonical) return { file: canonical.file, record: canonical, ambiguous: false };
+ const marked = records.filter((record) => record.lastLogin);
+ if (records.length > 1 && marked.length === 1) return { file: marked[0].file, record: marked[0], ambiguous: false };
+ return { file: null, record: null, ambiguous: records.length > 1, records };
+}
+
+function currentAuthFile() {
+ return resolveCurrentAuth().file;
+}
function defaultDataDir() {
// 旧版 launchd 可能把 WBSWITCH_DATA_DIR 设成 HelloBuddy;新版本始终落到 WorkDaddy,
@@ -871,11 +992,12 @@ function backupPath(dataDir, uid) {
}
/** WorkBuddy ignores auth files while this marker exists; retire it after a switch. */
-function retireLogoutMarker(log = () => {}) {
- if (!fs.existsSync(LOGOUT_MARKER)) return false;
+function retireLogoutMarker(log = () => {}, file = AUTH_FILE) {
+ const marker = file ? `${file}.logged-out` : LOGOUT_MARKER;
+ if (!marker || !fs.existsSync(marker)) return false;
try {
- const retired = `${LOGOUT_MARKER}.retired.${process.pid}.${Date.now()}`;
- fs.renameSync(LOGOUT_MARKER, retired);
+ const retired = `${marker}.retired.${process.pid}.${Date.now()}`;
+ fs.renameSync(marker, retired);
try {
fs.unlinkSync(retired);
} catch (_) {
@@ -890,7 +1012,7 @@ function retireLogoutMarker(log = () => {}) {
// WorkBuddy may launch the daemon in a sandbox that cannot unlink auth files.
try {
const { execFileSync } = require('child_process');
- const markerQ = LOGOUT_MARKER.replace(/"/g, '\\"');
+ const markerQ = marker.replace(/"/g, '\\"');
execFileSync('osascript', ['-e', `do shell script "rm -f \\\"${markerQ}\\\""`], {
timeout: 15000,
stdio: 'pipe',
@@ -964,27 +1086,14 @@ function ensureDirs(dataDir, log = () => {}) {
}
/** 读取登录信息文件并抽取账号关键字段(不返回令牌内容) */
-function readAuthFile() {
+function readAuthFile(file = currentAuthFile()) {
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') {
- throw new Error('auth 文件不是有效的 JSON 对象');
- }
- const acct = json.account || (Array.isArray(json.accounts) && json.accounts[0]) || null;
- if (!acct || !acct.uid) {
- throw new Error('auth 文件中未找到 account.uid');
- }
- return {
- uid: acct.uid,
- nickname: acct.nickname || '',
- uin: acct.uin || '',
- phone: acct.phoneNumber || '',
- type: acct.type || '',
- raw: json,
- };
+ if (!file) throw new Error('未找到唯一的当前登录信息文件');
+ const info = parseAuthFile(file, { strict: DYNAMIC_AUTH_DISCOVERY });
+ if (!info) throw new Error(`auth 文件无效或不属于当前客户端: ${path.basename(file)}`);
+ return info;
}
/** 更新 meta.json(uid -> nickname/uin/phone/时间) */
@@ -997,6 +1106,9 @@ function updateMeta(dataDir, info) {
nickname: info.nickname || prev.nickname || '',
uin: info.uin || prev.uin || '',
phone: info.phone || prev.phone || '',
+ authFileName: info.authFileName || prev.authFileName || '',
+ authDomain: info.authDomain || prev.authDomain || '',
+ authIssuer: info.authIssuer || prev.authIssuer || '',
firstSeen: prev.firstSeen || now,
lastSeen: now,
};
@@ -1004,23 +1116,53 @@ function updateMeta(dataDir, info) {
return meta;
}
-/** 把当前登录信息备份到 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();
+function backupAuthFile(dataDir, file, log = () => {}) {
+ const info = readAuthFile(file);
const dest = backupPath(dataDir, info.uid);
const tmp = dest + '.tmp';
- fs.writeFileSync(tmp, fs.readFileSync(AUTH_FILE), { mode: 0o600 });
+ fs.writeFileSync(tmp, fs.readFileSync(file), { mode: 0o600 });
fs.renameSync(tmp, dest);
fs.chmodSync(dest, 0o600);
updateMeta(dataDir, info);
- log(
- `[sync] 已备份账号 ${info.nickname || info.uid} (${info.uid}) -> ${dest}`
- );
+ log(`[sync] 已备份账号 ${info.nickname || info.uid} (${info.uid}) -> ${dest}`);
return info;
}
+/** 把活动登录信息备份到 accounts/<uid>.info(原子写入,0600)。 */
+function backupCurrent(dataDir, log = () => {}) {
+ if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号文件备份`);
+ ensureDirs(dataDir, log);
+ const records = listAuthRecords();
+ if (!records.length) throw new Error('未找到有效的登录信息文件');
+ const current = resolveCurrentAuth();
+ let result = null;
+ for (const record of records) {
+ const info = backupAuthFile(dataDir, record.file, log);
+ if (!result || (current.file && samePath(record.file, current.file))) result = info;
+ }
+ return Object.assign(result, { backedUp: records.length, ambiguous: !!current.ambiguous });
+}
+
+function resolveAuthTarget(dataDir, uid, authJson) {
+ if (!DYNAMIC_AUTH_DISCOVERY) return AUTH_FILE;
+ const meta = readMeta(dataDir);
+ const record = meta.accounts[String(uid)] || {};
+ const backup = authRecordFromJson(null, authJson);
+ if (!backup) throw new Error('备份文件认证数据无效,拒绝切换');
+ const targetName = safeAuthFileName(record.authFileName) ? record.authFileName : '';
+ if (targetName) {
+ const target = path.join(authDir(), targetName);
+ if (path.dirname(path.resolve(target)) !== path.resolve(authDir())) throw new Error('登录文件目标路径无效');
+ const existing = fs.existsSync(target) ? parseAuthFile(target) : null;
+ if (fs.existsSync(target) && !existing) throw new Error('登录文件目标不是当前客户端的有效认证文件,拒绝覆盖');
+ if (existing && existing.uid !== String(uid)) throw new Error('登录文件名已属于其他账号,拒绝覆盖');
+ return target;
+ }
+ const matching = listAuthRecords().filter((item) => item.uid === String(uid));
+ if (matching.length === 1) return matching[0].file;
+ throw new Error('账号缺少已确认的登录文件名,拒绝猜测写入目标');
+}
+
/** 列出所有已备份账号(直接读备份文件提取展示字段,按最近刷新时间倒序) */
function listAccounts(dataDir) {
if (!ACTIVE_PROFILE.capabilities.accounts) return [];
@@ -1098,6 +1240,9 @@ function deleteAccount(dataDir, uid) {
function switchTo(dataDir, uid, log = () => {}) {
if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号切换`);
migrateLegacyDataDir(dataDir, log);
+ // 不再用「当前 auth 目录是否 ambiguous」一票否决:切换写入的目标文件由
+ // resolveAuthTarget 精确决定(meta.json 记录 / 唯一 uid 匹配),目标无法唯一
+ // 确定时它自己会拒绝,避免历史 lastLogin 残留导致已登录账号切不回去。
const src = backupPath(dataDir, uid);
if (!fs.existsSync(src)) {
throw new Error(`未找到账号 ${uid} 的备份文件`);
@@ -1108,11 +1253,13 @@ function switchTo(dataDir, uid, log = () => {}) {
if (!acct || acct.uid !== uid) {
throw new Error('备份文件校验失败:uid 不匹配,已中止切换');
}
- const tmp = AUTH_FILE + '.wbswitch.tmp';
+ const target = resolveAuthTarget(dataDir, uid, json);
+ if (!target) throw new Error('未找到该账号已记录的登录文件名,拒绝猜测写入目标');
+ const tmp = target + '.wbswitch.tmp';
try {
fs.writeFileSync(tmp, raw, { mode: 0o600 });
- fs.renameSync(tmp, AUTH_FILE);
- fs.chmodSync(AUTH_FILE, 0o600);
+ fs.renameSync(tmp, target);
+ fs.chmodSync(target, 0o600);
} catch (e) {
// 沙箱环境(如从 WorkBuddy 托管后台运行)直接写系统目录会 EPERM。
// macOS 回退:osascript 委托 GUI 会话复制(不涉及内容转义,只传路径)。
@@ -1124,9 +1271,9 @@ function switchTo(dataDir, uid, log = () => {}) {
}
log(`[switch] 直写失败(${e.code}),改用 osascript 委托写入`);
const bridge = path.join(dataDir, '.auth-switch-bridge.tmp');
- const authBridge = AUTH_FILE + '.wbswitch.tmp';
+ const authBridge = target + '.wbswitch.tmp';
const bridgeQ = bridge.replace(/"/g, '\\"');
- const authQ = AUTH_FILE.replace(/"/g, '\\"');
+ const authQ = target.replace(/"/g, '\\"');
const tmpQ = authBridge.replace(/"/g, '\\"');
try {
// 1) 本进程写 bridge(数据目录可写)
@@ -1140,13 +1287,32 @@ function switchTo(dataDir, uid, log = () => {}) {
throw new Error(`写入登录文件失败: ${(e2.message || e2).toString().slice(0, 200)}`);
}
}
- retireLogoutMarker(log);
+ // Legacy call shape retained for source-compatible launchers: retireLogoutMarker(log);
+ retireLogoutMarker(log, target);
+ updateMeta(dataDir, {
+ uid: acct.uid,
+ nickname: acct.nickname || '',
+ uin: acct.uin || '',
+ phone: acct.phoneNumber || '',
+ authFileName: path.basename(target),
+ authDomain: normalizeAuthDomain(json.auth && json.auth.domain),
+ authIssuer: tokenIssuerOrigin(json.auth && (json.auth.accessToken || json.auth.access_token)),
+ });
log(`[switch] 已切换登录账号为 ${acct.nickname || uid} (${uid})`);
- return { uid: acct.uid, nickname: acct.nickname || '', uin: acct.uin || '' };
+ return { uid: acct.uid, nickname: acct.nickname || '', uin: acct.uin || '', authFile: target };
}
module.exports = {
AUTH_FILE,
+ authDir,
+ safeAuthFileName,
+ normalizeAuthDomain,
+ tokenIssuerOrigin,
+ parseAuthFile,
+ listAuthRecords,
+ resolveCurrentAuth,
+ currentAuthFile,
+ resolveAuthTarget,
ACTIVE_PROFILE,
defaultDataDir,
migrateLegacyDataDir,
diff --git a/scripts/profiles.js b/scripts/profiles.js
index 2c99faa..304210d 100644
--- a/scripts/profiles.js
+++ b/scripts/profiles.js
@@ -116,7 +116,6 @@ function getProfile(id = process.env.WBSWITCH_PROFILE || 'workbuddy-cn', options
const base = PROFILES[key];
if (base.kind !== 'workbuddy') return base;
const platform = options.platform || process.platform;
- if (platform !== 'win32') return base;
const env = options.env || process.env;
const dataDir = options.dataDir || env.WBSWITCH_DATA_DIR || profileDataDir(base);
const target = readWorkBuddyTarget({ dataDir, profileId: key, env, platform });
diff --git a/scripts/relaunch-with-cdp.sh b/scripts/relaunch-with-cdp.sh
index 444932f..4e18b38 100644
--- a/scripts/relaunch-with-cdp.sh
+++ b/scripts/relaunch-with-cdp.sh
@@ -22,6 +22,54 @@ case "$PROFILE" in
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
+
+# 企业版可能在 /Applications 下使用不同的 .app 名称。官方路径优先,
+# 其次按 profile 过滤候选,避免 CN 误选 WorkBuddy AI 的单实例。
+discover_workbuddy_app() {
+ local preferred="" candidate name
+ local -a matches=()
+ case "$PROFILE" in
+ workbuddy-ai)
+ preferred="/Applications/WorkBuddy AI.app"
+ ;;
+ workbuddy-cn)
+ preferred="/Applications/WorkBuddy.app"
+ ;;
+ *)
+ return 0
+ ;;
+ esac
+ if [ -x "$preferred/Contents/MacOS/Electron" ]; then matches+=("$preferred"); fi
+ for candidate in /Applications/WorkBuddy*.app; do
+ [ -x "$candidate/Contents/MacOS/Electron" ] || continue
+ [ "$candidate" = "$preferred" ] && continue
+ name="$(basename "$candidate" .app)"
+ case "$PROFILE:$name" in
+ workbuddy-ai:WorkBuddy|workbuddy-ai:WorkBuddy\ CN|workbuddy-ai:CodeBuddy*) continue ;;
+ workbuddy-ai:*) printf '%s' "$name" | grep -qi 'ai' || continue ;;
+ workbuddy-cn:WorkBuddy\ AI*|workbuddy-cn:WorkBuddyAI*|workbuddy-cn:CodeBuddy*) continue ;;
+ esac
+ matches+=("$candidate")
+ done
+ if [ "${#matches[@]}" -eq 1 ]; then
+ APP_BIN="${matches[0]}/Contents/MacOS/Electron"
+ APP_NAME="$(basename "${matches[0]}" .app)"
+ return 0
+ fi
+ APP_BIN=""
+ APP_NAME=""
+ if [ "${#matches[@]}" -gt 1 ]; then
+ APP_DISCOVERY_MULTIPLE=1
+ APP_DISCOVERY_ERROR="检测到多个 ${PROFILE} 客户端,将通过系统选择窗口确认:$(printf '%s, ' "${matches[@]}" | sed 's/, $//')"
+ else
+ APP_DISCOVERY_MULTIPLE=0
+ APP_DISCOVERY_ERROR="未找到 ${PROFILE} 客户端(搜索 /Applications/WorkBuddy*.app)"
+ fi
+ return 1
+}
+APP_DISCOVERY_ERROR=""
+APP_DISCOVERY_MULTIPLE=0
+discover_workbuddy_app || true
export WBSWITCH_PROFILE="$PROFILE"
if [ -z "$PORT" ]; then PORT="$DEFAULT_CDP_PORT"; fi
LABEL="com.workbuddy.workdaddy.${PROFILE}"
@@ -80,6 +128,54 @@ resolve_cdp_port() {
}
resolve_cdp_port
+# 若用户通过 workbuddy-target.json 指定了企业客户端,配置优先于自动发现。
+if [ -f "$DIR/scripts/workbuddy-target.js" ]; then
+ TARGET_ERR="/tmp/workdaddy-target-$$.err"
+ TARGET_BIN="$("$NODE_BIN" "$DIR/scripts/workbuddy-target.js" --resolve --profile="$PROFILE" --data-dir="$DATA_DIR" 2>"$TARGET_ERR")" || {
+ echo "错误:WorkBuddy 目标配置无效: $(tr '\n' ' ' <"$TARGET_ERR")"
+ rm -f "$TARGET_ERR"
+ exit 1
+ }
+ rm -f "$TARGET_ERR"
+ if [ -n "$TARGET_BIN" ]; then
+ APP_BIN="$TARGET_BIN"
+ APP_NAME="$(basename "$(dirname "$(dirname "$(dirname "$APP_BIN")")")" .app)"
+ fi
+fi
+
+# 候选不唯一或自动扫描不到时交给 macOS 原生应用选择器,由用户明确选择并自动记住结果。
+if [ -z "${TARGET_BIN:-}" ] && [ -z "$APP_BIN" ]; then
+ SELECTED_APP="$(osascript <<'APPLESCRIPT' 2>/dev/null
+try
+ set chosen to choose application with prompt "请选择要使用的 WorkBuddy 客户端"
+ POSIX path of (chosen as alias)
+on error number -128
+ return ""
+on error
+ return ""
+end try
+APPLESCRIPT
+)"
+ SELECTED_APP="${SELECTED_APP%/}"
+ if [ -z "$SELECTED_APP" ]; then
+ echo "已取消客户端选择"
+ exit 0
+ fi
+ APP_BIN="$SELECTED_APP/Contents/MacOS/Electron"
+ APP_NAME="$(basename "$SELECTED_APP" .app)"
+ if [ ! -x "$APP_BIN" ]; then
+ echo "错误:所选应用不是可用的 WorkBuddy 客户端: $SELECTED_APP"
+ exit 1
+ fi
+ if ! "$NODE_BIN" "$DIR/scripts/workbuddy-target.js" --configure --platform darwin \
+ --profile="$PROFILE" --binary="$APP_BIN" --data-dir="$DATA_DIR" >/dev/null 2>"$TARGET_ERR"; then
+ echo "错误:无法保存所选 WorkBuddy 客户端: $(tr '\n' ' ' <"$TARGET_ERR")"
+ rm -f "$TARGET_ERR"
+ exit 1
+ fi
+ rm -f "$TARGET_ERR"
+fi
+
# 清理旧版常驻服务和旧 profile 自启项,但保留账号数据;daemon 仅由本次手动执行启动。
for old_profile in workbuddy-cn workbuddy-ai codebuddy-cn codebuddy-intl; do
old_label="com.workbuddy.workdaddy.${old_profile}"
@@ -184,12 +280,14 @@ launch_plugin() {
# ---------- 2. 彻底退出 WorkBuddy ----------
echo "==> 退出 WorkBuddy ..."
- osascript -e "quit app \"${APP_NAME}\"" 2>/dev/null || true
+ if [ -n "$APP_NAME" ]; then
+ osascript -e "quit app \"${APP_NAME}\"" 2>/dev/null || true
+ fi
sleep 3
# 兜底:按真实进程路径精确清理(进程名是 Electron,切勿 killall Electron 以免误伤其他应用)
- pkill -f "$APP_BIN" 2>/dev/null || true
+ if [ -n "$APP_BIN" ]; then pkill -f "$APP_BIN" 2>/dev/null || true; fi
sleep 2
- if pgrep -f "$APP_BIN" >/dev/null 2>&1; then
+ if [ -n "$APP_BIN" ] && pgrep -f "$APP_BIN" >/dev/null 2>&1; then
echo " 警告:WorkBuddy 仍在运行,强制结束"
pkill -9 -f "$APP_BIN" 2>/dev/null || true
sleep 2
@@ -198,6 +296,7 @@ launch_plugin() {
# ---------- 3. 带调试端口启动 ----------
echo "==> 以 --remote-debugging-port=${PORT} 启动 WorkBuddy"
if [ ! -x "$APP_BIN" ]; then
+ echo "错误:${APP_DISCOVERY_ERROR:-未找到 WorkBuddy 应用}: APP_NAME=${APP_NAME} APP_BIN=${APP_BIN}"
echo " 错误:未找到 $APP_BIN"
exit 1
fi
@@ -207,7 +306,7 @@ launch_plugin() {
# ---------- 4. 验证 ----------
echo "==> 等待 CDP 端口开放"
OK=0
- for i in $(seq 1 15); do
+ for i in $(seq 1 60); do
sleep 1
if curl -s -m 2 "http://127.0.0.1:${PORT}/json/version" | grep -qiE 'WorkBuddy|CodeBuddy'; then
OK=1
@@ -222,10 +321,10 @@ launch_plugin() {
echo " 若未出现,可手动重新注入: curl -X POST http://127.0.0.1:47832/api/inject"
else
echo ""
- echo "警告:等待 15 秒仍未检测到 WorkBuddy CDP 端口 ${PORT}。"
+ echo "警告:等待 60 秒仍未检测到 WorkBuddy CDP 端口 ${PORT}。"
echo " WorkBuddy 可能忽略了该参数,或启动较慢。可再等几秒后执行:"
echo " curl http://127.0.0.1:${PORT}/json/version"
- "$NODE_BIN" "$REPORTER" --stage macos-cdp-timeout --message "等待 15 秒未检测到 WorkBuddy CDP 端口" --extra-json "{\"cdpPort\":${PORT}}" >/dev/null 2>&1 || true
+ "$NODE_BIN" "$REPORTER" --stage macos-cdp-timeout --message "等待 60 秒未检测到 WorkBuddy CDP 端口" --extra-json "{\"cdpPort\":${PORT}}" >/dev/null 2>&1 || true
fi
}
diff --git a/scripts/token-refresh.js b/scripts/token-refresh.js
new file mode 100644
index 0000000..fb8a9ce
--- /dev/null
+++ b/scripts/token-refresh.js
@@ -0,0 +1,101 @@
+'use strict';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+function normalizeTimestamp(value) {
+ if (value === null || value === undefined || value === '') return null;
+ const number = Number(value);
+ if (!Number.isFinite(number) || number <= 0) return null;
+ return Math.round(number < 1e11 ? number * 1000 : number);
+}
+
+function tokenValue(auth, camel, snake) {
+ const camelValue = auth && auth[camel];
+ const value = camelValue !== undefined && camelValue !== null && camelValue !== ''
+ ? camelValue
+ : auth && auth[snake];
+ return String(value || '');
+}
+
+function shouldRefreshAccessToken(auth, now = Date.now(), thresholdMs = DAY_MS) {
+ const expiresAt = normalizeTimestamp(auth && (auth.expiresAt ?? auth.expires_at));
+ return expiresAt === null || expiresAt <= now || expiresAt - now < thresholdMs;
+}
+
+function responseMessage(payload, status) {
+ if (payload && typeof payload === 'object') {
+ const value = payload.message || payload.msg || payload.error;
+ if (value) return String(value);
+ }
+ return status ? `HTTP ${status}` : '刷新请求失败';
+}
+
+/**
+ * Exchange a stored refresh token for fresh credentials without mutating the input.
+ * The upstream endpoint accepts the refresh token in X-Refresh-Token and returns
+ * either camelCase or snake_case token fields.
+ */
+async function refreshAuthToken(auth, options = {}) {
+ const original = auth && typeof auth === 'object' ? auth : {};
+ const refreshToken = tokenValue(original, 'refreshToken', 'refresh_token');
+ if (!refreshToken) return { ok: false, auth: original, error: '缺少 refresh token,无法刷新' };
+
+ const apiHost = String(options.apiHost || '').replace(/\/$/, '');
+ if (!apiHost) return { ok: false, auth: original, error: '缺少认证 API 地址,无法刷新' };
+ const fetchImpl = options.fetchImpl || globalThis.fetch;
+ if (typeof fetchImpl !== 'function') return { ok: false, auth: original, error: '当前运行时不支持 fetch' };
+
+ const accessToken = tokenValue(original, 'accessToken', 'access_token');
+ const headers = { accept: 'application/json', 'content-type': 'application/json', 'X-Refresh-Token': refreshToken };
+ if (accessToken) headers.authorization = `Bearer ${accessToken}`;
+
+ let response;
+ let payload;
+ try {
+ response = await fetchImpl(`${apiHost}/v2/plugin/auth/token/refresh`, {
+ method: 'POST',
+ headers,
+ body: '{}',
+ });
+ try {
+ payload = await response.json();
+ } catch (_) {
+ payload = {};
+ }
+ } catch (error) {
+ return { ok: false, auth: original, error: error && error.message ? error.message : '刷新请求失败' };
+ }
+
+ const code = payload && typeof payload.code === 'number' ? payload.code : null;
+ if (!response || response.ok !== true || (code !== null && code !== 0 && code !== 200)) {
+ return { ok: false, auth: original, error: responseMessage(payload, response && response.status) };
+ }
+ const data = payload && payload.data && typeof payload.data === 'object' ? payload.data : {};
+ const nextAccessToken = tokenValue(data, 'accessToken', 'access_token');
+ if (!nextAccessToken) return { ok: false, auth: original, error: '刷新响应缺少 accessToken' };
+
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
+ const next = Object.assign({}, original, {
+ accessToken: nextAccessToken,
+ refreshToken: tokenValue(data, 'refreshToken', 'refresh_token') || refreshToken,
+ lastRefreshTime: now,
+ });
+ const expiresAt = normalizeTimestamp(data.expiresAt ?? data.expires_at) ||
+ (Number(data.expiresIn ?? data.expires_in) > 0 ? now + Number(data.expiresIn ?? data.expires_in) * 1000 : normalizeTimestamp(original.expiresAt ?? original.expires_at));
+ const refreshExpiresAt = normalizeTimestamp(data.refreshExpiresAt ?? data.refresh_expires_at) ||
+ (Number(data.refreshExpiresIn ?? data.refresh_expires_in) > 0 ? now + Number(data.refreshExpiresIn ?? data.refresh_expires_in) * 1000 : normalizeTimestamp(original.refreshExpiresAt ?? original.refresh_expires_at));
+ if (expiresAt !== null) {
+ next.expiresAt = expiresAt;
+ next.expiresIn = Math.max(0, Math.round((expiresAt - now) / 1000));
+ }
+ if (refreshExpiresAt !== null) {
+ next.refreshExpiresAt = refreshExpiresAt;
+ next.refreshExpiresIn = Math.max(0, Math.round((refreshExpiresAt - now) / 1000));
+ }
+ for (const key of ['tokenType', 'domain', 'scope', 'sessionState', 'idToken']) {
+ if (data[key] !== undefined) next[key] = data[key];
+ }
+ return { ok: true, auth: next };
+}
+
+module.exports = { DAY_MS, normalizeTimestamp, shouldRefreshAccessToken, refreshAuthToken };
diff --git a/scripts/uninstall-win.cmd b/scripts/uninstall-win.cmd
new file mode 100644
index 0000000..3ea4ac4
--- /dev/null
+++ b/scripts/uninstall-win.cmd
@@ -0,0 +1,37 @@
+@echo off
+rem ============================================================
+rem WorkDaddy Windows 卸载核心(由 Uninstall-WorkDaddy.cmd 或安装目录调用)
+rem 作用:停止并校验 WorkDaddy 后台生命周期 → 移除登录自启 → 删除桌面快捷方式
+rem → 删除安装目录(默认保留 %APPDATA%\WorkDaddy 账号备份数据)
+rem 提示:卸载脚本必须与已安装目录同级运行(ps1 内部会校验),
+rem 因此请通过 zip 根目录的 Uninstall-WorkDaddy.cmd 或已安装目录的
+rem scripts\uninstall-win.cmd 执行。
+rem 设计:仅用 %~dp0 绝对路径定位 uninstall-win.ps1,杜绝相对路径歧义。
+rem ============================================================
+setlocal
+chcp 65001 >nul 2>&1
+
+where powershell >nul 2>nul
+if errorlevel 1 (
+ echo ERROR: PowerShell was not found.
+ pause
+ exit /b 1
+)
+
+if not exist "%~dp0uninstall-win.ps1" (
+ echo ERROR: uninstall-win.ps1 was not found beside this file.
+ pause
+ exit /b 3
+)
+
+powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0uninstall-win.ps1" %*
+set "EXIT_CODE=%ERRORLEVEL%"
+echo.
+if "%EXIT_CODE%"=="0" (
+ powershell -NoProfile -Command "$b='5Y246L295a6M5oiQ77yM6LSm5Y+35aSH5Lu95pWw5o2u5bey5L+d55WZ77yI5ZyoICVBUFBEQVRBJVxXb3JrRGFkZHnvvInjgII='; [Console]::OutputEncoding=[Text.Encoding]::UTF8; [Console]::WriteLine([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b)))"
+ powershell -NoProfile -Command "$b='5aaC6ZyA5ZCM5pe25Yig6Zmk6LSm5Y+35aSH5Lu977yM6K+36L+Q6KGMIHNjcmlwdHNcdW5pbnN0YWxsLXdpbi5wczEgLVJlbW92ZURhdGE='; [Console]::OutputEncoding=[Text.Encoding]::UTF8; [Console]::WriteLine([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b)))"
+) else (
+ echo ERROR: uninstall failed with code %EXIT_CODE%. See the output above.
+ echo If WorkDaddy is running with higher privileges, close it first and retry.
+)
+pause
\ No newline at end of file
diff --git a/scripts/uninstall-win.ps1 b/scripts/uninstall-win.ps1
index f26e40b..6539b68 100644
--- a/scripts/uninstall-win.ps1
+++ b/scripts/uninstall-win.ps1
@@ -52,6 +52,20 @@ try {
Write-Host ' 已移除登录自启项'
} catch {}
+# 2.5) 删除桌面快捷方式(与 install-win.ps1 创建对称;只删当前 profile 的,
+# 绝不连带另一个 profile(WorkDaddy / WorkDaddy AI 各自卸载各自清理)
+$desktopDir = [Environment]::GetFolderPath('Desktop')
+if (-not $desktopDir) { $desktopDir = Join-Path $env:USERPROFILE 'Desktop' }
+$lnk = Join-Path $desktopDir ($productName + '.lnk')
+if (Test-Path -LiteralPath $lnk -PathType Leaf) {
+ try {
+ Remove-Item -LiteralPath $lnk -Force -ErrorAction Stop
+ Write-Host (' 已删除桌面快捷方式: ' + $lnk)
+ } catch {
+ Write-Host (' 桌面快捷方式删除失败(可手动删除): ' + $lnk + ' - ' + $_.Exception.Message)
+ }
+}
+
# 3) 删除安装目录(Inno Setup 调用时由卸载器负责删除)
if (-not $SkipAppRemoval -and (Test-Path $AppDir)) {
Remove-Item -LiteralPath $AppDir -Recurse -Force -ErrorAction Stop
diff --git a/scripts/verify-win.cmd b/scripts/verify-win.cmd
index 263e7b8..714a350 100644
--- a/scripts/verify-win.cmd
+++ b/scripts/verify-win.cmd
@@ -20,7 +20,7 @@ set "FAIL=0"
rem ---- 1) 关键文件齐全 ----
echo.
echo [1/6] 检查关键文件...
-for %%F in (daemon.js session-db.js secure-transfer.js lib.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 windows-relaunch-standard.ps1 prepare-win-install.ps1 workbuddy-compat.js inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 uninstall-win.ps1 apply-update.ps1 win\setup.sed) do (
+for %%F in (daemon.js session-db.js secure-transfer.js lib.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 windows-relaunch-standard.ps1 prepare-win-install.ps1 workbuddy-compat.js inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 uninstall-win.cmd uninstall-win.ps1 apply-update.ps1 win\setup.sed) do (
if not exist "%SCRIPT_DIR%%%F" (
echo 缺失: %%~F
set /a FAIL+=1
@@ -34,6 +34,11 @@ if exist "%SCRIPT_DIR%..\Install-WorkDaddy.cmd" (
echo 提示: 顶层 Install-WorkDaddy.cmd 未就位(打包时从 scripts\ 提升到 zip 根)
)
if exist "%SCRIPT_DIR%..\Start-WorkDaddy.cmd" echo 顶层入口 Start-WorkDaddy.cmd 存在
+if exist "%SCRIPT_DIR%..\Uninstall-WorkDaddy.cmd" (
+ echo 顶层入口 Uninstall-WorkDaddy.cmd 存在
+) else (
+ echo 提示: 顶层 Uninstall-WorkDaddy.cmd 未就位(打包时从 scripts\ 提升到 zip 根)
+)
if not exist "%SCRIPT_DIR%node_modules\ws\index.js" (
echo 警告: node_modules\ws 缺失(DevTools 代理降级,其他功能不受影响)
)
@@ -57,7 +62,7 @@ if errorlevel 1 (
rem ---- 3) 脚本语法静态检查(node --check,不执行)----
echo.
echo [3/6] 校验 JS 语法...
-for %%F in (daemon.js session-db.js secure-transfer.js lib.js watchdog.js win-launcher.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js) do (
+for %%F in (daemon.js session-db.js secure-transfer.js lib.js watchdog.js win-launcher.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js) do (
"%NODE%" --check "%SCRIPT_DIR%%%F" >nul 2>&1
if errorlevel 1 (
echo 语法错误: %%~F
diff --git a/scripts/win-launcher.js b/scripts/win-launcher.js
index d3d8be5..d79e8fe 100644
--- a/scripts/win-launcher.js
+++ b/scripts/win-launcher.js
@@ -1305,7 +1305,8 @@ function nativeWorkBuddyRunning() {
function stopNativeWorkBuddy() {
const result = runNativeHelper(['--terminate-workbuddy', '--profile', PROFILE.id], { timeout: 60000 });
if (result.status !== 0) {
- throw new Error('无法精确重启当前 WorkBuddy(错误码 ' + result.status + ')');
+ const detail = String(result.stderr || '').trim();
+ throw new Error('无法精确重启当前 WorkBuddy(错误码 ' + result.status + ')' + (detail ? ': ' + detail : ''));
}
}
diff --git a/scripts/win/workdaddy.iss b/scripts/win/workdaddy.iss
index d4a6f98..3ad0c81 100644
--- a/scripts/win/workdaddy.iss
+++ b/scripts/win/workdaddy.iss
@@ -41,6 +41,7 @@ PrivilegesRequired=lowest
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
WizardStyle=modern
+UninstallStyle=modern
Compression=lzma2/ultra64
SolidCompression=yes
OutputDir={#OutputDir}
@@ -50,7 +51,7 @@ CloseApplications=no
RestartApplications=no
RestartIfNeededByRun=no
MinVersion=10.0
-UninstallDisplayName={#ProductName}
+UninstallDisplayName={#ProductName} {#AppVersion}
[Languages]
Name: "chinesesimplified"; MessagesFile: "ChineseSimplified.isl"
@@ -523,12 +524,86 @@ begin
Result := ResultCode = 0;
end;
+function UninstallerDisplayName(): String;
+begin
+ // 用户可见的卸载入口名:直观且不带 Inno 的 unins000 序号。
+ Result := '卸载 ' + '{#ProductName}';
+end;
+
+function RenamedUninstallerPath(): String;
+begin
+ Result := ExpandConstant('{app}\') + UninstallerDisplayName() + '.exe';
+end;
+
+procedure CreateUninstallShortcut(const TargetPath: String);
+var
+ Shell: Variant;
+ Shortcut: Variant;
+ IconFile: String;
+ GroupDir: String;
+begin
+ // 只在开始菜单创建“卸载 …”入口(卸载入口不进桌面,避免打扰用户)。
+ Shell := CreateOleObject('WScript.Shell');
+ IconFile := ExpandConstant('{app}\scripts\{#PackageName}-{#AppVersion}.ico');
+ GroupDir := ExpandConstant('{group}');
+ if GroupDir <> '' then
+ begin
+ Shortcut := Shell.CreateShortCut(GroupDir + '\' + UninstallerDisplayName() + '.lnk');
+ Shortcut.TargetPath := TargetPath;
+ Shortcut.Description := UninstallerDisplayName() + ' - ' + '{#AppVersion}';
+ if FileExists(IconFile) then
+ Shortcut.IconLocation := IconFile + ',0';
+ Shortcut.Save();
+ end;
+end;
+
+procedure RenameUninstallerAndFixEntries();
+var
+ OldPath, NewPath, OldDat, NewDat, UninstallKey: String;
+begin
+ OldPath := ExpandConstant('{app}\unins000.exe');
+ NewPath := RenamedUninstallerPath();
+ if FileExists(NewPath) then
+ DeleteFile(NewPath);
+ if not FileExists(OldPath) then
+ exit;
+ if RenameFile(OldPath, NewPath) then
+ begin
+ // Inno 卸载器按自身 exe 文件名推导同名的 .dat(卸载配置/日志);
+ // 只改 exe 不改 dat 会报“xxxx.dat 不存在,无法卸载”,必须一起改名。
+ OldDat := ExpandConstant('{app}\unins000.dat');
+ NewDat := ChangeFileExt(NewPath, '.dat');
+ if FileExists(OldDat) and not FileExists(NewDat) then
+ RenameFile(OldDat, NewDat);
+ UninstallKey := 'Software\Microsoft\Windows\CurrentVersion\Uninstall\{#AppGuid}_is1';
+ // 同步“应用和功能”的卸载入口,避免指向已改名的旧路径。
+ RegWriteStringValue(HKCU, UninstallKey, 'UninstallString', '"' + NewPath + '"');
+ RegWriteStringValue(HKCU, UninstallKey, 'QuietUninstallString', '"' + NewPath + '" /SILENT');
+ CreateUninstallShortcut(NewPath);
+ end;
+end;
+
procedure CurStepChanged(CurStep: TSetupStep);
begin
if CurStep = ssPostInstall then
begin
if not SaveSelectedClient() then
RaiseException('无法保存 WorkBuddy 客户端选择,安装已停止。');
+ RenameUninstallerAndFixEntries();
+ end;
+end;
+
+procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
+var
+ GroupShortcut: String;
+begin
+ // 安装时用 COM 创建的“卸载 …”快捷方式不在 Inno [Icons] 内,
+ // 卸载器不会自动清理,必须在卸载流程里显式删除。
+ if CurUninstallStep = usUninstall then
+ begin
+ GroupShortcut := ExpandConstant('{group}\') + UninstallerDisplayName() + '.lnk';
+ if FileExists(GroupShortcut) then
+ DeleteFile(GroupShortcut);
end;
end;
@@ -624,7 +699,10 @@ begin
end;
if ResultCode <> 10 then
begin
- MsgBox('无法确认 WorkBuddy 是否已退出(错误码 ' + IntToStr(ResultCode) + ')。安装已停止。', mbError, MB_OK);
+ if ResultCode = 12 then
+ MsgBox('无法确认 WorkBuddy 是否已退出(错误码 12)。检测到多个同名进程,或进程路径与刚才选择的客户端不一致。为避免误关其他客户端,安装已停止。请重启 Windows 后重新打开安装包,并在客户端选择页面确认 .exe 路径。', mbError, MB_OK)
+ else
+ MsgBox('无法确认 WorkBuddy 是否已退出(错误码 ' + IntToStr(ResultCode) + ')。系统没有返回可靠的进程信息,安装已停止。请重启 Windows,暂时退出安全软件的拦截功能后,再直接双击安装包重试。', mbError, MB_OK);
exit;
end;
Choice := ShowWorkBuddyCloseDialog();
@@ -639,11 +717,12 @@ begin
end;
if ResultCode <> 0 then
begin
- MsgBox('无法安全结束当前 WorkBuddy 进程。可能原因:' + #13#10 +
- '• WorkBuddy 由其他用户或管理员权限启动,当前安装器无法跨权限结束;' + #13#10 +
- '• 系统正在退出客户端,进程状态暂时不可查询;' + #13#10 +
- '• 安全软件或系统策略阻止结束进程,或检测到多个安装目录。' + #13#10 +
- '请手动结束当前客户端后点击“重新检测”。', mbError, MB_OK);
+ if ResultCode = 11 then
+ MsgBox('无法安全结束当前 WorkBuddy 进程(错误码 11)。普通安装器不会跨权限强行结束进程。请点击“取消”,打开任务管理器(Ctrl+Shift+Esc),结束你刚才选择的 WorkBuddy;如果它是用“以管理员身份运行”启动的,请先用相同方式退出。然后直接双击安装包,再点击“重新检测”。', mbError, MB_OK)
+ else if ResultCode = 12 then
+ MsgBox('无法安全结束当前 WorkBuddy 进程(错误码 12)。检测到多个同名进程或安装路径不一致,为避免误关其他客户端,安装已停止。请重启 Windows 后重新选择正确的 WorkBuddy .exe,再次安装。', mbError, MB_OK)
+ else
+ MsgBox('无法安全结束当前 WorkBuddy 进程(错误码 ' + IntToStr(ResultCode) + ')。请重启 Windows,确认没有 WorkBuddy 窗口或后台进程后,再直接双击安装包重试。', mbError, MB_OK);
end;
end;
end;
@@ -679,11 +758,13 @@ begin
exit;
end;
if ResultCode = 11 then
- Result := '无法安全停止 WorkDaddy 后台进程。可能原因:' + #13#10 +
- '• 正在运行的 WorkDaddy 使用了高于当前安装器的权限,普通安装器不会跨权限强行结束;' + #13#10 +
- '• WorkDaddy 退出后仍有后台进程未及时结束,或文件仍被占用;' + #13#10 +
- '• 安全软件或系统策略阻止后台进程退出。' + #13#10 +
- '请手动结束 WorkDaddy 后重试,并确保 WorkDaddy 通过普通方式启动。'
+ Result := '无法安全停止 WorkDaddy 后台进程:安装无法继续。检测到 WorkDaddy 或 WorkDaddyLauncher 仍在运行,但当前安装器没有结束它的权限(错误码 11)。请按以下步骤操作:' + #13#10 +
+ '1. 点击“取消”;' + #13#10 +
+ '2. 按 Ctrl+Shift+Esc 打开任务管理器,结束 WorkDaddy 和 WorkDaddyLauncher;' + #13#10 +
+ '3. 如果 WorkDaddy 是用“以管理员身份运行”启动的,请先用相同权限退出;' + #13#10 +
+ '4. 确认 UAC 已开启并重启 Windows,然后直接双击安装包重试。不要选择“以管理员身份运行”。'
+ else if ResultCode = 12 then
+ Result := '安装无法继续:旧版 WorkDaddy 的状态文件与实际程序不一致,或发现多个同名进程(错误码 12)。为避免误关其他程序,安装器没有强行处理。请重启 Windows,确认 WorkBuddy 已完全退出,并直接双击安装包重试;不要手动删除 WorkDaddy 数据目录。'
else if ResultCode <> 0 then
- Result := '无法安全停止 WorkDaddy 后台进程(错误码 ' + IntToStr(ResultCode) + ')。可能原因是进程仍在退出、文件被占用、安装目录不一致,或安全软件拦截。请手动结束 WorkDaddy 后重试。';
+ Result := '安装无法完成 WorkDaddy 后台清理(错误码 ' + IntToStr(ResultCode) + ')。系统没有返回可靠的进程信息,可能是安全软件拦截或文件仍被占用。请重启 Windows,确认 WorkBuddy 和 WorkDaddy 都已退出后,直接双击安装包重试。';
end;
diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.go
index f8f938c..c62e68a 100644
--- a/scripts/windows-native/main.go
+++ b/scripts/windows-native/main.go
@@ -455,7 +455,7 @@ func readLockPID(path string) int {
return owner.PID
}
-func terminateExactProcess(pid int, expectedPath string, label string) (bool, int, error) {
+func inspectExactProcess(pid int, expectedPath string, label string) (bool, int, error) {
if pid <= 0 {
return false, 0, nil
}
@@ -482,6 +482,17 @@ func terminateExactProcess(pid int, expectedPath string, label string) (bool, in
if !samePath(actual, expectedPath) {
return false, exitIdentityMismatch, fmt.Errorf("PID %d is %s, expected %s", pid, actual, expectedPath)
}
+ return true, 0, nil
+}
+
+func terminateExactProcess(pid int, expectedPath string, label string) (bool, int, error) {
+ active, code, inspectErr := inspectExactProcess(pid, expectedPath, label)
+ if inspectErr != nil {
+ return false, code, inspectErr
+ }
+ if !active {
+ return false, 0, nil
+ }
handle, err := openProcess(uint32(pid), processTerminate|synchronize|processQueryLimitedInformation)
if err != nil {
if errors.Is(err, syscall.ERROR_ACCESS_DENIED) {
@@ -508,7 +519,7 @@ func terminateExactNode(pid int, expectedNode string) (bool, int, error) {
return terminateExactProcess(pid, expectedNode, "node")
}
-func stopInstalledLauncher(appDir string) int {
+func stopInstalledLauncher(appDir string, elevated bool) int {
expectedLauncher := filepath.Join(appDir, "WorkDaddyLauncher.exe")
records, err := enumerateProcesses()
if err != nil {
@@ -534,6 +545,10 @@ func stopInstalledLauncher(appDir string) int {
if len(matches) == 0 {
return 0
}
+ if elevated {
+ fmt.Fprintln(os.Stderr, "installed WorkDaddy launcher is still running; lifecycle stop requires standard user privilege")
+ return exitAccessDenied
+ }
_, code, stopErr := terminateExactProcess(int(matches[0].PID), expectedLauncher, "launcher")
if stopErr != nil {
fmt.Fprintln(os.Stderr, stopErr)
@@ -644,7 +659,7 @@ func recoverWatchdogPID(records []processRecord, expectedNode string, daemonPID
return int(candidate.PID), nil
}
-func stopLifecycle(profile, appDir string) int {
+func stopLifecycle(profile, appDir string, elevated bool) int {
dir, err := dataDir(profile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -701,6 +716,20 @@ func stopLifecycle(profile, appDir string) int {
continue
}
seen[candidate.pid] = true
+ // An elevated helper may clear a stale PID, but must refuse any active
+ // lifecycle so it never becomes a cross-privilege process terminator.
+ active, code, inspectErr := inspectExactProcess(candidate.pid, expectedNode, "node")
+ if inspectErr != nil {
+ fmt.Fprintln(os.Stderr, inspectErr)
+ return code
+ }
+ if !active {
+ continue
+ }
+ if elevated {
+ fmt.Fprintln(os.Stderr, "running WorkDaddy lifecycle requires standard user privilege")
+ return exitAccessDenied
+ }
_, code, stopErr := terminateExactNode(candidate.pid, expectedNode)
if stopErr != nil {
fmt.Fprintln(os.Stderr, stopErr)
@@ -712,7 +741,7 @@ func stopLifecycle(profile, appDir string) int {
_ = os.Remove(candidate.path)
}
}
- if code := stopInstalledLauncher(appDir); code != 0 {
+ if code := stopInstalledLauncher(appDir, elevated); code != 0 {
return code
}
return 0
@@ -857,15 +886,11 @@ func helperMain(appDir, profile string) (bool, int) {
fmt.Fprintln(os.Stderr, "cannot determine helper privilege:", err)
return true, exitFailure
}
- if elevated {
- fmt.Fprintln(os.Stderr, "lifecycle stop requires standard user privilege")
- return true, exitAccessDenied
- }
targetApp := argumentValue("--app-dir")
if targetApp == "" {
targetApp = appDir
}
- return true, stopLifecycle(profile, targetApp)
+ return true, stopLifecycle(profile, targetApp, elevated)
}
if hasArgument("--self-test") {
elevated, err := isElevated()
diff --git a/scripts/workbuddy-target.js b/scripts/workbuddy-target.js
index 9f77377..babe7f5 100644
--- a/scripts/workbuddy-target.js
+++ b/scripts/workbuddy-target.js
@@ -16,7 +16,9 @@ function emptyTarget(configured = false, source = 'default') {
}
function platformPath(platform) {
- return platform === 'win32' ? path.win32 : path;
+ // 注意:Windows 上 require('path') 与 path.win32 是同一引用,
+ // 非 win32 平台必须显式返回 path.posix,否则 darwin 等分支会被误判为 win32。
+ return platform === 'win32' ? path.win32 : path.posix;
}
function targetFile(dataDir) {
@@ -39,8 +41,11 @@ function validateApiHost(value) {
function validateProcessName(value, pathApi) {
const name = clean(value);
- if (!/^[^\\/:*?"<>|\0]+\.exe$/i.test(name) || name !== pathApi.basename(name)) {
- throw new Error('WorkBuddy 进程名必须是单个 .exe 文件名');
+ const isSafeName = /^[^\\/:*?"<>|\0]+$/.test(name) && name === pathApi.basename(name);
+ if (!isSafeName || (pathApi === path.win32 && !/\.exe$/i.test(name))) {
+ throw new Error(pathApi === path.win32
+ ? 'WorkBuddy 进程名必须是单个 .exe 文件名'
+ : 'WorkBuddy 进程名必须是单个文件名');
}
return name;
}
@@ -170,9 +175,39 @@ function buildTargetFromBinary(options = {}) {
const platform = options.platform || process.platform;
const pathApi = platformPath(platform);
const binary = clean(options.binary);
- if (!binary || !isAbsolute(binary, platform)) throw new Error('请选择完整的 WorkBuddy .exe 路径');
+ if (!binary || !isAbsolute(binary, platform)) throw new Error(platform === 'win32' ? '请选择完整的 WorkBuddy .exe 路径' : '请选择完整的 WorkBuddy 应用可执行文件路径');
const processName = pathApi.basename(binary);
- if (!/\.exe$/i.test(processName)) throw new Error('请选择 WorkBuddy 的 .exe 主程序');
+ if (platform === 'win32' && !/\.exe$/i.test(processName)) throw new Error('请选择 WorkBuddy 的 .exe 主程序');
+ // Keep accepting legacy cross-platform test/configuration paths ending in
+ // .exe; real macOS app binaries use the branch below with their native name.
+ if (platform === 'darwin' && !/\.exe$/i.test(processName)) {
+ // macOS 路径必须始终用 posix 拼装:Windows 上默认 path 是 win32,
+ // 用它 join 会产出 C:\ 风格路径,被 darwin 的绝对路径校验拒绝。
+ const posixPath = path.posix;
+ const profileId = clean(options.profileId) || 'workbuddy-cn';
+ const port = Number(options.cdpPort) || (profileId === 'workbuddy-ai' ? 9223 : 9222);
+ const appName = posixPath.basename(binary.replace(/\/Contents\/MacOS\/[^/]+$/i, '')).replace(/\.app$/i, '');
+ const home = options.home || os.homedir();
+ const appSupport = posixPath.join(home, 'Library', 'Application Support');
+ const extensionAuth = posixPath.join(appSupport, 'CodeBuddyExtension', 'Data', 'Public', 'auth');
+ const ai = profileId === 'workbuddy-ai';
+ const workbuddyRoot = posixPath.join(home, ai ? '.workbuddy-ai' : '.workbuddy');
+ return validateTarget({
+ schemaVersion: 1,
+ clientType: 'enterprise',
+ profileId,
+ binary,
+ version: clean(options.version),
+ processNames: [processName],
+ authFile: posixPath.join(extensionAuth, ai ? 'workbuddy-desktop-ai.info' : 'workbuddy-desktop.info'),
+ sessionDb: posixPath.join(workbuddyRoot, 'workbuddy.db'),
+ modelsFile: posixPath.join(workbuddyRoot, 'models.json'),
+ apiHost: ai ? 'https://www.workbuddy.ai' : 'https://www.codebuddy.cn',
+ targetHints: [appName].filter(Boolean),
+ cdp: { mode: 'argument', port },
+ capabilities: { accounts: true, sessions: true, models: true, stashPrompt: true, theme: true, checkin: true },
+ }, { platform });
+ }
const processNames = inferredProcessNames(binary, platform);
const stem = processName.replace(/\.exe$/i, '').toLowerCase();
const home = options.home || os.homedir();
@@ -249,7 +284,16 @@ function readWorkBuddyTarget({ dataDir, profileId, env = process.env, platform =
delete merged.processName;
}
if (envVersion) merged.version = envVersion;
- return { ...validateTarget(merged, { platform }), configured: true, source: envBinary ? 'environment' : 'file' };
+ // 读取须容忍跨平台目标:Windows 管理机上可能读出为 macOS 客户端写入的
+ // target(进程名非 .exe),按当前平台严格校验会误报;先按当前平台尝试,
+ // 失败则按另一平台校验,仅平台相关约束(.exe / 绝对路径形态)被放宽。
+ try {
+ return { ...validateTarget(merged, { platform }), configured: true, source: envBinary ? 'environment' : 'file' };
+ } catch (error) {
+ const fallbackPlatform = platform === 'win32' ? 'darwin' : 'win32';
+ if (fallbackPlatform === platform) throw error;
+ return { ...validateTarget(merged, { platform: fallbackPlatform }), configured: true, source: envBinary ? 'environment' : 'file' };
+ }
}
if (envBinary) return { configured: true, binary: envBinary, version: envVersion, source: 'environment' };
if (!target) return emptyTarget();
@@ -290,7 +334,10 @@ function removeWorkBuddyTarget({ dataDir } = {}) {
function cliValue(argv, name) {
const index = argv.indexOf(name);
- return index >= 0 && index + 1 < argv.length ? argv[index + 1] : '';
+ if (index >= 0 && index + 1 < argv.length) return argv[index + 1];
+ const prefix = `${name}=`;
+ const inline = argv.find((value) => typeof value === 'string' && value.startsWith(prefix));
+ return inline ? inline.slice(prefix.length) : '';
}
function configureFromInstaller(argv = process.argv.slice(2)) {
@@ -299,7 +346,21 @@ function configureFromInstaller(argv = process.argv.slice(2)) {
const binary = clean(cliValue(argv, '--binary'));
const version = clean(cliValue(argv, '--version'));
const dataDir = clean(cliValue(argv, '--data-dir'));
- const pathApi = platformPath('win32');
+ const platform = clean(cliValue(argv, '--platform')) || process.env.WBSWITCH_TARGET_PLATFORM || 'win32';
+ const pathApi = platformPath(platform);
+ if (platform !== 'win32' && platform !== 'darwin') throw new Error('仅支持 win32 或 darwin 客户端配置');
+ if (platform !== 'win32') {
+ const target = buildTargetFromBinary({
+ binary,
+ version,
+ profileId,
+ cdpPort: profileId === 'workbuddy-ai' ? 9223 : 9222,
+ platform,
+ });
+ const saved = writeWorkBuddyTarget({ dataDir, profileId, target, platform });
+ process.stdout.write(JSON.stringify({ ok: true, name: pathApi.basename(saved.binary), version: saved.version || '', clientType: saved.clientType }) + '\n');
+ return saved;
+ }
const expectedName = profileId === 'workbuddy-ai' ? 'WorkBuddyAI.exe' : 'WorkBuddy.exe';
const official = pathApi.basename(binary).toLowerCase() === expectedName.toLowerCase();
const target = official
@@ -316,7 +377,24 @@ function configureFromInstaller(argv = process.argv.slice(2)) {
return saved;
}
-if (require.main === module && process.argv.slice(2).includes('--configure')) {
+function resolveFromConfig(argv = process.argv.slice(2)) {
+ const profileId = clean(cliValue(argv, '--profile'));
+ const dataDir = clean(cliValue(argv, '--data-dir'));
+ if (!profileId || !dataDir) return '';
+ const target = readWorkBuddyTarget({ dataDir, profileId, platform: process.platform });
+ if (!target.configured || !target.binary) return '';
+ process.stdout.write(target.binary + '\n');
+ return target.binary;
+}
+
+if (require.main === module && process.argv.slice(2).includes('--resolve')) {
+ try {
+ resolveFromConfig();
+ } catch (error) {
+ process.stderr.write(String(error && error.message || error) + '\n');
+ process.exitCode = 1;
+ }
+} else if (require.main === module && process.argv.slice(2).includes('--configure')) {
try {
configureFromInstaller();
} catch (error) {
@@ -332,9 +410,11 @@ module.exports = {
buildTargetFromBinary,
configureFromInstaller,
inferredProcessNames,
+ resolveFromConfig,
readWorkBuddyTarget,
removeWorkBuddyTarget,
targetFile,
+ validateProcessName,
validateTarget,
writeWorkBuddyTarget,
};
diff --git a/test/auth-discovery.test.js b/test/auth-discovery.test.js
new file mode 100644
index 0000000..3824e29
--- /dev/null
+++ b/test/auth-discovery.test.js
@@ -0,0 +1,168 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+
+function jwt(issuer) {
+ const payload = Buffer.from(JSON.stringify({ iss: issuer }), 'utf8').toString('base64url');
+ return `header.${payload}.signature`;
+}
+
+function fixture() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-auth-'));
+ // lib.js 按平台定位 auth 目录:macOS 用 ~/Library/Application Support,
+ // Windows 用 %LOCALAPPDATA%;必须按平台建隔离目录,否则会扫到本机真实账号文件。
+ const authDir = os.platform() === 'win32'
+ ? path.join(root, 'AppData', 'Local', 'CodeBuddyExtension', 'Data', 'Public', 'auth')
+ : path.join(root, 'Library', 'Application Support', 'CodeBuddyExtension', 'Data', 'Public', 'auth');
+ const dataDir = path.join(root, 'WorkDaddy');
+ fs.mkdirSync(authDir, { recursive: true });
+ return { root, authDir, dataDir };
+}
+
+function auth(uid, issuer, lastLogin = false) {
+ return {
+ account: { uid, nickname: uid, lastLogin },
+ auth: { accessToken: jwt(issuer), domain: new URL(issuer).origin, lastRefreshTime: Date.now() },
+ };
+}
+
+function run(root, dataDir, code, profile = 'workbuddy-cn') {
+ const script = `const lib=require(${JSON.stringify(path.join(__dirname, '..', 'scripts', 'lib.js'))}); ${code}`;
+ const result = spawnSync(process.execPath, ['-e', script], {
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ HOME: root,
+ LOCALAPPDATA: path.join(root, 'AppData', 'Local'),
+ WBSWITCH_PROFILE: profile,
+ WBSWITCH_DATA_DIR: dataDir,
+ },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(result.stdout || 'null');
+}
+
+test('default WorkBuddy profiles scan valid info files regardless of filename', () => {
+ const f = fixture();
+ try {
+ fs.writeFileSync(path.join(f.authDir, 'Tencent-Cloud.coding-copilot.info'), JSON.stringify(auth('cn-user', 'https://www.codebuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.authDir, 'opaque-login.info'), JSON.stringify(auth('cn-user-2', 'https://www.workbuddy.cn/auth/realms/copilot', true)));
+ fs.writeFileSync(path.join(f.authDir, 'snapshot.info.tmp'), '{}');
+ fs.writeFileSync(path.join(f.authDir, 'other-product.info'), JSON.stringify(auth('other', 'https://untrusted.example/auth')));
+ const records = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.listAuthRecords().map(x=>({uid:x.uid,name:x.authFileName}))))');
+ assert.deepEqual(records.map((x) => x.uid).sort(), ['cn-user', 'cn-user-2']);
+ const current = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.resolveCurrentAuth()))');
+ assert.equal(path.basename(current.file), 'opaque-login.info');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('multiple valid files without one lastLogin marker are ambiguous and backup all', () => {
+ const f = fixture();
+ try {
+ fs.writeFileSync(path.join(f.authDir, 'a.info'), JSON.stringify(auth('a', 'https://www.codebuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.authDir, 'b.info'), JSON.stringify(auth('b', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ const current = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.resolveCurrentAuth()))');
+ assert.equal(current.file, null);
+ assert.equal(current.ambiguous, true);
+ const backup = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.backupCurrent(process.env.WBSWITCH_DATA_DIR)))');
+ assert.equal(backup.backedUp, 2);
+ assert.equal(fs.existsSync(path.join(f.dataDir, 'accounts', 'a.info')), true);
+ assert.equal(fs.existsSync(path.join(f.dataDir, 'accounts', 'b.info')), true);
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('switch writes only the metadata-recorded opaque filename', () => {
+ const f = fixture();
+ try {
+ const source = path.join(f.authDir, 'channel-a.info');
+ fs.writeFileSync(source, JSON.stringify(auth('a', 'https://www.codebuddy.cn/auth/realms/copilot', true)));
+ fs.writeFileSync(path.join(f.authDir, 'channel-b.info'), JSON.stringify(auth('b', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');
+ fs.unlinkSync(source);
+ fs.unlinkSync(path.join(f.authDir, 'channel-b.info'));
+ const switched = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.switchTo(process.env.WBSWITCH_DATA_DIR,"a")))');
+ assert.equal(switched.authFile.endsWith('channel-a.info'), true);
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.authDir, 'channel-a.info'), 'utf8')).account.uid, 'a');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('explicit WBSWITCH_AUTH_FILE keeps the legacy single-file behavior', () => {
+ const f = fixture();
+ const file = path.join(f.authDir, 'legacy-name.info');
+ fs.writeFileSync(file, JSON.stringify({ account: { uid: 'legacy' }, auth: {} }));
+ const script = `const lib=require(${JSON.stringify(path.join(__dirname, '..', 'scripts', 'lib.js'))}); process.stdout.write(JSON.stringify(lib.readAuthFile().uid))`;
+ const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf8', env: { ...process.env, WBSWITCH_AUTH_FILE: file, WBSWITCH_DATA_DIR: f.dataDir } });
+ try {
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(result.stdout), 'legacy');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('missing filename metadata refuses a switch instead of falling back to a guessed file', () => {
+ const f = fixture();
+ try {
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'target.info'), JSON.stringify(auth('target', 'https://www.codebuddy.cn/auth/realms/copilot')));
+ const result = run(f.root, f.dataDir, `try { lib.switchTo(process.env.WBSWITCH_DATA_DIR,'target'); process.stdout.write('unexpected') } catch (e) { process.stdout.write(JSON.stringify(e.message)) }`);
+ assert.match(result, /拒绝/);
+ assert.equal(fs.readdirSync(f.authDir).length, 0);
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('canonical fixed info file wins over historical lastLogin markers', () => {
+ const f = fixture();
+ try {
+ // 真实回归:固定文件 + 多条历史文件都残留 lastLogin:true(旧代码判成 ambiguous,拒绝切换)
+ fs.writeFileSync(path.join(f.authDir, 'workbuddy-desktop.info'), JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.authDir, 's-history.info'), JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot', true)));
+ fs.writeFileSync(path.join(f.authDir, 'h-history.info'), JSON.stringify(auth('h', 'https://www.workbuddy.cn/auth/realms/copilot', true)));
+ const current = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.resolveCurrentAuth()))');
+ assert.equal(path.basename(current.file), 'workbuddy-desktop.info');
+ assert.equal(current.record.uid, 's');
+ assert.equal(current.ambiguous, false);
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('switch must succeed via the recorded target name despite multiple lastLogin markers', () => {
+ const f = fixture();
+ try {
+ fs.writeFileSync(path.join(f.authDir, 'workbuddy-desktop.info'), JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ fs.writeFileSync(path.join(f.authDir, 's-history.info'), JSON.stringify(auth('s', 'https://www.workbuddy.cn/auth/realms/copilot', true)));
+ fs.writeFileSync(path.join(f.authDir, 'h-history.info'), JSON.stringify(auth('h', 'https://www.workbuddy.cn/auth/realms/copilot', true)));
+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');
+ // meta.json 已记录 h 的目标文件名(h-history.info),切换不再被当前歧义一票否决
+ const switched = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.switchTo(process.env.WBSWITCH_DATA_DIR,"h")))');
+ assert.equal(switched.authFile.endsWith('h-history.info'), true);
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.authDir, 'h-history.info'), 'utf8')).account.uid, 'h');
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
+
+test('AI profile does not claim a domestic Tencent/CodeBuddy auth file', () => {
+ const f = fixture();
+ try {
+ fs.writeFileSync(path.join(f.authDir, 'opaque.info'), JSON.stringify(auth('cn', 'https://www.codebuddy.cn/auth/realms/copilot')));
+ const records = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.listAuthRecords()))', 'workbuddy-ai');
+ assert.deepEqual(records, []);
+ } finally {
+ fs.rmSync(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/test/checkin-result.test.js b/test/checkin-result.test.js
index 8936100..e61b434 100644
--- a/test/checkin-result.test.js
+++ b/test/checkin-result.test.js
@@ -2,7 +2,12 @@
const assert = require('node:assert/strict');
const test = require('node:test');
-const { classifyCheckinResult } = require('../scripts/checkin-result.js');
+const { classifyCheckinResult, tokenIssuerOrigin, checkinEndpointsForToken } = require('../scripts/checkin-result.js');
+
+function jwtWithIssuer(issuer) {
+ const payload = Buffer.from(JSON.stringify({ iss: issuer }), 'utf8').toString('base64url');
+ return `header.${payload}.signature`;
+}
test('check-in requires an explicit successful response code', () => {
assert.equal(classifyCheckinResult({ httpOk: true, code: undefined, message: 'OK' }).ok, false);
@@ -12,6 +17,16 @@ test('check-in requires an explicit successful response code', () => {
test('code 10001 is cached only when it explicitly means already checked in', () => {
assert.equal(classifyCheckinResult({ httpOk: true, code: 10001, message: '今日已签到' }).ok, true);
+ assert.equal(classifyCheckinResult({ httpOk: false, code: 10001, message: '今天已签到,请明天再来' }).ok, true);
assert.equal(classifyCheckinResult({ httpOk: true, code: 10001, message: '活动未开启' }).ok, false);
assert.equal(classifyCheckinResult({ httpOk: true, code: 10001, message: '请求成功' }).ok, false);
});
+
+test('recognized token issuer selects its matching host', () => {
+ const token = jwtWithIssuer('https://www.codebuddy.cn/auth/realms/copilot');
+ assert.equal(tokenIssuerOrigin(token), 'https://www.codebuddy.cn');
+ assert.deepEqual(checkinEndpointsForToken(token, { apiHost: 'https://www.workbuddy.ai', region: 'intl' }), [
+ 'https://www.codebuddy.cn/billing/meter/daily-checkin',
+ 'https://www.codebuddy.cn/v2/billing/meter/daily-checkin',
+ ]);
+});
diff --git a/test/checkin-schedule.test.js b/test/checkin-schedule.test.js
index 3f1d778..31668f0 100644
--- a/test/checkin-schedule.test.js
+++ b/test/checkin-schedule.test.js
@@ -6,6 +6,7 @@ const path = require('node:path');
const test = require('node:test');
const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+const refresh = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'token-refresh.js'), 'utf8');
test('daemon checks in shortly after startup and hourly thereafter', () => {
assert.match(daemon, /const CHECKIN_STARTUP_DELAY_MS = 30 \* 1000;/);
@@ -19,3 +20,11 @@ test('check-in timers do not keep the daemon alive', () => {
assert.match(daemon, /startupCheckinTimer\.unref && startupCheckinTimer\.unref\(\);/);
assert.match(daemon, /periodicCheckinTimer\.unref && periodicCheckinTimer\.unref\(\);/);
});
+
+test('check-in path refreshes backup tokens lazily and runs daily keepalive', () => {
+ assert.match(daemon, /refreshAccountBackupToken\(uid\)/);
+ assert.match(daemon, /refreshAccountBackupToken\(uid, \{ dailyKeepalive: true \}\)/);
+ assert.match(refresh, /auth\/token\/refresh/);
+ assert.match(daemon, /lastRefreshTime/);
+ assert.match(daemon, /1\.1\.34/);
+});
diff --git a/test/credits-401.test.js b/test/credits-401.test.js
new file mode 100644
index 0000000..dd35f74
--- /dev/null
+++ b/test/credits-401.test.js
@@ -0,0 +1,31 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const test = require('node:test');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+
+test('credit 401 responses are classified as login-expired instead of a generic HTTP/parse error', () => {
+ // 个人版积分接口:401 必须先于 JSON.parse 归类(网关常直接返回 HTML 登录页)
+ assert.match(daemon, /if \(r\.status === 401\) \{[\s\S]*?登录身份过期/);
+ // 企业版接口同样归类
+ assert.match(daemon, /企业积分接口 HTTP/);
+ // /api/credits 对过期凭证返回结构化 401,前端可据此渲染可诊断文案
+ assert.match(daemon, /json\(res, 401, \{ ok: false, expired: true, error: '登录身份过期' \}\)/);
+ // 两个 robust 重试函数遇到 expired 立即终止,不空耗 3 次重试
+ const expiredGuard = (daemon.match(/if \(e && e\.expired\) throw e;/g) || []).length;
+ assert.ok(expiredGuard >= 2, `expected >=2 expired guards, got ${expiredGuard}`);
+});
+
+test('inject renders a visible login-expired label instead of hiding the credit cell', () => {
+ // 过期账号积分格展示「登录身份过期」文案,而不是整格隐藏/空白
+ assert.match(inject, /登录身份过期<\/span>/);
+ // fetchCreditsForAccounts 识别 daemon 的 {expired:true} 并标记 creditExpired
+ assert.match(inject, /e\.payload\.expired/);
+ assert.match(inject, /account\.creditExpired/);
+ // 不再对过期积分格整格隐藏(display:none 会让可诊断文案不可见)
+ assert.doesNotMatch(inject, /wbs-credit-hidden' \+ \(isIdentityExpired/);
+});
\ No newline at end of file
diff --git a/test/enterprise-target.test.js b/test/enterprise-target.test.js
index 5688f3d..50d2697 100644
--- a/test/enterprise-target.test.js
+++ b/test/enterprise-target.test.js
@@ -127,32 +127,66 @@ test('custom target persists outside the install and overlays only its base prof
}
});
-test('enterprise profile overrides remain Windows-only and macOS keeps the official profile', () => {
+test('enterprise profile overrides support a macOS Electron binary', () => {
const dataDir = tempDir();
try {
writeWorkBuddyTarget({
dataDir,
profileId: 'workbuddy-cn',
- platform: 'win32',
+ platform: 'darwin',
target: {
schemaVersion: 1,
profileId: 'workbuddy-cn',
- binary: 'C:\\Company\\workbuddy-ent.exe',
- processNames: ['workbuddy-ent.exe'],
- dataRoot: 'C:\\Users\\tester\\.workbuddy-ent',
- authFile: 'C:\\Auth\\workbuddy-desktop-workbuddy-ent.info',
- sessionDb: 'C:\\Users\\tester\\.workbuddy-ent\\workbuddy.db',
- modelsFile: 'C:\\Users\\tester\\.workbuddy-ent\\models.json',
- apiHost: 'https://api.ent.example.com',
- targetHints: ['workbuddy-ent', 'api.ent.example.com'],
- cdp: { mode: 'environment', port: 9226 },
+ binary: '/Applications/WorkBuddy企业定制版.app/Contents/MacOS/Electron',
+ processNames: ['Electron'],
+ cdp: { mode: 'argument', port: 9222 },
},
});
- assert.deepEqual(
- getProfile('workbuddy-cn', { dataDir, env: {}, platform: 'darwin' }),
- PROFILES['workbuddy-cn']
- );
+ const profile = getProfile('workbuddy-cn', { dataDir, env: {}, platform: 'darwin' });
+ assert.equal(profile.appPath, '/Applications/WorkBuddy企业定制版.app/Contents/MacOS/Electron');
+ assert.deepEqual(profile.binaryNames, ['Electron']);
+ assert.equal(profile.cdp.mode, 'argument');
+ assert.equal(profile.customTarget, true);
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('macOS target configuration accepts non-exe process names', () => {
+ const target = buildTargetFromBinary({
+ binary: '/Applications/WorkBuddy企业定制版.app/Contents/MacOS/Electron',
+ profileId: 'workbuddy-cn',
+ platform: 'darwin',
+ // macOS 上 os.homedir() 返回 posix 路径;Windows 上跑本用例须注入
+ // posix home,否则推导出的 authFile 无法通过 darwin 绝对路径校验。
+ home: '/Users/workdaddy',
+ });
+ assert.equal(target.clientType, 'enterprise');
+ assert.deepEqual(target.processNames, ['Electron']);
+ assert.deepEqual(target.cdp, { mode: 'argument', port: 9222 });
+});
+
+test('target resolver accepts launcher-style equals arguments', () => {
+ const dataDir = tempDir();
+ const script = path.join(__dirname, '..', 'scripts', 'workbuddy-target.js');
+ try {
+ writeWorkBuddyTarget({
+ dataDir,
+ profileId: 'workbuddy-cn',
+ platform: 'darwin',
+ target: {
+ profileId: 'workbuddy-cn',
+ binary: '/Applications/WorkBuddy企业定制版.app/Contents/MacOS/Electron',
+ processNames: ['Electron'],
+ cdp: { mode: 'argument', port: 9222 },
+ },
+ });
+ const result = spawnSync(process.execPath, [
+ script, '--resolve', '--profile=workbuddy-cn', `--data-dir=${dataDir}`,
+ ], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout.trim(), '/Applications/WorkBuddy企业定制版.app/Contents/MacOS/Electron');
} finally {
fs.rmSync(dataDir, { recursive: true, force: true });
}
diff --git a/test/i18n-coverage.test.js b/test/i18n-coverage.test.js
new file mode 100644
index 0000000..e599d83
--- /dev/null
+++ b/test/i18n-coverage.test.js
@@ -0,0 +1,189 @@
+'use strict';
+
+// i18n 覆盖度回归测试:
+// 1) 扫描 inject.js / daemon.js 中所有中文字面量,未进字典的必须在白名单内(否则新增中文 UI 文案会直接挂测试)
+// 2) 运行时翻译:从源码提取字典+翻译函数,断言典型拼接句翻译后无中文残留(无中英混合)
+// 3) 机制:属性白名单、变体覆盖、模板占位
+
+const assert = require('node:assert/strict');
+const test = require('node:test');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+
+const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+const lib = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib.js'), 'utf8');
+
+// ---- 工具:提取字典 + 翻译函数并构造可执行翻译器 ----
+function buildTranslator() {
+ const dictMatch = inject.match(/var WBS_I18N_EN = \{([\s\S]*?)\n \};/);
+ assert.ok(dictMatch, 'WBS_I18N_EN dict must exist');
+ const grab = (re) => {
+ const m = re.exec(inject);
+ assert.ok(m, `pattern missing: ${re}`);
+ return m[0];
+ };
+ const matchersVar = inject.match(/var wbsI18nMatchers = null;/);
+ const pieces = [
+ matchersVar && matchersVar[0],
+ grab(/function escapeRegExp\(s\) \{[\s\S]*?\n \}/),
+ grab(/function wbsI18nBuildMatchers\(\) \{[\s\S]*?\n \}/),
+ grab(/function wbsTranslateString\(value, language\) \{[\s\S]*?\n \}/),
+ ].filter(Boolean);
+ const sandbox = {};
+ vm.createContext(sandbox);
+ vm.runInContext(`var WBS_I18N_EN = {${dictMatch[1]}}; ${pieces.join('\n')}`, sandbox);
+ return sandbox.wbsTranslateString;
+}
+
+// ---- 白名单:这些是 console 日志 / 断句残留(运行时被整句模板覆盖)/ 内部模块,不属 UI 文案 ----
+const LOG_LIKE = /^(WorkBuddy 兼容层未加载|\[WBS\]|注入组件已销毁|收到 SIGTERM|当前 Node 运行时没有 WebSocket|daemon 使用临时目录锁|picker-internal\.js 注入锚点不存在)|^\[[a-z][^\]]*\]/;
+const FRAGMENT_LIKE = /^[」「,、。;:]|^已发送「|^已登录「|的自动继续|项)|」的备份|」的本地备份|」,请刷新|已发送「|已登录「|^\s*(个|条)$|^快捷短语吗|^这条$/;
+
+// 还原运行时真实文本:字面量常内嵌 HTML 标签/属性,运行时按文本节点拆分后翻译,
+// 这里仅剥离标签(含标签内属性)得到接近真实的纯文本再检查。不 trim 首尾空格、
+// 不剥引号内容——前导空格是整句 key 的一部分(如 ' 个会话'、' 的 WorkBuddy …'),
+// 引号内文本(如 回复"已完成")也是可翻译内容的一部分。
+function uiText(lit) {
+ return lit
+ .replace(/<[^>]*>/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+function stripComments(src) {
+ return src
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
+ .replace(/(^|[^:"'\\])\/\/[^\n]*/g, '$1');
+}
+
+function chineseLiterals(src) {
+ const out = new Set();
+ // 拆成两个独立正则:JS 单引号串与双引号串分别匹配。
+ // 原「(['"])((?:[^'"\\\n]|\\.)*)\1」在单引号串内嵌 HTML 双引号(如
+ // '<div class="x">…')时整段失配,导致弹窗/二级页文案漏出扫描网。
+ const single = /'((?:[^'\\\n]|\\.)*)'/g;
+ const dbl = /"((?:[^"\\\n]|\\.)*)"/g;
+ let m;
+ const collect = (re) => {
+ while ((m = re.exec(src))) {
+ const s = m[1];
+ if (s && /[\u4e00-\u9fff]/.test(s)) {
+ // 保留前导空格:部分整句 key 以空格开头(如 ' 的 WorkBuddy 桌面端增强工具…'),
+ // trim 会让运行时本可整句匹配的文本提前落入短词替换(误报混合)。
+ const clean = s.replace(/\\(['"])/g, '$1').replace(/\s+$/, '');
+ if (clean.length >= 2) out.add(clean);
+ }
+ }
+ re.lastIndex = 0;
+ };
+ collect(single);
+ collect(dbl);
+ const tpl = /`([^`${]*)`/g;
+ while ((m = tpl.exec(src))) {
+ const s = (m[1] || '').trim();
+ if (s && /[\u4e00-\u9fff]/.test(s) && s.length >= 2) out.add(s);
+ }
+ return out;
+}
+
+function extractKeys() {
+ const dictMatch = inject.match(/var WBS_I18N_EN = \{([\s\S]*?)\n \};/);
+ const keys = [];
+ for (const m of dictMatch[1].matchAll(/'([^']+)':\s*'[^']*'/g)) {
+ if (/[\u4e00-\u9fff]/.test(m[1])) keys.push(m[1]);
+ }
+ return keys.sort((a, b) => b.length - a.length);
+}
+
+test('every Chinese UI literal in inject.js translates at runtime with zero Chinese residue', () => {
+ const t = buildTranslator();
+ const missed = [];
+ for (const lit of chineseLiterals(stripComments(inject))) {
+ if (LOG_LIKE.test(lit)) continue;
+ if (FRAGMENT_LIKE.test(lit)) continue;
+ const text = uiText(lit);
+ if (text.length < 2) continue;
+ const out = t(text, 'en');
+ if (/[\u4e00-\u9fff]/.test(out)) missed.push(`「${lit}」-> ${out}`);
+ }
+ assert.deepEqual(missed, [], `运行时仍产中文(中英混合):\n${missed.map((m, i) => ` ${i + 1}. ${m}`).join('\n')}`);
+});
+
+test('every user-facing Chinese literal in daemon.js (non-log) is covered', () => {
+ const keys = extractKeys();
+ const missed = [];
+ for (const lit of chineseLiterals(stripComments(daemon))) {
+ if (LOG_LIKE.test(lit)) continue;
+ if (FRAGMENT_LIKE.test(lit)) continue;
+ if (/^(has|must|should|the|a |an |ports|cwd)/i.test(lit)) continue; // 英文为主的不检查
+ const covered = keys.some((k) => k.length >= 2 && lit.indexOf(k) >= 0);
+ if (!covered) missed.push(lit);
+ }
+ assert.deepEqual(missed, [], `daemon 未覆盖文案:\n${missed.map((m, i) => ` ${i + 1}. ${m}`).join('\n')}`);
+});
+
+test('lib.js account-flow errors (surface as toasts) translate without Chinese residue', () => {
+ const t = buildTranslator();
+ const missed = [];
+ for (const lit of chineseLiterals(stripComments(lib))) {
+ if (LOG_LIKE.test(lit)) continue;
+ if (FRAGMENT_LIKE.test(lit)) continue;
+ const out = t(lit, 'en');
+ if (/[\u4e00-\u9fff]/.test(out)) missed.push(`「${lit}」-> ${out}`);
+ }
+ assert.deepEqual(missed, [], `lib.js 运行时仍产中文:\n${missed.map((m, i) => ` ${i + 1}. ${m}`).join('\n')}`);
+});
+
+test('runtime translation: typical concatenated sentences yield pure English (no zh/en mix)', () => {
+ const t = buildTranslator();
+ const cases = [
+ '已切换为「h」,开始领取积分…',
+ '定位到第 3 条用户消息',
+ '已发送「hello」',
+ '「s」的备份',
+ '打开面板失败: 123',
+ '打开面板失败:456',
+ '已关闭:由环境变量控制',
+ '输入框非空,已放弃会话 abc123 的自动继续',
+ '剩余时间计算中',
+ '基础用量 500',
+ '账号汇总 · 总积分 100',
+ ];
+ for (const input of cases) {
+ const out = t(input, 'en');
+ assert.ok(!/[\u4e00-\u9fff]/.test(out), `「${input}」翻译后仍有中文: ${out}`);
+ assert.notEqual(out.trim(), '', `「${input}」被翻译成空串`);
+ }
+ // 用户数据(昵称/文本)不属于界面文案:保留原文是正确行为,只要求结构被翻译
+ const withVar = t('已登录「老板」', 'en');
+ assert.ok(withVar.indexOf('Logged in as') >= 0 && withVar.indexOf('老板') >= 0, withVar);
+});
+
+test('short keys cannot shred longer covered sentences', () => {
+ const t = buildTranslator();
+ // '切换' 是独立词条;整句模板存在时必须以整句为准,不允许输出 '已Switch为…'
+ const out = t('已切换为「h」,开始领取积分…', 'en');
+ assert.ok(out.indexOf('Switched to') >= 0, `整句模板未生效: ${out}`);
+ assert.ok(out.indexOf('Switch') < 0 || out.indexOf('Switched to') >= 0 && out.indexOf('已') < 0, out);
+ assert.ok(!/[\u4e00-\u9fff]/.test(out), out);
+});
+
+test('attribute whitelist includes alt and data-tip; observer watches them', () => {
+ assert.match(inject, /'title', 'aria-label', 'placeholder', 'alt', 'data-tip'/);
+ assert.match(inject, /attributeFilter: \['title', 'aria-label', 'placeholder', 'alt', 'data-tip'\]/);
+});
+
+test('variant keys: error prefixes with and without trailing space both translate', () => {
+ const t = buildTranslator();
+ // 半角冒号
+ assert.equal(t('打开面板失败: x', 'en'), 'Could not open panel: x');
+ // 全角冒号(归一化后同样命中)
+ assert.equal(t('打开面板失败:x', 'en'), 'Could not open panel: x');
+ assert.equal(t('删除失败: 原因', 'en'), 'Delete failed: 原因');
+});
+
+test('zh mode leaves text untouched', () => {
+ const t = buildTranslator();
+ assert.equal(t('已切换为「h」,开始领取积分…', 'zh'), '已切换为「h」,开始领取积分…');
+});
\ No newline at end of file
diff --git a/test/i18n.test.js b/test/i18n.test.js
new file mode 100644
index 0000000..4a96f4f
--- /dev/null
+++ b/test/i18n.test.js
@@ -0,0 +1,37 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+
+test('injected panel exposes persisted bilingual language selection', () => {
+ assert.match(source, /workdaddy\.ui\.language/);
+ assert.match(source, /navigator\.language/);
+ assert.match(source, /value\.indexOf\('zh'\) === 0 \? 'zh' : 'en'/);
+ assert.match(source, /data-tab="about"/);
+ // 语言切换为 Segmented 控件,且必须位于 About pane(data-pane="about" 的构建函数内),无独立设置页残留
+ assert.match(source, /function buildAboutPane\(\)[\s\S]*?wbs-lang-seg/);
+ assert.doesNotMatch(source, /data-tab="settings"/);
+ assert.doesNotMatch(source, /function buildSettingsPane\(\)/);
+ assert.match(source, /wbs-lang-seg/);
+ assert.match(source, /data-wbs-lang="zh"/);
+ assert.match(source, /data-wbs-lang="en"/);
+ assert.match(source, /localStorage\.setItem\(WBS_LANGUAGE_KEY/);
+ assert.match(source, /setAttribute\('lang', WBS_LANGUAGE === 'zh' \? 'zh-CN' : 'en'\)/);
+});
+
+test('all dynamic panel text and toast nodes pass through the translator', () => {
+ assert.match(source, /function applyI18n\(scope\)/);
+ assert.match(source, /applyI18n\(t\);/);
+ assert.match(source, /i18nObserver\.observe\(root/);
+ assert.match(source, /'账号': 'Accounts'/);
+ assert.match(source, /'设置语言': 'Language'/);
+});
+
+test('README language switch links are reciprocal', () => {
+ const readme = fs.readFileSync(path.join(__dirname, '..', 'README.md'), 'utf8');
+ const english = fs.readFileSync(path.join(__dirname, '..', 'README_en.md'), 'utf8');
+ assert.match(readme, /\[English\]\(README_en\.md\)/);
+ assert.match(english, /\[简体中文\]\(README\.md\)/);
+});
diff --git a/test/macos-dmg-layout.test.js b/test/macos-dmg-layout.test.js
index f3d9a7f..9d90910 100644
--- a/test/macos-dmg-layout.test.js
+++ b/test/macos-dmg-layout.test.js
@@ -50,3 +50,11 @@ test('macOS DMG uses a fixed-size SVG master for its arrow artwork', () => {
assert.doesNotMatch(svg, /<(?:line|polyline)\b/);
assert.doesNotMatch(svg, /<text\b/);
});
+
+test('macOS launcher keeps official WorkBuddy targets out of enterprise mode', () => {
+ assert.match(buildSource, /source = source\.replace\('export WBSWITCH_WORKBUDDY_BIN="\$APP_BIN"'/);
+ assert.match(buildSource, /TARGET_ENV_XML/);
+ assert.match(buildSource, /TARGET_BIN:-\}/);
+ assert.match(buildSource, /<key>WBSWITCH_PROFILE<\/key>/);
+ assert.match(buildSource, /PLIST_STALE/);
+});
diff --git a/test/theme-blur.test.js b/test/theme-blur.test.js
index 96ae02c..b408c28 100644
--- a/test/theme-blur.test.js
+++ b/test/theme-blur.test.js
@@ -33,8 +33,10 @@ test('theme pane keeps avatar controls visible and gates wallpaper controls to W
assert.match(inject, /syncWallpaperCardVisibility\(cur\)/);
});
-test('theme pane uses the requested WorkDaddy and blur labels', () => {
- assert.match(inject, /data-theme="nebula">' \+ WBS_BRAND \+ ' 主题<\/button>/);
+test('theme pane uses the requested blur labels and nebula tab', () => {
+ // 主题第 4 个 tab 文案为「毛玻璃」,且词典含英文 Frosted glass
+ assert.match(inject, /data-theme="nebula">毛玻璃<\/button>/);
+ assert.match(inject, /'毛玻璃': 'Frosted glass'/);
assert.doesNotMatch(inject, /背景毛玻璃<span class="wbs-blur-hint">0% 不调节背景图<\/span>/);
assert.match(inject, /<label class="wbs-blur-label" for="wbs-bg-blur-range">背景毛玻璃<\/label>/);
});
diff --git a/test/token-refresh.test.js b/test/token-refresh.test.js
new file mode 100644
index 0000000..4644253
--- /dev/null
+++ b/test/token-refresh.test.js
@@ -0,0 +1,86 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const test = require('node:test');
+const { refreshAuthToken, shouldRefreshAccessToken } = require('../scripts/token-refresh.js');
+
+test('refreshAuthToken exchanges the refresh token and preserves rotated credentials', async () => {
+ const calls = [];
+ const now = 1_700_000_000_000;
+ const result = await refreshAuthToken({
+ accessToken: 'old-access',
+ refreshToken: 'old-refresh',
+ expiresAt: now - 1000,
+ refreshExpiresAt: now + 30 * 86400000,
+ scope: 'openid offline_access',
+ }, {
+ apiHost: 'https://api.example.test',
+ now,
+ fetchImpl: async (url, init) => {
+ calls.push({ url, init });
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ code: 0,
+ data: {
+ accessToken: 'new-access',
+ refreshToken: 'new-refresh',
+ expiresIn: 3600,
+ refreshExpiresIn: 86400,
+ },
+ }),
+ };
+ },
+ });
+
+ assert.equal(result.ok, true);
+ assert.equal(result.auth.accessToken, 'new-access');
+ assert.equal(result.auth.refreshToken, 'new-refresh');
+ assert.equal(result.auth.expiresAt, now + 3600 * 1000);
+ assert.equal(result.auth.refreshExpiresAt, now + 86400 * 1000);
+ assert.equal(result.auth.lastRefreshTime, now);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].url, 'https://api.example.test/v2/plugin/auth/token/refresh');
+ assert.equal(calls[0].init.method, 'POST');
+ assert.equal(calls[0].init.headers.authorization, 'Bearer old-access');
+ assert.equal(calls[0].init.headers['X-Refresh-Token'], 'old-refresh');
+});
+
+test('refreshAuthToken leaves the old auth untouched when the server rejects the refresh', async () => {
+ const auth = { accessToken: 'old-access', refreshToken: 'old-refresh', expiresAt: 123 };
+ const result = await refreshAuthToken(auth, {
+ apiHost: 'https://api.example.test',
+ fetchImpl: async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ code: 12153, message: 'invalid_grant' }),
+ }),
+ });
+ assert.equal(result.ok, false);
+ assert.deepEqual(result.auth, auth);
+ assert.match(result.error, /invalid_grant/);
+});
+
+test('shouldRefreshAccessToken treats expired and near-expiry access tokens as stale', () => {
+ const now = 1_700_000_000_000;
+ assert.equal(shouldRefreshAccessToken({ expiresAt: now - 1 }, now), true);
+ assert.equal(shouldRefreshAccessToken({ expiresAt: now + 30 * 60 * 1000 }, now), true);
+ assert.equal(shouldRefreshAccessToken({ expiresAt: now + 2 * 86400000 }, now), false);
+ assert.equal(shouldRefreshAccessToken({}), true);
+});
+
+test('refreshAuthToken falls back to snake_case fields when camelCase fields are empty', async () => {
+ const result = await refreshAuthToken({ refreshToken: 'old-refresh' }, {
+ apiHost: 'https://api.example.test',
+ now: 1_700_000_000_000,
+ fetchImpl: async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ code: 0, data: { accessToken: '', access_token: 'new-access', refresh_token: 'new-refresh', expires_in: 60 } }),
+ }),
+ });
+ assert.equal(result.ok, true);
+ assert.equal(result.auth.accessToken, 'new-access');
+ assert.equal(result.auth.refreshToken, 'new-refresh');
+});
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index b9ea1b3..72a8923 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -607,6 +607,9 @@ test('Windows Setup waits for WorkBuddy and stops only a native-verified profile
assert.match(installer, /当前安装程序是以管理员权限运行的/);
assert.match(installer, /不要选择“以管理员身份运行”/);
assert.match(installer, /普通安装器不会跨权限强行结束/);
+ assert.match(installer, /按 Ctrl\+Shift\+Esc 打开任务管理器/);
+ assert.match(installer, /旧版 WorkDaddy 的状态文件与实际程序不一致/);
+ assert.match(installer, /不要手动删除 WorkDaddy 数据目录/);
assert.doesNotMatch(installer, /安装器本身可以使用管理员权限运行/);
assert.doesNotMatch(installer, /旧版 WorkDaddy 正以管理员权限运行/);
assert.doesNotMatch(installer, /prepare-win-install|windows-process-boundary|PowerShell/i);
@@ -626,6 +629,32 @@ test('macOS package launcher keeps WorkBuddy CN and AI CDP ports profile-specifi
assert.match(build, /workbuddy-ai\)/);
});
+test('macOS launchers discover renamed WorkBuddy app bundles and wait for slow CDP startup', () => {
+ const relaunch = read('relaunch-with-cdp.sh');
+ const build = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');
+ for (const source of [relaunch, build]) {
+ assert.match(source, /WorkBuddy\*\.app/);
+ assert.match(source, /Contents\/MacOS\/Electron/);
+ assert.match(source, /WorkBuddy AI/);
+ assert.match(source, /matches=\(\)/);
+ assert.match(source, /检测到多个/);
+ assert.match(source, /\[ -n "\$APP_BIN" \].*pkill/s);
+ assert.match(source, /choose application with prompt/);
+ assert.match(source, /所选应用不是可用的 WorkBuddy 客户端/);
+ assert.match(source, /等待 60 秒/);
+ }
+ assert.match(relaunch, /workbuddy-target\.json/);
+ assert.match(relaunch, /APP_DISCOVERY_ERROR.*APP_NAME=.*APP_BIN=/s);
+ assert.match(build, /APP_DISCOVERY_ERROR.*APP_NAME=.*APP_BIN=/s);
+});
+
+test('macOS launchers resolve an explicit target configuration before auto-discovery', () => {
+ const relaunch = read('relaunch-with-cdp.sh');
+ const build = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');
+ assert.match(relaunch, /workbuddy-target\.js" --resolve --profile=/);
+ assert.match(build, /workbuddy-target\.js" --resolve --profile=/);
+});
+
test('macOS package launcher returns focus to the target WorkBuddy and separates AI identity', () => {
const build = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');
assert.match(build, /activate_target_app\(\)/);
@@ -698,7 +727,7 @@ test('account cards keep the compact three-row layout', () => {
assert.doesNotMatch(script, /wbs-growth-activate/);
assert.doesNotMatch(script, /api\('\/api\/growth\/activate'/);
assert.match(script, /expired \? '' : '<button class="wbs-icon-btn wbs-acc-switch"/);
- assert.match(script, /switchBtn\.style\.display = hidden \? 'none' : ''/);
+ assert.match(script, /switchBtn\.style\.display = hidden \|\| account\.creditExpired \? 'none' : ''/);
assert.match(script, /height:5px;min-height:5px/);
assert.match(script, /\.wbs-credit-segment:first-child\{border-radius:3px 0 0 3px\}/);
assert.match(script, /\.wbs-credit-segment:last-child\{border-radius:0 3px 3px 0\}/);
diff --git a/test/verify-win-exit.test.js b/test/verify-win-exit.test.js
index c32ab09..1804dd0 100644
--- a/test/verify-win-exit.test.js
+++ b/test/verify-win-exit.test.js
@@ -61,7 +61,7 @@ test('Windows verifier returns success for a complete source package', { skip: p
'windows-process-boundary.js', 'windows-process-boundary.ps1', 'windows-relaunch-standard.ps1',
'workbuddy-compat.js', 'inject.js',
'theme-patches.js', 'launcher.cmd', 'launcher-hidden.vbs', 'install-win.cmd',
- 'install-win.ps1', 'prepare-win-install.ps1', 'uninstall-win.ps1', 'apply-update.ps1',
+ 'install-win.ps1', 'prepare-win-install.ps1', 'uninstall-win.cmd', 'uninstall-win.ps1', 'apply-update.ps1',
path.join('win', 'setup.sed'), 'verify-win.cmd',
];
try {
diff --git a/test/windows-launcher-boundary-repair.test.js b/test/windows-launcher-boundary-repair.test.js
index b2d73a9..0508967 100644
--- a/test/windows-launcher-boundary-repair.test.js
+++ b/test/windows-launcher-boundary-repair.test.js
@@ -361,7 +361,7 @@ test('Windows installer uses the bundled Simplified Chinese wizard and profile b
assert.match(installerSource, /\[Languages\][\s\S]*ChineseSimplified\.isl/);
assert.match(installerSource, /AppPublisher=\{#ProductName\} 团队/);
assert.match(installerSource, /Description: "\{#StartDescription\}"/);
- assert.match(fs.readFileSync(path.join(root, 'scripts', 'build-win-installer.ps1'), 'utf8'), /创建 WorkDaddy AI 桌面快捷方式/);
+ assert.match(fs.readFileSync(path.join(root, 'scripts', 'build-win-installer.ps1'), 'utf8'), /立即打开 WorkDaddy AI/);
assert.match(chineseLanguageSource, /LanguageName=简体中文/);
});
diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.js
index c98a653..0bbfdd7 100644
--- a/test/windows-native-flow.test.js
+++ b/test/windows-native-flow.test.js
@@ -180,6 +180,22 @@ test('native lifecycle cleanup accepts a PID that exits during exact inspection'
assert.match(source.slice(exitedCheck, mismatch), /waitResult == waitObject0[\s\S]*return false, 0, nil/);
});
+test('elevated lifecycle cleanup inspects exact state before refusing active termination', () => {
+ const source = read('scripts/windows-native/main.go');
+ const stopStart = source.indexOf('func stopLifecycle(');
+ const stopEnd = source.indexOf('\nfunc appendLog(', stopStart);
+ assert.ok(stopStart >= 0 && stopEnd > stopStart);
+ const stop = source.slice(stopStart, stopEnd);
+ assert.match(stop, /inspectExactProcess\(/);
+ assert.match(stop, /elevated[\s\S]*active[\s\S]*exitAccessDenied/);
+ assert.match(stop, /os\.Remove\(candidate\.path\)/);
+ const helperStart = source.indexOf('if hasArgument("--stop-lifecycle")');
+ const helperEnd = source.indexOf('\n\tif hasArgument("--self-test")', helperStart);
+ assert.ok(helperStart >= 0 && helperEnd > helperStart);
+ assert.match(source.slice(helperStart, helperEnd), /stopLifecycle\(profile, targetApp, elevated\)/);
+ assert.doesNotMatch(source.slice(helperStart, helperEnd), /if elevated \{[\s\S]*return true, exitAccessDenied/);
+});
+
test('native lifecycle can recover a missing watchdog PID only from a unique daemon parent', () => {
const source = read('scripts/windows-native/main.go');
assert.match(source, /ParentPID\s+uint32/);
@@ -188,7 +204,7 @@ test('native lifecycle can recover a missing watchdog PID only from a unique dae
assert.match(source, /daemonPID\s*int/);
assert.match(source, /len\(candidates\) != 1/);
assert.match(source, /candidate\.Path/);
- const stopStart = source.indexOf('func stopLifecycle(profile, appDir string) int');
+ const stopStart = source.indexOf('func stopLifecycle(');
const stopEnd = source.indexOf('\nfunc appendLog(', stopStart);
assert.ok(stopStart >= 0 && stopEnd > stopStart);
const stop = source.slice(stopStart, stopEnd);
@@ -199,7 +215,7 @@ test('native lifecycle can recover a missing watchdog PID only from a unique dae
test('installer lifecycle cleanup releases only the exact installed native launcher', () => {
const source = read('scripts/windows-native/main.go');
- const stopStart = source.indexOf('func stopInstalledLauncher(appDir string) int');
+ const stopStart = source.indexOf('func stopInstalledLauncher(');
const stopEnd = source.indexOf('\nfunc uniqueRunningWorkBuddyPath(', stopStart);
assert.ok(stopStart >= 0 && stopEnd > stopStart);
const stop = source.slice(stopStart, stopEnd);
@@ -279,6 +295,16 @@ test('native startup precisely restarts a verified WorkBuddy without CDP', () =>
assert.doesNotMatch(nativeMain, /return 10/);
});
+test('native WorkBuddy restart preserves helper diagnostics for permission failures', () => {
+ const launcher = read('scripts/win-launcher.js');
+ const start = launcher.indexOf('function stopNativeWorkBuddy()');
+ const end = launcher.indexOf('\nfunction ', start + 1);
+ assert.ok(start >= 0 && end > start);
+ const stop = launcher.slice(start, end);
+ assert.match(stop, /result\.stderr/);
+ assert.match(stop, /无法精确重启当前 WorkBuddy[\s\S]*detail/);
+});
+
test('native CDP startup detects failed child launches instead of waiting for the full timeout', () => {
assert.equal(nativeLaunchFailed(null), false);
assert.equal(nativeLaunchFailed({ errorCode: null, exitCode: null }), false);
diff --git a/test/windows-privilege-boundary.test.js b/test/windows-privilege-boundary.test.js
index 63972e3..dcd3045 100644
--- a/test/windows-privilege-boundary.test.js
+++ b/test/windows-privilege-boundary.test.js
@@ -246,7 +246,12 @@ test('native lifecycle stop validates the bundled node path before termination',
assert.match(nativeSource, /--terminate-workbuddy/);
assert.match(nativeSource, /exitAccessDenied/);
assert.match(nativeSource, /exitIdentityMismatch/);
- assert.match(nativeSource, /if elevated \{[\s\S]*return true, exitAccessDenied/);
+ const lifecycleStart = nativeSource.indexOf('if hasArgument("--stop-lifecycle")');
+ const lifecycleEnd = nativeSource.indexOf('\n\tif hasArgument("--self-test")', lifecycleStart);
+ assert.ok(lifecycleStart >= 0 && lifecycleEnd > lifecycleStart);
+ const lifecycleBranch = nativeSource.slice(lifecycleStart, lifecycleEnd);
+ assert.match(lifecycleBranch, /stopLifecycle\(profile, targetApp, elevated\)/);
+ assert.doesNotMatch(lifecycleBranch, /if elevated \{[\s\S]*return true, exitAccessDenied/);
});
test('native termination maps TerminateProcess access denial to the permission exit code', () => {