WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
feat: 合并 1.2.5 版本
[email protected]c397ac958d9d
diff --git a/scripts/account-credit-cache.js b/scripts/account-credit-cache.jsnew file mode 100644index 0000000..4e1b6da--- /dev/null+++ b/scripts/account-credit-cache.js@@ -0,0 +1,51 @@+'use strict';+const fs = require('node:fs');+const path = require('node:path');+const { replaceFileWithRetry } = require('./atomic-file-write');++// Public balance projection only; never persist an API response or auth data.+function projection(result) {+ const number = value => typeof value === 'number' && Number.isFinite(value) ? value : null;+ return {+ credits: number(result.credits),+ creditUnlimited: result.unlimited === true,+ creditSegments: (Array.isArray(result.segments) ? result.segments : []).filter(segment => segment && number(segment.remaining) !== null).map(segment => ({+ remaining: number(segment.remaining), total: number(segment.total), expiresAt: number(segment.expiresAt),+ source: typeof segment.source === 'string' ? segment.source : '',+ packageCode: typeof segment.packageCode === 'string' ? segment.packageCode : '',+ })),+ };+}+function nearestExpiry(account) {+ let nearest = Infinity;+ for (const segment of account.creditSegments || []) {+ if (segment.remaining > 0 && typeof segment.expiresAt === 'number' && Number.isFinite(segment.expiresAt)) nearest = Math.min(nearest, segment.expiresAt);+ }+ return nearest;+}+function createAccountCreditCache(dataDir) {+ const file = path.join(dataDir, 'account-credit-cache.json');+ const entries = new Map();+ try {+ for (const [uid, value] of Object.entries(JSON.parse(fs.readFileSync(file, 'utf8')))) {+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid) || !value || typeof value !== 'object') continue;+ entries.set(uid, projection({ credits: value.credits, unlimited: value.creditUnlimited, segments: value.creditSegments }));+ }+ } catch (_) { /* A missing or corrupt optional cache is safe to discard. */ }+ function get(uid) { return entries.has(uid) ? structuredClone(entries.get(uid)) : {}; }+ function set(uid, result) {+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return;+ entries.set(uid, projection(result));+ fs.mkdirSync(dataDir, { recursive: true });+ replaceFileWithRetry(file, JSON.stringify(Object.fromEntries(entries)), 0o600);+ }+ function order(accounts) {+ // Capture all keys before the first request; refreshed balances cannot move+ // remaining accounts while this loop is running. Unknown expiry goes last.+ return accounts.map((account, index) => ({ account, index, expiry: nearestExpiry(get(account.uid)) }))+ .sort((a, b) => a.expiry === b.expiry ? a.index - b.index : a.expiry - b.expiry)+ .map(item => item.account);+ }+ return { get, set, order };+}+module.exports = { createAccountCreditCache };diff --git a/scripts/automation-compatibility.js b/scripts/automation-compatibility.jsindex 2eb77cf..3a4a50e 100644--- a/scripts/automation-compatibility.js+++ b/scripts/automation-compatibility.js@@ -28,7 +28,7 @@ function assessRequirements(requires, runtime, actualCapabilities=[]) {if(requires){validateRequirements(requires);if(!runtime.version||!versionAtLeast(runtime.version,requires.minWorkDaddyVersion))issues.push({code:'workdaddy_version',required:requires.minWorkDaddyVersion});- if(requires.taskSchemaVersion!==1)issues.push({code:'unsupported_task_schema'});+ if(![1,2,3].includes(requires.taskSchemaVersion))issues.push({code:'unsupported_task_schema'});if(requires.profiles&&!requires.profiles.includes(runtime.profileId))issues.push({code:'profile',allowed:requires.profiles});if(requires.platforms&&!requires.platforms.includes(runtime.platform))issues.push({code:'platform',allowed:requires.platforms});}diff --git a/scripts/automation-likes.js b/scripts/automation-likes.jsnew file mode 100644index 0000000..926a3e3--- /dev/null+++ b/scripts/automation-likes.js@@ -0,0 +1,83 @@+'use strict';++const TASK_KEY = /^[0-9a-f]{64}$/i;+const CACHE_TTL_MS = 20 * 1000;+const DEFAULT_ENDPOINT = 'https://workdaddy.dev/api/automation-likes';++function normalizeKeys(tasks) {+ return [...new Set((Array.isArray(tasks) ? tasks : []).map(task => String(task && task.key || '').trim().toLowerCase()).filter(key => TASK_KEY.test(key)))];+}++function normalizeResult(keys, payload) {+ const source = payload && payload.favorites && typeof payload.favorites === 'object' ? payload.favorites : {};+ return Object.fromEntries(keys.map(key => {+ const item = source[key] || {};+ return [key, { count: Math.max(0, Number(item.count) || 0), favorited: item.favorited === true }];+ }));+}++function decorateCatalog(catalog, favorites) {+ const tasks = Array.isArray(catalog && catalog.tasks) ? catalog.tasks : [];+ return {+ ...(catalog || {}),+ tasks: tasks.map(task => {+ const item = favorites[String(task.key || '').toLowerCase()] || {};+ return { ...task, favoriteCount: Math.max(0, Number(item.count) || 0), favorited: item.favorited === true };+ }),+ };+}++function createAutomationLikesClient(options = {}) {+ const endpoint = String(options.endpoint || process.env.WORKDADDY_AUTOMATION_LIKES_ENDPOINT || DEFAULT_ENDPOINT).replace(/\/+$/, '');+ const fetchImpl = options.fetchImpl || globalThis.fetch;+ const getActorId = options.getActorId || (() => null);+ let cache = null;+ let lastFavorites = {};++ function actorHeaders() {+ const actor = String(getActorId() || '').trim().toLowerCase();+ return actor ? { 'X-WorkDaddy-Actor': actor } : {};+ }++ async function request(url, init = {}) {+ const response = await fetchImpl(url, { ...init, headers: { Accept: 'application/json', ...(init.headers || {}) } });+ let body = null;+ try { body = await response.json(); } catch (_) {}+ if (!response.ok || !body || body.ok === false) throw new Error(body && body.error || '收藏服务暂时不可用');+ return body;+ }++ async function getFavorites(tasks) {+ const keys = normalizeKeys(tasks);+ if (!keys.length) return {};+ const signature = keys.join(',');+ if (cache && cache.signature === signature && cache.expiresAt > Date.now()) return cache.value;+ const url = endpoint + '?keys=' + encodeURIComponent(signature);+ const value = normalizeResult(keys, await request(url, { headers: actorHeaders() }));+ cache = { signature, value, expiresAt: Date.now() + CACHE_TTL_MS };+ return value;+ }++ async function decorate(catalog) {+ try {+ lastFavorites = await getFavorites(catalog && catalog.tasks);+ return decorateCatalog(catalog, lastFavorites);+ } catch (_) { return decorateCatalog(catalog, lastFavorites); }+ }++ async function toggle(taskKey, favorite) {+ const key = String(taskKey || '').trim().toLowerCase();+ if (!TASK_KEY.test(key) || typeof favorite !== 'boolean') throw new Error('收藏任务参数无效');+ const result = await request(endpoint, {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...actorHeaders() },+ body: JSON.stringify({ taskKey: key, favorite }),+ });+ cache = null;+ return { taskKey: key, favoriteCount: Math.max(0, Number(result.favoriteCount) || 0), favorited: result.favorited === true };+ }++ return { getFavorites, decorate, toggle, normalizeKeys };+}++module.exports = { CACHE_TTL_MS, createAutomationLikesClient, decorateCatalog, normalizeKeys };diff --git a/scripts/automation-packages.js b/scripts/automation-packages.jsindex 79ae369..bbcf176 100644--- a/scripts/automation-packages.js+++ b/scripts/automation-packages.js@@ -46,6 +46,7 @@ function analyzeTask(task) {}}if (['logic.sequence','logic.repeat','logic.retry','logic.catch','logic.forEach','logic.waitUntil','account.forEach'].includes(op)) walk(value.steps);+ if (op === 'account.forEach') walk(value.prepare);if (op === 'logic.catch') walk(value.onError);if (op === 'logic.if') { walk(value.then); walk(value.else); }if (op === 'logic.switch') { Object.values(value.cases || {}).forEach(walk); walk(value.default); }@@ -105,7 +106,7 @@ function previewPackage(input, options = {}) {if (task.requires != null) throw new Error('Package requirements belong in the envelope only');inputs=document.inputs||{};}else { task=object(document.task||document,'task'); requires=task.requires || null; }- if(packaged ? (task.schemaVersion??1)!==1 : ![1,2].includes(task.schemaVersion??1))return incompatible('unsupported_task_schema');+ if(![1,2,3].includes(task.schemaVersion??1))return incompatible('unsupported_task_schema');const analysis=analyzeTask(task);issues.push(...assessRequirements(requires,{...runtime,capabilities:runtime.capabilities || CAPABILITIES.filter(c=>c.available!==false).map(c=>c.id)},analysis.capabilities));const bound=bindInputs(inputs,options.values||{});diff --git a/scripts/automation.js b/scripts/automation.jsindex 6a5d533..88b2bc6 100644--- a/scripts/automation.js+++ b/scripts/automation.js@@ -7,8 +7,8 @@ const { validateRequirements, assessRequirements } = require('./automation-compaconst { normalizeToastOptions } = require('./toast-options.js');const { normalizeAutomationModelId } = require('./automation-model.js');-const SCHEMA_VERSION = 2;-const SUPPORTED_SCHEMA_VERSIONS = new Set([1, 2]);+const SCHEMA_VERSION = 3;+const SUPPORTED_SCHEMA_VERSIONS = new Set([1, 2, 3]);const MAX_TASKS = 200;const MAX_STEPS = 200;const MAX_DEPTH = 12;@@ -43,7 +43,7 @@ const CAPABILITIES = [{ id: 'logic.catch', zh: '捕获错误', en: 'Catch an error', descriptionZh: '执行 steps;失败时把错误写入 vars.error 并运行 onError。', descriptionEn: 'Run steps; on failure, write the error to vars.error and run onError.', example: { op: 'logic.catch', steps: [], onError: [] } },{ id: 'logic.assert', zh: '条件断言', en: 'Assert a condition', descriptionZh: '条件不成立时终止任务并给出错误信息。', descriptionEn: 'Stop the task with an error when a condition is false.', example: { op: 'logic.assert', condition: { left: '{{response.ok}}', operator: 'truthy' }, message: '请求失败' } },{ id: 'log.write', zh: '写入运行日志', en: 'Write run log', descriptionZh: '将固定 message 中的 {参数名} 替换为 params 标量值后写入运行日志。参数可引用模板;拒绝凭据字段,对手机号和令牌格式脱敏。不弹出通知。', descriptionEn: 'Write a run log using {name} placeholders and scalar params. Templates are supported; credential paths are rejected and phone/token patterns are redacted. No notification.', example: { op: 'log.write', message: '账号 {account}:{state}', params: { account: '{{account.uid}}', state: '{{vars.catStatus.json.data.state}}' } } },- { id: 'account.forEach', zh: '循环账号', en: 'Iterate accounts', descriptionZh: '对全部或指定账号依次执行步骤;switch:true 会真实切换登录账号,并在循环结束后恢复原账号。', descriptionEn: 'Run steps for all or selected accounts; switch:true physically switches the logged-in account and restores the original account when the loop ends.', example: { op: 'account.forEach', accounts: 'all', switch: true, steps: [] } },+ { id: 'account.forEach', zh: '循环账号', en: 'Iterate accounts', descriptionZh: '对全部或指定账号依次执行步骤;switch:true 会真实切换登录账号,等待会话同步成功后再执行步骤,并在循环结束后安全恢复原账号;V3 支持 prepare 只读准备与 condition 切换前筛选。', descriptionEn: 'Run steps for all or selected accounts; switch:true physically switches the logged-in account, waits for successful session sync before executing steps, and safely restores the original account. V3 supports read-only prepare steps and a condition evaluated before switching.', example: { op: 'account.forEach', accounts: 'all', switch: true, steps: [] } },{ id: 'account.status', zh: '查询账号状态', en: 'Read account status', descriptionZh: '查询今日签到、今日活跃和积分等只读状态。', descriptionEn: 'Read check-in, activity, and credit status.', example: { op: 'account.status', fields: ['checkin.today', 'activity.today'] } },{ id: 'account.checkin', zh: '账号静默签到', en: 'Check in as account', descriptionZh: '使用循环账号的 token 签到,不切换客户端。当天已确认签到时跳过所有请求;返回 ok、skipped、code 等状态。', descriptionEn: 'Check in using the context account token without switching accounts. Confirmed daily records skip all requests. Returns ok, skipped and code.', example: { op: 'account.checkin', saveAs: 'checkin' } },{ id: 'http.request', zh: 'HTTP 请求', en: 'HTTP request', descriptionZh: '调用 HTTP/HTTPS 接口并保存响应。', descriptionEn: 'Call an HTTP/HTTPS endpoint and retain its response.', example: { op: 'http.request', method: 'GET', url: 'https://example.com/api', saveAs: 'response' } },@@ -257,6 +257,12 @@ function taskIsPassiveCleanup(task) {return valid && clicks > 0;}+function stepsContainCheckin(value) {+ if (Array.isArray(value)) return value.some(stepsContainCheckin);+ if (!value || typeof value !== 'object') return false;+ return value.op === 'account.checkin' || Object.values(value).some(stepsContainCheckin);+}+function taskNeedsPanelClosed(task) {const walk = (value) => {if (Array.isArray(value)) return value.some(walk);@@ -352,6 +358,13 @@ function validateSteps(steps, depth = 0, schemaVersion = 1) {steps.forEach((step, index) => {if (!step || typeof step !== 'object') throw new Error(`第 ${index + 1} 步不是对象`);const op = String(step.op || '').trim();+ if (op === 'account.forEach' && (step.prepare != null || step.condition != null)) {+ if (schemaVersion < 3) throw new Error('切换前筛选需要自动化协议 V3');+ const allowed = new Set(['account.status', 'state.get', 'vars.set', 'time.now', 'value.number', 'log.write']);+ if (step.prepare != null && (!Array.isArray(step.prepare) || step.prepare.some(item => !item || !allowed.has(item.op)))) throw new Error('prepare 仅支持只读账号状态、state.get、变量和日志步骤');+ validateSteps(step.prepare || [], depth + 1, schemaVersion);+ if (step.condition != null && (!step.condition || typeof step.condition !== 'object' || Array.isArray(step.condition))) throw new Error('筛选 condition 必须是条件对象');+ }if (op === 'log.write') {if (typeof step.message !== 'string' || !step.message.trim() || step.message.length > 240 || /\{\{|\}\}/.test(step.message)) throw new Error('日志 message 需要不含模板的固定文字(最多 240 字符)');const params = step.params == null ? {} : step.params;@@ -451,7 +464,7 @@ function createSafetyReviewTask(dataDir, taskId) {| 建议 | 可以启用 / 谨慎启用 / 不建议启用 |整张表不超过 160 字,不要解释原因、过程或原理。`;return validateTask({- schemaVersion: 2,+ schemaVersion: 3,id: 'safety_review_' + crypto.randomBytes(8).toString('hex'),name: '安全评估', enabled: true, trigger: { type: 'manual' },steps: [{ op: 'session.create', model: 'deepseek-v4.1-flash', message: finalMessage }],@@ -520,12 +533,12 @@ function capabilityText(language = 'zh') {groups[group].push(item.id + (item.available === false ? (zh ? '(预留)' : ' (reserved)') : ''));});const lines = zh ? [- 'WorkDaddy 自动化任务协议 v2(兼容 v1)',+ 'WorkDaddy 自动化任务协议 v3(兼容 v1、v2)','','任务 JSON:',- JSON.stringify({ schemaVersion: 2, id: 'example-task', name: '任务名称', description: '', enabled: true, concurrency: { policy: 'skip' }, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [], onSuccess: [], onFailure: [] }, null, 2),+ JSON.stringify({ schemaVersion: 3, id: 'example-task', name: '任务名称', description: '', enabled: true, concurrency: { policy: 'skip' }, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [], onSuccess: [], onFailure: [] }, null, 2),'',- '任务字段:schemaVersion 支持 1 和 2,新任务使用 2;id 在全部任务中唯一;name 必填;description 可空;enabled 控制生命周期触发;V2 concurrency.policy 支持 skip;variables 是任务初始变量;steps 是主步骤;onSuccess/onFailure 分别在成功/失败后执行。',+ '任务字段:schemaVersion 支持 1、2、3,新任务使用 3;id 在全部任务中唯一;name 必填;description 可空;enabled 控制生命周期触发;V2 concurrency.policy 支持 skip;variables 是任务初始变量;steps 是主步骤;onSuccess/onFailure 分别在成功/失败后执行。','约束:最多 200 个任务;每组最多 200 个步骤;最多嵌套 12 层;单次重复最多 100 次;重试最多 10 次;单次等待最多 300 秒。任务中不要保存 Token、Cookie 或密码。','触发器:manual 仅手动运行;pageReady 在首次打开、导航完成或账号切换后的页面刷新完成后运行。pageReady 默认同一次页面导航只触发一次;pageLoaded 同样覆盖页面加载(包括切换刷新);accountSwitched 仅账号切换;clientLoaded 仅 daemon 连接已加载客户端时触发(兼容名,不建议新任务使用)。组合事件同一导航只执行一次。','组合触发:trigger.types:["clientLoaded","panelOpened"] 可多选,存在时替代 trigger.type;空数组仅手动。schedule:{type:"interval",minutes:60} 每小时触发(1–10080 分钟);也支持 {type:"daily",time:"09:00"}、{type:"weekly",days:[1,2,3,4,5],time:"09:00"}(0=周日)、{type:"monthly",day:15,time:"09:00"}、{type:"once",at:"2026-12-01T09:00"}。均为电脑本地时区,每月不存在的日期跳过,指定时间任务不会重复,可与事件组合;enabled:false 停止所有自动触发。自动任务不提供立即运行;需要测试时在编辑器清空自动触发条件并关闭定时,再手动运行。运行中的同一任务不会重入,错过的定时不会补跑。POST /api/automations/events {type:"panelOpened"} 在面板从关闭变为打开时调用,需标准本地 API 认证。',@@ -533,24 +546,25 @@ function capabilityText(language = 'zh') {'通用步骤字段:op 必填;saveAs 可把该步骤返回值保存到 {{vars.<name>}};每个步骤的返回值也会覆盖 {{step.*}}。嵌套步骤仍按顺序执行。','模板变量:V2 提供 {{runtime.time.iso}}、{{runtime.time.epochMs}}、{{runtime.time.localDate}}、{{runtime.run.id}}、{{runtime.trigger.type}};并兼容 {{now}}、{{event.type}}、{{account.uid}}、{{vars.name}}、{{response.json}}、{{step.*}}。对象与数组递归展开模板;完整字符串模板保留原始数值/对象/数组类型,混合文本模板会转成字符串。','条件运算符:equals、notEquals、contains、matches、truthy、falsy、gt、gte、lt、lte。matches 的 right 是正则表达式字符串。',- '账号作用域:account.forEach 默认只改变嵌套步骤的账号上下文;设置 switch:true 才会真实切换登录账号,并在循环结束后恢复原账号。account.status 和 http.requestAsAccount 使用当前上下文;DOM 与当前会话步骤操作切换后的可见 WorkBuddy 页面。',+ '账号作用域:account.forEach 默认只改变嵌套步骤的账号上下文;设置 switch:true 才会真实切换登录账号,等待会话同步成功后再执行步骤,并在循环结束后安全恢复原账号;V3 支持 prepare 只读准备与 condition 切换前筛选。account.status 和 http.requestAsAccount 使用当前上下文;DOM 与当前会话步骤操作切换后的可见 WorkBuddy 页面。','元素定位 locator:{kind,value}。kind 支持 css、xpath、text、role、ariaLabel、placeholder、attribute。coordinates 仅保留协议格式,当前不可用于 DOM 步骤。','DOM 等待:dom.wait 可使用 seconds 做固定等待;或使用 locator、until:{state:"visible"|"hidden"|"attached"|"detached"|"clickable"}、timeoutMs 等待元素状态。until 还支持 text 包含匹配或 attribute/value 相等。locators 数组提供依次回退的定位器;readText 最多 100000 字符。iframe 内目前只支持读取,不支持点击与输入。DOM 读取结果可用 saveAs 保存。','HTTP 输入:method、url、query、headers、body、timeoutMs(500-60000)、saveAs。响应:{ok,status,headers,text,json},正文最多 1 MiB。http.request 不允许自定义 Authorization/Cookie;http.requestAsAccount 只对当前客户端官方 HTTPS origin 注入账号登录态;禁止跨域、非默认端口、URL 用户名密码。重定向不会自动跟随。body/query/headers 支持递归模板。默认非 2xx 返回 ok:false 供分支判断;throwOnHttpError:true 抛错以配合 retry(支持 backoff,默认 1)。停止会中止 HTTP 和等待。','运行日志:log.write 使用固定 message 和 params 命名标量参数,例如 {account} 对应 params.account:"{{account.uid}}"。会脱敏手机号和常见令牌格式,拒绝敏感字段路径;不要在 message 中写凭据。运行日志不弹通知,单次运行不按条数截断;daemon 重启后内存中的运行记录会清空。','会话:session.create 新建并发送第一条消息;session.send 仅向选中且无草稿的指定 conversationId 发送。V2 两者均可选 model(精确模型 ID,支持模板),切换未确认则拒绝发送;create 发送后恢复新建任务模型偏好,send 保留会话模型。返回 {accountUid,conversationId,userMessageId,requestId,baselineAssistantId} 回执,saveAs 保存。session.wait 接受 receipt(默认 vars.session)、timeoutMs(最长 300000)、contains,按回执监听。未知发送结果不会自动重发;发送不能嵌套 retry。session.sendCurrent/waitReply 是兼容别名,前者实际上新建会话。仅支持挂载的可见会话,不支持后台任意会话发送。',+ 'V3 账号循环:account.forEach 可选 prepare 数组(仅 account.status、state.get、vars.set、time.now、value.number、log.write),先在每个账号上下文执行,再判断 condition={left,operator,right};条件不满足则不切换、不执行 steps。V1/V2/V3 的 switch:true 均等待前序同步、页面刷新和本次同步成功才执行 steps;失败/部分成功/未解决冲突终止,大小提醒不影响成功。运行接口继续立即返回 202;run-status 的 phase/sync 展示等待和进度;停止请求以 stopRequested 标记,安全收尾完成后才变为 cancelled。','状态作用域:state.get/state.set 的 scope 支持 task(默认)或 account;所有状态首先按任务 ID 隔离;account scope 再按 uid 隔离。V2 state.set 可设置 ttlMs,过期后 state.get 返回空值并清理。key 必填;state.get 可配 saveAs。','通知:notify.toast 使用 react-hot-toast,从窗口底部向上弹出;level 支持 info、success、warning、error、loading。可选 duration(1000–60000 毫秒)、id、saveAs;相同 id 更新提示,notify.dismiss 用 id 关闭。id 按本次运行隔离,任务结束自动清理 loading。notify.afterAllTasks 已废弃,仅兼容旧任务;新任务不要使用。','失败语义:未捕获错误会停止主步骤并执行 onFailure;logic.catch 捕获局部错误并把消息写入 {{vars.error.message}};logic.retry 只重试其嵌套步骤。','','基础接口总目录:',] : [- 'WorkDaddy Automation Task Protocol v2 (backward compatible with v1)',+ 'WorkDaddy Automation Task Protocol v3 (backward compatible with v1 and v2)','','Task JSON:',- JSON.stringify({ schemaVersion: 2, id: 'example-task', name: 'Task name', description: '', enabled: true, concurrency: { policy: 'skip' }, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [], onSuccess: [], onFailure: [] }, null, 2),+ JSON.stringify({ schemaVersion: 3, id: 'example-task', name: 'Task name', description: '', enabled: true, concurrency: { policy: 'skip' }, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [], onSuccess: [], onFailure: [] }, null, 2),'',- 'Task fields: schemaVersion 1 and 2 are supported; new tasks use 2. id is unique; name is required; description may be empty; enabled controls lifecycle triggers; V2 concurrency.policy supports skip; variables contains initial values; steps is the main sequence; onSuccess/onFailure run after success/failure.',+ 'Task fields: schemaVersion 1, 2 and 3 are supported; new tasks use 3. id is unique; name is required; description may be empty; enabled controls lifecycle triggers; V2 concurrency.policy supports skip; variables contains initial values; steps is the main sequence; onSuccess/onFailure run after success/failure.','Limits: 200 tasks; 200 steps per group; nesting depth 12; 100 repeat iterations; 10 retry attempts; 300 seconds per wait. Never store tokens, cookies, or passwords in a task.','Triggers: manual only runs on demand; pageReady runs after initial load, navigation, or the page refresh following an account switch. pageReady runs once per navigation by default; pageLoaded includes all page loads; accountSwitched only matches switches; clientLoaded is a legacy connection-only trigger. Combined events run once per navigation.','Combined triggers: trigger.types:["clientLoaded","panelOpened"] overrides trigger.type. Empty types means manual only. schedule:{type:"interval",minutes:60} adds an interval of 1–10080 minutes. Also supported: {type:"daily",time:"09:00"}, {type:"weekly",days:[1,2,3,4,5],time:"09:00"} (0=Sunday), {type:"monthly",day:15,time:"09:00"}, {type:"once",at:"2026-12-01T09:00"}. All use local computer time; nonexistent month dates and missed slots are skipped, and calendar slots are not repeated after restart. Only tasks without automatic triggers or a schedule can run manually. Disabled tasks do not auto-run; running tasks skip overlapping triggers. POST /api/automations/events {type:"panelOpened"} requires local API authentication. account.checkin uses the context account token and skips all requests for a confirmed daily check-in; use logic.catch to handle individual account errors.',@@ -563,6 +577,7 @@ function capabilityText(language = 'zh') {'HTTP input: method, url, query, headers, body, timeoutMs (500-60000), saveAs. Response: {ok,status,headers,text,json}; body is capped at 1 MiB. http.request rejects Authorization/Cookie; http.requestAsAccount injects credentials only for current-profile official HTTPS origins, rejecting foreign origins, ports and URL credentials. Redirects are not followed. body/query/headers resolve recursive templates. Non-2xx returns ok:false by default; throwOnHttpError:true enables retry (backoff defaults to 1). Cancellation aborts HTTP and waits.','Run logs: log.write takes a fixed message and named scalar params; {account} reads params.account:"{{account.uid}}". Phone and common token patterns are redacted, and sensitive paths are rejected. Never put credentials in message. Run logs do not show notifications and are not truncated by entry count; in-memory runs are cleared on daemon restart.','Sessions: session.create creates by sending the first message; session.send targets only a selected conversationId with an empty composer. In V2 both accept an optional model (exact model ID, templates supported) and refuse to send if the switch is unconfirmed. create restores the New Task model preference after sending; send keeps the model selected in the conversation. Returns {accountUid,conversationId,userMessageId,requestId,baselineAssistantId}; saveAs persists the receipt in variables. session.wait accepts receipt (default vars.session), timeoutMs (up to 300000), contains. Unconfirmed sends are never automatically retried; sends cannot be nested in retry. sendCurrent/waitReply are legacy aliases; sendCurrent creates a new conversation. Only mounted visible sessions are supported.',+ 'V3 account loops: account.forEach accepts prepare (only account.status, state.get, vars.set, time.now, value.number, log.write) and condition={left,operator,right}, evaluated in each account context before any physical switch. A false condition skips switching and steps. switch:true in V1/V2/V3 waits for prior sync, page reload and successful inbound sync. Partial/failed/unresolved sync stops execution; size warnings do not. Run requests still return 202; run-status exposes phase/sync progress and stopRequested while cancellation drains safely.','State scope: state.get/state.set scope is task (default) or account. State is isolated by task ID and account scope adds the uid. V2 state.set accepts ttlMs; expired values are removed and state.get returns empty. key is required; state.get accepts saveAs.','Notifications: notify.toast uses react-hot-toast at bottom-center. level is info, success, warning, error, or loading. Optional duration (1000–60000 ms), id, and saveAs; reuse id to update, notify.dismiss with id to dismiss. IDs are scoped to a run; unfinished loading notifications are cleared when the run ends. notify.afterAllTasks is deprecated and retained only for saved tasks. Do not generate it for new tasks.','Failure behavior: an uncaught error stops main steps and runs onFailure. logic.catch writes a local error to {{vars.error.message}}. logic.retry retries only its nested steps.',@@ -580,7 +595,7 @@ function capabilityText(language = 'zh') {});lines.push('', zh ? '账号状态字段:checkin.today、activity.today、activity.streak、credits。返回 uid、isPrimary、checkin、activity、credits;activity.streak={days,status},days=null 表示不可用;credits={total,unlimited,cycleResetTime}。活跃天数是连续活跃天数,不是注册天数。' : 'Account fields: checkin.today, activity.today, activity.streak, credits. Returns uid,isPrimary,checkin,activity,credits. activity.streak={days,status}; null means unavailable. credits={total,unlimited,cycleResetTime}. Streak means consecutive active days, not registration age.');lines.push(zh ? '预检:POST /api/automations/validate 或 /api/automations/dry-run,body={task},需本地认证。仅静态校验并返回操作计划/弃用警告,executed:false,不发请求、不切账号、不发送消息,不保证运行时 DOM/API 可用。state.checkpoint 显式保存业务进度,state.get 读取;不会自动恢复或重放副作用。修改同一渲染器的任务排队串行,静默 API 任务可并发;restartOnNavigation 的只读/关闭按钮监听不占用整轮锁,但点击与输入仍互斥,避免关闭弹窗任务阻塞发送;取消不代表已发送消息或已完成服务器操作可撤销。' : 'Preflight: authenticated POST /api/automations/validate or /api/automations/dry-run with {task}. Static validation and operation plan/deprecation warnings only; executed:false. No HTTP, switches or messages. Does not guarantee runtime DOM/API availability. state.checkpoint explicitly saves progress for state.get; never automatically resumes or replays side effects. Renderer tasks queue serially; silent API tasks can run concurrently. Navigation-scoped read/click-only observers share a short input lock so popup cleanup can run between sends. Cancellation cannot undo messages or completed server operations.');- lines.push(zh ? '共享任务兼容:本地任务继续使用 schemaVersion:1,可选 requires={minWorkDaddyVersion,taskSchemaVersion,capabilities,profiles?,platforms?};不满足依赖时不会执行。外部分发使用独立的 workdaddy.automation-package 包(formatVersion:1、独立 id/version、requires、inputs、task)。POST /api/automations/packages/preview {document,values?} 只预检,需检查 compatible:true;不会安装或执行。为本面板生成任务时仍输出本地任务 JSON,不要向 Agent 收件箱写入包或索引。' : 'Sharing compatibility: local tasks remain schemaVersion:1 and may declare requires={minWorkDaddyVersion,taskSchemaVersion,capabilities,profiles?,platforms?}; incompatible tasks never execute. Distribution uses a separate workdaddy.automation-package envelope with formatVersion:1, independent id/version, requires, inputs and task. POST /api/automations/packages/preview {document,values?} is preview-only; check compatible:true. No installation or execution. When creating tasks for this panel, keep generating local task JSON, never a package or index in the Agent inbox.');+ lines.push(zh ? '共享任务兼容:本地任务支持 schemaVersion:1/2/3,新任务使用 3,可选 requires={minWorkDaddyVersion,taskSchemaVersion,capabilities,profiles?,platforms?};不满足依赖时不会执行。外部分发使用独立的 workdaddy.automation-package 包(formatVersion:1、独立 id/version、requires、inputs、task)。POST /api/automations/packages/preview {document,values?} 只预检,需检查 compatible:true;不会安装或执行。为本面板生成任务时仍输出本地任务 JSON,不要向 Agent 收件箱写入包或索引。' : 'Sharing compatibility: local tasks support schemaVersion:1/2/3; use 3 for new tasks and may declare requires={minWorkDaddyVersion,taskSchemaVersion,capabilities,profiles?,platforms?}; incompatible tasks never execute. Distribution uses a separate workdaddy.automation-package envelope with formatVersion:1, independent id/version, requires, inputs and task. POST /api/automations/packages/preview {document,values?} is preview-only; check compatible:true. No installation or execution. When creating tasks for this panel, keep generating local task JSON, never a package or index in the Agent inbox.');return lines.join('\n');}@@ -883,7 +898,8 @@ async function executeTask(taskInput, options = {}) {if (op === 'account.getCurrent') { ctx.account = options.currentAccount ? await options.currentAccount() : null; ctx.vars.account = ctx.account; return ctx.account; }if (op === 'account.forEach') {const all = typeof options.listAccounts === 'function' ? await options.listAccounts() : [];- const wanted = step.accounts === 'all' || !step.accounts ? all : all.filter((account) => (Array.isArray(step.accounts) ? step.accounts : [step.accounts]).includes(account.uid));+ let wanted = step.accounts === 'all' || !step.accounts ? all : all.filter((account) => (Array.isArray(step.accounts) ? step.accounts : [step.accounts]).includes(account.uid));+ if (stepsContainCheckin(step.steps) && typeof options.orderCheckinAccounts === 'function') wanted = await options.orderCheckinAccounts(wanted);const results = [];const physicallySwitch = step.switch === true || step.switchAccounts === true;const original = physicallySwitch && typeof options.currentAccount === 'function' ? await options.currentAccount() : null;@@ -896,6 +912,11 @@ async function executeTask(taskInput, options = {}) {assertActive();ctx.account = account;ctx.vars.account = account;+ if (step.prepare) await runSteps(step.prepare);+ if (step.condition && !compare(resolveValue(step.condition.left, ctx), step.condition.operator || 'truthy', resolveValue(step.condition.right, ctx))) {+ log('account:skip:' + account.uid);+ continue;+ }if (physicallySwitch) await options.accountSwitch(account);results.push(await runSteps(step.steps || []));}@@ -1009,6 +1030,7 @@ module.exports = {createScheduleTicker,validateSchedule,taskNeedsPanelClosed,+ stepsContainCheckin,taskIsPassiveCleanup,installBuiltinTask,SCHEMA_VERSION,diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex 0845ddb..722f0e7 100644--- a/scripts/build-mac-dmg.sh+++ b/scripts/build-mac-dmg.sh@@ -56,7 +56,7 @@ chmod 644 "$APP/Contents/Resources/AppIcon.icns"echo "==> 应用图标已同步(背景 #e1e1e1)"# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)-for f in daemon.js toast-runtime.js toast-options.js primary-account.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-zip.js automation.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.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 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 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 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-picker.js token-refresh.js session-db.js session-fork.js session-sync.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 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 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# Injection reads the wordmark at runtime; keep brand assets in both profiles.@@ -90,6 +90,7 @@ chmod 755 "$APP/Contents/Resources/scripts/daemon.js" \"$APP/Contents/Resources/scripts/uninstall.sh" \"$APP/Contents/Resources/scripts/apply-update.sh"chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \+ "$APP/Contents/Resources/scripts/account-credit-cache.js" \"$APP/Contents/Resources/scripts/automation.js" \"$APP/Contents/Resources/scripts/automation-picker.js" \"$APP/Contents/Resources/scripts/token-refresh.js" \diff --git a/scripts/daemon.js b/scripts/daemon.jsindex aced2b8..f77f3ef 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -29,6 +29,7 @@ const os = require('os');const crypto = require('crypto');const net = require('net');const sessionSync = require('./session-sync.js');+const { createAccountCreditCache } = require('./account-credit-cache.js');const { spawn, spawnSync } = require('child_process');const {assertSameProcessIdentity,@@ -141,6 +142,7 @@ const {const {captureException,captureMessage,+ persistentInstallationId,setTelemetryEnabled,telemetryEnabled,telemetryEnvironmentOverride,@@ -181,6 +183,7 @@ const {taskMatchesEvent,createScheduleTicker,taskNeedsPanelClosed,+ stepsContainCheckin,taskIsPassiveCleanup,isSupportedTaskSchema,isTaskCompatible,@@ -197,12 +200,14 @@ let automationInputActive = false;const { previewPackage, PACKAGE_FORMAT_VERSION } = require('./automation-packages.js');const { exportTasks, importTasks, readTransferBody } = require('./automation-transfer.js');const { createAutomationDiscovery } = require('./automation-discovery.js');+const { createAutomationLikesClient } = require('./automation-likes.js');const { createAutomationNotifier } = require('./toast-options.js');const { runCompletionReport, probeAccountCompletion } = require('./completion-report.js');const { createPrimaryAccountStore } = require('./primary-account.js');const PROFILE = getProfile();const DATA_DIR = defaultDataDir();+const accountCreditCache = createAccountCreditCache(DATA_DIR);const thirdPartyModels = createThirdPartyImport({ targetFile: workbuddyModelsFile(), dataDir: DATA_DIR });const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.existsSync(accountBackupFile(uid)));// 版本号:改动 daemon/inject/theme-patches/builtin 资产后递增,launcher 检测到运行中版本不一致会强制用 app 内置代码重启@@ -376,14 +381,18 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 1.2.52:成长任务支持在悬浮层内直接接取,并在完成后同步最新任务状态。// 1.2.55:成长弹窗支持开启盲盒与抽奖并提示奖励,收敛成长/用量统计 primary 色使用。// 1.2.56:成长任务补齐说明与标签、已领取折叠、Buddy 派出,并把用量柱状图改为面积折线图。-const DAEMON_VERSION = '1.2.83';-const DAEMON_BUILD_ID = 'release-1.2.83-20260919-switch-without-session-activity-gate';+const DAEMON_VERSION = '1.2.95';+const DAEMON_BUILD_ID = 'release-1.2.95-20260920-session-sync-skip-fastpath';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({dataDir: DATA_DIR,runtime: { version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform },});+const automationLikes = createAutomationLikesClient({+ endpoint: process.env.WORKDADDY_AUTOMATION_LIKES_ENDPOINT || 'https://workdaddy.dev/api/automation-likes',+ getActorId: persistentInstallationId,+});const HOST = '127.0.0.1';// 平台分支开关。上游历史代码把「非 Windows」一律当 macOS,Linux 适配时拆成// IS_MAC / IS_LINUX 两个显式常量,避免 Linux 走进 /Applications、osascript 等分支。@@ -3107,7 +3116,7 @@ async function automationHttpRequest(request, account) {return { ok: response.ok, status: response.status, headers: { 'content-type': response.headers.get('content-type') || '' }, text, json: jsonBody };} catch (e) { if (request.isCancelled && request.isCancelled()) throw new Error('任务已停止'); if (e && e.name === 'AbortError') throw new Error('HTTP 请求超时'); throw new Error(e && e.message === 'HTTP 响应超过 1 MiB' ? e.message : 'HTTP 请求失败'); } finally { clearTimeout(timer); clearInterval(cancelTimer); }}-function automationPublicRun(run) { return { id: run.id, taskId: run.taskId, status: run.status, phase: run.phase || 'executing', startedAt: run.startedAt, finishedAt: run.finishedAt || 0, error: run.error || '', logs: run.logs, result: run.result || null }; }+function automationPublicRun(run) { return { id: run.id, taskId: run.taskId, status: run.status, phase: run.phase || 'executing', sync: run.sync || null, stopRequested: !!run.stopRequested, startedAt: run.startedAt, finishedAt: run.finishedAt || 0, error: run.error || '', logs: run.logs, result: run.result || null }; }// 自动化运行前收拢 WorkDaddy 面板「窗口」,避免其 contenteditable/悬浮层与 WorkBuddy 原生// composer 抢焦点或遮挡,导致任务把提示词键入到 WorkDaddy 面板输入框 / 点不到官方发送按钮@@ -3181,6 +3190,7 @@ async function automationNotifyToast(detail) {return response.result.value;}let accountSwitchInProgress = false;+const accountSyncFailures = new Map();async function assertSessionSyncIdle() {if (PROFILE.kind !== 'workbuddy') return;if (!cdp.connected) throw new Error('无法确认会话状态,请连接 WorkBuddy 后重试');@@ -3201,16 +3211,82 @@ async function assertAccountSwitchIdle() {}let automationAccountSwitchTail = Promise.resolve();-function automationSwitchAccount(account) {+function assertAutoCopySucceeded(job) {+ if (job && (job.status !== 'done' || job.processed !== job.total || job.failed || job.failedItems || job.partial || job.conflicts)) {+ throw new Error('会话同步未成功完成,已停止自动切换(同步任务 ' + job.id + ',状态 ' + job.status + ')');+ }+}++function recordAccountSyncResult(job) {+ if (!job || !job.targetUid) return;+ try {+ assertAutoCopySucceeded(job);+ accountSyncFailures.delete(job.targetUid);+ } catch (_) {+ // UI history expires after 30 minutes. Keep a compact failure barrier until+ // a subsequent successful synchronization proves this account is ready.+ accountSyncFailures.set(job.targetUid, {+ id: job.id, status: job.status, total: job.total, processed: job.processed,+ failed: job.failed, failedItems: job.failedItems, partial: job.partial, conflicts: job.conflicts,+ });+ }+}++function automationSwitchProgress(options, phase, job = null) {+ if (typeof options.onProgress !== 'function') return;+ options.onProgress({ phase, sync: job ? {+ jobId: job.id, status: job.status, processed: job.processed, total: job.total,+ failed: job.failed || 0, conflicts: job.conflicts || 0,+ } : null });+}++async function waitAutomationSyncJob(job, options) {+ // Completion includes worker cleanup. Keep the account lock while writes drain,+ // even after Stop; releasing it early would let restoration race file commits.+ let finished = false;+ job.completion.then(() => { finished = true; });+ while (!finished) {+ automationSwitchProgress(options, options.isCancelled && options.isCancelled() ? 'stopping-sync' : 'syncing-sessions', job);+ await sleep(200);+ }+ automationSwitchProgress(options, 'syncing-sessions', job);+ assertAutoCopySucceeded(job);+}++async function acquireAutomationAccountSwitch(options) {+ for (;;) {+ if (options.isCancelled && options.isCancelled()) throw new Error('任务已停止');+ const busy = accountSwitchInProgress || autoCopyWorkerRunning || autoCopyQueue.length || sessionCopyLocks.size;+ if (!busy) {+ // Check the latest inbound result, not just an empty queue. A failed job+ // must not silently become permission to switch once its worker stops.+ const uid = String((currentAccount() || {}).uid || '');+ assertAutoCopySucceeded(accountSyncFailures.get(uid));+ let latest = null;+ for (const job of autoCopyJobs.values()) if (job.targetUid === uid) latest = job;+ assertAutoCopySucceeded(latest);+ // No await between the idle check and claiming the synchronous switch lock.+ return assertAccountSwitchIdle();+ }+ const pending = Array.from(autoCopyJobs.values()).find(job => job.status === 'queued' || job.status === 'running');+ automationSwitchProgress(options, 'waiting-sync', pending);+ await sleep(200);+ }+}++function automationSwitchAccount(account, options = {}) {const target = account && typeof account === 'object' ? account : { uid: String(account || '').trim() };const run = automationAccountSwitchTail.then(async () => {const uid = String(target.uid || '').trim();if (!uid) throw new Error('账号切换缺少 uid');- const active = currentAccount();- if (active && active.uid === uid) return { ok: true, uid, switched: false };- const releaseAccountSwitch = await assertAccountSwitchIdle();- const releaseRendererReload = beginRendererReloadPriority();+ const releaseAccountSwitch = await acquireAutomationAccountSwitch(options);+ let releaseRendererReload = null;try {+ if (options.isCancelled && options.isCancelled()) throw new Error('任务已停止');+ const active = currentAccount();+ if (active && active.uid === uid) return { ok: true, uid, switched: false };+ automationSwitchProgress(options, options.restore ? 'restoring-account' : 'switching-account');+ releaseRendererReload = beginRendererReloadPriority();const acct = switchTo(DATA_DIR, uid, log);pendingAutomationAccountSwitch = { account: { uid: acct.uid, nickname: acct.nickname } };await reloadWorkBuddyPage();@@ -3221,16 +3297,23 @@ function automationSwitchAccount(account) {}const sourceUid = String(active && active.uid || '');const rules = sourceUid ? getAutoCopyRules(DATA_DIR, sourceUid) : {};+ let job = null;if (rules.allSessions || (rules.sessionIds || []).length || (rules.workspaces || []).length) {- startAutoCopyJob(sourceUid, uid, [], { sourceName: active.nickname, targetName: acct.nickname });+ job = startAutoCopyJob(sourceUid, uid, [], { sourceName: active.nickname, targetName: acct.nickname });}- return { ok: true, uid: acct.uid, nickname: acct.nickname, switched: true };+ // Sync yields to reload priority: release it before awaiting the job.+ releaseRendererReload();+ releaseRendererReload = null;+ if (job) await waitAutomationSyncJob(job, options);+ if (options.isCancelled && options.isCancelled()) throw new Error('任务已停止');+ return { ok: true, uid: acct.uid, nickname: acct.nickname, switched: true, syncJobId: job ? job.id : null };} catch (error) {pendingAutomationAccountSwitch = null;throw error;} finally {- releaseRendererReload();+ if (releaseRendererReload) releaseRendererReload();releaseAccountSwitch();+ automationSwitchProgress(options, 'executing');}});automationAccountSwitchTail = run.catch(() => {});@@ -3246,7 +3329,7 @@ function startAutomationRun(task, event = null) {}const id = 'run_' + Date.now().toString(36) + '_' + crypto.randomBytes(3).toString('hex');const run = { id, taskId: task.id, status: 'running', startedAt: Date.now(), finishedAt: 0, error: '', logs: [], result: null, navigationSerial: event && event.navigationSerial, pageSessionId: event && event.pageSessionId };- const isCancelled = () => run.status === 'cancelled' || run.superseded === true ||+ const isCancelled = () => run.stopRequested === true || run.status === 'cancelled' || run.superseded === true ||(task.trigger.restartOnNavigation && event && (event.navigationSerial !== mainFrameNavigationSerial || event.pageSessionId !== cdpPageSessionId));log('[automation-focus-diagnostics] automation:start ' + JSON.stringify({ runId: id, taskId: task.id, source: event && event.source || '', account: event && event.account || null, cdpTargetUrl: cdp.targetUrl, cdpTargetTitle: cdp.targetTitle }));const appendRunLog = (message) => {@@ -3413,7 +3496,15 @@ function startAutomationRun(task, event = null) {run.cleanupNotifications = runNotifier.cleanup;const publicAccounts = () => listAccounts(DATA_DIR).map(a => ({uid:a.uid,nickname:a.nickname,isPrimary:primaryAccountStore.get()===a.uid}));const publicCurrent = () => { const a = currentAccount(); return a ? {uid:a.uid,nickname:a.nickname,isPrimary:primaryAccountStore.get()===a.uid} : null; };- const runDeps = { runId: id, sessionAction, primaryAccount: async () => publicAccounts().find(a=>a.isPrimary) || null, dismissToast: runNotifier.dismiss, completionReport, event, listAccounts: async () => publicAccounts(), currentAccount: publicCurrent, accountSwitch: (account, detail) => withInput(() => automationSwitchAccount(account), !!(detail && detail.restore)), accountStatus: automationAccountStatus, accountCheckin: async (account) => {+ const runDeps = { runId: id, sessionAction, primaryAccount: async () => publicAccounts().find(a=>a.isPrimary) || null, dismissToast: runNotifier.dismiss, completionReport, event, orderCheckinAccounts: (accounts) => accountCreditCache.order(accounts), listAccounts: async () => publicAccounts(), currentAccount: publicCurrent, accountSwitch: (account, detail) => withInput(() => automationSwitchAccount(account, {+ restore: !!(detail && detail.restore),+ isCancelled: detail && detail.restore ? () => false : isCancelled,+ onProgress: progress => {+ if (run.phase !== progress.phase || (run.sync && run.sync.jobId) !== (progress.sync && progress.sync.jobId)) appendRunLog('account:switch:' + progress.phase + (progress.sync ? ':' + progress.sync.jobId : ''));+ run.phase = progress.phase;+ run.sync = progress.sync;+ },+ }), !!(detail && detail.restore)), accountStatus: automationAccountStatus, accountCheckin: async (account) => {if (!account || !account.uid) throw new Error('没有可用账号');const result = await claimDailyForUid(account.uid);appendRunLog('account:checkin:' + (result.skipped ? 'skipped' : result.ok ? 'success' : 'failed'));@@ -4374,7 +4465,52 @@ async function importSessionArchives(payload, targetUid, staged = false) {return { imported, failed: errors.length, errors: summarizeSessionImportErrors(errors) };}+// Session-copy fingerprint cache: files whose size/mtime/ctime are unchanged+// reuse their stored SHA-256 instead of being re-read on every sync. Best+// effort only — a lost or stale entry just costs one re-read. The cap must+// cover every session file on disk (tens of thousands), or active sessions+// evict each other and the cache never warms up.+const SESSION_SYNC_CACHE_LIMIT = 100000;+let sessionSyncCacheState = null;+function getSessionSyncCache() {+ if (sessionSyncCacheState) return sessionSyncCacheState.map;+ const file = path.join(DATA_DIR, 'session-sync-cache.json');+ const map = new Map();+ try {+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));+ if (raw && raw.version === 1 && raw.entries && typeof raw.entries === 'object') {+ for (const [key, entry] of Object.entries(raw.entries)) {+ if (!entry || typeof entry !== 'object') continue;+ if (typeof entry.hash !== 'string' || !entry.hash) continue;+ if (![entry.size, entry.mtimeMs, entry.ctimeMs].every(Number.isFinite)) continue;+ map.set(key, entry);+ }+ }+ } catch (_) {}+ while (map.size > SESSION_SYNC_CACHE_LIMIT) map.delete(map.keys().next().value);+ sessionSyncCacheState = { file, map, timer: null, dirty: false };+ const set = map.set.bind(map);+ map.set = (key, value) => { sessionSyncCacheState.dirty = true; return set(key, value); };+ return map;+}+function scheduleSessionSyncCacheSave() {+ const state = sessionSyncCacheState;+ if (!state || !state.dirty || state.timer) return;+ state.timer = setTimeout(() => {+ state.timer = null;+ if (!state.dirty) return;+ state.dirty = false;+ try {+ while (state.map.size > SESSION_SYNC_CACHE_LIMIT) state.map.delete(state.map.keys().next().value);+ fs.mkdirSync(path.dirname(state.file), { recursive: true });+ replaceFileWithRetry(state.file, JSON.stringify({ version: 1, entries: Object.fromEntries(state.map) }), 0o600);+ } catch (_) { state.dirty = true; }+ }, 1000);+ if (typeof state.timer.unref === 'function') state.timer.unref();+}+async function copySessionRecord(src, targetUid, options = {}) {+ if (accountSwitchInProgress && !options.auto) throw new Error('账号正在切换,请稍后同步');const sourceUid = String(options.sourceUid || src.user_id || '').trim();targetUid = String(targetUid || '').trim();if (!sourceUid || !targetUid || sourceUid === targetUid) return { status: 'skipped', sourceId: src.id, targetId: src.id };@@ -4398,10 +4534,11 @@ async function copySessionRecord(src, targetUid, options = {}) {}const targetIds = candidates.length ? candidates.map(row => row.id) : [crypto.randomUUID()];const aliases = getAutoCopySessionMemberRecords(DATA_DIR, lineageId).map(member => member.id).concat(targetIds);- let left = sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases);+ const syncCache = getSessionSyncCache();+ let left = sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);const selection = await sessionSync.selectTargetSnapshot(left, targetIds, async id => {await yieldAutoCopyToRenderer();- return sessionSync.readSnapshot(PROFILE.dataRoot, id, aliases);+ return sessionSync.readSnapshot(PROFILE.dataRoot, id, aliases, syncCache);}, mapping && mapping.targetId);// A divergent source still needs to reach the destination. Publish it as// a new physical session in the same lineage, so later scans find it by@@ -4410,7 +4547,19 @@ async function copySessionRecord(src, targetUid, options = {}) {const targetId = branched ? crypto.randomUUID() : selection.targetId;if (branched) aliases.push(targetId);const existing = candidates.find(row => row.id === targetId) || null;- let right = sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases);+ // An equal selection needs no writes: the trimmed selection snapshot is+ // enough to skip, and the next sync re-reads everything anyway. Avoid the+ // extra full target snapshot on the hot all-skipped path.+ if (!branched && selection.comparison.kind === 'equal') {+ if (!getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid).includes(targetId)) addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId);+ if (!mapping || mapping.targetId !== targetId) setAutoCopyMapping(DATA_DIR, lineageId, targetUid, { targetId, status: 'copied', failedFiles: 0 });+ const warning = left.totalBytes > 100 * 1024 * 1024 ? '会话超过 100 MB,同步可能较慢' : '';+ return { status: 'skipped', sourceId: src.id, targetId, branched: false, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes: left.totalBytes, copiedBytes: 0 };+ }+ let right = sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases, syncCache);+ // Size is advisory only; both manual and automatic sync keep all files.+ const warning = Math.max(left.totalBytes, right.totalBytes) > 100 * 1024 * 1024+ ? '会话超过 100 MB,同步可能较慢' : '';// Selection may have yielded while inspecting other legacy copies.// Require the chosen complete snapshot to remain the same before writing.if (!branched && selection.snapshot.records && sessionSync.compareSnapshots(selection.snapshot, right).kind !== 'equal') {@@ -4419,6 +4568,8 @@ async function copySessionRecord(src, targetUid, options = {}) {const comparison = sessionSync.compareSnapshots(left, right);if (comparison.kind === 'conflict') throw new Error('会话记录正在变化,请稍后重试');let changed = false;+ let totalBytes = left.totalBytes;+ let copiedBytes = 0;const update = async (from, to, fromRow, toRow, missingOnly = false) => {await yieldAutoCopyToRenderer();const verifyRows = async () => {@@ -4429,7 +4580,7 @@ async function copySessionRecord(src, targetUid, options = {}) {throw new Error('会话记录正在变化,请稍后重试');}};- await sessionSync.applySnapshot(from, to, {+ const applied = await sessionSync.applySnapshot(from, to, {backupRoot: path.join(DATA_DIR, 'session-sync-backups'), metadata: toRow,missingOnly, guard: verifyRows,commit: async verifyPublished => {@@ -4448,6 +4599,8 @@ async function copySessionRecord(src, targetUid, options = {}) {);},});+ totalBytes = applied.totalBytes;+ copiedBytes += applied.copiedBytes;changed = true;};if (comparison.kind === 'left-extends') await update(left, right, sourceRow, existing);@@ -4456,14 +4609,14 @@ async function copySessionRecord(src, targetUid, options = {}) {if (comparison.missingRight) await update(left, right, sourceRow, existing, true);if (comparison.missingLeft) {// Re-read after the first repair, so race detection uses current bytes.- left = sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases);- right = sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases);+ left = sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);+ right = sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases, syncCache);await update(right, left, existing, sourceRow, true);}}if (!getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid).includes(targetId)) addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId);if (changed || !mapping || mapping.targetId !== targetId) setAutoCopyMapping(DATA_DIR, lineageId, targetUid, { targetId, status: 'copied', failedFiles: 0 });- return { status: changed ? 'copied' : 'skipped', sourceId: src.id, targetId, branched: branched && changed, failedFiles: 0 };+ return { status: changed ? 'copied' : 'skipped', sourceId: src.id, targetId, branched: branched && changed, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes, copiedBytes };};// One lineage lock also serializes manual copy and reverse-direction updates.const lockKey = lineageId;@@ -4471,7 +4624,10 @@ async function copySessionRecord(src, targetUid, options = {}) {const current = previous.catch(() => {}).then(perform);sessionCopyLocks.set(lockKey, current);try { return await current; }- finally { if (sessionCopyLocks.get(lockKey) === current) sessionCopyLocks.delete(lockKey); }+ finally {+ if (sessionCopyLocks.get(lockKey) === current) sessionCopyLocks.delete(lockKey);+ scheduleSessionSyncCacheSave();+ }}async function buildAutoCopyPlan(sourceUid, targetUid) {@@ -4558,7 +4714,9 @@ function runAutoCopyQueue() {pruneAutoCopyJobs();}).finally(() => {+ recordAccountSyncResult(item.job);autoCopyWorkerRunning = false;+ if (item.complete) item.complete(item.job);runAutoCopyQueue();});}@@ -4585,6 +4743,10 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {details: [],error: null,currentLabel: '',+ copiedBytes: 0,+ processedBytes: 0,+ totalBytes: null,+ copyStartedAt: null,startedAt: Date.now(),finishedAt: null,};@@ -4596,8 +4758,15 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {await yieldAutoCopyToRenderer();// A rapid switch chain may enqueue this job before the previous copy has// created the target rows. Re-plan after the queue reaches this job.+ job.copyStartedAt = Date.now();job.plan = await buildAutoCopyPlan(sourceUid, targetUid);job.total = job.plan.length;+ try {+ const sizes = await sessionSync.readSessionSizes(PROFILE.dataRoot, job.plan.map(src => String(src.id || '')));+ const values = job.plan.map(src => sizes.get(String(src.id || '')));+ job.totalBytes = values.every(value => typeof value === 'number' && Number.isFinite(value) && value >= 0)+ ? values.reduce((sum, value) => sum + value, 0) : null;+ } catch (_) { job.totalBytes = null; }for (const src of job.plan) {job.currentLabel = String(src.custom_title || src.title || src.cwd || '未命名会话');const detail = {@@ -4614,6 +4783,11 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {: result.status === 'conflict' ? 'conflict': result.status === 'skipped' ? 'skipped' : 'copied';detail.branched = result.branched === true;+ detail.totalBytes = result.totalBytes;+ job.copiedBytes += Math.max(0, Number(result.copiedBytes) || 0);+ job.processedBytes += Math.max(0, Number(result.sourceBytes) || 0);+ detail.warning = result.warning || '';+ if (detail.warning) job.warning = detail.warning;detail.failedFiles = Number(result.failedFiles) || 0;detail.conflicts = Number(result.conflicts) || 0;if (result.status === 'skipped') job.skipped++;@@ -4640,23 +4814,32 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {};// Serialising jobs makes a chain such as h -> s -> x observe the sessions// created by the preceding job, even when the user switches rapidly.- autoCopyQueue.push({ job, run });+ let complete;+ Object.defineProperty(job, 'completion', { value: new Promise(resolve => { complete = resolve; }) });+ autoCopyQueue.push({ job, run, complete });runAutoCopyQueue();return job;}function publicAutoCopyJob(job) {if (!job) return null;+ const copiedBytes = typeof job.copiedBytes === 'number' && Number.isFinite(job.copiedBytes) ? Math.max(0, job.copiedBytes) : null;+ const elapsedMs = job.copyStartedAt == null ? 0 : Math.max(0, (job.finishedAt == null ? Date.now() : job.finishedAt) - job.copyStartedAt);return {id: job.id,status: job.status,total: job.total,processed: job.processed,copied: job.copied,+ copiedBytes,+ processedBytes: typeof job.processedBytes === 'number' ? Math.max(0, job.processedBytes) : null,+ totalBytes: typeof job.totalBytes === 'number' && Number.isFinite(job.totalBytes) ? Math.max(0, job.totalBytes) : null,+ averageBytesPerSecond: copiedBytes == null || !elapsedMs ? null : Math.round(copiedBytes * 1000 / elapsedMs),skipped: job.skipped,partial: job.partial,failed: job.failed,failedItems: job.failedItems,+ warning: job.warning || '',conflicts: job.conflicts,details: Array.isArray(job.details) ? job.details.slice(0, 500) : [],error: job.error,@@ -7197,15 +7380,25 @@ function handleApi(req, res) {}if (req.method === 'GET' && p === '/api/automations/capabilities') {- return json(res, 200, { ok: true, schemaVersion: AUTOMATION_SCHEMA_VERSION, supportedSchemaVersions: [1, 2], capabilities: AUTOMATION_CAPABILITIES.filter(item => item.available !== false), protocolZh: automationCapabilityText('zh'), protocolEn: automationCapabilityText('en') });+ return json(res, 200, { ok: true, schemaVersion: AUTOMATION_SCHEMA_VERSION, supportedSchemaVersions: [1, 2, 3], capabilities: AUTOMATION_CAPABILITIES.filter(item => item.available !== false), protocolZh: automationCapabilityText('zh'), protocolEn: automationCapabilityText('en') });}if (req.method === 'GET' && p === '/api/automations/discovery') {return automationDiscovery.getCatalog({ force: url.searchParams.get('refresh') === '1' })+ .then(result => automationLikes.decorate(result)).then(result => json(res, 200, { ok: true, ...result })).catch(error => json(res, 503, { ok: false, error: error.message || '公开任务加载失败' }));}+ if (req.method === 'POST' && p === '/api/automations/discovery/favorite') {+ return readBody(req).then(body => {+ if (!body || typeof body.key !== 'string' || typeof body.favorite !== 'boolean') throw new Error('收藏请求参数无效');+ return automationLikes.toggle(body.key, body.favorite);+ })+ .then(result => json(res, 200, { ok: true, ...result }))+ .catch(error => json(res, 400, { ok: false, error: error.message || '收藏失败' }));+ }+if (req.method === 'POST' && p === '/api/automations/discovery/import') {return readBody(req).then((body) => {const content = automationDiscovery.getTaskContent(body && body.key);@@ -7374,7 +7567,7 @@ function handleApi(req, res) {const run = automationRuns.get(String(body && body.runId || ''));if (!run) return json(res, 404, { ok: false, error: '运行记录不存在' });// 当前执行器的网络/CDP调用由超时控制;停止请求先标记状态,避免新的批量运行进入。- if (run.status === 'running') { run.pendingEvent = null; run.status = 'cancelled'; run.finishedAt = Date.now(); run.error = '用户停止任务'; }+ if (run.status === 'running') { run.pendingEvent = null; run.stopRequested = true; run.phase = 'stopping'; run.error = '用户停止任务,正在安全收尾'; }if (run.cleanupNotifications) await run.cleanupNotifications();return json(res, 200, { ok: true, run: automationPublicRun(run) });});@@ -7813,6 +8006,7 @@ function handleApi(req, res) {if (req.method === 'GET' && p === '/api/accounts') {const accounts = listAccounts(DATA_DIR);+ const checkinAutomationEnabled = readAutomations(DATA_DIR).some(task => task.enabled && stepsContainCheckin(task.steps));const cache = loadCheckinCache();const today = todayStr();return CREDIT_USAGE_STORE.listDailyCheckins(accounts.map((a) => a.uid), today)@@ -7826,7 +8020,7 @@ function handleApi(req, res) {const checked = c && c.ok && (c.verified === true || classifyCheckinResult({ httpOk: true, code: c.code, message: c.message }).ok)? c: null;- return Object.assign({}, a, {+ return Object.assign({}, a, { creditSegments: [] }, accountCreditCache.get(a.uid), {checkin: checkinDisplayValue(checked, today),activityStreak: growthStreakCache.peek(a.uid),});@@ -7836,11 +8030,11 @@ function handleApi(req, res) {const withUsage = enriched.map((account) => summaries[account.uid]? Object.assign({}, account, { todayUsage: summaries[account.uid] }): account);- return json(res, 200, { ok: true, current: currentAccount(), primaryUid: primaryAccountStore.get(), accountOrder: getAccountOrder(DATA_DIR), accounts: withUsage });+ return json(res, 200, { ok: true, checkinAutomationEnabled, current: currentAccount(), primaryUid: primaryAccountStore.get(), accountOrder: getAccountOrder(DATA_DIR), accounts: withUsage });}).catch((error) => {log('[credits-usage] 读取本地今日用量失败: ' + error.message);- return json(res, 200, { ok: true, current: currentAccount(), primaryUid: primaryAccountStore.get(), accountOrder: getAccountOrder(DATA_DIR), accounts: enriched });+ return json(res, 200, { ok: true, checkinAutomationEnabled, current: currentAccount(), primaryUid: primaryAccountStore.get(), accountOrder: getAccountOrder(DATA_DIR), accounts: enriched });});});}@@ -7882,6 +8076,8 @@ function handleApi(req, res) {unlimited: !!r.unlimited,cycleResetTime: r.cycleResetTime || null,};+ // Cache failures must not turn a successful credit query into an error.+ try { accountCreditCache.set(uid, r); } catch (_) { log('[credits] 本地积分缓存写入失败'); }if (usage.synced) payload.todayUsage = usage.value;return json(res, 200, payload);} catch (e) {@@ -8431,10 +8627,9 @@ function handleApi(req, res) {const clauses = ["deleted_at IS NULL"];const params = [];if (uid) { clauses.push('user_id = ?'); params.push(uid); }- if (rangeMs) { clauses.push('COALESCE(last_activity_at, updated_at, created_at) >= ?'); params.push(rangeMs); }// 时间筛选和排序按最近活动/修改时间;旧记录缺字段时回退到创建时间。return sqliteQuery("SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, project_id FROM sessions WHERE " + clauses.join(' AND ') + " ORDER BY COALESCE(last_activity_at, updated_at, created_at) DESC, created_at DESC;", params)- .then((rows) => {+ .then(async (rows) => {const autoCopyAll = getAutoCopyRules(DATA_DIR, uid).allSessions;const rulesByUid = {};rows.forEach((row) => {@@ -8445,13 +8640,19 @@ function handleApi(req, res) {});const lineagesByUid = {}, branchesByUid = {};Object.keys(rulesByUid).forEach((owner) => { lineagesByUid[owner] = rulesByUid[owner].lineages; branchesByUid[owner] = rulesByUid[owner].branches; });- const sessions = dedupeAutoCopySessionRows(rows, lineagesByUid, branchesByUid).map((row) => {+ const allSessions = dedupeAutoCopySessionRows(rows, lineagesByUid, branchesByUid).map((row) => {const rules = rulesByUid[String(row.user_id || '').trim()] || { sessions: new Set(), workspaces: new Set() };return Object.assign({}, row, {autoCopySession: rules.sessions.has(String(row.id)),autoCopyWorkspace: rules.workspaces.has(canonicalWorkspace(row.cwd)),});});+ const sizes = await sessionSync.readSessionSizes(PROFILE.dataRoot, allSessions.map(row => String(row.id)));+ allSessions.forEach(row => { row.totalBytes = sizes.get(String(row.id)); });+ // Account totals deliberately include sessions hidden by either filter.+ const totalBytes = allSessions.every(row => typeof row.totalBytes === 'number' && Number.isFinite(row.totalBytes))+ ? allSessions.reduce((sum, row) => sum + row.totalBytes, 0) : null;+ const sessions = rangeMs ? allSessions.filter(row => Number(row.last_activity_at ?? row.updated_at ?? row.created_at) >= rangeMs) : allSessions;const currentRules = uid? (rulesByUid[uid] || (() => {const rules = getAutoCopyRules(DATA_DIR, uid);@@ -8462,6 +8663,7 @@ function handleApi(req, res) {ok: true,sessions,count: sessions.length,+ totalBytes,uid,range,autoCopyAll,@@ -8788,6 +8990,9 @@ function handleApi(req, res) {const targetUid = (body.targetUid || '').trim();if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });if (!targetUid) return json(res, 400, { ok: false, error: '未指定目标账号' });+ if (accountSwitchInProgress) return json(res, 409, { ok: false, error: '账号正在切换,请稍后同步' });+ const copyOperation = Symbol('manual-session-copy');+ sessionCopyLocks.set(copyOperation, true);try {// 1) 取出源会话(含 cwd 用于定位消息文件)const srcRows = await sqliteQuery(@@ -8796,16 +9001,18 @@ function handleApi(req, res) {);if (!srcRows.length) return json(res, 404, { ok: false, error: '源会话不存在' });let copied = 0, skipped = 0, conflicts = 0;+ let warning = '';for (const src of srcRows) {const result = await copySessionRecord(src, targetUid);+ if (result.warning) warning = result.warning;if (result.status === 'conflict') conflicts++;else if (result.status === 'skipped') skipped++;else copied++;}- return json(res, 200, { ok: true, copied, skipped, conflicts, targetUid });+ return json(res, 200, { ok: true, copied, skipped, conflicts, targetUid, warning });} catch (e) {return json(res, 500, { ok: false, error: e.message });- }+ } finally { sessionCopyLocks.delete(copyOperation); }});}// 迁移会话:POST /api/sessions/migrate { ids, targetUid }diff --git a/scripts/inject.js b/scripts/inject.jsindex 7f8b260..3d1fbe3 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -825,6 +825,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var WBS_LANGUAGE_KEY = 'workdaddy.ui.language';var WBS_ACCOUNT_MASK_KEY = 'workdaddy.account.mask.' + PROFILE_ID;var WBS_I18N_EN = {+ '总大小': 'Total size',+ '所选账号全部会话的大小,不受时间和大小筛选影响': 'Total size of all sessions for the selected account, regardless of time and size filters',+ '会话大小(消息和附件)': 'Session size (messages and attachments)',+ '筛选会话大小': 'Filter session size',+ '大小': 'Size','未同步': 'Not synced', '分叉会话尚未同步,请重试': 'The branched session has not been synced. Try again','已复制分叉副本,原会话已保留': 'Branch copied as a separate session; the original was preserved','账号正在切换,请稍后重试': 'Account switching is in progress. Try again later',@@ -842,7 +847,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'会话目录包含符号链接,未同步': 'The session directory is a symbolic link. Sync was skipped','会话文件无法读取': 'Cannot read session files','会话文件类型不受支持': 'Unsupported session file type',- '会话文件过大,未自动同步': 'Session files exceed the sync limit. Automatic sync was skipped',+ '会话超过 100 MB,同步可能较慢': 'Session exceeds 100 MB; syncing may take longer','会话文件正在变化,请稍后重试': 'Session files are changing. Try again later','会话产物索引损坏,未同步': 'The session artifact index is corrupt. Sync was skipped','会话消息文件不唯一,未同步': 'Multiple message files found for this session. Sync was skipped',@@ -1009,7 +1014,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {"请选择有效的执行日期和时间": "Choose a valid date and time","每月日期必须是 1–31": "Day of month must be 1\u201331",'产物索引已变化,请重试同步': 'Artifact index changed; retry synchronization', '已到期': 'Expired', ' 个未获取余额': ' balances unavailable', ' 个不限量': ' unlimited', '无效的账号排序设置': 'Invalid account order settings', '产物索引超过 16MB,未覆盖目标索引': 'Artifact index exceeds 16MB; target index was preserved', '产物索引格式不受支持': 'Unsupported artifact index format', '积分汇总': 'Credit summary', '更多账号设置': 'More account settings', '积分到期分布': 'Credit expiry distribution', '剩余天数 · 积分': 'Days left · Credits', '按剩余天数汇总积分': 'Credits by days remaining', '未知有效期': 'Unknown expiry', '暂无可汇总积分': 'No credits to summarize', '拖拽调整顺序,也可聚焦拖拽按钮后按 ↑ ↓ 调整。新增账号排在最后。': 'Drag to reorder, or focus a handle and press ↑ ↓. New accounts appear last.', '拖拽排序,或按上下方向键调整': 'Drag or use arrow keys to reorder', '调整账号顺序': 'Reorder account', '固定账号顺序': 'Fixed account order', '保存排序失败': 'Failed to save order', '暂无账号': 'No accounts', '{n} 个账号': '{n} accounts', '{n} 个未获取余额': '{n} balances unavailable', '{n} 个不限量': '{n} unlimited', '今日未签到': 'Not checked in today', '浅色': 'Light', '深色': 'Dark', '更多': 'More', '汇总': 'Summary', '账号排序': 'Account order', '按积分临近时间': 'Nearest credit expiry', '固定顺序': 'Fixed order', '今日签到': 'Daily check-in', '今日已签到': 'Checked in today', '今日尚未签到': 'Not checked in today', '客户端加载': 'Client loaded', '打开面板': 'Panel opened', '事件触发(可多选)': 'Event triggers (select any)', '定时间隔(分钟)': 'Interval (minutes)', '定时': 'Scheduled', '每 ': 'Every ', '定时间隔必须是 1–10080 分钟的整数': 'Interval must be an integer from 1 to 10080 minutes', '不支持的面板事件': 'Unsupported panel event', '无签到活动': 'No check-in activity', '登录身份过期': 'Login expired', '刚刚': 'Just now', '分钟前': ' minutes ago', '小时前': ' hours ago', '天前': ' days ago',- '发现新版本': 'New version available', '立即更新': 'Update now', '有新版本可用,点击更新。': 'A new version is available. Click Update.', '有新版': 'New version', '新版': 'New version', '更新': 'Update', '任务已更新': 'Task updated', '更新自动化任务?': 'Update automation task?', '确认用公开仓库中的新版覆盖本地任务?': 'Replace the local task with the newer public version?', '覆盖': 'Replace', '提示:部分会话尚未完成,当前 Token 和积分仅按已完成用量统计,最终数据可能存在偏差。': 'Note: Some sessions are still in progress. Token and credit totals include completed usage only and may change.', '下载中…': 'Downloading…', '正在打开…': 'Opening…', '安装程序已打开': 'Installer opened', '打开安装程序': 'Open installer', '安装中…': 'Installing…', '重启中…': 'Restarting…', '已完成': 'Completed', '重试更新': 'Retry update',+ '发现新版本': 'New version available', '立即更新': 'Update now', '有新版本可用,点击更新。': 'A new version is available. Click Update.', '有新版': 'New version', '新版': 'New version', '更新': 'Update', '任务已更新': 'Task updated', '更新自动化任务?': 'Update automation task?', '确认用公开仓库中的新版覆盖本地任务?': 'Replace the local task with the newer public version?', '覆盖': 'Replace', '用量统计会随会话完成逐步更新。': 'Usage totals update as sessions finish.', '下载中…': 'Downloading…', '正在打开…': 'Opening…', '安装程序已打开': 'Installer opened', '打开安装程序': 'Open installer', '安装中…': 'Installing…', '重启中…': 'Restarting…', '已完成': 'Completed', '重试更新': 'Retry update','安全传输': 'Secure transfer', '选择内容': 'Select content', '选择账号': 'Select accounts', '选择目标账号': 'Select target account', '选择目标账号…': 'Select a target account…', '密码': 'Password', '请输入密码': 'Enter password', '密码不能为空': 'Password cannot be empty', '请至少选择一项': 'Select at least one item', '处理中…': 'Processing…', '新版文件请输入密码': 'Enter the password for the new file', '新版文件必须输入密码;旧版导出文件可留空。': 'New files require a password; older exports may be left blank.', '新版文件请输入密码;已有的相同短语会自动跳过。': 'Enter the password for the new file; duplicate phrases are skipped.','电脑休眠': 'Computer sleep', '允许电脑休眠': 'Allow computer sleep', '持续禁止休眠': 'Keep awake', '所有会话结束允许休眠': 'Allow sleep when all sessions end', '系统默认,空闲后正常休眠': 'System default; sleep normally when idle', '保持唤醒,防黑屏锁屏': 'Stay awake to prevent screen lock', '任一会话运行中都保持唤醒': 'Stay awake while any session is running', '允许显示器休眠': 'Allow display sleep', '禁止休眠时,是否允许显示器单独黑屏': 'When sleep is blocked, allow the display to turn off','发送错误诊断': 'Send error diagnostics', '推荐开启': 'Recommended', '由环境变量控制': 'Controlled by environment variable', '默认开启 · 设置读取失败': 'Enabled by default · failed to read setting', '保存中…': 'Saving…', '此开关控制脱敏错误诊断。匿名安装数和日活独立统计(随机安装标识、系统、架构、版本、客户端类型及出口国家),不受此开关影响。不包含账号、会话内容、Token 或 API Key。': 'This switch controls redacted error diagnostics. Anonymous installation and daily active counts are collected independently (random installation ID, system, architecture, version, client type, and network country). No accounts, session content, tokens, or API keys.', '查看错误诊断说明': 'View diagnostics details', '问题反馈': 'Report an issue', '会话监听日志': 'Session monitor log', '仅保存在当前页面内存': 'Stored only in this page memory',@@ -1017,7 +1022,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'未设置': 'Not set', '当前使用中': 'Currently active', '停止生成': 'Stop generating', '正常重启': 'Restart normally', '清空日志': 'Clear log', '开发者工具': 'Developer tools', '隐藏功能': 'Hidden feature', '卡死': 'Stuck', '任务': 'Task', '空间': 'Workspace', '全部': 'All', '今天': 'Today', '近 7 天': 'Last 7 days', '近 30 天': 'Last 30 days', '企业配额': 'Enterprise quota', '积分到期分布': 'Credit expiry distribution','连接新服务…': 'Connecting to service…', '等待中': 'Waiting', '运行中': 'Running', '空闲': 'Idle', '已中断': 'Interrupted', '已停止': 'Stopped', '未确认': 'Unconfirmed', '等待确认': 'Waiting for confirmation', '等待新回复': 'Waiting for a new reply', '等待会话': 'Waiting for session', '等待允许': 'Waiting for approval', '整理中': 'Organizing', '恢复中': 'Restoring', '即将完成…': 'Finishing…', '已继续': 'Continued', '检测到会话异常中断,即将自动发送「': 'An interrupted session was detected. Sending “', '自动发送失败,请手动点击发送': 'Automatic send failed. Please click Send manually', '底层发送失败,请手动发送': 'Underlying send failed. Please send manually','导入中…': 'Importing…', ' 个任务': ' task(s)', '导入任务': 'Import tasks', '导出任务': 'Export tasks', '请先勾选要导出的任务': 'Select tasks to export first', '选择 JSON 或 ZIP 任务文件': 'Choose a JSON or ZIP task file', '读取任务文件…': 'Reading task file…', '任务导出成功': 'Tasks exported', '导入失败': 'Import failed', '导出失败': 'Export failed', '可导入': 'Ready to import', '已存在,将跳过': 'Already exists; skipped', '不兼容,无法导入': 'Incompatible; cannot import', '导入后保持停用,可在任务列表中启用。相同 ID 的任务会跳过。': 'Imported tasks stay disabled until you enable them. Existing task IDs are skipped.', '任务文件不能超过 8 MiB': 'Task files must not exceed 8 MiB', '缺少必填参数': 'Required inputs are missing', '需要更新 WorkDaddy': 'Requires a newer WorkDaddy version', '不支持当前客户端或系统': 'Unsupported client or platform', '文件不是自动化任务 JSON': 'Not an automation task JSON file', '任务格式或能力不受支持': 'Unsupported task format or capabilities',- '发现更多自动化任务': 'Discover more automations', '正在发现…': 'Discovering…', '搜索任务名称': 'Search task names', '没有匹配的任务': 'No matching tasks', '暂未发现公开任务': 'No public tasks found', '公开任务加载失败': 'Could not load public tasks', '这些任务来自互联网公开仓库,均为第三方内容,与 WorkDaddy 无归属关系。导入后默认停用,请先安全评估再启用。': 'These tasks come from public repositories and are third-party content unaffiliated with WorkDaddy. Imported tasks stay disabled; review them before enabling.', '部分来源暂时无法访问,当前显示上次缓存的结果。': 'Some sources are unavailable. Showing cached results.', '暂无说明': 'No description', '不兼容': 'Incompatible', '无法打开仓库': 'Could not open repository', '任务已导入,启用后生效': 'Task imported. Enable it to run.', '任务已存在,未重复导入': 'Task already exists and was not imported again.', '我也要出现在这里': 'Publish my tasks', '提交公开任务': 'Publish public tasks', '收录 GitHub 和 Gitee 公开仓库。参考': 'Public GitHub and Gitee repositories are indexed. See', '将任务 JSON 放在 tasks/ 目录,并在仓库描述中加入 WorkDaddyAutomationRepository。': 'Put task JSON files in tasks/ and add WorkDaddyAutomationRepository to the repository description.', '查看示例仓库': 'View example repository', '上一页': 'Previous', '下一页': 'Next', ' · 匹配 ': ' · Matches ', '安全评估': 'Safety review', '评估中…': 'Reviewing…', '安全评估会话已创建': 'Safety review session created', '安全评估失败': 'Safety review failed', '会话创建失败': 'Could not create the session', '无法读取评估状态': 'Could not read review status', '未返回安全评估运行记录': 'No safety review run was returned', '无法创建会话': 'Could not create a session', '评估会话仍在创建,请稍后查看 WorkBuddy': 'The review session is still being created. Check WorkBuddy shortly.',+ '发现更多自动化任务': 'Discover more automations', '正在发现…': 'Discovering…', '搜索任务名称': 'Search task names', '没有匹配的任务': 'No matching tasks', '暂未发现公开任务': 'No public tasks found', '公开任务加载失败': 'Could not load public tasks', '这些任务来自互联网公开仓库,均为第三方内容,与 WorkDaddy 无归属关系。导入后默认停用,请先安全评估再启用。': 'These tasks come from public repositories and are third-party content unaffiliated with WorkDaddy. Imported tasks stay disabled; review them before enabling.', '部分来源暂时无法访问,当前显示上次缓存的结果。': 'Some sources are unavailable. Showing cached results.', '暂无说明': 'No description', '不兼容': 'Incompatible', '无法打开仓库': 'Could not open repository', '任务已导入,启用后生效': 'Task imported. Enable it to run.', '任务已存在,未重复导入': 'Task already exists and was not imported again.', '我也要出现在这里': 'Publish my tasks', '我的收藏': 'My favorites', '暂无收藏的任务': 'No favorites yet', '收藏任务': 'Favorite task', '取消收藏': 'Remove favorite', '收藏失败': 'Favorite failed', '提交公开任务': 'Publish public tasks', '收录 GitHub 和 Gitee 公开仓库。参考': 'Public GitHub and Gitee repositories are indexed. See', '将任务 JSON 放在 tasks/ 目录,并在仓库描述中加入 WorkDaddyAutomationRepository。': 'Put task JSON files in tasks/ and add WorkDaddyAutomationRepository to the repository description.', '查看示例仓库': 'View example repository', '上一页': 'Previous', '下一页': 'Next', ' · 匹配 ': ' · Matches ', '安全评估': 'Safety review', '评估中…': 'Reviewing…', '安全评估会话已创建': 'Safety review session created', '安全评估失败': 'Safety review failed', '会话创建失败': 'Could not create the session', '无法读取评估状态': 'Could not read review status', '未返回安全评估运行记录': 'No safety review run was returned', '无法创建会话': 'Could not create a session', '评估会话仍在创建,请稍后查看 WorkBuddy': 'The review session is still being created. Check WorkBuddy shortly.',+ '已复制 ': 'Copied ', ' · 平均复制速率 ': ' · Average copy speed ', '按实际复制成功的数据量除以同步耗时计算,包含校验和备份时间': 'Copied data divided by sync duration, including verification and backups',+ '同步数据量和速率': 'Sync data and speed',+ '同步数据量': 'Sync data','会话同步完成': '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 ',@@ -1065,7 +1073,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'悬停预览,点击或拖动快速定位消息。': 'Hover to preview; click or drag to jump to a message.','选中会话消息文字后,一键插入输入框。': 'After selecting session message text, insert it into the composer with one click.','发送后不会自动删除。': 'Not deleted automatically after sending.', '需要我决策时弹窗确认(全局生效)': 'Ask me with a dialog when my decision is needed (applies globally)',- '自动化接口协议 V2': 'Automation interface protocol V2',+ '自动化接口协议 V3': 'Automation interface protocol V3',+ '等待会话同步': 'Waiting for session sync', '切换账号中': 'Switching account', '同步会话中': 'Syncing sessions', '恢复原账号': 'Restoring original account', '正在安全停止': 'Stopping safely', '等待同步安全收尾': 'Waiting for sync to finish safely','检测到会话异常中断,自动让它继续': 'Detected an interrupted session; letting it continue automatically.','暂存想法择机发送,发送后自动删除': 'Stashed thoughts send at an opportunity, then are deleted automatically.','悬停预览,点击或拖动快速定位消息': 'Hover to preview; click or drag to jump to a message.',@@ -1538,6 +1547,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 4h6M4 4v6M20 4h-6M20 4v6M4 20h6M4 20v-6M20 20h-6M20 20v-6"/><circle cx="12" cy="12" r="2.5"/></svg>';var AUTO_DISCOVER_SVG ='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>';+ var AUTO_FAVORITE_SVG =+ '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round" aria-hidden="true"><path d="m12 3.7 2.55 5.17 5.71.83-4.13 4.03.98 5.69L12 16.73l-5.11 2.69.98-5.69L3.74 9.7l5.71-.83L12 3.7Z"/></svg>';var GIFT_SVG ='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +'<rect x="3" y="8" width="18" height="4" rx="1"/>' +@@ -2037,6 +2048,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {popoverTimer: null,observer: null,state: null,+ // 性能缓存:避免 800ms 轮询反复全量扫描/强制布局+ ctrlCacheId: null,+ ctrlCache: null,+ ctrlScanTick: 0,+ geoEls: null,+ lastWrite: null,+ lastSig: '',};var CONVERSATION_USAGE_ENABLED_KEY = 'workdaddy.session.conversationUsageEnabled';var conversationUsageEnabled = true;@@ -2075,11 +2093,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function usageController(id) {if (!WBS_COMPAT || typeof WBS_COMPAT.findConversationControllers !== 'function') return null;+ var key = String(id || '');+ // 缓存命中:同会话且 controller 仍有效时跳过全文档 React 扫描(每 12 tick 强制重扫兜底)+ conversationUsage.ctrlScanTick++;+ var cached = conversationUsage.ctrlCache;+ if (cached && conversationUsage.ctrlCacheId === key && cached.messageStore && conversationUsage.ctrlScanTick % 12 !== 0) {+ return cached;+ }var controllers = [];try { controllers = WBS_COMPAT.findConversationControllers(document) || []; } catch (_) {}for (var i = 0; i < controllers.length; i++) {- if (!id || String(controllers[i].conversationId || '') === String(id)) return controllers[i];+ if (!id || String(controllers[i].conversationId || '') === String(id)) {+ conversationUsage.ctrlCache = controllers[i];+ conversationUsage.ctrlCacheId = String(controllers[i].conversationId || '');+ return controllers[i];+ }}+ conversationUsage.ctrlCache = null;+ conversationUsage.ctrlCacheId = null;return null;}function hideUsagePopover() {@@ -2162,23 +2193,50 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!summary || !surface || !conversationUsageEnabled) return;var contentRect = surface.content.getBoundingClientRect();if (!contentRect || contentRect.width <= 0) return;- var inputArea = document.querySelector('.conversation-input-area,.conversation-input,.cr-input-box');- var inputRect = inputArea && inputArea.getBoundingClientRect();- var viewport = surface.content.closest('.cr-message-list-viewport');- var viewportRect = viewport && viewport.getBoundingClientRect();- var bottomMask = document.querySelector('.cr-message-list__bottom-mask');- var maskRect = bottomMask && bottomMask.getBoundingClientRect();+ // 元素引用缓存(断连才重新 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))) {+ geo = {+ inputArea: document.querySelector('.conversation-input-area,.conversation-input,.cr-input-box'),+ viewport: surface.content.closest('.cr-message-list-viewport'),+ bottomMask: document.querySelector('.cr-message-list__bottom-mask'),+ };+ conversationUsage.geoEls = geo;+ }+ var inputRect = geo.inputArea && geo.inputArea.getBoundingClientRect();+ var viewportRect = geo.viewport && geo.viewport.getBoundingClientRect();+ 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;left = Math.max(8, left);- summary.style.left = Math.round(left) + 'px';+ 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)),+ };+ var last = conversationUsage.lastWrite;+ // 几何未变化时跳过样式写入,避免每次都触发 style invalidation+ if (last && last.left === write.left && last.maxWidth === write.maxWidth && last.bottom === write.bottom) {+ if (conversationUsage.spacer && conversationUsage.spacer.parentNode) {+ var sh = Math.ceil(summary.getBoundingClientRect().height || 34);+ if (last.spacerH !== sh) {+ conversationUsage.spacer.style.height = sh + 'px';+ last.spacerH = sh;+ }+ }+ return;+ }+ conversationUsage.lastWrite = write;+ summary.style.left = write.left + 'px';summary.style.width = 'max-content';- summary.style.maxWidth = Math.round(Math.min(maxWidth, window.innerWidth - left - 8)) + 'px';- summary.style.bottom = Math.round(Math.max(0, window.innerHeight - anchorBottom)) + 'px';+ summary.style.maxWidth = write.maxWidth + 'px';+ summary.style.bottom = write.bottom + 'px';if (conversationUsage.spacer && conversationUsage.spacer.parentNode) {- conversationUsage.spacer.style.height = Math.ceil(summary.getBoundingClientRect().height || 34) + 'px';+ var sh2 = Math.ceil(summary.getBoundingClientRect().height || 34);+ conversationUsage.spacer.style.height = sh2 + 'px';+ write.spacerH = sh2;}}function showUsagePopover() {@@ -2268,9 +2326,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var popover = el('div', 'wbs-session-usage-popover');popover.id = 'wbs-session-usage-popover';popover.setAttribute('role', 'tooltip');- popover.appendChild(el('div', 'wbs-session-usage-detail-title', '本会话用量明细'));- popover.appendChild(el('div', 'wbs-session-usage-detail-total'));- popover.appendChild(el('div', 'wbs-session-usage-detail-note', '提示:部分会话尚未完成,当前 Token 和积分仅按已完成用量统计,最终数据可能存在偏差。'));+ var detailTitleRow = el('div', 'wbs-session-usage-detail-title-row');+ detailTitleRow.appendChild(el('div', 'wbs-session-usage-detail-title', '本会话用量明细'));+ detailTitleRow.appendChild(el('div', 'wbs-session-usage-detail-total'));+ popover.appendChild(detailTitleRow);+ popover.appendChild(el('div', 'wbs-session-usage-detail-note', '用量统计会随会话完成逐步更新。'));var detailHead = el('div', 'wbs-session-usage-detail-head');detailHead.appendChild(el('span', '', '模型'));detailHead.appendChild(el('span', '', '调用'));@@ -2296,9 +2356,27 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {document.body.appendChild(conversationUsage.summary);}}+ // 变更签名:流式期间 store 频繁触发,只有消息数/末条状态变化才重算(800ms tick 与 subscribe 共用)+ function usageSignature(messages) {+ if (!Array.isArray(messages) || !messages.length) return '0';+ var last = messages[messages.length - 1] || {};+ var usage = last.usage || {};+ return messages.length + '|' + (last.id || '') + '|' + (last.complete ? 1 : 0) + '|' ++ (usage.total_tokens != null ? usage.total_tokens : (usage.totalTokens != null ? usage.totalTokens : ''));+ }+ function maybeRenderUsage(messages) {+ var sig = usageSignature(messages);+ if (sig === conversationUsage.lastSig) return;+ conversationUsage.lastSig = sig;+ renderConversationUsage(collectConversationUsage(messages));+ }function bindUsageController(controller) {if (conversationUsage.controller === controller) {- if (controller && controller.messageStore) renderConversationUsage(collectConversationUsage(controller.messageStore.getState().messages));+ if (controller && controller.messageStore) {+ var cur = null;+ try { cur = controller.messageStore.getState(); } catch (_) { cur = null; }+ maybeRenderUsage(cur && cur.messages);+ }return;}if (conversationUsage.unsubscribe) {@@ -2306,15 +2384,25 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {conversationUsage.unsubscribe = null;}conversationUsage.controller = controller || null;+ conversationUsage.lastSig = '';renderConversationUsage(null);if (!controller || !controller.messageStore) return;var store = controller.messageStore;+ var refreshScheduled = false;function refresh(state) {if (conversationUsage.controller !== controller) return;- if (!state || !Array.isArray(state.messages)) {- try { state = store.getState(); } catch (_) { state = null; }- }- renderConversationUsage(collectConversationUsage(state && state.messages));+ if (refreshScheduled) return;+ refreshScheduled = true;+ var raf = window.requestAnimationFrame || function (cb) { return window.setTimeout(cb, 16); };+ raf(function () {+ refreshScheduled = false;+ if (conversationUsage.controller !== controller) return;+ var s = state;+ if (!s || !Array.isArray(s.messages)) {+ try { s = store.getState(); } catch (_) { s = null; }+ }+ maybeRenderUsage(s && s.messages);+ });}try { conversationUsage.unsubscribe = store.subscribe(refresh); } catch (_) { conversationUsage.unsubscribe = null; }try { refresh(store.getState()); } catch (_) {}@@ -2357,10 +2445,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {positionUsagePopover();updateConversationUsageScrollState();});- listen(window, 'scroll', function () {- positionConversationUsage();- if (conversationUsage.popover && conversationUsage.popover.classList.contains('is-visible')) positionUsagePopover();- }, true);+ var usagePosFrame = null;+ function scheduleUsageReposition() {+ if (usagePosFrame != null) return;+ var raf = window.requestAnimationFrame || function (cb) { return window.setTimeout(cb, 16); };+ usagePosFrame = raf(function () {+ usagePosFrame = null;+ positionConversationUsage();+ if (conversationUsage.popover && conversationUsage.popover.classList.contains('is-visible')) positionUsagePopover();+ });+ }+ listen(window, 'scroll', scheduleUsageReposition, true);setBuildInterval(syncConversationUsage, 800);setBuildTimeout(syncConversationUsage, 120);registerDisposer(function () {@@ -6566,7 +6661,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return latest && comparePackageVersions(latest.packageVersion, info.packageVersion) > 0 ? latest : null;}function defaultTask() {- return { schemaVersion: 2, id: 'task_' + Date.now().toString(36), name: '新自动化任务', description: '', enabled: true, concurrency: { policy: 'skip' }, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [] };+ return { schemaVersion: 3, id: 'task_' + Date.now().toString(36), name: '新自动化任务', description: '', enabled: true, concurrency: { policy: 'skip' }, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [] };}function triggerBadgesHtml(task) {var trigger = task.trigger || {};@@ -6584,7 +6679,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function taskStatusLabel(task, run, stopping) {if (task.compatible === false) return '任务不兼容';if (stopping) return '正在停止…';- if (run && run.status === 'running') return run.phase === 'queued' ? '排队中' : '执行中';+ if (run && run.status === 'running') {+ var phases = { queued: '排队中', 'waiting-sync': '等待会话同步', 'switching-account': '切换账号中', 'syncing-sessions': '同步会话中', 'restoring-account': '恢复原账号', stopping: '正在安全停止', 'stopping-sync': '等待同步安全收尾' };+ var label = phases[run.phase] || '执行中';+ return label + (run.sync ? ' ' + run.sync.processed + '/' + run.sync.total : '');+ }if (!task.enabled && !task.manualRunnable) return '已停用';var events = task.trigger && (Array.isArray(task.trigger.types) ? task.trigger.types : [task.trigger.type]) || [];if (task.schedule && task.schedule.type === 'once' && new Date(task.schedule.at).getTime() + 60000 <= Date.now() && !events.some(function (type) { return type && type !== 'manual'; })) return '定时已结束';@@ -6626,7 +6725,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!still) delete automationState.stopping[rid];});}- var stopping = running && run && !!automationState.stopping[run.id]; // 已点停止、等待 daemon 确认结束+ var stopping = running && run && !!(run.stopRequested || automationState.stopping[run.id]); // 已点停止、等待 daemon 确认结束var active = running || stopping;var check = automationState.batchMode ? '<label class="wbs-auto-check"><input type="checkbox" data-auto-select="' + escAttr(task.id) + '"' + (automationState.selected[task.id] ? ' checked' : '') + '><span></span></label>' : '';var stateClass = active ? 'running' : !task.enabled && !task.manualRunnable ? 'off' : 'idle';@@ -6687,29 +6786,41 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var list = mask.querySelector('.wbs-auto-discovery-list');var query = mask.querySelector('.wbs-auto-discovery-search').value;var tasks = automationState.discovery && automationState.discovery.tasks || [];- var matches = tasks.filter(function (task) { return fuzzyTaskName(task.name, query); });+ var favoritesOnly = mask.__wbsDiscoveryFavoritesOnly === true;+ var matches = tasks.filter(function (task) { return (!favoritesOnly || task.favorited === true) && fuzzyTaskName(task.name, query); });+ matches.sort(function (left, right) {+ return (Number(right.favoriteCount) || 0) - (Number(left.favoriteCount) || 0);+ });var pageSize = 8;var pages = Math.max(1, Math.ceil(matches.length / pageSize));var page = mask.__wbsDiscoveryPage = Math.min(Math.max(1, mask.__wbsDiscoveryPage || 1), pages);- mask.querySelector('.wbs-auto-discovery-total').textContent = '共 ' + tasks.length + ' 个任务' + (query.trim() ? ' · 匹配 ' + matches.length + ' 个' : '');+ mask.querySelector('.wbs-auto-discovery-total').textContent = favoritesOnly ? '我的收藏 ' + matches.length + ' 个' : '共 ' + tasks.length + ' 个任务' + (query.trim() ? ' · 匹配 ' + matches.length + ' 个' : '');mask.querySelector('.wbs-auto-discovery-page').textContent = page + ' / ' + pages;mask.querySelector('[data-auto-discovery-page="prev"]').disabled = page <= 1;mask.querySelector('[data-auto-discovery-page="next"]').disabled = page >= pages;list.innerHTML = '';if (!matches.length) {var empty = document.createElement('div'); empty.className = 'wbs-auto-discovery-empty';- empty.textContent = tasks.length ? '没有匹配的任务' : (automationState.discoveryError || '暂未发现公开任务');+ empty.textContent = favoritesOnly && tasks.length ? '暂无收藏的任务' : tasks.length ? '没有匹配的任务' : (automationState.discoveryError || '暂未发现公开任务');list.appendChild(empty); return;}matches.slice((page - 1) * pageSize, page * pageSize).forEach(function (task) {var item = document.createElement('section'); item.className = 'wbs-auto-discovery-item';- item.innerHTML = '<div class="wbs-auto-discovery-head"><div class="wbs-auto-discovery-name" data-wbs-i18n-skip="1"></div><span class="wbs-auto-discovery-version"></span><span class="wbs-auto-discovery-update" hidden>新版</span></div><div class="wbs-auto-discovery-description" data-wbs-i18n-skip="1"></div><div class="wbs-auto-discovery-foot"><div class="wbs-auto-sources"></div><button class="wbs-modal-btn wbs-modal-ok" type="button" data-auto-discovery-import></button></div>';+ item.innerHTML = '<div class="wbs-auto-discovery-head"><div class="wbs-auto-discovery-name" data-wbs-i18n-skip="1"></div><span class="wbs-auto-discovery-version"></span><span class="wbs-auto-discovery-update" hidden>新版</span><button class="wbs-auto-discovery-favorite" type="button" data-auto-discovery-favorite aria-label="收藏任务" title="收藏任务" aria-pressed="false">' + AUTO_FAVORITE_SVG + '<span data-auto-discovery-favorite-count>0</span></button></div><div class="wbs-auto-discovery-description" data-wbs-i18n-skip="1"></div><div class="wbs-auto-discovery-foot"><div class="wbs-auto-sources"></div><button class="wbs-modal-btn wbs-modal-ok" type="button" data-auto-discovery-import></button></div>';item.querySelector('.wbs-auto-discovery-name').textContent = task.name || '未命名任务';item.querySelector('.wbs-auto-discovery-version').textContent = task.packageVersion ? 'v' + task.packageVersion : 'API V' + (Number(task.schemaVersion) || 1);var installed = installedPackage(task.packageId);var installedInfo = importedPackage(installed);var hasUpdate = !!(installedInfo && task.packageVersion && comparePackageVersions(task.packageVersion, installedInfo.packageVersion) > 0);item.querySelector('.wbs-auto-discovery-update').hidden = !hasUpdate;+ var favoriteButton = item.querySelector('[data-auto-discovery-favorite]');+ var favoriteCount = Math.max(0, Number(task.favoriteCount) || 0);+ favoriteButton.setAttribute('data-auto-discovery-favorite', task.key || '');+ favoriteButton.classList.toggle('is-active', task.favorited === true);+ favoriteButton.setAttribute('aria-pressed', String(task.favorited === true));+ favoriteButton.setAttribute('aria-label', task.favorited === true ? '取消收藏' : '收藏任务');+ favoriteButton.title = task.favorited === true ? '取消收藏' : '收藏任务';+ favoriteButton.querySelector('[data-auto-discovery-favorite-count]').textContent = String(favoriteCount);var description = item.querySelector('.wbs-auto-discovery-description');description.textContent = task.description || '暂无说明';var sources = item.querySelector('.wbs-auto-sources');@@ -6746,12 +6857,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function showAutomationDiscovery() {closePanelModal(root.querySelector('#wbs-auto-discovery-mask'));var mask = document.createElement('div'); mask.id = 'wbs-auto-discovery-mask'; mask.className = 'wbs-modal-mask wbs-usage-modal-mask wbs-auto-dialog-mask';- mask.innerHTML = '<div class="wbs-modal wbs-token-stats-modal wbs-auto-discovery-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-discovery-title"><div class="wbs-usage-header wbs-auto-discovery-header"><div class="wbs-auto-modal-head"><div><div class="wbs-modal-title" id="wbs-auto-discovery-title">发现更多自动化任务</div><div class="wbs-auto-discovery-note">这些任务来自互联网公开仓库,均为第三方内容,与 WorkDaddy 无归属关系。导入后默认停用,请先安全评估再启用。</div><div class="wbs-auto-discovery-note wbs-auto-discovery-status" hidden>部分来源暂时无法访问,当前显示上次缓存的结果。</div></div><div class="wbs-auto-discovery-head-actions"><button class="wbs-auto-textbtn" type="button" data-auto-discovery-guide>我也要出现在这里</button><button class="wbs-auto-modal-close" type="button" data-auto-close title="关闭" aria-label="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></div></div><input class="wbs-auto-discovery-search" type="search" maxlength="120" aria-label="搜索任务名称" placeholder="搜索任务名称"></div><div class="wbs-usage-scroll wbs-auto-discovery-list"></div><div class="wbs-modal-actions wbs-auto-discovery-pagination"><span class="wbs-auto-discovery-total" role="status"></span><button class="wbs-modal-btn" type="button" data-auto-discovery-page="prev" aria-label="上一页">上一页</button><span class="wbs-auto-discovery-page"></span><button class="wbs-modal-btn" type="button" data-auto-discovery-page="next" aria-label="下一页">下一页</button></div></div>';+ mask.innerHTML = '<div class="wbs-modal wbs-token-stats-modal wbs-auto-discovery-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-discovery-title"><div class="wbs-usage-header wbs-auto-discovery-header"><div class="wbs-auto-modal-head"><div><div class="wbs-modal-title" id="wbs-auto-discovery-title">发现更多自动化任务</div><div class="wbs-auto-discovery-note">这些任务来自互联网公开仓库,均为第三方内容,与 WorkDaddy 无归属关系。导入后默认停用,请先安全评估再启用。</div><div class="wbs-auto-discovery-note wbs-auto-discovery-status" hidden>部分来源暂时无法访问,当前显示上次缓存的结果。</div></div><div class="wbs-auto-discovery-head-actions"><button class="wbs-auto-textbtn" type="button" data-auto-discovery-guide>我也要出现在这里</button><button class="wbs-auto-modal-close" type="button" data-auto-close title="关闭" aria-label="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></div></div><div class="wbs-auto-discovery-toolbar"><input class="wbs-auto-discovery-search" type="search" maxlength="120" aria-label="搜索任务名称" placeholder="搜索任务名称"><button class="wbs-auto-discovery-filter" type="button" data-auto-discovery-filter="favorites" aria-pressed="false">我的收藏</button></div></div><div class="wbs-usage-scroll wbs-auto-discovery-list"></div><div class="wbs-modal-actions wbs-auto-discovery-pagination"><span class="wbs-auto-discovery-total" role="status"></span><button class="wbs-modal-btn" type="button" data-auto-discovery-page="prev" aria-label="上一页">上一页</button><span class="wbs-auto-discovery-page"></span><button class="wbs-modal-btn" type="button" data-auto-discovery-page="next" aria-label="下一页">下一页</button></div></div>';mask.querySelector('.wbs-auto-discovery-status').hidden = !(automationState.discovery && automationState.discovery.stale);mountAutomationModal(mask);renderAutomationDiscovery(mask);var search = mask.querySelector('.wbs-auto-discovery-search');search.addEventListener('input', function () { mask.__wbsDiscoveryPage = 1; renderAutomationDiscovery(mask); mask.querySelector('.wbs-auto-discovery-list').scrollTop = 0; });+ mask.querySelector('[data-auto-discovery-filter="favorites"]').addEventListener('click', function (event) {+ mask.__wbsDiscoveryFavoritesOnly = !mask.__wbsDiscoveryFavoritesOnly;+ event.currentTarget.setAttribute('aria-pressed', String(mask.__wbsDiscoveryFavoritesOnly));+ event.currentTarget.classList.toggle('active', mask.__wbsDiscoveryFavoritesOnly);+ mask.__wbsDiscoveryPage = 1;+ renderAutomationDiscovery(mask);+ mask.querySelector('.wbs-auto-discovery-list').scrollTop = 0;+ });mask.querySelector('[data-auto-discovery-guide]').addEventListener('click', showAutomationDiscoveryGuide);mask.querySelector('.wbs-auto-discovery-pagination').addEventListener('click', function (event) {var button = event.target.closest && event.target.closest('[data-auto-discovery-page]');@@ -6761,6 +6880,22 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {mask.querySelector('.wbs-auto-discovery-list').scrollTop = 0;});mask.querySelector('.wbs-auto-discovery-list').addEventListener('click', function (event) {+ var favoriteButton = event.target.closest && event.target.closest('[data-auto-discovery-favorite]');+ if (favoriteButton) {+ if (favoriteButton.disabled) return;+ var favoriteKey = favoriteButton.getAttribute('data-auto-discovery-favorite');+ var nextFavorite = favoriteButton.getAttribute('aria-pressed') !== 'true';+ favoriteButton.disabled = true;+ api('/api/automations/discovery/favorite', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key: favoriteKey, favorite: nextFavorite }) }).then(function (result) {+ var task = (automationState.discovery && automationState.discovery.tasks || []).filter(function (item) { return item.key === favoriteKey; })[0];+ if (task) { task.favorited = result.favorited === true; task.favoriteCount = Math.max(0, Number(result.favoriteCount) || 0); }+ renderAutomationDiscovery(mask);+ }).catch(function (error) {+ favoriteButton.disabled = false;+ toast(error.message || '收藏失败', true, root);+ });+ return;+ }var source = event.target.closest && event.target.closest('[data-auto-discovery-source]');if (source) {var url = source.getAttribute('data-auto-discovery-source');@@ -7067,7 +7202,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (typeof window.__wbsStartAutomationPicker === 'function') window.__wbsStartAutomationPicker();else toast('元素拾取器尚未加载', true, root);}- automationPane.innerHTML = '<div class="wbs-pcard wbs-auto-card"><div class="wbs-auto-toolbar"><div class="wbs-pcard-title">自动化<span class="wbs-pcard-sub" id="wbs-auto-count"></span></div><button type="button" class="wbs-auto-textbtn" id="wbs-auto-cap">自动化接口协议 V2</button><div class="wbs-auto-toolbar-actions"><div class="wbs-auto-normal-actions" id="wbs-auto-normal-actions"><button class="wbs-sess-bbtn wbs-auto-pick-btn is-loading" type="button" id="wbs-auto-discover" disabled>' + AUTO_DISCOVER_SVG + '<span>正在发现…</span></button><button class="wbs-sess-bbtn wbs-auto-pick-btn" type="button" id="wbs-auto-pick">' + AUTO_PICK_SVG + '<span>拾取元素</span></button><div class="wbs-auto-right-actions"><button class="wbs-sess-bbtn" type="button" id="wbs-auto-create">让 WorkBuddy 帮我创建</button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-batch">批量操作</button></div></div><div class="wbs-auto-batch-actions" id="wbs-auto-batch-actions" style="display:none"><span class="wbs-auto-batch-count" id="wbs-auto-batch-count">已选 0</span><button class="wbs-sess-bbtn" type="button" id="wbs-auto-select-all">全选</button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-export" disabled>' + EXPORT_ICON + '<span>导出</span></button><button class="wbs-sess-bbtn wbs-sess-delbtn" type="button" id="wbs-auto-batch-apply">' + TRASH_SVG + '<span>删除选中</span></button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-batch-cancel">取消</button></div></div></div><div class="wbs-auto-list" id="wbs-auto-list"></div></div>';+ automationPane.innerHTML = '<div class="wbs-pcard wbs-auto-card"><div class="wbs-auto-toolbar"><div class="wbs-pcard-title">自动化<span class="wbs-pcard-sub" id="wbs-auto-count"></span></div><button type="button" class="wbs-auto-textbtn" id="wbs-auto-cap">自动化接口协议 V3</button><div class="wbs-auto-toolbar-actions"><div class="wbs-auto-normal-actions" id="wbs-auto-normal-actions"><button class="wbs-sess-bbtn wbs-auto-pick-btn is-loading" type="button" id="wbs-auto-discover" disabled>' + AUTO_DISCOVER_SVG + '<span>正在发现…</span></button><button class="wbs-sess-bbtn wbs-auto-pick-btn" type="button" id="wbs-auto-pick">' + AUTO_PICK_SVG + '<span>拾取元素</span></button><div class="wbs-auto-right-actions"><button class="wbs-sess-bbtn" type="button" id="wbs-auto-create">让 WorkBuddy 帮我创建</button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-batch">批量操作</button></div></div><div class="wbs-auto-batch-actions" id="wbs-auto-batch-actions" style="display:none"><span class="wbs-auto-batch-count" id="wbs-auto-batch-count">已选 0</span><button class="wbs-sess-bbtn" type="button" id="wbs-auto-select-all">全选</button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-export" disabled>' + EXPORT_ICON + '<span>导出</span></button><button class="wbs-sess-bbtn wbs-sess-delbtn" type="button" id="wbs-auto-batch-apply">' + TRASH_SVG + '<span>删除选中</span></button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-batch-cancel">取消</button></div></div></div><div class="wbs-auto-list" id="wbs-auto-list"></div></div>';automationPane.querySelector('#wbs-auto-export').addEventListener('click', exportAutomationTasks);automationPane.querySelector('#wbs-auto-pick').addEventListener('click', startPicker);automationPane.querySelector('#wbs-auto-cap').addEventListener('click', showCapabilities);@@ -7110,7 +7245,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (stopRunId) automationState.stopping[stopRunId] = true;render(); // 立即进入“正在停止”转圈 + 置灰态api('/api/automations/stop', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ runId: id }) })- .then(function () { toast('任务已停止', false, root); return load(); })+ .then(function (result) { toast(result && result.run && result.run.status === 'running' ? '正在安全停止' : '任务已停止', false, root); return load(); }).catch(function (err) { toast(err.message || '停止失败', true, root); }).finally(function () {// 保持转圈至少一小段可感知窗口,再撤掉“停止中”标记,让按钮回到“运行”@@ -7138,7 +7273,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}// ===== 会话 pane(构建:账号/时间筛选 + 按空间分组[默认2条/展开10条] + 刷新 + 批量操作[迁移/删除])=====- var sessionsState = { uid: undefined, currentUid: '', range: 'all', list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null, autoCopyAll: false, autoCopyJob: null, autoCopyPollTimer: null };+ var sessionsState = { uid: undefined, currentUid: '', range: 'all', minBytes: 0, totalBytes: null, list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null, autoCopyAll: false, autoCopyJob: null, autoCopyPollTimer: null };function isTaskSessionRecordUI(s) {// 任务(未选择项目/一次性)会话:以官方 is_playground=1 为准。// 普通工作区也用 WorkBuddy\\YYYY-MM-DD-HH-MM-SS 命名,仅凭 cwd 无法区分。@@ -7184,6 +7319,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {else if (job.status === 'conflict') detail += ' · ' + (Number(job.conflicts) || 1) + ' 个会话已分叉,已保留双方内容';else if (job.status === 'partial') detail += ' · 有 ' + ((Number(job.failed) || 0) + (Number(job.partial) || 0)) + ' 项需要留意';else if (job.status === 'error') detail += ' · 请稍后重试';+ if (job.warning) detail += ' · ' + job.warning;box.className = 'wbs-sess-copy-progress is-' + String(job.status || 'running');box.querySelector('.wbs-sess-copy-title').textContent = title;box.querySelector('.wbs-sess-copy-detail').textContent = detail;@@ -7212,19 +7348,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {sessionsPane.innerHTML ='<div class="wbs-pcard">' +'<div class="wbs-sess-filters">' +- '<button class="wbs-sess-auto-all" type="button" id="wbs-sess-auto-all" role="checkbox" aria-checked="false" aria-label="自动同步所有会话" title="切换账号时自动同步当前账号的所有会话,包括之后新增的会话">' +- '<span class="wbs-sess-auto-all-box" aria-hidden="true"><svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="12" height="12" rx="2"/><path class="wbs-sess-auto-all-check" d="m4.5 8 2.2 2.2L11.5 5.5"/></svg></span>' +- '<span class="wbs-sess-auto-all-label">自动同步所有会话</span>' +- '</button>' +'<div class="wbs-sess-filter-row wbs-sess-account-filter"><span class="wbs-sess-flabel">账号</span><select class="wbs-sess-select" id="wbs-sess-account-select" title="选择要查看的账号"><option value="">加载中…</option></select></div>' ++ '<div class="wbs-sess-filter-row wbs-sess-size-filter"><span class="wbs-sess-flabel">大小</span><div class="wbs-usage-segment wbs-sess-seg" id="wbs-sess-size-seg" role="group" aria-label="筛选会话大小">' ++ '<button class="wbs-sess-seg-btn active" type="button" aria-pressed="true" data-min-bytes="0">全部</button>' ++ '<button class="wbs-sess-seg-btn" type="button" aria-pressed="false" data-min-bytes="10485760">> 10 MB</button>' ++ '<button class="wbs-sess-seg-btn" type="button" aria-pressed="false" data-min-bytes="104857600">> 100 MB</button>' ++ '</div></div>' +'<div class="wbs-sess-filter-row wbs-sess-time-filter"><span class="wbs-sess-flabel">时间</span><div class="wbs-usage-segment wbs-sess-seg" id="wbs-sess-range-seg">' ++ '<button class="wbs-sess-seg-btn active" type="button" aria-pressed="true" data-range="all">全部</button>' +'<button class="wbs-sess-seg-btn" type="button" aria-pressed="false" data-range="today">今天</button>' +'<button class="wbs-sess-seg-btn" type="button" aria-pressed="false" data-range="7d">近 7 天</button>' +'<button class="wbs-sess-seg-btn" type="button" aria-pressed="false" data-range="30d">近 30 天</button>' +- '<button class="wbs-sess-seg-btn active" type="button" aria-pressed="true" data-range="all">全部</button>' +'</div></div>' +'</div>' +'<div class="wbs-sess-toolbar">' ++ '<button class="wbs-sess-auto-all" type="button" id="wbs-sess-auto-all" role="checkbox" aria-checked="false" aria-label="自动同步所有会话" title="切换账号时自动同步当前账号的所有会话,包括之后新增的会话">' ++ '<span class="wbs-sess-auto-all-box" aria-hidden="true"><svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="12" height="12" rx="2"/><path class="wbs-sess-auto-all-check" d="m4.5 8 2.2 2.2L11.5 5.5"/></svg></span>' ++ '<span class="wbs-sess-auto-all-label">自动同步所有会话</span>' ++ '</button>' +'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-batch">批量操作</button>' +'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-import" title="从加密文件导入会话">' + IMPORT_ICON + '<span>导入</span></button>' +'<span class="wbs-sess-count" id="wbs-sess-count"></span>' +@@ -7303,6 +7444,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {api(url).then(function (d) {// 任务会话(is_playground=1)保留在列表中,由渲染层归入「任务」分组展示与操作。sessionsState.list = ((d && d.sessions) || []);+ sessionsState.totalBytes = d && d.totalBytes;sessionsState.autoCopy = (d && d.autoCopy) || null;sessionsState.autoCopyAll = !!(d && d.autoCopyAll);sessionsState.selected = {};@@ -7319,13 +7461,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});}+ function filteredSessions() {+ var minBytes = Number(sessionsState.minBytes) || 0;+ return sessionsState.list.filter(function (session) {+ return !minBytes || (typeof session.totalBytes === 'number' && isFinite(session.totalBytes) && session.totalBytes > minBytes);+ });+ }+// 按空间分组渲染:每个空间最多显示 INIT 条 + 展开按钮(每次 +STEP)。function renderSessions() {var listEl = sessionsPane.querySelector('#wbs-sess-list');var countEl = sessionsPane.querySelector('#wbs-sess-count');if (!listEl) return;updateAutoCopyAllButton();- if (!sessionsState.list.length) {+ if (!filteredSessions().length) {listEl.innerHTML = '<div class="wbs-empty">当前筛选下没有会话</div>';updateSessionSummary(countEl);return;@@ -7340,7 +7489,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var tasks = [];var groups = {};var wsOrder = [];- sessionsState.list.forEach(function (s) {+ filteredSessions().forEach(function (s) {if (isTaskSessionRecordUI(s)) { tasks.push(s); return; }var cwd = s.cwd || '(未指定空间)';var owner = String(s.user_id || sessionsState.uid || '');@@ -7348,7 +7497,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!groups[groupKey]) { groups[groupKey] = { cwd: cwd, uid: owner, items: [] }; wsOrder.push(groupKey); }groups[groupKey].items.push(s);});- var total = sessionsState.list.length;var html = '';var batch = sessionsState.batchMode;if (tasks.length) {@@ -7373,6 +7521,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<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 ? '' : autoCopyButton('session', s.id, s.user_id, marked, inherited)) ++ '<span class="wbs-sess-size" title="会话大小(消息和附件)">' + sessionCopySizeText(s.totalBytes) + '</span>' +'</div>';});if (taskMore > 0) html += '<button class="wbs-sess-more" type="button" data-ws="__TASKS__">展开 ' + Math.min(taskMore, SESS_WS_STEP) + ' 条(剩余 ' + taskMore + ')</button>';@@ -7404,6 +7553,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<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 ? '' : autoCopyButton('session', s.id, s.user_id, marked, inherited)) ++ '<span class="wbs-sess-size" title="会话大小(消息和附件)">' + sessionCopySizeText(s.totalBytes) + '</span>' +'</div>';});if (more > 0) html += '<button class="wbs-sess-more" type="button" data-ws="' + escAttr(groupKey) + '">展开 ' + Math.min(more, SESS_WS_STEP) + ' 条(剩余 ' + more + ')</button>';@@ -7414,15 +7564,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {bindSessEvents(listEl);}function activeAutoCopyCount() {- if (sessionsState.autoCopyAll) return sessionsState.list.length;- return sessionsState.list.filter(function (s) {+ if (sessionsState.autoCopyAll) return filteredSessions().length;+ return filteredSessions().filter(function (s) {return !!s.autoCopySession || !!s.autoCopyWorkspace;}).length;}function updateSessionSummary(countEl) {if (!countEl) return;- countEl.innerHTML = '<span class="wbs-sess-summary-tag">共 ' + sessionsState.list.length + ' 个会话</span>' +- '<span class="wbs-sess-summary-tag wbs-sess-summary-auto">自动同步 ' + activeAutoCopyCount() + '</span>';+ countEl.innerHTML = '<span class="wbs-sess-summary-tag">共 <strong>' + sessionCopyCountText(filteredSessions().length) + '</strong> 个会话</span>' ++ '<span class="wbs-sess-summary-tag wbs-sess-summary-auto">自动同步 <strong>' + sessionCopyCountText(activeAutoCopyCount()) + '</strong></span>' ++ '<span class="wbs-sess-summary-tag wbs-sess-summary-size" title="所选账号全部会话的大小,不受时间和大小筛选影响">总大小 <strong>' + sessionCopySizeText(sessionsState.totalBytes) + '</strong></span>';}function updateAutoCopyAllButton() {if (!sessionsPane) return;@@ -7476,7 +7627,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var wsCheck = t.closest ? t.closest('.wbs-ws-check') : null;if (wsCheck) {var w = wsCheck.getAttribute('data-ws');- var arr = sessionsState.list.filter(function (s) {+ var arr = filteredSessions().filter(function (s) {if (w === '__TASKS__') return isTaskSessionRecordUI(s);return String(s.user_id || sessionsState.uid || '') + '::' + (s.cwd || '(未指定空间)') === w;});@@ -7568,7 +7719,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});}function updateSessCount() {- var n = sessionsState.list.filter(function (s) { return sessionsState.selected[s.id]; }).length;+ var n = filteredSessions().filter(function (s) { return sessionsState.selected[s.id]; }).length;var countEl = sessionsPane.querySelector('#wbs-sess-count');updateSessionSummary(countEl);// 批量模式下「已选 N」显示在批量操作行内(模型页同款排版)@@ -7590,7 +7741,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!sessionsPane) return;var btn = sessionsPane.querySelector('#wbs-sess-check-all');if (!btn) return;- var selectable = sessionsState.list.slice();+ var selectable = filteredSessions();var allSel = selectable.length > 0 && selectable.every(function (s) { return sessionsState.selected[s.id]; });btn.textContent = allSel ? '取消全选' : '全选';}@@ -7624,6 +7775,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function wireSessionsPane() {+ var sizeSeg = sessionsPane.querySelector('#wbs-sess-size-seg');+ if (sizeSeg) sizeSeg.addEventListener('click', function (e) {+ var button = e.target.closest ? e.target.closest('.wbs-sess-seg-btn') : null;+ if (!button || button.disabled || sessionsState.batchMode) return;+ sizeSeg.querySelectorAll('.wbs-sess-seg-btn').forEach(function (item) {+ var active = item === button;+ item.classList.toggle('active', active);+ item.setAttribute('aria-pressed', String(active));+ });+ sessionsState.minBytes = Number(button.getAttribute('data-min-bytes')) || 0;+ sessionsState.selected = {};+ sessionsState.wsExpanded = {};+ renderSessions();+ updateSessCount();+ });var autoCopyAllBtn = sessionsPane.querySelector('#wbs-sess-auto-all');if (autoCopyAllBtn) {autoCopyAllBtn.addEventListener('click', function () {@@ -7663,7 +7829,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var checkAll = sessionsPane.querySelector('#wbs-sess-check-all');if (checkAll) {checkAll.addEventListener('click', function () {- var selectable = sessionsState.list.slice();+ var selectable = filteredSessions();var allSel = selectable.length > 0 && selectable.every(function (s) { return sessionsState.selected[s.id]; });sessionsState.selected = {};if (!allSel) selectable.forEach(function (s) { sessionsState.selected[s.id] = true; });@@ -7908,7 +8074,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {cancelBtn.focus();}function selectedSessIds() {- return sessionsState.list.filter(function (s) { return sessionsState.selected[s.id]; }).map(function (s) { return s.id; });+ return filteredSessions().filter(function (s) { return sessionsState.selected[s.id]; }).map(function (s) { return s.id; });}function showSessModal(show) {var mask = sessionsPane.querySelector('#wbs-sess-modal');@@ -13261,7 +13427,30 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function sessionCopySummaryText(job) {return '同步 ' + (Number(job && job.copied) || 0) + ' · 跳过 ' + (Number(job && job.skipped) || 0) +- ' · 失败 ' + (sessionCopyFailedItems(job) + (Number(job && job.conflicts) || 0));+ ' · 失败 ' + (sessionCopyFailedItems(job) + (Number(job && job.conflicts) || 0)) ++ (job && job.warning ? ' · ' + job.warning : '');+ }++ function sessionCopySizeText(bytes) {+ if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return '—';+ var units = ['B', 'KB', 'MB', 'GB', 'TB'];+ var unit = 0;+ while (bytes >= 1024 && unit < units.length - 1) { bytes /= 1024; unit++; }+ return (unit ? bytes.toFixed(1) : String(bytes)) + ' ' + units[unit];+ }++ function sessionCopyTransferText(job) {+ if (!job) return '';+ var completed = typeof job.processedBytes === 'number' && Number.isFinite(job.processedBytes)+ ? Math.max(0, job.processedBytes) : job.copiedBytes;+ var total = typeof job.totalBytes === 'number' && Number.isFinite(job.totalBytes) ? Math.max(0, job.totalBytes) : null;+ if (typeof completed !== 'number' || !Number.isFinite(completed)) return '';+ return '已同步 ' + sessionCopySizeText(completed) + (total == null ? '' : ' / ' + sessionCopySizeText(total));+ }++ function sessionCopyCountText(value) {+ var number = Number(value);+ return Number.isFinite(number) ? Math.max(0, Math.round(number)).toLocaleString('en-US') : '0';}function showSessionCopyDetails(job) {@@ -13297,10 +13486,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var rows = filtered.map(function (item) {var status = String(item && item.status || 'running');var note = status === 'copied' && item && item.branched ? '已复制分叉副本,原会话已保留' : status === 'conflict' ? '分叉会话尚未同步,请重试' : status === 'partial' ? '部分文件失败' : (item && item.error ? item.error : '');+ if (item && item.warning) note += (note ? ' · ' : '') + item.warning;return '<div class="wbs-session-copy-detail-row is-' + escAttr(status) + '">' +'<span class="wbs-session-copy-detail-status">' + esc(statusLabels[status] || status) + '</span>' +'<span class="wbs-session-copy-detail-label" title="' + escAttr(item && item.label || '') + '">' + esc(item && item.label || '未命名会话') + '</span>' +(note ? '<span class="wbs-session-copy-detail-note">' + esc(note) + '</span>' : '') ++ (status === 'copied' ? '<span class="wbs-session-copy-detail-size">' + sessionCopySizeText(item && item.totalBytes) + '</span>' : '') +'</div>';}).join('');list.innerHTML = rows || '<div class="wbs-session-copy-detail-empty">当前分类没有会话。</div>';@@ -13361,7 +13552,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {node.setAttribute('role', 'status');node.setAttribute('aria-live', 'polite');node.innerHTML = '<div class="wbs-session-copy-head"><span class="wbs-session-copy-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="15" height="15" 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 1v1"/></svg></span><strong class="wbs-session-copy-title">正在同步会话</strong><span class="wbs-session-copy-count">0 / 0</span><button type="button" class="wbs-session-copy-close" aria-label="关闭" title="关闭">×</button></div>' +- '<div class="wbs-session-copy-route"></div><div class="wbs-session-copy-track" role="progressbar" aria-label="会话同步进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><span class="wbs-session-copy-fill"></span></div><div class="wbs-session-copy-status"></div><div class="wbs-session-copy-summary"></div><div class="wbs-session-copy-actions" hidden><button type="button" class="wbs-session-copy-details-btn" data-session-copy-details>查看明细</button><span class="wbs-session-copy-countdown"></span></div>';+ '<div class="wbs-session-copy-route"></div><div class="wbs-session-copy-track" role="progressbar" aria-label="会话同步进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><span class="wbs-session-copy-fill"></span></div><div class="wbs-session-copy-transfer" title="同步数据量"></div><div class="wbs-session-copy-status"></div><div class="wbs-session-copy-summary"></div><div class="wbs-session-copy-actions" hidden><button type="button" class="wbs-session-copy-details-btn" data-session-copy-details>查看明细</button><span class="wbs-session-copy-countdown"></span></div>';document.body.appendChild(node);state.sessionCopyNotice = { node: node, jobId: job.id, job: null, timer: null, countdownTimer: null, closeScheduled: false, place: placeSessionCopyNotice };node.querySelector('.wbs-session-copy-close').addEventListener('click', closeSessionCopyNotice);@@ -13386,7 +13577,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {node.querySelector('.wbs-session-copy-route').textContent = sourceLabel + ' → ' + targetLabel;node.querySelector('.wbs-session-copy-status').textContent = status;node.querySelector('.wbs-session-copy-status').hidden = !active && job.status !== 'error';- node.querySelector('.wbs-session-copy-summary').textContent = active ? '已处理 ' + processed + ' 个候选会话' : sessionCopySummaryText(job);+ var summary = node.querySelector('.wbs-session-copy-summary');+ summary.textContent = active ? '' : sessionCopySummaryText(job);+ summary.hidden = active;+ var transfer = node.querySelector('.wbs-session-copy-transfer');+ transfer.textContent = sessionCopyTransferText(job);+ transfer.hidden = !transfer.textContent;var actions = node.querySelector('.wbs-session-copy-actions');actions.hidden = active;var track = node.querySelector('.wbs-session-copy-track');@@ -13689,8 +13885,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {render(data);// WorkBuddy can complete today's check-in outside WorkDaddy. Ask the// idempotent official endpoint for the current account only, then- // patch that card in place so read-only account snapshots stay read-only.- if (!WBS_PROFILE_IS_AI && CAPS.checkin !== false && data.current && data.current.uid) {+ // patch that card in place. An enabled check-in task owns the ordered+ // queue; do not let this current-account request jump ahead of it.+ if (!WBS_PROFILE_IS_AI && CAPS.checkin !== false && !data.checkinAutomationEnabled && data.current && data.current.uid) {api('/api/accounts/checkin-sync', {method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}',}).then(function (sync) {@@ -14376,9 +14573,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-session-usage-loading{color:var(--wb-icon-secondary,#667085);font-weight:400}','.wbs-session-usage-popover{position:fixed;z-index:21;width:min(390px,calc(100vw - 16px));box-sizing:border-box;padding:10px 12px;border:0;border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 90%,transparent);color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 6px 18px rgba(20,24,32,.16);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);opacity:0;pointer-events:none;transform:translateY(4px);transition:opacity .14s ease,transform .14s ease}','.wbs-session-usage-popover.is-visible{opacity:1;pointer-events:auto;transform:translateY(0)}',- '.wbs-session-usage-detail-title{font-size:14px;font-weight:700;line-height:1.4}',- '.wbs-session-usage-detail-total{margin-top:4px;color:var(--wb-color-text-secondary,#5f6368);font-size:12.5px;font-variant-numeric:tabular-nums}',- '.wbs-session-usage-detail-note{margin-top:6px;color:var(--wb-color-text-secondary,#5f6368);font-size:11px;line-height:1.45}',+ '.wbs-session-usage-detail-title-row{display:flex;align-items:center;justify-content:space-between;gap:10px;min-width:0}',+ '.wbs-session-usage-detail-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;font-weight:700;line-height:1.4}',+ '.wbs-session-usage-detail-total{flex:0 0 auto;margin-top:0;color:var(--wb-color-text-secondary,#5f6368);font-size:11px;font-variant-numeric:tabular-nums;white-space:nowrap}',+ '.wbs-session-usage-detail-note{margin-top:6px;color:var(--wb-icon-tertiary,#969aa3);font-size:10px;line-height:1.4;opacity:.72}','.wbs-session-usage-detail-head,.wbs-session-usage-detail-row{display:grid;grid-template-columns:minmax(0,1fr) 42px 58px 48px;gap:7px;align-items:center}','.wbs-session-usage-detail-head{margin-top:10px;padding:6px 0;border-top:1px solid var(--wb-border-subtle,#eee);border-bottom:1px solid var(--wb-border-subtle,#eee);color:var(--wb-color-text-secondary,#5f6368);font-size:12px}','.wbs-session-usage-detail-head span,.wbs-session-usage-detail-row span{text-align:left}',@@ -14782,9 +14980,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-auto-empty{padding:18px 8px;text-align:center;color:var(--wb-icon-tertiary,#999);font-size:12px}','.wbs-auto-cap-link{display:flex;justify-content:flex-end;margin-top:7px}.wbs-auto-textbtn{padding:3px 4px;border:0;background:transparent;color:var(--wb-color-text-secondary,#666);font:inherit;font-size:11px;cursor:pointer}.wbs-auto-textbtn:hover{color:var(--wb-color-text-primary,#1f1f1f);text-decoration:underline}','#wbs-auto-discover.is-loading svg{animation:wbs-auto-discover-pulse 1s ease-in-out infinite}@keyframes wbs-auto-discover-pulse{50%{opacity:.35}}#wbs-auto-discover:disabled{cursor:wait;opacity:.68}',- '.wbs-modal.wbs-auto-discovery-modal{display:grid;grid-template-rows:auto auto minmax(0,1fr);gap:9px;width:calc(100% - 24px);max-width:620px;height:min(560px,calc(100% - 28px));box-sizing:border-box;overflow:hidden}.wbs-auto-discovery-note{margin-top:3px;color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.45}.wbs-auto-discovery-search{box-sizing:border-box;width:100%;height:32px;padding:6px 10px;border:1px solid var(--wb-border-default,#ddd);border-radius:8px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:12px;outline:none}.wbs-auto-discovery-search:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 18%,transparent)}.wbs-auto-discovery-search::placeholder{color:var(--wb-icon-tertiary,#888)}',+ '.wbs-modal.wbs-auto-discovery-modal{display:grid;grid-template-rows:auto auto minmax(0,1fr);gap:9px;width:calc(100% - 24px);max-width:620px;height:min(560px,calc(100% - 28px));box-sizing:border-box;overflow:hidden}.wbs-auto-discovery-note{margin-top:3px;color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.45}.wbs-auto-discovery-toolbar{display:flex;align-items:center;gap:7px;margin-top:8px}.wbs-auto-discovery-search{box-sizing:border-box;flex:1;min-width:0;height:32px;padding:6px 10px;border:1px solid var(--wb-border-default,#ddd);border-radius:8px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:12px;outline:none}.wbs-auto-discovery-search:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 18%,transparent)}.wbs-auto-discovery-search::placeholder{color:var(--wb-icon-tertiary,#888)}.wbs-auto-discovery-filter{flex:0 0 auto;height:32px;padding:0 10px;border:1px solid var(--wb-border-default,#ddd);border-radius:8px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font:inherit;font-size:11px;cursor:pointer}.wbs-auto-discovery-filter:hover,.wbs-auto-discovery-filter.active{border-color:var(--wb-button-primary-bg,#1f1f1f);background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}.wbs-auto-discovery-filter:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:1px}','.wbs-auto-discovery-header .wbs-auto-modal-head>div:first-child{min-width:0}.wbs-auto-discovery-status[hidden]{display:none}',- '.wbs-auto-discovery-list{display:flex;min-height:0;flex-direction:column;gap:6px;overflow:auto;padding-right:2px}.wbs-auto-discovery-empty{display:flex;min-height:160px;align-items:center;justify-content:center;color:var(--wb-icon-tertiary,#888);font-size:12px}.wbs-auto-discovery-item{display:flex;flex:0 0 auto;flex-direction:column;gap:6px;padding:9px 10px;border:1px solid var(--wb-border-subtle,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 24%,transparent)}.wbs-auto-discovery-head{display:flex;align-items:flex-start;gap:8px}.wbs-auto-discovery-name{min-width:0;flex:1;color:var(--wb-color-text-primary,#1f1f1f);font-size:12px;font-weight:650;line-height:1.4;overflow-wrap:anywhere}.wbs-auto-discovery-version{flex:0 0 auto;padding:2px 6px;border:1px solid var(--wb-border-default,#ddd);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font-size:10px;font-weight:600;white-space:nowrap}.wbs-auto-discovery-description{color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.45;overflow-wrap:anywhere}.wbs-auto-discovery-foot{display:flex;align-items:flex-end;gap:8px}.wbs-auto-sources{display:flex;min-width:0;flex:1;flex-wrap:wrap;gap:4px}.wbs-auto-source{max-width:100%;padding:3px 6px;border:1px solid var(--wb-border-subtle,#ddd);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font:inherit;font-size:10px;line-height:1.3;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-auto-source:hover,.wbs-auto-source:focus-visible{border-color:var(--wb-border-strong,#bbb);color:var(--wb-color-text-primary,#1f1f1f);outline:none}.wbs-auto-discovery-foot>.wbs-modal-btn{flex:0 0 auto;min-width:48px;padding:5px 9px}.wbs-auto-discovery-foot>.wbs-modal-btn:disabled{opacity:.45;cursor:not-allowed}',+ '.wbs-auto-discovery-list{display:flex;min-height:0;flex-direction:column;gap:6px;overflow:auto;padding-right:2px}.wbs-auto-discovery-empty{display:flex;min-height:160px;align-items:center;justify-content:center;color:var(--wb-icon-tertiary,#888);font-size:12px}.wbs-auto-discovery-item{display:flex;flex:0 0 auto;flex-direction:column;gap:6px;padding:9px 10px;border:1px solid var(--wb-border-subtle,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 24%,transparent)}.wbs-auto-discovery-head{display:flex;align-items:center;gap:8px}.wbs-auto-discovery-name{min-width:0;flex:1;color:var(--wb-color-text-primary,#1f1f1f);font-size:12px;font-weight:650;line-height:1.4;overflow-wrap:anywhere}.wbs-auto-discovery-version{flex:0 0 auto;padding:2px 6px;border:1px solid var(--wb-border-default,#ddd);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font-size:10px;font-weight:600;white-space:nowrap}.wbs-auto-discovery-favorite{display:inline-flex;align-items:center;justify-content:center;gap:3px;flex:0 0 auto;min-width:34px;height:26px;padding:0 5px;border:0;border-radius:7px;background:transparent;color:var(--wb-icon-tertiary,#888);font:inherit;font-size:10px;cursor:pointer}.wbs-auto-discovery-favorite:hover,.wbs-auto-discovery-favorite:focus-visible{background:var(--wb-bg-hover,#f0f0f0);color:var(--wb-color-text-primary,#1f1f1f);outline:none}.wbs-auto-discovery-favorite.is-active{color:var(--wb-color-text-primary,#1f1f1f)}.wbs-auto-discovery-favorite:disabled{opacity:.5;cursor:wait}.wbs-auto-discovery-favorite svg{display:block;flex:0 0 16px}.wbs-auto-discovery-favorite.is-active svg{fill:currentColor}.wbs-auto-discovery-description{color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.45;overflow-wrap:anywhere}.wbs-auto-discovery-foot{display:flex;align-items:flex-end;gap:8px}.wbs-auto-sources{display:flex;min-width:0;flex:1;flex-wrap:wrap;gap:4px}.wbs-auto-source{max-width:100%;padding:3px 6px;border:1px solid var(--wb-border-subtle,#ddd);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font:inherit;font-size:10px;line-height:1.3;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-auto-source:hover,.wbs-auto-source:focus-visible{border-color:var(--wb-border-strong,#bbb);color:var(--wb-color-text-primary,#1f1f1f);outline:none}.wbs-auto-discovery-foot>.wbs-modal-btn{flex:0 0 auto;min-width:48px;padding:5px 9px}.wbs-auto-discovery-foot>.wbs-modal-btn:disabled{opacity:.45;cursor:not-allowed}','.wbs-auto-batchbar{display:flex;align-items:center;gap:6px;margin:4px 0 7px}.wbs-auto-batch-count{margin-right:auto;color:var(--wb-icon-tertiary,#888);font-size:11px}.wbs-auto-field input,.wbs-auto-field textarea{box-sizing:border-box;width:100%;border:1px solid var(--wb-border-default,#dedede);border-radius:7px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:12px;outline:none}.wbs-auto-field{display:flex;flex-direction:column;gap:4px;margin-bottom:8px;color:var(--wb-icon-secondary,#666);font-size:11px}.wbs-auto-field input{height:30px;padding:5px 8px}.wbs-auto-field textarea{min-height:72px;padding:8px;resize:vertical;line-height:1.45}.wbs-auto-field textarea[data-auto-field="steps"]{min-height:150px;resize:none;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.wbs-auto-field input:focus,.wbs-auto-field textarea:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 20%,transparent)}.wbs-auto-trigger-seg{display:flex;gap:3px;padding:3px;border-radius:9px;background:var(--wb-bg-tertiary,#f0f0f0)}.wbs-auto-trigger-seg label{flex:1;display:flex;align-items:center;justify-content:center;min-height:28px;padding:0 8px;border-radius:7px;color:var(--wb-icon-secondary,#666);cursor:pointer}.wbs-auto-trigger-seg input{position:absolute;opacity:0;pointer-events:none}.wbs-auto-trigger-seg label:has(input:checked){background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.16)}','.wbs-modal.wbs-auto-agent-modal{display:flex;flex-direction:column;width:calc(100% - 24px);max-width:520px;max-height:calc(100% - 28px);box-sizing:border-box}.wbs-auto-agent-intro{margin:0 0 14px;color:var(--wb-color-text-secondary,#666);font-size:12px;line-height:1.6;overflow-wrap:anywhere}.wbs-auto-agent-input-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:7px;font-size:12px;font-weight:600}.wbs-auto-agent-input-head #wbs-auto-examples{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:5px}.wbs-auto-example-fill{border:1px solid var(--wb-border-subtle,#ddd);border-radius:6px;padding:3px 8px;background:var(--wb-bg-tertiary,#f5f5f5);font-weight:400}.wbs-auto-agent-prompt{display:block;box-sizing:border-box;flex:1 1 160px;min-height:60px;width:100%;height:160px;max-height:26vh;resize:none;overflow:auto;padding:10px 12px;border:1px solid var(--wb-border-default,#ddd);border-radius:9px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);font-family:inherit;font-size:12px;line-height:1.65;white-space:pre-wrap;overflow-wrap:anywhere}.wbs-auto-agent-prompt:focus{outline:2px solid color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 30%,transparent);outline-offset:1px;border-color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-auto-agent-prompt::placeholder{color:var(--wb-icon-tertiary,#888)}.wbs-auto-agent-hint{margin:8px 0 14px;font-size:11px;color:var(--wb-color-text-secondary,#666)}.wbs-auto-agent-modal .wbs-modal-actions{flex-shrink:0;margin-top:0}.wbs-auto-agent-modal .wbs-modal-ok:disabled{opacity:.4;cursor:default}','.wbs-auto-modal-head{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;padding:0 0 10px}.wbs-auto-modal-head .wbs-modal-title{margin:0}.wbs-auto-modal-subtitle{max-width:360px;margin-top:3px;color:var(--wb-icon-tertiary,#888);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.wbs-auto-modal-close{display:inline-flex;align-items:center;justify-content:center;flex:0 0 26px;width:26px;height:26px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--wb-icon-secondary,#666);cursor:pointer}.wbs-auto-modal-close:hover,.wbs-auto-modal-close:focus-visible{background:var(--wb-bg-hover,#eee);color:var(--wb-color-text-primary,#222);outline:none}.wbs-auto-modal-close svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round}',@@ -14804,9 +15002,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-nd-title{font-size:12px;font-weight:600;color:var(--wb-color-text-primary,#1f1f1f);white-space:nowrap}','.wbs-nd-hint{font-size:11px;color:var(--wb-icon-tertiary,#999);text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',/* 会话页:筛选 + 批量 + 列表 + 迁移/删除弹窗 */- '.wbs-sess-filters{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:10px;min-width:0}',- '.wbs-sess-account-filter{flex:0 1 190px;min-width:150px}',- '.wbs-sess-time-filter{flex:1 1 240px;min-width:0}',+ /* 筛选栏不能参与纵向压缩;切回全部时只让会话列表滚动。 */+ '.wbs-sess-filters{display:flex;flex-shrink:0;flex-wrap:nowrap;align-items:center;gap:8px;margin-bottom:10px;min-width:0;overflow-x:auto;scrollbar-width:thin}',+ '.wbs-sess-account-filter{flex:0 1 150px;min-width:120px}',+ '.wbs-sess-size-filter{flex:1.1 1 230px;min-width:220px}',+ '.wbs-sess-time-filter{flex:1 1 250px;min-width:240px}',/* 会话页/模型页:卡片与列表贴底,减少底部留白 */'.wbs-pane[data-pane="sessions"]{padding-bottom:1px}','.wbs-pane[data-pane="sessions"] > .wbs-pcard{margin-bottom:0;padding-bottom:4px}',@@ -14824,8 +15024,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-select:hover{border-color:var(--wb-border-strong,#bbb)}','.wbs-sess-select:focus{outline:none;border-color:var(--wb-accent-blue,#4f86ff)}',/* 时间筛选:Segment 组件(容器灰底 + 激活黑块,与主题页 segmented 一致) */- '.wbs-sess-time-filter .wbs-sess-seg{display:flex;flex:1 1 auto;width:auto;max-width:none;min-width:0}',- '.wbs-sess-time-filter .wbs-sess-seg button{flex:1 1 0;min-width:0;padding:0 4px}',+ ':is(.wbs-sess-time-filter,.wbs-sess-size-filter) .wbs-sess-seg{display:flex;flex:1 1 auto;width:auto;max-width:none;min-width:0}',+ ':is(.wbs-sess-time-filter,.wbs-sess-size-filter) .wbs-sess-seg button{flex:1 1 0;min-width:0;padding:0 4px;font-size:11px}','.wbs-sess-seg-btn{flex:0 0 auto;padding:6px 4px;border:none;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;font-family:inherit;white-space:nowrap}','.wbs-sess-seg-btn:hover{color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-sess-seg-btn.active{background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.2)}',@@ -14859,10 +15059,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-delbtn{padding:7px;color:var(--wb-icon-secondary,#555)}','.wbs-sess-delbtn:hover{color:#ff6b6b;border-color:color-mix(in srgb,#ff6b6b 45%,transparent);background:color-mix(in srgb,#ff6b6b 8%,transparent)}','.wbs-sess-delbtn.armed{color:#fff;background:#ff6b6b;border-color:#ff6b6b}',- '.wbs-sess-count{display:flex;align-items:center;gap:5px;margin-left:auto;min-width:0}',+ '.wbs-sess-count{display:flex;flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:0 5px;margin-left:auto;min-width:0}','.wbs-sess-summary-tag{display:inline-flex;align-items:center;padding:0;border:0;border-radius:0;background:transparent;color:var(--wb-icon-tertiary,#999);font-size:10px;line-height:22px;white-space:nowrap}','.wbs-sess-summary-auto{color:var(--wb-icon-tertiary,#999)}',- '.wbs-sess-summary-auto::before{content:"·";margin-right:5px;opacity:.7}',+ '.wbs-sess-summary-tag strong{margin:0 2px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);font-variant-numeric:tabular-nums}',+ '.wbs-sess-summary-auto::before,.wbs-sess-summary-size::before{content:"·";margin-right:5px;opacity:.7}','.wbs-sess-summary-selected{font-size:11px;color:var(--wb-icon-tertiary,#999);white-space:nowrap}','.wbs-model-card{display:flex;flex:1;flex-direction:column;min-height:0;padding:10px 12px 12px}','.wbs-model-tabs{display:flex;gap:4px;padding:3px;margin-bottom:10px;border-radius:10px;background:var(--wb-bg-tertiary,#f0f0f0)}',@@ -14980,6 +15181,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-row input{margin:2px 0 0;accent-color:#fff;flex-shrink:0}','.wbs-sess-main{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1}','.wbs-sess-title{font-size:12px;font-weight:600;color:var(--wb-color-text-primary,#1f1f1f);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',+ '.wbs-sess-size{flex:0 0 auto;min-width:54px;text-align:right;white-space:nowrap;font-size:11px;line-height:20px;font-variant-numeric:tabular-nums;color:var(--wb-color-text-secondary,#667085)}','.wbs-sess-meta{font-size:11px;color:var(--wb-icon-tertiary,#999)}','.wbs-sess-auto{display:inline-flex;align-items:center;justify-content:flex-end;gap:6px;flex:0 0 auto;min-width:76px;height:26px;margin-top:-2px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--wb-icon-tertiary,#999);cursor:pointer;padding:0 3px 0 5px;transition:background .15s,color .15s,opacity .15s;font:inherit}','.wbs-sess-auto:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}',@@ -15217,6 +15419,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-session-copy-track{height:6px;overflow:hidden;border-radius:999px;background:var(--wb-bg-tertiary,#edf0f3);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--wb-border-subtle,#dfe3e8) 65%,transparent)}','.wbs-session-copy-fill{display:block;width:0;height:100%;border-radius:inherit;background:var(--wb-button-primary-bg,#1f1f1f);transition:width .25s ease}','.wbs-session-copy-status{min-height:16px;margin-top:7px;color:var(--wb-color-text-secondary,#667085);font-size:10.5px;line-height:1.45;overflow-wrap:anywhere}',+ '.wbs-session-copy-transfer{margin-top:4px;color:var(--wb-color-text-secondary);font-size:9.5px;line-height:1.35;font-variant-numeric:tabular-nums;text-align:right;overflow-wrap:anywhere}','.wbs-session-copy-summary{margin-top:3px;color:var(--wb-color-text-primary,#1f1f1f);font-size:10.5px;line-height:1.45;font-variant-numeric:tabular-nums}','.wbs-session-copy-actions{display:flex;align-items:center;justify-content:flex-start;gap:8px;margin-top:8px}','.wbs-session-copy-details-btn{min-height:26px;padding:4px 9px;border:1px solid var(--wb-border-default,#d7dbe0);border-radius:7px;background:var(--wb-bg-hover,#f5f6f8);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:10.5px;cursor:pointer}',@@ -15230,9 +15433,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-session-copy-detail-list{min-height:0;overflow:auto;margin-top:12px;border:1px solid var(--wb-border-subtle,#e2e5e9);border-radius:8px;background:var(--wb-bg-secondary,#fafbfc)}','.wbs-session-copy-detail-row{display:grid;grid-template-columns:58px minmax(0,1fr) minmax(0,1.1fr);gap:8px;align-items:center;min-height:34px;padding:6px 9px;border-bottom:1px solid var(--wb-border-subtle,#e7e9ed);font-size:11px}','.wbs-session-copy-detail-row:last-child{border-bottom:0}',+ '.wbs-session-copy-detail-row.is-copied{grid-template-columns:58px minmax(0,1fr) auto}.wbs-session-copy-detail-row.is-copied .wbs-session-copy-detail-note{grid-column:2/-1;grid-row:2}.wbs-session-copy-detail-size{grid-column:3;grid-row:1;justify-self:end;white-space:nowrap;font-variant-numeric:tabular-nums;color:var(--wb-color-text-secondary,#667085)}','.wbs-session-copy-detail-status{font-weight:650;color:var(--wb-color-text-secondary,#667085)}','.wbs-session-copy-detail-label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-session-copy-detail-note{min-width:0;color:var(--wb-color-text-secondary,#667085);overflow-wrap:anywhere;white-space:normal}',+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) :is(.wbs-session-copy-detail-note,.wbs-session-copy-details-summary,.wbs-session-copy-detail-size,.wbs-sess-size){color:var(--wb-color-text-secondary,#b9bdc7)}','.wbs-session-copy-detail-row.is-copied .wbs-session-copy-detail-status{color:#238a5b}.wbs-session-copy-detail-row.is-conflict .wbs-session-copy-detail-status{color:#a55f09}.wbs-session-copy-detail-row.is-failed .wbs-session-copy-detail-status,.wbs-session-copy-detail-row.is-partial .wbs-session-copy-detail-status{color:#b05d18}','.wbs-session-copy-detail-empty{padding:28px 14px;text-align:center;color:var(--wb-color-text-secondary,#667085);font-size:11px}','.wbs-session-copy-notice.is-done .wbs-session-copy-icon{background:color-mix(in srgb,#2e9b68 15%,transparent);color:#238a5b}.wbs-session-copy-notice.is-done .wbs-session-copy-fill{background:#2e9b68}',@@ -15241,7 +15446,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-session-copy-notice.is-error .wbs-session-copy-fill{background:#c44343}','html.cb-dark .wbs-session-copy-notice,html[data-theme="dark"] .wbs-session-copy-notice,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-notice{border-color:var(--wb-border-default,rgba(255,255,255,.16));background:var(--wb-bg-popover,#25262a);color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 14px 38px rgba(0,0,0,.42)}html.cb-dark .wbs-session-copy-track,html[data-theme="dark"] .wbs-session-copy-track,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-track{background:var(--wb-bg-tertiary,#34363b)}html.cb-dark .wbs-session-copy-route,html[data-theme="dark"] .wbs-session-copy-route,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-route,html.cb-dark .wbs-session-copy-status,html[data-theme="dark"] .wbs-session-copy-status,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-status{color:var(--wb-color-text-secondary,#b9bdc7)}html.cb-dark .wbs-session-copy-notice.is-conflict .wbs-session-copy-status,html[data-theme="dark"] .wbs-session-copy-notice.is-conflict .wbs-session-copy-status,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-notice.is-conflict .wbs-session-copy-status{color:#e4b36a}','html.cb-dark .wbs-session-copy-summary,html[data-theme="dark"] .wbs-session-copy-summary,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary,html.cb-dark .wbs-session-copy-detail-label,html[data-theme="dark"] .wbs-session-copy-detail-label,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-detail-label{color:var(--wb-color-text-primary,#f2f3f5)}html.cb-dark .wbs-session-copy-details,html[data-theme="dark"] .wbs-session-copy-details,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-details{background:var(--wb-bg-popover,#25262a);color:var(--wb-color-text-primary,#f2f3f5)}html.cb-dark .wbs-session-copy-detail-list,html[data-theme="dark"] .wbs-session-copy-detail-list,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-detail-list{border-color:var(--wb-border-default,rgba(255,255,255,.16));background:var(--wb-bg-secondary,#202126)}html.cb-dark .wbs-session-copy-detail-row,html[data-theme="dark"] .wbs-session-copy-detail-row,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-detail-row{border-color:var(--wb-border-default,rgba(255,255,255,.12))}',- '@media(max-width:460px){.wbs-session-copy-notice{min-height:104px;padding:11px 12px 10px}.wbs-session-copy-route{margin-left:29px;margin-right:24px}.wbs-session-copy-status{font-size:10px}.wbs-session-copy-detail-row{grid-template-columns:52px minmax(0,1fr);gap:5px}.wbs-session-copy-detail-note{grid-column:2;font-size:10px}}',+ '@media(max-width:460px){.wbs-session-copy-notice{min-height:104px;padding:11px 12px 10px}.wbs-session-copy-route{margin-left:29px;margin-right:24px}.wbs-session-copy-status{font-size:10px}.wbs-session-copy-detail-row{grid-template-columns:52px minmax(0,1fr);gap:5px}.wbs-session-copy-detail-row.is-copied{grid-template-columns:52px minmax(0,1fr) auto}.wbs-session-copy-detail-note{grid-column:2;font-size:10px}}','.wbs-fab.wbs-fab-credit-alert .button{animation:wbs-credit-robot-alert .45s ease-out}','@keyframes wbs-credit-robot-alert{0%,100%{transform:translateY(0)}45%{transform:translateY(-5px)}75%{transform:translateY(1px)}}','.wbs-usage-modal-mask{position:fixed!important;inset:0!important;z-index:2147483647!important;box-sizing:border-box;padding:24px;border-radius:0!important;background:rgba(15,18,24,.36);backdrop-filter:blur(5px);-webkit-backdrop-filter:blur(5px)}',diff --git a/scripts/lib.js b/scripts/lib.jsindex 08c08ad..e44d67f 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -584,18 +584,32 @@ function ensureAutoCopyMeta(meta) {return next;}+// Auto-copy rules are read several times per session during a sync batch.+// Memoize on the meta file fingerprint; all writes go through writeMeta+// (tmp + rename), which always bumps mtime, so a stale view lasts at most one+// call and self-corrects on the next stat.+const autoCopyConfigCache = new Map();function readAutoCopyConfig(dataDir) {+ let fingerprint = null;+ try { const stat = fs.statSync(metaFile(dataDir)); fingerprint = stat.mtimeMs + ':' + stat.size; } catch (_) {}+ const cached = autoCopyConfigCache.get(dataDir);+ if (cached && cached.fingerprint === fingerprint) return cached.value;const meta = readMeta(dataDir);const wasCurrent = !!(meta.autoCopy && meta.autoCopy.version === 2);const autoCopy = ensureAutoCopyMeta(meta);- if (!wasCurrent) writeMeta(dataDir, meta);- return {+ if (!wasCurrent) {+ writeMeta(dataDir, meta);+ try { const stat = fs.statSync(metaFile(dataDir)); fingerprint = stat.mtimeMs + ':' + stat.size; } catch (_) { fingerprint = null; }+ }+ const value = {allSessions: autoCopy.allSessions === true,sessions: autoCopy.sessions,sessionIndex: autoCopy.sessionIndex,workspaces: autoCopy.workspaces,copies: autoCopy.copies,};+ autoCopyConfigCache.set(dataDir, { fingerprint, value });+ return value;}function autoCopyRuleKey(lineageId, targetUid) {diff --git a/scripts/session-sync.js b/scripts/session-sync.jsindex 840881a..de92c5a 100644--- a/scripts/session-sync.js+++ b/scripts/session-sync.js@@ -5,8 +5,6 @@const fs = require('node:fs');const path = require('node:path');const crypto = require('node:crypto');-const MAX_BYTES = 64 * 1024 * 1024;-const MAX_FILES = 20000;const identityKeys = new Set(['sessionId', 'conversationId', 'ownerConversationId', 'session_id', 'conversation_id']);const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');@@ -32,39 +30,157 @@ function safePath(root, relative) {return target;}-function readSnapshot(root, id, aliases = []) {+// List views need byte counts, not message parsing or payload buffers. Limit+// concurrent scans, never the size/file count of a session itself.+async function readSessionSizes(root, ids) {+ root = path.resolve(root);+ const sizes = new Map();+ const sharedStats = new Map();+ async function stat(file) {+ try {+ const value = await fs.promises.lstat(file);+ if (value.isSymbolicLink()) throw Error('symbolic link');+ return value;+ } catch (error) { if (error.code === 'ENOENT') return null; throw error; }+ }+ async function base(relative) {+ if (!sharedStats.has(relative)) sharedStats.set(relative, (async () => {+ const parent = relative ? await base(path.dirname(relative) === '.' ? '' : path.dirname(relative)) : true;+ if (!parent) return null;+ if (parent !== true && !parent.isDirectory()) throw Error('invalid directory');+ return stat(path.join(root, relative));+ })());+ return sharedStats.get(relative);+ }+ async function visit(file) {+ const info = await stat(file);+ if (!info) return 0;+ if (info.isFile()) return info.size;+ if (!info.isDirectory()) throw Error('unsupported file');+ let total = 0;+ for (const entry of await fs.promises.readdir(file)) total += await visit(path.join(file, entry));+ return total;+ }+ let projects;+ try {+ const info = await base('projects');+ projects = info ? (await fs.promises.readdir(path.join(root, 'projects'), { withFileTypes: true })).filter(entry => entry.isDirectory()).map(entry => entry.name) : [];+ } catch (_) { return new Map(ids.map(id => [id, null])); }+ const queue = Array.from(new Set(ids));+ let next = 0;+ await Promise.all(Array.from({ length: Math.min(4, queue.length) }, async () => {+ while (next < queue.length) {+ const id = queue[next++];+ try {+ if (typeof id !== 'string' || !id || /[/\\\x00]/.test(id) || id === '.' || id === '..') throw Error('invalid id');+ let total = 0;+ const paths = projects.flatMap(project => ['projects/' + project + '/' + id + '.jsonl', 'projects/' + project + '/' + id]);+ paths.push('workspace/sessions/' + id, 'tasks/' + id, 'file-history/' + id, 'artifact-index/' + id + '.json');+ for (const relative of paths) {+ const parent = await base(path.dirname(relative));+ if (parent) {+ if (!parent.isDirectory()) throw Error('invalid directory');+ total += await visit(path.join(root, relative));+ }+ }+ sizes.set(id, total);+ } catch (_) { sizes.set(id, null); }+ }+ }));+ return sizes;+}++function aliasesEqual(left, right) {+ if (!Array.isArray(left) || left.length !== right.length) return false;+ const set = new Set(right);+ return left.every(value => set.has(value));+}++// Fingerprint cache: relative path -> { size, mtimeMs, ctimeMs, hash, mode,+// semantic, aliases, records }. A file whose size/mtime/ctime all match the+// cached fingerprint reuses its SHA-256 without being re-read; bytes load+// lazily (only files actually copied/backed up are read). Transcript records+// and the artifact index hash depend on the alias set, so those are reused+// only when computed for the same aliases.+function readSnapshot(root, id, aliases = [], cache = null) {if (!id || /[/\\\x00]/.test(id) || id === '.' || id === '..') throw Error('无效的会话标识');root = path.resolve(root);if (fs.lstatSync(root).isSymbolicLink()) throw Error('会话目录包含符号链接,未同步');const knownIds = Array.from(new Set([id, ...aliases]));const files = new Map();let total = 0;+ // Directory components repeat across thousands of session files. Verify each+ // path component once per snapshot instead of lstat-ing the whole chain per+ // file; the per-entry symlink/type checks below still apply to every file.+ const trustedComponents = new Map();+ function safePathFast(relative) {+ const parts = relative.split('/');+ let target = root;+ for (let i = 0; i < parts.length - 1; i++) {+ target = path.join(target, parts[i]);+ if (trustedComponents.has(target)) continue;+ try { if (fs.lstatSync(target).isSymbolicLink()) throw Error('会话文件包含符号链接,未同步'); }+ catch (error) { if (error.code !== 'ENOENT') throw error; }+ trustedComponents.set(target, true);+ }+ return path.join(target, parts[parts.length - 1]);+ }+ function attachBytes(entry) {+ if (entry.bytes) return;+ let loaded = null;+ Object.defineProperty(entry, 'bytes', {+ enumerable: true,+ get() {+ if (loaded) return loaded;+ const file = safePath(root, entry.relative);+ let now;+ try { now = fs.statSync(file); } catch (_) { throw Error('会话文件正在变化,请稍后重试'); }+ if (now.size !== entry.size || now.mtimeMs !== entry.mtimeMs || now.ctimeMs !== entry.ctimeMs) throw Error('会话文件正在变化,请稍后重试');+ loaded = fs.readFileSync(file);+ return loaded;+ },+ });+ }+ function cached(relative, stat) {+ if (!cache) return null;+ const entry = cache.get(relative);+ if (!entry || typeof entry !== 'object') return null;+ if (entry.size !== stat.size || entry.mtimeMs !== stat.mtimeMs || entry.ctimeMs !== stat.ctimeMs) return null;+ if (typeof entry.hash !== 'string' || !entry.hash) return null;+ return entry;+ }function visit(relative, logical) {- const file = safePath(root, relative);+ const file = safePathFast(relative);let stat;try { stat = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return; throw Error('会话文件无法读取'); }+ if (stat.isSymbolicLink()) throw Error('会话文件包含符号链接,未同步');if (stat.isDirectory()) {for (const entry of fs.readdirSync(file).sort()) visit(relative + '/' + entry, logical + '/' + entry);return;}if (!stat.isFile()) throw Error('会话文件类型不受支持');total += stat.size;- if (total > MAX_BYTES || files.size >= MAX_FILES) throw Error('会话文件过大,未自动同步');+ const hit = cached(relative, stat);+ if (hit) {+ const entry = {+ relative, hash: hit.hash, mode: stat.mode & 0o777, mtimeMs: stat.mtimeMs,+ size: stat.size, ctimeMs: stat.ctimeMs,+ semantic: typeof hit.semantic === 'string' && hit.semantic ? hit.semantic : null,+ semanticAliases: Array.isArray(hit.aliases) ? hit.aliases : null,+ records: Array.isArray(hit.records) ? hit.records : null,+ };+ attachBytes(entry);+ files.set(logical, entry);+ return;+ }const bytes = fs.readFileSync(file);const after = fs.statSync(file);if (stat.size !== bytes.length || stat.size !== after.size || stat.mtimeMs !== after.mtimeMs || stat.ctimeMs !== after.ctimeMs) throw Error('会话文件正在变化,请稍后重试');- let semantic = digest(bytes);- // Workspace files and history snapshots are user work products. Their- // extension does not guarantee valid JSON (JSONC, drafts, empty files,- // or arbitrary bytes). Preserve and compare those files byte-for-byte.- // Only the official index needs structured identity normalization because- // targetBytes rewrites its ownerConversationId during a copy.- if (logical === 'artifact-index/__session__.json') {- let value;- try { value = JSON.parse(bytes.toString('utf8')); } catch (_) { throw Error('会话产物索引损坏,未同步'); }- semantic = digest(JSON.stringify(canonical(value, knownIds)));- }- files.set(logical, { relative, bytes, hash: digest(bytes), semantic, mode: stat.mode & 0o777, mtimeMs: stat.mtimeMs });+ files.set(logical, {+ relative, bytes, hash: digest(bytes), mode: stat.mode & 0o777, mtimeMs: stat.mtimeMs,+ size: after.size, ctimeMs: after.ctimeMs,+ semantic: null, semanticAliases: null, records: null,+ });}const projects = safePath(root, 'projects');if (fs.existsSync(projects)) {@@ -76,24 +192,52 @@ function readSnapshot(root, id, aliases = []) {}for (const prefix of ['workspace/sessions', 'tasks', 'file-history']) visit(prefix + '/' + id, prefix + '/__session__');visit('artifact-index/' + id + '.json', 'artifact-index/__session__.json');+ // Workspace files and history snapshots are user work products. Their+ // extension does not guarantee valid JSON (JSONC, drafts, empty files,+ // or arbitrary bytes). Preserve and compare those files byte-for-byte.+ // Only the official index needs structured identity normalization because+ // targetBytes rewrites its ownerConversationId during a copy.const transcripts = [...files].filter(([key]) => /^projects\/[^/]+\/__session__\.jsonl$/.test(key));if (transcripts.length > 1) throw Error('会话消息文件不唯一,未同步');let records = null, transcriptKey = null;if (transcripts.length) {transcriptKey = transcripts[0][0];- const lines = transcripts[0][1].bytes.toString('utf8').split(/\r?\n/).filter(line => line.trim());- if (!lines.length) throw Error('会话消息文件为空,未同步');- records = lines.map(line => {- let record;- try { record = JSON.parse(line); } catch (_) { throw Error('会话消息文件未写完或已损坏,未同步'); }- if (!record || typeof record !== 'object' || Array.isArray(record) || typeof record.type !== 'string') throw Error('会话消息格式不受支持,未同步');- return digest(JSON.stringify(canonical(record, knownIds)));- });- // Require actual messages: a metadata-only journal is not an empty base.- if (!lines.some(line => JSON.parse(line).type === 'message')) throw Error('会话消息文件没有消息,未同步');- transcripts[0][1].semantic = digest(records.join('\n'));+ const entry = transcripts[0][1];+ if (!(entry.records && entry.semantic && aliasesEqual(entry.semanticAliases, knownIds))) {+ const lines = entry.bytes.toString('utf8').split(/\r?\n/).filter(line => line.trim());+ if (!lines.length) throw Error('会话消息文件为空,未同步');+ entry.records = lines.map(line => {+ let record;+ try { record = JSON.parse(line); } catch (_) { throw Error('会话消息文件未写完或已损坏,未同步'); }+ if (!record || typeof record !== 'object' || Array.isArray(record) || typeof record.type !== 'string') throw Error('会话消息格式不受支持,未同步');+ return digest(JSON.stringify(canonical(record, knownIds)));+ });+ // Require actual messages: a metadata-only journal is not an empty base.+ if (!lines.some(line => JSON.parse(line).type === 'message')) throw Error('会话消息文件没有消息,未同步');+ entry.semantic = digest(entry.records.join('\n'));+ entry.semanticAliases = [...knownIds];+ }+ records = entry.records;+ }+ const indexEntry = files.get('artifact-index/__session__.json');+ if (indexEntry && !(indexEntry.semantic && aliasesEqual(indexEntry.semanticAliases, knownIds))) {+ let value;+ try { value = JSON.parse(indexEntry.bytes.toString('utf8')); } catch (_) { throw Error('会话产物索引损坏,未同步'); }+ indexEntry.semantic = digest(JSON.stringify(canonical(value, knownIds)));+ indexEntry.semanticAliases = [...knownIds];+ }+ for (const [key, entry] of files) {+ if (!entry.semantic) entry.semantic = entry.hash;+ if (cache) {+ cache.set(entry.relative, {+ size: entry.size, mtimeMs: entry.mtimeMs, ctimeMs: entry.ctimeMs,+ hash: entry.hash, mode: entry.mode, semantic: entry.semantic,+ aliases: entry.semanticAliases ? [...entry.semanticAliases] : null,+ records: entry.records ? [...entry.records] : null,+ });+ }}- return { root, id, aliases: knownIds, files, records, transcriptKey };+ return { root, id, aliases: knownIds, files, records, transcriptKey, totalBytes: total, cache };}function compareSnapshots(left, right) {@@ -164,7 +308,7 @@ async function selectTargetSnapshot(source, targetIds, readTarget, preferredId)}function unchanged(snapshot) {- const now = readSnapshot(snapshot.root, snapshot.id, snapshot.aliases);+ const now = readSnapshot(snapshot.root, snapshot.id, snapshot.aliases, snapshot.cache || null);return now.files.size === snapshot.files.size && [...snapshot.files].every(([key, file]) => now.files.get(key)?.hash === file.hash);}@@ -217,12 +361,14 @@ async function applySnapshot(source, target, options) {if (change.bytes === null) expected.delete(change.key);else expected.set(change.key, digest(change.bytes));}+ let totalBytes = 0;const verifyPublished = () => {if (!unchanged(source)) throw Error('源会话正在变化,已停止同步');- const now = readSnapshot(target.root, target.id, target.aliases);+ const now = readSnapshot(target.root, target.id, target.aliases, target.cache || null);if (now.files.size !== expected.size || [...expected].some(([key, hash]) => now.files.get(key)?.hash !== hash)) {throw Error('目标会话正在变化,已停止同步');}+ totalBytes = now.totalBytes;};const applied = [];try {@@ -254,7 +400,10 @@ async function applySnapshot(source, target, options) {// Metadata already committed: a journal I/O failure must not undo files.let journalPending = false;try { save(); } catch (_) { journalPending = true; }- return { backup, copied: changes.length, journalPending };+ // Count only newly published payload bytes. Backups, unchanged files and+ // removals are not copied session data; rolled-back writes never reach here.+ const copiedBytes = changes.reduce((sum, change) => sum + (change.bytes ? change.bytes.length : 0), 0);+ return { backup, copied: changes.length, copiedBytes, journalPending, totalBytes };} catch (error) {// Do not roll back over an official write that happened after publication.let incomplete = false;@@ -275,4 +424,4 @@ async function applySnapshot(source, target, options) {}}-module.exports = { readSnapshot, compareSnapshots, selectTargetSnapshot, applySnapshot };+module.exports = { readSessionSizes, readSnapshot, compareSnapshots, selectTargetSnapshot, applySnapshot };diff --git a/test/account-credit-cache.test.js b/test/account-credit-cache.test.jsnew file mode 100644index 0000000..3289f3c--- /dev/null+++ b/test/account-credit-cache.test.js@@ -0,0 +1,50 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const os = require('node:os');+const { createAccountCreditCache } = require('../scripts/account-credit-cache');+const automation = require('../scripts/automation');+const credit = expiry => ({ credits: 10, segments: [{ remaining: 10, total: 20, expiresAt: expiry, source: 'test' }] });+function fixture(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-credit-cache-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ return { root, cache: createAccountCreditCache(root) };+}+test('cached credits survive restart and persist only public credit fields', t => {+ const { root, cache } = fixture(t);+ cache.set('a', { ...credit(200), accessToken: 'secret', auth: { cookie: 'secret' } });+ const restored = createAccountCreditCache(root).get('a');+ assert.equal(restored.credits, 10); assert.equal(restored.creditSegments[0].expiresAt, 200);+ restored.creditSegments[0].expiresAt = 0;+ assert.equal(cache.get('a').creditSegments[0].expiresAt, 200);+ const file = path.join(root, 'account-credit-cache.json');+ assert.doesNotMatch(fs.readFileSync(file, 'utf8'), /secret|accessToken|auth|cookie/);+ if (process.platform !== 'win32') assert.equal(fs.statSync(file).mode & 0o777, 0o600);+ fs.writeFileSync(file, '{invalid');+ assert.deepEqual(createAccountCreditCache(root).get('a'), {});+});+test('check-in iteration freezes cached expiry order, remains sequential and leaves unrelated loops alone', async t => {+ const { cache } = fixture(t);+ cache.set('later', credit(200)); cache.set('soon', credit(100)); cache.set('tie', credit(100));+ const accounts = ['unknown', 'later', 'soon', 'tie'].map(uid => ({ uid }));+ const task = { id: 'ordered', steps: [{ op: 'account.forEach', accounts: 'all', steps: [{ op: 'logic.catch', steps: [{ op: 'account.checkin' }], onError: [] }] }] };+ const seen = []; let active = 0, sorts = 0;+ const options = {+ listAccounts: async () => accounts,+ orderCheckinAccounts: values => { sorts++; return cache.order(values); },+ accountCheckin: async account => {+ assert.equal(active++, 0); seen.push(account.uid);+ cache.set('later', credit(1));+ await new Promise(resolve => setImmediate(resolve)); active--;+ if (account.uid === 'soon') throw Error('offline');+ return { ok: true };+ },+ };+ await automation.executeTask(task, options);+ assert.deepEqual(seen, ['soon', 'tie', 'later', 'unknown']); assert.equal(sorts, 1);+ assert.deepEqual(accounts.map(a => a.uid), ['unknown', 'later', 'soon', 'tie']);+ await automation.executeTask({ id: 'other', steps: [{ op: 'account.forEach', accounts: 'all', steps: [] }] }, options);+ assert.equal(sorts, 1);+});diff --git a/test/account-list-stability.test.js b/test/account-list-stability.test.jsindex b858d53..0b2c9cc 100644--- a/test/account-list-stability.test.js+++ b/test/account-list-stability.test.js@@ -25,14 +25,14 @@ function harness() {const ctx = vm.createContext({window: {},state: { accounts: [], current: null, open: true, creditRunId: 0, creditRefreshGeneration: {}, activityRunId: 0, creditRemaining: 0 },- alive: true, CAPS: { accounts: true }, accountsPane: pane, panel: el(), fab: el(), fabQuietMode: { wake() {} },+ alive: true, CAPS: { accounts: true }, WBS_PROFILE_IS_AI: false, accountsPane: pane, panel: el(), fab: el(), fabQuietMode: { wake() {} },api(route, options) { return new Promise((resolve, reject) => requests.push({ route, options, resolve, reject })); },el, esc: String, escAttr: String, tokenState: () => ({ label: '-' }), isIdentityExpired: a => !!a.identityExpired,checkinBadgeHtml: () => '', creditBlockHtml: () => '', applyAccountMask() {}, updateAccountSummary() {},updateCheckinCells() {}, updateCreditCell() {}, fetchActivityForAccounts() {}, toast() {}, root: {},PRIMARY_ACCOUNT_SVG: '', SWITCH_SVG: '', TRASH_SVG: '',setBuildTimeout: fn => fn(), setTimeout: () => 1, clearTimeout() {},- checkForUpdate() {}, acCheckPromptOnOpen() {}, syncSessionModule() {},+ checkForUpdate() {}, acCheckPromptOnOpen() {}, syncSessionModule() {}, fetchDailyProgressForAccounts() {}, pollActiveSessionCopyNotice() {},});vm.runInContext([section(' function isKnownActivityStreak(', ' function el(tag'),@@ -55,6 +55,23 @@ test('metadata refresh retains cached credits, sorted order and the actual buttoassert.equal(h.cards()[0], before[0]);});+test('cached first render fixes the visible order and delegates current-account check-in to the ordered automation', async () => {+ const h = harness();+ h.ctx.refresh();+ h.requests[0].resolve({ checkinAutomationEnabled: true, current: { uid: 'later' }, accounts: [account('later', 200), account('soon', 100), { uid: 'unknown', creditSegments: [] }] });+ await tick();+ const before = h.cards();+ assert.deepEqual(h.order(), ['soon', 'later', 'unknown']);+ assert.ok(h.requests.every(request => request.route !== '/api/accounts/checkin-sync'));+ for (const request of h.requests.filter(request => request.route === '/api/credits')) {+ const uid = JSON.parse(request.options.body).uid;+ request.resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: uid === 'unknown' ? 1 : 300 }] });+ }+ await tick();+ assert.deepEqual(h.order(), ['soon', 'later', 'unknown']);+ assert.deepEqual(h.cards(), before);+});+test('first credit batch after renderer reload sorts cards without reopening the panel', async () => {const h = harness();h.ctx.render({ current: { uid: 'later' }, accounts: [{ uid: 'later' }, { uid: 'soon' }] });diff --git a/test/automation-discovery.test.js b/test/automation-discovery.test.jsindex 0f2ba6c..52fa03f 100644--- a/test/automation-discovery.test.js+++ b/test/automation-discovery.test.js@@ -82,7 +82,7 @@ test('discovery searches GitHub and Gitee, deduplicates task JSON and caches resassert.equal(result.tasks.length, 1);assert.equal(result.tasks[0].name, '账号提示');assert.equal(result.tasks[0].schemaVersion, 1);- assert.equal(result.schemaVersion, 2);+ assert.equal(result.schemaVersion, 3);assert.equal(result.marker, MARKER);assert.deepEqual(result.tasks[0].sources.map(source => source.platform), ['github', 'gitee']);assert.equal(result.tasks[0].compatible, true);@@ -257,6 +257,14 @@ test('automation UI preloads discovery and exposes fuzzy task search and import'assert.match(source, /wbs-auto-discovery-version/);assert.match(source, /wbs-auto-update-badge/);assert.match(source, /wbs-auto-discovery-update/);+ assert.match(source, /data-auto-discovery-filter="favorites"/);+ assert.match(source, /data-auto-discovery-favorite/);+ assert.match(source, /\/api\/automations\/discovery\/favorite/);+ assert.match(source, /favoriteCount/);+ assert.match(source, /matches\.sort\(function \(left, right\)/);+ assert.match(source, /Number\(right\.favoriteCount\).*Number\(left\.favoriteCount\)/);+ assert.match(source, /wbs-auto-discovery-favorite\.is-active\{color:var\(--wb-color-text-primary/);+ assert.doesNotMatch(source, /wbs-auto-discovery-favorite\.is-active\{color:var\(--wb-accent-blue/);assert.match(source, /replaceExisting/);assert.match(source, /\/api\/automations\/discovery\?refresh=1/);assert.match(source, /确认用公开仓库中的新版覆盖本地任务/);diff --git a/test/automation-likes.test.js b/test/automation-likes.test.jsnew file mode 100644index 0000000..fd5a041--- /dev/null+++ b/test/automation-likes.test.js@@ -0,0 +1,33 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const { createAutomationLikesClient } = require('../scripts/automation-likes');++const key = 'a'.repeat(64);+const actor = '11111111-1111-4111-8111-111111111111';++test('automation likes client decorates discovery and invalidates cache after toggle', async () => {+ const calls = [];+ const fetchImpl = async (input, init) => {+ calls.push({ url: String(input), init });+ if (init && init.method === 'POST') return new Response(JSON.stringify({ ok: true, taskKey: key, favoriteCount: 4, favorited: true }));+ return new Response(JSON.stringify({ ok: true, favorites: { [key]: { count: 3, favorited: false } } }));+ };+ const client = createAutomationLikesClient({ endpoint: 'https://workdaddy.dev/api/automation-likes', fetchImpl, getActorId: () => actor });+ const catalog = await client.decorate({ tasks: [{ key, name: '任务' }] });+ assert.deepEqual(catalog.tasks[0].favoriteCount, 3);+ assert.equal(catalog.tasks[0].favorited, false);+ await client.toggle(key, true);+ await client.decorate({ tasks: [{ key, name: '任务' }] });+ assert.equal(calls.length, 3);+ assert.equal(calls[0].init.headers['X-WorkDaddy-Actor'], actor);+ assert.match(calls[1].init.body, /"favorite":true/);+});++test('automation likes client ignores invalid catalog keys', async () => {+ let calls = 0;+ const client = createAutomationLikesClient({ fetchImpl: async () => { calls += 1; return new Response('{}'); } });+ assert.deepEqual(await client.getFavorites([{ key: 'bad' }]), {});+ assert.equal(calls, 0);+});diff --git a/test/automation-model.test.js b/test/automation-model.test.jsindex 013a7c2..9f8cbcc 100644--- a/test/automation-model.test.js+++ b/test/automation-model.test.js@@ -12,7 +12,7 @@ const { normalizeAutomationModelId, selectAutomationModel, verifyAutomationModelconst builtIn = JSON.parse(fs.readFileSync(path.join(__dirname, '../scripts/builtin/automations/keep-accounts-active.json'), 'utf8'));test('V2 session sends accept a model ID without changing the protocol version', async () => {- assert.equal(SCHEMA_VERSION, 2);+ assert.equal(SCHEMA_VERSION, 3);const seen = [];const task = validateTask({ schemaVersion: 2, id: 'choose-model', name: 'choose-model', variables: { model: 'deepseek-v4.1-flash' }, steps: [{ op: 'session.create', message: 'hi', model: '{{vars.model}}' },@@ -159,7 +159,7 @@ test('daemon selects and checks the model before sending, and ships the rendererassert.ok(selectAt > 0 && sendAt > selectAt);assert.match(daemon, /if \(modelId\) await confirmAutomationModel\(modelId/);assert.match(daemon, /restoreAutomationNewTaskPreference\(modelSelection\)/);- assert.match(daemon, /const DAEMON_VERSION = '1\.2\.83'/);+ assert.match(daemon, /const DAEMON_VERSION = '1\.2\.95'/);const staging = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');assert.match(staging, /automation-model\.js/);});diff --git a/test/automation-packages.test.js b/test/automation-packages.test.jsindex 3ad5380..aa93d46 100644--- a/test/automation-packages.test.js+++ b/test/automation-packages.test.js@@ -4,7 +4,7 @@ const automation=require('../scripts/automation');test('editing another task preserves future-schema documents without executing them',()=>{const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-package-'));try {- const future={schemaVersion:3,id:'future',name:'Future task',enabled:true,trigger:{type:'panelOpened'},schedule:{type:'interval',minutes:1},steps:[],futureConfig:{value:1}};+ const future={schemaVersion:4,id:'future',name:'Future task',enabled:true,trigger:{type:'panelOpened'},schedule:{type:'interval',minutes:1},steps:[],futureConfig:{value:1}};fs.writeFileSync(path.join(dir,'automations.json'),JSON.stringify([future]));const tasks=automation.readAutomations(dir);assert.deepEqual(tasks[0],future);@@ -35,7 +35,7 @@ test('package compatibility rejects newer versions, other profiles/platforms and});test('future formats are not silently reinterpreted as legacy tasks',()=>{for(const patch of [{formatVersion:2},{kind:'other-package'}])assert.equal(previewPackage({...example(),...patch},{runtime}).compatible,false);- const p=example();p.requires.taskSchemaVersion=2;p.task.schemaVersion=2;assert.equal(previewPackage(p,{runtime}).task,null);+ const p=example();p.requires.taskSchemaVersion=4;p.task.schemaVersion=4;assert.equal(previewPackage(p,{runtime}).task,null);});test('legacy JSON remains previewable; hashes identify bytes, not publisher trust',()=>{const text='{"id":"legacy","steps":[]}';const p=previewPackage(text,{runtime});assert.equal(p.kind,'legacy-task');assert.equal(p.compatible,true);@@ -79,7 +79,7 @@ test('published example previews successfully and never enables itself',()=>{test('a future larger task list is not truncated by editing another task',()=>{const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-task-list-'));try{- const tasks=Array.from({length:201},(_,i)=>({schemaVersion:3,id:'future_'+i,steps:[]}));+ const tasks=Array.from({length:201},(_,i)=>({schemaVersion:4,id:'future_'+i,steps:[]}));fs.writeFileSync(path.join(dir,'automations.json'),JSON.stringify(tasks));const read=automation.readAutomations(dir);assert.equal(read.length,201);automation.writeAutomations(dir,read);assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir,'automations.json'))),tasks);diff --git a/test/automation-safety-review.test.js b/test/automation-safety-review.test.jsindex 61f49ec..74b4bd4 100644--- a/test/automation-safety-review.test.js+++ b/test/automation-safety-review.test.js@@ -8,7 +8,7 @@ const { createSafetyReviewTask, executeTask } = require('../scripts/automation')test('safety review creates only a model-selected V2 conversation about one stored task', () => {const task = createSafetyReviewTask('/tmp/workdaddy-review', 'untrusted-task');- assert.equal(task.schemaVersion, 2);+ assert.equal(task.schemaVersion, 3);assert.equal(task.trigger.type, 'manual');assert.deepEqual(task.steps.map(step => step.op), ['session.create']);assert.equal(task.steps[0].model, 'deepseek-v4.1-flash');diff --git a/test/automation-switch-sync.test.js b/test/automation-switch-sync.test.jsnew file mode 100644index 0000000..dc054a6--- /dev/null+++ b/test/automation-switch-sync.test.js@@ -0,0 +1,110 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const vm = require('node:vm');+const path = require('node:path');+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+const tick = () => new Promise(resolve => setImmediate(resolve));++function harness() {+ let active = { uid: 'a' }, reloadPriority = 0;+ const switches = [], jobs = [], phases = [];+ const ctx = {+ PROFILE: { kind: 'workbuddy' }, DATA_DIR: '/synthetic', log() {},+ cdp: { connected: true }, cdpSend: async () => ({ result: { value: false } }),+ currentAccount: () => active, switchTo: (_dir, uid) => { switches.push(uid); return (active = { uid }); },+ reloadWorkBuddyPage: async () => {}, pendingAutomationAccountSwitch: null,+ dispatchAutomationEvent() {}, mainFrameNavigationSerial: 1,+ beginRendererReloadPriority: () => { reloadPriority++; return () => { reloadPriority--; }; },+ getAutoCopyRules: () => ({ allSessions: true }),+ autoCopyJobs: new Map(), autoCopyQueue: [], autoCopyWorkerRunning: false,+ sessionCopyLocks: new Map(), sleep: tick,+ startAutoCopyJob: (_from, to) => {+ let complete;+ const job = { id: 'job-' + jobs.length, targetUid: to, status: 'running', total: 1, processed: 0,+ failed: 0, partial: 0, conflicts: 0, completion: new Promise(resolve => { complete = resolve; }) };+ job.finish = (status = 'done') => { job.status = status; job.processed = 1; ctx.autoCopyWorkerRunning = false; if (ctx.recordAccountSyncResult) ctx.recordAccountSyncResult(job); complete(job); };+ ctx.autoCopyWorkerRunning = true; ctx.autoCopyJobs.set(job.id, job); jobs.push(job); return job;+ },+ };+ vm.runInNewContext(source.slice(source.indexOf('let accountSwitchInProgress ='), source.indexOf('function startAutomationRun(')), ctx);+ const options = { onProgress: value => phases.push(value) };+ return { ctx, switches, jobs, phases, options, priority: () => reloadPriority, active: () => active };+}++test('switch waits for its exact sync job and releases reload priority before waiting', async () => {+ const h = harness(); let done = false;+ const run = h.ctx.automationSwitchAccount({ uid: 'b' }, h.options).then(() => { done = true; });+ await tick(); await tick();+ assert.equal(h.jobs.length, 1); assert.equal(h.priority(), 0);+ assert.equal(done, false, 'switch must not resolve merely because sync started');+ await assert.rejects(h.ctx.assertAccountSwitchIdle(), /账号正在切换/);+ h.jobs[0].finish(); await run;+ assert.equal(done, true); assert.ok(h.phases.some(p => p.phase === 'syncing-sessions'));+ (await h.ctx.assertAccountSwitchIdle())();+});++test('queued automation switches wait for preceding sync before switching', async () => {+ const h = harness();+ const first = h.ctx.automationSwitchAccount({ uid: 'b' }, h.options);+ const next = h.ctx.automationSwitchAccount({ uid: 'c' }, h.options);+ await tick(); await tick(); assert.deepEqual(h.switches, ['b']);+ h.jobs[0].finish(); await first; await tick(); await tick();+ assert.deepEqual(h.switches, ['b', 'c']);+ h.jobs[1].finish(); await next;+});++for (const status of ['partial', 'conflict', 'error']) test('failed sync blocks following switch and restoration: ' + status, async () => {+ const h = harness();+ const run = h.ctx.automationSwitchAccount({ uid: 'b' }, h.options);+ const rejected = assert.rejects(run, /同步/);+ await tick(); await tick(); h.jobs[0].finish(status); await rejected;+ await assert.rejects(h.ctx.automationSwitchAccount({ uid: 'a' }, { ...h.options, restore: true }), /同步/);+ assert.deepEqual(h.switches, ['b']);+});++test('same-account steps also wait for existing inbound sync', async () => {+ const h = harness(); const job = h.ctx.startAutoCopyJob('other', 'a'); let done = false;+ const run = h.ctx.automationSwitchAccount({ uid: 'a' }, h.options).then(() => { done = true; });+ await tick(); await tick(); assert.equal(done, false);+ job.finish(); await run; assert.deepEqual(h.switches, []);+});++test('cancellation drains writing before releasing the switch lock; restore is still safe', async () => {+ const h = harness(); let cancelled = false, done = false;+ const run = h.ctx.automationSwitchAccount({ uid: 'b' }, { ...h.options, isCancelled: () => cancelled });+ const rejected = assert.rejects(run, /停止/).then(() => { done = true; });+ await tick(); await tick(); cancelled = true; await tick();+ assert.equal(done, false);+ await assert.rejects(h.ctx.assertAccountSwitchIdle(), /账号正在切换/);+ h.jobs[0].finish(); await rejected;+ const restore = h.ctx.automationSwitchAccount({ uid: 'a' }, { ...h.options, restore: true });+ await tick(); await tick(); h.jobs[1].finish(); await restore;+ assert.equal(h.active().uid, 'a');+});++test('waiting for existing manual copy can be cancelled without a switch', async () => {+ const h = harness(); let cancelled = false;+ h.ctx.sessionCopyLocks.set('manual', Promise.resolve());+ const run = h.ctx.automationSwitchAccount({ uid: 'b' }, { isCancelled: () => cancelled });+ const rejected = assert.rejects(run, /停止/);+ await tick(); cancelled = true; await rejected;+ assert.deepEqual(h.switches, []);+});++test('pruning public job history cannot erase failed synchronization; successful retry clears it', async () => {+ const h = harness(); const failed = h.ctx.startAutoCopyJob('other', 'a');+ failed.finish('partial'); h.ctx.autoCopyJobs.clear();+ let outcome;+ const attempt = h.ctx.automationSwitchAccount({ uid: 'b' }).then(() => { outcome = 'success'; }, error => { outcome = error.message; });+ await tick(); await tick();+ if (h.jobs[1]) h.jobs[1].finish();+ await attempt;+ assert.match(outcome, /同步/);+ assert.deepEqual(h.switches, []);+ const retry = h.ctx.startAutoCopyJob('other', 'a'); retry.finish();+ const run = h.ctx.automationSwitchAccount({ uid: 'b' });+ await tick(); await tick(); h.jobs[2].finish(); await run;+ assert.deepEqual(h.switches, ['b']);+});diff --git a/test/automation-transfer.test.js b/test/automation-transfer.test.jsindex 051f7b8..09ab7ae 100644--- a/test/automation-transfer.test.js+++ b/test/automation-transfer.test.js@@ -57,7 +57,7 @@ test('invalid selected task and capacity failures do not partially save',()=>{test('JSON imports reject unrelated documents and block future schema, dependencies and missing package inputs',()=>{for(const doc of [{hello:'world'},[],{kind:'workdaddy.automation-index',items:[]}]){const p=previewImport({content:JSON.stringify(doc)},[],runtime);assert.equal(p.entries[0].compatible,false);}assert.equal(previewImport({content:JSON.stringify({...task(),schemaVersion:2})},[],runtime).entries[0].compatible,true);- for(const doc of [{...task(),schemaVersion:3},{...task(),requires:{minWorkDaddyVersion:'9.0.0',taskSchemaVersion:1,capabilities:[]}}])assert.equal(previewImport({content:JSON.stringify(doc)},[],runtime).entries[0].compatible,false);+ for(const doc of [{...task(),schemaVersion:4},{...task(),requires:{minWorkDaddyVersion:'9.0.0',taskSchemaVersion:1,capabilities:[]}}])assert.equal(previewImport({content:JSON.stringify(doc)},[],runtime).entries[0].compatible,false);const pkg=JSON.parse(fs.readFileSync(path.join(__dirname,'../examples/automation-packages/account-summary.workdaddy.json')));const p=previewImport({content:JSON.stringify(pkg)},[],runtime);assert.equal(p.entries[0].compatible,true);assert.notEqual(p.entries[0].task.id,'package_preview');assert.equal(p.entries[0].task.enabled,false);pkg.inputs.requiredValue={type:'string',required:true};assert.equal(previewImport({content:JSON.stringify(pkg)},[],runtime).entries[0].compatible,false);diff --git a/test/automation-ui-copy.test.js b/test/automation-ui-copy.test.jsindex 3ff28e0..22b4171 100644--- a/test/automation-ui-copy.test.js+++ b/test/automation-ui-copy.test.js@@ -7,11 +7,11 @@ const path = require('node:path');const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');-test('automation toolbar has one V2 protocol command and keeps creation and batch actions at the right', () => {+test('automation toolbar has one V3 protocol command and keeps creation and batch actions at the right', () => {const start = source.indexOf('automationPane.innerHTML =');const end = source.indexOf('automationPane.querySelector', start);const toolbar = source.slice(start, end);- assert.match(toolbar, /id="wbs-auto-cap">自动化接口协议 V2<\/button>/);+ assert.match(toolbar, /id="wbs-auto-cap">自动化接口协议 V3<\/button>/);assert.doesNotMatch(toolbar, /wbs-auto-api-version|查看接口说明/);assert.match(toolbar, /id="wbs-auto-pick"[\s\S]*class="wbs-auto-right-actions"[\s\S]*id="wbs-auto-create"[\s\S]*id="wbs-auto-batch"/);assert.match(source, /\.wbs-auto-right-actions\{[^}]*margin-left:auto/);diff --git a/test/automation-v2.test.js b/test/automation-v2.test.jsindex 846ced8..ddc9282 100644--- a/test/automation-v2.test.js+++ b/test/automation-v2.test.js@@ -11,10 +11,10 @@ const {} = require('../scripts/automation');test('automation v2 remains backward compatible and exposes generic runtime metadata', async () => {- assert.equal(SCHEMA_VERSION, 2);+ assert.equal(SCHEMA_VERSION, 3);assert.equal(isSupportedTaskSchema({ schemaVersion: 1 }), true);assert.equal(isSupportedTaskSchema({ schemaVersion: 2 }), true);- assert.equal(isSupportedTaskSchema({ schemaVersion: 3 }), false);+ assert.equal(isSupportedTaskSchema({ schemaVersion: 4 }), false);const task = validateTask({schemaVersion: 2,diff --git a/test/automation-v3.test.js b/test/automation-v3.test.jsnew file mode 100644index 0000000..2ede588--- /dev/null+++ b/test/automation-v3.test.js@@ -0,0 +1,43 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const { SCHEMA_VERSION, executeTask, validateTask, isSupportedTaskSchema, capabilityText } = require('../scripts/automation');+const { previewPackage } = require('../scripts/automation-packages');++test('V3 advertises current schema and imports V1/V2/V3 including requirements', () => {+ assert.equal(SCHEMA_VERSION, 3);+ for (const schemaVersion of [1, 2, 3]) {+ assert.equal(isSupportedTaskSchema({ schemaVersion }), true);+ const result = previewPackage({ schemaVersion, id: 'compat', steps: [], requires: { minWorkDaddyVersion: '1.0.0', taskSchemaVersion: schemaVersion, capabilities: [] } }, { runtime: { version: '1.2.91' } });+ assert.equal(result.compatible, true);+ }+ assert.equal(isSupportedTaskSchema({ schemaVersion: 4 }), false);+});++test('V3 filters before physical switches and restores original after awaited work', async () => {+ let active = { uid: 'original' };+ const switches = [], sends = [], reads = [];+ const task = { schemaVersion: 3, id: 'filtered', steps: [{+ op: 'account.forEach', switch: true, accounts: 'all',+ prepare: [{ op: 'state.get', scope: 'account', key: 'pending', saveAs: 'pending' }],+ condition: { left: '{{vars.pending}}', operator: 'truthy' },+ steps: [{ op: 'session.create', message: 'fixture', model: 'hy3' }],+ }] };+ await executeTask(task, {+ listAccounts: async () => [{ uid: 'done' }, { uid: 'pending' }, { uid: 'done2' }],+ currentAccount: () => active,+ getState: async (_scope, uid) => { reads.push(uid); return uid === 'pending'; },+ accountSwitch: async account => { await new Promise(resolve => setImmediate(resolve)); switches.push(account.uid); active = account; },+ sessionAction: async () => { sends.push(active.uid); },+ });+ assert.deepEqual(reads, ['done', 'pending', 'done2']);+ assert.deepEqual(switches, ['pending', 'original']);+ assert.deepEqual(sends, ['pending']);+});++test('preparation cannot send, switch or write persistent state; old tasks cannot silently ignore V3 fields', () => {+ for (const op of ['session.create', 'account.forEach', 'account.checkin', 'state.set', 'http.request']) {+ assert.throws(() => validateTask({ schemaVersion: 3, id: 'invalid', steps: [{ op: 'account.forEach', prepare: [{ op }], steps: [] }] }), /prepare/);+ }+ for (const schemaVersion of [1, 2]) assert.throws(() => validateTask({ schemaVersion, id: 'old', steps: [{ op: 'account.forEach', condition: { left: true }, steps: [] }] }), /V3/);+});diff --git a/test/automation.test.js b/test/automation.test.jsindex e9ec34a..a0d7efc 100644--- a/test/automation.test.js+++ b/test/automation.test.js@@ -69,8 +69,8 @@ test('account loops can physically switch each account and restore the original'test('capability protocol documents every supported step and rejects event ids as steps', () => {const documented = new Set(CAPABILITIES.map((item) => item.id));for (const op of SUPPORTED_OPS) assert.equal(documented.has(op), true, `missing capability documentation for ${op}`);- assert.match(capabilityText('zh'), /WorkDaddy 自动化任务协议 v2/);- assert.match(capabilityText('en'), /WorkDaddy Automation Task Protocol v2/);+ assert.match(capabilityText('zh'), /WorkDaddy 自动化任务协议 v3/);+ assert.match(capabilityText('en'), /WorkDaddy Automation Task Protocol v3/);assert.match(capabilityText('zh'), /基础接口总目录:[\s\S]*logic:[\s\S]*account:[\s\S]*http:[\s\S]*dom:[\s\S]*session:[\s\S]*state:[\s\S]*notify:/);assert.match(capabilityText('zh'), /HTTP 输入:[\s\S]*响应:\{ok,status,headers,text,json\}/);assert.match(capabilityText('en'), /Capability index:[\s\S]*Per-operation reference and minimal examples:/);diff --git a/test/conversation-usage.test.js b/test/conversation-usage.test.jsindex 9581d51..b541d3e 100644--- a/test/conversation-usage.test.js+++ b/test/conversation-usage.test.js@@ -59,9 +59,12 @@ test('conversation usage UI uses a body-fixed mount, bottom spacer and message sassert.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-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'/);assert.match(source, /wbs-session-usage-detail-row\{[^}]*font-size:12px/);assert.match(source, /wbs-session-usage-detail-note/);- assert.match(source, /部分会话尚未完成,当前 Token 和积分仅按已完成用量统计/);+ assert.match(source, /用量统计会随会话完成逐步更新/);+ assert.doesNotMatch(source, /部分会话尚未完成,当前 Token 和积分仅按已完成用量统计/);assert.match(source, /if \(open\) \{[\s\S]{0,260}closeSessionCopyNotice\(\)/);assert.match(source, /pollSessionCopyNotice[\s\S]{0,500}if \(state\.open\)/);assert.match(source, /return usageNumber\(value\) > 0 \? '≥' \+ formatted/);diff --git a/test/session-copy-rate.test.js b/test/session-copy-rate.test.jsnew file mode 100644index 0000000..e54f970--- /dev/null+++ b/test/session-copy-rate.test.js@@ -0,0 +1,49 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const os = require('node:os');+const vm = require('node:vm');+const { readSnapshot, applySnapshot } = require('../scripts/session-sync');++test('copy byte count includes changed published payloads, excludes unchanged files, backups and deletions', async t => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-copy-rate-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const write = (id, name, bytes) => { const file = path.join(root, 'tasks', id, name); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, bytes); };+ for (const id of ['a','b']) write(id, 'unchanged.bin', Buffer.alloc(1024 * 1024));+ write('a','changed.bin','new payload'); write('b','changed.bin','old'); write('b','removed.bin','removed');+ const snapshot = id => readSnapshot(root, id, ['a','b']);+ const options = { backupRoot: path.join(root, 'backups') };+ const result = await applySnapshot(snapshot('a'), snapshot('b'), options);+ assert.equal(result.copiedBytes, Buffer.byteLength('new payload'));+ assert.equal(result.totalBytes, 1024 * 1024 + result.copiedBytes);+ assert.equal((await applySnapshot(snapshot('a'), snapshot('b'), options)).copiedBytes, 0);+});++test('public copy rate excludes queue time, updates during work and freezes after completion', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+ let now = 4000;+ const ctx = { Date: { now: () => now } };+ vm.runInNewContext(source.slice(source.indexOf('function publicAutoCopyJob('), source.indexOf('function activeAutoCopyJob(')), ctx);+ const job = { status: 'running', startedAt: 1000, copyStartedAt: 3000, copiedBytes: 1024 * 1024, processedBytes: 2 * 1024 * 1024, totalBytes: 4 * 1024 * 1024, finishedAt: null };+ assert.equal(ctx.publicAutoCopyJob(job).averageBytesPerSecond, 1024 * 1024);+ now = 5000; assert.equal(ctx.publicAutoCopyJob(job).averageBytesPerSecond, 512 * 1024);+ job.status = 'done'; job.finishedAt = 5000; now = 9000;+ assert.equal(ctx.publicAutoCopyJob(job).averageBytesPerSecond, 512 * 1024);+ assert.equal(ctx.publicAutoCopyJob({ ...job, copiedBytes: 0 }).averageBytesPerSecond, 0);+ assert.equal(ctx.publicAutoCopyJob({ status: 'queued', copiedBytes: 0 }).averageBytesPerSecond, null);+});++test('copy notice formats rate units and tolerates older daemon responses', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ assert.match(source, /summary\.hidden = active/);+ assert.doesNotMatch(source, /active \? '已处理 ' \+ processed \+ ' 个候选会话'/);+ const ctx = {};+ vm.runInNewContext(source.slice(source.indexOf(' function sessionCopySizeText('), source.indexOf(' function showSessionCopyDetails(')), ctx);+ assert.equal(typeof ctx.sessionCopyTransferText, 'function');+ assert.equal(ctx.sessionCopyTransferText({}), '');+ assert.equal(ctx.sessionCopyTransferText({ processedBytes: 1024 ** 2 * 3, totalBytes: 1024 ** 2 * 8, averageBytesPerSecond: 1024 ** 2 * 1.5 }), '已同步 3.0 MB / 8.0 MB');+ assert.equal(ctx.sessionCopyTransferText({ processedBytes: 0, totalBytes: 0, averageBytesPerSecond: 0 }), '已同步 0 B / 0 B');+ assert.equal(ctx.sessionCopyTransferText({ processedBytes: 0, averageBytesPerSecond: null }), '已同步 0 B');+});diff --git a/test/session-delete-ui.test.js b/test/session-delete-ui.test.jsindex cd6c030..77fa479 100644--- a/test/session-delete-ui.test.js+++ b/test/session-delete-ui.test.js@@ -61,6 +61,8 @@ test('all-account delete button follows the current session selection', () => {updateSessionSummary() {}, syncCheckAllBtn() {},});const start = source.indexOf(' function updateSessCount()');+ const filterStart = source.indexOf(' function filteredSessions()');+ vm.runInContext(source.slice(filterStart, source.indexOf(' // 按空间分组渲染', filterStart)), ctx);vm.runInContext(source.slice(start, source.indexOf(' // 全选按钮', start)), ctx);ctx.updateSessCount();assert.equal(button.style.display, 'none', 'hidden before checking a session');diff --git a/test/session-filter-layout.test.js b/test/session-filter-layout.test.jsnew file mode 100644index 0000000..3aa219d--- /dev/null+++ b/test/session-filter-layout.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 { isTargetForProfile } = require('../scripts/cdp-targets');++// Opt-in browser regression: runs production session UI/CSS in an isolated+// iframe with synthetic accounts and sessions. No application API is invoked.+test('All filters keep their height when the session list grows', { skip: !process.env.WORKDADDY_CDP_TEST_PORT, timeout: 30000 }, async () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const section = (start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start)));+ const styles = { css: {} };+ vm.runInNewContext(section(' css.textContent = [', " ].join('');") + " ].join('');", styles);+ const functions = section(' var sessionsState =', ' // ===== 模型 pane') + section(' function sessionCopySizeText(', ' function showSessionCopyDetails(');+ const escape = source.split('\n').filter(line => /^ function esc(?:Attr)?\(/.test(line)).join('\n');+ const fixtures = Array.from({ length: 150 }, (_, i) => ({ id: 'fixture-' + i, user_id: 'fixture', title: 'Test session', cwd: '/fixture/project-' + Math.floor(i / 2), totalBytes: i ? 1024 : 200 * 1024 ** 2 }));+ const setup = `var sessionsPane=document.querySelector('.wbs-pane'),root=document.body,IMPORT_ICON='',EXPORT_ICON='',TRASH_SVG='';+ var setBuildTimeout=()=>0,registerDisposer=()=>{},toast=()=>{};+ var fixtures=${JSON.stringify(fixtures)};+ var api=async route=>route==='/api/accounts'?{accounts:[{uid:'fixture',nickname:'Test'}],current:{uid:'fixture'}}:+ route.startsWith('/api/sessions?')?{sessions:route.includes('range=today')?fixtures.slice(0,1):fixtures,totalBytes:1}:{};`;+ const targets = await (await fetch('http://127.0.0.1:' + process.env.WORKDADDY_CDP_TEST_PORT + '/json/list')).json();+ const target = targets.find(target => isTargetForProfile(target, { id: 'workbuddy-cn', kind: 'workbuddy' }));+ assert.ok(target, 'a verified WorkBuddy renderer is required');+ const socket = new WebSocket(target.webSocketDebuggerUrl);+ await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; });+ let sequence = 0;+ const pending = new Map();+ socket.onmessage = event => {+ const result = JSON.parse(event.data), waiter = pending.get(result.id);+ if (waiter) { pending.delete(result.id); clearTimeout(waiter.timer); result.error ? waiter.reject(Error(result.error.message)) : waiter.resolve(result.result); }+ };+ const evaluate = async expression => {+ const result = await new Promise((resolve, reject) => {+ const id = ++sequence;+ const timer = setTimeout(() => { pending.delete(id); reject(Error('UI evaluation timed out')); }, 8000);+ pending.set(id, { resolve, reject, timer });+ socket.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, awaitPromise: true, returnByValue: true } }));+ });+ if (result.exceptionDetails) throw Error(result.exceptionDetails.exception?.description || result.exceptionDetails.text);+ return result.result.value;+ };+ try {+ await evaluate(`(async()=>{+ const frame=document.createElement('iframe');frame.id='workdaddy-filter-layout-test';+ frame.style.cssText='position:fixed;left:0;top:0;width:720px;height:630px;border:0;z-index:2147483647';document.body.appendChild(frame);+ const d=frame.contentDocument;d.open();d.write('<!doctype html><html><head></head><body style="margin:0"><div class="wbs-panel" style="display:flex;position:relative;width:100%;height:600px;max-height:600px;right:auto;bottom:auto"><div class="wbs-body"><div class="wbs-pane active" data-pane="sessions"></div></div></div></body></html>');d.close();+ const style=d.createElement('style');style.textContent=${JSON.stringify(styles.css.textContent)};d.head.appendChild(style);+ frame.contentWindow.eval(${JSON.stringify(setup + escape + functions + '\nbuildSessionsPane();')});+ await Promise.resolve();await Promise.resolve();return true;+ })()`);+ for (const width of [720, 360]) for (const height of [600, 350]) for (const theme of ['light', 'class', 'attribute', 'body']) {+ const result = await evaluate(`(async()=>{+ const frame=document.getElementById('workdaddy-filter-layout-test'),w=frame.contentWindow,d=frame.contentDocument;+ frame.style.width='${width}px';d.querySelector('.wbs-panel').style.height='${height}px';+ d.documentElement.className='${theme === 'class' ? 'cb-dark' : ''}';d.documentElement.dataset.theme='${theme === 'attribute' ? 'dark' : 'light'}';d.body.dataset.vscodeThemeName='${theme === 'body' ? 'dark' : ''}';+ const header=d.querySelector('.wbs-sess-filters'),list=d.querySelector('.wbs-sess-list');+ const measure=()=>({height:header.getBoundingClientRect().height,rows:d.querySelectorAll('.wbs-sess-row').length});+ d.querySelector('[data-min-bytes="104857600"]').click();const small=measure();+ d.querySelector('[data-min-bytes="0"]').click();const all=measure();+ d.querySelector('[data-range="today"]').click();await Promise.resolve();await Promise.resolve();const today=measure();+ d.querySelector('[data-range="all"]').click();await Promise.resolve();await Promise.resolve();const allTime=measure();+ const bounds=header.getBoundingClientRect();+ const unclipped=[...header.querySelectorAll('button,select')].every(el=>{const r=el.getBoundingClientRect();return r.top>=bounds.top-1&&r.bottom<=bounds.bottom+1;});+ list.scrollTop=100;return {small,all,today,allTime,unclipped,scrollable:list.scrollTop>0};+ })()`);+ const label = `${width}px / ${height}px / ${theme}: ${JSON.stringify(result)}`;+ assert.equal(result.small.rows, 1, label);+ assert.equal(result.all.rows, 150, label);+ assert.equal(result.today.rows, 1, label);+ assert.equal(result.allTime.rows, 150, label);+ assert.ok(Math.abs(result.small.height - result.all.height) < 1, label);+ assert.ok(Math.abs(result.today.height - result.allTime.height) < 1, label);+ assert.ok(result.unclipped && result.scrollable, label);+ }+ } finally {+ await evaluate("document.getElementById('workdaddy-filter-layout-test')?.remove()");+ socket.close();+ }+});diff --git a/test/session-size-filter.test.js b/test/session-size-filter.test.jsnew file mode 100644index 0000000..68d5071--- /dev/null+++ b/test/session-size-filter.test.js@@ -0,0 +1,53 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const vm = require('node:vm');+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');+const section = (start, end) => source.includes(start) ? source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start))) : '';+function harness() {+ const controls = {};+ const control = id => controls[id] ||= { innerHTML: '', textContent: '', style: {}, disabled: false, addEventListener(type, callback) { this[type] = callback; }, querySelectorAll: () => [] };+ const ctx = vm.createContext({+ sessionsState: { list: [{ id: 'small', totalBytes: 10 * 1024 ** 2, title: 'small' }, { id: 'large', totalBytes: 100 * 1024 ** 2 + 1, title: '<unsafe>', is_playground: 1 }, { id: 'unknown', totalBytes: null }], selected: {}, wsExpanded: {}, totalBytes: 2 * 1024 ** 3, minBytes: 10 * 1024 ** 2 },+ sessionsPane: { querySelector: control, querySelectorAll: () => [] },+ esc: value => String(value).replace(/</g, '<'), escAttr: String,+ updateAutoCopyAllButton() {}, bindSessEvents() {}, isTaskSessionRecordUI: s => !!s.is_playground,+ fmtHumanTime: () => 'now', shortWs: String, SESS_WS_INIT: 5, SESS_WS_STEP: 5,+ });+ vm.runInContext([+ section(' function filteredSessions()', ' // 按空间分组渲染'),+ section(' function renderSessions()', ' function updateAutoCopyAllButton()'),+ section(' function updateSessCount()', ' // 人性化时间'),+ section(' function wireSessionsPane()', ' function selectedSessIds()'),+ section(' function selectedSessIds()', ' function showSessModal('),+ section(' function sessionCopySizeText(', ' function showSessionCopyDetails('),+ ].join('\n'), ctx);+ return { ctx, control };+}+test('size filter excludes exact thresholds and unknown sizes; select-all operates only on matches', () => {+ const { ctx, control } = harness();+ assert.deepEqual(Array.from(ctx.filteredSessions(), s => s.id), ['large']);+ ctx.wireSessionsPane(); control('#wbs-sess-check-all').click();+ assert.deepEqual(Array.from(ctx.selectedSessIds()), ['large']);+ assert.match(control('#wbs-sess-count').innerHTML, /共 <strong>1<\/strong> 个会话/);+ assert.match(control('#wbs-sess-list').innerHTML, /wbs-sess-size.*100\.0 MB/);+ assert.doesNotMatch(control('#wbs-sess-list').innerHTML, /<unsafe>|small/);+ ctx.sessionsState.batchMode = false;+ const button = { getAttribute: () => '0' };+ control('#wbs-sess-size-seg').click({ target: { closest: () => button } });+ assert.match(control('#wbs-sess-count').innerHTML, /总大小 <strong>2\.0 GB<\/strong>/);+ assert.equal(ctx.filteredSessions().length, 3);+ assert.equal(ctx.selectedSessIds().length, 0);+ ctx.sessionsState.minBytes = 500 * 1024 ** 2; ctx.renderSessions();+ assert.match(control('#wbs-sess-list').innerHTML, /当前筛选下没有会话/);+});++test('session summary formats large counts and emphasizes numeric values', () => {+ const { ctx, control } = harness();+ ctx.sessionsState.list = Array.from({ length: 1111 }, (_, index) => ({ id: String(index), totalBytes: 0 }));+ ctx.sessionsState.minBytes = 0;+ ctx.updateSessionSummary(control('#wbs-sess-count'));+ assert.match(control('#wbs-sess-count').innerHTML, /共 <strong>1,111<\/strong> 个会话/);+ assert.match(control('#wbs-sess-count').innerHTML, /总大小 <strong>2\.0 GB<\/strong>/);+});diff --git a/test/session-size-summary.test.js b/test/session-size-summary.test.jsnew file mode 100644index 0000000..4299d13--- /dev/null+++ b/test/session-size-summary.test.js@@ -0,0 +1,28 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const vm = require('node:vm');+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/daemon.js'), 'utf8');+async function query(range, sizes) {+ const rows = [{ id: 'old', user_id: 'owner', created_at: 10 }, { id: 'new', user_id: 'owner', created_at: 200 }];+ const ctx = vm.createContext({+ req: { method: 'GET' }, p: '/api/sessions', url: new URL('http://localhost/api/sessions?range=' + range), res: {}, DATA_DIR: '', PROFILE: { dataRoot: '' },+ normalizeAutoCopyLineages() {}, currentAccount: () => ({ uid: 'owner' }), sessionRangeMs: r => r === 'all' ? 0 : 100,+ sqliteQuery: async (sql, params) => { assert.ok(params.includes('owner')); return sql.includes('>= ?') ? rows.slice(1) : rows; },+ getAutoCopyRules: () => ({ sessionIds: [], workspaces: [], allLineages: {} }), canonicalWorkspace: String,+ dedupeAutoCopySessionRows: rows => rows,+ sessionSync: { readSessionSizes: async () => new Map(sizes) }, json: (_, status, body) => { assert.equal(status, 200); return body; },+ });+ const start = source.indexOf(" if (req.method === 'GET' && p === '/api/sessions')");+ return vm.runInContext('(async () => {' + source.slice(start, source.indexOf(' // 会话空间列表', start)) + '})()', ctx);+}+test('account total includes all sessions even when the time filter hides old sessions', async () => {+ const result = await query('today', [['old', 1000], ['new', 2000]]);+ assert.deepEqual(Array.from(result.sessions, s => s.id), ['new']);+ assert.equal(result.totalBytes, 3000);+ assert.equal((await query('all', [['old', 1000], ['new', 2000]])).totalBytes, 3000);+});+test('an unreadable session cannot silently understate the account total', async () => {+ assert.equal((await query('today', [['old', null], ['new', 2000]])).totalBytes, null);+});diff --git a/test/session-sizes.test.js b/test/session-sizes.test.jsnew file mode 100644index 0000000..b42b36e--- /dev/null+++ b/test/session-sizes.test.js@@ -0,0 +1,36 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const os = require('node:os');+const { readSessionSizes } = require('../scripts/session-sync');++test('session size counts only its complete sync payload, using metadata even for huge or invalid journals', async t => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-sizes-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const files = ['projects/p/a.jsonl', 'projects/p/a/sub/data', 'workspace/sessions/a/file', 'tasks/a/file', 'file-history/a/file', 'artifact-index/a.json'];+ for (const relative of [...files, 'projects/p/b.jsonl', 'unrelated/a']) {+ const file = path.join(root, relative);+ fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, 'bad json');+ }+ const huge = 2 * 1024 ** 3 + 1;+ fs.truncateSync(path.join(root, files[2]), huge);+ const result = await readSessionSizes(root, ['a', 'b', 'missing', '../escape']);+ assert.equal(result.get('a'), huge + 5 * 8);+ assert.equal(result.get('b'), 8);+ assert.equal(result.get('missing'), 0);+ assert.equal(result.get('../escape'), null);+});++test('symlinked paths are unknown, never followed or reported as complete sizes', async t => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-sizes-links-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'projects/p'), { recursive: true });+ fs.writeFileSync(path.join(root, 'projects/p/good.jsonl'), 'ok');+ fs.symlinkSync('good.jsonl', path.join(root, 'projects/p/link.jsonl'));+ const sizes = await readSessionSizes(root, ['good', 'link']);+ assert.equal(sizes.get('good'), 2); assert.equal(sizes.get('link'), null);+ fs.symlinkSync(path.join(root, 'projects'), path.join(root, 'tasks'), 'dir');+ assert.equal((await readSessionSizes(root, ['good'])).get('good'), null);+});diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.jsindex 6489736..5e93865 100644--- a/test/session-sync-daemon.test.js+++ b/test/session-sync-daemon.test.js@@ -21,8 +21,10 @@ function harness(t) {rows.set(id, { id, user_id: uid, title: 'fixture', created_at: 1, updated_at: 1 });lib.addAutoCopySessionMember(root, lineage, uid, id); write(id, base);}+ const syncCacheMap = new Map();const ctx = { ...lib, sessionSync, fs, path, crypto, DATA_DIR: root, PROFILE: { dataRoot: root, kind: 'workbuddy' },- SESSION_COPY_COLUMNS: ['id', 'user_id'], sessionCopyLocks: new Map(), yieldAutoCopyToRenderer: async () => {}, assertSessionSyncIdle: async () => {},+ accountSwitchInProgress: false, SESSION_COPY_COLUMNS: ['id', 'user_id'], sessionCopyLocks: new Map(), yieldAutoCopyToRenderer: async () => {}, assertSessionSyncIdle: async () => {},+ getSessionSyncCache: () => syncCacheMap, scheduleSessionSyncCacheSave: () => {},log: () => {}, sqliteQuery: async (_, params) => {const row = rows.get(params[0]); return row && (!params[1] || params[1] === row.user_id) ? [{ ...row }] : [];},@@ -39,6 +41,31 @@ test('account two continuation updates account one and never account three', asyassert.equal(result.status, 'copied');assert.deepEqual(fs.readFileSync(h.file('a')), fs.readFileSync(h.file('b')));assert.deepEqual(fs.readFileSync(h.file('c')), third);+ assert.equal(result.warning, '');+ assert.equal(result.totalBytes, fs.statSync(h.file('a')).size);+ assert.equal(result.copiedBytes, fs.statSync(h.file('a')).size);+ assert.equal((await h.copy()).copiedBytes, 0);+});++test('sessions over 100 MiB copy completely and report only an advisory, including on repeat sync', async t => {+ const h = harness(t);+ const file = path.join(h.root, 'workspace/sessions/a/large.bin');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, 'large session fixture');+ const size = 100 * 1024 * 1024 + 1;+ fs.truncateSync(file, size);+ const result = await h.copy();+ assert.equal(result.status, 'copied');+ assert.equal(result.failedFiles, 0);+ assert.equal(result.warning, '会话超过 100 MB,同步可能较慢');+ const target = path.join(h.root, 'workspace/sessions/b/large.bin');+ assert.equal(fs.statSync(target).size, size);+ assert.equal(result.totalBytes, size + fs.statSync(h.file('b')).size);+ const hash = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');+ assert.equal(hash(target), hash(file));+ const repeat = await h.copy();+ assert.equal(repeat.status, 'skipped');+ assert.equal(repeat.warning, result.warning);});test('divergent copies survive repeated switches and stale mappings cannot force overwrite', async t => {const h = harness(t);@@ -92,24 +119,37 @@ test('manual and automatic switching bypass session activity while retaining ope(await ctx.assertAccountSwitchIdle())();}for (const block of [source.slice(source.indexOf('function automationSwitchAccount('), source.indexOf('function startAutomationRun(')), source.slice(source.indexOf("if (req.method === 'POST' && p === '/api/switch')"))]) {- assert.ok(block.indexOf('await assertAccountSwitchIdle()') < block.indexOf('switchTo(DATA_DIR, uid, log)'));+ assert.ok(/await (assertAccountSwitchIdle|acquireAutomationAccountSwitch)\(/.test(block) && block.search(/await (assertAccountSwitchIdle|acquireAutomationAccountSwitch)\(/) < block.indexOf('switchTo(DATA_DIR, uid, log)'));}});test('mixed sync jobs continue after divergence and report every result', async () => {const results = ['conflict', 'copied', 'skipped', 'error'];const ctx = { crypto, 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' }; },+ 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' : '' }; },log() {}, runAutoCopyQueue() {}, pruneAutoCopyJobs() {}, setTimeout: () => ({ unref() {} }),};const start = source.indexOf('function startAutoCopyJob(');- vm.runInNewContext(source.slice(start, source.indexOf('function publicAutoCopyJob(', start)), ctx);+ vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);const job = ctx.startAutoCopyJob('one', 'two', []);await ctx.autoCopyQueue[0].run();assert.equal(job.processed, 4);+ assert.equal(job.copiedBytes, 123456);assert.equal(job.conflicts, 1); assert.equal(job.copied, 1); assert.equal(job.skipped, 1); assert.equal(job.failedItems, 1);assert.equal(job.details[1].branched, true);+ assert.equal(job.details[1].warning, 'large session advisory');+ assert.equal(job.warning, 'large session advisory');assert.deepEqual(Array.from(job.details, item => item.status), ['conflict', 'copied', 'skipped', 'failed']);+ results.splice(0, results.length, 'copied', 'skipped');+ const advisoryOnly = ctx.startAutoCopyJob('one', 'two', []);+ await ctx.autoCopyQueue[1].run();+ const published = ctx.publicAutoCopyJob(advisoryOnly);+ assert.equal(published.status, 'done');+ assert.equal(published.failed, 0);+ assert.equal(published.failedItems, 0);+ assert.equal(published.warning, 'large session advisory');+ assert.equal(published.details[0].warning, 'large session advisory');+ assert.equal(published.details[0].totalBytes, 123456);});test('macOS packaging includes the required sync module', () => {const script = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');diff --git a/test/session-sync.test.js b/test/session-sync.test.jsindex 606eef5..6e676b2 100644--- a/test/session-sync.test.js+++ b/test/session-sync.test.js@@ -18,6 +18,26 @@ function fixture(t) {};return { root, file, write, read: id => readSnapshot(root, id, ['a', 'b', 'c']) };}+test('session snapshots accept payloads larger than the former 64 MiB limit', t => {+ const f = fixture(t); f.write('a', base);+ const file = path.join(f.root, 'workspace', 'sessions', 'a', 'large.bin');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const size = 64 * 1024 * 1024 + 1;+ fs.writeFileSync(file, '');+ fs.truncateSync(file, size);+ const snapshot = f.read('a');+ assert.equal(snapshot.files.get('workspace/sessions/__session__/large.bin').bytes.length, size);+});++test('session snapshots accept more than 20,000 files', t => {+ const f = fixture(t); f.write('a', base);+ const directory = path.join(f.root, 'workspace', 'sessions', 'a');+ fs.mkdirSync(directory, { recursive: true });+ for (let i = 0; i <= 20000; i++) fs.writeFileSync(path.join(directory, 'file-' + i + '.bin'), '');+ const snapshot = f.read('a');+ assert.equal(snapshot.files.size, 20002);+});+test('same content skips; only a full prefix permits replacement, irrespective of mtime', t => {const f = fixture(t); f.write('a', base); f.write('b', base);assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'equal');@@ -174,3 +194,37 @@ test('malformed official artifact index still blocks sync and names the failingfs.writeFileSync(path.join(f.root, 'artifact-index/a.json'), '{broken');assert.throws(() => f.read('a'), /会话产物索引损坏,未同步/);});++test('fingerprint cache reuses hashes for unchanged files and reloads changed ones', async t => {+ const f = fixture(t); f.write('a', base); f.write('b', [...base, message('user', 'continued')]);+ const cache = new Map();+ const first = readSnapshot(f.root, 'a', ['a', 'b', 'c'], cache);+ assert.ok(cache.size > 0);+ // A cache hit defers payload reads: bytes arrive through a lazy getter.+ const second = readSnapshot(f.root, 'a', ['a', 'b', 'c'], cache);+ const transcript = second.files.get('projects/project/__session__.jsonl');+ assert.equal(typeof Object.getOwnPropertyDescriptor(transcript, 'bytes').get, 'function');+ assert.deepEqual(second.records, first.records);+ assert.equal(compareSnapshots(second, readSnapshot(f.root, 'b', ['a', 'b', 'c'], cache)).kind, 'right-extends');+ // Alias-dependent semantics are recomputed when the alias set changes.+ const otherAliases = readSnapshot(f.root, 'a', ['a', 'b', 'c', 'd'], cache);+ assert.notEqual(otherAliases.files.get('projects/project/__session__.jsonl').semanticAliases.length, 0);+ // Changed content invalidates the fingerprint and is re-read.+ f.write('a', [...base, message('assistant', 'updated')]);+ const changed = readSnapshot(f.root, 'a', ['a', 'b', 'c'], cache);+ assert.equal(changed.records.length, first.records.length + 1);+ assert.notEqual(changed.files.get('projects/project/__session__.jsonl').hash, first.files.get('projects/project/__session__.jsonl').hash);+});++test('cached snapshots still drive copy, race checks and rollback', async t => {+ const f = fixture(t); f.write('a', [...base, message('user', 'continued')]); f.write('b', base);+ const cache = new Map();+ readSnapshot(f.root, 'a', ['a', 'b', 'c'], cache);+ readSnapshot(f.root, 'b', ['a', 'b', 'c'], cache);+ const source = readSnapshot(f.root, 'a', ['a', 'b', 'c'], cache);+ const target = readSnapshot(f.root, 'b', ['a', 'b', 'c'], cache);+ assert.equal(compareSnapshots(source, target).kind, 'left-extends');+ await applySnapshot(source, target, { backupRoot: path.join(f.root, 'backups') });+ assert.deepEqual(fs.readFileSync(f.file('b')), fs.readFileSync(f.file('a')));+ assert.equal(compareSnapshots(readSnapshot(f.root, 'a', ['a', 'b', 'c'], cache), readSnapshot(f.root, 'b', ['a', 'b', 'c'], cache)).kind, 'equal');+});diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 7b1bab0..50b81c8 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -768,7 +768,7 @@ test('Windows daemon lock validates the owner process instead of trusting a reustest('session ranges use last-modified time and preserve standard WorkBuddy workspaces', () => {const daemon = read('daemon.js');const inject = read('inject.js');- assert.match(daemon, /COALESCE\(last_activity_at, updated_at, created_at\) >=/);+ assert.match(daemon, /Number\(row\.last_activity_at \?\? row\.updated_at \?\? row\.created_at\) >= rangeMs/);assert.match(daemon, /ORDER BY COALESCE\(last_activity_at, updated_at, created_at\) DESC/);assert.match(inject, /sessionsState\.list = \(\(d && d\.sessions\) \|\| \[\]\);/);assert.match(inject, /if \(isTaskSessionRecordUI\(s\)\) \{ tasks\.push\(s\); return; \}/);@@ -1168,9 +1168,11 @@ test('session copy-all is a separate override with a distinct toggle and hiddenassert.match(daemon, /sourceRules\.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-auto-all"[\s\S]*id="wbs-sess-account-select"[\s\S]*id="wbs-sess-range-seg"/);+ assert.match(filters, /id="wbs-sess-account-select"[\s\S]*id="wbs-sess-size-seg"[\s\S]*id="wbs-sess-range-seg"/);+ assert.match(inject, /<div class="wbs-sess-toolbar">[\s\S]*id="wbs-sess-auto-all"[\s\S]*id="wbs-sess-batch"/);+ assert.doesNotMatch(filters, /wbs-sess-auto-all|1073741824|524288000|wbs-sess-size-select/);assert.equal((filters.match(/<div\b/g) || []).length, (filters.match(/<\/div>/g) || []).length);- assert.match(inject, /\.wbs-sess-filters\{[^}]*flex-wrap:wrap/);+ assert.match(inject, /\.wbs-sess-filters\{[^}]*flex-wrap:nowrap[^}]*overflow-x:auto/);assert.match(inject, /id="wbs-sess-import"[\s\S]*id="wbs-sess-count"/);assert.match(inject, /id="wbs-sess-auto-all"[^>]*role="checkbox"[^>]*aria-checked="false"/);assert.match(inject, /wbs-sess-auto-all-box/);@@ -1277,8 +1279,8 @@ test('credit expiry summary keeps per-account nodes and reuses the compact usageassert.match(inject, /<div data-usage-pane="credit">/);assert.match(inject, /if \(mask\.querySelector\('\[data-usage-tab\]\.active'\).*loadCredits\(\); else load\(\);/);assert.match(inject, /class="wbs-usage-segment wbs-sess-seg" id="wbs-sess-range-seg"/);- assert.match(inject, /\.wbs-sess-time-filter \.wbs-sess-seg\{[^}]*flex:1 1 auto[^}]*width:auto/);- assert.match(inject, /\.wbs-sess-account-filter\{[^}]*flex:0 1 190px/);+ assert.match(inject, /:is\(\.wbs-sess-time-filter,\.wbs-sess-size-filter\) \.wbs-sess-seg\{[^}]*flex:1 1 auto[^}]*width:auto/);+ assert.match(inject, /\.wbs-sess-account-filter\{[^}]*flex:0 1 150px/);assert.match(inject, /\.wbs-sess-seg button\{[^}]*flex:1 1 0[^}]*min-width:0/);assert.match(inject, /\.wbs-credit-tip-account\{[^}]*color:var\(--wb-icon-tertiary[^}]*font-size:10px/);assert.match(inject, /\.wbs-status-popover\.is-credit\{[^}]*height:auto[^}]*max-height:calc\(100vh - 16px\)/);