WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
const section = (start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start)));
const tick = () => new Promise(resolve => setImmediate(resolve));
const account = (uid, expiry) => ({ uid, nickname: uid, credits: 10, creditSegments: [{ remaining: 10, expiresAt: expiry }] });
function harness() {
const requests = [];
function el(tag, className) {
return {
className, children: [], attrs: {}, dataset: {}, classList: { toggle() {}, add() {}, remove() {} },
setAttribute(k, v) { this.attrs[k] = v; }, getAttribute(k) { return this.attrs[k]; },
appendChild(child) { this.children = this.children.filter(value => value !== child); this.children.push(child); },
insertBefore(child) { this.appendChild(child); },
querySelector(selector) { return selector === '.wbs-acct-list' ? this.children.find(c => c.className === 'wbs-acct-list') : null; },
querySelectorAll(selector) { return selector === '.wbs-card' ? this.children.filter(c => c.className.startsWith('wbs-card')) : []; },
set innerHTML(value) { this.children = []; this.html = value; }, get innerHTML() { return this.html || ''; },
};
}
const pane = el('div', 'pane');
const ctx = vm.createContext({
window: {},
state: { accounts: [], current: null, open: true, creditRunId: 0, creditRefreshGeneration: {}, activityRunId: 0, creditRemaining: 0 },
alive: true, CAPS: { accounts: true }, WBS_PROFILE_IS_AI: false, accountsPane: pane, panel: el(), fab: el(), fabQuietMode: { wake() {} },
api(route, options) { return new Promise((resolve, reject) => requests.push({ route, options, resolve, reject })); },
el, esc: String, escAttr: String, tokenState: () => ({ label: '-' }), isIdentityExpired: a => !!a.identityExpired,
checkinBadgeHtml: () => '', creditBlockHtml: () => '', applyAccountMask() {}, updateAccountSummary() {},
updateCheckinCells() {}, updateCreditCell() {}, fetchActivityForAccounts() {}, toast() {}, root: {},
MODEL_EDIT_SVG: '', PRIMARY_ACCOUNT_SVG: '', SWITCH_SVG: '', TRASH_SVG: '',
setBuildTimeout: fn => fn(), setTimeout: () => 1, clearTimeout() {},
checkForUpdate() {}, acCheckPromptOnOpen() {}, syncSessionModule() {}, refreshSessionsSilently() {}, fetchDailyProgressForAccounts() {}, pollActiveSessionCopyNotice() {},
});
vm.runInContext([
section(' function isKnownActivityStreak(', ' function el(tag'),
section(' function nearestCreditExpiry(', ' function pollAutoCopyJob('),
section(' function render(data)', ' function maskAccountName('),
section(' function refresh()', ' function updateAccountSummary('),
section(' function requestCredit(uid)', ' function updateCreditCell('),
section(' function setOpen(', ' function setupFabDrag('),
].join('\n'), ctx);
return { ctx, requests, pane, order: () => Array.from(ctx.state.accounts, a => a.uid), cards: () => pane.querySelector('.wbs-acct-list').children.slice() };
}
test('metadata refresh retains cached credits, sorted order and the actual buttons/cards', () => {
const h = harness();
h.ctx.render({ accounts: [account('later', 200), account('soon', 100)] });
const before = h.cards();
h.ctx.render({ accounts: [{ uid: 'later', nickname: 'later' }, { uid: 'soon', nickname: 'soon' }] });
assert.deepEqual(h.order(), ['soon', 'later']);
assert.equal(h.ctx.state.accounts[0].credits, 10);
assert.equal(h.cards()[0], before[0]);
});
test('cached first render fixes the visible order and delegates current-account check-in to the ordered automation', async () => {
const h = harness();
h.ctx.refresh();
h.requests[0].resolve({ checkinAutomationEnabled: true, current: { uid: 'later' }, accounts: [account('later', 200), account('soon', 100), { uid: 'unknown', creditSegments: [] }] });
await tick();
const before = h.cards();
assert.deepEqual(h.order(), ['soon', 'later', 'unknown']);
assert.ok(h.requests.every(request => request.route !== '/api/accounts/checkin-sync'));
for (const request of h.requests.filter(request => request.route === '/api/credits')) {
const uid = JSON.parse(request.options.body).uid;
request.resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: uid === 'unknown' ? 1 : 300 }] });
}
await tick();
assert.deepEqual(h.order(), ['soon', 'later', 'unknown']);
assert.deepEqual(h.cards(), before);
});
test('first credit batch after renderer reload sorts cards without reopening the panel', async () => {
const h = harness();
h.ctx.render({ current: { uid: 'later' }, accounts: [{ uid: 'later' }, { uid: 'soon' }] });
const before = h.cards();
h.ctx.fetchCreditsForAccounts(); await tick();
h.requests[1].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 100 }] }); await tick();
assert.deepEqual(h.order(), ['later', 'soon'], 'wait for the complete batch before moving rows');
h.requests[0].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 200 }] }); await tick();
assert.deepEqual(h.order(), ['soon', 'later']);
assert.equal(h.cards()[0], before[1], 'move existing cards instead of rebuilding controls');
assert.equal(h.ctx.state.open, true);
h.ctx.fetchCreditsForAccounts(); await tick();
h.requests[2].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 300 }] });
h.requests[3].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 50 }] }); await tick();
assert.deepEqual(h.order(), ['soon', 'later'], 'later background batches preserve the visible order');
});
test('switching the current account reapplies expiry order after its credit batch', async () => {
const h = harness();
h.ctx.render({ current: { uid: 'a' }, accounts: [account('a', 100), account('b', 200)] });
h.ctx.render({ current: { uid: 'b' }, accounts: [account('a', 300), account('b', 200)] });
assert.deepEqual(h.order(), ['b', 'a']);
h.ctx.fetchCreditsForAccounts(); await tick();
h.requests.find(r => JSON.parse(r.options.body).uid === 'a').resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 50 }] });
h.requests.find(r => JSON.parse(r.options.body).uid === 'b').resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 200 }] }); await tick();
assert.deepEqual(h.order(), ['a', 'b'], 'current account must not be pinned');
assert.deepEqual(h.cards().map(c => c.getAttribute('data-uid')), ['a', 'b']);
});
test('credit responses never move a visible account; next opening applies expiry order', async () => {
const h = harness();
h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
const before = h.cards();
h.ctx.fetchCreditsForAccounts();
await tick();
h.requests.find(r => JSON.parse(r.options.body).uid === 'b').resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 50 }] });
h.requests.find(r => JSON.parse(r.options.body).uid === 'a').resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 300 }] });
await tick();
assert.deepEqual(h.order(), ['a', 'b']);
assert.deepEqual(h.cards(), before);
h.ctx.setOpen(false);
h.ctx.setOpen(true, { automation: true });
assert.deepEqual(h.order(), ['b', 'a']);
assert.equal(h.cards()[0], before[1]);
});
test('older overlapping account responses cannot restore stale accounts', async () => {
const h = harness();
h.ctx.refresh(); h.ctx.refresh();
h.requests[1].resolve({ accounts: [account('new', 100)] }); await tick();
h.requests[0].resolve({ accounts: [account('old', 100)] }); await tick();
assert.deepEqual(h.order(), ['new']);
});
test('temporary credit failures retain the cached value but expired identity clears it', async () => {
const h = harness();
h.ctx.render({ accounts: [account('network', 100), account('expired', 200)] });
h.ctx.fetchCreditsForAccounts(); await tick();
h.requests[0].reject(new Error('temporary network failure'));
h.requests[1].reject({ payload: { expired: true } }); await tick();
assert.equal(h.ctx.state.accounts.find(a => a.uid === 'network').credits, 10);
assert.equal(h.ctx.state.accounts.find(a => a.uid === 'expired').credits, null);
assert.equal(h.ctx.state.accounts.find(a => a.uid === 'expired').creditExpired, true);
});
test('expired identities are cleared from cached totals and skipped by credit refresh', async () => {
const h = harness();
h.ctx.render({ accounts: [
{ ...account('expired', 100), identityExpired: true },
account('live', 200),
] });
assert.equal(h.ctx.state.accounts.find(a => a.uid === 'expired').credits, null);
h.ctx.fetchCreditsForAccounts(); await tick();
assert.deepEqual(h.requests.map(request => JSON.parse(request.options.body).uid), ['live']);
h.requests[0].resolve({ credits: 7, segments: [{ remaining: 7, expiresAt: 200 }] }); await tick();
assert.equal(h.ctx.state.creditSummaryValue, 7);
assert.equal(h.ctx.state.accounts.find(a => a.uid === 'expired').credits, null);
await h.ctx.refreshCreditForAccount('expired');
assert.deepEqual(h.requests.map(request => JSON.parse(request.options.body).uid), ['live']);
});
test('account refresh errors retain the cached list', async () => {
const h = harness(); h.ctx.render({ accounts: [account('a', 100)] });
const before = h.cards()[0];
h.ctx.refresh(); h.requests[0].reject(new Error('offline')); await tick();
assert.ok(h.pane.querySelector('.wbs-acct-list'));
assert.equal(h.cards()[0], before);
});
test('deleted accounts stay removed and new accounts append without moving survivors', () => {
const h = harness(); h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
h.ctx.render({ accounts: [account('new', 1), { uid: 'b', nickname: 'b' }] });
assert.deepEqual(h.order(), ['b', 'new']);
});
test('closing the panel invalidates pending account responses', async () => {
const h = harness(); h.ctx.render({ accounts: [account('cached', 100)] });
const before = h.cards()[0];
h.ctx.refresh(); h.ctx.setOpen(false);
h.requests[0].resolve({ accounts: [account('stale', 10)] }); await tick();
assert.deepEqual(h.order(), ['cached']);
assert.equal(h.cards()[0], before);
});
test('account refresh after re-opening keeps the newly sorted card nodes', async () => {
const h = harness(); h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
h.ctx.state.accounts[1].creditSegments = [{ remaining: 10, expiresAt: 50 }];
h.ctx.setOpen(false); h.ctx.setOpen(true, { automation: true });
const before = h.cards();
h.requests[0].resolve({ accounts: [{ uid: 'a', nickname: 'a' }, { uid: 'b', nickname: 'b' }] }); await tick();
assert.deepEqual(h.order(), ['b', 'a']);
assert.equal(h.cards()[0], before[0]);
assert.equal(h.cards()[1], before[1]);
});
test('fresh current-account and identity changes update card controls', () => {
const h = harness(); h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
const before = h.cards();
h.ctx.render({ current: { uid: 'b' }, accounts: [{ ...account('a', 100), identityExpired: true }, account('b', 200)] });
assert.deepEqual(h.order(), ['b', 'a']);
assert.notEqual(h.cards()[0], before[0]);
assert.equal(h.cards().find(card => card.getAttribute('data-uid') === 'b').className, 'wbs-card cur');
});
test('expired identities retain a manual switch while malformed backups remain blocked', () => {
const h = harness();
h.ctx.render({ accounts: [
{ ...account('expired', 100), identityExpired: true },
{ ...account('invalid', 200), authValid: false },
] });
const expiredCard = h.cards().find(card => card.getAttribute('data-uid') === 'expired');
const invalidCard = h.cards().find(card => card.getAttribute('data-uid') === 'invalid');
assert.match(expiredCard.innerHTML, /wbs-acc-switch/);
assert.match(expiredCard.innerHTML, /可能需要重新登录/);
assert.doesNotMatch(invalidCard.innerHTML, /wbs-acc-switch/);
});
test('a background credit expiry response does not hide the manual switch', () => {
const button = { style: {} };
const credit = { classList: { remove() {} } };
const card = {
getAttribute: () => 'expired',
querySelector: selector => selector === '.wbs-credit-cell' ? credit : button,
};
const ctx = {
state: { accounts: [{ uid: 'expired', creditExpired: true }] },
accountsPane: { querySelectorAll: () => [card] },
isIdentityExpired: () => true, creditBlockHtml: () => '登录身份过期',
};
vm.runInNewContext(section(' function updateCreditCell(', ' // ===== 调试'), ctx);
ctx.updateCreditCell('expired', null, []);
assert.equal(button.style.display, '');
ctx.state.accounts[0].authValid = false;
ctx.updateCreditCell('expired', null, []);
assert.equal(button.style.display, 'none');
});
test('account metadata refresh retains valid activity days while the server cache is missing or failed', () => {
const h = harness();
h.ctx.render({ accounts: [{ ...account('a', 100), activityStreak: { days: 5, status: 'ready' } }] });
for (const activityStreak of [null, { days: null, status: 'unavailable' }]) {
h.ctx.render({ accounts: [{ uid: 'a', nickname: 'a', activityStreak }] });
assert.equal(h.ctx.state.accounts[0].activityStreak.days, 5);
}
h.ctx.render({ accounts: [{ uid: 'a', nickname: 'a', activityStreak: { days: 0, status: 'ready' } }] });
assert.equal(h.ctx.state.accounts[0].activityStreak.days, 0);
});
test('fixed sort remains stable through credit refresh and appends new accounts without a sort', () => {
const h = harness();
const a = { ...account('a', 10), sort: 2 }, b = { ...account('b', 20), sort: 1 };
h.ctx.render({ accountOrder: { mode: 'fixed' }, accounts: [a,b,account('c', 1)] });
assert.deepEqual(h.order(), ['b','a','c']);
h.ctx.render({ accountOrder: { mode: 'fixed' }, accounts: [a,b,account('c', 1),account('d', 0)] });
h.ctx.sortAccountsByCreditExpiry();
assert.deepEqual(h.order(), ['b','a','c','d']);
});
for (const mode of ['expiry', 'fixed']) {
test(mode + ' order puts all expired identities last, including the current account', () => {
const h = harness();
h.ctx.render({ accountOrder: { mode }, current: { uid: 'expired' }, accounts: [
{ ...account('expired', 1), identityExpired: true, sort: 1 },
{ ...account('credit-expired', 2), creditExpired: true, sort: 2 },
{ ...account('valid-later', 20), sort: 4 },
{ ...account('valid-soon', 10), sort: 3 },
] });
assert.deepEqual(h.order(), ['valid-soon', 'valid-later', 'expired', 'credit-expired']);
});
}
test('visible metadata refresh moves expired accounts behind new valid accounts', () => {
const h = harness();
h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
h.ctx.render({ accounts: [{ ...account('a', 100), identityExpired: true }, account('b', 200), account('new', 1)] });
assert.deepEqual(h.order(), ['b', 'new', 'a']);
});
test('background expiry detection moves the existing card once the batch settles', async () => {
const h = harness();
h.ctx.render({ accounts: [account('a', 100), account('b', 200), account('c', 300)] });
const before = h.cards();
h.ctx.fetchCreditsForAccounts(); await tick();
h.requests[0].reject({ payload: { expired: true } }); await tick();
assert.deepEqual(h.order(), ['a', 'b', 'c']);
h.requests[1].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 500 }] });
h.requests[2].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 1 }] }); await tick();
assert.deepEqual(h.order(), ['b', 'c', 'a']);
assert.equal(h.cards()[2], before[0]);
});