WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
fix: revert automatic session deletion propagation to 1.2.18 behavior
[email protected]2b4789809d63
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex fd65d63..be4ab50 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 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+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[ -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 7769c8e..d40d2d2 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -177,7 +177,6 @@ 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,@@ -535,8 +534,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.77';-const DAEMON_BUILD_ID = 'release-1.2.77-workspace-picker-hit-area';+const DAEMON_VERSION = '1.2.78';+const DAEMON_BUILD_ID = 'release-1.2.78-stop-historical-deletion-propagation';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -5535,19 +5534,6 @@ 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@@ -5844,17 +5830,6 @@ 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];@@ -5953,7 +5928,6 @@ 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('会话记录正在变化,请稍后重试');}@@ -6018,7 +5992,6 @@ 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))) {@@ -6028,7 +6001,6 @@ 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.@@ -6106,10 +6078,6 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])if (!source || !target || source === target) return [];assertSessionAccountIdentity(source);assertSessionAccountIdentity(target);- 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 : [])@@ -6472,11 +6440,6 @@ 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);}@@ -6546,7 +6509,6 @@ 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++;@@ -6578,14 +6540,9 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {else job.copied++;if (result.failedFiles) job.failed += result.failedFiles;} catch (e) {- const deleted = e.code === 'WBS_SESSION_DELETED';- if (!deleted) recoverOpenSessionTarget(src);- else if (job.openSessionId === String(src.id || '')) {- job.openSessionId = '';- job.openSessionTargetId = '';- }+ recoverOpenSessionTarget(src);const errorText = String(e.message || e).slice(0, 240);- if (deleted || ['会话消息文件没有消息,未同步', '会话消息文件为空,未同步'].includes(errorText)) {+ if (['会话消息文件没有消息,未同步', '会话消息文件为空,未同步'].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') {@@ -12071,22 +12028,15 @@ 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');- }+ // Lifecycle notifications are indexing hints, not cross-account delete+ // authority. Historical deleted_at values cannot establish new intent+ // after an upgrade (#505); preserve the 1.2.18 behavior here.return json(res, 200, { ok: true, marked, initialized: getSessionDirtyIndex().isInitialized(uid) });} catch (e) {return json(res, 400, { ok: false, error: e.message });@@ -12380,11 +12330,10 @@ 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: '未选择会话' });- const deletions = getSessionDeletionSync();- return (deletions ? deletions.restore(ids) : sqliteRun(+ return 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/session-deletion-sync.js b/scripts/session-deletion-sync.jsdeleted file mode 100644index d51b89f..0000000--- a/scripts/session-deletion-sync.js+++ /dev/null@@ -1,97 +0,0 @@-'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/test/session-deletion-sync.test.js b/test/session-deletion-sync.test.jsindex 48602cf..a681471 100644--- a/test/session-deletion-sync.test.js+++ b/test/session-deletion-sync.test.js@@ -1,122 +1,82 @@-const assertSessionAccountIdentity = require('../scripts/account-identity').createSessionAccountResolver([]).assertUnambiguous;'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 vm = require('node:vm');+const { createSessionDb, normalizeSessionIdBatch } = require('../scripts/session-db');const lib = require('../scripts/lib');-const { createSessionDeletionSync } = require('../scripts/session-deletion-sync');+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');async function fixture(t) {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-deletion-sync-'));+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-upgrade-deletion-'));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']]) {+ for (const [id, uid, deletedAt] of [['a', 'one', 100], ['b', 'two', null], ['c', 'three', null]]) {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, deleted_at, updated_at) VALUES (?, ?, ?, 200)', [id, uid, deletedAt]);+ fs.writeFileSync(path.join(root, id + '.jsonl'), JSON.stringify({ type: 'message', sessionId: id, content: 'synthetic' }) + '\n');}- 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 };+ const calls = [];+ const context = {+ normalizeSessionIdBatch, assertSessionAccountIdentity: uid => uid,+ readBody: async req => req.body, currentAccount: () => ({ uid: 'two' }),+ json: (_, status, body) => ({ status, body }), isValidSessionId: id => /^[a-z-]+$/.test(id),+ markSessionDirty: (...args) => calls.push(['dirty', ...args]),+ markSessionDirtyBaseline: uid => calls.push(['baseline', uid]),+ getSessionDirtyIndex: () => ({ isInitialized: () => true }),+ // Notifications must remain an index update, not a deletion authority.+ getSessionDeletionSync() { throw Error('unexpected deletion propagation'); },+ sqliteRun: (sql, params) => db.run(sql, Array.from(params)),+ sqlPlaceholders: ids => ids.map(() => '?').join(','),+ };+ for (const [name, route] of [['dirty', '/api/sessions/dirty'], ['restore', '/api/sessions/restore']]) {+ const start = source.indexOf(" if (req.method === 'POST' && p === '" + route + "')");+ const end = source.indexOf('\n }', start) + 4;+ assert.ok(start > 0 && end > start);+ vm.runInNewContext('async function ' + name + '(req,res) { const p=' + JSON.stringify(route) + ';\n' + source.slice(start, end) + '\n}', context);+ }+ return { root, db, calls, context,+ rows: () => db.all('SELECT * FROM sessions ORDER BY id'),+ call: (name, body) => context[name]({ method: 'POST', body }, {}),+ };}-test('official soft deletion propagates across known copies and survives restart; restore is lineage-wide', async t => {+for (const body of [+ { uid: 'two', ready: true, events: [] },+ { uid: 'two', events: [{ id: 'b', event: 'sessionUpdated' }] },+ { uid: 'two', events: [{ id: 'b', event: 'sessionDeleted' }] },+]) test('renderer notification cannot spread a historical deletion: ' + JSON.stringify(body), 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']);+ const before = await f.rows();+ const meta = fs.readFileSync(path.join(f.root, 'meta.json'));+ const messages = ['a', 'b', 'c'].map(id => fs.readFileSync(path.join(f.root, id + '.jsonl')));+ for (let reload = 0; reload < 2; reload++) {+ const result = await f.call('dirty', body);+ assert.equal(result.status, 200);+ assert.deepEqual(await f.rows(), before, 'startup and lifecycle notifications must not change any deletion marker');+ }+ assert.deepEqual(fs.readFileSync(path.join(f.root, 'meta.json')), meta);+ for (const [index, id] of ['a', 'b', 'c'].entries()) assert.deepEqual(fs.readFileSync(path.join(f.root, id + '.jsonl')), messages[index]);+ assert.ok(f.calls.length > 0, 'incremental dirty indexing still receives notifications');});-test('deletion waits for in-flight copy, then includes the copy published before lock release', async t => {+test('stale renderer account remains rejected before marking sessions dirty', 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);+ assert.equal((await f.call('dirty', { uid: 'one', events: [{ id: 'a', event: 'sessionDeleted' }] })).status, 409);+ assert.deepEqual(f.calls, []);});-test('a failed database write leaves deletion evidence for a later retry', async t => {+test('explicit restore only restores requested ids, preserving other intentional deletions', 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 = { assertSessionAccountIdentity,- 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']]);+ await f.db.run('UPDATE sessions SET deleted_at = 200 WHERE id = ?', ['b']);+ const result = await f.call('restore', { ids: ['b'] });+ assert.equal(result.status, 200);+ const rows = await f.rows();+ assert.equal(rows.find(row => row.id === 'a').deleted_at, 100);+ assert.equal(rows.find(row => row.id === 'b').deleted_at, null);+ assert.equal(rows.find(row => row.id === 'c').deleted_at, null);});diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.jsindex 3ccc2ed..89a5374 100644--- a/test/session-sync-daemon.test.js+++ b/test/session-sync-daemon.test.js@@ -14,7 +14,7 @@ const { sanitizeSessionCopyError } = require('../scripts/session-copy-error');const assertSessionAccountIdentity = createSessionAccountResolver([]).assertUnambiguous;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, withDeletions = false) {+function harness(t, withPlanner = 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();@@ -36,7 +36,6 @@ function harness(t, withPlanner = false, withDeletions = 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);@@ -71,40 +70,33 @@ function harness(t, withPlanner = false, withDeletions = false) {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();+test('historical deletion on another account cannot delete or block live copies on switch', async t => {+ const h = harness(t, true);h.rows.get('a').deleted_at = 100;+ lib.setAutoCopyAllSessions(h.root, true);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');+ const plan = await h.ctx.buildAutoCopyPlan('two', 'four');+ assert.equal(plan.length, 1);+ assert.equal(plan[0].id, 'b');+ assert.equal(h.rows.get('b').deleted_at, undefined);+ assert.equal(h.rows.get('c').deleted_at, undefined);+ const result = await h.ctx.copySessionRecord(plan[0], 'four', { auto: true, lineageId: plan[0].lineageId });+ assert.equal(result.status, 'copied');+ assert.ok(result.targetId);+ assert.deepEqual(fs.readFileSync(h.file(result.targetId)), before);+ assert.deepEqual(fs.readFileSync(h.file('b')), before);+ assert.equal(h.rows.get('a').deleted_at, 100, 'do not silently restore the old deletion either');});test('deletion during a copy guard aborts publication instead of recreating the target', async t => {- const h = harness(t, true, true);+ const h = harness(t, 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(), /已删除/);+ h.ctx.assertSessionSyncIdle = async () => { h.rows.get('a').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 => {@@ -1113,25 +1105,3 @@ 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, assertSessionAccountIdentity, sanitizeSessionCopyError, 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, '');-});