WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const test = require('node:test');
const compat = require('../scripts/workbuddy-compat.js');
const lib = require('../scripts/lib.js');
function visibleElement(className) {
return {
className: className || '',
children: [],
getBoundingClientRect() { return { width: 120, height: 32, left: 20 }; },
};
}
test('composer toolbar selection prefers the modern DOM and falls back to legacy DOM', () => {
const modern = visibleElement('cr-input-toolbar__right');
const legacy = visibleElement('_item_hash _gapLarge_hash');
const modernDocument = {
querySelector(selector) { return selector === 'div.cr-input-toolbar__right' ? modern : null; },
querySelectorAll() { return [legacy]; },
};
assert.deepEqual(compat.findComposerToolbar(modernDocument), { kind: 'modern', element: modern });
const legacyDocument = {
querySelector() { return null; },
querySelectorAll() { return [legacy]; },
};
assert.deepEqual(compat.findComposerToolbar(legacyDocument), { kind: 'legacy', element: legacy });
});
test('queue adapter selection prefers prototype-capable modern adapter and retains legacy fallback', () => {
const modernAdapter = Object.create({
enqueueConversationMessageQueueItem() {},
pauseConversationMessageQueue() {},
});
const modernRoot = visibleElement();
modernRoot.__reactFiber$test = { memoizedProps: { adapter: modernAdapter }, return: null };
const modernDocument = {
querySelector(selector) { return selector === '#root > div' ? modernRoot : null; },
};
assert.deepEqual(compat.findQueueAdapter(modernDocument), { kind: 'modern', adapter: modernAdapter });
const legacyAdapter = {
enqueueConversationMessageQueueItem() {},
pauseConversationMessageQueue() {},
};
const legacyRoot = visibleElement();
legacyRoot.__reactFiber$test = { memoizedProps: { value: legacyAdapter }, return: null };
const legacyDocument = {
querySelector(selector) { return selector === '.voice-mic-wrap' ? legacyRoot : null; },
};
assert.deepEqual(compat.findQueueAdapter(legacyDocument), { kind: 'legacy', adapter: legacyAdapter });
});
test('conversation activation exposes the official session lookup and jump event', async () => {
const emitted = [];
const modernAdapter = Object.create({
enqueueConversationMessageQueueItem() {},
pauseConversationMessageQueue() {},
emit(name, payload) { emitted.push({ name, payload }); },
});
modernAdapter.sessionsResource = {
on() {}, off() {},
getByIds(ids) { return Promise.resolve({ conversations: ids.map(id => ({ id })), missingIds: [] }); },
};
const modernRoot = visibleElement();
modernRoot.__reactFiber$test = { memoizedProps: { adapter: modernAdapter }, return: null };
const documentLike = { querySelector(selector) { return selector === '#root > div' ? modernRoot : null; } };
const activation = compat.findConversationActivationApi(documentLike);
assert.ok(activation);
assert.equal(await activation.hasSession('copied-session'), true);
activation.activate('copied-session');
assert.deepEqual(emitted, [{
name: 'jump-to-conversation',
payload: { source: 'tencent-docs', sessionId: 'copied-session', reason: 'already-active' },
}]);
});
test('conversation activation prefers the WorkBuddy 5.7 conversation-list handler', async () => {
const calls = [];
const navigate = async function loadConversationFromList(id, cwd = '', skipLocalCheck = false, preserveListView = false, options = {}) {
// Markers mirror WorkBuddy >= 5.7. Its loader dedupes on loadSession, reads
// options.conversationEngineRouteTarget and honours preserveListView.
if (preserveListView) calls.push('preserve');
if (options.conversationEngineRouteTarget === 'localAssistant') return;
console.debug('[ConversationList] loadSession deduped:', id);
calls.push([id, cwd, skipLocalCheck, preserveListView, options]);
};
const adapter = {
enqueueConversationMessageQueueItem() {},
pauseConversationMessageQueue() {},
emit() { throw new Error('legacy activation must not be used'); },
};
const root = visibleElement();
root.__reactFiber$test = {
memoizedProps: {},
memoizedState: { memoizedState: { current: navigate }, next: null },
return: null,
};
const documentLike = {
querySelector(selector) { return selector === '.conversation-list' ? root : null; },
};
const activation = compat.findConversationActivationApi(documentLike);
assert.ok(activation);
assert.equal(activation.authoritative, true);
assert.equal(activation.activate('official-session'), true);
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(calls, [['official-session', '', false, false, {}]]);
});
test('conversation activation still matches the pre-5.7 navigation handler', async () => {
const calls = [];
const navigate = async function handleConversationClick(id, cwd, skipLocalCheck, preserveListView, options) {
// Markers mirror WorkBuddy <= 5.6, which used these private symbols. Both
// were removed in 5.7, so they must stay supported for older clients.
function dismissHoverPeek() {}
function syncTaskRouteFromClick() {}
dismissHoverPeek();
syncTaskRouteFromClick();
calls.push([id, cwd, skipLocalCheck, preserveListView, options]);
};
const adapter = {
enqueueConversationMessageQueueItem() {},
pauseConversationMessageQueue() {},
emit() { throw new Error('legacy activation must not be used'); },
};
const root = visibleElement();
root.__reactFiber$test = {
memoizedProps: {},
memoizedState: { memoizedState: { current: navigate }, next: null },
return: null,
};
const documentLike = {
querySelector(selector) { return selector === '.conversation-list' ? root : null; },
};
const activation = compat.findConversationActivationApi(documentLike);
assert.ok(activation);
assert.equal(activation.authoritative, true);
assert.equal(activation.activate('legacy-session'), true);
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(calls, [['legacy-session', '', false, false, {}]]);
});
test('conversation activation ignores the non-navigating setCurrentConversation SDK method', () => {
// setCurrentConversation only reports the active conversation to the main
// process. Treating it as an authoritative route transition produced
// "official-dispatched" without a page change, then retried until timeout.
const calls = [];
const previousWindow = global.window;
global.window = {
wb: { conversations: { setCurrentConversation(id) { calls.push(id); } } },
};
try {
const documentLike = { querySelector() { return null; } };
assert.equal(compat.findConversationActivationApi(documentLike), null);
assert.deepEqual(calls, []);
} finally {
if (previousWindow === undefined) delete global.window;
else global.window = previousWindow;
}
});
test('conversation activation uses the session navigation SDK when it is exposed', async () => {
const calls = [];
const previousWindow = global.window;
global.window = {
wb: {
conversations: {
navigateToSession(id, options) { calls.push([this && typeof this.navigateToSession, id, options]); return Promise.resolve(); },
},
},
};
try {
const documentLike = { querySelector() { return null; } };
const activation = compat.findConversationActivationApi(documentLike);
assert.ok(activation);
assert.equal(activation.authoritative, true);
assert.equal(activation.activate('sdk-session'), true);
await new Promise((resolve) => setImmediate(resolve));
assert.equal(calls.length, 1);
assert.equal(calls[0][1], 'sdk-session');
assert.deepEqual(calls[0][2], { ensureLoaded: true });
} finally {
if (previousWindow === undefined) delete global.window;
else global.window = previousWindow;
}
});
test('selected conversation lookup is capability based rather than profile based', () => {
const selected = {
className: 'conversation-item',
firstElementChild: { className: '_card_hash _selected_hash' },
getAttribute(name) { return name === 'data-conversation-id' ? 'conversation-modern' : null; },
};
const documentLike = {
querySelectorAll(selector) {
return selector === '.conversation-item[data-conversation-id]' ? [selected] : [];
},
querySelector() { return null; },
};
assert.equal(compat.getSelectedConversationId(documentLike), 'conversation-modern');
});
test('account import accepts legacy plaintext and preserves encrypted token envelopes', () => {
const envelope = { $wbEncrypted: 1, envelope: 'opaque-envelope' };
const plaintext = {
account: { uid: 'legacy-user', nickname: 'Legacy' },
auth: { accessToken: 'legacy-access', refreshToken: 'legacy-refresh', domain: 'https://www.workbuddy.cn' },
};
const encrypted = {
account: { uid: 'encrypted-user', nickname: envelope },
auth: { accessToken: envelope, refreshToken: envelope, domain: 'https://www.workbuddy.cn' },
};
const plainResult = lib.normalizeAccountImportJson(plaintext);
assert.equal(plainResult.uid, 'legacy-user');
assert.equal(plainResult.normalized.auth.accessToken, 'legacy-access');
const encryptedResult = lib.normalizeAccountImportJson(encrypted);
assert.equal(encryptedResult.uid, 'encrypted-user');
assert.deepEqual(encryptedResult.normalized.auth.accessToken, envelope);
assert.deepEqual(encryptedResult.normalized.auth.refreshToken, envelope);
assert.deepEqual(encryptedResult.normalized.account.nickname, envelope);
assert.equal(lib.wdCompatAuthToken(encryptedResult.normalized.auth), '');
assert.equal(lib.wdCompatText(envelope), '(已加密)');
});
test('token phone claim fills an officially redacted phone field without exposing other claims', () => {
const payload = Buffer.from(JSON.stringify({ preferred_username: '13592246735', email: '[email protected]' })).toString('base64url');
const token = `header.${payload}.signature`;
assert.equal(lib.wdCompatTokenPhone(token), '13592246735');
assert.equal(lib.wdCompatTokenPhone('header.invalid.signature'), '');
assert.equal(lib.wdCompatTokenPhone(''), '');
});
test('Windows encrypted-field key lookup honors the configured WorkBuddy target path', { skip: process.platform !== 'win32' }, () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-compat-target-'));
const previousProfile = process.env.WBSWITCH_PROFILE;
const previousDataDir = process.env.WBSWITCH_DATA_DIR;
const target = 'Z:\\custom-workbuddy\\WorkBuddy.exe';
try {
fs.writeFileSync(path.join(root, 'workbuddy-target.json'), JSON.stringify({
schemaVersion: 1,
clientType: 'official',
profileId: 'workbuddy-cn',
binary: target,
processNames: ['WorkBuddy.exe'],
cdp: { mode: 'argument', port: 9222 },
}));
process.env.WBSWITCH_PROFILE = 'workbuddy-cn';
process.env.WBSWITCH_DATA_DIR = root;
assert.equal(lib.wdCompatExeCandidates()[0], target);
} finally {
if (previousProfile === undefined) delete process.env.WBSWITCH_PROFILE;
else process.env.WBSWITCH_PROFILE = previousProfile;
if (previousDataDir === undefined) delete process.env.WBSWITCH_DATA_DIR;
else process.env.WBSWITCH_DATA_DIR = previousDataDir;
fs.rmSync(root, { recursive: true, force: true });
}
});
test('Windows encrypted-field lookup keeps WorkBuddy key providers available for CodeBuddy imports', () => {
const candidates = lib.wdCompatWindowsExeCandidates({
localAppData: 'C:\\Users\\tester\\AppData\\Local',
profileId: 'codebuddy-cn',
configured: 'C:\\Users\\tester\\AppData\\Local\\Programs\\CodeBuddy CN\\CodeBuddy CN.exe',
});
assert.deepEqual(candidates.slice(0, 2), [
'C:\\Users\\tester\\AppData\\Local\\Programs\\WorkBuddy\\WorkBuddy.exe',
'C:\\Users\\tester\\AppData\\Local\\Programs\\WorkBuddyAI\\WorkBuddyAI.exe',
]);
assert.equal(candidates.includes('C:\\Users\\tester\\AppData\\Local\\Programs\\CodeBuddy CN\\CodeBuddy CN.exe'), false);
});
test('account backup keeps both legacy plaintext and encrypted source bytes unchanged', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-compat-'));
try {
const dataDir = path.join(root, 'WorkDaddy');
const authDir = path.join(root, 'auth');
fs.mkdirSync(authDir, { recursive: true });
lib.ensureDirs(dataDir);
const envelope = { $wbEncrypted: 1, envelope: 'opaque-envelope' };
const fixtures = [
{
uid: 'legacy-user',
value: { account: { uid: 'legacy-user', nickname: 'Legacy' }, auth: { accessToken: 'legacy-access', domain: 'https://www.workbuddy.cn' } },
},
{
uid: 'encrypted-user',
value: { account: { uid: 'encrypted-user', nickname: envelope }, auth: { accessToken: envelope, domain: 'https://www.workbuddy.cn' } },
},
];
for (const fixture of fixtures) {
const source = path.join(authDir, fixture.uid + '.info');
const raw = JSON.stringify(fixture.value, null, 2);
fs.writeFileSync(source, raw);
lib.backupAuthFile(dataDir, source);
assert.equal(fs.readFileSync(lib.backupPath(dataDir, fixture.uid), 'utf8'), raw);
}
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test('injected compatibility is packaged and AI theme access is no longer profile-gated', () => {
const root = path.join(__dirname, '..');
const daemon = fs.readFileSync(path.join(root, 'scripts', 'daemon.js'), 'utf8');
const inject = fs.readFileSync(path.join(root, 'scripts', 'inject.js'), 'utf8');
const macBuild = fs.readFileSync(path.join(root, 'scripts', 'build-mac-dmg.sh'), 'utf8');
const winVerify = fs.readFileSync(path.join(root, 'scripts', 'verify-win.cmd'), 'utf8');
assert.match(daemon, /workbuddy-compat\.js/);
assert.match(macBuild, /workbuddy-compat\.js/);
assert.match(winVerify, /workbuddy-compat\.js/);
assert.match(inject, /WBS_COMPAT\.findComposerToolbar\(document\)/);
assert.match(inject, /WBS_COMPAT\.findQueueAdapter\(document\)/);
assert.match(inject, /if \(!CAPS\.theme\)/);
assert.doesNotMatch(inject, /if \(!CAPS\.theme \|\| WBS_PROFILE_IS_AI\)/);
assert.doesNotMatch(inject, /migrateWorkBuddyAiThemeOnce/);
});
test('CodeBuddy activation uses its official guarded navigation handler with the native signature', async()=>{
const calls=[];
const navigate=async function(id,cwd,skip,preserve,title){
const SessionLoadCancelledError='SessionLoadCancelledError';
function getPendingMessageTracker(){} function getInitialMessages(){}
calls.push([id,cwd,skip,preserve,title]);
};
const root=visibleElement();
root.__reactFiber$native={memoizedState:{memoizedState:{current:navigate}},return:null};
const doc={querySelector:s=>s==='[data-conversation-id]'?root:null};
assert.equal(compat.findConversationActivationApi(doc),null);
const api=compat.findConversationActivationApi(doc,{profileId:'codebuddy-cn'});
assert.equal(api.authoritative,true);assert.equal(api.activate('native-session'),true);
await new Promise(r=>setImmediate(r));
assert.deepEqual(calls,[['native-session','',false,false,undefined]]);
});
test('CodeBuddy send lookup selects official submit handler and excludes plugin buttons', () => {
const compat = require('../scripts/workbuddy-compat');
const plugin={className:'wbs-explore-inline',closest:()=>({})};
const enhance={className:'_icon_hash',closest:()=>null,__reactProps$x:{onClick:()=>{}}};
const send={className:'_icon_hash _active_hash',closest:()=>null,
__reactProps$x:{onClick:function(){ editor.prepareBeforeSubmit?.(); editor.flushPendingContentChange(); }}};
const box={querySelectorAll:()=>[plugin,enhance,send]};
const doc={activeElement:{closest:()=>box},querySelectorAll:()=>[box]};
assert.equal(compat.findCodeBuddySendButton(doc),send);
box.querySelectorAll=()=>[plugin,enhance];
assert.equal(compat.findCodeBuddySendButton(doc),null);
doc.activeElement=null;doc.querySelectorAll=()=>[box,box];
assert.equal(compat.findCodeBuddySendButton(doc),null);
});