WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
feat: 合并 1.2.4 版本
[email protected]5adf96591515
diff --git a/AGENTS.md b/AGENTS.mdindex 100acd2..47c4230 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -14,6 +14,12 @@ The repository is deliberately lightweight:- `scripts/win-launcher.js`, `scripts/watchdog.js`, and the PowerShell/cmd scripts are the Windows startup/update path.- `WorkDaddy.app` is a packaged macOS artifact. Treat `scripts/` as the source of truth; update the app bundle only when the task explicitly asks for a packaged artifact or release output.+## Repository Hygiene++- Do not create one-off design QA screenshots, comparison images, `design-qa.md`, or ad hoc investigation/release notes in the repository root or `docs/` as a side effect of implementation or verification.+- Keep temporary screenshots, diagnostic notes, and generated comparison artifacts outside the repository (for example, in a task-specific temporary directory). Do not add them to Git.+- Add documentation or visual assets to the repository only when the user explicitly requests those deliverables or a shipped feature genuinely requires them. Reuse existing project documentation when possible and keep additions limited to the requested scope.+## Non-Negotiable Principles1. Diagnose the reported behavior against the current code before changing it. A historical report is evidence, not proof that the current version is broken.@@ -108,7 +114,7 @@ The queue item's 暂存提示词 tag is rendered by `syncQueueTags` (in `scripts- A release version must be identical in the package filename, macOS `Info.plist` (`CFBundleShortVersionString`/`CFBundleVersion`), and the packaged `scripts/daemon.js` `DAEMON_VERSION`. A package named `1.0.10` that runs daemon code reporting `1.0.6` is invalid.- Update availability has one source of truth: compare the latest GitHub or cached release version with the running `DAEMON_VERSION` every time. Never persist or trust a cached `hasUpdate` decision across daemon versions, and clear any existing update card/red dot when no newer version exists.- Build scripts must always rewrite the staged daemon version from the release `VERSION`; never rely on the version embedded in the reusable `WorkDaddy.app` shell or on a conditional test-only override.-- Windows releases are `Setup.exe` only. The `*-win64.zip` created by the installer pipeline is temporary staging and must be deleted before artifact upload or GitHub Release publication; ZIP remains supported only as an updater fallback for historical releases.+- Windows releases include two profile-specific `Setup.exe` files and two `*-Portable-<VERSION>.zip` files. The `*-win64.zip` inputs are temporary staging and must be removed before publication. Portable ZIPs use the native launcher, keep account data under `%APPDATA%\WorkDaddy`, and do not run the installer-style updater; historical ZIP updater compatibility remains unchanged for installed editions.- Before publishing or handing off a package, inspect the actual DMG/Setup.exe payload and record the daemon version, app metadata version, profile branding, and required update scripts. Do not infer package correctness from the filename alone.- The repair prompt `安装失败自主解决提示词.txt` may remain in the source tree for the user-initiated repair-agent flow, but it must not be copied into Windows Setup.exe payloads or macOS release staging directories. Release verification must confirm that the prompt is absent from the deliverable.- The updater must reject an artifact whose internal daemon version does not match the GitHub release target, and must leave a local diagnostic trail showing the selected asset, expected version, internal version, and installation attempt ID.@@ -117,7 +123,7 @@ The queue item's 暂存提示词 tag is rendered by `syncQueueTags` (in `scriptsUse this exact flow for a Windows release. The two client packages are built from the same source tree, but each is staged with its own profile, installation directory, daemon port, desktop shortcut, and WorkBuddy executable name.-1. Start from the requested source commit/branch and confirm the working tree. Do not silently change the release version in `scripts/daemon.js` when producing a fixed-version package; pass the requested version explicitly to the release script. Before building, remove only the existing `release/windows/*-Setup-*.exe` files if the request is to replace all installer artifacts; keep unrelated files outside that directory untouched.+1. Start from the requested source commit/branch and confirm the working tree. Do not silently change the release version in `scripts/daemon.js` when producing a fixed-version package; pass the requested version explicitly to the release script. Before building, remove only existing `release/windows/*-Setup-*.exe` and `release/windows/*-Portable-*.zip` files if the request is to replace all release artifacts; keep unrelated files outside that directory untouched.2. From the repository root, run the Windows release builder with Git Bash, Inno Setup 6, and Python available. Prefer explicit tool paths on the build host so the result is reproducible and does not depend on `PATH`:@@ -138,18 +144,20 @@ Use this exact flow for a Windows release. The two client packages are built froif ($p.ExitCode -ne 0) { throw "Windows build failed: $($p.ExitCode)" }```- `build-win-release.ps1` must build both `workbuddy-cn` and `workbuddy-ai`. `build-win-zip.sh` creates only an internal staging ZIP; `build-win-installer.ps1` rewrites the staged daemon version and build id to the requested release version before compiling Setup.exe. Do not hand-copy scripts into an old installer directory.+ `build-win-release.ps1` must build both `workbuddy-cn` and `workbuddy-ai`. `build-win-zip.sh` creates a staging ZIP; `build-win-installer.ps1` validates its version/profile, compiles Setup.exe, then renames it to the Portable ZIP. Do not hand-copy scripts into an old installer directory.3. Deliver only these files (replace `<VERSION>` with the requested release version):```textrelease/windows/WorkDaddy-Setup-<VERSION>.exerelease/windows/WorkDaddy-AI-Setup-<VERSION>.exe+ release/windows/WorkDaddy-Portable-<VERSION>.zip+ release/windows/WorkDaddy-AI-Portable-<VERSION>.zip```- Remove all generated `WorkDaddy-<VERSION>-win64.zip`, `WorkDaddy-AI-<VERSION>-win64.zip`, stale `release/windows/*-Setup-*.exe` files that are not part of this release, build logs, temporary verification directories, and `release/.cache` before handoff or publication. The ZIPs are staging inputs, not Windows release artifacts. Confirm that `安装失败自主解决提示词.txt` is absent from both Setup.exe payloads.+ Remove all generated `WorkDaddy-<VERSION>-win64.zip`, `WorkDaddy-AI-<VERSION>-win64.zip`, stale Setup/Portable artifacts from other versions, build logs, temporary verification directories, and `release/.cache` before handoff or publication. Only the `*-win64.zip` files are staging inputs. Confirm that `安装失败自主解决提示词.txt` is absent from all four payloads.-4. Inspect the actual Setup.exe payloads, not just their filenames. Run `innounp -t` on both files, list or extract them, and verify all of the following for each package:+4. Inspect the actual Setup.exe and Portable ZIP payloads, not just their filenames. Run `innounp -t` on both Setup files and extract both ZIPs; verify all of the following for each profile:- `scripts/runtime/node/node.exe` exists.- `scripts/daemon.js` reports the requested `<VERSION>`.@@ -157,6 +165,7 @@ Use this exact flow for a Windows release. The two client packages are built fro- CN uses `workbuddy-cn`, `47832`, `9222` as its defaults; AI uses `workbuddy-ai`, `47833`, `9223`.- The extracted `scripts/inject.js` keeps the platform placeholder unquoted (`var WBS_PLATFORM = __WBS_PLATFORM__;`) so daemon replacement with `JSON.stringify(process.platform)` produces the correct `"win32"` value. Confirm the Windows path contains the auto-open installer flow and does not enter the macOS reboot progress branch.- The package contains no `安装失败自主解决提示词.txt` and no temporary ZIP.+ - The ZIP root contains `WorkDaddy.portable`, `WorkDaddyLauncher.exe`, `Start-WorkDaddy.cmd`, and `Stop-WorkDaddy.cmd`, but no Install/Uninstall commands. The Setup payload contains no portable marker.5. Run release checks from the same repository:@@ -171,7 +180,7 @@ Use this exact flow for a Windows release. The two client packages are built froA skipped `sqlite3` CLI fallback test is expected on machines without the CLI. Windows runtime operation uses the bundled Node `node:sqlite` implementation and must not depend on a separately installed `sqlite3.exe`.-6. Smoke-test installation and startup in this order: install WorkDaddy AI first (including an elevated installer run), launch it; install WorkDaddy second with a normal installer run, launch it; then repeat normal and elevated shortcut launches for both profiles. Both clients must remain open simultaneously. If a previous install left a daemon/watchdog running, the installer may stop only the exact current-profile lifecycle after verifying script path, Node path, PID, owner, profile, port, and daemon status. It must never kill all `WorkBuddy.exe`/`Electron.exe` processes.+6. Smoke-test installation and startup in this order: install WorkDaddy AI first (including an elevated installer run), launch it; install WorkDaddy second with a normal installer run, launch it; then repeat normal and elevated shortcut launches for both profiles. Both clients must remain open simultaneously. Separately on a clean profile, extract each Portable ZIP, launch it with Start, stop it with Stop, then confirm manual replacement works without deleting account data. Do not run an installed and portable copy of the same profile simultaneously. If a previous install left a daemon/watchdog running, the installer may stop only the exact current-profile lifecycle after verifying script path, Node path, PID, owner, profile, port, and daemon status. It must never kill all `WorkBuddy.exe`/`Electron.exe` processes.7. When a PID file is missing during an install/update race, the launcher may reconstruct it only for one exact current-profile watchdog. Multiple matches, an unverified path, a foreign owner, an elevated target from a standard process, or an unbound daemon must fail closed with actionable logs. The old generic “请先完全退出 WorkBuddy” cold-start gate must not be used for a verified current-profile process; the launcher should restart that process precisely and wait for its expected CDP port.diff --git a/README.md b/README.mdindex 5d3bbf5..59e822b 100644--- a/README.md+++ b/README.md@@ -111,7 +111,7 @@ node scripts/workbuddy-target.js --configure --platform darwin \Linux 发布包面向 Ubuntu / Debian `amd64`。安装前请先安装并登录对应的 WorkBuddy 客户端;WorkDaddy 通过 CDP 连接客户端,不会替换或修改 WorkBuddy 本体。-1. 在 [Releases](../../releases) 下载 `WorkDaddy_x.y.z_amd64.deb`。+1. 在 [Releases](../../releases) 下载对应客户端的安装包:国内版是 `WorkDaddy_x.y.z_amd64.deb`,国际版是 `WorkDaddy-AI_x.y.z_amd64.deb`。2. 在下载目录执行:@@ -119,14 +119,26 @@ Linux 发布包面向 Ubuntu / Debian `amd64`。安装前请先安装并登录sudo apt install ./WorkDaddy_x.y.z_amd64.deb```+ 如果安装 WorkBuddy AI 国际版,请改用:++ ```bash+ sudo apt install ./WorkDaddy-AI_x.y.z_amd64.deb+ ```+3. 从应用菜单启动 **WorkDaddy**(国内版)或 **WorkDaddy AI**(国际版)。首次启动会准备本地数据目录并启动后台服务;随后按提示重启 WorkBuddy 以开启 CDP 面板。-安装包默认安装到 `/opt/workdaddy`,不默认设置开机自启。需要手动启动选择器时,可运行:+国内版安装到 `/opt/workdaddy`,国际版安装到 `/opt/workdaddy-ai`。两个包可以同时安装,互不覆盖;都不默认设置开机自启。需要手动启动选择器时,可运行:```bashbash /opt/workdaddy/scripts/launch-gui-linux.sh```+国际版对应路径为:++```bash+bash /opt/workdaddy-ai/scripts/launch-gui-linux.sh ai+```+如果系统没有应用菜单,也可以直接运行 `cn`、`ai`、`both` 或 `services` 参数选择启动方式:```bash@@ -146,6 +158,12 @@ WBSWITCH_PROFILE=workbuddy-ai bash /opt/workdaddy/scripts/systemd-install-linux.sudo apt remove workdaddy```+卸载国际版:++```bash+sudo apt remove workdaddy-ai+```+卸载软件包不会删除账号备份和运行数据;如需清理数据,请先确认对应的 `~/.config/WorkDaddy` 内容后再手动处理。#### 从源码安装 Linux 版本@@ -186,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`。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 发布 `WorkDaddy_<version>_amd64.deb` 和 `WorkDaddy-AI_<version>_amd64.deb`。macOS 构建时传 `WORKDADDY_BUILD_PROFILE=workbuddy-cn` 或 `workbuddy-ai` 可单独重打一个客户端。Windows 便携版 ZIP 与 Setup.exe 同源生成,顶层只有启动和停止入口。`install.sh` 做了:diff --git a/README_en.md b/README_en.mdindex 374431d..b4fe999 100644--- a/README_en.md+++ b/README_en.md@@ -108,7 +108,7 @@ WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.shPrompt 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 four packages for the two WorkBuddy clients: `WorkDaddy-<version>.dmg`, `WorkDaddy-AI-<version>.dmg`, `WorkDaddy-Setup-<version>.exe`, and `WorkDaddy-AI-Setup-<version>.exe`. 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>_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.`install.sh`:diff --git a/docs/images/linux/about-api-linux.png b/docs/images/linux/about-api-linux.pngdeleted file mode 100644index 45c2705..0000000Binary files a/docs/images/linux/about-api-linux.png and /dev/null differdiff --git a/docs/images/linux/status-workbuddy-ai.png b/docs/images/linux/status-workbuddy-ai.pngdeleted file mode 100644index e2f7890..0000000Binary files a/docs/images/linux/status-workbuddy-ai.png and /dev/null differdiff --git a/docs/images/linux/status-workbuddy-cn.png b/docs/images/linux/status-workbuddy-cn.pngdeleted file mode 100644index 67ee41b..0000000Binary files a/docs/images/linux/status-workbuddy-cn.png and /dev/null differdiff --git a/scripts/automation-discovery.js b/scripts/automation-discovery.jsindex 5deeb6d..be0c559 100644--- a/scripts/automation-discovery.js+++ b/scripts/automation-discovery.js@@ -6,6 +6,7 @@ const path = require('node:path');const { replaceFileWithRetry } = require('./atomic-file-write');const { previewPackage } = require('./automation-packages');const { SCHEMA_VERSION } = require('./automation');+const { stableVersion } = require('./automation-compatibility');const DISCOVERY_MARKER = 'WorkDaddyAutomationRepository';const CACHE_VERSION = 3;@@ -33,6 +34,15 @@ function documentIdentity(content) {return { document, key: crypto.createHash('sha256').update(canonical).digest('hex') };}+function comparePackageVersions(left, right) {+ const a = stableVersion(String(left));+ const b = stableVersion(String(right));+ for (let index = 0; index < 3; index += 1) {+ if (a[index] !== b[index]) return a[index] > b[index] ? 1 : -1;+ }+ return 0;+}+function emptyCache() {return { version: CACHE_VERSION, checkedAt: 0, refreshedAt: 0, providers: { github: [], gitee: [] }, repositories: {}, errors: [] };}@@ -260,13 +270,20 @@ function catalogFromState(state, runtime) {if (!preview.task) continue;const document = identity.document;const definition = document.kind ? document.task : document.task || document;- const item = merged.get(identity.key) || {+ const packageId = preview.package && String(preview.package.id || '') || '';+ const packageVersion = preview.package && String(preview.package.version || '') || '';+ const mergeKey = packageId ? 'package:' + packageId : 'document:' + identity.key;+ const existing = merged.get(mergeKey);+ if (existing && packageId && comparePackageVersions(packageVersion, existing.packageVersion) < 0) continue;+ if (existing && packageId && comparePackageVersions(packageVersion, existing.packageVersion) > 0) merged.delete(mergeKey);+ const item = merged.get(mergeKey) || {key: identity.key,name: String(document.name || preview.task.name || file.path).slice(0, 120),description: String(document.description || preview.task.description || '').slice(0, 1000),compatible: preview.compatible,issues: preview.issues || [],schemaVersion: definition.schemaVersion == null ? 1 : definition.schemaVersion,+ ...(packageId ? { packageId, packageVersion } : {}),stars: 0,sources: [],};@@ -281,7 +298,7 @@ function catalogFromState(state, runtime) {});item.stars += repository.stars;}- merged.set(identity.key, item);+ merged.set(mergeKey, item);} catch (_) {}}}@@ -347,8 +364,8 @@ function createAutomationDiscovery(options) {return publicCatalog();}- async function getCatalog() {- if (now() - Number(state.checkedAt || 0) < CACHE_TTL_MS) return publicCatalog();+ async function getCatalog(options = {}) {+ if (!options.force && now() - Number(state.checkedAt || 0) < CACHE_TTL_MS) return publicCatalog();if (!inFlight) inFlight = refresh().finally(() => { inFlight = null; });return inFlight;}@@ -369,6 +386,7 @@ function createAutomationDiscovery(options) {module.exports = {DISCOVERY_MARKER,CACHE_TTL_MS,+ comparePackageVersions,createAutomationDiscovery,documentIdentity,};diff --git a/scripts/automation-transfer.js b/scripts/automation-transfer.jsindex aa6bd23..45384a6 100644--- a/scripts/automation-transfer.js+++ b/scripts/automation-transfer.js@@ -65,15 +65,31 @@ function importTasks(dataDir, payload, runtime) {// Re-read, revalidate and write once, synchronously. Preview is not an authority// to overwrite tasks added/edited while the import dialog was open.const tasks = readAutomations(dataDir), preview = previewImport(payload, tasks, runtime);+ const replaceExisting = payload.replaceExisting === true;const selected = [...new Set(payload.selected)].map(key => {const entry = preview.entries.find(e => e.key === key);if (!entry || !entry.compatible) throw new Error('所选任务不兼容或文件已损坏');return entry;});- const added = selected.filter(e => !e.existing).map(e => e.task);+ const added = [];+ let replaced = 0;+ selected.forEach((entry) => {+ const packageId = entry.task && entry.task['x-workdaddy-import'] && entry.task['x-workdaddy-import'].packageId;+ const existingIndex = replaceExisting && packageId+ ? tasks.findIndex(task => task && task['x-workdaddy-import'] && task['x-workdaddy-import'].packageId === packageId)+ : -1;+ if (existingIndex >= 0) {+ // Keep the local runtime ID so existing run records and UI references remain valid.+ entry.task.id = tasks[existingIndex].id;+ tasks[existingIndex] = entry.task;+ replaced += 1;+ } else if (!entry.existing) {+ added.push(entry.task);+ }+ });if (added.length && tasks.length + added.length > MAX_TASKS) throw new Error('自动化任务数量已达到上限');- if (added.length) writeAutomations(dataDir, [...added, ...tasks]);- return { imported: added.length, skipped: selected.length - added.length, executed: false };+ if (added.length || replaced) writeAutomations(dataDir, [...added, ...tasks]);+ return { imported: added.length, replaced, skipped: selected.length - added.length - replaced, executed: false };}// These file endpoints use a bounded body reader instead of the legacy API reader.function readTransferBody(req) {diff --git a/scripts/build-linux-deb.sh b/scripts/build-linux-deb.shindex a8e3dfc..3dba608 100644--- a/scripts/build-linux-deb.sh+++ b/scripts/build-linux-deb.sh@@ -41,11 +41,10 @@ WS_ARCHIVE_NAME=ws-8.18.3.tgzWS_SHA256=424be604c8e7926fc29a1f067bf2dac256af3bcea62fe30395018bbaf8a9be2aTEMP="$(mktemp -d)"trap 'rm -rf -- "$TEMP"' EXIT-STAGE="$TEMP/stage"-SCRIPTS="$STAGE/opt/workdaddy/scripts"-mkdir -p "$SCRIPTS/runtime/node" "$SCRIPTS/node_modules/ws" "$SCRIPTS/assets" \- "$STAGE/DEBIAN" "$STAGE/usr/share/applications" \- "$STAGE/usr/share/icons/hicolor/1024x1024/apps" release/linux+COMMON="$TEMP/common"+COMMON_SCRIPTS="$COMMON/opt/workdaddy/scripts"+mkdir -p "$COMMON_SCRIPTS/runtime/node" "$COMMON_SCRIPTS/node_modules/ws" "$COMMON_SCRIPTS/assets" \+ "$COMMON/usr/share/icons/hicolor/1024x1024/apps" release/linuxfetch_archive() {local source="${1:-}" url="$2" expected="$3" output="$4"@@ -73,25 +72,25 @@ 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" "$SCRIPTS/runtime/node/node"-cp "$TEMP/node/node-v22.23.1-linux-x64/LICENSE" "$SCRIPTS/runtime/node/LICENSE"-chmod 755 "$SCRIPTS/runtime/node/node"-tar -xzf "$TEMP/$WS_ARCHIVE_NAME" -C "$SCRIPTS/node_modules/ws" --strip-components=1+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"+chmod 755 "$COMMON_SCRIPTS/runtime/node/node"+tar -xzf "$TEMP/$WS_ARCHIVE_NAME" -C "$COMMON_SCRIPTS/node_modules/ws" --strip-components=1# Explicit source list: no account data, macOS bundle, repair prompt, tests or staging archives.-cp scripts/*.js "$SCRIPTS/"-cp scripts/*-linux.sh "$SCRIPTS/"-cp -R scripts/builtin "$SCRIPTS/builtin"-cp -R scripts/builtin-overrides "$SCRIPTS/builtin-overrides"+cp scripts/*.js "$COMMON_SCRIPTS/"+cp scripts/*-linux.sh "$COMMON_SCRIPTS/"+cp -R scripts/builtin "$COMMON_SCRIPTS/builtin"+cp -R scripts/builtin-overrides "$COMMON_SCRIPTS/builtin-overrides"cp scripts/assets/workdaddy-logo.svg scripts/assets/workdaddy-app-icon-source.svg \- scripts/assets/workbuddy-buddy-mark.svg "$SCRIPTS/assets/"+ scripts/assets/workbuddy-buddy-mark.svg "$COMMON_SCRIPTS/assets/"cp scripts/assets/workdaddy-icon-foreground.png \- "$STAGE/usr/share/icons/hicolor/1024x1024/apps/workdaddy.png"-chmod 755 "$SCRIPTS/"*-linux.sh+ "$COMMON/usr/share/icons/hicolor/1024x1024/apps/workdaddy.png"+chmod 755 "$COMMON_SCRIPTS/"*-linux.sh-BUILD_NODE="$SCRIPTS/runtime/node/node"+BUILD_NODE="$COMMON_SCRIPTS/runtime/node/node"if [ "$CROSS_PACKAGE" = 1 ]; then BUILD_NODE="$(command -v node)"; fi-"$BUILD_NODE" - "$SCRIPTS/daemon.js" "$VERSION" <<'NODE'+"$BUILD_NODE" - "$COMMON_SCRIPTS/daemon.js" "$VERSION" <<'NODE'const fs = require('node:fs');const file = process.argv[2];const version = process.argv[3];@@ -106,44 +105,52 @@ for (const [field, value] of [}fs.writeFileSync(file, source);NODE-"$BUILD_NODE" --check "$SCRIPTS/daemon.js"-"$BUILD_NODE" -e "require(process.argv[1]); require('node:sqlite')" "$SCRIPTS/node_modules/ws"--cat > "$STAGE/DEBIAN/control" <<EOF-Package: workdaddy+"$BUILD_NODE" --check "$COMMON_SCRIPTS/daemon.js"+"$BUILD_NODE" -e "require(process.argv[1]); require('node:sqlite')" "$COMMON_SCRIPTS/node_modules/ws"++build_package() {+ local profile="$1" package_name="$2" install_root="$3" display_name="$4" output_name="$5"+ local stage="$TEMP/stage-$profile"+ local scripts="$stage$install_root/scripts"+ mkdir -p "$scripts" "$stage/DEBIAN" "$stage/usr/share/applications" \+ "$stage/usr/share/icons/hicolor/1024x1024/apps"+ cp -R "$COMMON/opt/workdaddy/scripts/." "$scripts/"+ cp "$COMMON/usr/share/icons/hicolor/1024x1024/apps/workdaddy.png" \+ "$stage/usr/share/icons/hicolor/1024x1024/apps/workdaddy-$profile.png"+ chmod 755 "$scripts/"*-linux.sh++ cat > "$stage/DEBIAN/control" <<EOF+Package: $package_nameVersion: $VERSIONSection: utilsPriority: optionalArchitecture: amd64Maintainer: WorkDaddy <[email protected]>Depends: libc6 (>= 2.28), libstdc++6, bash, curl, ca-certificates, procps, util-linux, xdg-utils, zenity-Description: WorkDaddy desktop enhancement for WorkBuddy- Local CDP integration for separately installed WorkBuddy CN and WorkBuddy AI.+Description: $display_name desktop enhancement for WorkBuddy+ Local CDP integration for the separately installed $display_name client.EOF-for profile in cn ai; do- if [ "$profile" = cn ]; then name=WorkDaddy; else name='WorkDaddy AI'; fi- cat > "$STAGE/usr/share/applications/workdaddy-$profile.desktop" <<EOF+ cat > "$stage/usr/share/applications/workdaddy-$profile.desktop" <<EOF[Desktop Entry]Type=Application-Name=$name-Exec=/opt/workdaddy/scripts/launch-gui-linux.sh $profile-TryExec=/opt/workdaddy/scripts/launch-gui-linux.sh-Icon=workdaddy+Name=$display_name+Exec=$install_root/scripts/launch-gui-linux.sh $profile+TryExec=$install_root/scripts/launch-gui-linux.sh+Icon=workdaddy-$profileTerminal=falseCategories=Utility;EOF-done-OUT="$ROOT/release/linux/WorkDaddy_${VERSION}_amd64.deb"-if [ "$CROSS_PACKAGE" = 1 ]; then- python3 - "$STAGE" "$OUT" "$VERSION" <<'PY'+ local out="$ROOT/release/linux/$output_name"+ if [ "$CROSS_PACKAGE" = 1 ]; then+ python3 - "$stage" "$out" "$VERSION" "$install_root" "$package_name" <<'PY'import pathlibimport sysimport tarfileimport tempfile-stage, output, version = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), sys.argv[3]+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]def add_entry(archive, path, name):info = archive.gettarinfo(str(path), name)@@ -195,32 +202,41 @@ with tempfile.TemporaryDirectory() as tmp:if version != next(line.split(': ', 1)[1] for line in (stage / 'DEBIAN/control').read_text().splitlines() if line.startswith('Version: ')):raise SystemExit('Debian metadata version mismatch')+ if package_name != next(line.split(': ', 1)[1] for line in (stage / 'DEBIAN/control').read_text().splitlines() if line.startswith('Package: ')):+ raise SystemExit('Debian metadata package mismatch')with tarfile.open(data, 'r:xz') as archive:names = archive.getnames()- for required in ('./opt/workdaddy/scripts/runtime/node/node', './opt/workdaddy/scripts/daemon.js'):+ prefix = './' + install_root.lstrip('/') + '/scripts/'+ for required in (prefix + 'runtime/node/node', prefix + 'daemon.js'):if required not in names:raise SystemExit(f'Missing payload file: {required}')if any('安装失败自主解决提示词' in name or name.endswith('.zip') for name in names):raise SystemExit('Forbidden payload file')- daemon = archive.extractfile('./opt/workdaddy/scripts/daemon.js').read().decode()- node = archive.extractfile('./opt/workdaddy/scripts/runtime/node/node').read(5)+ 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')PY-else- dpkg-deb --build --root-owner-group "$STAGE" "$OUT"- test "$(dpkg-deb --field "$OUT" Version)" = "$VERSION"- dpkg-deb --contents "$OUT" > "$TEMP/manifest"- grep -q '/opt/workdaddy/scripts/runtime/node/node$' "$TEMP/manifest"- grep -q '/opt/workdaddy/scripts/daemon.js$' "$TEMP/manifest"- if grep -q '安装失败自主解决提示词\|\.zip$' "$TEMP/manifest"; then- echo '发行包包含禁止交付的文件' >&2- exit 2+ else+ dpkg-deb --build --root-owner-group "$stage" "$out"+ test "$(dpkg-deb --field "$out" Version)" = "$VERSION"+ test "$(dpkg-deb --field "$out" Package)" = "$package_name"+ dpkg-deb --contents "$out" > "$TEMP/manifest-$profile"+ grep -q "$install_root/scripts/runtime/node/node$" "$TEMP/manifest-$profile"+ grep -q "$install_root/scripts/daemon.js$" "$TEMP/manifest-$profile"+ if grep -q '安装失败自主解决提示词\|\.zip$' "$TEMP/manifest-$profile"; then+ echo '发行包包含禁止交付的文件' >&2+ exit 2+ fi+ local verify="$TEMP/verify-$profile"+ 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"fi- mkdir -p "$TEMP/verify"- dpkg-deb --extract "$OUT" "$TEMP/verify"- grep -qx "const DAEMON_VERSION = '$VERSION';" "$TEMP/verify/opt/workdaddy/scripts/daemon.js"- "$TEMP/verify/opt/workdaddy/scripts/runtime/node/node" --check \- "$TEMP/verify/opt/workdaddy/scripts/daemon.js"-fi-echo "Linux 安装包: $OUT"+ 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"diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex 0368b65..0845ddb 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 completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-zip.js automation.js automation-picker.js token-refresh.js session-db.js session-fork.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 completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.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[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"done# Injection reads the wordmark at runtime; keep brand assets in both profiles.@@ -97,6 +97,7 @@ chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \"$APP/Contents/Resources/scripts/secure-transfer.js" \"$APP/Contents/Resources/scripts/session-transfer.js" \"$APP/Contents/Resources/scripts/session-fork.js" \+ "$APP/Contents/Resources/scripts/session-sync.js" \"$APP/Contents/Resources/scripts/windows-process-boundary.js" \"$APP/Contents/Resources/scripts/credit-request-usage.js" \"$APP/Contents/Resources/scripts/credit-history-sync.js" \diff --git a/scripts/daemon.js b/scripts/daemon.jsindex ef9686c..aced2b8 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -28,6 +28,7 @@ const path = require('path');const os = require('os');const crypto = require('crypto');const net = require('net');+const sessionSync = require('./session-sync.js');const { spawn, spawnSync } = require('child_process');const {assertSameProcessIdentity,@@ -91,7 +92,6 @@ const {getAutoCopySession,getAutoCopySessionMembers,getAutoCopySessionMemberRecords,- selectLatestAutoCopyMember,ensureAutoCopySessions,ensureAutoCopySession,normalizeAutoCopyLineages,@@ -376,8 +376,8 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 1.2.52:成长任务支持在悬浮层内直接接取,并在完成后同步最新任务状态。// 1.2.55:成长弹窗支持开启盲盒与抽奖并提示奖励,收敛成长/用量统计 primary 色使用。// 1.2.56:成长任务补齐说明与标签、已领取折叠、Buddy 派出,并把用量柱状图改为面积折线图。-const DAEMON_VERSION = '1.2.76';-const DAEMON_BUILD_ID = 'release-1.2.76-20260919-session-fork-stream-alignment-fix';+const DAEMON_VERSION = '1.2.83';+const DAEMON_BUILD_ID = 'release-1.2.83-20260919-switch-without-session-activity-gate';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -3180,6 +3180,26 @@ async function automationNotifyToast(detail) {if (response.exceptionDetails || !response.result || !response.result.value || !response.result.value.ok) throw new Error('WorkBuddy 通知组件未就绪');return response.result.value;}+let accountSwitchInProgress = false;+async function assertSessionSyncIdle() {+ if (PROFILE.kind !== 'workbuddy') return;+ if (!cdp.connected) throw new Error('无法确认会话状态,请连接 WorkBuddy 后重试');+ const result = await cdpSend('Runtime.evaluate', {+ expression: "typeof window.__wbsAnySessionBusy === 'function' ? window.__wbsAnySessionBusy() : null",+ returnByValue: true,+ });+ const busy = result && result.result && result.result.value;+ if (result.exceptionDetails || typeof busy !== 'boolean') throw new Error('无法确认会话状态,请等待面板加载后重试');+ if (busy) throw new Error('当前账号有会话仍在运行,请等待完成或停止后再同步');+}++async function assertAccountSwitchIdle() {+ if (accountSwitchInProgress) throw new Error('账号正在切换,请稍后重试');+ if (autoCopyWorkerRunning || autoCopyQueue.length || sessionCopyLocks.size) throw new Error('会话同步尚未完成,请稍后切换账号');+ accountSwitchInProgress = true;+ return () => { accountSwitchInProgress = false; };+}+let automationAccountSwitchTail = Promise.resolve();function automationSwitchAccount(account) {const target = account && typeof account === 'object' ? account : { uid: String(account || '').trim() };@@ -3188,6 +3208,7 @@ function automationSwitchAccount(account) {if (!uid) throw new Error('账号切换缺少 uid');const active = currentAccount();if (active && active.uid === uid) return { ok: true, uid, switched: false };+ const releaseAccountSwitch = await assertAccountSwitchIdle();const releaseRendererReload = beginRendererReloadPriority();try {const acct = switchTo(DATA_DIR, uid, log);@@ -3198,12 +3219,18 @@ function automationSwitchAccount(account) {pendingAutomationAccountSwitch = null;dispatchAutomationEvent('pageReady', { navigationSerial: mainFrameNavigationSerial, source: 'automation-account-switch', account: switchEvent.account });}+ const sourceUid = String(active && active.uid || '');+ const rules = sourceUid ? getAutoCopyRules(DATA_DIR, sourceUid) : {};+ if (rules.allSessions || (rules.sessionIds || []).length || (rules.workspaces || []).length) {+ startAutoCopyJob(sourceUid, uid, [], { sourceName: active.nickname, targetName: acct.nickname });+ }return { ok: true, uid: acct.uid, nickname: acct.nickname, switched: true };} catch (error) {pendingAutomationAccountSwitch = null;throw error;} finally {releaseRendererReload();+ releaseAccountSwitch();}});automationAccountSwitchTail = run.catch(() => {});@@ -4075,9 +4102,7 @@ function sessionContentMtime(wbHome, sessionId) {return latest;}-// Reconcile every live member of a shared lineage. A switch can arrive after-// either account has received new messages, so the active account is not a-// reliable source of truth; choose the freshest on-disk snapshot first.+// Yield between session pairs so renderer reloads and UI events can complete.async function yieldAutoCopyToRenderer() {await new Promise((resolve) => setImmediate(resolve));const reloadPriority = rendererReloadPriorityPromise;@@ -4086,93 +4111,6 @@ async function yieldAutoCopyToRenderer() {if (pending && !pending.settled) await pending.ready;}-async function syncAutoCopyLineage(lineageId, targetUid) {- if (!lineageId || PROFILE.kind !== 'workbuddy') return { members: 0, synced: 0, failedFiles: 0, targetIds: [], targetPresent: false };- const records = getAutoCopySessionMemberRecords(DATA_DIR, lineageId);- if (!records.length) return { members: 0, synced: 0, failedFiles: 0, targetIds: [], targetPresent: false };- const targetMapping = typeof getAutoCopyMapping === 'function'- ? getAutoCopyMapping(DATA_DIR, lineageId, targetUid)- : null;- const baselineAt = Number(targetMapping && targetMapping.updatedAt) || 0;- const live = [];- for (const member of records) {- await yieldAutoCopyToRenderer();- const rows = await sqliteQuery(- 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id = ? AND user_id = ? AND deleted_at IS NULL LIMIT 1;',- [member.id, member.uid]- );- if (!rows.length) continue;- live.push(Object.assign({}, member, {- row: rows[0],- contentMtime: sessionContentMtime(PROFILE.dataRoot, member.id),- updatedAt: Number(rows[0].updated_at || rows[0].last_activity_at || rows[0].created_at || 0),- }));- }- const targetIds = live.map((member) => member.id);- const targetPresent = targetUid === undefined || live.some((member) => member.uid === String(targetUid || '').trim());- if (live.length < 2) return { members: live.length, synced: 0, failedFiles: 0, targetIds, targetPresent };- // Once a lineage has been synchronized, a changed file on each side means- // both accounts wrote new content since the last common snapshot. Do not- // pick one side by mtime and silently overwrite the other; surface a- // conflict for the user after the progress bar completes.- const changedSinceBaseline = baselineAt > 0- ? live.filter((member) => Number(member.contentMtime || 0) > baselineAt)- : [];- if (changedSinceBaseline.length >= 2) {- return {- members: live.length,- synced: 0,- failedFiles: 0,- targetIds,- targetPresent,- conflict: true,- conflicts: 1,- };- }- // The lineage already has the target member and neither side changed since- // the last successful sync. Avoid a full overwrite of an unchanged session.- if (targetPresent && baselineAt > 0 && changedSinceBaseline.length === 0) {- return { members: live.length, synced: 0, failedFiles: 0, targetIds, targetPresent, unchanged: true };- }- const latest = selectLatestAutoCopyMember(live);- if (!latest) return { members: live.length, synced: 0, failedFiles: 0, targetIds, targetPresent };- const sourceRow = latest.row;- let synced = 0;- const ownerIds = records.map((member) => member.id);- // 旧版副本可能仍挂着最初源会话的 owner;也修复作为最新来源的副本自身。- const repairedSource = await copySessionFiles(PROFILE.dataRoot, latest.id, latest.id, ownerIds);- let failedFiles = repairedSource.failed;- for (const target of live) {- if (target.id === latest.id) continue;- await yieldAutoCopyToRenderer();- const files = await copySessionFiles(PROFILE.dataRoot, latest.id, target.id, ownerIds);- synced++;- failedFiles += files.failed;- try {- await sqliteRun(- 'UPDATE sessions SET title = ?, custom_title = ?, status = ?, updated_at = ?, last_activity_at = ? WHERE id = ? AND user_id = ? AND deleted_at IS NULL;',- [sourceRow.title || '', sourceRow.custom_title || '', sourceRow.status || 'Pending',- Number(sourceRow.updated_at || Date.now()), Number(sourceRow.last_activity_at || sourceRow.updated_at || Date.now()),- target.id, target.uid]- );- } catch (error) {- log(`[sessions-auto-copy] 同步会话元数据失败 ${target.uid}/${target.id}: ${error.message}`);- }- }- if (!failedFiles && targetUid !== undefined && typeof setAutoCopyMapping === 'function') {- const targetMember = live.find((member) => member.uid === String(targetUid || '').trim());- if (targetMember) {- setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {- ...(targetMapping || {}),- targetId: targetMember.id,- status: 'copied',- failedFiles: 0,- });- }- }- return { members: live.length, synced, failedFiles, sourceId: latest.id, targetIds, targetPresent };-}-const MAX_SESSION_EXPORT_FILES = 20000;const MAX_SESSION_IMPORT_ERRORS = 20;const MAX_SESSION_IMPORT_ERROR_LENGTH = 240;@@ -4438,128 +4376,102 @@ async function importSessionArchives(payload, targetUid, staged = false) {async function copySessionRecord(src, targetUid, options = {}) {const sourceUid = String(options.sourceUid || src.user_id || '').trim();- const auto = !!options.auto;- const wbHome = PROFILE.dataRoot;- let lineageId = options.lineageId || null;- const sourceLineage = sourceUid ? getAutoCopySession(DATA_DIR, sourceUid, src.id) : { lineageId: null, enabled: false };- if (!lineageId && sourceLineage.enabled) lineageId = sourceLineage.lineageId;- if (auto && sourceUid && !lineageId) lineageId = ensureAutoCopySession(DATA_DIR, sourceUid, src.id);+ targetUid = String(targetUid || '').trim();+ if (!sourceUid || !targetUid || sourceUid === targetUid) return { status: 'skipped', sourceId: src.id, targetId: src.id };+ // 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 });const perform = async () => {- let ownerIds = lineageId ? getAutoCopySessionMemberRecords(DATA_DIR, lineageId).map((member) => member.id) : [];- if (sourceUid && lineageId) {+ await yieldAutoCopyToRenderer();+ const readRow = async (id, uid) => (await sqliteQuery(+ 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id = ? AND user_id = ? AND deleted_at IS NULL LIMIT 1;', [id, uid]+ ))[0];+ const sourceRow = await readRow(src.id, sourceUid);+ if (!sourceRow) throw new Error('源会话已变化,请重试');const mapping = getAutoCopyMapping(DATA_DIR, lineageId, targetUid);- if (mapping && mapping.targetId) {- const existing = await sqliteQuery(- 'SELECT id, user_id FROM sessions WHERE id = ? AND deleted_at IS NULL LIMIT 1;',- [mapping.targetId]- );- if (existing.length && String(existing[0].user_id || '') === String(targetUid)) {- const files = await copySessionFiles(wbHome, src.id, mapping.targetId, ownerIds);- addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, mapping.targetId);- setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {- targetId: mapping.targetId,- status: files.failed ? 'partial' : 'copied',- failedFiles: files.failed,- });- return { status: files.failed ? 'partial' : 'skipped', sourceId: src.id, targetId: mapping.targetId, failedFiles: files.failed };- }- deleteAutoCopyMapping(DATA_DIR, lineageId, targetUid);- }-- // A stale/missing mapping used to cause a fresh INSERT even when this- // lineage already contained a target session. That produced one duplicate- // session on every account switch after the mapping was lost. Treat the- // lineage members as the authoritative fallback and choose a stable- // canonical row when old data contains more than one member for the uid.- const memberIds = getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid)- .filter((id) => String(id) !== String(src.id));- if (memberIds.length) {- const candidates = [];- for (let index = 0; index < memberIds.length; index++) {- const rows = await sqliteQuery(- 'SELECT id, user_id, created_at, updated_at FROM sessions WHERE id = ? AND deleted_at IS NULL LIMIT 1;',- [memberIds[index]]- );- if (rows.length && String(rows[0].user_id || '') === String(targetUid)) {- candidates.push(Object.assign({ memberIndex: index }, rows[0]));+ const ids = new Set(getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid));+ if (mapping && mapping.targetId) ids.add(mapping.targetId);+ const candidates = [];+ for (const id of ids) {+ const row = await readRow(id, targetUid);+ if (row) candidates.push(row);+ }+ const targetIds = candidates.length ? candidates.map(row => row.id) : [crypto.randomUUID()];+ const aliases = getAutoCopySessionMemberRecords(DATA_DIR, lineageId).map(member => member.id).concat(targetIds);+ let left = sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases);+ const selection = await sessionSync.selectTargetSnapshot(left, targetIds, async id => {+ await yieldAutoCopyToRenderer();+ return sessionSync.readSnapshot(PROFILE.dataRoot, id, aliases);+ }, 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+ // content and do not create another copy on every switch.+ const branched = selection.comparison.kind === 'conflict';+ const targetId = branched ? crypto.randomUUID() : selection.targetId;+ if (branched) aliases.push(targetId);+ const existing = candidates.find(row => row.id === targetId) || null;+ let right = sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases);+ // Selection may have yielded while inspecting other legacy copies.+ // Require the chosen complete snapshot to remain the same before writing.+ if (!branched && selection.snapshot.records && sessionSync.compareSnapshots(selection.snapshot, right).kind !== 'equal') {+ throw new Error('会话记录正在变化,请稍后重试');+ }+ const comparison = sessionSync.compareSnapshots(left, right);+ if (comparison.kind === 'conflict') throw new Error('会话记录正在变化,请稍后重试');+ let changed = false;+ const update = async (from, to, fromRow, toRow, missingOnly = false) => {+ await yieldAutoCopyToRenderer();+ const verifyRows = async () => {+ await assertSessionSyncIdle();+ 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('会话记录正在变化,请稍后重试');}- }- candidates.sort((a, b) => {- const created = Number(a.created_at || 0) - Number(b.created_at || 0);- if (created) return created;- const updated = Number(a.updated_at || 0) - Number(b.updated_at || 0);- if (updated) return updated;- return a.memberIndex - b.memberIndex;- });- if (candidates.length) {- const canonicalId = candidates[0].id;- const files = await copySessionFiles(wbHome, src.id, canonicalId, ownerIds);- addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, canonicalId);- setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {- targetId: canonicalId,- status: files.failed ? 'partial' : 'copied',- failedFiles: files.failed,- });- return { status: files.failed ? 'partial' : 'skipped', sourceId: src.id, targetId: canonicalId, failedFiles: files.failed };- }- }- }-- // Older metadata can lose or split the target member registration. Copies- // retain the source creation time and workspace, so adopt the existing row- // and repair its lineage before considering a new INSERT.- if (lineageId && src && Number(src.created_at || 0)) {- const candidates = await sqliteQuery(- 'SELECT id, cwd, updated_at FROM sessions WHERE user_id = ? AND created_at = ? AND deleted_at IS NULL ORDER BY updated_at, id LIMIT 6;',- [targetUid, Number(src.created_at)]- );- const sourceWorkspace = canonicalWorkspace(src.cwd);- const targetRules = getAutoCopyRules(DATA_DIR, targetUid);- const adopted = candidates.find((row) => String(row.id || '') !== String(src.id)- && canonicalWorkspace(row.cwd) === sourceWorkspace);- if (adopted) {- const adoptedId = String(adopted.id);- const otherLineageId = String((targetRules.allLineages || {})[adoptedId] || '').trim();- if (otherLineageId && otherLineageId !== lineageId) {- const merged = mergeAutoCopyLineages(DATA_DIR, lineageId, otherLineageId);- if (merged.ok) lineageId = otherLineageId;- }- ownerIds = getAutoCopySessionMemberRecords(DATA_DIR, lineageId).map((member) => member.id);- const files = await copySessionFiles(wbHome, src.id, adoptedId, ownerIds);- addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, adoptedId);- setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {- targetId: adoptedId,- status: files.failed ? 'partial' : 'copied',- failedFiles: files.failed,+ };+ 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(+ '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]+ );+ },});- log(`[sessions-auto-copy] 已认领目标账号中的同源会话 ${adoptedId.slice(0, 8)},未新建重复副本`);- return { status: files.failed ? 'partial' : 'skipped', sourceId: src.id, targetId: adoptedId, failedFiles: files.failed };- }- }-- const newId = crypto.randomUUID();- await insertCopiedSession(src, targetUid, newId);- const files = await copySessionFiles(wbHome, src.id, newId, ownerIds);- if (lineageId) {- addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, newId);- setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {- targetId: newId,- status: files.failed ? 'partial' : 'copied',- failedFiles: files.failed,- });- }- return { status: files.failed ? 'partial' : 'copied', sourceId: src.id, targetId: newId, failedFiles: files.failed };+ changed = true;+ };+ if (comparison.kind === 'left-extends') await update(left, right, sourceRow, existing);+ else if (comparison.kind === 'right-extends') await update(right, left, existing, sourceRow);+ else if (comparison.kind === 'repair') {+ 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);+ right = sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases);+ 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 });+ return { status: changed ? 'copied' : 'skipped', sourceId: src.id, targetId, branched: branched && changed, failedFiles: 0 };};- if (!lineageId) return perform();- const lockKey = JSON.stringify([lineageId, String(targetUid || '')]);+ // One lineage lock also serializes manual copy and reverse-direction updates.+ const lockKey = lineageId;const previous = sessionCopyLocks.get(lockKey) || Promise.resolve();const current = previous.catch(() => {}).then(perform);sessionCopyLocks.set(lockKey, current);- try {- return await current;- } finally {- if (sessionCopyLocks.get(lockKey) === current) sessionCopyLocks.delete(lockKey);- }+ try { return await current; }+ finally { if (sessionCopyLocks.get(lockKey) === current) sessionCopyLocks.delete(lockKey); }}async function buildAutoCopyPlan(sourceUid, targetUid) {@@ -4575,8 +4487,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid) {[source]);const workspaceSet = new Set(rules.workspaces.map(canonicalWorkspace));- const selectedRows = dedupeAutoCopySessionRows(rows, { [source]: rules.allLineages })- .filter((row) => isAutoCopySessionSelected(rules, row));+ const selectedRows = rows.filter((row) => isAutoCopySessionSelected(rules, row));// Full-copy and workspace matches need stable hidden lineages for idempotent// repeated switches. Prepare the whole batch with one metadata write.const lineageSessionIds = selectedRows@@ -4698,37 +4609,11 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {};await yieldAutoCopyToRenderer();try {- let result;- if (src.lineageId) {- // If the target already belongs to this lineage, reconcile all- // members before/after the switch instead of blindly overwriting it- // from the account that happened to be active most recently.- const synced = await syncAutoCopyLineage(src.lineageId, targetUid);- if (synced.conflict) {- result = { status: 'conflict', conflicts: synced.conflicts || 1, failedFiles: 0 };- } else if (synced.targetPresent) {- result = {- status: synced.failedFiles ? 'partial' : (synced.synced ? 'copied' : 'skipped'),- failedFiles: synced.failedFiles,- };- } else {- result = await copySessionRecord(src, targetUid, {- sourceUid,- lineageId: src.lineageId,- auto: true,- });- const synced = await syncAutoCopyLineage(src.lineageId, targetUid);- if (synced.conflict) result.status = 'conflict';- result.conflicts = synced.conflicts || 0;- result.failedFiles = (result.failedFiles || 0) + synced.failedFiles;- if (synced.failedFiles) result.status = 'partial';- }- } else {- result = await copySessionRecord(src, targetUid, { sourceUid, auto: true });- }+ 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.failedFiles = Number(result.failedFiles) || 0;detail.conflicts = Number(result.conflicts) || 0;if (result.status === 'skipped') job.skipped++;@@ -7316,7 +7201,7 @@ function handleApi(req, res) {}if (req.method === 'GET' && p === '/api/automations/discovery') {- return automationDiscovery.getCatalog()+ return automationDiscovery.getCatalog({ force: url.searchParams.get('refresh') === '1' }).then(result => json(res, 200, { ok: true, ...result })).catch(error => json(res, 503, { ok: false, error: error.message || '公开任务加载失败' }));}@@ -7325,7 +7210,7 @@ function handleApi(req, res) {return readBody(req).then((body) => {const content = automationDiscovery.getTaskContent(body && body.key);const runtime = { version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform };- return importTasks(DATA_DIR, { content, selected: ['0'] }, runtime);+ return importTasks(DATA_DIR, { content, selected: ['0'], replaceExisting: body && body.replaceExisting === true }, runtime);}).then(result => json(res, 200, { ok: true, ...result })).catch(error => json(res, 400, { ok: false, error: error.message }));}@@ -7902,6 +7787,30 @@ function handleApi(req, res) {});}+ // The official check-in endpoint is idempotent and reports "already+ // checked in" for a check-in completed outside WorkDaddy. Reconcile only+ // the currently logged-in account when the panel asks for a fresh account+ // snapshot; this keeps the optional all-account automation opt-in.+ if (req.method === 'POST' && p === '/api/accounts/checkin-sync') {+ return readBody(req).then(async (body) => {+ try {+ if (!PROFILE.capabilities.accounts || PROFILE.capabilities.checkin === false) {+ return json(res, 400, { ok: false, error: '当前客户端不支持账号签到' });+ }+ const current = currentAccount();+ const requestedUid = String(body && body.uid || '').trim();+ const uid = requestedUid || String(current && current.uid || '').trim();+ if (!uid || (current && requestedUid && requestedUid !== String(current.uid || ''))) {+ return json(res, 400, { ok: false, error: '签到状态同步仅支持当前账号' });+ }+ const result = await claimDailyForUid(uid);+ return json(res, 200, { ok: true, result });+ } catch (error) {+ return json(res, 400, { ok: false, error: error.message });+ }+ });+ }+if (req.method === 'GET' && p === '/api/accounts') {const accounts = listAccounts(DATA_DIR);const cache = loadCheckinCache();@@ -8532,11 +8441,11 @@ function handleApi(req, res) {const owner = String(row.user_id || '').trim();if (!owner || rulesByUid[owner]) return;const rules = getAutoCopyRules(DATA_DIR, owner);- rulesByUid[owner] = { allSessions: rules.allSessions, sessions: new Set(rules.sessionIds), workspaces: new Set(rules.workspaces), lineages: rules.allLineages };+ rulesByUid[owner] = { allSessions: rules.allSessions, sessions: new Set(rules.sessionIds), workspaces: new Set(rules.workspaces), lineages: rules.allLineages, branches: new Set(rules.branchSessionIds || []) };});- const lineagesByUid = {};- Object.keys(rulesByUid).forEach((owner) => { lineagesByUid[owner] = rulesByUid[owner].lineages; });- const sessions = dedupeAutoCopySessionRows(rows, lineagesByUid).map((row) => {+ const lineagesByUid = {}, branchesByUid = {};+ Object.keys(rulesByUid).forEach((owner) => { lineagesByUid[owner] = rulesByUid[owner].lineages; branchesByUid[owner] = rulesByUid[owner].branches; });+ const sessions = dedupeAutoCopySessionRows(rows, lineagesByUid, branchesByUid).map((row) => {const rules = rulesByUid[String(row.user_id || '').trim()] || { sessions: new Set(), workspaces: new Set() };return Object.assign({}, row, {autoCopySession: rules.sessions.has(String(row.id)),@@ -8546,7 +8455,7 @@ function handleApi(req, res) {const currentRules = uid? (rulesByUid[uid] || (() => {const rules = getAutoCopyRules(DATA_DIR, uid);- return { allSessions: rules.allSessions, sessions: new Set(rules.sessionIds), workspaces: new Set(rules.workspaces), lineages: rules.allLineages };+ return { allSessions: rules.allSessions, sessions: new Set(rules.sessionIds), workspaces: new Set(rules.workspaces), lineages: rules.allLineages, branches: new Set(rules.branchSessionIds || []) };})()): null;return json(res, 200, {@@ -8781,6 +8690,11 @@ function handleApi(req, res) {const job = autoCopyJobs.get(url.searchParams.get('id') || '');return job ? json(res, 200, { ok: true, job: publicAutoCopyJob(job) }) : json(res, 404, { ok: false, error: '自动复制任务不存在' });}+ // Old injected panels may still call this route. Never restore the former+ // baseline-clearing overwrite behavior, even with a stale UI.+ if (req.method === 'POST' && p === '/api/sessions/auto-copy/reset') {+ return json(res, 410, { ok: false, error: '会话已分叉,已保留双方内容;不再支持重置后覆盖' });+ }// 当前任务或刚完成的任务:renderer 重载后仍可恢复复制进度。if (req.method === 'GET' && p === '/api/sessions/auto-copy/active') {return json(res, 200, { ok: true, job: publicAutoCopyJob(activeAutoCopyJob()) });@@ -8881,12 +8795,14 @@ function handleApi(req, res) {ids);if (!srcRows.length) return json(res, 404, { ok: false, error: '源会话不存在' });- let copied = 0;+ let copied = 0, skipped = 0, conflicts = 0;for (const src of srcRows) {- await copySessionRecord(src, targetUid);- copied++;+ const result = await copySessionRecord(src, targetUid);+ if (result.status === 'conflict') conflicts++;+ else if (result.status === 'skipped') skipped++;+ else copied++;}- return json(res, 200, { ok: true, copied, targetUid });+ return json(res, 200, { ok: true, copied, skipped, conflicts, targetUid });} catch (e) {return json(res, 500, { ok: false, error: e.message });}@@ -9492,9 +9408,11 @@ function handleApi(req, res) {const uid = (body.uid || '').trim();if (!uid) return json(res, 400, { ok: false, error: '缺少 uid' });const releaseRendererReload = body.reload ? beginRendererReloadPriority() : null;+ let releaseAccountSwitch = null;try {// 只记录源账号;自动复制队列会在 renderer 刷新并完成组件注入后重新规划。// 不在这里预规划,否则大量会话的同步 SQLite/文件扫描会让切换界面长时间无响应。+ releaseAccountSwitch = await assertAccountSwitchIdle();const sourceAccount = currentAccount() || {};const sourceUid = String(sourceAccount.uid || '').trim();const acct = switchTo(DATA_DIR, uid, log);@@ -9572,6 +9490,7 @@ function handleApi(req, res) {return json(res, 500, { ok: false, error: e.message });} finally {if (releaseRendererReload) releaseRendererReload();+ if (releaseAccountSwitch) releaseAccountSwitch();}});}diff --git a/scripts/inject.js b/scripts/inject.jsindex 6c8c591..7f8b260 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -13,6 +13,90 @@* 与后端通信:fetch 本地 daemon(__WBS_API__ 占位符在注入时替换为实际地址)* 幂等:window.__wbsWidget 防重复注入;document.body 未就绪时等待 DOMContentLoaded。*/+function collectConversationUsage(messages) {+ var source = Array.isArray(messages) ? messages : [];+ var byRequest = Object.create(null);+ var order = [];+ function finite(value) {+ var number = Number(value);+ return isFinite(number) && number >= 0 ? number : null;+ }+ function keyFor(message, index) {+ var extra = message && message.extra || {};+ return String(extra.conversationRequestId || message.requestId || message.id || ('message:' + index));+ }+ function isTerminal(message) {+ var extra = message && message.extra || {};+ return message && (message.complete === true || extra.isRequestTerminal === true || extra.isEnd === true || message.isEnd === true) &&+ (!Object.prototype.hasOwnProperty.call(extra, 'isRequestTerminal') || extra.isRequestTerminal === true);+ }+ for (var i = 0; i < source.length; i++) {+ var message = source[i];+ var usage = message && message.usage;+ if (!usage || !isTerminal(message)) continue;+ var key = keyFor(message, i);+ var existing = byRequest[key];+ if (existing) {+ // Streaming updates may leave more than one terminal snapshot. Keep the+ // latest, richest snapshot for this request instead of adding it twice.+ var existingScore = (finite(existing.usage.lastTokens) || 0) + (finite(existing.usage.outputTokens) || 0);+ var nextScore = (finite(usage.lastTokens) || 0) + (finite(usage.outputTokens) || 0);+ if (nextScore >= existingScore) existing.message = message;+ continue;+ }+ byRequest[key] = { message: message, usage: usage };+ order.push(key);+ }++ var models = Object.create(null);+ var records = [];+ var totalInputTokens = 0;+ var totalOutputTokens = 0;+ var totalTokens = 0;+ var totalCredit = 0;+ var creditKnown = true;+ for (var j = 0; j < order.length; j++) {+ var item = byRequest[order[j]];+ var message = item.message;+ var usage = message.usage || {};+ var extra = message.extra || {};+ var input = finite(usage.inputTokens);+ var output = finite(usage.outputTokens);+ var last = finite(usage.lastTokens);+ var hasInputOutput = input !== null || output !== null;+ input = input || 0;+ output = output || 0;+ var tokens = hasInputOutput ? input + output : (last || 0);+ if (tokens === 0 && last !== null && last > 0) tokens = last;+ var credit = finite(usage.credit);+ var modelId = String(extra.modelId || usage.modelId || message.modelId || 'unknown-model');+ var modelName = String(extra.modelName || usage.modelName || extra.model || message.modelName || modelId || '未知模型');+ var record = { modelId: modelId, modelName: modelName, inputTokens: input, outputTokens: output, tokens: tokens, credit: credit };+ records.push(record);+ if (!models[modelId]) models[modelId] = { modelId: modelId, modelName: modelName, calls: 0, inputTokens: 0, outputTokens: 0, tokens: 0, credit: 0, creditKnown: true };+ var model = models[modelId];+ model.calls++;+ model.inputTokens += input;+ model.outputTokens += output;+ model.tokens += tokens;+ if (credit === null) { model.creditKnown = false; creditKnown = false; }+ else { model.credit += credit; totalCredit += credit; }+ totalInputTokens += input;+ totalOutputTokens += output;+ totalTokens += tokens;+ }+ return {+ records: records,+ models: Object.keys(models).map(function (id) { return models[id]; }),+ calls: records.length,+ inputTokens: totalInputTokens,+ outputTokens: totalOutputTokens,+ tokens: totalTokens,+ credit: totalCredit,+ creditKnown: creditKnown,+ };+}+// Activity signals contain no key, text, target or pointer coordinates.function createUsageActivity(options) {var doc = options.document, win = options.window;@@ -653,6 +737,7 @@ function createSessionMonitorRegistry(options) {if (typeof module !== 'undefined' && module.exports) {module.exports = {+ collectConversationUsage: collectConversationUsage,createUsageActivity: createUsageActivity,createBuildLifecycle: createBuildLifecycle,createBrandClickAction: createBrandClickAction,@@ -699,6 +784,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {for (var j = 0; j < ss.length; j++) ss[j].remove();var dbg = document.querySelectorAll('#wbs-diag-badge, #wbs-debug-panel');for (var k = 0; k < dbg.length; k++) dbg[k].remove();+ var usageSummaryNodes = document.querySelectorAll('#wbs-session-usage-summary, #wbs-session-usage-popover');+ for (var us = 0; us < usageSummaryNodes.length; us++) usageSummaryNodes[us].remove();// 销毁所有历史 build:置 alive=false、断开全部 observer/事件监听。// 关键:旧 build 的 observer 若不销毁,DOM 一变就会把旧的 stashBtn 重新设为可见(用户"始终看到按钮"的根因)。var builds = window.__wbsBuilds || [];@@ -711,6 +798,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {try { delete window.__wbsThemeAudit; } catch (e) { window.__wbsThemeAudit = null; }// 队列 adapter 缓存必须一并清除:旧 shim(包装方法齐全但指向失效/错误对象)若不删,// findWbsAdapter 的缓存校验会直接复用旧 shim,导致「修好代码重注入后仍跑旧逻辑」。+ try { delete window.__wbsAnySessionBusy; } catch (_) { window.__wbsAnySessionBusy = null; }try { delete window.__wbsAdapter; } catch (e) { window.__wbsAdapter = null; }})();// ===== 顶部红色角标已移除(用户要求);仅保留 console 标记 =====@@ -737,6 +825,37 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var WBS_LANGUAGE_KEY = 'workdaddy.ui.language';var WBS_ACCOUNT_MASK_KEY = 'workdaddy.account.mask.' + PROFILE_ID;var WBS_I18N_EN = {+ '未同步': 'Not synced', '分叉会话尚未同步,请重试': 'The branched session has not been synced. Try again',+ '已复制分叉副本,原会话已保留': 'Branch copied as a separate session; the original was preserved',+ '账号正在切换,请稍后重试': 'Account switching is in progress. Try again later',+ '无法确认会话状态,请连接 WorkBuddy 后重试': 'Cannot check session status. Connect WorkBuddy and try again',+ '无法确认会话状态,请等待面板加载后重试': 'Cannot check session status. Wait for the panel to load and try again',+ '当前账号有会话仍在运行,请等待完成或停止后再同步': 'This account has running sessions. Wait for them to finish or stop them before syncing',+ '会话同步尚未完成,请稍后切换账号': 'Session sync is still in progress. Switch accounts after it finishes',+ '源会话已变化,请重试': 'The source session changed. Try again',+ '目标账号存在多个同源副本,已保留全部内容': 'The target account has multiple copies of this session. All content was preserved',+ '会话记录正在变化,请稍后重试': 'Session records are changing. Try again later',+ '会话已分叉,已保留双方内容;不再支持重置后覆盖': 'Both branches were preserved. Resetting to overwrite is no longer supported',+ '无效的会话文件路径': 'Invalid session file path',+ '会话文件包含符号链接,未同步': 'Session files contain a symbolic link. Sync was skipped',+ '无效的会话标识': 'Invalid session identifier',+ '会话目录包含符号链接,未同步': 'The session directory is a symbolic link. Sync was skipped',+ '会话文件无法读取': 'Cannot read session files',+ '会话文件类型不受支持': 'Unsupported session file type',+ '会话文件过大,未自动同步': 'Session files exceed the sync limit. Automatic sync was skipped',+ '会话文件正在变化,请稍后重试': 'Session files are changing. Try again later',+ '会话产物索引损坏,未同步': 'The session artifact index is corrupt. Sync was skipped',+ '会话消息文件不唯一,未同步': 'Multiple message files found for this session. Sync was skipped',+ '会话消息文件为空,未同步': 'The session message file is empty. Sync was skipped',+ '会话消息文件未写完或已损坏,未同步': 'The session message file is incomplete or corrupt. Sync was skipped',+ '会话消息格式不受支持,未同步': 'Unsupported session message format. Sync was skipped',+ '会话消息文件没有消息,未同步': 'No messages found in the session file. Sync was skipped',+ '双方会话消息文件均缺失,未同步': 'Both session message files are missing. Sync was skipped',+ '会话消息缺失且附属文件不一致,未覆盖': 'Messages are missing and supporting files differ. No content was overwritten',+ '无效的会话同步目标': 'Invalid session sync target',+ '目标会话正在变化,已停止同步': 'The target session is changing. Sync was stopped',+ '源会话正在变化,已停止同步': 'The source session is changing. Sync was stopped',+ '会话文件校验失败': 'Session file verification failed','派猫猫旅行': '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',@@ -890,7 +1009,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {"请选择有效的执行日期和时间": "Choose a valid date and time","每月日期必须是 1–31": "Day of month must be 1\u201331",'产物索引已变化,请重试同步': 'Artifact index changed; retry synchronization', '已到期': 'Expired', ' 个未获取余额': ' balances unavailable', ' 个不限量': ' unlimited', '无效的账号排序设置': 'Invalid account order settings', '产物索引超过 16MB,未覆盖目标索引': 'Artifact index exceeds 16MB; target index was preserved', '产物索引格式不受支持': 'Unsupported artifact index format', '积分汇总': 'Credit summary', '更多账号设置': 'More account settings', '积分到期分布': 'Credit expiry distribution', '剩余天数 · 积分': 'Days left · Credits', '按剩余天数汇总积分': 'Credits by days remaining', '未知有效期': 'Unknown expiry', '暂无可汇总积分': 'No credits to summarize', '拖拽调整顺序,也可聚焦拖拽按钮后按 ↑ ↓ 调整。新增账号排在最后。': 'Drag to reorder, or focus a handle and press ↑ ↓. New accounts appear last.', '拖拽排序,或按上下方向键调整': 'Drag or use arrow keys to reorder', '调整账号顺序': 'Reorder account', '固定账号顺序': 'Fixed account order', '保存排序失败': 'Failed to save order', '暂无账号': 'No accounts', '{n} 个账号': '{n} accounts', '{n} 个未获取余额': '{n} balances unavailable', '{n} 个不限量': '{n} unlimited', '今日未签到': 'Not checked in today', '浅色': 'Light', '深色': 'Dark', '更多': 'More', '汇总': 'Summary', '账号排序': 'Account order', '按积分临近时间': 'Nearest credit expiry', '固定顺序': 'Fixed order', '今日签到': 'Daily check-in', '今日已签到': 'Checked in today', '今日尚未签到': 'Not checked in today', '客户端加载': 'Client loaded', '打开面板': 'Panel opened', '事件触发(可多选)': 'Event triggers (select any)', '定时间隔(分钟)': 'Interval (minutes)', '定时': 'Scheduled', '每 ': 'Every ', '定时间隔必须是 1–10080 分钟的整数': 'Interval must be an integer from 1 to 10080 minutes', '不支持的面板事件': 'Unsupported panel event', '无签到活动': 'No check-in activity', '登录身份过期': 'Login expired', '刚刚': 'Just now', '分钟前': ' minutes ago', '小时前': ' hours ago', '天前': ' days ago',- '发现新版本': 'New version available', '立即更新': 'Update now', '有新版本可用,点击更新。': 'A new version is available. Click Update.', '下载中…': 'Downloading…', '正在打开…': 'Opening…', '安装程序已打开': 'Installer opened', '打开安装程序': 'Open installer', '安装中…': 'Installing…', '重启中…': 'Restarting…', '已完成': 'Completed', '重试更新': 'Retry update',+ '发现新版本': 'New version available', '立即更新': 'Update now', '有新版本可用,点击更新。': 'A new version is available. Click Update.', '有新版': 'New version', '新版': 'New version', '更新': 'Update', '任务已更新': 'Task updated', '更新自动化任务?': 'Update automation task?', '确认用公开仓库中的新版覆盖本地任务?': 'Replace the local task with the newer public version?', '覆盖': 'Replace', '提示:部分会话尚未完成,当前 Token 和积分仅按已完成用量统计,最终数据可能存在偏差。': 'Note: Some sessions are still in progress. Token and credit totals include completed usage only and may change.', '下载中…': 'Downloading…', '正在打开…': 'Opening…', '安装程序已打开': 'Installer opened', '打开安装程序': 'Open installer', '安装中…': 'Installing…', '重启中…': 'Restarting…', '已完成': 'Completed', '重试更新': 'Retry update','安全传输': 'Secure transfer', '选择内容': 'Select content', '选择账号': 'Select accounts', '选择目标账号': 'Select target account', '选择目标账号…': 'Select a target account…', '密码': 'Password', '请输入密码': 'Enter password', '密码不能为空': 'Password cannot be empty', '请至少选择一项': 'Select at least one item', '处理中…': 'Processing…', '新版文件请输入密码': 'Enter the password for the new file', '新版文件必须输入密码;旧版导出文件可留空。': 'New files require a password; older exports may be left blank.', '新版文件请输入密码;已有的相同短语会自动跳过。': 'Enter the password for the new file; duplicate phrases are skipped.','电脑休眠': 'Computer sleep', '允许电脑休眠': 'Allow computer sleep', '持续禁止休眠': 'Keep awake', '所有会话结束允许休眠': 'Allow sleep when all sessions end', '系统默认,空闲后正常休眠': 'System default; sleep normally when idle', '保持唤醒,防黑屏锁屏': 'Stay awake to prevent screen lock', '任一会话运行中都保持唤醒': 'Stay awake while any session is running', '允许显示器休眠': 'Allow display sleep', '禁止休眠时,是否允许显示器单独黑屏': 'When sleep is blocked, allow the display to turn off','发送错误诊断': 'Send error diagnostics', '推荐开启': 'Recommended', '由环境变量控制': 'Controlled by environment variable', '默认开启 · 设置读取失败': 'Enabled by default · failed to read setting', '保存中…': 'Saving…', '此开关控制脱敏错误诊断。匿名安装数和日活独立统计(随机安装标识、系统、架构、版本、客户端类型及出口国家),不受此开关影响。不包含账号、会话内容、Token 或 API Key。': 'This switch controls redacted error diagnostics. Anonymous installation and daily active counts are collected independently (random installation ID, system, architecture, version, client type, and network country). No accounts, session content, tokens, or API keys.', '查看错误诊断说明': 'View diagnostics details', '问题反馈': 'Report an issue', '会话监听日志': 'Session monitor log', '仅保存在当前页面内存': 'Stored only in this page memory',@@ -899,8 +1018,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'连接新服务…': 'Connecting to service…', '等待中': 'Waiting', '运行中': 'Running', '空闲': 'Idle', '已中断': 'Interrupted', '已停止': 'Stopped', '未确认': 'Unconfirmed', '等待确认': 'Waiting for confirmation', '等待新回复': 'Waiting for a new reply', '等待会话': 'Waiting for session', '等待允许': 'Waiting for approval', '整理中': 'Organizing', '恢复中': 'Restoring', '即将完成…': 'Finishing…', '已继续': 'Continued', '检测到会话异常中断,即将自动发送「': 'An interrupted session was detected. Sending “', '自动发送失败,请手动点击发送': 'Automatic send failed. Please click Send manually', '底层发送失败,请手动发送': 'Underlying send failed. Please send manually','导入中…': 'Importing…', ' 个任务': ' task(s)', '导入任务': 'Import tasks', '导出任务': 'Export tasks', '请先勾选要导出的任务': 'Select tasks to export first', '选择 JSON 或 ZIP 任务文件': 'Choose a JSON or ZIP task file', '读取任务文件…': 'Reading task file…', '任务导出成功': 'Tasks exported', '导入失败': 'Import failed', '导出失败': 'Export failed', '可导入': 'Ready to import', '已存在,将跳过': 'Already exists; skipped', '不兼容,无法导入': 'Incompatible; cannot import', '导入后保持停用,可在任务列表中启用。相同 ID 的任务会跳过。': 'Imported tasks stay disabled until you enable them. Existing task IDs are skipped.', '任务文件不能超过 8 MiB': 'Task files must not exceed 8 MiB', '缺少必填参数': 'Required inputs are missing', '需要更新 WorkDaddy': 'Requires a newer WorkDaddy version', '不支持当前客户端或系统': 'Unsupported client or platform', '文件不是自动化任务 JSON': 'Not an automation task JSON file', '任务格式或能力不受支持': 'Unsupported task format or capabilities','发现更多自动化任务': 'Discover more automations', '正在发现…': 'Discovering…', '搜索任务名称': 'Search task names', '没有匹配的任务': 'No matching tasks', '暂未发现公开任务': 'No public tasks found', '公开任务加载失败': 'Could not load public tasks', '这些任务来自互联网公开仓库,均为第三方内容,与 WorkDaddy 无归属关系。导入后默认停用,请先安全评估再启用。': 'These tasks come from public repositories and are third-party content unaffiliated with WorkDaddy. Imported tasks stay disabled; review them before enabling.', '部分来源暂时无法访问,当前显示上次缓存的结果。': 'Some sources are unavailable. Showing cached results.', '暂无说明': 'No description', '不兼容': 'Incompatible', '无法打开仓库': 'Could not open repository', '任务已导入,启用后生效': 'Task imported. Enable it to run.', '任务已存在,未重复导入': 'Task already exists and was not imported again.', '我也要出现在这里': 'Publish my tasks', '提交公开任务': 'Publish public tasks', '收录 GitHub 和 Gitee 公开仓库。参考': 'Public GitHub and Gitee repositories are indexed. See', '将任务 JSON 放在 tasks/ 目录,并在仓库描述中加入 WorkDaddyAutomationRepository。': 'Put task JSON files in tasks/ and add WorkDaddyAutomationRepository to the repository description.', '查看示例仓库': 'View example repository', '上一页': 'Previous', '下一页': 'Next', ' · 匹配 ': ' · Matches ', '安全评估': 'Safety review', '评估中…': 'Reviewing…', '安全评估会话已创建': 'Safety review session created', '安全评估失败': 'Safety review failed', '会话创建失败': 'Could not create the session', '无法读取评估状态': 'Could not read review status', '未返回安全评估运行记录': 'No safety review run was returned', '无法创建会话': 'Could not create a session', '评估会话仍在创建,请稍后查看 WorkBuddy': 'The review session is still being created. Check WorkBuddy shortly.',- '会话同步完成': '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',+ '会话同步完成': '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 ','导出账号': 'Export accounts', '导入账号': 'Import accounts', '导出会话': 'Export sessions', '导入会话': 'Import sessions', '导出快捷短语': 'Export quick phrases', '导入快捷短语': 'Import quick phrases', '同步选中到其他账号': 'Sync selected to another account', '删除选中': 'Delete selected', '操作会话': 'Session actions', '连通测试': 'Test connection', '编辑模型': 'Edit model', '模型已保存': 'Model saved', '模型已启用': 'Model enabled', '模型已复制': 'Model copied', '模型配置已共用': 'Model configuration shared', '当前模型': 'Current model', '备选模型': 'Backup models', '模型加载失败:': 'Failed to load models: ', '保存模型失败:': 'Failed to save model: ', '删除当前模型失败:': 'Failed to delete current model: ', '启用模型失败:': 'Failed to enable model: ', '连通测试失败:': 'Connection test failed: ','选择要查看的账号': 'Choose an account to view', '选择账号并输入密码后导出备份': 'Choose accounts and enter a password to export backups', '从加密导出文件导入账号备份': 'Import account backups from an encrypted export', '使用密码导出选中会话': 'Export selected sessions with a password', '使用密码导出选中快捷短语': 'Export selected quick phrases with a password', '从加密文件导入会话': 'Import sessions from an encrypted file', '从加密文件导入快捷短语': 'Import quick phrases from an encrypted file', '仅支持 PNG / JPG / WebP': 'PNG / JPG / WebP only', '点击或拖拽上传壁纸': 'Click or drag to upload a wallpaper', '点击选择图片,或拖拽到此处': 'Click to choose an image, or drag it here', '支持 PNG / JPG / WebP,自动压缩;可添加多张': 'PNG / JPG / WebP supported; images are compressed automatically',@@ -1181,7 +1300,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'面板入口:': 'Panel entry:', '右下角机器人按钮': 'Bottom-right robot button', '已连接': 'Connected', '未连接': 'Not connected','Token 用量': 'Token usage', '正在读取统计…': 'Loading statistics…', '搜索': 'Search', '重置': 'Reset', '调用': 'Calls', '输入': 'Input', '输出': 'Output', '导入方式': 'Import method', '复制提示词': 'Copy prompt', '导入 WorkDaddy 加密文件': 'Import WorkDaddy encrypted file', '导入 WorkDaddy 导出的账号备份,选择文件后输入导出密码。': 'Import an account backup exported by WorkDaddy, then enter its export password.', '导入 JSON 文件': 'Import JSON file', '可以导入其他工具导出的明文账号。请先让 WorkBuddy 按指定格式整理,再选择生成的 JSON 文件。': 'Import plain-text accounts exported by another tool. Ask WorkBuddy to convert them to the required format, then choose the generated JSON file.', '把其他工具导出的账号文本发给 WorkBuddy,让它只输出符合 WorkDaddy 格式的 JSON,然后复制保存为文件。': 'Send the account text exported by another tool to WorkBuddy. Ask it to output only WorkDaddy-compatible JSON, then save it as a file.', '提示词已复制': 'Prompt copied', '选择文件': 'Choose file','缓存读取': 'Cache read', '缓存写入': 'Cache write',- ' 个文件,解析失败': ' files, parse failures', ' 行': ' lines', '暂无可统计的 Token 用量': 'No Token usage found',+ ' 个文件,解析失败': ' files, parse failures', ' 行': ' lines', '暂无可统计的 Token 用量': 'No Token usage found', '会话用量': 'Conversation usage', '本会话用量': 'This conversation usage', '本会话用量明细': 'Conversation usage details', '暂无已完成用量': 'No completed usage yet', '读取中…': 'Loading…', '未知模型': 'Unknown model', '总计': 'Total', '在会话底部显示 Token、积分和模型汇总': 'Show Token, credits and model summary at the bottom of conversations','当前积分段已用完': 'The current credit segment is used up', '积分将在': ' credits expire in', '到期': ' expires', '要切换账号吗?': 'Switch account?', '可以切换到账号': 'Can switch to account', '检测到积分到期时间最临近的账号': 'The account with the nearest credit expiry is', '积分将于': ' credits expire within', '内过期': '', '较长时间': 'a long time', ' 小时 ': ' hr ', ' 分': ' min','切换到此账号': 'Switch to this account', '今天不再提醒': 'Do not remind me again today', '关闭': 'Close','切换中…': 'Switching…', 'Token 用量统计': 'Token usage statistics', ' 分钟后': ' minutes', ' 小时后': ' hours', ' 天后': ' days',@@ -1499,25 +1618,43 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 每个积分段只归入一个剩余天数桶;缺失有效期的余额不展示,不猜测到期日。function summarizeCreditDays(accounts, now) {var buckets = new Map(), unavailable = 0, unlimited = 0;- function add(days, credits) {- if (credits > 0 && isFinite(credits)) buckets.set(days, (buckets.get(days) || 0) + credits);+ function add(days, credits, detail) {+ if (credits > 0 && isFinite(credits)) {+ var bucket = buckets.get(days);+ if (!bucket) { bucket = { credits: 0, segments: [] }; buckets.set(days, bucket); }+ bucket.credits += credits;+ if (detail) bucket.segments.push({+ remaining: credits,+ total: detail.total || credits,+ expiresAt: detail.expiresAt,+ source: detail.source,+ accountName: detail.accountName,+ });+ }}(accounts || []).forEach(function (account) {if (account.creditUnlimited) { unlimited++; return; }if (account.creditExpired || isIdentityExpired(account) || typeof account.credits !== 'number' || !isFinite(account.credits)) { unavailable++; return; }var balance = Math.max(0, account.credits);var segments = Array.isArray(account.creditSegments) ? account.creditSegments : [];+ var accountName = account.nickname || account.uid || '未命名账号';segments.forEach(function (segment) {if (!segment || !isFinite(Number(segment.remaining))) return;var amount = Math.min(balance, Math.max(0, Number(segment.remaining)));var expiry = segment.expiresAt;var days = expiry !== null && expiry !== undefined && expiry !== '' && isFinite(Number(expiry))? Math.max(0, Math.ceil((Number(expiry) - now) / 86400000)) : null;- add(days, amount); balance -= amount;+ add(days, amount, { total: segment.total || amount, expiresAt: expiry, source: segment.source, accountName: accountName }); balance -= amount;});add(null, balance);});- return { rows: Array.from(buckets, function (item) { return { days: item[0], credits: item[1] }; }).filter(function (row) { return row.days !== null; }).sort(function (a, b) {+ return { rows: Array.from(buckets, function (item) {+ var row = { days: item[0], credits: item[1].credits };+ // Keep the public summary shape stable for existing consumers while the+ // popup can still render each underlying account segment.+ Object.defineProperty(row, 'segments', { value: item[1].segments, enumerable: false });+ return row;+ }).filter(function (row) { return row.days !== null; }).sort(function (a, b) {if (a.days === b.days) return 0;if (a.days === null) return 1;if (b.days === null) return -1;@@ -1884,6 +2021,360 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {target.addEventListener(type, handler, options);registerDisposer(function () { target.removeEventListener(type, handler, options); });}++ // 会话底部用量汇总:数据来自官方 ConversationController 的 messageStore,+ // DOM 只负责找到稳定的挂载点,不读取官方 footer 文案。+ var conversationUsage = {+ surface: null,+ controller: null,+ unsubscribe: null,+ summary: null,+ popover: null,+ spacer: null,+ scrollElement: null,+ scrollFrame: null,+ visible: false,+ popoverTimer: null,+ observer: null,+ state: null,+ };+ var CONVERSATION_USAGE_ENABLED_KEY = 'workdaddy.session.conversationUsageEnabled';+ var conversationUsageEnabled = true;+ try { conversationUsageEnabled = localStorage.getItem(CONVERSATION_USAGE_ENABLED_KEY) !== '0'; } catch (_) {}+ function usageNumber(value) {+ var number = Number(value);+ return isFinite(number) && number >= 0 ? number : 0;+ }+ function formatUsageTokens(value) {+ value = usageNumber(value);+ if (value >= 1000000000) return (value / 1000000000).toFixed(1).replace(/\.0$/, '') + 'B';+ if (value >= 1000000) return (value / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';+ if (value >= 1000) return (value / 1000).toFixed(1).replace(/\.0$/, '') + 'K';+ return String(Math.round(value));+ }+ function formatUsageCredit(value, known) {+ var formatted = usageNumber(value).toFixed(2).replace(/\.00$/, '').replace(/(\.\d)0$/, '$1');+ if (known) return formatted;+ return usageNumber(value) > 0 ? '≥' + formatted : '—';+ }+ function usageSurface() {+ var selectedId = '';+ try { selectedId = String(WBS_COMPAT.getSelectedConversationId(document) || ''); } catch (_) {}+ var docs = document.querySelectorAll('.cr-document[data-root-id]');+ var fallback = null;+ for (var i = 0; i < docs.length; i++) {+ var conversation = docs[i];+ var content = conversation.closest('.cr-message-list__content');+ if (!content) continue;+ var id = String(conversation.getAttribute('data-root-id') || '');+ if (selectedId && id === selectedId) return { conversation: conversation, content: content, id: id };+ var rect = conversation.getBoundingClientRect();+ if (!fallback && rect.width > 0 && rect.height > 0) fallback = { conversation: conversation, content: content, id: id };+ }+ return fallback;+ }+ function usageController(id) {+ if (!WBS_COMPAT || typeof WBS_COMPAT.findConversationControllers !== 'function') return null;+ var controllers = [];+ try { controllers = WBS_COMPAT.findConversationControllers(document) || []; } catch (_) {}+ for (var i = 0; i < controllers.length; i++) {+ if (!id || String(controllers[i].conversationId || '') === String(id)) return controllers[i];+ }+ return null;+ }+ function hideUsagePopover() {+ if (!conversationUsage.popover) return;+ conversationUsage.popover.classList.remove('is-visible');+ }+ function usageScrollElement(surface) {+ if (!surface || !surface.content) return null;+ return surface.content.closest('.cr-message-list') || document.querySelector('.cr-message-list');+ }+ function setConversationUsageVisible(visible) {+ visible = !!visible;+ conversationUsage.visible = visible;+ if (conversationUsage.summary) conversationUsage.summary.classList.toggle('is-hidden', !visible);+ if (!visible) hideUsagePopover();+ }+ function updateConversationUsageScrollState() {+ var scrollElement = conversationUsage.scrollElement;+ if (!scrollElement || !conversationUsage.summary) {+ setConversationUsageVisible(false);+ return;+ }+ var maxScroll = scrollElement.scrollHeight - scrollElement.clientHeight;+ var canScroll = maxScroll > 1;+ var atBottom = canScroll && maxScroll - scrollElement.scrollTop <= 4;+ setConversationUsageVisible(atBottom);+ }+ function scheduleConversationUsageScrollState() {+ if (conversationUsage.scrollFrame != null) return;+ var raf = window.requestAnimationFrame || function (callback) { return window.setTimeout(callback, 16); };+ conversationUsage.scrollFrame = raf(function () {+ conversationUsage.scrollFrame = null;+ positionConversationUsage();+ if (conversationUsage.popover && conversationUsage.popover.classList.contains('is-visible')) positionUsagePopover();+ updateConversationUsageScrollState();+ });+ }+ function bindConversationUsageScroll(surface) {+ var next = usageScrollElement(surface);+ if (conversationUsage.scrollElement === next) {+ updateConversationUsageScrollState();+ return;+ }+ if (conversationUsage.scrollElement) {+ conversationUsage.scrollElement.removeEventListener('scroll', scheduleConversationUsageScrollState);+ }+ conversationUsage.scrollElement = next;+ if (next) next.addEventListener('scroll', scheduleConversationUsageScrollState, { passive: true });+ updateConversationUsageScrollState();+ }+ function unbindConversationUsageScroll() {+ if (conversationUsage.scrollElement) {+ conversationUsage.scrollElement.removeEventListener('scroll', scheduleConversationUsageScrollState);+ }+ conversationUsage.scrollElement = null;+ if (conversationUsage.scrollFrame != null) {+ var cancel = window.cancelAnimationFrame || window.clearTimeout;+ cancel(conversationUsage.scrollFrame);+ conversationUsage.scrollFrame = null;+ }+ setConversationUsageVisible(false);+ }+ function positionUsagePopover() {+ var summary = conversationUsage.summary;+ var popover = conversationUsage.popover;+ if (!summary || !popover || !popover.classList.contains('is-visible')) return;+ var rect = summary.getBoundingClientRect();+ var left = Math.max(8, rect.left);+ var width = Math.min(popover.offsetWidth || 320, Math.max(120, window.innerWidth - left - 8));+ var height = popover.offsetHeight || 180;+ var top = rect.top - height - 8;+ if (top < 8) top = Math.min(window.innerHeight - height - 8, rect.bottom + 8);+ popover.style.left = Math.round(left) + 'px';+ popover.style.width = Math.round(width) + 'px';+ popover.style.top = Math.round(Math.max(8, top)) + 'px';+ }+ function positionConversationUsage() {+ var summary = conversationUsage.summary;+ var surface = conversationUsage.surface;+ if (!summary || !surface || !conversationUsageEnabled) return;+ var contentRect = surface.content.getBoundingClientRect();+ if (!contentRect || contentRect.width <= 0) return;+ var inputArea = document.querySelector('.conversation-input-area,.conversation-input,.cr-input-box');+ var inputRect = inputArea && inputArea.getBoundingClientRect();+ var viewport = surface.content.closest('.cr-message-list-viewport');+ var viewportRect = viewport && viewport.getBoundingClientRect();+ var bottomMask = document.querySelector('.cr-message-list__bottom-mask');+ var maskRect = bottomMask && bottomMask.getBoundingClientRect();+ var anchorRect = maskRect && maskRect.width > 0 && maskRect.height > 0 ? maskRect : inputRect;+ var anchorBottom = anchorRect && anchorRect.bottom > 0 ? anchorRect.bottom : (viewportRect && viewportRect.bottom) || window.innerHeight;+ var left = anchorRect && anchorRect.width > 0 ? anchorRect.left : contentRect.left;+ var maxWidth = anchorRect && anchorRect.width > 0 ? anchorRect.width : contentRect.width;+ left = Math.max(8, left);+ summary.style.left = Math.round(left) + 'px';+ summary.style.width = 'max-content';+ summary.style.maxWidth = Math.round(Math.min(maxWidth, window.innerWidth - left - 8)) + 'px';+ summary.style.bottom = Math.round(Math.max(0, window.innerHeight - anchorBottom)) + 'px';+ if (conversationUsage.spacer && conversationUsage.spacer.parentNode) {+ conversationUsage.spacer.style.height = Math.ceil(summary.getBoundingClientRect().height || 34) + 'px';+ }+ }+ function showUsagePopover() {+ if (!conversationUsage.summary || !conversationUsage.popover) return;+ if (conversationUsage.popoverTimer) clearTimeout(conversationUsage.popoverTimer);+ conversationUsage.popover.classList.add('is-visible');+ positionUsagePopover();+ }+ function scheduleHideUsagePopover() {+ if (conversationUsage.popoverTimer) clearTimeout(conversationUsage.popoverTimer);+ conversationUsage.popoverTimer = setTimeout(function () {+ conversationUsage.popoverTimer = null;+ if (conversationUsage.summary && conversationUsage.summary.matches(':hover')) return;+ if (conversationUsage.popover && conversationUsage.popover.matches(':hover')) return;+ hideUsagePopover();+ }, 120);+ }+ function usageDetailRows(state) {+ var models = (state && state.models || []).slice().sort(function (a, b) { return b.tokens - a.tokens; });+ if (!models.length) return [el('div', 'wbs-session-usage-empty', wbsTranslateString('暂无已完成用量', WBS_LANGUAGE))];+ var rows = [];+ for (var i = 0; i < models.length; i++) {+ var model = models[i];+ var row = el('div', 'wbs-session-usage-detail-row');+ var name = el('span', 'wbs-session-usage-model', model.modelName);+ name.title = model.modelName;+ row.appendChild(name);+ row.appendChild(el('span', 'wbs-session-usage-calls', model.calls + ' 次'));+ row.appendChild(el('span', 'wbs-session-usage-tokens', formatUsageTokens(model.tokens)));+ row.appendChild(el('span', 'wbs-session-usage-credit', formatUsageCredit(model.credit, model.creditKnown)));+ rows.push(row);+ }+ return rows;+ }+ function renderConversationUsage(state) {+ conversationUsage.state = state || null;+ var summary = conversationUsage.summary;+ var popover = conversationUsage.popover;+ if (!summary || !popover) return;+ var main = summary.querySelector('.wbs-session-usage-main');+ var body = popover.querySelector('.wbs-session-usage-detail-body');+ if (!main || !body) return;+ main.textContent = '';+ body.textContent = '';+ var calls = state && state.calls || 0;+ if (!state) {+ main.appendChild(el('span', 'wbs-session-usage-label', '会话用量'));+ main.appendChild(el('span', 'wbs-session-usage-loading', '读取中…'));+ } else if (!calls) {+ main.appendChild(el('span', 'wbs-session-usage-label', '会话用量'));+ main.appendChild(el('span', 'wbs-session-usage-loading', '暂无已完成用量'));+ } else {+ main.appendChild(el('span', 'wbs-session-usage-label', '会话用量'));+ main.appendChild(el('span', 'wbs-session-usage-number', formatUsageTokens(state.tokens) + ' Token'));+ main.appendChild(el('span', 'wbs-session-usage-separator', '·'));+ main.appendChild(el('span', 'wbs-session-usage-number', formatUsageCredit(state.credit, state.creditKnown) + ' 积分'));+ main.appendChild(el('span', 'wbs-session-usage-separator', '·'));+ var models = state.models || [];+ var modelLabel = models.length === 1 ? models[0].modelName + ' × ' + calls : models.length + ' 个模型';+ main.appendChild(el('span', 'wbs-session-usage-models', modelLabel));+ }+ var total = popover.querySelector('.wbs-session-usage-detail-total');+ if (total) total.textContent = '总计 ' + formatUsageTokens(state && state.tokens) + ' Token · ' + formatUsageCredit(state && state.credit, state && state.creditKnown !== false) + ' 积分';+ var rows = usageDetailRows(state);+ for (var i = 0; i < rows.length; i++) body.appendChild(rows[i]);+ applyI18n(summary);+ applyI18n(popover);+ positionConversationUsage();+ positionUsagePopover();+ }+ function ensureUsageNodes(surface) {+ if (!conversationUsage.summary) {+ var summary = el('div', 'wbs-session-usage-summary');+ summary.id = 'wbs-session-usage-summary';+ summary.tabIndex = 0;+ summary.setAttribute('role', 'group');+ summary.setAttribute('aria-label', '本会话用量');+ summary.setAttribute('aria-describedby', 'wbs-session-usage-popover');+ summary.appendChild(el('div', 'wbs-session-usage-main'));+ conversationUsage.summary = summary;+ listen(summary, 'mouseenter', showUsagePopover);+ listen(summary, 'mouseleave', scheduleHideUsagePopover);+ listen(summary, 'focusin', showUsagePopover);+ listen(summary, 'focusout', scheduleHideUsagePopover);+ }+ if (!conversationUsage.popover) {+ var popover = el('div', 'wbs-session-usage-popover');+ popover.id = 'wbs-session-usage-popover';+ popover.setAttribute('role', 'tooltip');+ popover.appendChild(el('div', 'wbs-session-usage-detail-title', '本会话用量明细'));+ popover.appendChild(el('div', 'wbs-session-usage-detail-total'));+ popover.appendChild(el('div', 'wbs-session-usage-detail-note', '提示:部分会话尚未完成,当前 Token 和积分仅按已完成用量统计,最终数据可能存在偏差。'));+ var detailHead = el('div', 'wbs-session-usage-detail-head');+ detailHead.appendChild(el('span', '', '模型'));+ detailHead.appendChild(el('span', '', '调用'));+ detailHead.appendChild(el('span', '', 'Token'));+ detailHead.appendChild(el('span', '', '积分'));+ popover.appendChild(detailHead);+ popover.appendChild(el('div', 'wbs-session-usage-detail-body'));+ conversationUsage.popover = popover;+ document.body.appendChild(popover);+ listen(popover, 'mouseenter', showUsagePopover);+ listen(popover, 'mouseleave', scheduleHideUsagePopover);+ }+ if (!conversationUsage.spacer) {+ var spacer = el('div', 'wbs-session-usage-spacer');+ spacer.setAttribute('aria-hidden', 'true');+ conversationUsage.spacer = spacer;+ }+ if (surface && surface.content && conversationUsage.spacer.parentNode !== surface.content) {+ surface.content.appendChild(conversationUsage.spacer);+ }+ // fixed 元素必须挂在 body 下;消息网格祖先带 transform,会改变 fixed 的坐标系。+ if (conversationUsage.summary.parentNode !== document.body && document.body) {+ document.body.appendChild(conversationUsage.summary);+ }+ }+ function bindUsageController(controller) {+ if (conversationUsage.controller === controller) {+ if (controller && controller.messageStore) renderConversationUsage(collectConversationUsage(controller.messageStore.getState().messages));+ return;+ }+ if (conversationUsage.unsubscribe) {+ try { conversationUsage.unsubscribe(); } catch (_) {}+ conversationUsage.unsubscribe = null;+ }+ conversationUsage.controller = controller || null;+ renderConversationUsage(null);+ if (!controller || !controller.messageStore) return;+ var store = controller.messageStore;+ function refresh(state) {+ if (conversationUsage.controller !== controller) return;+ if (!state || !Array.isArray(state.messages)) {+ try { state = store.getState(); } catch (_) { state = null; }+ }+ renderConversationUsage(collectConversationUsage(state && state.messages));+ }+ try { conversationUsage.unsubscribe = store.subscribe(refresh); } catch (_) { conversationUsage.unsubscribe = null; }+ try { refresh(store.getState()); } catch (_) {}+ }+ function syncConversationUsage() {+ if (!alive) return;+ if (!conversationUsageEnabled) {+ if (conversationUsage.summary) conversationUsage.summary.remove();+ if (conversationUsage.spacer) conversationUsage.spacer.remove();+ unbindConversationUsageScroll();+ hideUsagePopover();+ bindUsageController(null);+ conversationUsage.surface = null;+ return;+ }+ var surface = usageSurface();+ if (!surface) {+ if (conversationUsage.summary) conversationUsage.summary.remove();+ if (conversationUsage.spacer) conversationUsage.spacer.remove();+ unbindConversationUsageScroll();+ hideUsagePopover();+ bindUsageController(null);+ conversationUsage.surface = null;+ return;+ }+ conversationUsage.surface = surface;+ ensureUsageNodes(surface);+ bindConversationUsageScroll(surface);+ positionConversationUsage();+ var controller = usageController(surface.id);+ bindUsageController(controller);+ }+ function setConversationUsageEnabled(enabled) {+ conversationUsageEnabled = !!enabled;+ try { localStorage.setItem(CONVERSATION_USAGE_ENABLED_KEY, conversationUsageEnabled ? '1' : '0'); } catch (_) {}+ syncConversationUsage();+ }+ listen(window, 'resize', function () {+ positionConversationUsage();+ positionUsagePopover();+ updateConversationUsageScrollState();+ });+ listen(window, 'scroll', function () {+ positionConversationUsage();+ if (conversationUsage.popover && conversationUsage.popover.classList.contains('is-visible')) positionUsagePopover();+ }, true);+ setBuildInterval(syncConversationUsage, 800);+ setBuildTimeout(syncConversationUsage, 120);+ registerDisposer(function () {+ if (conversationUsage.unsubscribe) { try { conversationUsage.unsubscribe(); } catch (_) {} }+ unbindConversationUsageScroll();+ if (conversationUsage.popoverTimer) clearTimeout(conversationUsage.popoverTimer);+ if (conversationUsage.summary) conversationUsage.summary.remove();+ if (conversationUsage.popover) conversationUsage.popover.remove();+ if (conversationUsage.spacer) conversationUsage.spacer.remove();+ conversationUsage.summary = null;+ conversationUsage.popover = null;+ conversationUsage.spacer = null;+ conversationUsage.controller = null;+ });var toastRuntime = window.__wbsToastRuntime;if (!toastRuntime) throw new Error('通知组件未加载');registerDisposer(function () { toastRuntime.destroy(); });@@ -2423,6 +2914,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {* 暂存提示词/快捷短语由 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;@@ -2447,6 +2939,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var sessState = {stash: true,messageNav: readMessageNavigationEnabled(),+ usageSummary: conversationUsageEnabled,selectionQuote: readSelectionQuoteEnabled(),fork: readForkEnabled(),phrase: true,@@ -2465,12 +2958,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var pane0 = enhancePane;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;@@ -4771,7 +5266,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var automationDiscoveryPromise = null;function preloadAutomationDiscovery() {if (automationDiscoveryPromise) return automationDiscoveryPromise;- automationDiscoveryPromise = api('/api/automations/discovery').finally(function () { automationDiscoveryPromise = null; });+ automationDiscoveryPromise = api('/api/automations/discovery?refresh=1').finally(function () { automationDiscoveryPromise = null; });return automationDiscoveryPromise;}@@ -4837,8 +5332,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function creditPopoverHtml(segment) {var lines = String(segment.getAttribute('data-tip') || '').split('\n');return '<div class="wbs-daily-popover-head"><strong>' + esc(lines[0] || '积分') + '</strong></div>' ++ (lines[3] ? '<div class="wbs-credit-tip-account">' + esc(lines[3]) + '</div>' : '') +'<div class="wbs-credit-tip-value"><i class="credit"></i><b>' + esc(lines[1] || '') + '</b></div>' +- '<div class="wbs-daily-manual">' + esc(lines.slice(2).join(' · ') || '有效期未知') + '</div>';+ '<div class="wbs-daily-manual">' + esc(lines[2] || '有效期未知') + '</div>';}function hideCreditTooltip() {@@ -5056,7 +5552,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {popup.innerHTML = '<div class="wbs-credit-summary-head"><strong>积分到期分布</strong><span>剩余天数 · 积分</span></div>' +'<div class="wbs-credit-summary-chart">' + (summary.rows.map(function (row) {var label = row.days === 0 ? '已到期' : row.days + ' 天';- return '<div class="wbs-credit-summary-row"><span>' + esc(label) + '</span><div class="wbs-credit-summary-track"><i class="wbs-credit-summary-fill" style="--wbs-credit-alpha:' + creditOpacity(row.days).toFixed(5) + ';width:' + Math.max(1, row.credits / max * 100).toFixed(2) + '%"></i></div><b>' + esc(fmtCredits(row.credits)) + '</b></div>';+ var total = row.credits || 1;+ var rowAlpha = creditOpacity(row.days);+ var nodes = (row.segments || []).map(function (segment) {+ var amount = Math.max(0, Number(segment.remaining) || 0);+ var tip = creditSummaryTip(segment);+ var attrTip = esc(tip).replace(/"/g, '"');+ var daysLeft = segment.expiresAt === null || segment.expiresAt === undefined || segment.expiresAt === '' ? null : (Number(segment.expiresAt) - Date.now()) / 86400000;+ return '<span class="wbs-credit-segment" style="--wbs-credit-alpha:' + creditOpacity(daysLeft).toFixed(5) + ';flex:' + Math.max(0.008, amount / total).toFixed(4) + ' 1 0" data-tip="' + attrTip + '" aria-label="' + attrTip + '"></span>';+ }).join('');+ return '<div class="wbs-credit-summary-row"><span>' + esc(label) + '</span><div class="wbs-credit-summary-track" style="--wbs-credit-alpha:' + rowAlpha.toFixed(5) + '">' + nodes + '</div><b>' + esc(fmtCredits(row.credits)) + '</b></div>';}).join('') || '<div class="wbs-empty">暂无可汇总积分</div>') + '</div>' +'<div class="wbs-credit-summary-foot">' + summary.accountCount + ' 个账号' +(summary.unavailable ? ' · ' + summary.unavailable + ' 个未获取余额' : '') +@@ -5072,9 +5577,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {listen(button, 'focus', show); listen(button, 'blur', deferHide);listen(button, 'click', show);listen(button, 'keydown', function (event) { if (event.key === 'Escape') { event.stopPropagation(); hide(); } });+ listen(popup, 'mouseover', function (event) {+ var segment = findCreditSegment(event.target);+ if (!segment || segment === creditTooltipSegment) return;+ creditTooltipSegment = segment;+ showCreditTooltip(segment);+ });+ listen(popup, 'mouseout', function (event) {+ var from = findCreditSegment(event.target);+ var to = findCreditSegment(event.relatedTarget);+ if (from && from !== to) hideCreditTooltip();+ });listen(popup, 'mouseenter', function () { clearTimeout(hideTimer); });listen(popup, 'mouseleave', deferHide);listen(popup, 'wheel', function (event) { event.stopPropagation(); });+ listen(popup, 'scroll', hideCreditTooltip, true);listen(popup, 'pointerdown', function (event) { event.stopPropagation(); });listen(window, 'resize', hide);listen(accountsPane, 'scroll', hide, true);@@ -5756,11 +6273,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {mask.className = 'wbs-modal-mask wbs-usage-modal-mask';mask.innerHTML = '<div class="wbs-modal wbs-token-stats-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-token-stats-title">' +'<div class="wbs-usage-header"><div class="wbs-token-stats-head"><div class="wbs-modal-title" id="wbs-token-stats-title">用量统计</div></div>' +- '<div class="wbs-usage-tabs"><button type="button" class="active" data-usage-tab="token">Token</button><button type="button" data-usage-tab="credit">积分</button></div></div><div class="wbs-usage-scroll wbs-usage-dashboard">' +- '<div data-usage-pane="token">' + usageTimeSegmentHtml('token') ++ '<div class="wbs-usage-tabs"><button type="button" class="active" data-usage-tab="credit">积分</button><button type="button" data-usage-tab="token">Token</button></div></div><div class="wbs-usage-scroll wbs-usage-dashboard">' ++ '<div data-usage-pane="token" hidden>' + usageTimeSegmentHtml('token') +'<div class="wbs-token-source-note">Token 用量仅统计本机记录,在不同电脑上查看的数据可能不一致。</div>' +'<div class="wbs-token-stats-content"><div class="wbs-token-stats-body"></div><div class="wbs-token-stats-overlay" role="status" aria-label="正在读取统计…"><div class="wbs-token-stats-spinner"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle></svg><span hidden>首次加载时间较长,请等候</span></div></div></div></div>' +- '<div data-usage-pane="credit" hidden>' + usageTimeSegmentHtml('credit') ++ '<div data-usage-pane="credit">' + usageTimeSegmentHtml('credit') +'<div data-credit-result role="status" class="wbs-credit-stats-note" hidden></div>' +'<div class="wbs-credit-query-content"><div class="wbs-credit-stats-body wbs-token-stats-body"></div><div class="wbs-credit-sync-overlay" hidden><div class="wbs-credit-sync-progress" role="status" aria-live="polite"><strong>正在查询积分用量…</strong><span data-credit-progress-copy>正在连接…</span><progress data-credit-progress max="100" value="0" aria-label="积分查询进度"></progress><span data-credit-progress-detail></span></div></div></div></div></div>' +'<div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" data-token-close>关闭</button></div></div>';@@ -5991,7 +6508,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {hasStats = true;}).catch(function (error) { if (!mask.isConnected || serial !== tokenReadSerial) return; if (hasStats) toast('读取失败:' + (error.message || error), true, root); else body.innerHTML = '<div class="wbs-token-stats-empty">读取失败:' + esc(error.message || error) + '</div>'; }).finally(function () { if (!mask.isConnected || serial !== tokenReadSerial) return; if (firstLoadTimer) { clearTimeout(firstLoadTimer); firstLoadTimer = null; } mask.querySelectorAll('[data-token-days]').forEach(function (button) { button.disabled = false; }); overlay.hidden = true; });}- load();+ if (mask.querySelector('[data-usage-tab].active').getAttribute('data-usage-tab') === 'credit') loadCredits(); else load();}// ===== Tab 切换 =====@@ -6009,6 +6526,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (name === 'models' && modelsPane && !modelsPane.dataset.built) buildModelsPane();if (name === 'enhance' && enhancePane && !enhancePane.dataset.built) buildEnhancePane();if (name === 'automations' && automationPane && !automationPane.dataset.built) buildAutomationPane();+ else if (name === 'automations' && automationPane && automationPane.__wbsRefreshDiscovery) automationPane.__wbsRefreshDiscovery();if (name === 'pc' && pcPane && !pcPane.dataset.built) buildPcPane();if (name === 'about' && aboutPane && !aboutPane.dataset.built) buildAboutPane();if (name === 'settings' && settingsPane && !settingsPane.dataset.built) buildSettingsPane();@@ -6024,6 +6542,29 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!automationPane) return;automationPane.dataset.built = '1';var automationState = { tasks: [], runs: [], examples: [], selected: {}, batchMode: false, editingId: null, pollTimer: null, reviewPollTimer: null, reviewingId: null, stopping: {}, agentDraft: '', agentCreating: false, discovery: null, discoveryLoading: true, discoveryError: '' };+ function comparePackageVersions(left, right) {+ var a = String(left || '').split('.').map(Number), b = String(right || '').split('.').map(Number);+ for (var i = 0; i < 3; i++) { if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0) ? 1 : -1; }+ return 0;+ }+ function importedPackage(task) {+ var info = task && task['x-workdaddy-import'];+ return info && info.kind === 'local-file' && info.packageId && info.packageVersion ? info : null;+ }+ function installedPackage(packageId) {+ if (!packageId) return null;+ for (var i = 0; i < automationState.tasks.length; i++) {+ var info = importedPackage(automationState.tasks[i]);+ if (info && info.packageId === packageId) return automationState.tasks[i];+ }+ return null;+ }+ function updateForTask(task) {+ var info = importedPackage(task);+ if (!info || !automationState.discovery) return null;+ var latest = (automationState.discovery.tasks || []).filter(function (item) { return item.packageId === info.packageId && item.compatible !== false; })[0];+ return latest && comparePackageVersions(latest.packageVersion, info.packageVersion) > 0 ? latest : null;+ }function defaultTask() {return { schemaVersion: 2, id: 'task_' + Date.now().toString(36), name: '新自动化任务', description: '', enabled: true, concurrency: { policy: 'skip' }, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [] };}@@ -6091,7 +6632,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var stateClass = active ? 'running' : !task.enabled && !task.manualRunnable ? 'off' : 'idle';var action = running ? '<button type="button" class="wbs-auto-icon is-running' + (stopping ? ' is-stopping' : '') + '" data-auto-stop="' + escAttr(run.id) + '" title="' + (stopping ? '正在停止…' : '停止本次执行') + '" aria-label="' + (stopping ? '正在停止…' : '停止本次执行') + '" aria-busy="true"' + (stopping ? ' disabled' : '') + '>' + (stopping ? AUTO_STOPPING_SVG : AUTO_STOP_SVG) + '</button>': task.manualRunnable ? '<button type="button" class="wbs-auto-icon" data-auto-run="' + escAttr(task.id) + '" title="立即运行" aria-label="立即运行">' + MODEL_ENABLE_SVG + '</button>' : '';- row.innerHTML = '<div class="wbs-auto-row-head">' + check + '<div class="wbs-auto-name"' + (wbsBuiltinAutomationText(task, 'name') ? '' : ' data-wbs-i18n-skip="1"') + ' title="' + escAttr(task.name) + '">' + esc(task.name) + '</div>' ++ var update = typeof updateForTask === 'function' ? updateForTask(task) : null;+ row.innerHTML = '<div class="wbs-auto-row-head">' + check + '<div class="wbs-auto-name"' + (wbsBuiltinAutomationText(task, 'name') ? '' : ' data-wbs-i18n-skip="1"') + ' title="' + escAttr(task.name) + '">' + esc(task.name) + (update ? '<span class="wbs-auto-update-badge">有新版</span>' : '') + '</div>' +'<button type="button" class="wbs-auto-review" data-auto-review="' + escAttr(task.id) + '" title="安全评估"' + (automationState.reviewingId ? ' disabled' : '') + '>' + (automationState.reviewingId === task.id ? '评估中…' : '安全评估') + '</button>' +'<label class="wbs-switch wbs-auto-enabled" title="' + (task.manualRunnable ? '手动任务无需自动触发' : '启用自动触发') + '"' + (task.manualRunnable || task.compatible === false ? ' hidden' : '') + '><input type="checkbox" data-auto-enabled="' + escAttr(task.id) + '" aria-label="启用自动触发"' + (task.enabled ? ' checked' : '') + '><span class="wbs-switch-slider"></span></label></div>' +(task.description ? '<div class="wbs-auto-description"' + (wbsBuiltinAutomationText(task, 'description') ? '' : ' data-wbs-i18n-skip="1"') + ' title="' + escAttr(task.description) + '">' + esc(task.description) + '</div>' : '') +@@ -6161,9 +6703,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}matches.slice((page - 1) * pageSize, page * pageSize).forEach(function (task) {var item = document.createElement('section'); item.className = 'wbs-auto-discovery-item';- item.innerHTML = '<div class="wbs-auto-discovery-head"><div class="wbs-auto-discovery-name" data-wbs-i18n-skip="1"></div><span class="wbs-auto-discovery-version"></span></div><div class="wbs-auto-discovery-description" data-wbs-i18n-skip="1"></div><div class="wbs-auto-discovery-foot"><div class="wbs-auto-sources"></div><button class="wbs-modal-btn wbs-modal-ok" type="button" data-auto-discovery-import></button></div>';+ item.innerHTML = '<div class="wbs-auto-discovery-head"><div class="wbs-auto-discovery-name" data-wbs-i18n-skip="1"></div><span class="wbs-auto-discovery-version"></span><span class="wbs-auto-discovery-update" hidden>新版</span></div><div class="wbs-auto-discovery-description" data-wbs-i18n-skip="1"></div><div class="wbs-auto-discovery-foot"><div class="wbs-auto-sources"></div><button class="wbs-modal-btn wbs-modal-ok" type="button" data-auto-discovery-import></button></div>';item.querySelector('.wbs-auto-discovery-name').textContent = task.name || '未命名任务';- item.querySelector('.wbs-auto-discovery-version').textContent = 'API V' + (Number(task.schemaVersion) || 1);+ item.querySelector('.wbs-auto-discovery-version').textContent = task.packageVersion ? 'v' + task.packageVersion : 'API V' + (Number(task.schemaVersion) || 1);+ var installed = installedPackage(task.packageId);+ var installedInfo = importedPackage(installed);+ var hasUpdate = !!(installedInfo && task.packageVersion && comparePackageVersions(task.packageVersion, installedInfo.packageVersion) > 0);+ item.querySelector('.wbs-auto-discovery-update').hidden = !hasUpdate;var description = item.querySelector('.wbs-auto-discovery-description');description.textContent = task.description || '暂无说明';var sources = item.querySelector('.wbs-auto-sources');@@ -6181,8 +6727,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});var importButton = item.querySelector('[data-auto-discovery-import]');importButton.setAttribute('data-auto-discovery-import', task.key || '');+ importButton.setAttribute('data-auto-discovery-replace', hasUpdate ? '1' : '0');importButton.disabled = task.compatible === false;- importButton.textContent = task.compatible === false ? '不兼容' : '导入';+ importButton.textContent = task.compatible === false ? '不兼容' : hasUpdate ? '更新' : '导入';list.appendChild(item);});}@@ -6222,15 +6769,23 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}var button = event.target.closest && event.target.closest('[data-auto-discovery-import]');if (!button || button.disabled) return;- button.disabled = true; button.textContent = '导入中…';- api('/api/automations/discovery/import', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key: button.getAttribute('data-auto-discovery-import') }) }).then(function (result) {- closePanelModal(mask);- toast(result.imported ? '任务已导入,启用后生效' : '任务已存在,未重复导入', false, root);- return load();- }).catch(function (error) {- button.disabled = false; button.textContent = '导入';- toast(error.message || '导入失败', true, root);- });+ var replaceExisting = button.getAttribute('data-auto-discovery-replace') === '1';+ var submitImport = function () {+ button.disabled = true; button.textContent = '导入中…';+ api('/api/automations/discovery/import', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key: button.getAttribute('data-auto-discovery-import'), replaceExisting: replaceExisting }) }).then(function (result) {+ closePanelModal(mask);+ toast(result.replaced ? '任务已更新' : result.imported ? '任务已导入,启用后生效' : '任务已存在,未重复导入', false, root);+ return load();+ }).catch(function (error) {+ button.disabled = false; button.textContent = replaceExisting ? '更新' : '导入';+ toast(error.message || '导入失败', true, root);+ });+ };+ if (replaceExisting) {+ showAutomationConfirm('更新自动化任务?', '确认用公开仓库中的新版覆盖本地任务?', submitImport, '覆盖');+ return;+ }+ submitImport();});search.focus();}@@ -6240,6 +6795,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (button) { button.disabled = true; button.classList.add('is-loading'); button.querySelector('span').textContent = '正在发现…'; }return preloadAutomationDiscovery().then(function (result) {automationState.discovery = result;+ render();return result;}).catch(function (error) {automationState.discoveryError = error.message || '公开任务加载失败';@@ -6573,10 +7129,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {else if (button.hasAttribute('data-auto-copy')) { var copy = JSON.parse(JSON.stringify(task)); copy.id = 'task_' + Date.now().toString(36); copy.name = task.name + '(副本)'; showEditor(copy); }else if (button.hasAttribute('data-auto-delete')) showAutomationConfirm('删除该自动化任务?', '删除后无法恢复。', function () { api('/api/automations/bulk', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ids: [id], action: 'delete' }) }).then(load).catch(function (err) { toast(err.message || '删除失败', true, root); }); });});- registerDisposer(function () { if (automationState.pollTimer) clearInterval(automationState.pollTimer); if (automationState.reviewPollTimer) clearTimeout(automationState.reviewPollTimer); hideEditor(); root.querySelectorAll('.wbs-auto-dialog-mask').forEach(closePanelModal); });+ registerDisposer(function () { if (automationState.pollTimer) clearInterval(automationState.pollTimer); if (automationState.reviewPollTimer) clearTimeout(automationState.reviewPollTimer); if (automationPane.__wbsRefreshDiscovery === loadAutomationDiscovery) delete automationPane.__wbsRefreshDiscovery; hideEditor(); root.querySelectorAll('.wbs-auto-dialog-mask').forEach(closePanelModal); });load();loadAgentInfo();loadAutomationDiscovery();+ automationPane.__wbsRefreshDiscovery = loadAutomationDiscovery;automationState.pollTimer = setInterval(load, 2500);}@@ -6619,12 +7176,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {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' ? '正在同步会话' : job.status === 'done' ? '会话同步完成' : job.status === 'conflict' ? '会话同步完成,已保留分叉' : job.status === 'partial' ? '会话同步完成,部分项目失败' : '会话同步失败';var route = sessionCopyAccountLabel(job.sourceUid, job.sourceName) + ' → ' + sessionCopyAccountLabel(job.targetUid, job.targetName);var detail = route;if (active && job.currentLabel) detail += ' · ' + job.currentLabel;else if (job.status === 'done') detail += ' · 新同步 ' + (Number(job.copied) || 0) + ',已存在 ' + (Number(job.skipped) || 0);- else if (job.status === 'conflict') detail += ' · ' + (Number(job.conflicts) || 1) + ' 个会话两边都修改过,未覆盖任何一边';+ else if (job.status === 'conflict') detail += ' · ' + (Number(job.conflicts) || 1) + ' 个会话已分叉,已保留双方内容';else if (job.status === 'partial') detail += ' · 有 ' + ((Number(job.failed) || 0) + (Number(job.partial) || 0)) + ' 项需要留意';else if (job.status === 'error') detail += ' · 请稍后重试';box.className = 'wbs-sess-copy-progress is-' + String(job.status || 'running');@@ -6655,21 +7212,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {sessionsPane.innerHTML ='<div class="wbs-pcard">' +'<div class="wbs-sess-filters">' +- '<div class="wbs-sess-filter-row"><span class="wbs-sess-flabel">账号</span><select class="wbs-sess-select" id="wbs-sess-account-select" title="选择要查看的账号"><option value="">加载中…</option></select></div>' +- '<div class="wbs-sess-filter-row"><span class="wbs-sess-flabel">时间</span><div class="wbs-sess-seg" id="wbs-sess-range-seg">' +- '<button class="wbs-sess-seg-btn" type="button" data-range="today">今天</button>' +- '<button class="wbs-sess-seg-btn" type="button" data-range="7d">近 7 天</button>' +- '<button class="wbs-sess-seg-btn" type="button" data-range="30d">近 30 天</button>' +- '<button class="wbs-sess-seg-btn active" type="button" data-range="all">全部</button>' ++ '<button class="wbs-sess-auto-all" type="button" id="wbs-sess-auto-all" role="checkbox" aria-checked="false" aria-label="自动同步所有会话" title="切换账号时自动同步当前账号的所有会话,包括之后新增的会话">' ++ '<span class="wbs-sess-auto-all-box" aria-hidden="true"><svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="12" height="12" rx="2"/><path class="wbs-sess-auto-all-check" d="m4.5 8 2.2 2.2L11.5 5.5"/></svg></span>' ++ '<span class="wbs-sess-auto-all-label">自动同步所有会话</span>' ++ '</button>' ++ '<div class="wbs-sess-filter-row wbs-sess-account-filter"><span class="wbs-sess-flabel">账号</span><select class="wbs-sess-select" id="wbs-sess-account-select" title="选择要查看的账号"><option value="">加载中…</option></select></div>' ++ '<div class="wbs-sess-filter-row wbs-sess-time-filter"><span class="wbs-sess-flabel">时间</span><div class="wbs-usage-segment wbs-sess-seg" id="wbs-sess-range-seg">' ++ '<button class="wbs-sess-seg-btn" type="button" aria-pressed="false" data-range="today">今天</button>' ++ '<button class="wbs-sess-seg-btn" type="button" aria-pressed="false" data-range="7d">近 7 天</button>' ++ '<button class="wbs-sess-seg-btn" type="button" aria-pressed="false" data-range="30d">近 30 天</button>' ++ '<button class="wbs-sess-seg-btn active" type="button" aria-pressed="true" data-range="all">全部</button>' +'</div></div>' +'</div>' +'<div class="wbs-sess-toolbar">' +'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-batch">批量操作</button>' +'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-import" title="从加密文件导入会话">' + IMPORT_ICON + '<span>导入</span></button>' +- '<button class="wbs-sess-auto-all" type="button" id="wbs-sess-auto-all" role="checkbox" aria-checked="false" aria-label="自动同步所有会话" title="切换账号时自动同步当前账号的所有会话,包括之后新增的会话">' +- '<span class="wbs-sess-auto-all-box" aria-hidden="true"><svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="12" height="12" rx="2"/><path class="wbs-sess-auto-all-check" d="m4.5 8 2.2 2.2L11.5 5.5"/></svg></span>' +- '<span class="wbs-sess-auto-all-label">自动同步所有会话</span>' +- '</button>' +'<span class="wbs-sess-count" id="wbs-sess-count"></span>' +'<div class="wbs-sess-batchbar" id="wbs-sess-batchbar" style="display:none">' +'<button class="wbs-sess-bbtn wbs-sess-check-all" type="button" id="wbs-sess-check-all">全选</button>' +@@ -6872,6 +7429,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var button = sessionsPane.querySelector('#wbs-sess-auto-all');if (!button) return;var enabled = !!sessionsState.autoCopyAll;+ button.disabled = !!sessionsState.batchMode || !!sessionsState.autoCopyAllBusy;button.classList.toggle('active', enabled);button.setAttribute('aria-checked', enabled ? 'true' : 'false');}@@ -6880,7 +7438,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!button || button.disabled) return;var previous = !!sessionsState.autoCopyAll;sessionsState.autoCopyAll = !!enabled;- button.disabled = true;+ sessionsState.autoCopyAllBusy = true;renderSessions();api('/api/sessions/auto-copy-all', {method: 'POST',@@ -6888,12 +7446,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {body: JSON.stringify({ enabled: !!enabled }),}).then(function (response) {sessionsState.autoCopyAll = !!(response && response.autoCopyAll);- button.disabled = false;+ sessionsState.autoCopyAllBusy = false;renderSessions();toast(sessionsState.autoCopyAll ? '已开启自动同步所有会话' : '已关闭自动同步所有会话', false, root);}).catch(function (e) {sessionsState.autoCopyAll = previous;- button.disabled = false;+ sessionsState.autoCopyAllBusy = false;renderSessions();toast('自动同步所有会话设置失败: ' + (e.message || e), true, root);});@@ -7055,18 +7613,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}// 事件绑定(元素在 buildSessionsPane 之后才存在)- // 批量模式工具栏切换:开启时隐藏「批量操作/count/刷新」并在同一行显示批量操作按钮;- // 关闭时恢复。批量按钮行与筛选行共用 toolbar,不再另起一行。+ // 批量模式保留顶部筛选和工具栏,禁用控件并在下方显示批量操作。function setSessBatchBar(on) {var bar = sessionsPane.querySelector('#wbs-sess-batchbar');- var bb = sessionsPane.querySelector('#wbs-sess-batch');- var importBtn = sessionsPane.querySelector('#wbs-sess-import');- var autoCopyAllBtn = sessionsPane.querySelector('#wbs-sess-auto-all');- var cnt = sessionsPane.querySelector('#wbs-sess-count');- if (bb) { bb.style.display = on ? 'none' : ''; bb.classList.toggle('active', on); }- if (importBtn) importBtn.style.display = on ? 'none' : '';- if (autoCopyAllBtn) autoCopyAllBtn.style.display = on ? 'none' : '';- if (cnt) cnt.style.display = on ? 'none' : '';+ sessionsPane.querySelectorAll('.wbs-sess-filters button,.wbs-sess-filters select,#wbs-sess-batch,#wbs-sess-import').forEach(function (control) {+ control.disabled = !!on;+ });+ updateAutoCopyAllButton();if (bar) bar.style.display = on ? 'flex' : 'none';}@@ -7082,15 +7635,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (rangeSeg) {rangeSeg.addEventListener('click', function (e) {var b = e.target.closest ? e.target.closest('.wbs-sess-seg-btn') : null;- if (!b) return;- rangeSeg.querySelectorAll('.wbs-sess-seg-btn').forEach(function (x) { x.classList.toggle('active', x === b); });+ if (!b || b.disabled || sessionsState.batchMode) return;+ rangeSeg.querySelectorAll('.wbs-sess-seg-btn').forEach(function (x) {+ var active = x === b;+ x.classList.toggle('active', active);+ x.setAttribute('aria-pressed', String(active));+ });sessionsState.range = b.getAttribute('data-range');sessionsState.selected = {};sessionsState.wsExpanded = {};loadSessions();});}- // 批量操作:进入批量模式(工具栏右侧按钮隐藏,批量按钮在同一行原位显示)。退出通过「取消」按钮+ // 批量操作:禁用顶部控件,退出通过「取消」按钮。var batchBtn = sessionsPane.querySelector('#wbs-sess-batch');if (batchBtn) {batchBtn.addEventListener('click', function () {@@ -7292,8 +7849,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ ids: ids, targetUid: sel.value }),- }).then(function () {- toast('已同步 ' + ids.length + ' 个会话', false, root);+ }).then(function (result) {+ toast(sessionCopySummaryText(result), false, root);showSessModal(false);loadSessions();}).catch(function (e) {@@ -7988,6 +8545,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<label class="wbs-switch" title="在会话左侧显示消息索引"><input type="checkbox" id="wbs-sess-message-nav"><span class="wbs-switch-slider"></span></label>' +'</div>' +'<div class="wbs-nd-row">' ++ '<span class="wbs-nd-title">会话用量汇总</span>' ++ '<span class="wbs-nd-hint">在会话底部显示 Token、积分和模型汇总</span>' ++ '<label class="wbs-switch" title="在会话底部显示 Token、积分和模型汇总"><input type="checkbox" id="wbs-sess-usage-summary"><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-fork" aria-label="分支到新会话"><span class="wbs-switch-slider"></span></label>' +@@ -8879,6 +9441,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function setOpen(open, options) {if (open && typeof closeRotationNotice === 'function') closeRotationNotice();+ if (open) {+ // 打开 WorkDaddy 面板时,复制会话进度提示会遮挡面板入口区域,立即收起并停止后续轮询。+ if (typeof closeSessionCopyNotice === 'function') closeSessionCopyNotice();+ if (state.sessionCopyNoticePollTimer) {+ clearTimeout(state.sessionCopyNoticePollTimer);+ state.sessionCopyNoticePollTimer = null;+ }+ }if (open && window.__wbsAutomationInputActive) {toast('正在输入或切换账号,请稍后打开面板', false, root);return;@@ -8895,7 +9465,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {fab.classList.toggle('hidden', open); // 打开时隐藏按钮fabQuietMode.wake();if (open) {- if (newlyOpened && typeof preloadAutomationDiscovery === 'function') preloadAutomationDiscovery().catch(function () {});+ if (newlyOpened && typeof automationPane !== 'undefined' && automationPane && automationPane.__wbsRefreshDiscovery) automationPane.__wbsRefreshDiscovery();+ else if (newlyOpened && typeof preloadAutomationDiscovery === 'function') preloadAutomationDiscovery().catch(function () {});if (newlyOpened && !(options && options.automation)) api('/api/automations/events', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ type: 'panelOpened' }) }).catch(function () {});if (newlyOpened) state.dailyProgressForceNext = true;refresh();@@ -11688,6 +12259,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {writeMessageNavigationEnabled(sessState.messageNav);if (messageNavigation) messageNavigation.setEnabled(sessState.messageNav);});+ var swU = pane2.querySelector('#wbs-sess-usage-summary');+ if (swU) {+ swU.checked = conversationUsageEnabled;+ swU.addEventListener('change', function () {+ sessState.usageSummary = !!this.checked;+ setConversationUsageEnabled(sessState.usageSummary);+ });+ }var swQ = pane2.querySelector('#wbs-sess-selection-quote');if (swQ) swQ.addEventListener('change', function () {sessState.selectionQuote = !!this.checked;@@ -12123,6 +12702,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (discoverSleepSessionBusy()) return true;return !!isSessionBusy(null).busy;}+ var sessionBusyProbe = function () { return alive ? isAnySessionBusy() : null; };+ window.__wbsAnySessionBusy = sessionBusyProbe;+ registerDisposer(function () { if (window.__wbsAnySessionBusy === sessionBusyProbe) delete window.__wbsAnySessionBusy; });function startUntilDoneCheck() {if (sleepUntilDoneCheck) return;sleepUntilDoneSession = null;@@ -12228,6 +12810,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return (source || '积分') + '\n' + amount + '\n' + expiryLine;}+ function creditSummaryTip(segment) {+ var accountName = segment.accountName || '未命名账号';+ var lines = creditTip(segment).split('\n');+ return (lines[0] || '积分') + '\n' + (lines[1] || '') + '\n' + (lines[2] || '') + '\n' + accountName;+ }+function creditBarHtml(credits, segments) {var list = Array.isArray(segments) ? segments.filter(function (s) { return s && Number(s.remaining) > 0; }) : [];if (!list.length && Number(credits) > 0) {@@ -12673,7 +13261,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function sessionCopySummaryText(job) {return '同步 ' + (Number(job && job.copied) || 0) + ' · 跳过 ' + (Number(job && job.skipped) || 0) +- ' · 失败 ' + sessionCopyFailedItems(job) + ' · 冲突 ' + (Number(job && job.conflicts) || 0);+ ' · 失败 ' + (sessionCopyFailedItems(job) + (Number(job && job.conflicts) || 0));}function showSessionCopyDetails(job) {@@ -12683,12 +13271,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {mask.className = 'wbs-modal-mask wbs-session-copy-details-modal';mask.setAttribute('role', 'presentation');var details = Array.isArray(job.details) ? job.details : [];- var statusLabels = { copied: '已同步', skipped: '已跳过', partial: '部分失败', failed: '失败', conflict: '冲突', running: '处理中' };+ 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: 'conflict', label: '冲突', count: details.filter(function (item) { return item && item.status === 'conflict'; }).length },- { id: 'failed', label: '失败', count: details.filter(function (item) { return item && (item.status === 'failed' || item.status === 'partial'); }).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">' +'<div class="wbs-auto-modal-head"><div><div class="wbs-modal-title" id="wbs-session-copy-details-title">会话同步明细</div><div class="wbs-session-copy-details-summary"></div></div>' +@@ -12705,11 +13292,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var renderTab = function (tabId) {var filtered = details.filter(function (item) {var status = String(item && item.status || 'running');- return tabId === 'failed' ? (status === 'failed' || status === 'partial') : status === tabId;+ return tabId === 'failed' ? (status === 'failed' || status === 'partial' || status === 'conflict') : status === tabId;});var rows = filtered.map(function (item) {var status = String(item && item.status || 'running');- var note = status === 'conflict' ? '两边都修改过,未覆盖' : status === 'partial' ? '部分文件失败' : (item && item.error ? item.error : '');+ var note = status === 'copied' && item && item.branched ? '已复制分叉副本,原会话已保留' : status === 'conflict' ? '分叉会话尚未同步,请重试' : status === 'partial' ? '部分文件失败' : (item && item.error ? item.error : '');return '<div class="wbs-session-copy-detail-row is-' + escAttr(status) + '">' +'<span class="wbs-session-copy-detail-status">' + esc(statusLabels[status] || status) + '</span>' +'<span class="wbs-session-copy-detail-label" title="' + escAttr(item && item.label || '') + '">' + esc(item && item.label || '未命名会话') + '</span>' +@@ -12788,7 +13375,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {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' ? '同步等待中' : active ? '正在同步会话' : job.status === 'done' ? '同步完成' : job.status === 'conflict' ? '同步完成,发现冲突' : job.status === 'partial' ? '同步完成,部分失败' : '同步失败';+ var title = job.status === 'queued' ? '同步等待中' : active ? '正在同步会话' : job.status === 'done' ? '同步完成' : job.status === 'conflict' ? '同步完成,已保留分叉' : job.status === 'partial' ? '同步完成,部分失败' : '同步失败';var sourceLabel = sessionCopyAccountLabel(job.sourceUid, job.sourceName);var targetLabel = accountName || sessionCopyAccountLabel(job.targetUid, job.targetName);var status = active ? '正在把已标记的会话从「' + sourceLabel + '」同步到「' + targetLabel + '」' :@@ -12809,14 +13396,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {placeSessionCopyNotice();if (!active && !notice.closeScheduled) {notice.closeScheduled = true;- var remaining = 10;+ var remaining = 5;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, 10000);+ notice.timer = setBuildTimeout(closeSessionCopyNotice, 5000);}}@@ -12825,6 +13412,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {state.sessionCopyNoticePollTimer = null;var endpoint = jobId ? '/api/sessions/auto-copy/status?id=' + encodeURIComponent(jobId) : '/api/sessions/auto-copy/active';api(endpoint).then(function (result) {+ if (state.open) {+ closeSessionCopyNotice();+ if (state.sessionCopyNoticePollTimer) {+ clearTimeout(state.sessionCopyNoticePollTimer);+ state.sessionCopyNoticePollTimer = null;+ }+ return;+ }var job = result && result.job;if (!job) {// Account switching reloads the renderer before the daemon enqueues@@ -12849,6 +13444,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {setBuildTimeout(refresh, 900);}}).catch(function () {+ if (state.open) return;state.sessionCopyNoticePollTimer = setBuildTimeout(function () { pollSessionCopyNotice(jobId, accountName); }, 1200);});}@@ -13091,6 +13687,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {.then(function (data) {if (!alive || requestId !== state.accountRefreshId) return;render(data);+ // WorkBuddy can complete today's check-in outside WorkDaddy. Ask the+ // idempotent official endpoint for the current account only, then+ // patch that card in place so read-only account snapshots stay read-only.+ if (!WBS_PROFILE_IS_AI && CAPS.checkin !== false && data.current && data.current.uid) {+ api('/api/accounts/checkin-sync', {+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}',+ }).then(function (sync) {+ if (!alive || requestId !== state.accountRefreshId || !sync || !sync.result) return;+ var result = sync.result;+ var current = state.accounts.filter(function (account) { return String(account.uid) === String(result.uid || data.current.uid); })[0];+ if (!current) return;+ current.checkin = { ok: !!result.ok, inactive: !!result.inactive, code: result.code, message: result.message };+ updateCheckinCells([current]);+ }).catch(function () {});+ }fetchCreditsForAccounts();fetchActivityForAccounts();fetchDailyProgressForAccounts(forceDailyProgress);@@ -13754,6 +14365,31 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-root{position:fixed;right:22px;bottom:22px;z-index:2147483647;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;font-size:13px;color:#1f1f1f;-webkit-font-smoothing:antialiased}','.wbs-root,.wbs-status-popover,.wbs-credit-summary-popover,#wbs-token-stats-modal{--wbs-primary:#22c55e;--wbs-primary-rgb:34,197,94;--wbs-primary-ink:#22c55e;--wbs-primary-soft:rgba(34,197,94,.09);--wbs-primary-soft-hover:rgba(34,197,94,.14)}','html[data-wbs-theme-id="dark"] .wbs-root,html[data-wbs-theme-id="dark"] .wbs-status-popover,html[data-wbs-theme-id="dark"] .wbs-credit-summary-popover,html[data-wbs-theme-id="dark"] #wbs-token-stats-modal,html[data-wbs-theme-id="cyber-purple"] .wbs-root,html[data-wbs-theme-id="cyber-purple"] .wbs-status-popover,html[data-wbs-theme-id="cyber-purple"] .wbs-credit-summary-popover,html[data-wbs-theme-id="cyber-purple"] #wbs-token-stats-modal,html[data-wbs-theme-id="nebula"] .wbs-root,html[data-wbs-theme-id="nebula"] .wbs-status-popover,html[data-wbs-theme-id="nebula"] .wbs-credit-summary-popover,html[data-wbs-theme-id="nebula"] #wbs-token-stats-modal{--wbs-primary:#7f77dd;--wbs-primary-rgb:127,119,221;--wbs-primary-ink:#7f77dd;--wbs-primary-soft:rgba(127,119,221,.12);--wbs-primary-soft-hover:rgba(127,119,221,.18)}',+ '.wbs-session-usage-summary{position:fixed;z-index:20;display:block;box-sizing:border-box;min-height:28px;padding:4px 8px 2px;border:0;border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 52%,transparent);color:var(--wb-color-text-primary,#1f1f1f);font-size:13px;font-weight:400;line-height:1.35;opacity:.72;box-shadow:none;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);outline:none;cursor:pointer;transition:opacity .15s ease}',+ '.wbs-session-usage-summary:hover,.wbs-session-usage-summary:focus-visible{opacity:.96}',+ '.wbs-session-usage-summary.is-hidden{visibility:hidden;opacity:0;pointer-events:none}',+ '.wbs-session-usage-main{display:flex;align-items:center;justify-content:flex-start;gap:7px;min-width:0;overflow:hidden;text-align:left;white-space:nowrap}',+ '.wbs-session-usage-label{flex:0 0 auto;color:var(--wb-color-text-secondary,#5f6368);font-weight:400}',+ '.wbs-session-usage-number{flex:0 0 auto;color:var(--wb-color-text-primary,#1f1f1f);font-variant-numeric:tabular-nums;font-weight:400}',+ '.wbs-session-usage-separator{flex:0 0 auto;color:var(--wb-icon-tertiary,#969aa3)}',+ '.wbs-session-usage-models{min-width:0;overflow:hidden;color:var(--wb-color-text-secondary,#5f6368);text-overflow:ellipsis;white-space:nowrap}',+ '.wbs-session-usage-loading{color:var(--wb-icon-secondary,#667085);font-weight:400}',+ '.wbs-session-usage-popover{position:fixed;z-index:21;width:min(390px,calc(100vw - 16px));box-sizing:border-box;padding:10px 12px;border:0;border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 90%,transparent);color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 6px 18px rgba(20,24,32,.16);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);opacity:0;pointer-events:none;transform:translateY(4px);transition:opacity .14s ease,transform .14s ease}',+ '.wbs-session-usage-popover.is-visible{opacity:1;pointer-events:auto;transform:translateY(0)}',+ '.wbs-session-usage-detail-title{font-size:14px;font-weight:700;line-height:1.4}',+ '.wbs-session-usage-detail-total{margin-top:4px;color:var(--wb-color-text-secondary,#5f6368);font-size:12.5px;font-variant-numeric:tabular-nums}',+ '.wbs-session-usage-detail-note{margin-top:6px;color:var(--wb-color-text-secondary,#5f6368);font-size:11px;line-height:1.45}',+ '.wbs-session-usage-detail-head,.wbs-session-usage-detail-row{display:grid;grid-template-columns:minmax(0,1fr) 42px 58px 48px;gap:7px;align-items:center}',+ '.wbs-session-usage-detail-head{margin-top:10px;padding:6px 0;border-top:1px solid var(--wb-border-subtle,#eee);border-bottom:1px solid var(--wb-border-subtle,#eee);color:var(--wb-color-text-secondary,#5f6368);font-size:12px}',+ '.wbs-session-usage-detail-head span,.wbs-session-usage-detail-row span{text-align:left}',+ '.wbs-session-usage-detail-row{min-height:32px;border-bottom:1px solid var(--wb-border-subtle,#eee);color:var(--wb-color-text-secondary,#5f6368);font-size:12px;font-variant-numeric:tabular-nums}',+ '.wbs-session-usage-detail-row:last-child{border-bottom:0}',+ '.wbs-session-usage-model{min-width:0;overflow:hidden;color:var(--wb-color-text-primary,#1f1f1f);text-overflow:ellipsis;white-space:nowrap}',+ '.wbs-session-usage-empty{padding:10px 0;color:var(--wb-color-text-secondary,#5f6368);font-size:12px}',+ '.wbs-session-usage-spacer{display:block;width:100%;height:28px;min-height:28px;pointer-events:none;visibility:hidden}',+ 'html.cb-dark .wbs-session-usage-summary,html[data-theme="dark"] .wbs-session-usage-summary,body[data-vscode-theme-name*="dark" i] .wbs-session-usage-summary{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 80%,transparent);color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 5px 18px rgba(0,0,0,.2)}',+ 'html.cb-dark .wbs-session-usage-popover,html[data-theme="dark"] .wbs-session-usage-popover,body[data-vscode-theme-name*="dark" i] .wbs-session-usage-popover{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 92%,transparent);color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 8px 22px rgba(0,0,0,.32)}',+ '@media(max-width:620px){.wbs-session-usage-summary{padding-left:8px;padding-right:8px}.wbs-session-usage-main{gap:5px}.wbs-session-usage-popover{width:calc(100vw - 16px)}}','.wbs-daily-rings,.wbs-status-popover{--wbs-ring-growth:var(--wbs-primary-ink);--wbs-ring-rewards:var(--wbs-primary-ink);--wbs-ring-cat:var(--wbs-primary-ink);--wbs-tip-credit:var(--wbs-primary-ink);--wbs-liquid-fill:var(--wbs-primary);--wbs-liquid-bg:color-mix(in srgb,var(--wbs-primary) 12%,var(--wb-bg-secondary,#f6f7f8));--wbs-liquid-ink:color-mix(in srgb,var(--wbs-primary-ink) 72%,var(--wb-color-text-primary,#1f1f1f))}','.wbs-root.wbs-no-stash .wbs-stash-inline{display:none !important}','.wbs-fork-button{display:flex;flex:0 0 24px;align-items:center;justify-content:center;width:24px;height:24px;box-sizing:border-box;padding:0;border:0;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,rgba(0,0,0,.7));cursor:pointer;transition:color .15s ease,background-color .15s ease}',@@ -13906,7 +14542,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-daily-streak-label{font-size:10.5px;line-height:1;font-weight:600;white-space:nowrap;font-variant-numeric:tabular-nums;color:inherit}.wbs-daily-streak-label.is-pending{color:var(--wb-icon-tertiary,#7c818b);font-weight:500}.wbs-daily-rings.is-loading .wbs-daily-vessel{opacity:.58}.wbs-daily-rings.is-loading .wbs-daily-cat-mark{animation:wbs-daily-cat-pulse 1.2s ease-in-out infinite}@keyframes wbs-daily-cat-pulse{50%{opacity:.45}}','.wbs-status-popover{position:fixed;z-index:2147483647;width:306px;box-sizing:border-box;padding:12px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.14));border-radius:11px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 96%,transparent);color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 16px 42px rgba(20,24,32,.16),inset 0 1px 0 rgba(255,255,255,.5);backdrop-filter:blur(20px) saturate(1.08);-webkit-backdrop-filter:blur(20px) saturate(1.08);font:12px/1.45 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;pointer-events:auto}.wbs-status-popover.is-daily{width:620px;max-width:calc(100vw - 16px);max-height:calc(100vh - 16px);overflow-y:auto;overscroll-behavior:contain;scrollbar-width:none}','.wbs-status-popover.is-daily::-webkit-scrollbar,.wbs-growth-task-list::-webkit-scrollbar{display:none}',- '.wbs-status-popover.is-passive{pointer-events:none}.wbs-status-popover[hidden]{display:none!important}.wbs-daily-popover-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:9px}.wbs-daily-popover-head strong{font-size:13px;font-weight:700;white-space:nowrap}.wbs-daily-popover-head span{color:var(--wb-icon-tertiary,#7c818b);font-size:10px;font-variant-numeric:tabular-nums}.wbs-daily-refresh-time{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}',+ '.wbs-status-popover.is-passive{pointer-events:none}.wbs-status-popover.is-credit{height:auto;min-height:0;max-height:calc(100vh - 16px);overflow:auto;overflow-wrap:anywhere}.wbs-status-popover[hidden]{display:none!important}.wbs-daily-popover-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:9px}.wbs-daily-popover-head strong{font-size:13px;font-weight:700;white-space:nowrap}.wbs-daily-popover-head span{color:var(--wb-icon-tertiary,#7c818b);font-size:10px;font-variant-numeric:tabular-nums}.wbs-daily-refresh-time{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}','.wbs-daily-refresh-spinner{width:9px;height:9px;box-sizing:border-box;border:1.5px solid color-mix(in srgb,var(--wbs-ring-growth) 25%,transparent);border-top-color:var(--wbs-ring-growth);border-radius:50%;animation:wbs-daily-spin .72s linear infinite}@keyframes wbs-daily-spin{to{transform:rotate(360deg)}}','.wbs-daily-detail{display:grid;grid-template-columns:8px 72px minmax(0,1fr);align-items:center;gap:7px;min-height:31px;margin-top:5px;padding:0 9px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent)}','.wbs-daily-detail i,.wbs-credit-tip-value i{display:block;width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 2px color-mix(in srgb,currentColor 17%,transparent)}.wbs-daily-detail i.growth{color:var(--wbs-ring-growth)}.wbs-daily-detail i.cat{color:var(--wbs-ring-cat)}.wbs-daily-detail i.credit{color:var(--wbs-tip-credit)}.wbs-daily-detail>span{color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-daily-detail b{min-width:0;text-align:right;font-size:11px;font-weight:650;overflow-wrap:anywhere}.wbs-daily-detail.cat-row b{white-space:nowrap;font-variant-numeric:tabular-nums}.wbs-daily-cat-value{display:flex;min-width:0;align-items:center;justify-content:flex-end;gap:8px}.wbs-travel-claim{flex:0 0 auto}',@@ -13917,6 +14553,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-daily-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:4px;margin-top:4px}.wbs-daily-action{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:7px;min-height:29px;padding:3px 5px 3px 8px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:7px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent)}.wbs-daily-action span{min-width:0;color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-daily-action b{color:var(--wb-color-text-primary,#1f1f1f);font-size:11px;font-weight:650;white-space:nowrap}.wbs-daily-action-button{min-width:46px}','.wbs-growth-rewards{margin-top:8px;padding:8px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 46%,transparent)}.wbs-growth-rewards-head,.wbs-growth-tier{display:grid;align-items:center;column-gap:8px}.wbs-growth-rewards-head{grid-template-columns:minmax(0,1fr) auto;padding-bottom:6px;border-bottom:1px solid var(--wb-border-subtle,rgba(20,24,32,.1))}.wbs-growth-rewards-head span{font-weight:650;white-space:nowrap}.wbs-growth-rewards-head em{font-size:10px;font-style:normal;color:var(--wb-icon-tertiary,#7c818b);white-space:nowrap}.wbs-growth-tier{grid-template-columns:52px 38px minmax(0,1fr);min-height:24px;color:var(--wb-color-text-secondary,#5f6368);font-size:10.5px}.wbs-growth-tier span,.wbs-growth-tier em,.wbs-growth-tier b{white-space:nowrap}.wbs-growth-tier em{font-style:normal;color:var(--wb-icon-tertiary,#7c818b)}.wbs-growth-tier b{text-align:right;color:var(--wb-color-text-secondary,#5f6368);font-weight:650}.wbs-growth-tier.is-claimed b{color:var(--wb-icon-tertiary,#7c818b)}','.wbs-status-popover button:not([disabled]){cursor:pointer}',+ '.wbs-credit-tip-account{margin:-4px 0 8px;color:var(--wb-icon-tertiary,#8a8f98);font-size:10px;line-height:1.35;overflow-wrap:anywhere}','.wbs-credit-tip-value{display:flex;align-items:center;gap:8px;padding:8px 9px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent);color:var(--wb-color-text-primary,#1f1f1f)}.wbs-credit-tip-value i.credit{color:var(--wbs-tip-credit)}.wbs-credit-tip-value b{font-size:12px;font-variant-numeric:tabular-nums}.wbs-credit-tip-value+.wbs-daily-manual{margin-top:11px}','.wbs-daily-popover-empty,.wbs-daily-refresh-error{margin-top:8px;padding-top:8px;border-top:1px solid var(--wb-border-subtle,rgba(20,24,32,.12));color:var(--wb-icon-secondary,#667085);font-size:10.5px;line-height:1.55;overflow-wrap:anywhere}.wbs-daily-refresh-error{color:var(--wb-color-text-secondary,#5f6368)}','html.cb-dark .wbs-status-popover,html[data-theme="dark"] .wbs-status-popover,body[data-vscode-theme-name*="dark" i] .wbs-status-popover{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 88%,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)}',@@ -14136,7 +14773,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-auto-row-head{display:flex;align-items:center;gap:8px;min-width:0}.wbs-auto-enabled{flex-shrink:0}.wbs-auto-enabled[hidden]{display:none!important}.wbs-auto-description{color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.5;overflow-wrap:anywhere;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden}.wbs-auto-row-foot{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px}.wbs-auto-details{min-width:0}.wbs-auto-triggers{display:flex;flex-wrap:wrap;gap:4px}.wbs-auto-trigger-chip{display:inline-flex;max-width:100%;padding:2px 6px;border:1px solid var(--wb-border-subtle,#e7e7e7);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font-size:10px;line-height:1.4;overflow-wrap:anywhere}.wbs-auto-state-line{display:flex;align-items:center;flex-wrap:wrap;gap:4px 8px;min-height:16px;margin-top:5px;color:var(--wb-icon-tertiary,#888);font-size:10px}.wbs-auto-state{display:inline-flex;align-items:center;gap:4px}.wbs-auto-state:before{content:"";width:4px;height:4px;flex:0 0 4px;border-radius:50%;background:currentColor}.wbs-auto-state.running{color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-auto-state.off{opacity:.65}.wbs-auto-last-run.failed{color:var(--wb-color-text-primary,#222)}.wbs-auto-icon:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:1px}','.wbs-auto-row:hover{background:var(--wb-bg-hover,#f5f5f5)}','.wbs-auto-check{display:flex;align-items:center;justify-content:center;flex:0 0 20px;cursor:pointer}.wbs-auto-check input{accent-color:var(--wb-button-primary-bg,#1f1f1f)}',- '.wbs-auto-main{min-width:0;flex:1}.wbs-auto-name{display:block;flex:1;min-width:0;font-size:12px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',+ '.wbs-auto-main{min-width:0;flex:1}.wbs-auto-name{display:flex;align-items:center;gap:6px;flex:1;min-width:0;font-size:12px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.wbs-auto-update-badge,.wbs-auto-discovery-update{flex:0 0 auto;padding:2px 5px;border:1px solid var(--wb-accent-blue,#4f86ff);border-radius:5px;background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 12%,transparent);color:var(--wb-accent-blue,#4f86ff);font-size:10px;font-weight:600;line-height:1.2;white-space:nowrap}.wbs-auto-update-badge{overflow:visible}','.wbs-auto-review{flex:0 0 auto;min-width:64px;height:25px;padding:0 6px;border:1px solid var(--wb-border-default,#ddd);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font:inherit;font-size:11px;cursor:pointer}.wbs-auto-review:hover{background:var(--wb-bg-hover,#eee);color:var(--wb-color-text-primary,#222)}.wbs-auto-review:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}.wbs-auto-review:disabled{opacity:.6;cursor:wait}','.wbs-auto-status{flex:0 0 auto;padding:2px 6px;border-radius:999px;font-size:10px;font-weight:500}.wbs-auto-status.on{color:#1b7f56;background:rgba(46,190,126,.14)}.wbs-auto-status.off{color:var(--wb-icon-tertiary,#888);background:var(--wb-bg-tertiary,#f1f1f1)}','.wbs-auto-meta{margin-top:3px;color:var(--wb-icon-tertiary,#999);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',@@ -14167,11 +14804,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-nd-title{font-size:12px;font-weight:600;color:var(--wb-color-text-primary,#1f1f1f);white-space:nowrap}','.wbs-nd-hint{font-size:11px;color:var(--wb-icon-tertiary,#999);text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',/* 会话页:筛选 + 批量 + 列表 + 迁移/删除弹窗 */- '.wbs-sess-filters{display:flex;flex-direction:row;align-items:center;gap:8px;margin-bottom:10px}',- // 账号 + 时间筛选同一行:账号下拉缩窄,时间分段占用剩余宽度- '.wbs-sess-filter-row{display:flex;align-items:center;gap:8px;flex:0 0 auto}',- '.wbs-sess-filter-row:last-child{flex:1 1 auto;min-width:0}',- '#wbs-sess-account-select{max-width:112px}',+ '.wbs-sess-filters{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:10px;min-width:0}',+ '.wbs-sess-account-filter{flex:0 1 190px;min-width:150px}',+ '.wbs-sess-time-filter{flex:1 1 240px;min-width:0}',/* 会话页/模型页:卡片与列表贴底,减少底部留白 */'.wbs-pane[data-pane="sessions"]{padding-bottom:1px}','.wbs-pane[data-pane="sessions"] > .wbs-pcard{margin-bottom:0;padding-bottom:4px}',@@ -14189,8 +14824,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-select:hover{border-color:var(--wb-border-strong,#bbb)}','.wbs-sess-select:focus{outline:none;border-color:var(--wb-accent-blue,#4f86ff)}',/* 时间筛选:Segment 组件(容器灰底 + 激活黑块,与主题页 segmented 一致) */- '.wbs-sess-seg{display:flex;flex:1;min-width:0;background:var(--wb-bg-tertiary,#f0f0f0);border-radius:10px;padding:3px;gap:3px}',- '.wbs-sess-seg-btn{flex:1;padding:6px 4px;border:none;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;font-family:inherit;white-space:nowrap}',+ '.wbs-sess-time-filter .wbs-sess-seg{display:flex;flex:1 1 auto;width:auto;max-width:none;min-width:0}',+ '.wbs-sess-time-filter .wbs-sess-seg button{flex:1 1 0;min-width:0;padding:0 4px}',+ '.wbs-sess-seg-btn{flex:0 0 auto;padding:6px 4px;border:none;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;font-family:inherit;white-space:nowrap}','.wbs-sess-seg-btn:hover{color:var(--wb-color-text-primary,#1f1f1f)}','.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}',@@ -14213,7 +14849,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-auto-all.active .wbs-sess-auto-all-box{color:var(--wb-button-primary-bg,#1f1f1f)}','.wbs-sess-auto-all.active .wbs-sess-auto-all-check{opacity:1}','.wbs-sess-auto-all-label{white-space:nowrap}',+ '.wbs-sess-account-filter .wbs-sess-select{width:100%;max-width:none}','.wbs-sess-batchbar{display:flex;align-items:center;gap:5px;flex-wrap:wrap;min-width:0;margin:0;padding:0;border:none;background:transparent}',+ '#wbs-sess-batchbar{flex-basis:100%}',+ '.wbs-sess-filters button:disabled,.wbs-sess-filters select:disabled,#wbs-sess-batch:disabled,#wbs-sess-import:disabled{opacity:.45;cursor:not-allowed;pointer-events:none}','.wbs-sess-done{margin-left:auto;color:#fff;background:#141416;border-color:#141416}','.wbs-sess-done:hover{background:#2a2a2e;color:#fff}',/* 删除按钮:图标按钮,尺寸与兄弟一致;点击后变警告色(armed) */@@ -14528,7 +15167,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.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-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{height:8px;border-radius:4px;background:var(--wb-bg-tertiary);overflow:hidden}.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}',+ '.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}','html.cb-dark .wbs-credit-summary-popover,html[data-theme="dark"] .wbs-credit-summary-popover,body[data-vscode-theme-name="IDE Night"] .wbs-credit-summary-popover{background:var(--wb-bg-popover,var(--wb-bg-primary));color:var(--wb-color-text-primary);border-color:var(--wb-border-default)}','@media(max-width:600px){.wbs-acct-toolbar{flex-wrap:wrap;gap:8px}.wbs-acct-summary{flex-wrap:wrap}.wbs-acct-actions{margin-left:auto}}','.wbs-acct-summary{display:flex;align-items:center;gap:12px;min-width:0}',@@ -14579,11 +15218,12 @@ 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-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:space-between;gap:8px;margin-top:8px}',+ '.wbs-session-copy-actions{display:flex;align-items:center;justify-content:flex-start;gap:8px;margin-top:8px}','.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{color:var(--wb-color-text-secondary,#667085);font-size:10px;white-space:nowrap}',+ '.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)}','.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}',@@ -14592,7 +15232,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-session-copy-detail-row:last-child{border-bottom:0}','.wbs-session-copy-detail-status{font-weight:650;color:var(--wb-color-text-secondary,#667085)}','.wbs-session-copy-detail-label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--wb-color-text-primary,#1f1f1f)}',- '.wbs-session-copy-detail-note{min-width:0;overflow:hidden;color:var(--wb-color-text-secondary,#667085);text-overflow:ellipsis;white-space:nowrap}',+ '.wbs-session-copy-detail-note{min-width:0;color:var(--wb-color-text-secondary,#667085);overflow-wrap:anywhere;white-space:normal}','.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}',diff --git a/scripts/lib.js b/scripts/lib.jsindex 719ac3d..08c08ad 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -609,10 +609,14 @@ function getAutoCopyRules(dataDir, uid) {const sessionIds = [];const lineages = {};const allLineages = {};+ const branchSessionIds = [];for (const sessionId of Object.keys(index)) {const lineageId = index[sessionId];const lineage = config.sessions[lineageId];- if (lineage) allLineages[sessionId] = lineageId;+ if (lineage) {+ allLineages[sessionId] = lineageId;+ if ((Array.isArray(lineage.members) ? lineage.members : []).some(member => member && member.uid === sourceUid && member.id === sessionId && member.branchCopy === true)) branchSessionIds.push(sessionId);+ }if (lineage && lineage.enabled !== false) {sessionIds.push(sessionId);lineages[sessionId] = lineageId;@@ -623,21 +627,21 @@ function getAutoCopyRules(dataDir, uid) {sessionIds,lineages,allLineages,+ branchSessionIds,workspaces: Object.keys(config.workspaces),};}-// A lineage represents one logical session per account. Older copies can-// leave multiple physical rows indexed under the same lineage; keep the first-// row (the SQL callers order newest activity first) for plans and UI counts.-function dedupeAutoCopySessionRows(rows, lineagesByUid) {+// Hide redundant legacy copies in lists, but keep explicit branch copies+// visible beside the original. Sync plans still inspect every physical row.+function dedupeAutoCopySessionRows(rows, lineagesByUid, branchesByUid = {}) {if (!Array.isArray(rows)) return [];const seen = new Set();return rows.filter((row) => {const uid = String(row && row.user_id || '').trim();const id = String(row && row.id || '').trim();const lineageId = lineagesByUid && lineagesByUid[uid] && lineagesByUid[uid][id];- if (!lineageId) return true;+ if (!lineageId || branchesByUid[uid]?.has(id)) return true;const key = uid + '::' + String(lineageId);if (seen.has(key)) return false;seen.add(key);@@ -882,7 +886,7 @@ function mergeAutoCopyLineages(dataDir, fromLineageId, intoLineageId) {return { ok: true, movedMembers };}-function addAutoCopySessionMember(dataDir, lineageId, uid, sessionId) {+function addAutoCopySessionMember(dataDir, lineageId, uid, sessionId, options = {}) {const meta = readMeta(dataDir);const config = ensureAutoCopyMeta(meta);const lineage = config.sessions[String(lineageId || '')];@@ -898,6 +902,7 @@ function addAutoCopySessionMember(dataDir, lineageId, uid, sessionId) {}config.sessionIndex[sourceUid][id] = String(lineageId);addLineageMember(lineage, sourceUid, id);+ if (options.branchCopy === true) lineage.members.find(member => member.uid === sourceUid && member.id === id).branchCopy = true;writeMeta(dataDir, meta);return true;}diff --git a/scripts/session-sync.js b/scripts/session-sync.jsnew file mode 100644index 0000000..840881a--- /dev/null+++ b/scripts/session-sync.js@@ -0,0 +1,278 @@+'use strict';++// Account copies share a logical session, but may have independent continuations.+// File times are only race detectors; they never choose a winning conversation.+const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');+const MAX_BYTES = 64 * 1024 * 1024;+const MAX_FILES = 20000;+const identityKeys = new Set(['sessionId', 'conversationId', 'ownerConversationId', 'session_id', 'conversation_id']);+const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');++function canonical(value, aliases) {+ if (Array.isArray(value)) return value.map(item => canonical(item, aliases));+ if (!value || typeof value !== 'object') return value;+ const result = Object.create(null);+ for (const key of Object.keys(value).sort()) {+ result[key] = identityKeys.has(key) && aliases.includes(value[key]) ? '__session__' : canonical(value[key], aliases);+ }+ return result;+}++function safePath(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 { if (fs.lstatSync(target).isSymbolicLink()) throw Error('会话文件包含符号链接,未同步'); }+ catch (error) { if (error.code !== 'ENOENT') throw error; }+ }+ return target;+}++function readSnapshot(root, id, aliases = []) {+ if (!id || /[/\\\x00]/.test(id) || id === '.' || id === '..') throw Error('无效的会话标识');+ root = path.resolve(root);+ if (fs.lstatSync(root).isSymbolicLink()) throw Error('会话目录包含符号链接,未同步');+ const knownIds = Array.from(new Set([id, ...aliases]));+ const files = new Map();+ let total = 0;+ function visit(relative, logical) {+ const file = safePath(root, relative);+ let stat;+ try { stat = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return; throw Error('会话文件无法读取'); }+ if (stat.isDirectory()) {+ for (const entry of fs.readdirSync(file).sort()) visit(relative + '/' + entry, logical + '/' + entry);+ return;+ }+ if (!stat.isFile()) throw Error('会话文件类型不受支持');+ total += stat.size;+ if (total > MAX_BYTES || files.size >= MAX_FILES) throw Error('会话文件过大,未自动同步');+ const bytes = fs.readFileSync(file);+ const after = fs.statSync(file);+ if (stat.size !== bytes.length || stat.size !== after.size || stat.mtimeMs !== after.mtimeMs || stat.ctimeMs !== after.ctimeMs) throw Error('会话文件正在变化,请稍后重试');+ let semantic = digest(bytes);+ // Workspace files and history snapshots are user work products. Their+ // extension does not guarantee valid JSON (JSONC, drafts, empty files,+ // or arbitrary bytes). Preserve and compare those files byte-for-byte.+ // Only the official index needs structured identity normalization because+ // targetBytes rewrites its ownerConversationId during a copy.+ if (logical === 'artifact-index/__session__.json') {+ let value;+ try { value = JSON.parse(bytes.toString('utf8')); } catch (_) { throw Error('会话产物索引损坏,未同步'); }+ semantic = digest(JSON.stringify(canonical(value, knownIds)));+ }+ files.set(logical, { relative, bytes, hash: digest(bytes), semantic, mode: stat.mode & 0o777, mtimeMs: stat.mtimeMs });+ }+ 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__');+ }+ }+ for (const prefix of ['workspace/sessions', 'tasks', 'file-history']) visit(prefix + '/' + id, prefix + '/__session__');+ 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 lines = transcripts[0][1].bytes.toString('utf8').split(/\r?\n/).filter(line => line.trim());+ if (!lines.length) throw Error('会话消息文件为空,未同步');+ records = lines.map(line => {+ 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)));+ });+ // Require actual messages: a metadata-only journal is not an empty base.+ if (!lines.some(line => JSON.parse(line).type === 'message')) throw Error('会话消息文件没有消息,未同步');+ transcripts[0][1].semantic = digest(records.join('\n'));+ }+ return { root, id, aliases: knownIds, files, records, transcriptKey };+}++function compareSnapshots(left, right) {+ const a = left.records, b = right.records;+ if (!a && !b) throw Error('双方会话消息文件均缺失,未同步');+ if (!a || !b) {+ const missing = a ? right : left, complete = a ? left : right;+ // A missing journal is repairable only when surviving supporting files+ // agree. Unknown/different surviving content is never discarded.+ for (const [key, file] of missing.files) {+ if (!complete.files.has(key) || complete.files.get(key).semantic !== file.semantic) throw Error('会话消息缺失且附属文件不一致,未覆盖');+ }+ return { kind: a ? 'left-extends' : 'right-extends' };+ }+ if (left.transcriptKey !== right.transcriptKey) return { kind: 'conflict' };+ for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return { kind: 'conflict' };+ if (a.length !== b.length) return { kind: a.length > b.length ? 'left-extends' : 'right-extends' };+ for (const [key, file] of left.files) {+ if (right.files.has(key) && right.files.get(key).semantic !== file.semantic) return { kind: 'conflict' };+ }+ const missingRight = [...left.files.keys()].some(key => !right.files.has(key));+ const missingLeft = [...right.files.keys()].some(key => !left.files.has(key));+ return { kind: missingRight || missingLeft ? 'repair' : 'equal', missingRight, missingLeft };+}++// Legacy copies can leave several physical sessions in the target account.+// Choose by complete content, never by timestamps or the mapping alone. Keep+// only hashes while scanning, so duplicate workspaces do not accumulate in RAM.+async function selectTargetSnapshot(source, targetIds, readTarget, preferredId) {+ const ordered = [...new Set(targetIds)].sort((a, b) => {+ if (a === preferredId) return -1;+ if (b === preferredId) return 1;+ return a < b ? -1 : a > b ? 1 : 0;+ });+ const repairs = [], ancestors = [], descendants = [], errors = [];+ for (const id of ordered) {+ try {+ const snapshot = await readTarget(id);+ const comparison = compareSnapshots(source, snapshot);+ 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 }])),+ } };+ // An existing complete copy already satisfies this source, even when+ // other legacy copies have diverged or become unreadable.+ if (comparison.kind === 'equal') return candidate;+ if (comparison.kind === 'repair') repairs.push(candidate);+ if (comparison.kind === 'left-extends') ancestors.push(candidate);+ if (comparison.kind === 'right-extends') descendants.push(candidate);+ } catch (error) { errors.push(error); }+ }+ if (repairs.length) return repairs[0];+ const longestFirst = (a, b) => (b.snapshot.records?.length || 0) - (a.snapshot.records?.length || 0);+ if (descendants.length) {+ descendants.sort(longestFirst);+ const longest = descendants[0];+ // Several continuations of the source may be different branches. A+ // stored mapping must never decide which branch replaces that source.+ if (descendants.some(candidate => compareSnapshots(longest.snapshot, candidate.snapshot).kind === 'conflict')) {+ return { targetId: null, comparison: { kind: 'conflict' } };+ }+ return longest;+ }+ if (ancestors.length) return ancestors.sort(longestFirst)[0];+ // Unreadable content remains an actual failure when no safe match exists.+ if (errors.length) throw errors[0];+ return { targetId: null, comparison: { kind: 'conflict' } };+}++function unchanged(snapshot) {+ const now = readSnapshot(snapshot.root, snapshot.id, snapshot.aliases);+ return now.files.size === snapshot.files.size && [...snapshot.files].every(([key, file]) => now.files.get(key)?.hash === file.hash);+}++function targetRelative(logical, id) {+ return logical.split('/').map(part => part === '__session__' ? id : part === '__session__.jsonl' ? id + '.jsonl' : part === '__session__.json' ? id + '.json' : part).join('/');+}++function targetBytes(key, file, source, target) {+ if (key !== 'artifact-index/__session__.json') return file.bytes;+ const index = JSON.parse(file.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 applySnapshot(source, target, options) {+ const { backupRoot, commit = async () => {}, guard = async () => {}, missingOnly = false } = 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 = targetBytes(key, file, source, target);+ if (target.files.get(key)?.hash === digest(bytes)) continue;+ changes.push({ key, relative: targetRelative(key, target.id), bytes, 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 });+ }+ await guard();+ if (!unchanged(source) || !unchanged(target)) throw Error('会话文件正在变化,请稍后重试');+ fs.mkdirSync(backupRoot, { recursive: true, mode: 0o700 });+ const backup = fs.mkdtempSync(path.join(backupRoot, 'sync-'));+ fs.chmodSync(backup, 0o700);+ for (const [key, file] of target.files) {+ const filePath = safePath(backup, 'files/' + key);+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });+ fs.writeFileSync(filePath, file.bytes, { mode: 0o600, flag: 'wx' });+ }+ 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.bytes === null ? null : digest(change.bytes) })) };+ const journalFile = path.join(backup, 'journal.json');+ const save = () => fs.writeFileSync(journalFile, JSON.stringify(journal), { mode: 0o600 });+ save();+ const expected = new Map([...target.files].map(([key, file]) => [key, file.hash]));+ for (const change of changes) {+ if (change.bytes === null) expected.delete(change.key);+ else expected.set(change.key, digest(change.bytes));+ }+ const verifyPublished = () => {+ if (!unchanged(source)) throw Error('源会话正在变化,已停止同步');+ const now = readSnapshot(target.root, target.id, target.aliases);+ if (now.files.size !== expected.size || [...expected].some(([key, hash]) => now.files.get(key)?.hash !== hash)) {+ throw Error('目标会话正在变化,已停止同步');+ }+ };+ const applied = [];+ try {+ // Snapshot all old bytes before publication. Recheck after the async guard.+ await guard();+ if (!unchanged(source) || !unchanged(target)) throw Error('会话文件正在变化,请稍后重试');+ for (const change of changes) {+ const file = safePath(target.root, change.relative);+ const old = target.files.get(change.key);+ const exists = fs.existsSync(file);+ if (old ? !exists || digest(fs.readFileSync(file)) !== old.hash : exists) throw Error('目标会话正在变化,已停止同步');+ if (change.bytes === null) fs.unlinkSync(file);+ else {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const staged = path.join(path.dirname(file), '.wbs-sync-' + crypto.randomUUID());+ try {+ fs.writeFileSync(staged, change.bytes, { mode: change.mode || 0o600, flag: 'wx' });+ 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);+ } finally { if (fs.existsSync(staged)) fs.unlinkSync(staged); }+ }+ applied.push(change);+ }+ verifyPublished();+ // The DB adapter calls this again after its asynchronous row/idle checks.+ await commit(verifyPublished);+ journal.status = 'committed';+ // Metadata already committed: a journal I/O failure must not undo files.+ let journalPending = false;+ try { save(); } catch (_) { journalPending = true; }+ return { backup, copied: changes.length, journalPending };+ } catch (error) {+ // Do not roll back over an official write that happened after publication.+ let incomplete = false;+ for (const change of applied.reverse()) {+ try {+ const file = safePath(target.root, change.relative);+ if (change.bytes === null ? fs.existsSync(file) : !fs.existsSync(file) || digest(fs.readFileSync(file)) !== digest(change.bytes)) { incomplete = true; continue; }+ const old = target.files.get(change.key);+ if (old) {+ fs.writeFileSync(file, old.bytes, { mode: old.mode });+ fs.utimesSync(file, new Date(old.mtimeMs), new Date(old.mtimeMs));+ } else if (fs.existsSync(file)) fs.unlinkSync(file);+ } catch (_) { incomplete = true; }+ }+ journal.status = incomplete ? 'recovery-needed' : 'rolled-back';+ try { save(); } catch (_) { /* Keep the original failure and retained backup. */ }+ throw error;+ }+}++module.exports = { readSnapshot, compareSnapshots, selectTargetSnapshot, applySnapshot };diff --git a/test/automation-checkin.test.js b/test/automation-checkin.test.jsindex 7371a9b..42299eb 100644--- a/test/automation-checkin.test.js+++ b/test/automation-checkin.test.js@@ -103,6 +103,16 @@ test('legacy implicit triggers and pending UI are removed; panel event is explicassert.doesNotMatch(ctx.checkinHtml({checkin:{ok:false,message:'bad'}}),/bad/);});+test('panel refresh exposes an explicit current-account check-in reconciliation route', () => {+ assert.match(source, /p === '\/api\/accounts\/checkin-sync'/);+ const route = source.slice(source.indexOf("p === '/api/accounts/checkin-sync'"), source.indexOf("if (req.method === 'GET' && p === '/api/accounts')"));+ assert.match(route, /claimDailyForUid\(uid\)/);+ assert.match(route, /仅支持当前账号/);+ const ui = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ assert.match(ui, /api\('\/api\/accounts\/checkin-sync'/);+ assert.match(ui, /current\.checkin = \{ ok: !!result\.ok/);+});+test('failed or stale cache records never suppress today\'s check-in request', async () => {for (const cached of [{date:'2026-09-08',ok:false,verified:false,code:0,message:'HTTP 500'},@@ -121,7 +131,7 @@ test('panel-open emits once per user opening and excludes automation restorationconst calls=[];const noop=()=>{};const ctx={window:{},state:{open:false,creditRunId:0},panel:{classList:{toggle:noop}},fab:{classList:{toggle:noop}},api:(route,options)=>{if(route==='/api/automations/discovery')return Promise.resolve({tasks:[]});calls.push([route,JSON.parse(options.body).type]);return Promise.resolve();},- preloadAutomationDiscovery:()=>Promise.resolve({tasks:[]}),CAPS:{accounts:false},refresh:noop,checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,fabQuietMode:{wake:noop}};+ preloadAutomationDiscovery:()=>Promise.resolve({tasks:[]}),CAPS:{accounts:false},refresh:noop,checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,closeSessionCopyNotice:noop,fabQuietMode:{wake:noop}};vm.createContext(ctx);vm.runInContext(ui.slice(start,end),ctx);ctx.setOpen(true);ctx.setOpen(true);assert.equal(calls.length,1);ctx.setOpen(false);ctx.setOpen(true,{automation:true});assert.equal(calls.length,1);diff --git a/test/automation-discovery.test.js b/test/automation-discovery.test.jsindex 77c32d0..0f2ba6c 100644--- a/test/automation-discovery.test.js+++ b/test/automation-discovery.test.js@@ -98,6 +98,10 @@ test('discovery searches GitHub and Gitee, deduplicates task JSON and caches resawait discovery.getCatalog();assert.ok(f.calls.length > before, 'stale cache should refresh repository searches');assert.equal(f.calls.filter(url => url.includes('/contents/tasks')).length, 4, 'unmarked or unchanged repositories should not be rescanned');++ const forcedBefore = f.calls.length;+ await discovery.getCatalog({ force: true });+ assert.ok(f.calls.length > forcedBefore, 'forced discovery should search when the automation page opens');} finally {fs.rmSync(dir, { recursive: true, force: true });}@@ -134,6 +138,37 @@ test('discovery ignores the old cache and reads V2 from task JSON, not the repos}});+test('discovery groups package revisions by ID and keeps the highest version', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-discovery-package-revisions-'));+ try {+ const packageFile = path.join(__dirname, '../examples/automation-packages/account-summary.workdaddy.json');+ const older = JSON.parse(fs.readFileSync(packageFile, 'utf8'));+ const newer = { ...older, version: '1.1.0', name: '账号积分与活跃天数新版' };+ fs.writeFileSync(path.join(dir, 'automation-discovery-cache.json'), JSON.stringify({+ version: 3, checkedAt: 1_000_000, refreshedAt: 1_000_000,+ providers: { github: [], gitee: [] },+ repositories: {+ 'github:demo/tasks': {+ platform: 'github', fullName: 'demo/tasks', repositoryUrl: 'https://github.com/demo/tasks', stars: 3,+ tasks: [+ { path: 'tasks/older.json', downloadUrl: 'https://raw.githubusercontent.com/demo/tasks/main/tasks/older.json', content: JSON.stringify(older) },+ { path: 'tasks/newer.json', downloadUrl: 'https://raw.githubusercontent.com/demo/tasks/main/tasks/newer.json', content: JSON.stringify(newer) },+ ],+ },+ }, errors: [],+ }));+ const discovery = createAutomationDiscovery({ dataDir: dir, fetchImpl: async () => { throw new Error('cache should be fresh'); }, now: () => 1_000_000, runtime });+ const catalog = await discovery.getCatalog();+ assert.equal(catalog.tasks.length, 1);+ assert.equal(catalog.tasks[0].packageId, older.id);+ assert.equal(catalog.tasks[0].packageVersion, '1.1.0');+ assert.equal(catalog.tasks[0].name, '账号积分与活跃天数新版');+ assert.match(discovery.getTaskContent(catalog.tasks[0].key), /"version":"1\.1\.0"/);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});+test('discovered task imports through the existing validator and remains disabled', async () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-discovery-import-'));try {@@ -220,6 +255,11 @@ test('automation UI preloads discovery and exposes fuzzy task search and import'assert.match(source, /WorkDaddyAutomationRepository。/);assert.doesNotMatch(source, /WorkDaddyAutomationRepositoryV1/);assert.match(source, /wbs-auto-discovery-version/);+ assert.match(source, /wbs-auto-update-badge/);+ assert.match(source, /wbs-auto-discovery-update/);+ assert.match(source, /replaceExisting/);+ assert.match(source, /\/api\/automations\/discovery\?refresh=1/);+ assert.match(source, /确认用公开仓库中的新版覆盖本地任务/);assert.match(source, /source\.platform === 'github'/);assert.match(source, /wbs-usage-modal-mask wbs-auto-dialog-mask/);assert.doesNotMatch(source, /wbs-auto-discovery-stars/);diff --git a/test/automation-model.test.js b/test/automation-model.test.jsindex cf34580..013a7c2 100644--- a/test/automation-model.test.js+++ b/test/automation-model.test.js@@ -159,7 +159,7 @@ test('daemon selects and checks the model before sending, and ships the rendererassert.ok(selectAt > 0 && sendAt > selectAt);assert.match(daemon, /if \(modelId\) await confirmAutomationModel\(modelId/);assert.match(daemon, /restoreAutomationNewTaskPreference\(modelSelection\)/);- assert.match(daemon, /const DAEMON_VERSION = '1\.2\.76'/);+ assert.match(daemon, /const DAEMON_VERSION = '1\.2\.83'/);const staging = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');assert.match(staging, /automation-model\.js/);});diff --git a/test/automation-panel-input.test.js b/test/automation-panel-input.test.jsindex 52f35a6..98fc28e 100644--- a/test/automation-panel-input.test.js+++ b/test/automation-panel-input.test.js@@ -5,7 +5,7 @@ const ui=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');test('panel opening is blocked only during input; waiting for a reply still allows access',()=>{const calls=[];const noop=()=>{};- const ctx={window:{__wbsAutomationInputActive:true},state:{open:false},root:{},panel:{classList:{toggle:noop}},fab:{classList:{toggle:noop}},CAPS:{accounts:false},fabQuietMode:{wake:noop},toast:()=>calls.push('blocked'),refresh:()=>calls.push('refresh'),checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,api:()=>Promise.resolve()};+ const ctx={window:{__wbsAutomationInputActive:true},state:{open:false},root:{},panel:{classList:{toggle:noop}},fab:{classList:{toggle:noop}},CAPS:{accounts:false},fabQuietMode:{wake:noop},toast:()=>calls.push('blocked'),refresh:()=>calls.push('refresh'),checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,closeSessionCopyNotice:noop,api:()=>Promise.resolve()};const start=ui.indexOf(' function setOpen(open, options)');vm.runInNewContext(ui.slice(start,ui.indexOf(' function setupFabDrag()',start)),ctx);ctx.setOpen(true);assert.equal(ctx.state.open,false);assert.deepEqual(calls,['blocked']);diff --git a/test/automation-transfer.test.js b/test/automation-transfer.test.jsindex 051cfc8..051f7b8 100644--- a/test/automation-transfer.test.js+++ b/test/automation-transfer.test.js@@ -24,6 +24,26 @@ test('duplicate IDs skip existing tasks without overwriting or re-enabling them,const before=fs.readFileSync(path.join(dir,'automations.json'));assert.equal(importTasks(dir,{...payload,selected:['1']},runtime).imported,0);assert.deepEqual(fs.readFileSync(path.join(dir,'automations.json')),before);}finally{fs.rmSync(dir,{recursive:true,force:true});}});++test('package updates replace the matching imported task and keep its runtime ID', () => {+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-transfer-package-update-'));+ try{+ const packageFile=path.join(__dirname,'../examples/automation-packages/account-summary.workdaddy.json');+ const older=JSON.parse(fs.readFileSync(packageFile,'utf8'));+ const newer={...older,version:'1.1.0',name:'新版账号概况',task:{...older.task,name:'新版账号概况'}};+ const first=importTasks(dir,{content:JSON.stringify(older),selected:['0']},runtime);+ assert.equal(first.imported,1);+ const before=readAutomations(dir)[0];+ const result=importTasks(dir,{content:JSON.stringify(newer),selected:['0'],replaceExisting:true},runtime);+ assert.equal(result.replaced,1);+ assert.equal(result.imported,0);+ const updated=readAutomations(dir)[0];+ assert.equal(updated.id,before.id);+ assert.equal(updated.name,'新版账号概况');+ assert.equal(updated['x-workdaddy-import'].packageId,older.id);+ assert.equal(updated['x-workdaddy-import'].packageVersion,'1.1.0');+ }finally{fs.rmSync(dir,{recursive:true,force:true});}+});test('invalid selected task and capacity failures do not partially save',()=>{const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-transfer-'));try{diff --git a/test/conversation-usage.test.js b/test/conversation-usage.test.jsnew file mode 100644index 0000000..9581d51--- /dev/null+++ b/test/conversation-usage.test.js@@ -0,0 +1,77 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');++const { collectConversationUsage } = require('../scripts/inject.js');++test('conversation usage keeps only terminal messages and groups credits by model', () => {+ const result = collectConversationUsage([+ { id: 'streaming', complete: false, usage: { inputTokens: 900, outputTokens: 40, credit: 9 }, extra: { modelId: 'a', modelName: 'Alpha' } },+ { id: 'a-1', complete: true, usage: { inputTokens: 100, outputTokens: 4, credit: 0.37 }, extra: { modelId: 'a', modelName: 'Alpha', isRequestTerminal: true } },+ { id: 'b-1', complete: true, usage: { inputTokens: 12, outputTokens: 3, credit: 0.11 }, extra: { modelId: 'b', modelName: 'Beta', isRequestTerminal: true } },+ { id: 'a-2', complete: true, usage: { inputTokens: 40, outputTokens: 5 }, extra: { modelId: 'a', modelName: 'Alpha', isRequestTerminal: true } },+ { id: 'c-1', complete: true, usage: { inputTokens: 0, outputTokens: 0, lastTokens: 20, credit: 0.05 }, extra: { modelId: 'c', isRequestTerminal: true } },+ ]);++ assert.equal(result.calls, 4);+ assert.equal(result.tokens, 184);+ assert.equal(result.credit, 0.53);+ assert.equal(result.creditKnown, false);+ assert.deepEqual(result.models.map(model => [model.modelId, model.calls, model.tokens, model.creditKnown]), [+ ['a', 2, 149, false],+ ['b', 1, 15, true],+ ['c', 1, 20, true],+ ]);+});++test('conversation usage does not double count repeated terminal snapshots', () => {+ const result = collectConversationUsage([+ { id: 'assistant-1', complete: true, usage: { inputTokens: 10, outputTokens: 2, lastTokens: 12, credit: 0.2 }, extra: { conversationRequestId: 'request-1', modelId: 'a', isRequestTerminal: true } },+ { id: 'assistant-1-final', complete: true, usage: { inputTokens: 10, outputTokens: 3, lastTokens: 13, credit: 0.3 }, extra: { conversationRequestId: 'request-1', modelId: 'a', isRequestTerminal: true } },+ ]);++ assert.equal(result.calls, 1);+ assert.equal(result.tokens, 13);+ assert.equal(result.credit, 0.3);+});++test('conversation usage UI uses a body-fixed mount, bottom spacer and message store', () => {+ const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ assert.match(source, /\.cr-message-list__content/);+ assert.match(source, /conversationUsage\.summary\.parentNode !== document\.body/);+ assert.match(source, /wbs-session-usage-spacer/);+ assert.match(source, /controller\.messageStore\.subscribe/);+ assert.match(source, /usage\.credit/);+ assert.match(source, /wbs-session-usage-popover/);+ assert.match(source, /position:fixed/);+ assert.match(source, /wbs-sess-usage-summary/);+ assert.match(source, /conversationUsageEnabled/);+ assert.doesNotMatch(source, /悬浮查看明细|Hover for details/);+ assert.doesNotMatch(source, /el\('strong', 'wbs-session-usage/);+ assert.match(source, /wbs-session-usage-popover\{[^}]*background:color-mix/);+ assert.match(source, /wbs-session-usage-summary\{[^}]*z-index:20/);+ assert.match(source, /wbs-session-usage-popover\{[^}]*z-index:21/);+ assert.match(source, /wbs-session-usage-summary\{[^}]*border:0/);+ assert.match(source, /wbs-session-usage-summary\{[^}]*cursor:pointer/);+ assert.match(source, /wbs-session-usage-detail-title\{[^}]*font-weight:700/);+ assert.match(source, /wbs-session-usage-summary\{[^}]*font-size:13px[^}]*opacity:\.72/);+ assert.match(source, /wbs-session-usage-detail-title\{[^}]*font-size:14px/);+ assert.match(source, /wbs-session-usage-detail-row\{[^}]*font-size:12px/);+ assert.match(source, /wbs-session-usage-detail-note/);+ assert.match(source, /部分会话尚未完成,当前 Token 和积分仅按已完成用量统计/);+ assert.match(source, /if \(open\) \{[\s\S]{0,260}closeSessionCopyNotice\(\)/);+ assert.match(source, /pollSessionCopyNotice[\s\S]{0,500}if \(state\.open\)/);+ assert.match(source, /return usageNumber\(value\) > 0 \? '≥' \+ formatted/);+ assert.match(source, /addEventListener\('scroll', scheduleConversationUsageScrollState, \{ passive: true \}\)/);+ assert.match(source, /var canScroll = maxScroll > 1/);+ assert.match(source, /var atBottom = canScroll && maxScroll - scrollElement\.scrollTop <= 4/);+ assert.match(source, /cr-message-list__bottom-mask/);+ assert.match(source, /var anchorBottom = anchorRect && anchorRect\.bottom/);+ assert.match(source, /window\.innerHeight - anchorBottom/);+ assert.match(source, /positionConversationUsage\(\);[\s\S]{0,120}updateConversationUsageScrollState\(\)/);+ assert.match(source, /wbs-session-usage-summary\.is-hidden/);+ assert.doesNotMatch(source, /conversation-finished-footer[\s\S]{0,120}usage/);+});diff --git a/test/i18n-coverage.test.js b/test/i18n-coverage.test.jsindex 936868d..0ccae15 100644--- a/test/i18n-coverage.test.js+++ b/test/i18n-coverage.test.js@@ -14,6 +14,7 @@ const vm = require('node:vm');const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');const automationPicker = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'automation-picker.js'), 'utf8');const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');+const sessionSync = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'session-sync.js'), 'utf8');const lib = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib.js'), 'utf8');// ---- 工具:提取字典 + 翻译函数并构造可执行翻译器 ----@@ -129,7 +130,7 @@ test('every user-facing Chinese literal in daemon.js (non-log) is covered', () =test('lib.js account-flow errors (surface as toasts) translate without Chinese residue', () => {const t = buildTranslator();const missed = [];- for (const lit of chineseLiterals(stripComments(lib))) {+ for (const lit of chineseLiterals(stripComments(lib + sessionSync))) {if (LOG_LIKE.test(lit)) continue;if (FRAGMENT_LIKE.test(lit)) continue;const out = t(lit, 'en');diff --git a/test/linux-release-script.test.js b/test/linux-release-script.test.jsindex a9ce89c..0094458 100644--- a/test/linux-release-script.test.js+++ b/test/linux-release-script.test.js@@ -24,8 +24,13 @@ test('Linux release builds a versioned, self-contained Debian package without roassert.match(source, /node_modules\/ws/);assert.match(source, /scripts\/builtin/);assert.match(source, /scripts\/assets\/workdaddy-logo\.svg/);- assert.match(source, /for profile in cn ai/);- assert.match(source, /workdaddy-\$profile\.desktop/);+ 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, /Exec=\$install_root\/scripts\/launch-gui-linux\.sh \$profile/);+ assert.match(source, /workdaddy-\$profile\.png/);+ assert.match(source, /Icon=workdaddy-\$profile/);assert.match(source, /const DAEMON_VERSION =/);assert.match(source, /\['DAEMON_BUILD_ID', `release-\$\{version\}-linux-deb`\]/);assert.doesNotMatch(source, /DEBIAN\/(?:preinst|postinst|prerm|postrm)/);@@ -49,32 +54,47 @@ test('Linux file-manager action does not invoke the macOS open command', () => {assert.match(daemon, /if \(IS_LINUX\) \{\s*require\('child_process'\)\.execFile\('xdg-open', \[DATA_DIR\]\)/);});-test('built Linux package has matching metadata and payload', { skip: process.platform !== 'linux' || !process.env.WORKDADDY_LINUX_DEB }, () => {- const deb = process.env.WORKDADDY_LINUX_DEB;+test('built Linux packages have matching metadata and isolated payloads', { skip: process.platform !== 'linux' || !process.env.WORKDADDY_LINUX_DEBS }, () => {+ 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$/ }],+ ]);+ for (const deb of debs) {+ const fileName = path.basename(deb);+ const entry = [...expected.entries()].find(([prefix]) => fileName.startsWith(prefix))?.[1];+ assert.ok(entry, `unexpected Linux package: ${fileName}`);+ assert.match(fileName, entry.filePattern);const version = spawnSync('dpkg-deb', ['-f', deb, 'Version'], { encoding: 'utf8' });assert.equal(version.status, 0);+ const packageName = spawnSync('dpkg-deb', ['-f', deb, 'Package'], { encoding: 'utf8' });+ assert.equal(packageName.stdout.trim(), entry.packageName);const entries = spawnSync('dpkg-deb', ['--contents', deb], { encoding: 'utf8' });assert.equal(entries.status, 0);for (const name of ['scripts/daemon.js', 'scripts/runtime/node/node', 'scripts/node_modules/ws/package.json',- 'scripts/builtin/nebula/theme.json', 'scripts/assets/workdaddy-logo.svg',- 'workdaddy-cn.desktop', 'workdaddy-ai.desktop']) {- assert.ok(entries.stdout.includes(name), `missing ${name}`);+ 'scripts/builtin/nebula/theme.json', 'scripts/assets/workdaddy-logo.svg']) {+ assert.ok(entries.stdout.includes(`${entry.root}/${name}`), `missing ${entry.root}/${name}`);}+ assert.ok(entries.stdout.includes(entry.desktop));+ assert.equal(entries.stdout.includes(entry.root === 'opt/workdaddy' ? 'opt/workdaddy-ai/' : 'opt/workdaddy/'), false);assert.ok(!entries.stdout.includes('安装失败自主解决提示词.txt'));const extracted = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'workdaddy-linux-deb-test-'));try {assert.equal(spawnSync('dpkg-deb', ['--extract', deb, extracted]).status, 0);- const daemon = fs.readFileSync(path.join(extracted, 'opt/workdaddy/scripts/daemon.js'), 'utf8');+ const daemon = fs.readFileSync(path.join(extracted, entry.root, 'scripts/daemon.js'), 'utf8');assert.match(daemon, new RegExp(`const DAEMON_VERSION = '${version.stdout.trim().replace(/\./g, '\\.')}';`));assert.match(daemon, /const DAEMON_BUILD_ID = 'release-[^']+-linux-deb';/);} finally {fs.rmSync(extracted, { recursive: true, force: true });}assert.match(path.basename(deb), new RegExp(version.stdout.trim().replace(/\./g, '\\.') + '_amd64\\.deb$'));+ }});-test('cross-built Debian archive exposes standard member names and control metadata', { skip: !process.env.WORKDADDY_LINUX_DEB }, () => {- const deb = process.env.WORKDADDY_LINUX_DEB;+test('cross-built Debian archives expose standard member names and control metadata', { skip: !process.env.WORKDADDY_LINUX_DEBS }, () => {+ const debs = process.env.WORKDADDY_LINUX_DEBS.split(path.delimiter).filter(Boolean);+ for (const deb of debs) {const members = spawnSync('ar', ['-t', deb], { encoding: 'utf8' });assert.equal(members.status, 0, members.stderr);assert.deepEqual(members.stdout.trim().split('\n'), ['debian-binary', 'control.tar.xz', 'data.tar.xz']);@@ -82,8 +102,9 @@ test('cross-built Debian archive exposes standard member names and control metadassert.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_(\d+\.\d+\.\d+)_amd64\.deb$/)?.[1];+ const version = path.basename(deb).match(/^(?:WorkDaddy|WorkDaddy-AI)_(\d+\.\d+\.\d+)_amd64\.deb$/)?.[1];assert.ok(version);assert.ok(metadata.stdout.split('\n').includes(`Version: ${version}`));assert.match(metadata.stdout, /^Architecture: amd64$/m);+ }});diff --git a/test/session-artifact-copy.test.js b/test/session-artifact-copy.test.jsindex 7df0fcf..327a47d 100644--- a/test/session-artifact-copy.test.js+++ b/test/session-artifact-copy.test.js@@ -7,8 +7,8 @@ const path = require('node:path');const vm = require('node:vm');const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');function helpers(fsImpl = fs, log = () => {}) {- const ctx = { fs: fsImpl, path, log };- vm.runInNewContext(source.slice(source.indexOf('async function copySessionFiles('), source.indexOf('// Reconcile every live member')), ctx);+ const ctx = { fs: fsImpl, path, log, crypto: require('node:crypto'), Buffer };+ vm.runInNewContext(source.slice(source.indexOf('async function copySessionFiles('), source.indexOf('// Yield between session pairs')), ctx);return ctx;}test('copied delivered artifacts retain official ownership visibility and original timestamps', async t => {@@ -100,35 +100,3 @@ test('unparseable artifact contents never appear in copy diagnostics', async t =assert.doesNotMatch(logs.join('\n'), /private-fixture/);assert.match(logs.join('\n'), /格式不受支持/);});--test('switch lineage synchronization repairs every legacy copy using the newest content', async t => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-artifact-lineage-'));- t.after(() => fs.rmSync(dir, { recursive: true, force: true }));- fs.mkdirSync(path.join(dir, 'artifact-index'));- const members = [{ uid: 'account-a', id: 'source' }, { uid: 'account-b', id: 'copy' }, { uid: 'account-c', id: 'third' }];- for (const [index, member] of members.entries()) {- const file = path.join(dir, 'artifact-index', member.id + '.json');- fs.writeFileSync(file, JSON.stringify({ version: 1, artifacts: [{ id: index === 1 ? 'newest-artifact' : 'old-artifact', requestId: 'protocol-42', _meta: { ownerConversationId: 'source' } }] }));- const time = new Date(index === 1 ? '2026-02-01' : '2026-01-01');- fs.utimesSync(file, time, time);- }- const h = helpers();- Object.assign(h, {- PROFILE: { kind: 'workbuddy', dataRoot: dir }, DATA_DIR: dir, SESSION_COPY_COLUMNS: ['id','user_id'],- getAutoCopySessionMemberRecords: () => members,- selectLatestAutoCopyMember: require('../scripts/lib.js').selectLatestAutoCopyMember,- yieldAutoCopyToRenderer: async () => {},- sqliteQuery: async (_, params) => [{ id: params[0], user_id: params[1], updated_at: 1 }],- sqliteRun: async () => {},- });- vm.runInNewContext(source.slice(source.indexOf('async function syncAutoCopyLineage('), source.indexOf('const MAX_SESSION_EXPORT_FILES')), h);- const result = await h.syncAutoCopyLineage('known-lineage', 'account-c');- assert.equal(result.sourceId, 'copy');- assert.equal(result.failedFiles, 0);- for (const member of members) {- const artifact = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-index', member.id + '.json'))).artifacts[0];- assert.equal(artifact.id, 'newest-artifact');- assert.equal(artifact._meta.ownerConversationId, member.id);- assert.equal(artifact.requestId, 'protocol-42');- }-});diff --git a/test/session-conflict-reset.test.js b/test/session-conflict-reset.test.jsnew file mode 100644index 0000000..1a9b67a--- /dev/null+++ b/test/session-conflict-reset.test.js@@ -0,0 +1,53 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const vm = require('node:vm');+const lib = require('../scripts/lib.js');+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');++function harness(t) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-reset-route-'));+ t.after(() => fs.rmSync(dataDir, { recursive: true, force: true }));+ const lineage = lib.ensureAutoCopySession(dataDir, 'source', 'session-source');+ lib.addAutoCopySessionMember(dataDir, lineage, 'target', 'session-target');+ lib.setAutoCopyMapping(dataDir, lineage, 'target', { targetId: 'session-target' });+ lib.setAutoCopyMapping(dataDir, lineage, 'other', { targetId: 'session-other' });+ const jobs = [];+ const ctx = {+ ...lib, URL, HOST: '127.0.0.1', DATA_DIR: dataDir,+ isApiRequestAuthorized: () => true,+ readBody: async req => req.body,+ json: (_, status, body) => ({ status, body }),+ listAccounts: () => [],+ buildAutoCopyPlan: async () => [{ id: 'session-source', lineageId: lineage }],+ startAutoCopyJob: (sourceUid, targetUid, plan) => {+ assert.equal(lib.getAutoCopyMapping(dataDir, lineage, targetUid), null);+ const job = { id: 'retry-job', sourceUid, targetUid, plan, status: 'queued' };+ jobs.push(job);+ return job;+ },+ publicAutoCopyJob: job => job,+ };+ const start = source.indexOf('function handleApi(');+ const end = source.indexOf('// ===== 电脑休眠控制', start);+ assert.ok(start >= 0 && end > start);+ vm.runInNewContext(source.slice(start, end), ctx);+ return { dataDir, lineage, jobs, request: body => ctx.handleApi({+ method: 'POST', url: '/api/sessions/auto-copy/reset', headers: {}, body,+ }, {}) };+}++for (const body of [{}, { sourceUid: 'source', targetUid: 'target', sessionIds: ['session-source'] }]) {+ test('retired reset endpoint preserves all baselines and starts no work: ' + JSON.stringify(body), async t => {+ const h = harness(t);+ const before = fs.readFileSync(lib.metaFile(h.dataDir));+ const result = await h.request(body);+ assert.equal(result.status, 410);+ assert.match(result.body.error, /已保留双方内容/);+ assert.deepEqual(fs.readFileSync(lib.metaFile(h.dataDir)), before);+ assert.equal(h.jobs.length, 0);+ });+}diff --git a/test/session-filter.test.js b/test/session-filter.test.jsindex 7cb8c95..0d47394 100644--- a/test/session-filter.test.js+++ b/test/session-filter.test.js@@ -4,6 +4,46 @@ const assert = require('node:assert/strict');const fs = require('node:fs');const path = require('node:path');const test = require('node:test');+const vm = require('node:vm');++test('batch mode keeps the header visible and disables controls until cancelled', () => {+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ const controls = Array.from({ length: 7 }, () => ({ disabled: false, style: { display: '' }, classList: { toggle() {} } }));+ const auto = { disabled: false, style: { display: '' }, classList: { toggle() {} }, setAttribute() {} };+ const count = { style: { display: '' } };+ const bar = { style: { display: 'none' } };+ const nodes = { '#wbs-sess-batchbar': bar, '#wbs-sess-batch': controls[0], '#wbs-sess-import': controls[1], '#wbs-sess-auto-all': auto, '#wbs-sess-count': count };+ const state = { batchMode: true, autoCopyAll: true };+ const context = vm.createContext({ sessionsState: state, sessionsPane: {+ querySelector: selector => nodes[selector],+ querySelectorAll: selector => {+ assert.match(selector, /wbs-sess-filters/);+ assert.match(selector, /select/);+ return [...controls, auto];+ },+ } });+ const extract = (start, end) => inject.slice(inject.indexOf(start), inject.indexOf(end, inject.indexOf(start)));+ vm.runInContext(extract('function updateAutoCopyAllButton()', 'function toggleAutoCopyAll(') + extract('function setSessBatchBar(on)', 'function wireSessionsPane()'), context);+ context.setSessBatchBar(true);+ for (const control of [...controls, auto]) {+ assert.equal(control.disabled, true);+ assert.equal(control.style.display, '');+ }+ assert.equal(count.style.display, '');+ assert.equal(bar.style.display, 'flex');+ state.batchMode = false;+ state.autoCopyAllBusy = true;+ context.setSessBatchBar(false);+ assert.ok(controls.every(control => !control.disabled));+ assert.equal(auto.disabled, true, 'an in-flight sync setting must remain disabled');+ assert.equal(bar.style.display, 'none');+ state.autoCopyAllBusy = false;+ context.updateAutoCopyAllButton();+ assert.equal(auto.disabled, false);+ state.batchMode = true;+ context.updateAutoCopyAllButton();+ assert.equal(auto.disabled, true, 'async completion must not unlock the batch header');+});test('session panel defaults its time filter to all sessions', () => {const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.jsnew file mode 100644index 0000000..6489736--- /dev/null+++ b/test/session-sync-daemon.test.js@@ -0,0 +1,266 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const vm = require('node:vm');+const crypto = require('node:crypto');+const lib = require('../scripts/lib.js');+const sessionSync = require('../scripts/session-sync.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) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-pair-daemon-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const rows = new Map();+ const file = id => path.join(root, 'projects', 'p', id + '.jsonl');+ const write = (id, messages) => { fs.mkdirSync(path.dirname(file(id)), { recursive: true }); fs.writeFileSync(file(id), messages.map(x => JSON.stringify(x)).join('\n') + '\n'); };+ const lineage = lib.ensureAutoCopySession(root, 'one', 'a');+ for (const [id, uid] of [['a', 'one'], ['b', 'two'], ['c', 'three']]) {+ rows.set(id, { id, user_id: uid, title: 'fixture', created_at: 1, updated_at: 1 });+ lib.addAutoCopySessionMember(root, lineage, uid, id); write(id, base);+ }+ const ctx = { ...lib, sessionSync, fs, path, crypto, DATA_DIR: root, PROFILE: { dataRoot: root, kind: 'workbuddy' },+ SESSION_COPY_COLUMNS: ['id', 'user_id'], sessionCopyLocks: new Map(), yieldAutoCopyToRenderer: async () => {}, assertSessionSyncIdle: async () => {},+ log: () => {}, sqliteQuery: async (_, params) => {+ 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 }); },+ };+ vm.runInNewContext(source.slice(source.indexOf('async function copySessionRecord('), 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 => {+ const h = harness(t); h.write('b', [...base, { type: 'message', role: 'user', content: [{ text: 'continued' }] }]);+ const third = fs.readFileSync(h.file('c'));+ const result = await h.copy();+ assert.equal(result.status, 'copied');+ assert.deepEqual(fs.readFileSync(h.file('a')), fs.readFileSync(h.file('b')));+ assert.deepEqual(fs.readFileSync(h.file('c')), third);+});+test('divergent copies survive repeated switches and stale mappings cannot force overwrite', async t => {+ const h = harness(t);+ h.write('a', [...base, { type: 'message', role: 'user', content: [{ text: 'branch one' }] }]);+ h.write('b', [...base, { type: 'message', role: 'user', content: [{ text: 'branch two' }] }]);+ const a = fs.readFileSync(h.file('a')), b = fs.readFileSync(h.file('b'));+ for (let i = 0; i < 2; i++) {+ const result = await h.copy();+ assert.equal(result.status, i === 0 ? 'copied' : 'skipped');+ if (i === 0) { assert.equal(result.branched, true); assert.deepEqual(fs.readFileSync(h.file(result.targetId)), a); }+ assert.equal([...h.rows.values()].filter(row => row.user_id === 'two').length, 2);+ assert.deepEqual(fs.readFileSync(h.file('a')), a); assert.deepEqual(fs.readFileSync(h.file('b')), b);+ }+});+test('missing target rows and missing target payloads are filled without consulting third-account conflicts', async t => {+ const h = harness(t); h.write('c', [{ type: 'message', role: 'user', content: [{ text: 'third branch' }] }]);+ fs.unlinkSync(h.file('b'));+ assert.equal((await h.copy()).status, 'copied');+ assert.deepEqual(fs.readFileSync(h.file('b')), fs.readFileSync(h.file('a')));+ h.rows.delete('b'); fs.unlinkSync(h.file('b'));+ lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b', updatedAt: 1 });+ const result = await h.copy();+ assert.equal(result.status, 'copied'); assert.notEqual(result.targetId, 'b');+ assert.equal((await h.copy()).status, 'skipped');+ assert.equal([...h.rows.values()].filter(row => row.user_id === 'two').length, 1);+});+test('manual and automatic switching bypass session activity while retaining operation locks', async () => {+ const start = source.indexOf('async function assertSessionSyncIdle(');+ const end = source.indexOf('let automationAccountSwitchTail', start);+ assert.ok(start >= 0 && end > start);+ 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(), /会话仍在运行/);+ ctx.cdpSend = async () => ({ result: { value: null } });+ await assert.rejects(ctx.assertSessionSyncIdle(), /无法确认/);+ ctx.cdpSend = async () => ({ result: { value: false } }); await ctx.assertSessionSyncIdle();+ ctx.cdp.connected = false;+ ctx.cdpSend = async () => { throw Error('Switching must not query session activity'); };+ const release = await ctx.assertAccountSwitchIdle();+ await assert.rejects(ctx.assertAccountSwitchIdle(), /账号正在切换/);+ release();+ ctx.cdp.connected = true;+ ctx.cdpSend = async () => ({ result: { value: true } });+ (await ctx.assertAccountSwitchIdle())();+ for (const key of ['autoCopyWorkerRunning', 'autoCopyQueue', 'sessionCopyLocks']) {+ const previous = ctx[key];+ ctx[key] = key === 'autoCopyWorkerRunning' ? true : key === 'autoCopyQueue' ? [{}] : new Map([['fixture', true]]);+ await assert.rejects(ctx.assertAccountSwitchIdle(), /会话同步尚未完成/);+ ctx[key] = previous;+ (await ctx.assertAccountSwitchIdle())();+ }+ for (const block of [source.slice(source.indexOf('function automationSwitchAccount('), source.indexOf('function startAutomationRun(')), source.slice(source.indexOf("if (req.method === 'POST' && p === '/api/switch')"))]) {+ assert.ok(block.indexOf('await assertAccountSwitchIdle()') < block.indexOf('switchTo(DATA_DIR, uid, log)'));+ }+});+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,+ 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' }; },+ log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout: () => ({ unref() {} }),+ };+ const start = source.indexOf('function startAutoCopyJob(');+ vm.runInNewContext(source.slice(start, source.indexOf('function publicAutoCopyJob(', start)), ctx);+ const job = ctx.startAutoCopyJob('one', 'two', []);+ await ctx.autoCopyQueue[0].run();+ assert.equal(job.processed, 4);+ 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);+ assert.deepEqual(Array.from(job.details, item => item.status), ['conflict', 'copied', 'skipped', 'failed']);+});+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/);+});++test('account switching copies valid messages alongside non-JSON workspace files without changing their bytes', async t => {+ const h = harness(t);+ const file = path.join(h.root, 'workspace/sessions/a/editor-settings.json');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const bytes = Buffer.from('// JSONC workspace fixture\n{"editor":true,}\n');+ fs.writeFileSync(file, bytes);+ const result = await h.copy();+ assert.equal(result.status, 'copied');+ assert.deepEqual(fs.readFileSync(path.join(h.root, 'workspace/sessions/b/editor-settings.json')), bytes);+ assert.deepEqual(fs.readFileSync(h.file('a')), fs.readFileSync(h.file('b')));+ assert.equal((await h.copy()).status, 'skipped');+ assert.equal(fs.existsSync(path.join(h.root, 'workspace/sessions/c/editor-settings.json')), false);+});++function addTarget(h, id, records = base) {+ h.rows.set(id, { ...h.rows.get('b'), id });+ lib.addAutoCopySessionMember(h.root, h.lineage, 'two', id);+ h.write(id, records);+}+const nextMessage = text => ({ type: 'message', role: 'user', content: [{ text }] });++test('multiple identical target copies skip without creating or rewriting sessions', async t => {+ const h = harness(t); addTarget(h, 'b2'); addTarget(h, 'b3');+ lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b2' });+ const before = [...h.rows.keys()].map(id => [id, fs.readFileSync(h.file(id))]);+ for (let i = 0; i < 2; i++) {+ const result = await h.copy();+ assert.equal(result.status, 'skipped'); assert.equal(result.targetId, 'b2');+ }+ assert.equal(h.rows.size, before.length);+ for (const [id, bytes] of before) assert.deepEqual(fs.readFileSync(h.file(id)), bytes);+ assert.equal(fs.existsSync(path.join(h.root, 'session-sync-backups')), false);+});++test('an exact copy is found even when the preferred duplicate is divergent or unreadable', async t => {+ const h = harness(t); addTarget(h, 'b2');+ lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b' });+ for (const content of ['{broken', JSON.stringify(nextMessage('other branch'))]) {+ fs.writeFileSync(h.file('b'), content);+ const result = await h.copy();+ assert.equal(result.status, 'skipped'); assert.equal(result.targetId, 'b2');+ assert.equal(fs.readFileSync(h.file('b'), 'utf8'), content);+ }+});++test('source continuation updates the closest proven base while preserving other copies and third accounts', async t => {+ const h = harness(t); const continued = [...base, nextMessage('next')];+ addTarget(h, 'b2', continued); addTarget(h, 'branch', [...base, nextMessage('different')]);+ h.write('a', [...continued, nextMessage('latest')]);+ lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'branch' });+ const untouched = ['b', 'branch', 'c'].map(id => [id, fs.readFileSync(h.file(id))]);+ const result = await h.copy();+ assert.equal(result.status, 'copied'); assert.equal(result.targetId, 'b2');+ assert.deepEqual(fs.readFileSync(h.file('b2')), fs.readFileSync(h.file('a')));+ for (const [id, bytes] of untouched) assert.deepEqual(fs.readFileSync(h.file(id)), bytes);+ assert.equal((await h.copy()).status, 'skipped');+ assert.equal(h.rows.size, 5);+});++test('multiple target continuations only update the source when they form one chain', async t => {+ const h = harness(t); const continued = [...base, nextMessage('next')];+ h.write('b', continued); addTarget(h, 'b2', [...continued, nextMessage('latest')]);+ const oldTarget = fs.readFileSync(h.file('b')), third = fs.readFileSync(h.file('c'));+ assert.equal((await h.copy()).status, 'copied');+ assert.deepEqual(fs.readFileSync(h.file('a')), fs.readFileSync(h.file('b2')));+ assert.deepEqual(fs.readFileSync(h.file('b')), oldTarget);+ assert.deepEqual(fs.readFileSync(h.file('c')), third);+});++test('divergent target continuations are reported as branches and never arbitrarily replace the source', async t => {+ const h = harness(t); h.write('b', [...base, nextMessage('branch one')]);+ addTarget(h, 'b2', [...base, nextMessage('branch two')]);+ lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b' });+ const before = [...h.rows.keys()].map(id => [id, fs.readFileSync(h.file(id))]);+ const result = await h.copy();+ assert.equal(result.status, 'copied'); assert.equal(result.branched, true);+ assert.deepEqual(fs.readFileSync(h.file(result.targetId)), fs.readFileSync(h.file('a')));+ for (const [id, bytes] of before) assert.deepEqual(fs.readFileSync(h.file(id)), bytes);+});++test('duplicates with only unreadable messages remain real failures and preserve every file', async t => {+ const h = harness(t); addTarget(h, 'b2');+ fs.writeFileSync(h.file('b'), '{broken'); fs.writeFileSync(h.file('b2'), '{also broken');+ await assert.rejects(h.copy(), /会话消息文件未写完或已损坏/);+ assert.equal(fs.readFileSync(h.file('b'), 'utf8'), '{broken');+ assert.equal(fs.readFileSync(h.file('b2'), 'utf8'), '{also broken');+});++test('a complete duplicate takes priority over repairing an incomplete copy', async t => {+ const h = harness(t); addTarget(h, 'b2');+ for (const id of ['a', 'b2']) {+ const file = path.join(h.root, 'tasks', id, 'output.txt');+ fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, 'fixture output');+ }+ lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b' });+ const result = await h.copy();+ assert.equal(result.status, 'skipped'); assert.equal(result.targetId, 'b2');+ assert.equal(fs.existsSync(path.join(h.root, 'tasks/b/output.txt')), false);+ assert.equal(fs.existsSync(path.join(h.root, 'session-sync-backups')), false);+});++test('no matching branch among multiple target copies preserves all versions without a copy failure', async t => {+ const h = harness(t);+ h.write('a', [...base, nextMessage('source branch')]);+ h.write('b', [...base, nextMessage('target branch one')]);+ addTarget(h, 'b2', [...base, nextMessage('target branch two')]);+ const before = [...h.rows.keys()].map(id => [id, fs.readFileSync(h.file(id))]);+ const result = await h.copy();+ assert.equal(result.status, 'copied'); assert.equal(result.branched, true); assert.equal(result.failedFiles, 0);+ for (const [id, bytes] of before) assert.deepEqual(fs.readFileSync(h.file(id)), bytes);+ assert.deepEqual(fs.readFileSync(h.file(result.targetId)), fs.readFileSync(h.file('a')));+ assert.equal(h.rows.size, before.length + 1);+ assert.equal((await h.copy()).status, 'skipped');+});+++test('a copied branch remains visible beside the original and later updates only its own continuation', async t => {+ const h = harness(t);+ h.write('a', [...base, nextMessage('source branch')]); h.write('b', [...base, nextMessage('target branch')]);+ const original = fs.readFileSync(h.file('b'));+ const result = await h.copy(); assert.equal(result.branched, true);+ const rules = lib.getAutoCopyRules(h.root, 'two');+ const targetRows = [...h.rows.values()].filter(row => row.user_id === 'two');+ 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')]);+ 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')));+ assert.deepEqual(fs.readFileSync(h.file('b')), original);+ assert.equal([...h.rows.values()].filter(row => row.user_id === 'two').length, 2);+ assert.equal((await h.copy()).status, 'skipped');+});++test('failed branch insertion leaves no visible row or copied files and a retry copies exactly once', async t => {+ const h = harness(t);+ h.write('a', [...base, nextMessage('source branch')]); h.write('b', [...base, nextMessage('target branch')]);+ const original = fs.readFileSync(h.file('b')), insert = h.ctx.insertCopiedSession;+ h.ctx.insertCopiedSession = async () => { throw Error('fixture insert failure'); };+ await assert.rejects(h.copy(), /fixture insert failure/);+ assert.equal(h.rows.size, 3);+ assert.equal(fs.readdirSync(path.dirname(h.file('a'))).filter(name => name.endsWith('.jsonl')).length, 3);+ assert.deepEqual(fs.readFileSync(h.file('b')), original);+ h.ctx.insertCopiedSession = insert;+ assert.equal((await h.copy()).status, 'copied');+ assert.equal((await h.copy()).status, 'skipped');+ assert.equal(h.rows.size, 4);+});diff --git a/test/session-sync.test.js b/test/session-sync.test.jsnew file mode 100644index 0000000..606eef5--- /dev/null+++ b/test/session-sync.test.js@@ -0,0 +1,176 @@+'use strict';+const test = require('node:test');+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 message = (role, text) => ({ type: 'message', role, content: [{ type: 'text', text }] });+const base = [message('user', 'question'), message('assistant', 'answer')];+function fixture(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-prefix-sync-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const file = id => path.join(root, 'projects', 'project', id + '.jsonl');+ const write = (id, records) => {+ fs.mkdirSync(path.dirname(file(id)), { recursive: true });+ fs.writeFileSync(file(id), records.map(value => JSON.stringify(value)).join('\n') + '\n');+ };+ return { root, file, write, read: id => readSnapshot(root, id, ['a', 'b', 'c']) };+}+test('same content skips; only a full prefix permits replacement, irrespective of mtime', t => {+ const f = fixture(t); f.write('a', base); f.write('b', base);+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'equal');+ f.write('b', [...base, message('user', 'next'), message('assistant', 'more')]);+ fs.utimesSync(f.file('b'), new Date(0), new Date(0));+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'right-extends');+ assert.equal(compareSnapshots(f.read('b'), f.read('a')).kind, 'left-extends');+ f.write('a', [...base, message('user', 'different')]);+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'conflict');+});+test('equal user messages cannot hide different replies, tools or attachments', t => {+ const f = fixture(t);+ for (const records of [+ [base[0], message('assistant', 'different answer')],+ [...base, { type: 'function_call_result', output: 'changed' }],+ [{ ...base[0], content: [{ type: 'image', url: 'different.png' }] }, base[1]],+ ]) {+ f.write('a', [...base, { type: 'function_call_result', output: 'original' }]); f.write('b', records);+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'conflict');+ }+});+test('only identity fields normalize; literal session IDs inside messages remain meaningful', t => {+ const f = fixture(t); f.write('a', base.map(v => ({ ...v, sessionId: 'a' })));+ f.write('b', base.map(v => ({ ...v, sessionId: 'b' })));+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'equal');+ 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 => {+ 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'), /符号链接/);+});+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);+ const aux = id => path.join(f.root, 'tasks', id, 'file.txt');+ fs.mkdirSync(path.dirname(aux('a')), { recursive: true }); fs.writeFileSync(aux('a'), 'original');+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'repair');+ fs.mkdirSync(path.dirname(aux('b')), { recursive: true }); fs.writeFileSync(aux('b'), 'different');+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'conflict');+});+test('update retains a backup, validates bytes, and never changes a third copy', async t => {+ const f = fixture(t); f.write('a', base); f.write('b', [...base, message('user', 'next')]); f.write('c', base);+ const original = fs.readFileSync(f.file('a')); let committed = false;+ const result = await applySnapshot(f.read('b'), f.read('a'), {+ backupRoot: path.join(f.root, 'backups'), metadata: { id: 'a', title: 'old' },+ commit: async () => { committed = true; },+ });+ assert.equal(committed, true);+ assert.deepEqual(fs.readFileSync(f.file('a')), fs.readFileSync(f.file('b')));+ assert.deepEqual(fs.readFileSync(f.file('c')), original);+ assert.deepEqual(fs.readFileSync(path.join(result.backup, 'files', 'projects', 'project', '__session__.jsonl')), original);+});+test('failed commit restores target bytes; source changes abort before publication', async t => {+ const f = fixture(t); f.write('a', base); f.write('b', [...base, message('user', 'next')]);+ const original = fs.readFileSync(f.file('a'));+ await assert.rejects(applySnapshot(f.read('b'), f.read('a'), {+ backupRoot: path.join(f.root, 'backups'), commit: async () => { throw Error('DB failure'); },+ }), /DB failure/);+ assert.deepEqual(fs.readFileSync(f.file('a')), original);+ const source = f.read('b'); f.write('b', [...base, message('user', 'changed while copying')]);+ await assert.rejects(applySnapshot(source, f.read('a'), { backupRoot: path.join(f.root, 'backups') }), /变化/);+ assert.deepEqual(fs.readFileSync(f.file('a')), original);+});+test('rollback preserves concurrent official writes instead of replacing them with old bytes', async t => {+ const f = fixture(t); f.write('a', base); f.write('b', [...base, message('user', 'next')]);+ await assert.rejects(applySnapshot(f.read('b'), f.read('a'), {+ backupRoot: path.join(f.root, 'backups'), commit: async () => {+ f.write('a', [...base, message('user', 'official new content')]); throw Error('concurrent update');+ },+ }), /concurrent update/);+ assert.match(fs.readFileSync(f.file('a'), 'utf8'), /official new content/);+});+test('a change to any target file during the final async check prevents metadata commit', async t => {+ const f = fixture(t); f.write('a', base); f.write('b', [...base, message('user', 'next')]);+ let committed = false;+ await assert.rejects(applySnapshot(f.read('b'), f.read('a'), {+ backupRoot: path.join(f.root, 'backups'), commit: async verifyPublished => {+ const extra = path.join(f.root, 'tasks', 'a', 'new.txt');+ fs.mkdirSync(path.dirname(extra), { recursive: true }); fs.writeFileSync(extra, 'official write');+ verifyPublished(); committed = true;+ },+ }), /目标会话正在变化/);+ assert.equal(committed, false);+ assert.match(fs.readFileSync(path.join(f.root, 'tasks', 'a', 'new.txt'), 'utf8'), /official write/);+ assert.equal(f.read('a').records.length, base.length);+});+test('failure to finalize a committed backup journal must never roll back committed files', async t => {+ const f = fixture(t); f.write('a', base); f.write('b', [...base, message('user', 'next')]);+ const backupRoot = path.join(f.root, 'backups');+ await applySnapshot(f.read('b'), f.read('a'), {+ backupRoot, commit: async () => {+ const journal = path.join(backupRoot, fs.readdirSync(backupRoot)[0], 'journal.json');+ fs.unlinkSync(journal); fs.mkdirSync(journal);+ },+ });+ assert.deepEqual(fs.readFileSync(f.file('a')), fs.readFileSync(f.file('b')));+});+test('sync remaps artifact ownership and preserves foreign owners and request IDs', async t => {+ const f = fixture(t); f.write('a', base);+ fs.mkdirSync(path.join(f.root, 'artifact-index'));+ fs.writeFileSync(path.join(f.root, 'artifact-index', 'a.json'), JSON.stringify({ artifacts: [+ { requestId: 'request-42', _meta: { ownerConversationId: 'a' } },+ { requestId: 'foreign-42', _meta: { ownerConversationId: 'foreign' } },+ ] }));+ await applySnapshot(f.read('a'), f.read('b'), { backupRoot: path.join(f.root, 'backups') });+ const artifacts = JSON.parse(fs.readFileSync(path.join(f.root, 'artifact-index', 'b.json'))).artifacts;+ assert.deepEqual(artifacts, [+ { requestId: 'request-42', _meta: { ownerConversationId: 'b' } },+ { requestId: 'foreign-42', _meta: { ownerConversationId: 'foreign' } },+ ]);+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'equal');+});++test('workspace and history JSON files are opaque work products, not conversation metadata', async t => {+ const f = fixture(t); f.write('a', base);+ const files = [+ ['workspace/sessions', 'settings.json', Buffer.from('// editor settings may use comments\n{"enabled":true,}\n')],+ ['workspace/sessions', 'unfinished.json', Buffer.from('{"draft":')],+ ['workspace/sessions', 'empty.json', Buffer.alloc(0)],+ ['file-history', 'snapshot.json', Buffer.from([0, 255, 254, 1])],+ ['projects/project', 'notes.json', Buffer.from('This is a work product, not a message record')],+ ];+ for (const [prefix, name, bytes] of files) {+ const file = path.join(f.root, prefix, 'a', name);+ fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, bytes);+ }+ const source = f.read('a');+ assert.equal(compareSnapshots(source, f.read('b')).kind, 'left-extends');+ await applySnapshot(source, f.read('b'), { backupRoot: path.join(f.root, 'backups') });+ for (const [prefix, name, bytes] of files) assert.deepEqual(fs.readFileSync(path.join(f.root, prefix, 'b', name)), bytes);+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'equal');+ fs.writeFileSync(path.join(f.root, 'workspace/sessions/b/unfinished.json'), '{"different":');+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'conflict');+});++test('JSON work product fields must not be normalized as session identity', t => {+ const f = fixture(t); f.write('a', base); f.write('b', base);+ for (const id of ['a', 'b']) {+ const file = path.join(f.root, 'workspace/sessions', id, 'data.json');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, JSON.stringify({ sessionId: id, conversationId: id }));+ }+ assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'conflict');+});++test('malformed official artifact index still blocks sync and names the failing index', t => {+ const f = fixture(t); f.write('a', base);+ fs.mkdirSync(path.join(f.root, 'artifact-index'));+ fs.writeFileSync(path.join(f.root, 'artifact-index/a.json'), '{broken');+ assert.throws(() => f.read('a'), /会话产物索引损坏,未同步/);+});diff --git a/test/sleep-mode.test.js b/test/sleep-mode.test.jsindex dd50635..bfdf38a 100644--- a/test/sleep-mode.test.js+++ b/test/sleep-mode.test.js@@ -60,7 +60,9 @@ test('until-done waits for every discovered session, including blocked and recen{conversationId:'a', busy:true}, {conversationId:'b', blocked:true},];const posts = [];+ const disposers = [];const ctx = {+ window: {}, registerDisposer: fn => disposers.push(fn),Date: {now:()=>now}, document:{}, alive:true, sleepMode:'until-done',acMulti:{sessions:{}}, sleepSessionCache:Object.create(null), sleepUntilDoneCheck:null,WBS_COMPAT:{findConversationControllers:()=>controllers},@@ -71,6 +73,7 @@ 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);ctx.startUntilDoneCheck();poll(); assert.equal(posts.length, 0);controllers[0].busy = false;@@ -80,4 +83,9 @@ test('until-done waits for every discovered session, including blocked and recencontrollers.push({conversationId:'b', busy:false});poll(); await Promise.resolve();assert.deepEqual(posts, [{mode:'allow', displaySleep:false}]);+ assert.equal(ctx.window.__wbsAnySessionBusy(), false);+ ctx.alive = false;+ assert.equal(ctx.window.__wbsAnySessionBusy(), null);+ disposers.forEach(fn => fn());+ assert.equal(ctx.window.__wbsAnySessionBusy, undefined);});diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 49eaf7b..7b1bab0 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -203,16 +203,13 @@ test('WorkDaddy-triggered reload injects on the new main execution context beforassert.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 syncStart = script.indexOf('async function syncAutoCopyLineage(', yieldStart);+ const syncStart = script.indexOf('const MAX_SESSION_EXPORT_FILES', yieldStart);const yieldHelper = script.slice(yieldStart, syncStart);assert.match(yieldHelper, /setImmediate/);assert.match(yieldHelper, /rendererReloadPriorityPromise/);assert.match(yieldHelper, /await reloadPriority/);assert.match(yieldHelper, /pendingReloadInjection/);assert.match(yieldHelper, /await pending\.ready/);- const syncEnd = script.indexOf('\nconst MAX_SESSION_EXPORT_FILES', syncStart);- const syncLineage = script.slice(syncStart, syncEnd);- assert.ok((syncLineage.match(/await yieldAutoCopyToRenderer\(\)/g) || []).length >= 2, 'lineage scans and copies must pause for renderer reloads');assert.match(switchRoute, /const releaseRendererReload = body\.reload \? beginRendererReloadPriority\(\) : null/);assert.match(switchRoute, /finally \{\s*if \(releaseRendererReload\) releaseRendererReload\(\)/);});@@ -1151,13 +1148,13 @@ test('automatic session copy includes workspace-only rules when the initial planassert.match(daemon, /GET' && p === '\/api\/sessions\/auto-copy\/status'/);assert.match(daemon, /getAutoCopyMapping\(DATA_DIR, lineageId, targetUid\)/);assert.match(daemon, /getAutoCopySessionMembers\(DATA_DIR, lineageId, targetUid\)/);- assert.match(daemon, /const canonicalId = candidates\[0\]\.id/);+ assert.match(daemon, /const existing = candidates\.find\(/);assert.match(daemon, /const sourceRules = sourceUid \? getAutoCopyRules\(DATA_DIR, sourceUid\)/);assert.match(daemon, /hasSourceAutoCopyRules/);assert.match(daemon, /hasPendingAutoCopyTo\(uid\)/);assert.match(daemon, /startAutoCopyJob\(sourceUid, uid, \[\]/);- assert.match(daemon, /syncAutoCopyLineage\(src\.lineageId, targetUid\)/);- assert.match(daemon, /selectLatestAutoCopyMember\(live\)/);+ 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(inject, /data-auto-kind="' \+ kind \+ '"/);assert.match(inject, /autoCopyButton\('workspace'/);@@ -1170,7 +1167,11 @@ test('session copy-all is a separate override with a distinct toggle and hiddenassert.match(daemon, /POST' && p === '\/api\/sessions\/auto-copy-all'/);assert.match(daemon, /sourceRules\.allSessions/);assert.match(inject, /id="wbs-sess-auto-all"/);- assert.match(inject, /id="wbs-sess-import"[\s\S]*id="wbs-sess-auto-all"/);+ const filters = inject.slice(inject.indexOf('<div class="wbs-sess-filters">'), inject.indexOf('<div class="wbs-sess-toolbar">'));+ assert.match(filters, /id="wbs-sess-auto-all"[\s\S]*id="wbs-sess-account-select"[\s\S]*id="wbs-sess-range-seg"/);+ assert.equal((filters.match(/<div\b/g) || []).length, (filters.match(/<\/div>/g) || []).length);+ assert.match(inject, /\.wbs-sess-filters\{[^}]*flex-wrap:wrap/);+ assert.match(inject, /id="wbs-sess-import"[\s\S]*id="wbs-sess-count"/);assert.match(inject, /id="wbs-sess-auto-all"[^>]*role="checkbox"[^>]*aria-checked="false"/);assert.match(inject, /wbs-sess-auto-all-box/);assert.match(inject, /getAttribute\('aria-checked'\)/);@@ -1187,13 +1188,13 @@ test('session copy-all is a separate override with a distinct toggle and hiddenassert.match(inject, /\.wbs-sess-summary-tag\{[^}]*border:0[^}]*background:transparent/);});-test('session auto-copy plans and API responses collapse duplicate rows by account lineage', () => {+test('session auto-copy plans preserve physical source rows while list APIs deduplicate display', () => {const daemon = read('daemon.js');const lib = read('lib.js');- assert.match(lib, /function dedupeAutoCopySessionRows\(rows, lineagesByUid\)/);+ assert.match(lib, /function dedupeAutoCopySessionRows\(rows, lineagesByUid, branchesByUid/);assert.match(lib, /const allLineages = \{\}/);- assert.match(daemon, /dedupeAutoCopySessionRows\(rows, \{ \[source\]: rules\.allLineages \}\)/);- assert.match(daemon, /dedupeAutoCopySessionRows\(rows, lineagesByUid\)/);+ assert.match(daemon, /rows\.filter\(/);+ assert.match(daemon, /dedupeAutoCopySessionRows\(rows, lineagesByUid, branchesByUid\)/);assert.match(daemon, /const DAEMON_VERSION = '\d+\.\d+\.\d+'/);});@@ -1213,7 +1214,7 @@ test('session pane restores and renders persistent auto-copy progress', () => {test('account switching shows a compact copy notice and defers conflict feedback until completion', () => {const daemon = read('daemon.js');const inject = read('inject.js');- assert.match(daemon, /conflict: true/);+ assert.match(daemon, /branched: branched && changed/);assert.match(daemon, /conflicts: 0/);assert.match(daemon, /job\.status = job\.conflicts \? 'conflict'/);assert.match(daemon, /failedItems: 0/);@@ -1222,15 +1223,15 @@ test('account switching shows a compact copy notice and defers conflict feedbackassert.match(daemon, /sourceName: job\.sourceName/);assert.match(daemon, /targetName: job\.targetName/);assert.match(daemon, /details: Array\.isArray\(job\.details\)/);- assert.match(daemon, /unchanged: true/);+ assert.match(daemon, /changed \? 'copied' : 'skipped'/);assert.match(inject, /wbs-session-copy-notice/);assert.match(inject, /function pollSessionCopyNotice\(jobId, accountName\)/);assert.match(inject, /sessionCopySummaryText\(job\)/);- assert.match(inject, /会话同步完成,发现冲突/);+ assert.match(inject, /会话同步完成,已保留分叉/);assert.match(inject, /会话同步明细/);assert.match(inject, /会话同步结果筛选/);assert.match(inject, /正在同步已标记会话/);- assert.match(inject, /setBuildTimeout\(closeSessionCopyNotice, 10000\)/);+ assert.match(inject, /setBuildTimeout\(closeSessionCopyNotice, 5000\)/);assert.match(inject, /sessionCopyNoticeChecked/);assert.match(inject, /sessionCopyNoticeActiveAttempts < 10/);assert.match(inject, /data-session-copy-details/);@@ -1247,6 +1248,42 @@ test('account switching shows a compact copy notice and defers conflict feedbackassert.match(inject, /html\.cb-dark \.wbs-session-copy-notice/);});+test('session conflict reset is retired and details stay at the left', () => {+ const daemon = read('daemon.js');+ const inject = read('inject.js');+ const route = daemon.slice(daemon.indexOf("if (req.method === 'POST' && p === '/api/sessions/auto-copy/reset')"));+ assert.match(route.slice(0, 300), /json\(res, 410/);+ assert.doesNotMatch(inject, /data-session-copy-reset|sessionCopyResetError/);+ assert.match(inject, /会话已分叉,已保留双方内容/);+ assert.match(inject, /\.wbs-session-copy-actions\{[^}]*justify-content:flex-start/);+});++test('credit expiry summary keeps per-account nodes and reuses the compact usage segment', () => {+ const inject = read('inject.js');+ const summaryStart = inject.indexOf('function setupCreditSummary()');+ const summaryEnd = inject.indexOf('function openOfficialGrowthCenter()', summaryStart);+ const summary = inject.slice(summaryStart, summaryEnd);+ assert.match(inject, /function creditSummaryTip\(segment\)/);+ assert.match(inject, /segments:\s*\[\]/);+ assert.match(summary, /row\.segments/);+ assert.match(summary, /class="wbs-credit-segment"/);+ assert.match(summary, /listen\(popup, 'mouseover'/);++ const modalStart = inject.indexOf('<div class="wbs-usage-tabs">');+ const modalTabs = inject.slice(modalStart, modalStart + 280);+ assert.ok(modalTabs.indexOf('data-usage-tab="credit"') < modalTabs.indexOf('data-usage-tab="token"'));+ assert.match(modalTabs, /class="active" data-usage-tab="credit"/);+ assert.match(inject, /<div data-usage-pane="token" hidden>/);+ assert.match(inject, /<div data-usage-pane="credit">/);+ assert.match(inject, /if \(mask\.querySelector\('\[data-usage-tab\]\.active'\).*loadCredits\(\); else load\(\);/);+ assert.match(inject, /class="wbs-usage-segment wbs-sess-seg" id="wbs-sess-range-seg"/);+ assert.match(inject, /\.wbs-sess-time-filter \.wbs-sess-seg\{[^}]*flex:1 1 auto[^}]*width:auto/);+ assert.match(inject, /\.wbs-sess-account-filter\{[^}]*flex:0 1 190px/);+ assert.match(inject, /\.wbs-sess-seg button\{[^}]*flex:1 1 0[^}]*min-width:0/);+ assert.match(inject, /\.wbs-credit-tip-account\{[^}]*color:var\(--wb-icon-tertiary[^}]*font-size:10px/);+ assert.match(inject, /\.wbs-status-popover\.is-credit\{[^}]*height:auto[^}]*max-height:calc\(100vh - 16px\)/);+});+test('session summary counts effective sessions and models tab only exposes sanitized model APIs', () => {const daemon = read('daemon.js');const inject = read('inject.js');