WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
feat: consolidate 1.2.8 theme, account and session updates
[email protected]d4cbe2265dd3
diff --git a/README.md b/README.mdindex 50ce751..95c8919 100644--- a/README.md+++ b/README.md@@ -22,6 +22,7 @@- **成长计划与活跃状态**:国内版账号页查询成长任务进度、当日签到和活跃状态、连续活跃天数,以及 Buddy 解锁和旅行状态。- **Token 和积分用量统计页面**:按天查看 Token 与积分消耗,支持按账号筛选,并显示模型和账号用量排行。- **积分不足时的账号切换建议**:当前账号积分不足时提示可用账号,方便继续工作。+- **模型频率限制与预计解封时间**:检测到模型限流后,在账号页展示受限模型及预计解封时间。- **自动化任务**:从 GitHub / Gitee 公开仓库发现并导入任务,或用自然语言让 WorkBuddy 创建任务;支持编辑、手动、事件和定时触发,以及运行日志、停止任务和 JSON / ZIP 导出。- **权限弹窗免打扰**:真正的零决策弹窗弹出,可以放心开启任务后睡觉。- **暂存提示词**:输入框边上一键把草稿「暂存」到待发送队列——图片 / 文件 / 引用原样保留,择机发送。@@ -252,7 +253,7 @@ WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:| Tab | 能做什么 || ------- | ----------------------------------------------------------------- |-| **账号** | 查看账号数、积分、当日签到状态、连续活跃天数、成长任务进度及 Buddy 旅行状态;切换、删除或登录新账号,并加密导入导出账号备份 |+| **账号** | 查看账号数、积分、模型频率限制与预计解封时间、当日签到状态、连续活跃天数、成长任务进度及 Buddy 旅行状态;切换、删除或登录新账号,并加密导入导出账号备份 || **主题** | 切换默认 / WorkDaddy 主题,选择或上传壁纸、更换头像,调整毛玻璃和背景蒙版 || **会话** | 按账号和时间筛选会话,批量复制或删除,并设置会话 / 工作空间在切换账号时自动复制 || **模型** | 管理当前模型和备选模型,支持备份、复制、编辑、启用、连通测试及批量删除 |diff --git a/README_en.md b/README_en.mdindex 829a64d..e7104e2 100644--- a/README_en.md+++ b/README_en.md@@ -37,6 +37,7 @@ It injects UI components into the running WorkBuddy renderer without patching or- **Daily credits:** daily check-in automation is disabled by default. On the first panel opening, a risk notice lets you enable the task or cancel. Either choice is saved locally and dismisses future notices; you can later enable or disable the task under Automations.- **Token and credit usage pages:** review daily token and credit consumption, filter by account, and view usage rankings by model and account.- **Credit-aware account suggestions:** when an account is running low on credits, WorkDaddy suggests another account you can use.+- **Model rate limits and reset estimates:** when a model rate limit is detected, the Accounts page shows the affected model and its estimated reset time. If no reset time is provided, it displays “Time unknown.”- **Automation tasks:** discover and import tasks from public GitHub and Gitee repositories, or describe what you need and let WorkBuddy create a task. Supports manual, event, and scheduled triggers, run logs, stopping tasks, and JSON / ZIP export.- **Quiet approval mode:** automatically handle supported permission prompts while you are away.- **Stash prompts:** send drafts to WorkBuddy's pending message queue while preserving images, files, and quotes for later use.@@ -156,7 +157,7 @@ Click the robot button in the lower-right corner of WorkBuddy and choose a tab:| Tab | Purpose || -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |-| **Accounts** | View account counts, credits, check-ins, and login status; switch, delete, or add accounts; import/export encrypted backups |+| **Accounts** | View account counts, credits, model rate limits and estimated reset times, check-ins, and login status; switch, delete, or add accounts; import/export encrypted backups || **Theme** | Switch between the default and WorkDaddy themes, choose or upload wallpapers, change avatars, and adjust blur and background overlays || **Sessions** | Filter by account and date, copy or delete in bulk, and configure automatic session or workspace copying when switching accounts || **Models** | Manage current and alternative models, including backups, copying, editing, enabling, connectivity tests, and bulk deletion |diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex ffec6fa..3fa784f 100644--- a/scripts/build-mac-dmg.sh+++ b/scripts/build-mac-dmg.sh@@ -55,10 +55,13 @@ cp "$APP_ICON" "$APP/Contents/Resources/AppIcon.icns"chmod 644 "$APP/Contents/Resources/AppIcon.icns"echo "==> 应用图标已同步(背景 #e1e1e1)"-# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)+# 2) 覆盖运行时代码和主题配置,保留 launcher/Info.plist/壁纸/node_modules/theme-audit.js。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 session-dirty.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js 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+# Theme tokens are source code too; the reusable shell may contain older colors.+mkdir -p "$APP/Contents/Resources/scripts/builtin/nebula"+cp scripts/builtin/nebula/theme.json "$APP/Contents/Resources/scripts/builtin/nebula/theme.json"# Injection reads the wordmark at runtime; keep brand assets in both profiles.mkdir -p "$APP/Contents/Resources/scripts/assets"cp scripts/assets/workdaddy-logo.svg scripts/assets/workdaddy-app-icon.svg scripts/assets/workdaddy-app-icon-source.svg scripts/assets/workbuddy-buddy-mark.svg "$APP/Contents/Resources/scripts/assets/"diff --git a/scripts/builtin/nebula/theme.json b/scripts/builtin/nebula/theme.jsonindex 02761e8..44853d8 100644--- a/scripts/builtin/nebula/theme.json+++ b/scripts/builtin/nebula/theme.json@@ -74,10 +74,10 @@"--wb-text-white": "#0a0a0a","--wb-bg-primary": "#0a0a0a","--wb-border-default": "rgba(255,255,255,0.12)",- "--wb-button-primary-fg": "#0a0a0a",- "--wb-button-primary-bg": "rgba(255,255,255,0.92)",+ "--wb-button-primary-fg": "var(--wb-color-text-primary)",+ "--wb-button-primary-bg": "transparent","--wb-shadow-lg": "0 4px 16px color-mix(in srgb, #000000 16%, transparent)",- "--wb-bg-secondary": "#111113",+ "--wb-bg-secondary": "transparent","--wb-error-foreground": "#F64041","--wb-bg-overlay": "rgba(230,230,233,0.4)","--wb-border-hover": "rgba(255,255,255,0.3)",diff --git a/scripts/cdp-targets.js b/scripts/cdp-targets.jsindex 14daddc..8904ad1 100644--- a/scripts/cdp-targets.js+++ b/scripts/cdp-targets.js@@ -121,4 +121,20 @@ function isTargetForProfile(target, profile) {return false;}-module.exports = { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile };+/**+ * Pick the renderer page for WorkDaddy injection. WorkBuddy can expose a+ * separate settings utility window before the main conversation page; that+ * window shares the same app URL and must not become the CDP session target.+ */+function selectPageTarget(targets, profile) {+ const candidates = (Array.isArray(targets) ? targets : []).filter((target) => isTargetForProfile(target, profile));+ const score = (target) => {+ const url = String(target && target.url || '');+ if (/windowAppId=settings|windowKind=settings|windowPreset=utility/i.test(url)) return 20;+ if (/accountSnapshot=|[?&]locale=/i.test(url)) return 0;+ return 10;+ };+ return candidates.sort((a, b) => score(a) - score(b))[0] || null;+}++module.exports = { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget };diff --git a/scripts/credit-usage-store.js b/scripts/credit-usage-store.jsindex 0028919..2ce7e90 100644--- a/scripts/credit-usage-store.js+++ b/scripts/credit-usage-store.js@@ -101,6 +101,23 @@ function createCreditUsageStore(options = {}) {CREATE INDEX IF NOT EXISTS idx_daily_checkin_uid_dateON daily_checkin_records (profile_id, uid, checkin_date)`);+ await db.run(`+ CREATE TABLE IF NOT EXISTS model_rate_limit_records (+ profile_id TEXT NOT NULL,+ uid TEXT NOT NULL,+ model_id TEXT NOT NULL,+ model_name TEXT NOT NULL DEFAULT '',+ reset_at INTEGER,+ observed_at INTEGER NOT NULL,+ source TEXT NOT NULL DEFAULT '',+ reason_code INTEGER,+ PRIMARY KEY (profile_id, uid, model_id)+ )+ `);+ await db.run(`+ CREATE INDEX IF NOT EXISTS idx_model_rate_limit_uid_reset+ ON model_rate_limit_records (profile_id, uid, reset_at)+ `);try { fs.chmodSync(dbPath, 0o600); } catch (_) {}})().catch((error) => {initPromise = null;@@ -326,6 +343,65 @@ function createCreditUsageStore(options = {}) {try { fs.chmodSync(dbPath, 0o600); } catch (_) {}}+ async function saveModelRateLimit({ uid, modelId, modelName, resetAt, observedAt, source, reasonCode }) {+ await initialize();+ const accountUid = validIdentity(uid, 'uid');+ const id = validIdentity(modelId, 'model id');+ const name = String(modelName || '').slice(0, 256);+ const observed = Number(observedAt);+ if (!Number.isSafeInteger(observed) || observed < 0) throw new Error('限流观察时间无效');+ let reset = resetAt === null || resetAt === undefined || resetAt === '' ? null : Number(resetAt);+ if (reset !== null && (!Number.isSafeInteger(reset) || reset < 0)) throw new Error('限流解封时间无效');+ const reason = reasonCode === null || reasonCode === undefined ? null : Number(reasonCode);+ if (reason !== null && !Number.isSafeInteger(reason)) throw new Error('限流 code 无效');+ await db.run(+ `INSERT INTO model_rate_limit_records+ (profile_id, uid, model_id, model_name, reset_at, observed_at, source, reason_code)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(profile_id, uid, model_id) DO UPDATE SET+ model_name = excluded.model_name,+ reset_at = excluded.reset_at,+ observed_at = excluded.observed_at,+ source = excluded.source,+ reason_code = excluded.reason_code`,+ [profileId, accountUid, id, name, reset, observed, String(source || '').slice(0, 80), reason]+ );+ try { fs.chmodSync(dbPath, 0o600); } catch (_) {}+ }++ async function listModelRateLimits(uids, now) {+ await initialize();+ const accountUids = Array.from(new Set((Array.isArray(uids) ? uids : []).map((uid) => validIdentity(uid, 'uid'))));+ if (!accountUids.length) return {};+ const timestamp = Number(now === undefined ? Date.now() : now);+ if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error('限流查询时间无效');+ const placeholders = accountUids.map(() => '?').join(',');+ await db.run(+ `DELETE FROM model_rate_limit_records+ WHERE profile_id = ? AND reset_at IS NOT NULL AND reset_at <= ? AND uid IN (${placeholders})`,+ [profileId, timestamp, ...accountUids]+ );+ const rows = await db.all(+ `SELECT uid, model_id, model_name, reset_at, observed_at, source, reason_code+ FROM model_rate_limit_records+ WHERE profile_id = ? AND uid IN (${placeholders})+ ORDER BY uid ASC, observed_at DESC, model_id ASC`,+ [profileId, ...accountUids]+ );+ const result = {};+ for (const row of rows) {+ if (!accountUids.includes(row.uid)) continue;+ if (!result[row.uid]) result[row.uid] = [];+ result[row.uid].push({+ modelId: String(row.model_id), modelName: String(row.model_name || ''),+ resetAt: row.reset_at === null ? null : Number(row.reset_at),+ observedAt: Number(row.observed_at), source: String(row.source || ''),+ reasonCode: row.reason_code === null ? null : Number(row.reason_code),+ });+ }+ return result;+ }+return {dailyUsageForUid,listDailyUsageRange,@@ -337,6 +413,8 @@ function createCreditUsageStore(options = {}) {saveSuccessfulSync,saveHistoryUsage,saveDailyCheckin,+ saveModelRateLimit,+ listModelRateLimits,};}diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 84b0fbe..c44c9db 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -126,6 +126,7 @@ const {checkinDisplayValue,getAccountOrder,setAccountOrder,+ setAccountNote,} = require('./lib.js');const { createThirdPartyImport } = require('./third-party-models.js');const { extractCreditSegments, sortCreditSegments, mergeCreditSegments, parseEnterpriseUsage, ENTERPRISE_EDITIONS } = require('./credit-segments.js');@@ -158,7 +159,7 @@ const { createUsageReporter } = require('./usage-report.js');const { getProfile, profileDataDir, listInstalledModelSources } = require('./profiles.js');const plat = require('./platform.js');const { readWorkBuddyTarget } = require('./workbuddy-target.js');-const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('./cdp-targets.js');+const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget } = require('./cdp-targets.js');const { createSessionDb, normalizeSessionIdBatch, parameterCount } = require('./session-db.js');const { createDirtyIndex } = require('./session-dirty.js');const {@@ -168,7 +169,7 @@ const {requiredPassword,resolveArchiveTarget,} = require('./secure-transfer.js');-const { writeSessionTransfer, readSessionTransfer, receiveSessionUpload } = require('./session-transfer.js');+const { writeSessionTransfer, readSessionTransfer, receiveSessionUpload, createSessionExportJobs } = require('./session-transfer.js');const { forkedTitle, planForkAtMessage } = require('./session-fork.js');const { pipeline: transferPipeline } = require('node:stream/promises');const { replaceFileWithRetry } = require('./atomic-file-write.js');@@ -420,8 +421,10 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 1.2.145:识别仅 updated_at 的激活漂移,清除无变更脏标记;无结果任务不再弹同步进度窗口。// 1.2.126:5.6 加密账号改为密文原样备份、内存解密;导入兼容明文 token,// 刷新结果不把解密后的 token 写回加密备份。-const DAEMON_VERSION = '1.2.153';-const DAEMON_BUILD_ID = 'release-1.2.153-20260924-respect-active-session-sync-rule';+// 1.2.188:关闭主题接管时跟随 WorkBuddy AI 的原生 agent-ui-theme,避免旧快照覆盖官方浅色/深色选择。+// 1.2.189:毛玻璃底色等待移至 daemon,避免后台页面定时器节流拖延开关和壁纸加载。+const DAEMON_VERSION = '1.2.189';+const DAEMON_BUILD_ID = 'release-1.2.189-20260927-wallpaper-loading';const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const automationDiscovery = createAutomationDiscovery({@@ -440,6 +443,11 @@ const IS_MAC = process.platform === 'darwin';const IS_LINUX = process.platform === 'linux';// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.appconst WORKDADDY_INSTALL_NAME = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy AI' : 'WorkDaddy';+const sessionExportJobs = createSessionExportJobs({+ prepare: prepareSessionExport,+ directory: () => path.join(process.env.WBSWITCH_LAUNCH_HOME || os.homedir(), 'Downloads', WORKDADDY_INSTALL_NAME),+ brand: WORKDADDY_INSTALL_NAME,+});const WORKDADDY_DIR_WIN = process.env.WBSWITCH_APP_DIR || path.resolve(__dirname, '..');const IS_PORTABLE_WIN = IS_WIN && fs.existsSync(path.join(WORKDADDY_DIR_WIN, 'WorkDaddy.portable'));const UI_PORT_BASE = parseInt(process.env.WBSWITCH_PORT || String(profileUiPortCandidates(PROFILE.id)[0]), 10);@@ -1785,6 +1793,9 @@ let suppressPageLoadInjectionForNavigation = 0;let cdpPageSessionId = '';const automationEventKeys = new Set();let pendingAutomationAccountSwitch = null;+// 自动主题恢复可能与用户刚关闭/开启接管开关并发。递增此序号使旧的+// Runtime.evaluate 在真正写入页面前失效,避免 WorkDaddy/WorkBuddy 两套主题来回闪烁。+let themeApplyGeneration = 0;function settlePendingReloadInjection(pending, mounted) {if (!pending || pendingReloadInjection !== pending || pending.settled) return;@@ -1920,7 +1931,7 @@ function isWorkBuddyCdpTarget(target) {async function getPageTarget(port) {const r = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(1500) });const list = await r.json();- return (Array.isArray(list) ? list : []).find(isWorkBuddyCdpTarget) || null;+ return selectPageTarget(list, PROFILE);}async function cleanupForeignInjectedTargets(targets) {@@ -3259,6 +3270,8 @@ function automationSwitchAccount(account, options = {}) {if (active && active.uid === uid) return { ok: true, uid, switched: false };automationSwitchProgress(options, options.restore ? 'restoring-account' : 'switching-account');releaseRendererReload = beginRendererReloadPriority();+ await preserveAccountSwitchTheme(uid);+ if (options.isCancelled && options.isCancelled()) throw new Error('任务已停止');const acct = switchTo(DATA_DIR, uid, log);pendingAutomationAccountSwitch = { account: { uid: acct.uid, nickname: acct.nickname } };await reloadWorkBuddyPage();@@ -4435,10 +4448,9 @@ async function createForkSession(src, selection) {return { id, sourceId: src.id, keptMessages: plan.keep, droppedMessages: plan.drop };}-async function exportSessions(ids, password) {+async function prepareSessionExport(ids) {const selectedIds = normalizeSessionIdBatch(ids);if (!selectedIds.length) throw new Error('未选择会话');- requiredPassword(password);const rows = await sqliteQuery('SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id IN (' + sqlPlaceholders(selectedIds) + ') AND deleted_at IS NULL;',selectedIds@@ -4450,6 +4462,12 @@ async function exportSessions(ids, password) {return { record, files: collectSessionArchiveFiles(wbHome, id) };});if (!sessions.length) throw new Error('没有可导出的会话');+ return sessions;+}++async function exportSessions(ids, password) {+ requiredPassword(password);+ const sessions = await prepareSessionExport(ids);const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'workdaddy-session-export-'));const file = path.join(directory, 'sessions.wds');try {@@ -4783,13 +4801,6 @@ async function copySessionRecord(src, targetUid, options = {}) {const aliases = getAutoCopySessionMemberRecords(DATA_DIR, lineageId).map(member => member.id).concat(targetIds);const syncCache = getSessionSyncCache();const existingMappingTarget = mapping && mapping.targetId ? candidates.find(row => row.id === mapping.targetId) : null;- // A brand-new destination has no target bytes to protect and is the only- // path that copies every selected session. The synchronous snapshot/apply- // implementation matches main's low-overhead file path; using it here- // avoids the per-file async stream/hash scheduling cost during first-time- // account initialization. Existing copies keep the async path so normal- // incremental repairs continue to yield to the renderer.- const firstTargetCopy = options.auto && !existingMappingTarget && candidates.length === 0;// Automatic switching revisits the same source/target pairs frequently.// WorkBuddy updates the session row whenever its content changes. Validate// the persisted source/target row revisions before paying for a complete@@ -4815,14 +4826,10 @@ async function copySessionRecord(src, targetUid, options = {}) {copiedBytes: 0,};}- let left = firstTargetCopy- ? sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases, syncCache)- : await sessionSync.readSnapshotAsync(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);+ let left = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);const selection = await sessionSync.selectTargetSnapshot(left, targetIds, async id => {await yieldAutoCopyToRenderer();- return firstTargetCopy- ? sessionSync.readSnapshot(PROFILE.dataRoot, id, aliases, syncCache)- : sessionSync.readSnapshotAsync(PROFILE.dataRoot, id, aliases, syncCache);+ return sessionSync.readSnapshotAsync(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@@ -4849,9 +4856,7 @@ async function copySessionRecord(src, targetUid, options = {}) {clearAutoDirty();return { status: 'skipped', sourceId: src.id, targetId, branched: false, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes: left.totalBytes, copiedBytes: 0 };}- let right = firstTargetCopy- ? sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases, syncCache)- : await sessionSync.readSnapshotAsync(PROFILE.dataRoot, targetId, aliases, syncCache);+ let right = await sessionSync.readSnapshotAsync(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,同步可能较慢' : '';@@ -4899,19 +4904,12 @@ async function copySessionRecord(src, targetUid, options = {}) {});}};- const applied = await (firstTargetCopy- ? sessionSync.applySnapshot(from, to, {- backupRoot: path.join(DATA_DIR, 'session-sync-backups'), metadata: toRow,- missingOnly, guard: verifyRows,- onProgress: options.onProgress,- commit,- })- : sessionSync.applySnapshotAsync(from, to, {+ const applied = await sessionSync.applySnapshotAsync(from, to, {backupRoot: path.join(DATA_DIR, 'session-sync-backups'), metadata: toRow,missingOnly, guard: verifyRows,onProgress: options.onProgress,commit,- }));+ });totalBytes = applied.totalBytes;copiedBytes += applied.copiedBytes;changed = true;@@ -4922,12 +4920,8 @@ 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 = firstTargetCopy- ? sessionSync.readSnapshot(PROFILE.dataRoot, sourceRow.id, aliases, syncCache)- : await sessionSync.readSnapshotAsync(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);- right = firstTargetCopy- ? sessionSync.readSnapshot(PROFILE.dataRoot, targetId, aliases, syncCache)- : await sessionSync.readSnapshotAsync(PROFILE.dataRoot, targetId, aliases, syncCache);+ left = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);+ right = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, targetId, aliases, syncCache);await update(right, left, existing, sourceRow, true);}}@@ -6100,7 +6094,7 @@ async function acSendCurrentInput() {// 开关状态 + 短语列表持久化在 ~/.workbuddy/settings.json 的 wbs.session 域(与 noDisturb/autoContinue 同模式)。// 默认值:暂存提示词开、快捷短语开(属性缺省即按开处理,保证旧用户全新功能默认可用)。const SESS_NS = 'session';-const SESS_SWITCHES = ['stashEnabled', 'phraseEnabled'];+const SESS_SWITCHES = ['stashEnabled', 'phraseEnabled', 'themeTakeoverEnabled'];// 首次使用时播种的默认快捷短语(仅一次;用户删除后不再补——seeded 标志已置位,删除即永久生效)const SESS_DEFAULT_PHRASES = ['继续执行'];let sessionSeedPersistReported = false;@@ -6109,6 +6103,7 @@ function sessBuild(st, phrases) {return {stashEnabled: st.stashEnabled !== false,phraseEnabled: st.phraseEnabled !== false,+ themeTakeoverEnabled: st.themeTakeoverEnabled !== false,phrases: Array.isArray(phrases) ? phrases : [],};}@@ -6152,7 +6147,7 @@ function writeSessionState(state) {const prior = (s.wbs && s.wbs[SESS_NS] && typeof s.wbs[SESS_NS] === 'object') ? s.wbs[SESS_NS] : {};if (!s.wbs || typeof s.wbs !== 'object') s.wbs = {};s.wbs[SESS_NS] = {- state: { stashEnabled: !!state.stashEnabled, phraseEnabled: !!state.phraseEnabled },+ state: { stashEnabled: !!state.stashEnabled, phraseEnabled: !!state.phraseEnabled, themeTakeoverEnabled: state.themeTakeoverEnabled !== false },phrases: state.phrases || [],seeded: prior.seeded !== false, // 保留播种标志(删除默认短语后不回补)};@@ -6907,22 +6902,263 @@ function getTheme(id) {const sub = path.join(THEMES_DIR, safeId, 'theme.json');if (fs.existsSync(sub)) t = JSON.parse(fs.readFileSync(sub, 'utf8'));}- if (t && t.colors) return t;+ if (t && t.colors) {+ // 毛玻璃的透明常量也是主题定义的一部分;旧安装的配色文件同样生效。+ if (id === 'nebula') t.colors = { ...t.colors,+ '--wb-button-primary-bg': 'transparent', '--wb-bg-secondary': 'transparent',+ '--wb-button-primary-fg': 'var(--wb-color-text-primary)',+ };+ return t;+ }} catch (_) {}if (BUILTIN_THEMES[id]) return BUILTIN_THEMES[id];return null;}+// 在官方加载目标账号前迁移当前外观。WorkBuddy syncCloudTheme 优先消费+// currentTheme + pendingSync.theme,再由官方队列同步云端;只写 currentTheme+// 会被启动时的旧云端选择覆盖。这里不安装 hook,也不改其他账号或皮肤 CSS。+function accountSwitchThemeExpression(targetUid) {+ return `(async function () {+ var uid = ${JSON.stringify(targetUid)};+ if (typeof uid !== 'string' || !/^[A-Za-z0-9_-]{1,160}$/.test(uid)) return { prepared: false };+ var theme;+ try { theme = JSON.parse(localStorage.getItem('workbuddy.appearance.lastApplied') || 'null'); } catch (_) {}+ if (!theme || typeof theme.resourceKey !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(theme.resourceKey)) return { prepared: false };+ // 官方跨窗口初始化会把 appearanceTheme 写回当前账号并清掉 pendingSync。+ // 仅清这个旧的跨窗口缓存,让账号状态与待同步选择成为启动依据;后续手动+ // 换肤仍会由官方 setPreference 写入新的值,不需要拦截或替换任何函数。+ if (typeof globalThis.wb?.config?.setPreference === 'function') {+ await globalThis.wb.config.setPreference('appearanceTheme', null);+ }+ var resource = theme.resourceKey;+ var mode = theme.appearance === 'dark' || resource === 'dark' ? 'dark' : 'light';+ var statePrefix = 'workbuddy.appearance.state::';+ var lastPrefix = 'workbuddy.appearance.lastApplied::';+ var modePrefix = 'workbuddy.appearance.mode::';+ var suffix = '::' + uid;+ var scopes = new Set(['personal']);+ var modeKeys = new Set([modePrefix + 'personal::personal' + suffix]);+ for (var i = 0; i < localStorage.length; i++) {+ var key = localStorage.key(i);+ if (!key || !key.endsWith(suffix)) continue;+ if (key.indexOf(statePrefix) === 0) scopes.add(key.slice(statePrefix.length, -suffix.length));+ else if (key.indexOf(lastPrefix) === 0) scopes.add(key.slice(lastPrefix.length, -suffix.length));+ else if (key.indexOf(modePrefix) === 0) {+ modeKeys.add(key);+ var namespace = key.slice(modePrefix.length, -suffix.length).split('::');+ if (namespace.length === 2 && namespace[1]) scopes.add(namespace[1]);+ }+ }+ scopes.forEach(function (scope) {+ var key = statePrefix + scope + suffix, previous = {};+ try { previous = JSON.parse(localStorage.getItem(key) || '{}') || {}; } catch (_) {}+ var state = Object.assign({}, previous, { currentTheme: resource,+ pendingSync: Object.assign({}, previous.pendingSync, { theme: resource }) });+ localStorage.setItem(key, JSON.stringify(state));+ localStorage.setItem(lastPrefix + scope + suffix, JSON.stringify(theme));+ });+ modeKeys.forEach(function (key) { localStorage.setItem(key, mode); });+ return { prepared: true };+ })()`;+}++async function preserveAccountSwitchTheme(targetUid) {+ if (!PROFILE.capabilities.theme || !cdp.connected) return false;+ try {+ const result = await cdpSend('Runtime.evaluate', {+ expression: accountSwitchThemeExpression(targetUid), returnByValue: true, awaitPromise: true, timeout: 1500,+ });+ return !!(result && !result.exceptionDetails && result.result && result.result.value && result.result.value.prepared);+ } catch (_) {+ // 外观迁移失败不阻断登录文件切换;不输出账号配置、皮肤资源或 CDP 异常内容。+ log('[theme] 切换前外观同步未完成');+ return false;+ }+}++// WorkBuddy 的外观设置在独立窗口中运行。关闭接管后,主会话窗口不会+// 自动收到特殊皮肤的 adoptedStyleSheet,因此只同步 WorkBuddy 自己保存+// 的 CSS 资源;浅色/深色仍由 WorkBuddy 原生状态负责。+function nativeAppearanceSyncExpression() {+ return `(function () {+ var h = null, b = null;+ function removeNativeSheet() {+ try {+ var own = window.__wbsNativeAppearanceSheet;+ if (!own || !document.adoptedStyleSheets) return;+ document.adoptedStyleSheets = Array.from(document.adoptedStyleSheets).filter(function (sheet) { return sheet !== own; });+ } catch (_) {}+ try { delete window.__wbsNativeAppearanceSheet; delete window.__wbsNativeAppearanceKey; } catch (_) {}+ }+ function setAttr(el, name, value) {+ // 同值 setAttribute 也会触发 MutationObserver(WorkBuddy ThemeManager 据此重应用主题),+ // 幂等写入避免与官方主题机制互相惊动形成无限回写。+ if (el.getAttribute(name) !== value) el.setAttribute(name, value);+ }+ function setMode(mode) {+ var dark = mode === 'dark';+ setAttr(h, 'data-theme', mode);+ h.classList.toggle('cb-dark', dark); h.classList.toggle('cb-light', !dark);+ h.classList.toggle('dark', dark); h.classList.toggle('light', !dark);+ setAttr(b, 'data-vscode-theme-kind', dark ? 'vscode-dark' : 'vscode-light');+ setAttr(b, 'data-vscode-theme-name', dark ? 'IDE Night' : 'IDE Light');+ b.classList.toggle('vscode-dark', dark); b.classList.toggle('vscode-light', !dark);+ b.classList.toggle('cb-dark', dark); b.classList.toggle('cb-light', !dark);+ b.classList.toggle('dark', dark); b.classList.toggle('light', !dark);+ }+ function sync() {+ h = document.documentElement; b = document.body;+ if (!h || !b) return;+ var applied = null, cssState = null, native = null;+ try { applied = JSON.parse(localStorage.getItem('workbuddy.appearance.lastApplied') || 'null'); } catch (_) {}+ try { cssState = JSON.parse(localStorage.getItem('workbuddy.appearance.lastApplied.css') || 'null'); } catch (_) {}+ // WorkBuddy AI 的原生浅色/深色设置由 ThemeManager 写入 agent-ui-theme;+ // appearance.lastApplied 只在外观面板/皮肤流程中更新。若优先读取后者,+ // 关闭 WorkDaddy 接管后官方刚选的浅色/深色会被旧快照每 500ms 改回。+ try { native = JSON.parse(localStorage.getItem('agent-ui-theme') || 'null'); } catch (_) {}+ var resource = String((cssState && cssState.resourceKey) || (applied && applied.resourceKey) || '');+ var css = String((cssState && cssState.css) || '');+ var special = resource && resource !== 'light' && resource !== 'dark' && css;+ var nativeMode = native && (native.theme === 'light' || native.theme === 'dark') ? native.theme : null;+ if (special && typeof CSSStyleSheet !== 'undefined' && document.adoptedStyleSheets) {+ var key = resource + ':' + css.length;+ var currentSheets = Array.from(document.adoptedStyleSheets || []);+ var ownSheetPresent = window.__wbsNativeAppearanceSheet && currentSheets.indexOf(window.__wbsNativeAppearanceSheet) >= 0;+ if (window.__wbsNativeAppearanceKey !== key || !ownSheetPresent) {+ removeNativeSheet();+ try {+ var sheet = new CSSStyleSheet();+ sheet.replaceSync(css);+ document.adoptedStyleSheets = Array.from(document.adoptedStyleSheets || []).concat([sheet]);+ window.__wbsNativeAppearanceSheet = sheet;+ window.__wbsNativeAppearanceKey = key;+ } catch (_) {}+ }+ setMode(applied && applied.appearance === 'dark' ? 'dark' : 'light');+ return;+ }+ removeNativeSheet();+ setMode(nativeMode || (resource === 'dark' || (applied && applied.appearance === 'dark') ? 'dark' : 'light'));+ }+ sync();+ try {+ // 释放接管后可能仍有旧版/并发应用泄漏的 250ms 外观守护在跑;bump token+ // 让它们下一次 fire 时自杀,避免用陈旧 wantedMode 与原生外观无限拉扯。+ window.__wbsThemeAppearanceGuardToken = (window.__wbsThemeAppearanceGuardToken || 0) + 1;+ if (window.__wbsNativeAppearanceSync) clearInterval(window.__wbsNativeAppearanceSync);+ window.__wbsNativeAppearanceSync = setInterval(sync, 500);+ } catch (_) {}+ })()`;+}++async function startNativeAppearanceSyncByCdp() {+ if (!cdp.connected || readSessionState().themeTakeoverEnabled !== false) return;+ await cdpSend('Runtime.evaluate', { expression: nativeAppearanceSyncExpression(), returnByValue: true });+}++async function releaseThemeByCdp() {+ themeApplyGeneration++;+ if (!cdp.connected) return;+ const releaseGeneration = themeApplyGeneration;+ // 先释放 WorkDaddy 注入,再恢复接管前保存的 WorkBuddy 外观;没有快照时+ // 才由官方同步流程决定当前主题。+ const result = await applyThemeByCdp('default', { release: true });+ if (releaseGeneration === themeApplyGeneration) {+ await restoreNativeAppearanceByCdp();+ if (releaseGeneration === themeApplyGeneration) await startNativeAppearanceSyncByCdp();+ }+ return result;+}++async function restoreNativeAppearanceByCdp() {+ if (!cdp.connected) return;+ let _accUid = null;+ try { const _a = currentAccount(); _accUid = _a ? _a.uid : null; } catch (_) {}+ const uid = (typeof _accUid === 'string' && _accUid) ? _accUid : null;+ if (!uid) return;+ try {+ await cdpSend('Runtime.evaluate', {+ expression: `(async function () {+ var WBS_UID = ${JSON.stringify(uid)};+ // 多账号文件同时存在时 daemon 可能无法唯一解析当前 auth;页面 URL+ // 仍带有 WorkBuddy 正在展示的 accountSnapshot,优先用它定位快照。+ try {+ var rawAccount = new URL(location.href).searchParams.get('accountSnapshot');+ for (var decodeAttempt = 0; rawAccount && decodeAttempt < 3; decodeAttempt++) {+ try { rawAccount = decodeURIComponent(rawAccount); } catch (_) { break; }+ }+ var pageAccount = JSON.parse(rawAccount || 'null');+ if (pageAccount && /^[A-Za-z0-9_-]{1,160}$/.test(String(pageAccount.uid || ''))) WBS_UID = String(pageAccount.uid);+ } catch (_) {}+ var snapshotKey = 'workdaddy.theme.native-snapshot::' + WBS_UID;+ var rawSnapshot = localStorage.getItem(snapshotKey);+ if (!rawSnapshot) return { restored: false };+ var snapshot = JSON.parse(rawSnapshot);+ var suffix = '::' + WBS_UID;+ var removeKeys = [];+ for (var i = 0; i < localStorage.length; i++) {+ var k = localStorage.key(i);+ if (!k) continue;+ if ((k.indexOf('workbuddy.appearance.mode::') === 0 ||+ k.indexOf('workbuddy.appearance.state::') === 0 ||+ k.indexOf('workbuddy.appearance.lastApplied::') === 0) && k.endsWith(suffix)) removeKeys.push(k);+ }+ for (var r = 0; r < removeKeys.length; r++) localStorage.removeItem(removeKeys[r]);+ var globalKeys = ['agent-ui-theme', 'workbuddy.appearance.lastApplied', 'workbuddy.appearance.lastApplied.css', 'workbuddy.appearance.lastApplied::__identity'];+ for (var g = 0; g < globalKeys.length; g++) localStorage.removeItem(globalKeys[g]);+ var saved = Array.isArray(snapshot.keys) ? snapshot.keys : [];+ var savedMap = {};+ for (var s = 0; s < saved.length; s++) if (Array.isArray(saved[s]) && saved[s].length >= 2) { savedMap[saved[s][0]] = saved[s][1]; localStorage.setItem(saved[s][0], saved[s][1]); }+ // WorkBuddy's official cross-window appearance sync consumes a resource+ // key through config.setPreference. Restoring localStorage alone leaves+ // the renderer's ThemeManager on the temporary light/dark base theme,+ // so special themes such as "有风" never rebuild their real variables.+ // Prefer the global snapshot, then fall back to the current account's+ // scoped lastApplied entry when older snapshots lack the global key.+ var savedTheme = null;+ try { savedTheme = JSON.parse(savedMap['workbuddy.appearance.lastApplied'] || 'null'); } catch (_) {}+ if (!savedTheme || typeof savedTheme.resourceKey !== 'string') {+ for (var savedKey in savedMap) {+ if (savedKey.indexOf('workbuddy.appearance.lastApplied::') !== 0 || !savedKey.endsWith(suffix)) continue;+ try {+ var scopedTheme = JSON.parse(savedMap[savedKey] || 'null');+ if (scopedTheme && typeof scopedTheme.resourceKey === 'string') { savedTheme = scopedTheme; break; }+ } catch (_) {}+ }+ }+ var reapplied = false;+ if (savedTheme && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(savedTheme.resourceKey) &&+ typeof globalThis.wb?.config?.setPreference === 'function') {+ try {+ await globalThis.wb.config.setPreference('appearanceTheme', savedTheme.resourceKey);+ reapplied = true;+ } catch (_) {}+ }+ // Preserve the saved WorkBuddy resource key and CSS payload verbatim;+ // special appearances must remain selectable after takeover is off.+ localStorage.removeItem(snapshotKey);+ return { restored: true, reapplied: reapplied,+ resourceKey: savedTheme && savedTheme.resourceKey || null };+ })()`,+ returnByValue: true, awaitPromise: true,+ });+ await startNativeAppearanceSyncByCdp();+ } catch (_) {}+}+/** 恢复已保存的主题(CDP 连接/页面刷新后调用):读取 current-theme.json 重新应用,保证深浅色在重启/刷新后仍生效 */async function restoreSavedTheme() {if (!PROFILE.capabilities.theme) return;if (!cdp.connected) return;- let id = 'default';- try {- const f = path.join(DATA_DIR, 'current-theme.json');- if (fs.existsSync(f)) id = String(JSON.parse(fs.readFileSync(f, 'utf8')).id || 'default');- } catch (_) {}- await applyThemeByCdp(id);+ if (readSessionState().themeTakeoverEnabled === false) {+ // 重载/重连时保留官方选择,不能再次触发关闭开关的一次性浅色重置。+ await startNativeAppearanceSyncByCdp();+ return;+ }+ // WorkDaddy 主题接管固定为毛玻璃;官方浅色/深色由关闭接管后的 WorkBuddy 自己管理。+ let id = 'nebula';+ await applyThemeByCdp(id, { automatic: true });}/** 应用主题:通过 CDP 注入主题样式。@@ -7006,10 +7242,11 @@ function themeVarsCss(isDark, id) {let out = '';const declOf = (vars) => Object.keys(vars || {}).map((k) => k + ':' + vars[k] + ';').join('');for (const b of mod.body || []) {+ if (b.themeId && b.themeId !== id) continue;if (b.darkOnly && !isDark) continue;const lead = b.darkOnly ? pre : '';const d = declOf(b.vars);- if (d) out += lead + 'body[data-vscode-theme-name]{' + d + '}';+ if (d) out += (b.includeRoot ? 'html[data-wbs-theme-id],' : '') + lead + 'body[data-vscode-theme-name]{' + d + '}';}for (const s of mod.scoped || []) {if (s.themeId && s.themeId !== id) continue;@@ -7033,9 +7270,38 @@ function readBackgroundBlur() {return blur;}-async function applyThemeByCdp(id) {+async function applyThemeByCdp(id, options = {}) {if (!PROFILE.capabilities.theme) throw new Error(`${PROFILE.name} 暂不支持主题功能`);+ if (options.release && readSessionState().themeTakeoverEnabled !== false) return { applied: false, takeover: true };+ if (options.automatic && readSessionState().themeTakeoverEnabled === false) return { applied: false, takeover: false };+ if (!options.automatic && !options.nativeOnly && !options.release) themeApplyGeneration++;+ const applyGeneration = themeApplyGeneration;if (!cdp.connected) throw new Error('CDP 未连接');+ const takeoverEnabled = !options.nativeOnly && readSessionState().themeTakeoverEnabled !== false;+ if (id === 'nebula' && takeoverEnabled) {+ // 分开两个 CDP 回合:释放自定义 CSS/守护,让官方深色真正渲染,再接管毛玻璃。+ // 不改持久化接管开关,避免中途失败或并发操作留下错误的用户设置。+ await applyThemeByCdp('dark', { ...options, nativeOnly: true });+ if (applyGeneration !== themeApplyGeneration || readSessionState().themeTakeoverEnabled === false) return { applied: false, cancelled: true };+ // Electron 后台窗口会节流 setTimeout/暂停 rAF;由 daemon 等待,+ // 再同步检查官方底色,不能让开关响应依赖 renderer 的下一帧。+ await new Promise((resolve) => setTimeout(resolve, 120));+ if (applyGeneration !== themeApplyGeneration || readSessionState().themeTakeoverEnabled === false) return { applied: false, cancelled: true };+ const settled = await cdpSend('Runtime.evaluate', {+ expression: `(function () {+ var native = null;+ try { native = JSON.parse(localStorage.getItem('agent-ui-theme') || 'null'); } catch (_) {}+ return { ready: document.documentElement.getAttribute('data-theme') === 'dark' &&+ document.body.getAttribute('data-vscode-theme-name') === 'IDE Night' &&+ native && native.theme === 'dark' && !document.documentElement.hasAttribute('data-skin') &&+ document.documentElement.style.colorScheme === 'dark' &&+ !document.getElementById('wbs-theme-style') && !window.__wbsThemeGuard };+ })()`,+ returnByValue: true, timeout: 2000,+ });+ if (applyGeneration !== themeApplyGeneration || readSessionState().themeTakeoverEnabled === false) return { applied: false, cancelled: true };+ if (!settled || settled.exceptionDetails || !settled.result || !settled.result.value || !settled.result.value.ready) throw new Error('官方深色主题尚未就绪,请重试毛玻璃主题');+ }let _accUid = null;try { const _a = currentAccount(); _accUid = _a ? _a.uid : null; } catch (_) {}const uid = (typeof _accUid === 'string' && _accUid) ? _accUid : null;@@ -7125,8 +7391,32 @@ async function applyThemeByCdp(id) {const expr = `(function(){var h = document.documentElement, b = document.body;if (!h || !b) return { pending: true };+ try {+ if (window.__wbsNativeAppearanceSync) clearInterval(window.__wbsNativeAppearanceSync);+ var nativeSheet = window.__wbsNativeAppearanceSheet;+ if (nativeSheet && document.adoptedStyleSheets) document.adoptedStyleSheets = Array.from(document.adoptedStyleSheets).filter(function (sheet) { return sheet !== nativeSheet; });+ delete window.__wbsNativeAppearanceSync; delete window.__wbsNativeAppearanceSheet; delete window.__wbsNativeAppearanceKey;+ } catch (_) {}if (window.__wbsThemeGuard) window.__wbsThemeGuard.disconnect();+ delete window.__wbsThemeGuard;+ // 清理上一次应用遗留的 250ms 外观守护:历史上这里只覆盖 window 上的句柄,+ // 并发/重复应用会泄漏旧 interval(10s 自停读的是共享 window 句柄,只有最后一个能被清),+ // 泄漏的守护用陈旧 wantedMode 持续回写 DOM/localStorage,是关闭接管后主题无限来回切换的根因。+ try { if (window.__wbsThemeAppearanceGuard) clearInterval(window.__wbsThemeAppearanceGuard); } catch (_) {}+ try { if (window.__wbsThemeAppearanceGuardStop) clearTimeout(window.__wbsThemeAppearanceGuardStop); } catch (_) {}+ try {+ delete window.__wbsThemeAppearanceGuard; delete window.__wbsThemeAppearanceGuardStop;+ window.__wbsThemeAppearanceGuardToken = (window.__wbsThemeAppearanceGuardToken || 0) + 1;+ } catch (_) {}var WBS_UID = ${JSON.stringify(uid || null)};+ try {+ var rawAccount = new URL(location.href).searchParams.get('accountSnapshot');+ for (var decodeAttempt = 0; rawAccount && decodeAttempt < 3; decodeAttempt++) {+ try { rawAccount = decodeURIComponent(rawAccount); } catch (_) { break; }+ }+ var pageAccount = JSON.parse(rawAccount || 'null');+ if (pageAccount && /^[A-Za-z0-9_-]{1,160}$/.test(String(pageAccount.uid || ''))) WBS_UID = String(pageAccount.uid);+ } catch (_) {}// WorkDaddy 自定义主题已应用标记:theme-patches 里部分规则用 html[data-wbs-theme] 限定// 只在 WorkDaddy 内置自定义主题下生效(官方默认主题不激活)。try { h.setAttribute('data-wbs-theme', ${id === 'default' || id === 'dark' ? "'0'" : "'1'"}); } catch (e) {}@@ -7139,24 +7429,123 @@ async function applyThemeByCdp(id) {// 会按账号原偏好(如 dark)恢复并覆盖我们的设置 —— 这是面板切主题被"弹回"的根因;// 4) 设置 body[data-vscode-theme-kind],触发 ThemeManager 的 MutationObserver(syncThemeClassesFromAttribute),// 让 WorkBuddy 内部 useTheme hook / 组件 theme prop 实时跟随,等价调用原生 setTheme()。+ function wbsBuiltinAppearance(mode) {+ return {+ kind: 'theme',+ resourceKey: mode,+ nameZh: mode === 'dark' ? '深色' : '浅色',+ nameEn: mode === 'dark' ? 'Dark' : 'Light',+ vipLevel: 'free',+ updatedAt: 0,+ series: 'base',+ appearance: mode,+ };+ }+ function wbsSnapshotNativeAppearance() {+ if (!WBS_UID || ${options.release ? 'true' : 'false'}) return;+ try {+ var snapshotKey = 'workdaddy.theme.native-snapshot::' + WBS_UID;+ if (localStorage.getItem(snapshotKey)) return;+ var keys = [];+ var suffix = '::' + WBS_UID;+ for (var i = 0; i < localStorage.length; i++) {+ var k = localStorage.key(i);+ if (!k) continue;+ if ((k.indexOf('workbuddy.appearance.mode::') === 0 ||+ k.indexOf('workbuddy.appearance.state::') === 0 ||+ k.indexOf('workbuddy.appearance.lastApplied::') === 0) && k.endsWith(suffix)) {+ keys.push([k, localStorage.getItem(k)]);+ }+ }+ var globalKeys = ['agent-ui-theme', 'workbuddy.appearance.lastApplied', 'workbuddy.appearance.lastApplied.css', 'workbuddy.appearance.lastApplied::__identity'];+ for (var g = 0; g < globalKeys.length; g++) {+ var gv = localStorage.getItem(globalKeys[g]);+ if (gv !== null) keys.push([globalKeys[g], gv]);+ }+ localStorage.setItem(snapshotKey, JSON.stringify({ keys: keys, at: Date.now() }));+ } catch (_) {}+ }+ function wbsClearNativeCustomCss() {+ // ThemeManager 遇到 data-skin 会直接跳过主题同步;即使皮肤 CSS 已清空,+ // 也必须先解除这个标记,再发出 theme-kind 通知,才能更新官方组件状态。+ var skinId = h.getAttribute('data-skin');+ h.removeAttribute('data-skin');+ try {+ if (document.querySelectorAll) document.querySelectorAll('style[data-skin-sheet]').forEach(function (sheet) { sheet.textContent = ''; });+ var raw = localStorage.getItem('workbuddy.appearance.lastApplied.css');+ var cssState = null;+ var applied = null;+ try { cssState = JSON.parse(raw || 'null'); } catch (_) {}+ try { applied = JSON.parse(localStorage.getItem('workbuddy.appearance.lastApplied') || 'null'); } catch (_) {}+ var css = String((cssState || {}).css || '');+ var resourceKey = String(skinId || (cssState || {}).resourceKey || (applied || {}).resourceKey || '');+ var special = !!resourceKey && resourceKey !== 'light' && resourceKey !== 'dark';+ if ((!css && !special) || !document.adoptedStyleSheets || !document.adoptedStyleSheets.length) return;+ var kept = [];+ for (var i = 0; i < document.adoptedStyleSheets.length; i++) {+ var sheet = document.adoptedStyleSheets[i];+ var text = '';+ try { text = Array.from(sheet.cssRules || []).map(function (rule) { return rule.cssText; }).join('\\n'); } catch (_) {}+ // CSSOM serialization may differ from the downloaded CSS. When the+ // active resource is a special skin, WorkBuddy theme variables give+ // us a stable marker for the adopted sheet.+ var looksLikeCustomSkin = special && (+ text.indexOf('--cb-bg-primary') !== -1 ||+ text.indexOf('--wb-bg-primary') !== -1 ||+ text.indexOf('--cb-color') !== -1+ );+ if (text !== css && !looksLikeCustomSkin) kept.push(sheet);+ else if (typeof sheet.replaceSync === 'function') {+ // 官方 SkinManager 持有这张 sheet;保留挂载,避免后续官方换肤写入+ // 一张已被我们移除的 sheet,表现为“怎么切都没有效果”。+ sheet.replaceSync(''); kept.push(sheet);+ }+ }+ if (kept.length !== document.adoptedStyleSheets.length) document.adoptedStyleSheets = kept;+ } catch (_) {}+ }+ function wbsWriteAppearanceState(key, mode) {+ var state = {};+ try { state = JSON.parse(localStorage.getItem(key) || '{}') || {}; } catch (_) {}+ state.currentTheme = mode;+ // 切换账号前留下的官方待同步状态必须保留到云端初始化完成。+ if (state.pendingSync && state.pendingSync.theme) state.pendingSync.theme = mode;+ localStorage.setItem(key, JSON.stringify(state));+ }function wbsSyncAppearanceKeys(mode) {try {- // 覆盖所有已存在的账号外观键(mode 存裸 'light'/'dark',state 存 {currentTheme})+ if (!WBS_UID) return;+ wbsSnapshotNativeAppearance();+ var builtin = wbsBuiltinAppearance(mode);+ var accountLastAppliedFound = false;for (var i = 0; i < localStorage.length; i++) {var k = localStorage.key(i);- if (typeof k !== 'string') continue;+ if (typeof k !== 'string' || !k.endsWith('::' + WBS_UID)) continue;if (k.indexOf('workbuddy.appearance.mode::') === 0) {localStorage.setItem(k, mode);} else if (k.indexOf('workbuddy.appearance.state::') === 0) {- try { localStorage.setItem(k, JSON.stringify({ currentTheme: mode })); } catch (e3) {}+ try { wbsWriteAppearanceState(k, mode); } catch (e3) {}+ } else if (k.indexOf('workbuddy.appearance.lastApplied::') === 0) {+ try { localStorage.setItem(k, JSON.stringify(builtin)); accountLastAppliedFound = true; } catch (e4) {}}}// 当前账号兜底键(个人版默认 accountType=personal、eid=personal),保证新账号也跟随if (WBS_UID) {localStorage.setItem('workbuddy.appearance.mode::personal::personal::' + WBS_UID, mode);- try { localStorage.setItem('workbuddy.appearance.state::personal::' + WBS_UID, JSON.stringify({ currentTheme: mode })); } catch (e4) {}+ try { wbsWriteAppearanceState('workbuddy.appearance.state::personal::' + WBS_UID, mode); } catch (e5) {}+ if (!accountLastAppliedFound) {+ try { localStorage.setItem('workbuddy.appearance.lastApplied::personal::' + WBS_UID, JSON.stringify(builtin)); } catch (e6) {}+ }}- } catch (e5) {}+ } catch (e7) {}+ }+ function wbsPrepareNativeAppearance(mode) {+ // 先清理官方特殊皮肤,再切换官方底色;毛玻璃直接用深色打底。+ wbsSnapshotNativeAppearance();+ wbsClearNativeCustomCss();+ wbsSyncNativeTheme(mode);+ h.classList.toggle('cb-dark', mode === 'dark');+ b.classList.toggle('vscode-dark', mode === 'dark');}function wbsSyncNativeTheme(mode) {var isLight = mode === 'light';@@ -7164,13 +7553,32 @@ async function applyThemeByCdp(id) {var name = isLight ? 'IDE Light' : 'IDE Night';try {localStorage.setItem('agent-ui-theme', JSON.stringify({ theme: mode, followSystem: false, vsCodeThemeName: name, vsCodeThemeKind: kind }));- try { localStorage.setItem('workbuddy.appearance.lastApplied', JSON.stringify({ appearance: mode })); } catch (e2) {}+ try { localStorage.setItem('workbuddy.appearance.lastApplied', JSON.stringify(wbsBuiltinAppearance(mode))); } catch (e2) {}wbsSyncAppearanceKeys(mode);} catch (e1) {}b.setAttribute('data-vscode-theme-kind', kind);b.setAttribute('data-vscode-theme-name', name);h.setAttribute('data-theme', mode);}+ // wbsSyncNativeThemeIdempotent:250ms 守护/keeper 的周期调用路径,属性同值时不写。+ function wbsSyncNativeThemeQuiet(mode) {+ var isLight = mode === 'light';+ var kind = isLight ? 'vscode-light' : 'vscode-dark';+ var name = isLight ? 'IDE Light' : 'IDE Night';+ if (h.getAttribute('data-theme') === mode &&+ b.getAttribute('data-vscode-theme-kind') === kind &&+ b.getAttribute('data-vscode-theme-name') === name) return false;+ wbsSyncNativeTheme(mode);+ return true;+ }+ if (${takeoverEnabled || options.release || options.nativeOnly ? 'true' : 'false'}) wbsPrepareNativeAppearance(${JSON.stringify(id === 'nebula' || options.nativeOnly ? 'dark' : 'light')});+ if (${options.release || options.nativeOnly ? 'true' : 'false'}) {+ wbsClearNativeCustomCss();+ // 清掉特殊皮肤缓存;外观快照留给 releaseThemeByCdp 立即恢复。+ try {+ localStorage.removeItem('workbuddy.appearance.lastApplied.css');+ } catch (_) {}+ }var s = document.getElementById('wbs-theme-style');if (${id === 'default' || id === 'dark' ? 'true' : 'false'}) {if (s) s.remove();@@ -7211,20 +7619,88 @@ async function applyThemeByCdp(id) {function keepSelectedTheme() {if (h.getAttribute('data-theme') === wantedMode &&h.classList.contains('cb-dark') === wantedDark &&+ h.classList.contains('cb-light') === !wantedDark &&+ h.classList.contains('dark') === wantedDark &&+ h.classList.contains('light') === !wantedDark &&+ h.classList.contains('vscode-dark') === wantedDark &&+ h.classList.contains('vscode-light') === !wantedDark &&b.getAttribute('data-vscode-theme-kind') === wantedKind &&b.getAttribute('data-vscode-theme-name') === wantedName &&- b.classList.contains('vscode-dark') === wantedDark) return;+ b.classList.contains('vscode-dark') === wantedDark &&+ b.classList.contains('vscode-light') === !wantedDark &&+ b.classList.contains('cb-dark') === wantedDark &&+ b.classList.contains('cb-light') === !wantedDark &&+ b.classList.contains('dark') === wantedDark &&+ b.classList.contains('light') === !wantedDark) return;h.classList.toggle('cb-dark', wantedDark);+ h.classList.toggle('cb-light', !wantedDark);+ h.classList.toggle('dark', wantedDark);+ h.classList.toggle('light', !wantedDark);+ h.classList.toggle('vscode-dark', wantedDark);+ h.classList.toggle('vscode-light', !wantedDark);b.classList.toggle('vscode-dark', wantedDark);+ b.classList.toggle('vscode-light', !wantedDark);+ b.classList.toggle('cb-dark', wantedDark);+ b.classList.toggle('cb-light', !wantedDark);+ b.classList.toggle('dark', wantedDark);+ b.classList.toggle('light', !wantedDark);wbsSyncNativeTheme(wantedMode);}keepSelectedTheme();- if (typeof MutationObserver !== 'undefined') {+ if (${takeoverEnabled ? 'true' : 'false'} && typeof MutationObserver !== 'undefined') {var guard = new MutationObserver(keepSelectedTheme);guard.observe(h, { attributes: true, attributeFilter: ['class', 'data-theme'] });guard.observe(b, { attributes: true, attributeFilter: ['class', 'data-vscode-theme-kind', 'data-vscode-theme-name'] });window.__wbsThemeGuard = guard;}+ if (${takeoverEnabled ? 'true' : 'false'} && WBS_UID && typeof setInterval === 'function') {+ function wbsHasSpecialNativeAppearance() {+ try {+ var globalCss = null;+ try { globalCss = JSON.parse(localStorage.getItem('workbuddy.appearance.lastApplied.css') || 'null'); } catch (_) {}+ if (globalCss && globalCss.resourceKey && globalCss.resourceKey !== 'light' && globalCss.resourceKey !== 'dark') return true;+ var globalApplied = null;+ try { globalApplied = JSON.parse(localStorage.getItem('workbuddy.appearance.lastApplied') || 'null'); } catch (_) {}+ if (globalApplied && globalApplied.resourceKey && globalApplied.resourceKey !== 'light' && globalApplied.resourceKey !== 'dark') return true;+ var suffix = '::' + WBS_UID;+ for (var i = 0; i < localStorage.length; i++) {+ var k = localStorage.key(i);+ if (!k || !k.endsWith(suffix)) continue;+ if (k.indexOf('workbuddy.appearance.lastApplied::') === 0) {+ var item = null;+ try { item = JSON.parse(localStorage.getItem(k) || 'null'); } catch (_) {}+ if (item && item.resourceKey && item.resourceKey !== 'light' && item.resourceKey !== 'dark') return true;+ } else if (k.indexOf('workbuddy.appearance.state::') === 0) {+ var state = null;+ try { state = JSON.parse(localStorage.getItem(k) || 'null'); } catch (_) {}+ if (state && state.currentTheme && state.currentTheme !== wantedMode && state.currentTheme !== 'light' && state.currentTheme !== 'dark') return true;+ }+ }+ } catch (_) {}+ return false;+ }+ function wbsHoldNativeAppearance() {+ if (!wbsHasSpecialNativeAppearance()) return;+ wbsClearNativeCustomCss();+ wbsSyncNativeThemeQuiet(wantedMode);+ keepSelectedTheme();+ }+ wbsHoldNativeAppearance();+ // token + 闭包句柄双保险:任何并发/重复应用都不会泄漏旧 interval;+ // 万一泄漏(如被新版 token 顶替),旧 interval 下一次 fire 即自杀。+ var wbsGuardToken = (window.__wbsThemeAppearanceGuardToken = (window.__wbsThemeAppearanceGuardToken || 0) + 1);+ var wbsGuardInterval = setInterval(function () {+ if (window.__wbsThemeAppearanceGuardToken !== wbsGuardToken) { try { clearInterval(wbsGuardInterval); } catch (_) {} return; }+ wbsHoldNativeAppearance();+ }, 250);+ window.__wbsThemeAppearanceGuard = wbsGuardInterval;+ window.__wbsThemeAppearanceGuardStop = setTimeout(function () {+ try { clearInterval(wbsGuardInterval); } catch (_) {}+ if (window.__wbsThemeAppearanceGuard === wbsGuardInterval) {+ try { delete window.__wbsThemeAppearanceGuard; delete window.__wbsThemeAppearanceGuardStop; } catch (_) {}+ }+ }, 10000);+ }var cs = getComputedStyle(b);return { applied: ${id === 'default' ? 'false' : 'true'}, dark: ${isDark ? 'true' : 'false'}, bg: cs.getPropertyValue('--vscode-editor-background').trim(), text: cs.getPropertyValue('--vscode-editor-foreground').trim() };})()`;@@ -7240,6 +7716,10 @@ async function applyThemeByCdp(id) {} else if (attempt) {await cdpActivatePage();}+ // 重连重试也必须服从后续主题选择或关闭接管,不能把过期阶段重新应用。+ if (applyGeneration !== themeApplyGeneration) return { applied: false, cancelled: true };+ if (options.release && (readSessionState().themeTakeoverEnabled !== false || applyGeneration !== themeApplyGeneration)) return { applied: false, takeover: readSessionState().themeTakeoverEnabled !== false };+ if (options.automatic && (readSessionState().themeTakeoverEnabled === false || applyGeneration !== themeApplyGeneration)) return { applied: false, takeover: false };r = await cdpSend('Runtime.evaluate', { expression: expr, returnByValue: true });if (r && r.exceptionDetails) {const detail = r.exceptionDetails.exception && r.exceptionDetails.exception.description;@@ -8375,9 +8855,16 @@ function handleApi(req, res) {}// 会话模块:POST /api/session-module-set { name, enabled }if (req.method === 'POST' && p === '/api/session-module-set') {- return readBody(req).then((body) => {+ return readBody(req).then(async (body) => {try {- return json(res, 200, { ok: true, ...setSessionSwitch(body.name, !!body.enabled) });+ if (typeof body.enabled !== 'boolean') return json(res, 400, { ok: false, error: '无效的开关状态' });+ const state = setSessionSwitch(body.name, body.enabled);+ if (body.name === 'themeTakeoverEnabled') {+ themeApplyGeneration++;+ if (state.themeTakeoverEnabled) await applyThemeByCdp('nebula');+ else await releaseThemeByCdp();+ }+ return json(res, 200, { ok: true, ...state });} catch (e) {return json(res, 500, { ok: false, error: e.message });}@@ -8677,6 +9164,13 @@ function handleApi(req, res) {});}+ if (req.method === 'POST' && p === '/api/accounts/note') {+ return readBody(req).then((body) => {+ try { return json(res, 200, { ok: true, account: setAccountNote(DATA_DIR, body) }); }+ catch (error) { return json(res, 400, { ok: false, error: error.message }); }+ });+ }+if (req.method === 'POST' && p === '/api/accounts/order') {return readBody(req).then((body) => {try { return json(res, 200, { ok: true, accountOrder: setAccountOrder(DATA_DIR, body) }); }@@ -8708,6 +9202,38 @@ function handleApi(req, res) {});}+ // Renderer reports only the structured model-rate-limit fields. Never accept+ // raw provider errors, prompts, response bodies, or credentials here.+ if (req.method === 'POST' && p === '/api/model-rate-limit') {+ return readBody(req).then(async (body) => {+ try {+ const uid = String(body && body.uid || '').trim();+ const modelId = String(body && body.modelId || '').trim();+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return json(res, 400, { ok: false, error: 'uid 格式无效' });+ if (!/^[^\x00-\x1F\x7F]{1,160}$/.test(modelId)) return json(res, 400, { ok: false, error: '模型 ID 无效' });+ const account = listAccounts(DATA_DIR).find((item) => String(item.uid) === uid);+ if (!account) return json(res, 404, { ok: false, error: '账号不存在' });+ const reasonCode = body && body.reasonCode === null ? null : Number(body && body.reasonCode);+ if (reasonCode !== 6004) return json(res, 400, { ok: false, error: '仅记录模型限流 code 6004' });+ const resetAt = body && body.resetAt === null ? null : Number(body && body.resetAt);+ if (resetAt !== null && (!Number.isSafeInteger(resetAt) || resetAt < Date.now() - 86400000 || resetAt > Date.now() + 90 * 86400000)) {+ return json(res, 400, { ok: false, error: '解封时间无效' });+ }+ await CREDIT_USAGE_STORE.saveModelRateLimit({+ uid, modelId,+ modelName: String(body && body.modelName || '').slice(0, 256),+ resetAt,+ observedAt: Date.now(),+ source: String(body && body.source || 'renderer-error').slice(0, 80),+ reasonCode,+ });+ return json(res, 200, { ok: true });+ } catch (error) {+ return json(res, 400, { ok: false, error: error.message });+ }+ });+ }+if (req.method === 'GET' && p === '/api/accounts') {const accounts = listAccounts(DATA_DIR);const checkinAutomationEnabled = readAutomations(DATA_DIR).some(task => task.enabled && stepsContainCheckin(task.steps));@@ -8729,17 +9255,24 @@ function handleApi(req, res) {activityStreak: growthStreakCache.peek(a.uid),});});- return listDailyUsage(enriched, today)+ return CREDIT_USAGE_STORE.listModelRateLimits(accounts.map((a) => a.uid), Date.now()).catch((error) => {+ log('[model-rate-limit] 读取 SQLite 标记失败: ' + error.message);+ return {};+ })+ .then((modelRateLimits) => {+ const withLimits = enriched.map((account) => Object.assign({}, account, { modelRateLimits: modelRateLimits[account.uid] || [] }));+ return listDailyUsage(withLimits, today).then((summaries) => {- const withUsage = enriched.map((account) => summaries[account.uid]+ const withUsage = withLimits.map((account) => summaries[account.uid]? Object.assign({}, account, { todayUsage: summaries[account.uid] }): account);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, checkinAutomationEnabled, 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: withLimits });});+ });});}@@ -9318,6 +9851,22 @@ function handleApi(req, res) {return sleepNow() ? json(res, 200, { ok: true }) : json(res, 500, { ok: false, error: '立即休眠失败' });}+ // 会话同步回滚备份:只返回占用与状态摘要,不返回备份内容。+ // Keep this expression self-contained because old renderer test harnesses+ // evaluate only handleApi without the daemon module's top-level imports.+ const syncBackupRoot = String(DATA_DIR || '') + (String(DATA_DIR || '').endsWith('/') || String(DATA_DIR || '').endsWith('\\') ? '' : '/') + 'session-sync-backups';+ if (req.method === 'GET' && p === '/api/sessions/sync-backups') {+ return json(res, 200, { ok: true, backups: sessionSync.inspectSyncBackups(syncBackupRoot) });+ }+ if (req.method === 'POST' && p === '/api/sessions/sync-backups/cleanup') {+ return readBody(req).then((body) => {+ const requestedDays = Number(body && body.maxAgeDays);+ const maxAgeDays = Number.isFinite(requestedDays) ? Math.min(365, Math.max(1, requestedDays)) : 30;+ const result = sessionSync.pruneSyncBackups(syncBackupRoot, { maxAgeMs: maxAgeDays * 24 * 60 * 60 * 1000 });+ return json(res, 200, { ok: true, removed: result.removed, retainedRecovery: result.retainedRecovery, maxAgeDays, backups: sessionSync.inspectSyncBackups(syncBackupRoot) });+ }).catch((error) => json(res, 400, { ok: false, error: error.message }));+ }+// 会话列表:GET /api/sessions?uid=<账号uid>&range=today|7d|30d|all(uid 缺省=当前账号;uid=空=全部账号)if (req.method === 'GET' && p === '/api/sessions') {normalizeAutoCopyLineages(DATA_DIR);@@ -9637,11 +10186,41 @@ function handleApi(req, res) {const currentUid = String((currentAccount() || {}).uid || '').trim();return json(res, 200, { ok: true, job: publicAutoCopyJob(activeAutoCopyJob(currentUid)) });}- // Stream the completed encrypted archive; clean up even if the download disconnects.+ if (req.method === 'GET' && p === '/api/sessions/export') {+ const id = url.searchParams.get('id');+ const job = sessionExportJobs.get(id);+ if (id && !job) return json(res, 404, { ok: false, code: 'EXPORT_JOB_NOT_FOUND', error: '导出任务不存在' });+ return json(res, 200, { ok: true, job });+ }+ if (req.method === 'POST' && p === '/api/sessions/export/cancel') {+ return readBody(req).then(body => {+ const job = body && typeof body.id === 'string' && sessionExportJobs.cancel(body.id);+ return json(res, job ? 200 : 404, job ? { ok: true, job } : { ok: false, error: '导出任务不存在' });+ });+ }+ if (req.method === 'POST' && p === '/api/sessions/export/open') {+ return readBody(req).then(async body => {+ const job = body && typeof body.id === 'string' && sessionExportJobs.get(body.id);+ if (!job || job.status !== 'completed' || !job.file) return json(res, 400, { ok: false, error: '导出尚未完成' });+ // The renderer supplies a job ID, never an arbitrary filesystem path.+ const command = IS_WIN ? 'explorer.exe' : IS_LINUX ? 'xdg-open' : '/usr/bin/open';+ const result = await runCommand(command, [path.dirname(job.file)]);+ if (result.error || (result.code !== 0 && !IS_WIN)) return json(res, 500, { ok: false, error: '无法打开导出目录' });+ return json(res, 200, { ok: true });+ });+ }+ // Older clients can still stream the completed archive. New panels request+ // a background job, which publishes directly to Downloads without a browser Blob.if (req.method === 'POST' && p === '/api/sessions/export') {return readBody(req).then(async (body) => {let result;try {+ if (body && body.background === true) {+ const ids = normalizeSessionIdBatch(body.ids);+ if (!ids.length) throw new Error('未选择会话');+ const job = sessionExportJobs.start(ids, body.password);+ return json(res, 202, { ok: true, job });+ }result = await exportSessions(body && body.ids, body && body.password);if (res.destroyed) return;const headers = {@@ -9893,7 +10472,7 @@ function handleApi(req, res) {r.on('end', () => {try {const list = JSON.parse(d);- const page = list.find(isWorkBuddyCdpTarget);+ const page = selectPageTarget(list, PROFILE);const id = page && page.id;if (!id) return resolve(json(res, 500, { ok: false, error: '未找到 WorkBuddy 页面 target' }));if (!wsLib) return resolve(json(res, 500, { ok: false, error: 'ws 代理库未加载,无法打开 DevTools' }));@@ -9914,6 +10493,7 @@ function handleApi(req, res) {if (id !== 'default' && !getTheme(id)) return json(res, 404, { ok: false, error: '主题不存在: ' + id });return applyThemeByCdp(id).then((info) => {+ if (info.cancelled) return json(res, 409, { ok: false, error: '主题切换已被后续操作取消' });try {fs.writeFileSync(path.join(DATA_DIR, 'current-theme.json'), JSON.stringify({ id, at: new Date().toISOString() }, null, 2));} catch (error) {@@ -10376,6 +10956,7 @@ function handleApi(req, res) {currentConversationRow = { ...ownerRows[0], id: currentConversationId };}}+ if (sourceUid !== uid) await preserveAccountSwitchTheme(uid);const acct = switchTo(DATA_DIR, uid, log);const hint = '登录文件已切换,请重启 WorkBuddy 使新账号生效';let reloaded = false;@@ -10739,6 +11320,10 @@ process.on('unhandledRejection', (reason) => {ensureDirs(DATA_DIR, log);if (!acquireDaemonLock()) process.exit(0);+const sessionBackupCleanup = sessionSync.pruneSyncBackups(path.join(DATA_DIR, 'session-sync-backups'));+if (sessionBackupCleanup.removed || sessionBackupCleanup.retainedRecovery) {+ log(`[session-sync-backups] 启动清理 ${sessionBackupCleanup.removed} 个无用备份,保留 ${sessionBackupCleanup.retainedRecovery} 个 recovery-needed 备份`);+}ensureAgentBridge(DATA_DIR, { profileId: PROFILE.id });const automationAgentInboxTimer = setInterval(() => {const imported = importAgentInbox(DATA_DIR, { profileId: PROFILE.id });diff --git a/scripts/inject.js b/scripts/inject.jsindex 0db2ecd..43eedb8 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -97,6 +97,12 @@ function collectConversationUsage(messages) {};}+function conversationUsageHeadline(state) {+ if (!state) return { prefix: '共', message: '读取中…' };+ if (!(Number(state.calls) > 0)) return { prefix: '', message: '等待会话完成' };+ return { prefix: '共', message: '' };+}+// 将官方消息 store 中的用户/助手消息还原成可直接粘贴的 Markdown。// 消息列表可能被虚拟化,复制必须依赖完整 store,而不是当前 DOM 中的节点。function conversationMessagesToMarkdown(messages) {@@ -235,8 +241,8 @@ function createBrandClickAction(options) {}function createFabAppearance(options) {- var styles = ['white', 'black', 'glass'];- var current = 'black';+ var styles = ['theme', 'white', 'black', 'glass'];+ var current = 'theme';try {var saved = options.storage.getItem(options.key);if (styles.indexOf(saved) >= 0) current = saved;@@ -361,16 +367,86 @@ function classifyAutoContinueReply(snapshot) {if (!s.observed || s.busy || s.manualStop) {return { trigger: false, reason: s.manualStop ? 'manual-stop' : 'not-idle' };}+ // WorkBuddy reports a terminal assistant message together with a renderer+ // error/fallback marker for quota and provider failures. Terminal evidence+ // wins so a finished request can never cause another automatic send.+ if (s.completionMarker || s.hasCompletionActions || s.terminal || s.complete) {+ return { trigger: false, reason: s.completionMarker ? 'completion-marker' : 'completion-actions' };+ }+ if (s.serviceErrorFallback) {+ return { trigger: false, reason: 'service-error-fallback' };+ }+ if (s.nonRetryableError || s.quotaExhausted || s.rateLimited || s.authFailure) {+ return { trigger: false, reason: s.rateLimited ? 'model-rate-limited' : (s.quotaExhausted ? 'quota-exhausted' : 'non-retryable-error') };+ }if (s.error || s.networkFailure) {return { trigger: true, reason: s.networkFailure ? 'network-failure' : 'error-ui' };}- if (s.completionMarker || s.hasCompletionActions) {- return { trigger: false, reason: s.completionMarker ? 'completion-marker' : 'completion-actions' };- }if (s.looksTruncated) return { trigger: true, reason: 'truncated-reply' };return { trigger: false, reason: 'no-incomplete-evidence' };}+var AUTO_CONTINUE_QUOTA_CODES = { 14012: true, 14014: true, 14018: true, 14019: true, 6004: true };++function normalizeAutoContinueError(error) {+ if (!error || typeof error !== 'object') return null;+ var terminal = error.terminal && typeof error.terminal === 'object' ? error.terminal : {};+ var details = terminal.details && typeof terminal.details === 'object' ? terminal.details : {};+ function numberValue() {+ for (var i = 0; i < arguments.length; i++) {+ var n = Number(arguments[i]);+ if (Number.isSafeInteger(n)) return n;+ }+ return null;+ }+ var code = numberValue(error.code, error.bizCode, terminal.bizCode, details.code);+ var statusCode = numberValue(error.statusCode, error.status, error.httpStatus);+ var requestModelId = String(error.requestModelId || error.modelId || details.requestModelId || '').slice(0, 160);+ var category = String(error.category || error.type || details.category || '').slice(0, 80).toLowerCase();+ var message = String(error.message || terminal.message || details.message || '').slice(0, 240);+ var rateLimited = code === 6004 || statusCode === 429 || /rate.?limit|频率|限流/i.test(category + ' ' + message);+ var quotaExhausted = code === 14018 || code === 14012 || code === 14014 || code === 14019 || /quota|credit|额度|积分|余额/i.test(category + ' ' + message);+ var authFailure = statusCode === 401 || statusCode === 403 || /auth|credential|登录|认证/i.test(category + ' ' + message);+ var resetAt = null;+ var resetSource = details.resetAt || details.reset_at || terminal.resetAt || error.resetAt;+ if (resetSource === undefined || resetSource === null || resetSource === '') {+ var resetMatch = /(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}(?:\s+UTC[+-]\d{1,2})?)/i.exec(message);+ if (resetMatch) resetSource = resetMatch[1];+ }+ if (resetSource !== undefined && resetSource !== null && resetSource !== '') {+ var resetNumber = Number(resetSource);+ if (Number.isFinite(resetNumber)) resetAt = resetNumber < 1e12 ? Math.round(resetNumber * 1000) : Math.round(resetNumber);+ else {+ var resetText = String(resetSource).trim();+ var parsed = Date.parse(resetText.replace(' UTC+8', '+08:00').replace(' UTC+0800', '+08:00').replace(' ', 'T'));+ if (Number.isFinite(parsed)) resetAt = parsed;+ }+ }+ return {+ code: code,+ statusCode: statusCode,+ category: category,+ requestModelId: requestModelId,+ resetAt: resetAt,+ rateLimited: rateLimited,+ quotaExhausted: quotaExhausted,+ authFailure: authFailure,+ nonRetryable: rateLimited || quotaExhausted || authFailure || AUTO_CONTINUE_QUOTA_CODES[code] === true,+ terminal: terminal === error.terminal || terminal.isTerminal === true,+ };+}++function classifyAutoContinueError(error) {+ var normalized = normalizeAutoContinueError(error) || {};+ return {+ quotaExhausted: !!normalized.quotaExhausted,+ rateLimited: !!normalized.rateLimited,+ authFailure: !!normalized.authFailure,+ nonRetryable: !!normalized.nonRetryable,+ code: normalized.code == null ? null : normalized.code,+ };+}+// WorkBuddy 新版 ConversationController 把会话运行态与消息时间线放在 store 中。// 这里保持为纯函数:终局 complete/terminal 等价于旧 DOM 的助手操作区;// 空闲后仍未 complete 的助手消息才是结构化的“回复中断”证据。@@ -384,6 +460,13 @@ function classifyAutoContinueControllerSnapshot(snapshot) {networkFailure: !!s.networkFailure,completionMarker: !!s.completionMarker,hasCompletionActions: !!(s.complete || s.terminal),+ complete: !!s.complete,+ terminal: !!s.terminal,+ serviceErrorFallback: !!s.serviceErrorFallback,+ quotaExhausted: !!s.quotaExhausted,+ rateLimited: !!s.rateLimited,+ authFailure: !!s.authFailure,+ nonRetryableError: !!s.nonRetryableError,looksTruncated: !!s.assistantId && !s.busy && !s.complete && !s.terminal,});}@@ -413,6 +496,11 @@ function controllerAutoContinueDecision(snapshot) {error: s.error,networkFailure: s.networkFailure,completionMarker: s.completionMarker,+ serviceErrorFallback: s.serviceErrorFallback,+ quotaExhausted: s.quotaExhausted,+ rateLimited: s.rateLimited,+ authFailure: s.authFailure,+ nonRetryableError: s.nonRetryableError,// 新版明确暴露 isRequestTerminal 时只认该字段;旧版没有该字段才退回 complete。complete: s.terminalKnown ? false : s.complete,terminal: s.terminal,@@ -658,6 +746,10 @@ function isSessionMonitorInProgress(snapshot) {function isSessionMonitorInterrupted(snapshot) {var s = snapshot || {};if (!s || s.busy || s.blocked || s.hydrating) return false; // 运行/等决策/恢复中:交给 in-progress 分支+ // 额度/限频错误通常同时带有 terminal=true 和 serviceErrorFallback=true。+ // 它们必须进入一次监控判定,先落盘模型限频记录并刷新账号标签;+ // controllerAutoContinueDecision 仍会因终局证据返回 trigger=false,因此不会自动重试。+ if (s.rateLimited || s.quotaExhausted) return true;return controllerAutoContinueDecision(s).trigger === true;}@@ -912,6 +1004,7 @@ function findLatestManualAutomationRun(tasks, runs) {if (typeof module !== 'undefined' && module.exports) {module.exports = {collectConversationUsage: collectConversationUsage,+ conversationUsageHeadline: conversationUsageHeadline,conversationMessagesToMarkdown: conversationMessagesToMarkdown,createUsageActivity: createUsageActivity,createBuildLifecycle: createBuildLifecycle,@@ -919,6 +1012,8 @@ if (typeof module !== 'undefined' && module.exports) {createFabAppearance: createFabAppearance,classifySessionHealth: classifySessionHealth,classifyAutoContinueReply: classifyAutoContinueReply,+ normalizeAutoContinueError: normalizeAutoContinueError,+ classifyAutoContinueError: classifyAutoContinueError,classifyAutoContinueControllerSnapshot: classifyAutoContinueControllerSnapshot,autoContinueMessageText: autoContinueMessageText,autoContinueControllerCompleted: autoContinueControllerCompleted,@@ -955,7 +1050,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var n;if ((n = document.querySelector('.wbs-root'))) n.remove();if ((n = document.getElementById('wbs-window-logo'))) n.remove();- var st = document.querySelectorAll('.wbs-stash-inline, .wbs-stash-btn, .wbs-explore-inline, .wbs-fork-button');+ var st = document.querySelectorAll('.wbs-stash-inline, .wbs-stash-btn, .wbs-explore-inline, .wbs-explore-pop, .wbs-fork-button');for (var i = 0; i < st.length; i++) st[i].remove();var nav = document.querySelectorAll('.wbs-message-nav-root');for (var ni = 0; ni < nav.length; ni++) nav[ni].remove();@@ -1005,6 +1100,29 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var WBS_ACCOUNT_MASK_KEY = 'workdaddy.account.mask.' + PROFILE_ID;var WBS_INITIAL_AUTO_COPY_ALL_KEY = 'workdaddy.initial.autoCopyAllSessions.' + PROFILE_ID;var WBS_I18N_EN = {+ '账号备注': 'Account note',+ '查看或编辑账号备注': 'View or edit account note',+ '暂无备注,点击添加…': 'No note yet. Click to add…',+ '未保存 ·': 'Unsaved ·',+ '已保存': 'Saved',+ '无效的账号': 'Invalid account',+ '备注不能超过 2000 个字符': 'Notes must be text and no longer than 2000 characters',+ '账号不存在或已删除': 'Account not found or deleted',++ '导出会话会在后台完成,文件保存到下载目录。': 'Export runs in the background and saves to Downloads.',+ '正在准备导出…': 'Preparing export…', '正在导出会话…': 'Exporting sessions…',+ '正在取消导出…': 'Cancelling export…', '会话导出已取消': 'Session export cancelled',+ '正在导出会话,请等待完成或取消': 'An export is already running. Wait or cancel it.',+ '下载目录空间不足,请释放空间后重试': 'Downloads is out of space. Free up space and retry.',+ '会话导出完成': 'Session export complete', '会话导出失败': 'Session export failed',+ '导出进度暂时无法读取,正在重试…': 'Could not read export progress. Retrying…',+ '取消导出': 'Cancel export', '打开导出目录': 'Open export folder',+ '导出进度': 'Export progress', '导出任务不存在': 'Export job not found', '导出尚未完成': 'Export is not finished',+ '无法打开导出目录': 'Could not open export folder',+ '接管主题': 'Manage theme',+ '关闭后,加载和切换账号时保留 WorkBuddy 的主题': 'When off, keep the WorkBuddy theme on load and account switches',+ '无效的开关状态': 'Invalid switch state',+ '释放主题接管失败': 'Could not release theme control','总大小': 'Total size','初始化设置': 'Initial setup','切换账号自动同步所有会话': 'Automatically sync all sessions when switching accounts',@@ -1064,7 +1182,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'查询已中断,请重新选择时间重试': 'Query interrupted. Select a time range to retry.','无法读取查询进度,请重新选择时间重试': 'Could not read progress. Select a time range to retry.','趋势分组': 'Trend grouping', '筛选折线': 'Filter lines', '统计时间': 'Statistics period',- '总览': 'Overview', '按账号': 'By account', '按模型': 'By model', '总量': 'Total', '模型用量': 'Model usage',+ '总览': 'Overview', '按账号': 'By account', '按模型': 'By model', '总量': 'Total', '模型用量': 'Model usage', '其他': 'Other', 'Token(输入 + 输出)': 'Tokens (input + output)', '输入 + 输出': 'Input + output','未识别模型': 'Unknown model', '未关联账号': 'Unassigned account', '暂无分组数据': 'No breakdown data','解锁后未读取到最新状态': 'Could not load the latest status after unlocking','Buddy 已解锁': 'Buddy unlocked', 'Buddy 解锁成功': 'Buddy unlocked', '解锁 Buddy 失败': 'Could not unlock Buddy',@@ -1288,7 +1406,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'将永久删除所选会话,以及已关联到其他账号的所有同步副本、消息文件和本地缓存。此操作不可恢复。': 'Permanently deletes the selected sessions and all synced copies, message files and local cache across accounts. This cannot be undone.','消息文字阴影': 'Message text shadow', '增强壁纸上的消息文字辨识度': 'Improve message readability over wallpaper','文字阴影设置失败: ': 'Could not set text shadow: ', '读取文字阴影失败: ': 'Could not load text shadow: ',- '悬浮机器人': 'Floating robot', '机器人外观': 'Robot appearance', '白色': 'White', '黑色': 'Black',+ '主题色': 'Theme color', '跟随发送按钮的主题色': 'Follow the send button theme color', '悬浮机器人': 'Floating robot', '机器人外观': 'Robot appearance', '白色': 'White', '黑色': 'Black','白底黑眼': 'White shell, black eyes', '黑底白眼': 'Black shell, white eyes', '毛玻璃底与镂空眼睛': 'Frosted shell, transparent eyes','自动贴边': 'Auto dock', '闲置 5 秒后收起,鼠标靠近即展开': 'Tuck away after 5 seconds idle; move nearby to reveal','打开官网;连续点击 5 次开启调试': 'Open website; click five times to enable debug', '点击打开官网': 'Click to open website', '打开官网失败: ': 'Could not open website: ',@@ -1363,6 +1481,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'开启后 WorkBuddy 需要你决策时会用弹窗提问(写入全局自定义指令,所有会话生效)': 'When enabled, WorkBuddy asks with a dialog when your decision is needed (written to the global custom prompt; affects all sessions)','当前没有进行中的会话,无法开启「所有会话结束允许休眠」': 'No active sessions; cannot enable “Allow sleep when all sessions end”','进行中的会话': 'active session(s)', '预计剩余': 'Estimated remaining', ' 秒': ' seconds', ' 分': ' minutes',+ '预计解封:': 'Reset estimate: ', '预计解封:时间未知': 'Reset estimate: unknown', '预计解封': 'Reset estimate', '时间未知': 'Time unknown', '模型限流': 'Model rate limited', '模型限流·': 'Model rate limited ·', '模型频率限制': 'Model rate limit', '账号状态': 'Account status', '当前没有有效的模型限流记录': 'No active model rate-limit records',+ '当前模型已触发频率限制,已停止自动发送': 'This model is rate limited; automatic sending stopped', '当前账号积分已耗尽': 'This account has no credits left', '模型:': 'Model: ','无法打开安装程序': 'Could not open the installer','安装程序已打开,请按提示退出 WorkBuddy 并完成安装。': 'The installer is open. Please quit WorkBuddy as prompted and finish installing.','停止旧服务…': 'Stopping old service…', '发现新版本,准备更新…': 'New version available; preparing to update…',@@ -1499,7 +1619,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'面板入口:': 'Panel entry:', '右下角机器人按钮': 'Bottom-right robot button', '已连接': 'Connected', '未连接': 'Not connected','Token 用量': 'Token usage', '正在读取统计…': 'Loading statistics…', '搜索': 'Search', '重置': 'Reset', '调用': 'Calls', '输入': 'Input', '输出': 'Output', '导入方式': 'Import method', '复制提示词': 'Copy prompt', '导入 WorkDaddy 加密文件': 'Import WorkDaddy encrypted file', '导入 WorkDaddy 导出的账号备份,选择文件后输入导出密码。': 'Import an account backup exported by WorkDaddy, then enter its export password.', '导入 JSON 文件': 'Import JSON file', '可以导入其他工具导出的明文账号。请先让 WorkBuddy 按指定格式整理,再选择生成的 JSON 文件。': 'Import plain-text accounts exported by another tool. Ask WorkBuddy to convert them to the required format, then choose the generated JSON file.', '把其他工具导出的账号文本发给 WorkBuddy,让它只输出符合 WorkDaddy 格式的 JSON,然后复制保存为文件。': 'Send the account text exported by another tool to WorkBuddy. Ask it to output only WorkDaddy-compatible JSON, then save it as a file.', '提示词已复制': 'Prompt copied', '选择文件': 'Choose file','缓存读取': 'Cache read', '缓存写入': 'Cache write',- ' 个文件,解析失败': ' files, parse failures', ' 行': ' lines', '暂无可统计的 Token 用量': 'No Token usage found', '会话用量': 'Conversation usage', '本会话用量': 'This conversation usage', '本会话用量明细': 'Conversation usage details', '暂无已完成用量': 'No completed usage yet', '读取中…': 'Loading…', '未知模型': 'Unknown model', '总计': 'Total', '在会话底部显示 Token、积分和模型汇总': 'Show Token, credits and model summary at the bottom of conversations',+ ' 个文件,解析失败': ' files, parse failures', ' 行': ' lines', '暂无可统计的 Token 用量': 'No Token usage found', '会话用量': 'Conversation usage', '本会话用量': 'This conversation usage', '本会话用量明细': 'Conversation usage details', '暂无已完成用量': 'No completed usage yet', '等待会话完成': 'Waiting for the session to finish', '读取中…': 'Loading…', '未知模型': 'Unknown model', '总计': 'Total', '在会话底部显示 Token、积分和模型汇总': 'Show Token, credits and model summary at the bottom of conversations','当前积分段已用完': 'The current credit segment is used up', '积分将在': ' credits expire in', '到期': ' expires', '要切换账号吗?': 'Switch account?', '可以切换到账号': 'Can switch to account', '检测到积分到期时间最临近的账号': 'The account with the nearest credit expiry is', '积分将于': ' credits expire within', '内过期': '', '较长时间': 'a long time', ' 小时 ': ' hr ', ' 分': ' min','切换到此账号': 'Switch to this account', '今天不再提醒': 'Do not remind me again today', '关闭': 'Close','切换中…': 'Switching…', 'Token 用量统计': 'Token usage statistics', ' 分钟后': ' minutes', ' 小时后': ' hours', ' 天后': ' days',@@ -1768,7 +1888,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>' +'<polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';- var CREDIT_SUMMARY_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M4 20h16M7 16V9m5 7V4m5 12v-5"/></svg>';+ var CREDIT_SUMMARY_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 2c1.2 4.1 2.9 5.8 7 7-4.1 1.2-5.8 2.9-7 7-1.2-4.1-2.9-5.8-7-7 4.1-1.2 5.8-2.9 7-7Z"/><path d="M13 21h9M15 18v-3m3 3v-6m3 6V9"/></svg>';+ var MODEL_RATE_LIMIT_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 2c1.2 4.1 2.9 5.8 7 7-4.1 1.2-5.8 2.9-7 7-1.2-4.1-2.9-5.8-7-7 4.1-1.2 5.8-2.9 7-7Z"/><path d="m19 13.4 3.6 6.2a1.1 1.1 0 0 1-1 1.6h-7.2a1.1 1.1 0 0 1-1-1.6l3.6-6.2a1.15 1.15 0 0 1 2 0ZM18 16v1.5"/><circle cx="18" cy="19.2" r=".45" fill="currentColor" stroke="none"/></svg>';var TOKEN_STATS_ICON ='<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 19V5M4 19h16"/><path d="m7 15 3-4 3 2 5-7"/></svg>';@@ -2537,14 +2658,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {main.textContent = '';body.textContent = '';var calls = state && state.calls || 0;- if (!state) {- main.appendChild(el('span', 'wbs-session-usage-label', '共'));- main.appendChild(el('span', 'wbs-session-usage-loading', '读取中…'));- } else if (!calls) {- main.appendChild(el('span', 'wbs-session-usage-label', '共'));- main.appendChild(el('span', 'wbs-session-usage-loading', '暂无已完成用量'));+ var headline = conversationUsageHeadline(state);+ if (headline.prefix) main.appendChild(el('span', 'wbs-session-usage-label', headline.prefix));+ if (headline.message) {+ main.appendChild(el('span', 'wbs-session-usage-loading', headline.message));} else {- main.appendChild(el('span', 'wbs-session-usage-label', '共'));main.appendChild(el('span', 'wbs-session-usage-number', formatUsageTokens(state.tokens) + ' Token'));main.appendChild(el('span', 'wbs-session-usage-separator', '·'));main.appendChild(el('span', 'wbs-session-usage-number', formatUsageCredit(state.credit, state.creditKnown) + ' 积分'));@@ -3225,7 +3343,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'</div>' +'</div>';applyI18n(exploreBtn);- var exploreSendTxt = exploreBtn.querySelector('.wbs-explore-send-txt');+ var explorePopover = exploreBtn.querySelector('.wbs-explore-pop');+ var exploreMenu = mountExplorePopover(exploreBtn, explorePopover);+ registerDisposer(exploreMenu.destroy);+ var exploreSendTxt = explorePopover.querySelector('.wbs-explore-send-txt');if (exploreSendTxt) {exploreSendTxt.addEventListener('click', function (e) {e.stopPropagation();@@ -3239,7 +3360,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}).catch(function (e2) { toast('发送失败: ' + (e2.message || e2), true, root); });});}- var exploreEditBtn = exploreBtn.querySelector('.wbs-explore-edit');+ var exploreEditBtn = explorePopover.querySelector('.wbs-explore-edit');if (exploreEditBtn) {exploreEditBtn.addEventListener('click', function (e) {e.stopPropagation();@@ -3272,13 +3393,56 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {fetch(API + '/api/breadcrumb', { method: 'POST', headers: { 'content-type': 'application/json', 'X-WorkDaddy-Token': WBS_API_TOKEN }, body: JSON.stringify({ msg: '[quick-phrase-diagnostics] ' + JSON.stringify(payload) }) }).catch(function () {});} catch (_) {}}+ // Only the popup leaves the official toolbar. Its body-level stacking context+ // keeps it above the usage summary even when the composer creates its own layer.+ function mountExplorePopover(button, popup) {+ document.body.appendChild(popup);+ var timer = null;+ var listeners = [];+ function listen(target, name, handler, options) {+ target.addEventListener(name, handler, options);+ listeners.push(function () { target.removeEventListener(name, handler, options); });+ }+ function cancelClose() { if (timer) { clearTimeout(timer); timer = null; } }+ function close() { cancelClose(); popup.classList.remove('is-open'); button.setAttribute('aria-expanded', 'false'); }+ function open() {+ cancelClose();+ var rect = button.getBoundingClientRect();+ if (!button.isConnected || !rect.width || !rect.height) return close();+ var width = popup.getBoundingClientRect().width;+ popup.style.left = Math.max(8, Math.min(window.innerWidth - width - 8, rect.left + rect.width / 2 - width / 2)) + 'px';+ popup.style.bottom = Math.max(8, window.innerHeight - rect.top + 10) + 'px';+ popup.classList.add('is-open');+ button.setAttribute('aria-expanded', 'true');+ }+ function delayedClose() { cancelClose(); timer = setTimeout(close, 120); }+ button.setAttribute('aria-expanded', 'false');+ listen(button, 'mouseenter', open);+ listen(button, 'mouseleave', delayedClose);+ listen(button, 'keydown', function (event) {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault(); event.stopPropagation();+ if (popup.classList.contains('is-open')) close(); else open();+ }+ if (event.key === 'Escape') { event.stopPropagation(); close(); }+ });+ listen(popup, 'mouseenter', cancelClose);+ listen(popup, 'mouseleave', delayedClose);+ listen(popup, 'mousedown', function (event) { event.preventDefault(); event.stopPropagation(); });+ ['click', 'pointerdown', 'pointerup', 'keyup', 'keypress'].forEach(function (name) {+ listen(popup, name, function (event) { event.stopPropagation(); });+ });+ listen(popup, 'keydown', function (event) { event.stopPropagation(); if (event.key === 'Escape') { close(); button.focus(); } });+ listen(window, 'resize', close);+ listen(document, 'scroll', function (event) { if (!popup.contains(event.target)) close(); }, true);+ listen(document, 'pointerdown', function (event) { if (!button.contains(event.target) && !popup.contains(event.target)) close(); }, true);+ return { close: close, open: open, destroy: function () { close(); listeners.forEach(function (remove) { remove(); }); popup.remove(); } };+ }function acMenuClose() {qpDiag('menu:close:before', { menuClass: exploreBtn.className });- exploreBtn.classList.add('wbs-menu-closed');+ exploreMenu.close();qpDiag('menu:close:after', { menuClass: exploreBtn.className });}- exploreBtn.addEventListener('mouseenter', function () { exploreBtn.classList.remove('wbs-menu-closed'); });- exploreBtn.addEventListener('mouseleave', function () { exploreBtn.classList.remove('wbs-menu-closed'); });exploreBtn.style.display = 'none'; // 找到可见会话输入区并完成定位后才显示,避免登录页出现悬空按钮。/* ———— 会话模块(session):暂存提示词、会话消息索引 & 快捷短语 ————@@ -3306,6 +3470,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {usageSummary: conversationUsageEnabled,fork: readForkEnabled(),phrase: true,+ themeTakeover: true,phrases: [],qpBatch: false,qpSel: {},@@ -3316,6 +3481,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!d || !d.ok) return;sessState.stash = !!d.stashEnabled;sessState.phrase = !!d.phraseEnabled;+ sessState.themeTakeover = d.themeTakeoverEnabled !== false;sessState.phrases = Array.isArray(d.phrases) ? d.phrases : [];// 同步 UI:会话开关 + 快捷短语列表区显隐var pane0 = enhancePane;@@ -3330,6 +3496,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (swU) swU.checked = !!conversationUsageEnabled;if (swF) swF.checked = !!sessState.fork;if (swP) swP.checked = !!sessState.phrase;+ var themeSwitch = themePane && themePane.querySelector('#wbs-theme-takeover');+ if (themeSwitch) themeSwitch.checked = sessState.themeTakeover;+ syncThemeTakeoverVisibility(sessState.themeTakeover);+ // 开关确认和异步设置回填也要启动图库加载,不能只在切换主题页时加载。+ syncWallpaperCardVisibility('nebula');if (area) area.style.display = sessState.phrase ? '' : 'none';renderQpList();renderExploreOptions();@@ -3343,7 +3514,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {/** 开关切换:写 daemon 并回应用户界(设置失败回滚 UI 状态) */function setSessionSwitchWire(name, el) {var v = !!el.checked;- api('/api/session-module-set', {+ el.disabled = true;+ return api('/api/session-module-set', {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ name: name, enabled: v }),@@ -3353,7 +3525,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}).catch(function (e) {toast('设置失败: ' + (e.message || e), true, root);syncSessionModule();- });+ }).finally(function () { el.disabled = false; });}/** 增强页快捷短语列表渲染(含批量模式) */@@ -3425,7 +3597,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}/** 发送按钮面板选项 = 快捷短语列表;点击项经 CDP 发送该短语(替换式,发完默认关面板) */function renderExploreOptions() {- var listHost = exploreBtn && exploreBtn.querySelector('#wbs-explore-list');+ var listHost = explorePopover && explorePopover.querySelector('#wbs-explore-list');if (!listHost) return;var phrases = sessState.phrases || [];// 渲染签名去重:短语内容无变化则不重建 DOM(syncStash 高频调用会摧毁 tooltip 的显示状态/绑定 → 闪烁)@@ -3684,35 +3856,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {exploreBtn.style.right = (wr - 38) + 'px'; // 32=按钮宽,6=gutter(贴暂存按钮右侧)exploreBtn.style.top = stashBtn.style.top || '0px';}- // 跟随主题设置按钮颜色(放弃跟随官方按钮):浅色主题=黑底白图标;深色/WorkDaddy 主题=白底黑图标- var acThemeObserver = null;- function acIsDarkTheme() {- try {- var de = document.documentElement;- if (de.classList && de.classList.contains('cb-dark')) return true;- if (de.getAttribute && de.getAttribute('data-theme') === 'dark') return true;- var bd = document.body;- if (bd && bd.getAttribute('data-vscode-theme-name') && /dark/i.test(bd.getAttribute('data-vscode-theme-name') || '')) return true;- return false;- } catch (e) { return false; }- }+ // 使用实时主题变量,颜色变化由 CSS 继承处理,无需监听深浅色属性。function applyThemeButtonColors() {- try {- var useWhite = acIsDarkTheme(); // 深色主题 → 白底;浅色 → 黑底- var bg = useWhite ? '#ffffff' : '#111111';- var fg = useWhite ? '#111111' : '#ffffff';- stashBtn.style.background = bg;- stashBtn.style.color = fg;- exploreBtn.style.background = bg;- exploreBtn.style.color = fg;- } catch (e) {}- }- function watchThemeForButtons() {- if (acThemeObserver || typeof MutationObserver === 'undefined') return;- try {- acThemeObserver = new MutationObserver(function () { applyThemeButtonColors(); });- acThemeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme'] });- } catch (e) {}+ stashBtn.style.background = 'var(--wb-button-primary-bg)';+ stashBtn.style.color = 'var(--wb-button-primary-fg)';+ exploreBtn.style.background = 'var(--wb-button-primary-bg)';+ exploreBtn.style.color = 'var(--wb-button-primary-fg)';}function positionStash() {// 新版布局没有 voice-mic-wrap:操作栏按钮行位于输入框正下方(与输入框同祖先容器)。@@ -3810,12 +3959,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (isWelcomePage() || !insertStash()) {stashBtn.style.display = 'none';exploreBtn.style.display = 'none';+ exploreMenu.close();exploreBtn.classList.add('wbs-menu-closed');return;}// 探索按钮常驻(若「快捷短语」开关开着):不等输入框有内容,只要定位到操作栏就常显exploreBtn.style.display = sessState.phrase ? 'flex' : 'none';- applyThemeButtonColors(); // 主题色按钮(浅色黑底白图 / 深色白底黑图)+ if (!sessState.phrase) exploreMenu.close();+ applyThemeButtonColors(); // 与发送按钮共享主题色renderExploreOptions(); // 面板选项 = 快捷短语列表(增删改后同步刷新)// 暂存按钮:仍按输入框是否有内容显隐,且「暂存提示词」开关需开着if (shouldShowStash() && sessState.stash) {@@ -5569,6 +5720,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var statusPopover = null;var statusPopoverOwner = null;var closeDailyProgressPopover = null;+ var closeAccountNotePopover = null;var refreshDailyProgressPopover = null;var dailyProgressRefreshPromises = {};var creditTooltipSegment = null;@@ -5616,6 +5768,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {left = rect.left - tipRect.width - gap;if (left < 8) left = rect.right + gap;top = rect.top - 8;+ } else if (placement === 'below') {+ left = rect.left + rect.width / 2 - tipRect.width / 2;+ top = rect.bottom + gap;} else {top = rect.top - tipRect.height - gap;if (top < 8) top = rect.bottom + gap;@@ -5692,6 +5847,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<span class="wbs-acct-stat-divider"></span>' +'<div class="wbs-acct-stat"><span>总积分</span><strong id="wbs-acct-total">-</strong></div>' +'<button class="wbs-acct-eye" type="button" data-act="credit-summary" title="汇总" aria-label="积分汇总" aria-expanded="false">' + CREDIT_SUMMARY_ICON + '</button>' ++ '<button class="wbs-acct-eye" type="button" data-act="model-rate-limit-summary" title="模型限流" aria-label="模型限流" aria-expanded="false">' + MODEL_RATE_LIMIT_ICON + '</button>' +'</div>' +'<div class="wbs-acct-actions">' +'<button class="wbs-acct-io wbs-acct-icon" type="button" data-act="token-stats" title="用量统计" aria-label="用量统计">' + TOKEN_STATS_ICON + '</button>' +@@ -5706,6 +5862,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {root.querySelector('[data-act="account-more"]').addEventListener('click', openAccountOrderModal);setupCreditSummary();setupDailyProgressPopover();+ setupAccountNotePopover();+ setupModelRateLimitPopover();logoutBtn = root.querySelector('[data-act="logout"]');var eyeBtn = root.querySelector('.wbs-acct-eye');if (eyeBtn) eyeBtn.addEventListener('click', toggleAccountMask);@@ -5998,6 +6156,160 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});}+ function setupAccountNotePopover() {+ if (!accountsPane) return;+ var popup = el('div', 'wbs-account-note-popover');+ popup.id = 'wbs-account-note-popover';+ popup.hidden = true;+ popup.setAttribute('role', 'dialog');+ popup.setAttribute('aria-label', '账号备注');+ popup.innerHTML = '<div class="wbs-account-note-head"><label for="wbs-account-note-input">账号备注</label><button type="button" class="wbs-icon-btn" data-note-close title="关闭" aria-label="关闭"><svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.5"><path d="m4 4 8 8m0-8-8 8"/></svg></button></div>' ++ '<textarea id="wbs-account-note-input" maxlength="2000" placeholder="暂无备注,点击添加…" rows="4"></textarea>' ++ '<div class="wbs-account-note-footer"><span role="status" aria-live="polite"></span><button type="button" class="wbs-modal-btn" data-note-cancel>取消</button><button type="button" class="wbs-modal-btn primary" data-note-save>保存</button></div>';+ document.body.appendChild(popup);+ var input = popup.querySelector('textarea');+ var save = popup.querySelector('[data-note-save]');+ var cancel = popup.querySelector('[data-note-cancel]');+ var status = popup.querySelector('[role="status"]');+ var owner = null, uid = '', saved = '', saving = false, hideTimer = null, restoringFocus = false;+ var drafts = Object.create(null);+ function trigger(target) { return target && target.closest ? target.closest('.wbs-account-name') : null; }+ function dirty() { return input.value !== saved; }+ function update() {+ save.disabled = saving || !dirty();+ cancel.disabled = saving;+ input.readOnly = saving;+ save.textContent = saving ? '保存中…' : '保存';+ status.textContent = saving ? '正在保存' : dirty() ? '未保存 · ' + input.value.length + '/2000' : '';+ }+ function hide(returnFocus) {+ clearTimeout(hideTimer);+ if (!owner) return;+ if (dirty()) drafts[uid] = input.value;+ else delete drafts[uid];+ var previous = owner;+ previous.setAttribute('aria-expanded', 'false');+ owner = null;+ popup.hidden = true;+ if (returnFocus && previous.isConnected) {+ restoringFocus = true;+ previous.focus();+ restoringFocus = false;+ }+ }+ function position() {+ if (!owner) return;+ var rect = owner.getBoundingClientRect();+ var bounds = accountsPane.getBoundingClientRect();+ if (!owner.isConnected || !rect.width || rect.bottom < bounds.top || rect.top > bounds.bottom) { hide(false); return; }+ var box = popup.getBoundingClientRect();+ var left = Math.max(8, Math.min(rect.left - 5, window.innerWidth - box.width - 8));+ var top = rect.bottom + 8;+ if (top + box.height > window.innerHeight - 8) top = rect.top - box.height - 8;+ popup.style.left = Math.round(left) + 'px';+ popup.style.top = Math.round(Math.max(8, top)) + 'px';+ }+ function show(button, edit) {+ clearTimeout(hideTimer);+ if (restoringFocus) return;+ if (owner !== button) {+ // Hovering a different name must not replace an in-progress edit.+ if (owner && (saving || dirty() || popup.contains(document.activeElement)) && !edit) return;+ if (saving) return;+ hide(false);+ uid = button.getAttribute('data-uid');+ var account = state.accounts.filter(function (a) { return String(a.uid) === uid; })[0];+ if (!account) return;+ saved = account.note || '';+ input.value = Object.prototype.hasOwnProperty.call(drafts, uid) ? drafts[uid] : saved;+ owner = button;+ owner.setAttribute('aria-expanded', 'true');+ popup.hidden = false;+ update();+ position();+ }+ if (edit && owner) input.focus();+ }+ function deferHide() {+ clearTimeout(hideTimer);+ hideTimer = setBuildTimeout(function () {+ if (saving || dirty() || popup.matches(':hover') || popup.contains(document.activeElement) ||+ (owner && (owner.matches(':hover') || owner === document.activeElement))) return;+ hide(false);+ }, 220);+ }+ function submit() {+ if (!owner || saving || !dirty()) return;+ var savingUid = uid, value = input.value;+ saving = true;+ update();+ api('/api/accounts/note', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ uid: savingUid, note: value }) })+ .then(function () {+ if (!alive) return;+ state.accounts.forEach(function (a) { if (String(a.uid) === savingUid) a.note = value; });+ delete drafts[savingUid];+ saved = value;+ saving = false;+ update();+ status.textContent = '已保存';+ }).catch(function () {+ if (!alive) return;+ saving = false;+ update();+ status.textContent = '保存失败,请重试';+ });+ }+ listen(accountsPane, 'mouseover', function (event) {+ var button = trigger(event.target);+ if (button && !button.contains(event.relatedTarget)) show(button, false);+ });+ listen(accountsPane, 'mouseout', function (event) {+ var button = trigger(event.target);+ if (button && !button.contains(event.relatedTarget)) deferHide();+ });+ listen(accountsPane, 'focusin', function (event) { var button = trigger(event.target); if (button) show(button, false); });+ listen(accountsPane, 'focusout', deferHide);+ listen(accountsPane, 'click', function (event) {+ var button = trigger(event.target);+ if (!button) return;+ event.stopPropagation();+ show(button, true);+ });+ listen(accountsPane, 'keydown', function (event) {+ var button = trigger(event.target);+ if (!button) return;+ if (event.key === 'ArrowDown' || (event.key === 'Tab' && !event.shiftKey && owner === button)) {+ event.preventDefault(); event.stopPropagation(); show(button, true);+ }+ });+ listen(popup, 'mouseenter', function () { clearTimeout(hideTimer); });+ listen(popup, 'mouseleave', deferHide);+ listen(popup, 'focusout', deferHide);+ ['pointerdown', 'mousedown', 'mouseup', 'dblclick', 'keyup', 'keypress', 'wheel'].forEach(function (type) {+ listen(popup, type, function (event) { event.stopPropagation(); });+ });+ listen(popup, 'input', function (event) { event.stopPropagation(); update(); });+ listen(popup, 'keydown', function (event) {+ event.stopPropagation();+ if (event.key === 'Escape') { event.preventDefault(); hide(true); }+ if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); }+ });+ listen(popup, 'click', function (event) {+ event.stopPropagation();+ if (event.target.closest('[data-note-save]')) submit();+ if (event.target.closest('[data-note-cancel]') && !saving) { input.value = saved; hide(true); }+ if (event.target.closest('[data-note-close]')) hide(true);+ });+ listen(document, 'pointerdown', function (event) {+ if (owner && !popup.contains(event.target) && !owner.contains(event.target)) hide(false);+ }, true);+ listen(document, 'keydown', function (event) { if (owner && event.key === 'Escape') { event.stopPropagation(); hide(true); } });+ listen(panel, 'scroll', position, true);+ listen(window, 'resize', position);+ closeAccountNotePopover = function () { hide(false); };+ registerDisposer(function () { hide(false); popup.remove(); closeAccountNotePopover = null; });+ }+function setupDailyProgressPopover() {if (!accountsPane || !CAPS.growthDaily || WBS_PROFILE_IS_AI) return;var popup = ensureStatusPopover();@@ -6124,6 +6436,124 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {registerDisposer(function () { hide(true); closeDailyProgressPopover = null; refreshDailyProgressPopover = null; });}+ function setupModelRateLimitPopover() {+ if (!accountsPane) return;+ var popup = ensureStatusPopover();+ var activeBadge = null;+ var pinned = false;+ var popoverHovered = false;+ var hideTimer = null;+ function findBadge(target) {+ var node = target;+ while (node && node !== accountsPane) {+ if (node.nodeType === 1 && node.classList && node.classList.contains('wbs-model-rate-limit')) return node;+ node = node.parentNode;+ }+ return null;+ }+ function hide(force) {+ clearTimeout(hideTimer);+ if ((pinned || popoverHovered) && !force) return;+ var previous = activeBadge;+ if (previous) previous.setAttribute('aria-expanded', 'false');+ activeBadge = null;+ pinned = false;+ popoverHovered = false;+ hideStatusPopover(previous);+ }+ function deferHide() {+ clearTimeout(hideTimer);+ hideTimer = setBuildTimeout(function () {+ if (popup && popup.matches && popup.matches(':hover')) {+ popoverHovered = true;+ return;+ }+ hide(false);+ }, 220);+ }+ function show(badge, shouldPin) {+ clearTimeout(hideTimer);+ if (!badge) return;+ if (activeBadge && activeBadge !== badge) activeBadge.setAttribute('aria-expanded', 'false');+ activeBadge = badge;+ pinned = !!shouldPin;+ badge.setAttribute('aria-expanded', 'true');+ var uid = badge.getAttribute('data-uid');+ var account = state.accounts.filter(function (item) { return String(item.uid) === String(uid); })[0];+ popup = showStatusPopover(badge, modelRateLimitPopoverHtml(account), 'rate-limit', 'side');+ }+ var summaryButton = accountsPane.querySelector('[data-act="model-rate-limit-summary"]');+ function showSummary(shouldPin) {+ if (!summaryButton) return;+ clearTimeout(hideTimer);+ if (activeBadge && activeBadge !== summaryButton) activeBadge.setAttribute('aria-expanded', 'false');+ activeBadge = summaryButton;+ pinned = !!shouldPin;+ summaryButton.setAttribute('aria-expanded', 'true');+ popup = showStatusPopover(summaryButton, modelRateLimitSummaryPopoverHtml(state.accounts), 'rate-limit-summary', 'below');+ }+ listen(accountsPane, 'mouseover', function (event) {+ var badge = findBadge(event.target);+ if (!badge || badge === activeBadge) return;+ show(badge, false);+ });+ listen(accountsPane, 'mouseout', function (event) {+ var from = findBadge(event.target);+ var to = findBadge(event.relatedTarget);+ if (from && from !== to) deferHide();+ });+ listen(accountsPane, 'focusin', function (event) {+ var badge = findBadge(event.target);+ if (badge) show(badge, false);+ });+ listen(accountsPane, 'focusout', function (event) {+ if (findBadge(event.target)) deferHide();+ });+ listen(accountsPane, 'click', function (event) {+ var badge = findBadge(event.target);+ if (!badge) return;+ event.preventDefault();+ event.stopPropagation();+ if (activeBadge === badge && pinned) hide(true);+ else show(badge, true);+ });+ listen(accountsPane, 'keydown', function (event) {+ var badge = findBadge(event.target);+ if (badge && (event.key === 'Enter' || event.key === ' ')) {+ event.preventDefault();+ if (activeBadge === badge && pinned) hide(true);+ else show(badge, true);+ }+ if (event.key === 'Escape') hide(true);+ });+ if (summaryButton) {+ listen(summaryButton, 'mouseenter', function () { showSummary(false); });+ listen(summaryButton, 'mouseleave', deferHide);+ listen(summaryButton, 'focus', function () { showSummary(false); });+ listen(summaryButton, 'blur', deferHide);+ listen(summaryButton, 'click', function (event) {+ event.preventDefault();+ event.stopPropagation();+ if (activeBadge === summaryButton && pinned) hide(true);+ else showSummary(true);+ });+ listen(summaryButton, 'keydown', function (event) {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ if (activeBadge === summaryButton && pinned) hide(true);+ else showSummary(true);+ }+ });+ }+ listen(popup, 'mouseenter', function () { popoverHovered = true; clearTimeout(hideTimer); });+ listen(popup, 'mouseleave', function () { popoverHovered = false; deferHide(); });+ listen(popup, 'pointerdown', function (event) { event.stopPropagation(); });+ listen(window, 'resize', function () { hide(true); });+ listen(accountsPane, 'scroll', function () { hide(true); }, true);+ listen(document, 'keydown', function (event) { if (event.key === 'Escape') hide(true); });+ registerDisposer(function () { hide(true); });+ }+function closeSecureTransferModal(mask) {if (mask && mask.parentNode) mask.parentNode.removeChild(mask);}@@ -6453,6 +6883,106 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'var(--wbs-trend-series-10)', 'var(--wbs-trend-series-11)', 'var(--wbs-trend-series-12)'];}+ function resolveUsageColor(value, owner) {+ if (!value) return '';+ var probe = document.createElement('span');+ probe.style.position = 'absolute';+ probe.style.width = '0';+ probe.style.height = '0';+ probe.style.color = value;+ (owner || document.body).appendChild(probe);+ var resolved = getComputedStyle(probe).color;+ probe.remove();+ return resolved;+ }++ function usagePieData(rows) {+ var sorted = (rows || []).map(function (row) {+ return { label: String(row.label || '未知'), value: Number(row.value), calls: Math.max(0, Number(row.calls) || 0) };+ }).filter(function (row) { return Number.isFinite(row.value) && row.value > 0; })+ .sort(function (a, b) { return b.value - a.value || a.label.localeCompare(b.label); });+ var total = sorted.reduce(function (sum, row) { return sum + row.value; }, 0);+ var segments = sorted.slice(0, 7);+ if (sorted.length > 8) {+ var rest = sorted.slice(7);+ segments.push({ label: '其他', value: rest.reduce(function (sum, row) { return sum + row.value; }, 0),+ calls: rest.reduce(function (sum, row) { return sum + row.calls; }, 0), children: rest });+ } else segments = sorted;+ return { total: total, segments: segments };+ }++ function usagePieHtml(rows, title, unit, formatValue, emptyText) {+ var data = usagePieData(rows);+ var heading = '<div class="wbs-token-stats-section wbs-usage-pie-section"><div class="wbs-token-stats-section-title">' + esc(title) + '</div>';+ if (!data.total) return heading + '<div class="wbs-token-stats-empty">' + esc(emptyText) + '</div></div>';+ var colors = usageTrendColors(), offset = -Math.PI / 2;+ function percent(value) { var p = value / data.total * 100; return p < 0.1 ? '<0.1%' : p.toFixed(1) + '%'; }+ function description(row) { return row.label + ' · ' + formatValue(row.value) + ' ' + unit + ' · ' + percent(row.value); }+ function legendRow(row, color, index) {+ return '<div class="wbs-pie-row" data-pie-index="' + index + '" title="' + escAttr(description(row)) + '"><i style="background:' + color + '" aria-hidden="true"></i>' ++ '<span class="wbs-pie-name">' + esc(row.label) + '<small>' + esc(formatTokenCount(row.calls)) + ' 次</small></span>' ++ '<b>' + esc(formatValue(row.value)) + '</b><span class="wbs-pie-percent">' + esc(percent(row.value)) + '</span></div>';+ }+ var arcs = data.segments.map(function (row, index) {+ var angle = row.value / data.total * Math.PI * 2;+ var end = offset + angle;+ var startX = 64 + 58 * Math.cos(offset), startY = 64 + 58 * Math.sin(offset);+ var endX = 64 + 58 * Math.cos(end), endY = 64 + 58 * Math.sin(end);+ var shape = data.segments.length === 1 ? '<circle cx="64" cy="64" r="58"' :+ '<path d="M64 64 L' + startX + ' ' + startY + ' A58 58 0 ' + (angle > Math.PI ? 1 : 0) + ' 1 ' + endX + ' ' + endY + ' Z"';+ offset = end;+ return shape + ' class="wbs-pie-slice" data-pie-index="' + index + '" tabindex="0" role="img" aria-label="' + escAttr(description(row)) + '"' ++ ' data-pie-label="' + escAttr(row.label) + '" data-pie-value="' + escAttr(formatValue(row.value) + ' ' + unit) + '" data-pie-percent="' + escAttr(percent(row.value)) + '" data-pie-calls="' + escAttr(formatTokenCount(row.calls)) + '"' ++ ' style="--wbs-pie-color:' + colors[index] + '"></' + (data.segments.length === 1 ? 'circle' : 'path') + '>';+ }).join('');+ var legend = data.segments.map(function (row, index) {+ var line = legendRow(row, colors[index], index);+ return row.children ? '<details class="wbs-pie-other"><summary>' + line + '</summary><div class="wbs-pie-details">' + row.children.map(function (child) { return legendRow(child, colors[index], index); }).join('') + '</div></details>' : line;+ }).join('');+ return heading + '<div class="wbs-pie-subtitle"><strong>' + esc(formatValue(data.total)) + '</strong><span>' + esc(unit) + '</span></div>' ++ '<div class="wbs-usage-pie"><div class="wbs-pie-plot"><svg viewBox="0 0 128 128" aria-label="' + escAttr(title) + '">' + arcs + '</svg></div>' ++ '<div class="wbs-pie-legend">' + legend + '</div></div>' ++ '<div class="wbs-pie-tooltip" role="tooltip" hidden><strong></strong><div data-pie-tip-value></div><div data-pie-tip-detail></div></div></div>';+ }++ function wireUsagePies(container) {+ container.querySelectorAll('.wbs-usage-pie-section').forEach(function (section) {+ var tooltip = section.querySelector('.wbs-pie-tooltip');+ if (!tooltip) return;+ function clear() {+ section.classList.remove('has-pie-preview');+ section.querySelectorAll('[data-pie-index]').forEach(function (el) { el.classList.remove('is-preview'); });+ tooltip.hidden = true;+ }+ function preview(target, event) {+ var item = target && target.closest && target.closest('[data-pie-index]');+ if (!item) { clear(); return; }+ var index = item.getAttribute('data-pie-index');+ var slice = section.querySelector('.wbs-pie-slice[data-pie-index="' + index + '"]');+ if (!slice) return;+ section.classList.add('has-pie-preview');+ section.querySelectorAll('[data-pie-index]').forEach(function (el) { el.classList.toggle('is-preview', el.getAttribute('data-pie-index') === index); });+ tooltip.querySelector('strong').textContent = slice.getAttribute('data-pie-label');+ tooltip.querySelector('[data-pie-tip-value]').textContent = slice.getAttribute('data-pie-value');+ tooltip.querySelector('[data-pie-tip-detail]').textContent = slice.getAttribute('data-pie-percent') + ' · ' + slice.getAttribute('data-pie-calls') + ' 次';+ tooltip.hidden = false;+ var bounds = item.getBoundingClientRect();+ var x = event && Number.isFinite(event.clientX) ? event.clientX : bounds.left + bounds.width / 2;+ var y = event && Number.isFinite(event.clientY) ? event.clientY : bounds.bottom;+ var tip = tooltip.getBoundingClientRect();+ tooltip.style.left = Math.max(8, Math.min(window.innerWidth - tip.width - 8, x + 12)) + 'px';+ tooltip.style.top = Math.max(8, y + tip.height + 20 > window.innerHeight ? y - tip.height - 12 : y + 12) + 'px';+ }+ section.addEventListener('pointermove', function (event) { preview(event.target, event); });+ section.addEventListener('pointerleave', clear);+ section.addEventListener('focusin', function (event) { preview(event.target); });+ section.addEventListener('focusout', clear);+ section.addEventListener('keydown', function (event) { if (event.key === 'Escape' && !tooltip.hidden) { clear(); event.stopPropagation(); } });+ section.addEventListener('scroll', clear, true);+ });+ }++function usageTrendGroups(days, records, dimension, names) {var groups = new Map();(records || []).forEach(function (row) {@@ -6518,7 +7048,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {renderUsageBreakdown(panel, days, records, modes, state, formatValue);};});- var series = mode === 'total' ? [{ label: '总量', values: days.map(function (day) { return day.value; }), color: getComputedStyle(panel).getPropertyValue('--wbs-primary').trim() }] :+ var series = mode === 'total' ? [{ label: '总量', values: days.map(function (day) { return day.value; }), color: getComputedStyle(panel).getPropertyValue('--wbs-trend-series-1').trim() || colors[0] }] :groups.filter(function (group) { return selected.has(group.key); }).map(function (group, index) {var dot = Array.from(legend.querySelectorAll('[data-trend-series]')).find(function (button) { return button.dataset.trendSeries === group.key; }).querySelector('i');return { label: group.label, values: group.values, color: getComputedStyle(dot).color, dash: index % 3 };@@ -6538,7 +7068,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var values = (Array.isArray(points) ? points : []).map(function (point) {return { label: String(point && point.label || ''), value: Math.max(0, Number(point && point.value) || 0), title: String(point && point.title || '') };});- series = Array.isArray(series) ? series : [{ label: '总量', values: values.map(function (point) { return point.value; }), color: 'var(--wbs-primary)' }];+ series = Array.isArray(series) ? series : [{ label: '总量', values: values.map(function (point) { return point.value; }), color: '' }];var cssWidth = Math.max(container.clientWidth - 24, values.length * 42, 320);var cssHeight = 166;var ratio = Math.max(1, Math.min(2, window.devicePixelRatio || 1));@@ -6550,9 +7080,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {context.setTransform(ratio, 0, 0, ratio, 0, 0);context.clearRect(0, 0, cssWidth, cssHeight);var styles = getComputedStyle(container);- var primaryRgb = styles.getPropertyValue('--wbs-primary-rgb').trim() || '34,197,94';- var muted = styles.getPropertyValue('--wb-icon-tertiary').trim() || '#8a8f98';- var border = styles.getPropertyValue('--wb-border-subtle').trim() || 'rgba(20,24,32,.1)';+ var primary = resolveUsageColor(styles.getPropertyValue('--wbs-trend-series-1').trim(), container) || styles.getPropertyValue('--wb-color-text-primary').trim();+ var muted = styles.getPropertyValue('--wb-icon-tertiary').trim() || styles.getPropertyValue('--wb-color-text-secondary').trim();+ var border = styles.getPropertyValue('--wb-border-subtle').trim() || styles.getPropertyValue('--wb-border-default').trim();+ // Canvas APIs do not resolve CSS var()/color-mix() values themselves.+ // Resolve every theme-token color against the chart container first so+ // both the total line and grouped lines render in the selected theme.+ series = series.map(function (line) {+ var color = resolveUsageColor(line.color, container) || primary;+ return Object.assign({}, line, { color: color });+ });// Keep endpoint labels inside the canvas. Centered labels at x=18 used to// clip the first/last value when a credit amount had more than a few digits.context.font = '600 11px -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif';@@ -6577,7 +7114,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});if (values.length && series.length === 1) {var area = context.createLinearGradient(0, chartTop, 0, chartBottom);- area.addColorStop(0, series[0].color || 'rgb(' + primaryRgb + ')');+ area.addColorStop(0, series[0].color || primary);area.addColorStop(1, 'transparent');context.beginPath();series[0].values.forEach(function (value, index) { var px = x(index), py = y(value); if (!index) context.moveTo(px, py); else context.lineTo(px, py); });@@ -6587,7 +7124,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {series.forEach(function (line) {context.beginPath();line.values.forEach(function (value, index) { var px = x(index), py = y(value); if (!index) context.moveTo(px, py); else context.lineTo(px, py); });- context.strokeStyle = line.color || 'rgb(' + primaryRgb + ')';+ context.strokeStyle = line.color || primary;context.lineWidth = 2; context.lineJoin = 'round'; context.lineCap = 'round';context.setLineDash(line.dash === 1 ? [6, 3] : line.dash === 2 ? [2, 3] : []); context.stroke(); context.setLineDash([]);line.values.forEach(function (value, index) {@@ -6682,12 +7219,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var creditPollTimer = null;var focusBefore = document.activeElement;function closeStats() {+ if (!mask.isConnected) return;if (creditPollTimer) clearTimeout(creditPollTimer);+ if (firstLoadTimer) clearTimeout(firstLoadTimer);+ tokenReadSerial++;mask.remove();if (focusBefore && focusBefore.isConnected) focusBefore.focus();}mask.__wbsClose = closeStats;- registerDisposer(function () { if (creditPollTimer) clearTimeout(creditPollTimer); mask.remove(); });+ mask.addEventListener('scroll', function () {+ mask.querySelectorAll('.wbs-pie-tooltip').forEach(function (tooltip) { tooltip.hidden = true; });+ mask.querySelectorAll('.has-pie-preview').forEach(function (section) { section.classList.remove('has-pie-preview'); });+ mask.querySelectorAll('.is-preview[data-pie-index]').forEach(function (item) { item.classList.remove('is-preview'); });+ }, true);+ registerDisposer(closeStats);mask.querySelector('[data-token-close]').addEventListener('click', closeStats);mask.addEventListener('click', function (event) { event.stopPropagation(); if (event.target === mask) closeStats(); });['pointerdown', 'pointerup', 'keyup', 'keypress'].forEach(function (name) { mask.addEventListener(name, function (event) { event.stopPropagation(); }); });@@ -6695,7 +7240,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {event.stopPropagation();if (event.key === 'Escape') { event.preventDefault(); closeStats(); }if (event.key === 'Tab') {- var controls = Array.from(mask.querySelectorAll('button,select,input')).filter(function (el) { return !el.disabled && el.getClientRects().length; });+ var controls = Array.from(mask.querySelectorAll('button,select,input,summary,[tabindex="0"]')).filter(function (el) { return !el.disabled && el.getClientRects().length; });var first = controls[0], last = controls[controls.length - 1];if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }@@ -6705,6 +7250,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function usageDays(kind) { return Number(mask.querySelector('[data-' + kind + '-days][aria-pressed="true"]').dataset[kind + 'Days']); }var overlay = mask.querySelector('.wbs-token-stats-overlay');var hasStats = false;+ var tokenBusy = false;var firstLoadTimer = null;var tokenReadSerial = 0;var tokenTrendState = { mode: 'total', selected: {} };@@ -6757,22 +7303,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});creditBody.innerHTML = '<div class="wbs-token-stats-grid wbs-credit-stats-grid"><div><span>积分消耗</span><strong>' + (creditData.daily.length ? esc(fmtCredits(total)) : '—') + '</strong></div><div><span>调用</span><strong>' + (creditData.daily.length ? esc(formatTokenCount(calls)) : '—') + '</strong></div></div>' +'<div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">每日趋势</div>' + usageTrendChartHtml('每日积分趋势', true) + ((creditData.failures || []).length ? '<div class="wbs-credit-stats-note">* 表示部分账号查询失败;— 表示查询失败,暂无数据。</div>' : '') + '</div>' +- '<div class="wbs-usage-columns"><div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">账号用量</div><div class="wbs-token-model-scroll"><div class="wbs-token-stats-table">' + (selected.slice().filter(function (a) { return (byAccount[a.uid] || 0) > 0; }).sort(function (a,b) { return (byAccount[b.uid] || 0) - (byAccount[a.uid] || 0); }).map(function (a) { return '<div><span title="' + escAttr(a.nickname || a.uid) + '">' + esc(a.nickname || a.uid) + '</span><b>' + esc(fmtCredits(byAccount[a.uid])) + '</b><em>' + esc(formatTokenCount(accountCalls[a.uid] || 0)) + ' 次</em></div>'; }).join('') || '<div class="wbs-token-stats-empty">没有匹配的账号</div>') + '</div></div></div>' +- (Object.keys(byModel).length ? '<div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">模型用量</div><div class="wbs-token-model-scroll"><div class="wbs-token-stats-table">' + Object.keys(byModel).sort(function (a, b) { return byModel[b].used - byModel[a].used || a.localeCompare(b); }).map(function (model) { return '<div><span title="' + escAttr(model) + '">' + esc(model) + '</span><b>' + esc(fmtCredits(byModel[model].used)) + '</b><em>' + esc(formatTokenCount(byModel[model].count)) + ' 次</em></div>'; }).join('') + '</div></div></div>' : '') + '</div>';+ '<div class="wbs-usage-columns">' ++ usagePieHtml(selected.map(function (a) { return { label: a.nickname || a.uid, value: byAccount[a.uid] || 0, calls: accountCalls[a.uid] || 0 }; }), '账号用量', '积分', fmtCredits, '暂无账号数据') ++ usagePieHtml(Object.keys(byModel).map(function (model) { return { label: model, value: byModel[model].used, calls: byModel[model].count }; }), '模型用量', '积分', fmtCredits, '暂无模型数据') + '</div>';+ wireUsagePies(creditBody);var creditNames = Object.create(null);creditAccounts.forEach(function (account) { creditNames[account.uid] = account.nickname || account.uid; });renderUsageBreakdown(creditBody.querySelector('.wbs-trend-panel'), days, (creditData.daily || []).map(function (row) {return { day: row.date, account: row.uid, value: Number(row.used) || 0 };}).concat(modelRecords), { account: creditNames, model: Object.keys(byModel).reduce(function (out, model) { out[model] = model; return out; }, {}) }, creditTrendState, fmtCredits);- var accountScroll = creditBody.querySelector('.wbs-token-model-scroll');- if (accountScroll) {- var syncAccountFade = function () {- accountScroll.classList.toggle('no-overflow', accountScroll.scrollHeight <= accountScroll.clientHeight + 1);- accountScroll.classList.toggle('at-end', accountScroll.scrollTop + accountScroll.clientHeight >= accountScroll.scrollHeight - 1);- };- accountScroll.addEventListener('scroll', syncAccountFade, { passive: true });- syncAccountFade();- }+}function setCreditBusy(busy, showOverlay) {creditBusy = busy;@@ -6852,6 +7392,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {mask.querySelectorAll('[data-usage-pane]').forEach(function (pane) { pane.hidden = pane.getAttribute('data-usage-pane') !== tab; });mask.querySelector('.wbs-usage-scroll').scrollTop = 0;if (tab === 'credit' && (changed || !creditLoaded)) loadCredits();+ if (tab === 'token' && !hasStats && !tokenBusy) load();});});['token', 'credit'].forEach(function (kind) {@@ -6868,6 +7409,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});});function load() {+ if (tokenBusy) return;+ tokenBusy = true;var serial = ++tokenReadSerial;mask.querySelectorAll('[data-token-days]').forEach(function (button) { button.disabled = true; });overlay.hidden = false;@@ -6905,35 +7448,32 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div><span>缓存读取</span><strong>' + esc(formatTokenCount(totals.cacheRead)) + '</strong></div>' +'<div><span>缓存写入</span><strong>' + esc(formatTokenCount(totals.cacheWrite)) + '</strong></div>' +'</div><div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">每日趋势</div>' + usageTrendChartHtml('每日 Token 趋势', true) + '</div>' +- '<div class="wbs-usage-columns"><div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">模型排行</div><div class="wbs-token-model-scroll"><div class="wbs-token-stats-table">' + ((stats.models || []).slice(0, 12).map(function (item) { return '<div><span>' + esc(item.model) + '</span><b>' + esc(formatTokenCount((item.input || 0) + (item.output || 0))) + '</b><em>' + esc(formatTokenCount(item.calls || 0)) + ' 次</em></div>'; }).join('') || '<div class="wbs-token-stats-empty wbs-token-empty-model">暂无模型数据</div>') + '</div></div></div>' +- '<div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">账号用量</div><div class="wbs-token-model-scroll"><div class="wbs-token-stats-table">' + (accountRows.map(function (item) { var label = item.nickname || item.account; var value = (item.input || 0) + (item.output || 0); return '<div><span title="' + escAttr(label) + '">' + esc(label) + '</span><b>' + esc(formatTokenCount(value)) + '</b><em>' + esc(formatTokenCount(item.calls || 0)) + ' 次</em></div>'; }).join('') || '<div class="wbs-token-stats-empty">暂无账号数据</div>') + '</div></div></div></div>';+ '<div class="wbs-usage-columns">' ++ usagePieHtml((stats.models || []).map(function (item) { return { label: item.model, value: (item.input || 0) + (item.output || 0), calls: item.calls }; }), '模型用量', 'Token(输入 + 输出)', formatTokenCount, '暂无模型数据') ++ usagePieHtml(accountRows.map(function (item) { return { label: item.nickname || item.account, value: (item.input || 0) + (item.output || 0), calls: item.calls }; }), '账号用量', 'Token(输入 + 输出)', formatTokenCount, '暂无账号数据') + '</div>';+ wireUsagePies(body);var tokenNames = Object.create(null);((result && result.accounts) || []).forEach(function (item) { tokenNames[item.uid] = item.nickname || item.uid; });renderUsageBreakdown(body.querySelector('.wbs-trend-panel'), tokenDays, (stats.dailyBreakdown || []).map(function (row) {return { day: row.day, account: row.account, model: row.model, value: (row.input || 0) + (row.output || 0) };}), { account: tokenNames, model: Object.create(null) }, tokenTrendState, formatTokenCount);- var modelScroll = mask.querySelector('.wbs-token-model-scroll');- if (modelScroll) {- var syncModelFade = function () { modelScroll.classList.toggle('at-end', modelScroll.scrollTop + modelScroll.clientHeight >= modelScroll.scrollHeight - 1); modelScroll.classList.toggle('no-overflow', modelScroll.scrollHeight <= modelScroll.clientHeight + 1); };- modelScroll.addEventListener('scroll', syncModelFade, { passive: true });- syncModelFade();- }+hasStats = true;- }).catch(function (error) { if (!mask.isConnected || serial !== tokenReadSerial) return; if (hasStats) toast('读取失败:' + (error.message || error), true, root); else body.innerHTML = '<div class="wbs-token-stats-empty">读取失败:' + esc(error.message || error) + '</div>'; }).finally(function () { if (!mask.isConnected || serial !== tokenReadSerial) return; if (firstLoadTimer) { clearTimeout(firstLoadTimer); firstLoadTimer = null; } mask.querySelectorAll('[data-token-days]').forEach(function (button) { button.disabled = false; }); overlay.hidden = true; });+ }).catch(function (error) { if (!mask.isConnected || serial !== tokenReadSerial) return; if (hasStats) toast('读取失败:' + (error.message || error), true, root); else body.innerHTML = '<div class="wbs-token-stats-empty">读取失败:' + esc(error.message || error) + '</div>'; }).finally(function () { if (!mask.isConnected || serial !== tokenReadSerial) return; tokenBusy = false; if (firstLoadTimer) { clearTimeout(firstLoadTimer); firstLoadTimer = null; } mask.querySelectorAll('[data-token-days]').forEach(function (button) { button.disabled = false; }); overlay.hidden = true; });}if (mask.querySelector('[data-usage-tab].active').getAttribute('data-usage-tab') === 'credit') loadCredits(); else load();}// ===== Tab 切换 =====function switchTab(name) {+ if (typeof closeAccountNotePopover === 'function') closeAccountNotePopover();var tabs = root.querySelectorAll('.wbs-tab');var panes = root.querySelectorAll('.wbs-pane');for (var i = 0; i < tabs.length; i++) tabs[i].classList.toggle('active', tabs[i].getAttribute('data-tab') === name);for (var j = 0; j < panes.length; j++) panes[j].classList.toggle('active', panes[j].getAttribute('data-pane') === name);if (name === 'theme') {if (themePane && !themePane.dataset.built) buildThemePane();- var themeBtn = themePane && themePane.querySelector('#wbs-theme-seg .wbs-theme-opt.active');- syncWallpaperCardVisibility(themeBtn ? themeBtn.getAttribute('data-wbs-theme-option') : 'default');+ syncWallpaperCardVisibility('nebula');}if (name === 'sessions' && sessionsPane && !sessionsPane.dataset.built) buildSessionsPane();if (name === 'models' && modelsPane && !modelsPane.dataset.built) buildModelsPane();@@ -7698,6 +8238,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<button class="wbs-sess-bbtn wbs-sess-done" type="button" id="wbs-sess-done">取消</button>' +'</div>' +'</div>' ++ '<div class="wbs-sess-export-progress" id="wbs-sess-export-progress" role="status" aria-live="polite" hidden>' ++ '<div class="wbs-sess-export-head"><strong data-export-title></strong><button type="button" class="wbs-sess-bbtn" data-export-cancel>取消导出</button><button type="button" class="wbs-sess-bbtn" data-export-open hidden>打开导出目录</button></div>' ++ '<progress data-export-progress max="100" aria-label="导出进度"></progress><div data-export-detail></div></div>' +'<div class="wbs-sess-copy-progress" id="wbs-sess-copy-progress" role="status" aria-live="polite" hidden>' +'<div class="wbs-sess-copy-head"><span class="wbs-sess-copy-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></span><strong class="wbs-sess-copy-title">正在同步会话</strong></div>' +'<div class="wbs-sess-copy-detail"></div><div class="wbs-sess-copy-track" role="progressbar" aria-label="会话同步进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><span class="wbs-sess-copy-fill"></span></div>' +@@ -7719,7 +8262,45 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {loadSessionAccounts();loadSessions();pollActiveSessionCopyJob();+ pollSessionExport();registerDisposer(function () { if (sessionsState.autoCopyPollTimer) clearTimeout(sessionsState.autoCopyPollTimer); });+ registerDisposer(function () { if (sessionsState.exportPollTimer) clearTimeout(sessionsState.exportPollTimer); });+ }++ function renderSessionExport(job) {+ var card = sessionsPane && sessionsPane.querySelector('#wbs-sess-export-progress');+ if (!card) return;+ sessionsState.exportJob = job;+ card.hidden = !job;+ var button = sessionsPane.querySelector('#wbs-sess-export');+ if (button) button.disabled = !!(job && job.running);+ if (!job) return;+ card.querySelector('[data-export-title]').textContent = ({ preparing: '正在准备导出…', writing: '正在导出会话…', cancelling: '正在取消导出…', cancelled: '会话导出已取消', completed: '会话导出完成', failed: '会话导出失败' })[job.status] || '正在准备导出…';+ var progress = card.querySelector('[data-export-progress]');+ progress.hidden = !job.running;+ if (job.status === 'preparing') progress.removeAttribute('value'); else progress.value = job.percent || 0;+ card.querySelector('[data-export-detail]').textContent = job.file || job.error ||+ (job.totalBytes ? sessionCopySizeText(job.processedBytes) + ' / ' + sessionCopySizeText(job.totalBytes) + ' · ' + job.percent + '%' : '');+ card.querySelector('[data-export-cancel]').hidden = !job.running;+ card.querySelector('[data-export-cancel]').disabled = job.status === 'cancelling';+ card.querySelector('[data-export-open]').hidden = job.status !== 'completed';+ }++ function pollSessionExport(id) {+ if (sessionsState.exportPollTimer) clearTimeout(sessionsState.exportPollTimer);+ sessionsState.exportPollTimer = null;+ var serial = sessionsState.exportReadSerial = (sessionsState.exportReadSerial || 0) + 1;+ return api('/api/sessions/export' + (id ? '?id=' + encodeURIComponent(id) : '')).then(function (result) {+ if (!alive || serial !== sessionsState.exportReadSerial) return;+ renderSessionExport(result.job);+ if (result.job && result.job.running) sessionsState.exportPollTimer = setBuildTimeout(function () { pollSessionExport(result.job.id); }, 800);+ }).catch(function (error) {+ if (!alive || serial !== sessionsState.exportReadSerial) return;+ if (error.payload && error.payload.code === 'EXPORT_JOB_NOT_FOUND') return pollSessionExport();+ var detail = sessionsPane && sessionsPane.querySelector('[data-export-detail]');+ if (detail && sessionsState.exportJob) detail.textContent = '导出进度暂时无法读取,正在重试…';+ sessionsState.exportPollTimer = setBuildTimeout(function () { pollSessionExport(id); }, 2500);+ });}function sortSessionAccounts(accounts, accountOrder) {@@ -8125,6 +8706,22 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function wireSessionsPane() {+ var exportCard = sessionsPane.querySelector('#wbs-sess-export-progress');+ if (exportCard) {+ exportCard.querySelector('[data-export-cancel]').addEventListener('click', function () {+ var job = sessionsState.exportJob;+ if (!job || !job.running) return;+ api('/api/sessions/export/cancel', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: job.id }) })+ .then(function (result) { renderSessionExport(result.job); pollSessionExport(job.id); })+ .catch(function (error) { toast(error.message, true, root); });+ });+ exportCard.querySelector('[data-export-open]').addEventListener('click', function () {+ var job = sessionsState.exportJob;+ if (!job || job.status !== 'completed') return;+ api('/api/sessions/export/open', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: job.id }) })+ .catch(function (error) { toast(error.message, true, root); });+ });+ }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;@@ -8204,15 +8801,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {title: '导出会话',requirePassword: true,confirmText: '导出',- hint: '将加密导出 ' + ids.length + ' 个会话及其本地消息附件。',+ hint: '导出会话会在后台完成,文件保存到下载目录。',onConfirm: function (password) { return api('/api/sessions/export', {- responseType: 'blob',method: 'POST',headers: { 'content-type': 'application/json' },- body: JSON.stringify({ ids: ids, password: password }),+ body: JSON.stringify({ ids: ids, password: password, background: true }),}).then(function (result) {- downloadTransfer(result, 'WorkDaddy-sessions-' + new Date().toISOString().slice(0, 10) + '.wds');- toast('已导出 ' + result.count + ' 个会话(已加密)', false, root);+ sessionsState.exportReadSerial = (sessionsState.exportReadSerial || 0) + 1;+ renderSessionExport(result.job);+ pollSessionExport(result.job.id);}); },});});@@ -8943,21 +9540,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {};}- // ===== 主题 pane(构建:主题选择 + 头像 + WorkDaddy 壁纸)=====+ // ===== 主题 pane(构建:头像 + 悬浮机器人 + 主题选择 + WorkDaddy 壁纸)=====function buildThemePane() {if (!themePane) return;themePane.dataset.built = '1';themePane.innerHTML =- '<div class="wbs-pcard">' +- '<div class="wbs-pcard-title">主题外观</div>' +- '<div class="wbs-theme-seg" id="wbs-theme-seg">' +- '<button class="wbs-theme-opt active" type="button" data-wbs-theme-option="default">浅色</button>' +- '<button class="wbs-theme-opt" type="button" data-wbs-theme-option="dark">深色</button>' +- '<button class="wbs-theme-opt" type="button" data-wbs-theme-option="eye-care">护眼绿</button>' +- '<button class="wbs-theme-opt" type="button" data-wbs-theme-option="cyber-purple">赛博紫</button>' +- '<button class="wbs-theme-opt" type="button" data-wbs-theme-option="nebula">毛玻璃</button>' +- '</div>' +- '</div>' +'<div class="wbs-pcard wbs-avatar-card">' +'<div class="wbs-pcard-title">头像</div>' +'<div class="wbs-avatar-row">' +@@ -8972,6 +9559,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-pcard wbs-fab-settings">' +'<div class="wbs-pcard-title">悬浮机器人</div>' +'<div class="wbs-theme-seg wbs-robot-seg" role="radiogroup" aria-label="机器人外观">' ++ '<label class="wbs-theme-opt wbs-robot-option" title="跟随发送按钮的主题色"><input type="radio" name="wbs-robot-style" value="theme"><span>主题色</span></label>' +'<label class="wbs-theme-opt wbs-robot-option" title="白底黑眼"><input type="radio" name="wbs-robot-style" value="white"><span>白色</span></label>' +'<label class="wbs-theme-opt wbs-robot-option" title="黑底白眼"><input type="radio" name="wbs-robot-style" value="black"><span>黑色</span></label>' +'<label class="wbs-theme-opt wbs-robot-option" title="毛玻璃底与镂空眼睛"><input type="radio" name="wbs-robot-style" value="glass"><span>毛玻璃</span></label>' +@@ -8980,7 +9568,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<label class="wbs-ask-label" for="wbs-fab-auto-dock">自动贴边<span class="wbs-ask-hint">闲置 5 秒后收起,鼠标靠近即展开</span></label>' +'<label class="wbs-switch"><input type="checkbox" id="wbs-fab-auto-dock"><span class="wbs-switch-slider"></span></label>' +'</div></div>' +- '<div class="wbs-pcard wbs-wallpaper-card" id="wbs-wallpaper-card" style="display:none">' ++ '<div class="wbs-pcard">' ++ '<div class="wbs-theme-takeover-row">' ++ '<div class="wbs-pcard-title">毛玻璃主题</div>' ++ '<label class="wbs-switch"><input type="checkbox" id="wbs-theme-takeover" checked><span class="wbs-switch-slider"></span></label></div>' ++ '</div>' ++ '<div class="wbs-pcard wbs-wallpaper-card wbs-theme-managed" id="wbs-wallpaper-card" style="display:none">' +'<div class="wbs-pcard-title">壁纸</div>' +'<div class="wbs-bg-source">' +'<button class="wbs-bg-src active" type="button" data-src="official">' + WBS_BRAND + ' 壁纸</button>' +@@ -9005,7 +9598,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<span class="wbs-mask-val" id="wbs-bg-blur-val">0%</span>' +'</div>' +'</div>' +- '<div class="wbs-pcard" id="wbs-text-shadow-card" style="display:none">' ++ '<div class="wbs-pcard wbs-theme-managed" id="wbs-text-shadow-card" style="display:none">' +'<div class="wbs-ask-row">' +'<label class="wbs-ask-label" for="wbs-text-shadow">消息文字阴影<span class="wbs-ask-hint">增强壁纸上的消息文字辨识度</span></label>' +'<label class="wbs-switch"><input type="checkbox" id="wbs-text-shadow" checked disabled><span class="wbs-switch-slider"></span></label>' +@@ -9618,15 +10211,36 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!themePane) return;var card = themePane.querySelector('#wbs-wallpaper-card');if (!card) return;- var visible = themeId === 'nebula';+ // 主题页固定使用毛玻璃;开关只控制这组玻璃主题设置是否可见。+ var visible = sessState.themeTakeover;card.style.display = visible ? '' : 'none';var textCard = themePane.querySelector('#wbs-text-shadow-card');if (textCard) textCard.style.display = visible ? '' : 'none';if (visible) loadWallpapers();}+ // 关闭接管后只隐藏主题外观选项;头像和悬浮机器人独立于主题接管。+ function syncThemeTakeoverVisibility(enabled) {+ var visible = enabled !== false;+ if (themePane) {+ themePane.querySelectorAll('.wbs-theme-managed').forEach(function (node) {+ node.style.display = visible ? '' : 'none';+ });+ }+ }+// 主题 pane 事件绑定(元素在 buildThemePane 之后才存在,延迟到首次切换时绑定)function wireThemePane() {+ var themeSwitch = themePane.querySelector('#wbs-theme-takeover');+ if (themeSwitch) {+ themeSwitch.checked = sessState.themeTakeover;+ if (!themeSwitch.dataset.wbsWired) {+ themeSwitch.dataset.wbsWired = '1';+ themeSwitch.addEventListener('change', function () { setSessionSwitchWire('themeTakeoverEnabled', this); });+ }+ syncThemeTakeoverVisibility(sessState.themeTakeover);+ syncSessionModule();+ }themePane.querySelectorAll('input[name="wbs-robot-style"]').forEach(function (input) {input.checked = input.value === fabAppearance.get();input.closest('.wbs-theme-opt').classList.toggle('active', input.checked);@@ -9658,26 +10272,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {dockSwitch.checked = fabQuietMode.isEnabled();dockSwitch.addEventListener('change', function () { fabQuietMode.setEnabled(this.checked); });}- // 主题选择:segmented 按钮直接切换+ // 主题页只提供毛玻璃主题开关;壁纸仍通过下方来源按钮管理。themePane.addEventListener('click', function (e) {var t = e.target;- var segBtn = t.closest ? t.closest('#wbs-theme-seg .wbs-theme-opt') : null;- if (segBtn) {- var id = segBtn.getAttribute('data-wbs-theme-option');- // 不做 active 拦截:即使当前已是该主题也强制重新应用(保证「切换到默认主题=强制浅色 / 切换到 WorkDaddy 主题=强制深色」始终生效,面板状态与真实主题不一致时也能纠正)- var previous = themePane.querySelector('#wbs-theme-seg .wbs-theme-opt.active');- themePane.querySelectorAll('#wbs-theme-seg .wbs-theme-opt').forEach(function (b) { b.classList.toggle('active', b === segBtn); });- syncWallpaperCardVisibility(id);- applyTheme(id).then(function () {- var names = { 'default': '浅色', 'dark': '深色', 'nebula': WBS_BRAND + ' 主题', 'eye-care': '护眼绿', 'cyber-purple': '赛博紫' };- toast('已应用主题「' + (names[id] || id) + '」', false, root);- }).catch(function (er) {- themePane.querySelectorAll('#wbs-theme-seg .wbs-theme-opt').forEach(function (b) { b.classList.toggle('active', b === previous); });- syncWallpaperCardVisibility(previous ? previous.getAttribute('data-wbs-theme-option') : 'default');- toast('应用主题失败: ' + (er.message || er), true, root);- });- return;- }var srcBtn = t.closest ? t.closest('.wbs-bg-src') : null;if (srcBtn) {themePane.querySelectorAll('.wbs-bg-src').forEach(function (b) { b.classList.toggle('active', b === srcBtn); });@@ -9864,7 +10461,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (grid && grid.dataset.loaded && !force) return;if (grid) grid.dataset.loaded = '1';var base = API.replace(/\/api\/?$/, '');- api('/api/wallpapers').then(function (d) {+ var wallpaperRequest = api('/api/wallpapers');+ var wallpaperTimeout = new Promise(function (_, reject) {+ setTimeout(function () { reject(new Error('壁纸请求超时')); }, 8000);+ });+ Promise.race([wallpaperRequest, wallpaperTimeout]).then(function (d) {var list = d.wallpapers || [];var customList = d.customWallpapers || [];var current = d.currentWallpaper || null;@@ -9955,6 +10556,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});}}).catch(function () {+ if (grid) grid.dataset.loaded = '';if (grid) grid.innerHTML = '<div class="wbs-wp-loading">壁纸加载失败(daemon 不可达)</div>';if (cgrid) cgrid.innerHTML = '<div class="wbs-wp-loading">壁纸加载失败(daemon 不可达)</div>';});@@ -9981,6 +10583,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {sortAccountsByCreditExpiry();reorderAccountCards();}+ if (!open && typeof closeAccountNotePopover === 'function') closeAccountNotePopover();state.open = open;panel.classList.toggle('show', open);fab.classList.toggle('hidden', open); // 打开时隐藏按钮@@ -10277,14 +10880,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function loadThemes() {api('/api/themes').then(function (d) {- var seg = root.querySelector('.wbs-theme-seg');- if (!seg) return;- var cur = d.current && ALLOWED_THEMES.indexOf(d.current) >= 0 ? d.current : 'default';- seg.querySelectorAll('.wbs-theme-opt').forEach(function (b) {- b.classList.toggle('active', b.getAttribute('data-wbs-theme-option') === cur);- });- syncWallpaperCardVisibility(cur);- // 列表展示不能更改已保存的主题;主题只能由用户明确选择。+ syncWallpaperCardVisibility('nebula');}).catch(function () {});}@@ -10297,7 +10893,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}// 当前主题 id(壁纸切换目标):segmented 激活项;无则 nebulafunction themeSelectValue() {- var seg = root.querySelector('.wbs-theme-seg');+ var seg = root.querySelector('#wbs-theme-seg');var act = seg ? seg.querySelector('.wbs-theme-opt.active') : null;var id = act ? act.getAttribute('data-wbs-theme-option') : null;return id && id !== 'default' && id !== 'dark' ? id : 'nebula';@@ -10902,6 +11498,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {baselineAssistantKey: '', // 当前会话「切换后/开启后」最后一条已有助手消息的稳定 key(baseline,绝不判定)awaitingNewReply: false, // 是否仍在等待新回复:为 true 时 baseline 消息的 feedback/文本变化/重排均不解除判定,不安排 settle};+ // sessionStore 在 terminal 状态落地后会清空 error。短暂保留结构化白名单,+ // 让同一轮 subscriber 回调仍能识别 6004/14018,而不保存原始错误正文。+ var acErrorSnapshots = Object.create(null);+ var acRateLimitRecorded = Object.create(null);+ var acCurrentUidPromise = null;var acRunning = false;var acStatusTimer = null;var acMonitorRegistry = createSessionMonitorRegistry({ maxLogs: 180 });@@ -11060,6 +11661,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {/* 监控状态常驻展示:开关开启期间卡片标题右侧固定显示「监控激活会话中」 */var acStatusVisible = false;+ var acLimitToastSeen = Object.create(null);function acShowStatus() {acStatusVisible = true;if (acStatusTimer) { clearTimeout(acStatusTimer); acStatusTimer = null; } // 清掉弱提示残留定时@@ -11088,6 +11690,26 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}, 4000);}+ function acNotifyLimit(snapshot) {+ if (!snapshot || (!snapshot.rateLimited && !snapshot.quotaExhausted)) return;+ var reason = snapshot.rateLimited ? 'model-rate-limited' : 'quota-exhausted';+ var key = [snapshot.conversationId || '', snapshot.assistantId || '', reason, snapshot.errorResetAt || ''].join('|');+ if (acLimitToastSeen[key]) return;+ acLimitToastSeen[key] = true;+ var message = wbsTranslateString(+ snapshot.rateLimited ? '当前模型已触发频率限制,已停止自动发送' : '当前账号积分已耗尽',+ WBS_LANGUAGE+ );+ if (snapshot.rateLimited) {+ var model = String(snapshot.errorModelName || snapshot.errorRequestModelId || '').trim();+ if (model) message += ',' + wbsTranslateString('模型:', WBS_LANGUAGE) + model;+ if (snapshot.errorResetAt) {+ message += ',' + wbsTranslateString('预计解封:', WBS_LANGUAGE) + fmtDateTime(snapshot.errorResetAt);+ }+ }+ toast(message, true, root);+ }+/** 取正文块:内容容器直接子块中排除 widget/推理/元信息折叠,优先最后一段文本内容块(_assistantTextContent/markdown) */function acPickBodyBlock(contentEl) {if (!contentEl || !contentEl.children || !contentEl.children.length) return contentEl;@@ -11507,11 +12129,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var cur = el[key], seen = 0;while (cur && seen++ < 650) {var props = cur.memoizedProps;- var controller = props && props.value;- if (controller && controller.conversationId && controller.messageStore && controller.sessionStore &&- typeof controller.getSessionViewState === 'function' && typeof controller.getMessagesViewState === 'function') {- if (!fallback) fallback = controller;- if (!activeId || String(controller.conversationId) === String(activeId)) return controller;+ // WorkBuddy classic stores the controller in props.value, while+ // the AI/new-teams renderer exposes the same capability-shaped+ // object as props.controller or props.adapter. Inspect all three+ // so the structured error monitor is actually started in both+ // clients; this does not depend on composer button state.+ var candidates = props && [props.value, props.controller, props.adapter];+ for (var candi = 0; candidates && candi < candidates.length; candi++) {+ var controller = candidates[candi];+ if (controller && controller.conversationId && controller.messageStore && controller.sessionStore &&+ typeof controller.messageStore.getState === 'function' &&+ typeof controller.sessionStore.getState === 'function' &&+ typeof controller.getSessionViewState === 'function') {+ if (!fallback) fallback = controller;+ if (!activeId || String(controller.conversationId) === String(activeId)) return controller;+ }}cur = cur.return;}@@ -11526,6 +12158,47 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {} catch (e) { return null; }}+ function acCaptureControllerError(controller) {+ if (!controller || !controller.conversationId || !controller.sessionStore || typeof controller.sessionStore.getState !== 'function') return null;+ try {+ var state = controller.sessionStore.getState() || {};+ var normalized = normalizeAutoContinueError(state.error || state.warning);+ if (!normalized) return null;+ var key = String(controller.conversationId);+ var messageState = controller.messageStore && controller.messageStore.getState ? controller.messageStore.getState() : {};+ var latest = selectAutoContinueAssistant(messageState);+ acErrorSnapshots[key] = { error: normalized, assistantId: latest && String(latest.id || latest.requestId || '') };+ return normalized;+ } catch (_) { return null; }+ }++ function acRecordModelRateLimit(snapshot) {+ if (!snapshot || !snapshot.rateLimited) return;+ var modelId = String(snapshot.errorRequestModelId || 'unknown-model').slice(0, 160);+ var code = Number(snapshot.errorCode);+ var signature = [snapshot.conversationId, snapshot.assistantId, modelId, code, snapshot.errorResetAt || ''].join('|');+ if (acRateLimitRecorded[signature]) return;+ acRateLimitRecorded[signature] = true;+ if (!acCurrentUidPromise) acCurrentUidPromise = api('/api/current').then(function (current) { return String(current && current.uid || '').trim(); }).catch(function () { return ''; });+ acCurrentUidPromise.then(function (uid) {+ if (!uid) return;+ return api('/api/model-rate-limit', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ uid: uid,+ modelId: modelId,+ modelName: snapshot.errorModelName || modelId,+ resetAt: snapshot.errorResetAt || null,+ reasonCode: Number.isSafeInteger(code) ? code : 6004,+ source: 'renderer-error',+ }),+ }).then(function () {+ try { window.dispatchEvent(new Event('workdaddy:accounts-updated')); } catch (_) {}+ }).catch(function () {});+ });+ }+function acControllerSnapshot(controller) {if (!controller) return null;try {@@ -11536,9 +12209,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var sessionState = controller.sessionStore.getState();var error = sessionState && sessionState.error;var warning = sessionState && sessionState.warning;- var errText = [error && error.code, error && error.message, warning && warning.code, warning && warning.message].filter(Boolean).join(' ');+ var liveError = normalizeAutoContinueError(error || warning);+ if (liveError) acErrorSnapshots[String(controller.conversationId)] = { error: liveError, assistantId: assistant && String(assistant.id || assistant.requestId || '') };+ var rememberedRecord = acErrorSnapshots[String(controller.conversationId)] || null;+ var currentAssistantId = assistant && String(assistant.id || assistant.requestId || '');+ var rememberedError = rememberedRecord && (!rememberedRecord.assistantId || !currentAssistantId || rememberedRecord.assistantId === currentAssistantId)+ ? rememberedRecord.error : null;+ if (rememberedRecord && currentAssistantId && rememberedRecord.assistantId && rememberedRecord.assistantId !== currentAssistantId) delete acErrorSnapshots[String(controller.conversationId)];+ var normalizedError = liveError || rememberedError;+ var errText = [error && error.code, warning && warning.code].filter(Boolean).join(' ');var text = autoContinueMessageText(assistant);var extra = assistant && assistant.extra || {};+ var modelId = String((extra && (extra.modelId || extra.model)) || (assistant && (assistant.modelId || assistant.model)) || (session && (session.model || session.modelId)) || '').slice(0, 160);return {conversationId: String(controller.conversationId || ''),version: Number(messageState.version || 0),@@ -11550,8 +12232,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {terminalKnown: Object.prototype.hasOwnProperty.call(extra, 'isRequestTerminal'),terminal: !!(assistant && extra.isRequestTerminal === true),manualStop: !!extra.isCancelled,- error: !!error || !!(errorView && (errorView.error || errorView.hasError)),+ error: !!error || !!(errorView && (errorView.error || errorView.hasError)) || !!normalizedError,networkFailure: /network|offline|timeout|connection|网络|离线|超时|连接/i.test(errText),+ errorCode: normalizedError && normalizedError.code,+ errorStatusCode: normalizedError && normalizedError.statusCode,+ errorRequestModelId: normalizedError && normalizedError.requestModelId || modelId,+ errorModelName: modelId,+ errorResetAt: normalizedError && normalizedError.resetAt,+ quotaExhausted: !!(normalizedError && normalizedError.quotaExhausted),+ rateLimited: !!(normalizedError && normalizedError.rateLimited),+ authFailure: !!(normalizedError && normalizedError.authFailure),+ nonRetryableError: !!(normalizedError && normalizedError.nonRetryable),+ serviceErrorFallback: !!(extra && extra.isServiceErrorFallback),blocked: !!(session && (session.isPending || session.state === 'pending')),busy: !!(session && (session.isBusy || session.isRunActive || session.isTurnActive || session.isSending || session.isPending)) ||!!messageState.streamingRequestId || !!messageState.streamingMessageId,@@ -11602,6 +12294,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {acLogR('controller-blocked', 'controller-blocked', { id: snap.assistantId, state: snap.state }, 3000);return;}+ acRecordModelRateLimit(snap);+ acNotifyLimit(snap);if (c.awaitingNewReply) {if (!snap.assistantId || snap.assistantId === c.baselineAssistantKey) return;c.awaitingNewReply = false;@@ -11658,7 +12352,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {c.controllerUnsubs = [];var notify = function () {if (!acRunning || controller !== acCtx.controller) return;- try { acControllerCheck(); } catch (e) {}+ try { acCaptureControllerError(controller); acControllerCheck(); } catch (e) {}};try { c.controllerUnsubs.push(controller.sessionStore.subscribe(notify)); } catch (e) {}try { c.controllerUnsubs.push(controller.messageStore.subscribe(notify)); } catch (e) {}@@ -12206,6 +12900,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}var snapshot = acControllerSnapshot(session.controller);if (!snapshot || !snapshot.conversationId) return;+ acRecordModelRateLimit(snapshot);+ acNotifyLimit(snapshot);session.lastSeen = Date.now();session.title = session.title || acSessionTitle(session.controller);acMonitorRegistry.ensure(session.id, { title: session.title });@@ -12336,7 +13032,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {session.baselineAssistantKey = initialSnapshot.assistantId || '';}}- var notify = function () { acMultiCheckSession(session); };+ var notify = function () { acCaptureControllerError(controller); acMultiCheckSession(session); };try { if (controller.sessionStore && typeof controller.sessionStore.subscribe === 'function') session.unsubs.push(controller.sessionStore.subscribe(notify)); } catch (_) {}try { if (controller.messageStore && typeof controller.messageStore.subscribe === 'function') session.unsubs.push(controller.messageStore.subscribe(notify)); } catch (_) {}if (initialSnapshot && (isSessionMonitorInProgress(initialSnapshot) || isSessionMonitorInterrupted(initialSnapshot) || !session.resourceActive)) acMultiCheckSession(session);@@ -13035,7 +13731,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {registerDisposer(function () {closeRotationNotice();acRunning = false;- if (acThemeObserver) { try { acThemeObserver.disconnect(); } catch (e) {} acThemeObserver = null; }acStopMonitor();stopNoDisturbAutoApprove();stopUntilDoneCheck();@@ -13424,6 +14119,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());}+ function fmtDateTimeSeconds(ts) {+ if (!ts) return '-';+ var d = new Date(ts);+ var p = function (n) { return String(n).padStart(2, '0'); };+ return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds());+ }+function fmtCredits(value) {if (value === null || value === undefined || value === '') return '-';var n = Number(value);@@ -13497,6 +14199,66 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return tag ? '<span class="wbs-checkin-slot">' + tag + '</span>' : '';}+ function modelRateLimitTip(record) {+ var name = String(record && (record.modelName || record.modelId) || '未知模型');+ var reset = record && record.resetAt ? Number(record.resetAt) : 0;+ var line = reset && isFinite(reset)+ ? wbsTranslateString('预计解封:', WBS_LANGUAGE) + fmtDateTimeSeconds(reset) + '(' + wbsTranslateString(fmtCreditExpiry(reset), WBS_LANGUAGE) + ')'+ : wbsTranslateString('预计解封:时间未知', WBS_LANGUAGE);+ return name + '\n' + line;+ }++ function modelRateLimitBadgeHtml(a) {+ var records = a && Array.isArray(a.modelRateLimits) ? a.modelRateLimits.filter(function (record) {+ return record && record.modelId;+ }) : [];+ if (!records.length) return '';+ var details = records.map(modelRateLimitTip).join('\n\n');+ var label = records.length === 1 ? wbsTranslateString('模型限流', WBS_LANGUAGE) : wbsTranslateString('模型限流·', WBS_LANGUAGE) + records.length;+ var attr = esc(details).replace(/"/g, '"');+ var uid = escAttr(a && a.uid || '');+ return '<span class="wbs-model-rate-limit-slot"><button type="button" class="wbs-model-rate-limit wbs-ck wbs-checkin-tag ok" data-uid="' + uid + '" aria-label="' + attr + '" aria-controls="wbs-status-popover" aria-expanded="false">' + esc(label) + '</button></span>';+ }++ function modelRateLimitPopoverHtml(account) {+ var records = account && Array.isArray(account.modelRateLimits) ? account.modelRateLimits.filter(function (record) {+ return record && record.modelId;+ }) : [];+ var rows = records.map(function (record) {+ var name = String(record.modelName || record.modelId || '未知模型');+ var reset = record.resetAt ? Number(record.resetAt) : 0;+ var resetText = reset && isFinite(reset) ? fmtDateTimeSeconds(reset) : wbsTranslateString('时间未知', WBS_LANGUAGE);+ var remaining = reset && isFinite(reset) ? '(' + wbsTranslateString(fmtCreditExpiry(reset), WBS_LANGUAGE) + ')' : '';+ return '<div class="wbs-daily-detail wbs-model-rate-limit-detail"><i class="rate-limit"></i>' ++ '<span>' + wbsTranslateString('模型限流', WBS_LANGUAGE) + '</span><b class="wbs-model-rate-limit-model">' + esc(name) + '</b>' ++ '<span>' + wbsTranslateString('预计解封', WBS_LANGUAGE) + '</span><b class="wbs-model-rate-limit-reset">' + esc(resetText + remaining) + '</b></div>';+ }).join('');+ return '<div class="wbs-daily-popover-head"><strong>' + wbsTranslateString('模型频率限制', WBS_LANGUAGE) + '</strong><span>' + wbsTranslateString('账号状态', WBS_LANGUAGE) + '</span></div>' ++ (rows || '<div class="wbs-daily-popover-empty">' + wbsTranslateString('当前没有有效的模型限流记录', WBS_LANGUAGE) + '</div>');+ }++ function modelRateLimitSummaryPopoverHtml(accounts) {+ var groups = [];+ (Array.isArray(accounts) ? accounts : []).forEach(function (account) {+ var records = account && Array.isArray(account.modelRateLimits) ? account.modelRateLimits.filter(function (record) {+ return record && record.modelId;+ }) : [];+ if (!records.length) return;+ var rawAccountName = String(account.nickname || account.phone || account.uin || account.uid || '未命名账号');+ var accountName = state.mask ? maskAccountName(rawAccountName) : rawAccountName;+ var rows = records.map(function (record) {+ var name = String(record.modelName || record.modelId || '未知模型');+ var reset = record.resetAt ? Number(record.resetAt) : 0;+ var resetText = reset && isFinite(reset) ? fmtDateTimeSeconds(reset) : wbsTranslateString('时间未知', WBS_LANGUAGE);+ var remaining = reset && isFinite(reset) ? '(' + wbsTranslateString(fmtCreditExpiry(reset), WBS_LANGUAGE) + ')' : '';+ return '<div class="wbs-model-rate-limit-summary-row"><b class="wbs-model-rate-limit-model">' + esc(name) + '</b><span class="wbs-model-rate-limit-reset-label">' + wbsTranslateString('预计解封', WBS_LANGUAGE) + '</span><b class="wbs-model-rate-limit-reset">' + esc(resetText + remaining) + '</b></div>';+ }).join('');+ groups.push('<section class="wbs-model-rate-limit-account-group"><div class="wbs-model-rate-limit-account-head"><strong>' + esc(accountName) + '</strong><span>' + records.length + wbsTranslateString(' 个模型', WBS_LANGUAGE) + '</span></div>' + rows + '</section>');+ });+ return '<div class="wbs-daily-popover-head"><strong>' + wbsTranslateString('模型频率限制', WBS_LANGUAGE) + '</strong><span>' + wbsTranslateString('{n} 个账号', WBS_LANGUAGE).replace('{n}', groups.length) + '</span></div>' ++ (groups.join('') || '<div class="wbs-daily-popover-empty">' + wbsTranslateString('当前没有有效的模型限流记录', WBS_LANGUAGE) + '</div>');+ }+function creditBlockHtml(credits, segments, account) {// 登录身份过期:展示可诊断文案(token 被服务端拒绝时不伪造积分,也不整格隐藏)if (isIdentityExpired(account) || (account && account.creditExpired)) {@@ -14382,6 +15144,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}state.accountLayoutKey = layoutKey;if (!list) { list = el('div', 'wbs-acct-list'); accountsPane.insertBefore(list, accountsPane.firstChild); }+ if (typeof closeAccountNotePopover === 'function') closeAccountNotePopover();list.innerHTML = '';if (!state.accounts.length) {list.appendChild(el('div', 'wbs-empty', '还没有备份账号。打开/登录一次 WorkBuddy 后会自动备份,稍后再来查看。'));@@ -14397,6 +15160,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var editionBadge = a.type === 'personal' ? '个人版' : (a.enterpriseName ? a.enterpriseName : (a.type ? '企业' : ''));var badge = editionBadge ? '<span class="wbs-badge">' + esc(editionBadge) + '</span>' : '';var checkinBadge = checkinBadgeHtml(a);+ var modelRateLimitBadge = typeof modelRateLimitBadgeHtml === 'function' ? modelRateLimitBadgeHtml(a) : '';var invalidAuthBadge = a.authValid === false ? '<span class="wbs-badge wbs-auth-invalid">认证数据无效</span>' : '';// 当前登录账号隐藏操作;认证已过期的账号保留删除,但隐藏切换,避免进入登录页。var expired = isIdentityExpired(a);@@ -14415,7 +15179,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var idVal = state.mask ? maskAccountId(rawId) : rawId;card.innerHTML ='<div class="wbs-info">' +- '<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + esc(nameVal) + '</span>' + badge + dailyRingsHtml(a) + checkinBadge + invalidAuthBadge + '</div>' + ops + '</div>' ++ '<div class="wbs-row1"><div class="wbs-name-group"><button type="button" class="wbs-account-name" data-uid="' + escAttr(a.uid) + '" aria-label="查看或编辑账号备注" aria-haspopup="dialog" aria-controls="wbs-account-note-popover" aria-expanded="false"><span class="wbs-name">' + esc(nameVal) + '</span><span class="wbs-account-name-edit" aria-hidden="true">' + MODEL_EDIT_SVG + '</span></button>' + badge + dailyRingsHtml(a) + checkinBadge + modelRateLimitBadge + invalidAuthBadge + '</div>' + ops + '</div>' +'<div class="wbs-meta wbs-secondary-row">' +'<div class="wbs-mi wbs-phone-cell' + (isUinMode ? ' wbs-uin-cell' : '') + '"><span class="wbs-lbl">' + idLbl + '</span><span class="wbs-val">' + esc(idVal) + '</span></div>' +'<div class="wbs-mi wbs-token-cell"><span class="wbs-lbl">有效期至</span><span class="wbs-val' + (ts.warn ? ' wbs-warn' : '') + '">' + esc(ts.label) + '</span></div>' +@@ -14797,6 +15561,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {state.accounts[j].activityStreak = a.activityStreak;}if (Object.prototype.hasOwnProperty.call(a, 'todayUsage')) state.accounts[j].todayUsage = a.todayUsage;+ state.accounts[j].modelRateLimits = Array.isArray(a.modelRateLimits) ? a.modelRateLimits : [];byUid[a.uid] = state.accounts[j];break;}@@ -14818,6 +15583,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {} else if (checkinBadge && nameGroup) {nameGroup.insertAdjacentHTML('beforeend', checkinBadge);}+ var modelLimitSlot = nameGroup && nameGroup.querySelector('.wbs-model-rate-limit-slot');+ var modelLimitBadge = typeof modelRateLimitBadgeHtml === 'function' ? modelRateLimitBadgeHtml(account) : '';+ if (modelLimitSlot) {+ if (modelLimitBadge) modelLimitSlot.outerHTML = modelLimitBadge;+ else modelLimitSlot.remove();+ } else if (modelLimitBadge && nameGroup) {+ nameGroup.insertAdjacentHTML('beforeend', modelLimitBadge);+ }if (cell) {var hidden = isIdentityExpired(account);// 不再整格隐藏/清空:过期时由 creditBlockHtml 展示「登录身份过期」诊断文案@@ -15210,8 +15983,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {try { syncSessionModule(); } catch (e) {}// 打开面板时校验指令块是否丢失,丢失则自动关闭开关(不弹 toast)try { acCheckPromptOnOpen(); } catch (e) {}- // 按钮主题色(浅色黑底白图 / 深色白底黑图)+ 监听主题切换- try { applyThemeButtonColors(); watchThemeForButtons(); } catch (e) {}+ // 按钮背景和图标始终跟随发送按钮的主题变量+ try { applyThemeButtonColors(); } catch (e) {}return { destroy: lifecycle.destroy, alive: lifecycle.alive };}@@ -15261,7 +16034,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {css.textContent = ['.wbs-root{position:fixed;right:22px;bottom:22px;z-index:2147483647;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;font-size:13px;color:#1f1f1f;-webkit-font-smoothing:antialiased}','.wbs-root,.wbs-status-popover,.wbs-credit-summary-popover,#wbs-token-stats-modal{--wbs-primary:#22c55e;--wbs-primary-rgb:34,197,94;--wbs-primary-ink:#22c55e;--wbs-primary-soft:rgba(34,197,94,.09);--wbs-primary-soft-hover:rgba(34,197,94,.14)}',- 'html[data-wbs-theme-id="dark"] .wbs-root,html[data-wbs-theme-id="dark"] .wbs-status-popover,html[data-wbs-theme-id="dark"] .wbs-credit-summary-popover,html[data-wbs-theme-id="dark"] #wbs-token-stats-modal,html[data-wbs-theme-id="cyber-purple"] .wbs-root,html[data-wbs-theme-id="cyber-purple"] .wbs-status-popover,html[data-wbs-theme-id="cyber-purple"] .wbs-credit-summary-popover,html[data-wbs-theme-id="cyber-purple"] #wbs-token-stats-modal,html[data-wbs-theme-id="nebula"] .wbs-root,html[data-wbs-theme-id="nebula"] .wbs-status-popover,html[data-wbs-theme-id="nebula"] .wbs-credit-summary-popover,html[data-wbs-theme-id="nebula"] #wbs-token-stats-modal{--wbs-primary:#7f77dd;--wbs-primary-rgb:127,119,221;--wbs-primary-ink:#7f77dd;--wbs-primary-soft:rgba(127,119,221,.12);--wbs-primary-soft-hover:rgba(127,119,221,.18)}',+ 'html[data-wbs-theme-id="dark"] .wbs-root,html[data-wbs-theme-id="dark"] .wbs-status-popover,html[data-wbs-theme-id="dark"] .wbs-credit-summary-popover,html[data-wbs-theme-id="dark"] #wbs-token-stats-modal,html[data-wbs-theme-id="cyber-purple"] .wbs-root,html[data-wbs-theme-id="cyber-purple"] .wbs-status-popover,html[data-wbs-theme-id="cyber-purple"] .wbs-credit-summary-popover,html[data-wbs-theme-id="cyber-purple"] #wbs-token-stats-modal,html[data-wbs-theme-id="nebula"] .wbs-root,html[data-wbs-theme-id="nebula"] .wbs-status-popover,html[data-wbs-theme-id="nebula"] .wbs-credit-summary-popover,html[data-wbs-theme-id="nebula"] #wbs-token-stats-modal,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) .wbs-root,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) .wbs-status-popover,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) .wbs-credit-summary-popover,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) #wbs-token-stats-modal{--wbs-primary:#7f77dd;--wbs-primary-rgb:127,119,221;--wbs-primary-ink:#7f77dd;--wbs-primary-soft:rgba(127,119,221,.12);--wbs-primary-soft-hover:rgba(127,119,221,.18)}','.wbs-session-usage-summary{position:fixed;z-index:20;display:flex;align-items:center;justify-content:flex-start;gap:10px;box-sizing:border-box;min-height:37px;padding:3px 0 2px;border:0;border-radius:0;background:transparent;color:var(--wb-color-text-primary,#1f1f1f);font-size:14px;font-weight:400;line-height:18px;outline:none;cursor:pointer}','.wbs-session-usage-summary:hover,.wbs-session-usage-summary:focus-visible{background:transparent}','.wbs-session-usage-summary.is-hidden{visibility:hidden;opacity:0;pointer-events:none}',@@ -15302,7 +16075,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'html.cb-dark .wbs-session-usage-popover,html[data-theme="dark"] .wbs-session-usage-popover,body[data-vscode-theme-name*="dark" i] .wbs-session-usage-popover{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 92%,transparent);color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 8px 22px rgba(0,0,0,.32)}','html[data-wbs-theme-id="nebula"] .wbs-session-usage-copy:hover,html[data-wbs-theme-id="nebula"] .wbs-session-usage-copy:focus-visible{background:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 88%,transparent);color:var(--wb-color-text-primary,#e8e5ff);box-shadow:0 3px 12px rgba(0,0,0,.32);backdrop-filter:blur(12px) saturate(1.12);-webkit-backdrop-filter:blur(12px) saturate(1.12)}','@media(max-width:620px){.wbs-session-usage-summary{padding-left:0;padding-right:0}.wbs-session-usage-main{gap:9px}.wbs-session-usage-popover{width:calc(100vw - 16px)}}',- '.wbs-daily-rings,.wbs-status-popover{--wbs-ring-growth:var(--wbs-primary-ink);--wbs-ring-rewards:var(--wbs-primary-ink);--wbs-ring-cat:var(--wbs-primary-ink);--wbs-tip-credit:var(--wbs-primary-ink);--wbs-liquid-fill:var(--wbs-primary);--wbs-liquid-bg:color-mix(in srgb,var(--wbs-primary) 12%,var(--wb-bg-secondary,#f6f7f8));--wbs-liquid-ink:color-mix(in srgb,var(--wbs-primary-ink) 72%,var(--wb-color-text-primary,#1f1f1f))}',+ '.wbs-daily-rings,.wbs-status-popover{--wbs-ring-growth:var(--wb-button-primary-bg);--wbs-ring-rewards:var(--wb-button-primary-bg);--wbs-ring-cat:var(--wb-button-primary-bg);--wbs-tip-credit:var(--wb-button-primary-bg);--wbs-liquid-fill:var(--wb-button-primary-bg);--wbs-liquid-bg:color-mix(in srgb,var(--wb-button-primary-bg) 12%,var(--wb-bg-secondary,#f6f7f8));--wbs-liquid-ink:color-mix(in srgb,var(--wb-button-primary-bg) 72%,var(--wb-color-text-primary,#1f1f1f))}','.wbs-root.wbs-no-stash .wbs-stash-inline{display:none !important}','.wbs-fork-button{display:flex;flex:0 0 24px;align-items:center;justify-content:center;width:24px;height:24px;box-sizing:border-box;padding:0;border:0;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,rgba(0,0,0,.7));cursor:pointer;transition:color .15s ease,background-color .15s ease}','.wbs-fork-button:hover{background:var(--wb-bg-hover,rgba(0,0,0,.06));color:var(--wb-color-text-primary,#1f1f1f)}',@@ -15348,6 +16121,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'html[data-wbs-theme-id="nebula"] .wbs-message-nav-marker:not(:hover):not(:focus-visible){box-shadow:none}','@media (prefers-reduced-motion:reduce){.wbs-message-nav-marker,.wbs-message-nav-dot,.wbs-message-nav-tooltip{transition:none!important}.wbs-message-nav-highlight{animation:none!important}}',/* 官网演示机器人:尺寸按 2 倍绘制,保留现有 0.5 缩放与停靠/拖动坐标。 */+ '.wbs-fab[data-wbs-robot-style="theme"],.wbs-root[data-wbs-robot-style="theme"] .wbs-automation-stop{--wbs-robot-shell:var(--wb-button-primary-bg);--wbs-robot-eye:var(--wb-button-primary-fg);--wbs-robot-rim:var(--wb-border-subtle)}','.wbs-fab[data-wbs-robot-style="black"]{--wbs-robot-shell:#111;--wbs-robot-eye:#fff;--wbs-robot-rim:rgba(255,255,255,.14)}','.wbs-fab[data-wbs-robot-style="glass"]{--wbs-robot-shell:color-mix(in srgb,var(--wb-bg-popover,#fff) 42%,transparent);--wbs-robot-eye:transparent;--wbs-robot-blur:blur(14px) saturate(1.3);--wbs-robot-rim:color-mix(in srgb,var(--wb-color-text-primary,#222) 18%,transparent)}','.wbs-fab[data-wbs-robot-style="white"]{--wbs-robot-shell:#fff;--wbs-robot-eye:#111;--wbs-robot-rim:rgba(255,255,255,.55)}',@@ -15409,6 +16183,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-fab.is-dragging .button{cursor:grabbing}','.wbs-fab.is-snapping{transition:right .56s cubic-bezier(.22,1.35,.36,1),bottom .56s cubic-bezier(.22,1.35,.36,1)}',/* 面板:毛玻璃主题(半透明 + 模糊,背景图透出) */+ // 毛玻璃让官方按钮底色透明;面板内的选中态、开关和操作按钮仍需深色主题的对比色。+ 'html[data-wbs-theme-id="nebula"] .wbs-panel,html[data-wbs-theme-id="nebula"] .wbs-modal,html[data-wbs-theme-id="nebula"] .wbs-account-note-popover,html[data-wbs-theme-id="nebula"] .wbs-status-popover,html[data-wbs-theme-id="nebula"] .wbs-credit-rotation-notice{--wb-button-primary-bg:var(--wb-palette-white-90);--wb-button-primary-fg:var(--wb-bg-primary)}','.wbs-panel{position:absolute;right:0;bottom:0;width:720px;max-width:94vw;height:650px;max-height:calc(100vh - 110px);background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden;backdrop-filter:blur(28px) saturate(1.25);-webkit-backdrop-filter:blur(28px) saturate(1.25)}','.wbs-panel.show{display:flex}',// 英文文案更长:英文面板额外加宽,配合 label 自适应避免挤压@@ -15443,6 +16219,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-row1{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:7px;min-height:26px}','.wbs-name-group{display:flex;align-items:center;flex-wrap:wrap;gap:6px;min-width:0}.wbs-checkin-slot{display:inline-flex;align-items:center;flex-wrap:wrap;gap:5px}','.wbs-name{font-size:14px;font-weight:600;color:var(--wb-color-text-primary,#1f1f1f)}',+ '.wbs-account-name{position:relative;display:inline-flex;align-items:center;min-width:0;max-width:100%;margin:0;padding:0;border:0;background:transparent;font:inherit;text-align:left;cursor:pointer;isolation:isolate}.wbs-account-name .wbs-name{position:relative;z-index:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-account-name:before{content:"";position:absolute;inset:-4px -5px;border:1px solid var(--wb-border-subtle,#e5e7eb);border-radius:7px;background:var(--wb-bg-popover,#fff);box-shadow:0 2px 7px rgba(0,0,0,.08);opacity:0;transition:opacity 200ms ease;pointer-events:none}.wbs-account-name-edit{position:absolute;right:0;top:50%;z-index:2;display:flex;align-items:center;justify-content:center;width:20px;max-width:100%;height:20px;border-radius:3px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#666);opacity:0;transform:translateY(-50%);transition:opacity 200ms ease;pointer-events:none}.wbs-account-name-edit svg{width:13px;height:13px}.wbs-account-name:hover,.wbs-account-name:focus-visible,.wbs-account-name[aria-expanded="true"]{z-index:2}.wbs-account-name:hover:before,.wbs-account-name:focus-visible:before,.wbs-account-name[aria-expanded="true"]:before{opacity:1}.wbs-account-name:hover .wbs-account-name-edit,.wbs-account-name:focus-visible .wbs-account-name-edit,.wbs-account-name[aria-expanded="true"] .wbs-account-name-edit{opacity:1;pointer-events:auto}.wbs-account-name-edit:hover{color:var(--wb-color-text-primary,#1f1f1f)}.wbs-account-name:focus-visible{outline:2px solid var(--wb-accent-primary,var(--wb-color-text-primary,#1f1f1f));outline-offset:4px;border-radius:4px}',+ '.wbs-account-note-popover{position:fixed;z-index:2147483647;box-sizing:border-box;width:280px;max-width:calc(100vw - 16px);max-height:calc(100vh - 16px);overflow:auto;padding:10px;border:1px solid var(--wb-border-subtle,#e5e7eb);border-radius:12px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 94%,transparent);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);box-shadow:0 10px 30px rgba(0,0,0,.16);color:var(--wb-color-text-primary,#1f1f1f);font:12px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overscroll-behavior:contain}.wbs-account-note-popover[hidden]{display:none}.wbs-account-note-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:7px;font-weight:600}.wbs-account-note-head .wbs-icon-btn{width:22px;height:22px}.wbs-account-note-popover textarea{display:block;box-sizing:border-box;width:100%;min-height:86px;max-height:180px;resize:vertical;padding:8px;border:1px solid var(--wb-border-default,#ddd);border-radius:8px;background:var(--wb-bg-secondary,#f7f8fa);color:inherit;font:inherit;line-height:1.6;overflow-wrap:anywhere;user-select:text}.wbs-account-note-popover textarea::placeholder{color:var(--wb-color-text-secondary,#777)}.wbs-account-note-popover textarea:focus-visible,.wbs-account-note-popover button:focus-visible{outline:2px solid var(--wb-accent-primary,var(--wb-color-text-primary,#1f1f1f));outline-offset:2px}.wbs-account-note-footer{display:flex;align-items:center;gap:6px;margin-top:9px}.wbs-account-note-footer [role="status"]{flex:1;min-width:0;overflow-wrap:anywhere;font-size:11px;color:var(--wb-color-text-secondary,#666)}.wbs-account-note-footer .wbs-modal-btn{flex:none;padding:4px 9px;font-size:11px}.wbs-account-note-footer .primary{background:var(--wb-button-primary-bg,#1f1f1f);border-color:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}.wbs-account-note-footer .primary:hover:not(:disabled){background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#333))}.wbs-account-note-footer button:disabled{opacity:.45;cursor:default}',+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-account-note-popover{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 94%,transparent);border-color:var(--wb-border-subtle,#3c3e45);color:var(--wb-color-text-primary,#f2f3f5)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-account-name:before{background:var(--wb-bg-popover,#202126);border-color:var(--wb-border-subtle,#3c3e45)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-account-name-edit{background:var(--wb-bg-popover,#202126)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-account-note-popover textarea{background:var(--wb-bg-secondary,#292b31);border-color:var(--wb-border-default,#454750)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) :is(.wbs-account-note-footer [role="status"],.wbs-account-name-edit){color:var(--wb-color-text-secondary,#b9bdc7)}',+ '@media(prefers-reduced-motion:reduce){.wbs-account-name:before,.wbs-account-name-edit{transition:none}}','.wbs-daily-rings{display:inline-flex;width:auto;height:22px;flex:0 0 auto;box-sizing:border-box;align-items:center;justify-content:center;gap:5px;padding:1px 7px 1px 2px;border:0;border-radius:999px;outline:none;cursor:pointer;transition:background-color .15s,box-shadow .15s,color .15s}','.wbs-daily-rings:hover,.wbs-daily-rings[aria-expanded="true"]{background:var(--wbs-primary-soft-hover);box-shadow:0 2px 8px rgba(var(--wbs-primary-rgb),.13),inset 0 1px 0 rgba(255,255,255,.28)}','.wbs-daily-rings:focus-visible{background:color-mix(in srgb,var(--wb-bg-hover,#eef0f3) 86%,transparent);box-shadow:0 0 0 2px color-mix(in srgb,var(--wbs-liquid-fill) 45%,transparent)}',@@ -15457,7 +16237,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-daily-detail{display:grid;grid-template-columns:8px 72px minmax(0,1fr);align-items:center;gap:7px;min-height:31px;margin-top:5px;padding:0 9px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent)}','.wbs-daily-detail i,.wbs-credit-tip-value i{display:block;width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 2px color-mix(in srgb,currentColor 17%,transparent)}.wbs-daily-detail i.growth{color:var(--wbs-ring-growth)}.wbs-daily-detail i.cat{color:var(--wbs-ring-cat)}.wbs-daily-detail i.credit{color:var(--wbs-tip-credit)}.wbs-daily-detail>span{color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-daily-detail b{min-width:0;text-align:right;font-size:11px;font-weight:650;overflow-wrap:anywhere}.wbs-daily-detail.cat-row b{white-space:nowrap;font-variant-numeric:tabular-nums}.wbs-daily-cat-value{display:flex;min-width:0;align-items:center;justify-content:flex-end;gap:8px}.wbs-travel-claim{flex:0 0 auto}','.wbs-daily-detail i,.wbs-credit-tip-value i{display:block;width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 2px color-mix(in srgb,currentColor 17%,transparent)}.wbs-daily-detail i.growth{color:var(--wbs-ring-growth)}.wbs-daily-detail i.cat{color:var(--wbs-ring-cat)}.wbs-daily-detail i.credit{color:var(--wbs-tip-credit)}.wbs-daily-detail>span{color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-daily-detail b{min-width:0;text-align:right;font-size:11px;font-weight:650;overflow-wrap:anywhere}.wbs-daily-detail.cat-row b{white-space:nowrap;font-variant-numeric:tabular-nums}.wbs-daily-cat-value{display:flex;min-width:0;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:8px}.wbs-daily-cat-value>b{white-space:normal!important}.wbs-travel-claim{flex:0 0 auto}',- '.wbs-growth-task-section{margin:7px 0 9px;padding:9px 10px 7px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 38%,var(--wb-bg-popover,#fff))}.wbs-growth-task-head{display:flex;align-items:center;justify-content:space-between;gap:10px;padding-bottom:5px}.wbs-growth-task-head span{font-size:10.5px;font-weight:650;color:var(--wb-color-text-secondary,#5f6368)}.wbs-growth-task-head em{font-size:10px;font-style:normal;color:var(--wbs-ring-growth);font-variant-numeric:tabular-nums}.wbs-growth-task-list{max-height:360px;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:none}.wbs-growth-task-row{padding:9px 0;border-top:1px solid color-mix(in srgb,var(--wb-border-subtle,rgba(20,24,32,.1)) 72%,transparent);font-size:10.5px}.wbs-growth-task-row:first-child{border-top:0}.wbs-growth-task-title{display:grid;grid-template-columns:6px minmax(0,1fr) 42px 62px;align-items:center;gap:7px;min-height:22px}.wbs-growth-task-title>i{width:6px;height:6px;border-radius:50%;background:var(--wb-border-default,var(--wb-bg-tertiary,#d9dadd))}.wbs-growth-task-row.is-completed .wbs-growth-task-title>i,.wbs-growth-task-row.is-claimed .wbs-growth-task-title>i{background:var(--wbs-ring-growth)}.wbs-growth-task-title>span{min-width:0;color:var(--wb-color-text-primary,#1f1f1f);font-weight:620;line-height:1.4;overflow-wrap:anywhere}.wbs-growth-task-title>em{font-style:normal;text-align:right;color:var(--wb-icon-tertiary,#7c818b);font-variant-numeric:tabular-nums;white-space:nowrap}.wbs-growth-task-state{display:flex;min-width:62px;align-items:center;justify-content:flex-end}.wbs-growth-task-title b{text-align:right;color:var(--wb-color-text-secondary,#5f6368);font-size:10px;font-weight:600;white-space:nowrap}.wbs-growth-task-row.is-completed .wbs-growth-task-title b,.wbs-growth-task-row.is-claimed .wbs-growth-task-title b{color:var(--wbs-ring-growth)}.wbs-growth-task-action{display:inline-flex;min-width:60px;height:22px;box-sizing:border-box;align-items:center;justify-content:center;gap:4px;padding:0 7px;border:1px solid color-mix(in srgb,var(--wbs-ring-growth) 28%,var(--wb-border-subtle,transparent));border-radius:6px;background:var(--wbs-primary-soft);color:var(--wbs-ring-growth);font:600 10px/1 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;white-space:nowrap;cursor:pointer;transition:background-color .16s,border-color .16s,box-shadow .16s}.wbs-growth-task-action:hover:not([disabled]){background:var(--wbs-primary-soft-hover);border-color:color-mix(in srgb,var(--wbs-ring-growth) 42%,var(--wb-border-subtle,transparent))}.wbs-growth-task-action:focus-visible{outline:0;box-shadow:0 0 0 2px color-mix(in srgb,var(--wbs-ring-growth) 34%,transparent)}.wbs-growth-task-action[disabled]{opacity:.72;cursor:default}.wbs-growth-task-action-spinner{width:9px;height:9px;box-sizing:border-box;border:1.5px solid color-mix(in srgb,currentColor 28%,transparent);border-top-color:currentColor;border-radius:50%;animation:wbs-daily-spin .72s linear infinite}.wbs-growth-task-meta{display:flex;align-items:flex-start;gap:16px;margin:5px 0 0 13px;color:var(--wb-color-text-secondary,#5f6368);font-size:10px}.wbs-growth-task-meta>span{display:flex;min-width:0;align-items:flex-start;gap:6px;overflow-wrap:anywhere}.wbs-growth-task-meta>span:last-child{flex:1}.wbs-growth-task-meta label{flex:0 0 auto;color:var(--wb-icon-tertiary,#7c818b);font-size:10px;white-space:nowrap}.wbs-growth-reward-tags{display:flex;min-width:0;flex-wrap:wrap;gap:4px}.wbs-growth-reward-tag{display:inline-flex;align-items:center;min-height:16px;box-sizing:border-box;padding:1px 5px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:999px;background:color-mix(in srgb,var(--wb-bg-tertiary,#f2f3f4) 72%,transparent);color:var(--wb-color-text-secondary,#5f6368);font-size:9px;font-weight:500;line-height:1.2;white-space:nowrap}.wbs-growth-reward-tag.is-empty{color:var(--wb-icon-tertiary,#7c818b)}',+ '.wbs-growth-task-section{margin:7px 0 9px;padding:9px 10px 7px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 38%,var(--wb-bg-popover,#fff))}.wbs-growth-task-head{display:flex;align-items:center;justify-content:space-between;gap:10px;padding-bottom:5px}.wbs-growth-task-head span{font-size:10.5px;font-weight:650;color:var(--wb-color-text-secondary,#5f6368)}.wbs-growth-task-head em{font-size:10px;font-style:normal;color:var(--wbs-ring-growth);font-variant-numeric:tabular-nums}.wbs-growth-task-list{max-height:360px;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:none}.wbs-growth-task-row{padding:9px 0;border-top:1px solid color-mix(in srgb,var(--wb-border-subtle,rgba(20,24,32,.1)) 72%,transparent);font-size:10.5px}.wbs-growth-task-row:first-child{border-top:0}.wbs-growth-task-title{display:grid;grid-template-columns:6px minmax(0,1fr) 42px 62px;align-items:center;gap:7px;min-height:22px}.wbs-growth-task-title>i{width:6px;height:6px;border-radius:50%;background:var(--wb-border-default,var(--wb-bg-tertiary,#d9dadd))}.wbs-growth-task-row.is-completed .wbs-growth-task-title>i,.wbs-growth-task-row.is-claimed .wbs-growth-task-title>i{background:var(--wbs-ring-growth)}.wbs-growth-task-title>span{min-width:0;color:var(--wb-color-text-primary,#1f1f1f);font-weight:620;line-height:1.4;overflow-wrap:anywhere}.wbs-growth-task-title>em{font-style:normal;text-align:right;color:var(--wb-icon-tertiary,#7c818b);font-variant-numeric:tabular-nums;white-space:nowrap}.wbs-growth-task-state{display:flex;min-width:62px;align-items:center;justify-content:flex-end}.wbs-growth-task-title b{text-align:right;color:var(--wb-color-text-secondary,#5f6368);font-size:10px;font-weight:600;white-space:nowrap}.wbs-growth-task-row.is-completed .wbs-growth-task-title b,.wbs-growth-task-row.is-claimed .wbs-growth-task-title b{color:var(--wbs-ring-growth)}.wbs-growth-task-action{display:inline-flex;min-width:60px;height:22px;box-sizing:border-box;align-items:center;justify-content:center;gap:4px;padding:0 7px;border:1px solid var(--wb-button-primary-bg,#1f1f1f);border-radius:6px;background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);font:600 10px/1 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;white-space:nowrap;cursor:pointer;transition:background-color .16s,border-color .16s,box-shadow .16s}.wbs-growth-task-action:hover:not([disabled]){background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#1f1f1f));border-color:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#1f1f1f))}.wbs-growth-task-action:focus-visible{outline:0;box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 34%,transparent)}.wbs-growth-task-action[disabled]{opacity:.72;cursor:default}.wbs-growth-task-action-spinner{width:9px;height:9px;box-sizing:border-box;border:1.5px solid color-mix(in srgb,currentColor 28%,transparent);border-top-color:currentColor;border-radius:50%;animation:wbs-daily-spin .72s linear infinite}.wbs-growth-task-meta{display:flex;align-items:flex-start;gap:16px;margin:5px 0 0 13px;color:var(--wb-color-text-secondary,#5f6368);font-size:10px}.wbs-growth-task-meta>span{display:flex;min-width:0;align-items:flex-start;gap:6px;overflow-wrap:anywhere}.wbs-growth-task-meta>span:last-child{flex:1}.wbs-growth-task-meta label{flex:0 0 auto;color:var(--wb-icon-tertiary,#7c818b);font-size:10px;white-space:nowrap}.wbs-growth-reward-tags{display:flex;min-width:0;flex-wrap:wrap;gap:4px}.wbs-growth-reward-tag{display:inline-flex;align-items:center;min-height:16px;box-sizing:border-box;padding:1px 5px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:999px;background:color-mix(in srgb,var(--wb-bg-tertiary,#f2f3f4) 72%,transparent);color:var(--wb-color-text-secondary,#5f6368);font-size:9px;font-weight:500;line-height:1.2;white-space:nowrap}.wbs-growth-reward-tag.is-empty{color:var(--wb-icon-tertiary,#7c818b)}','.wbs-growth-task-head>span{display:inline-flex;align-items:center;gap:7px}.wbs-growth-task-head i.growth{width:8px;height:8px;flex:none;border-radius:50%;background:var(--wbs-ring-growth);box-shadow:0 0 0 2px color-mix(in srgb,var(--wbs-ring-growth) 17%,transparent)}.wbs-growth-task-head em{color:var(--wb-icon-tertiary,#7c818b)}.wbs-growth-task-title{grid-template-columns:6px minmax(0,1fr) auto minmax(78px,auto)}.wbs-growth-task-title>span{font-size:11px}.wbs-growth-task-tag{display:inline-flex!important;min-height:17px;box-sizing:border-box;align-items:center;padding:1px 6px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:999px;background:color-mix(in srgb,var(--wb-bg-tertiary,#f2f3f4) 72%,transparent);color:var(--wb-color-text-secondary,#5f6368)!important;font-size:9px!important;font-weight:550!important;white-space:nowrap}.wbs-growth-task-state{grid-column:4;min-width:78px}.wbs-growth-task-action{min-width:74px}.wbs-growth-task-guide{margin:4px 78px 0 13px;color:var(--wb-color-text-secondary,#5f6368);font-size:10px;line-height:1.5;overflow-wrap:anywhere}.wbs-growth-task-meta{flex-wrap:wrap;gap:5px 14px;margin-top:6px}.wbs-growth-task-meta>span:last-child{flex:0 1 auto}.wbs-growth-task-reward{flex:1 1 150px!important}.wbs-growth-task-progress{font-variant-numeric:tabular-nums}.wbs-growth-reward-tag{opacity:.76}.wbs-growth-claimed-toggle{display:flex;width:100%;align-items:center;justify-content:center;margin:3px 0 0;padding:6px 0 2px;border:0;border-top:1px solid color-mix(in srgb,var(--wb-border-subtle,rgba(20,24,32,.1)) 72%,transparent);background:transparent;color:var(--wb-icon-secondary,#667085);font:600 10px/1.4 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;cursor:pointer}.wbs-growth-claimed-toggle em{font-style:normal;font-weight:500;color:var(--wb-icon-tertiary,#7c818b)}.wbs-growth-claimed-toggle:hover{color:var(--wb-color-text-primary,#1f1f1f)}.wbs-growth-claimed-toggle:focus-visible{outline:2px solid color-mix(in srgb,var(--wbs-primary) 40%,transparent);outline-offset:2px}','.wbs-buddy-picker{display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:8px;padding:7px 9px 2px;font-size:10.5px;color:var(--wb-color-text-secondary,#5f6368)}','.wbs-daily-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:4px;margin-top:4px}.wbs-daily-action{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:7px;min-height:29px;padding:3px 5px 3px 8px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:7px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent)}.wbs-daily-action span{min-width:0;color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-daily-action b{color:var(--wb-color-text-primary,#1f1f1f);font-size:11px;font-weight:650;white-space:nowrap}.wbs-daily-action-button{min-width:46px}',@@ -15497,7 +16277,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-credit-segment:first-child:last-child{border-radius:3px}','.wbs-credit-segment:hover{z-index:3;filter:brightness(1.12);transform:scaleY(1.35)}',/* 积分越接近到期透明度越高,1 天内只保留很轻的颜色痕迹。 */- '.wbs-credit-segment,.wbs-credit-summary-fill{background:rgba(var(--wbs-primary-rgb,34,197,94),var(--wbs-credit-alpha,1));border-color:rgba(var(--wbs-primary-rgb,34,197,94),var(--wbs-credit-alpha,1))}',+ // 保留浅色、深色、毛玻璃的积分配色;官方皮肤与其他接管主题跟随发送按钮。+ ':is(html[data-skin]:not([data-skin=""]):not([data-wbs-theme-id="dark"]):not([data-wbs-theme-id="nebula"]),html[data-wbs-theme-id]:not([data-wbs-theme-id="default"]):not([data-wbs-theme-id="dark"]):not([data-wbs-theme-id="nebula"])) :is(.wbs-root,.wbs-credit-summary-popover){--wbs-credit-theme-color:var(--wb-button-primary-bg)}',+ '.wbs-credit-segment,.wbs-credit-summary-fill{background:color-mix(in srgb,var(--wbs-credit-theme-color,var(--wbs-primary)) calc(var(--wbs-credit-alpha,1) * 100%),transparent);border-color:color-mix(in srgb,var(--wbs-credit-theme-color,var(--wbs-primary)) calc(var(--wbs-credit-alpha,1) * 100%),transparent)}','.wbs-credit-empty{height:5px;border-radius:0;background:color-mix(in srgb,var(--wb-bg-tertiary,#e8e8eb) 70%,transparent);color:var(--wb-icon-tertiary,#999);font-size:10px;line-height:5px;text-align:center}','.wbs-credit-hint{color:var(--wb-icon-tertiary,#999);font-size:10px;line-height:1.4;margin-top:2px}','.wbs-account-tags{display:inline-flex;align-items:center;gap:5px;min-width:0;margin-left:auto}',@@ -15514,6 +16296,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-daily-rings,.wbs-checkin-tag.ok{--wbs-badge-bg:var(--wb-color-text-primary,#1f1f1f);--wbs-badge-fg:var(--wb-bg-popover,#fff);background:var(--wbs-badge-bg);border-color:transparent;color:var(--wbs-badge-fg);box-shadow:none}.wbs-daily-rings{--wbs-liquid-fill:rgba(255,255,255,.46);--wbs-liquid-bg:rgba(255,255,255,.14);--wbs-liquid-ink:#fff}.wbs-daily-rings .wbs-daily-streak-label.is-pending{color:inherit;opacity:.75}.wbs-daily-rings:hover,.wbs-daily-rings[aria-expanded="true"]{background:color-mix(in srgb,var(--wbs-badge-bg) 84%,white);box-shadow:0 2px 8px rgba(0,0,0,.14)}',':is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings,:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-checkin-tag.ok{--wbs-badge-bg:rgba(255,255,255,.085);--wbs-badge-fg:var(--wb-color-text-primary,#f6f5ff);background:var(--wbs-badge-bg);border:1px solid rgba(255,255,255,.12);color:var(--wbs-badge-fg);box-shadow:inset 0 1px 0 rgba(255,255,255,.08);backdrop-filter:blur(12px) saturate(1.08);-webkit-backdrop-filter:blur(12px) saturate(1.08)}:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings{--wbs-liquid-fill:rgba(170,160,235,.62);--wbs-liquid-bg:rgba(255,255,255,.12);--wbs-liquid-ink:#f6f5ff}:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings:hover,:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings[aria-expanded="true"]{background:rgba(255,255,255,.14);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 3px 10px rgba(0,0,0,.12)}','.wbs-checkin-tag.fail{background:rgba(239,68,68,.1);color:#dc2626}',+ '.wbs-model-rate-limit-slot{display:inline-flex;align-items:center;min-width:0}.wbs-model-rate-limit{appearance:none;-webkit-appearance:none;font:inherit;cursor:pointer;transition:background-color .15s,box-shadow .15s,color .15s}.wbs-model-rate-limit:hover,.wbs-model-rate-limit[aria-expanded="true"]{background:color-mix(in srgb,var(--wbs-badge-bg) 84%,white);box-shadow:0 2px 8px rgba(0,0,0,.14)}.wbs-model-rate-limit:focus-visible{outline:2px solid color-mix(in srgb,var(--wbs-badge-bg) 45%,transparent);outline-offset:2px}',+ '.wbs-status-popover.is-rate-limit{width:500px;max-width:calc(100vw - 16px);overflow-x:auto}.wbs-status-popover.is-rate-limit-summary{width:360px;max-width:calc(100vw - 16px);overflow-x:auto}.wbs-model-rate-limit-detail{grid-template-columns:8px auto minmax(0,1fr) auto auto;gap:7px}.wbs-model-rate-limit-detail b{white-space:nowrap;overflow-wrap:normal}.wbs-model-rate-limit-detail .wbs-model-rate-limit-model{text-align:left}.wbs-model-rate-limit-detail i.rate-limit{color:var(--wb-color-text-primary,#1f1f1f)}.wbs-model-rate-limit-account-group{padding:7px 0 2px;border-top:1px solid var(--wb-border-subtle,rgba(20,24,32,.1))}.wbs-model-rate-limit-account-group:first-of-type{padding-top:0;border-top:0}.wbs-model-rate-limit-account-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 2px 2px}.wbs-model-rate-limit-account-head strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}.wbs-model-rate-limit-account-head span{flex:0 0 auto;color:var(--wb-icon-tertiary,#7c818b);font-size:10px;white-space:nowrap}.wbs-model-rate-limit-summary-row{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,auto);align-items:center;gap:7px;min-height:28px;margin-top:4px;padding:0 8px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent)}.wbs-model-rate-limit-summary-row>span{color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-model-rate-limit-summary-row>b{min-width:0;font-size:11px;font-weight:650;white-space:nowrap;overflow-wrap:normal}.wbs-model-rate-limit-summary-row .wbs-model-rate-limit-model{text-align:left}.wbs-model-rate-limit-summary-row .wbs-model-rate-limit-reset{text-align:right}',+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-model-rate-limit:hover,:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-model-rate-limit[aria-expanded="true"]{background:rgba(255,255,255,.14);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 3px 10px rgba(0,0,0,.12)}','.wbs-ck.pending{color:var(--wb-icon-tertiary,#999)}','.wbs-ck.fail{color:#f53f3f}',/* 右侧操作图标按钮:更轻量 */@@ -15522,7 +16307,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-icon-btn svg{width:16px;height:16px;flex-shrink:0}', // 图标保持 16x16/* 账号切换按钮(wbs-acc-switch,与开关 .wbs-switch 区分):与删除按钮同尺寸同风格 */'.wbs-acc-switch:hover{background:var(--wb-bg-hover,#e8e9eb);color:var(--wb-color-text-primary,#1f1f1f)}',- '.wbs-acc-switch.armed{background:#141416;color:#fff}',+ '.wbs-acc-switch.armed{background:var(--wb-button-primary-bg,#141416);color:var(--wb-button-primary-fg,#fff);border-color:var(--wb-button-primary-bg,#141416)}',/* 删除按钮:与切换按钮同风格(灰底图标),hover/armed 才显红 */'.wbs-del{background:var(--wb-bg-hover,#f7f8fa);color:var(--wb-icon-secondary,#555);border-color:transparent}','.wbs-del:hover{background:#ffecec;color:#f53f3f;border-color:transparent}',@@ -15557,14 +16342,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-ask-hint{font-size:11px;color:#9a9a9a;font-weight:400}','.wbs-fab-settings .wbs-ask-row{margin-top:0}.wbs-fab-settings .wbs-ask-label{flex-direction:column;align-items:flex-start;gap:4px}.wbs-fab-settings .wbs-ask-hint{color:var(--wb-color-text-tertiary,#9a9a9a);line-height:1.5;overflow-wrap:anywhere}','.wbs-robot-option{position:relative;text-align:center;line-height:normal}.wbs-robot-option input{position:absolute;opacity:0;width:1px;height:1px}.wbs-robot-option:has(input:focus-visible){outline:2px solid var(--wb-icon-secondary);outline-offset:1px}',- '.wbs-fab-settings .wbs-switch-slider{background:var(--wb-bg-tertiary,#e5e5e5);box-shadow:inset 0 0 0 1px var(--wb-border-default,#d0d0d0)}.wbs-fab-settings .wbs-switch-slider:before{background:var(--wb-color-text-secondary,#777)}.wbs-fab-settings input:checked + .wbs-switch-slider{background:var(--wb-button-primary-bg,#1f1f1f)}.wbs-fab-settings input:checked + .wbs-switch-slider:before{background:var(--wb-button-primary-fg,#fff)}.wbs-fab-settings input:focus-visible + .wbs-switch-slider{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:3px}','.wbs-switch{position:relative;display:inline-block;width:36px;height:20px;flex-shrink:0;cursor:pointer}','.wbs-switch input{opacity:0;width:0;height:0}',- '.wbs-switch-slider{position:absolute;inset:0;border-radius:20px;background:rgba(255,255,255,.16);box-shadow:inset 0 0 0 1px rgba(255,255,255,.22);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);transition:background .18s}',- '.wbs-switch-slider:before{content:"";position:absolute;width:16px;height:16px;left:2px;top:2px;border-radius:50%;background:var(--wb-bg-popover,#fff);transition:transform .18s;box-shadow:0 1px 2px rgba(0,0,0,.2)}',- '.wbs-switch input:checked + .wbs-switch-slider{background:#f2f2f4;box-shadow:inset 0 0 0 1px rgba(255,255,255,.35)}',- '.wbs-switch input:checked + .wbs-switch-slider:before{background:#111113;box-shadow:0 1px 3px rgba(0,0,0,.35)}',+ '.wbs-switch-slider{position:absolute;inset:0;border-radius:20px;background:var(--wb-bg-tertiary,#e5e5e5);box-shadow:inset 0 0 0 1px var(--wb-border-default,#d0d0d0);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);transition:background .18s}',+ '.wbs-switch-slider:before{content:"";position:absolute;width:16px;height:16px;left:2px;top:2px;border-radius:50%;background:var(--wb-color-text-secondary,#777);transition:transform .18s;box-shadow:0 1px 2px rgba(0,0,0,.2)}',+ '.wbs-switch input:checked + .wbs-switch-slider{background:var(--wb-button-primary-bg,#1f1f1f);box-shadow:inset 0 0 0 1px var(--wb-border-default,#d0d0d0)}',+ '.wbs-switch input:checked + .wbs-switch-slider:before{background:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 3px rgba(0,0,0,.35)}','.wbs-switch input:checked + .wbs-switch-slider:before{transform:translateX(16px)}',+ '.wbs-switch input:focus-visible + .wbs-switch-slider{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:3px}.wbs-switch input:disabled + .wbs-switch-slider{opacity:.5;cursor:default}',/* 背景毛玻璃开关 + 模糊度进度条 */'.wbs-blur-row{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:8px}','.wbs-blur-label{display:flex;align-items:baseline;gap:6px;font-size:12px;color:var(--wb-color-text-secondary,#444);font-weight:600;min-width:0;line-height:1.3;white-space:nowrap}',@@ -15587,21 +16372,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 宽度按 icon(16)+gap(7)+文字(~90)+padding(13) 收紧,不留过多右侧留白'html[data-wbs-language="en"] .wbs-stash-inline:hover,html[data-wbs-language="en"] .wbs-stash-inline.wbs-stash-inline-inline:hover{width:128px}','html[data-wbs-language="en"] .wbs-stash-inline:hover .wbs-stash-txt{max-width:96px}',+ '.wbs-theme-takeover-row{display:flex;align-items:center;flex-shrink:0;gap:12px;margin-bottom:8px;padding-bottom:8px;border-bottom:1px solid var(--wb-border-subtle)}.wbs-theme-takeover-row>.wbs-pcard-title{flex:1;min-width:0}',+ '.wbs-theme-takeover-row:has(#wbs-theme-takeover:not(:checked)){margin-bottom:0;padding-bottom:0;border-bottom:0}','.wbs-explore-inline{position:fixed;left:auto;display:flex;align-items:center;justify-content:center;cursor:pointer;flex-shrink:0;z-index:auto;top:0;right:0;overflow:visible;padding:0 8px}',/* 复用暂存按钮视觉(wbs-stash-inline 提供 32px 圆形/背景/阴影),但 hover 不变宽 */'.wbs-stash-inline.wbs-explore-inline:hover,.wbs-stash-inline.wbs-explore-inline.wbs-stash-inline-inline:hover{width:32px!important;min-width:32px!important;height:32px!important;border-radius:50%;padding:0 8px}',/* 图标常显;hover 无任何自身动画 */'.wbs-explore-ico{display:flex;align-items:center;justify-content:center}',- /* 新版内联模式:弹层(absolute)必须以按钮自身为定位上下文——static 会让 .wbs-explore-pop 的 bottom:100% 上溯到最近的 positioned 祖先(操作栏外壳),导致弹层大幅偏离按钮;z-index 抬升让按钮成为独立层叠上下文,弹层在其内不受操作栏兄弟元素压制 */'.wbs-explore-inline.wbs-stash-inline-inline{position:relative;z-index:99999}',- /* 按钮不可点击缩放(点击不改变按钮自身与面板大小),菜单全由 hover 展示 */'.wbs-explore-inline:active{transform:none}',- '.wbs-explore-pop{position:absolute;bottom:calc(100% + 10px);left:50%;transform:translateX(-50%) translateY(6px);width:280px;max-width:84vw;opacity:0;visibility:hidden;transition:opacity .18s ease,transform .18s ease,visibility 0s linear .18s;z-index:2147483647;pointer-events:none}',- /* hover 桥接:向下覆盖按钮与弹窗之间的 10px 间隙,按钮→弹窗移动不丢失悬停(菜单雏形) */+ '.wbs-explore-pop{position:fixed;bottom:0;left:0;transform:translateY(6px);width:280px;max-width:84vw;opacity:0;visibility:hidden;transition:opacity .18s ease,transform .18s ease,visibility 0s linear .18s;z-index:22;pointer-events:none;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif}','.wbs-explore-pop::before{content:"";position:absolute;left:-12px;right:-12px;bottom:-14px;height:14px}',- '.wbs-explore-inline:hover .wbs-explore-pop,.wbs-explore-pop:hover{opacity:1;visibility:visible;transform:translateX(-50%) translateY(0);pointer-events:auto}',- /* 点击选项后关闭面板(wbs-menu-closed 期间强制隐藏,重新进入按钮区后恢复可展示) */- '.wbs-explore-inline.wbs-menu-closed .wbs-explore-pop{opacity:0;visibility:hidden;pointer-events:none;transform:translateX(-50%) translateY(6px)}',+ '.wbs-explore-pop.is-open{opacity:1;visibility:visible;transform:translateY(0);pointer-events:auto}',/* 弹窗卡片:适配插件主题的毛玻璃;面板整体为默认箭头,仅选项 hover 变点击手型 */'.wbs-explore-card{position:relative;padding:8px;border-radius:12px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 62%,transparent);backdrop-filter:blur(18px) saturate(1.3);-webkit-backdrop-filter:blur(18px) saturate(1.3);border:1px solid var(--wb-border-subtle,#ececec);box-shadow:0 12px 32px rgba(0,0,0,.18);color:var(--wb-color-text-primary,#1f1f1f);cursor:default}','html[data-wbs-theme-id="nebula"] .wbs-explore-card{background:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 88%,transparent);background-color:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 88%,transparent);box-shadow:0 14px 36px rgba(0,0,0,.38)}',@@ -15679,7 +16461,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-auto-card{display:flex;flex:1;flex-direction:column;min-height:0;margin-bottom:0}','.wbs-auto-toolbar{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:6px;flex-shrink:0}.wbs-auto-toolbar .wbs-pcard-title{margin-bottom:0}.wbs-auto-toolbar>.wbs-auto-toolbar-actions{flex-basis:100%;justify-content:flex-start}.wbs-auto-toolbar .wbs-sess-bbtn{font-size:11px;padding:5px 8px}','.wbs-auto-toolbar-actions,.wbs-auto-editor-actions,.wbs-auto-normal-actions,.wbs-auto-batch-actions{display:flex;align-items:center;gap:6px;flex-wrap:wrap}.wbs-auto-toolbar-actions{justify-content:flex-end}.wbs-auto-normal-actions{width:100%;min-width:0}.wbs-auto-right-actions{display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:6px;max-width:100%;margin-left:auto}.wbs-auto-log-head-actions{display:flex;align-items:center;gap:8px}',- '.wbs-auto-normal-actions .wbs-auto-pick-btn{border-color:var(--wb-button-primary-bg,#1f1f1f);background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}.wbs-auto-normal-actions .wbs-auto-pick-btn:hover,.wbs-auto-normal-actions .wbs-auto-pick-btn:focus-visible{background:var(--wb-button-primary-hover-bg,var(--wb-button-primary-bg,#1f1f1f));color:var(--wb-button-primary-fg,#fff)}',+ '.wbs-auto-normal-actions .wbs-auto-pick-btn{border-color:var(--wb-button-primary-bg,#1f1f1f);background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}.wbs-auto-normal-actions .wbs-auto-pick-btn:hover,.wbs-auto-normal-actions .wbs-auto-pick-btn:focus-visible{background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#1f1f1f));color:var(--wb-button-primary-fg,#fff)}','.wbs-auto-list{display:flex;flex:1;min-height:0;flex-direction:column;gap:5px;overflow:auto;padding-right:2px;margin-top:10px}','.wbs-auto-row{display:flex;flex:0 0 auto;flex-direction:column;align-items:stretch;gap:7px;min-height:48px;padding:10px;border:1px solid var(--wb-border-subtle,#ececec);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 22%,transparent)}','.wbs-auto-row-head{display:flex;align-items:center;gap:8px;min-width:0}.wbs-auto-enabled{flex-shrink:0}.wbs-auto-enabled[hidden]{display:none!important}.wbs-auto-description{color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.5;overflow-wrap:anywhere;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden}.wbs-auto-row-foot{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px}.wbs-auto-details{min-width:0}.wbs-auto-triggers{display:flex;flex-wrap:wrap;gap:4px}.wbs-auto-trigger-chip{display:inline-flex;max-width:100%;padding:2px 6px;border:1px solid var(--wb-border-subtle,#e7e7e7);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font-size:10px;line-height:1.4;overflow-wrap:anywhere}.wbs-auto-state-line{display:flex;align-items:center;flex-wrap:wrap;gap:4px 8px;min-height:16px;margin-top:5px;color:var(--wb-icon-tertiary,#888);font-size:10px}.wbs-auto-state{display:inline-flex;align-items:center;gap:4px}.wbs-auto-state:before{content:"";width:4px;height:4px;flex:0 0 4px;border-radius:50%;background:currentColor}.wbs-auto-state.running{color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-auto-state.off{opacity:.65}.wbs-auto-last-run.failed{color:var(--wb-color-text-primary,#222)}.wbs-auto-icon:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:1px}',@@ -15696,7 +16478,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'#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-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: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-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-button-primary-bg,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}',@@ -15744,6 +16526,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.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)}','.wbs-sess-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin-bottom:8px}',+ '.wbs-sess-export-progress{flex:0 0 auto;min-width:0;margin:0 0 8px;padding:9px 10px;border:1px solid var(--wb-border-subtle);border-radius:9px;background:var(--wb-bg-secondary);color:var(--wb-color-text-primary);font-size:11px;line-height:1.5}.wbs-sess-export-progress[hidden],.wbs-sess-export-progress [hidden]{display:none}.wbs-sess-export-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.wbs-sess-export-head strong{flex:1;font-size:12px}.wbs-sess-export-progress progress{display:block;width:100%;height:5px;margin:7px 0;accent-color:var(--wbs-primary)}.wbs-sess-export-progress progress[hidden]{display:none}.wbs-sess-export-progress [data-export-detail]{overflow-wrap:anywhere;color:var(--wb-color-text-secondary)}','.wbs-sess-copy-progress{box-sizing:border-box;margin:0 0 8px;padding:9px 10px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 82%,transparent);box-shadow:0 2px 8px rgba(0,0,0,.04)}','.wbs-sess-copy-progress[hidden]{display:none!important}.wbs-sess-copy-head{display:flex;align-items:center;gap:6px;min-width:0}.wbs-sess-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex:0 0 20px;border-radius:6px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 9%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-sess-copy-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11.5px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-sess-copy-detail{margin:4px 0 6px 26px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;line-height:1.35;color:var(--wb-icon-tertiary,#8a8f98)}.wbs-sess-copy-track{height:4px;margin-left:26px;overflow:hidden;border-radius:999px;background:var(--wb-bg-tertiary,#e9eaed)}.wbs-sess-copy-fill{display:block;height:100%;width:0;border-radius:inherit;background:var(--wb-accent-blue,var(--wb-button-primary-bg,#1f1f1f));transition:width .2s ease}.wbs-sess-copy-progress.is-done .wbs-sess-copy-fill{background:#2f9e63}.wbs-sess-copy-progress.is-partial .wbs-sess-copy-fill{background:#d48a19}.wbs-sess-copy-progress.is-error .wbs-sess-copy-fill{background:#d84a4a}',@@ -15752,7 +16535,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-refresh:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-sess-bbtn{display:inline-flex;align-items:center;justify-content:center;gap:4px;padding:7px 12px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#555);font-size:12px;cursor:pointer;line-height:1;transition:all .15s}','.wbs-sess-bbtn:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}',- '.wbs-sess-bbtn.active{background:#fff;color:#1f1f1f;border-color:#fff}',+ '.wbs-sess-bbtn.active{background:var(--wb-button-primary-bg,#141416);color:var(--wb-button-primary-fg,#fff);border-color:var(--wb-button-primary-bg,#141416)}','.wbs-sess-auto-all{display:inline-flex;align-items:center;justify-content:center;gap:5px;height:30px;flex:0 0 auto;padding:0 8px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--wb-icon-secondary,#555);font:inherit;font-size:11px;font-weight:600;line-height:1;cursor:pointer;transition:background .15s,color .15s,border-color .15s}','.wbs-sess-auto-all:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-sess-auto-all.active{background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 10%,transparent);border-color:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 28%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}',@@ -15767,8 +16550,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-batchbar{display:flex;align-items:center;gap:5px;flex-wrap:wrap;min-width:0;margin:0;padding:0;border:none;background:transparent}','#wbs-sess-batchbar{flex-basis:100%}','.wbs-sess-filters button:disabled,.wbs-sess-filters select:disabled,#wbs-sess-batch:disabled,#wbs-sess-import:disabled{opacity:.45;cursor:not-allowed;pointer-events:none}',- '.wbs-sess-done{margin-left:auto;color:#fff;background:#141416;border-color:#141416}',- '.wbs-sess-done:hover{background:#2a2a2e;color:#fff}',+ '.wbs-sess-done{margin-left:auto;color:var(--wb-button-primary-fg,#fff);background:var(--wb-button-primary-bg,#141416);border-color:var(--wb-button-primary-bg,#141416)}',+ '.wbs-sess-done:hover{background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#2a2a2e));color:var(--wb-button-primary-fg,#fff)}',/* 删除按钮:图标按钮,尺寸与兄弟一致;点击后变警告色(armed) */'.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)}',@@ -15916,8 +16699,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-modal{width:300px;max-width:88vw;background:var(--wb-bg-popover,#fff);border-radius:14px;padding:16px;box-shadow:0 10px 40px rgba(0,0,0,.25);color:var(--wb-color-text-primary,#1f1f1f)}',/* 弹窗文字主题适配:body 继承 .wbs-root 硬编码深色字,暗色下必须显式覆盖为浅色 */'html.cb-dark .wbs-modal,html.cb-dark .wbs-modal-title,html.cb-dark .wbs-modal-body,html[data-theme="dark"] .wbs-modal,html[data-theme="dark"] .wbs-modal-title,html[data-theme="dark"] .wbs-modal-body{color:#e6e6e9}',- 'html.cb-dark .wbs-modal-btn,html[data-theme="dark"] .wbs-modal-btn{color:#d5d5d9;border-color:rgba(232,232,234,0.16);background:rgba(255,255,255,0.05)}',- 'html.cb-dark .wbs-modal-btn:hover,html[data-theme="dark"] .wbs-modal-btn:hover{background:rgba(255,255,255,0.12)}',+ 'html.cb-dark .wbs-modal-btn:not(:where(.wbs-modal-ok,.primary)),html[data-theme="dark"] .wbs-modal-btn:not(:where(.wbs-modal-ok,.primary)){color:#d5d5d9;border-color:rgba(232,232,234,0.16);background:rgba(255,255,255,0.05)}',+ 'html.cb-dark .wbs-modal-btn:not(:where(.wbs-modal-ok,.primary)):hover,html[data-theme="dark"] .wbs-modal-btn:not(:where(.wbs-modal-ok,.primary)):hover{background:rgba(255,255,255,0.12)}',/* 高危红色确认按钮在暗色下保持红色风格(略提亮更醒目) */'html.cb-dark .wbs-modal-btn.wbs-modal-danger,html[data-theme="dark"] .wbs-modal-btn.wbs-modal-danger{color:#fff;background:#e03d3d;border-color:#e03d3d}','html.cb-dark .wbs-modal-btn.wbs-modal-danger:hover,html[data-theme="dark"] .wbs-modal-btn.wbs-modal-danger:hover{background:#f04a4a}',@@ -15929,7 +16712,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-checkin-risk-modal p{margin:0}.wbs-checkin-risk-modal .wbs-modal-actions{flex-wrap:wrap}','.wbs-checkin-risk-modal .wbs-modal-btn{line-height:1.4;white-space:normal;transition:background .15s,color .15s,border-color .15s}','.wbs-checkin-risk-modal .wbs-modal-btn.wbs-modal-ok{background:var(--wb-button-primary-bg,#141416);color:var(--wb-button-primary-fg,#fff);border-color:var(--wb-button-primary-bg,#141416)}',- '.wbs-checkin-risk-modal .wbs-modal-btn.wbs-modal-ok:hover{background:var(--wb-button-primary-hover-bg,var(--wb-button-primary-bg,#2a2a2e))}',+ '.wbs-checkin-risk-modal .wbs-modal-btn.wbs-modal-ok:hover:not(:disabled){background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#2a2a2e))}','.wbs-checkin-risk-modal .wbs-modal-btn:focus-visible{outline:2px solid var(--wb-color-text-primary,#1f1f1f);outline-offset:2px}','.wbs-checkin-risk-modal .wbs-modal-btn:disabled{opacity:.55;cursor:wait}','.wbs-checkin-risk-error{font-size:12px;line-height:1.5;overflow-wrap:anywhere;margin-bottom:10px;color:var(--wb-color-text-primary,#1f1f1f)}',@@ -15946,11 +16729,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-modal-sub{font-size:11px;color:var(--wb-icon-tertiary,#999)}','.wbs-modal-warn{font-size:12px;color:#ff6b6b;line-height:1.6}','.wbs-modal-actions{display:flex;gap:8px;justify-content:flex-end}',- /* 会话弹窗按钮:取消=次级白底、确定=深色主按钮(与面板主按钮风格一致) */+ /* 会话弹窗按钮:取消和确定分别跟随主题的次级/主按钮颜色 */'.wbs-modal-btn{padding:7px 12px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#555);font-size:12px;cursor:pointer;line-height:1;transition:all .15s;font-family:inherit}','.wbs-modal-btn:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);border-color:var(--wb-border-strong,#bbb)}',- '.wbs-modal-btn.wbs-modal-ok{color:#fff;background:#141416;border-color:#141416}',- '.wbs-modal-btn.wbs-modal-ok:hover{background:#2a2a2e;color:#fff}',+ '.wbs-modal-btn.wbs-modal-ok{color:var(--wb-button-primary-fg,#fff);background:var(--wb-button-primary-bg,#141416);border-color:var(--wb-button-primary-bg,#141416)}',+ '.wbs-modal-btn.wbs-modal-ok:hover{background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#2a2a2e));color:var(--wb-button-primary-fg,#fff)}','.wbs-modal-btn.is-loading{display:inline-flex;align-items:center;justify-content:center;gap:6px;cursor:wait}','.wbs-modal-btn.is-loading::before{content:"";width:11px;height:11px;box-sizing:border-box;border:1.5px solid currentColor;border-top-color:transparent;border-radius:50%;animation:wbs-modal-btn-spin .72s linear infinite}','@keyframes wbs-modal-btn-spin{to{transform:rotate(360deg)}}',@@ -16090,7 +16873,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-credit-summary-chart{max-height:230px;overflow:auto;overscroll-behavior:contain}.wbs-credit-summary-row{display:grid;grid-template-columns:68px minmax(30px,1fr) 58px;align-items:center;gap:8px;min-height:28px}.wbs-credit-summary-row>span{font-size:11px;color:var(--wb-color-text-secondary)}.wbs-credit-summary-row>b{text-align:right;font-size:11px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.wbs-credit-summary-track{display:flex;align-items:stretch;gap:2px;height:8px;border-radius:4px;background:var(--wb-bg-tertiary);overflow:visible}.wbs-credit-summary-track .wbs-credit-segment{height:8px;min-width:3px}.wbs-credit-summary-track i{display:block;height:100%;border-radius:4px;}.wbs-credit-summary-foot{border-top:1px solid var(--wb-border-subtle);padding-top:8px;margin-top:8px}','html.cb-dark .wbs-credit-summary-popover,html[data-theme="dark"] .wbs-credit-summary-popover,body[data-vscode-theme-name="IDE Night"] .wbs-credit-summary-popover{background:var(--wb-bg-popover,var(--wb-bg-primary));color:var(--wb-color-text-primary);border-color:var(--wb-border-default)}','@media(max-width:600px){.wbs-acct-toolbar{flex-wrap:wrap;gap:8px}.wbs-acct-summary{flex-wrap:wrap}.wbs-acct-actions{margin-left:auto}}',- '.wbs-acct-summary{display:flex;align-items:center;gap:12px;min-width:0}',+ '.wbs-acct-summary{display:flex;align-items:center;gap:12px;min-width:0}.wbs-acct-summary>[data-act="model-rate-limit-summary"]{margin-left:-7px}','.wbs-acct-eye{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;padding:0;border:none;border-radius:6px;background:transparent;color:var(--wb-icon-secondary,var(--wb-color-text-secondary,#666));cursor:pointer;flex-shrink:0;transition:color .15s,background-color .15s}','.wbs-acct-eye:hover{background:var(--wb-bg-hover,#f0f0f0);color:var(--wb-color-text,#222)}','.wbs-acct-eye:active{transform:scale(.94)}',@@ -16127,7 +16910,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-session-copy-notice{position:fixed;z-index:2147483647;box-sizing:border-box;min-height:108px;padding:12px 13px 11px;border:1px solid var(--wb-border-subtle,rgba(0,0,0,.1));border-radius:13px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f2937);box-shadow:0 12px 34px rgba(0,0,0,.18);font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;animation:wbs-session-copy-in .2s cubic-bezier(.22,1,.36,1);pointer-events:auto}','@keyframes wbs-session-copy-in{from{opacity:0;transform:translateY(7px) scale(.985)}to{opacity:1;transform:translateY(0) scale(1)}}','.wbs-session-copy-head{display:flex;align-items:center;gap:7px;min-height:22px}',- '.wbs-session-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:23px;height:23px;flex:0 0 23px;border-radius:7px;background:color-mix(in srgb,#2e9b68 13%,transparent);color:#238a5b}',+ '.wbs-session-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:23px;height:23px;flex:0 0 23px;border-radius:7px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 13%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}','.wbs-session-copy-title{min-width:0;flex:1;font-size:12px;font-weight:700;line-height:1.35;overflow-wrap:anywhere}','.wbs-session-copy-close{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;flex:0 0 22px;margin:-2px -3px -2px 1px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--wb-icon-tertiary,#8a8f98);font:inherit;font-size:17px;line-height:1;cursor:pointer}','.wbs-session-copy-close:hover{background:var(--wb-bg-hover,#f5f6f8);color:var(--wb-color-text-primary,#1f2937)}',@@ -16138,7 +16921,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.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{display:flex;flex-direction:column;gap:6px;min-width:0;max-width:100%;margin-top:3px;color:var(--wb-color-text-primary,#1f1f1f);font-size:10.5px;line-height:1.45}',- '.wbs-session-copy-summary-group{display:flex;flex-direction:column;gap:1px;min-width:0}.wbs-session-copy-summary-label{align-self:flex-start;display:inline-flex;align-items:center;margin:3px 0 2px;padding:4px 9px;border-radius:999px;font-size:11px;font-weight:700;line-height:1.3}.wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label{background:color-mix(in srgb,#2e9b68 14%,transparent);color:#238a5b}.wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label{background:color-mix(in srgb,#c77a17 15%,transparent);color:#b05d18}.wbs-session-copy-summary-line{min-width:0;padding-left:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-session-copy-summary-line.is-copied{color:#238a5b}.wbs-session-copy-summary-line.is-failed{color:#b05d18}',+ '.wbs-session-copy-summary-group{display:flex;flex-direction:column;gap:1px;min-width:0}.wbs-session-copy-summary-label{align-self:flex-start;display:inline-flex;align-items:center;margin:3px 0 2px;padding:4px 9px;border-radius:999px;font-size:11px;font-weight:700;line-height:1.3}.wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label{background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 14%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label{background:color-mix(in srgb,#c77a17 15%,transparent);color:#b05d18}.wbs-session-copy-summary-line{min-width:0;padding-left:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-session-copy-summary-line.is-copied{color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-session-copy-summary-line.is-failed{color:#b05d18}','.wbs-session-copy-actions{display:flex;align-items:center;justify-content:flex-start;gap:8px;margin-top:8px;padding-top:8px;border-top:1px solid var(--wb-border-subtle,#e5e7eb)}','.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}','.wbs-session-copy-details-btn:hover{background:var(--wb-bg-active,#e9edf2)}',@@ -16156,41 +16939,43 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.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-row.is-copied .wbs-session-copy-detail-status{color:var(--wb-button-primary-bg,#1f1f1f)}.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:var(--wb-button-primary-bg,#1f1f1f)}',+ '.wbs-session-copy-notice.is-done .wbs-session-copy-icon{background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 15%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-session-copy-notice.is-done .wbs-session-copy-fill{background:var(--wb-button-primary-bg,#1f1f1f)}','.wbs-session-copy-notice.is-partial .wbs-session-copy-icon,.wbs-session-copy-notice.is-error .wbs-session-copy-icon{background:color-mix(in srgb,#c77a17 16%,transparent);color:#a96208}.wbs-session-copy-notice.is-partial .wbs-session-copy-fill{background:#c77a17}','.wbs-session-copy-notice.is-conflict .wbs-session-copy-icon{background:color-mix(in srgb,#b46a17 17%,transparent);color:#a55f09}.wbs-session-copy-notice.is-conflict .wbs-session-copy-fill{background:#b46a17}.wbs-session-copy-notice.is-conflict .wbs-session-copy-status{color:#96570b}','.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-summary-group.is-copied .wbs-session-copy-summary-label,html[data-theme="dark"] .wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label{background:color-mix(in srgb,#2e9b68 23%,transparent);color:#62c695}html.cb-dark .wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label,html[data-theme="dark"] .wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label{background:color-mix(in srgb,#c77a17 23%,transparent);color:#e4b36a}html.cb-dark .wbs-session-copy-summary-line.is-copied,html[data-theme="dark"] .wbs-session-copy-summary-line.is-copied,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-line.is-copied{color:#62c695}html.cb-dark .wbs-session-copy-summary-line.is-failed,html[data-theme="dark"] .wbs-session-copy-summary-line.is-failed,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-line.is-failed{color:#e4b36a}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))}',+ '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-summary-group.is-copied .wbs-session-copy-summary-label,html[data-theme="dark"] .wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-group.is-copied .wbs-session-copy-summary-label{background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 23%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}html.cb-dark .wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label,html[data-theme="dark"] .wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-group.is-failed .wbs-session-copy-summary-label{background:color-mix(in srgb,#c77a17 23%,transparent);color:#e4b36a}html.cb-dark .wbs-session-copy-summary-line.is-copied,html[data-theme="dark"] .wbs-session-copy-summary-line.is-copied,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-line.is-copied{color:var(--wb-button-primary-bg,#1f1f1f)}html.cb-dark .wbs-session-copy-summary-line.is-failed,html[data-theme="dark"] .wbs-session-copy-summary-line.is-failed,body[data-vscode-theme-name*="dark" i] .wbs-session-copy-summary-line.is-failed{color:#e4b36a}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-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)}','.wbs-token-stats-modal{width:min(980px,calc(100vw - 48px));max-width:calc(100vw - 48px);height:min(84vh,800px);max-height:calc(100vh - 48px);display:flex;flex-direction:column;overflow:hidden;border:1px solid var(--wb-border-default,rgba(20,24,32,.14));border-radius:16px;padding:0;box-shadow:0 24px 80px rgba(15,18,24,.22)}',- '.wbs-usage-header{position:sticky;top:0;z-index:4;flex-shrink:0;padding:20px 22px 0;border-bottom:1px solid var(--wb-border-subtle,#eee);background:color-mix(in srgb,var(--wb-bg-popover,#fff) 94%,transparent);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px)}.wbs-usage-scroll{min-height:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;flex:1;padding:8px 22px 22px}.wbs-usage-dashboard{scrollbar-width:none}.wbs-usage-dashboard::-webkit-scrollbar{display:none}.wbs-token-stats-modal>.wbs-modal-actions{flex-shrink:0;padding:13px 22px;border-top:1px solid var(--wb-border-subtle,#eee);background:var(--wb-bg-popover,#fff)}.wbs-token-stats-modal .wbs-token-model-scroll{max-height:280px;overflow-y:auto}.wbs-token-stats-modal .wbs-token-model-scroll:after{display:none}.wbs-credit-query-content{position:relative;min-height:430px}',+ '.wbs-usage-header{position:sticky;top:0;z-index:4;flex-shrink:0;padding:20px 22px 0;border-bottom:1px solid var(--wb-border-subtle,#eee);background:color-mix(in srgb,var(--wb-bg-popover,#fff) 94%,transparent);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px)}.wbs-usage-scroll{min-height:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;flex:1;padding:8px 22px 22px}.wbs-usage-dashboard{scrollbar-width:none}.wbs-usage-dashboard::-webkit-scrollbar{display:none}.wbs-token-stats-modal>.wbs-modal-actions{flex-shrink:0;padding:13px 22px;border-top:1px solid var(--wb-border-subtle,#eee);background:var(--wb-bg-popover,#fff)}.wbs-token-stats-modal .wbs-token-model-scroll{overflow:visible}.wbs-token-stats-modal .wbs-token-model-scroll:after{display:none}.wbs-credit-query-content{position:relative;min-height:430px}','.wbs-token-stats-head{display:flex;align-items:center;justify-content:space-between;gap:10px}','.wbs-token-source-note{margin:0 0 12px;font-size:11px;line-height:1.6;color:var(--wb-icon-secondary,#667085);overflow-wrap:anywhere}','.wbs-usage-tabs{display:flex;gap:18px;margin:13px 0 0;border-bottom:1px solid var(--wb-border-subtle,#eee)}.wbs-usage-tabs button{border:0;border-bottom:2px solid transparent;background:transparent;color:var(--wb-icon-secondary,#667085);padding:7px 2px 9px;font:inherit;font-size:12px;cursor:pointer;transition:color .15s,border-color .15s}.wbs-usage-tabs button.active{border-bottom-color:var(--wb-color-text-primary,#1f1f1f);color:var(--wb-color-text-primary,#1f1f1f);font-weight:700}.wbs-credit-stats-note{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:10px 0;color:var(--wb-icon-secondary,#667085);font-size:11px;line-height:1.5}.wbs-credit-sync{height:26px;padding:0 9px;border:1px solid var(--wb-border-default,#e2e4e8);border-radius:7px;background:var(--wb-bg-tertiary,#f5f6f8);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:11px;cursor:pointer}.wbs-credit-sync:disabled{opacity:.6;cursor:wait}.wbs-credit-stats-body{min-height:240px}','.wbs-usage-period{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:16px 0 12px;color:var(--wb-color-text-secondary,#667085);font-size:11px}.wbs-usage-segment{display:inline-flex;align-items:center;gap:2px;max-width:100%;padding:3px;border:1px solid var(--wb-border-subtle,#eee);border-radius:9px;background:var(--wb-bg-tertiary,#f5f6f8)}.wbs-usage-segment button{min-width:55px;height:27px;padding:0 9px;border:0;border-radius:6px;background:transparent;color:var(--wb-color-text-secondary,#667085);font:inherit;font-size:11px;cursor:pointer;white-space:nowrap}.wbs-usage-segment button.active{background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font-weight:600;box-shadow:0 1px 4px rgba(0,0,0,.1)}.wbs-usage-segment button:disabled{opacity:.55;cursor:wait}.wbs-usage-segment button:focus-visible,.wbs-trend-legend button:focus-visible{outline:2px solid var(--wbs-primary);outline-offset:2px}',- '.wbs-trend-panel{--wbs-trend-series-1:#388fc6;--wbs-trend-series-2:#df806a;--wbs-trend-series-3:#269f8b;--wbs-trend-series-4:#a179c6;--wbs-trend-series-5:#d8759b;--wbs-trend-series-6:#759c41;--wbs-trend-series-7:#b27d3c;--wbs-trend-series-8:#559db1;--wbs-trend-series-9:#c46b71;--wbs-trend-series-10:#7b86c2;--wbs-trend-series-11:#6b9b78;--wbs-trend-series-12:#b878aa}',- 'html.cb-dark #wbs-token-stats-modal .wbs-trend-panel,html[data-theme="dark"] #wbs-token-stats-modal .wbs-trend-panel,body[data-vscode-theme-name*="dark" i] #wbs-token-stats-modal .wbs-trend-panel,html[data-wbs-theme-id="dark"] #wbs-token-stats-modal .wbs-trend-panel,html[data-wbs-theme-id="cyber-purple"] #wbs-token-stats-modal .wbs-trend-panel,html[data-wbs-theme-id="nebula"] #wbs-token-stats-modal .wbs-trend-panel{--wbs-trend-series-1:#72bfeb;--wbs-trend-series-2:#f4a78d;--wbs-trend-series-3:#67cdb8;--wbs-trend-series-4:#bda0e0;--wbs-trend-series-5:#ed9ab9;--wbs-trend-series-6:#b1ce74;--wbs-trend-series-7:#dbb274;--wbs-trend-series-8:#8fc8d6;--wbs-trend-series-9:#e99a9f;--wbs-trend-series-10:#aab2ed;--wbs-trend-series-11:#94c8a2;--wbs-trend-series-12:#d9a1cd}',+ '.wbs-trend-panel,.wbs-usage-pie-section{--wbs-chart-base:var(--wbs-credit-theme-color,var(--wbs-primary));--wbs-trend-series-1:var(--wbs-chart-base);--wbs-trend-series-2:color-mix(in srgb,var(--wbs-chart-base) 84%,var(--wb-color-text-primary));--wbs-trend-series-3:color-mix(in srgb,var(--wbs-chart-base) 68%,var(--wb-bg-primary));--wbs-trend-series-4:color-mix(in srgb,var(--wbs-chart-base) 52%,var(--wb-bg-primary));--wbs-trend-series-5:color-mix(in srgb,var(--wbs-chart-base) 36%,var(--wb-bg-primary));--wbs-trend-series-6:color-mix(in srgb,var(--wbs-chart-base) 72%,transparent);--wbs-trend-series-7:color-mix(in srgb,var(--wbs-chart-base) 58%,var(--wb-color-text-primary));--wbs-trend-series-8:color-mix(in srgb,var(--wbs-chart-base) 44%,var(--wb-color-text-primary));--wbs-trend-series-9:color-mix(in srgb,var(--wbs-chart-base) 30%,var(--wb-color-text-primary));--wbs-trend-series-10:color-mix(in srgb,var(--wbs-chart-base) 70%,var(--wb-bg-secondary));--wbs-trend-series-11:color-mix(in srgb,var(--wbs-chart-base) 52%,transparent);--wbs-trend-series-12:color-mix(in srgb,var(--wbs-chart-base) 38%,transparent);}','.wbs-trend-controls{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap;margin-bottom:9px}.wbs-trend-modes{flex-shrink:0}.wbs-trend-modes button{min-width:48px}.wbs-trend-legend{display:flex;align-items:center;gap:6px;flex:1;flex-wrap:wrap;min-width:140px;max-height:74px;overflow-y:auto;scrollbar-width:none}.wbs-trend-legend::-webkit-scrollbar{display:none}.wbs-trend-legend button{display:inline-flex;align-items:center;gap:6px;max-width:165px;height:27px;padding:0 8px;border:1px solid var(--wb-border-subtle,#eee);border-radius:6px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-secondary,#667085);font:inherit;font-size:11px;cursor:pointer;opacity:.55}.wbs-trend-legend button.active{opacity:1;color:var(--wb-color-text-primary,#1f1f1f)}.wbs-trend-legend button i{flex:none;width:8px;height:8px;border-radius:50%;background:var(--wbs-series-color);color:var(--wbs-series-color)}.wbs-trend-legend button span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-trend-no-series{font-size:11px;color:var(--wb-color-text-secondary,#667085)}',- '.wbs-token-stats-actions{display:flex;justify-content:flex-end;gap:7px;margin:2px 0 12px}.wbs-token-stats-actions button{height:30px;padding:0 14px;border-radius:7px;font:inherit;font-size:11px;cursor:pointer}.wbs-token-stats-search{border:1px solid var(--wb-button-primary-bg,#1f1f1f);background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-text,#fff)}.wbs-token-stats-reset{border:1px solid var(--wb-border-default,#e2e4e8);background:var(--wb-bg-tertiary,#f5f6f8);color:var(--wb-color-text-secondary,#667085)}.wbs-token-stats-actions button:disabled{opacity:.55;cursor:wait}',+ '.wbs-token-stats-actions{display:flex;justify-content:flex-end;gap:7px;margin:2px 0 12px}.wbs-token-stats-actions button{height:30px;padding:0 14px;border-radius:7px;font:inherit;font-size:11px;cursor:pointer}.wbs-token-stats-search{border:1px solid var(--wb-button-primary-bg,#1f1f1f);background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}.wbs-token-stats-reset{border:1px solid var(--wb-border-default,#e2e4e8);background:var(--wb-bg-tertiary,#f5f6f8);color:var(--wb-color-text-secondary,#667085)}.wbs-token-stats-actions button:disabled{opacity:.55;cursor:wait}','.wbs-token-stats-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}','.wbs-token-stats-grid>div{position:relative;display:flex;min-width:0;overflow:hidden;flex-direction:column;gap:6px;padding:14px 12px 13px;border:1px solid var(--wb-border-subtle,#eee);border-radius:9px;background:var(--wb-bg-popover,#fff)}','.wbs-token-stats-grid span{font-size:10.5px;color:var(--wb-icon-secondary,#667085)}','.wbs-token-stats-grid strong{font-size:17px;line-height:1.25;color:var(--wb-color-text-primary,#1f1f1f);font-variant-numeric:tabular-nums}.wbs-usage-columns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px;align-items:start}',+ '.wbs-usage-pie{display:grid;grid-template-columns:116px minmax(0,1fr);gap:14px;align-items:start;min-width:0}.wbs-pie-plot{width:116px;height:116px;margin-top:4px}.wbs-pie-plot svg{display:block;width:100%;height:100%;overflow:visible}.wbs-pie-slice{fill:var(--wbs-pie-color);stroke:var(--wb-bg-popover);stroke-width:1.5;outline:none;transition:opacity .12s,filter .12s}.has-pie-preview .wbs-pie-slice:not(.is-preview){opacity:.35}.wbs-pie-slice.is-preview,.wbs-pie-slice:focus-visible{fill:var(--wbs-pie-color);filter:drop-shadow(0 2px 3px rgba(0,0,0,.12))}.wbs-pie-subtitle{display:flex;align-items:baseline;flex-wrap:wrap;gap:6px;margin:-5px 0 12px;color:var(--wb-color-text-secondary);font-size:10px}.wbs-pie-subtitle strong{font-size:13px;font-weight:600;color:var(--wb-color-text-primary);font-variant-numeric:tabular-nums}.wbs-pie-tooltip{position:fixed;z-index:20;max-width:min(260px,calc(100vw - 24px));padding:9px 11px;border:1px solid var(--wb-border-subtle);border-radius:8px;background:var(--wb-bg-popover);color:var(--wb-color-text-primary);box-shadow:0 4px 16px rgba(0,0,0,.12);pointer-events:none;font-size:11px;line-height:1.6;overflow-wrap:anywhere}.wbs-pie-tooltip[hidden]{display:none}.wbs-pie-tooltip strong{font-weight:600}.wbs-pie-tooltip [data-pie-tip-detail]{color:var(--wb-color-text-secondary)}',+ '.wbs-pie-legend{min-width:0;overflow:visible}.wbs-pie-row{display:grid;grid-template-columns:8px minmax(0,1fr) auto 40px;gap:6px;align-items:center;min-height:33px;border-bottom:0;font-size:11px;color:var(--wb-color-text-primary)}.wbs-pie-row>i{width:7px;height:7px;border-radius:50%}.wbs-pie-name{min-width:0;overflow-wrap:anywhere;line-height:1.4}.wbs-pie-name small{display:block;font-size:10px;color:var(--wb-color-text-secondary);font-weight:400}.wbs-pie-row>b{font-weight:600;font-variant-numeric:tabular-nums}.wbs-pie-percent{text-align:right;color:var(--wb-color-text-secondary);font-variant-numeric:tabular-nums}.wbs-pie-other>summary{cursor:pointer;list-style:none}.wbs-pie-other>summary::-webkit-details-marker{display:none}.wbs-pie-other>summary .wbs-pie-name:before{content:"▸ ";color:var(--wb-icon-secondary)}.wbs-pie-other[open]>summary .wbs-pie-name:before{content:"▾ "}.wbs-pie-other>summary:hover{background:var(--wb-bg-hover)}.wbs-pie-other>summary:focus-visible{outline:2px solid var(--wb-accent-blue);outline-offset:-2px}.wbs-pie-details{padding-left:10px}',+ '.wbs-pie-row.is-preview{background:var(--wb-bg-hover);border-radius:5px}.wbs-pie-row{padding:3px 4px;box-sizing:border-box}@media(max-width:900px) and (min-width:701px),(max-width:420px){.wbs-usage-pie{grid-template-columns:90px minmax(0,1fr);gap:8px}.wbs-pie-plot{width:90px;height:90px}.wbs-pie-row{grid-template-columns:6px minmax(0,1fr) auto;gap:4px}.wbs-pie-percent{grid-column:3;font-size:10px}.wbs-pie-row>b{align-self:end}.wbs-pie-name{grid-row:span 2}}','.wbs-token-stats-section{margin-top:20px;border-top:1px solid var(--wb-border-subtle,#eee);padding-top:14px}.wbs-token-stats-section-title{font-size:12.5px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);margin-bottom:11px}',- '.wbs-token-stats-chart{display:block;height:176px;overflow-x:auto;overflow-y:hidden;padding:5px 12px;border:1px solid var(--wb-border-subtle,#eee);border-radius:10px;background:var(--wb-bg-secondary,#fafafa);scrollbar-width:none}.wbs-token-stats-chart::-webkit-scrollbar{display:none}.wbs-usage-trend-canvas{display:block;height:166px}.wbs-usage-trend-canvas:focus-visible{outline:2px solid var(--wbs-primary);outline-offset:-3px;border-radius:5px}.wbs-usage-trend-tooltip{width:max-content;min-width:104px;max-width:min(320px,calc(100vw - 20px));display:flex;flex-direction:column;gap:6px;padding:8px 11px;font-size:11px;line-height:1.35;pointer-events:none;white-space:nowrap}.wbs-usage-trend-tooltip[hidden]{display:none}.wbs-usage-trend-tooltip span{color:var(--wb-color-text-secondary,#5f6368)}.wbs-usage-trend-tooltip [data-trend-values]{display:flex;flex-direction:column;gap:3px}.wbs-usage-trend-tooltip [data-trend-values]>div{display:flex;justify-content:space-between;gap:18px}.wbs-usage-trend-tooltip [data-trend-values] span{max-width:180px;overflow:hidden;text-overflow:ellipsis}.wbs-usage-trend-tooltip strong{font-size:13px;font-variant-numeric:tabular-nums}',- '.wbs-token-model-scroll{position:relative;max-height:250px;overflow-y:auto;scrollbar-width:thin}.wbs-token-model-scroll:after{content:"";position:sticky;display:block;bottom:0;height:28px;margin-top:-28px;background:linear-gradient(to bottom,transparent,color-mix(in srgb,var(--wb-bg-popover,#fff) 92%,transparent));pointer-events:none;opacity:1;transition:opacity .16s}.wbs-token-model-scroll.at-end:after,.wbs-token-model-scroll.no-overflow:after{opacity:0}.wbs-token-stats-table{display:flex;flex-direction:column}.wbs-token-stats-table>div{display:grid;grid-template-columns:minmax(0,1fr) 88px 58px;gap:8px;align-items:center;min-height:30px;border-bottom:1px solid var(--wb-border-subtle,#eee);font-size:11px;color:var(--wb-color-text-secondary,#667085)}.wbs-token-stats-table>div:last-child{border-bottom:0}.wbs-token-stats-table span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-token-stats-table b{color:var(--wb-color-text-primary,#1f1f1f);font-variant-numeric:tabular-nums;text-align:right}.wbs-token-stats-table em{font-style:normal;color:var(--wb-icon-tertiary,#8a8f98);text-align:right}',+ '.wbs-token-stats-chart{display:block;height:176px;overflow-x:auto;overflow-y:hidden;padding:5px 12px;border:1px solid var(--wb-border-subtle,#eee);border-radius:10px;background:var(--wb-bg-secondary,#fafafa);scrollbar-width:none}.wbs-token-stats-chart::-webkit-scrollbar{display:none}.wbs-usage-trend-canvas{display:block;height:166px}.wbs-usage-trend-canvas:focus-visible{outline:2px solid var(--wb-color-text-primary);outline-offset:-3px;border-radius:5px}.wbs-usage-trend-tooltip{width:max-content;min-width:104px;max-width:min(320px,calc(100vw - 20px));display:flex;flex-direction:column;gap:6px;padding:8px 11px;font-size:11px;line-height:1.35;pointer-events:none;white-space:nowrap}.wbs-usage-trend-tooltip[hidden]{display:none}.wbs-usage-trend-tooltip span{color:var(--wb-color-text-secondary,#5f6368)}.wbs-usage-trend-tooltip [data-trend-values]{display:flex;flex-direction:column;gap:3px}.wbs-usage-trend-tooltip [data-trend-values]>div{display:flex;justify-content:space-between;gap:18px}.wbs-usage-trend-tooltip [data-trend-values] span{max-width:180px;overflow:hidden;text-overflow:ellipsis}.wbs-usage-trend-tooltip strong{font-size:13px;font-variant-numeric:tabular-nums}',+ '.wbs-token-model-scroll{position:relative;overflow:visible}.wbs-token-model-scroll:after{display:none}.wbs-token-stats-table{display:flex;flex-direction:column}.wbs-token-stats-table>div{display:grid;grid-template-columns:minmax(0,1fr) 88px 58px;gap:8px;align-items:center;min-height:30px;border-bottom:1px solid var(--wb-border-subtle,#eee);font-size:11px;color:var(--wb-color-text-secondary,#667085)}.wbs-token-stats-table>div:last-child{border-bottom:0}.wbs-token-stats-table span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-token-stats-table b{color:var(--wb-color-text-primary,#1f1f1f);font-variant-numeric:tabular-nums;text-align:right}.wbs-token-stats-table em{font-style:normal;color:var(--wb-icon-tertiary,#8a8f98);text-align:right}','.wbs-token-stats-loading{min-height:410px;display:flex;align-items:center;justify-content:center;color:var(--wb-icon-secondary,#667085);font-size:12px}.wbs-token-stats-content{position:relative;min-height:410px}.wbs-token-stats-body{min-height:410px}.wbs-token-stats-overlay{position:absolute;inset:0;z-index:2;display:flex;align-items:center;justify-content:center;border-radius:9px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 38%,transparent);color:var(--wb-icon-secondary,#667085);backdrop-filter:blur(1.5px);-webkit-backdrop-filter:blur(1.5px)}.wbs-token-stats-overlay[hidden],.wbs-token-stats-overlay span[hidden]{display:none!important}.wbs-token-stats-spinner{display:flex;flex-direction:column;align-items:center;gap:10px;color:var(--wb-icon-secondary,#667085);font-size:11px}.wbs-token-stats-spinner svg{width:24px;height:24px;animation:wbs-token-spin .8s linear infinite;color:var(--wb-icon-secondary,#667085)}.wbs-token-stats-spinner circle{fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-dasharray:36 22}@keyframes wbs-token-spin{to{transform:rotate(360deg)}}.wbs-token-stats-empty{font-size:12px;line-height:1.6;color:var(--wb-icon-tertiary,#8a8f98)}.wbs-token-empty-trend{margin:auto;text-align:center}.wbs-token-empty-model{display:flex!important;align-items:center;justify-content:center;min-height:150px;text-align:center}.wbs-token-model-scroll.no-overflow:has(.wbs-token-empty-model){max-height:none}','html.cb-dark #wbs-token-stats-modal,html[data-theme="dark"] #wbs-token-stats-modal,body[data-vscode-theme-name*="dark" i] #wbs-token-stats-modal{color-scheme:dark;background:rgba(0,0,0,.56)}#wbs-token-stats-modal .wbs-token-stats-modal{box-sizing:border-box}.wbs-token-stats-modal{position:relative}.wbs-credit-stats-toolbar{display:flex;gap:8px;align-items:center;justify-content:space-between;flex-wrap:wrap;font-size:11px;color:var(--wb-icon-secondary,#667085)}.wbs-token-stats-grid.wbs-credit-stats-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.wbs-credit-chart{height:176px}.wbs-credit-sync{height:auto;min-height:28px;white-space:normal}.wbs-credit-sync-overlay{position:absolute;inset:0;z-index:5;display:flex;align-items:center;justify-content:center;padding:16px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 84%,transparent);backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);border-radius:inherit;pointer-events:auto}.wbs-credit-sync-overlay[hidden],[data-credit-result][hidden],[data-usage-pane][hidden]{display:none!important}.wbs-credit-sync-progress{display:flex;flex-direction:column;align-items:stretch;gap:12px;width:min(100%,340px);font-size:12px;line-height:1.6;overflow-wrap:anywhere;color:var(--wb-color-text-primary,#1f1f1f)}.wbs-credit-sync-progress>span{color:var(--wb-icon-secondary,#667085)}.wbs-credit-sync-progress progress{width:100%;height:8px;accent-color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-credit-sync-progress button{align-self:center}.wbs-usage-tabs button:focus-visible,.wbs-credit-sync:focus-visible{outline:2px solid var(--wb-color-text-primary,#1f1f1f);outline-offset:2px}','@media(max-width:700px){.wbs-usage-modal-mask{padding:12px}.wbs-usage-columns{grid-template-columns:1fr}.wbs-token-stats-modal{width:calc(100vw - 24px);max-width:calc(100vw - 24px);height:calc(100vh - 24px);max-height:calc(100vh - 24px)}.wbs-token-stats-grid{grid-template-columns:repeat(3,minmax(0,1fr))}}','@media(max-width:620px){.wbs-usage-header{padding:14px 14px 0}.wbs-usage-scroll{padding:4px 14px 14px}.wbs-token-stats-modal>.wbs-modal-actions{padding:10px 14px}.wbs-trend-controls{flex-direction:column}.wbs-trend-legend{width:100%;flex:none}.wbs-usage-segment button{min-width:0}}','.wbs-modal.wbs-auto-discovery-modal{display:flex;flex-direction:column;width:min(980px,calc(100vw - 48px));max-width:calc(100vw - 48px);height:min(84vh,800px);max-height:calc(100vh - 48px);gap:0;padding:0;border:1px solid var(--wb-border-default,rgba(20,24,32,.14));border-radius:16px;box-shadow:0 24px 80px rgba(15,18,24,.22)}.wbs-auto-discovery-header{padding-bottom:14px}.wbs-auto-discovery-header .wbs-auto-modal-head{align-items:center;flex-wrap:wrap}.wbs-auto-discovery-head-actions{display:flex;align-items:center;gap:10px}.wbs-auto-discovery-header .wbs-auto-textbtn{white-space:normal;text-align:right}.wbs-auto-discovery-list{flex:1;gap:8px;padding-top:14px;scrollbar-width:thin;overscroll-behavior:contain}.wbs-auto-discovery-item{padding:13px 14px}.wbs-auto-discovery-pagination{display:flex;align-items:center;justify-content:flex-end;gap:8px;margin:0}.wbs-auto-discovery-total{margin-right:auto;font-size:11px;color:var(--wb-color-text-secondary,#666)}.wbs-auto-discovery-page{min-width:36px;text-align:center;font-size:11px;font-variant-numeric:tabular-nums;color:var(--wb-color-text-secondary,#666)}.wbs-auto-discovery-pagination .wbs-modal-btn{min-width:54px;margin:0}.wbs-auto-discovery-pagination .wbs-modal-btn:disabled{opacity:.45;cursor:not-allowed}.wbs-auto-discovery-pagination .wbs-modal-btn:focus-visible,.wbs-auto-discovery-header button:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}',- '.wbs-auto-discovery-head-actions [data-auto-discovery-guide]{display:inline-flex;align-items:center;justify-content:center;min-height:30px;padding:6px 11px;border:1px solid var(--wb-button-primary-bg,#1f1f1f);border-radius:7px;background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);font:inherit;font-size:11px;font-weight:600;text-decoration:none;white-space:nowrap;cursor:pointer;box-shadow:0 1px 2px rgba(0,0,0,.12)}.wbs-auto-discovery-head-actions [data-auto-discovery-guide]:hover{background:var(--wb-button-primary-hover-bg,var(--wb-button-primary-bg,#1f1f1f));color:var(--wb-button-primary-fg,#fff)}.wbs-auto-discovery-head-actions [data-auto-discovery-guide]:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}',+ '.wbs-auto-discovery-head-actions [data-auto-discovery-guide]{display:inline-flex;align-items:center;justify-content:center;min-height:30px;padding:6px 11px;border:1px solid var(--wb-button-primary-bg,#1f1f1f);border-radius:7px;background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);font:inherit;font-size:11px;font-weight:600;text-decoration:none;white-space:nowrap;cursor:pointer;box-shadow:0 1px 2px rgba(0,0,0,.12)}.wbs-auto-discovery-head-actions [data-auto-discovery-guide]:hover{background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#1f1f1f));color:var(--wb-button-primary-fg,#fff)}.wbs-auto-discovery-head-actions [data-auto-discovery-guide]:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}','.wbs-modal.wbs-auto-guide-modal{box-sizing:border-box;width:min(520px,calc(100vw - 32px));max-width:calc(100vw - 32px);max-height:calc(100vh - 32px);overflow:auto;padding:18px 20px}.wbs-auto-guide-body{font-size:12px;line-height:1.65;color:var(--wb-color-text-secondary,#666);overflow-wrap:anywhere}.wbs-auto-guide-body p{margin:0 0 10px}.wbs-auto-guide-body .wbs-auto-textbtn{padding:0;color:var(--wb-color-text-primary,#1f1f1f);text-decoration:underline;overflow-wrap:anywhere;text-align:left}.wbs-auto-guide-modal .wbs-modal-actions{margin-top:12px}.wbs-auto-guide-body .wbs-auto-textbtn:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}','.wbs-auto-guide-body ol{margin:8px 0 0;padding-left:20px}.wbs-auto-guide-body li{margin:0 0 8px;padding-left:2px}.wbs-auto-guide-body code{padding:2px 4px;border-radius:4px;background:var(--wb-bg-tertiary,#f2f3f5);color:var(--wb-color-text-primary,#1f1f1f);font:10.5px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}','html.cb-dark #wbs-auto-discovery-mask,html[data-theme="dark"] #wbs-auto-discovery-mask,body[data-vscode-theme-name*="dark" i] #wbs-auto-discovery-mask,html.cb-dark #wbs-auto-discovery-guide,html[data-theme="dark"] #wbs-auto-discovery-guide,body[data-vscode-theme-name*="dark" i] #wbs-auto-discovery-guide{color-scheme:dark;background:rgba(0,0,0,.56)}html.cb-dark .wbs-auto-discovery-version,html[data-theme="dark"] .wbs-auto-discovery-version,body[data-vscode-theme-name*="dark" i] .wbs-auto-discovery-version{border-color:var(--wb-border-subtle,rgba(255,255,255,.18));background:var(--wb-bg-tertiary,#303137);color:var(--wb-color-text-secondary,#d0d0d5)}',@@ -16234,6 +17019,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-login-link{color:var(--wb-accent-blue,#4f86ff);text-decoration:none;font-weight:600}','.wbs-login-link:hover{text-decoration:underline}','.wbs-empty{text-align:center;color:var(--wb-icon-tertiary,#999);padding:28px 10px;font-size:12px}',+ // 主操作的交互色使用 WorkBuddy 正式 token;禁用态放在悬浮态之后,避免鼠标覆盖禁用颜色。+ ':is(.wbs-modal-btn.wbs-modal-ok,.wbs-account-note-footer .primary,.wbs-sess-bbtn.active,.wbs-sess-done,.wbs-acc-switch.armed,.wbs-token-stats-search,.wbs-growth-task-action,.wbs-auto-normal-actions .wbs-auto-pick-btn,.wbs-update-btn,.wbs-credit-rotation-switch,.wbs-auto-discovery-head-actions [data-auto-discovery-guide]):hover:not(:disabled){background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#2a2a2e));border-color:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#2a2a2e));color:var(--wb-button-primary-fg,#fff);opacity:1}',+ ':is(.wbs-modal-btn.wbs-modal-ok,.wbs-account-note-footer .primary,.wbs-sess-bbtn.active,.wbs-sess-done,.wbs-acc-switch.armed,.wbs-token-stats-search,.wbs-growth-task-action,.wbs-auto-normal-actions .wbs-auto-pick-btn,.wbs-update-btn,.wbs-credit-rotation-switch,.wbs-auto-discovery-head-actions [data-auto-discovery-guide]):disabled{background:var(--wb-button-primary-bg-disabled,color-mix(in srgb,var(--wb-button-primary-bg,#141416) 25%,transparent));border-color:var(--wb-button-primary-bg-disabled,color-mix(in srgb,var(--wb-button-primary-bg,#141416) 25%,transparent));color:var(--wb-button-primary-fg-disabled,var(--wb-button-primary-fg,#fff));opacity:1}',/* body 高度:无底部功能区后最大化 */'.wbs-body{max-height:calc(min(78vh,660px) - 118px)}',// 账号页填满面板剩余空间:少量账号时登录按钮靠底部,长列表仍在列表内滚动。diff --git a/scripts/lib.js b/scripts/lib.jsindex 5462f9e..4cab5f2 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -1652,6 +1652,18 @@ function setAccountOrder(dataDir, value) {return getAccountOrder(dataDir);}+/** 备注仅写入当前 profile 的元数据,保留认证备份和其他账号设置。 */+function setAccountNote(dataDir, value) {+ if (!value || typeof value.uid !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(value.uid) ||+ ['__proto__', 'prototype', 'constructor'].includes(value.uid)) throw new Error('无效的账号');+ if (typeof value.note !== 'string' || value.note.length > 2000) throw new Error('备注不能超过 2000 个字符');+ if (!fs.existsSync(backupPath(dataDir, value.uid))) throw new Error('账号不存在或已删除');+ const meta = readMeta(dataDir);+ meta.accounts[value.uid] = Object.assign({}, meta.accounts[value.uid], { note: value.note });+ writeMeta(dataDir, meta);+ return { uid: value.uid, note: value.note };+}+/** 列出所有已备份账号(直接读备份文件提取展示字段,按最近刷新时间倒序) */function listAccounts(dataDir) {if (!ACTIVE_PROFILE.capabilities.accounts) return [];@@ -1672,6 +1684,7 @@ function listAccounts(dataDir) {const item = {uid,sort: Number.isSafeInteger(savedSort) && savedSort > 0 ? savedSort : 0,+ note: typeof (orderMeta.accounts[uid] || {}).note === 'string' ? orderMeta.accounts[uid].note : '',nickname: '',phone: '',uin: '',@@ -1863,6 +1876,7 @@ module.exports = {wdCompatDecryptAuthJson, // [wd-compat]getAccountOrder,setAccountOrder,+ setAccountNote,readModelsFile,writeModelsFile,writeModelBackup,diff --git a/scripts/session-sync.js b/scripts/session-sync.jsindex 861eceb..9481a0f 100644--- a/scripts/session-sync.js+++ b/scripts/session-sync.js@@ -8,6 +8,8 @@ const crypto = require('node:crypto');const { StringDecoder } = require('node:string_decoder');const identityKeys = new Set(['sessionId', 'conversationId', 'ownerConversationId', 'session_id', 'conversation_id']);const SKIP_LOCAL_DIR = /^workspace\/sessions\/[^/]+\/(?:modify_backup|\.modify_backup_meta)$/;+const SYNC_BACKUP_DIR = /^sync-[A-Za-z0-9_-]+$/;+const DEFAULT_SYNC_BACKUP_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');// WorkBuddy appends session-meta lifecycle records when a conversation is@@ -683,10 +685,103 @@ function unchanged(snapshot) {return now.files.size === snapshot.files.size && [...snapshot.files].every(([key, file]) => now.files.get(key)?.hash === file.hash);}+function removeSyncBackup(backup) {+ try { fs.rmSync(backup, { recursive: true, force: true }); } catch (_) {}+}++async function removeSyncBackupAsync(backup) {+ try { await fs.promises.rm(backup, { recursive: true, force: true }); } catch (_) {}+}++// Successful and fully rolled-back syncs have no remaining reader for their+// snapshots. Keep only recovery-needed backups, and age out crash leftovers+// when the daemon starts so old versions cannot grow the data directory forever.+function pruneSyncBackups(backupRoot, options = {}) {+ const now = Number.isFinite(options.now) ? options.now : Date.now();+ const maxAgeMs = Number.isFinite(options.maxAgeMs) && options.maxAgeMs >= 0+ ? options.maxAgeMs : DEFAULT_SYNC_BACKUP_MAX_AGE_MS;+ const result = { removed: 0, retainedRecovery: 0 };+ let entries;+ try { entries = fs.readdirSync(backupRoot, { withFileTypes: true }); }+ catch (_) { return result; }+ for (const entry of entries) {+ if (!entry.isDirectory() || !SYNC_BACKUP_DIR.test(entry.name)) continue;+ const backup = path.join(backupRoot, entry.name);+ let status = '';+ try {+ const journal = JSON.parse(fs.readFileSync(path.join(backup, 'journal.json'), 'utf8'));+ status = typeof journal.status === 'string' ? journal.status : '';+ } catch (_) {}+ if (status === 'recovery-needed') { result.retainedRecovery++; continue; }+ let ageMs = 0;+ try { ageMs = Math.max(0, now - fs.statSync(backup).mtimeMs); } catch (_) { continue; }+ const remove = status === 'committed' || status === 'rolled-back' ||+ (ageMs >= maxAgeMs && (status === 'prepared' || !status));+ if (!remove) continue;+ try { fs.rmSync(backup, { recursive: true, force: true }); result.removed++; } catch (_) {}+ }+ return result;+}++// Return lightweight operational metadata for the local rollback area. This+// deliberately reads directory entries and stat metadata only; backup+// contents never leave the machine and are never included in the response.+function inspectSyncBackups(backupRoot) {+ const result = { count: 0, totalBytes: 0, recoveryCount: 0, recoveryBytes: 0, pendingCount: 0 };+ let entries;+ try { entries = fs.readdirSync(backupRoot, { withFileTypes: true }); }+ catch (_) { return result; }+ const sizeOf = (file) => {+ let info;+ try { info = fs.lstatSync(file); } catch (_) { return 0; }+ if (info.isSymbolicLink()) return 0;+ if (info.isFile()) return info.size;+ if (!info.isDirectory()) return 0;+ let total = 0;+ let children;+ try { children = fs.readdirSync(file); } catch (_) { return 0; }+ for (const child of children) total += sizeOf(path.join(file, child));+ return total;+ };+ for (const entry of entries) {+ if (!entry.isDirectory() || !SYNC_BACKUP_DIR.test(entry.name)) continue;+ const backup = path.join(backupRoot, entry.name);+ let status = '';+ try {+ const journal = JSON.parse(fs.readFileSync(path.join(backup, 'journal.json'), 'utf8'));+ status = typeof journal.status === 'string' ? journal.status : '';+ } catch (_) {}+ const bytes = sizeOf(backup);+ result.count++;+ result.totalBytes += bytes;+ if (status === 'recovery-needed') {+ result.recoveryCount++;+ result.recoveryBytes += bytes;+ } else if (status === 'prepared' || !status) {+ result.pendingCount++;+ }+ }+ return result;+}+function targetRelative(logical, id) {return logical.split('/').map(part => part === '__session__' ? id : part === '__session__.jsonl' ? id + '.jsonl' : part === '__session__.json' ? id + '.json' : part).join('/');}+function changedTargetFiles(changes, target) {+ const entries = [];+ const seen = new Set();+ for (const change of changes) {+ if (seen.has(change.key)) continue;+ seen.add(change.key);+ const file = target.files.get(change.key);+ // New source files have no old target bytes to restore. Only files that+ // will be overwritten or deleted need a rollback copy.+ if (file) entries.push([change.key, file]);+ }+ return entries;+}+function targetBytes(key, file, source, target) {if (key !== 'artifact-index/__session__.json') return file.bytes;const index = JSON.parse(file.bytes.toString('utf8'));@@ -712,18 +807,19 @@ async function applySnapshot(source, target, options) {if (!missingOnly) for (const [key, file] of target.files) {if (!source.files.has(key)) changes.push({ key, relative: file.relative, bytes: null });}+ const backupEntries = changedTargetFiles(changes, target);await guard();if (!unchanged(source) || !unchanged(target)) throw Error('会话文件正在变化,请稍后重试');fs.mkdirSync(backupRoot, { recursive: true, mode: 0o700 });const backup = fs.mkdtempSync(path.join(backupRoot, 'sync-'));fs.chmodSync(backup, 0o700);- for (const [key, file] of target.files) {+ for (const [key, file] of backupEntries) {const filePath = safePath(backup, 'files/' + key);fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });fs.writeFileSync(filePath, file.bytes, { mode: 0o600, flag: 'wx' });}const journal = { version: 1, sourceId: source.id, targetId: target.id, status: 'prepared', metadata: options.metadata || null,- files: [...target.files].map(([key, file]) => ({ key, relative: file.relative, mode: file.mode, mtimeMs: file.mtimeMs })),+ files: backupEntries.map(([key, file]) => ({ key, relative: file.relative, mode: file.mode, mtimeMs: file.mtimeMs })),changes: changes.map(change => ({ relative: change.relative, hash: change.bytes === null ? null : digest(change.bytes) })) };const journalFile = path.join(backup, 'journal.json');const save = () => fs.writeFileSync(journalFile, JSON.stringify(journal), { mode: 0o600 });@@ -773,6 +869,7 @@ 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; }+ removeSyncBackup(backup);// 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);@@ -793,6 +890,7 @@ async function applySnapshot(source, target, options) {}journal.status = incomplete ? 'recovery-needed' : 'rolled-back';try { save(); } catch (_) { /* Keep the original failure and retained backup. */ }+ if (!incomplete) removeSyncBackup(backup);throw error;}}@@ -838,12 +936,13 @@ async function applySnapshotAsync(source, target, options) {if (!missingOnly) for (const [key, file] of target.files) {if (!source.files.has(key)) changes.push({ key, relative: file.relative, bytes: null, sourceFile: null, hash: null, size: 0 });}+ const backupEntries = changedTargetFiles(changes, target);await guard();if (!await unchangedAsync(source) || !await unchangedAsync(target)) throw Error('会话文件正在变化,请稍后重试');await fs.promises.mkdir(backupRoot, { recursive: true, mode: 0o700 });const backup = await fs.promises.mkdtemp(path.join(backupRoot, 'sync-'));await fs.promises.chmod(backup, 0o700);- for (const [key, file] of target.files) {+ for (const [key, file] of backupEntries) {const filePath = await safePathAsync(backup, 'files/' + key);await fs.promises.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });await fs.promises.copyFile(file.sourcePath, filePath, fs.constants.COPYFILE_EXCL);@@ -852,7 +951,7 @@ async function applySnapshotAsync(source, target, options) {}const journal = {version: 1, sourceId: source.id, targetId: target.id, status: 'prepared', metadata: options.metadata || null,- files: [...target.files].map(([key, file]) => ({ key, relative: file.relative, mode: file.mode, mtimeMs: file.mtimeMs })),+ files: backupEntries.map(([key, file]) => ({ key, relative: file.relative, mode: file.mode, mtimeMs: file.mtimeMs })),changes: changes.map(change => ({ relative: change.relative, hash: change.hash })),};const journalFile = path.join(backup, 'journal.json');@@ -905,6 +1004,7 @@ async function applySnapshotAsync(source, target, options) {journal.status = 'committed';let journalPending = false;try { await save(); } catch (_) { journalPending = true; }+ await removeSyncBackupAsync(backup);const copiedBytes = changes.reduce((sum, change) => sum + (change.hash === null ? 0 : change.size), 0);return { backup, copied: changes.length, copiedBytes, journalPending, totalBytes };} catch (error) {@@ -926,11 +1026,12 @@ async function applySnapshotAsync(source, target, options) {}journal.status = incomplete ? 'recovery-needed' : 'rolled-back';try { await save(); } catch (_) { /* Keep the original failure and retained backup. */ }+ if (!incomplete) await removeSyncBackupAsync(backup);throw error;}}module.exports = {readSessionSizes, readSnapshot, readSnapshotAsync, readSessionFingerprintAsync, readSessionQuickFingerprintAsync, compareSnapshots, selectTargetSnapshot,- applySnapshot, applySnapshotAsync,+ applySnapshot, applySnapshotAsync, pruneSyncBackups, inspectSyncBackups,};diff --git a/scripts/session-transfer.js b/scripts/session-transfer.jsindex a2c2888..3cf53d6 100644--- a/scripts/session-transfer.js+++ b/scripts/session-transfer.js@@ -61,11 +61,13 @@ class ChunkReader {async close() { if (this.iterator.return) await this.iterator.return(); }}-async function* archiveChunks(sessions) {+async function* archiveChunks(sessions, options = {}) {+ let processedBytes = 0;yield frame({ type: 'archive', version: 4, count: sessions.length });for (const session of sessions) {yield frame({ type: 'session', record: session.record, count: session.files.length });for (const file of session.files) {+ options.signal?.throwIfAborted();remapSessionArchivePath(file.path, session.record.id, session.record.id);const handle = await fs.promises.open(file.source, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));try {@@ -75,7 +77,10 @@ async function* archiveChunks(sessions) {let total = 0;if (stat.size) {for await (const chunk of handle.createReadStream({ autoClose: false, start: 0, end: stat.size - 1 })) {- total += chunk.length; yield chunk;+ options.signal?.throwIfAborted();+ total += chunk.length; processedBytes += chunk.length;+ if (options.onProgress) options.onProgress(processedBytes);+ yield chunk;}}const after = await handle.stat();@@ -85,7 +90,7 @@ async function* archiveChunks(sessions) {}}-async function writeSessionTransfer(file, sessions, password) {+async function writeSessionTransfer(file, sessions, password, options = {}) {requiredPassword(password);if (!Array.isArray(sessions) || !sessions.length || sessions.length > 100) throw new Error('单次最多导出 100 个会话');const header = Buffer.alloc(HEADER_SIZE); MAGIC.copy(header);@@ -95,9 +100,10 @@ async function writeSessionTransfer(file, sessions, password) {cipher.setAAD(header.subarray(0, 36));let created = false;try {+ options.signal?.throwIfAborted();await fs.promises.writeFile(file, header, { flag: 'wx', mode: 0o600 }); created = true;- await pipeline(Readable.from(archiveChunks(sessions)), zlib.createGzip(), cipher,- fs.createWriteStream(file, { flags: 'r+', start: HEADER_SIZE }));+ await pipeline(Readable.from(archiveChunks(sessions, options)), zlib.createGzip(), cipher,+ fs.createWriteStream(file, { flags: 'r+', start: HEADER_SIZE }), { signal: options.signal });const handle = await fs.promises.open(file, 'r+');try { await handle.write(cipher.getAuthTag(), 0, 16, 36); } finally { await handle.close(); }} catch (error) {@@ -186,4 +192,68 @@ async function receiveSessionUpload(input, directory) {}}-module.exports = { writeSessionTransfer, readSessionTransfer, receiveSessionUpload };+// Jobs belong to the daemon, so closing/reloading the renderer cannot abort an+// export. Only bounded progress metadata crosses HTTP; passwords stay in the task.+function createSessionExportJobs({ prepare, directory, brand = 'WorkDaddy', write = writeSessionTransfer }) {+ const jobs = new Map();+ let latest = null, active = null, pending = Promise.resolve();+ const publicJob = job => job ? { ...job } : null;+ function get(id) { return publicJob(id ? jobs.get(id) : latest); }+ function start(ids, password) {+ requiredPassword(password);+ if (active) throw new Error('正在导出会话,请等待完成或取消');+ const job = { id: crypto.randomUUID(), status: 'preparing', running: true, count: 0,+ processedBytes: 0, totalBytes: 0, percent: 0, file: '', error: '', startedAt: Date.now() };+ const controller = new AbortController();+ active = { job, controller }; latest = job; jobs.set(job.id, job);+ while (jobs.size > 10) jobs.delete(jobs.keys().next().value);+ pending = (async () => {+ let staging;+ try {+ // Yield before collecting files or deriving keys, letting POST return immediately.+ await new Promise(resolve => setImmediate(resolve));+ controller.signal.throwIfAborted();+ const sessions = await prepare(ids);+ controller.signal.throwIfAborted();+ job.count = sessions.length;+ job.totalBytes = sessions.reduce((sum, session) => sum + session.files.reduce((bytes, file) => bytes + file.size, 0), 0);+ const outputDir = path.resolve(await directory());+ await fs.promises.mkdir(outputDir, { recursive: true, mode: 0o700 });+ staging = await fs.promises.mkdtemp(path.join(outputDir, '.workdaddy-export-'));+ await fs.promises.chmod(staging, 0o700);+ const stagedFile = path.join(staging, 'archive.wds');+ job.status = 'writing';+ await write(stagedFile, sessions, password, { signal: controller.signal, onProgress(bytes) {+ job.processedBytes = bytes;+ job.percent = job.totalBytes ? Math.min(99, Math.floor(bytes / job.totalBytes * 100)) : 0;+ } });+ controller.signal.throwIfAborted();+ const filename = brand.replace(/[^A-Za-z0-9_-]/g, '-') + '-sessions-' ++ new Date(job.startedAt).toISOString().replace(/[:.]/g, '-') + '-' + job.id + '.wds';+ const destination = path.join(outputDir, filename);+ // Same-volume exclusive publication: never replace an existing download,+ // and never expose the final filename before GCM authentication is sealed.+ await fs.promises.link(stagedFile, destination);+ job.file = destination; job.status = 'completed'; job.percent = 100;+ } catch (error) {+ job.status = controller.signal.aborted ? 'cancelled' : 'failed';+ job.error = controller.signal.aborted ? '' : error.code === 'ENOSPC' ? '下载目录空间不足,请释放空间后重试' : String(error.message || '会话导出失败');+ } finally {+ password = null;+ if (staging) await fs.promises.rm(staging, { recursive: true, force: true }).catch(() => {});+ job.running = false; active = null;+ }+ return publicJob(job);+ })();+ return publicJob(job);+ }+ function cancel(id) {+ if (active && active.job.id === id && active.job.status !== 'completed') {+ active.job.status = 'cancelling'; active.controller.abort();+ }+ return get(id);+ }+ return { start, get, cancel, wait: () => pending };+}++module.exports = { writeSessionTransfer, readSessionTransfer, receiveSessionUpload, createSessionExportJobs };diff --git a/scripts/theme-patches.js b/scripts/theme-patches.jsindex 1b65f1c..ea2c695 100644--- a/scripts/theme-patches.js+++ b/scripts/theme-patches.js@@ -69,8 +69,8 @@ module.exports = [},{id: 'patch-15',- desc: '弹窗/tooltip 通用深色适配:dropdown/popover/popper/picker-panel/menu-panel 背景默认白,深色下覆盖。排除官方新组件体系(cr-theme/cr-popover/cr-menu——官方自带深色适配)与官方 hash 触发器容器(_dropdownRoot_——仅定位容器,不应着色,否则更多按钮出现黑底)',- css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="toolbar"]):not([class*="cr-theme"]):not([class*="_dropdownRoot_"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"]:not([class*="cr-theme"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="popper"]:not([class*="cr-theme"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="picker-panel"]:not([class*="cr-theme"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="menu-panel"]:not([class*="cr-theme"]){background:var(--wb-bg-popover) !important;color:var(--wb-color-text-primary);border-color:var(--wb-border-subtle) !important;box-shadow:0 6px 24px rgba(0,0,0,0.5) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="tooltip"]:not([class*="chat"]):not([class*="message"]){background:var(--wb-bg-popover) !important;color:var(--wb-color-text-primary);}html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]):not([class*="_dropdownRoot_"]) [class*="item"]:hover,html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"]:not([class*="cr-theme"]) [class*="item"]:hover{background:var(--wb-bg-hover) !important;}',+ desc: '弹窗/tooltip 通用深色适配:dropdown/popover/popper/picker-panel/menu-panel 背景默认白,深色下覆盖。排除官方新组件体系(cr-theme/cr-popover/cr-menu——官方自带深色适配)与官方 hash/tooltip 触发器容器(仅定位容器,不应着色,否则文件链接、复制与发送按钮出现黑底)',+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="toolbar"]):not([class*="cr-theme"]):not([class*="_dropdownRoot_"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"]:not([class*="cr-theme"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="popper"]:not([class*="cr-theme"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="picker-panel"]:not([class*="cr-theme"]),html[data-theme="dark"] body[data-vscode-theme-name] [class*="menu-panel"]:not([class*="cr-theme"]){background:var(--wb-bg-popover) !important;color:var(--wb-color-text-primary);border-color:var(--wb-border-subtle) !important;box-shadow:0 6px 24px rgba(0,0,0,0.5) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="tooltip"]:not([class*="chat"]):not([class*="message"]):not(.cr-clickable-path-tooltip-anchor):not(.cr-code-block__copy-tooltip):not(.cr-send-button__tooltip-wrapper){background:var(--wb-bg-popover) !important;color:var(--wb-color-text-primary);}html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]):not([class*="_dropdownRoot_"]) [class*="item"]:hover,html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"]:not([class*="cr-theme"]) [class*="item"]:hover{background:var(--wb-bg-hover) !important;}',},{id: 'patch-16',@@ -192,11 +192,6 @@ module.exports = [desc: '输入框父组件(_input-area-container--opaque-main-area)透明;输入框主体 _mainArea 改毛玻璃(用户要求:父透明 + 输入框本体毛玻璃)。加 dark 前缀提特异性,压过 bgCssStr 后注入的 40% 背景',css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="_input-area-container_"]{background:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="_input-area-container_"] [class*="_mainArea_"]{background:color-mix(in srgb,var(--wb-bg-primary) 40%,transparent) !important;backdrop-filter:blur(20px) saturate(1.15) !important;-webkit-backdrop-filter:blur(20px) saturate(1.15) !important;}',},- {- id: 'patch-41',- desc: '插件暂存按钮(wbs-stash-inline)深色下改毛玻璃背景:半透明 bg-primary + backdrop blur,与输入框毛玻璃一致;颜色/阴影走主题变量',- css: 'html[data-theme="dark"] body[data-vscode-theme-name] .wbs-stash-inline{background:color-mix(in srgb,var(--wb-bg-primary) 62%,transparent) !important;color:var(--wb-color-text-primary) !important;backdrop-filter:blur(16px) saturate(1.15) !important;-webkit-backdrop-filter:blur(16px) saturate(1.15) !important;box-shadow:0 1px 4px rgba(0,0,0,0.4) !important;}',- },{id: 'patch-42',desc: '深色菜单弹窗(popover/dropdown 面板)背景已深色但内部文字/图标可能硬编码深色看不清:对 wb-dropdown 系弹窗全元素强制浅色(label/button/span/svg 全覆盖)',@@ -508,6 +503,18 @@ module.exports = [desc: '毛玻璃主题下左侧模板切换按钮与代码块复制提示去掉官方背景色,避免出现实心色块',css: ':is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container .industry-template-switcher__host>button.wb-button.wb-button--secondary,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container .industry-template-switcher__host>button.wb-button.wb-button--secondary:hover,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container .industry-template-switcher__host>button.wb-button.wb-button--secondary:focus-visible,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container .industry-template-switcher__host>button.wb-button.wb-button--secondary:active,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .cr-code-like-box__header>span.cr-code-block__copy-tooltip,:is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .cr-code-like-box__header>span.cr-code-block__copy-tooltip:hover,body[data-vscode-theme-name="IDE Night"] .teams-container .industry-template-switcher__host>button.wb-button.wb-button--secondary,body[data-vscode-theme-name="IDE Night"] .teams-container .industry-template-switcher__host>button.wb-button.wb-button--secondary:hover,body[data-vscode-theme-name="IDE Night"] .teams-container .industry-template-switcher__host>button.wb-button.wb-button--secondary:focus-visible,body[data-vscode-theme-name="IDE Night"] .teams-container .industry-template-switcher__host>button.wb-button.wb-button--secondary:active,body[data-vscode-theme-name="IDE Night"] .cr-code-like-box__header>span.cr-code-block__copy-tooltip,body[data-vscode-theme-name="IDE Night"] .cr-code-like-box__header>span.cr-code-block__copy-tooltip:hover{background:transparent !important;background-color:transparent !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;box-shadow:none !important;}',},+ {+ id: 'patch-105',+ themeId: 'nebula',+ desc: '毛玻璃发送按钮的实心圆底来自 SVG 复合路径;只保留原图的箭头子路径,停止/语音等其他图标不匹配。移除主题样式即恢复官方图标。',+ css: 'html[data-wbs-theme-id="nebula"] .cr-send-button__icon svg[viewBox="0 0 32 32"]>path[d^="M16 32C24.8366"]{d:path("M16 19.2104C15.5529 19.2104 15.1342 19.4074 14.2968 19.8015L12.9369 20.4415C12.6768 20.5639 12.4283 20.6835 12.1915 20.7975C10.6375 21.5456 9.588 22.0508 9.0686 21.5057C8.5493 20.9605 9.1048 19.9367 9.9273 18.4208C10.0527 18.1898 10.1842 17.9474 10.3191 17.6935L14.2338 10.3247C14.3137 10.1743 14.3891 10.03 14.461 9.8925C15.0315 8.8018 15.3821 8.1315 16 8.1315C16.6179 8.1315 16.9685 8.8018 17.539 9.8925C17.6109 10.03 17.6863 10.1743 17.7662 10.3247L21.6809 17.6935C21.8158 17.9474 21.9473 18.1898 22.0727 18.4208C22.8952 19.9367 23.4507 20.9605 22.9314 21.5057C22.412 22.0508 21.3625 21.5456 19.8085 20.7975C19.5717 20.6835 19.3232 20.5639 19.0631 20.4415L17.7032 19.8015C16.8658 19.4074 16.4471 19.2104 16 19.2104Z") !important;fill:var(--wb-button-primary-fg) !important;}',+ },+ {+ id: 'patch-106',+ themeId: 'nebula',+ desc: '毛玻璃下文件链接与代码复制控件透明:外层 tooltip 触发器不应有弹窗底色,内层文件标签使用独立的 cr-symbol 背景变量,也需单独清除。',+ css: 'html[data-wbs-theme-id="nebula"] body[data-vscode-theme-name] .cr-clickable-path-tooltip-anchor,html[data-wbs-theme-id="nebula"] body[data-vscode-theme-name] .cr-clickable-path,html[data-wbs-theme-id="nebula"] body[data-vscode-theme-name] .cr-code-block__copy-tooltip,html[data-wbs-theme-id="nebula"] body[data-vscode-theme-name] .cr-code-block__copy-button{background:transparent !important;}',+ },/* 原 patch-82(AI 端快捷短语弹层 z-index 抬升)已移入 inject.js 常驻样式:theme-patches 仅在非默认主题时注入,默认浅色主题下会失效;层级修复不依赖主题,随注入脚本常驻更可靠。 */];diff --git a/scripts/theme-vars.js b/scripts/theme-vars.jsindex 07cbac6..92f9a9d 100644--- a/scripts/theme-vars.js+++ b/scripts/theme-vars.js@@ -13,6 +13,16 @@module.exports = {// body 级变量(作用域 body[data-vscode-theme-name])body: [+ {+ themeId: 'nebula',+ includeRoot: true,+ // 毛玻璃按钮透出背景;前景沿用主题文字色,避免深色图标失去对比。+ vars: {+ '--wb-button-primary-bg': 'transparent !important',+ '--wb-bg-secondary': 'transparent !important',+ '--wb-button-primary-fg': 'var(--wb-color-text-primary)',+ },+ },{darkOnly: true,vars: {@@ -33,6 +43,16 @@ module.exports = {],// 组件作用域级变量:官方在这些组件上定义了局部浅色硬编码,必须同作用域重定向(直接定义 > 继承)scoped: [+ {+ themeId: 'nebula',+ sel: '[data-theme],.vscode-dark,.dark,.cb-dark,.cr-theme',+ // 官方主题容器也可能直接定义同名变量,覆盖必须落在同一作用域。+ vars: {+ '--wb-button-primary-bg': 'transparent !important',+ '--wb-bg-secondary': 'transparent !important',+ '--wb-button-primary-fg': 'var(--wb-color-text-primary)',+ },+ },{sel: '.cr-tool-head__primary-tooltip-anchor',themeId: 'nebula',diff --git a/scripts/win-launcher.js b/scripts/win-launcher.jsindex e089381..e51e52d 100644--- a/scripts/win-launcher.js+++ b/scripts/win-launcher.js@@ -84,6 +84,7 @@ const cliCdpPort = process.argv.find((arg) => /^--cdp-port=\d+$/i.test(arg));const HAS_EXPLICIT_CDP_PORT = Boolean(process.env.WBSWITCH_CDP_PORT || cliCdpPort);let CDP_PORT = parseInt(process.env.WBSWITCH_CDP_PORT || (cliCdpPort ? cliCdpPort.split('=')[1] : '') || String(DEFAULT_CDP_PORT), 10);process.env.WBSWITCH_CDP_PORT = String(CDP_PORT);+let CDP_PORT_DYNAMIC = false;const CDP_PORT_FILE = path.join(DATA_DIR, 'cdp-port.json');// 便携版/低速磁盘上的 WorkBuddy 首次启动可能超过 20 秒;超时只应在足够长的窗口后报告。const CDP_STARTUP_TIMEOUT_MS = 60000;@@ -248,7 +249,7 @@ function cdpPortCandidates() {const result = [];const profilePorts = PROFILE_CDP_PORTS[PROFILE.id] || [DEFAULT_CDP_PORT];const add = (port) => { if (validCdpPort(port) && !result.includes(port)) result.push(port); };- if (HAS_EXPLICIT_CDP_PORT || profilePorts.includes(CDP_PORT)) add(CDP_PORT);+ if (HAS_EXPLICIT_CDP_PORT || profilePorts.includes(CDP_PORT) || CDP_PORT_DYNAMIC) add(CDP_PORT);const savedPort = readCdpPortFile();if (profilePorts.includes(savedPort)) add(savedPort);for (const port of profilePorts) add(port);@@ -283,6 +284,23 @@ function isLocalPortAvailable(port) {});}+function reserveEphemeralCdpPort() {+ return new Promise((resolve) => {+ const server = net.createServer();+ let settled = false;+ const finish = (port) => {+ if (settled) return;+ settled = true;+ try { server.close(() => resolve(validCdpPort(port) ? port : 0)); } catch (_) { resolve(validCdpPort(port) ? port : 0); }+ };+ server.once('error', () => finish(0));+ server.listen({ host: HOST, port: 0 }, () => {+ const address = server.address();+ finish(address && typeof address === 'object' ? Number(address.port) : 0);+ });+ });+}+function httpGet(port, p, headers = {}) {return new Promise((resolve) => {const req = http.get({ host: HOST, port, path: p, headers, timeout: 1500 }, (res) => {@@ -352,7 +370,16 @@ async function configureCdpPort() {return port;}}- throw new Error('当前 profile 的 CDP 端口均被占用,无法启动 WorkBuddy');+ const ephemeralPort = await reserveEphemeralCdpPort();+ if (ephemeralPort) {+ CDP_PORT = ephemeralPort;+ CDP_PORT_DYNAMIC = true;+ process.env.WBSWITCH_CDP_PORT = String(ephemeralPort);+ writeCdpPortFile(ephemeralPort);+ log('固定 CDP 端口均不可用,选择系统动态端口: ' + ephemeralPort);+ return ephemeralPort;+ }+ throw new Error('当前 profile 的固定 CDP 端口均不可用,且无法分配备用端口,无法启动 WorkBuddy');}function strictPowerShellLines(cmd) {@@ -1788,4 +1815,5 @@ module.exports = {tasklistProcessIds,workBuddyRunning,cdpPortCandidates,+ reserveEphemeralCdpPort,};diff --git a/test/account-list-stability.test.js b/test/account-list-stability.test.jsindex 0b2c9cc..b318d0b 100644--- a/test/account-list-stability.test.js+++ b/test/account-list-stability.test.js@@ -30,7 +30,7 @@ function harness() {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: '',+ MODEL_EDIT_SVG: '', PRIMARY_ACCOUNT_SVG: '', SWITCH_SVG: '', TRASH_SVG: '',setBuildTimeout: fn => fn(), setTimeout: () => 1, clearTimeout() {},checkForUpdate() {}, acCheckPromptOnOpen() {}, syncSessionModule() {}, fetchDailyProgressForAccounts() {}, pollActiveSessionCopyNotice() {},});diff --git a/test/account-order.test.js b/test/account-order.test.jsindex d61b357..45316f8 100644--- a/test/account-order.test.js+++ b/test/account-order.test.js@@ -32,7 +32,7 @@ test('background auth backup and account switching preserve fixed sort metadata'assert.deepEqual(Object.fromEntries(lib.listAccounts(dir).map(a => [a.uid,a.sort])), { a: 2, b: 1 });});-test('legacy account notes stay in metadata but are not exposed in the account list', t => {+test('account notes survive backup refresh and ordering without changing auth files', t => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-account-settings-'));t.after(() => fs.rmSync(dir, { recursive: true, force: true }));fs.mkdirSync(lib.accountsDir(dir), { recursive: true });@@ -45,5 +45,26 @@ test('legacy account notes stay in metadata but are not exposed in the account lassert.deepEqual(fs.readFileSync(backup), before);lib.setAccountOrder(dir, { mode: 'expiry', uids: ['a'] });assert.equal(JSON.parse(fs.readFileSync(lib.metaFile(dir), 'utf8')).accounts.a.note, '公司邮箱注册');- assert.equal(Object.hasOwn(lib.listAccounts(dir)[0], 'note'), false);+ assert.equal(lib.listAccounts(dir)[0].note, '公司邮箱注册');+ assert.deepEqual(lib.setAccountNote(dir, { uid: 'a', note: '工作账号\n下周续费' }), { uid: 'a', note: '工作账号\n下周续费' });+ lib.updateMeta(dir, { uid: 'a', nickname: 'refreshed' });+ assert.equal(lib.listAccounts(dir)[0].note, '工作账号\n下周续费');+ assert.deepEqual(fs.readFileSync(backup), before);+ assert.equal(lib.setAccountNote(dir, { uid: 'a', note: '' }).note, '');+});++test('account notes reject invalid identities, deleted accounts and invalid text', t => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-note-validation-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.mkdirSync(lib.accountsDir(dir), { recursive: true });+ fs.writeFileSync(path.join(lib.accountsDir(dir), 'a.info'), '{}');+ for (const uid of ['../a', '__proto__', 'constructor', 'prototype', 'missing', '', null]) {+ assert.throws(() => lib.setAccountNote(dir, { uid, note: 'note' }));+ }+ for (const note of [null, 1, {}, 'x'.repeat(2001)]) {+ assert.throws(() => lib.setAccountNote(dir, { uid: 'a', note }));+ }+ assert.equal(lib.setAccountNote(dir, { uid: 'a', note: 'x'.repeat(2000) }).note.length, 2000);+ fs.unlinkSync(path.join(lib.accountsDir(dir), 'a.info'));+ assert.throws(() => lib.setAccountNote(dir, { uid: 'a', note: 'deleted' }), /不存在/);});diff --git a/test/account-switch-session-rules.test.js b/test/account-switch-session-rules.test.jsindex c6b0779..a9259f3 100644--- a/test/account-switch-session-rules.test.js+++ b/test/account-switch-session-rules.test.js@@ -17,6 +17,7 @@ function harness(rules, owner = 'source') {beginRendererReloadPriority: () => () => events.push('release-reload'),assertAccountSwitchIdle: async () => () => events.push('release-switch'),currentAccount: () => ({ uid: 'source' }),+ preserveAccountSwitchTheme: async uid => { assert.equal(uid, 'target'); events.push('preserve-theme'); },sqliteQuery: async () => owner ? [{ user_id: owner, cwd: '/current-workspace' }] : [],switchTo: (_, uid) => { events.push('switch'); return { uid }; },reloadWorkBuddyPage: async () => { events.push('reload'); },@@ -43,7 +44,7 @@ test('switch route reloads without syncing when no rule is enabled', async () =>assert.equal(result.status, 200);assert.equal(result.body.reloaded, true);assert.equal(h.jobs.length, 0);- assert.deepEqual(h.events, ['switch', 'reload', 'release-reload', 'release-switch']);+ assert.deepEqual(h.events, ['preserve-theme', 'switch', 'reload', 'release-reload', 'release-switch']);});for (const rules of [diff --git a/test/auto-continue.test.js b/test/auto-continue.test.jsindex c7f879c..f0eb950 100644--- a/test/auto-continue.test.js+++ b/test/auto-continue.test.js@@ -7,6 +7,8 @@const assert = require('assert');const {classifyAutoContinueReply,+ normalizeAutoContinueError,+ classifyAutoContinueError,classifyAutoContinueControllerSnapshot,autoContinueMessageText,autoContinueControllerCompleted,@@ -171,6 +173,11 @@ function acSupported(platform) {classifyAutoContinueReply({ observed: true, error: true, assistantTextLength: 240 }),{ trigger: true, reason: 'error-ui' },);+ assert.deepStrictEqual(+ classifyAutoContinueReply({ observed: true, error: true, terminal: true, serviceErrorFallback: true }),+ { trigger: false, reason: 'completion-actions' },+ 'terminal + renderer fallback 是已结束请求,绝不重复发送',+ );assert.deepStrictEqual(classifyAutoContinueReply({ observed: true, looksTruncated: true, assistantTextLength: 240 }),{ trigger: true, reason: 'truncated-reply' },@@ -268,6 +275,14 @@ function acSupported(platform) {{ trigger: true, reason: 'error-ui' },'store error 直接触发续跑判定',);+ assert.deepStrictEqual(+ classifyAutoContinueControllerSnapshot({ assistantId: 'req-a-assistant', error: true, terminal: true, serviceErrorFallback: true }),+ { trigger: false, reason: 'completion-actions' },+ );+ assert.deepStrictEqual(+ classifyAutoContinueControllerSnapshot({ assistantId: 'req-a-assistant', error: true, errorCode: 6004, rateLimited: true }),+ { trigger: false, reason: 'model-rate-limited' },+ );assert.deepStrictEqual(classifyAutoContinueControllerSnapshot({ assistantId: 'req-a-assistant', manualStop: true }),{ trigger: false, reason: 'manual-stop' },@@ -282,6 +297,25 @@ function acSupported(platform) {console.log('✓ controller/store 终局判定(busy/complete/terminal/incomplete/error/manual-stop)');}+/* ===== 测试 13b:官方额度/限流错误码不可自动重试,且只保留白名单字段 ===== */+{+ const normalized = normalizeAutoContinueError({+ code: 6004,+ requestModelId: 'deepseek-v4.1-flash',+ message: 'rate limit; reset at 2026-09-26 14:32:00 UTC+8',+ terminal: { bizCode: 6004, details: { resetAt: '2026-09-26 14:32:00 UTC+8' } },+ });+ assert.equal(normalized.rateLimited, true);+ assert.equal(normalized.nonRetryable, true);+ assert.equal(normalized.requestModelId, 'deepseek-v4.1-flash');+ assert.ok(Number.isFinite(normalized.resetAt));+ assert.equal(Object.prototype.hasOwnProperty.call(normalized, 'message'), false);+ assert.deepStrictEqual(classifyAutoContinueError({ code: 14018 }), {+ quotaExhausted: true, rateLimited: false, authFailure: false, nonRetryable: true, code: 14018,+ });+ console.log('✓ 官方 14018/6004 错误码停止自动继续,错误快照不保留原文');+}+/* ===== 测试 14:消息正文从结构化 blocks 提取,不依赖 DOM ===== */{const text = autoContinueMessageText({ content: [diff --git a/test/automation-checkin.test.js b/test/automation-checkin.test.jsindex 65e1e16..2692a43 100644--- a/test/automation-checkin.test.js+++ b/test/automation-checkin.test.js@@ -114,6 +114,17 @@ test('panel refresh exposes an explicit current-account check-in reconciliationassert.match(ui, /current\.checkin = \{ ok: !!result\.ok/);});+test('model rate limit route and account snapshots expose only structured 6004 records', () => {+ assert.match(source, /p === '\/api\/model-rate-limit'/);+ const route = source.slice(source.indexOf("p === '/api/model-rate-limit'"), source.indexOf("if (req.method === 'GET' && p === '/api/accounts')"));+ assert.match(route, /reasonCode !== 6004/);+ assert.match(route, /modelName/);+ assert.doesNotMatch(route, /body\.message|body\.response|body\.raw/);+ const accounts = source.slice(source.indexOf("if (req.method === 'GET' && p === '/api/accounts')"), source.indexOf('// 查询指定账号的剩余积分'));+ assert.match(accounts, /listModelRateLimits/);+ assert.match(accounts, /modelRateLimits/);+});+test('failed or stale cache records never suppress today\'s check-in request', async () => {for (const cached of [{date:'2026-09-08',ok:false,verified:false,code:0,message:'HTTP 500'},diff --git a/test/automation-discovery.test.js b/test/automation-discovery.test.jsindex 52fa03f..fe3ba56 100644--- a/test/automation-discovery.test.js+++ b/test/automation-discovery.test.js@@ -263,7 +263,7 @@ test('automation UI preloads discovery and exposes fuzzy task search and import'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.match(source, /wbs-auto-discovery-favorite\.is-active\{color:var\(--wb-button-primary-bg/);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/);diff --git a/test/automation-switch-sync.test.js b/test/automation-switch-sync.test.jsindex 74bb317..f1b2bdc 100644--- a/test/automation-switch-sync.test.js+++ b/test/automation-switch-sync.test.js@@ -9,11 +9,12 @@ const tick = () => new Promise(resolve => setImmediate(resolve));function harness() {let active = { uid: 'a' }, reloadPriority = 0;- const switches = [], jobs = [], phases = [];+ const switches = [], jobs = [], phases = [], themeTargets = [];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 }); },+ preserveAccountSwitchTheme: async uid => { themeTargets.push(uid); },+ currentAccount: () => active, switchTo: (_dir, uid) => { assert.equal(themeTargets.at(-1), uid, 'appearance is prepared before replacing the account'); switches.push(uid); return (active = { uid }); },reloadWorkBuddyPage: async () => {}, pendingAutomationAccountSwitch: null,dispatchAutomationEvent() {}, mainFrameNavigationSerial: 1,beginRendererReloadPriority: () => { reloadPriority++; return () => { reloadPriority--; }; },@@ -117,3 +118,16 @@ test('an empty message-file session does not block automation account switching'await run;assert.deepEqual(h.switches, ['b']);});+++test('cancelling during theme preparation prevents account replacement', async () => {+ const h = harness();+ let release, cancelled = false;+ h.ctx.preserveAccountSwitchTheme = () => new Promise(resolve => { release = resolve; });+ const run = h.ctx.automationSwitchAccount({ uid: 'b' }, { ...h.options, isCancelled: () => cancelled });+ await tick(); await tick();+ cancelled = true; release();+ await assert.rejects(run, /任务已停止/);+ assert.deepEqual(h.switches, []);+ assert.equal(h.priority(), 0);+});diff --git a/test/cdp-targets.test.js b/test/cdp-targets.test.jsindex a94f249..736f7c5 100644--- a/test/cdp-targets.test.js+++ b/test/cdp-targets.test.js@@ -3,7 +3,7 @@const test = require('node:test');const assert = require('node:assert/strict');const { PROFILES } = require('../scripts/profiles.js');-const { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('../scripts/cdp-targets.js');+const { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget } = require('../scripts/cdp-targets.js');const AI_URL = 'file:///Applications/WorkBuddy%20AI.app/Contents/Resources/app.asar/renderer/index.html';const CN_URL = 'file:///Applications/WorkBuddy.app/Contents/Resources/app.asar/renderer/index.html';@@ -16,6 +16,12 @@ test('normalizeTargetUrl 把 %20 还原为空格', () => {assert.equal(normalizeTargetUrl('WorkBuddy AI.app'), 'WorkBuddy AI.app');});+test('selectPageTarget prefers the main renderer over the settings utility window', () => {+ const settings = { type: 'page', url: CN_URL + '?colorScheme=dark&windowAppId=settings&windowKind=settings&windowPreset=utility', title: 'WorkBuddy' };+ const main = { type: 'page', url: CN_URL + '?locale=zh-CN&accountSnapshot=%7B%7D', title: 'WorkBuddy' };+ assert.equal(selectPageTarget([settings, main], PROFILES['workbuddy-cn']), main);+});+test('classifyTarget 依据 app 包路径识别四客户端(含 %20 编码)', () => {assert.equal(classifyTarget(AI_URL, 'WorkBuddy AI'), 'workbuddy-ai');assert.equal(classifyTarget(CN_URL, 'WorkBuddy'), 'workbuddy-cn');diff --git a/test/composer-button-visibility.test.js b/test/composer-button-visibility.test.jsindex 66026f1..a9a19b2 100644--- a/test/composer-button-visibility.test.js+++ b/test/composer-button-visibility.test.js@@ -39,7 +39,7 @@ function harness() {};const context = vm.createContext({document, window: { innerWidth: 1000, innerHeight: 800 }, WBS_COMPAT: compat,- stashBtn: element(), exploreBtn: element(), alive: true,+ stashBtn: element(), exploreBtn: element(), exploreMenu: { close() {} }, alive: true,sessState: { phrase: true, stash: true },findComposer: () => page.editor,composerHasContent: editor => !!editor?.hasContent,diff --git a/test/conversation-usage.test.js b/test/conversation-usage.test.jsindex 9e9fec7..ff47636 100644--- a/test/conversation-usage.test.js+++ b/test/conversation-usage.test.js@@ -5,7 +5,13 @@ const fs = require('node:fs');const path = require('node:path');const test = require('node:test');-const { collectConversationUsage, conversationMessagesToMarkdown } = require('../scripts/inject.js');+const { collectConversationUsage, conversationMessagesToMarkdown, conversationUsageHeadline } = require('../scripts/inject.js');++test('conversation usage hides the total prefix until a completed call exists', () => {+ assert.deepEqual(conversationUsageHeadline(null), { prefix: '共', message: '读取中…' });+ assert.deepEqual(conversationUsageHeadline({ calls: 0 }), { prefix: '', message: '等待会话完成' });+ assert.deepEqual(conversationUsageHeadline({ calls: 1 }), { prefix: '共', message: '' });+});test('conversation copy preserves complete user and assistant Markdown from the message store', () => {const markdown = conversationMessagesToMarkdown([@@ -89,7 +95,8 @@ test('conversation usage UI uses a body-fixed mount, bottom spacer and message sassert.match(source, /window\.innerHeight - anchorBottom/);assert.match(source, /positionConversationUsage\(\);[\s\S]{0,120}updateConversationUsageScrollState\(\)/);assert.match(source, /wbs-session-usage-summary\.is-hidden/);- assert.match(source, /wbs-session-usage-label', '共'/);+ assert.match(source, /conversationUsageHeadline\(state\)/);+ assert.match(source, /等待会话完成/);assert.match(source, /wbs-session-usage-copy/);assert.match(source, /复制整个会话/);assert.match(source, /event\.target\.closest\('\.wbs-session-usage-copy'\)/);diff --git a/test/credit-usage-store.test.js b/test/credit-usage-store.test.jsindex 3235278..ff9f730 100644--- a/test/credit-usage-store.test.js+++ b/test/credit-usage-store.test.js@@ -121,3 +121,20 @@ test('history backfill preserves the today anchor, deduplicates, and distinguishassert.equal(rows.find(r=>r.date==='2026-08-28').used,2.5);assert.equal(rows.find(r=>r.date==='2026-08-28').count,1);});++test('stores multiple model rate limits and removes expired reset times', async (t) => {+ const tmp = tempStore();+ t.after(() => fs.rmSync(tmp.dir, { recursive: true, force: true }));+ await tmp.store.saveModelRateLimit({ uid: 'u1', modelId: 'deepseek-v4.1-flash', modelName: 'DeepSeek V4.1 Flash', resetAt: 5000, observedAt: 1000, reasonCode: 6004, source: 'renderer-error' });+ await tmp.store.saveModelRateLimit({ uid: 'u1', modelId: 'gpt-5.6', modelName: 'GPT-5.6', resetAt: null, observedAt: 1100, reasonCode: 6004, source: 'renderer-error' });+ await tmp.store.saveModelRateLimit({ uid: 'u2', modelId: 'model-x', modelName: 'Model X', resetAt: 9000, observedAt: 1200, reasonCode: 6004, source: 'renderer-error' });+ assert.deepEqual(await tmp.store.listModelRateLimits(['u1', 'u2'], 4000), {+ u1: [+ { modelId: 'gpt-5.6', modelName: 'GPT-5.6', resetAt: null, observedAt: 1100, source: 'renderer-error', reasonCode: 6004 },+ { modelId: 'deepseek-v4.1-flash', modelName: 'DeepSeek V4.1 Flash', resetAt: 5000, observedAt: 1000, source: 'renderer-error', reasonCode: 6004 },+ ],+ u2: [{ modelId: 'model-x', modelName: 'Model X', resetAt: 9000, observedAt: 1200, source: 'renderer-error', reasonCode: 6004 }],+ });+ const afterExpiry = await tmp.store.listModelRateLimits(['u1', 'u2'], 6000);+ assert.deepEqual(afterExpiry.u1, [{ modelId: 'gpt-5.6', modelName: 'GPT-5.6', resetAt: null, observedAt: 1100, source: 'renderer-error', reasonCode: 6004 }]);+});diff --git a/test/growth-rings-ui.test.js b/test/growth-rings-ui.test.jsindex 1ae34d2..54b3fbe 100644--- a/test/growth-rings-ui.test.js+++ b/test/growth-rings-ui.test.js@@ -148,6 +148,17 @@ test('growth primary is green in light and blue-purple in dark, cyber, and glassassert.match(inject, /\.wbs-growth-tier b\{[^}]*color:var\(--wb-color-text-secondary/);});+test('growth status colors reuse WorkBuddy primary theme constants', () => {+ const vars = inject.match(/\.wbs-daily-rings,\.wbs-status-popover\{[^']+/);+ assert.ok(vars);+ assert.match(vars[0], /--wbs-ring-growth:var\(--wb-button-primary-bg/);+ assert.match(vars[0], /--wbs-ring-cat:var\(--wb-button-primary-bg/);+ assert.match(vars[0], /--wbs-tip-credit:var\(--wb-button-primary-bg/);+ assert.match(vars[0], /--wbs-liquid-fill:var\(--wb-button-primary-bg/);+ assert.match(inject, /\.wbs-session-copy-icon\{[^}]*var\(--wb-button-primary-bg/);+ assert.doesNotMatch(inject, /\.wbs-session-copy-summary-line\.is-copied\{color:#238a5b/);+});+test('growth actions open the official center and never write through local growth routes', async () => {assert.match(inject, /https:\/\/www\.workbuddy\.cn\/profile\/growth-center/);assert.match(inject, /data-wbs-growth-official/);@@ -276,3 +287,14 @@ test('travel countdown formats a live arrival time without dropping hours or zerassert.equal(format(now + 65_000, now), '01分 05秒');assert.equal(format(now, now), '');});++test('growth plan primary actions use WorkBuddy button theme tokens', () => {+ const action = inject.match(/\.wbs-growth-task-action\{[^']+/);+ assert.ok(action, 'growth action style exists');+ assert.match(action[0], /var\(--wb-button-primary-bg/);+ assert.match(action[0], /var\(--wb-button-primary-fg/);+ assert.doesNotMatch(action[0], /color:var\(--wbs-ring-growth\)/);+ const hover = inject.match(/\.wbs-growth-task-action:hover[^']+/);+ assert.ok(hover);+ assert.match(hover[0], /var\(--wb-button-primary-bg-hover/);+});diff --git a/test/panel-brand-robot.test.js b/test/panel-brand-robot.test.jsindex d03d619..91e093e 100644--- a/test/panel-brand-robot.test.js+++ b/test/panel-brand-robot.test.js@@ -39,15 +39,18 @@ test('robot appearance restores per-profile preferences and rejects unknown stylconst options = { key: 'robot-cn', storage: { getItem: key => values.get(key), setItem: (key, value) => values.set(key, value) },fab: { setAttribute: (key, value) => attrs.set(key, value) } };const style = createFabAppearance(options);- assert.equal(style.get(), 'black');+ assert.equal(style.get(), 'theme');style.set('black');assert.equal(attrs.get('data-wbs-robot-style'), 'black');assert.equal(createFabAppearance(options).get(), 'black');- assert.equal(createFabAppearance({ ...options, key: 'robot-ai' }).get(), 'black');+ assert.equal(createFabAppearance({ ...options, key: 'robot-ai' }).get(), 'theme');style.set('glass');assert.equal(createFabAppearance(options).get(), 'glass');+ style.set('theme');+ assert.equal(createFabAppearance(options).get(), 'theme');+ assert.equal(attrs.get('data-wbs-robot-style'), 'theme');style.set('invalid');- assert.equal(style.get(), 'glass');+ assert.equal(style.get(), 'theme');});test('panel owns the brand and groups robot controls; message shadow is the last theme card', () => {@@ -61,6 +64,9 @@ test('panel owns the brand and groups robot controls; message shadow is the lastconst robot = pane.slice(pane.indexOf('wbs-fab-settings'), pane.indexOf('wbs-wallpaper-card'));assert.match(robot, /wbs-robot-style/);assert.match(robot, /wbs-fab-auto-dock/);+ assert.ok(robot.indexOf('value="theme"') < robot.indexOf('value="white"'));+ assert.ok(robot.indexOf('value="theme"') < robot.indexOf('value="black"'));+ assert.ok(robot.indexOf('value="theme"') < robot.indexOf('value="glass"'));});// Exercise the actual panel wiring: browser timers reject an options object as `this`.@@ -91,3 +97,21 @@ test('panel five-click wiring preserves the browser timer receiver and reveals dassert.equal(picker.style.display, '');assert.equal(card.style.display, '');});+++test('composer controls use live primary button tokens with no dark glass override', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const start = source.indexOf(' function applyThemeButtonColors()');+ const end = source.indexOf(' function positionStash()', start);+ const context = { stashBtn: { style: {} }, exploreBtn: { style: {} } };+ vm.runInNewContext(source.slice(start, end), context);+ context.applyThemeButtonColors();+ for (const button of [context.stashBtn, context.exploreBtn]) {+ assert.equal(button.style.background, 'var(--wb-button-primary-bg)');+ assert.equal(button.style.color, 'var(--wb-button-primary-fg)');+ }+ const patches = require('../scripts/theme-patches.js');+ assert.ok(!patches.some(patch => patch.css.includes('.wbs-stash-inline')));+ assert.match(source, /value="theme"><span>主题色<\/span>/);+ assert.match(source, /data-wbs-robot-style="theme"[^\n]*--wbs-robot-shell:var\(--wb-button-primary-bg\)/);+});diff --git a/test/panel-theme-controls.test.js b/test/panel-theme-controls.test.jsindex 881fb45..94b8462 100644--- a/test/panel-theme-controls.test.js+++ b/test/panel-theme-controls.test.js@@ -5,17 +5,53 @@ const fs = require('node:fs');const path = require('node:path');const vm = require('node:vm');const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const section = (a,b) => source.slice(source.indexOf(a),source.indexOf(b,source.indexOf(a)));+test('frosted glass takeover is visible above wallpaper controls and retains the saved setting', () => {+ const theme = section('function buildThemePane()', 'function buildEnhancePane()');+ const sessions = section('function buildSessionsPane()', 'function wireSessionsPane()');+ assert.match(theme, /id="wbs-theme-takeover"/);+ assert.match(theme, /<div class="wbs-pcard-title">毛玻璃主题<\/div>/);+ assert.doesNotMatch(theme, /关闭后,加载和切换账号时保留 WorkBuddy 的主题/);+ assert.match(source, /\.wbs-theme-takeover-row>\.wbs-pcard-title\{[^}]*flex:1/);+ assert.ok(theme.indexOf('id="wbs-theme-takeover"') < theme.indexOf('wbs-wallpaper-card'));+ assert.doesNotMatch(sessions, /wbs-theme-takeover|wbs-sess-theme-takeover/);+ const wire = section('function wireThemePane()', ' var shadowSwitch =');+ assert.match(wire, /themeSwitch.checked = sessState.themeTakeover/);+ assert.match(wire, /if \(!themeSwitch\.dataset\.wbsWired\)/);+ assert.match(wire, /setSessionSwitchWire\('themeTakeoverEnabled', this\)/);+ assert.match(wire, /syncSessionModule\(\)/);+ const apply = section('function applySessionModule(', 'function syncSessionModule()');+ assert.match(apply, /themePane && themePane.querySelector\('#wbs-theme-takeover'\)/);+ assert.doesNotMatch(theme, /id="wbs-theme-appearance-options"/);+ assert.match(theme, /class="wbs-pcard wbs-avatar-card"/);+ assert.ok(theme.indexOf('wbs-avatar-card') < theme.indexOf('wbs-fab-settings'));+ assert.ok(theme.indexOf('wbs-fab-settings') < theme.indexOf('id="wbs-theme-takeover"'));+ assert.match(theme, /class="wbs-pcard wbs-fab-settings"/);+ assert.match(theme, /wbs-wallpaper-card wbs-theme-managed/);+ assert.match(source, /function syncThemeTakeoverVisibility\(enabled\)/);++});test('theme choices do not activate official data-theme scopes and robot radios reuse their visual component', () => {const pane = section('function buildThemePane()', 'function buildEnhancePane()');assert.doesNotMatch(pane, /data-theme="/);- assert.match(pane, /data-wbs-theme-option="dark"/);+ assert.doesNotMatch(pane, /id="wbs-theme-seg"|data-wbs-theme-option=/);+ assert.match(pane, /毛玻璃主题/);assert.match(pane, /class="wbs-theme-seg wbs-robot-seg"/);assert.match(pane, /class="wbs-theme-opt wbs-robot-option"/);- assert.match(source, /closest\('#wbs-theme-seg \.wbs-theme-opt'\)/);+ assert.doesNotMatch(source, /closest\('#wbs-theme-seg \.wbs-theme-opt'\)/);assert.match(pane, /wbs-avatar-default-option/);assert.match(pane, /value="default"/);});++test('theme pane exposes only the frosted glass takeover switch', () => {+ const pane = section('function buildThemePane()', 'function buildEnhancePane()');+ assert.match(pane, /<div class="wbs-pcard-title">毛玻璃主题<\/div>/);+ assert.doesNotMatch(pane, /<div class="wbs-pcard-title">主题外观<\/div>/);+ assert.doesNotMatch(pane, /data-wbs-theme-option=/);+ assert.match(daemon, /if \(state\.themeTakeoverEnabled\) await applyThemeByCdp\('nebula'\)/);+ assert.match(daemon, /let id = 'nebula';/);+});test('account order is centered in the panel and always shows names without numbered rows', () => {const modal = section('function openAccountOrderModal()', 'function setupCreditSummary()');assert.match(modal, /wbs-modal-mask wbs-modal-mask-panel/);@@ -56,3 +92,138 @@ test('avatar presets retain legacy custom uploads and are safe before official cassert.match(source, /if \(!target\) \{\s*restoreAvatarDom\(\);\s*return;/);assert.doesNotMatch(source, /id="wbs-avatar-reset"/);});++test('theme takeover off hides every managed theme module and blocks custom theme clicks', () => {+ const visibility = section('function syncThemeTakeoverVisibility(', ' // 主题 pane 事件绑定');+ assert.match(visibility, /querySelectorAll\('\.wbs-theme-managed'\)/);+ assert.match(visibility, /node\.style\.display = visible \? '' : 'none'/);+ assert.match(source, /var visible = sessState\.themeTakeover/);+ assert.doesNotMatch(source, /if \(!sessState\.themeTakeover\) return;\s+var id = segBtn/);+});+++test('theme takeover toggles only theme controls without changing the selected avatar', () => {+ const managed = [{ style: {} }, { style: {} }];+ let avatarChanges = 0;+ const context = {+ themePane: { querySelectorAll: selector => {+ assert.equal(selector, '.wbs-theme-managed');+ return managed;+ } },+ avatarLibrary: { snapshot: () => ({ selected: 'workdaddy' }), select: () => { avatarChanges++; } },+ applyAvatar: () => { avatarChanges++; },+ };+ vm.runInNewContext(section('function syncThemeTakeoverVisibility(', ' // 主题 pane 事件绑定'), context);+ context.syncThemeTakeoverVisibility(false);+ assert.ok(managed.every(node => node.style.display === 'none'));+ context.syncThemeTakeoverVisibility(true);+ assert.ok(managed.every(node => node.style.display === ''));+ assert.equal(avatarChanges, 0);+ assert.match(source, /\.wbs-theme-takeover-row:has\(#wbs-theme-takeover:not\(:checked\)\)\{margin-bottom:0;padding-bottom:0;border-bottom:0\}/);+});+++test('glass panel controls keep opaque primary colors without changing composer buttons', () => {+ const rule = source.split('\n').find(line => line.includes('html[data-wbs-theme-id="nebula"] .wbs-panel,'));+ assert.ok(rule, 'glass overrides are scoped to WorkDaddy panel and modal surfaces');+ assert.match(rule, /html\[data-wbs-theme-id="nebula"\] \.wbs-modal/);+ assert.match(rule, /--wb-button-primary-bg:var\(--wb-palette-white-90\)/);+ assert.match(rule, /--wb-button-primary-fg:var\(--wb-bg-primary\)/);+ assert.doesNotMatch(rule, /\.wbs-root|\.wbs-stash-inline|\.wbs-fab/);+});++test('theme refresh preserves robot radio selection while keeping the glass wallpaper visible', async () => {+ const robot = { active: true, getAttribute: () => null };+ robot.classList = { toggle: (_, selected) => { robot.active = selected; } };+ const group = buttons => ({ querySelectorAll: () => buttons, querySelector: () => buttons.find(b => b.active) });+ let synced = null;+ const root = { querySelector: () => group([robot]) };+ const context = { root, api: () => Promise.resolve({current:'cyber-purple'}), syncWallpaperCardVisibility: theme => { synced = theme; } };+ vm.runInNewContext(section(' function loadThemes()', ' // 页面主题由 daemon'), context);+ context.loadThemes();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(robot.active, true, 'appearance refresh must not clear the robot highlight');+ assert.equal(synced, 'nebula');+ assert.equal(context.themeSelectValue(), 'nebula');+});++test('all panel switches share themed track, thumb and keyboard focus colors', () => {+ const css = section(" '.wbs-switch{", " /* 背景毛玻璃开关");+ assert.match(css, /background:var\(--wb-bg-tertiary/);+ assert.match(css, /input:checked \+ \.wbs-switch-slider\{background:var\(--wb-button-primary-bg/);+ assert.match(css, /input:checked \+ \.wbs-switch-slider:before\{background:var\(--wb-button-primary-fg/);+ assert.match(css, /input:focus-visible \+ \.wbs-switch-slider/);+ assert.doesNotMatch(css, /background:#(?:f2f2f4|111113)/);+});++test('custom themes color account and expiry bars with primary token while preserving expiry opacity', () => {+ const rule = source.split('\n').find(line => line.includes('--wbs-credit-theme-color:var(--wb-button-primary-bg)'));+ assert.ok(rule, 'custom skins and nonstandard WorkDaddy themes opt into the theme token');+ for (const id of ['default','dark','nebula']) assert.ok(rule.includes(':not([data-wbs-theme-id="'+id+'"])'));+ assert.ok(rule.includes('[data-skin]'));+ assert.ok(rule.includes('.wbs-credit-summary-popover'));+ assert.match(source, /color-mix\(in srgb,var\(--wbs-credit-theme-color/);+ assert.match(source, /calc\(var\(--wbs-credit-alpha,1\) \* 100%\)/);+});++for (const trigger of ['switch', 'settings refresh']) test('frosted wallpaper starts loading on ' + trigger + ' without revisiting the tab', async () => {+ const grid = { dataset: {}, innerHTML: '壁纸加载中…', querySelectorAll: () => [] };+ const card = { style: {} }, toggle = { checked: false };+ const nodes = { '#wbs-wallpapers': grid, '#wbs-wallpaper-card': card, '#wbs-theme-takeover': toggle };+ const requests = [];+ let resolveWallpapers;+ const context = {+ sessState: {}, enhancePane: null, conversationUsageEnabled: false,+ themePane: { querySelector: selector => nodes[selector] || null, querySelectorAll: () => [card] },+ root: { querySelector: selector => nodes[selector] || null },+ API: 'http://127.0.0.1:47833',+ api: (route, opts) => {+ requests.push(route);+ if (route === '/api/wallpapers') return new Promise(resolve => { resolveWallpapers = resolve; });+ return Promise.resolve({ ok: true, themeTakeoverEnabled: route === '/api/session-module-set' ? JSON.parse(opts.body).enabled : true });+ },+ renderQpList() {}, renderExploreOptions() {}, syncStash() {}, lockPanelHeight() {},+ setTimeout() {}, escAttr: value => value, esc: value => value,+ toast: message => assert.fail(message),+ };+ vm.runInNewContext(section('function applySessionModule(', ' /** 增强页快捷短语列表') ++ section('function syncWallpaperCardVisibility(', ' // 主题 pane 事件绑定') ++ section('function loadWallpapers(force)', ' function setOpen('), context);+ context.applySessionModule({ ok: true, themeTakeoverEnabled: false });+ context.syncWallpaperCardVisibility('nebula'); // First visit with takeover off.+ assert.equal(requests.length, 0);+ if (trigger === 'switch') {+ toggle.checked = true;+ await context.setSessionSwitchWire('themeTakeoverEnabled', toggle);+ } else {+ context.syncSessionModule();+ await new Promise(resolve => setImmediate(resolve));+ }+ assert.equal(card.style.display, '');+ assert.equal(requests.filter(route => route === '/api/wallpapers').length, 1);+ context.applySessionModule({ ok: true, themeTakeoverEnabled: true });+ assert.equal(requests.filter(route => route === '/api/wallpapers').length, 1, 'pending loads are reused');+ resolveWallpapers({ wallpapers: [{ name: 'wallpaper-01.webp', title: '官方壁纸 1' }] });+ await new Promise(resolve => setImmediate(resolve));+ assert.match(grid.innerHTML, /data-wp="wallpaper-01.webp"/);+ assert.doesNotMatch(grid.innerHTML, /壁纸加载中/);+ context.applySessionModule({ ok: true, themeTakeoverEnabled: false });+ context.applySessionModule({ ok: true, themeTakeoverEnabled: true });+ assert.equal(requests.filter(route => route === '/api/wallpapers').length, 1, 'loaded wallpaper grid is reused');+});++test('primary actions use native button tokens in every interaction state', () => {+ for (const selector of ['.wbs-modal-btn.wbs-modal-ok', '.wbs-sess-bbtn.active', '.wbs-acc-switch.armed', '.wbs-sess-done']) {+ const start = source.indexOf(selector + '{');+ const rule = source.slice(start, source.indexOf('}', start));+ assert.match(rule, /background:var\(--wb-button-primary-bg/);+ assert.match(rule, /color:var\(--wb-button-primary-fg/);+ }+ assert.doesNotMatch(source, /--wb-button-primary-(hover-bg|text)\b/);+ assert.match(source, /background:var\(--wb-button-primary-bg-disabled/);+ assert.match(source, /color:var\(--wb-button-primary-fg-disabled/);+ assert.match(source, /\.wbs-modal-btn:not\(:where\(\.wbs-modal-ok,\.primary\)\)/);+ const glass = source.split('\n').find(line => line.includes('html[data-wbs-theme-id="nebula"] .wbs-panel,'));+ assert.match(glass, /\.wbs-account-note-popover/);+ assert.match(glass, /\.wbs-status-popover/);+});diff --git a/test/quick-phrase-popover.test.js b/test/quick-phrase-popover.test.jsnew file mode 100644index 0000000..bf311d3--- /dev/null+++ b/test/quick-phrase-popover.test.js@@ -0,0 +1,48 @@+'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');+test('quick phrase popup escapes composer stacking, bridges hover, and cleans up on reinjection', () => {+ const timers = new Map(); let nextTimer = 0;+ function element(rect = { width: 280, height: 100 }) {+ const classes = new Set(), listeners = new Map();+ return { style: {}, attrs: {}, isConnected: true, listeners,+ classList: { add: key => classes.add(key), remove: key => classes.delete(key), contains: key => classes.has(key) },+ setAttribute(key, value) { this.attrs[key] = value; }, getBoundingClientRect: () => rect,+ addEventListener(name, fn) { listeners.set(name, fn); }, removeEventListener(name) { listeners.delete(name); },+ appendChild(child) { child.parentElement = this; }, contains(child) { return child === this; },+ remove() { this.isConnected = false; }, focus() {},+ };+ }+ const window = Object.assign(element(), { innerWidth: 360, innerHeight: 800 });+ const document = Object.assign(element(), { body: element() });+ const button = element({ left: 320, top: 660, width: 32, height: 32 });+ const popup = element(); popup.parentElement = button;+ const context = { document, window, setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; }, clearTimeout: id => timers.delete(id) };+ const start = source.indexOf(' function mountExplorePopover(');+ vm.runInNewContext(source.slice(start, source.indexOf(' function acMenuClose()', start)), context);+ const menu = context.mountExplorePopover(button, popup);+ assert.equal(popup.parentElement, document.body);+ button.listeners.get('mouseenter')();+ assert.equal(popup.classList.contains('is-open'), true);+ assert.equal(button.attrs['aria-expanded'], 'true');+ assert.equal(popup.style.left, '72px', 'clamped inside a narrow viewport');+ button.listeners.get('mouseleave')();+ popup.listeners.get('mouseenter')();+ assert.equal(timers.size, 0, 'hover bridge cancels pending close');+ document.listeners.get('scroll')({target: popup});+ assert.equal(popup.classList.contains('is-open'), true);+ document.listeners.get('scroll')({target: document.body});+ assert.equal(popup.classList.contains('is-open'), false);+ menu.open(); window.listeners.get('resize')();+ assert.equal(button.attrs['aria-expanded'], 'false');+ button.listeners.get('mouseleave')(); menu.destroy();+ assert.equal(timers.size, 0);+ for (const target of [button, popup, window, document]) assert.equal(target.listeners.size, 0);+ assert.equal(popup.isConnected, false);+ const zIndex = selector => Number(source.match(new RegExp('\\.' + selector + '\\{[^}]*?z-index:(\\d+)'))[1]);+ assert.ok(zIndex('wbs-explore-pop') > zIndex('wbs-session-usage-popover'));+ assert.ok(zIndex('wbs-explore-pop') < zIndex('wbs-root'));+});diff --git a/test/renderer-escaping.test.js b/test/renderer-escaping.test.jsindex 3f8e902..1b32229 100644--- a/test/renderer-escaping.test.js+++ b/test/renderer-escaping.test.js@@ -86,7 +86,7 @@ test('model, wallpaper, and account cards escape each dynamic HTML sink', () =>assert.doesNotMatch(wallpapers, /(?:data-wp|title|data-src|alt)="' \+ (?:w\.|wallpaperUrl)/);const accounts = sourceBetween('function render(data)', 'function updateAccountSummary()');- assert.equal((accounts.match(/escAttr\(a\.uid\)/g) || []).length, 2);+ assert.equal((accounts.match(/escAttr\(a\.uid\)/g) || []).length, 3);assert.doesNotMatch(accounts, /data-primary-uid/);assert.equal((accounts.match(/escAttr\(a\.nickname \|\| '未命名'\)/g) || []).length, 2);assert.match(accounts, /var nameVal = state\.mask \? maskAccountName\(rawName\) : rawName;/);diff --git a/test/session-export-jobs.test.js b/test/session-export-jobs.test.jsnew file mode 100644index 0000000..ea9c211--- /dev/null+++ b/test/session-export-jobs.test.js@@ -0,0 +1,62 @@+'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 { createSessionExportJobs, readSessionTransfer } = require('../scripts/session-transfer');+function fixture(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-export-job-'));+ t.after(() => fs.rmSync(root, {recursive:true,force:true}));+ const file = path.join(root,'source'); fs.writeFileSync(file,'fixture content');+ const sessions = [{record:{id:'fixture-session'},files:[{path:'tasks/fixture-session/file.bin',source:file,size:fs.statSync(file).size}]}];+ return {root, sessions, directory:path.join(root,'Downloads','WorkDaddy')};+}+test('background export returns before preparation, publishes an authenticated file and no password', async t => {+ const f=fixture(t); let release;+ const preparing=new Promise(resolve=>{release=resolve;});+ const jobs=createSessionExportJobs({directory:()=>f.directory,prepare:async()=>{await preparing;return f.sessions;}});+ const started=jobs.start(['fixture-session'],'secret password');+ assert.equal(started.running,true); assert.equal(started.status,'preparing');+ assert.equal(JSON.stringify(started).includes('secret password'),false);+ assert.throws(()=>jobs.start(['fixture-session'],'another password'),/正在导出/);+ release(); await jobs.wait();+ const done=jobs.get(started.id);+ assert.equal(done.status,'completed');assert.equal(done.running,false);assert.equal(done.percent,100);+ assert.equal(done.processedBytes,f.sessions[0].files[0].size);+ assert.equal(path.dirname(done.file),f.directory);+ assert.equal(fs.readdirSync(f.directory).length,1,'no temporary files remain');+ const restored=await readSessionTransfer(done.file,'secret password',path.join(f.root,'restored'));+ assert.equal(fs.readFileSync(restored.sessions[0].files[0].source,'utf8'),'fixture content');+ assert.equal(JSON.stringify(jobs.get()).includes('secret password'),false);+});+test('cancelling before preparation completes never creates a finished archive', async t=>{+ const f=fixture(t);let release;+ const gate=new Promise(resolve=>{release=resolve;});+ const jobs=createSessionExportJobs({directory:()=>f.directory,prepare:async()=>{await gate;return f.sessions;}});+ const started=jobs.start(['fixture-session'],'password');jobs.cancel(started.id);release();await jobs.wait();+ assert.equal(jobs.get().status,'cancelled');assert.equal(jobs.get().file,'');+ assert.equal(fs.existsSync(f.directory),false);+});+test('stream cancellation and disk failures remove staged archives, preserving existing downloads', async t=>{+ for(const cancel of [true,false]){+ const f=fixture(t);fs.mkdirSync(f.directory,{recursive:true});fs.writeFileSync(path.join(f.directory,'keep.wds'),'existing');+ let jobs;+ jobs=createSessionExportJobs({directory:()=>f.directory,prepare:async()=>f.sessions,write:async(file,sessions,password,options)=>{+ fs.writeFileSync(file,'incomplete');+ if(cancel){jobs.cancel(jobs.get().id);options.signal.throwIfAborted();}+ const error=Error('disk full');error.code='ENOSPC';throw error;+ }});+ jobs.start(['fixture-session'],'password');await jobs.wait();+ assert.equal(jobs.get().status,cancel?'cancelled':'failed');+ assert.equal(jobs.get().file,'');assert.deepEqual(fs.readdirSync(f.directory),['keep.wds']);+ }+});+test('new export jobs never overwrite earlier completed downloads',async t=>{+ const f=fixture(t),jobs=createSessionExportJobs({directory:()=>f.directory,prepare:async()=>f.sessions});+ jobs.start(['fixture-session'],'password');await jobs.wait();const first=jobs.get();+ jobs.start(['fixture-session'],'password');await jobs.wait();const second=jobs.get();+ assert.notEqual(first.file,second.file);assert.equal(fs.existsSync(first.file),true);+ assert.equal(jobs.get(first.id).status,'completed');+ assert.equal(jobs.get('../../unknown'),null);+});diff --git a/test/session-export-ui.test.js b/test/session-export-ui.test.jsnew file mode 100644index 0000000..93b7fc9--- /dev/null+++ b/test/session-export-ui.test.js@@ -0,0 +1,40 @@+'use strict';+const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'),path=require('node:path');+const source=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');+function fixture(){+ const nodes=new Map(),node=key=>{if(!nodes.has(key))nodes.set(key,{hidden:false,disabled:false,textContent:'',removeAttribute(name){delete this[name];},querySelector:node});return nodes.get(key);};+ const calls=[],requests=[],timers=[];+ const ctx={sessionsPane:{querySelector:node},sessionsState:{},alive:true,clearTimeout(){},setBuildTimeout(fn){timers.push(fn);return timers.length;},+ sessionCopySizeText:bytes=>String(bytes),api:url=>{calls.push(url);return new Promise((resolve,reject)=>requests.push({resolve,reject}));}};+ const start=source.indexOf(' function renderSessionExport(');+ vm.runInNewContext(source.slice(start,source.indexOf(' function sortSessionAccounts(',start)),ctx);+ return{ctx,node,calls,requests,timers};+}+test('export progress uses byte counts above 2 GiB and safe text for paths and errors',()=>{+ const f=fixture(),job={id:'one',status:'writing',running:true,totalBytes:3*1024**3,processedBytes:2.4*1024**3,percent:80};+ f.ctx.renderSessionExport(job);+ assert.equal(f.node('#wbs-sess-export').disabled,true);+ assert.equal(f.node('[data-export-progress]').value,80);+ assert.equal(f.node('[data-export-open]').hidden,true);+ f.ctx.renderSessionExport({...job,status:'completed',running:false,file:'/Downloads/<not-html>.wds'});+ assert.equal(f.node('[data-export-detail]').textContent,'/Downloads/<not-html>.wds');+ assert.equal(f.node('[data-export-open]').hidden,false);assert.equal(f.node('[data-export-cancel]').hidden,true);+ assert.equal(f.node('[data-export-progress]').hidden,true);+ f.ctx.renderSessionExport(null);assert.equal(f.node('#wbs-sess-export-progress').hidden,true);+});+test('reload resumes daemon progress; stale responses cannot replace a newer job',async()=>{+ const f=fixture();const first=f.ctx.pollSessionExport();+ assert.equal(f.calls[0],'/api/sessions/export');+ const second=f.ctx.pollSessionExport('new');+ f.requests[1].resolve({job:{id:'new',running:false,status:'completed',file:'new.wds'}});await second;+ f.requests[0].resolve({job:{id:'old',running:true,status:'writing'}});await first;+ assert.equal(f.ctx.sessionsState.exportJob.id,'new');assert.equal(f.timers.length,0);+});+test('a daemon restart discards the missing job id instead of polling it forever',async()=>{+ const f=fixture();const poll=f.ctx.pollSessionExport('old');+ f.requests[0].reject({payload:{code:'EXPORT_JOB_NOT_FOUND'}});+ await new Promise(resolve=>setImmediate(resolve));+ assert.equal(f.calls[1],'/api/sessions/export');+ f.requests[1].resolve({job:null});await poll;+ assert.equal(f.node('#wbs-sess-export-progress').hidden,true);+});diff --git a/test/session-monitor.test.js b/test/session-monitor.test.jsindex 9625951..c004689 100644--- a/test/session-monitor.test.js+++ b/test/session-monitor.test.js@@ -140,6 +140,9 @@ test('session monitor interrupted gate accepts exactly what the judge would contassert.equal(decision(snapshot).trigger, true, 'judge should continue ' + JSON.stringify(snapshot));assert.equal(interrupted(snapshot), true, 'gate should bind ' + JSON.stringify(snapshot));});+ // 终局的模型限频/额度错误不应自动续跑,但必须绑定一次以记录限频状态。+ assert.equal(interrupted({ assistantId: 'req-rate-limit', terminal: true, terminalKnown: true, rateLimited: true }), true);+ assert.equal(interrupted({ assistantId: 'req-quota', terminal: true, terminalKnown: true, quotaExhausted: true }), true);// 仍在运行 / 等决策 / 恢复中:交给 in-progress 分支,不重复绑定assert.equal(interrupted({ assistantId: 'a', error: true, busy: true }), false);assert.equal(interrupted({ assistantId: 'a', error: true, blocked: true }), false);@@ -294,6 +297,29 @@ test('compat discovers multiple capability-shaped controllers and de-duplicatesassert.deepEqual(compat.findConversationControllers(doc).map((c) => c.conversationId), ['a', 'b']);});+test('auto-continue controller discovery accepts AI controllers without getMessagesViewState', () => {+ const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const start = inject.indexOf('function acFindConversationController()');+ const end = inject.indexOf('function acCaptureControllerError', start);+ const source = inject.slice(start, end);+ assert.match(source, /typeof controller\.messageStore\.getState === 'function'/);+ assert.doesNotMatch(source, /typeof controller\.getMessagesViewState === 'function'/);+ assert.match(source, /\[props\.value, props\.controller, props\.adapter\]/);+});++test('quota and model rate limit stops surface one renderer toast', () => {+ const start = injectSource.indexOf('function acNotifyLimit(snapshot)');+ const end = injectSource.indexOf('function acPickBodyBlock', start);+ const source = injectSource.slice(start, end);+ assert.match(source, /snapshot\.rateLimited/);+ assert.match(source, /snapshot\.quotaExhausted/);+ assert.match(source, /acLimitToastSeen/);+ assert.match(source, /toast\(message, true, root\)/);+ assert.match(source, /当前账号积分已耗尽/);+ assert.match(source, /当前模型已触发频率限制,已停止自动发送/);+ assert.doesNotMatch(source, /Auto-Continue 已停止/);+});+test('compat discovers the global session resource by capabilities', () => {const resource = { on() {}, off() {}, list() {}, getByIds() {} };const adapter = {diff --git a/test/session-size-filter.test.js b/test/session-size-filter.test.jsindex 1fe0de3..64d85a3 100644--- a/test/session-size-filter.test.js+++ b/test/session-size-filter.test.js@@ -10,7 +10,8 @@ function harness() {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: () => [] },+ sessionsPane: { querySelector: id => id === '#wbs-sess-export-progress' ? null : control(id), querySelectorAll: () => [] },+ sessState: { themeTakeover: true }, syncSessionModule() {},esc: value => String(value).replace(/</g, '<'), escAttr: String,updateAutoCopyAllButton() {}, isTaskSessionRecordUI: s => !!s.is_playground,fmtHumanTime: () => 'now', shortWs: String, SESS_WS_INIT: 5,diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.jsindex f2b388c..5ada616 100644--- a/test/session-sync-daemon.test.js+++ b/test/session-sync-daemon.test.js@@ -65,7 +65,7 @@ test('account two continuation updates account one and never account three', asyassert.equal((await h.copy()).copiedBytes, 0);});-test('automatic first copy to an account with no physical target uses the fast snapshot path', async t => {+test('automatic first copy to an account with no physical target streams snapshots and file copies', async t => {const h = harness(t);lib.removeAutoCopySessionMember(h.root, h.lineage, 'two', 'b');h.rows.delete('b');@@ -79,8 +79,8 @@ test('automatic first copy to an account with no physical target uses the fast stry {const result = await h.copy();assert.equal(result.status, 'copied');- assert.ok(syncReads > 0, 'first-time copies should use the synchronous snapshot path');- assert.equal(asyncReads, 0, 'first-time copies should not pay the async snapshot path');+ assert.equal(syncReads, 0, 'first-time copies must not buffer whole sessions');+ assert.ok(asyncReads > 0, 'first-time copies must use streaming snapshots');const mapping = lib.getAutoCopyMapping(h.root, h.lineage, 'two');assert.equal(mapping.targetStateRevision, h.ctx.sessionCopyStableStateRevision(h.rows.get(result.targetId)),'new mappings must record the inserted target row revision');diff --git a/test/session-sync.test.js b/test/session-sync.test.jsindex f6943b8..0a0f937 100644--- a/test/session-sync.test.js+++ b/test/session-sync.test.js@@ -4,7 +4,7 @@ const assert = require('node:assert/strict');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');-const { readSnapshot, readSnapshotAsync, readSessionFingerprintAsync, readSessionQuickFingerprintAsync, compareSnapshots, applySnapshot, applySnapshotAsync } = require('../scripts/session-sync.js');+const { readSnapshot, readSnapshotAsync, readSessionFingerprintAsync, readSessionQuickFingerprintAsync, compareSnapshots, applySnapshot, applySnapshotAsync, pruneSyncBackups, inspectSyncBackups } = require('../scripts/session-sync.js');const message = (role, text) => ({ type: 'message', role, content: [{ type: 'text', text }] });const base = [message('user', 'question'), message('assistant', 'answer')];@@ -212,6 +212,45 @@ test('async snapshots stream large transcripts and publication keeps the event lassert.ok(ticks > 0, 'large sync must yield to daemon HTTP and renderer work');});+test('async successful update removes its rollback backup', async t => {+ const f = fixture(t); f.write('a', base); f.write('b', [...base, message('user', 'next')]);+ const backupRoot = path.join(f.root, 'backups');+ const result = await applySnapshotAsync(+ await readSnapshotAsync(f.root, 'b', ['a', 'b']),+ await readSnapshotAsync(f.root, 'a', ['a', 'b']),+ { backupRoot }+ );+ assert.equal(fs.existsSync(result.backup), false);+ assert.deepEqual(fs.readdirSync(backupRoot), []);+});++test('async rollback backup contains only target files changed by the sync', async t => {+ const f = fixture(t);+ f.write('a', base); f.write('b', [...base, message('user', 'next')]);+ for (const id of ['a', 'b']) {+ const file = path.join(f.root, 'workspace', 'sessions', id, 'editor-settings.json');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, '{"enabled":true}\n');+ }+ const backupRoot = path.join(f.root, 'backups');+ await assert.rejects(applySnapshotAsync(+ await readSnapshotAsync(f.root, 'b', ['a', 'b']),+ await readSnapshotAsync(f.root, 'a', ['a', 'b']),+ {+ backupRoot,+ commit: async () => {+ fs.writeFileSync(f.file('a'), 'official write');+ throw Error('DB failure');+ },+ }+ ), /DB failure/);+ const backups = fs.readdirSync(backupRoot);+ assert.equal(backups.length, 1);+ const files = fs.readdirSync(path.join(backupRoot, backups[0], 'files', 'projects', 'project'));+ assert.deepEqual(files, ['__session__.jsonl']);+ assert.equal(fs.existsSync(path.join(backupRoot, backups[0], 'files', 'workspace')), false);+});+test('async publication rolls back commit failures without overwriting concurrent official writes', async t => {const f = fixture(t);f.write('a', [...base, message('user', 'continued')]);@@ -242,17 +281,93 @@ test('equal messages repair missing supporting files but conflicting supportingfs.mkdirSync(path.dirname(aux('b')), { recursive: true }); fs.writeFileSync(aux('b'), 'different');assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'conflict');});-test('update retains a backup, validates bytes, and never changes a third copy', async t => {+test('successful update removes its rollback backup and never changes a third copy', async t => {const f = fixture(t); f.write('a', base); f.write('b', [...base, message('user', 'next')]); f.write('c', base);const original = fs.readFileSync(f.file('a')); let committed = false;+ const backupRoot = path.join(f.root, 'backups');const result = await applySnapshot(f.read('b'), f.read('a'), {- backupRoot: path.join(f.root, 'backups'), metadata: { id: 'a', title: 'old' },+ backupRoot, metadata: { id: 'a', title: 'old' },commit: async () => { committed = true; },});assert.equal(committed, true);assert.deepEqual(fs.readFileSync(f.file('a')), fs.readFileSync(f.file('b')));assert.deepEqual(fs.readFileSync(f.file('c')), original);- assert.deepEqual(fs.readFileSync(path.join(result.backup, 'files', 'projects', 'project', '__session__.jsonl')), original);+ assert.equal(fs.existsSync(result.backup), false);+ assert.deepEqual(fs.readdirSync(backupRoot), []);+});++test('rollback backup contains only target files changed by the sync', async t => {+ const f = fixture(t);+ f.write('a', base); f.write('b', [...base, message('user', 'next')]);+ for (const id of ['a', 'b']) {+ const file = path.join(f.root, 'workspace', 'sessions', id, 'editor-settings.json');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, '{"enabled":true}\n');+ }+ const backupRoot = path.join(f.root, 'backups');+ await assert.rejects(applySnapshot(f.read('b'), f.read('a'), {+ backupRoot,+ commit: async () => {+ // Simulate a concurrent official write after publication. The rollback+ // must retain its backup so the recovery case is inspectable.+ fs.writeFileSync(f.file('a'), 'official write');+ throw Error('DB failure');+ },+ }), /DB failure/);+ const backups = fs.readdirSync(backupRoot);+ assert.equal(backups.length, 1);+ const backupFiles = [];+ const visit = (directory, relative = '') => {+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {+ const next = relative ? path.join(relative, entry.name) : entry.name;+ if (entry.isDirectory()) visit(path.join(directory, entry.name), next);+ else if (next !== 'journal.json') backupFiles.push(next);+ }+ };+ visit(path.join(backupRoot, backups[0], 'files'));+ assert.deepEqual(backupFiles, [path.join('projects', 'project', '__session__.jsonl')]);+});++test('backup pruning removes completed and stale crash journals but keeps recovery-needed data', t => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-sync-prune-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const now = 10_000_000;+ const make = (name, status, age) => {+ const dir = path.join(root, name); fs.mkdirSync(dir, { recursive: true });+ if (status !== null) fs.writeFileSync(path.join(dir, 'journal.json'), JSON.stringify({ status }));+ fs.utimesSync(dir, new Date(now - age), new Date(now - age));+ };+ make('sync-committed', 'committed', 0);+ make('sync-rolled-back', 'rolled-back', 0);+ make('sync-prepared-old', 'prepared', 31 * 24 * 60 * 60 * 1000);+ make('sync-prepared-new', 'prepared', 1_000);+ make('sync-recovery', 'recovery-needed', 365 * 24 * 60 * 60 * 1000);+ make('sync-malformed-old', null, 31 * 24 * 60 * 60 * 1000);+ const result = pruneSyncBackups(root, { now, maxAgeMs: 30 * 24 * 60 * 60 * 1000 });+ assert.equal(result.removed, 4);+ assert.equal(result.retainedRecovery, 1);+ assert.equal(fs.existsSync(path.join(root, 'sync-prepared-new')), true);+ assert.equal(fs.existsSync(path.join(root, 'sync-recovery')), true);+});++test('backup inspection reports bytes and recovery-needed count without reading payloads', t => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-backup-inspect-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const backupRoot = path.join(root, 'backups');+ const recovery = path.join(backupRoot, 'sync-recovery');+ const prepared = path.join(backupRoot, 'sync-prepared');+ fs.mkdirSync(path.join(recovery, 'files'), { recursive: true });+ fs.mkdirSync(path.join(prepared, 'files'), { recursive: true });+ fs.writeFileSync(path.join(recovery, 'files', 'old.jsonl'), '12345');+ fs.writeFileSync(path.join(prepared, 'files', 'pending.jsonl'), '12');+ fs.writeFileSync(path.join(recovery, 'journal.json'), JSON.stringify({ status: 'recovery-needed' }));+ fs.writeFileSync(path.join(prepared, 'journal.json'), JSON.stringify({ status: 'prepared' }));+ const stats = inspectSyncBackups(backupRoot);+ assert.equal(stats.count, 2);+ assert.equal(stats.recoveryCount, 1);+ assert.equal(stats.pendingCount, 1);+ assert.equal(stats.recoveryBytes, 5 + Buffer.byteLength('{"status":"recovery-needed"}'));+ assert.equal(stats.totalBytes, stats.recoveryBytes + 2 + Buffer.byteLength('{"status":"prepared"}'));});test('failed commit restores target bytes; source changes abort before publication', async t => {const f = fixture(t); f.write('a', base); f.write('b', [...base, message('user', 'next')]);diff --git a/test/session-transfer.test.js b/test/session-transfer.test.jsindex 5607850..c437881 100644--- a/test/session-transfer.test.js+++ b/test/session-transfer.test.js@@ -5,7 +5,7 @@ const fs = require('node:fs');const path = require('node:path');const os = require('node:os');const crypto = require('node:crypto');-const { writeSessionTransfer, readSessionTransfer, receiveSessionUpload } = require('../scripts/session-transfer');+const { writeSessionTransfer, readSessionTransfer, receiveSessionUpload, createSessionExportJobs } = require('../scripts/session-transfer');const { Readable } = require('node:stream');function fixture(t) {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-stream-test-'));@@ -73,7 +73,8 @@ test('real session export/import routes round-trip binary archives and retain owfs.writeFileSync(original, crypto.randomBytes(100001));const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const stored = [], records = [{ id, user_id: 'original-owner', title: 'fixture' }];- const ctx = { fs, path, os, crypto, Buffer, ...require('../scripts/secure-transfer'),+ const opened = [];+ const ctx = { fs, path, os, crypto, Buffer, URL, IS_WIN: false, IS_LINUX: false, runCommand: async (command, args) => { opened.push(args); return {code:0}; }, ...require('../scripts/secure-transfer'),writeSessionTransfer, readSessionTransfer, receiveSessionUpload,transferPipeline: require('node:stream/promises').pipeline,PROFILE: { dataRoot: home }, MAX_SESSION_ID_LENGTH: 200,@@ -88,8 +89,9 @@ test('real session export/import routes round-trip binary archives and retain owvm.runInContext(source.slice(source.indexOf('const MAX_SESSION_EXPORT_FILES'), source.indexOf('async function copySessionRecord(')), ctx);const validStart = source.indexOf('function isValidSessionId(');vm.runInContext(source.slice(validStart, source.indexOf('\n}\n', validStart) + 2), ctx);- const routeStart = source.indexOf("if (req.method === 'POST' && p === '/api/sessions/export')");- vm.runInContext('function serve(req, res) { const p = req.url; ' + source.slice(routeStart, source.indexOf(' // 复制会话:POST /api/sessions/copy', routeStart)) + '\n}', ctx);+ ctx.sessionExportJobs = createSessionExportJobs({ prepare: ctx.prepareSessionExport, directory: () => path.join(dir, 'Downloads') });+ const routeStart = source.indexOf("if (req.method === 'GET' && p === '/api/sessions/export')");+ vm.runInContext("function serve(req, res) { const url = new URL(req.url, 'http://127.0.0.1'); const p = url.pathname; " + source.slice(routeStart, source.indexOf(' // 复制会话:POST /api/sessions/copy', routeStart)) + '\n}', ctx);const server = http.createServer((req, res) => ctx.serve(req, res));await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }));@@ -115,15 +117,37 @@ test('real session export/import routes round-trip binary archives and retain owassert.deepEqual(fs.readFileSync(path.join(home, 'tasks', newId, '测试附件.bin')), fs.readFileSync(original));assert.equal((await upload('密码', 'override-owner')).status, 200);assert.equal(stored[1][2], 'override-owner');+ const response = await fetch(base + '/api/sessions/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids: [id], password: '密码', background: true }) });+ assert.equal(response.status, 202);+ const { job } = await response.json();+ assert.equal(job.running, true);+ await ctx.sessionExportJobs.wait();+ const done = (await (await fetch(base + '/api/sessions/export?id=' + job.id)).json()).job;+ assert.equal(done.status, 'completed');+ assert.equal(path.dirname(done.file), path.join(dir, 'Downloads'));+ const saved = await readSessionTransfer(done.file, '密码', path.join(dir, 'saved'));+ assert.deepEqual(fs.readFileSync(saved.sessions[0].files[0].source), fs.readFileSync(original));+ assert.equal((await fetch(base + '/api/sessions/export?id=unknown')).status, 404);+ const post = (route, body) => fetch(base + route, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });+ assert.equal((await post('/api/sessions/export/open', { id: 'unknown', path: '/etc' })).status, 400);+ assert.equal(opened.length, 0);+ assert.equal((await post('/api/sessions/export/open', { id: job.id, path: '/etc' })).status, 200);+ assert.equal(opened[0][0], path.join(dir, 'Downloads'));+ assert.equal((await post('/api/sessions/export/cancel', { id: 'unknown' })).status, 404);+});-test('panel uses Blob responses/uploads and release includes the streaming module', () => {+test('panel exports in the background while retaining binary uploads and legacy transfers', () => {const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');const build = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');assert.doesNotMatch(daemon, /MAX_SESSION_EXPORT_BYTES|附件超过 256/);assert.match(inject, /opts\.responseType === 'blob'[\s\S]*r\.blob\(\)/);assert.match(inject, /new Blob\(\[prefix, metadata, file\]/);+ const start = inject.indexOf("var exportBtn = sessionsPane.querySelector('#wbs-sess-export')");+ const exportUi = inject.slice(start, inject.indexOf('var importBtn =', start));+ assert.match(exportUi, /background: true/);+ assert.doesNotMatch(exportUi, /responseType: 'blob'|downloadTransfer/);assert.match(build, /session-transfer\.js/);const publicPaths = daemon.match(/const PUBLIC_API_PATHS = new Set\(([\s\S]*?)\);/);assert.doesNotMatch(publicPaths[1], /sessions\/(export|import)/);@@ -167,3 +191,14 @@ test('authenticated archives still reject path traversal, duplicates and excess}assert.equal(fs.existsSync(path.join(dir, 'outside')), false);});++test('cancelling an active streaming archive closes input and removes partial output', async t => {+ const dir = fixture(t), file = path.join(dir, 'source'), out = path.join(dir, 'export.wds');+ const fd = fs.openSync(file, 'w'); fs.ftruncateSync(fd, 16 * 1024 * 1024); fs.closeSync(fd);+ const controller = new AbortController(); let read = 0;+ await assert.rejects(writeSessionTransfer(out, archive(file, fs.statSync(file).size), 'password', {+ signal: controller.signal, onProgress(bytes) { read = bytes; controller.abort(); },+ }), error => error.name === 'AbortError');+ assert.ok(read > 0 && read < fs.statSync(file).size);+ assert.equal(fs.existsSync(out), false);+});diff --git a/test/theme-account-switch.test.js b/test/theme-account-switch.test.jsnew file mode 100644index 0000000..76eb252--- /dev/null+++ b/test/theme-account-switch.test.js@@ -0,0 +1,76 @@+'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');+function expression(target = 'target') {+ const start = source.indexOf('function accountSwitchThemeExpression(');+ assert.ok(start >= 0, 'theme switch snapshot builder exists');+ const context = {};+ vm.runInNewContext(source.slice(start, source.indexOf('\nasync function preserveAccountSwitchTheme', start)), context);+ return context.accountSwitchThemeExpression(target);+}+function renderer(resource = 'dark') {+ const applied = { kind: 'theme', resourceKey: resource, appearance: resource === 'dark' ? 'dark' : 'light', nameZh: resource };+ const entries = new Map([+ ['workbuddy.appearance.lastApplied', JSON.stringify(applied)],+ ['workbuddy.appearance.state::personal::source', '{"currentTheme":"dark"}'],+ ['workbuddy.appearance.state::personal::other', '{"currentTheme":"light"}'],+ ['workbuddy.appearance.state::enterprise::target', '{"currentTheme":"light","extra":true}'],+ ['workbuddy.appearance.mode::enterprise::enterprise::target', 'light'],+ ['workbuddy.appearance.lastApplied.css', '{"resourceKey":"theme-demo","css":"body{color:red}"}'],+ ]);+ const localStorage = { get length() { return entries.size; }, key: i => [...entries.keys()][i], getItem: key => entries.get(key) ?? null, setItem: (key, value) => entries.set(key, value) };+ return { entries, context: { localStorage, document: { documentElement: { getAttribute: () => applied.appearance } } } };+}+for (const resource of ['light', 'dark', 'theme-demo']) test('account switch gives current ' + resource + ' precedence over destination cloud theme', async () => {+ const h = renderer(resource), before = new Map(h.entries);+ assert.equal((await vm.runInNewContext(expression(), h.context)).prepared, true);+ for (const scope of ['personal', 'enterprise']) {+ const state = JSON.parse(h.entries.get('workbuddy.appearance.state::' + scope + '::target'));+ assert.equal(state.currentTheme, resource);+ // WorkBuddy syncCloudTheme prioritizes this pending selection over getSelections().+ assert.equal(state.pendingSync.theme, resource);+ assert.equal(JSON.parse(h.entries.get('workbuddy.appearance.lastApplied::' + scope + '::target')).resourceKey, resource);+ }+ assert.equal(h.entries.get('workbuddy.appearance.mode::enterprise::enterprise::target'), resource === 'dark' ? 'dark' : 'light');+ assert.equal(JSON.parse(h.entries.get('workbuddy.appearance.state::enterprise::target')).extra, true);+ for (const key of ['workbuddy.appearance.state::personal::source', 'workbuddy.appearance.state::personal::other', 'workbuddy.appearance.lastApplied', 'workbuddy.appearance.lastApplied.css']) assert.equal(h.entries.get(key), before.get(key));+});+test('next switch uses the latest official selection and keeps no persistent hook', async () => {+ const h = renderer('light');+ await vm.runInNewContext(expression(), h.context);+ h.context.localStorage.setItem('workbuddy.appearance.lastApplied', JSON.stringify({ kind: 'theme', resourceKey: 'theme-new', appearance: 'light' }));+ await vm.runInNewContext(expression('next'), h.context);+ assert.equal(JSON.parse(h.entries.get('workbuddy.appearance.state::personal::next')).currentTheme, 'theme-new');+ assert.doesNotMatch(expression(), /MutationObserver|setInterval|addEventListener|fetch\(/);+});+test('missing or malformed appearance data does not alter target account settings', async () => {+ for (const raw of [null, '{broken', '{"resourceKey":"invalid/resource"}']) {+ const h = renderer();+ if (raw === null) h.entries.delete('workbuddy.appearance.lastApplied');+ else h.entries.set('workbuddy.appearance.lastApplied', raw);+ const before = [...h.entries];+ assert.equal((await vm.runInNewContext(expression(), h.context)).prepared, false);+ assert.deepEqual([...h.entries], before);+ }+});+++test('stale cross-window hydration cannot erase the pending selection on the next startup', async () => {+ const h = renderer('dark');+ let authority = 'light';+ h.context.wb = { config: { async setPreference(key, value) {+ assert.equal(key, 'appearanceTheme'); authority = value;+ } } };+ await vm.runInNewContext(expression(), h.context);+ // Official installAppearanceCrossWindowSync only hydrates a non-empty string.+ if (typeof authority === 'string' && authority) {+ h.context.localStorage.setItem('workbuddy.appearance.state::personal::target', JSON.stringify({ currentTheme: authority }));+ }+ const state = JSON.parse(h.entries.get('workbuddy.appearance.state::personal::target'));+ assert.equal(state.currentTheme, 'dark');+ assert.equal(state.pendingSync.theme, 'dark');+});diff --git a/test/theme-blur.test.js b/test/theme-blur.test.jsindex abf1fbc..d8072ef 100644--- a/test/theme-blur.test.js+++ b/test/theme-blur.test.js@@ -23,19 +23,26 @@ test('theme pane exposes a percentage blur slider and syncs it with the daemon',assert.match(inject, /JSON\.stringify\(\{ blur: pct \/ 100 \}\)/);});-test('theme pane keeps avatar controls visible and gates wallpaper controls to WorkDaddy theme', () => {+test('theme pane keeps avatar controls visible and gates wallpaper controls to frosted takeover', () => {assert.doesNotMatch(inject, /背景与头像/);assert.match(inject, /wbs-avatar-card/);- assert.match(inject, /<div class="wbs-pcard wbs-wallpaper-card" id="wbs-wallpaper-card" style="display:none">/);+ assert.match(inject, /<div class="wbs-pcard wbs-wallpaper-card wbs-theme-managed" id="wbs-wallpaper-card" style="display:none">/);assert.match(inject, /function syncWallpaperCardVisibility\(themeId\)/);- assert.match(inject, /var visible = themeId === 'nebula'/);- assert.match(inject, /syncWallpaperCardVisibility\(id\)/);- assert.match(inject, /syncWallpaperCardVisibility\(cur\)/);+ assert.match(inject, /var visible = sessState\.themeTakeover/);+ assert.match(inject, /syncWallpaperCardVisibility\('nebula'\)/);});-test('theme pane uses the requested blur labels and nebula tab', () => {- // 主题第 4 个 tab 文案为「毛玻璃」,且词典含英文 Frosted glass- assert.match(inject, /data-wbs-theme-option="nebula">毛玻璃<\/button>/);+test('wallpaper loading leaves the loading state on daemon timeout and can retry', () => {+ const load = inject.slice(inject.indexOf('function loadWallpapers(force)'), inject.indexOf('\n function setOpen(', inject.indexOf('function loadWallpapers(force)')));+ assert.match(load, /wallpaperTimeout/);+ assert.match(load, /Promise\.race\(\[wallpaperRequest, wallpaperTimeout\]\)/);+ assert.match(load, /grid\.dataset\.loaded = ''/);+ assert.match(load, /壁纸加载失败(daemon 不可达)/);+});++test('theme pane uses the requested blur labels and frosted glass switch', () => {+ assert.match(inject, /<div class="wbs-pcard-title">毛玻璃主题<\/div>/);+ assert.doesNotMatch(inject, /data-wbs-theme-option=/);assert.match(inject, /'毛玻璃': 'Frosted glass'/);assert.doesNotMatch(inject, /背景毛玻璃<span class="wbs-blur-hint">0% 不调节背景图<\/span>/);assert.match(inject, /<label class="wbs-blur-label" for="wbs-bg-blur-range">背景毛玻璃<\/label>/);diff --git a/test/theme-patches.test.js b/test/theme-patches.test.jsindex 0518040..04eaf60 100644--- a/test/theme-patches.test.js+++ b/test/theme-patches.test.js@@ -59,3 +59,33 @@ test('nebula removes backgrounds from the template switcher and code copy tooltiassert.match(patch.css, /background:transparent !important/);assert.match(patch.css, /box-shadow:none !important/);});++test('nebula removes the send SVG disc without hiding the arrow or changing other icons', () => {+ const patch = patches.find(item => item.id === 'patch-105');+ assert.ok(patch);+ assert.equal(patch.themeId, 'nebula');+ assert.match(patch.css, /\.cr-send-button__icon svg\[viewBox="0 0 32 32"\]>path\[d\^="M16 32C24\.8366"\]/);+ assert.match(patch.css, /d:path\("M16 19\.2104/);+ assert.match(patch.css, /fill:var\(--wb-button-primary-fg\)/);+ assert.doesNotMatch(patch.css, /display:none|visibility:hidden|opacity:0|fill:transparent/);+});++test('legacy tooltip backgrounds exclude inline anchors and copy/send trigger wrappers', () => {+ const css = patches.find(p => p.id === 'patch-15').css;+ const rule = css.split('}').find(rule => rule.includes('[class*="tooltip"]'));+ for (const cls of ['cr-clickable-path-tooltip-anchor', 'cr-code-block__copy-tooltip', 'cr-send-button__tooltip-wrapper']) {+ assert.ok(rule.includes(':not(.' + cls + ')'), cls + ' is a trigger, not a tooltip surface');+ }+ assert.match(rule, /background:var\(--wb-bg-popover\)/, 'real tooltips retain a readable surface');+});++test('nebula file links and code copy controls use transparent backgrounds in all interaction states', () => {+ const patch = patches.find(p => p.id === 'patch-106');+ assert.ok(patch);+ assert.equal(patch.themeId, 'nebula');+ for (const cls of ['cr-clickable-path-tooltip-anchor', 'cr-clickable-path', 'cr-code-block__copy-tooltip', 'cr-code-block__copy-button']) {+ assert.ok(patch.css.includes('.' + cls));+ }+ assert.match(patch.css, /background:transparent !important/);+ assert.doesNotMatch(patch.css, /:hover|:focus|:active/, 'unconditional important override covers native hover and active fills');+});diff --git a/test/theme-restore-stability.test.js b/test/theme-restore-stability.test.jsindex df64e2c..57f32ce 100644--- a/test/theme-restore-stability.test.js+++ b/test/theme-restore-stability.test.js@@ -7,32 +7,36 @@ const path = require('node:path');const vm = require('node:vm');const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');-test('default theme is restored after navigation just like a custom theme', async () => {+test('theme takeover always restores the frosted theme after navigation', async () => {const start = source.indexOf('async function restoreSavedTheme()');const end = source.indexOf('\n/**', start);const applied = [];const context = {PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },+ readSessionState: () => ({ themeTakeoverEnabled: true }),DATA_DIR: '/test', path, fs: { existsSync: () => true, readFileSync: () => '{"id":"default"}' },applyThemeByCdp: async id => applied.push(id),};vm.runInNewContext(source.slice(start, end), context);await context.restoreSavedTheme();- assert.deepEqual(applied, ['default']);+ assert.deepEqual(applied, ['nebula']);});-async function themeExpression(id) {- const start = source.indexOf('async function applyThemeByCdp(id)');+async function themeExpression(id, takeover = true, accountUid = null, options = {}) {+ const start = source.indexOf('async function applyThemeByCdp(id, options = {})');const end = source.indexOf('\n/**', start);let expression;const context = {PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },- currentAccount: () => null, getTheme: () => ({ dark: id !== 'default', colors: {} }),+ readSessionState: () => ({ themeTakeoverEnabled: takeover }),+ themeApplyGeneration: 0,+ setTimeout: resolve => resolve(),+ currentAccount: () => accountUid ? { uid: accountUid } : null, getTheme: () => ({ dark: id !== 'default', colors: {} }),LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',- cdpSend: async (_, params) => { expression = params.expression; return { result: { value: { applied: true } } }; },+ cdpSend: async (_, params) => { expression = params.expression; return { result: { value: { applied: true, ready: true } } }; },};vm.runInNewContext(source.slice(start, end), context);- await context.applyThemeByCdp(id);+ await context.applyThemeByCdp(id, options);return expression;}@@ -56,7 +60,7 @@ function renderer() {};const storage = new Map();const context = { window: {}, document,- localStorage: { get length() { return storage.size; }, key: i => [...storage.keys()][i], getItem: k => storage.get(k) || null, setItem: (k, v) => storage.set(k, v) },+ localStorage: { get length() { return storage.size; }, key: i => [...storage.keys()][i], getItem: k => storage.get(k) || null, setItem: (k, v) => storage.set(k, v), removeItem: k => storage.delete(k) },getComputedStyle: () => ({ getPropertyValue: () => '' }),MutationObserver: class {constructor(callback) { this.callback = callback; this.active = false; observers.push(this); }@@ -66,6 +70,39 @@ function renderer() {return { context, document, observers, flush: () => observers.filter(o => o.active).forEach(o => o.callback([])) };}+for (const snapshot of ['light', 'dark', null]) test('native sync follows both official theme buttons with snapshot ' + snapshot, () => {+ const { context, document } = renderer();+ const intervals = new Map();+ let timer = 0;+ context.setInterval = fn => { intervals.set(++timer, fn); return timer; };+ context.clearInterval = id => intervals.delete(id);+ if (snapshot) context.localStorage.setItem('workbuddy.appearance.lastApplied', JSON.stringify({ kind: 'theme', resourceKey: snapshot, appearance: snapshot }));+ const savedSnapshot = context.localStorage.getItem('workbuddy.appearance.lastApplied');+ const start = source.indexOf('function nativeAppearanceSyncExpression()');+ const end = source.indexOf('\nasync function startNativeAppearanceSyncByCdp()', start);+ const expression = vm.runInNewContext(source.slice(start, end) + '\nnativeAppearanceSyncExpression();', {});+ vm.runInNewContext(expression, context);+ for (const mode of ['dark', 'light', 'dark', 'light']) {+ // Official AI menu calls ThemeManager.setTheme: DOM + agent-ui-theme change,+ // while the appearance-panel snapshot may be stale or absent.+ const native = JSON.stringify({ theme: mode, followSystem: false,+ vsCodeThemeName: mode === 'dark' ? 'IDE Night' : 'IDE Light', vsCodeThemeKind: 'vscode-' + mode });+ context.localStorage.setItem('agent-ui-theme', native);+ document.documentElement.setAttribute('data-theme', mode);+ document.body.setAttribute('data-vscode-theme-kind', 'vscode-' + mode);+ for (let tick = 0; tick < 3; tick++) [...intervals.values()].forEach(fn => fn());+ assert.equal(document.documentElement.getAttribute('data-theme'), mode);+ assert.equal(document.documentElement.classList.contains('cb-dark'), mode === 'dark');+ assert.equal(document.body.getAttribute('data-vscode-theme-kind'), 'vscode-' + mode);+ assert.equal(context.localStorage.getItem('agent-ui-theme'), native);+ assert.equal(context.localStorage.getItem('workbuddy.appearance.lastApplied'), savedSnapshot);+ // A daemon reconnect must replace the timer and retain the last selection.+ vm.runInNewContext(expression, context);+ assert.equal(intervals.size, 1);+ assert.equal(document.documentElement.getAttribute('data-theme'), mode);+ }+});+test('late account appearance cannot override the chosen light or dark theme', async () => {for (const id of ['default', 'nebula']) {const { context, document, flush } = renderer();@@ -79,7 +116,9 @@ test('late account appearance cannot override the chosen light or dark theme', aflush();assert.equal(document.documentElement.getAttribute('data-theme'), mode);assert.equal(document.documentElement.classList.contains('cb-dark'), mode === 'dark');+ assert.equal(document.documentElement.classList.contains('cb-light'), mode !== 'dark');assert.equal(document.body.getAttribute('data-vscode-theme-kind'), mode === 'dark' ? 'vscode-dark' : 'vscode-light');+ assert.equal(document.body.classList.contains('vscode-light'), mode !== 'dark');}});@@ -120,3 +159,437 @@ test('native theme choices cannot be shadowed by a custom theme file with the saassert.equal(ctx.getTheme('dark'), ctx.BUILTIN_THEMES.dark);assert.equal(ctx.getTheme('default'), ctx.BUILTIN_THEMES.default);});+++test('theme takeover opt-out follows native appearance on reload without forcing light', async () => {+ const start = source.indexOf('async function restoreSavedTheme()');+ const applied = [];+ const context = {+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },+ DATA_DIR: '/test', path, fs: { existsSync: () => true, readFileSync: () => '{"id":"nebula"}' },+ readSessionState: () => ({ themeTakeoverEnabled: false }),+ startNativeAppearanceSyncByCdp: async () => applied.push('native'),+ applyThemeByCdp: async id => applied.push(id),+ };+ vm.runInNewContext(source.slice(start, source.indexOf('\n/**', start)), context);+ await context.restoreSavedTheme();+ await context.restoreSavedTheme();+ assert.deepEqual(applied, ['native', 'native']);+ assert.match(source, /accountSnapshot/);+ assert.match(source, /workdaddy\.theme\.native-snapshot::' \+ WBS_UID/);+});++test('session settings default to takeover and retain opt-out when editing other switches', () => {+ let settings = { wbs: { session: { seeded: true, state: {}, phrases: [] } } };+ const context = {+ readWorkbuddySettings: () => structuredClone(settings),+ writeWorkbuddySettings: value => { settings = value; }, log() {},+ };+ const start = source.indexOf("const SESS_NS = 'session';");+ const end = source.indexOf('\n}', source.indexOf('function setSessionSwitch(', start)) + 2;+ vm.runInNewContext(source.slice(start, end), context);+ assert.equal(context.readSessionState().themeTakeoverEnabled, true);+ context.setSessionSwitch('themeTakeoverEnabled', false);+ context.setSessionSwitch('phraseEnabled', false);+ assert.equal(context.readSessionState().themeTakeoverEnabled, false);+});+++test('manual theme changes still work with takeover off but install no theme guard', async () => {+ const { context, document, observers } = renderer();+ vm.runInNewContext(await themeExpression('dark', false), context);+ assert.equal(document.documentElement.getAttribute('data-theme'), 'dark');+ assert.equal(observers.filter(o => o.active).length, 0);+});++test('turning off takeover restores the WorkBuddy appearance saved before takeover', async () => {+ const { context, document, observers } = renderer();+ const uid = 'current';+ context.localStorage.setItem('agent-ui-theme', JSON.stringify({ theme: 'dark', followSystem: false, vsCodeThemeName: 'IDE Night', vsCodeThemeKind: 'vscode-dark' }));+ context.localStorage.setItem('workbuddy.appearance.lastApplied', JSON.stringify({ resourceKey: 'dark', appearance: 'dark' }));+ context.localStorage.setItem('workbuddy.appearance.mode::personal::personal::' + uid, 'dark');+ context.localStorage.setItem('workbuddy.appearance.state::personal::' + uid, JSON.stringify({ currentTheme: 'dark' }));+ context.localStorage.setItem('workbuddy.appearance.lastApplied::personal::' + uid, JSON.stringify({ resourceKey: 'dark', appearance: 'dark' }));+ vm.runInNewContext(await themeExpression('nebula', true, uid), context);+ // Seed the persisted pre-takeover snapshot explicitly; the helper above+ // captures the final CDP expression, while this test focuses on release.+ context.localStorage.setItem('workdaddy.theme.native-snapshot::' + uid, JSON.stringify({ keys: [+ ['agent-ui-theme', JSON.stringify({ theme: 'dark', followSystem: false, vsCodeThemeName: 'IDE Night', vsCodeThemeKind: 'vscode-dark' })],+ ['workbuddy.appearance.lastApplied', JSON.stringify({ resourceKey: 'dark', appearance: 'dark' })],+ ['workbuddy.appearance.mode::personal::personal::' + uid, 'dark'],+ ['workbuddy.appearance.state::personal::' + uid, JSON.stringify({ currentTheme: 'dark' })],+ ['workbuddy.appearance.lastApplied::personal::' + uid, JSON.stringify({ resourceKey: 'dark', appearance: 'dark' })],+ ] }));+ const oldGuard = context.window.__wbsThemeGuard;+ document.adoptedStyleSheets = [+ { cssRules: [{ cssText: ':root { --wb-bg-primary: pink; }' }] },+ { cssRules: [{ cssText: '.official { color: red; }' }] },+ ];+ context.localStorage.setItem('workbuddy.appearance.lastApplied.css', JSON.stringify({ resourceKey: 'special', css: ':root { --wb-bg-primary: pink; }' }));+ context.localStorage.setItem('workbuddy.appearance.mode::personal::personal::other', 'dark');+ const daemon = {+ cdp: { connected: true }, themeApplyGeneration: 0,+ readSessionState: () => ({ themeTakeoverEnabled: false }),+ currentAccount: () => ({ uid }),+ cdpSend: async (_, params) => { vm.runInNewContext(params.expression, context); return {}; },+ startNativeAppearanceSyncByCdp: async () => {+ const applied = JSON.parse(context.localStorage.getItem('workbuddy.appearance.lastApplied') || '{}');+ const dark = applied.appearance === 'dark' || applied.resourceKey === 'dark';+ document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');+ document.body.setAttribute('data-vscode-theme-name', dark ? 'IDE Night' : 'IDE Light');+ },+ applyThemeByCdp: async (id, options) => {+ assert.equal(id, 'default');+ assert.equal(options.release, true);+ vm.runInNewContext(await themeExpression(id, false, uid, options), context);+ },+ };+ const start = source.indexOf('async function releaseThemeByCdp()');+ vm.runInNewContext(source.slice(start, source.indexOf('async function restoreNativeAppearanceByCdp()', start)), daemon);+ const restoreNativeStart = source.indexOf('async function restoreNativeAppearanceByCdp()');+ vm.runInNewContext(source.slice(restoreNativeStart, source.indexOf('/** 恢复已保存的主题', restoreNativeStart)), daemon);+ await daemon.releaseThemeByCdp();+ assert.equal(document.getElementById('wbs-theme-style'), null);+ assert.equal(oldGuard.active, false);+ assert.equal(observers.filter(o => o.active).length, 0);+ assert.equal(document.documentElement.getAttribute('data-theme'), 'dark');+ assert.equal(document.body.getAttribute('data-vscode-theme-name'), 'IDE Night');+ assert.equal(JSON.parse(context.localStorage.getItem('agent-ui-theme')).theme, 'dark');+ assert.equal(JSON.parse(context.localStorage.getItem('workbuddy.appearance.lastApplied')).resourceKey, 'dark');+ assert.equal(context.localStorage.getItem('workbuddy.appearance.lastApplied.css'), null);+ assert.equal(context.localStorage.getItem('workdaddy.theme.native-snapshot::' + uid), null);+ assert.equal(context.localStorage.getItem('workbuddy.appearance.mode::personal::personal::other'), 'dark');+ assert.equal(document.adoptedStyleSheets.length, 1);+});++test('turning off takeover reapplies the saved official special theme', async () => {+ const { context } = renderer();+ const uid = 'current';+ const savedTheme = {+ kind: 'theme', resourceKey: 'theme-wind', appearance: 'light',+ nameZh: '有风', nameEn: 'Wind', vipLevel: 'free', updatedAt: 0,+ };+ const calls = [];+ context.wb = { config: { setPreference: async (key, value) => { calls.push([key, value]); } } };+ context.localStorage.setItem('workdaddy.theme.native-snapshot::' + uid, JSON.stringify({ keys: [+ ['agent-ui-theme', JSON.stringify({ theme: 'light', followSystem: false, vsCodeThemeName: 'IDE Light', vsCodeThemeKind: 'vscode-light' })],+ ['workbuddy.appearance.lastApplied', JSON.stringify(savedTheme)],+ ['workbuddy.appearance.lastApplied.css', JSON.stringify({ resourceKey: 'theme-wind', css: ':root { --wb-button-primary-bg: #8a6f4d; }' })],+ ['workbuddy.appearance.state::personal::' + uid, JSON.stringify({ currentTheme: 'theme-wind' })],+ ['workbuddy.appearance.lastApplied::personal::' + uid, JSON.stringify(savedTheme)],+ ] }));+ const daemon = {+ cdp: { connected: true },+ currentAccount: () => ({ uid }),+ cdpSend: async (_, params) => {+ const value = await vm.runInNewContext(params.expression, context);+ return { result: { value } };+ },+ startNativeAppearanceSyncByCdp: async () => {},+ };+ const start = source.indexOf('async function restoreNativeAppearanceByCdp()');+ vm.runInNewContext(source.slice(start, source.indexOf('/** 恢复已保存的主题', start)), daemon);+ await daemon.restoreNativeAppearanceByCdp();+ assert.deepEqual(calls, [['appearanceTheme', 'theme-wind']]);+});++test('native opt-out syncs WorkBuddy special CSS from the settings window', () => {+ const start = source.indexOf('function nativeAppearanceSyncExpression()');+ const end = source.indexOf('\nasync function releaseThemeByCdp()', start);+ const expression = source.slice(start, end);+ assert.match(expression, /lastApplied\.css/);+ assert.match(expression, /new CSSStyleSheet\(\)/);+ assert.match(expression, /setInterval\(sync, 500\)/);+ assert.match(source.slice(source.indexOf('const expr = \`\(function\(\)\{', source.indexOf('async function applyThemeByCdp')), source.indexOf('function wbsBuiltinAppearance')), /__wbsNativeAppearanceSync/);+});+++test('manual native theme selection does not overwrite other accounts or the legacy fallback', async () => {+ const { context } = renderer();+ const storage = context.localStorage;+ storage.setItem('workbuddy.appearance.mode::personal::personal::other', 'light');+ storage.setItem('workbuddy.appearance.state::personal::other', '{"currentTheme":"light"}');+ storage.setItem('workbuddy.appearance.mode::legacy-snapshot', 'auto');+ vm.runInNewContext(await themeExpression('dark', false, 'current'), context);+ assert.equal(storage.getItem('workbuddy.appearance.mode::personal::personal::other'), 'light');+ assert.equal(JSON.parse(storage.getItem('workbuddy.appearance.state::personal::other')).currentTheme, 'light');+ assert.equal(storage.getItem('workbuddy.appearance.mode::legacy-snapshot'), 'auto');+ assert.equal(JSON.parse(storage.getItem('workbuddy.appearance.state::personal::current')).currentTheme, 'dark');+});++test('takeover prepares a WorkBuddy special theme as an official theme first', async () => {+ const expression = await themeExpression('default', true, 'current');+ assert.match(expression, /lastApplied::/);+ assert.match(expression, /lastApplied\.css/);+ assert.match(expression, /adoptedStyleSheets/);+ assert.match(expression, /resourceKey:.*mode/);+});++test('takeover removes a special adopted skin when CSSOM serialization differs', async () => {+ const { context, document } = renderer();+ document.adoptedStyleSheets = [+ { cssRules: [{ cssText: ':root{--cb-bg-primary:#123456;--wb-bg-primary:#234567}' }] },+ { cssRules: [{ cssText: '.official{color:red}' }] },+ ];+ context.localStorage.setItem('workbuddy.appearance.lastApplied.css', JSON.stringify({+ resourceKey: 'theme-tkbdzr',+ css: ':root { --cb-bg-primary: #123456; }',+ }));+ vm.runInNewContext(await themeExpression('default', true, 'current'), context);+ assert.equal(document.adoptedStyleSheets.length, 1);+ assert.equal(document.adoptedStyleSheets[0].cssRules[0].cssText, '.official{color:red}');+});++test('theme switch invalidates an in-flight automatic restore before CDP evaluation', () => {+ const applyStart = source.indexOf('async function applyThemeByCdp(id, options = {})');+ const releaseStart = source.indexOf('async function releaseThemeByCdp()');+ const routeStart = source.indexOf("if (req.method === 'POST' && p === '/api/session-module-set')");+ assert.ok(applyStart >= 0 && releaseStart >= 0 && routeStart >= 0);+ const apply = source.slice(applyStart, source.indexOf('\n/**', applyStart));+ const release = source.slice(releaseStart, source.indexOf('\n/**', releaseStart));+ const route = source.slice(routeStart, routeStart + 900);+ assert.match(apply, /const applyGeneration = themeApplyGeneration/);+ assert.match(apply, /applyGeneration !== themeApplyGeneration/);+ assert.match(release, /themeApplyGeneration\+\+/);+ assert.match(route, /themeApplyGeneration\+\+/);+});+++test('a pending light reset cannot overwrite takeover re-enabled during a CDP retry', async () => {+ let takeover = false;+ let evaluations = 0;+ const context = {+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true, ws: { readyState: 1 } },+ readSessionState: () => ({ themeTakeoverEnabled: takeover }), themeApplyGeneration: 0,+ currentAccount: () => null, getTheme: () => ({ dark: false, colors: {} }),+ LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',+ cdpSend: async () => { evaluations++; takeover = true; context.themeApplyGeneration++; return { result: { value: { pending: true } } }; },+ cdpActivatePage: async () => {},+ setTimeout: resolve => resolve(),+ };+ const start = source.indexOf('async function applyThemeByCdp(id, options = {})');+ vm.runInNewContext(source.slice(start, source.indexOf('\n/**', start)), context);+ const result = await context.applyThemeByCdp('default', { release: true });+ assert.equal(evaluations, 1);+ assert.equal(result.applied, false);+});+++test('release resets light once then follows official dark and special skins across reconnects', async () => {+ const { context, document } = renderer();+ const intervals = new Map();+ let nextTimer = 0, lightResets = 0;+ context.setInterval = fn => { intervals.set(++nextTimer, fn); return nextTimer; };+ context.clearInterval = id => intervals.delete(id);+ context.clearTimeout = () => {};+ context.CSSStyleSheet = class {+ replaceSync(css) { this.cssRules = [{ cssText: css }]; }+ };+ document.adoptedStyleSheets = [];+ const tick = () => [...intervals.values()].forEach(fn => fn());+ const daemon = {+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0,+ readSessionState: () => ({ themeTakeoverEnabled: false }),+ cdpSend: async (_, params) => { vm.runInNewContext(params.expression, context); return {}; },+ applyThemeByCdp: async (id, options) => {+ lightResets++;+ vm.runInNewContext(await themeExpression(id, false, 'current', options), context);+ },+ };+ const start = source.indexOf('function nativeAppearanceSyncExpression()');+ vm.runInNewContext(source.slice(start, source.indexOf('async function restoreNativeAppearanceByCdp()', start)), daemon);+ const restoreNativeStart = source.indexOf('async function restoreNativeAppearanceByCdp()');+ vm.runInNewContext(source.slice(restoreNativeStart, source.indexOf('/** 恢复已保存的主题', restoreNativeStart)), daemon);+ const restoreStart = source.indexOf('async function restoreSavedTheme()');+ vm.runInNewContext(source.slice(restoreStart, source.indexOf('\n/**', restoreStart)), daemon);+ await daemon.releaseThemeByCdp();+ assert.equal(document.documentElement.getAttribute('data-theme'), 'light');+ assert.equal(intervals.size, 1, 'release must resume official settings-window synchronization');+ context.localStorage.setItem('workbuddy.appearance.lastApplied', JSON.stringify({ resourceKey: 'dark', appearance: 'dark' }));+ context.localStorage.setItem('agent-ui-theme', JSON.stringify({ theme: 'dark', followSystem: false, vsCodeThemeName: 'IDE Night', vsCodeThemeKind: 'vscode-dark' }));+ tick();+ assert.equal(document.documentElement.getAttribute('data-theme'), 'dark');+ const css = ':root { --wb-button-primary-bg: purple; }';+ context.localStorage.setItem('workbuddy.appearance.lastApplied', JSON.stringify({ resourceKey: 'ripple', appearance: 'light' }));+ context.localStorage.setItem('workbuddy.appearance.lastApplied.css', JSON.stringify({ resourceKey: 'ripple', css }));+ tick();+ assert.equal(document.documentElement.getAttribute('data-theme'), 'light');+ assert.equal(document.adoptedStyleSheets.length, 1);+ assert.equal(document.adoptedStyleSheets[0].cssRules[0].cssText, css);+ await daemon.restoreSavedTheme();+ await daemon.restoreSavedTheme();+ tick();+ assert.equal(lightResets, 1, 'reconnects must preserve the user-selected native theme');+ assert.equal(intervals.size, 1, 'reconnects must replace the prior sync interval');+ assert.equal(document.adoptedStyleSheets.length, 1);+ assert.equal(context.localStorage.getItem('workbuddy.appearance.lastApplied.css'), JSON.stringify({ resourceKey: 'ripple', css }));+ context.localStorage.removeItem('workbuddy.appearance.lastApplied.css');+ context.localStorage.setItem('workbuddy.appearance.lastApplied', JSON.stringify({ resourceKey: 'dark', appearance: 'dark' }));+ tick();+ assert.equal(document.documentElement.getAttribute('data-theme'), 'dark');+ assert.equal(document.adoptedStyleSheets.length, 0);+});+++test('nebula prepares official dark before injecting glass styles without an intermediate light write', async () => {+ const { context, document } = renderer();+ const steps = [];+ const setItem = context.localStorage.setItem;+ context.localStorage.setItem = (key, value) => {+ if (key === 'agent-ui-theme') steps.push(JSON.parse(value).theme);+ setItem(key, value);+ };+ const appendChild = document.head.appendChild;+ document.head.appendChild = node => {+ if (node.id === 'wbs-theme-style') {+ assert.equal(document.documentElement.getAttribute('data-theme'), 'dark');+ assert.equal(document.body.getAttribute('data-vscode-theme-name'), 'IDE Night');+ assert.equal(JSON.parse(context.localStorage.getItem('agent-ui-theme')).theme, 'dark');+ steps.push('glass');+ }+ appendChild(node);+ };+ vm.runInNewContext(await themeExpression('nebula', true, 'current'), context);+ assert.equal(steps[0], 'dark');+ assert.ok(steps.includes('glass'));+ assert.ok(!steps.includes('light'));+});++test('only nebula overrides primary button background to transparent', () => {+ const context = { loadThemeVars: () => require('../scripts/theme-vars.js') };+ const start = source.indexOf('function themeVarsCss(isDark, id)');+ vm.runInNewContext(source.slice(start, source.indexOf('function readBackgroundBlur()', start)), context);+ const css = context.themeVarsCss(true, 'nebula');+ assert.match(css, /html\[data-wbs-theme-id\]/);+ assert.match(css, /body\[data-vscode-theme-name\]\{[^}]*--wb-button-primary-bg:transparent(?: !important)?;/);+ assert.match(css, /--wb-bg-secondary:transparent !important/);+ assert.match(css, /\.dark/);+ for (const [dark, id] of [[false, 'default'], [true, 'dark'], [false, 'eye-care'], [true, 'cyber-purple']]) {+ assert.doesNotMatch(context.themeVarsCss(dark, id), /--wb-button-primary-bg:transparent/);+ }+});+++test('nebula releases custom CSS and guards, waits for official dark, then reapplies glass', async () => {+ const { context, document, observers } = renderer();+ vm.runInNewContext(await themeExpression('nebula', true, 'current'), context);+ const stages = [];+ const daemon = {+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0,+ setTimeout: resolve => resolve(),+ readSessionState: () => ({ themeTakeoverEnabled: true }), currentAccount: () => ({ uid: 'current' }),+ getTheme: id => ({ dark: id !== 'default', colors: {} }),+ LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',+ cdpSend: async (_, params) => {+ if (params.expression.includes('ready:')) {+ stages.push('settle');+ assert.equal(document.getElementById('wbs-theme-style'), null);+ assert.equal(observers.filter(o => o.active).length, 0);+ assert.equal(document.documentElement.getAttribute('data-theme'), 'dark');+ assert.equal(JSON.parse(context.localStorage.getItem('agent-ui-theme')).theme, 'dark');+ return { result: { value: { ready: true } } };+ }+ const value = vm.runInNewContext(params.expression, context);+ stages.push(document.getElementById('wbs-theme-style') ? 'glass' : 'native');+ return { result: { value } };+ },+ };+ const start = source.indexOf('async function applyThemeByCdp(id, options = {})');+ vm.runInNewContext(source.slice(start, source.indexOf('\n/**', start)), daemon);+ await daemon.applyThemeByCdp('nebula');+ assert.deepEqual(stages, ['native', 'settle', 'glass']);+ assert.equal(observers.filter(o => o.active).length, 1);+});++test('native dark clears a stale skin marker before notifying the official theme observer', async () => {+ for (const uid of ['current', null]) {+ const { context, document } = renderer();+ const h = document.documentElement, b = document.body;+ h.setAttribute('data-skin', 'theme-tkbera');+ let officialMode = 'light';+ const set = b.setAttribute;+ b.setAttribute = (name, value) => {+ set(name, value);+ // WorkBuddy ThemeManager ignores theme-kind notifications while a skin is active.+ if (name === 'data-vscode-theme-kind' && !h.getAttribute('data-skin')) officialMode = value === 'vscode-dark' ? 'dark' : 'light';+ };+ // No CSS cache or adopted sheet remains: marker cleanup must not depend on them.+ vm.runInNewContext(await themeExpression('dark', true, uid, { nativeOnly: true }), context);+ assert.equal(h.getAttribute('data-skin'), null);+ assert.equal(officialMode, 'dark');+ }+});++test('clearing a native skin preserves its stylesheet attachment for later official selections', async () => {+ const { context, document } = renderer();+ const skin = { cssRules: [{ cssText: ':root{--wb-bg-primary:pink}' }], replaceSync(css) { this.cssRules = css ? [{ cssText: css }] : []; } };+ document.adoptedStyleSheets = [skin];+ document.documentElement.setAttribute('data-skin', 'special');+ context.localStorage.setItem('workbuddy.appearance.lastApplied.css', JSON.stringify({ resourceKey: 'special', css: ':root{--wb-bg-primary:pink}' }));+ vm.runInNewContext(await themeExpression('default', true, 'current'), context);+ assert.equal(document.adoptedStyleSheets[0], skin);+ assert.equal(skin.cssRules.length, 0);+ skin.replaceSync(':root{--wb-bg-primary:blue}');+ assert.equal(document.adoptedStyleSheets[0].cssRules[0].cssText, ':root{--wb-bg-primary:blue}');+});++test('nebula resolves transparent constants even from an existing installed theme file', () => {+ const start = source.indexOf('function getTheme(id)');+ const ctx = { THEMES_DIR: '/themes', path, BUILTIN_THEMES: {}, fs: {+ existsSync: () => true,+ readFileSync: () => JSON.stringify({ id: 'nebula', image: 'custom.webp', colors: {+ '--wb-button-primary-bg': 'white', '--wb-bg-secondary': '#111113', '--wb-color-text-primary': '#eee',+ } }),+ } };+ vm.runInNewContext(source.slice(start, source.indexOf('\n/**', start)), ctx);+ const theme = ctx.getTheme('nebula');+ assert.equal(theme.colors['--wb-button-primary-bg'], 'transparent');+ assert.equal(theme.colors['--wb-bg-secondary'], 'transparent');+ assert.equal(theme.colors['--wb-color-text-primary'], '#eee');+ assert.equal(theme.image, 'custom.webp');+ assert.equal(ctx.getTheme('other').colors['--wb-bg-secondary'], '#111113');+});+++test('early custom theme restore preserves pending official synchronization for the switched account', async () => {+ const { context } = renderer();+ const key = 'workbuddy.appearance.state::personal::target';+ context.localStorage.setItem(key, JSON.stringify({ currentTheme: 'dark', pendingSync: { theme: 'dark' } }));+ vm.runInNewContext(await themeExpression('nebula', true, 'target'), context);+ assert.equal(JSON.parse(context.localStorage.getItem(key)).pendingSync.theme, 'dark');+});++test('frosted takeover completes even when background renderer timers and animation frames are suspended', async () => {+ const delays = [];+ const nativePage = {+ document: {+ documentElement: { getAttribute: () => 'dark', hasAttribute: () => false, style: { colorScheme: 'dark' } },+ body: { getAttribute: () => 'IDE Night' }, getElementById: () => null,+ },+ localStorage: { getItem: () => '{"theme":"dark"}' }, window: {},+ setTimeout() {}, clearTimeout() {}, requestAnimationFrame() {},+ };+ let applies = 0;+ const daemon = {+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true }, themeApplyGeneration: 0,+ readSessionState: () => ({ themeTakeoverEnabled: true }), currentAccount: () => null,+ getTheme: () => ({ dark: true, colors: {} }),+ LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',+ setTimeout: (resolve, ms) => { delays.push(ms); resolve(); },+ cdpSend: async (_, params) => {+ if (params.expression.includes('ready:')) return { result: { value: await vm.runInNewContext(params.expression, nativePage) } };+ applies++;+ return { result: { value: { applied: true } } };+ },+ };+ const start = source.indexOf('async function applyThemeByCdp(id, options = {})');+ vm.runInNewContext(source.slice(start, source.indexOf('\n/**', start)), daemon);+ let deadline;+ try {+ await Promise.race([daemon.applyThemeByCdp('nebula'), new Promise((_, reject) => {+ deadline = setTimeout(() => reject(new Error('Theme switch is waiting for suspended renderer timers')), 100);+ })]);+ } finally { clearTimeout(deadline); }+ assert.equal(applies, 2, 'native dark precedes glass');+ assert.deepEqual(delays, [120], 'the daemon owns the bounded settle delay');+});diff --git a/test/token-stats-modal.test.js b/test/token-stats-modal.test.jsnew file mode 100644index 0000000..c3cc256--- /dev/null+++ b/test/token-stats-modal.test.js@@ -0,0 +1,71 @@+'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');+function harness() {+ function element(attrs = {}) {+ const listeners = {}, classes = new Set();+ return { attrs, listeners, dataset: {}, style: {}, hidden: false, isConnected: true,+ classList: { contains: x => classes.has(x), toggle: (x, on) => on ? classes.add(x) : classes.delete(x) },+ addEventListener: (name, fn) => { listeners[name] = fn; }, focus() {}, remove() { this.isConnected = false; },+ getAttribute: key => attrs[key], setAttribute: (key, value) => { attrs[key] = value; }, removeAttribute: key => { delete attrs[key]; },+ querySelector: () => element(), querySelectorAll: () => [],+ click() { if (!this.disabled && listeners.click) listeners.click({}); },+ };+ }+ const tabs = ['credit', 'token'].map(kind => element({ 'data-usage-tab': kind }));+ tabs[0].classList.toggle('active', true);+ const panes = ['credit', 'token'].map(kind => element({ 'data-usage-pane': kind }));+ const periods = {};+ for (const kind of ['credit', 'token']) periods[kind] = [1, 7, 30, 90].map(days => {+ const el = element({ 'aria-pressed': String(days === 7) }); el.dataset[kind + 'Days'] = days; return el;+ });+ const overlay = element(), body = element(), mask = element();+ mask.querySelectorAll = selector => selector === '[data-usage-tab]' ? tabs : selector === '[data-usage-pane]' ? panes+ : selector === '[data-token-days]' ? periods.token : selector === '[data-credit-days]' ? periods.credit : [];+ mask.querySelector = selector => {+ if (selector === '[data-usage-tab].active') return tabs.find(b => b.classList.contains('active'));+ for (const kind of ['token', 'credit']) if (selector === '[data-' + kind + '-days][aria-pressed="true"]') return periods[kind].find(b => b.attrs['aria-pressed'] === 'true');+ if (selector === '.wbs-token-stats-overlay') return overlay;+ if (selector === '.wbs-token-stats-body') return body;+ return element();+ };+ const calls = [], pending = [];+ const context = {+ document: { getElementById: () => null, createElement: () => mask }, root: { appendChild() {} },+ registerDisposer() {}, usageTimeSegmentHtml: () => '', setTimeout, clearTimeout,+ esc: String, escAttr: String, formatTokenCount: String, toast() {},+ usageTrendChartHtml: () => '', usagePieHtml: () => '', wireUsagePies() {}, renderUsageBreakdown() {},+ api: url => {+ calls.push(url);+ if (url.includes('cacheStatus')) return Promise.resolve({ cacheReady: true });+ if (url.startsWith('/api/token-stats')) return new Promise(resolve => pending.push(resolve));+ return Promise.reject(Error('fixture: no credits'));+ },+ };+ const start = source.indexOf(' function onTokenStats()');+ vm.runInNewContext(source.slice(start, source.indexOf('\n // ===== Tab 切换', start)), context);+ context.onTokenStats();+ return { calls, pending, tabs, periods, overlay, mask };+}+const settle = () => new Promise(resolve => setImmediate(resolve));+test('opening Token starts the default seven-day query once and hides the spinner on completion', async () => {+ const h = harness(); await settle();+ assert.equal(h.calls.some(url => url.startsWith('/api/token-stats')), false);+ h.tabs[1].click(); await settle();+ assert.equal(h.calls.filter(url => url === '/api/token-stats?days=7').length, 1);+ h.tabs[0].click(); h.tabs[1].click(); await settle();+ assert.equal(h.pending.length, 1, 'tab toggling must reuse the in-flight request');+ h.pending.shift()({stats: {}, accounts: []}); await settle();+ assert.equal(h.overlay.hidden, true);+ assert.equal(h.periods.token.every(b => !b.disabled), true);+ h.tabs[0].click(); h.tabs[1].click(); await settle();+ assert.equal(h.calls.filter(url => url === '/api/token-stats?days=7').length, 1);+ h.periods.token[2].click(); await settle();+ assert.equal(h.calls.at(-1), '/api/token-stats?days=30');+ h.mask.__wbsClose();+ h.pending.shift()({stats: {}, accounts: []}); await settle();+ assert.equal(h.mask.isConnected, false);+});diff --git a/test/token-stats.test.js b/test/token-stats.test.jsindex 3e3d9df..7fa92fb 100644--- a/test/token-stats.test.js+++ b/test/token-stats.test.js@@ -121,7 +121,7 @@ test('token statistics UI keeps results under an overlay and exposes presets thrassert.match(source, /if \(!metadata\.cacheReady\)/);assert.doesNotMatch(source, /__wbsTokenStatsCacheReady/);assert.match(source, /setTimeout\(function \(\) \{ if \(!overlay\.hidden\)/);- assert.match(source, /formatTokenCount\(item\.calls/);+ assert.match(source, /formatTokenCount\(row\.calls/);assert.match(source, /usageTimeSegmentHtml\('token'\)/);assert.match(source, /usageTimeSegmentHtml\('credit'\)/);assert.match(source, /data-' \+ kind \+ '-days="' \+ days/);@@ -162,15 +162,28 @@ test('usage statistics modal uses a larger responsive dashboard layout in both tassert.match(source, /@media\(max-width:700px\)[\s\S]{0,220}\.wbs-usage-columns\{grid-template-columns:1fr\}/);});-test('breakdown lines use distinct chart-only colors across light and dark themes', () => {+test('usage charts derive all series from WorkBuddy theme tokens', () => {const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');const colors = source.match(/function usageTrendColors\(\) \{([\s\S]*?)\n \}/);assert.ok(colors);+ const palette = source.match(/\.wbs-trend-panel,\.wbs-usage-pie-section\{([^}]+)\}/)[1];+ assert.doesNotMatch(palette, /#[0-9a-f]|rgba?\(/i);+ assert.match(palette, /--wbs-chart-base:var\(--wbs-credit-theme-color,var\(--wbs-primary\)\)/);+ assert.match(palette, /--wbs-trend-series-1:var\(--wbs-chart-base\)/);+ assert.match(palette, /--wbs-trend-series-2:color-mix\(in srgb,var\(--wbs-chart-base\)/);+ assert.match(palette, /--wbs-trend-series-12:color-mix\(in srgb,var\(--wbs-chart-base\)/);+ assert.doesNotMatch(palette, /--wb-palette-(blue|purple|green|cyan|red|orange)-5/);+ assert.match(source, /html\[data-theme="dark"\][\s\S]*--wbs-primary:#7f77dd/);+ assert.match(source, /--wbs-credit-theme-color:var\(--wb-button-primary-bg\)/);+ assert.equal((palette.match(/--wbs-trend-series-\d+:/g) || []).length, 12);+ const chart = source.slice(source.indexOf('function renderUsageTrendChart'), source.indexOf('function usageTimeSegmentHtml'));+ assert.doesNotMatch(chart, /--wbs-primary|34,197,94|#[0-9a-f]{3,8}/i);assert.doesNotMatch(colors[1], /--wbs-primary|--wb-color-text/);- assert.match(source, /\.wbs-trend-panel\{--wbs-trend-series-1:#/);- assert.match(source, /html\.cb-dark #wbs-token-stats-modal \.wbs-trend-panel/);- assert.match(source, /html\[data-theme="dark"\] #wbs-token-stats-modal \.wbs-trend-panel/);- assert.match(source, /body\[data-vscode-theme-name\*="dark" i\] #wbs-token-stats-modal \.wbs-trend-panel/);+ assert.match(source, /getComputedStyle\(panel\)\.getPropertyValue\('--wbs-trend-series-1'\)/);+ assert.match(source, /series = series\.map\(function \(line\)/);+ assert.match(source, /resolveUsageColor\(line\.color, container\)/);+ assert.doesNotMatch(source, /\.wbs-pie-legend\{[^}]*max-height/);+ assert.doesNotMatch(source, /\.wbs-token-model-scroll\{[^}]*max-height/);assert.match(source, /state\.colorSlots\[mode\]/);assert.match(source, /slots\.delete\(key\)/);assert.match(source, /new Set\(groups\.map\(function \(group\) \{ return group\.key; \}\)\)/);diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex d480ea2..8acdf79 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -1,6 +1,7 @@const assert = require('node:assert/strict');const childProcess = require('node:child_process');const fs = require('node:fs');+const net = require('node:net');const os = require('node:os');const path = require('node:path');const test = require('node:test');@@ -429,6 +430,23 @@ test('Windows launcher keeps local port probing and profile CDP candidates definassert.match(launcher, /isTargetForProfile\(target, PROFILE\)/);});+test('Windows launcher has an OS-assigned CDP fallback when profile ports are unavailable', async () => {+ const launcherSource = read('win-launcher.js');+ assert.match(launcherSource, /function reserveEphemeralCdpPort\(\)/);+ assert.match(launcherSource, /server\.listen\(\{ host: HOST, port: 0 \}/);+ assert.match(launcherSource, /const ephemeralPort = await reserveEphemeralCdpPort\(\)/);+ assert.match(launcherSource, /CDP_PORT_DYNAMIC/);++ const launcher = require(path.join(repoRoot, 'scripts', 'win-launcher.js'));+ const port = await launcher.reserveEphemeralCdpPort();+ assert.ok(Number.isInteger(port) && port >= 1024 && port <= 65535);+ await new Promise((resolve, reject) => {+ const server = net.createServer();+ server.once('error', reject);+ server.listen({ host: '127.0.0.1', port }, () => server.close((error) => error ? reject(error) : resolve()));+ });+});+test('Windows launcher propagates the WorkBuddy AI UI port to child processes', { skip: process.platform !== 'win32' }, () => {const launcherPath = path.join(repoRoot, 'scripts', 'win-launcher.js');const probe = [@@ -958,7 +976,7 @@ test('account cards keep the compact three-row layout', () => {assert.doesNotMatch(script, /data-tip="' \+ attrTip \+ '" title=/);assert.match(script, /creditOpacity\(row\.days\)/);assert.match(script, /creditOpacity\(segment\.expiresAt/);- assert.match(script, /\.wbs-credit-segment,\.wbs-credit-summary-fill\{background:rgba\(var\(--wbs-primary-rgb,34,197,94\),var\(--wbs-credit-alpha,1\)\)/);+ assert.match(script, /\.wbs-credit-segment,\.wbs-credit-summary-fill\{background:color-mix\(in srgb,var\(--wbs-credit-theme-color,var\(--wbs-primary\)\) calc\(var\(--wbs-credit-alpha,1\) \* 100%\),transparent\)/);['dark', 'cyber-purple', 'nebula'].forEach((themeId) => {assert.match(script, new RegExp('html\\[data-wbs-theme-id="' + themeId + '"\\][\\s\\S]*--wbs-primary-rgb:127,119,221'));});@@ -966,6 +984,22 @@ test('account cards keep the compact three-row layout', () => {assert.match(script, /今日签到/);assert.match(script, /function accountStatusTagsHtml\(a\)/);assert.match(script, /function checkinBadgeHtml\(a\)/);+ assert.match(script, /wbs-model-rate-limit wbs-ck wbs-checkin-tag ok/);+ assert.match(script, /function setupModelRateLimitPopover\(\)/);+ assert.match(script, /\.wbs-status-popover\.is-rate-limit/);+ assert.match(script, /\.wbs-status-popover\.is-rate-limit\{width:500px/);+ assert.match(script, /\.wbs-status-popover\.is-rate-limit-summary\{width:360px/);+ assert.match(script, /data-act="model-rate-limit-summary"/);+ assert.match(script, /function modelRateLimitSummaryPopoverHtml\(accounts\)/);+ assert.match(script, /showStatusPopover\(summaryButton, modelRateLimitSummaryPopoverHtml\(state\.accounts\)/);+ assert.match(script, /placement === 'below'/);+ assert.match(script, /\.wbs-model-rate-limit-summary-row/);+ assert.match(script, /\.wbs-model-rate-limit-detail b\{white-space:nowrap/);+ assert.match(script, /wbs-model-rate-limit-model/);+ assert.match(script, /wbs-model-rate-limit-reset/);+ assert.doesNotMatch(script, /限流期间可切换其他模型/);+ assert.match(script, /function fmtDateTimeSeconds\(ts\)/);+ assert.doesNotMatch(script, /wbs-model-rate-limit[^']*cursor:help/);assert.match(script, /badge \+ dailyRingsHtml\(a\) \+ checkinBadge/);assert.match(script, /if \(!usage \|\| usage\.synced !== true\) return '';/);assert.match(script, /wbs-usage-tag/);@@ -995,7 +1029,8 @@ test('account cards sort by credit expiry without pinning the current account',test('quick-phrase layering does not reposition WorkBuddy native chat toolbar', () => {const script = read('inject.js');assert.match(script, /\.wbs-explore-inline\.wbs-stash-inline-inline\{position:relative;z-index:99999\}/);- assert.match(script, /\.wbs-explore-pop\{[^}]*z-index:2147483647/);+ assert.match(script, /\.wbs-explore-pop\{position:fixed;[^}]*z-index:22/);+ assert.match(script, /document\.body\.appendChild\(popup\)/);assert.match(script, /html\[data-wbs-theme-id="nebula"\] \.wbs-explore-card\{[^}]*background:color-mix\(in srgb,var\(--wb-bg-popover/);assert.match(script, /html\[data-wbs-theme-id="nebula"\] \.wbs-explore-tip\{[^}]*background:color-mix\(in srgb,var\(--wb-bg-popover/);assert.doesNotMatch(script, /_chatMessageBottomToolbarWrapper_\}\{position:relative;z-index:68/);diff --git a/test/usage-pie.test.js b/test/usage-pie.test.jsnew file mode 100644index 0000000..9150e0c--- /dev/null+++ b/test/usage-pie.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 vm = require('node:vm');+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');+function helpers() {+ const start = source.indexOf(' function usagePieData(');+ assert.ok(start >= 0, 'shared chart helper exists');+ const escape = value => String(value).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));+ const ctx = { esc: escape, escAttr: escape, formatTokenCount: String, usageTrendColors: () => Array.from({length:12}, (_,i) => 'var(--wbs-trend-series-'+(i+1)+')') };+ vm.runInNewContext(source.slice(start, source.indexOf(' function usageTrendGroups(', start)), ctx);+ return ctx;+}+test('pie includes the whole distribution and preserves all grouped detail rows', () => {+ const h = helpers();+ const rows = Array.from({length:15}, (_,i) => ({label:'Model '+i,value:i+1,calls:2}));+ const data = h.usagePieData(rows);+ assert.equal(data.total, 120);+ assert.equal(data.segments.length, 8);+ assert.equal(data.segments.at(-1).value, 36);+ assert.equal(data.segments.at(-1).children.length, 8);+ assert.equal(data.segments.reduce((sum,r)=>sum+r.value,0), data.total);+ const html = h.usagePieHtml(rows, '模型用量', 'Token', String, '暂无模型数据');+ for (const row of rows) assert.ok(html.includes('>'+row.label+'<'));+ assert.match(html, /<details/);+ assert.match(html, /30\.0%/);+});+test('pie handles empty, invalid and single values without invalid SVG and escapes labels', () => {+ const h = helpers();+ assert.equal(h.usagePieData([{value:0},{value:-2},{value:Infinity},{value:NaN}]).total, 0);+ const empty = h.usagePieHtml([], '模型用量', 'Token', String, '暂无模型数据');+ assert.match(empty, /暂无模型数据/);+ assert.doesNotMatch(empty, /<svg|NaN|Infinity/);+ const html = h.usagePieHtml([{label:'<img src=x onerror="bad">',value:100,calls:2}], '模型用量', 'Token', String, '暂无模型数据');+ assert.match(html, /100\.0%/);+ assert.match(html, /<circle cx="64" cy="64" r="58"/);+ assert.doesNotMatch(html, /stroke-dasharray|wbs-pie-total/);+ assert.doesNotMatch(html, /<img/);+ assert.match(html, /<img/);+});+test('both usage tabs chart accounts and models without truncating token model totals', () => {+ const modal = source.slice(source.indexOf(' function onTokenStats()'),source.indexOf(' // ===== Tab 切换'));+ assert.equal((modal.match(/usagePieHtml\(/g)||[]).length,4);+ assert.doesNotMatch(modal, /stats\.models \|\| \[\]\)\.slice\(0, 12\)/);+});++test('pie hover and keyboard focus preview the selected slice and matching row, then clear on exit', () => {+ const h = helpers();+ h.window = { innerWidth: 360, innerHeight: 700 };+ function item(index, attrs = {}) {+ const classes = new Set();+ return { classes, classList: { add: x => classes.add(x), remove: x => classes.delete(x), toggle: (x,on) => on ? classes.add(x) : classes.delete(x) },+ getAttribute: k => k === 'data-pie-index' ? String(index) : attrs[k],+ closest() { return this; }, getBoundingClientRect: () => ({left:320,bottom:680,width:20}) };+ }+ const slices = [0,1].map(i => item(i, { 'data-pie-label':'Model '+i,'data-pie-value':'20 Token','data-pie-percent':'25.0%','data-pie-calls':'3' }));+ const rows = [item(0), item(1)];+ const labels = { strong:{}, '[data-pie-tip-value]':{}, '[data-pie-tip-detail]':{} };+ const tip = {hidden:true,style:{},querySelector:key=>labels[key],getBoundingClientRect:()=>({width:180,height:80})};+ const handlers = {}, section = item(-1);+ section.querySelector = selector => selector === '.wbs-pie-tooltip' ? tip : slices[Number(selector.match(/index="(\d+)"/)[1])];+ section.querySelectorAll = () => [...slices,...rows];+ section.addEventListener = (type, callback) => {handlers[type]=callback;};+ h.wireUsagePies({querySelectorAll:()=>[section]});+ handlers.pointermove({target:slices[1],clientX:350,clientY:690});+ assert.equal(tip.hidden,false);+ assert.equal(labels.strong.textContent,'Model 1');+ assert.equal(labels['[data-pie-tip-detail]'].textContent,'25.0% · 3 次');+ assert.equal(rows[1].classes.has('is-preview'),true);+ assert.equal(rows[0].classes.has('is-preview'),false);+ assert.ok(parseFloat(tip.style.left)+180<=352);+ assert.ok(parseFloat(tip.style.top)+80<=700);+ handlers.pointerleave();+ assert.equal(tip.hidden,true);+ handlers.focusin({target:slices[0]});+ assert.equal(tip.hidden,false);+ let stopped=false;+ handlers.keydown({key:'Escape',stopPropagation(){stopped=true;}});+ assert.equal(stopped,true);+ assert.equal(tip.hidden,true);+});