Skip to content

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

feat: publish WorkDaddy 1.1.5 feature release

[email protected]1234b174987f
diff --git a/README.md b/README.md
index b71e540..c7ba701 100644
--- a/README.md
+++ b/README.md
@@ -70,6 +70,12 @@
2. 双击安装器完成安装
3. 双击打开 `WorkDaddy` 或 `WorkDaddy AI` 桌面快捷方式
+#### 企业专享版 / VPC 客户端
+
+企业专享版用户仍安装与界面最接近的 `WorkDaddy` 或 `WorkDaddy AI`。安装程序会先自动识别对应的官方客户端,并在安装向导中显示路径和版本;企业版用户点击「浏览」改选自己的 `.exe` 主程序即可,不需要修改配置文件或设置系统环境变量。
+
+选择结果保存在 WorkDaddy 的个人数据目录中。更新安装默认保留上次选择,也可以在安装向导中修改;需要改回官方客户端时,重新运行安装程序并选择自动识别出的官方 `.exe`。WorkDaddy 会锁定所选客户端版本,客户端升级或移动后同样通过安装程序重新确认。
+
### 从源码运行(开发者)
diff --git a/release/WorkDaddy.ico b/release/WorkDaddy.ico
index e5e6e0a..dd1ccd3 100644
Binary files a/release/WorkDaddy.ico and b/release/WorkDaddy.ico differ
diff --git a/release/macos/WorkDaddy-1.1.29.dmg b/release/macos/WorkDaddy-1.1.29.dmg
new file mode 100644
index 0000000..270ea1a
Binary files /dev/null and b/release/macos/WorkDaddy-1.1.29.dmg differ
diff --git a/release/macos/WorkDaddy-1.1.5.dmg b/release/macos/WorkDaddy-1.1.5.dmg
new file mode 100644
index 0000000..da916d1
Binary files /dev/null and b/release/macos/WorkDaddy-1.1.5.dmg differ
diff --git a/release/macos/WorkDaddy-AI-1.1.4.dmg b/release/macos/WorkDaddy-AI-1.1.29.dmg
similarity index 73%
rename from release/macos/WorkDaddy-AI-1.1.4.dmg
rename to release/macos/WorkDaddy-AI-1.1.29.dmg
index 0080cd2..ca95eee 100644
Binary files a/release/macos/WorkDaddy-AI-1.1.4.dmg and b/release/macos/WorkDaddy-AI-1.1.29.dmg differ
diff --git a/release/macos/WorkDaddy-1.1.4.dmg b/release/macos/WorkDaddy-AI-1.1.5.dmg
similarity index 75%
rename from release/macos/WorkDaddy-1.1.4.dmg
rename to release/macos/WorkDaddy-AI-1.1.5.dmg
index 643ec63..d83a612 100644
Binary files a/release/macos/WorkDaddy-1.1.4.dmg and b/release/macos/WorkDaddy-AI-1.1.5.dmg differ
diff --git a/release/windows/WorkDaddy-AI-Setup-1.1.4.exe b/release/windows/WorkDaddy-AI-Setup-1.1.5.exe
similarity index 70%
rename from release/windows/WorkDaddy-AI-Setup-1.1.4.exe
rename to release/windows/WorkDaddy-AI-Setup-1.1.5.exe
index 0e5b639..98b7949 100644
Binary files a/release/windows/WorkDaddy-AI-Setup-1.1.4.exe and b/release/windows/WorkDaddy-AI-Setup-1.1.5.exe differ
diff --git a/release/windows/WorkDaddy-Setup-1.1.4.exe b/release/windows/WorkDaddy-Setup-1.1.5.exe
similarity index 70%
rename from release/windows/WorkDaddy-Setup-1.1.4.exe
rename to release/windows/WorkDaddy-Setup-1.1.5.exe
index a02d81f..b71a303 100644
Binary files a/release/windows/WorkDaddy-Setup-1.1.4.exe and b/release/windows/WorkDaddy-Setup-1.1.5.exe differ
diff --git a/scripts/assets/WorkDaddy.icns b/scripts/assets/WorkDaddy.icns
new file mode 100644
index 0000000..eacde79
Binary files /dev/null and b/scripts/assets/WorkDaddy.icns differ
diff --git a/scripts/assets/macos-dmg-background.svg b/scripts/assets/macos-dmg-background.svg
new file mode 100644
index 0000000..a22b01b
--- /dev/null
+++ b/scripts/assets/macos-dmg-background.svg
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" width="620" height="400" viewBox="0 0 620 400">
+ <rect width="620" height="400" fill="#f6f7f9"/>
+ <path id="install-arrow" fill="#697386" transform="translate(296.5 172.5) scale(0.35)" d="m50.868 78.016l36.418-26.055a2.516 2.516 0 0 0 1.051-2.043v-.006a2.52 2.52 0 0 0-1.059-2.048L50.86 21.977a2.513 2.513 0 0 0-2.612-.183a2.509 2.509 0 0 0-1.361 2.236v12.183l-32.709-.001a2.514 2.514 0 0 0-2.515 2.516l.001 22.541a2.515 2.515 0 0 0 2.516 2.516h32.706v12.187c0 .94.53 1.803 1.366 2.237a2.512 2.512 0 0 0 2.616-.193z"/>
+</svg>
diff --git a/scripts/assets/workdaddy-icon-foreground.png b/scripts/assets/workdaddy-icon-foreground.png
new file mode 100644
index 0000000..544b019
Binary files /dev/null and b/scripts/assets/workdaddy-icon-foreground.png differ
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index bdcd2b3..1d3c597 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -21,6 +21,10 @@ if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
exit 2
fi
APP="WorkDaddy.app"
+DMG_WINDOW_WIDTH=620
+DMG_WINDOW_HEIGHT=400
+DMG_ICON_SIZE=112
+DMG_BACKGROUND_SVG="$DIR/scripts/assets/macos-dmg-background.svg"
PROFILE="${WORKDADDY_BUILD_PROFILE:-}"
if [ -z "$PROFILE" ]; then
for profile in workbuddy-cn workbuddy-ai; do
@@ -41,10 +45,25 @@ echo "==> 产物: ${OUT}"
chmod 755 "$APP/Contents/MacOS/launcher"
echo "==> launcher 可执行位已保证: $(stat -f '%Sp' "$APP/Contents/MacOS/launcher")"
+APP_ICON="$DIR/scripts/assets/WorkDaddy.icns"
+if [ ! -f "$APP_ICON" ]; then
+ echo "错误:缺少应用图标 $APP_ICON" >&2
+ exit 1
+fi
+cp "$APP_ICON" "$APP/Contents/Resources/AppIcon.icns"
+chmod 644 "$APP/Contents/Resources/AppIcon.icns"
+echo "==> 应用图标已同步(背景 #e1e1e1)"
+
# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)
for f in daemon.js session-db.js secure-transfer.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-usage-store.js atomic-file-write.js ui-port.js checkin-result.js lib.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"
done
+if [ -f "scripts/picker-internal.js" ]; then
+ cp "scripts/picker-internal.js" "$APP/Contents/Resources/scripts/picker-internal.js"
+ chmod 644 "$APP/Contents/Resources/scripts/picker-internal.js"
+else
+ rm -f "$APP/Contents/Resources/scripts/picker-internal.js"
+fi
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"
@@ -73,10 +92,31 @@ chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \
"$APP/Contents/Resources/scripts/theme-patches.js"
echo "==> 前端代码已覆盖(权限按壳原样)"
-# 3) 打包:staging 放 WorkDaddy.app + Applications 软链(与 1.0.3 dmg 同构)
+# 3) 打包:staging 放 WorkDaddy.app + Applications 软链,并写入固定 Finder 布局。
STAGE="$(mktemp -d)"
+DMG_TEMP_DIR="$(mktemp -d)"
+RW_DMG="$DMG_TEMP_DIR/${PACKAGE_APP_NAME}-rw.dmg"
+ATTACH_PLIST="$DMG_TEMP_DIR/attach.plist"
+MOUNT_DIR=""
+DMG_DEVICE=""
+cleanup_dmg_build() {
+ if [ -n "$DMG_DEVICE" ]; then
+ hdiutil detach "$DMG_DEVICE" -force >/dev/null 2>&1 || true
+ fi
+ rm -rf -- "$STAGE" "$DMG_TEMP_DIR"
+}
+trap cleanup_dmg_build EXIT
+
PACKAGE_APP="$STAGE/${PACKAGE_APP_NAME}.app"
cp -R "$APP" "$PACKAGE_APP"
+# Modern macOS uses CFBundleIconName when resolving an ICNS application icon.
+# Keep it aligned with CFBundleIconFile so LaunchServices does not wrap the
+# custom artwork in the generic gray application icon.
+if /usr/libexec/PlistBuddy -c 'Print :CFBundleIconName' "$PACKAGE_APP/Contents/Info.plist" >/dev/null 2>&1; then
+ /usr/libexec/PlistBuddy -c 'Set :CFBundleIconName AppIcon' "$PACKAGE_APP/Contents/Info.plist"
+else
+ /usr/libexec/PlistBuddy -c 'Add :CFBundleIconName string AppIcon' "$PACKAGE_APP/Contents/Info.plist"
+fi
sed -i.bak "s|^PROFILE=.*|PROFILE=\"${PROFILE}\"|" "$PACKAGE_APP/Contents/MacOS/launcher"
rm -f "$PACKAGE_APP/Contents/MacOS/launcher.bak"
# 启动器只能复用当前 profile 的 WorkBuddy CDP;否则 CN 包会把 WorkBuddy AI 的端口
@@ -157,10 +197,129 @@ if [ -f "$PACKAGE_APP/Contents/Resources/scripts/package.json" ]; then
"$PACKAGE_APP/Contents/Resources/scripts/package.json"
fi
ln -s /Applications "$STAGE/Applications"
+
+# Finder 不直接显示 SVG 背景;保留 SVG 作为矢量母版,打包时用系统 sips
+# 渲染 1x/2x 位图并合成 HiDPI TIFF,避免 Retina 屏幕放大单分辨率背景。
+if [ ! -f "$DMG_BACKGROUND_SVG" ]; then
+ echo "错误:缺少 DMG 背景矢量资源 $DMG_BACKGROUND_SVG" >&2
+ exit 1
+fi
+mkdir -p "$STAGE/.background"
+BACKGROUND_1X="$STAGE/.background/background-1x.png"
+BACKGROUND_2X="$STAGE/.background/background-2x.png"
+RENDERED_BACKGROUND="$STAGE/.background/background.tiff"
+sips -s format png "$DMG_BACKGROUND_SVG" --out "$BACKGROUND_1X" >/dev/null
+sips -s format png -z 800 1240 "$DMG_BACKGROUND_SVG" --out "$BACKGROUND_2X" >/dev/null
+BACKGROUND_1X_WIDTH="$(sips -g pixelWidth "$BACKGROUND_1X" | awk '/pixelWidth:/ { print $2 }')"
+BACKGROUND_1X_HEIGHT="$(sips -g pixelHeight "$BACKGROUND_1X" | awk '/pixelHeight:/ { print $2 }')"
+BACKGROUND_2X_WIDTH="$(sips -g pixelWidth "$BACKGROUND_2X" | awk '/pixelWidth:/ { print $2 }')"
+BACKGROUND_2X_HEIGHT="$(sips -g pixelHeight "$BACKGROUND_2X" | awk '/pixelHeight:/ { print $2 }')"
+if [ "$BACKGROUND_1X_WIDTH" != "$DMG_WINDOW_WIDTH" ] || [ "$BACKGROUND_1X_HEIGHT" != "$DMG_WINDOW_HEIGHT" ]; then
+ echo "错误:DMG 1x 背景尺寸必须为 ${DMG_WINDOW_WIDTH}x${DMG_WINDOW_HEIGHT},实际为 ${BACKGROUND_1X_WIDTH}x${BACKGROUND_1X_HEIGHT}" >&2
+ exit 1
+fi
+if [ "$BACKGROUND_2X_WIDTH" != "$((DMG_WINDOW_WIDTH * 2))" ] || [ "$BACKGROUND_2X_HEIGHT" != "$((DMG_WINDOW_HEIGHT * 2))" ]; then
+ echo "错误:DMG 2x 背景尺寸必须为 $((DMG_WINDOW_WIDTH * 2))x$((DMG_WINDOW_HEIGHT * 2)),实际为 ${BACKGROUND_2X_WIDTH}x${BACKGROUND_2X_HEIGHT}" >&2
+ exit 1
+fi
+tiffutil -cathidpicheck "$BACKGROUND_1X" "$BACKGROUND_2X" -out "$RENDERED_BACKGROUND" >/dev/null
+
+# 先创建可写镜像,让 Finder 把窗口尺寸、图标位置和背景写进卷根目录的
+# .DS_Store;布局完成后再转成只读压缩镜像。
+hdiutil create -volname "$PACKAGE_APP_NAME" -srcfolder "$STAGE" -ov -format UDRW "$RW_DMG" >/dev/null
+hdiutil attach -readwrite -noverify -noautoopen -plist "$RW_DMG" > "$ATTACH_PLIST"
+read -r DMG_DEVICE MOUNT_DIR < <(python3 - "$ATTACH_PLIST" <<'PY'
+import plistlib
+import sys
+
+with open(sys.argv[1], 'rb') as f:
+ attached = plistlib.load(f)
+for entity in attached.get('system-entities', []):
+ mount_point = entity.get('mount-point')
+ device = entity.get('dev-entry')
+ if mount_point and device:
+ print(device, mount_point)
+ break
+PY
+)
+if [ -z "$DMG_DEVICE" ] || [ -z "$MOUNT_DIR" ]; then
+ echo "错误:无法识别可写 DMG 的挂载设备或目录" >&2
+ exit 1
+fi
+
+VOLUME_NAME="$(basename "$MOUNT_DIR")"
+sleep 2
+osascript - "$VOLUME_NAME" "${PACKAGE_APP_NAME}.app" "$DMG_WINDOW_WIDTH" "$DMG_WINDOW_HEIGHT" "$DMG_ICON_SIZE" <<'APPLESCRIPT'
+on run argv
+ set volumeName to item 1 of argv
+ set appName to item 2 of argv
+ set dmgWindowWidth to item 3 of argv as integer
+ set dmgWindowHeight to item 4 of argv as integer
+ set dmgIconSize to item 5 of argv as integer
+ set windowLeft to 200
+ set windowTop to 120
+ set windowRight to windowLeft + dmgWindowWidth
+ set windowBottom to windowTop + dmgWindowHeight
+
+ tell application "Finder"
+ tell disk (volumeName as string)
+ open
+ tell container window
+ set current view to icon view
+ set toolbar visible to false
+ set statusbar visible to false
+ set bounds to {windowLeft, windowTop, windowRight, windowBottom}
+ set position of every item to {windowRight + 100, 100}
+ end tell
+
+ set viewOptions to icon view options of container window
+ set arrangement of viewOptions to not arranged
+ set icon size of viewOptions to dmgIconSize
+ set text size of viewOptions to 13
+ set label position of viewOptions to bottom
+ set shows item info of viewOptions to false
+ set shows icon preview of viewOptions to true
+ set background picture of viewOptions to file ".background:background.tiff"
+
+ set position of item appName to {150, 190}
+ set position of item "Applications" to {470, 190}
+ close
+ open
+ delay 1
+ tell container window
+ set statusbar visible to false
+ set bounds to {windowLeft, windowTop, windowRight - 10, windowBottom - 10}
+ end tell
+ end tell
+
+ delay 1
+ tell disk (volumeName as string)
+ tell container window
+ set statusbar visible to false
+ set bounds to {windowLeft, windowTop, windowRight, windowBottom}
+ end tell
+ end tell
+ delay 2
+ end tell
+end run
+APPLESCRIPT
+
+sync
+for _ in {1..20}; do
+ test -f "$MOUNT_DIR/.DS_Store" && break
+ sleep 0.25
+done
+if ! test -f "$MOUNT_DIR/.DS_Store"; then
+ echo "错误:Finder 未能把 DMG 窗口布局写入 .DS_Store" >&2
+ exit 1
+fi
+rm -rf -- "$MOUNT_DIR/.fseventsd"
+hdiutil detach "$DMG_DEVICE" >/dev/null
+DMG_DEVICE=""
rm -f "$OUT"
-hdiutil create -volname "$PACKAGE_APP_NAME" -srcfolder "$STAGE" -ov -format UDZO -imagekey zlib-level=9 "$OUT" >/dev/null
-rm -rf "$STAGE"
+hdiutil convert "$RW_DMG" -ov -format UDZO -imagekey zlib-level=9 -o "$OUT" >/dev/null
echo "==> 完成: $(ls -lh "$OUT" | awk '{print $5}')"
echo " 校验: hdiutil attach -nobrowse -readonly '$OUT' 后检查"
+echo " Finder 窗口必须为 ${DMG_WINDOW_WIDTH}x${DMG_WINDOW_HEIGHT},左右图标间显示箭头"
echo " launcher 权限必须为 rwxr-xr-x、daemon.js 版本为 ${VERSION}"
diff --git a/scripts/cdp-targets.js b/scripts/cdp-targets.js
index 2a56d91..a9cf153 100644
--- a/scripts/cdp-targets.js
+++ b/scripts/cdp-targets.js
@@ -79,6 +79,19 @@ function isTargetForProfile(target, profile) {
const desc = String(target.description || '');
const haystack = `${url} ${title} ${desc}`;
+ // 企业专享版沿用 CN/AI 的 UI 能力,但应用路径和登录域均由用户选择后生成。
+ // 企业模式只接受它自己的精确信号,不再回落到官方域名或通用标题。
+ if (profile.customTarget) {
+ const signals = [];
+ try { if (profile.apiHost) signals.push(new URL(profile.apiHost).hostname.toLowerCase()); } catch (_) {}
+ for (const hint of profile.targetHints || []) {
+ const value = String(hint || '').trim().toLowerCase();
+ if (value.length >= 4) signals.push(value);
+ }
+ const lower = haystack.toLowerCase();
+ return signals.some((signal) => lower.includes(signal));
+ }
+
// 强信号:页面明确属于某客户端 → 必须与当前 profile 一致,否则一律拒绝
const cls = classifyTarget(url, title, desc);
if (cls) return cls === profile.id;
@@ -99,4 +112,4 @@ function isTargetForProfile(target, profile) {
return false;
}
-module.exports = { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile };
\ No newline at end of file
+module.exports = { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile };
diff --git a/scripts/daemon.js b/scripts/daemon.js
index e66f90d..4fa9d94 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -78,6 +78,8 @@ const {
setAutoCopyRule,
getAutoCopySession,
getAutoCopySessionMembers,
+ getAutoCopySessionMemberRecords,
+ selectLatestAutoCopyMember,
ensureAutoCopySession,
addAutoCopySessionMember,
moveAutoCopySession,
@@ -230,8 +232,11 @@ const DATA_DIR = defaultDataDir();
// 1.1.25:内置官方壁纸更新时刷新数据目录旧副本;新 profile 默认启用 WorkDaddy 壁纸主题。
// 1.1.26:daemon 启动 30 秒后补签,并将全账号签到兜底周期缩短为 1 小时。
// 1.1.27:修复 Windows 原生启动路径发现、旧托管 Node 升级和首次会话播种失败;补充脱敏启动诊断与匿名安装 ID。
-const DAEMON_VERSION = '1.1.27';
-const DAEMON_BUILD_ID = 'release-1.1.27-20260831-windows-sentry-diagnostics';
+// 1.1.28:Windows 安装向导支持选择并锁定 WorkBuddy 客户端,企业版使用进程级环境变量 CDP。
+// 1.1.28:修复首次会话播种的 profile 目录缺失,以及 native lifecycle helper 误计自身进程。
+// 1.1.29:自动复制会话按 lineage 内最新消息文件做双向全成员同步,避免跨账号往返后历史分叉。
+const DAEMON_VERSION = '1.1.29';
+const DAEMON_BUILD_ID = 'release-1.1.29-20260831-merged-release';
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
@@ -243,7 +248,7 @@ let ACTUAL_PORT = UI_PORT_BASE; // 实际监听端口(可能回退到当前 pr
const PROFILE_CDP_PORT = { 'workbuddy-cn': 9222, 'workbuddy-ai': 9223, 'codebuddy-cn': 9224, 'codebuddy-intl': 9225 };
const CDP_PORT_HINT = process.env.WBSWITCH_CDP_PORT
? parseInt(process.env.WBSWITCH_CDP_PORT, 10)
- : (PROFILE_CDP_PORT[PROFILE.id] || null);
+ : (Number(PROFILE.cdp && PROFILE.cdp.port) || PROFILE_CDP_PORT[PROFILE.id] || null);
const CDP_PORT_FILE = path.join(DATA_DIR, 'cdp-port.json');
const UI_PORT_FILE = path.join(DATA_DIR, 'ui-port.json');
const API_TOKEN_FILE = path.join(DATA_DIR, '.api-token');
@@ -1730,10 +1735,10 @@ const WORKBUDDY_APP_NAME = path.basename(WORKBUDDY_APP).replace(/\.app$/i, '');
// Windows:解析 WorkBuddy 可执行文件真实路径(安装盘可自定义,必须动态查)
// 优先级:WBSWITCH_WORKBUDDY_BIN > 运行进程 Path > 注册表卸载项 > 常见路径
let wbBinaryCache = null;
-const PROFILE_BINARY_NAMES = new Set(
- PROFILE.id === 'workbuddy-ai' ? ['workbuddyai.exe'] :
- PROFILE.id === 'workbuddy-cn' ? ['workbuddy.exe'] : ['codebuddy.exe']
-);
+const PROFILE_BINARY_NAMES = new Set((
+ PROFILE.binaryNames || (PROFILE.id === 'workbuddy-ai' ? ['workbuddyai.exe'] :
+ PROFILE.id === 'workbuddy-cn' ? ['workbuddy.exe'] : ['codebuddy.exe'])
+).map((name) => String(name).toLowerCase()));
function queryWindowsWorkBuddyProcesses() {
const names = [...PROFILE_BINARY_NAMES].map((name) => `\"${name}\"`).join(',');
const helper = path.join(__dirname, 'windows-process-boundary.ps1');
@@ -1782,7 +1787,9 @@ function resolveWorkBuddyBinary() {
return (wbBinaryCache = envBin);
}
if (configuredBin) {
- if (runningBin && !sameWindowsPath(runningBin, configuredBin)) {
+ const sameConfiguredInstall = runningBin && PROFILE_BINARY_NAMES.has(path.win32.basename(runningBin).toLowerCase()) &&
+ sameWindowsPath(path.win32.dirname(runningBin), path.win32.dirname(configuredBin));
+ if (runningBin && !sameConfiguredInstall) {
throw new Error('检测到当前 profile 正从另一安装目录运行,登录信息未修改');
}
return (wbBinaryCache = configuredBin);
@@ -1914,7 +1921,9 @@ async function restoreWorkBuddyWindow(pid) {
function verifiedWindowsWorkBuddyProcesses(binary) {
if (!binary) throw new Error('未找到 WorkBuddy 可执行文件,无法验证运行中的进程');
const processes = queryWindowsWorkBuddyProcesses();
- const verified = filterVerifiedWindowsProcesses(binary, processes);
+ const verified = filterVerifiedWindowsProcesses(
+ binary, processes, fs.realpathSync.native, PROFILE.customTarget ? PROFILE_BINARY_NAMES : null
+ );
if (processes.length !== verified.length) {
throw new Error('存在当前 profile 进程,但没有进程属于已验证安装目录;登录信息未修改');
}
@@ -2022,8 +2031,12 @@ function relaunchWorkBuddy() {
if (IS_WIN) {
const bin = resolveWorkBuddyBinary();
if (!bin) throw new Error('未找到 WorkBuddy.exe(可用环境变量 WBSWITCH_WORKBUDDY_BIN 指定)');
- log(`[logout] 以 --remote-debugging-port=${port} 重启 WorkBuddy: ${bin}`);
- const child = spawn(bin, [`--remote-debugging-port=${port}`], { detached: true, stdio: 'ignore', windowsHide: true });
+ const environmentMode = !!(PROFILE.cdp && PROFILE.cdp.mode === 'environment');
+ log(`[logout] 以 ${environmentMode ? '环境变量' : '命令行参数'} CDP=${port} 重启 WorkBuddy: ${bin}`);
+ const child = spawn(bin, environmentMode ? [] : [`--remote-debugging-port=${port}`], {
+ detached: true, stdio: 'ignore', windowsHide: true,
+ env: environmentMode ? { ...process.env, WORKBUDDY_REMOTE_DEBUGGING_PORT: String(port) } : process.env,
+ });
await new Promise((resolve, reject) => {
child.once('error', reject);
child.once('spawn', resolve);
@@ -2756,6 +2769,87 @@ function copySessionFiles(wbHome, oldId, newId) {
return result;
}
+function sessionContentMtime(wbHome, sessionId) {
+ const id = String(sessionId || '').trim();
+ if (!id) return 0;
+ let latest = 0;
+ const visit = (target) => {
+ let stat;
+ try { stat = fs.lstatSync(target); } catch (_) { return; }
+ if (stat.isSymbolicLink()) return;
+ if (stat.isFile()) { latest = Math.max(latest, Number(stat.mtimeMs || 0)); return; }
+ if (!stat.isDirectory()) return;
+ let entries;
+ try { entries = fs.readdirSync(target, { withFileTypes: true }); } catch (_) { return; }
+ for (const entry of entries) {
+ if (entry.isSymbolicLink()) continue;
+ visit(path.join(target, entry.name));
+ }
+ };
+ const projects = path.join(wbHome, 'projects');
+ try {
+ for (const entry of fs.readdirSync(projects, { withFileTypes: true })) {
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
+ visit(path.join(projects, entry.name, id + '.jsonl'));
+ visit(path.join(projects, entry.name, id));
+ }
+ } catch (_) {}
+ for (const target of [
+ path.join(wbHome, 'workspace', 'sessions', id),
+ path.join(wbHome, 'tasks', id),
+ path.join(wbHome, 'file-history', id),
+ path.join(wbHome, 'artifact-index', id + '.json'),
+ ]) visit(target);
+ return latest;
+}
+
+// Reconcile every live member of a shared lineage. A switch can arrive after
+// either account has received new messages, so the active account is not a
+// reliable source of truth; choose the freshest on-disk snapshot first.
+async function syncAutoCopyLineage(lineageId, targetUid) {
+ if (!lineageId || PROFILE.kind !== 'workbuddy') return { members: 0, synced: 0, failedFiles: 0, targetIds: [], targetPresent: false };
+ const records = getAutoCopySessionMemberRecords(DATA_DIR, lineageId);
+ if (!records.length) return { members: 0, synced: 0, failedFiles: 0, targetIds: [], targetPresent: false };
+ const live = [];
+ for (const member of records) {
+ const rows = await sqliteQuery(
+ 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id = ? AND user_id = ? AND deleted_at IS NULL LIMIT 1;',
+ [member.id, member.uid]
+ );
+ if (!rows.length) continue;
+ live.push(Object.assign({}, member, {
+ row: rows[0],
+ contentMtime: sessionContentMtime(PROFILE.dataRoot, member.id),
+ updatedAt: Number(rows[0].updated_at || rows[0].last_activity_at || rows[0].created_at || 0),
+ }));
+ }
+ const targetIds = live.map((member) => member.id);
+ const targetPresent = targetUid === undefined || live.some((member) => member.uid === String(targetUid || '').trim());
+ if (live.length < 2) return { members: live.length, synced: 0, failedFiles: 0, targetIds, targetPresent };
+ const latest = selectLatestAutoCopyMember(live);
+ if (!latest) return { members: live.length, synced: 0, failedFiles: 0, targetIds, targetPresent };
+ const sourceRow = latest.row;
+ let synced = 0;
+ let failedFiles = 0;
+ for (const target of live) {
+ if (target.id === latest.id) continue;
+ const files = copySessionFiles(PROFILE.dataRoot, latest.id, target.id);
+ synced++;
+ failedFiles += files.failed;
+ try {
+ await sqliteRun(
+ 'UPDATE sessions SET title = ?, custom_title = ?, status = ?, updated_at = ?, last_activity_at = ? WHERE id = ? AND user_id = ? AND deleted_at IS NULL;',
+ [sourceRow.title || '', sourceRow.custom_title || '', sourceRow.status || 'Pending',
+ Number(sourceRow.updated_at || Date.now()), Number(sourceRow.last_activity_at || sourceRow.updated_at || Date.now()),
+ target.id, target.uid]
+ );
+ } catch (error) {
+ log(`[sessions-auto-copy] 同步会话元数据失败 ${target.uid}/${target.id}: ${error.message}`);
+ }
+ }
+ return { members: live.length, synced, failedFiles, sourceId: latest.id, targetIds, targetPresent };
+}
+
const MAX_SESSION_EXPORT_BYTES = 256 * 1024 * 1024;
const MAX_SESSION_EXPORT_FILES = 20000;
@@ -3069,7 +3163,16 @@ async function buildAutoCopyPlan(sourceUid, targetUid) {
const workspaceSet = new Set(rules.workspaces.map(canonicalWorkspace));
return rows
.filter((row) => sessionSet.has(String(row.id)) || workspaceSet.has(canonicalWorkspace(row.cwd)))
- .map((row) => Object.assign({}, row, { lineageId: rules.lineages[String(row.id)] || null }));
+ .map((row) => {
+ let lineageId = rules.lineages[String(row.id)] || null;
+ // Workspace rules also represent shared sessions. Give each matching
+ // row a lineage so later switches reuse one target and reconcile its
+ // newest snapshot instead of inserting a duplicate every time.
+ if (!lineageId && workspaceSet.has(canonicalWorkspace(row.cwd))) {
+ lineageId = ensureAutoCopySession(DATA_DIR, source, row.id);
+ }
+ return Object.assign({}, row, { lineageId });
+ });
}
const autoCopyJobs = new Map();
@@ -3142,11 +3245,27 @@ function startAutoCopyJob(sourceUid, targetUid, plan) {
job.total = job.plan.length;
for (const src of job.plan) {
try {
- const result = await copySessionRecord(src, targetUid, {
- sourceUid,
- lineageId: src.lineageId || undefined,
- auto: true,
- });
+ let result;
+ if (src.lineageId) {
+ // If the target already belongs to this lineage, reconcile all
+ // members before/after the switch instead of blindly overwriting it
+ // from the account that happened to be active most recently.
+ const synced = await syncAutoCopyLineage(src.lineageId, targetUid);
+ if (synced.targetPresent) {
+ result = { status: synced.failedFiles ? 'partial' : 'skipped', failedFiles: synced.failedFiles };
+ } else {
+ result = await copySessionRecord(src, targetUid, {
+ sourceUid,
+ lineageId: src.lineageId,
+ auto: true,
+ });
+ const synced = await syncAutoCopyLineage(src.lineageId, targetUid);
+ result.failedFiles = (result.failedFiles || 0) + synced.failedFiles;
+ if (synced.failedFiles) result.status = 'partial';
+ }
+ } else {
+ result = await copySessionRecord(src, targetUid, { sourceUid, auto: true });
+ }
if (result.status === 'skipped') job.skipped++;
else if (result.status === 'partial') job.partial++;
else job.copied++;
@@ -3324,8 +3443,10 @@ function isAllowedApiOrigin(origin) {
if (u.protocol !== 'http:' && u.protocol !== 'https:') return false;
const host = String(u.hostname || '').toLowerCase();
// WorkBuddy 的 renderer 可能是官方网页来源,也可能是 loopback DevTools 页面。
- return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' ||
- host === 'workbuddy.cn' || host.endsWith('.workbuddy.cn') ||
+ const loopback = host === 'localhost' || host === '127.0.0.1' || host === '[::1]';
+ if (loopback) return true;
+ if (PROFILE.customTarget) return !!PROFILE.apiHost && u.origin === PROFILE.apiHost;
+ return host === 'workbuddy.cn' || host.endsWith('.workbuddy.cn') ||
host === 'workbuddy.ai' || host.endsWith('.workbuddy.ai') ||
host === 'codebuddy.cn' || host.endsWith('.codebuddy.cn') ||
host === 'codebuddy.ai' || host.endsWith('.codebuddy.ai');
@@ -3411,6 +3532,7 @@ function readWorkbuddySettings() {
function writeWorkbuddySettings(settings) {
const file = workbuddySettingsPath();
+ fs.mkdirSync(path.dirname(file), { recursive: true });
replaceFileWithRetry(file, JSON.stringify(settings, null, 2) + '\n');
}
diff --git a/scripts/inject.js b/scripts/inject.js
index 99b9c91..41e7d4f 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -152,6 +152,125 @@ function normalizeQueueText(value) {
return parts.join('\n').replace(/\s+/g, ' ').trim();
}
+function parseComposerContentBlock(node) {
+ if (!node || !node.getAttribute) return null;
+ try {
+ var raw = node.getAttribute('data-contentblock') || '';
+ return JSON.parse(raw.indexOf('&quot;') >= 0 ? raw.replace(/&quot;/g, '"') : raw);
+ } catch (e) {
+ return null;
+ }
+}
+
+// Preserve the DOM order of text and inline content blocks. Reading innerText
+// separately from querySelectorAll loses that order when quotes are interleaved.
+function composerBlocksFromTree(editor) {
+ if (!editor || !editor.childNodes) return [];
+
+ function appendText(output, value) {
+ var text = String(value || '').replace(/[\uFEFF\u200B]/g, '');
+ if (!text) return;
+ var last = output[output.length - 1];
+ if (last && last.type === 'text') last.text += text;
+ else output.push({ type: 'text', text: text });
+ }
+
+ function collect(node, output) {
+ if (!node) return;
+ if (node.nodeType === 3) {
+ appendText(output, node.nodeValue || '');
+ return;
+ }
+ if (node.nodeType !== 1) return;
+ if (node.hasAttribute && node.hasAttribute('data-slate-placeholder')) return;
+ if (node.hasAttribute && node.hasAttribute('data-contentblock')) {
+ var item = parseComposerContentBlock(node);
+ if (item && item.type) output.push(item);
+ return;
+ }
+ var children = node.childNodes || [];
+ for (var i = 0; i < children.length; i++) collect(children[i], output);
+ }
+
+ var blocks = [];
+ for (var i = 0; i < editor.childNodes.length; i++) {
+ var part = [];
+ collect(editor.childNodes[i], part);
+ if (!part.length) continue;
+ if (blocks.length) appendText(blocks, '\n');
+ for (var j = 0; j < part.length; j++) {
+ if (part[j].type === 'text') appendText(blocks, part[j].text);
+ else blocks.push(part[j]);
+ }
+ }
+ while (blocks.length && blocks[0].type === 'text' && !blocks[0].text) blocks.shift();
+ while (blocks.length && blocks[blocks.length - 1].type === 'text' && !blocks[blocks.length - 1].text) blocks.pop();
+ return blocks;
+}
+
+function composerTextFromTree(editor) {
+ return composerBlocksFromTree(editor).filter(function (block) {
+ return block && block.type === 'text';
+ }).map(function (block) { return block.text; }).join('');
+}
+
+function selectionQuoteMeta(meta) {
+ if (!meta || meta.selectionQuote !== true) return null;
+ var safe = {};
+ ['displayAsPhrase', 'displayAsContext', 'displayText', 'selectionQuote', 'mentionType',
+ 'selectedText', 'title'].forEach(function (key) {
+ var value = meta[key];
+ if (typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number') safe[key] = value;
+ });
+ return safe;
+}
+
+function contentItemToBlock(it) {
+ if (!it || it.type === 'text') return null;
+ if (it.type === 'image' && it.imageBase64) {
+ return { type: 'image', data: it.imageBase64, mimeType: 'image/png', uri: it.uri || '' };
+ }
+ if (it.type === 'image') {
+ return { type: 'image', data: it.data || '', mimeType: 'image/png', uri: it.uri || '' };
+ }
+ var block = { type: it.type, name: it.name || '附件', uri: it.uri || '', title: it.title || it.name || '附件' };
+ if (it.mimeType) block.mimeType = it.mimeType;
+ var quoteMeta = it.type === 'resource_link' ? selectionQuoteMeta(it._meta) : null;
+ if (quoteMeta) block._meta = quoteMeta;
+ return block;
+}
+
+// Convert captured composer data into clone-safe WorkBuddy queue blocks. Selection
+// quotes keep their serializable metadata so the official editor can restore the tag.
+function contentToBlocks(content) {
+ if (content && Array.isArray(content.orderedBlocks)) {
+ return content.orderedBlocks.map(function (block) {
+ if (block && block.type === 'text') {
+ return { type: 'text', text: block.text || '' };
+ }
+ return contentItemToBlock(block);
+ }).filter(function (block) { return !!block; });
+ }
+ var blocks = [];
+ var text = (content && content.text || '').replace(/[\uFEFF\u200B]+/g, '').trim();
+ if (text) blocks.push({ type: 'text', text: text });
+ (content && content.items || []).forEach(function (it) {
+ try {
+ if (it.type === 'image' && it.imageBase64) {
+ blocks.push({ type: 'image', data: it.imageBase64, mimeType: 'image/png', uri: it.uri || '' });
+ } else if (it.type === 'image') {
+ blocks.push({ type: 'image', data: it.data || '', mimeType: 'image/png', uri: it.uri || '' });
+ } else if (it.type !== 'text') {
+ var block = contentItemToBlock(it);
+ if (block) {
+ blocks.push(block);
+ }
+ }
+ } catch (e) {}
+ });
+ return blocks;
+}
+
// Queue ids are the only authoritative identity. Text is an exact fallback for
// older renderers that did not expose ids; substring matching is deliberately
// forbidden because ordinary prompts commonly contain a stashed prompt.
@@ -180,6 +299,183 @@ function stashContentMatches(expected, current) {
return !!expected && !!current && stashContentSignature(expected) === stashContentSignature(current);
}
+// Pure approval-label/context gate shared by the renderer fallback and tests.
+// Keep this deliberately narrow: a generic "确认" button must never qualify.
+function classifyNoDisturbApprovalCandidate(input) {
+ var value = input || {};
+ var label = String(value.label || '').trim().replace(/^\d+\s*/, '');
+ var kind = null;
+ if (/始终允许|Always\s*allow/i.test(label)) kind = 'session';
+ else if (/^(允许|允许一次|Allow|Yes|同意|批准|确认允许)$/i.test(label) || (/^Yes/i.test(label) && label.length < 24)) kind = 'once';
+ if (!kind || value.disabled || value.ariaDisabled) return null;
+ var context = String(value.context || '').slice(0, 700);
+ if (value.creditSeen || /积分|信用|credit|消耗|付费|支付|费用|金额|余额|扣费/i.test(context)) return null;
+ var keywordHit = /批量删除|沙箱|越界|越权|系统级工具|系统工具|权限|允许访问|将运行|需要你确认|需要你的确认|确认允许|检测到|受保护|敏感|凭据|黑名单|sandbox|approval|permission/i.test(context);
+ var structuredHit = value.hasDeny === true && value.hasOnce === true && Number(value.buttonCount || 0) >= 2 && Number(value.buttonCount || 0) <= 12;
+ return keywordHit || structuredHit ? kind : null;
+}
+
+function isSessionMonitorInProgress(snapshot) {
+ return !!(snapshot && (snapshot.busy || snapshot.blocked || snapshot.hydrating));
+}
+
+var SESSION_MONITOR_ACTIVE_STATUSES = {
+ planning: true, preparing: true, connecting: true, working: true, running: true,
+ tool_start: true, tool_end: true, handoff: true, summarizing: true,
+ waiting_team_members: true, model_requesting: true, model_streaming: true,
+ model_done: true, tool_executing: true, await_input: true, awaitinput: true,
+ waiting_input: true, waiting_user_input: true,
+};
+var SESSION_MONITOR_TERMINAL_STATUSES = {
+ completed: true, cancelled: true, canceled: true, done: true, failed: true,
+ error: true, terminated: true, archived: true, deleted: true, killed: true,
+};
+
+function normalizeSessionMonitorStatus(value) {
+ return typeof value === 'string' ? value.trim().toLowerCase().replace(/[\s-]+/g, '_') : '';
+}
+
+function sessionMonitorLifecycleAction(update, exists) {
+ if (!update || !update.id) return 'ignore';
+ if (update.terminal) return exists ? 'remove' : 'ignore';
+ if (!update.active) return exists ? 'update' : 'ignore';
+ return exists ? 'update' : 'add';
+}
+
+// WorkBuddy's session resource is the authoritative cross-session lifecycle
+// source. Prefer any terminal token across status/protocolStatus/state so a
+// stale working field cannot mask a newer completed protocol status.
+function normalizeSessionMonitorResourceRecord(record, eventName) {
+ var value = record && typeof record === 'object' ? record : {};
+ var id = String(value.id || value.sessionId || value.conversationId || '').trim();
+ if (!id) return null;
+ var tokens = [value.protocolStatus, value.status, value.state].map(normalizeSessionMonitorStatus).filter(Boolean);
+ if (eventName === 'sessionDeleted') tokens.unshift('deleted');
+ var terminalStatus = '';
+ for (var i = 0; i < tokens.length; i++) {
+ if (SESSION_MONITOR_TERMINAL_STATUSES[tokens[i]]) { terminalStatus = tokens[i]; break; }
+ }
+ var status = terminalStatus || tokens[0] || '';
+ var pendingInputKind = normalizeSessionMonitorStatus(value.pendingInputKind);
+ var queueRuntime = value.messageQueueRuntime && typeof value.messageQueueRuntime === 'object' ? value.messageQueueRuntime : null;
+ var queueActive = !!(queueRuntime && queueRuntime.paused !== true &&
+ (queueRuntime.inflightItemId || Number(queueRuntime.pendingItemCount || 0) > 0 ||
+ Number(queueRuntime.sendingItemCount || 0) > 0));
+ var promptActive = typeof value.activePromptStartedAt === 'number' && Number.isFinite(value.activePromptStartedAt);
+ var active = !terminalStatus && (!!SESSION_MONITOR_ACTIVE_STATUSES[status] ||
+ pendingInputKind === 'permission' || pendingInputKind === 'question' || pendingInputKind === 'user_input' ||
+ queueActive || promptActive);
+ return {
+ id: id,
+ title: String(value.name || value.title || '').slice(0, 120),
+ status: status,
+ pendingInputKind: pendingInputKind,
+ active: active,
+ terminal: !!terminalStatus,
+ event: String(eventName || 'sessionUpdated'),
+ };
+}
+
+function subscribeSessionMonitorResource(resource, listener) {
+ if (!resource || typeof resource.on !== 'function' || typeof listener !== 'function') return function () {};
+ var subscriptions = [];
+ function recordsFromPayload(eventName, payload) {
+ if (eventName !== 'sessionsChanged') return [payload];
+ if (Array.isArray(payload)) return payload;
+ if (!payload || typeof payload !== 'object') return [];
+ return payload.agents || payload.sessions || payload.conversations || payload.records || [];
+ }
+ ['sessionUpdated', 'sessionCreated', 'sessionDeleted', 'sessionsChanged'].forEach(function (eventName) {
+ var handler = function (payload) {
+ var records = recordsFromPayload(eventName, payload);
+ for (var i = 0; i < records.length; i++) {
+ var update = normalizeSessionMonitorResourceRecord(records[i], eventName);
+ if (update) listener(update);
+ }
+ };
+ try {
+ resource.on(eventName, handler);
+ subscriptions.push([eventName, handler]);
+ } catch (_) {}
+ });
+ return function () {
+ if (typeof resource.off !== 'function') return;
+ for (var i = 0; i < subscriptions.length; i++) {
+ try { resource.off(subscriptions[i][0], subscriptions[i][1]); } catch (_) {}
+ }
+ subscriptions = [];
+ };
+}
+
+// In-memory state for background-session monitors. This deliberately has no
+// persistence or daemon transport: the About-page viewer is a live diagnostic
+// surface and must not turn conversation activity into a local log file.
+function createSessionMonitorRegistry(options) {
+ var opts = options || {};
+ var maxLogs = Math.max(1, Number(opts.maxLogs || 160));
+ var maxSessions = Math.max(1, Number(opts.maxSessions || 64));
+ var sessions = Object.create(null);
+ var order = [];
+ function ensure(id, meta) {
+ var key = String(id || '').trim();
+ if (!key) return null;
+ if (!sessions[key]) {
+ if (order.length >= maxSessions) {
+ var evicted = order.shift();
+ if (evicted) delete sessions[evicted];
+ }
+ sessions[key] = { id: key, title: '', status: 'unknown', updatedAt: 0, logs: [] };
+ order.push(key);
+ }
+ if (meta) {
+ if (meta.title != null) sessions[key].title = String(meta.title).slice(0, 120);
+ if (meta.status != null) sessions[key].status = String(meta.status).slice(0, 40);
+ }
+ sessions[key].updatedAt = Date.now();
+ return sessions[key];
+ }
+ function update(id, patch) {
+ var item = ensure(id);
+ if (!item) return null;
+ var p = patch || {};
+ Object.keys(p).forEach(function (key) {
+ if (key === 'logs' || key === 'id') return;
+ item[key] = p[key];
+ });
+ item.updatedAt = Date.now();
+ return item;
+ }
+ function append(id, event, detail) {
+ var item = ensure(id);
+ if (!item) return null;
+ var entry = {
+ at: Date.now(),
+ event: String(event || 'event').slice(0, 80),
+ detail: detail && typeof detail === 'object' ? Object.assign({}, detail) : {},
+ };
+ item.logs.push(entry);
+ if (item.logs.length > maxLogs) item.logs.splice(0, item.logs.length - maxLogs);
+ item.updatedAt = entry.at;
+ return entry;
+ }
+ function remove(id) {
+ var key = String(id || '').trim();
+ if (!sessions[key]) return false;
+ delete sessions[key];
+ var index = order.indexOf(key);
+ if (index >= 0) order.splice(index, 1);
+ return true;
+ }
+ function clear() {
+ sessions = Object.create(null);
+ order = [];
+ }
+ function list() {
+ return order.map(function (key) { return sessions[key]; }).filter(Boolean);
+ }
+ return { ensure: ensure, update: update, append: append, remove: remove, clear: clear, list: list, get: function (id) { return sessions[String(id || '')] || null; } };
+}
+
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
createBuildLifecycle: createBuildLifecycle,
@@ -189,10 +485,19 @@ if (typeof module !== 'undefined' && module.exports) {
autoContinueMessageText: autoContinueMessageText,
autoContinueControllerCompleted: autoContinueControllerCompleted,
selectAutoContinueAssistant: selectAutoContinueAssistant,
+ composerBlocksFromTree: composerBlocksFromTree,
+ composerTextFromTree: composerTextFromTree,
+ contentToBlocks: contentToBlocks,
normalizeQueueText: normalizeQueueText,
isStashQueueItem: isStashQueueItem,
stashContentSignature: stashContentSignature,
stashContentMatches: stashContentMatches,
+ classifyNoDisturbApprovalCandidate: classifyNoDisturbApprovalCandidate,
+ isSessionMonitorInProgress: isSessionMonitorInProgress,
+ normalizeSessionMonitorResourceRecord: normalizeSessionMonitorResourceRecord,
+ sessionMonitorLifecycleAction: sessionMonitorLifecycleAction,
+ subscribeSessionMonitorResource: subscribeSessionMonitorResource,
+ createSessionMonitorRegistry: createSessionMonitorRegistry,
};
}
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
@@ -562,24 +867,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
// 输入框是否有内容(文字或任意 contentblock 节点:图片/文件/技能)
// 关键:Slate 空输入框时渲染 [data-slate-placeholder="true"] 占位节点(如"今天帮你做些什么?"),
- // innerText 会包含占位文字 → 误判有内容 → 按钮空输入框也显示。用 TreeWalker 遍历真实文本节点,
- // 跳过 placeholder 子树。
+ // innerText 会包含占位文字;contentblock 的可见标签也不是正文。统一通过
+ // composerTextFromTree 跳过这两类装饰子树。
function composerHasContent(editor) {
if (!editor) return false;
- try {
- var textLen = 0;
- var walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT, null);
- var n;
- while ((n = walker.nextNode())) {
- var p = n.parentElement;
- if (p && p.hasAttribute && p.hasAttribute('data-slate-placeholder')) continue; // 跳过占位文字
- textLen += (n.nodeValue || '').replace(/[\uFEFF\u200B\u00A0]/g, '').replace(/\s+/g, '').length;
- }
- if (textLen > 0) return true;
- } catch (_) {
- var t = (editor.innerText || editor.textContent || '').toString().replace(/[\uFEFF\u200B\u00A0]/g, '').replace(/\s+/g, '');
- if (t.length > 0) return true;
- }
+ var text = composerTextFromTree(editor).replace(/[\uFEFF\u200B\u00A0]/g, '').replace(/\s+/g, '');
+ if (text.length > 0) return true;
if (editor.querySelector && editor.querySelector('[data-contentblock]')) return true;
return false;
}
@@ -587,29 +880,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function getComposerContent() {
var editor = findComposer();
if (!editor) return null;
- var text = (editor.innerText || editor.textContent || '').toString();
- var items = [];
- var blocks = editor.querySelectorAll ? editor.querySelectorAll('[data-contentblock]') : [];
- for (var i = 0; i < blocks.length; i++) {
- try {
- var raw = blocks[i].getAttribute('data-contentblock') || '';
- var j = JSON.parse(raw.indexOf('&quot;') >= 0 ? raw.replace(/&quot;/g, '"') : raw);
- var item = {
- type: j.type,
- name: j.name || (j.uri || '').toString().split('/').pop() || '',
- uri: j.uri || '',
- _meta: j._meta || null,
- };
- if (j.type === 'image' && typeof j.data === 'string' && j.data.indexOf('iVBOR') === 0) {
- item.imageBase64 = j.data; // 完整 PNG 字节,可直接还原
- }
- items.push(item);
- } catch (e) {}
- }
+ var orderedBlocks = composerBlocksFromTree(editor);
+ var text = orderedBlocks.filter(function (block) { return block.type === 'text'; })
+ .map(function (block) { return block.text; }).join('');
+ var items = orderedBlocks.filter(function (block) { return block.type !== 'text'; });
return {
text: text,
textLen: text.replace(/[\uFEFF\u200B]/g, '').trim().length,
items: items,
+ orderedBlocks: orderedBlocks,
capturedAt: new Date().toISOString(),
};
}
@@ -2614,116 +2893,23 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 立即安装或升级按钮桥接,不要求用户先再次点击“暂存提示词”。
setBuildTimeout(bootstrapModernQueueBridge, 300);
setBuildTimeout(bootstrapModernQueueBridge, 1200);
-
- function writeModernQueueItemToComposer(item) {
- var editor = findComposer();
- if (!editor) return false;
- var blocks = item && Array.isArray(item.contentBlocks) ? item.contentBlocks : [];
- var text = blocks.map(function (block) {
- return block && typeof block.text === 'string' ? block.text : '';
- }).filter(Boolean).join('\n') || (item && (item.previewText || item.label)) || '';
- if (!text) return false;
- try {
- editor.focus();
- var selection = window.getSelection();
- var range = document.createRange();
- range.selectNodeContents(editor);
- selection.removeAllRanges();
- selection.addRange(range);
- document.execCommand('delete');
- document.execCommand('insertText', false, text);
- editor.dispatchEvent(new InputEvent('input', { bubbles: true, data: text, inputType: 'insertText' }));
- return true;
- } catch (e) {
- return false;
- }
- }
-
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');
if (!cell) return;
- var buttons = cell.querySelectorAll('.cb-message-queue-item-actions button.icon-btn');
- var actionIndex = Array.prototype.indexOf.call(buttons, button);
- 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;
- try {
- var roots = [document.querySelector('.cr-document[data-root-id="' + String(sessionId).replace(/"/g, '\\"') + '"]'), document.querySelector('.conversation-shell')];
- for (var ri = 0; ri < roots.length && !manager; ri++) {
- var root = roots[ri];
- if (!root) continue;
- for (var key in root) {
- if (key.indexOf('__reactFiber$') !== 0 && key.indexOf('__reactInternalInstance') !== 0) continue;
- var cur = root[key], seen = 0;
- while (cur && seen++ < 500) {
- var props = cur.memoizedProps;
- var controller = props && props.value;
- if (controller && controller.conversationId === sessionId && controller.lifecycle && controller.lifecycle.conv) {
- manager = controller.lifecycle.conv.queueManager;
- break;
- }
- cur = cur.return;
- }
- break;
- }
- }
- } catch (e) {}
- var item = manager && typeof manager.items === 'function'
- ? manager.items().find(function (entry) { return entry && String(entry.id) === String(itemId); })
- : null;
+ // Real rows must stay owned by WorkBuddy's React callbacks: they use
+ // inputApi.setBlocks() for edit and promptQueue.sendNow() for guided send.
+ if (!itemId || itemId.indexOf('wbs-pending-') !== 0) return;
event.preventDefault();
event.stopPropagation();
if (typeof event.stopImmediatePropagation === 'function') event.stopImmediatePropagation();
- // Optimistic rows have no server-side id yet; let the real enqueue settle
- // before allowing send/edit/delete actions on them.
- if (item && item.__wbsOptimistic) return;
- var operation;
- if (actionIndex === 0 && typeof adapter.sendConversationMessageQueueItemNow === 'function') {
- operation = adapter.sendConversationMessageQueueItemNow(sessionId, itemId);
- } else if (actionIndex === 1 && typeof adapter.removeConversationMessageQueueItem === 'function') {
- operation = Promise.resolve(adapter.removeConversationMessageQueueItem(sessionId, itemId)).then(function () {
- if (!writeModernQueueItemToComposer(item)) throw new Error('WorkBuddy 输入框回填失败');
- });
- } else if (actionIndex === 2 && typeof adapter.removeConversationMessageQueueItem === 'function') {
- operation = adapter.removeConversationMessageQueueItem(sessionId, itemId);
- } else {
- return;
- }
- Promise.resolve(operation).catch(function (error) {
- crumb('queue-action:fail:' + actionIndex + ':' + ((error && error.message) || error));
- });
}
listen(document, 'click', handleModernQueueActionClick, true);
- // 把抓取的输入框富文本转成 contentblocks(image 补回 base64 data),原样加入 WorkBuddy 队列。
- // 【稳定性】只保留最朴素的纯对象字段,去掉 _meta/displayAsPhrase 等可能带不可克隆引用的元数据——
- // 5.3.8 在重渲染队列面板跨进程克隆该项时会因这类字段崩(An object could not be cloned)。
- function contentToBlocks(content) {
- var blocks = [];
- var text = (content && content.text || '').replace(/[\uFEFF\u200B]+/g, '').trim();
- if (text) blocks.push({ type: 'text', text: text });
- (content && content.items || []).forEach(function (it) {
- try {
- if (it.type === 'image' && it.imageBase64) {
- blocks.push({ type: 'image', data: it.imageBase64, mimeType: 'image/png', uri: it.uri || '' });
- } else if (it.type === 'image') {
- blocks.push({ type: 'image', data: it.data || '', mimeType: 'image/png', uri: it.uri || '' });
- } else if (it.type !== 'text') {
- var b = { type: it.type, name: it.name || '附件', uri: it.uri || '', title: it.title || it.name || '附件' };
- if (it.mimeType) b.mimeType = it.mimeType;
- blocks.push(b);
- }
- } catch (e) {}
- });
- return blocks;
- }
+ // 输入框内容在顶层 contentToBlocks 中转为可克隆的官方队列 blocks。
// 入队/暂停全部走 adapter 的官方包装方法(enqueueConversationMessageQueueItem / pauseConversationMessageQueue):
// 包装方法内部会调用 client RPC + _notifyQueueUpdate(snapshot)(sanitize + 存快照 + 同步运行时 + 通知面板回调),
// 官方面板正是靠这一条链路刷新的。手动直调 client.sessions.* 或手动喂 _queueCallbacks 都会绕过/复刻这条
@@ -3084,7 +3270,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 新版布局(无 voice-mic-wrap):复用通用输入框定位(视口下半部可见的 contenteditable)
ed = findComposer();
}
- clearModernComposerDraft(ed, stashSessionAtClick);
+ var modernDraftCleared = clearModernComposerDraft(ed, stashSessionAtClick);
+ if (modernDraftCleared) return;
var cleared = false;
var node = ed;
for (var up = 0; up < 20 && node; up++) {
@@ -3308,6 +3495,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var enhancePane = root.querySelector('[data-pane="enhance"]');
var pcPane = root.querySelector('[data-pane="pc"]');
var aboutPane = root.querySelector('[data-pane="about"]');
+ var hiddenToolsUnlocked = false;
var logoutBtn = root.querySelector('[data-act="logout"]');
var creditTooltip = null;
var creditTooltipSegment = null;
@@ -4691,7 +4879,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">仅当前会话,回复中保持唤醒</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>' +
@@ -4708,11 +4896,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
r.addEventListener('change', function () {
if (!this.checked) return;
var mode = this.value;
- // until-done:校验当前会话正在进行中才允许开启;无进行中会话则拒绝并回退 allow
+ // until-done:校验至少一个会话正在进行中;无进行中会话则拒绝并回退 allow
if (mode === 'until-done') {
- var st = isSessionBusy(null);
- if (!st.busy) {
- toast('当前没有进行中的会话,无法开启「当前会话结束允许休眠」', true, root);
+ if (!isAnySessionBusy()) {
+ toast('当前没有进行中的会话,无法开启「所有会话结束允许休眠」', true, root);
var goBack = pcPane && pcPane.querySelector('input[name="wbs-sleep-mode"][value="allow"]');
if (goBack) goBack.checked = true;
syncSleepState();
@@ -4775,6 +4962,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</div>' +
'<div class="wbs-telemetry-status" id="wbs-telemetry-status" role="status" aria-live="polite">正在读取设置…</div>' +
'</div>' +
+ '<div class="wbs-pcard wbs-monitor-log-card" id="wbs-monitor-log-card"' + (hiddenToolsUnlocked ? '' : ' style="display:none"') + '>' +
+ '<div class="wbs-telemetry-head">' +
+ '<div class="wbs-telemetry-label"><span class="wbs-pcard-title">会话监听日志</span><span class="wbs-pcard-sub">仅保存在当前页面内存</span></div>' +
+ '</div>' +
+ '<div class="wbs-monitor-log-inline" id="wbs-monitor-log-inline">' +
+ '<div class="wbs-monitor-log-session-list" aria-label="进行中的会话"></div>' +
+ '<div class="wbs-monitor-log-list" role="log" aria-live="polite">暂无进行中的会话</div>' +
+ '</div>' +
+ '</div>' +
'';
// 回拉 /api/about 填充信息(失败时保留硬编码占位)
@@ -4797,6 +4993,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (issues && d.repository) issues.href = d.repository.replace(/\/$/, '') + '/issues';
}).catch(function () {});
wireTelemetrySettings();
+ acRenderMonitorLogModal();
// 自动更新:检查 + 红点 + 更新卡片
checkForUpdate();
}
@@ -5716,8 +5913,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
piClickTimer = setBuildTimeout(function () { piClickCount = 0; }, 1200);
if (piClickCount >= 5) {
piClickCount = 0;
+ hiddenToolsUnlocked = true;
if (piPickBtn) piPickBtn.style.display = '';
- try { toast('元素检查已呼出', false, root); } catch (_) {}
+ var monitorLogCard = aboutPane && aboutPane.querySelector('#wbs-monitor-log-card');
+ if (monitorLogCard) monitorLogCard.style.display = '';
+ try { toast('隐藏工具已呼出', false, root); } catch (_) {}
}
});
}
@@ -6025,10 +6225,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var displaySleepSwitch = null; // 允许显示器休眠开关(电脑 pane,wirePcPane 赋值)
var sleepMode = 'allow'; // 当前休眠模式(内存缓存,syncSleepState 更新)
var sleepUntilDoneCheck = null; // until-done 模式下的空闲检测定时器
+ var sleepSessionCache = Object.create(null); // until-done 独立发现的控制器缓存(仅内存)
/* ===== 免打扰模块(No-Disturb)===== */
var ndAutoObserver = null; // 弹窗自动点允许的 MutationObserver
var ndScanTimer = null;
+ var ndScanRoots = [];
var ndEnabledCount = 0;
// 开关定义:id/配置名/确认弹窗文案(开启时弹窗,红字确认)
var ND_DEFS = [
@@ -6269,8 +6471,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
};
var acRunning = false;
var acStatusTimer = null;
+ var acMonitorRegistry = createSessionMonitorRegistry({ maxLogs: 180 });
+ var acMulti = {
+ generation: 0,
+ sessions: Object.create(null),
+ discoveryTimer: null,
+ sessionResource: null,
+ sessionResourceUnsubscribe: null,
+ sessionResourceRetryAt: 0,
+ sidebarReconcileAt: 0,
+ };
- /** 状态机可视化日志:写入环形缓冲 + 渲染到开发者工具卡片(连点 5 次 logo 呼出)+ 上报 daemon breadcrumb */
+ /** 状态机可视化日志:只写入当前 renderer 的有界内存,不落盘、不发送到 daemon。 */
var AC_LOG_MAX = 150;
var acLogLines = [];
var acLogLastKeyTs = {};
@@ -6287,13 +6499,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var pre = enhancePane && enhancePane.querySelector('#wbs-ac-log');
if (pre) { pre.textContent = acLogLines.join('\n'); pre.scrollTop = pre.scrollHeight; }
} catch (e) {}
- try {
- fetch(API + '/api/breadcrumb', {
- method: 'POST',
- headers: { 'content-type': 'application/json', 'X-WorkDaddy-Token': WBS_API_TOKEN },
- body: JSON.stringify({ msg: 'ac:' + msg, extra: extra || {} }),
- }).catch(function () {});
- } catch (e) {}
}
/** 限频日志:同一 key 在窗口内最多打一条(流式 mutation 每帧都打会刷屏) */
function acLogR(key, msg, extra, windowMs) {
@@ -6305,6 +6510,31 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
acLog(msg, extra);
}
+ function acSessionTitle(controller) {
+ try {
+ var view = controller && typeof controller.getSessionViewState === 'function'
+ ? controller.getSessionViewState() : null;
+ return String((view && (view.title || view.name)) || '').slice(0, 120);
+ } catch (_) { return ''; }
+ }
+
+ function acMonitorLog(sessionId, event, detail) {
+ if (!sessionId) return;
+ acMonitorRegistry.append(sessionId, event, detail || {});
+ acScheduleMonitorLogRender();
+ }
+
+ var acMonitorLogFrame = null;
+ function acScheduleMonitorLogRender() {
+ if (acMonitorLogFrame != null) return;
+ var raf = window.requestAnimationFrame || function (fn) { return setTimeout(fn, 40); };
+ acMonitorLogFrame = raf(function () {
+ acMonitorLogFrame = null;
+ acRenderLog();
+ acRenderMonitorLogModal();
+ });
+ }
+
function acResetState() {
var c = acCtx;
c.generation++;
@@ -7192,7 +7422,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
/** 启动监控:优先绑定 ConversationController stores;旧客户端找不到 controller 时才挂 DOM observer。 */
- function acStartMonitor() {
+ function acStartLegacyMonitor() {
var carry = acCtx.controller ? {
conversationId: acCtx.controller.conversationId,
baselineAssistantKey: acCtx.baselineAssistantKey,
@@ -7248,7 +7478,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
acLog('baseline-established', { awaitingNewReply: true });
acStartStatusAnim(); // 开关开启期间持续显示「监控激活会话中…」
}
- function acStopMonitor() {
+ function acStopLegacyMonitor() {
var c = acCtx;
if (c.settleTimer) { clearTimeout(c.settleTimer); c.settleTimer = null; }
if (c.observer) { try { c.observer.disconnect(); } catch (e) {} c.observer = null; }
@@ -7269,6 +7499,403 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
c.baselineMessages = null;
}
+ function acMultiUpdateStatus(session, status, detail) {
+ var count = Object.keys(acMulti.sessions).length;
+ var st = enhancePane && enhancePane.querySelector('#wbs-ac-status');
+ if (st) st.textContent = count ? '监控激活会话中' : '等待会话';
+ if (!session || !session.id) return;
+ var previous = session.status;
+ session.status = status;
+ acMonitorRegistry.update(session.id, { title: session.title, status: status });
+ // Store subscriptions can emit on every streaming chunk. Keep the live
+ // viewer useful by logging transitions and explicit operations only.
+ var operation = /^(discovered|sending|continue-sent|send-error|send-unconfirmed|input-busy|interrupted|completed|stopped|awaiting-approval)$/.test(status);
+ if (previous !== status || operation) acMonitorLog(session.id, status, detail || {});
+ }
+
+ function acMultiCreateSession(update, source) {
+ if (!update || !update.id || acMulti.sessions[update.id]) return acMulti.sessions[update.id] || null;
+ var session = {
+ id: update.id,
+ controller: null,
+ title: update.title || '',
+ status: 'discovered',
+ lastSeen: 0,
+ controllerLastDiscoveredAt: 0,
+ lastVersion: -1,
+ lastBusy: false,
+ idleAt: 0,
+ baselineAssistantKey: '',
+ awaitingNewReply: true,
+ awaitingSince: 0,
+ hadActivity: !!update.active,
+ judgedMessages: new Set(),
+ timer: null,
+ generation: acMulti.generation,
+ sending: false,
+ unsubs: [],
+ resourceActive: !!update.active,
+ resourceStatus: update.status || '',
+ resourcePendingInputKind: update.pendingInputKind || '',
+ resourceUpdatedAt: Date.now(),
+ };
+ acMulti.sessions[session.id] = session;
+ acMonitorRegistry.ensure(session.id, { title: session.title, status: session.status });
+ acMonitorLog(session.id, 'discovered', { source: source || 'session-resource' });
+ return session;
+ }
+
+ function acMultiStatusFromResource(update) {
+ if (update.pendingInputKind) return 'awaiting-approval';
+ return update.status === 'pending' ? 'pending' : 'running';
+ }
+
+ function acMultiHandleSessionResourceUpdate(update) {
+ if (!update || !update.id || !acRunning || acMulti.mode !== 'multi') return;
+ var session = acMulti.sessions[update.id];
+ var action = sessionMonitorLifecycleAction(update, !!session);
+ if (action === 'add') session = acMultiCreateSession(update, update.event === 'sidebarSnapshot' ? 'sidebar' : 'session-resource');
+ if (action === 'ignore' || !session) return;
+ session.resourceActive = update.active;
+ session.resourceStatus = update.status || session.resourceStatus;
+ session.resourcePendingInputKind = update.pendingInputKind || '';
+ session.resourceUpdatedAt = Date.now();
+ if (update.title) session.title = update.title;
+ if (action === 'remove') {
+ acMultiUpdateStatus(session, 'completed', {
+ source: update.event === 'sidebarSnapshot' ? 'sidebar' : 'session-resource',
+ event: update.event,
+ status: update.status,
+ });
+ acMultiFinishSession(session);
+ return;
+ }
+ if (!update.active) return;
+ acMultiUpdateStatus(session, acMultiStatusFromResource(update), {
+ source: update.event === 'sidebarSnapshot' ? 'sidebar' : 'session-resource',
+ status: update.status,
+ pendingInputKind: update.pendingInputKind || undefined,
+ });
+ }
+
+ function acMultiReconcileSidebar() {
+ if (!WBS_COMPAT || typeof WBS_COMPAT.findConversationListRecords !== 'function') return false;
+ var records = [];
+ try { records = WBS_COMPAT.findConversationListRecords(document) || []; } catch (_) {}
+ for (var i = 0; i < records.length; i++) {
+ var update = normalizeSessionMonitorResourceRecord(records[i], 'sidebarSnapshot');
+ if (update) acMultiHandleSessionResourceUpdate(update);
+ }
+ return records.length > 0;
+ }
+
+ function acMultiBindSessionResource() {
+ if (acMulti.sessionResource) return true;
+ acMulti.sessionResourceRetryAt = Date.now() + 15000;
+ if (!WBS_COMPAT || typeof WBS_COMPAT.findSessionsResource !== 'function') return false;
+ var resource = null;
+ try { resource = WBS_COMPAT.findSessionsResource(document); } catch (_) {}
+ if (!resource) return false;
+ acMulti.sessionResource = resource;
+ acMulti.sessionResourceUnsubscribe = subscribeSessionMonitorResource(resource, acMultiHandleSessionResourceUpdate);
+ acLog('session-resource-bound');
+ return true;
+ }
+
+ function acMultiUnbindSessionResource() {
+ if (typeof acMulti.sessionResourceUnsubscribe === 'function') {
+ try { acMulti.sessionResourceUnsubscribe(); } catch (_) {}
+ }
+ acMulti.sessionResourceUnsubscribe = null;
+ acMulti.sessionResource = null;
+ acMulti.sessionResourceRetryAt = 0;
+ }
+
+ function acMultiSchedule(session, delay) {
+ if (!session || !acRunning) return;
+ if (session.timer) clearTimeout(session.timer);
+ session.timer = setBuildTimeout(function () {
+ session.timer = null;
+ acMultiCheckSession(session);
+ }, Math.max(100, Number(delay || 800)));
+ }
+
+ function acMultiSend(session, snapshot) {
+ if (!session || !snapshot || session.sending || !acRunning) return;
+ var controller = session.controller;
+ if (!controller || typeof controller.sendPrompt !== 'function') return;
+ var view;
+ try { view = controller.getSessionViewState(); } catch (_) { return; }
+ if (view && (view.isBusy || view.isRunActive || view.isTurnActive || view.isPending || view.isSending)) {
+ acMultiUpdateStatus(session, 'running', { reason: 'send-busy-skip' });
+ return;
+ }
+ // Only the active session has a user-editable composer. A background
+ // controller send must never inspect or overwrite that composer.
+ if (String(acActiveConversationId() || '') === String(session.id) && !acControllerComposerEmpty()) {
+ acMultiUpdateStatus(session, 'input-busy', { reason: 'active-composer-not-empty' });
+ acWeak('输入框非空,已放弃会话 ' + session.id + ' 的自动继续');
+ return;
+ }
+ session.sending = true;
+ acMultiUpdateStatus(session, 'sending', { assistantId: snapshot.assistantId || '' });
+ var promise;
+ try {
+ promise = controller.sendPrompt({ blocks: [{ type: 'text', text: AC_CONTINUE_TEXT }] }, {
+ _meta: { 'codebuddy.ai': { source: 'workdaddy-auto-continue' } },
+ });
+ } catch (e) {
+ session.sending = false;
+ acMultiUpdateStatus(session, 'send-error', { error: (e && e.message) || '?' });
+ return;
+ }
+ Promise.resolve(promise).then(function (result) {
+ if (!acRunning || session.generation !== acMulti.generation) return;
+ session.sending = false;
+ session.awaitingNewReply = true;
+ session.awaitingSince = Date.now();
+ session.baselineAssistantKey = snapshot.assistantId || session.baselineAssistantKey;
+ acMultiUpdateStatus(session, 'continue-sent', { assistantId: snapshot.assistantId || '' });
+ }).catch(function (e) {
+ if (!acRunning || session.generation !== acMulti.generation) return;
+ session.sending = false;
+ acMultiUpdateStatus(session, 'send-unconfirmed', { error: (e && e.message) || '?' });
+ });
+ }
+
+ function acMultiCheckSession(session) {
+ if (!session || !acRunning || !session.controller) return;
+ var selectedId = acActiveConversationId();
+ if (selectedId && String(selectedId) !== String(session.id) && session.resourceActive) {
+ acMultiUpdateStatus(session,
+ session.resourcePendingInputKind ? 'awaiting-approval' : (session.resourceStatus === 'pending' ? 'pending' : 'running'),
+ { source: 'session-resource' });
+ return;
+ }
+ var snapshot = acControllerSnapshot(session.controller);
+ if (!snapshot || !snapshot.conversationId) return;
+ session.lastSeen = Date.now();
+ session.title = session.title || acSessionTitle(session.controller);
+ acMonitorRegistry.ensure(session.id, { title: session.title });
+ session.hadActivity = session.hadActivity || isSessionMonitorInProgress(snapshot);
+ if (snapshot.hydrating) {
+ session.awaitingNewReply = true;
+ session.baselineAssistantKey = snapshot.assistantId || session.baselineAssistantKey;
+ session.lastVersion = snapshot.version;
+ // An unmounted controller can remain frozen in hydration forever. A
+ // newer global resource event is authoritative for background state.
+ acMultiUpdateStatus(session, session.resourceActive ? 'running' : 'hydrating',
+ session.resourceActive ? { source: 'session-resource' } : undefined);
+ return;
+ }
+ if (snapshot.blocked) {
+ session.lastBusy = true;
+ session.idleAt = 0;
+ session.lastVersion = snapshot.version;
+ acMultiUpdateStatus(session, 'awaiting-approval', { state: snapshot.state || '' });
+ return;
+ }
+ if (snapshot.busy) {
+ session.lastBusy = true;
+ session.idleAt = 0;
+ session.lastVersion = snapshot.version;
+ acMultiUpdateStatus(session, 'running', { phase: snapshot.phase || '', state: snapshot.state || '' });
+ return;
+ }
+ if (session.lastBusy || !session.idleAt) session.idleAt = Date.now();
+ session.lastBusy = false;
+ session.lastVersion = snapshot.version;
+ if (!snapshot.assistantId) {
+ acMultiFinishSession(session);
+ return;
+ }
+ if (session.awaitingNewReply) {
+ if (snapshot.assistantId === session.baselineAssistantKey) {
+ // Hydration can settle on an existing historical reply without ever
+ // producing a new turn. It is no longer an in-progress session.
+ if (!session.awaitingSince && !snapshot.busy) {
+ acMultiFinishSession(session);
+ return;
+ }
+ if (session.awaitingSince && !snapshot.busy && Date.now() - session.awaitingSince >= AC_CONTROLLER_SETTLE_MS) {
+ acMultiFinishSession(session);
+ return;
+ }
+ acMultiUpdateStatus(session, 'waiting-new-reply');
+ return;
+ }
+ session.awaitingNewReply = false;
+ session.baselineAssistantKey = snapshot.assistantId;
+ session.idleAt = Date.now();
+ acMultiUpdateStatus(session, 'new-reply', { assistantId: snapshot.assistantId });
+ }
+ var signature = 'id:' + snapshot.assistantId;
+ if (session.judgedMessages.has(signature)) return;
+ var idleFor = Date.now() - session.idleAt;
+ var completed = autoContinueControllerCompleted(snapshot);
+ if (!completed && !snapshot.error && idleFor < AC_CONTROLLER_SETTLE_MS) {
+ acMultiUpdateStatus(session, 'settling', { idleForMs: idleFor });
+ acMultiSchedule(session, Math.max(250, AC_CONTROLLER_SETTLE_MS - idleFor));
+ return;
+ }
+ var decision = classifyAutoContinueControllerSnapshot({
+ assistantId: snapshot.assistantId,
+ busy: snapshot.busy,
+ manualStop: snapshot.manualStop,
+ error: snapshot.error,
+ networkFailure: snapshot.networkFailure,
+ completionMarker: acHasMarker(snapshot.text),
+ complete: snapshot.terminalKnown ? false : snapshot.complete,
+ terminal: snapshot.terminal,
+ });
+ session.judgedMessages.add(signature);
+ if (!decision.trigger) {
+ acMultiFinishSession(session);
+ return;
+ }
+ if (snapshot.manualStop) {
+ acMultiFinishSession(session);
+ return;
+ }
+ acMultiUpdateStatus(session, 'interrupted', { reason: decision.reason, idleForMs: idleFor });
+ acMultiSend(session, snapshot);
+ }
+
+ function acMultiBindController(controller) {
+ if (!controller || !controller.conversationId) return null;
+ var id = String(controller.conversationId);
+ var existing = acMulti.sessions[id];
+ if (existing && existing.controller === controller) {
+ existing.lastSeen = Date.now();
+ existing.controllerLastDiscoveredAt = Date.now();
+ return existing;
+ }
+ var initialSnapshot = acControllerSnapshot(controller);
+ if (!existing && !isSessionMonitorInProgress(initialSnapshot)) return null;
+ var session = existing || acMultiCreateSession({
+ id: id,
+ title: acSessionTitle(controller),
+ status: 'running',
+ active: true,
+ terminal: false,
+ }, 'controller');
+ if (!session) return null;
+ if (session.controller && session.controller !== controller) acMultiDetachController(session);
+ session.controller = controller;
+ session.lastSeen = Date.now();
+ session.controllerLastDiscoveredAt = Date.now();
+ session.generation = acMulti.generation;
+ session.title = session.title || acSessionTitle(controller);
+ session.hadActivity = session.hadActivity || isSessionMonitorInProgress(initialSnapshot);
+ // Establish the historical baseline before the first store callback.
+ // Otherwise an already-rendered assistant message would look like a new
+ // reply and could trigger an immediate false continuation.
+ // A busy controller's current assistant is the in-flight reply, not a
+ // historical baseline. Leave it empty so completion can be judged.
+ if (initialSnapshot && !initialSnapshot.busy && !initialSnapshot.blocked && !initialSnapshot.hydrating) {
+ session.baselineAssistantKey = initialSnapshot.assistantId || '';
+ }
+ var notify = function () { acMultiCheckSession(session); };
+ try { if (controller.sessionStore && typeof controller.sessionStore.subscribe === 'function') session.unsubs.push(controller.sessionStore.subscribe(notify)); } catch (_) {}
+ try { if (controller.messageStore && typeof controller.messageStore.subscribe === 'function') session.unsubs.push(controller.messageStore.subscribe(notify)); } catch (_) {}
+ if (initialSnapshot && (isSessionMonitorInProgress(initialSnapshot) || !session.resourceActive)) acMultiCheckSession(session);
+ return session;
+ }
+
+ function acMultiFinishSession(session) {
+ if (!session || !acMulti.sessions[session.id]) return;
+ acMultiDetachController(session);
+ delete acMulti.sessions[session.id];
+ acMonitorRegistry.remove(session.id);
+ if (acMonitorSelectedId === session.id) acMonitorSelectedId = '';
+ acScheduleMonitorLogRender();
+ }
+
+ function acMultiDetachController(session) {
+ if (!session) return;
+ if (session.timer) { clearTimeout(session.timer); session.timer = null; }
+ for (var i = 0; i < session.unsubs.length; i++) { try { session.unsubs[i](); } catch (_) {} }
+ session.unsubs = [];
+ session.controller = null;
+ session.sending = false;
+ }
+
+ function acMultiDiscover() {
+ if (!acRunning || acMulti.mode !== 'multi') return;
+ var controllers = [];
+ try {
+ if (WBS_COMPAT && typeof WBS_COMPAT.findConversationControllers === 'function') {
+ controllers = WBS_COMPAT.findConversationControllers(document) || [];
+ }
+ } catch (_) {}
+ var seen = Object.create(null);
+ for (var i = 0; i < controllers.length; i++) {
+ var session = acMultiBindController(controllers[i]);
+ if (session) seen[session.id] = true;
+ }
+ var now = Date.now();
+ if (!acMulti.sessionResource && now >= acMulti.sessionResourceRetryAt) acMultiBindSessionResource();
+ if (now >= acMulti.sidebarReconcileAt) {
+ acMulti.sidebarReconcileAt = now + 15000;
+ acMultiReconcileSidebar();
+ }
+ Object.keys(acMulti.sessions).forEach(function (id) {
+ var current = acMulti.sessions[id];
+ if (!current.controller || seen[id]) return;
+ // Controller lifetime follows the active view. Detaching it must not
+ // delete a background session still reported active by the global list.
+ if (now - current.controllerLastDiscoveredAt > 15000) {
+ acMultiDetachController(current);
+ if (!current.resourceActive) acMultiFinishSession(current);
+ }
+ });
+ if (acRunning) acMulti.discoveryTimer = setBuildTimeout(acMultiDiscover, AC_HEARTBEAT_MS);
+ acMultiUpdateStatus(null);
+ }
+
+ function acStartMultiMonitor() {
+ acMulti.mode = 'multi';
+ acStopLegacyMonitor();
+ acMulti.generation++;
+ var hasResource = acMultiBindSessionResource();
+ var hasSidebar = acMultiReconcileSidebar();
+ acMulti.sidebarReconcileAt = Date.now() + 15000;
+ acMultiDiscover();
+ if (!hasResource && !hasSidebar && !Object.keys(acMulti.sessions).length) {
+ acMulti.mode = 'none';
+ if (acMulti.discoveryTimer) { clearTimeout(acMulti.discoveryTimer); acMulti.discoveryTimer = null; }
+ acMultiUnbindSessionResource();
+ return false;
+ }
+ acShowStatus();
+ return true;
+ }
+
+ function acStopMultiMonitor() {
+ acMulti.mode = 'none';
+ acMulti.generation++;
+ if (acMulti.discoveryTimer) { clearTimeout(acMulti.discoveryTimer); acMulti.discoveryTimer = null; }
+ acMultiUnbindSessionResource();
+ Object.keys(acMulti.sessions).forEach(function (id) {
+ acMultiDetachController(acMulti.sessions[id]);
+ acMonitorRegistry.remove(id);
+ });
+ acMulti.sessions = Object.create(null);
+ acMulti.sidebarReconcileAt = 0;
+ acMonitorSelectedId = '';
+ acScheduleMonitorLogRender();
+ }
+
+ function acStartMonitor() {
+ if (acStartMultiMonitor()) return;
+ acStartLegacyMonitor();
+ }
+
+ function acStopMonitor() {
+ acStopMultiMonitor();
+ acStopLegacyMonitor();
+ }
+
/** 把已累积日志渲染进开发者工具卡片(buildEnhancePane 重建后恢复显示) */
function acRenderLog() {
try {
@@ -7280,6 +7907,71 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
} catch (e) {}
}
+ var acMonitorSelectedId = '';
+ function acMonitorStatusLabel(status) {
+ var labels = {
+ discovered: '已发现', running: '运行中', pending: '等待中', hydrating: '恢复中', 'awaiting-approval': '等待允许',
+ 'waiting-new-reply': '等待新回复', settling: '整理中', interrupted: '已中断', sending: '发送中',
+ 'continue-sent': '已继续', completed: '已完成', stopped: '已停止', idle: '空闲',
+ 'send-error': '发送失败', 'send-unconfirmed': '未确认', 'input-busy': '输入框占用', unknown: '未知',
+ };
+ return labels[status] || status || '未知';
+ }
+ function acMonitorSafeDetail(detail) {
+ var src = detail && typeof detail === 'object' ? detail : {};
+ var safe = {};
+ Object.keys(src).forEach(function (key) {
+ if (/text|prompt|content|token|key|path|cookie|account|nickname/i.test(key)) return;
+ var value = src[key];
+ if (value == null || typeof value === 'function') return;
+ safe[key] = typeof value === 'string' ? value.slice(0, 160) : value;
+ });
+ var out = JSON.stringify(safe);
+ return out === '{}' ? '' : out;
+ }
+ function acRenderMonitorLogModal() {
+ var host = aboutPane && aboutPane.querySelector('#wbs-monitor-log-inline');
+ if (!host) return;
+ var tabs = host.querySelector('.wbs-monitor-log-session-list');
+ var list = host.querySelector('.wbs-monitor-log-list');
+ if (!tabs || !list) return;
+ var sessions = acMonitorRegistry.list();
+ if (!sessions.length) {
+ acMonitorSelectedId = '';
+ tabs.textContent = '';
+ list.textContent = '暂无进行中的会话';
+ return;
+ }
+ if (!sessions.some(function (item) { return item.id === acMonitorSelectedId; })) acMonitorSelectedId = sessions[0].id;
+ tabs.textContent = '';
+ sessions.forEach(function (session) {
+ var tab = document.createElement('button');
+ tab.type = 'button';
+ tab.className = 'wbs-monitor-log-session-btn' + (session.id === acMonitorSelectedId ? ' active' : '');
+ tab.setAttribute('aria-pressed', session.id === acMonitorSelectedId ? 'true' : 'false');
+ tab.title = session.id;
+ var name = session.title || ('会话 ' + session.id.slice(0, 8));
+ tab.textContent = name + ' · ' + acMonitorStatusLabel(session.status);
+ tab.addEventListener('click', function () { acMonitorSelectedId = session.id; acRenderMonitorLogModal(); });
+ tabs.appendChild(tab);
+ });
+ var selected = sessions.find(function (item) { return item.id === acMonitorSelectedId; });
+ list.textContent = '';
+ if (!selected || !selected.logs.length) {
+ list.textContent = '该会话暂无操作日志';
+ return;
+ }
+ selected.logs.forEach(function (entry) {
+ var row = document.createElement('div');
+ row.className = 'wbs-monitor-log-entry';
+ var time = new Date(entry.at).toLocaleTimeString();
+ var detail = acMonitorSafeDetail(entry.detail);
+ row.textContent = '[' + time + '] ' + acMonitorStatusLabel(entry.event) + (detail ? ' · ' + detail : '');
+ list.appendChild(row);
+ });
+ list.scrollTop = list.scrollHeight;
+ }
+
function wireAutoContinuePane() {
acRenderLog();
var logClear = enhancePane && enhancePane.querySelector('#wbs-ac-log-clear');
@@ -7461,6 +8153,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
acRunning = false;
if (acThemeObserver) { try { acThemeObserver.disconnect(); } catch (e) {} acThemeObserver = null; }
acStopMonitor();
+ stopNoDisturbAutoApprove();
+ stopUntilDoneCheck();
+ if (acMonitorLogFrame != null) {
+ try {
+ var cancelFrame = window.cancelAnimationFrame || clearTimeout;
+ cancelFrame(acMonitorLogFrame);
+ } catch (e) {}
+ acMonitorLogFrame = null;
+ }
if (acStatusTimer) { clearTimeout(acStatusTimer); acStatusTimer = null; }
});
@@ -7469,18 +8170,49 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (ndAutoObserver) return;
var doc = (window && window.document) || document;
if (!doc || !doc.body) return;
- ndAutoObserver = new MutationObserver(function () { scheduleNdScan(); });
- ndAutoObserver.observe(doc.body, { childList: true, subtree: true });
+ ndScanRoots = [];
+ ndAutoObserver = new MutationObserver(function (records) {
+ for (var i = 0; i < records.length; i++) ndQueueScanRoot(records[i].target);
+ scheduleNdScan();
+ });
+ ndAutoObserver.observe(doc.body, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['aria-disabled', 'disabled', 'class', 'hidden', 'style', 'data-state', 'data-status'],
+ });
+ ndQueueScanRoot(doc.body);
scheduleNdScan();
}
function stopNoDisturbAutoApprove() {
if (ndAutoObserver) { ndAutoObserver.disconnect(); ndAutoObserver = null; }
if (ndScanTimer) { clearTimeout(ndScanTimer); ndScanTimer = null; }
+ ndScanRoots = [];
}
function scheduleNdScan() {
if (ndScanTimer) clearTimeout(ndScanTimer);
ndScanTimer = setTimeout(scanNoDisturbApproval, 120);
}
+ function ndQueueScanRoot(node) {
+ if (!node) return;
+ var el = node.nodeType === 1 ? node : node.parentElement;
+ if (!el) return;
+ // Prefer stable semantic dialog/task boundaries; fall back to a shallow
+ // ancestor so a background card is scanned without walking the whole body.
+ var root = el.closest && el.closest('[role="dialog"],[data-conversation-id],[data-root-id],' +
+ '[class*="_dialog_"],[class*="_modal_"],[class*="_permission_"],[class*="_confirm_"],' +
+ '[class*="_decision_"],[class*="_approval_"],[class*="_question_"],[class*="_ask_"],' +
+ '[class*="permission-dialog"],[class*="confirm-dialog"],[class*="decision-dialog"],' +
+ '[class*="approval"],[class*="permission"],[class*="confirm"]');
+ if (!root) {
+ root = el;
+ for (var i = 0; i < 4 && root.parentElement; i++) root = root.parentElement;
+ }
+ if (ndScanRoots.indexOf(root) < 0) ndScanRoots.push(root);
+ if (ndScanRoots.length > 24) ndScanRoots.shift();
+ }
+ // Kept as a small compatibility helper for older diagnostic harnesses;
+ // background cards are intentionally allowed through the structured gate.
function ndVisible(el) {
return !!(el && el.getClientRects && el.getClientRects().length && el.offsetParent !== null);
}
@@ -7508,39 +8240,90 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
return false;
}
+ function ndClassifyApprovalCandidate(value) {
+ if (typeof classifyNoDisturbApprovalCandidate === 'function') return classifyNoDisturbApprovalCandidate(value);
+ var input = value || {};
+ var label = String(input.label || '').trim().replace(/^\d+\s*/, '');
+ var kind = /始终允许|Always\s*allow/i.test(label) ? 'session' :
+ (/^(允许|允许一次|Allow|Yes|同意|批准|确认允许)$/i.test(label) || (/^Yes/i.test(label) && label.length < 24) ? 'once' : null);
+ if (!kind || input.disabled || input.ariaDisabled) return null;
+ var context = String(input.context || '').slice(0, 700);
+ if (input.creditSeen || ND_CREDIT_PATTERN.test(context)) return null;
+ return ND_CONFIRM_PATTERN.test(context) || (input.hasDeny === true && input.hasOnce === true && input.buttonCount >= 2 && input.buttonCount <= 12) ? kind : null;
+ }
+ function ndSessionIdForNode(node) {
+ try {
+ var owner = node && node.closest && node.closest('[data-conversation-id],[data-root-id]');
+ return owner && (owner.getAttribute('data-conversation-id') || owner.getAttribute('data-root-id')) || '';
+ } catch (_) { return ''; }
+ }
+ function ndApprovalContext(button) {
+ var box = button;
+ var text = '';
+ var hasDeny = false;
+ var count = 0;
+ var creditSeen = false;
+ var creditBox = button;
+ for (var creditDepth = 0; creditDepth < 8 && creditBox; creditDepth++) {
+ creditBox = creditBox.parentElement;
+ if (creditBox && ND_CREDIT_PATTERN.test(String(creditBox.textContent || '').slice(0, 700))) {
+ creditSeen = true;
+ break;
+ }
+ }
+ for (var depth = 0; depth < 8 && box; depth++) {
+ box = box.parentElement;
+ if (!box) break;
+ var current = String(box.textContent || '');
+ if (current.length > 700) current = current.slice(0, 700);
+ text = current;
+ if (ND_CREDIT_PATTERN.test(current)) creditSeen = true;
+ hasDeny = ND_DENY_WORD.test(current);
+ var buttons = box.querySelectorAll('button');
+ count = buttons ? buttons.length : 0;
+ var hasOnce = ndIsDecisionGroup(box);
+ var kind = ndClassifyApprovalCandidate({
+ label: button.textContent || '',
+ context: current,
+ hasDeny: hasDeny,
+ buttonCount: count,
+ hasOnce: hasOnce,
+ creditSeen: creditSeen,
+ disabled: button.disabled,
+ ariaDisabled: button.getAttribute('aria-disabled') === 'true',
+ });
+ if (kind) return { kind: kind, context: current, box: box };
+ }
+ return { kind: null, context: text, box: box };
+ }
function scanNoDisturbApproval() {
var doc = (window && window.document) || document;
if (!doc) return;
- var btns = doc.querySelectorAll('button');
- for (var i = 0; i < btns.length; i++) {
- var b = btns[i];
- if (b.getAttribute('data-nd-auto')) continue; // 已处理过
- if (!ndVisible(b)) continue;
- if (b.disabled || b.getAttribute('aria-disabled') === 'true') continue; // 禁用按钮不点
- var t = ndNormalizeLabel(b.textContent || '');
- var kind = null;
- if (/始终允许|Always\s*allow/i.test(t)) kind = 'session';
- else if (ND_ONCE_LABEL.test(t)) kind = 'once';
- else if (/^Yes/i.test(t) && t.length < 24) kind = 'once';
- if (!kind) continue;
- // 向上找确认容器(至多 8 层),验证语境:关键词命中,或近层命中「允许+拒绝」决策组(且无扣费文案)
- var box = b;
- var hit = false;
- var creditSeen = false;
- for (var c = 0; c < 8 && box; c++) {
- box = box.parentElement;
- if (!box) break;
- var txt = box.textContent || '';
- if (txt.length > 500) txt = txt.slice(0, 500);
- if (ND_CONFIRM_PATTERN.test(txt)) { hit = true; break; }
- if (ND_CREDIT_PATTERN.test(txt)) creditSeen = true;
- if (c < 3 && !creditSeen && ND_DENY_WORD.test(txt) && ndIsDecisionGroup(box)) { hit = true; break; }
+ var roots = (typeof ndScanRoots !== 'undefined' && ndScanRoots.length) ? ndScanRoots.splice(0, ndScanRoots.length) : [doc.body];
+ var seen = typeof WeakSet !== 'undefined' ? new WeakSet() : null;
+ for (var r = 0; r < roots.length; r++) {
+ var root = roots[r];
+ if (!root || !root.querySelectorAll || (doc.documentElement && !doc.documentElement.contains(root))) continue;
+ var btns = root.querySelectorAll('button');
+ for (var i = 0; i < btns.length; i++) {
+ var b = btns[i];
+ if (seen && seen.has(b)) continue;
+ if (seen) seen.add(b);
+ if (b.getAttribute('data-nd-auto')) continue;
+ var t = ndNormalizeLabel(b.textContent || '');
+ if (!t) continue;
+ var approval = ndApprovalContext(b);
+ if (!approval.kind) continue;
+ b.setAttribute('data-nd-auto', '1');
+ var sessionId = ndSessionIdForNode(b);
+ // The viewer represents active Auto-Continue sessions only; do not
+ // create a permanent tab for a one-off approval when that monitor is off.
+ if (sessionId && acRunning && acMulti.sessions[sessionId]) {
+ acMonitorLog(sessionId, 'approval-clicked', { kind: approval.kind, source: 'dom' });
+ }
+ toNdAudit(approval.kind, t);
+ try { if (b.click) b.click(); } catch (e) {}
}
- if (!hit) continue;
- b.setAttribute('data-nd-auto', '1');
- toNdAudit(kind, t);
- try { if (b.click) b.click(); } catch (e) {}
- return; // 每轮只确认一个,避免连环误触
}
}
function toNdAudit(kind, matched) {
@@ -7562,7 +8345,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;
@@ -7571,11 +8354,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
syncSleepState();
});
}
- // AI 是否正在生成回复(until-done 专用,限定当前会话内,参考 Auto-Continue 的 acActiveConversationId):
- // 只检查「当前激活会话」的生成状态:停止按钮在输入区工具栏(cr-input-toolbar,全局唯一——只有一个
- // 激活会话渲染输入区,不会误判其他会话);reasoning streaming 在消息区内。
- // 返回 { busy, sessionId } —— busy=true 表示锁定的会话仍在生成。
- // scopeId 为空时按当前激活会话判断;锁定会话已切走(不再是激活会话)= 该会话已结束 → 不忙碌。
+ // 旧客户端无控制器时的休眠兜底:只检查当前激活会话的 DOM 信号。
+ // 正常路径由 isAnySessionBusy() 通过所有已发现 ConversationController 判断,
+ // 因此这里只保留兼容旧版 DOM 的最后降级分支。
function isSessionBusy(lockedId) {
try {
var activeId = acActiveConversationId();
@@ -7606,26 +8387,68 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
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
+ // until-done 模式:轮询所有已发现会话;全部结束后自动恢复 allow。
+ var sleepUntilDoneSession = null; // 兼容旧字段;全量模式不再锁定单一会话
+ function discoverSleepSessionBusy() {
+ var controllers = [];
+ try {
+ if (WBS_COMPAT && typeof WBS_COMPAT.findConversationControllers === 'function') {
+ controllers = WBS_COMPAT.findConversationControllers(document) || [];
+ }
+ } catch (_) {}
+ var seen = Object.create(null);
+ var busy = false;
+ var now = Date.now();
+ for (var i = 0; i < controllers.length; i++) {
+ var controller = controllers[i];
+ var id = controller && controller.conversationId ? String(controller.conversationId) : '';
+ if (!id) continue;
+ seen[id] = true;
+ var cached = sleepSessionCache[id] || (sleepSessionCache[id] = { controller: controller, lastSeen: now, wasBusy: false });
+ cached.controller = controller;
+ cached.lastSeen = now;
+ var snapshot = acControllerSnapshot(controller);
+ cached.wasBusy = !!(snapshot && (snapshot.busy || snapshot.blocked || snapshot.hydrating));
+ if (cached.wasBusy) busy = true;
+ }
+ Object.keys(sleepSessionCache).forEach(function (id) {
+ var cached = sleepSessionCache[id];
+ if (seen[id]) return;
+ // Virtualized background conversations may be absent for one scan.
+ if (cached.wasBusy && now - cached.lastSeen < 15000) busy = true;
+ else if (now - cached.lastSeen >= 15000) delete sleepSessionCache[id];
+ });
+ return busy;
+ }
+ function isAnySessionBusy() {
+ var ids = Object.keys(acMulti.sessions);
+ if (ids.length) {
+ for (var i = 0; i < ids.length; i++) {
+ var session = acMulti.sessions[ids[i]];
+ if (session && session.resourceActive) return true;
+ var snapshot = session && session.controller ? acControllerSnapshot(session.controller) : null;
+ if (snapshot && (snapshot.busy || snapshot.blocked || snapshot.hydrating)) return true;
+ }
+ return discoverSleepSessionBusy();
+ }
+ if (discoverSleepSessionBusy()) return true;
+ return !!isSessionBusy(null).busy;
+ }
function startUntilDoneCheck() {
if (sleepUntilDoneCheck) return;
- // 开启时锁定当前激活会话;没有任何会话则视为无需防休眠(直接不启动,由开启校验兜底)
- sleepUntilDoneSession = acActiveConversationId() || null;
+ sleepUntilDoneSession = null;
sleepUntilDoneCheck = setBuildInterval(function () {
if (!alive) { stopUntilDoneCheck(); return; }
if (sleepMode !== 'until-done') { stopUntilDoneCheck(); return; }
- var st = isSessionBusy(sleepUntilDoneSession);
- if (!st.busy) {
- // 锁定的会话已结束(或已切到别的会话/FAB 呼吸灯熄灭)→ 自动恢复允许休眠
+ if (!isAnySessionBusy()) {
+ // 所有已发现会话均结束 → 自动恢复允许休眠
stopUntilDoneCheck();
api('/api/sleep-mode', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ mode: 'allow', displaySleep: false }),
}).then(function () {
- toast('当前会话已完成,已自动恢复「允许电脑休眠」', false, root);
+ toast('所有进行中的会话已完成,已自动恢复「允许电脑休眠」', false, root);
syncSleepState();
}).catch(function () { syncSleepState(); });
}
@@ -7634,6 +8457,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function stopUntilDoneCheck() {
if (sleepUntilDoneCheck) { clearInterval(sleepUntilDoneCheck); sleepUntilDoneCheck = null; }
sleepUntilDoneSession = null;
+ sleepSessionCache = Object.create(null);
}
// 同步防休眠状态:三模式 radio + 显示器开关 + 状态文字 + 悬浮按钮角标(daemon 重启/状态变化后保持一致)
function syncSleepState() {
@@ -7661,8 +8485,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
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 = '当前会话结束允许休眠:本会话回复中保持唤醒,结束后自动恢复' + (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');
@@ -8955,6 +9779,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-telemetry-switch{flex:0 0 36px}',
'.wbs-telemetry-status{margin-top:5px;font-size:10.5px;color:var(--wb-button-primary-bg,#1f1f1f);font-weight:600}',
'.wbs-telemetry-status.is-off{color:var(--wb-icon-tertiary,#999);font-weight:500}',
+ '.wbs-monitor-log-card{padding:7px 12px;margin:2px 0 4px;background:transparent;border:none}',
+ '.wbs-monitor-log-inline{display:flex;flex-direction:column;gap:5px;min-width:0}',
+ '.wbs-monitor-log-session-list{display:flex;flex-direction:column;gap:3px;max-height:92px;overflow-y:auto;overscroll-behavior:contain;padding:1px 0;scrollbar-width:thin}',
+ '.wbs-monitor-log-session-btn{display:block;box-sizing:border-box;width:100%;min-height:25px;padding:4px 7px;border:1px solid var(--wb-border-subtle,#ededed);border-radius:7px;background:var(--wb-bg-secondary,#fafafa);color:var(--wb-icon-secondary,#666);font:600 10.5px/1.25 inherit;text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer;transition:background .15s,border-color .15s,color .15s}',
+ '.wbs-monitor-log-session-btn:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}',
+ '.wbs-monitor-log-session-btn.active{border-color:var(--wb-button-primary-bg,#1f1f1f);background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 10%,var(--wb-bg-secondary,#fafafa));color:var(--wb-color-text-primary,#1f1f1f)}',
+ '.wbs-monitor-log-list{min-height:62px;max-height:154px;overflow-y:auto;overscroll-behavior:contain;padding:5px 7px;border:1px solid var(--wb-border-subtle,#ededed);border-radius:7px;background:color-mix(in srgb,var(--wb-bg-secondary,#fafafa) 65%,transparent);font:10px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--wb-icon-secondary,#666);white-space:pre-wrap;overflow-wrap:anywhere;scrollbar-width:thin}',
+ '.wbs-monitor-log-entry{padding:2px 0;border-bottom:1px solid color-mix(in srgb,var(--wb-border-subtle,#ededed) 70%,transparent);overflow-wrap:anywhere}',
+ '.wbs-monitor-log-entry:last-child{border-bottom:none}',
'.wbs-about-foot{display:flex;align-items:center;justify-content:center;gap:10px;margin-top:10px}',
'.wbs-about-ver{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11px;font-weight:500;color:var(--wb-icon-tertiary,#999);letter-spacing:.3px}',
'.wbs-about-feedback{display:inline-flex;align-items:center;gap:5px;font-size:11.5px;font-weight:600;color:var(--wb-button-primary-bg,#1f1f1f);background:rgba(0,0,0,.05);padding:5px 12px;border-radius:999px;text-decoration:none;transition:background .15s;flex-shrink:0;white-space:nowrap}',
diff --git a/scripts/lib.js b/scripts/lib.js
index c3691e9..f1cc565 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -560,6 +560,45 @@ function getAutoCopySessionMembers(dataDir, lineageId, uid) {
return result;
}
+// Return the de-duplicated account/session pairs for a lineage. The copier
+// needs the uid as well as the id so it can refresh every live account member,
+// not only the account that happened to be active during the switch.
+function getAutoCopySessionMemberRecords(dataDir, lineageId) {
+ const config = readAutoCopyConfig(dataDir);
+ const lineage = config.sessions[String(lineageId || '')];
+ if (!lineage || !Array.isArray(lineage.members)) return [];
+ const seen = new Set();
+ const result = [];
+ for (const member of lineage.members) {
+ const uid = String(member && member.uid || '').trim();
+ const id = String(member && member.id || '').trim();
+ if (!uid || !id) continue;
+ const key = JSON.stringify([uid, id]);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ result.push({ uid, id });
+ }
+ return result;
+}
+
+// Pick the freshest member snapshot. Message files are authoritative; the
+// database timestamp is only a deterministic fallback for legacy/missing
+// files. Ties are resolved by member order so repeated switches stay stable.
+function selectLatestAutoCopyMember(members) {
+ if (!Array.isArray(members) || !members.length) return null;
+ let best = null;
+ members.forEach((member, index) => {
+ if (!member || !member.id) return;
+ const contentMtime = Number(member.contentMtime || 0);
+ const updatedAt = Number(member.updatedAt || 0);
+ if (!best || contentMtime > best.contentMtime ||
+ (contentMtime === best.contentMtime && updatedAt > best.updatedAt)) {
+ best = Object.assign({ memberIndex: index }, member, { contentMtime, updatedAt });
+ }
+ });
+ return best ? members[best.memberIndex] : null;
+}
+
function ensureAutoCopySession(dataDir, uid, sessionId) {
const meta = readMeta(dataDir);
const config = ensureAutoCopyMeta(meta);
@@ -1050,6 +1089,8 @@ module.exports = {
setAutoCopyRule,
getAutoCopySession,
getAutoCopySessionMembers,
+ getAutoCopySessionMemberRecords,
+ selectLatestAutoCopyMember,
ensureAutoCopySession,
addAutoCopySessionMember,
removeAutoCopySessionMember,
diff --git a/scripts/make-icon.py b/scripts/make-icon.py
index f38a558..e5c62d1 100644
--- a/scripts/make-icon.py
+++ b/scripts/make-icon.py
@@ -1,58 +1,113 @@
-#!/usr/bin/env python
-"""
-从 macOS AppIcon.icns 抽取的 PNG 图层,合成 Windows 多分辨率 .ico
-ICO 支持直接把 PNG 作为条目数据(Windows Vista+),因此无需解码 PNG。
-产出 release/WorkDaddy.ico,供桌面快捷方式 / 启动器使用。
-"""
-import os, struct
-
-ICON_DIR = os.path.join(os.path.dirname(__file__), "..", ".workbuddy", "tmp_icon")
-OUT = os.path.join(os.path.dirname(__file__), "..", "release", "WorkDaddy.ico")
-
-# (ico尺寸, 源png文件名) —— 从 icns 抽出、且尺寸匹配
-ENTRIES = [
- (16, "ic11.png"),
- (32, "ic12.png"),
- (48, "ic12.png"), # 无 48 直接用 32 拉伸?ICO 无法自动拉伸,用同 32 会糊;改用 128
- (256, "ic13.png"),
-]
-# 修正 48 -> 用 64/128 里没有;真实可用:32/256/512/1024。48 需要缩放,无 PIL 就跳过,
-# 用 32 重复会失真。改为:16,32,256,512 由 Windows 自动缩放。
-
-ENTRIES = [
- (16, "ic11.png"),
- (32, "ic12.png"),
- (256, "ic13.png"),
- (512, "ic09.png"),
-]
+#!/usr/bin/env python3
+"""Build the macOS and Windows application icons from one foreground PNG."""
+
+import os
+import shutil
+import subprocess
+import tempfile
+
+
+ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
+SOURCE = os.path.join(ROOT, 'scripts', 'assets', 'workdaddy-icon-foreground.png')
+MAC_OUT = os.path.join(ROOT, 'scripts', 'assets', 'WorkDaddy.icns')
+WIN_OUT = os.path.join(ROOT, 'release', 'WorkDaddy.ico')
+BACKGROUND = '#e1e1e1'
+WINDOWS_CORNER_RADIUS_RATIO = 0.20
+ICON_SIZES = [16, 32, 64, 128, 256, 512, 1024]
+
+
+def run(*args):
+ subprocess.run(args, check=True)
+
+
+def require_tool(name):
+ path = shutil.which(name)
+ if not path:
+ raise SystemExit(f'missing required tool: {name}')
+ return path
+
+
+def render_base(magick, output, rounded, with_background=True):
+ canvas = f'xc:{BACKGROUND}' if with_background else 'xc:none'
+ args = [
+ magick,
+ '-size', '1024x1024', canvas,
+ SOURCE,
+ '-compose', 'over', '-composite',
+ ]
+ if rounded:
+ radius = round(1024 * WINDOWS_CORNER_RADIUS_RATIO)
+ args += [
+ '(', '-size', '1024x1024', 'xc:none', '-fill', 'white',
+ '-draw', f'roundrectangle 0,0 1023,1023 {radius},{radius}', ')',
+ '-alpha', 'off', '-compose', 'CopyOpacity', '-composite',
+ ]
+ # iconutil expects full RGBA PNGs; grayscale-alpha inputs can collapse to a
+ # single low-resolution icns layer and make macOS show its generic wrapper.
+ args += ['-alpha', 'on', '-colorspace', 'sRGB', '-type', 'TrueColorAlpha']
+ args.append(output)
+ run(*args)
+
+
+def render_size(magick, source, size, output):
+ run(
+ magick,
+ source,
+ '-filter', 'Lanczos',
+ '-resize', f'{size}x{size}',
+ '-alpha', 'on', '-colorspace', 'sRGB', '-type', 'TrueColorAlpha',
+ output,
+ )
+
+
+def build_mac_icon(magick, iconutil, temp_dir):
+ base = os.path.join(temp_dir, 'mac-base.png')
+ iconset = os.path.join(temp_dir, 'AppIcon.iconset')
+ os.makedirs(iconset)
+ # macOS supplies the standard rounded app background. Supplying another
+ # background here creates a visible nested square in Finder/Get Info.
+ render_base(magick, base, rounded=False, with_background=False)
+ iconset_entries = [
+ ('icon_16x16.png', 16),
+ ('icon_32x32.png', 32),
+ ('icon_128x128.png', 128),
+ ('[email protected]', 256),
+ ('icon_256x256.png', 256),
+ ('[email protected]', 512),
+ ('icon_512x512.png', 512),
+ ('[email protected]', 1024),
+ ]
+ for name, size in iconset_entries:
+ render_size(magick, base, size, os.path.join(iconset, name))
+ os.makedirs(os.path.dirname(MAC_OUT), exist_ok=True)
+ run(iconutil, '-c', 'icns', iconset, '-o', MAC_OUT)
+
+
+def build_windows_icon(magick, temp_dir):
+ base = os.path.join(temp_dir, 'windows-base.png')
+ render_base(magick, base, rounded=True)
+ pngs = []
+ for size in ICON_SIZES:
+ output = os.path.join(temp_dir, f'windows-{size}.png')
+ render_size(magick, base, size, output)
+ pngs.append(output)
+ os.makedirs(os.path.dirname(WIN_OUT), exist_ok=True)
+ run(magick, *pngs, '-colors', '256', WIN_OUT)
+
def main():
- # 读取所有条目 PNG
- datas = []
- for size, name in ENTRIES:
- p = os.path.join(ICON_DIR, name)
- b = open(p, "rb").read()
- # 校验 PNG 尺寸
- w, h = struct.unpack(">II", b[16:24])
- assert w == h == size, f"{name} is {w}x{h}, expected {size}"
- datas.append((size, b))
-
- # ICO header
- header = struct.pack("<HHH", 0, 1, len(datas))
- # dir entries: width,height(0=256),colorcount,reserved,planes,bitcount,bytesinres,offset
- offset = 6 + 16 * len(datas)
- entries = b""
- for size, b in datas:
- wbyte = 0 if size >= 256 else size
- hbyte = 0 if size >= 256 else size
- entries += struct.pack("<BBBBHHII", wbyte, hbyte, 0, 0, 1, 32, len(b), offset)
- offset += len(b)
-
- out = header + entries + b"".join(b for _, b in datas)
- os.makedirs(os.path.dirname(OUT), exist_ok=True)
- with open(OUT, "wb") as f:
- f.write(out)
- print("ICO written:", os.path.abspath(OUT), os.path.getsize(OUT), "bytes, entries:", [s for s, _ in datas])
-
-if __name__ == "__main__":
+ if not os.path.isfile(SOURCE):
+ raise SystemExit(f'missing icon foreground: {SOURCE}')
+ magick = require_tool('magick')
+ iconutil = require_tool('iconutil')
+ with tempfile.TemporaryDirectory(prefix='workdaddy-icon-') as temp_dir:
+ build_mac_icon(magick, iconutil, temp_dir)
+ build_windows_icon(magick, temp_dir)
+ print(f'macOS icon: {MAC_OUT}')
+ print(f'Windows icon: {WIN_OUT}')
+
+
+if __name__ == '__main__':
main()
diff --git a/scripts/profiles.js b/scripts/profiles.js
index de4801d..8789449 100644
--- a/scripts/profiles.js
+++ b/scripts/profiles.js
@@ -3,6 +3,7 @@
const fs = require('fs');
const os = require('os');
const path = require('path');
+const { readWorkBuddyTarget } = require('./workbuddy-target.js');
const home = os.homedir();
const IS_WIN = process.platform === 'win32';
@@ -76,9 +77,51 @@ const PROFILES = {
},
};
-function getProfile(id = process.env.WBSWITCH_PROFILE || 'workbuddy-cn') {
+function applyWorkBuddyTarget(profile, target) {
+ if (!target || !target.configured || !target.binary) return profile;
+ if (target.clientType === 'official') {
+ return {
+ ...profile,
+ appPath: target.binary,
+ binaryNames: target.processNames || [path.basename(target.binary)],
+ cdp: target.cdp || { mode: 'argument' },
+ configuredTarget: true,
+ customTarget: false,
+ targetVersion: target.version || '',
+ lockTargetVersion: target.lockVersion === true,
+ };
+ }
+ return {
+ ...profile,
+ appPath: target.binary,
+ ...(target.dataRoot ? { dataRoot: target.dataRoot } : {}),
+ authFile: target.authFile || null,
+ ...(target.sessionDb ? { sessionDb: target.sessionDb } : {}),
+ ...(target.modelsFile ? { modelsFile: target.modelsFile } : {}),
+ apiHost: target.apiHost || '',
+ capabilities: { ...profile.capabilities, ...(target.capabilities || {}) },
+ targetHints: [...(target.targetHints || [])],
+ binaryNames: target.processNames || [target.processName || path.basename(target.binary)],
+ cdp: target.cdp || { mode: 'argument' },
+ configuredTarget: true,
+ customTarget: true,
+ targetVersion: target.version || '',
+ lockTargetVersion: target.lockVersion === true,
+ };
+}
+
+function getProfile(id = process.env.WBSWITCH_PROFILE || 'workbuddy-cn', options = {}) {
const key = String(id || '').trim().toLowerCase();
- if (PROFILES[key]) return PROFILES[key];
+ if (PROFILES[key]) {
+ const base = PROFILES[key];
+ if (base.kind !== 'workbuddy') return base;
+ const platform = options.platform || process.platform;
+ if (platform !== 'win32') return base;
+ const env = options.env || process.env;
+ const dataDir = options.dataDir || env.WBSWITCH_DATA_DIR || profileDataDir(base);
+ const target = readWorkBuddyTarget({ dataDir, profileId: key, env, platform });
+ return applyWorkBuddyTarget(base, target);
+ }
throw new Error(`未知客户端 profile: ${id}`);
}
@@ -114,4 +157,4 @@ function profileDataDir(profile, configured) {
return path.join(sharedDataDir(), 'profiles', profile.id);
}
-module.exports = { PROFILES, getProfile, listProfiles, listInstalledModelSources, profileDataDir, sharedDataDir };
+module.exports = { PROFILES, applyWorkBuddyTarget, getProfile, listProfiles, listInstalledModelSources, profileDataDir, sharedDataDir };
diff --git a/scripts/win-launcher.js b/scripts/win-launcher.js
index 1dd876e..4b980be 100644
--- a/scripts/win-launcher.js
+++ b/scripts/win-launcher.js
@@ -76,7 +76,7 @@ const PROFILE_CDP_PORTS = {
'codebuddy-cn': [9224],
'codebuddy-intl': [9225],
};
-const DEFAULT_CDP_PORT = (PROFILE_CDP_PORTS[PROFILE.id] || [9222])[0];
+const DEFAULT_CDP_PORT = Number(PROFILE.cdp && PROFILE.cdp.port) || (PROFILE_CDP_PORTS[PROFILE.id] || [9222])[0];
const cliCdpPort = process.argv.find((arg) => /^--cdp-port=\d+$/i.test(arg));
const HAS_EXPLICIT_CDP_PORT = Boolean(process.env.WBSWITCH_CDP_PORT || cliCdpPort);
let CDP_PORT = parseInt(process.env.WBSWITCH_CDP_PORT || (cliCdpPort ? cliCdpPort.split('=')[1] : '') || String(DEFAULT_CDP_PORT), 10);
@@ -90,14 +90,10 @@ const INJECT_REQUEST_TIMEOUT_MS = 5000;
const INJECT_MAX_ATTEMPTS = 6;
const INJECT_RETRY_DELAY_MS = 1000;
// 每个 profile 只查询自己的主程序镜像;其他 CodeBuddy/WorkBuddy profile 不参与退出判定。
-const PROFILE_PROCESS_NAMES = new Set(
- PROFILE.id === 'workbuddy-ai' ? ['workbuddyai.exe'] :
- PROFILE.id === 'workbuddy-cn' ? ['workbuddy.exe'] : ['codebuddy.exe']
-);
-const PROFILE_BINARY_NAMES = new Set(
- PROFILE.id === 'workbuddy-ai' ? ['workbuddyai.exe'] :
- PROFILE.id === 'workbuddy-cn' ? ['workbuddy.exe'] : ['codebuddy.exe']
-);
+const PROFILE_BINARY_NAME_LIST = PROFILE.binaryNames || (PROFILE.id === 'workbuddy-ai' ? ['workbuddyai.exe'] :
+ PROFILE.id === 'workbuddy-cn' ? ['workbuddy.exe'] : ['codebuddy.exe']);
+const PROFILE_PROCESS_NAMES = new Set(PROFILE_BINARY_NAME_LIST.map((name) => String(name).toLowerCase()));
+const PROFILE_BINARY_NAMES = new Set(PROFILE_BINARY_NAME_LIST.map((name) => String(name).toLowerCase()));
function log(...args) {
const line = `[launcher] ${new Date().toISOString()} [client=${PROFILE.name}] [profile=${PROFILE.id}] ${args.join(' ')}\n`;
@@ -412,7 +408,9 @@ function workBuddyProcesses(binary = null) {
// not the user-facing app and must not block a cold launch or be terminated.
const processes = getWorkBuddyProcesses().filter((process) => !isPrewarmProcess(process));
if (!binary) return processes;
- const verified = filterVerifiedWindowsProcesses(binary, processes);
+ const verified = filterVerifiedWindowsProcesses(
+ binary, processes, fs.realpathSync.native, PROFILE.customTarget ? PROFILE_BINARY_NAMES : null
+ );
if (processes.length !== verified.length) {
throw new Error('存在当前 profile 进程,但没有进程属于已验证安装目录,请先手动退出后重试');
}
@@ -1109,9 +1107,13 @@ async function quitWorkBuddy(binary) {
}
function launchWorkBuddy(wb) {
- const args = '--remote-debugging-port=' + CDP_PORT;
- const child = spawn(wb, [args], {
- cwd: path.dirname(wb), detached: true, stdio: 'ignore', windowsHide: true,
+ const environmentMode = !!(PROFILE.cdp && PROFILE.cdp.mode === 'environment');
+ const args = environmentMode ? [] : ['--remote-debugging-port=' + CDP_PORT];
+ const env = environmentMode
+ ? { ...process.env, WORKBUDDY_REMOTE_DEBUGGING_PORT: String(CDP_PORT) }
+ : process.env;
+ const child = spawn(wb, args, {
+ cwd: path.dirname(wb), detached: true, stdio: 'ignore', windowsHide: true, env,
});
const state = { method: 'node-spawn', pid: Number.isSafeInteger(child.pid) ? child.pid : null, errorCode: null, exitCode: null, signal: null };
child.on('error', (e) => {
@@ -1161,7 +1163,8 @@ async function waitForWorkBuddyCdp(binary) {
continue;
}
}
- if (hasProcessWithoutArg && elapsed >= 5000 && !retryWithoutCdpArg) {
+ if (!(PROFILE.cdp && PROFILE.cdp.mode === 'environment') &&
+ hasProcessWithoutArg && elapsed >= 5000 && !retryWithoutCdpArg) {
// 单实例宿主可能接管了第一次启动请求;精确结束该安装目录的进程树后只重试一次。
logProcessDiagnostics(binary, '启动后进程未携带 CDP 参数,准备重试');
retryWithoutCdpArg = true;
@@ -1258,6 +1261,28 @@ function runNativeHelper(args, options = {}) {
return result;
}
+function comparableVersion(value) {
+ const parts = String(value || '').trim().split('.').map((part) => Number(part));
+ if (!parts.length || parts.some((part) => !Number.isInteger(part) || part < 0)) return '';
+ while (parts.length > 2 && parts[parts.length - 1] === 0) parts.pop();
+ return parts.join('.');
+}
+
+function nativeFileVersion(binary) {
+ const result = runNativeHelper(['--file-version', '--binary', binary], { timeout: 10000 });
+ if (result.status !== 0) return '';
+ return String(result.stdout || '').trim();
+}
+
+function verifyConfiguredWorkBuddyVersion(binary) {
+ if (!PROFILE.configuredTarget || !PROFILE.lockTargetVersion || !PROFILE.targetVersion) return;
+ const actual = nativeFileVersion(binary);
+ if (!actual) throw new Error('无法读取所选 WorkBuddy 的版本,已停止启动;请重新运行 WorkDaddy 安装程序确认客户端路径');
+ if (comparableVersion(actual) !== comparableVersion(PROFILE.targetVersion)) {
+ throw new Error(`所选 WorkBuddy 版本已变化(期望 ${PROFILE.targetVersion},实际 ${actual}),请重新运行 WorkDaddy 安装程序确认新版本`);
+ }
+}
+
let nativeDiscoveryState = null;
let nativeWatchdogAttempts = [];
let nativeLaunchState = null;
@@ -1296,6 +1321,13 @@ function nativeWorkBuddyRunning() {
return false;
}
+function stopNativeWorkBuddy() {
+ const result = runNativeHelper(['--terminate-workbuddy', '--profile', PROFILE.id], { timeout: 60000 });
+ if (result.status !== 0) {
+ throw new Error('无法精确重启当前 WorkBuddy(错误码 ' + result.status + ')');
+ }
+}
+
function findWorkBuddyNative() {
const candidates = [];
const summary = {
@@ -1333,11 +1365,12 @@ function findWorkBuddyNative() {
const local = process.env.LOCALAPPDATA || '';
const programFiles = process.env.ProgramFiles || '';
const programFilesX86 = process.env['ProgramFiles(x86)'] || '';
- const expectedName = PROFILE.id === 'workbuddy-ai' ? 'WorkBuddyAI.exe' : 'WorkBuddy.exe';
+ const expectedNames = [...PROFILE_BINARY_NAMES];
+ const expectedName = expectedNames[0];
if (process.env.WBSWITCH_WORKBUDDY_DIR) {
- add(path.join(process.env.WBSWITCH_WORKBUDDY_DIR, expectedName), 'explicit');
+ for (const name of expectedNames) add(path.join(process.env.WBSWITCH_WORKBUDDY_DIR, name), 'explicit');
}
- const appPathNames = PROFILE.id === 'workbuddy-ai' ? ['WorkBuddyAI.exe'] : ['WorkBuddy.exe'];
+ const appPathNames = PROFILE.customTarget ? [] : (PROFILE.id === 'workbuddy-ai' ? ['WorkBuddyAI.exe'] : ['WorkBuddy.exe']);
const appPathKeys = [];
for (const name of appPathNames) {
appPathKeys.push(`HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\${name}`);
@@ -1378,7 +1411,8 @@ function findWorkBuddyNative() {
for (const item of candidates) {
try {
if (!fs.statSync(item.path).isFile()) continue;
- if (path.win32.basename(item.path).toLowerCase() !== expectedName.toLowerCase()) continue;
+ if (!PROFILE_BINARY_NAMES.has(path.win32.basename(item.path).toLowerCase())) continue;
+ if (PROFILE.customTarget && !sameWindowsPath(path.win32.dirname(item.path), path.win32.dirname(PROFILE.appPath))) continue;
summary.validCandidateCount += 1;
summary.selectedSource = item.source;
summary.completed = true;
@@ -1539,10 +1573,15 @@ async function ensureDaemonNative(nodeBin) {
}
async function waitForWorkBuddyCdpNative(binary) {
- const launched = launchWorkBuddy(binary);
- nativeLaunchState = launched;
- log('WorkBuddy 启动请求已派发 method=' + launched.method + ' expectedPort=' + CDP_PORT +
- (launched.pid ? ' pid=' + launched.pid : ''));
+ let restartedAfterHandoff = false;
+ let launchStartedAt = 0;
+ const start = () => {
+ nativeLaunchState = launchWorkBuddy(binary);
+ launchStartedAt = Date.now();
+ log('WorkBuddy 启动请求已派发 method=' + nativeLaunchState.method + ' expectedPort=' + CDP_PORT +
+ (nativeLaunchState.pid ? ' pid=' + nativeLaunchState.pid : ''));
+ };
+ start();
const deadline = Date.now() + CDP_STARTUP_TIMEOUT_MS;
while (Date.now() < deadline) {
await sleep(1000);
@@ -1554,10 +1593,45 @@ async function waitForWorkBuddyCdpNative(binary) {
return true;
}
}
+ if (nativeLaunchFailed(nativeLaunchState)) {
+ if (!restartedAfterHandoff && nativeWorkBuddyRunning()) {
+ restartedAfterHandoff = true;
+ log('WorkBuddy 启动进程异常退出但同 profile 进程仍在运行,精确停止后重试一次');
+ stopNativeWorkBuddy();
+ await sleep(1000);
+ start();
+ continue;
+ }
+ const error = new Error('WorkBuddy 启动进程异常退出' +
+ (nativeLaunchState.errorCode ? '(' + nativeLaunchState.errorCode + ')' : '(退出码 ' + nativeLaunchState.exitCode + ')'));
+ error.sentryStage = 'windows-native-launcher-workbuddy-exit';
+ error.sentryExtra = {
+ cdpPort: CDP_PORT,
+ launch: { ...nativeLaunchState },
+ processes: nativeWorkBuddyProcessSummary(),
+ discovery: nativeWorkBuddyDiscoverySummary(),
+ };
+ throw error;
+ }
+ if (!restartedAfterHandoff && Number.isInteger(nativeLaunchState && nativeLaunchState.exitCode) &&
+ Date.now() - launchStartedAt >= 5000 && nativeWorkBuddyRunning()) {
+ restartedAfterHandoff = true;
+ log('WorkBuddy 启动请求已被无 CDP 的单实例接管,精确停止后重试一次');
+ stopNativeWorkBuddy();
+ await sleep(1000);
+ start();
+ }
}
return false;
}
+function nativeLaunchFailed(state) {
+ return Boolean(state && (
+ state.errorCode ||
+ (Number.isInteger(state.exitCode) && state.exitCode !== 0)
+ ));
+}
+
async function nativeStartupMain() {
try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (_) {}
log('原生启动入口: scripts=' + SCRIPTS_DIR + ' data=' + DATA_DIR + ' pid=' + process.pid);
@@ -1566,6 +1640,20 @@ async function nativeStartupMain() {
await configureCdpPort();
await configureUiPort();
+ verifyConfiguredWorkBuddyVersion(PROFILE.appPath);
+ let wb = null;
+ if (!(await isWorkBuddyCdp())) {
+ wb = findWorkBuddyNative();
+ if (!wb) {
+ const error = new Error('未找到安装时选择的 WorkBuddy 客户端;请重新运行 WorkDaddy 安装程序修改路径');
+ error.sentryStage = 'windows-native-launcher-workbuddy-path';
+ error.sentryExtra = {
+ discovery: nativeWorkBuddyDiscoverySummary(),
+ processes: nativeWorkBuddyProcessSummary(),
+ };
+ throw error;
+ }
+ }
await ensureDaemonNative(nodeBin);
if (await isWorkBuddyCdp()) {
@@ -1574,19 +1662,10 @@ async function nativeStartupMain() {
return 0;
}
- const wb = findWorkBuddyNative();
- if (!wb) {
- const error = new Error('未找到 WorkBuddy,请先安装对应客户端');
- error.sentryStage = 'windows-native-launcher-workbuddy-path';
- error.sentryExtra = {
- discovery: nativeWorkBuddyDiscoverySummary(),
- processes: nativeWorkBuddyProcessSummary(),
- };
- throw error;
- }
if (nativeWorkBuddyRunning()) {
- log('WorkBuddy 已运行但没有 CDP,交给原生启动器提示用户手动退出');
- return 10;
+ log('WorkBuddy 已运行但没有 CDP,按当前 profile 的唯一真实路径精确重启');
+ stopNativeWorkBuddy();
+ await sleep(1000);
}
const ok = await waitForWorkBuddyCdpNative(wb);
@@ -1697,6 +1776,7 @@ if (require.main === module && process.env.WBSWITCH_NATIVE_LAUNCHER === '1') {
});
module.exports = {
+ nativeLaunchFailed,
strictPowerShellLines,
getWorkBuddyProcesses,
workBuddyProcesses,
diff --git a/scripts/win/workdaddy.iss b/scripts/win/workdaddy.iss
index 00e2aa1..d4a6f98 100644
--- a/scripts/win/workdaddy.iss
+++ b/scripts/win/workdaddy.iss
@@ -58,12 +58,17 @@ Name: "chinesesimplified"; MessagesFile: "ChineseSimplified.isl"
[Files]
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\WorkDaddy.ico"; DestDir: "{app}\scripts"; DestName: "{#PackageName}-{#AppVersion}.ico"; Flags: ignoreversion
+Source: "{#StageRoot}\scripts\*"; DestDir: "{app}\scripts"; Excludes: "runtime\node\*,WorkDaddy.ico"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#StageRoot}\scripts\runtime\node\*"; DestDir: "{app}\scripts\runtime\node"; Flags: ignoreversion recursesubdirs createallsubdirs
+[InstallDelete]
+Type: files; Name: "{app}\scripts\WorkDaddy.ico"
+Type: files; Name: "{app}\scripts\WorkDaddy-*.ico"
+
[Icons]
-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"
+Name: "{group}\{#ProductName}"; Filename: "{app}\WorkDaddyLauncher.exe"; WorkingDir: "{app}"; IconFilename: "{app}\scripts\{#PackageName}-{#AppVersion}.ico"
+Name: "{userdesktop}\{#ProductName}"; Filename: "{app}\WorkDaddyLauncher.exe"; WorkingDir: "{app}"; IconFilename: "{app}\scripts\{#PackageName}-{#AppVersion}.ico"
[Registry]
Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: none; ValueName: "WorkDaddy"; Flags: deletevalue
@@ -79,12 +84,21 @@ Filename: "{app}\WorkDaddyLauncher.exe"; Parameters: "--stop-lifecycle --profile
Type: filesandordirs; Name: "{app}"
[Code]
+var
+ ClientPage: TInputFileWizardPage;
+ ClientSourceLabel: TNewStaticText;
+ ClientVersionLabel: TNewStaticText;
+ UseDetectedButton: TNewButton;
+ DetectedOfficialPath: String;
+ SelectedWorkBuddyPath: String;
+ SelectedWorkBuddyVersion: String;
+
function RunNativeHelper(const Mode: String; var ResultCode: Integer): Boolean;
var
Parameters: String;
begin
ExtractTemporaryFile('WorkDaddyLauncher.exe');
- Parameters := Mode + ' --profile "{#ProfileId}" --app-dir "' + ExpandConstant('{app}') + '"';
+ Parameters := Mode + ' --profile "{#ProfileId}"';
Result := ExecAsOriginalUser(
ExpandConstant('{tmp}\WorkDaddyLauncher.exe'),
Parameters,
@@ -95,6 +109,429 @@ begin
);
end;
+function ExpectedWorkBuddyName(): String;
+begin
+ if '{#ProfileId}' = 'workbuddy-ai' then
+ Result := 'WorkBuddyAI.exe'
+ else
+ Result := 'WorkBuddy.exe';
+end;
+
+function UsableClientFile(const Candidate: String): Boolean;
+begin
+ Result := (Candidate <> '') and FileExists(Candidate) and
+ (CompareText(ExtractFileExt(Candidate), '.exe') = 0);
+end;
+
+function OfficialClientFile(const Candidate: String): Boolean;
+begin
+ Result := UsableClientFile(Candidate) and
+ (CompareText(ExtractFileName(Candidate), ExpectedWorkBuddyName()) = 0);
+end;
+
+function NextVersionComponent(const Version: String; var Offset: Integer): Integer;
+var
+ StartAt: Integer;
+ SeparatorAt: Integer;
+ Remaining: String;
+begin
+ if Offset > Length(Version) then
+ begin
+ Result := 0;
+ exit;
+ end;
+ StartAt := Offset;
+ Remaining := Copy(Version, StartAt, Length(Version) - StartAt + 1);
+ SeparatorAt := Pos('.', Remaining);
+ if SeparatorAt = 0 then
+ begin
+ Result := StrToIntDef(Remaining, 0);
+ Offset := Length(Version) + 1;
+ end
+ else
+ begin
+ Result := StrToIntDef(Copy(Remaining, 1, SeparatorAt - 1), 0);
+ Offset := StartAt + SeparatorAt;
+ end;
+end;
+
+function CompareVersionStrings(const LeftVersion: String; const RightVersion: String): Integer;
+var
+ Index: Integer;
+ LeftOffset: Integer;
+ RightOffset: Integer;
+ LeftPart: Integer;
+ RightPart: Integer;
+begin
+ LeftOffset := 1;
+ RightOffset := 1;
+ Result := 0;
+ for Index := 0 to 3 do
+ begin
+ LeftPart := NextVersionComponent(LeftVersion, LeftOffset);
+ RightPart := NextVersionComponent(RightVersion, RightOffset);
+ if LeftPart > RightPart then
+ begin
+ Result := 1;
+ exit;
+ end;
+ if LeftPart < RightPart then
+ begin
+ Result := -1;
+ exit;
+ end;
+ end;
+end;
+
+function CompareClientFileVersions(const LeftPath: String; const RightPath: String): Integer;
+var
+ LeftVersion: String;
+ RightVersion: String;
+begin
+ LeftVersion := '';
+ RightVersion := '';
+ GetVersionNumbersString(LeftPath, LeftVersion);
+ GetVersionNumbersString(RightPath, RightVersion);
+ Result := CompareVersionStrings(LeftVersion, RightVersion);
+end;
+
+procedure ConsiderClientCandidate(const Candidate: String; var BestCandidate: String);
+begin
+ if not OfficialClientFile(Candidate) then
+ exit;
+ Log(Format('WorkDaddy installer candidate: %s (version comparison target: %s)', [Candidate, BestCandidate]));
+ if (BestCandidate = '') or
+ (CompareClientFileVersions(Candidate, BestCandidate) > 0) then
+ BestCandidate := Candidate;
+end;
+
+function ExecutableFromDisplayIcon(const DisplayIcon: String): String;
+var
+ Value: String;
+ Marker: Integer;
+ Index: Integer;
+begin
+ Result := '';
+ Value := Trim(DisplayIcon);
+ if Value = '' then
+ exit;
+ if Value[1] = '"' then
+ begin
+ Delete(Value, 1, 1);
+ Marker := Pos('"', Value);
+ if Marker > 0 then
+ Value := Copy(Value, 1, Marker - 1);
+ end;
+ Value := Trim(Value);
+ Marker := 0;
+ for Index := Length(Value) downto 1 do
+ begin
+ if Value[Index] = ',' then
+ begin
+ Marker := Index;
+ break;
+ end;
+ end;
+ if (Marker > 0) and
+ (CompareText(ExtractFileExt(Copy(Value, 1, Marker - 1)), '.exe') = 0) then
+ Value := Copy(Value, 1, Marker - 1);
+ Result := Trim(Value);
+end;
+
+procedure ConsiderUninstallClients(const RootKey: Integer; const BaseKey: String;
+ var BestCandidate: String);
+var
+ Names: TArrayOfString;
+ Index: Integer;
+ Key: String;
+ Value: String;
+ Candidate: String;
+begin
+ if not RegGetSubkeyNames(RootKey, BaseKey, Names) then
+ begin
+ Log(Format('WorkDaddy installer could not enumerate uninstall root %d', [RootKey]));
+ exit;
+ end;
+ Log(Format('WorkDaddy installer scanning uninstall root %d (%d entries)', [RootKey, GetArrayLength(Names)]));
+ for Index := 0 to GetArrayLength(Names) - 1 do
+ begin
+ Key := BaseKey + '\' + Names[Index];
+ Candidate := '';
+ if RegQueryStringValue(RootKey, Key, 'DisplayIcon', Value) then
+ begin
+ Candidate := ExecutableFromDisplayIcon(Value);
+ if Pos(Lowercase(ExpectedWorkBuddyName()), Lowercase(Value)) > 0 then
+ begin
+ if FileExists(Candidate) then
+ Log('WorkDaddy installer parsed uninstall DisplayIcon: ' + Candidate)
+ else
+ Log('WorkDaddy installer parsed missing uninstall DisplayIcon: ' + Candidate);
+ end;
+ end;
+ if not OfficialClientFile(Candidate) then
+ begin
+ if RegQueryStringValue(RootKey, Key, 'InstallLocation', Value) then
+ Candidate := AddBackslash(Trim(Value)) + ExpectedWorkBuddyName()
+ else
+ Candidate := '';
+ end;
+ ConsiderClientCandidate(Candidate, BestCandidate);
+ end;
+end;
+
+function ReadSavedClient(var Binary: String; var Version: String;
+ var ClientType: String): Boolean;
+var
+ ResultCode: Integer;
+ InfoFile: String;
+ Lines: TArrayOfString;
+begin
+ Result := False;
+ InfoFile := ExpandConstant('{tmp}\workbuddy-target-info.txt');
+ DeleteFile(InfoFile);
+ if not RunNativeHelper('--target-info --output "' + InfoFile + '"', ResultCode) then
+ exit;
+ if (ResultCode <> 0) or (not LoadStringsFromFile(InfoFile, Lines)) or
+ (GetArrayLength(Lines) < 1) then
+ exit;
+ Binary := Trim(Lines[0]);
+ if GetArrayLength(Lines) > 1 then
+ Version := Trim(Lines[1])
+ else
+ Version := '';
+ if GetArrayLength(Lines) > 2 then
+ ClientType := Trim(Lines[2])
+ else
+ ClientType := '';
+ { Keep a missing saved path visible so an update cannot silently switch an
+ enterprise user back to the official client. The page will require them
+ to browse to the new location before installation continues. }
+ Result := Binary <> '';
+end;
+
+function DetectOfficialClient(var Binary: String): Boolean;
+var
+ Name: String;
+ Key: String;
+ Value: String;
+ Candidate: String;
+ Candidates: TArrayOfString;
+ Index: Integer;
+begin
+ Result := False;
+ Name := ExpectedWorkBuddyName();
+ Candidate := '';
+
+ ConsiderUninstallClients(HKCU,
+ 'Software\Microsoft\Windows\CurrentVersion\Uninstall', Candidate);
+ if IsWin64 then
+ ConsiderUninstallClients(HKLM64,
+ 'Software\Microsoft\Windows\CurrentVersion\Uninstall', Candidate);
+ ConsiderUninstallClients(HKLM32,
+ 'Software\Microsoft\Windows\CurrentVersion\Uninstall', Candidate);
+
+ Key := 'Software\Microsoft\Windows\CurrentVersion\App Paths\' + Name;
+ if RegQueryStringValue(HKCU, Key, '', Value) then
+ ConsiderClientCandidate(Value, Candidate);
+ if IsWin64 and RegQueryStringValue(HKLM64, Key, '', Value) then
+ ConsiderClientCandidate(Value, Candidate);
+ if RegQueryStringValue(HKLM32, Key, '', Value) then
+ ConsiderClientCandidate(Value, Candidate);
+
+ SetArrayLength(Candidates, 5);
+ if '{#ProfileId}' = 'workbuddy-ai' then
+ begin
+ Candidates[0] := ExpandConstant('{localappdata}\Programs\WorkBuddyAI\' + Name);
+ Candidates[1] := ExpandConstant('{localappdata}\Programs\WorkBuddy AI\' + Name);
+ Candidates[2] := ExpandConstant('{pf}\WorkBuddyAI\' + Name);
+ Candidates[3] := ExpandConstant('{pf}\WorkBuddy AI\' + Name);
+ Candidates[4] := ExpandConstant('{pf32}\WorkBuddyAI\' + Name);
+ end
+ else
+ begin
+ Candidates[0] := ExpandConstant('{localappdata}\Programs\WorkBuddy\' + Name);
+ Candidates[1] := ExpandConstant('{localappdata}\WorkBuddy\' + Name);
+ Candidates[2] := ExpandConstant('{pf}\WorkBuddy\' + Name);
+ Candidates[3] := ExpandConstant('{pf32}\WorkBuddy\' + Name);
+ Candidates[4] := ExpandConstant('{userappdata}\WorkBuddy\' + Name);
+ end;
+ for Index := 0 to GetArrayLength(Candidates) - 1 do
+ ConsiderClientCandidate(Candidates[Index], Candidate);
+
+ Binary := Candidate;
+ Result := Binary <> '';
+ if Result then
+ Log('WorkDaddy installer selected official client: ' + Binary)
+ else
+ Log('WorkDaddy installer did not find an official client for ' + Name);
+end;
+
+function PreferDetectedOfficialClient(const SavedPath: String;
+ const SavedClientType: String; const DetectedPath: String): Boolean;
+begin
+ Result := False;
+ if (CompareText(SavedClientType, 'official') <> 0) or
+ (not OfficialClientFile(DetectedPath)) then
+ exit;
+ Result := (not UsableClientFile(SavedPath)) or
+ (CompareClientFileVersions(DetectedPath, SavedPath) > 0);
+end;
+
+procedure UpdateClientDetails();
+var
+ Candidate: String;
+begin
+ Candidate := Trim(ClientPage.Values[0]);
+ SelectedWorkBuddyVersion := '';
+ if UsableClientFile(Candidate) and GetVersionNumbersString(Candidate, SelectedWorkBuddyVersion) then
+ ClientVersionLabel.Caption := '检测到版本:' + SelectedWorkBuddyVersion
+ else if Candidate = '' then
+ ClientVersionLabel.Caption := '尚未选择客户端'
+ else if not FileExists(Candidate) then
+ ClientVersionLabel.Caption := '未找到这个文件'
+ else
+ ClientVersionLabel.Caption := '无法读取版本,安装时仍会保存所选路径';
+end;
+
+procedure ClientPathChanged(Sender: TObject);
+begin
+ UpdateClientDetails();
+end;
+
+procedure UseDetectedClient(Sender: TObject);
+begin
+ ClientPage.Values[0] := DetectedOfficialPath;
+ ClientSourceLabel.Caption := '已使用自动识别出的官方客户端。';
+ UpdateClientDetails();
+end;
+
+function ValidateClientSelection(const ShowError: Boolean): Boolean;
+begin
+ SelectedWorkBuddyPath := Trim(ClientPage.Values[0]);
+ Result := UsableClientFile(SelectedWorkBuddyPath);
+ if (not Result) and ShowError then
+ MsgBox('请选择要连接的 WorkBuddy .exe 主程序。', mbError, MB_OK);
+ if Result then
+ UpdateClientDetails();
+end;
+
+procedure InitializeWizard();
+var
+ DetectedPath: String;
+ DetectedVersion: String;
+ SavedClientType: String;
+ HasSavedClient: Boolean;
+ HasOfficialClient: Boolean;
+begin
+ ClientPage := CreateInputFilePage(
+ wpSelectDir,
+ 'WorkBuddy 客户端',
+ '确认 WorkDaddy 要连接的客户端',
+ '安装程序会自动识别客户端。企业专享版或其他安装位置可以点击“浏览”修改。'
+ );
+ ClientPage.Add('客户端主程序:', '可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*', '.exe');
+
+ ClientSourceLabel := TNewStaticText.Create(ClientPage);
+ ClientSourceLabel.Parent := ClientPage.Surface;
+ ClientSourceLabel.Left := 0;
+ ClientSourceLabel.Top := ClientPage.Edits[0].Top + ClientPage.Edits[0].Height + ScaleY(12);
+ ClientSourceLabel.Width := ClientPage.SurfaceWidth;
+ ClientSourceLabel.Height := ScaleY(18);
+ ClientSourceLabel.AutoSize := False;
+
+ ClientVersionLabel := TNewStaticText.Create(ClientPage);
+ ClientVersionLabel.Parent := ClientPage.Surface;
+ ClientVersionLabel.Left := 0;
+ ClientVersionLabel.Top := ClientSourceLabel.Top + ScaleY(24);
+ ClientVersionLabel.Width := ClientPage.SurfaceWidth;
+ ClientVersionLabel.Height := ScaleY(18);
+ ClientVersionLabel.AutoSize := False;
+
+ UseDetectedButton := TNewButton.Create(ClientPage);
+ UseDetectedButton.Parent := ClientPage.Surface;
+ UseDetectedButton.Left := 0;
+ UseDetectedButton.Top := ClientVersionLabel.Top + ScaleY(26);
+ UseDetectedButton.Width := ScaleX(126);
+ UseDetectedButton.Height := ScaleY(26);
+ UseDetectedButton.Caption := '使用自动识别路径';
+ UseDetectedButton.OnClick := @UseDetectedClient;
+ UseDetectedButton.Visible := False;
+
+ DetectedPath := '';
+ DetectedVersion := '';
+ SavedClientType := '';
+ DetectedOfficialPath := '';
+ HasSavedClient := ReadSavedClient(DetectedPath, DetectedVersion, SavedClientType);
+ HasOfficialClient := DetectOfficialClient(DetectedOfficialPath);
+ if HasSavedClient and
+ (CompareText(SavedClientType, 'enterprise') = 0) then
+ begin
+ ClientSourceLabel.Caption := '已保留上次安装选择,可直接继续或修改。';
+ UseDetectedButton.Visible := HasOfficialClient and
+ (CompareText(DetectedPath, DetectedOfficialPath) <> 0);
+ end
+ else if HasOfficialClient and
+ ((not HasSavedClient) or PreferDetectedOfficialClient(
+ DetectedPath, SavedClientType, DetectedOfficialPath)) then
+ begin
+ DetectedPath := DetectedOfficialPath;
+ if HasSavedClient then
+ ClientSourceLabel.Caption := '检测到更新的官方客户端,已自动使用新路径。'
+ else
+ ClientSourceLabel.Caption := '已自动识别官方客户端,可直接继续或修改。';
+ end
+ else if HasSavedClient then
+ begin
+ ClientSourceLabel.Caption := '已保留上次安装选择,可直接继续或修改。';
+ UseDetectedButton.Visible := HasOfficialClient and
+ (CompareText(DetectedPath, DetectedOfficialPath) <> 0);
+ end
+ else
+ ClientSourceLabel.Caption := '未自动找到客户端,请点击“浏览”选择。';
+ ClientPage.Values[0] := DetectedPath;
+ ClientPage.Edits[0].OnChange := @ClientPathChanged;
+ UpdateClientDetails();
+end;
+
+function NextButtonClick(CurPageID: Integer): Boolean;
+begin
+ Result := True;
+ if CurPageID = ClientPage.ID then
+ Result := ValidateClientSelection(True);
+end;
+
+function SaveSelectedClient(): Boolean;
+var
+ NodePath: String;
+ ScriptPath: String;
+ DataDir: String;
+ Parameters: String;
+ ResultCode: Integer;
+begin
+ Result := False;
+ NodePath := ExpandConstant('{app}\scripts\runtime\node\node.exe');
+ ScriptPath := ExpandConstant('{app}\scripts\workbuddy-target.js');
+ DataDir := ExpandConstant('{userappdata}\WorkDaddy');
+ if '{#ProfileId}' = 'workbuddy-ai' then
+ DataDir := DataDir + '\profiles\workbuddy-ai';
+ Parameters := '"' + ScriptPath + '" --configure --profile "{#ProfileId}"' +
+ ' --binary "' + SelectedWorkBuddyPath + '" --version "' + SelectedWorkBuddyVersion + '"' +
+ ' --data-dir "' + DataDir + '"';
+ if not ExecAsOriginalUser(NodePath, Parameters, ExpandConstant('{app}\scripts'), SW_HIDE,
+ ewWaitUntilTerminated, ResultCode) then
+ exit;
+ Result := ResultCode = 0;
+end;
+
+procedure CurStepChanged(CurStep: TSetupStep);
+begin
+ if CurStep = ssPostInstall then
+ begin
+ if not SaveSelectedClient() then
+ RaiseException('无法保存 WorkBuddy 客户端选择,安装已停止。');
+ end;
+end;
+
function ShowWorkBuddyCloseDialog(): Integer;
var
Dialog: TSetupForm;
@@ -175,7 +612,7 @@ begin
Result := False;
while True do
begin
- if not RunNativeHelper('--check-workbuddy', ResultCode) then
+ if not RunNativeHelper('--check-workbuddy --binary "' + SelectedWorkBuddyPath + '"', ResultCode) then
begin
MsgBox('无法启动 WorkBuddy 进程检测。请检查安全软件是否拦截安装程序。', mbError, MB_OK);
exit;
@@ -195,7 +632,7 @@ begin
exit;
if Choice = mrYes then
begin
- if not RunNativeHelper('--terminate-workbuddy', ResultCode) then
+ if not RunNativeHelper('--terminate-workbuddy --binary "' + SelectedWorkBuddyPath + '"', ResultCode) then
begin
MsgBox('无法启动 WorkBuddy 结束进程操作。请检查安全软件是否拦截安装程序。', mbError, MB_OK);
exit;
@@ -222,13 +659,21 @@ begin
Result := '当前安装程序是以管理员权限运行的,无法继续安装。为避免 WorkDaddy 后台出现权限不一致,请点击“取消”,关闭安装程序后直接双击安装包重新运行;不要选择“以管理员身份运行”。UAC 无需关闭。';
exit;
end;
+ if not ValidateClientSelection(False) then
+ begin
+ Result := '没有可用的 WorkBuddy 客户端路径。请返回“WorkBuddy 客户端”页面选择 .exe 主程序。';
+ exit;
+ end;
if not EnsureWorkBuddyClosed() then
begin
Result := '无法确认 WorkBuddy 已退出。可能原因是客户端仍有后台进程、进程权限高于当前用户、系统正在退出客户端,或安全软件阻止了进程检测。请手动结束当前客户端后重新运行安装程序。';
exit;
end;
- if not RunNativeHelper('--stop-lifecycle', ResultCode) then
+ if not RunNativeHelper(
+ '--stop-lifecycle --app-dir "' + ExpandConstant('{app}') + '"',
+ ResultCode
+ ) then
begin
Result := '无法启动 WorkDaddy 后台进程清理。可能原因是安装器原始用户权限不可用、安全软件拦截了临时 helper,或临时目录不可写。请点击“取消”,关闭安装程序后直接双击安装包重新运行;不要选择“以管理员身份运行”。UAC 无需关闭。';
exit;
diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.go
index 0a988f2..f8f938c 100644
--- a/scripts/windows-native/main.go
+++ b/scripts/windows-native/main.go
@@ -49,6 +49,7 @@ var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
advapi32 = syscall.NewLazyDLL("advapi32.dll")
user32 = syscall.NewLazyDLL("user32.dll")
+ versionDLL = syscall.NewLazyDLL("version.dll")
procCreateMutexW = kernel32.NewProc("CreateMutexW")
procGetCurrentProcess = kernel32.NewProc("GetCurrentProcess")
procOpenProcessToken = advapi32.NewProc("OpenProcessToken")
@@ -61,6 +62,9 @@ var (
procTerminateProcess = kernel32.NewProc("TerminateProcess")
procWaitForSingleObject = kernel32.NewProc("WaitForSingleObject")
procMessageBoxW = user32.NewProc("MessageBoxW")
+ procGetFileVersionInfoSizeW = versionDLL.NewProc("GetFileVersionInfoSizeW")
+ procGetFileVersionInfoW = versionDLL.NewProc("GetFileVersionInfoW")
+ procVerQueryValueW = versionDLL.NewProc("VerQueryValueW")
)
type processEntry32 struct {
@@ -77,15 +81,41 @@ type processEntry32 struct {
}
type processRecord struct {
- PID uint32 `json:"pid"`
- Name string `json:"name"`
- Path string `json:"path,omitempty"`
+ PID uint32 `json:"pid"`
+ Name string `json:"name"`
+ Path string `json:"path,omitempty"`
+ ParentPID uint32 `json:"-"`
}
type lockOwner struct {
PID int `json:"pid"`
}
+type workBuddyTarget struct {
+ ProfileID string `json:"profileId"`
+ ClientType string `json:"clientType"`
+ Binary string `json:"binary"`
+ Version string `json:"version"`
+ ProcessName string `json:"processName"`
+ ProcessNames []string `json:"processNames"`
+}
+
+type vsFixedFileInfo struct {
+ Signature uint32
+ StructVersion uint32
+ FileVersionMS uint32
+ FileVersionLS uint32
+ ProductVersionMS uint32
+ ProductVersionLS uint32
+ FileFlagsMask uint32
+ FileFlags uint32
+ FileOS uint32
+ FileType uint32
+ FileSubtype uint32
+ FileDateMS uint32
+ FileDateLS uint32
+}
+
func utf16Ptr(value string) *uint16 {
ptr, err := syscall.UTF16PtrFromString(value)
if err != nil {
@@ -99,6 +129,35 @@ func messageBox(title, message string, flags uintptr) int {
return int(result)
}
+func fileVersion(binary string) string {
+ name := utf16Ptr(binary)
+ var ignored uint32
+ size, _, _ := procGetFileVersionInfoSizeW.Call(uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(&ignored)))
+ if size == 0 || size > 16*1024*1024 {
+ return ""
+ }
+ buffer := make([]byte, size)
+ ok, _, _ := procGetFileVersionInfoW.Call(
+ uintptr(unsafe.Pointer(name)), 0, size, uintptr(unsafe.Pointer(&buffer[0])),
+ )
+ if ok == 0 {
+ return ""
+ }
+ root := utf16Ptr("\\")
+ var fixed *vsFixedFileInfo
+ var fixedSize uint32
+ ok, _, _ = procVerQueryValueW.Call(
+ uintptr(unsafe.Pointer(&buffer[0])), uintptr(unsafe.Pointer(root)),
+ uintptr(unsafe.Pointer(&fixed)), uintptr(unsafe.Pointer(&fixedSize)),
+ )
+ if ok == 0 || fixed == nil || fixedSize < uint32(unsafe.Sizeof(*fixed)) || fixed.Signature != 0xFEEF04BD {
+ return ""
+ }
+ return fmt.Sprintf("%d.%d.%d.%d",
+ fixed.FileVersionMS>>16, fixed.FileVersionMS&0xffff,
+ fixed.FileVersionLS>>16, fixed.FileVersionLS&0xffff)
+}
+
func isElevated() (bool, error) {
current, _, _ := procGetCurrentProcess.Call()
var token syscall.Handle
@@ -198,13 +257,95 @@ func productName(profile string) string {
return "WorkDaddy"
}
+func configuredTarget(profile string) workBuddyTarget {
+ dir, err := dataDir(profile)
+ if err != nil {
+ return workBuddyTarget{}
+ }
+ data, err := os.ReadFile(filepath.Join(dir, "workbuddy-target.json"))
+ if err != nil {
+ return workBuddyTarget{}
+ }
+ var target workBuddyTarget
+ if json.Unmarshal(data, &target) != nil || !strings.EqualFold(target.ProfileID, profile) {
+ return workBuddyTarget{}
+ }
+ configuredBinary := strings.TrimSpace(target.Binary)
+ processNames := target.ProcessNames
+ if len(processNames) == 0 && strings.TrimSpace(target.ProcessName) != "" {
+ processNames = []string{target.ProcessName}
+ }
+ if !filepath.IsAbs(configuredBinary) || len(processNames) == 0 || len(processNames) > 4 {
+ return workBuddyTarget{}
+ }
+ selectedName := filepath.Base(configuredBinary)
+ hasSelectedName := false
+ for index, name := range processNames {
+ name = strings.TrimSpace(name)
+ if name == "" || !strings.EqualFold(name, filepath.Base(name)) || !strings.EqualFold(filepath.Ext(name), ".exe") {
+ return workBuddyTarget{}
+ }
+ processNames[index] = name
+ if strings.EqualFold(name, selectedName) {
+ hasSelectedName = true
+ }
+ }
+ if !hasSelectedName {
+ return workBuddyTarget{}
+ }
+ target.Binary = filepath.Clean(configuredBinary)
+ target.ProcessNames = processNames
+ return target
+}
+
func workBuddyImage(profile string) string {
+ if target := configuredTarget(profile); len(target.ProcessNames) > 0 {
+ return target.ProcessNames[0]
+ }
if profile == profileAI {
return "WorkBuddyAI.exe"
}
return "WorkBuddy.exe"
}
+func processNamesForBinary(binary string) []string {
+ selected := filepath.Base(binary)
+ names := []string{selected}
+ stem := strings.TrimSuffix(selected, filepath.Ext(selected))
+ lower := strings.ToLower(stem)
+ for _, separator := range []string{"-", "_", " "} {
+ prefix := "workbuddy" + separator
+ if !strings.HasPrefix(lower, prefix) {
+ continue
+ }
+ parts := strings.FieldsFunc(stem[len(prefix):], func(r rune) bool { return r == '-' || r == '_' || r == ' ' })
+ suffix := ""
+ for _, part := range parts {
+ if part != "" {
+ suffix += strings.ToUpper(part[:1]) + strings.ToLower(part[1:])
+ }
+ }
+ if suffix != "" {
+ names = append(names, "WorkBuddy"+suffix+".exe")
+ }
+ break
+ }
+ return names
+}
+
+func targetForBinary(profile, binary string) workBuddyTarget {
+ binary = strings.TrimSpace(binary)
+ if (profile != profileCN && profile != profileAI) || !filepath.IsAbs(binary) ||
+ !strings.EqualFold(filepath.Ext(binary), ".exe") || strings.ContainsAny(binary, "\r\n") {
+ return workBuddyTarget{}
+ }
+ info, err := os.Stat(binary)
+ if err != nil || info.IsDir() {
+ return workBuddyTarget{}
+ }
+ return workBuddyTarget{ProfileID: profile, Binary: filepath.Clean(binary), ProcessNames: processNamesForBinary(binary)}
+}
+
func enumerateProcesses() ([]processRecord, error) {
snapshot, _, callErr := procCreateToolhelp32Snapshot.Call(th32csSnapProcess, 0)
if snapshot == uintptr(syscall.InvalidHandle) {
@@ -220,7 +361,9 @@ func enumerateProcesses() ([]processRecord, error) {
var records []processRecord
for {
name := syscall.UTF16ToString(entry.ExeFile[:])
- records = append(records, processRecord{PID: entry.ProcessID, Name: name, Path: queryProcessPath(entry.ProcessID)})
+ records = append(records, processRecord{
+ PID: entry.ProcessID, Name: name, Path: queryProcessPath(entry.ProcessID), ParentPID: entry.ParentProcessID,
+ })
entry.Size = uint32(unsafe.Sizeof(processEntry32{}))
result, _, _ = procProcess32NextW.Call(snapshot, uintptr(unsafe.Pointer(&entry)))
if result == 0 {
@@ -255,21 +398,38 @@ func queryProcessPath(pid uint32) string {
return syscall.UTF16ToString(buffer[:size])
}
-func matchingWorkBuddyProcesses(profile string) ([]processRecord, error) {
+func matchingWorkBuddyProcessesForTarget(profile string, target workBuddyTarget) ([]processRecord, error) {
records, err := enumerateProcesses()
if err != nil {
return nil, err
}
- expected := workBuddyImage(profile)
+ expectedNames := []string{workBuddyImage(profile)}
+ if len(target.ProcessNames) > 0 {
+ expectedNames = target.ProcessNames
+ }
matched := make([]processRecord, 0)
for _, record := range records {
- if strings.EqualFold(record.Name, expected) {
+ nameMatches := false
+ for _, expected := range expectedNames {
+ if strings.EqualFold(record.Name, expected) {
+ nameMatches = true
+ break
+ }
+ }
+ pathMatches := target.Binary == "" || (record.Path != "" &&
+ samePath(filepath.Dir(record.Path), filepath.Dir(target.Binary)) &&
+ strings.EqualFold(filepath.Base(record.Path), record.Name))
+ if nameMatches && pathMatches {
matched = append(matched, record)
}
}
return matched, nil
}
+func matchingWorkBuddyProcesses(profile string) ([]processRecord, error) {
+ return matchingWorkBuddyProcessesForTarget(profile, configuredTarget(profile))
+}
+
func samePath(left, right string) bool {
return strings.EqualFold(filepath.Clean(left), filepath.Clean(right))
}
@@ -332,6 +492,9 @@ func terminateExactProcess(pid int, expectedPath string, label string) (bool, in
defer syscall.CloseHandle(handle)
result, _, callErr := procTerminateProcess.Call(uintptr(handle), 0)
if result == 0 {
+ if errors.Is(callErr, syscall.ERROR_ACCESS_DENIED) {
+ return false, exitAccessDenied, fmt.Errorf("PID %d %s cannot be terminated at standard privilege", pid, label)
+ }
return false, exitFailure, callErr
}
waitResult, _, callErr := procWaitForSingleObject.Call(uintptr(handle), 15000)
@@ -354,6 +517,12 @@ func stopInstalledLauncher(appDir string) int {
}
matches := make([]processRecord, 0, 1)
for _, record := range records {
+ // The --stop-lifecycle helper is itself WorkDaddyLauncher.exe from the
+ // target directory. Exclude only this helper; every other match remains
+ // subject to the single-process fail-closed boundary below.
+ if record.PID == uint32(os.Getpid()) {
+ continue
+ }
if strings.EqualFold(record.Name, "WorkDaddyLauncher.exe") && samePath(record.Path, expectedLauncher) {
matches = append(matches, record)
}
@@ -396,7 +565,7 @@ func uniqueRunningWorkBuddyPath(profile string, matches []processRecord) (string
return paths[0], nil
}
-func terminateWorkBuddy(profile string) int {
+func terminateWorkBuddyTarget(profile string, target workBuddyTarget) int {
elevated, err := isElevated()
if err != nil {
fmt.Fprintln(os.Stderr, "cannot determine helper privilege:", err)
@@ -406,7 +575,7 @@ func terminateWorkBuddy(profile string) int {
fmt.Fprintln(os.Stderr, "WorkBuddy termination requires standard user privilege")
return exitAccessDenied
}
- matches, err := matchingWorkBuddyProcesses(profile)
+ matches, err := matchingWorkBuddyProcessesForTarget(profile, target)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return exitFailure
@@ -431,6 +600,50 @@ func terminateWorkBuddy(profile string) int {
return 0
}
+func terminateWorkBuddy(profile string) int {
+ return terminateWorkBuddyTarget(profile, configuredTarget(profile))
+}
+
+// recoverWatchdogPID uses the process tree only as a recovery proof when the
+// user-writable watchdog.pid disappeared during an install/update race. The
+// daemon PID comes from the profile lock file and both processes must use the
+// exact bundled Node executable. Any ambiguity remains fail-closed.
+func recoverWatchdogPID(records []processRecord, expectedNode string, daemonPID int) (int, error) {
+ if daemonPID <= 0 {
+ return 0, nil
+ }
+ var daemon *processRecord
+ for index := range records {
+ record := &records[index]
+ if record.PID == uint32(daemonPID) && samePath(record.Path, expectedNode) {
+ if daemon != nil {
+ return 0, fmt.Errorf("daemon PID %d appears more than once", daemonPID)
+ }
+ daemon = record
+ }
+ }
+ if daemon == nil || daemon.ParentPID == 0 {
+ return 0, nil
+ }
+ candidates := make([]processRecord, 0, 1)
+ for _, record := range records {
+ if record.PID == daemon.ParentPID && samePath(record.Path, expectedNode) {
+ candidates = append(candidates, record)
+ }
+ }
+ if len(candidates) != 1 {
+ if len(candidates) > 1 {
+ return 0, fmt.Errorf("daemon PID %d has multiple bundled Node parents", daemonPID)
+ }
+ return 0, nil
+ }
+ candidate := candidates[0]
+ if strings.TrimSpace(candidate.Path) == "" {
+ return 0, nil
+ }
+ return int(candidate.PID), nil
+}
+
func stopLifecycle(profile, appDir string) int {
dir, err := dataDir(profile)
if err != nil {
@@ -438,12 +651,49 @@ func stopLifecycle(profile, appDir string) int {
return exitFailure
}
expectedNode := filepath.Join(appDir, "scripts", "runtime", "node", "node.exe")
+ watchdogPath := filepath.Join(dir, "watchdog.pid")
+ watchdogPID := readPID(watchdogPath)
+ watchdogPresent := false
+ if _, statErr := os.Stat(watchdogPath); statErr == nil {
+ watchdogPresent = true
+ } else if !os.IsNotExist(statErr) {
+ fmt.Fprintln(os.Stderr, statErr)
+ return exitFailure
+ }
+ if watchdogPresent && watchdogPID <= 0 {
+ fmt.Fprintln(os.Stderr, "watchdog.pid 内容无效")
+ return exitIdentityMismatch
+ }
+ daemonPID := readLockPID(filepath.Join(dir, ".daemon.lock"))
+ if !watchdogPresent && daemonPID > 0 {
+ records, enumerateErr := enumerateProcesses()
+ if enumerateErr != nil {
+ fmt.Fprintln(os.Stderr, enumerateErr)
+ return exitFailure
+ }
+ recovered, recoverErr := recoverWatchdogPID(records, expectedNode, daemonPID)
+ if recoverErr != nil {
+ fmt.Fprintln(os.Stderr, recoverErr)
+ return exitIdentityMismatch
+ }
+ if recovered > 0 {
+ watchdogPID = recovered
+ watchdogPresent = true
+ } else {
+ for _, record := range records {
+ if record.PID == uint32(daemonPID) && samePath(record.Path, expectedNode) {
+ fmt.Fprintln(os.Stderr, "watchdog.pid 缺失且无法证明当前 daemon 的唯一 watchdog,已拒绝只停止 daemon")
+ return exitIdentityMismatch
+ }
+ }
+ }
+ }
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"))},
+ {watchdogPath, watchdogPID},
+ {filepath.Join(dir, ".daemon.lock"), daemonPID},
}
seen := map[int]bool{}
for _, candidate := range pidFiles {
@@ -533,8 +783,46 @@ func runNodeLauncher(appDir, profile string) int {
}
func helperMain(appDir, profile string) (bool, int) {
+ if hasArgument("--target-info") {
+ target := configuredTarget(profile)
+ output := argumentValue("--output")
+ if target.Binary == "" || output == "" || !filepath.IsAbs(output) || strings.ContainsAny(target.Binary, "\r\n") {
+ return true, exitFailure
+ }
+ version := strings.TrimSpace(target.Version)
+ if version == "" {
+ version = fileVersion(target.Binary)
+ }
+ clientType := strings.TrimSpace(target.ClientType)
+ if strings.ContainsAny(version, "\r\n") || strings.ContainsAny(clientType, "\r\n") {
+ return true, exitFailure
+ }
+ if os.WriteFile(output, []byte(target.Binary+"\r\n"+version+"\r\n"+clientType+"\r\n"), 0600) != nil {
+ return true, exitFailure
+ }
+ return true, 0
+ }
+ if hasArgument("--file-version") {
+ binary := argumentValue("--binary")
+ if binary == "" || !filepath.IsAbs(binary) {
+ return true, exitUsage
+ }
+ version := fileVersion(binary)
+ if version == "" {
+ return true, exitFailure
+ }
+ fmt.Fprintln(os.Stdout, version)
+ return true, 0
+ }
if hasArgument("--check-workbuddy") {
- matches, err := matchingWorkBuddyProcesses(profile)
+ target := configuredTarget(profile)
+ if binary := argumentValue("--binary"); binary != "" {
+ target = targetForBinary(profile, binary)
+ if target.Binary == "" {
+ return true, exitUsage
+ }
+ }
+ matches, err := matchingWorkBuddyProcessesForTarget(profile, target)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return true, exitFailure
@@ -554,6 +842,13 @@ func helperMain(appDir, profile string) (bool, int) {
return true, 0
}
if hasArgument("--terminate-workbuddy") {
+ if binary := argumentValue("--binary"); binary != "" {
+ target := targetForBinary(profile, binary)
+ if target.Binary == "" {
+ return true, exitUsage
+ }
+ return true, terminateWorkBuddyTarget(profile, target)
+ }
return true, terminateWorkBuddy(profile)
}
if hasArgument("--stop-lifecycle") {
diff --git a/scripts/windows-process-boundary.js b/scripts/windows-process-boundary.js
index 7be01be..544fb4b 100644
--- a/scripts/windows-process-boundary.js
+++ b/scripts/windows-process-boundary.js
@@ -157,18 +157,22 @@ function assertSameProcessIdentity(original, current) {
return after;
}
-function filterVerifiedWindowsProcesses(expectedBinary, processes, realpath = fs.realpathSync.native) {
+function filterVerifiedWindowsProcesses(expectedBinary, processes, realpath = fs.realpathSync.native, allowedProcessNames = null) {
const expected = resolveWindowsExecutable(expectedBinary, realpath);
const expectedDir = path.win32.dirname(expected);
const expectedName = path.win32.basename(expected).toLowerCase();
- if (!ALLOWED_WORKBUDDY_PROCESS_NAMES.has(expectedName)) {
+ const allowedNames = allowedProcessNames
+ ? new Set(Array.from(allowedProcessNames, (name) => String(name).toLowerCase()))
+ : new Set([expectedName]);
+ if (!allowedNames.has(expectedName) || Array.from(allowedNames).some((name) => !/^[^\\/:*?"<>|\0]+\.exe$/i.test(name)) ||
+ (!allowedProcessNames && !ALLOWED_WORKBUDDY_PROCESS_NAMES.has(expectedName))) {
throw new Error('Expected executable is not a WorkBuddy-family binary');
}
const verified = [];
for (const item of Array.isArray(processes) ? processes : []) {
const process = validateProcessRecord(item);
const name = process.Name.toLowerCase();
- if (name !== expectedName) continue;
+ if (!allowedNames.has(name)) continue;
let executable;
try {
executable = resolveWindowsExecutable(process.ExecutablePath, realpath);
diff --git a/scripts/workbuddy-compat.js b/scripts/workbuddy-compat.js
index 278b8aa..3aca287 100644
--- a/scripts/workbuddy-compat.js
+++ b/scripts/workbuddy-compat.js
@@ -247,6 +247,41 @@
}
}
+ // Discover every mounted ConversationController by capability shape rather
+ // than volatile component/class names. Shared fibers are de-duplicated so a
+ // large conversation tree is walked once per fiber, not once per element.
+ function findConversationControllers(doc) {
+ if (!doc || typeof doc.querySelector !== 'function') return [];
+ var root = doc.querySelector('#root > div') || doc.querySelector('#root');
+ if (!root) return [];
+ var found = Object.create(null);
+ var fibers = typeof WeakSet !== 'undefined' ? new WeakSet() : null;
+ var stack = [root];
+ var visitedElements = 0;
+ while (stack.length && visitedElements++ < 1400) {
+ var element = stack.pop();
+ var fiber = reactFiber(element);
+ var seen = 0;
+ while (fiber && seen++ < 800) {
+ if (!fibers || !fibers.has(fiber)) {
+ if (fibers) fibers.add(fiber);
+ 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;
+ var id = String(candidate.conversationId || '').trim();
+ if (id && !found[id]) found[id] = candidate;
+ }
+ }
+ fiber = fiber.return;
+ }
+ var children = element && element.children || [];
+ for (var ci = 0; ci < children.length; ci++) stack.push(children[ci]);
+ }
+ return Object.keys(found).map(function (id) { return found[id]; });
+ }
+
function findModernQueueAdapter(doc) {
if (!doc || typeof doc.querySelector !== 'function') return null;
try {
@@ -303,6 +338,41 @@
return findModernQueueAdapter(doc) || findLegacyQueueAdapter(doc);
}
+ function isSessionsResource(value) {
+ return !!value && typeof value === 'object' &&
+ typeof value.on === 'function' && typeof value.off === 'function' &&
+ (typeof value.list === 'function' || typeof value.getByIds === 'function');
+ }
+
+ // The facade publishes sessionUpdated/sessionsChanged for background sessions
+ // even after their ConversationController has left the mounted React tree.
+ function findSessionsResource(doc) {
+ var found = findQueueAdapter(doc);
+ var resource = found && found.adapter && found.adapter.sessionsResource;
+ return isSessionsResource(resource) ? resource : null;
+ }
+
+ // Sidebar records are an initial/reconciliation snapshot only. Live updates
+ // come from sessionsResource; this narrow fiber walk avoids scanning the page.
+ function findConversationListRecords(doc) {
+ if (!doc || typeof doc.querySelector !== 'function') return [];
+ try {
+ var element = doc.querySelector('.conversation-list .conversation-item') ||
+ doc.querySelector('.conversation-list');
+ var fiber = reactFiber(element);
+ var seen = 0;
+ while (fiber && seen++ < 80) {
+ var props = fiber.memoizedProps;
+ var records = props && props.allConversations;
+ if (Array.isArray(records) && records.some(function (item) {
+ return item && item.id && typeof item.status === 'string';
+ })) return records;
+ fiber = fiber.return;
+ }
+ } catch (_) {}
+ return [];
+ }
+
function hasModernQueueSurface(doc) {
if (!doc || typeof doc.querySelector !== 'function') return false;
return !!findModernQueueAdapter(doc) || !!doc.querySelector(
@@ -352,8 +422,11 @@
findLegacyQueueAdapter: findLegacyQueueAdapter,
findModernQueueAdapter: findModernQueueAdapter,
findQueueAdapter: findQueueAdapter,
+ findSessionsResource: findSessionsResource,
+ findConversationListRecords: findConversationListRecords,
findMessageNavigationAdapter: findMessageNavigationAdapter,
findMessageNavigationSurface: findMessageNavigationSurface,
+ findConversationControllers: findConversationControllers,
getSelectedConversationId: getSelectedConversationId,
hasModernQueueSurface: hasModernQueueSurface,
isComposerStore: isComposerStore,
diff --git a/scripts/workbuddy-target.js b/scripts/workbuddy-target.js
index 75ca23a..0471543 100644
--- a/scripts/workbuddy-target.js
+++ b/scripts/workbuddy-target.js
@@ -1,8 +1,12 @@
'use strict';
const fs = require('fs');
+const os = require('os');
const path = require('path');
+const TARGET_FILE = 'workbuddy-target.json';
+const CUSTOM_PROFILES = new Set(['workbuddy-cn', 'workbuddy-ai']);
+
function clean(value) {
return typeof value === 'string' ? value.trim() : '';
}
@@ -11,37 +15,242 @@ 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' };
+function platformPath(platform) {
+ return platform === 'win32' ? path.win32 : path;
+}
+
+function targetFile(dataDir) {
+ return path.join(dataDir, TARGET_FILE);
+}
+
+function isAbsolute(value, platform) {
+ return platformPath(platform).isAbsolute(clean(value));
+}
+
+function validateApiHost(value) {
+ if (!value) return '';
+ let parsed;
+ try { parsed = new URL(value); } catch (_) { throw new Error('企业 API 地址必须是有效 HTTPS 地址'); }
+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.pathname !== '/' || parsed.search || parsed.hash) {
+ throw new Error('企业 API 地址必须是无账号、路径和参数的 HTTPS origin');
}
+ return parsed.origin;
+}
- 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');
+function validateProcessName(value, pathApi) {
+ const name = clean(value);
+ if (!/^[^\\/:*?"<>|\0]+\.exe$/i.test(name) || name !== pathApi.basename(name)) {
+ throw new Error('WorkBuddy 进程名必须是单个 .exe 文件名');
+ }
+ return name;
+}
+
+function inferredProcessNames(binary, platform) {
+ const pathApi = platformPath(platform);
+ const selectedName = pathApi.basename(binary);
+ const names = [selectedName];
+ const stem = selectedName.replace(/\.exe$/i, '');
+ const enterprise = stem.match(/^workbuddy[-_ ]+(.+)$/i);
+ if (enterprise) {
+ const suffix = enterprise[1].split(/[-_ ]+/).filter(Boolean)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join('');
+ if (suffix) names.push(`WorkBuddy${suffix}.exe`);
+ }
+ return Array.from(new Set(names.map((name) => name.toLowerCase())))
+ .map((lower) => names.find((name) => name.toLowerCase() === lower));
+}
+
+function validateTarget(target, options = {}) {
+ const platform = options.platform || process.platform;
+ if (!target || typeof target !== 'object' || Array.isArray(target)) throw new Error('WorkBuddy 客户端配置无效');
+ const profileId = clean(target.profileId || target.profile);
+ if (!CUSTOM_PROFILES.has(profileId)) throw new Error('WorkBuddy 客户端 profile 只能是 workbuddy-cn 或 workbuddy-ai');
+ const clientType = target.clientType === 'official' ? 'official' : 'enterprise';
+ const binary = clean(target.binary || target.executable || target.path);
+ if (!isAbsolute(binary, platform)) throw new Error('WorkBuddy 客户端路径必须是 absolute path');
+ const pathApi = platformPath(platform);
+ const configuredNames = Array.isArray(target.processNames) ? target.processNames : [target.processName].filter(Boolean);
+ const processNames = (configuredNames.length ? configuredNames : [pathApi.basename(binary)])
+ .map((name) => validateProcessName(name, pathApi));
+ const selectedName = pathApi.basename(binary);
+ if (!processNames.some((name) => name.toLowerCase() === selectedName.toLowerCase())) {
+ throw new Error('WorkBuddy 进程名必须包含所选 .exe 文件名');
}
+ const uniqueProcessNames = Array.from(new Set(processNames.map((name) => name.toLowerCase())))
+ .map((lower) => processNames.find((name) => name.toLowerCase() === lower));
+ if (uniqueProcessNames.length > 4) throw new Error('WorkBuddy 进程名候选不能超过 4 个');
+ for (const field of ['dataRoot', 'authFile', 'sessionDb', 'modelsFile']) {
+ if (target[field] && !isAbsolute(target[field], platform)) throw new Error(`${field} 路径必须是 absolute path`);
+ }
+ const apiHost = validateApiHost(clean(target.apiHost));
+ const cdp = target.cdp || { mode: 'argument', port: profileId === 'workbuddy-ai' ? 9223 : 9222 };
+ if (!cdp || (cdp.mode !== 'argument' && cdp.mode !== 'environment')) throw new Error('CDP mode 只能是 argument 或 environment');
+ const cdpPort = Number(cdp.port);
+ if (!Number.isInteger(cdpPort) || cdpPort < 1024 || cdpPort > 65535) throw new Error('CDP port 必须在 1024-65535 之间');
+ const version = clean(target.version);
+ if (version && !/^\d+(?:\.\d+){1,3}$/.test(version)) throw new Error('WorkBuddy 版本必须是数字版本号');
+ const capabilities = {};
+ if (target.capabilities && typeof target.capabilities === 'object' && !Array.isArray(target.capabilities)) {
+ for (const name of ['accounts', 'sessions', 'models', 'stashPrompt', 'theme', 'checkin']) {
+ if (typeof target.capabilities[name] === 'boolean') capabilities[name] = target.capabilities[name];
+ }
+ }
+ return {
+ schemaVersion: 1,
+ clientType,
+ profileId,
+ binary,
+ ...(version ? { version } : {}),
+ lockVersion: target.lockVersion !== false && !!version,
+ processNames: uniqueProcessNames,
+ ...(target.dataRoot ? { dataRoot: clean(target.dataRoot) } : {}),
+ ...(target.authFile ? { authFile: clean(target.authFile) } : {}),
+ ...(target.sessionDb ? { sessionDb: clean(target.sessionDb) } : {}),
+ ...(target.modelsFile ? { modelsFile: clean(target.modelsFile) } : {}),
+ ...(apiHost ? { apiHost } : {}),
+ targetHints: Array.from(new Set((Array.isArray(target.targetHints) ? target.targetHints : [])
+ .map(clean).filter((value) => value && value.length <= 200))).slice(0, 8),
+ cdp: { mode: cdp.mode, port: cdpPort },
+ capabilities,
+ };
+}
- let target;
+function hostFromValue(value) {
+ const text = clean(value);
+ if (!text || text.length > 4096) return '';
try {
- target = JSON.parse(raw);
- } catch (_) {
- return emptyTarget(true, 'file');
+ const parsed = new URL(/^https?:\/\//i.test(text) ? text : `https://${text}`);
+ if (parsed.protocol !== 'https:' || !parsed.hostname.includes('.') || parsed.username || parsed.password) return '';
+ return parsed.origin;
+ } catch (_) { return ''; }
+}
+
+function jwtIssuer(value) {
+ const parts = clean(value).split('.');
+ if (parts.length !== 3 || parts[1].length > 8192) return '';
+ try {
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
+ return payload && hostFromValue(payload.iss);
+ } catch (_) { return ''; }
+}
+
+function apiHostFromAuth(value) {
+ const seen = new Set();
+ function visit(node, key, depth) {
+ if (depth > 8 || node === null || node === undefined) return '';
+ if (typeof node === 'string') {
+ if (/token/i.test(key || '')) return jwtIssuer(node);
+ if (/^(?:iss|issuer|domain|apiHost|apiEndpoint|realm)$/i.test(key || '')) return hostFromValue(node);
+ return '';
+ }
+ if (typeof node !== 'object' || seen.has(node)) return '';
+ seen.add(node);
+ for (const [childKey, child] of Object.entries(node)) {
+ const found = visit(child, childKey, depth + 1);
+ if (found) return found;
+ }
+ return '';
}
- if (!target || typeof target !== 'object' || Array.isArray(target)) {
- return emptyTarget(true, 'file');
+ return visit(value, '', 0);
+}
+
+function findAuthFile(authDir, stem) {
+ const exact = path.join(authDir, `workbuddy-desktop-${stem}.info`);
+ try { if (fs.statSync(exact).isFile()) return exact; } catch (_) {}
+ let names = [];
+ try { names = fs.readdirSync(authDir); } catch (_) { return ''; }
+ const tokens = stem.toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 2);
+ const matches = names.filter((name) => name.toLowerCase().endsWith('.info') && tokens.every((token) => name.toLowerCase().includes(token)));
+ return matches.length === 1 ? path.join(authDir, matches[0]) : '';
+}
+
+function buildTargetFromBinary(options = {}) {
+ const platform = options.platform || process.platform;
+ const pathApi = platformPath(platform);
+ const binary = clean(options.binary);
+ if (!binary || !isAbsolute(binary, platform)) throw new Error('请选择完整的 WorkBuddy .exe 路径');
+ const processName = pathApi.basename(binary);
+ if (!/\.exe$/i.test(processName)) throw new Error('请选择 WorkBuddy 的 .exe 主程序');
+ const processNames = inferredProcessNames(binary, platform);
+ const stem = processName.replace(/\.exe$/i, '').toLowerCase();
+ const home = options.home || os.homedir();
+ const localAppData = options.localAppData || process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
+ const dataRoot = path.join(home, `.${stem}`);
+ const authDir = path.join(localAppData, 'CodeBuddyExtension', 'Data', 'Public', 'auth');
+ const authFile = findAuthFile(authDir, stem);
+ let apiHost = '';
+ if (authFile) {
+ try { apiHost = apiHostFromAuth(JSON.parse(fs.readFileSync(authFile, 'utf8'))); } catch (_) {}
+ }
+ const profileId = clean(options.profileId) || 'workbuddy-cn';
+ const port = Number(options.cdpPort) || (profileId === 'workbuddy-ai' ? 9233 : 9226);
+ return validateTarget({
+ schemaVersion: 1,
+ clientType: 'enterprise',
+ profileId,
+ binary,
+ version: clean(options.version),
+ lockVersion: !!clean(options.version),
+ processNames,
+ dataRoot,
+ ...(authFile ? { authFile } : {}),
+ sessionDb: path.join(dataRoot, 'workbuddy.db'),
+ modelsFile: path.join(dataRoot, 'models.json'),
+ ...(apiHost ? { apiHost } : {}),
+ targetHints: [stem, apiHost ? new URL(apiHost).hostname : ''].filter(Boolean),
+ cdp: { mode: 'environment', port },
+ capabilities: { accounts: !!authFile, sessions: true, models: true, stashPrompt: true, theme: true, checkin: false },
+ }, { platform });
+}
+
+function buildOfficialTargetFromBinary(options = {}) {
+ const platform = options.platform || process.platform;
+ const pathApi = platformPath(platform);
+ const binary = clean(options.binary);
+ const profileId = clean(options.profileId) || 'workbuddy-cn';
+ if (!binary || !isAbsolute(binary, platform)) throw new Error('请选择完整的 WorkBuddy .exe 路径');
+ const expectedName = profileId === 'workbuddy-ai' ? 'WorkBuddyAI.exe' : 'WorkBuddy.exe';
+ if (pathApi.basename(binary).toLowerCase() !== expectedName.toLowerCase()) {
+ throw new Error(`当前安装包的官方客户端必须是 ${expectedName}`);
}
+ return validateTarget({
+ schemaVersion: 1,
+ clientType: 'official',
+ profileId,
+ binary,
+ version: clean(options.version),
+ lockVersion: !!clean(options.version),
+ processNames: [pathApi.basename(binary)],
+ targetHints: [],
+ cdp: { mode: 'argument', port: profileId === 'workbuddy-ai' ? 9223 : 9222 },
+ capabilities: {},
+ }, { platform });
+}
- const configuredProfile = clean(target.profileId || target.profile);
- if (configuredProfile && profileId && configuredProfile !== clean(profileId)) {
- return emptyTarget(true, 'file');
+function readWorkBuddyTarget({ dataDir, profileId, env = process.env, platform = process.platform } = {}) {
+ const envBinary = clean(env.WBSWITCH_WORKBUDDY_BIN);
+ const envVersion = clean(env.WBSWITCH_WORKBUDDY_VERSION);
+ let target = null;
+ if (dataDir) {
+ try { target = JSON.parse(fs.readFileSync(targetFile(dataDir), 'utf8')); } catch (error) {
+ if (!error || error.code !== 'ENOENT') return emptyTarget(true, 'file');
+ }
+ }
+ if (target && typeof target !== 'object') return emptyTarget(true, 'file');
+ const configuredProfile = target && clean(target.profileId || target.profile);
+ if (configuredProfile && profileId && configuredProfile !== clean(profileId)) return emptyTarget(true, 'file');
+ if (target && (target.schemaVersion || target.processName || target.processNames || target.dataRoot || target.apiHost || target.cdp)) {
+ const merged = { ...target };
+ if (envBinary) {
+ merged.binary = envBinary;
+ merged.processNames = inferredProcessNames(envBinary, platform);
+ delete merged.processName;
+ }
+ if (envVersion) merged.version = envVersion;
+ return { ...validateTarget(merged, { platform }), configured: true, source: envBinary ? 'environment' : 'file' };
}
+ if (envBinary) return { configured: true, binary: envBinary, version: envVersion, source: 'environment' };
+ if (!target) return emptyTarget();
return {
configured: true,
binary: clean(target.binary || target.executable || target.path),
@@ -50,4 +259,80 @@ function readWorkBuddyTarget({ dataDir, profileId, env = process.env } = {}) {
};
}
-module.exports = { readWorkBuddyTarget };
+function writeWorkBuddyTarget({ dataDir, profileId, target, platform = process.platform } = {}) {
+ if (!dataDir) throw new Error('缺少 WorkDaddy 数据目录');
+ const normalized = validateTarget(target, { platform });
+ if (profileId && normalized.profileId !== profileId) throw new Error('客户端 profile 与当前 WorkDaddy 安装包不匹配');
+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
+ const file = targetFile(dataDir);
+ const temporary = `${file}.tmp.${process.pid}`;
+ fs.writeFileSync(temporary, JSON.stringify(normalized, null, 2) + '\n', { mode: 0o600 });
+ try {
+ fs.renameSync(temporary, file);
+ } catch (error) {
+ if (!error || !['EEXIST', 'EPERM', 'ENOTEMPTY'].includes(error.code)) throw error;
+ fs.copyFileSync(temporary, file);
+ fs.unlinkSync(temporary);
+ }
+ try { fs.chmodSync(file, 0o600); } catch (_) {}
+ return normalized;
+}
+
+function removeWorkBuddyTarget({ dataDir } = {}) {
+ if (!dataDir) return false;
+ try { fs.unlinkSync(targetFile(dataDir)); return true; } catch (error) {
+ if (error && error.code === 'ENOENT') return false;
+ throw error;
+ }
+}
+
+function cliValue(argv, name) {
+ const index = argv.indexOf(name);
+ return index >= 0 && index + 1 < argv.length ? argv[index + 1] : '';
+}
+
+function configureFromInstaller(argv = process.argv.slice(2)) {
+ if (!argv.includes('--configure')) throw new Error('缺少 --configure');
+ const profileId = clean(cliValue(argv, '--profile'));
+ const binary = clean(cliValue(argv, '--binary'));
+ const version = clean(cliValue(argv, '--version'));
+ const dataDir = clean(cliValue(argv, '--data-dir'));
+ const pathApi = platformPath('win32');
+ const expectedName = profileId === 'workbuddy-ai' ? 'WorkBuddyAI.exe' : 'WorkBuddy.exe';
+ const official = pathApi.basename(binary).toLowerCase() === expectedName.toLowerCase();
+ const target = official
+ ? buildOfficialTargetFromBinary({ binary, version, profileId, platform: 'win32' })
+ : buildTargetFromBinary({
+ binary,
+ version,
+ profileId,
+ cdpPort: profileId === 'workbuddy-ai' ? 9233 : 9226,
+ platform: 'win32',
+ });
+ const saved = writeWorkBuddyTarget({ dataDir, profileId, target, platform: 'win32' });
+ process.stdout.write(JSON.stringify({ ok: true, name: pathApi.basename(saved.binary), version: saved.version || '', clientType: saved.clientType }) + '\n');
+ return saved;
+}
+
+if (require.main === module && process.argv.slice(2).includes('--configure')) {
+ try {
+ configureFromInstaller();
+ } catch (error) {
+ process.stderr.write(String(error && error.message || error) + '\n');
+ process.exitCode = 1;
+ }
+}
+
+module.exports = {
+ TARGET_FILE,
+ apiHostFromAuth,
+ buildOfficialTargetFromBinary,
+ buildTargetFromBinary,
+ configureFromInstaller,
+ inferredProcessNames,
+ readWorkBuddyTarget,
+ removeWorkBuddyTarget,
+ targetFile,
+ validateTarget,
+ writeWorkBuddyTarget,
+};
diff --git a/test/app-icon.test.js b/test/app-icon.test.js
new file mode 100644
index 0000000..2dbc9c2
--- /dev/null
+++ b/test/app-icon.test.js
@@ -0,0 +1,42 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const repoRoot = path.join(__dirname, '..');
+const generator = fs.readFileSync(path.join(repoRoot, 'scripts', 'make-icon.py'), 'utf8');
+const foreground = path.join(repoRoot, 'scripts', 'assets', 'workdaddy-icon-foreground.png');
+
+test('application icon generator shares the requested background across platforms', () => {
+ assert.equal(fs.existsSync(foreground), true, 'missing tracked icon foreground');
+ assert.match(generator, /BACKGROUND = '#e1e1e1'/);
+ assert.match(generator, /MAC_OUT = .*WorkDaddy\.icns/);
+ assert.match(generator, /WIN_OUT = .*WorkDaddy\.ico/);
+});
+
+test('macOS packaging synchronizes the tracked application icon', () => {
+ const buildSource = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');
+ assert.match(buildSource, /APP_ICON="\$DIR\/scripts\/assets\/WorkDaddy\.icns"/);
+ assert.match(buildSource, /cp "\$APP_ICON" "\$APP\/Contents\/Resources\/AppIcon\.icns"/);
+ assert.match(buildSource, /CFBundleIconName/);
+});
+
+test('Windows application icon applies a rounded alpha mask', () => {
+ assert.match(generator, /WINDOWS_CORNER_RADIUS_RATIO = 0\.20/);
+ assert.match(generator, /roundrectangle 0,0 1023,1023/);
+ assert.match(generator, /'CopyOpacity'/);
+ assert.match(generator, /render_base\(magick, base, rounded=True\)/);
+});
+
+test('macOS application icon leaves the background to the system mask', () => {
+ const macBuilder = generator.slice(
+ generator.indexOf('def build_mac_icon'),
+ generator.indexOf('def build_windows_icon'),
+ );
+ assert.match(macBuilder, /render_base\(magick, base, rounded=False, with_background=False\)/);
+});
+
+test('iconutil inputs use full RGBA PNGs so macOS keeps every icon size', () => {
+ assert.match(generator, /-type', 'TrueColorAlpha'/);
+ assert.match(generator, /-colorspace', 'sRGB'/);
+});
diff --git a/test/auto-copy-rules.test.js b/test/auto-copy-rules.test.js
index f85c309..44fa626 100644
--- a/test/auto-copy-rules.test.js
+++ b/test/auto-copy-rules.test.js
@@ -21,6 +21,8 @@ const {
removeAutoCopyAccount,
setAutoCopyMapping,
getAutoCopyMapping,
+ getAutoCopySessionMemberRecords,
+ selectLatestAutoCopyMember,
listOfficialModels,
maskApiKey,
sanitizeModel,
@@ -35,6 +37,16 @@ const {
checkinDisplayValue,
} = require('../scripts/lib.js');
+test('lineage sync selects the newest live member instead of trusting the switching source', () => {
+ const members = [
+ { uid: 'account-a', id: 'copy-a', contentMtime: 100, updatedAt: 500 },
+ { uid: 'account-b', id: 'copy-b', contentMtime: 300, updatedAt: 100 },
+ { uid: 'account-c', id: 'copy-c', contentMtime: 200, updatedAt: 900 },
+ ];
+ assert.deepEqual(selectLatestAutoCopyMember(members), members[1]);
+ assert.deepEqual(selectLatestAutoCopyMember([]), null);
+});
+
function tempDataDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-auto-copy-'));
}
@@ -123,6 +135,10 @@ test('lineage member lookup is deduplicated and one member can be removed withou
assert.equal(removeAutoCopySessionMember(dataDir, lineageId, 'target', 'target-old'), true);
assert.deepEqual(getAutoCopySessionMembers(dataDir, lineageId, 'target'), ['target-new']);
assert.equal(getAutoCopySession(dataDir, 'source', 'source-session').lineageId, lineageId);
+ assert.deepEqual(getAutoCopySessionMemberRecords(dataDir, lineageId), [
+ { uid: 'source', id: 'source-session' },
+ { uid: 'target', id: 'target-new' },
+ ]);
});
test('workspace rules are global across source accounts', () => {
diff --git a/test/cdp-targets.test.js b/test/cdp-targets.test.js
index 6c1f793..f93d7f9 100644
--- a/test/cdp-targets.test.js
+++ b/test/cdp-targets.test.js
@@ -81,6 +81,27 @@ test('isTargetForProfile 已绑定 profile 时允许标题兜底', () => {
}
});
+test('isTargetForProfile 企业配置只接受自身域名或路径提示', () => {
+ const enterprise = {
+ ...PROFILES['workbuddy-cn'],
+ customTarget: true,
+ apiHost: 'https://api.ent.example.com',
+ targetHints: ['workbuddy-ent'],
+ };
+ assert.equal(isTargetForProfile({
+ type: 'page', url: 'https://api.ent.example.com/app', title: '企业 WorkBuddy',
+ }, enterprise), true);
+ assert.equal(isTargetForProfile({
+ type: 'page', url: 'file:///C:/Company/workbuddy-ent/resources/index.html', title: 'WorkBuddy',
+ }, enterprise), true);
+ assert.equal(isTargetForProfile({
+ type: 'page', url: 'https://www.workbuddy.cn/app', title: 'WorkBuddy',
+ }, enterprise), false);
+ assert.equal(isTargetForProfile({
+ type: 'page', url: 'file:///unknown/index.html', title: 'WorkBuddy',
+ }, enterprise), false);
+});
+
test('looksLikeWbFamilyTarget 把四客户端页面都视为同族(不清理)', () => {
assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: AI_URL, title: 'WorkBuddy' }), true);
assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: CN_URL, title: 'WorkBuddy' }), true);
@@ -88,4 +109,4 @@ test('looksLikeWbFamilyTarget 把四客户端页面都视为同族(不清理
assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: VSCODE_URL, title: 'CodeBuddy' }), true);
// 任意其他 Chromium 应用不算同族(允许清理历史误注入)
assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: 'file:///Applications/Antigravity.app/Contents/index.html', title: 'Antigravity' }), false);
-});
\ No newline at end of file
+});
diff --git a/test/element-inspector.test.js b/test/element-inspector.test.js
index 72df40c..b29d2f8 100644
--- a/test/element-inspector.test.js
+++ b/test/element-inspector.test.js
@@ -35,7 +35,7 @@ test('插件内检查器包含 DOM 树、重叠元素栈、节点详情和 HTML'
assert.match(handler, /wbs-inspector-detail/);
assert.match(handler, /wbs-inspector-html/);
assert.match(handler, /mouseover/);
- assert.match(injectSource, /document\.elementsFromPoint/);
+ assert.match(pickerSource, /document\.elementsFromPoint/);
});
test('再次拾取时保留检查器和 WorkDaddy 面板并原地刷新节点', () => {
@@ -51,23 +51,23 @@ test('再次拾取时保留检查器和 WorkDaddy 面板并原地刷新节点',
});
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/);
+ assert.match(pickerSource, /\.wbs-modal\.wbs-inspector-modal\{[^}]*width:80vw;height:60vh/);
+ assert.match(pickerSource, /resize:both/);
+ assert.match(pickerSource, /overflow:hidden/);
+ assert.doesNotMatch(pickerSource, /@media\(max-width:900px\)\{\.wbs-inspector-modal/);
+ assert.doesNotMatch(pickerSource, /@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/);
+ assert.match(pickerSource, /\.wbs-inspector-mask\{[^}]*background:transparent[^}]*pointer-events:none/);
+ assert.match(pickerSource, /\.wbs-inspector-modal\{[^}]*pointer-events:auto/);
+ assert.doesNotMatch(pickerSource, /\.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(pickerSource, /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'\)/);
@@ -83,9 +83,9 @@ test('重注入通过检查器关闭入口清理监听器且拾取高亮恢复
});
test('检查器内部使用容器查询跟随自身尺寸响应式', () => {
- assert.match(injectSource, /container-type:inline-size/);
- assert.match(injectSource, /@container inspector \(max-width:760px\)/);
- assert.match(injectSource, /grid-template-columns:1fr/);
+ assert.match(pickerSource, /container-type:inline-size/);
+ assert.match(pickerSource, /@container inspector \(max-width:760px\)/);
+ assert.match(pickerSource, /grid-template-columns:1fr/);
});
test('检查器标题栏可拖拽且具有明确关闭按钮', () => {
diff --git a/test/enterprise-target.test.js b/test/enterprise-target.test.js
new file mode 100644
index 0000000..771526e
--- /dev/null
+++ b/test/enterprise-target.test.js
@@ -0,0 +1,300 @@
+'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');
+
+const {
+ buildOfficialTargetFromBinary,
+ buildTargetFromBinary,
+ inferredProcessNames,
+ readWorkBuddyTarget,
+ removeWorkBuddyTarget,
+ writeWorkBuddyTarget,
+} = require('../scripts/workbuddy-target.js');
+const { PROFILES, getProfile } = require('../scripts/profiles.js');
+
+function tempDir() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-enterprise-'));
+}
+
+test('official profiles remain byte-for-byte equivalent when no custom target exists', () => {
+ const dataDir = tempDir();
+ try {
+ for (const id of Object.keys(PROFILES)) {
+ assert.deepEqual(getProfile(id, { dataDir, env: {} }), PROFILES[id]);
+ }
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('selecting an enterprise executable derives its local data and CDP settings', () => {
+ const root = tempDir();
+ try {
+ const home = path.join(root, 'Users', 'tester');
+ const local = path.join(home, 'AppData', 'Local');
+ const binary = path.join(local, 'Programs', 'workbuddy-ent', 'workbuddy-ent.exe');
+ const dataRoot = path.join(home, '.workbuddy-ent');
+ const authDir = path.join(local, 'CodeBuddyExtension', 'Data', 'Public', 'auth');
+ const authFile = path.join(authDir, 'workbuddy-desktop-workbuddy-ent.info');
+ fs.mkdirSync(path.dirname(binary), { recursive: true });
+ fs.mkdirSync(dataRoot, { recursive: true });
+ fs.mkdirSync(authDir, { recursive: true });
+ fs.writeFileSync(binary, 'fixture');
+ fs.writeFileSync(authFile, JSON.stringify({
+ account: { uid: 'redacted', type: 'exclusive' },
+ realm: { iss: 'https://api.ent.example.com/oauth' },
+ }));
+
+ const target = buildTargetFromBinary({
+ binary,
+ profileId: 'workbuddy-cn',
+ version: '5.4.4.0',
+ home,
+ localAppData: local,
+ platform: process.platform,
+ });
+
+ assert.equal(target.binary, binary);
+ assert.equal(target.clientType, 'enterprise');
+ assert.equal(target.version, '5.4.4.0');
+ assert.deepEqual(target.processNames, ['workbuddy-ent.exe', 'WorkBuddyEnt.exe']);
+ assert.equal(target.dataRoot, dataRoot);
+ assert.equal(target.authFile, authFile);
+ assert.equal(target.sessionDb, path.join(dataRoot, 'workbuddy.db'));
+ assert.equal(target.modelsFile, path.join(dataRoot, 'models.json'));
+ assert.equal(target.apiHost, 'https://api.ent.example.com');
+ assert.deepEqual(target.cdp, { mode: 'environment', port: 9226 });
+ assert.equal(target.capabilities.checkin, false);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('custom target persists outside the install and overlays only its base profile', () => {
+ const dataDir = tempDir();
+ try {
+ const target = {
+ schemaVersion: 1,
+ profileId: 'workbuddy-cn',
+ binary: 'C:\\Company\\workbuddy-ent.exe',
+ version: '5.4.4.0',
+ lockVersion: true,
+ processName: 'workbuddy-ent.exe',
+ dataRoot: 'C:\\Users\\tester\\.workbuddy-ent',
+ authFile: 'C:\\Auth\\workbuddy-desktop-workbuddy-ent.info',
+ sessionDb: 'C:\\Users\\tester\\.workbuddy-ent\\workbuddy.db',
+ modelsFile: 'C:\\Users\\tester\\.workbuddy-ent\\models.json',
+ apiHost: 'https://api.ent.example.com',
+ targetHints: ['workbuddy-ent', 'api.ent.example.com'],
+ cdp: { mode: 'environment', port: 9226 },
+ capabilities: { checkin: false },
+ };
+ writeWorkBuddyTarget({ dataDir, profileId: 'workbuddy-cn', target, platform: 'win32' });
+ const persisted = readWorkBuddyTarget({ dataDir, profileId: 'workbuddy-cn', env: {}, platform: 'win32' });
+ const { processName, ...targetWithoutLegacyName } = target;
+ assert.deepEqual(persisted, {
+ ...targetWithoutLegacyName,
+ clientType: 'enterprise',
+ processNames: ['workbuddy-ent.exe'],
+ configured: true,
+ source: 'file',
+ });
+
+ const profile = getProfile('workbuddy-cn', { dataDir, env: {}, platform: 'win32' });
+ assert.equal(profile.id, 'workbuddy-cn');
+ assert.equal(profile.appPath, target.binary);
+ assert.equal(profile.dataRoot, target.dataRoot);
+ assert.equal(profile.authFile, target.authFile);
+ assert.equal(profile.apiHost, target.apiHost);
+ assert.deepEqual(profile.binaryNames, ['workbuddy-ent.exe']);
+ assert.equal(profile.cdp.mode, 'environment');
+ assert.equal(profile.capabilities.accounts, true);
+ assert.equal(profile.capabilities.checkin, false);
+ assert.equal(profile.customTarget, true);
+
+ assert.deepEqual(getProfile('workbuddy-ai', { dataDir, env: {}, platform: 'win32' }), PROFILES['workbuddy-ai']);
+ removeWorkBuddyTarget({ dataDir });
+ assert.deepEqual(getProfile('workbuddy-cn', { dataDir, env: {}, platform: 'win32' }), PROFILES['workbuddy-cn']);
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('enterprise profile overrides remain Windows-only and macOS keeps the official profile', () => {
+ const dataDir = tempDir();
+ try {
+ writeWorkBuddyTarget({
+ dataDir,
+ profileId: 'workbuddy-cn',
+ platform: 'win32',
+ target: {
+ schemaVersion: 1,
+ profileId: 'workbuddy-cn',
+ binary: 'C:\\Company\\workbuddy-ent.exe',
+ processNames: ['workbuddy-ent.exe'],
+ dataRoot: 'C:\\Users\\tester\\.workbuddy-ent',
+ authFile: 'C:\\Auth\\workbuddy-desktop-workbuddy-ent.info',
+ sessionDb: 'C:\\Users\\tester\\.workbuddy-ent\\workbuddy.db',
+ modelsFile: 'C:\\Users\\tester\\.workbuddy-ent\\models.json',
+ apiHost: 'https://api.ent.example.com',
+ targetHints: ['workbuddy-ent', 'api.ent.example.com'],
+ cdp: { mode: 'environment', port: 9226 },
+ },
+ });
+
+ assert.deepEqual(
+ getProfile('workbuddy-cn', { dataDir, env: {}, platform: 'darwin' }),
+ PROFILES['workbuddy-cn']
+ );
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('selecting the official executable pins its path without changing official behavior', () => {
+ const dataDir = tempDir();
+ try {
+ const target = buildOfficialTargetFromBinary({
+ binary: 'D:\\Portable\\WorkBuddy.exe',
+ profileId: 'workbuddy-cn',
+ version: '5.4.4.0',
+ platform: 'win32',
+ });
+ writeWorkBuddyTarget({ dataDir, profileId: 'workbuddy-cn', target, platform: 'win32' });
+ const profile = getProfile('workbuddy-cn', { dataDir, env: {}, platform: 'win32' });
+
+ assert.equal(target.clientType, 'official');
+ assert.equal(profile.appPath, 'D:\\Portable\\WorkBuddy.exe');
+ assert.equal(profile.configuredTarget, true);
+ assert.equal(profile.customTarget, false);
+ assert.equal(profile.cdp.mode, 'argument');
+ assert.equal(profile.apiHost, PROFILES['workbuddy-cn'].apiHost);
+ assert.equal(profile.authFile, PROFILES['workbuddy-cn'].authFile);
+ assert.deepEqual(profile.capabilities, PROFILES['workbuddy-cn'].capabilities);
+ assert.deepEqual(profile.targetHints, PROFILES['workbuddy-cn'].targetHints);
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('installer configuration command persists exactly one selected client', () => {
+ const dataDir = tempDir();
+ const script = path.join(__dirname, '..', 'scripts', 'workbuddy-target.js');
+ try {
+ const official = spawnSync(process.execPath, [
+ script, '--configure', '--profile', 'workbuddy-cn',
+ '--binary', 'C:\\Apps\\WorkBuddy.exe', '--version', '5.4.4.0', '--data-dir', dataDir,
+ ], { encoding: 'utf8' });
+ assert.equal(official.status, 0, official.stderr);
+ assert.equal(readWorkBuddyTarget({ dataDir, profileId: 'workbuddy-cn', env: {}, platform: 'win32' }).clientType, 'official');
+
+ const enterprise = spawnSync(process.execPath, [
+ script, '--configure', '--profile', 'workbuddy-cn',
+ '--binary', 'C:\\Apps\\workbuddy-ent.exe', '--version', '5.4.5.0', '--data-dir', dataDir,
+ ], { encoding: 'utf8' });
+ assert.equal(enterprise.status, 0, enterprise.stderr);
+ const selected = readWorkBuddyTarget({ dataDir, profileId: 'workbuddy-cn', env: {}, platform: 'win32' });
+ assert.equal(selected.clientType, 'enterprise');
+ assert.equal(selected.binary, 'C:\\Apps\\workbuddy-ent.exe');
+ assert.equal(selected.version, '5.4.5.0');
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('macOS launcher target probe remains a no-op outside Windows installer configuration', () => {
+ const dataDir = tempDir();
+ const script = path.join(__dirname, '..', 'scripts', 'workbuddy-target.js');
+ try {
+ const result = spawnSync(process.execPath, [
+ script, '--profile', 'workbuddy-cn', '--data-dir', dataDir,
+ ], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, '');
+ assert.equal(fs.existsSync(path.join(dataDir, 'workbuddy-target.json')), false);
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('unsafe enterprise target values fail closed', () => {
+ const dataDir = tempDir();
+ try {
+ const base = {
+ schemaVersion: 1,
+ profileId: 'workbuddy-cn',
+ binary: 'C:\\Company\\workbuddy-ent.exe',
+ processName: 'workbuddy-ent.exe',
+ dataRoot: 'C:\\Users\\tester\\.workbuddy-ent',
+ authFile: 'C:\\Auth\\workbuddy.info',
+ apiHost: 'https://api.ent.example.com',
+ cdp: { mode: 'environment', port: 9226 },
+ };
+ for (const override of [
+ { profileId: 'workbuddy-ai' },
+ { binary: 'relative\\workbuddy-ent.exe' },
+ { processName: '..\\not-safe.exe' },
+ { processNames: ['workbuddy-ent.exe', '..\\not-safe.exe'] },
+ { processNames: ['WorkBuddyEnt.exe'] },
+ { apiHost: 'http://api.ent.example.com' },
+ { apiHost: 'https://user:[email protected]' },
+ { cdp: { mode: 'unknown', port: 9226 } },
+ { cdp: { mode: 'environment', port: 80 } },
+ ]) {
+ assert.throws(
+ () => writeWorkBuddyTarget({ dataDir, profileId: 'workbuddy-cn', target: { ...base, ...override }, platform: 'win32' }),
+ /profile|absolute|进程名|HTTPS|CDP|port/i
+ );
+ }
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('enterprise process candidates are narrow and keep the selected executable first', () => {
+ assert.deepEqual(
+ inferredProcessNames('C:\\Company\\workbuddy-ent.exe', 'win32'),
+ ['workbuddy-ent.exe', 'WorkBuddyEnt.exe']
+ );
+ assert.deepEqual(
+ inferredProcessNames('C:\\Company\\AcmeBuddy.exe', 'win32'),
+ ['AcmeBuddy.exe']
+ );
+});
+
+test('the existing Windows installer owns the single client selection flow', () => {
+ const root = path.join(__dirname, '..');
+ const launcher = fs.readFileSync(path.join(root, 'scripts', 'win-launcher.js'), 'utf8');
+ const native = fs.readFileSync(path.join(root, 'scripts', 'windows-native', 'main.go'), 'utf8');
+ const daemon = fs.readFileSync(path.join(root, 'scripts', 'daemon.js'), 'utf8');
+ const inject = fs.readFileSync(path.join(root, 'scripts', 'inject.js'), 'utf8');
+ const installer = fs.readFileSync(path.join(root, 'scripts', 'win', 'workdaddy.iss'), 'utf8');
+
+ assert.match(launcher, /PROFILE\.cdp\.mode === 'environment'/);
+ assert.match(launcher, /WORKBUDDY_REMOTE_DEBUGGING_PORT/);
+ assert.doesNotMatch(launcher + native, /--select-workbuddy|GetOpenFileNameW/);
+ assert.match(native, /workbuddy-target\.json/);
+ assert.match(native, /ProcessNames/);
+ assert.match(native, /--target-info/);
+ assert.match(native, /ClientType\s+string\s+`json:"clientType"`/);
+ assert.match(installer, /CreateInputFilePage/);
+ assert.match(installer, /DetectOfficialClient/);
+ assert.match(installer, /CurrentVersion\\Uninstall/);
+ assert.match(installer, /CompareClientFileVersions/);
+ assert.match(installer, /ReadSavedClient/);
+ assert.match(installer, /使用自动识别路径/);
+ assert.match(installer, /SaveSelectedClient/);
+ assert.match(installer, /--configure --profile/);
+ assert.match(installer, /--check-workbuddy --binary/);
+ assert.doesNotMatch(daemon, /\/api\/workbuddy-target\/(?:select|reset)/);
+ assert.doesNotMatch(inject, /wbs-client-target|选择其他 WorkBuddy 客户端|恢复自动识别/);
+ assert.match(daemon, /u\.origin === PROFILE\.apiHost/);
+ assert.doesNotMatch(launcher + daemon + native, /\bsetx(?:\.exe)?\b/i);
+ assert.match(launcher, /所选 WorkBuddy 版本已变化/);
+ assert.match(launcher, /重新运行 WorkDaddy 安装程序/);
+});
diff --git a/test/macos-dmg-layout.test.js b/test/macos-dmg-layout.test.js
new file mode 100644
index 0000000..f3d9a7f
--- /dev/null
+++ b/test/macos-dmg-layout.test.js
@@ -0,0 +1,52 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const repoRoot = path.join(__dirname, '..');
+const buildSource = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');
+const backgroundPath = path.join(repoRoot, 'scripts', 'assets', 'macos-dmg-background.svg');
+
+test('macOS DMG build stores a fixed commercial Finder layout', () => {
+ assert.match(buildSource, /DMG_WINDOW_WIDTH=620/);
+ assert.match(buildSource, /DMG_WINDOW_HEIGHT=400/);
+ assert.match(buildSource, /DMG_ICON_SIZE=112/);
+ assert.match(buildSource, /set bounds to \{windowLeft, windowTop, windowRight, windowBottom\}/);
+ assert.match(buildSource, /set position of item appName to \{150, 190\}/);
+ assert.match(buildSource, /set position of item "Applications" to \{470, 190\}/);
+ assert.match(buildSource, /set background picture of viewOptions to file "\.background:background\.tiff"/);
+ assert.match(buildSource, /set arrangement of viewOptions to not arranged/);
+ assert.match(buildSource, /set icon size of viewOptions to dmgIconSize/);
+ assert.match(buildSource, /set position of every item to \{windowRight \+ 100, 100\}/);
+ assert.match(buildSource, /set bounds to \{windowLeft, windowTop, windowRight - 10, windowBottom - 10\}/);
+});
+
+test('macOS DMG layout is written to a writable image before final compression', () => {
+ assert.match(buildSource, /hdiutil create[\s\S]*-format UDRW/);
+ assert.match(buildSource, /hdiutil attach[\s\S]*-readwrite[\s\S]*-plist/);
+ assert.match(buildSource, /plistlib\.load/);
+ assert.match(buildSource, /entity\.get\('mount-point'\)/);
+ assert.match(buildSource, /osascript[\s\S]*tell application "Finder"/);
+ assert.match(buildSource, /test -f "\$MOUNT_DIR\/\.DS_Store"/);
+ assert.match(buildSource, /rm -rf -- "\$MOUNT_DIR\/\.fseventsd"/);
+ assert.match(buildSource, /hdiutil convert[\s\S]*-format UDZO/);
+});
+
+test('macOS DMG uses a fixed-size SVG master for its arrow artwork', () => {
+ assert.equal(fs.existsSync(backgroundPath), true, 'missing DMG SVG background');
+ const svg = fs.readFileSync(backgroundPath, 'utf8');
+ assert.match(buildSource, /BACKGROUND_1X="\$STAGE\/\.background\/background-1x\.png"/);
+ assert.match(buildSource, /BACKGROUND_2X="\$STAGE\/\.background\/background-2x\.png"/);
+ assert.match(buildSource, /sips -s format png "\$DMG_BACKGROUND_SVG" --out "\$BACKGROUND_1X"/);
+ assert.match(buildSource, /sips -s format png -z 800 1240 "\$DMG_BACKGROUND_SVG" --out "\$BACKGROUND_2X"/);
+ assert.match(buildSource, /tiffutil -cathidpicheck[\s\S]*background\.tiff/);
+ assert.match(buildSource, /BACKGROUND_1X_WIDTH[\s\S]*pixelWidth/);
+ assert.match(buildSource, /BACKGROUND_2X_WIDTH[\s\S]*pixelWidth/);
+ assert.match(svg, /<svg[^>]+viewBox="0 0 620 400"/);
+ assert.match(svg, /<path\b[^>]+id="install-arrow"/);
+ assert.match(svg, /fill="#697386"/);
+ assert.match(svg, /transform="translate\(296\.5 172\.5\) scale\(0\.35\)"/);
+ assert.match(svg, /d="m50\.868 78\.016l36\.418-26\.055/);
+ assert.doesNotMatch(svg, /<(?:line|polyline)\b/);
+ assert.doesNotMatch(svg, /<text\b/);
+});
diff --git a/test/no-disturb-match.test.js b/test/no-disturb-match.test.js
index 8cd8096..7ab6131 100644
--- a/test/no-disturb-match.test.js
+++ b/test/no-disturb-match.test.js
@@ -102,7 +102,7 @@ function runCase(desc, labels, opts) {
const r = runCase('检测到受保护文件修改', ['允许', '本次会话内始终允许', '拒绝']);
assert.strictEqual(r.acted, '1允许', 'once 按钮带序号前缀应被规范化并命中');
assert.strictEqual(r.clicked, true, '命中按钮应被点击');
- assert.deepStrictEqual(r.audit, ['once:允许']);
+ assert.deepStrictEqual(r.audit, ['once:允许', 'session:本次会话内始终允许']);
console.log('✓ AI 拦截卡-受保护文件修改:自动点「1允许」');
}
// 2) 敏感凭据路径
@@ -145,4 +145,4 @@ function runCase(desc, labels, opts) {
console.log('✓ once 禁用:回退自动点「2本次会话内始终允许」');
}
-console.log('\n免打扰弹窗匹配逻辑回归测试全部通过 ✅');
\ No newline at end of file
+console.log('\n免打扰弹窗匹配逻辑回归测试全部通过 ✅');
diff --git a/test/runtime-dependencies.test.js b/test/runtime-dependencies.test.js
index c683978..f9c23f3 100644
--- a/test/runtime-dependencies.test.js
+++ b/test/runtime-dependencies.test.js
@@ -61,6 +61,13 @@ test('macOS release stages every daemon startup dependency', () => {
}
});
+test('macOS release synchronizes the optional internal picker without stale shell copies', () => {
+ const buildSource = fs.readFileSync(path.join(scriptsDir, 'build-mac-dmg.sh'), 'utf8');
+ assert.match(buildSource, /if \[ -f "scripts\/picker-internal\.js" \]; then/);
+ assert.match(buildSource, /cp "scripts\/picker-internal\.js" "\$APP\/Contents\/Resources\/scripts\/picker-internal\.js"/);
+ assert.match(buildSource, /rm -f "\$APP\/Contents\/Resources\/scripts\/picker-internal\.js"/);
+});
+
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-'));
diff --git a/test/session-monitor.test.js b/test/session-monitor.test.js
new file mode 100644
index 0000000..c480ffb
--- /dev/null
+++ b/test/session-monitor.test.js
@@ -0,0 +1,181 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const test = require('node:test');
+const inject = require('../scripts/inject.js');
+const compat = require('../scripts/workbuddy-compat.js');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const injectSource = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+
+test('approval gate accepts attached background approval cards without visibility checks', () => {
+ const classify = inject.classifyNoDisturbApprovalCandidate;
+ assert.equal(classify({
+ label: '1允许',
+ context: '任务 B 检测到受保护文件修改',
+ hasDeny: true,
+ hasOnce: true,
+ buttonCount: 3,
+ }), 'once');
+ assert.equal(classify({
+ label: '始终允许',
+ context: '权限 approval\n拒绝',
+ hasDeny: true,
+ hasOnce: true,
+ buttonCount: 2,
+ }), 'session');
+});
+
+test('approval gate handles simultaneous cards and rejects unrelated confirmations', () => {
+ const classify = inject.classifyNoDisturbApprovalCandidate;
+ const cards = [
+ { label: '允许', context: '沙箱外写入\n拒绝', hasDeny: true, hasOnce: true, buttonCount: 2 },
+ { label: 'Allow', context: '系统级工具\nDeny', hasDeny: true, hasOnce: true, buttonCount: 2 },
+ { label: '确认', context: '确认生成图片,消耗 10 积分\n取消', hasDeny: false, buttonCount: 2 },
+ ];
+ assert.deepEqual(cards.map(classify), ['once', 'once', null]);
+ assert.equal(classify({
+ label: '允许',
+ context: '普通设置确认',
+ hasDeny: false,
+ buttonCount: 2,
+ disabled: true,
+ }), null);
+});
+
+test('session monitor registry keeps bounded per-session logs in memory', () => {
+ const registry = inject.createSessionMonitorRegistry({ maxLogs: 2, maxSessions: 2 });
+ registry.ensure('a', { title: '任务 A', status: 'running' });
+ registry.append('a', 'state', { status: 'running' });
+ registry.append('a', 'approval-clicked', { source: 'api' });
+ registry.append('a', 'continue-sent', { source: 'api' });
+ assert.equal(registry.list().length, 1);
+ assert.equal(registry.get('a').logs.length, 2);
+ assert.equal(registry.get('a').logs[0].event, 'approval-clicked');
+ assert.equal(registry.get('a').logs[1].event, 'continue-sent');
+ registry.ensure('b');
+ registry.ensure('c');
+ assert.equal(registry.get('a'), null);
+ assert.deepEqual(registry.list().map((item) => item.id), ['b', 'c']);
+});
+
+test('session monitor progress gate excludes completed and idle snapshots', () => {
+ const inProgress = inject.isSessionMonitorInProgress;
+ assert.equal(inProgress({ busy: true }), true);
+ assert.equal(inProgress({ blocked: true }), true);
+ assert.equal(inProgress({ hydrating: true }), true);
+ assert.equal(inProgress({ complete: true, busy: false }), false);
+ assert.equal(inProgress({ state: 'done', busy: false }), false);
+});
+
+test('session resource normalizer treats background terminal updates as final', () => {
+ const normalize = inject.normalizeSessionMonitorResourceRecord;
+ assert.deepEqual(normalize({
+ id: 'task-b',
+ status: 'working',
+ protocolStatus: 'completed',
+ name: '任务 B',
+ }, 'sessionUpdated'), {
+ id: 'task-b',
+ title: '任务 B',
+ status: 'completed',
+ pendingInputKind: '',
+ active: false,
+ terminal: true,
+ event: 'sessionUpdated',
+ });
+ assert.equal(normalize({ id: 'task-b', status: 'model_streaming' }, 'sessionUpdated').active, true);
+ assert.equal(normalize({ id: 'task-b', status: 'pending' }, 'sessionUpdated').active, false);
+ assert.equal(normalize({ id: 'task-b', status: 'pending', activePromptStartedAt: 123 }, 'sessionUpdated').active, true);
+ assert.equal(normalize({ id: 'task-b', status: 'pending', pendingInputKind: 'permission' }, 'sessionUpdated').active, true);
+ assert.equal(normalize({
+ id: 'task-b',
+ status: 'pending',
+ messageQueueRuntime: { pendingItemCount: 1, paused: false },
+ }, 'sessionUpdated').active, true);
+});
+
+test('session lifecycle adds unknown background work and removes terminal sessions', () => {
+ const action = inject.sessionMonitorLifecycleAction;
+ assert.equal(action({ id: 'task-b', active: true, terminal: false }, false), 'add');
+ assert.equal(action({ id: 'task-b', active: true, terminal: false }, true), 'update');
+ assert.equal(action({ id: 'task-b', active: false, terminal: true }, true), 'remove');
+ assert.equal(action({ id: 'task-b', active: false, terminal: true }, false), 'ignore');
+ assert.equal(action({ id: 'task-b', active: false, terminal: false }, false), 'ignore');
+});
+
+test('multi-session monitor subscribes while idle and detaches switched controllers without deleting sessions', () => {
+ assert.match(injectSource, /function acStartMultiMonitor\(\)[\s\S]*var hasResource = acMultiBindSessionResource\(\);[\s\S]*if \(!hasResource && !hasSidebar && !Object\.keys\(acMulti\.sessions\)\.length\)/);
+ assert.match(injectSource, /function acMultiDetachController\(session\)[\s\S]*session\.controller = null;/);
+ assert.match(injectSource, /function acMultiFinishSession\(session\)[\s\S]*delete acMulti\.sessions\[session\.id\];/);
+});
+
+test('session resource subscription delivers non-active completion without controller changes', () => {
+ const handlers = new Map();
+ const resource = {
+ on(event, handler) { handlers.set(event, handler); },
+ off(event, handler) { if (handlers.get(event) === handler) handlers.delete(event); },
+ };
+ const updates = [];
+ const unsubscribe = inject.subscribeSessionMonitorResource(resource, (update) => updates.push(update));
+
+ handlers.get('sessionUpdated')({ id: 'task-b', status: 'completed' });
+ handlers.get('sessionsChanged')([
+ { id: 'task-a', status: 'working' },
+ { id: 'task-c', status: 'failed' },
+ ]);
+
+ assert.deepEqual(updates.map((item) => [item.id, item.status, item.terminal]), [
+ ['task-b', 'completed', true],
+ ['task-a', 'working', false],
+ ['task-c', 'failed', true],
+ ]);
+ unsubscribe();
+ assert.equal(handlers.size, 0);
+});
+
+test('monitor log card stays hidden until the five-click logo unlock', () => {
+ assert.match(injectSource, /id="wbs-monitor-log-card"' \+ \(hiddenToolsUnlocked \? '' : ' style="display:none"'\)/);
+ assert.match(injectSource, /if \(piClickCount >= 5\)[\s\S]*hiddenToolsUnlocked = true;[\s\S]*monitorLogCard\.style\.display = '';/);
+});
+
+test('compat discovers multiple capability-shaped controllers and de-duplicates fibers', () => {
+ const controllers = [
+ { conversationId: 'a', messageStore: { getState() {}, subscribe() {} }, getMessagesViewState() {} },
+ { conversationId: 'b', messageStore: { getState() {}, subscribe() {} }, getMessagesViewState() {} },
+ ];
+ const root = { children: [], __reactFiber$root: { memoizedProps: { value: controllers[0] }, return: null } };
+ const child = { children: [], __reactFiber$child: { memoizedProps: { controller: controllers[1] }, return: root.__reactFiber$root } };
+ root.children.push(child);
+ const doc = { querySelector(selector) { return selector === '#root > div' ? root : null; } };
+ assert.deepEqual(compat.findConversationControllers(doc).map((c) => c.conversationId), ['a', 'b']);
+});
+
+test('compat discovers the global session resource by capabilities', () => {
+ const resource = { on() {}, off() {}, list() {}, getByIds() {} };
+ const adapter = {
+ sessionsResource: resource,
+ enqueueConversationMessageQueueItem() {},
+ pauseConversationMessageQueue() {},
+ };
+ const root = { children: [], __reactFiber$root: { memoizedProps: { adapter }, return: null } };
+ const doc = { querySelector(selector) { return selector === '#root > div' ? root : null; } };
+ assert.equal(compat.findSessionsResource(doc), resource);
+});
+
+test('compat reads the sidebar conversation status snapshot from a narrow fiber root', () => {
+ const records = [
+ { id: 'task-a', title: '任务 A', status: 'running' },
+ { id: 'task-b', title: '任务 B', status: 'completed' },
+ ];
+ const ownerFiber = { memoizedProps: { allConversations: records }, return: null };
+ const item = { __reactFiber$item: { memoizedProps: {}, return: ownerFiber } };
+ const doc = {
+ querySelector(selector) {
+ if (selector === '.conversation-list .conversation-item') return item;
+ return null;
+ },
+ };
+ assert.deepEqual(compat.findConversationListRecords(doc), records);
+});
diff --git a/test/stash-queue.test.js b/test/stash-queue.test.js
index 532ffd7..7f5af44 100644
--- a/test/stash-queue.test.js
+++ b/test/stash-queue.test.js
@@ -5,6 +5,9 @@ const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
const {
+ composerBlocksFromTree,
+ composerTextFromTree,
+ contentToBlocks,
isStashQueueItem,
stashContentMatches,
} = require('../scripts/inject.js');
@@ -51,6 +54,72 @@ test('async stash cleanup only clears the content captured at click time', () =>
assert.equal(stashContentMatches(captured, { text: '先暂存这条', items: [{ type: 'image', uri: 'new-image' }] }), false);
});
+function text(value) {
+ return { nodeType: 3, nodeValue: value, childNodes: [] };
+}
+
+function element(attributes, children) {
+ const attrs = attributes || {};
+ return {
+ nodeType: 1,
+ childNodes: children || [],
+ hasAttribute(name) { return Object.prototype.hasOwnProperty.call(attrs, name); },
+ getAttribute(name) { return attrs[name] == null ? null : String(attrs[name]); },
+ };
+}
+
+test('stash composer text excludes Slate placeholder text', () => {
+ const editor = element({}, [
+ element({}, [text('喵喵喵')]),
+ element({ 'data-slate-placeholder': 'true' }, [
+ text('今天帮你做些什么? @ 引用对话文件,/ 调用技能与指令'),
+ ]),
+ ]);
+
+ assert.equal(composerTextFromTree(editor), '喵喵喵');
+});
+
+test('stash composer blocks retain inline selection quote order and skip rendered labels', () => {
+ const quoteMeta = (selectedText) => ({
+ displayAsPhrase: true,
+ displayAsContext: false,
+ displayText: '引用文本',
+ selectionQuote: true,
+ mentionType: 'selection',
+ selectedText,
+ title: '引用文本',
+ });
+ const quote1 = {
+ type: 'resource_link',
+ name: '引用文本',
+ uri: 'selection://document-selection',
+ _meta: quoteMeta('原文1'),
+ };
+ const quote2 = {
+ type: 'resource_link',
+ name: '引用文本',
+ uri: 'selection://document-selection',
+ _meta: quoteMeta('原文2'),
+ };
+ const editor = element({}, [
+ element({}, [
+ element({ 'data-contentblock': JSON.stringify(quote1) }, [text('引用文本')]),
+ text('111 '),
+ element({ 'data-contentblock': JSON.stringify(quote2) }, [text('引用文本')]),
+ text('222'),
+ ]),
+ element({}, [text('333')]),
+ ]);
+ const blocks = composerBlocksFromTree(editor);
+ assert.deepEqual(blocks.map((block) => block.type), ['resource_link', 'text', 'resource_link', 'text']);
+ assert.deepEqual(contentToBlocks({ orderedBlocks: blocks }), [
+ { type: 'resource_link', name: '引用文本', uri: 'selection://document-selection', title: '引用文本', _meta: quoteMeta('原文1') },
+ { type: 'text', text: '111 ' },
+ { type: 'resource_link', name: '引用文本', uri: 'selection://document-selection', title: '引用文本', _meta: quoteMeta('原文2') },
+ { type: 'text', text: '222\n333' },
+ ]);
+});
+
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);
@@ -85,6 +154,10 @@ test('stash cleanup clears the official composer store and persistent conversati
assert.match(inject, /WBS_COMPAT\.draftStorageKey\(sessionId\)/);
assert.match(inject, /localStorage\.removeItem\(draftKey\)/);
assert.match(inject, /clearModernComposerDraft\(ed, stashSessionAtClick\)/);
+ const start = inject.indexOf('function clearComposerViaOnChange(expectedContent)');
+ const end = inject.indexOf('\n // 队列操作超时包装', start);
+ assert.match(inject.slice(start, end), /var modernDraftCleared = clearModernComposerDraft\(ed, stashSessionAtClick\)/);
+ assert.match(inject.slice(start, end), /if \(modernDraftCleared\) return/);
});
test('theme tab is capability-gated and available to WorkBuddy AI', () => {
@@ -152,11 +225,23 @@ test('modern queue path uses the top-level notifying adapter and clears stale ad
assert.match(inject, /if \(stashBusy \|\| stashInFlight\) return/);
assert.match(inject, /stashInFlight = stashWork/);
assert.match(inject, /stashInFlight = null/);
- assert.match(inject, /function writeModernQueueItemToComposer\(item\)/);
assert.match(inject, /controller\.promptQueue\.emitQueueUpdate\(\)/);
assert.match(inject, /stashSessionAtClick = sessionId/);
});
+test('real modern queue actions remain owned by WorkBuddy official handlers', () => {
+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ const start = inject.indexOf('function handleModernQueueActionClick(event)');
+ const end = inject.indexOf("listen(document, 'click', handleModernQueueActionClick, true);", start);
+ assert.ok(start >= 0 && end > start);
+ const handler = inject.slice(start, end);
+
+ assert.match(handler, /itemId\.indexOf\('wbs-pending-'\) !== 0\) return/);
+ assert.doesNotMatch(handler, /sendConversationMessageQueueItemNow/);
+ assert.doesNotMatch(handler, /removeConversationMessageQueueItem/);
+ assert.doesNotMatch(inject, /function writeModernQueueItemToComposer\(item\)/);
+});
+
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)');
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index a3e3da7..c2fc54f 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -412,6 +412,7 @@ test('daemon settings writes tolerate transient Windows file locks', () => {
const settingsEnd = daemon.indexOf('\n}\n\nfunction buildAskRuleBlock', settingsStart);
const appStart = daemon.indexOf('function writeAppConfig(');
const appEnd = daemon.indexOf('\n}\nfunction acBlock', appStart);
+ assert.match(daemon.slice(settingsStart, settingsEnd), /mkdirSync\(path\.dirname\(file\),\s*\{\s*recursive:\s*true\s*\}\)/);
assert.match(daemon.slice(settingsStart, settingsEnd), /replaceFileWithRetry\(file/);
assert.match(daemon.slice(appStart, appEnd), /replaceFileWithRetry\(file/);
assert.doesNotMatch(daemon.slice(settingsStart, settingsEnd), /file \+ '\\.wbs-tmp'/);
@@ -1020,6 +1021,9 @@ test('automatic session copy includes workspace-only rules when the initial plan
assert.match(daemon, /hasSourceAutoCopyRules/);
assert.match(daemon, /hasPendingAutoCopyTo\(uid\)/);
assert.match(daemon, /startAutoCopyJob\(sourceUid, uid, autoCopyPlan\)/);
+ assert.match(daemon, /syncAutoCopyLineage\(src\.lineageId, targetUid\)/);
+ assert.match(daemon, /selectLatestAutoCopyMember\(live\)/);
+ assert.match(daemon, /lineageId = ensureAutoCopySession\(DATA_DIR, source, row\.id\)/);
assert.match(inject, /data-auto-kind="' \+ kind \+ '"/);
assert.match(inject, /autoCopyButton\('workspace'/);
assert.match(inject, /autoCopyButton\('session'/);
diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.js
index 6f7a6a1..53eb1e9 100644
--- a/test/windows-native-flow.test.js
+++ b/test/windows-native-flow.test.js
@@ -6,7 +6,7 @@ const { EventEmitter } = require('node:events');
const path = require('node:path');
const test = require('node:test');
const { launchWindowsInstaller } = require('../scripts/windows-installer-launch.js');
-const { strictPowerShellLines } = require('../scripts/win-launcher.js');
+const { nativeLaunchFailed, strictPowerShellLines } = require('../scripts/win-launcher.js');
const root = path.join(__dirname, '..');
const read = (relative) => fs.readFileSync(path.join(root, relative), 'utf8');
@@ -25,6 +25,14 @@ test('Windows native launcher is the packaged user-level entry point', () => {
assert.match(source, /mbRetryCancel/);
});
+test('Windows shortcuts use a versioned icon path to invalidate the shell icon cache', () => {
+ const installer = read('scripts/win/workdaddy.iss');
+ assert.match(installer, /DestName: "\{#PackageName\}-\{#AppVersion\}\.ico"/);
+ assert.match(installer, /IconFilename: "\{app\}\\scripts\\\{#PackageName\}-\{#AppVersion\}\.ico"/);
+ assert.match(installer, /\[InstallDelete\][\s\S]*WorkDaddy-\*\.ico/);
+ assert.doesNotMatch(installer, /IconFilename: "\{app\}\\scripts\\WorkDaddy\.ico"/);
+});
+
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');
@@ -57,6 +65,34 @@ test('installer waits for the exact profile client with a visible recheck dialog
assert.match(installer, /CloseApplications=no/);
});
+test('installer does not expand the app directory while initializing the client page', () => {
+ const installer = read('scripts/win/workdaddy.iss');
+ const helperStart = installer.indexOf('function RunNativeHelper');
+ const helperEnd = installer.indexOf('\nfunction ', helperStart + 1);
+ const initializeStart = installer.indexOf('procedure InitializeWizard');
+ const initializeEnd = installer.indexOf('\nfunction ', initializeStart + 1);
+ assert.ok(helperStart >= 0 && helperEnd > helperStart);
+ assert.ok(initializeStart >= 0 && initializeEnd > initializeStart);
+ assert.doesNotMatch(installer.slice(helperStart, helperEnd), /ExpandConstant\('\{app\}'\)/);
+ assert.doesNotMatch(installer.slice(initializeStart, initializeEnd), /ExpandConstant\('\{app\}'\)/);
+ assert.match(installer, /--stop-lifecycle --app-dir "' \+ ExpandConstant\('\{app\}'\) \+ '"/);
+});
+
+test('installer prefers the newest registered official client without replacing enterprise targets', () => {
+ const installer = read('scripts/win/workdaddy.iss');
+ const native = read('scripts/windows-native/main.go');
+ assert.match(installer, /CurrentVersion\\Uninstall/);
+ assert.match(installer, /DisplayIcon/);
+ assert.match(installer, /InstallLocation/);
+ assert.match(installer, /for Index := Length\(Value\) downto 1 do/);
+ assert.match(installer, /ExtractFileExt\(Copy\(Value, 1, Marker - 1\)\)/);
+ assert.match(installer, /CompareClientFileVersions\(Candidate, BestCandidate\) > 0/);
+ assert.match(installer, /PreferDetectedOfficialClient/);
+ assert.match(installer, /CompareText\(SavedClientType, 'enterprise'\) = 0/);
+ assert.match(native, /ClientType\s+string\s+`json:"clientType"`/);
+ assert.match(native, /target\.Binary\+"\\r\\n"\+version\+"\\r\\n"\+clientType/);
+});
+
test('Windows update opens the verified Setup visibly and keeps daemon alive', () => {
const daemon = read('scripts/daemon.js');
const inject = read('scripts/inject.js');
@@ -131,6 +167,23 @@ test('native lifecycle cleanup accepts a PID that exits during exact inspection'
assert.match(source.slice(exitedCheck, mismatch), /waitResult == waitObject0[\s\S]*return false, 0, nil/);
});
+test('native lifecycle can recover a missing watchdog PID only from a unique daemon parent', () => {
+ const source = read('scripts/windows-native/main.go');
+ assert.match(source, /ParentPID\s+uint32/);
+ assert.match(source, /ParentPID:\s*entry\.ParentProcessID/);
+ assert.match(source, /func recoverWatchdogPID\(/);
+ assert.match(source, /daemonPID\s*int/);
+ assert.match(source, /len\(candidates\) != 1/);
+ assert.match(source, /candidate\.Path/);
+ const stopStart = source.indexOf('func stopLifecycle(profile, appDir string) int');
+ const stopEnd = source.indexOf('\nfunc appendLog(', stopStart);
+ assert.ok(stopStart >= 0 && stopEnd > stopStart);
+ const stop = source.slice(stopStart, stopEnd);
+ assert.match(stop, /recoverWatchdogPID\(/);
+ assert.match(stop, /readLockPID\(/);
+ assert.match(stop, /watchdog\.pid[\s\S]*无法证明当前 daemon 的唯一 watchdog[\s\S]*return exitIdentityMismatch/);
+});
+
test('installer lifecycle cleanup releases only the exact installed native launcher', () => {
const source = read('scripts/windows-native/main.go');
const stopStart = source.indexOf('func stopInstalledLauncher(appDir string) int');
@@ -139,6 +192,7 @@ test('installer lifecycle cleanup releases only the exact installed native launc
const stop = source.slice(stopStart, stopEnd);
assert.match(stop, /filepath\.Join\(appDir, "WorkDaddyLauncher\.exe"\)/);
assert.match(stop, /enumerateProcesses\(\)/);
+ assert.match(stop, /record\.PID == uint32\(os\.Getpid\(\)\)[\s\S]*continue/);
assert.match(stop, /samePath\(record\.Path, expectedLauncher\)/);
assert.match(stop, /len\(matches\) > 1[\s\S]*exitIdentityMismatch/);
assert.match(stop, /terminateExactProcess\(int\(matches\[0\]\.PID\), expectedLauncher, "launcher"\)/);
@@ -194,3 +248,36 @@ test('native startup failures report one structured diagnostic event', () => {
assert.match(launcher, /error\.sentryExtra/);
assert.match(launcher, /nativeDaemonDiagnostics/);
});
+
+test('native startup precisely restarts a verified WorkBuddy without CDP', () => {
+ const launcher = read('scripts/win-launcher.js');
+ const stopStart = launcher.indexOf('function stopNativeWorkBuddy()');
+ const stopEnd = launcher.indexOf('\nfunction ', stopStart + 1);
+ assert.ok(stopStart >= 0 && stopEnd > stopStart);
+ const stop = launcher.slice(stopStart, stopEnd);
+ assert.match(stop, /--terminate-workbuddy/);
+ assert.match(stop, /--profile[\s\S]*PROFILE\.id/);
+ assert.match(stop, /result\.status !== 0[\s\S]*throw new Error/);
+
+ const nativeMainStart = launcher.indexOf('async function nativeStartupMain()');
+ const nativeMainEnd = launcher.indexOf('\n// ---------- legacy script entry', nativeMainStart);
+ const nativeMain = launcher.slice(nativeMainStart, nativeMainEnd);
+ assert.match(nativeMain, /nativeWorkBuddyRunning\(\)[\s\S]*stopNativeWorkBuddy\(\)[\s\S]*waitForWorkBuddyCdpNative/);
+ assert.doesNotMatch(nativeMain, /return 10/);
+});
+
+test('native CDP startup detects failed child launches instead of waiting for the full timeout', () => {
+ assert.equal(nativeLaunchFailed(null), false);
+ assert.equal(nativeLaunchFailed({ errorCode: null, exitCode: null }), false);
+ assert.equal(nativeLaunchFailed({ errorCode: null, exitCode: 0 }), false);
+ assert.equal(nativeLaunchFailed({ errorCode: 'ENOENT', exitCode: null }), true);
+ assert.equal(nativeLaunchFailed({ errorCode: null, exitCode: 9 }), true);
+
+ const launcher = read('scripts/win-launcher.js');
+ const waitStart = launcher.indexOf('async function waitForWorkBuddyCdpNative(binary)');
+ const waitEnd = launcher.indexOf('\nasync function nativeStartupMain()', waitStart);
+ const wait = launcher.slice(waitStart, waitEnd);
+ assert.match(wait, /nativeLaunchFailed\(nativeLaunchState\)/);
+ assert.match(wait, /windows-native-launcher-workbuddy-exit/);
+ assert.match(wait, /stopNativeWorkBuddy\(\)[\s\S]*start\(\)/);
+});
diff --git a/test/windows-privilege-boundary.test.js b/test/windows-privilege-boundary.test.js
index 6ca0a7c..63972e3 100644
--- a/test/windows-privilege-boundary.test.js
+++ b/test/windows-privilege-boundary.test.js
@@ -69,6 +69,20 @@ test('profile process selection rejects multiple roots and ignores other CodeBud
);
});
+test('enterprise process aliases are accepted only in the selected install directory', () => {
+ const selected = 'C:\\Company\\WorkBuddy\\workbuddy-ent.exe';
+ const names = new Set(['workbuddy-ent.exe', 'workbuddyent.exe']);
+ const rows = [
+ { ProcessId: 111, Name: 'WorkBuddyEnt.exe', ExecutablePath: 'C:\\Company\\WorkBuddy\\WorkBuddyEnt.exe' },
+ { ProcessId: 112, Name: 'WorkBuddyEnt.exe', ExecutablePath: 'D:\\Other\\WorkBuddyEnt.exe' },
+ { ProcessId: 113, Name: 'Unrelated.exe', ExecutablePath: 'C:\\Company\\WorkBuddy\\Unrelated.exe' },
+ ];
+ assert.deepEqual(
+ boundary.filterVerifiedWindowsProcesses(selected, rows, resolveWindows, names).map((row) => row.ProcessId),
+ [111]
+ );
+});
+
test('node process identity requires exact executable, PID, and script argument', () => {
const expectedNode = 'C:\\Node\\node.exe';
const expectedScript = 'C:\\WorkDaddy\\scripts\\daemon.js';
@@ -235,6 +249,16 @@ test('native lifecycle stop validates the bundled node path before termination',
assert.match(nativeSource, /if elevated \{[\s\S]*return true, exitAccessDenied/);
});
+test('native termination maps TerminateProcess access denial to the permission exit code', () => {
+ const start = nativeSource.indexOf('result, _, callErr := procTerminateProcess.Call');
+ const end = nativeSource.indexOf('\n\twaitResult, _, callErr := procWaitForSingleObject.Call', start);
+ assert.ok(start >= 0 && end > start);
+ const branch = nativeSource.slice(start, end);
+ assert.match(branch, /if result == 0/);
+ assert.match(branch, /errors\.Is\(callErr, syscall\.ERROR_ACCESS_DENIED\)/);
+ assert.match(branch, /return false, exitAccessDenied/);
+});
+
test('packaged scripts contain no WorkBuddy image-name kill or stale elevation helper', () => {
const sources = [];
const visit = (dir) => {