Skip to content

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

fix: prepare 1.2.21 session sync and UI improvements

[email protected]9e2fa0a8b88a
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index be4ab50..205f5bc 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -65,7 +65,7 @@ chmod 644 "$APP/Contents/Resources/AppIcon.icns"
echo "==> 应用图标已同步(背景 #e1e1e1)"
# 2) 覆盖运行时代码和主题配置,保留 launcher/Info.plist/壁纸/node_modules/theme-audit.js。
-for f in daemon.js account-identity.js session-copy-error.js persona.js markdown-preview.js renderer-api-bridge.js codebuddy-native.js codebuddy-native-recovery.js codebuddy-session-store.js codebuddy-files.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-account-sync.js official-automation-sync.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js wallpaper-rotation.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js client-launch-settings.js workbuddy-launch-env.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
+for f in daemon.js account-identity.js session-copy-error.js persona.js markdown-preview.js renderer-api-bridge.js codebuddy-native.js codebuddy-native-recovery.js codebuddy-session-store.js codebuddy-files.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-account-sync.js official-automation-sync.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js wallpaper-rotation.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js client-launch-settings.js client-temp.js workbuddy-launch-env.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"
done
# Theme tokens are source code too; the reusable shell may contain older colors.
diff --git a/scripts/cdp-targets.js b/scripts/cdp-targets.js
index 3f1c5ad..a0e5f13 100644
--- a/scripts/cdp-targets.js
+++ b/scripts/cdp-targets.js
@@ -30,10 +30,9 @@ const APP_CBINTL = /\/CodeBuddy\.app(?:\/|$)/i;
const APP_AI_LINUX = /\/workbuddy-ai\//i;
const APP_CN_LINUX = /\/opt\/WorkBuddy\//i;
// Windows 没有 .app 包,renderer URL 直接落在安装目录的 resources/app.asar 下。
-// 目录可能位于任意盘符,但官方 CN/AI 目录名仍可作为 profile 强信号。
+// AI 安装目录名可区分;通用 WorkBuddy 目录可能被 CN/AI 共用,不作强信号。
const APP_AI_WIN = /\/WorkBuddy(?:%20| )?AI\/resources\/app\.asar(?:\/|$)/i;
const APP_AI_WIN_COMPACT = /\/WorkBuddyAI\/resources\/app\.asar(?:\/|$)/i;
-const APP_CN_WIN = /\/WorkBuddy\/resources\/app\.asar(?:\/|$)/i;
const DOMAIN_WB_AI = /https?:\/\/(?:[^/]+\.)?workbuddy\.ai(?:\/|$)/i;
const DOMAIN_WB_CN = /https?:\/\/(?:[^/]+\.)?workbuddy\.cn(?:\/|$)/i;
const DOMAIN_CB_CN = /https?:\/\/(?:[^/]+\.)?codebuddy\.cn(?:\/|$)/i;
@@ -52,7 +51,7 @@ function classifyTarget(url, title, description) {
if (APP_AI_WIN.test(u) || APP_AI_WIN_COMPACT.test(u)) return 'workbuddy-ai';
if (APP_CN.test(u)) return 'workbuddy-cn';
if (APP_CN_LINUX.test(u)) return 'workbuddy-cn';
- if (APP_CN_WIN.test(u)) return 'workbuddy-cn';
+ // The generic Windows WorkBuddy install path may be shared by CN and AI.
if (APP_CBCN.test(u)) return 'codebuddy-cn';
if (APP_CBINTL.test(u)) return 'codebuddy-intl';
if (DOMAIN_WB_AI.test(u)) return 'workbuddy-ai';
@@ -113,14 +112,13 @@ function isTargetForProfile(target, profile) {
}
}
- // Windows 官方安装目录的 app.asar 路径是比标题更可靠的归属证据,必须先于
- // 标题兜底判断;自定义目标已先按所选安装目录判断。
+ // Windows AI 专属目录是可靠归属证据,必须先于标题兜底判断;通用 WorkBuddy
+ // 目录可能被 CN / AI 共用,由下方已绑定的 profile 判断。自定义目标先按所选目录判断。
const cls = classifyTarget(url, title, desc);
const normalizedUrl = normalizeTargetUrl(url);
const windowsOfficialPath = /^file:\/\/\/[A-Za-z]:\//i.test(normalizedUrl) && (
APP_AI_WIN.test(normalizedUrl)
|| APP_AI_WIN_COMPACT.test(normalizeTargetUrl(url))
- || APP_CN_WIN.test(normalizedUrl)
);
if (windowsOfficialPath) return cls === profile.id;
diff --git a/scripts/client-temp.js b/scripts/client-temp.js
new file mode 100644
index 0000000..a1c2efb
--- /dev/null
+++ b/scripts/client-temp.js
@@ -0,0 +1,179 @@
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const { replaceFileWithRetry } = require('./atomic-file-write');
+const RETENTION_DAYS = 7;
+const MAX_ENTRIES = 30000;
+const SCAN_TIMEOUT_MS = 10000;
+
+function supported(profile, platform) {
+ return platform === 'win32' && !profile.customTarget && ['workbuddy-cn', 'workbuddy-ai'].includes(profile.id);
+}
+
+function paths(dataDir, profile) {
+ if (!path.isAbsolute(dataDir)) throw new Error('临时文件数据目录必须是绝对路径');
+ return {
+ parent: path.join(dataDir, 'client-tmp'),
+ root: path.join(dataDir, 'client-tmp', profile.id),
+ state: path.join(dataDir, `client-temp-cleanup-${profile.id}.json`),
+ lock: path.join(dataDir, `.client-temp-cleanup-${profile.id}.lock`),
+ };
+}
+
+function readState(file) {
+ try {
+ const stat = fs.lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 4096) throw Error();
+ const state = JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (!state || typeof state.pending !== 'boolean' || (state.pending &&
+ (!Number.isFinite(state.requestedAt) || state.requestedAt <= 0 || typeof state.id !== 'string'))) throw Error();
+ return state;
+ } catch (error) {
+ if (error.code === 'ENOENT') return { pending: false };
+ throw new Error('临时文件清理设置无法读取,请检查数据目录');
+ }
+}
+
+function saveState(file, state) {
+ readState(file); // Reject links and malformed settings instead of replacing them.
+ replaceFileWithRetry(file, JSON.stringify(state) + '\n', 0o600);
+}
+
+function checkCleanupLock(file) {
+ try {
+ const stat = fs.lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 40) throw Error('invalid');
+ const pid = Number(fs.readFileSync(file, 'utf8'));
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw Error('invalid');
+ try { process.kill(pid, 0); }
+ catch (error) {
+ if (error.code === 'ESRCH') { fs.unlinkSync(file); return; }
+ }
+ } catch (error) {
+ if (error.code === 'ENOENT') return;
+ }
+ throw new Error('临时文件清理已在进行或锁状态无法验证,请稍后启动');
+}
+
+async function assertRoot(locations) {
+ for (const file of [locations.parent, locations.root]) {
+ try {
+ const stat = await fs.promises.lstat(file);
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('临时文件目录不是普通目录,已停止清理');
+ } catch (error) {
+ if (error.code === 'ENOENT') return false;
+ throw error;
+ }
+ }
+ return true;
+}
+
+// No file contents or names leave this module. Never follow links or remove
+// updater caches: cached Setup.exe may be a pending official client update.
+async function scanEntry(file, cutoff, budget, depth = 0) {
+ if (++budget.count > MAX_ENTRIES || Date.now() > budget.deadline || depth > 64) throw new Error('临时文件统计未完成,请稍后重试');
+ const stat = await fs.promises.lstat(file);
+ let safe = !stat.isSymbolicLink() && !/^workbuddy-update(?:-|$)/i.test(path.basename(file));
+ let bytes = stat.isFile() ? stat.size : 0;
+ let old = stat.mtimeMs < cutoff;
+ const digest = crypto.createHash('sha256').update([stat.dev, stat.ino, stat.mode, stat.size, stat.mtimeMs, stat.ctimeMs].join(':'));
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
+ for (const name of (await fs.promises.readdir(file)).sort()) {
+ const child = await scanEntry(path.join(file, name), cutoff, budget, depth + 1);
+ bytes += child.bytes;
+ old = old && child.old;
+ safe = safe && child.safe;
+ digest.update(JSON.stringify([name, child.signature]));
+ }
+ } else if (!stat.isFile() || stat.nlink !== 1) safe = false;
+ return { bytes, old, safe, signature: digest.digest('hex') };
+}
+
+async function scan(locations, cutoff) {
+ const result = { bytes: 0, cleanableBytes: 0, incomplete: false, entries: [] };
+ if (!await assertRoot(locations)) return result;
+ const budget = { count: 0, deadline: Date.now() + SCAN_TIMEOUT_MS };
+ for (const name of await fs.promises.readdir(locations.root)) {
+ try {
+ const entry = await scanEntry(path.join(locations.root, name), cutoff, budget);
+ result.bytes += entry.bytes;
+ if (entry.safe && entry.old) {
+ result.cleanableBytes += entry.bytes;
+ result.entries.push({ name, ...entry });
+ }
+ } catch (_) { result.incomplete = true; }
+ if (budget.count > MAX_ENTRIES || Date.now() > budget.deadline) break;
+ }
+ return result;
+}
+
+async function inspectClientTemp(dataDir, profile, platform = process.platform) {
+ if (!supported(profile, platform)) return { supported: false };
+ const locations = paths(dataDir, profile);
+ const state = readState(locations.state);
+ const { entries, ...sizes } = await scan(locations, (state.pending ? state.requestedAt : Date.now()) - RETENTION_DAYS * 86400000);
+ return { supported: true, retentionDays: RETENTION_DAYS, pending: state.pending, lastResult: state.lastResult || null, ...sizes };
+}
+
+function requestClientTempCleanup(dataDir, profile, pending, platform = process.platform) {
+ if (!supported(profile, platform) || typeof pending !== 'boolean') throw new Error('仅 Windows WorkBuddy 支持布尔值清理请求');
+ const locations = paths(dataDir, profile);
+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
+ const old = readState(locations.state);
+ saveState(locations.state, { pending, id: crypto.randomUUID(), requestedAt: Date.now(), lastResult: old.lastResult || null });
+ return { supported: true, pending };
+}
+
+async function runPendingClientTempCleanup(dataDir, profile, { platform = process.platform, isStopped } = {}) {
+ if (!supported(profile, platform)) return { skipped: 'unsupported' };
+ const locations = paths(dataDir, profile);
+ // Even a cancelled request must not allow another launcher past an active cleanup.
+ checkCleanupLock(locations.lock);
+ let state;
+ try { state = readState(locations.state); } catch (_) { return { skipped: 'invalid-settings' }; }
+ if (!state.pending) return { skipped: 'not-requested' };
+ const stopped = async () => { try { return typeof isStopped === 'function' && await isStopped() === true; } catch (_) { return false; } };
+ if (!await stopped()) return { skipped: 'client-running-or-unknown' };
+ // Another launcher must not start the client while this cleanup owns the lock.
+ try { fs.writeFileSync(locations.lock, String(process.pid), { flag: 'wx', mode: 0o600 }); }
+ catch (error) {
+ if (error.code === 'EEXIST') throw new Error('临时文件清理已在进行,请稍后启动');
+ throw error;
+ }
+ const result = { removedBytes: 0, removedEntries: 0, skippedEntries: 0, incomplete: false };
+ try {
+ const cutoff = state.requestedAt - RETENTION_DAYS * 86400000;
+ const planned = await scan(locations, cutoff);
+ result.incomplete = planned.incomplete;
+ let lastProcessCheck = 0;
+ const deadline = Date.now() + 30000;
+ for (const entry of planned.entries) {
+ if (Date.now() > deadline) { result.incomplete = true; break; }
+ const current = readState(locations.state);
+ if (!current.pending || current.id !== state.id) return { ...result, skipped: 'cancelled' };
+ if (Date.now() - lastProcessCheck > 2000) {
+ if (!await stopped()) return { ...result, skipped: 'client-running' };
+ lastProcessCheck = Date.now();
+ }
+ try {
+ if (!await assertRoot(locations)) break;
+ const target = path.join(locations.root, entry.name);
+ const fresh = await scanEntry(target, cutoff, { count: 0, deadline: Date.now() + SCAN_TIMEOUT_MS });
+ if (!fresh.safe || !fresh.old || fresh.signature !== entry.signature) { result.skippedEntries++; continue; }
+ if (!await assertRoot(locations)) break;
+ await fs.promises.rm(target, { recursive: true, force: false, maxRetries: 0 });
+ result.removedBytes += entry.bytes;
+ result.removedEntries++;
+ } catch (_) { result.skippedEntries++; }
+ }
+ const current = readState(locations.state);
+ if (current.id === state.id) saveState(locations.state, { pending: false, lastResult: { ...result, finishedAt: Date.now() } });
+ return result;
+ } catch (_) {
+ return { ...result, skipped: 'scan-failed' };
+ } finally { fs.unlinkSync(locations.lock); }
+}
+
+module.exports = { inspectClientTemp, requestClientTempCleanup, runPendingClientTempCleanup };
diff --git a/scripts/daemon.js b/scripts/daemon.js
index d40d2d2..7d1b99d 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -38,6 +38,7 @@ const { spawn, spawnSync, execFile } = require('child_process');
const { createWallpaperRotation, updateWallpaperInRenderer, pickWallpaperDirectory } = require('./wallpaper-rotation');
const { readClientLaunchSettings, setClientLaunchSettings, getClientLaunchArgs } = require('./client-launch-settings.js');
const { getWorkBuddyLaunchEnv } = require('./workbuddy-launch-env.js');
+const { inspectClientTemp, requestClientTempCleanup, runPendingClientTempCleanup } = require('./client-temp.js');
const PROBE_CLIENT_RUNNING = process.argv.includes('--probe-client-running');
const {
assertSameProcessIdentity,
@@ -118,6 +119,8 @@ const {
removeAutoCopySession,
removeAutoCopyAccount,
collectLineageMembersForDelete,
+ recordSessionDeletion,
+ isAutoCopyTargetExcluded,
getAutoCopyMapping,
getAutoCopyMappings,
migrateAutoCopyTargetRevisions: migrateAutoCopyTargetRevisionsFromMeta,
@@ -534,8 +537,9 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 1.2.65:兼容空会话同步、自定义模型和重定向备份目录,工作目录恢复退避重试。
// 1.2.66:刷新凭据按原信封加密保存,同账号刷新去重,过期账号保留手动切换。
// 1.2.67:Windows 重启 GUI 客户端时不再请求隐藏主窗口,与冷启动保持一致。
-const DAEMON_VERSION = '1.2.78';
-const DAEMON_BUILD_ID = 'release-1.2.78-stop-historical-deletion-propagation';
+// #507: explicit cleanup of old Windows client temp files, only before a verified cold launch.
+const DAEMON_VERSION = '1.2.80';
+const DAEMON_BUILD_ID = 'release-1.2.80-session-sync-shared-windows-target';
const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });
configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const automationDiscovery = createAutomationDiscovery({
@@ -3400,6 +3404,9 @@ function relaunchWorkBuddy() {
}
// 日志用 ASCII 标记(非用户可见文案,无需进 i18n 词典)
log(`[logout] 以 ${environmentMode ? '环境变量' : '命令行参数'} CDP=${port} 重启 WorkBuddy: ${command}${viaLauncher ? ' [via launcher]' : ''}`);
+ if (IS_WIN) await runPendingClientTempCleanup(DATA_DIR, PROFILE, {
+ isStopped: () => verifiedWindowsWorkBuddyProcesses(command).length === 0,
+ });
const childEnv = getWorkBuddyLaunchEnv(PROFILE, DATA_DIR, process.platform, process.env);
if (environmentMode) childEnv.WORKBUDDY_REMOTE_DEBUGGING_PORT = String(port);
if (viaLauncher) {
@@ -5545,6 +5552,80 @@ function sessionCopyContentRevision(row) {
]);
}
+function sessionTitlePair(row) {
+ return JSON.stringify([String(row && row.title || ''), String(row && row.custom_title || '')]);
+}
+
+function mappingTitlePair(mapping, side, uid) {
+ if (!mapping) return null;
+ const revisions = side === 'source'
+ ? [mapping.sourceRevisions && mapping.sourceRevisions[uid], mapping.sourceRevision, mapping.sourceStateRevision]
+ : [mapping.targetRevision, mapping.targetStateRevision];
+ for (const revision of revisions) {
+ try {
+ const parsed = JSON.parse(revision);
+ if (Array.isArray(parsed) && [5, 7].includes(parsed.length)) return JSON.stringify(parsed.slice(-2));
+ } catch (_) {}
+ }
+ return null;
+}
+
+// Title baselines are pairwise: a later A→B copy must not acknowledge B's
+// new title on behalf of C. Keep the last equal title for each physical pair,
+// and consult the reverse mapping so switching direction keeps that baseline.
+function titleBaselineEntry(mapping, source, target) {
+ const key = JSON.stringify([String(source.user_id), String(source.id)]);
+ const entry = mapping && mapping.titleBaselines && mapping.titleBaselines[key];
+ return entry && entry.targetId === String(target.id) && typeof entry.title === 'string' ? entry : null;
+}
+
+function sharedTitleBaseline(mapping, reverse, source, target) {
+ const entries = [titleBaselineEntry(mapping, source, target), titleBaselineEntry(reverse, target, source)].filter(Boolean);
+ if (entries.length) {
+ entries.sort((a, b) => b.at - a.at);
+ if (entries.length === 2 && entries[0].at === entries[1].at && entries[0].title !== entries[1].title) return null;
+ return entries[0].title;
+ }
+ // Legacy mappings are safe only if they prove this exact pair last had the
+ // same title. An old unequal-title skip is not a synchronization baseline.
+ for (const [candidate, from, to] of [[mapping, source, target], [reverse, target, source]]) {
+ if (!candidate || candidate.targetId !== String(to.id)) continue;
+ try {
+ const revision = JSON.parse(candidate.sourceRevisions && candidate.sourceRevisions[from.user_id] || candidate.sourceRevision);
+ const targetRevision = JSON.parse(candidate.targetRevision);
+ if (revision[0] !== String(from.id) || revision[1] !== String(from.user_id) ||
+ targetRevision[0] !== String(to.id) || targetRevision[1] !== String(to.user_id)) continue;
+ const left = mappingTitlePair(candidate, 'source', from.user_id);
+ if (left !== null && left === mappingTitlePair(candidate, 'target', to.user_id)) return left;
+ } catch (_) {}
+ }
+ return null;
+}
+
+function mappingWithTitleBaseline(mapping, reverse, source, target) {
+ const titleBaselines = Object.assign({}, mapping && mapping.titleBaselines);
+ if (target && sessionTitlePair(source) === sessionTitlePair(target)) {
+ const previous = titleBaselineEntry(mapping, source, target);
+ const backwards = titleBaselineEntry(reverse, target, source);
+ titleBaselines[JSON.stringify([String(source.user_id), String(source.id)])] = {
+ targetId: String(target.id), title: sessionTitlePair(source),
+ at: Math.max(Date.now(), Number(previous && previous.at || 0) + 1, Number(backwards && backwards.at || 0) + 1),
+ };
+ }
+ return { titleBaselines };
+}
+
+function mappingHasUnequalTitles(mapping) {
+ const source = mappingTitlePair(mapping, 'source', mapping && mapping.sourceUid);
+ const target = mappingTitlePair(mapping, 'target');
+ return source !== null && target !== null && source !== target;
+}
+
+function mappingSourceTitleChanged(mapping, uid, row) {
+ const baseline = mappingTitlePair(mapping, 'source', uid);
+ return baseline !== null && baseline !== sessionTitlePair(row);
+}
+
// WorkBuddy stores the context-window denominator on the session row and the
// usage ring data in session_usage. Both are optional across client versions;
// a missing column/table must not break account switching for older clients.
@@ -5771,6 +5852,7 @@ function mappingWithSourceRevision(mapping, sourceUid, sourceRow) {
sourceContentRevision: sessionCopyContentRevision(sourceRow),
sourceStateRevision: sessionCopyStableStateRevision(sourceRow),
sourceRevisions,
+ ...(mapping && mapping.titleBaselines ? { titleBaselines: mapping.titleBaselines } : {}),
};
}
@@ -5861,6 +5943,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
}
};
const mapping = getAutoCopyMapping(DATA_DIR, lineageId, targetUid);
+ const reverseMapping = getAutoCopyMapping(DATA_DIR, lineageId, sourceUid);
const ids = new Set(getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid));
if (mapping && mapping.targetId) ids.add(mapping.targetId);
const candidates = [];
@@ -5868,6 +5951,8 @@ async function copySessionRecord(src, targetUid, options = {}) {
const row = await readRow(id, targetUid);
if (row) candidates.push(row);
}
+ const targetExcluded = options.auto && isAutoCopyTargetExcluded(DATA_DIR, lineageId, targetUid);
+ if (targetExcluded && !candidates.length) return { status: 'skipped', sourceId: src.id, targetId: null };
// A previous daemon could have created the target row and crashed before
// persisting its lineage member/mapping. Repeated account switches must
// recover that exact content instead of allocating another physical row.
@@ -5904,8 +5989,14 @@ async function copySessionRecord(src, targetUid, options = {}) {
// revision persistence are revalidated once through the normal snapshot
// comparison path.
if (options.auto && existingMappingTarget && mapping.fingerprintVersion === 3 &&
+ sessionTitlePair(sourceRow) === sessionTitlePair(existingMappingTarget) &&
mappingSourceRevisionMatches(mapping, sourceUid, sourceRow) &&
mappingTargetRevisionMatches(mapping, existingMappingTarget)) {
+ if (!titleBaselineEntry(mapping, sourceRow, existingMappingTarget)) {
+ await withAutoCopyMetaWrite(() => setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
+ ...mapping, ...mappingWithTitleBaseline(mapping, reverseMapping, sourceRow, existingMappingTarget),
+ }));
+ }
const sourceBytes = Number(mapping.sourceBytes);
const totalBytes = Number(mapping.totalBytes);
const warning = (Number.isFinite(sourceBytes) ? sourceBytes : 0) > 100 * 1024 * 1024
@@ -5949,29 +6040,65 @@ async function copySessionRecord(src, targetUid, options = {}) {
// a new physical session in the same lineage, so later scans find it by
// content and do not create another copy on every switch.
const branched = selection.comparison.kind === 'conflict';
+ if (branched && targetExcluded) return { status: 'skipped', sourceId: src.id, targetId: null };
const targetId = branched ? crypto.randomUUID() : selection.targetId;
if (branched) {
aliases.push(targetId);
if (codeBuddyFiles) codeBuddyFiles.register({...sourceRow,id:targetId,user_id:targetUid});
}
const existing = candidates.find(row => row.id === targetId) || null;
- // An equal selection needs no writes: the trimmed selection snapshot is
- // enough to skip, and the next sync re-reads everything anyway. Avoid the
- // extra full target snapshot on the hot all-skipped path.
+ // Equal message snapshots still need independent title synchronization.
+ // The trimmed selection is enough; no message file rewrite is needed.
if (!branched && selection.comparison.kind === 'equal') {
+ let titleChanged = false;
+ if (existing && sessionTitlePair(sourceRow) !== sessionTitlePair(existing)) {
+ const baseline = sharedTitleBaseline(mapping, reverseMapping, sourceRow, existing);
+ const sourceChanged = baseline !== null && baseline !== sessionTitlePair(sourceRow);
+ const targetChanged = baseline !== null && baseline !== sessionTitlePair(existing);
+ // Activation timestamps do not prove which title was edited.
+ if (baseline === null || sourceChanged === targetChanged) {
+ return { status: 'conflict', sourceId: src.id, targetId, warning: '两端会话标题不同,已保留各自标题,请统一后重试' };
+ }
+ const from = sourceChanged ? sourceRow : existing;
+ const to = sourceChanged ? existing : sourceRow;
+ await assertSessionSyncIdle([sourceRow.id, existing.id]);
+ if (JSON.stringify(await readRow(sourceRow.id, sourceUid)) !== JSON.stringify(sourceRow) ||
+ JSON.stringify(await readRow(existing.id, targetUid)) !== JSON.stringify(existing)) {
+ throw new Error('会话记录正在变化,请稍后重试');
+ }
+ const updatedAt = Math.max(Number(to.updated_at || 0), Number(from.updated_at || 0));
+ const result = await sqliteRun(
+ "UPDATE sessions SET title = ?, custom_title = ?, updated_at = ? WHERE id = ? AND user_id = ? AND deleted_at IS NULL AND COALESCE(title, '') = ? AND COALESCE(custom_title, '') = ? AND COALESCE(updated_at, 0) = ? " +
+ "AND EXISTS (SELECT 1 FROM sessions AS source WHERE source.id = ? AND source.user_id = ? AND source.deleted_at IS NULL AND COALESCE(source.title, '') = ? AND COALESCE(source.custom_title, '') = ? AND COALESCE(source.updated_at, 0) = ?);",
+ [from.title || '', from.custom_title || '', updatedAt, to.id, to.user_id, to.title || '', to.custom_title || '', Number(to.updated_at || 0),
+ from.id, from.user_id, from.title || '', from.custom_title || '', Number(from.updated_at || 0)]
+ );
+ if (result && result.changes === 0) throw new Error('会话记录正在变化,请稍后重试');
+ // The sqlite3 CLI backend cannot report changes. Verify its result
+ // before acknowledging a title baseline after a conditional update.
+ if (!result || result.changes == null) {
+ const saved = await readRow(to.id, to.user_id);
+ const freshSource = await readRow(from.id, from.user_id);
+ if (!saved || sessionTitlePair(saved) !== sessionTitlePair(from) || Number(saved.updated_at || 0) !== updatedAt ||
+ JSON.stringify(freshSource) !== JSON.stringify(from)) throw new Error('会话记录正在变化,请稍后重试');
+ }
+ Object.assign(to, { title: from.title || '', custom_title: from.custom_title || '', updated_at: updatedAt });
+ titleChanged = true;
+ }
await withAutoCopyMetaWrite(() => {
if (!getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid).includes(targetId)) addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId);
setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
targetId, status: 'copied', failedFiles: 0, fingerprintVersion: 3,
...mappingWithSourceRevision(mapping, sourceUid, sourceRow),
+ ...mappingWithTitleBaseline(mapping, reverseMapping, sourceRow, existing),
targetRevision: sessionCopyRowRevision(existing || { ...sourceRow, id: targetId, user_id: targetUid }),
targetStateRevision: sessionCopyStableStateRevision(existing || { ...sourceRow, id: targetId, user_id: targetUid }),
sourceBytes: left.totalBytes, totalBytes: left.totalBytes,
});
});
const warning = left.totalBytes > 100 * 1024 * 1024 ? '会话超过 100 MB,同步可能较慢' : '';
- finishAutoDirty(targetId, runtimeRepairBytes > 0);
- return { status: runtimeRepairBytes ? 'copied' : 'skipped', sourceId: src.id, targetId, branched: false, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes: left.totalBytes, copiedBytes: runtimeRepairBytes };
+ finishAutoDirty(targetId, titleChanged || runtimeRepairBytes > 0);
+ return { status: titleChanged || runtimeRepairBytes ? 'copied' : 'skipped', sourceId: src.id, targetId, branched: false, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes: left.totalBytes, copiedBytes: runtimeRepairBytes };
}
let right = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, targetId, aliases, syncCache);
// Size is advisory only; both manual and automatic sync keep all files.
@@ -6052,6 +6179,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
return setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
targetId, status: 'copied', failedFiles: 0, fingerprintVersion: 3,
...mappingWithSourceRevision(mapping, sourceUid, sourceRow),
+ ...mappingWithTitleBaseline(mapping, reverseMapping, sourceRow, mappingTarget),
targetRevision: sessionCopyRowRevision(mappingTarget),
targetStateRevision: sessionCopyStableStateRevision(mappingTarget),
sourceBytes: left.totalBytes, totalBytes,
@@ -6121,6 +6249,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
return true;
};
const refreshStableMappedPayload = async (row, mapping, targetRow, lineageId) => {
+ if (mappingSourceTitleChanged(mapping, source, row) || sessionTitlePair(row) !== sessionTitlePair(targetRow)) return false;
if (!mapping || !mapping.targetId || !targetRow || !lineageId ||
typeof sessionSync === 'undefined' || typeof sessionSync.readSnapshotAsync !== 'function' ||
typeof sessionSync.compareSnapshots !== 'function') return false;
@@ -6207,6 +6336,9 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
const lineageId = (rules.allLineages && rules.allLineages[String(row.id)]) ||
(typeof getAutoCopySession === 'function' && getAutoCopySession(DATA_DIR, source, row.id)?.lineageId);
const mapping = lineageId ? mappings.get(String(lineageId)) : null;
+ if (mappingSourceTitleChanged(mapping, source, row) || mappingHasUnequalTitles(mapping) ||
+ (targetById && mapping && targetById.has(String(mapping.targetId)) &&
+ sessionTitlePair(row) !== sessionTitlePair(targetById.get(String(mapping.targetId))))) { dirtyRows.push(row); continue; }
// The target mapping is enough to restore the active view. Only enter
// the worker when it is missing, its row disappeared, or the renderer
// explicitly marked the source session dirty.
@@ -6238,6 +6370,9 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
}
const lineageId = rules.allLineages && rules.allLineages[String(row.id)];
const mapping = lineageId ? mappings.get(String(lineageId)) : null;
+ if (mappingSourceTitleChanged(mapping, source, row) || mappingHasUnequalTitles(mapping) ||
+ (targetById && mapping && targetById.has(String(mapping.targetId)) &&
+ sessionTitlePair(row) !== sessionTitlePair(targetById.get(String(mapping.targetId))))) { dirtyRows.push(row); continue; }
if (mapping && mapping.fingerprintVersion !== 3) { dirtyRows.push(row); continue; }
if (dirtyIndex.shouldSync(source, row.id)) {
if (clearStableDirtyMarker(row, mapping)) continue;
@@ -6287,7 +6422,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
const mapping = row.lineageId ? mappings.get(String(row.lineageId)) : null;
if (!mapping || mapping.fingerprintVersion !== 3 || !mapping.targetId) return true;
const targetRow = targetById.get(String(mapping.targetId));
- return !targetRow || !mappingSourceRevisionMatches(mapping, source, row) ||
+ return !targetRow || sessionTitlePair(row) !== sessionTitlePair(targetRow) || !mappingSourceRevisionMatches(mapping, source, row) ||
(!mappingTargetRevisionMatches(mapping, targetRow) &&
!mappingTargetLifecycleRevisionMatches(mapping, targetRow));
});
@@ -10857,6 +10992,22 @@ function handleApi(req, res) {
});
}
+ if (req.method === 'GET' && p === '/api/client-temp') {
+ return inspectClientTemp(DATA_DIR, PROFILE).then(data => json(res, 200, { ok: true, ...data }))
+ .catch(() => json(res, 500, { ok: false, error: '无法统计临时文件,请检查目录权限后重试' }));
+ }
+ if (req.method === 'POST' && p === '/api/client-temp') {
+ return readBody(req).then(body => {
+ if (!body || typeof body.pending !== 'boolean' || process.platform !== 'win32' || PROFILE.customTarget ||
+ !['workbuddy-cn', 'workbuddy-ai'].includes(PROFILE.id)) {
+ return json(res, 400, { ok: false, error: '当前客户端不支持此清理请求' });
+ }
+ try {
+ return json(res, 200, { ok: true, ...requestClientTempCleanup(DATA_DIR, PROFILE, body.pending) });
+ } catch (_) { return json(res, 500, { ok: false, error: '保存清理请求失败,请重试' }); }
+ });
+ }
+
if (req.method === 'GET' && p === '/api/client-launch-settings') {
return json(res, 200, { ok: true, ...readClientLaunchSettings(DATA_DIR, PROFILE.id, process.platform) });
}
@@ -12260,7 +12411,7 @@ function handleApi(req, res) {
}
});
}
- // 删除会话(真实删除):POST /api/sessions/delete { ids }——删除 DB 记录 + 该账号下全部会话文件(不可恢复)
+ // 删除会话:默认仅所选物理 ID;显式 lineage 范围须先预览并确认 previewToken。
if (req.method === 'POST' && p === '/api/sessions/delete') {
return readBody(req).then(async (body) => {
let ids;
@@ -12268,6 +12419,10 @@ function handleApi(req, res) {
catch (e) { return json(res, 400, { ok: false, error: e.message }); }
if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });
if (!ids.every(isValidSessionId)) return json(res, 400, { ok: false, error: '包含无效的会话 ID' });
+ const scope = body.scope === undefined ? 'selected' : body.scope;
+ if (!['selected', 'lineage'].includes(scope) || (body.preview !== undefined && typeof body.preview !== 'boolean')) {
+ return json(res, 400, { ok: false, error: '无效的删除范围' });
+ }
let releaseSessionSync = null;
try {
// A copy worker may have already read the source row and be about to
@@ -12277,10 +12432,9 @@ function handleApi(req, res) {
if (typeof assertAccountSwitchIdle === 'function') {
releaseSessionSync = await assertAccountSwitchIdle();
}
- // 展开目标会话所在的 lineage:其他账号自动复制出的同源副本一并级联删除,
- // 避免删除后切走再切回时被 auto-copy 原样复制回来(会话「复活」)。
+ // #511: ordinary deletion is strictly local to the selected physical IDs.
const requestedSet = new Set(ids.map(String));
- const members = collectLineageMembersForDelete(DATA_DIR, ids);
+ const members = scope === 'lineage' ? collectLineageMembersForDelete(DATA_DIR, ids) : ids.map(id => ({ id }));
const memberIds = Array.from(new Set(members.map((m) => m.id).filter((id) => isValidSessionId(id))));
if (!memberIds.length) return json(res, 404, { ok: false, error: '会话不存在或已删除' });
const placeholders = sqlPlaceholders(memberIds);
@@ -12289,20 +12443,25 @@ function handleApi(req, res) {
const matchedSet = new Set(before.map((row) => String(row.id || '')));
const matchedIds = memberIds.filter((id) => matchedSet.has(String(id)));
const matchedRows = before.filter((row) => matchedSet.has(String(row.id || '')));
+ const cascaded = matchedIds.filter(id => !requestedSet.has(String(id))).length;
+ const previewToken = crypto.createHash('sha256').update(JSON.stringify([
+ scope, [...requestedSet].sort(), matchedRows.map(row => [String(row.id), String(row.user_id)]).sort((a, b) => a[0].localeCompare(b[0])),
+ ])).digest('hex');
+ if (body.preview === true) return json(res, 200, {
+ ok: true, scope, total: matchedIds.length, cascaded,
+ accounts: new Set(matchedRows.map(row => String(row.user_id))).size, previewToken,
+ });
+ if ((scope === 'lineage' || body.previewToken !== undefined) && body.previewToken !== previewToken) {
+ return json(res, 409, { ok: false, error: '删除范围已变化,请重新预览并确认' });
+ }
// 1) 先完成可重试的文件与规则清理;失败时保留 DB 记录作为重试锚点。
const wbHome = PROFILE.dataRoot;
let filesRemoved = 0;
if (codeBuddyFiles) await assertSessionSyncIdle(matchedIds);
else for (const id of matchedIds) filesRemoved += deleteSessionFiles(wbHome, id);
- let rulesRemoved = 0;
- for (const row of matchedRows) {
- try {
- if (removeAutoCopySession(DATA_DIR, String(row.user_id || '').trim(), row.id)) rulesRemoved++;
- } catch (e) {
- log(`[sessions-auto-copy] 删除规则 ${row.id} 失败: ${e.message}`);
- throw e;
- }
- }
+ // Persist the exclusion before removing DB retry anchors. File failures
+ // above leave the original relationship intact; later retries are safe.
+ const rulesRemoved = recordSessionDeletion(DATA_DIR, matchedRows, { preserveMembers: true });
// 2) 最后真实删除 DB 记录(非软删)。若此步失败,重复请求可安全重试。
if (matchedIds.length) {
const removeRecords = () => sqliteRun(
@@ -12312,7 +12471,9 @@ function handleApi(req, res) {
if (codeBuddyFiles) filesRemoved = await codeBuddyFiles.deleteSessions(matchedIds, removeRecords);
else await removeRecords();
}
- const cascaded = matchedIds.filter((id) => !requestedSet.has(String(id))).length;
+ // Keep the family graph until DB deletion succeeds so a failed bulk
+ // delete can be previewed and retried with the same linked members.
+ recordSessionDeletion(DATA_DIR, matchedRows);
log(`[sessions-delete] 已真实删除 ${matchedIds.length} 个会话(DB + ${filesRemoved} 项文件,级联副本 ${cascaded})`);
return json(res, 200, { ok: true, deleted: matchedIds.length, requested: ids.length, cascaded, filesRemoved, rulesRemoved });
} catch (e) {
diff --git a/scripts/inject.js b/scripts/inject.js
index 0d18838..7751e5f 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -282,7 +282,8 @@ function createFabQuietMode(options) {
var height = fab.offsetHeight * 0.5;
var right = parseFloat(fab.style.right) || 22;
var bottom = parseFloat(fab.style.bottom) || 22;
- return { width: width, height: height, right: right,
+ var edge = options.rightEdge ? options.rightEdge() : win.innerWidth;
+ return { width: width, height: height, right: right - (win.innerWidth - edge), edge: edge,
left: win.innerWidth - right - width, centerY: win.innerHeight - bottom - height / 2 };
}
function cancel() {
@@ -293,23 +294,26 @@ function createFabQuietMode(options) {
if (!alive) return;
cancel();
fab.classList.remove('is-quiet');
- if (fab.classList.contains('hidden')) near = false;
- if (!enabled || near || fab.classList.contains('hidden') || options.isDragging()) return;
+ if ((fab.classList.contains('hidden') || fab.classList.contains('is-area-hidden'))) near = false;
+ if (!enabled || near || (fab.classList.contains('hidden') || fab.classList.contains('is-area-hidden')) || options.isDragging()) return;
timer = setTimeout(function () {
timer = null;
- if (!alive || near || fab.classList.contains('hidden') || options.isDragging() || fab.contains(doc.activeElement)) return;
+ if (!alive || near || (fab.classList.contains('hidden') || fab.classList.contains('is-area-hidden')) || options.isDragging() || fab.contains(doc.activeElement)) return;
var box = geometry();
// 左转后头顶朝左:头部只露 4px;停靠时 CSS 隐藏天线。
fab.style.setProperty('--wbs-fab-quiet-shift', (box.right + box.width / 2 + box.height / 2 - 4) + 'px');
+ // A chat edge inside the window cannot rely on viewport clipping.
+ // Convert the overflow back to the robot's unscaled coordinates.
+ fab.style.setProperty('--wbs-fab-quiet-clip', Math.max(0, box.width + box.height - 8) + 'px');
fab.classList.add('is-quiet');
}, IDLE_MS);
}
options.listen(win, 'pointermove', function (event) {
- if (!enabled || event.pointerType === 'touch' || fab.classList.contains('hidden') || options.isDragging()) return;
+ if (!enabled || event.pointerType === 'touch' || (fab.classList.contains('hidden') || fab.classList.contains('is-area-hidden')) || options.isDragging()) return;
var box = geometry();
var docked = fab.classList.contains('is-quiet');
// 停靠时只响应露出的头部附近;恢复后扩大保活范围,方便移向按钮点击。
- var next = event.clientX >= (docked ? win.innerWidth - 18 : box.left - 24) &&
+ var next = event.clientX >= (docked ? box.edge - 18 : box.left - 24) && event.clientX <= box.edge + 4 &&
Math.abs(event.clientY - box.centerY) <= box.width / 2 + (docked ? 12 : 24);
if (next !== near) { near = next; wake(); }
}, { capture: true, passive: true });
@@ -1513,6 +1517,28 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var WBS_ACCOUNT_NOTE_HOVER_KEY = 'workdaddy.account.noteHover.' + PROFILE_ID;
var WBS_GROWTH_PLAN_HOVER_KEY = 'workdaddy.account.growthPlanHover.' + PROFILE_ID;
var WBS_I18N_EN = {
+ '客户端临时文件': 'Client temporary files',
+ '仅清理当前客户端 7 天未修改的临时项目,保留近期文件和官方更新缓存。请先保存需要的临时产物并结束任务。': 'Clean only temporary items unchanged for 7 days in this client. Recent files and official update caches are kept. Save any needed temporary work and end tasks first.',
+ '点击统计查看占用': 'Calculate to view usage',
+ '统计占用': 'Calculate usage',
+ '下次启动清理': 'Clean on next launch',
+ '取消清理': 'Cancel cleanup',
+ '已安排:完全退出客户端并结束相关任务后,通过': 'Scheduled: fully quit the client and end related tasks, then launch through',
+ ' 再次启动时清理。': ' to clean temporary files.',
+ '占用 ': 'Used ',
+ ' · 可清理 ': ' · Eligible ',
+ '(统计不完整,无法读取的项目将保留)': ' (Partial scan; unreadable items will be kept)',
+ ' · 上次已清理 ': ' · Last cleaned ',
+ '(部分项目已跳过)': ' (Some items were skipped)',
+ '正在统计临时文件…': 'Calculating temporary file usage…',
+ '统计失败,请重试': 'Could not calculate usage. Try again',
+ '安排清理临时文件?': 'Schedule temporary file cleanup?',
+ '清理无法撤销。请保存需要的临时产物,完全退出客户端并结束相关任务,再通过 WorkDaddy 启动。仅处理 7 天未修改的临时项目,保留官方更新缓存;账号备份和正式会话目录不在清理范围内。': 'Cleanup cannot be undone. Save needed temporary work, fully quit the client and end related tasks, then launch through WorkDaddy. Only temporary items unchanged for 7 days are eligible. Official update caches, account backups and session directories are excluded.',
+ '清理无法撤销。请保存需要的临时产物,完全退出客户端并结束相关任务,再通过 WorkDaddy AI 启动。仅处理 7 天未修改的临时项目,保留官方更新缓存;账号备份和正式会话目录不在清理范围内。': 'Cleanup cannot be undone. Save needed temporary work, fully quit the client and end related tasks, then launch through WorkDaddy AI. Only temporary items unchanged for 7 days are eligible. Official update caches, account backups and session directories are excluded.',
+ '安排清理': 'Schedule cleanup',
+ '无法统计临时文件,请检查目录权限后重试': 'Cannot calculate temporary file usage. Check folder permissions and try again.',
+ '当前客户端不支持此清理请求': 'This client does not support this cleanup request.',
+ '保存清理请求失败,请重试': 'Could not save the cleanup request. Try again.',
'个人版与企业版共用官方会话 UID,无法可靠区分会话归属,已停止同步;账号备份和切换仍可使用': 'Personal and enterprise accounts share an official session UID. Sync stopped because ownership is ambiguous; account backup and switching remain available',
'会话数据库正被占用,请稍后重新同步': 'Session database is busy. Please retry later',
'没有读取或写入会话文件的权限,请检查文件权限后重新同步': 'Cannot access session files. Check permissions and retry',
@@ -2030,6 +2056,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'无可同步的目标账号(已排除会话所属账号)': 'No target accounts to sync to (the session owner account is excluded)',
'删除后会话将从列表中移除,该账号下的本地消息文件将被永久删除,此操作不可恢复。': 'The sessions are removed from the list and their local message files are permanently deleted; this cannot be undone.',
'删除后会话将从列表中移除,本账号的会话及同步到其他账号的同源会话(本地消息文件)都将被永久删除,此操作不可恢复。': 'The sessions are removed from the list. These sessions and their synced counterparts in other accounts (local message files) are permanently deleted; this cannot be undone.',
+ '将删除': 'Delete', ' 个会话,涉及': ' sessions across',
+ '正在核对删除范围…': 'Checking the deletion scope…',
+ '无法核对删除范围,请关闭后重试。': 'Cannot verify the deletion scope. Close this dialog and try again.',
+ '将删除 {n} 个会话,涉及 {m} 个账号。': 'Delete {n} sessions across {m} accounts. ',
+ '包含所选会话及其所有已关联副本,删除无法撤销。': 'Includes the selected sessions and all linked copies. Deletion cannot be undone.',
+ '仅删除所选会话,保留其他副本。自动同步不会在这些账号重新生成已删除的副本;如需恢复,可手动同步。删除无法撤销。': 'Only the selected sessions will be deleted; other copies are kept. Automatic sync will not recreate deleted copies in these accounts. To restore a copy, sync it manually. Deletion cannot be undone.',
+ '含关联副本 {n} 个': ' including {n} linked copies',
+ '无效的删除范围': 'Invalid deletion scope',
+ '删除范围已变化,请重新预览并确认': 'The deletion scope has changed. Preview and confirm it again.',
+ '两端会话标题不同,已保留各自标题,请统一后重试': 'Session titles differ. Both titles were preserved; make them match and retry.',
'含其他账号副本 {n} 个': ' including {n} other-account copies',
'以「不让当前账号登录身份过期」的方式切到登录页,可以登录新账号,也可以切回已登录账号': 'Goes to the login page without letting the current account expire; log in a new account or switch back to an existing one.',
'不退出 WorkBuddy,在浏览器完成授权后新账号自动加入列表': 'Keeps WorkBuddy running; after authorizing in the browser, the new account is added to the list automatically.',
@@ -4862,19 +4898,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function position() {
if (!root || !surface || !surface.viewportElement || hidden) return;
- // Narrow windows leave too little space beside the text for the rail.
- // Keep the user's setting/store intact so widening restores it immediately.
- if (window.innerWidth <= 1280) {
+ var area = WBS_COMPAT.findConversationArea(document, surface.viewportElement);
+ var rect = area && area.rect;
+ // Measure the chat itself, not the window (sidebar and file preview
+ // may consume most of a wide window). Keep turns/settings for restore.
+ if (!rect || rect.width < 800) {
root.style.display = 'none';
if (dragPointerId != null) finishNavDrag({ pointerId: dragPointerId }, true);
hideTooltip(true);
return;
}
- var rect = surface.viewportElement.getBoundingClientRect();
- if (!rect || rect.width <= 0 || rect.height <= 0) {
- root.style.display = 'none';
- return;
- }
+ var viewport = surface.viewportElement.getBoundingClientRect();
+ var top = Math.max(rect.top, viewport.top), bottom = Math.min(rect.bottom, viewport.bottom);
+ if (bottom <= top) { root.style.display = 'none'; hideTooltip(true); return; }
+ rect = { left:Math.max(rect.left, viewport.left), top:top, height:bottom-top };
root.style.display = 'block';
var railChrome = 14;
var markerCount = Math.min(20, turns.length);
@@ -4999,16 +5036,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!tooltip || tooltip.hidden || !anchorButton) return;
var margin = 8, gap = 8;
// 为右侧详情预留空间;窄窗口同时缩小两列,避免详情覆盖列表或超出视口。
+ var area = WBS_COMPAT.findConversationArea(document, surface && surface.viewportElement);
+ if (!area || !area.rect) { hideTooltip(true); return; }
+ var bounds = area.rect;
+ tooltip.style.maxHeight = Math.max(1, bounds.height - margin * 2) + 'px';
+ if (detail) detail.style.maxHeight = tooltip.style.maxHeight;
var rootRect = root.getBoundingClientRect();
- var left = Math.max(margin, Math.min(rootRect.right + gap, window.innerWidth - margin - 160));
- var available = Math.max(0, window.innerWidth - left - margin - gap);
+ var left = Math.max(bounds.left + margin, Math.min(rootRect.right + gap, bounds.right - margin - 160));
+ var available = Math.max(0, bounds.right - left - margin - gap);
var listWidth = Math.min(380, available * 0.46);
var detailWidth = Math.min(440, available - listWidth);
tooltip.style.width = listWidth + 'px';
tooltip.style.left = left + 'px';
var buttonRect = anchorButton.getBoundingClientRect();
var height = tooltip.getBoundingClientRect().height;
- tooltip.style.top = Math.max(margin, Math.min(window.innerHeight - height - margin,
+ tooltip.style.top = Math.max(bounds.top + margin, Math.min(bounds.bottom - height - margin,
buttonRect.top + buttonRect.height / 2 - height / 2)) + 'px';
if (!detail || detail.hidden || !previewRow) return;
var rowRect = previewRow.getBoundingClientRect();
@@ -5016,7 +5058,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (rowRect.bottom <= listRect.top || rowRect.top >= listRect.bottom) { hideDetail(); return; }
detail.style.width = detailWidth + 'px';
detail.style.left = (left + listWidth + gap) + 'px';
- detail.style.top = Math.max(margin, Math.min(window.innerHeight - detail.getBoundingClientRect().height - margin,
+ detail.style.top = Math.max(bounds.top + margin, Math.min(bounds.bottom - detail.getBoundingClientRect().height - margin,
rowRect.top)) + 'px';
}
@@ -5375,7 +5417,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
unbindStore();
if (root) root.remove();
});
- return { sync: sync, setEnabled: setEnabled };
+ return { sync: sync, setEnabled: setEnabled, updateLayout: position };
}
var messageNavigation = createMessageNavigation();
var forkBusy = false;
@@ -5610,12 +5652,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// anchor is that element's bottom-right corner. Anchoring to the component
// keeps the button beside the chat when the sidebar collapses, the window
// resizes, or a right-hand detail panel opens.
- var FAB_ANCHOR_SELECTORS = [
- '.teams-container.is-mac .conversation-shell',
- '.conversation-shell',
- '.conversation-shell__main',
- '.teams-main-content',
- ];
// v3 re-anchors the button to the conversation area. v2 stored a
// viewport-relative bottom offset, which parked the robot mid-screen
// (253px) even though it was asked to sit in the corner; that stale offset
@@ -5643,21 +5679,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function readFabAnchorNode() {
- for (var i = 0; i < FAB_ANCHOR_SELECTORS.length; i++) {
- var node = document.querySelector(FAB_ANCHOR_SELECTORS[i]);
- if (!node) continue;
- var rect = node.getBoundingClientRect();
- if (rect && rect.width > 0 && rect.height > 0) return node;
- }
- return null;
+ var area = WBS_COMPAT.findConversationArea(document);
+ return area && area.element;
}
- // Distance from the viewport edges to the anchor's bottom-right corner plus
- // the visual gap. Without a usable anchor the viewport corner is the floor.
function fabAnchorOffsets() {
- var node = readFabAnchorNode();
- if (!node) return { right: FAB_EDGE_GAP, bottom: FAB_EDGE_GAP };
- var rect = node.getBoundingClientRect();
+ var area = WBS_COMPAT.findConversationArea(document);
+ var rect = area && area.rect;
+ if (!rect) return { right:FAB_EDGE_GAP, bottom:FAB_EDGE_GAP };
return {
right: Math.max(FAB_EDGE_GAP, Math.round(window.innerWidth - rect.right) + FAB_EDGE_GAP),
bottom: Math.max(FAB_EDGE_GAP, Math.round(window.innerHeight - rect.bottom) + FAB_EDGE_GAP),
@@ -5666,13 +5695,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function clampFabBottom(bottom, height) {
var floor = fabAnchorOffsets().bottom;
- var max = Math.max(floor, window.innerHeight - height - FAB_EDGE_GAP);
+ var area = WBS_COMPAT.findConversationArea(document);
+ var max = Math.max(floor, window.innerHeight - (area && area.rect ? area.rect.top : 0) - height - FAB_EDGE_GAP);
return Math.max(floor, Math.min(max, Number(bottom) || floor));
}
function clampFabRight(right, width) {
var floor = fabAnchorOffsets().right;
- var max = Math.max(floor, window.innerWidth - width - FAB_EDGE_GAP);
+ var area = WBS_COMPAT.findConversationArea(document);
+ var max = Math.max(floor, window.innerWidth - (area && area.rect ? area.rect.left : 0) - width - FAB_EDGE_GAP);
return Math.max(floor, Math.min(max, Number(right) || floor));
}
@@ -5701,30 +5732,52 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// switches, detail panel motion), so re-resolve the node and watch its box
// instead of trusting the element captured at injection time.
var fabAnchorObserver = null;
- var fabAnchorObserverNode = null;
+ var fabLayoutObserver = null;
+ var fabObservedNodes = [];
function ensureFabAnchorObserver() {
- if (typeof ResizeObserver !== 'function') return;
- var node = readFabAnchorNode();
- if (node && node === fabAnchorObserverNode && node.isConnected) return;
+ var nodes = [], anchor = readFabAnchorNode();
+ var seeds = [anchor].concat(Array.from(document.querySelectorAll('.detail-panel-container')));
+ seeds.forEach(function (seed) {
+ for (var node = seed; node && node !== document.body; node = node.parentElement) {
+ if (nodes.indexOf(node) < 0) nodes.push(node);
+ }
+ });
+ if (nodes.length === fabObservedNodes.length && nodes.every(function (node, i) { return node === fabObservedNodes[i]; })) return;
if (fabAnchorObserver) fabAnchorObserver.disconnect();
- fabAnchorObserverNode = node;
- if (!node) return;
- if (!fabAnchorObserver) {
+ if (fabLayoutObserver) fabLayoutObserver.disconnect();
+ fabObservedNodes = nodes;
+ // Attributes are observed only on the layout ancestor chains, never on
+ // message descendants. Resize handles splitters/preview transitions;
+ // attributes handle visibility changes that keep the same dimensions.
+ if (!fabAnchorObserver && typeof ResizeObserver === 'function') {
fabAnchorObserver = new ResizeObserver(function () { scheduleFabPos(); });
}
- fabAnchorObserver.observe(node);
+ if (!fabLayoutObserver && typeof MutationObserver === 'function') {
+ fabLayoutObserver = new MutationObserver(scheduleFabPos);
+ }
+ nodes.forEach(function (node) {
+ if (fabAnchorObserver) fabAnchorObserver.observe(node);
+ if (fabLayoutObserver) fabLayoutObserver.observe(node, { attributes:true, attributeFilter:['class','style','hidden'], subtree:false });
+ });
}
registerDisposer(function () {
- if (!fabAnchorObserver) return;
- fabAnchorObserver.disconnect();
+ if (fabAnchorObserver) fabAnchorObserver.disconnect();
+ if (fabLayoutObserver) fabLayoutObserver.disconnect();
fabAnchorObserver = null;
- fabAnchorObserverNode = null;
+ fabLayoutObserver = null;
+ fabObservedNodes = [];
});
function positionFab() {
var fab = root.querySelector('.wbs-fab');
if (!fab) return;
ensureFabAnchorObserver();
- if (fab.classList.contains('hidden')) return; // 面板打开时保持隐藏
+ var area = WBS_COMPAT.findConversationArea(document);
+ var areaHidden = area ? !area.rect : !CAPS.nativeComposer;
+ var changed = fab.classList.contains('is-area-hidden') !== areaHidden;
+ fab.classList.toggle('is-area-hidden', areaHidden);
+ if (messageNavigation) messageNavigation.updateLayout();
+ if (changed && fabQuietMode) fabQuietMode.wake();
+ if (areaHidden || fab.classList.contains('hidden')) return;
if (fabDrag) return;
var anchor = fabAnchorOffsets();
var saved = readFabBottom();
@@ -8978,22 +9031,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
matches.sort(function (left, right) {
return (Number(right.favoriteCount) || 0) - (Number(left.favoriteCount) || 0);
});
- var pageSize = 8;
- var pages = Math.max(1, Math.ceil(matches.length / pageSize));
- var page = mask.__wbsDiscoveryPage = Math.min(Math.max(1, mask.__wbsDiscoveryPage || 1), pages);
mask.querySelector('.wbs-auto-discovery-total').textContent = favoritesOnly ? '我的收藏 ' + matches.length + ' 个' : '共 ' + tasks.length + ' 个任务' + (query.trim() ? ' · 匹配 ' + matches.length + ' 个' : '');
- mask.querySelector('.wbs-auto-discovery-page').textContent = page + ' / ' + pages;
- mask.querySelector('[data-auto-discovery-page="prev"]').disabled = page <= 1;
- mask.querySelector('[data-auto-discovery-page="next"]').disabled = page >= pages;
list.innerHTML = '';
if (!matches.length) {
var empty = document.createElement('div'); empty.className = 'wbs-auto-discovery-empty';
empty.textContent = favoritesOnly && tasks.length ? '暂无收藏的任务' : tasks.length ? '没有匹配的任务' : (automationState.discoveryError || '暂未发现公开任务');
list.appendChild(empty); return;
}
- matches.slice((page - 1) * pageSize, page * pageSize).forEach(function (task) {
+ matches.forEach(function (task, index) {
var item = document.createElement('section'); item.className = 'wbs-auto-discovery-item';
- item.innerHTML = '<div class="wbs-auto-discovery-head"><div class="wbs-auto-discovery-name" data-wbs-i18n-skip="1"></div><span class="wbs-auto-discovery-version"></span><span class="wbs-auto-discovery-update" hidden>新版</span><button class="wbs-auto-discovery-favorite" type="button" data-auto-discovery-favorite aria-label="收藏任务" title="收藏任务" aria-pressed="false">' + AUTO_FAVORITE_SVG + '<span data-auto-discovery-favorite-count>0</span></button></div><div class="wbs-auto-discovery-description" data-wbs-i18n-skip="1"></div><div class="wbs-auto-discovery-foot"><div class="wbs-auto-sources"></div><button class="wbs-modal-btn wbs-modal-ok" type="button" data-auto-discovery-import></button></div>';
+ item.innerHTML = '<div class="wbs-auto-discovery-head"><span class="wbs-auto-discovery-number"></span><div class="wbs-auto-discovery-name" data-wbs-i18n-skip="1"></div><span class="wbs-auto-discovery-version"></span><span class="wbs-auto-discovery-update" hidden>新版</span><button class="wbs-auto-discovery-favorite" type="button" data-auto-discovery-favorite aria-label="收藏任务" title="收藏任务" aria-pressed="false">' + AUTO_FAVORITE_SVG + '<span data-auto-discovery-favorite-count>0</span></button></div><div class="wbs-auto-discovery-description" data-wbs-i18n-skip="1"></div><div class="wbs-auto-discovery-foot"><div class="wbs-auto-sources"></div><button class="wbs-modal-btn wbs-modal-ok" type="button" data-auto-discovery-import></button></div>';
+ item.querySelector('.wbs-auto-discovery-number').textContent = String(index + 1);
item.querySelector('.wbs-auto-discovery-name').textContent = task.name || '未命名任务';
item.querySelector('.wbs-auto-discovery-version').textContent = task.packageVersion ? 'v' + task.packageVersion : 'API V' + (Number(task.schemaVersion) || 1);
var installed = installedPackage(task.packageId);
@@ -9044,28 +9092,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function showAutomationDiscovery() {
closePanelModal(root.querySelector('#wbs-auto-discovery-mask'));
var mask = document.createElement('div'); mask.id = 'wbs-auto-discovery-mask'; mask.className = 'wbs-modal-mask wbs-usage-modal-mask wbs-auto-dialog-mask';
- mask.innerHTML = '<div class="wbs-modal wbs-token-stats-modal wbs-auto-discovery-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-discovery-title"><div class="wbs-usage-header wbs-auto-discovery-header"><div class="wbs-auto-modal-head"><div><div class="wbs-modal-title" id="wbs-auto-discovery-title">发现更多自动化任务</div><div class="wbs-auto-discovery-note">这些任务来自互联网公开仓库,均为第三方内容,与 WorkDaddy 无归属关系。导入后默认停用,请先安全评估再启用。</div><div class="wbs-auto-discovery-note wbs-auto-discovery-status" hidden>部分来源暂时无法访问,当前显示上次缓存的结果。</div></div><div class="wbs-auto-discovery-head-actions"><button class="wbs-auto-textbtn" type="button" data-auto-discovery-guide>我也要出现在这里</button><button class="wbs-auto-modal-close" type="button" data-auto-close title="关闭" aria-label="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></div></div><div class="wbs-auto-discovery-toolbar"><input class="wbs-auto-discovery-search" type="search" maxlength="120" aria-label="搜索任务名称" placeholder="搜索任务名称"><button class="wbs-auto-discovery-filter" type="button" data-auto-discovery-filter="favorites" aria-pressed="false">我的收藏</button></div></div><div class="wbs-usage-scroll wbs-auto-discovery-list"></div><div class="wbs-modal-actions wbs-auto-discovery-pagination"><span class="wbs-auto-discovery-total" role="status"></span><button class="wbs-modal-btn" type="button" data-auto-discovery-page="prev" aria-label="上一页">上一页</button><span class="wbs-auto-discovery-page"></span><button class="wbs-modal-btn" type="button" data-auto-discovery-page="next" aria-label="下一页">下一页</button></div></div>';
+ mask.innerHTML = '<div class="wbs-modal wbs-token-stats-modal wbs-auto-discovery-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-discovery-title"><div class="wbs-usage-header wbs-auto-discovery-header"><div class="wbs-auto-modal-head"><div><div class="wbs-modal-title" id="wbs-auto-discovery-title">发现更多自动化任务</div><div class="wbs-auto-discovery-note">这些任务来自互联网公开仓库,均为第三方内容,与 WorkDaddy 无归属关系。导入后默认停用,请先安全评估再启用。</div><div class="wbs-auto-discovery-note wbs-auto-discovery-status" hidden>部分来源暂时无法访问,当前显示上次缓存的结果。</div></div><div class="wbs-auto-discovery-head-actions"><button class="wbs-auto-textbtn" type="button" data-auto-discovery-guide>我也要出现在这里</button><button class="wbs-auto-modal-close" type="button" data-auto-close title="关闭" aria-label="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></div></div><div class="wbs-auto-discovery-toolbar"><input class="wbs-auto-discovery-search" type="search" maxlength="120" aria-label="搜索任务名称" placeholder="搜索任务名称"><button class="wbs-auto-discovery-filter" type="button" data-auto-discovery-filter="favorites" aria-pressed="false">我的收藏</button></div></div><div class="wbs-usage-scroll wbs-auto-discovery-list"></div><div class="wbs-modal-actions wbs-auto-discovery-footer"><span class="wbs-auto-discovery-total" role="status"></span></div></div>';
mask.querySelector('.wbs-auto-discovery-status').hidden = !(automationState.discovery && automationState.discovery.stale);
mountAutomationModal(mask);
renderAutomationDiscovery(mask);
var search = mask.querySelector('.wbs-auto-discovery-search');
- search.addEventListener('input', function () { mask.__wbsDiscoveryPage = 1; renderAutomationDiscovery(mask); mask.querySelector('.wbs-auto-discovery-list').scrollTop = 0; });
+ search.addEventListener('input', function () { renderAutomationDiscovery(mask); mask.querySelector('.wbs-auto-discovery-list').scrollTop = 0; });
mask.querySelector('[data-auto-discovery-filter="favorites"]').addEventListener('click', function (event) {
mask.__wbsDiscoveryFavoritesOnly = !mask.__wbsDiscoveryFavoritesOnly;
event.currentTarget.setAttribute('aria-pressed', String(mask.__wbsDiscoveryFavoritesOnly));
event.currentTarget.classList.toggle('active', mask.__wbsDiscoveryFavoritesOnly);
- mask.__wbsDiscoveryPage = 1;
renderAutomationDiscovery(mask);
mask.querySelector('.wbs-auto-discovery-list').scrollTop = 0;
});
mask.querySelector('[data-auto-discovery-guide]').addEventListener('click', showAutomationDiscoveryGuide);
- mask.querySelector('.wbs-auto-discovery-pagination').addEventListener('click', function (event) {
- var button = event.target.closest && event.target.closest('[data-auto-discovery-page]');
- if (!button || button.disabled) return;
- mask.__wbsDiscoveryPage += button.getAttribute('data-auto-discovery-page') === 'next' ? 1 : -1;
- renderAutomationDiscovery(mask);
- mask.querySelector('.wbs-auto-discovery-list').scrollTop = 0;
- });
mask.querySelector('.wbs-auto-discovery-list').addEventListener('click', function (event) {
var favoriteButton = event.target.closest && event.target.closest('[data-auto-discovery-favorite]');
if (favoriteButton) {
@@ -10464,21 +10504,45 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 删除弹窗:确认框(真实删除,弹窗内警示不可恢复)
function openDeleteModal(ids, allAccounts) {
ids = ids.slice();
+ var scope = allAccounts ? 'lineage' : 'selected';
var titleEl = sessionsPane.querySelector('#wbs-sess-modal-title');
var body = sessionsPane.querySelector('#wbs-sess-modal-body');
var okBtn = sessionsPane.querySelector('#wbs-sess-modal-ok');
var cancelBtn = sessionsPane.querySelector('#wbs-sess-modal-cancel');
var confirmed = !allAccounts;
var pending = false;
+ var previewToken = null;
titleEl.textContent = allAccounts ? '删除所有账号的同源会话?' : '删除 ' + ids.length + ' 个会话?';
- body.innerHTML = allAccounts
- ? '<p>已选 ' + ids.length + ' 个会话</p><div class="wbs-modal-warn">将永久删除所选会话,以及已关联到其他账号的所有同步副本、消息文件和本地缓存。此操作不可恢复。</div>'
- : '<div class="wbs-modal-warn">删除后会话将从列表中移除,本账号的会话及同步到其他账号的同源会话(本地消息文件)都将被永久删除,此操作不可恢复。</div>';
okBtn.textContent = allAccounts ? '继续确认' : '确定';
- okBtn.disabled = false;
+ okBtn.disabled = true;
+ okBtn.classList.remove('is-loading');
+ okBtn.removeAttribute('aria-busy');
showSessModal(true);
+ function loadDeletePreview() {
+ previewToken = null;
+ confirmed = !allAccounts;
+ titleEl.textContent = allAccounts ? '删除所有账号的同源会话?' : '删除 ' + ids.length + ' 个会话?';
+ okBtn.disabled = true;
+ okBtn.textContent = allAccounts ? '继续确认' : '确定';
+ body.textContent = '正在核对删除范围…';
+ api('/api/sessions/delete', {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ids: ids, scope: scope, preview: true }),
+ }).then(function (data) {
+ if (okBtn.onclick !== submit) return;
+ previewToken = data.previewToken;
+ body.textContent = '将删除 ' + data.total + ' 个会话,涉及 ' + data.accounts + ' 个账号。' +
+ (allAccounts ? '包含所选会话及其所有已关联副本,删除无法撤销。' :
+ '仅删除所选会话,保留其他副本。自动同步不会在这些账号重新生成已删除的副本;如需恢复,可手动同步。删除无法撤销。');
+ okBtn.disabled = !previewToken || !data.total;
+ }).catch(function (error) {
+ if (okBtn.onclick !== submit) return;
+ body.textContent = '无法核对删除范围,请关闭后重试。';
+ toast('删除失败: ' + (error.message || error), true, root);
+ });
+ }
var submit = function () {
- if (pending) return;
+ if (pending || !previewToken || okBtn.disabled) return;
if (!confirmed) {
confirmed = true;
titleEl.textContent = '再次确认永久删除';
@@ -10488,32 +10552,30 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
pending = true;
okBtn.disabled = true;
- var pendingLabel = okBtn.textContent;
okBtn.textContent = '删除中…';
okBtn.classList.add('is-loading');
okBtn.setAttribute('aria-busy', 'true');
api('/api/sessions/delete', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ ids: ids }),
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ids: ids, scope: scope, previewToken: previewToken }),
}).then(function (d) {
- var extra = (d && d.cascaded) ? ',含其他账号副本 ' + d.cascaded + ' 个' : '';
+ var extra = (d && d.cascaded) ? ',含关联副本 ' + d.cascaded + ' 个' : '';
toast('已删除 ' + ((d && typeof d.deleted === 'number') ? d.deleted : ids.length) + ' 个会话' + extra, false, root);
if (okBtn.onclick === submit) showSessModal(false);
loadSessions();
- }).catch(function (e) {
- toast('删除失败: ' + (e.message || e), true, root);
+ }).catch(function (error) {
+ toast('删除失败: ' + (error.message || error), true, root);
+ if (okBtn.onclick === submit) loadDeletePreview();
}).finally(function () {
pending = false;
if (okBtn.onclick === submit) {
- okBtn.disabled = false;
- okBtn.textContent = pendingLabel;
okBtn.classList.remove('is-loading');
okBtn.removeAttribute('aria-busy');
}
});
};
okBtn.onclick = submit;
+ loadDeletePreview();
cancelBtn.focus();
}
function selectedSessIds() {
@@ -11368,6 +11430,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-pcard-sub" id="wbs-rendering-help">关闭硬件加速并使用软件渲染,可能降低性能。保存后请完全退出 WorkBuddy AI,再通过 WorkDaddy AI 启动;关闭此开关可恢复默认。</div>' +
'<div class="wbs-pcard-sub" id="wbs-rendering-status" role="status" aria-live="polite">正在读取设置…</div>' +
'</div>' : '') +
+ (WBS_PLATFORM === 'win32' && (WBS_PROFILE_IS_AI || PROFILE_ID === 'workbuddy-cn') ?
+ '<div class="wbs-pcard wbs-settings-card wbs-client-temp-card" id="wbs-client-temp-card">' +
+ '<div class="wbs-settings-row"><span class="wbs-pcard-title">客户端临时文件</span></div>' +
+ '<div class="wbs-pcard-sub">仅清理当前客户端 7 天未修改的临时项目,保留近期文件和官方更新缓存。请先保存需要的临时产物并结束任务。</div>' +
+ '<div class="wbs-pcard-sub" id="wbs-client-temp-status" role="status" aria-live="polite">点击统计查看占用</div>' +
+ '<div class="wbs-client-temp-actions"><button type="button" class="wbs-modal-btn" id="wbs-client-temp-scan">统计占用</button>' +
+ '<button type="button" class="wbs-modal-btn" id="wbs-client-temp-clean" disabled>下次启动清理</button></div>' +
+ '</div>' : '') +
'<div class="wbs-pcard wbs-telemetry-card" id="wbs-telemetry-card">' +
'<div class="wbs-telemetry-head">' +
'<div class="wbs-telemetry-label"><span class="wbs-pcard-title">发送错误诊断</span><span class="wbs-telemetry-help" tabindex="0" aria-label="查看错误诊断说明"><svg viewBox="0 0 20 20" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="10" cy="10" r="8"/><path d="M8.4 7.6a1.8 1.8 0 1 1 2.8 1.45c-.75.48-1.2.85-1.2 1.75M10 13.7v.1"/></svg><span class="wbs-telemetry-tooltip" role="tooltip">此开关控制脱敏错误诊断。匿名安装数和日活独立统计(随机安装标识、系统、架构、版本、客户端类型及出口国家),不受此开关影响。不包含账号、会话内容、Token 或 API Key。</span></span></div>' +
@@ -11431,11 +11501,84 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
wireTelemetrySettings();
wireClientLaunchSettings();
+ wireClientTempCleanup();
acRenderMonitorLogModal();
// 自动更新:检查 + 红点 + 更新卡片
checkForUpdate();
}
+ function wireClientTempCleanup() {
+ var card = aboutPane.querySelector('#wbs-client-temp-card');
+ if (!card) return;
+ var status = card.querySelector('#wbs-client-temp-status');
+ var scan = card.querySelector('#wbs-client-temp-scan');
+ var clean = card.querySelector('#wbs-client-temp-clean');
+ var pending = false;
+ var mask = null;
+ function size(bytes) { return (Math.max(0, Number(bytes) || 0) / 1048576).toFixed(1) + ' MB'; }
+ function renderClientTempStatus(data) {
+ if (!data.supported) { card.style.display = 'none'; return; }
+ pending = data.pending === true;
+ clean.textContent = pending ? '取消清理' : '下次启动清理';
+ clean.disabled = false;
+ status.textContent = pending ? '已安排:完全退出客户端并结束相关任务后,通过 ' + WBS_BRAND + ' 再次启动时清理。' :
+ '占用 ' + size(data.bytes) + ' · 可清理 ' + size(data.cleanableBytes) + (data.incomplete ? '(统计不完整,无法读取的项目将保留)' : '');
+ if (!pending && data.lastResult) status.textContent += ' · 上次已清理 ' + size(data.lastResult.removedBytes) +
+ (data.lastResult.skippedEntries || data.lastResult.incomplete ? '(部分项目已跳过)' : '');
+ }
+ function refreshClientTempStats() {
+ scan.disabled = true; clean.disabled = true; status.textContent = '正在统计临时文件…';
+ return api('/api/client-temp').then(renderClientTempStatus).catch(function (error) {
+ status.textContent = error.message || '统计失败,请重试';
+ }).finally(function () { scan.disabled = false; });
+ }
+ function save(next) {
+ clean.disabled = true;
+ api('/api/client-temp', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ pending: next }) })
+ .then(function (data) {
+ pending = data.pending === true;
+ if (pending) renderClientTempStatus(data); else refreshClientTempStats();
+ }).catch(function (error) { status.textContent = error.message || '保存失败,请重试'; clean.disabled = false; });
+ }
+ function close() { if (mask) { mask.remove(); mask = null; clean.focus(); } }
+ scan.addEventListener('click', refreshClientTempStats);
+ clean.addEventListener('click', function () {
+ if (pending) { save(false); return; }
+ if (mask) return;
+ mask = document.createElement('div');
+ mask.className = 'wbs-modal-mask wbs-client-temp-mask';
+ mask.innerHTML = '<div class="wbs-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-client-temp-title">' +
+ '<div class="wbs-modal-title" id="wbs-client-temp-title">安排清理临时文件?</div>' +
+ '<div class="wbs-modal-body">清理无法撤销。请保存需要的临时产物,完全退出客户端并结束相关任务,再通过 WorkDaddy 启动。仅处理 7 天未修改的临时项目,保留官方更新缓存;账号备份和正式会话目录不在清理范围内。</div>' +
+ '<div class="wbs-modal-actions"><button type="button" class="wbs-modal-btn" data-temp-action="cancel">取消</button>' +
+ '<button type="button" class="wbs-modal-btn wbs-modal-ok" data-temp-action="confirm">安排清理</button></div></div>';
+ mask.querySelector('.wbs-modal-body').textContent = mask.querySelector('.wbs-modal-body').textContent.replace('WorkDaddy', WBS_BRAND);
+ ['pointerdown', 'mousedown', 'mouseup', 'pointerup', 'wheel'].forEach(function (name) {
+ mask.addEventListener(name, function (event) { event.stopPropagation(); });
+ });
+ mask.addEventListener('click', function (event) {
+ event.stopPropagation();
+ var action = event.target.getAttribute && event.target.getAttribute('data-temp-action');
+ if (event.target === mask || action === 'cancel') close();
+ else if (action === 'confirm') { close(); save(true); }
+ });
+ mask.addEventListener('keydown', function (event) {
+ event.stopPropagation();
+ if (event.key === 'Escape') { event.preventDefault(); close(); }
+ else if (event.key === 'Tab') {
+ var buttons = mask.querySelectorAll('button');
+ if ((event.shiftKey && document.activeElement === buttons[0]) || (!event.shiftKey && document.activeElement === buttons[1])) {
+ event.preventDefault(); buttons[event.shiftKey ? 1 : 0].focus();
+ }
+ }
+ });
+ root.appendChild(mask);
+ applyI18n(mask);
+ mask.querySelector('button').focus();
+ });
+ registerDisposer(close);
+ }
+
function wireClientLaunchSettings() {
var toggle = aboutPane.querySelector('#wbs-software-rendering');
var status = aboutPane.querySelector('#wbs-rendering-status');
@@ -12422,6 +12565,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
fab: fab, window: window, document: document, listen: listen,
storage: localStorage, settingKey: 'wbs-fab-auto-dock-' + PROFILE_ID,
isDragging: function () { return !!fabDrag; },
+ rightEdge: function () {
+ var area = WBS_COMPAT.findConversationArea(document);
+ return area && area.rect ? area.rect.right : window.innerWidth;
+ },
});
registerDisposer(fabQuietMode.destroy);
setupFabDrag();
@@ -18076,7 +18223,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
/* 休眠状态仍由天线顶部圆点提示。 */
'@keyframes wbs-sleep-pulse{0%,100%{box-shadow:0 0 5px 1px rgba(46,229,157,.6)}50%{box-shadow:0 0 13px 4px rgba(46,229,157,.95)}}',
'@keyframes wbs-sleep-pulse-amber{0%,100%{box-shadow:0 0 5px 1px rgba(255,176,58,.6)}50%{box-shadow:0 0 13px 4px rgba(255,176,58,.95)}}',
- '.wbs-fab.hidden{display:none}',
+ '.wbs-fab.hidden,.wbs-fab.is-area-hidden{display:none}',
'.wbs-fab .click{position:relative;transition:transform .22s cubic-bezier(.22,1,.36,1)}',
'.wbs-fab .click > span:not(.wbs-fab-antenna){display:none}',
'.wbs-fab .button.shadow{display:none}',
@@ -18112,7 +18259,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-fab:hover{transform:scale(0.5)}.wbs-fab:hover .eye{scale:1.18}',
'.wbs-fab:active{transform:scale(0.5) translate(2px,2px)}',
- '.wbs-fab.is-quiet{transform:translateX(var(--wbs-fab-quiet-shift,59px)) scale(0.5)}',
+ '.wbs-fab.is-quiet{transform:translateX(var(--wbs-fab-quiet-shift,59px)) scale(0.5);clip-path:inset(-100px var(--wbs-fab-quiet-clip,0px) -100px -100px)}',
'.wbs-fab.is-quiet .click{transform:rotate(-90deg)}',
'.wbs-fab.is-quiet .wbs-fab-health-dot{visibility:hidden}',
'.wbs-fab.is-quiet .wbs-fab-antenna,.wbs-fab.is-quiet .wbs-fab-antenna-dot{visibility:hidden}',
@@ -18141,6 +18288,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-language-card .wbs-settings-row{justify-content:space-between}',
'.wbs-language-card .wbs-pcard-title{margin-bottom:0}',
'.wbs-rendering-card .wbs-pcard-title{margin-bottom:0;min-width:0}',
+ '.wbs-client-temp-card .wbs-pcard-sub{margin-top:6px;line-height:1.6;color:var(--wb-color-text-secondary);white-space:normal;overflow-wrap:anywhere}.wbs-client-temp-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}.wbs-client-temp-actions button{min-width:80px}.wbs-client-temp-actions button:disabled{opacity:.5;cursor:default}.wbs-client-temp-actions button:focus-visible,.wbs-client-temp-mask button:focus-visible{outline:2px solid var(--wb-accent-primary,var(--wb-color-text-primary));outline-offset:2px}.wbs-client-temp-mask{pointer-events:auto;padding:12px;box-sizing:border-box}.wbs-client-temp-mask .wbs-modal{max-height:calc(100vh - 24px);overflow:auto;box-sizing:border-box}.wbs-client-temp-mask .wbs-modal-body{line-height:1.6;white-space:normal;overflow-wrap:anywhere}',
'.wbs-rendering-card .wbs-pcard-sub{margin-top:6px;line-height:1.6;color:var(--wb-color-text-secondary);white-space:normal;overflow-wrap:anywhere}',
'.wbs-lang-seg{flex:0 0 auto;width:auto;margin-bottom:0}',
'.wbs-lang-seg .wbs-sess-seg-btn{padding:6px 14px}',
@@ -18444,7 +18592,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'#wbs-auto-discover.is-loading svg{animation:wbs-auto-discover-pulse 1s ease-in-out infinite}@keyframes wbs-auto-discover-pulse{50%{opacity:.35}}#wbs-auto-discover:disabled{cursor:wait;opacity:.68}',
'.wbs-modal.wbs-auto-discovery-modal{display:grid;grid-template-rows:auto auto minmax(0,1fr);gap:9px;width:calc(100% - 24px);max-width:620px;height:min(560px,calc(100% - 28px));box-sizing:border-box;overflow:hidden}.wbs-auto-discovery-note{margin-top:3px;color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.45}.wbs-auto-discovery-toolbar{display:flex;align-items:center;gap:7px;margin-top:8px}.wbs-auto-discovery-search{box-sizing:border-box;flex:1;min-width:0;height:32px;padding:6px 10px;border:1px solid var(--wb-border-default,#ddd);border-radius:8px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:12px;outline:none}.wbs-auto-discovery-search:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 18%,transparent)}.wbs-auto-discovery-search::placeholder{color:var(--wb-icon-tertiary,#888)}.wbs-auto-discovery-filter{flex:0 0 auto;height:32px;padding:0 10px;border:1px solid var(--wb-border-default,#ddd);border-radius:8px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font:inherit;font-size:11px;cursor:pointer}.wbs-auto-discovery-filter:hover,.wbs-auto-discovery-filter.active{border-color:var(--wb-button-primary-bg,#1f1f1f);background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}.wbs-auto-discovery-filter:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:1px}',
'.wbs-auto-discovery-header .wbs-auto-modal-head>div:first-child{min-width:0}.wbs-auto-discovery-status[hidden]{display:none}',
- '.wbs-auto-discovery-list{display:flex;min-height:0;flex-direction:column;gap:6px;overflow:auto;padding-right:2px}.wbs-auto-discovery-empty{display:flex;min-height:160px;align-items:center;justify-content:center;color:var(--wb-icon-tertiary,#888);font-size:12px}.wbs-auto-discovery-item{display:flex;flex:0 0 auto;flex-direction:column;gap:6px;padding:9px 10px;border:1px solid var(--wb-border-subtle,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 24%,transparent)}.wbs-auto-discovery-head{display:flex;align-items:center;gap:8px}.wbs-auto-discovery-name{min-width:0;flex:1;color:var(--wb-color-text-primary,#1f1f1f);font-size:12px;font-weight:650;line-height:1.4;overflow-wrap:anywhere}.wbs-auto-discovery-version{flex:0 0 auto;padding:2px 6px;border:1px solid var(--wb-border-default,#ddd);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font-size:10px;font-weight:600;white-space:nowrap}.wbs-auto-discovery-favorite{display:inline-flex;align-items:center;justify-content:center;gap:3px;flex:0 0 auto;min-width:34px;height:26px;padding:0 5px;border:0;border-radius:7px;background:transparent;color:var(--wb-icon-tertiary,#888);font:inherit;font-size:10px;cursor:pointer}.wbs-auto-discovery-favorite:hover,.wbs-auto-discovery-favorite:focus-visible{background:var(--wb-bg-hover,#f0f0f0);color:var(--wb-color-text-primary,#1f1f1f);outline:none}.wbs-auto-discovery-favorite.is-active{color:var(--wb-button-primary-bg,var(--wb-color-text-primary,#1f1f1f))}.wbs-auto-discovery-favorite:disabled{opacity:.5;cursor:wait}.wbs-auto-discovery-favorite svg{display:block;flex:0 0 16px}.wbs-auto-discovery-favorite.is-active svg{fill:currentColor}.wbs-auto-discovery-description{color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.45;overflow-wrap:anywhere}.wbs-auto-discovery-foot{display:flex;align-items:flex-end;gap:8px}.wbs-auto-sources{display:flex;min-width:0;flex:1;flex-wrap:wrap;gap:4px}.wbs-auto-source{max-width:100%;padding:3px 6px;border:1px solid var(--wb-border-subtle,#ddd);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font:inherit;font-size:10px;line-height:1.3;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-auto-source:hover,.wbs-auto-source:focus-visible{border-color:var(--wb-border-strong,#bbb);color:var(--wb-color-text-primary,#1f1f1f);outline:none}.wbs-auto-discovery-foot>.wbs-modal-btn{flex:0 0 auto;min-width:48px;padding:5px 9px}.wbs-auto-discovery-foot>.wbs-modal-btn:disabled{opacity:.45;cursor:not-allowed}',
+ '.wbs-auto-discovery-list{display:flex;min-height:0;flex-direction:column;gap:6px;overflow:auto;padding-right:2px}.wbs-auto-discovery-empty{display:flex;min-height:160px;align-items:center;justify-content:center;color:var(--wb-icon-tertiary,#888);font-size:12px}.wbs-auto-discovery-item{display:flex;flex:0 0 auto;flex-direction:column;gap:6px;padding:9px 10px;border:1px solid var(--wb-border-subtle,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 24%,transparent)}.wbs-auto-discovery-head{display:flex;align-items:center;gap:8px}.wbs-auto-discovery-number{flex:0 0 auto;color:var(--wb-color-text-secondary,#666);font-size:11px;font-variant-numeric:tabular-nums}.wbs-auto-discovery-name{min-width:0;flex:1;color:var(--wb-color-text-primary,#1f1f1f);font-size:12px;font-weight:650;line-height:1.4;overflow-wrap:anywhere}.wbs-auto-discovery-version{flex:0 0 auto;padding:2px 6px;border:1px solid var(--wb-border-default,#ddd);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font-size:10px;font-weight:600;white-space:nowrap}.wbs-auto-discovery-favorite{display:inline-flex;align-items:center;justify-content:center;gap:3px;flex:0 0 auto;min-width:34px;height:26px;padding:0 5px;border:0;border-radius:7px;background:transparent;color:var(--wb-icon-tertiary,#888);font:inherit;font-size:10px;cursor:pointer}.wbs-auto-discovery-favorite:hover,.wbs-auto-discovery-favorite:focus-visible{background:var(--wb-bg-hover,#f0f0f0);color:var(--wb-color-text-primary,#1f1f1f);outline:none}.wbs-auto-discovery-favorite.is-active{color:var(--wb-button-primary-bg,var(--wb-color-text-primary,#1f1f1f))}.wbs-auto-discovery-favorite:disabled{opacity:.5;cursor:wait}.wbs-auto-discovery-favorite svg{display:block;flex:0 0 16px}.wbs-auto-discovery-favorite.is-active svg{fill:currentColor}.wbs-auto-discovery-description{color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.45;overflow-wrap:anywhere}.wbs-auto-discovery-foot{display:flex;align-items:flex-end;gap:8px}.wbs-auto-sources{display:flex;min-width:0;flex:1;flex-wrap:wrap;gap:4px}.wbs-auto-source{max-width:100%;padding:3px 6px;border:1px solid var(--wb-border-subtle,#ddd);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font:inherit;font-size:10px;line-height:1.3;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-auto-source:hover,.wbs-auto-source:focus-visible{border-color:var(--wb-border-strong,#bbb);color:var(--wb-color-text-primary,#1f1f1f);outline:none}.wbs-auto-discovery-foot>.wbs-modal-btn{flex:0 0 auto;min-width:48px;padding:5px 9px}.wbs-auto-discovery-foot>.wbs-modal-btn:disabled{opacity:.45;cursor:not-allowed}',
'.wbs-auto-batchbar{display:flex;align-items:center;gap:6px;margin:4px 0 7px}.wbs-auto-batch-count{margin-right:auto;color:var(--wb-icon-tertiary,#888);font-size:11px}.wbs-auto-field input,.wbs-auto-field textarea{box-sizing:border-box;width:100%;border:1px solid var(--wb-border-default,#dedede);border-radius:7px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:12px;outline:none}.wbs-auto-field{display:flex;flex-direction:column;gap:4px;margin-bottom:8px;color:var(--wb-icon-secondary,#666);font-size:11px}.wbs-auto-field input{height:30px;padding:5px 8px}.wbs-auto-field textarea{min-height:72px;padding:8px;resize:vertical;line-height:1.45}.wbs-auto-field textarea[data-auto-field="steps"]{min-height:150px;resize:none;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.wbs-auto-field input:focus,.wbs-auto-field textarea:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 20%,transparent)}.wbs-auto-trigger-seg{display:flex;gap:3px;padding:3px;border-radius:9px;background:var(--wb-bg-tertiary,#f0f0f0)}.wbs-auto-trigger-seg label{flex:1;display:flex;align-items:center;justify-content:center;min-height:28px;padding:0 8px;border-radius:7px;color:var(--wb-icon-secondary,#666);cursor:pointer}.wbs-auto-trigger-seg input{position:absolute;opacity:0;pointer-events:none}.wbs-auto-trigger-seg label:has(input:checked){background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.16)}',
'.wbs-modal.wbs-auto-agent-modal{display:flex;flex-direction:column;width:calc(100% - 24px);max-width:520px;max-height:calc(100% - 28px);box-sizing:border-box}.wbs-auto-agent-intro{margin:0 0 14px;color:var(--wb-color-text-secondary,#666);font-size:12px;line-height:1.6;overflow-wrap:anywhere}.wbs-auto-agent-input-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:7px;font-size:12px;font-weight:600}.wbs-auto-agent-input-head #wbs-auto-examples{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:5px}.wbs-auto-example-fill{border:1px solid var(--wb-border-subtle,#ddd);border-radius:6px;padding:3px 8px;background:var(--wb-bg-tertiary,#f5f5f5);font-weight:400}.wbs-auto-agent-prompt{display:block;box-sizing:border-box;flex:1 1 160px;min-height:60px;width:100%;height:160px;max-height:26vh;resize:none;overflow:auto;padding:10px 12px;border:1px solid var(--wb-border-default,#ddd);border-radius:9px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);font-family:inherit;font-size:12px;line-height:1.65;white-space:pre-wrap;overflow-wrap:anywhere}.wbs-auto-agent-prompt:focus{outline:2px solid color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 30%,transparent);outline-offset:1px;border-color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-auto-agent-prompt::placeholder{color:var(--wb-icon-tertiary,#888)}.wbs-auto-agent-hint{margin:8px 0 14px;font-size:11px;color:var(--wb-color-text-secondary,#666)}.wbs-auto-agent-modal .wbs-modal-actions{flex-shrink:0;margin-top:0}.wbs-auto-agent-modal .wbs-modal-ok:disabled{opacity:.4;cursor:default}',
'.wbs-auto-modal-head{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;padding:0 0 10px}.wbs-auto-modal-head .wbs-modal-title{margin:0}.wbs-auto-modal-subtitle{max-width:360px;margin-top:3px;color:var(--wb-icon-tertiary,#888);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.wbs-auto-modal-close{display:inline-flex;align-items:center;justify-content:center;flex:0 0 26px;width:26px;height:26px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--wb-icon-secondary,#666);cursor:pointer}.wbs-auto-modal-close:hover,.wbs-auto-modal-close:focus-visible{background:var(--wb-bg-hover,#eee);color:var(--wb-color-text-primary,#222);outline:none}.wbs-auto-modal-close svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round}',
@@ -18975,12 +19123,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'html.cb-dark #wbs-token-stats-modal,html[data-theme="dark"] #wbs-token-stats-modal,body[data-vscode-theme-name*="dark" i] #wbs-token-stats-modal{color-scheme:dark;background:rgba(0,0,0,.56)}#wbs-token-stats-modal .wbs-token-stats-modal{box-sizing:border-box}.wbs-token-stats-modal{position:relative}.wbs-credit-stats-toolbar{display:flex;gap:8px;align-items:center;justify-content:space-between;flex-wrap:wrap;font-size:11px;color:var(--wb-icon-secondary,#667085)}.wbs-token-stats-grid.wbs-credit-stats-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.wbs-credit-chart{height:176px}.wbs-credit-sync{height:auto;min-height:28px;white-space:normal}.wbs-credit-sync-overlay{position:absolute;inset:0;z-index:5;display:flex;align-items:center;justify-content:center;padding:16px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 84%,transparent);backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);border-radius:inherit;pointer-events:auto}.wbs-credit-sync-overlay[hidden],[data-credit-result][hidden],[data-usage-pane][hidden]{display:none!important}.wbs-credit-sync-progress{display:flex;flex-direction:column;align-items:stretch;gap:12px;width:min(100%,340px);font-size:12px;line-height:1.6;overflow-wrap:anywhere;color:var(--wb-color-text-primary,#1f1f1f)}.wbs-credit-sync-progress>span{color:var(--wb-icon-secondary,#667085)}.wbs-credit-sync-progress progress{width:100%;height:8px;accent-color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-credit-sync-progress button{align-self:center}.wbs-usage-tabs button:focus-visible,.wbs-credit-sync:focus-visible{outline:2px solid var(--wb-color-text-primary,#1f1f1f);outline-offset:2px}',
'@media(max-width:700px){.wbs-usage-modal-mask{padding:12px}.wbs-usage-columns{grid-template-columns:1fr}.wbs-token-stats-modal{width:calc(100vw - 24px);max-width:calc(100vw - 24px);height:calc(100vh - 24px);max-height:calc(100vh - 24px)}.wbs-token-stats-grid{grid-template-columns:repeat(3,minmax(0,1fr))}}',
'@media(max-width:620px){.wbs-usage-header{padding:14px 14px 0}.wbs-usage-scroll{padding:4px 14px 14px}.wbs-token-stats-modal>.wbs-modal-actions{padding:10px 14px}.wbs-trend-controls{flex-direction:column}.wbs-trend-legend{width:100%;flex:none}.wbs-usage-segment button{min-width:0}}',
- '.wbs-modal.wbs-auto-discovery-modal{display:flex;flex-direction:column;width:min(980px,calc(100vw - 48px));max-width:calc(100vw - 48px);height:min(84vh,800px);max-height:calc(100vh - 48px);gap:0;padding:0;border:1px solid var(--wb-border-default,rgba(20,24,32,.14));border-radius:16px;box-shadow:0 24px 80px rgba(15,18,24,.22)}.wbs-auto-discovery-header{padding-bottom:14px}.wbs-auto-discovery-header .wbs-auto-modal-head{align-items:center;flex-wrap:wrap}.wbs-auto-discovery-head-actions{display:flex;align-items:center;gap:10px}.wbs-auto-discovery-header .wbs-auto-textbtn{white-space:normal;text-align:right}.wbs-auto-discovery-list{flex:1;gap:8px;padding-top:14px;scrollbar-width:thin;overscroll-behavior:contain}.wbs-auto-discovery-item{padding:13px 14px}.wbs-auto-discovery-pagination{display:flex;align-items:center;justify-content:flex-end;gap:8px;margin:0}.wbs-auto-discovery-total{margin-right:auto;font-size:11px;color:var(--wb-color-text-secondary,#666)}.wbs-auto-discovery-page{min-width:36px;text-align:center;font-size:11px;font-variant-numeric:tabular-nums;color:var(--wb-color-text-secondary,#666)}.wbs-auto-discovery-pagination .wbs-modal-btn{min-width:54px;margin:0}.wbs-auto-discovery-pagination .wbs-modal-btn:disabled{opacity:.45;cursor:not-allowed}.wbs-auto-discovery-pagination .wbs-modal-btn:focus-visible,.wbs-auto-discovery-header button:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}',
+ '.wbs-modal.wbs-auto-discovery-modal{display:flex;flex-direction:column;width:min(980px,calc(100vw - 48px));max-width:calc(100vw - 48px);height:min(84vh,800px);max-height:calc(100vh - 48px);gap:0;padding:0;border:1px solid var(--wb-border-default,rgba(20,24,32,.14));border-radius:16px;box-shadow:0 24px 80px rgba(15,18,24,.22)}.wbs-auto-discovery-header{padding-bottom:14px}.wbs-auto-discovery-header .wbs-auto-modal-head{align-items:center;flex-wrap:wrap}.wbs-auto-discovery-head-actions{display:flex;align-items:center;gap:10px}.wbs-auto-discovery-header .wbs-auto-textbtn{white-space:normal;text-align:right}.wbs-auto-discovery-list{flex:1;gap:8px;padding-top:14px;scrollbar-width:thin;overscroll-behavior:contain}.wbs-auto-discovery-item{padding:13px 14px}.wbs-auto-discovery-footer{display:flex;align-items:center;margin:0}.wbs-auto-discovery-total{margin-right:auto;font-size:11px;color:var(--wb-color-text-secondary,#666)}.wbs-auto-discovery-header button:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}',
'.wbs-auto-discovery-head-actions [data-auto-discovery-guide]{display:inline-flex;align-items:center;justify-content:center;min-height:30px;padding:6px 11px;border:1px solid var(--wb-button-primary-bg,#1f1f1f);border-radius:7px;background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);font:inherit;font-size:11px;font-weight:600;text-decoration:none;white-space:nowrap;cursor:pointer;box-shadow:0 1px 2px rgba(0,0,0,.12)}.wbs-auto-discovery-head-actions [data-auto-discovery-guide]:hover{background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#1f1f1f));color:var(--wb-button-primary-fg,#fff)}.wbs-auto-discovery-head-actions [data-auto-discovery-guide]:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}',
'.wbs-modal.wbs-auto-guide-modal{box-sizing:border-box;width:min(520px,calc(100vw - 32px));max-width:calc(100vw - 32px);max-height:calc(100vh - 32px);overflow:auto;padding:18px 20px}.wbs-auto-guide-body{font-size:12px;line-height:1.65;color:var(--wb-color-text-secondary,#666);overflow-wrap:anywhere}.wbs-auto-guide-body p{margin:0 0 10px}.wbs-auto-guide-body .wbs-auto-textbtn{padding:0;color:var(--wb-color-text-primary,#1f1f1f);text-decoration:underline;overflow-wrap:anywhere;text-align:left}.wbs-auto-guide-modal .wbs-modal-actions{margin-top:12px}.wbs-auto-guide-body .wbs-auto-textbtn:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}',
'.wbs-auto-guide-body ol{margin:8px 0 0;padding-left:20px}.wbs-auto-guide-body li{margin:0 0 8px;padding-left:2px}.wbs-auto-guide-body code{padding:2px 4px;border-radius:4px;background:var(--wb-bg-tertiary,#f2f3f5);color:var(--wb-color-text-primary,#1f1f1f);font:10.5px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}',
'html.cb-dark #wbs-auto-discovery-mask,html[data-theme="dark"] #wbs-auto-discovery-mask,body[data-vscode-theme-name*="dark" i] #wbs-auto-discovery-mask,html.cb-dark #wbs-auto-discovery-guide,html[data-theme="dark"] #wbs-auto-discovery-guide,body[data-vscode-theme-name*="dark" i] #wbs-auto-discovery-guide{color-scheme:dark;background:rgba(0,0,0,.56)}html.cb-dark .wbs-auto-discovery-version,html[data-theme="dark"] .wbs-auto-discovery-version,body[data-vscode-theme-name*="dark" i] .wbs-auto-discovery-version{border-color:var(--wb-border-subtle,rgba(255,255,255,.18));background:var(--wb-bg-tertiary,#303137);color:var(--wb-color-text-secondary,#d0d0d5)}',
- '@media(max-width:700px){.wbs-modal.wbs-auto-discovery-modal{width:calc(100vw - 24px);max-width:calc(100vw - 24px);height:calc(100vh - 24px);max-height:calc(100vh - 24px)}}@media(max-width:620px){.wbs-auto-discovery-header{padding-bottom:12px}.wbs-auto-discovery-pagination{gap:5px;flex-wrap:wrap}.wbs-auto-discovery-pagination .wbs-modal-btn{min-width:45px;padding:6px}.wbs-auto-discovery-total{flex-basis:100%}}',
+ '@media(max-width:700px){.wbs-modal.wbs-auto-discovery-modal{width:calc(100vw - 24px);max-width:calc(100vw - 24px);height:calc(100vh - 24px);max-height:calc(100vh - 24px)}}@media(max-width:620px){.wbs-auto-discovery-header{padding-bottom:12px}.wbs-auto-discovery-total{flex-basis:100%}}',
/* 登录新账号二选一弹窗(方法一 假退出 / 方法二 无感登录) */
/* 选择登录方式:遮罩限定在 WorkDaddy 面板内部,沿用会话弹窗的层级与按钮风格 */
'.wbs-pane{position:relative}',
diff --git a/scripts/lib.js b/scripts/lib.js
index 86a4cf8..fb92206 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -1164,6 +1164,9 @@ function mergeAutoCopyLineages(dataDir, fromLineageId, intoLineageId) {
const fromLineage = config.sessions[from];
const intoLineage = config.sessions[into];
if (!fromLineage || !intoLineage) return { ok: false, reason: 'missing' };
+ if (fromLineage.excludedUids || intoLineage.excludedUids) {
+ intoLineage.excludedUids = Array.from(new Set([...(intoLineage.excludedUids || []), ...(fromLineage.excludedUids || [])]));
+ }
const knownMembers = new Set((intoLineage.members || []).map((member) =>
JSON.stringify([String(member && member.uid || ''), String(member && member.id || '')])));
@@ -1289,15 +1292,52 @@ function removeAutoCopySession(dataDir, uid, sessionId) {
return true;
}
-// 真实删除路径的展开器:把要删除的会话按 lineage 扩展到全部物理副本(其他
-// 账号自动复制出来的同源会话)。否则删除某个账号的会话后,副本仍留在其他
-// 账号,切换回来时 auto-copy 会把它们原样复制回来(用户观察到的「删除后
-// 切走再切回、会话复活」现象)。无 lineage 的会话映射回自身。
+// #511: a local deletion is a destination exclusion, never permission to erase
+// surviving siblings. Keep provenance so an all/workspace sync cannot recreate
+// the deleted copy. Explicit manual copy can still restore it.
+function recordSessionDeletion(dataDir, rows, options = {}) {
+ const families = rows.map(row => {
+ const lineageIds = new Set();
+ collectLineageMembersForDelete(dataDir, [row.id], lineageIds);
+ return { row, lineageIds };
+ });
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ for (const { row, lineageIds } of families) {
+ const uid = String(row.user_id || '').trim();
+ const id = String(row.id || '').trim();
+ if (!uid || !id) continue;
+ for (const lineageId of lineageIds) {
+ const lineage = config.sessions[lineageId];
+ if (!lineage) continue;
+ lineage.excludedUids = Array.from(new Set([...(Array.isArray(lineage.excludedUids) ? lineage.excludedUids : []), uid]));
+ }
+ if (options.preserveMembers) continue;
+ for (const lineage of Object.values(config.sessions)) {
+ lineage.members = (lineage.members || []).filter(member => !(member.uid === uid && member.id === id));
+ }
+ if (config.sessionIndex[uid]) delete config.sessionIndex[uid][id];
+ for (const [key, mapping] of Object.entries(config.copies)) {
+ if (mapping && String(mapping.targetId || '') === id) delete config.copies[key];
+ }
+ }
+ if (!options.preserveMembers) config.duplicates = collectAutoCopyDuplicates(config);
+ writeMeta(dataDir, meta);
+ return rows.length;
+}
+
+function isAutoCopyTargetExcluded(dataDir, lineageId, uid) {
+ const lineage = readAutoCopyConfig(dataDir).sessions[String(lineageId || '')];
+ return !!(lineage && Array.isArray(lineage.excludedUids) && lineage.excludedUids.includes(String(uid || '').trim()));
+}
+
+// 仅供显式「所有账号」删除及来源关系检查使用;普通删除不展开。
+// 按 lineage 扩展到全部已关联物理副本;无 lineage 的会话映射回自身。
// 返回 [{ uid, id, lineageId }];uid 可能为空(脏索引),id 必有值。
// Copy guards consult provenance repeatedly. Rebuild its graph only after the
// meta-file fingerprint changes, rather than scanning every account per guard.
const lineageDeleteIndexes = new WeakMap();
-function collectLineageMembersForDelete(dataDir, sessionIds) {
+function collectLineageMembersForDelete(dataDir, sessionIds, relatedLineageIds) {
const config = readAutoCopyConfig(dataDir);
const ids = new Set(
(Array.isArray(sessionIds) ? sessionIds : [])
@@ -1360,6 +1400,7 @@ function collectLineageMembersForDelete(dataDir, sessionIds) {
const lineageId = pending[i];
if (seenLineages.has(lineageId)) continue;
seenLineages.add(lineageId);
+ if (relatedLineageIds) relatedLineageIds.add(lineageId);
const lineage = config.sessions[lineageId];
const origin = String(lineage.originLineageId || lineageId);
for (const related of lineagesByOrigin.get(origin) || []) {
@@ -2098,6 +2139,8 @@ module.exports = {
removeAutoCopySession,
removeAutoCopyAccount,
collectLineageMembersForDelete,
+ recordSessionDeletion,
+ isAutoCopyTargetExcluded,
getAutoCopyMapping,
getAutoCopyMappings,
migrateAutoCopyTargetRevisions,
diff --git a/scripts/win-launcher.js b/scripts/win-launcher.js
index a0ec07e..98a7abe 100644
--- a/scripts/win-launcher.js
+++ b/scripts/win-launcher.js
@@ -55,6 +55,7 @@ const { replaceFileWithRetry } = require('./atomic-file-write.js');
const { parseUiPortState, profileUiPortCandidates } = require('./ui-port.js');
const { getClientLaunchArgs } = require('./client-launch-settings.js');
const { getWorkBuddyLaunchEnv } = require('./workbuddy-launch-env.js');
+const { runPendingClientTempCleanup } = require('./client-temp.js');
const SCRIPTS_DIR = __dirname;
const WORKDADDY_APP_DIR = path.resolve(SCRIPTS_DIR, '..');
@@ -1188,6 +1189,9 @@ function launchWorkBuddy(wb) {
}
async function waitForWorkBuddyCdp(binary) {
+ await runPendingClientTempCleanup(DATA_DIR, PROFILE, {
+ isStopped: () => getWorkBuddyProcesses().length === 0,
+ });
const deadline = Date.now() + CDP_STARTUP_TIMEOUT_MS;
let retryWithoutCdpArg = false;
let retryOnNextPort = false;
@@ -1651,6 +1655,11 @@ async function ensureDaemonNative(nodeBin) {
}
async function waitForWorkBuddyCdpNative(binary) {
+ await runPendingClientTempCleanup(DATA_DIR, PROFILE, {
+ // Cleanup is optional: if CIM cannot verify even a headless/prewarm process,
+ // defer it rather than relying only on the native installation-path filter.
+ isStopped: () => !nativeWorkBuddyRunning() && getWorkBuddyProcesses().length === 0,
+ });
let restartedAfterHandoff = false;
let retriedAfterUpdate = false;
let installationChanged = false;
diff --git a/scripts/workbuddy-compat.js b/scripts/workbuddy-compat.js
index 1ecbce7..1953176 100644
--- a/scripts/workbuddy-compat.js
+++ b/scripts/workbuddy-compat.js
@@ -49,6 +49,52 @@
return findModernToolbar(doc) || findLegacyToolbar(doc);
}
+ // Shared geometry for conversation-owned overlays. The shell can remain
+ // mounted at its old size behind a fullscreen artifact preview.
+ function findConversationArea(doc, preferred) {
+ if (!doc || typeof doc.querySelectorAll !== 'function') return null;
+ var win = doc.defaultView;
+ function visibleRect(node) {
+ if (!node || node.isConnected === false) return null;
+ for (var p = node; p && p !== doc; p = p.parentElement) {
+ var css = win && win.getComputedStyle ? win.getComputedStyle(p) : null;
+ if (css && (css.display === 'none' || css.visibility === 'hidden' ||
+ css.visibility === 'collapse' || css.opacity === '0')) return null;
+ }
+ var box = node.getBoundingClientRect();
+ if (!box || box.width <= 0 || box.height <= 0) return null;
+ var left = Math.max(0, box.left), top = Math.max(0, box.top);
+ var right = Math.min(win && win.innerWidth || box.right, box.right);
+ var bottom = Math.min(win && win.innerHeight || box.bottom, box.bottom);
+ return right > left && bottom > top ? { left:left, top:top, right:right, bottom:bottom,
+ width:right-left, height:bottom-top } : null;
+ }
+ var own = preferred && preferred.closest && preferred.closest('.conversation-shell');
+ var shells = own ? [own] : Array.from(doc.querySelectorAll('.conversation-shell'));
+ // Only old clients may use the legacy chat host. A missing modern shell
+ // must not fall back to the teams grid or the whole application window.
+ if (!shells.length && !doc.querySelector('.teams-container,.conversation-page-chrome')) {
+ shells = Array.from(doc.querySelectorAll('.chat-container'));
+ }
+ var previews = Array.from(doc.querySelectorAll('.detail-panel-container'));
+ var fallback = shells.length ? { element:shells[0], rect:null } : null;
+ for (var i = 0; i < shells.length; i++) {
+ var rect = visibleRect(shells[i]);
+ if (!rect) continue;
+ for (var j = 0; j < previews.length && rect; j++) {
+ var cover = visibleRect(previews[j]);
+ if (!cover || cover.top > rect.top || cover.bottom < rect.bottom ||
+ cover.right <= rect.left || cover.left >= rect.right) continue;
+ if (cover.left <= rect.left && cover.right >= rect.right) rect = null;
+ else if (cover.right >= rect.right) rect.right = cover.left;
+ else if (cover.left <= rect.left) rect.left = cover.right;
+ if (rect) rect.width = rect.right - rect.left;
+ }
+ if (rect) return { element:shells[i], rect:rect };
+ }
+ return fallback;
+ }
+
function findMessageNavigationSurface(doc) {
if (!doc || typeof doc.querySelector !== 'function') return null;
try {
@@ -602,6 +648,7 @@
draftStorageKey: draftStorageKey,
collectMessageNavigationTurnsFromMessages: collectMessageNavigationTurnsFromMessages,
findComposerToolbar: findComposerToolbar,
+ findConversationArea: findConversationArea,
findCodeBuddySendButton: findCodeBuddySendButton,
findLegacyQueueAdapter: findLegacyQueueAdapter,
findModernQueueAdapter: findModernQueueAdapter,
diff --git a/test/automation-discovery.test.js b/test/automation-discovery.test.js
index eb86b68..2f50ee8 100644
--- a/test/automation-discovery.test.js
+++ b/test/automation-discovery.test.js
@@ -246,7 +246,10 @@ test('automation UI preloads discovery and exposes fuzzy task search and import'
assert.match(source, /wbs-auto-discovery-search/);
assert.match(source, /data-auto-discovery-import/);
assert.match(source, /发现更多自动化任务/);
- assert.match(source, /wbs-auto-discovery-pagination/);
+ assert.match(source, /matches\.forEach\(function \(task, index\)/);
+ assert.match(source, /wbs-auto-discovery-number/);
+ assert.match(source, /textContent = String\(index \+ 1\)/);
+ assert.doesNotMatch(source, /__wbsDiscoveryPage|data-auto-discovery-page|wbs-auto-discovery-pagination/);
assert.match(source, /我也要出现在这里/);
assert.match(source, /wbs-auto-discovery-head-actions \[data-auto-discovery-guide\]/);
assert.match(source, /git clone https:\/\/github\.com\/babygoton\/workdaddy-official-plugin\.git/);
diff --git a/test/cdp-targets.test.js b/test/cdp-targets.test.js
index a8227ca..1a1b169 100644
--- a/test/cdp-targets.test.js
+++ b/test/cdp-targets.test.js
@@ -34,11 +34,34 @@ test('classifyTarget 依据 app 包路径识别四客户端(含 %20 编码)'
});
test('classifyTarget 识别 Windows 安装目录中的 app.asar 页面', () => {
- assert.equal(classifyTarget(WIN_CN_URL, 'WorkBuddy'), 'workbuddy-cn');
+ assert.equal(classifyTarget(WIN_CN_URL, 'WorkBuddy'), null);
assert.equal(classifyTarget(WIN_AI_URL, 'WorkBuddy AI'), 'workbuddy-ai');
assert.equal(classifyTarget('file:///E:/WorkBuddy%20AI/resources/app.asar/renderer/index.html', 'WorkBuddy'), 'workbuddy-ai');
});
+test('Windows shared WorkBuddy path follows the bound profile and preserves AI isolation', () => {
+ const previous = process.env.WBSWITCH_PROFILE;
+ const shared = { type: 'page', url: WIN_CN_URL, title: 'WorkBuddy' };
+ const explicitAi = { type: 'page', url: WIN_AI_URL, title: 'WorkBuddy' };
+ const ai = PROFILES['workbuddy-ai'];
+ const cn = PROFILES['workbuddy-cn'];
+ try {
+ delete process.env.WBSWITCH_PROFILE;
+ assert.equal(isTargetForProfile(shared, ai), false);
+ process.env.WBSWITCH_PROFILE = 'workbuddy-ai';
+ assert.equal(isTargetForProfile(shared, ai), true);
+ assert.equal(selectPageTarget([shared], ai), shared);
+ assert.equal(isTargetForProfile(explicitAi, ai), true);
+ assert.equal(isTargetForProfile(explicitAi, cn), false);
+ process.env.WBSWITCH_PROFILE = 'workbuddy-cn';
+ assert.equal(isTargetForProfile(shared, cn), true);
+ assert.equal(selectPageTarget([shared], cn), shared);
+ } finally {
+ if (previous === undefined) delete process.env.WBSWITCH_PROFILE;
+ else process.env.WBSWITCH_PROFILE = previous;
+ }
+});
+
test('Windows custom target 按所选安装目录认领页面,允许 AI profile 显式绑定国内版', () => {
const profile = {
...PROFILES['workbuddy-ai'], customTarget: true,
@@ -54,8 +77,6 @@ test('Windows custom target 按所选安装目录认领页面,允许 AI profil
'file://other-host/E:/WorkBuddy/resources/index.html']) {
assert.equal(isTargetForProfile({ ...own, url }, profile), false, url);
}
- // 未配置 custom target 时,绑定端口也不能覆盖官方路径归属。
- assert.equal(isTargetForProfile(own, PROFILES['workbuddy-ai']), false);
});
test('Windows custom target 正确处理编码、大小写、路径边界及非官方目录', () => {
@@ -134,6 +155,7 @@ test('isTargetForProfile 企业配置只接受自身域名或路径提示', () =
const enterprise = {
...PROFILES['workbuddy-cn'],
customTarget: true,
+ appPath: '',
apiHost: 'https://api.ent.example.com',
targetHints: ['workbuddy-ent'],
};
@@ -163,6 +185,7 @@ test('isTargetForProfile Linux 双实例:CN 与 AI 互不认领(两端可执
const aiProfile = {
...PROFILES['workbuddy-ai'],
customTarget: true,
+ appPath: '',
apiHost: 'https://www.workbuddy.ai',
targetHints: ['/home/u/.local/share/workbuddy-ai/app', 'workbuddy-ai'],
};
diff --git a/test/client-launch-settings.test.js b/test/client-launch-settings.test.js
index 3293c21..03917f0 100644
--- a/test/client-launch-settings.test.js
+++ b/test/client-launch-settings.test.js
@@ -51,6 +51,7 @@ test('normal Windows startup and daemon relaunch both apply the persisted flags
const ctx = {
PROFILE: { id: 'workbuddy-ai', dataRoot: path.join(dir, '.workbuddy-ai'), cdp: { mode: 'environment' } }, DATA_DIR: dir, CDP_PORT: 9223,
process: { platform: 'win32', env: {} }, IS_WIN: true, IS_LINUX: false, path,
+ runPendingClientTempCleanup: async () => ({}),
getClientLaunchArgs, getWorkBuddyLaunchEnv, log() {}, selectCdpPort: async () => 9223,
resolveWorkBuddyBinary: () => 'C:\\WorkBuddyAI.exe', sleep: async () => {}, restoreWorkBuddyWindow: async () => {},
spawn: (command, args, options) => {
diff --git a/test/client-temp.test.js b/test/client-temp.test.js
new file mode 100644
index 0000000..14ed936
--- /dev/null
+++ b/test/client-temp.test.js
@@ -0,0 +1,223 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { inspectClientTemp, requestClientTempCleanup, runPendingClientTempCleanup } = require('../scripts/client-temp');
+
+function fixture(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-client-temp-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const profile = { id: 'workbuddy-cn' };
+ const root = path.join(dir, 'client-tmp', profile.id);
+ const old = new Date(Date.now() - 14 * 86400000);
+ function file(name, content = 'temporary', aged = true) {
+ const target = path.join(root, name);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, content);
+ if (aged) {
+ fs.utimesSync(target, old, old);
+ for (let parent = path.dirname(target); parent !== root; parent = path.dirname(parent)) fs.utimesSync(parent, old, old);
+ }
+ return target;
+ }
+ const inspect = () => inspectClientTemp(dir, profile, 'win32');
+ const request = enabled => requestClientTempCleanup(dir, profile, enabled, 'win32');
+ const run = (isStopped = () => true) => runPendingClientTempCleanup(dir, profile, { platform: 'win32', isStopped });
+ return { dir, root, profile, file, inspect, request, run };
+}
+
+test('#507 cleanup is opt-in, survives restart, and stays inside the current profile', async t => {
+ const f = fixture(t);
+ const target = f.file('old-cache/data');
+ const sibling = path.join(f.dir, 'client-tmp/workbuddy-ai/keep');
+ const account = path.join(f.dir, 'accounts/keep');
+ for (const file of [sibling, account]) { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, 'keep'); }
+ assert.equal((await f.inspect()).cleanableBytes, 9);
+ await f.run(() => { throw Error('no request must not query processes'); });
+ assert.ok(fs.existsSync(target));
+ f.request(true);
+ assert.equal((await f.inspect()).pending, true);
+ const result = await f.run();
+ assert.equal(result.removedBytes, 9);
+ assert.equal(fs.existsSync(target), false);
+ assert.ok(fs.existsSync(sibling));
+ assert.ok(fs.existsSync(account));
+ assert.equal((await f.inspect()).pending, false);
+});
+
+test('recent trees and official updater caches are retained as whole entries', async t => {
+ const f = fixture(t);
+ const oldInActive = f.file('active/old');
+ const recent = f.file('active/recent', 'new', false);
+ const installer = f.file('WorkBuddy-Update-x64/WorkBuddy-Setup-9.exe');
+ const nestedInstaller = f.file('nested/workbuddy-update-arm64/Setup.exe');
+ const old = f.file('unused/file');
+ assert.equal((await f.inspect()).cleanableBytes, 9);
+ f.request(true);
+ await f.run();
+ for (const file of [oldInActive, recent, installer, nestedInstaller]) assert.ok(fs.existsSync(file), file);
+ assert.equal(fs.existsSync(old), false);
+});
+
+test('running, unknown and failed process checks never authorize deletion', async t => {
+ const f = fixture(t);
+ const file = f.file('keep');
+ f.request(true);
+ for (const check of [() => false, () => undefined, () => { throw Error('query failed'); }]) {
+ await f.run(check);
+ assert.ok(fs.existsSync(file));
+ assert.equal((await f.inspect()).pending, true);
+ }
+ f.request(false);
+ await f.run();
+ assert.ok(fs.existsSync(file));
+});
+
+test('files changed since the cleanup request remain untouched', async t => {
+ const f = fixture(t);
+ const file = f.file('changed');
+ f.request(true);
+ fs.writeFileSync(file, 'active');
+ await f.run();
+ assert.equal(fs.readFileSync(file, 'utf8'), 'active');
+});
+
+test('links, hardlinks and linked roots cannot lead cleanup outside the managed directory', async t => {
+ const f = fixture(t);
+ const outside = path.join(f.dir, 'outside');
+ fs.mkdirSync(outside);
+ const keep = path.join(outside, 'keep');
+ fs.writeFileSync(keep, 'outside');
+ f.file('old');
+ fs.linkSync(keep, path.join(f.root, 'hardlink'));
+ fs.symlinkSync(outside, path.join(f.root, 'linked'), process.platform === 'win32' ? 'junction' : 'dir');
+ f.request(true);
+ await f.run();
+ assert.equal(fs.readFileSync(keep, 'utf8'), 'outside');
+ assert.ok(fs.lstatSync(path.join(f.root, 'linked')).isSymbolicLink());
+ fs.rmSync(f.root, { recursive: true });
+ fs.symlinkSync(outside, f.root, process.platform === 'win32' ? 'junction' : 'dir');
+ f.request(true);
+ await assert.rejects(f.inspect(), /目录/);
+ await f.run();
+ assert.equal(fs.readFileSync(keep, 'utf8'), 'outside');
+});
+
+test('unsupported platforms/profiles and malformed requests cannot schedule cleanup', async t => {
+ const f = fixture(t);
+ for (const [profile, platform] of [[f.profile, 'darwin'], [{ id: 'codebuddy-cn' }, 'win32'], [{ id: '../escape' }, 'win32'], [{ id: 'workbuddy-cn', customTarget: true }, 'win32']]) {
+ assert.equal((await inspectClientTemp(f.dir, profile, platform)).supported, false);
+ assert.throws(() => requestClientTempCleanup(f.dir, profile, true, platform));
+ }
+ for (const value of [null, 1, 'true', {}, undefined]) assert.throws(() => f.request(value));
+});
+
+test('locked files are skipped, never reported as successfully removed', async t => {
+ const f = fixture(t);
+ const file = f.file('locked');
+ f.request(true);
+ const real = fs.promises.rm;
+ t.mock.method(fs.promises, 'rm', async (target, options) => {
+ if (target === file) throw Object.assign(Error('locked'), { code: 'EBUSY' });
+ return real(target, options);
+ });
+ const result = await f.run();
+ assert.equal(result.removedBytes, 0);
+ assert.equal(result.skippedEntries, 1);
+ assert.ok(fs.existsSync(file));
+});
+
+test('a late cancellation or client start prevents removal after the scan', async t => {
+ for (const cancel of [false, true]) {
+ const f = fixture(t);
+ const file = f.file('old');
+ f.request(true);
+ let calls = 0;
+ await f.run(() => {
+ if (++calls === 1) { if (cancel) f.request(false); return true; }
+ return false;
+ });
+ assert.ok(fs.existsSync(file));
+ }
+});
+
+test('a concurrent launch cannot pass an active cleanup lock, even after cancellation', async t => {
+ const f = fixture(t);
+ f.file('old');
+ f.request(true);
+ f.request(false);
+ const lock = path.join(f.dir, '.client-temp-cleanup-workbuddy-cn.lock');
+ fs.writeFileSync(lock, String(process.pid));
+ await assert.rejects(f.run(), /清理/);
+ fs.unlinkSync(lock);
+});
+
+test('client temp API accepts only a scheduling flag and never deletes in the renderer request', async t => {
+ const f = fixture(t);
+ const file = f.file('old');
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const start = source.indexOf(" if (req.method === 'GET' && p === '/api/client-temp')");
+ const end = source.indexOf(" if (req.method === 'GET' && p === '/api/client-launch-settings')", start);
+ const handler = new Function('req', 'p', 'res', 'PROFILE', 'DATA_DIR', 'process', 'readBody', 'json',
+ 'inspectClientTemp', 'requestClientTempCleanup', source.slice(start, end));
+ const call = (method, body, platform = 'win32') => handler({ method }, '/api/client-temp', {}, f.profile, f.dir, { platform },
+ async () => body, (_, status, data) => ({ status, data }),
+ (dir, profile) => inspectClientTemp(dir, profile, platform),
+ (dir, profile, enabled) => requestClientTempCleanup(dir, profile, enabled, platform));
+ assert.equal((await call('GET')).data.cleanableBytes, 9);
+ assert.equal((await call('POST', { pending: true, path: '../accounts' })).data.pending, true);
+ assert.ok(fs.existsSync(file));
+ assert.equal((await call('POST', { pending: 'true' })).status, 400);
+ assert.equal((await call('POST', { pending: true }, 'darwin')).status, 400);
+ assert.equal((await call('POST', { pending: false })).data.pending, false);
+});
+
+test('all Windows launch paths await cleanup before spawning and use a strict process query', () => {
+ const launcher = fs.readFileSync(path.join(__dirname, '../scripts/win-launcher.js'), 'utf8');
+ for (const name of ['waitForWorkBuddyCdp', 'waitForWorkBuddyCdpNative']) {
+ const part = launcher.slice(launcher.indexOf(`async function ${name}(`));
+ assert.ok(part.indexOf('await runPendingClientTempCleanup(') < part.indexOf('launchWorkBuddy(binary)'));
+ assert.match(part.slice(0, part.indexOf('launchWorkBuddy(binary)')), /getWorkBuddyProcesses\(\)\.length === 0/);
+ }
+ const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const part = daemon.slice(daemon.indexOf('function relaunchWorkBuddy()'));
+ assert.ok(part.indexOf('await runPendingClientTempCleanup(') < part.indexOf('spawn(command, args'));
+ assert.match(part.slice(0, part.indexOf('spawn(command, args')), /verifiedWindowsWorkBuddyProcesses\(command\)\.length === 0/);
+});
+
+test('about-page cleanup is on demand, exposes cancellation and recovers from save failure', async () => {
+ const vm = require('node:vm');
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+ const start = source.indexOf(' function wireClientTempCleanup()');
+ const end = source.indexOf(' function wireClientLaunchSettings()', start);
+ const element = () => ({ disabled: false, textContent: '', events: {}, addEventListener(name, fn) { this.events[name] = fn; } });
+ const scan = element(), clean = element(), status = element();
+ let reads = 0, fail = false, pending = true;
+ const context = {
+ WBS_BRAND: 'WorkDaddy', registerDisposer() {},
+ aboutPane: { querySelector: () => ({ querySelector: selector => ({ '#wbs-client-temp-status': status, '#wbs-client-temp-scan': scan, '#wbs-client-temp-clean': clean })[selector] }) },
+ api: async (_, options) => {
+ if (!options) { reads++; return { supported: true, pending, bytes: 20, cleanableBytes: 10 }; }
+ if (fail) throw Error('write failed');
+ pending = JSON.parse(options.body).pending;
+ return { supported: true, pending };
+ },
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ context.wireClientTempCleanup();
+ assert.equal(reads, 0, 'opening About must not walk the filesystem');
+ await scan.events.click();
+ assert.equal(clean.textContent, '取消清理');
+ fail = true;
+ clean.events.click();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(clean.disabled, false);
+ assert.equal(pending, true);
+ fail = false;
+ clean.events.click();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(pending, false);
+ assert.equal(clean.textContent, '下次启动清理');
+});
diff --git a/test/conversation-area.test.js b/test/conversation-area.test.js
new file mode 100644
index 0000000..99101db
--- /dev/null
+++ b/test/conversation-area.test.js
@@ -0,0 +1,75 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const compat = require('../scripts/workbuddy-compat');
+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
+function element(x, y, width, height, parentElement = null) {
+ return { isConnected: true, parentElement, css: {},
+ rect: { x, y, left:x, top:y, width, height, right:x+width, bottom:y+height },
+ getBoundingClientRect() { return this.rect; }, closest() { return this.shell || null; } };
+}
+function harness() {
+ const parent = element(240,64,1160,836), shell = element(240,64,700,836,parent);
+ shell.shell = shell;
+ const preview = element(940,0,460,900);
+ const doc = {
+ defaultView: {innerWidth:1400,innerHeight:900,getComputedStyle:n=>({display:'block',visibility:'visible',opacity:'1',...n.css})},
+ querySelector: selector => selector.includes('teams-container') ? parent : null,
+ querySelectorAll: selector => selector === '.conversation-shell' ? [shell] : selector === '.detail-panel-container' ? [preview] : [],
+ };
+ return { doc, shell, preview, parent };
+}
+test('conversation area uses shell width independently from the WorkBuddy viewport', () => {
+ const h = harness();
+ const area = compat.findConversationArea(h.doc);
+ assert.equal(area.element,h.shell);
+ assert.equal(area.rect.width,700);
+ assert.equal(area.rect.right,940);
+});
+test('fullscreen file preview hides a still-mounted, nonzero chat shell and restores it on exit', () => {
+ const h = harness();
+ const split = h.preview.rect;
+ h.preview.rect = element(0,0,1400,900).rect;
+ assert.equal(compat.findConversationArea(h.doc).rect,null);
+ assert.equal(h.shell.rect.width,700);
+ h.preview.rect = split;
+ assert.equal(compat.findConversationArea(h.doc).rect.width,700);
+});
+test('partial overlay and viewport clipping constrain the usable chat area', () => {
+ const h = harness();
+ h.shell.rect = element(240,64,1160,836).rect;
+ assert.equal(compat.findConversationArea(h.doc).rect.width,700);
+ h.preview.css.display='none'; h.doc.defaultView.innerWidth=1000;
+ assert.equal(compat.findConversationArea(h.doc).rect.width,760);
+});
+test('hidden ancestors, zero size and unmounted chat never fall back to teams main content', () => {
+ const h = harness();
+ h.parent.css.visibility='hidden'; assert.equal(compat.findConversationArea(h.doc).rect,null);
+ h.parent.css={opacity:'0'}; assert.equal(compat.findConversationArea(h.doc).rect,null);
+ h.parent.css={}; h.shell.rect=element(240,64,0,0).rect;
+ assert.equal(compat.findConversationArea(h.doc).rect,null);
+ h.doc.querySelectorAll=()=>[];
+ assert.equal(compat.findConversationArea(h.doc),null);
+});
+test('message navigation selects its own shell when several conversations are mounted', () => {
+ const h=harness(), other=element(20,64,300,836), viewport=element(240,64,700,700);
+ viewport.shell=h.shell;
+ h.doc.querySelectorAll=selector=>selector==='.conversation-shell'?[other,h.shell]:[];
+ assert.equal(compat.findConversationArea(h.doc,viewport).element,h.shell);
+});
+test('robot hides with absent chat without overriding panel-open state, then restores', () => {
+ const classes=new Set(), fab={classList:{contains:x=>classes.has(x),toggle:(x,on)=>on?classes.add(x):classes.delete(x)}};
+ let area=null, positions=0;
+ const ctx={CAPS:{},root:{querySelector:()=>fab},document:{querySelector:()=>({})},WBS_COMPAT:{findConversationArea:()=>area},
+ ensureFabAnchorObserver(){},fabDrag:null,fabQuietMode:{wake(){}},messageNavigation:{updateLayout(){}},
+ readFabBottom:()=>null,fabAnchorOffsets:()=>({right:22,bottom:22}),applyFabPosition:()=>positions++};
+ const start=source.indexOf(' function positionFab()');
+ vm.runInNewContext(source.slice(start,source.indexOf(' setBuildTimeout(scheduleFabPos',start)),ctx);
+ ctx.positionFab(); assert.equal(classes.has('is-area-hidden'),true); assert.equal(positions,0);
+ area={element:{},rect:element(0,0,1000,800).rect}; classes.add('hidden');
+ ctx.positionFab(); assert.equal(classes.has('is-area-hidden'),false);assert.equal(classes.has('hidden'),true);assert.equal(positions,0);
+ classes.delete('hidden');ctx.positionFab();assert.equal(positions,1);
+ area=null;ctx.CAPS.nativeComposer=true;ctx.positionFab();assert.equal(classes.has('is-area-hidden'),false,'native IDE clients retain their existing fallback');
+});
diff --git a/test/fab-quiet-mode.test.js b/test/fab-quiet-mode.test.js
index 9a11126..569ce9c 100644
--- a/test/fab-quiet-mode.test.js
+++ b/test/fab-quiet-mode.test.js
@@ -5,7 +5,7 @@ const vm = require('node:vm');
const test = require('node:test');
const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
-function harness(enabled = true) {
+function harness(enabled = true, edge) {
const start = source.indexOf('function createFabQuietMode(');
assert.notEqual(start, -1);
const end = source.indexOf('// Keep the decision logic', start);
@@ -30,7 +30,7 @@ function harness(enabled = true) {
vm.runInContext(source.slice(start, end), context);
const mode = context.createFabQuietMode({ fab, window: win, document: doc,
storage, settingKey: 'dock-test',
- isDragging: () => dragging,
+ isDragging: () => dragging, rightEdge: () => edge === undefined ? win.innerWidth : edge,
listen: (target, type, fn) => listeners.push({ target, type, fn }),
});
return { mode, fab, doc, button, classes, timers, win, saved,
@@ -108,3 +108,19 @@ test('resize uses the new viewport and saved vertical position; disposal cancels
h.tick();
assert(!h.classes.has('is-quiet'));
});
+
+test('quiet robot docks and wakes at the chat edge rather than the file preview edge', () => {
+ const h=harness(true,700);h.fab.style.right='322px';h.tick();
+ assert.equal(h.fab.style['--wbs-fab-quiet-shift'],'59px');
+ const scale=0.5, shift=parseFloat(h.fab.style['--wbs-fab-quiet-shift']);
+ const clip=parseFloat(h.fab.style['--wbs-fab-quiet-clip']);
+ const paintedRight=h.win.innerWidth-parseFloat(h.fab.style.right)+shift-clip*scale;
+ assert.equal(paintedRight,700,'docked robot must be clipped at the chat edge, before the file preview');
+ assert.match(source,/\.wbs-fab\.is-quiet\{[^}]*clip-path:inset\(-100px var\(--wbs-fab-quiet-clip,0px\) -100px -100px\)/);
+ h.fire(h.win,'pointermove',{clientX:990,clientY:658});
+ assert(h.classes.has('is-quiet'),'pointer over preview must not wake robot');
+ h.fire(h.win,'pointermove',{clientX:690,clientY:658});
+ assert(!h.classes.has('is-quiet'));
+ h.classes.add('is-area-hidden');h.mode.wake();
+ assert.equal(h.timers.size,0,'hidden chat cancels docking timer');
+});
diff --git a/test/message-navigation.test.js b/test/message-navigation.test.js
index da24845..2cf9706 100644
--- a/test/message-navigation.test.js
+++ b/test/message-navigation.test.js
@@ -17,33 +17,29 @@ function navigationFunction(name, context) {
return context[name];
}
-test('resizing a narrow window hides navigation, closes previews and cancels dragging; widening restores it', () => {
+test('chat width controls navigation and fullscreen previews cancel dragging and hide flyouts', () => {
const style = { setProperty() {} };
let previewOpen = true, cancelled = false;
+ const area = { rect: { left:240, right:1240, top:40, bottom:840, width:1000, height:800 } };
const context = {
- root: { style }, surface: { viewportElement: { getBoundingClientRect: () => ({ left: 240, top: 40, width: 1000, height: 800 }) } },
- hidden: false, window: { innerWidth: 1440 }, turns: [{ id: 'a' }, { id: 'b' }],
- dragPointerId: 7, positionFlyouts() {},
- hideTooltip(immediate) { assert.equal(immediate, true); previewOpen = false; },
- finishNavDrag(event, cancel) { assert.equal(event.pointerId, 7); cancelled = cancel; context.dragPointerId = null; },
+ root: { style }, surface: { viewportElement: { getBoundingClientRect: () => ({ left:240, top:40, right:1240, bottom:840, width:1000, height:800 }) } },
+ WBS_COMPAT: { findConversationArea: () => area }, document: {},
+ hidden: false, window: { innerWidth:1440 }, turns: [{id:'a'},{id:'b'}],
+ dragPointerId:7, positionFlyouts() {},
+ hideTooltip(immediate) { assert.equal(immediate,true); previewOpen=false; },
+ finishNavDrag(event,cancel) { assert.equal(event.pointerId,7);cancelled=cancel;context.dragPointerId=null; },
};
- const position = navigationFunction('position', context);
- position();
- assert.equal(style.display, 'block');
- context.window.innerWidth = 1280;
- position();
- assert.equal(style.display, 'none');
- assert.equal(previewOpen, false);
- assert.equal(cancelled, true);
- assert.equal(context.hidden, false, 'responsive hiding must not disable the feature or lose its loaded turns');
- context.window.innerWidth = 1281;
- position();
- assert.equal(style.display, 'block');
- assert.equal(previewOpen, false, 'expanding the window must not reopen an old preview');
- context.hidden = true;
- style.display = 'none';
- position();
- assert.equal(style.display, 'none', 'resizing must not enable disabled or empty navigation');
+ const position=navigationFunction('position',context);
+ position(); assert.equal(style.display,'block');
+ area.rect.width=799; area.rect.right=1039;
+ position(); assert.equal(style.display,'none');assert.equal(previewOpen,false);assert.equal(cancelled,true);
+ assert.equal(context.hidden,false,'layout changes preserve the user setting and loaded turns');
+ area.rect.width=900;area.rect.right=1140;context.window.innerWidth=1200;
+ position();assert.equal(style.display,'block','a narrow window can still have a wide enough chat');
+ area.rect=null;position();assert.equal(style.display,'none','fullscreen preview occlusion hides the index');
+ area.rect={left:240,right:1140,top:40,bottom:840,width:900,height:800};
+ position();assert.equal(style.display,'block');assert.equal(previewOpen,false);
+ context.hidden=true;style.display='none';position();assert.equal(style.display,'none');
});
test('navigation displays at most 20 evenly spaced markers while retaining both conversation ends', () => {
diff --git a/test/session-delete-confinement.test.js b/test/session-delete-confinement.test.js
index 30a2f84..50d7b5d 100644
--- a/test/session-delete-confinement.test.js
+++ b/test/session-delete-confinement.test.js
@@ -250,7 +250,7 @@ test('delete route validates before SQL and deletes the matched set only', () =>
assert.match(route, /for \(const id of matchedIds\) filesRemoved \+= deleteSessionFiles\(wbHome, id\)/);
assert.doesNotMatch(route, /for \(const id of ids\) filesRemoved/);
const filesAt = route.indexOf('for (const id of matchedIds) filesRemoved += deleteSessionFiles');
- const rulesAt = route.indexOf('for (const row of matchedRows)');
+ const rulesAt = route.indexOf('recordSessionDeletion(DATA_DIR, matchedRows, { preserveMembers: true })');
const deleteAt = route.indexOf('DELETE FROM sessions WHERE id IN');
assert.ok(filesAt >= 0 && filesAt < rulesAt && rulesAt < deleteAt,
'filesystem and rule cleanup must succeed before the retry anchor is removed from the database');
@@ -293,7 +293,7 @@ test('delete route accepts more than 100 session IDs in one request', async (t)
...loadSessionDeleteHelpers(),
normalizeSessionIdBatch,
collectLineageMembersForDelete: (_dataDir, requested) => requested.map((id) => ({ id })),
- removeAutoCopySession: () => false,
+ recordSessionDeletion: () => 0, crypto: require('node:crypto'),
DATA_DIR: root,
PROFILE: { dataRoot: root },
req: { method: 'POST' },
@@ -313,7 +313,7 @@ test('delete route accepts more than 100 session IDs in one request', async (t)
assert.deepEqual(await db.all('SELECT id FROM sessions'), []);
});
-test('delete route removes recorded copies across accounts from both DB and files', async (t) => {
+for (const scope of ['selected', 'lineage']) test('#511 delete scope is explicit: ' + scope, async (t) => {
const lib = require('../scripts/lib.js');
const { createSessionDb, normalizeSessionIdBatch } = require('../scripts/session-db.js');
const root = tempDir(t);
@@ -338,22 +338,50 @@ test('delete route removes recorded copies across accounts from both DB and file
...loadSessionDeleteHelpers(),
normalizeSessionIdBatch,
collectLineageMembersForDelete: lib.collectLineageMembersForDelete,
- removeAutoCopySession: lib.removeAutoCopySession,
+ ...lib, crypto: require('node:crypto'),
DATA_DIR: root, PROFILE: { dataRoot: root },
req: { method: 'POST' }, res: {}, p: '/api/sessions/delete',
- readBody: async () => ({ ids: ['copy-a'] }),
+ readBody: async () => ({ ids: ['copy-a'], scope, preview: true }),
sqliteQuery: (sql, params) => db.all(sql, Array.from(params)),
sqliteRun: (sql, params) => db.run(sql, Array.from(params)),
sqlPlaceholders: ids => ids.map(() => '?').join(','),
json: (_, status, body) => ({ status, body }), log() {},
});
- const result = await vm.runInContext('(async function () {\n' + source.slice(start, end) + '\n})()', ctx);
+ const run = () => vm.runInContext('(async function () {\n' + source.slice(start, end) + '\n})()', ctx);
+ const preview = await run();
+ assert.equal(preview.status, 200);
+ assert.equal(preview.body.total, scope === 'selected' ? 1 : 3);
+ assert.equal((await db.all('SELECT id FROM sessions')).length, 4, 'preview must not delete');
+ ctx.readBody = async () => ({ ids: ['copy-a'], scope });
+ if (scope === 'lineage') {
+ assert.equal((await run()).status, 409, 'cross-account delete requires preview confirmation');
+ await db.run('INSERT INTO sessions (id, user_id) VALUES (?, ?)', ['late-copy', 'fourth']);
+ lib.addAutoCopySessionMember(root, original, 'fourth', 'late-copy');
+ ctx.readBody = async () => ({ ids: ['copy-a'], scope, previewToken: preview.body.previewToken });
+ assert.equal((await run()).status, 409, 'a changed family requires another preview');
+ ctx.readBody = async () => ({ ids: ['copy-a'], scope, preview: true });
+ const updated = await run();
+ ctx.readBody = async () => ({ ids: ['copy-a'], scope, previewToken: updated.body.previewToken });
+ }
+ const retryBody = await ctx.readBody();
+ const write = ctx.sqliteRun;
+ ctx.sqliteRun = async () => { throw new Error('database locked'); };
+ assert.equal((await run()).status, 500);
+ ctx.sqliteRun = write;
+ ctx.readBody = async () => ({ ids: ['copy-a'], scope, preview: true });
+ const retryPreview = await run();
+ assert.equal(retryPreview.body.total, scope === 'selected' ? 1 : 4, 'DB failure preserves the family for retry');
+ ctx.readBody = async () => retryBody;
+ const result = await run();
assert.equal(result.status, 200);
- assert.equal(result.body.deleted, 3);
- assert.equal(result.body.cascaded, 2);
- assert.deepEqual(await db.all('SELECT id FROM sessions'), [{ id: 'unrelated' }]);
- assert.deepEqual(fs.readdirSync(path.join(root, 'tasks')), ['unrelated']);
+ assert.equal(result.body.deleted, scope === 'selected' ? 1 : 4);
+ assert.equal(result.body.cascaded, scope === 'selected' ? 0 : 3);
+ const expected = scope === 'selected' ? ['copy-third', 'session-a', 'unrelated'] : ['unrelated'];
+ assert.deepEqual((await db.all('SELECT id FROM sessions ORDER BY id')).map(row => row.id), expected);
+ assert.deepEqual(fs.readdirSync(path.join(root, 'tasks')).sort(), expected);
assert.equal(lib.getAutoCopySession(root, 'target', 'unrelated').enabled, true);
+ assert.equal(lib.isAutoCopyTargetExcluded(root, original, 'target'), true);
+ assert.equal(lib.isAutoCopyTargetExcluded(root, split, 'target'), true);
});
test('configured data root may be a directory junction while child links still fail closed', (t) => {
diff --git a/test/session-delete-ui.test.js b/test/session-delete-ui.test.js
index 4e9f1e3..4c21ba9 100644
--- a/test/session-delete-ui.test.js
+++ b/test/session-delete-ui.test.js
@@ -27,44 +27,71 @@ function harness() {
return { ctx, requests, nodes, ok: nodes['#wbs-sess-modal-ok'] };
}
-test('all-account deletion requires two confirmations and freezes the selected IDs', async () => {
+const flush = () => new Promise(resolve => setImmediate(resolve));
+async function preview(h, index = 0, total = 3) {
+ h.requests[index].resolve({ previewToken: 'range-token', total, accounts: 2 });
+ await flush();
+}
+
+test('all-account deletion previews the range, requires two confirmations and freezes IDs', async () => {
const h = harness(), selected = ['selected-session'];
h.ctx.openDeleteModal(selected, true);
selected.push('later-selection');
- assert.equal(h.requests.length, 0);
+ assert.deepEqual(JSON.parse(h.requests[0].options.body), { ids: ['selected-session'], scope: 'lineage', preview: true });
+ assert.equal(h.ok.disabled, true);
+ h.ok.onclick(); assert.equal(h.requests.length, 1);
+ await preview(h);
+ assert.match(h.nodes['#wbs-sess-modal-body'].textContent, /3 个会话.*2 个账号/);
h.ok.onclick();
- assert.equal(h.requests.length, 0, 'first confirmation must not delete');
+ assert.equal(h.requests.length, 1, 'first confirmation must not delete');
assert.match(h.nodes['#wbs-sess-modal-title'].textContent, /再次确认/);
h.ok.onclick(); h.ok.onclick();
- assert.equal(h.requests.length, 1, 'ignore duplicate submission');
- assert.equal(h.ok.disabled, true, 'delete button is disabled while the request is pending');
- assert.equal(h.ok.classList.contains('is-loading'), true, 'delete button shows loading while the request is pending');
+ assert.equal(h.requests.length, 2, 'ignore duplicate submission');
+ assert.equal(h.ok.disabled, true);
+ assert.equal(h.ok.classList.contains('is-loading'), true);
assert.equal(h.ok.getAttribute('aria-busy'), 'true');
assert.equal(h.ok.textContent, '删除中…');
- assert.equal(h.requests[0].route, '/api/sessions/delete');
- assert.deepEqual(JSON.parse(h.requests[0].options.body).ids, ['selected-session']);
- h.requests[0].resolve({ deleted: 3, cascaded: 2 });
- await new Promise(resolve => setImmediate(resolve));
+ assert.deepEqual(JSON.parse(h.requests[1].options.body), { ids: ['selected-session'], scope: 'lineage', previewToken: 'range-token' });
+ h.requests[1].resolve({ deleted: 3, cascaded: 2 });
+ await flush();
assert.equal(h.ctx.open, false);
});
-test('cancelling the second confirmation sends no deletion request', () => {
- const h = harness(); h.ctx.openDeleteModal(['selected-session'], true);
- h.ok.onclick(); h.ctx.showSessModal(false);
- assert.equal(h.requests.length, 0);
- assert.equal(h.ok.onclick, null);
+test('cancelling either preview or second confirmation sends no deletion', async () => {
+ for (const stage of ['preview', 'confirmation']) {
+ const h = harness(); h.ctx.openDeleteModal(['selected-session'], true);
+ if (stage === 'confirmation') { await preview(h); h.ok.onclick(); }
+ h.ctx.showSessModal(false);
+ if (stage === 'preview') await preview(h);
+ assert.equal(h.requests.length, 1);
+ assert.equal(h.ok.onclick, null);
+ }
});
-test('existing deletion retains its single confirmation and errors permit retry', async () => {
+test('ordinary deletion sends selected scope and requires a fresh preview after failure', async () => {
const h = harness(); h.ctx.openDeleteModal(['selected-session']);
- h.ok.onclick(); assert.equal(h.requests.length, 1);
- h.requests[0].reject(Error('locked'));
- await new Promise(resolve => setImmediate(resolve));
- assert.equal(h.ok.disabled, false);
+ await preview(h, 0, 1);
+ assert.match(h.nodes['#wbs-sess-modal-body'].textContent, /保留其他副本/);
+ h.ok.onclick();
+ assert.equal(JSON.parse(h.requests[1].options.body).scope, 'selected');
+ h.requests[1].reject(Error('locked')); await flush();
+ assert.equal(h.requests.length, 3);
+ assert.equal(JSON.parse(h.requests[2].options.body).preview, true);
+ assert.equal(h.ok.disabled, true);
assert.equal(h.ok.classList.contains('is-loading'), false);
assert.equal(h.ok.getAttribute('aria-busy'), null);
- assert.equal(h.ok.textContent, '确定');
- assert.equal(h.ctx.open, true);
+ h.ok.onclick(); assert.equal(h.requests.length, 3);
+ await preview(h, 2, 1);
+ h.ok.onclick(); assert.equal(h.requests.length, 4);
+});
+
+test('failed or stale previews cannot enable deletion in another dialog', async () => {
+ const h = harness(); h.ctx.openDeleteModal(['old']);
+ h.ctx.showSessModal(false); h.ctx.openDeleteModal(['new']);
+ await preview(h);
+ assert.equal(h.ok.disabled, true);
+ h.requests[1].reject(Error('offline')); await flush();
+ assert.equal(h.ok.disabled, true);
h.ok.onclick(); assert.equal(h.requests.length, 2);
});
diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.js
index 89a5374..ffb3158 100644
--- a/test/session-sync-daemon.test.js
+++ b/test/session-sync-daemon.test.js
@@ -54,6 +54,12 @@ function harness(t, withPlanner = false) {
const row = rows.get(params[0]); return row && (!params[1] || params[1] === row.user_id) && (!_.includes('deleted_at IS NULL') || row.deleted_at == null) ? [{ ...row }] : [];
},
sqliteRun: async (_, params) => {
+ if (_.startsWith('UPDATE sessions SET title = ?, custom_title = ?, updated_at = ?')) {
+ const row = rows.get(params[3]);
+ assert.ok(row); Object.assign(row, { title: params[0], custom_title: params[1], updated_at: params[2] });
+ return { changes: 1 };
+ }
+
if (_.startsWith('UPDATE sessions SET deleted_at = ?')) {
let changes = 0;
for (let i = 2; i < params.length; i += 2) {
@@ -1105,3 +1111,143 @@ test('copy completion preserves timestamps of concurrent source and target dirty
assert.equal(h.ctx.getSessionDirtyIndex().get('two', 'b').at, at + 1);
assert.equal((await h.switchTo('two', 'three')).length, 1);
});
+
+for (const field of ['title', 'custom_title']) test('#511 title-only edit syncs without rewriting messages: ' + field, async t => {
+ const h = harness(t, true);
+ await h.copy();
+ const before = fs.readFileSync(h.file('b'));
+ h.rows.get('a')[field] = 'renamed';
+ h.rows.get('a').updated_at = 200;
+ assert.equal((await h.ctx.buildAutoCopyPlan('one', 'two')).length, 1, 'a clean renderer baseline must not hide renames');
+ const result = await h.copy();
+ assert.equal(result.status, 'copied');
+ assert.equal(h.rows.get('b')[field], 'renamed');
+ assert.deepEqual(fs.readFileSync(h.file('b')), before);
+ assert.equal(h.rows.get('c')[field] || '', field === 'title' ? 'fixture' : '');
+ assert.equal((await h.copy()).status, 'skipped');
+});
+
+test('#511 independent title edits are preserved as a conflict', async t => {
+ const h = harness(t);
+ await h.copy();
+ h.rows.get('a').custom_title = 'source edit';
+ h.rows.get('b').custom_title = 'target edit';
+ const result = await h.copy();
+ assert.equal(result.status, 'conflict');
+ assert.equal(h.rows.get('a').custom_title, 'source edit');
+ assert.equal(h.rows.get('b').custom_title, 'target edit');
+});
+
+test('#511 deleting a local copy preserves siblings and stops automatic recreation across restart', async t => {
+ const h = harness(t);
+ await h.copy();
+ lib.recordSessionDeletion(h.root, [{ id: 'b', user_id: 'two' }]);
+ h.rows.delete('b'); fs.unlinkSync(h.file('b'));
+ for (let i = 0; i < 2; i++) assert.equal((await h.copy()).status, 'skipped');
+ assert.deepEqual([...h.rows.keys()], ['a', 'c']);
+ assert.equal(lib.isAutoCopyTargetExcluded(h.root, h.lineage, 'two'), true);
+ const manual = await h.ctx.copySessionRecord(h.rows.get('a'), 'two');
+ assert.equal(manual.status, 'copied', 'explicit manual sync can restore a copy');
+});
+
+for (const direction of ['target', 'reverse']) test('#511 rename sync resolves direction: ' + direction, async t => {
+ const h = harness(t, true);
+ await h.copy();
+ h.rows.get('b').custom_title = 'renamed on account two';
+ const from = direction === 'reverse' ? 'b' : 'a';
+ const to = direction === 'reverse' ? 'one' : 'two';
+ const result = await h.ctx.copySessionRecord(h.rows.get(from), to, { auto: true, lineageId: h.lineage });
+ assert.equal(result.status, 'copied');
+ assert.equal(h.rows.get('a').custom_title, 'renamed on account two');
+});
+
+test('#511 clearing a custom title propagates even with a clean lifecycle baseline', async t => {
+ const h = harness(t, true);
+ h.rows.get('a').custom_title = h.rows.get('b').custom_title = 'previous name';
+ await h.copy();
+ const dirty = h.ctx.getSessionDirtyIndex();
+ dirty.markBaseline('one'); dirty.clear('one', 'a');
+ h.rows.get('a').custom_title = '';
+ assert.equal((await h.ctx.buildAutoCopyPlan('one', 'two')).length, 1);
+ assert.equal((await h.copy()).status, 'copied');
+ assert.equal(h.rows.get('b').custom_title, '');
+});
+
+test('#511 successive renames propagate through account switches and back', async t => {
+ const h = harness(t, true);
+ const copy = (id, uid) => h.ctx.copySessionRecord(h.rows.get(id), uid, { auto: true, lineageId: h.lineage });
+ await copy('a', 'two'); await copy('b', 'one');
+ await copy('c', 'two'); await copy('a', 'three');
+ h.rows.get('a').custom_title = 'first name';
+ await copy('a', 'two');
+ assert.equal((await copy('c', 'two')).status, 'copied');
+ assert.equal(h.rows.get('c').custom_title, 'first name');
+ h.rows.get('b').custom_title = 'second name';
+ assert.equal((await copy('b', 'one')).status, 'copied');
+ assert.equal(h.rows.get('a').custom_title, 'second name');
+});
+
+test('#511 historical unequal titles surface a conflict instead of a permanent fast-path skip', async t => {
+ const h = harness(t, true);
+ h.rows.get('b').custom_title = 'old local name';
+ const sourceRow = h.rows.get('a'), target = h.rows.get('b');
+ lib.setAutoCopyMapping(h.root, h.lineage, 'two', {
+ targetId: 'b', fingerprintVersion: 3,
+ ...h.ctx.mappingWithSourceRevision(null, 'one', sourceRow),
+ targetRevision: h.ctx.sessionCopyRowRevision(target),
+ });
+ h.ctx.getSessionDirtyIndex().markBaseline('one');
+ assert.equal((await h.ctx.buildAutoCopyPlan('one', 'two')).length, 1);
+ assert.equal((await h.copy()).status, 'conflict');
+ assert.equal(h.rows.get('b').custom_title, 'old local name');
+});
+
+for (const changed of ['a', 'b']) test('#511 atomic title update preserves a concurrent edit on ' + changed, async t => {
+ const h = harness(t);
+ await h.copy();
+ h.rows.get('a').custom_title = 'rename';
+ const before = fs.readFileSync(h.file('b'));
+ const { createSessionDb } = require('../scripts/session-db');
+ const db = createSessionDb({ dbPath: path.join(h.root, 'cas.db') });
+ await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT, title TEXT, custom_title TEXT, updated_at INTEGER, deleted_at INTEGER)');
+ for (const row of h.rows.values()) await db.run('INSERT INTO sessions VALUES (?, ?, ?, ?, ?, NULL)', [row.id, row.user_id, row.title, row.custom_title || '', row.updated_at]);
+ h.ctx.sqliteRun = async (sql, params) => {
+ await db.run('UPDATE sessions SET custom_title = ? WHERE id = ?', ['concurrent rename', changed]);
+ return db.run(sql, Array.from(params));
+ };
+ await assert.rejects(h.copy(), /会话记录正在变化/);
+ const row = (await db.all('SELECT custom_title FROM sessions WHERE id = ?', [changed]))[0];
+ assert.equal(row.custom_title, 'concurrent rename');
+ assert.deepEqual(fs.readFileSync(h.file('b')), before);
+});
+
+test('#511 deleting an extra same-account copy preserves the original and suppresses branch recreation', async t => {
+ const h = harness(t, true);
+ const extra = { ...h.rows.get('b'), id: 'extra' };
+ h.rows.set(extra.id, extra); h.write(extra.id, base);
+ lib.addAutoCopySessionMember(h.root, h.lineage, 'two', extra.id);
+ lib.recordSessionDeletion(h.root, [{ id: extra.id, user_id: 'two' }]);
+ h.rows.delete(extra.id); fs.unlinkSync(h.file(extra.id));
+ assert.equal((await h.copy()).status, 'skipped');
+ h.write('a', [...base, { type: 'message', role: 'user', content: [{ text: 'source branch' }] }]);
+ h.write('b', [...base, { type: 'message', role: 'user', content: [{ text: 'target branch' }] }]);
+ h.rows.get('a').updated_at++; h.rows.get('b').updated_at++;
+ const original = fs.readFileSync(h.file('b'));
+ for (let i = 0; i < 2; i++) assert.equal((await h.copy()).status, 'skipped');
+ assert.deepEqual([...h.rows.keys()], ['a', 'b', 'c']);
+ assert.deepEqual(fs.readFileSync(h.file('b')), original);
+});
+
+test('#511 a title update reaches a clean third account through the planner', async t => {
+ const h = harness(t, true);
+ await h.copy();
+ await h.ctx.copySessionRecord(h.rows.get('c'), 'two', { auto: true, lineageId: h.lineage });
+ h.rows.get('a').custom_title = 'new name';
+ await h.copy();
+ const dirty = h.ctx.getSessionDirtyIndex();
+ dirty.markBaseline('three'); dirty.clear('three', 'c');
+ const plan = await h.ctx.buildAutoCopyPlan('three', 'two');
+ assert.equal(plan.length, 1);
+ await h.ctx.copySessionRecord(plan[0], 'two', { auto: true, lineageId: h.lineage });
+ assert.equal(h.rows.get('c').custom_title, 'new name');
+});
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index 56073ab..90a1fef 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -1101,7 +1101,9 @@ test('robot button anchors to the conversation area bottom-right and snaps right
assert.match(script, /raw !== null && raw !== '' && isFinite\(value\)/);
assert.match(script, /localStorage\.removeItem\(FAB_RETIRED_POSITION_KEYS\[i\]\)/);
// The anchor is the conversation area, not the window.
- assert.match(script, /'\.teams-container\.is-mac \.conversation-shell'/);
+ assert.match(script, /WBS_COMPAT\.findConversationArea\(document\)/);
+ assert.match(read('workbuddy-compat.js'), /querySelectorAll\('\.conversation-shell'\)/);
+ assert.match(script, /classList\.toggle\('is-area-hidden', areaHidden\)/);
assert.match(script, /function readFabAnchorNode\(\)/);
assert.match(script, /function fabAnchorOffsets\(\)/);
assert.match(script, /window\.innerWidth - rect\.right\) \+ FAB_EDGE_GAP/);
diff --git a/test/windows-startup-recovery.test.js b/test/windows-startup-recovery.test.js
index b7e3f8e..3df55e1 100644
--- a/test/windows-startup-recovery.test.js
+++ b/test/windows-startup-recovery.test.js
@@ -10,6 +10,7 @@ const source = fs.readFileSync(path.join(__dirname, '../scripts/win-launcher.js'
function harness({ changed = false, running = false, stable = true, recovered = true } = {}) {
let now = 0, launches = 0, stops = 0, waits = 0;
const context = {
+ DATA_DIR: '/fixture', runPendingClientTempCleanup: async () => ({}),
PROFILE: { id: 'workbuddy-cn' }, nativeLaunchState: null, CDP_PORT: 9222, CDP_STARTUP_TIMEOUT_MS: 60000,
Date: { now: () => now }, process: { env: {} }, log() {}, writeCdpPortFile() {},
sleep: async ms => { now += ms; }, cdpPortCandidates: () => [9222],
diff --git a/test/workbuddy-launch-env.test.js b/test/workbuddy-launch-env.test.js
index 2ecea9b..f68ff97 100644
--- a/test/workbuddy-launch-env.test.js
+++ b/test/workbuddy-launch-env.test.js
@@ -20,6 +20,7 @@ function launchContext(profile, dataDir, env, spawn) {
const ctx = {
PROFILE: profile, DATA_DIR: dataDir, CDP_PORT: 9223,
process: { platform: 'win32', env }, IS_WIN: true, IS_LINUX: false, path,
+ runPendingClientTempCleanup: async () => ({}),
getClientLaunchArgs,
getWorkBuddyLaunchEnv,
log() {}, selectCdpPort: async () => 9223,