Skip to content

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

修复 windows 安装问题;悬浮按钮可拖拽;查询今日使用积分;修复其他问题;

[email protected]dd3eb380ce1e
diff --cc AGENTS.md
index d5f32d6,d5f32d6..35b9d2b
--- a/AGENTS.md
+++ b/AGENTS.md
@@@ -109,9 -109,9 +109,57 @@@ The queue item's 暂存提示词 tag i
- 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.
- 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.
--- Every Windows Setup.exe payload and macOS DMG staging directory must include `安装失败自主解决提示词.txt`; `scripts/verify-win.cmd` must treat the Windows copy as required. Inspect the packaged prompt filename/encoding along with the other release contents.
++- 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.
++## Windows Packaging Runbook
++
++Use this exact flow for a Windows release. The two client packages are built from the same source tree, but each is staged with its own profile, installation directory, daemon port, desktop shortcut, and WorkBuddy executable name.
++
++1. Start from the requested source commit/branch and confirm the working tree. Do not silently change the release version in `scripts/daemon.js` when producing a fixed-version package; pass the requested version explicitly to the release script.
++
++2. From the repository root, run the Windows release builder with Git Bash, Inno Setup 6, and Python available:
++
++ ```powershell
++ powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-win-release.ps1 -Version 1.1.2
++ ```
++
++ `build-win-release.ps1` must build both `workbuddy-cn` and `workbuddy-ai`. `build-win-zip.sh` creates only an internal staging ZIP; `build-win-installer.ps1` rewrites the staged daemon version and build id to the requested release version before compiling Setup.exe. Do not hand-copy scripts into an old installer directory.
++
++3. Deliver only these files:
++
++ ```text
++ release/windows/WorkDaddy-Setup-1.1.2.exe
++ release/windows/WorkDaddy-AI-Setup-1.1.2.exe
++ ```
++
++ Remove the generated `WorkDaddy-1.1.2-win64.zip`, `WorkDaddy-AI-1.1.2-win64.zip`, and `release/.cache` before handoff or publication. The ZIPs are staging inputs, not Windows release artifacts. Confirm that `安装失败自主解决提示词.txt` is absent from both Setup.exe payloads.
++
++4. Inspect the actual Setup.exe payloads, not just their filenames. Run `innounp -t` on both files, list or extract them, and verify all of the following for each package:
++
++ - `scripts/runtime/node/node.exe` exists.
++ - `scripts/daemon.js` reports the requested version, here `1.1.2`.
++ - `scripts/win-launcher.js`, `scripts/watchdog.js`, and the required PowerShell scripts are present.
++ - CN uses `workbuddy-cn`, `47832`, `9222` as its defaults; AI uses `workbuddy-ai`, `47833`, `9223`.
++ - The package contains no `安装失败自主解决提示词.txt` and no temporary ZIP.
++
++5. Run release checks from the same repository:
++
++ ```powershell
++ node --check scripts/daemon.js
++ node --check scripts/inject.js
++ node --check scripts/win-launcher.js
++ node --check scripts/watchdog.js
++ node --test test/*.test.js
++ git diff --check
++ ```
++
++ A 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.
++
++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.
++
## Change Workflow
1. Read the surrounding code and existing tests before editing.
diff --cc release/macos/WorkDaddy-1.1.2.dmg
index 1399f57,8e7ceb2..ea74172
Binary files differ
diff --cc release/macos/WorkDaddy-AI-1.1.2.dmg
index d5d6e0a,1031187..7cd5923
Binary files differ
diff --cc release/windows/WorkDaddy-AI-Setup-1.1.2.exe
index 6d3a993,cf76b6f..186ca23
Binary files differ
diff --cc release/windows/WorkDaddy-Setup-1.1.2.exe
index e40505a,16e08c4..8c2fef4
Binary files differ
diff --cc scripts/atomic-file-write.js
index 0000000,0000000..826dc55
new file mode 100644
--- /dev/null
+++ b/scripts/atomic-file-write.js
@@@ -1,0 -1,0 +1,55 @@@
++'use strict';
++
++const crypto = require('crypto');
++const fs = require('fs');
++
++const WINDOWS_TRANSIENT_CODES = new Set(['UNKNOWN', 'EPERM', 'EACCES', 'EBUSY', 'EMFILE', 'ENFILE']);
++
++function defaultSleep(ms) {
++ if (ms <= 0) return;
++ const buffer = new SharedArrayBuffer(4);
++ Atomics.wait(new Int32Array(buffer), 0, 0, ms);
++}
++
++function defaultSuffix() {
++ return `${process.pid}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
++}
++
++function replaceFileWithRetry(file, content, mode, options = {}) {
++ const fileSystem = options.fs || fs;
++ const platform = options.platform || process.platform;
++ const sleep = options.sleep || defaultSleep;
++ const suffix = options.suffix || defaultSuffix;
++ const maxAttempts = platform === 'win32' ? 80 : 1;
++ const tmp = `${file}.wbs-tmp-${suffix()}`;
++ let tempReady = false;
++ let lastError = null;
++
++ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
++ try {
++ if (!tempReady) {
++ fileSystem.writeFileSync(tmp, content, 'utf8');
++ if (mode !== undefined) fileSystem.chmodSync(tmp, mode);
++ tempReady = true;
++ }
++ fileSystem.renameSync(tmp, file);
++ return;
++ } catch (error) {
++ lastError = error;
++ const retryable = platform === 'win32' && WINDOWS_TRANSIENT_CODES.has(error && error.code);
++ if (!tempReady) {
++ try { fileSystem.unlinkSync(tmp); } catch (_) {}
++ }
++ if (!retryable || attempt === maxAttempts) break;
++ if (attempt === 1 && error && error.code === 'EPERM') {
++ try { fileSystem.chmodSync(file, 0o666); } catch (_) {}
++ }
++ sleep(Math.min(250, 50 + attempt * 10));
++ }
++ }
++
++ try { fileSystem.unlinkSync(tmp); } catch (_) {}
++ throw lastError;
++}
++
++module.exports = { replaceFileWithRetry, WINDOWS_TRANSIENT_CODES };
diff --cc scripts/build-mac-dmg.sh
index 15443bf,15443bf..9b4ccba
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@@ -43,7 -43,7 +43,7 @@@ chmod 755 "$APP/Contents/MacOS/launcher
echo "==> launcher 可执行位已保证: $(stat -f '%Sp' "$APP/Contents/MacOS/launcher")"
# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)
--for f in daemon.js session-db.js windows-process-boundary.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js lib.js profiles.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
++for f in daemon.js session-db.js windows-process-boundary.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-usage-store.js atomic-file-write.js ui-port.js checkin-result.js lib.js profiles.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"
done
# 恢复这些文件的壳权限(与 1.0.3 壳内一致:sh/lib/daemon 755,inject/theme-patches 644)
@@@ -56,6 -56,6 +56,11 @@@ chmod 755 "$APP/Contents/Resources/scri
"$APP/Contents/Resources/scripts/apply-update.sh"
chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \
"$APP/Contents/Resources/scripts/windows-process-boundary.js" \
++ "$APP/Contents/Resources/scripts/credit-request-usage.js" \
++ "$APP/Contents/Resources/scripts/credit-usage-store.js" \
++ "$APP/Contents/Resources/scripts/atomic-file-write.js" \
++ "$APP/Contents/Resources/scripts/ui-port.js" \
++ "$APP/Contents/Resources/scripts/checkin-result.js" \
"$APP/Contents/Resources/scripts/inject.js" \
"$APP/Contents/Resources/scripts/theme-patches.js"
echo "==> 前端代码已覆盖(权限按壳原样)"
diff --cc scripts/build-win-installer.ps1
index e3bc3bb,b71b727..26a1025
--- a/scripts/build-win-installer.ps1
+++ b/scripts/build-win-installer.ps1
@@@ -61,10 -61,12 +61,6 @@@ try
if (-not $stagedVersionMatch.Success -or $stagedVersionMatch.Groups[1].Value -ne $version) {
throw "ZIP 内部 daemon 版本与安装器版本不一致: $($stagedVersionMatch.Groups[1].Value) != $version"
}
-- $prompt = Join-Path $stageRoot '安装失败自主解决提示词.txt'
-- if (-not (Test-Path -LiteralPath $prompt -PathType Leaf)) {
-- throw 'The ZIP payload is missing 安装失败自主解决提示词.txt.'
-- }
- Copy-Item -LiteralPath $prompt -Destination (Join-Path $stageRoot 'troubleshooting.txt') -Force
-
$iss = Join-Path $scriptsRoot 'win\workdaddy.iss'
$args = @(
"/DAppVersion=$version",
diff --cc scripts/build-win-zip.sh
index a0c31f6,a0c31f6..4b3d0fc
--- a/scripts/build-win-zip.sh
+++ b/scripts/build-win-zip.sh
@@@ -119,10 -119,10 +119,6 @@@ f
# 3.1) 顶层入口(zip 根):Install-WorkDaddy.cmd / Start-WorkDaddy.cmd
cp scripts/Install-WorkDaddy.cmd "$STAGE/Install-WorkDaddy.cmd"
cp scripts/Start-WorkDaddy.cmd "$STAGE/Start-WorkDaddy.cmd"
--# 3.1a) Windows 故障排查提示词(供用户在安装失败时交给修复 agent)
--if [ -f "$DIR/安装失败自主解决提示词.txt" ]; then
-- cp "$DIR/安装失败自主解决提示词.txt" "$STAGE/安装失败自主解决提示词.txt"
--fi
# 3.2) scripts\ 本体(含 node_modules/ws、builtin)
cp -R scripts "$STAGE/scripts"
# Windows cmd.exe expects CRLF in batch files. Normalise every staged .cmd
@@@ -321,20 -321,20 +317,18 @@@ patch('scripts/verify-win.cmd',
print('==> 品牌化替换完成(Install/Start/install-win/launcher/verify-win + base64 提示)')
PY
fi
--# 3.3.5) 非 ASCII 文件名守护:仅允许根目录的故障排查提示词,其余路径必须保持 ASCII。
++# 3.3.5) 非 ASCII 文件名守护:Windows 安装包路径必须保持 ASCII。
# macOS 自带 Info-ZIP 会使用 UTF-8 条目写入;安装/更新脚本本身仍全部使用 ASCII 路径。
NON_ASCII_PATHS="$(find "$STAGE" -not -path '*/node_modules/*' 2>/dev/null | LC_ALL=C grep '[^ -~]' || true)"
--UNEXPECTED_NON_ASCII="$(printf '%s\n' "$NON_ASCII_PATHS" | LC_ALL=C grep -v '安装失败自主解决提示词\.txt$' || true)"
--if [ -n "$UNEXPECTED_NON_ASCII" ]; then
-- echo "==> ERROR: 发布包包含未批准的非 ASCII 文件路径,已终止打包!"
-- printf '%s\n' "$UNEXPECTED_NON_ASCII" | head -20
++if [ -n "$NON_ASCII_PATHS" ]; then
++ echo "==> ERROR: 发布包包含非 ASCII 文件路径,已终止打包!"
++ printf '%s\n' "$NON_ASCII_PATHS" | head -20
rm -rf "$STAGE" 2>/dev/null || true
exit 3
fi
--echo "==> 非 ASCII 文件名守护通过(仅包含批准的故障排查提示词)"
--# 3.4) 打包:优先使用 Python zipfile,确保中文提示词写入 UTF-8 文件名标记。
--# macOS 自带 zip 会把中文文件名按本地代码页写入,Windows/Python 解压后会出现乱码。
--# 没有 Python 且需要中文提示词时直接失败,避免生成名字损坏的发布包。
++echo "==> 非 ASCII 文件名守护通过"
++# 3.4) 打包:优先使用 Python zipfile,确保 Windows 条目编码稳定。
++# macOS 自带 zip 会把非 ASCII 文件名按本地代码页写入,Windows/Python 解压后会出现乱码。
if [ -n "$PYTHON_BIN" ]; then
"$PYTHON_BIN" - "$(winpath "$STAGE")" "$(winpath "$DIR/$OUT")" <<'PY'
import os
@@@ -355,11 -355,11 +349,7 @@@ with zipfile.ZipFile(output, 'w', compr
arcname = os.path.relpath(source, stage).replace(os.sep, '/')
archive.write(source, arcname)
PY
--elif [ -f "$STAGE/安装失败自主解决提示词.txt" ]; then
-- echo "==> ERROR: 包含中文故障排查提示词,但当前环境没有可用 Python,无法生成 UTF-8 ZIP。"
-- rm -rf "$STAGE" 2>/dev/null || true
-- exit 4
--elif command -v zip >/dev/null 2>&1; then
++ elif command -v zip >/dev/null 2>&1; then
(cd "$STAGE" && zip -r -q "$DIR/$OUT" .)
else
tar -a -cf "$DIR/$OUT" -C "$STAGE" .
diff --cc scripts/checkin-result.js
index 0000000,0000000..fec7d78
new file mode 100644
--- /dev/null
+++ b/scripts/checkin-result.js
@@@ -1,0 -1,0 +1,27 @@@
++'use strict';
++
++const INACTIVE_MESSAGE = /未开启|未开始|未开放|已过期|无.*活动|活动.*(?:结束|关闭|暂停)/i;
++const ALREADY_MESSAGE = /已签到|已领取|已经.*(?:签到|领取)|重复签到|already\s*(?:checked[- ]?in|claimed)|already/i;
++
++function numericCode(value) {
++ if (value === null || value === undefined || value === '') return null;
++ const number = Number(value);
++ return Number.isFinite(number) ? number : null;
++}
++
++/**
++ * Accept only an explicit successful response from the official check-in API.
++ * A successful HTTP status alone is insufficient because gateways can return
++ * an empty or non-JSON 200 response. Code 10001 is accepted only when its
++ * message proves that today's check-in was already completed.
++ */
++function classifyCheckinResult({ httpOk, code, message }) {
++ const normalizedCode = numericCode(code);
++ const text = String(message || '');
++ const inactive = INACTIVE_MESSAGE.test(text);
++ const already = normalizedCode === 10001 && !inactive && ALREADY_MESSAGE.test(text);
++ const ok = !!httpOk && !inactive && (normalizedCode === 0 || already);
++ return { ok, already, inactive, code: normalizedCode, message: text };
++}
++
++module.exports = { classifyCheckinResult, INACTIVE_MESSAGE, ALREADY_MESSAGE };
diff --cc scripts/credit-request-usage.js
index 0000000,9f4c10d..30b0aad
mode 000000,100644..100644
--- a/scripts/credit-request-usage.js
+++ b/scripts/credit-request-usage.js
@@@ -1,0 -1,115 +1,197 @@@
+ 'use strict';
+
-// 今日已用积分:调用 WorkBuddy 官方接口 /billing/meter/get-user-request-usage,
-// 按「今天 0 点 ~ 当前」的时间范围拉取逐条请求的积分消耗(credit),求和得到精确今日已用。
-// 相比本地基线法(当日观测最大剩余 − 当前剩余),官方接口记录了每一条请求,没有跨天盲区。
++const DEFAULT_PAGE_SIZE = 100;
++const DEFAULT_MAX_PAGES = 100;
++const DEFAULT_REQUEST_TIMEOUT_MS = 8000;
+
-// 单次请求分页大小(官方接口单页上限有限,用较大的分页减少请求次数)
-const PAGE_SIZE = 100;
++function pad2(value) {
++ return String(value).padStart(2, '0');
++}
+
+ function formatLocalDateTime(date) {
- const pad = (n) => String(n).padStart(2, '0');
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
++ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ` +
++ `${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`;
+ }
+
+ function startOfLocalDay(date) {
- const d = new Date(date.getTime());
- d.setHours(0, 0, 0, 0);
- return d;
-}
-
-/**
- * 纯函数:对接口返回的请求记录,按 requestTime 落在 [startMs, endMs] 内过滤,汇总 credit。
- * @param {Array} rows 接口返回的 data.data[]
- * @param {number} startMs 时间范围起点(毫秒)
- * @param {number} endMs 时间范围终点(毫秒)
- * @returns {number} 该时间范围内的积分消耗总和
- */
-function sumRequestCredits(rows, startMs, endMs) {
- let total = 0;
- if (!Array.isArray(rows)) return 0;
- for (const row of rows) {
- if (!row || typeof row !== 'object') continue;
- const credit = Number(row.credit);
- if (!Number.isFinite(credit) || credit <= 0) continue;
- const ts = parseRowTime(row.requestTime);
- if (ts === null) continue;
- if (ts >= startMs && ts <= endMs) total += credit;
- }
- return Number(total.toFixed(2));
++ const result = new Date(date.getTime());
++ result.setHours(0, 0, 0, 0);
++ return result;
+ }
+
-// 兼容 requestTime 的常见格式:'YYYY-MM-DD HH:mm:ss' / ISO / 数字时间戳
-function parseRowTime(value) {
++function parseRequestTime(value) {
+ if (value === undefined || value === null || value === '') return null;
+ if (typeof value === 'number' || /^\d+(?:\.\d+)?$/.test(String(value).trim())) {
- const n = Number(value);
- if (!Number.isFinite(n)) return null;
- return n < 1e12 ? n * 1000 : n;
++ const numeric = Number(value);
++ if (!Number.isFinite(numeric)) return null;
++ return numeric < 1e12 ? numeric * 1000 : numeric;
+ }
+ const parsed = Date.parse(String(value).replace(/^(\d{4}-\d\d-\d\d)\s+/, '$1T'));
+ return Number.isFinite(parsed) ? parsed : null;
+ }
+
-/**
- * 调用官方 get-user-request-usage,拉取 [startTime, endTime] 范围内全部请求,汇总积分消耗。
- * @param {object} options
- * @param {string} options.accessToken
- * @param {string} options.apiHost 例如 'https://www.codebuddy.cn'
- * @param {Date} [options.now] 当前时间(可注入,便于测试)
- * @returns {Promise<{ok:boolean, todayUsed:number|null, count:number, total:number, error?:string}>}
- */
-async function fetchTodayUsage({ accessToken, apiHost, now }) {
- const result = { ok: false, todayUsed: null, count: 0, total: 0 };
- if (!accessToken || !apiHost) return result;
- const current = now instanceof Date ? now : new Date();
- const start = startOfLocalDay(current);
- const end = current;
- const startStr = formatLocalDateTime(start);
- const endStr = formatLocalDateTime(end);
- const url = `${apiHost}/billing/meter/get-user-request-usage`;
++function localDateString(timestamp) {
++ const date = new Date(timestamp);
++ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
++}
+
- let allRows = [];
- let serverTotal = 0;
- let page = 1;
++function safeText(value, maxLength = 200) {
++ if (value === undefined || value === null) return '';
++ return String(value).replace(/\0/g, '').slice(0, maxLength);
++}
++
++function normalizeUsageRow(row) {
++ if (!row || typeof row !== 'object') throw new Error('用量记录不是对象');
++ const requestId = safeText(row.requestId, 512).trim();
++ const requestTime = parseRequestTime(row.requestTime);
++ const credit = Number(row.credit);
++ if (!requestId) throw new Error('用量记录缺少 requestId');
++ if (requestTime === null) throw new Error(`用量记录 ${requestId.slice(0, 12)} 缺少有效 requestTime`);
++ if (!Number.isFinite(credit) || credit < 0) throw new Error(`用量记录 ${requestId.slice(0, 12)} 的 credit 无效`);
++ return {
++ requestId,
++ requestTime,
++ usageDate: localDateString(requestTime),
++ credit,
++ model: safeText(row.model),
++ client: safeText(row.client),
++ agentPurpose: safeText(row.agentPurpose),
++ };
++}
++
++async function fetchUsagePage(options) {
++ const {
++ accessToken,
++ apiHost,
++ startTime,
++ endTime,
++ pageNum,
++ pageSize,
++ fetchImpl,
++ requestTimeoutMs,
++ } = options;
++ const controller = new AbortController();
++ const timeout = setTimeout(() => controller.abort(), requestTimeoutMs);
+ try {
- for (;;) {
- const r = await fetch(url, {
- method: 'POST',
- headers: {
- accept: 'application/json, text/plain, */*',
- 'content-type': 'application/json',
- 'x-client-platform': 'web',
- origin: apiHost,
- referer: `${apiHost}/profile/plans-usage`,
- authorization: `Bearer ${accessToken}`,
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) WorkBuddy/5.3.14 Chrome/138.0.7204.251 Safari/537.36',
- },
- body: JSON.stringify({ startTime: startStr, endTime: endStr, pageNum: page, pageSize: PAGE_SIZE }),
- signal: AbortSignal.timeout(12000),
- });
- const text = await r.text();
- let o;
- try { o = JSON.parse(text); } catch (_) { throw new Error('解析用量接口失败'); }
- if (!r.ok) throw new Error(`用量接口 HTTP ${r.status}`);
- if (o.code !== 0) throw new Error(o.msg || `用量接口 code=${o.code}`);
- const data = o.data || {};
- serverTotal = Number(data.total) || 0;
- const rows = Array.isArray(data.data) ? data.data : [];
- allRows = allRows.concat(rows);
- if (!rows.length || allRows.length >= serverTotal || page >= 20) break;
- page++;
++ const response = await fetchImpl(`${apiHost}/billing/meter/get-user-request-usage`, {
++ method: 'POST',
++ headers: {
++ accept: 'application/json, text/plain, */*',
++ 'content-type': 'application/json',
++ 'x-client-platform': 'web',
++ origin: apiHost,
++ referer: `${apiHost}/profile/plans-usage`,
++ authorization: `Bearer ${accessToken}`,
++ },
++ body: JSON.stringify({
++ startTime: formatLocalDateTime(startTime),
++ endTime: formatLocalDateTime(endTime),
++ pageNum,
++ pageSize,
++ }),
++ signal: controller.signal,
++ });
++ const text = await response.text();
++ let payload;
++ try {
++ payload = JSON.parse(text);
++ } catch (_) {
++ throw new Error('官方用量接口返回了无法解析的数据');
++ }
++ if (!response.ok) throw new Error(`官方用量接口 HTTP ${response.status}`);
++ if (payload.code !== 0 && payload.code !== undefined && payload.code !== null) {
++ throw new Error(payload.msg || `官方用量接口 code=${payload.code}`);
++ }
++ const data = payload.data && typeof payload.data === 'object' ? payload.data : null;
++ const total = data && Number(data.total);
++ if (!data || !Number.isSafeInteger(total) || total < 0 || !Array.isArray(data.data)) {
++ throw new Error('官方用量接口分页结构无效');
++ }
++ return { total, rows: data.data };
++ } catch (error) {
++ if (error && error.name === 'AbortError') throw new Error('官方用量接口请求超时');
++ throw error;
++ } finally {
++ clearTimeout(timeout);
++ }
++}
++
++async function fetchUsageSinceAnchor(options = {}) {
++ const accessToken = String(options.accessToken || '');
++ const apiHost = String(options.apiHost || '').replace(/\/$/, '');
++ const startTime = options.startTime instanceof Date ? options.startTime : null;
++ const endTime = options.endTime instanceof Date ? options.endTime : null;
++ const anchorRequestId = safeText(options.anchorRequestId, 512).trim();
++ const pageSize = Number.isSafeInteger(options.pageSize) && options.pageSize > 0
++ ? options.pageSize
++ : DEFAULT_PAGE_SIZE;
++ const maxPages = Number.isSafeInteger(options.maxPages) && options.maxPages > 0
++ ? options.maxPages
++ : DEFAULT_MAX_PAGES;
++ const requestTimeoutMs = Number.isFinite(options.requestTimeoutMs) && options.requestTimeoutMs > 0
++ ? Number(options.requestTimeoutMs)
++ : DEFAULT_REQUEST_TIMEOUT_MS;
++ const fetchImpl = options.fetchImpl || globalThis.fetch;
++ if (!accessToken || !apiHost || !startTime || !endTime || typeof fetchImpl !== 'function') {
++ throw new Error('官方用量查询参数不完整');
++ }
++ if (startTime.getTime() > endTime.getTime()) throw new Error('官方用量查询时间范围无效');
++
++ const records = [];
++ let newestRequestId = '';
++ let previousRequestTime = Infinity;
++ let expectedTotal = null;
++ let fetchedRows = 0;
++ let reachedAnchor = false;
++
++ for (let pageNum = 1; pageNum <= maxPages; pageNum++) {
++ const page = await fetchUsagePage({
++ accessToken,
++ apiHost,
++ startTime,
++ endTime,
++ pageNum,
++ pageSize,
++ fetchImpl,
++ requestTimeoutMs,
++ });
++ if (expectedTotal === null) expectedTotal = page.total;
++ else if (page.total !== expectedTotal) throw new Error('官方用量接口分页总数发生变化');
++ if (!page.rows.length) {
++ if (fetchedRows >= expectedTotal) {
++ return { records, newestRequestId, total: expectedTotal, pages: pageNum, reachedAnchor };
++ }
++ throw new Error(`官方用量分页不完整: 已读取 ${fetchedRows}/${expectedTotal}`);
++ }
++
++ for (const raw of page.rows) {
++ const record = normalizeUsageRow(raw);
++ if (record.requestTime > previousRequestTime) {
++ throw new Error('官方用量记录未按时间倒序返回');
++ }
++ previousRequestTime = record.requestTime;
++ if (!newestRequestId) newestRequestId = record.requestId;
++ if (anchorRequestId && record.requestId === anchorRequestId) {
++ reachedAnchor = true;
++ break;
++ }
++ records.push(record);
++ }
++ if (reachedAnchor) {
++ return { records, newestRequestId, total: expectedTotal, pages: pageNum, reachedAnchor: true };
++ }
++ fetchedRows += page.rows.length;
++ if (fetchedRows >= expectedTotal) {
++ return { records, newestRequestId, total: expectedTotal, pages: pageNum, reachedAnchor: false };
+ }
- const todayUsed = sumRequestCredits(allRows, start.getTime(), end.getTime());
- result.ok = true;
- result.todayUsed = todayUsed;
- result.count = allRows.length;
- result.total = serverTotal;
- return result;
- } catch (e) {
- result.error = e.message;
- return result;
+ }
++ throw new Error(`官方用量分页不完整: 超过 ${maxPages} 页`);
+ }
+
-module.exports = { fetchTodayUsage, sumRequestCredits, formatLocalDateTime, startOfLocalDay, parseRowTime };
++module.exports = {
++ fetchUsageSinceAnchor,
++ formatLocalDateTime,
++ normalizeUsageRow,
++ parseRequestTime,
++ startOfLocalDay,
++};
diff --cc scripts/credit-usage-store.js
index 0000000,0000000..e17869a
new file mode 100644
--- /dev/null
+++ b/scripts/credit-usage-store.js
@@@ -1,0 -1,0 +1,283 @@@
++'use strict';
++
++const fs = require('fs');
++const path = require('path');
++const { createSessionDb } = require('./session-db.js');
++
++const INSERT_USAGE_SQL = `
++ INSERT INTO credit_usage_records
++ (profile_id, uid, request_id, request_time, usage_date, credit, model, client, agent_purpose)
++ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
++ ON CONFLICT(profile_id, uid, request_id) DO UPDATE SET
++ request_time = excluded.request_time,
++ usage_date = excluded.usage_date,
++ credit = excluded.credit,
++ model = excluded.model,
++ client = excluded.client,
++ agent_purpose = excluded.agent_purpose
++`;
++
++function validIdentity(value, label) {
++ const text = String(value || '').trim();
++ if (!text || text.length > 512 || text.includes('\0')) throw new Error(`${label} 无效`);
++ return text;
++}
++
++function localDayRange(date) {
++ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(date || ''));
++ if (!match) throw new Error('用量日期无效');
++ const year = Number(match[1]);
++ const month = Number(match[2]);
++ const day = Number(match[3]);
++ const start = new Date(year, month - 1, day, 0, 0, 0, 0);
++ if (start.getFullYear() !== year || start.getMonth() !== month - 1 || start.getDate() !== day) {
++ throw new Error('用量日期无效');
++ }
++ const end = new Date(year, month - 1, day + 1, 0, 0, 0, 0);
++ return { start: start.getTime(), end: end.getTime() };
++}
++
++function validDate(value) {
++ const text = String(value || '');
++ localDayRange(text);
++ return text;
++}
++
++function createCreditUsageStore(options = {}) {
++ const dbPath = path.resolve(String(options.dbPath || ''));
++ const profileId = validIdentity(options.profileId, 'profile id');
++ const db = options.adapter || createSessionDb({ dbPath });
++ let initPromise = null;
++
++ function initialize() {
++ if (initPromise) return initPromise;
++ initPromise = (async () => {
++ fs.mkdirSync(path.dirname(dbPath), { recursive: true, mode: 0o700 });
++ await db.run(`
++ CREATE TABLE IF NOT EXISTS credit_usage_records (
++ profile_id TEXT NOT NULL,
++ uid TEXT NOT NULL,
++ request_id TEXT NOT NULL,
++ request_time INTEGER NOT NULL,
++ usage_date TEXT NOT NULL,
++ credit REAL NOT NULL,
++ model TEXT NOT NULL DEFAULT '',
++ client TEXT NOT NULL DEFAULT '',
++ agent_purpose TEXT NOT NULL DEFAULT '',
++ PRIMARY KEY (profile_id, uid, request_id)
++ )
++ `);
++ await db.run(`
++ CREATE INDEX IF NOT EXISTS idx_credit_usage_uid_date
++ ON credit_usage_records (profile_id, uid, usage_date, request_time)
++ `);
++ await db.run(`
++ CREATE TABLE IF NOT EXISTS credit_usage_sync_state (
++ profile_id TEXT NOT NULL,
++ uid TEXT NOT NULL,
++ anchor_request_id TEXT,
++ last_success_at INTEGER NOT NULL,
++ PRIMARY KEY (profile_id, uid)
++ )
++ `);
++ await db.run(`
++ CREATE TABLE IF NOT EXISTS daily_checkin_records (
++ profile_id TEXT NOT NULL,
++ uid TEXT NOT NULL,
++ checkin_date TEXT NOT NULL,
++ checked_at INTEGER NOT NULL,
++ response_code INTEGER,
++ message TEXT NOT NULL DEFAULT '',
++ PRIMARY KEY (profile_id, uid, checkin_date)
++ )
++ `);
++ await db.run(`
++ CREATE INDEX IF NOT EXISTS idx_daily_checkin_uid_date
++ ON daily_checkin_records (profile_id, uid, checkin_date)
++ `);
++ try { fs.chmodSync(dbPath, 0o600); } catch (_) {}
++ })().catch((error) => {
++ initPromise = null;
++ throw error;
++ });
++ return initPromise;
++ }
++
++ async function getSyncState(uid) {
++ await initialize();
++ const accountUid = validIdentity(uid, 'uid');
++ const rows = await db.all(
++ `SELECT anchor_request_id, last_success_at
++ FROM credit_usage_sync_state
++ WHERE profile_id = ? AND uid = ?
++ LIMIT 1`,
++ [profileId, accountUid]
++ );
++ if (!rows.length) return null;
++ return {
++ anchorRequestId: rows[0].anchor_request_id || '',
++ lastSuccessAt: Number(rows[0].last_success_at),
++ };
++ }
++
++ async function saveSuccessfulSync({ uid, records, anchorRequestId, syncedAt }) {
++ await initialize();
++ const accountUid = validIdentity(uid, 'uid');
++ const list = Array.isArray(records) ? records : [];
++ const timestamp = Number(syncedAt);
++ if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error('同步时间无效');
++ for (let offset = 0; offset < list.length; offset += 200) {
++ const statements = list.slice(offset, offset + 200).map((record) => ({
++ sql: INSERT_USAGE_SQL,
++ params: [
++ profileId,
++ accountUid,
++ validIdentity(record.requestId, 'request id'),
++ Number(record.requestTime),
++ String(record.usageDate || ''),
++ Number(record.credit),
++ String(record.model || ''),
++ String(record.client || ''),
++ String(record.agentPurpose || ''),
++ ],
++ }));
++ if (statements.length) await db.transaction(statements);
++ }
++ await db.run(
++ `INSERT INTO credit_usage_sync_state
++ (profile_id, uid, anchor_request_id, last_success_at)
++ VALUES (?, ?, ?, ?)
++ ON CONFLICT(profile_id, uid) DO UPDATE SET
++ anchor_request_id = excluded.anchor_request_id,
++ last_success_at = excluded.last_success_at`,
++ [profileId, accountUid, anchorRequestId ? validIdentity(anchorRequestId, 'anchor request id') : null, timestamp]
++ );
++ try { fs.chmodSync(dbPath, 0o600); } catch (_) {}
++ }
++
++ async function listDailyUsage(uids, date) {
++ await initialize();
++ const accountUids = Array.from(new Set((Array.isArray(uids) ? uids : []).map((uid) => validIdentity(uid, 'uid'))));
++ if (!accountUids.length) return {};
++ const usageDate = String(date || '');
++ const dayRange = localDayRange(usageDate);
++ const placeholders = accountUids.map(() => '?').join(',');
++ const rows = await db.all(
++ `SELECT uid, ROUND(SUM(credit), 2) AS used, COUNT(*) AS count
++ FROM credit_usage_records
++ WHERE profile_id = ? AND usage_date = ? AND uid IN (${placeholders})
++ GROUP BY uid`,
++ [profileId, usageDate, ...accountUids]
++ );
++ const result = {};
++ for (const row of rows) {
++ const count = Number(row.count);
++ const used = Number(row.used);
++ if (!accountUids.includes(row.uid) || !Number.isFinite(used) || !Number.isSafeInteger(count) || count <= 0) continue;
++ result[row.uid] = { date: usageDate, used, count, synced: true };
++ }
++ const syncedRows = await db.all(
++ `SELECT uid
++ FROM credit_usage_sync_state
++ WHERE profile_id = ? AND uid IN (${placeholders})
++ AND last_success_at >= ? AND last_success_at < ?`,
++ [profileId, ...accountUids, dayRange.start, dayRange.end]
++ );
++ for (const row of syncedRows) {
++ if (!accountUids.includes(row.uid) || result[row.uid]) continue;
++ result[row.uid] = { date: usageDate, used: 0, count: 0, synced: true };
++ }
++ return result;
++ }
++
++ async function dailyUsageForUid(uid, date) {
++ const accountUid = validIdentity(uid, 'uid');
++ const summaries = await listDailyUsage([accountUid], date);
++ return summaries[accountUid] || null;
++ }
++
++ async function getDailyCheckin(uid, date) {
++ await initialize();
++ const accountUid = validIdentity(uid, 'uid');
++ const checkinDate = validDate(date);
++ const rows = await db.all(
++ `SELECT checkin_date, checked_at, response_code, message
++ FROM daily_checkin_records
++ WHERE profile_id = ? AND uid = ? AND checkin_date = ?
++ LIMIT 1`,
++ [profileId, accountUid, checkinDate]
++ );
++ if (!rows.length) return null;
++ return {
++ date: rows[0].checkin_date,
++ ok: true,
++ already: Number(rows[0].response_code) === 10001,
++ code: rows[0].response_code === null ? null : Number(rows[0].response_code),
++ message: String(rows[0].message || ''),
++ at: Number(rows[0].checked_at),
++ verified: true,
++ };
++ }
++
++ async function listDailyCheckins(uids, date) {
++ await initialize();
++ const accountUids = Array.from(new Set((Array.isArray(uids) ? uids : []).map((uid) => validIdentity(uid, 'uid'))));
++ const checkinDate = validDate(date);
++ if (!accountUids.length) return {};
++ const placeholders = accountUids.map(() => '?').join(',');
++ const rows = await db.all(
++ `SELECT uid, checkin_date, checked_at, response_code, message
++ FROM daily_checkin_records
++ WHERE profile_id = ? AND checkin_date = ? AND uid IN (${placeholders})`,
++ [profileId, checkinDate, ...accountUids]
++ );
++ const result = {};
++ for (const row of rows) {
++ if (!accountUids.includes(row.uid)) continue;
++ result[row.uid] = {
++ date: row.checkin_date,
++ ok: true,
++ already: Number(row.response_code) === 10001,
++ code: row.response_code === null ? null : Number(row.response_code),
++ message: String(row.message || ''),
++ at: Number(row.checked_at),
++ verified: true,
++ };
++ }
++ return result;
++ }
++
++ async function saveDailyCheckin({ uid, date, checkedAt, code, message }) {
++ await initialize();
++ const accountUid = validIdentity(uid, 'uid');
++ const checkinDate = validDate(date);
++ const timestamp = Number(checkedAt);
++ if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error('签到时间无效');
++ const responseCode = code === null || code === undefined ? null : Number(code);
++ if (responseCode !== null && !Number.isSafeInteger(responseCode)) throw new Error('签到响应 code 无效');
++ await db.run(
++ `INSERT INTO daily_checkin_records
++ (profile_id, uid, checkin_date, checked_at, response_code, message)
++ VALUES (?, ?, ?, ?, ?, ?)
++ ON CONFLICT(profile_id, uid, checkin_date) DO UPDATE SET
++ checked_at = excluded.checked_at,
++ response_code = excluded.response_code,
++ message = excluded.message`,
++ [profileId, accountUid, checkinDate, timestamp, responseCode, String(message || '')]
++ );
++ try { fs.chmodSync(dbPath, 0o600); } catch (_) {}
++ }
++
++ return {
++ dailyUsageForUid,
++ getDailyCheckin,
++ listDailyCheckins,
++ getSyncState,
++ initialize,
++ listDailyUsage,
++ saveSuccessfulSync,
++ saveDailyCheckin,
++ };
++}
++
++module.exports = { createCreditUsageStore };
diff --cc scripts/daemon.js
index 7039cc7,9d98c64..1ea32bb
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@@ -32,6 -32,6 +32,7 @@@ const
detectWindowsPrivilege,
buildNativeProcessQuery,
filterVerifiedWindowsProcesses,
++ filterVerifiedNodeProcesses,
parseCimProcessResult,
resolveWindowsExecutable,
sameWindowsPath,
@@@ -97,7 -97,9 +98,10 @@@ const
checkinDisplayValue,
} = require('./lib.js');
const { extractCreditSegments, sortCreditSegments, mergeCreditSegments, parseEnterpriseUsage, ENTERPRISE_EDITIONS } = require('./credit-segments.js');
-const { updateDailyBaseline, pruneBaselines } = require('./credit-usage.js');
-const { fetchTodayUsage } = require('./credit-request-usage.js');
const { buildCreditResourceBody } = require('./credit-resource-queries.js');
++const { fetchUsageSinceAnchor, startOfLocalDay } = require('./credit-request-usage.js');
++const { createCreditUsageStore } = require('./credit-usage-store.js');
++const { classifyCheckinResult } = require('./checkin-result.js');
const {
captureException,
captureMessage,
@@@ -108,6 -110,6 +112,8 @@@
const { getProfile, profileDataDir, listInstalledModelSources } = require('./profiles.js');
const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('./cdp-targets.js');
const { createSessionDb, normalizeSessionIdBatch, parameterCount } = require('./session-db.js');
++const { replaceFileWithRetry } = require('./atomic-file-write.js');
++const { parseUiPortState, profileUiPortCandidates } = require('./ui-port.js');
const PROFILE = getProfile();
const DATA_DIR = defaultDataDir();
@@@ -197,23 -199,27 +203,34 @@@
// 1.0.49:主题 CDP 应用增加异常回读/重试,失败主题不再覆盖已保存主题。
// 1.0.18:主题应用在页面刷新/切换期间自动重连 CDP,并补充失败诊断。
// 1.1.0:Windows launcher 固定传递 profile UI 端口;显式端口冲突时不再递增到相邻 profile。
- const DAEMON_VERSION = '1.1.1';
- const DAEMON_BUILD_ID = 'release-1.1.1-20260827-windows-standard-launch-normalization';
-// 1.1.1:积分卡新增「今日已用」(跨天基线 = 当日观测到的最大剩余 − 当前剩余)与「已用」(TotalDosage)。
-// /api/credits 新增 todayUsed 字段;基线缓存存于 credit-daily-baseline.json,30 天自动清理。
-// 1.1.2:今日已用改为调用官方 /billing/meter/get-user-request-usage 精确汇总(按 requestTime 过滤今日
-// credit 求和,无跨天盲区);接口失败时回退到本地基线法。新模块 scripts/credit-request-usage.js。
-const DAEMON_VERSION = '1.1.2';
-const DAEMON_BUILD_ID = 'release-1.1.2-20260827-credit-today-used-official';
++// 1.1.2:当前登录账号通过官方请求用量接口增量同步;SQLite 按账号持久化,并为所有账号回显今日用量缓存。
++// 1.1.3:账号面板稳定置顶当前登录账号。
++// 1.1.5:区分“当天已同步但用量为零”和“从未同步”,已同步零用量显示 0.00。
++// 1.1.6:今日用量标签复用积分 AI 图标,并统一展示文案。
++// 1.1.7:Windows 启动可靠性、profile 隔离 UI 端口、原子配置写入和 CIM 竞态修复。
++// 1.1.8:签到只接受明确成功响应并写入 SQLite;悬浮球释放时增加阻尼回弹。
++// 1.1.9:签到请求进行中仍立即展示已确认的今日签到标记。
++const DAEMON_VERSION = '1.1.9';
++const DAEMON_BUILD_ID = 'release-1.1.9-20260828-checkin-cache-first';
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
const WORKDADDY_INSTALL_NAME = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy AI' : 'WorkDaddy';
--const WORKDADDY_DIR_WIN = process.env.WBSWITCH_APP_DIR ||
-- path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Programs', WORKDADDY_INSTALL_NAME);
--const UI_PORT_BASE = parseInt(process.env.WBSWITCH_PORT || '47832', 10);
++const WORKDADDY_DIR_WIN = process.env.WBSWITCH_APP_DIR || path.resolve(__dirname, '..');
++const UI_PORT_BASE = parseInt(process.env.WBSWITCH_PORT || String(profileUiPortCandidates(PROFILE.id)[0]), 10);
const ALLOW_UI_PORT_FALLBACK = !process.env.WBSWITCH_PORT;
--let ACTUAL_PORT = UI_PORT_BASE; // 实际监听端口(被占用时 +1)
++let ACTUAL_PORT = UI_PORT_BASE; // 实际监听端口(可能回退到当前 profile 的备用端口)
const PROFILE_CDP_PORT = { 'workbuddy-cn': 9222, 'workbuddy-ai': 9223, 'codebuddy-cn': 9224, 'codebuddy-intl': 9225 };
const CDP_PORT_HINT = process.env.WBSWITCH_CDP_PORT
? parseInt(process.env.WBSWITCH_CDP_PORT, 10)
: (PROFILE_CDP_PORT[PROFILE.id] || null);
const CDP_PORT_FILE = path.join(DATA_DIR, 'cdp-port.json');
++const UI_PORT_FILE = path.join(DATA_DIR, 'ui-port.json');
const API_TOKEN_FILE = path.join(DATA_DIR, '.api-token');
++const CREDIT_USAGE_DB_FILE = path.join(DATA_DIR, 'credit-usage.db');
++const CREDIT_USAGE_STORE = createCreditUsageStore({ dbPath: CREDIT_USAGE_DB_FILE, profileId: PROFILE.id });
++const CREDIT_USAGE_REFRESH_MS = 15000;
++const creditUsageSyncInFlight = new Map();
const WATCH_INTERVAL = 3000; // 文件监听兜底
const BACKUP_DEBOUNCE = 1500; // CDP 事件触发的备份防抖
const CDP_RECONNECT_MS = 5000;
@@@ -301,6 -307,6 +318,25 @@@ function writeCdpPortFile(port, logFn
}
}
++function readUiPortFile() {
++ try { return parseUiPortState(fs.readFileSync(UI_PORT_FILE, 'utf8'), PROFILE.id); } catch (_) { return null; }
++}
++
++function writeUiPortFile(port, logFn = log) {
++ try {
++ fs.mkdirSync(DATA_DIR, { recursive: true });
++ replaceFileWithRetry(UI_PORT_FILE, JSON.stringify({
++ profileId: PROFILE.id,
++ port,
++ updatedAt: new Date().toISOString(),
++ }) + '\n', 0o600);
++ return true;
++ } catch (error) {
++ logFn(`[http] 保存 UI 端口配置失败: ${error.message}`);
++ return false;
++ }
++}
++
function cdpPortCandidates() {
const ports = [];
const add = (port) => { if (validCdpPort(port) && !ports.includes(port)) ports.push(port); };
@@@ -1256,6 -1262,6 +1292,38 @@@ function reportDaemonLockFallback(error
}).catch(() => {});
}
++function isCurrentWindowsDaemonProcess(pid) {
++ if (process.platform !== 'win32' || !Number.isSafeInteger(pid) || pid <= 0) return false;
++ const command = buildNativeProcessQuery(
++ path.join(__dirname, 'windows-process-boundary.ps1'),
++ `Get-CimInstance Win32_Process -Filter \"ProcessId = ${pid}\" -ErrorAction Stop | ` +
++ `Where-Object { $_.Name -ieq 'node.exe' }`
++ );
++ try {
++ const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command], {
++ encoding: 'utf8', timeout: 10000, windowsHide: true,
++ });
++ const processes = parseCimProcessResult(result, {
++ requireCommandLine: true,
++ requireCurrentOwner: true,
++ requireNativeArguments: true,
++ allowTransientNotFound: true,
++ });
++ return processes.some((item) => {
++ try {
++ return filterVerifiedNodeProcesses(item.ExecutablePath, __filename, [item])
++ .some((match) => match.ProcessId === pid);
++ } catch (_) {
++ return false;
++ }
++ });
++ } catch (_) {
++ // Failure to prove ownership must keep the lock: deleting it could permit
++ // two daemons to operate on the same profile at once.
++ return true;
++ }
++}
++
// launchd 应只启动一个 daemon;启动器的 nohup 兜底和 launchd 异步拉起可能短暂重叠,
// 用原子创建锁文件把这类竞态变成可观测的单实例退出,而不是两个进程同时清理/注入页面。
// Windows 数据目录锁不可写时,使用同一台机器用户临时目录中的哈希锁继续保证单实例。
@@@ -1285,7 -1291,7 +1353,10 @@@ function acquireDaemonLock()
const ownerPid = Number(owner && owner.pid);
let alive = false;
if (ownerPid > 0 && ownerPid !== process.pid) {
-- try { process.kill(ownerPid, 0); alive = true; } catch (_) {}
++ if (IS_WIN) alive = isCurrentWindowsDaemonProcess(ownerPid);
++ else {
++ try { process.kill(ownerPid, 0); alive = true; } catch (_) {}
++ }
}
if (alive) {
process.stdout.write(`[${new Date().toISOString()}] [lock] 已有 daemon 运行 (pid=${ownerPid}),当前进程退出\n`);
@@@ -1661,6 -1667,6 +1732,7 @@@ function queryWindowsWorkBuddyProcesses
});
return parseCimProcessResult(result, {
requireCommandLine: true, requireCurrentOwner: true, requireNativeArguments: true,
++ allowTransientNotFound: true,
});
}
@@@ -2143,7 -2198,7 +2215,7 @@@ function saveCheckinCache(cache)
/**
* 用指定账号 accessToken 调用签到接口(多域名兜底)。
-- * 成功 / 已签(code=10001)均视为当日已完成。
++ * 只有明确 code=0,或 code=10001 且文案明确表示已签到/已领取,才视为成功。
*/
async function dailyCheckin(accessToken) {
const origin = PROFILE.apiHost || 'https://www.workbuddy.cn';
@@@ -2169,14 -2224,14 +2241,13 @@@
const text = await r.text();
let o = {};
try { o = JSON.parse(text); } catch (_) {}
-- const code = o.code;
-- const already = code === 10001;
-- const ok = already || (r.ok && (code === 0 || code === undefined || code === null));
// 401 = token 过期/未授权:直接给友好文案,避免面板显示裸 "HTTP 401"
const failMsg = r.status === 401 ? '登录身份过期' : 'HTTP ' + r.status;
-- const result = { ok, already, code, message: o.msg || o.message || (r.ok ? 'ok' : failMsg), url };
++ const message = o.msg || o.message || (r.ok ? 'ok' : failMsg);
++ const classified = classifyCheckinResult({ httpOk: r.ok, code: o.code, message });
++ const result = { ...classified, status: r.status, url };
// 网络异常或服务端错误才切换兜底域名;认证/参数错误直接返回,避免无意义地重复请求。
-- if (ok || r.status === 401 || (r.status >= 400 && r.status < 500 && r.status !== 404)) return result;
++ if (classified.ok || r.status === 401 || (r.status >= 400 && r.status < 500 && r.status !== 404) || (r.ok && r.status !== 404)) return result;
lastErr = result.message;
} catch (e) {
lastErr = e.name === 'AbortError' ? '请求超时(' + (CHECKIN_REQUEST_TIMEOUT_MS / 1000) + ' 秒)' : e.message;
@@@ -2189,11 -2244,11 +2260,27 @@@
/** 对单个账号签到(带每日缓存,幂等:今日已成功过则跳过) */
async function claimDailyForUid(uid) {
-- const cache = loadCheckinCache();
const today = todayStr();
++ let dbHit = null;
++ try { dbHit = await CREDIT_USAGE_STORE.getDailyCheckin(uid, today); } catch (e) {
++ log('[checkin] 读取 SQLite 标记失败: ' + e.message);
++ }
++ if (dbHit && dbHit.ok === true && dbHit.verified === true) {
++ return { uid, skipped: true, ...dbHit };
++ }
++ const cache = loadCheckinCache();
const hit = cache[uid];
-- if (hit && hit.date === today && hit.ok) {
-- return { uid, skipped: true, ok: true, already: hit.already, code: hit.code, message: hit.message };
++ const cachedResult = hit && hit.date === today
++ ? classifyCheckinResult({ httpOk: true, code: hit.code, message: hit.message })
++ : null;
++ if (cachedResult && cachedResult.ok) {
++ const migrated = { uid, skipped: true, date: today, ...cachedResult, at: Number(hit.at) || Date.now(), verified: true };
++ try {
++ await CREDIT_USAGE_STORE.saveDailyCheckin({ uid, date: today, checkedAt: migrated.at, code: migrated.code, message: migrated.message });
++ } catch (e) {
++ log('[checkin] 迁移 SQLite 标记失败: ' + e.message);
++ }
++ return migrated;
}
const file = path.join(DATA_DIR, 'accounts', uid + '.info');
if (!fs.existsSync(file)) return { uid, ok: false, reason: 'no-backup' };
@@@ -2206,9 -2261,9 +2293,16 @@@
}
if (!tk) return { uid, ok: false, reason: 'no-accessToken' };
const r = await dailyCheckin(tk);
-- const rec = { date: today, ok: !!r.ok, already: !!r.already, code: r.code, message: r.message, at: Date.now() };
++ const rec = { date: today, ok: !!r.ok, already: !!r.already, inactive: !!r.inactive, code: r.code, message: r.message, at: Date.now(), verified: !!r.ok };
cache[uid] = rec;
saveCheckinCache(cache);
++ if (rec.ok) {
++ try {
++ await CREDIT_USAGE_STORE.saveDailyCheckin({ uid, date: today, checkedAt: rec.at, code: rec.code, message: rec.message });
++ } catch (e) {
++ log('[checkin] 写入 SQLite 标记失败: ' + e.message);
++ }
++ }
return { uid, ...rec };
}
@@@ -3119,44 -3174,44 +3213,6 @@@ function readWorkbuddySettings()
}
}
--function sleepSync(ms) {
-- if (ms <= 0) return;
-- const sab = new SharedArrayBuffer(4);
-- Atomics.wait(new Int32Array(sab), 0, 0, ms);
--}
--
--/**
-- * Replace a JSON file atomically. WorkBuddy can briefly hold the destination
-- * open on Windows; retry only transient sharing/permission errors so config
-- * writes do not fail during batch operations.
-- */
--function replaceFileWithRetry(file, content, mode) {
-- const tmp = `${file}.wbs-tmp-${process.pid}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
-- fs.writeFileSync(tmp, content, 'utf8');
-- if (mode !== undefined) fs.chmodSync(tmp, mode);
-- const maxAttempts = process.platform === 'win32' ? 80 : 1;
-- let lastError;
-- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
-- try {
-- fs.renameSync(tmp, file);
-- return;
-- } catch (error) {
-- lastError = error;
-- const retryable = process.platform === 'win32' && ['EPERM', 'EACCES', 'EBUSY'].includes(error && error.code);
-- if (!retryable || attempt === maxAttempts) break;
-- // A stale read-only attribute can surface as EPERM independently of a
-- // sharing violation. Clearing it is limited to this known config file;
-- // the atomic rename remains the only successful write path.
-- if (attempt === 1 && error && error.code === 'EPERM') {
-- try { fs.chmodSync(file, 0o666); } catch (_) {}
-- }
-- sleepSync(Math.min(250, 50 + attempt * 10));
-- }
-- }
-- try { fs.unlinkSync(tmp); } catch (_) {}
-- throw lastError;
--}
--
function writeWorkbuddySettings(settings) {
const file = workbuddySettingsPath();
replaceFileWithRetry(file, JSON.stringify(settings, null, 2) + '\n');
@@@ -4865,6 -4920,6 +4921,49 @@@ async function fetchCredits(accessToken
};
}
++async function listDailyUsage(accounts, date = todayStr()) {
++ const list = Array.isArray(accounts) ? accounts : [];
++ if (!list.length) return {};
++ return CREDIT_USAGE_STORE.listDailyUsage(list.map((account) => account.uid), date);
++}
++
++async function syncCurrentCreditUsage(uid, accessToken) {
++ const existing = creditUsageSyncInFlight.get(uid);
++ if (existing) return existing;
++ const task = (async () => {
++ const now = new Date();
++ const nowMs = now.getTime();
++ const state = await CREDIT_USAGE_STORE.getSyncState(uid);
++ if (state && Number.isFinite(state.lastSuccessAt) && nowMs - state.lastSuccessAt < CREDIT_USAGE_REFRESH_MS) {
++ return CREDIT_USAGE_STORE.dailyUsageForUid(uid, todayStr(now));
++ }
++ const lastSuccessAt = state && Number.isFinite(state.lastSuccessAt) && state.lastSuccessAt <= nowMs
++ ? new Date(state.lastSuccessAt)
++ : now;
++ const startTime = startOfLocalDay(lastSuccessAt);
++ const result = await fetchUsageSinceAnchor({
++ accessToken,
++ apiHost: PROFILE.apiHost || 'https://www.workbuddy.cn',
++ startTime,
++ endTime: now,
++ anchorRequestId: state && state.anchorRequestId,
++ });
++ await CREDIT_USAGE_STORE.saveSuccessfulSync({
++ uid,
++ records: result.records,
++ anchorRequestId: result.newestRequestId || (state && state.anchorRequestId) || '',
++ syncedAt: nowMs,
++ });
++ return CREDIT_USAGE_STORE.dailyUsageForUid(uid, todayStr(now));
++ })();
++ creditUsageSyncInFlight.set(uid, task);
++ try {
++ return await task;
++ } finally {
++ if (creditUsageSyncInFlight.get(uid) === task) creditUsageSyncInFlight.delete(uid);
++ }
++}
++
/* ================= 账号导出 / 导入 =================
* v2 导出:用户在面板输入非空密码;随机 salt + AES-256-GCM,密码不落盘、不写日志。
* v1 导入:兼容历史固定密码 workdaddy 的导出文件,空密码即走旧格式默认值。
@@@ -5279,13 -5334,13 +5378,33 @@@ function handleApi(req, res)
const cache = loadCheckinCache();
const today = todayStr();
const checkinPending = !!claimInFlight;
-- const enriched = accounts.map((a) => {
-- const c = cache[a.uid];
-- return Object.assign({}, a, {
-- checkin: checkinDisplayValue(c, today, checkinPending),
++ return CREDIT_USAGE_STORE.listDailyCheckins(accounts.map((a) => a.uid), today)
++ .catch((error) => {
++ log('[checkin] 读取 SQLite 标记失败: ' + error.message);
++ return {};
++ })
++ .then((dbCheckins) => {
++ const enriched = accounts.map((a) => {
++ const c = dbCheckins[a.uid] || cache[a.uid];
++ const checked = c && c.ok && (c.verified === true || classifyCheckinResult({ httpOk: true, code: c.code, message: c.message }).ok)
++ ? c
++ : null;
++ return Object.assign({}, a, {
++ checkin: checkinDisplayValue(checked, today, checkinPending),
++ });
++ });
++ return listDailyUsage(enriched, today)
++ .then((summaries) => {
++ const withUsage = enriched.map((account) => summaries[account.uid]
++ ? Object.assign({}, account, { todayUsage: summaries[account.uid] })
++ : account);
++ return json(res, 200, { ok: true, current: currentAccount(), accounts: withUsage, checkin: checkinSnapshot() });
++ })
++ .catch((error) => {
++ log('[credits-usage] 读取本地今日用量失败: ' + error.message);
++ return json(res, 200, { ok: true, current: currentAccount(), accounts: enriched, checkin: checkinSnapshot() });
++ });
});
-- });
-- return json(res, 200, { ok: true, current: currentAccount(), accounts: enriched, checkin: checkinSnapshot() });
}
// 查询指定账号的剩余积分(v2 全量资源 Account 汇总)
@@@ -5299,8 -5354,19 +5418,18 @@@
const j = JSON.parse(fs.readFileSync(file, 'utf8'));
const tk = j.auth && j.auth.accessToken;
if (!tk) return json(res, 400, { ok: false, error: '备份中无 accessToken' });
-- const r = await fetchCredits(tk, j.account);
- // 今日已用:优先用官方 get-user-request-usage 精确汇总(按 requestTime 过滤今日 credit 求和);
- // 接口失败时回退到本地基线法(当日观测到的最大剩余 − 当前剩余,跨天自动重置)。
- const apiHost = PROFILE.apiHost || 'https://www.workbuddy.cn';
- const usage = await fetchTodayUsage({ accessToken: tk, apiHost });
- let todayUsed;
- if (usage.ok) {
- todayUsed = usage.todayUsed;
- } else {
- todayUsed = todayUsedFor(uid, r.credits);
- maybePruneCreditBaselines();
- }
-- return json(res, 200, {
++ const current = currentAccount();
++ const shouldSyncUsage = !!(current && current.uid === uid);
++ const usagePromise = shouldSyncUsage
++ ? syncCurrentCreditUsage(uid, tk)
++ .then((value) => ({ synced: true, value }))
++ .catch((error) => {
++ log('[credits-usage] 当前账号增量同步失败: ' + error.message);
++ return { synced: false };
++ })
++ : Promise.resolve({ synced: false });
++ const [r, usage] = await Promise.all([fetchCredits(tk, j.account), usagePromise]);
++ const payload = {
ok: true,
uid,
credits: r.credits,
@@@ -5313,7 -5381,7 +5442,9 @@@
segments: r.segments,
unlimited: !!r.unlimited,
cycleResetTime: r.cycleResetTime || null,
-- });
++ };
++ if (usage.synced) payload.todayUsage = usage.value;
++ return json(res, 200, payload);
} catch (e) {
log(`[credits] 查询 ${uid} 积分失败: ${e.message}`);
return json(res, 500, { ok: false, error: e.message });
@@@ -6610,14 -6678,14 +6741,16 @@@ function startServer()
log('[ws] DevTools 代理就绪 (/devtools-proxy/<targetId>)');
}
-- // 直接运行且未指定端口时保留旧的 +1 兼容行为。launcher/install 已绑定 profile
-- // 端口时必须 fail closed,避免 AI 47833 串到其他 profile 的 47834/47835。
-- let port = UI_PORT_BASE;
++ // 每个 profile 的候选端口完全不重叠。显式端口由 launcher 预先选定,
++ // 直接运行 daemon 时才在本 profile 的持久化/固定候选中回退。
++ const ports = ALLOW_UI_PORT_FALLBACK
++ ? profileUiPortCandidates(PROFILE.id, { persistedPort: readUiPortFile(), preferredPort: UI_PORT_BASE })
++ : [UI_PORT_BASE];
const tryListen = (attempt) => {
++ const port = ports[attempt];
server.once('error', (e) => {
-- if (e.code === 'EADDRINUSE' && ALLOW_UI_PORT_FALLBACK && attempt < 7) {
-- port += 1;
-- log(`[http] 端口占用,改用 ${port}`);
++ if (e.code === 'EADDRINUSE' && attempt + 1 < ports.length) {
++ log(`[http] 端口 ${port} 不可绑定,改用当前 profile 备用端口 ${ports[attempt + 1]}`);
tryListen(attempt + 1);
} else {
log(`[http] 启动失败: ${e.message}`);
@@@ -6626,6 -6694,6 +6759,7 @@@
});
server.listen(port, HOST, () => {
ACTUAL_PORT = port;
++ writeUiPortFile(port);
log(`[http] Web 界面: http://${HOST}:${port} (数据目录: ${DATA_DIR})`);
});
};
@@@ -6646,6 -6714,6 +6780,7 @@@ process.on('unhandledRejection', (reaso
ensureDirs(DATA_DIR, log);
if (!acquireDaemonLock()) process.exit(0);
++CREDIT_USAGE_STORE.initialize().catch((error) => log('[credits-usage] 初始化数据库失败: ' + error.message));
// 首次启动初始化(新电脑 / 数据目录为空时):内置壁纸 + WorkDaddy 主题 + 默认蒙版 10%
initBuiltinAssets();
// 启动时刷新决策弹窗规则到最新版本(已启用时替换旧规则段)
diff --cc scripts/inject.js
index 5eb51f7,2910483..3557514
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@@ -426,7 -426,7 +426,7 @@@ if (typeof window !== 'undefined' && ty
var msg = c.message || '';
// 国际版/活动空窗期:接口 code 10001 且文案表明「活动未开启/未开始/已过期」时,
// 并不是“今日已签到”,不应展示绿色成功标签,改为中性「无签到活动」。
-- if (c.ok && /未开启|未开始|未开放|已过期|无.*活动|活动.*(结束|关闭|暂停)/i.test(msg)) {
++ if (c.inactive || (c.ok && /未开启|未开始|未开放|已过期|无.*活动|活动.*(结束|关闭|暂停)/i.test(msg))) {
return '<span class="wbs-ck wbs-checkin-tag pending">无签到活动</span>';
}
// “本轮刚领取”和“今天已领取过”都是成功态,统一展示避免同一页面出现两套文案。
@@@ -713,7 -713,7 +713,6 @@@
var buildTimeouts = [];
var buildIntervals = [];
var buildFrames = [];
-- var fabPosTimer = null;
var sleepSyncTimer = null;
var avatarTimer = null;
var debugTimer = null;
@@@ -1010,7 -1010,7 +1009,7 @@@
}
});
-- // 根节点(fixed 右下角,面板 absolute 定位,右下角与按钮重合)
++ // 根节点(面板保持右下角,按钮拖动后水平回到右侧)
var root = el('div', 'wbs-root');
root.setAttribute('data-wbs-profile', PROFILE_ID);
if (!CAPS.theme) root.classList.add('wbs-no-theme');
@@@ -1021,7 -1021,7 +1020,7 @@@
'<span class="wbs-fab-health-dot" title="会话状态" style="display:none"></span>',
'<div class="click">',
'<span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span>',
-- '<button class="button up" type="button" aria-label="Codex 助手">',
++ '<button class="button up" type="button" aria-label="WorkDaddy,点击打开面板,可拖动">',
'<span class="wbs-fab-antenna" aria-hidden="true"><span class="wbs-fab-antenna-dot"></span></span>',
'<span class="wbs-fab-ear wbs-fab-ear-left" aria-hidden="true"></span>',
'<span class="wbs-fab-ear wbs-fab-ear-right" aria-hidden="true"></span>',
@@@ -1773,9 -1773,9 +1772,46 @@@
syncStash(); // 初始检查
setBuildTimeout(wrapQueueReorder, 800);
-- // ===== 悬浮按钮动态定位:优先贴消息队列(cb-message-queue)右上角上方,否则贴输入框 mainArea 右上角上方 =====
-- // 监听 body DOM/class 变化(onDomChange/onInputSync) + 轮询兜底,实时跟随组件显隐
++ // ===== 悬浮按钮位置:拖动时可在窗口内移动,释放后水平吸附右边 =====
var fabPosPending = false;
++ var fabDrag = null;
++ var fabDragMoved = false;
++ var fabDragSuppressClick = false;
++ var fabSnapTimer = null;
++ var FAB_DRAG_THRESHOLD = 6;
++ var FAB_EDGE_GAP = 22;
++ var FAB_POSITION_KEY = 'wbs-fab-bottom-' + PROFILE_ID;
++
++ function readFabBottom() {
++ try {
++ var value = Number(localStorage.getItem(FAB_POSITION_KEY));
++ return isFinite(value) ? value : null;
++ } catch (_) { return null; }
++ }
++
++ function clampFabBottom(bottom, height) {
++ var max = Math.max(FAB_EDGE_GAP, window.innerHeight - height - FAB_EDGE_GAP);
++ return Math.max(FAB_EDGE_GAP, Math.min(max, Number(bottom) || FAB_EDGE_GAP));
++ }
++
++ function clampFabRight(right, width) {
++ var max = Math.max(FAB_EDGE_GAP, window.innerWidth - width - FAB_EDGE_GAP);
++ return Math.max(FAB_EDGE_GAP, Math.min(max, Number(right) || FAB_EDGE_GAP));
++ }
++
++ function applyFabPosition(fab, right, bottom) {
++ if (!fab) return;
++ var rect = fab.getBoundingClientRect();
++ var nextRight = clampFabRight(right, rect.width || 52);
++ var nextBottom = clampFabBottom(bottom, rect.height || 32);
++ fab.style.position = 'fixed';
++ fab.style.left = 'auto';
++ fab.style.top = 'auto';
++ fab.style.right = nextRight + 'px';
++ fab.style.bottom = nextBottom + 'px';
++ return { right: nextRight, bottom: nextBottom };
++ }
++
function scheduleFabPos() {
if (fabPosPending) return;
fabPosPending = true;
@@@ -1788,75 -1788,75 +1824,10 @@@
var fab = root.querySelector('.wbs-fab');
if (!fab) return;
if (fab.classList.contains('hidden')) return; // 面板打开时保持隐藏
-- // WorkBuddy 首页 composer 的右上插槽存在时,按钮放回 WorkBuddy 窗口右下角,
-- // 避免被首页输入区的内部定位挤到中间位置。
-- var homeComposerCorner = document.querySelector('.wb-home-page [class*="_topRightSlotStandalone_"] > div:nth-child(1) > div:nth-child(3)');
-- // WorkBuddy AI 欢迎页的右上插槽结构不同,第二个操作项出现时固定到窗口右下角。
-- var aiHomeComposerCorner = PROFILE_ID === 'workbuddy-ai'
-- ? document.querySelector('.wb-home-page [class*="_topRightSlotStandalone_"] > div:nth-child(1) > div:nth-child(2)')
-- : null;
-- if (homeComposerCorner || aiHomeComposerCorner) {
-- var cornerRect = (aiHomeComposerCorner || homeComposerCorner).getBoundingClientRect();
-- if (cornerRect.width > 0 && cornerRect.height > 0) {
-- fab.classList.remove('fab--solid');
-- fab.style.position = 'fixed';
-- fab.style.left = 'auto';
-- fab.style.top = 'auto';
-- fab.style.right = '22px';
-- fab.style.bottom = '22px';
-- return;
-- }
-- }
-- var target = null;
-- var solid = false; // 贴消息队列上方时纯色背景(不毛玻璃)
-- // 1) 消息队列展开时优先贴它
-- var q = document.querySelector('.cb-message-queue.cb-expand');
-- if (q) {
-- var qr = q.getBoundingClientRect();
-- if (qr.height > 1 && qr.width > 1) { target = qr; solid = true; }
-- }
-- // 2) WorkBuddy AI 新版聊天输入框不再使用旧的 _input-area-container/_mainArea_ 类名,
-- // 实际可定位元素是 conversation-input-area 下的 .cr-input-container。
-- // 必须在旧的生成类名兜底之前命中它,否则无队列时机器人只能落到默认右下角。
-- if (!target && WBS_PROFILE_IS_AI) {
-- var aiInput = document.querySelector(
-- '.conversation-input-area .conversation-input .cr-input-box .cr-input-container,' +
-- ' .conversation-input-area .cr-input-container,' +
-- ' .conversation-shell__main .cr-input-container'
-- );
-- if (aiInput) {
-- var air = aiInput.getBoundingClientRect();
-- if (air.height > 1 && air.width > 1) target = air;
-- }
-- }
-- // 3) 旧版/普通 WorkBuddy 兜底:输入框主体 _mainArea(聊天页 _input-area-container 内 /
-- // 主页 wb-home-composer 内)。
-- if (!target) {
-- var ma = document.querySelector('[class*="_input-area-container_"] [class*="_mainArea_"]');
-- if (!ma) ma = document.querySelector('.wb-home-composer [class*="_mainArea_"]');
-- if (ma) {
-- var mr = ma.getBoundingClientRect();
-- if (mr.height > 1 && mr.width > 1) target = mr;
-- }
-- }
-- if (!target) {
-- // 无目标(如登录页):回落到默认右下角
-- fab.style.right = '22px';
-- fab.style.bottom = '22px';
-- return;
-- }
-- var GAP_R = 8; // 右边留间距
-- var GAP_V = 0; // 垂直完全贴合
-- // 贴 queue 时纯色背景,贴 mainArea 时毛玻璃
-- fab.classList.toggle('fab--solid', solid);
-- fab.style.position = 'fixed';
-- fab.style.left = 'auto';
-- fab.style.top = 'auto';
-- fab.style.right = (window.innerWidth - target.right + GAP_R) + 'px';
-- fab.style.bottom = (window.innerHeight - target.top + GAP_V) + 'px';
++ if (fabDrag) return;
++ var saved = readFabBottom();
++ applyFabPosition(fab, FAB_EDGE_GAP, saved == null ? FAB_EDGE_GAP : saved);
}
-- // 轮询兜底:queue 显隐 / 输入框高度变化可能漏触发 observer
-- fabPosTimer = setBuildInterval(function () { if (alive) scheduleFabPos(); }, 1500);
setBuildTimeout(scheduleFabPos, 600); // 首屏定位
// ===== chat widget 预览 iframe 背景透明(用户要求)=====
@@@ -4785,7 -4785,7 +4756,76 @@@
}
}
-- fab.addEventListener('click', function () { setOpen(true); });
++ function setupFabDrag() {
++ var handle = fab.querySelector('.wbs-fab .button.up');
++ if (!handle) return;
++ fab.style.touchAction = 'none';
++ fab.style.userSelect = 'none';
++ handle.style.touchAction = 'none';
++ listen(handle, 'pointerdown', function (e) {
++ if (e.button !== undefined && e.button !== 0) return;
++ var rect = fab.getBoundingClientRect();
++ fabDrag = {
++ pointerId: e.pointerId,
++ startY: e.clientY,
++ startX: e.clientX,
++ startRight: window.innerWidth - rect.right,
++ startBottom: window.innerHeight - rect.bottom,
++ };
++ fabDragMoved = false;
++ fabDragSuppressClick = false;
++ fab.classList.add('is-dragging');
++ try { handle.setPointerCapture(e.pointerId); } catch (_) {}
++ if (e.preventDefault) e.preventDefault();
++ });
++ listen(handle, 'pointermove', function (e) {
++ if (!fabDrag || e.pointerId !== fabDrag.pointerId) return;
++ var deltaX = e.clientX - fabDrag.startX;
++ var deltaY = e.clientY - fabDrag.startY;
++ if (Math.max(Math.abs(deltaX), Math.abs(deltaY)) >= FAB_DRAG_THRESHOLD) {
++ fabDragMoved = true;
++ fabDragSuppressClick = true;
++ }
++ applyFabPosition(fab, fabDrag.startRight - deltaX, fabDrag.startBottom - deltaY);
++ if (e.preventDefault) e.preventDefault();
++ });
++ function finishFabDrag(e) {
++ if (!fabDrag || (e && e.pointerId !== fabDrag.pointerId)) return;
++ var rect = fab.getBoundingClientRect();
++ var bottom = clampFabBottom(window.innerHeight - rect.bottom, rect.height || 32);
++ // 释放后水平吸附回右边,垂直位置保留。
++ if (fabSnapTimer !== null) {
++ clearTimeout(fabSnapTimer);
++ fabSnapTimer = null;
++ }
++ fab.classList.remove('is-dragging');
++ fab.classList.add('is-snapping');
++ applyFabPosition(fab, FAB_EDGE_GAP, bottom);
++ try { localStorage.setItem(FAB_POSITION_KEY, String(Math.round(bottom))); } catch (_) {}
++ fabDrag = null;
++ fabSnapTimer = setBuildTimeout(function () {
++ fabSnapTimer = null;
++ fab.classList.remove('is-snapping');
++ }, 620);
++ }
++ listen(handle, 'pointerup', finishFabDrag);
++ listen(handle, 'pointercancel', finishFabDrag);
++ listen(handle, 'lostpointercapture', function () {
++ if (fabDrag) finishFabDrag();
++ });
++ }
++
++ setupFabDrag();
++ fab.addEventListener('click', function (e) {
++ if (fabDragSuppressClick || fabDragMoved) {
++ fabDragSuppressClick = false;
++ fabDragMoved = false;
++ if (e.preventDefault) e.preventDefault();
++ if (e.stopPropagation) e.stopPropagation();
++ return;
++ }
++ setOpen(true);
++ });
root.querySelector('[data-act="close"]').addEventListener('click', function () { setOpen(false); });
@@@ -7177,20 -7177,31 +7217,38 @@@
return '<div class="wbs-credit-bar" role="img" aria-label="积分到期分布">' + cells + '</div>';
}
- // 「今日已用」用量行:值未知(null)时不渲染;剩余积分已在卡片上方展示,这里不再重复显示累计用量。
- function creditUsageHtml(account) {
- if (!account) return '';
- var todayUsed = account.todayUsed === null || account.todayUsed === undefined ? null : Number(account.todayUsed);
- if (todayUsed === null) return '';
- return '<div class="wbs-credit-usage">' +
- '<span class="wbs-cu-item"><span class="wbs-cu-key">今日已用</span><b>' + fmtCredits(todayUsed) + '</b></span>' +
- '</div>';
++ function todayUsageHtml(a) {
++ var usage = a && a.todayUsage;
++ if (!usage || usage.synced !== true) return '';
++ var used = Number(usage.used);
++ if (!isFinite(used) || used <= 0) return '';
++ return '<span class="wbs-usage-tag"><span>今日已使用</span>' + CREDIT_ICON + '<b>' + fmtCredits(used) + '</b></span>';
++ }
++
++ function accountStatusTagsHtml(a) {
++ var tags = todayUsageHtml(a);
++ return tags ? '<span class="wbs-account-tags">' + tags + '</span>' : '';
++ }
++
++ function checkinBadgeHtml(a) {
++ var tag = checkinHtml(a);
++ return tag ? '<span class="wbs-checkin-slot">' + tag + '</span>' : '';
+ }
+
function creditBlockHtml(credits, segments, account) {
if (isIdentityExpired(account)) return '';
-- var checkin = checkinHtml(account);
++ var usage = accountStatusTagsHtml(account);
// 企业账号不限量(官方 getEnterpriseUsage 返回 limitNum === -1)
if (account && account.creditUnlimited) {
return '<div class="wbs-credit-block">' +
-- '<div class="wbs-credit-line"><div class="wbs-credit-label"><span class="wbs-lbl">剩余积分</span>' + checkin + '</div><span class="wbs-credit-total">' + CREDIT_ICON + '<b>不限量</b></span></div>' +
++ '<div class="wbs-credit-line"><div class="wbs-credit-left"><span class="wbs-lbl">剩余</span><span class="wbs-credit-total">' + CREDIT_ICON + '<b>不限量</b></span></div>' + usage + '</div>' +
'<div class="wbs-credit-hint">企业配额</div>' +
'</div>';
}
-- if (credits === undefined) return '<div class="wbs-credit-block"><div class="wbs-credit-line"><div class="wbs-credit-label"><span class="wbs-lbl">剩余积分</span>' + checkin + '</div><span class="wbs-credit-loading">读取中…</span></div></div>';
-- if (credits === null) return '<div class="wbs-credit-block"><div class="wbs-credit-line"><div class="wbs-credit-label"><span class="wbs-lbl">剩余积分</span>' + checkin + '</div><span class="wbs-credit-na">-</span></div></div>';
++ if (credits === undefined) return '<div class="wbs-credit-block"><div class="wbs-credit-line"><div class="wbs-credit-left"><span class="wbs-lbl">剩余</span><span class="wbs-credit-loading">读取中…</span></div>' + usage + '</div></div>';
++ if (credits === null) return '<div class="wbs-credit-block"><div class="wbs-credit-line"><div class="wbs-credit-left"><span class="wbs-lbl">剩余</span><span class="wbs-credit-na">-</span></div>' + usage + '</div></div>';
return '<div class="wbs-credit-block">' +
-- '<div class="wbs-credit-line"><div class="wbs-credit-label"><span class="wbs-lbl">剩余积分</span>' + checkin + '</div><span class="wbs-credit-total">' + CREDIT_ICON + '<b>' + fmtCredits(credits) + '</b></span></div>' +
- creditUsageHtml(account) +
++ '<div class="wbs-credit-line"><div class="wbs-credit-left"><span class="wbs-lbl">剩余</span><span class="wbs-credit-total">' + CREDIT_ICON + '<b>' + fmtCredits(credits) + '</b></span></div>' + usage + '</div>' +
creditBarHtml(credits, segments) +
'</div>';
}
@@@ -7209,8 -7220,8 +7267,14 @@@
function sortAccountsByCreditExpiry() {
state.accounts = state.accounts.map(function (account, index) {
-- return { account: account, index: index, expiresAt: nearestCreditExpiry(account) };
++ return {
++ account: account,
++ index: index,
++ isCurrent: !!(state.current && account && account.uid === state.current.uid),
++ expiresAt: nearestCreditExpiry(account),
++ };
}).sort(function (a, b) {
++ if (a.isCurrent !== b.isCurrent) return a.isCurrent ? -1 : 1;
if (a.expiresAt !== b.expiresAt) return a.expiresAt - b.expiresAt;
return a.index - b.index;
}).map(function (item) { return item.account; });
@@@ -7268,8 -7279,8 +7332,16 @@@
}
function render(data) {
-- state.accounts = data.accounts || [];
state.current = data.current;
++ state.accounts = (data.accounts || []).slice();
++ if (state.current && state.current.uid) {
++ state.accounts.sort(function (left, right) {
++ var leftIsCurrent = !!(left && left.uid === state.current.uid);
++ var rightIsCurrent = !!(right && right.uid === state.current.uid);
++ if (leftIsCurrent === rightIsCurrent) return 0;
++ return leftIsCurrent ? -1 : 1;
++ });
++ }
state.creditRemaining = state.accounts.length;
updateAccountSummary();
var list = accountsPane.querySelector('.wbs-acct-list');
@@@ -7288,6 -7299,6 +7360,7 @@@
// 版本标签:个人账号显示「个人版」;企业账号显示企业名称(enterpriseName),缺省回退「企业」。
var editionBadge = a.type === 'personal' ? '个人版' : (a.enterpriseName ? a.enterpriseName : (a.type ? '企业' : ''));
var badge = editionBadge ? '<span class="wbs-badge">' + esc(editionBadge) + '</span>' : '';
++ var checkinBadge = checkinBadgeHtml(a);
// 当前登录账号:卡片右上角对勾角标(替代原「当前」文字标签)
var curMark = isCur ? '<span class="wbs-cur-marker" title="当前使用中">' + CUR_MARK_SVG + '</span>' : '';
// 当前登录账号隐藏操作;认证已过期的账号保留删除,但隐藏切换,避免进入登录页。
@@@ -7299,14 -7310,14 +7372,14 @@@
'<button class="wbs-icon-btn wbs-del" type="button" title="删除" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(a.nickname || '未命名') + '">' + TRASH_SVG + '</button>' +
'</div>';
// 国际版没有手机号:用 UIN(账号唯一数字标识)替代展示;国内版仍显示手机。
-- // wbs-uin-cell 用于 UIN 模式下补齐标签与取值之间的间距(wbs-phone-cell 默认 gap:0 过于紧凑)。
++ // UIN 与手机号共用同一标签和值间距,确保与“剩余”额度列对齐。
var isUinMode = !a.phone;
var idLbl = a.phone ? '手机' : (a.uin ? 'UIN' : '账号');
var idVal = a.phone ? esc(a.phone) : (a.uin ? esc(a.uin) : '-');
card.innerHTML =
curMark +
'<div class="wbs-info">' +
-- '<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + esc(a.nickname || '(未命名)') + '</span>' + badge + '</div>' + ops + '</div>' +
++ '<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + esc(a.nickname || '(未命名)') + '</span>' + badge + checkinBadge + '</div>' + ops + '</div>' +
'<div class="wbs-meta wbs-secondary-row">' +
'<div class="wbs-mi wbs-phone-cell' + (isUinMode ? ' wbs-uin-cell' : '') + '"><span class="wbs-lbl">' + idLbl + '</span><span class="wbs-val">' + idVal + '</span></div>' +
'<div class="wbs-mi wbs-token-cell"><span class="wbs-lbl">有效期至</span><span class="wbs-val' + (ts.warn ? ' wbs-warn' : '') + '">' + esc(ts.label) + '</span></div>' +
@@@ -7446,10 -7457,10 +7519,14 @@@
function updateCheckinCells(accounts) {
var cards = accountsPane.querySelectorAll('.wbs-card');
var byUid = {};
-- (accounts || []).forEach(function (a) { if (a && a.uid) byUid[a.uid] = a; });
(accounts || []).forEach(function (a) {
for (var j = 0; j < state.accounts.length; j++) {
-- if (state.accounts[j].uid === a.uid) { state.accounts[j].checkin = a.checkin; break; }
++ if (state.accounts[j].uid === a.uid) {
++ state.accounts[j].checkin = a.checkin;
++ if (Object.prototype.hasOwnProperty.call(a, 'todayUsage')) state.accounts[j].todayUsage = a.todayUsage;
++ byUid[a.uid] = state.accounts[j];
++ break;
++ }
}
});
for (var i = 0; i < cards.length; i++) {
@@@ -7457,8 -7468,8 +7534,17 @@@
var account = byUid[uid];
if (!account) continue;
var cell = cards[i].querySelector('.wbs-credit-cell');
-- var status = cell && cell.querySelector('.wbs-checkin-tag');
-- if (status) status.outerHTML = checkinHtml(account);
++ var status = cell && cell.querySelector('.wbs-account-tags');
++ if (status) status.outerHTML = accountStatusTagsHtml(account);
++ var nameGroup = cards[i].querySelector('.wbs-name-group');
++ var checkinSlot = nameGroup && nameGroup.querySelector('.wbs-checkin-slot');
++ var checkinBadge = checkinBadgeHtml(account);
++ if (checkinSlot) {
++ if (checkinBadge) checkinSlot.outerHTML = checkinBadge;
++ else checkinSlot.remove();
++ } else if (checkinBadge && nameGroup) {
++ nameGroup.insertAdjacentHTML('beforeend', checkinBadge);
++ }
if (cell) {
var hidden = isIdentityExpired(account);
cell.classList.toggle('wbs-credit-hidden', hidden);
@@@ -7551,8 -7562,17 +7637,15 @@@
var credits = r && typeof r.credits === 'number' && isFinite(r.credits) ? r.credits : null;
var segments = r && Array.isArray(r.segments) ? r.segments : [];
var unlimited = !!(r && r.unlimited);
- var todayUsed = r && r.todayUsed !== null && r.todayUsed !== undefined ? Number(r.todayUsed) : null;
- var used = r && r.totalDosage !== null && r.totalDosage !== undefined ? Number(r.totalDosage) : null;
++ var hasTodayUsage = !!(r && Object.prototype.hasOwnProperty.call(r, 'todayUsage'));
for (var i = 0; i < state.accounts.length; i++) {
- if (state.accounts[i].uid === a.uid) { state.accounts[i].credits = credits; state.accounts[i].creditSegments = segments; state.accounts[i].creditUnlimited = unlimited; break; }
+ if (state.accounts[i].uid === a.uid) {
+ state.accounts[i].credits = credits;
+ state.accounts[i].creditSegments = segments;
+ state.accounts[i].creditUnlimited = unlimited;
- state.accounts[i].todayUsed = todayUsed;
- state.accounts[i].used = used;
++ if (hasTodayUsage) state.accounts[i].todayUsage = r.todayUsage;
+ break;
+ }
}
updateCreditCell(a.uid, credits, segments);
})
@@@ -7787,7 -7807,7 +7880,7 @@@
'.wbs-root{position:fixed;right:22px;bottom:22px;z-index:2147483647;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;font-size:13px;color:#1f1f1f;-webkit-font-smoothing:antialiased}',
'.wbs-root.wbs-no-stash .wbs-stash-inline{display:none !important}',
/* 机器人悬浮按钮(bitter-dragon-16 移植):静态版 0.5 倍 · 无头顶尖角 · 眼睛双眨 */
-- '.wbs-fab{position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:pointer}',
++ '.wbs-fab{position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;will-change:right,bottom}',
'.wbs-fab-sleep-dot{position:absolute;top:-4px;right:-4px;width:18px;height:18px;border-radius:50%;background:rgba(126,128,138,.55);border:2px solid #141416;box-shadow:0 1px 3px rgba(0,0,0,.5);transition:background .25s,box-shadow .25s;z-index:3}',
'.wbs-fab-health-dot{position:absolute;top:-5px;left:-5px;width:14px;height:14px;border-radius:50%;background:#8b8f98;border:2px solid #141416;box-shadow:0 1px 3px rgba(0,0,0,.5);z-index:3}',
'.wbs-fab-health-dot.running{background:#4da3ff}.wbs-fab-health-dot.blocked{background:#ffb03a}.wbs-fab-health-dot.error{background:#ef6262}.wbs-fab-health-dot.suspected{background:#f08a3c}.wbs-fab-health-dot.stopped{background:#9ca3af}',
@@@ -7830,6 -7850,6 +7923,9 @@@
'@keyframes wbs-cc-upb{0%,10%{top:0;left:0%}20%,40%{top:-50%;left:0%}50%,100%{top:0;left:0%}}',
'.wbs-fab:hover{transform:scale(0.5)}',
'.wbs-fab:active{transform:scale(0.5) translate(2px,2px)}',
++ '.wbs-fab.is-dragging{cursor:grabbing;transition:none !important}',
++ '.wbs-fab.is-dragging .button{cursor:grabbing}',
++ '.wbs-fab.is-snapping{transition:right .56s cubic-bezier(.22,1.35,.36,1),bottom .56s cubic-bezier(.22,1.35,.36,1)}',
/* 面板:毛玻璃主题(半透明 + 模糊,背景图透出) */
'.wbs-panel{position:absolute;right:0;bottom:0;width:520px;max-width:94vw;height:650px;max-height:650px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden;backdrop-filter:blur(28px) saturate(1.25);-webkit-backdrop-filter:blur(28px) saturate(1.25)}',
'.wbs-panel.show{display:flex}',
@@@ -7855,11 -7875,11 +7951,12 @@@
'.wbs-secondary-row{flex-direction:row;align-items:center;justify-content:space-between;gap:12px;margin-bottom:8px}',
'.wbs-mi{display:flex;align-items:center;gap:6px;font-size:12px;line-height:1.4}',
'.wbs-phone-cell,.wbs-token-cell{flex:1;min-width:0}',
-- '.wbs-phone-cell{gap:0}',
++ '.wbs-phone-cell{gap:4px}',
// UIN 模式(国际版无手机号时用 UIN 替代):标签与数字之间保留正常间距
-- '.wbs-phone-cell.wbs-uin-cell{gap:8px}',
++ '.wbs-phone-cell.wbs-uin-cell{gap:4px}',
'.wbs-token-cell{justify-content:flex-end}',
-- '.wbs-phone-cell .wbs-lbl,.wbs-token-cell .wbs-lbl,.wbs-credit-label .wbs-lbl{width:auto}',
++ '.wbs-phone-cell .wbs-lbl,.wbs-credit-left .wbs-lbl{width:28px}',
++ '.wbs-token-cell .wbs-lbl{width:48px}',
'.wbs-phone-cell .wbs-val,.wbs-token-cell .wbs-val{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
'.wbs-lbl{color:var(--wb-icon-tertiary,#999);flex-shrink:0;width:60px;white-space:nowrap}',
'.wbs-val{color:var(--wb-color-text-primary,#1f1f1f);font-variant-numeric:tabular-nums;word-break:break-all}',
@@@ -7868,8 -7888,8 +7965,8 @@@
'.wbs-credit-cell{display:block!important;width:100%;min-width:0}',
'.wbs-credit-hidden{display:none!important}',
'.wbs-credit-block{width:100%;min-width:0}',
-- '.wbs-credit-line{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:6px}',
-- '.wbs-credit-label{display:inline-flex;align-items:center;gap:8px;min-width:0}',
++ '.wbs-credit-line{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:6px;min-width:0}',
++ '.wbs-credit-left{display:inline-flex;align-items:center;gap:4px;min-width:0}',
'.wbs-credit-total{display:inline-flex;align-items:center;gap:4px;color:var(--wb-color-text-primary,#1f1f1f);font-size:12px;font-variant-numeric:tabular-nums}',
'.wbs-credit-total b{font-weight:700}',
'.wbs-credit-bar{display:flex;align-items:stretch;gap:2px;width:100%;height:5px;min-height:5px;border-radius:0;overflow:visible;background:color-mix(in srgb,var(--wb-bg-tertiary,#e8e8eb) 70%,transparent)}',
@@@ -7895,6 -7915,9 +7992,11 @@@
'.wbs-credit-tooltip{display:none;position:fixed;z-index:2147483647;min-width:170px;max-width:260px;padding:8px 10px;border-radius:7px;background:#151518;color:#fff;font-size:11px;font-weight:500;line-height:1.55;white-space:pre-line;box-shadow:0 8px 22px rgba(0,0,0,.28);pointer-events:none}',
'.wbs-credit-empty{height:5px;border-radius:0;background:color-mix(in srgb,var(--wb-bg-tertiary,#e8e8eb) 70%,transparent);color:var(--wb-icon-tertiary,#999);font-size:10px;line-height:5px;text-align:center}',
'.wbs-credit-hint{color:var(--wb-icon-tertiary,#999);font-size:10px;line-height:1.4;margin-top:2px}',
- '.wbs-credit-usage{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:2px;color:var(--wb-icon-tertiary,#999);font-size:12px;line-height:1.4}',
- '.wbs-credit-usage .wbs-cu-item{display:inline-flex;align-items:center;gap:4px;min-width:0;font-variant-numeric:tabular-nums}',
- '.wbs-credit-usage b{color:var(--wb-color-text-primary,#1f1f1f);font-weight:600}',
++ '.wbs-account-tags{display:inline-flex;align-items:center;gap:5px;min-width:0;margin-left:auto}',
++ '.wbs-usage-tag{display:inline-flex;align-items:center;gap:4px;min-width:0;white-space:nowrap;color:var(--wb-color-text-primary,#1f1f1f);font-size:12px;font-weight:400;font-variant-numeric:tabular-nums}',
++ '.wbs-usage-tag svg{width:14px;height:14px;flex:0 0 14px}',
++ '.wbs-usage-tag b{font-weight:700}',
++ 'html.cb-dark .wbs-usage-tag,html[data-theme="dark"] .wbs-usage-tag{color:var(--wb-color-text-primary,#f3f5fa)}',
'.wbs-credit-icon{width:14px;height:14px;vertical-align:middle;flex-shrink:0}',
'.wbs-credit-loading{color:var(--wb-icon-tertiary,#999);font-size:12px}',
'.wbs-credit-na{color:var(--wb-icon-tertiary,#999);font-size:12px}',
diff --cc scripts/launcher-hidden.vbs
index da29a05,da29a05..6fd0df5
--- a/scripts/launcher-hidden.vbs
+++ b/scripts/launcher-hidden.vbs
@@@ -1,7 -1,7 +1,7 @@@
Option Explicit
' Desktop shortcut entry point. wscript.exe starts the Node launcher without a console window.
--Dim shell, fso, launcher, launcherJs, nodeBin, command, status
++Dim shell, fso, launcher, launcherJs, nodeBin, command, status, logPath
Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
@@@ -41,7 -41,7 +41,11 @@@ If Not fso.FileExists(nodeBin) Then nod
shell.CurrentDirectory = fso.GetParentFolderName(launcher)
command = """" & nodeBin & """ --experimental-sqlite """ & launcherJs & """"
status = shell.Run(command, 0, True)
--' The Node launcher records failures in %APPDATA%\\WorkDaddy\\launcher.log.
--' Keep the desktop shortcut silent: a modal dialog makes a successful GUI launch
--' look broken and can remain hidden behind WorkBuddy.
++' The Node launcher records failures in %APPDATA%\\WorkDaddy\\launcher.log and
++' shows details for uncaught failures. A non-zero status without that dialog means
++' Node itself failed before the launcher could report the error.
++If status <> 0 And status <> 4 Then
++ logPath = shell.ExpandEnvironmentStrings("%APPDATA%") & "\WorkDaddy\launcher.log"
++ MsgBox "WorkDaddy launch failed, exit code " & status & "." & vbCrLf & "See " & logPath & ".", 48, "WorkDaddy"
++End If
WScript.Quit status
diff --cc scripts/lib.js
index 8016a50,8016a50..c3691e9
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@@ -145,7 -145,7 +145,9 @@@ function sanitizeModel(model, opts)
}
function checkinDisplayValue(record, today, pending) {
-- if (pending || !record || record.date !== today) return null;
++ if (!record || record.date !== today) return null;
++ // 正在签到时保留已确认的成功标记;只有失败/未完成记录才暂不展示,避免首屏把已签到账号误显示为“签到中”。
++ if (pending && !record.ok) return null;
return { ok: !!record.ok, already: !!record.already, code: record.code, message: record.message };
}
diff --cc scripts/ui-port.js
index 0000000,0000000..6d3d16e
new file mode 100644
--- /dev/null
+++ b/scripts/ui-port.js
@@@ -1,0 -1,0 +1,43 @@@
++'use strict';
++
++const PROFILE_UI_PORTS = Object.freeze({
++ 'workbuddy-cn': Object.freeze([47832, 17832, 27832, 37832]),
++ 'workbuddy-ai': Object.freeze([47833, 17833, 27833, 37833]),
++ 'codebuddy-cn': Object.freeze([47834, 17834, 27834, 37834]),
++ 'codebuddy-intl': Object.freeze([47835, 17835, 27835, 37835]),
++});
++
++function validUiPort(port) {
++ return Number.isInteger(port) && port >= 1024 && port <= 65535;
++}
++
++function profileUiPortCandidates(profileId, options = {}) {
++ const fixed = PROFILE_UI_PORTS[profileId] || PROFILE_UI_PORTS['workbuddy-cn'];
++ const ports = [];
++ const add = (port) => {
++ const value = Number(port);
++ if (validUiPort(value) && !ports.includes(value)) ports.push(value);
++ };
++ if (fixed.includes(Number(options.persistedPort))) add(options.persistedPort);
++ add(options.preferredPort);
++ fixed.forEach(add);
++ return ports;
++}
++
++function selectPersistedUiPort(profileId, state) {
++ if (!state || state.profileId !== profileId) return null;
++ const port = Number(state.port);
++ return (PROFILE_UI_PORTS[profileId] || []).includes(port) ? port : null;
++}
++
++function parseUiPortState(text, profileId) {
++ try { return selectPersistedUiPort(profileId, JSON.parse(String(text || ''))); } catch (_) { return null; }
++}
++
++module.exports = {
++ PROFILE_UI_PORTS,
++ parseUiPortState,
++ profileUiPortCandidates,
++ selectPersistedUiPort,
++ validUiPort,
++};
diff --cc scripts/verify-win.cmd
index 34d7399,a4cc046..ee0a976
--- a/scripts/verify-win.cmd
+++ b/scripts/verify-win.cmd
@@@ -34,12 -34,12 +34,6 @@@ if exist "%SCRIPT_DIR%..\Install-WorkDa
echo 提示: 顶层 Install-WorkDaddy.cmd 未就位(打包时从 scripts\ 提升到 zip 根)
)
if exist "%SCRIPT_DIR%..\Start-WorkDaddy.cmd" echo 顶层入口 Start-WorkDaddy.cmd 存在
--if exist "%SCRIPT_DIR%..\安装失败自主解决提示词.txt" (
-- echo 安装失败自主解决提示词.txt 存在
--) else (
-- echo 缺失: 安装失败自主解决提示词.txt
-- set /a FAIL+=1
--)
if not exist "%SCRIPT_DIR%node_modules\ws\index.js" (
echo 警告: node_modules\ws 缺失(DevTools 代理降级,其他功能不受影响)
)
diff --cc scripts/watchdog.js
index ee2f746,ee2f746..39d70bd
--- a/scripts/watchdog.js
+++ b/scripts/watchdog.js
@@@ -38,6 -38,6 +38,45 @@@ const LOG_FILE = path.join(DATA_DIR, 'w
const UPDATE_PENDING_FILE = path.join(DATA_DIR, 'update', 'pending.json'); // 自动更新进行中标记(update 目录由 apply 流程创建)
const DAEMON_FILE = path.join(SCRIPTS_DIR, 'daemon.js');
++function updateProcessIsActive(pid) {
++ if (process.platform !== 'win32' || !Number.isSafeInteger(pid) || pid <= 0) return false;
++ const command = `Get-CimInstance Win32_Process -Filter \"ProcessId = ${pid}\" -ErrorAction SilentlyContinue | ` +
++ `Where-Object { $_.Name -match '^(powershell|pwsh)(\\.exe)?$' -and $_.CommandLine -match '(?i)apply-update\\.ps1' } | ` +
++ 'Select-Object -First 1 ProcessId | ConvertTo-Json -Compress';
++ const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command], {
++ encoding: 'utf8', timeout: 10000, windowsHide: true,
++ });
++ return !result.error && result.status === 0 && /ProcessId/.test(String(result.stdout || ''));
++}
++
++function updatePendingIsActive() {
++ if (!fs.existsSync(UPDATE_PENDING_FILE)) return false;
++ let pending = null;
++ try { pending = JSON.parse(fs.readFileSync(UPDATE_PENDING_FILE, 'utf8')); } catch (_) {}
++ const attemptId = pending && typeof pending.attempt === 'string' ? pending.attempt : '';
++ let attempt = null;
++ try {
++ const attemptFile = path.join(path.dirname(UPDATE_PENDING_FILE), 'last-attempt.json');
++ attempt = JSON.parse(fs.readFileSync(attemptFile, 'utf8'));
++ } catch (_) {}
++ const scriptPid = Number(attempt && attempt.attemptId === attemptId ? attempt.scriptPid : 0);
++ if (updateProcessIsActive(scriptPid)) return true;
++
++ // A marker without a live apply-update process is allowed a short grace
++ // period for the spawn/exit race, then it is safe to remove as stale.
++ const markedAt = pending && Date.parse(pending.at);
++ const gracePeriodMs = 10 * 60 * 1000;
++ if (Number.isFinite(markedAt) && Date.now() - markedAt < gracePeriodMs) return true;
++ try {
++ fs.unlinkSync(UPDATE_PENDING_FILE);
++ log('已清理确认没有更新进程的过期 pending.json,继续启动 daemon');
++ } catch (error) {
++ log('清理过期 pending.json 失败: ' + error.message);
++ return true;
++ }
++ return false;
++}
++
function log(...args) {
const line = `[${new Date().toISOString()}] ${args.join(' ')}\n`;
try {
@@@ -71,6 -71,6 +110,7 @@@ function runProcessQuery(whereClause)
});
return parseCimProcessResult(result, {
requireCommandLine: true, requireCurrentOwner: true, requireNativeArguments: true,
++ allowTransientNotFound: true,
});
}
@@@ -93,7 -93,7 +133,13 @@@ function pidFileState()
process.execPath, __filename, queryWatchdogProcesses()
).filter((item) => item.ProcessId !== process.pid)
.map((item) => assertSameProcessIdentity(item, item));
-- if (untracked.length) {
++ if (untracked.length === 1) {
++ // The PID file is only a lock hint. A single exact watchdog process is
++ // already bound to this profile by its Node path and entry script, so a
++ // file lost during installation/update can be safely reconstructed.
++ return { kind: 'recoverable', pid: untracked[0].ProcessId, watchdog: untracked[0], processes: queryWatchdogProcessFamily(untracked[0].ProcessId) };
++ }
++ if (untracked.length > 1) {
return { kind: 'untracked', pid: null, processIds: untracked.map((item) => item.ProcessId) };
}
return { kind: 'absent', pid: null };
@@@ -149,9 -149,9 +195,15 @@@ function terminateVerifiedProcess(origi
}
function stopVerifiedWatchdog() {
-- const state = pidFileState();
++ let state = pidFileState();
if (state.kind === 'absent') return;
if (state.kind === 'self') throw new Error('stop 命令不能结束自身');
++ if (state.kind === 'recoverable') {
++ fs.writeFileSync(PID_FILE, String(state.pid), { flag: 'wx' });
++ state = pidFileState();
++ if (state.kind !== 'verified') throw new Error('恢复 watchdog.pid 后无法再次验证 watchdog 身份');
++ log(`通过精确身份恢复缺失的 watchdog.pid=${state.pid}`);
++ }
if (state.kind === 'untracked') {
throw new Error(`检测到没有 PID 文件的 watchdog 进程 PID=${state.processIds.join(',')},无法确定当前 profile,拒绝结束`);
}
@@@ -186,6 -186,6 +238,17 @@@ if (existing.kind === 'stale')
removePidFileIf(existing.pid);
log('已清理确认不存在的旧 watchdog.pid,继续启动');
}
++if (existing.kind === 'recoverable') {
++ try {
++ fs.writeFileSync(PID_FILE, String(existing.pid), { flag: 'wx' });
++ log(`通过精确身份恢复缺失的 watchdog.pid=${existing.pid},本实例退出`);
++ } catch (error) {
++ const current = readPidFile();
++ if (current !== existing.pid) throw error;
++ log(`watchdog.pid 已由并发启动恢复为 ${existing.pid},本实例退出`);
++ }
++ process.exit(0);
++}
if (existing.kind === 'untracked') {
throw new Error(`检测到没有 PID 文件的 watchdog 进程 PID=${existing.processIds.join(',')},拒绝启动重复实例`);
}
@@@ -212,7 -212,7 +275,7 @@@ function startDaemon()
// 自动更新标记存在:daemon 是在「更新替换」窗口内退出的(apply-update.ps1 正在换文件),
// 绝不能立刻重启 daemon 抢占 47832 端口,否则会干扰替换甚至导致更新失败(历史偶发根因)。
// 标记由 apply-update.ps1 成功/失败后删除;删除后靠新版 launcher/手动启动重新拉起。
-- if (fs.existsSync(UPDATE_PENDING_FILE)) {
++ if (updatePendingIsActive()) {
log('检测到更新标记 pending.json,跳过自动重启 daemon(等待 apply-update.ps1 完成替换)');
return;
}
diff --cc scripts/win-launcher.js
index d9e7b9a,4c67597..c81c754
--- a/scripts/win-launcher.js
+++ b/scripts/win-launcher.js
@@@ -4,12 -4,12 +4,12 @@@
*
* 冷启动流程:
* 1) 确保 daemon 运行 —— watchdog 常驻(崩溃自动拉起);daemon 版本与内置不一致时强制重启
-- * 2) 若 WorkBuddy 已在运行,弹窗要求用户完全退出,本次入口安静结束
-- * 3) 否则以自动选择的 CDP 端口启动 → 等端口 → 注入
++ * 2) 若当前 profile 的 WorkBuddy 已在运行但没有 CDP,先按已验证 PID 重启
++ * 3) 以自动选择的 CDP 端口启动 → 等端口 → 注入
*
* 由 launcher.cmd 调用(cmd 负责兜底找 node),也可 node win-launcher.js 直接运行。
- * 默认按普通用户运行;用户明确以管理员身份启动时,整条 launcher/daemon
- * 链路继承 elevated 模式并在状态中校验,避免混用两个权限层级。
+ * 默认按普通用户运行;用户明确以管理员身份启动时,先通过桌面 Shell
- * 重启为标准权限。真正关闭 UAC、没有过滤 token 时才继续当前权限。
++ * 重启为标准权限。若无法确认已降权,则 fail closed 并提示用户。
*/
'use strict';
@@@ -47,8 -46,8 +47,12 @@@ if (process.platform === 'win32')
const { captureMessage, captureException } = require('./sentry-report.js');
const { getProfile, profileDataDir } = require('./profiles.js');
const { isTargetForProfile } = require('./cdp-targets.js');
++const { replaceFileWithRetry } = require('./atomic-file-write.js');
++const { parseUiPortState, profileUiPortCandidates } = require('./ui-port.js');
const SCRIPTS_DIR = __dirname;
++const WORKDADDY_APP_DIR = path.resolve(SCRIPTS_DIR, '..');
++process.env.WBSWITCH_APP_DIR = WORKDADDY_APP_DIR;
const HOST = '127.0.0.1';
const PROFILE_ID = process.env.WBSWITCH_PROFILE || 'workbuddy-cn';
if (!process.env.WBSWITCH_PROFILE) process.env.WBSWITCH_PROFILE = PROFILE_ID;
@@@ -57,13 -56,11 +61,15 @@@ const WBS_BRAND = PROFILE.appName || 'W
const DATA_DIR =
process.env.WBSWITCH_DATA_DIR ||
profileDataDir(PROFILE);
+const API_TOKEN_FILE = path.join(DATA_DIR, '.api-token');
+const DESKTOP_RELAUNCH_ARG = '--desktop-shell-relaunch';
const DEFAULT_UI_PORT = { 'workbuddy-cn': 47832, 'workbuddy-ai': 47833, 'codebuddy-cn': 47834, 'codebuddy-intl': 47835 }[PROFILE.id] || 47832;
--const UI_PORT = parseInt(process.env.WBSWITCH_PORT || String(DEFAULT_UI_PORT), 10);
--// watchdog/daemon inherit process.env. Persist the resolved profile port so an
--// AI launcher cannot fall back to daemon.js's legacy 47832 default.
++const REQUESTED_UI_PORT = parseInt(process.env.WBSWITCH_PORT || String(DEFAULT_UI_PORT), 10);
++let UI_PORT = REQUESTED_UI_PORT;
++// Make the profile's initial UI port available to every child process immediately.
++// configureUiPort() may replace it with a persisted fallback later.
process.env.WBSWITCH_PORT = String(UI_PORT);
++const UI_PORT_FILE = path.join(DATA_DIR, 'ui-port.json');
const PROFILE_CDP_PORTS = {
'workbuddy-cn': [9222, 9226, 9227, 9228, 9229, 9230, 9231, 9232],
'workbuddy-ai': [9223, 9233, 9234, 9235, 9236, 9237, 9238, 9239],
@@@ -102,35 -99,6 +108,80 @@@ function log(...args)
// ---------- 小工具 ----------
function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
+function readApiToken() {
+ try {
+ const token = fs.readFileSync(API_TOKEN_FILE, 'utf8').trim();
+ return /^[a-f0-9]{64}$/i.test(token) ? token : '';
+ } catch (_) { return ''; }
+}
+
+function localApiHeaders() {
+ const token = readApiToken();
+ return token ? { 'X-WorkDaddy-Token': token } : {};
+}
+
++function readUiPortFile() {
++ try { return parseUiPortState(fs.readFileSync(UI_PORT_FILE, 'utf8'), PROFILE.id); } catch (_) { return null; }
++}
++
++function writeUiPortFile(port) {
++ fs.mkdirSync(DATA_DIR, { recursive: true });
++ replaceFileWithRetry(UI_PORT_FILE, JSON.stringify({
++ profileId: PROFILE.id,
++ port,
++ updatedAt: new Date().toISOString(),
++ }) + '\n', 0o600);
++}
++
++function useUiPort(port) {
++ UI_PORT = port;
++ process.env.WBSWITCH_PORT = String(port);
++ writeUiPortFile(port);
++ return port;
++}
++
++async function configureUiPort() {
++ const candidates = profileUiPortCandidates(PROFILE.id, {
++ preferredPort: REQUESTED_UI_PORT,
++ persistedPort: readUiPortFile(),
++ });
++ for (const port of candidates) {
++ const response = await httpGet(port, '/api/status', localApiHeaders());
++ if (!response || response.status !== 200) continue;
++ let status;
++ try { status = JSON.parse(response.body); } catch (_) { continue; }
++ if (status && status.profile && status.profile.id === PROFILE.id &&
++ status.dataDir && sameWindowsPath(status.dataDir, DATA_DIR)) {
++ log('发现当前 profile daemon UI 端口: ' + port);
++ return useUiPort(port);
++ }
++ }
++ for (const port of candidates) {
++ if (await isLocalPortAvailable(port)) {
++ log((port === DEFAULT_UI_PORT ? '选择默认' : '选择备用') + ' daemon UI 端口: ' + port);
++ return useUiPort(port);
++ }
++ }
++ throw new Error('当前 profile 的 daemon UI 端口均不可绑定。请关闭占用端口的软件或 WSL2/Hyper-V 后重试');
++}
++
+function relaunchWithDesktopShell(nodeBin) {
+ const helper = path.join(SCRIPTS_DIR, 'windows-relaunch-standard.ps1');
+ if (!fs.existsSync(helper)) throw new Error('缺少标准权限重启脚本 windows-relaunch-standard.ps1');
+ const powershell = path.join(
+ process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'
+ );
+ const result = spawnSync(powershell, [
+ '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',
+ '-File', helper, '-NodePath', nodeBin, '-LauncherPath', __filename,
+ ], { encoding: 'utf8', windowsHide: true, timeout: 10000 });
+ if (result.error) throw result.error;
+ if (result.status !== 0) {
+ const detail = String(result.stderr || result.stdout || '').trim();
+ throw new Error(`无法通过桌面 Shell 重新启动${detail ? ': ' + detail : ''}`);
+ }
+}
+
function runHiddenPowerShell(script) {
if (process.platform !== 'win32') return;
try {
@@@ -342,6 -310,6 +393,7 @@@ function getWorkBuddyProcesses()
requireCommandLine: true,
requireCurrentOwner: true,
requireNativeArguments: true,
++ allowTransientNotFound: true,
});
}
@@@ -350,8 -318,8 +402,14 @@@ function daemonRunning()
return portOpen(UI_PORT);
}
++function isPrewarmProcess(process) {
++ return /(?:^|\s)--prewarm(?:\s|$)/i.test(String(process && process.CommandLine || ''));
++}
++
function workBuddyProcesses(binary = null) {
-- const processes = getWorkBuddyProcesses();
++ // WorkBuddy AI keeps a headless prewarm helper alive between windows. It is
++ // not the user-facing app and must not block a cold launch or be terminated.
++ const processes = getWorkBuddyProcesses().filter((process) => !isPrewarmProcess(process));
if (!binary) return processes;
const verified = filterVerifiedWindowsProcesses(binary, processes);
if (processes.length !== verified.length) {
@@@ -414,8 -382,8 +472,8 @@@ function logProcessDiagnostics(binary,
return rows;
}
--// 桌面快捷方式是“冷启动”入口:已有 WorkBuddy 时不结束用户进程,也不抢占其窗口。
--// 进程查询失败同样按无法确认处理,避免在边界状态误重启官方应用。
++// 仅保留给旧调用方的状态查询。真正的启动流程会在 findWorkBuddy() 后,
++// 通过 quitWorkBuddy() 对当前 profile 的已验证进程做精确重启。
function requireWorkBuddyClosedBeforeLaunch() {
if (process.platform !== 'win32') return false;
let rows;
@@@ -463,19 -431,19 +521,26 @@@ function findNode()
.filter((p) => fs.existsSync(p))
.sort();
} catch (_) {}
-- // Existing installs may have a watchdog/daemon still running under WorkBuddy's
-- // managed Node. Reuse that runtime first so identity checks can see the old
-- // process during an upgrade; fresh installs still prefer the bundled runtime.
-- const hasExistingWatchdogState = fs.existsSync(path.join(DATA_DIR, 'watchdog.pid'));
-- if (hasExistingWatchdogState && verDirs.length) {
-- return resolveWindowsExecutable(verDirs[verDirs.length - 1]);
++
++ // A stale watchdog.pid is not evidence that the daemon uses WorkBuddy's
++ // managed Node. Select a runtime only when its exact daemon/watchdog process
++ // is actually running; otherwise a stale PID file can make identity checks
++ // reject a valid daemon started by the bundled runtime.
++ const candidates = [];
++ for (const candidate of [bundled, ...verDirs]) {
++ try {
++ const resolved = resolveWindowsExecutable(candidate);
++ if (!candidates.some((item) => sameWindowsPath(item, resolved))) candidates.push(resolved);
++ } catch (_) {}
}
-- try {
-- if (fs.existsSync(bundled)) return resolveWindowsExecutable(bundled);
-- } catch (_) {}
-- if (verDirs.length) {
-- try { return resolveWindowsExecutable(verDirs[verDirs.length - 1]); } catch (_) {}
++ for (const candidate of candidates) {
++ try {
++ if (uniqueNodeProcess(candidate, DAEMON_SCRIPT) || uniqueNodeProcess(candidate, WATCHDOG_SCRIPT)) {
++ return candidate;
++ }
++ } catch (_) {}
}
++ if (candidates.length) return candidates[0];
try {
const r = spawnSync('where.exe', ['node.exe'], { encoding: 'utf8', timeout: 3000, windowsHide: true });
const candidate = String(r.stdout || '').split(/\r?\n/).map((line) => line.trim()).find(Boolean);
@@@ -497,7 -465,7 +562,10 @@@ function findWorkBuddy()
} catch (_) {}
return null;
};
-- const runningBin = selectRunningProfileBinary([...PROFILE_BINARY_NAMES], getWorkBuddyProcesses());
++ const runningBin = selectRunningProfileBinary(
++ [...PROFILE_BINARY_NAMES],
++ getWorkBuddyProcesses().filter((process) => !isPrewarmProcess(process))
++ );
const envBin = tryFile(process.env.WBSWITCH_WORKBUDDY_BIN);
if (process.env.WBSWITCH_WORKBUDDY_BIN && !envBin) {
throw new Error('WBSWITCH_WORKBUDDY_BIN 不是可验证的当前 profile 主程序');
@@@ -654,10 -622,10 +722,41 @@@ function readWatchdogPid()
}
}
--function watchdogState(nodeBin) {
-- const pid = readWatchdogPid();
-- const exact = uniqueNodeProcess(nodeBin, WATCHDOG_SCRIPT);
-- if (!pid) return exact ? { kind: 'untracked', pid: null, process: exact } : { kind: 'absent', pid: null };
++async function watchdogState(nodeBin) {
++ let pid = readWatchdogPid();
++ let exact = uniqueNodeProcess(nodeBin, WATCHDOG_SCRIPT);
++ if (!pid) {
++ // A detached watchdog can be visible to CIM a moment before its atomic
++ // PID-file write becomes visible. Give that startup race a short window;
++ // after it expires, a single exact process can be recovered below while
++ // ambiguous or duplicate instances still fail closed.
++ for (let attempt = 0; attempt < 10 && !pid; attempt += 1) {
++ if (attempt > 0) await sleep(250);
++ pid = readWatchdogPid();
++ if (pid) break;
++ exact = uniqueNodeProcess(nodeBin, WATCHDOG_SCRIPT);
++ }
++ }
++ if (!pid && exact) {
++ // An installer/update can remove watchdog.pid after the exact watchdog
++ // process has started but before that process exits. The executable path,
++ // entry script, owner, and profile-specific scripts directory are already
++ // stronger identity evidence than the user-writable PID file. Recreate the
++ // file only for this single exact process, then re-read it and verify the
++ // process again before allowing reuse.
++ try {
++ fs.writeFileSync(WATCHDOG_PID_FILE, String(exact.ProcessId), { flag: 'wx' });
++ log(`通过精确身份恢复缺失的 watchdog.pid=${exact.ProcessId}`);
++ pid = readWatchdogPid();
++ } catch (error) {
++ const current = readWatchdogPid();
++ if (current !== Number(exact.ProcessId)) {
++ throw new Error('当前 profile 的 watchdog.pid 缺失,且无法安全恢复: ' + error.message);
++ }
++ pid = current;
++ }
++ }
++ if (!pid) return { kind: 'absent', pid: null };
let processes;
try {
processes = queryNodeProcesses(nodeBin, [pid], path.basename(WATCHDOG_SCRIPT));
@@@ -752,7 -708,7 +851,13 @@@ function killVerifiedNodeProcess(proces
const result = spawnSync('taskkill', ['/F', '/PID', String(pid)], {
stdio: 'ignore', windowsHide: true, timeout: 10000,
});
-- if (result.error || result.status !== 0) throw new Error(`无法结束已验证进程 PID=${pid}`);
++ if (result.error || result.status !== 0) {
++ // taskkill can race with a process that exits after the final identity
++ // check. Re-query the exact PID before failing; a missing PID means the
++ // requested termination already happened.
++ if (queryNodeProcesses(nodeBin, [pid]).length === 0) return true;
++ throw new Error(`无法结束已验证进程 PID=${pid}`);
++ }
if (queryNodeProcesses(nodeBin, [pid]).length !== 0) throw new Error(`已验证进程 PID=${pid} 未退出`);
return true;
}
@@@ -778,7 -734,7 +883,7 @@@ function removeWatchdogPidIf(pid)
}
async function stopDaemonByPort(nodeBin, allowLowerPrivilege = false) {
-- const watchdog = watchdogState(nodeBin);
++ const watchdog = await watchdogState(nodeBin);
if (watchdog.kind === 'untracked') {
throw new Error('发现没有当前 profile PID 文件的 watchdog 进程,拒绝复用或结束');
}
@@@ -860,7 -819,7 +965,7 @@@ async function ensureDaemon(nodeBin)
}
}
-- let watchdog = watchdogState(nodeBin);
++ let watchdog = await watchdogState(nodeBin);
if (watchdog.kind === 'untracked') {
throw new Error('发现没有当前 profile PID 文件的 watchdog 进程,拒绝复用或结束');
}
@@@ -928,11 -887,11 +1033,18 @@@ function exitSnapshot(binary = null)
};
}
--async function killForExit(args, stage) {
++async function killForExit(args, stage, verifyGone) {
const result = await runTaskkill(args);
const error = result.error ? result.error.message : '';
log(`[exit] ${stage} taskkill=${args.join(' ')} code=${result.code == null ? 'null' : result.code}${error ? ' error=' + error : ''}`);
if (result.error || result.code !== 0) {
++ // Windows may report ERRORLEVEL 128 when the target exits between the
++ // caller's identity re-check and taskkill. Accept it only when this exact
++ // target PID has disappeared.
++ if (verifyGone && await verifyGone()) {
++ log(`[exit] ${stage} taskkill 非零但目标 PID 已消失,按竞态成功处理`);
++ return result;
++ }
throw result.error || new Error(`${stage} taskkill 失败 (code=${result.code})`);
}
return result;
@@@ -943,7 -902,7 +1055,16 @@@ async function killVerifiedWorkBuddyPro
const current = workBuddyProcesses(binary).find((item) => Number(item.ProcessId) === pid);
if (!current) return false;
assertSameProcessIdentity(process, current);
-- await killForExit([...(force ? ['/F'] : []), '/PID', String(pid)], stage);
++ await killForExit(
++ [...(force ? ['/F'] : []), '/PID', String(pid)],
++ stage,
++ async () => {
++ const after = workBuddyProcesses(binary).find((item) => Number(item.ProcessId) === pid);
++ if (!after) return true;
++ assertSameProcessIdentity(process, after);
++ return false;
++ }
++ );
return true;
}
@@@ -1125,15 -1084,7 +1246,18 @@@ if (require.main === module) (async ()
await reportAndExit(1, '未找到 Node.js(WorkBuddy 托管运行时或 PATH)', 'windows-launcher-node');
return;
}
+ if (process.platform === 'win32' && WINDOWS_PRIVILEGE === 'elevated') {
+ if (!process.argv.includes(DESKTOP_RELAUNCH_ARG)) {
+ relaunchWithDesktopShell(nodeBin);
+ log('管理员入口已通过桌面 Shell 重新派发;当前 elevated launcher 退出');
+ process.exit(0);
+ }
- log('桌面 Shell 仍返回 elevated token(可能已关闭 UAC),继续使用当前系统权限');
++ log('桌面 Shell 仍返回 elevated token(可能已关闭 UAC),拒绝继续启动管理员权限 WorkDaddy');
++ showWindowsMessageBox(WBS_BRAND, '无法自动降回普通用户权限,已拒绝启动管理员权限 WorkDaddy。请开启 UAC 后双击快捷方式重试。');
++ process.exit(5);
+ }
await configureCdpPort();
++ await configureUiPort();
await ensureDaemon(nodeBin);
@@@ -1182,6 -1133,6 +1304,7 @@@
})().catch((e) => {
log('launcher 异常: ' + (e && e.stack || e));
console.error(WBS_BRAND + ' 启动异常: ' + (e && e.message || e));
++ showWindowsMessageBox(WBS_BRAND, '启动失败:' + (e && e.message || e) + '\n\n详细信息已写入 launcher.log。');
captureException(e, { stage: 'windows-launcher-uncaught' }).catch(() => {}).finally(() => process.exit(4));
});
diff --cc scripts/win/workdaddy.iss
index 80ac7ec,3394ad3..bf5fd05
--- a/scripts/win/workdaddy.iss
+++ b/scripts/win/workdaddy.iss
@@@ -60,9 -60,8 +60,8 @@@ Name: "chinesesimplified"; MessagesFile
[Files]
Source: "{#StageRoot}\scripts\prepare-win-install.ps1"; Flags: dontcopy
Source: "{#StageRoot}\scripts\windows-process-boundary.ps1"; Flags: dontcopy
-Source: "{#StageRoot}\scripts\*"; DestDir: "{app}\scripts"; Excludes: "prepare-win-install.ps1"; Flags: ignoreversion recursesubdirs createallsubdirs
-Source: "{#StageRoot}\troubleshooting.txt"; DestDir: "{app}"; Flags: ignoreversion
+Source: "{#StageRoot}\scripts\*"; DestDir: "{app}\scripts"; Excludes: "prepare-win-install.ps1,runtime\node\*"; Flags: ignoreversion recursesubdirs createallsubdirs
+Source: "{#StageRoot}\scripts\runtime\node\*"; DestDir: "{app}\scripts\runtime\node"; Flags: ignoreversion recursesubdirs createallsubdirs; Check: ShouldReplaceRuntime
- Source: "{#StageRoot}\安装失败自主解决提示词.txt"; DestDir: "{app}"; Flags: ignoreversion
[Icons]
Name: "{group}\{#ProductName}"; Filename: "{sys}\wscript.exe"; Parameters: "//nologo ""{app}\scripts\launcher-hidden.vbs"""; WorkingDir: "{app}\scripts"; IconFilename: "{app}\scripts\WorkDaddy.ico"
diff --cc scripts/windows-process-boundary.js
index 9354e15,dcb62ac..7be01be
--- a/scripts/windows-process-boundary.js
+++ b/scripts/windows-process-boundary.js
@@@ -87,6 -87,6 +87,7 @@@ function parseCimProcessResult(result,
}
if (result.status !== 0) {
const detail = String(result.stderr || '').trim();
++ if (options.allowTransientNotFound && /(0x80041002|ObjectNotFound|not found)/i.test(detail)) return [];
throw new Error(`CIM process query exited with status ${result.status}${detail ? ': ' + detail : ''}`);
}
const output = String(result.stdout || '').trim();
@@@ -132,7 -132,7 +133,7 @@@ function buildNativeProcessQuery(helper
throw new Error('Native process query requires a trusted absolute helper and source');
}
const quotedHelper = helper.replace(/'/g, "''");
-- return `. '${quotedHelper}'; ${source} | ForEach-Object { ConvertTo-WorkDaddyProcessRecord -Process $_ } | ConvertTo-Json -Compress -Depth 4`;
++ return `. '${quotedHelper}'; ${source} | ForEach-Object { ConvertTo-WorkDaddyProcessRecordIfPresent -Process $_ } | Where-Object { $null -ne $_ } | ConvertTo-Json -Compress -Depth 4`;
}
function sameWindowsFilePath(a, b) {
diff --cc scripts/windows-process-boundary.ps1
index 8f0e20e,32c4480..ab5aa6a
--- a/scripts/windows-process-boundary.ps1
+++ b/scripts/windows-process-boundary.ps1
@@@ -106,7 -106,7 +106,12 @@@ function ConvertTo-WorkDaddyProcessReco
[string]::IsNullOrWhiteSpace([string]$Process.Name) -or
[string]::IsNullOrWhiteSpace([string]$Process.ExecutablePath) -or
[string]::IsNullOrWhiteSpace([string]$Process.CommandLine)) { throw 'CIM 进程身份字段不完整' }
-- $ownerResult = Invoke-CimMethod -InputObject $Process -MethodName GetOwner -ErrorAction Stop
++ try {
++ $ownerResult = Invoke-CimMethod -InputObject $Process -MethodName GetOwner -ErrorAction Stop
++ } catch {
++ if (Test-CimProcessDisappearedError $_) { return $null }
++ throw
++ }
if ($ownerResult.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$ownerResult.User)) {
throw "无法确认 PID $processId 的进程所有者"
}
@@@ -131,6 -131,6 +136,21 @@@
}
}
++function Test-CimProcessDisappearedError {
++ param([Parameter(Mandatory = $true)]$ErrorRecord)
++ $text = [string]$ErrorRecord.Exception + ' ' + [string]$ErrorRecord
++ return $text -match '(?i)(0x80041002|ObjectNotFound|not found|不存在)'
++}
++
++function ConvertTo-WorkDaddyProcessRecordIfPresent {
++ param([Parameter(Mandatory = $true)]$Process)
++ try { return ConvertTo-WorkDaddyProcessRecord -Process $Process }
++ catch {
++ if (Test-CimProcessDisappearedError $_) { return $null }
++ throw
++ }
++}
++
function Test-ExactNodeEntryCommandLine {
param(
[Parameter(Mandatory = $true)][string]$CommandLine,
@@@ -190,6 -190,6 +210,7 @@@ function Get-StrictProcessRecord
if ($rows.Count -eq 0) { return $null }
if ($rows.Count -ne 1) { throw "PID $ProcessId 的 CIM 记录不唯一" }
$record = ConvertTo-WorkDaddyProcessRecord -Process $rows[0]
++ if ($null -eq $record) { return $null }
if ([int]$record.ProcessId -ne $ProcessId) { throw "PID $ProcessId 的 CIM 记录不匹配" }
return $record
}
@@@ -240,6 -240,6 +261,17 @@@ function Assert-CmdLauncherIdentity
}
function Get-UniqueNodeProcessForScript {
++ param(
++ [Parameter(Mandatory = $true)][string]$ExpectedScript,
++ [int]$ExpectedParentProcessId = 0
++ )
++ $matches = @(Get-VerifiedNodeProcessesForScript -ExpectedScript $ExpectedScript -ExpectedParentProcessId $ExpectedParentProcessId)
++ if ($matches.Count -gt 1) { throw "目标 Node 入口存在多个进程: $ExpectedScript" }
++ if ($matches.Count -eq 0) { return $null }
++ return $matches[0]
++}
++
++function Get-VerifiedNodeProcessesForScript {
param(
[Parameter(Mandatory = $true)][string]$ExpectedScript,
[int]$ExpectedParentProcessId = 0
@@@ -275,9 -275,9 +307,7 @@@
if ($null -eq $record) { throw "目标 Node 进程 PID=$processId 在身份验证期间消失" }
$matches += ,(Assert-NodeProcessIdentity -Process $record -ExpectedPid $processId -ExpectedScript $ExpectedScript)
}
-- if ($matches.Count -gt 1) { throw "目标 Node 入口存在多个进程: $ExpectedScript" }
-- if ($matches.Count -eq 0) { return $null }
-- return $matches[0]
++ return $matches
}
function Get-ListeningProcessIdsFromLines {
@@@ -401,6 -351,6 +431,14 @@@ function Stop-VerifiedWorkDaddyLifecycl
[Parameter(Mandatory = $true)][string]$ExpectedWatchdogScript,
[Parameter(Mandatory = $true)][string]$ExpectedDaemonScript
)
++ $scriptsDir = Split-Path -Parent $ExpectedDaemonScript
++ $expectedLauncherScript = Join-Path $scriptsDir 'win-launcher.js'
++ # The launcher itself runs from the packaged Node runtime and can keep
++ # runtime\node\node.exe locked while it waits for CDP or a retry window.
++ # Stop only exact launcher entries under this profile's installation path.
++ $launchers = @(Get-VerifiedNodeProcessesForScript -ExpectedScript $expectedLauncherScript)
++ foreach ($launcher in $launchers) { Stop-VerifiedProcess -Process $launcher }
++
$pidFile = Join-Path $DataDir 'watchdog.pid'
$pidFileExists = Test-Path -LiteralPath $pidFile
$watchdogPid = $null
@@@ -505,6 -455,6 +543,7 @@@
}
Remove-Item -LiteralPath $pidFile -Force -ErrorAction Stop
}
++ [void](Wait-VerifiedFileUnlocked -Path (Join-Path $scriptsDir 'runtime\node\node.exe'))
}
function Assert-DaemonStatusIdentity {
@@@ -554,6 -504,6 +593,16 @@@ function Test-ExclusiveFile
}
}
++function Wait-VerifiedFileUnlocked {
++ param([Parameter(Mandatory = $true)][string]$Path)
++ if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $true }
++ for ($attempt = 0; $attempt -lt 30; $attempt++) {
++ if (Test-ExclusiveFile -Path $Path) { return $true }
++ Start-Sleep -Milliseconds 200
++ }
++ throw "文件锁未释放: $Path"
++}
++
function Release-VerifiedLauncherLock {
param([Parameter(Mandatory = $true)][string]$LauncherPath)
if (Test-ExclusiveFile -Path $LauncherPath) { return $true }
diff --cc scripts/windows-relaunch-standard.ps1
index 3447a1f,0000000..012a3a4
mode 100644,000000..100644
--- a/scripts/windows-relaunch-standard.ps1
+++ b/scripts/windows-relaunch-standard.ps1
@@@ -1,31 -1,0 +1,50 @@@
- param(
++param(
+ [Parameter(Mandatory = $true)][string]$NodePath,
+ [Parameter(Mandatory = $true)][string]$LauncherPath
+)
+
+$ErrorActionPreference = 'Stop'
+
+function Quote-WindowsArgument {
+ param([Parameter(Mandatory = $true)][string]$Value)
+ if ($Value.IndexOfAny([char[]]@([char]0, [char]10, [char]13, [char]34)) -ge 0) {
+ throw 'Invalid relaunch argument path.'
+ }
+ return [char]34 + $Value + [char]34
+}
+
+$node = [IO.Path]::GetFullPath($NodePath)
+$launcher = [IO.Path]::GetFullPath($LauncherPath)
+$scriptsRoot = [IO.Path]::GetFullPath($PSScriptRoot).TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar
+if (-not (Test-Path -LiteralPath $node -PathType Leaf)) { throw 'Node runtime is missing.' }
+if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) { throw 'Windows launcher is missing.' }
+if (-not $launcher.StartsWith($scriptsRoot, [StringComparison]::OrdinalIgnoreCase)) {
+ throw 'Windows launcher is outside the installed scripts directory.'
+}
+
- # Shell.Application delegates ShellExecute to the interactive Explorer shell.
- # With normal UAC this yields the desktop user's standard token. If UAC is
- # genuinely disabled, Explorer has no filtered token and the marker prevents a
- # relaunch loop; the Node launcher then continues in the only available mode.
- $shell = New-Object -ComObject Shell.Application
++# Ask the out-of-process Explorer desktop for its Application object. Creating
++# Shell.Application in-process from an elevated launcher can preserve the
++# elevated token instead of performing a real de-elevation.
++$shellWindows = New-Object -ComObject Shell.Application
++$desktopView = $null
++try {
++ $desktopLocation = 0
++ $desktopRoot = 0
++ $desktopHwnd = 0
++ # SWC_DESKTOP (8) asks the ShellWindows collection for Explorer's desktop
++ # view, whose Application object is owned by the unelevated Explorer process.
++ $desktopView = $shellWindows.FindWindowSW([ref]$desktopLocation, [ref]$desktopRoot, 8, [ref]$desktopHwnd, 1)
++} catch {}
++if (-not $desktopView) {
++ # Explorer's MainWindowHandle is not guaranteed to match the HWND exposed
++ # by ShellWindows. Match the out-of-process Shell object by executable path.
++ $desktopView = $shellWindows.Windows() |
++ Where-Object {
++ try { [IO.Path]::GetFileName([string]$_.FullName) -ieq 'explorer.exe' } catch { $false }
++ } |
++ Select-Object -First 1
++}
++if (-not $desktopView) { throw '无法取得 Explorer 桌面视图,拒绝以管理员权限继续启动。' }
++$shell = $desktopView.Document.Application
+$arguments = '--experimental-sqlite ' + (Quote-WindowsArgument $launcher) + ' --desktop-shell-relaunch'
+$shell.ShellExecute($node, $arguments, (Split-Path -Parent $launcher), 'open', 0)
diff --cc test/atomic-file-write.test.js
index 0000000,0000000..0d7c2a2
new file mode 100644
--- /dev/null
+++ b/test/atomic-file-write.test.js
@@@ -1,0 -1,0 +1,55 @@@
++'use strict';
++
++const test = require('node:test');
++const assert = require('node:assert/strict');
++const { replaceFileWithRetry } = require('../scripts/atomic-file-write.js');
++
++test('atomic replacement retries transient Windows temp writes and destination renames', () => {
++ let writes = 0;
++ let renames = 0;
++ const sleeps = [];
++ const files = new Set();
++ const fakeFs = {
++ writeFileSync(file) {
++ writes++;
++ if (writes < 3) throw Object.assign(new Error('temporary filesystem failure'), { code: 'UNKNOWN' });
++ files.add(file);
++ },
++ chmodSync() {},
++ renameSync(source, destination) {
++ renames++;
++ if (renames === 1) throw Object.assign(new Error('sharing violation'), { code: 'EPERM' });
++ assert.equal(files.has(source), true);
++ files.delete(source);
++ files.add(destination);
++ },
++ unlinkSync(file) { files.delete(file); },
++ };
++
++ replaceFileWithRetry('C:\\Users\\me\\.workbuddy\\settings.json', '{}\n', undefined, {
++ fs: fakeFs,
++ platform: 'win32',
++ sleep: (ms) => sleeps.push(ms),
++ suffix: () => 'fixed',
++ });
++
++ assert.equal(writes, 3);
++ assert.equal(renames, 2);
++ assert.equal(files.has('C:\\Users\\me\\.workbuddy\\settings.json'), true);
++ assert.equal([...files].some((file) => file.includes('.wbs-tmp-')), false);
++ assert.equal(sleeps.length, 3);
++});
++
++test('atomic replacement does not retry non-transient write failures', () => {
++ let writes = 0;
++ const fakeFs = {
++ writeFileSync() { writes++; throw Object.assign(new Error('parent missing'), { code: 'ENOENT' }); },
++ chmodSync() {},
++ renameSync() {},
++ unlinkSync() {},
++ };
++ assert.throws(() => replaceFileWithRetry('C:\\missing\\settings.json', '{}', undefined, {
++ fs: fakeFs, platform: 'win32', sleep: () => {}, suffix: () => 'fixed',
++ }), /parent missing/);
++ assert.equal(writes, 1);
++});
diff --cc test/auto-copy-rules.test.js
index 02c487b,02c487b..f85c309
--- a/test/auto-copy-rules.test.js
+++ b/test/auto-copy-rules.test.js
@@@ -267,9 -267,9 +267,12 @@@ test('api keys keep their full masked l
assert.equal(masked.includes('abcdef'), false);
});
--test('checkin display hides cached result while the current claim is still running', () => {
++test('checkin display keeps a confirmed result while the current claim is still running', () => {
const record = { date: '2026-08-23', ok: true, already: false, code: 0, message: 'ok' };
-- assert.equal(checkinDisplayValue(record, '2026-08-23', true), null);
++ assert.deepEqual(checkinDisplayValue(record, '2026-08-23', true), {
++ ok: true, already: false, code: 0, message: 'ok',
++ });
++ assert.equal(checkinDisplayValue({ date: '2026-08-23', ok: false }, '2026-08-23', true), null);
assert.deepEqual(checkinDisplayValue(record, '2026-08-23', false), {
ok: true, already: false, code: 0, message: 'ok',
});
diff --cc test/checkin-result.test.js
index 0000000,0000000..8936100
new file mode 100644
--- /dev/null
+++ b/test/checkin-result.test.js
@@@ -1,0 -1,0 +1,17 @@@
++'use strict';
++
++const assert = require('node:assert/strict');
++const test = require('node:test');
++const { classifyCheckinResult } = require('../scripts/checkin-result.js');
++
++test('check-in requires an explicit successful response code', () => {
++ assert.equal(classifyCheckinResult({ httpOk: true, code: undefined, message: 'OK' }).ok, false);
++ assert.equal(classifyCheckinResult({ httpOk: true, code: 0, message: 'OK' }).ok, true);
++ assert.equal(classifyCheckinResult({ httpOk: false, code: 0, message: 'OK' }).ok, false);
++});
++
++test('code 10001 is cached only when it explicitly means already checked in', () => {
++ assert.equal(classifyCheckinResult({ httpOk: true, code: 10001, message: '今日已签到' }).ok, true);
++ assert.equal(classifyCheckinResult({ httpOk: true, code: 10001, message: '活动未开启' }).ok, false);
++ assert.equal(classifyCheckinResult({ httpOk: true, code: 10001, message: '请求成功' }).ok, false);
++});
diff --cc test/credit-request-usage.test.js
index 0000000,74b592f..237f72a
mode 000000,100644..100644
--- a/test/credit-request-usage.test.js
+++ b/test/credit-request-usage.test.js
@@@ -1,0 -1,97 +1,126 @@@
+ 'use strict';
++
+ const assert = require('node:assert/strict');
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const test = require('node:test');
+
+ const {
- sumRequestCredits,
++ fetchUsageSinceAnchor,
+ formatLocalDateTime,
- startOfLocalDay,
- parseRowTime,
++ normalizeUsageRow,
+ } = require('../scripts/credit-request-usage.js');
+
-const dayStart = new Date(2026, 7, 27, 0, 0, 0, 0).getTime(); // 2026-08-27 00:00:00 本地
-const dayEnd = new Date(2026, 7, 27, 23, 59, 59, 0).getTime();
++function jsonResponse(payload, status = 200) {
++ return {
++ ok: status >= 200 && status < 300,
++ status,
++ async text() { return JSON.stringify(payload); },
++ };
++}
+
-test('sums credit of requests whose requestTime falls inside the window', () => {
- const rows = [
- { credit: 0.08, requestTime: '2026-08-27 17:54:00' },
- { credit: 6.37, requestTime: '2026-08-27 17:03:00' },
- { credit: 0, requestTime: '2026-08-27 19:39:00' }, // 0 积分不计
- { credit: 1.5, requestTime: '2026-08-27 23:59:59' },
- { credit: 99, requestTime: '2026-08-26 23:59:59' }, // 昨天,不计
- { credit: 88, requestTime: '2026-08-28 00:00:00' }, // 明天,不计
- ];
- const sum = sumRequestCredits(rows, dayStart, dayEnd);
- assert.equal(sum, 7.95); // 0.08+6.37+1.5
-});
++function usageRow(id, requestTime, credit = 1) {
++ return {
++ requestId: id,
++ requestTime,
++ credit,
++ model: 'claude-test',
++ client: 'desktop',
++ agentPurpose: 'chat',
++ input: 'must never be persisted',
++ inputTrunc: 'must never be persisted',
++ };
++}
+
-test('sumRequestCredits handles missing/blank credit and rows', () => {
- assert.equal(sumRequestCredits(null, dayStart, dayEnd), 0);
- assert.equal(sumRequestCredits([], dayStart, dayEnd), 0);
- assert.equal(sumRequestCredits([{ requestTime: '2026-08-27 12:00:00' }], dayStart, dayEnd), 0);
- assert.equal(sumRequestCredits([{ credit: 'abc', requestTime: '2026-08-27 12:00:00' }], dayStart, dayEnd), 0);
++test('normalizes only non-sensitive fields from official usage records', () => {
++ const row = normalizeUsageRow(usageRow('req-1', '2026-08-28 09:10:11', '1.25'));
++ assert.deepEqual(row, {
++ requestId: 'req-1',
++ requestTime: new Date(2026, 7, 28, 9, 10, 11).getTime(),
++ usageDate: '2026-08-28',
++ credit: 1.25,
++ model: 'claude-test',
++ client: 'desktop',
++ agentPurpose: 'chat',
++ });
++ assert.equal(Object.prototype.hasOwnProperty.call(row, 'input'), false);
++ assert.equal(Object.prototype.hasOwnProperty.call(row, 'inputTrunc'), false);
+ });
+
-test('sumRequestCredits supports numeric timestamp requestTime', () => {
- const ts = new Date(2026, 7, 27, 12, 0, 0).getTime(); // 毫秒
- const rows = [{ credit: 2.5, requestTime: ts }];
- assert.equal(sumRequestCredits(rows, dayStart, dayEnd), 2.5);
- // 秒级时间戳
- const s = Math.floor(ts / 1000);
- assert.equal(sumRequestCredits([{ credit: 3, requestTime: s }], dayStart, dayEnd), 3);
-});
++test('requests official pages newest-first and stops at the previous complete-sync anchor', async () => {
++ const calls = [];
++ const firstPage = Array.from({ length: 100 }, (_, index) =>
++ usageRow(`new-${index}`, `2026-08-28 10:${String(59 - Math.floor(index / 2)).padStart(2, '0')}:${String(59 - (index % 2)).padStart(2, '0')}`)
++ );
++ const fetchImpl = async (url, options) => {
++ const body = JSON.parse(options.body);
++ calls.push({ url, body, authorization: options.headers.authorization });
++ if (body.pageNum === 1) {
++ return jsonResponse({ code: 0, data: { total: 203, data: firstPage } });
++ }
++ if (body.pageNum === 2) {
++ return jsonResponse({ code: 0, data: { total: 203, data: [
++ usageRow('new-100', '2026-08-28 09:00:00', 2),
++ usageRow('known-anchor', '2026-08-28 08:59:59', 3),
++ usageRow('older-record', '2026-08-28 08:59:58', 4),
++ ] } });
++ }
++ throw new Error('anchor should stop pagination before page 3');
++ };
+
-test('rounds the daily total to two decimals', () => {
- const rows = [
- { credit: 0.005, requestTime: '2026-08-27 12:00:00' },
- { credit: 0.005, requestTime: '2026-08-27 12:00:01' },
- ];
- assert.equal(sumRequestCredits(rows, dayStart, dayEnd), 0.01);
-});
++ const result = await fetchUsageSinceAnchor({
++ accessToken: 'secret-token',
++ apiHost: 'https://www.codebuddy.cn',
++ startTime: new Date(2026, 7, 28, 0, 0, 0),
++ endTime: new Date(2026, 7, 28, 12, 0, 0),
++ anchorRequestId: 'known-anchor',
++ fetchImpl,
++ });
+
-test('parseRowTime handles string date-time and numeric', () => {
- assert.equal(parseRowTime('2026-08-27 12:00:00'), new Date(2026, 7, 27, 12, 0, 0).getTime());
- assert.equal(parseRowTime(''), null);
- assert.equal(parseRowTime(null), null);
- assert.equal(parseRowTime('abc'), null);
- assert.equal(parseRowTime(1787800000000), 1787800000000); // 毫秒
- assert.equal(parseRowTime(1787800000), 1787800000000); // 秒 → 毫秒
++ assert.equal(result.reachedAnchor, true);
++ assert.equal(result.newestRequestId, 'new-0');
++ assert.equal(result.records.length, 101);
++ assert.equal(result.records.some((row) => row.requestId === 'known-anchor'), false);
++ assert.equal(result.records.some((row) => row.requestId === 'older-record'), false);
++ assert.deepEqual(calls.map((call) => call.body.pageNum), [1, 2]);
++ assert.equal(calls[0].body.pageSize, 100);
++ assert.equal(calls[0].body.startTime, '2026-08-28 00:00:00');
++ assert.equal(calls[0].body.endTime, '2026-08-28 12:00:00');
++ assert.equal(calls[0].authorization, 'Bearer secret-token');
+ });
+
-test('formatLocalDateTime produces YYYY-MM-DD HH:mm:ss in local time', () => {
- const d = new Date(2026, 7, 27, 9, 5, 6);
- assert.equal(formatLocalDateTime(d), '2026-08-27 09:05:06');
-});
++test('rejects an incomplete official result instead of caching a partial total', async () => {
++ const fetchImpl = async (_url, options) => {
++ const page = JSON.parse(options.body).pageNum;
++ if (page === 1) {
++ return jsonResponse({ code: 0, data: {
++ total: 250,
++ data: Array.from({ length: 100 }, (_, index) => usageRow(`req-${index}`, `2026-08-28 10:${String(59 - Math.floor(index / 2)).padStart(2, '0')}:${String(59 - (index % 2)).padStart(2, '0')}`)),
++ } });
++ }
++ return jsonResponse({ code: 0, data: { total: 250, data: [] } });
++ };
+
-test('startOfLocalDay returns midnight of the same local day', () => {
- const d = new Date(2026, 7, 27, 18, 30, 0);
- const s = startOfLocalDay(d);
- assert.equal(s.getFullYear(), 2026);
- assert.equal(s.getMonth(), 7);
- assert.equal(s.getDate(), 27);
- assert.equal(s.getHours(), 0);
- assert.equal(s.getMinutes(), 0);
- assert.equal(s.getSeconds(), 0);
++ await assert.rejects(
++ fetchUsageSinceAnchor({
++ accessToken: 'secret-token',
++ apiHost: 'https://www.codebuddy.cn',
++ startTime: new Date(2026, 7, 28, 0, 0, 0),
++ endTime: new Date(2026, 7, 28, 12, 0, 0),
++ fetchImpl,
++ }),
++ /incomplete|不完整/i
++ );
+ });
+
-test('daemon uses the official usage endpoint with correct params', () => {
- const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
- const module = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'credit-request-usage.js'), 'utf8');
- assert.match(daemon, /fetchTodayUsage/);
- assert.match(daemon, /todayUsedFallback/);
- // 官方接口路径与分页参数封装在模块里
- assert.match(module, /billing\/meter\/get-user-request-usage/);
- assert.match(module, /pageNum/);
- assert.match(module, /startTime/);
- assert.match(module, /sumRequestCredits/);
++test('formats official request timestamps in local time', () => {
++ assert.equal(formatLocalDateTime(new Date(2026, 7, 28, 9, 5, 6)), '2026-08-28 09:05:06');
+ });
+
-test('renderer shows only today-used, not the ambiguous total-dosage figure', () => {
- const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
- assert.match(inject, /creditUsageHtml/);
- assert.match(inject, /今日已用/);
- // TotalDosage 语义容易引起误解(实测接近剩余余额),面板只显示今日已用,不再展示累计用量
- assert.doesNotMatch(inject, /累计已用/);
++test('daemon syncs official usage only for the current account and reads cached usage for all accounts', () => {
++ const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
++ assert.match(daemon, /listDailyUsage/);
++ assert.match(daemon, /syncCurrentCreditUsage/);
++ assert.match(daemon, /current.*\.uid === uid/);
++ assert.match(daemon, /todayUsage/);
+ });
diff --cc test/credit-usage-store.test.js
index 0000000,0000000..0067450
new file mode 100644
--- /dev/null
+++ b/test/credit-usage-store.test.js
@@@ -1,0 -1,0 +1,109 @@@
++'use strict';
++
++const assert = require('node:assert/strict');
++const fs = require('node:fs');
++const os = require('node:os');
++const path = require('node:path');
++const test = require('node:test');
++
++const { createCreditUsageStore } = require('../scripts/credit-usage-store.js');
++
++function tempStore() {
++ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-credit-usage-'));
++ return {
++ dir,
++ store: createCreditUsageStore({
++ dbPath: path.join(dir, 'credit-usage.db'),
++ profileId: 'workbuddy-cn',
++ }),
++ };
++}
++
++function record(requestId, usageDate, credit, requestTime) {
++ return {
++ requestId,
++ usageDate,
++ credit,
++ requestTime,
++ model: 'model-a',
++ client: 'desktop',
++ agentPurpose: 'chat',
++ };
++}
++
++test('persists usage by profile, uid and request id and aggregates all cached accounts', async (t) => {
++ const tmp = tempStore();
++ t.after(() => fs.rmSync(tmp.dir, { recursive: true, force: true }));
++
++ await tmp.store.saveSuccessfulSync({
++ uid: 'u1',
++ records: [
++ record('r1', '2026-08-28', 1.25, 1000),
++ record('r2', '2026-08-28', 2.5, 2000),
++ ],
++ anchorRequestId: 'r2',
++ syncedAt: 3000,
++ });
++ await tmp.store.saveSuccessfulSync({
++ uid: 'u2',
++ records: [record('r3', '2026-08-28', 4, 2500)],
++ anchorRequestId: 'r3',
++ syncedAt: 3500,
++ });
++ await tmp.store.saveSuccessfulSync({
++ uid: 'u3',
++ records: [],
++ anchorRequestId: '',
++ syncedAt: new Date(2026, 7, 28, 12, 0, 0).getTime(),
++ });
++
++ const summaries = await tmp.store.listDailyUsage(['u1', 'u2', 'u3', 'u4'], '2026-08-28');
++ assert.deepEqual(summaries, {
++ u1: { date: '2026-08-28', used: 3.75, count: 2, synced: true },
++ u2: { date: '2026-08-28', used: 4, count: 1, synced: true },
++ u3: { date: '2026-08-28', used: 0, count: 0, synced: true },
++ });
++ assert.equal(Object.prototype.hasOwnProperty.call(summaries, 'u4'), false);
++});
++
++test('repeated official request ids update instead of double counting and preserve sync state', async (t) => {
++ const tmp = tempStore();
++ t.after(() => fs.rmSync(tmp.dir, { recursive: true, force: true }));
++
++ await tmp.store.saveSuccessfulSync({
++ uid: 'u1',
++ records: [record('same-request', '2026-08-28', 1, 1000)],
++ anchorRequestId: 'same-request',
++ syncedAt: 2000,
++ });
++ await tmp.store.saveSuccessfulSync({
++ uid: 'u1',
++ records: [record('same-request', '2026-08-28', 2, 1000)],
++ anchorRequestId: 'new-anchor',
++ syncedAt: 3000,
++ });
++
++ assert.deepEqual(await tmp.store.dailyUsageForUid('u1', '2026-08-28'), {
++ date: '2026-08-28',
++ used: 2,
++ count: 1,
++ synced: true,
++ });
++ assert.deepEqual(await tmp.store.getSyncState('u1'), {
++ anchorRequestId: 'new-anchor',
++ lastSuccessAt: 3000,
++ });
++});
++
++test('persists verified daily check-in marks by profile, uid and date', async (t) => {
++ const tmp = tempStore();
++ t.after(() => fs.rmSync(tmp.dir, { recursive: true, force: true }));
++ await tmp.store.saveDailyCheckin({ uid: 'u1', date: '2026-08-28', checkedAt: 3000, code: 0, message: 'OK' });
++ assert.deepEqual(await tmp.store.getDailyCheckin('u1', '2026-08-28'), {
++ date: '2026-08-28', ok: true, already: false, code: 0, message: 'OK', at: 3000, verified: true,
++ });
++ assert.deepEqual(await tmp.store.listDailyCheckins(['u1', 'u2'], '2026-08-28'), {
++ u1: { date: '2026-08-28', ok: true, already: false, code: 0, message: 'OK', at: 3000, verified: true },
++ });
++ assert.equal(await tmp.store.getDailyCheckin('u1', '2026-08-27'), null);
++});
diff --cc test/ui-port.test.js
index 0000000,0000000..29b728b
new file mode 100644
--- /dev/null
+++ b/test/ui-port.test.js
@@@ -1,0 -1,0 +1,23 @@@
++'use strict';
++
++const test = require('node:test');
++const assert = require('node:assert/strict');
++const { profileUiPortCandidates, selectPersistedUiPort } = require('../scripts/ui-port.js');
++
++test('UI fallback ports stay disjoint across profiles and avoid the Windows dynamic range', () => {
++ const profiles = ['workbuddy-cn', 'workbuddy-ai', 'codebuddy-cn', 'codebuddy-intl'];
++ const lists = profiles.map((profile) => profileUiPortCandidates(profile));
++ for (let i = 0; i < lists.length; i++) {
++ assert.equal(new Set(lists[i]).size, lists[i].length);
++ assert.equal(lists[i].slice(1).every((port) => port < 46000), true);
++ for (let j = i + 1; j < lists.length; j++) {
++ assert.deepEqual(lists[i].filter((port) => lists[j].includes(port)), []);
++ }
++ }
++});
++
++test('only a current-profile UI port can be restored from persistent state', () => {
++ assert.equal(selectPersistedUiPort('workbuddy-cn', { profileId: 'workbuddy-cn', port: 17832 }), 17832);
++ assert.equal(selectPersistedUiPort('workbuddy-cn', { profileId: 'workbuddy-ai', port: 17833 }), null);
++ assert.equal(selectPersistedUiPort('workbuddy-cn', { profileId: 'workbuddy-cn', port: 17833 }), null);
++});
diff --cc test/update-layout.test.js
index 667ef5a,b729f29..a3bab8a
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@@ -285,7 -285,7 +285,8 @@@ test('Windows launcher rejects a persis
test('explicit daemon UI ports never fall through into another profile port', () => {
const daemon = read('daemon.js');
assert.match(daemon, /const ALLOW_UI_PORT_FALLBACK = !process\.env\.WBSWITCH_PORT/);
-- assert.match(daemon, /e\.code === 'EADDRINUSE' && ALLOW_UI_PORT_FALLBACK && attempt < 7/);
++ assert.match(daemon, /profileUiPortCandidates\(PROFILE\.id/);
++ assert.match(daemon, /e\.code === 'EADDRINUSE' && attempt \+ 1 < ports\.length/);
});
test('Windows launcher does not report success when manual injection is not mounted', () => {
@@@ -383,16 -383,16 +384,10 @@@ test('release scripts synchronize daemo
test('daemon settings writes tolerate transient Windows file locks', () => {
const daemon = read('daemon.js');
-- const helperStart = daemon.indexOf('function replaceFileWithRetry(');
-- const helperEnd = daemon.indexOf('\n}\n\nfunction writeWorkbuddySettings', helperStart);
-- assert.ok(helperStart >= 0 && helperEnd > helperStart, 'atomic replacement helper must exist');
-- const helper = daemon.slice(helperStart, helperEnd);
-- assert.match(helper, /\.wbs-tmp-\$\{process\.pid\}-\$\{Date\.now\(\)\}-\$\{crypto\.randomBytes\(/);
-- assert.match(helper, /process\.platform === 'win32' \? 80 : 1/);
-- assert.match(helper, /\['EPERM', 'EACCES', 'EBUSY'\]/);
-- assert.match(helper, /sleepSync\(Math\.min\(250, 50 \+ attempt \* 10\)\)/);
-- assert.match(helper, /chmodSync\(file, 0o666\)/);
-- assert.match(helper, /unlinkSync\(tmp\)/);
++ const helper = fs.readFileSync(path.join(repoRoot, 'scripts', 'atomic-file-write.js'), 'utf8');
++ assert.match(helper, /UNKNOWN/);
++ assert.match(helper, /writeFileSync/);
++ assert.match(helper, /renameSync/);
assert.doesNotMatch(helper, /unlinkSync\(file\)|rmSync\(file\)/);
const settingsStart = daemon.indexOf('function writeWorkbuddySettings(');
@@@ -479,11 -479,9 +474,20 @@@ test('Windows launcher searches app-dat
assert.match(daemon, /Get-ChildItem[\s\S]*-Recurse/);
});
--test('Windows release package includes the troubleshooting prompt as UTF-8', () => {
++test('Windows launcher selects the Node runtime from an actual daemon or watchdog', () => {
++ const launcher = read('win-launcher.js');
++ const findNode = launcher.slice(launcher.indexOf('function findNode()'), launcher.indexOf('// ---------- 定位 WorkBuddy.exe'));
++ assert.match(findNode, /uniqueNodeProcess\(candidate, DAEMON_SCRIPT\)/);
++ assert.match(findNode, /uniqueNodeProcess\(candidate, WATCHDOG_SCRIPT\)/);
++ assert.match(findNode, /if \(candidates\.length\) return candidates\[0\]/);
++ assert.doesNotMatch(findNode, /hasExistingWatchdogState/);
++});
++
++test('Windows release package excludes the troubleshooting prompt', () => {
const build = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-win-zip.sh'), 'utf8');
- assert.match(build, /安装失败自主解决提示词\.txt/);
+ const installer = fs.readFileSync(path.join(repoRoot, 'scripts', 'win', 'workdaddy.iss'), 'utf8');
- assert.match(build, /安装失败自主解决提示词\.txt/);
- assert.match(installer, /Source: "\{#StageRoot\}\\安装失败自主解决提示词\.txt"/);
++ assert.doesNotMatch(build, /cp\s+.*安装失败自主解决提示词/);
++ assert.doesNotMatch(installer, /Source:.*安装失败自主解决提示词/);
assert.match(build, /Python zipfile/);
assert.match(build, /ZIP_DEFLATED/);
});
@@@ -628,6 -619,6 +632,14 @@@ test('daemon lock falls back when the d
assert.match(daemon, /releaseDaemonLock[\s\S]*daemonLockPath/);
});
++test('Windows daemon lock validates the owner process instead of trusting a reused PID', () => {
++ const daemon = read('daemon.js');
++ const lockBlock = daemon.slice(daemon.indexOf('function isCurrentWindowsDaemonProcess'), daemon.indexOf('function acquireDaemonLock'));
++ assert.match(lockBlock, /Get-CimInstance Win32_Process -Filter/);
++ assert.match(lockBlock, /filterVerifiedNodeProcesses\(item\.ExecutablePath, __filename/);
++ assert.match(daemon, /if \(IS_WIN\) alive = isCurrentWindowsDaemonProcess\(ownerPid\)/);
++});
++
test('session ranges use last-modified time and preserve standard WorkBuddy workspaces', () => {
const daemon = read('daemon.js');
const inject = read('inject.js');
@@@ -648,14 -639,14 +660,14 @@@ test('account cards keep the compact th
const script = read('inject.js');
assert.match(script, /wbs-name-group/);
assert.match(script, /wbs-secondary-row/);
-- assert.match(script, /剩余积分/);
++ assert.match(script, /剩余<\/span>/);
assert.match(script, /今日已签到/);
// 登录有效期展示:国际版也将 token 有效截止时间展示为「有效期至」而非歧义的「登录过期于」
assert.match(script, /有效期至/);
assert.doesNotMatch(script, /登录过期于/);
assert.match(script, /var isUinMode = !a\.phone;/);
assert.match(script, /var idLbl = a\.phone \? '手机' : \(a\.uin \? 'UIN' : '账号'\)/);
-- assert.match(script, /\.wbs-phone-cell\.wbs-uin-cell\{gap:8px\}/);
++ assert.match(script, /\.wbs-phone-cell\.wbs-uin-cell\{gap:4px\}/);
// 国际版:签到标签不展示;暂存按钮内联进操作栏按钮组第一位(AI 端无 voice-mic-wrap)
assert.match(script, /if \(PROFILE_ID === 'workbuddy-ai'\) return '';/);
assert.match(script, /function findAiToolbar\(\)/);
@@@ -686,12 -677,12 +698,30 @@@
assert.match(script, /\.wbs-checkin-tag\.ok\{background:#edf9ef/);
assert.match(script, /html\.cb-dark \.wbs-checkin-tag\.ok\{/);
assert.match(script, /今日已签到✓/);
++ assert.match(script, /function accountStatusTagsHtml\(a\)/);
++ assert.match(script, /function checkinBadgeHtml\(a\)/);
++ assert.match(script, /badge \+ checkinBadge/);
++ assert.match(script, /if \(!usage \|\| usage\.synced !== true\) return '';/);
++ assert.match(script, /wbs-usage-tag/);
++ assert.match(script, /wbs-usage-tag[^\n]+今日已使用[^\n]+CREDIT_ICON/);
++ assert.match(script, /wbs-usage-tag[^\n]+<b>\x27 \+ fmtCredits\(used\) \+ \x27<\/b>/);
++ assert.match(script, /\.wbs-phone-cell \.wbs-lbl,\.wbs-credit-left \.wbs-lbl\{width:28px\}/);
++ assert.match(script, /if \(!isFinite\(used\) \|\| used <= 0\) return '';/);
++ assert.match(script, /wbs-credit-left/);
++ assert.doesNotMatch(script, /今日已用/);
assert.doesNotMatch(script, /wbs-token-expired/);
assert.doesNotMatch(script, /按到期时间排序/);
assert.doesNotMatch(script, /个额度/);
assert.doesNotMatch(script, /wbs-checkin-cell/);
});
++test('account cards place the current logged-in account first', () => {
++ const script = read('inject.js');
++ assert.match(script, /state\.current = data\.current;\s*state\.accounts = \(data\.accounts \|\| \[\]\)\.slice\(\);/);
++ assert.match(script, /state\.accounts\.sort\(function \(left, right\) \{[\s\S]*left\.uid === state\.current\.uid[\s\S]*right\.uid === state\.current\.uid[\s\S]*return leftIsCurrent \? -1 : 1;[\s\S]*\}\);/);
++ assert.match(script, /function sortAccountsByCreditExpiry\(\) \{[\s\S]*isCurrent:[\s\S]*if \(a\.isCurrent !== b\.isCurrent\) return a\.isCurrent \? -1 : 1;[\s\S]*if \(a\.expiresAt !== b\.expiresAt\)/);
++});
++
test('quick-phrase layering does not reposition WorkBuddy native chat toolbar', () => {
const script = read('inject.js');
assert.match(script, /\.wbs-explore-inline\.wbs-stash-inline-inline\{position:relative;z-index:99999\}/);
@@@ -729,26 -720,26 +759,19 @@@ test('robot button decorations remain v
assert.match(script, /\.wbs-fab \.click \.button \.speak~\.speak\{display:none\}/);
});
--test('home composer keeps the robot button at the WorkBuddy bottom-right', () => {
-- const script = read('inject.js');
-- assert.match(script, /\.wb-home-page \[class\*="_topRightSlotStandalone_"\] > div:nth-child\(1\) > div:nth-child\(3\)/);
-- assert.match(script, /fab\.style\.right = '22px';\s*fab\.style\.bottom = '22px';/);
--});
--
--test('WorkBuddy AI welcome composer keeps the robot at the window bottom-right', () => {
-- const script = read('inject.js');
-- assert.match(script, /PROFILE_ID === 'workbuddy-ai'/);
-- assert.match(script, /_topRightSlotStandalone_\"\] > div:nth-child\(1\) > div:nth-child\(2\)/);
-- assert.match(script, /aiHomeComposerCorner/);
--});
--
--test('WorkBuddy AI chat composer anchors the robot when the queue is absent', () => {
++test('robot button defaults to the window bottom-right and snaps right after free dragging', () => {
const script = read('inject.js');
-- assert.match(script, /if \(!target && WBS_PROFILE_IS_AI\)/);
-- assert.match(script, /\.conversation-input-area \.conversation-input \.cr-input-box \.cr-input-container/);
-- assert.match(script, /\.conversation-input-area \.cr-input-container/);
-- assert.match(script, /var air = aiInput\.getBoundingClientRect\(\)/);
-- assert.match(script, /if \(!target\) \{\s*var ma = document\.querySelector\('\[class\*="_input-area-container_"\]/);
++ assert.match(script, /FAB_POSITION_KEY = 'wbs-fab-bottom-' \+ PROFILE_ID/);
++ assert.match(script, /setPointerCapture\(e\.pointerId\)/);
++ assert.match(script, /FAB_DRAG_THRESHOLD = 6/);
++ assert.match(script, /fabDrag\.startRight - deltaX/);
++ assert.match(script, /fabDrag\.startBottom - deltaY/);
++ assert.match(script, /applyFabPosition\(fab, FAB_EDGE_GAP, bottom\)/);
++ assert.match(script, /localStorage\.setItem\(FAB_POSITION_KEY/);
++ assert.match(script, /touchAction = 'none'/);
++ assert.match(script, /is-snapping/);
++ assert.match(script, /cubic-bezier\(\.22,1\.35,\.36,1\)/);
++ assert.doesNotMatch(script, /homeComposerCorner|aiHomeComposerCorner|cb-message-queue\.cb-expand/);
});
test('installers disable login auto-start and clean prior registrations', () => {
@@@ -1027,7 -1018,7 +1050,8 @@@ test('session summary counts effective
assert.match(inject, /签到请求完成后再查询积分/);
assert.match(inject, /fetchCreditsForAccounts\(\);/);
assert.match(read('lib.js'), /function checkinDisplayValue\(record, today, pending\)/);
-- assert.match(daemon, /checkin: checkinDisplayValue\(c, today, checkinPending\)/);
++ assert.match(daemon, /CREDIT_USAGE_STORE\.listDailyCheckins/);
++ assert.match(daemon, /checkin: checkinDisplayValue\(checked, today, checkinPending\)/);
assert.doesNotMatch(inject, /id="wbs-model-refresh"/);
assert.match(inject, /wbs-model-group-title/);
assert.match(inject, /delete-official/);
diff --cc test/verify-win-exit.test.js
index 7c55527,267acd2..21f0d6b
--- a/test/verify-win-exit.test.js
+++ b/test/verify-win-exit.test.js
@@@ -49,7 -49,7 +49,7 @@@ test('Windows verifier reports missing
assert.ifError(result.error);
assert.equal(result.status, 1, result.stdout + result.stderr);
} finally {
-- fs.rmSync(dir, { recursive: true, force: true });
++ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 250 });
}
});
@@@ -79,7 -79,7 +79,7 @@@ test('Windows verifier returns success
assert.ifError(result.error);
assert.equal(result.status, 0, result.stdout + result.stderr);
} finally {
-- fs.rmSync(dir, { recursive: true, force: true });
++ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 250 });
}
});
@@@ -112,6 -112,6 +112,6 @@@ test('Windows verifier restores the cal
assert.match(result.stdout, /VERIFY_STATUS=1/);
assert.match(result.stdout, /AFTER_CP=\s*437/);
} finally {
-- fs.rmSync(dir, { recursive: true, force: true });
++ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 250 });
}
});
diff --cc test/windows-launcher-boundary-repair.test.js
index ff51353,18243a2..92d663b
--- a/test/windows-launcher-boundary-repair.test.js
+++ b/test/windows-launcher-boundary-repair.test.js
@@@ -119,10 -118,10 +119,13 @@@ test('launcher enumerates exact lifecyc
assert.match(launcherSource, /uniqueNodeProcess\(nodeBin, DAEMON_SCRIPT\)/);
assert.match(launcherSource, /queryNodeProcesses\(nodeBin, null, path\.basename\(expectedScript\)\)/);
assert.match(launcherSource, /watchdog\.pid 已从陈旧 PID=/);
- assert.match(launcherSource, /普通权限 launcher 复用现有服务/);
- assert.match(launcherSource, /exactDaemonStatus\(nodeBin, status, true\)/);
+ assert.match(launcherSource, /普通权限 launcher 复用已验证的 elevated 服务/);
+ assert.match(launcherSource, /assertAuthenticatedDaemonCapability/);
assert.match(launcherSource, /assertSameProcessIdentity/);
assert.match(launcherSource, /requireCurrentOwner:\s*true/);
++ assert.match(launcherSource, /taskkill 非零但目标 PID 已消失,按竞态成功处理/);
++ assert.match(launcherSource, /verifyGone && await verifyGone\(\)/);
++ assert.match(launcherSource, /queryNodeProcesses\(nodeBin, \[pid\]\)\.length === 0/);
for (const source of [launcherSource, daemonSource, watchdogSource]) {
assert.match(source, /buildNativeProcessQuery/);
assert.match(source, /windows-process-boundary\.ps1/);
@@@ -130,47 -129,6 +133,79 @@@
}
});
++test('installer boundary releases the exact profile launcher and waits for its runtime lock', () => {
++ assert.match(powershellSource, /Get-VerifiedNodeProcessesForScript -ExpectedScript \$expectedLauncherScript/);
++ assert.match(powershellSource, /foreach \(\$launcher in \$launchers\) \{ Stop-VerifiedProcess -Process \$launcher \}/);
++ assert.match(powershellSource, /function Wait-VerifiedFileUnlocked/);
++ assert.match(powershellSource, /Wait-VerifiedFileUnlocked -Path \(Join-Path \$scriptsDir 'runtime\\node\\node\.exe'\)/);
++ assert.match(powershellSource, /function Get-VerifiedNodeProcessesForScript/);
++});
++
+test('elevated launcher relaunches through the desktop shell before starting lifecycle processes', () => {
+ assert.match(launcherSource, /windows-relaunch-standard\.ps1/);
+ assert.match(launcherSource, /--desktop-shell-relaunch/);
+ assert.ok(
+ launcherSource.indexOf('relaunchWithDesktopShell') < launcherSource.indexOf('await ensureDaemon(nodeBin)'),
+ 'privilege normalization must happen before the daemon lifecycle starts'
+ );
- assert.match(standardRelaunchSource, /Shell\.Application/);
++ assert.match(standardRelaunchSource, /\.Windows\(\)/);
++ assert.match(standardRelaunchSource, /FindWindowSW/);
++ assert.match(standardRelaunchSource, /\.Document\.Application/);
+ assert.match(standardRelaunchSource, /ShellExecute/);
+ assert.doesNotMatch(standardRelaunchSource, /runas/i);
++ assert.match(launcherSource, /仍返回 elevated token[\s\S]*showWindowsMessageBox[\s\S]*拒绝启动管理员权限/);
++});
++
++test('hidden Windows launch failures remain visible to the desktop user', () => {
++ const hiddenSource = hiddenLauncherSource;
++ const catchSource = launcherSource.slice(launcherSource.indexOf('})().catch((e) =>'));
++ assert.match(catchSource, /showWindowsMessageBox/);
++ assert.match(hiddenSource, /If status <> 0 And status <> 4 Then/);
++ assert.match(hiddenSource, /MsgBox/);
++});
++
++test('Windows launcher derives and propagates its real installation root', () => {
++ assert.match(launcherSource, /const WORKDADDY_APP_DIR = path\.resolve\(SCRIPTS_DIR, '\.\.'\)/);
++ assert.match(launcherSource, /process\.env\.WBSWITCH_APP_DIR = WORKDADDY_APP_DIR/);
++ assert.match(daemonSource, /process\.env\.WBSWITCH_APP_DIR \|\| path\.resolve\(__dirname, '\.\.'\)/);
++});
++
++test('CIM process disappearance is treated as an empty snapshot, not a launcher failure', () => {
++ assert.match(boundarySource, /allowTransientNotFound/);
++ assert.match(boundarySource, /0x80041002/);
++ assert.match(launcherSource, /allowTransientNotFound:\s*true/);
++ assert.match(watchdogSource, /allowTransientNotFound:\s*true/);
+});
+
+test('authenticated daemon capability binds token-only status to profile, data directory, and listener PID', () => {
+ const status = {
+ ok: true,
+ pid: 716,
+ version: '1.1.1',
+ buildId: 'old-build',
+ privilege: 'elevated',
+ dataDir: 'C:\\Users\\alice\\AppData\\Roaming\\WorkDaddy',
+ profile: { id: 'workbuddy-cn' },
+ };
+ const input = {
+ status,
+ expectedProfileId: 'workbuddy-cn',
+ expectedVersion: '1.1.1',
+ expectedDataDir: status.dataDir,
+ listenerPids: [716],
+ };
+ assert.equal(boundary.assertAuthenticatedDaemonCapability(input).pid, 716);
+ assert.throws(() => boundary.assertAuthenticatedDaemonCapability({ ...input, listenerPids: [717] }), /listener|PID/i);
+ assert.throws(() => boundary.assertAuthenticatedDaemonCapability({ ...input, status: { ...status, dataDir: 'C:\\Other' } }), /data|目录/i);
+ assert.throws(() => boundary.assertAuthenticatedDaemonCapability({ ...input, status: { ...status, profile: { id: 'workbuddy-ai' } } }), /profile/i);
+ assert.throws(() => boundary.assertAuthenticatedDaemonCapability({ ...input, status: { ...status, version: '1.1.0' } }), /version/i);
+ assert.equal(boundary.assertAuthenticatedDaemonCapability({
+ ...input,
+ status: { ...status, version: '1.1.0' },
+ allowVersionMismatch: true,
+ }).version, '1.1.0');
+});
+
test('launcher retries while daemon listener is ready before status', () => {
assert.match(launcherSource, /if \(!status \|\| listeners\.length !== 1\) continue/);
assert.doesNotMatch(launcherSource, /if \(!status && listeners\.length === 0\) continue/);
@@@ -225,7 -183,7 +260,7 @@@ test('daemon termination authorization
);
});
--test('launcher never adopts untracked watchdogs or kills unbound daemon entries', () => {
++test('launcher repairs a missing PID file only for one exact watchdog and never kills unbound daemon entries', () => {
const stateSource = launcherSource.slice(
launcherSource.indexOf('function watchdogState'),
launcherSource.indexOf('function validateDaemonProcess')
@@@ -238,9 -196,9 +273,11 @@@
launcherSource.indexOf('async function ensureDaemon'),
launcherSource.indexOf('// ---------- 2/3.')
);
-- assert.match(stateSource, /!pid[\s\S]*kind:\s*'untracked'/);
++ assert.match(stateSource, /!pid[\s\S]*fs\.writeFileSync\(WATCHDOG_PID_FILE, String\(exact\.ProcessId\)/);
++ assert.match(stateSource, /通过精确身份恢复缺失的 watchdog\.pid/);
assert.match(stopSource, /watchdog\.kind === 'untracked'[\s\S]*throw new Error/);
assert.match(ensureSource, /watchdog\.kind === 'untracked'[\s\S]*throw new Error/);
++ assert.match(ensureSource, /if \(watchdog\.kind === 'verified'\)/);
assert.match(stopSource, /authorizeDaemonTermination/);
assert.doesNotMatch(stopSource, /remainingDaemon[\s\S]*killVerifiedNodeProcess\(remainingDaemon/);
const untrackedGuard = stopSource.indexOf("watchdog.kind === 'untracked'");
@@@ -273,6 -231,6 +310,19 @@@ test('Windows launcher reconciles a reu
assert.match(stateSource, /watchdog\.pid 在修复前发生变化/);
});
++test('Windows launcher waits for a watchdog PID file startup race before rejecting it', () => {
++ assert.match(launcherSource, /async function watchdogState\(nodeBin\)/);
++ assert.match(launcherSource, /for \(let attempt = 0; attempt < 10 && !pid; attempt \+= 1\)/);
++ assert.match(launcherSource, /await sleep\(250\)/);
++ assert.match(launcherSource, /if \(!pid && exact\)[\s\S]*通过精确身份恢复缺失的 watchdog\.pid/);
++});
++
++test('Windows launcher ignores WorkBuddy AI headless prewarm helpers during cold start', () => {
++ assert.match(launcherSource, /function isPrewarmProcess\(process\)/);
++ assert.match(launcherSource, /--prewarm/);
++ assert.match(launcherSource, /getWorkBuddyProcesses\(\)\.filter\(\(process\) => !isPrewarmProcess\(process\)\)/);
++});
++
test('Windows process queries are scoped to the selected Node runtime', () => {
assert.match(launcherSource, /ExecutablePath -ieq/);
assert.match(watchdogSource, /ExecutablePath -ieq/);
@@@ -293,8 -251,8 +343,8 @@@ test('verified launcher lock cleanup ha
assert.match(hiddenLauncherSource, /shell\.Run\(command, 0, True\)/);
});
--test('desktop launcher is silent and diagnostics tolerate a transient CIM failure', () => {
-- assert.doesNotMatch(hiddenLauncherSource, /MsgBox/i);
++test('desktop launcher only reports failures not already shown by Node', () => {
++ assert.match(hiddenLauncherSource, /If status <> 0 And status <> 4 Then/);
assert.match(hiddenLauncherSource, /WScript\.Quit status/);
assert.match(launcherSource, /function processDiagnostics\(binary = null\) \{[\s\S]*try \{[\s\S]*catch \(error\)[\s\S]*return \[\];[\s\S]*\}/);
assert.match(launcherSource, /进程诊断暂不可用/);
@@@ -308,17 -266,13 +358,17 @@@ test('Windows installer uses the bundle
assert.match(chineseLanguageSource, /LanguageName=简体中文/);
});
--test('Windows cold-start guards an already running WorkBuddy and sends a native notification', () => {
++test('Windows cold-start restarts the verified current-profile WorkBuddy and sends a native notification', () => {
assert.match(launcherSource, /function requireWorkBuddyClosedBeforeLaunch\(\)/);
assert.match(launcherSource, /请先完全退出 WorkBuddy/);
assert.match(launcherSource, /function showWindowsNotification\(title, message\)/);
assert.match(launcherSource, /NotifyIcon/);
assert.match(launcherSource, /spawnSync\(powershell/);
-- assert.match(launcherSource, /if \(requireWorkBuddyClosedBeforeLaunch\(\)\) process\.exit\(0\)/);
+ assert.ok(
- launcherSource.indexOf('if (await isWorkBuddyCdp())') < launcherSource.indexOf('if (requireWorkBuddyClosedBeforeLaunch())'),
- 'an already-debuggable WorkBuddy must be injected before the cold-start guard'
++ launcherSource.indexOf('const wb = findWorkBuddy()') < launcherSource.indexOf('await quitWorkBuddy(wb)'),
++ 'cold start must resolve and verify the target before restarting it'
+ );
++ assert.doesNotMatch(launcherSource, /if \(requireWorkBuddyClosedBeforeLaunch\(\)\) process\.exit\(0\)/);
assert.match(launcherSource, /showWindowsNotification\('WorkBuddy', '正在打开 WorkBuddy,请稍等…'\)/);
});
diff --cc test/windows-powershell-boundary.test.js
index 1a024eb,1a024eb..d8ca1a3
--- a/test/windows-powershell-boundary.test.js
+++ b/test/windows-powershell-boundary.test.js
@@@ -68,6 -68,6 +68,10 @@@ test('PowerShell source validates owner
const helper = fs.readFileSync(helperPath, 'utf8');
assert.doesNotMatch(helper, /Add-Type|csc\.exe/i);
assert.match(helper, /Invoke-CimMethod[^\r\n]*GetOwner/i);
++ assert.match(helper, /function Test-CimProcessDisappearedError/);
++ assert.match(helper, /0x80041002/);
++ assert.match(helper, /function ConvertTo-WorkDaddyProcessRecordIfPresent/);
++ assert.match(helper, /\$record = ConvertTo-WorkDaddyProcessRecord[\s\S]*\$null -eq \$record/);
assert.match(helper, /Test-ExactCmdLauncherCommandLine/);
assert.match(helper, /Get-UniqueListeningProcessId/);
assert.match(helper, /function Get-UniqueNodeProcessForScript/);
diff --cc test/windows-privilege-boundary.test.js
index 22cdf29,cd6cbee..20176df
--- a/test/windows-privilege-boundary.test.js
+++ b/test/windows-privilege-boundary.test.js
@@@ -320,7 -318,7 +320,7 @@@ test('watchdog stop terminates only rev
}
});
--test('watchdog startup refuses an exact untracked instance when the PID file is absent', () => {
++test('watchdog startup repairs a missing PID file for one exact instance', () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-watchdog-untracked-'));
const preload = path.join(tempDir, 'preload.js');
const untrackedPid = 424203;
@@@ -350,9 -348,9 +350,9 @@@
env: { ...process.env, WBSWITCH_DATA_DIR: tempDir },
timeout: 10000,
});
-- assert.notEqual(result.status, 0);
-- assert.match(result.stderr, /没有 PID 文件|untracked|重复实例/i);
-- assert.equal(fs.existsSync(path.join(tempDir, 'watchdog.pid')), false);
++ assert.equal(result.status, 0);
++ assert.match(result.stdout, /恢复缺失的 watchdog\.pid|本实例退出/i);
++ assert.equal(fs.readFileSync(path.join(tempDir, 'watchdog.pid'), 'utf8'), String(untrackedPid));
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
@@@ -399,7 -397,7 +399,7 @@@ test('logout and restart paths refuse u
test('Windows self-check includes the shared boundary and old admin comments are removed', () => {
const verify = fs.readFileSync(path.join(scriptsDir, 'verify-win.cmd'), 'utf8');
assert.match(verify, /win-launcher\.js windows-process-boundary\.js/);
-- assert.match(verify, /安装失败自主解决提示词\.txt/);
++ assert.doesNotMatch(verify, /安装失败自主解决提示词\.txt/);
assert.doesNotMatch(verify, /win-inject-helper\.js/);
assert.doesNotMatch(hiddenLauncherSource + cmdLauncherSource, /shortcut as administrator|管理员启动/i);
});
diff --cc test/windows-release-script.test.js
index 2e349eb,2f5d6a3..f26af1d
--- a/test/windows-release-script.test.js
+++ b/test/windows-release-script.test.js
@@@ -7,12 -7,10 +7,16 @@@ const test = require('node:test')
const scriptPath = path.join(__dirname, '..', 'scripts', 'build-win-release.ps1');
const launcherPath = path.join(__dirname, '..', 'scripts', 'build-win-release.cmd');
-const source = fs.readFileSync(scriptPath, 'utf8');
++const hiddenLauncherPath = path.join(__dirname, '..', 'scripts', 'launcher-hidden.vbs');
++const standardRelaunchPath = path.join(__dirname, '..', 'scripts', 'windows-relaunch-standard.ps1');
+const scriptBytes = fs.readFileSync(scriptPath);
+const source = scriptBytes.toString('utf8');
const launcher = fs.readFileSync(launcherPath, 'utf8');
++const hiddenLauncherBytes = fs.readFileSync(hiddenLauncherPath);
++const standardRelaunchBytes = fs.readFileSync(standardRelaunchPath);
test('Windows release script interactively builds both profiles for one version', () => {
+ assert.deepEqual([...scriptBytes.subarray(0, 3)], [0xef, 0xbb, 0xbf], 'Windows PowerShell 5.1 needs a UTF-8 BOM for Chinese prompts');
assert.match(source, /Read-Host\s+"[^"]*版本号/);
assert.match(source, /\$Version -notmatch '\^\\d\+\\\.\\d\+\\\.\\d\+\$'/);
assert.match(source, /foreach \(\$profile in @\('workbuddy-cn', 'workbuddy-ai'\)\)/);
@@@ -24,3 -21,3 +28,36 @@@
assert.match(launcher, /build-win-release\.ps1/);
assert.match(launcher, /ExecutionPolicy Bypass/);
});
++
++test('Windows hidden launcher stays parseable under WSH code pages', () => {
++ assert.equal(hiddenLauncherBytes.some((byte) => byte >= 0x80), false);
++});
++
++test('Windows standard relaunch script is UTF-8 with BOM for Windows PowerShell 5.1', () => {
++ assert.deepEqual([...standardRelaunchBytes.subarray(0, 3)], [0xef, 0xbb, 0xbf]);
++});
++
++test('Windows standard relaunch falls back to the Explorer Shell object by executable path', () => {
++ const relaunch = standardRelaunchBytes.toString('utf8');
++ assert.match(relaunch, /shellWindows\.Windows\(\)/);
++ assert.match(relaunch, /GetFileName\(\[string\]\$_.FullName\).*explorer\.exe/);
++ assert.doesNotMatch(relaunch, /Get-Process\s+-Name\s+explorer/);
++});
++
++test('Windows watchdog only pauses for a live or recent update marker', () => {
++ const watchdog = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'watchdog.js'), 'utf8');
++ assert.match(watchdog, /updateProcessIsActive/);
++ assert.match(watchdog, /apply-update\\\\\.ps1/);
++ assert.match(watchdog, /gracePeriodMs\s*=\s*10 \* 60 \* 1000/);
++ assert.match(watchdog, /unlinkSync\(UPDATE_PENDING_FILE\)/);
++ assert.match(watchdog, /if \(updatePendingIsActive\(\)\)/);
++});
++
++test('Windows installer excludes the repair prompt from all release stages', () => {
++ const zipBuild = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'build-win-zip.sh'), 'utf8');
++ const installerBuild = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'build-win-installer.ps1'), 'utf8');
++ const iss = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'win', 'workdaddy.iss'), 'utf8');
++ assert.doesNotMatch(zipBuild, /cp\s+.*安装失败自主解决提示词/);
++ assert.doesNotMatch(installerBuild, /Test-Path[\s\S]{0,160}安装失败自主解决提示词/);
++ assert.doesNotMatch(iss, /Source:.*安装失败自主解决提示词/);
++});