Skip to content

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

- 适配 WorkBuddy 5.4.4; - 会话消息指示器; - 账号可多选部分导出; - 增加会话导入导出功能; - 增加快捷短语导入导出; - 当前会话结束允许休眠; - Windows 安装打开流程重构,增加稳定性,提高打开速度; - Windows 版本更新流程重构,增加稳定性;

[email protected]48d6d5252372
diff --git a/.github/workflows/build-win.yml b/.github/workflows/build-win.yml
index c7a4e2f..d688f6b 100644
--- a/.github/workflows/build-win.yml
+++ b/.github/workflows/build-win.yml
@@ -26,6 +26,12 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
+ - name: 安装固定 Go 工具链
+ uses: actions/setup-go@v5
+ with:
+ go-version: '1.27.0'
+ cache: false
+
- name: 校验 CRLF(cmd 必须 CRLF,否则 cmd.exe 解析括号块会失败)
shell: bash
run: |
diff --git a/.gitignore b/.gitignore
index 53cabd8..a3bf751 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,9 @@ WorkDaddy.app
*.log
daemon.log
+# 内部调试模块(元素检查/DevTools 实现,不公开入库;他人环境点按钮报错属预期)
+scripts/picker-internal.js
+
# 工作区元数据(WorkBuddy 项目数据,不入库)
.workbuddy/
.workbuddy-ai/
diff --git a/AGENTS.md b/AGENTS.md
index 35b9d2b..bdd5238 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -116,31 +116,45 @@ The queue item's 暂存提示词 tag is rendered by `syncQueueTags` (in `scripts
Use this exact flow for a Windows release. The two client packages are built from the same source tree, but each is staged with its own profile, installation directory, daemon port, desktop shortcut, and WorkBuddy executable name.
-1. Start from the requested source commit/branch and confirm the working tree. Do not silently change the release version in `scripts/daemon.js` when producing a fixed-version package; pass the requested version explicitly to the release script.
+1. Start from the requested source commit/branch and confirm the working tree. Do not silently change the release version in `scripts/daemon.js` when producing a fixed-version package; pass the requested version explicitly to the release script. Before building, remove only the existing `release/windows/*-Setup-*.exe` files if the request is to replace all installer artifacts; keep unrelated files outside that directory untouched.
-2. From the repository root, run the Windows release builder with Git Bash, Inno Setup 6, and Python available:
+2. From the repository root, run the Windows release builder with Git Bash, Inno Setup 6, and Python available. Prefer explicit tool paths on the build host so the result is reproducible and does not depend on `PATH`:
```powershell
- powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-win-release.ps1 -Version 1.1.2
+ powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-win-release.ps1 `
+ -Version <VERSION> `
+ -GoPath "$env:USERPROFILE\.workdaddy-toolchains\go1.27.0\bin\go.exe" `
+ -IsccPath "$env:USERPROFILE\.workdaddy-toolchains\Inno Setup 6\ISCC.exe"
+ ```
+
+ On a host where the compiler emits a large amount of output, run the same command through a child PowerShell with stdout/stderr redirected to temporary log files and wait for its exit code. Do not treat a truncated terminal response or an intermediate file as a completed build:
+
+ ```powershell
+ $argString = '-NoProfile -ExecutionPolicy Bypass -File "scripts/build-win-release.ps1" -Version <VERSION> -GoPath "<GO_EXE>" -IsccPath "<ISCC_EXE>"'
+ $p = Start-Process powershell.exe -ArgumentList $argString `
+ -RedirectStandardOutput release/build.stdout.log `
+ -RedirectStandardError release/build.stderr.log -Wait -PassThru
+ if ($p.ExitCode -ne 0) { throw "Windows build failed: $($p.ExitCode)" }
```
`build-win-release.ps1` must build both `workbuddy-cn` and `workbuddy-ai`. `build-win-zip.sh` creates only an internal staging ZIP; `build-win-installer.ps1` rewrites the staged daemon version and build id to the requested release version before compiling Setup.exe. Do not hand-copy scripts into an old installer directory.
-3. Deliver only these files:
+3. Deliver only these files (replace `<VERSION>` with the requested release version):
```text
- release/windows/WorkDaddy-Setup-1.1.2.exe
- release/windows/WorkDaddy-AI-Setup-1.1.2.exe
+ release/windows/WorkDaddy-Setup-<VERSION>.exe
+ release/windows/WorkDaddy-AI-Setup-<VERSION>.exe
```
- Remove the generated `WorkDaddy-1.1.2-win64.zip`, `WorkDaddy-AI-1.1.2-win64.zip`, and `release/.cache` before handoff or publication. The ZIPs are staging inputs, not Windows release artifacts. Confirm that `安装失败自主解决提示词.txt` is absent from both Setup.exe payloads.
+ Remove all generated `WorkDaddy-<VERSION>-win64.zip`, `WorkDaddy-AI-<VERSION>-win64.zip`, stale `release/windows/*-Setup-*.exe` files that are not part of this release, build logs, temporary verification directories, and `release/.cache` before handoff or publication. The ZIPs are staging inputs, not Windows release artifacts. Confirm that `安装失败自主解决提示词.txt` is absent from both Setup.exe payloads.
4. Inspect the actual Setup.exe payloads, not just their filenames. Run `innounp -t` on both files, list or extract them, and verify all of the following for each package:
- `scripts/runtime/node/node.exe` exists.
- - `scripts/daemon.js` reports the requested version, here `1.1.2`.
+ - `scripts/daemon.js` reports the requested `<VERSION>`.
- `scripts/win-launcher.js`, `scripts/watchdog.js`, and the required PowerShell scripts are present.
- CN uses `workbuddy-cn`, `47832`, `9222` as its defaults; AI uses `workbuddy-ai`, `47833`, `9223`.
+ - The extracted `scripts/inject.js` keeps the platform placeholder unquoted (`var WBS_PLATFORM = __WBS_PLATFORM__;`) so daemon replacement with `JSON.stringify(process.platform)` produces the correct `"win32"` value. Confirm the Windows path contains the auto-open installer flow and does not enter the macOS reboot progress branch.
- The package contains no `安装失败自主解决提示词.txt` and no temporary ZIP.
5. Run release checks from the same repository:
diff --git "a/docs/css-vars-\345\270\270\351\207\217\346\270\205\345\215\225.md" "b/docs/css-vars-\345\270\270\351\207\217\346\270\205\345\215\225.md"
new file mode 100644
index 0000000..0bd0d82
--- /dev/null
+++ "b/docs/css-vars-\345\270\270\351\207\217\346\270\205\345\215\225.md"
@@ -0,0 +1,171 @@
+# WorkDaddy CSS 变量常量全量清单
+
+> 来源:`scripts/daemon.js`(内置主题 `BUILTIN_THEMES`)、`scripts/inject.js`(检查器/皮肤生成/样式)、`scripts/theme-patches.js`(深色化补丁)。
+> 变量分三大命名空间:**`--vscode-*`**(body 层,整体布局)、**`--wb-*`**(:root 层,组件 token)、**`--dc-*`**(WorkDaddy 自定义面板 token);另有一批 **`--cb-*`**(WorkBuddy 官方 CodeBuddy 变量,被深色化补丁二次赋值)。
+
+---
+
+## 一、主题检查器使用的 9 个核心常量(用户示例出处,inject.js:5174)
+
+| 中文名 | 变量 | 官方深色值 |
+|---|---|---|
+| 背景-主 | `--wb-bg-primary` | `#0a0a0a` |
+| 背景-面板 | `--wb-bg-secondary` | `#111113` |
+| 侧边栏背景 | `--wb-sidebar-bg` | `#0c0c0e` |
+| 文字-主 | `--wb-color-text-primary` | `#f2f2f4` |
+| 文字-次 | `--wb-color-text-secondary` | `rgba(242,242,244,0.72)` |
+| 边框 | `--wb-border-default` | `rgba(255,255,255,0.12)` |
+| 按钮背景 | `--wb-button-primary-bg` | `rgba(255,255,255,0.92)` |
+| vscode背景 | `--vscode-editor-background` | `#0a0a0a` |
+| vscode文字 | `--vscode-editor-foreground` | `#f2f2f4` |
+
+> 这 9 个是主题检查器悬停检测用的最小集。完整主题文件需要下方全套变量。
+
+---
+
+## 二、内置主题完整 Schema(daemon.js:4119 `BUILTIN_THEMES`,三套共用)
+
+### 2.1 `--vscode-*` 层(50 个)
+
+```
+--vscode-editor-background --vscode-editor-foreground
+--vscode-sideBar-background --vscode-sideBar-foreground --vscode-sideBar-border
+--vscode-activityBar-background --vscode-activityBar-foreground
+--vscode-activityBar-inactiveForeground
+--vscode-activityBarBadge-background --vscode-activityBarBadge-foreground
+--vscode-titleBar-activeBackground --vscode-titleBar-activeForeground
+--vscode-tab-activeBackground --vscode-tab-activeForeground
+--vscode-tab-inactiveBackground --vscode-tab-inactiveForeground
+--vscode-tab-border
+--vscode-input-background --vscode-input-foreground
+--vscode-input-border --vscode-input-placeholderForeground
+--vscode-button-background --vscode-button-foreground
+--vscode-button-hoverBackground
+--vscode-list-activeSelectionBackground --vscode-list-activeSelectionForeground
+--vscode-list-hoverBackground --vscode-list-inactiveSelectionBackground
+--vscode-menu-background --vscode-menu-foreground
+--vscode-dropdown-background --vscode-dropdown-foreground --vscode-dropdown-border
+--vscode-panel-background --vscode-panel-border
+--vscode-badge-background --vscode-badge-foreground
+--vscode-foreground --vscode-descriptionForeground
+--vscode-focusBorder
+--vscode-scrollbarSlider-background --vscode-scrollbarSlider-hoverBackground
+--vscode-editorGroupHeader-tabsBackground --vscode-editorGroupHeader-tabsBorder
+--vscode-editorGroup-border
+--vscode-statusBar-background --vscode-statusBar-foreground
+--vscode-checkbox-background --vscode-checkbox-border --vscode-checkbox-foreground
+--vscode-editorWidget-background --vscode-editorWidget-border
+```
+
+### 2.2 `--wb-*` 组件层(44 个)
+
+**背景**
+```
+--wb-bg-primary --wb-bg-secondary --wb-bg-tertiary --wb-bg-popover
+--wb-bg-hover --wb-bg-active --wb-bg-overlay --wb-card-bg
+```
+
+**文字**
+```
+--wb-text-strong --wb-text-medium --wb-text-muted --wb-text-weak
+--wb-color-text-primary --wb-color-text-secondary --wb-color-text-tertiary
+--wb-color-text-disabled
+```
+
+**边框**
+```
+--wb-border-default --wb-border-subtle --wb-border-strong --wb-border-hover
+```
+
+**按钮**
+```
+--wb-button-primary-bg --wb-button-primary-fg --wb-button-primary-bg-hover
+```
+
+**状态**
+```
+--wb-status-success --wb-status-warning --wb-status-error --wb-status-info
+```
+
+**知识库(kb)**
+```
+--wb-kb-tabs-container-bg --wb-kb-tabs-container-border
+--wb-kb-card-bg --wb-kb-card-bg-soft --wb-kb-card-border
+```
+
+### 2.3 `--dc-*` 层(14 个,WorkDaddy 面板专用)
+
+```
+--dc-bg-primary --dc-bg-secondary --dc-bg-tertiary --dc-bg-hover
+--dc-text-primary --dc-text-secondary --dc-text-tertiary
+--dc-border --dc-border-light --dc-card-bg
+--dc-primary --dc-primary-hover --dc-primary-active --dc-btn-text
+```
+
+### 2.4 三套内置主题值
+
+- **default(默认浅色)**:`colors: {}` 空对象,即完全用 WorkBuddy 官方变量,不覆盖。
+- **oled-dark(OLED 纯黑,deep)**、**eye-care(护眼绿)**、**cyber-purple(赛博紫)**:同一 schema 三套值,见 daemon.js:4121-4278。
+- 示例值(oled-dark 深色):`--wb-bg-primary:#0a0a0c`、`--wb-bg-secondary:#131316`、`--wb-color-text-primary:#e6e6e9`、`--wb-border-subtle:#202025`、`--wb-button-primary-bg:rgba(255,255,255,0.92)`、`--dc-bg-primary:#0a0a0c`……
+
+> 注:内置主题的深色值与官方实际运行值(第一节表)是两套近似色,主题应用时直接覆盖页面变量。
+
+---
+
+## 三、运行期读取/适配的其他变量(代码引用,未在内置主题 schema 中)
+
+### 3.1 图片皮肤生成(inject.js:5776-5800,随图生成主题时写入)
+
+背景系:`--wb-bg-modal` `--wb-bg-card` `--wb-bg-content` `--wb-main-area-background`
+`--wb-home-bg-secondary` `--wb-home-composer-card-bg` `--wb-sidebar-bg` `--wb-home-bg-primary`
+`--cb-colleagues-dashboard-bg`
+
+文字系:`--wb-color-text-solid` `--wb-voice-input-text-primary`(加 `--wb-text-strong`/`--wb-color-text-primary`)
+
+vscode 系:`--vscode-panel-background` `--vscode-tab-activeBackground` `--vscode-sideBar-background`
+`--vscode-activityBar-background` `--vscode-editorGroupHeader-tabsBackground`
+
+固定值:`--wb-border-strong` `--wb-border-subtle` `--wb-button-primary-bg-hover` `--wb-status-*`
+
+### 3.2 主题探测 selectors 映射(daemon.js:4353-4357)
+
+```
+.teams-container.is-mac → --wb-home-bg-primary --wb-home-bg-secondary
+.project-detail-view__chat-input → --wb-bg-primary
+.project-detail-view__chat-input--task → --wb-bg-primary --wb-color-border-secondary
+[class*="mainArea"] → --wb-bg-hover
+.workbuddy-collab → --wb-border-info --wb-bg-info --wb-bg-action
+```
+
+### 3.3 theme-patches.js 深色化补丁引用的官方变量
+
+**wb 扩展 token**:`--wb-bg-modal` `--wb-bg-card` `--wb-bg-input` `--wb-bg-pill-active`
+`--wb-accent`(fallback `#f53f3f`)`--wb-accent-blue` `--wb-color-link` `--wb-color-border-secondary`
+`--wb-icon-secondary` `--wb-icon-tertiary` `--wb-color-bg-primary-hover-strong`
+`--wb-palette-brand-8`(官方青绿 rgb(0,194,154))`--wb-palette-gray-3`
+
+**cb 系官方变量(深色化时被覆盖赋值)**:
+```
+--cb-bg-secondary: var(--wb-bg-tertiary) --cb-border: var(--wb-border-subtle)
+--wb-palette-gray-3: var(--wb-bg-primary)
+--cb-markdown-table-cell-bg: var(--wb-bg-primary)
+--cb-markdown-table-header-bg: var(--wb-bg-secondary)
+--cb-markdown-table-border-color: var(--wb-border-strong)
+--cb-markdown-border-color: var(--wb-border-strong)
+```
+其余引用(未赋值,仅 var() 读取):`--cb-colleagues-dashboard-bg` `--cb-hover-bg` `--cb-panel-bg-primary`
+`--cb-text-primary` `--cb-text-secondary` `--cb-text-tertiary` `--cb-vscode-sideBar-background`
+`--cb-markdown-code-block-*` `--cb-markdown-table-color-bg`
+
+---
+
+## 四、全部变量清单速查(按命名空间计数)
+
+| 命名空间 | 数量 | 说明 |
+|---|---|---|
+| `--vscode-*` | 50 | body 层整体布局(内置主题 Schema) |
+| `--wb-*` | 44 | :root 组件 token(内置主题 Schema) |
+| `--dc-*` | 14 | WorkDaddy 面板 token(内置主题 Schema) |
+| `--wb-*` 扩展引用 | 21 | 皮肤生成/补丁/探测器引用(非 Schema) |
+| `--cb-*` | 15 | WorkBuddy 官方变量,补丁覆盖或引用 |
+| `--wb-palette-*` | 2 | `--wb-palette-brand-8`、`--wb-palette-gray-3` |
\ No newline at end of file
diff --git a/release/macos/WorkDaddy-1.1.2.dmg b/release/macos/WorkDaddy-1.1.3.dmg
similarity index 63%
rename from release/macos/WorkDaddy-1.1.2.dmg
rename to release/macos/WorkDaddy-1.1.3.dmg
index ea74172..f8a7902 100644
Binary files a/release/macos/WorkDaddy-1.1.2.dmg and b/release/macos/WorkDaddy-1.1.3.dmg differ
diff --git a/release/macos/WorkDaddy-AI-1.1.2.dmg b/release/macos/WorkDaddy-AI-1.1.3.dmg
similarity index 63%
rename from release/macos/WorkDaddy-AI-1.1.2.dmg
rename to release/macos/WorkDaddy-AI-1.1.3.dmg
index 7cd5923..3e5c406 100644
Binary files a/release/macos/WorkDaddy-AI-1.1.2.dmg and b/release/macos/WorkDaddy-AI-1.1.3.dmg differ
diff --git a/release/windows/WorkDaddy-Setup-1.1.2.exe b/release/windows/WorkDaddy-AI-Setup-1.1.3.exe
similarity index 72%
rename from release/windows/WorkDaddy-Setup-1.1.2.exe
rename to release/windows/WorkDaddy-AI-Setup-1.1.3.exe
index 8c2fef4..a0cccc5 100644
Binary files a/release/windows/WorkDaddy-Setup-1.1.2.exe and b/release/windows/WorkDaddy-AI-Setup-1.1.3.exe differ
diff --git a/release/windows/WorkDaddy-AI-Setup-1.1.2.exe b/release/windows/WorkDaddy-Setup-1.1.3.exe
similarity index 72%
rename from release/windows/WorkDaddy-AI-Setup-1.1.2.exe
rename to release/windows/WorkDaddy-Setup-1.1.3.exe
index 186ca23..95f34d6 100644
Binary files a/release/windows/WorkDaddy-AI-Setup-1.1.2.exe and b/release/windows/WorkDaddy-Setup-1.1.3.exe differ
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index 9b4ccba..ed79211 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -43,9 +43,15 @@ chmod 755 "$APP/Contents/MacOS/launcher"
echo "==> launcher 可执行位已保证: $(stat -f '%Sp' "$APP/Contents/MacOS/launcher")"
# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)
-for f in daemon.js session-db.js windows-process-boundary.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-usage-store.js atomic-file-write.js ui-port.js checkin-result.js lib.js profiles.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
+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 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
+WALLPAPER_OVERRIDE="scripts/builtin-overrides/wallpaper-06.webp"
+if [ -f "$WALLPAPER_OVERRIDE" ]; then
+ mkdir -p "$APP/Contents/Resources/scripts/builtin/wallpapers" "$APP/Contents/Resources/scripts/builtin/nebula"
+ cp "$WALLPAPER_OVERRIDE" "$APP/Contents/Resources/scripts/builtin/wallpapers/wallpaper-06.webp"
+ cp "$WALLPAPER_OVERRIDE" "$APP/Contents/Resources/scripts/builtin/nebula/background.webp"
+fi
# 恢复这些文件的壳权限(与 1.0.3 壳内一致:sh/lib/daemon 755,inject/theme-patches 644)
chmod 755 "$APP/Contents/Resources/scripts/daemon.js" \
"$APP/Contents/Resources/scripts/lib.js" \
@@ -55,12 +61,15 @@ 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/workbuddy-target.js" \
+ "$APP/Contents/Resources/scripts/secure-transfer.js" \
"$APP/Contents/Resources/scripts/windows-process-boundary.js" \
"$APP/Contents/Resources/scripts/credit-request-usage.js" \
"$APP/Contents/Resources/scripts/credit-usage-store.js" \
"$APP/Contents/Resources/scripts/atomic-file-write.js" \
"$APP/Contents/Resources/scripts/ui-port.js" \
"$APP/Contents/Resources/scripts/checkin-result.js" \
+ "$APP/Contents/Resources/scripts/workbuddy-compat.js" \
"$APP/Contents/Resources/scripts/inject.js" \
"$APP/Contents/Resources/scripts/theme-patches.js"
echo "==> 前端代码已覆盖(权限按壳原样)"
@@ -148,45 +157,6 @@ if [ -f "$PACKAGE_APP/Contents/Resources/scripts/package.json" ]; then
"$PACKAGE_APP/Contents/Resources/scripts/package.json"
fi
ln -s /Applications "$STAGE/Applications"
-cat > "$STAGE/安装失败自主解决提示词.txt" <<'EOF'
-WorkDaddy macOS 安装失败自助修复
-============================
-
-你是 WorkDaddy 的故障修复 agent。用户已经无法正常安装或启动 WorkDaddy。启动后必须先完整读取本文件,再在用户授权的源码目录内完成排查、修复和验证。修复通过后,诊断报告是本次修复流程的必需步骤;不得跳过、伪造或把排队当成成功。
-
-一、准备与排查
-
-1. 在临时目录执行:
- git clone https://github.com/babygoton/WorkDaddy.git
- cd WorkDaddy
-2. 阅读 README.md、scripts/install.sh、scripts/relaunch-with-cdp.sh、scripts/daemon.js,结合用户提供的错误复现问题。
-3. 只在源码目录操作;不要读取、复制、上传或修改 ~/Library/Application Support/CodeBuddyExtension/Data/Public/auth/、~/Library/Application Support/WorkDaddy/accounts/、数据库、Cookie、环境变量、私钥或完整日志。
-4. 记录一条关键错误、系统/Node/WorkBuddy 版本和可复现命令;不要粘贴完整日志。
-5. 可复现时运行 `bash scripts/install.sh` 和 `bash scripts/relaunch-with-cdp.sh`。
-
-二、修复与验证
-
-1. 只修改源码,保持用户数据和脱敏逻辑不变。
-2. 先确认根因;无法确认时明确写“未确认”,不要猜测。
-3. 运行:
- node --check scripts/sentry-report.js
- node --check scripts/daemon.js
- node --test test/*.test.js
-
-三、生成短报告
-
-在源码根目录写 WORKDADDY_FIX_REPORT.md。报告硬上限 3500 字符,最多包含:问题/根因、修改文件及目的、测试汇总、用户下一步。每项用短句;只引用一条脱敏错误,不附完整日志、命令输出、账号数据或凭据。
-
-四、诊断上报(修复通过后必须完成)
-
-「发送错误诊断」开关同时控制远程 Sentry 和本地脱敏诊断。用户启动本修复 agent 即表示允许发送本次脱敏修复报告;不要修改用户的持久化设置,也不要读取账号、Cookie、Token、数据库或完整日志。修复通过测试后必须执行以下命令:
-
- node scripts/sentry-report.js --stage agent-fix --level info --message-file WORKDADDY_FIX_REPORT.md --tags-json '{"source":"workbuddy-agent","status":"fixed","platform":"macos"}' --force-send --require-sent
-
-命令输出必须是 JSON,命令会自动重试。只有看到 `sent=true` 才算上报成功;看到 `queued=true` 或命令退出码非 0 时,必须继续检查网络、DNS、代理和系统时间后重试,不能向用户报告“已上报”。即使关于页开关关闭,`--force-send --require-sent` 也只用于本次用户主动发起的修复报告,并且仍受同样的脱敏规则约束。不要把 token、账号备份、数据库、输入框内容或完整日志放进 WORKDADDY_FIX_REPORT.md。
-
-如果测试仍未通过,不得伪造 fixed 状态;可以改用 status=unresolved,但仍必须使用同样的 `--force-send --require-sent`,并在报告中写清楚阻塞原因。
-EOF
rm -f "$OUT"
hdiutil create -volname "$PACKAGE_APP_NAME" -srcfolder "$STAGE" -ov -format UDZO -imagekey zlib-level=9 "$OUT" >/dev/null
rm -rf "$STAGE"
diff --git a/scripts/build-win-release.ps1 b/scripts/build-win-release.ps1
index 262cabf..b02b746 100644
--- a/scripts/build-win-release.ps1
+++ b/scripts/build-win-release.ps1
@@ -4,7 +4,8 @@ param(
[string]$OutputDirectory = '',
[string]$GitBashPath = '',
[string]$IsccPath = '',
- [string]$PythonPath = ''
+ [string]$PythonPath = '',
+ [string]$GoPath = ''
)
$ErrorActionPreference = 'Stop'
@@ -61,7 +62,8 @@ function Invoke-WindowsZipBuild {
[Parameter(Mandatory)][string]$Bash,
[Parameter(Mandatory)][string]$Profile,
[Parameter(Mandatory)][string]$ReleaseVersion,
- [string]$CachedPython
+ [string]$CachedPython,
+ [string]$GoExecutable
)
$bashRepo = ConvertTo-GitBashPath $repoRoot
@@ -70,7 +72,12 @@ function Invoke-WindowsZipBuild {
$pythonBash = ConvertTo-GitBashPath $CachedPython
$pythonAssignment = " WORKDADDY_PYTHON=`"$pythonBash`""
}
- $command = "cd `"$bashRepo`" && WORKDADDY_BUILD_PROFILE=`"$Profile`" WORKDADDY_BUILD_VERSION=`"$ReleaseVersion`"$pythonAssignment bash scripts/build-win-zip.sh"
+ $goAssignment = ''
+ if ($GoExecutable) {
+ $goBash = ConvertTo-GitBashPath $GoExecutable
+ $goAssignment = " WORKDADDY_GO=`"$goBash`""
+ }
+ $command = "cd `"$bashRepo`" && WORKDADDY_BUILD_PROFILE=`"$Profile`" WORKDADDY_BUILD_VERSION=`"$ReleaseVersion`"$pythonAssignment$goAssignment bash scripts/build-win-zip.sh"
Write-Host "`n==> 生成 $Profile staging ZIP"
& $Bash -lc $command
if ($LASTEXITCODE -ne 0) {
@@ -136,10 +143,22 @@ try {
throw "找不到指定的 Python: $PythonPath"
}
+ if (-not $GoPath) {
+ $goCommand = Get-Command go.exe -ErrorAction SilentlyContinue
+ if ($goCommand) { $GoPath = $goCommand.Source }
+ if (-not $GoPath) {
+ $cachedGo = Join-Path $env:USERPROFILE '.workdaddy-toolchains\go1.27.0\bin\go.exe'
+ if (Test-Path -LiteralPath $cachedGo -PathType Leaf) { $GoPath = $cachedGo }
+ }
+ }
+ if (-not $GoPath -or -not (Test-Path -LiteralPath $GoPath -PathType Leaf)) {
+ throw '找不到 Go 1.24+;请安装 Go 或使用 -GoPath 指定 go.exe。'
+ }
+
New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null
$packages = @()
foreach ($profile in @('workbuddy-cn', 'workbuddy-ai')) {
- Invoke-WindowsZipBuild -Bash $bash -Profile $profile -ReleaseVersion $Version -CachedPython $PythonPath
+ Invoke-WindowsZipBuild -Bash $bash -Profile $profile -ReleaseVersion $Version -CachedPython $PythonPath -GoExecutable $GoPath
$packages += Invoke-WindowsInstallerBuild -Profile $profile -ReleaseVersion $Version -Compiler $iscc
}
diff --git a/scripts/build-win-zip.sh b/scripts/build-win-zip.sh
index 4b3d0fc..33cf732 100644
--- a/scripts/build-win-zip.sh
+++ b/scripts/build-win-zip.sh
@@ -50,11 +50,6 @@ case "$PROFILE" in
*) PROFILE="workbuddy-cn"; PACKAGE_NAME="WorkDaddy"; OUT="release/windows/WorkDaddy-${VERSION}-win64.zip" ;;
esac
-if [ ! -f scripts/apply-update.vbs ]; then
- echo "错误:关键文件 scripts/apply-update.vbs 缺失,无法生成 Windows 更新包" >&2
- exit 2
-fi
-
echo "==> profile: ${PROFILE}"
echo "==> 版本: ${VERSION}"
echo "==> 产物: ${OUT}"
@@ -64,10 +59,23 @@ echo "==> 产物: ${OUT}"
# WORKDADDY_NODE_ARCHIVE 指向预下载压缩包以支持离线/受限网络构建。
NODE_VERSION="${WORKDADDY_NODE_VERSION:-22.23.1}"
NODE_ARCHIVE="node-v${NODE_VERSION}-win-x64.zip"
-NODE_URL="https://nodejs.org/dist/v${NODE_VERSION}/${NODE_ARCHIVE}"
+NODE_URL="${WORKDADDY_NODE_URL:-https://npmmirror.com/mirrors/node/v${NODE_VERSION}/${NODE_ARCHIVE}}"
NODE_SHA256="7df0bc9375723f4a86b3aa1b7cc73342423d9677a8df4538aca31a049e309c29"
NODE_CACHE="${WORKDADDY_NODE_CACHE:-$DIR/release/.cache}"
mkdir -p "$NODE_CACHE"
+
+# 正式 Windows 入口是自包含原生 EXE。它负责标准权限、单实例、原生对话框和
+# 精确进程检测;普通启动不再经过 cmd/vbs/PowerShell/CIM。
+GO_BIN="${WORKDADDY_GO:-go}"
+if ! command -v "$GO_BIN" >/dev/null 2>&1 && [ ! -x "$GO_BIN" ]; then
+ echo "错误:缺少 Go 1.24+(可设置 WORKDADDY_GO 指向 go.exe)" >&2
+ exit 2
+fi
+NATIVE_LAUNCHER="$NODE_CACHE/WorkDaddyLauncher.exe"
+echo "==> 编译原生 Windows 启动器"
+CGO_ENABLED=0 GOOS=windows GOARCH=amd64 "$GO_BIN" build -trimpath \
+ -ldflags '-s -w -H=windowsgui' -o "$NATIVE_LAUNCHER" ./scripts/windows-native/main.go
+test -s "$NATIVE_LAUNCHER"
NODE_ARCHIVE_PATH="${WORKDADDY_NODE_ARCHIVE:-$NODE_CACHE/$NODE_ARCHIVE}"
if [ ! -f "$NODE_ARCHIVE_PATH" ]; then
echo "==> 下载 Node.js v${NODE_VERSION} Windows x64 运行时"
@@ -108,6 +116,11 @@ if [ -d "$BUILTIN_SRC" ]; then
else
echo "==> 警告: 未找到内置资产 $BUILTIN_SRC(无 WorkDaddy.app?),打包将不含官方壁纸/主题"
fi
+WALLPAPER_OVERRIDE="$DIR/scripts/builtin-overrides/wallpaper-06.webp"
+if [ -f "$WALLPAPER_OVERRIDE" ] && [ -d scripts/builtin ]; then
+ cp "$WALLPAPER_OVERRIDE" scripts/builtin/wallpapers/wallpaper-06.webp
+ cp "$WALLPAPER_OVERRIDE" scripts/builtin/nebula/background.webp
+fi
# 3) 打包:staging 目录,把两个顶层入口文件 + scripts/ 一起打进 zip 根(解压即见一键安装/启动)
# 注意 apply-update.ps1 复用本结构(需 zip 内存在 scripts\daemon.js 做 srcRoot 判定)
@@ -121,6 +134,9 @@ cp scripts/Install-WorkDaddy.cmd "$STAGE/Install-WorkDaddy.cmd"
cp scripts/Start-WorkDaddy.cmd "$STAGE/Start-WorkDaddy.cmd"
# 3.2) scripts\ 本体(含 node_modules/ws、builtin)
cp -R scripts "$STAGE/scripts"
+cp "$NATIVE_LAUNCHER" "$STAGE/WorkDaddyLauncher.exe"
+printf '%s\n' "$PROFILE" > "$STAGE/scripts/profile-id.txt"
+echo "==> 原生入口: WorkDaddyLauncher.exe (${PROFILE})"
# Windows cmd.exe expects CRLF in batch files. Normalise every staged .cmd
# after copying so a source edit made on macOS cannot leave a mixed-ending
# launcher that silently stops before invoking Node.
diff --git a/scripts/build-windows-native.ps1 b/scripts/build-windows-native.ps1
new file mode 100644
index 0000000..71c9667
--- /dev/null
+++ b/scripts/build-windows-native.ps1
@@ -0,0 +1,45 @@
+[CmdletBinding()]
+param(
+ [string]$OutputPath = '',
+ [string]$GoPath = ''
+)
+
+$ErrorActionPreference = 'Stop'
+Set-StrictMode -Version 2.0
+
+$scriptsRoot = $PSScriptRoot
+$source = Join-Path $scriptsRoot 'windows-native\main.go'
+if (-not $OutputPath) { $OutputPath = Join-Path $scriptsRoot 'WorkDaddyLauncher.exe' }
+$OutputPath = [IO.Path]::GetFullPath($OutputPath)
+
+if (-not $GoPath) {
+ $command = Get-Command go.exe -ErrorAction SilentlyContinue
+ if ($command) { $GoPath = $command.Source }
+}
+if (-not $GoPath) {
+ $userToolchain = Join-Path $env:USERPROFILE '.workdaddy-toolchains\go1.27.0\bin\go.exe'
+ if (Test-Path -LiteralPath $userToolchain -PathType Leaf) { $GoPath = $userToolchain }
+}
+if (-not $GoPath -or -not (Test-Path -LiteralPath $GoPath -PathType Leaf)) {
+ throw 'Go 1.27+ was not found. Install Go or pass -GoPath.'
+}
+
+$versionOutput = & $GoPath version
+if ($LASTEXITCODE -ne 0 -or $versionOutput -notmatch 'go version go(?<major>\d+)\.(?<minor>\d+)') {
+ throw 'Unable to read the Go version.'
+}
+if ([int]$matches.major -lt 1 -or ([int]$matches.major -eq 1 -and [int]$matches.minor -lt 24)) {
+ throw "Go version is too old: $versionOutput"
+}
+
+$outputDir = Split-Path -Parent $OutputPath
+New-Item -ItemType Directory -Force -Path $outputDir | Out-Null
+$env:CGO_ENABLED = '0'
+$env:GOOS = 'windows'
+$env:GOARCH = 'amd64'
+& $GoPath build -trimpath -ldflags '-s -w -H=windowsgui' -o $OutputPath $source
+if ($LASTEXITCODE -ne 0) { throw "Native launcher build failed with exit code $LASTEXITCODE." }
+if (-not (Test-Path -LiteralPath $OutputPath -PathType Leaf) -or (Get-Item -LiteralPath $OutputPath).Length -le 0) {
+ throw "Native launcher output is missing: $OutputPath"
+}
+Write-Host "Created $OutputPath"
diff --git a/scripts/builtin-overrides/wallpaper-06.webp b/scripts/builtin-overrides/wallpaper-06.webp
new file mode 100644
index 0000000..09f26db
Binary files /dev/null and b/scripts/builtin-overrides/wallpaper-06.webp differ
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 1ea32bb..4e6224b 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -15,6 +15,8 @@
* WBSWITCH_DATA_DIR 备份数据目录(默认 ~/Library/Application Support/WorkDaddy)
* WBSWITCH_PORT Web 界面端口(显式指定时固定;未指定时从 47832 起尝试)
* WBSWITCH_CDP_PORT WorkBuddy CDP 首选端口(被占用时自动切换到 9222-9232/9333)
+ * WBSWITCH_WORKBUDDY_BIN / WBSWITCH_WORKBUDDY_VERSION
+ * VPC/便携版目标程序路径与可选版本校验
*
* 用法: node scripts/daemon.js
*/
@@ -40,7 +42,7 @@ const {
selectPreferredDiscoveredBinary,
} = require('./windows-process-boundary.js');
const DAEMON_PRIVILEGE = process.platform === 'win32'
- ? detectWindowsPrivilege()
+ ? (process.env.WBSWITCH_NATIVE_LAUNCHER === '1' ? 'standard' : detectWindowsPrivilege())
: 'standard';
// ws(WebSocketServer)用于 DevTools 代理:Electron 的 CDP server 拒绝带 Origin 的 WS 连接
// (浏览器必带 Origin → DevTools 前端 "websocket disconnected"),daemon 代理中转去掉 Origin
@@ -110,8 +112,16 @@ const {
telemetryEnvironmentOverride,
} = require('./sentry-report.js');
const { getProfile, profileDataDir, listInstalledModelSources } = require('./profiles.js');
+const { readWorkBuddyTarget } = require('./workbuddy-target.js');
const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('./cdp-targets.js');
const { createSessionDb, normalizeSessionIdBatch, parameterCount } = require('./session-db.js');
+const {
+ createEncryptedExport,
+ openEncryptedExport,
+ remapSessionArchivePath,
+ requiredPassword,
+ resolveArchiveTarget,
+} = require('./secure-transfer.js');
const { replaceFileWithRetry } = require('./atomic-file-write.js');
const { parseUiPortState, profileUiPortCandidates } = require('./ui-port.js');
@@ -210,8 +220,16 @@ const DATA_DIR = defaultDataDir();
// 1.1.7:Windows 启动可靠性、profile 隔离 UI 端口、原子配置写入和 CIM 竞态修复。
// 1.1.8:签到只接受明确成功响应并写入 SQLite;悬浮球释放时增加阻尼回弹。
// 1.1.9:签到请求进行中仍立即展示已确认的今日签到标记。
-const DAEMON_VERSION = '1.1.9';
-const DAEMON_BUILD_ID = 'release-1.1.9-20260828-checkin-cache-first';
+// 1.1.10:账号支持选择性导出;会话和快捷短语支持强制密码加密导入导出。
+// 1.1.11:会话导入成功后通过 CDP 刷新 WorkBuddy 窗口,使新会话立即载入。
+// 1.1.12:VPC/便携版可通过用户数据目录配置 WorkBuddy 路径与版本。
+// 1.1.14:Windows 安装器依赖改为仅在 Windows 更新分支加载,避免 macOS daemon 启动失败。
+// 1.1.15:新版 WorkBuddy 按 DOM/队列能力适配,不再把新版布局等同于 AI profile。
+// 1.1.16:元素检查器改为 WorkDaddy 插件内弹窗,支持 DOM 树、悬停高亮和重叠元素浏览,不再提供独立页面。
+// 1.1.24:6 号官方壁纸替换为新默认图;消息导航与机器人瞳孔改为悬浮毛玻璃。
+// 1.1.25:内置官方壁纸更新时刷新数据目录旧副本;新 profile 默认启用 WorkDaddy 壁纸主题。
+const DAEMON_VERSION = '1.1.25';
+const DAEMON_BUILD_ID = 'release-1.1.25-20260830-unread-dot-theme';
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
@@ -1084,8 +1102,8 @@ function extractAppFromDmg(dmgPath) {
});
}
-// 安装:macOS 调 apply-update.sh(launchctl 停服 → 备份 → 替换 → relaunch);
-// Windows 调 apply-update.ps1(杀 watchdog/daemon → 释放文件锁 → 替换目录 → 重启)
+// 安装:macOS 继续使用 apply-update.sh;Windows 打开已校验的可见 Setup.exe,
+// 由 Inno Setup 确认 WorkBuddy 已退出、替换文件并启动新版。
function applyUpdate() {
if (!updateState.downloaded) {
updateDebug('apply-error', { stage: 'preflight', error: '尚未下载完成', latest: updateState.latest });
@@ -1121,72 +1139,61 @@ function applyUpdate() {
};
const markSpawnFailure = (error) => markAttemptFailure(error, 'spawn-error');
if (IS_WIN) {
- // Windows 安装位置由 install.ps1 铺好(%LOCALAPPDATA%\Programs\WorkDaddy)
- const scriptPath = path.join(__dirname, 'apply-update.ps1');
- const appDir = WORKDADDY_DIR_WIN;
+ const { launchWindowsInstaller } = require('./windows-installer-launch.js');
+ // Windows 更新只负责打开已经过 SHA-256 校验的可见 Setup.exe。
+ // 文件替换、WorkBuddy 退出确认和新版启动全部由 Inno Setup 接管;
+ // daemon/watchdog 在安装器真正开始复制前保持运行,因此 UI 不会失联。
const updatePrefix = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI-' : 'WorkDaddy-';
const packageExt = /\.exe$/i.test(updateState.assetName || '') ? '.exe' : '.zip';
const srcPackage = path.join(UPDATE_DIR, updatePrefix + updateState.latest + packageExt);
- if (!fs.existsSync(scriptPath)) {
- const error = new Error('缺少 apply-update.ps1');
- markAttemptFailure(error, 'preflight-error');
- return Promise.reject(error);
- }
if (!fs.existsSync(srcPackage)) {
const error = new Error('缺少已下载的新版本安装包');
markAttemptFailure(error, 'preflight-error');
return Promise.reject(error);
}
+ if (packageExt !== '.exe') {
+ const error = new Error('此历史版本只提供 ZIP,无法使用新的可见安装流程;请从发布页下载 Setup.exe');
+ markAttemptFailure(error, 'unsupported-artifact');
+ return Promise.reject(error);
+ }
+ const expectedAsset = PROFILE.id === 'workbuddy-ai'
+ ? `WorkDaddy-AI-Setup-${updateState.latest}.exe`
+ : `WorkDaddy-Setup-${updateState.latest}.exe`;
+ if (String(updateState.assetName || '').toLowerCase() !== expectedAsset.toLowerCase()) {
+ const error = new Error('安装包名称与目标 profile 或版本不一致');
+ markAttemptFailure(error, 'artifact-identity');
+ return Promise.reject(error);
+ }
attempt.sourcePackage = srcPackage;
- attempt.targetApp = appDir;
+ attempt.assetName = updateState.assetName;
writeUpdateAttempt(attempt);
- log('[update] 执行 apply-update.ps1 attempt=' + attempt.id + ' log=' + applyLog);
- updateDebug('apply-script-start', { script: 'apply-update.ps1', attemptId: attempt.id, sourcePackage: srcPackage, targetApp: appDir, applyLog });
- // 【更新标记】写入 pending.json:watchdog 检测到它在 daemon 退出后【不自动重启 daemon】,
- // 双重保险(配合本函数末尾「先精确停 watchdog 再自我退出」),彻底杜绝 watchdog 在替换窗口期
- // 复活 daemon 抢占 47832 端口的竞态(历史上第一轮更新偶发失败、需点第二次才成功的根因)。
- // apply-update.ps1 成功/失败都负责删除该标记。
- const pendingFile = path.join(UPDATE_DIR, 'pending.json');
- try { fs.writeFileSync(pendingFile, JSON.stringify({ attempt: attempt.id, at: new Date().toISOString() })); } catch (_) {}
- // 【Windows 更新进程模型真相 · 挖坑实录 2.0】这条路踩遍三种写法,全部实例验证:
- // ① detached:true + stdio:'ignore':PowerShell 5.1(console 程序)在 detached(无控制台)下宿主
- // 初始化静默退出,-File 脚本根本不执行 → apply.log 永不生成、替换永不发生,面板一直「重启中」。
- // ② 不 detached + pipe 收集输出:脚本能跑,但 Node 在 Windows 上 spawn 的子进程位于 Job Object,
- // daemon 自我退出 → job 关闭 → powershell 被连带杀死(实测日志停在「停止 watchdog」一步)。
- // ③ detached + cmd.exe /c 中转:cmd 同为 console 程序,一样不执行。
- // 唯一可靠的「父进程死后子进程照跑」通道:wscript.exe(GUI 子系统,不依赖控制台)做中介,
- // VBS 内 WScript.Shell.Run 用 ShellExecute 创建完全独立于 Node Job Object 的 powershell 进程。
- let applyVbs;
- try {
- applyVbs = resolveApplyUpdateVbs();
- } catch (e) {
- markAttemptFailure(e, 'preflight-error');
- return Promise.reject(e);
- }
- const wscript = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'wscript.exe');
- const child = spawn(
- wscript,
- ['//nologo', applyVbs, scriptPath, srcPackage, appDir, String(ACTUAL_PORT), applyLog, attempt.id, PROFILE.id],
- { detached: true, stdio: 'ignore', windowsHide: true }
- );
- child.once('error', markSpawnFailure);
- child.once('spawn', () => {
- attempt.status = 'script-started';
- attempt.scriptPid = child.pid;
- writeUpdateAttempt(attempt);
- log('[update] apply-update.ps1 已启动(经 wscript 中介) pid=' + child.pid);
- updateDebug('apply-script-spawned', { script: 'apply-update.ps1', attemptId: attempt.id, pid: child.pid });
+ updateDebug('installer-open', { attemptId: attempt.id, sourcePackage: srcPackage, assetName: updateState.assetName });
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const child = launchWindowsInstaller(srcPackage);
+ child.once('error', (error) => {
+ if (settled) return;
+ settled = true;
+ markSpawnFailure(error);
+ updateState.status = 'error';
+ updateState.message = '无法打开安装程序';
+ updateState.error = error.message;
+ reject(error);
+ });
+ child.once('spawn', () => {
+ if (settled) return;
+ settled = true;
+ child.unref();
+ attempt.status = 'installer-opened';
+ attempt.installerPid = child.pid;
+ attempt.finishedAt = new Date().toISOString();
+ writeUpdateAttempt(attempt);
+ updateState.status = 'installer-opened';
+ updateState.message = '安装程序已打开';
+ updateDebug('installer-opened', { attemptId: attempt.id, pid: child.pid, assetName: updateState.assetName });
+ resolve({ ok: true, opened: true, status: 'installer-opened', message: '安装程序已打开,请按提示完成安装' });
+ });
});
- child.unref();
- // 【竞态加固 · 更新标记】daemon 自我退出后,watchdog 默认会在 3s 后重启新的 daemon 抢占 47832,
- // 干扰替换。防复活职责完全交给「update/pending.json 更新标记」:watchdog 检测到标记后不自动
- // 重启 daemon(见 watchdog.js),标记由 apply-update.ps1 finally 清理。
- // ⚠️ 千万不要在这里用 spawnSync 去杀 watchdog / 做任何同步操作:spawnSync 会阻塞 Node 事件循环,
- // daemon 将既无法响应 API(面板报「daemon 不可达」)也无法执行下面这行 process.exit(0),
- // 安装目录一直被占用 → Mov-Item 报「正在使用中」→ 更新必失败(实测 4 连败的根因)。
- // 直接干净退出即可,退出过程零阻塞(毫秒级)。
- setTimeout(() => { try { process.exit(0); } catch (_) {} }, 800);
- return Promise.resolve({ ok: true, message: '已启动更新,正在替换文件并自动重启,请稍候…' });
}
const scriptPath = path.join(__dirname, 'apply-update.sh');
const appPath = macWorkDaddyAppPath();
@@ -1711,7 +1718,10 @@ async function reloadWorkBuddyPage() {
await cdpSend('Page.reload', { ignoreCache: false });
}
-const WORKBUDDY_APP = IS_WIN ? '' : PROFILE.appPath;
+const WORKBUDDY_TARGET = IS_WIN ? null : readWorkBuddyTarget({ dataDir: DATA_DIR, profileId: PROFILE.id });
+const WORKBUDDY_APP = IS_WIN ? '' : (WORKBUDDY_TARGET.binary
+ ? path.resolve(WORKBUDDY_TARGET.binary, '../../..')
+ : PROFILE.appPath);
const WORKBUDDY_BINARY = IS_WIN ? '' : `${WORKBUDDY_APP}/Contents/MacOS/Electron`;
const WORKBUDDY_APP_NAME = path.basename(WORKBUDDY_APP).replace(/\.app$/i, '');
@@ -1753,6 +1763,11 @@ function resolveWorkBuddyBinary() {
const { execFileSync } = require('child_process');
const psCmd = (cmd) => execFileSync('powershell', ['-NoProfile', '-Command', cmd], { encoding: 'utf8', timeout: 8000, windowsHide: true });
const runningBin = selectRunningProfileBinary(PROFILE_BINARY_NAMES, queryWindowsWorkBuddyProcesses());
+ const configuredTarget = readWorkBuddyTarget({ dataDir: DATA_DIR, profileId: PROFILE.id });
+ const configuredBin = tryFile(configuredTarget.binary);
+ if (configuredTarget.configured && !configuredBin) {
+ throw new Error('workbuddy-target.json 指定的路径不是可验证的当前 profile 主程序;登录信息未修改');
+ }
// 1) 显式指定;若当前 profile 已运行,必须与运行路径完全一致。
const envBin = tryFile(process.env.WBSWITCH_WORKBUDDY_BIN);
if (process.env.WBSWITCH_WORKBUDDY_BIN && !envBin) {
@@ -1764,6 +1779,12 @@ function resolveWorkBuddyBinary() {
}
return (wbBinaryCache = envBin);
}
+ if (configuredBin) {
+ if (runningBin && !sameWindowsPath(runningBin, configuredBin)) {
+ throw new Error('检测到当前 profile 正从另一安装目录运行,登录信息未修改');
+ }
+ return (wbBinaryCache = configuredBin);
+ }
// 2) 运行中当前 profile 的主程序优先(便携安装)。
if (runningBin) return (wbBinaryCache = runningBin);
const discovered = [];
@@ -2371,14 +2392,27 @@ function injectWidget(reason) {
lastInjectTs = now;
let script;
try {
- script = fs.readFileSync(path.join(__dirname, 'inject.js'), 'utf8');
+ const compatScript = fs.readFileSync(path.join(__dirname, 'workbuddy-compat.js'), 'utf8');
+ let injectScript = fs.readFileSync(path.join(__dirname, 'inject.js'), 'utf8');
+ // 内部调试模块(元素检查/DevTools):picker-internal.js 存在才注入(git 不跟踪,
+ // 他人环境无此文件 → 隐藏入口的拾取按钮点击会报错,符合预期,不影响面板其他功能)。
+ // 注入位置:放进 build() 函数体末尾(与面板共享闭包作用域:root/toast/esc 等),
+ // 这样拾取实现与原版稳定版 debug 模块完全同域,不被 IIFE 边界隔开。
+ const pickerPath = path.join(__dirname, 'picker-internal.js');
+ if (fs.existsSync(pickerPath)) {
+ const pickerCode = fs.readFileSync(pickerPath, 'utf8');
+ const anchor = 'return { destroy: lifecycle.destroy, alive: lifecycle.alive };';
+ if (!injectScript.includes(anchor)) {
+ return Promise.reject(new Error('picker-internal.js 注入锚点不存在'));
+ }
+ injectScript = injectScript.replace(anchor, pickerCode + '\n' + anchor);
+ }
+ script = compatScript + '\n' + injectScript;
} catch (e) {
return Promise.reject(new Error('读取注入脚本失败: ' + e.message));
}
// 组件内通过 fetch 调用本机 API,注入时写入实际端口
script = script.replace(/__WBS_API__/g, `http://${HOST}:${ACTUAL_PORT}`);
- // 同步注入当前 daemon 版本号(inject.js 顶部的 __WBS_VERSION__ 占位符会在面板「关于」页直接展示,
- // 这样版本升级后不需要改 inject.js、面板永远显示 daemon 的真实版本)
script = script.replace(/__WBS_VERSION__/g, DAEMON_VERSION);
// 注入本地 API 能力凭证;旧版面板不会携带该 header,但新版 daemon 会在启动时重新注入新版面板。
script = script.replace(/__WBS_API_TOKEN__/g, API_TOKEN);
@@ -2718,6 +2752,104 @@ function copySessionFiles(wbHome, oldId, newId) {
return result;
}
+const MAX_SESSION_EXPORT_BYTES = 256 * 1024 * 1024;
+const MAX_SESSION_EXPORT_FILES = 20000;
+
+function archiveRelativePath(wbHome, target) {
+ return path.relative(wbHome, target).split(path.sep).join('/');
+}
+
+function collectSessionArchiveFiles(wbHome, sessionId) {
+ if (!isValidSessionId(sessionId)) throw new Error('无效的会话 ID');
+ const files = [];
+ let totalBytes = 0;
+ const collect = (target) => {
+ let stat;
+ try { stat = fs.lstatSync(target); }
+ catch (error) { if (error && error.code === 'ENOENT') return; throw error; }
+ if (stat.isSymbolicLink()) return;
+ if (stat.isDirectory()) {
+ const entries = fs.readdirSync(target, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
+ for (const entry of entries) {
+ if (entry.isSymbolicLink()) continue;
+ collect(path.join(target, entry.name));
+ }
+ return;
+ }
+ if (!stat.isFile()) return;
+ if (files.length >= MAX_SESSION_EXPORT_FILES) throw new Error('会话附件文件过多,无法导出');
+ if (totalBytes + stat.size > MAX_SESSION_EXPORT_BYTES) throw new Error('会话附件超过 256 MB,无法导出');
+ const relative = archiveRelativePath(wbHome, target);
+ // Validate every exported path with the same mapper used during import.
+ remapSessionArchivePath(relative, sessionId, sessionId);
+ const content = fs.readFileSync(target);
+ totalBytes += content.length;
+ if (totalBytes > MAX_SESSION_EXPORT_BYTES) throw new Error('会话附件超过 256 MB,无法导出');
+ files.push({ path: relative, data: content.toString('base64') });
+ };
+
+ const projects = path.join(wbHome, 'projects');
+ try {
+ const projectEntries = fs.readdirSync(projects, { withFileTypes: true });
+ for (const project of projectEntries) {
+ if (!project.isDirectory() || project.isSymbolicLink()) continue;
+ const projectRoot = path.join(projects, project.name);
+ collect(path.join(projectRoot, sessionId + '.jsonl'));
+ collect(path.join(projectRoot, sessionId));
+ }
+ } catch (error) {
+ if (!error || error.code !== 'ENOENT') throw error;
+ }
+ collect(path.join(wbHome, 'workspace', 'sessions', sessionId));
+ collect(path.join(wbHome, 'tasks', sessionId));
+ collect(path.join(wbHome, 'file-history', sessionId));
+ collect(path.join(wbHome, 'artifact-index', sessionId + '.json'));
+ return files;
+}
+
+function ensureArchiveParentNoFollow(wbHome, target) {
+ const root = path.resolve(wbHome);
+ const rootStat = fs.lstatSync(root);
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) throw new Error('WorkBuddy 数据目录不是受管目录');
+ const parent = path.dirname(resolveArchiveTarget(root, archiveRelativePath(root, target)));
+ const relative = path.relative(root, parent);
+ let current = root;
+ for (const part of relative.split(path.sep).filter(Boolean)) {
+ current = path.join(current, part);
+ try {
+ const stat = fs.lstatSync(current);
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('会话归档目标包含符号链接或普通文件');
+ } catch (error) {
+ if (error && error.code === 'ENOENT') fs.mkdirSync(current, { mode: 0o700 });
+ else throw error;
+ }
+ }
+}
+
+function restoreSessionArchiveFiles(wbHome, sessionArchive, newId) {
+ const oldId = String(sessionArchive && sessionArchive.record && sessionArchive.record.id || '');
+ if (!isValidSessionId(oldId) || !isValidSessionId(newId)) throw new Error('会话归档包含无效 ID');
+ const sourceFiles = Array.isArray(sessionArchive.files) ? sessionArchive.files : [];
+ if (sourceFiles.length > MAX_SESSION_EXPORT_FILES) throw new Error('会话归档附件文件过多');
+ let totalBytes = 0;
+ const targets = new Set();
+ for (const entry of sourceFiles) {
+ if (!entry || typeof entry.path !== 'string' || typeof entry.data !== 'string' || entry.data.length % 4 === 1 || !/^[A-Za-z0-9+/]*={0,2}$/.test(entry.data)) {
+ throw new Error('会话归档包含无效附件');
+ }
+ const relative = remapSessionArchivePath(entry.path, oldId, newId);
+ const target = resolveArchiveTarget(wbHome, relative);
+ if (targets.has(target)) throw new Error('会话归档包含重复附件路径');
+ targets.add(target);
+ const content = Buffer.from(entry.data, 'base64');
+ totalBytes += content.length;
+ if (totalBytes > MAX_SESSION_EXPORT_BYTES) throw new Error('会话归档附件超过 256 MB');
+ ensureArchiveParentNoFollow(wbHome, target);
+ fs.writeFileSync(target, content, { flag: 'wx', mode: 0o600 });
+ }
+ return sourceFiles.length;
+}
+
const SESSION_COPY_COLUMNS = [
'id', 'cwd', 'user_id', 'title', 'custom_title', 'status', 'created_at', 'updated_at',
'last_activity_at', 'is_playground', 'source_mode', 'is_background_automation', 'mode', 'model',
@@ -2765,6 +2897,66 @@ async function insertCopiedSession(src, targetUid, newId) {
);
}
+async function exportSessions(ids, password) {
+ const selectedIds = normalizeSessionIdBatch(ids);
+ if (!selectedIds.length) throw new Error('未选择会话');
+ requiredPassword(password);
+ const rows = await sqliteQuery(
+ 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id IN (' + sqlPlaceholders(selectedIds) + ') AND deleted_at IS NULL;',
+ selectedIds
+ );
+ const byId = new Map(rows.map((row) => [String(row.id), row]));
+ const wbHome = PROFILE.dataRoot;
+ const sessions = selectedIds.filter((id) => byId.has(id)).map((id) => {
+ const record = byId.get(id);
+ return { record, files: collectSessionArchiveFiles(wbHome, id) };
+ });
+ if (!sessions.length) throw new Error('没有可导出的会话');
+ const payload = { exportType: 'WorkDaddy-sessions', version: 1, sessions };
+ const content = createEncryptedExport('sessions', payload, password);
+ return {
+ filename: 'WorkDaddy-会话导出-' + new Date().toISOString().slice(0, 10) + '.json',
+ content,
+ count: sessions.length,
+ };
+}
+
+function validImportedSessionUid(value) {
+ const uid = String(value || '').trim();
+ if (!uid || uid.length > 200 || /[\x00-\x1f\x7f]/.test(uid)) throw new Error('会话归档缺少有效的账号归属');
+ return uid;
+}
+
+async function importSessions(content, password, targetUid) {
+ const payload = openEncryptedExport(content, 'sessions', password);
+ const archives = Array.isArray(payload.sessions) ? payload.sessions : [];
+ if (!archives.length) throw new Error('导入文件中没有会话数据');
+ if (archives.length > 100) throw new Error('单次最多导入 100 个会话');
+ const overrideUid = typeof targetUid === 'string' && targetUid.trim() ? validImportedSessionUid(targetUid) : '';
+ const currentUid = String((currentAccount() || {}).uid || '').trim();
+ const imported = [];
+ const errors = [];
+ for (const archive of archives) {
+ const record = archive && archive.record;
+ const oldId = String(record && record.id || '');
+ if (!record || !isValidSessionId(oldId)) { errors.push('无效会话记录'); continue; }
+ let ownerUid;
+ try { ownerUid = overrideUid || validImportedSessionUid(record.user_id || currentUid); }
+ catch (error) { errors.push(error.message); continue; }
+ const newId = crypto.randomUUID();
+ try {
+ restoreSessionArchiveFiles(PROFILE.dataRoot, archive, newId);
+ await insertCopiedSession(record, ownerUid, newId);
+ imported.push({ sourceId: oldId, id: newId, uid: ownerUid });
+ } catch (error) {
+ try { deleteSessionFiles(PROFILE.dataRoot, newId); } catch (_) {}
+ errors.push(error.message);
+ }
+ }
+ if (!imported.length) throw new Error(errors[0] || '没有可导入的会话');
+ return { imported, failed: errors.length };
+}
+
async function copySessionRecord(src, targetUid, options = {}) {
const sourceUid = String(options.sourceUid || src.user_id || '').trim();
const auto = !!options.auto;
@@ -3614,6 +3806,58 @@ function deleteQuickPhrases(ids) {
writeSessionState(st);
return readSessionState();
}
+function normalizeQuickPhraseIds(ids) {
+ if (!Array.isArray(ids)) throw new Error('快捷短语选择必须是数组');
+ if (ids.length > 1000) throw new Error('单次最多处理 1000 条快捷短语');
+ const result = [];
+ const seen = new Set();
+ for (const value of ids) {
+ const id = String(value || '').trim();
+ if (!id) throw new Error('快捷短语标识不能为空');
+ if (!seen.has(id)) { seen.add(id); result.push(id); }
+ }
+ return result;
+}
+function exportQuickPhrases(ids, password) {
+ const selectedIds = normalizeQuickPhraseIds(ids);
+ if (!selectedIds.length) throw new Error('未选择快捷短语');
+ requiredPassword(password);
+ const selected = new Set(selectedIds);
+ const phrases = readSessionState().phrases
+ .filter((item) => selected.has(String(item.id)))
+ .map((item) => ({ text: String(item.text || ''), createdAt: Number(item.createdAt || Date.now()) }));
+ if (!phrases.length) throw new Error('没有可导出的快捷短语');
+ const payload = { exportType: 'WorkDaddy-quick-phrases', version: 1, phrases };
+ return {
+ filename: 'WorkDaddy-快捷短语导出-' + new Date().toISOString().slice(0, 10) + '.json',
+ content: createEncryptedExport('quick-phrases', payload, password),
+ count: phrases.length,
+ };
+}
+function importQuickPhrases(content, password) {
+ const payload = openEncryptedExport(content, 'quick-phrases', password);
+ const incoming = Array.isArray(payload.phrases) ? payload.phrases : [];
+ if (!incoming.length) throw new Error('导入文件中没有快捷短语');
+ if (incoming.length > 1000) throw new Error('单次最多导入 1000 条快捷短语');
+ const state = readSessionState();
+ const existing = new Set(state.phrases.map((item) => String(item.text || '').trim()).filter(Boolean));
+ let imported = 0;
+ let skipped = 0;
+ for (const item of incoming) {
+ const text = String(item && item.text || '').trim();
+ if (!text || existing.has(text)) { skipped++; continue; }
+ existing.add(text);
+ state.phrases.push({
+ id: 'qp_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8),
+ text,
+ createdAt: Number(item && item.createdAt || Date.now()),
+ });
+ imported++;
+ }
+ if (!imported && !skipped) throw new Error('没有可导入的快捷短语');
+ writeSessionState(state);
+ return { state: readSessionState(), imported, skipped };
+}
/** 通过 CDP 发送指定短语:聚焦 composer → 全选 → 真实输入短语 → 真实 Enter(replace 式发送,多行短语按段落插入) */
async function acSendPhrase(text) {
if (!cdp.connected) throw new Error('CDP 未连接');
@@ -3821,9 +4065,14 @@ function builtinAssetsDir() {
return null;
}
-/** 内置资产补齐(新电脑 / 数据目录为空 / 资产缺失时):内置壁纸 + WorkDaddy 主题 + 默认蒙版 10%
- * 幂等:逐项补齐——壁纸缺失才复制、nebula 主题缺失才安装、mask.json 缺失才写,
- * 不覆盖用户已有的自定义/删减内容(已存在的文件不动)。
+function builtinWallpaperSource(baseDir, fileName) {
+ const override = path.join(__dirname, 'builtin-overrides', fileName);
+ return fs.existsSync(override) ? override : path.join(baseDir, 'wallpapers', fileName);
+}
+
+/** 内置资产同步:官方壁纸 + WorkDaddy 主题 + 默认蒙版 10%
+ * 幂等:官方 wallpaper-*.webp 由应用管理,内置内容变化时刷新;custom-* 与用户主题不覆盖。
+ * nebula 主题和背景仅在缺失时安装,避免覆盖用户后来选择的主题配色或背景。
*/
function initBuiltinAssets() {
if (!PROFILE.capabilities.theme) return;
@@ -3833,21 +4082,26 @@ function initBuiltinAssets() {
log('[init] 未找到内置资产目录(builtin/),跳过初始化');
return;
}
- // 1) 内置壁纸 → themes/wallpapers/(缺哪张补哪张,已有不动)
+ // 1) 内置官方壁纸 → themes/wallpapers/(缺失时补齐、应用升级内容变化时刷新)
const wpSrc = path.join(src, 'wallpapers');
if (fs.existsSync(wpSrc)) {
const files = fs.readdirSync(wpSrc).filter((f) => /\.webp$/i.test(f)).sort();
if (files.length) {
fs.mkdirSync(WALLPAPERS_DIR, { recursive: true });
let added = 0;
+ let updated = 0;
for (const f of files) {
+ const source = builtinWallpaperSource(src, f);
const dest = path.join(WALLPAPERS_DIR, f);
if (!fs.existsSync(dest)) {
- fs.copyFileSync(path.join(wpSrc, f), dest);
+ fs.copyFileSync(source, dest);
added++;
+ } else if (Buffer.compare(fs.readFileSync(source), fs.readFileSync(dest)) !== 0) {
+ fs.copyFileSync(source, dest);
+ updated++;
}
}
- if (added) log(`[init] 补齐内置壁纸 ${added} 张 -> ${WALLPAPERS_DIR}(已有 ${files.length - added} 张保留)`);
+ if (added || updated) log(`[init] 同步内置壁纸:新增 ${added} 张,更新 ${updated} 张 -> ${WALLPAPERS_DIR}`);
}
}
// 2) WorkDaddy 主题(nebula)→ themes/nebula/(缺失才安装,已有不动)
@@ -3860,7 +4114,7 @@ function initBuiltinAssets() {
fs.copyFileSync(path.join(thSrc, 'theme.json'), themeJson);
log('[init] 已安装 WorkDaddy 主题(nebula)');
}
- const bgSrc = path.join(thSrc, 'background.webp');
+ const bgSrc = builtinWallpaperSource(src, 'wallpaper-06.webp');
const bgDst = path.join(thDst, 'background.webp');
if (fs.existsSync(bgSrc) && !fs.existsSync(bgDst)) {
fs.copyFileSync(bgSrc, bgDst);
@@ -3873,11 +4127,11 @@ function initBuiltinAssets() {
fs.writeFileSync(maskFile, JSON.stringify({ opacity: 0.1 }, null, 2));
log('[init] 首次初始化:背景蒙版默认 10% -> mask.json');
}
- // 4) 默认主题 → WorkBuddy 默认主题(仅当未设置过;用户要求默认选中官方浅色,不再默认 nebula)
+ // 4) 默认主题 → WorkDaddy 壁纸主题(仅当 profile 从未设置过主题)
const curFile = path.join(DATA_DIR, 'current-theme.json');
if (!fs.existsSync(curFile)) {
- fs.writeFileSync(curFile, JSON.stringify({ id: 'default', at: new Date().toISOString() }, null, 2));
- log('[init] 首次初始化:默认主题 -> WorkBuddy 默认主题(default)');
+ fs.writeFileSync(curFile, JSON.stringify({ id: 'nebula', at: new Date().toISOString() }, null, 2));
+ log('[init] 首次初始化:默认主题 -> WorkDaddy 壁纸主题(nebula)');
}
} catch (e) {
log('[init] 首次初始化失败: ' + e.message);
@@ -4158,6 +4412,50 @@ function themeExtrasCss() {
return loadThemePatches().map((p) => (p && p.css ? p.css : '')).join('');
}
+/** 主题变量别名层:从 theme-vars.js 热加载(官方漏定义/深色值不对的 token 重定向到主题变量)。
+ * body 级定义生成 `html[data-theme="dark"] body[data-vscode-theme-name]{...}`(darkOnly=true 时前缀深色条件),
+ * 组件作用域定义生成 `html[data-theme="dark"] body[data-vscode-theme-name] <sel>{...}`。
+ * 属「常量可搞定」的样式处理,不占 theme-patches.js(那里只保留必须针对元素写规则的魔改补丁)。
+ */
+let _varsCache = null;
+let _varsMtime = 0;
+function loadThemeVars() {
+ try {
+ const f = path.join(__dirname, 'theme-vars.js');
+ const st = fs.statSync(f);
+ if (!_varsCache || st.mtimeMs !== _varsMtime) {
+ delete require.cache[require.resolve(f)];
+ _varsCache = require(f);
+ _varsMtime = st.mtimeMs;
+ }
+ return _varsCache || { body: [], scoped: [] };
+ } catch (e) {
+ log('[theme] 变量别名层加载失败: ' + e.message);
+ return { body: [], scoped: [] };
+ }
+}
+/** 生成变量别名 CSS:isDark 时 darkOnly 条目加 html[data-theme="dark"] 前缀;浅色主题跳过 darkOnly 条目 */
+function themeVarsCss(isDark) {
+ const mod = loadThemeVars();
+ const pre = isDark ? 'html[data-theme="dark"] ' : '';
+ let out = '';
+ const declOf = (vars) => Object.keys(vars || {}).map((k) => k + ':' + vars[k] + ';').join('');
+ for (const b of mod.body || []) {
+ if (b.darkOnly && !isDark) continue;
+ const lead = b.darkOnly ? pre : '';
+ const d = declOf(b.vars);
+ if (d) out += lead + 'body[data-vscode-theme-name]{' + d + '}';
+ }
+ for (const s of mod.scoped || []) {
+ if (s.darkOnly && !isDark) continue;
+ const lead = (s.darkOnly ? pre : '') + 'body[data-vscode-theme-name] ';
+ const sels = String(s.sel).split(',').map((seg) => lead + seg.trim()).join(',');
+ const d = declOf(s.vars);
+ if (d) out += sels + '{' + d + '}';
+ }
+ return out;
+}
+
async function applyThemeByCdp(id) {
if (!PROFILE.capabilities.theme) throw new Error(`${PROFILE.name} 暂不支持主题功能`);
if (!cdp.connected) throw new Error('CDP 未连接');
@@ -4209,11 +4507,15 @@ async function applyThemeByCdp(id) {
const dataUrl = 'data:' + mime + ';base64,' + buf.toString('base64');
// WBSS 背景图方案:背景图铺 #root,容器透明 + 半透明毛玻璃让底图透出
// 遮罩/半透明度调低(40%/34%/30%):背景图偏暗时让图更透出,毛玻璃更可见
- // 全局黑色蒙版(默认 0.1,面板主题页可调):rgba(0,0,0,α) 压在最上层,让背景图更沉、文字更可读
+ // 全局黑色蒙版(默认 0.3,面板主题页可调):rgba(0,0,0,α) 压在最上层,让背景图更沉、文字更可读
+ // 注意:opacity=0 是合法的「关闭蒙版」,不能用 || 兜底(0 会被当成 falsy 变成 0.1)
const maskFile = path.join(DATA_DIR, 'mask.json');
let mask = 0.3;
try {
- if (fs.existsSync(maskFile)) mask = Math.min(1, Math.max(0, parseFloat(JSON.parse(fs.readFileSync(maskFile, 'utf8')).opacity) || 0.1));
+ if (fs.existsSync(maskFile)) {
+ const v = parseFloat(JSON.parse(fs.readFileSync(maskFile, 'utf8')).opacity);
+ if (!Number.isNaN(v)) mask = Math.min(1, Math.max(0, v));
+ }
} catch (_) {}
bgCssStr = [
'#root{background:',
@@ -4224,8 +4526,8 @@ async function applyThemeByCdp(id) {
'body[data-vscode-theme-name] .teams-container,body[data-vscode-theme-name] .teams-container.is-mac{background:transparent !important}',
'body[data-vscode-theme-name] [data-view-id]{background:transparent !important}',
'body[data-vscode-theme-name] .main-content{background:transparent !important}',
- // 左侧菜单(会话列表)半透明毛玻璃:背景图透出 + 模糊
- 'body[data-vscode-theme-name] .conversation-list,body[data-vscode-theme-name] [data-view-id=sidebar]{background:color-mix(in srgb,var(--wb-bg-primary) 34%,transparent) !important;backdrop-filter:blur(26px) saturate(1.2);-webkit-backdrop-filter:blur(26px) saturate(1.2)}',
+ // 左侧菜单(会话列表)透明(用户 08-30 00:46 要求去掉毛玻璃,连同子组件全透明,背景图直接透出)
+ 'body[data-vscode-theme-name] .conversation-list,body[data-vscode-theme-name] [data-view-id=sidebar]{background:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important}',
// 输入框区域:毛玻璃背景(用户要求加回:半透明 + 模糊,背景图透出)
// 注意:聊天页 [class*="input-area-container"] 父容器改为透明(patch-40 处理),
// 主页 .wb-home-composer 也改为透明(patch-37),毛玻璃只保留在输入框主体 _mainArea(patch-40)。
@@ -4242,6 +4544,9 @@ async function applyThemeByCdp(id) {
var h = document.documentElement, b = document.body;
if (!h || !b) return { pending: true };
var WBS_UID = ${JSON.stringify(uid || null)};
+ // WorkDaddy 自定义主题已应用标记:theme-patches 里部分规则用 html[data-wbs-theme] 限定
+ // 只在 WorkDaddy 内置自定义主题下生效(官方默认主题不激活)。
+ try { h.setAttribute('data-wbs-theme', ${id === 'default' ? "'0'" : "'1'"}); } catch (e) {}
// 联动 WorkBuddy 原生主题(源码 theme.ts ThemeManager + legacy-appearance-mode-storage):
// 1) 写 localStorage 'agent-ui-theme'(ThemeManager.saveTheme 同款结构),reload/重启后 WorkBuddy 自己恢复该主题;
// 2) 写 'workbuddy.appearance.lastApplied'(getInitialTheme 优先读它,避免残留旧外观覆盖我们的配置);
@@ -4303,8 +4608,11 @@ async function applyThemeByCdp(id) {
b.setAttribute('data-vscode-theme-name', 'IDE Light'); b.classList.remove('vscode-dark');
wbsSyncNativeTheme('light');
}
- // 注入自定义色板(body 层覆盖,同优先级后插入胜出)
- var css = 'body[data-vscode-theme-name]{' + ${JSON.stringify(allCssStr)} + '}' + ${JSON.stringify(localCssStr)} + ${JSON.stringify(extrasCss)} + ${JSON.stringify(bgCssStr)};
+ // 注入自定义色板(body 层覆盖,同优先级后插入胜出)+ 变量别名层(官方漏定义 token 重定向)
+ var css = 'body[data-vscode-theme-name]{' + ${JSON.stringify(allCssStr)} + '}' +
+ ${JSON.stringify(localCssStr)} +
+ ${JSON.stringify(themeVarsCss(isDark))} +
+ ${JSON.stringify(extrasCss)} + ${JSON.stringify(bgCssStr)};
var st = document.createElement('style');
st.id = 'wbs-theme-style';
st.textContent = css;
@@ -4964,7 +5272,7 @@ async function syncCurrentCreditUsage(uid, accessToken) {
}
}
-/* ================= 账号导出 / 导入 =================
+/* ================= 加密导出 / 导入 =================
* v2 导出:用户在面板输入非空密码;随机 salt + AES-256-GCM,密码不落盘、不写日志。
* v1 导入:兼容历史固定密码 workdaddy 的导出文件,空密码即走旧格式默认值。
*/
@@ -4974,27 +5282,6 @@ const EXPORT_KDF_SALT = 'WorkDaddy-account-export-v1';
function exportSecretKey(password, salt) {
return crypto.scryptSync(String(password), salt, 32);
}
-// 密文布局:iv(12) + authTag(16) + ciphertext
-function encryptExport(plain, password) {
- const salt = crypto.randomBytes(16);
- const iv = crypto.randomBytes(12);
- const cipher = crypto.createCipheriv('aes-256-gcm', exportSecretKey(password, salt), iv);
- const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
- const tag = cipher.getAuthTag();
- return { data: Buffer.concat([iv, tag, enc]).toString('base64'), salt: salt.toString('base64') };
-}
-function decryptExport(b64, password, saltB64) {
- const buf = Buffer.from(String(b64 || ''), 'base64');
- if (buf.length <= 28) throw new Error('导出数据不完整或已损坏');
- const salt = Buffer.from(String(saltB64 || ''), 'base64');
- if (salt.length !== 16) throw new Error('导出文件缺少有效的加密 salt');
- const iv = buf.subarray(0, 12);
- const tag = buf.subarray(12, 28);
- const data = buf.subarray(28);
- const decipher = crypto.createDecipheriv('aes-256-gcm', exportSecretKey(password, salt), iv);
- decipher.setAuthTag(tag);
- return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8');
-}
function decryptLegacyExport(b64, password) {
const buf = Buffer.from(String(b64 || ''), 'base64');
@@ -5170,6 +5457,30 @@ function handleApi(req, res) {
}
});
}
+ // 快捷短语加密导出:POST /api/quick-phrases/export { ids, password }
+ if (req.method === 'POST' && p === '/api/quick-phrases/export') {
+ return readBody(req).then((body) => {
+ try {
+ const result = exportQuickPhrases(body && body.ids, body && body.password);
+ log(`[quick-phrases-export] 已导出 ${result.count} 条快捷短语`);
+ return json(res, 200, { ok: true, ...result });
+ } catch (error) {
+ return json(res, 400, { ok: false, error: error.message });
+ }
+ });
+ }
+ // 快捷短语加密导入:POST /api/quick-phrases/import { content, password }
+ if (req.method === 'POST' && p === '/api/quick-phrases/import') {
+ return readBody(req).then((body) => {
+ try {
+ const result = importQuickPhrases(body && body.content, body && body.password);
+ log(`[quick-phrases-import] 已导入 ${result.imported} 条,跳过 ${result.skipped} 条`);
+ return json(res, 200, { ok: true, ...result.state, imported: result.imported, skipped: result.skipped });
+ } catch (error) {
+ return json(res, 400, { ok: false, error: error.message });
+ }
+ });
+ }
// 会话模块:POST /api/quick-phrase-send { text }(CDP 替换输入框内容并发送)
if (req.method === 'POST' && p === '/api/quick-phrase-send') {
return readBody(req).then((body) =>
@@ -5457,10 +5768,15 @@ function handleApi(req, res) {
return readBody(req).then((body) => {
try {
const enteredPassword = body && typeof body.password === 'string' ? body.password : '';
- const password = enteredPassword.trim() ? enteredPassword : '';
- if (password.length > 1024) return json(res, 400, { ok: false, error: '密码不能超过 1024 个字符' });
- if (!password.trim()) return json(res, 400, { ok: false, error: '导出密码不能为空' });
- const accounts = listAccounts(DATA_DIR);
+ const password = requiredPassword(enteredPassword);
+ let selectedUids = null;
+ if (body && body.uids !== undefined) {
+ if (!Array.isArray(body.uids)) return json(res, 400, { ok: false, error: '账号选择必须是数组' });
+ if (body.uids.length > 500) return json(res, 400, { ok: false, error: '选择的账号过多' });
+ selectedUids = new Set(body.uids.map((uid) => String(uid || '').trim()).filter(Boolean));
+ if (!selectedUids.size) return json(res, 400, { ok: false, error: '请至少选择一个账号' });
+ }
+ const accounts = listAccounts(DATA_DIR).filter((account) => !selectedUids || selectedUids.has(String(account.uid)));
const items = [];
for (const a of accounts) {
const file = backupPath(DATA_DIR, a.uid);
@@ -5473,15 +5789,7 @@ function handleApi(req, res) {
}
if (!items.length) return json(res, 200, { ok: false, error: '没有可导出的账号备份' });
const payload = { exportType: 'WorkDaddy-accounts', version: 2, accounts: items };
- const encrypted = encryptExport(JSON.stringify(payload), password);
- const envelope = JSON.stringify({
- wbsExport: 'WorkDaddy',
- version: 2,
- createdAt: new Date().toISOString(),
- kdf: 'aes-256-gcm+scrypt',
- salt: encrypted.salt,
- data: encrypted.data,
- });
+ const envelope = createEncryptedExport('accounts', payload, password);
const filename = 'WorkDaddy-账号导出-' + new Date().toISOString().slice(0, 10) + '.json';
log(`[export] 导出 ${items.length} 个账号 -> ${filename}`);
return json(res, 200, { ok: true, filename, content: envelope, count: items.length });
@@ -5507,15 +5815,12 @@ function handleApi(req, res) {
const enteredPassword = body && typeof body.password === 'string' ? body.password : '';
const password = enteredPassword.trim() ? enteredPassword : '';
if (password.length > 1024) throw new Error('密码不能超过 1024 个字符');
- let payloadText;
+ let payload;
if (Number(envelope.version) >= 2) {
- if (!envelope.salt) throw new Error('导出文件缺少有效的加密 salt');
- if (!password.trim()) throw new Error('导入该文件需要密码');
- payloadText = decryptExport(envelope.data, password, envelope.salt);
+ payload = openEncryptedExport(text, 'accounts', password);
} else {
- payloadText = decryptLegacyExport(envelope.data, password || EXPORT_PASSPHRASE);
+ payload = JSON.parse(decryptLegacyExport(envelope.data, password || EXPORT_PASSPHRASE));
}
- const payload = JSON.parse(payloadText);
const list = Array.isArray(payload && payload.accounts) ? payload.accounts : [];
if (!list.length) throw new Error('导入文件中没有账号数据');
ensureDirs(DATA_DIR);
@@ -5573,11 +5878,14 @@ function handleApi(req, res) {
// 官方背景图库列表(themes/wallpapers/*.webp),供面板「主题」页预览切换。
// 附带 currentWallpaper:当前主题 background.webp 内容哈希匹配到的图库文件名(供面板高亮当前壁纸)
+ // 附带 customWallpapers:用户上传的自定义壁纸(custom-*.webp),供面板分开展示
if (req.method === 'GET' && p === '/api/wallpapers') {
try {
const files = fs.existsSync(WALLPAPERS_DIR)
? fs.readdirSync(WALLPAPERS_DIR).filter((f) => /\.webp$/i.test(f)).sort()
: [];
+ const official = files.filter((f) => !/^custom-/i.test(f));
+ const custom = files.filter((f) => /^custom-/i.test(f));
// 当前背景 = 当前主题目录的 background.webp(哈希对比图库)
let currentWallpaper = null;
try {
@@ -5592,7 +5900,59 @@ function handleApi(req, res) {
}
}
} catch (_) {}
- return json(res, 200, { ok: true, wallpapers: files.map((f) => ({ name: f, title: '官方壁纸 ' + String(f.replace(/\.webp$/i, '')).replace(/^wallpaper-?0*/, '') })), currentWallpaper });
+ return json(res, 200, {
+ ok: true,
+ wallpapers: official.map((f) => ({ name: f, title: '官方壁纸 ' + String(f.replace(/\.webp$/i, '')).replace(/^wallpaper-?0*/, '') })),
+ customWallpapers: custom.map((f) => ({ name: f, title: '自定义壁纸 ' + String(f.replace(/\.webp$/i, '')).replace(/^custom-/, '') })),
+ currentWallpaper,
+ });
+ } catch (e) {
+ return json(res, 500, { ok: false, error: e.message });
+ }
+ }
+
+ // 自定义壁纸管理(themes/wallpapers/custom-*.webp):
+ // GET /api/custom-wallpapers —— 列表(冗余,主要随 /api/wallpapers 返回)
+ // POST /api/custom-wallpapers —— 上传 body.dataUrl(base64),保存为 custom-<时间戳>.webp 并返回 name
+ // DELETE /api/custom-wallpapers?name=x —— 删除指定自定义壁纸文件(仅 custom- 前缀,防误删官方壁纸)
+ if (req.method === 'GET' && p === '/api/custom-wallpapers') {
+ try {
+ const files = fs.existsSync(WALLPAPERS_DIR)
+ ? fs.readdirSync(WALLPAPERS_DIR).filter((f) => /^custom-[A-Za-z0-9_.-]+\.webp$/i.test(f)).sort()
+ : [];
+ return json(res, 200, { ok: true, wallpapers: files.map((f) => ({ name: f, title: '自定义壁纸 ' + String(f.replace(/\.webp$/i, '')).replace(/^custom-/, '') })) });
+ } catch (e) {
+ return json(res, 500, { ok: false, error: e.message });
+ }
+ }
+ if (req.method === 'POST' && p === '/api/custom-wallpapers') {
+ return readBody(req).then((body) => {
+ try {
+ const dataUrl = String(body.dataUrl || '');
+ const m = /^data:image\/(png|jpe?g|webp);base64,(.+)$/i.exec(dataUrl);
+ if (!m) return json(res, 400, { ok: false, error: '图片必须是 PNG/JPEG/WebP base64' });
+ const buf = Buffer.from(m[2], 'base64');
+ if (buf.length > 10 * 1024 * 1024) return json(res, 400, { ok: false, error: '图片不能超过 10MB' });
+ fs.mkdirSync(WALLPAPERS_DIR, { recursive: true });
+ const name = 'custom-' + Date.now().toString(36) + '.webp';
+ fs.writeFileSync(path.join(WALLPAPERS_DIR, name), buf);
+ log(`[theme] 上传自定义壁纸 -> ${name} (${buf.length}B)`);
+ return json(res, 200, { ok: true, name });
+ } catch (e) {
+ return json(res, 500, { ok: false, error: e.message });
+ }
+ });
+ }
+ if (req.method === 'DELETE' && p === '/api/custom-wallpapers') {
+ try {
+ const raw = String(req.url.split('?')[1] || '');
+ const name = decodeURIComponent(/name=([^&]+)/.exec(raw) ? RegExp.$1 : '');
+ if (!/^custom-[A-Za-z0-9_.-]+\.webp$/i.test(name)) return json(res, 400, { ok: false, error: '仅支持删除自定义壁纸(custom-*.webp)' });
+ const file = path.join(WALLPAPERS_DIR, name);
+ if (!fs.existsSync(file)) return json(res, 404, { ok: false, error: '壁纸不存在: ' + name });
+ fs.unlinkSync(file);
+ log('[theme] 删除自定义壁纸 -> ' + name);
+ return json(res, 200, { ok: true, name });
} catch (e) {
return json(res, 500, { ok: false, error: e.message });
}
@@ -5602,8 +5962,12 @@ function handleApi(req, res) {
if (req.method === 'GET' && p === '/api/mask') {
try {
const f = path.join(DATA_DIR, 'mask.json');
- const opacity = fs.existsSync(f) ? (parseFloat(JSON.parse(fs.readFileSync(f, 'utf8')).opacity) || 0.3) : 0.1;
- return json(res, 200, { ok: true, opacity: Math.min(1, Math.max(0, opacity)) });
+ let opacity = 0.1;
+ if (fs.existsSync(f)) {
+ const v = parseFloat(JSON.parse(fs.readFileSync(f, 'utf8')).opacity);
+ if (!Number.isNaN(v)) opacity = Math.min(1, Math.max(0, v));
+ }
+ return json(res, 200, { ok: true, opacity });
} catch (e) {
return json(res, 200, { ok: true, opacity: 0.1 });
}
@@ -5883,6 +6247,38 @@ function handleApi(req, res) {
const job = autoCopyJobs.get(url.searchParams.get('id') || '');
return job ? json(res, 200, { ok: true, job: publicAutoCopyJob(job) }) : json(res, 404, { ok: false, error: '自动复制任务不存在' });
}
+ // 加密导出会话及其受管消息附件:POST /api/sessions/export { ids, password }
+ if (req.method === 'POST' && p === '/api/sessions/export') {
+ return readBody(req).then(async (body) => {
+ try {
+ const result = await exportSessions(body && body.ids, body && body.password);
+ log(`[sessions-export] 已导出 ${result.count} 个会话`);
+ return json(res, 200, { ok: true, ...result });
+ } catch (error) {
+ return json(res, 400, { ok: false, error: error.message });
+ }
+ });
+ }
+ // 加密导入会话;targetUid 缺省时保留归档中的账号归属。
+ if (req.method === 'POST' && p === '/api/sessions/import') {
+ return readBody(req).then(async (body) => {
+ try {
+ const result = await importSessions(body && body.content, body && body.password, body && body.targetUid);
+ log(`[sessions-import] 已导入 ${result.imported.length} 个会话,失败 ${result.failed} 个`);
+ let reloaded = false;
+ try {
+ await reloadWorkBuddyPage();
+ reloaded = true;
+ log('[sessions-import] 已通过 CDP 刷新 WorkBuddy 窗口');
+ } catch (reloadError) {
+ log(`[sessions-import] CDP 刷新失败: ${reloadError.message}`);
+ }
+ return json(res, 200, { ok: true, count: result.imported.length, imported: result.imported, failed: result.failed, reloaded });
+ } catch (error) {
+ return json(res, 400, { ok: false, error: error.message });
+ }
+ });
+ }
// 复制会话:POST /api/sessions/copy { ids, targetUid }(保留原会话,复制记录+消息文件到目标账号)
if (req.method === 'POST' && p === '/api/sessions/copy') {
return readBody(req).then(async (body) => {
@@ -6103,7 +6499,10 @@ function handleApi(req, res) {
// 替换主题背景图(保持主题配色不变):存 background.webp + 更新 theme.json image 字段 +
// 设 current 并立即应用。用于面板「图片」按钮——用户换背景图不生成新主题,reload 后恢复的就是新图。
- // 支持两种来源:body.dataUrl(用户上传 base64)/ body.wallpaper(官方图库文件名,从 wallpapers 目录复制)
+ // 支持三种来源:body.dataUrl(用户上传 base64)/ body.wallpaper(官方图库文件名,从 wallpapers 目录复制)/
+ // body.custom(自定义壁纸文件名,从 wallpapers/custom-* 复制)
+ // 注意:CDP 未连接时应用主题会失败,但文件与 current-theme.json 已保存——此时仍返回成功,
+ // 由 restoreSavedTheme 在连接恢复后自动应用,避免"背景图已保存但应用失败"的报错困扰用户。
if (req.method === 'POST' && p === '/api/theme-bg') {
return readBody(req).then((body) => {
try {
@@ -6111,12 +6510,20 @@ function handleApi(req, res) {
if (!id) return json(res, 400, { ok: false, error: '缺少 id' });
let buf = null;
const wpName = String(body.wallpaper || '');
+ const customName = String(body.custom || '');
if (wpName) {
// 官方图库:从 wallpapers 目录读取(防路径穿越:只允许纯文件名)
const safeName = path.basename(wpName).replace(/[^A-Za-z0-9._-]/g, '_');
const src = path.join(WALLPAPERS_DIR, safeName);
if (!fs.existsSync(src)) return json(res, 400, { ok: false, error: '壁纸不存在: ' + safeName });
buf = fs.readFileSync(src);
+ } else if (customName) {
+ // 自定义壁纸:从 wallpapers/custom-* 读取(同样防路径穿越)
+ const safeName = path.basename(customName).replace(/[^A-Za-z0-9._-]/g, '_');
+ if (!/^custom-/i.test(safeName)) return json(res, 400, { ok: false, error: '壁纸不存在: ' + safeName });
+ const src = path.join(WALLPAPERS_DIR, safeName);
+ if (!fs.existsSync(src)) return json(res, 400, { ok: false, error: '壁纸不存在: ' + safeName });
+ buf = fs.readFileSync(src);
} else {
const dataUrl = String(body.dataUrl || '');
const m = /^data:image\/(png|jpe?g|webp);base64,(.+)$/i.exec(dataUrl);
@@ -6141,9 +6548,10 @@ function handleApi(req, res) {
fs.writeFileSync(path.join(DATA_DIR, 'current-theme.json'), JSON.stringify({ id, at: new Date().toISOString() }, null, 2));
} catch (_) {}
log('[theme] 替换背景图 -> ' + id + '/background.webp (' + buf.length + 'B)');
+ // CDP 未连接/应用失败不再判为整体失败:文件已落盘,连接恢复后 restoreSavedTheme 会应用
return applyThemeByCdp(id)
- .then((info) => json(res, 200, { ok: true, image: 'background.webp', applied: info.ok, id }))
- .catch((e) => json(res, 500, { ok: false, error: '背景图已保存但应用失败: ' + e.message }));
+ .then((info) => json(res, 200, { ok: true, image: 'background.webp', applied: !!(info && info.ok), id }))
+ .catch((e) => json(res, 200, { ok: true, image: 'background.webp', applied: false, pending: true, id, warn: '背景已保存,主题将在连接恢复后自动应用' }));
} catch (e) {
return json(res, 500, { ok: false, error: e.message });
}
diff --git a/scripts/inject.js b/scripts/inject.js
index 3557514..e060659 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -180,53 +180,6 @@ function stashContentMatches(expected, current) {
return !!expected && !!current && stashContentSignature(expected) === stashContentSignature(current);
}
-// WorkBuddy AI 的会话 id 在侧栏 conversation-item 上;用户/助手消息的 req-* id
-// 只是消息请求 id,不能用于队列 RPC。选择态目前落在卡片子节点的 _selected_* class,
-// 同时兼容 aria-selected/active,避免依赖某个构建生成的完整 hash class。
-function resolveWorkBuddyAiConversationId(candidates) {
- var list = Array.isArray(candidates) ? candidates : [];
- for (var i = 0; i < list.length; i++) {
- var item = list[i] || {};
- var classes = String(item.className || '') + ' ' + String(item.childClassName || '');
- if (item.ariaSelected === true || item.ariaSelected === 'true' ||
- /(^|\s)active(\s|$)/.test(classes) || /_selected_/.test(classes)) {
- var id = String(item.conversationId || '').trim();
- if (id) return id;
- }
- }
- return null;
-}
-
-function workBuddyAiDraftStorageKey(sessionId) {
- var id = String(sessionId || '').trim();
- return id ? 'cb-draft:' + id : null;
-}
-
-function isWorkBuddyAiComposerStore(store, sessionId) {
- try {
- if (!store || typeof store !== 'object' || !store.api ||
- typeof store.api.clear !== 'function' || typeof store.api.setBlocks !== 'function' ||
- typeof store.api.getDraft !== 'function' || typeof store.getSnapshot !== 'function') return false;
- var snapshot = store.getSnapshot();
- return !!snapshot && String(snapshot.activeSessionId || '') === String(sessionId || '');
- } catch (_) {
- return false;
- }
-}
-
-// WorkDaddy AI 新版移除面板主题入口后,首次打开面板时把旧版可能遗留的
-// WorkDaddy 主题恢复为官方浅色。key 固定且带迁移版本,确保只执行一次。
-function workBuddyAiThemeMigrationKey(profileId) {
- return String(profileId || '') === 'workbuddy-ai'
- ? 'workdaddy:theme-migration:workbuddy-ai:official-light:v1'
- : null;
-}
-
-function shouldMigrateWorkBuddyAiTheme(profileId, markerValue) {
- var key = workBuddyAiThemeMigrationKey(profileId);
- return !!key && markerValue !== '1';
-}
-
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
createBuildLifecycle: createBuildLifecycle,
@@ -240,11 +193,6 @@ if (typeof module !== 'undefined' && module.exports) {
isStashQueueItem: isStashQueueItem,
stashContentSignature: stashContentSignature,
stashContentMatches: stashContentMatches,
- resolveWorkBuddyAiConversationId: resolveWorkBuddyAiConversationId,
- workBuddyAiDraftStorageKey: workBuddyAiDraftStorageKey,
- isWorkBuddyAiComposerStore: isWorkBuddyAiComposerStore,
- workBuddyAiThemeMigrationKey: workBuddyAiThemeMigrationKey,
- shouldMigrateWorkBuddyAiTheme: shouldMigrateWorkBuddyAiTheme,
};
}
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
@@ -257,6 +205,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if ((n = document.querySelector('.wbs-root'))) n.remove();
var st = document.querySelectorAll('.wbs-stash-inline, .wbs-stash-btn, .wbs-explore-inline');
for (var i = 0; i < st.length; i++) st[i].remove();
+ var nav = document.querySelectorAll('.wbs-message-nav-root');
+ for (var ni = 0; ni < nav.length; ni++) nav[ni].remove();
var ss = document.querySelectorAll('#wbs-style');
for (var j = 0; j < ss.length; j++) ss[j].remove();
var dbg = document.querySelectorAll('#wbs-diag-badge, #wbs-debug-panel');
@@ -283,16 +233,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var CAPS = __WBS_CAPS__;
var WBS_API_TOKEN = '__WBS_API_TOKEN__';
var WBS_DIAGNOSTICS_ENABLED = __WBS_DIAGNOSTICS_ENABLED__;
- var WBS_PLATFORM = '__WBS_PLATFORM__'; // 注入时替换为 process.platform(如 'darwin'/'win32')
+ var WBS_PLATFORM = __WBS_PLATFORM__; // 注入时替换为 JSON 字符串(如 "darwin"/"win32")
+ var WBS_COMPAT = window.__wbsWorkBuddyCompat;
+ if (!WBS_COMPAT) throw new Error('WorkBuddy 兼容层未加载');
// WorkBuddy 基于 Electron,持续会话模块在 macOS/Windows 使用同一套 CDP 逻辑。
var AC_SUPPORTED = true;
- // 面板品牌名跟随 profile:workbuddy-ai 显示 WorkDaddy AI,其余显示 WorkDaddy
- var WBS_BRAND = PROFILE_ID === 'workbuddy-ai' ? 'WorkDaddy AI' : 'WorkDaddy';
- // 客户端类型判断(WorkDaddy vs WorkDaddy AI,UI/功能区分的主依据,详见 AGENTS.md「客户端类型判断」):
- // - workbuddy-ai(WorkBuddy AI 客户端)= WorkDaddy AI:输入框右下角两个插件按钮内联进
- // cr-input-toolbar__right(输入框右下角按钮组父容器)的最左侧(其他按钮左边)。
- // - 其余 profile(WorkBuddy 客户端)= WorkDaddy:两个插件按钮保持既有摆放方式不变。
+ // 客户端身份只控制真实的 profile 差异;DOM 与队列能力由 WBS_COMPAT 独立判断。
var WBS_PROFILE_IS_AI = PROFILE_ID === 'workbuddy-ai';
+ var WBS_BRAND = WBS_PROFILE_IS_AI ? 'WorkDaddy AI' : 'WorkDaddy';
// ===== 全局错误钩子:捕获渲染进程不可捕获的 error / unhandledrejection,把完整消息+栈
// 打到 daemon 日志。渲染进程级崩溃(如 An object could not be cloned)虽非 try/catch 能拦,
@@ -572,7 +520,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function findComposer() {
var mic = document.querySelector('.voice-mic-wrap');
if (!mic) {
- // AI 端(无 voice-mic-wrap):输入框特征是 [contenteditable=true],且位于视口下半部、
+ // 新版布局(无 voice-mic-wrap):输入框特征是 [contenteditable=true],且位于视口下半部、
// 可见、有尺寸(消息历史是只读渲染,不是 contenteditable=true)。取最靠底部的那个。
var all = document.querySelectorAll('[contenteditable="true"]');
var best = null, bestCy = -Infinity;
@@ -665,40 +613,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
capturedAt: new Date().toISOString(),
};
}
- function getWorkBuddyAiSelectedConversationId() {
- if (!WBS_PROFILE_IS_AI) return null;
- try {
- var nodes = document.querySelectorAll('.conversation-item[data-conversation-id]');
- var candidates = [];
- for (var i = 0; i < nodes.length; i++) {
- var child = nodes[i].firstElementChild;
- candidates.push({
- conversationId: nodes[i].getAttribute('data-conversation-id'),
- ariaSelected: nodes[i].getAttribute('aria-selected') || (child && child.getAttribute('aria-selected')),
- className: nodes[i].className,
- childClassName: child && child.className,
- });
- }
- return resolveWorkBuddyAiConversationId(candidates);
- } catch (e) {
- return null;
- }
- }
-
- // 尽量拿到当前会话 id(URL / WorkBuddy AI 选中侧栏项 / 通用激活项 / 标题兜底)
+ // 尽量拿到当前会话 id(URL / 当前布局选中会话 / 标题兜底)
function getConversationId() {
try {
var u = new URL(location.href);
var q = u.searchParams.get('conversationId') || u.searchParams.get('conversation_id');
if (q) return q;
} catch (_) {}
- var aiId = getWorkBuddyAiSelectedConversationId();
- if (aiId) return aiId;
- var sel = document.querySelector('[data-conversation-id].active,[data-conversation-id][aria-selected="true"],.conversation-item.active,[data-conversation-id][class*="active"],.conv-item.active,[class*="conversation"][class*="active"]');
- if (sel) {
- var id = sel.getAttribute('data-conversation-id') || sel.getAttribute('data-id');
- if (id) return id;
- }
+ var selectedId = WBS_COMPAT.getSelectedConversationId(document);
+ if (selectedId) return selectedId;
var any = document.querySelector('[data-conversation-id]');
if (any) return any.getAttribute('data-conversation-id');
var titleEl = document.querySelector('[class*="chat-title"],[class*="conversation-title"],[class*="ChatTitle"],[class*="chatTitle"]');
@@ -1016,14 +939,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!CAPS.stashPrompt) root.classList.add('wbs-no-stash');
root.innerHTML = [
'<div class="wbs-fab" title="' + WBS_BRAND + '">',
- '<span class="wbs-fab-sleep-dot" title="防休眠未开启"></span>',
'<span class="wbs-fab-health-dot" title="会话状态" style="display:none"></span>',
'<div class="click">',
'<span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span>',
'<button class="button up" type="button" aria-label="WorkDaddy,点击打开面板,可拖动">',
- '<span class="wbs-fab-antenna" aria-hidden="true"><span class="wbs-fab-antenna-dot"></span></span>',
- '<span class="wbs-fab-ear wbs-fab-ear-left" aria-hidden="true"></span>',
- '<span class="wbs-fab-ear wbs-fab-ear-right" aria-hidden="true"></span>',
+ '<span class="wbs-fab-antenna" aria-hidden="true"></span>',
+ '<span class="wbs-fab-antenna-dot" id="wbs-fab-sleep-light" title="允许电脑休眠(默认)"></span>',
'<div class="speak dblink"><div class="wrap"><div class="eye double-blink"></div><div class="eye double-blink"></div></div></div>',
'<div class="speak doblink"><div class="wrap"><div class="eye down"></div><div class="eye down"></div></div></div>',
'<div class="speak rblink"><div class="wrap"><div class="eye right-blink"></div><div class="eye right-blink"></div></div></div>',
@@ -1035,7 +956,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-panel">',
'<div class="wbs-head">',
'<div class="wbs-head-left">',
- '<div class="wbs-title" id="wbs-title" title="连续点击 5 次呼出元素检查">' + WBS_BRAND + '</div>',
+ '<div class="wbs-title" id="wbs-title" title="WorkDaddy">' + WBS_BRAND + '</div>',
+ '<button class="wbs-pick-btn" id="wbs-pick-btn" type="button" style="display:none" title="元素检查">🔍</button>',
'<span class="wbs-health-status" id="wbs-health-status" aria-live="polite"></span>',
'<a class="wbs-ghbtn" href="https://github.com/babygoton/WorkDaddy" target="_blank" rel="noopener" title="GitHub 仓库">',
'<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M12 .3a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.03c-3.34.73-4.04-1.61-4.04-1.61-.55-1.39-1.33-1.76-1.33-1.76-1.09-.74.08-.73.08-.73 1.2.09 1.84 1.24 1.84 1.24 1.07 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.66-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.11-3.18 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 0 1 6.01 0c2.29-1.55 3.3-1.23 3.3-1.23.65 1.66.24 2.88.12 3.18.77.84 1.23 1.91 1.23 3.22 0 4.61-2.81 5.62-5.49 5.92.43.37.82 1.1.82 2.22v3.29c0 .32.22.7.83.58A12 12 0 0 0 12 .3z"/></svg>',
@@ -1066,9 +988,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
document.body.appendChild(root);
// 不同客户端只开放明确支持的能力;保留统一面板结构可避免模式切换时布局抖动。
- // WorkDaddy AI 新版本不再暴露 WorkDaddy 主题入口;普通 WorkDaddy 仍按
- // 原有 CAPS.theme 能力决定是否显示主题页。
- if (!CAPS.theme || WBS_PROFILE_IS_AI) {
+ // 主题能力由 profile capabilities 统一控制,两个 WorkBuddy 客户端均可使用。
+ if (!CAPS.theme) {
var themeTab = root.querySelector('[data-tab="theme"]');
var themePane = root.querySelector('[data-pane="theme"]');
if (themeTab) themeTab.remove();
@@ -1165,10 +1086,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
exploreBtn.addEventListener('mouseleave', function () { exploreBtn.classList.remove('wbs-menu-closed'); });
if (isWelcomePage()) exploreBtn.style.display = 'none'; // 欢迎页无操作栏,定位没意义;其余情况由 syncStash 常驻显示
- /* ———— 会话模块(session):暂存提示词 & 快捷短语 ————
- * 状态持久化在 daemon(~/.workbuddy/settings.json 的 wbs.session 域)。
+ /* ———— 会话模块(session):暂存提示词、会话消息索引 & 快捷短语 ————
+ * 暂存提示词/快捷短语由 daemon 持久化;消息索引开关保存在渲染器 localStorage。
* stash 按钮显隐受「暂存提示词」开关影响;explore 按钮与面板选项受「快捷短语」开关/列表影响。 */
- var sessState = { stash: true, phrase: true, phrases: [], qpBatch: false, qpSel: {} };
+ var MESSAGE_NAV_ENABLED_KEY = 'workdaddy.session.messageNavigationEnabled';
+ function readMessageNavigationEnabled() {
+ try { return localStorage.getItem(MESSAGE_NAV_ENABLED_KEY) !== '0'; } catch (_) { return true; }
+ }
+ function writeMessageNavigationEnabled(enabled) {
+ try { localStorage.setItem(MESSAGE_NAV_ENABLED_KEY, enabled ? '1' : '0'); } catch (_) {}
+ }
+ var sessState = {
+ stash: true,
+ messageNav: readMessageNavigationEnabled(),
+ phrase: true,
+ phrases: [],
+ qpBatch: false,
+ qpSel: {},
+ };
var sessLastExploreSig = ''; // 面板选项渲染签名(内容未变不重建保留 tooltip 状态)
var sessLastQpSig = ''; // 增强页列表渲染签名(内容/批量模式/选中集未变不重建)
function applySessionModule(d) {
@@ -1176,12 +1111,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
sessState.stash = !!d.stashEnabled;
sessState.phrase = !!d.phraseEnabled;
sessState.phrases = Array.isArray(d.phrases) ? d.phrases : [];
- // 同步 UI:两个开关 + 快捷短语列表区显隐
+ // 同步 UI:三个开关 + 快捷短语列表区显隐
var pane0 = enhancePane;
var swS = pane0 && pane0.querySelector('#wbs-sess-stash');
+ var swN = pane0 && pane0.querySelector('#wbs-sess-message-nav');
var swP = pane0 && pane0.querySelector('#wbs-sess-phrase');
var area = pane0 && pane0.querySelector('#wbs-qp-area');
if (swS) swS.checked = !!sessState.stash;
+ if (swN) swN.checked = !!sessState.messageNav;
if (swP) swP.checked = !!sessState.phrase;
if (area) area.style.display = sessState.phrase ? '' : 'none';
renderQpList();
@@ -1223,11 +1160,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var barEl = pane1.querySelector('#wbs-qp-batchbar');
var countEl = pane1.querySelector('#wbs-qp-batch-count');
var batchBtn = pane1.querySelector('#wbs-qp-batch');
+ var importBtn = pane1.querySelector('#wbs-qp-import');
+ var addBtn = pane1.querySelector('#wbs-qp-add');
var allBtn = pane1.querySelector('#wbs-qp-checkall');
+ var selectedCount = Object.keys(sessState.qpSel).length;
if (barEl) barEl.style.display = sessState.qpBatch ? 'inline-flex' : 'none';
if (batchBtn) batchBtn.style.display = (sessState.qpBatch || !phrases.length) ? 'none' : '';
- if (countEl) countEl.textContent = '已选 ' + Object.keys(sessState.qpSel).length;
- if (allBtn) allBtn.textContent = (sessState.qpBatch && phrases.length && Object.keys(sessState.qpSel).length === phrases.length) ? '取消全选' : '全选';
+ if (importBtn) importBtn.style.display = sessState.qpBatch ? 'none' : '';
+ if (addBtn) addBtn.style.display = sessState.qpBatch ? 'none' : '';
+ if (countEl) countEl.textContent = '已选 ' + selectedCount;
+ if (allBtn) allBtn.textContent = (sessState.qpBatch && phrases.length && selectedCount === phrases.length) ? '取消全选' : '全选';
+ ['#wbs-qp-copy', '#wbs-qp-export', '#wbs-qp-batch-del'].forEach(function (selector) {
+ var action = pane1.querySelector(selector);
+ if (action) action.style.display = selectedCount ? '' : 'none';
+ });
if (!phrases.length) {
listEl.innerHTML = '<div class="wbs-qp-empty">暂无快捷短语,点击「+ 新增」添加</div>';
return;
@@ -1415,7 +1361,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function findActionRow() {
var mic = document.querySelector('.voice-mic-wrap');
if (mic) return mic.parentElement;
- // AI 端(无 voice-mic-wrap):从输入框向上找最近的含按钮容器(操作栏),
+ // 新版布局(无 voice-mic-wrap):从输入框向上找最近的含按钮容器(操作栏),
// 仅用于发送按钮状态监听,找不到不影响暂存按钮本身。
var ed = findComposer();
if (!ed) return null;
@@ -1432,38 +1378,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
return null;
}
- // AI 端输入框右下角按钮组。新布局(WorkBuddy AI teams 新界面)用户 DOM 路径:
+ // 新版输入框右下角按钮组路径:
// ... > div.conversation-input > div.cr-theme > div.cr-theme.cr-input-box >
// div.cr-input-box__main > div.cr-input-container-wrapper > div.cr-input-container >
// div.cr-input-toolbar > div.cr-input-toolbar__right
// cr-input-toolbar__right 即输入框右下角按钮组的父容器(上下文用量/增强/模型/发送)。
- // WorkDaddy AI 客户端:两个插件按钮(暂存提示词、快捷短语)内联插到该容器最左侧(其他按钮左边)。
+ // 新版布局:两个插件按钮(暂存提示词、快捷短语)内联插到该容器最左侧(其他按钮左边)。
// 老布局兜底:..._input-area-container_ > ... > div._spaceBetween_._inputBottom_ > div._item_._gapLarge_
//(_inputBottom_ 下有两个按钮组:左侧工具组 class 含 _selector_、右侧发送按钮组 class 含 _gapLarge_,
// 必须命中右侧 _gapLarge_ 组,排除 _selector_ 组)
- function findAiToolbar() {
- // 新布局优先(仅 WorkDaddy AI 客户端启用;普通 WorkBuddy 客户端仍保持既有摆放)
- if (WBS_PROFILE_IS_AI) {
- var cr = document.querySelector('div.cr-input-toolbar__right');
- if (cr) {
- var crR = cr.getBoundingClientRect();
- if (crR.width > 0 && crR.height > 0) return cr;
- }
- }
- var cands = document.querySelectorAll(
- '[class*="_inputBottom_"] > [class*="_gapLarge_"],' +
- '[class*="_inputBottom_"] > [class*="_gap_"]:not([class*="_selector_"]),' +
- '[class*="_inputBottom_"] > [class*="_item_"]:not([class*="_selector_"])'
- );
- var best = null, bestLeft = -Infinity;
- for (var i = 0; i < cands.length; i++) {
- var r = cands[i].getBoundingClientRect();
- if (r.width <= 0 || r.height <= 0) continue;
- // 同一行内取最靠右的按钮组(发送按钮组);行位置应贴近输入框底部
- if (r.left > bestLeft) { bestLeft = r.left; best = cands[i]; }
- }
- return best;
- }
// 操作栏最右侧的「圆形可点击」元素才是发送按钮(左侧还可能有增强提示词/停止等圆形按钮)
function findSendButton() {
var row = findActionRow();
@@ -1496,13 +1419,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (/(^|[\s_])disabled($|[\s_])/.test(cls) || cls.indexOf('is-disabled') >= 0 || cls.indexOf('ant-btn-disabled') >= 0) return true;
return false;
}
- // 关键:CN 端用 position: fixed 绝对定位到发送按钮坐标旁,挂在 document.body 下,
- // 不插入到操作栏 row.children 里——避开 React reconciliation 丢弃外部节点的问题。
- // 客户端类型判断(见 AGENTS.md「客户端类型判断」)决定了摆放方式:
- // - WorkDaddy 普通客户端(voice-mic-wrap 存在):固定定位,保持既有位置。
- // - WorkDaddy AI(workbuddy-ai,无 voice-mic-wrap):内联插入输入框右下角按钮组
- // cr-input-toolbar__right 的最左侧(其他按钮左边,用户要求的摆放方式),
- // fixed 定位由 CSS 类覆盖为静态参与 flex。
+ // 新版或旧版内联工具栏存在时放进工具栏;带 voice-mic-wrap 的旧布局保持固定定位。
function insertStash() {
// 重新注入脚本时先移除旧版按钮(避免旧 SVG 图标/样式残留)
var oldBtn = document.querySelector('.wbs-stash-inline');
@@ -1511,7 +1428,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (oldExp && oldExp !== exploreBtn) oldExp.remove();
var mic0 = document.querySelector('.voice-mic-wrap');
if (!mic0) {
- var row0 = findAiToolbar();
+ var toolbarMatch = WBS_COMPAT.findComposerToolbar(document);
+ var row0 = toolbarMatch && toolbarMatch.element;
if (row0) {
stashBtn.classList.add('wbs-stash-inline-inline');
exploreBtn.classList.add('wbs-stash-inline-inline');
@@ -1572,7 +1490,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
} catch (e) {}
}
function positionStash() {
- // AI 端没有 voice-mic-wrap:操作栏按钮行位于输入框正下方(与输入框同祖先容器)。
+ // 新版布局没有 voice-mic-wrap:操作栏按钮行位于输入框正下方(与输入框同祖先容器)。
// 取该行最左按钮的左边为锚,top 与按钮行对齐——与 CN 端「操作栏最左」语义一致。
var mic = document.querySelector('.voice-mic-wrap');
if (!mic) {
@@ -1718,9 +1636,450 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (sid) lastStashSessionId = sid;
} catch (e) {}
}
+
+ // 会话消息导航:完整索引来自 controller.messageStore,DOM 仅用于判断当前可见位置。
+ function createMessageNavigation() {
+ var surface = null;
+ var adapter = null;
+ var messageStore = null;
+ var unsubscribeStore = null;
+ var root = null;
+ var rail = null;
+ var tooltip = null;
+ var turns = [];
+ var buttons = Object.create(null);
+ var activeId = null;
+ var resizeObserver = null;
+ var scrollElement = null;
+ var syncTimer = null;
+ var tooltipTimer = null;
+ var activeFrame = null;
+ var dragPointerId = null;
+ var dragLastIndex = -1;
+ var suppressPointerClick = false;
+ var suppressClickTimer = null;
+ var renderedSignature = '';
+ var lastMessages = null;
+ var lastVersion = null;
+ var hidden = true;
+ var disposed = false;
+
+ function messageText(message, limit) {
+ var content = message && message.content;
+ var blocks = Array.isArray(content) ? content : [];
+ var parts = [];
+ for (var i = 0; i < blocks.length; i++) {
+ var block = blocks[i];
+ var type = String(block && block.type || '').toLowerCase();
+ if (type !== 'text' && type !== 'markdown') continue;
+ var text = block && (block.text != null ? block.text : block.content);
+ if (typeof text === 'string' && text) parts.push(text);
+ }
+ var value = parts.join(' ');
+ value = value.replace(/\s+/g, ' ').trim();
+ if (limit && value.length > limit) return value.slice(0, limit - 1) + '…';
+ return value;
+ }
+
+ function ensureRoot() {
+ if (root && root.isConnected) return;
+ root = document.createElement('div');
+ root.className = 'wbs-message-nav-root';
+ renderedSignature = '';
+ root.setAttribute('aria-label', '会话消息导航');
+ rail = el('div', 'wbs-message-nav-rail');
+ rail.setAttribute('role', 'navigation');
+ rail.setAttribute('aria-label', '会话消息索引');
+ tooltip = document.createElement('div');
+ tooltip.className = 'wbs-message-nav-tooltip';
+ tooltip.id = 'wbs-message-nav-tooltip';
+ tooltip.setAttribute('role', 'tooltip');
+ tooltip.hidden = true;
+ root.appendChild(rail);
+ root.appendChild(tooltip);
+ document.body.appendChild(root);
+ listen(root, 'pointerover', onPointerOver);
+ listen(root, 'pointerout', onPointerOut);
+ listen(root, 'focusin', onFocusIn);
+ listen(root, 'focusout', onFocusOut);
+ listen(root, 'click', onClick);
+ listen(root, 'keydown', onKeyDown);
+ listen(root, 'pointerdown', onNavPointerDown);
+ listen(root, 'pointermove', onNavPointerMove);
+ listen(root, 'pointerup', onNavPointerUp);
+ listen(root, 'pointercancel', onNavPointerCancel);
+ listen(root, 'lostpointercapture', onNavPointerCancel);
+ }
+
+ function position() {
+ if (!root || !surface || !surface.scrollElement || hidden) return;
+ var rect = surface.scrollElement.getBoundingClientRect();
+ if (!rect || rect.width <= 0 || rect.height <= 0) {
+ root.style.display = 'none';
+ return;
+ }
+ root.style.display = 'block';
+ var railChrome = 14;
+ var desiredRailHeight = Math.max(36, turns.length * 12 + railChrome);
+ var railHeight = Math.min(desiredRailHeight, rect.height);
+ var markerHeight = Math.max(1, Math.min(12,
+ (railHeight - Math.min(railChrome, railHeight)) / Math.max(1, turns.length)));
+ root.style.height = railHeight + 'px';
+ root.style.top = (rect.top + (rect.height - railHeight) / 2) + 'px';
+ var left = rect.left + 12;
+ root.style.left = Math.max(8, Math.min(window.innerWidth - 28, left)) + 'px';
+ root.style.setProperty('--wbs-message-nav-marker-height', markerHeight + 'px');
+ root.style.setProperty('--wbs-message-nav-tooltip-max', Math.max(160, Math.min(320, window.innerWidth * 0.32)) + 'px');
+ }
+
+ function setActive(id) {
+ activeId = id || null;
+ Object.keys(buttons).forEach(function (key) {
+ var button = buttons[key];
+ if (!button) return;
+ if (key === activeId) button.setAttribute('aria-current', 'true');
+ else button.removeAttribute('aria-current');
+ button.classList.toggle('is-active', key === activeId);
+ });
+ }
+
+ function hideTooltip(immediate) {
+ if (tooltipTimer) { clearTimeout(tooltipTimer); tooltipTimer = null; }
+ var close = function () {
+ if (!tooltip) return;
+ tooltip.hidden = true;
+ tooltip.classList.remove('is-visible');
+ };
+ if (immediate) close();
+ else tooltipTimer = setBuildTimeout(close, 90);
+ }
+
+ function showTooltip(turn, button) {
+ if (!tooltip || !turn || !button) return;
+ if (tooltipTimer) { clearTimeout(tooltipTimer); tooltipTimer = null; }
+ tooltip.textContent = '';
+ var prompt = el('div', 'wbs-message-nav-prompt', messageText(turn.userMessage, 240) || '用户消息');
+ tooltip.appendChild(prompt);
+ var response = messageText(turn.assistantMessage, 320);
+ if (response) tooltip.appendChild(el('div', 'wbs-message-nav-response', response));
+ tooltip.hidden = false;
+ tooltip.classList.add('is-visible');
+ var buttonRect = button.getBoundingClientRect();
+ var rootRect = root.getBoundingClientRect();
+ var leftSpace = Math.max(0, rootRect.left - 12);
+ var rightSpace = Math.max(0, window.innerWidth - rootRect.right - 12);
+ var side = rightSpace >= leftSpace ? 'right' : 'left';
+ var available = side === 'right' ? rightSpace : leftSpace;
+ var preferred = Math.max(160, Math.min(320, window.innerWidth * 0.32));
+ tooltip.style.width = Math.max(120, Math.min(preferred, available)) + 'px';
+ var top = buttonRect.top - rootRect.top + buttonRect.height / 2;
+ var tooltipHeight = tooltip.getBoundingClientRect().height || 80;
+ tooltip.style.top = Math.max(tooltipHeight / 2, Math.min(rootRect.height - tooltipHeight / 2, top)) + 'px';
+ tooltip.classList.toggle('is-left', side === 'left');
+ tooltip.classList.toggle('is-right', side === 'right');
+ }
+
+ function render() {
+ if (!rail) return;
+ rail.textContent = '';
+ buttons = Object.create(null);
+ for (var i = 0; i < turns.length; i++) {
+ var turn = turns[i];
+ var button = el('button', 'wbs-message-nav-marker');
+ button.type = 'button';
+ button.setAttribute('data-wbs-message-nav-id', turn.id);
+ button.setAttribute('aria-label', '定位到第 ' + (i + 1) + ' 条用户消息');
+ button.setAttribute('aria-describedby', tooltip.id);
+ button.appendChild(el('span', 'wbs-message-nav-dot'));
+ rail.appendChild(button);
+ buttons[turn.id] = button;
+ }
+ setActive(activeId || (turns[0] && turns[0].id));
+ }
+
+ function updateActive() {
+ if (!surface || !turns.length) return;
+ var viewport = surface.viewportElement.getBoundingClientRect();
+ var frames = surface.conversationElement.querySelectorAll('.cr-document__virtual-item[data-index]');
+ var visibleMessageIndex = -1;
+ var bestDistance = Infinity;
+ for (var i = 0; i < frames.length; i++) {
+ var rect = frames[i].getBoundingClientRect();
+ if (!rect) continue;
+ var distance = Math.abs(rect.top - viewport.top - 28);
+ if (rect.top <= viewport.bottom + 20 && distance < bestDistance) {
+ visibleMessageIndex = Number(frames[i].getAttribute('data-index'));
+ bestDistance = distance;
+ }
+ }
+ var best = turns[0];
+ for (var ti = 0; ti < turns.length; ti++) {
+ if (turns[ti].messageIndex <= visibleMessageIndex) best = turns[ti];
+ else break;
+ }
+ setActive(best && best.id);
+ }
+
+ function scheduleActive() {
+ if (activeFrame != null) return;
+ activeFrame = requestAnimationFrame(function () {
+ activeFrame = null;
+ updateActive();
+ });
+ }
+
+ function refreshFromStore(state) {
+ if (!sessState.messageNav || !messageStore || disposed) return;
+ var messageState = state && Array.isArray(state.messages) ? state : messageStore.getState();
+ if (!messageState || !Array.isArray(messageState.messages)) return;
+ if (messageState.messages === lastMessages && messageState.version === lastVersion) return;
+ lastMessages = messageState.messages;
+ lastVersion = messageState.version;
+ turns = WBS_COMPAT.collectMessageNavigationTurnsFromMessages(messageState.messages);
+ hidden = turns.length <= 1;
+ ensureRoot();
+ if (hidden) {
+ root.style.display = 'none';
+ hideTooltip(true);
+ return;
+ }
+ var signature = turns.map(function (turn) { return turn.id; }).join('\u001f');
+ if (signature !== renderedSignature) {
+ renderedSignature = signature;
+ render();
+ }
+ position();
+ scheduleActive();
+ }
+
+ function unbindStore() {
+ if (unsubscribeStore) {
+ try { unsubscribeStore(); } catch (_) {}
+ }
+ unsubscribeStore = null;
+ messageStore = null;
+ adapter = null;
+ lastMessages = null;
+ lastVersion = null;
+ turns = [];
+ renderedSignature = '';
+ }
+
+ function bindAdapter(nextAdapter) {
+ var nextStore = nextAdapter && nextAdapter.messageStore;
+ if (adapter && nextAdapter && messageStore === nextStore &&
+ adapter.controller === nextAdapter.controller &&
+ adapter.navigationHandle === nextAdapter.navigationHandle) return;
+ unbindStore();
+ adapter = nextAdapter;
+ messageStore = nextStore || null;
+ if (!messageStore) return;
+ unsubscribeStore = messageStore.subscribe(function (state, previousState) {
+ if (previousState && state && state.messages === previousState.messages &&
+ state.version === previousState.version) return;
+ refreshFromStore(state);
+ });
+ refreshFromStore(messageStore.getState());
+ }
+
+ function sync() {
+ if (disposed || !sessState.messageNav) return;
+ if (syncTimer) return;
+ syncTimer = setBuildTimeout(function () {
+ syncTimer = null;
+ if (!sessState.messageNav) return;
+ var nextSurface = WBS_COMPAT.findMessageNavigationSurface(document);
+ if (!nextSurface) {
+ hidden = true;
+ surface = null;
+ if (root) root.style.display = 'none';
+ if (resizeObserver) { resizeObserver.disconnect(); resizeObserver = null; }
+ if (scrollElement) { scrollElement.removeEventListener('scroll', scheduleActive); scrollElement = null; }
+ unbindStore();
+ return;
+ }
+ var conversationChanged = nextSurface.conversationElement !== (surface && surface.conversationElement);
+ var scrollChanged = nextSurface.scrollElement !== (surface && surface.scrollElement);
+ surface = nextSurface;
+ var currentConversationId = surface.conversationElement.getAttribute &&
+ surface.conversationElement.getAttribute('data-root-id');
+ var boundConversationId = adapter && adapter.controller && adapter.controller.conversationId;
+ if (conversationChanged || scrollChanged || !adapter ||
+ (currentConversationId && String(currentConversationId) !== String(boundConversationId || ''))) {
+ bindAdapter(WBS_COMPAT.findMessageNavigationAdapter(document, surface));
+ }
+ if (!adapter) {
+ hidden = true;
+ if (root) root.style.display = 'none';
+ return;
+ }
+ position();
+ scheduleActive();
+ if ((conversationChanged || scrollChanged) && resizeObserver) {
+ resizeObserver.disconnect();
+ resizeObserver = null;
+ }
+ if (typeof ResizeObserver !== 'undefined' && !resizeObserver) {
+ resizeObserver = new ResizeObserver(position);
+ resizeObserver.observe(surface.scrollElement);
+ }
+ if (scrollElement !== surface.scrollElement) {
+ if (scrollElement) scrollElement.removeEventListener('scroll', scheduleActive);
+ scrollElement = surface.scrollElement;
+ if (scrollElement) scrollElement.addEventListener('scroll', scheduleActive, { passive: true });
+ }
+ }, 40);
+ }
+
+ function setEnabled(enabled) {
+ if (enabled) {
+ sync();
+ return;
+ }
+ if (syncTimer) { clearTimeout(syncTimer); syncTimer = null; }
+ if (dragPointerId != null) finishNavDrag({ pointerId: dragPointerId }, true);
+ hidden = true;
+ hideTooltip(true);
+ if (root) root.style.display = 'none';
+ if (resizeObserver) { resizeObserver.disconnect(); resizeObserver = null; }
+ if (scrollElement) { scrollElement.removeEventListener('scroll', scheduleActive); scrollElement = null; }
+ unbindStore();
+ }
+
+ function turnForButton(button) {
+ var id = button && button.getAttribute('data-wbs-message-nav-id');
+ for (var i = 0; i < turns.length; i++) if (turns[i].id === id) return turns[i];
+ return null;
+ }
+ function navigateToTurn(turn, preview) {
+ if (!turn || !adapter || !adapter.navigationHandle) return false;
+ try {
+ adapter.navigationHandle.scrollToMessage(turn.messageId, { behavior: 'auto', block: 'start' });
+ } catch (_) { return false; }
+ setActive(turn.id);
+ var button = buttons[turn.id];
+ if (preview && button) showTooltip(turn, button);
+ else hideTooltip(true);
+ return true;
+ }
+ function dragIndexAt(clientY) {
+ if (!rail || !turns.length || !rail.firstElementChild || !rail.lastElementChild) return -1;
+ var firstRect = rail.firstElementChild.getBoundingClientRect();
+ var lastRect = rail.lastElementChild.getBoundingClientRect();
+ var firstCenter = firstRect.top + firstRect.height / 2;
+ var lastCenter = lastRect.top + lastRect.height / 2;
+ if (lastCenter <= firstCenter) return 0;
+ var ratio = (clientY - firstCenter) / (lastCenter - firstCenter);
+ ratio = Math.max(0, Math.min(1, ratio));
+ return Math.round(ratio * (turns.length - 1));
+ }
+ function onNavPointerDown(event) {
+ if (dragPointerId != null || event.button !== 0) return;
+ var button = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
+ var turn = turnForButton(button);
+ if (!button || !turn) return;
+ dragPointerId = event.pointerId;
+ dragLastIndex = Array.prototype.indexOf.call(rail.children, button);
+ root.classList.add('is-dragging');
+ try { rail.setPointerCapture(event.pointerId); } catch (_) {}
+ navigateToTurn(turn, true);
+ event.preventDefault();
+ }
+ function onNavPointerMove(event) {
+ if (dragPointerId == null || event.pointerId !== dragPointerId) return;
+ var nextIndex = dragIndexAt(event.clientY);
+ if (nextIndex < 0 || nextIndex === dragLastIndex) return;
+ dragLastIndex = nextIndex;
+ navigateToTurn(turns[nextIndex], true);
+ event.preventDefault();
+ }
+ function finishNavDrag(event, cancelled) {
+ if (dragPointerId == null || (event.pointerId != null && event.pointerId !== dragPointerId)) return;
+ var pointerId = dragPointerId;
+ dragPointerId = null;
+ dragLastIndex = -1;
+ if (root) root.classList.remove('is-dragging');
+ try {
+ if (rail && rail.hasPointerCapture(pointerId)) rail.releasePointerCapture(pointerId);
+ } catch (_) {}
+ if (cancelled) {
+ suppressPointerClick = false;
+ hideTooltip(true);
+ return;
+ }
+ suppressPointerClick = true;
+ if (suppressClickTimer) clearTimeout(suppressClickTimer);
+ suppressClickTimer = setBuildTimeout(function () {
+ suppressPointerClick = false;
+ suppressClickTimer = null;
+ }, 400);
+ hideTooltip(false);
+ }
+ function onNavPointerUp(event) { finishNavDrag(event, false); }
+ function onNavPointerCancel(event) { finishNavDrag(event, true); }
+ function onPointerOver(event) {
+ if (dragPointerId != null) return;
+ var button = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
+ if (button) showTooltip(turnForButton(button), button);
+ }
+ function onPointerOut(event) {
+ if (dragPointerId != null) return;
+ var from = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
+ var to = event.relatedTarget && event.relatedTarget.closest ? event.relatedTarget.closest('.wbs-message-nav-marker') : null;
+ if (from && from !== to) hideTooltip(false);
+ }
+ function onFocusIn(event) {
+ var button = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
+ if (button) showTooltip(turnForButton(button), button);
+ }
+ function onFocusOut(event) {
+ if (dragPointerId != null) return;
+ if (!event.relatedTarget || !root.contains(event.relatedTarget)) hideTooltip(false);
+ }
+ function onClick(event) {
+ if (suppressPointerClick && event.detail !== 0) {
+ suppressPointerClick = false;
+ if (suppressClickTimer) { clearTimeout(suppressClickTimer); suppressClickTimer = null; }
+ event.preventDefault();
+ return;
+ }
+ var button = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
+ var turn = turnForButton(button);
+ if (!button || !turn) return;
+ navigateToTurn(turn, false);
+ }
+ function onKeyDown(event) {
+ if (event.key === 'Escape') { hideTooltip(true); return; }
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
+ var current = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
+ if (!current) return;
+ var index = Array.prototype.indexOf.call(rail.children, current);
+ var next = event.key === 'ArrowDown' ? index + 1 : index - 1;
+ if (next >= 0 && next < rail.children.length) { event.preventDefault(); rail.children[next].focus(); }
+ }
+ function onWindowChange() { position(); scheduleActive(); }
+
+ listen(window, 'resize', onWindowChange);
+ listen(window, 'scroll', onWindowChange, true);
+ sync();
+ registerDisposer(function () {
+ disposed = true;
+ if (syncTimer) clearTimeout(syncTimer);
+ if (tooltipTimer) clearTimeout(tooltipTimer);
+ if (suppressClickTimer) clearTimeout(suppressClickTimer);
+ if (activeFrame != null) cancelAnimationFrame(activeFrame);
+ if (resizeObserver) resizeObserver.disconnect();
+ if (scrollElement) scrollElement.removeEventListener('scroll', scheduleActive);
+ unbindStore();
+ if (root) root.remove();
+ });
+ return { sync: sync, setEnabled: setEnabled };
+ }
+ var messageNavigation = createMessageNavigation();
function onDomChange() {
if (!alive) return;
guardSessionChange();
+ if (messageNavigation) messageNavigation.sync();
scheduleFabPos();
watchRow();
syncStash(); // 页面切换(欢迎页↔聊天页)后立即重算暂存按钮显隐
@@ -1863,19 +2222,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// ===== 暂存提示词:优先入队到 WorkBuddy 的 message queue(完整富文本 + 暂停自动发送)=====
// 通过 React fiber 提取 adapter(含 enqueueConversationMessageQueueItem / pauseConversationMessageQueue)。
- // 客户端差异(见 AGENTS.md「客户端类型判断」):
- // - WorkDaddy 普通客户端(workbuddy-cn 等):队列方法直接挂在 props 的 adapter 对象上,
+ // 布局代际差异:
+ // - 旧版布局:队列方法直接挂在 props 的 adapter 对象上,
// 从 voice-mic-wrap/_cbChat_/chat-container 等旧根向上走 fiber。
- // - WorkDaddy AI(workbuddy-ai,teams 新布局):官方队列包装方法位于 props.adapter 的原型链,
+ // - 新版布局:官方队列包装方法位于 props.adapter 的原型链,
// 内部负责 _notifyQueueUpdate 刷新官方队列面板;adapter.sessionsResource 只是底层透传,不能使用。
// 新布局已无 voice-mic-wrap/_cbChat_/chat-container 旧根 → 用 DFS 全树找 adapter,
- // 包一层与旧接口同名的适配层;会话 id 优先 adapter 字段,再取 AI 侧栏选中项。
- var aiOptimisticQueueIds = {};
- function syncWorkBuddyAiQueueSnapshot(sessionId, snapshot) {
- if (!WBS_PROFILE_IS_AI || !sessionId || !snapshot ||
+ // 包一层与旧接口同名的适配层;会话 id 优先 adapter 字段,再按新版/旧版 DOM 查找。
+ var modernOptimisticQueueIds = {};
+ function syncModernQueueSnapshot(sessionId, snapshot) {
+ if (!WBS_COMPAT.isModernQueueAdapter(window.__wbsAdapter) || !sessionId || !snapshot ||
(!Array.isArray(snapshot.items) && !snapshot.__wbsOptimistic)) return false;
try {
- // WorkBuddy AI 新版队列组件订阅 ConversationController.promptQueue store,
+ // 新版队列组件订阅 ConversationController.promptQueue store,
// 不直接订阅 adapter._notifyQueueUpdate。把官方 RPC 返回的真实快照同步给当前会话 store。
var roots = [
document.querySelector('.cr-document[data-root-id="' + String(sessionId).replace(/"/g, '\\"') + '"]'),
@@ -1909,11 +2268,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
previewText: normalizeQueueText(snapshot.__wbsOptimistic),
__wbsOptimistic: true,
};
- aiOptimisticQueueIds[sessionId] = String(optimistic.id);
+ modernOptimisticQueueIds[sessionId] = String(optimistic.id);
queueItems = currentItems.concat([optimistic]);
}
if (!Array.isArray(queueItems)) return false;
- // AI 5.4 在 RPC 尚未完成/重连时可能返回不带 runtime/version 的空快照。
+ // 新版 5.4 在 RPC 尚未完成/重连时可能返回不带 runtime/version 的空快照。
// 这不是“队列已清空”的确认,必须在更新 store 或 manager 镜像前直接丢弃。
if (queueItems.length === 0 && Array.isArray(currentItems) && currentItems.length > 0 &&
snapshot.runtime == null && snapshot.version == null && snapshot.updatedAt == null) {
@@ -1933,14 +2292,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
manager.delete = function (itemId) {
var adapter = window.__wbsAdapter;
if (!adapter || typeof adapter.removeConversationMessageQueueItem !== 'function') {
- return Promise.reject(new Error('WorkBuddy AI 队列删除接口不可用'));
+ return Promise.reject(new Error('WorkBuddy 队列删除接口不可用'));
}
return Promise.resolve(adapter.removeConversationMessageQueueItem(sessionId, itemId));
};
manager.sendNow = function (itemId) {
var adapter = window.__wbsAdapter;
if (!adapter || typeof adapter.sendConversationMessageQueueItemNow !== 'function') {
- return Promise.reject(new Error('WorkBuddy AI 队列立即发送接口不可用'));
+ return Promise.reject(new Error('WorkBuddy 队列立即发送接口不可用'));
}
return Promise.resolve(adapter.sendConversationMessageQueueItemNow(sessionId, itemId));
};
@@ -1954,7 +2313,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
items.splice(targetIndex, 0, moved);
var orderedIds = items.map(function (item) { return item && item.id; }).filter(Boolean);
if (!adapter || typeof adapter.reorderConversationMessageQueueItems !== 'function') {
- return Promise.reject(new Error('WorkBuddy AI 队列排序接口不可用'));
+ return Promise.reject(new Error('WorkBuddy 队列排序接口不可用'));
}
return Promise.resolve(adapter.reorderConversationMessageQueueItems(sessionId, orderedIds));
};
@@ -1964,7 +2323,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (store && typeof store.setPromptQueue === 'function') {
store.setPromptQueue(queueItems);
controller.promptQueue.emitQueueUpdate();
- if (!snapshot.__wbsOptimistic) delete aiOptimisticQueueIds[sessionId];
+ if (!snapshot.__wbsOptimistic) delete modernOptimisticQueueIds[sessionId];
return true;
}
}
@@ -1977,21 +2336,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return false;
}
- function dropWorkBuddyAiOptimisticItem(sessionId) {
- if (!sessionId || !aiOptimisticQueueIds[sessionId]) return Promise.resolve();
+ function dropModernOptimisticItem(sessionId) {
+ if (!sessionId || !modernOptimisticQueueIds[sessionId]) return Promise.resolve();
var adapter = window.__wbsAdapter;
if (!adapter || typeof adapter.getConversationMessageQueue !== 'function') return Promise.resolve();
- var id = aiOptimisticQueueIds[sessionId];
+ var id = modernOptimisticQueueIds[sessionId];
return Promise.resolve(adapter.getConversationMessageQueue(sessionId)).then(function (snapshot) {
if (snapshot && Array.isArray(snapshot.items)) {
snapshot.items = snapshot.items.filter(function (item) { return String(item && item.id) !== String(id); });
- syncWorkBuddyAiQueueSnapshot(sessionId, snapshot);
+ syncModernQueueSnapshot(sessionId, snapshot);
}
- delete aiOptimisticQueueIds[sessionId];
- }).catch(function () { delete aiOptimisticQueueIds[sessionId]; });
+ delete modernOptimisticQueueIds[sessionId];
+ }).catch(function () { delete modernOptimisticQueueIds[sessionId]; });
}
- function getWorkBuddyAiQueueSnapshot(adapter, sessionId, preferred) {
+ function getModernQueueSnapshot(adapter, sessionId, preferred) {
if (preferred && Array.isArray(preferred.items) &&
(preferred.items.length > 0 || preferred.runtime != null || preferred.version != null || preferred.updatedAt != null)) {
return Promise.resolve(preferred);
@@ -2010,131 +2369,61 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 缓存校验:adapter 的官方包装方法必须仍在(切账号/重挂载后旧实例可能失效,需重新查找)
if (window.__wbsAdapter && typeof window.__wbsAdapter.enqueueConversationMessageQueueItem === 'function' &&
typeof window.__wbsAdapter.pauseConversationMessageQueue === 'function') return window.__wbsAdapter;
- // WorkDaddy AI(workbuddy-ai):只包装顶层官方 adapter,确保入队/暂停后触发 _notifyQueueUpdate。
- if (WBS_PROFILE_IS_AI) {
- var ai = findAiSessionsAdapter();
- if (ai) {
- var target = ai.adapter;
- var shim = {};
- ['enqueueConversationMessageQueueItem', 'pauseConversationMessageQueue', 'resumeConversationMessageQueue',
- 'sendConversationMessageQueueItemNow', 'getConversationMessageQueue', 'getQueueState',
- 'activateConversationMessageQueue', 'removeConversationMessageQueueItem',
- 'reorderConversationMessageQueueItems'].forEach(function (m) {
- if (typeof target[m] === 'function') {
- shim[m] = function () {
- var args = Array.prototype.slice.call(arguments);
- var sessionId = args[0];
- var result = target[m].apply(target, args);
- // 所有会返回队列 snapshot 的操作都同步 UI store;无 snapshot 的查询不产生副作用。
- return Promise.resolve(result).then(function (snapshot) {
- syncWorkBuddyAiQueueSnapshot(sessionId, snapshot);
- return snapshot;
- });
- };
- }
- });
- // WorkBuddy AI 的 adapter.currentActiveSessionId 在当前版本为空;侧栏选中项
- // .conversation-item[data-conversation-id] 才是队列 RPC 所需会话 id。
- // cr-self-message/data-user-message-id 与 cr-agent/data-message-id 的 req-* 是消息 id,不能使用。
- Object.defineProperty(shim, 'currentActiveSessionId', {
- enumerable: true,
- configurable: true,
- get: function () {
- try {
- if (ai.adapter && ai.adapter.currentActiveSessionId) return ai.adapter.currentActiveSessionId;
- var selectedId = getWorkBuddyAiSelectedConversationId();
- if (selectedId) return selectedId;
- var cd = document.querySelector('.cr-document[data-root-id]');
- if (cd) return cd.getAttribute('data-root-id') || null;
- } catch (e) {}
- return null;
- },
- });
- window.__wbsAdapter = shim;
- return shim;
- }
- }
- var roots = [document.querySelector('.voice-mic-wrap'), document.querySelector('[class*="_cbChat_"]'), document.querySelector('.chat-container')];
- for (var ri = 0; ri < roots.length; ri++) {
- var el = roots[ri];
- if (!el) continue;
- var node = el;
- for (var up = 0; up < 30 && node; up++) {
- var fk = Object.keys(node).find(function (k) { return k.indexOf('__reactFiber') === 0; });
- if (fk) {
- var cur = node[fk], seen = 0;
- while (cur && seen < 150) {
- var p = cur.memoizedProps;
- if (p && typeof p === 'object') {
- for (var pk in p) {
- var v = p[pk];
- if (v && typeof v === 'object' && typeof v.enqueueConversationMessageQueueItem === 'function') {
- window.__wbsAdapter = v;
- return v;
- }
- }
- }
- cur = cur.return; seen++;
- }
- }
- node = node.parentElement;
+ var found = WBS_COMPAT.findQueueAdapter(document);
+ if (!found || !found.adapter) return null;
+ if (found.kind !== 'modern') {
+ window.__wbsAdapter = WBS_COMPAT.markQueueAdapter(found.adapter, found.kind);
+ return window.__wbsAdapter;
+ }
+
+ // 新版顶层 adapter 的方法位于原型链,并负责通知官方队列面板。兼容层只负责发现,
+ // 此处包装返回值,把真实 snapshot 同步到当前 ConversationController store。
+ var target = found.adapter;
+ var shim = {};
+ ['enqueueConversationMessageQueueItem', 'pauseConversationMessageQueue', 'resumeConversationMessageQueue',
+ 'sendConversationMessageQueueItemNow', 'getConversationMessageQueue', 'getQueueState',
+ 'activateConversationMessageQueue', 'removeConversationMessageQueueItem',
+ 'reorderConversationMessageQueueItems'].forEach(function (m) {
+ if (typeof target[m] === 'function') {
+ shim[m] = function () {
+ var args = Array.prototype.slice.call(arguments);
+ var sessionId = args[0];
+ var result = target[m].apply(target, args);
+ return Promise.resolve(result).then(function (snapshot) {
+ syncModernQueueSnapshot(sessionId, snapshot);
+ return snapshot;
+ });
+ };
}
- }
- return null;
- }
- // WorkDaddy AI:DFS 渲染树找「props.adapter 带队列接口」的官方 adapter(新布局无旧根可走)。
- // 关键(实测):官方 adapter 是类实例,enqueue/pause/resume/send/get 等方法在**原型链**上,
- // Object.keys 看不到但 typeof 可命中;且它的包装方法内部会 `_notifyQueueUpdate`(刷新官方面板
- // 并返回真实快照)。因此按「typeof adapter.enqueueConversationMessageQueueItem === 'function'」
- // 直接命中 adapter 自身即可——不要取 adapter.sessionsResource(那是底层透传:返回 null、不刷新面板)。
- function findAiSessionsAdapter() {
- try {
- var el0 = document.querySelector('#root > div');
- if (!el0) return null;
- var stack = [el0], guardEl = 0;
- while (stack.length && guardEl++ < 300) {
- var el = stack.pop();
- if (!el) continue;
- for (var k in el) {
- if (k.indexOf('__reactFiber$') === 0 || k.indexOf('__reactInternalInstance') === 0) {
- var cur = el[k], seen = 0;
- while (cur && seen < 400) {
- try {
- var p = cur.memoizedProps;
- if (p && typeof p === 'object' && p.adapter && typeof p.adapter === 'object') {
- // 方法在原型链:typeof 判定(勿用 Object.keys)
- if (typeof p.adapter.enqueueConversationMessageQueueItem === 'function' &&
- typeof p.adapter.pauseConversationMessageQueue === 'function') {
- return { adapter: p.adapter };
- }
- }
- } catch (e) {}
- if (!cur) break;
- cur = cur.return; seen++;
- }
- break; // 每个 DOM 节点只看一次 fiber 链
- }
+ });
+ Object.defineProperty(shim, 'currentActiveSessionId', {
+ enumerable: true,
+ configurable: true,
+ get: function () {
+ try {
+ return target.currentActiveSessionId || WBS_COMPAT.getSelectedConversationId(document) || null;
+ } catch (e) {
+ return null;
}
- for (var i = 0; i < el.children.length; i++) stack.push(el.children[i]);
- }
- } catch (e) {}
- return null;
+ },
+ });
+ window.__wbsAdapter = WBS_COMPAT.markQueueAdapter(shim, 'modern');
+ return window.__wbsAdapter;
}
- function bootstrapWorkBuddyAiQueueBridge() {
- if (!WBS_PROFILE_IS_AI) return;
+ function bootstrapModernQueueBridge() {
try {
var adapter = findWbsAdapter();
+ if (!WBS_COMPAT.isModernQueueAdapter(adapter)) return;
var sessionId = adapter && adapter.currentActiveSessionId;
if (!sessionId || typeof adapter.getConversationMessageQueue !== 'function') return;
Promise.resolve(adapter.getConversationMessageQueue(sessionId)).catch(function () {});
} catch (e) {}
}
- // WorkBuddy AI 冷启动时 React adapter/当前会话可能还在挂载。首次点击不能把
+ // 新版布局冷启动时 React adapter/当前会话可能还在挂载。首次点击不能把
// 这类“暂不可用”误判成队列故障并写入旧版本地 stash,否则官方队列准备好后
// 第二次点击会得到两条。这里异步等待官方 adapter + 当前会话,不阻塞渲染主线程。
- function waitForWorkBuddyAiQueueAdapter(maxMs) {
- if (!WBS_PROFILE_IS_AI) return Promise.reject(new Error('非 WorkBuddy AI profile'));
+ function waitForModernQueueAdapter(maxMs) {
var startedAt = Date.now();
var limit = Number(maxMs) > 0 ? Number(maxMs) : 10000;
return new Promise(function (resolve, reject) {
@@ -2143,14 +2432,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
try {
var adapter = window.__wbsAdapter || findWbsAdapter();
var sessionId = adapter && adapter.currentActiveSessionId;
- if (adapter && sessionId &&
+ if (WBS_COMPAT.isModernQueueAdapter(adapter) && sessionId &&
typeof adapter.enqueueConversationMessageQueueItem === 'function' &&
typeof adapter.pauseConversationMessageQueue === 'function') {
return resolve({ adapter: adapter, sessionId: sessionId });
}
} catch (_) {}
if (Date.now() - startedAt >= limit) {
- var e = new Error('WorkBuddy AI 队列尚未准备完成');
+ var e = new Error('WorkBuddy 队列尚未准备完成');
e.code = 'WBS_QUEUE_NOT_READY';
return reject(e);
}
@@ -2161,20 +2450,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
// 后台预热只做只读查找,不触碰用户操作;点击路径随后直接复用缓存。
- function warmWorkBuddyAiQueueAdapter() {
- if (!WBS_PROFILE_IS_AI || !alive || window.__wbsAdapter) return;
+ function warmModernQueueAdapter() {
+ if (!alive || window.__wbsAdapter) return;
try { findWbsAdapter(); } catch (e) {}
}
- setBuildTimeout(warmWorkBuddyAiQueueAdapter, 0);
- setBuildTimeout(warmWorkBuddyAiQueueAdapter, 120);
- setBuildTimeout(warmWorkBuddyAiQueueAdapter, 500);
- setBuildTimeout(warmWorkBuddyAiQueueAdapter, 1500);
+ setBuildTimeout(warmModernQueueAdapter, 0);
+ setBuildTimeout(warmModernQueueAdapter, 120);
+ setBuildTimeout(warmModernQueueAdapter, 500);
+ setBuildTimeout(warmModernQueueAdapter, 1500);
// ConversationController/queueManager 会跨重注入存活;注入后主动只读拉一次当前队列,
// 立即安装或升级按钮桥接,不要求用户先再次点击“暂存提示词”。
- setBuildTimeout(bootstrapWorkBuddyAiQueueBridge, 300);
- setBuildTimeout(bootstrapWorkBuddyAiQueueBridge, 1200);
+ setBuildTimeout(bootstrapModernQueueBridge, 300);
+ setBuildTimeout(bootstrapModernQueueBridge, 1200);
- function writeWorkBuddyAiQueueItemToComposer(item) {
+ function writeModernQueueItemToComposer(item) {
var editor = findComposer();
if (!editor) return false;
var blocks = item && Array.isArray(item.contentBlocks) ? item.contentBlocks : [];
@@ -2198,8 +2487,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
}
- function handleWorkBuddyAiQueueActionClick(event) {
- if (!WBS_PROFILE_IS_AI || !event || event.button > 0) return;
+ function handleModernQueueActionClick(event) {
+ if (!event || event.button > 0) return;
var button = event.target && event.target.closest && event.target.closest('.cb-message-queue-item-actions button.icon-btn');
if (!button) return;
var cell = button.closest('.cb-message-queue-item');
@@ -2209,6 +2498,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (actionIndex < 0 || actionIndex > 2) return;
var itemId = cell.getAttribute('data-queue-item-id');
var adapter = findWbsAdapter();
+ if (!WBS_COMPAT.isModernQueueAdapter(adapter)) return;
var sessionId = adapter && adapter.currentActiveSessionId;
if (!itemId || !sessionId) return;
var manager = null;
@@ -2247,7 +2537,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
operation = adapter.sendConversationMessageQueueItemNow(sessionId, itemId);
} else if (actionIndex === 1 && typeof adapter.removeConversationMessageQueueItem === 'function') {
operation = Promise.resolve(adapter.removeConversationMessageQueueItem(sessionId, itemId)).then(function () {
- if (!writeWorkBuddyAiQueueItemToComposer(item)) throw new Error('WorkBuddy AI 输入框回填失败');
+ if (!writeModernQueueItemToComposer(item)) throw new Error('WorkBuddy 输入框回填失败');
});
} else if (actionIndex === 2 && typeof adapter.removeConversationMessageQueueItem === 'function') {
operation = adapter.removeConversationMessageQueueItem(sessionId, itemId);
@@ -2258,7 +2548,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
crumb('queue-action:fail:' + actionIndex + ':' + ((error && error.message) || error));
});
}
- if (WBS_PROFILE_IS_AI) listen(document, 'click', handleWorkBuddyAiQueueActionClick, true);
+ listen(document, 'click', handleModernQueueActionClick, true);
// 把抓取的输入框富文本转成 contentblocks(image 补回 base64 data),原样加入 WorkBuddy 队列。
// 【稳定性】只保留最朴素的纯对象字段,去掉 _meta/displayAsPhrase 等可能带不可克隆引用的元数据——
@@ -2583,12 +2873,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
// 兼容旧调用点(onDomChange/onInputSync/setTimeout 仍调用旧函数名,改为内部转发)
function wrapQueueReorder() { /* no-op:见 watchQueueOrder */ }
- // WorkBuddy AI 新版输入组件将每个会话的草稿保存在 composer store,并持久化到
+ // 新版输入组件将每个会话的草稿保存在 composer store,并持久化到
// localStorage 的 cb-draft:<conversationId>。只清 Slate/DOM 会导致切回会话时旧草稿重新水合。
// 这里沿当前 composer 的 fiber 向上找官方 store.api.clear(),仅接受 activeSessionId 与
// 暂存会话完全一致的 store;持久化键删除是官方 store 更新未同步落盘时的窄兜底。
- function clearWorkBuddyAiComposerDraft(ed, sessionId) {
- if (!WBS_PROFILE_IS_AI || !ed || !sessionId || !document.contains(ed)) return false;
+ function clearModernComposerDraft(ed, sessionId) {
+ if (!WBS_COMPAT.hasModernQueueSurface(document) || !ed || !sessionId || !document.contains(ed)) return false;
var node = ed;
for (var up = 0; up < 20 && node; up++) {
var fk = Object.keys(node).find(function (k) {
@@ -2599,10 +2889,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
while (cur && seen < 120) {
var p = cur.memoizedProps;
var store = p && p.store;
- if (isWorkBuddyAiComposerStore(store, sessionId)) {
+ if (WBS_COMPAT.isComposerStore(store, sessionId)) {
try { store.api.clear(); } catch (_) { return false; }
try {
- var draftKey = workBuddyAiDraftStorageKey(sessionId);
+ var draftKey = WBS_COMPAT.draftStorageKey(sessionId);
if (draftKey) localStorage.removeItem(draftKey);
} catch (_) {}
return true;
@@ -2614,7 +2904,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
return false;
}
- // 清空输入框:WorkBuddy AI 先清官方 composer store;旧客户端仍通过 React fiber
+ // 清空输入框:新版布局先清官方 composer store;旧版布局仍通过 React fiber
// 找 Slate onChange。两端最后都用 DOM 编辑命令做显示同步兜底。
// 【切会话守卫】入队 await 期间可能发生会话切换:此时 fiber 链可能已失效/指向旧会话,
// 直接清 store/onChange 有渲染进程风险——一律跳过(输入框留着内容,用户可见可清)。
@@ -2639,10 +2929,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
p0 = p0.parentElement;
}
} else {
- // AI 端(无 voice-mic-wrap):复用通用输入框定位(视口下半部可见的 contenteditable)
+ // 新版布局(无 voice-mic-wrap):复用通用输入框定位(视口下半部可见的 contenteditable)
ed = findComposer();
}
- clearWorkBuddyAiComposerDraft(ed, stashSessionAtClick);
+ clearModernComposerDraft(ed, stashSessionAtClick);
var cleared = false;
var node = ed;
for (var up = 0; up < 20 && node; up++) {
@@ -2684,7 +2974,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
node = node.parentElement;
}
- // AI 端(无 mic)fiber 未命中回退:execCommand 全选删除(占位符一并清除,React/Slate 由 input 事件驱动更新),
+ // 新版布局(无 mic)fiber 未命中回退:execCommand 全选删除(占位符一并清除,React/Slate 由 input 事件驱动更新),
// 有内容才清(避免空输入也触发编辑命令),仍受 hadText 判断约束
if (!cleared && !mic) {
try {
@@ -2722,9 +3012,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
try {
var blocks = contentToBlocks(content);
if (!blocks.length) return Promise.reject(new Error('输入框内容为空'));
- var ready = WBS_PROFILE_IS_AI
- ? waitForWorkBuddyAiQueueAdapter(10000)
- : Promise.resolve({ adapter: window.__wbsAdapter || findWbsAdapter(), sessionId: null });
+ var cachedAdapter = window.__wbsAdapter || findWbsAdapter();
+ var modernQueue = WBS_COMPAT.isModernQueueAdapter(cachedAdapter) || WBS_COMPAT.hasModernQueueSurface(document);
+ var ready = modernQueue
+ ? waitForModernQueueAdapter(10000)
+ : Promise.resolve({ adapter: cachedAdapter, sessionId: null });
return ready.then(function (readyState) {
var adapter = readyState && readyState.adapter;
// 官方包装方法必须齐全:enqueueConversationMessageQueueItem(入队+刷新面板)/ pauseConversationMessageQueue(暂停自动发送+刷新面板)
@@ -2736,26 +3028,27 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!sessionId) throw new Error('未获取到当前会话');
// 记录本次实际入队使用的会话 id。等待冷启动就绪期间也不允许换会话后误清空输入。
stashSessionAtClick = sessionId;
+ var modernAdapter = WBS_COMPAT.isModernQueueAdapter(adapter);
var enqueueSnapshot = null;
- // 关键事务顺序:先暂停,再入队。AI 5.4 的 dispatcher 会在 enqueue RPC
+ // 关键事务顺序:先暂停,再入队。新版 5.4 的 dispatcher 会在 enqueue RPC
// 返回前继续 activate(),旧的“先入队后暂停”会把已有普通项全部发送掉。
- var pauseWait = WBS_PROFILE_IS_AI
+ var pauseWait = modernAdapter
? withQueueTimeout(adapter.pauseConversationMessageQueue(sessionId, 'manual'), 5000)
: Promise.resolve(null);
return pauseWait
.then(function () { crumb('pause:ok'); })
.catch(function () { crumb('pause:fail'); return null; })
.then(function () {
- // 立即把暂存项镜像到 AI 官方队列 store,避免新版 RPC 冷启动时 UI 空等数秒。
+ // 立即把暂存项镜像到新版官方队列 store,避免 RPC 冷启动时 UI 空等数秒。
// 真实快照返回后会整体替换该临时项;临时项不参与任何官方操作。
- if (WBS_PROFILE_IS_AI) {
- try { syncWorkBuddyAiQueueSnapshot(sessionId, { __wbsOptimistic: blocks }); } catch (e) {}
+ if (modernAdapter) {
+ try { syncModernQueueSnapshot(sessionId, { __wbsOptimistic: blocks }); } catch (e) {}
}
var rawEnqueue = adapter.enqueueConversationMessageQueueItem(sessionId, blocks);
return Promise.resolve(rawEnqueue).then(function (snapshot) {
- // 某些 AI 5.4 时机返回 null/{items:[]},立即重新读取当前会话,避免
+ // 某些 5.4 时机返回 null/{items:[]},立即重新读取当前会话,避免
// 暂存 ID 丢失或旧空快照覆盖 UI。
- return getWorkBuddyAiQueueSnapshot(adapter, sessionId, snapshot);
+ return getModernQueueSnapshot(adapter, sessionId, snapshot);
});
})
.then(function (snapshot) {
@@ -2775,7 +3068,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var stashBusy = false;
var stashBusyTimer = null;
- // WorkBuddy AI 官方入队 Promise 可能晚于 UI 超时才 settle。保留同一内容的
+ // 新版官方入队 Promise 可能晚于 UI 超时才 settle。保留同一内容的
// in-flight 事务,后续重复点击只复用原事务,绝不再次调用 enqueue。
var stashInFlight = null;
var stashSessionAtClick = null; // 点击暂存时的会话 id:清空输入框的切会话守卫用
@@ -2811,15 +3104,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
syncStash(); // 输入框清空后隐藏暂存按钮
})
.catch(function (e) {
- var optimisticCleanup = WBS_PROFILE_IS_AI ? dropWorkBuddyAiOptimisticItem(stashSessionAtClick) : Promise.resolve();
- // A timeout is still retained for legacy WorkDaddy only. WorkBuddy AI does
- // not timeout the official promise: a late successful RPC must not be paired
+ var modernQueue = WBS_COMPAT.isModernQueueAdapter(window.__wbsAdapter) || WBS_COMPAT.hasModernQueueSurface(document);
+ var optimisticCleanup = modernQueue ? dropModernOptimisticItem(stashSessionAtClick) : Promise.resolve();
+ // A timeout is still retained for the legacy layout only. The modern layout does
+ // not fall back after timeout: a late successful RPC must not be paired
// with a local fallback item, which would create duplicate queue entries.
if (e && e.code === 'WBS_QUEUE_TIMEOUT') {
crumb('enqueue:timeout-no-fallback');
return optimisticCleanup;
}
- if (e && e.code === 'WBS_QUEUE_NOT_READY' && WBS_PROFILE_IS_AI) {
+ if (e && e.code === 'WBS_QUEUE_NOT_READY' && modernQueue) {
crumb('enqueue:not-ready-no-fallback');
return optimisticCleanup;
}
@@ -2931,7 +3225,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-acct-stat"><span>总积分</span><strong id="wbs-acct-total">-</strong></div>' +
'</div>' +
'<div class="wbs-acct-actions">' +
- '<button class="wbs-acct-io" type="button" data-act="export" title="输入密码后导出全部账号备份">' + EXPORT_ICON + '<span>导出</span></button>' +
+ '<button class="wbs-acct-io" type="button" data-act="export" title="选择账号并输入密码后导出备份">' + EXPORT_ICON + '<span>导出</span></button>' +
'<button class="wbs-acct-io" type="button" data-act="import" title="从加密导出文件导入账号备份">' + IMPORT_ICON + '<span>导入</span></button>' +
'</div>' +
'</div>' +
@@ -2946,44 +3240,93 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
root.querySelector('#wbs-import-file').addEventListener('change', onImportFile);
}
- function closeAccountPasswordModal(mask) {
+ function closeSecureTransferModal(mask) {
if (mask && mask.parentNode) mask.parentNode.removeChild(mask);
}
- function openAccountPasswordModal(mode, onConfirm) {
- closeAccountPasswordModal(panel && panel.querySelector('#wbs-account-password-modal'));
- var isExport = mode === 'export';
+ function openSecureTransferModal(options) {
+ options = options || {};
+ closeSecureTransferModal(panel && panel.querySelector('#wbs-secure-transfer-modal'));
+ var items = Array.isArray(options.items) ? options.items : [];
+ var requirePassword = options.requirePassword !== false;
+ var selected = {};
+ var itemHtml = '';
+ for (var i = 0; i < items.length; i++) {
+ selected[String(items[i].id)] = true;
+ itemHtml += '<label class="wbs-transfer-option selected">' +
+ '<input type="checkbox" data-transfer-id="' + escAttr(items[i].id) + '" checked>' +
+ '<span class="wbs-transfer-copy"><span class="wbs-transfer-title">' + esc(items[i].title || '') + '</span>' +
+ (items[i].sub ? '<span class="wbs-transfer-sub">' + esc(items[i].sub) + '</span>' : '') + '</span></label>';
+ }
var mask = document.createElement('div');
- mask.className = 'wbs-panel-modal-mask';
- mask.id = 'wbs-account-password-modal';
+ mask.className = 'wbs-modal-mask wbs-modal-mask-panel';
+ mask.id = 'wbs-secure-transfer-modal';
mask.innerHTML =
- '<div class="wbs-password-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-password-title">' +
- '<div class="wbs-login-modal-title" id="wbs-password-title">' + (isExport ? '导出账号' : '导入账号') + '</div>' +
- '<label class="wbs-password-field"><span>密码' + (isExport ? '' : '(可留空)') + '</span>' +
- '<input id="wbs-account-password" type="password" autocomplete="new-password" placeholder="' + (isExport ? '请输入密码' : '新版文件请输入密码') + '"></label>' +
- '<div class="wbs-password-hint">' + (isExport ? '密码不能为空,请妥善保管。' : '导入密码可留空;旧版导出文件默认使用 workdaddy。') + '</div>' +
- '<div class="wbs-password-error" id="wbs-password-error" role="alert"></div>' +
- '<div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" id="wbs-password-cancel">取消</button>' +
- '<button class="wbs-modal-btn wbs-modal-ok" type="button" id="wbs-password-confirm">确定</button></div>' +
+ '<div class="wbs-password-modal wbs-transfer-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-transfer-title">' +
+ '<div class="wbs-login-modal-title" id="wbs-transfer-title">' + esc(options.title || '安全传输') + '</div>' +
+ (items.length ? '<div class="wbs-transfer-select-head"><span>' + esc(options.selectionLabel || '选择内容') + '</span>' +
+ '<button class="wbs-transfer-toggle" type="button" id="wbs-transfer-toggle">取消全选</button></div>' +
+ '<div class="wbs-transfer-list">' + itemHtml + '</div>' : '') +
+ '<label class="wbs-password-field"><span>密码' + (requirePassword ? '' : '(旧版文件可留空)') + '</span>' +
+ '<input id="wbs-transfer-password" type="password" autocomplete="new-password" placeholder="' + esc(options.passwordPlaceholder || '请输入密码') + '"></label>' +
+ '<div class="wbs-password-hint">' + esc(options.hint || (requirePassword ? '密码不能为空,请妥善保管。' : '新版文件请输入密码。')) + '</div>' +
+ '<div class="wbs-password-error" id="wbs-transfer-error" role="alert"></div>' +
+ '<div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" id="wbs-transfer-cancel">取消</button>' +
+ '<button class="wbs-modal-btn wbs-modal-ok" type="button" id="wbs-transfer-confirm">' + esc(options.confirmText || '确定') + '</button></div>' +
'</div>';
(panel || root).appendChild(mask);
- var input = mask.querySelector('#wbs-account-password');
- var error = mask.querySelector('#wbs-password-error');
- var confirm = mask.querySelector('#wbs-password-confirm');
- var close = function () { closeAccountPasswordModal(mask); };
- mask.querySelector('#wbs-password-cancel').addEventListener('click', close);
+ var input = mask.querySelector('#wbs-transfer-password');
+ var error = mask.querySelector('#wbs-transfer-error');
+ var confirm = mask.querySelector('#wbs-transfer-confirm');
+ var close = function () { closeSecureTransferModal(mask); };
+ function selectedIds() { return Object.keys(selected).filter(function (id) { return selected[id]; }); }
+ function syncSelection() {
+ var checks = mask.querySelectorAll('[data-transfer-id]');
+ for (var c = 0; c < checks.length; c++) {
+ var id = checks[c].getAttribute('data-transfer-id');
+ checks[c].checked = !!selected[id];
+ checks[c].closest('.wbs-transfer-option').classList.toggle('selected', !!selected[id]);
+ }
+ var toggle = mask.querySelector('#wbs-transfer-toggle');
+ if (toggle) toggle.textContent = selectedIds().length === items.length ? '取消全选' : '全选';
+ }
+ var optionChecks = mask.querySelectorAll('[data-transfer-id]');
+ for (var oi = 0; oi < optionChecks.length; oi++) {
+ optionChecks[oi].addEventListener('change', function () {
+ selected[this.getAttribute('data-transfer-id')] = !!this.checked;
+ syncSelection();
+ });
+ }
+ var toggle = mask.querySelector('#wbs-transfer-toggle');
+ if (toggle) toggle.addEventListener('click', function () {
+ var selectAll = selectedIds().length !== items.length;
+ for (var t = 0; t < items.length; t++) selected[String(items[t].id)] = selectAll;
+ syncSelection();
+ });
+ mask.querySelector('#wbs-transfer-cancel').addEventListener('click', close);
mask.addEventListener('click', function (ev) { if (ev.target === mask) close(); });
confirm.addEventListener('click', function () {
var value = input.value;
- if (isExport && !value.trim()) {
+ if (items.length && !selectedIds().length) {
+ error.textContent = '请至少选择一项';
+ return;
+ }
+ if (requirePassword && !value.trim()) {
error.textContent = '密码不能为空';
input.focus();
return;
}
+ error.textContent = '';
confirm.disabled = true;
confirm.textContent = '处理中…';
- close();
- onConfirm(value);
+ Promise.resolve().then(function () {
+ return options.onConfirm(value, selectedIds());
+ }).then(close).catch(function (err) {
+ error.textContent = (err && err.message) || String(err || '操作失败');
+ confirm.disabled = false;
+ confirm.textContent = options.confirmText || '确定';
+ input.focus();
+ });
});
input.addEventListener('keydown', function (ev) {
if (ev.key === 'Enter') confirm.click();
@@ -2992,26 +3335,71 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
setBuildTimeout(function () { input.focus(); }, 0);
}
+ function downloadTransfer(result, fallbackName) {
+ var blob = new Blob([result.content], { type: 'application/json' });
+ var url = URL.createObjectURL(blob);
+ var anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = result.filename || fallbackName;
+ document.body.appendChild(anchor);
+ anchor.click();
+ setTimeout(function () { document.body.removeChild(anchor); URL.revokeObjectURL(url); }, 300);
+ }
+
+ function readTransferFile(file) {
+ return new Promise(function (resolve, reject) {
+ var reader = new FileReader();
+ reader.onload = function () { resolve(String(reader.result || '')); };
+ reader.onerror = function () { reject(new Error('读取文件失败')); };
+ reader.readAsText(file);
+ });
+ }
+
+ function copyPlainText(text) {
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
+ return navigator.clipboard.writeText(String(text));
+ }
+ return new Promise(function (resolve, reject) {
+ var textarea = document.createElement('textarea');
+ textarea.value = String(text);
+ textarea.setAttribute('readonly', '');
+ textarea.style.position = 'fixed';
+ textarea.style.opacity = '0';
+ document.body.appendChild(textarea);
+ textarea.select();
+ var copied = false;
+ try { copied = document.execCommand('copy'); } catch (_) {}
+ document.body.removeChild(textarea);
+ if (copied) resolve(); else reject(new Error('复制失败'));
+ });
+ }
+
// 导出账号:密码必填,daemon 使用随机 salt 加密后触发浏览器下载。
function onExportAccounts() {
- openAccountPasswordModal('export', function (password) {
- api('/api/accounts/export', {
+ var items = state.accounts.map(function (account) {
+ return {
+ id: account.uid,
+ title: account.nickname || '未命名账号',
+ sub: account.phone || account.uin || '',
+ };
+ });
+ if (!items.length) { toast('没有可导出的账号备份', true, root); return; }
+ openSecureTransferModal({
+ title: '导出账号',
+ selectionLabel: '选择账号',
+ items: items,
+ requirePassword: true,
+ confirmText: '导出',
+ hint: '所选账号将加密保存,密码不能为空,请妥善保管。',
+ onConfirm: function (password, uids) { return api('/api/accounts/export', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ password: password }),
- })
- .then(function (r) {
- var blob = new Blob([r.content], { type: 'application/json' });
- var url = URL.createObjectURL(blob);
- var a = document.createElement('a');
- a.href = url;
- a.download = r.filename || 'WorkDaddy-accounts.json';
- document.body.appendChild(a);
- a.click();
- setTimeout(function () { document.body.removeChild(a); URL.revokeObjectURL(url); }, 300);
+ body: JSON.stringify({ password: password, uids: uids }),
+ }).then(function (r) {
+ downloadTransfer(r, 'WorkDaddy-accounts.json');
toast('已导出 ' + r.count + ' 个账号(已加密)', false, root);
- })
- .catch(function (e) { toast('导出失败: ' + e.message, true, root); });
+ });
+ },
});
}
@@ -3020,24 +3408,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var file = ev.target && ev.target.files && ev.target.files[0];
ev.target.value = '';
if (!file) return;
- var reader = new FileReader();
- reader.onload = function () {
- var content = String(reader.result);
- openAccountPasswordModal('import', function (password) {
- api('/api/accounts/import', {
+ readTransferFile(file).then(function (content) {
+ openSecureTransferModal({
+ title: '导入账号',
+ requirePassword: false,
+ passwordPlaceholder: '新版文件请输入密码',
+ hint: '新版文件必须输入密码;旧版导出文件可留空。',
+ confirmText: '导入',
+ onConfirm: function (password) { return api('/api/accounts/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: content, password: password }),
- })
- .then(function (r) {
+ }).then(function (r) {
toast('成功导入 ' + r.count + ' 个账号', false, root);
refresh();
- })
- .catch(function (e) { toast('导入失败: ' + e.message, true, root); });
+ });
+ },
});
- };
- reader.onerror = function () { toast('读取文件失败', true, root); };
- reader.readAsText(file);
+ }).catch(function (e) { toast(e.message || '读取文件失败', true, root); });
}
// ===== Tab 切换 =====
@@ -3061,7 +3449,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
// ===== 会话 pane(构建:账号/时间筛选 + 按空间分组[默认2条/展开10条] + 刷新 + 批量操作[迁移/删除])=====
- var sessionsState = { uid: undefined, range: '7d', list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null };
+ var sessionsState = { uid: undefined, currentUid: '', range: '7d', list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null };
function isTaskSessionRecordUI(s) {
// 任务(未选择项目/一次性)会话:以官方 is_playground=1 为准。
// 普通工作区也用 WorkBuddy\\YYYY-MM-DD-HH-MM-SS 命名,仅凭 cwd 无法区分。
@@ -3100,15 +3488,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</div>' +
'<div class="wbs-sess-toolbar">' +
'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-batch">批量操作</button>' +
+ '<button class="wbs-sess-bbtn" type="button" id="wbs-sess-import" title="从加密文件导入会话">' + IMPORT_ICON + '<span>导入</span></button>' +
'<span class="wbs-sess-count" id="wbs-sess-count"></span>' +
'<div class="wbs-sess-batchbar" id="wbs-sess-batchbar" style="display:none">' +
'<button class="wbs-sess-bbtn wbs-sess-check-all" type="button" id="wbs-sess-check-all">全选</button>' +
'<span class="wbs-sess-batch-count" id="wbs-sess-batch-count">已选 0</span>' +
'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-copy" title="复制选中到其他账号"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><span>复制</span></button>' +
+ '<button class="wbs-sess-bbtn" type="button" id="wbs-sess-export" title="使用密码导出选中会话">' + EXPORT_ICON + '<span>导出</span></button>' +
'<button class="wbs-sess-bbtn wbs-sess-delbtn" type="button" id="wbs-sess-delete" title="删除选中"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg><span>删除</span></button>' +
'<button class="wbs-sess-bbtn wbs-sess-done" type="button" id="wbs-sess-done">取消</button>' +
'</div>' +
'</div>' +
+ '<input type="file" id="wbs-sess-import-file" accept=".json,application/json" style="display:none">' +
'<div class="wbs-sess-list" id="wbs-sess-list"></div>' +
'</div>' +
'<div class="wbs-modal-mask" id="wbs-sess-modal" style="display:none">' +
@@ -3134,6 +3525,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var accts = (d && d.accounts) || [];
sessionsState.accounts = accts;
var curUid = (d && d.current && d.current.uid) || '';
+ sessionsState.currentUid = curUid;
var curName = '当前账号';
for (var i = 0; i < accts.length; i++) if (accts[i].uid === curUid) curName = accts[i].nickname || curName;
var html = '<option value="">' + esc(curName) + '</option>';
@@ -3404,8 +3796,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (bc) bc.textContent = '已选 ' + n;
// 未选中会话时隐藏「复制/删除」按钮(仅批量模式可见)
var cp = sessionsPane.querySelector('#wbs-sess-copy');
+ var ex = sessionsPane.querySelector('#wbs-sess-export');
var dl = sessionsPane.querySelector('#wbs-sess-delete');
if (cp) cp.style.display = n ? '' : 'none';
+ if (ex) ex.style.display = n ? '' : 'none';
if (dl) dl.style.display = n ? '' : 'none';
syncCheckAllBtn();
}
@@ -3442,8 +3836,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function setSessBatchBar(on) {
var bar = sessionsPane.querySelector('#wbs-sess-batchbar');
var bb = sessionsPane.querySelector('#wbs-sess-batch');
+ var importBtn = sessionsPane.querySelector('#wbs-sess-import');
var cnt = sessionsPane.querySelector('#wbs-sess-count');
if (bb) { bb.style.display = on ? 'none' : ''; bb.classList.toggle('active', on); }
+ if (importBtn) importBtn.style.display = on ? 'none' : '';
if (cnt) cnt.style.display = on ? 'none' : '';
if (bar) bar.style.display = on ? 'flex' : 'none';
}
@@ -3495,6 +3891,53 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
openCopyModal(ids);
});
}
+ var exportBtn = sessionsPane.querySelector('#wbs-sess-export');
+ if (exportBtn) exportBtn.addEventListener('click', function () {
+ var ids = selectedSessIds();
+ if (!ids.length) { toast('请先勾选要导出的会话', true, root); return; }
+ openSecureTransferModal({
+ title: '导出会话',
+ requirePassword: true,
+ confirmText: '导出',
+ hint: '将加密导出 ' + ids.length + ' 个会话及其本地消息附件。',
+ onConfirm: function (password) { return api('/api/sessions/export', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ids: ids, password: password }),
+ }).then(function (result) {
+ downloadTransfer(result, 'WorkDaddy-sessions.json');
+ toast('已导出 ' + result.count + ' 个会话(已加密)', false, root);
+ }); },
+ });
+ });
+ var importBtn = sessionsPane.querySelector('#wbs-sess-import');
+ var importFile = sessionsPane.querySelector('#wbs-sess-import-file');
+ if (importBtn && importFile) {
+ importBtn.addEventListener('click', function () { importFile.click(); });
+ importFile.addEventListener('change', function (event) {
+ var file = event.target && event.target.files && event.target.files[0];
+ event.target.value = '';
+ if (!file) return;
+ readTransferFile(file).then(function (content) {
+ var targetUid = sessionsState.uid === '' ? '' : (sessionsState.uid || sessionsState.currentUid || '');
+ var target = sessionsState.accounts.find(function (account) { return account.uid === targetUid; });
+ openSecureTransferModal({
+ title: '导入会话',
+ requirePassword: true,
+ confirmText: '导入',
+ hint: targetUid ? '会话将导入到「' + ((target && target.nickname) || '当前账号') + '」。' : '会话将保留导出时的账号归属。',
+ onConfirm: function (password) { return api('/api/sessions/import', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ content: content, password: password, targetUid: targetUid }),
+ }).then(function (result) {
+ toast('已导入 ' + result.count + ' 个会话' + (result.failed ? ',' + result.failed + ' 个失败' : ''), !!result.failed, root);
+ loadSessions();
+ }); },
+ });
+ }).catch(function (error) { toast(error.message || '读取文件失败', true, root); });
+ });
+ }
// 删除选中(批量栏按钮):直接弹删除确认框(真实删除,弹窗内已警示不可恢复)
var delBtn = sessionsPane.querySelector('#wbs-sess-delete');
if (delBtn) {
@@ -3949,8 +4392,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-pcard">' +
'<div class="wbs-pcard-title">主题外观</div>' +
'<div class="wbs-theme-seg" id="wbs-theme-seg">' +
- '<button class="wbs-theme-opt active" type="button" data-theme="default">WorkBuddy 默认主题</button>' +
- '<button class="wbs-theme-opt" type="button" data-theme="nebula">' + WBS_BRAND + ' 主题</button>' +
+ '<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>' +
'</div>' +
'</div>' +
'<div class="wbs-pcard">' +
@@ -3963,8 +4408,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-wallpapers" id="wbs-wallpapers"><div class="wbs-wp-loading">壁纸加载中…</div></div>' +
'</div>' +
'<div class="wbs-bg-panel" data-src-panel="custom" style="display:none">' +
- '<div class="wbs-bg-upload" id="wbs-bg-upload" title="点击选择图片,或拖拽到此处"><span class="wbs-bg-upload-ico">+</span><span>点击或拖拽上传壁纸</span><span class="wbs-bg-upload-hint">支持 PNG / JPG / WebP,自动压缩</span></div>' +
- '<img class="wbs-bg-preview" id="wbs-bg-preview" alt="自定义壁纸预览">' +
+ '<div class="wbs-bg-upload" id="wbs-bg-upload" title="点击选择图片,或拖拽到此处"><span class="wbs-bg-upload-ico">+</span><span>点击或拖拽上传壁纸</span><span class="wbs-bg-upload-hint">支持 PNG / JPG / WebP,自动压缩;可添加多张</span></div>' +
+ '<div class="wbs-wallpapers wbs-custom-wallpapers" id="wbs-custom-wallpapers"><div class="wbs-wp-loading">壁纸加载中…</div></div>' +
'<input type="file" id="wbs-theme-file" accept="image/png,image/jpeg,image/webp" style="display:none">' +
'</div>' +
'<div class="wbs-avatar-row">' +
@@ -3973,15 +4418,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<button class="wbs-theme-upload" id="wbs-avatar-reset" type="button" title="恢复 WorkBuddy 官方头像">恢复默认</button>' +
'<input type="file" id="wbs-avatar-file" accept="image/png,image/jpeg,image/webp" style="display:none">' +
'</div>' +
- '<div class="wbs-blur-row" id="wbs-blur-row">' +
- '<label class="wbs-blur-label" for="wbs-blur-switch">背景毛玻璃<span class="wbs-blur-hint">背景图模糊、文字清晰</span></label>' +
- '<label class="wbs-switch" title="开启后背景图呈毛玻璃模糊感"><input type="checkbox" id="wbs-blur-switch"><span class="wbs-switch-slider"></span></label>' +
- '</div>' +
- '<div class="wbs-blur-ctrl" id="wbs-blur-ctrl" style="display:none">' +
- '<label class="wbs-blur-label">模糊度</label>' +
- '<input type="range" id="wbs-blur-range" min="0" max="100" step="1" value="80">' +
- '<span class="wbs-blur-val" id="wbs-blur-val">16</span>' +
- '</div>' +
'<div class="wbs-mask-row">' +
'<label class="wbs-blur-label" for="wbs-mask-range">背景蒙版<span class="wbs-blur-hint">黑色半透明遮罩,压暗背景图</span></label>' +
'<input type="range" id="wbs-mask-range" min="0" max="100" step="1" value="30">' +
@@ -4043,6 +4479,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<label class="wbs-switch"><input type="checkbox" id="wbs-sess-stash"><span class="wbs-switch-slider"></span></label>' +
'</div>' +
'<div class="wbs-nd-row">' +
+ '<span class="wbs-nd-title">会话消息索引</span>' +
+ '<span class="wbs-nd-hint">悬停预览,点击或拖动快速定位消息。</span>' +
+ '<label class="wbs-switch" title="在会话左侧显示消息索引"><input type="checkbox" id="wbs-sess-message-nav"><span class="wbs-switch-slider"></span></label>' +
+ '</div>' +
+ '<div class="wbs-nd-row">' +
'<span class="wbs-nd-title">快捷短语</span>' +
'<span class="wbs-nd-hint">发送后不会自动删除。</span>' +
'<label class="wbs-switch"><input type="checkbox" id="wbs-sess-phrase"><span class="wbs-switch-slider"></span></label>' +
@@ -4052,13 +4493,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<span class="wbs-qp-batchbar" id="wbs-qp-batchbar" style="display:none">' +
'<button class="wbs-sess-bbtn" type="button" id="wbs-qp-checkall">全选</button>' +
'<span class="wbs-qp-batch-count" id="wbs-qp-batch-count">已选 0</span>' +
+ '<button class="wbs-sess-bbtn" type="button" id="wbs-qp-copy" title="复制选中快捷短语">' + MODEL_COPY_SVG + '<span>复制</span></button>' +
+ '<button class="wbs-sess-bbtn" type="button" id="wbs-qp-export" title="使用密码导出选中快捷短语">' + EXPORT_ICON + '<span>导出</span></button>' +
'<button class="wbs-sess-bbtn wbs-qp-batch-action" type="button" id="wbs-qp-batch-del">删除</button>' +
'<button class="wbs-sess-bbtn wbs-sess-done" type="button" id="wbs-qp-done">取消</button>' +
'</span>' +
- '<button class="wbs-sess-bbtn" type="button" id="wbs-qp-batch">批量管理</button>' +
+ '<button class="wbs-sess-bbtn" type="button" id="wbs-qp-batch">批量操作</button>' +
+ '<button class="wbs-sess-bbtn" type="button" id="wbs-qp-import" title="从加密文件导入快捷短语">' + IMPORT_ICON + '<span>导入</span></button>' +
'<span class="wbs-qp-toolbar-spacer"></span>' +
'<button class="wbs-sess-bbtn" type="button" id="wbs-qp-add">+ 新增</button>' +
'</div>' +
+ '<input type="file" id="wbs-qp-import-file" accept=".json,application/json" style="display:none">' +
'<div class="wbs-qp-list" id="wbs-qp-list"><div class="wbs-empty">加载中…</div></div>' +
'</div>' +
'</div>' +
@@ -4071,11 +4516,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</div>' +
'<div class="wbs-pcard" id="wbs-devtools-card" style="display:none">' +
'<div class="wbs-pcard-title">开发者工具<span class="wbs-pcard-sub">隐藏功能</span></div>' +
- '<div class="wbs-enh-row">' +
- '<button class="wbs-theme-devtools" id="wbs-theme-devtools" type="button" title="打开 Chrome DevTools(完整元素检查/控制台/网络调试)">打开 DevTools</button>' +
- '<button class="wbs-theme-inspect" id="wbs-theme-inspect" type="button" title="检查元素:点击页面任意组件,查看它的样式与颜色来源">元素检查</button>' +
- '</div>' +
- '<div class="wbs-enh-tip">连续点击面板标题「' + WBS_BRAND + '」5 次可隐藏/呼出本模块</div>' +
'<div class="wbs-ac-log-wrap" id="wbs-ac-log-wrap">' +
'<div class="wbs-ac-log-head">会话 · 状态机日志<span class="wbs-ac-log-clear" id="wbs-ac-log-clear" title="清空日志">清空</span></div>' +
'<pre class="wbs-ac-log" id="wbs-ac-log">(未开启「会话异常中断」监控时无日志)</pre>' +
@@ -4094,7 +4534,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-sleep-modes" id="wbs-sleep-modes">' +
'<label class="wbs-sleep-mode"><input type="radio" name="wbs-sleep-mode" value="allow"><span class="wbs-sleep-mode-name">允许电脑休眠</span><span class="wbs-sleep-mode-hint">系统默认,空闲后正常休眠</span></label>' +
'<label class="wbs-sleep-mode"><input type="radio" name="wbs-sleep-mode" value="keep"><span class="wbs-sleep-mode-name">持续禁止休眠</span><span class="wbs-sleep-mode-hint">保持唤醒,防黑屏锁屏</span></label>' +
- '<label class="wbs-sleep-mode"><input type="radio" name="wbs-sleep-mode" value="until-done"><span class="wbs-sleep-mode-name">所有任务结束后允许休眠</span><span class="wbs-sleep-mode-hint">AI 忙碌时保持唤醒,结束自动恢复</span></label>' +
+ '<label class="wbs-sleep-mode"><input type="radio" name="wbs-sleep-mode" value="until-done"><span class="wbs-sleep-mode-name">当前会话结束允许休眠</span><span class="wbs-sleep-mode-hint">仅当前会话,回复中保持唤醒</span></label>' +
'</div>' +
'<div class="wbs-ask-row" id="wbs-display-sleep-row" style="display:none">' +
'<label class="wbs-ask-label" for="wbs-display-switch">允许显示器休眠<span class="wbs-ask-hint">禁止休眠时,是否允许显示器单独黑屏</span></label>' +
@@ -4110,7 +4550,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
sleepModeRadios.forEach(function (r) {
r.addEventListener('change', function () {
if (!this.checked) return;
- postSleepMode(this.value, displaySleepSwitch ? displaySleepSwitch.checked : false);
+ var mode = this.value;
+ // until-done:校验当前会话正在进行中才允许开启;无进行中会话则拒绝并回退 allow
+ if (mode === 'until-done') {
+ var st = isSessionBusy(null);
+ if (!st.busy) {
+ toast('当前没有进行中的会话,无法开启「当前会话结束允许休眠」', true, root);
+ var goBack = pcPane && pcPane.querySelector('input[name="wbs-sleep-mode"][value="allow"]');
+ if (goBack) goBack.checked = true;
+ syncSleepState();
+ return;
+ }
+ }
+ postSleepMode(mode, displaySleepSwitch ? displaySleepSwitch.checked : false);
});
});
}
@@ -4315,14 +4767,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return text;
}
- // 点击「立即更新」:后台下载 → 轮询状态 → 安装(daemon 写脚本替换 + 自动重启)
+ // 点击「立即更新」:后台下载并校验。Windows 下载完成后由用户明确打开
+ // 可见 Setup.exe;macOS 继续沿用原有自动安装与重启流程。
function startUpdate() {
var btn = aboutPane.querySelector('#wbs-update-btn');
var prog = aboutPane.querySelector('#wbs-update-progress');
var card = aboutPane.querySelector('#wbs-update-card');
if (!btn || !card) return;
btn.disabled = true;
- btn.textContent = '更新中…';
+ btn.textContent = '下载中…';
if (prog) { prog.innerHTML = ''; prog._wbsLastLog = ''; appendUpdateLog(prog, '正在准备更新…'); }
api('/api/update-download', { method: 'POST' }).then(function (d) {
if (!d.ok) throw new Error(d.error || '下载失败');
@@ -4335,6 +4788,64 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
+ function openWindowsInstaller(prog, btn) {
+ if (!btn) return;
+ btn.disabled = true;
+ btn.textContent = '正在打开…';
+ appendUpdateLog(prog, '正在打开已校验的安装程序…');
+ api('/api/update-apply', { method: 'POST' }).then(function (result) {
+ if (!result || !result.ok || !result.opened) {
+ var rejected = new Error(formatUpdateFailure(result, '无法打开安装程序'));
+ rejected.payload = result;
+ throw rejected;
+ }
+ btn.textContent = '安装程序已打开';
+ appendUpdateLog(prog, '安装程序已打开,请按提示退出 WorkBuddy 并完成安装。');
+ }).catch(function (error) {
+ btn.disabled = false;
+ btn.textContent = '打开安装程序';
+ var failure = formatUpdateFailure(error, '无法打开安装程序');
+ appendUpdateLog(prog, failure);
+ try { toast(failure, true, root); } catch (_) {}
+ });
+ }
+
+ function showWindowsInstallerReady(prog, btn, card, timer) {
+ if (timer) clearInterval(timer);
+ appendUpdateLog(prog, '即将打开安装包…');
+ var bar = card ? card.querySelector('#wbs-update-bar') : null;
+ var barFill = bar ? bar.querySelector('#wbs-update-bar-fill') : null;
+ if (bar) bar.style.display = '';
+ if (barFill) barFill.style.width = '100%';
+ if (btn) {
+ btn.disabled = false;
+ btn.textContent = '打开安装程序';
+ btn.onclick = function () { openWindowsInstaller(prog, btn); };
+ }
+ }
+
+ function openWindowsInstallerAfterDownload(prog, btn, card, timer, resolve, reject) {
+ showWindowsInstallerReady(prog, btn, card, timer);
+ api('/api/update-apply', { method: 'POST' }).then(function (result) {
+ if (!result || !result.ok || !result.opened) {
+ var rejected = new Error(formatUpdateFailure(result, '无法打开安装程序'));
+ rejected.payload = result;
+ throw rejected;
+ }
+ if (btn) {
+ btn.disabled = true;
+ btn.textContent = '安装包已打开';
+ btn.onclick = null;
+ }
+ resolve(true);
+ }).catch(function (error) {
+ var failure = formatUpdateFailure(error, '无法打开安装程序');
+ appendUpdateLog(prog, failure);
+ try { toast(failure, true, root); } catch (_) {}
+ reject(error);
+ });
+ }
+
// 轮询 /api/update-status 直到下载完成 → 触发 apply → daemon 自我退出进入「重启等待」。
// 重启期间 /api/update-status 会连接失败(daemon 已退出换文件)——这属于"正常重启"而非失败,
// 继续重试直到新 daemon 起来并报告新版本号,才算完成。全程用分阶段文案反馈,不再一句「即将重启」了事。
@@ -4404,17 +4915,30 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
appendUpdateLog(prog, (s.message || '正在下载…') + (s.progress ? ' ' + s.progress + '%' : '') + transfer);
} else if (st === 'installing') {
- appendUpdateLog(prog, '正在安装新版本…');
- if (btn) btn.textContent = '安装中…';
- fireApply();
+ // Windows 安装由用户打开的 Setup.exe 接管;兼容旧 daemon 的残留
+ // installing 状态时也必须停在安装包入口,不能再次触发自动重启流程。
+ if (WBS_PLATFORM === 'win32') {
+ if (s.downloaded) {
+ showWindowsInstallerReady(prog, btn, card, timer);
+ resolve(true);
+ }
+ } else {
+ appendUpdateLog(prog, '正在安装新版本…');
+ if (btn) btn.textContent = '安装中…';
+ fireApply();
+ }
} else if (st === 'error') {
clearInterval(timer);
var statusError = new Error(formatUpdateFailure(s, '更新出错'));
statusError.payload = s;
reject(statusError);
} else if (st === 'idle' && s.downloaded) {
- appendUpdateLog(prog, '下载完成,准备安装…');
- fireApply();
+ if (WBS_PLATFORM === 'win32') {
+ openWindowsInstallerAfterDownload(prog, btn, card, timer, resolve, reject);
+ } else {
+ appendUpdateLog(prog, '下载完成,准备安装…');
+ fireApply();
+ }
} else if (st === 'idle' && s.hasUpdate) {
appendUpdateLog(prog, s.message || '发现新版本,准备更新…');
}
@@ -4461,7 +4985,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var previous = themePane.querySelector('.wbs-theme-opt.active');
themePane.querySelectorAll('.wbs-theme-opt').forEach(function (b) { b.classList.toggle('active', b === segBtn); });
applyTheme(id).then(function () {
- toast('已应用主题「' + (id === 'default' ? 'WorkBuddy 默认主题' : WBS_BRAND + ' 主题') + '」', false, root);
+ var names = { 'default': '默认', 'nebula': WBS_BRAND + ' 主题', 'eye-care': '护眼绿', 'cyber-purple': '赛博紫' };
+ toast('已应用主题「' + (names[id] || id) + '」', false, root);
}).catch(function (er) {
themePane.querySelectorAll('.wbs-theme-opt').forEach(function (b) { b.classList.toggle('active', b === previous); });
toast('应用主题失败: ' + (er.message || er), true, root);
@@ -4531,32 +5056,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
t.value = '';
}
});
- // 毛玻璃控件绑定(元素在主题 pane 构建后才存在)
- blurSwitch = themePane.querySelector('#wbs-blur-switch');
- blurRange = themePane.querySelector('#wbs-blur-range');
- blurVal = themePane.querySelector('#wbs-blur-val');
- blurRow = themePane.querySelector('#wbs-blur-row');
- blurCtrl = themePane.querySelector('#wbs-blur-ctrl');
- if (blurSwitch) {
- blurSwitch.addEventListener('change', function () {
- var enabled = this.checked;
- var px = sliderToBlur(blurRange ? blurRange.value : 80);
- saveBlur(enabled, px);
- applyBlur();
- toast(enabled ? '已开启背景毛玻璃(模糊 ' + px + 'px)' : '已关闭背景毛玻璃', false, root);
- });
- }
- if (blurRange) {
- blurRange.addEventListener('input', function () {
- var px = sliderToBlur(this.value);
- if (blurVal) blurVal.textContent = String(blurRange ? blurRange.value : blurToSlider(px)) + '%';
- if (blurSwitch && blurSwitch.checked) {
- saveBlur(true, px);
- applyBlur();
- }
- });
- }
- applyBlur(); // 同步开关/滑块状态到 UI
loadThemes();
// 背景蒙版滑块:拖动防抖 300ms 调 /api/mask(daemon 保存 + 重应用主题)
var maskRange = themePane.querySelector('#wbs-mask-range');
@@ -4631,23 +5130,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
wireNoDisturbPane();
wireAutoContinuePane();
wireSessionControls();
- // DevTools 按钮
- var devtoolsBtn = enhancePane.querySelector('#wbs-theme-devtools');
- if (devtoolsBtn) {
- devtoolsBtn.addEventListener('click', function () {
- api('/api/devtools-url').then(function (d) {
- if (d && d.ok && d.url) { window.open(d.url, '_blank'); }
- else { toast('无法打开 DevTools:' + ((d && d.error) || '未知错误'), true, root); }
- }).catch(function () {
- toast('无法打开 DevTools:daemon 不可达', true, root);
- });
- });
- }
- // 🔍 元素检查按钮(隐藏入口:连点标题 5 次呼出;按钮点击切换检查模式)
- var inspectBtn = enhancePane.querySelector('#wbs-theme-inspect');
- if (inspectBtn) {
- inspectBtn.addEventListener('click', function () { toggleInspect(); });
- }
+ // (开发调试入口已抽离至独立脚本 picker-internal.js,连点 logo 右侧按钮呼出)
}
// 官方壁纸网格:加载 /api/wallpapers,渲染缩略图,点击切换背景图
@@ -4661,82 +5144,106 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var bodyEl = panel.querySelector('.wbs-body');
if (bodyEl) bodyEl.style.overflowY = 'auto';
}
- function loadWallpapers() {
+ function loadWallpapers(force) {
var grid = root.querySelector('#wbs-wallpapers');
- if (!grid) return;
- if (grid.dataset.loaded) return;
- grid.dataset.loaded = '1';
+ var cgrid = root.querySelector('#wbs-custom-wallpapers');
+ if (!grid && !cgrid) return;
+ if (grid && grid.dataset.loaded && !force) return;
+ if (grid) grid.dataset.loaded = '1';
var base = API.replace(/\/api\/?$/, '');
api('/api/wallpapers').then(function (d) {
var list = d.wallpapers || [];
- if (!list.length) { grid.innerHTML = '<div class="wbs-wp-loading">暂无官方壁纸</div>'; return; }
- var html = '';
- list.forEach(function (w) {
- var wallpaperUrl = base + '/wallpapers/' + encodeURIComponent(w.name);
- html +=
- '<div class="wbs-wp" data-wp="' + escAttr(w.name) + '" title="' + escAttr(w.title) + '">' +
- '<div class="wbs-wp-thumb"><img data-src="' + escAttr(wallpaperUrl) + '" alt="' + escAttr(w.title) + '" loading="lazy"></div>' +
- '<div class="wbs-wp-badge">' + esc(String(w.name).replace(/\D/g, '').replace(/^0+/, '') || w.title) + '</div>' +
- '</div>';
- });
- grid.innerHTML = html;
- // 高亮当前正在使用的壁纸(daemon 按内容哈希匹配返回)
- if (d.currentWallpaper) {
- grid.querySelectorAll('.wbs-wp').forEach(function (c) {
- if (c.getAttribute('data-wp') === d.currentWallpaper) c.classList.add('active');
- });
+ var customList = d.customWallpapers || [];
+ var current = d.currentWallpaper || null;
+ if (grid) {
+ if (!list.length) { grid.innerHTML = '<div class="wbs-wp-loading">暂无官方壁纸</div>'; }
+ else {
+ var html = '';
+ list.forEach(function (w) {
+ var wallpaperUrl = base + '/wallpapers/' + encodeURIComponent(w.name);
+ html +=
+ '<div class="wbs-wp' + (current === w.name ? ' active' : '') + '" data-wp="' + escAttr(w.name) + '" title="' + escAttr(w.title) + '">' +
+ '<div class="wbs-wp-thumb"><img data-src="' + escAttr(wallpaperUrl) + '" alt="' + escAttr(w.title) + '" loading="lazy"></div>' +
+ '<div class="wbs-wp-badge">' + esc(String(w.name).replace(/\D/g, '').replace(/^0+/, '') || w.title) + '</div>' +
+ '</div>';
+ });
+ grid.innerHTML = html;
+ }
+ }
+ if (cgrid) {
+ if (!customList.length) { cgrid.innerHTML = '<div class="wbs-wp-loading">还没有自定义壁纸,先上传一张</div>'; }
+ else {
+ var chtml = '';
+ customList.forEach(function (w) {
+ var wallpaperUrl = base + '/wallpapers/' + encodeURIComponent(w.name);
+ chtml +=
+ '<div class="wbs-wp wbs-wp-custom' + (current === w.name ? ' active' : '') + '" data-wp="' + escAttr(w.name) + '" title="' + escAttr(w.title) + '">' +
+ '<button class="wbs-wp-del" type="button" title="删除壁纸" data-del="' + escAttr(w.name) + '"><span class="wbs-wp-del-ico"></span></button>' +
+ '<div class="wbs-wp-thumb"><img data-src="' + escAttr(wallpaperUrl) + '" alt="' + escAttr(w.title) + '" loading="lazy"></div>' +
+ '</div>';
+ });
+ cgrid.innerHTML = chtml;
+ }
}
// 面板高度固定为主题页高度:首进主题页壁纸渲染后锁定,防止切 tab 高度跳动
lockPanelHeight();
// 逐张 fetch → blob → objectURL 预览(no-store 防 HTTP 缓存旧图——图库重建后同名文件内容会变)
- grid.querySelectorAll('.wbs-wp-thumb img').forEach(function (im) {
- fetch(im.getAttribute('data-src'), { cache: 'no-store' })
- .then(function (r) { return r.ok ? r.blob() : Promise.reject(new Error('HTTP ' + r.status)); })
- .then(function (blob) { im.src = URL.createObjectURL(blob); })
- .catch(function () {
- im.alt = '加载失败';
- im.style.opacity = '.25';
- });
+ var allGrids = [grid, cgrid].filter(Boolean);
+ allGrids.forEach(function (g) {
+ g.querySelectorAll('.wbs-wp-thumb img').forEach(function (im) {
+ fetch(im.getAttribute('data-src'), { cache: 'no-store' })
+ .then(function (r) { return r.ok ? r.blob() : Promise.reject(new Error('HTTP ' + r.status)); })
+ .then(function (blob) { im.src = URL.createObjectURL(blob); })
+ .catch(function () {
+ im.alt = '加载失败';
+ im.style.opacity = '.25';
+ });
+ });
});
- grid.querySelectorAll('.wbs-wp').forEach(function (card) {
- card.addEventListener('click', function () {
- var name = card.getAttribute('data-wp');
- if (card.classList.contains('busy')) return;
- card.classList.add('busy');
- var target = themeSelectValue();
- api('/api/theme-bg', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ id: target, wallpaper: name }),
- }).then(function (r) {
- if (!r || !r.ok) throw new Error((r && r.error) || '切换壁纸失败');
- grid.querySelectorAll('.wbs-wp').forEach(function (c) { c.classList.remove('active'); });
- card.classList.add('active');
- toast('已应用壁纸「' + card.getAttribute('title') + '」', false, root);
- }).catch(function (e) {
- toast('切换壁纸失败: ' + (e.message || e), true, root);
- }).finally(function () { card.classList.remove('busy'); });
+ // 官方/自定义壁纸点击切换(互斥高亮:切换后重载两侧网格同步选中态)
+ allGrids.forEach(function (g) {
+ g.querySelectorAll('.wbs-wp').forEach(function (card) {
+ card.addEventListener('click', function () {
+ var name = card.getAttribute('data-wp');
+ if (card.classList.contains('busy')) return;
+ card.classList.add('busy');
+ var target = themeSelectValue();
+ api('/api/theme-bg', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ id: target, wallpaper: name }),
+ }).then(function (r) {
+ if (!r || !r.ok) throw new Error((r && r.error) || '切换壁纸失败');
+ toast('已应用壁纸「' + (card.getAttribute('title') || name) + '」', false, root);
+ loadWallpapers(true);
+ }).catch(function (e) {
+ toast('切换壁纸失败: ' + (e.message || e), true, root);
+ }).finally(function () { card.classList.remove('busy'); });
+ });
});
});
+ // 自定义壁纸删除(仅 custom 网格):直接删文件 + 刷新;删除的是当前壁纸时提示
+ if (cgrid) {
+ cgrid.querySelectorAll('.wbs-wp-del').forEach(function (btn) {
+ btn.addEventListener('click', function (ev) {
+ ev.stopPropagation();
+ var name = btn.getAttribute('data-del');
+ var card = btn.closest('.wbs-wp');
+ if (card && card.classList.contains('busy')) return;
+ api('/api/custom-wallpapers?name=' + encodeURIComponent(name), { method: 'DELETE' }).then(function (r) {
+ if (!r || !r.ok) throw new Error((r && r.error) || '删除失败');
+ if (name === current) toast('已删除当前壁纸(背景保留不变)', false, root);
+ else toast('已删除壁纸', false, root);
+ loadWallpapers(true);
+ }).catch(function (e) {
+ toast('删除壁纸失败: ' + (e.message || e), true, root);
+ });
+ });
+ });
+ }
}).catch(function () {
- grid.innerHTML = '<div class="wbs-wp-loading">壁纸加载失败(daemon 不可达)</div>';
- });
- }
-
- var workBuddyAiThemeMigrationStarted = false;
- function migrateWorkBuddyAiThemeOnce() {
- if (!WBS_PROFILE_IS_AI || workBuddyAiThemeMigrationStarted) return;
- var migrationKey = workBuddyAiThemeMigrationKey(PROFILE_ID);
- var marker = null;
- try { marker = localStorage.getItem(migrationKey); } catch (_) {}
- if (!shouldMigrateWorkBuddyAiTheme(PROFILE_ID, marker)) return;
- // 同一 build 内先锁住,避免重复点击/重复打开并发发起两次迁移;失败时
- // 解锁,让下次打开仍可重试,而不是把用户永久留在旧主题上。
- workBuddyAiThemeMigrationStarted = true;
- applyTheme('default').then(function () {
- try { localStorage.setItem(migrationKey, '1'); } catch (_) {}
- }).catch(function () {
- workBuddyAiThemeMigrationStarted = false;
+ if (grid) grid.innerHTML = '<div class="wbs-wp-loading">壁纸加载失败(daemon 不可达)</div>';
+ if (cgrid) cgrid.innerHTML = '<div class="wbs-wp-loading">壁纸加载失败(daemon 不可达)</div>';
});
}
@@ -4745,7 +5252,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
panel.classList.toggle('show', open);
fab.classList.toggle('hidden', open); // 打开时隐藏按钮
if (open) {
- migrateWorkBuddyAiThemeOnce(); // WorkDaddy AI 仅首次打开时恢复官方浅色
refresh();
checkForUpdate(); // 打开面板即检测更新(每次打开都强制查一次新版本)
try { acCheckPromptOnOpen(); } catch (e) {} // 每次打开面板:指令块丢失则请求 daemon 补写(无 toast)
@@ -4996,9 +5502,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// ===== 主题系统(WorkDaddy 换肤):segmented 切换 =====
// 主题 = CSS 变量覆盖(--wb-* / --dc-*),daemon 通过 CDP 注入 <style>。
- // 只提供两个入口:官方主题(default) 与 WorkDaddy 官方主题(nebula),其余自定义主题不展示
+ // 只提供四个入口:官方主题(default) 与 WorkDaddy 官方主题(nebula)、官方内置深色主题(eye-care/cyber-purple)
// 默认选中「WorkBuddy 默认主题」(default):未设置/异常时回退到 default 而非 nebula(用户要求)
- var ALLOWED_THEMES = ['default', 'nebula'];
+ var ALLOWED_THEMES = ['default', 'nebula', 'eye-care', 'cyber-purple'];
function loadThemes() {
api('/api/themes')
.then(function (d) {
@@ -5038,267 +5544,35 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}).catch(function () {});
}, 1500);
- // ===== 背景毛玻璃:开关 + 模糊度调节 =====
- // 原理:给内容容器加 backdrop-filter: blur(px),背景图透过半透明容器被模糊(真毛玻璃),文字保持清晰。
- // 通过独立 style 标签注入(优先级高于主题 CSS 的透明背景),关掉即移除。
- var blurRow = root.querySelector('#wbs-blur-row');
- var blurSwitch = root.querySelector('#wbs-blur-switch');
- var blurCtrl = root.querySelector('#wbs-blur-ctrl');
- var blurRange = root.querySelector('#wbs-blur-range');
- var blurVal = root.querySelector('#wbs-blur-val');
- var BLUR_KEY = 'wbsBgBlur';
- var blurStyleEl = null;
- // 滑块 0-100 映射到模糊度 0-20px(每格 0.2px,粒度更细)
- var BLUR_MAX = 20;
- function sliderToBlur(v) { return Math.round((parseInt(v, 10) || 0) * BLUR_MAX / 100 * 10) / 10; }
- function blurToSlider(px) { return Math.round(((parseFloat(px) || 0) / BLUR_MAX) * 100); }
-
- function blurCssFor(px) {
- // 半透明背景 + 毛玻璃:内容容器看到背景图被模糊;侧边栏/主区/弹层都覆盖
- // 背景不加 !important:有背景图的主题(daemon 注入的毛玻璃背景 !important)优先,
- // 无背景图主题时本规则仍提供 38% 半透明效果;blur 值始终由用户滑块控制
- return [
- 'body[data-vscode-theme-name] .teams-container,',
- 'body[data-vscode-theme-name] [data-view-id],',
- 'body[data-vscode-theme-name] .conversation-list,',
- 'body[data-vscode-theme-name] .main-content,',
- 'body[data-vscode-theme-name] [class*="cbChat"],',
- 'body[data-vscode-theme-name] .cb-message,',
- 'body[data-vscode-theme-name] [class*="message-box"] {',
- 'background: color-mix(in srgb, var(--wb-bg-primary) 38%, transparent);',
- 'backdrop-filter: blur(' + px + 'px) saturate(1.15) !important;',
- '-webkit-backdrop-filter: blur(' + px + 'px) saturate(1.15) !important;',
- '}',
- // 输入框区域也要毛玻璃
- 'body[data-vscode-theme-name] [class*="input-area-container"] {',
- 'background: color-mix(in srgb, var(--wb-bg-primary) 52%, transparent);',
- 'backdrop-filter: blur(' + px + 'px) saturate(1.15) !important;',
- '-webkit-backdrop-filter: blur(' + px + 'px) saturate(1.15) !important;',
- '}',
- ].join('');
- }
- function applyBlur() {
- var saved = null;
- try { saved = JSON.parse(localStorage.getItem(BLUR_KEY) || 'null'); } catch (_) {}
- var enabled = !!(saved && saved.enabled);
- var px = saved && typeof saved.blur === 'number' ? saved.blur : 16;
- if (blurSwitch) blurSwitch.checked = enabled;
- if (blurRow) blurRow.style.display = ''; // 行始终可见(后续可优化为仅背景主题显示)
- if (blurCtrl) blurCtrl.style.display = enabled ? '' : 'none';
- if (blurRange) blurRange.value = String(blurToSlider(px));
- if (blurVal) blurVal.textContent = String(blurRange ? blurRange.value : blurToSlider(px)) + '%';
- if (blurStyleEl) { blurStyleEl.remove(); blurStyleEl = null; }
- if (enabled && px > 0) {
- blurStyleEl = document.createElement('style');
- blurStyleEl.id = 'wbs-blur-style';
- blurStyleEl.textContent = blurCssFor(px);
- document.head.appendChild(blurStyleEl);
- }
- }
- function saveBlur(enabled, blur) {
- try { localStorage.setItem(BLUR_KEY, JSON.stringify({ enabled: !!enabled, blur: blur })); } catch (_) {}
- }
- // 毛玻璃开关/滑块事件在 wireThemePane() 中绑定(元素位于主题 pane,构建后才存在)
- // 初始化(读取上次设置;等主题恢复后再应用,避免被主题 CSS 覆盖)
- setBuildTimeout(applyBlur, 1800);
-
- // ===== 开发者工具(类 Chrome DevTools:拾取元素 → 查看样式/主题变量/规则来源 + DevTools)=====
- // 隐藏入口:默认隐藏整个「开发者工具」模块,连续点击面板标题「WorkDaddy」5 次才呼出
- var inspectBtn = null; // 增强 pane 构建后由 wireEnhancePane 赋值
- var inspectTitle = root.querySelector('#wbs-title');
- var inspectHidden = true;
- var titleClickCount = 0;
- var titleClickTimer = null;
- if (inspectTitle) {
- inspectTitle.addEventListener('click', function () {
- titleClickCount += 1;
- clearTimeout(titleClickTimer);
- titleClickTimer = setBuildTimeout(function () { titleClickCount = 0; }, 1200);
- if (titleClickCount >= 5) {
- titleClickCount = 0;
- inspectHidden = !inspectHidden;
- if (enhancePane && !enhancePane.dataset.built) buildEnhancePane();
- if (aboutPane && !aboutPane.dataset.built) buildAboutPane();
- var card = root.querySelector('#wbs-devtools-card');
- if (card) card.style.display = inspectHidden ? 'none' : '';
- try { toast(inspectHidden ? '开发者工具已隐藏' : '开发者工具已呼出', false, root); } catch (_) {}
+ // ===== 元素检查(隐藏入口,实现抽离在 picker-internal.js,git 不跟踪)=====
+ // 连续点击面板标题 5 次 → 在标题右侧显示「🔍 拾取」按钮;点击进入拾取模式。
+ // 实现代码在 picker-internal.js(daemon 拼注入脚本时若有该文件则注入,定义 window.__wbsStartPicked);
+ // 他人环境没有该文件 → 按钮点击时 __wbsStartPicked 不存在 → toast 报错即可,不影响其他功能。
+ var piTitle = root.querySelector('#wbs-title');
+ var piPickBtn = root.querySelector('#wbs-pick-btn');
+ var piClickCount = 0;
+ var piClickTimer = null;
+ if (piTitle) {
+ piTitle.addEventListener('click', function () {
+ piClickCount += 1;
+ clearTimeout(piClickTimer);
+ piClickTimer = setBuildTimeout(function () { piClickCount = 0; }, 1200);
+ if (piClickCount >= 5) {
+ piClickCount = 0;
+ if (piPickBtn) piPickBtn.style.display = '';
+ try { toast('元素检查已呼出', false, root); } catch (_) {}
}
});
}
- var inspectState = { active: false, hoverEl: null };
- var INSPECT_KEYS = [
- ['--wb-bg-primary', '背景-主'], ['--wb-bg-secondary', '背景-面板'], ['--wb-sidebar-bg', '侧边栏背景'],
- ['--wb-color-text-primary', '文字-主'], ['--wb-color-text-secondary', '文字-次'], ['--wb-border-default', '边框'],
- ['--wb-button-primary-bg', '按钮背景'], ['--vscode-editor-background', 'vscode背景'], ['--vscode-editor-foreground', 'vscode文字'],
- ];
- function buildSelector(el) {
- if (!el || el === document.body) return 'body';
- if (el.id) return '#' + el.id;
- var cls = (el.className || '').toString().trim().split(/\s+/).filter(Boolean).slice(0, 2);
- var sel = el.tagName.toLowerCase();
- if (cls.length) sel += '.' + cls.join('.');
- return sel;
- }
- // 元素 query 路径:从 body 到元素的完整 CSS 选择器(带 :nth-child 保证唯一,可直接 document.querySelector)
- function buildQueryPath(el) {
- var parts = [];
- var node = el;
- while (node && node !== document.body && node !== document.documentElement) {
- var seg = node.tagName.toLowerCase();
- if (node.id) { parts.unshift(seg + '#' + node.id); break; }
- var cls = (node.className || '').toString().trim().split(/\s+/).filter(Boolean).slice(0, 2);
- if (cls.length) seg += '.' + cls.join('.');
- else if (node.parentElement) {
- var idx = Array.prototype.indexOf.call(node.parentElement.children, node) + 1;
- seg += ':nth-child(' + idx + ')';
- }
- parts.unshift(seg);
- node = node.parentElement;
- }
- parts.unshift('body');
- return parts.join(' > ');
- }
- function showInspector(el) {
- try {
- var old = document.getElementById('wbs-inspector');
- if (old) old.remove();
- var cs = getComputedStyle(el);
- var r = el.getBoundingClientRect();
- var rows = '';
- var items = [
- ['标签', el.tagName.toLowerCase()], ['尺寸', Math.round(r.width) + ' x ' + Math.round(r.height)],
- ['背景色', cs.backgroundColor], ['文字色', cs.color], ['字号', cs.fontSize],
- ['圆角', cs.borderRadius], ['模糊', cs.backdropFilter === 'none' ? '—' : cs.backdropFilter],
- ];
- for (var i = 0; i < items.length; i++) {
- rows += '<div class="wbs-ins-row"><span>' + esc(items[i][0]) + '</span><code>' + esc(items[i][1] || '—') + '</code></div>';
- }
- var vars = '';
- for (var k = 0; k < INSPECT_KEYS.length; k++) {
- var v = cs.getPropertyValue(INSPECT_KEYS[k][0]).trim();
- vars += '<div class="wbs-ins-row"><span>' + esc(INSPECT_KEYS[k][1]) + ' <em>' + esc(INSPECT_KEYS[k][0]) + '</em></span><code>' + esc(v || '未定义(继承上层)') + '</code></div>';
- }
- var rules = [];
- try {
- for (var s = 0; s < document.styleSheets.length && rules.length < 4; s++) {
- var sheet; try { sheet = document.styleSheets[s]; } catch (e) { continue; }
- var rs; try { rs = sheet.cssRules; } catch (e) { continue; }
- for (var i2 = 0; i2 < rs.length && rules.length < 4; i2++) {
- var rr = rs[i2];
- if (rr.selectorText && rr.style && el.matches(rr.selectorText) &&
- (rr.style.getPropertyValue('background') || rr.style.getPropertyValue('background-color') || rr.style.getPropertyValue('color') || rr.style.getPropertyValue('filter'))) {
- rules.push(rr.selectorText.slice(0, 72));
- }
- }
- }
- } catch (e) {}
- var rulesHtml = rules.length
- ? rules.map(function (x) { return '<div class="wbs-ins-rule">' + esc(x) + '</div>'; }).join('')
- : '<div class="wbs-ins-rule muted">无直接样式规则(颜色来自继承)</div>';
- // 完整报告文本(复制用:选择器 + 基础样式 + 主题变量 + 匹配规则)
- var report = ['🔍 ' + buildSelector(el), ''];
- items.forEach(function (it) { report.push(it[0] + ': ' + (it[1] || '—')); });
- report.push('', '主题变量(当前生效值)');
- INSPECT_KEYS.forEach(function (kv, idx) {
- var v = cs.getPropertyValue(kv[0]).trim();
- report.push(' ' + kv[0] + ' = ' + (v || '未定义(继承上层)'));
- });
- report.push('', '匹配的样式规则');
- if (rules.length) rules.forEach(function (x) { report.push(' ' + x); });
- else report.push(' 无直接样式规则(颜色来自继承)');
- var div = document.createElement('div');
- div.id = 'wbs-inspector';
- div.className = 'wbs-inspector'; // 必须设 class:CSS 选择器是 .wbs-inspector,只设 id 会变全宽 div 掉到页面底部
- // 元素 query 路径(从 body 到该元素的完整 CSS 选择器,可直接用于 document.querySelector)
- var queryPath = buildQueryPath(el);
- div.innerHTML =
- '<div class="wbs-ins-head"><span>🔍 ' + esc(buildSelector(el)) + '</span>' +
- '<span class="wbs-ins-btns"><button class="wbs-ins-copy" type="button" title="复制元素 query 路径(从 body 起的完整 CSS 选择器)">复制路径</button><button class="wbs-ins-repick" type="button">再检查</button><button class="wbs-ins-close" type="button">✕</button></span></div>' +
- '<div class="wbs-ins-sec">元素路径</div><div class="wbs-ins-path">' + esc(queryPath) + '</div>' +
- '<div class="wbs-ins-sec">基础样式</div>' + rows +
- '<div class="wbs-ins-sec">主题变量(当前生效值)</div>' + vars +
- '<div class="wbs-ins-sec">匹配的样式规则</div>' + rulesHtml +
- '<div class="wbs-ins-tip">变量显示「未定义」说明组件颜色来自硬编码,可用「定制」修复 · 「复制路径」把 query 路径贴给 AI 或查 DevTools</div>';
- document.body.appendChild(div);
- div.querySelector('.wbs-ins-close').addEventListener('click', function () { div.remove(); });
- div.querySelector('.wbs-ins-repick').addEventListener('click', function () { div.remove(); startInspect(); });
- div.querySelector('.wbs-ins-copy').addEventListener('click', function () {
- try {
- var ta = document.createElement('textarea');
- ta.value = queryPath;
- ta.style.position = 'fixed';
- ta.style.opacity = '0';
- document.body.appendChild(ta);
- ta.select();
- var ok = false;
- try { ok = document.execCommand('copy'); } catch (_) {}
- ta.remove();
- try { toast(ok ? '已复制元素路径 ✓' : '复制失败,请手动选择', !ok, root); } catch (_) {}
- } catch (e2) {
- try { toast('复制失败:' + String(e2).slice(0, 60), true, root); } catch (_) {}
+ if (piPickBtn) {
+ piPickBtn.addEventListener('click', function () {
+ if (typeof window.__wbsStartPicked === 'function') {
+ window.__wbsStartPicked();
+ } else {
+ toast('元素检查不可用:内部模块未加载', true, root);
}
});
- } catch (err) {
- try { toast('检查失败:' + String(err && err.message || err).slice(0, 80), true, root); } catch (_) {}
- }
- }
- function stopInspect() {
- inspectState.active = false;
- document.removeEventListener('mousemove', onInspectMove, true);
- document.removeEventListener('click', onInspectClick, true);
- document.removeEventListener('keydown', onInspectKey, true);
- if (inspectState.hoverEl) { inspectState.hoverEl.style.outline = ''; inspectState.hoverEl = null; }
- var tip = document.getElementById('wbs-inspect-tip');
- if (tip) tip.remove();
- // 恢复面板显示
- if (root && root.style && inspectState.panelDisplay !== undefined) {
- root.style.display = inspectState.panelDisplay;
- inspectState.panelDisplay = undefined;
- }
- }
- function onInspectMove(e) {
- var el = e.target;
- if (el.closest && (el.closest('.wbs-root') || el.closest('#wbs-inspector'))) return;
- if (inspectState.hoverEl && inspectState.hoverEl !== el) inspectState.hoverEl.style.outline = '';
- el.style.outline = '2px solid #22d3ee';
- el.style.outlineOffset = '-2px';
- inspectState.hoverEl = el;
- }
- function onInspectClick(e) {
- var el = e.target;
- if (el.closest && (el.closest('.wbs-root') || el.closest('#wbs-inspector'))) return;
- e.preventDefault(); e.stopPropagation();
- stopInspect();
- showInspector(el);
- if (inspectBtn) inspectBtn.textContent = '🔍';
- }
- function onInspectKey(e) {
- if (e.key === 'Escape') { stopInspect(); if (inspectBtn) inspectBtn.textContent = '🔍'; }
- }
- function startInspect() {
- if (inspectState.active) return;
- inspectState.active = true;
- // 收起面板:避免面板遮挡浮层/干扰拾取(检查完自动恢复)
- if (root && root.style && root.style.display !== 'none') {
- inspectState.panelDisplay = root.style.display;
- root.style.display = 'none';
- }
- document.addEventListener('mousemove', onInspectMove, true);
- document.addEventListener('click', onInspectClick, true);
- document.addEventListener('keydown', onInspectKey, true);
- var tip = document.createElement('div');
- tip.id = 'wbs-inspect-tip';
- tip.textContent = '拾取模式:移动鼠标高亮元素,点击查看详情(Esc 退出)';
- document.body.appendChild(tip);
- if (inspectBtn) inspectBtn.textContent = '✕';
- }
- // 🔍 按钮切换(增强 pane 构建后由 wireEnhancePane 绑定到按钮点击)
- function toggleInspect() {
- if (inspectState.active) { stopInspect(); if (inspectBtn) inspectBtn.textContent = '🔍 元素检查'; return; }
- startInspect();
- }
- // DevTools 按钮:打开 WorkBuddy 的完整 DevTools(Electron 自带前端,绕开 chrome://inspect 404)
- // 绑定逻辑已迁移到 wireEnhancePane()(按钮位于增强 pane)
+ }
// ===== 头像(官方 footer-brand-logo SVG / 自定义上传,localStorage 持久化,定时保持)=====
var AVATAR_KEY = 'wbsAvatar';
@@ -5426,20 +5700,27 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
full.height = Math.round(img.height * scale);
full.getContext('2d').drawImage(img, 0, 0, full.width, full.height);
var compressed = full.toDataURL('image/webp', 0.82);
- // 目标主题:当前选中的主题;若是 default 则用内置默认深色主题 nebula
- var target = themeSelectValue();
- api('/api/theme-bg', {
+ // 先存入自定义壁纸库(多张),拿到文件名后再应用到当前主题
+ api('/api/custom-wallpapers', {
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ id: target, dataUrl: compressed }),
- }).then(function (d) {
- if (!d || !d.ok) throw new Error((d && d.error) || '替换背景图失败');
- toast('已应用壁纸「' + target + '」', false, root);
- loadThemes();
-
- // 自定义背景图预览
- var preview = root.querySelector('#wbs-bg-preview');
- if (preview) { preview.src = compressed; preview.style.display = 'block'; }
+ body: JSON.stringify({ dataUrl: compressed }),
+ }).then(function (up) {
+ if (!up || !up.ok) throw new Error((up && up.error) || '上传壁纸失败');
+ var name = up.name;
+ // 目标主题:当前选中的主题;若是 default 则用内置默认深色主题 nebula
+ var target = themeSelectValue();
+ return api('/api/theme-bg', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ id: target, custom: name }),
+ }).then(function (d) {
+ if (!d || !d.ok) throw new Error((d && d.error) || '替换背景图失败');
+ toast('已添加并应用自定义壁纸', false, root);
+ loadThemes();
+ // 刷新自定义壁纸网格(含选中态)与当前壁纸高亮
+ loadWallpapers(true);
+ });
}).catch(function (e) {
toast('替换背景图失败: ' + (e.message || e), true, root);
});
@@ -6871,12 +7152,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
syncAutoContinue();
}
- /** 会话模块控件绑定:两个开关(暂存提示词/快捷短语)+ 快捷短语列表(批量/新增)。面板每次打开重建时重绑(元素全新无叠加) */
+ /** 会话模块控件绑定:暂存提示词/消息索引/快捷短语开关 + 快捷短语列表。面板每次打开重建时重绑。 */
function wireSessionControls() {
var pane2 = enhancePane;
if (!pane2) { syncSessionModule(); return; }
var swS = pane2.querySelector('#wbs-sess-stash');
if (swS) swS.addEventListener('change', function () { setSessionSwitchWire('stashEnabled', this); });
+ var swN = pane2.querySelector('#wbs-sess-message-nav');
+ if (swN) swN.addEventListener('change', function () {
+ sessState.messageNav = !!this.checked;
+ writeMessageNavigationEnabled(sessState.messageNav);
+ if (messageNavigation) messageNavigation.setEnabled(sessState.messageNav);
+ });
var swP = pane2.querySelector('#wbs-sess-phrase');
if (swP) swP.addEventListener('change', function () { setSessionSwitchWire('phraseEnabled', this); });
var batchBtn = pane2.querySelector('#wbs-qp-batch');
@@ -6892,12 +7179,65 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
renderQpList();
});
+ var batchCopy = pane2.querySelector('#wbs-qp-copy');
+ if (batchCopy) batchCopy.addEventListener('click', function () {
+ var selected = sessState.phrases.filter(function (phrase) { return !!sessState.qpSel[phrase.id]; });
+ if (!selected.length) { acWeak('请先勾选要复制的短语'); return; }
+ copyPlainText(selected.map(function (phrase) { return phrase.text; }).join('\n')).then(function () {
+ toast('已复制 ' + selected.length + ' 条快捷短语', false, root);
+ }).catch(function (error) { toast(error.message || '复制失败', true, root); });
+ });
+ var batchExport = pane2.querySelector('#wbs-qp-export');
+ if (batchExport) batchExport.addEventListener('click', function () {
+ var ids = Object.keys(sessState.qpSel);
+ if (!ids.length) { acWeak('请先勾选要导出的短语'); return; }
+ openSecureTransferModal({
+ title: '导出快捷短语',
+ requirePassword: true,
+ confirmText: '导出',
+ hint: '将加密导出 ' + ids.length + ' 条快捷短语。',
+ onConfirm: function (password) { return api('/api/quick-phrases/export', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ids: ids, password: password }),
+ }).then(function (result) {
+ downloadTransfer(result, 'WorkDaddy-quick-phrases.json');
+ toast('已导出 ' + result.count + ' 条快捷短语(已加密)', false, root);
+ }); },
+ });
+ });
var batchDel = pane2.querySelector('#wbs-qp-batch-del');
if (batchDel) batchDel.addEventListener('click', function () {
var ids = Object.keys(sessState.qpSel);
if (!ids.length) { acWeak('请先勾选要删除的短语'); return; }
confirmQpDelete(ids);
});
+ var importBtn = pane2.querySelector('#wbs-qp-import');
+ var importFile = pane2.querySelector('#wbs-qp-import-file');
+ if (importBtn && importFile) {
+ importBtn.addEventListener('click', function () { importFile.click(); });
+ importFile.addEventListener('change', function (event) {
+ var file = event.target && event.target.files && event.target.files[0];
+ event.target.value = '';
+ if (!file) return;
+ readTransferFile(file).then(function (content) {
+ openSecureTransferModal({
+ title: '导入快捷短语',
+ requirePassword: true,
+ confirmText: '导入',
+ hint: '输入导出时设置的密码;已有的相同短语会自动跳过。',
+ onConfirm: function (password) { return api('/api/quick-phrases/import', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ content: content, password: password }),
+ }).then(function (result) {
+ applySessionModule(result);
+ toast('已导入 ' + result.imported + ' 条快捷短语' + (result.skipped ? ',跳过 ' + result.skipped + ' 条' : ''), false, root);
+ }); },
+ });
+ }).catch(function (error) { toast(error.message || '读取文件失败', true, root); });
+ });
+ }
var addBtn = pane2.querySelector('#wbs-qp-add');
if (addBtn) addBtn.addEventListener('click', function () { openQpEdit(null); });
syncSessionModule(); // 每次面板打开拉取最新开关与短语(含外部修改)
@@ -7058,7 +7398,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ mode: mode, displaySleep: displaySleep }),
}).then(function (d) {
- var map = { allow: '允许电脑休眠(系统默认)', keep: '持续禁止休眠(保持唤醒)', 'until-done': '所有任务结束后允许休眠(暂禁休眠)' };
+ var map = { allow: '允许电脑休眠(系统默认)', keep: '持续禁止休眠(保持唤醒)', 'until-done': '当前会话结束允许休眠(暂禁休眠)' };
toast('休眠模式已切换为「' + (map[mode] || mode) + '」' + (displaySleep ? ',显示器可单独休眠' : ''), false, root);
syncSleepState();
return d;
@@ -7067,48 +7407,69 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
syncSleepState();
});
}
- // AI 是否正在生成回复(用于 until-done 模式检测"所有任务结束"):存在停止/生成中按钮则忙碌
- function isAiBusy() {
+ // AI 是否正在生成回复(until-done 专用,限定当前会话内,参考 Auto-Continue 的 acActiveConversationId):
+ // 只检查「当前激活会话」的生成状态:停止按钮在输入区工具栏(cr-input-toolbar,全局唯一——只有一个
+ // 激活会话渲染输入区,不会误判其他会话);reasoning streaming 在消息区内。
+ // 返回 { busy, sessionId } —— busy=true 表示锁定的会话仍在生成。
+ // scopeId 为空时按当前激活会话判断;锁定会话已切走(不再是激活会话)= 该会话已结束 → 不忙碌。
+ function isSessionBusy(lockedId) {
try {
- // 停止按钮:操作栏圆形按钮 aria-label 含"停止"或 class 含 stop
- var row = findActionRow();
- if (row) {
- var kids = row.children;
- for (var i = 0; i < kids.length; i++) {
- var k = kids[i];
- var al = (k.getAttribute && k.getAttribute('aria-label')) || '';
- if (/停止|stop/i.test(al)) return true;
- var cls = (k.className && k.className.toString()) || '';
- if (/cb-stop|_stop_/i.test(cls)) return true;
- }
+ var activeId = acActiveConversationId();
+ // 无任何激活会话(或锁定的会话已不是当前会话)→ 视为该会话已结束
+ if (!activeId) return { busy: false, sessionId: activeId || '' };
+ if (lockedId && String(lockedId) !== String(activeId)) return { busy: false, sessionId: activeId };
+ // 停止按钮(5.4.4 实测):发送按钮在生成中变身为 cr-send-button--sending/--stop,aria-label=「停止」,
+ // 位于输入区 cr-input-toolbar(全局唯一当前会话输入区);兜底 cr-btn-stop/cb-stop/_stop_。
+ var stops = document.querySelectorAll(
+ '.cr-send-button.cr-send-button--sending,' +
+ '.cr-send-button[class*="--stop"],' +
+ '[aria-label*="停止"],[aria-label*="stop"],' +
+ '[class*="cr-btn-stop"],[class*="cb-stop"],[class*="_stop_"]'
+ );
+ // 只认可见的(生成中场必然可见)
+ for (var si = 0; si < stops.length; si++) {
+ var rc = stops[si].getBoundingClientRect();
+ if (rc.height > 0 && rc.width > 0) return { busy: true, sessionId: activeId };
}
- // 兜底:reasoning streaming 存在
- var secs = document.querySelectorAll('section[class*=_assistantReasoning_][class*=_streaming_]');
- return secs.length > 0;
- } catch (e) { return false; }
- }
- // until-done 模式:轮询检测任务是否全部结束,结束后自动恢复 allow
+ // 兜底:当前会话消息区内 reasoning streaming 存在
+ var rootEl = document.querySelector('.cr-message-list, .cr-conversation-timeline, .conversation-timeline');
+ var container = rootEl || document;
+ var secs = container.querySelectorAll ? container.querySelectorAll(
+ 'section[class*=_assistantReasoning_][class*=_streaming_],' +
+ '[class*="_assistantReasoning_"][data-wbs-theme-state="streaming"]'
+ ) : [];
+ if (secs.length > 0) return { busy: true, sessionId: activeId };
+ return { busy: false, sessionId: activeId };
+ } catch (e) { return { busy: false, sessionId: acActiveConversationId ? acActiveConversationId() : '' }; }
+ }
+ // until-done 模式:锁定开启时的当前会话,轮询该会话是否仍在生成;会话结束(或切走)自动恢复 allow。
+ // 只监听当前会话(参考 Auto-Continue 的 acActiveConversationId 定位会话),不做全局任务扫描。
+ var sleepUntilDoneSession = null; // 开启 until-done 时锁定的会话 ID
function startUntilDoneCheck() {
if (sleepUntilDoneCheck) return;
+ // 开启时锁定当前激活会话;没有任何会话则视为无需防休眠(直接不启动,由开启校验兜底)
+ sleepUntilDoneSession = acActiveConversationId() || null;
sleepUntilDoneCheck = setBuildInterval(function () {
if (!alive) { stopUntilDoneCheck(); return; }
if (sleepMode !== 'until-done') { stopUntilDoneCheck(); return; }
- if (!isAiBusy()) {
- // 连续空闲:任务已结束,自动恢复允许休眠
+ var st = isSessionBusy(sleepUntilDoneSession);
+ if (!st.busy) {
+ // 锁定的会话已结束(或已切到别的会话/FAB 呼吸灯熄灭)→ 自动恢复允许休眠
stopUntilDoneCheck();
api('/api/sleep-mode', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ mode: 'allow', displaySleep: false }),
}).then(function () {
- toast('所有 AI 任务已完成,已自动恢复「允许电脑休眠」', false, root);
+ toast('当前会话已完成,已自动恢复「允许电脑休眠」', false, root);
syncSleepState();
}).catch(function () { syncSleepState(); });
}
- }, 5000);
+ }, 3000);
}
function stopUntilDoneCheck() {
if (sleepUntilDoneCheck) { clearInterval(sleepUntilDoneCheck); sleepUntilDoneCheck = null; }
+ sleepUntilDoneSession = null;
}
// 同步防休眠状态:三模式 radio + 显示器开关 + 状态文字 + 悬浮按钮角标(daemon 重启/状态变化后保持一致)
function syncSleepState() {
@@ -7124,19 +7485,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var drow = pcPane.querySelector('#wbs-display-sleep-row');
if (drow) drow.style.display = preventing ? '' : 'none';
}
- var dot = root.querySelector('.wbs-fab-sleep-dot');
+ var dot = root.querySelector('#wbs-fab-sleep-light');
if (dot) {
var on = preventing;
- // 允许电脑休眠(allow):完全不显示角标;禁止休眠时才亮起
- dot.style.display = on ? '' : 'none';
- dot.classList.toggle('on', on);
- dot.classList.toggle('until-done', d.mode === 'until-done');
+ // 默认黑色;禁止休眠时天线圆点亮起呼吸
+ dot.classList.remove('sleep-on', 'sleep-until-done');
+ if (on) {
+ dot.classList.add(d.mode === 'until-done' ? 'sleep-until-done' : 'sleep-on');
+ }
var t = '允许电脑休眠(默认)';
var antiLock = d.antiLock === true; // daemon 是否已启用防锁屏(UserIsActive 断言)
if (d.mode === 'keep') t = '持续禁止休眠:电脑/显示器保持唤醒' + (antiLock ? ',已防锁屏' : '');
if (d.mode === 'keep' && d.displaySleep) t = '持续禁止休眠:仅阻止系统睡眠,显示器可黑屏(可能锁屏)';
- if (d.mode === 'until-done') t = '任务结束后允许休眠:AI 回复期间保持唤醒' + (antiLock ? ',已防锁屏' : '');
- if (d.mode === 'until-done' && d.displaySleep) t = '任务结束后允许休眠:暂禁中,显示器可黑屏(可能锁屏)';
+ if (d.mode === 'until-done') t = '当前会话结束允许休眠:本会话回复中保持唤醒,结束后自动恢复' + (antiLock ? ',已防锁屏' : '');
+ if (d.mode === 'until-done' && d.displaySleep) t = '当前会话结束允许休眠:暂禁中,显示器可黑屏(可能锁屏)';
dot.title = t;
}
var fab = root.querySelector('.wbs-fab');
@@ -7803,13 +8165,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
sessionHealthTimer = null;
});
registerDisposer(function () {
- stopInspect();
+ try { if (typeof window.__wbsStopPicked === 'function') window.__wbsStopPicked(); } catch (e) {}
var inspector = document.getElementById('wbs-inspector');
- if (inspector) inspector.remove();
+ if (inspector && inspector.__wbsClose) inspector.__wbsClose();
+ else if (inspector) inspector.remove();
});
registerDisposer(function () {
restoreAvatarDom();
- if (blurStyleEl) { blurStyleEl.remove(); blurStyleEl = null; }
root.remove();
stashBtn.remove();
exploreBtn.remove();
@@ -7879,42 +8241,64 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
css.textContent = [
'.wbs-root{position:fixed;right:22px;bottom:22px;z-index:2147483647;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;font-size:13px;color:#1f1f1f;-webkit-font-smoothing:antialiased}',
'.wbs-root.wbs-no-stash .wbs-stash-inline{display:none !important}',
+ /* 会话消息索引:跟随官方消息视口定位,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-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}',
+ '.wbs-message-nav-marker{display:flex;width:22px;height:var(--wbs-message-nav-marker-height,12px);min-height:var(--wbs-message-nav-marker-height,12px);box-sizing:border-box;flex:0 0 var(--wbs-message-nav-marker-height,12px);align-items:center;justify-content:center;padding:0;border:1px solid transparent;border-radius:4px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 10%,transparent);color:var(--wb-icon-secondary,#72757d);cursor:pointer;outline:none;transition:background-color .18s ease,color .18s ease,border-color .18s ease,box-shadow .18s ease,backdrop-filter .18s ease}',
+ '.wbs-message-nav-marker:hover,.wbs-message-nav-marker:focus-visible{border-color:var(--wb-border-subtle,rgba(20,24,32,.14));background:color-mix(in srgb,var(--wb-bg-hover,rgba(0,0,0,.06)) 82%,var(--wb-bg-popover,#fff));color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 3px 10px rgba(24,28,36,.10);backdrop-filter:blur(10px) saturate(1.1);-webkit-backdrop-filter:blur(10px) saturate(1.1)}',
+ '.wbs-message-nav-marker:focus-visible{box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 62%,transparent),0 3px 10px rgba(24,28,36,.10)}',
+ '.wbs-message-nav-dot{display:block;width:5px;height:min(2px,var(--wbs-message-nav-marker-height,12px));border-radius:2px;background:currentColor;opacity:.62;transition:width .18s ease,opacity .18s ease}',
+ '.wbs-message-nav-marker:hover .wbs-message-nav-dot,.wbs-message-nav-marker:focus-visible .wbs-message-nav-dot{width:11px;opacity:.82}',
+ '.wbs-message-nav-marker.is-active .wbs-message-nav-dot{width:14px;opacity:1}',
+ '.wbs-message-nav-tooltip{position:absolute;width:var(--wbs-message-nav-tooltip-max,300px);max-height:min(42vh,320px);box-sizing:border-box;overflow:hidden;padding:10px 11px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.14));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 84%,transparent);color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 12px 34px rgba(20,24,32,.18),inset 0 1px 0 rgba(255,255,255,.38);backdrop-filter:blur(22px) saturate(1.24);-webkit-backdrop-filter:blur(22px) saturate(1.24);pointer-events:none;opacity:0;transform:translateY(-50%) translateX(3px);transition:opacity .18s ease,transform .18s ease}',
+ '.wbs-message-nav-tooltip.is-left{right:calc(100% + 10px)}.wbs-message-nav-tooltip.is-right{left:calc(100% + 10px)}',
+ '.wbs-message-nav-tooltip.is-visible{opacity:1;transform:translateY(-50%) translateX(0)}',
+ '.wbs-message-nav-prompt,.wbs-message-nav-response{display:-webkit-box;overflow:hidden;-webkit-box-orient:vertical;word-break:break-word;letter-spacing:0}',
+ '.wbs-message-nav-prompt{-webkit-line-clamp:4;font-size:12px;font-weight:600;line-height:1.55;color:var(--wb-color-text-primary,#1f1f1f)}',
+ '.wbs-message-nav-response{-webkit-line-clamp:6;margin-top:7px;padding-top:7px;border-top:1px solid var(--wb-border-subtle,rgba(20,24,32,.12));font-size:11px;font-weight:400;line-height:1.55;color:var(--wb-color-text-secondary,#5f626a)}',
+ '.wbs-message-nav-highlight{animation:wbs-message-nav-highlight .7s ease-out}',
+ '@keyframes wbs-message-nav-highlight{0%{box-shadow:0 0 0 3px color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 48%,transparent)}100%{box-shadow:0 0 0 8px transparent}}',
+ 'html.cb-dark .wbs-message-nav-rail,html[data-theme="dark"] .wbs-message-nav-rail,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 14%,transparent);border-color:transparent;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}',
+ 'html.cb-dark .wbs-message-nav-rail:hover,html.cb-dark .wbs-message-nav-rail:focus-within,html[data-theme="dark"] .wbs-message-nav-rail:hover,html[data-theme="dark"] .wbs-message-nav-rail:focus-within,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail:hover,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail:focus-within{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 44%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.12));box-shadow:0 6px 20px rgba(0,0,0,.28);backdrop-filter:blur(14px) saturate(1.12);-webkit-backdrop-filter:blur(14px) saturate(1.12)}',
+ 'html.cb-dark .wbs-message-nav-tooltip,html[data-theme="dark"] .wbs-message-nav-tooltip,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-tooltip{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 70%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.14));color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 14px 38px rgba(0,0,0,.42),inset 0 1px 0 rgba(255,255,255,.08)}',
+ '@media (prefers-reduced-motion:reduce){.wbs-message-nav-marker,.wbs-message-nav-dot,.wbs-message-nav-tooltip{transition:none!important}.wbs-message-nav-highlight{animation:none!important}}',
/* 机器人悬浮按钮(bitter-dragon-16 移植):静态版 0.5 倍 · 无头顶尖角 · 眼睛双眨 */
'.wbs-fab{position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;will-change:right,bottom}',
- '.wbs-fab-sleep-dot{position:absolute;top:-4px;right:-4px;width:18px;height:18px;border-radius:50%;background:rgba(126,128,138,.55);border:2px solid #141416;box-shadow:0 1px 3px rgba(0,0,0,.5);transition:background .25s,box-shadow .25s;z-index:3}',
'.wbs-fab-health-dot{position:absolute;top:-5px;left:-5px;width:14px;height:14px;border-radius:50%;background:#8b8f98;border:2px solid #141416;box-shadow:0 1px 3px rgba(0,0,0,.5);z-index:3}',
'.wbs-fab-health-dot.running{background:#4da3ff}.wbs-fab-health-dot.blocked{background:#ffb03a}.wbs-fab-health-dot.error{background:#ef6262}.wbs-fab-health-dot.suspected{background:#f08a3c}.wbs-fab-health-dot.stopped{background:#9ca3af}',
'.wbs-health-status{display:none;align-items:center;min-height:18px;padding:2px 7px;border-radius:999px;font-size:10px;line-height:14px;white-space:nowrap;color:var(--wb-color-text-secondary,#666);background:var(--wb-bg-tertiary,#f2f2f2)}',
'.wbs-health-status.running,.wbs-health-status.blocked,.wbs-health-status.error,.wbs-health-status.suspected,.wbs-health-status.stopped{display:inline-flex}',
'.wbs-health-status.running{color:#2369a8;background:rgba(77,163,255,.14)}.wbs-health-status.blocked{color:#9a5b00;background:rgba(255,176,58,.18)}.wbs-health-status.error{color:#a52828;background:rgba(239,98,98,.16)}.wbs-health-status.suspected{color:#9a4d0a;background:rgba(240,138,60,.17)}.wbs-health-status.stopped{color:var(--wb-color-text-secondary,#666)}',
'html.cb-dark .wbs-health-status.running,html[data-theme="dark"] .wbs-health-status.running{color:#b9dcff;background:rgba(77,163,255,.22)}html.cb-dark .wbs-health-status.blocked,html[data-theme="dark"] .wbs-health-status.blocked{color:#ffd58d;background:rgba(255,176,58,.24)}html.cb-dark .wbs-health-status.error,html[data-theme="dark"] .wbs-health-status.error{color:#ffb3b3;background:rgba(239,98,98,.25)}html.cb-dark .wbs-health-status.suspected,html[data-theme="dark"] .wbs-health-status.suspected{color:#ffc18d;background:rgba(240,138,60,.24)}',
- '.wbs-fab-sleep-dot.on{background:#2ee59d;border-color:#0e3d2a;box-shadow:0 0 8px 1px rgba(46,229,157,.8);animation:wbs-sleep-pulse 2.2s ease-in-out infinite}',
- '.wbs-fab-sleep-dot.on.until-done{background:#ffb03a;border-color:#5c3a08;box-shadow:0 0 8px 1px rgba(255,176,58,.85);animation:wbs-sleep-pulse-amber 2.2s ease-in-out infinite}',
+ /* 休眠呼吸灯 keyframes(天线圆点禁用休眠时呼吸;默认毛玻璃由 .wbs-fab-antenna-dot 提供) */
'@keyframes wbs-sleep-pulse{0%,100%{box-shadow:0 0 5px 1px rgba(46,229,157,.6)}50%{box-shadow:0 0 13px 4px rgba(46,229,157,.95)}}',
'@keyframes wbs-sleep-pulse-amber{0%,100%{box-shadow:0 0 5px 1px rgba(255,176,58,.6)}50%{box-shadow:0 0 13px 4px rgba(255,176,58,.95)}}',
'.wbs-fab.hidden{display:none}',
'.wbs-fab .click{position:relative}',
- '.wbs-fab .click > span:not(.wbs-fab-antenna):not(.wbs-fab-ear){display:none}',
+ '.wbs-fab .click > span:not(.wbs-fab-antenna){display:none}',
'.wbs-fab .button.shadow{display:none}',
- '.wbs-fab .button{position:relative;left:0;top:0;transform:none;cursor:pointer;border:solid 4px rgba(255,255,255,0);background-color:#141416;font-size:20px;color:#fff;border-color:rgba(255,255,255,0);box-shadow:0 4px 14px rgba(0,0,0,.45);border-radius:50px;display:flex;align-items:center;justify-content:center;width:100px;height:48px;box-sizing:content-box;padding:0;margin:0;outline:none;transition:background-color .2s,color .2s}',
+ '.wbs-fab .button{position:relative;left:0;top:0;transform:none;cursor:pointer;border:solid 4px rgba(255,255,255,0);background-color:rgba(20,20,22,.55);backdrop-filter:blur(14px) saturate(1.3);-webkit-backdrop-filter:blur(14px) saturate(1.3);font-size:20px;color:#fff;border-color:rgba(255,255,255,0);box-shadow:0 4px 14px rgba(0,0,0,.45),inset 0 0 0 1px rgba(255,255,255,.08);border-radius:50px;display:flex;align-items:center;justify-content:center;width:100px;height:48px;box-sizing:content-box;padding:0;margin:0;outline:none;transition:background-color .2s,color .2s}',
/* 贴消息队列时(queue 上方)保持纯色背景(与默认黑色一致,逻辑保留) */
'.wbs-fab.fab--solid .button{background:#141416;box-shadow:0 4px 14px rgba(0,0,0,.45)}',
'.wbs-fab .button:before,.wbs-fab .button:after{display:none}',
'.wbs-fab .button.up{z-index:2}',
- '.wbs-fab-antenna{position:absolute;left:50%;top:-20px;width:4px;height:18px;transform:translateX(-50%);background:#141416;border-radius:3px;z-index:1;pointer-events:none}',
- '.wbs-fab-antenna-dot{position:absolute;left:50%;top:-7px;width:14px;height:14px;transform:translateX(-50%);border-radius:50%;background:#141416}',
- '.wbs-fab-ear{position:absolute;top:50%;width:20px;height:30px;transform:translateY(-50%);border-radius:58% 38% 38% 58% / 50%;background:#141416;overflow:hidden;z-index:1;pointer-events:none}',
- '.wbs-fab-ear::before{content:"";position:absolute;top:4px;left:4px;width:12px;height:22px;border-radius:58% 38% 38% 58% / 50%;background:#141416}',
- '.wbs-fab-ear::after{content:"";position:absolute;top:10px;left:8px;width:4px;height:10px;border-radius:50%;background:#141416}',
- '.wbs-fab-ear-left{left:-11px;transform:translateY(-50%) rotate(-8deg)}',
- '.wbs-fab-ear-right{right:-11px;transform:translateY(-50%) rotate(8deg);border-radius:38% 58% 58% 38% / 50%}',
- '.wbs-fab-ear-right::before{left:4px;border-radius:38% 58% 58% 38% / 50%}',
+ /* 天线:SVG mask 数学绘制「圆 + 杆」一体图形(用户 08-30 01:22 修正杆底穿透:设计值 +4px 上移,
+ scale(0.5) 折算后杆底视觉停在按钮顶上方约 2px,不再穿入头部) */
+ '.wbs-fab-antenna{position:absolute;left:50%;top:-28px;width:14px;height:24px;transform:translateX(-50%);background:rgba(20,20,22,.55);backdrop-filter:blur(14px) saturate(1.3);-webkit-backdrop-filter:blur(14px) saturate(1.3);z-index:2;pointer-events:none;mask-image:url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 24\'><rect x=\'5\' y=\'14\' width=\'4\' height=\'10\'/><circle cx=\'7\' cy=\'7\' r=\'7\'/></svg>");-webkit-mask-image:url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 24\'><rect x=\'5\' y=\'14\' width=\'4\' height=\'10\'/><circle cx=\'7\' cy=\'7\' r=\'7\'/></svg>");mask-size:14px 24px;-webkit-mask-size:14px 24px;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat}',
+ /* 呼吸灯圆点:独立于 mask 容器(避免 mask/backdrop-filter 裁剪呼吸辉光),相对 button 定位到天线圆点位置(ant top:-28 内圆占 y0~14 → button 上 -28~-14) */
+ '.wbs-fab-antenna-dot{position:absolute;left:50%;top:-28px;width:14px;height:14px;transform:translateX(-50%);border-radius:50%;background:transparent;pointer-events:none;z-index:4}',
+ /* 休眠呼吸灯:天线顶部圆点(用户 08-30 00:20 要求替代右上角绿点;08-30 00:37 默认改毛玻璃半透明而非纯黑)——默认毛玻璃,禁止休眠时绿/琥珀呼吸 */
+ '#wbs-fab-sleep-light{transition:background .25s,box-shadow .25s}',
+ '#wbs-fab-sleep-light.sleep-on{background:rgba(46,229,157,.85);box-shadow:0 0 8px 2px rgba(46,229,157,.85);animation:wbs-sleep-pulse 2.2s ease-in-out infinite}',
+ '#wbs-fab-sleep-light.sleep-until-done{background:rgba(255,176,58,.85);box-shadow:0 0 8px 2px rgba(255,176,58,.85);animation:wbs-sleep-pulse-amber 2.2s ease-in-out infinite}',
'.wbs-fab .click .button .speak~.speak{display:none}',
'.wbs-fab .speak{position:relative;z-index:2;font-size:15px}',
'.wbs-fab .wrap{position:relative;width:100px;height:40px;margin:0 2rem;color:#fff;line-height:40px;font-size:2rem;text-align:center;font-weight:400;margin-bottom:0;display:flex;gap:5px}',
'.wbs-fab .eye{position:relative;margin:auto;top:0;bottom:0;background:#fff;width:40px;height:40px;border-radius:50%;display:inline-block;animation:wbs-cc-double-blink 4s cubic-bezier(0.785,0.135,0.15,0.86) infinite;overflow:hidden}',
'@keyframes wbs-cc-double-blink{0%,8%{height:40px}10%,12%{height:10px}13%{height:40px}14%,16%{height:0}18%,100%{height:40px}}',
- '.wbs-fab .eye:before{content:"";position:absolute;margin:auto;width:10px;height:10px;left:0;right:0;top:0;bottom:0;border-radius:50%;background:#141416}',
+ '.wbs-fab .eye:before{content:"";position:absolute;margin:auto;width:10px;height:10px;left:0;right:0;top:0;bottom:0;border-radius:50%;background:rgba(20,20,22,.55);backdrop-filter:blur(14px) saturate(1.3);-webkit-backdrop-filter:blur(14px) saturate(1.3);box-shadow:inset 0 0 3px rgba(0,0,0,.35),0 0 0 1px rgba(255,255,255,.14)}',
'.wbs-fab .down:before{animation:wbs-cc-downb 4s cubic-bezier(0.785,0.135,0.15,0.86) infinite}',
'@keyframes wbs-cc-downb{0%,10%{top:0;left:-10px}20%,40%{top:50%;left:-10px}50%,100%{top:0;left:-10px}}',
'.wbs-fab .right-blink:before{animation:wbs-cc-rightb 4s cubic-bezier(0.785,0.135,0.15,0.86) infinite}',
@@ -7931,7 +8315,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-panel.show{display:flex}',
'.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:default;user-select:none}',
+ '.wbs-title{font-size:16px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);letter-spacing:.3px;cursor:pointer;user-select:none}',
+ /* 元素检查拾取按钮(隐藏入口,连点标题 5 次显示) */
+ '.wbs-pick-btn{flex:0 0 auto;width:22px;height:22px;border:none;border-radius:7px;background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 14%,transparent);color:var(--wb-accent-blue,#4f86ff);font-size:12px;line-height:1;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:background .15s}',
+ '.wbs-pick-btn:hover{background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 24%,transparent)}',
'.wbs-ghbtn{display:flex;align-items:center;justify-content:center;width:24px;height:24px;flex-shrink:0;color:var(--wb-icon-tertiary,#999);border-radius:6px;text-decoration:none;transition:color .15s,background .15s}',
'.wbs-ghbtn:hover{color:var(--wb-color-text-primary,#1f1f1f);background:var(--wb-bg-hover,#f5f5f5)}',
'.wbs-ghbtn svg{display:block}',
@@ -8041,34 +8428,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-theme-select:focus{border-color:var(--wb-border-strong,#bbb)}',
'.wbs-theme-upload{flex-shrink:0;padding:7px 12px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#555);font-size:12px;cursor:pointer;line-height:1;transition:all .15s}',
'.wbs-theme-upload:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);border-color:var(--wb-border-strong,#bbb)}',
- '.wbs-theme-inspect{flex-shrink:0;padding:7px 10px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#555);font-size:12px;cursor:pointer;line-height:1;transition:all .15s}',
- '.wbs-theme-inspect:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);border-color:var(--wb-border-strong,#bbb)}',
- '.wbs-theme-inspect.active{background:#22d3ee;color:#04222b;border-color:#22d3ee}',
- '.wbs-theme-devtools{flex-shrink:0;padding:7px 10px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#555);font-size:11px;cursor:pointer;line-height:1;transition:all .15s}',
- '.wbs-theme-devtools:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);border-color:var(--wb-border-strong,#bbb)}',
- '.wbs-ac-log-wrap{margin-top:8px;border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 55%,transparent);overflow:hidden}',
- '.wbs-ac-log-head{display:flex;align-items:center;justify-content:space-between;padding:5px 8px;font-size:11px;color:var(--wb-icon-secondary,#555);border-bottom:1px solid var(--wb-border-subtle,#f0f0f0)}',
- '.wbs-ac-log-clear{cursor:pointer;color:var(--wb-icon-tertiary,#999);user-select:none}',
- '.wbs-ac-log-clear:hover{color:var(--wb-color-text-primary,#1f1f1f)}',
- '.wbs-ac-log{margin:0;padding:6px 8px;max-height:180px;overflow:auto;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;line-height:1.55;color:var(--wb-icon-secondary,#555);white-space:pre-wrap;word-break:break-all}',
- /* 元素检查器浮层 */
- '.wbs-inspector{position:fixed;right:16px;top:16px;width:360px;max-height:calc(100vh - 40px);overflow:auto;background:var(--wb-bg-popover,#fff);border:1px solid var(--wb-border-default,#e5e5e5);border-radius:12px;box-shadow:0 8px 30px rgba(0,0,0,.18);z-index:2147483647;font-size:12px;color:var(--wb-color-text-primary,#1f1f1f);font-family:-apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif}',
- '.wbs-ins-head{display:flex;justify-content:space-between;align-items:center;padding:10px 12px;border-bottom:1px solid #eee;font-weight:600;position:sticky;top:0;background:var(--wb-bg-popover,#fff);z-index:1;word-break:break-all}',
- '.wbs-ins-btns{display:flex;gap:6px;flex-shrink:0;margin-left:8px}',
- '.wbs-ins-btns button{border:1px solid #ddd;background:var(--wb-bg-popover,#fff);border-radius:6px;padding:3px 8px;font-size:11px;cursor:pointer;color:var(--wb-icon-secondary,#555);line-height:1}',
- '.wbs-ins-btns button:hover{background:var(--wb-bg-hover,#f5f5f5)}',
- '.wbs-ins-btns .wbs-ins-copy{background:#22d3ee;border-color:#22d3ee;color:#04222b;font-weight:600}',
- '.wbs-ins-btns .wbs-ins-copy:hover{background:#67e8f9;border-color:#67e8f9}',
- '.wbs-ins-sec{padding:8px 12px 2px;font-size:11px;color:var(--wb-icon-tertiary,#888);font-weight:600}',
- '.wbs-ins-row{display:flex;justify-content:space-between;gap:8px;padding:3px 12px;align-items:center}',
- '.wbs-ins-row span{color:#666;flex-shrink:0;white-space:nowrap}',
- '.wbs-ins-row span em{font-style:normal;color:#aaa;font-size:10px;margin-left:4px;font-family:ui-monospace,Menlo,monospace}',
- '.wbs-ins-row code{font-family:ui-monospace,Menlo,monospace;font-size:11px;color:#1a7f37;word-break:break-all;text-align:right}',
- '.wbs-ins-rule{font-family:ui-monospace,Menlo,monospace;font-size:10px;color:var(--wb-icon-secondary,#555);background:#f7f7f7;border-radius:4px;margin:2px 12px;padding:3px 6px;word-break:break-all}',
- '.wbs-ins-path{font-family:ui-monospace,Menlo,monospace;font-size:10px;color:#0a5fd0;background:#f2f7ff;border-radius:4px;margin:0 12px 4px;padding:5px 8px;word-break:break-all;line-height:1.5}',
- '.wbs-ins-rule.muted{color:var(--wb-icon-tertiary,#999)}',
- '.wbs-ins-tip{padding:8px 12px;font-size:10px;color:var(--wb-icon-tertiary,#999);border-top:1px solid #eee;line-height:1.6}',
- '#wbs-inspect-tip{position:fixed;left:50%;top:12px;transform:translateX(-50%);background:rgba(34,211,238,.95);color:#04222b;padding:6px 16px;border-radius:20px;font-size:12px;z-index:2147483647;box-shadow:0 4px 12px rgba(0,0,0,.15);pointer-events:none;white-space:nowrap}',
+'.wbs-ac-log-wrap{margin-top:8px;border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 55%,transparent);overflow:hidden}',
+'.wbs-ac-log-head{display:flex;align-items:center;justify-content:space-between;padding:5px 8px;font-size:11px;color:var(--wb-icon-secondary,#555);border-bottom:1px solid var(--wb-border-subtle,#f0f0f0)}',
+'.wbs-ac-log-clear{cursor:pointer;color:var(--wb-icon-tertiary,#999);user-select:none}',
+'.wbs-ac-log-clear:hover{color:var(--wb-color-text-primary,#1f1f1f)}',
+'.wbs-ac-log{margin:0;padding:6px 8px;max-height:180px;overflow:auto;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;line-height:1.55;color:var(--wb-icon-secondary,#555);white-space:pre-wrap;word-break:break-all}',
/* 决策弹窗开关(iOS 风格 switch,跟随主题按钮色) */
'.wbs-ask-row{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:8px}',
'.wbs-ask-label{display:flex;align-items:baseline;gap:6px;font-size:12px;color:var(--wb-color-text-secondary,#444);font-weight:600;min-width:0;line-height:1.3}',
@@ -8090,7 +8454,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
/* 所见即所得定制器浮层 */
/* 暂存提示词:position: fixed 用 right 锚定(left:auto),hover 时 width 增大 → 左边向左展开(参考 wbs-fab);默认隐藏,JS 控制 display */
'.wbs-stash-inline{position:fixed;left:auto;display:flex;align-items:center;justify-content:flex-start;gap:0;width:32px;height:32px;border-radius:50%;background:var(--wb-button-primary-bg);cursor:pointer;flex-shrink:0;color:var(--wb-button-primary-fg);box-shadow:0 1px 3px rgba(0,0,0,.2);overflow:hidden;padding:0 8px;transition:width .18s,border-radius .18s,padding .15s,background .15s;z-index:auto;top:0;right:0}',
- // AI 端内联进操作栏按钮组(flex):取消 fixed 参与布局,保持与其他按钮一致的圆形
+ // 新版布局内联进操作栏按钮组(flex):取消 fixed 参与布局,保持与其他按钮一致的圆形
'.wbs-stash-inline.wbs-stash-inline-inline{position:static;left:auto;right:auto;top:auto;border-radius:50%;box-shadow:none}',
'.wbs-stash-inline.wbs-stash-inline-inline:hover{width:113px;border-radius:40px}',
'.wbs-stash-inline .wbs-stash-ico{display:flex;align-items:center;justify-content:center;flex-shrink:0}',
@@ -8103,7 +8467,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-stash-inline.wbs-explore-inline:hover{width:32px;height:32px;border-radius:50%;padding:0 8px}',
/* 图标常显;hover 无任何自身动画 */
'.wbs-explore-ico{display:flex;align-items:center;justify-content:center}',
- /* AI 端内联模式:弹层(absolute)必须以按钮自身为定位上下文——static 会让 .wbs-explore-pop 的 bottom:100% 上溯到最近的 positioned 祖先(操作栏外壳),导致弹层大幅偏离按钮;z-index 抬升让按钮成为独立层叠上下文,弹层在其内不受操作栏兄弟元素压制 */
+ /* 新版内联模式:弹层(absolute)必须以按钮自身为定位上下文——static 会让 .wbs-explore-pop 的 bottom:100% 上溯到最近的 positioned 祖先(操作栏外壳),导致弹层大幅偏离按钮;z-index 抬升让按钮成为独立层叠上下文,弹层在其内不受操作栏兄弟元素压制 */
'.wbs-explore-inline.wbs-stash-inline-inline{position:relative;z-index:99999}',
/* 按钮不可点击缩放(点击不改变按钮自身与面板大小),菜单全由 hover 展示 */
'.wbs-explore-inline:active{transform:none}',
@@ -8442,9 +8806,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-wp.active .wbs-wp-badge{background:#fff;color:#0a0a0a}',
'.wbs-wp-loading{padding:20px 0;text-align:center;color:var(--wb-icon-tertiary,#999);font-size:12px;grid-column:1/-1}',
'.wbs-wp.busy{opacity:.6;pointer-events:none}',
- /* 主题切换 segmented(默认主题 / WorkDaddy 主题):样式与下方壁纸来源切换按钮统一 */
+ /* 自定义壁纸网格:三列布局、删除按钮(悬浮显示)、选中矢量角标 */
+ '.wbs-custom-wallpapers{grid-template-columns:repeat(3,1fr);margin-top:10px}',
+ '.wbs-wp-custom .wbs-wp-del{position:absolute;top:4px;left:4px;z-index:3;width:20px;height:20px;border:none;border-radius:6px;background:rgba(0,0,0,.55);color:#fff;cursor:pointer;opacity:0;transition:opacity .15s;backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);padding:0;font-family:inherit;display:flex;align-items:center;justify-content:center}',
+ '.wbs-wp-custom:hover .wbs-wp-del{opacity:1}',
+ '.wbs-wp-custom .wbs-wp-del:hover{background:#e24b4a}',
+ '.wbs-wp-del-ico{position:relative;display:block;width:10px;height:10px}',
+ '.wbs-wp-del-ico::before,.wbs-wp-del-ico::after{content:"";position:absolute;left:50%;top:50%;width:10px;height:1.5px;background:currentColor;border-radius:1px;transform:translate(-50%,-50%) rotate(45deg)}',
+ '.wbs-wp-del-ico::after{transform:translate(-50%,-50%) rotate(-45deg)}',
+ '.wbs-wp-custom.active::after{content:"";position:absolute;top:4px;right:4px;width:16px;height:16px;border-radius:50%;background:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px rgba(255,255,255,.85)}',
+ '.wbs-wp-custom.active::before{content:"";position:absolute;top:8px;right:8px;width:8px;height:5px;border-left:2px solid var(--wb-button-primary-fg,#fff);border-bottom:2px solid var(--wb-button-primary-fg,#fff);transform:rotate(-45deg);z-index:2}',
+ '.wbs-wp-custom .wbs-wp-badge{background:rgba(0,0,0,.35)}',
+ /* 主题切换 segmented(默认 / WorkDaddy / 官方内置深色主题):样式与下方壁纸来源切换按钮统一 */
'.wbs-theme-seg{display:flex;background:var(--wb-bg-tertiary,#f0f0f0);border-radius:10px;padding:3px;gap:3px;margin-bottom:8px}',
- '.wbs-theme-opt{flex:1;padding:6px 4px;border:none;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;font-family:inherit;white-space:nowrap}',
+ '.wbs-theme-opt{flex:1;min-width:0;padding:6px 4px;border:none;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;font-family:inherit;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
'.wbs-theme-opt:hover{color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-theme-opt.active{background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.2)}',
/* 背景图来源切换(WorkDaddy 壁纸 / 自定义背景图) */
@@ -8500,6 +8875,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-password-field input:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 16%,transparent)}',
'.wbs-password-hint{margin-top:7px;color:var(--wb-icon-tertiary,#999);font-size:11px;line-height:1.5}',
'.wbs-password-error{min-height:17px;margin-top:4px;color:#d14343;font-size:11px;line-height:1.5}',
+ '.wbs-transfer-modal{display:flex;max-height:min(520px,calc(100% - 28px));flex-direction:column}',
+ '.wbs-transfer-select-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin:0 0 6px;color:var(--wb-icon-secondary,#666);font-size:12px}',
+ '.wbs-transfer-toggle{border:0;padding:3px 0;background:transparent;color:var(--wb-button-primary-bg,#1f1f1f);font:inherit;font-size:11px;font-weight:600;cursor:pointer}',
+ '.wbs-transfer-list{display:flex;min-height:0;max-height:190px;flex-direction:column;gap:5px;overflow-y:auto;margin:0 0 12px;padding-right:2px}',
+ '.wbs-transfer-option{display:flex;align-items:center;gap:9px;box-sizing:border-box;width:100%;padding:8px 9px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-secondary,#fff);cursor:pointer;transition:background .15s,border-color .15s,box-shadow .15s}',
+ '.wbs-transfer-option:hover{background:var(--wb-bg-hover,#f5f5f5);border-color:var(--wb-border-strong,#bbb)}',
+ '.wbs-transfer-option.selected{border-color:var(--wb-button-primary-bg,#1f1f1f);background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 7%,var(--wb-bg-popover,#fff));box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 12%,transparent)}',
+ '.wbs-transfer-option input{width:15px;height:15px;flex:0 0 15px;margin:0;accent-color:var(--wb-button-primary-bg,#1f1f1f);cursor:pointer}',
+ '.wbs-transfer-copy{display:flex;min-width:0;flex:1;flex-direction:column;gap:2px}',
+ '.wbs-transfer-title{overflow:hidden;color:var(--wb-color-text-primary,#1f1f1f);font-size:12px;font-weight:650;line-height:1.35;text-overflow:ellipsis;white-space:nowrap}',
+ '.wbs-transfer-sub{overflow:hidden;color:var(--wb-icon-tertiary,#888);font-size:11px;line-height:1.35;text-overflow:ellipsis;white-space:nowrap}',
+ '.wbs-transfer-option:focus-within,.wbs-transfer-toggle:focus-visible,.wbs-modal-btn:focus-visible,.wbs-sess-bbtn:focus-visible,.wbs-acct-io:focus-visible{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:2px}',
'.wbs-login-body{display:flex;flex-direction:column;gap:9px;margin-bottom:16px}',
'.wbs-login-option{display:flex;align-items:flex-start;gap:10px;width:100%;box-sizing:border-box;padding:12px 13px;border:1px solid transparent;border-radius:11px;background:var(--wb-bg-popover,#fff);cursor:pointer;text-align:left;transition:border-color .16s,background .16s,box-shadow .16s;font-family:inherit}',
'.wbs-login-option:hover{border-color:var(--wb-border-strong,#b9b9bd);background:var(--wb-bg-hover,#f5f5f5)}',
diff --git a/scripts/secure-transfer.js b/scripts/secure-transfer.js
new file mode 100644
index 0000000..c1ac963
--- /dev/null
+++ b/scripts/secure-transfer.js
@@ -0,0 +1,129 @@
+'use strict';
+
+const crypto = require('node:crypto');
+const path = require('node:path');
+
+const MAX_PASSWORD_LENGTH = 1024;
+const EXPORT_KDF = 'aes-256-gcm+scrypt';
+
+function requiredPassword(value) {
+ const password = typeof value === 'string' ? value : '';
+ if (!password.trim()) throw new Error('密码不能为空');
+ if (password.length > MAX_PASSWORD_LENGTH) throw new Error('密码不能超过 1024 个字符');
+ return password;
+}
+
+function exportSecretKey(password, salt) {
+ return crypto.scryptSync(String(password), salt, 32);
+}
+
+function encryptExport(plain, password) {
+ const checkedPassword = requiredPassword(password);
+ const salt = crypto.randomBytes(16);
+ const iv = crypto.randomBytes(12);
+ const cipher = crypto.createCipheriv('aes-256-gcm', exportSecretKey(checkedPassword, salt), iv);
+ const encrypted = Buffer.concat([cipher.update(String(plain), 'utf8'), cipher.final()]);
+ return {
+ data: Buffer.concat([iv, cipher.getAuthTag(), encrypted]).toString('base64'),
+ salt: salt.toString('base64'),
+ };
+}
+
+function decryptExport(data, password, saltBase64) {
+ const checkedPassword = requiredPassword(password);
+ const packed = Buffer.from(String(data || ''), 'base64');
+ if (packed.length <= 28) throw new Error('导出数据不完整或已损坏');
+ const salt = Buffer.from(String(saltBase64 || ''), 'base64');
+ if (salt.length !== 16) throw new Error('导出文件缺少有效的加密 salt');
+ try {
+ const decipher = crypto.createDecipheriv('aes-256-gcm', exportSecretKey(checkedPassword, salt), packed.subarray(0, 12));
+ decipher.setAuthTag(packed.subarray(12, 28));
+ return Buffer.concat([decipher.update(packed.subarray(28)), decipher.final()]).toString('utf8');
+ } catch (_) {
+ throw new Error('密码错误或导出文件已损坏');
+ }
+}
+
+function normalizeExportKind(kind) {
+ const value = String(kind || '').trim();
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(value)) throw new Error('无效的导出类型');
+ return value;
+}
+
+function createEncryptedExport(kind, payload, password, createdAt) {
+ const normalizedKind = normalizeExportKind(kind);
+ if (!payload || typeof payload !== 'object' || payload.exportType !== 'WorkDaddy-' + normalizedKind) {
+ throw new Error('导出数据类型不匹配');
+ }
+ const encrypted = encryptExport(JSON.stringify(payload), password);
+ return JSON.stringify({
+ wbsExport: 'WorkDaddy',
+ version: 2,
+ exportType: normalizedKind,
+ createdAt: createdAt || new Date().toISOString(),
+ kdf: EXPORT_KDF,
+ salt: encrypted.salt,
+ data: encrypted.data,
+ });
+}
+
+function openEncryptedExport(content, expectedKind, password) {
+ const normalizedKind = normalizeExportKind(expectedKind);
+ let envelope;
+ try { envelope = JSON.parse(String(content || '')); }
+ catch (_) { throw new Error('文件不是有效的导出 JSON'); }
+ if (!envelope || envelope.wbsExport !== 'WorkDaddy' || Number(envelope.version) < 2) {
+ throw new Error('不是有效的 WorkDaddy 加密导出文件');
+ }
+ if (envelope.exportType && envelope.exportType !== normalizedKind) throw new Error('导出文件类型不匹配');
+ let payload;
+ try { payload = JSON.parse(decryptExport(envelope.data, password, envelope.salt)); }
+ catch (error) {
+ if (/密码|损坏|salt/.test(String(error && error.message))) throw error;
+ throw new Error('导出数据无法解析或已损坏');
+ }
+ if (!payload || payload.exportType !== 'WorkDaddy-' + normalizedKind) throw new Error('导出文件类型不匹配');
+ return payload;
+}
+
+function remapSessionArchivePath(relativePath, oldId, newId) {
+ const relative = String(relativePath || '');
+ const sourceId = String(oldId || '');
+ const targetId = String(newId || '');
+ if (!relative || !sourceId || !targetId || relative.includes('\\') || relative.startsWith('/') || relative.split('/').some((part) => !part || part === '.' || part === '..')) {
+ throw new Error('无效的会话归档路径');
+ }
+ const escaped = sourceId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const mappings = [
+ [new RegExp('^projects/([^/]+)/' + escaped + '\\.jsonl$'), (match) => `projects/${match[1]}/${targetId}.jsonl`],
+ [new RegExp('^projects/([^/]+)/' + escaped + '/(.+)$'), (match) => `projects/${match[1]}/${targetId}/${match[2]}`],
+ [new RegExp('^(workspace/sessions|tasks|file-history)/' + escaped + '/(.+)$'), (match) => `${match[1]}/${targetId}/${match[2]}`],
+ [new RegExp('^artifact-index/' + escaped + '\\.json$'), () => `artifact-index/${targetId}.json`],
+ ];
+ for (const [pattern, build] of mappings) {
+ const match = pattern.exec(relative);
+ if (match) return build(match);
+ }
+ throw new Error('会话归档包含不受支持的文件路径');
+}
+
+function resolveArchiveTarget(root, relativePath) {
+ const base = path.resolve(String(root || ''));
+ const target = path.resolve(base, String(relativePath || ''));
+ const relative = path.relative(base, target);
+ if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
+ throw new Error('会话归档文件超出 WorkBuddy 数据目录');
+ }
+ return target;
+}
+
+module.exports = {
+ MAX_PASSWORD_LENGTH,
+ createEncryptedExport,
+ decryptExport,
+ encryptExport,
+ openEncryptedExport,
+ remapSessionArchivePath,
+ requiredPassword,
+ resolveArchiveTarget,
+};
diff --git a/scripts/theme-patches.js b/scripts/theme-patches.js
index 7033f88..2dde512 100644
--- a/scripts/theme-patches.js
+++ b/scripts/theme-patches.js
@@ -7,16 +7,6 @@
// 增删对应补丁的 css → 重应用主题验证。
// ============================================================
module.exports = [
- {
- id: 'patch-00',
- desc: '(no comment)',
- css: 'body[data-vscode-theme-name] .cb-markdown{--cb-markdown-table-cell-bg:var(--wb-bg-primary);--cb-markdown-table-header-bg:var(--wb-bg-secondary);--cb-markdown-table-border-color:var(--wb-border-strong);--cb-markdown-border-color:var(--wb-border-strong);}',
- },
- {
- id: 'patch-02',
- desc: '与 markdown 表格同款坑,统一在 .cb-markdown 上直接定义为主题变量',
- css: 'body[data-vscode-theme-name] .cb-markdown{--cb-markdown-code-block-header-bg:var(--wb-bg-secondary);--cb-markdown-code-block-title-fg:var(--wb-color-text-primary);--cb-markdown-code-block-action-fg:var(--wb-color-text-secondary);--cb-markdown-code-block-action-hover-bg:var(--wb-bg-hover);--cb-markdown-code-block-border:var(--wb-border-subtle);--cb-markdown-code-block-bg:var(--wb-bg-tertiary);}body[data-vscode-theme-name] [class*="input-area-container"]::before{--cb-colleagues-dashboard-bg:var(--wb-bg-primary);}',
- },
{
id: 'patch-03',
desc: '改为半透明毛玻璃(背景图透出 + 模糊),而非纯色',
@@ -79,8 +69,8 @@ module.exports = [
},
{
id: 'patch-15',
- desc: '弹窗/tooltip 通用深色适配:dropdown/popover/popper/picker-panel/menu-panel 背景默认白,深色下覆盖',
- css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="toolbar"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="popper"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="picker-panel"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="menu-panel"]{background:var(--wb-bg-popover) !important;color:var(--wb-color-text-primary);border-color:var(--wb-border-subtle) !important;box-shadow:0 6px 24px rgba(0,0,0,0.5) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="tooltip"]:not([class*="chat"]):not([class*="message"]){background:var(--wb-bg-popover) !important;color:var(--wb-color-text-primary);}html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"] [class*="item"]:hover,html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"] [class*="item"]:hover{background:var(--wb-bg-hover) !important;}',
+ desc: '弹窗/tooltip 通用深色适配:dropdown/popover/popper/picker-panel/menu-panel 背景默认白,深色下覆盖。排除官方新组件体系(cr-theme/cr-popover/cr-menu——官方自带深色适配)与官方 hash 触发器容器(_dropdownRoot_——仅定位容器,不应着色,否则更多按钮出现黑底)',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="toolbar"]):not([class*="cr-theme"]):not([class*="_dropdownRoot_"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"]:not([class*="cr-theme"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="popper"]:not([class*="cr-theme"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="picker-panel"]:not([class*="cr-theme"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="menu-panel"]:not([class*="cr-theme"]){background:var(--wb-bg-popover) !important;color:var(--wb-color-text-primary);border-color:var(--wb-border-subtle) !important;box-shadow:0 6px 24px rgba(0,0,0,0.5) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="tooltip"]:not([class*="chat"]):not([class*="message"]){background:var(--wb-bg-popover) !important;color:var(--wb-color-text-primary);}html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]):not([class*="_dropdownRoot_"]) [class*="item"]:hover,html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"]:not([class*="cr-theme"]) [class*="item"]:hover{background:var(--wb-bg-hover) !important;}',
},
{
id: 'patch-16',
@@ -159,18 +149,18 @@ module.exports = [
},
{
id: 'patch-31',
- desc: '注意:body 层定义会被中间祖先链的局部浅色值覆盖,必须在组件元素上直接定义(直接定义 > 继承)',
- css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="_questionAnswerDisplay_"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="_qaQuestion_"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="_qaAnswerText_"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="_qaAnswer_"]{--qad-card-bg:var(--wb-bg-secondary) !important;--qad-question-color:var(--wb-color-text-secondary) !important;--qad-answer-color:var(--wb-color-text-primary) !important;}html[data-theme="dark"] body[data-vscode-theme-name] .ask-user-question [class*="_questionAnswerDisplay_"]{background-color:var(--qad-card-bg) !important;}',
+ desc: '问答展示区背景绑定 qad-card-bg 变量(变量定义已移入 theme-vars.js scoped 层,此处仅保留元素背景应用)',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] .ask-user-question [class*="_questionAnswerDisplay_"]{background-color:var(--qad-card-bg) !important;}',
},
{
id: 'patch-32',
desc: '问答状态文本(skipped/failed/cancelled 用 --cb-text-tertiary,深色下未定义回退浅色)',
- css: 'html[data-theme="dark"] body[data-vscode-theme-name] .ask-user-question--skipped .skipped-content,html[data-theme="dark"] body[data-vscode-theme-name] .ask-user-question--failed .failed-content,html[data-theme="dark"] body[data-vscode-theme-name] .ask-user-question--cancelled .cancelled-content{color:var(--wb-color-text-tertiary) !important;}html[data-theme="dark"] body[data-vscode-theme-name]{--qad-card-bg:var(--wb-bg-secondary);--qad-question-color:var(--wb-color-text-secondary);--qad-answer-color:var(--wb-color-text-primary);}',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] .ask-user-question--skipped .skipped-content,html[data-theme="dark"] body[data-vscode-theme-name] .ask-user-question--failed .failed-content,html[data-theme="dark"] body[data-vscode-theme-name] .ask-user-question--cancelled .cancelled-content{color:var(--wb-color-text-tertiary) !important;}',
},
{
id: 'patch-33',
- desc: '更多按钮弹层(dropdownRoot):背景透明 + 去边框 + 去阴影(patch-15 通用弹窗规则会给它加边框/阴影,需在此一并清掉)',
- css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="_moreMenu_"] [class*="_dropdownRoot_"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="_moreButton_"]{background:transparent !important;border-color:transparent !important;box-shadow:none !important;}',
+ desc: '更多按钮弹层(dropdownRoot/_moreMenu/_moreButton):背景透明 + 去边框 + 去阴影(patch-15 通用弹窗规则会给 _dropdownRoot_ 命中 dropdown 子串染上 --wb-bg-popover 背景色/阴影,需在此一并清掉;_moreButton_ 内层同样)',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="_moreMenu_"] [class*="_dropdownRoot_"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="_dropdownRoot_"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="_moreButton_"]{background:transparent !important;border-color:transparent !important;box-shadow:none !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',
},
{
id: 'patch-34',
@@ -194,13 +184,8 @@ module.exports = [
},
{
id: 'patch-38',
- desc: '= rgb(31,31,31) 纯色硬块,改为与输入框一致的毛玻璃;并全局兜底 palette-gray-3 变量',
- css: 'body[data-vscode-theme-name] .cb-message-queue.cb-expand{background:color-mix(in srgb,var(--wb-bg-primary) 40%,transparent) !important;backdrop-filter:blur(20px) saturate(1.15);-webkit-backdrop-filter:blur(20px) saturate(1.15);}html[data-theme="dark"] body[data-vscode-theme-name]{--wb-palette-gray-3:var(--wb-bg-primary);}',
- },
- {
- id: 'patch-39',
- desc: '--cb-bg-secondary/--cb-border 深色下仍是浅色值(浅灰 #f5f5f5 / #d1d5db),全局深色化',
- css: 'html[data-theme="dark"] body[data-vscode-theme-name]{--cb-bg-secondary:var(--wb-bg-tertiary);--cb-border:var(--wb-border-subtle);}',
+ desc: '消息队列展开态(cb-expand)毛玻璃(全局 palette-gray-3 兜底变量已移入 theme-vars.js body 层)',
+ css: 'body[data-vscode-theme-name] .cb-message-queue.cb-expand{background:color-mix(in srgb,var(--wb-bg-primary) 40%,transparent) !important;backdrop-filter:blur(20px) saturate(1.15);-webkit-backdrop-filter:blur(20px) saturate(1.15);}',
},
{
id: 'patch-40',
@@ -224,8 +209,8 @@ module.exports = [
},
{
id: 'patch-44',
- desc: 'tooltip/悬浮提示组件文字硬编码深色(与深色弹窗同色看不见):强制浅色 + hover 高亮态文字浅色',
- css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="tooltip"]:not([class*="chat"]):not([class*="message"]) *,html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"] *,html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"] *{color:var(--wb-color-text-primary) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"] [class*="item"]:hover,html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"] [class*="item"]:hover *{color:var(--wb-color-text-primary) !important;background:var(--wb-bg-hover) !important;}',
+ desc: 'tooltip/悬浮提示组件文字硬编码深色(与深色弹窗同色看不见):强制浅色 + hover 高亮态文字浅色(排除官方新组件体系 cr-theme——其自带深色文字适配)',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="tooltip"]:not([class*="chat"]):not([class*="message"]) *,html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"]:not([class*="cr-theme"]) *,html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]) *{color:var(--wb-color-text-primary) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]) [class*="item"]:hover,html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]) [class*="item"]:hover *{color:var(--wb-color-text-primary) !important;background:var(--wb-bg-hover) !important;}',
},
{
id: 'patch-45',
@@ -279,8 +264,8 @@ module.exports = [
},
{
id: 'patch-55',
- desc: '深度思考标题与正文语义标签颜色适配;不修改折叠、流式显隐、动画、尺寸或代码高亮 token',
- css: 'html[data-theme="dark"] body[data-vscode-theme-name]{--cb-text-primary:var(--wb-color-text-primary);--cb-text-tertiary:var(--wb-color-text-secondary);}html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoning_"] [class*="_assistantReasoningHeader_"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoning_"] [class*="_assistantReasoningHeader_"]:hover{color:var(--wb-color-text-primary) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoning_"] [class*="_assistantReasoningIcon_"]{color:var(--wb-color-text-secondary) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] p,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] li,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h1,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h2,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h3,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h4,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h5,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h6,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] blockquote,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] a{color:var(--wb-color-text-primary) !important;}',
+ desc: '深度思考标题与正文语义标签颜色适配;不修改折叠、流式显隐、动画、尺寸或代码高亮 token(--cb-text-* 全局变量已移入 theme-vars.js body 层)',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoning_"] [class*="_assistantReasoningHeader_"],html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoning_"] [class*="_assistantReasoningHeader_"]:hover{color:var(--wb-color-text-primary) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoning_"] [class*="_assistantReasoningIcon_"]{color:var(--wb-color-text-secondary) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] p,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] li,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h1,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h2,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h3,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h4,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h5,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] h6,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] blockquote,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_assistantReasoningContent_"] a{color:var(--wb-color-text-primary) !important;}',
},
{
id: 'patch-56',
@@ -359,8 +344,8 @@ module.exports = [
},
{
id: 'patch-71',
- desc: 'markdown 表格边框线条透明:官方 .cb-markdown table border + th/td border-right/bottom 用 --cb-markdown-table-border-color(主题映射=#262626 深色)太抢眼;改为 transparent(表格外框与单元格分隔线都透明,仅靠毛玻璃底区分),并覆盖变量让同类边框同步透明',
- css: 'html[data-theme="dark"] body[data-vscode-theme-name] .cb-markdown{--cb-markdown-table-border-color:transparent !important;--cb-markdown-border-color:transparent !important;}html[data-theme="dark"] body[data-vscode-theme-name] .cb-markdown table,html[data-theme="dark"] body[data-vscode-theme-name] .cb-markdown-table-wrapper > table,html[data-theme="dark"] body[data-vscode-theme-name] .cb-markdown th,html[data-theme="dark"] body[data-vscode-theme-name] .cb-markdown td{border-color:transparent !important;}',
+ desc: 'markdown 表格边框线条透明:官方 .cb-markdown table border + th/td border-right/bottom 用 --cb-markdown-table-border-color(主题映射=#262626 深色)太抢眼;改为 transparent(表格外框与单元格分隔线都透明,仅靠毛玻璃底区分;变量覆盖已移入 theme-vars.js scoped 层)',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] .cb-markdown table,html[data-theme="dark"] body[data-vscode-theme-name] .cb-markdown-table-wrapper > table,html[data-theme="dark"] body[data-vscode-theme-name] .cb-markdown th,html[data-theme="dark"] body[data-vscode-theme-name] .cb-markdown td{border-color:transparent !important;}',
},
{
id: 'patch-72',
@@ -407,6 +392,86 @@ module.exports = [
desc: '消息队列项左侧「拖拽图标」(prompt-ico/prompt-icon)在有暂存提示词时透明但仍占位,导致文字左侧空白:整体隐藏不占位(用户要求)',
css: '.cb-message-queue-item-left .prompt-ico,.cb-message-queue-item-left .prompt-icon{display:none !important;width:0 !important;margin:0 !important;}',
},
+ {
+ id: 'patch-83',
+ desc: '会话主区域(conversation-shell__main)去背景色全透明(用户 08-29 18:02 终版要求透明);侧栏代理卡片(cb-agent-card)仅选中态毛玻璃(用户 08-30 10:03 调整:只有带 selected class 的卡片才 32% 毛玻璃,其余透明)——选中判定覆盖 conversation-item 的 active / aria-selected / _selected_ 及卡片自身挂 _selected_(5.4.4 选中 class 直接挂在 card 上,如 _selected_914ll_20)',
+ css: 'body[data-vscode-theme-name] .conversation-shell__main{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}body[data-vscode-theme-name] .conversation-section-content .cb-agent-card{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}body[data-vscode-theme-name] .conversation-section-content .conversation-item.active .cb-agent-card,body[data-vscode-theme-name] .conversation-section-content .conversation-item[aria-selected="true"] .cb-agent-card,body[data-vscode-theme-name] .conversation-section-content .conversation-item[class*="_selected_"] .cb-agent-card,body[data-vscode-theme-name] .conversation-section-content .cb-agent-card[class*="_selected_"]{background:color-mix(in srgb,var(--wb-bg-primary) 32%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 32%,transparent) !important;backdrop-filter:blur(14px) saturate(1.15) !important;-webkit-backdrop-filter:blur(14px) saturate(1.15) !important;border-color:var(--wb-border-subtle) !important;}',
+ },
+ {
+ id: 'patch-84',
+ desc: '主页路由主体(.wb-home-route__body)去背景色全透明(用户 08-29 18:02 要求透明,撤销此前 45% 毛玻璃);主页整链 teams-main-content / wb-home-route / wb-home-route__body 全透明,层次由输入框毛玻璃局部呈现',
+ css: 'body[data-vscode-theme-name] .teams-main-content main.wb-home-route > .wb-home-route__body{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',
+ },
+ {
+ id: 'patch-85',
+ desc: '会话输入框容器(cr-input-container,新版 5.4.4 conversation-input 内)毛玻璃:42% 半透明 bg-primary + blur(18px),与整体系列毛玻璃风格统一;会话主区域已透明,输入框需保留层次(用户要求)',
+ css: 'body[data-vscode-theme-name] .conversation-input .cr-input-box__main .cr-input-container{background:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;backdrop-filter:blur(18px) saturate(1.15) !important;-webkit-backdrop-filter:blur(18px) saturate(1.15) !important;border-color:var(--wb-border-subtle) !important;}',
+ },
+ {
+ id: 'patch-86',
+ desc: '消息列表滚动到底部渐变色去除·v3(用户 08-29 18:16 反馈仍存在):清理面从 content--revealed 扩大到整条虚拟滚动链 cr-message-list-viewport / cr-message-list / content--revealed / cr-document / virtual-spacer,清 background-image 与 mask 全家族(含简写),隐藏所有承载渐变的 ::before/::after',
+ css: 'body[data-vscode-theme-name] .cr-message-list-viewport,body[data-vscode-theme-name] .cr-message-list,body[data-vscode-theme-name] .cr-message-list__content.cr-message-list__content--revealed,body[data-vscode-theme-name] .cr-document,body[data-vscode-theme-name] .cr-document__virtual-spacer{background-image:none !important;mask:none !important;-webkit-mask:none !important;mask-image:none !important;-webkit-mask-image:none !important;}body[data-vscode-theme-name] .cr-message-list-viewport::before,body[data-vscode-theme-name] .cr-message-list-viewport::after,body[data-vscode-theme-name] .cr-message-list::before,body[data-vscode-theme-name] .cr-message-list::after,body[data-vscode-theme-name] .cr-message-list__content.cr-message-list__content--revealed::before,body[data-vscode-theme-name] .cr-message-list__content.cr-message-list__content--revealed::after,body[data-vscode-theme-name] .cr-document::before,body[data-vscode-theme-name] .cr-document::after,body[data-vscode-theme-name] .cr-document__virtual-spacer::before,body[data-vscode-theme-name] .cr-document__virtual-spacer::after{display:none !important;background-image:none !important;background:transparent !important;mask:none !important;-webkit-mask:none !important;mask-image:none !important;-webkit-mask-image:none !important;}',
+ },
+ {
+ id: 'patch-87',
+ desc: '输入框底部工具栏右侧(cr-input-toolbar__right)全局背景透明(会话页 + 主页 wb-home-composer 均命中):官方不透明底 → 完全透明,露出输入框容器(cr-input-container)的毛玻璃层(用户 08-29 要求,主页版同步覆盖)',
+ css: 'body[data-vscode-theme-name] .cr-input-toolbar__right{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',
+ },
+ {
+ id: 'patch-88',
+ desc: '会话页最外层内容容器(teams-main-content)去背景色全透明(用户 08-29 18:02 要求透明,撤销此前 42% 毛玻璃);配合 conversation-shell/shell__main 全透明,整体露出背景,层次由 topbar/气泡/输入框等局部毛玻璃呈现',
+ css: 'body[data-vscode-theme-name] .teams-main-content{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',
+ },
+ {
+ id: 'patch-89',
+ desc: '会话容器分层整理(用户 08-30 00:20 修正):conversation-shell 深色主题下半透明黑 45%(无 blur,仅底色,不影响背景图清晰度;浅色主题如护眼绿不受影响);teams 布局最外层 grid 网格项(_gridViewItem_)透明;主页路由 main.wb-home-route 透明;侧栏会话列表 tab 按钮(conversation-list-tab-button-box)透明',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] .conversation-shell{background:rgba(0,0,0,0.45) !important;background-color:rgba(0,0,0,0.45) !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}body[data-vscode-theme-name] .teams-container.is-mac [class*="_gridViewItem_"]{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}body[data-vscode-theme-name] .teams-main-content main.wb-home-route{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}body[data-vscode-theme-name] .conversation-list-tab-button.conversation-list-tab-button-box{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',
+ },
+ {
+ id: 'patch-90',
+ desc: '局部毛玻璃组(用户 08-29 18:02/18:16 批量需求,统一 42% bg-primary + blur(18px)):workbuddy-topbar--mac 顶栏、会话自己的消息气泡(cr-self-bubble)、滚动到底按钮(cr-scroll-to-bottom__inner)、主页输入框本体(cr-input-box__main);markdown 分隔线 cr-markdown hr 改毛玻璃质感(硬边框 → 半透明主题色渐变线)',
+ css: 'body[data-vscode-theme-name] .workbuddy-topbar--mac,body[data-vscode-theme-name] .cr-self-message .cr-self-bubble,body[data-vscode-theme-name] .cr-scroll-to-bottom,body[data-vscode-theme-name] .cr-scroll-to-bottom__inner,body[data-vscode-theme-name] .wb-home-composer .cr-input-box__main{background:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;backdrop-filter:blur(18px) saturate(1.15) !important;-webkit-backdrop-filter:blur(18px) saturate(1.15) !important;border-color:var(--wb-border-subtle) !important;}body[data-vscode-theme-name] .cr-markdown hr{background:linear-gradient(90deg,transparent,color-mix(in srgb,var(--wb-color-text-secondary) 30%,transparent) 50%,transparent) !important;border:none !important;height:1px !important;border-radius:1px !important;box-shadow:none !important;}',
+ },
+ {
+ id: 'patch-91',
+ desc: '主页输入框容器(.wb-home-composer 内 cr-input-container)改透明背景(用户 08-29 18:02 要求):主页输入区层次为本体 cr-input-box__main 毛玻璃(patch-90) + 容器与工具栏全透明',
+ css: 'body[data-vscode-theme-name] .wb-home-composer .cr-input-container{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',
+ },
+ {
+ id: 'patch-92',
+ desc: '侧栏会话卡片未读圆点(_unreadDot_,挂 cb-agent-card 的 header 内)适配主题:圆点由 ::before 实现(官方硬编码 rgb(0,194,154) 青绿、局部 --wb-accent-unread 也被官方污染为青绿;无 --wb-accent 定义导致 fallback 蓝色突兀),改为主题文字色 var(--wb-color-text-primary)(WorkDaddy 建主题必定义:深色=白/浅色=深绿,与主题绝对协调),fallback #8a8f98 中性灰;容器自身保持透明背景(用户 08-30 10:40 修正 10:36 的蓝色)',
+ css: 'html[data-wbs-theme="1"] body[data-vscode-theme-name] .cb-agent-card [class*="_unreadDot_"]{background:transparent !important;background-color:transparent !important;}html[data-wbs-theme="1"] body[data-vscode-theme-name] .cb-agent-card [class*="_unreadDot_"]::before{background:var(--wb-color-text-primary,#8a8f98) !important;background-color:var(--wb-color-text-primary,#8a8f98) !important;}',
+ },
+ {
+ id: 'patch-93',
+ desc: '细节适配组(用户 08-29 18:21 / 08-30 09:57 调整):1) 深度思考推理区 cr-collapse__content(-inner) 左侧边框线条去掉;2) markdown 表格:外层容器 cr-table-block 透明背景,表格本体 cr-table-block table 毛玻璃(42%+blur18) + 表头 thead/th 半透明背景;3) 会话列表 tab 行 conversation-list-tab-row 鼠标悬浮时毛玻璃背景(仅背景/模糊,不改变布局)',
+ css: 'body[data-vscode-theme-name] .cr-reasoning .cr-collapse__content,body[data-vscode-theme-name] .cr-reasoning .cr-collapse__content-inner{border-left:none !important;}body[data-vscode-theme-name] .cr-markdown .cr-table-block{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}body[data-vscode-theme-name] .cr-markdown .cr-table-block .cr-table-block__inner table,body[data-vscode-theme-name] .cr-markdown .cr-table-block table{background:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;backdrop-filter:blur(18px) saturate(1.15) !important;-webkit-backdrop-filter:blur(18px) saturate(1.15) !important;border-color:var(--wb-border-subtle) !important;}body[data-vscode-theme-name] .cr-markdown .cr-table-block thead,body[data-vscode-theme-name] .cr-markdown .cr-table-block thead th{background:color-mix(in srgb,var(--wb-bg-secondary) 52%,transparent) !important;}body[data-vscode-theme-name] .conversation-list-tab-row:hover{background:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;backdrop-filter:blur(18px) saturate(1.15) !important;-webkit-backdrop-filter:blur(18px) saturate(1.15) !important;}',
+ },
+ {
+ id: 'patch-94',
+ desc: '会话消息列表底部渐变色(cr-message-list__bottom-mask, 72px 高)改透明:官方 background-image 硬编码 linear-gradient(rgba(0,0,0,0),rgb(20,20,20)),滚动场景下 expose 渐变,用户要求顶部/中部/底部均无渐变遮罩(非默认主题注入)',
+ css: 'body[data-vscode-theme-name] .cr-message-list__bottom-mask{background-image:none !important;background:transparent !important;background-color:transparent !important;mask:none !important;-webkit-mask:none !important;mask-image:none !important;-webkit-mask-image:none !important;}body[data-vscode-theme-name] .cr-message-list__bottom-mask::before,body[data-vscode-theme-name] .cr-message-list__bottom-mask::after{background-image:none !important;background:transparent !important;mask:none !important;-webkit-mask:none !important;}',
+ },
+ {
+ id: 'patch-95',
+ desc: '工具调用展开内容(cr-tool-exp__content)背景半透明(用户 08-30 00:46):官方硬编码 rgb(42,44,49) 不透明纯色块 → 45% 主题次级底 + 轻微 blur,与整体毛玻璃语言统一',
+ css: 'body[data-vscode-theme-name] .cr-tool-exp__content-shell .cr-tool-exp__content,body[data-vscode-theme-name] .cr-tool-exp__content{background:color-mix(in srgb,var(--wb-bg-tertiary) 45%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-tertiary) 45%,transparent) !important;backdrop-filter:blur(16px) saturate(1.15) !important;-webkit-backdrop-filter:blur(16px) saturate(1.15) !important;border-color:var(--wb-border-subtle) !important;}',
+ },
+ {
+ id: 'patch-96',
+ desc: '左侧栏整理(用户 08-30 00:52 调整):conversation-sidebar 外层改与顶栏(workbuddy-topbar--mac)相同的毛玻璃 42% + blur(18px);内部容器(list/topbar/content/section 等)保持透明避免叠层;选中会话卡片 32% 毛玻璃选中态保留(patch-83)',
+ css: 'body[data-vscode-theme-name] .conversation-sidebar{background:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;backdrop-filter:blur(18px) saturate(1.15) !important;-webkit-backdrop-filter:blur(18px) saturate(1.15) !important;}body[data-vscode-theme-name] .conversation-list,body[data-vscode-theme-name] [data-view-id="sidebar"],body[data-vscode-theme-name] .conversation-list-topbar,body[data-vscode-theme-name] .conversation-list-content,body[data-vscode-theme-name] .conversation-section,body[data-vscode-theme-name] .conversation-section-content,body[data-vscode-theme-name] .conversation-section-groups{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',
+ },
+ {
+ id: 'patch-97',
+ desc: '代码块容器(cr-code-like-box)背景毛玻璃(用户 08-30 01:16):官方硬编码 rgb(26,27,30) 不透明 → 45% 主题深色底 + blur(16px),与消息区毛玻璃语言统一',
+ css: 'body[data-vscode-theme-name] .cr-code-like-box{background:color-mix(in srgb,var(--wb-bg-primary) 45%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 45%,transparent) !important;backdrop-filter:blur(16px) saturate(1.15) !important;-webkit-backdrop-filter:blur(16px) saturate(1.15) !important;border-color:var(--wb-border-subtle) !important;}',
+ },
+ {
+ id: 'patch-98',
+ desc: '代码块头部(cr-code-like-box__header)背景半透明(用户 08-30 01:16):官方硬编码 rgb(20,21,24) 不透明 → 32% 主题深色底(比容器略深形成层次,无独立 blur 透出容器毛玻璃)',
+ css: 'body[data-vscode-theme-name] .cr-code-like-box__header{background:color-mix(in srgb,var(--wb-bg-primary) 32%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 32%,transparent) !important;border-color:var(--wb-border-subtle) !important;}',
+ },
/* 原 patch-82(AI 端快捷短语弹层 z-index 抬升)已移入 inject.js 常驻样式:
theme-patches 仅在非默认主题时注入,默认浅色主题下会失效;层级修复不依赖主题,随注入脚本常驻更可靠。 */
];
diff --git a/scripts/theme-vars.js b/scripts/theme-vars.js
new file mode 100644
index 0000000..f1b1cfc
--- /dev/null
+++ b/scripts/theme-vars.js
@@ -0,0 +1,82 @@
+// WorkBuddy 主题变量别名层(热插拔模块)
+// ============================================================
+// 用途:官方 token 里「漏定义 / 深色下值不对」的变量,重定向到 WorkDaddy 主题变量。
+// 这些是「改常量就能搞定」的样式问题(等价 vscode 主题 token 映射),不属于 DOM 魔改,
+// 因此独立于 theme-patches.js(那里只保留必须针对元素写规则的补丁)。
+//
+// 注入时机:daemon applyThemeByCdp 生成主题 CSS 时统一附加(非 default 主题)。
+// darkOnly: true 等价原补丁的 html[data-theme="dark"] 前缀,仅深色主题注入。
+// 顺序:body 层在前、组件作用域层在后;同特异性后注入者胜(dark 覆盖按此排列)。
+// 修改本文件后重应用主题即生效(POST /api/theme-apply,无需重启 daemon)。
+// ============================================================
+
+module.exports = {
+ // body 级变量(作用域 body[data-vscode-theme-name])
+ body: [
+ {
+ darkOnly: true,
+ vars: {
+ // 官方 .cb-* 组件变量深色下仍是浅色值(浅灰 #f5f5f5 / #d1d5db),全局重定向为主题深色
+ '--cb-bg-secondary': 'var(--wb-bg-tertiary)',
+ '--cb-border': 'var(--wb-border-subtle)',
+ // 官方 --cb-text-* 深色下未定义回退浅色,重定向为主题文字色
+ '--cb-text-primary': 'var(--wb-color-text-primary)',
+ '--cb-text-tertiary': 'var(--wb-color-text-secondary)',
+ // 消息队列/骨架屏回退色
+ '--wb-palette-gray-3': 'var(--wb-bg-primary)',
+ // 问答卡片变量兜底(组件作用域还会再定义,这里保证 body 继承链有值)
+ '--qad-card-bg': 'var(--wb-bg-secondary)',
+ '--qad-question-color': 'var(--wb-color-text-secondary)',
+ '--qad-answer-color': 'var(--wb-color-text-primary)',
+ },
+ },
+ ],
+ // 组件作用域级变量:官方在这些组件上定义了局部浅色硬编码,必须同作用域重定向(直接定义 > 继承)
+ scoped: [
+ {
+ sel: '.cb-markdown',
+ darkOnly: false,
+ vars: {
+ // markdown 表格:官方 --cb-markdown-table-* 浅色分支继承白底值
+ '--cb-markdown-table-cell-bg': 'var(--wb-bg-primary)',
+ '--cb-markdown-table-header-bg': 'var(--wb-bg-secondary)',
+ '--cb-markdown-table-border-color': 'var(--wb-border-strong)',
+ '--cb-markdown-border-color': 'var(--wb-border-strong)',
+ // markdown 代码块:官方深色下未定义的组件变量
+ '--cb-markdown-code-block-header-bg': 'var(--wb-bg-secondary)',
+ '--cb-markdown-code-block-title-fg': 'var(--wb-color-text-primary)',
+ '--cb-markdown-code-block-action-fg': 'var(--wb-color-text-secondary)',
+ '--cb-markdown-code-block-action-hover-bg': 'var(--wb-bg-hover)',
+ '--cb-markdown-code-block-border': 'var(--wb-border-subtle)',
+ '--cb-markdown-code-block-bg': 'var(--wb-bg-tertiary)',
+ },
+ },
+ {
+ sel: '[class*="input-area-container"]::before',
+ darkOnly: false,
+ vars: {
+ // 输入框上方渐变:官方 var(--cb-colleagues-dashboard-bg, #FAFAFA),浅色下变量未定义回退白色
+ '--cb-colleagues-dashboard-bg': 'var(--wb-bg-primary)',
+ },
+ },
+ // 深色下 markdown 表格边框改透明(浅色保持上方 --wb-border-strong 值)
+ {
+ sel: '.cb-markdown',
+ darkOnly: true,
+ vars: {
+ '--cb-markdown-table-border-color': 'transparent !important',
+ '--cb-markdown-border-color': 'transparent !important',
+ },
+ },
+ // 问答卡片:body 层定义会被中间祖先链的局部浅色值覆盖,必须组件作用域(直接定义 > 继承)
+ {
+ sel: '[class*="_questionAnswerDisplay_"],[class*="_qaQuestion_"],[class*="_qaAnswerText_"],[class*="_qaAnswer_"]',
+ darkOnly: true,
+ vars: {
+ '--qad-card-bg': 'var(--wb-bg-secondary) !important',
+ '--qad-question-color': 'var(--wb-color-text-secondary) !important',
+ '--qad-answer-color': 'var(--wb-color-text-primary) !important',
+ },
+ },
+ ],
+};
\ No newline at end of file
diff --git a/scripts/verify-win.cmd b/scripts/verify-win.cmd
index ee0a976..263e7b8 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 lib.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 windows-relaunch-standard.ps1 prepare-win-install.ps1 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.ps1 apply-update.ps1 win\setup.sed) do (
if not exist "%SCRIPT_DIR%%%F" (
echo 缺失: %%~F
set /a FAIL+=1
@@ -57,7 +57,7 @@ if errorlevel 1 (
rem ---- 3) 脚本语法静态检查(node --check,不执行)----
echo.
echo [3/6] 校验 JS 语法...
-for %%F in (daemon.js session-db.js lib.js watchdog.js win-launcher.js windows-process-boundary.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/watchdog.js b/scripts/watchdog.js
index 39d70bd..97f4666 100644
--- a/scripts/watchdog.js
+++ b/scripts/watchdog.js
@@ -1,295 +1,75 @@
#!/usr/bin/env node
/**
- * WorkDaddy Windows 守护进程(对应 macOS launchd 的 KeepAlive 能力)
+ * WorkDaddy Windows watchdog.
*
- * 职责:spawn daemon.js 并常驻监听;daemon 崩溃/退出后自动拉起(指数退避防抖)。
- * 单实例:PID 文件锁(%DATA_DIR%\watchdog.pid),重复启动直接退出。
- * 更新流程:apply-update.ps1 先按 PID 杀本进程,再做文件替换。
- *
- * 用法: node watchdog.js
- * node watchdog.js stop # 停止:杀 daemon + 退出自己
+ * The loopback lock belongs to the OS and disappears automatically when this
+ * process exits. watchdog.pid is only a hint for the native install helper;
+ * it is never trusted on its own for process termination.
*/
'use strict';
const fs = require('fs');
+const net = require('net');
const path = require('path');
-const os = require('os');
-const { spawn, spawnSync } = require('child_process');
-const {
- assertSameProcessIdentity,
- detectWindowsPrivilege,
- assertVerifiedNodeProcess,
- buildNativeProcessQuery,
- filterVerifiedNodeProcesses,
- parseCimProcessResult,
-} = require('./windows-process-boundary.js');
+const { spawn } = require('child_process');
const { getProfile, profileDataDir } = require('./profiles.js');
-const WINDOWS_PRIVILEGE = process.platform === 'win32' ? detectWindowsPrivilege() : 'standard';
-
-const SCRIPTS_DIR = __dirname;
const PROFILE_ID = process.env.WBSWITCH_PROFILE || 'workbuddy-cn';
const PROFILE = getProfile(PROFILE_ID);
-const DATA_DIR =
- process.env.WBSWITCH_DATA_DIR ||
- profileDataDir(PROFILE);
+const DATA_DIR = process.env.WBSWITCH_DATA_DIR || profileDataDir(PROFILE);
const PID_FILE = path.join(DATA_DIR, 'watchdog.pid');
const LOG_FILE = path.join(DATA_DIR, 'watchdog.log');
-const UPDATE_PENDING_FILE = path.join(DATA_DIR, 'update', 'pending.json'); // 自动更新进行中标记(update 目录由 apply 流程创建)
-const DAEMON_FILE = path.join(SCRIPTS_DIR, 'daemon.js');
-
-function updateProcessIsActive(pid) {
- if (process.platform !== 'win32' || !Number.isSafeInteger(pid) || pid <= 0) return false;
- const command = `Get-CimInstance Win32_Process -Filter \"ProcessId = ${pid}\" -ErrorAction SilentlyContinue | ` +
- `Where-Object { $_.Name -match '^(powershell|pwsh)(\\.exe)?$' -and $_.CommandLine -match '(?i)apply-update\\.ps1' } | ` +
- 'Select-Object -First 1 ProcessId | ConvertTo-Json -Compress';
- const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command], {
- encoding: 'utf8', timeout: 10000, windowsHide: true,
- });
- return !result.error && result.status === 0 && /ProcessId/.test(String(result.stdout || ''));
-}
+const DAEMON_FILE = path.join(__dirname, 'daemon.js');
+const LOCK_PORT = PROFILE.id === 'workbuddy-ai' ? 47933 : 47932;
-function updatePendingIsActive() {
- if (!fs.existsSync(UPDATE_PENDING_FILE)) return false;
- let pending = null;
- try { pending = JSON.parse(fs.readFileSync(UPDATE_PENDING_FILE, 'utf8')); } catch (_) {}
- const attemptId = pending && typeof pending.attempt === 'string' ? pending.attempt : '';
- let attempt = null;
- try {
- const attemptFile = path.join(path.dirname(UPDATE_PENDING_FILE), 'last-attempt.json');
- attempt = JSON.parse(fs.readFileSync(attemptFile, 'utf8'));
- } catch (_) {}
- const scriptPid = Number(attempt && attempt.attemptId === attemptId ? attempt.scriptPid : 0);
- if (updateProcessIsActive(scriptPid)) return true;
-
- // A marker without a live apply-update process is allowed a short grace
- // period for the spawn/exit race, then it is safe to remove as stale.
- const markedAt = pending && Date.parse(pending.at);
- const gracePeriodMs = 10 * 60 * 1000;
- if (Number.isFinite(markedAt) && Date.now() - markedAt < gracePeriodMs) return true;
- try {
- fs.unlinkSync(UPDATE_PENDING_FILE);
- log('已清理确认没有更新进程的过期 pending.json,继续启动 daemon');
- } catch (error) {
- log('清理过期 pending.json 失败: ' + error.message);
- return true;
- }
- return false;
-}
+let child = null;
+let stopping = false;
+let restartDelay = 3000;
function log(...args) {
const line = `[${new Date().toISOString()}] ${args.join(' ')}\n`;
- try {
- fs.appendFileSync(LOG_FILE, line);
- } catch (_) {}
- // 前台运行时也输出(便于手动调试)
+ try { fs.appendFileSync(LOG_FILE, line); } catch (_) {}
try { process.stdout.write(line); } catch (_) {}
}
-function readPidFile() {
+function writePidFile() {
+ fs.mkdirSync(DATA_DIR, { recursive: true });
+ const temporary = PID_FILE + '.tmp.' + process.pid;
+ fs.writeFileSync(temporary, String(process.pid), 'utf8');
try {
- const text = fs.readFileSync(PID_FILE, 'utf8').trim();
- const pid = Number(text);
- if (!Number.isSafeInteger(pid) || pid <= 0 || String(pid) !== text) {
- throw new Error('watchdog.pid 内容无效');
- }
- return pid;
- } catch (error) {
- if (error && error.code === 'ENOENT') return null;
- throw error;
- }
-}
-
-function runProcessQuery(whereClause) {
- const helper = path.join(__dirname, 'windows-process-boundary.ps1');
- const expectedNode = String(process.execPath).replace(/'/g, "''");
- const command = buildNativeProcessQuery(helper,
- `Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { $_.Name -ieq 'node.exe' -and $_.ExecutablePath -ieq '${expectedNode}' } | Where-Object { ${whereClause} }`);
- const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command], {
- encoding: 'utf8', timeout: 10000, windowsHide: true,
- });
- return parseCimProcessResult(result, {
- requireCommandLine: true, requireCurrentOwner: true, requireNativeArguments: true,
- allowTransientNotFound: true,
- });
-}
-
-function queryProcess(pid) {
- return runProcessQuery(`[int]$_.ProcessId -eq ${pid}`);
-}
-
-function queryWatchdogProcessFamily(pid) {
- return runProcessQuery(`[int]$_.ProcessId -eq ${pid} -or [int]$_.ParentProcessId -eq ${pid}`);
-}
-
-function queryWatchdogProcesses() {
- return runProcessQuery("$_.Name -eq 'node.exe'");
-}
-
-function pidFileState() {
- const pid = readPidFile();
- if (!pid) {
- const untracked = filterVerifiedNodeProcesses(
- process.execPath, __filename, queryWatchdogProcesses()
- ).filter((item) => item.ProcessId !== process.pid)
- .map((item) => assertSameProcessIdentity(item, item));
- if (untracked.length === 1) {
- // The PID file is only a lock hint. A single exact watchdog process is
- // already bound to this profile by its Node path and entry script, so a
- // file lost during installation/update can be safely reconstructed.
- return { kind: 'recoverable', pid: untracked[0].ProcessId, watchdog: untracked[0], processes: queryWatchdogProcessFamily(untracked[0].ProcessId) };
- }
- if (untracked.length > 1) {
- return { kind: 'untracked', pid: null, processIds: untracked.map((item) => item.ProcessId) };
- }
- return { kind: 'absent', pid: null };
+ fs.renameSync(temporary, PID_FILE);
+ } catch (_) {
+ try { fs.unlinkSync(PID_FILE); } catch (_) {}
+ fs.renameSync(temporary, PID_FILE);
}
- if (pid === process.pid) return { kind: 'self', pid };
- const processes = queryWatchdogProcessFamily(pid);
- if (!processes.length) return { kind: 'stale', pid };
- const watchdog = assertVerifiedNodeProcess(pid, process.execPath, __filename, processes);
- assertSameProcessIdentity(watchdog, watchdog);
- return { kind: 'verified', pid, watchdog, processes };
-}
-
-function removePidFileIf(pid) {
- const current = readPidFile();
- if (current !== pid) throw new Error('watchdog.pid 在操作期间发生变化,拒绝删除');
- fs.unlinkSync(PID_FILE);
}
-function verifiedDaemonChildren(watchdogPid, processes) {
- const matches = filterVerifiedNodeProcesses(process.execPath, DAEMON_FILE, processes)
- .map((item) => assertSameProcessIdentity(item, item));
- for (const daemon of matches) {
- if (!Number.isSafeInteger(daemon.ParentProcessId) || daemon.ParentProcessId !== watchdogPid) {
- throw new Error(`无法验证 daemon PID=${daemon.ProcessId} 的 watchdog 父进程`);
- }
- }
- return matches;
-}
-
-function terminateVerifiedProcess(original, expectedScript, label, expectedParentPid, allowMissing = false) {
- const processes = queryProcess(original.ProcessId);
- if (!processes.length) {
- if (allowMissing) return false;
- throw new Error(`结束前无法再次验证 ${label} PID=${original.ProcessId}`);
- }
- const verified = assertVerifiedNodeProcess(
- original.ProcessId, process.execPath, expectedScript, processes
- );
- assertSameProcessIdentity(original, verified);
- if (expectedParentPid !== undefined && verified.ParentProcessId !== expectedParentPid) {
- throw new Error(`结束前无法再次验证 ${label} PID=${original.ProcessId} 的父进程`);
- }
- const result = spawnSync('taskkill', ['/F', '/PID', String(original.ProcessId)], {
- stdio: 'ignore', windowsHide: true, timeout: 10000,
- });
- if (result.error || result.status !== 0) {
- throw new Error(`无法结束已验证 ${label} PID=${original.ProcessId}`);
- }
- if (queryProcess(original.ProcessId).length) {
- throw new Error(`${label} PID=${original.ProcessId} 在结束后仍然存在`);
- }
- return true;
-}
-
-function stopVerifiedWatchdog() {
- let state = pidFileState();
- if (state.kind === 'absent') return;
- if (state.kind === 'self') throw new Error('stop 命令不能结束自身');
- if (state.kind === 'recoverable') {
- fs.writeFileSync(PID_FILE, String(state.pid), { flag: 'wx' });
- state = pidFileState();
- if (state.kind !== 'verified') throw new Error('恢复 watchdog.pid 后无法再次验证 watchdog 身份');
- log(`通过精确身份恢复缺失的 watchdog.pid=${state.pid}`);
- }
- if (state.kind === 'untracked') {
- throw new Error(`检测到没有 PID 文件的 watchdog 进程 PID=${state.processIds.join(',')},无法确定当前 profile,拒绝结束`);
- }
- if (state.kind === 'stale') {
- removePidFileIf(state.pid);
- log('已清理确认不存在的旧 watchdog.pid');
- return;
- }
- const daemons = verifiedDaemonChildren(state.pid, state.processes);
- // 先结束守护进程,防止它在 daemon 退出后竞态拉起新实例;子进程逐个复验并结束。
- terminateVerifiedProcess(state.watchdog, __filename, 'watchdog');
- for (const daemon of daemons) {
- terminateVerifiedProcess(daemon, DAEMON_FILE, 'daemon', state.pid, true);
- }
- removePidFileIf(state.pid);
-}
-
-if (process.argv.includes('stop')) {
- log('收到 stop 指令,退出中...');
- stopVerifiedWatchdog();
- process.exit(0);
-}
-
-// 单实例保护:用户可写 PID 文件只作候选,必须用 CIM 路径和命令行证明真实身份。
-const existing = pidFileState();
-if (existing.kind === 'verified') {
- log('已有 watchdog 实例在运行,本实例退出');
- process.exit(0);
-}
-if (existing.kind === 'self') throw new Error('watchdog.pid 意外指向当前进程');
-if (existing.kind === 'stale') {
- removePidFileIf(existing.pid);
- log('已清理确认不存在的旧 watchdog.pid,继续启动');
-}
-if (existing.kind === 'recoverable') {
+function removePidFile() {
try {
- fs.writeFileSync(PID_FILE, String(existing.pid), { flag: 'wx' });
- log(`通过精确身份恢复缺失的 watchdog.pid=${existing.pid},本实例退出`);
- } catch (error) {
- const current = readPidFile();
- if (current !== existing.pid) throw error;
- log(`watchdog.pid 已由并发启动恢复为 ${existing.pid},本实例退出`);
- }
- process.exit(0);
-}
-if (existing.kind === 'untracked') {
- throw new Error(`检测到没有 PID 文件的 watchdog 进程 PID=${existing.processIds.join(',')},拒绝启动重复实例`);
+ if (Number(fs.readFileSync(PID_FILE, 'utf8').trim()) === process.pid) fs.unlinkSync(PID_FILE);
+ } catch (_) {}
}
-fs.mkdirSync(DATA_DIR, { recursive: true });
-fs.writeFileSync(PID_FILE, String(process.pid), { flag: 'wx' });
-
-let child = null;
-let stopping = false;
-let restartDelay = 3000; // 初始 3s,连续崩溃递增,上限 60s
-
function startDaemon() {
if (stopping) return;
- const node = process.execPath;
const args = ['--experimental-sqlite', DAEMON_FILE];
- log('启动 daemon: ' + node + ' ' + args.join(' '));
- child = spawn(node, args, { stdio: 'ignore', windowsHide: true, env: process.env });
- child.on('error', (e) => {
- log('daemon 启动错误: ' + e.message);
- });
+ log('启动 daemon: ' + process.execPath + ' ' + args.join(' '));
+ child = spawn(process.execPath, args, { stdio: 'ignore', windowsHide: true, env: process.env });
+ child.on('error', (error) => log('daemon 启动错误: ' + error.message));
child.on('exit', (code, signal) => {
child = null;
- if (stopping) { log('daemon 已退出(watchdog 停止中)'); return; }
- // 自动更新标记存在:daemon 是在「更新替换」窗口内退出的(apply-update.ps1 正在换文件),
- // 绝不能立刻重启 daemon 抢占 47832 端口,否则会干扰替换甚至导致更新失败(历史偶发根因)。
- // 标记由 apply-update.ps1 成功/失败后删除;删除后靠新版 launcher/手动启动重新拉起。
- if (updatePendingIsActive()) {
- log('检测到更新标记 pending.json,跳过自动重启 daemon(等待 apply-update.ps1 完成替换)');
+ if (stopping) {
+ log('daemon 已退出(watchdog 停止中)');
return;
}
- log('daemon 退出 code=' + code + ' signal=' + signal + ',' + restartDelay + 'ms 后重启');
- setTimeout(startDaemon, restartDelay);
+ const delay = restartDelay;
+ log('daemon 退出 code=' + code + ' signal=' + signal + ',' + delay + 'ms 后重启');
+ setTimeout(startDaemon, delay);
restartDelay = Math.min(restartDelay * 2, 60000);
});
- // 正常存活 60s 后重置退避
setTimeout(() => { restartDelay = 3000; }, 60000);
}
-startDaemon();
-
-// 优雅停止:外部 kill(更新前)或 Ctrl+C
function shutdown() {
if (stopping) return;
stopping = true;
@@ -298,9 +78,27 @@ function shutdown() {
try { child.kill(); } catch (_) {}
}
setTimeout(() => {
- try { removePidFileIf(process.pid); } catch (_) {}
+ removePidFile();
+ try { lockServer.close(); } catch (_) {}
process.exit(0);
}, 800);
}
+
+const lockServer = net.createServer();
+lockServer.unref();
+lockServer.once('error', (error) => {
+ if (error && error.code === 'EADDRINUSE') {
+ log('当前 profile 的 watchdog 已在运行,本实例退出');
+ process.exit(0);
+ }
+ throw error;
+});
+lockServer.listen({ host: '127.0.0.1', port: LOCK_PORT, exclusive: true }, () => {
+ writePidFile();
+ log('watchdog 已获取回环单实例锁 port=' + LOCK_PORT + ' pid=' + process.pid);
+ startDaemon();
+});
+
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
+process.on('exit', removePidFile);
diff --git a/scripts/win-launcher.js b/scripts/win-launcher.js
index c81c754..d70d378 100644
--- a/scripts/win-launcher.js
+++ b/scripts/win-launcher.js
@@ -36,7 +36,7 @@ const {
selectPreferredDiscoveredBinary,
} = require('./windows-process-boundary.js');
let WINDOWS_PRIVILEGE = 'standard';
-if (process.platform === 'win32') {
+if (process.platform === 'win32' && process.env.WBSWITCH_NATIVE_LAUNCHER !== '1') {
try {
WINDOWS_PRIVILEGE = detectWindowsPrivilege();
} catch (error) {
@@ -1233,8 +1233,195 @@ async function injectNowOrPending() {
return true;
}
+function nativeHelperPath() {
+ return path.join(WORKDADDY_APP_DIR, 'WorkDaddyLauncher.exe');
+}
+
+function runNativeHelper(args, options = {}) {
+ const helper = nativeHelperPath();
+ if (!fs.existsSync(helper)) throw new Error('缺少原生启动器 WorkDaddyLauncher.exe');
+ const result = spawnSync(helper, args, {
+ encoding: 'utf8',
+ windowsHide: true,
+ timeout: options.timeout || 20000,
+ });
+ if (result.error) throw result.error;
+ return result;
+}
+
+function nativeWorkBuddyRunning() {
+ const result = runNativeHelper(['--check-workbuddy', '--profile', PROFILE.id]);
+ if (result.status === 10) return true;
+ if (result.status !== 0) throw new Error('原生 WorkBuddy 进程检测失败(错误码 ' + result.status + ')');
+ return false;
+}
+
+function findWorkBuddyNative() {
+ const candidates = [];
+ const add = (value) => {
+ const candidate = String(value || '').trim().replace(/^"(.*)"(?:,\d+)?$/, '$1').replace(/,\d+$/, '');
+ if (candidate && !candidates.some((item) => sameWindowsPath(item, candidate))) candidates.push(candidate);
+ };
+ add(process.env.WBSWITCH_WORKBUDDY_BIN);
+ add(PROFILE.appPath);
+ const local = process.env.LOCALAPPDATA || '';
+ const programFiles = process.env.ProgramFiles || '';
+ const programFilesX86 = process.env['ProgramFiles(x86)'] || '';
+ if (PROFILE.id === 'workbuddy-ai') {
+ add(path.join(local, 'Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'));
+ add(path.join(local, 'Programs', 'WorkBuddy AI', 'WorkBuddyAI.exe'));
+ add(path.join(programFiles, 'WorkBuddyAI', 'WorkBuddyAI.exe'));
+ add(path.join(programFiles, 'WorkBuddy AI', 'WorkBuddyAI.exe'));
+ add(path.join(programFilesX86, 'WorkBuddyAI', 'WorkBuddyAI.exe'));
+ add(path.join(programFilesX86, 'WorkBuddy AI', 'WorkBuddyAI.exe'));
+ } else {
+ add(path.join(local, 'Programs', 'WorkBuddy', 'WorkBuddy.exe'));
+ add(path.join(programFiles, 'WorkBuddy', 'WorkBuddy.exe'));
+ add(path.join(programFilesX86, 'WorkBuddy', 'WorkBuddy.exe'));
+ }
+ for (const candidate of candidates) {
+ try {
+ if (!fs.statSync(candidate).isFile()) continue;
+ const expectedName = PROFILE.id === 'workbuddy-ai' ? 'workbuddyai.exe' : 'workbuddy.exe';
+ if (path.win32.basename(candidate).toLowerCase() === expectedName) return fs.realpathSync.native(candidate);
+ } catch (_) {}
+ }
+ return null;
+}
+
+function nativeDaemonStatusMatches(status) {
+ const identity = readDaemonIdentity();
+ return Boolean(
+ status && status.ok === true &&
+ status.profile && status.profile.id === PROFILE.id &&
+ status.dataDir && sameWindowsPath(status.dataDir, DATA_DIR) &&
+ status.version === identity.version &&
+ status.buildId === identity.buildId &&
+ status.privilege === 'standard'
+ );
+}
+
+async function waitForNativeDaemon(attempts = 40) {
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
+ if (attempt > 0) await sleep(250);
+ const status = await readStatus();
+ if (nativeDaemonStatusMatches(status)) return status;
+ }
+ return null;
+}
+
+function stopNativeLifecycle() {
+ const result = runNativeHelper([
+ '--stop-lifecycle', '--profile', PROFILE.id, '--app-dir', WORKDADDY_APP_DIR,
+ ], { timeout: 30000 });
+ if (result.status !== 0) {
+ const detail = String(result.stderr || '').trim();
+ throw new Error('无法停止旧版 WorkDaddy 后台进程(错误码 ' + result.status + ')' + (detail ? ': ' + detail : ''));
+ }
+}
+
+async function ensureDaemonNative(nodeBin) {
+ fs.mkdirSync(path.join(DATA_DIR, 'accounts'), { recursive: true });
+ let status = await readStatus();
+ if (status && nativeDaemonStatusMatches(status)) {
+ log('daemon profile、版本、构建和标准权限均已验证,跳过启动');
+ return true;
+ }
+ if (status) {
+ log('daemon 身份或版本不匹配,使用原生 helper 停止当前 profile 生命周期');
+ stopNativeLifecycle();
+ await sleep(800);
+ }
+
+ const startWatchdog = () => {
+ log('通过内置 Node 启动无 CIM watchdog: ' + nodeBin);
+ const child = spawn(nodeBin, [WATCHDOG_SCRIPT], { detached: true, stdio: 'ignore', windowsHide: true, env: process.env });
+ child.unref();
+ };
+ startWatchdog();
+ status = await waitForNativeDaemon();
+ if (status) return true;
+
+ // A previous watchdog may own the OS lock while its daemon is unhealthy.
+ // Stop only the PID whose executable path is the bundled node, then retry once.
+ log('首次等待 daemon 超时,原生 helper 清理精确 lifecycle 后重试');
+ stopNativeLifecycle();
+ await sleep(800);
+ startWatchdog();
+ status = await waitForNativeDaemon();
+ if (status) return true;
+ throw new Error('等待 WorkDaddy 后台服务启动超时');
+}
+
+async function waitForWorkBuddyCdpNative(binary) {
+ const launched = launchWorkBuddy(binary);
+ log('WorkBuddy 启动请求已派发 method=' + launched.method + ' expectedPort=' + CDP_PORT +
+ (launched.pid ? ' pid=' + launched.pid : ''));
+ const deadline = Date.now() + CDP_STARTUP_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ await sleep(1000);
+ for (const port of cdpPortCandidates()) {
+ if (await isWorkBuddyCdpAt(port)) {
+ CDP_PORT = port;
+ process.env.WBSWITCH_CDP_PORT = String(port);
+ writeCdpPortFile(port);
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+async function nativeStartupMain() {
+ try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (_) {}
+ log('原生启动入口: scripts=' + SCRIPTS_DIR + ' data=' + DATA_DIR + ' pid=' + process.pid);
+ const nodeBin = path.join(SCRIPTS_DIR, 'runtime', 'node', 'node.exe');
+ if (!fs.existsSync(nodeBin)) throw new Error('安装文件不完整:缺少内置 Node.js');
+
+ await configureCdpPort();
+ await configureUiPort();
+ await ensureDaemonNative(nodeBin);
+
+ if (await isWorkBuddyCdp()) {
+ await injectNowOrPending();
+ log('WorkBuddy 已在 CDP 模式,组件注入已请求');
+ return 0;
+ }
+
+ const wb = findWorkBuddyNative();
+ if (!wb) {
+ await captureMessage('未找到 WorkBuddy.exe', { stage: 'windows-native-launcher-workbuddy-path' }).catch(() => {});
+ throw new Error('未找到 WorkBuddy,请先安装对应客户端');
+ }
+ if (nativeWorkBuddyRunning()) {
+ log('WorkBuddy 已运行但没有 CDP,交给原生启动器提示用户手动退出');
+ return 10;
+ }
+
+ const ok = await waitForWorkBuddyCdpNative(wb);
+ if (!ok) {
+ await captureMessage('等待 WorkBuddy CDP 端口超时', {
+ stage: 'windows-native-launcher-cdp-timeout', extra: { cdpPort: CDP_PORT, timeoutMs: CDP_STARTUP_TIMEOUT_MS },
+ }).catch(() => {});
+ return 3;
+ }
+ await sleep(1200);
+ await injectNowOrPending();
+ log('WorkBuddy 已由原生入口启动,组件注入已请求');
+ return 0;
+}
+
+// ---------- legacy script entry ----------
+
// ---------- main ----------
-if (require.main === module) (async () => {
+if (require.main === module && process.env.WBSWITCH_NATIVE_LAUNCHER === '1') {
+ nativeStartupMain().then((code) => process.exit(code)).catch((error) => {
+ log('原生启动路径异常: ' + (error && error.stack || error));
+ console.error(error && error.message || error);
+ captureException(error, { stage: 'windows-native-launcher-uncaught' })
+ .catch(() => {}).finally(() => process.exit(4));
+ });
+} else if (require.main === module) (async () => {
// 入口级 breadcrumb 必须先于 Node/PowerShell/进程探测写出,避免管理员启动时
// 探测耗时让 Windows Terminal 看起来像“空白无响应”;同一行也会落到 launcher.log。
try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (_) {}
diff --git a/scripts/win/workdaddy.iss b/scripts/win/workdaddy.iss
index bf5fd05..00e2aa1 100644
--- a/scripts/win/workdaddy.iss
+++ b/scripts/win/workdaddy.iss
@@ -24,8 +24,6 @@
#endif
#define AppUrl "https://github.com/babygoton/WorkDaddy"
-#define PowerShellPath "{sysnative}\WindowsPowerShell\v1.0\powershell.exe"
-#define PersistentPowerShellPath "{win}\System32\WindowsPowerShell\v1.0\powershell.exe"
[Setup]
AppId={#AppGuid}
@@ -58,61 +56,189 @@ UninstallDisplayName={#ProductName}
Name: "chinesesimplified"; MessagesFile: "ChineseSimplified.isl"
[Files]
-Source: "{#StageRoot}\scripts\prepare-win-install.ps1"; Flags: dontcopy
-Source: "{#StageRoot}\scripts\windows-process-boundary.ps1"; Flags: dontcopy
-Source: "{#StageRoot}\scripts\*"; DestDir: "{app}\scripts"; Excludes: "prepare-win-install.ps1,runtime\node\*"; Flags: ignoreversion recursesubdirs createallsubdirs
-Source: "{#StageRoot}\scripts\runtime\node\*"; DestDir: "{app}\scripts\runtime\node"; Flags: ignoreversion recursesubdirs createallsubdirs; Check: ShouldReplaceRuntime
+Source: "{#StageRoot}\WorkDaddyLauncher.exe"; DestDir: "{app}"; Flags: ignoreversion
+Source: "{#StageRoot}\WorkDaddyLauncher.exe"; Flags: dontcopy
+Source: "{#StageRoot}\scripts\*"; DestDir: "{app}\scripts"; Excludes: "runtime\node\*"; Flags: ignoreversion recursesubdirs createallsubdirs
+Source: "{#StageRoot}\scripts\runtime\node\*"; DestDir: "{app}\scripts\runtime\node"; Flags: ignoreversion recursesubdirs createallsubdirs
[Icons]
-Name: "{group}\{#ProductName}"; Filename: "{sys}\wscript.exe"; Parameters: "//nologo ""{app}\scripts\launcher-hidden.vbs"""; WorkingDir: "{app}\scripts"; IconFilename: "{app}\scripts\WorkDaddy.ico"
-Name: "{userdesktop}\{#ProductName}"; Filename: "{sys}\wscript.exe"; Parameters: "//nologo ""{app}\scripts\launcher-hidden.vbs"""; WorkingDir: "{app}\scripts"; IconFilename: "{app}\scripts\WorkDaddy.ico"
+Name: "{group}\{#ProductName}"; Filename: "{app}\WorkDaddyLauncher.exe"; WorkingDir: "{app}"; IconFilename: "{app}\scripts\WorkDaddy.ico"
+Name: "{userdesktop}\{#ProductName}"; Filename: "{app}\WorkDaddyLauncher.exe"; WorkingDir: "{app}"; IconFilename: "{app}\scripts\WorkDaddy.ico"
+
+[Registry]
+Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: none; ValueName: "WorkDaddy"; Flags: deletevalue
+Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: none; ValueName: "WorkDaddy AI"; Flags: deletevalue
[Run]
-Filename: "{#PowerShellPath}"; Description: "{#StartDescription}"; Parameters: "-NoProfile -WindowStyle Hidden -ExecutionPolicy RemoteSigned -File ""{app}\scripts\install-win.ps1"" -SrcDir ""{app}\scripts"" -AppDir ""{app}"" -Profile ""{#ProfileId}"""; WorkingDir: "{app}\scripts"; Flags: waituntilterminated postinstall skipifsilent
+Filename: "{app}\WorkDaddyLauncher.exe"; Description: "{#StartDescription}"; WorkingDir: "{app}"; Flags: nowait postinstall skipifsilent runasoriginaluser
[UninstallRun]
-Filename: "{#PowerShellPath}"; Parameters: "-NoProfile -WindowStyle Hidden -ExecutionPolicy RemoteSigned -File ""{app}\scripts\uninstall-win.ps1"" -AppDir ""{app}"" -Profile ""{#ProfileId}"" -SkipAppRemoval"; WorkingDir: "{app}\scripts"; Flags: waituntilterminated
+Filename: "{app}\WorkDaddyLauncher.exe"; Parameters: "--stop-lifecycle --profile ""{#ProfileId}"" --app-dir ""{app}"""; WorkingDir: "{app}"; Flags: runhidden waituntilterminated; RunOnceId: "StopWorkDaddyLifecycle"
[UninstallDelete]
Type: filesandordirs; Name: "{app}"
[Code]
+function RunNativeHelper(const Mode: String; var ResultCode: Integer): Boolean;
var
- PreserveExistingLifecycle: Boolean;
+ Parameters: String;
+begin
+ ExtractTemporaryFile('WorkDaddyLauncher.exe');
+ Parameters := Mode + ' --profile "{#ProfileId}" --app-dir "' + ExpandConstant('{app}') + '"';
+ Result := ExecAsOriginalUser(
+ ExpandConstant('{tmp}\WorkDaddyLauncher.exe'),
+ Parameters,
+ ExpandConstant('{tmp}'),
+ SW_HIDE,
+ ewWaitUntilTerminated,
+ ResultCode
+ );
+end;
+
+function ShowWorkBuddyCloseDialog(): Integer;
+var
+ Dialog: TSetupForm;
+ MessageLabel: TNewStaticText;
+ DetailLabel: TNewStaticText;
+ RetryButton: TNewButton;
+ TerminateButton: TNewButton;
+ CancelButton: TNewButton;
+begin
+ Dialog := CreateCustomForm(ScaleX(480), ScaleY(196), False, False);
+ try
+ Dialog.Caption := '请先退出 WorkBuddy';
+ Dialog.ClientWidth := ScaleX(480);
+ Dialog.ClientHeight := ScaleY(196);
+ Dialog.Position := poScreenCenter;
+
+ MessageLabel := TNewStaticText.Create(Dialog);
+ MessageLabel.Parent := Dialog;
+ MessageLabel.Left := ScaleX(20);
+ MessageLabel.Top := ScaleY(18);
+ MessageLabel.Width := ScaleX(440);
+ MessageLabel.Height := ScaleY(42);
+ MessageLabel.AutoSize := False;
+ MessageLabel.WordWrap := True;
+ MessageLabel.Font.Style := [fsBold];
+ MessageLabel.Caption := '安装前需要完全退出当前的 WorkBuddy。';
+
+ DetailLabel := TNewStaticText.Create(Dialog);
+ DetailLabel.Parent := Dialog;
+ DetailLabel.Left := ScaleX(20);
+ DetailLabel.Top := ScaleY(64);
+ DetailLabel.Width := ScaleX(440);
+ DetailLabel.Height := ScaleY(50);
+ DetailLabel.AutoSize := False;
+ DetailLabel.WordWrap := True;
+ DetailLabel.Caption := '退出后点击“重新检测”。如果客户端窗口已关闭但后台进程仍未退出,可以点击“结束进程”。只处理当前客户端,不会影响另一个客户端。';
+
+ RetryButton := TNewButton.Create(Dialog);
+ RetryButton.Parent := Dialog;
+ RetryButton.Width := ScaleX(104);
+ RetryButton.Height := ScaleY(28);
+ RetryButton.Left := Dialog.ClientWidth - ScaleX(330);
+ RetryButton.Top := ScaleY(150);
+ RetryButton.Caption := '重新检测';
+ RetryButton.Default := True;
+ RetryButton.ModalResult := mrOk;
+
+ TerminateButton := TNewButton.Create(Dialog);
+ TerminateButton.Parent := Dialog;
+ TerminateButton.Width := ScaleX(104);
+ TerminateButton.Height := ScaleY(28);
+ TerminateButton.Left := Dialog.ClientWidth - ScaleX(216);
+ TerminateButton.Top := ScaleY(150);
+ TerminateButton.Caption := '结束进程';
+ TerminateButton.ModalResult := mrYes;
+
+ CancelButton := TNewButton.Create(Dialog);
+ CancelButton.Parent := Dialog;
+ CancelButton.Width := ScaleX(104);
+ CancelButton.Height := ScaleY(28);
+ CancelButton.Left := Dialog.ClientWidth - ScaleX(106);
+ CancelButton.Top := ScaleY(150);
+ CancelButton.Caption := '取消';
+ CancelButton.Cancel := True;
+ CancelButton.ModalResult := mrCancel;
+
+ Result := Dialog.ShowModal();
+ finally
+ Dialog.Free();
+ end;
+end;
-function ShouldReplaceRuntime(): Boolean;
+function EnsureWorkBuddyClosed(): Boolean;
+var
+ ResultCode: Integer;
+ Choice: Integer;
begin
- Result := not PreserveExistingLifecycle;
+ Result := False;
+ while True do
+ begin
+ if not RunNativeHelper('--check-workbuddy', ResultCode) then
+ begin
+ MsgBox('无法启动 WorkBuddy 进程检测。请检查安全软件是否拦截安装程序。', mbError, MB_OK);
+ exit;
+ end;
+ if ResultCode = 0 then
+ begin
+ Result := True;
+ exit;
+ end;
+ if ResultCode <> 10 then
+ begin
+ MsgBox('无法确认 WorkBuddy 是否已退出(错误码 ' + IntToStr(ResultCode) + ')。安装已停止。', mbError, MB_OK);
+ exit;
+ end;
+ Choice := ShowWorkBuddyCloseDialog();
+ if Choice = mrCancel then
+ exit;
+ if Choice = mrYes then
+ begin
+ if not RunNativeHelper('--terminate-workbuddy', ResultCode) then
+ begin
+ MsgBox('无法启动 WorkBuddy 结束进程操作。请检查安全软件是否拦截安装程序。', mbError, MB_OK);
+ exit;
+ end;
+ if ResultCode <> 0 then
+ begin
+ MsgBox('无法安全结束当前 WorkBuddy 进程。可能原因:' + #13#10 +
+ '• WorkBuddy 由其他用户或管理员权限启动,当前安装器无法跨权限结束;' + #13#10 +
+ '• 系统正在退出客户端,进程状态暂时不可查询;' + #13#10 +
+ '• 安全软件或系统策略阻止结束进程,或检测到多个安装目录。' + #13#10 +
+ '请手动结束当前客户端后点击“重新检测”。', mbError, MB_OK);
+ end;
+ end;
+ end;
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
var
ResultCode: Integer;
- Parameters: String;
begin
Result := '';
- if not DirExists(ExpandConstant('{app}')) then
+ if IsAdminInstallMode then
+ begin
+ Result := '当前安装程序是以管理员权限运行的,无法继续安装。为避免 WorkDaddy 后台出现权限不一致,请点击“取消”,关闭安装程序后直接双击安装包重新运行;不要选择“以管理员身份运行”。UAC 无需关闭。';
exit;
-
- ExtractTemporaryFile('prepare-win-install.ps1');
- ExtractTemporaryFile('windows-process-boundary.ps1');
- Parameters := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "' +
- ExpandConstant('{tmp}\prepare-win-install.ps1') + '" -BoundaryPath "' +
- ExpandConstant('{tmp}\windows-process-boundary.ps1') + '" -AppDir "' +
- ExpandConstant('{app}') + '" -Profile "{#ProfileId}" -ExpectedVersion "{#AppVersion}"';
- if not Exec(ExpandConstant('{#PowerShellPath}'), Parameters, '', SW_HIDE,
- ewWaitUntilTerminated, ResultCode) then
+ end;
+ if not EnsureWorkBuddyClosed() then
begin
- Result := '无法启动安装前的 WorkDaddy 进程检查。';
+ Result := '无法确认 WorkBuddy 已退出。可能原因是客户端仍有后台进程、进程权限高于当前用户、系统正在退出客户端,或安全软件阻止了进程检测。请手动结束当前客户端后重新运行安装程序。';
exit;
end;
- if ResultCode = 10 then
+
+ if not RunNativeHelper('--stop-lifecycle', ResultCode) then
begin
- PreserveExistingLifecycle := True;
- Result := '';
- end
- else if ResultCode = 5 then
- Result := '无法判断安装程序的权限。请关闭安全软件对 PowerShell 的拦截后,重新打开安装包。'
+ Result := '无法启动 WorkDaddy 后台进程清理。可能原因是安装器原始用户权限不可用、安全软件拦截了临时 helper,或临时目录不可写。请点击“取消”,关闭安装程序后直接双击安装包重新运行;不要选择“以管理员身份运行”。UAC 无需关闭。';
+ exit;
+ end;
+ if ResultCode = 11 then
+ Result := '无法安全停止 WorkDaddy 后台进程。可能原因:' + #13#10 +
+ '• 正在运行的 WorkDaddy 使用了高于当前安装器的权限,普通安装器不会跨权限强行结束;' + #13#10 +
+ '• WorkDaddy 退出后仍有后台进程未及时结束,或文件仍被占用;' + #13#10 +
+ '• 安全软件或系统策略阻止后台进程退出。' + #13#10 +
+ '请手动结束 WorkDaddy 后重试,并确保 WorkDaddy 通过普通方式启动。'
else if ResultCode <> 0 then
- Result := '安装被后台进程阻止:可能存在管理员权限运行的旧版 WorkDaddy,当前安装程序无法确认并停止它。请先退出 WorkBuddy;仍无法安装时,请右键以管理员身份运行本安装包一次完成迁移。';
+ Result := '无法安全停止 WorkDaddy 后台进程(错误码 ' + IntToStr(ResultCode) + ')。可能原因是进程仍在退出、文件被占用、安装目录不一致,或安全软件拦截。请手动结束 WorkDaddy 后重试。';
end;
diff --git a/scripts/windows-installer-launch.js b/scripts/windows-installer-launch.js
new file mode 100644
index 0000000..9ec0a74
--- /dev/null
+++ b/scripts/windows-installer-launch.js
@@ -0,0 +1,16 @@
+'use strict';
+
+const { spawn } = require('node:child_process');
+
+function launchWindowsInstaller(installerPath, spawnImpl = spawn) {
+ if (typeof installerPath !== 'string' || !/\.exe$/i.test(installerPath)) {
+ throw new Error('Windows installer path must point to Setup.exe');
+ }
+ return spawnImpl(installerPath, [], {
+ detached: true,
+ stdio: 'ignore',
+ windowsHide: false,
+ });
+}
+
+module.exports = { launchWindowsInstaller };
diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.go
new file mode 100644
index 0000000..87fc31f
--- /dev/null
+++ b/scripts/windows-native/main.go
@@ -0,0 +1,586 @@
+//go:build windows
+
+package main
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+ "unsafe"
+)
+
+const (
+ profileCN = "workbuddy-cn"
+ profileAI = "workbuddy-ai"
+
+ exitFailure = 4
+ exitElevated = 5
+ exitWorkBuddyRunning = 10
+ exitAccessDenied = 11
+ exitIdentityMismatch = 12
+ exitUsage = 20
+
+ processTerminate = 0x0001
+ processQueryLimitedInformation = 0x1000
+ synchronize = 0x00100000
+ tokenQuery = 0x0008
+ tokenElevation = 20 // TokenElevation
+ th32csSnapProcess = 0x00000002
+ maxPath = 260
+ infinite = 0xffffffff
+ waitObject0 = 0
+ errorAlreadyExists = 183
+ mbOK = 0x00000000
+ mbIconWarning = 0x00000030
+ mbIconError = 0x00000010
+ mbRetryCancel = 0x00000005
+ idRetry = 4
+)
+
+var (
+ kernel32 = syscall.NewLazyDLL("kernel32.dll")
+ advapi32 = syscall.NewLazyDLL("advapi32.dll")
+ user32 = syscall.NewLazyDLL("user32.dll")
+ procCreateMutexW = kernel32.NewProc("CreateMutexW")
+ procGetCurrentProcess = kernel32.NewProc("GetCurrentProcess")
+ procOpenProcessToken = advapi32.NewProc("OpenProcessToken")
+ procGetTokenInformation = advapi32.NewProc("GetTokenInformation")
+ procCreateToolhelp32Snapshot = kernel32.NewProc("CreateToolhelp32Snapshot")
+ procProcess32FirstW = kernel32.NewProc("Process32FirstW")
+ procProcess32NextW = kernel32.NewProc("Process32NextW")
+ procOpenProcess = kernel32.NewProc("OpenProcess")
+ procQueryFullProcessImageName = kernel32.NewProc("QueryFullProcessImageNameW")
+ procTerminateProcess = kernel32.NewProc("TerminateProcess")
+ procWaitForSingleObject = kernel32.NewProc("WaitForSingleObject")
+ procMessageBoxW = user32.NewProc("MessageBoxW")
+)
+
+type processEntry32 struct {
+ Size uint32
+ Usage uint32
+ ProcessID uint32
+ DefaultHeapID uintptr
+ ModuleID uint32
+ Threads uint32
+ ParentProcessID uint32
+ PriorityClassBase int32
+ Flags uint32
+ ExeFile [maxPath]uint16
+}
+
+type processRecord struct {
+ PID uint32 `json:"pid"`
+ Name string `json:"name"`
+ Path string `json:"path,omitempty"`
+}
+
+type lockOwner struct {
+ PID int `json:"pid"`
+}
+
+func utf16Ptr(value string) *uint16 {
+ ptr, err := syscall.UTF16PtrFromString(value)
+ if err != nil {
+ panic(err)
+ }
+ return ptr
+}
+
+func messageBox(title, message string, flags uintptr) int {
+ result, _, _ := procMessageBoxW.Call(0, uintptr(unsafe.Pointer(utf16Ptr(message))), uintptr(unsafe.Pointer(utf16Ptr(title))), flags)
+ return int(result)
+}
+
+func isElevated() (bool, error) {
+ current, _, _ := procGetCurrentProcess.Call()
+ var token syscall.Handle
+ result, _, callErr := procOpenProcessToken.Call(current, tokenQuery, uintptr(unsafe.Pointer(&token)))
+ if result == 0 {
+ return false, callErr
+ }
+ defer syscall.CloseHandle(token)
+ var elevation uint32
+ var returned uint32
+ result, _, callErr = procGetTokenInformation.Call(
+ uintptr(token), tokenElevation, uintptr(unsafe.Pointer(&elevation)), unsafe.Sizeof(elevation), uintptr(unsafe.Pointer(&returned)),
+ )
+ if result == 0 {
+ return false, callErr
+ }
+ return elevation != 0, nil
+}
+
+func acquireMutex(profile string) (syscall.Handle, bool, error) {
+ name := "Local\\WorkDaddyLauncher-" + profile
+ handle, _, callErr := procCreateMutexW.Call(0, 0, uintptr(unsafe.Pointer(utf16Ptr(name))))
+ if handle == 0 {
+ return 0, false, callErr
+ }
+ alreadyExists := errors.Is(callErr, syscall.Errno(errorAlreadyExists))
+ return syscall.Handle(handle), alreadyExists, nil
+}
+
+func executableDir() (string, error) {
+ exe, err := os.Executable()
+ if err != nil {
+ return "", err
+ }
+ resolved, err := filepath.EvalSymlinks(exe)
+ if err == nil {
+ exe = resolved
+ }
+ return filepath.Dir(exe), nil
+}
+
+func normalizeProfile(profile string) string {
+ if strings.EqualFold(strings.TrimSpace(profile), profileAI) {
+ return profileAI
+ }
+ return profileCN
+}
+
+func readProfile(appDir string) string {
+ if value := argumentValue("--profile"); value != "" {
+ return normalizeProfile(value)
+ }
+ data, err := os.ReadFile(filepath.Join(appDir, "scripts", "profile-id.txt"))
+ if err == nil {
+ return normalizeProfile(string(data))
+ }
+ return profileCN
+}
+
+func argumentValue(name string) string {
+ for index, arg := range os.Args[1:] {
+ if arg == name && index+2 <= len(os.Args[1:]) {
+ return os.Args[index+2]
+ }
+ if strings.HasPrefix(arg, name+"=") {
+ return strings.TrimPrefix(arg, name+"=")
+ }
+ }
+ return ""
+}
+
+func hasArgument(name string) bool {
+ for _, arg := range os.Args[1:] {
+ if arg == name {
+ return true
+ }
+ }
+ return false
+}
+
+func dataDir(profile string) (string, error) {
+ root := os.Getenv("APPDATA")
+ if root == "" {
+ return "", errors.New("APPDATA is not available")
+ }
+ root = filepath.Join(root, "WorkDaddy")
+ if profile == profileAI {
+ return filepath.Join(root, "profiles", profileAI), nil
+ }
+ return root, nil
+}
+
+func productName(profile string) string {
+ if profile == profileAI {
+ return "WorkDaddy AI"
+ }
+ return "WorkDaddy"
+}
+
+func workBuddyImage(profile string) string {
+ if profile == profileAI {
+ return "WorkBuddyAI.exe"
+ }
+ return "WorkBuddy.exe"
+}
+
+func enumerateProcesses() ([]processRecord, error) {
+ snapshot, _, callErr := procCreateToolhelp32Snapshot.Call(th32csSnapProcess, 0)
+ if snapshot == uintptr(syscall.InvalidHandle) {
+ return nil, callErr
+ }
+ defer syscall.CloseHandle(syscall.Handle(snapshot))
+
+ entry := processEntry32{Size: uint32(unsafe.Sizeof(processEntry32{}))}
+ result, _, callErr := procProcess32FirstW.Call(snapshot, uintptr(unsafe.Pointer(&entry)))
+ if result == 0 {
+ return nil, callErr
+ }
+ var records []processRecord
+ for {
+ name := syscall.UTF16ToString(entry.ExeFile[:])
+ records = append(records, processRecord{PID: entry.ProcessID, Name: name, Path: queryProcessPath(entry.ProcessID)})
+ entry.Size = uint32(unsafe.Sizeof(processEntry32{}))
+ result, _, _ = procProcess32NextW.Call(snapshot, uintptr(unsafe.Pointer(&entry)))
+ if result == 0 {
+ break
+ }
+ }
+ return records, nil
+}
+
+func openProcess(pid uint32, access uint32) (syscall.Handle, error) {
+ handle, _, callErr := procOpenProcess.Call(uintptr(access), 0, uintptr(pid))
+ if handle == 0 {
+ return 0, callErr
+ }
+ return syscall.Handle(handle), nil
+}
+
+func queryProcessPath(pid uint32) string {
+ handle, err := openProcess(pid, processQueryLimitedInformation)
+ if err != nil {
+ return ""
+ }
+ defer syscall.CloseHandle(handle)
+ buffer := make([]uint16, 32768)
+ size := uint32(len(buffer))
+ result, _, _ := procQueryFullProcessImageName.Call(
+ uintptr(handle), 0, uintptr(unsafe.Pointer(&buffer[0])), uintptr(unsafe.Pointer(&size)),
+ )
+ if result == 0 || size == 0 {
+ return ""
+ }
+ return syscall.UTF16ToString(buffer[:size])
+}
+
+func matchingWorkBuddyProcesses(profile string) ([]processRecord, error) {
+ records, err := enumerateProcesses()
+ if err != nil {
+ return nil, err
+ }
+ expected := workBuddyImage(profile)
+ matched := make([]processRecord, 0)
+ for _, record := range records {
+ if strings.EqualFold(record.Name, expected) {
+ matched = append(matched, record)
+ }
+ }
+ return matched, nil
+}
+
+func samePath(left, right string) bool {
+ return strings.EqualFold(filepath.Clean(left), filepath.Clean(right))
+}
+
+func readPID(path string) int {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return 0
+ }
+ pid, _ := strconv.Atoi(strings.TrimSpace(string(data)))
+ return pid
+}
+
+func readLockPID(path string) int {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return 0
+ }
+ var owner lockOwner
+ if json.Unmarshal(data, &owner) != nil {
+ return 0
+ }
+ return owner.PID
+}
+
+func terminateExactProcess(pid int, expectedPath string, label string) (bool, int, error) {
+ if pid <= 0 {
+ return false, 0, nil
+ }
+ actual := queryProcessPath(uint32(pid))
+ if actual == "" {
+ // A process can exit between reading the PID file and querying it.
+ handle, err := openProcess(uint32(pid), synchronize)
+ if err != nil {
+ if errors.Is(err, syscall.Errno(87)) { // ERROR_INVALID_PARAMETER: PID no longer exists.
+ return false, 0, nil
+ }
+ if errors.Is(err, syscall.ERROR_ACCESS_DENIED) {
+ return false, exitAccessDenied, fmt.Errorf("PID %d cannot be inspected at standard privilege", pid)
+ }
+ return false, exitFailure, err
+ }
+ waitResult, _, _ := procWaitForSingleObject.Call(uintptr(handle), 2000)
+ syscall.CloseHandle(handle)
+ if waitResult == waitObject0 {
+ return false, 0, nil
+ }
+ return false, exitIdentityMismatch, fmt.Errorf("PID %d %s executable path is unavailable", pid, label)
+ }
+ if !samePath(actual, expectedPath) {
+ return false, exitIdentityMismatch, fmt.Errorf("PID %d is %s, expected %s", pid, actual, expectedPath)
+ }
+ handle, err := openProcess(uint32(pid), processTerminate|synchronize|processQueryLimitedInformation)
+ if err != nil {
+ if errors.Is(err, syscall.ERROR_ACCESS_DENIED) {
+ return false, exitAccessDenied, fmt.Errorf("PID %d %s cannot be terminated at standard privilege", pid, label)
+ }
+ return false, exitFailure, err
+ }
+ defer syscall.CloseHandle(handle)
+ result, _, callErr := procTerminateProcess.Call(uintptr(handle), 0)
+ if result == 0 {
+ return false, exitFailure, callErr
+ }
+ waitResult, _, callErr := procWaitForSingleObject.Call(uintptr(handle), 15000)
+ if waitResult != waitObject0 {
+ return false, exitFailure, fmt.Errorf("PID %d did not exit: %v", pid, callErr)
+ }
+ return true, 0, nil
+}
+
+func terminateExactNode(pid int, expectedNode string) (bool, int, error) {
+ return terminateExactProcess(pid, expectedNode, "node")
+}
+
+func uniqueRunningWorkBuddyPath(profile string, matches []processRecord) (string, error) {
+ paths := make([]string, 0, len(matches))
+ for _, match := range matches {
+ if strings.TrimSpace(match.Path) == "" {
+ return "", fmt.Errorf("PID %d WorkBuddy executable path is unavailable", match.PID)
+ }
+ found := false
+ for _, existing := range paths {
+ if samePath(existing, match.Path) {
+ found = true
+ break
+ }
+ }
+ if !found {
+ paths = append(paths, match.Path)
+ }
+ }
+ if len(paths) != 1 {
+ return "", fmt.Errorf("发现多个 %s 安装目录中的 WorkBuddy 进程,已拒绝批量结束", productName(profile))
+ }
+ return paths[0], nil
+}
+
+func terminateWorkBuddy(profile string) int {
+ elevated, err := isElevated()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "cannot determine helper privilege:", err)
+ return exitFailure
+ }
+ if elevated {
+ fmt.Fprintln(os.Stderr, "WorkBuddy termination requires standard user privilege")
+ return exitAccessDenied
+ }
+ matches, err := matchingWorkBuddyProcesses(profile)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return exitFailure
+ }
+ if len(matches) == 0 {
+ return 0
+ }
+ expectedPath, err := uniqueRunningWorkBuddyPath(profile, matches)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return exitIdentityMismatch
+ }
+ for _, match := range matches {
+ if !samePath(match.Path, expectedPath) {
+ continue
+ }
+ if _, code, stopErr := terminateExactProcess(int(match.PID), expectedPath, "WorkBuddy"); stopErr != nil {
+ fmt.Fprintln(os.Stderr, stopErr)
+ return code
+ }
+ }
+ return 0
+}
+
+func stopLifecycle(profile, appDir string) int {
+ dir, err := dataDir(profile)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return exitFailure
+ }
+ expectedNode := filepath.Join(appDir, "scripts", "runtime", "node", "node.exe")
+ pidFiles := []struct {
+ path string
+ pid int
+ }{
+ {filepath.Join(dir, "watchdog.pid"), readPID(filepath.Join(dir, "watchdog.pid"))},
+ {filepath.Join(dir, ".daemon.lock"), readLockPID(filepath.Join(dir, ".daemon.lock"))},
+ }
+ seen := map[int]bool{}
+ for _, candidate := range pidFiles {
+ if candidate.pid <= 0 || seen[candidate.pid] {
+ continue
+ }
+ seen[candidate.pid] = true
+ _, code, stopErr := terminateExactNode(candidate.pid, expectedNode)
+ if stopErr != nil {
+ fmt.Fprintln(os.Stderr, stopErr)
+ return code
+ }
+ }
+ for _, candidate := range pidFiles {
+ if candidate.path != "" {
+ _ = os.Remove(candidate.path)
+ }
+ }
+ return 0
+}
+
+func appendLog(dir string, args ...any) *os.File {
+ _ = os.MkdirAll(dir, 0700)
+ file, err := os.OpenFile(filepath.Join(dir, "native-launcher.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
+ if err != nil {
+ return nil
+ }
+ fmt.Fprintln(file, append([]any{time.Now().Format(time.RFC3339)}, args...)...)
+ return file
+}
+
+func runNodeLauncher(appDir, profile string) int {
+ dir, err := dataDir(profile)
+ if err != nil {
+ messageBox(productName(profile), "无法确定 WorkDaddy 数据目录:"+err.Error(), mbOK|mbIconError)
+ return exitFailure
+ }
+ logFile := appendLog(dir, "launch", "profile="+profile, "appDir="+appDir)
+ if logFile != nil {
+ defer logFile.Close()
+ }
+ node := filepath.Join(appDir, "scripts", "runtime", "node", "node.exe")
+ launcher := filepath.Join(appDir, "scripts", "win-launcher.js")
+ if _, err := os.Stat(node); err != nil {
+ messageBox(productName(profile), "安装文件不完整:找不到内置 Node.js。请重新安装。", mbOK|mbIconError)
+ return exitFailure
+ }
+ if _, err := os.Stat(launcher); err != nil {
+ messageBox(productName(profile), "安装文件不完整:找不到启动脚本。请重新安装。", mbOK|mbIconError)
+ return exitFailure
+ }
+
+ for {
+ cmd := exec.Command(node, launcher)
+ cmd.Dir = filepath.Join(appDir, "scripts")
+ cmd.Env = append(os.Environ(), "WBSWITCH_NATIVE_LAUNCHER=1", "WBSWITCH_PROFILE="+profile, "WBSWITCH_APP_DIR="+appDir)
+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
+ if logFile != nil {
+ cmd.Stdout = io.MultiWriter(logFile)
+ cmd.Stderr = io.MultiWriter(logFile)
+ }
+ err := cmd.Run()
+ code := 0
+ if err != nil {
+ var exitErr *exec.ExitError
+ if errors.As(err, &exitErr) {
+ code = exitErr.ExitCode()
+ } else {
+ code = exitFailure
+ }
+ }
+ if code == exitWorkBuddyRunning {
+ choice := messageBox(productName(profile), "WorkBuddy 已经打开,但没有启用 WorkDaddy 所需的调试端口。\n\n请完全退出 WorkBuddy,然后点击“重试”。", mbRetryCancel|mbIconWarning)
+ if choice == idRetry {
+ continue
+ }
+ return 0
+ }
+ if code != 0 {
+ messageBox(productName(profile), fmt.Sprintf("启动失败(错误码 %d)。\n\n详细信息已写入 native-launcher.log。", code), mbOK|mbIconError)
+ }
+ return code
+ }
+}
+
+func helperMain(appDir, profile string) (bool, int) {
+ if hasArgument("--check-workbuddy") {
+ matches, err := matchingWorkBuddyProcesses(profile)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return true, exitFailure
+ }
+ if len(matches) > 0 {
+ return true, exitWorkBuddyRunning
+ }
+ return true, 0
+ }
+ if hasArgument("--list-workbuddy") {
+ matches, err := matchingWorkBuddyProcesses(profile)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return true, exitFailure
+ }
+ _ = json.NewEncoder(os.Stdout).Encode(matches)
+ return true, 0
+ }
+ if hasArgument("--terminate-workbuddy") {
+ return true, terminateWorkBuddy(profile)
+ }
+ if hasArgument("--stop-lifecycle") {
+ elevated, err := isElevated()
+ if err != nil {
+ 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)
+ }
+ if hasArgument("--self-test") {
+ elevated, err := isElevated()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return true, exitFailure
+ }
+ _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"profile": profile, "appDir": appDir, "elevated": elevated})
+ return true, 0
+ }
+ return false, 0
+}
+
+func main() {
+ appDir, err := executableDir()
+ if err != nil {
+ os.Exit(exitFailure)
+ }
+ profile := readProfile(appDir)
+ if handled, code := helperMain(appDir, profile); handled {
+ os.Exit(code)
+ }
+
+ elevated, err := isElevated()
+ if err != nil {
+ messageBox(productName(profile), "无法确认当前 Windows 权限,已停止启动。", mbOK|mbIconError)
+ os.Exit(exitFailure)
+ }
+ if elevated {
+ messageBox(productName(profile), "请使用普通方式启动 WorkDaddy,不要选择“以管理员身份运行”。\n\nUAC 可以保持开启;正常双击快捷方式不会请求管理员权限。", mbOK|mbIconWarning)
+ os.Exit(exitElevated)
+ }
+
+ mutex, alreadyRunning, err := acquireMutex(profile)
+ if err != nil {
+ messageBox(productName(profile), "无法创建启动锁:"+err.Error(), mbOK|mbIconError)
+ os.Exit(exitFailure)
+ }
+ defer syscall.CloseHandle(mutex)
+ if alreadyRunning {
+ os.Exit(0)
+ }
+ os.Exit(runNodeLauncher(appDir, profile))
+}
diff --git a/scripts/workbuddy-compat.js b/scripts/workbuddy-compat.js
new file mode 100644
index 0000000..278b8aa
--- /dev/null
+++ b/scripts/workbuddy-compat.js
@@ -0,0 +1,364 @@
+'use strict';
+
+// WorkBuddy renderer compatibility seam. Keep volatile DOM/React discovery here;
+// inject.js owns user-facing behavior and calls these selectors through one API.
+(function (root, factory) {
+ var api = factory();
+ if (typeof module !== 'undefined' && module.exports) module.exports = api;
+ if (root) root.__wbsWorkBuddyCompat = api;
+})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
+ function hasQueueMethods(value) {
+ return !!value && typeof value === 'object' &&
+ typeof value.enqueueConversationMessageQueueItem === 'function' &&
+ typeof value.pauseConversationMessageQueue === 'function';
+ }
+
+ function isVisible(element) {
+ if (!element || typeof element.getBoundingClientRect !== 'function') return false;
+ var rect = element.getBoundingClientRect();
+ return rect.width > 0 && rect.height > 0;
+ }
+
+ function findModernToolbar(doc) {
+ if (!doc || typeof doc.querySelector !== 'function') return null;
+ var toolbar = doc.querySelector('div.cr-input-toolbar__right');
+ return isVisible(toolbar) ? { kind: 'modern', element: toolbar } : null;
+ }
+
+ function findLegacyToolbar(doc) {
+ if (!doc || typeof doc.querySelectorAll !== 'function') return null;
+ var candidates = doc.querySelectorAll(
+ '[class*="_inputBottom_"] > [class*="_gapLarge_"],' +
+ '[class*="_inputBottom_"] > [class*="_gap_"]:not([class*="_selector_"]),' +
+ '[class*="_inputBottom_"] > [class*="_item_"]:not([class*="_selector_"])'
+ );
+ var best = null;
+ var bestLeft = -Infinity;
+ for (var i = 0; i < candidates.length; i++) {
+ if (!isVisible(candidates[i])) continue;
+ var left = candidates[i].getBoundingClientRect().left;
+ if (left > bestLeft) {
+ best = candidates[i];
+ bestLeft = left;
+ }
+ }
+ return best ? { kind: 'legacy', element: best } : null;
+ }
+
+ function findComposerToolbar(doc) {
+ return findModernToolbar(doc) || findLegacyToolbar(doc);
+ }
+
+ function findMessageNavigationSurface(doc) {
+ if (!doc || typeof doc.querySelector !== 'function') return null;
+ try {
+ var scrollElement = doc.querySelector('.cr-message-list');
+ var viewportElement = doc.querySelector('.cr-message-list-viewport');
+ var contentElement = doc.querySelector('.cr-message-list__content');
+ var conversationElement = doc.querySelector('.cr-document[data-root-id]');
+ if (!scrollElement || !viewportElement || !contentElement || !conversationElement) return null;
+ return {
+ scrollElement: scrollElement,
+ viewportElement: viewportElement,
+ contentElement: contentElement,
+ conversationElement: conversationElement,
+ };
+ } catch (_) {
+ return null;
+ }
+ }
+
+ function collectMessageNavigationTurnsFromMessages(messages) {
+ var list = Array.isArray(messages) ? messages : [];
+ var turns = [];
+ var current = null;
+ var seenIds = Object.create(null);
+ for (var i = 0; i < list.length; i++) {
+ var message = list[i];
+ if (!message || typeof message !== 'object') continue;
+ if (message.messageType === 'user') {
+ // 过滤发送中的临时消息:只有 requestId(req-* 前缀)而无真实服务端 id 的 user 消息,
+ // 在 DOM/消息流里没有可定位的帧(5.4.4 发送中 pending 消息不落虚拟列表),跳过不建 turn。
+ var realId = message.id ? String(message.id) : '';
+ var reqId = message.requestId ? String(message.requestId) : '';
+ if (!realId && /^req-/.test(reqId)) continue;
+ var messageId = realId || reqId || ('message-' + i);
+ var baseId = messageId;
+ var id = baseId;
+ var duplicate = 2;
+ while (seenIds[id]) id = baseId + '-' + duplicate++;
+ seenIds[id] = true;
+ current = {
+ id: id,
+ // messageId 保持原始 id 用于滚动定位(supports scrollToMessage(id));
+ // turn.id 若被去重加后缀(同 id 多轮),滚动仍用原始 messageId。
+ messageId: messageId,
+ messageIndex: i,
+ userMessage: message,
+ assistantMessage: null,
+ };
+ turns.push(current);
+ continue;
+ }
+ if (message.messageType === 'assistant' && current) current.assistantMessage = message;
+ }
+ return turns;
+ }
+
+ function selectedConversationId(candidates) {
+ var list = Array.isArray(candidates) ? candidates : [];
+ for (var i = 0; i < list.length; i++) {
+ var item = list[i] || {};
+ var classes = String(item.className || '') + ' ' + String(item.childClassName || '');
+ if (item.ariaSelected === true || item.ariaSelected === 'true' ||
+ /(^|\s)active(\s|$)/.test(classes) || /_selected_/.test(classes)) {
+ var id = String(item.conversationId || '').trim();
+ if (id) return id;
+ }
+ }
+ return null;
+ }
+
+ function getModernSelectedConversationId(doc) {
+ if (!doc || typeof doc.querySelectorAll !== 'function') return null;
+ try {
+ var nodes = doc.querySelectorAll('.conversation-item[data-conversation-id]');
+ var candidates = [];
+ for (var i = 0; i < nodes.length; i++) {
+ var child = nodes[i].firstElementChild;
+ candidates.push({
+ conversationId: nodes[i].getAttribute('data-conversation-id'),
+ ariaSelected: nodes[i].getAttribute('aria-selected') || (child && child.getAttribute && child.getAttribute('aria-selected')),
+ className: nodes[i].className,
+ childClassName: child && child.className,
+ });
+ }
+ var selected = selectedConversationId(candidates);
+ if (selected) return selected;
+ if (typeof doc.querySelector === 'function') {
+ var current = doc.querySelector('.cr-document[data-root-id]');
+ if (current) return current.getAttribute('data-root-id') || null;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ function getLegacySelectedConversationId(doc) {
+ if (!doc || typeof doc.querySelector !== 'function') return null;
+ try {
+ var selected = doc.querySelector(
+ '[data-conversation-id].active,' +
+ '[data-conversation-id][aria-selected="true"],' +
+ '.conversation-item.active,' +
+ '[data-conversation-id][class*="active"],' +
+ '.conv-item.active,' +
+ '[class*="conversation"][class*="active"]'
+ );
+ return selected && (selected.getAttribute('data-conversation-id') || selected.getAttribute('data-id')) || null;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ function getSelectedConversationId(doc) {
+ return getModernSelectedConversationId(doc) || getLegacySelectedConversationId(doc);
+ }
+
+ function reactFiber(element) {
+ if (!element) return null;
+ for (var key in element) {
+ if (key.indexOf('__reactFiber$') === 0 || key.indexOf('__reactInternalInstance') === 0) return element[key];
+ }
+ return null;
+ }
+
+ function isConversationController(value) {
+ return !!value && typeof value === 'object' && value.conversationId &&
+ value.messageStore && typeof value.messageStore.getState === 'function' &&
+ typeof value.messageStore.subscribe === 'function' &&
+ typeof value.getMessagesViewState === 'function';
+ }
+
+ function isMessageNavigationHandle(value) {
+ return !!value && typeof value === 'object' &&
+ typeof value.scrollToMessage === 'function' &&
+ typeof value.getScrollMetrics === 'function';
+ }
+
+ function controllerFromFiber(element, conversationId) {
+ var fiber = reactFiber(element);
+ var seen = 0;
+ while (fiber && seen++ < 700) {
+ var props = fiber.memoizedProps;
+ var candidates = props && [props.value, props.controller, props.adapter];
+ for (var i = 0; candidates && i < candidates.length; i++) {
+ var candidate = candidates[i];
+ if (!isConversationController(candidate)) continue;
+ if (!conversationId || String(candidate.conversationId) === String(conversationId)) return candidate;
+ }
+ fiber = fiber.return;
+ }
+ return null;
+ }
+
+ function navigationHandleFromFiber(element) {
+ var fiber = reactFiber(element);
+ var seen = 0;
+ while (fiber && seen++ < 700) {
+ var props = fiber.memoizedProps;
+ var value = props && props.value;
+ var candidates = props && [props.handle, value && value.handle, value];
+ for (var i = 0; candidates && i < candidates.length; i++) {
+ if (isMessageNavigationHandle(candidates[i])) return candidates[i];
+ }
+ fiber = fiber.return;
+ }
+ return null;
+ }
+
+ function findMessageNavigationAdapter(doc, surface) {
+ if (!doc || typeof doc.querySelector !== 'function') return null;
+ var currentSurface = surface || findMessageNavigationSurface(doc);
+ if (!currentSurface) return null;
+ try {
+ var conversationId = currentSurface.conversationElement.getAttribute &&
+ currentSurface.conversationElement.getAttribute('data-root-id');
+ var controllerRoots = [
+ currentSurface.conversationElement,
+ currentSurface.scrollElement,
+ doc.querySelector('.conversation-shell'),
+ doc.querySelector('#root > div'),
+ ];
+ var controller = null;
+ for (var i = 0; i < controllerRoots.length && !controller; i++) {
+ if (controllerRoots[i]) controller = controllerFromFiber(controllerRoots[i], conversationId);
+ }
+ var navigationHandle = navigationHandleFromFiber(currentSurface.scrollElement) ||
+ navigationHandleFromFiber(currentSurface.viewportElement) ||
+ navigationHandleFromFiber(currentSurface.contentElement);
+ if (!controller || !navigationHandle) return null;
+ return {
+ controller: controller,
+ messageStore: controller.messageStore,
+ navigationHandle: navigationHandle,
+ };
+ } catch (_) {
+ return null;
+ }
+ }
+
+ function findModernQueueAdapter(doc) {
+ if (!doc || typeof doc.querySelector !== 'function') return null;
+ try {
+ var root = doc.querySelector('#root > div') || doc.querySelector('#root');
+ if (!root) return null;
+ var stack = [root];
+ var visitedElements = 0;
+ while (stack.length && visitedElements++ < 300) {
+ var element = stack.pop();
+ var fiber = reactFiber(element);
+ var seen = 0;
+ while (fiber && seen++ < 400) {
+ var props = fiber.memoizedProps;
+ if (props && hasQueueMethods(props.adapter)) return { kind: 'modern', adapter: props.adapter };
+ fiber = fiber.return;
+ }
+ var children = element && element.children || [];
+ for (var i = 0; i < children.length; i++) stack.push(children[i]);
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ function findLegacyQueueAdapter(doc) {
+ if (!doc || typeof doc.querySelector !== 'function') return null;
+ var roots = [
+ doc.querySelector('.voice-mic-wrap'),
+ doc.querySelector('[class*="_cbChat_"]'),
+ doc.querySelector('.chat-container'),
+ ];
+ for (var ri = 0; ri < roots.length; ri++) {
+ var node = roots[ri];
+ for (var up = 0; up < 30 && node; up++) {
+ var fiber = reactFiber(node);
+ var seen = 0;
+ while (fiber && seen++ < 150) {
+ var props = fiber.memoizedProps;
+ if (props && typeof props === 'object') {
+ for (var key in props) {
+ var value;
+ try { value = props[key]; } catch (_) { continue; }
+ if (hasQueueMethods(value)) return { kind: 'legacy', adapter: value };
+ }
+ }
+ fiber = fiber.return;
+ }
+ node = node.parentElement;
+ }
+ }
+ return null;
+ }
+
+ function findQueueAdapter(doc) {
+ return findModernQueueAdapter(doc) || findLegacyQueueAdapter(doc);
+ }
+
+ function hasModernQueueSurface(doc) {
+ if (!doc || typeof doc.querySelector !== 'function') return false;
+ return !!findModernQueueAdapter(doc) || !!doc.querySelector(
+ '.cr-input-toolbar__right,.cr-document[data-root-id],.conversation-shell'
+ );
+ }
+
+ function markQueueAdapter(adapter, kind) {
+ if (!adapter || typeof adapter !== 'object') return adapter;
+ try {
+ Object.defineProperty(adapter, '__wbsCompatKind', {
+ value: kind,
+ configurable: true,
+ enumerable: false,
+ });
+ } catch (_) {
+ adapter.__wbsCompatKind = kind;
+ }
+ return adapter;
+ }
+
+ function isModernQueueAdapter(adapter) {
+ return !!adapter && adapter.__wbsCompatKind === 'modern';
+ }
+
+ function draftStorageKey(sessionId) {
+ var id = String(sessionId || '').trim();
+ return id ? 'cb-draft:' + id : null;
+ }
+
+ function isComposerStore(store, sessionId) {
+ try {
+ if (!store || typeof store !== 'object' || !store.api ||
+ typeof store.api.clear !== 'function' || typeof store.api.setBlocks !== 'function' ||
+ typeof store.api.getDraft !== 'function' || typeof store.getSnapshot !== 'function') return false;
+ var snapshot = store.getSnapshot();
+ return !!snapshot && String(snapshot.activeSessionId || '') === String(sessionId || '');
+ } catch (_) {
+ return false;
+ }
+ }
+
+ return {
+ draftStorageKey: draftStorageKey,
+ collectMessageNavigationTurnsFromMessages: collectMessageNavigationTurnsFromMessages,
+ findComposerToolbar: findComposerToolbar,
+ findLegacyQueueAdapter: findLegacyQueueAdapter,
+ findModernQueueAdapter: findModernQueueAdapter,
+ findQueueAdapter: findQueueAdapter,
+ findMessageNavigationAdapter: findMessageNavigationAdapter,
+ findMessageNavigationSurface: findMessageNavigationSurface,
+ getSelectedConversationId: getSelectedConversationId,
+ hasModernQueueSurface: hasModernQueueSurface,
+ isComposerStore: isComposerStore,
+ isModernQueueAdapter: isModernQueueAdapter,
+ markQueueAdapter: markQueueAdapter,
+ selectedConversationId: selectedConversationId,
+ };
+});
diff --git a/scripts/workbuddy-target.js b/scripts/workbuddy-target.js
new file mode 100644
index 0000000..75ca23a
--- /dev/null
+++ b/scripts/workbuddy-target.js
@@ -0,0 +1,53 @@
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+
+function clean(value) {
+ return typeof value === 'string' ? value.trim() : '';
+}
+
+function emptyTarget(configured = false, source = 'default') {
+ return { configured, binary: '', version: '', source };
+}
+
+function readWorkBuddyTarget({ dataDir, profileId, env = process.env } = {}) {
+ const envBinary = clean(env.WBSWITCH_WORKBUDDY_BIN);
+ const envVersion = clean(env.WBSWITCH_WORKBUDDY_VERSION);
+ if (envBinary) {
+ return { configured: true, binary: envBinary, version: envVersion, source: 'environment' };
+ }
+
+ if (!dataDir) return emptyTarget();
+ const targetFile = path.join(dataDir, 'workbuddy-target.json');
+ let raw;
+ try {
+ raw = fs.readFileSync(targetFile, 'utf8');
+ } catch (error) {
+ if (error && error.code === 'ENOENT') return emptyTarget();
+ return emptyTarget(true, 'file');
+ }
+
+ let target;
+ try {
+ target = JSON.parse(raw);
+ } catch (_) {
+ return emptyTarget(true, 'file');
+ }
+ if (!target || typeof target !== 'object' || Array.isArray(target)) {
+ return emptyTarget(true, 'file');
+ }
+
+ const configuredProfile = clean(target.profileId || target.profile);
+ if (configuredProfile && profileId && configuredProfile !== clean(profileId)) {
+ return emptyTarget(true, 'file');
+ }
+ return {
+ configured: true,
+ binary: clean(target.binary || target.executable || target.path),
+ version: envVersion || clean(target.version),
+ source: 'file',
+ };
+}
+
+module.exports = { readWorkBuddyTarget };
diff --git a/test/builtin-wallpaper.test.js b/test/builtin-wallpaper.test.js
new file mode 100644
index 0000000..90ac499
--- /dev/null
+++ b/test/builtin-wallpaper.test.js
@@ -0,0 +1,40 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+
+const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+const macBuild = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'build-mac-dmg.sh'), 'utf8');
+const winBuild = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'build-win-zip.sh'), 'utf8');
+const wallpaperOverride = path.join(__dirname, '..', 'scripts', 'builtin-overrides', 'wallpaper-06.webp');
+
+test('built-in official wallpapers refresh stale managed copies', () => {
+ const start = daemon.indexOf('function initBuiltinAssets()');
+ const end = daemon.indexOf('\n/** 内置主题', start);
+ const source = daemon.slice(start, end);
+
+ assert.match(source, /Buffer\.compare\(/);
+ assert.match(source, /fs\.copyFileSync\(source, dest\)/);
+ assert.match(daemon, /function builtinWallpaperSource\(/);
+ assert.ok(fs.existsSync(wallpaperOverride));
+ assert.equal(fs.readFileSync(wallpaperOverride, null).subarray(0, 4).toString('ascii'), 'RIFF');
+});
+
+test('a fresh profile starts with the WorkDaddy wallpaper theme', () => {
+ const start = daemon.indexOf('function initBuiltinAssets()');
+ const end = daemon.indexOf('\n/** 内置主题', start);
+ const source = daemon.slice(start, end);
+
+ assert.match(source, /JSON\.stringify\(\{ id: 'nebula'/);
+ assert.doesNotMatch(source, /JSON\.stringify\(\{ id: 'default'/);
+});
+
+test('release builders stage the tracked wallpaper override as wallpaper 6 and the default background', () => {
+ for (const source of [macBuild, winBuild]) {
+ assert.match(source, /builtin-overrides\/wallpaper-06\.webp/);
+ assert.match(source, /builtin\/wallpapers\/wallpaper-06\.webp/);
+ assert.match(source, /builtin\/nebula\/background\.webp/);
+ }
+});
diff --git a/test/element-inspector.test.js b/test/element-inspector.test.js
new file mode 100644
index 0000000..9d0158a
--- /dev/null
+++ b/test/element-inspector.test.js
@@ -0,0 +1,104 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const injectSource = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+// 拾取实现随内部模块抽离(picker-internal.js 不入库);文件存在才测试,缺失则整文件跳过
+const pickerPath = path.join(__dirname, '../scripts/picker-internal.js');
+const pickerSource = fs.existsSync(pickerPath) ? fs.readFileSync(pickerPath, 'utf8') : null;
+const daemonSource = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+const macBuildSource = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+if (!pickerSource) {
+ test('picker-internal.js 未就绪(内部模块不入库)', (t) => t.skip());
+} else {
+ test('拾取点击直接打开插件内 DOM 检查器', () => {
+ const handler = functionSource('showInspector', 'stopInspect');
+ const handler = functionSource('onInspectClick', 'onInspectKey');
+ assert.match(handler, /showInspector\(stack, el\)/);
+ assert.doesNotMatch(handler, /window\.open|api\(|element-inspector-url|open-url/);
+});
+
+test('插件内检查器包含 DOM 树、重叠元素栈、节点详情和 HTML', () => {
+ const handler = functionSource('showInspector', 'stopInspect');
+ assert.match(handler, /wbs-inspector-tree/);
+ assert.match(handler, /wbs-inspector-stack/);
+ assert.match(handler, /wbs-inspector-detail/);
+ assert.match(handler, /wbs-inspector-html/);
+ assert.match(handler, /mouseover/);
+ assert.match(injectSource, /document\.elementsFromPoint/);
+});
+
+test('再次拾取时保留检查器和 WorkDaddy 面板并原地刷新节点', () => {
+ const handler = functionSource('onInspectClick', 'onInspectKey');
+ assert.doesNotMatch(handler, /setOpen\(false\)|stopInspect\(\)/);
+ assert.match(handler, /inspector\.__wbsInspectAt\(stack, el\)/);
+ assert.match(handler, /showInspector\(stack, el\)/);
+ const startHandler = functionSource('startInspect', 'toggleInspect');
+ assert.doesNotMatch(startHandler, /root\.style\.display\s*=\s*'none'/);
+ const inspector = functionSource('showInspector', 'stopInspect');
+ assert.match(inspector, /mask\.__wbsInspectAt = inspectAt/);
+ assert.doesNotMatch(inspector, /wbs-ins-repick[^\n]+closeInspector\(\)/);
+});
+
+test('检查器默认严格保持 80% 高 60% 并允许手动缩放', () => {
+ assert.match(injectSource, /\.wbs-modal\.wbs-inspector-modal\{[^}]*width:80vw;height:60vh/);
+ assert.match(injectSource, /resize:both/);
+ assert.match(injectSource, /overflow:hidden/);
+ assert.doesNotMatch(injectSource, /@media\(max-width:900px\)\{\.wbs-inspector-modal/);
+ assert.doesNotMatch(injectSource, /@media\(max-width:600px\)\{\.wbs-inspector-modal/);
+});
+
+test('检查器浮窗外不遮罩不模糊并允许页面接收指针', () => {
+ assert.match(injectSource, /\.wbs-inspector-mask\{[^}]*background:transparent[^}]*pointer-events:none/);
+ assert.match(injectSource, /\.wbs-inspector-modal\{[^}]*pointer-events:auto/);
+ assert.doesNotMatch(injectSource, /\.wbs-inspector-mask\{[^}]*backdrop-filter/);
+});
+
+test('节点详情眼睛按钮切换 opacity 0 并精确恢复原内联值', () => {
+ const inspector = functionSource('showInspector', 'stopInspect');
+ assert.match(inspector, /wbs-ins-visibility/);
+ assert.match(injectSource, /opacityStates = new WeakMap\(\)/);
+ assert.match(inspector, /style\.setProperty\('opacity', '0', 'important'\)/);
+ assert.match(inspector, /style\.setProperty\('opacity', state\.value, state\.priority\)/);
+ assert.match(inspector, /style\.removeProperty\('opacity'\)/);
+ assert.match(inspector, /state = \{ hadValue: value !== '', value: value, priority:/);
+ assert.doesNotMatch(inspector, /if \(!state\) \{\s*var value = selected\.style\.getPropertyValue\('opacity'\)/);
+});
+
+test('重注入通过检查器关闭入口清理监听器且拾取高亮恢复原样', () => {
+ assert.match(injectSource, /if \(inspector && inspector\.__wbsClose\) inspector\.__wbsClose\(\)/);
+ const stopHandler = functionSource('stopInspect', 'onInspectMove');
+ assert.match(stopHandler, /style\.setProperty\('outline', inspectState\.hoverOutline\.value, inspectState\.hoverOutline\.priority\)/);
+ assert.match(stopHandler, /style\.setProperty\('outline-offset', inspectState\.hoverOutlineOffset\.value, inspectState\.hoverOutlineOffset\.priority\)/);
+});
+
+test('检查器内部使用容器查询跟随自身尺寸响应式', () => {
+ assert.match(injectSource, /container-type:inline-size/);
+ assert.match(injectSource, /@container inspector \(max-width:760px\)/);
+ assert.match(injectSource, /grid-template-columns:1fr/);
+});
+
+test('检查器标题栏可拖拽且具有明确关闭按钮', () => {
+ const handler = functionSource('showInspector', 'stopInspect');
+ assert.match(handler, /wbs-inspector-drag-handle/);
+ assert.match(handler, />关闭<\/button>/);
+ assert.match(handler, /pointerdown/);
+ assert.match(handler, /pointermove/);
+ assert.match(handler, /pointerup/);
+ assert.match(handler, /setPointerCapture/);
+});
+
+test('daemon 不再暴露 localhost 元素检查器页面与 bridge', () => {
+ assert.doesNotMatch(daemonSource, /element-inspector-url|element-inspector-command|element-inspector\.html|INSPECTOR_TICKETS|createInspectorTicketStore/);
+});
+
+test('macOS 打包不再携带外部元素检查器文件', () => {
+ assert.doesNotMatch(macBuildSource, /element-inspector\.js|element-inspector\.html/);
+});
diff --git a/test/message-navigation.test.js b/test/message-navigation.test.js
new file mode 100644
index 0000000..97a06e9
--- /dev/null
+++ b/test/message-navigation.test.js
@@ -0,0 +1,160 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+
+const compat = require('../scripts/workbuddy-compat.js');
+
+test('modern conversation surface is discovered without treating mounted virtual items as the message source', () => {
+ const conversationElement = { name: 'conversation' };
+ const scrollElement = { name: 'scroll' };
+ const viewportElement = { name: 'viewport' };
+ const contentElement = { name: 'content' };
+ const documentLike = {
+ querySelector(selector) {
+ if (selector === '.cr-message-list') return scrollElement;
+ if (selector === '.cr-message-list-viewport') return viewportElement;
+ if (selector === '.cr-message-list__content') return contentElement;
+ if (selector === '.cr-document[data-root-id]') return conversationElement;
+ return null;
+ },
+ };
+
+ const surface = compat.findMessageNavigationSurface(documentLike);
+ assert.deepEqual(surface, { scrollElement, viewportElement, contentElement, conversationElement });
+});
+
+test('all navigation turns are built from the structured message store regardless of DOM virtualization', () => {
+ const initialAssistant = { id: 'timeline:initial', messageType: 'assistant', content: [] };
+ const userOne = { id: 'user-1', requestId: 'request-1', messageType: 'user', content: [{ type: 'text', text: 'one' }] };
+ const assistantOne = { id: 'assistant-1', requestId: 'request-1', messageType: 'assistant', content: [{ type: 'text', text: 'answer one' }] };
+ const userTwo = { id: 'user-2', requestId: 'request-2', messageType: 'user', content: [{ type: 'text', text: 'two' }] };
+ const assistantTwo = { id: 'assistant-2', requestId: 'request-2', messageType: 'assistant', content: [{ type: 'text', text: 'answer two' }] };
+ const turns = compat.collectMessageNavigationTurnsFromMessages([
+ initialAssistant,
+ userOne,
+ assistantOne,
+ userTwo,
+ assistantTwo,
+ ]);
+
+ assert.equal(turns.length, 2);
+ assert.deepEqual(turns.map((turn) => turn.id), ['user-1', 'user-2']);
+ assert.equal(turns[0].messageIndex, 1);
+ assert.equal(turns[0].userMessage, userOne);
+ assert.equal(turns[0].assistantMessage, assistantOne);
+ assert.equal(turns[1].assistantMessage, assistantTwo);
+});
+
+test('pending in-flight user messages (req-* requestId only) are skipped from navigation turns', () => {
+ const realUser = { id: 'real-1', messageType: 'user', content: [] };
+ const pendingUser = { requestId: 'req-1788055901657776', messageType: 'user', content: [] };
+ const realUser2 = { id: 'real-2', messageType: 'user', content: [] };
+ const turns = compat.collectMessageNavigationTurnsFromMessages([realUser, pendingUser, realUser2]);
+ assert.equal(turns.length, 2);
+ assert.deepEqual(turns.map((turn) => turn.id), ['real-1', 'real-2']);
+ // 有真实 id 时 messageId 用真实 id(滚动定位 DOM 帧用),而非 requestId
+ assert.equal(turns[0].messageId, 'real-1');
+});
+
+test('message navigation adapter discovers the complete store and official virtual-list handle by capability', () => {
+ const messageStore = { getState() {}, subscribe() {} };
+ const controller = {
+ conversationId: 'conversation-1',
+ messageStore,
+ getMessagesViewState() {},
+ };
+ const navigationHandle = {
+ scrollToMessage() {},
+ getScrollMetrics() {},
+ };
+ const controllerFiber = { memoizedProps: { value: controller }, return: null };
+ const handleFiber = { memoizedProps: { value: { handle: navigationHandle } }, return: controllerFiber };
+ const conversationElement = {
+ __reactFiber$test: controllerFiber,
+ getAttribute(name) { return name === 'data-root-id' ? 'conversation-1' : null; },
+ };
+ const scrollElement = { __reactFiber$test: handleFiber };
+ const viewportElement = { __reactFiber$test: handleFiber };
+ const contentElement = {};
+ const documentLike = {
+ querySelector(selector) {
+ if (selector === '.cr-message-list') return scrollElement;
+ if (selector === '.cr-message-list-viewport') return viewportElement;
+ if (selector === '.cr-message-list__content') return contentElement;
+ if (selector === '.cr-document[data-root-id]') return conversationElement;
+ return null;
+ },
+ };
+
+ const adapter = compat.findMessageNavigationAdapter(documentLike);
+ assert.equal(adapter.controller, controller);
+ assert.equal(adapter.messageStore, messageStore);
+ assert.equal(adapter.navigationHandle, navigationHandle);
+});
+
+test('injected navigation rail is theme-aware, glassy, accessible, and profile agnostic', () => {
+ const root = path.join(__dirname, '..');
+ const inject = fs.readFileSync(path.join(root, 'scripts', 'inject.js'), 'utf8');
+
+ assert.match(inject, /function createMessageNavigation\(/);
+ assert.match(inject, /WBS_COMPAT\.findMessageNavigationSurface\(document\)/);
+ assert.match(inject, /WBS_COMPAT\.findMessageNavigationAdapter\(document/);
+ assert.match(inject, /WBS_COMPAT\.collectMessageNavigationTurnsFromMessages\(messageState\.messages\)/);
+ assert.match(inject, /messageStore\.subscribe\(/);
+ assert.match(inject, /turns\.length <= 1/);
+ assert.match(inject, /className = 'wbs-message-nav-root'/);
+ assert.match(inject, /className = 'wbs-message-nav-tooltip'/);
+ assert.match(inject, /aria-label/);
+ assert.match(inject, /aria-current/);
+ assert.match(inject, /\.wbs-message-nav-tooltip\{[^\n]*backdrop-filter:blur\(/);
+ assert.match(inject, /var\(--wb-bg-popover/);
+ assert.match(inject, /var\(--wb-border-subtle/);
+ assert.match(inject, /var\(--wb-color-text-primary/);
+ assert.match(inject, /\.wbs-message-nav-rail\{[^\n]*border:1px solid transparent[^\n]*box-shadow:none[^\n]*backdrop-filter:none/);
+ assert.match(inject, /\.wbs-message-nav-rail:hover,\.wbs-message-nav-rail:focus-within\{[^\n]*backdrop-filter:blur\(/);
+ assert.match(inject, /\.wbs-message-nav-marker\{[^\n]*background:color-mix\(in srgb,var\(--wb-bg-popover/);
+ assert.match(inject, /\.wbs-message-nav-marker:hover,\.wbs-message-nav-marker:focus-visible\{[^\n]*border-color:[^\n]*box-shadow:[^\n]*backdrop-filter:blur\(/);
+ assert.match(inject, /prefers-reduced-motion:reduce/);
+ assert.match(inject, /querySelectorAll\('\.wbs-message-nav-root'\)/);
+
+ const navigationStart = inject.indexOf('function createMessageNavigation(');
+ const navigationEnd = inject.indexOf('\n // =====', navigationStart);
+ const navigationSource = inject.slice(navigationStart, navigationEnd);
+ assert.doesNotMatch(navigationSource, /WBS_PROFILE_IS_AI|PROFILE_ID/);
+ assert.doesNotMatch(navigationSource, /scrollIntoView/);
+ assert.match(navigationSource, /scrollToMessage\(turn\.messageId, \{ behavior: 'auto'/);
+ assert.match(navigationSource, /surface\.scrollElement\.getBoundingClientRect\(\)/);
+ assert.match(navigationSource, /rect\.left \+ 12/);
+ assert.doesNotMatch(navigationSource, /rect\.height \* 0\.7|420/);
+ assert.match(navigationSource, /Math\.min\(desiredRailHeight, rect\.height\)/);
+ assert.match(navigationSource, /--wbs-message-nav-marker-height/);
+ assert.match(navigationSource, /setPointerCapture\(event\.pointerId\)/);
+ assert.match(navigationSource, /function onNavPointerMove\(/);
+ assert.match(navigationSource, /navigateToTurn\(turns\[nextIndex\], true\)/);
+ assert.match(inject, /\.wbs-message-nav-rail\{[^\n]*touch-action:none/);
+ assert.match(inject, /\.wbs-message-nav-marker\{[^\n]*height:var\(--wbs-message-nav-marker-height/);
+ assert.doesNotMatch(navigationSource, /button\.focus\(/);
+ assert.doesNotMatch(inject, /\.wbs-message-nav-root\.is-dragging[^\n]*cursor:/);
+ assert.match(inject, /\.wbs-message-nav-marker:focus-visible/);
+ assert.match(inject, /workdaddy\.session\.messageNavigationEnabled/);
+ assert.match(inject, /localStorage\.getItem\(MESSAGE_NAV_ENABLED_KEY\) !== '0'/);
+ assert.match(navigationSource, /function setEnabled\(enabled\)/);
+ assert.match(inject, /messageNavigation\.setEnabled\(sessState\.messageNav\)/);
+
+ const stashSwitch = inject.indexOf('id="wbs-sess-stash"');
+ const navigationSwitch = inject.indexOf('id="wbs-sess-message-nav"');
+ const phraseSwitch = inject.indexOf('id="wbs-sess-phrase"');
+ assert.ok(stashSwitch >= 0 && navigationSwitch > stashSwitch && phraseSwitch > navigationSwitch);
+ assert.match(inject, /会话消息索引/);
+ assert.match(inject, /悬停预览,点击或拖动快速定位消息。/);
+});
+
+test('robot pupils use the antenna glass treatment instead of opaque black', () => {
+ const root = path.join(__dirname, '..');
+ const inject = fs.readFileSync(path.join(root, 'scripts', 'inject.js'), 'utf8');
+ assert.match(inject, /\.wbs-fab \.eye:before\{[^\n]*background:rgba\(20,20,22,\.55\)[^\n]*backdrop-filter:blur\(14px\) saturate\(1\.3\)/);
+ assert.doesNotMatch(inject, /\.wbs-fab \.eye:before\{[^\n]*background:rgba\(20,20,22,\.92\)/);
+});
diff --git a/test/renderer-escaping.test.js b/test/renderer-escaping.test.js
index 4f4b626..a7ec24a 100644
--- a/test/renderer-escaping.test.js
+++ b/test/renderer-escaping.test.js
@@ -6,12 +6,16 @@ const path = require('node:path');
const test = require('node:test');
const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+// 内部调试模块(git 不跟踪):存在才测试,缺失(他人环境)则跳过
+const pickerPath = path.join(__dirname, '..', 'scripts', 'picker-internal.js');
+const picker = fs.existsSync(pickerPath) ? fs.readFileSync(pickerPath, 'utf8') : null;
-function sourceBetween(start, end) {
- const startIndex = source.indexOf(start);
- const endIndex = source.indexOf(end, startIndex + start.length);
+function sourceBetween(start, end, src) {
+ src = src || source;
+ const startIndex = src.indexOf(start);
+ const endIndex = src.indexOf(end, startIndex + start.length);
assert.ok(startIndex >= 0 && endIndex > startIndex, `missing source block ${start}`);
- return source.slice(startIndex, endIndex);
+ return src.slice(startIndex, endIndex);
}
test('HTML and attribute escaping cover markup and quoted attributes', () => {
@@ -67,12 +71,14 @@ test('model, wallpaper, and account cards escape each dynamic HTML sink', () =>
assert.doesNotMatch(models, /data-model-(?:backup|test|delete-official)="' \+ model\.index/);
assert.doesNotMatch(models, /data-model-(?:copy|edit|enable)="' \+ model\.backupId/);
- const wallpapers = sourceBetween('function loadWallpapers()', 'function setOpen(open)');
+ const wallpapers = sourceBetween('function loadWallpapers(force)', 'function setOpen(open)');
assert.match(wallpapers, /data-wp="' \+ escAttr\(w\.name\)/);
assert.match(wallpapers, /title="' \+ escAttr\(w\.title\)/);
assert.match(wallpapers, /data-src="' \+ escAttr\(wallpaperUrl\)/);
assert.match(wallpapers, /alt="' \+ escAttr\(w\.title\)/);
assert.match(wallpapers, /wbs-wp-badge">' \+ esc\(/);
+ assert.match(wallpapers, /data-del="' \+ escAttr\(w\.name\)/);
+ assert.match(wallpapers, /btn\.getAttribute\('data-del'\)/);
assert.doesNotMatch(wallpapers, /(?:data-wp|title|data-src|alt)="' \+ (?:w\.|wallpaperUrl)/);
const accounts = sourceBetween('function render(data)', 'function updateAccountSummary()');
@@ -94,16 +100,16 @@ test('dynamic error and check-in messages are escaped before HTML insertion', ()
assert.doesNotMatch(source, /innerHTML\s*=\s*'[^\n]*'\s*\+\s*\(e\.message \|\| e\)/);
});
-test('inspector escapes page-controlled selectors and computed style values', () => {
- const inspector = sourceBetween('function showInspector(el)', 'function stopInspect()');
- assert.match(inspector, /esc\(buildSelector\(el\)\)/);
+test('inspector escapes page-controlled labels, attributes, paths and computed style values', (t) => {
+ if (!picker) return t.skip('picker-internal.js 未就绪(内部模块不入库)');
+ const inspector = sourceBetween('function showInspector(stack, fallbackEl)', 'function stopInspect()', picker);
+ assert.match(inspector, /esc\(nodeLabel\(node\)\)/);
assert.match(inspector, /esc\(queryPath\)/);
- assert.match(inspector, /esc\(items\[i\]\[1\] \|\| '—'\)/);
- assert.match(inspector, /esc\(v \|\| '未定义(继承上层)'\)/);
- assert.match(inspector, /rules\.map\(function \(x\) \{ return '[^\n]+' \+ esc\(x\)/);
- assert.doesNotMatch(inspector, /\+ buildSelector\(el\) \+/);
+ assert.match(inspector, /esc\(attr\.name\)/);
+ assert.match(inspector, /esc\(attr\.value\)/);
+ assert.match(inspector, /esc\(value \|\| '未定义'\)/);
+ assert.match(inspector, /textContent = selected\.outerHTML/);
+ assert.doesNotMatch(inspector, /\+ nodeLabel\(node\) \+/);
assert.doesNotMatch(inspector, /\+ queryPath \+/);
- assert.doesNotMatch(inspector, /<code>' \+ \(items\[i\]\[1\]/);
- assert.doesNotMatch(inspector, /<code>' \+ \(v \|\|/);
- assert.doesNotMatch(inspector, /wbs-ins-rule">' \+ x \+/);
+ assert.doesNotMatch(inspector, /innerHTML = selected\.outerHTML/);
});
diff --git a/test/runtime-dependencies.test.js b/test/runtime-dependencies.test.js
new file mode 100644
index 0000000..c683978
--- /dev/null
+++ b/test/runtime-dependencies.test.js
@@ -0,0 +1,96 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+
+const root = path.join(__dirname, '..');
+const scriptsDir = path.join(root, 'scripts');
+
+test('runtime entry points have every relative CommonJS dependency', () => {
+ const pending = ['daemon.js', 'win-launcher.js', 'watchdog.js'];
+ const visited = new Set();
+ const optional = new Set(['package.json', 'plist-reader.js']);
+ while (pending.length) {
+ const relativeFile = pending.pop();
+ if (visited.has(relativeFile)) continue;
+ visited.add(relativeFile);
+ const source = fs.readFileSync(path.join(scriptsDir, relativeFile), 'utf8');
+ for (const match of source.matchAll(/require\(['"](\.\/[^'"]+)['"]\)/g)) {
+ const dependency = path.normalize(path.join(path.dirname(relativeFile), match[1]));
+ const dependencyFile = path.extname(dependency) ? dependency : dependency + '.js';
+ if (optional.has(dependencyFile)) continue;
+ assert.equal(fs.existsSync(path.join(scriptsDir, dependencyFile)), true,
+ `${relativeFile} requires missing ${dependencyFile}`);
+ if (dependencyFile.endsWith('.js')) pending.push(dependencyFile);
+ }
+ }
+});
+
+test('macOS release stages every daemon startup dependency', () => {
+ const daemonSource = fs.readFileSync(path.join(scriptsDir, 'daemon.js'), 'utf8');
+ const buildSource = fs.readFileSync(path.join(scriptsDir, 'build-mac-dmg.sh'), 'utf8');
+ const manifest = buildSource.match(/for f in ([^;\n]+); do/);
+ assert.ok(manifest, 'macOS build script must expose its staged script manifest');
+ const stagedFiles = new Set(manifest[1].trim().split(/\s+/));
+ const startupEnd = daemonSource.indexOf('const PROFILE = getProfile();');
+ assert.ok(startupEnd > 0, 'daemon startup import boundary is missing');
+
+ const pending = [{ file: 'daemon.js', source: daemonSource.slice(0, startupEnd) }];
+ const visited = new Set();
+ const optional = new Set(['package.json', 'plist-reader.js']);
+ while (pending.length) {
+ const current = pending.pop();
+ if (visited.has(current.file)) continue;
+ visited.add(current.file);
+ for (const match of current.source.matchAll(/require\(['"](\.\/[^'"]+)['"]\)/g)) {
+ const dependency = path.normalize(path.join(path.dirname(current.file), match[1]));
+ const dependencyFile = path.extname(dependency) ? dependency : dependency + '.js';
+ if (optional.has(dependencyFile)) continue;
+ assert.equal(stagedFiles.has(dependencyFile), true,
+ `macOS package omits startup dependency ${current.file} -> ${dependencyFile}`);
+ if (dependencyFile.endsWith('.js')) {
+ pending.push({
+ file: dependencyFile,
+ source: fs.readFileSync(path.join(scriptsDir, dependencyFile), 'utf8'),
+ });
+ }
+ }
+ }
+});
+
+test('WorkBuddy target configuration prefers explicit environment and fails closed', () => {
+ const { readWorkBuddyTarget } = require('../scripts/workbuddy-target.js');
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-target-'));
+ try {
+ assert.deepEqual(readWorkBuddyTarget({ dataDir, profileId: 'workbuddy-cn', env: {} }), {
+ configured: false, binary: '', version: '', source: 'default',
+ });
+
+ fs.writeFileSync(path.join(dataDir, 'workbuddy-target.json'), JSON.stringify({
+ profileId: 'workbuddy-cn', binary: 'D:\\Portable\\WorkBuddy.exe', version: '3.2.1',
+ }));
+ assert.deepEqual(readWorkBuddyTarget({ dataDir, profileId: 'workbuddy-cn', env: {} }), {
+ configured: true, binary: 'D:\\Portable\\WorkBuddy.exe', version: '3.2.1', source: 'file',
+ });
+ assert.equal(readWorkBuddyTarget({ dataDir, profileId: 'workbuddy-ai', env: {} }).binary, '');
+
+ const explicit = readWorkBuddyTarget({
+ dataDir,
+ profileId: 'workbuddy-cn',
+ env: { WBSWITCH_WORKBUDDY_BIN: 'E:\\WorkBuddy\\WorkBuddy.exe', WBSWITCH_WORKBUDDY_VERSION: '4.0.0' },
+ });
+ assert.deepEqual(explicit, {
+ configured: true, binary: 'E:\\WorkBuddy\\WorkBuddy.exe', version: '4.0.0', source: 'environment',
+ });
+
+ fs.writeFileSync(path.join(dataDir, 'workbuddy-target.json'), '{broken');
+ assert.deepEqual(readWorkBuddyTarget({ dataDir, profileId: 'workbuddy-cn', env: {} }), {
+ configured: true, binary: '', version: '', source: 'file',
+ });
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
diff --git a/test/secure-transfer.test.js b/test/secure-transfer.test.js
new file mode 100644
index 0000000..6ea35c5
--- /dev/null
+++ b/test/secure-transfer.test.js
@@ -0,0 +1,91 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+
+const {
+ createEncryptedExport,
+ openEncryptedExport,
+ remapSessionArchivePath,
+ resolveArchiveTarget,
+} = require('../scripts/secure-transfer.js');
+
+test('encrypted transfers require a password, randomize ciphertext, and bind the payload type', () => {
+ const payload = {
+ exportType: 'WorkDaddy-quick-phrases',
+ version: 1,
+ phrases: [{ text: '继续执行' }],
+ };
+ const first = createEncryptedExport('quick-phrases', payload, 'correct horse', '2026-08-28T00:00:00.000Z');
+ const second = createEncryptedExport('quick-phrases', payload, 'correct horse', '2026-08-28T00:00:00.000Z');
+
+ assert.notEqual(first, second, 'salt and IV must make repeated exports distinct');
+ assert.doesNotMatch(first, /继续执行|correct horse/);
+ assert.deepEqual(openEncryptedExport(first, 'quick-phrases', 'correct horse'), payload);
+ assert.throws(() => createEncryptedExport('quick-phrases', payload, ' '), /密码不能为空/);
+ assert.throws(() => openEncryptedExport(first, 'quick-phrases', ''), /密码不能为空/);
+ assert.throws(() => openEncryptedExport(first, 'sessions', 'correct horse'), /类型不匹配/);
+ assert.throws(() => openEncryptedExport(first, 'quick-phrases', 'wrong password'), /密码错误|损坏/);
+});
+
+test('session archive paths remap only managed session payload locations', () => {
+ const oldId = '11111111-1111-4111-8111-111111111111';
+ const newId = '22222222-2222-4222-8222-222222222222';
+ assert.equal(remapSessionArchivePath(`projects/hash/${oldId}.jsonl`, oldId, newId), `projects/hash/${newId}.jsonl`);
+ assert.equal(remapSessionArchivePath(`projects/hash/${oldId}/nested/data.json`, oldId, newId), `projects/hash/${newId}/nested/data.json`);
+ assert.equal(remapSessionArchivePath(`workspace/sessions/${oldId}/state.json`, oldId, newId), `workspace/sessions/${newId}/state.json`);
+ assert.equal(remapSessionArchivePath(`tasks/${oldId}/task.json`, oldId, newId), `tasks/${newId}/task.json`);
+ assert.equal(remapSessionArchivePath(`file-history/${oldId}/1.json`, oldId, newId), `file-history/${newId}/1.json`);
+ assert.equal(remapSessionArchivePath(`artifact-index/${oldId}.json`, oldId, newId), `artifact-index/${newId}.json`);
+ assert.throws(() => remapSessionArchivePath('../settings.json', oldId, newId), /无效|不受支持/);
+ assert.throws(() => remapSessionArchivePath(`projects/hash/other.jsonl`, oldId, newId), /不受支持/);
+
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-transfer-'));
+ try {
+ assert.equal(resolveArchiveTarget(root, `tasks/${newId}/task.json`), path.join(root, 'tasks', newId, 'task.json'));
+ assert.throws(() => resolveArchiveTarget(root, '../outside.json'), /数据目录/);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('daemon and injected panel expose password-protected account, session, and quick-phrase transfers', () => {
+ const repoRoot = path.join(__dirname, '..');
+ const daemon = fs.readFileSync(path.join(repoRoot, 'scripts', 'daemon.js'), 'utf8');
+ const inject = fs.readFileSync(path.join(repoRoot, 'scripts', 'inject.js'), 'utf8');
+ const macBuild = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');
+
+ assert.match(daemon, /body\s*&&\s*body\.uids/);
+ assert.match(daemon, /\/api\/sessions\/export/);
+ assert.match(daemon, /\/api\/sessions\/import/);
+ assert.match(daemon, /\/api\/quick-phrases\/export/);
+ assert.match(daemon, /\/api\/quick-phrases\/import/);
+ assert.match(macBuild, /secure-transfer\.js/);
+
+ const sessionToolbar = inject.slice(inject.indexOf('<div class="wbs-sess-toolbar">'), inject.indexOf('<div class="wbs-sess-list"'));
+ assert.ok(sessionToolbar.indexOf('id="wbs-sess-batch"') < sessionToolbar.indexOf('id="wbs-sess-import"'));
+ assert.ok(sessionToolbar.indexOf('id="wbs-sess-copy"') < sessionToolbar.indexOf('id="wbs-sess-export"'));
+ assert.ok(sessionToolbar.indexOf('id="wbs-sess-export"') < sessionToolbar.indexOf('id="wbs-sess-delete"'));
+
+ const phraseToolbar = inject.slice(inject.indexOf('<div class="wbs-qp-toolbar">'), inject.indexOf('<div class="wbs-qp-list"'));
+ assert.ok(phraseToolbar.indexOf('id="wbs-qp-batch"') < phraseToolbar.indexOf('id="wbs-qp-import"'));
+ assert.ok(phraseToolbar.indexOf('id="wbs-qp-copy"') < phraseToolbar.indexOf('id="wbs-qp-export"'));
+ assert.match(inject, /class="wbs-transfer-option selected"/);
+ assert.match(inject, /wbs-transfer-option[\s\S]*type="checkbox"[\s\S]*checked/);
+ assert.match(inject, /requirePassword:\s*true/);
+});
+
+test('successful session import reloads WorkBuddy through CDP without restarting it', () => {
+ const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+ const routeStart = daemon.indexOf("if (req.method === 'POST' && p === '/api/sessions/import')");
+ const routeEnd = daemon.indexOf("if (req.method === 'POST' && p === '/api/sessions/copy')", routeStart);
+ assert.notEqual(routeStart, -1);
+ assert.notEqual(routeEnd, -1);
+ const route = daemon.slice(routeStart, routeEnd);
+ const imported = route.indexOf('await importSessions(');
+ const reloaded = route.indexOf('await reloadWorkBuddyPage()');
+ assert.ok(imported >= 0 && reloaded > imported, 'reload must happen only after session import succeeds');
+ assert.match(route, /reloaded\s*=\s*true/);
+ assert.doesNotMatch(route, /quitWorkBuddy|relaunchWorkBuddy/);
+});
diff --git a/test/sentry.test.js b/test/sentry.test.js
index 3a50134..e0bedcc 100644
--- a/test/sentry.test.js
+++ b/test/sentry.test.js
@@ -150,17 +150,12 @@ test('privacy documentation distinguishes local data from required remote servic
assert.match(readme, /对应 API Key/);
});
-test('packaged repair instructions require a verified Sentry send', () => {
- const prompts = [
- fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8'),
- fs.readFileSync(path.join(repoRoot, '安装失败自主解决提示词.txt'), 'utf8'),
- ];
- for (const instructions of prompts) {
- assert.match(instructions, /启动后必须先完整读取本文件/);
- assert.match(instructions, /--force-send --require-sent/);
- assert.match(instructions, /只有看到 `sent=true` 才算上报成功/);
- assert.doesNotMatch(instructions, /可选诊断上报/);
- }
+test('source repair instructions require a verified Sentry send', () => {
+ const instructions = fs.readFileSync(path.join(repoRoot, '安装失败自主解决提示词.txt'), 'utf8');
+ assert.match(instructions, /启动后必须先完整读取本文件/);
+ assert.match(instructions, /--force-send --require-sent/);
+ assert.match(instructions, /只有看到 `sent=true` 才算上报成功/);
+ assert.doesNotMatch(instructions, /可选诊断上报/);
assert.match(reporterSource, /if \(key === 'force-send'\)/);
assert.match(reporterSource, /if \(args\.requireSent && result\.sent !== true\) process\.exitCode = 1/);
assert.match(reporterSource, /process\.exitCode = 1/);
diff --git a/test/session-db.test.js b/test/session-db.test.js
index 60f1779..ee6a6c3 100644
--- a/test/session-db.test.js
+++ b/test/session-db.test.js
@@ -254,10 +254,12 @@ test('daemon session SQL uses bound parameters without delimiter serialization',
assert.ok((daemon.match(/catch \(e\) \{ return json\(res, 400, \{ ok: false, error: e\.message \}\); \}/g) || []).length >= 4);
assert.doesNotMatch(daemon, /body\.ids\.filter\(/);
assert.match(daemon, /sqliteQuery\([^,]+,\s*\[[^\]]/s);
- assert.match(verifyWin, /daemon\.js session-db\.js lib\.js/);
+ assert.match(verifyWin, /daemon\.js session-db\.js secure-transfer\.js lib\.js/);
const copyList = (macBuild.match(/for f in ([^;]+); do/) || [])[1] || '';
assert.match(copyList, /(?:^|\s)session-db\.js(?:\s|$)/);
+ assert.match(copyList, /(?:^|\s)secure-transfer\.js(?:\s|$)/);
assert.match(copyList, /(?:^|\s)windows-process-boundary\.js(?:\s|$)/);
assert.match(macBuild, /chmod 644[\s\S]*session-db\.js/);
+ assert.match(macBuild, /chmod 644[\s\S]*secure-transfer\.js/);
assert.match(macBuild, /chmod 644[\s\S]*windows-process-boundary\.js/);
});
diff --git a/test/stash-queue.test.js b/test/stash-queue.test.js
index 0ebc834..532ffd7 100644
--- a/test/stash-queue.test.js
+++ b/test/stash-queue.test.js
@@ -7,12 +7,8 @@ const test = require('node:test');
const {
isStashQueueItem,
stashContentMatches,
- resolveWorkBuddyAiConversationId,
- workBuddyAiDraftStorageKey,
- isWorkBuddyAiComposerStore,
- workBuddyAiThemeMigrationKey,
- shouldMigrateWorkBuddyAiTheme,
} = require('../scripts/inject.js');
+const compat = require('../scripts/workbuddy-compat.js');
test('ordinary queue items are not classified as stash items by a text substring', () => {
const stashIds = ['stash-1'];
@@ -55,9 +51,9 @@ test('async stash cleanup only clears the content captured at click time', () =>
assert.equal(stashContentMatches(captured, { text: '先暂存这条', items: [{ type: 'image', uri: 'new-image' }] }), false);
});
-test('WorkBuddy AI draft cleanup is scoped to the exact active conversation store', () => {
- assert.equal(workBuddyAiDraftStorageKey(' conversation-a '), 'cb-draft:conversation-a');
- assert.equal(workBuddyAiDraftStorageKey(''), null);
+test('modern draft cleanup is scoped to the exact active conversation store', () => {
+ assert.equal(compat.draftStorageKey(' conversation-a '), 'cb-draft:conversation-a');
+ assert.equal(compat.draftStorageKey(''), null);
const matchingStore = {
api: {
@@ -76,33 +72,26 @@ test('WorkBuddy AI draft cleanup is scoped to the exact active conversation stor
getSnapshot() { return { activeSessionId: 'conversation-a' }; },
};
- assert.equal(isWorkBuddyAiComposerStore(matchingStore, 'conversation-a'), true);
- assert.equal(isWorkBuddyAiComposerStore(otherConversationStore, 'conversation-a'), false);
- assert.equal(isWorkBuddyAiComposerStore(unrelatedStore, 'conversation-a'), false);
+ assert.equal(compat.isComposerStore(matchingStore, 'conversation-a'), true);
+ assert.equal(compat.isComposerStore(otherConversationStore, 'conversation-a'), false);
+ assert.equal(compat.isComposerStore(unrelatedStore, 'conversation-a'), false);
});
test('stash cleanup clears the official composer store and persistent conversation draft before DOM fallback', () => {
const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
- assert.match(inject, /function clearWorkBuddyAiComposerDraft\(ed, sessionId\)/);
- assert.match(inject, /isWorkBuddyAiComposerStore\(store, sessionId\)/);
+ assert.match(inject, /function clearModernComposerDraft\(ed, sessionId\)/);
+ assert.match(inject, /WBS_COMPAT\.isComposerStore\(store, sessionId\)/);
assert.match(inject, /store\.api\.clear\(\)/);
+ assert.match(inject, /WBS_COMPAT\.draftStorageKey\(sessionId\)/);
assert.match(inject, /localStorage\.removeItem\(draftKey\)/);
- assert.match(inject, /clearWorkBuddyAiComposerDraft\(ed, stashSessionAtClick\)/);
+ assert.match(inject, /clearModernComposerDraft\(ed, stashSessionAtClick\)/);
});
-test('WorkBuddy AI theme migration is profile-gated and one-time', () => {
- assert.equal(workBuddyAiThemeMigrationKey('workbuddy-ai'), 'workdaddy:theme-migration:workbuddy-ai:official-light:v1');
- assert.equal(workBuddyAiThemeMigrationKey('workbuddy-cn'), null);
- assert.equal(shouldMigrateWorkBuddyAiTheme('workbuddy-ai', null), true);
- assert.equal(shouldMigrateWorkBuddyAiTheme('workbuddy-ai', '1'), false);
- assert.equal(shouldMigrateWorkBuddyAiTheme('workbuddy-cn', null), false);
-
+test('theme tab is capability-gated and available to WorkBuddy AI', () => {
const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
- assert.match(inject, /if \(!CAPS\.theme \|\| WBS_PROFILE_IS_AI\)/);
- assert.match(inject, /function migrateWorkBuddyAiThemeOnce\(\)/);
- assert.match(inject, /applyTheme\('default'\)/);
- assert.match(inject, /localStorage\.setItem\(migrationKey, '1'\)/);
- assert.match(inject, /migrateWorkBuddyAiThemeOnce\(\);/);
+ assert.match(inject, /if \(!CAPS\.theme\)/);
+ assert.doesNotMatch(inject, /if \(!CAPS\.theme \|\| WBS_PROFILE_IS_AI\)/);
+ assert.doesNotMatch(inject, /migrateWorkBuddyAiThemeOnce/);
});
test('daemon stash restore has an AI composer fallback when voice-mic-wrap is absent', () => {
@@ -111,8 +100,8 @@ test('daemon stash restore has an AI composer fallback when voice-mic-wrap is ab
assert.match(daemon, /var allEd = document\.querySelectorAll\('\[contenteditable="true"\]'\)/);
});
-test('WorkBuddy AI conversation id comes from the selected sidebar card, not message req ids', () => {
- const id = resolveWorkBuddyAiConversationId([
+test('modern conversation id comes from the selected sidebar card, not message req ids', () => {
+ const id = compat.selectedConversationId([
{
conversationId: 'background-conversation',
className: 'conversation-item',
@@ -129,45 +118,46 @@ test('WorkBuddy AI conversation id comes from the selected sidebar card, not mes
assert.notEqual(id, 'req-1787762196288001-assistant');
});
-test('WorkBuddy AI selected conversation resolver also supports aria-selected and rejects arbitrary rows', () => {
- assert.equal(resolveWorkBuddyAiConversationId([
+test('modern selected conversation resolver also supports aria-selected and rejects arbitrary rows', () => {
+ assert.equal(compat.selectedConversationId([
{ conversationId: 'arbitrary', className: 'conversation-item' },
{ conversationId: 'aria-selected', ariaSelected: 'true', className: 'conversation-item' },
]), 'aria-selected');
- assert.equal(resolveWorkBuddyAiConversationId([
+ assert.equal(compat.selectedConversationId([
{ conversationId: 'arbitrary', className: 'conversation-item' },
]), null);
});
-test('WorkBuddy AI queue path uses the top-level notifying adapter and clears stale adapter cache', () => {
+test('modern queue path uses the top-level notifying adapter and clears stale adapter cache', () => {
const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
assert.match(inject, /delete window\.__wbsAdapter/);
- assert.match(inject, /var target = ai\.adapter/);
+ assert.match(inject, /var target = found\.adapter/);
assert.doesNotMatch(inject, /var srX = p\.adapter\.sessionsResource/);
- assert.match(inject, /var selectedId = getWorkBuddyAiSelectedConversationId\(\)/);
- assert.match(inject, /function syncWorkBuddyAiQueueSnapshot\(sessionId, snapshot\)/);
+ assert.match(inject, /WBS_COMPAT\.getSelectedConversationId\(document\)/);
+ assert.match(inject, /function syncModernQueueSnapshot\(sessionId, snapshot\)/);
assert.match(inject, /store\.setPromptQueue\(queueItems\)/);
assert.match(inject, /__wbsQueueMirrorInstalled/);
assert.match(inject, /manager\.__wbsQueueMirrorItems = queueItems\.slice\(\)/);
assert.match(inject, /manager\.delete = function \(itemId\)/);
assert.match(inject, /adapter\.removeConversationMessageQueueItem\(sessionId, itemId\)/);
assert.match(inject, /adapter\.sendConversationMessageQueueItemNow\(sessionId, itemId\)/);
- assert.match(inject, /function handleWorkBuddyAiQueueActionClick\(event\)/);
- assert.match(inject, /listen\(document, 'click', handleWorkBuddyAiQueueActionClick, true\)/);
- assert.match(inject, /function waitForWorkBuddyAiQueueAdapter\(maxMs\)/);
- assert.match(inject, /var pauseWait = WBS_PROFILE_IS_AI\s*\?/);
+ assert.match(inject, /function handleModernQueueActionClick\(event\)/);
+ assert.match(inject, /listen\(document, 'click', handleModernQueueActionClick, true\)/);
+ assert.match(inject, /function waitForModernQueueAdapter\(maxMs\)/);
+ assert.match(inject, /var pauseWait = modernAdapter\s*\?/);
+ assert.match(inject, /WBS_COMPAT\.isModernQueueAdapter\(adapter\)/);
assert.match(inject, /enqueue:not-ready-no-fallback/);
- assert.match(inject, /function warmWorkBuddyAiQueueAdapter\(\)/);
+ assert.match(inject, /function warmModernQueueAdapter\(\)/);
assert.match(inject, /var stashInFlight = null/);
assert.match(inject, /if \(stashBusy \|\| stashInFlight\) return/);
assert.match(inject, /stashInFlight = stashWork/);
assert.match(inject, /stashInFlight = null/);
- assert.match(inject, /function writeWorkBuddyAiQueueItemToComposer\(item\)/);
+ assert.match(inject, /function writeModernQueueItemToComposer\(item\)/);
assert.match(inject, /controller\.promptQueue\.emitQueueUpdate\(\)/);
assert.match(inject, /stashSessionAtClick = sessionId/);
});
-test('WorkBuddy AI stash pauses before enqueue and refreshes incomplete snapshots', () => {
+test('modern stash pauses before enqueue and refreshes incomplete snapshots', () => {
const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
const start = inject.indexOf('function enqueueToWorkBuddyQueue(content)');
const end = inject.indexOf('\n var stashBusy = false;', start);
@@ -175,10 +165,10 @@ test('WorkBuddy AI stash pauses before enqueue and refreshes incomplete snapshot
const queuePath = inject.slice(start, end);
assert.match(queuePath, /pauseWait[\s\S]*pauseConversationMessageQueue\(sessionId, 'manual'\)/);
assert.ok(queuePath.indexOf('pauseConversationMessageQueue(sessionId, \'manual\')') < queuePath.indexOf('enqueueConversationMessageQueueItem(sessionId, blocks)'), 'pause must be requested before enqueue');
- assert.match(queuePath, /getWorkBuddyAiQueueSnapshot\(adapter, sessionId, snapshot\)/);
- assert.match(inject, /function getWorkBuddyAiQueueSnapshot\(adapter, sessionId, preferred\)/);
+ assert.match(queuePath, /getModernQueueSnapshot\(adapter, sessionId, snapshot\)/);
+ assert.match(inject, /function getModernQueueSnapshot\(adapter, sessionId, preferred\)/);
assert.match(inject, /__wbsOptimistic/);
assert.match(inject, /id: 'wbs-pending-'/);
- assert.match(inject, /dropWorkBuddyAiOptimisticItem\(stashSessionAtClick\)/);
+ assert.match(inject, /dropModernOptimisticItem\(stashSessionAtClick\)/);
assert.match(inject, /queueItems\.length === 0[\s\S]*currentItems\.length > 0[\s\S]*snapshot\.runtime == null/);
});
diff --git a/test/theme-patches.test.js b/test/theme-patches.test.js
new file mode 100644
index 0000000..2d639e0
--- /dev/null
+++ b/test/theme-patches.test.js
@@ -0,0 +1,17 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const test = require('node:test');
+
+const patches = require('../scripts/theme-patches.js');
+
+test('conversation shell and grouped agent cards use global theme patch rules', () => {
+ const patch = patches.find((item) => item && item.id === 'patch-83');
+ assert.ok(patch, 'patch-83 must remain registered');
+ assert.equal(typeof patch.css, 'string');
+ assert.match(patch.css, /\.conversation-shell__main\{background:transparent !important/);
+ assert.match(patch.css, /\.conversation-section-content \.cb-agent-card\{/);
+ assert.match(patch.css, /color-mix\(in srgb,var\(--wb-bg-primary\) 32%,transparent\)/);
+ assert.match(patch.css, /backdrop-filter:blur\(14px\)/);
+ assert.doesNotMatch(patch.css, /WBS_PROFILE|workbuddy-ai|data-theme="dark"/);
+});
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index a3bab8a..f1f56b4 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -44,13 +44,16 @@ test('theme apply retries CDP evaluation and persists the selection only after s
assert.ok(route.indexOf("fs.writeFileSync(path.join(DATA_DIR, 'current-theme.json')") > route.indexOf('.then((info)'), 'failed theme must not be persisted');
});
-test('Windows updater keeps an apply-update VBS bridge in the package and has a runtime fallback', () => {
+test('Windows updater opens the verified Setup directly without a script bridge', () => {
const daemon = read('daemon.js');
const build = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-win-zip.sh'), 'utf8');
- assert.match(build, /apply-update\.vbs/);
- assert.match(build, /关键文件|required|必须/);
- assert.match(daemon, /apply-update\.vbs/);
- assert.match(daemon, /runtime.*vbs|生成.*VBS|写入.*VBS/i);
+ const branchStart = daemon.indexOf('if (IS_WIN) {', daemon.indexOf('function applyUpdate()'));
+ const branchEnd = daemon.indexOf("const scriptPath = path.join(__dirname, 'apply-update.sh')", branchStart);
+ const branch = daemon.slice(branchStart, branchEnd);
+ assert.match(build, /WorkDaddyLauncher\.exe/);
+ assert.match(branch, /launchWindowsInstaller\(srcPackage\)/);
+ assert.match(branch, /installer-opened/);
+ assert.doesNotMatch(branch, /apply-update\.vbs|wscript|pending\.json/);
});
test('update status exposes the running daemon version so reboot polling can finish', () => {
@@ -546,7 +549,10 @@ test('Windows release packages bundle a pinned Node runtime and build a user-lev
assert.match(workflow, /-Version \$\{\{ steps\.ver\.outputs\.version \}\}/);
assert.match(iss, /PrivilegesRequired=lowest/);
assert.match(iss, /runtime|scripts\\\*/i);
- assert.match(iss, /install-win\.ps1/);
+ assert.match(iss, /WorkDaddyLauncher\.exe/);
+ assert.doesNotMatch(iss, /install-win\.ps1|launcher-hidden\.vbs|wscript\.exe/i);
+ assert.match(build, /GOOS=windows GOARCH=amd64/);
+ assert.match(workflow, /actions\/setup-go@v5/);
assert.match(workflow, /(?:Install Inno Setup|安装 Inno Setup)/);
assert.match(workflow, /build-win-installer\.ps1/);
assert.match(workflow, /release\/windows\/WorkDaddy-Setup-\*\.exe/);
@@ -566,34 +572,34 @@ test('Windows release publishes Setup.exe only and removes temporary ZIP staging
assert.match(guide, /temporary staging/);
});
-test('Windows Setup stops a verified lifecycle or preserves an authenticated elevated runtime', () => {
+test('Windows Setup waits for WorkBuddy and stops only a native-verified profile lifecycle', () => {
const installer = fs.readFileSync(path.join(repoRoot, 'scripts', 'win', 'workdaddy.iss'), 'utf8');
- const prepare = fs.readFileSync(path.join(repoRoot, 'scripts', 'prepare-win-install.ps1'), 'utf8');
- const verify = fs.readFileSync(path.join(repoRoot, 'scripts', 'verify-win.cmd'), 'utf8');
assert.match(installer, /function PrepareToInstall\(var NeedsRestart: Boolean\): String/);
- assert.match(installer, /ExtractTemporaryFile\('prepare-win-install\.ps1'\)/);
- assert.match(installer, /ExtractTemporaryFile\('windows-process-boundary\.ps1'\)/);
+ assert.match(installer, /ExtractTemporaryFile\('WorkDaddyLauncher\.exe'\)/);
+ assert.match(installer, /function EnsureWorkBuddyClosed/);
+ assert.match(installer, /--check-workbuddy/);
+ assert.match(installer, /重新检测/);
+ assert.match(installer, /结束进程/);
+ assert.match(installer, /--terminate-workbuddy/);
+ assert.match(installer, /--stop-lifecycle/);
assert.match(installer, /ewWaitUntilTerminated/);
- assert.match(prepare, /Stop-VerifiedWorkDaddyLifecycle/);
- assert.match(prepare, /Get-AuthenticatedWorkDaddyStatus/);
- assert.match(prepare, /-AllowVersionMismatch/);
- assert.match(prepare, /exit 10/);
- assert.match(prepare, /\$privilege = if \(\$principal\.IsInRole/);
- assert.doesNotMatch(prepare, /Refusing to prepare WorkDaddy installation with elevated privileges/);
- assert.match(installer, /ResultCode = 5/);
- assert.match(installer, /ResultCode = 10/);
- assert.match(installer, /ShouldReplaceRuntime/);
+ assert.match(installer, /ResultCode <> 10/);
+ assert.match(installer, /ResultCode = 11/);
assert.match(installer, /runtime\\node\\\*/);
- assert.match(installer, /管理员权限运行的旧版 WorkDaddy/);
- assert.match(prepare, /WorkDaddy-prepare-install\.log/);
- assert.match(prepare, /-ExpectedWatchdogScript \(Join-Path \$AppDir 'scripts\\watchdog\.js'\)/);
- assert.match(verify, /prepare-win-install\.ps1/);
+ assert.match(installer, /无法安全停止 WorkDaddy 后台进程/);
+ assert.match(installer, /IsAdminInstallMode/);
+ assert.match(installer, /当前安装程序是以管理员权限运行的/);
+ assert.match(installer, /不要选择“以管理员身份运行”/);
+ assert.match(installer, /普通安装器不会跨权限强行结束/);
+ assert.doesNotMatch(installer, /安装器本身可以使用管理员权限运行/);
+ assert.doesNotMatch(installer, /旧版 WorkDaddy 正以管理员权限运行/);
+ assert.doesNotMatch(installer, /prepare-win-install|windows-process-boundary|PowerShell/i);
});
-test('macOS release staging includes the troubleshooting prompt', () => {
+test('macOS release staging excludes the troubleshooting prompt', () => {
const build = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');
- assert.match(build, /STAGE\/安装失败自主解决提示词\.txt/);
- assert.match(build, /cat > "\$STAGE\/安装失败自主解决提示词\.txt"/);
+ assert.doesNotMatch(build, /STAGE\/安装失败自主解决提示词\.txt/);
+ assert.doesNotMatch(build, /cat > "\$STAGE\/安装失败自主解决提示词\.txt"/);
});
test('macOS package launcher keeps WorkBuddy CN and AI CDP ports profile-specific', () => {
@@ -614,12 +620,9 @@ test('macOS package launcher returns focus to the target WorkBuddy and separates
test('troubleshooting prompts keep Sentry reports short and omit raw logs', () => {
const prompt = fs.readFileSync(path.join(repoRoot, '安装失败自主解决提示词.txt'), 'utf8');
- const macBuild = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');
- assert.ok(prompt.length < 3500, 'Windows prompt should stay compact');
+ assert.ok(prompt.length < 3500, 'source prompt should stay compact');
assert.match(prompt, /报告硬上限 3500 字符/);
assert.match(prompt, /不要粘贴完整日志/);
- assert.match(macBuild, /报告硬上限 3500 字符/);
- assert.match(macBuild, /不附完整日志/);
});
test('daemon lock falls back when the data-directory lock is not writable on Windows', () => {
@@ -668,9 +671,9 @@ test('account cards keep the compact three-row layout', () => {
assert.match(script, /var isUinMode = !a\.phone;/);
assert.match(script, /var idLbl = a\.phone \? '手机' : \(a\.uin \? 'UIN' : '账号'\)/);
assert.match(script, /\.wbs-phone-cell\.wbs-uin-cell\{gap:4px\}/);
- // 国际版:签到标签不展示;暂存按钮内联进操作栏按钮组第一位(AI 端无 voice-mic-wrap)
+ // 国际版:签到标签不展示;新版布局按能力把暂存按钮内联进操作栏按钮组第一位。
assert.match(script, /if \(PROFILE_ID === 'workbuddy-ai'\) return '';/);
- assert.match(script, /function findAiToolbar\(\)/);
+ assert.match(script, /WBS_COMPAT\.findComposerToolbar\(document\)/);
assert.match(script, /wbs-stash-inline-inline/);
assert.match(script, /row0\.insertBefore\(stashBtn, row0\.firstChild\)/);
assert.match(script, /wbs-credit-hidden/);
@@ -746,15 +749,12 @@ test('auto-continue keeps the three-second terminal settle window', () => {
test('robot button decorations remain visible alongside the eye states', () => {
const script = read('inject.js');
assert.match(script, /wbs-fab-antenna/);
- assert.match(script, /wbs-fab-ear wbs-fab-ear-left/);
- assert.match(script, /wbs-fab-ear wbs-fab-ear-right/);
- assert.match(script, /\.wbs-fab-ear\{[^}]*width:20px;height:30px[^}]*background:#141416/);
- assert.match(script, /\.wbs-fab-ear::before\{[^}]*width:12px;height:22px[^}]*background:#141416/);
- assert.doesNotMatch(script, /\.wbs-fab-ear::before\{[^}]*background:#fff/);
- assert.match(script, /\.wbs-fab-ear::after\{[^}]*width:4px;height:10px[^}]*background:#141416/);
- assert.match(script, /wbs-fab-ear-left\{left:-11px;transform:[^}]*rotate\(-8deg\)/);
- assert.match(script, /wbs-fab-ear-right\{right:-11px;transform:[^}]*rotate\(8deg\)/);
- assert.match(script, /\.wbs-fab \.click > span:not\(\.wbs-fab-antenna\):not\(\.wbs-fab-ear\)\{display:none\}/);
+ assert.doesNotMatch(script, /wbs-fab-ear/); // 用户 08-30 00:37 要求去掉双耳
+ assert.match(script, /\.wbs-fab-antenna\{[^}]*background:rgba\(20,20,22,\.55\)[^}]*mask-image:url\("data:image\/svg\+xml/);
+ assert.match(script, /\.wbs-fab-antenna-dot\{[^}]*background:transparent/);
+ assert.match(script, /viewBox=\\'0 0 14 24\\'>/);
+ assert.match(script, /#wbs-fab-sleep-light\.sleep-on\{background:rgba\(46,229,157,\.85\)/);
+ assert.match(script, /\.wbs-fab \.click > span:not\(\.wbs-fab-antenna\)\{display:none\}/);
assert.doesNotMatch(script, /\.wbs-fab \.click span\{display:none\}/);
assert.match(script, /\.wbs-fab \.click \.button \.speak~\.speak\{display:none\}/);
});
@@ -803,6 +803,19 @@ test('update card keeps the action button stable beside short progress text', ()
assert.doesNotMatch(script, /也可双击桌面 .* 图标手动启动/);
});
+test('Windows updater stops at the installer prompt after download', () => {
+ const script = read('inject.js');
+ assert.match(script, /var WBS_PLATFORM = __WBS_PLATFORM__/);
+ assert.doesNotMatch(script, /var WBS_PLATFORM = '__WBS_PLATFORM__'/);
+ const injectedWindows = script.replace(/__WBS_PLATFORM__/g, JSON.stringify('win32'));
+ assert.match(injectedWindows, /var WBS_PLATFORM = "win32";/);
+ assert.match(script, /function showWindowsInstallerReady\(prog, btn, card, timer\)/);
+ assert.match(script, /function openWindowsInstallerAfterDownload\(prog, btn, card, timer, resolve, reject\)/);
+ assert.match(script, /appendUpdateLog\(prog, '即将打开安装包…'\)/);
+ assert.match(script, /if \(WBS_PLATFORM === 'win32'\) \{[\s\S]*openWindowsInstallerAfterDownload\(prog, btn, card, timer, resolve, reject\);/);
+ assert.doesNotMatch(script, /下载和校验完成,可以打开安装程序。/);
+});
+
test('update notes keep the full release text inside the panel scroll area', () => {
const script = read('inject.js');
assert.doesNotMatch(script, /\.slice\(0,\s*3\)\.map/);
@@ -819,7 +832,6 @@ test('auto-continue and session controls are available on Windows and macOS', ()
assert.match(inject, /var acRow = enhancePane && enhancePane\.querySelector\('\#wbs-ac-row'\)/);
assert.match(inject, /var AC_SUPPORTED = true/);
assert.doesNotMatch(inject, /WBS_PLATFORM !== 'win32'/);
- assert.doesNotMatch(inject, /WBS_PLATFORM === 'win32'\) \{/);
assert.match(daemon, /platformSupported: true/);
assert.doesNotMatch(daemon, /const enabled = !IS_WIN/);
assert.doesNotMatch(daemon, /if \(IS_WIN\) return readAutoContinueState/);
@@ -938,12 +950,13 @@ test('update downloads use a unique partial file before atomically promoting the
test('account export asks for a non-empty password and import supports an optional password', () => {
const daemon = read('daemon.js');
const inject = read('inject.js');
- assert.match(daemon, /password.*不能为空|导出密码不能为空/);
- assert.match(daemon, /randomBytes\(16\)/);
+ const secureTransfer = read('secure-transfer.js');
+ assert.match(secureTransfer, /密码不能为空/);
+ assert.match(secureTransfer, /randomBytes\(16\)/);
assert.match(daemon, /version:\s*2/);
assert.match(daemon, /EXPORT_PASSPHRASE/);
- assert.match(inject, /导出账号.*密码/);
- assert.match(inject, /导入密码可留空/);
+ assert.match(inject, /title:\s*'导出账号'[\s\S]*requirePassword:\s*true/);
+ assert.match(inject, /旧版导出文件可留空/);
assert.match(inject, /type="password"/);
});
diff --git a/test/verify-win-exit.test.js b/test/verify-win-exit.test.js
index 21f0d6b..1346bae 100644
--- a/test/verify-win-exit.test.js
+++ b/test/verify-win-exit.test.js
@@ -57,7 +57,7 @@ test('Windows verifier returns success for a complete source package', { skip: p
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-verify-win-complete-'));
const scriptsDir = path.join(dir, 'scripts');
const required = [
- 'daemon.js', 'session-db.js', 'lib.js', 'watchdog.js', 'win-launcher.js',
+ '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', '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',
diff --git a/test/windows-launcher-boundary-repair.test.js b/test/windows-launcher-boundary-repair.test.js
index 92d663b..b2d73a9 100644
--- a/test/windows-launcher-boundary-repair.test.js
+++ b/test/windows-launcher-boundary-repair.test.js
@@ -126,11 +126,14 @@ test('launcher enumerates exact lifecycle entries and never kills process trees'
assert.match(launcherSource, /taskkill 非零但目标 PID 已消失,按竞态成功处理/);
assert.match(launcherSource, /verifyGone && await verifyGone\(\)/);
assert.match(launcherSource, /queryNodeProcesses\(nodeBin, \[pid\]\)\.length === 0/);
- for (const source of [launcherSource, daemonSource, watchdogSource]) {
+ for (const source of [launcherSource, daemonSource]) {
assert.match(source, /buildNativeProcessQuery/);
assert.match(source, /windows-process-boundary\.ps1/);
assert.match(source, /-ExecutionPolicy['"],\s*['"]Bypass/);
}
+ assert.match(watchdogSource, /net\.createServer\(\)/);
+ assert.match(watchdogSource, /exclusive:\s*true/);
+ assert.doesNotMatch(watchdogSource, /Get-CimInstance|PowerShell|taskkill/i);
});
test('installer boundary releases the exact profile launcher and waits for its runtime lock', () => {
@@ -174,7 +177,7 @@ test('CIM process disappearance is treated as an empty snapshot, not a launcher
assert.match(boundarySource, /allowTransientNotFound/);
assert.match(boundarySource, /0x80041002/);
assert.match(launcherSource, /allowTransientNotFound:\s*true/);
- assert.match(watchdogSource, /allowTransientNotFound:\s*true/);
+ assert.doesNotMatch(watchdogSource, /CIM|Get-CimInstance/);
});
test('authenticated daemon capability binds token-only status to profile, data directory, and listener PID', () => {
@@ -293,11 +296,12 @@ test('PowerShell reconciles only a proven stale watchdog PID file', () => {
assert.match(powershellSource, /Remove-Item -LiteralPath \$pidFile -Force -ErrorAction Stop/);
});
-test('Windows launcher and watchdog recover a PID file whose process is gone', () => {
+test('legacy launcher recovers stale PID files while the new watchdog uses an OS lock', () => {
assert.match(launcherSource, /watchdog\.kind === 'stale'[\s\S]*removeWatchdogPidIf\(watchdog\.pid\)/);
assert.match(launcherSource, /已清理确认不存在的旧 watchdog\.pid/);
- assert.match(watchdogSource, /state\.kind === 'stale'[\s\S]*removePidFileIf\(state\.pid\)/);
- assert.match(watchdogSource, /existing\.kind === 'stale'[\s\S]*removePidFileIf\(existing\.pid\)/);
+ assert.match(watchdogSource, /LOCK_PORT/);
+ assert.match(watchdogSource, /EADDRINUSE/);
+ assert.match(watchdogSource, /writePidFile\(\)/);
});
test('Windows launcher reconciles a reused PID file to an exact watchdog', () => {
@@ -325,7 +329,10 @@ test('Windows launcher ignores WorkBuddy AI headless prewarm helpers during cold
test('Windows process queries are scoped to the selected Node runtime', () => {
assert.match(launcherSource, /ExecutablePath -ieq/);
- assert.match(watchdogSource, /ExecutablePath -ieq/);
+ const nativeSource = fs.readFileSync(path.join(root, 'scripts', 'windows-native', 'main.go'), 'utf8');
+ assert.match(nativeSource, /expectedNode/);
+ assert.match(nativeSource, /QueryFullProcessImageNameW/);
+ assert.match(nativeSource, /samePath\(actual, expectedPath\)/);
});
test('optional WorkBuddy path discovery does not make launcher startup fatal', () => {
diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.js
new file mode 100644
index 0000000..c3880b6
--- /dev/null
+++ b/test/windows-native-flow.test.js
@@ -0,0 +1,131 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const { EventEmitter } = require('node:events');
+const path = require('node:path');
+const test = require('node:test');
+const { launchWindowsInstaller } = require('../scripts/windows-installer-launch.js');
+
+const root = path.join(__dirname, '..');
+const read = (relative) => fs.readFileSync(path.join(root, relative), 'utf8');
+
+test('Windows native launcher is the packaged user-level entry point', () => {
+ const installer = read('scripts/win/workdaddy.iss');
+ const build = read('scripts/build-win-zip.sh');
+ const source = read('scripts/windows-native/main.go');
+
+ assert.match(installer, /Filename: "\{app\}\\WorkDaddyLauncher\.exe"/);
+ assert.doesNotMatch(installer, /launcher-hidden\.vbs|wscript\.exe/i);
+ assert.match(build, /WorkDaddyLauncher\.exe/);
+ assert.match(source, /TokenElevation/);
+ assert.match(source, /CreateMutexW/);
+ assert.match(source, /WBSWITCH_NATIVE_LAUNCHER/);
+ assert.match(source, /mbRetryCancel/);
+});
+
+test('normal Windows startup does not use Explorer de-elevation or CIM', () => {
+ const launcher = read('scripts/win-launcher.js');
+ const watchdog = read('scripts/watchdog.js');
+
+ assert.match(launcher, /async function nativeStartupMain/);
+ assert.match(launcher, /WBSWITCH_NATIVE_LAUNCHER/);
+ const nativeStart = launcher.slice(
+ launcher.indexOf('async function nativeStartupMain'),
+ launcher.indexOf('// ---------- legacy script entry ----------')
+ );
+ assert.doesNotMatch(nativeStart, /Get-CimInstance|windows-relaunch-standard|quitWorkBuddy/);
+ assert.doesNotMatch(watchdog, /Get-CimInstance|windows-process-boundary|pending\.json/);
+});
+
+test('installer waits for the exact profile client with a visible recheck dialog', () => {
+ const installer = read('scripts/win/workdaddy.iss');
+
+ assert.match(installer, /function EnsureWorkBuddyClosed/);
+ assert.match(installer, /--check-workbuddy/);
+ assert.match(installer, /Caption := '\u91cd\u65b0\u68c0\u6d4b'/);
+ assert.match(installer, /Caption := '\u7ed3\u675f\u8fdb\u7a0b'/);
+ assert.match(installer, /Caption := '\u53d6\u6d88'/);
+ assert.match(installer, /--terminate-workbuddy/);
+ assert.match(installer, /--stop-lifecycle/);
+ assert.match(installer, /IsAdminInstallMode/);
+ assert.match(installer, /当前安装程序是以管理员权限运行的/);
+ assert.match(installer, /ExecAsOriginalUser\(/);
+ assert.match(installer, /runasoriginaluser/);
+ assert.match(installer, /PrivilegesRequired=lowest/);
+ assert.match(installer, /CloseApplications=no/);
+});
+
+test('Windows update opens the verified Setup visibly and keeps daemon alive', () => {
+ const daemon = read('scripts/daemon.js');
+ const inject = read('scripts/inject.js');
+ const windowsBranchStart = daemon.indexOf('if (IS_WIN) {', daemon.indexOf('function applyUpdate()'));
+ const macBranchStart = daemon.indexOf("const scriptPath = path.join(__dirname, 'apply-update.sh')", windowsBranchStart);
+ const windowsBranch = daemon.slice(windowsBranchStart, macBranchStart);
+
+ assert.match(windowsBranch, /launchWindowsInstaller\(srcPackage\)/);
+ assert.match(windowsBranch, /installer-opened/);
+ assert.doesNotMatch(windowsBranch, /apply-update\.ps1|apply-update\.vbs|pending\.json|process\.exit/);
+ assert.doesNotMatch(windowsBranch, /VERYSILENT|SILENT/i);
+ assert.match(inject, /\u6253\u5f00\u5b89\u88c5\u7a0b\u5e8f/);
+ assert.match(inject, /function showWindowsInstallerReady[\s\S]*\u6253\u5f00\u5b89\u88c5\u7a0b\u5e8f/);
+ assert.match(inject, /WBS_PLATFORM === 'win32'[\s\S]*showWindowsInstallerReady/);
+});
+
+test('Windows installer launch uses a visible detached process without shell arguments', async () => {
+ let call = null;
+ let unreferenced = false;
+ const fakeSpawn = (file, args, options) => {
+ call = { file, args, options };
+ const child = new EventEmitter();
+ child.pid = 424242;
+ child.unref = () => { unreferenced = true; };
+ queueMicrotask(() => child.emit('spawn'));
+ return child;
+ };
+ const child = launchWindowsInstaller('C:\\Updates\\WorkDaddy-Setup-9.9.9.exe', fakeSpawn);
+ await new Promise((resolve, reject) => {
+ child.once('spawn', resolve);
+ child.once('error', reject);
+ });
+ child.unref();
+ assert.deepEqual(call, {
+ file: 'C:\\Updates\\WorkDaddy-Setup-9.9.9.exe',
+ args: [],
+ options: { detached: true, stdio: 'ignore', windowsHide: false },
+ });
+ assert.equal(unreferenced, true);
+ assert.throws(() => launchWindowsInstaller('C:\\Updates\\legacy.zip', fakeSpawn), /Setup\.exe/);
+});
+
+test('macOS update still uses the existing apply-update shell script', () => {
+ const daemon = read('scripts/daemon.js');
+ const applyStart = daemon.indexOf('function applyUpdate()');
+ const branch = daemon.slice(applyStart, daemon.indexOf('// ================', applyStart));
+ assert.match(branch, /apply-update\.sh/);
+ assert.match(branch, /extractAppFromDmg/);
+ assert.match(branch, /spawn\('bash'/);
+});
+
+test('native helper keeps WorkBuddy CN and AI process detection isolated', () => {
+ const source = read('scripts/windows-native/main.go');
+ const launcher = read('scripts/win-launcher.js');
+ assert.match(source, /workbuddy-cn[\s\S]*WorkBuddy\.exe/);
+ assert.match(source, /workbuddy-ai[\s\S]*WorkBuddyAI\.exe/);
+ assert.match(source, /QueryFullProcessImageNameW/);
+ assert.match(source, /func terminateWorkBuddy\(profile string\)/);
+ assert.match(source, /uniqueRunningWorkBuddyPath/);
+ assert.match(source, /terminateExactProcess\(int\(match\.PID\), expectedPath, "WorkBuddy"\)/);
+ assert.match(source, /lifecycle stop requires standard user privilege/);
+ assert.match(launcher, /path\.join\(programFiles, 'WorkBuddy', 'WorkBuddy\.exe'\)/);
+ assert.match(launcher, /path\.join\(programFilesX86, 'WorkBuddy', 'WorkBuddy\.exe'\)/);
+});
+
+test('native lifecycle cleanup accepts a PID that exits during exact inspection', () => {
+ const source = read('scripts/windows-native/main.go');
+ const missingPath = source.indexOf('if actual == ""');
+ const exitedCheck = source.indexOf('procWaitForSingleObject.Call(uintptr(handle), 2000)', missingPath);
+ const mismatch = source.indexOf('return false, exitIdentityMismatch', missingPath);
+ assert.ok(missingPath >= 0 && exitedCheck > missingPath && mismatch > exitedCheck);
+ assert.match(source.slice(exitedCheck, mismatch), /waitResult == waitObject0[\s\S]*return false, 0, nil/);
+});
diff --git a/test/windows-privilege-boundary.test.js b/test/windows-privilege-boundary.test.js
index 20176df..6ca0a7c 100644
--- a/test/windows-privilege-boundary.test.js
+++ b/test/windows-privilege-boundary.test.js
@@ -1,9 +1,7 @@
'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');
@@ -12,6 +10,7 @@ const scriptsDir = path.join(root, 'scripts');
const launcherSource = fs.readFileSync(path.join(scriptsDir, 'win-launcher.js'), 'utf8');
const daemonSource = fs.readFileSync(path.join(scriptsDir, 'daemon.js'), 'utf8');
const watchdogSource = fs.readFileSync(path.join(scriptsDir, 'watchdog.js'), 'utf8');
+const nativeSource = fs.readFileSync(path.join(scriptsDir, 'windows-native', 'main.go'), 'utf8');
const installerSource = fs.readFileSync(path.join(scriptsDir, 'install-win.ps1'), 'utf8');
const readmeSource = fs.readFileSync(path.join(root, 'README.md'), 'utf8');
const hiddenLauncherSource = fs.readFileSync(path.join(scriptsDir, 'launcher-hidden.vbs'), 'utf8');
@@ -165,43 +164,21 @@ test('daemon status identity binds metadata, listener PID, node path, and script
assert.throws(() => boundary.assertDaemonServiceIdentity({ ...input, status: { ...status, pid: '301' } }), /PID/i);
});
-test('Windows entry points detect and expose a matching daemon privilege mode', () => {
+test('Windows native entry point enforces standard privilege and exposes daemon identity', () => {
assert.equal(fs.existsSync(path.join(scriptsDir, 'win-inject-helper.js')), false);
- assert.match(launcherSource, /detectWindowsPrivilege/);
- assert.match(watchdogSource, /detectWindowsPrivilege/);
+ assert.match(nativeSource, /TokenElevation/);
+ assert.match(nativeSource, /func isElevated\(\)/);
+ assert.match(nativeSource, /if elevated \{/);
+ assert.match(nativeSource, /WBSWITCH_NATIVE_LAUNCHER=1/);
assert.match(daemonSource, /detectWindowsPrivilege/);
assert.match(daemonSource, /privilege:\s*DAEMON_PRIVILEGE/);
assert.match(daemonSource, /pid:\s*process\.pid/);
- assert.match(launcherSource, /assertDaemonServiceIdentity/);
- const privilegeProbe = launcherSource.indexOf('detectWindowsPrivilege();');
- const telemetryImport = launcherSource.indexOf('const { captureMessage');
- assert.ok(privilegeProbe >= 0 && telemetryImport > privilegeProbe);
- const privilegeFailure = launcherSource.slice(privilegeProbe, telemetryImport);
- assert.doesNotMatch(privilegeFailure, /reportAndExit|captureMessage|captureException|\blog\s*\(/);
- const ensureDaemonSource = launcherSource.slice(
- launcherSource.indexOf('async function ensureDaemon'),
- launcherSource.indexOf('// ---------- 2\/3.', launcherSource.indexOf('async function ensureDaemon'))
- );
- assert.doesNotMatch(ensureDaemonSource, /daemonRunning\s*\(/);
- assert.match(ensureDaemonSource, /exactDaemonStatus/);
- assert.match(watchdogSource, /assertVerifiedNodeProcess/);
- assert.match(watchdogSource, /filterVerifiedNodeProcesses/);
- assert.match(watchdogSource, /assertSameProcessIdentity/);
- assert.match(watchdogSource, /requireCurrentOwner:\s*true/);
- assert.match(watchdogSource, /requireNativeArguments:\s*true/);
- assert.match(watchdogSource, /ParentProcessId/);
- assert.match(watchdogSource, /flag:\s*['"]wx['"]/);
- assert.match(watchdogSource, /queryWatchdogProcesses\(\)/);
- assert.match(watchdogSource, /state\.kind === 'untracked'/);
- assert.doesNotMatch(watchdogSource, /taskkill[\s\S]{0,120}['"]\/T['"]/i);
- assert.match(watchdogSource, /terminateVerifiedProcess\(state\.watchdog/);
- assert.match(watchdogSource, /terminateVerifiedProcess\(daemon/);
- assert.match(watchdogSource, /if \(state\.kind === 'stale'\) \{[\s\S]*removePidFileIf\(state\.pid\)/);
- assert.match(launcherSource, /if \(watchdog\.kind === 'stale'\) \{[\s\S]*removeWatchdogPidIf\(watchdog\.pid\)/);
- assert.match(launcherSource, /queryNodeProcesses\(nodeBin, \[pid\]\)/);
- assert.match(launcherSource, /allowLowerPrivilege/);
- assert.match(watchdogSource, /ExecutablePath -ieq/);
- assert.doesNotMatch(launcherSource + daemonSource, /Start-Process[^\n]*-Verb\s+RunAs/i);
+ assert.match(watchdogSource, /net\.createServer\(\)/);
+ assert.match(watchdogSource, /exclusive:\s*true/);
+ assert.doesNotMatch(watchdogSource, /powershell|Get-CimInstance|Invoke-CimMethod|taskkill/i);
+ assert.match(nativeSource, /expectedNode := filepath\.Join\(appDir, "scripts", "runtime", "node", "node\.exe"\)/);
+ assert.match(nativeSource, /if !samePath\(actual, expectedPath\)/);
+ assert.doesNotMatch(nativeSource + daemonSource, /Start-Process[^\n]*-Verb\s+RunAs/i);
assert.doesNotMatch(installerSource, /请以管理员身份运行/);
assert.doesNotMatch(readmeSource, /右键以管理员身份运行 WorkDaddy/);
});
@@ -233,129 +210,29 @@ test('PowerShell lifecycle scopes daemon discovery to a verified watchdog parent
assert.match(boundary, /for \(\$attempt = 0; \$attempt -lt 20; \$attempt\+\+\)[\s\S]*Get-StrictProcessRecord -ProcessId \$targetPid[\s\S]*catch/);
});
-test('watchdog stop terminates only reverified watchdog and direct daemon PIDs', () => {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-watchdog-stop-'));
- const preload = path.join(tempDir, 'preload.js');
- const callsFile = path.join(tempDir, 'calls.jsonl');
- const watchdogPid = 424201;
- const daemonPid = 424202;
- fs.writeFileSync(path.join(tempDir, 'watchdog.pid'), String(watchdogPid));
- fs.writeFileSync(preload, `
- const cp = require('node:child_process');
- const fs = require('node:fs');
- const node = ${JSON.stringify(process.execPath)};
- const watchdog = ${JSON.stringify(path.join(scriptsDir, 'watchdog.js'))};
- const daemon = ${JSON.stringify(path.join(scriptsDir, 'daemon.js'))};
- const callsFile = ${JSON.stringify(callsFile)};
- const alive = new Set(process.env.TEST_NO_DAEMON === '1' ? [${watchdogPid}] : [${watchdogPid}, ${daemonPid}]);
- const owner = 'DESKTOP\\alice';
- const rows = {
- ${watchdogPid}: { ProcessId: ${watchdogPid}, ParentProcessId: 100, Name: 'node.exe', ExecutablePath: node, CommandLine: '"' + node + '" --experimental-sqlite "' + watchdog + '"', ArgumentsSource: 'CommandLineToArgvW', Arguments: [node, '--experimental-sqlite', watchdog], Owner: owner, OwnerIsCurrent: process.env.TEST_FOREIGN_OWNER !== '1' },
- ${daemonPid}: { ProcessId: ${daemonPid}, ParentProcessId: ${watchdogPid}, Name: 'node.exe', ExecutablePath: node, CommandLine: '"' + node + '" --experimental-sqlite "' + daemon + '"', ArgumentsSource: 'CommandLineToArgvW', Arguments: [node, '--experimental-sqlite', daemon], Owner: owner, OwnerIsCurrent: process.env.TEST_FOREIGN_OWNER !== '1' },
- };
- cp.spawn = () => { throw new Error('unexpected daemon spawn'); };
- cp.spawnSync = (command, args) => {
- if (command === 'powershell') {
- const script = String(args[args.length - 1]);
- if (script.includes('WindowsBuiltInRole')) return { status: 0, stdout: 'False\\r\\n', stderr: '' };
- let selected = [];
- if (script.includes('ParentProcessId -eq ${watchdogPid}')) {
- selected = [rows[${watchdogPid}], rows[${daemonPid}]].filter((row) => alive.has(row.ProcessId));
- } else {
- const match = script.match(/ProcessId -eq (\\d+)/);
- if (match && alive.has(Number(match[1]))) selected = [rows[Number(match[1])]];
- }
- return { status: 0, stdout: selected.length ? JSON.stringify(selected.length === 1 ? selected[0] : selected) : '', stderr: '' };
- }
- if (command === 'taskkill') {
- fs.appendFileSync(callsFile, JSON.stringify(args) + '\\n');
- const pid = Number(args[args.indexOf('/PID') + 1]);
- alive.delete(pid);
- return { status: 0, stdout: '', stderr: '' };
- }
- throw new Error('unexpected command: ' + command);
- };
- `);
- try {
- const result = spawnSync(process.execPath, ['--require', preload, path.join(scriptsDir, 'watchdog.js'), 'stop'], {
- encoding: 'utf8',
- env: { ...process.env, WBSWITCH_DATA_DIR: tempDir },
- timeout: 10000,
- });
- assert.equal(result.status, 0, result.stderr);
- assert.equal(fs.existsSync(path.join(tempDir, 'watchdog.pid')), false);
- const calls = fs.readFileSync(callsFile, 'utf8').trim().split(/\r?\n/).map(JSON.parse);
- assert.deepEqual(calls, [
- ['/F', '/PID', String(watchdogPid)],
- ['/F', '/PID', String(daemonPid)],
- ]);
-
- fs.writeFileSync(path.join(tempDir, 'watchdog.pid'), String(watchdogPid));
- fs.writeFileSync(callsFile, '');
- const crashWindow = spawnSync(process.execPath, ['--require', preload, path.join(scriptsDir, 'watchdog.js'), 'stop'], {
- encoding: 'utf8',
- env: { ...process.env, WBSWITCH_DATA_DIR: tempDir, TEST_NO_DAEMON: '1' },
- timeout: 10000,
- });
- assert.equal(crashWindow.status, 0, crashWindow.stderr);
- assert.equal(fs.existsSync(path.join(tempDir, 'watchdog.pid')), false);
- assert.deepEqual(
- fs.readFileSync(callsFile, 'utf8').trim().split(/\r?\n/).map(JSON.parse),
- [['/F', '/PID', String(watchdogPid)]]
- );
-
- fs.writeFileSync(path.join(tempDir, 'watchdog.pid'), String(watchdogPid));
- fs.writeFileSync(callsFile, '');
- const foreignOwner = spawnSync(process.execPath, ['--require', preload, path.join(scriptsDir, 'watchdog.js'), 'stop'], {
- encoding: 'utf8',
- env: { ...process.env, WBSWITCH_DATA_DIR: tempDir, TEST_FOREIGN_OWNER: '1' },
- timeout: 10000,
- });
- assert.notEqual(foreignOwner.status, 0);
- assert.match(foreignOwner.stderr, /owner|current user|所有者|当前用户/i);
- assert.equal(fs.readFileSync(path.join(tempDir, 'watchdog.pid'), 'utf8'), String(watchdogPid));
- assert.equal(fs.readFileSync(callsFile, 'utf8'), '');
- } finally {
- fs.rmSync(tempDir, { recursive: true, force: true });
- }
+test('watchdog uses an OS-managed profile lock and no process scanner', () => {
+ assert.match(watchdogSource, /const LOCK_PORT = PROFILE\.id === 'workbuddy-ai' \? 47933 : 47932/);
+ assert.match(watchdogSource, /const lockServer = net\.createServer\(\)/);
+ assert.match(watchdogSource, /lockServer\.listen\(\{ host: '127\.0\.0\.1', port: LOCK_PORT, exclusive: true \}/);
+ assert.match(watchdogSource, /error\.code === 'EADDRINUSE'/);
+ assert.doesNotMatch(watchdogSource, /spawnSync|powershell|Get-CimInstance|taskkill/i);
});
-test('watchdog startup repairs a missing PID file for one exact instance', () => {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-watchdog-untracked-'));
- const preload = path.join(tempDir, 'preload.js');
- const untrackedPid = 424203;
- fs.writeFileSync(preload, `
- const cp = require('node:child_process');
- const node = ${JSON.stringify(process.execPath)};
- const watchdog = ${JSON.stringify(path.join(scriptsDir, 'watchdog.js'))};
- cp.spawn = () => { throw new Error('duplicate watchdog reached daemon spawn'); };
- cp.spawnSync = (command, args) => {
- if (command !== 'powershell') throw new Error('unexpected command: ' + command);
- const script = String(args[args.length - 1]);
- if (script.includes('WindowsBuiltInRole')) return { status: 0, stdout: 'False\\r\\n', stderr: '' };
- if (script.includes("Name -eq 'node.exe'")) {
- return { status: 0, stderr: '', stdout: JSON.stringify({
- ProcessId: ${untrackedPid}, ParentProcessId: 100, Name: 'node.exe', ExecutablePath: node,
- CommandLine: '"' + node + '" --experimental-sqlite "' + watchdog + '"',
- ArgumentsSource: 'CommandLineToArgvW', Arguments: [node, '--experimental-sqlite', watchdog],
- Owner: 'DESKTOP\\alice', OwnerIsCurrent: true,
- }) };
- }
- return { status: 0, stdout: '', stderr: '' };
- };
- `);
- try {
- const result = spawnSync(process.execPath, ['--require', preload, path.join(scriptsDir, 'watchdog.js')], {
- encoding: 'utf8',
- env: { ...process.env, WBSWITCH_DATA_DIR: tempDir },
- timeout: 10000,
- });
- assert.equal(result.status, 0);
- assert.match(result.stdout, /恢复缺失的 watchdog\.pid|本实例退出/i);
- assert.equal(fs.readFileSync(path.join(tempDir, 'watchdog.pid'), 'utf8'), String(untrackedPid));
- } finally {
- fs.rmSync(tempDir, { recursive: true, force: true });
- }
+test('native lifecycle stop validates the bundled node path before termination', () => {
+ const expectedNode = nativeSource.indexOf('expectedNode := filepath.Join(appDir, "scripts", "runtime", "node", "node.exe")');
+ const identityCheck = nativeSource.indexOf('if !samePath(actual, expectedPath)');
+ const terminate = nativeSource.indexOf('procTerminateProcess.Call', identityCheck);
+ const lifecycleCall = nativeSource.indexOf('terminateExactNode(candidate.pid, expectedNode)', expectedNode);
+ assert.ok(expectedNode >= 0, 'native helper must derive the bundled node path from the target app');
+ assert.ok(identityCheck >= 0, 'process path must be checked against the bundled node path');
+ assert.ok(terminate > identityCheck, 'termination must happen only after the exact path check');
+ assert.ok(lifecycleCall > expectedNode, 'lifecycle stop must pass the derived path into the terminating helper');
+ assert.match(nativeSource, /func terminateWorkBuddy\(profile string\)/);
+ assert.match(nativeSource, /if len\(paths\) != 1/);
+ assert.match(nativeSource, /--terminate-workbuddy/);
+ assert.match(nativeSource, /exitAccessDenied/);
+ assert.match(nativeSource, /exitIdentityMismatch/);
+ assert.match(nativeSource, /if elevated \{[\s\S]*return true, exitAccessDenied/);
});
test('packaged scripts contain no WorkBuddy image-name kill or stale elevation helper', () => {
diff --git a/test/windows-release-script.test.js b/test/windows-release-script.test.js
index f26af1d..5437104 100644
--- a/test/windows-release-script.test.js
+++ b/test/windows-release-script.test.js
@@ -44,13 +44,13 @@ test('Windows standard relaunch falls back to the Explorer Shell object by execu
assert.doesNotMatch(relaunch, /Get-Process\s+-Name\s+explorer/);
});
-test('Windows watchdog only pauses for a live or recent update marker', () => {
+test('Windows watchdog uses an OS-managed profile lock and keeps restart backoff', () => {
const watchdog = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'watchdog.js'), 'utf8');
- assert.match(watchdog, /updateProcessIsActive/);
- assert.match(watchdog, /apply-update\\\\\.ps1/);
- assert.match(watchdog, /gracePeriodMs\s*=\s*10 \* 60 \* 1000/);
- assert.match(watchdog, /unlinkSync\(UPDATE_PENDING_FILE\)/);
- assert.match(watchdog, /if \(updatePendingIsActive\(\)\)/);
+ assert.match(watchdog, /net\.createServer\(\)/);
+ assert.match(watchdog, /const LOCK_PORT = PROFILE\.id === 'workbuddy-ai' \? 47933 : 47932/);
+ assert.match(watchdog, /exclusive:\s*true/);
+ assert.match(watchdog, /restartDelay = Math\.min\(restartDelay \* 2, 60000\)/);
+ assert.doesNotMatch(watchdog, /pending\.json|updateProcessIsActive|powershell|Get-CimInstance|taskkill/i);
});
test('Windows installer excludes the repair prompt from all release stages', () => {
diff --git a/test/workbuddy-compat.test.js b/test/workbuddy-compat.test.js
new file mode 100644
index 0000000..ecc4959
--- /dev/null
+++ b/test/workbuddy-compat.test.js
@@ -0,0 +1,88 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+
+const compat = require('../scripts/workbuddy-compat.js');
+
+function visibleElement(className) {
+ return {
+ className: className || '',
+ children: [],
+ getBoundingClientRect() { return { width: 120, height: 32, left: 20 }; },
+ };
+}
+
+test('composer toolbar selection prefers the modern DOM and falls back to legacy DOM', () => {
+ const modern = visibleElement('cr-input-toolbar__right');
+ const legacy = visibleElement('_item_hash _gapLarge_hash');
+ const modernDocument = {
+ querySelector(selector) { return selector === 'div.cr-input-toolbar__right' ? modern : null; },
+ querySelectorAll() { return [legacy]; },
+ };
+ assert.deepEqual(compat.findComposerToolbar(modernDocument), { kind: 'modern', element: modern });
+
+ const legacyDocument = {
+ querySelector() { return null; },
+ querySelectorAll() { return [legacy]; },
+ };
+ assert.deepEqual(compat.findComposerToolbar(legacyDocument), { kind: 'legacy', element: legacy });
+});
+
+test('queue adapter selection prefers prototype-capable modern adapter and retains legacy fallback', () => {
+ const modernAdapter = Object.create({
+ enqueueConversationMessageQueueItem() {},
+ pauseConversationMessageQueue() {},
+ });
+ const modernRoot = visibleElement();
+ modernRoot.__reactFiber$test = { memoizedProps: { adapter: modernAdapter }, return: null };
+ const modernDocument = {
+ querySelector(selector) { return selector === '#root > div' ? modernRoot : null; },
+ };
+ assert.deepEqual(compat.findQueueAdapter(modernDocument), { kind: 'modern', adapter: modernAdapter });
+
+ const legacyAdapter = {
+ enqueueConversationMessageQueueItem() {},
+ pauseConversationMessageQueue() {},
+ };
+ const legacyRoot = visibleElement();
+ legacyRoot.__reactFiber$test = { memoizedProps: { value: legacyAdapter }, return: null };
+ const legacyDocument = {
+ querySelector(selector) { return selector === '.voice-mic-wrap' ? legacyRoot : null; },
+ };
+ assert.deepEqual(compat.findQueueAdapter(legacyDocument), { kind: 'legacy', adapter: legacyAdapter });
+});
+
+test('selected conversation lookup is capability based rather than profile based', () => {
+ const selected = {
+ className: 'conversation-item',
+ firstElementChild: { className: '_card_hash _selected_hash' },
+ getAttribute(name) { return name === 'data-conversation-id' ? 'conversation-modern' : null; },
+ };
+ const documentLike = {
+ querySelectorAll(selector) {
+ return selector === '.conversation-item[data-conversation-id]' ? [selected] : [];
+ },
+ querySelector() { return null; },
+ };
+ assert.equal(compat.getSelectedConversationId(documentLike), 'conversation-modern');
+});
+
+test('injected compatibility is packaged and AI theme access is no longer profile-gated', () => {
+ const root = path.join(__dirname, '..');
+ const daemon = fs.readFileSync(path.join(root, 'scripts', 'daemon.js'), 'utf8');
+ const inject = fs.readFileSync(path.join(root, 'scripts', 'inject.js'), 'utf8');
+ const macBuild = fs.readFileSync(path.join(root, 'scripts', 'build-mac-dmg.sh'), 'utf8');
+ const winVerify = fs.readFileSync(path.join(root, 'scripts', 'verify-win.cmd'), 'utf8');
+
+ assert.match(daemon, /workbuddy-compat\.js/);
+ assert.match(macBuild, /workbuddy-compat\.js/);
+ assert.match(winVerify, /workbuddy-compat\.js/);
+ assert.match(inject, /WBS_COMPAT\.findComposerToolbar\(document\)/);
+ assert.match(inject, /WBS_COMPAT\.findQueueAdapter\(document\)/);
+ assert.match(inject, /if \(!CAPS\.theme\)/);
+ assert.doesNotMatch(inject, /if \(!CAPS\.theme \|\| WBS_PROFILE_IS_AI\)/);
+ assert.doesNotMatch(inject, /migrateWorkBuddyAiThemeOnce/);
+});