WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
feat: consolidate 1.2.7 changes into main
[email protected]58ce4270aa26
diff --git a/scripts/credit-history-sync.js b/scripts/credit-history-sync.jsindex ba4761c..7dd1fd2 100644--- a/scripts/credit-history-sync.js+++ b/scripts/credit-history-sync.js@@ -5,6 +5,8 @@ const path = require('node:path');const { randomUUID } = require('node:crypto');const { fetchUsageSinceAnchor, startOfLocalDay } = require('./credit-request-usage.js');+const CREDIT_HISTORY_CACHE_VERSION = 2;+function dateString(date) {return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;}@@ -29,7 +31,7 @@ function createCreditHistorySync(options) {const key = (uid, date) => uid + ':' + date;try {const stored = JSON.parse(fs.readFileSync(options.cacheFile, 'utf8'));- if (stored.version === 1 && Array.isArray(stored.daily)) for (const row of stored.daily) {+ if (stored.version === CREDIT_HISTORY_CACHE_VERSION && Array.isArray(stored.daily)) for (const row of stored.daily) {if (typeof row.uid !== 'string' || !/^\d{4}-\d\d-\d\d$/.test(row.date) ||!Number.isFinite(row.used) || row.used < 0 || !Number.isSafeInteger(row.count) || row.count < 0 ||!Number.isFinite(row.queriedAt) || typeof row.final !== 'boolean') continue;@@ -42,7 +44,7 @@ function createCreditHistorySync(options) {const tmp = options.cacheFile + '.tmp';try {fs.mkdirSync(path.dirname(options.cacheFile), { recursive: true, mode: 0o700 });- fs.writeFileSync(tmp, JSON.stringify({ version: 1, daily: Array.from(cache.values()) }), { mode: 0o600 });+ fs.writeFileSync(tmp, JSON.stringify({ version: CREDIT_HISTORY_CACHE_VERSION, daily: Array.from(cache.values()) }), { mode: 0o600 });fs.renameSync(tmp, options.cacheFile);} catch (_) { /* In-memory results remain usable if disk is unavailable. */ }}diff --git a/scripts/credit-request-usage.js b/scripts/credit-request-usage.jsindex 16cd577..2dd43e3 100644--- a/scripts/credit-request-usage.js+++ b/scripts/credit-request-usage.js@@ -40,6 +40,27 @@ function safeText(value, maxLength = 200) {return String(value).replace(/\0/g, '').slice(0, maxLength);}+// The billing endpoint has returned model metadata in several shapes over+// time. Keep the model key readable and stable without persisting the raw+// upstream object.+function modelText(value, depth = 0) {+ if (typeof value === 'string' || typeof value === 'number') return safeText(value).trim();+ if (!value || typeof value !== 'object' || depth > 2) return '';+ for (const key of ['name', 'modelName', 'model_name', 'id', 'modelId', 'model_id', 'slug']) {+ const text = modelText(value[key], depth + 1);+ if (text) return text;+ }+ return '';+}++function usageModel(row) {+ for (const key of ['model', 'modelName', 'model_name', 'modelId', 'model_id', 'modelInfo', 'model_info']) {+ const text = modelText(row[key]);+ if (text) return text;+ }+ return '';+}+function normalizeUsageRow(row) {if (!row || typeof row !== 'object') throw new Error('用量记录不是对象');const requestId = safeText(row.requestId, 512).trim();@@ -53,7 +74,7 @@ function normalizeUsageRow(row) {requestTime,usageDate: localDateString(requestTime),credit,- model: safeText(row.model),+ model: usageModel(row),client: safeText(row.client),agentPurpose: safeText(row.agentPurpose),};@@ -196,6 +217,7 @@ module.exports = {fetchUsageSinceAnchor,formatLocalDateTime,normalizeUsageRow,+ usageModel,parseRequestTime,startOfLocalDay,};diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 6b6ccc7..84b0fbe 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -420,8 +420,8 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 1.2.145:识别仅 updated_at 的激活漂移,清除无变更脏标记;无结果任务不再弹同步进度窗口。// 1.2.126:5.6 加密账号改为密文原样备份、内存解密;导入兼容明文 token,// 刷新结果不把解密后的 token 写回加密备份。-const DAEMON_VERSION = '1.2.148';-const DAEMON_BUILD_ID = 'release-1.2.148-20260923-windows-compat-target';+const DAEMON_VERSION = '1.2.153';+const DAEMON_BUILD_ID = 'release-1.2.153-20260924-respect-active-session-sync-rule';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -5219,6 +5219,12 @@ function hasPendingAutoCopyTo(uid) {return false;}+function shouldStartAutoCopyJob(sourceRules, pendingToSource) {+ const rules = sourceRules || {};+ return !!(rules.allSessions || (Array.isArray(rules.sessionIds) && rules.sessionIds.length) ||+ (Array.isArray(rules.workspaces) && rules.workspaces.length) || pendingToSource);+}+function pruneAutoCopyJobs() {const completed = Array.from(autoCopyJobs.values()).filter((job) => job.status === 'done' || job.status === 'partial' || job.status === 'conflict' || job.status === 'error')@@ -8564,6 +8570,20 @@ function handleApi(req, res) {const u = String((body && body.url) || '');if (!/^https?:\/\//i.test(u)) return json(res, 400, { ok: false, error: '仅支持 http(s) 链接' });try {+ if (IS_LINUX) {+ return new Promise((resolve, reject) => {+ const child = spawn('xdg-open', [u], { detached: true, stdio: 'ignore' });+ // 不记录 URL:授权链接可能包含登录 state。缺少命令时也不能让 error 事件退出 daemon。+ child.once('error', reject);+ child.once('spawn', () => {+ child.unref();+ resolve();+ });+ }).then(+ () => json(res, 200, { ok: true }),+ () => json(res, 500, { ok: false, error: '无法启动系统浏览器,请确认已安装 xdg-utils' })+ );+ }if (IS_WIN) {spawn('rundll32', ['url.dll,FileProtocolHandler', u], { detached: true, stdio: 'ignore' }).unref();} else {@@ -9281,7 +9301,7 @@ function handleApi(req, res) {if (req.method === 'GET' && p === '/api/sleep-mode') {let st = { mode: 'allow', displaySleep: false };try { st = Object.assign(st, JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'sleep-mode.json'), 'utf8'))); } catch (_) {}- return json(res, 200, { ok: true, mode: st.mode, displaySleep: !!st.displaySleep, preventing: st.mode === 'keep' || st.mode === 'until-done', active: !!(IS_WIN ? sleepPowershell : sleepCaffeinate), antiLock: !!sleepUserActivityTimer });+ return json(res, 200, { ok: true, mode: st.mode, displaySleep: !!st.displaySleep, preventing: st.mode === 'keep' || st.mode === 'until-done', active: !!(IS_WIN ? sleepPowershell : IS_LINUX ? sleepInhibit : sleepCaffeinate), antiLock: !!sleepUserActivityTimer });}if (req.method === 'POST' && p === '/api/sleep-mode') {return readBody(req).then((body) => {@@ -10338,6 +10358,7 @@ function handleApi(req, res) {releaseAccountSwitch = await assertAccountSwitchIdle();const sourceAccount = currentAccount() || {};const sourceUid = String(sourceAccount.uid || '').trim();+ let currentConversationRow = null;let currentConversationId = isValidSessionId(String(body.currentConversationId || '').trim())? String(body.currentConversationId).trim() : '';// Renderer projection state can briefly retain the destination id from@@ -10345,12 +10366,14 @@ function handleApi(req, res) {// the session index proves it belongs to the account being replaced.if (currentConversationId && sourceUid) {const ownerRows = await sqliteQuery(- 'SELECT user_id FROM sessions WHERE id = ? AND deleted_at IS NULL LIMIT 1;',+ 'SELECT user_id, cwd FROM sessions WHERE id = ? AND deleted_at IS NULL LIMIT 1;',[currentConversationId]);if (!ownerRows.length || String(ownerRows[0].user_id || '') !== sourceUid) {log(`[switch] 丢弃不属于源账号的当前会话 source=${sourceUid} session=${currentConversationId}`);currentConversationId = '';+ } else {+ currentConversationRow = { ...ownerRows[0], id: currentConversationId };}}const acct = switchTo(DATA_DIR, uid, log);@@ -10383,12 +10406,15 @@ function handleApi(req, res) {// 空间规则可能因切换前后的会话索引时序暂时无法生成初始计划,但规则本身仍需触发复制任务;// 任务规则通常能直接命中,所以旧逻辑只表现为“任务能复制、空间不复制”。const sourceRules = sourceUid ? getAutoCopyRules(DATA_DIR, sourceUid) : { allSessions: false, sessionIds: [], workspaces: [] };- const hasSourceAutoCopyRules = !!(sourceRules.allSessions || sourceRules.sessionIds.length || sourceRules.workspaces.length);- const autoCopyJob = (hasSourceAutoCopyRules || hasPendingAutoCopyTo(sourceUid) || currentConversationId)+ // An unrelated workspace rule may start a job, but must never opt the+ // open conversation into copying. Use the planner's exact selection rule.+ const autoCopyOpenSessionId = currentConversationRow && isAutoCopySessionSelected(sourceRules, currentConversationRow)+ ? currentConversationId : '';+ const autoCopyJob = shouldStartAutoCopyJob(sourceRules, hasPendingAutoCopyTo(sourceUid))? startAutoCopyJob(sourceUid, uid, [], {sourceName: sourceAccount.nickname || '',targetName: acct.nickname || '',- openSessionId: currentConversationId,+ openSessionId: autoCopyOpenSessionId,}): null;return json(res, 200, {@@ -10412,14 +10438,22 @@ function handleApi(req, res) {}-// ===== 电脑休眠控制(三模式:allow/keep/until-done + 显示器开关 + 立即休眠 pmset sleepnow)=====+// ===== 电脑休眠控制(三模式:allow/keep/until-done + 显示器开关 + 立即休眠)=====// mode: 'allow' 允许电脑休眠(默认)| 'keep' 持续禁止休眠 | 'until-done' 所有任务结束后允许休眠// displaySleep: 禁止休眠时是否允许显示器休眠(默认 false = 显示器也保持唤醒)let sleepCaffeinate = null;let sleepUserActivity = null; // 防锁屏:caffeinate -u -t 300(UserIsActive 断言,阻止屏保启动/空闲锁屏)let sleepUserActivityTimer = null; // -u 断言每 240s 续期一次(-t 300 超时前续期,保持无间隙)let sleepPowershell = null; // Windows: 常驻 powershell 进程持有 SetThreadExecutionState+let sleepInhibit = null; // Linux: systemd-inhibit 持有 sleep/idle inhibitorfunction stopCaffeinate() {+ if (IS_LINUX) {+ const c = sleepInhibit;+ sleepInhibit = null;+ // detached 子进程独占进程组;同时结束 inhibitor 和 sleep,避免遗留后台进程。+ if (c && c.pid) { try { process.kill(-c.pid, 'SIGTERM'); } catch (_) {} }+ return;+ }if (IS_WIN) {const c = sleepPowershell;sleepPowershell = null; // 先置 null 再 kill,避免 exit 回调把旧引用覆盖@@ -10441,7 +10475,7 @@ function stopUserActivity() {// 系统认为用户一直在操作,屏保与空闲锁屏便不会触发;每 240s 重启一个 -t 300 的断言实现无间隙续期。// 无需辅助功能权限(-u 走系统 IOKit 用户活动断言)。function startUserActivityLoop() {- if (IS_WIN) return; // Windows 无 caffeinate -u 等价;防锁屏由系统电源策略控制+ if (IS_WIN || IS_LINUX) return; // 防锁屏由系统/桌面策略控制,不运行 macOS 用户活动断言stopUserActivity();const tick = () => {if (!sleepCaffeinate) return; // 防休眠已停止(allow 模式),不再续期@@ -10456,6 +10490,17 @@ function startUserActivityLoop() {if (sleepUserActivityTimer.unref) sleepUserActivityTimer.unref();}function startCaffeinate(displaySleep) {+ if (IS_LINUX) {+ // logind 的 idle inhibitor 不保证阻止 Wayland 锁屏;不接管合盖策略。+ const child = spawn('systemd-inhibit', [+ '--what=' + (displaySleep ? 'sleep' : 'sleep:idle'), '--mode=block',+ '--who=WorkDaddy', '--why=WorkDaddy 正在运行任务', 'sleep', 'infinity',+ ], { detached: true, stdio: 'ignore' });+ child.on('error', (e) => { log('[sleep] systemd-inhibit 启动失败: ' + e.message); if (sleepInhibit === child) sleepInhibit = null; });+ child.on('exit', () => { if (sleepInhibit === child) sleepInhibit = null; });+ sleepInhibit = child;+ return child;+ }if (IS_WIN) {// Windows:常驻 powershell 循环调用 SetThreadExecutionState。// 0x80000000 ES_CONTINUOUS | 0x1 ES_SYSTEM_REQUIRED | 0x2 ES_DISPLAY_REQUIRED@@ -10478,12 +10523,12 @@ function startCaffeinate(displaySleep) {function applySleepMode(mode, displaySleep) {const preventing = mode === 'keep' || mode === 'until-done';if (preventing) {- if (IS_WIN) {- // Windows:powershell 持有进程参数固定,无法比较 spawnargs,直接重启(低频操作,代价可接受)+ if (IS_WIN || IS_LINUX) {+ // 平台持有进程直接重启(低频操作),同步更新显示器休眠策略。stopCaffeinate();try {startCaffeinate(!!displaySleep);- log('[sleep] 禁止休眠已开启(Windows,模式=' + mode + (displaySleep ? ',允许显示器休眠' : ',显示器保持唤醒') + ')');+ log('[sleep] 禁止休眠已开启(' + (IS_LINUX ? 'Linux,systemd-inhibit' : 'Windows') + ',模式=' + mode + (displaySleep ? ',允许显示器休眠' : IS_LINUX ? ',请求阻止空闲休眠' : ',显示器保持唤醒') + ')');} catch (e) { log('[sleep] 开启失败: ' + e.message); return false; }return true;}@@ -10498,7 +10543,7 @@ function applySleepMode(mode, displaySleep) {log('[sleep] 禁止休眠已开启(模式=' + mode + (displaySleep ? ',允许显示器休眠,防锁屏关闭' : ',显示器保持唤醒,防锁屏开启') + ')');} catch (e) { log('[sleep] 开启失败: ' + e.message); return false; }} else {- if (!sleepCaffeinate && !sleepPowershell && !sleepUserActivityTimer) return true;+ if (!sleepCaffeinate && !sleepPowershell && !sleepInhibit && !sleepUserActivityTimer) return true;stopCaffeinate();log('[sleep] 禁止休眠已解除(允许电脑休眠)');}@@ -10506,6 +10551,12 @@ function applySleepMode(mode, displaySleep) {}function sleepNow() {try {+ if (IS_LINUX) {+ const c = spawn('systemctl', ['suspend'], { stdio: 'ignore' });+ c.on('error', (e) => log('[sleep] 立即休眠失败: ' + e.message));+ c.on('exit', (code) => log(code === 0 ? '[sleep] 已请求立即休眠(systemctl suspend)' : '[sleep] systemctl suspend 失败,退出码=' + code));+ return true;+ }if (IS_WIN) {// Windows:SetSuspendState(Hibernate=0, ForceCritical=0, DisableWakeEvent=0) → 睡眠const c = spawn('rundll32.exe', ['powrprof.dll,SetSuspendState', '0,1,0'], { stdio: 'ignore', windowsHide: true });diff --git a/scripts/inject.js b/scripts/inject.jsindex f949a70..0db2ecd 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -97,6 +97,57 @@ function collectConversationUsage(messages) {};}+// 将官方消息 store 中的用户/助手消息还原成可直接粘贴的 Markdown。+// 消息列表可能被虚拟化,复制必须依赖完整 store,而不是当前 DOM 中的节点。+function conversationMessagesToMarkdown(messages) {+ var source = Array.isArray(messages) ? messages : [];+ function roleOf(message) {+ var role = String(message && (message.messageType || message.role || message.type) || '').toLowerCase();+ if (role === 'user' || role.indexOf('user') >= 0) return 'user';+ if (role === 'assistant' || role.indexOf('assistant') >= 0) return 'assistant';+ return '';+ }+ function blocksToMarkdown(content) {+ var parts = [];+ function visit(value) {+ if (typeof value === 'string') {+ parts.push(value);+ return;+ }+ if (Array.isArray(value)) {+ for (var i = 0; i < value.length; i++) visit(value[i]);+ return;+ }+ if (!value || typeof value !== 'object') return;+ var type = String(value.type || '').toLowerCase();+ if (typeof value.text === 'string' && (!type || type === 'text' || type === 'markdown')) {+ parts.push(value.text);+ return;+ }+ if (typeof value.content === 'string') {+ parts.push(value.content);+ return;+ }+ if (value.content) visit(value.content);+ else if (value.children) visit(value.children);+ }+ visit(content);+ return parts.join('\n');+ }+ var turns = [];+ for (var i = 0; i < source.length; i++) {+ var message = source[i];+ var role = roleOf(message);+ if (!role || /^timeline:/.test(String(message && message.id || ''))) continue;+ var markdown = blocksToMarkdown(message && message.content);+ if (!markdown) continue;+ // WorkDaddy 的完成标记是内部 Markdown 定义,不属于用户看到的回复正文。+ if (role === 'assistant') markdown = markdown.replace(/\n?\[wbs-reply-done\]:\s*#\s*$/, '');+ turns.push((role === 'user' ? '用户' : '助手') + ':\n\n' + markdown);+ }+ return turns.join('\n\n---\n\n');+}+// Activity signals contain no key, text, target or pointer coordinates.function createUsageActivity(options) {var doc = options.document, win = options.window;@@ -861,6 +912,7 @@ function findLatestManualAutomationRun(tasks, runs) {if (typeof module !== 'undefined' && module.exports) {module.exports = {collectConversationUsage: collectConversationUsage,+ conversationMessagesToMarkdown: conversationMessagesToMarkdown,createUsageActivity: createUsageActivity,createBuildLifecycle: createBuildLifecycle,createBrandClickAction: createBrandClickAction,@@ -1094,7 +1146,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {"已关闭首页活动弹窗": "Home activity popup closed.","Token 用量仅统计本机记录,在不同电脑上查看的数据可能不一致。": "Token usage only includes records on this computer. Figures may differ between computers.","会话输入框非空,未覆盖草稿、未发送": "The composer contains a draft. Nothing was overwritten or sent.",- '页面就绪': 'Page ready', '删除选中的': 'Delete selected', '删除该自动化任务?': 'Delete this automation task?', '删除选中的自动化任务?': 'Delete selected automation tasks?', '删除后无法恢复。': 'This cannot be undone.', '清除': 'Clear', '清除日志': 'Clear logs', '清除运行日志?': 'Clear run logs?', '仅清除已结束的运行记录。': 'Only completed run records will be cleared.', '清除日志失败': 'Failed to clear logs', '任务已启用': 'Task enabled', '任务已停用': 'Task disabled', '发送中': 'Sending',+ '页面就绪': 'Page ready', '删除选中的': 'Delete selected', '删除中…': 'Deleting…', '删除该自动化任务?': 'Delete this automation task?', '删除选中的自动化任务?': 'Delete selected automation tasks?', '删除后无法恢复。': 'This cannot be undone.', '清除': 'Clear', '清除日志': 'Clear logs', '清除运行日志?': 'Clear run logs?', '仅清除已结束的运行记录。': 'Only completed run records will be cleared.', '清除日志失败': 'Failed to clear logs', '任务已启用': 'Task enabled', '任务已停用': 'Task disabled', '发送中': 'Sending','成长计划读取中': 'Growth plan is loading', '成长计划暂不可用': 'Growth plan is unavailable','Buddy 今日旅行已完成': 'Buddy finished traveling today', 'Buddy 旅行中': 'Buddy is traveling', 'Buddy 待领取礼物': 'Buddy gift pending', 'Buddy 已归来,待领奖': 'Buddy returned; reward pending', 'Buddy 在家': 'Buddy is home', 'Buddy 尚未解锁': 'Buddy is not unlocked','成长任务': 'Growth tasks', '状态暂不可用': 'Status unavailable', '暂不可用': 'Unavailable', '今日旅行已完成': "Today's travel is complete", '旅行中,预计': 'Traveling, expected ', ' 归来': ' return', '旅行中': 'Traveling', '即将归来': 'Returning soon',@@ -1193,7 +1245,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// —— 第二批补齐(inject 剩余 + daemon 端会进入 UI/API 的文案)——'没有找到符合格式的账号,请先让 WorkBuddy 整理 JSON': 'No compatible accounts found. Ask WorkBuddy to format the JSON first.','免打扰': 'Quiet mode', 'WorkBuddy 即将退出并重新打开到登录页': 'WorkBuddy will exit and reopen to the login page', 'WorkBuddy 队列尚未准备完成': 'WorkBuddy queue is not ready yet', 'WorkBuddy 队列排序接口不可用': 'WorkBuddy queue sort API unavailable', 'WorkBuddy 队列立即发送接口不可用': 'WorkBuddy queue send-now API unavailable', '未找到 WorkBuddy 队列接口': 'WorkBuddy queue API not found',- '一个基于': 'A ', '个备选': 'standby', '备选': 'standby', '个失败': ' failed', '个已不存在': ' no longer exist', '项失败': ' failed', '已选': ' selected', '例如 deepseek-v4-flash': 'e.g. deepseek-v4-flash', '例如我的 DeepSeek': 'e.g. my DeepSeek', '加载失败': 'Load failed', '发起授权失败:': 'Authorization failed:', '开启': 'Enable', '关闭': 'Close', '失败': 'Failed', '用户消息': 'User message',+ '一个基于': 'A ', '个备选': 'standby', '备选': 'standby', '个失败': ' failed', '个已不存在': ' no longer exist', '项失败': ' failed', '已选': ' selected', '例如 deepseek-v4-flash': 'e.g. deepseek-v4-flash', '例如我的 DeepSeek': 'e.g. my DeepSeek', '加载失败': 'Load failed', '发起授权失败:': 'Authorization failed:', '开启': 'Enable', '关闭': 'Close', '失败': 'Failed', '用户消息': 'User message', '用户': 'User', '助手': 'Assistant', '复制整个会话': 'Copy entire conversation', '当前会话暂无可复制内容': 'No copyable content in the current conversation', '会话已复制到剪贴板': 'Conversation copied to clipboard', '剪贴板不可用': 'Clipboard unavailable','OLED 纯黑': 'OLED Pure Black', '未发现 CDP 端口(WorkBuddy 需以 --remote-debugging-port 启动)': 'No CDP port found (start WorkBuddy with --remote-debugging-port)', '本地 API 未授权': 'Local API unauthorized', '仅支持 http(s) 链接': 'Only http(s) links are supported', '图片不能超过 10MB': 'Image must not exceed 10MB', '图片必须是 PNG/JPEG/WebP base64': 'Image must be PNG/JPEG/WebP base64', '遥测开关值必须是布尔值': 'Telemetry switch must be a boolean', 'blur 必须是数字': 'Blur must be a number', 'opacity 必须是数字': 'Opacity must be a number', '查询返回空结果': 'Query returned empty results','正在解包新应用…': 'Unpacking new app…', '挂载 dmg 失败:': 'Failed to mount dmg:', '缺少解包后的新应用': 'Unpacked new app missing', '解包应用失败': 'Failed to unpack app', '缺少 apply-update.sh': 'apply-update.sh missing', '(仓库暂无 Release)': ' (no Releases in the repository yet)', 'auth/state 响应缺少 state': 'auth/state response is missing state','WBSWITCH_WORKBUDDY_BIN 不是可验证的当前 profile 主程序;登录信息未修改': 'WBSWITCH_WORKBUDDY_BIN is not a verified main program for the current profile; login info unchanged', '无法以普通用户权限安全退出 WorkBuddy。请手动关闭该程序;若它以管理员身份运行,请先退出后再重试。登录信息未修改': 'Cannot safely quit WorkBuddy at standard user privilege. Please close it manually; if it runs as admin, quit it first and retry. Login info unchanged', '未找到 WorkBuddy 可执行文件,无法安全退出;登录信息未修改': 'WorkBuddy executable not found; cannot quit safely. Login info unchanged', 'workbuddy-target.json 指定的路径不是可验证的当前 profile 主程序;登录信息未修改': 'The path in workbuddy-target.json is not a verified main program for the current profile; login info unchanged', '存在当前 profile 进程,但没有进程属于已验证安装目录;登录信息未修改': 'A current profile process exists, but none belongs to a verified install directory; login info unchanged', '检测到当前 profile 正从另一安装目录运行,登录信息未修改': 'The current profile is running from another install directory; login info unchanged', '检测到多个 dormant WorkBuddy 安装目录,按发现优先级选择:': 'Multiple dormant WorkBuddy installs found; selecting by discovery priority:', 'WorkBuddy 数据目录不是受管目录': 'WorkBuddy data directory is not managed', 'WorkBuddy 页面尚未完成加载': 'WorkBuddy page has not finished loading', '刷新 WorkBuddy 页面': 'Refresh WorkBuddy page', '注入脚本页面抛错': 'Injected script page threw an error', '读取注入脚本失败:': 'Failed to read the injected script:', '运行时桥接文件未生成': 'Runtime bridge file was not created',@@ -2189,6 +2241,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {popoverTimer: null,observer: null,state: null,+ messages: null,// 性能缓存:避免 800ms 轮询反复全量扫描/强制布局ctrlCacheId: null,ctrlCache: null,@@ -2334,6 +2387,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!summary || !surface || !conversationUsageEnabled) return;var contentRect = surface.content.getBoundingClientRect();if (!contentRect || contentRect.width <= 0) return;+ var documentRect = surface.conversation && surface.conversation.getBoundingClientRect ? surface.conversation.getBoundingClientRect() : null;// 元素引用缓存(断连才重新 querySelector)var geo = conversationUsage.geoEls;if (!geo || !geo.inputArea || !document.contains(geo.inputArea) || (geo.bottomMask && !document.contains(geo.bottomMask)) || (geo.viewport && !document.contains(geo.viewport))) {@@ -2349,13 +2403,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var maskRect = geo.bottomMask && geo.bottomMask.getBoundingClientRect();var anchorRect = maskRect && maskRect.width > 0 && maskRect.height > 0 ? maskRect : inputRect;var anchorBottom = anchorRect && anchorRect.bottom > 0 ? anchorRect.bottom : (viewportRect && viewportRect.bottom) || window.innerHeight;- var left = anchorRect && anchorRect.width > 0 ? anchorRect.left : contentRect.left;- var maxWidth = anchorRect && anchorRect.width > 0 ? anchorRect.width : contentRect.width;+ // 水平基准使用真实消息文档,避免跟随外层 message-list-content 的内缩留白。+ var alignmentRect = documentRect && documentRect.width > 0 ? documentRect : contentRect;+ var left = alignmentRect.left;+ var maxWidth = alignmentRect.width;left = Math.max(8, left);var write = {left: Math.round(left),maxWidth: Math.round(Math.min(maxWidth, window.innerWidth - left - 8)),- bottom: Math.round(Math.max(0, window.innerHeight - anchorBottom)),+ // 与底部保留少量间距,避免组件紧贴输入区/窗口边缘。+ bottom: Math.round(Math.max(4, window.innerHeight - anchorBottom + 4)),};var last = conversationUsage.lastWrite;// 几何未变化时跳过样式写入,避免每次都触发 style invalidation@@ -2380,7 +2437,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {write.spacerH = sh2;}}- function showUsagePopover() {+ function showUsagePopover(event) {+ var copyButton = conversationUsage.summary && conversationUsage.summary.querySelector('.wbs-session-usage-copy');+ // The copy action has its own expanded state; never let the usage tooltip+ // reappear while the pointer or keyboard focus is on that control.+ if (copyButton && (copyButton.matches(':hover') || copyButton.matches(':focus'))) {+ hideUsagePopover();+ return;+ }+ if (event && event.target && event.target.closest && event.target.closest('.wbs-session-usage-copy')) {+ hideUsagePopover();+ return;+ }if (!conversationUsage.summary || !conversationUsage.popover) return;if (conversationUsage.popoverTimer) clearTimeout(conversationUsage.popoverTimer);conversationUsage.popover.classList.add('is-visible');@@ -2395,6 +2463,52 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {hideUsagePopover();}, 120);}+ function writeConversationClipboard(text) {+ var clipboard = window.navigator && window.navigator.clipboard;+ if (clipboard && typeof clipboard.writeText === 'function') return clipboard.writeText(text);+ return new Promise(function (resolve, reject) {+ var area = document.createElement('textarea');+ area.value = text;+ area.setAttribute('readonly', '');+ area.style.position = 'fixed';+ area.style.left = '-9999px';+ area.style.top = '0';+ document.body.appendChild(area);+ area.select();+ var copied = false;+ try { copied = document.execCommand('copy'); } catch (_) { copied = false; }+ area.remove();+ if (copied) resolve();+ else reject(new Error('剪贴板不可用'));+ });+ }+ function copyConversation(button) {+ var state = null;+ try {+ if (conversationUsage.controller && conversationUsage.controller.messageStore) {+ state = conversationUsage.controller.messageStore.getState();+ }+ } catch (_) {}+ if (!state) state = conversationUsage.state;+ var messages = state && Array.isArray(state.messages) && state.messages.length ? state.messages : conversationUsage.messages;+ var text = conversationMessagesToMarkdown(messages);+ if (!text) {+ toast('当前会话暂无可复制内容', true);+ return;+ }+ button.disabled = true;+ writeConversationClipboard(text).then(function () {+ button.classList.add('is-copied');+ toast('会话已复制到剪贴板', false, null, 'success');+ setBuildTimeout(function () {+ button.disabled = false;+ button.classList.remove('is-copied');+ }, 1400);+ }).catch(function (error) {+ button.disabled = false;+ toast('复制失败: ' + (error && error.message ? error.message : '剪贴板不可用'), true);+ });+ }function usageDetailRows(state) {var models = (state && state.models || []).slice().sort(function (a, b) { return b.tokens - a.tokens; });if (!models.length) return [el('div', 'wbs-session-usage-empty', wbsTranslateString('暂无已完成用量', WBS_LANGUAGE))];@@ -2424,13 +2538,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {body.textContent = '';var calls = state && state.calls || 0;if (!state) {- main.appendChild(el('span', 'wbs-session-usage-label', '会话用量'));+ main.appendChild(el('span', 'wbs-session-usage-label', '共'));main.appendChild(el('span', 'wbs-session-usage-loading', '读取中…'));} else if (!calls) {- main.appendChild(el('span', 'wbs-session-usage-label', '会话用量'));+ main.appendChild(el('span', 'wbs-session-usage-label', '共'));main.appendChild(el('span', 'wbs-session-usage-loading', '暂无已完成用量'));} else {- main.appendChild(el('span', 'wbs-session-usage-label', '会话用量'));+ main.appendChild(el('span', 'wbs-session-usage-label', '共'));main.appendChild(el('span', 'wbs-session-usage-number', formatUsageTokens(state.tokens) + ' Token'));main.appendChild(el('span', 'wbs-session-usage-separator', '·'));main.appendChild(el('span', 'wbs-session-usage-number', formatUsageCredit(state.credit, state.creditKnown) + ' 积分'));@@ -2457,7 +2571,25 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {summary.setAttribute('aria-label', '本会话用量');summary.setAttribute('aria-describedby', 'wbs-session-usage-popover');summary.appendChild(el('div', 'wbs-session-usage-main'));+ var copyButton = el('button', 'wbs-session-usage-copy');+ copyButton.type = 'button';+ copyButton.title = '复制整个会话';+ copyButton.setAttribute('aria-label', '复制整个会话');+ copyButton.innerHTML = '<span class="wbs-session-usage-copy-icon" aria-hidden="true"><svg class="wbs-session-usage-copy-glyph" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="wbs-session-usage-check-glyph" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m5 12 4 4L19 6"/></svg></span>';+ copyButton.appendChild(el('span', 'wbs-session-usage-copy-label', '复制整个会话'));+ summary.appendChild(copyButton);conversationUsage.summary = summary;+ listen(copyButton, 'mouseenter', hideUsagePopover);+ listen(copyButton, 'focusin', hideUsagePopover);+ listen(copyButton, 'mouseleave', function (event) {+ var next = event.relatedTarget;+ if (next && summary.contains(next) && !(next.closest && next.closest('.wbs-session-usage-copy'))) showUsagePopover();+ });+ listen(copyButton, 'click', function (event) {+ event.preventDefault();+ event.stopPropagation();+ copyConversation(copyButton);+ });listen(summary, 'mouseenter', showUsagePopover);listen(summary, 'mouseleave', scheduleHideUsagePopover);listen(summary, 'focusin', showUsagePopover);@@ -2506,6 +2638,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {(usage.total_tokens != null ? usage.total_tokens : (usage.totalTokens != null ? usage.totalTokens : ''));}function maybeRenderUsage(messages) {+ conversationUsage.messages = Array.isArray(messages) ? messages : [];var sig = usageSignature(messages);if (sig === conversationUsage.lastSig) return;conversationUsage.lastSig = sig;@@ -2525,6 +2658,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {conversationUsage.unsubscribe = null;}conversationUsage.controller = controller || null;+ conversationUsage.messages = null;conversationUsage.lastSig = '';renderConversationUsage(null);if (!controller || !controller.messageStore) return;@@ -2614,9 +2748,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var toastRuntime = window.__wbsToastRuntime;if (!toastRuntime) throw new Error('通知组件未加载');registerDisposer(function () { toastRuntime.destroy(); });- function toast(msg, isErr, targetRoot) {+ function toast(msg, isErr, targetRoot, level) {if (!alive) return;- return toastRuntime.show({ message: wbsTranslateString(String(msg == null ? '' : msg), WBS_LANGUAGE), level: isErr ? 'error' : 'info' });+ return toastRuntime.show({ message: wbsTranslateString(String(msg == null ? '' : msg), WBS_LANGUAGE), level: level || (isErr ? 'error' : 'info') });}function receiveToast(detail) {if (!alive) throw new Error('通知组件已关闭');@@ -6322,6 +6456,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function usageTrendGroups(days, records, dimension, names) {var groups = new Map();(records || []).forEach(function (row) {+ // Credit trends share account-total and model-detail records. A row+ // without the active dimension belongs to the other view and must not+ // become a synthetic "未识别模型"/"未关联账号" group.+ if (!Object.prototype.hasOwnProperty.call(row, dimension)) return;var key = String(row[dimension] || '');var group = groups.get(key);if (!group) {@@ -8266,6 +8404,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}pending = true;okBtn.disabled = true;+ var pendingLabel = okBtn.textContent;+ okBtn.textContent = '删除中…';+ okBtn.classList.add('is-loading');+ okBtn.setAttribute('aria-busy', 'true');api('/api/sessions/delete', {method: 'POST',headers: { 'content-type': 'application/json' },@@ -8279,7 +8421,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {toast('删除失败: ' + (e.message || e), true, root);}).finally(function () {pending = false;- if (okBtn.onclick === submit) okBtn.disabled = false;+ if (okBtn.onclick === submit) {+ okBtn.disabled = false;+ okBtn.textContent = pendingLabel;+ okBtn.classList.remove('is-loading');+ okBtn.removeAttribute('aria-busy');+ }});};okBtn.onclick = submit;@@ -15115,12 +15262,25 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-root{position:fixed;right:22px;bottom:22px;z-index:2147483647;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;font-size:13px;color:#1f1f1f;-webkit-font-smoothing:antialiased}','.wbs-root,.wbs-status-popover,.wbs-credit-summary-popover,#wbs-token-stats-modal{--wbs-primary:#22c55e;--wbs-primary-rgb:34,197,94;--wbs-primary-ink:#22c55e;--wbs-primary-soft:rgba(34,197,94,.09);--wbs-primary-soft-hover:rgba(34,197,94,.14)}','html[data-wbs-theme-id="dark"] .wbs-root,html[data-wbs-theme-id="dark"] .wbs-status-popover,html[data-wbs-theme-id="dark"] .wbs-credit-summary-popover,html[data-wbs-theme-id="dark"] #wbs-token-stats-modal,html[data-wbs-theme-id="cyber-purple"] .wbs-root,html[data-wbs-theme-id="cyber-purple"] .wbs-status-popover,html[data-wbs-theme-id="cyber-purple"] .wbs-credit-summary-popover,html[data-wbs-theme-id="cyber-purple"] #wbs-token-stats-modal,html[data-wbs-theme-id="nebula"] .wbs-root,html[data-wbs-theme-id="nebula"] .wbs-status-popover,html[data-wbs-theme-id="nebula"] .wbs-credit-summary-popover,html[data-wbs-theme-id="nebula"] #wbs-token-stats-modal{--wbs-primary:#7f77dd;--wbs-primary-rgb:127,119,221;--wbs-primary-ink:#7f77dd;--wbs-primary-soft:rgba(127,119,221,.12);--wbs-primary-soft-hover:rgba(127,119,221,.18)}',- '.wbs-session-usage-summary{position:fixed;z-index:20;display:block;box-sizing:border-box;min-height:28px;padding:4px 8px 2px;border:0;border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 52%,transparent);color:var(--wb-color-text-primary,#1f1f1f);font-size:13px;font-weight:400;line-height:1.35;opacity:.72;box-shadow:none;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);outline:none;cursor:pointer;transition:opacity .15s ease}',- '.wbs-session-usage-summary:hover,.wbs-session-usage-summary:focus-visible{opacity:.96}',+ '.wbs-session-usage-summary{position:fixed;z-index:20;display:flex;align-items:center;justify-content:flex-start;gap:10px;box-sizing:border-box;min-height:37px;padding:3px 0 2px;border:0;border-radius:0;background:transparent;color:var(--wb-color-text-primary,#1f1f1f);font-size:14px;font-weight:400;line-height:18px;outline:none;cursor:pointer}',+ '.wbs-session-usage-summary:hover,.wbs-session-usage-summary:focus-visible{background:transparent}','.wbs-session-usage-summary.is-hidden{visibility:hidden;opacity:0;pointer-events:none}',- '.wbs-session-usage-main{display:flex;align-items:center;justify-content:flex-start;gap:7px;min-width:0;overflow:hidden;text-align:left;white-space:nowrap}',+ '.wbs-session-usage-main{display:flex;align-items:center;justify-content:flex-start;gap:9px;min-width:0;flex:0 1 auto;overflow:hidden;text-overflow:ellipsis;text-align:left;white-space:nowrap;color:var(--wb-color-text-secondary,#68686d);opacity:1}',+ '.wbs-session-usage-copy{display:inline-flex;align-items:center;justify-content:flex-start;gap:6px;width:auto;min-width:34px;height:30px;box-sizing:border-box;overflow:hidden;padding:0 9px;border:0;border-radius:0;background:transparent;color:var(--wb-color-text-primary,#1d1d1f);font:inherit;font-size:11px;line-height:1;cursor:pointer;box-shadow:none;transition:border-radius .2s ease,background .15s ease,box-shadow .15s ease;white-space:nowrap}',+ '.wbs-session-usage-copy:hover,.wbs-session-usage-copy:focus-visible{border-radius:999px;background:var(--wb-bg-hover,#f2f2f7);color:var(--wb-color-text-primary,#1d1d1f);box-shadow:0 2px 8px rgba(0,0,0,.12)}',+ '.wbs-session-usage-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:28px;flex:0 0 16px}',+ '.wbs-session-usage-copy-icon svg{display:block;width:16px;height:16px;flex:0 0 16px}',+ '.wbs-session-usage-copy-glyph{opacity:1;transition:opacity .12s ease,transform .18s ease}',+ '.wbs-session-usage-copy-icon .wbs-session-usage-check-glyph{display:none;opacity:0;transform:scale(.55)}',+ '.wbs-session-usage-copy-label{display:block;box-sizing:border-box;width:auto;max-width:0;overflow:hidden;padding:0;opacity:0;text-align:left;font-size:12px;font-weight:500;transition:max-width .2s ease,opacity .15s ease}',+ '.wbs-session-usage-copy:hover .wbs-session-usage-copy-label,.wbs-session-usage-copy:focus-visible .wbs-session-usage-copy-label{max-width:72px;opacity:1}',+ '.wbs-session-usage-copy:focus-visible{outline:2px solid color-mix(in srgb,var(--wb-color-text-primary,#1f1f1f) 50%,transparent);outline-offset:2px}',+ '.wbs-session-usage-copy:disabled{opacity:.58;cursor:wait}',+ '.wbs-session-usage-copy.is-copied .wbs-session-usage-copy-glyph{display:none}.wbs-session-usage-copy.is-copied .wbs-session-usage-check-glyph{display:block;opacity:1;transform:scale(1);animation:wbs-session-copy-check .24s ease-out}.wbs-session-usage-copy.is-copied .wbs-session-usage-check-glyph path{stroke-dasharray:24;stroke-dashoffset:24;animation:wbs-session-copy-check-draw .3s ease-out .02s forwards}.wbs-session-usage-copy.is-copied{color:var(--wb-color-text-primary,#1f1f1f)}',+ '@keyframes wbs-session-copy-check{from{opacity:0;transform:scale(.55)}to{opacity:1;transform:scale(1)}}',+ '@keyframes wbs-session-copy-check-draw{from{stroke-dashoffset:24}to{stroke-dashoffset:0}}','.wbs-session-usage-label{flex:0 0 auto;color:var(--wb-color-text-secondary,#5f6368);font-weight:400}',- '.wbs-session-usage-number{flex:0 0 auto;color:var(--wb-color-text-primary,#1f1f1f);font-variant-numeric:tabular-nums;font-weight:400}',+ '.wbs-session-usage-number{flex:0 0 auto;color:var(--wb-color-text-primary,#1d1d1f);font-variant-numeric:tabular-nums;font-weight:500}','.wbs-session-usage-separator{flex:0 0 auto;color:var(--wb-icon-tertiary,#969aa3)}','.wbs-session-usage-models{min-width:0;overflow:hidden;color:var(--wb-color-text-secondary,#5f6368);text-overflow:ellipsis;white-space:nowrap}','.wbs-session-usage-loading{color:var(--wb-icon-secondary,#667085);font-weight:400}',@@ -15138,9 +15298,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-session-usage-model{min-width:0;overflow:hidden;color:var(--wb-color-text-primary,#1f1f1f);text-overflow:ellipsis;white-space:nowrap}','.wbs-session-usage-empty{padding:10px 0;color:var(--wb-color-text-secondary,#5f6368);font-size:12px}','.wbs-session-usage-spacer{display:block;width:100%;height:28px;min-height:28px;pointer-events:none;visibility:hidden}',- 'html.cb-dark .wbs-session-usage-summary,html[data-theme="dark"] .wbs-session-usage-summary,body[data-vscode-theme-name*="dark" i] .wbs-session-usage-summary{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 80%,transparent);color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 5px 18px rgba(0,0,0,.2)}',+ 'html.cb-dark .wbs-session-usage-summary,html[data-theme="dark"] .wbs-session-usage-summary,body[data-vscode-theme-name*="dark" i] .wbs-session-usage-summary{background:transparent;color:var(--wb-color-text-primary,#f2f3f5)}html.cb-dark .wbs-session-usage-main,html[data-theme="dark"] .wbs-session-usage-main,body[data-vscode-theme-name*="dark" i] .wbs-session-usage-main{color:var(--wb-color-text-secondary,#b7bbc5)}html.cb-dark .wbs-session-usage-copy,html[data-theme="dark"] .wbs-session-usage-copy,body[data-vscode-theme-name*="dark" i] .wbs-session-usage-copy{border:0;background:transparent;color:var(--wb-color-text-primary,#f2f3f5);box-shadow:none}html.cb-dark .wbs-session-usage-copy:hover,html[data-theme="dark"] .wbs-session-usage-copy:hover,body[data-vscode-theme-name*="dark" i] .wbs-session-usage-copy:hover{background:var(--wb-bg-hover,#34363b);color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 2px 8px rgba(0,0,0,.25)}','html.cb-dark .wbs-session-usage-popover,html[data-theme="dark"] .wbs-session-usage-popover,body[data-vscode-theme-name*="dark" i] .wbs-session-usage-popover{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 92%,transparent);color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 8px 22px rgba(0,0,0,.32)}',- '@media(max-width:620px){.wbs-session-usage-summary{padding-left:8px;padding-right:8px}.wbs-session-usage-main{gap:5px}.wbs-session-usage-popover{width:calc(100vw - 16px)}}',+ 'html[data-wbs-theme-id="nebula"] .wbs-session-usage-copy:hover,html[data-wbs-theme-id="nebula"] .wbs-session-usage-copy:focus-visible{background:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 88%,transparent);color:var(--wb-color-text-primary,#e8e5ff);box-shadow:0 3px 12px rgba(0,0,0,.32);backdrop-filter:blur(12px) saturate(1.12);-webkit-backdrop-filter:blur(12px) saturate(1.12)}',+ '@media(max-width:620px){.wbs-session-usage-summary{padding-left:0;padding-right:0}.wbs-session-usage-main{gap:9px}.wbs-session-usage-popover{width:calc(100vw - 16px)}}','.wbs-daily-rings,.wbs-status-popover{--wbs-ring-growth:var(--wbs-primary-ink);--wbs-ring-rewards:var(--wbs-primary-ink);--wbs-ring-cat:var(--wbs-primary-ink);--wbs-tip-credit:var(--wbs-primary-ink);--wbs-liquid-fill:var(--wbs-primary);--wbs-liquid-bg:color-mix(in srgb,var(--wbs-primary) 12%,var(--wb-bg-secondary,#f6f7f8));--wbs-liquid-ink:color-mix(in srgb,var(--wbs-primary-ink) 72%,var(--wb-color-text-primary,#1f1f1f))}','.wbs-root.wbs-no-stash .wbs-stash-inline{display:none !important}','.wbs-fork-button{display:flex;flex:0 0 24px;align-items:center;justify-content:center;width:24px;height:24px;box-sizing:border-box;padding:0;border:0;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,rgba(0,0,0,.7));cursor:pointer;transition:color .15s ease,background-color .15s ease}',@@ -15248,7 +15409,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-fab.is-dragging .button{cursor:grabbing}','.wbs-fab.is-snapping{transition:right .56s cubic-bezier(.22,1.35,.36,1),bottom .56s cubic-bezier(.22,1.35,.36,1)}',/* 面板:毛玻璃主题(半透明 + 模糊,背景图透出) */- '.wbs-panel{position:absolute;right:0;bottom:0;width:720px;max-width:94vw;height:650px;max-height:650px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden;backdrop-filter:blur(28px) saturate(1.25);-webkit-backdrop-filter:blur(28px) saturate(1.25)}',+ '.wbs-panel{position:absolute;right:0;bottom:0;width:720px;max-width:94vw;height:650px;max-height:calc(100vh - 110px);background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden;backdrop-filter:blur(28px) saturate(1.25);-webkit-backdrop-filter:blur(28px) saturate(1.25)}','.wbs-panel.show{display:flex}',// 英文文案更长:英文面板额外加宽,配合 label 自适应避免挤压'html[data-wbs-language="en"] .wbs-panel{width:880px}',@@ -15270,7 +15431,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {/* 元素检查拾取按钮(隐藏入口,连点标题 5 次显示) */'.wbs-pick-btn{flex:0 0 auto;width:22px;height:22px;border:none;border-radius:7px;background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 14%,transparent);color:var(--wb-accent-blue,#4f86ff);font-size:12px;line-height:1;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:background .15s}','.wbs-pick-btn:hover{background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 24%,transparent)}',- '.wbs-btn-close{border:none;background:none;color:var(--wb-icon-tertiary,#999);font-size:16px;cursor:pointer;padding:4px 6px;border-radius:6px;line-height:1}',+ '.wbs-btn-close{position:relative;z-index:1;border:none;background:none;color:var(--wb-icon-tertiary,#999);font-size:16px;cursor:pointer;padding:4px 6px;border-radius:6px;line-height:1}','.wbs-btn-close:hover{color:var(--wb-color-text-primary,#1f1f1f);background:var(--wb-bg-hover,#f5f5f5)}','.wbs-body{overflow-y:auto;padding:10px 10px 6px;flex:1;min-height:0;height:calc(650px - 170px);max-height:none}',/* 账号卡片:头像 + 信息 + 右侧操作 */@@ -15443,11 +15604,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-explore-inline.wbs-menu-closed .wbs-explore-pop{opacity:0;visibility:hidden;pointer-events:none;transform:translateX(-50%) translateY(6px)}',/* 弹窗卡片:适配插件主题的毛玻璃;面板整体为默认箭头,仅选项 hover 变点击手型 */'.wbs-explore-card{position:relative;padding:8px;border-radius:12px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 62%,transparent);backdrop-filter:blur(18px) saturate(1.3);-webkit-backdrop-filter:blur(18px) saturate(1.3);border:1px solid var(--wb-border-subtle,#ececec);box-shadow:0 12px 32px rgba(0,0,0,.18);color:var(--wb-color-text-primary,#1f1f1f);cursor:default}',+ 'html[data-wbs-theme-id="nebula"] .wbs-explore-card{background:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 88%,transparent);background-color:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 88%,transparent);box-shadow:0 14px 36px rgba(0,0,0,.38)}','.wbs-explore-item{position:relative;display:flex;align-items:center;gap:8px;padding:9px 10px;border-radius:8px;font-size:12px;color:var(--wb-color-text-primary,#1f1f1f);line-height:1.4;cursor:pointer}','.wbs-explore-it{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}','.wbs-explore-item:hover{background:color-mix(in srgb,var(--wb-bg-hover,#f3f3f3) 76%,transparent)}',/* 选项 hover:antd 风格 tooltip(半透明毛玻璃小气泡,出现在选项左侧,完全展示文字) */'.wbs-explore-tip{position:absolute;right:calc(100% + 10px);top:50%;transform:translateY(-50%);display:block;width:max-content;padding:5px 11px;border-radius:8px;font-size:11px;line-height:1.35;white-space:normal;word-break:break-word;max-width:240px;color:var(--wb-color-text-primary,#1f1f1f);background:var(--wb-bg-popover,#fff);border:1px solid color-mix(in srgb,var(--wb-border-subtle,#ececec) 65%,transparent);box-shadow:0 6px 20px rgba(0,0,0,.16);opacity:0;visibility:hidden;transition:opacity .15s ease;pointer-events:none;z-index:2}',+ 'html[data-wbs-theme-id="nebula"] .wbs-explore-tip{background:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 94%,transparent);background-color:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 94%,transparent);border-color:var(--wb-border-strong,#3a3160);box-shadow:0 8px 24px rgba(0,0,0,.4);backdrop-filter:blur(14px) saturate(1.12);-webkit-backdrop-filter:blur(14px) saturate(1.12)}',/* 滚动条默认透明,滚动/悬停时才出现(内容多时可上下滚动,内容少完全展示无滚动条) */'.wbs-explore-tip-body{display:block;max-height:240px;overflow-y:auto;scrollbar-width:thin;scrollbar-color:transparent transparent;white-space:normal;word-break:break-word}','.wbs-explore-tip-body::-webkit-scrollbar{width:6px}',@@ -15788,6 +15951,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-modal-btn:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);border-color:var(--wb-border-strong,#bbb)}','.wbs-modal-btn.wbs-modal-ok{color:#fff;background:#141416;border-color:#141416}','.wbs-modal-btn.wbs-modal-ok:hover{background:#2a2a2e;color:#fff}',+ '.wbs-modal-btn.is-loading{display:inline-flex;align-items:center;justify-content:center;gap:6px;cursor:wait}',+ '.wbs-modal-btn.is-loading::before{content:"";width:11px;height:11px;box-sizing:border-box;border:1.5px solid currentColor;border-top-color:transparent;border-radius:50%;animation:wbs-modal-btn-spin .72s linear infinite}',+ '@keyframes wbs-modal-btn-spin{to{transform:rotate(360deg)}}',/* 免打扰确认弹窗:红字确认按钮(高危操作,用红色警示) */'.wbs-modal-btn.wbs-modal-danger{color:#fff;background:#c62828;border-color:#c62828}','.wbs-modal-btn.wbs-modal-danger:hover{background:#b71c1c}',diff --git a/scripts/theme-patches.js b/scripts/theme-patches.jsindex 1e3dbf0..908b8d3 100644--- a/scripts/theme-patches.js+++ b/scripts/theme-patches.js@@ -490,6 +490,24 @@ module.exports = [desc: '毛玻璃消息正文文字阴影(默认开启,可在主题面板关闭),不影响输入框或侧栏',css: 'body[data-vscode-theme-name] .conversation-timeline .cr-document,body[data-vscode-theme-name] .conversation-timeline .cr-document *{text-shadow:0 1px 2px rgba(0,0,0,.65),0 0 6px rgba(0,0,0,.3) !important;}',},+ {+ id: 'patch-102',+ themeId: 'nebula',+ desc: '最新版 mac teams 布局:滚动容器与内部 gridView 的不透明底色会盖住毛玻璃背景,改为透明并移除自身模糊层',+ css: ':is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container.is-mac>.teams-grid-scroll-content,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container.is-mac>.teams-grid-scroll-content>[class*="_grid_"]>[class*="_gridView_"],body[data-vscode-theme-name="IDE Night"] .teams-container.is-mac>.teams-grid-scroll-content,body[data-vscode-theme-name="IDE Night"] .teams-container.is-mac>.teams-grid-scroll-content>[class*="_grid_"]>[class*="_gridView_"]{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',+ },+ {+ id: 'patch-103',+ themeId: 'nebula',+ desc: '毛玻璃主题下新版 mac teams 主页与会话页发送按钮 tooltip 包装层去掉背景色,避免输入框右侧出现多余色块',+ css: ':is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container.is-mac .cr-input-toolbar__send>span.cr-send-button__tooltip-wrapper,body[data-vscode-theme-name="IDE Night"] .teams-container.is-mac .cr-input-toolbar__send>span.cr-send-button__tooltip-wrapper{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',+ },+ {+ id: 'patch-104',+ themeId: 'nebula',+ desc: '毛玻璃主题下左侧模板切换按钮与代码块复制提示去掉官方背景色,避免出现实心色块',+ css: ':is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container.is-mac .industry-template-switcher__host>button.wb-button.wb-button--secondary,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container.is-mac .industry-template-switcher__host>button.wb-button.wb-button--secondary:hover,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container.is-mac .industry-template-switcher__host>button.wb-button.wb-button--secondary:focus-visible,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container.is-mac .industry-template-switcher__host>button.wb-button.wb-button--secondary:active,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .cr-code-like-box__header>span.cr-code-block__copy-tooltip,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .cr-code-like-box__header>span.cr-code-block__copy-tooltip:hover,body[data-vscode-theme-name="IDE Night"] .teams-container.is-mac .industry-template-switcher__host>button.wb-button.wb-button--secondary,body[data-vscode-theme-name="IDE Night"] .teams-container.is-mac .industry-template-switcher__host>button.wb-button.wb-button--secondary:hover,body[data-vscode-theme-name="IDE Night"] .teams-container.is-mac .industry-template-switcher__host>button.wb-button.wb-button--secondary:focus-visible,body[data-vscode-theme-name="IDE Night"] .teams-container.is-mac .industry-template-switcher__host>button.wb-button.wb-button--secondary:active,body[data-vscode-theme-name="IDE Night"] .cr-code-like-box__header>span.cr-code-block__copy-tooltip,body[data-vscode-theme-name="IDE Night"] .cr-code-like-box__header>span.cr-code-block__copy-tooltip:hover{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;box-shadow:none !important;}',+ },/* 原 patch-82(AI 端快捷短语弹层 z-index 抬升)已移入 inject.js 常驻样式:theme-patches 仅在非默认主题时注入,默认浅色主题下会失效;层级修复不依赖主题,随注入脚本常驻更可靠。 */];diff --git a/test/account-switch-session-rules.test.js b/test/account-switch-session-rules.test.jsnew file mode 100644index 0000000..c6b0779--- /dev/null+++ b/test/account-switch-session-rules.test.js@@ -0,0 +1,82 @@+'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 lib = require('../scripts/lib');+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');++function harness(rules, owner = 'source') {+ const jobs = [], events = [];+ const ctx = vm.createContext({+ DATA_DIR: 'fixture', log() {}, isAutoCopySessionSelected: lib.isAutoCopySessionSelected,+ isValidSessionId: id => !!id,+ readBody: async req => req.body,+ json: (_, status, body) => ({ status, body }),+ beginRendererReloadPriority: () => () => events.push('release-reload'),+ assertAccountSwitchIdle: async () => () => events.push('release-switch'),+ currentAccount: () => ({ uid: 'source' }),+ sqliteQuery: async () => owner ? [{ user_id: owner, cwd: '/current-workspace' }] : [],+ switchTo: (_, uid) => { events.push('switch'); return { uid }; },+ reloadWorkBuddyPage: async () => { events.push('reload'); },+ mainFrameNavigationSerial: 1, setTimeout() {},+ getAutoCopyRules: () => rules,+ hasPendingAutoCopyTo: () => false,+ startAutoCopyJob: (from, to, plan, labels) => {+ events.push('job');+ jobs.push({ from, to, ...labels });+ return { id: 'job', total: 0, openSessionId: labels.openSessionId };+ },+ });+ const helperStart = source.indexOf('function shouldStartAutoCopyJob(');+ vm.runInContext(source.slice(helperStart, source.indexOf('\nfunction pruneAutoCopyJobs', helperStart)), ctx);+ const routeStart = source.indexOf(" if (req.method === 'POST' && p === '/api/switch')");+ const routeEnd = source.indexOf('\n return json(res, 404', routeStart);+ vm.runInContext('async function switchRoute(req, res) { const p = "/api/switch";\n' + source.slice(routeStart, routeEnd) + '\n}', ctx);+ return { jobs, events, run: () => ctx.switchRoute({ method: 'POST', body: { uid: 'target', reload: true, currentConversationId: 'open' } }, {}) };+}++test('switch route reloads without syncing when no rule is enabled', async () => {+ const h = harness({ allSessions: false, sessionIds: [], workspaces: [] });+ const result = await h.run();+ assert.equal(result.status, 200);+ assert.equal(result.body.reloaded, true);+ assert.equal(h.jobs.length, 0);+ assert.deepEqual(h.events, ['switch', 'reload', 'release-reload', 'release-switch']);+});++for (const rules of [+ { allSessions: false, sessionIds: [], workspaces: ['/unrelated-workspace'] },+ { allSessions: false, sessionIds: ['another-session'], workspaces: [] },+]) {+ test('switch route never adds an unselected open conversation to another rule’s job: ' + JSON.stringify(rules), async () => {+ const h = harness(rules);+ const result = await h.run();+ assert.equal(result.status, 200);+ assert.equal(h.jobs.length, 1, 'the other rule still has its normal sync job');+ assert.equal(h.jobs[0].openSessionId, '', 'an unselected open conversation must not become a forced planner request');+ assert.equal(result.body.autoCopy.openSessionId, '');+ assert.ok(h.events.indexOf('reload') < h.events.indexOf('job'));+ });+}++for (const rules of [+ { allSessions: true, sessionIds: [], workspaces: [] },+ { allSessions: false, sessionIds: ['open'], workspaces: [] },+ { allSessions: false, sessionIds: [], workspaces: ['/current-workspace/'] },+]) {+ test('switch route preserves restoration for a selected open conversation: ' + JSON.stringify(rules), async () => {+ const h = harness(rules);+ assert.equal((await h.run()).status, 200);+ assert.equal(h.jobs[0].openSessionId, 'open');+ });+}++for (const owner of ['', 'other-account']) {+ test('switch route never carries a missing or foreign conversation: ' + owner, async () => {+ const h = harness({ allSessions: true, sessionIds: [], workspaces: [] }, owner);+ assert.equal((await h.run()).status, 200);+ assert.equal(h.jobs[0].openSessionId, '');+ });+}diff --git a/test/conversation-usage.test.js b/test/conversation-usage.test.jsindex b41fb72..9e9fec7 100644--- a/test/conversation-usage.test.js+++ b/test/conversation-usage.test.js@@ -5,7 +5,18 @@ const fs = require('node:fs');const path = require('node:path');const test = require('node:test');-const { collectConversationUsage } = require('../scripts/inject.js');+const { collectConversationUsage, conversationMessagesToMarkdown } = require('../scripts/inject.js');++test('conversation copy preserves complete user and assistant Markdown from the message store', () => {+ const markdown = conversationMessagesToMarkdown([+ { id: 'timeline:initial', messageType: 'assistant', content: [{ type: 'text', text: 'hidden' }] },+ { id: 'u-1', messageType: 'user', content: [{ type: 'text', text: '# 需求\n\n请保留 **Markdown**。'}] },+ { id: 'a-1', messageType: 'assistant', content: [{ type: 'markdown', text: '```js\nconst answer = true;\n```\n[wbs-reply-done]: #' }] },+ { id: 'u-2', role: 'user', content: '继续。' },+ { id: 'a-2', role: 'assistant', content: [{ type: 'text', text: '第二次回复' }] },+ ]);+ assert.equal(markdown, '用户:\n\n# 需求\n\n请保留 **Markdown**。\n\n---\n\n助手:\n\n```js\nconst answer = true;\n```\n\n---\n\n用户:\n\n继续。\n\n---\n\n助手:\n\n第二次回复');+});test('conversation usage keeps only terminal messages and groups credits by model', () => {const result = collectConversationUsage([@@ -52,12 +63,14 @@ test('conversation usage UI uses a body-fixed mount, bottom spacer and message sassert.doesNotMatch(source, /悬浮查看明细|Hover for details/);assert.doesNotMatch(source, /el\('strong', 'wbs-session-usage/);assert.match(source, /wbs-session-usage-popover\{[^}]*background:color-mix/);+ assert.match(source, /html\[data-wbs-theme-id="nebula"\] \.wbs-session-usage-copy:hover,[^}]*\.wbs-session-usage-copy:focus-visible\{[^}]*background:color-mix\(in srgb,var\(--wb-bg-popover,/);assert.match(source, /wbs-session-usage-summary\{[^}]*z-index:20/);assert.match(source, /wbs-session-usage-popover\{[^}]*z-index:21/);- assert.match(source, /wbs-session-usage-summary\{[^}]*border:0/);+ assert.match(source, /wbs-session-usage-summary\{[^}]*border:0[^}]*background:transparent/);assert.match(source, /wbs-session-usage-summary\{[^}]*cursor:pointer/);assert.match(source, /wbs-session-usage-detail-title\{[^}]*font-weight:700/);- assert.match(source, /wbs-session-usage-summary\{[^}]*font-size:13px[^}]*opacity:\.72/);+ assert.match(source, /wbs-session-usage-summary\{[^}]*font-size:14px[^}]*line-height:18px/);+ assert.match(source, /wbs-session-usage-summary\{[^}]*background:transparent/);assert.match(source, /wbs-session-usage-detail-title\{[^}]*font-size:14px/);assert.match(source, /wbs-session-usage-detail-title-row\{[^}]*display:flex[^}]*align-items:center[^}]*justify-content:space-between/);assert.match(source, /detailTitleRow\.appendChild\(el\('div', 'wbs-session-usage-detail-total'/);@@ -76,6 +89,29 @@ test('conversation usage UI uses a body-fixed mount, bottom spacer and message sassert.match(source, /window\.innerHeight - anchorBottom/);assert.match(source, /positionConversationUsage\(\);[\s\S]{0,120}updateConversationUsageScrollState\(\)/);assert.match(source, /wbs-session-usage-summary\.is-hidden/);+ assert.match(source, /wbs-session-usage-label', '共'/);+ assert.match(source, /wbs-session-usage-copy/);+ assert.match(source, /复制整个会话/);+ assert.match(source, /event\.target\.closest\('\.wbs-session-usage-copy'\)/);+ assert.match(source, /listen\(copyButton, 'mouseenter', hideUsagePopover\)/);+ assert.match(source, /wbs-session-usage-copy-icon/);+ assert.match(source, /wbs-session-usage-copy\{[^}]*gap:6px[^}]*width:auto[^}]*min-width:34px[^}]*height:30px[^}]*padding:0 9px[^}]*border-radius:0[^}]*background:transparent[^}]*box-shadow:none/);+ assert.match(source, /wbs-session-usage-copy-label\{[^}]*width:auto[^}]*max-width:0[^}]*padding:0[^}]*text-align:left/);+ assert.match(source, /wbs-session-usage-copy:hover \.wbs-session-usage-copy-label[^']*max-width:72px/);+ assert.match(source, /wbs-session-usage-main\{[^}]*gap:9px[^}]*flex:0 1 auto/);+ assert.match(source, /wbs-session-usage-copy-icon svg\{[^}]*width:16px[^}]*height:16px[^}]*flex:0 0 16px/);+ assert.match(source, /wbs-session-usage-copy-icon \.wbs-session-usage-check-glyph\{[^}]*display:none/);+ assert.match(source, /wbs-session-usage-copy-icon\{[^}]*width:16px[^}]*flex:0 0 16px/);+ assert.doesNotMatch(source, /wbs-session-usage-copy-icon\{[^}]*transform:/);+ assert.match(source, /wbs-session-usage-check-glyph/);+ assert.match(source, /toast\('会话已复制到剪贴板', false, null, 'success'\)/);+ assert.doesNotMatch(source, /label\.textContent = '已复制'/);+ assert.match(source, /conversationMessagesToMarkdown/);+ assert.match(source, /messageStore\.getState\(\)/);+ assert.match(source, /surface\.conversation\.getBoundingClientRect/);+ assert.match(source, /alignmentRect = documentRect/);+ assert.match(source, /Math\.max\(4, window\.innerHeight - anchorBottom \+ 4\)/);+ assert.match(source, /var\(--wb-accent-blue/);assert.doesNotMatch(source, /conversation-finished-footer[\s\S]{0,120}usage/);});diff --git a/test/credit-history-sync.test.js b/test/credit-history-sync.test.jsindex 964afca..dbb2de6 100644--- a/test/credit-history-sync.test.js+++ b/test/credit-history-sync.test.js@@ -1,5 +1,8 @@'use strict';const test = require('node:test');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');const assert = require('node:assert/strict');const { createCreditHistorySync, historyRange } = require('../scripts/credit-history-sync.js');const { fetchUsageSinceAnchor } = require('../scripts/credit-request-usage.js');@@ -89,6 +92,24 @@ test('historical credit results retain model totals when the official usage rows});});+test('legacy cache without model details is refreshed after model normalization changes', async t => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-credit-model-cache-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const cacheFile = path.join(dir, 'cache.json');+ fs.writeFileSync(cacheFile, JSON.stringify({ version: 1, daily: [{+ uid: 'one', date: '2026-09-12', used: 1, count: 1, queriedAt: now.getTime(), final: true,+ }] }));+ let calls = 0;+ const sync = createCreditHistorySync({ cacheFile, now: () => now, getAccessToken: async () => 'test', fetchUsage: async () => {+ calls++;+ return { records: [{ usageDate: '2026-09-12', credit: 1, requestId: 'new', model: 'Recovered model' }] };+ } });+ sync.start({ accounts: [{ uid: 'one' }], days: 1 });+ const result = await settle(sync);+ assert.equal(calls, 1);+ assert.deepEqual(result.daily[0].models, { 'Recovered model': { used: 1, count: 1 } });+});+test('failed account contributes no cached values or false zero records', async () => {const sync = createCreditHistorySync({ now: () => now, getAccessToken: async uid => uid,fetchUsage: async o => { if (o.accessToken === 'bad') throw Error('timeout'); return { records: [] }; }diff --git a/test/credit-request-usage.test.js b/test/credit-request-usage.test.jsindex 237f72a..da66cc4 100644--- a/test/credit-request-usage.test.js+++ b/test/credit-request-usage.test.js@@ -47,6 +47,15 @@ test('normalizes only non-sensitive fields from official usage records', () => {assert.equal(Object.prototype.hasOwnProperty.call(row, 'inputTrunc'), false);});+test('normalizes model aliases returned by billing API variants', () => {+ const byName = normalizeUsageRow({ ...usageRow('req-name', '2026-08-28 09:10:11'), model: '', modelName: 'claude-3-7-sonnet' });+ const byId = normalizeUsageRow({ ...usageRow('req-id', '2026-08-28 09:10:10'), model: '', model_id: 'deepseek-v3.1' });+ const nested = normalizeUsageRow({ ...usageRow('req-nested', '2026-08-28 09:10:09'), model: { id: 'gemini-2.5-pro', name: 'Gemini 2.5 Pro' } });+ assert.equal(byName.model, 'claude-3-7-sonnet');+ assert.equal(byId.model, 'deepseek-v3.1');+ assert.equal(nested.model, 'Gemini 2.5 Pro');+});+test('requests official pages newest-first and stops at the previous complete-sync anchor', async () => {const calls = [];const firstPage = Array.from({ length: 100 }, (_, index) =>diff --git a/test/open-url.test.js b/test/open-url.test.jsnew file mode 100644index 0000000..5dbfcfc--- /dev/null+++ b/test/open-url.test.js@@ -0,0 +1,63 @@+'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 { EventEmitter } = require('node:events');+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+const route = source.slice(source.indexOf(" if (req.method === 'POST' && p === '/api/open-url')"), source.indexOf(" if (req.method === 'GET' && p === '/api/status')"));++async function openUrl(platform, url, failure) {+ const calls = [];+ const context = {+ IS_WIN: platform === 'win32', IS_LINUX: platform === 'linux',+ req: { method: 'POST' }, p: '/api/open-url', res: {},+ readBody: async () => ({ url }),+ json: (_res, status, body) => ({ status, ...body }),+ spawn(command, args, options) {+ const child = new EventEmitter();+ child.unref = () => { child.unreferenced = true; };+ calls.push({ command, args: Array.from(args), options, child });+ queueMicrotask(() => {+ if (failure) child.emit('error', Object.assign(new Error('missing opener'), { code: 'ENOENT' }));+ else child.emit('spawn');+ });+ return child;+ },+ };+ const result = await vm.runInNewContext('(function(){' + route + '})()', context);+ return { calls, result };+}++test('open-url uses the platform opener and passes the URL as one unchanged argument', async () => {+ const url = 'https://example.invalid/login?state=a%2Bb&next=%2F';+ for (const [platform, command, args] of [+ ['linux', 'xdg-open', [url]], ['darwin', 'open', [url]],+ ['win32', 'rundll32', ['url.dll,FileProtocolHandler', url]],+ ]) {+ const { calls, result } = await openUrl(platform, url);+ assert.equal(result.status, 200);+ assert.equal(result.ok, true);+ assert.equal(calls.length, 1);+ assert.equal(calls[0].command, command);+ assert.deepEqual(calls[0].args, args);+ assert.equal(calls[0].options.shell, undefined);+ assert.equal(calls[0].child.unreferenced, true);+ }+});++test('open-url rejects non-HTTP URLs before spawning an opener', async () => {+ for (const url of ['file:///tmp/test', 'javascript:alert(1)', '']) {+ const { calls, result } = await openUrl('linux', url);+ assert.equal(result.status, 400);+ assert.equal(calls.length, 0);+ }+});++test('Linux missing xdg-open returns an error without leaking the URL or an unhandled event', async () => {+ const { result } = await openUrl('linux', 'https://example.invalid/?state=private-fixture', true);+ assert.equal(result.status, 500);+ assert.equal(result.ok, false);+ assert.doesNotMatch(result.error, /private-fixture/);+});diff --git a/test/session-delete-ui.test.js b/test/session-delete-ui.test.jsindex 77fa479..4e9f1e3 100644--- a/test/session-delete-ui.test.js+++ b/test/session-delete-ui.test.js@@ -6,7 +6,16 @@ const vm = require('node:vm');const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');function harness() {const requests = [], nodes = {};- for (const id of ['title', 'body', 'ok', 'cancel']) nodes['#wbs-sess-modal-' + id] = { textContent: '', focus() {}, disabled: false };+ for (const id of ['title', 'body', 'ok', 'cancel']) {+ const classes = new Set(), attrs = {};+ nodes['#wbs-sess-modal-' + id] = {+ textContent: '', focus() {}, disabled: false,+ classList: { add: name => classes.add(name), remove: name => classes.delete(name), contains: name => classes.has(name) },+ setAttribute: (name, value) => { attrs[name] = String(value); },+ getAttribute: name => attrs[name] || null,+ removeAttribute: name => { delete attrs[name]; },+ };+ }const ctx = vm.createContext({sessionsPane: { querySelector: id => nodes[id] },sessionsState: {}, root: {}, toast() {}, loadSessions() {},@@ -28,6 +37,10 @@ test('all-account deletion requires two confirmations and freezes the selected Iassert.match(h.nodes['#wbs-sess-modal-title'].textContent, /再次确认/);h.ok.onclick(); h.ok.onclick();assert.equal(h.requests.length, 1, 'ignore duplicate submission');+ assert.equal(h.ok.disabled, true, 'delete button is disabled while the request is pending');+ assert.equal(h.ok.classList.contains('is-loading'), true, 'delete button shows loading while the request is pending');+ assert.equal(h.ok.getAttribute('aria-busy'), 'true');+ assert.equal(h.ok.textContent, '删除中…');assert.equal(h.requests[0].route, '/api/sessions/delete');assert.deepEqual(JSON.parse(h.requests[0].options.body).ids, ['selected-session']);h.requests[0].resolve({ deleted: 3, cascaded: 2 });@@ -48,6 +61,9 @@ test('existing deletion retains its single confirmation and errors permit retry'h.requests[0].reject(Error('locked'));await new Promise(resolve => setImmediate(resolve));assert.equal(h.ok.disabled, false);+ assert.equal(h.ok.classList.contains('is-loading'), false);+ assert.equal(h.ok.getAttribute('aria-busy'), null);+ assert.equal(h.ok.textContent, '确定');assert.equal(h.ctx.open, true);h.ok.onclick(); assert.equal(h.requests.length, 2);});diff --git a/test/sleep-mode.test.js b/test/sleep-mode.test.jsindex 6103f9e..c26bfda 100644--- a/test/sleep-mode.test.js+++ b/test/sleep-mode.test.js@@ -5,12 +5,13 @@ const fs = require('node:fs');const vm = require('node:vm');const { EventEmitter } = require('node:events');const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/daemon.js'), 'utf8');-function harness(windows = false) {- const children = [], timers = new Set();- const ctx = { IS_WIN: windows, log() {},- spawn(command, args) {+function harness(windows = false, linux = false) {+ const children = [], timers = new Set(), signals = [];+ const ctx = { IS_WIN: windows, IS_LINUX: linux, log() {},+ process: { kill(pid, signal) { signals.push({ pid, signal }); } },+ spawn(command, args, options) {const child = new EventEmitter();- Object.assign(child, { spawnargs: [command, ...args], killed: false,+ Object.assign(child, { pid: 1000 + children.length, options, spawnargs: [command, ...args], killed: false,kill() { this.killed = true; this.emit('exit'); },});children.push(child);@@ -20,8 +21,15 @@ function harness(windows = false) {clearInterval(timer) { timers.delete(timer); },};vm.createContext(ctx);- vm.runInContext(source.slice(source.indexOf('let sleepCaffeinate ='), source.indexOf('function sleepNow()')), ctx);- return { ctx, children, timers };+ vm.runInContext(source.slice(source.indexOf('let sleepCaffeinate ='), source.indexOf('function restoreSleepMode()')), ctx);+ const statusBlock = source.slice(source.indexOf(" if (req.method === 'GET' && p === '/api/sleep-mode')"), source.indexOf(" if (req.method === 'POST' && p === '/api/sleep-mode')"));+ Object.assign(ctx, {+ req: { method: 'GET' }, p: '/api/sleep-mode', res: {}, DATA_DIR: '',+ fs: { readFileSync: () => '{"mode":"keep"}' }, path: { join: () => '' },+ json: (_res, _status, body) => body,+ });+ const status = () => vm.runInContext('(function(){' + statusBlock + '})()', ctx);+ return { ctx, children, timers, signals, status };}test('Windows allow releases the exact keep-awake process', () => {const h = harness(true);@@ -48,10 +56,52 @@ test('macOS unchanged mode reuses assertions; display sleep removes display and});test('sleep status reports the Windows power process as active', () => {- const block = source.slice(source.indexOf(" if (req.method === 'GET' && p === '/api/sleep-mode')"), source.indexOf(" if (req.method === 'POST' && p === '/api/sleep-mode')"));- const readStatus = new Function('req', 'p', 'fs', 'path', 'DATA_DIR', 'res', 'json', 'IS_WIN', 'sleepPowershell', 'sleepCaffeinate', 'sleepUserActivityTimer', block);- const result = readStatus({method:'GET'}, '/api/sleep-mode', {readFileSync:()=>'{"mode":"keep"}'}, {join:()=>''}, '', {}, (res, code, body)=>body, true, {}, null, null);- assert.equal(result.active, true);+ const h = harness(true);+ h.ctx.applySleepMode('keep', false);+ assert.equal(h.status().active, true);+});++test('Linux keep/until-done uses an inhibitor and allow releases its entire process group', () => {+ const h = harness(false, true);+ assert(h.ctx.applySleepMode('keep', false));+ const first = h.children[0];+ assert.equal(first.spawnargs[0], 'systemd-inhibit');+ assert(first.spawnargs.includes('--what=sleep:idle'));+ assert.equal(first.options.detached, true);+ assert.equal(h.children.length, 1, 'Linux must not start caffeinate for screen locking');+ assert.equal(h.timers.size, 0);+ assert.equal(h.status().active, true);+ assert.equal(h.status().antiLock, false);+ h.ctx.applySleepMode('until-done', true);+ const second = h.children[1];+ assert(second.spawnargs.includes('--what=sleep'));+ assert.deepEqual(h.signals, [{ pid: -first.pid, signal: 'SIGTERM' }]);+ first.emit('exit', 0);+ assert.equal(h.status().active, true, 'old exit must not clear the replacement inhibitor');+ h.ctx.applySleepMode('allow', true);+ assert.deepEqual(h.signals[1], { pid: -second.pid, signal: 'SIGTERM' });+ assert.equal(h.status().active, false);+});++test('Linux inhibitor startup failure and exit clear active state without macOS fallback', () => {+ const h = harness(false, true);+ h.ctx.applySleepMode('keep', false);+ h.children[0].emit('error', Object.assign(new Error('missing command'), { code: 'ENOENT' }));+ assert.equal(h.status().active, false);+ h.ctx.applySleepMode('keep', true);+ h.children[1].emit('exit', 1);+ assert.equal(h.status().active, false);+ assert(h.children.every(child => child.spawnargs[0] === 'systemd-inhibit'));+});++test('immediate sleep selects the native command on each platform', () => {+ for (const [win, linux, command] of [[false, true, 'systemctl'], [false, false, 'pmset'], [true, false, 'rundll32.exe']]) {+ const h = harness(win, linux);+ assert.equal(h.ctx.sleepNow(), true);+ assert.equal(h.children[0].spawnargs[0], command);+ if (linux) assert.deepEqual(h.children[0].spawnargs, ['systemctl', 'suspend']);+ h.children[0].emit('error', new Error('unavailable'));+ }});test('until-done waits for every discovered session, including blocked and recently hidden sessions', async () => {diff --git a/test/theme-patches.test.js b/test/theme-patches.test.jsindex ee8951b..e7c7985 100644--- a/test/theme-patches.test.js+++ b/test/theme-patches.test.js@@ -25,3 +25,33 @@ test('WorkBuddy widget cards use translucent theme surfaces', () => {assert.match(patch.css, /\.cr-widget-header\{[^}]*background-color:color-mix/);assert.doesNotMatch(patch.css, /WBS_PROFILE|workbuddy-ai/);});++test('nebula makes the latest mac teams grid containers transparent', () => {+ const patch = patches.find((item) => item && item.id === 'patch-102');+ assert.ok(patch, 'patch-102 must be registered');+ assert.equal(patch.themeId, 'nebula');+ assert.match(patch.css, /\.teams-container\.is-mac\s*>\s*\.teams-grid-scroll-content(?:,|\{)/);+ assert.match(patch.css, /\.teams-grid-scroll-content\s*>\s*\[class\*="_grid_"\]\s*>\s*\[class\*="_gridView_"\]\{/);+ assert.match(patch.css, /background:transparent !important/);+ assert.match(patch.css, /background-color:transparent !important/);+ assert.match(patch.css, /backdrop-filter:none !important/);+});++test('nebula removes the mac teams send tooltip wrapper background', () => {+ const patch = patches.find((item) => item && item.id === 'patch-103');+ assert.ok(patch, 'patch-103 must be registered');+ assert.equal(patch.themeId, 'nebula');+ assert.match(patch.css, /\.teams-container\.is-mac \.cr-input-toolbar__send>span\.cr-send-button__tooltip-wrapper/);+ assert.match(patch.css, /background:transparent !important/);+ assert.match(patch.css, /background-color:transparent !important/);+});++test('nebula removes backgrounds from the template switcher and code copy tooltip', () => {+ const patch = patches.find((item) => item && item.id === 'patch-104');+ assert.ok(patch, 'patch-104 must be registered');+ assert.equal(patch.themeId, 'nebula');+ assert.match(patch.css, /\.industry-template-switcher__host>button\.wb-button\.wb-button--secondary/);+ assert.match(patch.css, /\.cr-code-like-box__header>span\.cr-code-block__copy-tooltip/);+ assert.match(patch.css, /background:transparent !important/);+ assert.match(patch.css, /box-shadow:none !important/);+});diff --git a/test/token-stats.test.js b/test/token-stats.test.jsindex cfcb9c6..3e3d9df 100644--- a/test/token-stats.test.js+++ b/test/token-stats.test.js@@ -5,6 +5,7 @@ const assert = require('node:assert/strict');const fs = require('fs');const os = require('os');const path = require('path');+const vm = require('vm');const { scanTokenStats, scanTokenStatsCached, dateBounds, tokenStatsCacheReady } = require('../scripts/token-stats.js');test('scans usage metadata without reading message semantics into the result', () => {@@ -68,6 +69,22 @@ test('daily breakdown keeps account and model dimensions without changing totalsassert.deepEqual(scanTokenStatsCached(root, { now, days: 1, account: 'b' }).dailyBreakdown.map(row => row.account), ['b']);});+test('credit model trend ignores account-total records without a model dimension', () => {+ const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ const start = source.indexOf('function usageTrendGroups');+ const end = source.indexOf('\n function renderUsageBreakdown', start);+ const usageTrendGroups = vm.runInNewContext('(' + source.slice(start, end).trim() + ')');+ const groups = usageTrendGroups([{ title: '2026-09-20' }], [+ { day: '2026-09-20', account: 'account-a', value: 1365.17 },+ { day: '2026-09-20', model: 'kimi-k3-1', value: 1291.88 },+ { day: '2026-09-20', model: 'deepseek-v4.1-flash', value: 73.29 },+ ], 'model', { 'kimi-k3-1': 'kimi-k3-1', 'deepseek-v4.1-flash': 'deepseek-v4.1-flash' });+ assert.deepEqual(JSON.parse(JSON.stringify(groups.map(group => [group.key, group.total]))), [+ ['kimi-k3-1', 1291.88],+ ['deepseek-v4.1-flash', 73.29],+ ]);+});+test('date range is limited to 90 days', () => {const now = Date.parse('2026-09-11T10:00:00Z');assert.throws(() => dateBounds(now, { from: '2026-01-01', until: '2026-09-11' }), /不能超过 90 天/);diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 1ec7f44..d480ea2 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -176,7 +176,7 @@ test('account switching carries the active conversation and opens its copied tarconst routeStart = script.indexOf("if (req.method === 'POST' && p === '/api/switch')");const route = script.slice(routeStart, routeStart + 9000);assert.match(route, /currentConversationId/);- assert.match(route, /SELECT user_id FROM sessions WHERE id = \? AND deleted_at IS NULL LIMIT 1;/);+ assert.match(route, /SELECT user_id, cwd FROM sessions WHERE id = \? AND deleted_at IS NULL LIMIT 1;/);assert.match(route, /不属于源账号的当前会话/);const dirtyStart = script.indexOf("if (req.method === 'POST' && p === '/api/sessions/dirty')");const dirtyRoute = script.slice(dirtyStart);@@ -205,6 +205,24 @@ test('account switching carries the active conversation and opens its copied tarassert.match(inject, /setBuildTimeout\(function \(\) \{ openCopiedSession\(id, started, attempt \+ 1\); \}, 500\)/);});+test('account switching does not auto-copy an opened session without an enabled rule', () => {+ const daemon = read('daemon.js');+ const helperStart = daemon.indexOf('function shouldStartAutoCopyJob(');+ assert.notEqual(helperStart, -1, 'auto-copy decision must have a testable helper');+ const helperEnd = daemon.indexOf('\n}\n', helperStart) + 3;+ const context = {};+ vm.runInNewContext(daemon.slice(helperStart, helperEnd), context);+ assert.equal(context.shouldStartAutoCopyJob({ allSessions: false, sessionIds: [], workspaces: [] }, false), false);+ assert.equal(context.shouldStartAutoCopyJob({ allSessions: false, sessionIds: [], workspaces: [] }, true), true);+ assert.equal(context.shouldStartAutoCopyJob({ allSessions: true, sessionIds: [], workspaces: [] }, false), true);+ assert.equal(context.shouldStartAutoCopyJob({ allSessions: false, sessionIds: ['session'], workspaces: [] }, false), true);+ assert.equal(context.shouldStartAutoCopyJob({ allSessions: false, sessionIds: [], workspaces: ['/workspace'] }, false), true);+ const routeStart = daemon.indexOf("if (req.method === 'POST' && p === '/api/switch')");+ const route = daemon.slice(routeStart, routeStart + 9000);+ assert.match(route, /shouldStartAutoCopyJob\(sourceRules, hasPendingAutoCopyTo\(sourceUid\)\)/);+ assert.doesNotMatch(route, /hasPendingAutoCopyTo\(sourceUid\) \|\| currentConversationId/);+});+test('copied-session activation trusts the official handler even when projection ids are empty', async () => {const inject = read('inject.js');const start = inject.indexOf(' function openCopiedSession(sessionId, startedAt) {');@@ -978,6 +996,8 @@ test('quick-phrase layering does not reposition WorkBuddy native chat toolbar',const script = read('inject.js');assert.match(script, /\.wbs-explore-inline\.wbs-stash-inline-inline\{position:relative;z-index:99999\}/);assert.match(script, /\.wbs-explore-pop\{[^}]*z-index:2147483647/);+ assert.match(script, /html\[data-wbs-theme-id="nebula"\] \.wbs-explore-card\{[^}]*background:color-mix\(in srgb,var\(--wb-bg-popover/);+ assert.match(script, /html\[data-wbs-theme-id="nebula"\] \.wbs-explore-tip\{[^}]*background:color-mix\(in srgb,var\(--wb-bg-popover/);assert.doesNotMatch(script, /_chatMessageBottomToolbarWrapper_\}\{position:relative;z-index:68/);assert.doesNotMatch(script, /_chatMessageBottomToolbar_\}\{position:relative;z-index:69/);assert.doesNotMatch(script, /_chatMessageBottomToolbarItem_\}\{position:relative;z-index:70/);@@ -1307,7 +1327,7 @@ test('automatic session copy includes workspace-only rules when the initial planassert.match(daemon, /getAutoCopySessionMembers\(DATA_DIR, lineageId, targetUid\)/);assert.match(daemon, /const existing = candidates\.find\(/);assert.match(daemon, /const sourceRules = sourceUid \? getAutoCopyRules\(DATA_DIR, sourceUid\)/);- assert.match(daemon, /hasSourceAutoCopyRules/);+ assert.match(daemon, /shouldStartAutoCopyJob\(sourceRules, hasPendingAutoCopyTo\(sourceUid\)\)/);assert.match(daemon, /hasPendingAutoCopyTo\(uid\)/);assert.match(daemon, /startAutoCopyJob\(sourceUid, uid, \[\]/);assert.match(daemon, /copySessionRecord\(src, targetUid/);@@ -1335,7 +1355,7 @@ test('session copy-all is a separate override with a distinct toggle and hiddenconst daemon = read('daemon.js');const inject = read('inject.js');assert.match(daemon, /POST' && p === '\/api\/sessions\/auto-copy-all'/);- assert.match(daemon, /sourceRules\.allSessions/);+ assert.match(daemon, /rules\.allSessions/);assert.match(inject, /id="wbs-sess-auto-all"/);const filters = inject.slice(inject.indexOf('<div class="wbs-sess-filters">'), inject.indexOf('<div class="wbs-sess-toolbar">'));assert.match(filters, /id="wbs-sess-account-select"[\s\S]*id="wbs-sess-size-seg"[\s\S]*id="wbs-sess-range-seg"/);