WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
fix: address pending session, persona and startup issues for 1.2.19
[email protected]684ffa8aab45
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex 4769aef..8423859 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 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 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 session-deletion-sync.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js 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[ -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/daemon.js b/scripts/daemon.jsindex 8b64bcd..2daf2e0 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -173,6 +173,7 @@ const { createCodeBuddySessionStore } = require('./codebuddy-session-store.js');const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget, selectIdeTargets } = require('./cdp-targets.js');const { createSessionDb, normalizeSessionIdBatch, parameterCount } = require('./session-db.js');const { createDirtyIndex } = require('./session-dirty.js');+const { createSessionDeletionSync } = require('./session-deletion-sync.js');const {createEncryptedExport,openEncryptedExport,@@ -530,8 +531,8 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 1.2.65:兼容空会话同步、自定义模型和重定向备份目录,工作目录恢复退避重试。// 1.2.66:刷新凭据按原信封加密保存,同账号刷新去重,过期账号保留手动切换。// 1.2.67:Windows 重启 GUI 客户端时不再请求隐藏主窗口,与冷启动保持一致。-const DAEMON_VERSION = '1.2.68';-const DAEMON_BUILD_ID = 'release-1.2.68-login-page-persona-switch';+const DAEMON_VERSION = '1.2.69';+const DAEMON_BUILD_ID = 'release-1.2.69-issue-fixes-1.2.19';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -5482,6 +5483,19 @@ function sessionCopyRowRevision(row) {]);}+let sessionDeletionSync = null;+function getSessionDeletionSync() {+ if (PROFILE.kind !== 'workbuddy') return null;+ if (sessionDeletionSync) return sessionDeletionSync;+ sessionDeletionSync = createSessionDeletionSync({+ query: sqliteQuery,+ run: sqliteRun,+ locks: sessionCopyLocks,+ members: ids => collectLineageMembersForDelete(DATA_DIR, ids),+ });+ return sessionDeletionSync;+}+// The physical session id and account id intentionally differ between members// of one shared lineage. Keep the content portion separately so a mapping// created from another account can still prove that an unchanged member is a@@ -5776,6 +5790,17 @@ async function copySessionRecord(src, targetUid, options = {}) {};const perform = async () => {await yieldAutoCopyToRenderer();+ const deletions = typeof getSessionDeletionSync === 'function' ? getSessionDeletionSync() : null;+ const assertNotDeleted = async () => {+ if (deletions && await deletions.hasDeletion(src.id, sourceUid)) {+ const error = new Error('同源会话已删除,停止同步');+ error.code = 'WBS_SESSION_DELETED';+ throw error;+ }+ };+ if (deletions && await deletions.hasDeletion(src.id, sourceUid)) {+ return { status: 'skipped', sourceId: src.id, targetId: '', copiedBytes: 0, totalBytes: 0 };+ }const readRow = async (id, uid) => (await sqliteQuery('SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id = ? AND user_id = ? AND deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0 LIMIT 1;', [id, uid]))[0];@@ -5874,6 +5899,7 @@ async function copySessionRecord(src, targetUid, options = {}) {const row = id === sourceRow.id ? sourceRow : candidates.find(candidate => candidate.id === id);const guard = async () => {await assertSessionSyncIdle([id]);+ await assertNotDeleted();if (row && JSON.stringify(await readRow(id, row.user_id)) !== JSON.stringify(row)) {throw new Error('会话记录正在变化,请稍后重试');}@@ -5938,6 +5964,7 @@ async function copySessionRecord(src, targetUid, options = {}) {await yieldAutoCopyToRenderer();const verifyRows = async () => {await assertSessionSyncIdle([fromRow && fromRow.id, toRow && toRow.id]);+ await assertNotDeleted();const freshSource = await readRow(fromRow.id, fromRow.user_id);const freshTarget = toRow ? await readRow(toRow.id, toRow.user_id) : null;if (JSON.stringify(freshSource) !== JSON.stringify(fromRow) || (toRow && JSON.stringify(freshTarget) !== JSON.stringify(toRow))) {@@ -5947,6 +5974,7 @@ async function copySessionRecord(src, targetUid, options = {}) {const commit = async (verifyPublished) => {await verifyRows();await verifyPublished();+ await assertNotDeleted();if (!toRow) {// Reserve provenance before the row becomes visible, so a crash// after insertion cannot create an untracked duplicate on retry.@@ -6022,6 +6050,10 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])const source = String(sourceUid || '').trim();const target = String(targetUid || '').trim();if (!source || !target || source === target) return [];+ const deletions = typeof getSessionDeletionSync === 'function' ? getSessionDeletionSync() : null;+ if (deletions && await deletions.reconcileAll() && typeof refreshWorkBuddySessionList === 'function') {+ await refreshWorkBuddySessionList(target, 'sessions-deleted');+ }normalizeAutoCopyLineages(DATA_DIR);const rules = getAutoCopyRules(DATA_DIR, source);const requested = new Set((Array.isArray(requestedSessionIds) ? requestedSessionIds : [])@@ -6383,6 +6415,11 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {job.copyStartedAt = Date.now();job.plan = await buildAutoCopyPlan(sourceUid, targetUid, job.openSessionId ? [job.openSessionId] : []);job.total = job.plan.length;+ const deletions = typeof getSessionDeletionSync === 'function' ? getSessionDeletionSync() : null;+ if (job.openSessionId && deletions && await deletions.hasDeletion(job.openSessionId, sourceUid)) {+ job.openSessionId = '';+ job.openSessionTargetId = '';+ }if (job.openSessionId && !job.plan.some((row) => String(row && row.id || '') === job.openSessionId)) {job.openSessionTargetId = resolveAutoCopyTargetId(sourceUid, targetUid, job.openSessionId);}@@ -6452,6 +6489,7 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {});break;} catch (error) {+ if (error.code === 'WBS_SESSION_DELETED') throw error;if (!activeSession || copyAttempt >= activeSessionRetryDelays.length) throw error;const retryDelay = activeSessionRetryDelays[copyAttempt];copyAttempt++;@@ -6483,9 +6521,14 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {else job.copied++;if (result.failedFiles) job.failed += result.failedFiles;} catch (e) {- recoverOpenSessionTarget(src);+ const deleted = e.code === 'WBS_SESSION_DELETED';+ if (!deleted) recoverOpenSessionTarget(src);+ else if (job.openSessionId === String(src.id || '')) {+ job.openSessionId = '';+ job.openSessionTargetId = '';+ }const errorText = String(e.message || e).slice(0, 240);- if (['会话消息文件没有消息,未同步', '会话消息文件为空,未同步'].includes(errorText)) {+ if (deleted || ['会话消息文件没有消息,未同步', '会话消息文件为空,未同步'].includes(errorText)) {// Empty metadata-only sessions are normal transient WorkBuddy// rows (for example a newly opened draft), not sync failures.if (typeof getSessionDirtyIndex === 'function' && typeof clearSessionDirty === 'function') {@@ -11890,7 +11933,7 @@ function handleApi(req, res) {// deliberately limited to session ids and event names; message contents// never leave WorkBuddy and the local API token remains the only auth gate.if (req.method === 'POST' && p === '/api/sessions/dirty') {- return readBody(req).then((body) => {+ return readBody(req).then(async (body) => {try {const currentUid = String((currentAccount() || {}).uid || '').trim();const claimedUid = String(body && body.uid || '').trim();@@ -11908,12 +11951,22 @@ function handleApi(req, res) {const events = Array.isArray(body.events) ? body.events : [];if (events.length > 500) return json(res, 400, { ok: false, error: '脏会话通知过多' });let marked = 0;+ const deletedIds = [];for (const event of events) {const id = String(event && event.id || '').trim();if (!isValidSessionId(id)) continue;+ if (event.event === 'sessionDeleted') deletedIds.push(id);markSessionDirty(uid, id, String(event.event || 'sessionUpdated'));marked++;}+ const deletions = getSessionDeletionSync();+ if (deletions) {+ let changed = deletedIds.length ? await deletions.observeDeleted(uid, deletedIds) : 0;+ // A fresh renderer also reconciles durable deletions missed while+ // disconnected, even if automatic copying is currently disabled.+ if (body.ready === true) changed += await deletions.reconcileAll();+ if (changed) await refreshWorkBuddySessionList(uid, 'sessions-deleted');+ }return json(res, 200, { ok: true, marked, initialized: getSessionDirtyIndex().isInitialized(uid) });} catch (e) {return json(res, 400, { ok: false, error: e.message });@@ -12205,10 +12258,11 @@ function handleApi(req, res) {try { ids = normalizeSessionIdBatch(body && body.ids); }catch (e) { return json(res, 400, { ok: false, error: e.message }); }if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });- return sqliteRun(+ const deletions = getSessionDeletionSync();+ return (deletions ? deletions.restore(ids) : sqliteRun("UPDATE sessions SET deleted_at = NULL, updated_at = ? WHERE id IN (" + sqlPlaceholders(ids) + ");",[Date.now(), ...ids]- )+ )).then(() => json(res, 200, { ok: true, restored: ids.length })).catch((e) => json(res, 500, { ok: false, error: e.message }));});diff --git a/scripts/inject.js b/scripts/inject.jsindex 7387910..82fa798 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -961,13 +961,20 @@ function createSessionDirtyTracker(send, options) {function queue(update) {var id = String(update && update.id || '').trim();if (!id) return false;- pending[id] = { id: id, event: String(update.event || 'sessionUpdated').slice(0, 40) };+ // Do not let a trailing lifecycle update overwrite an explicit deletion.+ if (!pending[id] || pending[id].event !== 'sessionDeleted') {+ pending[id] = { id: id, event: String(update.event || 'sessionUpdated').slice(0, 40) };+ }if (timer == null) timer = setTimeout(flush, delay);return true;}function observe(update) {var id = String(update && update.id || '').trim();if (!id) return false;+ if (update.event === 'sessionDeleted') {+ delete seen[id];+ return queue(update);+ }var next = signature(update);if (seen[id] === undefined) {seen[id] = next;@@ -4672,6 +4679,14 @@ 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) {+ 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';diff --git a/scripts/lib.js b/scripts/lib.jsindex 8435cca..5d8e116 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -1291,9 +1291,11 @@ function removeAutoCopySession(dataDir, uid, sessionId) {// 账号,切换回来时 auto-copy 会把它们原样复制回来(用户观察到的「删除后// 切走再切回、会话复活」现象)。无 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) {- const meta = readMeta(dataDir);- const config = ensureAutoCopyMeta(meta);+ const config = readAutoCopyConfig(dataDir);const ids = new Set((Array.isArray(sessionIds) ? sessionIds : []).map((s) => String(s || '').trim())@@ -1303,39 +1305,45 @@ function collectLineageMembersForDelete(dataDir, sessionIds) {// 成员表、反向索引及历史复制映射共同证明同源关系。只查成员表会漏掉// 旧版复制记录,以及 normalizeAutoCopyLineages 拆出的重复物理会话。// 不使用标题、工作目录或消息相似度推断,避免删除独立会话。- const membersByLineage = new Map();- const lineagesBySession = new Map();- const lineagesByOrigin = new Map();- const addLink = (lineageId, memberUid, memberId) => {- if (!config.sessions[lineageId]) return;- const uid = String(memberUid || '').trim();- const id = String(memberId || '').trim();- if (!id) return;- if (!membersByLineage.has(lineageId)) membersByLineage.set(lineageId, new Map());- membersByLineage.get(lineageId).set(id, { uid, id, lineageId });- if (!lineagesBySession.has(id)) lineagesBySession.set(id, new Set());- lineagesBySession.get(id).add(lineageId);- };- for (const [lineageId, lineage] of Object.entries(config.sessions)) {- if (!lineage) continue;- const origin = String(lineage.originLineageId || lineageId);- if (!lineagesByOrigin.has(origin)) lineagesByOrigin.set(origin, []);- lineagesByOrigin.get(origin).push(lineageId);- for (const member of (Array.isArray(lineage.members) ? lineage.members : [])) {- addLink(lineageId, member && member.uid, member && member.id);- }- }- for (const [uid, index] of Object.entries(config.sessionIndex)) {- for (const [id, lineageId] of Object.entries(index || {})) addLink(String(lineageId || ''), uid, id);- }- for (const [key, mapping] of Object.entries(config.copies)) {- try {- const parts = JSON.parse(key);- if (Array.isArray(parts) && parts.length === 2) {- addLink(String(parts[0] || ''), parts[1], mapping && mapping.targetId);+ let indexes = lineageDeleteIndexes.get(config);+ if (!indexes) {+ const membersByLineage = new Map();+ const lineagesBySession = new Map();+ const lineagesByOrigin = new Map();+ const addLink = (lineageId, memberUid, memberId) => {+ if (!config.sessions[lineageId]) return;+ const uid = String(memberUid || '').trim();+ const id = String(memberId || '').trim();+ if (!id) return;+ if (!membersByLineage.has(lineageId)) membersByLineage.set(lineageId, new Map());+ membersByLineage.get(lineageId).set(id, { uid, id, lineageId });+ if (!lineagesBySession.has(id)) lineagesBySession.set(id, new Set());+ lineagesBySession.get(id).add(lineageId);+ };+ for (const [lineageId, lineage] of Object.entries(config.sessions)) {+ if (!lineage) continue;+ const origin = String(lineage.originLineageId || lineageId);+ if (!lineagesByOrigin.has(origin)) lineagesByOrigin.set(origin, []);+ lineagesByOrigin.get(origin).push(lineageId);+ for (const member of (Array.isArray(lineage.members) ? lineage.members : [])) {+ addLink(lineageId, member && member.uid, member && member.id);}- } catch (_) { /* Malformed legacy keys cannot establish a copy relationship. */ }+ }+ for (const [uid, index] of Object.entries(config.sessionIndex)) {+ for (const [id, lineageId] of Object.entries(index || {})) addLink(String(lineageId || ''), uid, id);+ }+ for (const [key, mapping] of Object.entries(config.copies)) {+ try {+ const parts = JSON.parse(key);+ if (Array.isArray(parts) && parts.length === 2) {+ addLink(String(parts[0] || ''), parts[1], mapping && mapping.targetId);+ }+ } catch (_) { /* Malformed legacy keys cannot establish a copy relationship. */ }+ }+ indexes = { membersByLineage, lineagesBySession, lineagesByOrigin };+ lineageDeleteIndexes.set(config, indexes);}+ const { membersByLineage, lineagesBySession, lineagesByOrigin } = indexes;const members = [];const seenIds = new Set();const seenLineages = new Set();diff --git a/scripts/persona.js b/scripts/persona.jsindex 6baa197..b5b5239 100644--- a/scripts/persona.js+++ b/scripts/persona.js@@ -14,7 +14,7 @@ const PERSONA_MODES = ['unset', 'shared', 'independent'];function validUid(uid) { return typeof uid === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(uid); }function personaDir(root, uid) {if (!validUid(uid)) throw new Error('账号格式无效');- return path.join(path.resolve(root), `user-${uid}-personal`);+ return path.join(resolveTrustedRoot(root), `user-${uid}-personal`);}function assertSafePath(file) {let cursor = path.resolve(file);@@ -57,6 +57,7 @@ function usableSource(files) {(!files['BOOTSTRAP.md'] || !!stateOf(files).onboardingCompletedAt);}function scopedLayout(root) {+ root = resolveTrustedRoot(root);assertSafePath(root);const marker = path.join(root, 'storage/device/global/user-data-migration.json');assertSafePath(marker);@@ -91,16 +92,16 @@ function inspectPersona(options) {const sourceFiles = snapshot(personaDir(dataRoot, uid));if (usableSource(sourceFiles)) sources.push({ uid, nickname: String(account.nickname || uid), files: IDENTITY_FILES.filter(name => nonempty(sourceFiles, name)) });}- const legacyFiles = snapshot(path.resolve(dataRoot));+ const legacyFiles = snapshot(resolveTrustedRoot(dataRoot));if (usableSource(legacyFiles)) sources.push({ uid: 'legacy', nickname: '升级前共用的设置', files: IDENTITY_FILES.filter(name => nonempty(legacyFiles, name)) });return { uid: targetUid, status, eligible: ['missing', 'empty', 'bootstrap'].includes(status) && sources.length > 0, sources, revision };}-// The configured backup root may be redirected (for example an AppData-// Junction). Canonicalize that trusted root, including a not-yet-created suffix;-// paths inside persona still pass through assertSafePath without following links.-function resolveBackupRoot(backupRoot) {- let cursor = path.resolve(backupRoot);+// Configured client/backup roots may be redirected (for example an AppData+// junction). Resolve only the trusted root, including a not-yet-created suffix;+// account directories and files inside it still reject links.+function resolveTrustedRoot(root) {+ let cursor = path.resolve(root);const missing = [];for (;;) {try { return path.join(fs.realpathSync(cursor), ...missing); }@@ -113,7 +114,7 @@ function resolveBackupRoot(backupRoot) {}}function personaSettingsFile(backupRoot) {- const file = path.join(resolveBackupRoot(backupRoot), 'persona', 'settings.json');+ const file = path.join(resolveTrustedRoot(backupRoot), 'persona', 'settings.json');assertSafePath(file);return file;}@@ -143,7 +144,7 @@ function dismissPersonaNotice(backupRoot) {return writePersonaSettings(backupRoot, { ...readPersonaSettings(backupRoot), noticeDismissed: true });}function sharedPersonaDir(backupRoot) {- const dir = path.join(resolveBackupRoot(backupRoot), 'persona', 'shared');+ const dir = path.join(resolveTrustedRoot(backupRoot), 'persona', 'shared');assertSafePath(dir);return dir;}@@ -152,7 +153,7 @@ function listPersonaSources({ dataRoot, accounts = [] }) {for (const account of [...accounts.filter(a => a.uid !== 'legacy'), { uid: 'legacy', nickname: '升级前共用的设置' }]) {const uid = String(account.uid || '');if (!validUid(uid)) continue;- const files = snapshot(uid === 'legacy' ? path.resolve(dataRoot) : personaDir(dataRoot, uid));+ const files = snapshot(uid === 'legacy' ? resolveTrustedRoot(dataRoot) : personaDir(dataRoot, uid));const available = usableSource(files);if (uid === 'legacy' && !available) continue;sources.push({ uid, nickname: String(account.nickname || uid), available,@@ -162,7 +163,7 @@ function listPersonaSources({ dataRoot, accounts = [] }) {return sources;}function backupPersonaDirectory(backupRoot, label, original) {- const dir = path.join(resolveBackupRoot(backupRoot), 'persona', 'backups', label,+ const dir = path.join(resolveTrustedRoot(backupRoot), 'persona', 'backups', label,`${Date.now()}-${crypto.randomBytes(6).toString('hex')}`);assertSafePath(dir);fs.mkdirSync(dir, { recursive: true, mode: 0o700 });@@ -239,7 +240,7 @@ function configurePersona(options) {const source = listPersonaSources(options).find(a => a.uid === options.sourceUid && a.available);if (!source) throw new Error('请选择可用的个性化设置来源');if (!options.revision || source.revision !== options.revision) throw new Error('来源个性化设置已变化,请重新选择');- const sourceDir = source.uid === 'legacy' ? path.resolve(options.dataRoot) : personaDir(options.dataRoot, source.uid);+ const sourceDir = source.uid === 'legacy' ? resolveTrustedRoot(options.dataRoot) : personaDir(options.dataRoot, source.uid);const files = snapshot(sourceDir);if (fingerprint(files) !== options.revision) throw new Error('来源个性化设置已变化,请重新选择');const next = { mode: 'shared', noticeDismissed: true, activeUid: options.currentUid };@@ -266,7 +267,7 @@ function copyPersona(options) {if (!options.revision || preview.revision !== options.revision) throw new Error('目标个性化设置已变化,请重新查看并确认');if (!preview.sources.some(source => source.uid === options.sourceUid)) throw new Error('个性化设置来源无效');const target = personaDir(options.dataRoot, options.targetUid);- const source = options.sourceUid === 'legacy' ? path.resolve(options.dataRoot) : personaDir(options.dataRoot, options.sourceUid);+ const source = options.sourceUid === 'legacy' ? resolveTrustedRoot(options.dataRoot) : personaDir(options.dataRoot, options.sourceUid);const original = snapshot(target);const sourceFiles = snapshot(source);const state = { ...stateOf(original), version: stateOf(original).version || 1, onboardingCompletedAt: new Date().toISOString() };@@ -274,7 +275,7 @@ function copyPersona(options) {const writes = {};for (const name of IDENTITY_FILES) if (nonempty(sourceFiles, name)) writes[name] = sourceFiles[name].text;writes['workspace-state.json'] = JSON.stringify(state, null, 2) + '\n';- const backupDir = path.join(resolveBackupRoot(options.backupRoot), 'persona', options.targetUid, `${Date.now()}-${crypto.randomBytes(6).toString('hex')}`);+ const backupDir = path.join(resolveTrustedRoot(options.backupRoot), 'persona', options.targetUid, `${Date.now()}-${crypto.randomBytes(6).toString('hex')}`);assertSafePath(backupDir);fs.mkdirSync(backupDir, { recursive: true, mode: 0o700 });for (const name of Object.keys(original)) fs.writeFileSync(path.join(backupDir, name), original[name].text, { mode: 0o600, flag: 'wx' });diff --git a/scripts/session-deletion-sync.js b/scripts/session-deletion-sync.jsnew file mode 100644index 0000000..d51b89f--- /dev/null+++ b/scripts/session-deletion-sync.js@@ -0,0 +1,97 @@+'use strict';++// Official deletion is soft deletion in the session database. Reuse those+// durable markers instead of inferring deletion from missing files/cache entries.+// Only persisted provenance links accounts; titles and working directories do not.+function createSessionDeletionSync({ query, run, members, locks }) {+ const isDeleted = row => row && row.deleted_at !== null && row.deleted_at !== undefined && row.deleted_at !== '';+ const group = ids => members(ids).filter(member => member && member.id && member.uid);+ async function rowsFor(links) {+ const rows = [];+ for (let start = 0; start < links.length; start += 100) {+ const batch = links.slice(start, start + 100);+ rows.push(...await query('SELECT id, user_id, deleted_at FROM sessions WHERE COALESCE(is_background_automation, 0) = 0 AND (' ++ batch.map(() => '(id = ? AND user_id = ?)').join(' OR ') + ');', batch.flatMap(member => [member.id, member.uid])));+ }+ return rows;+ }+ async function withLocks(ids, task) {+ const keys = [...new Set(group(ids).map(member => member.lineageId).filter(Boolean))].sort();+ const previous = keys.map(key => locks.get(key)).filter(Boolean);+ const current = Promise.all(previous.map(promise => Promise.resolve(promise).catch(() => {}))).then(task);+ // Reserve synchronously: subsequent copy workers must queue behind this+ // deletion. Re-read membership after waiting to include just-published copies.+ keys.forEach(key => locks.set(key, current));+ try { return await current; }+ finally { keys.forEach(key => { if (locks.get(key) === current) locks.delete(key); }); }+ }+ async function hasDeletion(id, uid) {+ const links = group([id]);+ if (!links.some(member => member.id === id && member.uid === uid)) return false;+ return (await rowsFor(links)).some(isDeleted);+ }+ async function propagate(id, uid, explicit) {+ return withLocks([id], async () => {+ const links = group([id]);+ if (!links.some(member => member.id === id && member.uid === uid)) return 0;+ const rows = await rowsFor(links);+ const seed = rows.find(row => row.id === id && row.user_id === uid);+ let deletedAt = rows.find(isDeleted)?.deleted_at;+ if (deletedAt === undefined) {+ if (!explicit || seed) return 0;+ // An explicit renderer deletion may follow a hard delete. Confirm the+ // known record really is absent, not reassigned or a background task.+ if ((await query('SELECT id FROM sessions WHERE id = ?;', [id])).length) return 0;+ deletedAt = Date.now();+ }+ let changed = 0;+ for (let start = 0; start < rows.length; start += 100) {+ const live = rows.slice(start, start + 100).filter(row => !isDeleted(row));+ if (!live.length) continue;+ const result = await run('UPDATE sessions SET deleted_at = ?, updated_at = ? WHERE deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0 AND (' ++ live.map(() => '(id = ? AND user_id = ?)').join(' OR ') + ');',+ [deletedAt, Date.now(), ...live.flatMap(row => [row.id, row.user_id])]);+ changed += Number(result && result.changes) || 0;+ }+ return changed;+ });+ }+ async function reconcileAll() {+ const deleted = await query('SELECT id, user_id FROM sessions WHERE deleted_at IS NOT NULL AND COALESCE(is_background_automation, 0) = 0;');+ const seen = new Set();+ let changed = 0;+ for (const row of deleted) {+ if (seen.has(row.id)) continue;+ const links = group([row.id]);+ if (!links.some(member => member.id === row.id && member.uid === row.user_id)) continue;+ links.forEach(member => seen.add(member.id));+ changed += await propagate(row.id, row.user_id, false);+ }+ return changed;+ }+ async function observeDeleted(uid, ids) {+ let changed = 0;+ for (const id of new Set(ids)) changed += await propagate(id, uid, true);+ return changed;+ }+ async function restore(ids) {+ return withLocks(ids, async () => {+ const links = group(ids);+ const rows = await rowsFor(links);+ // Standalone sessions have no lineage; retain the old restore behavior.+ const known = new Set(links.map(member => member.id));+ for (const id of ids) if (!known.has(id)) {+ rows.push(...await query('SELECT id, user_id, deleted_at FROM sessions WHERE id = ? AND COALESCE(is_background_automation, 0) = 0;', [id]));+ }+ for (let start = 0; start < rows.length; start += 100) {+ const batch = rows.slice(start, start + 100);+ await run('UPDATE sessions SET deleted_at = NULL, updated_at = ? WHERE COALESCE(is_background_automation, 0) = 0 AND (' ++ batch.map(() => '(id = ? AND user_id = ?)').join(' OR ') + ');',+ [Date.now(), ...batch.flatMap(row => [row.id, row.user_id])]);+ }+ });+ }+ return { hasDeletion, reconcileAll, observeDeleted, restore };+}++module.exports = { createSessionDeletionSync };diff --git a/scripts/win-launcher.js b/scripts/win-launcher.jsindex 34d312d..a0ec07e 100644--- a/scripts/win-launcher.js+++ b/scripts/win-launcher.js@@ -14,6 +14,7 @@'use strict';const fs = require('fs');+const { readWorkBuddyInstallation, waitForStableWorkBuddyInstallation } = require('./windows-startup-recovery');const path = require('path');const os = require('os');const net = require('net');@@ -1369,7 +1370,9 @@ function stopNativeWorkBuddy() {const result = runNativeHelper(['--terminate-workbuddy', '--profile', PROFILE.id], { timeout: 60000 });if (result.status !== 0) {const detail = String(result.stderr || '').trim();- throw new Error('无法精确重启当前 WorkBuddy(错误码 ' + result.status + ')' + (detail ? ': ' + detail : ''));+ const error = new Error('无法精确重启当前 WorkBuddy(错误码 ' + result.status + ')' + (detail ? ': ' + detail : ''));+ error.exitCode = result.status;+ throw error;}}@@ -1649,8 +1652,13 @@ async function ensureDaemonNative(nodeBin) {async function waitForWorkBuddyCdpNative(binary) {let restartedAfterHandoff = false;+ let retriedAfterUpdate = false;+ let installationChanged = false;+ let launchInstallation = null;let launchStartedAt = 0;const start = () => {+ launchInstallation = readWorkBuddyInstallation(binary);+ installationChanged = false;nativeLaunchState = launchWorkBuddy(binary);launchStartedAt = Date.now();log('WorkBuddy 启动请求已派发 method=' + nativeLaunchState.method + ' expectedPort=' + CDP_PORT +@@ -1668,8 +1676,31 @@ async function waitForWorkBuddyCdpNative(binary) {return true;}}+ const installation = readWorkBuddyInstallation(binary);+ installationChanged = installationChanged || installation.signature !== launchInstallation.signature;if (nativeLaunchFailed(nativeLaunchState)) {- if (!restartedAfterHandoff && nativeWorkBuddyRunning()) {+ if (installationChanged && !retriedAfterUpdate) {+ retriedAfterUpdate = true;+ // A changed executable/archive during this attempt is evidence of an+ // installation write, not proof of the crash cause. Bound recovery by+ // the original startup deadline and retain exact-process checks.+ log('启动期间安装文件发生变化,等待稳定后重试一次');+ await waitForStableWorkBuddyInstallation(binary, deadline);+ // The official updater may have already restarted a usable instance.+ // Reuse its verified CDP endpoint instead of stopping it again.+ for (const port of cdpPortCandidates()) {+ if (await isWorkBuddyCdpAt(port)) {+ CDP_PORT = port;+ process.env.WBSWITCH_CDP_PORT = String(port);+ writeCdpPortFile(port);+ return true;+ }+ }+ if (nativeWorkBuddyRunning()) stopNativeWorkBuddy();+ start();+ continue;+ }+ if (!restartedAfterHandoff && !retriedAfterUpdate && nativeWorkBuddyRunning()) {restartedAfterHandoff = true;log('WorkBuddy 启动进程异常退出但同 profile 进程仍在运行,精确停止后重试一次');stopNativeWorkBuddy();@@ -1678,7 +1709,8 @@ async function waitForWorkBuddyCdpNative(binary) {continue;}const error = new Error('WorkBuddy 启动进程异常退出' +- (nativeLaunchState.errorCode ? '(' + nativeLaunchState.errorCode + ')' : '(退出码 ' + nativeLaunchState.exitCode + ')'));+ (nativeLaunchState.errorCode ? '(' + nativeLaunchState.errorCode + ')' : '(退出码 ' + nativeLaunchState.exitCode + ' / 0x' + (nativeLaunchState.exitCode >>> 0).toString(16).toUpperCase().padStart(8, '0') + ')'));+ error.exitCode = 14;error.sentryStage = 'windows-native-launcher-workbuddy-exit';error.sentryExtra = {cdpPort: CDP_PORT,@@ -1688,7 +1720,7 @@ async function waitForWorkBuddyCdpNative(binary) {};throw error;}- if (!restartedAfterHandoff && Number.isInteger(nativeLaunchState && nativeLaunchState.exitCode) &&+ if (!restartedAfterHandoff && !retriedAfterUpdate && Number.isInteger(nativeLaunchState && nativeLaunchState.exitCode) &&Date.now() - launchStartedAt >= 5000 && nativeWorkBuddyRunning()) {restartedAfterHandoff = true;log('WorkBuddy 启动请求已被无 CDP 的单实例接管,精确停止后重试一次');@@ -1707,6 +1739,10 @@ function nativeLaunchFailed(state) {));}+function nativeStartupExitCode(error) {+ return error && [11, 12, 13, 14, 15].includes(error.exitCode) ? error.exitCode : 4;+}+async function nativeStartupMain() {try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (_) {}log('原生启动入口: scripts=' + SCRIPTS_DIR + ' data=' + DATA_DIR + ' pid=' + process.pid);@@ -1773,7 +1809,7 @@ if (require.main === module && process.env.WBSWITCH_NATIVE_LAUNCHER === '1') {stage: error && error.sentryStage || 'windows-native-launcher-uncaught',extra: error && error.sentryExtra || {},})- .catch(() => {}).finally(() => process.exit(4));+ .catch(() => {}).finally(() => process.exit(nativeStartupExitCode(error)));});} else if (require.main === module) (async () => {// 入口级 breadcrumb 必须先于 Node/PowerShell/进程探测写出,避免管理员启动时@@ -1856,6 +1892,7 @@ if (require.main === module && process.env.WBSWITCH_NATIVE_LAUNCHER === '1') {module.exports = {nativeLaunchFailed,+ nativeStartupExitCode,strictPowerShellLines,getWorkBuddyProcesses,workBuddyProcesses,diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.goindex 3da5fce..a4aa6a7 100644--- a/scripts/windows-native/main.go+++ b/scripts/windows-native/main.go@@ -1343,6 +1343,27 @@ func appendLog(dir string, args ...any) *os.File {return file}+func startupFailureMessage(code int) string {+ var detail string+ switch code {+ case 3:+ detail = "等待 WorkBuddy 调试端口超时。请确认官方更新已完成,并完全退出旧实例后从 WorkDaddy 重试。"+ case exitAccessDenied:+ detail = "无法以当前权限检查或关闭旧 WorkBuddy 实例。请手动退出旧实例,检查 WorkBuddy 的兼容性设置,取消“以管理员身份运行”后重试。"+ case exitIdentityMismatch:+ detail = "无法验证旧进程的路径、账号或会话身份,已停止操作。请手动退出旧实例后重试;若仍失败,请重新选择客户端安装路径。"+ case exitPreserveLifecycle:+ detail = "无法安全确认当前组件的归属,已保留现有进程。请手动退出当前客户端及其 WorkDaddy 后重试。"+ case 14:+ detail = "WorkBuddy 启动进程异常退出。请等待官方更新完成后重试;具体退出码(含十六进制)见日志。"+ case 15:+ detail = "WorkBuddy 安装文件仍在变化或尚不完整。请等待官方更新完成后重试。"+ default:+ detail = "启动失败。请查看日志中的具体原因。"+ }+ return fmt.Sprintf("%s\n\n错误码:%d\n详细信息已写入 native-launcher.log。", detail, code)+}+func runNodeLauncher(appDir, profile string) int {dir, err := dataDir(profile)if err != nil {@@ -1391,7 +1412,7 @@ func runNodeLauncher(appDir, profile string) int {return 0}if code != 0 {- messageBox(productName(profile), fmt.Sprintf("启动失败(错误码 %d)。\n\n详细信息已写入 native-launcher.log。", code), mbOK|mbIconError)+ messageBox(productName(profile), startupFailureMessage(code), mbOK|mbIconError)}return code}diff --git a/scripts/windows-native/main_test.go b/scripts/windows-native/main_test.goindex 3b32c55..bd117e3 100644--- a/scripts/windows-native/main_test.go+++ b/scripts/windows-native/main_test.go@@ -6,9 +6,28 @@ import ("fmt""os""path/filepath"+ "strings""testing")+func TestStartupFailureMessagesPreserveFailureCategory(t *testing.T) {+ for _, item := range []struct {+ code int+ text string+ }{+ {3, "调试端口"}, {11, "权限"}, {12, "身份"}, {13, "保留"},+ {14, "异常退出"}, {15, "更新"}, {4, "启动失败"},+ } {+ message := startupFailureMessage(item.code)+ if !strings.Contains(message, item.text) || !strings.Contains(message, "native-launcher.log") {+ t.Fatalf("code %d lost category or log location: %s", item.code, message)+ }+ if strings.Contains(message, "管理员身份重试") {+ t.Fatal("startup guidance must not request privilege escalation")+ }+ }+}+func TestProcessNameDiffersRequiresPositiveMismatch(t *testing.T) {for _, test := range []struct {name stringdiff --git a/scripts/windows-startup-recovery.js b/scripts/windows-startup-recovery.jsnew file mode 100644index 0000000..cd818d1--- /dev/null+++ b/scripts/windows-startup-recovery.js@@ -0,0 +1,39 @@+'use strict';++const fs = require('node:fs');+const path = require('node:path');++// Only sample metadata of the selected installation; never read application or+// account contents, search other installations, or infer updates from age alone.+function readWorkBuddyInstallation(binary) {+ const root = path.dirname(binary);+ const files = [binary, path.join(root, 'resources', 'app.asar'),+ path.join(root, 'resources', 'app', 'package.json'), path.join(root, 'chrome_elf.dll'),+ path.join(root, 'icudtl.dat')];+ const stamps = files.map(file => {+ try {+ const stat = fs.statSync(file);+ return stat.isFile() ? [stat.size, stat.mtimeMs, stat.ctimeMs, stat.ino] : null;+ } catch (_) { return null; }+ });+ return { signature: JSON.stringify(stamps), ready: !!(stamps[0] && (stamps[1] || stamps[2])) };+}++async function waitForStableWorkBuddyInstallation(binary, deadline, options = {}) {+ const now = options.now || Date.now;+ const sleep = options.sleep || (ms => new Promise(resolve => setTimeout(resolve, ms)));+ const read = options.read || readWorkBuddyInstallation;+ let previous = null, stableSince = now();+ while (now() < deadline) {+ const current = read(binary);+ if (!current.ready || !previous || !previous.ready || current.signature !== previous.signature) stableSince = now();+ if (current.ready && now() - stableSince >= 3000) return;+ previous = current;+ await sleep(Math.min(1000, deadline - now()));+ }+ const error = new Error('WorkBuddy 安装文件仍在变化或尚不完整,请等待官方更新完成后重试');+ error.exitCode = 15;+ throw error;+}++module.exports = { readWorkBuddyInstallation, waitForStableWorkBuddyInstallation };diff --git a/test/message-navigation.test.js b/test/message-navigation.test.jsindex 7daa1b3..da24845 100644--- a/test/message-navigation.test.js+++ b/test/message-navigation.test.js@@ -17,6 +17,35 @@ function navigationFunction(name, context) {return context[name];}+test('resizing a narrow window hides navigation, closes previews and cancels dragging; widening restores it', () => {+ const style = { setProperty() {} };+ let previewOpen = true, cancelled = false;+ 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; },+ };+ 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');+});+test('navigation displays at most 20 evenly spaced markers while retaining both conversation ends', () => {const context = {};const indices = navigationFunction('markerTurnIndices', context);diff --git a/test/persona-sharing.test.js b/test/persona-sharing.test.jsindex 28efb69..618c3d6 100644--- a/test/persona-sharing.test.js+++ b/test/persona-sharing.test.js@@ -56,6 +56,25 @@ test('a not-yet-created backup root beneath a redirected parent can initialize sp.dismissPersonaNotice(nested);assert.equal(p.readPersonaSettings(path.join(actualRoot, 'new', 'profile')).noticeDismissed, true);});+test('a redirected client root supports sharing, switching and rollback but rejects inner links', t => {+ const f = fixture(t);+ const actualRoot = f.options.dataRoot;+ const alias = actualRoot + '-alias';+ fs.symlinkSync(actualRoot, alias, process.platform === 'win32' ? 'junction' : 'dir');+ f.options.dataRoot = alias;+ f.enable();+ f.write('a', 'USER.md', 'updated through redirected root');+ const result = p.syncSharedPersonaForSwitch({ ...f.options, sourceUid: 'a', targetUid: 'b' });+ assert.equal(fs.readFileSync(f.file('b', 'USER.md'), 'utf8'), 'updated through redirected root');+ result.rollback();+ assert.equal(fs.readFileSync(f.file('b', 'USER.md'), 'utf8'), 'bUSER.md');+ const outside = path.join(path.dirname(actualRoot), 'outside-client');+ fs.mkdirSync(outside);+ fs.rmSync(path.join(actualRoot, 'user-b-personal'), { recursive: true });+ fs.symlinkSync(outside, path.join(actualRoot, 'user-b-personal'), process.platform === 'win32' ? 'junction' : 'dir');+ assert.throws(() => p.syncSharedPersonaForSwitch({ ...f.options, sourceUid: 'a', targetUid: 'b' }), /符号链接/);+ assert.deepEqual(fs.readdirSync(outside), []);+});test('shared A edits reach B; B edits and optional memory deletion reach A, preserving state', t => {const f=fixture(t); f.enable();f.write('a','MEMORY.md','new A memory');diff --git a/test/session-deletion-sync.test.js b/test/session-deletion-sync.test.jsnew file mode 100644index 0000000..8ce09d7--- /dev/null+++ b/test/session-deletion-sync.test.js@@ -0,0 +1,121 @@+'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 { createSessionDb } = require('../scripts/session-db');+const lib = require('../scripts/lib');+const { createSessionDeletionSync } = require('../scripts/session-deletion-sync');++async function fixture(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-deletion-sync-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const db = createSessionDb({ dbPath: path.join(root, 'sessions.db') });+ await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT, deleted_at INTEGER, updated_at INTEGER, is_background_automation INTEGER DEFAULT 0)');+ const lineage = lib.ensureAutoCopySession(root, 'one', 'a');+ for (const [id, uid] of [['a', 'one'], ['b', 'two'], ['c', 'three']]) {+ lib.addAutoCopySessionMember(root, lineage, uid, id);+ await db.run('INSERT INTO sessions (id, user_id, updated_at) VALUES (?, ?, 1)', [id, uid]);+ }+ await db.run('INSERT INTO sessions (id, user_id, updated_at) VALUES (?, ?, 1)', ['unrelated', 'one']);+ const locks = new Map();+ const make = () => createSessionDeletionSync({ query: db.all, run: db.run, locks,+ members: ids => lib.collectLineageMembersForDelete(root, ids) });+ const alive = async () => (await db.all('SELECT id FROM sessions WHERE deleted_at IS NULL ORDER BY id')).map(r => r.id);+ return { root, db, locks, lineage, sync: make(), make, alive };+}++test('official soft deletion propagates across known copies and survives restart; restore is lineage-wide', async t => {+ const f = await fixture(t);+ await f.db.run('UPDATE sessions SET deleted_at = 100 WHERE id = ?', ['a']);+ assert.equal(await f.sync.hasDeletion('b', 'two'), true);+ await f.sync.reconcileAll();+ assert.deepEqual(await f.alive(), ['unrelated']);+ assert.equal(await f.make().hasDeletion('c', 'three'), true);+ assert.equal(await f.make().reconcileAll(), 0, 'repeated reconciliation must not rewrite deleted records');+ await f.sync.restore(['b']);+ assert.deepEqual(await f.alive(), ['a', 'b', 'c', 'unrelated']);+ assert.equal(await f.make().hasDeletion('a', 'one'), false);+});++test('explicit hard deletion requires known owner; mere absence never means deletion', async t => {+ const f = await fixture(t);+ await f.db.run('DELETE FROM sessions WHERE id = ?', ['a']);+ assert.equal(await f.sync.hasDeletion('b', 'two'), false);+ await f.sync.reconcileAll();+ assert.deepEqual(await f.alive(), ['b', 'c', 'unrelated']);+ await f.sync.observeDeleted('foreign', ['a']);+ assert.deepEqual(await f.alive(), ['b', 'c', 'unrelated']);+ await f.sync.observeDeleted('one', ['a']);+ assert.deepEqual(await f.alive(), ['unrelated']);+ assert.equal(await f.make().hasDeletion('b', 'two'), true);+});++test('live records, foreign owners and background automation cannot authorize cascade deletion', async t => {+ const f = await fixture(t);+ await f.sync.observeDeleted('one', ['a']);+ assert.deepEqual(await f.alive(), ['a', 'b', 'c', 'unrelated']);+ await f.db.run('UPDATE sessions SET deleted_at = 100, user_id = ? WHERE id = ?', ['foreign', 'a']);+ await f.sync.reconcileAll();+ assert.deepEqual(await f.alive(), ['b', 'c', 'unrelated']);+ await f.db.run('UPDATE sessions SET user_id = ?, is_background_automation = 1 WHERE id = ?', ['one', 'a']);+ await f.sync.reconcileAll();+ assert.deepEqual(await f.alive(), ['b', 'c', 'unrelated']);+});++test('deletion waits for in-flight copy, then includes the copy published before lock release', async t => {+ const f = await fixture(t);+ let release;+ const inFlight = new Promise(resolve => { release = resolve; });+ f.locks.set(f.lineage, inFlight);+ await f.db.run('UPDATE sessions SET deleted_at = 100 WHERE id = ?', ['a']);+ let finished = false;+ const deletion = f.sync.observeDeleted('one', ['a']).then(() => { finished = true; });+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(finished, false);+ lib.addAutoCopySessionMember(f.root, f.lineage, 'four', 'd');+ await f.db.run('INSERT INTO sessions (id, user_id, updated_at) VALUES (?, ?, 1)', ['d', 'four']);+ release(); await deletion;+ assert.deepEqual(await f.alive(), ['unrelated']);+ assert.equal(f.locks.size, 0);+});++test('a failed database write leaves deletion evidence for a later retry', async t => {+ const f = await fixture(t);+ await f.db.run('UPDATE sessions SET deleted_at = 100 WHERE id = ?', ['a']);+ const failing = createSessionDeletionSync({ query: f.db.all, run: async () => { throw Error('locked'); }, locks: f.locks,+ members: ids => lib.collectLineageMembersForDelete(f.root, ids) });+ await assert.rejects(failing.reconcileAll(), /locked/);+ assert.equal(f.locks.size, 0);+ await f.make().reconcileAll();+ assert.deepEqual(await f.alive(), ['unrelated']);+});++test('renderer deletion route rejects a stale account and reconciles missed deletion on baseline', async () => {+ const vm = require('node:vm');+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+ const start = source.indexOf(" if (req.method === 'POST' && p === '/api/sessions/dirty')");+ const end = source.indexOf('\n }', start) + 4;+ const calls = [];+ const context = {+ readBody: async req => req.body, currentAccount: () => ({ uid: 'one' }),+ json: (_, status, body) => ({ status, body }), isValidSessionId: id => /^[a-z-]+$/.test(id),+ markSessionDirty: (...args) => calls.push(['dirty', ...args]), markSessionDirtyBaseline() {},+ getSessionDirtyIndex: () => ({ isInitialized: () => true }),+ getSessionDeletionSync: () => ({+ observeDeleted: async (uid, ids) => { calls.push(['deleted', uid, ...ids]); return 1; },+ reconcileAll: async () => { calls.push(['reconcile']); return 1; },+ }),+ refreshWorkBuddySessionList: async uid => calls.push(['refresh', uid]),+ };+ vm.runInNewContext('async function route(req,res) { const p="/api/sessions/dirty";\n' + source.slice(start,end) + '\n}', context);+ const call = body => context.route({ method: 'POST', body }, {});+ assert.equal((await call({ uid: 'two', events: [{ id: 'a', event: 'sessionDeleted' }] })).status, 409);+ assert.deepEqual(calls, []);+ assert.equal((await call({ uid: 'one', events: [{ id: 'a', event: 'sessionDeleted' }] })).status, 200);+ assert.deepEqual(calls, [['dirty', 'one', 'a', 'sessionDeleted'], ['deleted', 'one', 'a'], ['refresh', 'one']]);+ calls.length = 0;+ assert.equal((await call({ uid: 'one', ready: true })).status, 200);+ assert.deepEqual(calls, [['reconcile'], ['refresh', 'one']]);+});diff --git a/test/session-monitor.test.js b/test/session-monitor.test.jsindex cc3808d..eef5ccb 100644--- a/test/session-monitor.test.js+++ b/test/session-monitor.test.js@@ -10,6 +10,18 @@ const path = require('node:path');const injectSource = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');const { createDirtyIndex } = require('../scripts/session-dirty.js');+test('explicit deletion is sent even without content changes or a baseline, and survives later lifecycle events', () => {+ const sent = [];+ const tracker = inject.createSessionDirtyTracker(payload => sent.push(payload), { delay: 0 });+ tracker.baseline([{ id: 'a', title: 'A', updatedAt: 10 }]);+ assert.equal(tracker.observe({ id: 'a', title: 'A', updatedAt: 10, event: 'sessionDeleted' }), true);+ tracker.observe({ id: 'a', title: 'A', updatedAt: 11, event: 'sessionUpdated' });+ assert.equal(tracker.observe({ id: 'b', event: 'sessionDeleted' }), true);+ tracker.flush();+ assert.deepEqual(sent[1], [{ id: 'a', event: 'sessionDeleted' }, { id: 'b', event: 'sessionDeleted' }]);+ tracker.destroy();+});+test('session dirty index uses the renderer baseline and preserves concurrent changes', () => {const index = createDirtyIndex();assert.equal(index.shouldSync('account-a', 'session-a'), true, 'uninitialized accounts use the safe fallback');diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.jsindex 574fec4..4765cb8 100644--- a/test/session-sync-daemon.test.js+++ b/test/session-sync-daemon.test.js@@ -11,7 +11,7 @@ const sessionSync = require('../scripts/session-sync.js');const { createDirtyIndex } = require('../scripts/session-dirty.js');const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const base = [{ type: 'message', role: 'user', content: [{ text: 'question' }] }, { type: 'message', role: 'assistant', content: [{ text: 'answer' }] }];-function harness(t, withPlanner = false) {+function harness(t, withPlanner = false, withDeletions = false) {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-pair-daemon-'));t.after(() => fs.rmSync(root, { recursive: true, force: true }));const rows = new Map();@@ -33,10 +33,15 @@ function harness(t, withPlanner = false) {accountSwitchInProgress: false, SESSION_COPY_COLUMNS: ['id', 'user_id'], sessionCopyLocks: new Map(), yieldAutoCopyToRenderer: async () => {}, assertSessionSyncIdle: async () => {},getSessionSyncCache: () => syncCacheMap, scheduleSessionSyncCacheSave: () => {},getSessionDirtyIndex: () => dirtyIndex,+ getSessionDeletionSync: () => null,setTimeout, clearTimeout,log: () => {}, sqliteQuery: async (_, params) => {+ if (_.includes('WHERE deleted_at IS NOT NULL')) return [...rows.values()].filter(row => row.deleted_at != null);+ if (_.startsWith('SELECT id, user_id, deleted_at FROM sessions')) {+ return [...rows.values()].filter(row => params.some((id, i) => i % 2 === 0 && row.id === id && row.user_id === params[i + 1])).map(row => ({ ...row }));+ }if (withPlanner && params.length === 1 && /FROM sessions WHERE deleted_at IS NULL.* user_id = \?/.test(_)) {- return [...rows.values()].filter(row => row.user_id === params[0]).map(row => ({ ...row }));+ return [...rows.values()].filter(row => row.user_id === params[0] && row.deleted_at == null).map(row => ({ ...row }));}if (params.length >= 4) {return [...rows.values()].filter((candidate) => String(candidate.user_id) === String(params[0]) &&@@ -44,18 +49,61 @@ function harness(t, withPlanner = false) {String(candidate.title || '') === String(params[2] || '') &&String(candidate.custom_title || '') === String(params[3] || '')).map((candidate) => ({ ...candidate }));}- const row = rows.get(params[0]); return row && (!params[1] || params[1] === row.user_id) ? [{ ...row }] : [];+ 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 deleted_at = ?')) {+ let changes = 0;+ for (let i = 2; i < params.length; i += 2) {+ const row = rows.get(params[i]);+ if (row && row.user_id === params[i + 1] && row.deleted_at == null) { row.deleted_at = params[0]; changes++; }+ }+ return { changes };+ }+ const row = rows.get(params[5]); assert.ok(row); Object.assign(row, { title: params[0], custom_title: params[1], status: params[2], updated_at: params[3], last_activity_at: params[4] });},- sqliteRun: async (_, params) => { const row = rows.get(params[5]); assert.ok(row); Object.assign(row, { title: params[0], custom_title: params[1], status: params[2], updated_at: params[3], last_activity_at: params[4] }); },insertCopiedSession: async (src, uid, id) => {const row = { ...src, user_id: uid, id, updated_at: Date.now(), last_activity_at: Number(src.last_activity_at || src.updated_at || Date.now()) };rows.set(id, row);return row;},};+ if (withDeletions) {+ const deletionSync = require('../scripts/session-deletion-sync').createSessionDeletionSync({+ query: ctx.sqliteQuery, run: ctx.sqliteRun, locks: ctx.sessionCopyLocks,+ members: ids => lib.collectLineageMembersForDelete(root, ids),+ });+ ctx.getSessionDeletionSync = () => deletionSync;+ }vm.runInNewContext(source.slice(source.indexOf('function sessionCopyContentRevision('), source.indexOf(withPlanner ? 'const autoCopyJobs' : 'async function buildAutoCopyPlan(')), ctx);return { root, rows, file, write, ctx, lineage, copy: () => ctx.copySessionRecord(rows.get('a'), 'two', { auto: true, lineageId: lineage }) };}+test('official deletion blocks reverse copy and propagates before the next switch plan', async t => {+ const h = harness(t, true, true);+ const refreshed = [];+ h.ctx.refreshWorkBuddySessionList = async uid => refreshed.push(uid);+ await h.copy();+ h.rows.get('a').deleted_at = 100;+ const before = fs.readFileSync(h.file('b'));+ const result = await h.ctx.copySessionRecord(h.rows.get('b'), 'one', { auto: true, lineageId: h.lineage });+ assert.equal(result.status, 'skipped');+ assert.equal(result.targetId, '', 'a deleted conversation must not be reopened after switching');+ assert.equal(h.rows.size, 3, 'the deleted target must not be replaced with a new physical session');+ assert.equal((await h.ctx.buildAutoCopyPlan('two', 'one')).length, 0);+ assert.equal((await h.ctx.buildAutoCopyPlan('one', 'two')).length, 0);+ assert.ok(h.rows.get('b').deleted_at && h.rows.get('c').deleted_at);+ assert.deepEqual(refreshed, ['one'], 'an all-deleted plan still refreshes the destination list');+ assert.deepEqual(fs.readFileSync(h.file('b')), before, 'soft deletion must preserve message files');+});++test('deletion during a copy guard aborts publication instead of recreating the target', async t => {+ const h = harness(t, true, true);+ lib.removeAutoCopySessionMember(h.root, h.lineage, 'two', 'b');+ h.rows.delete('b'); fs.unlinkSync(h.file('b'));+ h.ctx.assertSessionSyncIdle = async () => { h.rows.get('c').deleted_at = 100; };+ await assert.rejects(h.copy(), /已删除/);+ assert.equal([...h.rows.values()].filter(row => row.user_id === 'two').length, 0);+});test('account two continuation updates account one and never account three', async t => {const h = harness(t); h.write('b', [...base, { type: 'message', role: 'user', content: [{ text: 'continued' }] }]);const third = fs.readFileSync(h.file('c'));@@ -1003,3 +1051,25 @@ test('copy completion preserves timestamps of concurrent source and target dirtyassert.equal(h.ctx.getSessionDirtyIndex().get('two', 'b').at, at + 1);assert.equal((await h.switchTo('two', 'three')).length, 1);});++for (const duringCopy of [false, true]) test('deleting the active session never reopens its old mapping or blocks later automation: ' + duringCopy, async () => {+ let attempts = 0;+ const ctx = { codeBuddyFiles: null, crypto, DATA_DIR: 'fixture', PROFILE: { dataRoot: 'fixture' },+ autoCopyJobs: new Map(), autoCopyQueue: [], Date,+ yieldAutoCopyToRenderer: async () => {},+ buildAutoCopyPlan: async () => duringCopy ? [{ id: 'a', lineageId: 'lineage' }] : [],+ getSessionDeletionSync: () => ({ hasDeletion: async () => !duringCopy }),+ resolveAutoCopyTargetId: () => 'deleted-target',+ getAutoCopyMapping: () => ({ targetId: 'deleted-target' }),+ copySessionRecord: async () => { attempts++; const e = Error('同源会话已删除,停止同步'); e.code = 'WBS_SESSION_DELETED'; throw e; },+ log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout,+ };+ const start = source.indexOf('function startAutoCopyJob(');+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);+ const job = ctx.startAutoCopyJob('one', 'two', [], { openSessionId: 'a' });+ await ctx.autoCopyQueue[0].run();+ assert.equal(attempts, duringCopy ? 1 : 0, 'deletion is final, not a transient copy failure to retry');+ assert.equal(job.status, 'done');+ assert.equal(job.failed, 0);+ assert.equal(ctx.publicAutoCopyJob(job).openSessionId, '');+});diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.jsindex ae6371d..90c6576 100644--- a/test/windows-native-flow.test.js+++ b/test/windows-native-flow.test.js@@ -420,7 +420,7 @@ test('native startup precisely restarts a verified WorkBuddy without CDP', () =>const stop = launcher.slice(stopStart, stopEnd);assert.match(stop, /--terminate-workbuddy/);assert.match(stop, /--profile[\s\S]*PROFILE\.id/);- assert.match(stop, /result\.status !== 0[\s\S]*throw new Error/);+ assert.match(stop, /result\.status !== 0[\s\S]*error\.exitCode = result\.status[\s\S]*throw error/);const nativeMainStart = launcher.indexOf('async function nativeStartupMain()');const nativeMainEnd = launcher.indexOf('\n// ---------- legacy script entry', nativeMainStart);diff --git a/test/windows-startup-recovery.test.js b/test/windows-startup-recovery.test.jsnew file mode 100644index 0000000..b7e3f8e--- /dev/null+++ b/test/windows-startup-recovery.test.js@@ -0,0 +1,107 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const os = require('node:os');+const vm = require('node:vm');+const source = fs.readFileSync(path.join(__dirname, '../scripts/win-launcher.js'), 'utf8');++function harness({ changed = false, running = false, stable = true, recovered = true } = {}) {+ let now = 0, launches = 0, stops = 0, waits = 0;+ const context = {+ 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],+ isWorkBuddyCdpAt: async () => launches > 1 && recovered,+ launchWorkBuddy: () => { launches++; return { exitCode: 3221226505 }; },+ nativeWorkBuddyRunning: () => running, stopNativeWorkBuddy: () => { stops++; },+ nativeWorkBuddyProcessSummary: () => ({}), nativeWorkBuddyDiscoverySummary: () => ({}),+ readWorkBuddyInstallation: () => ({ signature: changed && launches ? 'new' : 'old', ready: true }),+ waitForStableWorkBuddyInstallation: async () => { waits++; if (!stable) { const e = Error('安装文件仍在变化'); e.exitCode = 15; throw e; } },+ };+ vm.runInNewContext(source.slice(source.indexOf('async function waitForWorkBuddyCdpNative('), source.indexOf('async function nativeStartupMain()')), context);+ return { context, run: () => context.waitForWorkBuddyCdpNative('fixture.exe'), counts: () => ({ launches, stops, waits }) };+}++test('installation changed during a failed launch: wait for stability then retry even without surviving processes', async () => {+ const h = harness({ changed: true });+ assert.equal(await h.run(), true);+ assert.deepEqual(h.counts(), { launches: 2, stops: 0, waits: 1 });+});+test('an unexplained crash fails without retry and keeps decimal/hex exit details', async () => {+ const h = harness();+ await assert.rejects(h.run(), error => error.exitCode === 14 && /3221226505.*0xC0000409/.test(error.message));+ assert.deepEqual(h.counts(), { launches: 1, stops: 0, waits: 0 });+});+test('update recovery is bounded to one retry', async () => {+ const h = harness({ changed: true, recovered: false });+ await assert.rejects(h.run(), error => error.exitCode === 14);+ assert.deepEqual(h.counts(), { launches: 2, stops: 0, waits: 1 });+});+test('unstable installation stops recovery without another spawn', async () => {+ const h = harness({ changed: true, stable: false });+ await assert.rejects(h.run(), error => error.exitCode === 15);+ assert.equal(h.counts().launches, 1);+});+test('existing handoff retry still stops only the verified profile process', async () => {+ const h = harness({ running: true });+ assert.equal(await h.run(), true);+ assert.deepEqual(h.counts(), { launches: 2, stops: 1, waits: 0 });+});+test('update recovery reuses a verified CDP endpoint that became ready while waiting', async () => {+ const h = harness({ changed: true, running: true });+ let ready = false;+ h.context.waitForStableWorkBuddyInstallation = async () => { ready = true; };+ h.context.isWorkBuddyCdpAt = async () => ready;+ assert.equal(await h.run(), true);+ assert.equal(h.counts().launches, 1);+ assert.equal(h.counts().stops, 0);+});+test('update recovery does not bypass a privilege or identity failure', async () => {+ const h = harness({ changed: true, running: true });+ h.context.stopNativeWorkBuddy = () => { const e = Error('boundary'); e.exitCode = 11; throw e; };+ await assert.rejects(h.run(), error => error.exitCode === 11);+ assert.equal(h.counts().launches, 1);+});+test('native termination errors retain boundary exit codes; unrelated exceptions remain generic', () => {+ const c = { PROFILE: { id: 'workbuddy-cn' }, runNativeHelper: () => ({ status: 11, stderr: 'fixture' }) };+ vm.runInNewContext(source.slice(source.indexOf('function stopNativeWorkBuddy()'), source.indexOf('function findWorkBuddyNative()')), c);+ assert.throws(() => c.stopNativeWorkBuddy(), error => error.exitCode === 11);+ const { nativeStartupExitCode } = require('../scripts/win-launcher');+ assert.equal(nativeStartupExitCode({ exitCode: 11 }), 11);+ assert.equal(nativeStartupExitCode({ exitCode: 12 }), 12);+ assert.equal(nativeStartupExitCode({ exitCode: 13 }), 13);+ assert.equal(nativeStartupExitCode({ exitCode: 14 }), 14);+ assert.equal(nativeStartupExitCode({ exitCode: 15 }), 15);+ assert.equal(nativeStartupExitCode({ exitCode: 0 }), 4);+ assert.equal(nativeStartupExitCode({ exitCode: 10 }), 4);+ assert.equal(nativeStartupExitCode(Error('unknown')), 4);+ assert.match(source, /finally\(\(\) => process\.exit\(nativeStartupExitCode\(error\)\)\)/);+});++test('installation sampling uses file metadata and waits for a continuous quiet period', async t => {+ const { readWorkBuddyInstallation, waitForStableWorkBuddyInstallation } = require('../scripts/windows-startup-recovery');+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-startup-stability-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const binary = path.join(root, 'WorkBuddy.exe');+ fs.mkdirSync(path.join(root, 'resources'));+ fs.writeFileSync(binary, 'fixture'); fs.writeFileSync(path.join(root, 'resources', 'app.asar'), 'fixture');+ const before = readWorkBuddyInstallation(binary);+ assert.equal(before.ready, true);+ fs.writeFileSync(path.join(root, 'resources', 'app.asar'), 'changed fixture');+ assert.notEqual(readWorkBuddyInstallation(binary).signature, before.signature);+ fs.unlinkSync(binary);+ assert.equal(readWorkBuddyInstallation(binary).ready, false);+ let now = 0;+ const samples = [{ signature: 'a', ready: true }, { signature: 'b', ready: true }, { signature: 'b', ready: false }];+ await waitForStableWorkBuddyInstallation(binary, 10000, {+ now: () => now, sleep: async ms => { now += ms; },+ read: () => samples.shift() || { signature: 'b', ready: true },+ });+ assert.ok(now >= 6000, 'missing files and later changes must reset the quiet interval');+ now = 0;+ await assert.rejects(waitForStableWorkBuddyInstallation(binary, 4000, {+ now: () => now, sleep: async ms => { now += ms; }, read: () => ({ signature: String(now), ready: true }),+ }), error => error.exitCode === 15);+});