Skip to content

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

fix: preserve official session pins across account switches

[email protected]03aeabcce4ca
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index c0c602e..6075b2e 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -65,7 +65,7 @@ chmod 644 "$APP/Contents/Resources/AppIcon.icns"
echo "==> 应用图标已同步(背景 #e1e1e1)"
# 2) 覆盖运行时代码和主题配置,保留 launcher/Info.plist/壁纸/node_modules/theme-audit.js。
-for f in daemon.js account-identity.js session-copy-error.js persona.js markdown-preview.js renderer-api-bridge.js codebuddy-native.js codebuddy-native-recovery.js codebuddy-session-store.js codebuddy-files.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-account-sync.js official-automation-sync.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js wallpaper-rotation.js wallpaper-video.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js client-launch-settings.js client-temp.js workbuddy-launch-env.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
+for f in daemon.js account-identity.js session-copy-error.js persona.js markdown-preview.js renderer-api-bridge.js codebuddy-native.js codebuddy-native-recovery.js codebuddy-session-store.js codebuddy-files.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-account-sync.js official-automation-sync.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-pin-sync.js session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js wallpaper-rotation.js wallpaper-video.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js client-launch-settings.js client-temp.js workbuddy-launch-env.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"
done
# Theme tokens are source code too; the reusable shell may contain older colors.
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 48c85f4..3ffc2f4 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -32,6 +32,7 @@ const { sanitizeSessionCopyError } = require('./session-copy-error');
const net = require('net');
const { inspectPersona, copyPersona, readPersonaSettings, listPersonaSources, configurePersona, dismissPersonaNotice, syncSharedPersonaForSwitch } = require('./persona.js');
let sessionSync = require('./session-sync.js');
+const { createSessionPinSync, readPinsInRenderer, applyPinsInRenderer } = require('./session-pin-sync');
const {createCodeBuddyFiles} = require('./codebuddy-files.js');
const { createAccountCreditCache } = require('./account-credit-cache.js');
const { spawn, spawnSync, execFile } = require('child_process');
@@ -546,8 +547,8 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 1.2.70:视频壁纸层夹在 body 底色与 #root 之间,毛玻璃主题下正常显示画面。
// #507: explicit cleanup of old Windows client temp files, only before a verified cold launch.
// 1.2.81:在共享目标分支加入视频壁纸及失败重试、主题路径边界修复。
-const DAEMON_VERSION = '1.2.82';
-const DAEMON_BUILD_ID = 'release-1.2.82-expired-credit-filter';
+const DAEMON_VERSION = '1.2.84';
+const DAEMON_BUILD_ID = 'release-1.2.84-session-pin-capture';
const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });
configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const automationDiscovery = createAutomationDiscovery({
@@ -1954,6 +1955,7 @@ function syncCodeBuddyAuth() {
return work;
}
async function switchAccountForProfile(uid) {
+ await captureSessionPins();
if (!codeBuddyNative) {
const sharing = PROFILE.kind === 'workbuddy' ? syncSharedPersonaForSwitch({ dataRoot: PROFILE.dataRoot,
backupRoot: DATA_DIR, accounts: listAccounts(DATA_DIR), sourceUid: String((currentAccount() || {}).uid || ''), targetUid: String(uid) }) : null;
@@ -4688,6 +4690,7 @@ async function injectWidget(reason, executionContextId) {
// Reinjection and daemon replacement must reflect the current input lease,
// including a reset after an interrupted run. Reply-waiting never locks UI.
.then(async (r) => { await automationPanelSetInputActive(automationInputActive); return r; })
+ .then(async (r) => { if (!r?.exceptionDetails) await flushSessionPins(); return r; })
// 注入脚本若在页面抛错,CDP 协议不报错(无 protocol error),会被误判为"已注入";
// 显式检查 exceptionDetails 让失败可见、留痕,便于定位 WorkBuddy 版本差异导致的挂载失败。
.then((r) => {
@@ -6505,6 +6508,67 @@ function pruneAutoCopyJobs() {
}
}
+// Official pin state is scoped to the signed-in account. Capture before auth
+// replacement, then deliver only proven mapped copies after the copy queue.
+// Never use source IDs in the target list or modify WorkBuddy's React state.
+let sessionPinSync = null;
+function getSessionPinSync() {
+ if (!sessionPinSync) sessionPinSync = createSessionPinSync({
+ file: path.join(DATA_DIR, 'session-pin-sync-' + PROFILE.id + '.json'),
+ read: (uid) => evaluateSessionPins(readPinsInRenderer, uid),
+ apply: (uid, ids) => evaluateSessionPins(applyPinsInRenderer, uid, ids),
+ resolve: async (sourceUid, targetUid, ids) => {
+ if (sessionAccountAmbiguous(sourceUid) || sessionAccountAmbiguous(targetUid)) return [];
+ const candidates = ids.map(sourceId => ({ sourceId, targetId: resolveAutoCopyTargetId(sourceUid, targetUid, sourceId) }))
+ .filter(item => isValidSessionId(item.sourceId) && isValidSessionId(item.targetId));
+ if (!candidates.length) return [];
+ const allIds = [...new Set(candidates.flatMap(item => [item.sourceId, item.targetId]))];
+ const rows = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + sqlPlaceholders(allIds) + ") AND deleted_at IS NULL AND COALESCE(status, '') != 'archived';", allIds);
+ const owners = new Map(rows.map(row => [String(row.id), String(row.user_id)]));
+ return candidates.filter(item => owners.get(item.sourceId) === sourceUid && owners.get(item.targetId) === targetUid);
+ },
+ });
+ return sessionPinSync;
+}
+async function evaluateSessionPins(fn, uid, ids) {
+ const account = currentAccount();
+ if (!cdp.connected || !account || String(account.uid) !== String(uid)) return null;
+ const expected = { uid: String(account.rawUid || account.uid), type: account.type || '', enterpriseId: account.enterpriseId || '' };
+ let timer;
+ try {
+ const result = await Promise.race([
+ cdpSend('Runtime.evaluate', {
+ expression: '(' + fn.toString() + ')(' + JSON.stringify(expected) + ',' + JSON.stringify(ids || []) + ')',
+ awaitPromise: true, returnByValue: true,
+ }),
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('同步会话置顶超时')), 3000); }),
+ ]);
+ if (result?.exceptionDetails) return null;
+ return result?.result?.value;
+ } finally { clearTimeout(timer); }
+}
+async function captureSessionPins() {
+ if (PROFILE.kind !== 'workbuddy') return;
+ const uid = String((currentAccount() || {}).uid || '');
+ if (!uid || sessionAccountAmbiguous(uid)) return;
+ try {
+ await getSessionPinSync().flush(uid);
+ await getSessionPinSync().capture(uid);
+ } catch (_) { log('[sessions-pins] 暂时无法读取置顶,保留原记录'); }
+}
+async function syncSessionPins(sourceUid, targetUid) {
+ if (PROFILE.kind !== 'workbuddy' || accountSwitchInProgress) return;
+ try { await getSessionPinSync().sync(sourceUid, targetUid); }
+ catch (_) { log('[sessions-pins] 置顶同步未确认,保留待处理记录'); }
+}
+async function flushSessionPins() {
+ if (PROFILE.kind !== 'workbuddy' || accountSwitchInProgress) return;
+ const uid = String((currentAccount() || {}).uid || '');
+ if (!uid || sessionAccountAmbiguous(uid)) return;
+ try { await getSessionPinSync().flush(uid); }
+ catch (_) { log('[sessions-pins] 置顶恢复未确认,稍后重试'); }
+}
+
function resolveAutoCopyTargetId(sourceUid, targetUid, sessionId) {
const source = String(sourceUid || '').trim();
const target = String(targetUid || '').trim();
@@ -6773,6 +6837,7 @@ async function refreshWorkBuddySessionList(targetUid, reason = 'sessions') {
}
async function refreshCopiedSessionList(job) {
+ if (job) await syncSessionPins(job.sourceUid, job.targetUid);
if (!job || !(job.copied || job.partial || job.conflicts || job.openSessionId)) return false;
return refreshWorkBuddySessionList(job.targetUid, 'sessions-auto-copy');
}
@@ -12634,6 +12699,7 @@ function handleApi(req, res) {
const copyOperation = Symbol('manual-session-copy');
sessionCopyLocks.set(copyOperation, true);
try {
+ await captureSessionPins();
// 1) 取出源会话(含 cwd 用于定位消息文件)
const srcRows = await sqliteQuery(
"SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id FROM sessions WHERE id IN (" + sqlPlaceholders(ids) + ") AND deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0;",
@@ -12649,6 +12715,7 @@ function handleApi(req, res) {
else if (result.status === 'skipped') skipped++;
else copied++;
}
+ for (const sourceUid of new Set(srcRows.map(row => String(row.user_id || '')))) await syncSessionPins(sourceUid, targetUid);
// [CodeBuddy 会话同步] 同步到当前账号时刷新 IDE workbench:扩展宿主的
// indexCache 不因外部写 index.json 失效,侧边栏要等 TTL/重启才显示(详见
// reloadIdeWorkbenchWindows 注释)。同步到其他账号无需刷新——切号时
diff --git a/scripts/inject.js b/scripts/inject.js
index 5c2ee89..9c99248 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -1857,7 +1857,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'会话同步完成': 'Session sync complete', '会话同步完成,已保留分叉': 'Session sync complete with conflicts', '会话同步完成,部分项目失败': 'Session sync complete with some failures', '会话同步等待中': 'Session sync waiting', '正在同步会话': 'Syncing session', '会话同步失败': 'Session sync failed', '同步等待中': 'Sync waiting', '同步失败': 'Sync failed', '同步': 'Sync', '已同步': 'Synced', ' · 新同步': ' · Newly synced ', ' · 有': ' · ', ' 项需要留意': ' item(s) need attention', ' · 请稍后重试': ' · Try again later', '会话同步进度': 'Session sync progress', ' 个会话已分叉,已保留双方内容': ' session(s) were changed on both sides; neither side was overwritten', '其他账号': 'Other account', '同步完成': 'Sync complete', '同步完成,已保留分叉': 'Sync complete with conflicts', '同步完成,部分失败': 'Sync complete with some failures', '正在把已标记的会话同步到「': 'Syncing marked sessions to “', ' 个未变化会话': ' unchanged session(s)', '同步任务未完成,请稍后重试': 'Sync did not finish. Try again later',
' · 跳过': ' · Skipped', ' · 分叉': ' · Conflicts', '成功': 'Succeeded', '跳过': 'Skipped', '已跳过': 'Skipped', '部分失败': 'Partial failure', '分叉': 'Conflict', '处理中': 'Processing', '会话已分叉,已保留双方内容': 'Changed on both sides; neither side was overwritten', '部分文件失败': 'Some files failed', '当前任务未记录逐项明细。': 'No per-session details were recorded for this task.', '会话同步明细': 'Session sync details', '会话同步结果筛选': 'Filter session sync results', '当前分类没有会话。': 'No sessions in this category.', '正在把已标记的会话从「': 'Syncing marked sessions from “', '」同步到「': '” to “', '查看明细': 'View details', ' 个候选会话': ' candidate session(s)', ' 秒后自动关闭': ' seconds until automatic close',
'收录 GitHub 和 Gitee 公开仓库。参考 ': 'Public GitHub and Gitee repositories are indexed. See ', '。': '.', '克隆示例仓库:': 'Clone the example repository: ', '删除 ': 'Delete ', ' 目录中不需要的示例任务。': ' directory tasks you do not need.', '把你的自动化任务 JSON 放进 ': 'Put your automation task JSON in ', ' 目录。': ' directory.', '提交改动并推送到 GitHub 或 Gitee。': 'Commit and push changes to GitHub or Gitee.', '在仓库简介中加入关键词 ': 'Add the keyword ',
- '移除置顶备忘': 'Remove pinned reminder', '记住置顶会话': 'Remember pinned session',
'导出账号': 'Export accounts', '导入账号': 'Import accounts', '导出会话': 'Export sessions', '导入会话': 'Import sessions', '导出快捷短语': 'Export quick phrases', '导入快捷短语': 'Import quick phrases', '同步选中到其他账号': 'Sync selected to another account', '删除选中': 'Delete selected', '操作会话': 'Session actions', '连通测试': 'Test connection', '编辑模型': 'Edit model', '模型已保存': 'Model saved', '模型已启用': 'Model enabled', '模型已复制': 'Model copied', '模型配置已共用': 'Model configuration shared', '与 {name} 共用模型配置': 'Model configuration shared with {name}', '当前模型': 'Current model', '备选模型': 'Backup models', '模型加载失败:': 'Failed to load models: ', '保存模型失败:': 'Failed to save model: ', '删除当前模型失败:': 'Failed to delete current model: ', '启用模型失败:': 'Failed to enable model: ', '连通测试失败:': 'Connection test failed: ',
'请选择壁纸文件夹': 'Choose a wallpaper folder', '壁纸模式': 'Wallpaper mode', '手动应用': 'Manual', '文件夹随机': 'Shuffle folder', '壁纸文件夹': 'Wallpaper folder', '选择或填写文件夹路径': 'Choose or enter a folder path', '选择文件夹': 'Choose folder', '切换间隔': 'Change every', '1 分钟': '1 minute', '3 分钟': '3 minutes', '5 分钟': '5 minutes', '10 分钟': '10 minutes', '30 分钟': '30 minutes', '1 小时': '1 hour', '自定义': 'Custom', '分钟': 'minutes', '自定义切换间隔(分钟)': 'Custom interval (minutes)', '立即换一张': 'Next wallpaper', '已暂停,恢复毛玻璃主题后继续': 'Paused until the frosted theme resumes', '当前:': 'Current: ', '等待应用壁纸': 'Waiting to apply wallpaper', '壁纸设置保存失败': 'Could not save wallpaper settings', '仅读取此文件夹内的 PNG / JPG / WebP,不复制或修改原文件;自动跳过超过 20MB 或 1600 万像素的图片。': 'Reads PNG / JPG / WebP from this folder without copying or modifying originals. Images over 20MB or 16 megapixels are skipped.',
'选择要查看的账号': 'Choose an account to view', '选择账号并输入密码后导出备份': 'Choose accounts and enter a password to export backups', '从加密导出文件导入账号备份': 'Import account backups from an encrypted export', '使用密码导出选中会话': 'Export selected sessions with a password', '使用密码导出选中快捷短语': 'Export selected quick phrases with a password', '从加密文件导入会话': 'Import sessions from an encrypted file', '从加密文件导入快捷短语': 'Import quick phrases from an encrypted file', '仅支持 PNG / JPG / WebP': 'PNG / JPG / WebP only', '点击或拖拽上传壁纸': 'Click or drag to upload a wallpaper', '点击选择图片,或拖拽到此处': 'Click to choose an image, or drag it here', '支持 PNG / JPG / WebP,自动压缩;可添加多张': 'PNG / JPG / WebP supported; images are compressed automatically',
@@ -9853,30 +9852,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
- var rememberedSessionsKey = 'wbs-remembered-sessions-' + (typeof PROFILE_ID === 'undefined' ? 'workbuddy-cn' : PROFILE_ID);
- function rememberedSessions() {
- try {
- var value = JSON.parse(localStorage.getItem(rememberedSessionsKey) || '{}');
- return value && typeof value === 'object' ? value : {};
- } catch (_) { return {}; }
- }
- function isSessionRemembered(session) {
- var uid = String(session && session.user_id || sessionsState.uid || sessionsState.currentUid || '');
- var records = rememberedSessions()[uid];
- return !!(uid && Array.isArray(records) && records.some(function (item) { return item && String(item.id) === String(session.id); }));
- }
- function toggleRememberedSession(session) {
- var uid = String(session && session.user_id || sessionsState.uid || sessionsState.currentUid || '');
- if (!uid || !session || !session.id) return;
- var recordsByUid = rememberedSessions();
- var records = Array.isArray(recordsByUid[uid]) ? recordsByUid[uid].slice() : [];
- var existing = records.findIndex(function (item) { return item && String(item.id) === String(session.id); });
- if (existing >= 0) records.splice(existing, 1);
- else records.unshift({ id:String(session.id), title:String(session.custom_title || session.title || '(无标题)'), savedAt:Date.now() });
- recordsByUid[uid] = records.slice(0, 500);
- try { localStorage.setItem(rememberedSessionsKey, JSON.stringify(recordsByUid)); } catch (_) {}
- }
-
// 按空间分组渲染:每个空间默认显示 INIT 条,可一次展开全部。
function renderSessions() {
var listEl = sessionsPane.querySelector('#wbs-sess-list');
@@ -9896,11 +9871,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return '<button class="wbs-sess-sync" type="button" data-id="' + escAttr(s.id) + '" title="同步到其他账号" aria-label="同步到其他账号">' +
'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 3l4 4-4 4"/><path d="M20 7H8"/><path d="M8 21l-4-4 4-4"/><path d="M4 17h12"/></svg></button>';
}
- function rememberSessionButton(s) {
- var remembered = isSessionRemembered(s);
- var title = remembered ? '移除置顶备忘' : '记住置顶会话';
- return '<button class="wbs-sess-remember' + (remembered ? ' active' : '') + '" type="button" data-id="' + escAttr(s.id) + '" aria-label="' + title + '" title="' + title + '" aria-pressed="' + (remembered ? 'true' : 'false') + '"><svg viewBox="0 0 24 24" width="16" height="16" fill="' + (remembered ? 'currentColor' : 'none') + '" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3 2.7 5.5 6.1.9-4.4 4.3 1 6.1-5.4-2.9-5.4 2.9 1-6.1-4.4-4.3 6.1-.9L12 3z"/></svg></button>';
- }
function autoCopyButton(kind, key, uid, enabled, inherited) {
if (sessionsState.autoCopyAll || !canEditAutoCopy(uid)) return '';
var title = inherited ? '随空间自动同步' : (enabled ? '取消自动同步' : '切换账号时自动同步');
@@ -9941,7 +9911,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
(batch ? '<input type="checkbox" class="wbs-sess-check" data-id="' + escAttr(s.id) + '"' + sel + '>' : '') +
'<span class="wbs-sess-main"><span class="wbs-sess-title">' + esc(title) + '</span>' +
'<span class="wbs-sess-meta">' + esc(fmtHumanTime(s.last_activity_at || s.updated_at || s.created_at)) + '</span></span>' +
- (batch ? '' : rememberSessionButton(s) + sessSyncButton(s) + autoCopyButton('session', s.id, s.user_id, marked, inherited)) +
+ (batch ? '' : sessSyncButton(s) + autoCopyButton('session', s.id, s.user_id, marked, inherited)) +
'<span class="wbs-sess-size" title="会话大小(消息和附件)">' + sessionCopySizeText(s.totalBytes) + '</span>' +
'</div>';
});
@@ -9974,7 +9944,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
(batch ? '<input type="checkbox" class="wbs-sess-check" data-id="' + escAttr(s.id) + '"' + sel + '>' : '') +
'<span class="wbs-sess-main"><span class="wbs-sess-title">' + esc(title) + '</span>' +
'<span class="wbs-sess-meta">' + esc(fmtHumanTime(s.last_activity_at || s.updated_at || s.created_at)) + '</span></span>' +
- (batch ? '' : rememberSessionButton(s) + sessSyncButton(s) + autoCopyButton('session', s.id, s.user_id, marked, inherited)) +
+ (batch ? '' : sessSyncButton(s) + autoCopyButton('session', s.id, s.user_id, marked, inherited)) +
'<span class="wbs-sess-size" title="会话大小(消息和附件)">' + sessionCopySizeText(s.totalBytes) + '</span>' +
'</div>';
});
@@ -10070,17 +10040,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function bindSessEvents(listEl) {
listEl.onclick = function (e) {
var t = e.target;
- var rememberBtn = t.closest ? t.closest('.wbs-sess-remember') : null;
- if (rememberBtn) {
- e.preventDefault();
- e.stopPropagation();
- var rememberedSession = sessionsState.list.find(function (item) { return String(item.id) === String(rememberBtn.getAttribute('data-id')); });
- if (rememberedSession) {
- toggleRememberedSession(rememberedSession);
- renderSessions();
- }
- return;
- }
// [会话单条同步] 行内同步按钮:打开单条目标账号弹窗
var syncBtn = t.closest ? t.closest('.wbs-sess-sync') : null;
if (syncBtn) {
@@ -19055,9 +19014,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
/* [会话单条同步] 行内同步图标按钮:尺寸/圆角/交互色与自动同步按钮一致 */
'.wbs-sess-sync{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:26px;height:26px;margin-top:-2px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--wb-icon-tertiary,#999);cursor:pointer;padding:0;transition:background .15s,color .15s;font:inherit}',
'.wbs-sess-sync:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}',
- '.wbs-sess-remember{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:26px;height:26px;margin-top:-2px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--wb-icon-tertiary,#999);cursor:pointer;padding:0;transition:background .15s,color .15s;font:inherit}',
- '.wbs-sess-remember:hover,.wbs-sess-remember.active{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-accent-primary,var(--wb-color-text-primary,#1f1f1f))}',
- '.wbs-sess-remember:focus-visible{outline:2px solid color-mix(in srgb,var(--wb-color-text-primary,#1f1f1f) 50%,transparent);outline-offset:1px}',
'.wbs-sess-sync:focus-visible{outline:2px solid color-mix(in srgb,var(--wb-color-text-primary,#1f1f1f) 50%,transparent);outline-offset:1px}',
'.wbs-sess-auto-switch{position:relative;display:inline-flex;align-items:center;width:24px;height:14px;flex:0 0 24px;border-radius:999px;background:var(--wb-bg-tertiary,#dedede);transition:background .15s}',
'.wbs-sess-auto-switch span{width:10px;height:10px;margin-left:2px;border-radius:50%;background:var(--wb-bg-popover,#fff);box-shadow:0 1px 2px rgba(0,0,0,.18);transition:transform .15s}',
diff --git a/scripts/session-pin-sync.js b/scripts/session-pin-sync.js
new file mode 100644
index 0000000..cbc4283
--- /dev/null
+++ b/scripts/session-pin-sync.js
@@ -0,0 +1,95 @@
+'use strict';
+const fs = require('node:fs');
+const path = require('node:path');
+
+// Only IDs are retained, never conversation contents or account credentials.
+// Separate from official storage: this is a delivery queue, not a pin authority.
+function createSessionPinSync({ file, read, resolve, apply }) {
+ let state = { snapshots: {}, pending: {}, delivered: {} };
+ try { const saved = JSON.parse(fs.readFileSync(file, 'utf8')); if (saved.version === 1) state = saved; } catch (_) {}
+ let tail = Promise.resolve();
+ const serial = fn => { const task=tail.then(fn); tail=task.catch(()=>{}); return task; };
+ const clean = ids => [...new Set((Array.isArray(ids) ? ids : []).filter(id => typeof id === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(id)))];
+ const save = () => {
+ fs.mkdirSync(path.dirname(file), { recursive:true, mode:0o700 });
+ const temp=file+'.tmp'; fs.writeFileSync(temp, JSON.stringify({ ...state, version:1 }), {mode:0o600}); fs.renameSync(temp,file);
+ };
+ const key = (source, target, sourceId, targetId) => JSON.stringify([source,target,sourceId,targetId]);
+ async function capture(uid) {
+ const ids=await read(uid);
+ if (!Array.isArray(ids)) return false;
+ const pins=clean(ids); state.snapshots[uid]=pins;
+ // Fresh official unpins invalidate undelivered copies and allow a future
+ // explicit repin to be propagated again. Never unpin another account.
+ for (const target of Object.keys(state.pending)) state.pending[target]=state.pending[target].filter(item=>item.source!==uid || pins.includes(item.sourceId));
+ for (const id of Object.keys(state.delivered)) { const [source,,sourceId]=JSON.parse(id); if (source===uid&&!pins.includes(sourceId)) delete state.delivered[id]; }
+ save(); return true;
+ }
+ async function flush(uid) {
+ const pending=state.pending[uid]||[];
+ if (!pending.length) return false;
+ // Revalidate mappings at delivery time: a copied session may have been
+ // deleted or remapped while this account was inactive.
+ const valid=[];
+ for (const source of new Set(pending.map(item=>item.source))) {
+ const group=pending.filter(item=>item.source===source);
+ const mappings=await resolve(source,uid,group.map(item=>item.sourceId));
+ valid.push(...group.filter(item=>mappings.some(m=>m.sourceId===item.sourceId&&m.targetId===item.targetId)));
+ }
+ const ordered=pending.filter(item=>valid.includes(item));
+ if (ordered.length && !await apply(uid,clean(ordered.map(item=>item.targetId)))) return false;
+ for (const item of ordered) state.delivered[key(item.source,uid,item.sourceId,item.targetId)]=true;
+ delete state.pending[uid]; save(); return ordered.length>0;
+ }
+ return {
+ capture: uid => serial(()=>capture(uid)),
+ flush: uid => serial(()=>flush(uid)),
+ sync: (source,target) => serial(async()=>{
+ if (!source||!target||source===target) return false;
+ // Include incoming pending pins for rapid A -> B -> C rotations, where
+ // B's renderer has not mounted yet but the copy queue has completed.
+ const ids=clean([...(state.pending[source]||[]).map(item=>item.targetId),...(state.snapshots[source]||[])]);
+ if (!ids.length) return false;
+ const mappings=await resolve(source,target,ids);
+ const queue=state.pending[target]||[];
+ for (const sourceId of ids) {
+ const targetId=mappings.find(item=>item.sourceId===sourceId)?.targetId;
+ if (!clean([targetId]).length || targetId===sourceId || state.delivered[key(source,target,sourceId,targetId)]) continue;
+ if (!queue.some(item=>item.source===source&&item.sourceId===sourceId&&item.targetId===targetId)) queue.push({source,sourceId,targetId});
+ }
+ if (!queue.length) return false;
+ state.pending[target]=queue; save(); return flush(target);
+ }),
+ };
+}
+
+// These self-contained functions run through CDP. Use the public SDK, never
+// React state or storage RPCs. Compare raw UID plus login context on each step.
+async function readPinsInRenderer(expected) {
+ const wb=window.wb;
+ if (!wb?.account?.profile || !wb?.conversations?.listPinned) return null;
+ const matches=p=>p&&String(p.uid||'')===String(expected.uid||'')&&String(p.type||'')===String(expected.type||'')&&String(p.enterpriseId||'')===String(expected.enterpriseId||'');
+ if (!matches(await wb.account.profile())) return null;
+ const items=await wb.conversations.listPinned();
+ if (!Array.isArray(items)||!matches(await wb.account.profile())) return null;
+ return items.map(item=>item.id).filter(id=>typeof id==='string');
+}
+async function applyPinsInRenderer(expected, ids) {
+ const wb=window.wb, c=wb?.conversations;
+ if (!wb?.account?.profile || !c?.listPinned || !c?.pin) return false;
+ const matches=p=>p&&String(p.uid||'')===String(expected.uid||'')&&String(p.type||'')===String(expected.type||'')&&String(p.enterpriseId||'')===String(expected.enterpriseId||'');
+ if (!matches(await wb.account.profile())) return false;
+ const before=await c.listPinned(); if (!Array.isArray(before)) return false;
+ const existing=new Set(before.map(item=>item.id));
+ // Official pin inserts at the front. Reverse the source order once, and
+ // leave existing target pins (and their relative order) untouched.
+ for (const id of ids.slice().reverse()) {
+ if (existing.has(id)) continue;
+ if (!matches(await wb.account.profile())) return false;
+ const result=await c.pin(id); if (result?.errorCode) return false;
+ }
+ if (!matches(await wb.account.profile())) return false;
+ const after=await c.listPinned();
+ return Array.isArray(after)&&ids.every(id=>after.some(item=>item.id===id));
+}
+module.exports={createSessionPinSync,readPinsInRenderer,applyPinsInRenderer};
diff --git a/test/cdp-custom-target.test.js b/test/cdp-custom-target.test.js
index 426c92f..6a23b1a 100644
--- a/test/cdp-custom-target.test.js
+++ b/test/cdp-custom-target.test.js
@@ -41,7 +41,7 @@ function harness({ targets = [own], unavailable = false, activeProfile = profile
evaluations.push({ method, ...params });
return { result: { value: { root: true, widget: true, url: cdp.targetUrl } } };
},
- automationPanelSetInputActive: async () => {}, automationInputActive: false,
+ flushSessionPins: async () => {}, automationPanelSetInputActive: async () => {}, automationInputActive: false,
wallpaperRotation: { status: () => ({ mode: 'fixed' }) },
});
for (const [start, end] of [
diff --git a/test/persona-api.test.js b/test/persona-api.test.js
index 023264d..ed9f15b 100644
--- a/test/persona-api.test.js
+++ b/test/persona-api.test.js
@@ -17,6 +17,7 @@ function harness(t, profile = 'workbuddy-cn') {
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' }],
diff --git a/test/renderer-escaping.test.js b/test/renderer-escaping.test.js
index 011861c..596e134 100644
--- a/test/renderer-escaping.test.js
+++ b/test/renderer-escaping.test.js
@@ -57,8 +57,8 @@ test('session and account selectors escape every text and attribute sink', () =>
const sessions = sourceBetween('function renderSessions()', 'function activeAutoCopyCount()');
assert.equal((sessions.match(/escAttr\(key\)/g) || []).length, 1);
assert.equal((sessions.match(/escAttr\(uid\)/g) || []).length, 1);
- // 2 处勾选框 + 同步按钮 + 置顶备忘按钮,均经 escAttr
- assert.equal((sessions.match(/escAttr\(s\.id\)/g) || []).length, 4);
+ // 2 处勾选框 + 同步按钮,均经 escAttr
+ assert.equal((sessions.match(/escAttr\(s\.id\)/g) || []).length, 3);
assert.equal((sessions.match(/esc\(title\)/g) || []).length, 2);
assert.equal((sessions.match(/esc\(fmtHumanTime\(/g) || []).length, 2);
assert.match(sessions, /title="' \+ escAttr\(group\.cwd\)/);
diff --git a/test/session-copy-list-refresh.test.js b/test/session-copy-list-refresh.test.js
index fb3d3c6..03875b6 100644
--- a/test/session-copy-list-refresh.test.js
+++ b/test/session-copy-list-refresh.test.js
@@ -9,7 +9,7 @@ const source = fs.readFileSync(require.resolve('../scripts/daemon.js'), 'utf8');
function harness({ kind = 'workbuddy', owner = 'target', connected = true, reject = false, status = 'copied', openSessionId = '' } = {}) {
const stored = new Set(), visible = new Set(), calls = [];
let activeSession = 'existing-session';
- const ctx = { crypto, Date, PROFILE: { kind }, cdp: { connected },
+ const ctx = { syncSessionPins: async () => {}, crypto, Date, PROFILE: { kind }, cdp: { connected },
currentAccount: () => ({ uid: owner }),
autoCopyJobs: new Map(), autoCopyQueue: [],
yieldAutoCopyToRenderer: async () => {},
@@ -60,6 +60,7 @@ test('completed copy batches publish the new WorkBuddy list before reporting don
async function manualCopy({ kind = 'workbuddy', owner = 'target', connected = true, reject = false, status = 'copied' } = {}) {
const stored = new Set(), visible = new Set(), calls = [];
const ctx = {
+ syncSessionPins: async () => {}, captureSessionPins: async () => {},
PROFILE: { kind }, cdp: { connected },
currentAccount: () => ({ uid: owner }),
readBody: async () => ({ ids: ['a', 'b'], targetUid: 'target' }),
diff --git a/test/session-pin-sync.test.js b/test/session-pin-sync.test.js
new file mode 100644
index 0000000..ee53189
--- /dev/null
+++ b/test/session-pin-sync.test.js
@@ -0,0 +1,113 @@
+'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 { createSessionPinSync, readPinsInRenderer, applyPinsInRenderer } = require('../scripts/session-pin-sync');
+
+function harness(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-pins-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ let active = 'a';
+ const pins = { a: ['a2', 'a1'], b: ['b-own'], c: [] }, writes = [];
+ const mappings = { 'a:b': { a1: 'b1', a2: 'b2' }, 'b:c': { b1: 'c1', b2: 'c2' } };
+ const options = { file: path.join(dir, 'pins.json'),
+ read: async uid => active === uid ? pins[uid].slice() : null,
+ resolve: async (from, to, ids) => ids.map(id => ({ sourceId:id, targetId:mappings[from+':'+to]?.[id] })).filter(x=>x.targetId),
+ apply: async (uid, ids) => {
+ if (active !== uid) return false;
+ writes.push([uid, ids.slice()]); pins[uid] = [...ids.filter(id=>!pins[uid].includes(id)), ...pins[uid]]; return true;
+ },
+ };
+ return { options, pins, writes, setActive: uid => { active=uid; }, service: createSessionPinSync(options) };
+}
+test('copy carries official pin order to mapped IDs and preserves both accounts existing pins', async t => {
+ const h=harness(t); await h.service.capture('a'); h.setActive('b');
+ await h.service.sync('a','b');
+ assert.deepEqual(h.pins.a,['a2','a1']); assert.deepEqual(h.pins.b,['b2','b1','b-own']);
+ assert.equal(h.pins.b.includes('a1'),false);
+});
+test('pending pins survive restart and only apply to the matching account', async t => {
+ const h=harness(t); await h.service.capture('a');
+ await h.service.sync('a','b'); assert.equal(h.writes.length,0);
+ const service=createSessionPinSync(h.options); h.setActive('c'); await service.flush('b');
+ assert.equal(h.writes.length,0); h.setActive('b'); await service.flush('b');
+ assert.deepEqual(h.pins.b,['b2','b1','b-own']);
+});
+test('same mapping is delivered once so a later manual unpin is respected', async t => {
+ const h=harness(t); await h.service.capture('a'); h.setActive('b'); await h.service.sync('a','b');
+ h.pins.b=['b-own']; await h.service.sync('a','b'); assert.deepEqual(h.pins.b,['b-own']);
+ assert.equal(h.writes.length,1);
+});
+test('empty source pins cancel pending work; unmapped and deleted target sessions are ignored', async t => {
+ const h=harness(t); await h.service.capture('a'); await h.service.sync('a','b');
+ h.pins.a=[]; await h.service.capture('a'); h.setActive('b'); await h.service.flush('b');
+ assert.deepEqual(h.pins.b,['b-own']); assert.equal(h.writes.length,0);
+});
+test('pins propagate through a rapid A to B to C chain even before B renderer loads', async t => {
+ const h=harness(t); await h.service.capture('a'); h.setActive('c');
+ await h.service.sync('a','b'); await h.service.sync('b','c');
+ assert.deepEqual(h.pins.c,['c2','c1']);
+});
+test('failed reads do not replace a known snapshot with an empty list', async t => {
+ const h=harness(t); await h.service.capture('a'); h.setActive('b'); await h.service.capture('a');
+ await h.service.sync('a','b'); assert.deepEqual(h.pins.b,['b2','b1','b-own']);
+});
+test('renderer uses official pin API and verifies account scope before every mutation', async () => {
+ let uid='a'; let pins=['own']; const calls=[];
+ const wb={account:{profile:async()=>({uid,type:'personal'})},conversations:{
+ listPinned:async()=>pins.map(id=>({id,groupKey:''})),
+ pin:async id=>{calls.push(id); pins.unshift(id);},
+ }};
+ const before=global.window; global.window={wb};
+ try {
+ assert.deepEqual(await readPinsInRenderer({uid:'a',type:'personal'}),['own']);
+ assert.equal(await readPinsInRenderer({uid:'b',type:'personal'}),null);
+ assert.equal(await applyPinsInRenderer({uid:'a',type:'personal'},['one','two']),true);
+ assert.deepEqual(pins,['one','two','own']);
+ wb.conversations.pin=async id=>{calls.push(id);uid='b';};
+ assert.equal(await applyPinsInRenderer({uid:'a',type:'personal'},['three','four']),false);
+ assert.equal(calls.includes('three'),false);
+ assert.equal(await applyPinsInRenderer({uid:'b',type:'ultimate',enterpriseId:'org'},['x']),false);
+ } finally {global.window=before;}
+});
+test('the obsolete reminder button is removed and pin synchronization is wired into switch and copy',()=>{
+ const inject=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');
+ const daemon=fs.readFileSync(path.join(__dirname,'../scripts/daemon.js'),'utf8');
+ assert.doesNotMatch(inject,/wbs-sess-remember|rememberedSessionsKey/);
+ assert.match(daemon,/await captureSessionPins\(\)/);
+ assert.match(daemon,/await syncSessionPins\(job.sourceUid, job.targetUid\)/);
+});
+
+test('daemon resolves real lineage mappings and rejects deleted, foreign or ambiguous target copies', async t => {
+ const vm=require('node:vm'); const h=harness(t);
+ const source=fs.readFileSync(path.join(__dirname,'../scripts/daemon.js'),'utf8');
+ const pins={a:['a2','a1'],b:['b-own']}; let account={uid:'a',rawUid:'a',type:'personal'}; let ambiguous=false, queries=0;
+ const wb={account:{profile:async()=>account},conversations:{
+ listPinned:async()=>pins[account.uid].map(id=>({id})),
+ pin:async id=>{pins[account.uid].unshift(id);},
+ }};
+ const ctx={createSessionPinSync,readPinsInRenderer,applyPinsInRenderer,path,
+ DATA_DIR:path.dirname(h.options.file),PROFILE:{kind:'workbuddy',id:'workbuddy-cn'},
+ cdp:{connected:true},accountSwitchInProgress:false,currentAccount:()=>account,
+ sessionAccountAmbiguous:()=>ambiguous,log(){},setTimeout,clearTimeout,
+ cdpSend:async(_,params)=>({result:{value:await vm.runInNewContext(params.expression,{window:{wb}})}}),
+ resolveAutoCopyTargetId:(_,__,id)=>({a1:'b1',a2:'foreign'}[id]||''),
+ isValidSessionId:id=>!!id,sqlPlaceholders:ids=>ids.map(()=>'?').join(','),
+ sqliteQuery:async()=>{ queries++; return [{id:'a1',user_id:'a'},{id:'a2',user_id:'a'},{id:'b1',user_id:'b'},{id:'foreign',user_id:'c'}]; },
+ };
+ vm.createContext(ctx); vm.runInContext(source.slice(source.indexOf('let sessionPinSync = null;'),source.indexOf('function resolveAutoCopyTargetId(')),ctx);
+ await ctx.captureSessionPins(); account={uid:'b',rawUid:'b',type:'personal'};
+ await ctx.syncSessionPins('a','b'); assert.deepEqual(pins.b,['b1','b-own']);
+ assert.deepEqual(pins.a,['a2','a1']);
+ const beforeQueries=queries; ambiguous=true; await ctx.syncSessionPins('a','b'); assert.equal(queries,beforeQueries);
+ const build=fs.readFileSync(path.join(__dirname,'../scripts/build-mac-dmg.sh'),'utf8');
+ assert.match(build,/session-pin-sync\.js/);
+});
+
+test('deleted mappings are rechecked before deferred delivery', async t => {
+ const h=harness(t); await h.service.capture('a'); await h.service.sync('a','b');
+ h.options.resolve=async()=>[]; const service=createSessionPinSync(h.options); h.setActive('b');
+ await service.flush('b'); assert.deepEqual(h.pins.b,['b-own']); assert.equal(h.writes.length,0);
+});
diff --git a/test/session-remembered.test.js b/test/session-remembered.test.js
deleted file mode 100644
index fd98a15..0000000
--- a/test/session-remembered.test.js
+++ /dev/null
@@ -1,32 +0,0 @@
-'use strict';
-const test = require('node:test');
-const assert = require('node:assert/strict');
-const fs = require('node:fs');
-const path = require('node:path');
-const vm = require('node:vm');
-
-const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
-const start = source.indexOf(' var rememberedSessionsKey =');
-const end = source.indexOf(' // 按空间分组渲染', start);
-
-test('remembered sessions persist by profile and account UID and can be removed', () => {
- const values = new Map();
- const context = vm.createContext({
- PROFILE_ID: 'workbuddy-cn',
- localStorage: {
- getItem: key => values.has(key) ? values.get(key) : null,
- setItem: (key, value) => values.set(key, value),
- },
- sessionsState: { uid: 'account-a', currentUid: 'account-a' },
- });
- vm.runInContext(source.slice(start, end), context);
- const sessionA = { id: 'session-1', user_id: 'account-a', title: 'Pinned task' };
- const sessionB = { id: 'session-1', user_id: 'account-b', title: 'Different task' };
-
- assert.equal(context.isSessionRemembered(sessionA), false);
- context.toggleRememberedSession(sessionA);
- assert.equal(context.isSessionRemembered(sessionA), true);
- assert.equal(context.isSessionRemembered(sessionB), false);
- context.toggleRememberedSession(sessionA);
- assert.equal(context.isSessionRemembered(sessionA), false);
-});
diff --git a/test/session-size-filter.test.js b/test/session-size-filter.test.js
index 5ef3ce4..a913b91 100644
--- a/test/session-size-filter.test.js
+++ b/test/session-size-filter.test.js
@@ -21,7 +21,6 @@ function harness() {
});
vm.runInContext([
section(' function filteredSessions()', ' // 按空间分组渲染'),
- section(' var rememberedSessionsKey =', ' // 按空间分组渲染'),
section(' function renderSessions()', ' function updateAutoCopyAllButton()'),
section(' function bindSessEvents(', ' function updateSessCount()'),
section(' function updateSessCount()', ' // 人性化时间'),
diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.js
index ffb3158..6fd4143 100644
--- a/test/session-sync-daemon.test.js
+++ b/test/session-sync-daemon.test.js
@@ -667,7 +667,7 @@ test('manual and automatic switching bypass session activity while retaining ope
test('mixed sync jobs continue after divergence and report every result', async () => {
const results = ['conflict', 'copied', 'skipped', 'error'];
let sizeReads = 0;
- const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ 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(); } },
@@ -699,7 +699,7 @@ test('mixed sync jobs continue after divergence and report every result', async
test('active session copy retries transient file races and preserves its target id', async () => {
let attempts = 0;
- const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
+ const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
DATA_DIR: 'fixture-data',
PROFILE: { dataRoot: 'fixture-root' },
@@ -726,7 +726,7 @@ test('active session copy retries transient file races and preserves its target
test('active session copy keeps waiting through a longer renderer flush', async () => {
let attempts = 0;
- const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
+ const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
@@ -753,7 +753,7 @@ test('active session copy keeps waiting through a longer renderer flush', async
test('unchanged requested session resolves its target without entering the copy worker', async () => {
let copies = 0;
- const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
+ const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
@@ -774,7 +774,7 @@ test('unchanged requested session resolves its target without entering the copy
for (const error of ['会话消息文件没有消息,未同步', '会话消息文件为空,未同步']) test('empty message sessions are skipped instead of shown as sync failures: ' + error, async () => {
let cleared = 0;
- const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
+ const ctx = { syncSessionPins: async () => {}, codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
@@ -799,7 +799,7 @@ for (const error of ['会话消息文件没有消息,未同步', '会话消息
test('an empty automatic copy plan does not wait for renderer injection', async () => {
const planningYields = [];
let rendererWaits = 0;
- const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ 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++;
@@ -820,7 +820,7 @@ test('an empty automatic copy plan does not wait for renderer injection', async
test('automatic session sync uses a bounded worker pool', async () => {
let running = 0;
let peak = 0;
- const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ 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++;
@@ -842,7 +842,7 @@ test('automatic session sync uses a bounded worker pool', async () => {
});
test('automatic session sync aggregates copied bytes independently across workers', async () => {
- const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ 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));
diff --git a/test/token-refresh-persistence.test.js b/test/token-refresh-persistence.test.js
index f47d433..eff7bf9 100644
--- a/test/token-refresh-persistence.test.js
+++ b/test/token-refresh-persistence.test.js
@@ -88,7 +88,7 @@ function daemonHarness(t, options = {}) {
? compat.wdCompatDecryptAuthJson(stored) : stored), { mode: 0o600 });
let requests = 0;
let failWrite = false;
- const context = { accountIdentity,
+ const context = { accountIdentity, captureSessionPins: async () => {},
...compat, fs: { ...fs, writeFileSync(...args) {
if (failWrite && String(args[0]).startsWith(file)) throw new Error('fixture write failure');
return fs.writeFileSync(...args);