Skip to content

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

feat: 合并 1.2.6 版本

[email protected]d3f2961667d3
diff --git a/README.md b/README.md
index 59e822b..50ce751 100644
--- a/README.md
+++ b/README.md
@@ -109,20 +109,20 @@ node scripts/workbuddy-target.js --configure --platform darwin \
### Linux
-Linux 发布包面向 Ubuntu / Debian `amd64`。安装前请先安装并登录对应的 WorkBuddy 客户端;WorkDaddy 通过 CDP 连接客户端,不会替换或修改 WorkBuddy 本体。
+Linux 发布包面向 Ubuntu / Debian `amd64` 和 `arm64`。安装前请先安装并登录同架构的 WorkBuddy 客户端;WorkDaddy 通过 CDP 连接客户端,不会替换或修改 WorkBuddy 本体。
-1. 在 [Releases](../../releases) 下载对应客户端的安装包:国内版是 `WorkDaddy_x.y.z_amd64.deb`,国际版是 `WorkDaddy-AI_x.y.z_amd64.deb`。
+1. 在 [Releases](../../releases) 下载对应客户端和机器架构的安装包:国内版是 `WorkDaddy_x.y.z_<arch>.deb`,国际版是 `WorkDaddy-AI_x.y.z_<arch>.deb`,其中 `<arch>` 为 `amd64` 或 `arm64`。
2. 在下载目录执行:
```bash
- sudo apt install ./WorkDaddy_x.y.z_amd64.deb
+ sudo apt install ./WorkDaddy_x.y.z_<arch>.deb
```
如果安装 WorkBuddy AI 国际版,请改用:
```bash
- sudo apt install ./WorkDaddy-AI_x.y.z_amd64.deb
+ sudo apt install ./WorkDaddy-AI_x.y.z_<arch>.deb
```
3. 从应用菜单启动 **WorkDaddy**(国内版)或 **WorkDaddy AI**(国际版)。首次启动会准备本地数据目录并启动后台服务;随后按提示重启 WorkBuddy 以开启 CDP 面板。
@@ -204,7 +204,7 @@ WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh
暂存提示词和主题功能在两个 WorkBuddy profile 开启。CodeBuddy profile 的适配暂缓,不进入当前发布包。
-当前发布脚本打包两个 WorkBuddy 客户端:Windows 每个客户端发布 Setup.exe 与便携版 ZIP 两个包:`WorkDaddy-Setup-<version>.exe` / `WorkDaddy-Portable-<version>.zip`、`WorkDaddy-AI-Setup-<version>.exe` / `WorkDaddy-AI-Portable-<version>.zip`;macOS 发布两个 DMG;Linux 发布 `WorkDaddy_<version>_amd64.deb` 和 `WorkDaddy-AI_<version>_amd64.deb`。macOS 构建时传 `WORKDADDY_BUILD_PROFILE=workbuddy-cn` 或 `workbuddy-ai` 可单独重打一个客户端。Windows 便携版 ZIP 与 Setup.exe 同源生成,顶层只有启动和停止入口。
+当前发布脚本打包两个 WorkBuddy 客户端:Windows 每个客户端发布 Setup.exe 与便携版 ZIP 两个包:`WorkDaddy-Setup-<version>.exe` / `WorkDaddy-Portable-<version>.zip`、`WorkDaddy-AI-Setup-<version>.exe` / `WorkDaddy-AI-Portable-<version>.zip`;macOS 发布两个 DMG;Linux 为 `amd64` 和 `arm64` 分别发布 `WorkDaddy_<version>_<arch>.deb` 和 `WorkDaddy-AI_<version>_<arch>.deb`。macOS 构建时传 `WORKDADDY_BUILD_PROFILE=workbuddy-cn` 或 `workbuddy-ai` 可单独重打一个客户端;Linux 构建时传 `WORKDADDY_BUILD_ARCH=amd64` 或 `arm64`。Windows 便携版 ZIP 与 Setup.exe 同源生成,顶层只有启动和停止入口。
`install.sh` 做了:
diff --git a/README_en.md b/README_en.md
index b4fe999..829a64d 100644
--- a/README_en.md
+++ b/README_en.md
@@ -108,7 +108,7 @@ WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh
Prompt stashing and themes are enabled for both WorkBuddy profiles. CodeBuddy profile support is on hold and is outside the current release scope.
-The release scripts produce packages for both WorkBuddy clients: `WorkDaddy-<version>.dmg` and `WorkDaddy-AI-<version>.dmg` on macOS; `WorkDaddy-Setup-<version>.exe` / `WorkDaddy-Portable-<version>.zip` and `WorkDaddy-AI-Setup-<version>.exe` / `WorkDaddy-AI-Portable-<version>.zip` on Windows; and `WorkDaddy_<version>_amd64.deb` / `WorkDaddy-AI_<version>_amd64.deb` on Linux. For macOS builds, set `WORKDADDY_BUILD_PROFILE=workbuddy-cn` or `workbuddy-ai` to build only one client. Windows ZIPs are temporary installer build inputs, not release downloads.
+The release scripts produce packages for both WorkBuddy clients: `WorkDaddy-<version>.dmg` and `WorkDaddy-AI-<version>.dmg` on macOS; `WorkDaddy-Setup-<version>.exe` / `WorkDaddy-Portable-<version>.zip` and `WorkDaddy-AI-Setup-<version>.exe` / `WorkDaddy-AI-Portable-<version>.zip` on Windows; and `WorkDaddy_<version>_<arch>.deb` / `WorkDaddy-AI_<version>_<arch>.deb` for Linux `amd64` and `arm64`. For macOS builds, set `WORKDADDY_BUILD_PROFILE=workbuddy-cn` or `workbuddy-ai` to build only one client. For Linux, set `WORKDADDY_BUILD_ARCH=amd64` or `arm64`. Windows ZIPs are temporary installer build inputs, not release downloads.
`install.sh`:
diff --git a/scripts/automation-runtime.js b/scripts/automation-runtime.js
index d490801..531b7a9 100644
--- a/scripts/automation-runtime.js
+++ b/scripts/automation-runtime.js
@@ -68,7 +68,7 @@ function createRendererGate() {
}
// Executed read-only inside the renderer. Never returns composer or message text.
-function probeSessionReceipt() {
+function probeSessionReceipt(expectedReceipt) {
const compat = window.__wbsWorkBuddyCompat;
if (!compat) return null;
const selected = compat.getSelectedConversationId(document);
@@ -79,8 +79,16 @@ function probeSessionReceipt() {
const session = controller.getSessionViewState();
const messages = Array.isArray(state.messages) ? state.messages : [];
const users = messages.filter(m => (m.messageType || m.role) === 'user');
- const user = users[users.length-1];
- const last = [...messages].reverse().find(m => (m.messageType || m.role) === 'assistant' && !/^timeline:/.test(String(m.id || '')));
+ const expectedUserMessageId = String(expectedReceipt && expectedReceipt.userMessageId || '');
+ const expectedRequestId = String(expectedReceipt && expectedReceipt.requestId || '');
+ const user = (expectedUserMessageId || expectedRequestId)
+ ? users.find(m => String(m.id || m.requestId || '') === expectedUserMessageId || String(m.requestId || '') === expectedRequestId) || users[users.length-1]
+ : users[users.length-1];
+ const userRequestId = String(user && user.requestId || expectedRequestId || '');
+ const assistants = messages.filter(m => (m.messageType || m.role) === 'assistant' && !/^timeline:/.test(String(m.id || '')));
+ const last = (expectedRequestId || userRequestId)
+ ? [...assistants].reverse().find(m => String(m.requestId || '') === (expectedRequestId || userRequestId)) || assistants[assistants.length-1]
+ : assistants[assistants.length-1];
const error = typeof controller.getErrorViewState === 'function' ? controller.getErrorViewState() : {};
const extra = last && last.extra || {};
return {
@@ -92,13 +100,14 @@ function probeSessionReceipt() {
complete:!!(last && (Object.prototype.hasOwnProperty.call(extra,'isRequestTerminal') ? extra.isRequestTerminal === true : last.complete === true)),
cancelled:extra.isCancelled === true,
error:!!(error && (error.error || error.hasError)),
- busy:!!(state.streamingRequestId || state.streamingMessageId || session && (session.isBusy || session.isRunActive || session.isTurnActive || session.isSending || session.isPending || session.isHydrating)),
+ busy:!!((state.streamingRequestId && (!userRequestId || String(state.streamingRequestId) === userRequestId)) || (state.streamingMessageId && (!userRequestId || String(state.streamingMessageId) === userRequestId)) || last && !((Object.prototype.hasOwnProperty.call(extra,'isRequestTerminal') ? extra.isRequestTerminal === true : last.complete === true)) || !user && session && (session.isBusy || session.isRunActive || session.isTurnActive || session.isSending || session.isPending || session.isHydrating)),
};
} catch (_) { return null; }
}
function receiptComplete(receipt, snapshot) {
if (!snapshot || snapshot.conversationId !== receipt.conversationId) throw new Error('目标会话不再可见,已停止等待');
- if (snapshot.userMessageId !== receipt.userMessageId) throw new Error('会话已有其他请求,已停止等待');
+ const snapshotRequestId = snapshot.requestId || snapshot.assistantRequestId || '';
+ if (snapshot.userMessageId !== receipt.userMessageId && snapshotRequestId !== receipt.requestId) throw new Error('会话已有其他请求,已停止等待');
if (snapshot.error || snapshot.cancelled) throw new Error('会话回复失败或已取消');
if (receipt.requestId && snapshot.assistantRequestId && snapshot.assistantRequestId !== receipt.requestId) return false;
return !!snapshot.assistantId && snapshot.assistantId !== receipt.baselineAssistantId && snapshot.complete && !snapshot.busy;
diff --git a/scripts/build-linux-deb.sh b/scripts/build-linux-deb.sh
index 3dba608..e468bc2 100644
--- a/scripts/build-linux-deb.sh
+++ b/scripts/build-linux-deb.sh
@@ -1,18 +1,45 @@
#!/usr/bin/env bash
-# Build a self-contained Ubuntu/Debian amd64 package. macOS can cross-package it,
-# but runtime verification still requires a Linux x86_64 host.
+# Build a self-contained Ubuntu/Debian amd64 or arm64 package. macOS and a
+# different-architecture Linux host can cross-package it; runtime verification
+# still requires a matching Linux host.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
-if [ "$(uname -s)" = Linux ] && [ "$(uname -m)" = x86_64 ]; then
+DEB_ARCH="${WORKDADDY_BUILD_ARCH:-amd64}"
+case "$DEB_ARCH" in
+ amd64)
+ NODE_ARCH=x64
+ NODE_SHA256=9749e988f437343b7fa832c69ded82a312e41a03116d766797ac14f6f9eee578
+ ELF_MACHINE_HEX=3e00
+ ;;
+ arm64)
+ NODE_ARCH=arm64
+ NODE_SHA256=0294e8b915ab75f92c7513d2fcb830ae06e10684e6c603e99a87dbf8835389c1
+ ELF_MACHINE_HEX=b700
+ ;;
+ *)
+ echo "不支持的 Linux 架构: $DEB_ARCH(仅支持 amd64/arm64)" >&2
+ exit 2
+ ;;
+esac
+
+HOST_ARCH="$(uname -m)"
+case "$HOST_ARCH" in
+ x86_64|amd64) HOST_DEB_ARCH=amd64 ;;
+ aarch64|arm64) HOST_DEB_ARCH=arm64 ;;
+ *) HOST_DEB_ARCH=unknown ;;
+esac
+if [ "$(uname -s)" = Linux ] && [ "$HOST_DEB_ARCH" != unknown ]; then
CROSS_PACKAGE=0
elif [ "$(uname -s)" = Darwin ]; then
CROSS_PACKAGE=1
else
- echo '构建需要 Linux x86_64 或 macOS;运行验收仍需 Linux x86_64' >&2
+ echo '构建需要 Linux x86_64/aarch64 或 macOS;运行验收仍需同架构 Linux' >&2
exit 2
fi
+CAN_RUN_BUNDLED=0
+if [ "$(uname -s)" = Linux ] && [ "$HOST_DEB_ARCH" = "$DEB_ARCH" ]; then CAN_RUN_BUNDLED=1; fi
for command in curl tar; do
command -v "$command" >/dev/null 2>&1 || { echo "缺少构建工具: $command" >&2; exit 2; }
done
@@ -26,6 +53,9 @@ if [ "$CROSS_PACKAGE" = 1 ]; then
done
else
command -v dpkg-deb >/dev/null 2>&1 || { echo '缺少构建工具: dpkg-deb' >&2; exit 2; }
+ if [ "$CAN_RUN_BUNDLED" = 0 ]; then
+ command -v node >/dev/null 2>&1 || { echo '交叉架构构建需要主机 Node.js' >&2; exit 2; }
+ fi
fi
SOURCE_VERSION="$(sed -n "s/^const DAEMON_VERSION = '\([^']*\)';/\1/p" scripts/daemon.js | head -1)"
@@ -35,8 +65,7 @@ if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
exit 2
fi
-NODE_ARCHIVE_NAME=node-v22.23.1-linux-x64.tar.xz
-NODE_SHA256=9749e988f437343b7fa832c69ded82a312e41a03116d766797ac14f6f9eee578
+NODE_ARCHIVE_NAME=node-v22.23.1-linux-$NODE_ARCH.tar.xz
WS_ARCHIVE_NAME=ws-8.18.3.tgz
WS_SHA256=424be604c8e7926fc29a1f067bf2dac256af3bcea62fe30395018bbaf8a9be2a
TEMP="$(mktemp -d)"
@@ -72,8 +101,8 @@ fetch_archive "${WORKDADDY_WS_ARCHIVE:-}" \
"https://registry.npmjs.org/ws/-/$WS_ARCHIVE_NAME" "$WS_SHA256" "$TEMP/$WS_ARCHIVE_NAME"
mkdir -p "$TEMP/node"
tar -xJf "$TEMP/$NODE_ARCHIVE_NAME" -C "$TEMP/node"
-cp "$TEMP/node/node-v22.23.1-linux-x64/bin/node" "$COMMON_SCRIPTS/runtime/node/node"
-cp "$TEMP/node/node-v22.23.1-linux-x64/LICENSE" "$COMMON_SCRIPTS/runtime/node/LICENSE"
+cp "$TEMP/node/node-v22.23.1-linux-$NODE_ARCH/bin/node" "$COMMON_SCRIPTS/runtime/node/node"
+cp "$TEMP/node/node-v22.23.1-linux-$NODE_ARCH/LICENSE" "$COMMON_SCRIPTS/runtime/node/LICENSE"
chmod 755 "$COMMON_SCRIPTS/runtime/node/node"
tar -xzf "$TEMP/$WS_ARCHIVE_NAME" -C "$COMMON_SCRIPTS/node_modules/ws" --strip-components=1
@@ -89,7 +118,7 @@ cp scripts/assets/workdaddy-icon-foreground.png \
chmod 755 "$COMMON_SCRIPTS/"*-linux.sh
BUILD_NODE="$COMMON_SCRIPTS/runtime/node/node"
-if [ "$CROSS_PACKAGE" = 1 ]; then BUILD_NODE="$(command -v node)"; fi
+if [ "$CAN_RUN_BUNDLED" = 0 ]; then BUILD_NODE="$(command -v node)"; fi
"$BUILD_NODE" - "$COMMON_SCRIPTS/daemon.js" "$VERSION" <<'NODE'
const fs = require('node:fs');
const file = process.argv[2];
@@ -124,7 +153,7 @@ Package: $package_name
Version: $VERSION
Section: utils
Priority: optional
-Architecture: amd64
+Architecture: $DEB_ARCH
Maintainer: WorkDaddy <[email protected]>
Depends: libc6 (>= 2.28), libstdc++6, bash, curl, ca-certificates, procps, util-linux, xdg-utils, zenity
Description: $display_name desktop enhancement for WorkBuddy
@@ -144,13 +173,13 @@ EOF
local out="$ROOT/release/linux/$output_name"
if [ "$CROSS_PACKAGE" = 1 ]; then
- python3 - "$stage" "$out" "$VERSION" "$install_root" "$package_name" <<'PY'
+ python3 - "$stage" "$out" "$VERSION" "$install_root" "$package_name" "$DEB_ARCH" <<'PY'
import pathlib
import sys
import tarfile
import tempfile
-stage, output, version, install_root, package_name = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5]
+stage, output, version, install_root, package_name, architecture = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6]
def add_entry(archive, path, name):
info = archive.gettarinfo(str(path), name)
@@ -213,9 +242,11 @@ with tempfile.TemporaryDirectory() as tmp:
if any('安装失败自主解决提示词' in name or name.endswith('.zip') for name in names):
raise SystemExit('Forbidden payload file')
daemon = archive.extractfile(prefix + 'daemon.js').read().decode()
- node = archive.extractfile(prefix + 'runtime/node/node').read(5)
- if f"const DAEMON_VERSION = '{version}';" not in daemon or node != b'\x7fELF\x02':
- raise SystemExit('Payload version or Linux x64 runtime mismatch')
+ node = archive.extractfile(prefix + 'runtime/node/node').read(20)
+ expected_machine = {'amd64': 62, 'arm64': 183}[architecture]
+ actual_machine = int.from_bytes(node[18:20], 'little') if node[:5] == b'\x7fELF\x02' else -1
+ if f"const DAEMON_VERSION = '{version}';" not in daemon or actual_machine != expected_machine:
+ raise SystemExit('Payload version or Linux runtime architecture mismatch')
PY
else
dpkg-deb --build --root-owner-group "$stage" "$out"
@@ -232,11 +263,17 @@ PY
mkdir -p "$verify"
dpkg-deb --extract "$out" "$verify"
grep -qx "const DAEMON_VERSION = '$VERSION';" "$verify$install_root/scripts/daemon.js"
- "$verify$install_root/scripts/runtime/node/node" --check \
- "$verify$install_root/scripts/daemon.js"
+ local machine_hex
+ machine_hex="$(od -An -tx1 -j18 -N2 "$verify$install_root/scripts/runtime/node/node" | tr -d ' \n')"
+ [ "$machine_hex" = "$ELF_MACHINE_HEX" ] || { echo "Node 运行时架构错误: $machine_hex" >&2; exit 2; }
+ if [ "$CAN_RUN_BUNDLED" = 1 ]; then
+ "$verify$install_root/scripts/runtime/node/node" --check "$verify$install_root/scripts/daemon.js"
+ else
+ node --check "$verify$install_root/scripts/daemon.js"
+ fi
fi
echo "Linux 安装包: $out"
}
-build_package cn workdaddy /opt/workdaddy 'WorkDaddy' "WorkDaddy_${VERSION}_amd64.deb"
-build_package ai workdaddy-ai /opt/workdaddy-ai 'WorkDaddy AI' "WorkDaddy-AI_${VERSION}_amd64.deb"
+build_package cn workdaddy /opt/workdaddy 'WorkDaddy' "WorkDaddy_${VERSION}_${DEB_ARCH}.deb"
+build_package ai workdaddy-ai /opt/workdaddy-ai 'WorkDaddy AI' "WorkDaddy-AI_${VERSION}_${DEB_ARCH}.deb"
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index 722f0e7..ffec6fa 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -56,7 +56,7 @@ chmod 644 "$APP/Contents/Resources/AppIcon.icns"
echo "==> 应用图标已同步(背景 #e1e1e1)"
# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)
-for f in daemon.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
+for f in daemon.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"
done
# Injection reads the wordmark at runtime; keep brand assets in both profiles.
@@ -90,6 +90,7 @@ chmod 755 "$APP/Contents/Resources/scripts/daemon.js" \
"$APP/Contents/Resources/scripts/uninstall.sh" \
"$APP/Contents/Resources/scripts/apply-update.sh"
chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \
+ "$APP/Contents/Resources/scripts/session-dirty.js" \
"$APP/Contents/Resources/scripts/account-credit-cache.js" \
"$APP/Contents/Resources/scripts/automation.js" \
"$APP/Contents/Resources/scripts/automation-picker.js" \
diff --git a/scripts/credit-history-sync.js b/scripts/credit-history-sync.js
index 3dd5ec1..ba4761c 100644
--- a/scripts/credit-history-sync.js
+++ b/scripts/credit-history-sync.js
@@ -33,7 +33,8 @@ function createCreditHistorySync(options) {
if (typeof row.uid !== 'string' || !/^\d{4}-\d\d-\d\d$/.test(row.date) ||
!Number.isFinite(row.used) || row.used < 0 || !Number.isSafeInteger(row.count) || row.count < 0 ||
!Number.isFinite(row.queriedAt) || typeof row.final !== 'boolean') continue;
- cache.set(key(row.uid, row.date), row);
+ const models = row.models && typeof row.models === 'object' && !Array.isArray(row.models) ? row.models : {};
+ cache.set(key(row.uid, row.date), { ...row, models });
}
} catch (_) { /* Absent or invalid cache: query the official API. */ }
function persist() {
@@ -78,7 +79,7 @@ function createCreditHistorySync(options) {
});
function readDaily() {
return selected.flatMap(a => dates.map(date => cache.get(key(a.uid, dateString(date)))).filter(Boolean)
- .map(row => ({ uid: row.uid, date: row.date, used: row.used, count: row.count, complete: true })));
+ .map(row => ({ uid: row.uid, date: row.date, used: row.used, count: row.count, models: row.models || {}, complete: true })));
}
const initial = readDaily();
const cacheHit = plans.every(plan => !plan.gaps.length);
@@ -111,7 +112,7 @@ function createCreditHistorySync(options) {
const daily = new Map();
for (const date = new Date(gap.startTime); date <= gap.endTime; date.setDate(date.getDate() + 1)) {
const day = dateString(date);
- daily.set(day, { uid: account.uid, date: day, used: 0, count: 0,
+ daily.set(day, { uid: account.uid, date: day, used: 0, count: 0, models: {},
queriedAt: range.endTime.getTime(), final: day < range.to });
}
const seen = new Set();
@@ -120,9 +121,18 @@ function createCreditHistorySync(options) {
if (!day || seen.has(record.requestId)) continue;
seen.add(record.requestId);
day.used += record.credit; day.count++;
+ const model = String(record.model || '').trim();
+ if (model) {
+ const modelUsage = day.models[model] || (day.models[model] = { used: 0, count: 0 });
+ modelUsage.used += record.credit;
+ modelUsage.count++;
+ }
}
for (const day of daily.values()) {
day.used = Math.round(day.used * 100) / 100;
+ Object.values(day.models).forEach(modelUsage => {
+ modelUsage.used = Math.round(modelUsage.used * 100) / 100;
+ });
cache.set(key(day.uid, day.date), day);
}
persist();
diff --git a/scripts/daemon.js b/scripts/daemon.js
index f77f3ef..6b6ccc7 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -82,6 +82,11 @@ const {
listAccounts,
switchTo,
deleteAccount,
+ wdCompatText, // [wd-compat]
+ wdCompatContainsEncryptedFields, // [wd-compat]
+ wdCompatDecryptAuthJson, // [wd-compat] WorkBuddy 5.6+ 字段信封解密
+ wdCompatAuthToken, // [wd-compat] 仅返回可直接发送的明文 token
+ normalizeAccountImportJson, // [wd-compat] 明文/信封账号导入归一化
backupPath,
updateMeta,
canonicalWorkspace,
@@ -103,6 +108,8 @@ const {
removeAutoCopyAccount,
collectLineageMembersForDelete,
getAutoCopyMapping,
+ getAutoCopyMappings,
+ migrateAutoCopyTargetRevisions: migrateAutoCopyTargetRevisionsFromMeta,
setAutoCopyMapping,
deleteAutoCopyMapping,
workbuddyModelsFile,
@@ -153,6 +160,7 @@ const plat = require('./platform.js');
const { readWorkBuddyTarget } = require('./workbuddy-target.js');
const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('./cdp-targets.js');
const { createSessionDb, normalizeSessionIdBatch, parameterCount } = require('./session-db.js');
+const { createDirtyIndex } = require('./session-dirty.js');
const {
createEncryptedExport,
openEncryptedExport,
@@ -326,8 +334,7 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 401 归类为「登录身份过期」并返回结构化 401;语言选择器移入「关于」页。
// 1.1.37:修复 legacy 账号切换失败——无文件记录的旧账号无条件写回官方固定登录文件,
// 固定文件名(workbuddy-desktop.info)跨认证通道可交替覆盖,个性化文件名保留通道校验。
-// 1.1.38:备份扫描禁止历史存档覆盖有效备份(s 身份过期事故根源);切换账号后自动打开
-// 目标账号中与当前会话同标题的复制会话(auto-focus)。
+// 1.1.38:备份扫描禁止历史存档覆盖有效备份(s 身份过期事故根源)。
// 1.1.39:账号脱敏状态按 profile 持久化;WorkDaddy 触发页面重载后在主执行上下文创建时提前注入。
// 1.1.40:跨账号重载跟随新主 frame,并在会话自动复制占用事件循环前等待组件实际挂载。
// 1.1.41:后台会话自动复制在文件边界让出 I/O;账号重载期间暂停复制,优先完成组件挂载。
@@ -381,8 +388,40 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 1.2.52:成长任务支持在悬浮层内直接接取,并在完成后同步最新任务状态。
// 1.2.55:成长弹窗支持开启盲盒与抽奖并提示奖励,收敛成长/用量统计 primary 色使用。
// 1.2.56:成长任务补齐说明与标签、已领取折叠、Buddy 派出,并把用量柱状图改为面积折线图。
-const DAEMON_VERSION = '1.2.95';
-const DAEMON_BUILD_ID = 'release-1.2.95-20260920-session-sync-skip-fastpath';
+// 1.2.102:新建任务挂载会话后按会话控制器确认模型,不再误用新建任务偏好校验。
+// 1.2.103:发送按钮点击后由回执阶段重试确认正式会话模型,避开新建任务挂载竞态。
+// 1.2.104:同步会话时跳过本机 modify_backup,避免无用途的回滚副本拖慢切号。
+// 1.2.105:自动同步移除重复大小预扫描,并区分已检查字节与实际写入字节。
+// 1.2.106:普通切号不再等待注入确认;自动同步使用有限并发并实时报告写入字节。
+// 1.2.107:自动同步对未变化会话使用持久化轻量指纹,跳过重复快照扫描。
+// 1.2.108:自动同步热路径改用固定路径标记与源/目标数据库版本,避免重复枚举项目目录。
+// 1.2.109:暂停持久化指纹快路径,恢复完整会话比较,避免旧映射误判。
+// 1.2.110:并发自动同步按会话独立汇总实际写入字节,避免统计竞态漏计。
+// 1.2.112:自动化发送支持新版 textarea 输入框,并只聚焦当前可见的输入区。
+// 1.2.114:自动同步命中稳定行版本与文件元数据指纹时直接跳过完整快照扫描。
+// 1.2.115:自动同步未变化快路径只比较源/目标会话行修订号,避免逐会话遍历全部项目目录。
+// 1.2.116:会话同步写入前只检查本次源/目标会话,避免无关忙会话拦截同步。
+// 1.2.117:新用户首次初始化默认使用浅色主题,已有主题设置保持不变。
+// 1.2.118:多账号自动同步避免重复写入元数据,并兼容跨账号 lineage 的稳定 revision。
+// 1.2.119:无变化同步规划不再等待 renderer 注入,只有实际复制时才等待就绪。
+// 1.2.122:首次复制到没有物理副本的账号使用同步快照路径,避免异步文件校验链路拖慢全量初始化。
+// 1.2.123:自动复制映射保存目标数据库实际 revision,避免未变化会话反复进入完整快照校验。
+// 1.2.124:启动时批量校准旧目标 revision,避免历史映射让未变化会话重复进入规划。
+// 1.2.128:5.6 会话同步对瞬态冲突进行延迟重读,避免一次投影抖动生成 branchCopy 重复会话。
+// 1.2.129:自动同步跳过会话内符号链接;归档导入允许配置的数据根是目录链接。
+// 1.2.130:自动化等待按本轮会话回执绑定消息;空消息会话复制失败不阻断自动化切号。
+// 1.2.131:WorkBuddy 5.6 乐观 user 消息换正式 ID 时按稳定 requestId 继续等待。
+// 1.2.140:稳定映射自动清理历史生命周期脏标记,避免无变化切换进入同步 worker。
+// 1.2.141:已建立 dirty baseline 后忽略历史 lineage revision 漂移,并确认官方会话导航结果。
+// 1.2.142:忽略激活引起的会话生命周期漂移,拒绝切号后的旧脏通知,并按目标账号恢复同步状态。
+// 1.2.143:内容相同的激活会话刷新映射并清除旧脏标记;缺失映射时复用已有目标会话,避免重复创建。
+// 1.2.144:删除会话允许一次处理超过 100 个 ID;其他批量接口仍保留原有上限。
+// 1.2.147:忽略会话激活日志的 session-meta 记录,避免反向切换误报导入;刷新指纹缓存版本。
+// 1.2.145:识别仅 updated_at 的激活漂移,清除无变更脏标记;无结果任务不再弹同步进度窗口。
+// 1.2.126:5.6 加密账号改为密文原样备份、内存解密;导入兼容明文 token,
+// 刷新结果不把解密后的 token 写回加密备份。
+const DAEMON_VERSION = '1.2.148';
+const DAEMON_BUILD_ID = 'release-1.2.148-20260923-windows-compat-target';
const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });
configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const automationDiscovery = createAutomationDiscovery({
@@ -425,7 +464,7 @@ const creditHistorySync = createCreditHistorySync({
const refreshed = await refreshAccountBackupToken(uid);
if (refreshed.error || !refreshed.root) throw new Error('账号凭据不可用');
const auth = refreshed.root.auth || {};
- return auth.accessToken || auth.access_token || auth.token;
+ return wdCompatAuthToken(auth);
},
});
const CREDIT_USAGE_REFRESH_MS = 15000;
@@ -770,7 +809,52 @@ function expectedUpdateSha256() {
return updateState.dmgSha256 || parseSha256(updateState.notes);
}
-// 检查更新:按源降级链请求 Releases API(GitHub 失败自动降级 Gitee),比对版本,结果写缓存(内存 + 文件)
+// 多源同时可用时取最高版本;同版本优先使用带安装包的候选。
+function selectBestUpdateCandidate(candidates) {
+ return (candidates || []).filter((candidate) => candidate && candidate.latest).sort((a, b) => {
+ const version = semverCompare(b.latest, a.latest);
+ if (version) return version;
+ return (Number(!!b.asset) - Number(!!a.asset)) || (Number(a.order) || 0) - (Number(b.order) || 0);
+ })[0] || null;
+}
+
+function selectUpdateAsset(source, rel) {
+ const assets = (rel.assets || []).filter((a) =>
+ a && typeof a.name === 'string' &&
+ typeof a.browser_download_url === 'string' &&
+ a.browser_download_url.startsWith(source.downloadRoot + '/')
+ );
+ const profileAsset = PROFILE.id === 'workbuddy-ai'
+ ? /^(?:WorkDaddy-AI-Setup-|WorkDaddy-AI-).*\.(?:exe|zip|dmg)$/i
+ : /^WorkDaddy-(?!AI-)(?:Setup-|).*\.(?:exe|zip|dmg)$/i;
+ const profileSetup = PROFILE.id === 'workbuddy-ai'
+ ? /^WorkDaddy-AI-Setup-\d+\.\d+\.\d+\.exe$/i
+ : /^WorkDaddy-Setup-\d+\.\d+\.\d+\.exe$/i;
+ const profileZip = PROFILE.id === 'workbuddy-ai'
+ ? /^WorkDaddy-AI-\d+\.\d+\.\d+-win64\.zip$/i
+ : /^WorkDaddy-\d+\.\d+\.\d+-win64\.zip$/i;
+ return IS_WIN
+ ? (assets.find((a) => profileSetup.test(a.name || '')) ||
+ assets.find((a) => profileZip.test(a.name || '')) ||
+ assets.find((a) => profileAsset.test(a.name || '') && /\.(?:exe|zip)$/i.test(a.name || '')) || null)
+ : (assets.find((a) => profileAsset.test(a.name || '') && /\.dmg$/i.test(a.name || '')) ||
+ assets.find((a) => /\.dmg$/i.test(a.name || '') && (PROFILE.id !== 'workbuddy-ai' || !/WorkDaddy-AI-/i.test(a.name || ''))) || null);
+}
+
+function makeUpdateCandidate(source, rel, order) {
+ const latest = String(rel.tag_name || '').replace(/^v/, '');
+ if (!latest) return null;
+ const notes = (rel.body || '').slice(0, 2000);
+ const asset = selectUpdateAsset(source, rel);
+ return {
+ source, order, rel, latest, notes, asset,
+ dmgUrl: asset ? `${source.downloadRoot}/${rel.tag_name}/${asset.name}` : null,
+ dmgSize: asset ? (Number(asset.size) || 0) : 0,
+ dmgSha256: asset ? (normalizeAssetSha256(asset.digest) || parseSha256Map(notes)[asset.name] || parseSha256(notes)) : null,
+ };
+}
+
+// 检查更新:同时请求所有更新源,选择最高版本(同版本优先有包),结果写缓存。
function checkUpdate(force) {
// Linux 暂不提供自动更新。直接返回「无更新」,避免误下载 macOS 的 dmg。
if (IS_LINUX) {
@@ -792,70 +876,40 @@ function checkUpdate(force) {
updateState.message = '正在检查更新…';
const order = updateSourceOrder();
updateDebug('check-start', { force: !!force, current: DAEMON_VERSION, sources: order.map((s) => s.id) });
- // 依次尝试各更新源,第一个可用的源即采用(检测与下载同源)
- let attempt = Promise.reject(new Error('尚未尝试任何更新源'));
- for (const source of order) {
- attempt = attempt.catch(() =>
- httpsGet(source.api).then(({ status, body }) => {
- if (status !== 200) {
- throw new Error('Releases API ' + status + (status === 404 ? '(仓库暂无 Release)' : ''));
- }
- return { source, rel: JSON.parse(body) };
- }).catch((err) => {
- log(`[update] ${source.id} 源检查失败: ${err.message}`);
- updateDebug('check-source-failed', { source: source.id, api: source.api, error: err.message });
- throw err;
- })
- );
- }
- return attempt
- .then(({ source, rel }) => {
- const latest = String(rel.tag_name || '').replace(/^v/, '');
- updateState.latest = latest;
- updateState.hasUpdate = semverCompare(latest, DAEMON_VERSION) > 0;
- updateState.source = source.id;
- updateState.releaseUrl = rel.html_url || (source.id === 'gitee' ? `https://gitee.com/${UPDATE_REPO}/releases` : null);
- updateState.notes = (rel.body || '').slice(0, 2000);
- // 资产按平台选取:macOS 找 .dmg;Windows 新版本优先同 profile 的 Setup.exe,
- // 旧版本仍只识别 ZIP,因此没有 EXE 时回退到对应的 -win64.zip。
- // Gitee 会把源码包(/archive/ 路径)混进 assets,且下载 URL 只信白名单 origin
- // 的 /releases/download/ 路径,防止响应里的任意地址被当作安装包来源。
- const assets = (rel.assets || []).filter((a) =>
- a && typeof a.name === 'string' &&
- typeof a.browser_download_url === 'string' &&
- a.browser_download_url.startsWith(source.downloadRoot + '/'));
- const profileAsset = PROFILE.id === 'workbuddy-ai'
- ? /^(?:WorkDaddy-AI-Setup-|WorkDaddy-AI-).*\.(?:exe|zip|dmg)$/i
- : /^WorkDaddy-(?!AI-)(?:Setup-|).*\.(?:exe|zip|dmg)$/i;
- const profileSetup = PROFILE.id === 'workbuddy-ai'
- ? /^WorkDaddy-AI-Setup-\d+\.\d+\.\d+\.exe$/i
- : /^WorkDaddy-Setup-\d+\.\d+\.\d+\.exe$/i;
- const profileZip = PROFILE.id === 'workbuddy-ai'
- ? /^WorkDaddy-AI-\d+\.\d+\.\d+-win64\.zip$/i
- : /^WorkDaddy-\d+\.\d+\.\d+-win64\.zip$/i;
- const asset = IS_WIN
- ? (assets.find((a) => profileSetup.test(a.name || '')) ||
- assets.find((a) => profileZip.test(a.name || '')) ||
- // tolerate older release naming while keeping profile isolation
- assets.find((a) => profileAsset.test(a.name || '') && /\.(?:exe|zip)$/i.test(a.name || '')) || null)
- : (assets.find((a) => profileAsset.test(a.name || '') && /\.dmg$/i.test(a.name || '')) ||
- assets.find((a) => /\.dmg$/i.test(a.name || '') && (PROFILE.id !== 'workbuddy-ai' || !/WorkDaddy-AI-/i.test(a.name || ''))) || null);
- // 下载 URL 从白名单 origin 派生(tag + 文件名),不直接采用响应里的 browser_download_url
- updateState.dmgUrl = asset ? `${source.downloadRoot}/${rel.tag_name}/${asset.name}` : null;
- // Gitee 不返回资产大小(null)→ 0,下载进度以响应 content-length 为准
- updateState.dmgSize = asset ? (Number(asset.size) || 0) : 0;
- // 完整性校验优先级:asset.digest(GitHub)→ notes 逐文件哈希(sha256sum 格式行)→ notes 单一哈希
- updateState.dmgSha256 = asset
- ? (normalizeAssetSha256(asset.digest) || parseSha256Map(updateState.notes)[asset.name] || parseSha256(updateState.notes))
- : null;
- updateState.assetName = asset ? asset.name : null;
+ const attempts = order.map((source, orderIndex) => httpsGet(source.api).then(({ status, body }) => {
+ if (status !== 200) {
+ throw new Error('Releases API ' + status + (status === 404 ? '(仓库暂无 Release)' : ''));
+ }
+ return makeUpdateCandidate(source, JSON.parse(body), orderIndex);
+ }).catch((err) => {
+ log(`[update] ${source.id} 源检查失败: ${err.message}`);
+ updateDebug('check-source-failed', { source: source.id, api: source.api, error: err.message });
+ return null;
+ }));
+ return Promise.all(attempts)
+ .then((candidates) => {
+ const latestCandidate = selectBestUpdateCandidate(candidates);
+ if (!latestCandidate) throw new Error('所有更新源均不可用');
+ const packageCandidate = selectBestUpdateCandidate(candidates.filter((candidate) =>
+ candidate && candidate.asset && semverCompare(candidate.latest, latestCandidate.latest) === 0
+ ));
+ const selectedCandidate = packageCandidate || latestCandidate;
+ updateState.latest = latestCandidate.latest;
+ updateState.hasUpdate = semverCompare(latestCandidate.latest, DAEMON_VERSION) > 0;
+ updateState.source = selectedCandidate.source.id;
+ updateState.releaseUrl = selectedCandidate.rel.html_url || (selectedCandidate.source.id === 'gitee' ? `https://gitee.com/${UPDATE_REPO}/releases` : null);
+ updateState.notes = latestCandidate.notes;
+ updateState.dmgUrl = packageCandidate ? packageCandidate.dmgUrl : null;
+ updateState.dmgSize = packageCandidate ? packageCandidate.dmgSize : 0;
+ updateState.dmgSha256 = packageCandidate ? packageCandidate.dmgSha256 : null;
+ updateState.assetName = packageCandidate && packageCandidate.asset ? packageCandidate.asset.name : null;
updateState.checkedAt = Date.now();
updateState.status = 'idle';
- updateState.message = updateState.hasUpdate ? '发现新版本 v' + latest : '已是最新版本';
+ updateState.message = updateState.hasUpdate ? '发现新版本 v' + latestCandidate.latest : '已是最新版本';
// 缓存发布信息(含成功的更新源),不缓存依赖当前运行版本的判断结果。
- try { fs.writeFileSync(UPDATE_CHECK_CACHE, JSON.stringify({ latest, source: source.id, dmgUrl: updateState.dmgUrl, dmgSize: updateState.dmgSize, dmgSha256: updateState.dmgSha256, assetName: updateState.assetName, notes: updateState.notes, checkedAt: updateState.checkedAt })); } catch (_) {}
- log(`[update] 检查完成: source=${source.id} latest=${latest} hasUpdate=${updateState.hasUpdate} (current=${DAEMON_VERSION})`);
- updateDebug('check-result', { source: source.id, current: DAEMON_VERSION, latest, hasUpdate: updateState.hasUpdate, assetName: updateState.assetName, assetSize: updateState.dmgSize, assetSha256: updateState.dmgSha256 });
+ try { fs.writeFileSync(UPDATE_CHECK_CACHE, JSON.stringify({ latest: latestCandidate.latest, source: updateState.source, dmgUrl: updateState.dmgUrl, dmgSize: updateState.dmgSize, dmgSha256: updateState.dmgSha256, assetName: updateState.assetName, notes: updateState.notes, checkedAt: updateState.checkedAt })); } catch (_) {}
+ log(`[update] 检查完成: source=${updateState.source} latest=${latestCandidate.latest} hasUpdate=${updateState.hasUpdate} (current=${DAEMON_VERSION})`);
+ updateDebug('check-result', { source: updateState.source, current: DAEMON_VERSION, latest: latestCandidate.latest, hasUpdate: updateState.hasUpdate, assetName: updateState.assetName, assetSize: updateState.dmgSize, assetSha256: updateState.dmgSha256 });
return updateState;
})
.catch((e) => {
@@ -1237,7 +1291,7 @@ function buildSeamlessAuthFile(tokenData, accData) {
let all = [];
try {
const activeAuthFile = currentAuthFile();
- const cur = activeAuthFile ? JSON.parse(fs.readFileSync(activeAuthFile, 'utf8')) : null;
+ const cur = activeAuthFile ? wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(activeAuthFile, 'utf8'))) : null; // [wd-compat]
const arr = cur.allAccounts || cur.accounts;
if (Array.isArray(arr)) all = arr;
} catch (_) {}
@@ -2206,7 +2260,7 @@ async function cdpLoop() {
}
}
-async function reloadWorkBuddyPage() {
+async function reloadWorkBuddyPage(options = {}) {
if (!cdp.connected) throw new Error('CDP 未连接,无法自动刷新窗口');
const withTimeout = (promise, ms, label) => new Promise((resolve, reject) => {
let settled = false;
@@ -2237,113 +2291,16 @@ async function reloadWorkBuddyPage() {
const pending = armPendingReloadInjection(frameId);
try {
await withTimeout(cdpSend('Page.reload', { ignoreCache: false }), 10000, '刷新 WorkBuddy 页面');
+ if (options.waitForInjection === false) return true;
const mounted = await pending.ready;
if (!mounted) log('[cdp] 页面重载后组件未在 5 秒内确认挂载,继续后台流程');
+ return mounted;
} catch (error) {
settlePendingReloadInjection(pending, false);
throw error;
}
}
-// 切换账号后自动打开目标账号中「与切换前当前会话同标题」的会话:
-// 自动复制会话会为目标账号创建同标题会话,刷新后轮询官方会话列表:
-// 标题精确匹配叶子 -> 定位 .conversation-item 行 -> 若已选中(_selected_)则完成,
-// 否则点击该行等待下轮确认。列表是虚拟滚动(只渲染可视行),按步进滚动扫描,
-// 并自动展开折叠的分组;最长约 26s,找不到则静默放弃。
-function autoFocusSessionByTitle(sourceTitle, logFn) {
- const target = String(sourceTitle || '').trim();
- if (!target) return;
- const logger = typeof logFn === 'function' ? logFn : () => {};
- let attempts = 0;
- let scrollPhase = 0; // 0=顶部初始, 1=向下扫描, 2=向上回扫
- let scrollTop = 0;
- const SCROLL_STEP = 480;
- const timer = setInterval(async () => {
- attempts++;
- try {
- if (!cdp.connected) throw new Error('CDP 未连接');
- // 1) 设置滚动位置(虚拟列表只渲染可视行)
- const scrollExpr =
- '(function(){var c=document.querySelector(".conversation-list-content");' +
- 'if(!c) return {ok:false, max:0};' +
- 'c.scrollTop=' + String(scrollTop) + ';' +
- 'return {ok:true, max:Math.max(0,c.scrollHeight-c.clientHeight)};})()';
- const sr = await cdpSend('Runtime.evaluate', { expression: scrollExpr, returnByValue: true });
- const scrollInfo = sr && sr.result && sr.result.value;
- // 2) 扫描匹配行:找到即返回 hit=已选中,pending=已点击待确认,miss=未渲染
- const findExpr =
- '(function(){' +
- 'var wanted = ' + JSON.stringify(target) + ';' +
- 'var list = document.querySelector(".conversation-list");' +
- 'if (!list) return { miss: true };' +
- 'var leaves = [];' +
- 'var all = list.querySelectorAll("*");' +
- 'for (var i = 0; i < all.length; i++) {' +
- ' var el = all[i];' +
- ' if (el.children.length === 0 && (el.textContent || "").trim() === wanted) leaves.push(el);' +
- '}' +
- 'if (!leaves.length) {' +
- ' var headers = list.querySelectorAll(".collapsible-section-header");' +
- ' for (var k = 0; k < headers.length; k++) {' +
- ' var hdr = headers[k];' +
- ' if (hdr.className.indexOf("expanded") === -1) hdr.click();' +
- ' }' +
- ' return { miss: true };' +
- '}' +
- 'for (var j = 0; j < leaves.length; j++) {' +
- ' var row = leaves[j];' +
- ' for (var d = 0; d < 8 && row && row.parentElement; d++) {' +
- ' var rc = row.classList ? row.className : "";' +
- ' if (rc.indexOf("conversation-item") !== -1 || rc.indexOf("_card_") !== -1) break;' +
- ' row = row.parentElement;' +
- ' }' +
- ' var rcls = row && row.classList ? row.className : "";' +
- ' if (!row || row === list || (rcls.indexOf("conversation-item") === -1 && rcls.indexOf("_card_") === -1)) continue;' +
- ' var rect = row.getBoundingClientRect ? row.getBoundingClientRect() : null;' +
- ' if (!rect || rect.width === 0 || rect.height === 0) continue;' +
- ' if (rcls.indexOf("_selected_") !== -1 || rcls.indexOf("selected") !== -1) {' +
- ' return { hit: true };' +
- ' }' +
- ' row.click();' +
- ' return { pending: true };' +
- '}' +
- 'return { miss: true };' +
- '})()';
- const fr = await cdpSend('Runtime.evaluate', { expression: findExpr, returnByValue: true });
- const out = fr && fr.result && fr.result.value;
- if (out && out.hit) {
- clearInterval(timer);
- logger('[auto-focus] 已自动打开目标账号会话「' + target + '」');
- return;
- }
- if (out && out.pending) {
- // 已点击,下轮确认选中态;本轮不推进滚动
- if (attempts >= 30) {
- clearInterval(timer);
- logger('[auto-focus] 已点击目标会话「' + target + '」,未确认选中(放弃继续等待)');
- }
- return;
- }
- // 3) 未渲染:推进滚动扫描
- const max = scrollInfo && scrollInfo.max ? scrollInfo.max : 0;
- if (scrollPhase === 0) { scrollPhase = 1; scrollTop = 0; }
- else if (scrollPhase === 1) {
- scrollTop += SCROLL_STEP;
- if (scrollTop > max + SCROLL_STEP) { scrollPhase = 2; scrollTop = max; }
- } else {
- scrollTop -= SCROLL_STEP;
- if (scrollTop <= -SCROLL_STEP) { scrollPhase = 1; scrollTop = 0; }
- }
- } catch (_) {
- /* 页面加载中或 CDP 抖动,下一轮再试 */
- }
- if (attempts >= 30) {
- clearInterval(timer);
- logger('[auto-focus] 未找到目标会话「' + target + '」(复制未完成或标题不一致)');
- }
- }, 800);
-}
-
const WORKBUDDY_TARGET = IS_WIN ? null : readWorkBuddyTarget({ dataDir: DATA_DIR, profileId: PROFILE.id });
// 三平台的应用标识(WORKBUDDY_BINARY 用于 pgrep/pkill 精确匹配与直接启动):
// macOS : 二进制在 <X.app>/Contents/MacOS/Electron,WORKBUDDY_APP 是 .app 包路径
@@ -2564,10 +2521,11 @@ function verifiedWindowsWorkBuddyProcesses(binary) {
return verified;
}
-function revalidateWindowsWorkBuddyProcess(original, binary) {
+function revalidateWindowsWorkBuddyProcess(original, binary, options = {}) {
const current = verifiedWindowsWorkBuddyProcesses(binary)
.find((process) => process.ProcessId === original.ProcessId);
if (!current) {
+ if (options.tolerateMissing) return null;
throw new Error(`结束前无法再次验证 WorkBuddy PID=${original.ProcessId}`);
}
return assertSameProcessIdentity(original, current);
@@ -2638,19 +2596,24 @@ async function quitWorkBuddy() {
if (!processes.length) return true;
for (const process of processes) {
- const current = revalidateWindowsWorkBuddyProcess(process, binary);
+ const current = revalidateWindowsWorkBuddyProcess(process, binary, { tolerateMissing: true });
+ if (!current) continue;
const result = await runCommand('taskkill', ['/PID', String(current.ProcessId)]);
if (result.error || result.code !== 0) {
- throw result.error || new Error(`taskkill 无法结束已验证进程 PID=${process.ProcessId}`);
+ // Console-less Electron children commonly reject the graceful pass.
+ // Continue so the verified survivor set can enter the force pass.
+ log(`[relaunch] taskkill 普通退出未结束 PID=${process.ProcessId},将复验后强制退出`);
}
}
if (await waitForWorkBuddyExit(1800, binary)) return true;
processes = verifiedWindowsWorkBuddyProcesses(binary);
for (const process of processes) {
- const current = revalidateWindowsWorkBuddyProcess(process, binary);
+ const current = revalidateWindowsWorkBuddyProcess(process, binary, { tolerateMissing: true });
+ if (!current) continue;
const result = await runCommand('taskkill', ['/F', '/PID', String(current.ProcessId)]);
if (result.error || result.code !== 0) {
+ if (!revalidateWindowsWorkBuddyProcess(process, binary, { tolerateMissing: true })) continue;
throw result.error || new Error(`taskkill 无法强制结束已验证进程 PID=${process.ProcessId}`);
}
}
@@ -2940,14 +2903,14 @@ const CHECKIN_REQUEST_TIMEOUT_MS = 12000;
// 声明式自动化任务:任务 JSON 只保存步骤,不保存账号 Token;运行时按账号上下文
// 读取受管备份并把凭据限制在一次 HTTP 请求内。第三方代码执行不在此模块范围内。
const growthStreakCache = createGrowthStreakCache(async (uid) => {
- const raw = JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'));
+ const raw = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'))); // [wd-compat]
const auth = raw && raw.auth || {};
- return fetchGrowthStreak(auth.accessToken || auth.access_token || auth.token, { apiHost: PROFILE.apiHost });
+ return fetchGrowthStreak(wdCompatAuthToken(auth), { apiHost: PROFILE.apiHost });
});
const dailyProgressCache = createDailyProgressCache(async (uid) => {
- const raw = JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'));
+ const raw = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'))); // [wd-compat]
const auth = raw && raw.auth || {};
- const token = auth.accessToken || auth.access_token || auth.token;
+ const token = wdCompatAuthToken(auth);
if (!token) throw new Error('备份中无 accessToken');
return fetchDailyProgress(token, { apiHost: PROFILE.apiHost });
});
@@ -2968,7 +2931,7 @@ async function automationAccountStatus(account, fields) {
if (!target || !target.uid) throw new Error('没有可用账号');
const file = accountBackupFile(target.uid);
if (!fs.existsSync(file)) throw new Error('账号备份不存在');
- const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
+ const raw = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(file, 'utf8'))); // [wd-compat]
const auth = raw && raw.auth && typeof raw.auth === 'object' ? raw.auth : {};
const result = { uid: target.uid, isPrimary: primaryAccountStore.get() === target.uid, checkin: {}, activity: {}, credits: {} };
const wanted = Array.isArray(fields) && fields.length ? fields : ['checkin.today', 'activity.today'];
@@ -2981,7 +2944,7 @@ async function automationAccountStatus(account, fields) {
result.checkin = { today: !!(hit && hit.date === today && hit.ok && (hit.verified === true || classifyCheckinResult({ httpOk: true, code: hit.code, message: hit.message }).ok)), verified: !!(hit && hit.date === today && hit.verified === true), source: mark ? 'sqlite' : 'cache' };
}
if (wanted.includes('activity.today')) {
- const token = auth.accessToken || auth.access_token || auth.token;
+ const token = wdCompatAuthToken(auth);
if (!token) throw new Error('备份中无 accessToken');
result.activity = Object.assign({ source: 'server' }, await fetchGrowthTodayActive(token, { apiHost: PROFILE.apiHost }));
}
@@ -2990,7 +2953,7 @@ async function automationAccountStatus(account, fields) {
result.activity.streak = { days: Number.isFinite(streak && streak.days) ? streak.days : null, status: streak && streak.status || 'unavailable' };
}
if (wanted.includes('credits')) {
- const token = auth.accessToken || auth.access_token || auth.token;
+ const token = wdCompatAuthToken(auth);
if (!token) throw new Error('备份中无 accessToken');
const credits = await fetchCredits(token, raw.account || {});
result.credits = { total: credits.credits, unlimited: !!credits.unlimited, cycleResetTime: credits.cycleResetTime || null };
@@ -3101,8 +3064,8 @@ async function automationHttpRequest(request, account) {
if (request.headers && typeof request.headers === 'object') Object.keys(request.headers).slice(0, 40).forEach((key) => { if (!/^(authorization|cookie|proxy-authorization)$/i.test(key)) headers[key] = String(request.headers[key]).slice(0, 2000); });
if (account && account.uid) {
assertAccountRequestUrl(url, PROFILE.apiHost);
- const raw = JSON.parse(fs.readFileSync(accountBackupFile(account.uid), 'utf8')); const auth = raw && raw.auth && typeof raw.auth === 'object' ? raw.auth : {};
- const token = auth.accessToken || auth.access_token || auth.token; if (!token) throw new Error('账号没有 accessToken'); headers.authorization = 'Bearer ' + token;
+ const raw = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(accountBackupFile(account.uid), 'utf8'))); const auth = raw && raw.auth && typeof raw.auth === 'object' ? raw.auth : {}; // [wd-compat]
+ const token = wdCompatAuthToken(auth); if (!token) throw new Error('账号凭据暂不可用'); headers.authorization = 'Bearer ' + token;
}
if (request.isCancelled && request.isCancelled()) throw new Error('任务已停止');
if (request.body && typeof request.body === 'object' && !Object.keys(headers).some(k => k.toLowerCase() === 'content-type')) headers['content-type'] = 'application/json';
@@ -3191,11 +3154,20 @@ async function automationNotifyToast(detail) {
}
let accountSwitchInProgress = false;
const accountSyncFailures = new Map();
-async function assertSessionSyncIdle() {
+function isIgnorableAutomationSyncFailure(job) {
+ if (!job || job.status === 'done' || !Array.isArray(job.details) || !job.details.length) return false;
+ const failed = job.details.filter(item => item && item.status === 'failed');
+ return failed.length > 0 && failed.every(item => item.error === '会话消息文件没有消息,未同步');
+}
+async function assertSessionSyncIdle(sessionIds = []) {
if (PROFILE.kind !== 'workbuddy') return;
if (!cdp.connected) throw new Error('无法确认会话状态,请连接 WorkBuddy 后重试');
+ const ids = Array.isArray(sessionIds) ? sessionIds.map((id) => String(id || '').trim()).filter(Boolean) : [];
+ const expression = ids.length
+ ? "typeof window.__wbsSessionsBusy === 'function' ? window.__wbsSessionsBusy(" + JSON.stringify(ids) + ") : (typeof window.__wbsAnySessionBusy === 'function' ? window.__wbsAnySessionBusy() : null)"
+ : "typeof window.__wbsAnySessionBusy === 'function' ? window.__wbsAnySessionBusy() : null";
const result = await cdpSend('Runtime.evaluate', {
- expression: "typeof window.__wbsAnySessionBusy === 'function' ? window.__wbsAnySessionBusy() : null",
+ expression,
returnByValue: true,
});
const busy = result && result.result && result.result.value;
@@ -3212,7 +3184,7 @@ async function assertAccountSwitchIdle() {
let automationAccountSwitchTail = Promise.resolve();
function assertAutoCopySucceeded(job) {
- if (job && (job.status !== 'done' || job.processed !== job.total || job.failed || job.failedItems || job.partial || job.conflicts)) {
+ if (job && !isIgnorableAutomationSyncFailure(job) && (job.status !== 'done' || job.processed !== job.total || job.failed || job.failedItems || job.partial || job.conflicts)) {
throw new Error('会话同步未成功完成,已停止自动切换(同步任务 ' + job.id + ',状态 ' + job.status + ')');
}
}
@@ -3369,9 +3341,12 @@ function startAutomationRun(task, event = null) {
}
};
let lastReceipt = null;
- const readSession = async () => {
+ const readSession = async (expectedReceipt = null) => {
if (isCancelled()) throw new Error('任务已停止');
- const response = await cdpSend('Runtime.evaluate', { expression: '(' + probeSessionReceipt.toString() + ')()', returnByValue: true });
+ const expected = expectedReceipt && typeof expectedReceipt === 'object'
+ ? { userMessageId: String(expectedReceipt.userMessageId || ''), requestId: String(expectedReceipt.requestId || '') }
+ : null;
+ const response = await cdpSend('Runtime.evaluate', { expression: '(' + probeSessionReceipt.toString() + ')(' + JSON.stringify(expected) + ')', returnByValue: true });
return response && response.result && response.result.value || null;
};
const sessionAction = async (op, detail) => {
@@ -3382,7 +3357,7 @@ function startAutomationRun(task, event = null) {
const end = Date.now() + Math.min(300000,Math.max(1000,Number(detail.timeoutMs)||120000));
while (Date.now() < end) {
if ((currentAccount() || {}).uid !== receipt.accountUid) throw new Error('账号已变化,已停止等待');
- const snapshot = await readSession();
+ const snapshot = await readSession(receipt);
if (receiptComplete(receipt,snapshot)) {
if (detail.contains) {
const response = await cdpSend('Runtime.evaluate', {expression: `(function(){var c=window.__wbsWorkBuddyCompat.findConversationControllers(document).find(c=>String(c.conversationId)===${JSON.stringify(receipt.conversationId)});if(!c)return false;var m=c.messageStore.getState().messages.find(m=>String(m.id||m.requestId||'')===${JSON.stringify(snapshot.assistantId)});return !!m&&JSON.stringify(m.content||[]).includes(${JSON.stringify(String(detail.contains))});})()`,returnByValue:true});
@@ -3400,7 +3375,12 @@ function startAutomationRun(task, event = null) {
if (op === 'session.create') await withInput(() => ensureAutomationNewTask({ guard: () => {
if (isCancelled() || (currentAccount() || {}).uid !== accountUid) throw new Error('发送前账号或运行状态已变化');
} }));
- const before = await readSession();
+ let before = await readSession();
+ // New Task has no conversation controller until WorkBuddy accepts the first
+ // send. Keep the first controller it mounts as the send baseline; after that,
+ // a conversation change is still treated as an external navigation.
+ let sendBaseline = before;
+ let sendSubmitted = false;
if (op === 'session.send') {
if (!detail.conversationId || !before || before.conversationId !== detail.conversationId) throw new Error('只能发送到已选中的指定会话');
if (before.busy) throw new Error('目标会话正在运行');
@@ -3413,17 +3393,43 @@ function startAutomationRun(task, event = null) {
modelSelection = await withInput(() => selectAutomationModelById(modelId,
op === 'session.send' ? { conversationId: detail.conversationId } : { accountUid }));
appendRunLog('session:model:confirmed');
+ // Selecting a model on New Task may mount its provisional conversation
+ // before any text is entered. Treat that renderer-owned transition as
+ // the send baseline; later changes are still rejected by the guard.
+ if (op === 'session.create') {
+ before = await readSession();
+ sendBaseline = before;
+ }
}
if (isCancelled() || (currentAccount() || {}).uid !== accountUid) throw new Error('发送前账号或运行状态已变化');
- await withInput(() => acSendPhrase(String(detail.message || ''), { requireEmpty: true, isCancelled, guard: async () => {
+ await withInput(() => acSendPhrase(String(detail.message || ''), { requireEmpty: true, isCancelled, beforeSubmit: () => {
+ sendSubmitted = true;
+ }, guard: async () => {
if (isCancelled() || (currentAccount() || {}).uid !== accountUid) throw new Error('账号或运行状态已变化,停止发送');
const selected = await readSession();
- if (op === 'session.send' ? !selected || selected.conversationId !== detail.conversationId : selected && (!before || selected.conversationId !== before.conversationId)) throw new Error('会话已变化,停止发送');
- if (modelId) await confirmAutomationModel(modelId, { displayName: modelSelection.displayName,
- ...(op === 'session.send' ? { conversationId: detail.conversationId } : { accountUid }) });
+ if (op === 'session.send') {
+ if (!selected || selected.conversationId !== detail.conversationId) throw new Error('会话已变化,停止发送');
+ } else if (selected) {
+ if (!sendBaseline) sendBaseline = selected;
+ else if (selected.conversationId !== sendBaseline.conversationId) {
+ if (!sendSubmitted) throw new Error('会话已变化,停止发送');
+ // WorkBuddy creates the real conversation immediately after the
+ // official send click. Accept that one expected transition.
+ sendBaseline = selected;
+ }
+ }
+ // Before the official click, the selected model is a hard safety guard.
+ // Once the click has happened, WorkBuddy may briefly unmount the New
+ // Task controller while mounting the real conversation. The post-send
+ // receipt loop below confirms that real controller with retries; do
+ // not reject an already-submitted message during that transition.
+ if (modelId && !sendSubmitted) await confirmAutomationModel(modelId, { displayName: modelSelection.displayName,
+ ...(op === 'session.send'
+ ? { conversationId: detail.conversationId }
+ : (selected && selected.conversationId ? { conversationId: selected.conversationId, accountUid } : { accountUid })) });
} }));
// Do not retry an unconfirmed send: it may already have reached WorkBuddy.
- const end = Date.now() + 12000;
+ const end = Date.now() + 30000;
while (Date.now() < end) {
if ((currentAccount() || {}).uid !== accountUid) throw new Error('发送后账号已变化,请检查会话;不会自动重发');
const snapshot = await readSession();
@@ -3480,9 +3486,9 @@ function startAutomationRun(task, event = null) {
},
send: async (uid, message) => {
if (isCancelled()) throw new Error('用户停止任务');
- const raw = JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'));
+ const raw = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'))); // [wd-compat]
const auth = raw.auth || {};
- const token = auth.accessToken || auth.access_token || auth.token;
+ const token = wdCompatAuthToken(auth);
if (!token) throw new Error('主账号凭据不可用');
try { return await activateGrowthAccount(token, { apiHost: PROFILE.apiHost, prompt: message, purpose: 'completion-report', timeoutMs: 60000 }); }
catch (_) { throw new Error('云端汇报未确认成功,请检查主账号云端会话;不会自动重试,避免重复发送'); }
@@ -3557,12 +3563,24 @@ function saveCheckinCache(cache) {
}
}
+// 加密备份的刷新结果只在 daemon 生命周期内缓存,绝不把解密后的 token 写回磁盘。
+const backupAuthRuntimeCache = new Map();
+
/** 刷新备份账号凭证:临期惰性刷新,或距上次刷新超过一天时执行保活。 */
async function refreshAccountBackupToken(uid, options = {}) {
const file = path.join(DATA_DIR, 'accounts', uid + '.info');
let root;
+ let encryptedAtRest = false;
+ let sourceSignature = '';
try {
- root = JSON.parse(fs.readFileSync(file, 'utf8'));
+ const stat = fs.statSync(file);
+ sourceSignature = `${stat.mtimeMs}:${stat.size}`;
+ const stored = JSON.parse(fs.readFileSync(file, 'utf8'));
+ encryptedAtRest = wdCompatContainsEncryptedFields(stored);
+ const cached = backupAuthRuntimeCache.get(uid);
+ root = cached && cached.signature === sourceSignature
+ ? cached.root
+ : wdCompatDecryptAuthJson(stored); // [wd-compat]
} catch (e) {
return { root: null, error: 'read-account-failed: ' + e.message };
}
@@ -3580,6 +3598,11 @@ async function refreshAccountBackupToken(uid, options = {}) {
return { root, refreshed: false, error: result.error };
}
const nextRoot = Object.assign({}, root, { auth: result.auth });
+ if (encryptedAtRest) {
+ backupAuthRuntimeCache.set(uid, { signature: sourceSignature, root: nextRoot });
+ log(`[token-refresh] 账号 ${uid} 已刷新(加密备份仅保存在内存)`);
+ return { root: nextRoot, refreshed: true, persisted: false };
+ }
const tmp = file + '.tmp';
try {
fs.writeFileSync(tmp, JSON.stringify(nextRoot, null, 2), { mode: 0o600 });
@@ -3590,7 +3613,8 @@ async function refreshAccountBackupToken(uid, options = {}) {
log(`[token-refresh] 账号 ${uid} 刷新结果落盘失败: ${e.message}`);
return { root, refreshed: false, error: 'write-account-failed: ' + e.message };
}
- return { root: nextRoot, refreshed: true };
+ backupAuthRuntimeCache.delete(uid);
+ return { root: nextRoot, refreshed: true, persisted: true };
}
/**
@@ -3683,7 +3707,7 @@ async function performAccountCheckin(uid) {
const refreshError = refreshed.error || '';
if (!accountRoot) return { uid, ok: false, reason: refreshed.error || 'no-backup' };
const auth = accountRoot.auth && typeof accountRoot.auth === 'object' ? accountRoot.auth : {};
- const tk = auth.accessToken || auth.access_token || auth.token;
+ const tk = wdCompatAuthToken(auth);
if (!tk) return { uid, ok: false, reason: 'no-accessToken' };
const account = { uid, domain: auth.domain || '' };
const r = await dailyCheckin(tk, account);
@@ -4194,8 +4218,9 @@ function sessionContentMtime(wbHome, sessionId) {
}
// Yield between session pairs so renderer reloads and UI events can complete.
-async function yieldAutoCopyToRenderer() {
+async function yieldAutoCopyToRenderer(options = {}) {
await new Promise((resolve) => setImmediate(resolve));
+ if (options && options.waitForInjection === false) return;
const reloadPriority = rendererReloadPriorityPromise;
if (reloadPriority) await reloadPriority;
const pending = pendingReloadInjection;
@@ -4264,10 +4289,14 @@ function collectSessionArchiveFiles(wbHome, sessionId) {
}
function ensureArchiveParentNoFollow(wbHome, target) {
- const root = path.resolve(wbHome);
+ // The configured WorkBuddy root may itself be a junction/symlink. Resolve
+ // only that boundary; every managed child component remains no-follow.
+ const configuredRoot = path.resolve(wbHome);
+ const root = fs.realpathSync(configuredRoot);
const rootStat = fs.lstatSync(root);
- if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) throw new Error('WorkBuddy 数据目录不是受管目录');
- const parent = path.dirname(resolveArchiveTarget(root, archiveRelativePath(root, target)));
+ if (!rootStat.isDirectory()) throw new Error('WorkBuddy 数据目录不是受管目录');
+ const relativeTarget = archiveRelativePath(configuredRoot, path.resolve(target));
+ const parent = path.dirname(resolveArchiveTarget(root, relativeTarget));
const relative = path.relative(root, parent);
let current = root;
for (const part of relative.split(path.sep).filter(Boolean)) {
@@ -4337,6 +4366,8 @@ function sqlPlaceholders(values) {
}
async function insertCopiedSession(src, targetUid, newId) {
+ const updatedAt = Date.now();
+ const lastActivityAt = Number(src.last_activity_at || src.updated_at || updatedAt);
const vals = [
newId,
src.cwd || '',
@@ -4345,8 +4376,8 @@ async function insertCopiedSession(src, targetUid, newId) {
src.custom_title || '',
src.status || 'Pending',
Number(src.created_at || Date.now()),
- Date.now(),
- Number(src.last_activity_at || src.updated_at || Date.now()),
+ updatedAt,
+ lastActivityAt,
Number(src.is_playground || 0),
src.source_mode || null,
src.is_background_automation === null || src.is_background_automation === undefined || src.is_background_automation === '' ? null : Number(src.is_background_automation),
@@ -4364,6 +4395,11 @@ async function insertCopiedSession(src, targetUid, newId) {
'INSERT INTO sessions (' + SESSION_COPY_COLUMNS.join(',') + ') VALUES (' + sqlPlaceholders(vals) + ');',
vals
);
+ // The inserted row intentionally gets a fresh updated_at. Persisting the
+ // source revision here would make every later switch look dirty.
+ return Object.assign({}, src, {
+ id: newId, user_id: targetUid, updated_at: updatedAt, last_activity_at: lastActivityAt,
+ });
}
async function createForkSession(src, selection) {
@@ -4471,6 +4507,7 @@ async function importSessionArchives(payload, targetUid, staged = false) {
// cover every session file on disk (tens of thousands), or active sessions
// evict each other and the cache never warms up.
const SESSION_SYNC_CACHE_LIMIT = 100000;
+const SESSION_SYNC_CACHE_VERSION = 2;
let sessionSyncCacheState = null;
function getSessionSyncCache() {
if (sessionSyncCacheState) return sessionSyncCacheState.map;
@@ -4478,7 +4515,7 @@ function getSessionSyncCache() {
const map = new Map();
try {
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
- if (raw && raw.version === 1 && raw.entries && typeof raw.entries === 'object') {
+ if (raw && raw.version === SESSION_SYNC_CACHE_VERSION && raw.entries && typeof raw.entries === 'object') {
for (const [key, entry] of Object.entries(raw.entries)) {
if (!entry || typeof entry !== 'object') continue;
if (typeof entry.hash !== 'string' || !entry.hash) continue;
@@ -4503,12 +4540,192 @@ function scheduleSessionSyncCacheSave() {
try {
while (state.map.size > SESSION_SYNC_CACHE_LIMIT) state.map.delete(state.map.keys().next().value);
fs.mkdirSync(path.dirname(state.file), { recursive: true });
- replaceFileWithRetry(state.file, JSON.stringify({ version: 1, entries: Object.fromEntries(state.map) }), 0o600);
+ replaceFileWithRetry(state.file, JSON.stringify({ version: SESSION_SYNC_CACHE_VERSION, entries: Object.fromEntries(state.map) }), 0o600);
} catch (_) { state.dirty = true; }
}, 1000);
if (typeof state.timer.unref === 'function') state.timer.unref();
}
+function sessionCopyRowRevision(row) {
+ return JSON.stringify([
+ String(row && row.id || ''), String(row && row.user_id || ''),
+ Number(row && row.updated_at || 0), Number(row && row.last_activity_at || 0),
+ String(row && row.status || ''), String(row && row.title || ''), String(row && row.custom_title || ''),
+ ]);
+}
+
+// The physical session id and account id intentionally differ between members
+// of one shared lineage. Keep the content portion separately so a mapping
+// created from another account can still prove that an unchanged member is a
+// no-op without entering the filesystem snapshot path.
+function sessionCopyContentRevision(row) {
+ return JSON.stringify([
+ Number(row && row.updated_at || 0), Number(row && row.last_activity_at || 0),
+ String(row && row.status || ''), String(row && row.title || ''), String(row && row.custom_title || ''),
+ ]);
+}
+
+// This revision is the cheap fallback used when the renderer event was
+// missed. WorkBuddy advances updated_at for edits that do not necessarily
+// change the sidebar lifecycle payload, so it is part of the observable
+// session state. The fallback still avoids filesystem snapshots and hashes.
+function sessionCopyStableStateRevision(row) {
+ return JSON.stringify([
+ Number(row && row.updated_at || 0), Number(row && row.last_activity_at || 0), String(row && row.status || ''),
+ String(row && row.title || ''), String(row && row.custom_title || ''),
+ ]);
+}
+
+const SESSION_DIRTY_FILE = typeof DATA_DIR !== 'undefined' && typeof path !== 'undefined'
+ ? path.join(DATA_DIR, 'session-dirty.json') : '';
+let sessionDirtyState = null;
+function getSessionDirtyIndex() {
+ if (sessionDirtyState) return sessionDirtyState.index;
+ let raw = null;
+ try { if (SESSION_DIRTY_FILE) raw = JSON.parse(fs.readFileSync(SESSION_DIRTY_FILE, 'utf8')); } catch (_) {}
+ const index = typeof createDirtyIndex === 'function'
+ ? createDirtyIndex(raw)
+ : { get: () => null, mark: () => null, markBaseline: () => false, clear: () => false, shouldSync: () => true, isInitialized: () => false, state: {} };
+ sessionDirtyState = { index, timer: null, dirty: false };
+ return index;
+}
+function scheduleSessionDirtySave() {
+ const state = sessionDirtyState;
+ if (!state || !state.dirty || state.timer) return;
+ state.timer = setTimeout(() => {
+ state.timer = null;
+ if (!state.dirty) return;
+ state.dirty = false;
+ try {
+ if (!SESSION_DIRTY_FILE) return;
+ fs.mkdirSync(path.dirname(SESSION_DIRTY_FILE), { recursive: true });
+ replaceFileWithRetry(SESSION_DIRTY_FILE, JSON.stringify(state.index.state), 0o600);
+ } catch (_) { state.dirty = true; }
+ }, 250);
+ if (typeof state.timer.unref === 'function') state.timer.unref();
+}
+function markSessionDirty(uid, sessionId, event) {
+ const state = sessionDirtyState || (getSessionDirtyIndex(), sessionDirtyState);
+ const before = state.index.get(uid, sessionId);
+ const marker = state.index.mark(uid, sessionId, event);
+ if (marker && (!before || before.at !== marker.at || before.event !== marker.event)) {
+ state.dirty = true;
+ scheduleSessionDirtySave();
+ }
+ return marker;
+}
+function markSessionDirtyBaseline(uid) {
+ const state = sessionDirtyState || (getSessionDirtyIndex(), sessionDirtyState);
+ if (state.index.markBaseline(uid)) {
+ state.dirty = true;
+ scheduleSessionDirtySave();
+ }
+}
+function clearSessionDirty(uid, sessionId, expectedAt) {
+ const state = sessionDirtyState || (getSessionDirtyIndex(), sessionDirtyState);
+ if (!state.index.clear(uid, sessionId, expectedAt)) return false;
+ state.dirty = true;
+ scheduleSessionDirtySave();
+ return true;
+}
+
+function mappingSourceRevisionMatches(mapping, sourceUid, sourceRow) {
+ if (!mapping) return false;
+ const sourceRevision = sessionCopyRowRevision(sourceRow);
+ const sourceRevisions = mapping.sourceRevisions;
+ if (sourceRevisions && typeof sourceRevisions === 'object' &&
+ sourceRevisions[String(sourceUid || '')] === sourceRevision) return true;
+ if (mapping.sourceUid && String(mapping.sourceUid) === String(sourceUid || '') &&
+ mapping.sourceRevision === sourceRevision) return true;
+ const contentRevision = sessionCopyContentRevision(sourceRow);
+ if (mapping.sourceStateRevision === sessionCopyStableStateRevision(sourceRow)) return true;
+ if (mapping.sourceContentRevision === contentRevision) return true;
+ // Mappings written before sourceStateRevision existed contain the same
+ // content tuple after the id/user fields. Accept that tuple for migration.
+ try {
+ const legacy = JSON.parse(mapping.sourceRevision);
+ if (Array.isArray(legacy) && JSON.stringify(legacy.slice(2)) === sessionCopyStableStateRevision(sourceRow)) return true;
+ } catch (_) {}
+ return false;
+}
+
+// WorkBuddy may advance only updated_at while restoring/activating a
+// conversation. That row change is a renderer lifecycle event; a real message
+// edit also advances last_activity_at (or changes status/title metadata). Keep
+// this narrower check separate from the full revision check so message edits
+// still enter the snapshot worker.
+function mappingSourceLifecycleRevisionMatches(mapping, sourceRow) {
+ if (!mapping || !sourceRow) return false;
+ const candidates = [];
+ if (typeof mapping.sourceRevision === 'string') candidates.push(mapping.sourceRevision);
+ if (typeof mapping.sourceStateRevision === 'string') candidates.push(mapping.sourceStateRevision);
+ if (typeof mapping.sourceContentRevision === 'string') candidates.push(mapping.sourceContentRevision);
+ const current = JSON.stringify([
+ Number(sourceRow.last_activity_at || 0), String(sourceRow.status || ''),
+ String(sourceRow.title || ''), String(sourceRow.custom_title || ''),
+ ]);
+ for (const value of candidates) {
+ try {
+ const parsed = JSON.parse(value);
+ if (!Array.isArray(parsed)) continue;
+ const offset = parsed.length >= 7 ? 2 : 0;
+ if (parsed.length >= offset + 5 && JSON.stringify(parsed.slice(offset + 1, offset + 5)) === current) return true;
+ } catch (_) {}
+ }
+ return false;
+}
+
+function mappingWithSourceRevision(mapping, sourceUid, sourceRow) {
+ const sourceRevision = sessionCopyRowRevision(sourceRow);
+ const sourceRevisions = mapping && mapping.sourceRevisions && typeof mapping.sourceRevisions === 'object'
+ ? Object.assign({}, mapping.sourceRevisions)
+ : {};
+ sourceRevisions[String(sourceUid || '')] = sourceRevision;
+ return {
+ sourceRevision,
+ sourceUid: String(sourceUid || ''),
+ sourceContentRevision: sessionCopyContentRevision(sourceRow),
+ sourceStateRevision: sessionCopyStableStateRevision(sourceRow),
+ sourceRevisions,
+ };
+}
+
+function mappingTargetRevisionMatches(mapping, targetRow) {
+ if (!mapping || !targetRow) return false;
+ const stable = sessionCopyStableStateRevision(targetRow);
+ if (mapping.targetStateRevision === stable) return true;
+ try {
+ const legacy = JSON.parse(mapping.targetRevision);
+ if (Array.isArray(legacy) && JSON.stringify(legacy.slice(2)) === stable) return true;
+ } catch (_) {}
+ return mapping.targetRevision === sessionCopyRowRevision(targetRow);
+}
+
+// Opening a copied conversation can refresh its status/last-activity fields
+// without changing any session files. Treat that lifecycle-only drift as a
+// stable target when planning incremental sync; actual content/title revision
+// changes still go through the normal worker path.
+function mappingTargetLifecycleRevisionMatches(mapping, targetRow) {
+ if (!mapping || !targetRow) return false;
+ const candidates = [];
+ if (typeof mapping.targetRevision === 'string') candidates.push(mapping.targetRevision);
+ if (typeof mapping.targetStateRevision === 'string') candidates.push(mapping.targetStateRevision);
+ for (const value of candidates) {
+ try {
+ const parsed = JSON.parse(value);
+ if (!Array.isArray(parsed) || parsed.length < 5) continue;
+ // Revisions are [updatedAt, lastActivityAt, status, title, customTitle]
+ // or their row form with the id/user prefix. Activation can rewrite all
+ // lifecycle fields; title/custom title remain the user-facing identity.
+ const offset = parsed.length >= 7 ? 2 : 0;
+ const comparable = JSON.stringify([parsed[offset + 3], parsed[offset + 4]]);
+ const now = JSON.stringify([String(targetRow.title || ''), String(targetRow.custom_title || '')]);
+ if (comparable === now) return true;
+ } catch (_) {}
+ }
+ return false;
+}
+
async function copySessionRecord(src, targetUid, options = {}) {
if (accountSwitchInProgress && !options.auto) throw new Error('账号正在切换,请稍后同步');
const sourceUid = String(options.sourceUid || src.user_id || '').trim();
@@ -4517,6 +4734,14 @@ async function copySessionRecord(src, targetUid, options = {}) {
// Provenance, not matching titles/timestamps, identifies an existing copy.
const lineageId = options.lineageId || getAutoCopySession(DATA_DIR, sourceUid, src.id).lineageId ||
ensureAutoCopySession(DATA_DIR, sourceUid, src.id, { enabled: false });
+ // Multiple session workers may finish together. Serialize only the shared
+ // meta.json read-modify-write operations; filesystem snapshots stay parallel.
+ const withAutoCopyMetaWrite = (task) => {
+ const previous = copySessionRecord._metaWriteTail || Promise.resolve();
+ const current = previous.catch(() => {}).then(task);
+ copySessionRecord._metaWriteTail = current.catch(() => {});
+ return current;
+ };
const perform = async () => {
await yieldAutoCopyToRenderer();
const readRow = async (id, uid) => (await sqliteQuery(
@@ -4524,6 +4749,11 @@ async function copySessionRecord(src, targetUid, options = {}) {
))[0];
const sourceRow = await readRow(src.id, sourceUid);
if (!sourceRow) throw new Error('源会话已变化,请重试');
+ const dirtyIndex = typeof getSessionDirtyIndex === 'function' ? getSessionDirtyIndex() : null;
+ const dirtyMarker = options.auto && dirtyIndex ? dirtyIndex.get(sourceUid, sourceRow.id) : null;
+ const clearAutoDirty = () => {
+ if (options.auto && dirtyMarker && typeof clearSessionDirty === 'function') clearSessionDirty(sourceUid, sourceRow.id, dirtyMarker.at);
+ };
const mapping = getAutoCopyMapping(DATA_DIR, lineageId, targetUid);
const ids = new Set(getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid));
if (mapping && mapping.targetId) ids.add(mapping.targetId);
@@ -4532,13 +4762,67 @@ async function copySessionRecord(src, targetUid, options = {}) {
const row = await readRow(id, targetUid);
if (row) candidates.push(row);
}
+ // A previous daemon could have created the target row and crashed before
+ // persisting its lineage member/mapping. Repeated account switches must
+ // recover that exact content instead of allocating another physical row.
+ // Restrict the recovery probe to the same workspace/title so unrelated
+ // sessions are never merged by a fuzzy match; the snapshot comparison
+ // below remains the final proof of identity.
+ if (!candidates.length && (!mapping || !mapping.targetId) && sourceRow.cwd) {
+ try {
+ const fallbackRows = await sqliteQuery(
+ 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE deleted_at IS NULL AND user_id = ? AND cwd = ? AND title = ? AND custom_title = ?;',
+ [targetUid, sourceRow.cwd, sourceRow.title || '', sourceRow.custom_title || '']
+ );
+ for (const row of fallbackRows || []) {
+ if (row && String(row.id || '') !== String(sourceRow.id || '')) candidates.push(row);
+ }
+ } catch (_) {}
+ }
const targetIds = candidates.length ? candidates.map(row => row.id) : [crypto.randomUUID()];
const aliases = getAutoCopySessionMemberRecords(DATA_DIR, lineageId).map(member => member.id).concat(targetIds);
const syncCache = getSessionSyncCache();
- let left = sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);
+ const existingMappingTarget = mapping && mapping.targetId ? candidates.find(row => row.id === mapping.targetId) : null;
+ // A brand-new destination has no target bytes to protect and is the only
+ // path that copies every selected session. The synchronous snapshot/apply
+ // implementation matches main's low-overhead file path; using it here
+ // avoids the per-file async stream/hash scheduling cost during first-time
+ // account initialization. Existing copies keep the async path so normal
+ // incremental repairs continue to yield to the renderer.
+ const firstTargetCopy = options.auto && !existingMappingTarget && candidates.length === 0;
+ // Automatic switching revisits the same source/target pairs frequently.
+ // WorkBuddy updates the session row whenever its content changes. Validate
+ // the persisted source/target row revisions before paying for a complete
+ // recursive snapshot and hash comparison. Do not scan projects/ here:
+ // there can be thousands of unrelated project directories, and doing that
+ // once per unchanged session made account switching slower than copying.
+ // Fast path is opt-in by fingerprintVersion so mappings written before
+ // revision persistence are revalidated once through the normal snapshot
+ // comparison path.
+ if (options.auto && existingMappingTarget && mapping.fingerprintVersion === 2 &&
+ mappingSourceRevisionMatches(mapping, sourceUid, sourceRow) &&
+ mappingTargetRevisionMatches(mapping, existingMappingTarget)) {
+ const sourceBytes = Number(mapping.sourceBytes);
+ const totalBytes = Number(mapping.totalBytes);
+ const warning = (Number.isFinite(sourceBytes) ? sourceBytes : 0) > 100 * 1024 * 1024
+ ? '会话超过 100 MB,同步可能较慢' : '';
+ clearAutoDirty();
+ return {
+ status: 'skipped', sourceId: sourceRow.id, targetId: existingMappingTarget.id,
+ branched: false, failedFiles: 0, warning,
+ sourceBytes: Number.isFinite(sourceBytes) ? sourceBytes : 0,
+ totalBytes: Number.isFinite(totalBytes) ? totalBytes : (Number.isFinite(sourceBytes) ? sourceBytes : 0),
+ copiedBytes: 0,
+ };
+ }
+ let left = firstTargetCopy
+ ? sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases, syncCache)
+ : await sessionSync.readSnapshotAsync(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);
const selection = await sessionSync.selectTargetSnapshot(left, targetIds, async id => {
await yieldAutoCopyToRenderer();
- return sessionSync.readSnapshot(PROFILE.dataRoot, id, aliases, syncCache);
+ return firstTargetCopy
+ ? sessionSync.readSnapshot(PROFILE.dataRoot, id, aliases, syncCache)
+ : sessionSync.readSnapshotAsync(PROFILE.dataRoot, id, aliases, syncCache);
}, mapping && mapping.targetId);
// A divergent source still needs to reach the destination. Publish it as
// a new physical session in the same lineage, so later scans find it by
@@ -4551,12 +4835,23 @@ async function copySessionRecord(src, targetUid, options = {}) {
// enough to skip, and the next sync re-reads everything anyway. Avoid the
// extra full target snapshot on the hot all-skipped path.
if (!branched && selection.comparison.kind === 'equal') {
- if (!getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid).includes(targetId)) addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId);
- if (!mapping || mapping.targetId !== targetId) setAutoCopyMapping(DATA_DIR, lineageId, targetUid, { targetId, status: 'copied', failedFiles: 0 });
+ await withAutoCopyMetaWrite(() => {
+ if (!getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid).includes(targetId)) addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId);
+ setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
+ targetId, status: 'copied', failedFiles: 0, fingerprintVersion: 2,
+ ...mappingWithSourceRevision(mapping, sourceUid, sourceRow),
+ targetRevision: sessionCopyRowRevision(existing || { ...sourceRow, id: targetId, user_id: targetUid }),
+ targetStateRevision: sessionCopyStableStateRevision(existing || { ...sourceRow, id: targetId, user_id: targetUid }),
+ sourceBytes: left.totalBytes, totalBytes: left.totalBytes,
+ });
+ });
const warning = left.totalBytes > 100 * 1024 * 1024 ? '会话超过 100 MB,同步可能较慢' : '';
+ clearAutoDirty();
return { status: 'skipped', sourceId: src.id, targetId, branched: false, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes: left.totalBytes, copiedBytes: 0 };
}
- let right = sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases, syncCache);
+ let right = firstTargetCopy
+ ? sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases, syncCache)
+ : await sessionSync.readSnapshotAsync(PROFILE.dataRoot, targetId, aliases, syncCache);
// Size is advisory only; both manual and automatic sync keep all files.
const warning = Math.max(left.totalBytes, right.totalBytes) > 100 * 1024 * 1024
? '会话超过 100 MB,同步可能较慢' : '';
@@ -4570,35 +4865,53 @@ async function copySessionRecord(src, targetUid, options = {}) {
let changed = false;
let totalBytes = left.totalBytes;
let copiedBytes = 0;
+ let persistedTargetRow = existing || null;
const update = async (from, to, fromRow, toRow, missingOnly = false) => {
await yieldAutoCopyToRenderer();
const verifyRows = async () => {
- await assertSessionSyncIdle();
+ await assertSessionSyncIdle([fromRow && fromRow.id, toRow && toRow.id]);
const freshSource = await readRow(fromRow.id, fromRow.user_id);
const freshTarget = toRow ? await readRow(toRow.id, toRow.user_id) : null;
if (JSON.stringify(freshSource) !== JSON.stringify(fromRow) || (toRow && JSON.stringify(freshTarget) !== JSON.stringify(toRow))) {
throw new Error('会话记录正在变化,请稍后重试');
}
};
- const applied = await sessionSync.applySnapshot(from, to, {
- backupRoot: path.join(DATA_DIR, 'session-sync-backups'), metadata: toRow,
- missingOnly, guard: verifyRows,
- commit: async verifyPublished => {
- await verifyRows();
- verifyPublished();
- if (!toRow) {
- // Reserve provenance before the row becomes visible, so a crash
- // after insertion cannot create an untracked duplicate on retry.
- addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId, { branchCopy: branched });
- await insertCopiedSession(fromRow, targetUid, targetId);
- }
- else if (!missingOnly) await sqliteRun(
+ const commit = async (verifyPublished) => {
+ await verifyRows();
+ await verifyPublished();
+ if (!toRow) {
+ // Reserve provenance before the row becomes visible, so a crash
+ // after insertion cannot create an untracked duplicate on retry.
+ await withAutoCopyMetaWrite(() => addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId, { branchCopy: branched }));
+ persistedTargetRow = await insertCopiedSession(fromRow, targetUid, targetId);
+ }
+ else if (!missingOnly) {
+ const updatedAt = Number(fromRow.updated_at || 0);
+ const lastActivityAt = Number(fromRow.last_activity_at || fromRow.updated_at || 0);
+ await sqliteRun(
'UPDATE sessions SET title = ?, custom_title = ?, status = ?, updated_at = ?, last_activity_at = ? WHERE id = ? AND user_id = ? AND deleted_at IS NULL;',
[fromRow.title || '', fromRow.custom_title || '', fromRow.status || 'Pending',
- Number(fromRow.updated_at || 0), Number(fromRow.last_activity_at || fromRow.updated_at || 0), toRow.id, toRow.user_id]
+ updatedAt, lastActivityAt, toRow.id, toRow.user_id]
);
- },
- });
+ persistedTargetRow = Object.assign({}, toRow, {
+ title: fromRow.title || '', custom_title: fromRow.custom_title || '', status: fromRow.status || 'Pending',
+ updated_at: updatedAt, last_activity_at: lastActivityAt,
+ });
+ }
+ };
+ const applied = await (firstTargetCopy
+ ? sessionSync.applySnapshot(from, to, {
+ backupRoot: path.join(DATA_DIR, 'session-sync-backups'), metadata: toRow,
+ missingOnly, guard: verifyRows,
+ onProgress: options.onProgress,
+ commit,
+ })
+ : sessionSync.applySnapshotAsync(from, to, {
+ backupRoot: path.join(DATA_DIR, 'session-sync-backups'), metadata: toRow,
+ missingOnly, guard: verifyRows,
+ onProgress: options.onProgress,
+ commit,
+ }));
totalBytes = applied.totalBytes;
copiedBytes += applied.copiedBytes;
changed = true;
@@ -4609,13 +4922,27 @@ async function copySessionRecord(src, targetUid, options = {}) {
if (comparison.missingRight) await update(left, right, sourceRow, existing, true);
if (comparison.missingLeft) {
// Re-read after the first repair, so race detection uses current bytes.
- left = sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);
- right = sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases, syncCache);
+ left = firstTargetCopy
+ ? sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases, syncCache)
+ : await sessionSync.readSnapshotAsync(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);
+ right = firstTargetCopy
+ ? sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases, syncCache)
+ : await sessionSync.readSnapshotAsync(PROFILE.dataRoot, targetId, aliases, syncCache);
await update(right, left, existing, sourceRow, true);
}
}
- if (!getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid).includes(targetId)) addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId);
- if (changed || !mapping || mapping.targetId !== targetId) setAutoCopyMapping(DATA_DIR, lineageId, targetUid, { targetId, status: 'copied', failedFiles: 0 });
+ const mappingTarget = persistedTargetRow || existing || { ...sourceRow, id: targetId, user_id: targetUid };
+ await withAutoCopyMetaWrite(() => {
+ if (!getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid).includes(targetId)) addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId);
+ return setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
+ targetId, status: 'copied', failedFiles: 0, fingerprintVersion: 2,
+ ...mappingWithSourceRevision(mapping, sourceUid, sourceRow),
+ targetRevision: sessionCopyRowRevision(mappingTarget),
+ targetStateRevision: sessionCopyStableStateRevision(mappingTarget),
+ sourceBytes: left.totalBytes, totalBytes,
+ });
+ });
+ clearAutoDirty();
return { status: changed ? 'copied' : 'skipped', sourceId: src.id, targetId, branched: branched && changed, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes, copiedBytes };
};
// One lineage lock also serializes manual copy and reverse-direction updates.
@@ -4630,31 +4957,235 @@ async function copySessionRecord(src, targetUid, options = {}) {
}
}
-async function buildAutoCopyPlan(sourceUid, targetUid) {
+async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = []) {
const source = String(sourceUid || '').trim();
const target = String(targetUid || '').trim();
if (!source || !target || source === target) return [];
normalizeAutoCopyLineages(DATA_DIR);
const rules = getAutoCopyRules(DATA_DIR, source);
- if (!rules.allSessions && !rules.sessionIds.length && !rules.workspaces.length) return [];
+ const requested = new Set((Array.isArray(requestedSessionIds) ? requestedSessionIds : [])
+ .map((id) => String(id || '').trim())
+ .filter((id) => id && id.length <= 200 && id !== '.' && id !== '..' &&
+ !/[\\/\x00-\x1f\x7f]/.test(id) && !/^[ .]|[ .]$/.test(id) && !/[<>:"|?*]/.test(id)));
+ if (!rules.allSessions && !rules.sessionIds.length && !rules.workspaces.length && !requested.size) return [];
const rows = await sqliteQuery(
'SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id ' +
'FROM sessions WHERE deleted_at IS NULL AND user_id = ? ORDER BY created_at DESC;',
[source]
);
const workspaceSet = new Set(rules.workspaces.map(canonicalWorkspace));
- const selectedRows = rows.filter((row) => isAutoCopySessionSelected(rules, row));
+ const selectedRows = rows.filter((row) => requested.has(String(row.id || '')) || isAutoCopySessionSelected(rules, row));
+ const mappings = getAutoCopyMappings(
+ DATA_DIR,
+ selectedRows.map((row) => {
+ const known = rules.allLineages && rules.allLineages[String(row.id)];
+ if (known) return known;
+ if (!requested.has(String(row.id || '')) || typeof getAutoCopySession !== 'function') return null;
+ try { return getAutoCopySession(DATA_DIR, source, row.id).lineageId; } catch (_) { return null; }
+ }).filter(Boolean),
+ target
+ );
+ const dirtyIndex = typeof getSessionDirtyIndex === 'function'
+ ? getSessionDirtyIndex()
+ : { shouldSync: () => true };
+ const clearStableDirtyMarker = (row, mapping, provenEqual = false) => {
+ if (!mapping || mapping.fingerprintVersion !== 2 || !mapping.targetId ||
+ (!provenEqual && !mappingSourceRevisionMatches(mapping, source, row))) return false;
+ if (typeof dirtyIndex.get !== 'function' || typeof clearSessionDirty !== 'function') return false;
+ const marker = dirtyIndex.get(source, row.id);
+ if (!marker) return false;
+ // Markers written by the pre-1.2.139 lifecycle signature can survive a
+ // reload even though both persisted revisions prove the mapping is clean.
+ // Clear only that proven no-op; a changed source revision remains dirty.
+ clearSessionDirty(source, row.id, marker.at);
+ return true;
+ };
+ const refreshStableMappedPayload = async (row, mapping, targetRow, lineageId) => {
+ if (!mapping || !mapping.targetId || !targetRow || !lineageId ||
+ typeof sessionSync === 'undefined' || typeof sessionSync.readSnapshotAsync !== 'function' ||
+ typeof sessionSync.compareSnapshots !== 'function') return false;
+ try {
+ const members = typeof getAutoCopySessionMemberRecords === 'function'
+ ? getAutoCopySessionMemberRecords(DATA_DIR, lineageId).map((member) => member && member.id).filter(Boolean)
+ : [];
+ const aliases = Array.from(new Set([String(row.id), String(targetRow.id), ...members]));
+ const cache = typeof getSessionSyncCache === 'function' ? getSessionSyncCache() : null;
+ const sourceSnapshot = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, row.id, aliases, cache);
+ const targetSnapshot = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, targetRow.id, aliases, cache);
+ if (sessionSync.compareSnapshots(sourceSnapshot, targetSnapshot).kind !== 'equal') return false;
+ setAutoCopyMapping(DATA_DIR, lineageId, target,
+ Object.assign({}, mapping, mappingWithSourceRevision(mapping, source, row), {
+ targetRevision: sessionCopyRowRevision(targetRow),
+ targetStateRevision: sessionCopyStableStateRevision(targetRow),
+ sourceBytes: sourceSnapshot.totalBytes,
+ totalBytes: sourceSnapshot.totalBytes,
+ }));
+ return true;
+ } catch (_) {
+ return false;
+ }
+ };
+ // A requested active session still needs its target id for post-switch
+ // navigation, but it must not force a full snapshot when the renderer did
+ // not report that session as dirty. Read target rows only for this narrow
+ // requested-session check; regular no-op plans keep the original hot path.
+ let targetRows = null;
+ let targetById = null;
+ const loadTargetRows = async () => {
+ if (targetRows) return;
+ targetRows = await sqliteQuery(
+ 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE deleted_at IS NULL AND user_id = ?;',
+ [target]
+ );
+ targetById = new Map(targetRows.map((row) => [String(row.id), row]));
+ };
+ if (requested.size) await loadTargetRows();
+ const hasDirtyMarker = (row) => typeof dirtyIndex.get === 'function' && !!dirtyIndex.get(source, row.id);
+ const initializedClean = (row) => typeof dirtyIndex.isInitialized === 'function' &&
+ dirtyIndex.isInitialized(source) && !hasDirtyMarker(row);
+ const stableTargetExists = (mapping) => !!(mapping && mapping.targetId && targetById &&
+ targetById.has(String(mapping.targetId)) && (() => {
+ const targetRow = targetById.get(String(mapping.targetId));
+ return mappingTargetRevisionMatches(mapping, targetRow) ||
+ mappingTargetLifecycleRevisionMatches(mapping, targetRow);
+ })());
+ // A lineage may contain several historical physical copies. Their persisted
+ // source revision can refer to a different member even though the renderer
+ // has established a clean baseline for the current account. Resolve target
+ // rows once so that this legacy drift can stay on the metadata-only path.
+ if (!targetRows && typeof dirtyIndex.isInitialized === 'function' && dirtyIndex.isInitialized(source)) {
+ const hasRevisionDrift = selectedRows.some((row) => {
+ if (!initializedClean(row)) return false;
+ const lineageId = rules.allLineages && rules.allLineages[String(row.id)];
+ const mapping = lineageId ? mappings.get(String(lineageId)) : null;
+ return mapping && mapping.fingerprintVersion === 2 && mapping.targetId &&
+ !mappingSourceRevisionMatches(mapping, source, row);
+ });
+ if (hasRevisionDrift) await loadTargetRows();
+ }
+ // Dirty lifecycle notifications need the target row to prove that the
+ // mapped copy still exists before they can be cleared without a worker.
+ if (!targetRows && selectedRows.some((row) => {
+ if (!dirtyIndex.shouldSync(source, row.id)) return false;
+ const lineageId = rules.allLineages && rules.allLineages[String(row.id)];
+ const mapping = lineageId ? mappings.get(String(lineageId)) : null;
+ return !!(mapping && mapping.targetId);
+ })) await loadTargetRows();
+ // Once the renderer has established a baseline, only sessions reported by
+ // its lifecycle feed enter the copy worker. Before that first baseline the
+ // conservative fallback keeps existing installations fully synchronised.
+ // Do the source-side check before reading the target account: the common
+ // no-op switch should be a single sessions query plus metadata lookup.
+ // Keep the array realm of the SQLite result. Some embedders execute this
+ // planner in a VM context; returning a foreign-realm array breaks callers'
+ // strict structural comparisons even when the plan is empty. `filter`
+ // preserves the source array's realm in both the daemon and VM harness.
+ const dirtyRows = selectedRows.filter(() => false);
+ for (const row of selectedRows) {
+ const requestedRow = requested.has(String(row.id || ''));
+ if (requestedRow) {
+ const lineageId = (rules.allLineages && rules.allLineages[String(row.id)]) ||
+ (typeof getAutoCopySession === 'function' && getAutoCopySession(DATA_DIR, source, row.id)?.lineageId);
+ const mapping = lineageId ? mappings.get(String(lineageId)) : null;
+ // The target mapping is enough to restore the active view. Only enter
+ // the worker when it is missing, its row disappeared, or the renderer
+ // explicitly marked the source session dirty.
+ if (!mapping || mapping.fingerprintVersion !== 2 || !mapping.targetId ||
+ !targetById || !targetById.has(String(mapping.targetId))) {
+ dirtyRows.push(row);
+ continue;
+ }
+ if (mappingSourceRevisionMatches(mapping, source, row) &&
+ mappingTargetRevisionMatches(mapping, targetById.get(String(mapping.targetId)))) {
+ clearStableDirtyMarker(row, mapping);
+ continue;
+ }
+ if (mappingSourceLifecycleRevisionMatches(mapping, row) && stableTargetExists(mapping)) {
+ clearStableDirtyMarker(row, mapping, true);
+ continue;
+ }
+ if (!mappingSourceRevisionMatches(mapping, source, row) && stableTargetExists(mapping)) {
+ const refreshed = await refreshStableMappedPayload(
+ row, mapping, targetById.get(String(mapping.targetId)), lineageId
+ );
+ if (initializedClean(row) || refreshed) {
+ clearStableDirtyMarker(row, mapping, refreshed);
+ continue;
+ }
+ }
+ dirtyRows.push(row);
+ continue;
+ }
+ const lineageId = rules.allLineages && rules.allLineages[String(row.id)];
+ const mapping = lineageId ? mappings.get(String(lineageId)) : null;
+ if (dirtyIndex.shouldSync(source, row.id)) {
+ if (clearStableDirtyMarker(row, mapping)) continue;
+ if (mappingSourceLifecycleRevisionMatches(mapping, row) && targetById && stableTargetExists(mapping)) {
+ clearStableDirtyMarker(row, mapping, true);
+ continue;
+ }
+ dirtyRows.push(row);
+ continue;
+ }
+ if (!mapping || mapping.fingerprintVersion !== 2 || !mapping.targetId) { dirtyRows.push(row); continue; }
+ if (mappingSourceRevisionMatches(mapping, source, row)) continue;
+ // Once the renderer has supplied a baseline, a persisted revision drift
+ // without a dirty event is historical lineage churn, not a content edit.
+ // Keep missing target rows on the worker path so first-time recovery still
+ // creates the physical copy.
+ if (!(initializedClean(row) && stableTargetExists(mapping))) dirtyRows.push(row);
+ }
+ if (!dirtyRows.length) return [];
+
+ // Only dirty/new source rows need target state to resolve an existing copy,
+ // repair a missing row, or detect a divergent continuation.
+ if (!targetRows) {
+ await loadTargetRows();
+ }
// Full-copy and workspace matches need stable hidden lineages for idempotent
// repeated switches. Prepare the whole batch with one metadata write.
- const lineageSessionIds = selectedRows
+ const lineageSessionIds = dirtyRows
.filter((row) => rules.allSessions || workspaceSet.has(canonicalWorkspace(row.cwd)))
.map((row) => row.id);
- const ensuredLineages = lineageSessionIds.length
- ? ensureAutoCopySessions(DATA_DIR, source, lineageSessionIds, { enabled: !rules.allSessions })
+ // `getAutoCopyRules` already loaded the lineage index. On the hot path all
+ // selected sessions are normally indexed, so avoid reparsing and rewriting
+ // the large metadata file just to confirm that nothing needs to be created.
+ const missingLineageIds = lineageSessionIds.filter((id) => !rules.allLineages[String(id)]);
+ const ensuredLineages = missingLineageIds.length
+ ? ensureAutoCopySessions(DATA_DIR, source, missingLineageIds, { enabled: !rules.allSessions })
: {};
- return selectedRows.map((row) => Object.assign({}, row, {
+ const lineageRows = dirtyRows.map((row) => Object.assign({}, row, {
lineageId: rules.allLineages[String(row.id)] || ensuredLineages[String(row.id)] || null,
}));
+ if (!lineageRows.length) return lineageRows;
+
+ // Filter the hot path in one batch. The persisted mapping and the target
+ // session row already carry the same revisions used by copySessionRecord;
+ // unchanged sessions do not need to enter the worker pool at all.
+ return lineageRows.filter((row) => {
+ const mapping = row.lineageId ? mappings.get(String(row.lineageId)) : null;
+ if (!mapping || mapping.fingerprintVersion !== 2 || !mapping.targetId) return true;
+ const targetRow = targetById.get(String(mapping.targetId));
+ return !targetRow || !mappingSourceRevisionMatches(mapping, source, row) ||
+ (!mappingTargetRevisionMatches(mapping, targetRow) &&
+ !mappingTargetLifecycleRevisionMatches(mapping, targetRow));
+ });
+}
+
+let autoCopyTargetRevisionMigrationStarted = false;
+async function migrateAutoCopyTargetRevisionBaselines() {
+ if (autoCopyTargetRevisionMigrationStarted) return;
+ autoCopyTargetRevisionMigrationStarted = true;
+ try {
+ const rows = await sqliteQuery(
+ 'SELECT id, user_id, updated_at, last_activity_at, status, title, custom_title FROM sessions WHERE deleted_at IS NULL;'
+ );
+ const rowsByKey = new Map(rows.map((row) => [JSON.stringify([String(row.id || ''), String(row.user_id || '')]), row]));
+ const changed = migrateAutoCopyTargetRevisionsFromMeta(DATA_DIR, rowsByKey);
+ if (changed) log(`[sessions-auto-copy] 已校准 ${changed} 条历史目标 revision`);
+ } catch (error) {
+ log(`[sessions-auto-copy] 历史目标 revision 校准失败: ${error.message}`);
+ }
}
const autoCopyJobs = new Map();
@@ -4698,6 +5229,22 @@ function pruneAutoCopyJobs() {
}
}
+function resolveAutoCopyTargetId(sourceUid, targetUid, sessionId) {
+ const source = String(sourceUid || '').trim();
+ const target = String(targetUid || '').trim();
+ const id = String(sessionId || '').trim();
+ if (!source || !target || !id || typeof getAutoCopyRules !== 'function' || typeof getAutoCopyMapping !== 'function') return '';
+ try {
+ const rules = getAutoCopyRules(DATA_DIR, source);
+ const lineageId = (rules.allLineages && rules.allLineages[id]) ||
+ (typeof getAutoCopySession === 'function' && getAutoCopySession(DATA_DIR, source, id)?.lineageId);
+ const mapping = lineageId ? getAutoCopyMapping(DATA_DIR, lineageId, target) : null;
+ return mapping && mapping.targetId ? String(mapping.targetId) : '';
+ } catch (_) {
+ return '';
+ }
+}
+
function runAutoCopyQueue() {
if (autoCopyWorkerRunning || !autoCopyQueue.length) return;
autoCopyWorkerRunning = true;
@@ -4731,6 +5278,8 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {
targetUid,
sourceName: String(accountLabels.sourceName || ''),
targetName: String(accountLabels.targetName || ''),
+ openSessionId: String(accountLabels.openSessionId || '').trim(),
+ openSessionTargetId: '',
plan: Array.isArray(plan) ? plan : [],
total: Array.isArray(plan) ? plan.length : 0,
processed: 0,
@@ -4755,56 +5304,141 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {
job.status = 'running';
// 账号切换响应、CDP 导航和注入事件必须先有机会完成;Node SQLite 与文件复制
// 的 Promise 可能同步结算,连续微任务会在 macOS 上长期饿死 I/O 事件。
- await yieldAutoCopyToRenderer();
+ // Planning only reads SQLite and auto-copy metadata. Do not make a
+ // no-op synchronization wait for the renderer's post-reload injection.
+ await yieldAutoCopyToRenderer({ waitForInjection: false });
// A rapid switch chain may enqueue this job before the previous copy has
// created the target rows. Re-plan after the queue reaches this job.
job.copyStartedAt = Date.now();
- job.plan = await buildAutoCopyPlan(sourceUid, targetUid);
+ job.plan = await buildAutoCopyPlan(sourceUid, targetUid, job.openSessionId ? [job.openSessionId] : []);
job.total = job.plan.length;
- try {
- const sizes = await sessionSync.readSessionSizes(PROFILE.dataRoot, job.plan.map(src => String(src.id || '')));
- const values = job.plan.map(src => sizes.get(String(src.id || '')));
- job.totalBytes = values.every(value => typeof value === 'number' && Number.isFinite(value) && value >= 0)
- ? values.reduce((sum, value) => sum + value, 0) : null;
- } catch (_) { job.totalBytes = null; }
- for (const src of job.plan) {
- job.currentLabel = String(src.custom_title || src.title || src.cwd || '未命名会话');
- const detail = {
- id: String(src.id || ''),
- label: job.currentLabel,
- status: 'running',
- failedFiles: 0,
- conflicts: 0,
- };
- await yieldAutoCopyToRenderer();
+ if (job.openSessionId && !job.plan.some((row) => String(row && row.id || '') === job.openSessionId)) {
+ job.openSessionTargetId = resolveAutoCopyTargetId(sourceUid, targetUid, job.openSessionId);
+ }
+ // Each source snapshot already computes its byte total. Avoid a separate
+ // full directory walk here: the old pre-scan doubled metadata I/O before
+ // the per-session snapshot pass, especially on Windows with many files.
+ job.totalBytes = null;
+ // Session snapshots are independent across lineages. A small worker pool
+ // prevents hundreds of "already equal" sessions from serialising all
+ // directory metadata I/O, while keeping the disk pressure bounded on
+ // lower-end Windows machines.
+ const concurrency = Math.min(4, Math.max(1, job.plan.length));
+ // The active conversation is still flushed by WorkBuddy for a short
+ // period after account navigation. Give that one requested session a
+ // bounded backoff retry window; ordinary sessions remain fail-fast.
+ const activeSessionRetryDelays = [350, 700, 1200];
+ let nextIndex = 0;
+ const recoverOpenSessionTarget = (src) => {
+ if (!job.openSessionId || String(src && src.id || '') !== job.openSessionId || job.openSessionTargetId) return;
+ if (typeof DATA_DIR === 'undefined' || typeof getAutoCopyMapping !== 'function') return;
try {
- const result = await copySessionRecord(src, targetUid, { sourceUid, lineageId: src.lineageId, auto: true });
- detail.status = result.status === 'partial' ? 'partial'
- : result.status === 'conflict' ? 'conflict'
- : result.status === 'skipped' ? 'skipped' : 'copied';
- detail.branched = result.branched === true;
- detail.totalBytes = result.totalBytes;
- job.copiedBytes += Math.max(0, Number(result.copiedBytes) || 0);
- job.processedBytes += Math.max(0, Number(result.sourceBytes) || 0);
- detail.warning = result.warning || '';
- if (detail.warning) job.warning = detail.warning;
- detail.failedFiles = Number(result.failedFiles) || 0;
- detail.conflicts = Number(result.conflicts) || 0;
- if (result.status === 'skipped') job.skipped++;
- else if (result.status === 'partial') { job.partial++; job.failedItems++; }
- else if (result.status === 'conflict') job.conflicts += Number(result.conflicts) || 1;
- else job.copied++;
- if (result.failedFiles) job.failed += result.failedFiles;
- } catch (e) {
- job.failed++;
- job.failedItems++;
- detail.status = 'failed';
- detail.error = String(e.message || e).slice(0, 240);
- log(`[sessions-auto-copy] ${sourceUid} -> ${targetUid} 会话 ${src.id} 失败: ${e.message}`);
+ let lineageId = src && src.lineageId;
+ if (!lineageId && typeof getAutoCopySession === 'function') {
+ const record = getAutoCopySession(DATA_DIR, sourceUid, src.id);
+ lineageId = record && record.lineageId;
+ }
+ const mapping = lineageId ? getAutoCopyMapping(DATA_DIR, lineageId, targetUid) : null;
+ if (mapping && mapping.targetId) {
+ job.openSessionTargetId = String(mapping.targetId);
+ log(`[sessions-auto-copy] 已恢复当前会话目标映射 source=${src.id} target=${job.openSessionTargetId}`);
+ }
+ } catch (error) {
+ log(`[sessions-auto-copy] 恢复当前会话目标映射失败: ${error.message}`);
}
- if (job.details.length < 500) job.details.push(detail);
- job.processed++;
- }
+ };
+ const processNext = async () => {
+ for (;;) {
+ const index = nextIndex++;
+ if (index >= job.plan.length) return;
+ const src = job.plan[index];
+ job.currentLabel = String(src.custom_title || src.title || src.cwd || '未命名会话');
+ const detail = {
+ id: String(src.id || ''),
+ label: job.currentLabel,
+ status: 'running',
+ failedFiles: 0,
+ conflicts: 0,
+ };
+ await yieldAutoCopyToRenderer();
+ try {
+ // Keep this counter local to the session. Other workers may publish
+ // bytes while this one is awaiting the copy, so a shared before/after
+ // comparison can mistake another worker's progress for this one's.
+ let reportedBytes = 0;
+ const activeSession = job.openSessionId && String(src.id || '') === job.openSessionId;
+ let result;
+ let copyAttempt = 0;
+ for (;;) {
+ try {
+ result = await copySessionRecord(src, targetUid, {
+ sourceUid, lineageId: src.lineageId, auto: true,
+ onProgress: (progress) => {
+ const bytes = Math.max(0, Number(progress && progress.bytes) || 0);
+ reportedBytes += bytes;
+ job.copiedBytes += bytes;
+ },
+ });
+ break;
+ } catch (error) {
+ if (!activeSession || copyAttempt >= activeSessionRetryDelays.length) throw error;
+ const retryDelay = activeSessionRetryDelays[copyAttempt];
+ copyAttempt++;
+ log(`[sessions-auto-copy] 当前会话复制失败,${retryDelay}ms 后重试 attempt=${copyAttempt}: ${error.message}`);
+ await new Promise((resolve) => setTimeout(resolve, retryDelay));
+ await yieldAutoCopyToRenderer();
+ }
+ }
+ detail.status = result.status === 'partial' ? 'partial'
+ : result.status === 'conflict' ? 'conflict'
+ : result.status === 'skipped' ? 'skipped' : 'copied';
+ detail.branched = result.branched === true;
+ if (job.openSessionId && String(result.sourceId || '') === job.openSessionId) {
+ job.openSessionTargetId = String(result.targetId || '');
+ }
+ detail.totalBytes = result.totalBytes;
+ // Test doubles and older adapters may not call onProgress. Add only
+ // the unreported remainder so a real callback is never double-counted.
+ const resultBytes = Math.max(0, Number(result.copiedBytes) || 0);
+ if (resultBytes > reportedBytes) job.copiedBytes += resultBytes - reportedBytes;
+ job.processedBytes += Math.max(0, Number(result.sourceBytes) || 0);
+ detail.warning = result.warning || '';
+ if (detail.warning) job.warning = detail.warning;
+ detail.failedFiles = Number(result.failedFiles) || 0;
+ detail.conflicts = Number(result.conflicts) || 0;
+ if (result.status === 'skipped') job.skipped++;
+ else if (result.status === 'partial') { job.partial++; job.failedItems++; }
+ else if (result.status === 'conflict') job.conflicts += Number(result.conflicts) || 1;
+ else job.copied++;
+ if (result.failedFiles) job.failed += result.failedFiles;
+ } catch (e) {
+ recoverOpenSessionTarget(src);
+ const errorText = String(e.message || e).slice(0, 240);
+ if (errorText === '会话消息文件没有消息,未同步') {
+ // Empty metadata-only sessions are normal transient WorkBuddy
+ // rows (for example a newly opened draft), not sync failures.
+ if (typeof getSessionDirtyIndex === 'function' && typeof clearSessionDirty === 'function') {
+ const dirty = getSessionDirtyIndex().get(sourceUid, src.id);
+ if (dirty) clearSessionDirty(sourceUid, src.id, dirty.at);
+ }
+ detail.status = 'skipped';
+ detail.skipReason = 'empty-message-file';
+ job.skipped++;
+ log(`[sessions-auto-copy] ${sourceUid} -> ${targetUid} 会话 ${src.id} 跳过: ${errorText}`);
+ } else {
+ job.failed++;
+ job.failedItems++;
+ detail.status = 'failed';
+ detail.error = errorText;
+ log(`[sessions-auto-copy] ${sourceUid} -> ${targetUid} 会话 ${src.id} 失败: ${e.message}`);
+ }
+ }
+ if (index < 500) job.details[index] = detail;
+ job.processed++;
+ }
+ };
+ await Promise.all(Array.from({ length: concurrency }, () => processNext()));
+ job.details = job.details.filter(Boolean);
job.status = job.conflicts ? 'conflict' : (job.failed || job.partial ? 'partial' : 'done');
job.finishedAt = Date.now();
log(`[sessions-auto-copy] ${sourceUid} -> ${targetUid} 完成 total=${job.total} copied=${job.copied} skipped=${job.skipped} partial=${job.partial} conflicts=${job.conflicts} failed=${job.failed}`);
@@ -4845,6 +5479,7 @@ function publicAutoCopyJob(job) {
error: job.error,
sourceUid: job.sourceUid,
targetUid: job.targetUid,
+ openSessionId: job.openSessionTargetId || '',
sourceName: job.sourceName,
targetName: job.targetName,
currentLabel: job.currentLabel,
@@ -4853,9 +5488,11 @@ function publicAutoCopyJob(job) {
};
}
-function activeAutoCopyJob() {
+function activeAutoCopyJob(targetUid = '') {
+ const wantedTarget = String(targetUid || '').trim();
const jobs = Array.from(autoCopyJobs.values());
const active = jobs
+ .filter((job) => !wantedTarget || String(job.targetUid || '') === wantedTarget)
.filter((job) => job.status === 'running' || job.status === 'queued')
.sort((a, b) => {
if (a.status !== b.status) return a.status === 'running' ? -1 : 1;
@@ -4863,6 +5500,7 @@ function activeAutoCopyJob() {
})[0];
if (active) return active;
const recent = jobs
+ .filter((job) => !wantedTarget || String(job.targetUid || '') === wantedTarget)
.filter((job) => job.finishedAt && Date.now() - job.finishedAt < 15000)
.sort((a, b) => Number(b.finishedAt || 0) - Number(a.finishedAt || 0))[0];
return recent || null;
@@ -5733,9 +6371,15 @@ async function ensureAutomationNewTask(options = {}) {
await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp' });
await cdpSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
- await sleep(150);
+ const clearDeadline = Date.now() + 3000;
+ do {
+ await sleep(100);
+ if (options.guard) await options.guard();
+ surface = await readAutomationAgentSurface(false);
+ if (surface && surface.newTaskReady && !surface.composerText) break;
+ } while (Date.now() < clearDeadline);
}
- surface = await readAutomationAgentSurface(false);
+ if (!surface || surface.composerText) surface = await readAutomationAgentSurface(false);
if (!surface || !surface.newTaskReady || surface.composerText) throw new Error('新建任务输入框尚未清空,原草稿已保留在暂存');
return surface;
}
@@ -5906,6 +6550,7 @@ function buildBusyExpr() {
for (var i = 0; i < sels.length; i++) {
var els = document.querySelectorAll(sels[i]);
for (var j = 0; j < els.length; j++) {
+ if (els[j].closest && els[j].closest('.wbs-root')) continue;
var r = els[j].getBoundingClientRect();
if (r.width > 0 && r.height > 0) return true;
}
@@ -6038,11 +6683,11 @@ function initBuiltinAssets() {
fs.writeFileSync(BACKGROUND_BLUR_FILE, JSON.stringify({ blur: 0 }, null, 2));
log('[init] 首次初始化:背景毛玻璃默认 0% -> background-blur.json');
}
- // 5) 默认主题 → WorkDaddy 壁纸主题(仅当 profile 从未设置过主题)
+ // 5) 默认主题 → 浅色主题(仅当 profile 从未设置过主题)
const curFile = path.join(DATA_DIR, 'current-theme.json');
if (!fs.existsSync(curFile)) {
- fs.writeFileSync(curFile, JSON.stringify({ id: 'nebula', at: new Date().toISOString() }, null, 2));
- log('[init] 首次初始化:默认主题 -> WorkDaddy 壁纸主题(nebula)');
+ fs.writeFileSync(curFile, JSON.stringify({ id: 'default', at: new Date().toISOString() }, null, 2));
+ log('[init] 首次初始化:默认主题 -> 浅色主题(default)');
}
} catch (e) {
log('[init] 首次初始化失败: ' + e.message);
@@ -6700,18 +7345,23 @@ async function sendStashToComposer(record) {
const focusExpr = `(function(){
try {
+ function visibleEditor(element) {
+ if (!element || element.closest('.wbs-root')) return false;
+ var rect = element.getBoundingClientRect(), style = getComputedStyle(element);
+ return rect.width > 0 && rect.height > 0 && rect.bottom > 0 && style.display !== 'none' && style.visibility !== 'hidden';
+ }
var mic = document.querySelector('.voice-mic-wrap');
var ed = null;
if (mic) {
var p = mic.parentElement;
for (var up = 0; up < 6 && p; up++) {
- var e = p.querySelector('[contenteditable="true"]') || p.querySelector('[data-slate-editor="true"]');
- if (e) { ed = e; break; }
+ var e = p.querySelector('[contenteditable="true"],textarea') || p.querySelector('[data-slate-editor="true"]');
+ if (visibleEditor(e)) { ed = e; break; }
p = p.parentElement;
}
}
if (!ed) {
- var all = document.querySelectorAll('[contenteditable="true"]');
+ var all = Array.from(document.querySelectorAll('[contenteditable="true"],textarea')).filter(visibleEditor);
if (mic && all.length) {
var mr = mic.getBoundingClientRect(), best = null, bd = Infinity;
for (var i = 0; i < all.length; i++) {
@@ -6723,7 +7373,10 @@ async function sendStashToComposer(record) {
}
if (best) ed = best;
}
- if (!ed && all.length) ed = all[0];
+ if (!ed && all.length) {
+ ed = all.find(function(element) { return !!element.closest('.cr-input-box,.wb-home-composer'); }) ||
+ all.sort(function(left, right) { return right.getBoundingClientRect().bottom - left.getBoundingClientRect().bottom; })[0];
+ }
}
if (!ed) return { ok: false, error: '未找到输入框' };
ed.focus();
@@ -6749,10 +7402,10 @@ async function sendStashToComposer(record) {
var ed = null;
if (mic) {
var p = mic.parentElement;
- for (var up = 0; up < 6 && p; up++) { var e = p.querySelector('[contenteditable="true"]'); if (e) { ed = e; break; } p = p.parentElement; }
+ for (var up = 0; up < 6 && p; up++) { var e = p.querySelector('[contenteditable="true"],textarea'); if (e) { ed = e; break; } p = p.parentElement; }
}
if (!ed) {
- var all = document.querySelectorAll('[contenteditable="true"]'), best = null, bestBottom = -Infinity;
+ var all = document.querySelectorAll('[contenteditable="true"],textarea'), best = null, bestBottom = -Infinity;
for (var i = 0; i < all.length; i++) {
var r = all[i].getBoundingClientRect();
if (r.width > 0 && r.height > 0 && r.bottom > 0 && r.bottom > bestBottom) { best = all[i]; bestBottom = r.bottom; }
@@ -6765,7 +7418,8 @@ async function sendStashToComposer(record) {
// inspect a detached clone so the live editor and its selection stay intact.
var clone = ed.cloneNode(true);
clone.querySelectorAll('[data-slate-placeholder="true"],[data-slate-zero-width]').forEach(function(node){ node.remove(); });
- return { ok: true, hasContent: ((clone.innerText || clone.textContent || '').replace(/[\\uFEFF\\u200B\\u00A0]/g, '').trim().length > 0) || !!ed.querySelector('[data-contentblock]') };
+ var editorText = ed.tagName === 'TEXTAREA' ? ed.value : (clone.innerText || clone.textContent || '');
+ return { ok: true, hasContent: (String(editorText || '').replace(/[\\uFEFF\\u200B\\u00A0]/g, '').trim().length > 0) || !!ed.querySelector('[data-contentblock]') };
} catch (e) { return { ok: false, error: String(e) }; }
})()`;
const clr = await guardedSend('Runtime.evaluate', { expression: clearExpr, returnByValue: true });
@@ -6809,9 +7463,9 @@ async function sendStashToComposer(record) {
var mic = document.querySelector('.voice-mic-wrap');
var ed = null;
if (mic) { var p = mic.parentElement;
- for (var up = 0; up < 6 && p; up++) { var e = p.querySelector('[contenteditable="true"]'); if (e) { ed = e; break; } p = p.parentElement; } }
+ for (var up = 0; up < 6 && p; up++) { var e = p.querySelector('[contenteditable="true"],textarea'); if (e) { ed = e; break; } p = p.parentElement; } }
if (!ed) {
- var all = document.querySelectorAll('[contenteditable="true"]'), best = null, bestBottom = -Infinity;
+ var all = document.querySelectorAll('[contenteditable="true"],textarea'), best = null, bestBottom = -Infinity;
for (var i = 0; i < all.length; i++) { var r = all[i].getBoundingClientRect(); if (r.width > 0 && r.height > 0 && r.bottom > 0 && r.bottom > bestBottom) { best = all[i]; bestBottom = r.bottom; } }
ed = best;
}
@@ -6834,9 +7488,9 @@ async function sendStashToComposer(record) {
var mic = document.querySelector('.voice-mic-wrap');
var ed = null;
if (mic) { var p = mic.parentElement;
- for (var up = 0; up < 6 && p; up++) { var e = p.querySelector('[contenteditable="true"]'); if (e) { ed = e; break; } p = p.parentElement; } }
+ for (var up = 0; up < 6 && p; up++) { var e = p.querySelector('[contenteditable="true"],textarea'); if (e) { ed = e; break; } p = p.parentElement; } }
if (!ed) {
- var all = document.querySelectorAll('[contenteditable="true"]'), best = null, bestBottom = -Infinity;
+ var all = document.querySelectorAll('[contenteditable="true"],textarea'), best = null, bestBottom = -Infinity;
for (var i = 0; i < all.length; i++) { var r = all[i].getBoundingClientRect(); if (r.width > 0 && r.height > 0 && r.bottom > 0 && r.bottom > bestBottom) { best = all[i]; bestBottom = r.bottom; } }
ed = best;
}
@@ -6933,7 +7587,7 @@ async function sendStashToComposer(record) {
var mic = document.querySelector('.voice-mic-wrap');
var row = mic ? mic.parentElement : null;
if (!row) {
- var allEd = document.querySelectorAll('[contenteditable="true"]'), ed = null, bestBottom = -Infinity;
+ var allEd = document.querySelectorAll('[contenteditable="true"],textarea'), ed = null, bestBottom = -Infinity;
for (var ei = 0; ei < allEd.length; ei++) { var er = allEd[ei].getBoundingClientRect(); if (er.width > 0 && er.height > 0 && er.bottom > 0 && er.bottom > bestBottom) { ed = allEd[ei]; bestBottom = er.bottom; } }
if (ed) {
var er2 = ed.getBoundingClientRect();
@@ -6984,7 +7638,37 @@ async function sendStashToComposer(record) {
if (Date.now() >= sendDeadline) throw new Error('等待发送按钮可点击超时(5 秒),未发送');
if (!sv || !sv.ok) throw new Error((sv && sv.error) || '未找到发送按钮');
if (record.guard) await record.guard();
+ if (record.beforeSubmit) await record.beforeSubmit();
await cdpMouseClick('automation:sendPhrase', sv.x, sv.y, { textLen: text.length, button: sv });
+ const submittedComposerExpr = `(function(){/* composer-after-submit */
+ try {
+ var editors = document.querySelectorAll('[contenteditable="true"],textarea'), ed = null, bestBottom = -Infinity;
+ for (var i = 0; i < editors.length; i++) {
+ var r = editors[i].getBoundingClientRect();
+ if (r.width > 0 && r.height > 0 && r.bottom > 0 && r.bottom > bestBottom) { ed = editors[i]; bestBottom = r.bottom; }
+ }
+ if (!ed) return { ok: true, hasContent: false };
+ var clone = ed.cloneNode(true);
+ clone.querySelectorAll('[data-slate-placeholder="true"],[data-slate-zero-width]').forEach(function(node){ node.remove(); });
+ var editorText = ed.tagName === 'TEXTAREA' ? ed.value : (clone.innerText || clone.textContent || '');
+ return { ok: true, hasContent: (String(editorText || '').replace(/[\\uFEFF\\u200B\\u00A0]/g, '').trim().length > 0) || !!ed.querySelector('[data-contentblock]') };
+ } catch (e) { return { ok: false, error: String(e) }; }
+ })()`;
+ let submitState = null;
+ for (let attempt = 0; attempt < 20; attempt++) {
+ if (record.guard) await record.guard();
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ try {
+ const response = await guardedSend('Runtime.evaluate', { expression: submittedComposerExpr, returnByValue: true });
+ submitState = response.result && response.result.value;
+ if (submitState && submitState.ok && !submitState.hasContent) break;
+ } catch (error) {
+ if (!/Execution context was destroyed|Cannot find (?:default execution context|context with specified id)/i.test(String(error && error.message || error))) throw error;
+ }
+ }
+ if (!submitState || !submitState.ok || submitState.hasContent) {
+ throw new Error('输入框仍有内容,未确认发送;不会自动重发');
+ }
const result = { sent: true, textLen: text.length, itemCount: allItems.length, imagesRestored, imagesFailed, blocksRestored, blocksFailed };
log('[quick-phrase-diagnostics] composer:finish ' + JSON.stringify({ ok: true, result: { sent: result.sent, textLen: result.textLen, itemCount: result.itemCount } }));
return result;
@@ -7266,8 +7950,8 @@ async function refreshCreditRotationAccounts(currentUid, currentResult) {
const results = await Promise.all(batch.map(async (account) => {
const uid = String(account.uid);
if (uid === currentUid) return { uid, nickname: account.nickname || '', creditSegments: currentResult.segments };
- const raw = JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'));
- const token = raw && raw.auth && (raw.auth.accessToken || raw.auth.access_token || raw.auth.token);
+ const raw = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'))); // [wd-compat]
+ const token = wdCompatAuthToken(raw && raw.auth);
if (!token) throw new Error('账号凭证不可用');
const result = await fetchCredits(token, raw.account || {});
if (!Array.isArray(result.segments) || result.meterError || result.packageError) throw new Error('积分段不可用');
@@ -8048,8 +8732,8 @@ function handleApi(req, res) {
try {
const file = accountBackupFile(uid);
if (!fs.existsSync(file)) return json(res, 404, { ok: false, error: '账号备份不存在' });
- const j = JSON.parse(fs.readFileSync(file, 'utf8'));
- const tk = j.auth && j.auth.accessToken;
+ const j = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(file, 'utf8'))); // [wd-compat]
+ const tk = wdCompatAuthToken(j.auth);
if (!tk) return json(res, 400, { ok: false, error: '备份中无 accessToken' });
const current = currentAccount();
const shouldSyncUsage = !!(current && current.uid === uid);
@@ -8099,8 +8783,8 @@ function handleApi(req, res) {
try {
const file = accountBackupFile(uid);
if (!fs.existsSync(file)) return json(res, 404, { ok: false, error: '账号备份不存在' });
- const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
- const token = raw && raw.auth && (raw.auth.accessToken || raw.auth.access_token || raw.auth.token);
+ const raw = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(file, 'utf8'))); // [wd-compat]
+ const token = wdCompatAuthToken(raw && raw.auth);
if (!token) return json(res, 400, { ok: false, error: '备份中无 accessToken' });
const refreshed = await fetchCredits(token, raw.account || {});
let accounts;
@@ -8244,8 +8928,8 @@ function handleApi(req, res) {
try {
const file = accountBackupFile(uid);
if (!fs.existsSync(file)) return json(res, 404, { ok: false, error: '账号备份不存在' });
- const j = JSON.parse(fs.readFileSync(file, 'utf8'));
- const tk = j.auth && j.auth.accessToken;
+ const j = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(file, 'utf8'))); // [wd-compat]
+ const tk = wdCompatAuthToken(j.auth);
if (!tk) return json(res, 400, { ok: false, error: '备份中无 accessToken' });
const today = await fetchGrowthTodayActive(tk, { apiHost: PROFILE.apiHost });
return json(res, 200, { ok: true, uid, ...today });
@@ -8266,8 +8950,8 @@ function handleApi(req, res) {
try {
const file = accountBackupFile(uid);
if (!fs.existsSync(file)) return json(res, 404, { ok: false, error: '账号备份不存在' });
- const j = JSON.parse(fs.readFileSync(file, 'utf8'));
- const tk = j.auth && j.auth.accessToken;
+ const j = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(file, 'utf8'))); // [wd-compat]
+ const tk = wdCompatAuthToken(j.auth);
if (!tk) return json(res, 400, { ok: false, error: '备份中无 accessToken' });
const before = await fetchGrowthTodayActive(tk, { apiHost: PROFILE.apiHost });
if (before.is_active) return json(res, 200, { ok: true, uid, activated: false, alreadyActive: true, ...before });
@@ -8342,28 +9026,25 @@ function handleApi(req, res) {
ensureDirs(DATA_DIR);
const imported = [];
for (const candidate of candidates) {
- const j = candidate && typeof candidate === 'object' ? candidate : null;
- const acct = j && j.account && typeof j.account === 'object' ? j.account : j;
- const auth = j && j.auth && typeof j.auth === 'object' ? j.auth : null;
- const uid = String(acct && acct.uid || '').trim();
- const accessToken = String(auth && (auth.accessToken || auth.access_token || auth.token) || '').trim();
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid) || !accessToken) continue;
- const normalized = {
- account: { ...acct, uid },
- auth: { ...auth, accessToken },
- };
- const authRecord = parseAuthJson(normalized);
- if (!authRecord || authRecord.uid !== uid) continue;
+ const normalizedImport = normalizeAccountImportJson(candidate);
+ if (!normalizedImport) continue;
+ const { uid, normalized } = normalizedImport;
+ const acct = normalized.account;
const dest = backupPath(DATA_DIR, uid);
const tmp = dest + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(normalized), { mode: 0o600 });
fs.renameSync(tmp, dest);
try { fs.chmodSync(dest, 0o600); } catch (_) {}
- updateMeta(DATA_DIR, { uid, nickname: normalized.account.nickname || '', uin: normalized.account.uin || '', phone: normalized.account.phoneNumber || '' });
+ updateMeta(DATA_DIR, {
+ uid,
+ nickname: wdCompatText(normalized.account.nickname),
+ uin: typeof normalized.account.uin === 'string' || typeof normalized.account.uin === 'number' ? normalized.account.uin : '',
+ phone: wdCompatText(normalized.account.phoneNumber),
+ });
imported.push(uid);
}
if (!imported.length) throw new Error('没有找到符合格式的账号,请先让 WorkBuddy 整理 JSON');
- log(`[import] 明文 JSON 导入 ${imported.length}/${candidates.length} 个账号`);
+ log(`[import] JSON 导入 ${imported.length}/${candidates.length} 个账号`);
return json(res, 200, { ok: true, imported, count: imported.length });
}
if (!envelope || envelope.wbsExport !== 'WorkDaddy') throw new Error('不是 WorkDaddy 的账号导出文件');
@@ -8399,9 +9080,9 @@ function handleApi(req, res) {
try { fs.chmodSync(dest, 0o600); } catch (_) {}
updateMeta(DATA_DIR, {
uid,
- nickname: acct.nickname || '',
- uin: acct.uin || '',
- phone: acct.phoneNumber || '',
+ nickname: wdCompatText(acct.nickname),
+ uin: typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '',
+ phone: wdCompatText(acct.phoneNumber),
});
imported.push(uid);
}
@@ -8887,6 +9568,40 @@ function handleApi(req, res) {
}
});
}
+ // Renderer lifecycle feed for incremental auto-copy planning. The payload is
+ // deliberately limited to session ids and event names; message contents
+ // never leave WorkBuddy and the local API token remains the only auth gate.
+ if (req.method === 'POST' && p === '/api/sessions/dirty') {
+ return readBody(req).then((body) => {
+ try {
+ const currentUid = String((currentAccount() || {}).uid || '').trim();
+ const claimedUid = String(body && body.uid || '').trim();
+ // A renderer can flush a debounced dirty batch while an account switch
+ // is replacing its auth file. Never let that old page mark the newly
+ // active account (or keep the old account dirty) after the switch.
+ if (currentUid && claimedUid && claimedUid !== currentUid) {
+ return json(res, 409, { ok: false, error: '账号已切换,忽略旧会话通知' });
+ }
+ const uid = currentUid ||
+ (/^[A-Za-z0-9_-]{1,128}$/.test(claimedUid) && fs.existsSync(accountBackupFile(claimedUid)) ? claimedUid : '');
+ if (!uid) return json(res, 409, { ok: false, error: '当前账号不可用' });
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return json(res, 400, { ok: false, error: '脏会话通知格式无效' });
+ if (body.ready === true) markSessionDirtyBaseline(uid);
+ const events = Array.isArray(body.events) ? body.events : [];
+ if (events.length > 500) return json(res, 400, { ok: false, error: '脏会话通知过多' });
+ let marked = 0;
+ for (const event of events) {
+ const id = String(event && event.id || '').trim();
+ if (!isValidSessionId(id)) continue;
+ markSessionDirty(uid, id, String(event.event || 'sessionUpdated'));
+ marked++;
+ }
+ return json(res, 200, { ok: true, marked, initialized: getSessionDirtyIndex().isInitialized(uid) });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
// 自动复制任务状态:GET /api/sessions/auto-copy/status?id=<jobId>
if (req.method === 'GET' && p === '/api/sessions/auto-copy/status') {
const job = autoCopyJobs.get(url.searchParams.get('id') || '');
@@ -8899,7 +9614,8 @@ function handleApi(req, res) {
}
// 当前任务或刚完成的任务:renderer 重载后仍可恢复复制进度。
if (req.method === 'GET' && p === '/api/sessions/auto-copy/active') {
- return json(res, 200, { ok: true, job: publicAutoCopyJob(activeAutoCopyJob()) });
+ const currentUid = String((currentAccount() || {}).uid || '').trim();
+ return json(res, 200, { ok: true, job: publicAutoCopyJob(activeAutoCopyJob(currentUid)) });
}
// Stream the completed encrypted archive; clean up even if the download disconnects.
if (req.method === 'POST' && p === '/api/sessions/export') {
@@ -9054,7 +9770,7 @@ function handleApi(req, res) {
if (req.method === 'POST' && p === '/api/sessions/delete') {
return readBody(req).then(async (body) => {
let ids;
- try { ids = normalizeSessionIdBatch(body && body.ids); }
+ try { ids = normalizeSessionIdBatch(body && body.ids, { maxBatch: null }); }
catch (e) { return json(res, 400, { ok: false, error: e.message }); }
if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });
if (!ids.every(isValidSessionId)) return json(res, 400, { ok: false, error: '包含无效的会话 ID' });
@@ -9622,54 +10338,43 @@ function handleApi(req, res) {
releaseAccountSwitch = await assertAccountSwitchIdle();
const sourceAccount = currentAccount() || {};
const sourceUid = String(sourceAccount.uid || '').trim();
+ let currentConversationId = isValidSessionId(String(body.currentConversationId || '').trim())
+ ? String(body.currentConversationId).trim() : '';
+ // Renderer projection state can briefly retain the destination id from
+ // the previous rotation. Never carry an id into the next account unless
+ // the session index proves it belongs to the account being replaced.
+ if (currentConversationId && sourceUid) {
+ const ownerRows = await sqliteQuery(
+ 'SELECT user_id FROM sessions WHERE id = ? AND deleted_at IS NULL LIMIT 1;',
+ [currentConversationId]
+ );
+ if (!ownerRows.length || String(ownerRows[0].user_id || '') !== sourceUid) {
+ log(`[switch] 丢弃不属于源账号的当前会话 source=${sourceUid} session=${currentConversationId}`);
+ currentConversationId = '';
+ }
+ }
const acct = switchTo(DATA_DIR, uid, log);
const hint = '登录文件已切换,请重启 WorkBuddy 使新账号生效';
let reloaded = false;
if (body.reload) {
- // 读取切换前当前会话标题:官方会话列表的选中行(.conversation-item 带 selected);
-// 刷新后用于在目标账号里自动打开对应的复制会话。读不到则跳过自动聚焦。
- let sourceSessionTitle = '';
- try {
- if (cdp.connected) {
- const titleExpr =
- '(function(){' +
- 'var list = document.querySelector(".conversation-list");' +
- 'if (!list) return "";' +
- 'var rows = list.querySelectorAll(".conversation-item");' +
- 'for (var i = 0; i < rows.length; i++) {' +
- ' var r = rows[i];' +
- ' if ((r.className || "").indexOf("selected") === -1) continue;' +
- ' var best = "";' +
- ' var els = r.querySelectorAll("*");' +
- ' for (var j = 0; j < els.length; j++) {' +
- ' var el = els[j];' +
- ' if (el.children.length === 0) {' +
- ' var t = (el.textContent || "").trim();' +
- ' if (t.length > best.length) best = t;' +
- ' }' +
- ' }' +
- ' if (best) return best;' +
- '}' +
- 'return "";' +
- '})()';
- const t = await cdpSend('Runtime.evaluate', { expression: titleExpr, returnByValue: true });
- sourceSessionTitle = String((t && t.result && t.result.value) || '').trim();
- }
- } catch (_) { /* 读不到就跳过自动聚焦会话 */ }
try {
pendingAutomationAccountSwitch = { account: { uid: acct.uid, nickname: acct.nickname } };
- await reloadWorkBuddyPage();
+ // The user-facing switch must not wait for the injected panel's
+ // readiness promise (which can take the full 5s timeout on a slow
+ // renderer). The pending injection remains in place and the copy
+ // worker will yield on it before touching session files.
+ await reloadWorkBuddyPage({ waitForInjection: false });
reloaded = true;
log('[switch] 已通过 CDP 刷新 WorkBuddy 窗口');
- // 某些 renderer 不发送 Page.loadEventFired;刷新流程已返回且新页面已挂载时兜底。
- if (pendingAutomationAccountSwitch) {
+ // 某些 renderer 不发送 Page.loadEventFired;给正常 load 事件
+ // 留出时间后再兜底派发,避免在空白页面上启动自动化任务。
+ const fallbackNavigationSerial = mainFrameNavigationSerial;
+ setTimeout(() => {
+ if (!pendingAutomationAccountSwitch) return;
const switchEvent = pendingAutomationAccountSwitch;
pendingAutomationAccountSwitch = null;
- dispatchAutomationEvent('pageReady', { navigationSerial: mainFrameNavigationSerial, source: 'account-switch-fallback', account: switchEvent.account });
- }
- if (sourceSessionTitle) {
- autoFocusSessionByTitle(sourceSessionTitle, log);
- }
+ dispatchAutomationEvent('pageReady', { navigationSerial: fallbackNavigationSerial, source: 'account-switch-fallback', account: switchEvent.account });
+ }, 1500);
} catch (e) {
pendingAutomationAccountSwitch = null;
log(`[switch] CDP 刷新失败: ${e.message}`);
@@ -9679,10 +10384,11 @@ function handleApi(req, res) {
// 任务规则通常能直接命中,所以旧逻辑只表现为“任务能复制、空间不复制”。
const sourceRules = sourceUid ? getAutoCopyRules(DATA_DIR, sourceUid) : { allSessions: false, sessionIds: [], workspaces: [] };
const hasSourceAutoCopyRules = !!(sourceRules.allSessions || sourceRules.sessionIds.length || sourceRules.workspaces.length);
- const autoCopyJob = (hasSourceAutoCopyRules || hasPendingAutoCopyTo(sourceUid))
+ const autoCopyJob = (hasSourceAutoCopyRules || hasPendingAutoCopyTo(sourceUid) || currentConversationId)
? startAutoCopyJob(sourceUid, uid, [], {
sourceName: sourceAccount.nickname || '',
targetName: acct.nickname || '',
+ openSessionId: currentConversationId,
})
: null;
return json(res, 200, {
@@ -9690,7 +10396,7 @@ function handleApi(req, res) {
uid: acct.uid,
nickname: acct.nickname,
reloaded,
- autoCopy: autoCopyJob ? { jobId: autoCopyJob.id, total: autoCopyJob.total } : { total: 0 },
+ autoCopy: autoCopyJob ? { jobId: autoCopyJob.id, total: autoCopyJob.total, openSessionId: autoCopyJob.openSessionId || '' } : { total: 0 },
hint: reloaded ? '已切换并触发窗口刷新' : hint,
});
} catch (e) {
@@ -10015,6 +10721,9 @@ for (const preset of ['close-buddy-popups.json', ...(PROFILE.capabilities.accoun
restoreSleepMode();
startServer();
cdpLoop();
+// Migrate legacy target row baselines off the switch hot path. This is a
+// metadata-only repair and does not read any session payload files.
+setTimeout(() => { migrateAutoCopyTargetRevisionBaselines().catch(() => {}); }, 0);
// All automatic check-in entry points are owned by the visible automation task.
const tickAutomationSchedules = createScheduleTicker(DATA_DIR);
function runAutomationSchedules() {
diff --git a/scripts/inject.js b/scripts/inject.js
index 3d1fbe3..f949a70 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -190,7 +190,10 @@ function createFabAppearance(options) {
var saved = options.storage.getItem(options.key);
if (styles.indexOf(saved) >= 0) current = saved;
} catch (_) {}
- function apply() { options.fab.setAttribute('data-wbs-robot-style', current); }
+ function apply() {
+ options.fab.setAttribute('data-wbs-robot-style', current);
+ if (options.root) options.root.setAttribute('data-wbs-robot-style', current);
+ }
apply();
return {
get: function () { return current; },
@@ -346,6 +349,25 @@ function autoContinueControllerCompleted(snapshot) {
return s.terminalKnown ? !!s.terminal : !!s.complete;
}
+// Controller/store 快照 → 判定证据的唯一映射。原来的映射写在 acControllerCheck 内联对象里,
+// 只有「已经进入判定」的会话才会用到它;绑定闸门要判断「这个空闲会话该不该进判定」时,
+// 若另写一套更窄的规则(例如只认 error),两条规则就会错位:判定层愿意续跑的会话被闸门
+// 挡在门外,功能对这类会话彻底失效。判定与绑定必须共用同一份映射。
+function controllerAutoContinueDecision(snapshot) {
+ var s = snapshot || {};
+ return classifyAutoContinueControllerSnapshot({
+ assistantId: s.assistantId,
+ busy: s.busy,
+ manualStop: s.manualStop,
+ error: s.error,
+ networkFailure: s.networkFailure,
+ completionMarker: s.completionMarker,
+ // 新版明确暴露 isRequestTerminal 时只认该字段;旧版没有该字段才退回 complete。
+ complete: s.terminalKnown ? false : s.complete,
+ terminal: s.terminal,
+ });
+}
+
function selectAutoContinueAssistant(messageState) {
var state = messageState || {};
var messages = Array.isArray(state.messages) ? state.messages : [];
@@ -574,6 +596,20 @@ function isSessionMonitorInProgress(snapshot) {
return !!(snapshot && (snapshot.busy || snapshot.blocked || snapshot.hydrating));
}
+// isSessionMonitorInProgress 判「还在跑」,本函数判「已经停下、但判定层会续跑」。
+// 两者合起来才是完整的绑定闸门:只按 in-progress 过滤时,已中断的会话在绑定阶段就被
+// 当成历史会话丢掉(acMultiCreateSession 返回 null / acBindController 重建 baseline),
+// 判定层一次都看不到它。它又不会再产生新回复,于是「等新回复」的 baseline 门控是一条
+// 死等待——用户关掉再打开开关同样无效,因为重开只是在同一条卡住的回复上重建 baseline。
+// 这里不自己判断「算不算中断」,直接复用判定层的结论,保证「允许绑定的会话」与
+// 「会被续跑的会话」永远一致:判定层不续跑的历史回复(已完成 / 带完成标记 / 主动取消)
+// 同样不会绑定。
+function isSessionMonitorInterrupted(snapshot) {
+ var s = snapshot || {};
+ if (!s || s.busy || s.blocked || s.hydrating) return false; // 运行/等决策/恢复中:交给 in-progress 分支
+ return controllerAutoContinueDecision(s).trigger === true;
+}
+
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,
@@ -629,6 +665,15 @@ function normalizeSessionMonitorResourceRecord(record, eventName) {
title: String(value.name || value.title || '').slice(0, 120),
status: status,
pendingInputKind: pendingInputKind,
+ protocolStatus: normalizeSessionMonitorStatus(value.protocolStatus),
+ state: normalizeSessionMonitorStatus(value.state),
+ activePromptStartedAt: promptActive ? Number(value.activePromptStartedAt) : 0,
+ queueRevision: queueRuntime ? [
+ String(queueRuntime.inflightItemId || ''), Number(queueRuntime.pendingItemCount || 0),
+ Number(queueRuntime.sendingItemCount || 0), queueRuntime.paused === true,
+ ] : null,
+ updatedAt: Number(value.updatedAt || value.updated_at || 0) || 0,
+ lastActivityAt: Number(value.lastActivityAt || value.last_activity_at || 0) || 0,
active: active,
terminal: !!terminalStatus,
event: String(eventName || 'sessionUpdated'),
@@ -666,6 +711,72 @@ function subscribeSessionMonitorResource(resource, listener) {
};
}
+// Keep a renderer-local baseline so a broad sessionsChanged snapshot only
+// marks records whose observable state actually changed. The daemon receives
+// ids and event names, never message text or session contents.
+function createSessionDirtyTracker(send, options) {
+ var opts = options || {};
+ var seen = Object.create(null);
+ var pending = Object.create(null);
+ var timer = null;
+ var delay = Math.max(0, Number(opts.delay == null ? 120 : opts.delay));
+ function signature(update) {
+ var value = update && typeof update === 'object' ? update : {};
+ // Account reloads emit status/state/active/terminal churn for every row.
+ // Those fields describe the renderer lifecycle, not session content. Keep
+ // only the persisted metadata revisions that can represent an edit; the
+ // daemon still uses its row-revision fallback when a content event is
+ // missed.
+ return JSON.stringify([
+ String(value.id || ''), String(value.title || ''), String(value.customTitle || ''),
+ // Opening/activating a copied conversation updates lastActivityAt on
+ // some WorkBuddy builds. That is renderer lifecycle churn, not a
+ // message edit; updatedAt remains the content-side revision fallback.
+ Number(value.updatedAt || 0),
+ ]);
+ }
+ function flush() {
+ timer = null;
+ var batch = Object.keys(pending).map(function (id) { return pending[id]; });
+ pending = Object.create(null);
+ if (batch.length && typeof send === 'function') send(batch);
+ }
+ function queue(update) {
+ var id = String(update && update.id || '').trim();
+ if (!id) return false;
+ pending[id] = { id: id, event: String(update.event || 'sessionUpdated').slice(0, 40) };
+ if (timer == null) timer = setTimeout(flush, delay);
+ return true;
+ }
+ function observe(update) {
+ var id = String(update && update.id || '').trim();
+ if (!id) return false;
+ var next = signature(update);
+ if (seen[id] === undefined) {
+ seen[id] = next;
+ return String(update.event || '') === 'sessionCreated' ? queue(update) : false;
+ }
+ if (seen[id] === next) return false;
+ seen[id] = next;
+ return queue(update);
+ }
+ function baseline(records) {
+ var list = Array.isArray(records) ? records : [];
+ for (var i = 0; i < list.length; i++) {
+ var id = String(list[i] && (list[i].id || list[i].sessionId || '') || '').trim();
+ if (id) seen[id] = signature(list[i]);
+ }
+ if (typeof send === 'function') send({ ready: true });
+ }
+ function destroy() {
+ if (timer != null) clearTimeout(timer);
+ timer = null;
+ pending = Object.create(null);
+ seen = Object.create(null);
+ }
+ return { observe: observe, baseline: baseline, flush: flush, destroy: destroy };
+}
+
// 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.
@@ -735,6 +846,18 @@ function createSessionMonitorRegistry(options) {
return { ensure: ensure, update: update, append: append, remove: remove, clear: clear, list: list, get: function (id) { return sessions[String(id || '')] || null; } };
}
+function findLatestManualAutomationRun(tasks, runs) {
+ var taskById = Object.create(null);
+ (Array.isArray(tasks) ? tasks : []).forEach(function (task) {
+ if (task && task.id) taskById[task.id] = task;
+ });
+ return (Array.isArray(runs) ? runs : []).filter(function (run) {
+ return run && run.status === 'running' && taskById[run.taskId] && taskById[run.taskId].manualRunnable === true;
+ }).sort(function (a, b) {
+ return Number(b.startedAt || 0) - Number(a.startedAt || 0);
+ })[0] || null;
+}
+
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
collectConversationUsage: collectConversationUsage,
@@ -747,6 +870,7 @@ if (typeof module !== 'undefined' && module.exports) {
classifyAutoContinueControllerSnapshot: classifyAutoContinueControllerSnapshot,
autoContinueMessageText: autoContinueMessageText,
autoContinueControllerCompleted: autoContinueControllerCompleted,
+ controllerAutoContinueDecision: controllerAutoContinueDecision,
selectAutoContinueAssistant: selectAutoContinueAssistant,
composerBlocksFromTree: composerBlocksFromTree,
composerTextFromTree: composerTextFromTree,
@@ -761,10 +885,13 @@ if (typeof module !== 'undefined' && module.exports) {
ndConfirmHints: ND_CONFIRM_HINTS,
ndDenyHints: ND_DENY_HINTS,
isSessionMonitorInProgress: isSessionMonitorInProgress,
+ isSessionMonitorInterrupted: isSessionMonitorInterrupted,
normalizeSessionMonitorResourceRecord: normalizeSessionMonitorResourceRecord,
sessionMonitorLifecycleAction: sessionMonitorLifecycleAction,
subscribeSessionMonitorResource: subscribeSessionMonitorResource,
+ createSessionDirtyTracker: createSessionDirtyTracker,
createSessionMonitorRegistry: createSessionMonitorRegistry,
+ findLatestManualAutomationRun: findLatestManualAutomationRun,
};
}
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
@@ -776,7 +903,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var n;
if ((n = document.querySelector('.wbs-root'))) n.remove();
if ((n = document.getElementById('wbs-window-logo'))) n.remove();
- var st = document.querySelectorAll('.wbs-stash-inline, .wbs-stash-btn, .wbs-explore-inline, .wbs-selection-quote-btn, .wbs-fork-button');
+ var st = document.querySelectorAll('.wbs-stash-inline, .wbs-stash-btn, .wbs-explore-inline, .wbs-fork-button');
for (var i = 0; i < st.length; i++) st[i].remove();
var nav = document.querySelectorAll('.wbs-message-nav-root');
for (var ni = 0; ni < nav.length; ni++) nav[ni].remove();
@@ -824,8 +951,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// panes and toasts follow the same language without touching WorkBuddy's DOM.
var WBS_LANGUAGE_KEY = 'workdaddy.ui.language';
var WBS_ACCOUNT_MASK_KEY = 'workdaddy.account.mask.' + PROFILE_ID;
+ var WBS_INITIAL_AUTO_COPY_ALL_KEY = 'workdaddy.initial.autoCopyAllSessions.' + PROFILE_ID;
var WBS_I18N_EN = {
'总大小': 'Total size',
+ '初始化设置': 'Initial setup',
+ '切换账号自动同步所有会话': 'Automatically sync all sessions when switching accounts',
+ '开启后,切换账号时会自动同步当前账号的全部会话,包括之后新增的会话。': 'When enabled, switching accounts automatically syncs all sessions for the current account, including new sessions added later.',
+ '选择切换账号时是否自动同步会话。此设置之后也可以在「会话」页面修改。': 'Choose whether to sync sessions automatically when switching accounts. You can change this later on the “Sessions” page.',
+ '保存失败,请重试': 'Save failed, please try again',
'所选账号全部会话的大小,不受时间和大小筛选影响': 'Total size of all sessions for the selected account, regardless of time and size filters',
'会话大小(消息和附件)': 'Session size (messages and attachments)',
'筛选会话大小': 'Filter session size',
@@ -845,6 +978,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'会话文件包含符号链接,未同步': 'Session files contain a symbolic link. Sync was skipped',
'无效的会话标识': 'Invalid session identifier',
'会话目录包含符号链接,未同步': 'The session directory is a symbolic link. Sync was skipped',
+ '会话目录无法读取': 'Cannot read the session directory',
'会话文件无法读取': 'Cannot read session files',
'会话文件类型不受支持': 'Unsupported session file type',
'会话超过 100 MB,同步可能较慢': 'Session exceeds 100 MB; syncing may take longer',
@@ -861,6 +995,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'目标会话正在变化,已停止同步': 'The target session is changing. Sync was stopped',
'源会话正在变化,已停止同步': 'The source session is changing. Sync was stopped',
'会话文件校验失败': 'Session file verification failed',
+ '收起': 'Collapse',
+ '输入框仍有内容,未确认发送;不会自动重发': 'The composer still contains text, so sending was not confirmed. It will not be retried automatically',
'派猫猫旅行': 'Send Buddy traveling',
'自动选择已拥有的 Buddy,派出旅行并领取旅行礼物。未领养 Buddy 的账号需先在官网同意协议并解锁,此任务会跳过。需要 WorkDaddy 1.2.66 或更新版本。': 'Select an owned Buddy, send it traveling, and claim travel gifts. Accounts without an adopted Buddy are skipped until the agreement is accepted and Buddy is unlocked on the official site. Requires WorkDaddy 1.2.66 or later.',
'账号 {account}:开始检查猫猫旅行': 'Account {account}: Checking Buddy travel', '当前 Buddy 查询失败': 'Could not load current Buddy', 'Buddy 列表查询失败': 'Could not load Buddy list',
@@ -876,7 +1012,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'查询已中断,请重新选择时间重试': 'Query interrupted. Select a time range to retry.',
'无法读取查询进度,请重新选择时间重试': 'Could not read progress. Select a time range to retry.',
'趋势分组': 'Trend grouping', '筛选折线': 'Filter lines', '统计时间': 'Statistics period',
- '总览': 'Overview', '按账号': 'By account', '按模型': 'By model', '总量': 'Total',
+ '总览': 'Overview', '按账号': 'By account', '按模型': 'By model', '总量': 'Total', '模型用量': 'Model usage',
'未识别模型': 'Unknown model', '未关联账号': 'Unassigned account', '暂无分组数据': 'No breakdown data',
'解锁后未读取到最新状态': 'Could not load the latest status after unlocking',
'Buddy 已解锁': 'Buddy unlocked', 'Buddy 解锁成功': 'Buddy unlocked', '解锁 Buddy 失败': 'Could not unlock Buddy',
@@ -968,6 +1104,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'无法打开官方成长中心': 'Could not open the official growth center', '请先切换到该账号再操作': 'Switch to this account first', '无法确认当前登录账号': 'Could not verify the current account', '去官网接取': 'Open official site to accept', '去官网开启': 'Open official site to open', '去官网抽奖': 'Open official site to draw', '去官网解锁 Buddy': 'Open official site to unlock Buddy', '去官网领取': 'Open official site to claim', '去官网派出': 'Open official site to depart', '去官网选择 Buddy': 'Open official site to choose Buddy',
'正在刷新成长计划与 Buddy 旅行状态…': 'Refreshing the growth plan and Buddy travel status…', '刷新失败,移开后再次悬浮即可重试': 'Refresh failed. Move away and hover again to retry.', '本次刷新失败,当前展示上次结果': 'Refresh failed. Showing the previous result.',
' 待领取': ' pending', 'Buddy 旅行': 'Buddy travel', '开启盲盒': 'Open blind box', '待抽奖': 'Draw chances', '未派出': 'Not departed', '刷新于 ': 'Refreshed at ', '尚未刷新': 'Not refreshed', '连续登录 ': 'Current streak ', '连续登录读取中': 'Loading streak', '连续登录读取失败': 'Streak unavailable', '补登卡': 'Makeup cards', ' 张': '', '入门档': 'Starter', '进阶档': 'Advanced', '巅峰档': 'Peak', '还差 ': '', ' 天': ' days remaining', '可领取': 'Available', '每日积分趋势': 'Daily Credits trend', '每日 Token 趋势': 'Daily Token trend',
+ '停止运行': 'Stop running',
'账号': 'Accounts', '主题': 'Theme', '会话': 'Sessions', '模型': 'Models', '增强': 'Enhance', '自动化': 'Automation', '电脑': 'Computer', '关于': 'About', '设置': 'Settings',
'导出': 'Export', '导入': 'Import', '删除': 'Delete', '编辑': 'Edit', '保存': 'Save', '内置': 'Built-in', '取消': 'Cancel', '确定': 'Confirm', '确认': 'Confirm', '复制': 'Copy', '切换': 'Switch', '启用': 'Enable', '停用': 'Disable', '停止': 'Stop', '立即运行': 'Run now', '新建任务': 'New task', '刷新': 'Refresh', '步骤 JSON': 'Steps JSON', '任务说明': 'Task description', '任务名称': 'Task name', '调度': 'Schedule', '手动运行': 'Manual', '手动': 'Manual', '每小时': 'Hourly', '每天': 'Daily', '选择任务': 'Select tasks', '查看接口': 'View capabilities', '拾取元素': 'Pick element', '复制 XPath': 'Copy XPath', '运行中': 'Running', '已成功': 'Succeeded', '失败': 'Failed', '未运行': 'Not run', '页面加载完成': 'Page loaded', '账号切换完成': 'Account switched', '新自动化任务': 'New automation task', '任务已保存': 'Task saved', '任务已开始运行': 'Task started', '步骤 JSON 格式无效': 'Invalid steps JSON', '步骤 JSON 必须是数组': 'Steps JSON must be an array', '查看接口说明': 'View interface docs', '自动化接口协议': 'Automation interface protocol', '复制全部': 'Copy all', '接口协议已复制': 'Interface protocol copied', '暂无自动化任务': 'No automations yet', '编辑任务': 'Edit task', '触发方式': 'Trigger', '插入点击步骤': 'Insert click step', 'XPath 已复制': 'XPath copied', '点击步骤已插入': 'Click step inserted', '请先拾取元素': 'Pick an element first', '加载自动化失败': 'Failed to load automations', '读取接口失败': 'Failed to read interfaces', '批量操作失败': 'Batch operation failed', '删除失败': 'Delete failed', '确认删除该任务?': 'Delete this task?', '执行': 'Apply', '已拾取': 'Picked', '运行失败': 'Run failed', '(副本)': ' (copy)', '查看提示词': 'View prompt', '交给 WorkBuddy 创建': 'Ask WorkBuddy to create', '正在打开新任务…': 'Opening a new task…', '已创建新会话,WorkBuddy 完成后任务会自动出现': 'New session created. The task will appear after WorkBuddy finishes.', 'WorkBuddy 创建失败': 'WorkBuddy creation failed', '加载示例失败': 'Failed to load examples', '暂无示例': 'No examples available', '运行日志': 'Run logs', '暂无运行日志': 'No run logs yet', '开始时间': 'Started', '结束时间': 'Finished', '捕获错误': 'Caught error', '暂无执行日志': 'No execution log entries', '执行日志': 'Execution log', '尚未结束': 'Still running',
'暂存提示词': 'Stash prompt', '暂存': 'Stashed', '引用文本': 'Quote text', '快捷短语': 'Quick phrases', '点击后发送': 'Send on click', '编辑 →': 'Edit →', '新增': 'Add', '批量操作': 'Batch actions', '批量管理': 'Batch manage', '全选': 'Select all', '取消全选': 'Deselect all', '已选 0': 'Selected 0',
@@ -1026,6 +1163,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'已复制 ': 'Copied ', ' · 平均复制速率 ': ' · Average copy speed ', '按实际复制成功的数据量除以同步耗时计算,包含校验和备份时间': 'Copied data divided by sync duration, including verification and backups',
'同步数据量和速率': 'Sync data and speed',
'同步数据量': 'Sync data',
+ '已检查': 'Checked', '实际写入': 'Written',
'会话同步完成': 'Session sync complete', '会话同步完成,已保留分叉': 'Session sync complete with conflicts', '会话同步完成,部分项目失败': 'Session sync complete with some failures', '会话同步等待中': 'Session sync waiting', '正在同步会话': 'Syncing session', '会话同步失败': 'Session sync failed', '同步等待中': 'Sync waiting', '同步失败': 'Sync failed', '同步': 'Sync', '已同步': 'Synced', ' · 新同步': ' · Newly synced ', ' · 有': ' · ', ' 项需要留意': ' item(s) need attention', ' · 请稍后重试': ' · Try again later', '会话同步进度': 'Session sync progress', ' 个会话已分叉,已保留双方内容': ' session(s) were changed on both sides; neither side was overwritten', '其他账号': 'Other account', '同步完成': 'Sync complete', '同步完成,已保留分叉': 'Sync complete with conflicts', '同步完成,部分失败': 'Sync complete with some failures', '正在把已标记的会话同步到「': 'Syncing marked sessions to “', ' 个未变化会话': ' unchanged session(s)', '同步任务未完成,请稍后重试': 'Sync did not finish. Try again later',
' · 跳过': ' · Skipped', ' · 分叉': ' · Conflicts', '成功': 'Succeeded', '跳过': 'Skipped', '已跳过': 'Skipped', '部分失败': 'Partial failure', '分叉': 'Conflict', '处理中': 'Processing', '会话已分叉,已保留双方内容': 'Changed on both sides; neither side was overwritten', '部分文件失败': 'Some files failed', '当前任务未记录逐项明细。': 'No per-session details were recorded for this task.', '会话同步明细': 'Session sync details', '会话同步结果筛选': 'Filter session sync results', '当前分类没有会话。': 'No sessions in this category.', '正在把已标记的会话从「': 'Syncing marked sessions from “', '」同步到「': '” to “', '查看明细': 'View details', ' 个候选会话': ' candidate session(s)', ' 秒后自动关闭': ' seconds until automatic close',
'收录 GitHub 和 Gitee 公开仓库。参考 ': 'Public GitHub and Gitee repositories are indexed. See ', '。': '.', '克隆示例仓库:': 'Clone the example repository: ', '删除 ': 'Delete ', ' 目录中不需要的示例任务。': ' directory tasks you do not need.', '把你的自动化任务 JSON 放进 ': 'Put your automation task JSON in ', ' 目录。': ' directory.', '提交改动并推送到 GitHub 或 Gitee。': 'Commit and push changes to GitHub or Gitee.', '在仓库简介中加入关键词 ': 'Add the keyword ',
@@ -1046,7 +1184,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'打开面板失败:': 'Could not open panel:', '无法连接本地服务:': 'Cannot connect to local service:', '退出失败:': 'Could not log out:', '登录失败,请关闭后重试': 'Login failed, please close and retry', '登录方式': 'Login method', '请求超时': 'Request timed out', '超时': 'Timeout',
'开启「弹窗自动点允许」?': 'Enable “auto-allow dialogs”?', '开启「系统级工具放行」?': 'Enable “system-wide tool allow”?', '开启后,AI 可直接读写工作区外的任意文件,不再逐次询问。': 'When enabled, the AI can read and write any file outside the workspace without asking each time.', '风险:误改文件时不会提醒。': 'Risk: accidental edits will not trigger warnings.', '开启后 npm、git、curl、python3 等常用命令直接本地执行,不再先进沙箱': 'When enabled, common commands like npm, git, curl, and python3 run directly without the sandbox first', '开启后仅阻止系统睡眠,显示器可黑屏省电': 'When enabled, only system sleep is blocked; the display can still turn off to save power', '开启,移入回收站': 'Enable and move to Trash', '关闭(指令块已移除)': 'Off (custom prompt block removed)', '开启(指令块已写入 app-config.customPrompt)': 'On (custom prompt block written to app-config.customPrompt)', '允许完全访问': 'Allow full access', '环境变量': 'Environment variable', '命令行参数': 'Command-line arguments', '隐藏工具已呼出': 'Hidden tools revealed',
'这会把该备份覆盖到官方 models.json 中,同 id 的旧配置将被移除。': 'This overwrites the official models.json with this backup; old configs with the same id are removed.', '输入框非空,已放弃自动发送,避免覆盖你的输入': 'Composer is not empty; automatic send was skipped to avoid overwriting your input', '输入框占用': 'Composer in use', '接口返回 HTTP': 'API returned HTTP', '发送经过脱敏的错误诊断': 'Send redacted error diagnostics',
- '登录请求不存在或已过期': 'Login request does not exist or has expired', '登录超时,请重新发起': 'Login timed out, please retry', '未找到该短语': 'Quick phrase not found', '缺少 uid': 'Missing uid', 'uid 格式无效': 'Invalid uid format', '缺少 key': 'Missing key', '非法 key:': 'Invalid key:', '备份中无 accessToken': 'No accessToken in the backup', '缺少企业 ID': 'Missing enterprise ID', '账号备份不存在': 'Account backup not found',
+ '登录请求不存在或已过期': 'Login request does not exist or has expired', '登录超时,请重新发起': 'Login timed out, please retry', '未找到该短语': 'Quick phrase not found', '缺少 uid': 'Missing uid', 'uid 格式无效': 'Invalid uid format', '缺少 key': 'Missing key', '非法 key:': 'Invalid key:', '备份中无 accessToken': 'No accessToken in the backup', '缺少企业 ID': 'Missing enterprise ID', '账号备份不存在': 'Account backup not found', '(已加密)': '(encrypted)', '取钥暂不可用': 'Decryption key temporarily unavailable', '未找到 WorkBuddy 可执行文件': 'WorkBuddy executable not found',
'CDP 未连接': 'CDP not connected', 'CDP 未连接,无法注入组件': 'CDP not connected; injection skipped', 'CDP 未连接,无法自动刷新窗口': 'CDP not connected; window refresh skipped', 'CDP 未连接,无法发送': 'CDP not connected; cannot send',
',显示器保持唤醒': ', display stays awake', ',显示器保持唤醒,防锁屏开启': ', display stays awake, screen lock blocked', ',显示器可单独休眠': ', display may sleep on its own', ',已防锁屏': ', screen lock blocked', ',更新完成': ', update complete', ',跳过': ', skipped',
'(阶段:': ' (stage: ', ';安装日志:': '; install log: ', ';尝试 ID:': '; attempt ID: ', ';诊断日志:': '; diagnostics log: ',
@@ -1168,7 +1306,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'未找到该账号已记录的登录文件名,拒绝猜测写入目标': 'No recorded login filename for this account; refusing to guess a write target',
'「': '“', '」': '”',
// —— 第七批:头像/主题/安装器/休眠等散落整句 ——
- '上传图片替换左下角头像': 'Upload an image to replace the bottom-left avatar', '恢复 WorkBuddy 官方头像': 'Restore the official WorkBuddy avatar',
+ '上传图片替换左下角头像': 'Upload an image to replace the bottom-left avatar', '恢复 WorkBuddy 官方头像': 'Restore the official WorkBuddy avatar', '保留 WorkBuddy 默认头像': 'Keep the WorkBuddy default avatar',
'复制选中快捷短语': 'Copy selected quick phrases',
'开启后 WorkBuddy 需要你决策时会用弹窗提问(写入全局自定义指令,所有会话生效)': 'When enabled, WorkBuddy asks with a dialog when your decision is needed (written to the global custom prompt; affects all sessions)',
'当前没有进行中的会话,无法开启「所有会话结束允许休眠」': 'No active sessions; cannot enable “Allow sleep when all sessions end”',
@@ -1533,6 +1671,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m4 16-.8 4.8L8 20l11.5-11.5a2.1 2.1 0 0 0-3-3L5 17z"/><path d="m14.5 7.5 2 2"/></svg>';
var MODEL_ENABLE_SVG =
'<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor"><path d="M8 5.2a1 1 0 0 1 1.55-.83l9.6 6.8a1 1 0 0 1 0 1.66l-9.6 6.8A1 1 0 0 1 8 18.8V5.2Z"/></svg>';
+ var AUTO_TAB_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 8V4H9"/><rect x="4" y="8" width="16" height="12" rx="3"/><path d="M2 12v4M22 12v4M9 12v2M15 12v2M9 17h6"/></svg>';
var AUTO_STOP_SVG =
'<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="1.5"/></svg>';
// 停止中:loading 转圈(弧线 + 缺口,配合 .wbs-auto-stopping 的旋转动画)
@@ -1689,7 +1829,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!item || typeof item.id !== 'string' || !/^custom-[a-z0-9-]+$/.test(item.id) || ids.has(item.id) || !validImage(item.src)) return false;
ids.add(item.id); return true;
}).map(function (item) { return { id: item.id, src: item.src }; });
- if (saved.selected === 'workbuddy' || saved.selected === 'workdaddy' || ids.has(saved.selected)) state.selected = saved.selected;
+ if (saved.selected === 'default' || saved.selected === 'workbuddy' || saved.selected === 'workdaddy' || ids.has(saved.selected)) state.selected = saved.selected;
} else {
var legacy = storage.getItem('wbsAvatar');
if (validImage(legacy)) { state.items = [{ id: 'custom-legacy', src: legacy }]; state.selected = 'custom-legacy'; }
@@ -1705,7 +1845,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return {
snapshot: snapshot,
select: function (id) {
- if (id !== 'workbuddy' && id !== 'workdaddy' && !state.items.some(function (item) { return item.id === id; })) return;
+ if (id !== 'default' && id !== 'workbuddy' && id !== 'workdaddy' && !state.items.some(function (item) { return item.id === id; })) return;
var next = snapshot(); next.selected = id; commit(next);
},
add: function (src) {
@@ -1723,7 +1863,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
};
}
- function resolveAvatarChoice(saved, official, brand) {
+ function resolveAvatarChoice(saved, official, brand, defaultAvatar) {
+ if (saved === 'default') return { preset: 'default', src: defaultAvatar };
if (saved === 'workdaddy') return { preset: 'workdaddy', src: brand };
if (typeof saved === 'string' && /^data:image\/(png|jpeg|webp);base64,/.test(saved)) return { preset: 'custom', src: saved };
return { preset: 'workbuddy', src: official };
@@ -2797,7 +2938,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function applyInjectedI18n() {
applyI18n(root);
- var nodes = document.querySelectorAll('.wbs-stash-inline,.wbs-selection-quote-btn,.wbs-queue-tag,.wbs-message-nav-root,.wbs-fork-button,#wbs-fork-tooltip,#wbs-auto-inspector,#wbs-auto-inspect-tip');
+ var nodes = document.querySelectorAll('.wbs-stash-inline,.wbs-queue-tag,.wbs-message-nav-root,.wbs-fork-button,#wbs-fork-tooltip,#wbs-auto-inspector,#wbs-auto-inspect-tip');
for (var i = 0; i < nodes.length; i++) applyI18n(nodes[i]);
}
window.__wbsSetLanguage = setLanguage;
@@ -2812,6 +2953,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!CAPS.theme) root.classList.add('wbs-no-theme');
if (!CAPS.stashPrompt) root.classList.add('wbs-no-stash');
root.innerHTML = [
+ '<button class="wbs-automation-stop" type="button" title="停止运行" aria-label="停止运行" hidden>' + AUTO_TAB_SVG + '<span class="wbs-automation-stop-label">停止运行</span></button>',
'<div class="wbs-fab" title="' + WBS_BRAND + '">',
'<span class="wbs-fab-health-dot" title="会话状态" style="display:none"></span>',
'<svg class="wbs-robot-masks" width="0" height="0" aria-hidden="true" focusable="false"><defs><mask id="wbs-robot-face-mask" maskUnits="userSpaceOnUse" x="0" y="0" width="82" height="64" style="mask-type:luminance">',
@@ -2844,7 +2986,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<button class="wbs-tab" type="button" data-tab="sessions"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg><span>会话</span></button>',
'<button class="wbs-tab" type="button" data-tab="models"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 2 9 5-9 5-9-5 9-5Z"/><path d="m3 12 9 5 9-5"/><path d="m3 17 9 5 9-5"/></svg><span>模型</span></button>',
'<button class="wbs-tab" type="button" data-tab="enhance"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg><span>增强</span></button>',
- '<button class="wbs-tab" type="button" data-tab="automations"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 8V4H9"/><rect x="4" y="8" width="16" height="12" rx="3"/><path d="M2 12v4M22 12v4M9 12v2M15 12v2M9 17h6"/></svg><span>自动化</span></button>',
+ '<button class="wbs-tab" type="button" data-tab="automations">' + AUTO_TAB_SVG + '<span>自动化</span></button>',
'<button class="wbs-tab" type="button" data-tab="pc"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg><span>电脑</span></button>',
'<button class="wbs-tab" type="button" data-tab="about"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg><span>关于</span></button>',
'</div>',
@@ -3005,12 +3147,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
exploreBtn.addEventListener('mouseleave', function () { exploreBtn.classList.remove('wbs-menu-closed'); });
exploreBtn.style.display = 'none'; // 找到可见会话输入区并完成定位后才显示,避免登录页出现悬空按钮。
- /* ———— 会话模块(session):暂存提示词、会话消息索引、选中文字引用 & 快捷短语 ————
+ /* ———— 会话模块(session):暂存提示词、会话消息索引 & 快捷短语 ————
* 暂存提示词/快捷短语由 daemon 持久化;消息索引开关保存在渲染器 localStorage。
* stash 按钮显隐受「暂存提示词」开关影响;explore 按钮与面板选项受「快捷短语」开关/列表影响。 */
var MESSAGE_NAV_ENABLED_KEY = 'workdaddy.session.messageNavigationEnabled';
// 会话用量开关使用 renderer localStorage,默认开启,不依赖 daemon 状态。
- var SELECTION_QUOTE_ENABLED_KEY = 'workdaddy.session.selectionQuoteEnabled';
var FORK_ENABLED_KEY = 'workdaddy.session.forkEnabled';
var FORK_OPEN_KEY = 'workdaddy.session.pendingForkOpen.' + PROFILE_ID;
function readMessageNavigationEnabled() {
@@ -3019,12 +3160,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function writeMessageNavigationEnabled(enabled) {
try { localStorage.setItem(MESSAGE_NAV_ENABLED_KEY, enabled ? '1' : '0'); } catch (_) {}
}
- function readSelectionQuoteEnabled() {
- try { return localStorage.getItem(SELECTION_QUOTE_ENABLED_KEY) !== '0'; } catch (_) { return true; }
- }
- function writeSelectionQuoteEnabled(enabled) {
- try { localStorage.setItem(SELECTION_QUOTE_ENABLED_KEY, enabled ? '1' : '0'); } catch (_) {}
- }
function readForkEnabled() {
try { return localStorage.getItem(FORK_ENABLED_KEY) !== '0'; } catch (_) { return true; }
}
@@ -3035,7 +3170,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
stash: true,
messageNav: readMessageNavigationEnabled(),
usageSummary: conversationUsageEnabled,
- selectionQuote: readSelectionQuoteEnabled(),
fork: readForkEnabled(),
phrase: true,
phrases: [],
@@ -3054,14 +3188,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var swS = pane0 && pane0.querySelector('#wbs-sess-stash');
var swN = pane0 && pane0.querySelector('#wbs-sess-message-nav');
var swU = pane0 && pane0.querySelector('#wbs-sess-usage-summary');
- var swQ = pane0 && pane0.querySelector('#wbs-sess-selection-quote');
var swF = pane0 && pane0.querySelector('#wbs-sess-fork');
var swP = pane0 && pane0.querySelector('#wbs-sess-phrase');
var area = pane0 && pane0.querySelector('#wbs-qp-area');
if (swS) swS.checked = !!sessState.stash;
if (swN) swN.checked = !!sessState.messageNav;
if (swU) swU.checked = !!conversationUsageEnabled;
- if (swQ) swQ.checked = !!sessState.selectionQuote;
if (swF) swF.checked = !!sessState.fork;
if (swP) swP.checked = !!sessState.phrase;
if (area) area.style.display = sessState.phrase ? '' : 'none';
@@ -3090,137 +3222,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
- // 轻量选区引用:只保存当前选中的文字,通过 WorkBuddy 官方 content-block 请求插入输入框。
- // 不复制 Codex 的 locator/回复标注协议,避免依赖脆弱的内部状态。
- var selectionQuoteButton = null;
- var selectionQuotePending = null;
- var selectionQuoteFrame = null;
- var SELECTION_QUOTE_MAX_LENGTH = 12000;
- /* WorkBuddy 的 selection-quote renderer 会通过 InputContextTag 自己渲染消息图标。 */
-
- function selectionQuoteElement(range) {
- if (!range || !range.commonAncestorContainer) return null;
- var node = range.commonAncestorContainer;
- var element = node.nodeType === 1 ? node : node.parentElement;
- if (!element || !element.closest) return null;
- if (element.closest('.wbs-root,.wbs-selection-quote-btn,textarea,input')) return null;
- var editable = element.closest('[contenteditable="true"]');
- var composer = findComposer();
- if (editable && composer && editable === composer) return null;
- return element.closest(
- '[data-message-id],[data-message-request-id],.cb-message,.cr-message,.cr-message-content,' +
- '[class*="message-content"],[class*="messageContent"],[class*="message-bubble"],[class*="messageBubble"]'
- ) || element.closest('.cr-document[data-root-id]');
- }
-
- function selectionQuoteBlock(text) {
- return {
- type: 'resource_link',
- name: '引用文本',
- uri: 'selection://document-selection',
- _meta: {
- displayAsPhrase: true,
- displayAsContext: false,
- displayText: '引用文本',
- selectionQuote: true,
- mentionType: 'selection',
- selectedText: text,
- title: '引用文本',
- },
- };
- }
-
- function hideSelectionQuoteButton() {
- if (selectionQuoteButton) selectionQuoteButton.style.display = 'none';
- selectionQuotePending = null;
- }
-
- function updateSelectionQuoteButton() {
- selectionQuoteFrame = null;
- if (!alive || !sessState.selectionQuote || !selectionQuoteButton) return;
- var sel = window.getSelection && window.getSelection();
- if (!sel || sel.rangeCount < 1 || sel.isCollapsed) return hideSelectionQuoteButton();
- var range = sel.getRangeAt(0);
- var message = selectionQuoteElement(range);
- var text = String(sel.toString() || '').trim();
- if (!message || !text || text.length > SELECTION_QUOTE_MAX_LENGTH) return hideSelectionQuoteButton();
- var rect = range.getBoundingClientRect();
- if (!rect || rect.width <= 0 || rect.height <= 0 || rect.bottom < 0 || rect.top > window.innerHeight) {
- return hideSelectionQuoteButton();
- }
- selectionQuotePending = { text: text, rect: rect };
- selectionQuoteButton.style.display = 'inline-flex';
- var buttonRect = selectionQuoteButton.getBoundingClientRect();
- var left = Math.max(8, Math.min(window.innerWidth - buttonRect.width - 8, rect.right - buttonRect.width));
- var top = rect.top - buttonRect.height - 8;
- if (top < 8) top = Math.min(window.innerHeight - buttonRect.height - 8, rect.bottom + 8);
- selectionQuoteButton.style.left = Math.round(left) + 'px';
- selectionQuoteButton.style.top = Math.round(Math.max(8, top)) + 'px';
- }
-
- function scheduleSelectionQuoteButton() {
- if (selectionQuoteFrame !== null) return;
- var request = window.requestAnimationFrame || function (callback) { return setTimeout(callback, 40); };
- selectionQuoteFrame = request(updateSelectionQuoteButton);
- }
-
- function insertSelectionQuote() {
- var pending = selectionQuotePending;
- if (!pending || !pending.text) return;
- hideSelectionQuoteButton();
- var adapter = null;
- try { adapter = window.__wbsAdapter || findWbsAdapter(); } catch (_) {}
- if (!adapter || typeof adapter.requestInsertContentBlocks !== 'function') {
- toast('当前输入框暂不支持引用插入', true, root);
- return;
- }
- var request = { contentBlocks: [selectionQuoteBlock(pending.text)] };
- try {
- Promise.resolve(adapter.requestInsertContentBlocks(request)).catch(function () {
- toast('引用插入失败,请重试', true, root);
- });
- } catch (_) {
- toast('引用插入失败,请重试', true, root);
- }
- }
-
- function setupSelectionQuote() {
- if (!document.body) return;
- if (!sessState.selectionQuote) hideSelectionQuoteButton();
- if (!selectionQuoteButton) {
- selectionQuoteButton = el('button', 'wbs-selection-quote-btn');
- selectionQuoteButton.type = 'button';
- selectionQuoteButton.setAttribute('aria-label', '引用文本');
- selectionQuoteButton.textContent = '引用文本';
- document.body.appendChild(selectionQuoteButton);
- applyI18n(selectionQuoteButton);
- listen(selectionQuoteButton, 'pointerdown', function (event) {
- if (event.preventDefault) event.preventDefault();
- if (event.stopPropagation) event.stopPropagation();
- });
- listen(selectionQuoteButton, 'click', function (event) {
- if (event.preventDefault) event.preventDefault();
- if (event.stopPropagation) event.stopPropagation();
- insertSelectionQuote();
- });
- }
- listen(document, 'selectionchange', scheduleSelectionQuoteButton);
- listen(document, 'mouseup', scheduleSelectionQuoteButton);
- listen(window, 'scroll', scheduleSelectionQuoteButton, true);
- listen(window, 'resize', scheduleSelectionQuoteButton);
- listen(document, 'keydown', function (event) {
- if (event.key === 'Escape') hideSelectionQuoteButton();
- });
- registerDisposer(function () {
- if (selectionQuoteFrame !== null) {
- var cancel = window.cancelAnimationFrame || clearTimeout;
- try { cancel(selectionQuoteFrame); } catch (_) {}
- selectionQuoteFrame = null;
- }
- if (selectionQuoteButton) { selectionQuoteButton.remove(); selectionQuoteButton = null; }
- selectionQuotePending = null;
- });
- }
/** 增强页快捷短语列表渲染(含批量模式) */
function renderQpList() {
var pane1 = enhancePane;
@@ -4394,12 +4395,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var fabSnapTimer = null;
var FAB_DRAG_THRESHOLD = 6;
var FAB_EDGE_GAP = 22;
- var FAB_POSITION_KEY = 'wbs-fab-bottom-' + PROFILE_ID;
+ // v2 deliberately ignores the pre-drag/anchor coordinates. Those values
+ // could place the button at the top edge (where WorkBuddy's toolbar
+ // intercepts the hit), leaving a visible but unusable robot after upgrade.
+ var FAB_POSITION_KEY = 'wbs-fab-bottom-v2-' + PROFILE_ID;
+ var FAB_LEGACY_POSITION_KEY = 'wbs-fab-bottom-' + PROFILE_ID;
function readFabBottom() {
try {
- var value = Number(localStorage.getItem(FAB_POSITION_KEY));
- return isFinite(value) ? value : null;
+ var raw = localStorage.getItem(FAB_POSITION_KEY);
+ var value = Number(raw);
+ if (raw !== null && raw !== '' && isFinite(value)) return value;
+ // Remove the old coordinate so a later downgrade/reinjection cannot
+ // immediately restore the broken top-edge position.
+ localStorage.removeItem(FAB_LEGACY_POSITION_KEY);
+ return null;
} catch (_) { return null; }
}
@@ -5339,7 +5349,77 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
var fab = root.querySelector('.wbs-fab');
- var fabAppearance = createFabAppearance({ fab: fab, storage: localStorage, key: 'wbs-fab-style-' + PROFILE_ID });
+ var automationStop = root.querySelector('.wbs-automation-stop');
+ var automationStopState = { runId: '', stopping: false };
+ function syncAutomationStopPosition() {
+ if (!automationStop || !fab || automationStop.hidden) return;
+ var rect = fab.getBoundingClientRect();
+ if (!rect.width || !rect.height) return;
+ var height = automationStop.offsetHeight || 32;
+ var centerY = rect.top + rect.height / 2;
+ automationStop.style.right = Math.max(8, window.innerWidth - rect.left + 8) + 'px';
+ automationStop.style.bottom = Math.max(8, window.innerHeight - centerY - height / 2) + 'px';
+ }
+ function renderAutomationStop(run) {
+ if (!automationStop) return;
+ var visible = !!run && !state.open;
+ automationStop.hidden = !visible;
+ if (!visible) {
+ automationStopState.runId = '';
+ automationStopState.stopping = false;
+ automationStop.classList.remove('is-stopping');
+ automationStop.disabled = false;
+ automationStop.innerHTML = AUTO_TAB_SVG + '<span class="wbs-automation-stop-label">停止运行</span>';
+ return;
+ }
+ automationStopState.runId = String(run.id || '');
+ var stopping = automationStopState.stopping || !!run.stopRequested;
+ automationStop.classList.toggle('is-stopping', stopping);
+ automationStop.disabled = stopping;
+ automationStop.title = stopping ? '正在停止…' : '停止运行';
+ automationStop.setAttribute('aria-label', stopping ? '正在停止…' : '停止运行');
+ automationStop.innerHTML = AUTO_TAB_SVG + '<span class="wbs-automation-stop-label">' + (stopping ? '正在停止…' : '停止运行') + '</span>';
+ syncAutomationStopPosition();
+ }
+ function refreshAutomationStop() {
+ if (!automationStop || state.open) return Promise.resolve();
+ return api('/api/automations').then(function (result) {
+ var run = findLatestManualAutomationRun(result && result.tasks, result && result.runs);
+ renderAutomationStop(run);
+ }).catch(function () {});
+ }
+ if (automationStop) {
+ automationStop.addEventListener('click', function (event) {
+ if (event.preventDefault) event.preventDefault();
+ if (event.stopPropagation) event.stopPropagation();
+ var runId = automationStopState.runId;
+ if (!runId || automationStopState.stopping) return;
+ automationStopState.stopping = true;
+ automationStop.classList.add('is-stopping');
+ automationStop.disabled = true;
+ automationStop.title = '正在停止…';
+ automationStop.setAttribute('aria-label', '正在停止…');
+ automationStop.innerHTML = AUTO_TAB_SVG + '<span class="wbs-automation-stop-label">正在停止…</span>';
+ api('/api/automations/stop', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ runId: runId }),
+ }).then(function (result) {
+ toast(result && result.run && result.run.status === 'running' ? '正在安全停止' : '任务已停止', false, root);
+ return refreshAutomationStop();
+ }).catch(function (error) {
+ automationStopState.stopping = false;
+ toast(error.message || '停止失败', true, root);
+ renderAutomationStop({ id: runId, status: 'running' });
+ }).finally(function () {
+ setBuildTimeout(function () { automationStopState.stopping = false; refreshAutomationStop(); }, 900);
+ });
+ });
+ setBuildInterval(refreshAutomationStop, 2500);
+ setBuildInterval(syncAutomationStopPosition, 250);
+ setBuildTimeout(refreshAutomationStop, 700);
+ }
+ var fabAppearance = createFabAppearance({ fab: fab, root: root, storage: localStorage, key: 'wbs-fab-style-' + PROFILE_ID });
var panel = root.querySelector('.wbs-panel');
var body = root.querySelector('.wbs-body');
var accountsPane = root.querySelector('[data-pane="account"]');
@@ -5503,6 +5583,78 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
root.querySelector('#wbs-import-file').addEventListener('change', onImportFile);
}
+ function initialAutoCopyAllSeen() {
+ try { return localStorage.getItem(WBS_INITIAL_AUTO_COPY_ALL_KEY) === '1'; } catch (_) { return false; }
+ }
+
+ function openInitialAutoCopyAllModal() {
+ if (!CAPS.sessions || !panel || initialAutoCopyAllSeen() || panel.querySelector('#wbs-initial-auto-copy-all-mask')) return;
+ var previousFocus = document.activeElement;
+ var mask = el('div', 'wbs-modal-mask wbs-modal-mask-panel');
+ mask.id = 'wbs-initial-auto-copy-all-mask';
+ mask.innerHTML = '<div class="wbs-modal wbs-initial-sync-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-initial-sync-title">' +
+ '<div class="wbs-modal-title" id="wbs-initial-sync-title">初始化设置</div>' +
+ '<div class="wbs-initial-sync-copy">选择切换账号时是否自动同步会话。此设置之后也可以在「会话」页面修改。</div>' +
+ '<label class="wbs-account-settings-toggle wbs-initial-sync-toggle"><span>切换账号自动同步所有会话</span><span class="wbs-switch"><input type="checkbox" data-initial-auto-copy-all checked><span class="wbs-switch-slider"></span></span></label>' +
+ '<div class="wbs-password-error wbs-initial-sync-error" role="alert"></div>' +
+ '<div class="wbs-modal-actions"><button class="wbs-modal-btn wbs-modal-ok" type="button" data-initial-auto-copy-all-save>确定</button></div>' +
+ '</div>';
+ panel.appendChild(mask);
+ applyI18n(mask);
+ var save = mask.querySelector('[data-initial-auto-copy-all-save]');
+ var busy = false;
+ function close() {
+ if (busy) return;
+ mask.remove();
+ if (previousFocus && previousFocus.isConnected && typeof previousFocus.focus === 'function') previousFocus.focus();
+ }
+ function showError(message) {
+ var error = mask.querySelector('.wbs-initial-sync-error');
+ if (error) error.textContent = message || '保存失败,请重试';
+ }
+ function saveSetting() {
+ if (busy) return;
+ busy = true;
+ save.disabled = true;
+ save.textContent = wbsTranslateString('保存中…', WBS_LANGUAGE);
+ var enabled = !!mask.querySelector('[data-initial-auto-copy-all]').checked;
+ api('/api/sessions/auto-copy-all', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ enabled: enabled }),
+ }).then(function (response) {
+ if (!response || response.autoCopyAll !== enabled) throw new Error('daemon 未确认设置');
+ try { localStorage.setItem(WBS_INITIAL_AUTO_COPY_ALL_KEY, '1'); } catch (_) {}
+ if (typeof sessionsState !== 'undefined' && sessionsState) sessionsState.autoCopyAll = enabled;
+ if (sessionsPane && sessionsPane.dataset.built) {
+ updateAutoCopyAllButton();
+ updateSessCount();
+ }
+ busy = false;
+ close();
+ }).catch(function (error) {
+ busy = false;
+ save.disabled = false;
+ save.textContent = wbsTranslateString('确定', WBS_LANGUAGE);
+ showError(error && error.message ? error.message : '保存失败,请重试');
+ });
+ }
+ mask.addEventListener('keydown', function (event) {
+ event.stopPropagation();
+ if (event.key !== 'Tab') return;
+ var focusable = Array.from(mask.querySelectorAll('button,input')).filter(function (node) { return !node.disabled && node.getClientRects().length; });
+ if (!focusable.length) return;
+ var first = focusable[0], last = focusable[focusable.length - 1];
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
+ if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
+ });
+ ['click', 'dblclick', 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'keyup', 'keypress', 'wheel', 'touchstart', 'touchmove'].forEach(function (type) {
+ mask.addEventListener(type, function (event) { event.stopPropagation(); });
+ });
+ save.addEventListener('click', saveSetting);
+ save.focus();
+ }
+
function openAccountOrderModal() {
var existing = root.querySelector('#wbs-account-order-mask');
if (existing) return;
@@ -6263,7 +6415,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var primaryRgb = styles.getPropertyValue('--wbs-primary-rgb').trim() || '34,197,94';
var muted = styles.getPropertyValue('--wb-icon-tertiary').trim() || '#8a8f98';
var border = styles.getPropertyValue('--wb-border-subtle').trim() || 'rgba(20,24,32,.1)';
- var chartLeft = 18, chartRight = cssWidth - 18, chartTop = 28, chartBottom = 132;
+ // Keep endpoint labels inside the canvas. Centered labels at x=18 used to
+ // clip the first/last value when a credit amount had more than a few digits.
+ context.font = '600 11px -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif';
+ var edgeLabelWidth = 0;
+ if (values.length && values.length <= 14 && series.length === 1) {
+ series[0].values.forEach(function (value) { edgeLabelWidth = Math.max(edgeLabelWidth, context.measureText(formatValue(value)).width); });
+ }
+ if (values.length) {
+ edgeLabelWidth = Math.max(edgeLabelWidth, context.measureText(values[0].label).width, context.measureText(values[values.length - 1].label).width);
+ }
+ var chartInset = Math.max(24, Math.ceil(edgeLabelWidth / 2) + 6);
+ var chartLeft = chartInset, chartRight = cssWidth - chartInset, chartTop = 28, chartBottom = 132;
var max = Math.max.apply(null, series.flatMap(function (line) { return line.values; }).concat([1]));
var x = function (index) { return values.length <= 1 ? (chartLeft + chartRight) / 2 : chartLeft + (chartRight - chartLeft) * index / (values.length - 1); };
var y = function (value) { return chartBottom - (chartBottom - chartTop) * value / max; };
@@ -6438,14 +6601,31 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
days.push({ title: key, label: key.slice(5), value: byDay[key] ? byDay[key].used : 0 });
date.setDate(date.getDate() + 1);
}
+ var byModel = Object.create(null);
+ var modelRecords = [];
+ (creditData.daily || []).forEach(function (item) {
+ if (ids.indexOf(item.uid) < 0) return;
+ var models = item.models && typeof item.models === 'object' ? item.models : {};
+ Object.keys(models).forEach(function (model) {
+ var detail = models[model] || {};
+ var used = Number(detail.used) || 0;
+ var count = Number(detail.count) || 0;
+ if (!used && !count) return;
+ if (!byModel[model]) byModel[model] = { used: 0, count: 0 };
+ byModel[model].used += used;
+ byModel[model].count += count;
+ modelRecords.push({ day: item.date, model: model, value: used });
+ });
+ });
creditBody.innerHTML = '<div class="wbs-token-stats-grid wbs-credit-stats-grid"><div><span>积分消耗</span><strong>' + (creditData.daily.length ? esc(fmtCredits(total)) : '—') + '</strong></div><div><span>调用</span><strong>' + (creditData.daily.length ? esc(formatTokenCount(calls)) : '—') + '</strong></div></div>' +
- '<div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">每日趋势</div>' + usageTrendChartHtml('每日积分趋势', false) + ((creditData.failures || []).length ? '<div class="wbs-credit-stats-note">* 表示部分账号查询失败;— 表示查询失败,暂无数据。</div>' : '') + '</div>' +
- '<div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">账号用量</div><div class="wbs-token-model-scroll"><div class="wbs-token-stats-table">' + (selected.slice().filter(function (a) { return (byAccount[a.uid] || 0) > 0; }).sort(function (a,b) { return (byAccount[b.uid] || 0) - (byAccount[a.uid] || 0); }).map(function (a) { return '<div><span title="' + escAttr(a.nickname || a.uid) + '">' + esc(a.nickname || a.uid) + '</span><b>' + esc(fmtCredits(byAccount[a.uid])) + '</b><em>' + esc(formatTokenCount(accountCalls[a.uid] || 0)) + ' 次</em></div>'; }).join('') || '<div class="wbs-token-stats-empty">没有匹配的账号</div>') + '</div></div></div>';
+ '<div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">每日趋势</div>' + usageTrendChartHtml('每日积分趋势', true) + ((creditData.failures || []).length ? '<div class="wbs-credit-stats-note">* 表示部分账号查询失败;— 表示查询失败,暂无数据。</div>' : '') + '</div>' +
+ '<div class="wbs-usage-columns"><div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">账号用量</div><div class="wbs-token-model-scroll"><div class="wbs-token-stats-table">' + (selected.slice().filter(function (a) { return (byAccount[a.uid] || 0) > 0; }).sort(function (a,b) { return (byAccount[b.uid] || 0) - (byAccount[a.uid] || 0); }).map(function (a) { return '<div><span title="' + escAttr(a.nickname || a.uid) + '">' + esc(a.nickname || a.uid) + '</span><b>' + esc(fmtCredits(byAccount[a.uid])) + '</b><em>' + esc(formatTokenCount(accountCalls[a.uid] || 0)) + ' 次</em></div>'; }).join('') || '<div class="wbs-token-stats-empty">没有匹配的账号</div>') + '</div></div></div>' +
+ (Object.keys(byModel).length ? '<div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">模型用量</div><div class="wbs-token-model-scroll"><div class="wbs-token-stats-table">' + Object.keys(byModel).sort(function (a, b) { return byModel[b].used - byModel[a].used || a.localeCompare(b); }).map(function (model) { return '<div><span title="' + escAttr(model) + '">' + esc(model) + '</span><b>' + esc(fmtCredits(byModel[model].used)) + '</b><em>' + esc(formatTokenCount(byModel[model].count)) + ' 次</em></div>'; }).join('') + '</div></div></div>' : '') + '</div>';
var creditNames = Object.create(null);
creditAccounts.forEach(function (account) { creditNames[account.uid] = account.nickname || account.uid; });
renderUsageBreakdown(creditBody.querySelector('.wbs-trend-panel'), days, (creditData.daily || []).map(function (row) {
return { day: row.date, account: row.uid, value: Number(row.used) || 0 };
- }), { account: creditNames }, creditTrendState, fmtCredits);
+ }).concat(modelRecords), { account: creditNames, model: Object.keys(byModel).reduce(function (out, model) { out[model] = model; return out; }, {}) }, creditTrendState, fmtCredits);
var accountScroll = creditBody.querySelector('.wbs-token-model-scroll');
if (accountScroll) {
var syncAccountFade = function () {
@@ -7272,7 +7452,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
automationState.pollTimer = setInterval(load, 2500);
}
- // ===== 会话 pane(构建:账号/时间筛选 + 按空间分组[默认2条/展开10条] + 刷新 + 批量操作[迁移/删除])=====
+ // ===== 会话 pane(构建:账号/时间筛选 + 按空间分组[默认2条/展开全部] + 刷新 + 批量操作[迁移/删除])=====
var sessionsState = { uid: undefined, currentUid: '', range: 'all', minBytes: 0, totalBytes: null, list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null, autoCopyAll: false, autoCopyJob: null, autoCopyPollTimer: null };
function isTaskSessionRecordUI(s) {
// 任务(未选择项目/一次性)会话:以官方 is_playground=1 为准。
@@ -7295,7 +7475,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return value;
}
var SESS_WS_INIT = 2; // 每个空间默认显示条数
- var SESS_WS_STEP = 10; // 展开一次追加条数
function sessionCopyAccountLabel(uid, fallbackName) {
var key = String(uid || '');
var account = sessionsState.accounts.find(function (item) { return String(item.uid || '') === key; });
@@ -7308,10 +7487,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!box) return;
if (!job) { box.hidden = true; return; }
var active = job.status === 'queued' || job.status === 'running';
+ // The sessions page is a live progress surface. Do not leave a stale
+ // completion card visible after the next status poll.
+ if (!active && job.status !== 'error') { box.hidden = true; return; }
var total = Math.max(0, Number(job.total) || 0);
var processed = Math.min(total, Math.max(0, Number(job.processed) || 0));
var percent = total ? Math.round(processed / total * 100) : (active ? 0 : 100);
- var title = job.status === 'queued' ? '会话同步等待中' : job.status === 'running' ? '正在同步会话' : job.status === 'done' ? '会话同步完成' : job.status === 'conflict' ? '会话同步完成,已保留分叉' : job.status === 'partial' ? '会话同步完成,部分项目失败' : '会话同步失败';
+ var title = job.status === 'queued' ? '会话同步等待中' : job.status === 'running' ? '正在同步会话' : '会话同步失败';
var route = sessionCopyAccountLabel(job.sourceUid, job.sourceName) + ' → ' + sessionCopyAccountLabel(job.targetUid, job.targetName);
var detail = route;
if (active && job.currentLabel) detail += ' · ' + job.currentLabel;
@@ -7323,7 +7505,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
box.className = 'wbs-sess-copy-progress is-' + String(job.status || 'running');
box.querySelector('.wbs-sess-copy-title').textContent = title;
box.querySelector('.wbs-sess-copy-detail').textContent = detail;
- box.querySelector('.wbs-sess-copy-count').textContent = processed + ' / ' + total;
var progress = box.querySelector('.wbs-sess-copy-track');
progress.setAttribute('aria-valuenow', String(percent));
progress.setAttribute('aria-valuetext', title + ',' + processed + '/' + total);
@@ -7380,7 +7561,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</div>' +
'</div>' +
'<div class="wbs-sess-copy-progress" id="wbs-sess-copy-progress" role="status" aria-live="polite" hidden>' +
- '<div class="wbs-sess-copy-head"><span class="wbs-sess-copy-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></span><strong class="wbs-sess-copy-title">正在同步会话</strong><span class="wbs-sess-copy-count">0 / 0</span></div>' +
+ '<div class="wbs-sess-copy-head"><span class="wbs-sess-copy-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></span><strong class="wbs-sess-copy-title">正在同步会话</strong></div>' +
'<div class="wbs-sess-copy-detail"></div><div class="wbs-sess-copy-track" role="progressbar" aria-label="会话同步进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><span class="wbs-sess-copy-fill"></span></div>' +
'</div>' +
'<input type="file" id="wbs-sess-import-file" accept=".wds,.json,application/json,application/octet-stream" style="display:none">' +
@@ -7403,12 +7584,34 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
registerDisposer(function () { if (sessionsState.autoCopyPollTimer) clearTimeout(sessionsState.autoCopyPollTimer); });
}
+ function sortSessionAccounts(accounts, accountOrder) {
+ var ordered = (accounts || []).slice();
+ return ordered.map(function (account, index) {
+ var expiry = Infinity;
+ (Array.isArray(account.creditSegments) ? account.creditSegments : []).forEach(function (segment) {
+ if (!segment || Number(segment.remaining) <= 0 || segment.expiresAt === null || segment.expiresAt === undefined || segment.expiresAt === '') return;
+ var value = Number(segment.expiresAt);
+ if (isFinite(value) && value < expiry) expiry = value;
+ });
+ return { account: account, index: index, expiry: expiry };
+ }).sort(function (a, b) {
+ if (accountOrder && accountOrder.mode === 'fixed') {
+ var left = Number(a.account.sort) > 0 ? Number(a.account.sort) : Infinity;
+ var right = Number(b.account.sort) > 0 ? Number(b.account.sort) : Infinity;
+ return left === right ? a.index - b.index : left - right;
+ }
+ return a.expiry === b.expiry ? a.index - b.index : a.expiry - b.expiry;
+ }).map(function (item) {
+ return item.account;
+ });
+ }
+
// 加载账号下拉(当前账号 + 全部备份账号 + 全部账号)
function loadSessionAccounts() {
var sel = sessionsPane.querySelector('#wbs-sess-account-select');
if (!sel) return;
api('/api/accounts').then(function (d) {
- var accts = (d && d.accounts) || [];
+ var accts = sortSessionAccounts((d && d.accounts) || [], d && d.accountOrder);
sessionsState.accounts = accts;
var curUid = (d && d.current && d.current.uid) || '';
sessionsState.currentUid = curUid;
@@ -7468,7 +7671,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
- // 按空间分组渲染:每个空间最多显示 INIT 条 + 展开按钮(每次 +STEP)。
+ // 按空间分组渲染:每个空间默认显示 INIT 条,可一次展开全部。
function renderSessions() {
var listEl = sessionsPane.querySelector('#wbs-sess-list');
var countEl = sessionsPane.querySelector('#wbs-sess-count');
@@ -7524,7 +7727,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<span class="wbs-sess-size" title="会话大小(消息和附件)">' + sessionCopySizeText(s.totalBytes) + '</span>' +
'</div>';
});
- if (taskMore > 0) html += '<button class="wbs-sess-more" type="button" data-ws="__TASKS__">展开 ' + Math.min(taskMore, SESS_WS_STEP) + ' 条(剩余 ' + taskMore + ')</button>';
+ if (taskMore > 0) html += '<button class="wbs-sess-more" type="button" data-action="expand" data-ws="__TASKS__">展开</button>';
+ if (taskShown >= tasks.length && tasks.length > SESS_WS_INIT) html += '<button class="wbs-sess-more" type="button" data-action="collapse" data-ws="__TASKS__">收起</button>';
html += '</div>';
}
wsOrder.forEach(function (groupKey) {
@@ -7556,7 +7760,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<span class="wbs-sess-size" title="会话大小(消息和附件)">' + sessionCopySizeText(s.totalBytes) + '</span>' +
'</div>';
});
- if (more > 0) html += '<button class="wbs-sess-more" type="button" data-ws="' + escAttr(groupKey) + '">展开 ' + Math.min(more, SESS_WS_STEP) + ' 条(剩余 ' + more + ')</button>';
+ if (more > 0) html += '<button class="wbs-sess-more" type="button" data-action="expand" data-ws="' + escAttr(groupKey) + '">展开</button>';
+ if (shown >= arr.length && arr.length > SESS_WS_INIT) html += '<button class="wbs-sess-more" type="button" data-action="collapse" data-ws="' + escAttr(groupKey) + '">收起</button>';
html += '</div>';
});
listEl.innerHTML = html;
@@ -7637,11 +7842,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
updateSessCount(); // 组头全选后同步刷新计数与「复制/删除」按钮显隐
return;
}
- // 展开按钮
+ // 展开/收起按钮
var more = t.closest ? t.closest('.wbs-sess-more') : null;
if (more) {
var w2 = more.getAttribute('data-ws');
- sessionsState.wsExpanded[w2] = (sessionsState.wsExpanded[w2] || SESS_WS_INIT) + SESS_WS_STEP;
+ if (more.getAttribute('data-action') === 'collapse') delete sessionsState.wsExpanded[w2];
+ else {
+ var groupItems = filteredSessions().filter(function (s) {
+ if (w2 === '__TASKS__') return isTaskSessionRecordUI(s);
+ return String(s.user_id || sessionsState.uid || '') + '::' + (s.cwd || '(未指定空间)') === w2;
+ });
+ sessionsState.wsExpanded[w2] = groupItems.length;
+ }
renderSessions();
return;
}
@@ -8602,8 +8814,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-pcard wbs-avatar-card">' +
'<div class="wbs-pcard-title">头像</div>' +
'<div class="wbs-avatar-row">' +
- '<label class="wbs-avatar-option" title="WorkBuddy"><input type="radio" name="wbs-avatar-preset" value="workbuddy"><img data-avatar-image="workbuddy" alt="WorkBuddy"><span>WorkBuddy</span></label>' +
- '<label class="wbs-avatar-option" title="WorkDaddy"><input type="radio" name="wbs-avatar-preset" value="workdaddy"><img data-avatar-image="workdaddy" alt="WorkDaddy"><span>WorkDaddy</span></label>' +
+ '<label class="wbs-avatar-option wbs-avatar-default-option" title="默认头像"><input type="radio" name="wbs-avatar-preset" value="default"><img class="wb-avatar__img" data-avatar-image="default" alt="默认头像"></label>' +
+ '<label class="wbs-avatar-option" title="WorkBuddy"><input type="radio" name="wbs-avatar-preset" value="workbuddy"><img class="wb-avatar__img" data-avatar-image="workbuddy" alt="WorkBuddy"></label>' +
+ '<label class="wbs-avatar-option" title="WorkDaddy"><input type="radio" name="wbs-avatar-preset" value="workdaddy"><img data-avatar-image="workdaddy" alt="WorkDaddy"></label>' +
'<div class="wbs-avatar-custom-list" id="wbs-avatar-custom-list"></div>' +
'<button class="wbs-avatar-add" id="wbs-avatar-upload" type="button" title="添加头像" aria-label="添加头像"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg></button>' +
'<input type="file" id="wbs-avatar-file" accept="image/png,image/jpeg,image/webp" style="display:none">' +
@@ -8721,11 +8934,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<label class="wbs-switch"><input type="checkbox" id="wbs-sess-fork" aria-label="分支到新会话"><span class="wbs-switch-slider"></span></label>' +
'</div>' +
'<div class="wbs-nd-row">' +
- '<span class="wbs-nd-title">引用消息文本</span>' +
- '<span class="wbs-nd-hint">选中会话消息文字后,一键插入输入框</span>' +
- '<label class="wbs-switch" title="选中会话消息中的文字后显示引用按钮"><input type="checkbox" id="wbs-sess-selection-quote"><span class="wbs-switch-slider"></span></label>' +
- '</div>' +
- '<div class="wbs-nd-row">' +
'<span class="wbs-nd-title">快捷短语</span>' +
'<span class="wbs-nd-hint">发送后不会自动删除</span>' +
'<label class="wbs-switch"><input type="checkbox" id="wbs-sess-phrase"><span class="wbs-switch-slider"></span></label>' +
@@ -9629,6 +9837,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
state.open = open;
panel.classList.toggle('show', open);
fab.classList.toggle('hidden', open); // 打开时隐藏按钮
+ if (typeof automationStop !== 'undefined' && automationStop && typeof automationStopState !== 'undefined') {
+ automationStop.hidden = open || !automationStopState.runId;
+ if (!automationStop.hidden) syncAutomationStopPosition();
+ }
fabQuietMode.wake();
if (open) {
if (newlyOpened && typeof automationPane !== 'undefined' && automationPane && automationPane.__wbsRefreshDiscovery) automationPane.__wbsRefreshDiscovery();
@@ -9639,6 +9851,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
checkForUpdate(); // 打开面板即检测更新(每次打开都强制查一次新版本)
try { acCheckPromptOnOpen(); } catch (e) {} // 每次打开面板:指令块丢失则请求 daemon 补写(无 toast)
try { syncSessionModule(); } catch (e) {} // 每次打开面板刷新会话模块(开关+快捷短语,含外部修改)
+ if (newlyOpened && CAPS.sessions) setBuildTimeout(function () { if (state.open) openInitialAutoCopyAllModal(); }, 0);
} else {
if (typeof hideCreditTooltip === 'function') hideCreditTooltip();
if (typeof closeDailyProgressPopover === 'function') closeDailyProgressPopover();
@@ -9657,6 +9870,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
handle.style.touchAction = 'none';
listen(handle, 'pointerdown', function (e) {
if (e.button !== undefined && e.button !== 0) return;
+ if (e.stopPropagation) e.stopPropagation();
fab.classList.add('is-dragging');
fabQuietMode.wake();
var rect = fab.getBoundingClientRect();
@@ -9670,10 +9884,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
fabDragMoved = false;
fabDragSuppressClick = false;
try { handle.setPointerCapture(e.pointerId); } catch (_) {}
- if (e.preventDefault) e.preventDefault();
});
listen(handle, 'pointermove', function (e) {
if (!fabDrag || e.pointerId !== fabDrag.pointerId) return;
+ if (e.stopPropagation) e.stopPropagation();
var deltaX = e.clientX - fabDrag.startX;
var deltaY = e.clientY - fabDrag.startY;
if (Math.max(Math.abs(deltaX), Math.abs(deltaY)) >= FAB_DRAG_THRESHOLD) {
@@ -9681,10 +9895,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
fabDragSuppressClick = true;
}
applyFabPosition(fab, fabDrag.startRight - deltaX, fabDrag.startBottom - deltaY);
+ syncAutomationStopPosition();
if (e.preventDefault) e.preventDefault();
});
function finishFabDrag(e) {
if (!fabDrag || (e && e.pointerId !== fabDrag.pointerId)) return;
+ if (e && e.stopPropagation) e.stopPropagation();
var rect = fab.getBoundingClientRect();
var bottom = clampFabBottom(window.innerHeight - rect.bottom, rect.height || 32);
// 释放后水平吸附回右边,垂直位置保留。
@@ -9695,6 +9911,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
fab.classList.remove('is-dragging');
fab.classList.add('is-snapping');
applyFabPosition(fab, FAB_EDGE_GAP, bottom);
+ syncAutomationStopPosition();
try { localStorage.setItem(FAB_POSITION_KEY, String(Math.round(bottom))); } catch (_) {}
fabDrag = null;
fabQuietMode.wake();
@@ -9990,7 +10207,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<rect x="74.4458" y="126.121" width="16.1364" height="33.514" rx="8.06819" transform="rotate(-30 74.4458 126.121)" fill="#4C4F6B" fill-opacity="0.3"></rect>' +
'<rect x="117.981" y="100.984" width="16.1364" height="33.514" rx="8.06819" transform="rotate(-30 117.981 100.984)" fill="#4C4F6B" fill-opacity="0.3"></rect>' +
'</g><defs><clipPath id="c0"><rect width="161" height="161" rx="34.7421" fill="white"></rect></clipPath></defs></svg>';
- var OFFICIAL_AVATAR = null; // 官方头像 PNG dataURL(SVG 转 96px)
+ // 第一个内置头像:用户指定的默认 PNG;第二个头像由官方 SVG 转 PNG。
+ var OFFICIAL_AVATAR = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABHNCSVQICAgIfAhkiAAAAQRpQ0NQVEdGWAAAGJVjYGA8wwAELAYMDLl5JUVB7k4KEZFRCuwvGTgZxBnAIDG5uIABN2BkYPh2DUQyMFzWxaMOF+BMSS1OBtIfgFilCGg50EgRIFskHcLWALGTIGwbELu8pKAEyA4AsYtCgpyB7BQgWyMdiZ2ExE4uKAKp7wGyHXJzSpMR7mbgSc0LDQbSHEAsw1DMEMTgzuAE8j9ESf4iBgaLrwwMzBMQYkkzGRi2tzIwSNxCiKksYGDgb2Fg2HYeIYYIk4LEokSwEAsQM6WlMTB8Ws7AwBvJwCB8gYGBKxoWEDjcpgR2WwhDKkMeQzKYLGFQYPAE8/SALCMGAyA2ZWAAAPaCP+RXa/pgAAALgElEQVRogb2ZfXBV9ZnHP8/vnHPvTS4hJIR3DYSu60uglhc1yK60WLdvTsetreOuiu3YmY7VrS7idKaFzlLdrVPLan1pRWc7Em3tlm5nnVZLcTt9WTURYgtaxBdQiEggAQPJTS65957fs3+cl3tuEhJA2F/mN+eXc57fud/neb7PyzlHOA2jruNnjf6QvwwjF6lqs4g0gU4FsqHIAEi3qr4jIjuwutVJO3/oXXxN5wf9bTnVjTUdP2mgyApBrgEuObVfl3ZVuxGP1v7F/3jolG5xshvqOn7W6BdLq1TkVlRP2QDDYKgIDzqus+5kvXJSACa0PbVa0G/D6QI+Ao4q+q3ckuvuPuEdJyJU2/7jRRYeQmk5dXAnMYR2A7cebbnu5fFFxxnZF1pvEGM2nIjsaR6qwoqBluufHEvIjHUx2/bESjHSGlBGOVPzuilNbG6+gpunn4sRovMiqk9k2378z2NhPK5Vs20bVgqybqzNp2NcNnE6/zZ7EY4IgrCpdx9r3/0zmpBRWDmwZMV9o+0f1QPZF1pv+P8AX2Vc7pw1D0cEg2AErqw/mztnza+QE/j3bPuG60e7xwgFqtsfX4TDBuXM/9049UNM8aoCBURwCBT5hylzuWpyY4UsSmt12xMLx1XAwEOoPaOcB2Wi43Ftw1wcIbA+YBKKrDnrIzRXT0ruEYP/8JgKVLc9vlpVW840eFCubWhiguNhEByRmEaOBIpkjMO9cy4mY0y8R9GW6rYfrU5ijoM409HaaEr+HvTMp8uUGDY1f4p6N40QeEBCTwggYTwIQmv3W9y178/J7Wp9Z86xv1nRCQkPmGJxVdAanHnrf3zSTCa7aQwEvBdi/psKbwhfnPbXI6jkOKU7ItwCUNOxvsEved2nr7cZe2w452MsyjYgoZUNICKjeCNYb8sd5qrXf0M5tYo6xpnSf8mNhw1AqeiuUFU587aHuZmJLJrQEARsaOV4TXkdewNh8YQpfLZ+TuI+KiVbXAExhfSaMw3dAEtrpvHNsxaEdKGc/xOKOBVrYko9OPdSvt24iFrHC+4pXAMgmY7WRikO7T1lPowzZqWy/P3kJq6ub2J6KhvTxUBMkYguUeBKCLxMqfK6tzTE1/e28/PDb6O+nS2Z9kdvEKX1dANvykzkthnzuaL2rBBMGWDE85j/FeCTcsNjoyy/NddNR67n+64oF+nYWE5qTPWquGX6PK6ePBdXZFyLVqTPkFJJ+dEUNwgtNdPo9wvLXRXbfDqeTwS4tuEc7ph5IVnHS1BkNCtT9gpBlLw80MPOfC+vDfbiimFWKss5mVo+UdeIi6lQPBp1XtUsF6UJPpgP6t0M3529hKUTZ1RYNkmDSisH1xTlqUO7eKDrFfYM9Y9672leNV+edj63zbiQGseruDbdzUyUdPsjOTR+e3DS47yqOn4w9zJmpbJjB+IwurzQf4DVnS+xM997Qr8zr7qeX5z7SRrTNfG5I35BJd32w9j8F2YbuLRmOpPdDBnjULCWvC3xfukY3cU8B4t59gz10V3MA3B57Vmsm7OUauOeQCAG685CjrXvbuGZ3pNPfFO8KjZf8FnOr6oDoKgWN6JPY7qG9XM/Ok6mCKyXtz6dQ/1cUF2HgzmhQBy0Jb7ftZ1HDvyFgvrHBSnKcUOypzjIjW89x/PzryYlDoriquiAKNmosIyWsobn6hrHY151fUUgHi/dCbDx8C7u2reFnsIgyFgP18FvjRWTrw728EDXdlbNXMigLamLarciTZ2Ffo7ZEhMcb1waVGaWRLob5oGOgW5Wd7axbaAnwhdKDoet4TUtiyV0GN4g3/NeB9dPOZeSVd+o8A4ovlq25g4mOkKO26tEnePxWoEDxUFufed3XLnzabYNdMegAg9ZRCyCxWAxYjEoRodNgimioUy4TywDfpE1ne0cKA32uajuQFgO8Juje7liUuOIjrAis4ygV3k9pD4/PLCdBw5sI29LEOVtUUQ1cgCigAleY0mo2efqz6HWTfNM79v0FAdJOkFD3ml4UkX5yaHXWFoz83UXsVsjF/326Lv0+wXq3MyYhWi0PP/L3rf5l3fb2FfIlWkiCqoBYJEQioZ7CY/KfXMu50tTgwf526YvZNmOp8j5hRC8xhRSyiRT4MlDr/2ncVz9Q8Stgvr89PCbZaqIVKxHo1RXcZAvvPksX979XAV4SYIVMCgOigPloyhZx43BA8zNTOJrMxbgYivkjGjYnYKRgF5/yu/7b3Ns8e2doO2Rfq09r1FQv/IJaRjno5b3L/nDLNuxkT/2dZZ5LopgkQSvHWw4g7WL4oqPh8W3BXYfqyxmd85sobm6Hk8snvi4WFwN7yHxfbb0Lr690wCo2o2RAu+X8jx5aGfFG4KyB0x8vruY57pdz9Ln5xOZJAQvieALAzBSwpVgeoRTLOve+1+Gj9tnXISHj4eSCuVcsYFnxOIY3QjhA03J81sDtgZqPHxwOwN+sfJ9TZJSCDft3kxXIZd4Ui2HXRCwGhYzxUlMl3AKuKJ4WDYfeZ3fHd1docBVky/g45OaAi+geKKhAoqL2pTrbYgVYPGqQ2AfjLxwpHSMhw5uGzV1GhH+NHCQttz+MuAK2gQeSNLFCUFHFk+JJSU+aXzSYkljebTr+RFe+HTdX5EOZVPYhCf8Rw8s/FpPWQGg5Jp1AaJAice6X2F/IVfhgWi9vvsVBBtTR9SWrR6Cv33GIn553hf4xqxLcQm4XAneBuDFkhGftwb38VT3lgoFDgz1khGftLGk8SMFrGsL341knFj60U1HzU2f8FV0OUBJLRnjsLy2cYQHvt75R/r8IcqRm6ALcNPUD3PP7MtpTNeypOZsXIGt/XvxRGM6BAEa0cPiirJjYC9TU7U0eDVs7n2V9V2/DYsaYUyBEf3OrovW/FcE201qXFqy8m6nfd1nIPiQYRlZzBSlq9hP1LdEXJfQnQa4sHpqhSVvm7mU547sYE++B08iSgUx4IQUE8DqEN/b+4sgnhRSgCPgI7gq+MK2LU/bNcnGYpR3o3prEM8avzlI1oAjpSH8KNw1qLCGcrk3Ynm+f2SrfPP0S0P6WDIhbTL4wVEsGROeNz5V4pMx4fmQZp6oLZbsLbJ2ra3EO2wUW1a9DLpCUXK2UJH3DcIUr4oJjhdUWdE4+0T8N2r51fs7+Z+juyru+5n6eSyrbYqDMS0+qTCA0wllgrhIxoiSFktB9J+2Xbz2xZEGH2X4LXc+icjKIevHqTTqIQWhuWpyELQaWp1y8xXEgeWh/SNz+1dmfCwALT4pAmBp45eDGUsGn3R0TYLgzVu5+6UFa38wGtbjfmKyl6y6b351w6jfp5bXNhK+XCq3DWF5d1AcgVcH36O1+6WKfedVz6LOTZGSJEACK6MBxYwGWUeC/3PW+c7vF9615ng4x/xGdsfMi294rPuVh/O2VHH+5mkLyDgmTJ2JtoFIiSD/P37wRfK2GO/b2vcGRX8wBpoKQaaw8TGtwdFg9bB1Vm5aePc3xsLojHUR4Fffe+TZCV/99OtnexOvnOSmXYAaJ0WfP0R7bl+QeaJmK5xeWGGL9hhbjr5BQYd4ue9NNnRtAophexBV13JVdiRo3BB5q7OU+fyvF/zrT8fDd8IvhFQ1+8yRt3/9d7Vz/tYTQ58/xPzt6zlcygWgAQ8b0AMNaGEsGZRMdD6cqSj/EyodGkFBc7iP/Ufz1ltEfl8aDxOMQ6EKTUUGrqz70GVPHHx1+fP9nW9kTYq1Zy+La0DUOgceCaajlHugsHi5cQ0gCV6LVp4eMM6HfzTv3q+cKHj4AB+vf967Y0FanXvu3f/ijO2D781PEXFaSWPJhNauinO5ktHg6ElMn115Nc/UuP79959//55TwXFaPmhMe+neJpHBj3rCJS62OSN2dlqYnBG/qiqg1LG02KOOsN8V3S0qWzNu8dkNzfft+KC//X+0NJns/GFkTwAAAABJRU5ErkJggg=='; // 官方头像 PNG dataURL
+ var DEFAULT_AVATAR = OFFICIAL_AVATAR;
+ OFFICIAL_AVATAR = null;
var avatarWrapperStates = [], avatarImageStates = [];
function rememberAvatarWrapper(wrap) {
for (var i = 0; i < avatarWrapperStates.length; i++) {
@@ -10033,10 +10253,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgStr);
});
}
- // 初始化官方头像(转换完成后立即应用一次)
- svgToPng(OFFICIAL_LOGO_SVG, 96).then(function (d) {
+ // 将 WorkBuddy 官方品牌 SVG 转为第二个内置头像。
+ svgToPng(OFFICIAL_LOGO_SVG, 96).then(function (dataUrl) {
if (!alive) return;
- OFFICIAL_AVATAR = d;
+ OFFICIAL_AVATAR = dataUrl;
applyAvatar();
});
function applyAvatar() {
@@ -10054,15 +10274,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
}
var selected = saved.items.find(function (item) { return item.id === saved.selected; });
- var choice = resolveAvatarChoice(selected ? selected.src : saved.selected, OFFICIAL_AVATAR, WBS_AVATAR_LOGO);
+ var choice = resolveAvatarChoice(selected ? selected.src : saved.selected, OFFICIAL_AVATAR, WBS_AVATAR_LOGO, DEFAULT_AVATAR);
var target = choice.src;
var wrap = document.querySelector('.user-menu-trigger-avatar');
root.querySelectorAll('input[name="wbs-avatar-preset"]').forEach(function (input) {
input.checked = input.value === saved.selected;
var image = input.parentNode.querySelector('img');
- var src = input.value === 'workbuddy' ? OFFICIAL_AVATAR : input.value === 'workdaddy' ? WBS_AVATAR_LOGO : null;
- if (src && image.getAttribute('src') !== src) image.src = src;
+ var src = input.value === 'default' ? DEFAULT_AVATAR : input.value === 'workbuddy' ? OFFICIAL_AVATAR : input.value === 'workdaddy' ? WBS_AVATAR_LOGO : null;
+ if (src && image && image.getAttribute('src') !== src) image.src = src;
});
+ if (!target) {
+ restoreAvatarDom();
+ return;
+ }
if (wrap && target) {
rememberAvatarWrapper(wrap);
// 官方默认头像图片改用 visibility:hidden(保留占位与布局,仅不可见):
@@ -10544,6 +10768,67 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
sidebarReconcileAt: 0,
};
+ // Session sync uses this lightweight lifecycle feed as its dirty source.
+ // It is intentionally independent from the optional auto-continue switch:
+ // switching accounts must still know which sessions changed when that
+ // feature is disabled.
+ var sessionDirtyResource = null;
+ var sessionDirtyUnsubscribe = null;
+ var sessionDirtyRetryTimer = null;
+ var sessionDirtyUid = '';
+ api('/api/current').then(function (current) {
+ sessionDirtyUid = String(current && current.uid || '').trim();
+ }).catch(function () {});
+ var sessionDirtyTracker = createSessionDirtyTracker(function (payload) {
+ var body = payload && Array.isArray(payload) ? { events: payload } : (payload || {});
+ if (sessionDirtyUid) body.uid = sessionDirtyUid;
+ api('/api/sessions/dirty', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ }).catch(function () {});
+ });
+ function sessionDirtyResourceRecords(resource) {
+ if (!resource || typeof resource.list !== 'function') return null;
+ try {
+ var result = resource.list();
+ return Promise.resolve(result).then(function (value) {
+ if (Array.isArray(value)) return value;
+ if (!value || typeof value !== 'object') return [];
+ return value.agents || value.sessions || value.conversations || value.records || [];
+ });
+ } catch (_) { return null; }
+ }
+ function bindSessionDirtyMonitor() {
+ if (sessionDirtyResource || !WBS_COMPAT || typeof WBS_COMPAT.findSessionsResource !== 'function') return !!sessionDirtyResource;
+ var resource = null;
+ try { resource = WBS_COMPAT.findSessionsResource(document); } catch (_) {}
+ if (!resource) {
+ if (!sessionDirtyRetryTimer) sessionDirtyRetryTimer = setTimeout(function () {
+ sessionDirtyRetryTimer = null;
+ bindSessionDirtyMonitor();
+ }, 1500);
+ return false;
+ }
+ sessionDirtyResource = resource;
+ sessionDirtyUnsubscribe = subscribeSessionMonitorResource(resource, function (update) {
+ sessionDirtyTracker.observe(update);
+ });
+ var snapshot = sessionDirtyResourceRecords(resource);
+ if (snapshot) snapshot.then(function (records) { sessionDirtyTracker.baseline(records); }).catch(function () {});
+ return true;
+ }
+ bindSessionDirtyMonitor();
+ registerDisposer(function () {
+ if (sessionDirtyRetryTimer) { clearTimeout(sessionDirtyRetryTimer); sessionDirtyRetryTimer = null; }
+ if (typeof sessionDirtyUnsubscribe === 'function') {
+ try { sessionDirtyUnsubscribe(); } catch (_) {}
+ }
+ sessionDirtyUnsubscribe = null;
+ sessionDirtyResource = null;
+ sessionDirtyTracker.destroy();
+ });
+
/** 状态机可视化日志:只写入当前 renderer 的有界内存,不落盘、不发送到 daemon。 */
var AC_LOG_MAX = 150;
var acLogLines = [];
@@ -10881,7 +11166,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
* 不依赖输入框 DOM 与 CDP。只有控制器缺失/调用失败时才回退旧发送链。 */
function acSendViaController(gen, controller, assistantId) {
if (gen !== acCtx.generation || !controller || typeof controller.sendPrompt !== 'function') return false;
- var activeId = acActiveConversationId();
+ var activeId = typeof acActiveConversationId === 'function' ? acActiveConversationId() : '';
if (activeId && String(activeId) !== String(controller.conversationId || '')) {
acLog('controller-send-session-mismatch', { activeId: activeId, controllerId: controller.conversationId || '' });
acStartMonitor();
@@ -11113,6 +11398,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
assistant: assistant,
assistantId: assistant && String(assistant.id || assistant.requestId || ''),
text: text,
+ completionMarker: acHasMarker(text),
complete: !!(assistant && assistant.complete === true),
terminalKnown: Object.prototype.hasOwnProperty.call(extra, 'isRequestTerminal'),
terminal: !!(assistant && extra.isRequestTerminal === true),
@@ -11192,17 +11478,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
acScheduleSettle(Math.max(250, AC_CONTROLLER_SETTLE_MS - idleFor));
return;
}
- var decision = classifyAutoContinueControllerSnapshot({
- assistantId: snap.assistantId,
- busy: snap.busy,
- manualStop: snap.manualStop,
- error: snap.error,
- networkFailure: snap.networkFailure,
- completionMarker: acHasMarker(snap.text),
- // 新版明确暴露 isRequestTerminal 时只认该字段;旧版没有该字段才退回 complete。
- complete: snap.terminalKnown ? false : snap.complete,
- terminal: snap.terminal,
- });
+ var decision = controllerAutoContinueDecision(snap);
c.judgedMessages.add(signature);
if (!decision.trigger) {
acLog('controller-completed', { id: snap.assistantId, reason: decision.reason, complete: snap.complete, terminal: snap.terminal });
@@ -11226,7 +11502,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
c.controllerLastBusy = snap.busy;
c.controllerIdleAt = snap.busy ? 0 : Date.now();
c.baselineAssistantKey = preserve ? String(carry.baselineAssistantKey || '') : (snap.assistantId || '');
- c.awaitingNewReply = preserve ? !!carry.awaitingNewReply : true;
+ // 已中断的会话不会有新回复:awaitingNewReply 置 true 会让 acControllerCheck 的
+ // baseline 分支永久 return,当前这条被中断的回复一次都判不到(与多会话监控同一缺陷)。
+ c.awaitingNewReply = preserve
+ ? (!!carry.awaitingNewReply && !isSessionMonitorInterrupted(snap))
+ : !isSessionMonitorInterrupted(snap);
c.judgedMessages = new Set(preserve && Array.isArray(carry.judgedMessages) ? carry.judgedMessages : []);
c.controllerUnsubs = [];
var notify = function () {
@@ -11236,7 +11516,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
try { c.controllerUnsubs.push(controller.sessionStore.subscribe(notify)); } catch (e) {}
try { c.controllerUnsubs.push(controller.messageStore.subscribe(notify)); } catch (e) {}
acLog('controller-monitor-start', { id: snap.conversationId, assistantId: snap.assistantId, busy: snap.busy, version: snap.version });
- acLog('baseline-established', { via: 'controller', awaitingNewReply: true });
+ acLog('baseline-established', { via: 'controller', awaitingNewReply: c.awaitingNewReply });
acStartStatusAnim();
return true;
}
@@ -11348,10 +11628,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}, ms);
}
- /** Auto-Continue 专用的「当前激活会话 ID」:优先级 adapter.currentActiveSessionId(官方,最可靠)
- * → URL 参数 conversationId/conversation_id → active/aria-selected=true 的官方 data-conversation-id。
- * 全部取不到返回 '';绝不回退到任意会话、标题或文本(共享的 getConversationId 有任意会话兜底,本模块不用) */
+ /** 当前激活会话 ID:官方 SDK getter 是唯一首选通道。
+ * 它实时读取 conversationCurrentStore,不依赖 DOM,也不会从 fiber 上散落的
+ * 残留 UUID 中误选。旧版客户端再依次回退到 adapter、URL 和选中节点。 */
function acActiveConversationId() {
+ try {
+ var conversations = window.wb && window.wb.conversations;
+ var officialId = conversations && conversations.currentId;
+ if (officialId) return String(officialId);
+ // A mounted official SDK with no currentId is authoritative too. Do
+ // not fall back to a stale adapter/DOM id during its null hydration
+ // window (the SDK emits that transient state during a switch).
+ if (conversations && 'currentId' in conversations) return '';
+ } catch (e) {}
try {
var a = window.__wbsAdapter;
if (a && a.currentActiveSessionId) return a.currentActiveSessionId;
@@ -11372,7 +11661,31 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return '';
}
- /** 会话身份签名:当前激活会话的官方 conversation ID(adapter 优先,其次 URL 参数 / active 的 data-conversation-id)。
+ // Account switching runs immediately before a renderer reload. During the
+ // SDK's null-hydration window `acActiveConversationId()` intentionally
+ // returns empty for monitor safety, but the mounted document/sidebar still
+ // identifies the conversation the user is looking at. Capture that
+ // concrete id only for the switch request; never use it for monitor logic.
+ function acSwitchConversationId() {
+ var id = acActiveConversationId();
+ if (id) return String(id);
+ try {
+ var root = document.querySelector('.cr-document[data-root-id]');
+ id = root && root.getAttribute('data-root-id');
+ if (id) return String(id);
+ } catch (_) {}
+ try {
+ var selected = document.querySelector(
+ '[data-conversation-id].active,[data-conversation-id][aria-selected="true"],' +
+ '[data-conversation-id][class*="active"]'
+ );
+ id = selected && (selected.getAttribute('data-conversation-id') || selected.getAttribute('data-id'));
+ if (id) return String(id);
+ } catch (_) {}
+ return '';
+ }
+
+ /** 会话身份签名:当前激活会话的官方 conversation ID(SDK 优先,其次旧版回退通道)。
* 取不到返回 '' → 调用方保守跳过判定(绝不回退任意会话/标题/文本) */
function acSessionSig(sessionRoot) {
try {
@@ -11814,16 +12127,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
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,
- });
+ var decision = controllerAutoContinueDecision(snapshot);
session.judgedMessages.add(signature);
if (!decision.trigger) {
acMultiFinishSession(session);
@@ -11851,7 +12155,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return existing;
}
var initialSnapshot = acControllerSnapshot(controller);
- if (!existing && !isSessionMonitorInProgress(initialSnapshot)) return null;
+ // 已中断(空闲 + 判定层愿意续跑)的会话也必须绑定一次:它不会再产生新回复,
+ // 只按 in-progress 过滤会让它永远进不了监控,Auto-Continue 对它完全失效。
+ if (!existing && !isSessionMonitorInProgress(initialSnapshot) && !isSessionMonitorInterrupted(initialSnapshot)) return null;
var session = existing || acMultiCreateSession({
id: id,
title: acSessionTitle(controller),
@@ -11873,12 +12179,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 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 || '';
+ if (isSessionMonitorInterrupted(initialSnapshot)) {
+ // 已中断的会话没有「新回复」可等:保留 baseline + awaitingNewReply 会让
+ // acMultiCheckSession 的等待分支立刻注销会话(acMultiFinishSession),
+ // 一次判定都走不到。改为放行对当前这条被中断回复的判定。
+ session.awaitingNewReply = false;
+ session.baselineAssistantKey = '';
+ } else {
+ 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);
+ if (initialSnapshot && (isSessionMonitorInProgress(initialSnapshot) || isSessionMonitorInterrupted(initialSnapshot) || !session.resourceActive)) acMultiCheckSession(session);
return session;
}
@@ -12433,13 +12747,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
setConversationUsageEnabled(sessState.usageSummary);
});
}
- var swQ = pane2.querySelector('#wbs-sess-selection-quote');
- if (swQ) swQ.addEventListener('change', function () {
- sessState.selectionQuote = !!this.checked;
- writeSelectionQuoteEnabled(sessState.selectionQuote);
- if (!sessState.selectionQuote) hideSelectionQuoteButton();
- else scheduleSelectionQuoteButton();
- });
var swF = pane2.querySelector('#wbs-sess-fork');
if (swF) {
swF.checked = sessState.fork;
@@ -12824,6 +13131,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// until-done 模式:轮询所有已发现会话;全部结束后自动恢复 allow。
var sleepUntilDoneSession = null; // 兼容旧字段;全量模式不再锁定单一会话
function discoverSleepSessionBusy() {
+ var wantedIds = arguments[0];
var controllers = [];
try {
if (WBS_COMPAT && typeof WBS_COMPAT.findConversationControllers === 'function') {
@@ -12843,13 +13151,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
cached.lastSeen = now;
var snapshot = acControllerSnapshot(controller);
cached.wasBusy = !!(snapshot && (snapshot.busy || snapshot.blocked || snapshot.hydrating));
- if (cached.wasBusy) busy = true;
+ if (cached.wasBusy && (!wantedIds || wantedIds[id])) 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;
+ if (cached.wasBusy && (!wantedIds || wantedIds[id]) && now - cached.lastSeen < 15000) busy = true;
else if (now - cached.lastSeen >= 15000) delete sleepSessionCache[id];
});
return busy;
@@ -12868,9 +13176,34 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (discoverSleepSessionBusy()) return true;
return !!isSessionBusy(null).busy;
}
+ function isAnySessionBusyForIds(ids) {
+ var wanted = Object.create(null);
+ if (Array.isArray(ids)) {
+ for (var i = 0; i < ids.length; i++) {
+ var id = String(ids[i] || '').trim();
+ if (id) wanted[id] = true;
+ }
+ }
+ if (!Object.keys(wanted).length) return isAnySessionBusy();
+ var known = Object.keys(wanted);
+ for (var j = 0; j < known.length; j++) {
+ var session = acMulti.sessions[known[j]];
+ 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;
+ var cached = sleepSessionCache[known[j]];
+ if (cached && cached.wasBusy && Date.now() - cached.lastSeen < 15000) return true;
+ }
+ if (discoverSleepSessionBusy(wanted)) return true;
+ var activeId = typeof acActiveConversationId === 'function' ? acActiveConversationId() : '';
+ return !!(activeId && wanted[String(activeId)] && isSessionBusy(activeId).busy);
+ }
var sessionBusyProbe = function () { return alive ? isAnySessionBusy() : null; };
+ var sessionBusyIdsProbe = function (ids) { return alive ? isAnySessionBusyForIds(ids) : null; };
window.__wbsAnySessionBusy = sessionBusyProbe;
+ window.__wbsSessionsBusy = sessionBusyIdsProbe;
registerDisposer(function () { if (window.__wbsAnySessionBusy === sessionBusyProbe) delete window.__wbsAnySessionBusy; });
+ registerDisposer(function () { if (window.__wbsSessionsBusy === sessionBusyIdsProbe) delete window.__wbsSessionsBusy; });
function startUntilDoneCheck() {
if (sleepUntilDoneCheck) return;
sleepUntilDoneSession = null;
@@ -13425,12 +13758,70 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return Math.max(0, (Number(job.partial) || 0) + (Number(job.failed) || 0));
}
+ function sessionCopyIsNoop(job) {
+ if (!job || job.status !== 'done') return false;
+ if ((Number(job.copied) || 0) || (Number(job.failed) || 0) ||
+ (Number(job.failedItems) || 0) || (Number(job.partial) || 0) ||
+ (Number(job.conflicts) || 0)) return false;
+ var details = Array.isArray(job.details) ? job.details : [];
+ return !details.some(function (item) {
+ var status = String(item && item.status || '');
+ return status === 'copied' || status === 'failed' || status === 'partial' || status === 'conflict';
+ });
+ }
+
function sessionCopySummaryText(job) {
- return '同步 ' + (Number(job && job.copied) || 0) + ' · 跳过 ' + (Number(job && job.skipped) || 0) +
+ return '同步 ' + (Number(job && job.copied) || 0) +
' · 失败 ' + (sessionCopyFailedItems(job) + (Number(job && job.conflicts) || 0)) +
(job && job.warning ? ' · ' + job.warning : '');
}
+ function sessionCopyItemFailed(item) {
+ var status = String(item && item.status || '');
+ return status === 'failed' || status === 'partial' || status === 'conflict';
+ }
+
+ function sessionCopyNoticeGroups(job) {
+ var details = Array.isArray(job && job.details) ? job.details : [];
+ return {
+ copied: details.filter(function (item) {
+ return String(item && item.status || '') === 'copied';
+ }),
+ failed: details.filter(function (item) {
+ return sessionCopyItemFailed(item);
+ }),
+ };
+ }
+
+ function renderSessionCopyNoticeSummary(node, job) {
+ node.textContent = '';
+ var groups = sessionCopyNoticeGroups(job);
+ [
+ { key: 'copied', label: '同步成功', className: 'is-copied' },
+ { key: 'failed', label: '同步失败', className: 'is-failed' },
+ ].forEach(function (definition) {
+ var items = groups[definition.key];
+ if (!items.length) return;
+ var group = document.createElement('div');
+ group.className = 'wbs-session-copy-summary-group ' + definition.className;
+ var badge = document.createElement('div');
+ badge.className = 'wbs-session-copy-summary-label';
+ badge.textContent = definition.label + ' ' + items.length;
+ group.appendChild(badge);
+ items.slice(0, 3).forEach(function (item) {
+ var line = document.createElement('div');
+ var label = String(item && item.label || '未命名会话');
+ line.className = 'wbs-session-copy-summary-line ' + definition.className;
+ line.textContent = label;
+ line.title = label;
+ group.appendChild(line);
+ });
+ node.appendChild(group);
+ });
+ node.hidden = !groups.copied.length && !groups.failed.length;
+ return groups;
+ }
+
function sessionCopySizeText(bytes) {
if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return '—';
var units = ['B', 'KB', 'MB', 'GB', 'TB'];
@@ -13440,12 +13831,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function sessionCopyTransferText(job) {
- if (!job) return '';
- var completed = typeof job.processedBytes === 'number' && Number.isFinite(job.processedBytes)
- ? Math.max(0, job.processedBytes) : job.copiedBytes;
- var total = typeof job.totalBytes === 'number' && Number.isFinite(job.totalBytes) ? Math.max(0, job.totalBytes) : null;
- if (typeof completed !== 'number' || !Number.isFinite(completed)) return '';
- return '已同步 ' + sessionCopySizeText(completed) + (total == null ? '' : ' / ' + sessionCopySizeText(total));
+ // Transfer byte details are intentionally hidden from the user-facing
+ // sync notice; the session count and status already communicate progress.
+ return '';
}
function sessionCopyCountText(value) {
@@ -13463,7 +13851,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var statusLabels = { copied: '已同步', skipped: '已跳过', partial: '部分失败', failed: '失败', conflict: '未同步', running: '处理中' };
var tabDefs = [
{ id: 'copied', label: '成功', count: details.filter(function (item) { return item && item.status === 'copied'; }).length },
- { id: 'skipped', label: '跳过', count: details.filter(function (item) { return item && item.status === 'skipped'; }).length },
{ id: 'failed', label: '失败', count: details.filter(function (item) { return item && (item.status === 'failed' || item.status === 'partial' || item.status === 'conflict'); }).length },
];
mask.innerHTML = '<div class="wbs-modal wbs-session-copy-details" role="dialog" aria-modal="true" aria-labelledby="wbs-session-copy-details-title">' +
@@ -13551,7 +13938,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
node.className = 'wbs-session-copy-notice';
node.setAttribute('role', 'status');
node.setAttribute('aria-live', 'polite');
- node.innerHTML = '<div class="wbs-session-copy-head"><span class="wbs-session-copy-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 1v1"/></svg></span><strong class="wbs-session-copy-title">正在同步会话</strong><span class="wbs-session-copy-count">0 / 0</span><button type="button" class="wbs-session-copy-close" aria-label="关闭" title="关闭">×</button></div>' +
+ node.innerHTML = '<div class="wbs-session-copy-head"><span class="wbs-session-copy-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 1v1"/></svg></span><strong class="wbs-session-copy-title">正在同步会话</strong><button type="button" class="wbs-session-copy-close" aria-label="关闭" title="关闭">×</button></div>' +
'<div class="wbs-session-copy-route"></div><div class="wbs-session-copy-track" role="progressbar" aria-label="会话同步进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><span class="wbs-session-copy-fill"></span></div><div class="wbs-session-copy-transfer" title="同步数据量"></div><div class="wbs-session-copy-status"></div><div class="wbs-session-copy-summary"></div><div class="wbs-session-copy-actions" hidden><button type="button" class="wbs-session-copy-details-btn" data-session-copy-details>查看明细</button><span class="wbs-session-copy-countdown"></span></div>';
document.body.appendChild(node);
state.sessionCopyNotice = { node: node, jobId: job.id, job: null, timer: null, countdownTimer: null, closeScheduled: false, place: placeSessionCopyNotice };
@@ -13573,18 +13960,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
job.status === 'error' ? '同步任务未完成,请稍后重试' : '';
node.className = 'wbs-session-copy-notice is-' + String(job.status || 'running');
node.querySelector('.wbs-session-copy-title').textContent = title;
- node.querySelector('.wbs-session-copy-count').textContent = processed + ' / ' + total;
node.querySelector('.wbs-session-copy-route').textContent = sourceLabel + ' → ' + targetLabel;
node.querySelector('.wbs-session-copy-status').textContent = status;
node.querySelector('.wbs-session-copy-status').hidden = !active && job.status !== 'error';
var summary = node.querySelector('.wbs-session-copy-summary');
- summary.textContent = active ? '' : sessionCopySummaryText(job);
- summary.hidden = active;
+ var noticeGroups = null;
+ if (active) {
+ summary.textContent = '';
+ summary.hidden = true;
+ } else {
+ noticeGroups = renderSessionCopyNoticeSummary(summary, job);
+ var hasResultDetails = noticeGroups.copied.length > 0 || noticeGroups.failed.length > 0;
+ node.querySelector('[data-session-copy-details]').hidden = !hasResultDetails;
+ }
var transfer = node.querySelector('.wbs-session-copy-transfer');
transfer.textContent = sessionCopyTransferText(job);
transfer.hidden = !transfer.textContent;
var actions = node.querySelector('.wbs-session-copy-actions');
- actions.hidden = active;
+ actions.hidden = active || !(noticeGroups && (noticeGroups.copied.length || noticeGroups.failed.length));
var track = node.querySelector('.wbs-session-copy-track');
track.setAttribute('aria-valuenow', String(percent));
track.setAttribute('aria-valuetext', title + ',' + processed + '/' + total);
@@ -13592,14 +13985,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
placeSessionCopyNotice();
if (!active && !notice.closeScheduled) {
notice.closeScheduled = true;
- var remaining = 5;
+ var copiedCount = Math.max(0, Number(job && job.copied) || 0);
+ var failedCount = sessionCopyFailedItems(job) + (Number(job && job.conflicts) || 0);
+ var countdownSeconds = copiedCount || failedCount ? 5 : 3;
+ var remaining = countdownSeconds;
var countdown = node.querySelector('.wbs-session-copy-countdown');
countdown.textContent = remaining + ' 秒后自动关闭';
notice.countdownTimer = setInterval(function () {
remaining--;
if (remaining > 0) countdown.textContent = remaining + ' 秒后自动关闭';
}, 1000);
- notice.timer = setBuildTimeout(closeSessionCopyNotice, 5000);
+ notice.timer = setBuildTimeout(closeSessionCopyNotice, countdownSeconds * 1000);
}
}
@@ -13632,11 +14028,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
state.sessionCopyNoticeChecked = true;
state.sessionCopyNoticeActiveAttempts = 0;
+ if (sessionCopyIsNoop(job)) {
+ closeSessionCopyNotice();
+ if (job.openSessionId) setBuildTimeout(function () { openCopiedSession(job.openSessionId); }, 1000);
+ setBuildTimeout(refresh, 900);
+ return;
+ }
renderSessionCopyNotice(job, accountName);
renderSessionCopyProgress(job);
if (job.status === 'queued' || job.status === 'running') {
state.sessionCopyNoticePollTimer = setBuildTimeout(function () { pollSessionCopyNotice(job.id, accountName); }, 700);
} else {
+ // Give the newly switched renderer one turn to finish session
+ // hydration before invoking the official navigation handler.
+ if (job.openSessionId) setBuildTimeout(function () { openCopiedSession(job.openSessionId); }, 1000);
setBuildTimeout(refresh, 900);
}
}).catch(function () {
@@ -13656,6 +14061,145 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
pollSessionCopyNotice(jobId, accountName);
}
+ function openCopiedSession(sessionId, startedAt) {
+ var id = String(sessionId || '').trim();
+ var started = Number(startedAt) || Date.now();
+ var attempt = Number(arguments[2]) || 0;
+ // A copied row can become visible only after the post-reload session
+ // store hydrates. Keep this bounded, but do not treat an emitted jump
+ // event as success until the renderer reports the requested session.
+ var OPEN_SESSION_TIMEOUT = 15000;
+ function shortId(value) {
+ var text = String(value || '');
+ return text.length > 12 ? text.slice(0, 8) + '…' + text.slice(-4) : text;
+ }
+ function activationLog(event, extra) {
+ try {
+ var payload = Object.assign({ event: event, target: shortId(id), attempt: attempt, elapsedMs: Math.max(0, Date.now() - started) }, extra || {});
+ console.log('[session-activation] ' + JSON.stringify(payload));
+ } catch (_) {}
+ }
+ if (!id) {
+ activationLog('skip-empty-id');
+ return;
+ }
+ if (Date.now() - started >= OPEN_SESSION_TIMEOUT) {
+ activationLog('timeout');
+ return;
+ }
+
+ function isActive() {
+ try {
+ if (typeof acActiveConversationId === 'function' && String(acActiveConversationId() || '') === id) return true;
+ } catch (_) {}
+ try {
+ var root = document.querySelector('.cr-document[data-root-id]');
+ if (root && String(root.getAttribute('data-root-id') || '') === id) return true;
+ } catch (_) {}
+ return false;
+ }
+
+ function currentIds() {
+ var sdk = '', dom = '';
+ try { sdk = typeof acActiveConversationId === 'function' ? String(acActiveConversationId() || '') : ''; } catch (_) {}
+ try {
+ var root = document.querySelector('.cr-document[data-root-id]');
+ dom = root ? String(root.getAttribute('data-root-id') || '') : '';
+ } catch (_) {}
+ return { sdk: shortId(sdk), dom: shortId(dom) };
+ }
+
+ // The official adapter owns route/state activation. Its session resource
+ // becomes aware of copied rows slightly after the daemon reports done, so
+ // poll that API before considering any DOM fallback.
+ var activationApi = null;
+ try {
+ activationApi = WBS_COMPAT && typeof WBS_COMPAT.findConversationActivationApi === 'function'
+ ? WBS_COMPAT.findConversationActivationApi(document) : null;
+ } catch (_) {}
+ function confirmActivation() {
+ setBuildTimeout(function () {
+ var active = isActive();
+ activationLog(active ? 'confirmed' : 'not-confirmed', { current: currentIds() });
+ if (active) return;
+ if (Date.now() - started < OPEN_SESSION_TIMEOUT) openCopiedSession(id, started, attempt + 1);
+ }, 350);
+ }
+ activationLog('probe', { activationApi: !!activationApi, current: currentIds() });
+ if (activationApi) {
+ Promise.resolve(activationApi.hasSession(id)).then(function (found) {
+ activationLog('has-session', { found: found, current: currentIds() });
+ if (found === true || found === null) {
+ if (isActive()) {
+ activationLog('already-active', { current: currentIds() });
+ return;
+ }
+ var activated = false;
+ try { activated = activationApi.activate(id); } catch (_) { activated = false; }
+ activationLog('activate-called', { returned: activated, current: currentIds() });
+ if (activated && activationApi.authoritative === true) {
+ // The official navigation handler emits the renderer's session
+ // switch itself. Older WorkBuddy builds do not expose the active
+ // id through either projection used by this injector, so a
+ // second call is only attempted when a modern resource claimed
+ // the target but the active projection did not confirm it.
+ activationLog('official-dispatched', { current: currentIds() });
+ if (found === true) confirmActivation();
+ return;
+ }
+ // Navigation handlers update the SDK/DOM asynchronously. Confirm
+ // the resulting current ID before stopping; otherwise a no-op
+ // adapter.emit can make account switching appear successful.
+ confirmActivation();
+ return;
+ }
+ if (found === false && activationApi.authoritative === true && attempt >= 4) {
+ var lateActivated = false;
+ try { lateActivated = activationApi.activate(id); } catch (_) { lateActivated = false; }
+ activationLog(lateActivated ? 'official-dispatched-unverified' : 'activate-failed', { current: currentIds() });
+ if (lateActivated) {
+ // A false resource probe can race session hydration. Confirm the
+ // dispatch and retry if the target is still not active.
+ confirmActivation();
+ return;
+ }
+ }
+ if (Date.now() - started < OPEN_SESSION_TIMEOUT) {
+ setBuildTimeout(function () { openCopiedSession(id, started, attempt + 1); }, 500);
+ }
+ }).catch(function () {
+ activationLog('has-session-error', { current: currentIds() });
+ if (Date.now() - started < OPEN_SESSION_TIMEOUT) {
+ setBuildTimeout(function () { openCopiedSession(id, started, attempt + 1); }, 500);
+ }
+ });
+ return;
+ }
+
+ // Older clients have no activation event; retain the narrow DOM fallback
+ // for those versions, with the same five-second readiness budget.
+ var nodes = document.querySelectorAll('[data-conversation-id]');
+ for (var i = 0; i < nodes.length; i++) {
+ if (String(nodes[i].getAttribute('data-conversation-id') || '') !== id) continue;
+ var rect = nodes[i].getBoundingClientRect();
+ if (rect.width > 0 && rect.height > 0) {
+ var clicked = false;
+ try { nodes[i].click(); clicked = true; } catch (_) {}
+ activationLog('dom-click', { returned: clicked, current: currentIds() });
+ setBuildTimeout(function () {
+ var active = isActive();
+ activationLog(active ? 'confirmed' : 'not-confirmed', { source: 'dom', current: currentIds() });
+ if (!active && Date.now() - started < OPEN_SESSION_TIMEOUT) openCopiedSession(id, started, attempt + 1);
+ }, 350);
+ return;
+ }
+ }
+ if (Date.now() - started < OPEN_SESSION_TIMEOUT) {
+ activationLog('target-not-mounted', { current: currentIds() });
+ setBuildTimeout(function () { openCopiedSession(id, started, attempt + 1); }, 500);
+ }
+ }
+
// token 过期状态:< 7 天 / 已过期 -> 红字高亮
function tokenState(expiresAt, account) {
if (isIdentityExpired(account) && expiresAt) return { warn: true, expired: true, label: '已过期 ' + fmtDateTime(expiresAt) };
@@ -13762,7 +14306,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
api('/api/switch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ uid: btn.dataset.uid, reload: true }),
+ body: JSON.stringify({
+ uid: btn.dataset.uid,
+ reload: true,
+ currentConversationId: acSwitchConversationId(),
+ }),
})
.then(function (r) {
var autoCopy = r && r.autoCopy;
@@ -14010,7 +14558,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (closeButton) closeButton.textContent = '关闭(' + Math.max(0, remaining) + ')';
if (remaining <= 0) closeRotationNotice();
}, 1000);
- state.rotationNotice = { node: node, timer: timer, uid: candidate.uid };
+ // Capture the official active conversation while the suggestion is
+ // created. The popup itself is outside the WorkBuddy conversation tree,
+ // and a later renderer refresh may briefly expose a null currentId.
+ var rotationConversationId = typeof acActiveConversationId === 'function' ? acActiveConversationId() : '';
+ if (!rotationConversationId) rotationConversationId = acSwitchConversationId();
+ state.rotationNotice = { node: node, timer: timer, uid: candidate.uid, conversationId: rotationConversationId };
fab.classList.add('wbs-fab-credit-alert');
node.querySelector('.wbs-credit-rotation-close').addEventListener('click', closeRotationNotice);
var todayBtn = node.querySelector('.wbs-credit-rotation-today');
@@ -14023,7 +14576,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (button.disabled) return;
button.disabled = true;
button.textContent = '切换中…';
- api('/api/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ uid: candidate.uid, reload: true }) })
+ var currentConversationId = state.rotationNotice && state.rotationNotice.conversationId;
+ if (!currentConversationId) currentConversationId = acSwitchConversationId();
+ api('/api/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ uid: candidate.uid, reload: true, currentConversationId: currentConversationId || '' }) })
.then(function (result) {
closeRotationNotice();
toast('已切换为「' + (result.nickname || candidate.nickname || candidate.uid) + '」', false, root);
@@ -14506,8 +15061,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
try { ensureAutoContinueMonitor(); } catch (e) {}
// 注入完成即同步会话模块状态(暂存/快捷短语开关 + 短语列表)并应用到输入框按钮显隐
try { syncSessionModule(); } catch (e) {}
- // 选区引用按钮默认开启;开关关闭时仅保留监听器,重新开启无需重注入。
- try { setupSelectionQuote(); } catch (e) {}
// 打开面板时校验指令块是否丢失,丢失则自动关闭开关(不弹 toast)
try { acCheckPromptOnOpen(); } catch (e) {}
// 按钮主题色(浅色黑底白图 / 深色白底黑图)+ 监听主题切换
@@ -14625,10 +15178,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'html.cb-dark .sq-tooltip-wrapper{background:var(--wb-bg-popover,#202126)!important;border-color:color-mix(in srgb,var(--wb-border-subtle,#ececec) 65%,transparent)!important;color:var(--wb-color-text-primary,#f2f3f5)}',
/* 复用 WorkBuddy 官方 InputContextTag 的消息图标与关闭图标,仅修正 sceneTag 的 hover 覆盖规则。 */
'.slate-selection-quote-sceneTag._hasCloseIcon:hover [class*="iconContainer"],.slate-selection-quote-sceneTag__readOnly._hasCloseIcon:hover [class*="iconContainer"]{visibility:hidden!important}',
- '.wbs-selection-quote-btn{position:fixed;z-index:1000;display:none;align-items:center;justify-content:center;min-width:64px;height:30px;box-sizing:border-box;padding:0 10px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.18));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 7px 18px rgba(20,24,32,.2),inset 0 1px 0 rgba(255,255,255,.45);backdrop-filter:blur(12px) saturate(1.2);-webkit-backdrop-filter:blur(12px) saturate(1.2);cursor:pointer;outline:none;font:inherit;font-size:12px;line-height:1;white-space:nowrap;transition:background .15s,border-color .15s,box-shadow .15s;color-scheme:light}',
- '.wbs-selection-quote-btn:hover,.wbs-selection-quote-btn:focus-visible{background:color-mix(in srgb,var(--wb-bg-hover,#f3f3f3) 86%,transparent);border-color:var(--wb-border-default,#d5d5d5);box-shadow:0 8px 20px rgba(20,24,32,.2),inset 0 1px 0 rgba(255,255,255,.35)}',
- 'html.cb-dark .wbs-selection-quote-btn,html[data-theme="dark"] .wbs-selection-quote-btn,body[data-vscode-theme-name*="dark" i] .wbs-selection-quote-btn{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 70%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.16));color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 8px 22px rgba(0,0,0,.4),inset 0 1px 0 rgba(255,255,255,.08);color-scheme:dark}',
- 'html.cb-dark .wbs-selection-quote-btn:hover,html.cb-dark .wbs-selection-quote-btn:focus-visible,html[data-theme="dark"] .wbs-selection-quote-btn:hover,html[data-theme="dark"] .wbs-selection-quote-btn:focus-visible,body[data-vscode-theme-name*="dark" i] .wbs-selection-quote-btn:hover,body[data-vscode-theme-name*="dark" i] .wbs-selection-quote-btn:focus-visible{background:color-mix(in srgb,var(--wb-bg-hover,#303238) 84%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.2));box-shadow:0 9px 24px rgba(0,0,0,.38),inset 0 1px 0 rgba(255,255,255,.08)}',
'html.cb-dark .wbs-message-nav-rail,html[data-theme="dark"] .wbs-message-nav-rail,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 14%,transparent);border-color:transparent;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}',
'html.cb-dark .wbs-message-nav-rail:hover,html.cb-dark .wbs-message-nav-rail:focus-within,html[data-theme="dark"] .wbs-message-nav-rail:hover,html[data-theme="dark"] .wbs-message-nav-rail:focus-within,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail:hover,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail:focus-within{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 44%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.12));box-shadow:0 6px 20px rgba(0,0,0,.28);backdrop-filter:blur(14px) saturate(1.12);-webkit-backdrop-filter:blur(14px) saturate(1.12)}',
'html.cb-dark .wbs-message-nav-tooltip,html[data-theme="dark"] .wbs-message-nav-tooltip,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-tooltip{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 70%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.14));color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 14px 38px rgba(0,0,0,.42),inset 0 1px 0 rgba(255,255,255,.08)}',
@@ -14641,6 +15190,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-fab[data-wbs-robot-style="black"]{--wbs-robot-shell:#111;--wbs-robot-eye:#fff;--wbs-robot-rim:rgba(255,255,255,.14)}',
'.wbs-fab[data-wbs-robot-style="glass"]{--wbs-robot-shell:color-mix(in srgb,var(--wb-bg-popover,#fff) 42%,transparent);--wbs-robot-eye:transparent;--wbs-robot-blur:blur(14px) saturate(1.3);--wbs-robot-rim:color-mix(in srgb,var(--wb-color-text-primary,#222) 18%,transparent)}',
'.wbs-fab[data-wbs-robot-style="white"]{--wbs-robot-shell:#fff;--wbs-robot-eye:#111;--wbs-robot-rim:rgba(255,255,255,.55)}',
+ '.wbs-root[data-wbs-robot-style="black"] .wbs-automation-stop{--wbs-robot-shell:#111;--wbs-robot-eye:#fff;--wbs-robot-rim:rgba(255,255,255,.14)}.wbs-root[data-wbs-robot-style="glass"] .wbs-automation-stop{--wbs-robot-shell:color-mix(in srgb,var(--wb-bg-popover,#fff) 42%,transparent);--wbs-robot-eye:var(--wb-color-text-primary,#222);--wbs-robot-rim:color-mix(in srgb,var(--wb-color-text-primary,#222) 18%,transparent)}.wbs-root[data-wbs-robot-style="white"] .wbs-automation-stop{--wbs-robot-shell:#fff;--wbs-robot-eye:#111;--wbs-robot-rim:rgba(0,0,0,.12)}',
+ '.wbs-automation-stop{position:fixed;z-index:2147483647;box-sizing:border-box;min-width:94px;height:32px;padding:0 11px;border:1px solid var(--wbs-robot-rim,rgba(255,255,255,.14));border-radius:8px;background:var(--wbs-robot-shell,#111);color:var(--wbs-robot-eye,#fff);box-shadow:0 3px 10px rgba(0,0,0,.18);display:flex;align-items:center;justify-content:center;gap:6px;cursor:pointer;font:inherit;font-size:12px;line-height:1;letter-spacing:0;white-space:nowrap;transition:opacity .15s,box-shadow .15s}.wbs-automation-stop[hidden]{display:none}.wbs-automation-stop:hover{box-shadow:0 4px 12px rgba(0,0,0,.24);opacity:.88}.wbs-automation-stop:focus-visible{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:3px}.wbs-automation-stop:disabled{cursor:default;opacity:.68}.wbs-automation-stop svg{flex:0 0 auto}.wbs-automation-stop-label{display:block}.wbs-automation-stop.is-stopping svg{opacity:.7}@keyframes wbs-auto-stopping{to{transform:rotate(360deg)}}',
'.wbs-fab{--wbs-robot-shell:#111;--wbs-robot-eye:#fff;--wbs-robot-blur:none;--wbs-robot-rim:rgba(255,255,255,.55);position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;will-change:transform;transition:transform .22s cubic-bezier(.22,1,.36,1)}',
'.wbs-fab-health-dot{position:absolute;top:-5px;left:-5px;width:14px;height:14px;border-radius:50%;background:#8b8f98;border:2px solid #141416;box-shadow:0 1px 3px rgba(0,0,0,.5);z-index:3}',
'.wbs-fab-health-dot.running{background:#4da3ff}.wbs-fab-health-dot.blocked{background:#ffb03a}.wbs-fab-health-dot.error{background:#ef6262}.wbs-fab-health-dot.suspected{background:#f08a3c}.wbs-fab-health-dot.stopped{background:#9ca3af}',
@@ -15031,7 +15582,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-sess-seg-btn.active{background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.2)}',
'.wbs-sess-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin-bottom:8px}',
'.wbs-sess-copy-progress{box-sizing:border-box;margin:0 0 8px;padding:9px 10px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 82%,transparent);box-shadow:0 2px 8px rgba(0,0,0,.04)}',
- '.wbs-sess-copy-progress[hidden]{display:none!important}.wbs-sess-copy-head{display:flex;align-items:center;gap:6px;min-width:0}.wbs-sess-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex:0 0 20px;border-radius:6px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 9%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-sess-copy-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11.5px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f)}.wbs-sess-copy-count{margin-left:auto;flex:0 0 auto;font-size:10.5px;font-variant-numeric:tabular-nums;color:var(--wb-icon-secondary,#667085)}',
+ '.wbs-sess-copy-progress[hidden]{display:none!important}.wbs-sess-copy-head{display:flex;align-items:center;gap:6px;min-width:0}.wbs-sess-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex:0 0 20px;border-radius:6px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 9%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-sess-copy-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11.5px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-sess-copy-detail{margin:4px 0 6px 26px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;line-height:1.35;color:var(--wb-icon-tertiary,#8a8f98)}.wbs-sess-copy-track{height:4px;margin-left:26px;overflow:hidden;border-radius:999px;background:var(--wb-bg-tertiary,#e9eaed)}.wbs-sess-copy-fill{display:block;height:100%;width:0;border-radius:inherit;background:var(--wb-accent-blue,var(--wb-button-primary-bg,#1f1f1f));transition:width .2s ease}.wbs-sess-copy-progress.is-done .wbs-sess-copy-fill{background:#2f9e63}.wbs-sess-copy-progress.is-partial .wbs-sess-copy-fill{background:#d48a19}.wbs-sess-copy-progress.is-error .wbs-sess-copy-fill{background:#d84a4a}',
'html.cb-dark .wbs-sess-copy-progress,html[data-theme="dark"] .wbs-sess-copy-progress,body[data-vscode-theme-name*="dark" i] .wbs-sess-copy-progress{border-color:var(--wb-border-default,rgba(255,255,255,.14));background:color-mix(in srgb,var(--wb-bg-secondary,#25262a) 88%,transparent);box-shadow:0 3px 12px rgba(0,0,0,.18)}',
'.wbs-sess-refresh{display:flex;align-items:center;justify-content:center;flex-shrink:0;padding:7px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#555);font-size:12px;cursor:pointer;line-height:1;transition:all .15s}',
@@ -15346,7 +15897,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-bg-upload-ico{width:30px;height:30px;border-radius:50%;background:var(--wb-bg-hover,#e8e9eb);display:flex;align-items:center;justify-content:center;font-size:18px;line-height:1;font-weight:400}',
'.wbs-bg-upload-hint{font-size:11px;color:var(--wb-icon-tertiary,#999);font-weight:400}',
'.wbs-bg-preview{display:none;width:100%;max-height:140px;object-fit:cover;border-radius:10px;margin-top:8px;border:1px solid var(--wb-border-subtle,#eee)}',
- '.wbs-avatar-option{position:relative;display:flex;flex-direction:column;align-items:center;gap:4px;cursor:pointer;font-size:10px;color:var(--wb-color-text-secondary)}.wbs-avatar-option input{position:absolute;opacity:0;width:1px;height:1px}.wbs-avatar-option img{box-sizing:border-box;width:42px;height:42px;padding:3px;object-fit:contain;border:1px solid var(--wb-border-subtle);border-radius:10px;background:var(--wb-bg-tertiary)}.wbs-avatar-option input:checked+img{border-color:var(--wb-button-primary-bg);box-shadow:0 0 0 1px var(--wb-button-primary-bg)}.wbs-avatar-option input:focus-visible+img{outline:2px solid var(--wb-accent-blue);outline-offset:3px}',
+ '.wbs-avatar-option{position:relative;display:flex;flex-direction:column;align-items:center;gap:4px;cursor:pointer;font-size:10px;color:var(--wb-color-text-secondary)}.wbs-avatar-option input{position:absolute;opacity:0;width:1px;height:1px}.wbs-avatar-option img,.wbs-avatar-default-mark{box-sizing:border-box;width:42px;height:42px;padding:3px;object-fit:contain;border:1px solid var(--wb-border-subtle);border-radius:10px;background:var(--wb-bg-tertiary)}.wbs-avatar-option input:checked+img,.wbs-avatar-option input:checked+.wbs-avatar-default-mark{border-color:var(--wb-button-primary-bg);box-shadow:0 0 0 1px var(--wb-button-primary-bg)}.wbs-avatar-option input:focus-visible+img,.wbs-avatar-option input:focus-visible+.wbs-avatar-default-mark{outline:2px solid var(--wb-accent-blue);outline-offset:3px}.wbs-avatar-default-mark{display:flex;align-items:center;justify-content:center;color:var(--wb-icon-secondary);font-size:18px;font-weight:600;line-height:1}',
/* 背景蒙版滑块(黑色半透明遮罩,0~100%) */
'.wbs-mask-row{display:flex;align-items:center;gap:8px;margin-top:8px}',
'.wbs-mask-row input[type=range]{flex:1;min-width:0;accent-color:#f2f2f4;height:4px;cursor:pointer}',
@@ -15367,6 +15918,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-account-order-list{margin-top:12px;max-height:min(280px,40vh);overflow:auto;overscroll-behavior:contain;display:flex;flex-direction:column;gap:5px}',
'.wbs-account-order-row{display:flex;align-items:center;gap:8px;min-height:34px;padding:3px 8px;border:1px solid var(--wb-border-subtle);border-radius:8px;background:var(--wb-bg-secondary);font-size:12px}.wbs-account-order-row>span{flex:1;min-width:0;overflow-wrap:anywhere}.wbs-account-order-row button{cursor:grab}.wbs-account-order-row.dragging{opacity:.45}.wbs-account-order-row.drop-target{border-color:var(--wb-accent-blue);background:var(--wb-bg-hover)}',
'.wbs-account-order-modal :is(button,input):focus-visible{outline:2px solid var(--wb-accent-blue);outline-offset:2px}.wbs-account-order-modal button:disabled{opacity:.5;cursor:default}',
+ '.wbs-initial-sync-modal{box-sizing:border-box;width:380px;max-width:calc(100% - 28px)}.wbs-initial-sync-copy{margin:-2px 0 12px;color:var(--wb-color-text-secondary,#666);font-size:11.5px;line-height:1.6;overflow-wrap:anywhere}.wbs-initial-sync-toggle{margin:0 0 10px}.wbs-initial-sync-error{min-height:17px;margin:0 0 2px}.wbs-initial-sync-modal .wbs-modal-actions{justify-content:flex-end}.wbs-initial-sync-modal .wbs-modal-ok{min-width:66px}',
'.wbs-credit-summary-popover{position:fixed;z-index:2147483647;box-sizing:border-box;width:300px;max-width:calc(100vw - 16px);padding:12px;background:var(--wb-bg-popover,var(--wb-bg-primary));color:var(--wb-color-text-primary);border:1px solid var(--wb-border-default);border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.18);font:12px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overflow:auto;overscroll-behavior:contain;pointer-events:auto}',
'.wbs-credit-summary-head{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px}.wbs-credit-summary-head strong{font-size:13px}.wbs-credit-summary-head span,.wbs-credit-summary-foot{font-size:10px;color:var(--wb-color-text-secondary)}',
'.wbs-credit-summary-chart{max-height:230px;overflow:auto;overscroll-behavior:contain}.wbs-credit-summary-row{display:grid;grid-template-columns:68px minmax(30px,1fr) 58px;align-items:center;gap:8px;min-height:28px}.wbs-credit-summary-row>span{font-size:11px;color:var(--wb-color-text-secondary)}.wbs-credit-summary-row>b{text-align:right;font-size:11px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.wbs-credit-summary-track{display:flex;align-items:stretch;gap:2px;height:8px;border-radius:4px;background:var(--wb-bg-tertiary);overflow:visible}.wbs-credit-summary-track .wbs-credit-segment{height:8px;min-width:3px}.wbs-credit-summary-track i{display:block;height:100%;border-radius:4px;}.wbs-credit-summary-foot{border-top:1px solid var(--wb-border-subtle);padding-top:8px;margin-top:8px}',
@@ -15409,9 +15961,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-session-copy-notice{position:fixed;z-index:2147483647;box-sizing:border-box;min-height:108px;padding:12px 13px 11px;border:1px solid var(--wb-border-subtle,rgba(0,0,0,.1));border-radius:13px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f2937);box-shadow:0 12px 34px rgba(0,0,0,.18);font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;animation:wbs-session-copy-in .2s cubic-bezier(.22,1,.36,1);pointer-events:auto}',
'@keyframes wbs-session-copy-in{from{opacity:0;transform:translateY(7px) scale(.985)}to{opacity:1;transform:translateY(0) scale(1)}}',
'.wbs-session-copy-head{display:flex;align-items:center;gap:7px;min-height:22px}',
- '.wbs-session-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:23px;height:23px;flex:0 0 23px;border-radius:7px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 11%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}',
+ '.wbs-session-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:23px;height:23px;flex:0 0 23px;border-radius:7px;background:color-mix(in srgb,#2e9b68 13%,transparent);color:#238a5b}',
'.wbs-session-copy-title{min-width:0;flex:1;font-size:12px;font-weight:700;line-height:1.35;overflow-wrap:anywhere}',
- '.wbs-session-copy-count{flex:0 0 auto;color:var(--wb-color-text-secondary,#667085);font-size:10.5px;font-variant-numeric:tabular-nums;white-space:nowrap}',
'.wbs-session-copy-close{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;flex:0 0 22px;margin:-2px -3px -2px 1px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--wb-icon-tertiary,#8a8f98);font:inherit;font-size:17px;line-height:1;cursor:pointer}',
'.wbs-session-copy-close:hover{background:var(--wb-bg-hover,#f5f6f8);color:var(--wb-color-text-primary,#1f2937)}',
'.wbs-session-copy-close:focus-visible{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:1px}',
@@ -15420,13 +15971,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-session-copy-fill{display:block;width:0;height:100%;border-radius:inherit;background:var(--wb-button-primary-bg,#1f1f1f);transition:width .25s ease}',
'.wbs-session-copy-status{min-height:16px;margin-top:7px;color:var(--wb-color-text-secondary,#667085);font-size:10.5px;line-height:1.45;overflow-wrap:anywhere}',
'.wbs-session-copy-transfer{margin-top:4px;color:var(--wb-color-text-secondary);font-size:9.5px;line-height:1.35;font-variant-numeric:tabular-nums;text-align:right;overflow-wrap:anywhere}',
- '.wbs-session-copy-summary{margin-top:3px;color:var(--wb-color-text-primary,#1f1f1f);font-size:10.5px;line-height:1.45;font-variant-numeric:tabular-nums}',
- '.wbs-session-copy-actions{display:flex;align-items:center;justify-content:flex-start;gap:8px;margin-top:8px}',
+ '.wbs-session-copy-summary{display:flex;flex-direction:column;gap:6px;min-width:0;max-width:100%;margin-top:3px;color:var(--wb-color-text-primary,#1f1f1f);font-size:10.5px;line-height:1.45}',
+ '.wbs-session-copy-summary-group{display:flex;flex-direction:column;gap:1px;min-width:0}.wbs-session-copy-summary-label{align-self:flex-start;display:inline-flex;align-items:center;margin:3px 0 2px;padding:4px 9px;border-radius:999px;font-size:11px;font-weight:700;line-height:1.3}.wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label{background:color-mix(in srgb,#2e9b68 14%,transparent);color:#238a5b}.wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label{background:color-mix(in srgb,#c77a17 15%,transparent);color:#b05d18}.wbs-session-copy-summary-line{min-width:0;padding-left:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-session-copy-summary-line.is-copied{color:#238a5b}.wbs-session-copy-summary-line.is-failed{color:#b05d18}',
+ '.wbs-session-copy-actions{display:flex;align-items:center;justify-content:flex-start;gap:8px;margin-top:8px;padding-top:8px;border-top:1px solid var(--wb-border-subtle,#e5e7eb)}',
'.wbs-session-copy-details-btn{min-height:26px;padding:4px 9px;border:1px solid var(--wb-border-default,#d7dbe0);border-radius:7px;background:var(--wb-bg-hover,#f5f6f8);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:10.5px;cursor:pointer}',
'.wbs-session-copy-details-btn:hover{background:var(--wb-bg-active,#e9edf2)}',
'.wbs-session-copy-details-btn:focus-visible{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:1px}',
'.wbs-session-copy-countdown{margin-left:auto;color:var(--wb-color-text-secondary,#667085);font-size:10px;white-space:nowrap}',
- ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-session-copy-count,:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-session-copy-countdown{color:var(--wb-color-text-secondary,#b9bdc7)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-session-copy-details-btn{border-color:var(--wb-border-default,#4b4e56);background:var(--wb-bg-hover,#34363b);color:var(--wb-color-text-primary,#f2f3f5)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-session-copy-details-btn:hover{background:var(--wb-bg-active,#41444b)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-session-copy-notice.is-conflict .wbs-session-copy-icon{color:var(--wb-color-text-warning,#e4b36a)}',
+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-session-copy-countdown{color:var(--wb-color-text-secondary,#b9bdc7)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-session-copy-details-btn{border-color:var(--wb-border-default,#4b4e56);background:var(--wb-bg-hover,#34363b);color:var(--wb-color-text-primary,#f2f3f5)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-session-copy-details-btn:hover{background:var(--wb-bg-active,#41444b)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-session-copy-notice.is-conflict .wbs-session-copy-icon{color:var(--wb-color-text-warning,#e4b36a)}',
'.wbs-modal.wbs-session-copy-details{display:grid;grid-template-rows:auto auto minmax(0,1fr) auto;width:min(620px,calc(100vw - 28px));height:min(620px,calc(100vh - 28px));box-sizing:border-box;overflow:hidden}',
'.wbs-session-copy-details-summary{margin-top:4px;color:var(--wb-color-text-secondary,#667085);font-size:11px;font-variant-numeric:tabular-nums}',
'.wbs-session-copy-detail-tabs{margin-top:12px;margin-bottom:0}.wbs-session-copy-detail-tabs .wbs-model-tab{font-size:12px}',
@@ -15440,12 +15992,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) :is(.wbs-session-copy-detail-note,.wbs-session-copy-details-summary,.wbs-session-copy-detail-size,.wbs-sess-size){color:var(--wb-color-text-secondary,#b9bdc7)}',
'.wbs-session-copy-detail-row.is-copied .wbs-session-copy-detail-status{color:#238a5b}.wbs-session-copy-detail-row.is-conflict .wbs-session-copy-detail-status{color:#a55f09}.wbs-session-copy-detail-row.is-failed .wbs-session-copy-detail-status,.wbs-session-copy-detail-row.is-partial .wbs-session-copy-detail-status{color:#b05d18}',
'.wbs-session-copy-detail-empty{padding:28px 14px;text-align:center;color:var(--wb-color-text-secondary,#667085);font-size:11px}',
- '.wbs-session-copy-notice.is-done .wbs-session-copy-icon{background:color-mix(in srgb,#2e9b68 15%,transparent);color:#238a5b}.wbs-session-copy-notice.is-done .wbs-session-copy-fill{background:#2e9b68}',
+ '.wbs-session-copy-notice.is-done .wbs-session-copy-icon{background:color-mix(in srgb,#2e9b68 15%,transparent);color:#238a5b}.wbs-session-copy-notice.is-done .wbs-session-copy-fill{background:var(--wb-button-primary-bg,#1f1f1f)}',
'.wbs-session-copy-notice.is-partial .wbs-session-copy-icon,.wbs-session-copy-notice.is-error .wbs-session-copy-icon{background:color-mix(in srgb,#c77a17 16%,transparent);color:#a96208}.wbs-session-copy-notice.is-partial .wbs-session-copy-fill{background:#c77a17}',
'.wbs-session-copy-notice.is-conflict .wbs-session-copy-icon{background:color-mix(in srgb,#b46a17 17%,transparent);color:#a55f09}.wbs-session-copy-notice.is-conflict .wbs-session-copy-fill{background:#b46a17}.wbs-session-copy-notice.is-conflict .wbs-session-copy-status{color:#96570b}',
'.wbs-session-copy-notice.is-error .wbs-session-copy-fill{background:#c44343}',
'html.cb-dark .wbs-session-copy-notice,html[data-theme="dark"] .wbs-session-copy-notice,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-notice{border-color:var(--wb-border-default,rgba(255,255,255,.16));background:var(--wb-bg-popover,#25262a);color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 14px 38px rgba(0,0,0,.42)}html.cb-dark .wbs-session-copy-track,html[data-theme="dark"] .wbs-session-copy-track,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-track{background:var(--wb-bg-tertiary,#34363b)}html.cb-dark .wbs-session-copy-route,html[data-theme="dark"] .wbs-session-copy-route,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-route,html.cb-dark .wbs-session-copy-status,html[data-theme="dark"] .wbs-session-copy-status,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-status{color:var(--wb-color-text-secondary,#b9bdc7)}html.cb-dark .wbs-session-copy-notice.is-conflict .wbs-session-copy-status,html[data-theme="dark"] .wbs-session-copy-notice.is-conflict .wbs-session-copy-status,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-notice.is-conflict .wbs-session-copy-status{color:#e4b36a}',
- 'html.cb-dark .wbs-session-copy-summary,html[data-theme="dark"] .wbs-session-copy-summary,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary,html.cb-dark .wbs-session-copy-detail-label,html[data-theme="dark"] .wbs-session-copy-detail-label,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-detail-label{color:var(--wb-color-text-primary,#f2f3f5)}html.cb-dark .wbs-session-copy-details,html[data-theme="dark"] .wbs-session-copy-details,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-details{background:var(--wb-bg-popover,#25262a);color:var(--wb-color-text-primary,#f2f3f5)}html.cb-dark .wbs-session-copy-detail-list,html[data-theme="dark"] .wbs-session-copy-detail-list,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-detail-list{border-color:var(--wb-border-default,rgba(255,255,255,.16));background:var(--wb-bg-secondary,#202126)}html.cb-dark .wbs-session-copy-detail-row,html[data-theme="dark"] .wbs-session-copy-detail-row,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-detail-row{border-color:var(--wb-border-default,rgba(255,255,255,.12))}',
+ 'html.cb-dark .wbs-session-copy-summary,html[data-theme="dark"] .wbs-session-copy-summary,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary,html.cb-dark .wbs-session-copy-detail-label,html[data-theme="dark"] .wbs-session-copy-detail-label,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-detail-label{color:var(--wb-color-text-primary,#f2f3f5)}html.cb-dark .wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label,html[data-theme="dark"] .wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label{background:color-mix(in srgb,#2e9b68 23%,transparent);color:#62c695}html.cb-dark .wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label,html[data-theme="dark"] .wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label{background:color-mix(in srgb,#c77a17 23%,transparent);color:#e4b36a}html.cb-dark .wbs-session-copy-summary-line.is-copied,html[data-theme="dark"] .wbs-session-copy-summary-line.is-copied,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-line.is-copied{color:#62c695}html.cb-dark .wbs-session-copy-summary-line.is-failed,html[data-theme="dark"] .wbs-session-copy-summary-line.is-failed,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-line.is-failed{color:#e4b36a}html.cb-dark .wbs-session-copy-details,html[data-theme="dark"] .wbs-session-copy-details,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-details{background:var(--wb-bg-popover,#25262a);color:var(--wb-color-text-primary,#f2f3f5)}html.cb-dark .wbs-session-copy-detail-list,html[data-theme="dark"] .wbs-session-copy-detail-list,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-detail-list{border-color:var(--wb-border-default,rgba(255,255,255,.16));background:var(--wb-bg-secondary,#202126)}html.cb-dark .wbs-session-copy-detail-row,html[data-theme="dark"] .wbs-session-copy-detail-row,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-detail-row{border-color:var(--wb-border-default,rgba(255,255,255,.12))}',
'@media(max-width:460px){.wbs-session-copy-notice{min-height:104px;padding:11px 12px 10px}.wbs-session-copy-route{margin-left:29px;margin-right:24px}.wbs-session-copy-status{font-size:10px}.wbs-session-copy-detail-row{grid-template-columns:52px minmax(0,1fr);gap:5px}.wbs-session-copy-detail-row.is-copied{grid-template-columns:52px minmax(0,1fr) auto}.wbs-session-copy-detail-note{grid-column:2;font-size:10px}}',
'.wbs-fab.wbs-fab-credit-alert .button{animation:wbs-credit-robot-alert .45s ease-out}',
'@keyframes wbs-credit-robot-alert{0%,100%{transform:translateY(0)}45%{transform:translateY(-5px)}75%{transform:translateY(1px)}}',
diff --git a/scripts/lib.js b/scripts/lib.js
index e44d67f..5462f9e 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -33,6 +33,175 @@ const LEGACY_DATA_DIR = IS_MAC
? path.join(os.homedir(), 'Library', 'Application Support', 'HelloBuddy')
: null;
+// ===================== [wd-compat] WorkBuddy 5.6+ $wbEncrypted 字段信封解密适配 =====================
+// WorkBuddy 5.6 起对 workbuddy.cn 域账号启用 at-rest 字段级加密(编译期策略,无用户开关):
+// auth/account 文件中 nickname/phoneNumber/accessToken/refreshToken 等写为
+// {"$wbEncrypted":1,"envelope":"<base64(JSON)>"},内层 AES-256-GCM(sym-v1 帧 + AAD)。
+// 方案:读取端解密——经 WorkBuddy 自带 Electron(ELECTRON_RUN_AS_NODE=1)子进程调用原生
+// 绑定取密钥负载并派生密钥;密钥只经管道回传、内存缓存、绝不落盘、绝不写日志。
+// 失败语义:任何一步失败保留原值、60s 后允许重试——不阻断账号管理,界面以「(已加密)」占位降级。
+const WD_COMPAT = { key: null, keyFailAt: 0, keyFailReason: '', decOk: 0, decFail: 0 };
+const WD_COMPAT_KEY_RETRY_MS = 60000;
+
+// 被 wdCompatStaticKey 以 ELECTRON_RUN_AS_NODE=1 方式再次执行本文件时派生密钥并退出。
+// 密钥只写父子进程管道;该绑定仅存在于 WorkBuddy 的 Electron 运行时内。
+if (process.argv.includes('--wd-compat-print-key')) {
+ try {
+ const binding = process._linkedBinding('electron_browser_workbuddy_storage');
+ const payload = JSON.parse(binding.loggerGet());
+ if (payload && payload.version === 1 && typeof payload.atRestSecretKey === 'string') {
+ const key = crypto.createHash('sha256').update(payload.atRestSecretKey, 'utf8').digest();
+ process.stdout.write(`WD_COMPAT_KEY ${key.toString('base64')}\n`);
+ key.fill(0);
+ process.exit(0);
+ }
+ process.stderr.write('payload schema mismatch');
+ process.exit(4);
+ } catch (e) { process.stderr.write(String(e.message || e).slice(0, 200)); process.exit(3); }
+}
+
+function isWbEncryptedEnvelope(v) {
+ return !!v && typeof v === 'object' && !Array.isArray(v) && v.$wbEncrypted === 1 && typeof v.envelope === 'string';
+}
+
+function wdCompatContainsEncryptedFields(value) {
+ if (isWbEncryptedEnvelope(value)) return true;
+ if (Array.isArray(value)) return value.some(wdCompatContainsEncryptedFields);
+ if (!value || typeof value !== 'object') return false;
+ return Object.values(value).some(wdCompatContainsEncryptedFields);
+}
+
+/** 信封字段的展示兜底:取钥不可用时显示占位而非整段密文/[object Object]。 */
+function wdCompatText(v) {
+ if (typeof v === 'string') return v;
+ return isWbEncryptedEnvelope(v) ? '(已加密)' : '';
+}
+
+/** 只返回可直接用于 HTTP 的明文 token;信封不可用时返回空字符串。 */
+function wdCompatAuthToken(auth) {
+ if (!auth || typeof auth !== 'object') return '';
+ const value = auth.accessToken ?? auth.access_token ?? auth.token;
+ return typeof value === 'string' ? value.trim() : '';
+}
+
+function wdCompatHasAuthCredential(auth) {
+ if (!auth || typeof auth !== 'object') return false;
+ const value = auth.accessToken ?? auth.access_token ?? auth.token;
+ return typeof value === 'string' ? value.trim().length > 0 : isWbEncryptedEnvelope(value);
+}
+
+function wdCompatLog(msg) {
+ try { fs.appendFileSync(path.join(PLATFORM_DATA_DIR, 'daemon.log'), `[wd-compat] ${msg}\n`); } catch (_) {}
+}
+
+// Windows 安装目录可以由用户选择,不能只依赖默认的 %LOCALAPPDATA% 路径。
+// profiles.js 会读取当前 profile 的 workbuddy-target.json,并返回已经过 profile
+// 校验的主程序路径;只在 Node/daemon 侧读取,注入到 renderer 的 compat 脚本不会触发。
+function wdCompatConfiguredExe() {
+ if (!IS_WIN || typeof module === 'undefined' || !module.exports) return '';
+ try {
+ const { getProfile } = require('./profiles.js');
+ const profile = getProfile(process.env.WBSWITCH_PROFILE || 'workbuddy-cn', {
+ dataDir: process.env.WBSWITCH_DATA_DIR || undefined,
+ env: process.env,
+ platform: process.platform,
+ });
+ return profile && typeof profile.appPath === 'string' ? profile.appPath : '';
+ } catch (_) {
+ return '';
+ }
+}
+
+function wdCompatExeCandidates() {
+ if (process.env.WORKDADDY_WB_EXE) return [process.env.WORKDADDY_WB_EXE];
+ const home = os.homedir();
+ if (IS_MAC) {
+ const apps = [];
+ for (const root of ['/Applications', path.join(home, 'Applications')]) {
+ for (const name of ['WorkBuddy.app', 'WorkBuddy AI.app']) {
+ apps.push(path.join(root, name, 'Contents', 'MacOS', 'Electron'));
+ }
+ }
+ return apps;
+ }
+ if (IS_WIN) {
+ const base = process.env.LOCALAPPDATA || '';
+ const configured = wdCompatConfiguredExe();
+ return [
+ ...(configured ? [configured] : []),
+ path.join(base, 'Programs', 'WorkBuddy', 'WorkBuddy.exe'),
+ path.join(base, 'Programs', 'WorkBuddy AI', 'WorkBuddy AI.exe'),
+ ].filter(Boolean);
+ }
+ return ['/opt/WorkBuddy/workbuddy', '/opt/WorkBuddy/workbuddy-ai'];
+}
+
+function wdCompatStaticKey() {
+ if (WD_COMPAT.key) return WD_COMPAT.key;
+ if (WD_COMPAT.keyFailAt && Date.now() - WD_COMPAT.keyFailAt < WD_COMPAT_KEY_RETRY_MS) {
+ throw new Error(WD_COMPAT.keyFailReason || '取钥暂不可用');
+ }
+ let lastErr = '未找到 WorkBuddy 可执行文件';
+ for (const exe of wdCompatExeCandidates()) {
+ if (!fs.existsSync(exe)) continue;
+ const r = require('child_process').spawnSync(exe, [__filename, '--wd-compat-print-key'], {
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
+ timeout: 15000, encoding: 'utf8',
+ });
+ const m = r.stdout && r.stdout.match(/WD_COMPAT_KEY ([A-Za-z0-9+/=]+)/);
+ if (m) {
+ WD_COMPAT.key = Buffer.from(m[1], 'base64');
+ WD_COMPAT.keyFailAt = 0;
+ WD_COMPAT.keyFailReason = '';
+ return WD_COMPAT.key;
+ }
+ lastErr = (r.stderr && String(r.stderr).trim().slice(0, 120)) || `exit=${r.status}`;
+ }
+ WD_COMPAT.keyFailAt = Date.now();
+ WD_COMPAT.keyFailReason = lastErr;
+ wdCompatLog(`取钥失败(60s 后重试): ${lastErr}`);
+ throw new Error(lastErr);
+}
+
+function wdCompatOpenEnvelope(env, key) {
+ const FRAMING_FIELD = 2, FMT_FIELD = 'WBEV1', AAD_DOMAIN = Buffer.from('WB-AAD\0', 'ascii');
+ const lp = (s) => { const b = Buffer.from(s, 'utf8'); const l = Buffer.alloc(4); l.writeUInt32BE(b.length); return Buffer.concat([l, b]); };
+ const u32 = (n) => { const b = Buffer.alloc(4); b.writeUInt32BE(n); return b; };
+ const aad = Buffer.concat([
+ AAD_DOMAIN, Buffer.from([1]), lp(FMT_FIELD), lp('sym-v1'), u32(env.suite || 1),
+ lp(env.keyId || ''), Buffer.from([FRAMING_FIELD]), Buffer.from([0]), Buffer.from([0]),
+ ]);
+ const d = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(env.nonce, 'base64'), { authTagLength: 16 });
+ d.setAAD(aad);
+ d.setAuthTag(Buffer.from(env.authTag, 'base64'));
+ return Buffer.concat([d.update(Buffer.from(env.ciphertext, 'base64')), d.final()]).toString('utf8');
+}
+
+/** 原地解密 JSON 中的全部 $wbEncrypted 信封字段;失败字段保留原值,不抛错。 */
+function wdCompatDecryptAuthJson(json) {
+ if (!json || typeof json !== 'object') return json;
+ const walk = (node) => {
+ if (Array.isArray(node)) { node.forEach(walk); return; }
+ if (!node || typeof node !== 'object') return;
+ for (const k of Object.keys(node)) {
+ const v = node[k];
+ if (isWbEncryptedEnvelope(v)) {
+ try {
+ const env = JSON.parse(Buffer.from(v.envelope, 'base64').toString('utf8'));
+ node[k] = wdCompatOpenEnvelope(env, wdCompatStaticKey());
+ WD_COMPAT.decOk++;
+ } catch (e) {
+ WD_COMPAT.decFail++;
+ wdCompatLog(`解密失败 ${k}: ${String(e.message || e).slice(0, 80)}`);
+ }
+ } else if (v && typeof v === 'object') walk(v);
+ }
+ };
+ walk(json);
+ return json;
+}
+// ===================== [wd-compat] 适配层结束 =====================
+
function samePath(a, b) {
return !!a && !!b && path.resolve(a) === path.resolve(b);
}
@@ -110,25 +279,30 @@ function authRecordFromJson(file, json, { strict = DYNAMIC_AUTH_DISCOVERY } = {}
const acct = json.account || (Array.isArray(json.accounts) && json.accounts[0]) || null;
if (!acct || !acct.uid) return null;
const auth = json.auth && typeof json.auth === 'object' ? json.auth : {};
- const accessToken = String(auth.accessToken || auth.access_token || auth.token || '');
+ const rawToken = auth.accessToken ?? auth.access_token ?? auth.token;
+ // [wd-compat] 信封对象不能 String()——避免 "[object Object]" 污染 issuer 校验
+ const accessToken = wdCompatAuthToken(auth);
+ const encryptedToken = isWbEncryptedEnvelope(rawToken);
const authDomain = normalizeAuthDomain(auth.domain || auth.issuer || '');
const authIssuer = tokenIssuerOrigin(accessToken);
if (strict) {
- if (!accessToken) return null;
+ if (!wdCompatHasAuthCredential(auth)) return null;
const allowed = allowedAuthOrigins();
+ // 无法取钥时无法从信封解析 issuer;此时只接受明确属于当前客户端的 domain。
if (![authDomain, authIssuer].some((origin) => origin && allowed.has(origin))) return null;
}
return {
uid: String(acct.uid),
- nickname: acct.nickname || '',
- uin: acct.uin || '',
- phone: acct.phoneNumber || '',
- type: acct.type || '',
+ nickname: wdCompatText(acct.nickname),
+ uin: typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '',
+ phone: wdCompatText(acct.phoneNumber),
+ type: typeof acct.type === 'string' ? acct.type : '',
raw: json,
file,
authFileName: file ? path.basename(file) : '',
authDomain,
authIssuer,
+ tokenEncrypted: encryptedToken,
lastLogin: acct.lastLogin === true,
lastRefreshTime: Number(auth.lastRefreshTime) || 0,
};
@@ -138,6 +312,7 @@ function parseAuthFile(file, options = {}) {
if (!file || !fs.existsSync(file)) return null;
try {
const json = JSON.parse(fs.readFileSync(file, 'utf8'));
+ wdCompatDecryptAuthJson(json); // [wd-compat] 5.6+ 字段信封读取端解密
return authRecordFromJson(file, json, options);
} catch (_) {
return null;
@@ -145,9 +320,37 @@ function parseAuthFile(file, options = {}) {
}
function parseAuthJson(json, options = {}) {
+ json = wdCompatDecryptAuthJson(json); // [wd-compat]
return authRecordFromJson(null, json, options);
}
+/**
+ * Normalize a user-supplied account JSON without destroying encrypted fields.
+ * Validation runs on a deep clone because parseAuthJson may decrypt in place.
+ */
+function normalizeAccountImportJson(candidate) {
+ const source = candidate && typeof candidate === 'object' && !Array.isArray(candidate) ? candidate : null;
+ if (!source) return null;
+ const acct = source.account && typeof source.account === 'object' ? source.account : source;
+ const auth = source.auth && typeof source.auth === 'object' ? source.auth : null;
+ const uid = String(acct && acct.uid || '').trim();
+ const rawToken = auth && (auth.accessToken ?? auth.access_token ?? auth.token);
+ const accessToken = typeof rawToken === 'string' ? rawToken.trim() : rawToken;
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return null;
+ if (!(typeof accessToken === 'string' ? accessToken : isWbEncryptedEnvelope(accessToken))) return null;
+ const normalized = {
+ account: { ...acct, uid },
+ auth: { ...auth, accessToken },
+ };
+ let authRecord;
+ try {
+ authRecord = parseAuthJson(JSON.parse(JSON.stringify(normalized)));
+ } catch (_) {
+ return null;
+ }
+ return authRecord && authRecord.uid === uid ? { uid, normalized, authRecord } : null;
+}
+
function listAuthRecords() {
if (!AUTH_FILE) return [];
if (!DYNAMIC_AUTH_DISCOVERY) {
@@ -793,13 +996,18 @@ function selectLatestAutoCopyMember(members) {
function ensureAutoCopySessions(dataDir, uid, sessionIds, options) {
const meta = readMeta(dataDir);
+ const previousConfig = meta.autoCopy;
const config = ensureAutoCopyMeta(meta);
+ let changed = config !== previousConfig;
const sourceUid = String(uid || '').trim();
const ids = Array.from(new Set((Array.isArray(sessionIds) ? sessionIds : [sessionIds])
.map((id) => String(id || '').trim())
.filter(Boolean)));
if (!sourceUid || !ids.length) throw new Error('缺少共享会话标识');
- if (!config.sessionIndex[sourceUid]) config.sessionIndex[sourceUid] = {};
+ if (!config.sessionIndex[sourceUid]) {
+ config.sessionIndex[sourceUid] = {};
+ changed = true;
+ }
const lineages = {};
ids.forEach((id) => {
let lineageId = config.sessionIndex[sourceUid][id];
@@ -807,11 +1015,16 @@ function ensureAutoCopySessions(dataDir, uid, sessionIds, options) {
lineageId = crypto.randomUUID();
config.sessions[lineageId] = { enabled: !(options && options.enabled === false), members: [], createdAt: Date.now() };
config.sessionIndex[sourceUid][id] = lineageId;
+ changed = true;
}
- addLineageMember(config.sessions[lineageId], sourceUid, id);
+ const lineage = config.sessions[lineageId];
+ const hasMember = Array.isArray(lineage.members)
+ && lineage.members.some((member) => member && member.uid === sourceUid && member.id === id);
+ addLineageMember(lineage, sourceUid, id);
+ if (!hasMember) changed = true;
lineages[id] = lineageId;
});
- writeMeta(dataDir, meta);
+ if (changed) writeMeta(dataDir, meta);
return lineages;
}
@@ -1120,6 +1333,60 @@ function getAutoCopyMapping(dataDir, lineageOrUid, targetUid, maybeSessionId) {
return config.copies[autoCopyRuleKey(lineageId, targetUid)] || null;
}
+// Load the mappings for one target account from the memoized auto-copy config
+// in one pass. Automatic switching can have hundreds of selected sessions;
+// callers should not reparse the same metadata JSON once per session.
+function getAutoCopyMappings(dataDir, lineageIds, targetUid) {
+ const config = readAutoCopyConfig(dataDir);
+ const result = new Map();
+ for (const lineageId of new Set(Array.isArray(lineageIds) ? lineageIds : [])) {
+ const mapping = config.copies[autoCopyRuleKey(lineageId, targetUid)];
+ if (mapping) result.set(String(lineageId || ''), mapping);
+ }
+ return result;
+}
+
+function autoCopyTargetRowRevision(row) {
+ return JSON.stringify([
+ String(row && row.id || ''), String(row && row.user_id || ''),
+ Number(row && row.updated_at || 0), Number(row && row.last_activity_at || 0),
+ String(row && row.status || ''), String(row && row.title || ''), String(row && row.custom_title || ''),
+ ]);
+}
+
+function autoCopyTargetStateRevision(row) {
+ return JSON.stringify([
+ Number(row && row.updated_at || 0), Number(row && row.last_activity_at || 0),
+ String(row && row.status || ''), String(row && row.title || ''), String(row && row.custom_title || ''),
+ ]);
+}
+
+// Older daemons persisted the source row's timestamps as the target baseline.
+// Repair those cheap row-level baselines in one metadata write; file snapshots
+// remain the authority for mappings that are actually marked dirty.
+function migrateAutoCopyTargetRevisions(dataDir, rowsByKey) {
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ const changed = [];
+ for (const [key, mapping] of Object.entries(config.copies || {})) {
+ if (!mapping || typeof mapping !== 'object' || !mapping.targetId) continue;
+ let parts;
+ try { parts = JSON.parse(key); } catch (_) { continue; }
+ if (!Array.isArray(parts) || parts.length !== 2) continue;
+ const rowKey = JSON.stringify([String(mapping.targetId), String(parts[1] || '')]);
+ const row = rowsByKey && typeof rowsByKey.get === 'function' ? rowsByKey.get(rowKey) : null;
+ if (!row) continue;
+ const targetRevision = autoCopyTargetRowRevision(row);
+ const targetStateRevision = autoCopyTargetStateRevision(row);
+ if (mapping.targetRevision === targetRevision && mapping.targetStateRevision === targetStateRevision) continue;
+ mapping.targetRevision = targetRevision;
+ mapping.targetStateRevision = targetStateRevision;
+ changed.push(key);
+ }
+ if (changed.length) writeMeta(dataDir, meta);
+ return changed.length;
+}
+
function setAutoCopyMapping(dataDir, lineageOrUid, targetUid, mappingOrSessionId, maybeMapping) {
const meta = readMeta(dataDir);
const config = ensureAutoCopyMeta(meta);
@@ -1286,7 +1553,10 @@ function backupAuthFile(dataDir, file, log = () => {}) {
const info = readAuthFile(file);
const dest = backupPath(dataDir, info.uid);
const tmp = dest + '.tmp';
- fs.writeFileSync(tmp, fs.readFileSync(file), { mode: 0o600 });
+ // [wd-compat] 密文信封原样落盘;需要查询/刷新时才在内存中解密。
+ // 这样不会在 WorkDaddy 目录制造明文 token 副本,也能保留旧版明文 auth 文件。
+ fs.copyFileSync(file, tmp);
+ fs.chmodSync(tmp, 0o600);
fs.renameSync(tmp, dest);
fs.chmodSync(dest, 0o600);
updateMeta(dataDir, info, { preserveBinding: true });
@@ -1412,13 +1682,13 @@ function listAccounts(dataDir) {
authValid: false,
};
try {
- const j = JSON.parse(fs.readFileSync(path.join(dir, n), 'utf8'));
+ const j = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(path.join(dir, n), 'utf8'))); // [wd-compat]
item.authValid = !!parseAuthJson(j);
const acct = j.account || (Array.isArray(j.accounts) && j.accounts[0]);
if (acct) {
- item.nickname = acct.nickname || '';
- item.phone = acct.phoneNumber || '';
- item.uin = acct.uin || '';
+ item.nickname = wdCompatText(acct.nickname);
+ item.phone = wdCompatText(acct.phoneNumber);
+ item.uin = typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '';
item.type = typeof acct.type === 'string' ? acct.type : '';
item.enterpriseName = typeof acct.enterpriseName === 'string' ? acct.enterpriseName.trim() : '';
}
@@ -1526,7 +1796,7 @@ function switchTo(dataDir, uid, log = () => {}) {
throw new Error(`未找到账号 ${uid} 的备份文件`);
}
const raw = fs.readFileSync(src, 'utf8');
- const json = JSON.parse(raw);
+ const json = wdCompatDecryptAuthJson(JSON.parse(raw)); // [wd-compat] 校验前解密;写回仍用 raw 原字节
const acct = json.account || (Array.isArray(json.accounts) && json.accounts[0]);
if (!acct || acct.uid !== uid) {
throw new Error('备份文件校验失败:uid 不匹配,已中止切换');
@@ -1570,18 +1840,27 @@ function switchTo(dataDir, uid, log = () => {}) {
retireLogoutMarker(log, target);
updateMeta(dataDir, {
uid: acct.uid,
- nickname: acct.nickname || '',
- uin: acct.uin || '',
- phone: acct.phoneNumber || '',
+ nickname: wdCompatText(acct.nickname),
+ uin: typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '',
+ phone: wdCompatText(acct.phoneNumber),
authFileName: path.basename(target),
authDomain: normalizeAuthDomain(json.auth && json.auth.domain),
authIssuer: tokenIssuerOrigin(json.auth && (json.auth.accessToken || json.auth.access_token)),
});
- log(`[switch] 已切换登录账号为 ${acct.nickname || uid} (${uid})`);
- return { uid: acct.uid, nickname: acct.nickname || '', uin: acct.uin || '', authFile: target };
+ const switchName = wdCompatText(acct.nickname) || uid;
+ log(`[switch] 已切换登录账号为 ${switchName} (${uid})`);
+ return { uid: acct.uid, nickname: wdCompatText(acct.nickname), uin: typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '', authFile: target };
}
module.exports = {
+ isWbEncryptedEnvelope, // [wd-compat]
+ wdCompatExeCandidates, // [wd-compat]
+ wdCompatContainsEncryptedFields, // [wd-compat]
+ wdCompatText, // [wd-compat]
+ wdCompatAuthToken, // [wd-compat]
+ wdCompatHasAuthCredential, // [wd-compat]
+ normalizeAccountImportJson, // [wd-compat]
+ wdCompatDecryptAuthJson, // [wd-compat]
getAccountOrder,
setAccountOrder,
readModelsFile,
@@ -1622,6 +1901,7 @@ module.exports = {
importModels,
logFile,
backupPath,
+ backupAuthFile,
retireLogoutMarker,
ensureDirs,
readAuthFile,
@@ -1647,6 +1927,8 @@ module.exports = {
removeAutoCopyAccount,
collectLineageMembersForDelete,
getAutoCopyMapping,
+ getAutoCopyMappings,
+ migrateAutoCopyTargetRevisions,
setAutoCopyMapping,
deleteAutoCopyMapping,
backupCurrent,
diff --git a/scripts/session-db.js b/scripts/session-db.js
index 9ed06b6..7e4ed28 100644
--- a/scripts/session-db.js
+++ b/scripts/session-db.js
@@ -251,9 +251,13 @@ function normalizeTransactionStatements(statements) {
});
}
-function normalizeSessionIdBatch(value) {
+function normalizeSessionIdBatch(value, options = {}) {
if (!Array.isArray(value)) throw new TypeError('会话 ID 批次必须是数组');
- if (value.length > MAX_SESSION_ID_BATCH) {
+ // Most batch endpoints keep the defensive cap. Destructive deletion passes
+ // maxBatch:null after validating every ID and matching it back to the DB,
+ // so large user selections are processed as one logical request.
+ const maxBatch = options && options.maxBatch === null ? null : MAX_SESSION_ID_BATCH;
+ if (maxBatch !== null && value.length > maxBatch) {
throw new RangeError(`单次最多接收 ${MAX_SESSION_ID_BATCH} 个会话 ID`);
}
const ids = [];
diff --git a/scripts/session-dirty.js b/scripts/session-dirty.js
new file mode 100644
index 0000000..2b0da5d
--- /dev/null
+++ b/scripts/session-dirty.js
@@ -0,0 +1,88 @@
+'use strict';
+
+const VERSION = 1;
+
+function createDirtyIndex(raw) {
+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ const state = { version: VERSION, accounts: {} };
+ const accounts = source.accounts && typeof source.accounts === 'object' && !Array.isArray(source.accounts)
+ ? source.accounts : {};
+ for (const [uid, value] of Object.entries(accounts)) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
+ const sessions = value.sessions && typeof value.sessions === 'object' && !Array.isArray(value.sessions)
+ ? value.sessions : {};
+ state.accounts[String(uid)] = {
+ initialized: value.initialized === true,
+ sessions: {},
+ };
+ for (const [id, marker] of Object.entries(sessions)) {
+ if (!marker || typeof marker !== 'object') continue;
+ const at = Number(marker.at);
+ if (!Number.isFinite(at) || at <= 0) continue;
+ state.accounts[String(uid)].sessions[String(id)] = {
+ at,
+ event: String(marker.event || 'sessionUpdated').slice(0, 40),
+ };
+ }
+ }
+
+ function account(uid, create) {
+ const key = String(uid || '').trim();
+ if (!key) return null;
+ if (!state.accounts[key] && create) state.accounts[key] = { initialized: false, sessions: {} };
+ return state.accounts[key] || null;
+ }
+
+ return {
+ state,
+ isInitialized(uid) {
+ const item = account(uid, false);
+ return !!(item && item.initialized);
+ },
+ markBaseline(uid) {
+ const item = account(uid, true);
+ if (!item) return false;
+ const changed = item.initialized !== true;
+ item.initialized = true;
+ return changed;
+ },
+ mark(uid, sessionId, event, at = Date.now()) {
+ const item = account(uid, true);
+ const id = String(sessionId || '').trim();
+ const timestamp = Number(at);
+ if (!item || !id || !Number.isFinite(timestamp) || timestamp <= 0) return null;
+ const previous = item.sessions[id];
+ const marker = { at: timestamp, event: String(event || 'sessionUpdated').slice(0, 40) };
+ item.sessions[id] = marker;
+ return previous && previous.at === marker.at ? previous : marker;
+ },
+ get(uid, sessionId) {
+ const item = account(uid, false);
+ return item && item.sessions[String(sessionId || '').trim()] || null;
+ },
+ shouldSync(uid, sessionId) {
+ const item = account(uid, false);
+ if (!item || item.initialized !== true) return true;
+ return !!item.sessions[String(sessionId || '').trim()];
+ },
+ clear(uid, sessionId, expectedAt) {
+ const item = account(uid, false);
+ const id = String(sessionId || '').trim();
+ if (!item || !id || !item.sessions[id]) return false;
+ if (expectedAt !== undefined && Number(item.sessions[id].at) !== Number(expectedAt)) return false;
+ delete item.sessions[id];
+ return true;
+ },
+ prune(uid, validIds) {
+ const item = account(uid, false);
+ if (!item || !validIds || typeof validIds.has !== 'function') return false;
+ let changed = false;
+ for (const id of Object.keys(item.sessions)) {
+ if (!validIds.has(id)) { delete item.sessions[id]; changed = true; }
+ }
+ return changed;
+ },
+ };
+}
+
+module.exports = { VERSION, createDirtyIndex };
diff --git a/scripts/session-sync.js b/scripts/session-sync.js
index de92c5a..861eceb 100644
--- a/scripts/session-sync.js
+++ b/scripts/session-sync.js
@@ -5,9 +5,28 @@
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
+const { StringDecoder } = require('node:string_decoder');
const identityKeys = new Set(['sessionId', 'conversationId', 'ownerConversationId', 'session_id', 'conversation_id']);
+const SKIP_LOCAL_DIR = /^workspace\/sessions\/[^/]+\/(?:modify_backup|\.modify_backup_meta)$/;
const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
+// WorkBuddy appends session-meta lifecycle records when a conversation is
+// opened or restored. Their generated id, session id and timestamp describe
+// that local activation event, not a user message. Keep the stable metadata
+// fields in the semantic fingerprint while ignoring those per-account event
+// fields so an account round-trip does not become a false content conflict.
+function canonicalTranscriptRecord(record, aliases) {
+ if (record && record.type === 'session-meta') {
+ const stable = {};
+ for (const key of Object.keys(record)) {
+ if (key === 'id' || key === 'sessionId' || key === 'timestamp') continue;
+ stable[key] = record[key];
+ }
+ return canonical(stable, aliases);
+ }
+ return canonical(record, aliases);
+}
+
function canonical(value, aliases) {
if (Array.isArray(value)) return value.map(item => canonical(item, aliases));
if (!value || typeof value !== 'object') return value;
@@ -30,16 +49,34 @@ function safePath(root, relative) {
return target;
}
+async function safePathAsync(root, relative) {
+ const parts = relative.split('/');
+ if (parts.some(part => !part || part === '.' || part === '..' || /[\\\x00]/.test(part))) throw Error('无效的会话文件路径');
+ let target = root;
+ for (const part of parts) {
+ target = path.join(target, part);
+ try {
+ const info = await fs.promises.lstat(target);
+ if (info.isSymbolicLink()) throw Error('会话文件包含符号链接,未同步');
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
+ }
+ return target;
+}
+
// List views need byte counts, not message parsing or payload buffers. Limit
// concurrent scans, never the size/file count of a session itself.
async function readSessionSizes(root, ids) {
- root = path.resolve(root);
+ try { root = await fs.promises.realpath(path.resolve(root)); }
+ catch (error) {
+ if (error && error.code === 'ENOENT') return new Map((ids || []).map(id => [id, null]));
+ throw error;
+ }
const sizes = new Map();
const sharedStats = new Map();
async function stat(file) {
try {
const value = await fs.promises.lstat(file);
- if (value.isSymbolicLink()) throw Error('symbolic link');
+ if (value.isSymbolicLink()) return null;
return value;
} catch (error) { if (error.code === 'ENOENT') return null; throw error; }
}
@@ -52,13 +89,14 @@ async function readSessionSizes(root, ids) {
})());
return sharedStats.get(relative);
}
- async function visit(file) {
+ async function visit(file, relative) {
+ if (SKIP_LOCAL_DIR.test(relative)) return 0;
const info = await stat(file);
if (!info) return 0;
if (info.isFile()) return info.size;
if (!info.isDirectory()) throw Error('unsupported file');
let total = 0;
- for (const entry of await fs.promises.readdir(file)) total += await visit(path.join(file, entry));
+ for (const entry of await fs.promises.readdir(file)) total += await visit(path.join(file, entry), relative + '/' + entry);
return total;
}
let projects;
@@ -80,7 +118,7 @@ async function readSessionSizes(root, ids) {
const parent = await base(path.dirname(relative));
if (parent) {
if (!parent.isDirectory()) throw Error('invalid directory');
- total += await visit(path.join(root, relative));
+ total += await visit(path.join(root, relative), relative);
}
}
sizes.set(id, total);
@@ -104,7 +142,10 @@ function aliasesEqual(left, right) {
// only when computed for the same aliases.
function readSnapshot(root, id, aliases = [], cache = null) {
if (!id || /[/\\\x00]/.test(id) || id === '.' || id === '..') throw Error('无效的会话标识');
- root = path.resolve(root);
+ // The configured WorkBuddy data root may itself be a Windows junction. Trust
+ // only that configured boundary; safePathFast/safePath still reject links at
+ // every managed child component below the resolved root.
+ root = fs.realpathSync(path.resolve(root));
if (fs.lstatSync(root).isSymbolicLink()) throw Error('会话目录包含符号链接,未同步');
const knownIds = Array.from(new Set([id, ...aliases]));
const files = new Map();
@@ -119,7 +160,7 @@ function readSnapshot(root, id, aliases = [], cache = null) {
for (let i = 0; i < parts.length - 1; i++) {
target = path.join(target, parts[i]);
if (trustedComponents.has(target)) continue;
- try { if (fs.lstatSync(target).isSymbolicLink()) throw Error('会话文件包含符号链接,未同步'); }
+ try { if (fs.lstatSync(target).isSymbolicLink()) return null; }
catch (error) { if (error.code !== 'ENOENT') throw error; }
trustedComponents.set(target, true);
}
@@ -150,10 +191,12 @@ function readSnapshot(root, id, aliases = [], cache = null) {
return entry;
}
function visit(relative, logical) {
+ if (SKIP_LOCAL_DIR.test(relative)) return;
const file = safePathFast(relative);
+ if (!file) return;
let stat;
try { stat = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return; throw Error('会话文件无法读取'); }
- if (stat.isSymbolicLink()) throw Error('会话文件包含符号链接,未同步');
+ if (stat.isSymbolicLink()) return;
if (stat.isDirectory()) {
for (const entry of fs.readdirSync(file).sort()) visit(relative + '/' + entry, logical + '/' + entry);
return;
@@ -182,12 +225,16 @@ function readSnapshot(root, id, aliases = [], cache = null) {
semantic: null, semanticAliases: null, records: null,
});
}
- const projects = safePath(root, 'projects');
- if (fs.existsSync(projects)) {
- for (const entry of fs.readdirSync(projects, { withFileTypes: true })) {
- if (!entry.isDirectory()) continue;
- visit('projects/' + entry.name + '/' + id + '.jsonl', 'projects/' + entry.name + '/__session__.jsonl');
- visit('projects/' + entry.name + '/' + id, 'projects/' + entry.name + '/__session__');
+ const projects = safePathFast('projects');
+ if (projects) {
+ let projectsStat;
+ try { projectsStat = fs.lstatSync(projects); } catch (error) { if (error.code === 'ENOENT') projectsStat = null; else throw error; }
+ if (projectsStat && projectsStat.isDirectory() && !projectsStat.isSymbolicLink()) {
+ for (const entry of fs.readdirSync(projects, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue;
+ visit('projects/' + entry.name + '/' + id + '.jsonl', 'projects/' + entry.name + '/__session__.jsonl');
+ visit('projects/' + entry.name + '/' + id, 'projects/' + entry.name + '/__session__');
+ }
}
}
for (const prefix of ['workspace/sessions', 'tasks', 'file-history']) visit(prefix + '/' + id, prefix + '/__session__');
@@ -210,8 +257,13 @@ function readSnapshot(root, id, aliases = [], cache = null) {
let record;
try { record = JSON.parse(line); } catch (_) { throw Error('会话消息文件未写完或已损坏,未同步'); }
if (!record || typeof record !== 'object' || Array.isArray(record) || typeof record.type !== 'string') throw Error('会话消息格式不受支持,未同步');
- return digest(JSON.stringify(canonical(record, knownIds)));
+ // session-meta is an activation journal entry. It may be appended on
+ // only one account after navigation, so it must not change the
+ // conversation continuation shape used for sync decisions.
+ if (record.type === 'session-meta') return null;
+ return digest(JSON.stringify(canonicalTranscriptRecord(record, knownIds)));
});
+ entry.records = entry.records.filter(Boolean);
// Require actual messages: a metadata-only journal is not an empty base.
if (!lines.some(line => JSON.parse(line).type === 'message')) throw Error('会话消息文件没有消息,未同步');
entry.semantic = digest(entry.records.join('\n'));
@@ -240,6 +292,307 @@ function readSnapshot(root, id, aliases = [], cache = null) {
return { root, id, aliases: knownIds, files, records, transcriptKey, totalBytes: total, cache };
}
+function validSessionId(id) {
+ return typeof id === 'string' && !!id && !/[/\\\x00]/.test(id) && id !== '.' && id !== '..';
+}
+
+function sameFileStat(expected, actual, size = actual.size) {
+ return expected.size === size && expected.size === actual.size &&
+ expected.mtimeMs === actual.mtimeMs && expected.ctimeMs === actual.ctimeMs;
+}
+
+async function hashFileAsync(file, expected = null) {
+ const hash = crypto.createHash('sha256');
+ let size = 0;
+ for await (const chunk of fs.createReadStream(file, { highWaterMark: 1024 * 1024 })) {
+ hash.update(chunk);
+ size += chunk.length;
+ }
+ const after = await fs.promises.stat(file);
+ if (expected && !sameFileStat(expected, after, size)) throw Error('会话文件正在变化,请稍后重试');
+ return { hash: hash.digest('hex'), size, stat: after };
+}
+
+async function readStableBytesAsync(entry) {
+ const bytes = await fs.promises.readFile(entry.sourcePath);
+ const after = await fs.promises.stat(entry.sourcePath);
+ if (!sameFileStat(entry, after, bytes.length)) throw Error('会话文件正在变化,请稍后重试');
+ return bytes;
+}
+
+async function readTranscriptAsync(file, stat, knownIds) {
+ const fileHash = crypto.createHash('sha256');
+ const semanticHash = crypto.createHash('sha256');
+ const decoder = new StringDecoder('utf8');
+ const records = [];
+ let pending = '';
+ let size = 0;
+ let lineCount = 0;
+ let hasMessage = false;
+ const consume = raw => {
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
+ if (!line.trim()) return;
+ let record;
+ try { record = JSON.parse(line); } catch (_) { throw Error('会话消息文件未写完或已损坏,未同步'); }
+ if (!record || typeof record !== 'object' || Array.isArray(record) || typeof record.type !== 'string') {
+ throw Error('会话消息格式不受支持,未同步');
+ }
+ if (record.type === 'session-meta') return;
+ const recordHash = digest(JSON.stringify(canonicalTranscriptRecord(record, knownIds)));
+ if (lineCount++) semanticHash.update('\n');
+ semanticHash.update(recordHash);
+ records.push(recordHash);
+ if (record.type === 'message') hasMessage = true;
+ };
+ for await (const chunk of fs.createReadStream(file, { highWaterMark: 1024 * 1024 })) {
+ fileHash.update(chunk);
+ size += chunk.length;
+ const text = decoder.write(chunk);
+ let start = 0;
+ for (;;) {
+ const newline = text.indexOf('\n', start);
+ if (newline < 0) break;
+ consume(pending + text.slice(start, newline));
+ pending = '';
+ start = newline + 1;
+ }
+ pending += text.slice(start);
+ }
+ pending += decoder.end();
+ consume(pending);
+ const after = await fs.promises.stat(file);
+ if (!sameFileStat(stat, after, size)) throw Error('会话文件正在变化,请稍后重试');
+ if (!lineCount) throw Error('会话消息文件为空,未同步');
+ if (!hasMessage) throw Error('会话消息文件没有消息,未同步');
+ return { hash: fileHash.digest('hex'), records, semantic: semanticHash.digest('hex') };
+}
+
+async function readSnapshotAsync(root, id, aliases = [], cache = null) {
+ if (!validSessionId(id)) throw Error('无效的会话标识');
+ root = await fs.promises.realpath(path.resolve(root));
+ const rootStat = await fs.promises.lstat(root);
+ if (rootStat.isSymbolicLink()) throw Error('会话目录包含符号链接,未同步');
+ if (!rootStat.isDirectory()) throw Error('会话目录无法读取');
+ const knownIds = Array.from(new Set([id, ...aliases]));
+ const files = new Map();
+ const trustedComponents = new Map();
+ let total = 0;
+
+ async function safePathFastAsync(relative) {
+ const parts = relative.split('/');
+ if (parts.some(part => !part || part === '.' || part === '..' || /[\\\x00]/.test(part))) throw Error('无效的会话文件路径');
+ let target = root;
+ for (let i = 0; i < parts.length - 1; i++) {
+ target = path.join(target, parts[i]);
+ if (trustedComponents.has(target)) continue;
+ try {
+ const info = await fs.promises.lstat(target);
+ if (info.isSymbolicLink()) return null;
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
+ trustedComponents.set(target, true);
+ }
+ return path.join(target, parts[parts.length - 1]);
+ }
+
+ function cached(relative, stat) {
+ if (!cache) return null;
+ const entry = cache.get(relative);
+ if (!entry || typeof entry !== 'object') return null;
+ if (entry.size !== stat.size || entry.mtimeMs !== stat.mtimeMs || entry.ctimeMs !== stat.ctimeMs) return null;
+ if (typeof entry.hash !== 'string' || !entry.hash) return null;
+ return entry;
+ }
+
+ async function visit(relative, logical) {
+ if (SKIP_LOCAL_DIR.test(relative)) return;
+ const file = await safePathFastAsync(relative);
+ if (!file) return;
+ let stat;
+ try { stat = await fs.promises.lstat(file); }
+ catch (error) { if (error.code === 'ENOENT') return; throw Error('会话文件无法读取'); }
+ if (stat.isSymbolicLink()) return;
+ if (stat.isDirectory()) {
+ for (const entry of (await fs.promises.readdir(file)).sort()) await visit(relative + '/' + entry, logical + '/' + entry);
+ return;
+ }
+ if (!stat.isFile()) throw Error('会话文件类型不受支持');
+ total += stat.size;
+ const hit = cached(relative, stat);
+ let entry;
+ if (hit) {
+ entry = {
+ relative, sourcePath: file, hash: hit.hash, mode: stat.mode & 0o777, mtimeMs: stat.mtimeMs,
+ size: stat.size, ctimeMs: stat.ctimeMs,
+ semantic: typeof hit.semantic === 'string' && hit.semantic ? hit.semantic : null,
+ semanticAliases: Array.isArray(hit.aliases) ? hit.aliases : null,
+ records: Array.isArray(hit.records) ? hit.records : null,
+ };
+ } else if (/^projects\/[^/]+\/__session__\.jsonl$/.test(logical)) {
+ const parsed = await readTranscriptAsync(file, stat, knownIds);
+ entry = {
+ relative, sourcePath: file, hash: parsed.hash, mode: stat.mode & 0o777, mtimeMs: stat.mtimeMs,
+ size: stat.size, ctimeMs: stat.ctimeMs, semantic: parsed.semantic,
+ semanticAliases: [...knownIds], records: parsed.records,
+ };
+ } else {
+ const hashed = await hashFileAsync(file, stat);
+ entry = {
+ relative, sourcePath: file, hash: hashed.hash, mode: stat.mode & 0o777, mtimeMs: stat.mtimeMs,
+ size: stat.size, ctimeMs: stat.ctimeMs, semantic: null, semanticAliases: null, records: null,
+ };
+ }
+ files.set(logical, entry);
+ if (cache) cache.set(relative, {
+ size: entry.size, mtimeMs: entry.mtimeMs, ctimeMs: entry.ctimeMs, hash: entry.hash,
+ mode: entry.mode, semantic: entry.semantic, aliases: entry.semanticAliases, records: entry.records,
+ });
+ }
+
+ const projects = path.join(root, 'projects');
+ try {
+ const projectsStat = await fs.promises.lstat(projects);
+ if (projectsStat.isDirectory() && !projectsStat.isSymbolicLink()) {
+ for (const entry of await fs.promises.readdir(projects, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue;
+ await visit('projects/' + entry.name + '/' + id + '.jsonl', 'projects/' + entry.name + '/__session__.jsonl');
+ await visit('projects/' + entry.name + '/' + id, 'projects/' + entry.name + '/__session__');
+ }
+ }
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
+ for (const prefix of ['workspace/sessions', 'tasks', 'file-history']) await visit(prefix + '/' + id, prefix + '/__session__');
+ await visit('artifact-index/' + id + '.json', 'artifact-index/__session__.json');
+
+ const transcripts = [...files].filter(([key]) => /^projects\/[^/]+\/__session__\.jsonl$/.test(key));
+ if (transcripts.length > 1) throw Error('会话消息文件不唯一,未同步');
+ let records = null, transcriptKey = null;
+ if (transcripts.length) {
+ transcriptKey = transcripts[0][0];
+ const entry = transcripts[0][1];
+ if (!(entry.records && entry.semantic && aliasesEqual(entry.semanticAliases, knownIds))) {
+ const parsed = await readTranscriptAsync(entry.sourcePath, entry, knownIds);
+ if (parsed.hash !== entry.hash) throw Error('会话文件正在变化,请稍后重试');
+ entry.records = parsed.records;
+ entry.semantic = parsed.semantic;
+ entry.semanticAliases = [...knownIds];
+ }
+ records = entry.records;
+ }
+ const indexEntry = files.get('artifact-index/__session__.json');
+ if (indexEntry && !(indexEntry.semantic && aliasesEqual(indexEntry.semanticAliases, knownIds))) {
+ let value;
+ try { value = JSON.parse((await readStableBytesAsync(indexEntry)).toString('utf8')); }
+ catch (error) {
+ if (/变化/.test(String(error && error.message))) throw error;
+ throw Error('会话产物索引损坏,未同步');
+ }
+ indexEntry.semantic = digest(JSON.stringify(canonical(value, knownIds)));
+ indexEntry.semanticAliases = [...knownIds];
+ }
+ for (const entry of files.values()) {
+ if (!entry.semantic) entry.semantic = entry.hash;
+ if (cache) cache.set(entry.relative, {
+ size: entry.size, mtimeMs: entry.mtimeMs, ctimeMs: entry.ctimeMs,
+ hash: entry.hash, mode: entry.mode, semantic: entry.semantic,
+ aliases: entry.semanticAliases ? [...entry.semanticAliases] : null,
+ records: entry.records ? [...entry.records] : null,
+ });
+ }
+ return { root, id, aliases: knownIds, files, records, transcriptKey, totalBytes: total, cache };
+}
+
+// A cheap invalidation marker for the automatic-copy hot path. It deliberately
+// does not read file contents: the normal snapshot path remains the authority
+// whenever the database revision or any shallow session marker changes. The
+// workspace backup directories are excluded because they are local-only data.
+async function readSessionFingerprintAsync(root, id) {
+ if (!validSessionId(id)) throw Error('无效的会话标识');
+ root = await fs.promises.realpath(path.resolve(root));
+ const rootStat = await fs.promises.lstat(root);
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) throw Error('会话目录无法读取');
+ const markers = [];
+ const addStat = async (relative, includeDirectoryTimes = true) => {
+ const file = path.join(root, ...relative.split('/'));
+ let stat;
+ try { stat = await fs.promises.lstat(file); }
+ catch (error) { if (error.code === 'ENOENT') { markers.push([relative, 'missing']); return null; } throw error; }
+ if (stat.isSymbolicLink()) return null;
+ markers.push([relative, stat.isDirectory() ? 'dir' : stat.isFile() ? 'file' : 'other', stat.size,
+ includeDirectoryTimes || !stat.isDirectory() ? stat.mtimeMs : 0,
+ includeDirectoryTimes || !stat.isDirectory() ? stat.ctimeMs : 0, stat.mode & 0o777]);
+ return stat;
+ };
+ const addDirectoryChildren = async (relative, skipNames = new Set()) => {
+ const stat = await addStat(relative, false);
+ if (!stat) return;
+ if (!stat.isDirectory()) throw Error('会话文件类型不受支持');
+ const dir = path.join(root, ...relative.split('/'));
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (skipNames.has(entry.name)) continue;
+ await addStat(relative + '/' + entry.name);
+ }
+ };
+ const sessionRoot = 'workspace/sessions/' + id;
+ await addDirectoryChildren(sessionRoot, new Set(['modify_backup', '.modify_backup_meta']));
+ for (const relative of ['tasks/' + id, 'file-history/' + id]) await addDirectoryChildren(relative);
+ await addStat('artifact-index/' + id + '.json');
+
+ const projects = await addStat('projects', false);
+ if (projects && projects.isDirectory()) {
+ const projectRoot = path.join(root, 'projects');
+ const entries = await fs.promises.readdir(projectRoot, { withFileTypes: true });
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
+ const prefix = 'projects/' + entry.name;
+ await addStat(prefix, false);
+ await addStat(prefix + '/' + id + '.jsonl');
+ await addStat(prefix + '/' + id, false);
+ }
+ }
+ return digest(JSON.stringify(markers));
+}
+
+// Hot-path marker: only fixed session roots and the shared projects directory.
+// Normal WorkBuddy edits also advance the session DB revision; this marker
+// catches file creation/removal without enumerating every project/session file.
+async function readSessionQuickFingerprintAsync(root, id) {
+ if (!validSessionId(id)) throw Error('无效的会话标识');
+ root = await fs.promises.realpath(path.resolve(root));
+ const markers = [];
+ const add = async (relative) => {
+ const file = path.join(root, ...relative.split('/'));
+ try {
+ const stat = await fs.promises.lstat(file);
+ if (stat.isSymbolicLink()) return null;
+ markers.push([relative, stat.isDirectory() ? 'dir' : stat.isFile() ? 'file' : 'other', stat.size,
+ stat.mtimeMs, stat.ctimeMs, stat.mode & 0o777]);
+ } catch (error) {
+ if (error.code === 'ENOENT') { markers.push([relative, 'missing']); return null; }
+ else throw error;
+ }
+ return file;
+ };
+ await add('workspace/sessions/' + id);
+ await add('tasks/' + id);
+ await add('file-history/' + id);
+ await add('artifact-index/' + id + '.json');
+ const projects = await add('projects');
+ try {
+ if (!projects) return digest(JSON.stringify(markers));
+ const entries = await fs.promises.readdir(projects, { withFileTypes: true });
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
+ const prefix = 'projects/' + entry.name;
+ await add(prefix);
+ await add(prefix + '/' + id + '.jsonl');
+ await add(prefix + '/' + id);
+ }
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ }
+ return digest(JSON.stringify(markers));
+}
+
function compareSnapshots(left, right) {
const a = left.records, b = right.records;
if (!a && !b) throw Error('双方会话消息文件均缺失,未同步');
@@ -275,8 +628,26 @@ async function selectTargetSnapshot(source, targetIds, readTarget, preferredId)
const repairs = [], ancestors = [], descendants = [], errors = [];
for (const id of ordered) {
try {
- const snapshot = await readTarget(id);
- const comparison = compareSnapshots(source, snapshot);
+ let snapshot = await readTarget(id);
+ let comparison = compareSnapshots(source, snapshot);
+ // WorkBuddy 5.6 can briefly expose a session file while the account
+ // projection is still settling. A single conflict sample is not enough
+ // evidence of an independent branch: retry the same target before the
+ // caller allocates a new physical session id.
+ if (comparison.kind === 'conflict') {
+ for (const delayMs of [100, 200, 400]) {
+ await new Promise(resolve => setTimeout(resolve, delayMs));
+ try {
+ const retry = await readTarget(id);
+ const retryComparison = compareSnapshots(source, retry);
+ snapshot = retry;
+ comparison = retryComparison;
+ if (comparison.kind !== 'conflict') break;
+ } catch (error) {
+ errors.push(error);
+ }
+ }
+ }
const candidate = { targetId: id, comparison, snapshot: {
id: snapshot.id, records: snapshot.records, transcriptKey: snapshot.transcriptKey,
files: new Map([...snapshot.files].map(([key, file]) => [key, { semantic: file.semantic }])),
@@ -328,7 +699,8 @@ function targetBytes(key, file, source, target) {
}
async function applySnapshot(source, target, options) {
- const { backupRoot, commit = async () => {}, guard = async () => {}, missingOnly = false } = options;
+ const { backupRoot, commit = async () => {}, guard = async () => {}, missingOnly = false,
+ onProgress = () => {} } = options;
if (source.root !== target.root || source.id === target.id) throw Error('无效的会话同步目标');
const changes = [];
for (const [key, file] of source.files) {
@@ -389,6 +761,7 @@ async function applySnapshot(source, target, options) {
if (digest(fs.readFileSync(staged)) !== digest(change.bytes)) throw Error('会话文件校验失败');
fs.utimesSync(staged, new Date(change.mtimeMs), new Date(change.mtimeMs));
fs.renameSync(staged, file);
+ if (change.bytes !== null) onProgress({ bytes: change.bytes.length, relative: change.relative });
} finally { if (fs.existsSync(staged)) fs.unlinkSync(staged); }
}
applied.push(change);
@@ -424,4 +797,140 @@ async function applySnapshot(source, target, options) {
}
}
-module.exports = { readSessionSizes, readSnapshot, compareSnapshots, selectTargetSnapshot, applySnapshot };
+async function unchangedAsync(snapshot) {
+ const now = await readSnapshotAsync(snapshot.root, snapshot.id, snapshot.aliases, snapshot.cache || null);
+ return now.files.size === snapshot.files.size &&
+ [...snapshot.files].every(([key, file]) => now.files.get(key)?.hash === file.hash);
+}
+
+async function targetBytesAsync(key, file, source, target) {
+ if (key !== 'artifact-index/__session__.json') return null;
+ const bytes = await readStableBytesAsync(file);
+ const index = JSON.parse(bytes.toString('utf8'));
+ const artifacts = Array.isArray(index) ? index : index && index.artifacts;
+ if (!Array.isArray(artifacts)) throw Error('产物索引格式不受支持');
+ for (const artifact of artifacts) {
+ if (artifact?._meta && source.aliases.includes(artifact._meta.ownerConversationId)) artifact._meta.ownerConversationId = target.id;
+ }
+ return Buffer.from(JSON.stringify(index));
+}
+
+async function existingHashAsync(file) {
+ try { return (await hashFileAsync(file)).hash; }
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
+}
+
+async function applySnapshotAsync(source, target, options) {
+ const { backupRoot, commit = async () => {}, guard = async () => {}, missingOnly = false,
+ onProgress = () => {} } = options;
+ if (source.root !== target.root || source.id === target.id) throw Error('无效的会话同步目标');
+ const changes = [];
+ for (const [key, file] of source.files) {
+ if (missingOnly && target.files.has(key)) continue;
+ const bytes = await targetBytesAsync(key, file, source, target);
+ const hash = bytes ? digest(bytes) : file.hash;
+ if (target.files.get(key)?.hash === hash) continue;
+ changes.push({
+ key, relative: targetRelative(key, target.id), bytes, sourceFile: file,
+ hash, size: bytes ? bytes.length : file.size, mode: file.mode, mtimeMs: file.mtimeMs,
+ });
+ }
+ if (!missingOnly) for (const [key, file] of target.files) {
+ if (!source.files.has(key)) changes.push({ key, relative: file.relative, bytes: null, sourceFile: null, hash: null, size: 0 });
+ }
+ await guard();
+ if (!await unchangedAsync(source) || !await unchangedAsync(target)) throw Error('会话文件正在变化,请稍后重试');
+ await fs.promises.mkdir(backupRoot, { recursive: true, mode: 0o700 });
+ const backup = await fs.promises.mkdtemp(path.join(backupRoot, 'sync-'));
+ await fs.promises.chmod(backup, 0o700);
+ for (const [key, file] of target.files) {
+ const filePath = await safePathAsync(backup, 'files/' + key);
+ await fs.promises.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
+ await fs.promises.copyFile(file.sourcePath, filePath, fs.constants.COPYFILE_EXCL);
+ await fs.promises.chmod(filePath, 0o600);
+ if ((await hashFileAsync(filePath)).hash !== file.hash) throw Error('会话备份校验失败');
+ }
+ const journal = {
+ version: 1, sourceId: source.id, targetId: target.id, status: 'prepared', metadata: options.metadata || null,
+ files: [...target.files].map(([key, file]) => ({ key, relative: file.relative, mode: file.mode, mtimeMs: file.mtimeMs })),
+ changes: changes.map(change => ({ relative: change.relative, hash: change.hash })),
+ };
+ const journalFile = path.join(backup, 'journal.json');
+ const save = () => fs.promises.writeFile(journalFile, JSON.stringify(journal), { mode: 0o600 });
+ await save();
+ const expected = new Map([...target.files].map(([key, file]) => [key, file.hash]));
+ for (const change of changes) {
+ if (change.hash === null) expected.delete(change.key);
+ else expected.set(change.key, change.hash);
+ }
+ let totalBytes = 0;
+ const verifyPublished = async () => {
+ if (!await unchangedAsync(source)) throw Error('源会话正在变化,已停止同步');
+ const now = await readSnapshotAsync(target.root, target.id, target.aliases, target.cache || null);
+ if (now.files.size !== expected.size || [...expected].some(([key, hash]) => now.files.get(key)?.hash !== hash)) {
+ throw Error('目标会话正在变化,已停止同步');
+ }
+ totalBytes = now.totalBytes;
+ };
+ const applied = [];
+ try {
+ await guard();
+ if (!await unchangedAsync(source) || !await unchangedAsync(target)) throw Error('会话文件正在变化,请稍后重试');
+ for (const change of changes) {
+ const file = await safePathAsync(target.root, change.relative);
+ const old = target.files.get(change.key);
+ const currentHash = await existingHashAsync(file);
+ if (old ? currentHash !== old.hash : currentHash !== null) throw Error('目标会话正在变化,已停止同步');
+ if (change.hash === null) {
+ await fs.promises.unlink(file);
+ } else {
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
+ const staged = path.join(path.dirname(file), '.wbs-sync-' + crypto.randomUUID());
+ try {
+ if (change.bytes) await fs.promises.writeFile(staged, change.bytes, { mode: change.mode || 0o600, flag: 'wx' });
+ else await fs.promises.copyFile(change.sourceFile.sourcePath, staged, fs.constants.COPYFILE_EXCL);
+ if ((await hashFileAsync(staged)).hash !== change.hash) throw Error('会话文件校验失败');
+ await fs.promises.chmod(staged, change.mode || 0o600);
+ await fs.promises.utimes(staged, new Date(change.mtimeMs), new Date(change.mtimeMs));
+ await fs.promises.rename(staged, file);
+ // Report only after the published target has been replaced. The
+ // daemon uses this to update the live "actual written" counter.
+ if (change.hash !== null) await onProgress({ bytes: change.size, relative: change.relative });
+ } finally { try { await fs.promises.unlink(staged); } catch (error) { if (error.code !== 'ENOENT') throw error; } }
+ }
+ applied.push(change);
+ }
+ await verifyPublished();
+ await commit(verifyPublished);
+ journal.status = 'committed';
+ let journalPending = false;
+ try { await save(); } catch (_) { journalPending = true; }
+ const copiedBytes = changes.reduce((sum, change) => sum + (change.hash === null ? 0 : change.size), 0);
+ return { backup, copied: changes.length, copiedBytes, journalPending, totalBytes };
+ } catch (error) {
+ let incomplete = false;
+ for (const change of applied.reverse()) {
+ try {
+ const file = await safePathAsync(target.root, change.relative);
+ const currentHash = await existingHashAsync(file);
+ if (change.hash === null ? currentHash !== null : currentHash !== change.hash) { incomplete = true; continue; }
+ const old = target.files.get(change.key);
+ if (old) {
+ const backupFile = await safePathAsync(backup, 'files/' + change.key);
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
+ await fs.promises.copyFile(backupFile, file);
+ await fs.promises.chmod(file, old.mode || 0o600);
+ await fs.promises.utimes(file, new Date(old.mtimeMs), new Date(old.mtimeMs));
+ } else if (currentHash !== null) await fs.promises.unlink(file);
+ } catch (_) { incomplete = true; }
+ }
+ journal.status = incomplete ? 'recovery-needed' : 'rolled-back';
+ try { await save(); } catch (_) { /* Keep the original failure and retained backup. */ }
+ throw error;
+ }
+}
+
+module.exports = {
+ readSessionSizes, readSnapshot, readSnapshotAsync, readSessionFingerprintAsync, readSessionQuickFingerprintAsync, compareSnapshots, selectTargetSnapshot,
+ applySnapshot, applySnapshotAsync,
+};
diff --git a/scripts/workbuddy-compat.js b/scripts/workbuddy-compat.js
index ea2d635..5a662da 100644
--- a/scripts/workbuddy-compat.js
+++ b/scripts/workbuddy-compat.js
@@ -365,6 +365,45 @@
return findModernQueueAdapter(doc) || findLegacyQueueAdapter(doc);
}
+ function functionLooksLikeConversationNavigation(value) {
+ if (typeof value !== 'function') return false;
+ try {
+ var source = Function.prototype.toString.call(value);
+ return source.indexOf('dismissHoverPeek') >= 0 &&
+ source.indexOf('syncTaskRouteFromClick') >= 0;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ function findConversationNavigationHandler(doc) {
+ if (!doc || typeof doc.querySelector !== 'function') return null;
+ var roots = [
+ doc.querySelector('#root > div'),
+ doc.querySelector('.conversation-list'),
+ doc.querySelector('.conversation-shell'),
+ doc.querySelector('.conversation-item'),
+ ];
+ for (var ri = 0; ri < roots.length; ri++) {
+ var root = roots[ri];
+ var fiber = reactFiber(root);
+ var fiberSeen = 0;
+ while (fiber && fiberSeen++ < 700) {
+ var hook = fiber.memoizedState;
+ var hookSeen = 0;
+ while (hook && hookSeen++ < 700) {
+ var state = hook.memoizedState;
+ var candidate = state && typeof state === 'object' ? state.current : null;
+ if (functionLooksLikeConversationNavigation(candidate)) return candidate;
+ if (functionLooksLikeConversationNavigation(state)) return state;
+ hook = hook.next;
+ }
+ fiber = fiber.return;
+ }
+ }
+ return null;
+ }
+
function isSessionsResource(value) {
return !!value && typeof value === 'object' &&
typeof value.on === 'function' && typeof value.off === 'function' &&
@@ -379,6 +418,73 @@
return isSessionsResource(resource) ? resource : null;
}
+ // WorkBuddy's conversation list owns the real navigation path. Prefer the
+ // official SDK/navigation handler; adapter.emit is retained for older builds
+ // whose list did not expose the handler through React hooks.
+ function findConversationActivationApi(doc) {
+ var found = findQueueAdapter(doc);
+ var adapter = found && found.adapter;
+ var resource = findSessionsResource(doc);
+ var handler = findConversationNavigationHandler(doc);
+ var sdkNavigate = null;
+ var sdkNavigateKind = '';
+ try {
+ var conversations = typeof window !== 'undefined' && window.wb && window.wb.conversations;
+ if (conversations && typeof conversations.navigateToSession === 'function') {
+ sdkNavigate = conversations.navigateToSession;
+ sdkNavigateKind = 'navigateToSession';
+ } else if (conversations && typeof conversations.setCurrentConversation === 'function') {
+ // Current WorkBuddy exposes the official route transition under this
+ // SDK name. It is authoritative even while React has not mounted the
+ // sidebar handler yet, which is the common post-reload window.
+ sdkNavigate = conversations.setCurrentConversation;
+ sdkNavigateKind = 'setCurrentConversation';
+ }
+ } catch (_) {}
+ if (!handler && !sdkNavigate && (!adapter || typeof adapter.emit !== 'function')) return null;
+ return {
+ authoritative: !!(handler || sdkNavigate),
+ hasSession: function (sessionId) {
+ var id = String(sessionId || '').trim();
+ if (!id || !resource || typeof resource.getByIds !== 'function') return Promise.resolve(null);
+ try {
+ return Promise.resolve(resource.getByIds([id])).then(function (result) {
+ // The renderer adapter normalizes the session resource response to
+ // `conversations`; lower-level/test adapters may expose `sessions`
+ // or return the array directly.
+ var sessions = result && Array.isArray(result.conversations) ? result.conversations :
+ result && Array.isArray(result.sessions) ? result.sessions :
+ Array.isArray(result) ? result : [];
+ return sessions.some(function (item) { return String(item && (item.id || item.sessionId) || '') === id; });
+ });
+ } catch (_) {
+ return Promise.resolve(false);
+ }
+ },
+ activate: function (sessionId) {
+ var id = String(sessionId || '').trim();
+ if (!id) return false;
+ try {
+ if (handler) {
+ Promise.resolve(handler(id, '', false, false, {})).catch(function () {});
+ } else if (sdkNavigate) {
+ var conversationsApi = (typeof window !== 'undefined' && window.wb && window.wb.conversations) || null;
+ Promise.resolve(sdkNavigate.call(conversationsApi, id, sdkNavigateKind === 'navigateToSession' ? { ensureLoaded: true } : undefined)).catch(function () {});
+ } else {
+ adapter.emit('jump-to-conversation', {
+ source: 'tencent-docs',
+ sessionId: id,
+ reason: 'already-active',
+ });
+ }
+ return true;
+ } catch (_) {
+ return false;
+ }
+ },
+ };
+ }
+
// Sidebar records are an initial/reconciliation snapshot only. Live updates
// come from sessionsResource; this narrow fiber walk avoids scanning the page.
function findConversationListRecords(doc) {
@@ -450,6 +556,7 @@
findModernQueueAdapter: findModernQueueAdapter,
findQueueAdapter: findQueueAdapter,
findSessionsResource: findSessionsResource,
+ findConversationActivationApi: findConversationActivationApi,
findConversationListRecords: findConversationListRecords,
findMessageNavigationAdapter: findMessageNavigationAdapter,
findMessageNavigationSurface: findMessageNavigationSurface,
diff --git a/test/agent-new-task-draft.test.js b/test/agent-new-task-draft.test.js
index 135cfca..134ca7b 100644
--- a/test/agent-new-task-draft.test.js
+++ b/test/agent-new-task-draft.test.js
@@ -6,26 +6,61 @@ const vm = require('node:vm');
const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/daemon.js'), 'utf8');
const functions = source.slice(source.indexOf('async function ensureAutomationNewTask('), source.indexOf('\nfunction currentAccount()'));
function harness(options = {}) {
- let sessionSent = false; let clock = 0;
+ let sessionSent = false; let modelConversation = false; let clock = 0; let receiptProbes = 0; let clearReads = 0; let clearing = false;
const calls = []; let draft = options.draft === false ? '' : 'existing draft'; let ready = !options.project;
const context = { automationAgentSurfaceExpression: () => '({newTaskReady:true})', cdp: { connected: true }, sleep: async ms => { clock += ms; }, Date: { now: () => clock },
- readAutomationAgentSurface: async () => ({ ready: true, newTaskReady: ready, hasComposer: true, composerText: draft, button: {x:1,y:1} }),
+ readAutomationAgentSurface: async () => {
+ if (clearing && options.clearAfterReads && clearReads++ >= options.clearAfterReads) draft = '';
+ return { ready: true, newTaskReady: ready, hasComposer: true, composerText: draft, button: {x:1,y:1} };
+ },
cdpMouseClick: async () => { calls.push('navigate'); ready = true; },
cdpSend: async (method, params) => {
- if (method === 'Runtime.evaluate' && params.expression.includes('probeSessionReceipt')) return {result:{value:sessionSent?{conversationId:'c',userMessageId:'u',requestId:'r'}:null}};
+ if (method === 'Runtime.evaluate' && params.expression.includes('probeSessionReceipt')) {
+ receiptProbes++;
+ const confirmed = sessionSent && receiptProbes >= (options.receiptAfterProbes || 1);
+ const provisional = options.modelCreatesConversation && modelConversation
+ ? { conversationId: 'c', userMessageId: '', requestId: '' }
+ : null;
+ const initial = options.initialConversation && !sessionSent
+ ? { conversationId: 'old', userMessageId: '', requestId: '' }
+ : null;
+ return {result:{value:confirmed?{conversationId:'c',userMessageId:'u',requestId:'r'}:provisional || initial}};
+ }
calls.push(method);
if (method === 'Runtime.evaluate') { if (options.draftChanges) draft = 'newly typed draft'; return { result: { value: { saved: !options.backupFails } } }; }
- if (params.key === 'Backspace' && params.type === 'keyDown') draft = '';
+ if (params.key === 'Backspace' && params.type === 'keyDown') {
+ clearing = true;
+ if (!options.clearAfterReads) draft = '';
+ }
return {};
},
sendStashToComposer: async () => { calls.push('send'); return { sent: true }; },
};
vm.createContext(context);vm.runInContext(functions,context);
const callback = source.slice(source.indexOf(' let lastReceipt = null;'), source.indexOf(' const completionReport =', source.indexOf(' let lastReceipt = null;')));
- Object.assign(context,require('../scripts/automation-runtime'),{withInput:async fn=>fn(),isCancelled:()=>false,currentAccount:()=>({uid:'a'})});
- context.acSendPhrase = async () => { calls.push('session-send'); sessionSent=true; return {sent:true}; };
+ Object.assign(context,require('../scripts/automation-runtime'),{
+ withInput:async fn=>fn(),isCancelled:()=>false,currentAccount:()=>({uid:'a'}),cancellableWait:async ms=>{clock+=ms;},
+ normalizeAutomationModelId:model=>model,
+ selectAutomationModelById:async()=>{modelConversation=true;return {displayName:'Deepseek',changed:false};},
+ confirmAutomationModel:async()=>true,
+ appendRunLog:message=>calls.push(message),
+ });
+ context.acSendPhrase = async (message, sendOptions = {}) => {
+ if (sendOptions.guard) await sendOptions.guard();
+ if (sendOptions.beforeSubmit) await sendOptions.beforeSubmit();
+ calls.push('session-send'); sessionSent=true;
+ // The real sender runs the guard again while observing the composer after
+ // the click, when a New Task controller may have just mounted.
+ if (sendOptions.guard) await sendOptions.guard();
+ return {sent:true};
+ };
vm.runInContext(callback + '\nthis.sessionSend = sessionSendCurrent; this.sessionAction = sessionAction;', context);
- return { run: () => context.openNewAutomationAgentTask('Agent requirement'), session: () => context.sessionSend('1+1='), calls };
+ return {
+ run: () => context.openNewAutomationAgentTask('Agent requirement'),
+ session: () => context.sessionSend('1+1='),
+ sessionWithModel: () => context.sessionAction('session.create', { message: '1+1=', model: 'deepseek-v4.1-flash' }),
+ calls,
+ };
}
test('Agent creation saves a new-task draft before clearing and sending', async () => {
const h=harness();await h.run();assert.ok(h.calls.indexOf('Runtime.evaluate')<h.calls.indexOf('Input.dispatchKeyEvent'));assert.equal(h.calls.at(-1),'send');
@@ -55,3 +90,33 @@ test('automation session.sendCurrent refuses to send if saving fails or the draf
const h=harness(options);await assert.rejects(h.session());assert.ok(!h.calls.includes('session-send'));assert.ok(!h.calls.includes('Input.dispatchKeyEvent'));
}
});
+
+test('controlled New Task composer may clear after several renderer probes', async () => {
+ const h=harness({clearAfterReads:3});await h.run();assert.equal(h.calls.at(-1),'send');
+});
+
+test('new-session receipt may mount after the former twelve-second window', async () => {
+ const h=harness({draft:false,receiptAfterProbes:150});await h.session();assert.equal(h.calls.at(-1),'session-send');
+});
+
+test('new session accepts the first conversation mounted after the send', async () => {
+ const h=harness({draft:false});
+ await h.session();
+ assert.ok(h.calls.includes('session-send'));
+});
+
+test('new session accepts the expected conversation transition after the send', async () => {
+ const h=harness({draft:false,initialConversation:true});
+ await h.session();
+ assert.ok(h.calls.includes('session-send'));
+});
+
+test('model selection may mount the provisional new conversation before sending', async () => {
+ const h=harness({draft:false,modelCreatesConversation:true});await h.sessionWithModel();assert.ok(h.calls.includes('session-send'));
+});
+
+test('model selection replaces a stale pre-navigation controller before sending', async () => {
+ const h=harness({draft:false,initialConversation:true,modelCreatesConversation:true});
+ await h.sessionWithModel();
+ assert.ok(h.calls.includes('session-send'));
+});
diff --git a/test/auto-copy-rules.test.js b/test/auto-copy-rules.test.js
index 385a5f8..a972f9e 100644
--- a/test/auto-copy-rules.test.js
+++ b/test/auto-copy-rules.test.js
@@ -29,6 +29,7 @@ const {
collectLineageMembersForDelete,
setAutoCopyMapping,
getAutoCopyMapping,
+ migrateAutoCopyTargetRevisions,
getAutoCopySessionMemberRecords,
selectLatestAutoCopyMember,
listOfficialModels,
@@ -119,6 +120,20 @@ test('marked session keeps one lineage through migration and repeated account sw
assert.equal(getAutoCopySession(dataDir, 'x', 'session-a').enabled, false);
});
+test('historical target revisions are migrated in one metadata update', () => {
+ const dataDir = tempDataDir();
+ setAutoCopyRule(dataDir, { uid: 'source', kind: 'session', key: 'session-a', enabled: true });
+ const lineageId = getAutoCopySession(dataDir, 'source', 'session-a').lineageId;
+ addAutoCopySessionMember(dataDir, lineageId, 'target', 'session-b');
+ setAutoCopyMapping(dataDir, lineageId, 'target', { targetId: 'session-b', fingerprintVersion: 2, targetStateRevision: 'legacy' });
+ const row = { id: 'session-b', user_id: 'target', updated_at: 20, last_activity_at: 21, status: 'Done', title: 'title', custom_title: '' };
+ assert.equal(migrateAutoCopyTargetRevisions(dataDir, new Map([[JSON.stringify(['session-b', 'target']), row]])), 1);
+ const mapping = getAutoCopyMapping(dataDir, lineageId, 'target');
+ assert.equal(mapping.targetStateRevision, JSON.stringify([20, 21, 'Done', 'title', '']));
+ assert.equal(mapping.targetRevision, JSON.stringify(['session-b', 'target', 20, 21, 'Done', 'title', '']));
+ assert.equal(migrateAutoCopyTargetRevisions(dataDir, new Map([[JSON.stringify(['session-b', 'target']), row]])), 0);
+});
+
test('deleting the last lineage member removes mappings, while other members retain them', () => {
const dataDir = tempDataDir();
setAutoCopyRule(dataDir, { uid: 'h', kind: 'session', key: 'session-a', enabled: true });
@@ -274,6 +289,16 @@ test('copy-all can prepare hidden lineages for a session batch without enabling
assert.deepEqual(getAutoCopyRules(dataDir, 'source').sessionIds, []);
});
+test('preparing an unchanged auto-copy batch does not rewrite metadata', () => {
+ const dataDir = tempDataDir();
+ ensureAutoCopySessions(dataDir, 'source', ['new-a', 'new-b'], { enabled: false });
+ const before = fs.statSync(metaFile(dataDir));
+ ensureAutoCopySessions(dataDir, 'source', ['new-a', 'new-b'], { enabled: false });
+ const after = fs.statSync(metaFile(dataDir));
+ assert.equal(after.ino, before.ino);
+ assert.equal(after.size, before.size);
+});
+
test('duplicate session rows sharing one lineage collapse per account without deleting rows', () => {
const rows = [
{ id: 's-new', user_id: 'account-s' },
diff --git a/test/automation-checkin.test.js b/test/automation-checkin.test.js
index 42299eb..65e1e16 100644
--- a/test/automation-checkin.test.js
+++ b/test/automation-checkin.test.js
@@ -73,6 +73,7 @@ function claimHarness({stored=null,cached=null}={}) {
const ctx={Map,Promise,Date,PROFILE:{capabilities:{accounts:true,checkin:true}},todayStr:()=> '2026-09-08',
CREDIT_USAGE_STORE:{getDailyCheckin:async()=>stored,saveDailyCheckin:async()=>{}},
loadCheckinCache:()=>cached?{a:cached}:records,saveCheckinCache:()=>{},
+ wdCompatAuthToken:(auth)=>auth && typeof auth.accessToken==='string' ? auth.accessToken : '',
classifyCheckinResult:require('../scripts/checkin-result').classifyCheckinResult,
refreshAccountBackupToken:async()=>{refreshes++;return {root:{auth:{accessToken:'test-token'}}};},
dailyCheckin:async()=>{requests++;await Promise.resolve();return {ok:true,code:0,message:'ok'};},log:()=>{},
diff --git a/test/automation-model.test.js b/test/automation-model.test.js
index 9f8cbcc..a2844ae 100644
--- a/test/automation-model.test.js
+++ b/test/automation-model.test.js
@@ -157,9 +157,10 @@ test('daemon selects and checks the model before sending, and ships the renderer
const selectAt = daemon.indexOf('modelSelection = await withInput(() => selectAutomationModelById(');
const sendAt = daemon.indexOf("await withInput(() => acSendPhrase(String(detail.message || '')");
assert.ok(selectAt > 0 && sendAt > selectAt);
- assert.match(daemon, /if \(modelId\) await confirmAutomationModel\(modelId/);
+ assert.match(daemon, /if \(modelId && !sendSubmitted\) await confirmAutomationModel\(modelId/);
assert.match(daemon, /restoreAutomationNewTaskPreference\(modelSelection\)/);
- assert.match(daemon, /const DAEMON_VERSION = '1\.2\.95'/);
+ assert.match(daemon, /selected && selected\.conversationId \? \{ conversationId: selected\.conversationId, accountUid \}/);
+ assert.match(daemon, /const DAEMON_VERSION = '\d+\.\d+\.\d+'/);
const staging = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');
assert.match(staging, /automation-model\.js/);
});
diff --git a/test/automation-runtime.test.js b/test/automation-runtime.test.js
index 9d5c124..2a891f9 100644
--- a/test/automation-runtime.test.js
+++ b/test/automation-runtime.test.js
@@ -22,7 +22,8 @@ test('completion is bound to user request, conversation and assistant identity',
assert.equal(receiptComplete(receipt,snap),true);
assert.equal(receiptComplete(receipt,{...snap,assistantId:'a0'}),false);
assert.equal(receiptComplete(receipt,{...snap,busy:true}),false);
- assert.throws(()=>receiptComplete(receipt,{...snap,userMessageId:'u2'}));
+ assert.throws(()=>receiptComplete(receipt,{...snap,userMessageId:'u2',requestId:'r2'}));
+ assert.equal(receiptComplete(receipt,{...snap,userMessageId:'u2'}),true,'5.6 may replace the optimistic user id while retaining requestId');
assert.throws(()=>receiptComplete(receipt,{...snap,conversationId:'other'}));
assert.throws(()=>receiptComplete(receipt,{...snap,cancelled:true}));
});
@@ -30,7 +31,7 @@ test('completion is bound to user request, conversation and assistant identity',
const fs=require('node:fs'),vm=require('node:vm');
const daemon=fs.readFileSync(require('node:path').join(__dirname,'../scripts/daemon.js'),'utf8');
function httpHarness(fetchImpl,read=()=>'{"auth":{"accessToken":"fake-test-token"}}') {
- const scope={URL,Buffer,AbortController,setTimeout,clearTimeout,setInterval,clearInterval,fetch:fetchImpl,fs:{readFileSync:read},accountBackupFile:()=>'/fake',PROFILE:{apiHost:'https://www.codebuddy.cn'},assertAccountRequestUrl};
+ const scope={URL,Buffer,AbortController,setTimeout,clearTimeout,setInterval,clearInterval,fetch:fetchImpl,fs:{readFileSync:read},accountBackupFile:()=>'/fake',PROFILE:{apiHost:'https://www.codebuddy.cn'},assertAccountRequestUrl,wdCompatDecryptAuthJson:(x)=>x,wdCompatAuthToken:(auth)=>auth && typeof auth.accessToken==='string' ? auth.accessToken : ''};
vm.runInNewContext(daemon.slice(daemon.indexOf('async function automationHttpRequest('),daemon.indexOf('\nfunction automationPublicRun(')),scope);return scope.automationHttpRequest;
}
test('HTTP daemon denies token access before reading backups; aborts fetch on stop',async()=>{
@@ -55,3 +56,17 @@ test('renderer receipt probe uses real messageType shape without returning priva
assert.equal(result.userMessageId,'u');assert.equal(result.requestId,'r');assert.equal(result.complete,false,'explicit non-terminal wins over interim complete');
assert.ok(!JSON.stringify(result).includes('private'));
});
+test('renderer receipt probe stays bound to the requested message in a 5.6 message list',()=>{
+ const {probeSessionReceipt}=require('../scripts/automation-runtime');
+ const state={messages:[
+ {messageType:'user',id:'u1',requestId:'r1'},
+ {messageType:'assistant',id:'a1',requestId:'r1',complete:true,extra:{isRequestTerminal:true}},
+ {messageType:'user',id:'u2',requestId:'r2'},
+ {messageType:'assistant',id:'a2',requestId:'r2',complete:true,extra:{isRequestTerminal:true}},
+ ]};
+ const compat={getSelectedConversationId:()=> 'c',findConversationControllers:()=>[{conversationId:'c',messageStore:{getState:()=>state},getSessionViewState:()=>({})}]};
+ const result=vm.runInNewContext('('+probeSessionReceipt.toString()+')({userMessageId:"u1",requestId:"r1"})',{window:{__wbsWorkBuddyCompat:compat},document:{}});
+ assert.equal(result.userMessageId,'u1');
+ assert.equal(result.requestId,'r1');
+ assert.equal(result.assistantId,'a1');
+});
diff --git a/test/automation-switch-sync.test.js b/test/automation-switch-sync.test.js
index dc054a6..74bb317 100644
--- a/test/automation-switch-sync.test.js
+++ b/test/automation-switch-sync.test.js
@@ -24,7 +24,7 @@ function harness() {
let complete;
const job = { id: 'job-' + jobs.length, targetUid: to, status: 'running', total: 1, processed: 0,
failed: 0, partial: 0, conflicts: 0, completion: new Promise(resolve => { complete = resolve; }) };
- job.finish = (status = 'done') => { job.status = status; job.processed = 1; ctx.autoCopyWorkerRunning = false; if (ctx.recordAccountSyncResult) ctx.recordAccountSyncResult(job); complete(job); };
+ job.finish = (status = 'done', details = []) => { job.status = status; job.processed = 1; job.details = details; ctx.autoCopyWorkerRunning = false; if (ctx.recordAccountSyncResult) ctx.recordAccountSyncResult(job); complete(job); };
ctx.autoCopyWorkerRunning = true; ctx.autoCopyJobs.set(job.id, job); jobs.push(job); return job;
},
};
@@ -108,3 +108,12 @@ test('pruning public job history cannot erase failed synchronization; successful
await tick(); await tick(); h.jobs[2].finish(); await run;
assert.deepEqual(h.switches, ['b']);
});
+
+test('an empty message-file session does not block automation account switching', async () => {
+ const h = harness();
+ const run = h.ctx.automationSwitchAccount({ uid: 'b' }, h.options);
+ await tick(); await tick();
+ h.jobs[0].finish('partial', [{ status: 'failed', error: '会话消息文件没有消息,未同步' }]);
+ await run;
+ assert.deepEqual(h.switches, ['b']);
+});
diff --git a/test/automation-ui-copy.test.js b/test/automation-ui-copy.test.js
index 22b4171..5c9cc76 100644
--- a/test/automation-ui-copy.test.js
+++ b/test/automation-ui-copy.test.js
@@ -24,7 +24,6 @@ test('six session feature descriptions omit terminal Chinese periods', () => {
'暂存想法择机发送,发送后自动删除',
'悬停预览,点击或拖动快速定位消息',
'复制到这条回复为止的聊天内容,在当前工作区继续聊;原会话不变',
- '选中会话消息文字后,一键插入输入框',
'发送后不会自动删除',
];
for (const hint of hints) assert.ok(source.includes('<span class="wbs-nd-hint">' + hint + '</span>'), hint);
diff --git a/test/avatar-automation-stop.test.js b/test/avatar-automation-stop.test.js
new file mode 100644
index 0000000..39614b0
--- /dev/null
+++ b/test/avatar-automation-stop.test.js
@@ -0,0 +1,59 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const injectPath = path.join(__dirname, '../scripts/inject.js');
+const source = fs.readFileSync(injectPath, 'utf8');
+const { findLatestManualAutomationRun } = require('../scripts/inject');
+
+test('floating stop control targets only the latest running manual automation', () => {
+ const tasks = [
+ { id: 'manual-old', manualRunnable: true },
+ { id: 'scheduled', manualRunnable: false },
+ { id: 'manual-new', manualRunnable: true },
+ ];
+ const runs = [
+ { id: 'run-old', taskId: 'manual-old', status: 'running', startedAt: 10 },
+ { id: 'run-scheduled', taskId: 'scheduled', status: 'running', startedAt: 30 },
+ { id: 'run-finished', taskId: 'manual-new', status: 'success', startedAt: 40 },
+ { id: 'run-new', taskId: 'manual-new', status: 'running', startedAt: 20 },
+ ];
+
+ assert.equal(findLatestManualAutomationRun(tasks, runs).id, 'run-new');
+ assert.equal(findLatestManualAutomationRun(tasks, runs.filter((run) => run.taskId === 'scheduled')), null);
+});
+
+test('theme avatar keeps three built-ins, defaults to the second, and removes all captions', () => {
+ assert.match(source, /state = \{ selected: 'workbuddy', items: \[\] \}/);
+ const first = source.match(/<label class="wbs-avatar-option wbs-avatar-default-option"[\s\S]*?<\/label>/);
+ assert.ok(first, 'the supplied avatar should replace the old refresh mark');
+ assert.match(first[0], /<img class="wb-avatar__img" data-avatar-image="default"/);
+ assert.doesNotMatch(first[0], /wbs-avatar-default-mark|<svg/);
+ assert.doesNotMatch(first[0], /<span>/);
+ const preset = source.match(/<label class="wbs-avatar-option" title="WorkBuddy">[^']+value="workbuddy"[^']+<\/label>/);
+ assert.ok(preset, 'the second WorkBuddy avatar preset should exist');
+ assert.doesNotMatch(preset[0], /<span>/);
+ const workdaddy = source.match(/<label class="wbs-avatar-option" title="WorkDaddy">[^']+value="workdaddy"[^']+<\/label>/);
+ assert.ok(workdaddy, 'the third WorkDaddy avatar preset should exist');
+ assert.doesNotMatch(workdaddy[0], /<span>/);
+
+ const image = source.match(/var OFFICIAL_AVATAR = '(data:image\/png;base64,([^']+))'/);
+ assert.ok(image, 'the supplied default avatar should remain embedded as the first preset source');
+ assert.equal(Buffer.from(image[2], 'base64').subarray(0, 8).toString('hex'), '89504e470d0a1a0a');
+ assert.match(source, /var DEFAULT_AVATAR = OFFICIAL_AVATAR;/);
+ assert.match(source, /svgToPng\(OFFICIAL_LOGO_SVG, 96\)/);
+ assert.match(source, /input\.value === 'default' \? DEFAULT_AVATAR/);
+});
+
+test('floating manual automation stop uses the existing safe-stop endpoint', () => {
+ assert.match(source, /class="wbs-automation-stop"[^>]+aria-label="停止运行"/);
+ assert.match(source, /AUTO_TAB_SVG \+ '<span class="wbs-automation-stop-label">停止运行<\/span>'/);
+ assert.match(source, /data-tab="automations">' \+ AUTO_TAB_SVG \+ '<span>自动化<\/span>/);
+ assert.match(source, /findLatestManualAutomationRun\(result && result\.tasks, result && result\.runs\)/);
+ assert.match(source, /api\('\/api\/automations\/stop',[\s\S]*JSON\.stringify\(\{ runId: runId \}\)/);
+ assert.match(source, /\.wbs-root\[data-wbs-robot-style="black"\] \.wbs-automation-stop/);
+ assert.match(source, /--wbs-robot-shell/);
+});
diff --git a/test/avatar-library-credit-opacity.test.js b/test/avatar-library-credit-opacity.test.js
index c151b5d..bb1a64f 100644
--- a/test/avatar-library-credit-opacity.test.js
+++ b/test/avatar-library-credit-opacity.test.js
@@ -26,13 +26,15 @@ test('legacy upload survives selecting either preset and adding multiple avatars
const { createAvatarLibrary } = load(), cache = storage({wbsAvatar:png});
const lib = createAvatarLibrary(cache);
assert.equal(lib.snapshot().items[0].src,png);
- lib.select('workbuddy'); lib.select('workdaddy');
+ lib.select('default'); lib.select('workbuddy'); lib.select('workdaddy');
const added = lib.add(webp);
assert.equal(lib.snapshot().items.length,2);
assert.equal(lib.snapshot().selected,added);
const restored = createAvatarLibrary(cache);
assert.equal(restored.snapshot().selected,added);
assert.equal(restored.snapshot().items[0].src,png);
+ restored.select('default');
+ assert.equal(createAvatarLibrary(cache).snapshot().selected,'default');
restored.select('workbuddy');
restored.remove(added);
assert.equal(restored.snapshot().selected,'workdaddy');
diff --git a/test/builtin-wallpaper.test.js b/test/builtin-wallpaper.test.js
index fd4c809..f90265d 100644
--- a/test/builtin-wallpaper.test.js
+++ b/test/builtin-wallpaper.test.js
@@ -26,13 +26,13 @@ test('built-in official wallpapers refresh stale managed copies', () => {
assert.equal(fs.readFileSync(wallpaperOverride, null).subarray(0, 4).toString('ascii'), 'RIFF');
});
-test('a fresh profile starts with the WorkDaddy wallpaper theme', () => {
+test('a fresh profile starts with the light theme', () => {
const start = daemon.indexOf('function initBuiltinAssets()');
const end = daemon.indexOf('\n/** 内置主题', start);
const source = daemon.slice(start, end);
- assert.match(source, /JSON\.stringify\(\{ id: 'nebula'/);
- assert.doesNotMatch(source, /JSON\.stringify\(\{ id: 'default'/);
+ assert.match(source, /JSON\.stringify\(\{ id: 'default'/);
+ assert.doesNotMatch(source, /JSON\.stringify\(\{ id: 'nebula'/);
});
test('release builders stage the tracked wallpaper override as wallpaper 6 and the default background', () => {
diff --git a/test/conversation-usage.test.js b/test/conversation-usage.test.js
index b541d3e..b41fb72 100644
--- a/test/conversation-usage.test.js
+++ b/test/conversation-usage.test.js
@@ -78,3 +78,19 @@ test('conversation usage UI uses a body-fixed mount, bottom spacer and message s
assert.match(source, /wbs-session-usage-summary\.is-hidden/);
assert.doesNotMatch(source, /conversation-finished-footer[\s\S]{0,120}usage/);
});
+
+test('usage trend reserves horizontal label space so endpoint values stay visible', () => {
+ const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ const chart = source.slice(source.indexOf('function renderUsageTrendChart'), source.indexOf('function usageTimeSegmentHtml'));
+ assert.match(chart, /measureText\(/);
+ assert.match(chart, /chartInset = Math\.max\(/);
+ assert.match(chart, /chartRight = cssWidth - chartInset/);
+});
+
+test('credit model breakdown follows the selected account filter', () => {
+ const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ const start = source.indexOf('var byModel = Object.create(null);');
+ const end = source.indexOf("creditBody.innerHTML =", start);
+ assert.ok(start >= 0 && end > start);
+ assert.match(source.slice(start, end), /if \(ids\.indexOf\(item\.uid\) < 0\) return;/);
+});
diff --git a/test/credit-history-sync.test.js b/test/credit-history-sync.test.js
index 78df8c5..964afca 100644
--- a/test/credit-history-sync.test.js
+++ b/test/credit-history-sync.test.js
@@ -74,6 +74,21 @@ test('repeated credit queries reuse complete daily API results', async () => {
assert.equal(second.daily.find(d => d.date === '2026-09-12').used, 1);
});
+test('historical credit results retain model totals when the official usage rows provide a model', async () => {
+ const sync = createCreditHistorySync({ now: () => now, getAccessToken: async () => 'test', fetchUsage: async () => ({ records: [
+ { usageDate: '2026-09-12', credit: 1.25, requestId: 'a', model: 'Model A' },
+ { usageDate: '2026-09-12', credit: 2.5, requestId: 'b', model: 'Model B' },
+ { usageDate: '2026-09-12', credit: 0.75, requestId: 'c', model: 'Model A' },
+ ] }) });
+ sync.start({ accounts: [{ uid: 'one' }] });
+ const result = await settle(sync);
+ const day = result.daily.find(item => item.date === '2026-09-12');
+ assert.deepEqual(day.models, {
+ 'Model A': { used: 2, count: 2 },
+ 'Model B': { used: 2.5, count: 1 },
+ });
+});
+
test('failed account contributes no cached values or false zero records', async () => {
const sync = createCreditHistorySync({ now: () => now, getAccessToken: async uid => uid,
fetchUsage: async o => { if (o.accessToken === 'bad') throw Error('timeout'); return { records: [] }; }
diff --git a/test/credit-rotation.test.js b/test/credit-rotation.test.js
index 08fa181..3de1f7b 100644
--- a/test/credit-rotation.test.js
+++ b/test/credit-rotation.test.js
@@ -55,13 +55,13 @@ test('rotation refresh compares every saved account using fresh segments', async
const accounts = [{ uid: 'current' }, { uid: 'cached-later' }, { uid: 'fresh-sooner' }];
const queried = [];
let fail = false;
- const refresh = new Function('listAccounts', 'DATA_DIR', 'fs', 'accountBackupFile', 'fetchCredits', `return ${source} refreshCreditRotationAccounts;`)(
+ const refresh = new Function('listAccounts', 'DATA_DIR', 'fs', 'accountBackupFile', 'fetchCredits', 'wdCompatDecryptAuthJson', 'wdCompatAuthToken', `return ${source} refreshCreditRotationAccounts;`)(
() => accounts, '', { readFileSync: (file) => JSON.stringify({ auth: { accessToken: file } }) },
uid => uid, async token => {
queried.push(token);
if (fail && token === 'fresh-sooner') throw new Error('积分查询失败');
return { segments: [{ remaining: 20, expiresAt: now + (token === 'fresh-sooner' ? 3_600_000 : 86_400_000) }] };
- }
+ }, (x) => x, (auth) => auth && typeof auth.accessToken === 'string' ? auth.accessToken : ''
);
const refreshed = await refresh('current', { segments: [{ remaining: 5, expiresAt: now + 172_800_000 }] });
assert.deepEqual(queried, ['cached-later', 'fresh-sooner']);
@@ -100,6 +100,8 @@ test('rotation completion request uses real segment detection and keeps the veri
assert.match(daemon, /await refreshCreditRotationAccounts\(uid, refreshed\)/);
assert.match(daemon, /catch \(_\) \{ return json\(res, 200, \{ ok: true, shouldSuggest: false/);
assert.match(inject, /检测到积分到期时间最临近的账号/);
+ assert.match(inject, /rotationConversationId = typeof acActiveConversationId === 'function' \? acActiveConversationId\(\) : ''/);
+ assert.match(inject, /currentConversationId: currentConversationId \|\| ''/);
assert.doesNotMatch(inject, /action === 'remove'[\s\S]{0,500}checkCreditRotationAfterSession/);
assert.match(inject, /Account rotation must wait for an actual reply/);
assert.match(inject, /Use the untransformed fixed position/);
diff --git a/test/linux-release-script.test.js b/test/linux-release-script.test.js
index 0094458..4362c33 100644
--- a/test/linux-release-script.test.js
+++ b/test/linux-release-script.test.js
@@ -15,9 +15,12 @@ test('Linux release builds a versioned, self-contained Debian package without ro
assert.match(source, /CROSS_PACKAGE=1/);
assert.match(source, /tarfile\.open\(control, 'w:xz'\)/);
assert.match(source, /tarfile\.open\(data, 'w:xz'\)/);
- assert.match(source, /node != b'\\x7fELF\\x02'/);
- assert.match(source, /node-v22\.23\.1-linux-x64\.tar\.xz/);
- assert.match(source, /9749e988f437343b7fa832c69ded82a312e41a03116d766797ac14f6f9eee578/);
+ assert.match(source, /expected_machine = \{'amd64': 62, 'arm64': 183\}/);
+ assert.match(source, /actual_machine = int\.from_bytes\(node\[18:20\], 'little'\)/);
+ assert.match(source, /WORKDADDY_BUILD_ARCH/);
+ assert.match(source, /node-v22\.23\.1-linux-\$NODE_ARCH\.tar\.xz/);
+ assert.match(source, /amd64[\s\S]*x64[\s\S]*9749e988f437343b7fa832c69ded82a312e41a03116d766797ac14f6f9eee578/);
+ assert.match(source, /arm64[\s\S]*arm64[\s\S]*NODE_SHA256/);
assert.match(source, /ws-8\.18\.3\.tgz/);
assert.match(source, /424be604c8e7926fc29a1f067bf2dac256af3bcea62fe30395018bbaf8a9be2a/);
assert.match(source, /scripts\/runtime\/node\/node/);
@@ -26,8 +29,9 @@ test('Linux release builds a versioned, self-contained Debian package without ro
assert.match(source, /scripts\/assets\/workdaddy-logo\.svg/);
assert.match(source, /build_package cn workdaddy \/opt\/workdaddy/);
assert.match(source, /build_package ai workdaddy-ai \/opt\/workdaddy-ai/);
- assert.match(source, /WorkDaddy_\$\{VERSION\}_amd64\.deb/);
- assert.match(source, /WorkDaddy-AI_\$\{VERSION\}_amd64\.deb/);
+ assert.match(source, /WorkDaddy_\$\{VERSION\}_\$\{DEB_ARCH\}\.deb/);
+ assert.match(source, /WorkDaddy-AI_\$\{VERSION\}_\$\{DEB_ARCH\}\.deb/);
+ assert.match(source, /Architecture: \$DEB_ARCH/);
assert.match(source, /Exec=\$install_root\/scripts\/launch-gui-linux\.sh \$profile/);
assert.match(source, /workdaddy-\$profile\.png/);
assert.match(source, /Icon=workdaddy-\$profile/);
@@ -58,8 +62,8 @@ test('built Linux packages have matching metadata and isolated payloads', { skip
const debs = process.env.WORKDADDY_LINUX_DEBS.split(path.delimiter).filter(Boolean);
assert.equal(debs.length, 2);
const expected = new Map([
- ['WorkDaddy_', { packageName: 'workdaddy', root: 'opt/workdaddy', desktop: 'workdaddy-cn.desktop', filePattern: /^WorkDaddy_\d+\.\d+\.\d+_amd64\.deb$/ }],
- ['WorkDaddy-AI_', { packageName: 'workdaddy-ai', root: 'opt/workdaddy-ai', desktop: 'workdaddy-ai.desktop', filePattern: /^WorkDaddy-AI_\d+\.\d+\.\d+_amd64\.deb$/ }],
+ ['WorkDaddy_', { packageName: 'workdaddy', root: 'opt/workdaddy', desktop: 'workdaddy-cn.desktop', filePattern: /^WorkDaddy_\d+\.\d+\.\d+_(?:amd64|arm64)\.deb$/ }],
+ ['WorkDaddy-AI_', { packageName: 'workdaddy-ai', root: 'opt/workdaddy-ai', desktop: 'workdaddy-ai.desktop', filePattern: /^WorkDaddy-AI_\d+\.\d+\.\d+_(?:amd64|arm64)\.deb$/ }],
]);
for (const deb of debs) {
const fileName = path.basename(deb);
@@ -88,7 +92,9 @@ test('built Linux packages have matching metadata and isolated payloads', { skip
} finally {
fs.rmSync(extracted, { recursive: true, force: true });
}
- assert.match(path.basename(deb), new RegExp(version.stdout.trim().replace(/\./g, '\\.') + '_amd64\\.deb$'));
+ const architecture = spawnSync('dpkg-deb', ['-f', deb, 'Architecture'], { encoding: 'utf8' }).stdout.trim();
+ assert.ok(['amd64', 'arm64'].includes(architecture));
+ assert.match(path.basename(deb), new RegExp(version.stdout.trim().replace(/\./g, '\\.') + '_' + architecture + '\\.deb$'));
}
});
@@ -102,9 +108,10 @@ test('cross-built Debian archives expose standard member names and control metad
assert.equal(control.status, 0, String(control.stderr));
const metadata = spawnSync('tar', ['-xOJf', '-', './control'], { input: control.stdout, encoding: 'utf8' });
assert.equal(metadata.status, 0, metadata.stderr);
- const version = path.basename(deb).match(/^(?:WorkDaddy|WorkDaddy-AI)_(\d+\.\d+\.\d+)_amd64\.deb$/)?.[1];
- assert.ok(version);
+ const match = path.basename(deb).match(/^(?:WorkDaddy|WorkDaddy-AI)_(\d+\.\d+\.\d+)_(amd64|arm64)\.deb$/);
+ assert.ok(match);
+ const [, version, architecture] = match;
assert.ok(metadata.stdout.split('\n').includes(`Version: ${version}`));
- assert.match(metadata.stdout, /^Architecture: amd64$/m);
+ assert.match(metadata.stdout, new RegExp('^Architecture: ' + architecture + '$', 'm'));
}
});
diff --git a/test/panel-theme-controls.test.js b/test/panel-theme-controls.test.js
index d5e7379..881fb45 100644
--- a/test/panel-theme-controls.test.js
+++ b/test/panel-theme-controls.test.js
@@ -13,6 +13,8 @@ test('theme choices do not activate official data-theme scopes and robot radios
assert.match(pane, /class="wbs-theme-seg wbs-robot-seg"/);
assert.match(pane, /class="wbs-theme-opt wbs-robot-option"/);
assert.match(source, /closest\('#wbs-theme-seg \.wbs-theme-opt'\)/);
+ assert.match(pane, /wbs-avatar-default-option/);
+ assert.match(pane, /value="default"/);
});
test('account order is centered in the panel and always shows names without numbered rows', () => {
const modal = section('function openAccountOrderModal()', 'function setupCreditSummary()');
@@ -47,8 +49,10 @@ test('avatar presets retain legacy custom uploads and are safe before official c
assert.equal(choose(null, 'official', 'brand').src, 'official');
assert.equal(choose('workbuddy', 'official', 'brand').preset, 'workbuddy');
assert.equal(choose('workdaddy', 'official', 'brand').src, 'brand');
+ assert.equal(choose('default', 'official', 'brand', 'default-avatar').src, 'default-avatar');
assert.equal(choose('data:image/png;base64,upload', 'official', 'brand').src, 'data:image/png;base64,upload');
assert.equal(choose(null, null, 'brand').src, null);
assert.equal(choose('javascript:bad', 'official', 'brand').src, 'official');
+ assert.match(source, /if \(!target\) \{\s*restoreAvatarDom\(\);\s*return;/);
assert.doesNotMatch(source, /id="wbs-avatar-reset"/);
});
diff --git a/test/quick-phrase-composer.test.js b/test/quick-phrase-composer.test.js
index 09daa53..4e2ddd2 100644
--- a/test/quick-phrase-composer.test.js
+++ b/test/quick-phrase-composer.test.js
@@ -11,9 +11,35 @@ const start = source.indexOf('async function sendStashToComposer(record) {');
const end = source.indexOf('\n/**', start);
assert.ok(start >= 0 && end > start);
-function harness(hasContent, failSelect = false) {
+const busyStart = source.indexOf('function buildBusyExpr() {');
+const busyEnd = source.indexOf('\n/**', busyStart);
+assert.ok(busyStart >= 0 && busyEnd > busyStart);
+
+function evaluateBusy(elements) {
+ const context = {};
+ vm.runInNewContext(source.slice(busyStart, busyEnd), context);
+ return vm.runInNewContext(context.buildBusyExpr(), {
+ document: { querySelectorAll: () => elements },
+ });
+}
+
+test('AI busy detection ignores WorkDaddy controls but keeps official stop controls', () => {
+ const ownStop = {
+ closest: selector => selector === '.wbs-root' ? {} : null,
+ getBoundingClientRect: () => ({ width: 96, height: 32 }),
+ };
+ const officialStop = {
+ closest: () => null,
+ getBoundingClientRect: () => ({ width: 32, height: 32 }),
+ };
+ assert.equal(evaluateBusy([ownStop]), false);
+ assert.equal(evaluateBusy([officialStop]), true);
+});
+
+function harness(hasContent, failSelect = false, postClickHasContent = false) {
const calls = [];
let evaluations = 0;
+ let submitted = false;
const context = {
cdp: { connected: true },
log() {},
@@ -25,18 +51,24 @@ function harness(hasContent, failSelect = false) {
evaluations++;
const value = evaluations === 1 ? { ok: true }
: evaluations === 2 ? { ok: true, hasContent }
+ : params.expression.includes('composer-after-submit') ? { ok: true, hasContent: postClickHasContent || !submitted }
: { ok: true, x: 100, y: 100 };
return { result: { value } };
}
if (failSelect && params.commands?.includes('selectAll')) throw new Error('selection failed');
return {};
},
- cdpMouseClick: async () => calls.push({ method: 'submit' }),
+ cdpMouseClick: async () => { submitted = true; calls.push({ method: 'submit' }); },
};
vm.runInNewContext(source.slice(start, end), context);
return { calls, send: (text) => context.sendStashToComposer({ content: { text, items: [] } }) };
}
+test('quick phrase rejects a click when the composer still contains text', async () => {
+ const { send } = harness(false, false, true);
+ await assert.rejects(send('replacement'), /输入框仍有内容|未确认发送/);
+});
+
test('quick phrase replaces a draft using a renderer edit command without macOS menu shortcuts', async () => {
const { calls, send } = harness(true);
assert.equal((await send('replacement')).sent, true);
@@ -70,11 +102,14 @@ test('failed selection aborts before deleting, inserting or submitting', async (
assert.equal(calls.some(({ method, params }) => method === 'submit' || method === 'Input.insertText' || params?.key === 'Backspace'), false);
});
-function guardedComposerHarness({ draft = '', attachment = false } = {}) {
+function guardedComposerHarness({ draft = '', attachment = false, textarea = false } = {}) {
const calls = [];
const editor = {
+ tagName: textarea ? 'TEXTAREA' : 'DIV',
+ value: textarea ? draft : undefined,
innerText: 'Ask WorkBuddy anything\u200b' + draft,
focus() {}, scrollIntoView() {},
+ closest: selector => selector.includes('.cr-input-box') ? {} : null,
getBoundingClientRect: () => ({ width: 400, height: 80, bottom: 400 }),
querySelector: () => attachment ? {} : null,
cloneNode() {
@@ -83,7 +118,12 @@ function guardedComposerHarness({ draft = '', attachment = false } = {}) {
return clone;
},
};
- const dom = { document: { querySelector: () => null, querySelectorAll: () => [editor] }, window: { getSelection: () => null } };
+ const dom = { document: { querySelector: () => null, querySelectorAll: selector => {
+ if (selector.includes('[contenteditable') && selector.includes('textarea')) return [editor];
+ if (selector.includes('textarea')) return textarea ? [editor] : [];
+ if (selector.includes('[contenteditable')) return textarea ? [] : [editor];
+ return [editor];
+ } }, window: { getSelection: () => null }, getComputedStyle: () => ({ display: 'block', visibility: 'visible' }) };
const context = { cdp: { connected: true }, log() {}, waitAiIdle: async () => true, setTimeout: fn => fn(),
cdpSend: async (method, params) => {
calls.push(method);
@@ -102,10 +142,20 @@ test('automation sends from an empty Slate editor containing a visible placehold
const h = guardedComposerHarness();
assert.equal((await h.send()).sent, true);
assert.ok(h.calls.includes('Input.insertText'));
- assert.equal(h.calls.at(-1), 'submit');
+ const submit = h.calls.indexOf('submit');
+ assert.ok(submit >= 0);
+ assert.equal(h.calls.filter(method => method === 'submit').length, 1);
+ assert.ok(h.calls.slice(submit + 1).includes('Runtime.evaluate'), 'must confirm the composer cleared after submitting');
assert.ok(!h.calls.includes('Input.dispatchKeyEvent'), 'placeholder must not trigger draft deletion');
});
+test('automation sends from the modern textarea composer after model selection', async () => {
+ const h = guardedComposerHarness({ textarea: true });
+ assert.equal((await h.send()).sent, true);
+ assert.ok(h.calls.includes('Input.insertText'));
+ assert.equal(h.calls.filter(method => method === 'submit').length, 1);
+});
+
test('automation still rejects real drafts and attachment-only editors before input', async () => {
for (const options of [{ draft: 'my unsent draft' }, { attachment: true }]) {
const h = guardedComposerHarness(options);
@@ -117,6 +167,7 @@ test('automation still rejects real drafts and attachment-only editors before in
function delayedButtonHarness({ enableAfter = 3, cancelAfter = Infinity, disabledBy = 'property', probeCost = 0, scoped = false, missing = false, stop = false } = {}) {
const calls = [];
let probes = 0, evaluations = 0, guardChecks = 0, clock = 0;
+ let submitted = false;
const waits = [], probeTimes = [];
const button = {
tagName: 'BUTTON',
@@ -136,6 +187,9 @@ function delayedButtonHarness({ enableAfter = 3, cancelAfter = Infinity, disable
if (method !== 'Runtime.evaluate') return {};
evaluations++;
if (evaluations <= 2) return { result: { value: { ok: true, hasContent: false } } };
+ if (params.expression.includes('composer-after-submit')) {
+ return { result: { value: { ok: true, hasContent: !submitted } } };
+ }
probes++; probeTimes.push(clock); clock += probeCost;
const foreign = { ...button, disabled: false, hasAttribute: () => false, getAttribute: () => null };
const dom = {
@@ -143,7 +197,7 @@ function delayedButtonHarness({ enableAfter = 3, cancelAfter = Infinity, disable
getComputedStyle: () => ({ display: 'block', visibility: 'visible', borderRadius: '50%' }),
};
return { result: { value: vm.runInNewContext(params.expression, dom) } };
- }, cdpMouseClick: async () => calls.push('submit'),
+ }, cdpMouseClick: async () => { submitted = true; calls.push('submit'); },
};
vm.runInNewContext(source.slice(start, end), context);
return { calls, waits, probeTimes, elapsed: () => clock, probes: () => probes, send: () => context.sendStashToComposer({ requireEmpty: true, content: { text: '1+1=', items: [] }, guard: async () => { if (++guardChecks >= cancelAfter) throw Error('account changed'); } }) };
diff --git a/test/selection-quote.test.js b/test/selection-quote.test.js
index 79ad380..6447725 100644
--- a/test/selection-quote.test.js
+++ b/test/selection-quote.test.js
@@ -5,41 +5,16 @@ const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
-test('selection quote is a local session setting enabled by default and ordered after message navigation', () => {
+test('the obsolete selection quote enhancement switch is removed', () => {
const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
- const navigationSwitch = inject.indexOf('id="wbs-sess-message-nav"');
- const quoteSwitch = inject.indexOf('id="wbs-sess-selection-quote"');
- const phraseSwitch = inject.indexOf('id="wbs-sess-phrase"');
-
- assert.ok(navigationSwitch >= 0 && quoteSwitch > navigationSwitch && phraseSwitch > quoteSwitch);
- assert.match(inject, /workdaddy\.session\.selectionQuoteEnabled/);
- assert.match(inject, /<span class="wbs-nd-title">引用消息文本<\/span>/);
- assert.doesNotMatch(inject, /<span class="wbs-nd-title">选中文字引用<\/span>/);
- assert.match(inject, /localStorage\.getItem\(SELECTION_QUOTE_ENABLED_KEY\) !== '0'/);
- assert.match(inject, /localStorage\.setItem\(SELECTION_QUOTE_ENABLED_KEY, enabled \? '1' : '0'\)/);
+ assert.doesNotMatch(inject, /id="wbs-sess-selection-quote"/);
+ assert.doesNotMatch(inject, /<span class="wbs-nd-title">引用消息文本<\/span>/);
+ assert.doesNotMatch(inject, /SELECTION_QUOTE_ENABLED_KEY/);
});
-test('selection quote uses the official content-block insertion request and avoids direct Slate DOM edits', () => {
+test('selection quote is delegated to WorkBuddy and WorkDaddy no longer injects a custom button', () => {
const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
- assert.match(inject, /requestInsertContentBlocks/);
- assert.match(inject, /contentBlocks: \[selectionQuoteBlock\(pending\.text\)\]/);
- assert.match(inject, /type: 'resource_link'/);
- assert.match(inject, /name: '引用文本'/);
- assert.match(inject, /displayText: '引用文本'/);
- assert.match(inject, /selectionQuote: true/);
- assert.match(inject, /selection:\/\/document-selection/);
- assert.match(inject, /selectionQuoteButton\.textContent = '引用文本'/);
- assert.doesNotMatch(inject, /selectionQuoteButton\.title/);
- assert.match(inject, /sq-tooltip-wrapper \.sq-popover__locate-btn[^']*display:none!important/);
- assert.match(inject, /sq-tooltip-wrapper \.sq-popover[^']*max-height:min\(48vh,240px\)/);
- assert.doesNotMatch(inject, /function syncSelectionQuoteIcons\(\)/);
- assert.doesNotMatch(inject, /container\.innerHTML = SELECTION_QUOTE_MESSAGE_ICON/);
- assert.match(inject, /InputContextTag/);
- assert.match(inject, /slate-selection-quote-sceneTag\._hasCloseIcon:hover[^']*visibility:hidden!important/);
- assert.match(inject, /wbs-selection-quote-btn\{position:fixed;z-index:1000;/);
- assert.doesNotMatch(inject, /wbs-selection-quote-btn\{position:fixed;z-index:2147483647;/);
- assert.match(inject, /background:color-mix\(in srgb,var\(--wb-bg-hover/);
- assert.doesNotMatch(inject, /wbs-selection-quote-btn:hover[^']*border-color:var\(--wb-accent-blue/);
- assert.match(inject, /backdrop-filter:blur\(12px\) saturate\(1\.2\)/);
- assert.match(inject, /html\.cb-dark \.wbs-selection-quote-btn/);
+ assert.doesNotMatch(inject, /function setupSelectionQuote\(\)/);
+ assert.doesNotMatch(inject, /selectionQuoteButton/);
+ assert.doesNotMatch(inject, /selection:\/\/document-selection/);
});
diff --git a/test/session-copy-rate.test.js b/test/session-copy-rate.test.js
index e54f970..9ccea01 100644
--- a/test/session-copy-rate.test.js
+++ b/test/session-copy-rate.test.js
@@ -5,7 +5,7 @@ const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const vm = require('node:vm');
-const { readSnapshot, applySnapshot } = require('../scripts/session-sync');
+const { readSnapshot, readSnapshotAsync, applySnapshot, applySnapshotAsync } = require('../scripts/session-sync');
test('copy byte count includes changed published payloads, excludes unchanged files, backups and deletions', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-copy-rate-'));
@@ -14,13 +14,32 @@ test('copy byte count includes changed published payloads, excludes unchanged fi
for (const id of ['a','b']) write(id, 'unchanged.bin', Buffer.alloc(1024 * 1024));
write('a','changed.bin','new payload'); write('b','changed.bin','old'); write('b','removed.bin','removed');
const snapshot = id => readSnapshot(root, id, ['a','b']);
- const options = { backupRoot: path.join(root, 'backups') };
+ const progress = [];
+ const options = { backupRoot: path.join(root, 'backups'), onProgress: event => progress.push(event) };
const result = await applySnapshot(snapshot('a'), snapshot('b'), options);
assert.equal(result.copiedBytes, Buffer.byteLength('new payload'));
+ assert.deepEqual(progress.map(event => event.bytes), [Buffer.byteLength('new payload')]);
assert.equal(result.totalBytes, 1024 * 1024 + result.copiedBytes);
assert.equal((await applySnapshot(snapshot('a'), snapshot('b'), options)).copiedBytes, 0);
});
+test('async copy byte count reports published payloads before returning', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-copy-rate-async-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const write = (id, name, bytes) => { const file = path.join(root, 'tasks', id, name); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, bytes); };
+ write('a', 'changed.bin', Buffer.alloc(1024 * 1024, 'a'));
+ write('b', 'changed.bin', Buffer.from('old'));
+ const source = await readSnapshotAsync(root, 'a', ['a', 'b']);
+ const target = await readSnapshotAsync(root, 'b', ['a', 'b']);
+ const progress = [];
+ const result = await applySnapshotAsync(source, target, {
+ backupRoot: path.join(root, 'backups'),
+ onProgress: event => progress.push(event.bytes),
+ });
+ assert.deepEqual(progress, [1024 * 1024]);
+ assert.equal(result.copiedBytes, 1024 * 1024);
+});
+
test('public copy rate excludes queue time, updates during work and freezes after completion', () => {
const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
let now = 4000;
@@ -35,15 +54,58 @@ test('public copy rate excludes queue time, updates during work and freezes afte
assert.equal(ctx.publicAutoCopyJob({ status: 'queued', copiedBytes: 0 }).averageBytesPerSecond, null);
});
-test('copy notice formats rate units and tolerates older daemon responses', () => {
+test('copy notice omits transfer byte details', () => {
const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
- assert.match(source, /summary\.hidden = active/);
+ assert.match(source, /node\.hidden = !groups\.copied\.length && !groups\.failed\.length/);
+ assert.match(source, /actions\.hidden = active \|\| !\(noticeGroups && \(noticeGroups\.copied\.length \|\| noticeGroups\.failed\.length\)\)/);
+ assert.match(source, /wbs-session-copy-summary-label\{[^}]*margin:3px 0 2px[^}]*border-radius:999px/);
+ assert.match(source, /wbs-session-copy-notice\.is-done \.wbs-session-copy-fill\{background:var\(--wb-button-primary-bg,#1f1f1f\)\}/);
assert.doesNotMatch(source, /active \? '已处理 ' \+ processed \+ ' 个候选会话'/);
const ctx = {};
- vm.runInNewContext(source.slice(source.indexOf(' function sessionCopySizeText('), source.indexOf(' function showSessionCopyDetails(')), ctx);
+ vm.runInNewContext(source.slice(source.indexOf(' function sessionCopyItemFailed('), source.indexOf(' function showSessionCopyDetails(')), ctx);
assert.equal(typeof ctx.sessionCopyTransferText, 'function');
assert.equal(ctx.sessionCopyTransferText({}), '');
- assert.equal(ctx.sessionCopyTransferText({ processedBytes: 1024 ** 2 * 3, totalBytes: 1024 ** 2 * 8, averageBytesPerSecond: 1024 ** 2 * 1.5 }), '已同步 3.0 MB / 8.0 MB');
- assert.equal(ctx.sessionCopyTransferText({ processedBytes: 0, totalBytes: 0, averageBytesPerSecond: 0 }), '已同步 0 B / 0 B');
- assert.equal(ctx.sessionCopyTransferText({ processedBytes: 0, averageBytesPerSecond: null }), '已同步 0 B');
+ assert.equal(ctx.sessionCopyTransferText({ processedBytes: 1024 ** 2 * 3, copiedBytes: 1024 ** 2 * 1.5, totalBytes: 1024 ** 2 * 8, averageBytesPerSecond: 1024 ** 2 * 1.5 }), '');
+ assert.equal(ctx.sessionCopyTransferText({ processedBytes: 0, copiedBytes: 0, totalBytes: 0, averageBytesPerSecond: 0 }), '');
+ assert.equal(ctx.sessionCopyTransferText({ processedBytes: 0, averageBytesPerSecond: null }), '');
+});
+
+test('copy notice groups copied and failed titles with counts and skips skipped rows', () => {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+ const fakeDocument = {
+ createElement: () => ({
+ className: '', textContent: '', title: '',
+ appendChild(child) { this.children = this.children || []; this.children.push(child); },
+ }),
+ };
+ const ctx = { document: fakeDocument };
+ vm.runInNewContext(source.slice(source.indexOf(' function sessionCopyItemFailed('), source.indexOf(' function showSessionCopyDetails(')), ctx);
+ const summary = { textContent: 'old summary', hidden: false, children: [], appendChild(child) { this.children.push(child); } };
+ ctx.renderSessionCopyNoticeSummary(summary, { details: [
+ { label: '跳过会话', status: 'skipped' },
+ { label: '会话一', status: 'copied' },
+ { label: '失败会话', status: 'failed' },
+ { label: '会话三', status: 'skipped' },
+ { label: '会话四', status: 'copied' },
+ { label: '会话五', status: 'partial' },
+ ] });
+ assert.equal(summary.children.length, 2);
+ assert.equal(summary.children[0].className, 'wbs-session-copy-summary-group is-copied');
+ assert.equal(summary.children[0].children[0].textContent, '同步成功 2');
+ assert.deepEqual(summary.children[0].children.slice(1).map(child => child.textContent), ['会话一', '会话四']);
+ assert.equal(summary.children[1].className, 'wbs-session-copy-summary-group is-failed');
+ assert.equal(summary.children[1].children[0].textContent, '同步失败 2');
+ assert.deepEqual(summary.children[1].children.slice(1).map(child => child.textContent), ['失败会话', '会话五']);
+ assert.equal(summary.hidden, false);
+});
+
+test('copy notice hides the summary when every session was skipped', () => {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+ const fakeDocument = { createElement: () => ({ className: '', textContent: '', title: '' }) };
+ const ctx = { document: fakeDocument };
+ vm.runInNewContext(source.slice(source.indexOf(' function sessionCopyItemFailed('), source.indexOf(' function showSessionCopyDetails(')), ctx);
+ const summary = { textContent: 'old summary', hidden: false, children: [], appendChild(child) { this.children.push(child); } };
+ ctx.renderSessionCopyNoticeSummary(summary, { details: [{ label: '跳过会话', status: 'skipped' }] });
+ assert.equal(summary.children.length, 0);
+ assert.equal(summary.hidden, true);
});
diff --git a/test/session-db.test.js b/test/session-db.test.js
index ee6a6c3..9d08548 100644
--- a/test/session-db.test.js
+++ b/test/session-db.test.js
@@ -242,6 +242,11 @@ test('session ID batches validate raw input, cap work, and deduplicate in order'
);
});
+test('session ID batches can opt out of the cap for deletion-style operations', () => {
+ const ids = Array.from({ length: 101 }, (_, index) => `session-${index}`);
+ assert.deepEqual(normalizeSessionIdBatch(ids, { maxBatch: null }), ids);
+});
+
test('daemon session SQL uses bound parameters without delimiter serialization', () => {
const daemon = fs.readFileSync(path.join(repoRoot, 'scripts', 'daemon.js'), 'utf8');
const verifyWin = fs.readFileSync(path.join(repoRoot, 'scripts', 'verify-win.cmd'), 'utf8');
@@ -250,7 +255,8 @@ test('daemon session SQL uses bound parameters without delimiter serialization',
assert.doesNotMatch(daemon, /function sqlQuote\(/);
assert.doesNotMatch(daemon, /id IN \(['"]?\s*\+\s*esc/);
assert.match(daemon, /createSessionDb/);
- assert.equal((daemon.match(/normalizeSessionIdBatch\(body\s*&&\s*body\.ids\)/g) || []).length, 4);
+ assert.equal((daemon.match(/normalizeSessionIdBatch\(body\s*&&\s*body\.ids\)/g) || []).length, 3);
+ assert.match(daemon, /normalizeSessionIdBatch\(body\s*&&\s*body\.ids,\s*\{\s*maxBatch:\s*null\s*\}\)/);
assert.ok((daemon.match(/catch \(e\) \{ return json\(res, 400, \{ ok: false, error: e\.message \}\); \}/g) || []).length >= 4);
assert.doesNotMatch(daemon, /body\.ids\.filter\(/);
assert.match(daemon, /sqliteQuery\([^,]+,\s*\[[^\]]/s);
diff --git a/test/session-delete-confinement.test.js b/test/session-delete-confinement.test.js
index 9634848..4975ec3 100644
--- a/test/session-delete-confinement.test.js
+++ b/test/session-delete-confinement.test.js
@@ -255,6 +255,41 @@ test('delete route validates before SQL and deletes the matched set only', () =>
'filesystem and rule cleanup must succeed before the retry anchor is removed from the database');
});
+test('delete route accepts more than 100 session IDs in one request', async (t) => {
+ const { createSessionDb, normalizeSessionIdBatch } = require('../scripts/session-db.js');
+ const root = tempDir(t);
+ const db = createSessionDb({ dbPath: path.join(root, 'sessions.db') });
+ await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT)');
+ const ids = Array.from({ length: 101 }, (_, index) => `00000000-0000-0000-0000-${String(index).padStart(12, '0')}`);
+ for (const id of ids) await db.run('INSERT INTO sessions (id, user_id) VALUES (?, ?)', [id, 'owner']);
+
+ const source = fs.readFileSync(daemonPath, 'utf8');
+ const start = source.indexOf(" if (req.method === 'POST' && p === '/api/sessions/delete')");
+ const end = source.indexOf(' // 恢复会话:', start);
+ const ctx = vm.createContext({
+ ...loadSessionDeleteHelpers(),
+ normalizeSessionIdBatch,
+ collectLineageMembersForDelete: (_dataDir, requested) => requested.map((id) => ({ id })),
+ removeAutoCopySession: () => false,
+ DATA_DIR: root,
+ PROFILE: { dataRoot: root },
+ req: { method: 'POST' },
+ res: {},
+ p: '/api/sessions/delete',
+ readBody: async () => ({ ids }),
+ sqliteQuery: (sql, params) => db.all(sql, Array.from(params)),
+ sqliteRun: (sql, params) => db.run(sql, Array.from(params)),
+ sqlPlaceholders: (values) => values.map(() => '?').join(','),
+ json: (_, status, body) => ({ status, body }),
+ log() {},
+ });
+
+ const result = await vm.runInContext('(async function () {\n' + source.slice(start, end) + '\n})()', ctx);
+ assert.equal(result.status, 200);
+ assert.equal(result.body.deleted, ids.length);
+ assert.deepEqual(await db.all('SELECT id FROM sessions'), []);
+});
+
test('delete route removes recorded copies across accounts from both DB and files', async (t) => {
const lib = require('../scripts/lib.js');
const { createSessionDb, normalizeSessionIdBatch } = require('../scripts/session-db.js');
diff --git a/test/session-monitor.test.js b/test/session-monitor.test.js
index e7cde2c..9625951 100644
--- a/test/session-monitor.test.js
+++ b/test/session-monitor.test.js
@@ -8,6 +8,62 @@ const fs = require('node:fs');
const path = require('node:path');
const injectSource = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+const { createDirtyIndex } = require('../scripts/session-dirty.js');
+
+test('session dirty index uses the renderer baseline and preserves concurrent changes', () => {
+ const index = createDirtyIndex();
+ assert.equal(index.shouldSync('account-a', 'session-a'), true, 'uninitialized accounts use the safe fallback');
+ assert.equal(index.markBaseline('account-a'), true);
+ assert.equal(index.shouldSync('account-a', 'session-a'), false);
+ const marker = index.mark('account-a', 'session-a', 'sessionUpdated', 100);
+ assert.deepEqual(marker, { at: 100, event: 'sessionUpdated' });
+ assert.equal(index.shouldSync('account-a', 'session-a'), true);
+ assert.equal(index.clear('account-a', 'session-a', 99), false, 'a newer event must remain dirty');
+ assert.equal(index.clear('account-a', 'session-a', 100), true);
+ assert.equal(index.shouldSync('account-a', 'session-a'), false);
+});
+
+test('renderer dirty tracker ignores the initial snapshot and unchanged lifecycle events', async () => {
+ const sent = [];
+ const tracker = inject.createSessionDirtyTracker((payload) => sent.push(payload), { delay: 0 });
+ tracker.baseline([{ id: 'session-a', status: 'completed', title: 'A' }]);
+ assert.deepEqual(sent, [{ ready: true }]);
+ assert.equal(tracker.observe({ id: 'session-a', status: 'completed', title: 'A' }), false);
+ assert.equal(tracker.observe({ id: 'session-a', status: 'running', title: 'A', updatedAt: 11, event: 'sessionUpdated' }), true);
+ tracker.flush();
+ assert.deepEqual(sent[1], [{ id: 'session-a', event: 'sessionUpdated' }]);
+ tracker.destroy();
+});
+
+test('renderer dirty tracker ignores account-switch lifecycle churn', () => {
+ const sent = [];
+ const tracker = inject.createSessionDirtyTracker((payload) => sent.push(payload), { delay: 0 });
+ tracker.baseline([{
+ id: 'session-a', title: 'A', status: 'completed', state: 'idle',
+ active: false, terminal: true, updatedAt: 10, lastActivityAt: 10,
+ }]);
+ assert.equal(tracker.observe({
+ id: 'session-a', title: 'A', status: 'running', state: 'hydrating',
+ active: true, terminal: false, updatedAt: 10, lastActivityAt: 10,
+ event: 'sessionUpdated',
+ }), false);
+ tracker.flush();
+ assert.deepEqual(sent, [{ ready: true }]);
+ tracker.destroy();
+});
+
+test('renderer dirty tracker ignores activation-only last-activity changes', () => {
+ const sent = [];
+ const tracker = inject.createSessionDirtyTracker((payload) => sent.push(payload), { delay: 0 });
+ tracker.baseline([{ id: 'session-a', title: 'A', updatedAt: 10, lastActivityAt: 10 }]);
+ assert.equal(tracker.observe({
+ id: 'session-a', title: 'A', updatedAt: 10, lastActivityAt: 11,
+ status: 'completed', event: 'sessionUpdated',
+ }), false);
+ tracker.flush();
+ assert.deepEqual(sent, [{ ready: true }]);
+ tracker.destroy();
+});
test('approval gate accepts attached background approval cards without visibility checks', () => {
const classify = inject.classifyNoDisturbApprovalCandidate;
@@ -69,6 +125,75 @@ test('session monitor progress gate excludes completed and idle snapshots', () =
assert.equal(inProgress({ state: 'done', busy: false }), false);
});
+test('session monitor interrupted gate accepts exactly what the judge would continue', () => {
+ const interrupted = inject.isSessionMonitorInterrupted;
+ const decision = inject.controllerAutoContinueDecision;
+ // 空闲 + 判定层愿意续跑 = 必须绑定。旧版绑定闸门只按 in-progress 过滤,
+ // 这些会话在绑定阶段就被丢掉,判定层一次都走不到。
+ const continuable = [
+ { assistantId: 'req-a-assistant', error: true }, // 错误 UI
+ { assistantId: 'req-a-assistant', networkFailure: true }, // 网络类错误
+ { assistantId: 'req-a-assistant', complete: false, terminal: false }, // 结构化中断(无错误 UI 也常见)
+ { assistantId: 'req-a-assistant', terminalKnown: true, terminal: false, complete: true }, // 明确未终局
+ ];
+ continuable.forEach((snapshot) => {
+ assert.equal(decision(snapshot).trigger, true, 'judge should continue ' + JSON.stringify(snapshot));
+ assert.equal(interrupted(snapshot), true, 'gate should bind ' + JSON.stringify(snapshot));
+ });
+ // 仍在运行 / 等决策 / 恢复中:交给 in-progress 分支,不重复绑定
+ assert.equal(interrupted({ assistantId: 'a', error: true, busy: true }), false);
+ assert.equal(interrupted({ assistantId: 'a', error: true, blocked: true }), false);
+ assert.equal(interrupted({ assistantId: 'a', error: true, hydrating: true }), false);
+ // 判定层不续跑的空闲会话:闸门同样不绑定,避免对正常历史回复多发一次续跑
+ const finished = [
+ { assistantId: 'a', manualStop: true, error: true }, // 用户主动取消
+ { assistantId: 'a', complete: true, terminal: true }, // 结构化完成
+ { assistantId: 'a', terminalKnown: true, terminal: true, complete: true },
+ { assistantId: 'a', complete: true }, // 旧版无 terminal 字段
+ { assistantId: 'a', completionMarker: true, complete: false, terminal: false },
+ { assistantId: '', error: true }, // 没有助手回复
+ null,
+ ];
+ finished.forEach((snapshot) => {
+ assert.equal(decision(snapshot).trigger, false, 'judge should not continue ' + JSON.stringify(snapshot));
+ assert.equal(interrupted(snapshot), false, 'gate should not bind ' + JSON.stringify(snapshot));
+ });
+});
+
+test('interrupted sessions enter auto-continue instead of waiting for a new reply', () => {
+ // 判定层对同一份快照确实会触发续跑(error-ui):缺口只在「能否进入判定」
+ assert.deepEqual(
+ inject.classifyAutoContinueControllerSnapshot({ assistantId: 'req-a-assistant', error: true }),
+ { trigger: true, reason: 'error-ui' },
+ );
+ // 两条绑定路径都必须接纳已中断会话,而不是无限等待不会到来的新回复
+ assert.match(
+ injectSource,
+ /if \(!existing && !isSessionMonitorInProgress\(initialSnapshot\) && !isSessionMonitorInterrupted\(initialSnapshot\)\) return null;/,
+ );
+ assert.match(injectSource, /session\.awaitingNewReply = false;[\s\S]{0,80}session\.baselineAssistantKey = '';/);
+ assert.match(
+ injectSource,
+ /c\.awaitingNewReply = preserve[\s\S]{0,100}!!carry\.awaitingNewReply && !isSessionMonitorInterrupted\(snap\)[\s\S]{0,60}: !isSessionMonitorInterrupted\(snap\);/,
+ );
+ assert.match(injectSource, /acLog\('baseline-established', \{ via: 'controller', awaitingNewReply: c\.awaitingNewReply \}\);/);
+ // 控制器快照必须自带完成标记,判定与绑定闸门共用同一份证据
+ assert.match(injectSource, /completionMarker: acHasMarker\(text\),/);
+ // 判定路径与绑定闸门必须走同一个映射,否则两条规则会再次错位
+ assert.match(injectSource, /var decision = controllerAutoContinueDecision\(snap\);/);
+ assert.match(injectSource, /var decision = controllerAutoContinueDecision\(snapshot\);/);
+ assert.equal(
+ (injectSource.match(/classifyAutoContinueControllerSnapshot\(\{/g) || []).length,
+ 1,
+ '控制器/多会话判定不得各自内联一份映射',
+ );
+ assert.match(
+ injectSource,
+ /function controllerAutoContinueDecision\(snapshot\) \{[\s\S]{0,400}return classifyAutoContinueControllerSnapshot\(\{/,
+ );
+ assert.match(injectSource, /return controllerAutoContinueDecision\(s\)\.trigger === true;/);
+});
+
test('session resource normalizer treats background terminal updates as final', () => {
const normalize = inject.normalizeSessionMonitorResourceRecord;
assert.deepEqual(normalize({
@@ -81,6 +206,12 @@ test('session resource normalizer treats background terminal updates as final',
title: '任务 B',
status: 'completed',
pendingInputKind: '',
+ protocolStatus: 'completed',
+ state: '',
+ activePromptStartedAt: 0,
+ queueRevision: null,
+ updatedAt: 0,
+ lastActivityAt: 0,
active: false,
terminal: true,
event: 'sessionUpdated',
@@ -95,6 +226,9 @@ test('session resource normalizer treats background terminal updates as final',
status: 'pending',
messageQueueRuntime: { pendingItemCount: 1, paused: false },
}, 'sessionUpdated').active, true);
+ const revision = normalize({ id: 'task-b', status: 'running', updated_at: 10, last_activity_at: 9,
+ messageQueueRuntime: { inflightItemId: 'q1', pendingItemCount: 2, paused: false } });
+ assert.deepEqual([revision.updatedAt, revision.lastActivityAt, revision.queueRevision], [10, 9, ['q1', 2, 0, false]]);
});
test('session lifecycle adds unknown background work and removes terminal sessions', () => {
@@ -112,6 +246,12 @@ test('multi-session monitor subscribes while idle and detaches switched controll
assert.match(injectSource, /function acMultiFinishSession\(session\)[\s\S]*delete acMulti\.sessions\[session\.id\];/);
});
+test('sync idle probe can scope busy checks to the sessions being copied', () => {
+ assert.match(injectSource, /function isAnySessionBusyForIds\(ids\)/);
+ assert.match(injectSource, /window\.__wbsSessionsBusy = sessionBusyIdsProbe/);
+ assert.match(injectSource, /discoverSleepSessionBusy\(wanted\)/);
+});
+
test('session resource subscription delivers non-active completion without controller changes', () => {
const handlers = new Map();
const resource = {
diff --git a/test/session-size-filter.test.js b/test/session-size-filter.test.js
index 68d5071..1fe0de3 100644
--- a/test/session-size-filter.test.js
+++ b/test/session-size-filter.test.js
@@ -12,12 +12,13 @@ function harness() {
sessionsState: { list: [{ id: 'small', totalBytes: 10 * 1024 ** 2, title: 'small' }, { id: 'large', totalBytes: 100 * 1024 ** 2 + 1, title: '<unsafe>', is_playground: 1 }, { id: 'unknown', totalBytes: null }], selected: {}, wsExpanded: {}, totalBytes: 2 * 1024 ** 3, minBytes: 10 * 1024 ** 2 },
sessionsPane: { querySelector: control, querySelectorAll: () => [] },
esc: value => String(value).replace(/</g, '&lt;'), escAttr: String,
- updateAutoCopyAllButton() {}, bindSessEvents() {}, isTaskSessionRecordUI: s => !!s.is_playground,
- fmtHumanTime: () => 'now', shortWs: String, SESS_WS_INIT: 5, SESS_WS_STEP: 5,
+ updateAutoCopyAllButton() {}, isTaskSessionRecordUI: s => !!s.is_playground,
+ fmtHumanTime: () => 'now', shortWs: String, SESS_WS_INIT: 5,
});
vm.runInContext([
section(' function filteredSessions()', ' // 按空间分组渲染'),
section(' function renderSessions()', ' function updateAutoCopyAllButton()'),
+ section(' function bindSessEvents(', ' function updateSessCount()'),
section(' function updateSessCount()', ' // 人性化时间'),
section(' function wireSessionsPane()', ' function selectedSessIds()'),
section(' function selectedSessIds()', ' function showSessModal('),
@@ -51,3 +52,67 @@ test('session summary formats large counts and emphasizes numeric values', () =>
assert.match(control('#wbs-sess-count').innerHTML, /共 <strong>1,111<\/strong> 个会话/);
assert.match(control('#wbs-sess-count').innerHTML, /总大小 <strong>2\.0 GB<\/strong>/);
});
+
+test('expanded session groups can collapse back to the default row count', () => {
+ const { ctx, control } = harness();
+ ctx.SESS_WS_INIT = 2;
+ ctx.sessionsState.minBytes = 0;
+ ctx.sessionsState.list = Array.from({ length: 5 }, (_, index) => ({ id: String(index), cwd: '/repo', title: 'session ' + index, totalBytes: 1 }));
+ ctx.renderSessions();
+ const list = control('#wbs-sess-list');
+ assert.match(list.innerHTML, />展开<\/button>/);
+ assert.doesNotMatch(list.innerHTML, /展开 .*条/);
+ assert.equal((list.innerHTML.match(/class="wbs-sess-row"/g) || []).length, 2);
+ const button = action => ({ getAttribute: name => name === 'data-ws' ? '::/repo' : name === 'data-action' ? action : null });
+ list.onclick({ target: { closest: selector => selector === '.wbs-sess-more' ? button('expand') : null } });
+ assert.equal((list.innerHTML.match(/class="wbs-sess-row"/g) || []).length, 5);
+ assert.match(list.innerHTML, /收起/);
+ assert.doesNotMatch(list.innerHTML, />展开<\/button>/);
+ list.onclick({ target: { closest: selector => selector === '.wbs-sess-more' ? button('collapse') : null } });
+ assert.match(list.innerHTML, />展开<\/button>/);
+ assert.doesNotMatch(list.innerHTML, /收起/);
+ assert.equal((list.innerHTML.match(/class="wbs-sess-row"/g) || []).length, 2);
+});
+
+test('task session group expands all rows before showing collapse', () => {
+ const { ctx, control } = harness();
+ ctx.SESS_WS_INIT = 2;
+ ctx.sessionsState.minBytes = 0;
+ ctx.sessionsState.list = Array.from({ length: 4 }, (_, index) => ({ id: String(index), title: 'task ' + index, totalBytes: 1, is_playground: 1 }));
+ ctx.renderSessions();
+ const list = control('#wbs-sess-list');
+ const button = action => ({ getAttribute: name => name === 'data-ws' ? '__TASKS__' : name === 'data-action' ? action : null });
+ assert.match(list.innerHTML, />展开<\/button>/);
+ assert.doesNotMatch(list.innerHTML, /收起/);
+ list.onclick({ target: { closest: selector => selector === '.wbs-sess-more' ? button('expand') : null } });
+ assert.equal((list.innerHTML.match(/class="wbs-sess-row"/g) || []).length, 4);
+ assert.match(list.innerHTML, /收起/);
+ assert.doesNotMatch(list.innerHTML, />展开<\/button>/);
+});
+
+test('session account selector follows the fixed account order', () => {
+ const start = source.indexOf(' function sortSessionAccounts(');
+ const end = source.indexOf(' function loadSessionAccounts()', start);
+ assert.ok(start >= 0 && end > start, 'missing session account ordering helper');
+ const ctx = vm.createContext({});
+ vm.runInContext(source.slice(start, end), ctx);
+ const ordered = ctx.sortSessionAccounts([
+ { uid: 'late', sort: 2 }, { uid: 'first', sort: 1 }, { uid: 'new', sort: 0 },
+ ], { mode: 'fixed' });
+ assert.deepEqual(Array.from(ordered, account => account.uid), ['first', 'late', 'new']);
+});
+
+test('session account selector follows the account page credit-expiry order', () => {
+ const start = source.indexOf(' function sortSessionAccounts(');
+ const end = source.indexOf(' function loadSessionAccounts()', start);
+ assert.ok(start >= 0 && end > start, 'missing session account ordering helper');
+ const ctx = vm.createContext({ isFinite });
+ vm.runInContext(source.slice(start, end), ctx);
+ const ordered = ctx.sortSessionAccounts([
+ { uid: 'later', creditSegments: [{ remaining: 2, expiresAt: 300 }] },
+ { uid: 'first', creditSegments: [{ remaining: 1, expiresAt: 100 }] },
+ { uid: 'spent', creditSegments: [{ remaining: 0, expiresAt: 50 }] },
+ { uid: 'middle', creditSegments: [{ remaining: 3, expiresAt: 200 }] },
+ ], { mode: 'expiry' });
+ assert.deepEqual(Array.from(ordered, account => account.uid), ['first', 'middle', 'later', 'spent']);
+});
diff --git a/test/session-sizes.test.js b/test/session-sizes.test.js
index b42b36e..33854a5 100644
--- a/test/session-sizes.test.js
+++ b/test/session-sizes.test.js
@@ -23,14 +23,26 @@ test('session size counts only its complete sync payload, using metadata even fo
assert.equal(result.get('../escape'), null);
});
-test('symlinked paths are unknown, never followed or reported as complete sizes', async t => {
+test('symlinked paths are skipped, never followed or counted as payload sizes', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-sizes-links-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.mkdirSync(path.join(root, 'projects/p'), { recursive: true });
fs.writeFileSync(path.join(root, 'projects/p/good.jsonl'), 'ok');
fs.symlinkSync('good.jsonl', path.join(root, 'projects/p/link.jsonl'));
const sizes = await readSessionSizes(root, ['good', 'link']);
- assert.equal(sizes.get('good'), 2); assert.equal(sizes.get('link'), null);
+ assert.equal(sizes.get('good'), 2); assert.equal(sizes.get('link'), 0);
fs.symlinkSync(path.join(root, 'projects'), path.join(root, 'tasks'), 'dir');
- assert.equal((await readSessionSizes(root, ['good'])).get('good'), null);
+ assert.equal((await readSessionSizes(root, ['good'])).get('good'), 2);
+});
+
+test('session size excludes local modify backups from workspace sessions', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-sizes-modify-backup-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const sessionRoot = path.join(root, 'workspace', 'sessions', 'a');
+ fs.mkdirSync(path.join(sessionRoot, 'modify_backup'), { recursive: true });
+ fs.mkdirSync(path.join(sessionRoot, '.modify_backup_meta'), { recursive: true });
+ fs.writeFileSync(path.join(sessionRoot, 'keep.bin'), 'keep');
+ fs.writeFileSync(path.join(sessionRoot, 'modify_backup', '12.m.a1b2c3.original'), 'ignored backup');
+ fs.writeFileSync(path.join(sessionRoot, '.modify_backup_meta', 'meta.json'), 'ignored metadata');
+ assert.equal((await readSessionSizes(root, ['a'])).get('a'), 4);
});
diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.js
index 5e93865..f2b388c 100644
--- a/test/session-sync-daemon.test.js
+++ b/test/session-sync-daemon.test.js
@@ -8,6 +8,7 @@ const vm = require('node:vm');
const crypto = require('node:crypto');
const lib = require('../scripts/lib.js');
const sessionSync = require('../scripts/session-sync.js');
+const { createDirtyIndex } = require('../scripts/session-dirty.js');
const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
const base = [{ type: 'message', role: 'user', content: [{ text: 'question' }] }, { type: 'message', role: 'assistant', content: [{ text: 'answer' }] }];
function harness(t) {
@@ -22,16 +23,33 @@ function harness(t) {
lib.addAutoCopySessionMember(root, lineage, uid, id); write(id, base);
}
const syncCacheMap = new Map();
- const ctx = { ...lib, sessionSync, fs, path, crypto, DATA_DIR: root, PROFILE: { dataRoot: root, kind: 'workbuddy' },
+ const dirtyIndex = createDirtyIndex(); dirtyIndex.markBaseline('one');
+ const ctx = { ...lib, sessionSync, fs, path, crypto, DATA_DIR: root, PROFILE: { dataRoot: root, kind: 'workbuddy' }, createDirtyIndex,
+ sessionCopyRowRevision: row => JSON.stringify([
+ String(row && row.id || ''), String(row && row.user_id || ''),
+ Number(row && row.updated_at || 0), Number(row && row.last_activity_at || 0),
+ String(row && row.status || ''), String(row && row.title || ''), String(row && row.custom_title || ''),
+ ]),
accountSwitchInProgress: false, SESSION_COPY_COLUMNS: ['id', 'user_id'], sessionCopyLocks: new Map(), yieldAutoCopyToRenderer: async () => {}, assertSessionSyncIdle: async () => {},
getSessionSyncCache: () => syncCacheMap, scheduleSessionSyncCacheSave: () => {},
+ getSessionDirtyIndex: () => dirtyIndex,
log: () => {}, sqliteQuery: async (_, params) => {
+ if (params.length >= 4) {
+ return [...rows.values()].filter((candidate) => String(candidate.user_id) === String(params[0]) &&
+ String(candidate.cwd || '') === String(params[1] || '') &&
+ String(candidate.title || '') === String(params[2] || '') &&
+ String(candidate.custom_title || '') === String(params[3] || '')).map((candidate) => ({ ...candidate }));
+ }
const row = rows.get(params[0]); return row && (!params[1] || params[1] === row.user_id) ? [{ ...row }] : [];
},
sqliteRun: async (_, params) => { const row = rows.get(params[5]); assert.ok(row); Object.assign(row, { title: params[0], updated_at: params[3] }); },
- insertCopiedSession: async (src, uid, id) => { rows.set(id, { ...src, user_id: uid, id }); },
+ insertCopiedSession: async (src, uid, id) => {
+ const row = { ...src, user_id: uid, id, updated_at: Date.now(), last_activity_at: Number(src.last_activity_at || src.updated_at || Date.now()) };
+ rows.set(id, row);
+ return row;
+ },
};
- vm.runInNewContext(source.slice(source.indexOf('async function copySessionRecord('), source.indexOf('async function buildAutoCopyPlan(')), ctx);
+ vm.runInNewContext(source.slice(source.indexOf('function sessionCopyContentRevision('), source.indexOf('async function buildAutoCopyPlan(')), ctx);
return { root, rows, file, write, ctx, lineage, copy: () => ctx.copySessionRecord(rows.get('a'), 'two', { auto: true, lineageId: lineage }) };
}
test('account two continuation updates account one and never account three', async t => {
@@ -47,6 +65,389 @@ test('account two continuation updates account one and never account three', asy
assert.equal((await h.copy()).copiedBytes, 0);
});
+test('automatic first copy to an account with no physical target uses the fast snapshot path', async t => {
+ const h = harness(t);
+ lib.removeAutoCopySessionMember(h.root, h.lineage, 'two', 'b');
+ h.rows.delete('b');
+ fs.rmSync(h.file('b'), { force: true });
+ let syncReads = 0;
+ let asyncReads = 0;
+ const readSnapshot = h.ctx.sessionSync.readSnapshot;
+ const readSnapshotAsync = h.ctx.sessionSync.readSnapshotAsync;
+ h.ctx.sessionSync.readSnapshot = (...args) => { syncReads++; return readSnapshot(...args); };
+ h.ctx.sessionSync.readSnapshotAsync = async (...args) => { asyncReads++; return readSnapshotAsync(...args); };
+ try {
+ const result = await h.copy();
+ assert.equal(result.status, 'copied');
+ assert.ok(syncReads > 0, 'first-time copies should use the synchronous snapshot path');
+ assert.equal(asyncReads, 0, 'first-time copies should not pay the async snapshot path');
+ const mapping = lib.getAutoCopyMapping(h.root, h.lineage, 'two');
+ assert.equal(mapping.targetStateRevision, h.ctx.sessionCopyStableStateRevision(h.rows.get(result.targetId)),
+ 'new mappings must record the inserted target row revision');
+ } finally {
+ h.ctx.sessionSync.readSnapshot = readSnapshot;
+ h.ctx.sessionSync.readSnapshotAsync = readSnapshotAsync;
+ }
+});
+
+test('stale active-session lifecycle markers are cleared after an equal payload probe', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-active-lifecycle-dirty-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const write = (id) => {
+ const file = path.join(root, 'projects', 'p', id + '.jsonl');
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, base.map((item) => JSON.stringify(item)).join('\n') + '\n');
+ };
+ write('a'); write('b');
+ fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
+ version: 1, accounts: { one: { initialized: true, sessions: { a: { at: 123, event: 'sessionUpdated' } } } },
+ }));
+ lib.setAutoCopyAllSessions(root, true);
+ const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
+ lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
+ const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 8, last_activity_at: 8 };
+ const targetRow = { ...sourceRow, id: 'b', user_id: 'two', updated_at: 7, last_activity_at: 7 };
+ const revision = row => JSON.stringify([
+ String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
+ String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
+ ]);
+ lib.setAutoCopyMapping(root, lineage, 'two', {
+ targetId: 'b', fingerprintVersion: 2,
+ sourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),
+ targetRevision: revision(targetRow),
+ });
+ const ctx = {
+ ...lib, fs, path, DATA_DIR: root, PROFILE: { dataRoot: root }, sessionSync,
+ createDirtyIndex, getSessionSyncCache: () => new Map(),
+ setTimeout, clearTimeout,
+ SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
+ sessionCopyRowRevision: revision,
+ sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }],
+ };
+ const start = source.indexOf('function sessionCopyContentRevision(');
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two', ['a'])).length, 0);
+ assert.equal(ctx.getSessionDirtyIndex().get('one', 'a'), null, 'equal active payloads clear the stale lifecycle marker');
+ assert.equal(lib.getAutoCopyMapping(root, lineage, 'two').sourceRevision, revision(sourceRow));
+});
+
+test('missing mapping recovers an equal target row instead of creating a duplicate', async t => {
+ const h = harness(t);
+ for (const row of h.rows.values()) { row.cwd = '/fixture'; row.custom_title = ''; }
+ lib.removeAutoCopySessionMember(h.root, h.lineage, 'two', 'b');
+ const before = [...h.rows.values()].filter((row) => row.user_id === 'two').length;
+ const result = await h.copy();
+ assert.equal(result.status, 'skipped');
+ assert.equal(result.targetId, 'b');
+ assert.equal([...h.rows.values()].filter((row) => row.user_id === 'two').length, before);
+ assert.equal(lib.getAutoCopyMapping(h.root, h.lineage, 'two').targetId, 'b');
+});
+
+test('automatic repeat sync rechecks persisted content and reports no writes', async t => {
+ const h = harness(t);
+ assert.equal((await h.copy()).status, 'skipped');
+ const originalSnapshot = h.ctx.sessionSync.readSnapshotAsync;
+ const originalQuickFingerprint = h.ctx.sessionSync.readSessionQuickFingerprintAsync;
+ let fullReads = 0;
+ let quickReads = 0;
+ h.ctx.sessionSync.readSnapshotAsync = async (...args) => { fullReads++; return originalSnapshot(...args); };
+ h.ctx.sessionSync.readSessionQuickFingerprintAsync = async (...args) => { quickReads++; return originalQuickFingerprint(...args); };
+ try {
+ const result = await h.copy();
+ assert.equal(result.status, 'skipped');
+ assert.equal(result.copiedBytes, 0);
+ assert.equal(fullReads, 0, 'unchanged mapped sessions should skip full snapshots');
+ assert.equal(quickReads, 0, 'unchanged mapped sessions use DB revisions without filesystem scans');
+ } finally {
+ h.ctx.sessionSync.readSnapshotAsync = originalSnapshot;
+ h.ctx.sessionSync.readSessionQuickFingerprintAsync = originalQuickFingerprint;
+ }
+});
+
+test('reverse sync skips an activation-only append after the first account copy', async t => {
+ const h = harness(t);
+ const first = await h.copy();
+ assert.equal(first.status, 'skipped');
+ h.write('b', [...base, { type: 'session-meta', id: 'activation-b', sessionId: 'b', timestamp: 99, meta: { 'codebuddy.ai/hostKind': 'unopted' } }]);
+ const reverse = await h.ctx.copySessionRecord(h.rows.get('b'), 'one', {
+ auto: true, sourceUid: 'two', lineageId: h.lineage,
+ });
+ assert.equal(reverse.status, 'skipped');
+ assert.equal(reverse.copiedBytes, 0);
+ assert.equal(reverse.targetId, 'a');
+});
+
+test('automatic sync falls back to snapshots when a session row revision changes', async t => {
+ const h = harness(t);
+ assert.equal((await h.copy()).status, 'skipped');
+ h.write('a', [...base, nextMessage('changed')]);
+ h.rows.get('a').updated_at++;
+ const originalSnapshot = h.ctx.sessionSync.readSnapshotAsync;
+ let fullReads = 0;
+ h.ctx.sessionSync.readSnapshotAsync = async (...args) => { fullReads++; return originalSnapshot(...args); };
+ try {
+ const result = await h.copy();
+ assert.equal(result.status, 'copied');
+ assert.ok(fullReads > 0, 'changed DB revisions should leave the fast path');
+ } finally {
+ h.ctx.sessionSync.readSnapshotAsync = originalSnapshot;
+ }
+});
+
+test('automatic copy planning drops revision-stable mappings before workers', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-daemon-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({ version: 1, accounts: { one: { initialized: true, sessions: {} } } }));
+ lib.setAutoCopyAllSessions(root, true);
+ const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
+ lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
+ const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7 };
+ const target = { ...sourceRow, id: 'b', user_id: 'two' };
+ const revision = row => JSON.stringify([
+ String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
+ String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
+ ]);
+ lib.setAutoCopyMapping(root, lineage, 'two', {
+ targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision(target),
+ });
+ let targetQueries = 0;
+ const makeContext = () => ({ ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
+ sqliteQuery: async (_, params) => { if (String(params[0]) === 'two') targetQueries++; return [String(params[0]) === 'one' ? { ...sourceRow } : { ...target }]; } });
+ const start = source.indexOf('function sessionCopyContentRevision(');
+ let ctx = makeContext();
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0, 'stable mapped sessions should not enter the copy worker pool');
+ assert.equal(targetQueries, 0, 'clean plans should not query the target account');
+ sourceRow.updated_at++;
+ sourceRow.last_activity_at++;
+ fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
+ version: 1, accounts: { one: { initialized: true, sessions: { a: { at: 123, event: 'sessionUpdated' } } } },
+ }));
+ ctx = makeContext();
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 1, 'a changed source revision should be planned');
+ assert.equal(targetQueries, 1, 'dirty plans should query the target account once');
+});
+
+test('initialized clean mappings ignore legacy source revision drift', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-clean-revision-drift-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
+ version: 1, accounts: { one: { initialized: true, sessions: {} } },
+ }));
+ lib.setAutoCopyAllSessions(root, true);
+ const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
+ lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
+ const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 8, last_activity_at: 8 };
+ const targetRow = { ...sourceRow, id: 'b', user_id: 'two' };
+ const revision = row => JSON.stringify([
+ String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
+ String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
+ ]);
+ lib.setAutoCopyMapping(root, lineage, 'two', {
+ targetId: 'b', fingerprintVersion: 2,
+ sourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),
+ targetRevision: revision(targetRow),
+ });
+ const ctx = { ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
+ SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
+ sessionCopyRowRevision: revision,
+ sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }],
+ };
+ const start = source.indexOf('function sessionCopyContentRevision(');
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0, 'clean initialized mappings should not enter the worker for historical revision drift');
+});
+
+test('automatic copy planning reuses a stable cross-account mapping without a worker', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-cross-account-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ lib.setAutoCopyAllSessions(root, true);
+ const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
+ lib.addAutoCopySessionMember(root, lineage, 'three', 'c');
+ lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
+ const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7 };
+ const previousSource = { ...sourceRow, id: 'c', user_id: 'three' };
+ const target = { ...sourceRow, id: 'b', user_id: 'two' };
+ const revision = row => JSON.stringify([
+ String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
+ String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
+ ]);
+ lib.setAutoCopyMapping(root, lineage, 'two', {
+ targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(previousSource), targetRevision: revision(target),
+ });
+ const ctx = { ...lib, DATA_DIR: root, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
+ sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...target }] };
+ const start = source.indexOf('function sessionCopyContentRevision(');
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0, 'cross-account stable mappings should not enter the copy worker pool');
+ sourceRow.updated_at++;
+ sourceRow.last_activity_at++;
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 1, 'a changed cross-account source revision should be planned');
+});
+
+test('automatic copy planning ignores target activation lifecycle drift', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-target-lifecycle-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
+ version: 1, accounts: { one: { initialized: true, sessions: {} } },
+ }));
+ lib.setAutoCopyAllSessions(root, true);
+ const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
+ lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
+ const sourceRow = { id: 'a', user_id: 'one', title: 'fixture', custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7 };
+ const targetRow = { ...sourceRow, id: 'b', user_id: 'two', status: 'running', last_activity_at: 99 };
+ const revision = row => JSON.stringify([
+ String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
+ String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
+ ]);
+ lib.setAutoCopyMapping(root, lineage, 'two', {
+ targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision({ ...sourceRow, id: 'b', user_id: 'two' }),
+ });
+ const ctx = { ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
+ SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
+ sessionCopyRowRevision: revision,
+ sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? sourceRow : targetRow],
+ };
+ const start = source.indexOf('function sessionCopyContentRevision(');
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0, 'activation metadata must not enter the copy worker');
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two', ['a'])).length, 0, 'active-session restoration must also stay on the metadata path');
+});
+
+test('source activation-only updated_at drift clears dirty state without a snapshot worker', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-source-lifecycle-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
+ version: 1, accounts: { one: { initialized: true, sessions: { a: { at: 123, event: 'sessionUpdated' } } } },
+ }));
+ lib.setAutoCopyAllSessions(root, true);
+ const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
+ lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
+ const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 9, last_activity_at: 7 };
+ const targetRow = { ...sourceRow, id: 'b', user_id: 'two', updated_at: 8 };
+ const revision = row => JSON.stringify([
+ String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
+ String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
+ ]);
+ lib.setAutoCopyMapping(root, lineage, 'two', {
+ targetId: 'b', fingerprintVersion: 2, sourceRevision: revision({ ...sourceRow, updated_at: 8 }),
+ targetRevision: revision(targetRow),
+ });
+ let snapshotReads = 0;
+ const ctx = {
+ ...lib, fs, path, DATA_DIR: root, PROFILE: { dataRoot: root }, createDirtyIndex,
+ setTimeout, clearTimeout, getSessionSyncCache: () => new Map(),
+ SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
+ sessionCopyRowRevision: revision,
+ sessionSync: {
+ readSnapshotAsync: async () => { snapshotReads++; throw new Error('activation-only drift must stay off the snapshot worker'); },
+ compareSnapshots: () => ({ kind: 'equal' }),
+ },
+ sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }],
+ };
+ const start = source.indexOf('function sessionCopyContentRevision(');
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0);
+ assert.equal(snapshotReads, 0);
+ assert.equal(ctx.getSessionDirtyIndex().get('one', 'a'), null);
+});
+
+test('active sync status ignores a recent job for another target account', () => {
+ const start = source.indexOf('function activeAutoCopyJob(');
+ const ctx = {
+ Date: { now: () => 10000 },
+ autoCopyJobs: new Map([
+ ['other', { id: 'other', targetUid: 'two', status: 'done', finishedAt: 9900, startedAt: 9000 }],
+ ['current', { id: 'current', targetUid: 'one', status: 'done', finishedAt: 9800, startedAt: 8800 }],
+ ]),
+ };
+ vm.runInNewContext(source.slice(start, source.indexOf('const MAX_SESSION_ID_LENGTH', start)), ctx);
+ assert.equal(ctx.activeAutoCopyJob('one').id, 'current');
+ assert.equal(ctx.activeAutoCopyJob('missing'), null);
+});
+
+test('explicitly requested open session is planned without regular auto-copy rules', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-requested-session-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const sourceRow = {
+ id: 'open-session', user_id: 'one', cwd: '/fixture', title: 'Open conversation',
+ custom_title: '', status: 'completed', created_at: 1, updated_at: 7, last_activity_at: 7,
+ };
+ const targetRow = { ...sourceRow, id: 'other-session', user_id: 'two' };
+ const ctx = {
+ ...lib, fs, path, DATA_DIR: root,
+ SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
+ sessionCopyRowRevision: row => JSON.stringify([
+ String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
+ String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
+ ]),
+ sqliteQuery: async (_, params) => String(params[0]) === 'one' ? [{ ...sourceRow }] : [{ ...targetRow }],
+ };
+ const start = source.indexOf('function sessionCopyContentRevision(');
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+
+ const plan = await ctx.buildAutoCopyPlan('one', 'two', ['open-session']);
+ assert.deepEqual(plan.map(row => row.id), ['open-session']);
+ assert.equal(plan[0].lineageId, null, 'an explicitly requested session need not already have a copy lineage');
+});
+
+test('requested unchanged open session resolves its mapping without entering the copy worker', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-requested-clean-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
+ version: 1, accounts: { one: { initialized: true, sessions: {} } },
+ }));
+ lib.setAutoCopyAllSessions(root, true);
+ const lineage = lib.ensureAutoCopySession(root, 'one', 'open-session');
+ lib.addAutoCopySessionMember(root, lineage, 'two', 'copied-session');
+ const sourceRow = {
+ id: 'open-session', user_id: 'one', cwd: '/fixture', title: 'Open conversation',
+ custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7,
+ };
+ const targetRow = { ...sourceRow, id: 'copied-session', user_id: 'two' };
+ const revision = row => JSON.stringify([
+ String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
+ String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
+ ]);
+ lib.setAutoCopyMapping(root, lineage, 'two', {
+ targetId: targetRow.id, fingerprintVersion: 2,
+ sourceRevision: revision(sourceRow), targetRevision: revision(targetRow),
+ });
+ let targetQueries = 0;
+ const ctx = {
+ ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
+ SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
+ sessionCopyRowRevision: revision,
+ sqliteQuery: async (_, params) => {
+ if (String(params[0]) === 'two') targetQueries++;
+ return [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }];
+ },
+ };
+ const start = source.indexOf('function sessionCopyContentRevision(');
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two', ['open-session'])).length, 0);
+ assert.equal(targetQueries, 1, 'requested recovery may read the target row but must not snapshot it');
+});
+
+test('stable mappings clear legacy lifecycle dirty markers before planning', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-stale-dirty-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({ version: 1, accounts: { one: { initialized: true, sessions: { a: { at: 123, event: 'sessionUpdated' } } } } }));
+ lib.setAutoCopyAllSessions(root, true);
+ const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
+ lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
+ const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7 };
+ const targetRow = { ...sourceRow, id: 'b', user_id: 'two' };
+ const revision = row => JSON.stringify([String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0), String(row.status || ''), String(row.title || ''), String(row.custom_title || '')]);
+ lib.setAutoCopyMapping(root, lineage, 'two', { targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision(targetRow) });
+ const ctx = { ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision, sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }] };
+ const start = source.indexOf('function sessionCopyContentRevision(');
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0);
+ assert.equal(ctx.getSessionDirtyIndex().get('one', 'a'), null);
+});
+
test('sessions over 100 MiB copy completely and report only an advisory, including on repeat sync', async t => {
const h = harness(t);
const file = path.join(h.root, 'workspace/sessions/a/large.bin');
@@ -99,7 +500,7 @@ test('manual and automatic switching bypass session activity while retaining ope
const ctx = { accountSwitchInProgress: false, cdp: { connected: true }, PROFILE: { kind: 'workbuddy' }, autoCopyWorkerRunning: false, autoCopyQueue: [], sessionCopyLocks: new Map(),
cdpSend: async () => ({ result: { value: true } }) };
vm.runInNewContext(source.slice(start, end), ctx);
- await assert.rejects(ctx.assertSessionSyncIdle(), /会话仍在运行/);
+ await assert.rejects(ctx.assertSessionSyncIdle(['source', 'target']), /会话仍在运行/);
ctx.cdpSend = async () => ({ result: { value: null } });
await assert.rejects(ctx.assertSessionSyncIdle(), /无法确认/);
ctx.cdpSend = async () => ({ result: { value: false } }); await ctx.assertSessionSyncIdle();
@@ -124,9 +525,11 @@ test('manual and automatic switching bypass session activity while retaining ope
});
test('mixed sync jobs continue after divergence and report every result', async () => {
const results = ['conflict', 'copied', 'skipped', 'error'];
- const ctx = { crypto, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ let sizeReads = 0;
+ const ctx = { crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => results.map((_, i) => ({ id: String(i) })),
copySessionRecord: async row => { const status = results[Number(row.id)]; if (status === 'error') throw Error('fixture failure'); return { status, branched: status === 'copied', copiedBytes: status === 'copied' ? 123456 : 0, totalBytes: 123456, warning: status === 'copied' ? 'large session advisory' : '' }; },
+ sessionSync: { readSessionSizes: async () => { sizeReads++; return new Map(); } },
log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout: () => ({ unref() {} }),
};
const start = source.indexOf('function startAutoCopyJob(');
@@ -134,6 +537,7 @@ test('mixed sync jobs continue after divergence and report every result', async
const job = ctx.startAutoCopyJob('one', 'two', []);
await ctx.autoCopyQueue[0].run();
assert.equal(job.processed, 4);
+ assert.equal(sizeReads, 0);
assert.equal(job.copiedBytes, 123456);
assert.equal(job.conflicts, 1); assert.equal(job.copied, 1); assert.equal(job.skipped, 1); assert.equal(job.failedItems, 1);
assert.equal(job.details[1].branched, true);
@@ -151,6 +555,167 @@ test('mixed sync jobs continue after divergence and report every result', async
assert.equal(published.details[0].warning, 'large session advisory');
assert.equal(published.details[0].totalBytes, 123456);
});
+
+test('active session copy retries transient file races and preserves its target id', async () => {
+ let attempts = 0;
+ const ctx = {
+ crypto,
+ DATA_DIR: 'fixture-data',
+ PROFILE: { dataRoot: 'fixture-root' },
+ autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ yieldAutoCopyToRenderer: async () => {},
+ buildAutoCopyPlan: async () => [{ id: 'active-source', lineageId: 'lineage-active' }],
+ copySessionRecord: async () => {
+ attempts++;
+ if (attempts === 1) throw Error('会话文件正在变化,请稍后重试');
+ return { status: 'copied', sourceId: 'active-source', targetId: 'active-target', sourceBytes: 1, copiedBytes: 1, totalBytes: 1 };
+ },
+ getAutoCopyMapping: () => null,
+ getAutoCopySession: () => ({ lineageId: 'lineage-active' }),
+ log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout,
+ };
+ const start = source.indexOf('function startAutoCopyJob(');
+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
+ const job = ctx.startAutoCopyJob('source', 'target', [], { openSessionId: 'active-source' });
+ await ctx.autoCopyQueue[0].run();
+ assert.equal(attempts, 2);
+ assert.equal(job.failed, 0);
+ assert.equal(ctx.publicAutoCopyJob(job).openSessionId, 'active-target');
+});
+
+test('active session copy keeps waiting through a longer renderer flush', async () => {
+ let attempts = 0;
+ const ctx = {
+ crypto,
+ PROFILE: { dataRoot: 'fixture-root' },
+ autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ yieldAutoCopyToRenderer: async () => {},
+ buildAutoCopyPlan: async () => [{ id: 'active-source', lineageId: 'lineage-active' }],
+ copySessionRecord: async () => {
+ attempts++;
+ if (attempts <= 3) throw Error('会话文件正在变化,请稍后重试');
+ return { status: 'skipped', sourceId: 'active-source', targetId: 'active-target', sourceBytes: 1, copiedBytes: 0, totalBytes: 1 };
+ },
+ getAutoCopyMapping: () => null,
+ getAutoCopySession: () => ({ lineageId: 'lineage-active' }),
+ log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout,
+ };
+ const start = source.indexOf('function startAutoCopyJob(');
+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
+ const job = ctx.startAutoCopyJob('source', 'target', [], { openSessionId: 'active-source' });
+ await ctx.autoCopyQueue[0].run();
+ assert.equal(attempts, 4);
+ assert.equal(job.failed, 0);
+ assert.equal(job.skipped, 1);
+ assert.equal(ctx.publicAutoCopyJob(job).openSessionId, 'active-target');
+});
+
+test('unchanged requested session resolves its target without entering the copy worker', async () => {
+ let copies = 0;
+ const ctx = {
+ crypto,
+ PROFILE: { dataRoot: 'fixture-root' },
+ autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ yieldAutoCopyToRenderer: async () => {},
+ buildAutoCopyPlan: async () => [],
+ resolveAutoCopyTargetId: () => 'existing-target',
+ copySessionRecord: async () => { copies++; throw Error('must not copy'); },
+ log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout,
+ };
+ const start = source.indexOf('function startAutoCopyJob(');
+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
+ const job = ctx.startAutoCopyJob('source', 'target', [], { openSessionId: 'active-source' });
+ await ctx.autoCopyQueue[0].run();
+ assert.equal(copies, 0);
+ assert.equal(job.failed, 0);
+ assert.equal(ctx.publicAutoCopyJob(job).openSessionId, 'existing-target');
+});
+
+test('empty message sessions are skipped instead of shown as sync failures', async () => {
+ let cleared = 0;
+ const ctx = {
+ crypto,
+ PROFILE: { dataRoot: 'fixture-root' },
+ autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ yieldAutoCopyToRenderer: async () => {},
+ buildAutoCopyPlan: async () => [{ id: 'empty-session' }],
+ copySessionRecord: async () => { throw Error('会话消息文件没有消息,未同步'); },
+ getSessionDirtyIndex: () => ({ get: () => ({ at: 7 }) }),
+ clearSessionDirty: (_uid, _id, at) => { if (at === 7) cleared++; return true; },
+ log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout,
+ };
+ const start = source.indexOf('function startAutoCopyJob(');
+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
+ const job = ctx.startAutoCopyJob('source', 'target', []);
+ await ctx.autoCopyQueue[0].run();
+ assert.equal(job.failed, 0);
+ assert.equal(job.failedItems, 0);
+ assert.equal(job.skipped, 1);
+ assert.equal(cleared, 1);
+ assert.equal(ctx.publicAutoCopyJob(job).details[0].status, 'skipped');
+});
+
+test('an empty automatic copy plan does not wait for renderer injection', async () => {
+ const planningYields = [];
+ let rendererWaits = 0;
+ const ctx = { crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ yieldAutoCopyToRenderer: async options => {
+ planningYields.push(options);
+ if (!options || options.waitForInjection !== false) rendererWaits++;
+ },
+ buildAutoCopyPlan: async () => [], sessionSync: { readSessionSizes: async () => new Map() },
+ log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout: () => ({ unref() {} }),
+ };
+ const start = source.indexOf('function startAutoCopyJob(');
+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
+ const job = ctx.startAutoCopyJob('one', 'two', []);
+ await ctx.autoCopyQueue[0].run();
+ assert.equal(job.status, 'done');
+ assert.equal(planningYields.length, 1);
+ assert.equal(planningYields[0].waitForInjection, false);
+ assert.equal(rendererWaits, 0);
+});
+
+test('automatic session sync uses a bounded worker pool', async () => {
+ let running = 0;
+ let peak = 0;
+ const ctx = { crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => Array.from({ length: 8 }, (_, id) => ({ id: String(id) })),
+ copySessionRecord: async row => {
+ running++;
+ peak = Math.max(peak, running);
+ await new Promise(resolve => setTimeout(resolve, 5));
+ running--;
+ return { status: 'skipped', sourceBytes: 1, copiedBytes: 0, totalBytes: 1 };
+ },
+ log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout,
+ };
+ const start = source.indexOf('function startAutoCopyJob(');
+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
+ const job = ctx.startAutoCopyJob('one', 'two', []);
+ await ctx.autoCopyQueue[0].run();
+ assert.equal(peak, 4);
+ assert.equal(job.processed, 8);
+ assert.equal(job.skipped, 8);
+ assert.deepEqual(Array.from(job.details, item => item.id), Array.from({ length: 8 }, (_, id) => String(id)));
+});
+
+test('automatic session sync aggregates copied bytes independently across workers', async () => {
+ const ctx = { crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => Array.from({ length: 8 }, (_, id) => ({ id: String(id) })),
+ copySessionRecord: async () => {
+ await new Promise(resolve => setTimeout(resolve, 2));
+ return { status: 'copied', sourceBytes: 100, copiedBytes: 100, totalBytes: 100 };
+ },
+ log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout,
+ };
+ const start = source.indexOf('function startAutoCopyJob(');
+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
+ const job = ctx.startAutoCopyJob('one', 'two', []);
+ await ctx.autoCopyQueue[0].run();
+ assert.equal(job.copiedBytes, 800);
+});
+
test('macOS packaging includes the required sync module', () => {
const script = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');
assert.match(script, /for f in [^\n]*session-sync\.js/);
@@ -282,6 +847,7 @@ test('a copied branch remains visible beside the original and later updates only
const visible = lib.dedupeAutoCopySessionRows(targetRows, { two: rules.allLineages }, { two: new Set(rules.branchSessionIds) });
assert.equal(visible.length, 2);
h.write('a', [...base, nextMessage('source branch'), nextMessage('continued source branch')]);
+ h.rows.get('a').updated_at++;
const updated = await h.copy();
assert.equal(updated.status, 'copied'); assert.equal(updated.targetId, result.targetId);
assert.deepEqual(fs.readFileSync(h.file(updated.targetId)), fs.readFileSync(h.file('a')));
diff --git a/test/session-sync.test.js b/test/session-sync.test.js
index 6e676b2..f6943b8 100644
--- a/test/session-sync.test.js
+++ b/test/session-sync.test.js
@@ -4,7 +4,7 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
-const { readSnapshot, compareSnapshots, applySnapshot } = require('../scripts/session-sync.js');
+const { readSnapshot, readSnapshotAsync, readSessionFingerprintAsync, readSessionQuickFingerprintAsync, compareSnapshots, applySnapshot, applySnapshotAsync } = require('../scripts/session-sync.js');
const message = (role, text) => ({ type: 'message', role, content: [{ type: 'text', text }] });
const base = [message('user', 'question'), message('assistant', 'answer')];
@@ -48,6 +48,30 @@ test('same content skips; only a full prefix permits replacement, irrespective o
f.write('a', [...base, message('user', 'different')]);
assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'conflict');
});
+
+test('a transient target conflict is rechecked before it can become a branch', async t => {
+ const f = fixture(t); f.write('a', base); f.write('b', base);
+ const source = f.read('a');
+ let reads = 0;
+ const result = await require('../scripts/session-sync.js').selectTargetSnapshot(
+ source,
+ ['b'],
+ async () => {
+ reads++;
+ if (reads === 1) {
+ return {
+ ...f.read('b'),
+ records: [...source.records.slice(0, -1), 'transient-conflict'],
+ };
+ }
+ return f.read('b');
+ }
+ );
+ assert.equal(result.targetId, 'b');
+ assert.equal(result.comparison.kind, 'equal');
+ assert.ok(reads >= 2);
+});
+
test('equal user messages cannot hide different replies, tools or attachments', t => {
const f = fixture(t);
for (const records of [
@@ -66,14 +90,149 @@ test('only identity fields normalize; literal session IDs inside messages remain
f.write('a', [message('user', 'a')]); f.write('b', [message('user', 'b')]);
assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'conflict');
});
-test('missing payload is repairable but empty, corrupt and symlinked files fail closed', t => {
+
+test('activation-only session-meta records do not conflict across account copies', t => {
+ const f = fixture(t);
+ const stable = { type: 'session-meta', meta: { 'codebuddy.ai/hostKind': 'unopted' } };
+ f.write('a', [{ ...stable, id: 'event-a', sessionId: 'a', timestamp: 100 }, ...base]);
+ f.write('b', [{ ...stable, id: 'event-b', sessionId: 'b', timestamp: 200 }, ...base]);
+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'equal');
+});
+
+test('an activation-only session-meta append does not become an imported continuation', t => {
+ const f = fixture(t);
+ const stable = { type: 'session-meta', meta: { 'codebuddy.ai/hostKind': 'unopted' } };
+ f.write('a', base);
+ f.write('b', [...base, { ...stable, id: 'event-b', sessionId: 'b', timestamp: 200 }]);
+ assert.equal(compareSnapshots(f.read('b'), f.read('a')).kind, 'equal');
+});
+test('missing payload is repairable and symlinked files are skipped without following them', async t => {
const f = fixture(t); f.write('a', base);
assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'left-extends');
for (const text of ['', '{broken\n']) {
fs.writeFileSync(f.file('b'), text); assert.throws(() => f.read('b'));
}
fs.unlinkSync(f.file('b')); fs.symlinkSync(f.file('a'), f.file('b'));
- assert.throws(() => f.read('b'), /符号链接/);
+ assert.equal(f.read('b').files.size, 0);
+
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-sync-link-outside-'));
+ t.after(() => fs.rmSync(outside, { recursive: true, force: true }));
+ fs.unlinkSync(f.file('b'));
+ f.write('b', base);
+ const sourceDir = path.join(f.root, 'workspace', 'sessions', 'a');
+ const targetDir = path.join(f.root, 'workspace', 'sessions', 'b');
+ fs.mkdirSync(sourceDir, { recursive: true });
+ fs.mkdirSync(targetDir, { recursive: true });
+ fs.writeFileSync(path.join(sourceDir, 'keep.bin'), 'keep');
+ fs.writeFileSync(path.join(outside, 'secret.bin'), 'secret');
+ fs.symlinkSync(path.join(outside, 'secret.bin'), path.join(sourceDir, 'link.bin'));
+ const source = await readSnapshotAsync(f.root, 'a', ['a', 'b']);
+ assert.equal(source.files.has('workspace/sessions/__session__/keep.bin'), true);
+ assert.equal(source.files.has('workspace/sessions/__session__/link.bin'), false);
+ await applySnapshotAsync(source, await readSnapshotAsync(f.root, 'b', ['a', 'b']), { backupRoot: path.join(f.root, 'backups') });
+ assert.equal(fs.readFileSync(path.join(targetDir, 'keep.bin'), 'utf8'), 'keep');
+ assert.equal(fs.existsSync(path.join(targetDir, 'link.bin')), false);
+});
+
+test('configured data root may be a directory junction while child links are skipped', async t => {
+ const realRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-sync-real-'));
+ const linkedRoot = path.join(os.tmpdir(), 'wd-sync-root-' + require('node:crypto').randomUUID());
+ t.after(() => {
+ fs.rmSync(linkedRoot, { recursive: true, force: true });
+ fs.rmSync(realRoot, { recursive: true, force: true });
+ });
+ fs.mkdirSync(path.join(realRoot, 'projects', 'project'), { recursive: true });
+ fs.writeFileSync(path.join(realRoot, 'projects', 'project', 'a.jsonl'), JSON.stringify(base[0]) + '\n');
+ fs.symlinkSync(realRoot, linkedRoot, process.platform === 'win32' ? 'junction' : 'dir');
+ assert.equal(readSnapshot(linkedRoot, 'a', ['a']).records.length, 1);
+ assert.equal((await readSnapshotAsync(linkedRoot, 'a', ['a'])).records.length, 1);
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-sync-outside-'));
+ t.after(() => fs.rmSync(outside, { recursive: true, force: true }));
+ fs.mkdirSync(path.join(realRoot, 'tasks'), { recursive: true });
+ fs.symlinkSync(outside, path.join(realRoot, 'tasks', 'a'), process.platform === 'win32' ? 'junction' : 'dir');
+ assert.equal(readSnapshot(linkedRoot, 'a', ['a']).records.length, 1);
+ assert.equal((await readSnapshotAsync(linkedRoot, 'a', ['a'])).records.length, 1);
+ await readSessionFingerprintAsync(linkedRoot, 'a');
+ await readSessionQuickFingerprintAsync(linkedRoot, 'a');
+});
+
+test('snapshots exclude local modify backups from workspace sessions', async t => {
+ const f = fixture(t); f.write('a', base);
+ const sessionRoot = path.join(f.root, 'workspace', 'sessions', 'a');
+ fs.mkdirSync(path.join(sessionRoot, 'modify_backup'), { recursive: true });
+ fs.mkdirSync(path.join(sessionRoot, '.modify_backup_meta'), { recursive: true });
+ fs.writeFileSync(path.join(sessionRoot, 'keep.bin'), 'keep');
+ fs.writeFileSync(path.join(sessionRoot, 'modify_backup', '12.m.a1b2c3.original'), 'ignored backup');
+ fs.writeFileSync(path.join(sessionRoot, '.modify_backup_meta', 'meta.json'), 'ignored metadata');
+ for (const read of [
+ id => readSnapshot(f.root, id, ['a']),
+ id => readSnapshotAsync(f.root, id, ['a']),
+ ]) {
+ const snapshot = await read('a');
+ assert.equal(snapshot.totalBytes, 4 + Buffer.byteLength(JSON.stringify(base[0]) + '\n' + JSON.stringify(base[1]) + '\n'));
+ assert.ok(snapshot.files.has('workspace/sessions/__session__/keep.bin'));
+ assert.equal([...snapshot.files.keys()].some(key => key.includes('modify_backup')), false);
+ }
+});
+
+test('session fingerprints ignore local modify backups but change for managed entries', async t => {
+ const f = fixture(t); f.write('a', base);
+ const sessionRoot = path.join(f.root, 'workspace', 'sessions', 'a');
+ fs.mkdirSync(path.join(sessionRoot, 'modify_backup'), { recursive: true });
+ const before = await readSessionFingerprintAsync(f.root, 'a');
+ fs.writeFileSync(path.join(sessionRoot, 'modify_backup', '1.m.hash.original'), 'local backup');
+ assert.equal(await readSessionFingerprintAsync(f.root, 'a'), before);
+ fs.writeFileSync(path.join(sessionRoot, 'keep.bin'), 'managed');
+ assert.notEqual(await readSessionFingerprintAsync(f.root, 'a'), before);
+});
+
+test('async snapshots stream large transcripts and publication keeps the event loop responsive', async t => {
+ const f = fixture(t);
+ const payload = 'x'.repeat(64 * 1024);
+ const records = Array.from({ length: 256 }, (_, index) => message(index % 2 ? 'assistant' : 'user', payload + index));
+ f.write('a', records);
+ f.write('b', records.slice(0, 128));
+ let ticks = 0;
+ const timer = setInterval(() => { ticks++; }, 0);
+ try {
+ const source = await readSnapshotAsync(f.root, 'a', ['a', 'b', 'c']);
+ const target = await readSnapshotAsync(f.root, 'b', ['a', 'b', 'c']);
+ const synchronous = readSnapshot(f.root, 'a', ['a', 'b', 'c']);
+ assert.deepEqual(source.records, synchronous.records);
+ assert.equal(source.files.get(source.transcriptKey).semantic, synchronous.files.get(synchronous.transcriptKey).semantic);
+ assert.equal(compareSnapshots(source, target).kind, 'left-extends');
+ await applySnapshotAsync(source, target, { backupRoot: path.join(f.root, 'backups') });
+ assert.equal(compareSnapshots(
+ await readSnapshotAsync(f.root, 'a', ['a', 'b', 'c']),
+ await readSnapshotAsync(f.root, 'b', ['a', 'b', 'c'])
+ ).kind, 'equal');
+ } finally {
+ clearInterval(timer);
+ }
+ assert.ok(ticks > 0, 'large sync must yield to daemon HTTP and renderer work');
+});
+
+test('async publication rolls back commit failures without overwriting concurrent official writes', async t => {
+ const f = fixture(t);
+ f.write('a', [...base, message('user', 'continued')]);
+ f.write('b', base);
+ const original = fs.readFileSync(f.file('b'));
+ await assert.rejects(applySnapshotAsync(
+ await readSnapshotAsync(f.root, 'a', ['a', 'b', 'c']),
+ await readSnapshotAsync(f.root, 'b', ['a', 'b', 'c']),
+ { backupRoot: path.join(f.root, 'backups'), commit: async () => { throw Error('DB failure'); } }
+ ), /DB failure/);
+ assert.deepEqual(fs.readFileSync(f.file('b')), original);
+
+ await assert.rejects(applySnapshotAsync(
+ await readSnapshotAsync(f.root, 'a', ['a', 'b', 'c']),
+ await readSnapshotAsync(f.root, 'b', ['a', 'b', 'c']),
+ { backupRoot: path.join(f.root, 'backups'), commit: async verifyPublished => {
+ f.write('b', [...base, message('user', 'official write')]);
+ await verifyPublished();
+ } }
+ ), /目标会话正在变化/);
+ assert.match(fs.readFileSync(f.file('b'), 'utf8'), /official write/);
});
test('equal messages repair missing supporting files but conflicting supporting files are preserved', t => {
const f = fixture(t); f.write('a', base); f.write('b', base);
diff --git a/test/session-transfer.test.js b/test/session-transfer.test.js
index d006371..5607850 100644
--- a/test/session-transfer.test.js
+++ b/test/session-transfer.test.js
@@ -64,7 +64,10 @@ test('export detects files changed after collection and removes partial output',
test('real session export/import routes round-trip binary archives and retain ownership', async t => {
const vm = require('node:vm'), http = require('node:http');
- const dir = fixture(t), home = path.join(dir, 'home');
+ const dir = fixture(t), realHome = path.join(dir, 'real-home'), home = path.join(dir, 'home');
+ fs.mkdirSync(realHome, { recursive: true });
+ try { fs.symlinkSync(realHome, home, process.platform === 'win32' ? 'junction' : 'dir'); }
+ catch (error) { if (['EPERM', 'EACCES'].includes(error.code)) return t.skip('symlinks unavailable'); throw error; }
const original = path.join(home, 'tasks', id, '测试附件.bin');
fs.mkdirSync(path.dirname(original), { recursive: true });
fs.writeFileSync(original, crypto.randomBytes(100001));
diff --git a/test/sleep-mode.test.js b/test/sleep-mode.test.js
index bfdf38a..6103f9e 100644
--- a/test/sleep-mode.test.js
+++ b/test/sleep-mode.test.js
@@ -74,6 +74,8 @@ test('until-done waits for every discovered session, including blocked and recen
vm.createContext(ctx);
vm.runInContext(ui.slice(ui.indexOf(' function discoverSleepSessionBusy()'), ui.indexOf(' // 同步防休眠状态:三模式')), ctx);
assert.equal(ctx.window.__wbsAnySessionBusy(), true);
+ assert.equal(ctx.window.__wbsSessionsBusy(['a']), true);
+ assert.equal(ctx.window.__wbsSessionsBusy(['unrelated']), false);
ctx.startUntilDoneCheck();
poll(); assert.equal(posts.length, 0);
controllers[0].busy = false;
diff --git a/test/stash-queue.test.js b/test/stash-queue.test.js
index 7f5af44..09c7e02 100644
--- a/test/stash-queue.test.js
+++ b/test/stash-queue.test.js
@@ -170,7 +170,7 @@ test('theme tab is capability-gated and available to WorkBuddy AI', () => {
test('daemon stash restore has an AI composer fallback when voice-mic-wrap is absent', () => {
const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
assert.match(daemon, /const clearExpr = `\(function\(\)\{[\s\S]*?if \(!ed\) \{[\s\S]*?contenteditable/);
- assert.match(daemon, /var allEd = document\.querySelectorAll\('\[contenteditable="true"\]'\)/);
+ assert.match(daemon, /var allEd = document\.querySelectorAll\('\[contenteditable="true"\],textarea'\)/);
});
test('modern conversation id comes from the selected sidebar card, not message req ids', () => {
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index 50b81c8..1ec7f44 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -4,6 +4,7 @@ const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const test = require('node:test');
+const vm = require('node:vm');
const repoRoot = path.resolve(__dirname, '..');
const read = (name) => fs.readFileSync(path.join(repoRoot, 'scripts', name), 'utf8').replace(/\r\n/g, '\n');
@@ -158,20 +159,146 @@ test('account switching refreshes WorkBuddy after replacing auth without restart
const lib = read('lib.js');
const routeStart = script.indexOf("if (req.method === 'POST' && p === '/api/switch')");
assert.notEqual(routeStart, -1);
- const route = script.slice(routeStart, routeStart + 2600);
+ const route = script.slice(routeStart, routeStart + 5200);
const copy = route.indexOf('switchTo(DATA_DIR, uid, log)');
assert.notEqual(copy, -1);
- assert.match(route, /await reloadWorkBuddyPage\(\)/);
+ assert.match(route, /await reloadWorkBuddyPage\(\{ waitForInjection: false \}\)/);
assert.doesNotMatch(route, /await quitWorkBuddy\(\)/);
assert.doesNotMatch(route, /await relaunchWorkBuddy\(\)/);
assert.match(lib, /function retireLogoutMarker/);
assert.match(lib, /retireLogoutMarker\(log\);/);
});
+test('account switching carries the active conversation and opens its copied target', () => {
+ const script = read('daemon.js');
+ const inject = read('inject.js');
+ const compat = read('workbuddy-compat.js');
+ const routeStart = script.indexOf("if (req.method === 'POST' && p === '/api/switch')");
+ const route = script.slice(routeStart, routeStart + 9000);
+ assert.match(route, /currentConversationId/);
+ assert.match(route, /SELECT user_id FROM sessions WHERE id = \? AND deleted_at IS NULL LIMIT 1;/);
+ assert.match(route, /不属于源账号的当前会话/);
+ const dirtyStart = script.indexOf("if (req.method === 'POST' && p === '/api/sessions/dirty')");
+ const dirtyRoute = script.slice(dirtyStart);
+ assert.match(dirtyRoute.slice(0, 900), /claimedUid && claimedUid !== currentUid/);
+ assert.match(dirtyRoute.slice(0, 900), /忽略旧会话通知/);
+ assert.match(route, /openSessionId/);
+ assert.match(inject, /conversations\.currentId/);
+ assert.match(inject, /currentConversationId: acSwitchConversationId\(\)/);
+ assert.match(inject, /function acSwitchConversationId()/);
+ assert.match(inject, /openCopiedSession/);
+ assert.match(compat, /function findConversationActivationApi\(doc\)/);
+ assert.match(compat, /setCurrentConversation/);
+ assert.match(compat, /sdkNavigateKind/);
+ assert.match(compat, /adapter\.emit\('jump-to-conversation'/);
+ assert.match(inject, /activationApi\.hasSession\(id\)/);
+ assert.match(inject, /job\.openSessionId\) setBuildTimeout\(function \(\) \{ openCopiedSession\(job\.openSessionId\); \}, 1000\)/);
+ assert.match(inject, /OPEN_SESSION_TIMEOUT = 15000/);
+ assert.match(inject, /String\(acActiveConversationId\(\) \|\| ''\) === id/);
+ assert.match(inject, /activationApi\.activate\(id\)/);
+ assert.match(inject, /if \(isActive\(\)\) \{/);
+ assert.match(inject, /\[session-activation\]/);
+ assert.match(inject, /activationLog\('has-session'/);
+ assert.match(inject, /activationLog\('activate-called'/);
+ assert.match(inject, /'confirmed' : 'not-confirmed'/);
+ assert.match(inject, /activationLog\('timeout'/);
+ assert.match(inject, /setBuildTimeout\(function \(\) \{ openCopiedSession\(id, started, attempt \+ 1\); \}, 500\)/);
+});
+
+test('copied-session activation trusts the official handler even when projection ids are empty', async () => {
+ const inject = read('inject.js');
+ const start = inject.indexOf(' function openCopiedSession(sessionId, startedAt) {');
+ const end = inject.indexOf('\n // token 过期状态', start);
+ assert.ok(start >= 0 && end > start);
+ let activeId = '';
+ let activations = 0;
+ const logs = [];
+ const context = {
+ Date,
+ String,
+ Promise,
+ console: { log: (...args) => logs.push(args.join(' ')) },
+ setBuildTimeout: setTimeout,
+ acActiveConversationId: () => activeId,
+ WBS_COMPAT: {
+ findConversationActivationApi() {
+ return {
+ authoritative: true,
+ hasSession: () => Promise.resolve(null),
+ activate() {
+ activations++;
+ return true;
+ },
+ };
+ },
+ },
+ document: {
+ querySelector() { return null; },
+ querySelectorAll() { return []; },
+ },
+ };
+ vm.runInNewContext(inject.slice(start, end), context);
+ context.openCopiedSession('copied-session');
+ await new Promise((resolve) => setTimeout(resolve, 800));
+ assert.equal(activations, 1, 'an authoritative handler must not be called repeatedly when projection ids are unavailable');
+ assert.equal(activeId, '');
+ assert.ok(logs.some((line) => line.includes('[session-activation]') && line.includes('has-session')));
+ assert.ok(logs.some((line) => line.includes('official-dispatched')));
+});
+
+test('copied-session activation retries an unverified official dispatch', async () => {
+ const inject = read('inject.js');
+ const start = inject.indexOf(' function openCopiedSession(sessionId, startedAt) {');
+ const end = inject.indexOf('\n // token 过期状态', start);
+ let activeId = '';
+ let activations = 0;
+ const logs = [];
+ const context = {
+ Date,
+ String,
+ Promise,
+ console: { log: (...args) => logs.push(args.join(' ')) },
+ setBuildTimeout: setTimeout,
+ acActiveConversationId: () => activeId,
+ WBS_COMPAT: {
+ findConversationActivationApi() {
+ return {
+ authoritative: true,
+ hasSession: () => Promise.resolve(false),
+ activate() {
+ activations++;
+ if (activations >= 2) activeId = 'copied-session';
+ return true;
+ },
+ };
+ },
+ },
+ document: {
+ querySelector() { return null; },
+ querySelectorAll() { return []; },
+ },
+ };
+ vm.runInNewContext(inject.slice(start, end), context);
+ context.openCopiedSession('copied-session');
+ await new Promise((resolve) => setTimeout(resolve, 3800));
+ assert.ok(activations >= 2, 'an unverified official dispatch must be confirmed and retried');
+ assert.equal(activeId, 'copied-session');
+ assert.ok(logs.some((line) => line.includes('official-dispatched-unverified')));
+ assert.ok(logs.some((line) => line.includes('not-confirmed')));
+ assert.ok(logs.some((line) => line.includes('confirmed')));
+});
+
+test('account switching does not auto-select a session by title after reload', () => {
+ const script = read('daemon.js');
+ assert.doesNotMatch(script, /autoFocusSessionByTitle/);
+ assert.doesNotMatch(script, /sourceSessionTitle/);
+ assert.doesNotMatch(script, /\[auto-focus\]/);
+});
+
test('WorkDaddy-triggered reload injects on the new main execution context before page load', () => {
const script = read('daemon.js');
- const reloadStart = script.indexOf('async function reloadWorkBuddyPage()');
- const reloadEnd = script.indexOf('\n// 切换账号后自动打开', reloadStart);
+ const reloadStart = script.indexOf('async function reloadWorkBuddyPage(');
+ const reloadEnd = script.indexOf('\nconst WORKBUDDY_TARGET', reloadStart);
const reload = script.slice(reloadStart, reloadEnd);
const eventsStart = script.indexOf('function onCdpEvent(method, params)');
const eventsEnd = script.indexOf('\nasync function cdpLoop()', eventsStart);
@@ -196,13 +323,13 @@ test('WorkDaddy-triggered reload injects on the new main execution context befor
const switchWrite = switchRoute.indexOf('switchTo(DATA_DIR, uid, log)');
assert.notEqual(switchWrite, -1);
assert.doesNotMatch(switchRoute.slice(0, switchWrite), /buildAutoCopyPlan\(/, 'session planning must not delay auth replacement and renderer reload');
- assert.ok(switchRoute.indexOf('await reloadWorkBuddyPage()') < switchRoute.indexOf('startAutoCopyJob('), 'widget readiness must precede the synchronous auto-copy queue');
+ assert.ok(switchRoute.indexOf('await reloadWorkBuddyPage({ waitForInjection: false })') < switchRoute.indexOf('startAutoCopyJob('), 'renderer reload must precede the background auto-copy queue');
const autoCopyStart = script.indexOf('function startAutoCopyJob(');
const autoCopyEnd = script.indexOf('\nfunction publicAutoCopyJob(', autoCopyStart);
const autoCopy = script.slice(autoCopyStart, autoCopyEnd);
- assert.ok((autoCopy.match(/await yieldAutoCopyToRenderer\(\)/g) || []).length >= 2, 'auto-copy must yield before planning and each synchronous file batch');
+ assert.ok((autoCopy.match(/await yieldAutoCopyToRenderer\([^)]*\)/g) || []).length >= 2, 'auto-copy must yield before planning and each synchronous file batch');
- const yieldStart = script.indexOf('async function yieldAutoCopyToRenderer()');
+ const yieldStart = script.indexOf('async function yieldAutoCopyToRenderer(');
const syncStart = script.indexOf('const MAX_SESSION_EXPORT_FILES', yieldStart);
const yieldHelper = script.slice(yieldStart, syncStart);
assert.match(yieldHelper, /setImmediate/);
@@ -882,7 +1009,10 @@ test('robot button decorations remain visible alongside the eye states', () => {
test('robot button defaults to the window bottom-right and snaps right after free dragging', () => {
const script = read('inject.js');
- assert.match(script, /FAB_POSITION_KEY = 'wbs-fab-bottom-' \+ PROFILE_ID/);
+ assert.match(script, /FAB_POSITION_KEY = 'wbs-fab-bottom-v2-' \+ PROFILE_ID/);
+ assert.match(script, /FAB_LEGACY_POSITION_KEY = 'wbs-fab-bottom-' \+ PROFILE_ID/);
+ assert.match(script, /raw !== null && raw !== '' && isFinite\(value\)/);
+ assert.match(script, /localStorage\.removeItem\(FAB_LEGACY_POSITION_KEY\)/);
assert.match(script, /setPointerCapture\(e\.pointerId\)/);
assert.match(script, /FAB_DRAG_THRESHOLD = 6/);
assert.match(script, /fabDrag\.startRight - deltaX/);
@@ -892,6 +1022,9 @@ test('robot button defaults to the window bottom-right and snaps right after fre
assert.match(script, /touchAction = 'none'/);
assert.match(script, /is-snapping/);
assert.match(script, /cubic-bezier\(\.22,1\.35,\.36,1\)/);
+ const pointerDown = script.slice(script.indexOf("listen(handle, 'pointerdown'"), script.indexOf("listen(handle, 'pointermove'"));
+ assert.match(pointerDown, /e\.stopPropagation\(\)/);
+ assert.doesNotMatch(pointerDown, /e\.preventDefault\(\)/);
assert.doesNotMatch(script, /homeComposerCorner|aiHomeComposerCorner|cb-message-queue\.cb-expand/);
});
@@ -999,6 +1132,30 @@ test('cached update metadata is rechecked against the running daemon version', (
assert.doesNotMatch(checkUpdate, /updateState\.hasUpdate = !!c\.hasUpdate/);
});
+test('update release selection uses the highest source version and a packaged asset as tie-breaker', () => {
+ const daemon = read('daemon.js');
+ const checkStart = daemon.indexOf('function checkUpdate(force)');
+ const downloadStart = daemon.indexOf('\nfunction downloadUpdate()', checkStart);
+ const checkUpdate = daemon.slice(checkStart, downloadStart);
+ assert.match(checkUpdate, /const attempts = order\.map/);
+ assert.match(checkUpdate, /return Promise\.all\(attempts\)/);
+ const start = daemon.indexOf('function semverCompare');
+ const end = daemon.indexOf('\n// 检查更新:', start);
+ assert.ok(start >= 0 && end > start);
+ const context = {};
+ vm.runInNewContext(daemon.slice(start, end) + '\nthis.selectBestUpdateCandidate = selectBestUpdateCandidate;', context);
+ const select = context.selectBestUpdateCandidate;
+ assert.equal(typeof select, 'function');
+ assert.equal(select([
+ { source: 'github', order: 0, latest: '1.2.4', asset: { name: 'WorkDaddy-1.2.4-win64.zip' } },
+ { source: 'gitee', order: 1, latest: '1.2.5', asset: { name: 'WorkDaddy-Setup-1.2.5.exe' } },
+ ]).source, 'gitee');
+ assert.equal(select([
+ { source: 'github', order: 0, latest: '1.2.5', asset: null },
+ { source: 'gitee', order: 1, latest: '1.2.5', asset: { name: 'WorkDaddy-Setup-1.2.5.exe' } },
+ ]).source, 'gitee');
+});
+
test('about page clears stale update UI when no newer version exists', () => {
const inject = read('inject.js');
const checkStart = inject.indexOf('function checkForUpdate()');
@@ -1155,12 +1312,25 @@ test('automatic session copy includes workspace-only rules when the initial plan
assert.match(daemon, /startAutoCopyJob\(sourceUid, uid, \[\]/);
assert.match(daemon, /copySessionRecord\(src, targetUid/);
assert.match(daemon, /sessionSync\.compareSnapshots\(left, right\)/);
- assert.match(daemon, /ensureAutoCopySessions\(DATA_DIR, source, lineageSessionIds, \{ enabled: !rules\.allSessions \}\)/);
+ assert.match(daemon, /ensureAutoCopySessions\(DATA_DIR, source, missingLineageIds, \{ enabled: !rules\.allSessions \}\)/);
assert.match(inject, /data-auto-kind="' \+ kind \+ '"/);
assert.match(inject, /autoCopyButton\('workspace'/);
assert.match(inject, /autoCopyButton\('session'/);
});
+test('automatic session copy filters clean sessions before target queries and snapshot work', () => {
+ const daemon = read('daemon.js');
+ const inject = read('inject.js');
+ assert.match(daemon, /const dirtyIndex = (?:getSessionDirtyIndex\(\)|typeof getSessionDirtyIndex === 'function'[\s\S]*?getSessionDirtyIndex\(\))[\s\S]*const dirtyRows = selectedRows\.filter\(\(\) => false\);[\s\S]*for \(const row of selectedRows\)[\s\S]*dirtyIndex\.shouldSync\(source, row\.id\)[\s\S]*mappingSourceRevisionMatches/);
+ assert.match(daemon, /const SESSION_DIRTY_FILE = (?:path\.join\(DATA_DIR, 'session-dirty\.json'\)|typeof DATA_DIR !== 'undefined'[\s\S]*?session-dirty\.json)/);
+ assert.match(daemon, /POST' && p === '\/api\/sessions\/dirty'/);
+ assert.match(daemon, /clearAutoDirty\(\);/);
+ assert.match(inject, /function sessionCopyIsNoop\(job\)/);
+ assert.match(inject, /if \(sessionCopyIsNoop\(job\)\) \{[\s\S]*closeSessionCopyNotice\(\);/);
+ assert.match(inject, /createSessionDirtyTracker\(function \(payload\)/);
+ assert.match(inject, /sessionDirtyTracker\.baseline\(records\)/);
+});
+
test('session copy-all is a separate override with a distinct toggle and hidden row controls', () => {
const daemon = read('daemon.js');
const inject = read('inject.js');
@@ -1190,6 +1360,18 @@ test('session copy-all is a separate override with a distinct toggle and hidden
assert.match(inject, /\.wbs-sess-summary-tag\{[^}]*border:0[^}]*background:transparent/);
});
+test('first panel open presents the session sync initialization modal once per profile', () => {
+ const inject = read('inject.js');
+ assert.match(inject, /WBS_INITIAL_AUTO_COPY_ALL_KEY = 'workdaddy\.initial\.autoCopyAllSessions\.' \+ PROFILE_ID/);
+ assert.match(inject, /function initialAutoCopyAllSeen\(\)[\s\S]*localStorage\.getItem\(WBS_INITIAL_AUTO_COPY_ALL_KEY\) === '1'/);
+ assert.match(inject, /function openInitialAutoCopyAllModal\(\)[\s\S]*id = 'wbs-initial-auto-copy-all-mask'/);
+ assert.match(inject, /切换账号自动同步所有会话[\s\S]*data-initial-auto-copy-all checked/);
+ assert.match(inject, /api\('\/api\/sessions\/auto-copy-all'[\s\S]*JSON\.stringify\(\{ enabled: enabled \}\)/);
+ assert.match(inject, /localStorage\.setItem\(WBS_INITIAL_AUTO_COPY_ALL_KEY, '1'\)/);
+ assert.match(inject, /newlyOpened && CAPS\.sessions\) setBuildTimeout\(function \(\) \{ if \(state\.open\) openInitialAutoCopyAllModal\(\); \}, 0\)/);
+ assert.match(inject, /\.wbs-initial-sync-modal\{[^}]*width:380px/);
+});
+
test('session auto-copy plans preserve physical source rows while list APIs deduplicate display', () => {
const daemon = read('daemon.js');
const lib = read('lib.js');
@@ -1204,13 +1386,16 @@ test('session pane restores and renders persistent auto-copy progress', () => {
const daemon = read('daemon.js');
const inject = read('inject.js');
assert.match(daemon, /GET' && p === '\/api\/sessions\/auto-copy\/active'/);
- assert.match(daemon, /function activeAutoCopyJob\(\)/);
+ assert.match(daemon, /function activeAutoCopyJob\(targetUid = ''\)/);
assert.match(inject, /id="wbs-sess-copy-progress"/);
assert.match(inject, /function renderSessionCopyProgress\(job\)/);
+ assert.match(inject, /if \(!active && job\.status !== 'error'\) \{ box\.hidden = true; return; \}/);
assert.match(inject, /\/api\/sessions\/auto-copy\/active/);
assert.match(inject, /aria-valuenow/);
assert.match(inject, /\.wbs-sess-copy-progress\{/);
assert.match(inject, /html\.cb-dark \.wbs-sess-copy-progress/);
+ assert.doesNotMatch(inject, /wbs-session-copy-count["']/);
+ assert.doesNotMatch(inject, /wbs-sess-copy-count["']/);
});
test('account switching shows a compact copy notice and defers conflict feedback until completion', () => {
@@ -1229,11 +1414,14 @@ test('account switching shows a compact copy notice and defers conflict feedback
assert.match(inject, /wbs-session-copy-notice/);
assert.match(inject, /function pollSessionCopyNotice\(jobId, accountName\)/);
assert.match(inject, /sessionCopySummaryText\(job\)/);
+ assert.match(inject, /return '同步 ' \+ \(Number\(job && job\.copied\) \|\| 0\) \+/);
+ assert.doesNotMatch(inject, /return '同步 ' \+ \(Number\(job && job\.copied\) \|\| 0\) \+ ' · 跳过 '/);
assert.match(inject, /会话同步完成,已保留分叉/);
assert.match(inject, /会话同步明细/);
assert.match(inject, /会话同步结果筛选/);
assert.match(inject, /正在同步已标记会话/);
- assert.match(inject, /setBuildTimeout\(closeSessionCopyNotice, 5000\)/);
+ assert.match(inject, /var countdownSeconds = copiedCount \|\| failedCount \? 5 : 3;/);
+ assert.match(inject, /setBuildTimeout\(closeSessionCopyNotice, countdownSeconds \* 1000\)/);
assert.match(inject, /sessionCopyNoticeChecked/);
assert.match(inject, /sessionCopyNoticeActiveAttempts < 10/);
assert.match(inject, /data-session-copy-details/);
@@ -1242,6 +1430,7 @@ test('account switching shows a compact copy notice and defers conflict feedback
assert.match(inject, /data-session-copy-tab/);
assert.match(inject, /wbs-session-copy-detail-tabs/);
assert.match(inject, /wbs-model-tabs wbs-session-copy-detail-tabs/);
+ assert.doesNotMatch(inject, /\{ id: 'skipped', label: '跳过'/);
assert.match(inject, /grid-template-rows:auto auto minmax\(0,1fr\) auto/);
assert.match(inject, /sourceLabel = sessionCopyAccountLabel/);
assert.match(inject, /\.wbs-session-copy-status'\)\.hidden = !active/);
@@ -1250,6 +1439,13 @@ test('account switching shows a compact copy notice and defers conflict feedback
assert.match(inject, /html\.cb-dark \.wbs-session-copy-notice/);
});
+test('new profiles initialize with the light theme without overwriting saved themes', () => {
+ const daemon = read('daemon.js');
+ assert.match(daemon, /if \(!fs\.existsSync\(curFile\)\) \{[\s\S]*JSON\.stringify\(\{ id: 'default'/);
+ assert.match(daemon, /首次初始化:默认主题 -> 浅色主题(default)/);
+ assert.doesNotMatch(daemon, /首次初始化:默认主题 -> WorkDaddy 壁纸主题(nebula)/);
+});
+
test('session conflict reset is retired and details stay at the left', () => {
const daemon = read('daemon.js');
const inject = read('inject.js');
diff --git a/test/windows-privilege-boundary.test.js b/test/windows-privilege-boundary.test.js
index dcd3045..de938d8 100644
--- a/test/windows-privilege-boundary.test.js
+++ b/test/windows-privilege-boundary.test.js
@@ -211,6 +211,32 @@ test('Windows installer stops the verified profile lifecycle before replacing or
assert.match(installerSource, /runtime\\node/);
});
+test('daemon continues to the verified force pass when graceful taskkill returns non-zero', async () => {
+ const start = daemonSource.indexOf('async function quitWorkBuddy()');
+ const end = daemonSource.indexOf('\nfunction relaunchWorkBuddy()', start);
+ assert.ok(start >= 0 && end > start);
+ const calls = [];
+ let waits = 0;
+ const process = { ProcessId: 701, CreationDate: 'one' };
+ const context = {
+ IS_WIN: true,
+ IS_LINUX: false,
+ resolveWorkBuddyBinary: () => 'C:\\WorkBuddy\\WorkBuddy.exe',
+ verifiedWindowsWorkBuddyProcesses: () => [process],
+ revalidateWindowsWorkBuddyProcess: value => value,
+ runCommand: async (_, args) => {
+ calls.push(args);
+ return args.includes('/F') ? { code: 0 } : { code: 1 };
+ },
+ waitForWorkBuddyExit: async () => ++waits > 1,
+ workBuddyRunning: () => false,
+ spawnSync() {}, WORKBUDDY_APP: '', WORKBUDDY_BINARY: '', linuxWorkBuddyPids: () => [], sleep: async () => {}, log() {},
+ };
+ require('node:vm').runInNewContext(daemonSource.slice(start, end), context);
+ assert.equal(await context.quitWorkBuddy(), true);
+ assert.deepEqual(calls.map(args => Array.from(args)), [['/PID', '701'], ['/F', '/PID', '701']]);
+});
+
test('PowerShell lifecycle scopes daemon discovery to a verified watchdog parent', () => {
const boundary = fs.readFileSync(path.join(scriptsDir, 'windows-process-boundary.ps1'), 'utf8');
const pidValidation = boundary.indexOf('$watchdog = Assert-NodeProcessIdentity');
diff --git a/test/workbuddy-compat.test.js b/test/workbuddy-compat.test.js
index ecc4959..3a6c76b 100644
--- a/test/workbuddy-compat.test.js
+++ b/test/workbuddy-compat.test.js
@@ -2,10 +2,12 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
+const os = require('node:os');
const path = require('node:path');
const test = require('node:test');
const compat = require('../scripts/workbuddy-compat.js');
+const lib = require('../scripts/lib.js');
function visibleElement(className) {
return {
@@ -55,6 +57,63 @@ test('queue adapter selection prefers prototype-capable modern adapter and retai
assert.deepEqual(compat.findQueueAdapter(legacyDocument), { kind: 'legacy', adapter: legacyAdapter });
});
+test('conversation activation exposes the official session lookup and jump event', async () => {
+ const emitted = [];
+ const modernAdapter = Object.create({
+ enqueueConversationMessageQueueItem() {},
+ pauseConversationMessageQueue() {},
+ emit(name, payload) { emitted.push({ name, payload }); },
+ });
+ modernAdapter.sessionsResource = {
+ on() {}, off() {},
+ getByIds(ids) { return Promise.resolve({ conversations: ids.map(id => ({ id })), missingIds: [] }); },
+ };
+ const modernRoot = visibleElement();
+ modernRoot.__reactFiber$test = { memoizedProps: { adapter: modernAdapter }, return: null };
+ const documentLike = { querySelector(selector) { return selector === '#root > div' ? modernRoot : null; } };
+
+ const activation = compat.findConversationActivationApi(documentLike);
+ assert.ok(activation);
+ assert.equal(await activation.hasSession('copied-session'), true);
+ activation.activate('copied-session');
+ assert.deepEqual(emitted, [{
+ name: 'jump-to-conversation',
+ payload: { source: 'tencent-docs', sessionId: 'copied-session', reason: 'already-active' },
+ }]);
+});
+
+test('conversation activation prefers the official React navigation handler', async () => {
+ const calls = [];
+ const navigate = async function handleConversationClick(id, cwd, skipLocalCheck, preserveListView, options) {
+ // The markers mirror WorkBuddy's current handler without depending on its
+ // minified component names.
+ function dismissHoverPeek() {}
+ function syncTaskRouteFromClick() {}
+ dismissHoverPeek();
+ syncTaskRouteFromClick();
+ calls.push([id, cwd, skipLocalCheck, preserveListView, options]);
+ };
+ const adapter = {
+ enqueueConversationMessageQueueItem() {},
+ pauseConversationMessageQueue() {},
+ emit() { throw new Error('legacy activation must not be used'); },
+ };
+ const root = visibleElement();
+ root.__reactFiber$test = {
+ memoizedProps: {},
+ memoizedState: { memoizedState: { current: navigate }, next: null },
+ return: null,
+ };
+ const documentLike = {
+ querySelector(selector) { return selector === '#root > div' ? root : null; },
+ };
+ const activation = compat.findConversationActivationApi(documentLike);
+ assert.ok(activation);
+ assert.equal(activation.activate('official-session'), true);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(calls, [['official-session', '', false, false, {}]]);
+});
+
test('selected conversation lookup is capability based rather than profile based', () => {
const selected = {
className: 'conversation-item',
@@ -70,6 +129,86 @@ test('selected conversation lookup is capability based rather than profile based
assert.equal(compat.getSelectedConversationId(documentLike), 'conversation-modern');
});
+test('account import accepts legacy plaintext and preserves encrypted token envelopes', () => {
+ const envelope = { $wbEncrypted: 1, envelope: 'opaque-envelope' };
+ const plaintext = {
+ account: { uid: 'legacy-user', nickname: 'Legacy' },
+ auth: { accessToken: 'legacy-access', refreshToken: 'legacy-refresh', domain: 'https://www.workbuddy.cn' },
+ };
+ const encrypted = {
+ account: { uid: 'encrypted-user', nickname: envelope },
+ auth: { accessToken: envelope, refreshToken: envelope, domain: 'https://www.workbuddy.cn' },
+ };
+
+ const plainResult = lib.normalizeAccountImportJson(plaintext);
+ assert.equal(plainResult.uid, 'legacy-user');
+ assert.equal(plainResult.normalized.auth.accessToken, 'legacy-access');
+
+ const encryptedResult = lib.normalizeAccountImportJson(encrypted);
+ assert.equal(encryptedResult.uid, 'encrypted-user');
+ assert.deepEqual(encryptedResult.normalized.auth.accessToken, envelope);
+ assert.deepEqual(encryptedResult.normalized.auth.refreshToken, envelope);
+ assert.deepEqual(encryptedResult.normalized.account.nickname, envelope);
+ assert.equal(lib.wdCompatAuthToken(encryptedResult.normalized.auth), '');
+ assert.equal(lib.wdCompatText(envelope), '(已加密)');
+});
+
+test('Windows encrypted-field key lookup honors the configured WorkBuddy target path', { skip: process.platform !== 'win32' }, () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-compat-target-'));
+ const previousProfile = process.env.WBSWITCH_PROFILE;
+ const previousDataDir = process.env.WBSWITCH_DATA_DIR;
+ const target = 'Z:\\custom-workbuddy\\WorkBuddy.exe';
+ try {
+ fs.writeFileSync(path.join(root, 'workbuddy-target.json'), JSON.stringify({
+ schemaVersion: 1,
+ clientType: 'official',
+ profileId: 'workbuddy-cn',
+ binary: target,
+ processNames: ['WorkBuddy.exe'],
+ cdp: { mode: 'argument', port: 9222 },
+ }));
+ process.env.WBSWITCH_PROFILE = 'workbuddy-cn';
+ process.env.WBSWITCH_DATA_DIR = root;
+ assert.equal(lib.wdCompatExeCandidates()[0], target);
+ } finally {
+ if (previousProfile === undefined) delete process.env.WBSWITCH_PROFILE;
+ else process.env.WBSWITCH_PROFILE = previousProfile;
+ if (previousDataDir === undefined) delete process.env.WBSWITCH_DATA_DIR;
+ else process.env.WBSWITCH_DATA_DIR = previousDataDir;
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('account backup keeps both legacy plaintext and encrypted source bytes unchanged', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-compat-'));
+ try {
+ const dataDir = path.join(root, 'WorkDaddy');
+ const authDir = path.join(root, 'auth');
+ fs.mkdirSync(authDir, { recursive: true });
+ lib.ensureDirs(dataDir);
+ const envelope = { $wbEncrypted: 1, envelope: 'opaque-envelope' };
+ const fixtures = [
+ {
+ uid: 'legacy-user',
+ value: { account: { uid: 'legacy-user', nickname: 'Legacy' }, auth: { accessToken: 'legacy-access', domain: 'https://www.workbuddy.cn' } },
+ },
+ {
+ uid: 'encrypted-user',
+ value: { account: { uid: 'encrypted-user', nickname: envelope }, auth: { accessToken: envelope, domain: 'https://www.workbuddy.cn' } },
+ },
+ ];
+ for (const fixture of fixtures) {
+ const source = path.join(authDir, fixture.uid + '.info');
+ const raw = JSON.stringify(fixture.value, null, 2);
+ fs.writeFileSync(source, raw);
+ lib.backupAuthFile(dataDir, source);
+ assert.equal(fs.readFileSync(lib.backupPath(dataDir, fixture.uid), 'utf8'), raw);
+ }
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
test('injected compatibility is packaged and AI theme access is no longer profile-gated', () => {
const root = path.join(__dirname, '..');
const daemon = fs.readFileSync(path.join(root, 'scripts', 'daemon.js'), 'utf8');