WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const vm = require('node:vm');
const crypto = require('node:crypto');
const lib = require('../scripts/lib.js');
const sessionSync = require('../scripts/session-sync.js');
const { createDirtyIndex } = require('../scripts/session-dirty.js');
const { createSessionAccountResolver } = require('../scripts/account-identity');
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) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-pair-daemon-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const rows = new Map();
const file = id => path.join(root, 'projects', 'p', id + '.jsonl');
const write = (id, messages) => { fs.mkdirSync(path.dirname(file(id)), { recursive: true }); fs.writeFileSync(file(id), messages.map(x => JSON.stringify(x)).join('\n') + '\n'); };
const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
for (const [id, uid] of [['a', 'one'], ['b', 'two'], ['c', 'three']]) {
rows.set(id, { id, user_id: uid, title: 'fixture', created_at: 1, updated_at: 1 });
lib.addAutoCopySessionMember(root, lineage, uid, id); write(id, base);
}
const syncCacheMap = new Map();
const dirtyIndex = createDirtyIndex(); dirtyIndex.markBaseline('one');
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, sessionSync, fs, path, crypto, DATA_DIR: root, PROFILE: { dataRoot: root, kind: 'workbuddy' }, createDirtyIndex,
sessionCopyRowRevision: row => JSON.stringify([
String(row && row.id || ''), String(row && row.user_id || ''),
Number(row && row.updated_at || 0), Number(row && row.last_activity_at || 0),
String(row && row.status || ''), String(row && row.title || ''), String(row && row.custom_title || ''),
]),
accountSwitchInProgress: false, SESSION_COPY_COLUMNS: ['id', 'user_id'], sessionCopyLocks: new Map(), yieldAutoCopyToRenderer: async () => {}, assertSessionSyncIdle: async () => {},
getSessionSyncCache: () => syncCacheMap, scheduleSessionSyncCacheSave: () => {},
getSessionDirtyIndex: () => dirtyIndex,
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] && row.deleted_at == null).map(row => ({ ...row }));
}
if (params.length >= 4) {
return [...rows.values()].filter((candidate) => String(candidate.user_id) === String(params[0]) &&
String(candidate.cwd || '') === String(params[1] || '') &&
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) && (!_.includes('deleted_at IS NULL') || row.deleted_at == null) ? [{ ...row }] : [];
},
sqliteRun: async (_, params) => {
if (_.startsWith('UPDATE sessions SET title = ?, custom_title = ?, updated_at = ?')) {
const row = rows.get(params[3]);
assert.ok(row); Object.assign(row, { title: params[0], custom_title: params[1], updated_at: params[2] });
return { changes: 1 };
}
if (_.startsWith('UPDATE sessions SET deleted_at = ?')) {
let changes = 0;
for (let i = 2; i < params.length; i += 2) {
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] });
},
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;
},
};
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('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 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);
lib.removeAutoCopySessionMember(h.root, h.lineage, 'two', 'b');
h.rows.delete('b'); fs.unlinkSync(h.file('b'));
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 => {
const h = harness(t); h.write('b', [...base, { type: 'message', role: 'user', content: [{ text: 'continued' }] }]);
const third = fs.readFileSync(h.file('c'));
const result = await h.copy();
assert.equal(result.status, 'copied');
assert.deepEqual(fs.readFileSync(h.file('a')), fs.readFileSync(h.file('b')));
assert.deepEqual(fs.readFileSync(h.file('c')), third);
assert.equal(result.warning, '');
assert.equal(result.totalBytes, fs.statSync(h.file('a')).size);
assert.equal(result.copiedBytes, fs.statSync(h.file('a')).size);
assert.equal((await h.copy()).copiedBytes, 0);
});
test('fork and original keep separate runtime identities and continuations across workspace account switches', async t => {
const h = harness(t, true);
for (const [id, uid] of [['b', 'two'], ['c', 'three']]) {
lib.removeAutoCopySessionMember(h.root, h.lineage, uid, id);
h.rows.delete(id);
fs.unlinkSync(h.file(id));
}
const fork = require('../scripts/session-fork');
Object.assign(h.ctx, {
Buffer, forkedTitle: fork.forkedTitle, planForkAtMessage: fork.planForkAtMessage,
collectSessionArchiveFiles: (_root, id) => [{ path: 'projects/p/' + id + '.jsonl', source: h.file(id) }],
ensureArchiveParentNoFollow() {},
});
const start = source.indexOf('async function createForkSession(');
vm.runInNewContext(source.slice(start, source.indexOf('\nasync function prepareSessionExport(', start)), h.ctx);
const original = h.rows.get('a');
Object.assign(original, { cwd: '/fixture/workspace', status: 'completed', last_activity_at: 1 });
lib.setAutoCopyRule(h.root, { uid: 'one', kind: 'workspace', key: original.cwd, enabled: true });
const records = ['user', 'assistant', 'user', 'assistant'].map((role, index) => ({
type: 'message', role, sessionId: 'a', timestamp: 10000 + index * 1000,
content: [{ text: 'shared history ' + index }],
}));
h.write('a', records);
const branch = await h.ctx.createForkSession(original, { messageIndex: 1, roles: 'uaua', finishedAt: 11000 });
const read = id => fs.readFileSync(h.file(id), 'utf8').trim().split('\n').map(JSON.parse);
assert.ok(read(branch.id).every(record => record.sessionId === branch.id), 'fork must resume as itself before switching');
const continueSession = (id, label) => {
h.write(id, [...read(id), { type: 'message', role: 'user', sessionId: id, content: [{ text: label }] }]);
Object.assign(h.rows.get(id), { updated_at: Date.now(), last_activity_at: Date.now() });
};
continueSession(branch.id, 'branch continuation');
continueSession('a', 'original continuation');
const originalBefore = fs.readFileSync(h.file('a'));
const branchBefore = fs.readFileSync(h.file(branch.id));
const switchTo = async (from, to) => {
for (const row of await h.ctx.buildAutoCopyPlan(from, to)) {
await h.ctx.copySessionRecord(row, to, { auto: true, lineageId: row.lineageId });
}
};
await switchTo('one', 'two');
const branchLineage = lib.getAutoCopySession(h.root, 'one', branch.id).lineageId;
assert.notEqual(branchLineage, h.lineage);
const copies = [h.lineage, branchLineage].map(lineage => lib.getAutoCopyMapping(h.root, lineage, 'two').targetId);
assert.equal(new Set(copies).size, 2);
assert.equal([...h.rows.values()].filter(row => row.user_id === 'two' && row.deleted_at == null).length, 2);
for (const [index, id] of copies.entries()) {
assert.ok(read(id).every(record => record.sessionId === id));
assert.deepEqual(read(id), read(index === 0 ? 'a' : branch.id).map(record => ({ ...record, sessionId: id })));
}
continueSession(copies[1], 'branch on account two');
await switchTo('two', 'one');
assert.deepEqual(fs.readFileSync(h.file('a')), originalBefore, 'branch edits must never overwrite the original');
assert.notDeepEqual(fs.readFileSync(h.file(branch.id)), branchBefore);
assert.equal(read(branch.id).at(-1).content[0].text, 'branch on account two');
assert.ok(read(branch.id).every(record => record.sessionId === branch.id));
const rows = [...h.rows.values()].filter(row => row.user_id === 'one');
assert.equal(lib.dedupeAutoCopySessionRows(rows, { one: lib.getAutoCopyRules(h.root, 'one').allLineages }).length, 2);
});
test('legacy equal mappings repair runtime IDs once instead of taking the revision fast path', async t => {
const h = harness(t);
const records = base.map(row => ({ ...row, sessionId: 'a' }));
h.write('a', records); h.write('b', records);
lib.setAutoCopyMapping(h.root, h.lineage, 'two', {
targetId: 'b', fingerprintVersion: 2,
sourceRevision: h.ctx.sessionCopyRowRevision(h.rows.get('a')),
targetRevision: h.ctx.sessionCopyRowRevision(h.rows.get('b')),
});
const original = fs.readFileSync(h.file('a'));
const result = await h.copy();
assert.equal(result.status, 'copied');
assert.deepEqual(fs.readFileSync(h.file('a')), original);
assert.deepEqual(fs.readFileSync(h.file('b'), 'utf8').trim().split('\n').map(JSON.parse),
records.map(row => ({ ...row, sessionId: 'b' })));
assert.equal(lib.getAutoCopyMapping(h.root, h.lineage, 'two').fingerprintVersion, 3);
assert.equal((await h.copy()).copiedBytes, 0);
});
test('automatic first copy to an account with no physical target streams snapshots and file copies', async t => {
const h = harness(t);
lib.removeAutoCopySessionMember(h.root, h.lineage, 'two', 'b');
h.rows.delete('b');
fs.rmSync(h.file('b'), { force: true });
let syncReads = 0;
let asyncReads = 0;
const readSnapshot = h.ctx.sessionSync.readSnapshot;
const readSnapshotAsync = h.ctx.sessionSync.readSnapshotAsync;
h.ctx.sessionSync.readSnapshot = (...args) => { syncReads++; return readSnapshot(...args); };
h.ctx.sessionSync.readSnapshotAsync = async (...args) => { asyncReads++; return readSnapshotAsync(...args); };
try {
const result = await h.copy();
assert.equal(result.status, 'copied');
assert.equal(syncReads, 0, 'first-time copies must not buffer whole sessions');
assert.ok(asyncReads > 0, 'first-time copies must use streaming snapshots');
const mapping = lib.getAutoCopyMapping(h.root, h.lineage, 'two');
assert.equal(mapping.targetStateRevision, h.ctx.sessionCopyStableStateRevision(h.rows.get(result.targetId)),
'new mappings must record the inserted target row revision');
} finally {
h.ctx.sessionSync.readSnapshot = readSnapshot;
h.ctx.sessionSync.readSnapshotAsync = readSnapshotAsync;
}
});
test('stale active-session lifecycle markers are cleared after an equal payload probe', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-active-lifecycle-dirty-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const write = (id) => {
const file = path.join(root, 'projects', 'p', id + '.jsonl');
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, base.map((item) => JSON.stringify(item)).join('\n') + '\n');
};
write('a'); write('b');
fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
version: 1, accounts: { one: { initialized: true, sessions: { a: { at: 123, event: 'sessionUpdated' } } } },
}));
lib.setAutoCopyAllSessions(root, true);
const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 8, last_activity_at: 8 };
const targetRow = { ...sourceRow, id: 'b', user_id: 'two', updated_at: 7, last_activity_at: 7 };
const revision = row => JSON.stringify([
String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: 'b', fingerprintVersion: 3,
sourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),
targetRevision: revision(targetRow),
});
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
...lib, fs, path, DATA_DIR: root, PROFILE: { dataRoot: root }, sessionSync,
createDirtyIndex, getSessionSyncCache: () => new Map(),
setTimeout, clearTimeout,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }],
};
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two', ['a'])).length, 0);
assert.equal(ctx.getSessionDirtyIndex().get('one', 'a'), null, 'equal active payloads clear the stale lifecycle marker');
assert.equal(lib.getAutoCopyMapping(root, lineage, 'two').sourceRevision, revision(sourceRow));
});
test('missing mapping recovers an equal target row instead of creating a duplicate', async t => {
const h = harness(t);
for (const row of h.rows.values()) { row.cwd = '/fixture'; row.custom_title = ''; }
lib.removeAutoCopySessionMember(h.root, h.lineage, 'two', 'b');
const before = [...h.rows.values()].filter((row) => row.user_id === 'two').length;
const result = await h.copy();
assert.equal(result.status, 'skipped');
assert.equal(result.targetId, 'b');
assert.equal([...h.rows.values()].filter((row) => row.user_id === 'two').length, before);
assert.equal(lib.getAutoCopyMapping(h.root, h.lineage, 'two').targetId, 'b');
});
test('automatic repeat sync rechecks persisted content and reports no writes', async t => {
const h = harness(t);
assert.equal((await h.copy()).status, 'skipped');
const originalSnapshot = h.ctx.sessionSync.readSnapshotAsync;
const originalQuickFingerprint = h.ctx.sessionSync.readSessionQuickFingerprintAsync;
let fullReads = 0;
let quickReads = 0;
h.ctx.sessionSync.readSnapshotAsync = async (...args) => { fullReads++; return originalSnapshot(...args); };
h.ctx.sessionSync.readSessionQuickFingerprintAsync = async (...args) => { quickReads++; return originalQuickFingerprint(...args); };
try {
const result = await h.copy();
assert.equal(result.status, 'skipped');
assert.equal(result.copiedBytes, 0);
assert.equal(fullReads, 0, 'unchanged mapped sessions should skip full snapshots');
assert.equal(quickReads, 0, 'unchanged mapped sessions use DB revisions without filesystem scans');
} finally {
h.ctx.sessionSync.readSnapshotAsync = originalSnapshot;
h.ctx.sessionSync.readSessionQuickFingerprintAsync = originalQuickFingerprint;
}
});
test('reverse sync skips an activation-only append after the first account copy', async t => {
const h = harness(t);
const first = await h.copy();
assert.equal(first.status, 'skipped');
h.write('b', [...base, { type: 'session-meta', id: 'activation-b', sessionId: 'b', timestamp: 99, meta: { 'codebuddy.ai/hostKind': 'unopted' } }]);
const reverse = await h.ctx.copySessionRecord(h.rows.get('b'), 'one', {
auto: true, sourceUid: 'two', lineageId: h.lineage,
});
assert.equal(reverse.status, 'skipped');
assert.equal(reverse.copiedBytes, 0);
assert.equal(reverse.targetId, 'a');
});
test('automatic sync falls back to snapshots when a session row revision changes', async t => {
const h = harness(t);
assert.equal((await h.copy()).status, 'skipped');
h.write('a', [...base, nextMessage('changed')]);
h.rows.get('a').updated_at++;
const originalSnapshot = h.ctx.sessionSync.readSnapshotAsync;
let fullReads = 0;
h.ctx.sessionSync.readSnapshotAsync = async (...args) => { fullReads++; return originalSnapshot(...args); };
try {
const result = await h.copy();
assert.equal(result.status, 'copied');
assert.ok(fullReads > 0, 'changed DB revisions should leave the fast path');
} finally {
h.ctx.sessionSync.readSnapshotAsync = originalSnapshot;
}
});
test('automatic copy planning drops revision-stable mappings before workers', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-daemon-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({ version: 1, accounts: { one: { initialized: true, sessions: {} } } }));
lib.setAutoCopyAllSessions(root, true);
const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7 };
const target = { ...sourceRow, id: 'b', user_id: 'two' };
const revision = row => JSON.stringify([
String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(sourceRow), targetRevision: revision(target),
});
let targetQueries = 0;
const makeContext = () => ({ assertSessionAccountIdentity, ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => { if (String(params[0]) === 'two') targetQueries++; return [String(params[0]) === 'one' ? { ...sourceRow } : { ...target }]; } });
const start = source.indexOf('function sessionCopyContentRevision(');
let ctx = makeContext();
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0, 'stable mapped sessions should not enter the copy worker pool');
assert.equal(targetQueries, 0, 'clean plans should not query the target account');
sourceRow.updated_at++;
sourceRow.last_activity_at++;
fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
version: 1, accounts: { one: { initialized: true, sessions: { a: { at: 123, event: 'sessionUpdated' } } } },
}));
ctx = makeContext();
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 1, 'a changed source revision should be planned');
assert.equal(targetQueries, 1, 'dirty plans should query the target account once');
fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
version: 1, accounts: { one: { initialized: true, sessions: {} } },
}));
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision(target),
});
ctx = makeContext();
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 1, 'legacy clean copies need one runtime identity repair');
assert.equal((await ctx.buildAutoCopyPlan('one', 'two', ['a'])).length, 1, 'active legacy copies must be repaired before opening');
});
test('initialized clean mappings ignore legacy source revision drift', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-clean-revision-drift-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
version: 1, accounts: { one: { initialized: true, sessions: {} } },
}));
lib.setAutoCopyAllSessions(root, true);
const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 8, last_activity_at: 8 };
const targetRow = { ...sourceRow, id: 'b', user_id: 'two' };
const revision = row => JSON.stringify([
String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: 'b', fingerprintVersion: 3,
sourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),
targetRevision: revision(targetRow),
});
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }],
};
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0, 'clean initialized mappings should not enter the worker for historical revision drift');
});
test('automatic copy planning reuses a stable cross-account mapping without a worker', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-cross-account-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
lib.setAutoCopyAllSessions(root, true);
const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
lib.addAutoCopySessionMember(root, lineage, 'three', 'c');
lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7 };
const previousSource = { ...sourceRow, id: 'c', user_id: 'three' };
const target = { ...sourceRow, id: 'b', user_id: 'two' };
const revision = row => JSON.stringify([
String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(previousSource), targetRevision: revision(target),
});
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, DATA_DIR: root, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...target }] };
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0, 'cross-account stable mappings should not enter the copy worker pool');
sourceRow.updated_at++;
sourceRow.last_activity_at++;
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 1, 'a changed cross-account source revision should be planned');
});
test('automatic copy planning ignores target activation lifecycle drift', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-target-lifecycle-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
version: 1, accounts: { one: { initialized: true, sessions: {} } },
}));
lib.setAutoCopyAllSessions(root, true);
const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
const sourceRow = { id: 'a', user_id: 'one', title: 'fixture', custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7 };
const targetRow = { ...sourceRow, id: 'b', user_id: 'two', status: 'running', last_activity_at: 99 };
const revision = row => JSON.stringify([
String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(sourceRow), targetRevision: revision({ ...sourceRow, id: 'b', user_id: 'two' }),
});
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? sourceRow : targetRow],
};
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0, 'activation metadata must not enter the copy worker');
assert.equal((await ctx.buildAutoCopyPlan('one', 'two', ['a'])).length, 0, 'active-session restoration must also stay on the metadata path');
});
test('source activation-only updated_at drift clears dirty state without a snapshot worker', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-source-lifecycle-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
version: 1, accounts: { one: { initialized: true, sessions: { a: { at: 123, event: 'sessionUpdated' } } } },
}));
lib.setAutoCopyAllSessions(root, true);
const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 9, last_activity_at: 7 };
const targetRow = { ...sourceRow, id: 'b', user_id: 'two', updated_at: 8 };
const revision = row => JSON.stringify([
String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: 'b', fingerprintVersion: 3, sourceRevision: revision({ ...sourceRow, updated_at: 8 }),
targetRevision: revision(targetRow),
});
let snapshotReads = 0;
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
...lib, fs, path, DATA_DIR: root, PROFILE: { dataRoot: root }, createDirtyIndex,
setTimeout, clearTimeout, getSessionSyncCache: () => new Map(),
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: revision,
sessionSync: {
readSnapshotAsync: async () => { snapshotReads++; throw new Error('activation-only drift must stay off the snapshot worker'); },
compareSnapshots: () => ({ kind: 'equal' }),
},
sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }],
};
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0);
assert.equal(snapshotReads, 0);
assert.equal(ctx.getSessionDirtyIndex().get('one', 'a'), null);
});
test('active sync status ignores a recent job for another target account', () => {
const start = source.indexOf('function activeAutoCopyJob(');
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
Date: { now: () => 10000 },
autoCopyJobs: new Map([
['other', { id: 'other', targetUid: 'two', status: 'done', finishedAt: 9900, startedAt: 9000 }],
['current', { id: 'current', targetUid: 'one', status: 'done', finishedAt: 9800, startedAt: 8800 }],
]),
};
vm.runInNewContext(source.slice(start, source.indexOf('const MAX_SESSION_ID_LENGTH', start)), ctx);
assert.equal(ctx.activeAutoCopyJob('one').id, 'current');
assert.equal(ctx.activeAutoCopyJob('missing'), null);
});
test('explicitly requested open session is planned without regular auto-copy rules', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-requested-session-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const sourceRow = {
id: 'open-session', user_id: 'one', cwd: '/fixture', title: 'Open conversation',
custom_title: '', status: 'completed', created_at: 1, updated_at: 7, last_activity_at: 7,
};
const targetRow = { ...sourceRow, id: 'other-session', user_id: 'two' };
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
...lib, fs, path, DATA_DIR: root,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: row => JSON.stringify([
String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]),
sqliteQuery: async (_, params) => String(params[0]) === 'one' ? [{ ...sourceRow }] : [{ ...targetRow }],
};
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
const plan = await ctx.buildAutoCopyPlan('one', 'two', ['open-session']);
assert.deepEqual(plan.map(row => row.id), ['open-session']);
assert.equal(plan[0].lineageId, null, 'an explicitly requested session need not already have a copy lineage');
});
test('requested unchanged open session resolves its mapping without entering the copy worker', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-requested-clean-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
version: 1, accounts: { one: { initialized: true, sessions: {} } },
}));
lib.setAutoCopyAllSessions(root, true);
const lineage = lib.ensureAutoCopySession(root, 'one', 'open-session');
lib.addAutoCopySessionMember(root, lineage, 'two', 'copied-session');
const sourceRow = {
id: 'open-session', user_id: 'one', cwd: '/fixture', title: 'Open conversation',
custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7,
};
const targetRow = { ...sourceRow, id: 'copied-session', user_id: 'two' };
const revision = row => JSON.stringify([
String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0),
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: targetRow.id, fingerprintVersion: 3,
sourceRevision: revision(sourceRow), targetRevision: revision(targetRow),
});
let targetQueries = 0;
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
...lib, fs, path, DATA_DIR: root, createDirtyIndex,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => {
if (String(params[0]) === 'two') targetQueries++;
return [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }];
},
};
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two', ['open-session'])).length, 0);
assert.equal(targetQueries, 1, 'requested recovery may read the target row but must not snapshot it');
});
test('stable mappings clear legacy lifecycle dirty markers before planning', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-plan-stale-dirty-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({ version: 1, accounts: { one: { initialized: true, sessions: { a: { at: 123, event: 'sessionUpdated' } } } } }));
lib.setAutoCopyAllSessions(root, true);
const lineage = lib.ensureAutoCopySession(root, 'one', 'a');
lib.addAutoCopySessionMember(root, lineage, 'two', 'b');
const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7 };
const targetRow = { ...sourceRow, id: 'b', user_id: 'two' };
const revision = row => JSON.stringify([String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0), String(row.status || ''), String(row.title || ''), String(row.custom_title || '')]);
lib.setAutoCopyMapping(root, lineage, 'two', { targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(sourceRow), targetRevision: revision(targetRow) });
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision, sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }] };
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0);
assert.equal(ctx.getSessionDirtyIndex().get('one', 'a'), null);
});
test('sessions over 100 MiB copy completely and report only an advisory, including on repeat sync', async t => {
const h = harness(t);
const file = path.join(h.root, 'workspace/sessions/a/large.bin');
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, 'large session fixture');
const size = 100 * 1024 * 1024 + 1;
fs.truncateSync(file, size);
const result = await h.copy();
assert.equal(result.status, 'copied');
assert.equal(result.failedFiles, 0);
assert.equal(result.warning, '会话超过 100 MB,同步可能较慢');
const target = path.join(h.root, 'workspace/sessions/b/large.bin');
assert.equal(fs.statSync(target).size, size);
assert.equal(result.totalBytes, size + fs.statSync(h.file('b')).size);
const hash = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
assert.equal(hash(target), hash(file));
const repeat = await h.copy();
assert.equal(repeat.status, 'skipped');
assert.equal(repeat.warning, result.warning);
});
test('divergent copies survive repeated switches and stale mappings cannot force overwrite', async t => {
const h = harness(t);
h.write('a', [...base, { type: 'message', role: 'user', content: [{ text: 'branch one' }] }]);
h.write('b', [...base, { type: 'message', role: 'user', content: [{ text: 'branch two' }] }]);
const a = fs.readFileSync(h.file('a')), b = fs.readFileSync(h.file('b'));
for (let i = 0; i < 2; i++) {
const result = await h.copy();
assert.equal(result.status, i === 0 ? 'copied' : 'skipped');
if (i === 0) { assert.equal(result.branched, true); assert.deepEqual(fs.readFileSync(h.file(result.targetId)), a); }
assert.equal([...h.rows.values()].filter(row => row.user_id === 'two').length, 2);
assert.deepEqual(fs.readFileSync(h.file('a')), a); assert.deepEqual(fs.readFileSync(h.file('b')), b);
}
});
test('missing target rows and missing target payloads are filled without consulting third-account conflicts', async t => {
const h = harness(t); h.write('c', [{ type: 'message', role: 'user', content: [{ text: 'third branch' }] }]);
fs.unlinkSync(h.file('b'));
assert.equal((await h.copy()).status, 'copied');
assert.deepEqual(fs.readFileSync(h.file('b')), fs.readFileSync(h.file('a')));
h.rows.delete('b'); fs.unlinkSync(h.file('b'));
lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b', updatedAt: 1 });
const result = await h.copy();
assert.equal(result.status, 'copied'); assert.notEqual(result.targetId, 'b');
assert.equal((await h.copy()).status, 'skipped');
assert.equal([...h.rows.values()].filter(row => row.user_id === 'two').length, 1);
});
test('manual and automatic switching bypass session activity while retaining operation locks', async () => {
const start = source.indexOf('async function assertSessionSyncIdle(');
const end = source.indexOf('let automationAccountSwitchTail', start);
assert.ok(start >= 0 && end > start);
const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, accountSwitchInProgress: false, cdp: { connected: true }, PROFILE: { kind: 'workbuddy' }, autoCopyWorkerRunning: false, autoCopyQueue: [], sessionCopyLocks: new Map(),
cdpSend: async () => ({ result: { value: true } }) };
vm.runInNewContext(source.slice(start, end), ctx);
await assert.rejects(ctx.assertSessionSyncIdle(['source', 'target']), /会话仍在运行/);
ctx.cdpSend = async () => ({ result: { value: null } });
await assert.rejects(ctx.assertSessionSyncIdle(), /无法确认/);
ctx.cdpSend = async () => ({ result: { value: false } }); await ctx.assertSessionSyncIdle();
ctx.cdp.connected = false;
ctx.cdpSend = async () => { throw Error('Switching must not query session activity'); };
const release = await ctx.assertAccountSwitchIdle();
await assert.rejects(ctx.assertAccountSwitchIdle(), /账号正在切换/);
release();
ctx.cdp.connected = true;
ctx.cdpSend = async () => ({ result: { value: true } });
(await ctx.assertAccountSwitchIdle())();
for (const key of ['autoCopyWorkerRunning', 'autoCopyQueue', 'sessionCopyLocks']) {
const previous = ctx[key];
ctx[key] = key === 'autoCopyWorkerRunning' ? true : key === 'autoCopyQueue' ? [{}] : new Map([['fixture', true]]);
await assert.rejects(ctx.assertAccountSwitchIdle(), /会话同步尚未完成/);
ctx[key] = previous;
(await ctx.assertAccountSwitchIdle())();
}
for (const block of [source.slice(source.indexOf('function automationSwitchAccount('), source.indexOf('function startAutomationRun(')), source.slice(source.indexOf("if (req.method === 'POST' && p === '/api/switch')"))]) {
assert.ok(/await (assertAccountSwitchIdle|acquireAutomationAccountSwitch)\(/.test(block) && block.search(/await (assertAccountSwitchIdle|acquireAutomationAccountSwitch)\(/) < block.indexOf('await switchAccountForProfile(uid)'));
}
});
test('mixed sync jobs continue after divergence and report every result', async () => {
const results = ['conflict', 'copied', 'skipped', 'error'];
let sizeReads = 0;
const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => results.map((_, i) => ({ id: String(i) })),
copySessionRecord: async row => { const status = results[Number(row.id)]; if (status === 'error') throw Error('fixture failure'); return { status, branched: status === 'copied', copiedBytes: status === 'copied' ? 123456 : 0, totalBytes: 123456, warning: status === 'copied' ? 'large session advisory' : '' }; },
sessionSync: { readSessionSizes: async () => { sizeReads++; return new Map(); } },
log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout: () => ({ unref() {} }),
};
const start = source.indexOf('function startAutoCopyJob(');
vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
const job = ctx.startAutoCopyJob('one', 'two', []);
await ctx.autoCopyQueue[0].run();
assert.equal(job.processed, 4);
assert.equal(sizeReads, 0);
assert.equal(job.copiedBytes, 123456);
assert.equal(job.conflicts, 1); assert.equal(job.copied, 1); assert.equal(job.skipped, 1); assert.equal(job.failedItems, 1);
assert.equal(job.details[1].branched, true);
assert.equal(job.details[1].warning, 'large session advisory');
assert.equal(job.warning, 'large session advisory');
assert.deepEqual(Array.from(job.details, item => item.status), ['conflict', 'copied', 'skipped', 'failed']);
results.splice(0, results.length, 'copied', 'skipped');
const advisoryOnly = ctx.startAutoCopyJob('one', 'two', []);
await ctx.autoCopyQueue[1].run();
const published = ctx.publicAutoCopyJob(advisoryOnly);
assert.equal(published.status, 'done');
assert.equal(published.failed, 0);
assert.equal(published.failedItems, 0);
assert.equal(published.warning, 'large session advisory');
assert.equal(published.details[0].warning, 'large session advisory');
assert.equal(published.details[0].totalBytes, 123456);
});
test('active session copy retries transient file races and preserves its target id', async () => {
let attempts = 0;
const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
DATA_DIR: 'fixture-data',
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {},
buildAutoCopyPlan: async () => [{ id: 'active-source', lineageId: 'lineage-active' }],
copySessionRecord: async () => {
attempts++;
if (attempts === 1) throw Error('会话文件正在变化,请稍后重试');
return { status: 'copied', sourceId: 'active-source', targetId: 'active-target', sourceBytes: 1, copiedBytes: 1, totalBytes: 1 };
},
getAutoCopyMapping: () => null,
getAutoCopySession: () => ({ lineageId: 'lineage-active' }),
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('source', 'target', [], { openSessionId: 'active-source' });
await ctx.autoCopyQueue[0].run();
assert.equal(attempts, 2);
assert.equal(job.failed, 0);
assert.equal(ctx.publicAutoCopyJob(job).openSessionId, 'active-target');
});
test('active session copy keeps waiting through a longer renderer flush', async () => {
let attempts = 0;
const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {},
buildAutoCopyPlan: async () => [{ id: 'active-source', lineageId: 'lineage-active' }],
copySessionRecord: async () => {
attempts++;
if (attempts <= 3) throw Error('会话文件正在变化,请稍后重试');
return { status: 'skipped', sourceId: 'active-source', targetId: 'active-target', sourceBytes: 1, copiedBytes: 0, totalBytes: 1 };
},
getAutoCopyMapping: () => null,
getAutoCopySession: () => ({ lineageId: 'lineage-active' }),
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('source', 'target', [], { openSessionId: 'active-source' });
await ctx.autoCopyQueue[0].run();
assert.equal(attempts, 4);
assert.equal(job.failed, 0);
assert.equal(job.skipped, 1);
assert.equal(ctx.publicAutoCopyJob(job).openSessionId, 'active-target');
});
test('unchanged requested session resolves its target without entering the copy worker', async () => {
let copies = 0;
const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {},
buildAutoCopyPlan: async () => [],
resolveAutoCopyTargetId: () => 'existing-target',
copySessionRecord: async () => { copies++; throw Error('must not copy'); },
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('source', 'target', [], { openSessionId: 'active-source' });
await ctx.autoCopyQueue[0].run();
assert.equal(copies, 0);
assert.equal(job.failed, 0);
assert.equal(ctx.publicAutoCopyJob(job).openSessionId, 'existing-target');
});
for (const error of ['会话消息文件没有消息,未同步', '会话消息文件为空,未同步']) test('empty message sessions are skipped instead of shown as sync failures: ' + error, async () => {
let cleared = 0;
const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {},
buildAutoCopyPlan: async () => [{ id: 'empty-session' }],
copySessionRecord: async () => { throw Error(error); },
getSessionDirtyIndex: () => ({ get: () => ({ at: 7 }) }),
clearSessionDirty: (_uid, _id, at) => { if (at === 7) cleared++; return true; },
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('source', 'target', []);
await ctx.autoCopyQueue[0].run();
assert.equal(job.failed, 0);
assert.equal(job.failedItems, 0);
assert.equal(job.skipped, 1);
assert.equal(cleared, 1);
assert.equal(ctx.publicAutoCopyJob(job).details[0].status, 'skipped');
});
test('an empty automatic copy plan does not wait for renderer injection', async () => {
const planningYields = [];
let rendererWaits = 0;
const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async options => {
planningYields.push(options);
if (!options || options.waitForInjection !== false) rendererWaits++;
},
buildAutoCopyPlan: async () => [], sessionSync: { readSessionSizes: async () => new Map() },
log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout: () => ({ unref() {} }),
};
const start = source.indexOf('function startAutoCopyJob(');
vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
const job = ctx.startAutoCopyJob('one', 'two', []);
await ctx.autoCopyQueue[0].run();
assert.equal(job.status, 'done');
assert.equal(planningYields.length, 1);
assert.equal(planningYields[0].waitForInjection, false);
assert.equal(rendererWaits, 0);
});
test('automatic session sync uses a bounded worker pool', async () => {
let running = 0;
let peak = 0;
const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => Array.from({ length: 8 }, (_, id) => ({ id: String(id) })),
copySessionRecord: async row => {
running++;
peak = Math.max(peak, running);
await new Promise(resolve => setTimeout(resolve, 5));
running--;
return { status: 'skipped', sourceBytes: 1, copiedBytes: 0, totalBytes: 1 };
},
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', []);
await ctx.autoCopyQueue[0].run();
assert.equal(peak, 4);
assert.equal(job.processed, 8);
assert.equal(job.skipped, 8);
assert.deepEqual(Array.from(job.details, item => item.id), Array.from({ length: 8 }, (_, id) => String(id)));
});
test('automatic session sync aggregates copied bytes independently across workers', async () => {
const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => Array.from({ length: 8 }, (_, id) => ({ id: String(id) })),
copySessionRecord: async () => {
await new Promise(resolve => setTimeout(resolve, 2));
return { status: 'copied', sourceBytes: 100, copiedBytes: 100, totalBytes: 100 };
},
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', []);
await ctx.autoCopyQueue[0].run();
assert.equal(job.copiedBytes, 800);
});
test('macOS packaging includes the required sync module', () => {
const script = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');
assert.match(script, /for f in [^\n]*session-sync\.js/);
});
test('account switching copies valid messages alongside non-JSON workspace files without changing their bytes', async t => {
const h = harness(t);
const file = path.join(h.root, 'workspace/sessions/a/editor-settings.json');
fs.mkdirSync(path.dirname(file), { recursive: true });
const bytes = Buffer.from('// JSONC workspace fixture\n{"editor":true,}\n');
fs.writeFileSync(file, bytes);
const result = await h.copy();
assert.equal(result.status, 'copied');
assert.deepEqual(fs.readFileSync(path.join(h.root, 'workspace/sessions/b/editor-settings.json')), bytes);
assert.deepEqual(fs.readFileSync(h.file('a')), fs.readFileSync(h.file('b')));
assert.equal((await h.copy()).status, 'skipped');
assert.equal(fs.existsSync(path.join(h.root, 'workspace/sessions/c/editor-settings.json')), false);
});
function addTarget(h, id, records = base) {
h.rows.set(id, { ...h.rows.get('b'), id });
lib.addAutoCopySessionMember(h.root, h.lineage, 'two', id);
h.write(id, records);
}
const nextMessage = text => ({ type: 'message', role: 'user', content: [{ text }] });
test('multiple identical target copies skip without creating or rewriting sessions', async t => {
const h = harness(t); addTarget(h, 'b2'); addTarget(h, 'b3');
lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b2' });
const before = [...h.rows.keys()].map(id => [id, fs.readFileSync(h.file(id))]);
for (let i = 0; i < 2; i++) {
const result = await h.copy();
assert.equal(result.status, 'skipped'); assert.equal(result.targetId, 'b2');
}
assert.equal(h.rows.size, before.length);
for (const [id, bytes] of before) assert.deepEqual(fs.readFileSync(h.file(id)), bytes);
assert.equal(fs.existsSync(path.join(h.root, 'session-sync-backups')), false);
});
test('an exact copy is found even when the preferred duplicate is divergent or unreadable', async t => {
const h = harness(t); addTarget(h, 'b2');
lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b' });
for (const content of ['{broken', JSON.stringify(nextMessage('other branch'))]) {
fs.writeFileSync(h.file('b'), content);
const result = await h.copy();
assert.equal(result.status, 'skipped'); assert.equal(result.targetId, 'b2');
assert.equal(fs.readFileSync(h.file('b'), 'utf8'), content);
}
});
test('source continuation updates the closest proven base while preserving other copies and third accounts', async t => {
const h = harness(t); const continued = [...base, nextMessage('next')];
addTarget(h, 'b2', continued); addTarget(h, 'branch', [...base, nextMessage('different')]);
h.write('a', [...continued, nextMessage('latest')]);
lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'branch' });
const untouched = ['b', 'branch', 'c'].map(id => [id, fs.readFileSync(h.file(id))]);
const result = await h.copy();
assert.equal(result.status, 'copied'); assert.equal(result.targetId, 'b2');
assert.deepEqual(fs.readFileSync(h.file('b2')), fs.readFileSync(h.file('a')));
for (const [id, bytes] of untouched) assert.deepEqual(fs.readFileSync(h.file(id)), bytes);
assert.equal((await h.copy()).status, 'skipped');
assert.equal(h.rows.size, 5);
});
test('multiple target continuations only update the source when they form one chain', async t => {
const h = harness(t); const continued = [...base, nextMessage('next')];
h.write('b', continued); addTarget(h, 'b2', [...continued, nextMessage('latest')]);
const oldTarget = fs.readFileSync(h.file('b')), third = fs.readFileSync(h.file('c'));
assert.equal((await h.copy()).status, 'copied');
assert.deepEqual(fs.readFileSync(h.file('a')), fs.readFileSync(h.file('b2')));
assert.deepEqual(fs.readFileSync(h.file('b')), oldTarget);
assert.deepEqual(fs.readFileSync(h.file('c')), third);
});
test('divergent target continuations are reported as branches and never arbitrarily replace the source', async t => {
const h = harness(t); h.write('b', [...base, nextMessage('branch one')]);
addTarget(h, 'b2', [...base, nextMessage('branch two')]);
lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b' });
const before = [...h.rows.keys()].map(id => [id, fs.readFileSync(h.file(id))]);
const result = await h.copy();
assert.equal(result.status, 'copied'); assert.equal(result.branched, true);
assert.deepEqual(fs.readFileSync(h.file(result.targetId)), fs.readFileSync(h.file('a')));
for (const [id, bytes] of before) assert.deepEqual(fs.readFileSync(h.file(id)), bytes);
});
test('duplicates with only unreadable messages remain real failures and preserve every file', async t => {
const h = harness(t); addTarget(h, 'b2');
fs.writeFileSync(h.file('b'), '{broken'); fs.writeFileSync(h.file('b2'), '{also broken');
await assert.rejects(h.copy(), /会话消息文件未写完或已损坏/);
assert.equal(fs.readFileSync(h.file('b'), 'utf8'), '{broken');
assert.equal(fs.readFileSync(h.file('b2'), 'utf8'), '{also broken');
});
test('a complete duplicate takes priority over repairing an incomplete copy', async t => {
const h = harness(t); addTarget(h, 'b2');
for (const id of ['a', 'b2']) {
const file = path.join(h.root, 'tasks', id, 'output.txt');
fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, 'fixture output');
}
lib.setAutoCopyMapping(h.root, h.lineage, 'two', { targetId: 'b' });
const result = await h.copy();
assert.equal(result.status, 'skipped'); assert.equal(result.targetId, 'b2');
assert.equal(fs.existsSync(path.join(h.root, 'tasks/b/output.txt')), false);
assert.equal(fs.existsSync(path.join(h.root, 'session-sync-backups')), false);
});
test('no matching branch among multiple target copies preserves all versions without a copy failure', async t => {
const h = harness(t);
h.write('a', [...base, nextMessage('source branch')]);
h.write('b', [...base, nextMessage('target branch one')]);
addTarget(h, 'b2', [...base, nextMessage('target branch two')]);
const before = [...h.rows.keys()].map(id => [id, fs.readFileSync(h.file(id))]);
const result = await h.copy();
assert.equal(result.status, 'copied'); assert.equal(result.branched, true); assert.equal(result.failedFiles, 0);
for (const [id, bytes] of before) assert.deepEqual(fs.readFileSync(h.file(id)), bytes);
assert.deepEqual(fs.readFileSync(h.file(result.targetId)), fs.readFileSync(h.file('a')));
assert.equal(h.rows.size, before.length + 1);
assert.equal((await h.copy()).status, 'skipped');
});
test('a copied branch remains visible beside the original and later updates only its own continuation', async t => {
const h = harness(t);
h.write('a', [...base, nextMessage('source branch')]); h.write('b', [...base, nextMessage('target branch')]);
const original = fs.readFileSync(h.file('b'));
const result = await h.copy(); assert.equal(result.branched, true);
const rules = lib.getAutoCopyRules(h.root, 'two');
const targetRows = [...h.rows.values()].filter(row => row.user_id === 'two');
const visible = lib.dedupeAutoCopySessionRows(targetRows, { two: rules.allLineages }, { two: new Set(rules.branchSessionIds) });
assert.equal(visible.length, 2);
h.write('a', [...base, nextMessage('source branch'), nextMessage('continued source branch')]);
h.rows.get('a').updated_at++;
const updated = await h.copy();
assert.equal(updated.status, 'copied'); assert.equal(updated.targetId, result.targetId);
assert.deepEqual(fs.readFileSync(h.file(updated.targetId)), fs.readFileSync(h.file('a')));
assert.deepEqual(fs.readFileSync(h.file('b')), original);
assert.equal([...h.rows.values()].filter(row => row.user_id === 'two').length, 2);
assert.equal((await h.copy()).status, 'skipped');
});
test('failed branch insertion leaves no visible row or copied files and a retry copies exactly once', async t => {
const h = harness(t);
h.write('a', [...base, nextMessage('source branch')]); h.write('b', [...base, nextMessage('target branch')]);
const original = fs.readFileSync(h.file('b')), insert = h.ctx.insertCopiedSession;
h.ctx.insertCopiedSession = async () => { throw Error('fixture insert failure'); };
await assert.rejects(h.copy(), /fixture insert failure/);
assert.equal(h.rows.size, 3);
assert.equal(fs.readdirSync(path.dirname(h.file('a'))).filter(name => name.endsWith('.jsonl')).length, 3);
assert.deepEqual(fs.readFileSync(h.file('b')), original);
h.ctx.insertCopiedSession = insert;
assert.equal((await h.copy()).status, 'copied');
assert.equal((await h.copy()).status, 'skipped');
assert.equal(h.rows.size, 4);
});
test('native automatic first copy registers destination ownership before selecting its snapshot', async t => {
const h=harness(t);
lib.removeAutoCopySessionMember(h.root,h.lineage,'two','b'); h.rows.delete('b');
const files=require('../scripts/codebuddy-files').createCodeBuddyFiles({root:path.join(h.root,'native'),sync:sessionSync});
const row=h.rows.get('a'); row.cwd='/fixture'; files.register(row);
const base=path.join(h.root,'native','one','CodeBuddyIDE','one','history',crypto.createHash('md5').update('/fixture').digest('hex'),'a');
fs.mkdirSync(path.join(base,'messages'),{recursive:true});
fs.writeFileSync(path.join(base,'index.json'),JSON.stringify({messages:[{id:'message'}]}));
fs.writeFileSync(path.join(base,'messages','message.json'),JSON.stringify({id:'message',conversationId:'a',role:'user',message:'fixture'}));
h.ctx.codeBuddyFiles=files;h.ctx.sessionSync=files.sync;
const result=await h.copy();
assert.equal(result.status,'copied');
assert.ok(files.collect(result.targetId).every(f=>f.source.includes(path.join('two','CodeBuddyIDE','two'))));
assert.equal((await h.copy()).status,'skipped');
});
async function multiAccountHarness(t) {
const h = harness(t, true);
lib.setAutoCopyAllSessions(h.root, true);
h.rows.set('d', { ...h.rows.get('a'), id: 'd', user_id: 'four' });
lib.addAutoCopySessionMember(h.root, h.lineage, 'four', 'd');
h.write('d', base);
for (const row of h.rows.values()) {
Object.assign(row, { status: 'completed', custom_title: '', last_activity_at: 1 });
h.ctx.markSessionDirtyBaseline(row.user_id);
}
for (const uid of ['two', 'three', 'four']) {
await h.ctx.copySessionRecord(h.rows.get('a'), uid, { auto: true, lineageId: h.lineage });
}
await h.ctx.copySessionRecord(h.rows.get('b'), 'one', { auto: true, lineageId: h.lineage });
// All four accounts already have stable mappings before the old session changes.
h.write('a', [...base, nextMessage('continued old session')]);
Object.assign(h.rows.get('a'), { updated_at: 2, last_activity_at: 2 });
h.ctx.markSessionDirty('one', 'a', 'sessionUpdated');
h.switchTo = async (from, to) => {
const plan = await h.ctx.buildAutoCopyPlan(from, to);
h.lastResults = [];
for (const row of plan) h.lastResults.push(await h.ctx.copySessionRecord(row, to, { auto: true, lineageId: row.lineageId }));
return plan;
};
return h;
}
test('one old-session edit reaches all four initialized accounts over successive switches', async t => {
const h = await multiAccountHarness(t);
for (const [from, to, id] of [['one', 'two', 'b'], ['two', 'three', 'c'], ['three', 'four', 'd']]) {
assert.equal((await h.switchTo(from, to)).length, 1, `${from} -> ${to} must retain the update signal`);
assert.deepEqual(fs.readFileSync(h.file(id)), fs.readFileSync(h.file('a')));
}
const circuit = [['four', 'one'], ['one', 'two'], ['two', 'three'], ['three', 'four']];
for (const [from, to] of circuit) {
await h.switchTo(from, to);
assert.ok(h.lastResults.every(result => result.status === 'skipped' && result.copiedBytes === 0),
'returning to the edited source may refresh its mapping but must not rewrite files');
}
for (const [from, to] of circuit) {
assert.equal((await h.switchTo(from, to)).length, 0, 'a completed circuit does not schedule duplicate copies');
}
});
test('returning through an already synchronized account does not lose remaining targets', async t => {
const h = await multiAccountHarness(t);
assert.equal((await h.switchTo('one', 'two')).length, 1);
await h.switchTo('two', 'one');
assert.ok(h.lastResults.every(result => result.status === 'skipped' && result.copiedBytes === 0));
assert.equal((await h.switchTo('one', 'three')).length, 1);
assert.deepEqual(fs.readFileSync(h.file('c')), fs.readFileSync(h.file('a')));
});
test('existing and later lifecycle markers cannot consume an updated member before fanout', async t => {
const h = await multiAccountHarness(t);
h.ctx.markSessionDirty('two', 'b', 'sessionUpdated');
await h.switchTo('one', 'two');
await h.switchTo('two', 'one');
h.ctx.markSessionDirty('two', 'b', 'sessionUpdated');
assert.equal((await h.switchTo('two', 'one')).length, 0);
assert.equal((await h.switchTo('two', 'three')).length, 1);
assert.deepEqual(fs.readFileSync(h.file('c')), fs.readFileSync(h.file('a')));
});
test('copy completion preserves timestamps of concurrent source and target dirty events', async t => {
const h = await multiAccountHarness(t);
const at = h.ctx.getSessionDirtyIndex().get('one', 'a').at + 100;
let yields = 0;
h.ctx.yieldAutoCopyToRenderer = async () => {
if (++yields === 2) {
h.ctx.markSessionDirty('one', 'a', 'sessionUpdated', at);
h.ctx.markSessionDirty('two', 'b', 'sessionUpdated', at + 1);
}
};
await h.switchTo('one', 'two');
assert.ok(yields >= 2);
assert.equal(h.ctx.getSessionDirtyIndex().get('one', 'a').at, at);
assert.equal(h.ctx.getSessionDirtyIndex().get('two', 'b').at, at + 1);
assert.equal((await h.switchTo('two', 'three')).length, 1);
});
for (const field of ['title', 'custom_title']) test('#511 title-only edit syncs without rewriting messages: ' + field, async t => {
const h = harness(t, true);
await h.copy();
const before = fs.readFileSync(h.file('b'));
h.rows.get('a')[field] = 'renamed';
h.rows.get('a').updated_at = 200;
assert.equal((await h.ctx.buildAutoCopyPlan('one', 'two')).length, 1, 'a clean renderer baseline must not hide renames');
const result = await h.copy();
assert.equal(result.status, 'copied');
assert.equal(h.rows.get('b')[field], 'renamed');
assert.deepEqual(fs.readFileSync(h.file('b')), before);
assert.equal(h.rows.get('c')[field] || '', field === 'title' ? 'fixture' : '');
assert.equal((await h.copy()).status, 'skipped');
});
test('#511 independent title edits are preserved as a conflict', async t => {
const h = harness(t);
await h.copy();
h.rows.get('a').custom_title = 'source edit';
h.rows.get('b').custom_title = 'target edit';
const result = await h.copy();
assert.equal(result.status, 'conflict');
assert.equal(h.rows.get('a').custom_title, 'source edit');
assert.equal(h.rows.get('b').custom_title, 'target edit');
});
test('#511 deleting a local copy preserves siblings and stops automatic recreation across restart', async t => {
const h = harness(t);
await h.copy();
lib.recordSessionDeletion(h.root, [{ id: 'b', user_id: 'two' }]);
h.rows.delete('b'); fs.unlinkSync(h.file('b'));
for (let i = 0; i < 2; i++) assert.equal((await h.copy()).status, 'skipped');
assert.deepEqual([...h.rows.keys()], ['a', 'c']);
assert.equal(lib.isAutoCopyTargetExcluded(h.root, h.lineage, 'two'), true);
const manual = await h.ctx.copySessionRecord(h.rows.get('a'), 'two');
assert.equal(manual.status, 'copied', 'explicit manual sync can restore a copy');
});
for (const direction of ['target', 'reverse']) test('#511 rename sync resolves direction: ' + direction, async t => {
const h = harness(t, true);
await h.copy();
h.rows.get('b').custom_title = 'renamed on account two';
const from = direction === 'reverse' ? 'b' : 'a';
const to = direction === 'reverse' ? 'one' : 'two';
const result = await h.ctx.copySessionRecord(h.rows.get(from), to, { auto: true, lineageId: h.lineage });
assert.equal(result.status, 'copied');
assert.equal(h.rows.get('a').custom_title, 'renamed on account two');
});
test('#511 clearing a custom title propagates even with a clean lifecycle baseline', async t => {
const h = harness(t, true);
h.rows.get('a').custom_title = h.rows.get('b').custom_title = 'previous name';
await h.copy();
const dirty = h.ctx.getSessionDirtyIndex();
dirty.markBaseline('one'); dirty.clear('one', 'a');
h.rows.get('a').custom_title = '';
assert.equal((await h.ctx.buildAutoCopyPlan('one', 'two')).length, 1);
assert.equal((await h.copy()).status, 'copied');
assert.equal(h.rows.get('b').custom_title, '');
});
test('#511 successive renames propagate through account switches and back', async t => {
const h = harness(t, true);
const copy = (id, uid) => h.ctx.copySessionRecord(h.rows.get(id), uid, { auto: true, lineageId: h.lineage });
await copy('a', 'two'); await copy('b', 'one');
await copy('c', 'two'); await copy('a', 'three');
h.rows.get('a').custom_title = 'first name';
await copy('a', 'two');
assert.equal((await copy('c', 'two')).status, 'copied');
assert.equal(h.rows.get('c').custom_title, 'first name');
h.rows.get('b').custom_title = 'second name';
assert.equal((await copy('b', 'one')).status, 'copied');
assert.equal(h.rows.get('a').custom_title, 'second name');
});
test('#511 historical unequal titles surface a conflict instead of a permanent fast-path skip', async t => {
const h = harness(t, true);
h.rows.get('b').custom_title = 'old local name';
const sourceRow = h.rows.get('a'), target = h.rows.get('b');
lib.setAutoCopyMapping(h.root, h.lineage, 'two', {
targetId: 'b', fingerprintVersion: 3,
...h.ctx.mappingWithSourceRevision(null, 'one', sourceRow),
targetRevision: h.ctx.sessionCopyRowRevision(target),
});
h.ctx.getSessionDirtyIndex().markBaseline('one');
assert.equal((await h.ctx.buildAutoCopyPlan('one', 'two')).length, 1);
assert.equal((await h.copy()).status, 'conflict');
assert.equal(h.rows.get('b').custom_title, 'old local name');
});
for (const changed of ['a', 'b']) test('#511 atomic title update preserves a concurrent edit on ' + changed, async t => {
const h = harness(t);
await h.copy();
h.rows.get('a').custom_title = 'rename';
const before = fs.readFileSync(h.file('b'));
const { createSessionDb } = require('../scripts/session-db');
const db = createSessionDb({ dbPath: path.join(h.root, 'cas.db') });
await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT, title TEXT, custom_title TEXT, updated_at INTEGER, deleted_at INTEGER)');
for (const row of h.rows.values()) await db.run('INSERT INTO sessions VALUES (?, ?, ?, ?, ?, NULL)', [row.id, row.user_id, row.title, row.custom_title || '', row.updated_at]);
h.ctx.sqliteRun = async (sql, params) => {
await db.run('UPDATE sessions SET custom_title = ? WHERE id = ?', ['concurrent rename', changed]);
return db.run(sql, Array.from(params));
};
await assert.rejects(h.copy(), /会话记录正在变化/);
const row = (await db.all('SELECT custom_title FROM sessions WHERE id = ?', [changed]))[0];
assert.equal(row.custom_title, 'concurrent rename');
assert.deepEqual(fs.readFileSync(h.file('b')), before);
});
test('#511 deleting an extra same-account copy preserves the original and suppresses branch recreation', async t => {
const h = harness(t, true);
const extra = { ...h.rows.get('b'), id: 'extra' };
h.rows.set(extra.id, extra); h.write(extra.id, base);
lib.addAutoCopySessionMember(h.root, h.lineage, 'two', extra.id);
lib.recordSessionDeletion(h.root, [{ id: extra.id, user_id: 'two' }]);
h.rows.delete(extra.id); fs.unlinkSync(h.file(extra.id));
assert.equal((await h.copy()).status, 'skipped');
h.write('a', [...base, { type: 'message', role: 'user', content: [{ text: 'source branch' }] }]);
h.write('b', [...base, { type: 'message', role: 'user', content: [{ text: 'target branch' }] }]);
h.rows.get('a').updated_at++; h.rows.get('b').updated_at++;
const original = fs.readFileSync(h.file('b'));
for (let i = 0; i < 2; i++) assert.equal((await h.copy()).status, 'skipped');
assert.deepEqual([...h.rows.keys()], ['a', 'b', 'c']);
assert.deepEqual(fs.readFileSync(h.file('b')), original);
});
test('#511 a title update reaches a clean third account through the planner', async t => {
const h = harness(t, true);
await h.copy();
await h.ctx.copySessionRecord(h.rows.get('c'), 'two', { auto: true, lineageId: h.lineage });
h.rows.get('a').custom_title = 'new name';
await h.copy();
const dirty = h.ctx.getSessionDirtyIndex();
dirty.markBaseline('three'); dirty.clear('three', 'c');
const plan = await h.ctx.buildAutoCopyPlan('three', 'two');
assert.equal(plan.length, 1);
await h.ctx.copySessionRecord(plan[0], 'two', { auto: true, lineageId: h.lineage });
assert.equal(h.rows.get('c').custom_title, 'new name');
});