Skip to content

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

10.4 KB
Raw Blame
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const vm = require('node:vm');
const persona = require('../scripts/persona');
const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
const routes = daemon.slice(daemon.indexOf("  if (req.method === 'GET' && p === '/api/persona')"), daemon.indexOf("  if (req.method === 'GET' && p === '/api/accounts')"));
function harness(t, profile = 'workbuddy-cn') {
  const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-persona-api-')));
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));
  const dataRoot = path.join(root, profile);
  fs.mkdirSync(path.join(dataRoot, 'user-b-personal'), { recursive: true });
  for (const file of ['IDENTITY.md', 'USER.md', 'SOUL.md', 'MEMORY.md']) fs.writeFileSync(path.join(dataRoot, file), 'fixture ' + file);
  fs.writeFileSync(path.join(dataRoot, 'user-b-personal/BOOTSTRAP.md'), 'fixture onboarding');
  let reloads = 0, locked = false;
  const context = vm.createContext({
    captureSessionPins: async () => {},
    PROFILE: { kind: profile.startsWith('workbuddy') ? 'workbuddy' : 'codebuddy', dataRoot, capabilities: { accounts: true } },
    DATA_DIR: path.join(root, 'WorkDaddy'), URL, ...persona,
    currentAccount: () => ({ uid: 'b' }), listAccounts: () => [{ uid: 'a' }],
    assertAccountSwitchIdle: async () => { if (locked) throw new Error('busy'); locked = true; return () => { locked = false; }; },
    reloadWorkBuddyPage: async () => { reloads++; }, log: () => {}, readBody: req => Promise.resolve(req.body),
    json: (res, status, body) => ({ status, body }),
  });
  const run = vm.runInContext('(async function(req) { const res = {}; const url = new URL(req.url, "http://127.0.0.1"); const p = url.pathname; ' + routes + '})', context);
  return { dataRoot, context, run, reloads: () => reloads, locked: () => locked };
}
for (const profile of ['workbuddy-cn', 'workbuddy-ai']) test('persona API uses ' + profile + ' root, consent, backup and current-account CDP reload', async t => {
  const h = harness(t, profile);
  const get = await h.run({ method: 'GET', url: '/api/persona' });
  assert.equal(get.body.eligible, true);
  assert.equal(JSON.stringify(get).includes('fixture MEMORY'), false, 'private contents never leave the API');
  const body = { uid: 'b', sourceUid: 'legacy', revision: get.body.revision };
  assert.equal((await h.run({ method: 'POST', url: '/api/persona-copy', body })).status, 400);
  assert.equal(fs.existsSync(path.join(h.dataRoot, 'user-b-personal/MEMORY.md')), false);
  assert.equal(h.locked(), false);
  const copy = await h.run({ method: 'POST', url: '/api/persona-copy', body: { ...body, confirmed: true } });
  assert.equal(copy.status, 200);
  assert.equal(copy.body.reloaded, true);
  assert.equal(copy.body.backedUp, true);
  assert.equal(h.reloads(), 1);
  assert.equal(h.locked(), false);
  assert.equal((await h.run({ method: 'GET', url: '/api/persona' })).body.eligible, false);
});
test('repairing destination leaves current renderer alone until normal switch', async t => {
  const h = harness(t);
  h.context.currentAccount = () => ({ uid: 'a' });
  h.context.listAccounts = () => [{ uid: 'a' }, { uid: 'b' }];
  const preview = await h.run({ method: 'GET', url: '/api/persona?uid=b' });
  const result = await h.run({ method: 'POST', url: '/api/persona-copy', body: { uid: 'b', sourceUid: 'legacy', confirmed: true, revision: preview.body.revision } });
  assert.equal(result.body.reloaded, false);
  assert.equal(h.reloads(), 0);
});
test('reload failure reports saved repair without claiming successful refresh', async t => {
  const h = harness(t);
  h.context.reloadWorkBuddyPage = async () => { throw new Error('disconnected'); };
  const preview = await h.run({ method: 'GET', url: '/api/persona' });
  const result = await h.run({ method: 'POST', url: '/api/persona-copy', body: { uid: 'b', sourceUid: 'legacy', confirmed: true, revision: preview.body.revision } });
  assert.equal(result.status, 200);
  assert.equal(result.body.reloaded, false);
  assert.ok(result.body.hint.includes('下次刷新'));
});
test('unknown accounts and non-WorkBuddy profiles cannot copy', async t => {
  const h = harness(t);
  assert.equal((await h.run({ method: 'GET', url: '/api/persona?uid=unknown' })).status, 400);
  h.context.PROFILE.kind = 'codebuddy';
  assert.equal((await h.run({ method: 'GET', url: '/api/persona' })).body.status, 'unsupported');
  assert.equal((await h.run({ method: 'POST', url: '/api/persona-copy', body: { uid: 'b', confirmed: true } })).status, 400);
});
for (const profile of ['workbuddy-cn','workbuddy-ai']) test('shared settings persist dismissal, validate consent source and lock, and remain profile scoped: '+profile, async t => {
  const h=harness(t,profile);
  const before=await h.run({method:'GET',url:'/api/persona/settings'});
  assert.equal(before.body.mode,'unset');
  assert.deepEqual(Array.from(before.body.sources,s=>s.uid),['a','b','legacy']);
  assert.equal(before.body.sources.find(s=>s.uid==='a').available,false);
  assert.equal(JSON.stringify(before).includes('fixture MEMORY'),false);
  assert.equal((await h.run({method:'POST',url:'/api/persona/settings',body:{dismissNotice:true}})).body.noticeDismissed,true);
  assert.equal((await h.run({method:'GET',url:'/api/persona/settings'})).body.mode,'unset');
  assert.equal((await h.run({method:'POST',url:'/api/persona/settings',body:{mode:'shared',currentUid:'a'}})).status,400);
  const source=before.body.sources.find(s=>s.available);
  const saved=await h.run({method:'POST',url:'/api/persona/settings',body:{mode:'shared',currentUid:'b',sourceUid:source.uid,revision:source.revision}});
  assert.equal(saved.status,200); assert.equal(saved.body.mode,'shared'); assert.equal(saved.body.reloaded,true);
  assert.equal(h.locked(),false);
  assert.equal((await h.run({method:'POST',url:'/api/persona-copy',body:{uid:'a',confirmed:true}})).status,400);
  assert.equal((await h.run({method:'POST',url:'/api/persona/settings',body:{mode:'independent',currentUid:'b'}})).body.mode,'independent');
  h.context.PROFILE.kind='codebuddy';
  assert.equal((await h.run({method:'GET',url:'/api/persona/settings'})).body.supported,false);
  assert.equal((await h.run({method:'POST',url:'/api/persona/settings',body:{dismissNotice:true}})).status,400);
});
test('shared switching protects authentication until projection succeeds and undoes projection if authentication fails',async t=>{
  const h=harness(t);
  const options={dataRoot:h.dataRoot,backupRoot:h.context.DATA_DIR,accounts:[{uid:'a'},{uid:'b'}],currentUid:'b'};
  persona.configurePersona({...options,mode:'shared',sourceUid:'legacy',revision:persona.listPersonaSources(options).find(s=>s.uid==='legacy').revision});
  const context=vm.createContext({...h.context,codeBuddyNative:null,switchTo:async()=>{throw new Error('auth failed');}});
  const seam=daemon.slice(daemon.indexOf('async function switchAccountForProfile(uid)'),daemon.indexOf('\nfunction scheduleBackup('));
  vm.runInContext(seam,context);
  await assert.rejects(context.switchAccountForProfile('a'),/auth failed/);
  assert.equal(fs.existsSync(path.join(h.dataRoot,'user-a-personal')),false);
  assert.equal(persona.readPersonaSettings(options.backupRoot).activeUid,'b');
  let switched=false; context.switchTo=()=>{switched=true;};
  fs.unlinkSync(path.join(h.dataRoot,'user-b-personal/USER.md'));
  await assert.rejects(context.switchAccountForProfile('a'),/尚未完成/);
  assert.equal(switched,false);
});

for (const profile of ['workbuddy-cn', 'workbuddy-ai']) {
  for (const targetUid of ['a', 'b']) test(profile + ': login-page switching resumes shared persona for ' + targetUid, async t => {
    const h = harness(t, profile);
    const options = { dataRoot: h.dataRoot, backupRoot: h.context.DATA_DIR, accounts: [{ uid: 'a' }, { uid: 'b' }], currentUid: 'b' };
    persona.configurePersona({ ...options, mode: 'shared', sourceUid: 'legacy', revision: persona.listPersonaSources(options).find(s => s.uid === 'legacy').revision });
    fs.writeFileSync(path.join(h.dataRoot, 'user-b-personal/USER.md'), 'latest shared edit');
    let current = null;
    const switches = [];
    const context = vm.createContext({ ...h.context, codeBuddyNative: null, currentAccount: () => current,
      listAccounts: () => options.accounts,
      switchTo: async (_, uid) => { switches.push(uid); current = { uid }; return current; },
    });
    const seam = daemon.slice(daemon.indexOf('async function switchAccountForProfile(uid)'), daemon.indexOf('\nfunction scheduleBackup('));
    vm.runInContext(seam, context);
    assert.equal((await context.switchAccountForProfile(targetUid)).uid, targetUid);
    assert.deepEqual(switches, [targetUid]);
    assert.equal(persona.readPersonaSettings(options.backupRoot).activeUid, targetUid);
    assert.equal(fs.readFileSync(path.join(h.dataRoot, `user-${targetUid}-personal/USER.md`), 'utf8'), 'latest shared edit');
    const nextUid = targetUid === 'a' ? 'b' : 'a';
    await context.switchAccountForProfile(nextUid);
    assert.equal(persona.readPersonaSettings(options.backupRoot).activeUid, nextUid);
    assert.equal(fs.readFileSync(path.join(h.dataRoot, `user-${nextUid}-personal/USER.md`), 'utf8'), 'latest shared edit');
  });
}

test('login-page auth failure rolls shared persona back; a different logged-in account remains guarded', async t => {
  const h = harness(t);
  const options = { dataRoot: h.dataRoot, backupRoot: h.context.DATA_DIR, accounts: [{ uid: 'a' }, { uid: 'b' }], currentUid: 'b' };
  persona.configurePersona({ ...options, mode: 'shared', sourceUid: 'legacy', revision: persona.listPersonaSources(options).find(s => s.uid === 'legacy').revision });
  const context = vm.createContext({ ...h.context, codeBuddyNative: null, currentAccount: () => null,
    listAccounts: () => options.accounts, switchTo: async () => { throw new Error('auth failed'); },
  });
  const seam = daemon.slice(daemon.indexOf('async function switchAccountForProfile(uid)'), daemon.indexOf('\nfunction scheduleBackup('));
  vm.runInContext(seam, context);
  await assert.rejects(context.switchAccountForProfile('a'), /auth failed/);
  assert.equal(fs.existsSync(path.join(h.dataRoot, 'user-a-personal')), false);
  assert.equal(persona.readPersonaSettings(options.backupRoot).activeUid, 'b');
  context.currentAccount = () => ({ uid: 'a' });
  await assert.rejects(context.switchAccountForProfile('b'), /当前账号已变化/);
});