WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
1. 增加 Token 和积分用量统计页面,支持柱状图、账号筛选、模型筛选和调用量统计。 2. Token 统计增加输入、输出、缓存读取、缓存写入等数据。 3. 积分统计改为真实接口数据,并缓存结果,减少重复请求。 4. Token 和积分都支持今天、近 7 天、近 30 天、近 90 天。 5. 统计弹窗改为固定标题和 Tab,只有内容区域滚动。 6. 优化首次加载提示,后续优先使用缓存。 7. 增加积分不足时的账号切换建议。 8. 改进账号导入、无效账号备份识别和账号切换保护。 9. 优化账号列表排序、刷新和账号切换后的稳定性。 10. 增加从 CC Switch 导入第三方模型的功能。 11. 改进会话删除、跨账号会话关联清理和消息定位。 12. 优化自动化任务显示、内置任务更新和首页弹窗自动关闭。 13. 缩小自动确认范围,避免误操作账单或积分确认按钮。 14. 优化主题、机器人外观、品牌 Logo、深色模式和毛玻璃效果。 15. 修复 macOS 启动、Dock 身份、更新和应用打包问题。
[email protected]ad95bebf8e8d
diff --git a/README.md b/README.mdindex 0498f59..3391c48 100644--- a/README.md+++ b/README.md@@ -1,4 +1,4 @@-# WorkDaddy+<h1><img src="docs/images/workdaddy-app-icon-rounded.svg" alt="" width="40" height="40" align="absmiddle"> WorkDaddy</h1>**语言:** [简体中文](README.md) · [English](README_en.md)@@ -31,6 +31,8 @@- **无感登录新账号**:「登录新账号」支持免退出 OAuth 授权——不退出 WorkBuddy,在浏览器完成扫码后新账号自动加入列表;也可选传统的「假退出」方式回登录页扫码。- **账号导入导出**:把全部账号备份加密导出,在另一台电脑安装 WorkDaddy 后一键导入,方便电脑之间迁移账号。- **自动领每日积分**:由自动化任务管理多账号每日签到,缓存已完成状态,不打断你。+- **Token 和积分用量统计页面**:按天查看 Token 与积分消耗,支持按账号筛选,并显示模型和账号用量排行。+- **积分不足时的账号切换建议**:当前账号积分不足时提示可用账号,方便继续工作。- **自动化任务**:用自然语言让 WorkBuddy 创建任务,或自行编辑步骤;支持手动、事件和定时触发,以及运行日志、停止任务和 JSON / ZIP 导入导出。- **权限弹窗免打扰**:真正的零决策弹窗弹出,可以放心开启任务后睡觉。- **暂存提示词**:输入框边上一键把草稿「暂存」到待发送队列——图片 / 文件 / 引用原样保留,择机发送。diff --git a/README_en.md b/README_en.mdindex cc5cf57..7df0d03 100644--- a/README_en.md+++ b/README_en.md@@ -1,4 +1,4 @@-# WorkDaddy+<h1><img src="docs/images/workdaddy-app-icon-rounded.svg" alt="" width="40" height="40" align="absmiddle"> WorkDaddy</h1>**Language:** [简体中文](README.md) · [English](README_en.md)@@ -31,6 +31,8 @@ It injects UI components into the running WorkBuddy renderer without patching or- **Add an account without quitting:** authorize through OAuth in your browser while WorkBuddy stays open. The new account joins the list automatically. A traditional soft logout flow is also available.- **Encrypted account import/export:** move account backups between computers using a password-protected file.- **Daily credits:** automation tasks manage daily check-ins across accounts and cache completed results without interrupting your work.+- **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.- **Automation tasks:** describe what you need and let WorkBuddy create a task, or edit the steps yourself. Supports manual, event, and scheduled triggers, run logs, stopping tasks, and JSON / ZIP import/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.diff --git a/docs/cc-switch-import.md b/docs/cc-switch-import.mdnew file mode 100644index 0000000..75a8008--- /dev/null+++ b/docs/cc-switch-import.md@@ -0,0 +1,36 @@+# CC Switch 模型导入++入口:模型 → 当前模型 → 从第三方导入 → CC Switch。按来源客户端分开展示,同一供应商合并为一项并列出包含的模型;默认全选当前客户端的可导入供应商。计数与全选仅针对当前客户端,点击确定时读取当前配置检查冲突:没有同名模型则直接导入;会覆盖现有模型或选中项之间存在重复 ID 时,才显示 380px 的确认弹窗。模型选择弹窗保持 640px。++## 数据来源++参考源码:`https://github.com/farion1231/cc-switch`,分析版本 `b78192e8fec3e062948237526d9c03ad08ea7831`(3.20.2)。本实现独立编写,不运行第三方代码。++- 优先读取用户目录 `.cc-switch/cc-switch.db` 的 `providers` 表;旧版回退 `config.json`。+- 遵循 `com.ccswitch.desktop/app_paths.json` 中的 `app_config_dir_override`,兼容 macOS、Windows 和 Linux 的 Tauri 数据目录。Windows 同时兼容历史 `HOME` 目录。+- 数据库使用现有只读 SQLite 适配器,支持安装包自带 Node SQLite,不依赖 Windows 另装 SQLite。不会创建缺失的第三方数据库。+- 支持 Claude 主模型(未设置时回退 Sonnet 默认模型)、Codex TOML 根配置和 profiles、Gemini、OpenCode 模型映射、OpenClaw 模型列表;兼容明确启用的公共配置片段。+- 仅读取供应商模型配置,不读取 CC Switch OAuth 会话、使用记录,不探测网络接口。预览只返回模型摘要、接口地址和 API Key,供本机用户确认配置;数据仅走 loopback,不写日志、不上传。++## 格式兼容边界++WorkBuddy 自定义模型的标准请求格式为 OpenAI Chat Completions。`useCustomProtocol` 只是 URL 原样传递,并非 Anthropic/Responses 协议转换器。++- Chat 配置保留模型 ID、密钥、路径前缀,规范为 `/chat/completions` 地址。+- Claude / Codex / 第三方 Gemini 的地址转换要求供应商同时支持 Chat Completions。不保证只提供原生协议的服务可用。+- Google Gemini 官方 API 使用其 OpenAI 兼容入口 `/v1beta/openai/chat/completions`。+- Anthropic 官方原生接口、OAuth 登录、缺少模型或密钥、额外认证请求头、无法解析的 TOML 等条目直接从预览过滤;不伪造模型名或凭据。+- 只转移有明确对应关系的模型能力、上下文/输出限制与推理强度,不迁移 CC Switch 的代理、工具、系统提示或脚本。++## 写入与覆盖++- 预览在 daemon 内保存 10 分钟,最多保留 4 份。导入请求必须携带有效快照与选择标识,不能提交任意文件路径或客户端自造配置。有冲突且未确认时只返回冲突数量,不写入模型或备份。成功后快照作废,避免重复提交。+- 按 WorkBuddy 的模型 ID 覆盖,保留未选择的现有模型;同 ID 多供应商采用选择顺序最后一项。所有所选配置同时保存到“备选模型”,可随时换用。+- 先将当前原文件以 `models.json.before-cc-switch-<uuid>.bak` 保存(权限 0600),再原子替换模型配置。保留原 JSON 包装和 `availableModels` 列表。+- 检测、预览和取消都不会写入 WorkBuddy 模型配置。++## 验证++`node --test test/third-party-models.test.js test/third-party-model-ui.test.js` 覆盖 SQLite / 旧 JSON、自定义目录、字段转换、缺失凭据过滤、公共配置、覆盖备份、同 ID 多供应商、快照过期,以及实际预览数据格式下的分组、选择、计数与确认行为。++在模拟数据页面中运行实际 `inject.js` 模型模块,验证默认勾选、全选/取消全选、两阶段确认、取消、重复提交、`html.cb-dark` / `html[data-theme="dark"]` 和 360px 窄窗口。没有用真实模型发起付费请求。Windows 安装器实机验证需在 Windows 进行。diff --git a/docs/images/workdaddy-app-icon-rounded.svg b/docs/images/workdaddy-app-icon-rounded.svgnew file mode 100644index 0000000..408f3ba--- /dev/null+++ b/docs/images/workdaddy-app-icon-rounded.svg@@ -0,0 +1,46 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024" fill="none">+<defs><clipPath id="readme-rounded-icon"><rect width="1024" height="1024" rx="256"/></clipPath></defs>+<g clip-path="url(#readme-rounded-icon)">+ <!-- Square master, based on the website's original floating robot. -->+ <defs>+ <linearGradient id="background" x1="160" y1="0" x2="890" y2="1100" gradientUnits="userSpaceOnUse">+ <stop stop-color="#34363d"/><stop offset=".5" stop-color="#17181d"/><stop offset="1" stop-color="#050506"/>+ </linearGradient>+ <linearGradient id="shell-side" x1="490" y1="315" x2="885" y2="910" gradientUnits="userSpaceOnUse">+ <stop stop-color="#e3e6da"/><stop offset=".48" stop-color="#b5bdae"/><stop offset="1" stop-color="#8b9785"/>+ </linearGradient>+ <radialGradient id="shell" cx="0" cy="0" r="1" gradientTransform="translate(301 391) rotate(48) scale(762 909)" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fffef7"/><stop offset=".48" stop-color="#eeeee9"/><stop offset=".83" stop-color="#dce0d4"/><stop offset="1" stop-color="#b7c0ac"/>+ </radialGradient>+ <linearGradient id="antenna" x1="461" y1="157" x2="506" y2="312" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fffef7"/><stop offset=".6" stop-color="#eeeee9"/><stop offset="1" stop-color="#bac3b0"/>+ </linearGradient>+ <linearGradient id="eyes" x1="280" y1="420" x2="558" y2="610" gradientUnits="userSpaceOnUse">+ <stop stop-color="#465443"/><stop offset="1" stop-color="#687267"/>+ </linearGradient>+ <linearGradient id="rim" x1="311" y1="295" x2="796" y2="878" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fff" stop-opacity=".85"/><stop offset="1" stop-color="#fff" stop-opacity=".04"/>+ </linearGradient>+ <filter id="robot-shadow" x="-30%" y="-30%" width="170%" height="180%">+ <feDropShadow dx="8" dy="27" stdDeviation="22" flood-color="#24331f" flood-opacity=".25"/>+ </filter>+ </defs>+ <defs><clipPath id="app-mask"><path d="M360 0H664C790 0 853 0 901 24C944 46 978 80 1000 123C1024 171 1024 234 1024 360V664C1024 790 1024 853 1000 901C978 944 944 978 901 1000C853 1024 790 1024 664 1024H360C234 1024 171 1024 123 1000C80 978 46 944 24 901C0 853 0 790 0 664V360C0 234 0 171 24 123C46 80 80 46 123 24C171 0 234 0 360 0Z"/></clipPath></defs>+ <g clip-path="url(#app-mask)">+ <rect width="1024" height="1024" fill="url(#background)"/>+ <!-- Keep the compact rounded-square shell, single antenna, and two upright eyes. -->+ <g transform="rotate(8 512 540)" filter="url(#robot-shadow)">+ <rect x="448" y="201" width="47" height="124" rx="23.5" fill="url(#antenna)"/>+ <circle cx="471.5" cy="188" r="42" fill="url(#antenna)"/>+ <rect x="155" y="314" width="725" height="604" rx="155" fill="url(#shell-side)"/>+ <rect x="116" y="292" width="720" height="604" rx="154" fill="url(#shell)"/>+ <rect x="120" y="296" width="712" height="596" rx="150" stroke="url(#rim)" stroke-width="8"/>+ <!-- Shift the original eyes up and left instead of changing the character. -->+ <rect x="259" y="430" width="99" height="158" rx="49.5" fill="#fff" fill-opacity=".6"/>+ <rect x="259" y="425" width="99" height="158" rx="49.5" fill="url(#eyes)"/>+ <rect x="469" y="430" width="108" height="162" rx="54" fill="#fff" fill-opacity=".6"/>+ <rect x="469" y="425" width="108" height="162" rx="54" fill="url(#eyes)"/>+ </g>+ </g>+</g>+</svg>diff --git a/docs/usage-analytics.md b/docs/usage-analytics.mdnew file mode 100644index 0000000..44495ea--- /dev/null+++ b/docs/usage-analytics.md@@ -0,0 +1,16 @@+# 匿名用户数和日活++`scripts/usage-report.js` 向 `https://workdaddy.dev/api/track` 上报匿名安装活跃状态。服务端源码、部署步骤和查看入口见相邻官网项目 `analytics/README.md`;生产统计页为 `https://workdaddy.dev/api/track/dashboard`,需要管理密钥。++- 使用现有 `sentry-report.js` 的共享随机 `installation-id`,不读取账号作为用户标识。仅持久化成功的 ID 可上报,避免临时随机 ID 膨胀安装数。+- 同一安装的 CN/AI/profile 共用 `usage-state.json` 和 `.usage-report.lock`,文件位于 WorkDaddy 共享数据目录。`WBSWITCH_SHARED_DATA_DIR` 可覆盖共享目录,便于隔离测试。+- 获得焦点的可见 renderer 初次加载或真实键鼠/窗口事件触发无内容的本地 `POST /api/usage`,受现有 profile API Token 校验。事件不读取输入、按键值、DOM 内容或坐标;监听器通过 build lifecycle 清理。+- renderer 的本地请求每小时最多一次,北京时间跨天后可立即触发。后台守护进程和自动化不会自行发送活跃事件。+- daemon 在发送前读取遥测设置:About 页「发送错误诊断」和 `WORKDADDY_TELEMETRY` 的现有优先级不变,无绕过开关的采集选项。关闭开关会取消进行中的请求,但无法撤回已经送达的请求。+- 每天最多成功一次;失败最少间隔 6 小时、每日最多尝试 3 次,重启不清零。不补报历史活跃。每次请求总超时 5 秒,不跟随重定向;仅 HTTP 204 且携带服务端确认头视作成功,官网静态兜底 200 不算成功。+- 本地配额先写盘再发送,写盘失败、状态损坏或持久标识缺失时跳过上报。异常退出留下的空锁目录 60 秒后可回收。状态损坏需要人工检查共享目录中的 `usage-state.json`,不要删除账号目录或 `installation-id`。+- 上报仅含随机安装标识、profile、WorkDaddy 版本、系统、架构和 `os.release()` 内核版本。服务端可补充出口国家,不保存 IP。没有功能使用事件、账号、会话、输入内容、硬件序列号。++统计用户数是自该版本启用后被服务端观测到的安装数;不代表自然人数,关闭遥测或未升级的用户不会计入。同一电脑保留共享数据重装仍算一个安装;更换电脑或删除共享数据则算新安装。++验证:`node --test test/usage-report.test.js test/usage-activity.test.js test/sentry.test.js`,并执行仓库全量测试。发布时必须包含新 `usage-report.js`;macOS 构建清单已同步,Windows 继续沿用 scripts 目录整体复制。diff --git a/release/WorkDaddy.ico b/release/WorkDaddy.icoindex dd1ccd3..810d0e4 100644Binary files a/release/WorkDaddy.ico and b/release/WorkDaddy.ico differdiff --git a/scripts/apply-update.sh b/scripts/apply-update.shindex ef39d19..0445b0a 100644--- a/scripts/apply-update.sh+++ b/scripts/apply-update.sh@@ -109,6 +109,24 @@ mkdir -p "$(dirname "$APP_PATH")"cp -R "$SRC_APP" "$APP_PATH" || rollback 22chmod -R u+rwX "$APP_PATH" || rollback 23xattr -cr "$APP_PATH" 2>&1 || log "清除隔离属性失败(继续,可能已无隔离属性)"++# 覆盖 bundle 之后必须让 LaunchServices 重新注册。壳的 CFBundleExecutable 是 bash 脚本、+# bundle 也未签名,旧注册里可能带着 macOS 伪造的 LSArchitecturePriority=(x86_64, arm64)+# 缓存;只替换文件不会刷新该缓存,下一次启动仍按 Rosetta 拉起并弹「需要安装 Rosetta」。+# 必须先注销再注册才会真正重读 Info.plist 的 arm64 声明,并顺带清掉已挂载 dmg 卷里+# 同名副本的旧注册(用户可能曾直接从 dmg 双击启动过)。+LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"+if [ -x "$LSREGISTER" ]; then+ for stale in /Volumes/*/WorkDaddy*.app; do+ [ -d "$stale" ] || continue+ "$LSREGISTER" -u "$stale" >/dev/null 2>&1 || log "注销挂载卷残留注册失败: $stale"+ done+ "$LSREGISTER" -u "$APP_PATH" >/dev/null 2>&1 || log "注销旧注册失败(继续)"+ "$LSREGISTER" -f "$APP_PATH" >/dev/null 2>&1 || log "重新注册失败(继续)"+ log "LaunchServices 注册已刷新: $APP_PATH"+else+ log "未找到 lsregister,跳过注册刷新"+fiTARGET_DAEMON_VERSION="$(grep -o "const DAEMON_VERSION = '[^']*'" "$APP_PATH/Contents/Resources/scripts/daemon.js" | head -1 || true)"log "target daemon version=$TARGET_DAEMON_VERSION"diff --git a/scripts/assets/WorkDaddy.icns b/scripts/assets/WorkDaddy.icnsindex eacde79..1f28cff 100644Binary files a/scripts/assets/WorkDaddy.icns and b/scripts/assets/WorkDaddy.icns differdiff --git a/scripts/assets/workdaddy-app-icon.svg b/scripts/assets/workdaddy-app-icon.svgnew file mode 100644index 0000000..6edc5b0--- /dev/null+++ b/scripts/assets/workdaddy-app-icon.svg@@ -0,0 +1,43 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024" fill="none">+ <!-- Square master, based on the website's original floating robot. -->+ <defs>+ <linearGradient id="background" x1="160" y1="0" x2="890" y2="1100" gradientUnits="userSpaceOnUse">+ <stop stop-color="#34363d"/><stop offset=".5" stop-color="#17181d"/><stop offset="1" stop-color="#050506"/>+ </linearGradient>+ <linearGradient id="shell-side" x1="490" y1="315" x2="885" y2="910" gradientUnits="userSpaceOnUse">+ <stop stop-color="#e3e6da"/><stop offset=".48" stop-color="#b5bdae"/><stop offset="1" stop-color="#8b9785"/>+ </linearGradient>+ <radialGradient id="shell" cx="0" cy="0" r="1" gradientTransform="translate(301 391) rotate(48) scale(762 909)" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fffef7"/><stop offset=".48" stop-color="#eeeee9"/><stop offset=".83" stop-color="#dce0d4"/><stop offset="1" stop-color="#b7c0ac"/>+ </radialGradient>+ <linearGradient id="antenna" x1="461" y1="157" x2="506" y2="312" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fffef7"/><stop offset=".6" stop-color="#eeeee9"/><stop offset="1" stop-color="#bac3b0"/>+ </linearGradient>+ <linearGradient id="eyes" x1="280" y1="420" x2="558" y2="610" gradientUnits="userSpaceOnUse">+ <stop stop-color="#465443"/><stop offset="1" stop-color="#687267"/>+ </linearGradient>+ <linearGradient id="rim" x1="311" y1="295" x2="796" y2="878" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fff" stop-opacity=".85"/><stop offset="1" stop-color="#fff" stop-opacity=".04"/>+ </linearGradient>+ <filter id="robot-shadow" x="-30%" y="-30%" width="170%" height="180%">+ <feDropShadow dx="8" dy="27" stdDeviation="22" flood-color="#24331f" flood-opacity=".25"/>+ </filter>+ </defs>+ <defs><clipPath id="app-mask"><path d="M360 0H664C790 0 853 0 901 24C944 46 978 80 1000 123C1024 171 1024 234 1024 360V664C1024 790 1024 853 1000 901C978 944 944 978 901 1000C853 1024 790 1024 664 1024H360C234 1024 171 1024 123 1000C80 978 46 944 24 901C0 853 0 790 0 664V360C0 234 0 171 24 123C46 80 80 46 123 24C171 0 234 0 360 0Z"/></clipPath></defs>+ <g clip-path="url(#app-mask)">+ <rect width="1024" height="1024" fill="url(#background)"/>+ <!-- Keep the compact rounded-square shell, single antenna, and two upright eyes. -->+ <g transform="rotate(8 512 540)" filter="url(#robot-shadow)">+ <rect x="448" y="201" width="47" height="124" rx="23.5" fill="url(#antenna)"/>+ <circle cx="471.5" cy="188" r="42" fill="url(#antenna)"/>+ <rect x="155" y="314" width="725" height="604" rx="155" fill="url(#shell-side)"/>+ <rect x="116" y="292" width="720" height="604" rx="154" fill="url(#shell)"/>+ <rect x="120" y="296" width="712" height="596" rx="150" stroke="url(#rim)" stroke-width="8"/>+ <!-- Shift the original eyes up and left instead of changing the character. -->+ <rect x="259" y="430" width="99" height="158" rx="49.5" fill="#fff" fill-opacity=".6"/>+ <rect x="259" y="425" width="99" height="158" rx="49.5" fill="url(#eyes)"/>+ <rect x="469" y="430" width="108" height="162" rx="54" fill="#fff" fill-opacity=".6"/>+ <rect x="469" y="425" width="108" height="162" rx="54" fill="url(#eyes)"/>+ </g>+ </g>+</svg>diff --git a/scripts/assets/workdaddy-icon-foreground.png b/scripts/assets/workdaddy-icon-foreground.pngindex 544b019..c22ac10 100644Binary files a/scripts/assets/workdaddy-icon-foreground.png and b/scripts/assets/workdaddy-icon-foreground.png differdiff --git a/scripts/assets/workdaddy-logo.svg b/scripts/assets/workdaddy-logo.svgnew file mode 100644index 0000000..6edc5b0--- /dev/null+++ b/scripts/assets/workdaddy-logo.svg@@ -0,0 +1,43 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024" fill="none">+ <!-- Square master, based on the website's original floating robot. -->+ <defs>+ <linearGradient id="background" x1="160" y1="0" x2="890" y2="1100" gradientUnits="userSpaceOnUse">+ <stop stop-color="#34363d"/><stop offset=".5" stop-color="#17181d"/><stop offset="1" stop-color="#050506"/>+ </linearGradient>+ <linearGradient id="shell-side" x1="490" y1="315" x2="885" y2="910" gradientUnits="userSpaceOnUse">+ <stop stop-color="#e3e6da"/><stop offset=".48" stop-color="#b5bdae"/><stop offset="1" stop-color="#8b9785"/>+ </linearGradient>+ <radialGradient id="shell" cx="0" cy="0" r="1" gradientTransform="translate(301 391) rotate(48) scale(762 909)" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fffef7"/><stop offset=".48" stop-color="#eeeee9"/><stop offset=".83" stop-color="#dce0d4"/><stop offset="1" stop-color="#b7c0ac"/>+ </radialGradient>+ <linearGradient id="antenna" x1="461" y1="157" x2="506" y2="312" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fffef7"/><stop offset=".6" stop-color="#eeeee9"/><stop offset="1" stop-color="#bac3b0"/>+ </linearGradient>+ <linearGradient id="eyes" x1="280" y1="420" x2="558" y2="610" gradientUnits="userSpaceOnUse">+ <stop stop-color="#465443"/><stop offset="1" stop-color="#687267"/>+ </linearGradient>+ <linearGradient id="rim" x1="311" y1="295" x2="796" y2="878" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fff" stop-opacity=".85"/><stop offset="1" stop-color="#fff" stop-opacity=".04"/>+ </linearGradient>+ <filter id="robot-shadow" x="-30%" y="-30%" width="170%" height="180%">+ <feDropShadow dx="8" dy="27" stdDeviation="22" flood-color="#24331f" flood-opacity=".25"/>+ </filter>+ </defs>+ <defs><clipPath id="app-mask"><path d="M360 0H664C790 0 853 0 901 24C944 46 978 80 1000 123C1024 171 1024 234 1024 360V664C1024 790 1024 853 1000 901C978 944 944 978 901 1000C853 1024 790 1024 664 1024H360C234 1024 171 1024 123 1000C80 978 46 944 24 901C0 853 0 790 0 664V360C0 234 0 171 24 123C46 80 80 46 123 24C171 0 234 0 360 0Z"/></clipPath></defs>+ <g clip-path="url(#app-mask)">+ <rect width="1024" height="1024" fill="url(#background)"/>+ <!-- Keep the compact rounded-square shell, single antenna, and two upright eyes. -->+ <g transform="rotate(8 512 540)" filter="url(#robot-shadow)">+ <rect x="448" y="201" width="47" height="124" rx="23.5" fill="url(#antenna)"/>+ <circle cx="471.5" cy="188" r="42" fill="url(#antenna)"/>+ <rect x="155" y="314" width="725" height="604" rx="155" fill="url(#shell-side)"/>+ <rect x="116" y="292" width="720" height="604" rx="154" fill="url(#shell)"/>+ <rect x="120" y="296" width="712" height="596" rx="150" stroke="url(#rim)" stroke-width="8"/>+ <!-- Shift the original eyes up and left instead of changing the character. -->+ <rect x="259" y="430" width="99" height="158" rx="49.5" fill="#fff" fill-opacity=".6"/>+ <rect x="259" y="425" width="99" height="158" rx="49.5" fill="url(#eyes)"/>+ <rect x="469" y="430" width="108" height="162" rx="54" fill="#fff" fill-opacity=".6"/>+ <rect x="469" y="425" width="108" height="162" rx="54" fill="url(#eyes)"/>+ </g>+ </g>+</svg>diff --git a/scripts/automation.js b/scripts/automation.jsindex aa6bc27..d04f5de 100644--- a/scripts/automation.js+++ b/scripts/automation.js@@ -243,7 +243,7 @@ function taskIsPassiveCleanup(task) {const walk = value => {if (Array.isArray(value)) value.forEach(walk);else if (value && typeof value === 'object') {- if (value.op) { if (!allowed.has(value.op)) valid = false; if (value.op === 'dom.click') { clicks++; const locators = value.locators || [value.locator]; if (!locators.every(l=>l && l.visible === true && /close|dismiss|关闭|不再展示/i.test(l.value || ''))) valid = false; } }+ if (value.op) { if (!allowed.has(value.op)) valid = false; if (value.op === 'dom.click') { clicks++; const locators = value.locators || [value.locator]; if (!locators.every(l=>l && l.visible === true && (l.intent === 'dismiss' || /close|dismiss|关闭|不再展示/i.test(l.value || '')))) valid = false; } }Object.values(value).forEach(walk);}};@@ -261,18 +261,71 @@ function taskNeedsPanelClosed(task) {return walk([task.steps, task.onSuccess, task.onFailure]);}+function builtinContentHash(task) {+ const content = {+ schemaVersion: task.schemaVersion || SCHEMA_VERSION,+ id: task.id,+ name: task.name || '',+ description: task.description || '',+ variables: task.variables || {},+ steps: task.steps || [],+ onSuccess: task.onSuccess || [],+ onFailure: task.onFailure || [],+ requires: task.requires || null,+ };+ return crypto.createHash('sha256').update(JSON.stringify(content)).digest('hex');+}+function installBuiltinTask(dataDir, file) {const task = validateTask(JSON.parse(fs.readFileSync(file, 'utf8')));const markerFile = path.join(dataDir, 'automation-builtins.json');let markers = {};try { markers = JSON.parse(fs.readFileSync(markerFile, 'utf8')); } catch (_) {}- if (markers[task.id]) return;+ const previous = markers[task.id];const tasks = readAutomations(dataDir);- if (!tasks.some((t) => t.id === task.id)) {- if (tasks.length >= MAX_TASKS) return;+ const index = tasks.findIndex((item) => item && item.id === task.id);+ const revision = Number.isInteger(task.revision) && task.revision > 0 ? task.revision : 0;+ const writeMarker = (value) => atomicWriteText(markerFile, JSON.stringify({ ...markers, [task.id]: value }) + '\n');+ const managedMarker = () => ({ managed: true, revision: revision || 1, contentHash: builtinContentHash(task) });++ if (index === -1) {+ if (previous || tasks.length >= MAX_TASKS) return { status: 'skipped', revision };writeAutomations(dataDir, tasks.concat(task));+ writeMarker(revision ? managedMarker() : true);+ return { status: 'installed', revision: revision || 1 };}- atomicWriteText(markerFile, JSON.stringify({ ...markers, [task.id]: true }) + '\n');++ // An existing unmarked ID may be user-owned. Adopt it without ever making it+ // eligible for a later automatic replacement.+ if (!previous) {+ writeMarker({ managed: false });+ return { status: 'skipped', revision };+ }+ if (!revision || previous && typeof previous === 'object' && previous.managed === false) return { status: 'skipped', revision };++ const previousRevision = previous === true ? 1 : Number(previous.revision) || 1;+ if (revision <= previousRevision) return { status: 'skipped', revision };+ const installedHash = builtinContentHash(tasks[index]);+ const knownHistoricalHashes = Array.isArray(task.upgradeFromContentHashes) ? task.upgradeFromContentHashes : [];+ const expectedHash = previous && typeof previous === 'object' ? String(previous.contentHash || '') : '';+ const unchanged = expectedHash ? installedHash === expectedHash : knownHistoricalHashes.includes(installedHash);+ if (!unchanged) {+ writeMarker({ managed: false });+ return { status: 'skipped', revision };+ }++ const upgraded = {+ ...task,+ enabled: tasks[index].enabled !== false,+ trigger: tasks[index].trigger || task.trigger,+ schedule: tasks[index].schedule || task.schedule,+ updatedAt: Date.now(),+ };+ const next = tasks.slice();+ next[index] = upgraded;+ writeAutomations(dataDir, next);+ writeMarker(managedMarker());+ return { status: 'upgraded', revision };}function validateLocator(locator) {diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex 76992b7..5b3e2e0 100644--- a/scripts/build-mac-dmg.sh+++ b/scripts/build-mac-dmg.sh@@ -56,12 +56,19 @@ chmod 644 "$APP/Contents/Resources/AppIcon.icns"echo "==> 应用图标已同步(背景 #e1e1e1)"# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)-for f in daemon.js toast-runtime.js toast-options.js primary-account.js completion-report.js automation-runtime.js automation-packages.js automation-compatibility.js automation-transfer.js automation-zip.js automation.js automation-picker.js token-refresh.js session-db.js secure-transfer.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-usage-store.js growth-active.js atomic-file-write.js ui-port.js checkin-result.js lib.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do+for f in daemon.js toast-runtime.js toast-options.js primary-account.js completion-report.js automation-runtime.js automation-packages.js automation-compatibility.js automation-transfer.js automation-zip.js automation.js automation-picker.js token-refresh.js session-db.js third-party-models.js secure-transfer.js windows-process-boundary.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 atomic-file-write.js ui-port.js checkin-result.js lib.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"done+# Injection reads the wordmark at runtime; keep brand assets in both profiles.+mkdir -p "$APP/Contents/Resources/scripts/assets"+cp scripts/assets/workdaddy-logo.svg scripts/assets/workdaddy-app-icon.svg "$APP/Contents/Resources/scripts/assets/"# Presets are runtime source, independent of the reusable wallpaper/theme shell.mkdir -p "$APP/Contents/Resources/scripts/builtin/automations"cp scripts/builtin/automations/*.json "$APP/Contents/Resources/scripts/builtin/automations/"+if [ "$(find "$APP/Contents/Resources/scripts/builtin/automations" -type f -name '*.json' | wc -l | tr -d '[:space:]')" -lt 1 ]; then+ echo "错误:缺少内置自动化任务定义或未写入应用包" >&2+ exit 1+fiif [ -f "scripts/picker-internal.js" ]; thencp "scripts/picker-internal.js" "$APP/Contents/Resources/scripts/picker-internal.js"chmod 644 "$APP/Contents/Resources/scripts/picker-internal.js"@@ -90,7 +97,10 @@ chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \"$APP/Contents/Resources/scripts/secure-transfer.js" \"$APP/Contents/Resources/scripts/windows-process-boundary.js" \"$APP/Contents/Resources/scripts/credit-request-usage.js" \+ "$APP/Contents/Resources/scripts/credit-history-sync.js" \"$APP/Contents/Resources/scripts/credit-usage-store.js" \+ "$APP/Contents/Resources/scripts/credit-rotation.js" \+ "$APP/Contents/Resources/scripts/token-stats.js" \"$APP/Contents/Resources/scripts/atomic-file-write.js" \"$APP/Contents/Resources/scripts/ui-port.js" \"$APP/Contents/Resources/scripts/checkin-result.js" \@@ -124,6 +134,14 @@ if /usr/libexec/PlistBuddy -c 'Print :CFBundleIconName' "$PACKAGE_APP/Contents/Ielse/usr/libexec/PlistBuddy -c 'Add :CFBundleIconName string AppIcon' "$PACKAGE_APP/Contents/Info.plist"fi+LS_ARCH_PRIORITY="arm64"+if /usr/libexec/PlistBuddy -c 'Print :LSArchitecturePriority' "$PACKAGE_APP/Contents/Info.plist" >/dev/null 2>&1; then+ /usr/libexec/PlistBuddy -c 'Delete :LSArchitecturePriority' "$PACKAGE_APP/Contents/Info.plist"+fi+/usr/libexec/PlistBuddy -c 'Add :LSArchitecturePriority array' "$PACKAGE_APP/Contents/Info.plist"+/usr/libexec/PlistBuddy -c "Add :LSArchitecturePriority:0 string ${LS_ARCH_PRIORITY}" "$PACKAGE_APP/Contents/Info.plist"+BUILT_ARCH_PRIORITY="$(/usr/libexec/PlistBuddy -c 'Print :LSArchitecturePriority:0' "$PACKAGE_APP/Contents/Info.plist" 2>/dev/null || true)"+if [ "$BUILT_ARCH_PRIORITY" != "$LS_ARCH_PRIORITY" ]; then exit 3; fised -i.bak "s|^PROFILE=.*|PROFILE=\"${PROFILE}\"|" "$PACKAGE_APP/Contents/MacOS/launcher"rm -f "$PACKAGE_APP/Contents/MacOS/launcher.bak"# 企业版可能在 /Applications 下使用不同的 .app 名称。把官方路径优先、@@ -280,6 +298,26 @@ if [ "$PROFILE" = "workbuddy-ai" ]; thenperl -0pi -e 's/<string>WorkDaddy<\/string>/<string>WorkDaddy AI<\/string>/g' "$PACKAGE_APP/Contents/Info.plist"perl -0pi -e 's/<string>com\.workdaddy\.launcher<\/string>/<string>com.workdaddy.ai.launcher<\/string>/g' "$PACKAGE_APP/Contents/Info.plist"fi+# LaunchServices must own the target app identity, rather than inheriting the shell launcher.+python3 - "$PACKAGE_APP/Contents/MacOS/launcher" <<'PY'+import sys+from pathlib import Path+p = Path(sys.argv[1])+s = p.read_text()+old = 'nohup "$APP_BIN" --remote-debugging-port="$PORT" >/dev/null 2>&1 &\ndisown 2>/dev/null || true'+new = '''TARGET_APP_BUNDLE="${APP_BIN%/Contents/MacOS/*}"+if [ "$TARGET_APP_BUNDLE" = "$APP_BIN" ] || [ ! -d "$TARGET_APP_BUNDLE" ]; then+ notify "WorkDaddy" "WorkBuddy 应用路径无效,启动失败"+ exit 1+fi+if ! /usr/bin/open -a "$TARGET_APP_BUNDLE" --args "--remote-debugging-port=$PORT"; then+ notify "WorkDaddy" "无法启动 WorkBuddy,请重试"+ exit 1+fi'''+if old not in s and new not in s:+ raise SystemExit('macOS launcher 缺少应用启动锚点')+p.write_text(s.replace(old, new))+PY# 注入完成后把目标 WorkBuddy 置前台,避免复用已有 CDP 时 Dock 仍停留在启动器上。python3 - "$PACKAGE_APP/Contents/MacOS/launcher" <<'PY'import rediff --git a/scripts/builtin/automations/close-buddy-popups.json b/scripts/builtin/automations/close-buddy-popups.jsonindex 6565da4..cee66fd 100644--- a/scripts/builtin/automations/close-buddy-popups.json+++ b/scripts/builtin/automations/close-buddy-popups.json@@ -1,8 +1,12 @@{"schemaVersion": 1,"id": "buddy-fuel-station-close-on-account-switch",+ "revision": 2,+ "upgradeFromContentHashes": [+ "7409d4d92618b59326e56629f4d9ba804ae30a4e36d7d5ed156042b9a3a744bd"+ ],"name": "页面就绪后自动关闭首页弹窗",- "description": "页面就绪后立即检查三类弹窗,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。",+ "description": "页面就绪后立即检查首页弹窗与运营位,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。","enabled": true,"trigger": {"type": "pageReady",@@ -88,19 +92,90 @@"steps": [{"op": "dom.click",- "locator": {- "kind": "css",- "value": "button.activity-bubble__close",- "visible": true- }+ "locators": [+ {+ "kind": "css",+ "value": "button[data-track-id=\"home_growth_close\"]",+ "visible": true+ },+ {+ "kind": "css",+ "value": ".wb-slot--home-growth button.wb-slot--closable-close",+ "visible": true+ }+ ]},{"op": "dom.wait",- "locator": {- "kind": "css",- "value": "button.activity-bubble__close",- "visible": true+ "locators": [+ {+ "kind": "css",+ "value": "button[data-track-id=\"home_growth_close\"]",+ "visible": true+ },+ {+ "kind": "css",+ "value": ".wb-slot--home-growth button.wb-slot--closable-close",+ "visible": true+ }+ ],+ "until": {+ "state": "hidden"},+ "timeoutMs": 750+ },+ {+ "op": "notify.toast",+ "level": "success",+ "message": "已关闭「做任务赢积分好礼」入口"+ }+ ],+ "onError": []+ },+ {+ "op": "logic.catch",+ "steps": [+ {+ "op": "dom.click",+ "locators": [+ {+ "kind": "css",+ "value": "button.activity-bubble__close",+ "visible": true+ },+ {+ "kind": "css",+ "value": "button.claw-welcome-activity-card__close",+ "visible": true+ },+ {+ "kind": "css",+ "value": "div[style*=\"width: 213px\"][style*=\"pointer-events: auto\"] > div[style*=\"height: 124px\"] > div[style*=\"height: 40px\"] > button[type=\"button\"][style*=\"width: 16px\"][style*=\"height: 16px\"]",+ "visible": true,+ "intent": "dismiss"+ }+ ]+ },+ {+ "op": "dom.wait",+ "locators": [+ {+ "kind": "css",+ "value": "button.activity-bubble__close",+ "visible": true+ },+ {+ "kind": "css",+ "value": "button.claw-welcome-activity-card__close",+ "visible": true+ },+ {+ "kind": "css",+ "value": "div[style*=\"width: 213px\"][style*=\"pointer-events: auto\"] > div[style*=\"height: 124px\"] > div[style*=\"height: 40px\"] > button[type=\"button\"][style*=\"width: 16px\"][style*=\"height: 16px\"]",+ "visible": true,+ "intent": "dismiss"+ }+ ],"until": {"state": "hidden"},diff --git a/scripts/credit-history-sync.js b/scripts/credit-history-sync.jsnew file mode 100644index 0000000..3dd5ec1--- /dev/null+++ b/scripts/credit-history-sync.js@@ -0,0 +1,152 @@+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const { randomUUID } = require('node:crypto');+const { fetchUsageSinceAnchor, startOfLocalDay } = require('./credit-request-usage.js');++function dateString(date) {+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;+}++function historyRange(days = 7, now = new Date()) {+ days = Number(days);+ if (!Number.isSafeInteger(days) || days < 1) throw new Error('用量日期范围无效');+ days = Math.min(90, days);+ const endTime = new Date(now);+ const startTime = startOfLocalDay(endTime);+ startTime.setDate(startTime.getDate() - days + 1);+ return { days, startTime, endTime, from: dateString(startTime), to: dateString(endTime) };+}++// Only validated daily API totals are persisted, including verified zero days.+// Today's snapshot expires briefly; after midnight its unfinished day is fetched+// once more before becoming immutable history. Never reuse the today-usage anchor.+function createCreditHistorySync(options) {+ const cache = new Map();+ const clock = options.now || (() => new Date());+ const todayTtl = options.todayTtlMs || 60000;+ const key = (uid, date) => uid + ':' + date;+ try {+ const stored = JSON.parse(fs.readFileSync(options.cacheFile, 'utf8'));+ if (stored.version === 1 && Array.isArray(stored.daily)) for (const row of stored.daily) {+ if (typeof row.uid !== 'string' || !/^\d{4}-\d\d-\d\d$/.test(row.date) ||+ !Number.isFinite(row.used) || row.used < 0 || !Number.isSafeInteger(row.count) || row.count < 0 ||+ !Number.isFinite(row.queriedAt) || typeof row.final !== 'boolean') continue;+ cache.set(key(row.uid, row.date), row);+ }+ } catch (_) { /* Absent or invalid cache: query the official API. */ }+ function persist() {+ if (!options.cacheFile) return;+ const tmp = options.cacheFile + '.tmp';+ try {+ fs.mkdirSync(path.dirname(options.cacheFile), { recursive: true, mode: 0o700 });+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, daily: Array.from(cache.values()) }), { mode: 0o600 });+ fs.renameSync(tmp, options.cacheFile);+ } catch (_) { /* In-memory results remain usable if disk is unavailable. */ }+ }+ let job = null;+ let completion = Promise.resolve({ running: false });+ function status() { return job ? JSON.parse(JSON.stringify(job)) : { running: false }; }+ function start({ accounts, days }) {+ const range = historyRange(days, clock());+ const selected = Array.from(new Map(accounts.map(a => [a.uid, { uid: a.uid, nickname: a.nickname || a.uid }])).values());+ const sameScope = job && job.from === range.from && job.to === range.to &&+ job.accounts.map(a => a.uid).sort().join(',') === selected.map(a => a.uid).sort().join(',');+ if (job && job.running) {+ if (sameScope) return status();+ const error = new Error('另一个积分查询正在进行,请稍后重试');+ error.status = 409;+ throw error;+ }+ const cutoff = historyRange(90, range.endTime).from;+ for (const [id, row] of cache) if (row.date < cutoff || row.queriedAt > range.endTime.getTime()) cache.delete(id);+ const dates = [];+ for (const date = new Date(range.startTime); date <= range.endTime; date.setDate(date.getDate() + 1)) dates.push(new Date(date));+ const fresh = row => row && (row.final || (row.date === range.to && range.endTime.getTime() - row.queriedAt < todayTtl));+ const plans = selected.map(account => {+ const gaps = [];+ for (const date of dates) {+ if (fresh(cache.get(key(account.uid, dateString(date))))) continue;+ const end = new Date(date); end.setDate(end.getDate() + 1); end.setSeconds(end.getSeconds() - 1);+ const endTime = new Date(Math.min(end.getTime(), range.endTime.getTime()));+ const previous = gaps[gaps.length - 1];+ if (previous && previous.endTime.getTime() + 1000 === date.getTime()) previous.endTime = endTime;+ else gaps.push({ startTime: date, endTime });+ }+ return { account, gaps };+ });+ function readDaily() {+ return selected.flatMap(a => dates.map(date => cache.get(key(a.uid, dateString(date)))).filter(Boolean)+ .map(row => ({ uid: row.uid, date: row.date, used: row.used, count: row.count, complete: true })));+ }+ const initial = readDaily();+ const cacheHit = plans.every(plan => !plan.gaps.length);+ job = { id: randomUUID(), running: !cacheHit, from: range.from, to: range.to,+ source: 'server', accounts: selected, daily: initial, queriedAt: range.endTime.getTime(),+ cacheHit, hasCachedData: initial.length > 0, total: selected.length,+ completed: 0, synced: 0, failures: [], current: '', page: 0, pages: 0, records: 0, percent: 0 };+ const active = job;+ if (cacheHit) {+ Object.assign(active, { completed: selected.length, synced: selected.length, percent: 100 });+ completion = Promise.resolve(status());+ return status();+ }+ async function run() {+ for (const { account, gaps } of plans) {+ active.current = account.nickname;+ active.page = 0; active.pages = 0; active.records = 0;+ try {+ const accessToken = gaps.length ? await options.getAccessToken(account.uid) : '';+ if (gaps.length && !accessToken) throw new Error('账号凭据不可用');+ for (let i = 0; i < gaps.length; i++) {+ const gap = gaps[i];+ const result = await (options.fetchUsage || fetchUsageSinceAnchor)({+ accessToken, apiHost: options.apiHost, ...gap,+ onProgress: ({ page, pages, records }) => {+ active.page = page; active.pages = pages; active.records = records;+ active.percent = Math.min(99, Math.floor((active.completed + (i + (pages ? page / pages : 0)) / gaps.length) / active.total * 100));+ },+ });+ const daily = new Map();+ for (const date = new Date(gap.startTime); date <= gap.endTime; date.setDate(date.getDate() + 1)) {+ const day = dateString(date);+ daily.set(day, { uid: account.uid, date: day, used: 0, count: 0,+ queriedAt: range.endTime.getTime(), final: day < range.to });+ }+ const seen = new Set();+ for (const record of result.records) {+ const day = daily.get(record.usageDate);+ if (!day || seen.has(record.requestId)) continue;+ seen.add(record.requestId);+ day.used += record.credit; day.count++;+ }+ for (const day of daily.values()) {+ day.used = Math.round(day.used * 100) / 100;+ cache.set(key(day.uid, day.date), day);+ }+ persist();+ }+ active.synced++;+ } catch (error) {+ const text = String(error && error.message || '');+ const reason = /401|403|凭据|accessToken|token/i.test(text) ? '登录身份过期或不可用,请重新登录后重试' :+ /超时|timeout/i.test(text) ? '请求超时,请稍后重试' : '记录未完整获取,请稍后重试';+ active.failures.push({ uid: account.uid, nickname: account.nickname, error: reason });+ }+ active.daily = readDaily();+ active.completed++;+ active.percent = Math.floor(active.completed / active.total * 100);+ }+ active.running = false;+ active.current = '';+ active.percent = 100;+ return JSON.parse(JSON.stringify(active));+ }+ completion = run();+ return status();+ }+ return { start, status, wait: () => completion };+}++module.exports = { createCreditHistorySync, historyRange };diff --git a/scripts/credit-request-usage.js b/scripts/credit-request-usage.jsindex 30b0aad..16cd577 100644--- a/scripts/credit-request-usage.js+++ b/scripts/credit-request-usage.js@@ -157,6 +157,10 @@ async function fetchUsageSinceAnchor(options = {}) {});if (expectedTotal === null) expectedTotal = page.total;else if (page.total !== expectedTotal) throw new Error('官方用量接口分页总数发生变化');+ if (typeof options.onProgress === 'function') options.onProgress({+ page: pageNum, pages: Math.max(pageNum, Math.ceil(expectedTotal / pageSize)),+ records: fetchedRows + page.rows.length, total: expectedTotal,+ });if (!page.rows.length) {if (fetchedRows >= expectedTotal) {return { records, newestRequestId, total: expectedTotal, pages: pageNum, reachedAnchor };diff --git a/scripts/credit-rotation.js b/scripts/credit-rotation.jsnew file mode 100644index 0000000..ea02141--- /dev/null+++ b/scripts/credit-rotation.js@@ -0,0 +1,80 @@+'use strict';++const DAY_MS = 24 * 60 * 60 * 1000;++function finiteNumber(value) {+ const number = Number(value);+ return Number.isFinite(number) ? number : null;+}++function normalizeSegment(segment) {+ if (!segment || typeof segment !== 'object') return null;+ const remaining = finiteNumber(segment.remaining);+ if (remaining === null || remaining <= 0) return null;+ const expiresAt = segment.expiresAt === null || segment.expiresAt === undefined || segment.expiresAt === ''+ ? null+ : finiteNumber(segment.expiresAt);+ return {+ remaining,+ expiresAt,+ source: String(segment.source || '积分'),+ packageCode: String(segment.packageCode || ''),+ };+}++function nearestExpiringSegment(segments, now = Date.now()) {+ const current = Number(now);+ const at = Number.isFinite(current) ? current : Date.now();+ return (Array.isArray(segments) ? segments : [])+ .map(normalizeSegment)+ .filter(Boolean)+ .filter((segment) => segment.expiresAt === null || segment.expiresAt > at)+ .sort((a, b) => {+ if (a.expiresAt === null && b.expiresAt !== null) return 1;+ if (a.expiresAt !== null && b.expiresAt === null) return -1;+ return (a.expiresAt || Number.MAX_SAFE_INTEGER) - (b.expiresAt || Number.MAX_SAFE_INTEGER);+ })[0] || null;+}++function segmentKey(segment) {+ if (!segment) return '';+ return [segment.expiresAt === null ? 'never' : segment.expiresAt, segment.packageCode || segment.source].join('|');+}++function wasNearestSegmentConsumed(previousSegments, nextSegments, now = Date.now()) {+ const previous = nearestExpiringSegment(previousSegments, now);+ if (!previous) return false;+ const next = nearestExpiringSegment(nextSegments, now);+ if (!next) return true;+ return segmentKey(previous) !== segmentKey(next) &&+ (previous.expiresAt !== null && (next.expiresAt === null || next.expiresAt > previous.expiresAt));+}++function selectRotationCandidate(accounts, currentUid, now = Date.now()) {+ const candidates = (Array.isArray(accounts) ? accounts : [])+ .filter((account) => account && String(account.uid || '') && String(account.uid) !== String(currentUid || ''))+ .map((account) => ({ account, segment: nearestExpiringSegment(account.creditSegments || account.segments, now) }))+ .filter((item) => item.segment && item.segment.remaining > 0)+ .sort((a, b) => {+ const ae = a.segment.expiresAt === null ? Number.MAX_SAFE_INTEGER : a.segment.expiresAt;+ const be = b.segment.expiresAt === null ? Number.MAX_SAFE_INTEGER : b.segment.expiresAt;+ if (ae !== be) return ae - be;+ return b.segment.remaining - a.segment.remaining;+ });+ return candidates[0] || null;+}++function isSameLocalDay(a, b = Date.now()) {+ const left = new Date(Number(a));+ const right = new Date(Number(b));+ if (!Number.isFinite(left.getTime()) || !Number.isFinite(right.getTime())) return false;+ return left.getFullYear() === right.getFullYear() && left.getMonth() === right.getMonth() && left.getDate() === right.getDate();+}++module.exports = {+ DAY_MS,+ nearestExpiringSegment,+ wasNearestSegmentConsumed,+ selectRotationCandidate,+ isSameLocalDay,+};diff --git a/scripts/credit-usage-store.js b/scripts/credit-usage-store.jsindex e17869a..0028919 100644--- a/scripts/credit-usage-store.js+++ b/scripts/credit-usage-store.js@@ -80,6 +80,12 @@ function createCreditUsageStore(options = {}) {PRIMARY KEY (profile_id, uid))`);+ await db.run(`+ CREATE TABLE IF NOT EXISTS credit_history_days (+ profile_id TEXT NOT NULL, uid TEXT NOT NULL, usage_date TEXT NOT NULL,+ synced_at INTEGER NOT NULL, PRIMARY KEY (profile_id, uid, usage_date)+ )+ `);await db.run(`CREATE TABLE IF NOT EXISTS daily_checkin_records (profile_id TEXT NOT NULL,@@ -120,12 +126,8 @@ function createCreditUsageStore(options = {}) {};}- async function saveSuccessfulSync({ uid, records, anchorRequestId, syncedAt }) {- await initialize();- const accountUid = validIdentity(uid, 'uid');+ async function saveRecords(accountUid, records) {const list = Array.isArray(records) ? records : [];- const timestamp = Number(syncedAt);- if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error('同步时间无效');for (let offset = 0; offset < list.length; offset += 200) {const statements = list.slice(offset, offset + 200).map((record) => ({sql: INSERT_USAGE_SQL,@@ -143,6 +145,33 @@ function createCreditUsageStore(options = {}) {}));if (statements.length) await db.transaction(statements);}+ }++ async function saveHistoryUsage({ uid, records, from, to, syncedAt }) {+ await initialize();+ const accountUid = validIdentity(uid, 'uid');+ const start = localDayRange(validDate(from)).start;+ const end = localDayRange(validDate(to)).start;+ if (start > end || end - start > 90 * 86400000) throw new Error('用量日期范围无效');+ if (!Number.isSafeInteger(syncedAt) || syncedAt < 0) throw new Error('同步时间无效');+ await saveRecords(accountUid, records);+ const days = [];+ for (const date = new Date(start); date.getTime() <= end; date.setDate(date.getDate() + 1)) {+ const day = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;+ days.push({ sql: `INSERT INTO credit_history_days (profile_id, uid, usage_date, synced_at)+ VALUES (?, ?, ?, ?) ON CONFLICT(profile_id, uid, usage_date) DO UPDATE SET synced_at = excluded.synced_at`,+ params: [profileId, accountUid, day, syncedAt] });+ }+ await db.transaction(days);+ try { fs.chmodSync(dbPath, 0o600); } catch (_) {}+ }++ async function saveSuccessfulSync({ uid, records, anchorRequestId, syncedAt }) {+ await initialize();+ const accountUid = validIdentity(uid, 'uid');+ const timestamp = Number(syncedAt);+ if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error('同步时间无效');+ await saveRecords(accountUid, records);await db.run(`INSERT INTO credit_usage_sync_state(profile_id, uid, anchor_request_id, last_success_at)@@ -196,6 +225,35 @@ function createCreditUsageStore(options = {}) {return summaries[accountUid] || null;}+ async function listDailyUsageRange(uids, fromDate, toDate) {+ await initialize();+ const accountUids = Array.from(new Set((Array.isArray(uids) ? uids : []).map((uid) => validIdentity(uid, 'uid'))));+ if (!accountUids.length) return [];+ const from = validDate(fromDate);+ const to = validDate(toDate);+ if (from > to) throw new Error('用量日期范围无效');+ const placeholders = accountUids.map(() => '?').join(',');+ const rows = await db.all(+ `SELECT uid, usage_date AS date, ROUND(SUM(credit), 2) AS used, COUNT(*) AS count+ FROM credit_usage_records+ WHERE profile_id = ? AND usage_date >= ? AND usage_date <= ? AND uid IN (${placeholders})+ GROUP BY uid, usage_date ORDER BY usage_date ASC, uid ASC`,+ [profileId, from, to, ...accountUids]+ );+ const result = new Map(rows.map(row => [row.uid + ':' + row.date,+ { uid: String(row.uid), date: String(row.date), used: Number(row.used) || 0, count: Number(row.count) || 0, cached: true, complete: false }]));+ const coverage = await db.all(`SELECT uid, usage_date, synced_at FROM credit_history_days+ WHERE profile_id = ? AND usage_date >= ? AND usage_date <= ? AND uid IN (${placeholders})`,+ [profileId, from, to, ...accountUids]);+ for (const row of coverage) {+ const key = row.uid + ':' + row.usage_date;+ const item = result.get(key) || { uid: row.uid, date: row.usage_date, used: 0, count: 0, cached: true };+ item.complete = true; item.syncedAt = Number(row.synced_at);+ result.set(key, item);+ }+ return Array.from(result.values()).sort((a, b) => a.date.localeCompare(b.date) || a.uid.localeCompare(b.uid));+ }+async function getDailyCheckin(uid, date) {await initialize();const accountUid = validIdentity(uid, 'uid');@@ -270,12 +328,14 @@ function createCreditUsageStore(options = {}) {return {dailyUsageForUid,+ listDailyUsageRange,getDailyCheckin,listDailyCheckins,getSyncState,initialize,listDailyUsage,saveSuccessfulSync,+ saveHistoryUsage,saveDailyCheckin,};}diff --git a/scripts/daemon.js b/scripts/daemon.jsindex eab493b..d653699 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -72,6 +72,7 @@ const {logFile,ensureDirs,readAuthFile,+ parseAuthJson,backupCurrent,listAccounts,switchTo,@@ -112,10 +113,13 @@ const {importModels,checkinDisplayValue,} = require('./lib.js');+const { createThirdPartyImport } = require('./third-party-models.js');const { extractCreditSegments, sortCreditSegments, mergeCreditSegments, parseEnterpriseUsage, ENTERPRISE_EDITIONS } = require('./credit-segments.js');const { buildCreditResourceBody } = require('./credit-resource-queries.js');const { fetchUsageSinceAnchor, startOfLocalDay } = require('./credit-request-usage.js');+const { createCreditHistorySync, historyRange } = require('./credit-history-sync.js');const { createCreditUsageStore } = require('./credit-usage-store.js');+const { scanTokenStatsCached, tokenStatsCacheReady } = require('./token-stats.js');const { classifyCheckinResult, checkinEndpointsForToken } = require('./checkin-result.js');const {DAY_MS: TOKEN_REFRESH_DAY_MS,@@ -131,6 +135,7 @@ const {telemetryEnabled,telemetryEnvironmentOverride,} = require('./sentry-report.js');+const { createUsageReporter } = require('./usage-report.js');const { getProfile, profileDataDir, listInstalledModelSources } = require('./profiles.js');const { readWorkBuddyTarget } = require('./workbuddy-target.js');const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('./cdp-targets.js');@@ -180,6 +185,7 @@ const { runCompletionReport, probeAccountCompletion } = require('./completion-reconst { createPrimaryAccountStore } = require('./primary-account.js');const PROFILE = getProfile();const DATA_DIR = defaultDataDir();+const thirdPartyModels = createThirdPartyImport({ targetFile: workbuddyModelsFile(), dataDir: DATA_DIR });const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.existsSync(accountBackupFile(uid)));// 版本号:改动 daemon/inject/theme-patches/builtin 资产后递增,launcher 检测到运行中版本不一致会强制用 app 内置代码重启// 0.6.6:品牌 HelloBuddy→WorkDaddy 期间版本号未递增,旧 HelloBuddy daemon 会被 launcher 误判为"同版本"而不重启,导致旧代码继续注入;递增后强制升级@@ -330,8 +336,19 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis// 1.1.65:自动化会话发送前确保进入新版 WorkBuddy 新建任务页。// 1.1.66:新版侧栏 tab 共用 conversation-list-tab-button-box,改用文字确认新建任务。// 1.1.67:项目页存在普通 composer 时仍强制定位并点击新建任务 tab。-const DAEMON_VERSION = '1.2.4';-const DAEMON_BUILD_ID = 'release-1.2.4-20260908-send-button-poll-200ms';+// 1.2.17:会话完成后的积分段轮换建议:刷新当前账号,候选账号只读内存缓存。+// 1.2.18:Token 统计支持账号、模型、预设时间和日期范围筛选,诊断信息折叠展示。+// 1.2.19:Token 历史统计落盘缓存,今日记录按文件变化增量更新。+// 1.2.20:Token 查询收紧至 90 天,搜索使用固定尺寸蒙层并统一紧凑数字格式。+// 1.2.21:Token 扫描从 sessions 表恢复日志账号归属并重建旧缓存,修复按账号筛选为空。+// 1.2.22:Token 缓存改为日期/账号/模型聚合结果,打开面板时复用缓存并仅增量读取今日变更文件。+// 1.2.23:临时支持会话完成后强制弹出账号切换提示,供交互验收。+// 1.2.24:账号轮换恢复真实积分段消耗检测,仅推荐缓存中到期时间最近的可用账号。+// 1.2.25:首页弹窗任务补齐成长/活动入口,并按 renderer 页面身份修复重连后的 pageReady 触发。+// 1.2.26:无效账号备份不再显示可点击的切换按钮,导入路径拒绝写入无效认证数据。+const DAEMON_VERSION = '1.2.36';+const DAEMON_BUILD_ID = 'release-1.2.36-20260913-credit-rotation-always-check';+const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});const HOST = '127.0.0.1';const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)@@ -349,11 +366,24 @@ const CDP_PORT_FILE = path.join(DATA_DIR, 'cdp-port.json');const UI_PORT_FILE = path.join(DATA_DIR, 'ui-port.json');const API_TOKEN_FILE = path.join(DATA_DIR, '.api-token');const BACKGROUND_BLUR_FILE = path.join(DATA_DIR, 'background-blur.json');+const themeTextShadow = require('./theme-text-shadow.js').createThemeTextShadow(path.join(DATA_DIR, 'theme-text-shadow.json'));const MAX_BACKGROUND_BLUR_PX = 32;const CREDIT_USAGE_DB_FILE = path.join(DATA_DIR, 'credit-usage.db');const CREDIT_USAGE_STORE = createCreditUsageStore({ dbPath: CREDIT_USAGE_DB_FILE, profileId: PROFILE.id });+const creditHistorySync = createCreditHistorySync({+ cacheFile: path.join(DATA_DIR, 'credit-stats-cache.json'),+ apiHost: PROFILE.apiHost,+ getAccessToken: async (uid) => {+ const refreshed = await refreshAccountBackupToken(uid);+ if (refreshed.error || !refreshed.root) throw new Error('账号凭据不可用');+ const auth = refreshed.root.auth || {};+ return auth.accessToken || auth.access_token || auth.token;+ },+});const CREDIT_USAGE_REFRESH_MS = 15000;const creditUsageSyncInFlight = new Map();+const { selectRotationCandidate } = require('./credit-rotation.js');+const creditRotationCache = new Map();const WATCH_INTERVAL = 3000; // 文件监听兜底const BACKUP_DEBOUNCE = 1500; // CDP 事件触发的备份防抖const CDP_RECONNECT_MS = 5000;@@ -966,7 +996,7 @@ function validateUpdateArtifact(file, expectSha = null) {// ---------------------------------------------------------------------------// 无感登录(OAuth state 轮询采集,流程与 workbuddy-switch 一致):-// 1. POST /v2/plugin/auth/state?platform=workbuddy 申请 state + 授权链接+// 1. POST /v2/plugin/auth/state?platform=<客户端标识> 申请 state + 授权链接// 2. 用户在系统浏览器完成扫码授权(WorkBuddy 全程不退出)// 3. 轮询 GET /v2/plugin/auth/token?state=... 拿 accessToken// 4. GET /v2/plugin/login/account?state=... 拉账号信息,拼成官方认证文件结构入库@@ -1577,6 +1607,7 @@ let manualInjectPromise = null; // launcher 超时重试时复用同一轮注入let pendingReloadInjection = null; // 仅对 WorkDaddy 主动触发的页面重载做一次主 frame 早期注入let mainFrameNavigationSerial = 0;let suppressPageLoadInjectionForNavigation = 0;+let cdpPageSessionId = '';const automationEventKeys = new Set();let pendingAutomationAccountSwitch = null;@@ -1821,6 +1852,9 @@ async function connectCdp() {cdp.error = null;cdp.targetUrl = target.url || '';cdp.targetTitle = target.title || '';+ // Target ids survive a transient WebSocket reconnect but change with a+ // restarted renderer, unlike the navigation serial missed while offline.+ cdpPageSessionId = String(target.id || target.webSocketDebuggerUrl || 'unknown');log(`[cdp] 已连接 WorkBuddy (port=${cdp.port}, target=${cdp.targetUrl})`);// 打开感兴趣的能力域cdpSend('Page.enable').catch(() => {});@@ -1836,11 +1870,8 @@ async function connectCdp() {// 恢复已保存的主题(页面刷新/WorkBuddy 重启后 WorkBuddy 回到官方浅色,// 这里重新应用,保证「WorkDaddy 主题=深色 / WorkBuddy 默认主题=浅色」在重启后仍生效)restoreSavedTheme().catch((e) => log(`[theme] 恢复主题失败: ${e.message}`));- // 某些旧版 renderer 在 daemon 连接后不会再发送 loadEventFired;- // readyState 已完成时补发一次首屏生命周期事件,按导航序号去重。- cdpSend('Runtime.evaluate', { expression: 'document.readyState', returnByValue: true }).then((r) => {- if (r && r.result && r.result.value === 'complete') dispatchAutomationEvent('pageReady', { navigationSerial: mainFrameNavigationSerial, source: 'connect' });- }).catch(() => {});+ // 连接可能发生在 loadEventFired 之后,也可能正好处于页面加载中。+ waitForPageReadyThenDispatch(cdpPageSessionId);}, 1200);resolve(true);};@@ -1876,11 +1907,27 @@ async function connectCdp() {});}+function waitForPageReadyThenDispatch(pageSessionId, attempt = 0) {+ if (!cdp.connected || pageSessionId !== cdpPageSessionId) return;+ const retry = () => {+ if (attempt < 20) setTimeout(() => waitForPageReadyThenDispatch(pageSessionId, attempt + 1), 500);+ };+ cdpSend('Runtime.evaluate', { expression: 'document.readyState', returnByValue: true }).then((response) => {+ if (!cdp.connected || pageSessionId !== cdpPageSessionId) return;+ if (response && response.result && response.result.value === 'complete') {+ dispatchAutomationEvent('pageReady', { navigationSerial: mainFrameNavigationSerial, pageSessionId, source: 'connect' });+ return;+ }+ retry();+ }).catch(retry);+}+function dispatchAutomationEvent(type, detail = {}) {const eventType = String(type || '').trim();if (!['pageReady', 'pageLoaded', 'accountSwitched', 'panelOpened'].includes(eventType)) return;const canonicalType = eventType === 'pageReady' ? 'pageReady' : eventType;- const key = canonicalType + ':' + String(detail.navigationSerial == null ? mainFrameNavigationSerial : detail.navigationSerial);+ const pageSessionId = String(detail.pageSessionId || cdpPageSessionId || 'unknown');+ const key = canonicalType + ':' + pageSessionId + ':' + String(detail.navigationSerial == null ? mainFrameNavigationSerial : detail.navigationSerial);if (canonicalType === 'pageReady' && automationEventKeys.has(key)) return;if (canonicalType === 'pageReady') {automationEventKeys.add(key);@@ -1891,10 +1938,10 @@ function dispatchAutomationEvent(type, detail = {}) {const account = detail.account || currentAccount();tasks.forEach((task) => {try {- const event = { type: canonicalType, navigationSerial: detail.navigationSerial == null ? mainFrameNavigationSerial : detail.navigationSerial, source: detail.source || 'cdp', account: account ? { uid: account.uid, nickname: account.nickname } : null };+ const event = { type: canonicalType, navigationSerial: detail.navigationSerial == null ? mainFrameNavigationSerial : detail.navigationSerial, pageSessionId, source: detail.source || 'cdp', account: account ? { uid: account.uid, nickname: account.nickname } : null };const run = Array.from(automationRuns.values()).find((item) => item.taskId === task.id && item.status === 'running');if (run) {- if (task.trigger.restartOnNavigation && run.navigationSerial !== event.navigationSerial) {+ if (task.trigger.restartOnNavigation && (run.navigationSerial !== event.navigationSerial || run.pageSessionId !== event.pageSessionId)) {run.superseded = true;run.pendingEvent = event;}@@ -2747,7 +2794,9 @@ async function automationDomAction(op, locator, detail) {assertActive();if (found.blocked) throw new Error('页面元素被遮挡或禁用,稍后重试');const x = found.x + found.w / 2; const y = found.y + found.h / 2;- await cdpMouseClick('dom.click:' + String(locator && locator.value || ''), x, y, { op, found }, { skipMove: locator && locator.visible === true });+ const locators = Array.isArray(locator) ? locator : [locator];+ const locatorLabel = locators.map((item) => item && item.value || '').filter(Boolean).join(' | ');+ await cdpMouseClick('dom.click:' + locatorLabel, x, y, { op, found }, { skipMove: locators.some((item) => item && item.visible === true) });return found;}const focus = `(function(){var el=${expr};if(!el)return false;el.focus();return true})()`;@@ -2894,7 +2943,7 @@ function automationSwitchAccount(account) {return run;}function startAutomationRun(task, event = null) {- if (event && event.navigationSerial == null) event = { ...event, navigationSerial: mainFrameNavigationSerial };+ if (event && (event.navigationSerial == null || event.pageSessionId == null)) event = { ...event, navigationSerial: event.navigationSerial == null ? mainFrameNavigationSerial : event.navigationSerial, pageSessionId: event.pageSessionId || cdpPageSessionId };if (automationRuns.size > 200) {for (const [key, value] of automationRuns) {if (value.status !== 'running') automationRuns.delete(key);@@ -2902,9 +2951,9 @@ function startAutomationRun(task, event = null) {}}const id = 'run_' + Date.now().toString(36) + '_' + crypto.randomBytes(3).toString('hex');- const run = { id, taskId: task.id, status: 'running', startedAt: Date.now(), finishedAt: 0, error: '', logs: [], result: null, navigationSerial: event && event.navigationSerial };+ const run = { id, taskId: task.id, status: 'running', startedAt: Date.now(), finishedAt: 0, error: '', logs: [], result: null, navigationSerial: event && event.navigationSerial, pageSessionId: event && event.pageSessionId };const isCancelled = () => run.status === 'cancelled' || run.superseded === true ||- (task.trigger.restartOnNavigation && event && event.navigationSerial !== mainFrameNavigationSerial);+ (task.trigger.restartOnNavigation && event && (event.navigationSerial !== mainFrameNavigationSerial || event.pageSessionId !== cdpPageSessionId));log('[automation-focus-diagnostics] automation:start ' + JSON.stringify({ runId: id, taskId: task.id, source: event && event.source || '', account: event && event.account || null, cdpTargetUrl: cdp.targetUrl, cdpTargetTitle: cdp.targetTitle }));const appendRunLog = (message) => {run.logs.push({ at: Date.now(), message: String(message || '').slice(0, 300) });@@ -3045,7 +3094,7 @@ function startAutomationRun(task, event = null) {run.completion = panelPrepare.then(() => executeTask(task, runDeps)).then(async (result) => { if (isCancelled()) throw new Error('任务已停止'); if (run.wasPanelOpen) await automationPanelSetOpen(true); if (run.status === 'running') { run.status = 'success'; run.result = result; run.finishedAt = Date.now(); } log('[automation-focus-diagnostics] automation:finish ' + JSON.stringify({ runId: id, status: run.status, error: run.error })); })- .catch(async (error) => { if (run.wasPanelOpen && !run.superseded && (!task.trigger.restartOnNavigation || !event || event.navigationSerial === mainFrameNavigationSerial)) await automationPanelSetOpen(true); run.status = isCancelled() ? 'cancelled' : 'failed'; run.error = run.superseded ? '页面已切换,重新检测新页面' : String(error && error.message || error); run.finishedAt = Date.now(); appendRunLog(run.error); log('[automation-focus-diagnostics] automation:finish ' + JSON.stringify({ runId: id, status: run.status, error: run.error })); })+ .catch(async (error) => { if (run.wasPanelOpen && !run.superseded && (!task.trigger.restartOnNavigation || !event || event.navigationSerial === mainFrameNavigationSerial && event.pageSessionId === cdpPageSessionId)) await automationPanelSetOpen(true); run.status = isCancelled() ? 'cancelled' : 'failed'; run.error = run.superseded ? '页面已切换,重新检测新页面' : String(error && error.message || error); run.finishedAt = Date.now(); appendRunLog(run.error); log('[automation-focus-diagnostics] automation:finish ' + JSON.stringify({ runId: id, status: run.status, error: run.error })); }).finally(async () => { try { await runNotifier.cleanup(); } finally { releaseRenderer(); resumeAutomationAfterNavigation(run); } });return run;}@@ -3053,7 +3102,7 @@ function startAutomationRun(task, event = null) {function resumeAutomationAfterNavigation(run) {const next = run.pendingEvent;run.pendingEvent = null;- if (!next || next.navigationSerial !== mainFrameNavigationSerial) return;+ if (!next || next.navigationSerial !== mainFrameNavigationSerial || next.pageSessionId !== cdpPageSessionId) return;const task = readAutomations(DATA_DIR).find((item) => item.id === run.taskId && item.enabled && item.trigger.restartOnNavigation);if (task) startAutomationRun(task, next);}@@ -3363,6 +3412,7 @@ function buildInjectScript() {.replace(/__WBS_DIAGNOSTICS_ENABLED__/g, diagnosticsEnabled() ? 'true' : 'false').replace(/__WBS_PROFILE__/g, PROFILE.id).replace(/__WBS_CAPS__/g, JSON.stringify(PROFILE.capabilities))+ .replace(/__WBS_LOGO__/g, 'data:image/svg+xml;base64,' + fs.readFileSync(path.join(__dirname, 'assets', 'workdaddy-logo.svg')).toString('base64')).replace(/__WBS_PLATFORM__/g, JSON.stringify(process.platform));}@@ -4268,11 +4318,44 @@ function isManagedDirectoryNoFollow(wbHome, directory) {return true;}+// app/sessions.json 是共享窗口缓存,只移除所选会话的条目,不删除整个文件或 app 目录。+function removeSessionAppCache(wbHome, id) {+ const appDir = path.join(wbHome, 'app');+ if (!isManagedDirectoryNoFollow(wbHome, appDir)) return false;+ const file = resolveManagedSessionTarget(appDir, 'sessions.json');+ let stat;+ try { stat = fs.lstatSync(file); }+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error('会话缓存必须是普通文件');+ const original = fs.readFileSync(file, 'utf8');+ let data;+ try { data = JSON.parse(original); }+ catch (_) { throw new Error('会话缓存无法解析,请稍后重试'); }+ const entries = Array.isArray(data) ? data : data && data.sessions;+ if (!Array.isArray(entries)) throw new Error('会话缓存格式不受支持,未改写缓存');+ const kept = entries.filter((entry) => !entry || entry.conversationId !== id);+ if (kept.length === entries.length) return false;+ const next = Array.isArray(data) ? kept : Object.assign({}, data, { sessions: kept });+ const tempDir = fs.mkdtempSync(path.join(appDir, '.wbs-session-cache-'));+ try {+ const temp = path.join(tempDir, 'sessions.json');+ fs.writeFileSync(temp, JSON.stringify(next, null, 2) + '\n', { mode: stat.mode & 0o777, flag: 'wx' });+ // 官方进程若已改写缓存,保留最新文件和 DB 重试锚点,不能覆盖它的新内容。+ if (fs.lstatSync(file).isSymbolicLink() || fs.readFileSync(file, 'utf8') !== original) {+ throw new Error('会话缓存已变化,请重试删除');+ }+ fs.renameSync(temp, file);+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }+ return true;+}+// 真实删除会话的消息文件:projects/<项目>/<id>.jsonl + <id>/、workspace/sessions/<id>/、// tasks/<id>/、file-history/<id>/、artifact-index/<id>.json(全部按会话 id 精确删除,不可恢复)function deleteSessionFiles(wbHome, id) {if (!isValidSessionId(id)) throw new Error('无效的会话 ID');- let removed = 0;+ let removed = removeSessionAppCache(wbHome, id) ? 1 : 0;const delOne = (parent, leaf) => {let target;try {@@ -5601,8 +5684,9 @@ function loadThemePatches() {}}/** 主题附加样式:从 theme-patches.js 热加载,不硬编码在此 */-function themeExtrasCss() {- return loadThemePatches().map((p) => (p && p.css ? p.css : '')).join('');+function themeExtrasCss(id) {+ return loadThemePatches().filter((p) => p && (!p.themeId || p.themeId === id) &&+ (p.setting !== 'textShadow' || themeTextShadow.read())).map((p) => p.css || '').join('');}/** 主题变量别名层:从 theme-vars.js 热加载(官方漏定义/深色值不对的 token 重定向到主题变量)。@@ -5628,7 +5712,7 @@ function loadThemeVars() {}}/** 生成变量别名 CSS:isDark 时 darkOnly 条目加 html[data-theme="dark"] 前缀;浅色主题跳过 darkOnly 条目 */-function themeVarsCss(isDark) {+function themeVarsCss(isDark, id) {const mod = loadThemeVars();const pre = isDark ? 'html[data-theme="dark"] ' : '';let out = '';@@ -5640,6 +5724,7 @@ function themeVarsCss(isDark) {if (d) out += lead + 'body[data-vscode-theme-name]{' + d + '}';}for (const s of mod.scoped || []) {+ if (s.themeId && s.themeId !== id) continue;if (s.darkOnly && !isDark) continue;const lead = (s.darkOnly ? pre : '') + 'body[data-vscode-theme-name] ';const sels = String(s.sel).split(',').map((seg) => lead + seg.trim()).join(',');@@ -5678,7 +5763,7 @@ async function applyThemeByCdp(id) {}if (parts.length) localCssStr += 'body[data-vscode-theme-name] ' + loc.sel + '{' + parts.join('') + '}';}- const extrasCss = themeExtrasCss();+ const extrasCss = themeExtrasCss(id);const isDark = !!(theme && theme.dark);// 背景图:主题 JSON 带 image 字段时,从 themes/<id>/<image> 读取转 data URL(WBSS 方案:#root 背景 + 容器透明化)let bgCssStr = '';@@ -5757,6 +5842,7 @@ async function applyThemeByCdp(id) {// WorkDaddy 自定义主题已应用标记:theme-patches 里部分规则用 html[data-wbs-theme] 限定// 只在 WorkDaddy 内置自定义主题下生效(官方默认主题不激活)。try { h.setAttribute('data-wbs-theme', ${id === 'default' ? "'0'" : "'1'"}); } catch (e) {}+ try { h.setAttribute('data-wbs-theme-id', ${JSON.stringify(id)}); } catch (e) {}// 联动 WorkBuddy 原生主题(源码 theme.ts ThemeManager + legacy-appearance-mode-storage):// 1) 写 localStorage 'agent-ui-theme'(ThemeManager.saveTheme 同款结构),reload/重启后 WorkBuddy 自己恢复该主题;// 2) 写 'workbuddy.appearance.lastApplied'(getInitialTheme 优先读它,避免残留旧外观覆盖我们的配置);@@ -5821,7 +5907,7 @@ async function applyThemeByCdp(id) {// 注入自定义色板(body 层覆盖,同优先级后插入胜出)+ 变量别名层(官方漏定义 token 重定向)var css = 'body[data-vscode-theme-name]{' + ${JSON.stringify(allCssStr)} + '}' +${JSON.stringify(localCssStr)} +- ${JSON.stringify(themeVarsCss(isDark))} ++ ${JSON.stringify(themeVarsCss(isDark, id))} +${JSON.stringify(extrasCss)} + ${JSON.stringify(bgCssStr)};var st = s || document.createElement('style');st.id = 'wbs-theme-style';@@ -6531,6 +6617,30 @@ async function fetchCredits(accessToken, account) {};}+function rememberCreditRotation(uid, result) {+ const key = String(uid || '').trim();+ if (!key || !result || !Array.isArray(result.segments)) return;+ creditRotationCache.set(key, {+ uid: key,+ credits: result.credits,+ segments: result.segments,+ unlimited: !!result.unlimited,+ fetchedAt: Date.now(),+ });+}++function cachedCreditRotationAccounts() {+ const names = new Map(listAccounts(DATA_DIR).map((account) => [String(account.uid), account.nickname || '']));+ return Array.from(creditRotationCache.values()).map((entry) => ({+ uid: entry.uid,+ nickname: names.get(entry.uid) || '',+ creditSegments: entry.segments,+ credits: entry.credits,+ creditUnlimited: entry.unlimited,+ creditFetchedAt: entry.fetchedAt,+ }));+}+async function listDailyUsage(accounts, date = todayStr()) {const list = Array.isArray(accounts) ? accounts : [];if (!list.length) return {};@@ -7046,15 +7156,16 @@ function handleApi(req, res) {if (req.method === 'POST' && p === '/api/oauth/start') {return (async () => {try {+ const oauthPlatform = PROFILE.id === 'workbuddy-ai' ? 'workbuddy-ai' : 'workbuddy';const resp = await httpJson(- `${WB_API_ENDPOINT}${WB_API_PREFIX}/auth/state?platform=workbuddy`,+ `${WB_API_ENDPOINT}${WB_API_PREFIX}/auth/state?platform=${oauthPlatform}`,'POST',{});const d = (resp && resp.data) || {};if (!d.state) throw new Error('auth/state 响应缺少 state');const authUrl =- d.authUrl || d.auth_url || d.url || `${WB_API_ENDPOINT}/login?state=${d.state}`;+ d.authUrl || d.auth_url || d.url || `${WB_API_ENDPOINT}/login/started?platform=${oauthPlatform}&state=${encodeURIComponent(d.state)}`;const loginId = 'wd_' + crypto.randomUUID().replace(/-/g, '');oauthStates.set(loginId, {state: d.state,@@ -7135,6 +7246,14 @@ function handleApi(req, res) {return json(res, 200, status);}+ // The existing local API authorization gate requires the current profile token.+ // Renderer sends no input, account, session or device payload to this route.+ if (req.method === 'POST' && p === '/api/usage') {+ req.resume();+ usageReporter.report().catch(() => {});+ return json(res, 200, { ok: true });+ }+if (req.method === 'GET' && p === '/api/telemetry-settings') {return json(res, 200, {ok: true,@@ -7153,6 +7272,7 @@ function handleApi(req, res) {}try {const enabled = setTelemetryEnabled(body.enabled);+ if (!enabled) usageReporter.cancel();diagnosticsState = { value: enabled, checkedAt: Date.now() };return json(res, 200, { ok: true, enabled, managed: true });} catch (e) {@@ -7247,6 +7367,7 @@ function handleApi(req, res) {unlimited: !!r.unlimited,cycleResetTime: r.cycleResetTime || null,};+ rememberCreditRotation(uid, r);if (usage.synced) payload.todayUsage = usage.value;return json(res, 200, payload);} catch (e) {@@ -7258,6 +7379,102 @@ function handleApi(req, res) {});}+ // 会话完成后的轮换建议:只刷新当前账号,其他账号只使用最近一次已缓存的积分段。+ if (req.method === 'POST' && p === '/api/credit-rotation') {+ return readBody(req).then(async (body) => {+ const uid = String(body && body.uid || '').trim();+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return json(res, 400, { ok: false, error: 'uid 格式无效' });+ const current = currentAccount();+ if (!current || String(current.uid) !== uid) return json(res, 409, { ok: false, error: '当前账号已发生变化' });+ try {+ const file = accountBackupFile(uid);+ if (!fs.existsSync(file)) return json(res, 404, { ok: false, error: '账号备份不存在' });+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));+ const token = raw && raw.auth && (raw.auth.accessToken || raw.auth.access_token || raw.auth.token);+ if (!token) return json(res, 400, { ok: false, error: '备份中无 accessToken' });+ const previousCached = creditRotationCache.get(uid);+ const refreshed = await fetchCredits(token, raw.account || {});+ rememberCreditRotation(uid, refreshed);+ const candidate = selectRotationCandidate(cachedCreditRotationAccounts(), uid, Date.now());+ if (!candidate) return json(res, 200, { ok: true, shouldSuggest: false, current: { uid, segments: refreshed.segments } });+ return json(res, 200, {+ ok: true,+ shouldSuggest: true,+ current: { uid, segments: refreshed.segments },+ candidate: {+ uid: candidate.account.uid,+ nickname: candidate.account.nickname || '',+ remaining: candidate.segment.remaining,+ expiresAt: candidate.segment.expiresAt,+ },+ generatedAt: Date.now(),+ });+ } catch (e) {+ log(`[credit-rotation] 查询 ${uid} 失败: ${e.message}`);+ if (e && e.expired) return json(res, 401, { ok: false, expired: true, error: '登录身份过期' });+ return json(res, 500, { ok: false, error: e.message });+ }+ });+ }++ if (req.method === 'GET' && p === '/api/token-stats') {+ if (PROFILE.kind !== 'workbuddy') return json(res, 400, { ok: false, error: '当前客户端不支持 Token 统计' });+ if (url.searchParams.get('cacheStatus') === '1') return json(res, 200, { ok: true, cacheReady: tokenStatsCacheReady(PROFILE.dataRoot) });+ const days = Math.max(1, Math.min(90, Number(url.searchParams.get('days') || 7)));+ const accounts = listAccounts(DATA_DIR);+ return sqliteQuery('SELECT id, user_id FROM sessions WHERE deleted_at IS NULL;')+ .then((rows) => {+ const sessionAccounts = Object.fromEntries(rows.map((row) => [String(row.id || ''), String(row.user_id || '')]).filter((item) => item[0] && item[1]));+ const stats = scanTokenStatsCached(PROFILE.dataRoot, {+ days,+ account: url.searchParams.get('account') || '',+ model: url.searchParams.get('model') || '',+ accountOptions: accounts,+ sessionAccounts,+ });+ return json(res, 200, { ok: true, stats, accounts: accounts.map((a) => ({ uid: a.uid, nickname: a.nickname || '', phone: a.phone || '' })) });+ })+ .catch((e) => {+ log('[token-stats] 统计失败: ' + e.message);+ const status = /日期范围|开始日期/.test(String(e && e.message)) ? 400 : 500;+ return json(res, status, { ok: false, error: e.message || '读取会话统计失败' });+ });+ }++ if (req.method === 'GET' && p === '/api/credit-stats') {+ if (PROFILE.kind !== 'workbuddy') return json(res, 400, { ok: false, error: '当前客户端不支持积分历史查询' });+ try {+ const range = historyRange(url.searchParams.get('days') || 7);+ const accounts = listAccounts(DATA_DIR);+ const uid = url.searchParams.get('account') || '';+ const selected = uid ? accounts.filter(a => a.uid === uid) : accounts;+ if (uid && !selected.length) return json(res, 400, { ok: false, error: '账号选择无效' });+ creditHistorySync.start({ accounts: selected, days: range.days });+ return creditHistorySync.wait().then(result => json(res, 200, { ok: true, ...result,+ accounts: accounts.map(a => ({ uid: a.uid, nickname: a.nickname || '' })) }));+ } catch (error) { return json(res, error.status || 400, { ok: false, error: error.message }); }+ }+ if (req.method === 'GET' && p === '/api/credit-stats/sync') {+ return json(res, 200, { ok: true, job: creditHistorySync.status() });+ }+ if (req.method === 'POST' && p === '/api/credit-stats') {+ if (PROFILE.kind !== 'workbuddy') return json(res, 400, { ok: false, error: '当前客户端不支持积分历史查询' });+ return readBody(req).then((body) => {+ const range = historyRange(body && body.days !== undefined ? body.days : 7);+ const requested = body && body.uids;+ const accounts = listAccounts(DATA_DIR);+ if (requested !== undefined && (!Array.isArray(requested) || requested.some(uid =>+ typeof uid !== 'string' || !accounts.some(account => account.uid === uid)))) {+ return json(res, 400, { ok: false, error: '账号选择无效' });+ }+ const selected = requested === undefined ? accounts : accounts.filter(account => requested.includes(account.uid));+ if (!selected.length) return json(res, 400, { ok: false, error: '请先选择账号' });+ return json(res, 202, { ok: true, job: creditHistorySync.start({ accounts: selected, days: range.days }),+ accounts: accounts.map(a => ({ uid: a.uid, nickname: a.nickname || '' })) });+ }).catch(error => json(res, error.status || 400, { ok: false,+ error: error.status === 409 ? '另一个积分查询正在进行,请稍后重试' : '查询参数无效,请选择近 7、30 或 90 天' }));+ }+// Read-only per-account continuous activity count; never creates a conversation or changes accounts.if (req.method === 'POST' && p === '/api/growth/streak') {return readBody(req).then(async (body) => {@@ -7370,6 +7587,37 @@ function handleApi(req, res) {if (!text) throw new Error('未读取到有效内容,请选择导出文件');let envelope;try { envelope = JSON.parse(text); } catch (_) { throw new Error('文件不是有效的导出 JSON'); }+ const plainJson = body && body.format === 'plain-json';+ if (plainJson) {+ const candidates = Array.isArray(envelope) ? envelope : (Array.isArray(envelope.accounts) ? envelope.accounts : [envelope]);+ if (!candidates.length) throw new Error('JSON 中没有账号数据');+ ensureDirs(DATA_DIR);+ const imported = [];+ for (const candidate of candidates) {+ const j = candidate && typeof candidate === 'object' ? candidate : null;+ const acct = j && j.account && typeof j.account === 'object' ? j.account : j;+ const auth = j && j.auth && typeof j.auth === 'object' ? j.auth : null;+ const uid = String(acct && acct.uid || '').trim();+ const accessToken = String(auth && (auth.accessToken || auth.access_token || auth.token) || '').trim();+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid) || !accessToken) continue;+ const normalized = {+ account: { ...acct, uid },+ auth: { ...auth, accessToken },+ };+ const authRecord = parseAuthJson(normalized);+ if (!authRecord || authRecord.uid !== uid) continue;+ const dest = backupPath(DATA_DIR, uid);+ const tmp = dest + '.tmp';+ fs.writeFileSync(tmp, JSON.stringify(normalized), { mode: 0o600 });+ fs.renameSync(tmp, dest);+ try { fs.chmodSync(dest, 0o600); } catch (_) {}+ updateMeta(DATA_DIR, { uid, nickname: normalized.account.nickname || '', uin: normalized.account.uin || '', phone: normalized.account.phoneNumber || '' });+ imported.push(uid);+ }+ if (!imported.length) throw new Error('没有找到符合格式的账号,请先让 WorkBuddy 整理 JSON');+ log(`[import] 明文 JSON 导入 ${imported.length}/${candidates.length} 个账号`);+ return json(res, 200, { ok: true, imported, count: imported.length });+ }if (!envelope || envelope.wbsExport !== 'WorkDaddy') throw new Error('不是 WorkDaddy 的账号导出文件');const enteredPassword = body && typeof body.password === 'string' ? body.password : '';const password = enteredPassword.trim() ? enteredPassword : '';@@ -7394,6 +7642,8 @@ function handleApi(req, res) {try { j = JSON.parse(info); } catch (_) { continue; }const acct = j.account || (Array.isArray(j.accounts) && j.accounts[0]);if (!acct || !acct.uid || String(acct.uid) !== uid) continue; // 安全校验:uid 必须匹配+ const authRecord = parseAuthJson(j);+ if (!authRecord || authRecord.uid !== uid) continue;const dest = backupPath(DATA_DIR, uid);const tmp = dest + '.tmp';fs.writeFileSync(tmp, info, { mode: 0o600 });@@ -7552,6 +7802,27 @@ function handleApi(req, res) {});}+ // 毛玻璃消息文字阴影:默认开启,关闭后随主题重应用移除样式。+ if (req.method === 'GET' && p === '/api/theme-text-shadow') {+ return json(res, 200, { ok: true, enabled: themeTextShadow.read() });+ }+ if (req.method === 'POST' && p === '/api/theme-text-shadow') {+ return readBody(req).then(async (body) => {+ let enabled;+ try { enabled = themeTextShadow.save(body); }+ catch (e) { return json(res, e.code ? 500 : 400, { ok: false, error: e.message }); }+ try {+ const currentFile = path.join(DATA_DIR, 'current-theme.json');+ const cur = fs.existsSync(currentFile) ? JSON.parse(fs.readFileSync(currentFile, 'utf8')).id : 'default';+ if (cur !== 'nebula') return json(res, 200, { ok: true, enabled, applied: false });+ const info = await applyThemeByCdp(cur);+ return json(res, 200, { ok: true, enabled, applied: info.ok });+ } catch (e) {+ return json(res, 500, { ok: false, error: '文字阴影已保存但应用失败: ' + e.message });+ }+ });+ }+// 背景图毛玻璃模糊程度(0~1,默认 0):GET 读取、POST 保存并重应用当前主题。// 百分比到像素的映射只在主题应用时执行,避免把 CSS 实现细节暴露给前端。if (req.method === 'GET' && p === '/api/blur') {@@ -7727,6 +7998,25 @@ function handleApi(req, res) {}});}+ if (req.method === 'GET' && p === '/api/models/third-party') {+ try { return json(res, 200, { ok: true, sources: thirdPartyModels.discover() }); }+ catch (_) { return json(res, 400, { ok: false, error: '无法读取 CC Switch 本地配置位置' }); }+ }+ if (req.method === 'POST' && p === '/api/models/third-party/preview') {+ return readBody(req).then(async (body) => {+ if (!body || body.source !== 'cc-switch') return json(res, 400, { ok: false, error: '不支持的第三方来源' });+ try { return json(res, 200, { ok: true, ...await thirdPartyModels.preview() }); }+ catch (e) { return json(res, 400, { ok: false, error: e.message }); }+ });+ }+ if (req.method === 'POST' && p === '/api/models/third-party/import') {+ return readBody(req).then(async (body) => {+ try {+ const result = await thirdPartyModels.import(body);+ return json(res, 200, { ok: true, confirmationRequired: result.confirmationRequired, duplicateIds: result.duplicateIds, imported: result.imported, replaced: result.replaced, sameIdSkipped: result.sameIdSkipped });+ } catch (_) { return json(res, 400, { ok: false, error: '第三方模型导入失败,请重新读取列表并确认;原配置备份会保留在本地' }); }+ });+ }if (req.method === 'POST' && p === '/api/models/backup') {return readBody(req).then((body) => {try {@@ -8881,8 +9171,11 @@ log(`备份目录: ${DATA_DIR}`);updateDebug('daemon-start', { authFile: currentAuthFile(), dataDir: DATA_DIR, appPath: IS_WIN ? WORKDADDY_DIR_WIN : macWorkDaddyAppPath(), apiPort: UI_PORT_BASE });for (const preset of ['close-buddy-popups.json', ...(PROFILE.capabilities.accounts ? ['keep-accounts-active.json'] : [])]) {- try { installBuiltinTask(DATA_DIR, path.join(__dirname, 'builtin/automations', preset)); }- catch (_) { log('[automation] 初始化内置任务失败'); }+ try {+ const result = installBuiltinTask(DATA_DIR, path.join(__dirname, 'builtin/automations', preset));+ if (result && result.status === 'upgraded') log(`[automation] 内置任务已升级: ${preset} (revision ${result.revision})`);+ }+ catch (_) { log('[automation] 初始化内置任务失败: ' + preset); }}if (PROFILE.capabilities.accounts && PROFILE.capabilities.checkin !== false) {try { installBuiltinTask(DATA_DIR, path.join(__dirname, 'builtin/automations/daily-account-checkin.json')); }diff --git a/scripts/inject.js b/scripts/inject.jsindex 83df11c..7cc11ab 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -2,7 +2,7 @@* 右下角悬浮组件(注入到 WorkBuddy 渲染进程,由 daemon.js 通过 CDP 注入执行)** 功能:- * 1. 右下角圆形黑色悬浮按钮(hover 展开为胶囊显示"WorkDaddy")+ * 1. 右下角官网同款机器人按钮,支持拖动与自动停靠* 2. 点击按钮弹出账号面板(白色主题):面板右下角与按钮右下角重叠;面板打开时按钮隐藏,关闭后恢复* 3. 账号列表展示 昵称 / 手机(明文) / Token 过期时间(<7 天红字);不展示 uid/uin/上次登录* 4. 每账号右侧为「发起会话」「切换」「删除」纯图标按钮;发起会话使用备份 token,不切换当前账号@@ -13,6 +13,36 @@* 与后端通信:fetch 本地 daemon(__WBS_API__ 占位符在注入时替换为实际地址)* 幂等:window.__wbsWidget 防重复注入;document.body 未就绪时等待 DOMContentLoaded。*/+// Activity signals contain no key, text, target or pointer coordinates.+function createUsageActivity(options) {+ var doc = options.document, win = options.window;+ var alive = true, last = null, lastDay = '';+ function notify(event) {+ if (!alive || !options.enabled() || doc.visibilityState !== 'visible' || !doc.hasFocus()) return;+ if (event && event.isTrusted !== true) return;+ var time = options.now();+ var day = new Date(time + 8 * 3600000).toISOString().slice(0, 10);+ if (last !== null && lastDay === day && time - last < 3600000) return;+ last = time; lastDay = day;+ try { Promise.resolve(options.send()).catch(function () {}); } catch (_) {}+ }+ doc.addEventListener('pointerdown', notify, true);+ doc.addEventListener('keydown', notify, true);+ doc.addEventListener('visibilitychange', notify, true);+ win.addEventListener('focus', notify, true);+ notify();+ return {+ notify: notify,+ destroy: function () {+ alive = false;+ doc.removeEventListener('pointerdown', notify, true);+ doc.removeEventListener('keydown', notify, true);+ doc.removeEventListener('visibilitychange', notify, true);+ win.removeEventListener('focus', notify, true);+ },+ };+}+function createBuildLifecycle() {var active = true;var disposers = [];@@ -44,6 +74,51 @@ function createBuildLifecycle() {};}+// 单击与五连击共享一个等待窗口,避免打开官网打断调试手势。+function createBrandClickAction(options) {+ var count = 0, timer = null, alive = true;+ return {+ click: function () {+ if (!alive) return;+ count++;+ if (timer !== null) options.clearTimeout(timer);+ timer = options.setTimeout(function () {+ timer = null;+ var open = count > 0 && count < 5;+ count = 0;+ if (alive && open) options.openWebsite();+ }, 1200);+ if (count === 5) options.unlockDebug();+ },+ destroy: function () {+ alive = false;+ if (timer !== null) options.clearTimeout(timer);+ timer = null;+ count = 0;+ },+ };+}++function createFabAppearance(options) {+ var styles = ['white', 'black', 'glass'];+ var current = 'black';+ try {+ var saved = options.storage.getItem(options.key);+ if (styles.indexOf(saved) >= 0) current = saved;+ } catch (_) {}+ function apply() { options.fab.setAttribute('data-wbs-robot-style', current); }+ apply();+ return {+ get: function () { return current; },+ set: function (value) {+ if (styles.indexOf(value) < 0) return;+ current = value;+ try { options.storage.setItem(options.key, current); } catch (_) {}+ apply();+ },+ };+}+// 机器人闲置吸边:只监听指针位置,不拦截 WorkBuddy 事件;由 build lifecycle 清理。function createFabQuietMode(options) {var fab = options.fab;@@ -371,19 +446,43 @@ function stashContentMatches(expected, current) {return !!expected && !!current && stashContentSignature(expected) === stashContentSignature(current);}+/* ── 确认类弹窗的「允许」文案表(唯一事实来源,扫描与测试共用)──+ *+ * 精确匹配,不做模糊包含:泛化的「确认」「确定」永远不得命中(扣费/提权弹窗只有这类按钮)。+ *+ * 收录范围(按官方源码/文案核对):+ * · sandbox.interceptAllowOnce 「允许」 沙箱越权拦截卡(含 .sensitive 变体)+ * · sensitiveProtection.allowAccess 「允许访问」 敏感凭证拦截卡 ingress 的 allow_once+ * · sensitiveProtection.allowEncryptedAccess 「允许加密访问(推荐)」 ingress-protectable / protect-only 选项+ * · sensitiveProtection.allowAndProtect 「允许,并加密保护」+ *+ * 故意不收录(自动放行会造成真实损失或提权,必须留人工把关):+ * · sensitiveProtection.allowSend 「允许发送」 凭证外发(egress)→ 自动点等于静默外泄;+ * · 批量删除的「允许本次删除」 交给「大批量删除免确认」开关单独控制;+ * · 「确认开启」 开启「允许完全访问」的授权确认,属提权,必须人来点;+ * · teamMember 的「本次允许」 其他成员请求执行工具,不是本机自动化的目标。+ */+var ND_ALLOW_ONCE_LABELS = /^(允许|允许一次|允许访问|允许,并加密保护|允许加密访问(推荐)|允许加密访问|Allow|Allow once|Allow access|Allow and encrypt|Allow encrypted access( \(Recommended\))?|Yes|同意|批准|确认允许)$/i;+var ND_ALLOW_SESSION_LABELS = /始终允许|Always\s*allow/i;+// 决策组按钮数量上限,也是「还在卡片内」的判据:超过即视为已上溯到会话/页面容器,停止。+var ND_MAX_DECISION_BUTTONS = 12;+var ND_DENY_HINTS = /拒绝|禁止|取消删除|Deny/i;+var ND_CREDIT_HINTS = /积分|信用|credit|消耗|付费|支付|费用|金额|余额|扣费/i;+var ND_CONFIRM_HINTS = /批量删除|沙箱|越界|越权|系统级工具|系统工具|权限|允许访问|允许加密访问|将运行|需要你确认|需要你的确认|确认允许|检测到|受保护|敏感|凭据|凭证|黑名单|sandbox|approval|permission/i;+// Pure approval-label/context gate shared by the renderer fallback and tests.// Keep this deliberately narrow: a generic "确认" button must never qualify.function classifyNoDisturbApprovalCandidate(input) {var value = input || {};var label = String(value.label || '').trim().replace(/^\d+\s*/, '');var kind = null;- if (/始终允许|Always\s*allow/i.test(label)) kind = 'session';- else if (/^(允许|允许一次|Allow|Yes|同意|批准|确认允许)$/i.test(label) || (/^Yes/i.test(label) && label.length < 24)) kind = 'once';+ if (ND_ALLOW_SESSION_LABELS.test(label)) kind = 'session';+ else if (ND_ALLOW_ONCE_LABELS.test(label) || (/^Yes/i.test(label) && label.length < 24)) kind = 'once';if (!kind || value.disabled || value.ariaDisabled) return null;var context = String(value.context || '').slice(0, 700);- if (value.creditSeen || /积分|信用|credit|消耗|付费|支付|费用|金额|余额|扣费/i.test(context)) return null;- var keywordHit = /批量删除|沙箱|越界|越权|系统级工具|系统工具|权限|允许访问|将运行|需要你确认|需要你的确认|确认允许|检测到|受保护|敏感|凭据|黑名单|sandbox|approval|permission/i.test(context);- var structuredHit = value.hasDeny === true && value.hasOnce === true && Number(value.buttonCount || 0) >= 2 && Number(value.buttonCount || 0) <= 12;+ if (value.creditSeen || ND_CREDIT_HINTS.test(context)) return null;+ var keywordHit = ND_CONFIRM_HINTS.test(context);+ var structuredHit = value.hasDeny === true && value.hasOnce === true && Number(value.buttonCount || 0) >= 2 && Number(value.buttonCount || 0) <= ND_MAX_DECISION_BUTTONS;return keywordHit || structuredHit ? kind : null;}@@ -554,7 +653,10 @@ function createSessionMonitorRegistry(options) {if (typeof module !== 'undefined' && module.exports) {module.exports = {+ createUsageActivity: createUsageActivity,createBuildLifecycle: createBuildLifecycle,+ createBrandClickAction: createBrandClickAction,+ createFabAppearance: createFabAppearance,classifySessionHealth: classifySessionHealth,classifyAutoContinueReply: classifyAutoContinueReply,classifyAutoContinueControllerSnapshot: classifyAutoContinueControllerSnapshot,@@ -569,6 +671,10 @@ if (typeof module !== 'undefined' && module.exports) {stashContentSignature: stashContentSignature,stashContentMatches: stashContentMatches,classifyNoDisturbApprovalCandidate: classifyNoDisturbApprovalCandidate,+ ndAllowOnceLabels: ND_ALLOW_ONCE_LABELS,+ ndAllowSessionLabels: ND_ALLOW_SESSION_LABELS,+ ndConfirmHints: ND_CONFIRM_HINTS,+ ndDenyHints: ND_DENY_HINTS,isSessionMonitorInProgress: isSessionMonitorInProgress,normalizeSessionMonitorResourceRecord: normalizeSessionMonitorResourceRecord,sessionMonitorLifecycleAction: sessionMonitorLifecycleAction,@@ -584,6 +690,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {(function () {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-selection-quote-btn');for (var i = 0; i < st.length; i++) st[i].remove();var nav = document.querySelectorAll('.wbs-message-nav-root');@@ -615,6 +722,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var WBS_API_TOKEN = '__WBS_API_TOKEN__';var WBS_DIAGNOSTICS_ENABLED = __WBS_DIAGNOSTICS_ENABLED__;var WBS_PLATFORM = __WBS_PLATFORM__; // 注入时替换为 JSON 字符串(如 "darwin"/"win32")+ var WBS_LOGO = '__WBS_LOGO__';var WBS_COMPAT = window.__wbsWorkBuddyCompat;if (!WBS_COMPAT) throw new Error('WorkBuddy 兼容层未加载');// WorkBuddy 基于 Electron,持续会话模块在 macOS/Windows 使用同一套 CDP 逻辑。@@ -628,6 +736,62 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var WBS_LANGUAGE_KEY = 'workdaddy.ui.language';var WBS_ACCOUNT_MASK_KEY = 'workdaddy.account.mask.' + PROFILE_ID;var WBS_I18N_EN = {+ '查询失败,请重新选择时间或账号重试': 'Query failed. Select a time range or account to retry.',+ '查询已中断,请重新选择时间或账号重试': 'Query interrupted. Select a time range or account to retry.',+ '无法读取查询进度,请重新选择时间或账号重试': 'Could not read progress. Select a time range or account to retry.',+ '积分(部分日期加载中)': 'credits (some dates are loading)',+ '日期数据加载中': 'Loading date records',++ '直接查询官方积分用量': 'Live credit usage from the official service',+ '重新查询最新积分用量': 'Refresh credit usage from the official service',+ '正在查询积分用量…': 'Querying credit usage…',+ '积分查询进度': 'Credit query progress',+ '积分消耗': 'Credits used',+ '积分(部分账号查询失败)': 'credits (some accounts failed)',+ '查询失败,暂无数据': 'Query failed; no data',+ '查询失败,请点击刷新重试': 'Query failed. Click Refresh to retry.',+ '已查询': 'Queried ',+ '查询成功': 'Query succeeded for ',+ ' 个账号;结果不完整。': ' accounts; results are incomplete.',+ '查询时间:': 'Queried at: ',+ '查询已中断,请点击刷新重试': 'Query interrupted. Click Refresh to retry.',+ '无法读取查询进度,请点击刷新重试': 'Could not read query progress. Click Refresh to retry.',+ '另一个积分查询正在进行,请稍后重试': 'Another credit query is running. Please retry shortly.',+ '记录未完整获取,请稍后重试': 'Could not retrieve all records. Please retry later.',+ '* 表示部分账号查询失败;— 表示查询失败,暂无数据。': '* Some accounts failed; — query failed, no data.',+ '查询参数无效,请选择近 7、30 或 90 天': 'Invalid range. Select the last 7, 30 or 90 days.',++ '用量统计': 'Usage statistics',+ '更新历史积分记录': 'Update credit history',+ '正在更新历史积分记录': 'Updating credit history',+ '先显示已保存的记录;更新历史可补齐其他设备的使用记录。账号和记录越多,等待越久,可能需要数分钟。': 'Saved records appear first. Update history to include usage from other devices. More accounts and records take longer; this may take several minutes.',+ '账号和记录越多,等待越久,可能需要数分钟。关闭窗口后仍会在后台继续。': 'More accounts and records take longer; this may take several minutes. Updating continues in the background if you close this window.',+ '正在连接…': 'Connecting…',+ '后台继续': 'Continue in background',+ '更新范围:近': 'Update range: last ',+ '已记录积分消耗': 'Recorded credits used',+ '筛选账号数': 'Selected accounts',+ '积分(记录待补齐)': 'credits (incomplete history)',+ '尚无记录,请更新历史': 'No records yet; update history',+ '* 表示部分账号查询失败;— 表示查询失败,暂无数据。': '* Incomplete history; — no records, which does not mean zero usage. Today reflects the last update.',+ '账号用量': 'Usage by account',+ '没有匹配的账号': 'No matching accounts',+ '读取失败,请切换时间范围后重试': 'Could not load records. Change the date range to retry.',+ '已处理': 'Processed ',+ ' · 第': ' · Page ',+ ' 页 · 已读取': ' · Read ',+ ' 条记录': ' records',+ '更新完成:成功': 'Update complete: succeeded ',+ ' 个,可重试。': ' accounts; you can retry.',+ '进度连接暂时中断,正在重试…': 'Progress connection interrupted. Reconnecting…',+ '更新请求未确认,正在检查后台进度…': 'Update request unconfirmed. Checking background progress…',+ '搜索账号名称或 ID': 'Search account name or ID',+ '积分记录更新进度': 'Credit history update progress',+ '登录身份过期或不可用,请重新登录后重试': 'Login expired or unavailable. Sign in again to retry.',+ '请求超时,请稍后重试': 'Request timed out. Try again later.',+ '记录未完整获取或保存,请稍后重试': 'Could not retrieve or save complete records. Try again later.',+ '后台更新已中断,请重新更新历史记录。': 'Background update interrupted. Please update history again.',+'等待发送按钮可点击超时(5 秒),未发送': 'The send button was not ready within 5 seconds. Nothing was sent.','无法关闭面板,请重试': 'Could not close the panel. Please try again.','正在输入或切换账号,请稍后打开面板': 'Typing or switching accounts. Please open the panel in a moment.',@@ -636,6 +800,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {"依次切换所有账号,等待当前会话输入框出现后发送 1+1=,等待回复完成,最后恢复开始时的账号。": "Switch through all accounts, wait for the composer, send 1+1=, wait for each reply to finish, then restore the starting account.","页面就绪后自动关闭首页弹窗": "Close home popups when the page is ready","页面就绪后立即检查三类弹窗,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。": "Check for three types of home popups every 300 ms for about 30 seconds. Close any that reappear and restart detection after account switches.",+ "页面就绪后立即检查首页弹窗与运营位,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。": "Check home popups and promotional slots every 300 ms for about 30 seconds. Close any that reappear and restart detection after account switches.","循环账号静默签到": "Check in all accounts in the background","使用各账号 token 签到,不切换当前账号;跳过今日已签到账号。每小时、客户端加载和打开面板时检查。": "Check in with each account without switching the active account. Skip accounts already checked in today. Check hourly, on client load, and when the panel opens.","所有账号已按序处理完毕,已恢复开始时的账号": "All accounts have been processed. The starting account has been restored.",@@ -643,11 +808,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {"该账号签到未成功,请检查登录状态或签到活动": "Check-in failed for this account. Check its login status and check-in availability.","识别到 Buddy 加油站弹窗,已关闭": "Buddy Fuel Station popup detected and closed.","已关闭相关玩法推荐,今日不再展示": "Related playbook recommendations dismissed for today.",+ "已关闭「做任务赢积分好礼」入口": "Tasks-for-credits promotion closed.","已关闭首页活动弹窗": "Home activity popup closed.",+ "Token 用量仅统计本机记录,在不同电脑上查看的数据可能不一致。": "Token usage only includes records on this computer. Figures may differ between computers.","会话输入框非空,未覆盖草稿、未发送": "The composer contains a draft. Nothing was overwritten or sent.",'页面就绪': 'Page ready', '删除选中的': 'Delete selected', '删除该自动化任务?': 'Delete this automation task?', '删除选中的自动化任务?': 'Delete selected automation tasks?', '删除后无法恢复。': 'This cannot be undone.', '清除': 'Clear', '清除日志': 'Clear logs', '清除运行日志?': 'Clear run logs?', '仅清除已结束的运行记录。': 'Only completed run records will be cleared.', '清除日志失败': 'Failed to clear logs', '任务已启用': 'Task enabled', '任务已停用': 'Task disabled', '发送中': 'Sending','账号': 'Accounts', '主题': 'Theme', '会话': 'Sessions', '模型': 'Models', '增强': 'Enhance', '自动化': 'Automation', '电脑': 'Computer', '关于': 'About', '设置': 'Settings',- '导出': 'Export', '导入': 'Import', '删除': 'Delete', '编辑': 'Edit', '保存': 'Save', '取消': 'Cancel', '确定': 'Confirm', '确认': 'Confirm', '复制': 'Copy', '切换': 'Switch', '启用': 'Enable', '停用': 'Disable', '停止': 'Stop', '立即运行': 'Run now', '新建任务': 'New task', '刷新': 'Refresh', '步骤 JSON': 'Steps JSON', '任务说明': 'Task description', '任务名称': 'Task name', '调度': 'Schedule', '手动运行': 'Manual', '手动': 'Manual', '每小时': 'Hourly', '每天': 'Daily', '选择任务': 'Select tasks', '查看接口': 'View capabilities', '拾取元素': 'Pick element', '复制 XPath': 'Copy XPath', '运行中': 'Running', '已成功': 'Succeeded', '失败': 'Failed', '未运行': 'Not run', '页面加载完成': 'Page loaded', '账号切换完成': 'Account switched', '新自动化任务': 'New automation task', '任务已保存': 'Task saved', '任务已开始运行': 'Task started', '步骤 JSON 格式无效': 'Invalid steps JSON', '步骤 JSON 必须是数组': 'Steps JSON must be an array', '查看接口说明': 'View interface docs', '自动化接口协议': 'Automation interface protocol', '复制全部': 'Copy all', '接口协议已复制': 'Interface protocol copied', '暂无自动化任务,点击“新建任务”开始。': 'No automation tasks yet. Click “New task” to start.', '编辑任务': 'Edit task', '触发方式': 'Trigger', '插入点击步骤': 'Insert click step', 'XPath 已复制': 'XPath copied', '点击步骤已插入': 'Click step inserted', '请先拾取元素': 'Pick an element first', '加载自动化失败': 'Failed to load automations', '读取接口失败': 'Failed to read interfaces', '批量操作失败': 'Batch operation failed', '删除失败': 'Delete failed', '确认删除该任务?': 'Delete this task?', '执行': 'Apply', '已拾取': 'Picked', '运行失败': 'Run failed', '(副本)': ' (copy)', '查看提示词': 'View prompt', '交给 WorkBuddy 创建': 'Ask WorkBuddy to create', '正在打开新任务…': 'Opening a new task…', '已创建新会话,WorkBuddy 完成后任务会自动出现': 'New session created. The task will appear after WorkBuddy finishes.', 'WorkBuddy 创建失败': 'WorkBuddy creation failed', '加载示例失败': 'Failed to load examples', '暂无示例': 'No examples available', '运行日志': 'Run logs', '暂无运行日志': 'No run logs yet', '开始时间': 'Started', '结束时间': 'Finished', '捕获错误': 'Caught error', '暂无执行日志': 'No execution log entries', '执行日志': 'Execution log', '尚未结束': 'Still running',+ '导出': 'Export', '导入': 'Import', '删除': 'Delete', '编辑': 'Edit', '保存': 'Save', '内置': 'Built-in', '取消': 'Cancel', '确定': 'Confirm', '确认': 'Confirm', '复制': 'Copy', '切换': 'Switch', '启用': 'Enable', '停用': 'Disable', '停止': 'Stop', '立即运行': 'Run now', '新建任务': 'New task', '刷新': 'Refresh', '步骤 JSON': 'Steps JSON', '任务说明': 'Task description', '任务名称': 'Task name', '调度': 'Schedule', '手动运行': 'Manual', '手动': 'Manual', '每小时': 'Hourly', '每天': 'Daily', '选择任务': 'Select tasks', '查看接口': 'View capabilities', '拾取元素': 'Pick element', '复制 XPath': 'Copy XPath', '运行中': 'Running', '已成功': 'Succeeded', '失败': 'Failed', '未运行': 'Not run', '页面加载完成': 'Page loaded', '账号切换完成': 'Account switched', '新自动化任务': 'New automation task', '任务已保存': 'Task saved', '任务已开始运行': 'Task started', '步骤 JSON 格式无效': 'Invalid steps JSON', '步骤 JSON 必须是数组': 'Steps JSON must be an array', '查看接口说明': 'View interface docs', '自动化接口协议': 'Automation interface protocol', '复制全部': 'Copy all', '接口协议已复制': 'Interface protocol copied', '暂无自动化任务,点击“新建任务”开始。': 'No automation tasks yet. Click “New task” to start.', '编辑任务': 'Edit task', '触发方式': 'Trigger', '插入点击步骤': 'Insert click step', 'XPath 已复制': 'XPath copied', '点击步骤已插入': 'Click step inserted', '请先拾取元素': 'Pick an element first', '加载自动化失败': 'Failed to load automations', '读取接口失败': 'Failed to read interfaces', '批量操作失败': 'Batch operation failed', '删除失败': 'Delete failed', '确认删除该任务?': 'Delete this task?', '执行': 'Apply', '已拾取': 'Picked', '运行失败': 'Run failed', '(副本)': ' (copy)', '查看提示词': 'View prompt', '交给 WorkBuddy 创建': 'Ask WorkBuddy to create', '正在打开新任务…': 'Opening a new task…', '已创建新会话,WorkBuddy 完成后任务会自动出现': 'New session created. The task will appear after WorkBuddy finishes.', 'WorkBuddy 创建失败': 'WorkBuddy creation failed', '加载示例失败': 'Failed to load examples', '暂无示例': 'No examples available', '运行日志': 'Run logs', '暂无运行日志': 'No run logs yet', '开始时间': 'Started', '结束时间': 'Finished', '捕获错误': 'Caught error', '暂无执行日志': 'No execution log entries', '执行日志': 'Execution log', '尚未结束': 'Still running','暂存提示词': 'Stash prompt', '暂存': 'Stashed', '引用文本': 'Quote text', '快捷短语': 'Quick phrases', '点击后发送': 'Send on click', '编辑 →': 'Edit →', '新增': 'Add', '批量操作': 'Batch actions', '批量管理': 'Batch manage', '全选': 'Select all', '取消全选': 'Deselect all', '已选 0': 'Selected 0','账号汇总': 'Account summary', '账号数': 'Accounts', '总积分': 'Total credits', '手机': 'Phone', '有效期至': 'Expires', '当前使用中': 'Currently active', '隐藏敏感信息': 'Mask sensitive info', '显示明文': 'Show plaintext', '登录新账号': 'Log in a new account', '没有可导出的账号备份': 'No account backups to export', '还没有备份账号。打开/登录一次 WorkBuddy 后会自动备份,稍后再来查看。': 'No account backups yet. Open or log in to WorkBuddy once and check again later.','语言': 'Language', '中文': 'Chinese', '英语': 'English', 'English': 'English', '跟随系统': 'Follow system', '设置语言': 'Language', '首次打开时自动跟随系统语言;未匹配时使用英语。': 'The first launch follows your system language. English is used when no match is found.', '语言设置已更新': 'Language updated',@@ -694,14 +861,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'发现新版本': 'New version available', '立即更新': 'Update now', '有新版本可用,点击更新。': 'A new version is available. Click Update.', '下载中…': 'Downloading…', '正在打开…': 'Opening…', '安装程序已打开': 'Installer opened', '打开安装程序': 'Open installer', '安装中…': 'Installing…', '重启中…': 'Restarting…', '已完成': 'Completed', '重试更新': 'Retry update','安全传输': 'Secure transfer', '选择内容': 'Select content', '选择账号': 'Select accounts', '选择目标账号': 'Select target account', '选择目标账号…': 'Select a target account…', '密码': 'Password', '请输入密码': 'Enter password', '密码不能为空': 'Password cannot be empty', '请至少选择一项': 'Select at least one item', '处理中…': 'Processing…', '新版文件请输入密码': 'Enter the password for the new file', '新版文件必须输入密码;旧版导出文件可留空。': 'New files require a password; older exports may be left blank.', '新版文件请输入密码;已有的相同短语会自动跳过。': 'Enter the password for the new file; duplicate phrases are skipped.','电脑休眠': 'Computer sleep', '允许电脑休眠': 'Allow computer sleep', '持续禁止休眠': 'Keep awake', '所有会话结束允许休眠': 'Allow sleep when all sessions end', '系统默认,空闲后正常休眠': 'System default; sleep normally when idle', '保持唤醒,防黑屏锁屏': 'Stay awake to prevent screen lock', '任一会话运行中都保持唤醒': 'Stay awake while any session is running', '允许显示器休眠': 'Allow display sleep', '禁止休眠时,是否允许显示器单独黑屏': 'When sleep is blocked, allow the display to turn off',- '发送错误诊断': 'Send error diagnostics', '推荐开启': 'Recommended', '由环境变量控制': 'Controlled by environment variable', '默认开启 · 设置读取失败': 'Enabled by default · failed to read setting', '保存中…': 'Saving…', '仅发送经过脱敏、截断的版本、系统和错误信息,不包含账号、会话内容、Token 或 API Key;可随时关闭。': 'Only redacted and truncated version, system, and error details are sent. Accounts, sessions, tokens, and API keys are excluded; you can turn this off anytime.', '查看错误诊断说明': 'View diagnostics details', '问题反馈': 'Report an issue', '会话监听日志': 'Session monitor log', '仅保存在当前页面内存': 'Stored only in this page memory',+ '发送错误诊断': 'Send error diagnostics', '推荐开启': 'Recommended', '由环境变量控制': 'Controlled by environment variable', '默认开启 · 设置读取失败': 'Enabled by default · failed to read setting', '保存中…': 'Saving…', '发送脱敏错误诊断,并统计匿名安装数和日活(随机安装标识、系统、架构、版本、客户端类型及出口国家)。不包含账号、会话内容、Token 或 API Key;关闭后停止上报。': 'Sends redacted error diagnostics and anonymous installation and daily active counts (random installation ID, system, architecture, version, client type, and network country). No accounts, session content, tokens, or API keys. Turning this off stops reporting.', '查看错误诊断说明': 'View diagnostics details', '问题反馈': 'Report an issue', '会话监听日志': 'Session monitor log', '仅保存在当前页面内存': 'Stored only in this page memory','权限免打扰': 'Permission quiet mode', '异常中断会话': 'Continue interrupted sessions', '决策弹窗': 'Decision prompts', '用弹窗提问': 'Ask with a dialog', '确认弹窗自动允许': 'Auto-allow confirmation dialogs', '自动复制所有会话': 'Auto-copy all sessions', '会话消息索引': 'Message index', '引用消息文本': 'Quote message text', '选择登录方式': 'Choose a login method', '假退出': 'Soft logout', '无感登录': 'Seamless login','未设置': 'Not set', '当前使用中': 'Currently active', '停止生成': 'Stop generating', '正常重启': 'Restart normally', '清空日志': 'Clear log', '开发者工具': 'Developer tools', '隐藏功能': 'Hidden feature', '卡死': 'Stuck', '任务': 'Task', '空间': 'Workspace', '全部': 'All', '今天': 'Today', '近 7 天': 'Last 7 days', '近 30 天': 'Last 30 days', '企业配额': 'Enterprise quota', '积分到期分布': 'Credit expiry distribution','连接新服务…': 'Connecting to service…', '等待中': 'Waiting', '运行中': 'Running', '空闲': 'Idle', '已中断': 'Interrupted', '已停止': 'Stopped', '未确认': 'Unconfirmed', '等待确认': 'Waiting for confirmation', '等待新回复': 'Waiting for a new reply', '等待会话': 'Waiting for session', '等待允许': 'Waiting for approval', '整理中': 'Organizing', '恢复中': 'Restoring', '即将完成…': 'Finishing…', '已继续': 'Continued', '检测到会话异常中断,即将自动发送「': 'An interrupted session was detected. Sending “', '自动发送失败,请手动点击发送': 'Automatic send failed. Please click Send manually', '底层发送失败,请手动发送': 'Underlying send failed. Please send manually','导入中…': 'Importing…', ' 个任务': ' task(s)', '导入任务': 'Import tasks', '导出任务': 'Export tasks', '请先勾选要导出的任务': 'Select tasks to export first', '选择 JSON 或 ZIP 任务文件': 'Choose a JSON or ZIP task file', '读取任务文件…': 'Reading task file…', '任务导出成功': 'Tasks exported', '导入失败': 'Import failed', '导出失败': 'Export failed', '可导入': 'Ready to import', '已存在,将跳过': 'Already exists; skipped', '不兼容,无法导入': 'Incompatible; cannot import', '导入后保持停用,可在任务列表中启用。相同 ID 的任务会跳过。': 'Imported tasks stay disabled until you enable them. Existing task IDs are skipped.', '任务文件不能超过 8 MiB': 'Task files must not exceed 8 MiB', '缺少必填参数': 'Required inputs are missing', '需要更新 WorkDaddy': 'Requires a newer WorkDaddy version', '不支持当前客户端或系统': 'Unsupported client or platform', '文件不是自动化任务 JSON': 'Not an automation task JSON file', '任务格式或能力不受支持': 'Unsupported task format or capabilities','导出账号': 'Export accounts', '导入账号': 'Import accounts', '导出会话': 'Export sessions', '导入会话': 'Import sessions', '导出快捷短语': 'Export quick phrases', '导入快捷短语': 'Import quick phrases', '复制选中到其他账号': 'Copy selected to another account', '删除选中': 'Delete selected', '操作会话': 'Session actions', '连通测试': 'Test connection', '编辑模型': 'Edit model', '模型已保存': 'Model saved', '模型已启用': 'Model enabled', '模型已复制': 'Model copied', '模型配置已共用': 'Model configuration shared', '当前模型': 'Current model', '备选模型': 'Backup models', '模型加载失败:': 'Failed to load models: ', '保存模型失败:': 'Failed to save model: ', '删除当前模型失败:': 'Failed to delete current model: ', '启用模型失败:': 'Failed to enable model: ', '连通测试失败:': 'Connection test failed: ','选择要查看的账号': 'Choose an account to view', '选择账号并输入密码后导出备份': 'Choose accounts and enter a password to export backups', '从加密导出文件导入账号备份': 'Import account backups from an encrypted export', '使用密码导出选中会话': 'Export selected sessions with a password', '使用密码导出选中快捷短语': 'Export selected quick phrases with a password', '从加密文件导入会话': 'Import sessions from an encrypted file', '从加密文件导入快捷短语': 'Import quick phrases from an encrypted file', '仅支持 PNG / JPG / WebP': 'PNG / JPG / WebP only', '点击或拖拽上传壁纸': 'Click or drag to upload a wallpaper', '点击选择图片,或拖拽到此处': 'Click to choose an image, or drag it here', '支持 PNG / JPG / WebP,自动压缩;可添加多张': 'PNG / JPG / WebP supported; images are compressed automatically',- '未命名账号': 'Unnamed account', '未命名模型': 'Unnamed model', '未命名': 'Unnamed', '未知错误': 'Unknown error', '未知': 'Unknown', '有效期未知': 'Expiry unknown', '未找到输入框': 'Composer not found', '输入框内容为空': 'Composer is empty', '当前输入框暂不支持引用插入': 'The current composer does not support quote insertion', '引用插入失败,请重试': 'Could not insert quote. Please try again', '已引用选中文字': 'Selected text quoted', '短语不能为空': 'Quick phrase cannot be empty', '请输入快捷短语': 'Enter a quick phrase', '删除快捷短语': 'Delete quick phrase', '编辑快捷短语': 'Edit quick phrase', '新增快捷短语': 'Add quick phrase', '确定删除': 'Confirm deletion', '确认永久删除': 'Confirm permanent deletion',+ '未命名账号': 'Unnamed account', '未命名模型': 'Unnamed model', '未命名': 'Unnamed', '未知错误': 'Unknown error', '未知': 'Unknown', '有效期未知': 'Expiry unknown', '未找到输入框': 'Composer not found', '输入框内容为空': 'Composer is empty', '当前输入框暂不支持引用插入': 'The current composer does not support quote insertion', '引用插入失败,请重试': 'Could not insert quote. Please try again', '短语不能为空': 'Quick phrase cannot be empty', '请输入快捷短语': 'Enter a quick phrase', '删除快捷短语': 'Delete quick phrase', '编辑快捷短语': 'Edit quick phrase', '新增快捷短语': 'Add quick phrase', '确定删除': 'Confirm deletion', '确认永久删除': 'Confirm permanent deletion','本机回环 CDP 注入 · 不改官方安装包': 'Local CDP injection · official app untouched', '一个基于 ': 'A ', ' 的 WorkBuddy 桌面端增强工具。零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。': ' WorkBuddy desktop enhancement tool using Chrome DevTools Protocol (CDP). No intrusion or re-signing; UI components are injected into the running renderer.', '问题反馈': 'Report an issue',// —— 覆盖度补齐(分区域,模板条目支持 {name} 占位,匹配时最长优先)——'(无标题)': 'Untitled', 'GitHub 仓库': 'GitHub repository', '去 GitHub Issues 反馈问题': 'Report an issue on GitHub', '在 GitHub 上给 WorkDaddy 点 Star': 'Star WorkDaddy on GitHub', 'WorkDaddy,点击打开面板,可拖动': 'WorkDaddy – click to open the panel, draggable', '如果 WorkDaddy 对你有帮助,欢迎在 GitHub 点个 Star。你的支持会让这个小项目持续更新。': 'If WorkDaddy helps you, please star it on GitHub. Your support keeps this small project alive.',@@ -723,6 +890,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// —— 模板条目({name}/{n} 占位,最长优先整句替换,杜绝中英混合)——'已切换为「{name}」,开始领取积分…': 'Switched to “{name}”, claiming credits…', '已切换为「{name}」,正在复制已标记会话…': 'Switched to “{name}”, copying marked sessions…', '已登录「{name}」': 'Logged in as “{name}”', '已发送「{text}」': 'Sent “{text}”', '「{name}」的备份': 'Backup of “{name}”', '「{name}」的本地备份,不可恢复': 'Local backup of “{name}”, cannot be restored', '「{name}」,请刷新 WorkBuddy 窗口': '“{name}”, please refresh the WorkBuddy window', '「{name}」,重启后生效': '“{name}”, effective after restart', '定位到第{n}条用户消息': 'Jump to user message {n}', '已关闭:{reason}': 'Disabled: {reason}', '已开启:{reason}': 'Enabled: {reason}', '已删除 {n} 项': 'Deleted {n} item(s)', '已复制 {n} 项': 'Copied {n} item(s)', '检测到会话异常中断,即将自动发送「{text}」': 'An interrupted session was detected. Sending “{text}”', '输入框非空,已放弃会话 {id} 的自动继续': 'Composer is not empty; skipped auto-continue for session {id}',// —— 第二批补齐(inject 剩余 + daemon 端会进入 UI/API 的文案)——+ '没有找到符合格式的账号,请先让 WorkBuddy 整理 JSON': 'No compatible accounts found. Ask WorkBuddy to format the JSON first.','免打扰': 'Quiet mode', 'WorkBuddy 即将退出并重新打开到登录页': 'WorkBuddy will exit and reopen to the login page', 'WorkBuddy 队列尚未准备完成': 'WorkBuddy queue is not ready yet', 'WorkBuddy 队列排序接口不可用': 'WorkBuddy queue sort API unavailable', 'WorkBuddy 队列立即发送接口不可用': 'WorkBuddy queue send-now API unavailable', '未找到 WorkBuddy 队列接口': 'WorkBuddy queue API not found','一个基于': 'A ', '个备选': 'standby', '备选': 'standby', '个失败': ' failed', '个已不存在': ' no longer exist', '项失败': ' failed', '已选': ' selected', '例如 deepseek-v4-flash': 'e.g. deepseek-v4-flash', '例如我的 DeepSeek': 'e.g. my DeepSeek', '加载失败': 'Load failed', '发起授权失败:': 'Authorization failed:', '开启': 'Enable', '关闭': 'Close', '失败': 'Failed', '用户消息': 'User message','OLED 纯黑': 'OLED Pure Black', '未发现 CDP 端口(WorkBuddy 需以 --remote-debugging-port 启动)': 'No CDP port found (start WorkBuddy with --remote-debugging-port)', '本地 API 未授权': 'Local API unauthorized', '仅支持 http(s) 链接': 'Only http(s) links are supported', '图片不能超过 10MB': 'Image must not exceed 10MB', '图片必须是 PNG/JPEG/WebP base64': 'Image must be PNG/JPEG/WebP base64', '遥测开关值必须是布尔值': 'Telemetry switch must be a boolean', 'blur 必须是数字': 'Blur must be a number', 'opacity 必须是数字': 'Opacity must be a number', '查询返回空结果': 'Query returned empty results',@@ -753,10 +921,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'时间': 'Time', '自动复制': 'Auto-copy', '模型名': 'Model name', '自定义名称': 'Custom name', '确认操作': 'Confirm operation', '小贴士': 'Tip','解决 WorkBuddy 不支持多个同名模型的问题。': 'Solves WorkBuddy not supporting multiple models with the same name.','清空': 'Clear', '继续': 'Continue', '更换': 'Change',+ '删除所有账号副本': 'Delete across accounts', '删除选中会话及所有账号的同源副本': 'Delete selected sessions and their linked copies across accounts',+ '删除所有账号的同源会话?': 'Delete linked sessions across all accounts?', '再次确认永久删除': 'Confirm permanent deletion again',+ '继续确认': 'Continue to confirmation', '永久删除': 'Delete permanently',+ '将永久删除所选会话,以及已关联到其他账号的所有同源副本、消息文件和本地缓存。此操作不可恢复。': 'Permanently deletes the selected sessions and all linked 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',+ '白底黑眼': '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: ','共 {n} 个': 'Total: {n} ', '展开 {n} 条(': 'Show {n} (', '从 {src} 导入': 'Import from {src}','(': '(', ')': ')',// —— 第五批:基础高频词(杜绝词根缺失造成的半句混合)+ 会话/模型/账号错误整句 ——- '错误': 'Error', '状态': 'Status', '导航': 'navigation', '消息': 'message', '当前': 'Current', '配置': 'config', '无效': 'invalid', '接口': 'API', '队列': 'queue', '不可用': 'unavailable', '缺少': 'Missing', '未找到页面元素': 'Page element not found', '页面元素不可见': 'Page element is not visible', '无法聚焦页面元素': 'Could not focus page element', 'HTTP URL 仅支持 http(s)': 'HTTP URL must use http(s)', '运行记录不存在': 'Run record not found',+ '错误': 'Error', '状态': 'Status', '导航': 'navigation', '消息': 'message', '当前': 'Current', '配置': 'config', '无效': 'invalid', '认证数据无效': 'Invalid authentication data', '接口': 'API', '队列': 'queue', '不可用': 'unavailable', '缺少': 'Missing', '未找到页面元素': 'Page element not found', '页面元素不可见': 'Page element is not visible', '无法聚焦页面元素': 'Could not focus page element', 'HTTP URL 仅支持 http(s)': 'HTTP URL must use http(s)', '运行记录不存在': 'Run record not found','会话错误': 'Session error', '会话状态': 'Session status', '会话消息导航': 'Session message navigation', '未获取到当前会话': 'Could not get the current session','回复已停止,但没有发现明确完成证据': 'Reply stopped without clear completion evidence','会话正在等待决策确认': 'Session awaiting a decision confirmation', '会话出现模型或网络错误': 'Session hit a model or network error',@@ -774,6 +952,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'模型索引无效': 'Invalid model index', '模型配置无效': 'Invalid model config', '未选择当前模型': 'No current model selected','模型备份缺少 id/name,无法保存': 'Model backup is missing id/name; cannot save', '模型备份缺少 id/name,无法启用': 'Model backup is missing id/name; cannot enable','不能从当前客户端导入模型': 'Cannot import models from the current client',+ '来源客户端': 'Source client',+ '未找到可导入的模型配置': 'No importable model configurations found',+ '从第三方导入': 'Import from third party',+ '从 CC Switch 导入模型': 'Import models from CC Switch',+ '未命名供应商': 'Unnamed provider',+ 'CC Switch 中还没有模型配置': 'No model configurations in CC Switch',+ '确认覆盖同名模型?': 'Replace models with matching IDs?',+ '将覆盖 ': 'This will replace ',+ ' 个现有模型。': ' existing models. ',+ '所选配置中有 ': 'The selection contains ',+ ' 个重复模型 ID,当前模型将采用最后一项。': ' duplicate model IDs; the last entry for each ID will become active. ',+ '导入前会自动备份,所选配置也会保存到「备选模型」。': 'The current configuration will be backed up, and selected configurations will also be saved in Backup models.',+ ' 个现有模型': ' existing models',+ '导入失败,请重新读取模型列表': 'Import failed. Reload the model list.',+ '未检测到 CC Switch 本地模型配置': 'No local CC Switch model configuration found',+ '读取第三方配置失败': 'Failed to read third-party configuration',+ '读取 CC Switch 模型失败': 'Failed to read CC Switch models',+ ',所选配置已保存到「备选模型」': '; selected configurations saved in Backup models','无效的自动复制规则类型': 'Invalid auto-copy rule type', '缺少自动复制规则标识': 'Missing auto-copy rule id', '缺少源账号 uid': 'Missing source account uid','缺少共享会话标识': 'Missing shared session id', '标记仍然存在': 'Marker still present','未找到唯一的当前登录信息文件': 'No unique current login file found', '未找到有效的登录信息文件': 'No valid login file found',@@ -933,7 +1129,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'蒙版已保存但应用失败:': 'Overlay saved but failed to apply:', '模糊设置已保存但应用失败:': 'Blur setting saved but failed to apply:','无法清空输入框': 'Could not clear the composer', '未找到发送按钮': 'Send button not found', '未找到操作栏': 'Toolbar not found',// —— 第十五批:面板入口描述与连接状态 ——- '面板入口:': 'Panel entry:', '右下角机器人按钮': 'Bottom-right robot button', '已连接': 'Connected', '未连接': 'Not connected'+ '首次加载时间较长,请等候': 'The first load may take a little longer. Please wait.',+ '面板入口:': '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',+ '当前积分段已用完': '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',+ '切换到此账号': 'Switch to this account', '今天不再提醒': 'Do not remind me again today', '关闭': 'Close',+ '切换中…': 'Switching…', 'Token 用量统计': 'Token usage statistics', ' 分钟后': ' minutes', ' 小时后': ' hours', ' 天后': ' days',+ '未设置时间': 'no expiry time', '时间': 'Time', '近 7 天': 'Last 7 days', '近 30 天': 'Last 30 days', '近 90 天': 'Last 90 days',+ '账号': 'Account', '全部账号': 'All accounts', '模型': 'Model', '全部模型': 'All models', '刷新': 'Refresh', '刷新统计': 'Refresh statistics', '开始日期': 'From', '结束日期': 'To',+ '每日趋势': 'Daily trend', '暂无趋势数据': 'No trend data', '模型排行': 'Model ranking', ' 次': ' calls', '暂无模型数据': 'No model data', '暂无账号数据': 'No account data'};function wbsSystemLanguage() {var value = String((navigator && (navigator.language || navigator.userLanguage)) || '').toLowerCase();@@ -1032,6 +1238,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {return out;}+ function wbsIsBuiltinAutomation(task) {+ return !!task && [+ 'buddy-fuel-station-close-on-account-switch',+ 'daily-account-checkin',+ 'keep-accounts-active-1-plus-1'+ ].indexOf(task.id) >= 0;+ }+function wbsBuiltinAutomationText(task, field) {var defaults = {"daily-account-checkin": {@@ -1056,7 +1270,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {"页面就绪后自动关闭首页弹窗"],"description": [- "页面就绪后立即检查三类弹窗,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。"+ "页面就绪后立即检查三类弹窗,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。",+ "页面就绪后立即检查首页弹窗与运营位,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。"]}};@@ -1102,7 +1317,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var accountMaskEnabled = false;try { accountMaskEnabled = localStorage.getItem(WBS_ACCOUNT_MASK_KEY) === '1'; } catch (_) {}- var state = { accounts: [], current: null, open: false, batchRunning: false, creditRunId: 0, activityRunId: 0, creditRemaining: 0, creditSummaryValue: null, mask: accountMaskEnabled };+ var state = { accounts: [], current: null, open: false, batchRunning: false, creditRunId: 0, activityRunId: 0, creditRemaining: 0, creditSummaryValue: null, mask: accountMaskEnabled, rotationNotice: null, rotationPromptDay: '' };var currentBuild = null;// 当前注入的 daemon 版本号(由 daemon.js 注入时把 __WBS_VERSION__ 替换为 DAEMON_VERSION)// 「关于」tab 直接展示,升级 daemon 后这里自动同步@@ -1185,6 +1400,9 @@ 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 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>';// 脱敏小眼睛:睁眼 = 明文可见(点击后隐藏);闭眼(斜线) = 已脱敏(点击后显示明文)var EYE_SVG ='<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">' +@@ -1474,6 +1692,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function build() {var lifecycle = createBuildLifecycle();var registerDisposer = lifecycle.registerDisposer;+ var usageActivity = createUsageActivity({ document: document, window: window,+ now: Date.now, enabled: function () { return WBS_DIAGNOSTICS_ENABLED; },+ send: function () { return api('/api/usage', { method: 'POST' }); } });+ registerDisposer(function () { usageActivity.destroy(); });var alive = true;var buildTimeouts = [];var buildIntervals = [];@@ -1869,29 +2091,27 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {root.innerHTML = ['<div class="wbs-fab" title="' + WBS_BRAND + '">','<span class="wbs-fab-health-dot" title="会话状态" style="display:none"></span>',+ '<svg class="wbs-robot-masks" width="0" height="0" aria-hidden="true" focusable="false"><defs><mask id="wbs-robot-face-mask" maskUnits="userSpaceOnUse" x="0" y="0" width="82" height="64" style="mask-type:luminance">',+ '<rect width="82" height="64" fill="white"/><rect class="wbs-robot-cutout" x="22" y="23" width="12" height="18" rx="6" fill="black"/><rect class="wbs-robot-cutout" x="48" y="23" width="12" height="18" rx="6" fill="black"/>',+ '</mask></defs></svg>','<div class="click">',- '<span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span>','<button class="button up" type="button" aria-label="WorkDaddy,点击打开面板,可拖动">','<span class="wbs-fab-antenna" aria-hidden="true"></span>','<span class="wbs-fab-antenna-dot" id="wbs-fab-sleep-light" title="允许电脑休眠(默认)"></span>','<div class="speak dblink"><div class="wrap"><div class="eye double-blink"></div><div class="eye double-blink"></div></div></div>',- '<div class="speak doblink"><div class="wrap"><div class="eye down"></div><div class="eye down"></div></div></div>',- '<div class="speak rblink"><div class="wrap"><div class="eye right-blink"></div><div class="eye right-blink"></div></div></div>',- '<div class="speak ublink"><div class="wrap"><div class="eye up-blink"></div><div class="eye up-blink"></div></div></div>','</button>',- '<button disabled class="button shadow"></button>','</div>','</div>','<div class="wbs-panel">','<div class="wbs-head">','<div class="wbs-head-left">',- '<div class="wbs-title-wrap"><div class="wbs-title-row"><div class="wbs-title" id="wbs-title" title="WorkDaddy">' + WBS_BRAND + '</div>',+ '<div class="wbs-title-wrap"><div class="wbs-title-row">',+ '<button class="wbs-brand" id="wbs-title" type="button" title="点击打开官网">',+ '<span class="wbs-brand-copy"><span class="wbs-title">' + WBS_BRAND + '</span><span class="wbs-version-line" id="wbs-version-line"></span></span>',+ '</button>','<button class="wbs-pick-btn" id="wbs-pick-btn" type="button" style="display:none" title="元素检查">🔍</button>','<span class="wbs-health-status" id="wbs-health-status" aria-live="polite"></span>',- '<a class="wbs-ghbtn" href="https://github.com/babygoton/WorkDaddy" target="_blank" rel="noopener" title="GitHub 仓库">',- '<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M12 .3a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.03c-3.34.73-4.04-1.61-4.04-1.61-.55-1.39-1.33-1.76-1.33-1.76-1.09-.74.08-.73.08-.73 1.2.09 1.84 1.24 1.84 1.24 1.07 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.66-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.11-3.18 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 0 1 6.01 0c2.29-1.55 3.3-1.23 3.3-1.23.65 1.66.24 2.88.12 3.18.77.84 1.23 1.91 1.23 3.22 0 4.61-2.81 5.62-5.49 5.92.43.37.82 1.1.82 2.22v3.29c0 .32.22.7.83.58A12 12 0 0 0 12 .3z"/></svg>',- '</a>',- '</div><div class="wbs-version-line" id="wbs-version-line"></div></div>',+ '</div></div>','</div>','<button class="wbs-btn-close" type="button" data-act="close">✕</button>','</div>',@@ -2218,9 +2438,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}var request = { contentBlocks: [selectionQuoteBlock(pending.text)] };try {- Promise.resolve(adapter.requestInsertContentBlocks(request)).then(function () {- toast('已引用选中文字', false, root);- }).catch(function () {+ Promise.resolve(adapter.requestInsertContentBlocks(request)).catch(function () {toast('引用插入失败,请重试', true, root);});} catch (_) {@@ -2953,6 +3171,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function updateActive() {if (!surface || !turns.length) return;+ // 末条消息较短时无法顶齐视口;到底后直接对应最后一轮,避免顶部位置推断选回上一轮。+ var scroll = surface.scrollElement;+ if (scroll && scroll.scrollHeight > scroll.clientHeight &&+ scroll.scrollHeight - scroll.scrollTop - scroll.clientHeight <= 2) {+ setActive(turns[turns.length - 1].id);+ return;+ }var viewport = surface.viewportElement.getBoundingClientRect();var frames = surface.conversationElement.querySelectorAll('.cr-document__virtual-item[data-index]');var visibleMessageIndex = -1;@@ -4239,6 +4464,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});var fab = root.querySelector('.wbs-fab');+ var fabAppearance = createFabAppearance({ fab: fab, storage: localStorage, key: 'wbs-fab-style-' + PROFILE_ID });var panel = root.querySelector('.wbs-panel');var body = root.querySelector('.wbs-body');var accountsPane = root.querySelector('[data-pane="account"]');@@ -4290,6 +4516,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}if (accountsPane) {+ var accountImportMode = 'encrypted';listen(accountsPane, 'mouseover', function (event) {var segment = findCreditSegment(event.target);if (!segment || segment === creditTooltipSegment) return;@@ -4320,8 +4547,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-acct-stat"><span>总积分</span><strong id="wbs-acct-total">-</strong></div>' +'</div>' +'<div class="wbs-acct-actions">' +- '<button class="wbs-acct-io" type="button" data-act="export" title="选择账号并输入密码后导出备份">' + EXPORT_ICON + '<span>导出</span></button>' +- '<button class="wbs-acct-io" type="button" data-act="import" title="从加密导出文件导入账号备份">' + IMPORT_ICON + '<span>导入</span></button>' ++ '<button class="wbs-acct-io wbs-acct-icon" type="button" data-act="token-stats" title="用量统计" aria-label="用量统计">' + TOKEN_STATS_ICON + '</button>' ++ '<button class="wbs-acct-io wbs-acct-icon" type="button" data-act="export" title="选择账号并输入密码后导出备份" aria-label="导出账号">' + EXPORT_ICON + '</button>' ++ '<button class="wbs-acct-io wbs-acct-icon" type="button" data-act="import" title="从加密导出文件导入账号备份" aria-label="导入账号">' + IMPORT_ICON + '</button>' +'</div>' +'</div>' +'<div class="wbs-acct-list"></div>' +@@ -4331,8 +4559,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var eyeBtn = root.querySelector('.wbs-acct-eye');if (eyeBtn) eyeBtn.addEventListener('click', toggleAccountMask);root.querySelector('[data-act="export"]').addEventListener('click', onExportAccounts);+ root.querySelector('[data-act="token-stats"]').addEventListener('click', onTokenStats);root.querySelector('[data-act="import"]').addEventListener('click', function () {- root.querySelector('#wbs-import-file').click();+ openAccountImportChoice();});root.querySelector('#wbs-import-file').addEventListener('change', onImportFile);}@@ -4590,7 +4819,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {onConfirm: function (password) { return api('/api/accounts/import', {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ content: content, password: password }),+ body: JSON.stringify({ content: content, password: password, format: accountImportMode }),}).then(function (r) {toast('成功导入 ' + r.count + ' 个账号', false, root);refresh();@@ -4600,6 +4829,314 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}).catch(function (e) { toast(e.message || '读取文件失败', true, root); });}+ function openAccountImportChoice() {+ var existing = root.querySelector('#wbs-account-import-choice');+ if (existing) existing.remove();+ var mask = document.createElement('div');+ mask.className = 'wbs-panel-modal-mask';+ mask.id = 'wbs-account-import-choice';+ mask.innerHTML = '<div class="wbs-login-modal wbs-import-choice-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-account-import-choice-title">' ++ '<div class="wbs-login-modal-title" id="wbs-account-import-choice-title">导入账号</div>' ++ '<div class="wbs-login-body" role="radiogroup" aria-label="导入方式">' ++ '<label class="wbs-login-option selected" data-import-way="encrypted"><input type="radio" name="wbs-import-way" value="encrypted" checked><span class="wbs-login-option-copy"><span class="wbs-login-option-title">导入 WorkDaddy 加密文件</span><span class="wbs-login-option-desc">导入 WorkDaddy 导出的账号备份,选择文件后输入导出密码。</span></span></label>' ++ '<label class="wbs-login-option" data-import-way="plain-json"><input type="radio" name="wbs-import-way" value="plain-json"><span class="wbs-login-option-copy"><span class="wbs-login-option-title">导入 JSON 文件</span><span class="wbs-login-option-desc">可以导入其他工具导出的明文账号。请先让 WorkBuddy 按指定格式整理,再选择生成的 JSON 文件。</span></span></label>' ++ '</div>' ++ '<div class="wbs-import-json-hint" hidden>把其他工具导出的账号文本发给 WorkBuddy,让它只输出符合 WorkDaddy 格式的 JSON,然后复制保存为文件。</div>' ++ '<div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" data-import-copy>复制提示词</button><button class="wbs-modal-btn" type="button" data-import-cancel>取消</button><button class="wbs-modal-btn wbs-modal-ok" type="button" data-import-confirm>选择文件</button></div>' ++ '</div>';+ (panel || root).appendChild(mask);+ var options = mask.querySelectorAll('.wbs-login-option');+ var hint = mask.querySelector('.wbs-import-json-hint');+ var copyBtn = mask.querySelector('[data-import-copy]');+ var prompt = '\u8bf7\u628a\u6211\u63d0\u4f9b\u7684\u5176\u4ed6\u5de5\u5177\u8d26\u53f7\u6587\u672c\u6574\u7406\u6210 WorkDaddy \u53ef\u5bfc\u5165\u7684 JSON\u3002\u53ea\u8f93\u51fa JSON\uff0c\u4e0d\u8981 Markdown\uff0c\u4e0d\u8981\u89e3\u91ca\u3002\u683c\u5f0f\u5fc5\u987b\u662f\u5bf9\u8c61\u6570\u7ec4\uff0c\u6bcf\u9879\u5305\u542b account \u5bf9\u8c61\u548c auth \u5bf9\u8c61\uff1baccount.uid \u4e3a\u5b57\u6bcd\u3001\u6570\u5b57\u3001\u4e0b\u5212\u7ebf\u6216\u77ed\u6a2a\u7ebf\uff0cauth.accessToken \u4e3a\u5b57\u7b26\u4e32\uff0c\u5176\u4ed6\u5b57\u6bb5\u6309\u539f\u6587\u4fdd\u7559\u3002\u793a\u4f8b\uff1a[{"account":{"uid":"...","nickname":"..."},"auth":{"accessToken":"...","refreshToken":"..."}}]';+ function sync() {+ var selected = mask.querySelector('input[name="wbs-import-way"]:checked');+ accountImportMode = selected ? selected.value : 'encrypted';+ for (var i = 0; i < options.length; i++) options[i].classList.toggle('selected', options[i].querySelector('input').checked);+ hint.hidden = accountImportMode !== 'plain-json';+ copyBtn.hidden = accountImportMode !== 'plain-json';+ }+ for (var i = 0; i < options.length; i++) {+ options[i].addEventListener('click', sync);+ options[i].querySelector('input').addEventListener('change', sync);+ }+ copyBtn.addEventListener('click', function () { copyPlainText(prompt).then(function () { toast('提示词已复制', false, root); }).catch(function () { toast('复制失败', true, root); }); });+ mask.querySelector('[data-import-cancel]').addEventListener('click', function () { mask.remove(); });+ mask.addEventListener('click', function (ev) { if (ev.target === mask) mask.remove(); });+ mask.querySelector('[data-import-confirm]').addEventListener('click', function () {+ accountImportMode = (mask.querySelector('input[name="wbs-import-way"]:checked') || {}).value || 'encrypted';+ mask.remove();+ root.querySelector('#wbs-import-file').click();+ });+ sync();+ }++ function formatTokenCount(value) {+ var number = Number(value) || 0;+ var units = [[1000000000000, 'T'], [1000000000, 'B'], [1000000, 'M'], [1000, 'K']];+ for (var i = 0; i < units.length; i++) {+ if (number >= units[i][0]) return (number / units[i][0]).toFixed(2).replace(/\.?0+$/, '') + units[i][1];+ }+ return String(Math.round(number));+ }++ function onTokenStats() {+ var existing = root.querySelector('#wbs-token-stats-modal');+ if (existing) { if (existing.__wbsClose) existing.__wbsClose(); else existing.remove(); }+ var mask = document.createElement('div');+ mask.id = 'wbs-token-stats-modal';+ mask.className = 'wbs-modal-mask wbs-modal-mask-panel';+ var glassFab = root.querySelector('.wbs-fab[data-wbs-robot-style="glass"]');+ if (glassFab) mask.classList.add('wbs-token-stats-glass');+ mask.innerHTML = '<div class="wbs-modal wbs-token-stats-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-token-stats-title">' ++ '<div class="wbs-usage-header"><div class="wbs-token-stats-head"><div class="wbs-modal-title" id="wbs-token-stats-title">用量统计</div></div>' ++ '<div class="wbs-usage-tabs"><button type="button" class="active" data-usage-tab="token">Token</button><button type="button" data-usage-tab="credit">积分</button></div></div><div class="wbs-usage-scroll">' ++ '<div data-usage-pane="token"><div class="wbs-token-stats-filters"><label>时间<select data-token-days><option value="1">今天</option><option value="7" selected>近 7 天</option><option value="30">近 30 天</option><option value="90">近 90 天</option></select></label><label>账号<select data-token-account><option value="">全部账号</option></select></label><label>模型<select data-token-model><option value="">全部模型</option></select></label></div>' ++ '<div class="wbs-token-source-note">Token 用量仅统计本机记录,在不同电脑上查看的数据可能不一致。</div>' ++ '<div class="wbs-token-stats-content"><div class="wbs-token-stats-body"></div><div class="wbs-token-stats-overlay" role="status" aria-label="正在读取统计…"><div class="wbs-token-stats-spinner"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle></svg><span hidden>首次加载时间较长,请等候</span></div></div></div></div>' ++ '<div data-usage-pane="credit" hidden><div class="wbs-token-stats-filters wbs-credit-filters"><label>时间<select data-credit-days><option value="1">今天</option><option value="7" selected>近 7 天</option><option value="30">近 30 天</option><option value="90">近 90 天</option></select></label><label>账号<select data-credit-account><option value="">全部账号</option></select></label></div>' ++ '<div data-credit-result role="status" class="wbs-credit-stats-note" hidden></div>' ++ '<div class="wbs-credit-query-content"><div class="wbs-credit-stats-body wbs-token-stats-body"></div><div class="wbs-credit-sync-overlay" hidden><div class="wbs-credit-sync-progress" role="status" aria-live="polite"><strong>正在查询积分用量…</strong><span data-credit-progress-copy>正在连接…</span><progress data-credit-progress max="100" value="0" aria-label="积分查询进度"></progress><span data-credit-progress-detail></span></div></div></div></div></div>' ++ '<div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" data-token-close>关闭</button></div></div>';+ (panel || root).appendChild(mask);+ var body = mask.querySelector('.wbs-token-stats-body');+ var creditPollTimer = null;+ var focusBefore = document.activeElement;+ function closeStats() {+ if (creditPollTimer) clearTimeout(creditPollTimer);+ mask.remove();+ if (focusBefore && focusBefore.isConnected) focusBefore.focus();+ }+ mask.__wbsClose = closeStats;+ registerDisposer(function () { if (creditPollTimer) clearTimeout(creditPollTimer); mask.remove(); });+ 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(); }); });+ mask.addEventListener('keydown', function (event) {+ 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 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(); }+ }+ });+ mask.querySelector('[data-token-close]').focus();+ var daysSelect = mask.querySelector('[data-token-days]');+ var accountSelect = mask.querySelector('[data-token-account]');+ var modelSelect = mask.querySelector('[data-token-model]');+ var overlay = mask.querySelector('.wbs-token-stats-overlay');+ var loadedAccounts = [];+ var hasStats = false;+ var firstLoadTimer = null;+ var filterControls = [daysSelect, accountSelect, modelSelect];+ var creditLoaded = false;+ var creditDays = mask.querySelector('[data-credit-days]');+ var creditAccount = mask.querySelector('[data-credit-account]');+ var creditBody = mask.querySelector('.wbs-credit-stats-body');+ var creditSyncOverlay = mask.querySelector('.wbs-credit-sync-overlay');+ var creditResult = mask.querySelector('[data-credit-result]');+ var creditData = null;+ var creditReadSerial = 0;+ var creditAccounts = [];+ var creditBusy = false;+ var creditJobId = '';+ function selectedCreditAccounts() {+ return creditAccounts.filter(function (a) { return !creditAccount.value || a.uid === creditAccount.value; });+ }+ function updateCreditAccounts() {+ var previous = creditAccount.value;+ creditAccount.innerHTML = '<option value="">全部账号</option>' + creditAccounts.map(function (a) { return '<option value="' + escAttr(a.uid) + '">' + esc(a.nickname || a.uid) + '</option>'; }).join('');+ creditAccount.value = previous;+ if (creditAccount.selectedIndex < 0) creditAccount.value = '';+ }+ function renderCredits() {+ if (!creditData) return;+ var selected = selectedCreditAccounts();+ var ids = selected.map(function (a) { return a.uid; });+ var byDay = Object.create(null), byAccount = Object.create(null), accountCalls = Object.create(null), total = 0, calls = 0;+ (creditData.daily || []).forEach(function (item) {+ if (ids.indexOf(item.uid) < 0) return;+ var value = Number(item.used) || 0;+ var day = byDay[item.date] || (byDay[item.date] = { used: 0, complete: 0 });+ day.used += value; if (item.complete) day.complete++;+ byAccount[item.uid] = (byAccount[item.uid] || 0) + value;+ accountCalls[item.uid] = (accountCalls[item.uid] || 0) + (Number(item.count) || 0);+ total += value; calls += Number(item.count) || 0;+ });+ var days = [], parts = creditData.from.split('-');+ var date = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));+ for (var i = 0; i < Number(creditDays.value); i++) {+ var key = date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0');+ days.push({ date: key, value: byDay[key] ? byDay[key].used : 0, known: !!byDay[key], complete: !!selected.length && !!byDay[key] && byDay[key].complete === selected.length });+ date.setDate(date.getDate() + 1);+ }+ var max = Math.max.apply(null, days.map(function (d) { return d.value; }).concat([1]));++ 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><div class="wbs-credit-chart wbs-token-stats-chart">' + days.map(function (d) {+ var label = d.complete ? fmtCredits(d.value) : d.known ? fmtCredits(d.value) + '*' : '—';+ var hint = d.date + ' · ' + (d.complete ? fmtCredits(d.value) + ' 积分' : d.known ? fmtCredits(d.value) + (creditData.running ? ' 积分(部分日期加载中)' : ' 积分(部分账号查询失败)') : (creditData.running ? '日期数据加载中' : '查询失败,暂无数据'));+ return '<div class="wbs-token-day wbs-credit-day" title="' + escAttr(hint) + '"><b>' + esc(label) + '</b><div class="wbs-credit-bar-track"><i style="height:' + (d.value ? Math.max(2, Math.round(d.value / max * 100)) : 0) + '%"></i></div><span>' + esc(d.date.slice(5)) + '</span></div>';+ }).join('') + '</div>' + ((creditData.failures || []).length ? '<div class="wbs-credit-stats-note">* 表示部分账号查询失败;— 表示查询失败,暂无数据。</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">' + (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>';+ 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();+ }+ var chart = creditBody.querySelector('.wbs-credit-chart');+ if (chart) chart.scrollLeft = chart.scrollWidth;+ }+ function setCreditBusy(busy, showOverlay) {+ creditBusy = busy;+ if (!busy) creditBody.style.visibility = '';+ creditSyncOverlay.hidden = !busy || !showOverlay;+ creditDays.disabled = busy;+ creditAccount.disabled = busy;+ mask.querySelector('.wbs-credit-query-content').setAttribute('aria-busy', String(busy));+ }+ function creditQueryFailed(message) {+ setCreditBusy(false);+ creditData = null;+ creditResult.hidden = false;+ creditResult.textContent = message;+ creditBody.innerHTML = '<div class="wbs-token-stats-empty">查询失败,请重新选择时间或账号重试</div>';+ }+ function showCreditJob(job) {+ mask.querySelector('[data-credit-progress]').value = job.percent || 0;+ mask.querySelector('[data-credit-progress-copy]').textContent = '已查询 ' + job.completed + '/' + job.total + ' 个账号 · ' + (job.percent || 0) + '%';+ mask.querySelector('[data-credit-progress-detail]').textContent = job.current ? job.current + (job.pages ? ' · 第 ' + job.page + '/' + job.pages + ' 页 · 已读取 ' + job.records + ' 条记录' : ' · 正在连接…') : '';+ setCreditBusy(job.running, !job.hasCachedData && !job.cacheHit);+ creditData = job;+ creditBody.style.visibility = '';+ if (!job.hasCachedData && job.running) creditBody.innerHTML = '';+ if (job.running) {+ creditResult.hidden = true;+ if (job.hasCachedData) renderCredits();+ } else {+ var failures = job.failures || [];+ creditResult.hidden = !failures.length;+ creditResult.textContent = failures.length+ ? '查询成功 ' + job.synced + '/' + job.total + ' 个账号;结果不完整。' + failures.map(function (a) { return a.nickname + ':' + a.error; }).join(';') : '';+ renderCredits();+ }+ }++ function pollCreditJob(serial) {+ creditPollTimer = null;+ api('/api/credit-stats/sync').then(function (result) {+ if (!mask.isConnected || serial !== creditReadSerial) return;+ var job = result.job || {};+ if (job.id !== creditJobId) { creditQueryFailed('查询已中断,请重新选择时间或账号重试'); return; }+ showCreditJob(job);+ if (job.running) creditPollTimer = setTimeout(function () { pollCreditJob(serial); }, 400);+ }).catch(function () {+ if (!mask.isConnected || serial !== creditReadSerial) return;+ creditQueryFailed('无法读取查询进度,请重新选择时间或账号重试');+ });+ }+ function loadCredits() {+ if (creditBusy) return;+ if (creditPollTimer) clearTimeout(creditPollTimer);+ var serial = ++creditReadSerial;+ creditLoaded = true; creditResult.textContent = ''; creditResult.hidden = true;+ creditBody.style.visibility = 'hidden';+ setCreditBusy(true, false);+ mask.querySelector('[data-credit-progress]').removeAttribute('value');+ mask.querySelector('[data-credit-progress-copy]').textContent = '正在连接…';+ mask.querySelector('[data-credit-progress-detail]').textContent = '';+ mask.querySelector('.wbs-usage-scroll').scrollTop = 0;+ var request = { days: Number(creditDays.value) };+ if (creditAccount.value) request.uids = [creditAccount.value];+ api('/api/credit-stats', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(request) }).then(function (result) {+ if (!mask.isConnected || serial !== creditReadSerial) return;+ creditAccounts = result.accounts || [];+ updateCreditAccounts();+ creditJobId = result.job.id;+ showCreditJob(result.job);+ if (result.job.running) pollCreditJob(serial);+ }).catch(function (error) {+ if (!mask.isConnected || serial !== creditReadSerial) return;+ creditQueryFailed(error.message || '查询失败,请重新选择时间或账号重试');+ });+ }+ mask.querySelectorAll('[data-usage-tab]').forEach(function (button) {+ button.addEventListener('click', function () {+ var tab = button.getAttribute('data-usage-tab');+ var changed = !button.classList.contains('active');+ mask.querySelectorAll('[data-usage-tab]').forEach(function (b) { b.classList.toggle('active', b === button); });+ 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();+ });+ });+ creditDays.addEventListener('change', loadCredits);+ creditAccount.addEventListener('change', loadCredits);+ function load() {+ for (var fi = 0; fi < filterControls.length; fi++) filterControls[fi].disabled = true;+ overlay.hidden = false;+ body.innerHTML = '<div class="wbs-token-stats-loading" role="status">正在读取 Token 用量…</div>';+ if (firstLoadTimer) { clearTimeout(firstLoadTimer); firstLoadTimer = null; }+ var loadingLabel = overlay.querySelector('span');+ loadingLabel.hidden = true;+ var query = '/api/token-stats?days=' + encodeURIComponent(daysSelect.value) + '&account=' + encodeURIComponent(accountSelect.value) + '&model=' + encodeURIComponent(modelSelect.value);+ api('/api/token-stats?cacheStatus=1').then(function (metadata) {+ if (!mask.isConnected) return null;+ if (!metadata.cacheReady) {+ overlay.hidden = false;+ firstLoadTimer = setTimeout(function () { if (!overlay.hidden) loadingLabel.hidden = false; }, 350);+ }+ return api(query);+ }).then(function (result) {+ if (!result || !mask.isConnected) return;+ var stats = result && result.stats || {};+ loadingLabel.hidden = true;+ var totals = stats.totals || {};+ var previousAccount = accountSelect.value;+ var previousModel = modelSelect.value;+ loadedAccounts = (result && result.accounts) || stats.accounts || [];+ accountSelect.innerHTML = '<option value="">全部账号</option>' + loadedAccounts.map(function (item) { var uid = item.uid || item.account || ''; var label = item.nickname || uid; return '<option value="' + escAttr(uid) + '">' + esc(label) + '</option>'; }).join('');+ modelSelect.innerHTML = '<option value="">全部模型</option>' + (stats.models || []).map(function (item) { return '<option value="' + escAttr(item.model) + '">' + esc(item.model) + '</option>'; }).join('');+ accountSelect.value = previousAccount;+ modelSelect.value = previousModel;+ var dailyByDate = Object.create(null);+ (stats.daily || []).forEach(function (item) { dailyByDate[item.day] = item; });+ var tokenDays = [], tokenDate = new Date(); tokenDate.setHours(0, 0, 0, 0); tokenDate.setDate(tokenDate.getDate() - (Number(daysSelect.value) - 1));+ for (var dayIndex = 0; dayIndex < Number(daysSelect.value); dayIndex++) {+ var dayKey = tokenDate.getFullYear() + '-' + String(tokenDate.getMonth() + 1).padStart(2, '0') + '-' + String(tokenDate.getDate()).padStart(2, '0');+ tokenDays.push(dailyByDate[dayKey] || { day: dayKey, input: 0, output: 0 });+ tokenDate.setDate(tokenDate.getDate() + 1);+ }+ var maxDay = Math.max.apply(null, tokenDays.map(function (item) { return (item.input || 0) + (item.output || 0); }).concat([1]));+ var accountRows = (stats.accounts || []).filter(function (item) { return (item.input || 0) + (item.output || 0) + (item.cacheRead || 0) + (item.cacheWrite || 0) > 0; });+ body.innerHTML = '<div class="wbs-token-stats-grid">' ++ '<div><span>调用</span><strong>' + esc(formatTokenCount(totals.calls)) + '</strong></div>' ++ '<div><span>输入</span><strong>' + esc(formatTokenCount(totals.input)) + '</strong></div>' ++ '<div><span>输出</span><strong>' + esc(formatTokenCount(totals.output)) + '</strong></div>' ++ '<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><div class="wbs-credit-chart wbs-token-stats-chart">' + tokenDays.map(function (item) { var value = (item.input || 0) + (item.output || 0); return '<div class="wbs-token-day wbs-credit-day"><b>' + esc(formatTokenCount(value)) + '</b><div class="wbs-credit-bar-track"><i style="height:' + (value ? Math.max(2, Math.round(value / maxDay * 100)) : 0) + '%" title="' + esc(formatTokenCount(value)) + '"></i></div><span>' + esc(String(item.day).slice(5)) + '</span></div>'; }).join('') + '</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">' + ((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>';+ 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 (hasStats) toast('读取失败:' + (error.message || error), true, root); else body.innerHTML = '<div class="wbs-token-stats-empty">读取失败:' + esc(error.message || error) + '</div>'; }).finally(function () { if (firstLoadTimer) { clearTimeout(firstLoadTimer); firstLoadTimer = null; } for (var fi = 0; fi < filterControls.length; fi++) filterControls[fi].disabled = false; overlay.hidden = true; });+ }+ for (var fi = 0; fi < filterControls.length; fi++) filterControls[fi].addEventListener('change', load);+ load();+ }+// ===== Tab 切换 =====function switchTab(name) {var tabs = root.querySelectorAll('.wbs-tab');@@ -4695,9 +5232,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var active = running || stopping;var check = automationState.batchMode ? '<label class="wbs-auto-check"><input type="checkbox" data-auto-select="' + escAttr(task.id) + '"' + (automationState.selected[task.id] ? ' checked' : '') + '><span></span></label>' : '';var stateClass = active ? 'running' : !task.enabled && !task.manualRunnable ? 'off' : 'idle';+ var builtinBadge = wbsIsBuiltinAutomation(task) ? '<span class="wbs-auto-builtin-badge">内置</span>' : '';var action = running ? '<button type="button" class="wbs-auto-icon is-running' + (stopping ? ' is-stopping' : '') + '" data-auto-stop="' + escAttr(run.id) + '" title="' + (stopping ? '正在停止…' : '停止本次执行') + '" aria-label="' + (stopping ? '正在停止…' : '停止本次执行') + '" aria-busy="true"' + (stopping ? ' disabled' : '') + '>' + (stopping ? AUTO_STOPPING_SVG : AUTO_STOP_SVG) + '</button>': task.manualRunnable ? '<button type="button" class="wbs-auto-icon" data-auto-run="' + escAttr(task.id) + '" title="立即运行" aria-label="立即运行">' + MODEL_ENABLE_SVG + '</button>' : '';- row.innerHTML = '<div class="wbs-auto-row-head">' + check + '<div class="wbs-auto-name"' + (wbsBuiltinAutomationText(task, 'name') ? '' : ' data-wbs-i18n-skip="1"') + ' title="' + escAttr(task.name) + '">' + esc(task.name) + '</div>' ++ row.innerHTML = '<div class="wbs-auto-row-head">' + check + builtinBadge + '<div class="wbs-auto-name"' + (wbsBuiltinAutomationText(task, 'name') ? '' : ' data-wbs-i18n-skip="1"') + ' title="' + escAttr(task.name) + '">' + esc(task.name) + '</div>' +'<label class="wbs-switch wbs-auto-enabled" title="' + (task.manualRunnable ? '手动任务无需自动触发' : '启用自动触发') + '"' + (task.manualRunnable || task.compatible === false ? ' hidden' : '') + '><input type="checkbox" data-auto-enabled="' + escAttr(task.id) + '" aria-label="启用自动触发"' + (task.enabled ? ' checked' : '') + '><span class="wbs-switch-slider"></span></label></div>' +(task.description ? '<div class="wbs-auto-description"' + (wbsBuiltinAutomationText(task, 'description') ? '' : ' data-wbs-i18n-skip="1"') + ' title="' + escAttr(task.description) + '">' + esc(task.description) + '</div>' : '') +'<div class="wbs-auto-row-foot"><div class="wbs-auto-details"><div class="wbs-auto-triggers" aria-label="触发方式">' + triggerBadgesHtml(task) + '</div><div class="wbs-auto-state-line"><span class="wbs-auto-state ' + stateClass + '">' + esc(taskStatusLabel(task, run, stopping)) + '</span>' +@@ -4824,7 +5362,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var mask = document.createElement('div');mask.id = 'wbs-auto-editor-mask';mask.className = 'wbs-modal-mask wbs-modal-mask-panel';- mask.innerHTML = '<div class="wbs-modal wbs-auto-editor-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-editor-title"><div class="wbs-auto-modal-head"><div class="wbs-modal-title" id="wbs-auto-editor-title">编辑任务</div><button class="wbs-auto-modal-close" type="button" title="关闭" aria-label="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></div><div class="wbs-auto-editor-body"><label class="wbs-auto-field"><span>任务名称</span><input data-auto-field="name" type="text" maxlength="120"></label><label class="wbs-auto-field"><span>任务说明</span><textarea data-auto-field="description" rows="3" maxlength="500"></textarea></label><div class="wbs-auto-field"><span>事件触发(可多选)</span><div class="wbs-auto-trigger-options" data-auto-field="trigger" role="group" aria-label="触发方式"><label><input type="checkbox" value="pageReady"><span>页面就绪</span></label><label><input type="checkbox" value="pageLoaded"><span>页面加载</span></label><label><input type="checkbox" value="accountSwitched"><span>账号切换后</span></label><label><input type="checkbox" value="clientLoaded"><span>客户端加载</span></label><label><input type="checkbox" value="panelOpened"><span>打开面板</span></label></div><div class="wbs-auto-schedule"><label>定时方式 <select data-auto-field="scheduleType" aria-label="定时方式"><option value="manual">不定时</option><option value="interval">按间隔</option><option value="daily">每天</option><option value="weekly">每周</option><option value="monthly">每月</option><option value="once">指定时间一次</option></select></label><label data-schedule-for="interval">每 <input type="number" data-auto-field="intervalValue" min="1" max="10080" step="1" aria-label="间隔数值"><select data-auto-field="intervalUnit" aria-label="间隔单位"><option value="1">分钟</option><option value="60">小时</option><option value="1440">天</option></select></label><label data-schedule-for="monthly">日期 <input type="number" data-auto-field="monthDay" min="1" max="31" aria-label="每月日期"></label><label data-schedule-for="daily weekly monthly">时间 <input type="time" data-auto-field="time" aria-label="执行时间"></label><label data-schedule-for="once">日期时间 <input type="datetime-local" data-auto-field="onceAt" aria-label="执行日期和时间"></label><div class="wbs-auto-weekdays" data-schedule-for="weekly"><label><input type="checkbox" data-auto-weekday="1"><span>周一</span></label><label><input type="checkbox" data-auto-weekday="2"><span>周二</span></label><label><input type="checkbox" data-auto-weekday="3"><span>周三</span></label><label><input type="checkbox" data-auto-weekday="4"><span>周四</span></label><label><input type="checkbox" data-auto-weekday="5"><span>周五</span></label><label><input type="checkbox" data-auto-weekday="6"><span>周六</span></label><label><input type="checkbox" data-auto-weekday="0"><span>周日</span></label><button type="button" class="wbs-auto-textbtn" data-auto-workdays>工作日</button></div><div class="wbs-auto-schedule-hint" data-schedule-for="interval daily weekly monthly once">按电脑本地时间执行;错过不补跑,运行中跳过。</div><div class="wbs-auto-schedule-hint" data-schedule-for="monthly">当月没有该日期时跳过。</div></div></div><label class="wbs-auto-field wbs-auto-steps-field"><span>步骤 JSON</span><textarea data-auto-field="steps" spellcheck="false"></textarea></label></div><div class="wbs-modal-actions wbs-auto-editor-actions"><button class="wbs-modal-btn" type="button" id="wbs-auto-cancel">取消</button><button class="wbs-modal-btn wbs-modal-ok" type="button" id="wbs-auto-save">保存</button></div></div>';+ mask.innerHTML = '<div class="wbs-modal wbs-auto-editor-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-editor-title"><div class="wbs-auto-modal-head"><div class="wbs-modal-title" id="wbs-auto-editor-title">编辑任务</div><button class="wbs-auto-modal-close" type="button" title="关闭" aria-label="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></div><div class="wbs-auto-editor-body"><label class="wbs-auto-field"><span>任务名称</span><input data-auto-field="name" type="text" maxlength="120"></label><label class="wbs-auto-field"><span>任务说明</span><textarea data-auto-field="description" rows="3" maxlength="500"></textarea></label><div class="wbs-auto-field"><span>事件触发(可多选)</span><div class="wbs-auto-trigger-options" data-auto-field="trigger" role="group" aria-label="触发方式"><label><input type="checkbox" value="pageReady"><span>页面就绪</span></label><label><input type="checkbox" value="pageLoaded"><span>页面加载</span></label><label><input type="checkbox" value="accountSwitched"><span>账号切换后</span></label><label><input type="checkbox" value="clientLoaded"><span>客户端加载</span></label><label><input type="checkbox" value="panelOpened"><span>打开面板</span></label></div><div class="wbs-auto-schedule"><label>定时方式 <select data-auto-field="scheduleType" aria-label="定时方式"><option value="manual">不定时</option><option value="interval">按间隔</option><option value="daily">每天</option><option value="weekly">每周</option><option value="monthly">每月</option><option value="once">指定时间一次</option></select></label><label data-schedule-for="interval">每 <input type="number" data-auto-field="intervalValue" min="1" max="10080" step="1" aria-label="间隔数值"><select data-auto-field="intervalUnit" aria-label="间隔单位"><option value="1">分钟</option><option value="60">小时</option><option value="1440">天</option></select></label><label data-schedule-for="monthly">日期 <input type="number" data-auto-field="monthDay" min="1" max="31" aria-label="每月日期"></label><label data-schedule-for="daily weekly monthly">时间 <input type="time" data-auto-field="time" aria-label="执行时间"></label><label data-schedule-for="once">日期时间 <input type="datetime-local" data-auto-field="onceAt" aria-label="执行日期和时间"></label><div class="wbs-auto-weekdays" data-schedule-for="weekly"><label><input type="checkbox" data-auto-weekday="1"><span>周一</span></label><label><input type="checkbox" data-auto-weekday="2"><span>周二</span></label><label><input type="checkbox" data-auto-weekday="3"><span>周三</span></label><label><input type="checkbox" data-auto-weekday="4"><span>周四</span></label><label><input type="checkbox" data-auto-weekday="5"><span>周五</span></label><label><input type="checkbox" data-auto-weekday="6"><span>周六</span></label><label><input type="checkbox" data-auto-weekday="0"><span>周日</span></label><button type="button" class="wbs-auto-textbtn" data-auto-workdays>工作日</button></div><div class="wbs-auto-schedule-hint" data-schedule-for="interval daily weekly monthly once">按电脑本地时间执行;错过不补跑,运行中跳过。</div><div class="wbs-auto-schedule-hint" data-schedule-for="monthly">当月没有该日期时跳过。</div></div></div><label class="wbs-auto-field wbs-auto-steps-field"><span>步骤 JSON</span><textarea data-auto-field="steps" spellcheck="false"></textarea></label></div><div class="wbs-modal-actions wbs-auto-editor-actions"><button class="wbs-modal-btn" type="button" id="wbs-auto-cancel">取消</button>' + (wbsIsBuiltinAutomation(task) ? '' : '<button class="wbs-modal-btn wbs-modal-ok" type="button" id="wbs-auto-save">保存</button>') + '</div></div>';(panel || root).appendChild(mask);var editor = mask.querySelector('.wbs-auto-editor-modal');automationState.editingId = task && task.id || null;@@ -4852,7 +5390,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {editor.querySelector('[data-auto-field="steps"]').value = JSON.stringify(task ? task.steps : [], null, 2);mask.__wbsKeyHandler = function (event) { if (event.key === 'Escape') hideEditor(); };document.addEventListener('keydown', mask.__wbsKeyHandler, true);- mask.querySelector('#wbs-auto-save').addEventListener('click', saveEditor);+ var saveButton = mask.querySelector('#wbs-auto-save');+ if (saveButton) saveButton.addEventListener('click', saveEditor);mask.querySelector('#wbs-auto-cancel').addEventListener('click', hideEditor);mask.querySelector('.wbs-auto-modal-close').addEventListener('click', hideEditor);mask.addEventListener('click', function (event) { if (event.target === mask) hideEditor(); });@@ -5128,6 +5667,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-copy" title="复制选中到其他账号"><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="13" height="13" 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>复制</span></button>' +'<button class="wbs-sess-bbtn" type="button" id="wbs-sess-export" title="使用密码导出选中会话">' + EXPORT_ICON + '<span>导出</span></button>' +'<button class="wbs-sess-bbtn wbs-sess-delbtn" type="button" id="wbs-sess-delete" title="删除选中"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg><span>删除</span></button>' ++ '<button class="wbs-sess-bbtn wbs-sess-delbtn" type="button" id="wbs-sess-delete-all" style="display:none" title="删除选中会话及所有账号的同源副本">' + TRASH_SVG + '<span>删除所有账号副本</span></button>' +'<button class="wbs-sess-bbtn wbs-sess-done" type="button" id="wbs-sess-done">取消</button>' +'</div>' +'</div>' +@@ -5135,7 +5675,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-sess-list" id="wbs-sess-list"></div>' +'</div>' +'<div class="wbs-modal-mask" id="wbs-sess-modal" style="display:none">' +- '<div class="wbs-modal">' ++ '<div class="wbs-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-sess-modal-title">' +'<div class="wbs-modal-title" id="wbs-sess-modal-title">操作会话</div>' +'<div class="wbs-modal-body" id="wbs-sess-modal-body"></div>' +'<div class="wbs-modal-actions">' +@@ -5464,9 +6004,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var cp = sessionsPane.querySelector('#wbs-sess-copy');var ex = sessionsPane.querySelector('#wbs-sess-export');var dl = sessionsPane.querySelector('#wbs-sess-delete');+ var da = sessionsPane.querySelector('#wbs-sess-delete-all');if (cp) cp.style.display = n ? '' : 'none';if (ex) ex.style.display = n ? '' : 'none';if (dl) dl.style.display = n ? '' : 'none';+ if (da) da.style.display = n ? '' : 'none';syncCheckAllBtn();}// 全选按钮:根据当前是否全选切换图标(勾选框 空/勾选 两种状态)与文案@@ -5646,6 +6188,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {openDeleteModal(ids);});}+ var delAllBtn = sessionsPane.querySelector('#wbs-sess-delete-all');+ if (delAllBtn) {+ delAllBtn.addEventListener('click', function () {+ var ids = selectedSessIds();+ if (!ids.length) { toast('请先勾选要删除的会话', true, root); return; }+ openDeleteModal(ids, true);+ });+ }// 取消(退出批量模式,恢复工具栏右侧按钮)var doneBtn = sessionsPane.querySelector('#wbs-sess-done');if (doneBtn) {@@ -5665,6 +6215,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var mask = sessionsPane.querySelector('#wbs-sess-modal');if (mask) {mask.addEventListener('click', function (e) { if (e.target === mask) showSessModal(false); });+ mask.addEventListener('keydown', function (e) {+ e.stopPropagation();+ if (e.key === 'Escape') { e.preventDefault(); showSessModal(false); }+ if (e.key === 'Tab') {+ var controls = mask.querySelectorAll('button:not(:disabled),select:not(:disabled),input:not(:disabled)');+ var first = controls[0], last = controls[controls.length - 1];+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }+ }+ });}}// 迁移弹窗:选目标账号@@ -5673,6 +6233,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var titleEl = sessionsPane.querySelector('#wbs-sess-modal-title');var body = sessionsPane.querySelector('#wbs-sess-modal-body');var okBtn = sessionsPane.querySelector('#wbs-sess-modal-ok');+ okBtn.textContent = '确定';+ okBtn.disabled = false;titleEl.textContent = '复制 ' + ids.length + ' 个会话到…';api('/api/accounts').then(function (d) {var accts = (d && d.accounts) || [];@@ -5715,27 +6277,50 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {});}// 删除弹窗:确认框(真实删除,弹窗内警示不可恢复)- function openDeleteModal(ids) {+ function openDeleteModal(ids, allAccounts) {+ ids = ids.slice();var titleEl = sessionsPane.querySelector('#wbs-sess-modal-title');var body = sessionsPane.querySelector('#wbs-sess-modal-body');var okBtn = sessionsPane.querySelector('#wbs-sess-modal-ok');- titleEl.textContent = '删除 ' + ids.length + ' 个会话?';- body.innerHTML = '<div class="wbs-modal-warn">删除后会话将从列表中移除,本账号的会话与其自动复制到其他账号的同源副本(本地消息文件)都将被永久删除,此操作不可恢复。</div>';+ var cancelBtn = sessionsPane.querySelector('#wbs-sess-modal-cancel');+ var confirmed = !allAccounts;+ var pending = false;+ titleEl.textContent = allAccounts ? '删除所有账号的同源会话?' : '删除 ' + ids.length + ' 个会话?';+ body.innerHTML = allAccounts+ ? '<p>已选 ' + ids.length + ' 个会话</p><div class="wbs-modal-warn">将永久删除所选会话,以及已关联到其他账号的所有同源副本、消息文件和本地缓存。此操作不可恢复。</div>'+ : '<div class="wbs-modal-warn">删除后会话将从列表中移除,本账号的会话与其自动复制到其他账号的同源副本(本地消息文件)都将被永久删除,此操作不可恢复。</div>';+ okBtn.textContent = allAccounts ? '继续确认' : '确定';+ okBtn.disabled = false;showSessModal(true);- okBtn.onclick = function () {+ var submit = function () {+ if (pending) return;+ if (!confirmed) {+ confirmed = true;+ titleEl.textContent = '再次确认永久删除';+ okBtn.textContent = '永久删除';+ cancelBtn.focus();+ return;+ }+ pending = true;+ okBtn.disabled = true;api('/api/sessions/delete', {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ ids: ids }),}).then(function (d) {var extra = (d && d.cascaded) ? ',含其他账号副本 ' + d.cascaded + ' 个' : '';- toast('已删除 ' + ((d && d.deleted) || ids.length) + ' 个会话' + extra, false, root);- showSessModal(false);+ toast('已删除 ' + ((d && typeof d.deleted === 'number') ? d.deleted : ids.length) + ' 个会话' + extra, false, root);+ if (okBtn.onclick === submit) showSessModal(false);loadSessions();}).catch(function (e) {toast('删除失败: ' + (e.message || e), true, root);+ }).finally(function () {+ pending = false;+ if (okBtn.onclick === submit) okBtn.disabled = false;});};+ okBtn.onclick = submit;+ cancelBtn.focus();}function selectedSessIds() {return sessionsState.list.filter(function (s) { return sessionsState.selected[s.id]; }).map(function (s) { return s.id; });@@ -5743,6 +6328,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function showSessModal(show) {var mask = sessionsPane.querySelector('#wbs-sess-modal');if (mask) mask.style.display = show ? '' : 'none';+ if (!show) {+ var okBtn = sessionsPane.querySelector('#wbs-sess-modal-ok');+ if (okBtn) okBtn.onclick = null;+ }}// ===== 模型 pane(当前模型 + WorkDaddy 本地备份) =====@@ -5877,7 +6466,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {: (source.available ? '只导入当前不存在的模型,同名模型保留当前配置' : '未找到模型配置文件');var label = source.shared ? '模型配置已共用' : '从 ' + esc(source.name) + ' 导入';return '<button class="wbs-sess-bbtn wbs-model-import" type="button" data-model-import="' + escAttr(source.profileId) + '" title="' + escAttr(title) + '"' + disabled + '>' + label + '</button>';- }).join('');+ }).join('') + '<span class="wbs-model-third-party"><button class="wbs-sess-bbtn" id="wbs-model-third-party" type="button" aria-haspopup="menu" aria-expanded="false">从第三方导入</button><span class="wbs-model-source-menu" id="wbs-model-source-menu" role="menu" style="display:none"><button type="button" role="menuitem" id="wbs-model-source-cc-switch">CC Switch</button></span></span>';}updateModelCounts();if (modelsState.tab === 'official') {@@ -5925,8 +6514,168 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {mask.onclick = function (event) { if (event.target === mask) close(); };ok.onclick = function () { close(); onConfirm(); };}+ function closeThirdPartyMenu() {+ var menu = modelsPane.querySelector('#wbs-model-source-menu');+ var button = modelsPane.querySelector('#wbs-model-third-party');+ if (menu) menu.style.display = 'none';+ if (button) button.setAttribute('aria-expanded', 'false');+ }+ function openThirdPartyModels(data) {+ var prior = modelsPane.querySelector('#wbs-model-third-party-modal');+ if (prior) prior.remove();+ var mask = document.createElement('div');+ mask.className = 'wbs-modal-mask';+ mask.id = 'wbs-model-third-party-modal';+ mask.innerHTML = '<div class="wbs-modal wbs-model-import-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-model-import-title"><div class="wbs-modal-title" id="wbs-model-import-title">从 CC Switch 导入模型</div><div class="wbs-modal-body"></div><div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" data-third-cancel>取消</button><button class="wbs-modal-btn wbs-modal-ok" type="button" data-third-ok>确定</button></div></div>';+ modelsPane.appendChild(mask);+ var body = mask.querySelector('.wbs-modal-body');+ var title = mask.querySelector('.wbs-modal-title');+ var ok = mask.querySelector('[data-third-ok]');+ var cancel = mask.querySelector('[data-third-cancel]');+ // The preview contains only importable models. It no longer has an available flag.+ var rows = Array.isArray(data.models) ? data.models : [];+ var groups = [];+ rows.forEach(function (row) {+ var key = row.providerKey || row.key;+ var group = groups.find(function (item) { return item.key === key; });+ if (!group) { group = { key: key, provider: row.provider || row.name, appType: row.appType, rows: [] }; groups.push(group); }+ group.rows.push(row);+ });+ var appNames = { claude: 'Claude Code', codex: 'Codex', gemini: 'Gemini', opencode: 'OpenCode', openclaw: 'OpenClaw' };+ var apps = Object.keys(appNames).filter(function (app) { return groups.some(function (group) { return group.appType === app; }); });+ var activeApp = apps[0] || '';+ var visibleGroups = function () { return groups.filter(function (group) { return group.appType === activeApp; }); };+ var chosen = {};+ groups.forEach(function (group) { chosen[group.key] = true; });+ var step = 'select', pending = false;+ var selectedGroups = function () { return visibleGroups().filter(function (group) { return chosen[group.key]; }); };+ var selectedIds = function () { return selectedGroups().reduce(function (ids, group) { return ids.concat(group.rows.map(function (row) { return row.key; })); }, []); };+ var close = function () {+ if (pending) return;+ mask.remove();+ var trigger = modelsPane.querySelector('#wbs-model-third-party');+ if (trigger) trigger.focus();+ };+ var updateCount = function () {+ var count = selectedGroups().length;+ var all = body.querySelector('[data-third-all]');+ var total = visibleGroups().length;+ if (all) { all.checked = total > 0 && count === total; all.indeterminate = count > 0 && count < total; all.disabled = !total; }+ var label = body.querySelector('[data-third-count]');+ if (label) label.textContent = '已选 ' + count + ' / ' + total;+ ok.disabled = !count;+ };+ body.innerHTML = '<div class="wbs-third-toolbar"><select class="wbs-sess-select" data-third-app aria-label="来源客户端">' + apps.map(function (app) { return '<option value="' + escAttr(app) + '">' + esc(appNames[app]) + '</option>'; }).join('') + '</select><label class="wbs-third-all"><input type="checkbox" data-third-all><span>全选</span><span data-third-count></span></label></div><div data-third-list></div>';+ var renderGroups = function () {+ var visible = visibleGroups();+ body.querySelector('[data-third-list]').innerHTML = visible.length ? visible.map(function (group) {+ var credentials = [];+ group.rows.forEach(function (row) {+ if (!credentials.some(function (item) { return item.url === row.url && item.apiKey === row.apiKey; })) credentials.push(row);+ });+ return '<label class="wbs-third-row"><input type="checkbox" data-third-key="' + escAttr(group.key) + '"' + (chosen[group.key] ? ' checked' : '') + '><span class="wbs-third-text"><strong>' + esc(group.provider || '未命名供应商') + '</strong><span>' + esc(group.rows.map(function (row) { return row.id; }).join(' / ')) + '</span>' + credentials.map(function (row) { return (row.url ? '<span>' + esc(row.url) + '</span>' : '') + (row.apiKey ? '<span>apiKey:' + esc(row.apiKey) + '</span>' : ''); }).join('') + '</span></label>';+ }).join('') : '<div class="wbs-empty">未找到可导入的模型配置</div>';+ updateCount();+ };+ renderGroups();+ body.onchange = function (event) {+ if (pending) return;+ var input = event.target;+ if (input.hasAttribute('data-third-app')) {+ activeApp = input.value;+ renderGroups();+ return;+ }+ if (input.hasAttribute('data-third-all')) {+ visibleGroups().forEach(function (group) { chosen[group.key] = input.checked; });+ body.querySelectorAll('[data-third-key]').forEach(function (box) { box.checked = input.checked; });+ } else if (input.hasAttribute('data-third-key')) chosen[input.getAttribute('data-third-key')] = input.checked;+ updateCount();+ };+ cancel.onclick = close;+ mask.addEventListener('click', function (event) { event.stopPropagation(); if (event.target === mask) close(); });+ ['pointerdown', 'mousedown', 'keyup'].forEach(function (name) { mask.addEventListener(name, function (event) { event.stopPropagation(); }); });+ mask.addEventListener('keydown', function (event) {+ event.stopPropagation();+ if (event.key === 'Escape') { event.preventDefault(); close(); }+ if (event.key === 'Tab') {+ var controls = Array.from(mask.querySelectorAll('button:not(:disabled),select:not(:disabled),input:not(:disabled)'));+ var first = controls[0], last = controls[controls.length - 1];+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }+ }+ });+ ok.onclick = function () {+ if (pending) return;+ var ids = selectedIds();+ if (!ids.length) return;+ pending = true;+ ok.disabled = true;+ cancel.disabled = true;+ body.querySelectorAll('input,select').forEach(function (input) { input.disabled = true; });+ ok.textContent = '导入中…';+ api('/api/models/third-party/import', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ snapshot: data.snapshot, ids: ids, confirmed: step === 'confirm' }) })+ .then(function (result) {+ pending = false;+ if (result.confirmationRequired) {+ step = 'confirm';+ mask.querySelector('.wbs-modal').classList.add('wbs-model-import-confirm');+ title.textContent = '确认覆盖同名模型?';+ body.onchange = null;+ body.textContent = (result.replaced ? '将覆盖 ' + result.replaced + ' 个现有模型。' : '') ++ (result.duplicateIds ? '所选配置中有 ' + result.duplicateIds + ' 个重复模型 ID,当前模型将采用最后一项。' : '') ++ '导入前会自动备份,所选配置也会保存到「备选模型」。';+ ok.disabled = false;+ cancel.disabled = false;+ ok.textContent = '确认导入';+ cancel.focus();+ return;+ }+ close();+ toast('已导入 ' + result.imported + ' 个模型' + (result.replaced ? ',覆盖 ' + result.replaced + ' 个现有模型' : '') + ',所选配置已保存到「备选模型」', false, root);+ loadModels();+ }).catch(function (error) {+ pending = false;+ ok.disabled = false;+ cancel.disabled = false;+ body.querySelectorAll('input,select').forEach(function (input) { input.disabled = false; });+ ok.textContent = step === 'confirm' ? '确认导入' : '确定';+ toast(error.message || '导入失败,请重新读取模型列表', true, root);+ });+ };+ cancel.focus();+ }function wireModelsPane() {+ listen(document, 'click', function (event) { if (!event.target.closest || !event.target.closest('.wbs-model-third-party')) closeThirdPartyMenu(); });+ modelsPane.addEventListener('keydown', function (event) {+ var menu = modelsPane.querySelector('#wbs-model-source-menu');+ if (event.key === 'Escape' && menu && menu.style.display !== 'none') {+ event.preventDefault(); event.stopPropagation(); closeThirdPartyMenu();+ modelsPane.querySelector('#wbs-model-third-party').focus();+ }+ });modelsPane.addEventListener('click', function (event) {+ var third = event.target.closest ? event.target.closest('#wbs-model-third-party') : null;+ if (third && !third.disabled) {+ var menu = modelsPane.querySelector('#wbs-model-source-menu');+ if (menu.style.display !== 'none') { closeThirdPartyMenu(); return; }+ third.disabled = true;+ api('/api/models/third-party').then(function (result) {+ if (!(result.sources || []).some(function (source) { return source.id === 'cc-switch'; })) { toast('未检测到 CC Switch 本地模型配置', true, root); return; }+ menu.style.display = '';+ third.setAttribute('aria-expanded', 'true');+ menu.querySelector('button').focus();+ }).catch(function (error) { toast(error.message || '读取第三方配置失败', true, root); }).finally(function () { third.disabled = false; });+ return;+ }+ var cc = event.target.closest ? event.target.closest('#wbs-model-source-cc-switch') : null;+ if (cc && !cc.disabled) {+ closeThirdPartyMenu();+ cc.disabled = true;+ api('/api/models/third-party/preview', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ source: 'cc-switch' }) })+ .then(openThirdPartyModels).catch(function (error) { toast(error.message || '读取 CC Switch 模型失败', true, root); }).finally(function () { cc.disabled = false; });+ return;+ }var tab = event.target.closest ? event.target.closest('.wbs-model-tab') : null;if (tab) { modelsState.tab = tab.getAttribute('data-model-tab') || 'official'; modelsState.batch = false; modelsState.selected = {}; renderModels(); return; }var backup = event.target.closest ? event.target.closest('[data-model-backup]') : null;@@ -6108,8 +6857,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'</div>' +'</div>' +'<div class="wbs-pcard wbs-fab-settings">' ++ '<div class="wbs-pcard-title">悬浮机器人</div>' ++ '<div class="wbs-robot-seg" role="radiogroup" aria-label="机器人外观">' ++ '<label title="白底黑眼"><input type="radio" name="wbs-robot-style" value="white"><span>白色</span></label>' ++ '<label title="黑底白眼"><input type="radio" name="wbs-robot-style" value="black"><span>黑色</span></label>' ++ '<label title="毛玻璃底与镂空眼睛"><input type="radio" name="wbs-robot-style" value="glass"><span>毛玻璃</span></label>' ++ '</div>' +'<div class="wbs-ask-row">' +- '<label class="wbs-ask-label" for="wbs-fab-auto-dock">机器人自动停靠<span class="wbs-ask-hint">闲置 5 秒后收起到窗口右侧,鼠标靠近边缘展开</span></label>' ++ '<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">' +@@ -6136,7 +6891,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<input type="range" id="wbs-bg-blur-range" min="0" max="100" step="1" value="0">' +'<span class="wbs-mask-val" id="wbs-bg-blur-val">0%</span>' +'</div>' +- '</div>';+ '</div>' ++ '<div class="wbs-pcard" 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>' ++ '</div></div>';wireThemePane();}// 增强 pane(构建:决策弹窗 + 开发者工具[默认隐藏,连点标题5次呼出])@@ -6312,7 +7072,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-update-bar" id="wbs-update-bar" style="display:none;height:6px;border-radius:3px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 22%,transparent);overflow:hidden;margin-top:8px"><i id="wbs-update-bar-fill" style="display:block;height:100%;width:0;border-radius:3px;background:var(--wb-button-primary-bg,#1f1f1f);transition:width .6s ease"></i></div>' +'</div>' +'<div class="wbs-pcard wbs-about-hero">' +- '<div class="wbs-about-name-row"><div class="wbs-about-name" id="wbs-about-name">' + WBS_BRAND + '</div><span class="wbs-about-ver" id="wbs-about-ver">' + esc('') + '</span></div>' ++ '<div class="wbs-about-name-row"><span class="wbs-about-brand"><img class="wbs-about-logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDI0IiBoZWlnaHQ9IjEwMjQiIHZpZXdCb3g9IjAgMCAxMDI0IDEwMjQiIGZpbGw9Im5vbmUiPgogIDwhLS0gU3F1YXJlIG1hc3RlciwgYmFzZWQgb24gdGhlIHdlYnNpdGUncyBvcmlnaW5hbCBmbG9hdGluZyByb2JvdC4gLS0+CiAgPGRlZnM+CiAgICA8bGluZWFyR3JhZGllbnQgaWQ9ImJhY2tncm91bmQiIHgxPSIxNjAiIHkxPSIwIiB4Mj0iODkwIiB5Mj0iMTEwMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgogICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjMzQzNjNkIi8+PHN0b3Agb2Zmc2V0PSIuNSIgc3RvcC1jb2xvcj0iIzE3MTgxZCIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzA1MDUwNiIvPgogICAgPC9saW5lYXJHcmFkaWVudD4KICAgIDxsaW5lYXJHcmFkaWVudCBpZD0ic2hlbGwtc2lkZSIgeDE9IjQ5MCIgeTE9IjMxNSIgeDI9Ijg4NSIgeTI9IjkxMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgogICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjZTNlNmRhIi8+PHN0b3Agb2Zmc2V0PSIuNDgiIHN0b3AtY29sb3I9IiNiNWJkYWUiLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM4Yjk3ODUiLz4KICAgIDwvbGluZWFyR3JhZGllbnQ+CiAgICA8cmFkaWFsR3JhZGllbnQgaWQ9InNoZWxsIiBjeD0iMCIgY3k9IjAiIHI9IjEiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzAxIDM5MSkgcm90YXRlKDQ4KSBzY2FsZSg3NjIgOTA5KSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgogICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjZmZmZWY3Ii8+PHN0b3Agb2Zmc2V0PSIuNDgiIHN0b3AtY29sb3I9IiNlZWVlZTkiLz48c3RvcCBvZmZzZXQ9Ii44MyIgc3RvcC1jb2xvcj0iI2RjZTBkNCIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI2I3YzBhYyIvPgogICAgPC9yYWRpYWxHcmFkaWVudD4KICAgIDxsaW5lYXJHcmFkaWVudCBpZD0iYW50ZW5uYSIgeDE9IjQ2MSIgeTE9IjE1NyIgeDI9IjUwNiIgeTI9IjMxMiIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgogICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjZmZmZWY3Ii8+PHN0b3Agb2Zmc2V0PSIuNiIgc3RvcC1jb2xvcj0iI2VlZWVlOSIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI2JhYzNiMCIvPgogICAgPC9saW5lYXJHcmFkaWVudD4KICAgIDxsaW5lYXJHcmFkaWVudCBpZD0iZXllcyIgeDE9IjI4MCIgeTE9IjQyMCIgeDI9IjU1OCIgeTI9IjYxMCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgogICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjNDY1NDQzIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjNjg3MjY3Ii8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogICAgPGxpbmVhckdyYWRpZW50IGlkPSJyaW0iIHgxPSIzMTEiIHkxPSIyOTUiIHgyPSI3OTYiIHkyPSI4NzgiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KICAgICAgPHN0b3Agc3RvcC1jb2xvcj0iI2ZmZiIgc3RvcC1vcGFjaXR5PSIuODUiLz48c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNmZmYiIHN0b3Atb3BhY2l0eT0iLjA0Ii8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogICAgPGZpbHRlciBpZD0icm9ib3Qtc2hhZG93IiB4PSItMzAlIiB5PSItMzAlIiB3aWR0aD0iMTcwJSIgaGVpZ2h0PSIxODAlIj4KICAgICAgPGZlRHJvcFNoYWRvdyBkeD0iOCIgZHk9IjI3IiBzdGREZXZpYXRpb249IjIyIiBmbG9vZC1jb2xvcj0iIzI0MzMxZiIgZmxvb2Qtb3BhY2l0eT0iLjI1Ii8+CiAgICA8L2ZpbHRlcj4KICA8L2RlZnM+CiAgPGRlZnM+PGNsaXBQYXRoIGlkPSJhcHAtbWFzayI+PHBhdGggZD0iTTM2MCAwSDY2NEM3OTAgMCA4NTMgMCA5MDEgMjRDOTQ0IDQ2IDk3OCA4MCAxMDAwIDEyM0MxMDI0IDE3MSAxMDI0IDIzNCAxMDI0IDM2MFY2NjRDMTAyNCA3OTAgMTAyNCA4NTMgMTAwMCA5MDFDOTc4IDk0NCA5NDQgOTc4IDkwMSAxMDAwQzg1MyAxMDI0IDc5MCAxMDI0IDY2NCAxMDI0SDM2MEMyMzQgMTAyNCAxNzEgMTAyNCAxMjMgMTAwMEM4MCA5NzggNDYgOTQ0IDI0IDkwMUMwIDg1MyAwIDc5MCAwIDY2NFYzNjBDMCAyMzQgMCAxNzEgMjQgMTIzQzQ2IDgwIDgwIDQ2IDEyMyAyNEMxNzEgMCAyMzQgMCAzNjAgMFoiLz48L2NsaXBQYXRoPjwvZGVmcz4KICA8ZyBjbGlwLXBhdGg9InVybCgjYXBwLW1hc2spIj4KICA8cmVjdCB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIxMDI0IiBmaWxsPSJ1cmwoI2JhY2tncm91bmQpIi8+CiAgPCEtLSBLZWVwIHRoZSBjb21wYWN0IHJvdW5kZWQtc3F1YXJlIHNoZWxsLCBzaW5nbGUgYW50ZW5uYSwgYW5kIHR3byB1cHJpZ2h0IGV5ZXMuIC0tPgogIDxnIHRyYW5zZm9ybT0icm90YXRlKDggNTEyIDU0MCkiIGZpbHRlcj0idXJsKCNyb2JvdC1zaGFkb3cpIj4KICAgIDxyZWN0IHg9IjQ0OCIgeT0iMjAxIiB3aWR0aD0iNDciIGhlaWdodD0iMTI0IiByeD0iMjMuNSIgZmlsbD0idXJsKCNhbnRlbm5hKSIvPgogICAgPGNpcmNsZSBjeD0iNDcxLjUiIGN5PSIxODgiIHI9IjQyIiBmaWxsPSJ1cmwoI2FudGVubmEpIi8+CiAgICA8cmVjdCB4PSIxNTUiIHk9IjMxNCIgd2lkdGg9IjcyNSIgaGVpZ2h0PSI2MDQiIHJ4PSIxNTUiIGZpbGw9InVybCgjc2hlbGwtc2lkZSkiLz4KICAgIDxyZWN0IHg9IjExNiIgeT0iMjkyIiB3aWR0aD0iNzIwIiBoZWlnaHQ9IjYwNCIgcng9IjE1NCIgZmlsbD0idXJsKCNzaGVsbCkiLz4KICAgIDxyZWN0IHg9IjEyMCIgeT0iMjk2IiB3aWR0aD0iNzEyIiBoZWlnaHQ9IjU5NiIgcng9IjE1MCIgc3Ryb2tlPSJ1cmwoI3JpbSkiIHN0cm9rZS13aWR0aD0iOCIvPgogICAgPCEtLSBTaGlmdCB0aGUgb3JpZ2luYWwgZXllcyB1cCBhbmQgbGVmdCBpbnN0ZWFkIG9mIGNoYW5naW5nIHRoZSBjaGFyYWN0ZXIuIC0tPgogICAgPHJlY3QgeD0iMjU5IiB5PSI0MzAiIHdpZHRoPSI5OSIgaGVpZ2h0PSIxNTgiIHJ4PSI0OS41IiBmaWxsPSIjZmZmIiBmaWxsLW9wYWNpdHk9Ii42Ii8+CiAgICA8cmVjdCB4PSIyNTkiIHk9IjQyNSIgd2lkdGg9Ijk5IiBoZWlnaHQ9IjE1OCIgcng9IjQ5LjUiIGZpbGw9InVybCgjZXllcykiLz4KICAgIDxyZWN0IHg9IjQ2OSIgeT0iNDMwIiB3aWR0aD0iMTA4IiBoZWlnaHQ9IjE2MiIgcng9IjU0IiBmaWxsPSIjZmZmIiBmaWxsLW9wYWNpdHk9Ii42Ii8+CiAgICA8cmVjdCB4PSI0NjkiIHk9IjQyNSIgd2lkdGg9IjEwOCIgaGVpZ2h0PSIxNjIiIHJ4PSI1NCIgZmlsbD0idXJsKCNleWVzKSIvPgogIDwvZz4KICA8L2c+Cjwvc3ZnPgo=" alt="" width="32" height="32"><span class="wbs-about-name" id="wbs-about-name">' + WBS_BRAND + '</span></span><span class="wbs-about-ver" id="wbs-about-ver">' + esc('') + '</span></div>' +'<span class="wbs-about-badge" id="wbs-about-badge">本机回环 CDP 注入 · 不改官方安装包</span>' +'<div class="wbs-about-desc">一个基于 <b>Chrome DevTools Protocol (CDP)</b> 的 WorkBuddy 桌面端增强工具。零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。</div>' +'<div class="wbs-about-support">' +@@ -6337,7 +7097,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'</div>' +'<div class="wbs-pcard wbs-telemetry-card" id="wbs-telemetry-card">' +'<div class="wbs-telemetry-head">' +- '<div class="wbs-telemetry-label"><span class="wbs-pcard-title">发送错误诊断</span><span class="wbs-telemetry-help" tabindex="0" aria-label="查看错误诊断说明"><svg viewBox="0 0 20 20" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="10" cy="10" r="8"/><path d="M8.4 7.6a1.8 1.8 0 1 1 2.8 1.45c-.75.48-1.2.85-1.2 1.75M10 13.7v.1"/></svg><span class="wbs-telemetry-tooltip" role="tooltip">仅发送经过脱敏、截断的版本、系统和错误信息,不包含账号、会话内容、Token 或 API Key;可随时关闭。</span></span></div>' ++ '<div class="wbs-telemetry-label"><span class="wbs-pcard-title">发送错误诊断</span><span class="wbs-telemetry-help" tabindex="0" aria-label="查看错误诊断说明"><svg viewBox="0 0 20 20" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="10" cy="10" r="8"/><path d="M8.4 7.6a1.8 1.8 0 1 1 2.8 1.45c-.75.48-1.2.85-1.2 1.75M10 13.7v.1"/></svg><span class="wbs-telemetry-tooltip" role="tooltip">发送脱敏错误诊断,并统计匿名安装数和日活(随机安装标识、系统、架构、版本、客户端类型及出口国家)。不包含账号、会话内容、Token 或 API Key;关闭后停止上报。</span></span></div>' +'<div class="wbs-telemetry-ctrl"><span class="wbs-telemetry-reco">推荐开启</span>' +'<label class="wbs-switch wbs-telemetry-switch" title="发送经过脱敏的错误诊断"><input type="checkbox" id="wbs-telemetry-switch" aria-label="发送错误诊断"><span class="wbs-switch-slider"></span></label>' +'</div>' +@@ -6407,6 +7167,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var status = aboutPane.querySelector('#wbs-telemetry-status');if (!toggle || !status) return;function renderTelemetryState(enabled, managed) {+ WBS_DIAGNOSTICS_ENABLED = !!enabled;+ if (enabled) usageActivity.notify();toggle.checked = !!enabled;toggle.disabled = !managed;// 管理范围内:开关左侧固定展示「推荐开启」,不再显示已开启/已关闭动态文案@@ -6739,11 +7501,37 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!card) return;var visible = themeId === 'nebula';card.style.display = visible ? '' : 'none';+ var textCard = themePane.querySelector('#wbs-text-shadow-card');+ if (textCard) textCard.style.display = visible ? '' : 'none';if (visible) loadWallpapers();}// 主题 pane 事件绑定(元素在 buildThemePane 之后才存在,延迟到首次切换时绑定)function wireThemePane() {+ themePane.querySelectorAll('input[name="wbs-robot-style"]').forEach(function (input) {+ input.checked = input.value === fabAppearance.get();+ input.addEventListener('change', function () {+ if (input.checked) fabAppearance.set(input.value);+ });+ });+ var shadowSwitch = themePane.querySelector('#wbs-text-shadow');+ if (shadowSwitch) {+ shadowSwitch.addEventListener('change', function () {+ var enabled = shadowSwitch.checked;+ shadowSwitch.disabled = true;+ api('/api/theme-text-shadow', {+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled: enabled }),+ }).then(function (d) { shadowSwitch.checked = d.enabled; }).catch(function (e) {+ shadowSwitch.checked = !enabled;+ toast('文字阴影设置失败: ' + (e.message || e), true, root);+ }).finally(function () { shadowSwitch.disabled = false; });+ });+ api('/api/theme-text-shadow').then(function (d) {+ shadowSwitch.checked = d.enabled;+ }).catch(function (e) {+ toast('读取文字阴影失败: ' + (e.message || e), true, root);+ }).finally(function () { shadowSwitch.disabled = false; });+ }var dockSwitch = themePane.querySelector('#wbs-fab-auto-dock');if (dockSwitch) {dockSwitch.checked = fabQuietMode.isEnabled();@@ -7051,12 +7839,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function setOpen(open, options) {+ if (open && typeof closeRotationNotice === 'function') closeRotationNotice();if (open && window.__wbsAutomationInputActive) {toast('正在输入或切换账号,请稍后打开面板', false, root);return;}var newlyOpened = open && !state.open;- // 面板还不可见时应用最新到期顺序;本次打开期间只更新数值,不移动账号。+ // 面板还不可见时应用最新到期顺序;首次加载/切换后的积分批次另行校正一次。if (newlyOpened && CAPS.accounts) {state.activityRetryUsed = false;sortAccountsByCreditExpiry();@@ -7377,22 +8166,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 他人环境没有该文件 → 按钮点击时 __wbsStartPicked 不存在 → toast 报错即可,不影响其他功能。var piTitle = root.querySelector('#wbs-title');var piPickBtn = root.querySelector('#wbs-pick-btn');- var piClickCount = 0;- var piClickTimer = null;if (piTitle) {- piTitle.addEventListener('click', function () {- piClickCount += 1;- clearTimeout(piClickTimer);- piClickTimer = setBuildTimeout(function () { piClickCount = 0; }, 1200);- if (piClickCount >= 5) {- piClickCount = 0;+ var brandClicks = createBrandClickAction({+ setTimeout: setBuildTimeout, clearTimeout: function (id) { clearTimeout(id); },+ openWebsite: function () {+ api('/api/open-url', { method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ url: 'https://www.workdaddy.dev' })+ }).catch(function (e) { toast('打开官网失败: ' + (e.message || e), true, root); });+ },+ unlockDebug: function () {hiddenToolsUnlocked = true;if (piPickBtn) piPickBtn.style.display = '';var monitorLogCard = aboutPane && aboutPane.querySelector('#wbs-monitor-log-card');if (monitorLogCard) monitorLogCard.style.display = '';try { toast('隐藏工具已呼出', false, root); } catch (_) {}- }+ },});+ listen(piTitle, 'click', function (event) { event.preventDefault(); brandClicks.click(); });+ registerDisposer(brandClicks.destroy);}if (piPickBtn) {piPickBtn.addEventListener('click', function () {@@ -8592,6 +9383,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (c.judgedMessages.has(signature)) return;var idleFor = Date.now() - c.controllerIdleAt;var controllerCompleted = autoContinueControllerCompleted(snap);+ // A completed flag can appear when the assistant row is created, before+ // its reply text arrives. Account rotation must wait for an actual reply.+ if (controllerCompleted && !String(snap.text || '').trim()) {+ acScheduleSettle(350);+ return;+ }// 明确 terminal(或旧版无 terminal 字段时的 complete)是可靠终局,可立即判定;错误也只需短缓冲;// 其余 incomplete 空闲等待 8 秒,避免 state 与最后一个消息 chunk 存在极短时序差。if (!controllerCompleted && !snap.error && idleFor < AC_CONTROLLER_SETTLE_MS) {@@ -8612,6 +9409,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {c.judgedMessages.add(signature);if (!decision.trigger) {acLog('controller-completed', { id: snap.assistantId, reason: decision.reason, complete: snap.complete, terminal: snap.terminal });+ if (controllerCompleted) checkCreditRotationAfterSession();return;}if (snap.manualStop) { acLog('controller-user-cancelled-skip', { id: snap.assistantId }); return; }@@ -9210,6 +10008,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (session.judgedMessages.has(signature)) return;var idleFor = Date.now() - session.idleAt;var completed = autoContinueControllerCompleted(snapshot);+ if (completed && !String(snapshot.text || '').trim()) {+ acMultiSchedule(session, 350);+ return;+ }if (!completed && !snapshot.error && idleFor < AC_CONTROLLER_SETTLE_MS) {acMultiUpdateStatus(session, 'settling', { idleForMs: idleFor });acMultiSchedule(session, Math.max(250, AC_CONTROLLER_SETTLE_MS - idleFor));@@ -9228,6 +10030,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {session.judgedMessages.add(signature);if (!decision.trigger) {acMultiFinishSession(session);+ if (completed && !session.rotationNotified) {+ session.rotationNotified = true;+ checkCreditRotationAfterSession();+ }return;}if (snapshot.manualStop) {@@ -9959,6 +10765,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// reinject/刷新时销毁监控,避免叠加 observer/timerregisterDisposer(function () {+ closeRotationNotice();acRunning = false;if (acThemeObserver) { try { acThemeObserver.disconnect(); } catch (e) {} acThemeObserver = null; }acStopMonitor();@@ -10033,17 +10840,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 它们只有「确认/始终允许/拒绝」,没有独立「允许」选项,天然不命中)。// 注意(1.0.16):WorkBuddy AI 拦截卡选项按钮文本带序号前缀(如「1允许」「2本次会话内始终允许」),// once 匹配必须先规范化(去序号);文件拦截文案是「检测到受保护文件修改」等,已补进关键词表。- var ND_CONFIRM_PATTERN = /批量删除|沙箱|越界|越权|系统级工具|系统工具|权限|允许访问|将运行|需要你确认|需要你的确认|确认允许|检测到|受保护|敏感|凭据|黑名单|sandbox|approval|permission/i;- var ND_CREDIT_PATTERN = /积分|信用|credit|消耗|付费|支付|费用|金额|余额|扣费/i;- var ND_DENY_WORD = /拒绝|Deny/i;- var ND_ONCE_LABEL = /^(允许|允许一次|Allow|Yes|同意|批准|确认允许)$/i;+ // 注意(WorkBuddy 5.5.4):敏感凭据路径不再走沙箱拦截卡,而走独立的+ // 「敏感凭证保护」卡(interceptType=sensitive-protection),其允许选项文案是+ // 「允许访问」/「允许加密访问(推荐)」,且 ingress-protect-only 场景下只有后者——+ // 旧规则只认精确的「允许」,这类卡会一直挂着不点。文案表已补齐(见 ND_ALLOW_ONCE_LABELS)。+ // 该卡同样是 <button> + 序号 span + 文案 span,结构与沙箱拦截卡一致,无需额外选择器适配。+ // 文案表统一取自顶层常量(ND_*_HINTS / ND_ALLOW_*_LABELS),此处只做局部别名,+ // 避免扫描逻辑与纯函数判定各写一份正则后再次漂移。+ var ND_CONFIRM_PATTERN = ND_CONFIRM_HINTS;+ var ND_CREDIT_PATTERN = ND_CREDIT_HINTS;+ var ND_DENY_WORD = ND_DENY_HINTS;+ var ND_ONCE_LABEL = ND_ALLOW_ONCE_LABELS;function ndNormalizeLabel(t) {return String(t || '').trim().replace(/^\d+\s*/g, '');}// 容器是否构成「允许+拒绝」决策组:含 ≥2 个按钮,且其中一个是精确 once 允许选项function ndIsDecisionGroup(box) {var opts = box.querySelectorAll('button');- if (!opts || opts.length < 2 || opts.length > 12) return false;+ if (!opts || opts.length < 2 || opts.length > ND_MAX_DECISION_BUTTONS) return false;for (var i = 0; i < opts.length; i++) {if (ND_ONCE_LABEL.test(ndNormalizeLabel(opts[i].textContent || ''))) return true;}@@ -10053,12 +10867,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (typeof classifyNoDisturbApprovalCandidate === 'function') return classifyNoDisturbApprovalCandidate(value);var input = value || {};var label = String(input.label || '').trim().replace(/^\d+\s*/, '');- var kind = /始终允许|Always\s*allow/i.test(label) ? 'session' :- (/^(允许|允许一次|Allow|Yes|同意|批准|确认允许)$/i.test(label) || (/^Yes/i.test(label) && label.length < 24) ? 'once' : null);+ var kind = ND_ALLOW_SESSION_LABELS.test(label) ? 'session' :+ (ND_ALLOW_ONCE_LABELS.test(label) || (/^Yes/i.test(label) && label.length < 24) ? 'once' : null);if (!kind || input.disabled || input.ariaDisabled) return null;var context = String(input.context || '').slice(0, 700);if (input.creditSeen || ND_CREDIT_PATTERN.test(context)) return null;- return ND_CONFIRM_PATTERN.test(context) || (input.hasDeny === true && input.hasOnce === true && input.buttonCount >= 2 && input.buttonCount <= 12) ? kind : null;+ return ND_CONFIRM_PATTERN.test(context) || (input.hasDeny === true && input.hasOnce === true && input.buttonCount >= 2 && input.buttonCount <= ND_MAX_DECISION_BUTTONS) ? kind : null;}function ndSessionIdForNode(node) {try {@@ -10072,24 +10886,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var hasDeny = false;var count = 0;var creditSeen = false;- var creditBox = button;- for (var creditDepth = 0; creditDepth < 8 && creditBox; creditDepth++) {- creditBox = creditBox.parentElement;- if (creditBox && ND_CREDIT_PATTERN.test(String(creditBox.textContent || '').slice(0, 700))) {- creditSeen = true;- break;- }- }for (var depth = 0; depth < 8 && box; depth++) {box = box.parentElement;if (!box) break;+ var buttons = box.querySelectorAll('button');+ count = buttons ? buttons.length : 0;+ // 逃出卡片就停:祖先容器(消息列表 / BODY)按钮数量必然远超卡片量级。+ // 必须停,否则:① 祖先文本前 700 字里出现「积分/费用/金额」等词,会把整个候选+ // 误判成扣费弹窗而永不点击(历史故障:弹窗一个都点不动);② 关键词命中变成+ // 「整段会话开头恰好含关键词」的碰运气。+ if (count > ND_MAX_DECISION_BUTTONS) break;var current = String(box.textContent || '');if (current.length > 700) current = current.slice(0, 700);text = current;if (ND_CREDIT_PATTERN.test(current)) creditSeen = true;hasDeny = ND_DENY_WORD.test(current);- var buttons = box.querySelectorAll('button');- count = buttons ? buttons.length : 0;var hasOnce = ndIsDecisionGroup(box);var kind = ndClassifyApprovalCandidate({label: button.textContent || '',@@ -10478,7 +11289,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function accountCardLayoutKey() {// 积分/签到刷新不应重建切换按钮,保留焦点和两击确认状态。var rows = state.accounts.map(function (a) {- return [a.uid, a.nickname, a.phone, a.uin, a.type, a.enterpriseName, a.tokenExpiresAt, isIdentityExpired(a)];+ return [a.uid, a.nickname, a.phone, a.uin, a.type, a.enterpriseName, a.tokenExpiresAt, a.authValid, isIdentityExpired(a)];}).sort(function (a, b) { return String(a[0]).localeCompare(String(b[0])); });return JSON.stringify([state.current && state.current.uid, state.primaryUid, rows]);}@@ -10523,15 +11334,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function render(data) {var previous = state.accounts;+ var currentChanged = previous.length > 0 && (state.current && state.current.uid) !== (data.current && data.current.uid);state.current = data.current;state.accounts = mergeAccountSnapshot(previous, data.accounts || []);state.primaryUid = data.primaryUid || '';- if (!previous.length || !state.open) sortAccountsByCreditExpiry();+ // 页面重载后还没有积分缓存,或刚切换账号:等本轮积分齐备后校正一次顺序。+ if (currentChanged || (!previous.length && state.accounts.some(function (account) { return !Array.isArray(account.creditSegments); }))) {+ state.accountSortPending = true;+ }+ if (!previous.length || !state.open || currentChanged) sortAccountsByCreditExpiry();state.creditRemaining = state.accounts.length;updateAccountSummary();var list = accountsPane.querySelector('.wbs-acct-list');var layoutKey = accountCardLayoutKey();if (list && state.accountLayoutKey === layoutKey) {+ if (!state.open) reorderAccountCards();updateCheckinCells(state.accounts);state.accounts.forEach(function (account) { updateCreditCell(account.uid, account.credits, account.creditSegments); });return;@@ -10556,11 +11373,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var primaryBadge = isPrimary ? '<span class="wbs-primary-mark" role="img" aria-label="主账号" title="主账号">' + PRIMARY_ACCOUNT_SVG + '</span>' : '';var primaryAction = '<button class="wbs-icon-btn wbs-set-primary" type="button" data-primary-uid="' + escAttr(a.uid) + '" title="设为主账号" aria-label="设为主账号"' + (isPrimary ? ' hidden' : '') + '>' + PRIMARY_ACCOUNT_SVG + '</button>';var checkinBadge = checkinBadgeHtml(a);+ var invalidAuthBadge = a.authValid === false ? '<span class="wbs-badge wbs-auth-invalid">认证数据无效</span>' : '';// 当前登录账号隐藏操作;认证已过期的账号保留删除,但隐藏切换,避免进入登录页。var expired = isIdentityExpired(a);var ops = primaryAction + (isCur? ''- : (expired ? '' : '<button class="wbs-icon-btn wbs-acc-switch" type="button" title="切换" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(a.nickname || '未命名') + '">' + SWITCH_SVG + '</button>') ++ : (expired || a.authValid === false ? '' : '<button class="wbs-icon-btn wbs-acc-switch" type="button" title="切换" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(a.nickname || '未命名') + '">' + SWITCH_SVG + '</button>') +'<button class="wbs-icon-btn wbs-del" type="button" title="删除" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(a.nickname || '未命名') + '">' + TRASH_SVG + '</button>');ops = '<div class="wbs-ops"' + (isCur && isPrimary ? ' hidden' : '') + '>' + ops + '</div>';// 国际版没有手机号:用 UIN(账号唯一数字标识)替代展示;国内版仍显示手机。@@ -10573,7 +11391,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>' + primaryBadge + badge + checkinBadge + '</div>' + ops + '</div>' ++ '<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + esc(nameVal) + '</span>' + primaryBadge + badge + checkinBadge + 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>' +@@ -10797,6 +11615,143 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {total.textContent = state.creditSummaryValue === null ? '查询中…' : fmtCredits(state.creditSummaryValue);}+ function rotationToday() {+ var d = new Date();+ return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');+ }++ function closeRotationNotice() {+ var notice = state.rotationNotice;+ if (!notice) return;+ if (notice.timer) clearInterval(notice.timer);+ if (notice.place) window.removeEventListener('resize', notice.place);+ if (notice.node && notice.node.parentNode) notice.node.remove();+ fab.classList.remove('wbs-fab-credit-alert');+ state.rotationNotice = null;+ }++ function showRotationNotice(candidate) {+ if (!candidate || !candidate.uid || state.open || state.rotationNotice) return;+ var today = rotationToday();+ var dismissed = '';+ try { dismissed = localStorage.getItem('wbs-credit-rotation-dismiss-' + PROFILE_ID) || ''; } catch (_) {}+ if (dismissed === today) return;+ var shown = 0;+ try {+ var raw = JSON.parse(localStorage.getItem('wbs-credit-rotation-shown-' + PROFILE_ID) || '{}');+ shown = raw && raw.day === today ? Number(raw.count) || 0 : 0;+ localStorage.setItem('wbs-credit-rotation-shown-' + PROFILE_ID, JSON.stringify({ day: today, count: shown + 1 }));+ } catch (_) {}+ var node = document.createElement('div');+ node.className = 'wbs-credit-rotation-notice';+ node.setAttribute('role', 'status');+ var title = '要切换账号吗?';+ var expiryCopy = Number.isFinite(Number(candidate.expiresAt))+ ? (',有 <b>' + esc(fmtCredits(candidate.remaining)) + '</b> 积分将于 <b>' + esc(formatRotationDays(candidate.expiresAt)) + '</b> 内过期')+ : ',当前有可用积分';+ var copy = '检测到积分到期时间最临近的账号「' + esc(candidate.nickname || '未命名账号') + '」' + expiryCopy;+ node.innerHTML = '<div class="wbs-credit-rotation-title">' + title + '</div>' ++ '<div class="wbs-credit-rotation-copy">' + copy + '</div>' ++ '<div class="wbs-credit-rotation-actions"><button type="button" class="wbs-credit-rotation-switch">切换到此账号</button>' ++ (shown >= 1 ? '<button type="button" class="wbs-credit-rotation-today">今天不再提醒</button>' : '') ++ '<button type="button" class="wbs-credit-rotation-close" aria-label="关闭">关闭(10)</button></div>';+ document.body.appendChild(node);+ function place() {+ var width = Math.min(330, Math.max(260, window.innerWidth - 24));+ node.style.width = width + 'px';+ // Use the untransformed fixed position. Auto-dock moves/rotates the+ // robot with CSS, so its transformed bounding box can sit outside the+ // viewport and make an anchored notice appear to be missing.+ var right = parseFloat(fab.style.right);+ var bottom = parseFloat(fab.style.bottom);+ if (!Number.isFinite(right)) right = 22;+ if (!Number.isFinite(bottom)) bottom = 22;+ var fabWidth = (fab.offsetWidth || 82) * 0.5;+ var fabHeight = (fab.offsetHeight || 64) * 0.5;+ var anchorRight = window.innerWidth - right;+ var anchorTop = window.innerHeight - bottom - fabHeight;+ var left = Math.max(12, Math.min(window.innerWidth - width - 12, anchorRight - width));+ node.style.left = left + 'px';+ node.style.top = Math.max(12, Math.min(window.innerHeight - node.offsetHeight - 12, anchorTop - node.offsetHeight - 12)) + 'px';+ }+ place();+ var remaining = 10;+ var timer = setInterval(function () {+ remaining -= 1;+ var closeButton = node.querySelector('.wbs-credit-rotation-close');+ if (closeButton) closeButton.textContent = '关闭(' + Math.max(0, remaining) + ')';+ if (remaining <= 0) closeRotationNotice();+ }, 1000);+ state.rotationNotice = { node: node, timer: timer, uid: candidate.uid };+ fab.classList.add('wbs-fab-credit-alert');+ node.querySelector('.wbs-credit-rotation-close').addEventListener('click', closeRotationNotice);+ var todayBtn = node.querySelector('.wbs-credit-rotation-today');+ if (todayBtn) todayBtn.addEventListener('click', function () {+ try { localStorage.setItem('wbs-credit-rotation-dismiss-' + PROFILE_ID, today); } catch (_) {}+ closeRotationNotice();+ });+ node.querySelector('.wbs-credit-rotation-switch').addEventListener('click', function (event) {+ var button = event.currentTarget;+ if (button.disabled) return;+ button.disabled = true;+ button.textContent = '切换中…';+ api('/api/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ uid: candidate.uid, reload: true }) })+ .then(function (result) {+ closeRotationNotice();+ toast('已切换为「' + (result.nickname || candidate.nickname || candidate.uid) + '」', false, root);+ setBuildTimeout(refresh, 1200);+ })+ .catch(function (error) {+ button.disabled = false;+ button.textContent = '切换到此账号';+ toast('切换失败:' + (error.message || error), true, root);+ });+ });+ window.addEventListener('resize', place);+ state.rotationNotice.place = place;+ }++ function formatRotationEta(expiresAt) {+ var ts = Number(expiresAt);+ if (!Number.isFinite(ts)) return '未设置时间';+ var diff = Math.max(0, ts - Date.now());+ if (diff < 3600000) return Math.max(1, Math.ceil(diff / 60000)) + ' 分钟后';+ if (diff < 86400000) return Math.ceil(diff / 3600000) + ' 小时后';+ return Math.ceil(diff / 86400000) + ' 天后';+ }++ function formatRotationDays(expiresAt) {+ var ts = Number(expiresAt);+ if (!Number.isFinite(ts)) return '较长时间';+ var diff = Math.max(0, ts - Date.now());+ if (diff < 86400000) return '1 天';+ return Math.max(1, Math.ceil(diff / 86400000)) + ' 天';+ }++ function checkCreditRotationAfterSession() {+ if (!CAPS.accounts || state.open || state.rotationNotice) return;+ function run() {+ if (!state.current || !state.current.uid || state.rotationNotice) return;+ var current = state.accounts.filter(function (account) { return String(account.uid) === String(state.current.uid); })[0] || { uid: state.current.uid, creditSegments: [] };+ api('/api/credit-rotation', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ uid: current.uid, previousSegments: current.creditSegments }),+ }).then(function (result) {+ current.creditSegments = Array.isArray(result && result.current && result.current.segments) ? result.current.segments : current.creditSegments;+ if (!result || !result.shouldSuggest || !result.candidate) return;+ showRotationNotice(result.candidate);+ }).catch(function () {});+ }+ if (state.current) { run(); return; }+ api('/api/accounts').then(function (data) {+ if (!alive || state.open || !data) return;+ state.current = data.current || null;+ state.accounts = mergeAccountSnapshot(state.accounts, data.accounts || []);+ run();+ }).catch(function () {});+ }+function updateCheckinCells(accounts) {var cards = accountsPane.querySelectorAll('.wbs-card');var byUid = {};@@ -10836,7 +11791,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {cell.classList.remove('wbs-credit-hidden');cell.innerHTML = creditBlockHtml(account.credits, account.creditSegments, account);var switchBtn = cards[i].querySelector('.wbs-acc-switch');- if (switchBtn) switchBtn.style.display = hidden || account.creditExpired ? 'none' : '';+ if (switchBtn) switchBtn.style.display = hidden || account.creditExpired || account.authValid === false ? 'none' : '';}}}@@ -10910,7 +11865,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {state.creditRemaining = accounts.length;function settleBatch() {if (runId !== state.creditRunId || state.creditRemaining !== 0) return;- // 到期信息留在缓存,下次打开前排序,避免响应回来时点到另一账号。+ if (state.accountSortPending) {+ state.accountSortPending = false;+ sortAccountsByCreditExpiry();+ reorderAccountCards();+ }+ // 后续后台批次只更新缓存,下次打开前再排序,避免逐条响应导致账号反复移动。var sum = 0;state.accounts.forEach(function (account) {if (typeof account.credits === 'number' && isFinite(account.credits)) sum += account.credits;@@ -11010,7 +11970,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {elCredit.classList.remove('wbs-credit-hidden');elCredit.innerHTML = creditBlockHtml(credits, segments || [], account);var cellSwitch = card.querySelector('.wbs-acc-switch');- if (cellSwitch) cellSwitch.style.display = hidden || (account && account.creditExpired) ? 'none' : '';+ if (cellSwitch) cellSwitch.style.display = hidden || (account && (account.creditExpired || account.authValid === false)) ? 'none' : '';}// ===== 调试:暴露内部状态到 window.__wbsDiag(控制台可调) =====@@ -11255,56 +12215,66 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'html.cb-dark .wbs-message-nav-rail,html[data-theme="dark"] .wbs-message-nav-rail,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 14%,transparent);border-color:transparent;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}','html.cb-dark .wbs-message-nav-rail:hover,html.cb-dark .wbs-message-nav-rail:focus-within,html[data-theme="dark"] .wbs-message-nav-rail:hover,html[data-theme="dark"] .wbs-message-nav-rail:focus-within,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail:hover,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail:focus-within{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 44%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.12));box-shadow:0 6px 20px rgba(0,0,0,.28);backdrop-filter:blur(14px) saturate(1.12);-webkit-backdrop-filter:blur(14px) saturate(1.12)}','html.cb-dark .wbs-message-nav-tooltip,html[data-theme="dark"] .wbs-message-nav-tooltip,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-tooltip{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 70%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.14));color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 14px 38px rgba(0,0,0,.42),inset 0 1px 0 rgba(255,255,255,.08)}',+ // 毛玻璃主题下移出即隐藏底色与模糊,鼠标点击留下的焦点不会让背景常驻。+ 'html[data-wbs-theme-id="nebula"] .wbs-message-nav-rail:not(:hover){background:transparent;border-color:transparent;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}',+ 'html[data-wbs-theme-id="nebula"] .wbs-message-nav-marker:not(:hover){background:transparent;border-color:transparent;backdrop-filter:none;-webkit-backdrop-filter:none}',+ '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}}',- /* 机器人悬浮按钮(bitter-dragon-16 移植):静态版 0.5 倍 · 无头顶尖角 · 眼睛双眨 */- '.wbs-fab{position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;will-change:transform;transition:transform .22s cubic-bezier(.22,1,.36,1)}',+ /* 官网演示机器人:尺寸按 2 倍绘制,保留现有 0.5 缩放与停靠/拖动坐标。 */+ '.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)}',+ '.wbs-fab{--wbs-robot-shell:#111;--wbs-robot-eye:#fff;--wbs-robot-blur:none;--wbs-robot-rim:rgba(255,255,255,.55);position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;will-change:transform;transition:transform .22s cubic-bezier(.22,1,.36,1)}','.wbs-fab-health-dot{position:absolute;top:-5px;left:-5px;width:14px;height:14px;border-radius:50%;background:#8b8f98;border:2px solid #141416;box-shadow:0 1px 3px rgba(0,0,0,.5);z-index:3}','.wbs-fab-health-dot.running{background:#4da3ff}.wbs-fab-health-dot.blocked{background:#ffb03a}.wbs-fab-health-dot.error{background:#ef6262}.wbs-fab-health-dot.suspected{background:#f08a3c}.wbs-fab-health-dot.stopped{background:#9ca3af}','.wbs-health-status{display:none;align-items:center;min-height:18px;padding:2px 7px;border-radius:999px;font-size:10px;line-height:14px;white-space:nowrap;color:var(--wb-color-text-secondary,#666);background:var(--wb-bg-tertiary,#f2f2f2)}','.wbs-health-status.running,.wbs-health-status.blocked,.wbs-health-status.error,.wbs-health-status.suspected,.wbs-health-status.stopped{display:inline-flex}','.wbs-health-status.running{color:#2369a8;background:rgba(77,163,255,.14)}.wbs-health-status.blocked{color:#9a5b00;background:rgba(255,176,58,.18)}.wbs-health-status.error{color:#a52828;background:rgba(239,98,98,.16)}.wbs-health-status.suspected{color:#9a4d0a;background:rgba(240,138,60,.17)}.wbs-health-status.stopped{color:var(--wb-color-text-secondary,#666)}','html.cb-dark .wbs-health-status.running,html[data-theme="dark"] .wbs-health-status.running{color:#b9dcff;background:rgba(77,163,255,.22)}html.cb-dark .wbs-health-status.blocked,html[data-theme="dark"] .wbs-health-status.blocked{color:#ffd58d;background:rgba(255,176,58,.24)}html.cb-dark .wbs-health-status.error,html[data-theme="dark"] .wbs-health-status.error{color:#ffb3b3;background:rgba(239,98,98,.25)}html.cb-dark .wbs-health-status.suspected,html[data-theme="dark"] .wbs-health-status.suspected{color:#ffc18d;background:rgba(240,138,60,.24)}',- /* 休眠呼吸灯 keyframes(天线圆点禁用休眠时呼吸;默认毛玻璃由 .wbs-fab-antenna-dot 提供) */+ /* 休眠状态仍由天线顶部圆点提示。 */'@keyframes wbs-sleep-pulse{0%,100%{box-shadow:0 0 5px 1px rgba(46,229,157,.6)}50%{box-shadow:0 0 13px 4px rgba(46,229,157,.95)}}','@keyframes wbs-sleep-pulse-amber{0%,100%{box-shadow:0 0 5px 1px rgba(255,176,58,.6)}50%{box-shadow:0 0 13px 4px rgba(255,176,58,.95)}}','.wbs-fab.hidden{display:none}','.wbs-fab .click{position:relative;transition:transform .22s cubic-bezier(.22,1,.36,1)}','.wbs-fab .click > span:not(.wbs-fab-antenna){display:none}','.wbs-fab .button.shadow{display:none}',- '.wbs-fab .button{position:relative;left:0;top:0;transform:none;cursor:pointer;border:solid 4px rgba(255,255,255,0);background-color:rgba(20,20,22,.55);backdrop-filter:blur(14px) saturate(1.3);-webkit-backdrop-filter:blur(14px) saturate(1.3);font-size:20px;color:#fff;border-color:rgba(255,255,255,0);box-shadow:0 4px 14px rgba(0,0,0,.45),inset 0 0 0 1px rgba(255,255,255,.08);border-radius:50px;display:flex;align-items:center;justify-content:center;width:100px;height:48px;box-sizing:content-box;padding:0;margin:0;outline:none;transition:background-color .2s,color .2s}',+ '.wbs-fab .button{position:relative;left:0;top:0;transform:none;cursor:pointer;border:0;background:var(--wbs-robot-shell);box-shadow:inset 0 2px 0 var(--wbs-robot-rim),0 8px 10px rgba(0,0,0,.12);backdrop-filter:var(--wbs-robot-blur);-webkit-backdrop-filter:var(--wbs-robot-blur);border-radius:22px;display:flex;align-items:center;justify-content:center;width:82px;height:64px;box-sizing:content-box;padding:0;margin:0;outline:none;transition:box-shadow .2s}',/* 贴消息队列时(queue 上方)保持纯色背景(与默认黑色一致,逻辑保留) */- '.wbs-fab.fab--solid .button{background:#141416;box-shadow:0 4px 14px rgba(0,0,0,.45)}',+ '.wbs-fab.fab--solid .button{background:var(--wbs-robot-shell)}','.wbs-fab .button:before,.wbs-fab .button:after{display:none}','.wbs-fab .button.up{z-index:2}',- /* 天线:SVG mask 数学绘制「圆 + 杆」一体图形(用户 08-30 01:22 修正杆底穿透:设计值 +4px 上移,- scale(0.5) 折算后杆底视觉停在按钮顶上方约 2px,不再穿入头部) */- '.wbs-fab-antenna{position:absolute;left:50%;top:-28px;width:14px;height:24px;transform:translateX(-50%);background:rgba(20,20,22,.55);backdrop-filter:blur(14px) saturate(1.3);-webkit-backdrop-filter:blur(14px) saturate(1.3);z-index:2;pointer-events:none;mask-image:url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 24\'><rect x=\'5\' y=\'14\' width=\'4\' height=\'10\'/><circle cx=\'7\' cy=\'7\' r=\'7\'/></svg>");-webkit-mask-image:url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 24\'><rect x=\'5\' y=\'14\' width=\'4\' height=\'10\'/><circle cx=\'7\' cy=\'7\' r=\'7\'/></svg>");mask-size:14px 24px;-webkit-mask-size:14px 24px;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat}',- /* 呼吸灯圆点:独立于 mask 容器(避免 mask/backdrop-filter 裁剪呼吸辉光),相对 button 定位到天线圆点位置(ant top:-28 内圆占 y0~14 → button 上 -28~-14) */- '.wbs-fab-antenna-dot{position:absolute;left:50%;top:-28px;width:14px;height:14px;transform:translateX(-50%);border-radius:50%;background:transparent;pointer-events:none;z-index:4}',- /* 休眠呼吸灯:天线顶部圆点(用户 08-30 00:20 要求替代右上角绿点;08-30 00:37 默认改毛玻璃半透明而非纯黑)——默认毛玻璃,禁止休眠时绿/琥珀呼吸 */+ /* 只遮罩玻璃面层,眼睛直接透出背景;天线和点击区域保持完整。 */+ '.wbs-robot-masks{position:absolute;pointer-events:none}.wbs-robot-cutout{transform-box:fill-box;transform-origin:center;scale:1;animation:wbs-robot-blink 7s infinite;transition:scale .18s ease}',+ '.wbs-fab[data-wbs-robot-style="glass"] .button{background:transparent;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}',+ '.wbs-fab[data-wbs-robot-style="glass"] .button:before{content:"";display:block;position:absolute;inset:0;border-radius:inherit;background:var(--wbs-robot-shell);box-shadow:inset 0 2px 0 var(--wbs-robot-rim);backdrop-filter:var(--wbs-robot-blur);-webkit-backdrop-filter:var(--wbs-robot-blur);mask:url("#wbs-robot-face-mask");pointer-events:none}',+ '.wbs-fab[data-wbs-robot-style="glass"] .eye{visibility:hidden}',+ '.wbs-fab:hover .wbs-robot-cutout{scale:1.18}',+ '.wbs-fab-antenna{position:absolute;left:50%;top:-14px;width:6px;height:16px;transform:translateX(-50%);border-radius:6px;background:var(--wbs-robot-shell);pointer-events:none}',+ '.wbs-fab-antenna-dot{position:absolute;left:50%;top:-18px;width:10px;height:10px;transform:translateX(-50%);border-radius:50%;background:var(--wbs-robot-shell);pointer-events:none;z-index:4}',+ /* 禁止休眠时绿/琥珀呼吸,关闭后恢复官网机器人天线色。 */'#wbs-fab-sleep-light{transition:background .25s,box-shadow .25s}','#wbs-fab-sleep-light.sleep-on{background:rgba(46,229,157,.85);box-shadow:0 0 8px 2px rgba(46,229,157,.85);animation:wbs-sleep-pulse 2.2s ease-in-out infinite}','#wbs-fab-sleep-light.sleep-until-done{background:rgba(255,176,58,.85);box-shadow:0 0 8px 2px rgba(255,176,58,.85);animation:wbs-sleep-pulse-amber 2.2s ease-in-out infinite}','.wbs-fab .click .button .speak~.speak{display:none}','.wbs-fab .speak{position:relative;z-index:2;font-size:15px}',- '.wbs-fab .wrap{position:relative;width:100px;height:40px;margin:0 2rem;color:#fff;line-height:40px;font-size:2rem;text-align:center;font-weight:400;margin-bottom:0;display:flex;gap:5px}',- '.wbs-fab .eye{position:relative;margin:auto;top:0;bottom:0;background:#fff;width:40px;height:40px;border-radius:50%;display:inline-block;animation:wbs-cc-double-blink 4s cubic-bezier(0.785,0.135,0.15,0.86) infinite;overflow:hidden}',- '@keyframes wbs-cc-double-blink{0%,8%{height:40px}10%,12%{height:10px}13%{height:40px}14%,16%{height:0}18%,100%{height:40px}}',- '.wbs-fab .eye:before{content:"";position:absolute;margin:auto;width:10px;height:10px;left:0;right:0;top:0;bottom:0;border-radius:50%;background:rgba(20,20,22,.55);backdrop-filter:blur(14px) saturate(1.3);-webkit-backdrop-filter:blur(14px) saturate(1.3);box-shadow:inset 0 0 3px rgba(0,0,0,.35),0 0 0 1px rgba(255,255,255,.14)}',- '.wbs-fab .down:before{animation:wbs-cc-downb 4s cubic-bezier(0.785,0.135,0.15,0.86) infinite}',- '@keyframes wbs-cc-downb{0%,10%{top:0;left:-10px}20%,40%{top:50%;left:-10px}50%,100%{top:0;left:-10px}}',- '.wbs-fab .right-blink:before{animation:wbs-cc-rightb 4s cubic-bezier(0.785,0.135,0.15,0.86) infinite}',- '@keyframes wbs-cc-rightb{0%,10%{top:0;left:50%}20%,40%{top:50%;left:50%}50%,100%{top:0;left:50%}}',- '.wbs-fab .up-blink:before{animation:wbs-cc-upb 4s cubic-bezier(0.785,0.135,0.15,0.86) infinite}',- '@keyframes wbs-cc-upb{0%,10%{top:0;left:0%}20%,40%{top:-50%;left:0%}50%,100%{top:0;left:0%}}',- '.wbs-fab:hover{transform:scale(0.5)}',+ '.wbs-fab .wrap{display:flex;align-items:center;justify-content:center;gap:14px;height:18px}',+ '.wbs-fab .eye{display:block;width:12px;height:18px;border-radius:6px;background:var(--wbs-robot-eye);scale:1;animation:wbs-robot-blink 7s infinite;transition:scale .18s ease}',+ '@keyframes wbs-robot-blink{0%,43%,47%,100%{transform:scaleY(1)}45%{transform:scaleY(.15)}}',++++++++ '.wbs-fab:hover{transform:scale(0.5)}.wbs-fab:hover .eye{scale:1.18}','.wbs-fab:active{transform:scale(0.5) translate(2px,2px)}','.wbs-fab.is-quiet{transform:translateX(var(--wbs-fab-quiet-shift,59px)) scale(0.5)}','.wbs-fab.is-quiet .click{transform:rotate(-90deg)}','.wbs-fab.is-quiet .wbs-fab-health-dot{visibility:hidden}','.wbs-fab.is-quiet .wbs-fab-antenna,.wbs-fab.is-quiet .wbs-fab-antenna-dot{visibility:hidden}','.wbs-fab .button:focus-visible{outline:3px solid var(--wb-accent-blue,#4f86ff);outline-offset:5px}',- '@media(prefers-reduced-motion:reduce){.wbs-fab,.wbs-fab .click{transition:none!important}}',+ '@media(prefers-reduced-motion:reduce){.wbs-fab,.wbs-fab .click{transition:none!important}.wbs-fab .eye,.wbs-fab .wbs-robot-cutout{animation:none!important;transition:none!important}}','.wbs-fab.is-dragging{cursor:grabbing;transition:none !important}','.wbs-fab.is-dragging .click{transition:none}','.wbs-fab.is-dragging .button{cursor:grabbing}',@@ -11324,16 +12294,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-lang-seg .wbs-sess-seg-btn{padding:6px 14px}','.wbs-head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px 12px;border-bottom:1px solid var(--wb-border-subtle,#f0f0f0);background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 30%,transparent)}','.wbs-head-left{display:flex;align-items:center;gap:9px;min-width:0}',+ '.wbs-brand{display:inline-flex;align-items:center;max-width:100%;padding:0;border:0;border-radius:8px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;user-select:none}.wbs-brand:focus-visible{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:4px}.wbs-brand-copy{display:flex;flex-direction:column;align-items:flex-start;min-width:0;gap:0}','.wbs-title-wrap{display:flex;flex-direction:column;align-items:flex-start;min-width:0}',- '.wbs-title-row{display:flex;align-items:center;gap:9px;min-width:0}',- '.wbs-title{font-size:16px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);letter-spacing:.3px;cursor:pointer;user-select:none}',- '.wbs-version-line{margin-top:1px;color:var(--wb-color-text-tertiary,#a3a6ad);font-size:10px;font-weight:400;line-height:1.2;letter-spacing:0;font-variant-numeric:tabular-nums;white-space:nowrap}',+ '.wbs-title-row{display:flex;align-items:center;flex-wrap:wrap;gap:6px 9px;min-width:0}',+ '.wbs-title{font-family:"Avenir Next",Avenir,"Segoe UI Variable Display","Segoe UI",sans-serif;font-size:15px;line-height:1.15;font-weight:750;letter-spacing:-.55px;color:var(--wb-color-text-primary,#1f1f1f);white-space:nowrap;user-select:none}',+ '.wbs-version-line{margin:0;color:var(--wb-color-text-tertiary,#a3a6ad);font-size:10px;font-weight:400;line-height:1.2;letter-spacing:0;font-variant-numeric:tabular-nums;white-space:nowrap}',/* 元素检查拾取按钮(隐藏入口,连点标题 5 次显示) */'.wbs-pick-btn{flex:0 0 auto;width:22px;height:22px;border:none;border-radius:7px;background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 14%,transparent);color:var(--wb-accent-blue,#4f86ff);font-size:12px;line-height:1;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:background .15s}','.wbs-pick-btn:hover{background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 24%,transparent)}',- '.wbs-ghbtn{display:flex;align-items:center;justify-content:center;width:24px;height:24px;flex-shrink:0;color:var(--wb-icon-tertiary,#999);border-radius:6px;text-decoration:none;transition:color .15s,background .15s}',- '.wbs-ghbtn:hover{color:var(--wb-color-text-primary,#1f1f1f);background:var(--wb-bg-hover,#f5f5f5)}',- '.wbs-ghbtn svg{display:block}','.wbs-btn-close{border:none;background:none;color:var(--wb-icon-tertiary,#999);font-size:16px;cursor:pointer;padding:4px 6px;border-radius:6px;line-height:1}','.wbs-btn-close:hover{color:var(--wb-color-text-primary,#1f1f1f);background:var(--wb-bg-hover,#f5f5f5)}','.wbs-body{overflow-y:auto;padding:10px 10px 6px;flex:1;min-height:0;height:calc(650px - 170px);max-height:none}',@@ -11448,6 +12416,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-ask-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}','.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-seg{display:flex;gap:3px;padding:3px;margin-bottom:12px;border-radius:9px;background:var(--wb-bg-tertiary,#f0f0f0)}.wbs-robot-seg label{position:relative;flex:1;min-width:0;cursor:pointer}.wbs-robot-seg input{position:absolute;opacity:0;width:1px;height:1px}.wbs-robot-seg span{display:flex;align-items:center;justify-content:center;min-height:28px;padding:2px 6px;border-radius:7px;font-size:12px;color:var(--wb-color-text-secondary,#666);box-sizing:border-box}.wbs-robot-seg input:checked+span{background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#222);box-shadow:0 1px 4px rgba(0,0,0,.12);font-weight:600}.wbs-robot-seg label:hover span{color:var(--wb-color-text-primary,#222)}.wbs-robot-seg input:focus-visible+span{outline:2px solid var(--wb-accent-blue,#4f86ff);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}',@@ -11480,7 +12449,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'html[data-wbs-language="en"] .wbs-stash-inline:hover .wbs-stash-txt{max-width:96px}','.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{width:32px;height:32px;border-radius:50%;padding:0 8px}',+ '.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 抬升让按钮成为独立层叠上下文,弹层在其内不受操作栏兄弟元素压制 */@@ -11575,7 +12544,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.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}','.wbs-auto-row:hover{background:var(--wb-bg-hover,#f5f5f5)}','.wbs-auto-check{display:flex;align-items:center;justify-content:center;flex:0 0 20px;cursor:pointer}.wbs-auto-check input{accent-color:var(--wb-button-primary-bg,#1f1f1f)}',- '.wbs-auto-main{min-width:0;flex:1}.wbs-auto-name{display:block;flex:1;min-width:0;font-size:12px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',+ '.wbs-auto-main{min-width:0;flex:1}.wbs-auto-builtin-badge{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;min-height:18px;padding:1px 6px;box-sizing:border-box;border:1px solid var(--wb-border-default,#d8d8d8);border-radius:999px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font-size:10px;font-weight:500;line-height:1}.wbs-auto-name{display:block;flex:1;min-width:0;font-size:12px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}','.wbs-auto-status{flex:0 0 auto;padding:2px 6px;border-radius:999px;font-size:10px;font-weight:500}.wbs-auto-status.on{color:#1b7f56;background:rgba(46,190,126,.14)}.wbs-auto-status.off{color:var(--wb-icon-tertiary,#888);background:var(--wb-bg-tertiary,#f1f1f1)}','.wbs-auto-meta{margin-top:3px;color:var(--wb-icon-tertiary,#999);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}','.wbs-auto-enabled{flex:0 0 auto;margin-left:4px}.wbs-auto-actions{display:flex;gap:2px;flex:0 0 auto}.wbs-auto-icon{display:inline-flex;align-items:center;justify-content:center;width:27px;height:27px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--wb-icon-secondary,#666);cursor:pointer;line-height:27px}.wbs-auto-icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round}.wbs-auto-icon:hover,.wbs-auto-icon:focus-visible{background:var(--wb-bg-hover,#f0f0f0);color:var(--wb-color-text-primary,#1f1f1f);outline:none}.wbs-auto-icon.danger:hover{color:#d04a4a}.wbs-auto-icon.is-running,.wbs-auto-icon.is-running:hover{opacity:1;filter:none;background:transparent;color:var(--wb-icon-secondary,#666);cursor:pointer}.wbs-auto-icon:disabled{opacity:.45;cursor:wait}',@@ -11628,7 +12597,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-seg-btn{flex:1;padding:6px 4px;border:none;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;font-family:inherit;white-space:nowrap}','.wbs-sess-seg-btn:hover{color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-sess-seg-btn.active{background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.2)}',- '.wbs-sess-toolbar{display:flex;align-items:center;gap:6px;margin-bottom:8px}',+ '.wbs-sess-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin-bottom:8px}','.wbs-sess-refresh{display:flex;align-items:center;justify-content:center;flex-shrink:0;padding:7px;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-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}',@@ -11644,7 +12613,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sess-auto-all.active .wbs-sess-auto-all-box{color:var(--wb-button-primary-bg,#1f1f1f)}','.wbs-sess-auto-all.active .wbs-sess-auto-all-check{opacity:1}','.wbs-sess-auto-all-label{white-space:nowrap}',- '.wbs-sess-batchbar{display:flex;align-items:center;gap:5px;flex-wrap:nowrap;margin:0;padding:0;border:none;background:transparent}',+ '.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-done{margin-left:auto;color:#fff;background:#141416;border-color:#141416}','.wbs-sess-done:hover{background:#2a2a2e;color:#fff}',/* 删除按钮:图标按钮,尺寸与兄弟一致;点击后变警告色(armed) */@@ -11662,10 +12631,32 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-model-tab:hover{color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-model-tab.active{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-model-tab-count{font-size:12px;opacity:.72;font-variant-numeric:tabular-nums}',- '.wbs-model-toolbar{display:flex;align-items:center;gap:6px;min-height:28px;margin-bottom:7px}',+ '.wbs-model-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:6px;min-height:28px;margin-bottom:7px}','.wbs-model-toolbar-spacer{flex:1}','.wbs-model-imports{display:flex;align-items:center;gap:5px;flex-wrap:wrap}','.wbs-model-import:disabled{opacity:.5;cursor:not-allowed}',+ '.wbs-model-third-party{position:relative;display:inline-flex}',+ '.wbs-model-source-menu{position:absolute;right:0;top:calc(100% + 4px);z-index:10;min-width:120px;padding:4px;border:1px solid var(--wb-border-default,#ddd);border-radius:8px;background:var(--wb-bg-popover,#fff);box-shadow:0 6px 20px rgba(0,0,0,.16)}',+ '.wbs-model-source-menu button{width:100%;padding:8px;text-align:left;border:0;border-radius:5px;background:transparent;color:var(--wb-color-text-primary,#222);font:inherit;font-size:12px;cursor:pointer}',+ '.wbs-model-source-menu button:hover,.wbs-model-source-menu button:focus-visible{background:var(--wb-bg-hover,#f3f3f3)}',+ '.wbs-modal.wbs-model-import-modal{width:640px;max-width:calc(100vw - 32px);box-sizing:border-box;max-height:88vh;display:flex;flex-direction:column}',+ '.wbs-modal.wbs-model-import-confirm{width:380px}',+ '.wbs-model-import-modal .wbs-modal-body{min-height:0;max-height:min(520px,65vh);flex-shrink:1;overflow-wrap:anywhere;font-size:12px;line-height:1.5}',+ '.wbs-third-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:12px;position:sticky;top:0;background:var(--wb-bg-popover,#fff);z-index:1;padding-bottom:6px}',+ '.wbs-third-toolbar .wbs-third-all{flex:1}',+ '.wbs-third-toolbar select{max-width:100%;font-size:12px}',+ '.wbs-third-all{display:flex;align-items:center;gap:8px;padding:4px 2px;font-size:12px}',+ '.wbs-third-all [data-third-count]{margin-left:auto;color:var(--wb-icon-secondary,#666)}',+ '.wbs-third-row{display:flex;align-items:flex-start;gap:8px;padding:8px 5px;border-bottom:1px solid var(--wb-border-default,#eee);cursor:pointer}',+ '.wbs-third-row:hover{background:var(--wb-bg-hover,#f3f3f3)}',+ '.wbs-third-row input{flex-shrink:0;margin-top:3px}',+ '.wbs-third-text{display:flex;flex-direction:column;gap:3px;min-width:0;color:var(--wb-icon-secondary,#666);font-size:11px;overflow-wrap:anywhere}',+ '.wbs-third-text strong{color:var(--wb-color-text-primary,#222);font-size:12px;font-weight:600}',+ '.wbs-third-note{color:var(--wb-color-text-primary,#333)}',+ '.wbs-third-unavailable{opacity:.6;cursor:default}',+ '.wbs-model-import-modal input{accent-color:var(--wb-button-primary-bg,#333)}',+ '.wbs-model-import-modal button:disabled{opacity:.45;cursor:default}',+'.wbs-model-count{font-size:13px;color:var(--wb-icon-tertiary,#888)}','.wbs-model-batchbar{display:flex;align-items:center;gap:5px;flex-wrap:nowrap;margin:0;padding:0;border:none;background:transparent}','.wbs-model-batch-count{font-size:11px;color:var(--wb-icon-tertiary,#999);white-space:nowrap}',@@ -11808,6 +12799,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-sleep-mode-hint{font-size:11px;color:var(--wb-icon-tertiary,#999);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',/* 关于页:项目信息卡(名字/标语/原理徽章/介绍 + 支持项目入口 + 版本) */'.wbs-about-hero{display:flex;flex-direction:column;align-items:center;gap:8px;padding:20px 16px 16px}',+ '.wbs-about-brand{display:inline-flex;align-items:center;gap:8px;min-width:0}.wbs-about-logo{display:block;width:32px;height:32px;flex:0 0 32px;border-radius:9px;object-fit:cover;box-shadow:0 0 0 1px var(--wb-border-subtle,rgba(0,0,0,.08))}','.wbs-about-name{font-size:18px;font-weight:700;letter-spacing:.3px;color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-about-tag{font-size:12.5px;color:var(--wb-icon-tertiary,#888);text-align:center;line-height:1.5}','.wbs-about-badge{font-size:11px;font-weight:600;color:var(--wb-button-primary-bg,#1f1f1f);background:rgba(0,0,0,.05);border:1px solid rgba(0,0,0,.08);padding:3px 10px;border-radius:999px;white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis}',@@ -11927,17 +12919,52 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-acct-io:hover{background:var(--wb-bg-hover,#f0f0f0);border-color:var(--wb-border-default,#d5d5d5)}','.wbs-acct-io svg{flex-shrink:0}','.wbs-acct-io span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',+ '.wbs-acct-icon{width:28px;height:28px;padding:0;border-radius:8px}','.wbs-acct-list{flex:1;min-height:0;overflow-y:auto;padding-right:2px}','.wbs-logout-btn{display:flex;align-items:center;justify-content:center;gap:6px;width:100%;margin-top:10px;padding:10px 0;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:12px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:13px;font-weight:600;cursor:pointer;transition:all .15s;font-family:inherit;flex-shrink:0}','.wbs-logout-btn:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);border-color:var(--wb-border-default,#d5d5d5)}','.wbs-logout-btn.armed{background:#f53f3f;color:#fff;border-color:#f53f3f}','.wbs-logout-btn svg{width:15px;height:15px}',+ '.wbs-credit-rotation-notice{position:fixed;z-index:2147483647;box-sizing:border-box;padding:13px 14px 11px;border:1px solid rgba(0,0,0,.08);border-radius:12px;background:#fff;color:#1f2937;box-shadow:0 10px 28px rgba(0,0,0,.16);font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;animation:wbs-credit-rotation-in .2s cubic-bezier(.22,1,.36,1)}',+ '@keyframes wbs-credit-rotation-in{from{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}',+ '.wbs-credit-rotation-title{font-size:13px;font-weight:700;line-height:1.4}',+ '.wbs-credit-rotation-copy{margin-top:5px;font-size:11px;line-height:1.55;color:#667085;word-break:break-word}',+ '.wbs-credit-rotation-copy b{color:#1f2937;font-weight:700}',+ '.wbs-credit-rotation-actions{display:flex;align-items:center;gap:6px;margin-top:10px}',+ '.wbs-credit-rotation-actions button{min-height:26px;border-radius:7px;padding:0 9px;font:inherit;font-size:11px;cursor:pointer;white-space:nowrap}',+ '.wbs-credit-rotation-switch{border:1px solid #1f1f1f;background:#1f1f1f;color:#fff}',+ '.wbs-credit-rotation-switch:hover{background:#333}',+ '.wbs-credit-rotation-today,.wbs-credit-rotation-close{border:1px solid rgba(0,0,0,.1);background:#fff;color:#667085}',+ '.wbs-credit-rotation-today:hover,.wbs-credit-rotation-close:hover{background:#f5f6f8;color:#1f2937}',+ '.wbs-credit-rotation-actions button:disabled{opacity:.55;cursor:wait}',+ '.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-token-stats-modal{width:min(760px,calc(100% - 24px));max-height:min(86vh,760px);display:flex;flex-direction:column;overflow:hidden;border:1px solid var(--wb-border-default,rgba(20,24,32,.14))}',+ '.wbs-usage-header{flex-shrink:0}.wbs-usage-scroll{min-height:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;flex:1;padding-right:3px}.wbs-token-stats-modal>.wbs-modal-actions{flex-shrink:0}.wbs-token-stats-modal .wbs-token-model-scroll{max-height:none;overflow:visible}.wbs-token-stats-modal .wbs-token-model-scroll:after{display:none}.wbs-credit-query-content{position:relative;min-height:330px}.wbs-token-stats-filters.wbs-credit-filters{grid-template-columns:repeat(2,minmax(0,1fr))}',+ '.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:4px;margin:10px 0 2px;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:6px 12px;font:inherit;font-size:12px;cursor:pointer}.wbs-usage-tabs button.active{border-bottom-color:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-color-text-primary,#1f1f1f);font-weight:650}.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:180px}',+ '.wbs-token-stats-filters{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:12px 0}',+ '.wbs-token-stats-filters label{display:flex;align-items:center;gap:6px;min-width:0;font-size:11px;color:var(--wb-icon-secondary,#667085)}',+ '.wbs-token-stats-filters select{min-width:0;flex:1;height:30px;padding:0 7px;border:1px solid var(--wb-border-default,#e2e4e8);border-radius:7px;background:var(--wb-bg-secondary,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit}',+ '.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-glass .wbs-token-stats-modal{border:1px solid var(--wb-border-subtle,rgba(20,24,32,.18));background:color-mix(in srgb,var(--wb-bg-popover,#fff) 68%,transparent);backdrop-filter:blur(24px) saturate(1.2);-webkit-backdrop-filter:blur(24px) saturate(1.2);box-shadow:0 18px 46px rgba(20,24,32,.22),inset 0 1px 0 rgba(255,255,255,.42)}.wbs-token-stats-glass .wbs-token-stats-search{border-color:var(--wb-border-subtle,rgba(20,24,32,.22));background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 78%,transparent);box-shadow:inset 0 1px 0 rgba(255,255,255,.22)}',+ '.wbs-token-stats-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px}',+ '.wbs-token-stats-grid>div{display:flex;min-width:0;flex-direction:column;gap:4px;padding:7px 5px;border-radius:7px;background:var(--wb-bg-tertiary,#f5f6f8)}',+ '.wbs-token-stats-grid span{font-size:10px;color:var(--wb-icon-tertiary,#8a8f98)}',+ '.wbs-token-stats-grid strong{font-size:12px;color:var(--wb-color-text-primary,#1f1f1f);font-variant-numeric:tabular-nums}',+ '.wbs-token-stats-section{margin-top:14px;border-top:1px solid var(--wb-border-subtle,#eee);padding-top:9px}.wbs-token-stats-section-title{font-size:12px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f);margin-bottom:8px}',+ '.wbs-token-stats-chart{display:flex;align-items:flex-end;gap:8px;height:125px;overflow-x:auto;padding:0 4px 2px;border-bottom:1px solid var(--wb-border-subtle,#eee)}.wbs-token-day{display:flex;min-width:38px;height:100%;flex-direction:column;align-items:center;justify-content:flex-end;gap:3px;font-size:9px;color:var(--wb-icon-tertiary,#8a8f98)}.wbs-token-day i{display:block;width:18px;min-height:3px;border-radius:4px 4px 0 0;background:var(--wb-button-primary-bg,#1f1f1f)}.wbs-token-day b{font-size:9px;font-weight:500;color:var(--wb-icon-secondary,#667085);font-variant-numeric:tabular-nums}',+ '.wbs-token-model-scroll{position:relative;max-height:220px;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;gap:4px}.wbs-token-stats-table>div{display:grid;grid-template-columns:minmax(0,1fr) 100px 60px;gap:8px;align-items:center;font-size:11px;color:var(--wb-color-text-secondary,#667085)}.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:330px;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:330px}.wbs-token-stats-body{min-height:330px}.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-button-primary-bg,#1f1f1f);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}.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-glass .wbs-token-stats-search,html[data-theme="dark"] .wbs-token-stats-glass .wbs-token-stats-search,body[data-vscode-theme-name*="dark" i] .wbs-token-stats-glass .wbs-token-stats-search{background:color-mix(in srgb,var(--wb-button-primary-bg,#fff) 28%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.24));color:var(--wb-color-text-primary,#f3f3f3)}',+ '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}#wbs-token-stats-modal .wbs-token-stats-modal{box-sizing:border-box;max-height:calc(100% - 24px)}.wbs-token-stats-modal{position:relative}.wbs-credit-filters label{white-space:nowrap}.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:142px}.wbs-credit-day{height:138px;flex-shrink:0}.wbs-credit-bar-track{height:100px;flex:0 0 100px;display:flex;align-items:flex-end}.wbs-credit-bar-track i{min-height:0;flex-shrink:0}.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,.wbs-credit-filters select:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}',+ '@media(max-width:620px){.wbs-token-stats-filters{grid-template-columns:1fr 1fr}.wbs-token-stats-filters label:first-child{grid-column:1/-1}.wbs-token-stats-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.wbs-token-stats-modal{max-height:calc(100vh - 24px)}}',/* 登录新账号二选一弹窗(方法一 假退出 / 方法二 无感登录) *//* 选择登录方式:遮罩限定在 WorkDaddy 面板内部,沿用会话弹窗的层级与按钮风格 */'.wbs-pane{position:relative}','@keyframes wbs-modal-in{from{opacity:0}to{opacity:1}}','.wbs-panel-modal-mask{position:absolute;inset:0;z-index:20;display:flex;align-items:center;justify-content:center;padding:14px;background:transparent;pointer-events:auto;animation:wbs-modal-in .16s ease}',- '.wbs-login-modal{width:min(360px,calc(100% - 28px));box-sizing:border-box;padding:16px;border:1px solid var(--wb-border-default,rgba(0,0,0,.12));border-radius:14px;background:var(--wb-bg-popover,#fff);box-shadow:0 10px 40px rgba(0,0,0,.25)}',+ '.wbs-login-modal{width:min(360px,calc(100% - 28px));box-sizing:border-box;padding:16px;border:1px solid var(--wb-border-default,rgba(0,0,0,.12));border-radius:14px;background:var(--wb-bg-popover,#fff);box-shadow:0 10px 40px rgba(0,0,0,.25)}.wbs-import-choice-modal{width:min(460px,calc(100% - 28px))}.wbs-import-json-hint{margin:-3px 0 12px;padding:9px 10px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.14));border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 55%,transparent);color:var(--wb-icon-secondary,#667085);font-size:11px;line-height:1.55}.wbs-import-json-hint[hidden]{display:none!important}','.wbs-login-modal-title{font-size:15px;font-weight:700;line-height:1.35;color:var(--wb-color-text-primary,#1f1f1f);margin:0 0 14px}','.wbs-password-modal{width:min(360px,calc(100% - 28px));box-sizing:border-box;padding:16px;border:1px solid var(--wb-border-default,rgba(0,0,0,.12));border-radius:14px;background:var(--wb-bg-popover,#fff);box-shadow:0 10px 40px rgba(0,0,0,.25)}','.wbs-password-field{display:flex;flex-direction:column;gap:6px;font-size:12px;color:var(--wb-icon-secondary,#666)}',@@ -11973,6 +13000,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-empty{text-align:center;color:var(--wb-icon-tertiary,#999);padding:28px 10px;font-size:12px}',/* body 高度:无底部功能区后最大化 */'.wbs-body{max-height:calc(min(78vh,660px) - 118px)}',+ // 账号页填满面板剩余空间:少量账号时登录按钮靠底部,长列表仍在列表内滚动。+ '.wbs-body:has(>[data-pane="account"].active){max-height:none;overflow:hidden}',].join('');(document.head || document.documentElement).appendChild(css);start();diff --git a/scripts/lib.js b/scripts/lib.jsindex 4e29da9..b29b48f 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -149,6 +149,10 @@ function parseAuthFile(file, options = {}) {}}+function parseAuthJson(json, options = {}) {+ return authRecordFromJson(null, json, options);+}+function listAuthRecords() {if (!AUTH_FILE) return [];if (!DYNAMIC_AUTH_DISCOVERY) {@@ -827,6 +831,7 @@ function normalizeAutoCopyLineages(dataDir) {}const replacementId = crypto.randomUUID();config.sessions[replacementId] = {+ originLineageId: lineage.originLineageId || lineageId,enabled: lineage.enabled !== false,members: [{ uid, id }],createdAt: Date.now(),@@ -944,42 +949,70 @@ function collectLineageMembersForDelete(dataDir, sessionIds) {.filter(Boolean));if (!ids.size) return [];- // 跨账号全表反向索引:sessionId -> lineageId(会话 id 全局唯一)- const lineageBySession = new Map();- for (const owner of Object.keys(config.sessionIndex || {})) {- const index = config.sessionIndex[owner] || {};- for (const sessionId of Object.keys(index)) {- const lineageId = String(index[sessionId] || '');- if (lineageId) lineageBySession.set(sessionId, lineageId);- }- }- const members = [];- const seenKeys = new Set();- const seenLineages = new Set();- const addMember = (memberUid, memberId, lineageId) => {+ // 成员表、反向索引及历史复制映射共同证明同源关系。只查成员表会漏掉+ // 旧版复制记录,以及 normalizeAutoCopyLineages 拆出的重复物理会话。+ // 不使用标题、工作目录或消息相似度推断,避免删除独立会话。+ const membersByLineage = new Map();+ const lineagesBySession = new Map();+ const lineagesByOrigin = new Map();+ const addLink = (lineageId, memberUid, memberId) => {+ if (!config.sessions[lineageId]) return;const uid = String(memberUid || '').trim();const id = String(memberId || '').trim();if (!id) return;- const key = (uid || '*') + '::' + id;- if (seenKeys.has(key)) return;- seenKeys.add(key);- members.push({ uid, id, lineageId: String(lineageId || '') });+ if (!membersByLineage.has(lineageId)) membersByLineage.set(lineageId, new Map());+ membersByLineage.get(lineageId).set(id, { uid, id, lineageId });+ if (!lineagesBySession.has(id)) lineagesBySession.set(id, new Set());+ lineagesBySession.get(id).add(lineageId);};+ for (const [lineageId, lineage] of Object.entries(config.sessions)) {+ if (!lineage) continue;+ const origin = String(lineage.originLineageId || lineageId);+ if (!lineagesByOrigin.has(origin)) lineagesByOrigin.set(origin, []);+ lineagesByOrigin.get(origin).push(lineageId);+ for (const member of (Array.isArray(lineage.members) ? lineage.members : [])) {+ addLink(lineageId, member && member.uid, member && member.id);+ }+ }+ for (const [uid, index] of Object.entries(config.sessionIndex)) {+ for (const [id, lineageId] of Object.entries(index || {})) addLink(String(lineageId || ''), uid, id);+ }+ for (const [key, mapping] of Object.entries(config.copies)) {+ try {+ const parts = JSON.parse(key);+ if (Array.isArray(parts) && parts.length === 2) {+ addLink(String(parts[0] || ''), parts[1], mapping && mapping.targetId);+ }+ } catch (_) { /* Malformed legacy keys cannot establish a copy relationship. */ }+ }+ const members = [];+ const seenIds = new Set();+ const seenLineages = new Set();for (const id of ids) {- const lineageId = lineageBySession.get(id);- if (!lineageId || !config.sessions[lineageId]) {- addMember('', id, '');- continue;+ const pending = Array.from(lineagesBySession.get(id) || []);+ if (!pending.length && !seenIds.has(id)) {+ seenIds.add(id);+ members.push({ uid: '', id, lineageId: '' });}- if (seenLineages.has(lineageId)) continue;- seenLineages.add(lineageId);- const lineage = config.sessions[lineageId];- const lineageMembers = Array.isArray(lineage.members) ? lineage.members : [];- if (!lineageMembers.length) {- addMember('', id, lineageId);- continue;+ for (let i = 0; i < pending.length; i++) {+ const lineageId = pending[i];+ if (seenLineages.has(lineageId)) continue;+ seenLineages.add(lineageId);+ const lineage = config.sessions[lineageId];+ const origin = String(lineage.originLineageId || lineageId);+ for (const related of lineagesByOrigin.get(origin) || []) {+ if (!seenLineages.has(related)) pending.push(related);+ }+ for (const member of (membersByLineage.get(lineageId) || new Map()).values()) {+ if (!seenIds.has(member.id)) {+ seenIds.add(member.id);+ members.push(member);+ }+ for (const related of lineagesBySession.get(member.id) || []) {+ if (!seenLineages.has(related)) pending.push(related);+ }+ }}- lineageMembers.forEach((m) => addMember(m && m.uid, m && m.id, lineageId));}return members;}@@ -1289,9 +1322,11 @@ function listAccounts(dataDir) {refreshExpiresAt: null,lastRefreshTime: null,lastSeen: null,+ authValid: false,};try {const j = JSON.parse(fs.readFileSync(path.join(dir, n), 'utf8'));+ item.authValid = !!parseAuthJson(j);const acct = j.account || (Array.isArray(j.accounts) && j.accounts[0]);if (acct) {item.nickname = acct.nickname || '';@@ -1459,11 +1494,15 @@ function switchTo(dataDir, uid, log = () => {}) {}module.exports = {+ readModelsFile,+ writeModelsFile,+ writeModelBackup,AUTH_FILE,authDir,safeAuthFileName,normalizeAuthDomain,tokenIssuerOrigin,+ parseAuthJson,parseAuthFile,listAuthRecords,resolveCurrentAuth,diff --git a/scripts/make-icon.py b/scripts/make-icon.pyindex e5c62d1..cb39642 100644--- a/scripts/make-icon.py+++ b/scripts/make-icon.py@@ -1,19 +1,19 @@#!/usr/bin/env python3-"""Build the macOS and Windows application icons from one foreground PNG."""+"""Build both application icons from the website's rounded SVG logo."""import osimport shutilimport subprocessimport tempfile+import xml.etree.ElementTree as ETROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))-SOURCE = os.path.join(ROOT, 'scripts', 'assets', 'workdaddy-icon-foreground.png')+SOURCE = os.path.join(ROOT, 'scripts', 'assets', 'workdaddy-logo.svg')+PNG_OUT = os.path.join(ROOT, 'scripts', 'assets', 'workdaddy-icon-foreground.png')MAC_OUT = os.path.join(ROOT, 'scripts', 'assets', 'WorkDaddy.icns')WIN_OUT = os.path.join(ROOT, 'release', 'WorkDaddy.ico')-BACKGROUND = '#e1e1e1'-WINDOWS_CORNER_RADIUS_RATIO = 0.20-ICON_SIZES = [16, 32, 64, 128, 256, 512, 1024]+ICON_SIZES = [16, 24, 32, 48, 64, 128, 256]def run(*args):@@ -27,26 +27,21 @@ def require_tool(name):return path-def render_base(magick, output, rounded, with_background=True):- canvas = f'xc:{BACKGROUND}' if with_background else 'xc:none'- args = [- magick,- '-size', '1024x1024', canvas,- SOURCE,- '-compose', 'over', '-composite',- ]- if rounded:- radius = round(1024 * WINDOWS_CORNER_RADIUS_RATIO)- args += [- '(', '-size', '1024x1024', 'xc:none', '-fill', 'white',- '-draw', f'roundrectangle 0,0 1023,1023 {radius},{radius}', ')',- '-alpha', 'off', '-compose', 'CopyOpacity', '-composite',- ]- # iconutil expects full RGBA PNGs; grayscale-alpha inputs can collapse to a- # single low-resolution icns layer and make macOS show its generic wrapper.- args += ['-alpha', 'on', '-colorspace', 'sRGB', '-type', 'TrueColorAlpha']- args.append(output)- run(*args)+def render_base(magick, rsvg, output):+ # The panel keeps the website SVG unchanged. Application icons need a larger,+ # optically centered robot so its dark surround does not read as extra padding.+ namespace = 'http://www.w3.org/2000/svg'+ tree = ET.parse(SOURCE)+ robot = tree.getroot().find('.//{' + namespace + '}g[@filter="url(#robot-shadow)"]')+ if robot is None:+ raise SystemExit('website logo is missing its robot artwork group')+ robot.set('transform', 'translate(512 512) scale(1.14) translate(-490 -545) ' + robot.get('transform', ''))+ ET.register_namespace('', namespace)+ app_source = os.path.join(os.path.dirname(output), 'application-logo.svg')+ tree.write(app_source, encoding='unicode')+ # librsvg preserves the website's gradients, shadows and rounded alpha mask.+ run(rsvg, '--width', '1024', '--height', '1024', '--output', output, app_source)+ run(magick, output, '-alpha', 'on', '-colorspace', 'sRGB', '-type', 'TrueColorAlpha', output)def render_size(magick, source, size, output):@@ -60,13 +55,10 @@ def render_size(magick, source, size, output):)-def build_mac_icon(magick, iconutil, temp_dir):- base = os.path.join(temp_dir, 'mac-base.png')+def build_mac_icon(magick, iconutil, temp_dir, base):iconset = os.path.join(temp_dir, 'AppIcon.iconset')os.makedirs(iconset)- # macOS supplies the standard rounded app background. Supplying another- # background here creates a visible nested square in Finder/Get Info.- render_base(magick, base, rounded=False, with_background=False)+ # The SVG already owns its silhouette; do not add another background or mask.iconset_entries = [('icon_16x16.png', 16),('[email protected]', 32),@@ -85,26 +77,28 @@ def build_mac_icon(magick, iconutil, temp_dir):run(iconutil, '-c', 'icns', iconset, '-o', MAC_OUT)-def build_windows_icon(magick, temp_dir):- base = os.path.join(temp_dir, 'windows-base.png')- render_base(magick, base, rounded=True)+def build_windows_icon(magick, temp_dir, base):pngs = []for size in ICON_SIZES:output = os.path.join(temp_dir, f'windows-{size}.png')render_size(magick, base, size, output)pngs.append(output)os.makedirs(os.path.dirname(WIN_OUT), exist_ok=True)- run(magick, *pngs, '-colors', '256', WIN_OUT)+ run(magick, *pngs, WIN_OUT)def main():if not os.path.isfile(SOURCE):- raise SystemExit(f'missing icon foreground: {SOURCE}')+ raise SystemExit(f'missing website logo: {SOURCE}')magick = require_tool('magick')iconutil = require_tool('iconutil')+ rsvg = require_tool('rsvg-convert')with tempfile.TemporaryDirectory(prefix='workdaddy-icon-') as temp_dir:- build_mac_icon(magick, iconutil, temp_dir)- build_windows_icon(magick, temp_dir)+ base = os.path.join(temp_dir, 'website-logo.png')+ render_base(magick, rsvg, base)+ build_mac_icon(magick, iconutil, temp_dir, base)+ build_windows_icon(magick, temp_dir, base)+ shutil.copyfile(base, PNG_OUT)print(f'macOS icon: {MAC_OUT}')print(f'Windows icon: {WIN_OUT}')diff --git a/scripts/sentry-report.js b/scripts/sentry-report.jsindex e82caa9..eb16a6a 100644--- a/scripts/sentry-report.js+++ b/scripts/sentry-report.js@@ -79,6 +79,13 @@ function installationId() {return processInstallationId;}+function persistentInstallationId() {+ const id = installationId();+ try {+ return fs.readFileSync(INSTALLATION_ID_FILE, 'utf8').trim().toLowerCase() === id ? id : null;+ } catch (_) { return null; }+}+function telemetrySettingsPath(env = process.env) {const dataDir = String(env.WBSWITCH_DATA_DIR || DATA_DIR);return path.join(dataDir, path.basename(TELEMETRY_SETTINGS_FILE));@@ -363,6 +370,7 @@ async function cli() {}module.exports = {+ persistentInstallationId,captureMessage,captureException,flushOutbox,diff --git a/scripts/theme-patches.js b/scripts/theme-patches.jsindex a89f2b4..1e3dbf0 100644--- a/scripts/theme-patches.js+++ b/scripts/theme-patches.js@@ -477,6 +477,19 @@ module.exports = [desc: 'WorkBuddy 主题会话 widget 卡片(.cr-widget-card)使用主题毛玻璃,标题(.cr-widget-header)改为半透明以透出卡片层次',css: 'body[data-vscode-theme-name] .cr-widget-card{background:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 42%,transparent) !important;backdrop-filter:blur(18px) saturate(1.15) !important;-webkit-backdrop-filter:blur(18px) saturate(1.15) !important;border-color:var(--wb-border-subtle) !important;}body[data-vscode-theme-name] .cr-widget-header{background:color-mix(in srgb,var(--wb-bg-primary) 30%,transparent) !important;background-color:color-mix(in srgb,var(--wb-bg-primary) 30%,transparent) !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;border-color:var(--wb-border-subtle) !important;}',},+ {+ id: 'patch-100',+ themeId: 'nebula',+ desc: '毛玻璃主题:顶栏、会话外壳、侧栏去背景,透出已有壁纸与全局模糊层',+ css: ':is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container :is(.workbuddy-topbar--mac,.conversation-shell,.conversation-sidebar),body[data-vscode-theme-name="IDE Night"] .teams-container :is(.workbuddy-topbar--mac,.conversation-shell,.conversation-sidebar){background:transparent !important;background-color:transparent !important;}',+ },+ {+ id: 'patch-101',+ themeId: 'nebula',+ setting: 'textShadow',+ desc: '毛玻璃消息正文文字阴影(默认开启,可在主题面板关闭),不影响输入框或侧栏',+ css: 'body[data-vscode-theme-name] .conversation-timeline .cr-document,body[data-vscode-theme-name] .conversation-timeline .cr-document *{text-shadow:0 1px 2px rgba(0,0,0,.65),0 0 6px rgba(0,0,0,.3) !important;}',+ },/* 原 patch-82(AI 端快捷短语弹层 z-index 抬升)已移入 inject.js 常驻样式:theme-patches 仅在非默认主题时注入,默认浅色主题下会失效;层级修复不依赖主题,随注入脚本常驻更可靠。 */];diff --git a/scripts/theme-text-shadow.js b/scripts/theme-text-shadow.jsnew file mode 100644index 0000000..cb8979c--- /dev/null+++ b/scripts/theme-text-shadow.js@@ -0,0 +1,19 @@+'use strict';++const fs = require('node:fs');++function createThemeTextShadow(file) {+ return {+ read() {+ try { return JSON.parse(fs.readFileSync(file, 'utf8')).enabled !== false; }+ catch (_) { return true; }+ },+ save(value) {+ if (!value || typeof value.enabled !== 'boolean') throw new Error('enabled 必须是布尔值');+ fs.writeFileSync(file, JSON.stringify({ enabled: value.enabled }, null, 2));+ return value.enabled;+ },+ };+}++module.exports = { createThemeTextShadow };diff --git a/scripts/theme-vars.js b/scripts/theme-vars.jsindex f1b1cfc..07cbac6 100644--- a/scripts/theme-vars.js+++ b/scripts/theme-vars.js@@ -33,6 +33,13 @@ module.exports = {],// 组件作用域级变量:官方在这些组件上定义了局部浅色硬编码,必须同作用域重定向(直接定义 > 继承)scoped: [+ {+ sel: '.cr-tool-head__primary-tooltip-anchor',+ themeId: 'nebula',+ darkOnly: false,+ // tooltip 通用补丁命中了工具标题触发器;只清空此处的背景常量,保留真实弹窗底色。+ vars: { '--wb-bg-popover': 'transparent !important' },+ },{sel: '.cb-markdown',darkOnly: false,@@ -79,4 +86,4 @@ module.exports = {},},],-};\ No newline at end of file+};diff --git a/scripts/third-party-models.js b/scripts/third-party-models.jsnew file mode 100644index 0000000..28eafc5--- /dev/null+++ b/scripts/third-party-models.js@@ -0,0 +1,324 @@+'use strict';++// CC Switch source format reference: farion1231/cc-switch @ b78192e8fec3e062948237526d9c03ad08ea7831.+// Read providers only; never execute source config, contact endpoints, or expose credentials in previews.+const fs = require('fs');+const path = require('path');+const os = require('os');+const crypto = require('crypto');+const { createSessionDb } = require('./session-db');+const { readModelsFile, writeModelsFile } = require('./lib');+const MAX_PROVIDERS = 2000;+const MAX_MODELS = 5000;+const MAX_JSON_BYTES = 16 * 1024 * 1024;+const object = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {};+const str = value => typeof value === 'string' ? value.trim() : '';++function readJson(file) {+ if (fs.statSync(file).size > MAX_JSON_BYTES) throw new Error('CC Switch 配置过大,无法读取');+ try { return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); }+ catch (_) { throw new Error('CC Switch 配置不是有效 JSON'); }+}++function discoverCCSwitch(options = {}) {+ const home = options.home || os.homedir();+ const platform = options.platform || process.platform;+ const env = options.env || process.env;+ const appData = platform === 'win32' ? (env.APPDATA || path.join(home, 'AppData', 'Roaming'))+ : platform === 'darwin' ? path.join(home, 'Library', 'Application Support')+ : (env.XDG_DATA_HOME || path.join(home, '.local', 'share'));+ const dirs = [];+ const store = path.join(appData, 'com.ccswitch.desktop', 'app_paths.json');+ if (fs.existsSync(store)) {+ const raw = str(readJson(store).app_config_dir_override);+ const resolved = raw === '~' ? home : /^~[/\\]/.test(raw) ? path.join(home, raw.slice(2)) : raw;+ if (resolved && path.isAbsolute(resolved) && fs.existsSync(resolved)) dirs.push(resolved);+ }+ dirs.push(path.join(home, '.cc-switch'));+ if (platform === 'win32' && env.HOME && env.HOME !== home) dirs.push(path.join(env.HOME, '.cc-switch'));+ for (const dir of [...new Set(dirs)]) {+ for (const name of ['cc-switch.db', 'config.json']) {+ const file = path.join(dir, name);+ if (fs.existsSync(file) && fs.statSync(file).isFile()) return { id: 'cc-switch', name: 'CC Switch', file, format: name.endsWith('.db') ? 'sqlite' : 'json' };+ }+ }+ return null;+}++// Parse only the scalar TOML configuration used for model routing. Unsupported+// multiline/inline-table constructs are rejected instead of guessing or executing them.+function parseRoutingToml(text) {+ if (typeof text !== 'string' || text.length > MAX_JSON_BYTES) throw new Error('Codex 配置无效');+ const tables = new Map([['', {}]]);+ let table = tables.get('');+ function keyParts(raw) {+ const parts = raw.match(/"(?:\\.|[^"\\])*"|'[^']*'|[A-Za-z0-9_-]+/g) || [];+ if (parts.join('.').replace(/\s/g, '') !== raw.replace(/\s/g, '')) throw new Error('Codex 配置键格式暂不支持');+ return parts.map(p => p[0] === '"' ? JSON.parse(p) : p[0] === "'" ? p.slice(1, -1) : p);+ }+ for (const raw of text.replace(/^\uFEFF/, '').split(/\r?\n/)) {+ let quote = '', escaped = false, end = raw.length;+ for (let i = 0; i < raw.length; i++) {+ const c = raw[i];+ if (escaped) { escaped = false; continue; }+ if (quote === '"' && c === '\\') { escaped = true; continue; }+ if (quote) { if (c === quote) quote = ''; }+ else if (c === '"' || c === "'") quote = c;+ else if (c === '#') { end = i; break; }+ }+ const line = raw.slice(0, end).trim();+ if (!line) continue;+ if (line.includes('"""') || line.includes("'''")) throw new Error('Codex 多行 TOML 暂不支持');+ if (line.startsWith('[')) {+ if (!line.endsWith(']') || line.startsWith('[[')) { table = {}; continue; }+ const key = JSON.stringify(keyParts(line.slice(1, -1).trim()));+ if (!tables.has(key)) tables.set(key, {});+ table = tables.get(key);+ continue;+ }+ const match = line.match(/^([A-Za-z0-9_-]+|"(?:\\.|[^"\\])*")\s*=\s*(.*)$/);+ if (!match) continue;+ const key = keyParts(match[1])[0];+ if (!['model', 'model_provider', 'base_url', 'wire_api', 'env_key', 'api_key', 'model_reasoning_effort', 'model_context_window', 'model_max_output_tokens', 'requires_openai_auth'].includes(key)) continue;+ const value = match[2];+ if (/^"(?:\\.|[^"\\])*"$/.test(value)) table[key] = JSON.parse(value);+ else if (/^'[^']*'$/.test(value)) table[key] = value.slice(1, -1);+ else if (/^\d+$/.test(value)) table[key] = Number(value);+ else if (value === 'true' || value === 'false') table[key] = value === 'true';+ else throw new Error('Codex 模型配置包含暂不支持的 TOML 写法');+ }+ return tables;+}++function secret(value, env) {+ const text = str(value);+ const ref = text.match(/^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$|^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/);+ if (ref) return str(env[ref[1] || ref[2]]);+ if (/^\{(?:file|env):|^\$|^<|YOUR[_ -]|PLACEHOLDER/i.test(text)) return '';+ return text;+}++function chatEndpoint(raw, format) {+ let url;+ try { url = new URL(raw); } catch (_) { throw new Error('缺少有效的接口地址'); }+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {+ throw new Error('接口地址需为不含凭据或查询参数的 HTTP(S) 地址');+ }+ if (url.hostname === 'api.anthropic.com' || url.hostname.endsWith('.anthropic.com')) {+ throw new Error('Anthropic 官方接口不支持 WorkBuddy 所需的 OpenAI 协议');+ }+ let p = url.pathname.replace(/\/+$/, '');+ if (format === 'gemini_native' && url.hostname === 'generativelanguage.googleapis.com') p = '/v1beta/openai';+ else {+ p = p.replace(/\/(?:chat\/completions|responses|messages)$/, '');+ if (!p) p = '/v1';+ }+ url.pathname = p + '/chat/completions';+ return url.toString();+}++function convertProvider(provider, env = process.env) {+ const type = str(provider.app_type);+ const label = str(provider.name) || type || '未命名供应商';+ let config, meta;+ try {+ config = typeof provider.settings_config === 'string' ? JSON.parse(provider.settings_config) : (provider.settings_config || provider.settingsConfig);+ meta = typeof provider.meta === 'string' ? JSON.parse(provider.meta) : provider.meta;+ } catch (_) { return [{ provider: label, appType: type, reason: '供应商配置不是有效 JSON' }]; }+ config = object(config); meta = object(meta);+ const rows = [], seen = new Set();+ const blocked = reason => rows.push({ provider: label, appType: type, reason });+ const add = (id, base, key, format, details = {}) => {+ id = str(id);+ if (!id) return;+ const identity = JSON.stringify([id, base, key, format]);+ if (seen.has(identity)) return;+ seen.add(identity);+ try {+ if (rows.length >= MAX_MODELS) throw new Error('供应商模型数量过多');+ if (id.length > 256 || /[\x00-\x1f]/.test(id)) throw new Error('模型名无效');+ if (meta.authBinding && !str(key)) throw new Error('账号登录授权不能作为 API Key 导入');+ const apiKey = secret(key, env);+ if (!apiKey) throw new Error('缺少 API Key,或环境变量尚未配置(OAuth 登录不能直接导入)');+ if (apiKey.length > 20000) throw new Error('API Key 格式无效');+ if (!['openai_chat', 'openai_responses', 'anthropic', 'gemini_native'].includes(format)) throw new Error('此供应商协议暂不支持');+ const url = chatEndpoint(base, format);+ const model = { id, name: label + ' · ' + (str(details.name) || id), vendor: 'Custom', url, apiKey,+ useCustomProtocol: false, supportsToolCall: details.tool_call !== false, supportsImages: !!details.images, supportsReasoning: !!details.reasoning };+ for (const [field, value] of [['maxInputTokens', details.context], ['maxOutputTokens', details.output]]) {+ if (Number.isSafeInteger(value) && value > 0) model[field] = value;+ }+ if (str(details.effort)) { model.supportsReasoning = true; model.reasoning = { effort: str(details.effort) }; }+ rows.push({ provider: label, appType: type, model });+ } catch (error) { rows.push({ provider: label, appType: type, id, reason: error.message }); }+ };+ try {+ const values = object(config.env);+ if (type === 'claude') {+ const key = values[meta.apiKeyField] || values.ANTHROPIC_AUTH_TOKEN || values.ANTHROPIC_API_KEY;+ const id = values.ANTHROPIC_MODEL || config.model || values.ANTHROPIC_DEFAULT_SONNET_MODEL;+ add(id, values.ANTHROPIC_BASE_URL || 'https://api.anthropic.com', key, meta.apiFormat || 'anthropic');+ } else if (type === 'codex') {+ const tables = parseRoutingToml(config.config || '');+ const defaults = tables.get('');+ const variants = [defaults, ...[...tables].filter(([key]) => key && JSON.parse(key)[0] === 'profiles' && JSON.parse(key).length === 2).map(([, value]) => ({ ...defaults, ...value }))];+ for (const variant of variants) {+ const providerId = str(variant.model_provider) || 'openai';+ const details = tables.get(JSON.stringify(['model_providers', providerId])) || {};+ const base = details.base_url || (providerId === 'openai' ? 'https://api.openai.com/v1' : '');+ const key = (details.env_key ? env[details.env_key] : '') || details.api_key || object(config.auth).OPENAI_API_KEY;+ add(variant.model, base, key, meta.apiFormat || (details.wire_api === 'chat' ? 'openai_chat' : 'openai_responses'),+ { effort: variant.model_reasoning_effort, context: variant.model_context_window, output: variant.model_max_output_tokens });+ }+ } else if (type === 'gemini') {+ add(values.GEMINI_MODEL || object(object(config.config).model).name, values.GOOGLE_GEMINI_BASE_URL || 'https://generativelanguage.googleapis.com', values.GEMINI_API_KEY || values.GOOGLE_API_KEY, 'gemini_native');+ } else if (type === 'opencode') {+ const opts = object(config.options);+ const format = { '@ai-sdk/openai-compatible': 'openai_chat', '@ai-sdk/openai': 'openai_responses', '@ai-sdk/anthropic': 'anthropic', '@ai-sdk/google': 'gemini_native' }[config.npm];+ if (Object.keys(object(opts.headers)).length) throw new Error('包含额外认证请求头,不能直接导入');+ for (const [id, model] of Object.entries(object(config.models))) {+ const d = object(model), limit = object(d.limit);+ add(id, opts.baseURL, opts.apiKey, format, { ...d, context: limit.context, output: limit.output, images: (object(d.modalities).input || []).includes('image') });+ }+ } else if (type === 'openclaw') {+ const format = { 'openai-completions': 'openai_chat', 'openai-responses': 'openai_responses', 'anthropic-messages': 'anthropic', 'google-generative-ai': 'gemini_native' }[config.api];+ if (Object.keys(object(config.headers)).length) throw new Error('包含额外认证请求头,不能直接导入');+ for (const d of Array.isArray(config.models) ? config.models : []) add(d.id, config.baseUrl, config.apiKey, format, { ...d, context: d.contextWindow, output: d.maxTokens, images: (d.input || []).includes('image') });+ } else blocked('此客户端的供应商配置暂不支持导入');+ } catch (_) { blocked('模型配置格式暂不支持,或包含无法迁移的认证设置'); }+ if (!rows.length) blocked('未配置明确的模型名;请先在 CC Switch 中填写模型和 API Key');+ return rows;+}++async function readCCSwitch(options = {}) {+ const source = discoverCCSwitch(options);+ if (!source) return { found: false, rows: [] };+ let providers = [], common = {};+ if (source.format === 'sqlite') {+ const db = createSessionDb({ dbPath: source.file });+ try {+ const columns = await db.all('PRAGMA table_info(providers)');+ const names = new Set(columns.map(c => c.name));+ if (!['id', 'name', 'app_type', 'settings_config'].every(c => names.has(c))) throw new Error('schema');+ providers = await db.all(`SELECT id, name, app_type, settings_config${names.has('meta') ? ', meta' : ''} FROM providers ORDER BY app_type, id LIMIT ${MAX_PROVIDERS + 1}`);+ const tables = await db.all("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'settings'");+ if (tables.length) {+ for (const row of await db.all("SELECT key, value FROM settings WHERE key IN ('common_config_claude', 'common_config_codex', 'common_config_gemini')")) common[row.key.replace('common_config_', '')] = row.value;+ }+ } catch (_) { throw new Error('无法读取 CC Switch 数据库,请关闭 CC Switch 后重试或检查版本'); }+ } else {+ const config = object(readJson(source.file));+ for (const [type, manager] of Object.entries(config)) {+ for (const [id, provider] of Object.entries(object(object(manager).providers))) providers.push({ ...object(provider), id: provider.id || id, app_type: type });+ }+ // Pre-multi-app releases stored Claude providers directly at the root.+ if (!providers.length) for (const [id, provider] of Object.entries(object(config.providers))) providers.push({ ...object(provider), id, app_type: 'claude' });+ common = object(config.common_config_snippets);+ if (config.claude_common_config_snippet && !common.claude) common.claude = config.claude_common_config_snippet;+ }+ if (providers.length > MAX_PROVIDERS) throw new Error('CC Switch 供应商数量超过读取上限');+ const rows = [];+ for (const provider of providers) {+ // Common snippets explicitly enabled in CC Switch override provider values.+ let effective = provider;+ try {+ const meta = typeof provider.meta === 'string' ? JSON.parse(provider.meta) : object(provider.meta);+ const snippet = common[provider.app_type];+ if (meta.commonConfigEnabled === true && snippet) {+ const config = typeof provider.settings_config === 'string' ? JSON.parse(provider.settings_config) : (provider.settings_config || provider.settingsConfig);+ const next = { ...object(config) };+ if (provider.app_type === 'codex') {+ // Overlay only routing scalars/tables after parsing each document independently.+ const a = parseRoutingToml(next.config || ''), b = parseRoutingToml(snippet);+ for (const [key, value] of b) a.set(key, { ...a.get(key), ...value });+ next.config = [...a].map(([key, value]) => (key ? '[' + JSON.parse(key).map(x => JSON.stringify(x)).join('.') + ']\n' : '') + Object.entries(value).map(([k, v]) => k + ' = ' + JSON.stringify(v)).join('\n')).join('\n');+ } else {+ const patch = object(JSON.parse(snippet));+ next.env = { ...object(next.env), ...object(provider.app_type === 'claude' ? patch.env : patch) };+ if (provider.app_type === 'claude' && patch.model) next.model = patch.model;+ }+ effective = { ...provider, settings_config: next };+ }+ } catch (_) { rows.push({ provider: str(provider.name), appType: provider.app_type, reason: '通用配置片段无法解析' }); continue; }+ for (const row of convertProvider(effective, options.env || process.env)) {+ const key = crypto.createHash('sha256').update(JSON.stringify([provider.app_type, provider.id, row.id || row.model?.id || '', row.model?.url || ''])).digest('hex');+ const providerKey = crypto.createHash('sha256').update(JSON.stringify([provider.app_type, provider.id])).digest('hex');+ rows.push({ ...row, key, providerKey });+ if (rows.length > MAX_MODELS) throw new Error('CC Switch 模型数量超过读取上限');+ }+ }+ return { found: true, rows };+}++function createThirdPartyImport(options) {+ const snapshots = new Map();+ const now = options.now || Date.now;+ function prune() {+ for (const [id, value] of snapshots) if (now() - value.created > 10 * 60 * 1000) snapshots.delete(id);+ while (snapshots.size >= 4) snapshots.delete(snapshots.keys().next().value);+ }+ return {+ discover() { return discoverCCSwitch(options) ? [{ id: 'cc-switch', name: 'CC Switch' }] : []; },+ async preview() {+ const data = await readCCSwitch(options);+ if (!data.found) throw new Error('未检测到 CC Switch 本地模型配置');+ prune();+ const snapshot = crypto.randomUUID();+ snapshots.set(snapshot, { created: now(), rows: data.rows });+ const usable = data.rows.filter(row => row && row.model);+ return { snapshot, models: usable.map(row => ({ key: row.key, providerKey: row.providerKey, provider: row.provider, appType: row.appType,+ id: row.model.id, name: row.model.name || row.provider, url: row.model.url || '', apiKey: row.model.apiKey || '' })) };+ },+ async import(body) {+ if (!body) throw new Error('未选择有效模型');+ const snapshot = snapshots.get(body.snapshot);+ if (!snapshot || now() - snapshot.created > 10 * 60 * 1000) throw new Error('模型列表已失效,请重新读取');+ if (!Array.isArray(body.ids) || !body.ids.length || body.ids.length > MAX_MODELS || body.ids.some(id => typeof id !== 'string')) throw new Error('未选择有效模型');+ const ids = [...new Set(body.ids)];+ const selected = ids.map(id => snapshot.rows.find(row => row.key === id));+ if (selected.some(row => !row || !row.model)) throw new Error('模型选择无效,请重新读取');+ // WorkBuddy has one physical config per model ID. Preserve every selected+ // provider in backups before resolving same-ID conflicts in source order.+ const { writeModelBackup } = require('./lib');+ const target = readModelsFile(options.targetFile);+ const models = target.models.slice();+ let replaced = 0;+ const byId = new Map();+ for (const row of selected) byId.set(row.model.id, row.model);+ const duplicateIds = new Set(selected.filter((row, index) => selected.findIndex(other => other.model.id === row.model.id) !== index).map(row => row.model.id)).size;+ const existingIds = new Set(models.map(model => str(model && model.id)));+ const conflicts = [...byId.keys()].filter(id => existingIds.has(id)).length;+ // Check the current file at submission time. A conflict-free import writes+ // immediately; otherwise return counts without creating backups or writing.+ if (body.confirmed !== true && (conflicts || duplicateIds)) {+ return { confirmationRequired: true, replaced: conflicts, duplicateIds };+ }+ const next = [];+ const written = new Set();+ for (const existing of models) {+ const id = str(existing && existing.id);+ if (byId.has(id)) {+ if (!written.has(id)) { next.push(byId.get(id)); written.add(id); replaced++; }+ } else next.push(existing);+ }+ for (const [id, model] of byId) if (!written.has(id)) next.push(model);+ let backupFile = '';+ if (fs.existsSync(target.file)) {+ backupFile = target.file + '.before-cc-switch-' + crypto.randomUUID() + '.bak';+ fs.copyFileSync(target.file, backupFile, fs.constants.COPYFILE_EXCL);+ fs.chmodSync(backupFile, 0o600);+ }+ if (target.format === 'object' && Array.isArray(target.wrapper.availableModels)) {+ target.wrapper = { ...target.wrapper, availableModels: [...new Set([...target.wrapper.availableModels, ...byId.keys()])] };+ }+ for (const row of selected) writeModelBackup(options.dataDir || path.dirname(target.file), {+ schema: 1, backupId: crypto.randomUUID(), createdAt: new Date().toISOString(), model: row.model,+ });+ writeModelsFile(target, next);+ snapshots.delete(body.snapshot);+ return { imported: byId.size, replaced, sameIdSkipped: selected.length - byId.size, backupFile };+ },+ };+}++module.exports = { discoverCCSwitch, convertProvider, readCCSwitch, createThirdPartyImport };diff --git a/scripts/token-stats.js b/scripts/token-stats.jsnew file mode 100644index 0000000..aacbc94--- /dev/null+++ b/scripts/token-stats.js@@ -0,0 +1,463 @@+'use strict';++const fs = require('fs');+const path = require('path');++const TOKEN_FIELDS = {+ input: ['input_tokens', 'prompt_tokens', 'inputTokens', 'promptTokens'],+ output: ['output_tokens', 'completion_tokens', 'outputTokens', 'completionTokens'],+ cacheRead: ['cache_read_input_tokens', 'cache_read_tokens', 'cacheReadTokens', 'cached_tokens'],+ cacheWrite: ['cache_creation_input_tokens', 'cache_write_tokens', 'cacheWriteTokens'],+};++function numberField(value, fields) {+ for (const field of fields) {+ const number = Number(value && value[field]);+ if (Number.isFinite(number) && number >= 0) return number;+ }+ return 0;+}++function findUsage(value, depth = 0) {+ if (!value || typeof value !== 'object' || depth > 4) return null;+ const hasUsage = Object.values(TOKEN_FIELDS).some((fields) => fields.some((field) => value[field] !== undefined));+ if (hasUsage) return value;+ for (const child of Object.values(value)) {+ const found = findUsage(child, depth + 1);+ if (found) return found;+ }+ return null;+}++function findText(value, fields, depth = 0) {+ if (!value || typeof value !== 'object' || depth > 4) return '';+ for (const field of fields) {+ if (typeof value[field] === 'string' && value[field].trim()) return value[field].trim();+ }+ for (const child of Object.values(value)) {+ const found = findText(child, fields, depth + 1);+ if (found) return found;+ }+ return '';+}++function walkJsonl(root, maxFiles = 5000) {+ const out = [];+ function walk(dir) {+ if (out.length >= maxFiles) return;+ let entries;+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return; }+ for (const entry of entries) {+ if (out.length >= maxFiles) return;+ if (entry.name === 'subagents' || entry.name.startsWith('.')) continue;+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else if (entry.isFile() && entry.name.endsWith('.jsonl')) out.push(full);+ }+ }+ // Official session files live under projects; logs contain duplicate usage snapshots.+ const projects = path.join(root, 'projects');+ walk(fs.existsSync(projects) ? projects : root);+ return out;+}++function dayString(timestamp) {+ const date = new Date(timestamp);+ return Number.isFinite(date.getTime()) ? date.toISOString().slice(0, 10) : null;+}++function localDayString(timestamp) {+ const date = new Date(timestamp);+ if (!Number.isFinite(date.getTime())) return null;+ const y = date.getFullYear();+ const m = String(date.getMonth() + 1).padStart(2, '0');+ const d = String(date.getDate()).padStart(2, '0');+ return `${y}-${m}-${d}`;+}++function timestampValue(value, fallback) {+ if (typeof value === 'number' && Number.isFinite(value)) return value < 1e12 ? value * 1000 : value;+ if (typeof value === 'string' && value.trim()) {+ const numeric = Number(value);+ if (Number.isFinite(numeric)) return numeric < 1e12 ? numeric * 1000 : numeric;+ const parsed = Date.parse(value);+ if (Number.isFinite(parsed)) return parsed;+ }+ return fallback;+}++const CACHE_VERSION = 7;+const MAX_CACHE_DAYS = 90;+const DAY_MS = 24 * 60 * 60 * 1000;++function dateBounds(now, options = {}) {+ const days = Math.max(1, Math.min(MAX_CACHE_DAYS, Number(options.days) || 7));+ const localStart = new Date(now); localStart.setHours(0, 0, 0, 0);+ localStart.setDate(localStart.getDate() - (days - 1));+ const defaultSince = localStart.getTime();+ const parsedFrom = options.from ? Date.parse(options.from) : NaN;+ const parsedUntil = options.until ? Date.parse(options.until) + DAY_MS - 1 : now;+ if (options.from && !Number.isFinite(parsedFrom)) throw new Error('开始日期无效');+ if (options.until && !Number.isFinite(parsedUntil)) throw new Error('结束日期无效');+ const from = Number.isFinite(parsedFrom) ? parsedFrom : defaultSince;+ const until = Number.isFinite(parsedUntil) ? Math.min(parsedUntil, now) : now;+ if (from > until) throw new Error('开始日期不能晚于结束日期');+ if (until - from > MAX_CACHE_DAYS * DAY_MS) throw new Error('日期范围不能超过 90 天');+ return { from, until, days };+}++function parseRecords(root, options = {}) {+ const now = Number(options.now) || Date.now();+ const lowerBound = Number.isFinite(options.lowerBound) ? options.lowerBound : now - MAX_CACHE_DAYS * DAY_MS;+ const upperBound = Number.isFinite(options.upperBound) ? options.upperBound : now + 60 * 1000;+ const files = Array.isArray(options.files) ? options.files : walkJsonl(root, options.maxFiles || 5000);+ const accountIds = new Set((options.accountOptions || []).map((item) => String(item && (item.uid || item.account) || '').trim()).filter(Boolean));+ const records = [];+ let parseErrors = 0;+ let parsedLines = 0;+ const parseErrorFiles = new Set();+ for (const file of files) {+ const relative = path.relative(root, file).split(path.sep).join('/');+ if (options.skipUnchanged && options.knownFileState && options.knownFileState[relative]) {+ try {+ const stat = fs.statSync(file);+ const known = options.knownFileState[relative];+ if (Number(known.mtimeMs) === Number(stat.mtimeMs) && Number(known.size) === Number(stat.size)) continue;+ } catch (_) { continue; }+ }+ let text;+ try { text = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }+ let lineIndex = 0;+ for (const line of text.split(/\r?\n/)) {+ lineIndex++;+ if (!line.trim()) continue;+ let record;+ try { record = JSON.parse(line); } catch (_) {+ // Only object-like lines are likely structured records. WorkBuddy may+ // place plain text, stack traces, or array annotations in the same file.+ if (/^\s*\{/.test(line) && /"(?:usage|input_tokens|output_tokens|model)"/i.test(line)) {+ parseErrors++;+ parseErrorFiles.add(relative);+ }+ continue;+ }+ if (record.isSnapshotUpdate) continue;+ const usage = findUsage(record.message && record.message.usage) || findUsage(record.providerData && record.providerData.usage) || findUsage(record);+ if (!usage) continue;+ const timestamp = timestampValue(record.timestamp || record.created_at || record.createdAt || usage.timestamp, now);+ if (!Number.isFinite(timestamp) || timestamp < lowerBound || timestamp > upperBound) continue;+ const input = numberField(usage, TOKEN_FIELDS.input);+ const output = numberField(usage, TOKEN_FIELDS.output);+ const cacheRead = numberField(usage, TOKEN_FIELDS.cacheRead);+ const cacheWrite = numberField(usage, TOKEN_FIELDS.cacheWrite);+ if (!(input || output || cacheRead || cacheWrite)) continue;+ const model = findText(record, ['model', 'modelName', 'model_id', 'modelId']) || findText(usage, ['model', 'modelName', 'model_id', 'modelId']);+ let account = findText(record, ['accountUid', 'accountId', 'uid', 'userId']) || findText(usage, ['accountUid', 'accountId', 'uid', 'userId']);+ if (!account && options.sessionAccounts) {+ const sessionId = path.basename(file, '.jsonl');+ account = options.sessionAccounts instanceof Map+ ? String(options.sessionAccounts.get(sessionId) || '')+ : String(options.sessionAccounts[sessionId] || '');+ }+ if (!account && accountIds.size) {+ const pathPart = relative.split('/').find((part) => accountIds.has(part.replace(/\.jsonl$/i, '')));+ if (pathPart) account = pathPart.replace(/\.jsonl$/i, '');+ }+ records.push({+ key: relative + ':' + lineIndex,+ timestamp,+ model: model || '',+ account: account || '',+ input,+ output,+ cacheRead,+ cacheWrite,+ calls: 1,+ });+ parsedLines++;+ }+ }+ return { records, files: files.length, parsedLines, parseErrors, parseErrorFiles: Array.from(parseErrorFiles) };+}++function cacheFile(root, options = {}) {+ return options.cacheFile || path.join(root, '.workdaddy-token-stats-cache.json');+}++function readCache(file) {+ try {+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));+ if (!value || value.version !== CACHE_VERSION || !Array.isArray(value.historicalBuckets) || !value.todayFiles || typeof value.todayFiles !== 'object') return null;+ return value;+ } catch (_) { return null; }+}++function usableCache(cache, now) {+ return !!cache && Number.isFinite(cache.generatedAt) && cache.generatedAt <= now &&+ Number.isFinite(cache.cutoff) && cache.cutoff <= dateBounds(now, { days: MAX_CACHE_DAYS }).from &&+ cache.timezone === Intl.DateTimeFormat().resolvedOptions().timeZone;+}++function tokenStatsCacheReady(root, options = {}) {+ return usableCache(readCache(cacheFile(root, options)), Number(options.now) || Date.now());+}++function writeCache(file, payload) {+ try {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const tmp = file + '.tmp';+ fs.writeFileSync(tmp, JSON.stringify(payload), { mode: 0o600 });+ fs.renameSync(tmp, file);+ return true;+ } catch (_) { return false; /* cache failure must not break statistics */ }+}++function aggregateRecords(records, options = {}) {+ const now = Number(options.now) || Date.now();+ const bounds = dateBounds(now, options);+ const accountFilter = String(options.account || '').trim();+ const modelFilter = String(options.model || '').trim();+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ const byDay = new Map();+ const byModel = new Map();+ const byAccount = new Map();+ for (const record of records) {+ if (!record || record.timestamp < bounds.from || record.timestamp > bounds.until) continue;+ if (accountFilter && record.account !== accountFilter) continue;+ if (modelFilter && record.model !== modelFilter) continue;+ const values = { input: Number(record.input) || 0, output: Number(record.output) || 0, cacheRead: Number(record.cacheRead) || 0, cacheWrite: Number(record.cacheWrite) || 0, calls: Number(record.calls) || 1 };+ for (const key of Object.keys(totals)) totals[key] += values[key];+ const day = localDayString(record.timestamp);+ if (day) {+ const row = byDay.get(day) || { day, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ for (const key of Object.keys(values)) row[key] += values[key];+ byDay.set(day, row);+ }+ if (record.model) {+ const row = byModel.get(record.model) || { model: record.model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ for (const key of Object.keys(values)) row[key] += values[key];+ byModel.set(record.model, row);+ }+ if (record.account) {+ const row = byAccount.get(record.account) || { account: record.account, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ for (const key of Object.keys(values)) row[key] += values[key];+ byAccount.set(record.account, row);+ }+ }+ const accountOptions = Array.isArray(options.accountOptions) ? options.accountOptions : [];+ for (const account of accountOptions) {+ const uid = String(account && (account.uid || account.account) || '').trim();+ if (!uid) continue;+ if (!byAccount.has(uid)) byAccount.set(uid, { account: uid, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0, nickname: account.nickname || '' });+ else if (account.nickname) byAccount.get(uid).nickname = account.nickname;+ }+ return {+ source: 'local-workbuddy-jsonl',+ since: bounds.from,+ until: bounds.until,+ totals,+ daily: Array.from(byDay.values()).sort((a, b) => a.day.localeCompare(b.day)),+ models: Array.from(byModel.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),+ accounts: Array.from(byAccount.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),+ };+}++function aggregateBuckets(records) {+ const buckets = new Map();+ for (const record of records || []) {+ const day = localDayString(record.timestamp);+ if (!day) continue;+ const account = String(record.account || '');+ const model = String(record.model || '');+ const key = day + '\u0000' + account + '\u0000' + model;+ const bucket = buckets.get(key) || { day, account, model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ bucket.input += Number(record.input) || 0;+ bucket.output += Number(record.output) || 0;+ bucket.cacheRead += Number(record.cacheRead) || 0;+ bucket.cacheWrite += Number(record.cacheWrite) || 0;+ bucket.calls += Number(record.calls) || 1;+ buckets.set(key, bucket);+ }+ return Array.from(buckets.values());+}++function aggregateCachedBuckets(buckets, options = {}) {+ const now = Number(options.now) || Date.now();+ const bounds = dateBounds(now, options);+ const accountFilter = String(options.account || '').trim();+ const modelFilter = String(options.model || '').trim();+ const firstDay = localDayString(bounds.from);+ const lastDay = localDayString(bounds.until);+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ const byDay = new Map();+ const byModel = new Map();+ const byAccount = new Map();+ for (const bucket of buckets || []) {+ if (!bucket || !bucket.day) continue;+ if (bucket.day < firstDay || bucket.day > lastDay) continue;+ if (accountFilter && String(bucket.account || '') !== accountFilter) continue;+ if (modelFilter && String(bucket.model || '') !== modelFilter) continue;+ const values = {+ input: Number(bucket.input) || 0,+ output: Number(bucket.output) || 0,+ cacheRead: Number(bucket.cacheRead) || 0,+ cacheWrite: Number(bucket.cacheWrite) || 0,+ calls: Number(bucket.calls) || 0,+ };+ for (const key of Object.keys(totals)) totals[key] += values[key];+ const day = String(bucket.day);+ const dayRow = byDay.get(day) || { day, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ for (const key of Object.keys(values)) dayRow[key] += values[key];+ byDay.set(day, dayRow);+ if (bucket.model) {+ const modelRow = byModel.get(bucket.model) || { model: bucket.model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ for (const key of Object.keys(values)) modelRow[key] += values[key];+ byModel.set(bucket.model, modelRow);+ }+ if (bucket.account) {+ const accountRow = byAccount.get(bucket.account) || { account: bucket.account, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ for (const key of Object.keys(values)) accountRow[key] += values[key];+ byAccount.set(bucket.account, accountRow);+ }+ }+ const accountOptions = Array.isArray(options.accountOptions) ? options.accountOptions : [];+ for (const account of accountOptions) {+ const uid = String(account && (account.uid || account.account) || '').trim();+ if (!uid) continue;+ if (!byAccount.has(uid)) byAccount.set(uid, { account: uid, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0, nickname: account.nickname || '' });+ else if (account.nickname) byAccount.get(uid).nickname = account.nickname;+ }+ return {+ source: 'local-workbuddy-jsonl', since: bounds.from, until: bounds.until, totals,+ daily: Array.from(byDay.values()).sort((a, b) => a.day.localeCompare(b.day)),+ models: Array.from(byModel.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),+ accounts: Array.from(byAccount.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),+ };+}++function scanTokenStatsCached(root, options = {}) {+ const now = Number(options.now) || Date.now();+ // Always cache the complete retained range, independent of the UI filter.+ // Each file owns its buckets: replacing a changed file cannot drop another+ // file's usage on the same date or count immutable/live history twice.+ const cutoff = dateBounds(now, { days: MAX_CACHE_DAYS }).from;+ const file = cacheFile(root, options);+ const cache = readCache(file);+ const hadValidCache = usableCache(cache, now);+ const currentFiles = walkJsonl(root, options.maxFiles || 5000);+ const todayFiles = {};+ let parsedLines = 0, parseErrors = 0;+ const parseErrorFiles = new Set();+ for (const currentFile of currentFiles) {+ const relative = path.relative(root, currentFile).split(path.sep).join('/');+ let stat;+ try { stat = fs.statSync(currentFile); } catch (_) { continue; }+ const known = hadValidCache && cache.todayFiles[relative];+ let item;+ if (known && known.mtimeMs === stat.mtimeMs && known.size === stat.size) {+ item = known;+ } else {+ const parsed = parseRecords(root, { ...options, now, lowerBound: cutoff, upperBound: now,+ files: [currentFile] });+ item = { mtimeMs: stat.mtimeMs, size: stat.size, buckets: aggregateBuckets(parsed.records),+ parsedLines: parsed.parsedLines, parseErrors: parsed.parseErrors, parseErrorFiles: parsed.parseErrorFiles };+ }+ item.buckets = item.buckets.filter(bucket => bucket.day >= localDayString(cutoff));+ todayFiles[relative] = item;+ parsedLines += item.parsedLines || 0;+ parseErrors += item.parseErrors || 0;+ for (const errorFile of item.parseErrorFiles || []) parseErrorFiles.add(errorFile);+ }+ const buckets = Object.values(todayFiles).flatMap(item => item.buckets);+ const cacheReady = writeCache(file, { version: CACHE_VERSION, generatedAt: now, cutoff,+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ historicalBuckets: [], todayFiles });+ const stats = aggregateCachedBuckets(buckets, { ...options, now });+ return { ...stats, files: currentFiles.length, parsedLines, parseErrors,+ parseErrorFiles: Array.from(parseErrorFiles), cached: hadValidCache, cacheHit: hadValidCache,+ cacheReady, cacheGeneratedAt: hadValidCache ? cache.generatedAt : now };+}++function scanTokenStats(root, options = {}) {+ const now = Number(options.now) || Date.now();+ const days = Math.max(1, Math.min(90, Number(options.days) || 7));+ const localStart = new Date(now); localStart.setHours(0, 0, 0, 0);+ const since = dateBounds(now, { days }).from;+ const from = options.from ? Date.parse(options.from) : since;+ const until = options.until ? Date.parse(options.until) + 24 * 60 * 60 * 1000 - 1 : now;+ const accountFilter = String(options.account || '').trim();+ const modelFilter = String(options.model || '').trim();+ const files = walkJsonl(root, options.maxFiles || 5000);+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ const byDay = new Map();+ const byModel = new Map();+ const byAccount = new Map();+ let parsedLines = 0;+ let parseErrors = 0;+ for (const file of files) {+ let text;+ try { text = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }+ const relative = path.relative(root, file).split(path.sep);+ const project = relative.length > 1 ? relative[0] : '';+ const session = path.basename(file, '.jsonl');+ for (const line of text.split(/\r?\n/)) {+ if (!line.trim()) continue;+ let record;+ try { record = JSON.parse(line); } catch (_) {+ // Some WorkBuddy files contain non-JSON annotations between records; only+ // count malformed object/array lines as parse errors worth surfacing.+ if (/^\s*[\[{]/.test(line)) parseErrors++;+ continue;+ }+ if (record.isSnapshotUpdate) continue;+ const usage = findUsage(record.message && record.message.usage) || findUsage(record.providerData && record.providerData.usage) || findUsage(record);+ if (!usage) continue;+ const timestamp = timestampValue(record.timestamp || record.created_at || record.createdAt || usage.timestamp, now);+ if (!Number.isFinite(timestamp) || timestamp < since || timestamp > now + 60 * 1000) continue;+ const input = numberField(usage, TOKEN_FIELDS.input);+ const output = numberField(usage, TOKEN_FIELDS.output);+ const cacheRead = numberField(usage, TOKEN_FIELDS.cacheRead);+ const cacheWrite = numberField(usage, TOKEN_FIELDS.cacheWrite);+ if (!(input || output || cacheRead || cacheWrite)) continue;+ const model = findText(record, ['model', 'modelName', 'model_id', 'modelId']) || findText(usage, ['model', 'modelName', 'model_id', 'modelId']);+ const account = findText(record, ['accountUid', 'accountId', 'uid', 'userId']) || findText(usage, ['accountUid', 'accountId', 'uid', 'userId']);+ if (Number.isFinite(from) && timestamp < from) continue;+ if (Number.isFinite(until) && timestamp > until) continue;+ if (accountFilter && account !== accountFilter) continue;+ if (modelFilter && model !== modelFilter) continue;+ const values = { input, output, cacheRead, cacheWrite, calls: 1 };+ for (const key of Object.keys(totals)) totals[key] += values[key];+ const day = localDayString(timestamp);+ if (day) {+ const current = byDay.get(day) || { day, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ for (const key of Object.keys(values)) current[key] += values[key];+ byDay.set(day, current);+ }+ if (model) {+ const modelRow = byModel.get(model) || { model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ for (const key of Object.keys(values)) modelRow[key] += values[key];+ byModel.set(model, modelRow);+ }+ if (account) {+ const accountRow = byAccount.get(account) || { account, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };+ for (const key of Object.keys(values)) accountRow[key] += values[key];+ byAccount.set(account, accountRow);+ }+ parsedLines++;+ }+ }+ return {+ source: 'local-workbuddy-jsonl',+ since,+ until: now,+ files: files.length,+ parsedLines,+ parseErrors,+ totals,+ daily: Array.from(byDay.values()).sort((a, b) => a.day.localeCompare(b.day)),+ models: Array.from(byModel.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),+ accounts: Array.from(byAccount.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),+ };+}++module.exports = { tokenStatsCacheReady, scanTokenStats, scanTokenStatsCached, findUsage, walkJsonl, dateBounds };diff --git a/scripts/usage-report.js b/scripts/usage-report.jsnew file mode 100644index 0000000..df435b4--- /dev/null+++ b/scripts/usage-report.js@@ -0,0 +1,101 @@+'use strict';++// Anonymous installation / daily-active counts only. No account or renderer data.+const fs = require('fs');+const path = require('path');+const os = require('os');+const https = require('https');+const { telemetryEnabled, persistentInstallationId } = require('./sentry-report.js');+const { sharedDataDir } = require('./profiles.js');+const ENDPOINT = 'https://workdaddy.dev/api/track';+const RETRY_MS = 6 * 3600000;+const usageDay = (time) => new Date(time + 8 * 3600000).toISOString().slice(0, 10);++function sendUsage(body, signal) {+ return new Promise((resolve) => {+ const data = JSON.stringify(body);+ let timer;+ const finish = (result) => { clearTimeout(timer); resolve(result); };+ const req = https.request(ENDPOINT, { method: 'POST', signal,+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) },+ }, (res) => {+ // Never follow redirects or read/log the response body. A Pages fallback+ // page is not an acknowledgement from the collector.+ finish({ status: res.headers['x-workdaddy-usage'] === '1' ? res.statusCode : 0 });+ res.destroy();+ });+ timer = setTimeout(() => { finish({ status: 0 }); req.destroy(); }, 5000);+ timer.unref();+ req.on('error', () => finish({ status: 0 }));+ req.end(data);+ });+}++function createUsageReporter(options) {+ const dir = options.dataDir || process.env.WBSWITCH_SHARED_DATA_DIR || sharedDataDir();+ const file = path.join(dir, 'usage-state.json');+ const lock = path.join(dir, '.usage-report.lock');+ const now = options.now || Date.now;+ const enabled = options.enabled || telemetryEnabled;+ const getId = options.installationId || persistentInstallationId;+ const send = options.send || sendUsage;+ let pending = null, controller = null;++ async function attempt() {+ if (!enabled()) return;+ const id = getId();+ if (!id) return; // An ephemeral ID would inflate the installation count.+ let locked = false, temp = '';+ try {+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });+ // CN and AI share identity AND quota. A crashed process leaves an empty+ // lock directory; a live request has a five-second total timeout.+ try { fs.mkdirSync(lock, { mode: 0o700 }); locked = true; }+ catch (error) {+ if (error.code !== 'EEXIST' || Date.now() - fs.statSync(lock).mtimeMs < 60000) return;+ fs.rmdirSync(lock);+ fs.mkdirSync(lock, { mode: 0o700 }); locked = true;+ }+ const time = now(), day = usageDay(time);+ let state = { day, attempts: 0, lastAttempt: 0, sent: false };+ try {+ const saved = JSON.parse(fs.readFileSync(file, 'utf8'));+ if (!/^\d{4}-\d{2}-\d{2}$/.test(saved.day) || !Number.isInteger(saved.attempts)+ || saved.attempts < 0 || saved.attempts > 3 || !Number.isFinite(saved.lastAttempt)+ || typeof saved.sent !== 'boolean') return;+ if (saved.day >= day) state = saved;+ } catch (error) { if (error.code !== 'ENOENT') return; }+ if (state.sent || state.attempts >= 3 || (state.attempts && time - state.lastAttempt < RETRY_MS)) return;+ const save = () => {+ temp = `${file}.tmp.${process.pid}`;+ fs.writeFileSync(temp, JSON.stringify(state) + '\n', { mode: 0o600 });+ // No blocking retry loop: telemetry must not delay local app operations.+ fs.renameSync(temp, file);+ temp = '';+ };+ state.attempts++; state.lastAttempt = time;+ save(); // Persist the attempt BEFORE sending, including across restarts.+ if (!enabled()) return;+ controller = new AbortController();+ const result = await send({ installationId: id, profile: options.profile,+ version: options.version, platform: process.platform, arch: process.arch,+ osRelease: os.release().slice(0, 80) }, controller.signal);+ if (result && result.status === 204) { state.sent = true; save(); }+ } catch (_) {+ // Offline, full disk, locked state or exhausted free quota: skip silently.+ } finally {+ controller = null;+ if (temp) try { fs.unlinkSync(temp); } catch (_) {}+ if (locked) try { fs.rmdirSync(lock); } catch (_) {}+ }+ }+ return {+ report() {+ if (!pending) pending = attempt().finally(() => { pending = null; });+ return pending;+ },+ cancel() { if (controller) controller.abort(); },+ };+}++module.exports = { createUsageReporter, usageDay };diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.goindex 5c4a419..12b6596 100644--- a/scripts/windows-native/main.go+++ b/scripts/windows-native/main.go@@ -561,6 +561,20 @@ func inspectExactProcess(pid int, expectedPath string, label string) (bool, int,return false, 0, nil}if errors.Is(err, syscall.ERROR_ACCESS_DENIED) {+ records, snapshotErr := enumerateProcesses()+ if snapshotErr != nil {+ return false, exitFailure, fmt.Errorf("PID %d process snapshot failed: %w", pid, snapshotErr)+ }+ present := false+ for _, record := range records {+ if record.PID == uint32(pid) {+ present = true+ break+ }+ }+ if !present {+ return false, 0, nil+ }return false, exitAccessDenied, fmt.Errorf("PID %d cannot be inspected at standard privilege", pid)}return false, exitFailure, errdiff --git a/test/account-list-stability.test.js b/test/account-list-stability.test.jsindex 86ceae5..52bd656 100644--- a/test/account-list-stability.test.js+++ b/test/account-list-stability.test.js@@ -55,6 +55,35 @@ test('metadata refresh retains cached credits, sorted order and the actual buttoassert.equal(h.cards()[0], before[0]);});+test('first credit batch after renderer reload sorts cards without reopening the panel', async () => {+ const h = harness();+ h.ctx.render({ current: { uid: 'later' }, accounts: [{ uid: 'later' }, { uid: 'soon' }] });+ const before = h.cards();+ h.ctx.fetchCreditsForAccounts(); await tick();+ h.requests[1].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 100 }] }); await tick();+ assert.deepEqual(h.order(), ['later', 'soon'], 'wait for the complete batch before moving rows');+ h.requests[0].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 200 }] }); await tick();+ assert.deepEqual(h.order(), ['soon', 'later']);+ assert.equal(h.cards()[0], before[1], 'move existing cards instead of rebuilding controls');+ assert.equal(h.ctx.state.open, true);+ h.ctx.fetchCreditsForAccounts(); await tick();+ h.requests[2].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 300 }] });+ h.requests[3].resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 50 }] }); await tick();+ assert.deepEqual(h.order(), ['soon', 'later'], 'later background batches preserve the visible order');+});++test('switching the current account reapplies expiry order after its credit batch', async () => {+ const h = harness();+ h.ctx.render({ current: { uid: 'a' }, accounts: [account('a', 100), account('b', 200)] });+ h.ctx.render({ current: { uid: 'b' }, accounts: [account('a', 300), account('b', 200)] });+ assert.deepEqual(h.order(), ['b', 'a']);+ h.ctx.fetchCreditsForAccounts(); await tick();+ h.requests.find(r => JSON.parse(r.options.body).uid === 'a').resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 50 }] });+ h.requests.find(r => JSON.parse(r.options.body).uid === 'b').resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 200 }] }); await tick();+ assert.deepEqual(h.order(), ['a', 'b'], 'current account must not be pinned');+ assert.deepEqual(h.cards().map(c => c.getAttribute('data-uid')), ['a', 'b']);+});+test('credit responses never move a visible account; next opening applies expiry order', async () => {const h = harness();h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });diff --git a/test/account-sort.test.js b/test/account-sort.test.jsindex 2c679c2..c409779 100644--- a/test/account-sort.test.js+++ b/test/account-sort.test.js@@ -21,6 +21,6 @@ test('account list sorts by credit expiry without pinning the current account',const renderStart = inject.indexOf('function render(data)');const renderBody = inject.slice(renderStart, inject.indexOf('state.creditRemaining', renderStart));assert.ok(renderBody.indexOf('leftIsCurrent ? -1 : 1') === -1, 'render must not pin current account');- assert.match(renderBody, /if \(!previous\.length \|\| !state\.open\) sortAccountsByCreditExpiry\(\)/,+ assert.match(renderBody, /if \(!previous\.length \|\| !state\.open \|\| currentChanged\) sortAccountsByCreditExpiry\(\)/,'initial or hidden render sorts by expiry; visible cached rows retain their order');});diff --git a/test/app-icon.test.js b/test/app-icon.test.jsindex 2dbc9c2..d71d25a 100644--- a/test/app-icon.test.js+++ b/test/app-icon.test.js@@ -7,9 +7,10 @@ const repoRoot = path.join(__dirname, '..');const generator = fs.readFileSync(path.join(repoRoot, 'scripts', 'make-icon.py'), 'utf8');const foreground = path.join(repoRoot, 'scripts', 'assets', 'workdaddy-icon-foreground.png');-test('application icon generator shares the requested background across platforms', () => {+test('application icon generator shares the website SVG across platforms', () => {assert.equal(fs.existsSync(foreground), true, 'missing tracked icon foreground');- assert.match(generator, /BACKGROUND = '#e1e1e1'/);+ assert.match(generator, /SOURCE = .*workdaddy-logo\.svg/);+ assert.match(generator, /rsvg-convert/);assert.match(generator, /MAC_OUT = .*WorkDaddy\.icns/);assert.match(generator, /WIN_OUT = .*WorkDaddy\.ico/);});@@ -21,22 +22,70 @@ test('macOS packaging synchronizes the tracked application icon', () => {assert.match(buildSource, /CFBundleIconName/);});-test('Windows application icon applies a rounded alpha mask', () => {- assert.match(generator, /WINDOWS_CORNER_RADIUS_RATIO = 0\.20/);- assert.match(generator, /roundrectangle 0,0 1023,1023/);- assert.match(generator, /'CopyOpacity'/);- assert.match(generator, /render_base\(magick, base, rounded=True\)/);+test('application icons preserve the website rounded alpha mask without an extra background', () => {+ const svg = fs.readFileSync(path.join(repoRoot, 'scripts/assets/workdaddy-logo.svg'), 'utf8');+ assert.match(svg, /clip-path="url\(#app-mask\)"/);+ assert.match(svg, /#34363d/);+ assert.doesNotMatch(generator, /xc:|CopyOpacity/);+ assert.match(generator, /build_windows_icon\(magick, temp_dir, base\)/);});-test('macOS application icon leaves the background to the system mask', () => {+test('macOS application icon uses the same rendered logo as Windows', () => {const macBuilder = generator.slice(generator.indexOf('def build_mac_icon'),generator.indexOf('def build_windows_icon'),);- assert.match(macBuilder, /render_base\(magick, base, rounded=False, with_background=False\)/);+ assert.match(macBuilder, /render_size\(magick, base, size/);+ assert.match(generator, /build_mac_icon\(magick, iconutil, temp_dir, base\)/);});test('iconutil inputs use full RGBA PNGs so macOS keeps every icon size', () => {assert.match(generator, /-type', 'TrueColorAlpha'/);assert.match(generator, /-colorspace', 'sRGB'/);});++// Inspect the shipped raster, including its actual artwork rather than just canvas size.+function readRgbaPng(file) {+ const zlib = require('node:zlib');+ const png = fs.readFileSync(file);+ assert.equal(png.readUInt8(24), 8, 'icon must use 8-bit channels');+ assert.equal(png.readUInt8(25), 6, 'icon must use RGBA');+ const width = png.readUInt32BE(16), height = png.readUInt32BE(20), chunks = [];+ for (let offset = 8; offset < png.length;) {+ const length = png.readUInt32BE(offset);+ if (png.toString('ascii', offset + 4, offset + 8) === 'IDAT') chunks.push(png.subarray(offset + 8, offset + 8 + length));+ offset += length + 12;+ }+ const raw = zlib.inflateSync(Buffer.concat(chunks)), stride = width * 4;+ const pixels = Buffer.alloc(stride * height);+ for (let y = 0; y < height; y++) {+ const row = y * (stride + 1), filter = raw[row];+ assert.ok(filter <= 4, 'unsupported PNG filter');+ for (let x = 0; x < stride; x++) {+ const i = y * stride + x;+ const a = x >= 4 ? pixels[i - 4] : 0, b = y ? pixels[i - stride] : 0;+ const c = y && x >= 4 ? pixels[i - stride - 4] : 0;+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);+ const predictor = filter === 0 ? 0 : filter === 1 ? a : filter === 2 ? b : filter === 3 ? Math.floor((a + b) / 2) : pa <= pb && pa <= pc ? a : pb <= pc ? b : c;+ pixels[i] = (raw[row + 1 + x] + predictor) & 255;+ }+ }+ return { width, height, pixels };+}++test('application artwork fills the tile without clipping the robot or antenna', () => {+ const { width, height, pixels } = readRgbaPng(foreground);+ let left = width, right = 0, top = height, bottom = 0;+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {+ const i = (y * width + x) * 4;+ // The cream robot is distinct from its dark tile and green eyes/shadow.+ if (pixels[i + 3] > 240 && Math.min(pixels[i], pixels[i + 1], pixels[i + 2]) > 135) {+ left = Math.min(left, x); right = Math.max(right, x);+ top = Math.min(top, y); bottom = Math.max(bottom, y);+ }+ }+ assert.ok((right - left + 1) / width >= .85, 'robot has excessive horizontal padding');+ assert.ok((bottom - top + 1) / height >= .85, 'robot has excessive vertical padding');+ assert.ok(left / width >= .025 && (width - 1 - right) / width >= .025, 'robot sides must stay inside the tile');+ assert.ok(top / height >= .025 && (height - 1 - bottom) / height >= .025, 'antenna and robot base must not be clipped');+});diff --git a/test/auth-discovery.test.js b/test/auth-discovery.test.jsindex f915fce..19dbcaa 100644--- a/test/auth-discovery.test.js+++ b/test/auth-discovery.test.js@@ -63,6 +63,25 @@ test('default WorkBuddy profiles scan valid info files regardless of filename',}});+test('account listing marks backups that cannot be used for a dynamic switch', () => {+ const f = fixture();+ try {+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'valid.info'), JSON.stringify(auth('valid', 'https://www.workbuddy.cn/auth/realms/copilot')));+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'invalid.info'), JSON.stringify({+ account: { uid: 'invalid', nickname: 'invalid' },+ auth: { accessToken: 'opaque-token', domain: 'https://untrusted.example' },+ }));+ const accounts = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.listAccounts(process.env.WBSWITCH_DATA_DIR).map(a=>({uid:a.uid,authValid:a.authValid}))))');+ assert.deepEqual(accounts, [+ { uid: 'valid', authValid: true },+ { uid: 'invalid', authValid: false },+ ]);+ } finally {+ fs.rmSync(f.root, { recursive: true, force: true });+ }+});+test('multiple valid files without one lastLogin marker are ambiguous and backup all', () => {const f = fixture();try {diff --git a/test/auto-copy-rules.test.js b/test/auto-copy-rules.test.jsindex ae75c20..a793e7d 100644--- a/test/auto-copy-rules.test.js+++ b/test/auto-copy-rules.test.js@@ -172,6 +172,41 @@ test('delete expansion dedupes repeated members and survives dirty indices', ()assert.equal(members[0].uid, '');});+test('delete expansion follows recorded copies even when member/index records are incomplete', () => {+ const dataDir = tempDataDir();+ const lineageId = ensureAutoCopySession(dataDir, 'source', 'session-a');+ setAutoCopyMapping(dataDir, lineageId, 'target', { targetId: 'copy-a' });+ ensureAutoCopySession(dataDir, 'unrelated', 'same-title-but-unrelated');+ for (const selected of ['session-a', 'copy-a']) {+ assert.deepEqual(collectLineageMembersForDelete(dataDir, [selected]).map(m => m.id).sort(),+ ['copy-a', 'session-a']);+ }+});++test('delete expansion crosses a split lineage connected by an existing copy mapping', () => {+ const dataDir = tempDataDir();+ const original = ensureAutoCopySession(dataDir, 'source', 'session-a');+ setAutoCopyMapping(dataDir, original, 'target', { targetId: 'copy-a' });+ const split = ensureAutoCopySession(dataDir, 'target', 'copy-a');+ addAutoCopySessionMember(dataDir, split, 'third', 'copy-third');+ for (const selected of ['session-a', 'copy-a', 'copy-third']) {+ assert.deepEqual(collectLineageMembersForDelete(dataDir, [selected]).map(m => m.id).sort(),+ ['copy-a', 'copy-third', 'session-a']);+ }+});++test('normalizing duplicate sessions preserves the complete family for deletion', () => {+ const dataDir = tempDataDir();+ const lineageId = ensureAutoCopySession(dataDir, 'source', 'session-a');+ addAutoCopySessionMember(dataDir, lineageId, 'target', 'copy-old');+ addAutoCopySessionMember(dataDir, lineageId, 'target', 'copy-new');+ normalizeAutoCopyLineages(dataDir);+ for (const selected of ['session-a', 'copy-old', 'copy-new']) {+ assert.deepEqual(collectLineageMembersForDelete(dataDir, [selected]).map(m => m.id).sort(),+ ['copy-new', 'copy-old', 'session-a']);+ }+});+test('lineage member lookup is deduplicated and one member can be removed without deleting the lineage', () => {const dataDir = tempDataDir();setAutoCopyRule(dataDir, { uid: 'source', kind: 'session', key: 'source-session', enabled: true });diff --git a/test/automation-calendar.test.js b/test/automation-calendar.test.jsindex 451d626..7c950e9 100644--- a/test/automation-calendar.test.js+++ b/test/automation-calendar.test.js@@ -44,3 +44,32 @@ test('existing builtin IDs are adopted without replacing definitions when markera.writeAutomations(dir,[]);a.installBuiltinTask(dir,file);assert.deepEqual(a.readAutomations(dir),[]);}finally{fs.rmSync(dir,{recursive:true,force:true});}});++test('a revisioned builtin upgrades only an unchanged historical definition',()=>{+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-builtin-upgrade-'));try{+ const oldFile=path.join(dir,'old.json'),newFile=path.join(dir,'new.json');+ const oldTask={schemaVersion:1,id:'builtin',name:'Built in',description:'old',enabled:true,trigger:{type:'pageReady'},schedule:{type:'manual'},variables:{},steps:[{op:'logic.delay',ms:100}],onSuccess:[],onFailure:[]};+ fs.writeFileSync(oldFile,JSON.stringify(oldTask));+ a.installBuiltinTask(dir,oldFile);+ const installed=a.readAutomations(dir);installed[0].enabled=false;installed[0].schedule={type:'daily',time:'09:00'};installed[0].trigger={type:'panelOpened',oncePerNavigation:true};a.writeAutomations(dir,installed);+ const next={...oldTask,revision:2,upgradeFromContentHashes:['6fde9da397c1295d89f44c3f816919fb05e5b5fcb1ce7e140640d54f58119f7f'],description:'new',steps:[{op:'logic.delay',ms:200}]};+ fs.writeFileSync(newFile,JSON.stringify(next));+ const result=a.installBuiltinTask(dir,newFile);+ const upgraded=a.readAutomations(dir)[0];+ assert.equal(result.status,'upgraded');assert.equal(upgraded.revision,2);assert.equal(upgraded.steps[0].ms,200);+ assert.equal(upgraded.enabled,false);assert.deepEqual(upgraded.schedule,{type:'daily',time:'09:00'});assert.equal(upgraded.trigger.type,'panelOpened');+ }finally{fs.rmSync(dir,{recursive:true,force:true});}+});++test('a revisioned builtin never overwrites customized content or an unmarked matching ID',()=>{+ const makeDir=()=>fs.mkdtempSync(path.join(os.tmpdir(),'wd-builtin-custom-'));+ for(const marked of [true,false]){const dir=makeDir();try{+ const oldTask={schemaVersion:1,id:'builtin',name:'Built in',description:'old',enabled:true,trigger:{type:'manual'},schedule:{type:'manual'},variables:{},steps:[{op:'logic.delay',ms:999}],onSuccess:[],onFailure:[]};+ const file=path.join(dir,'new.json');+ a.writeAutomations(dir,[a.validateTask(oldTask)]);+ if(marked)fs.writeFileSync(path.join(dir,'automation-builtins.json'),JSON.stringify({builtin:true}));+ fs.writeFileSync(file,JSON.stringify({...oldTask,revision:2,upgradeFromContentHashes:['6fde9da397c1295d89f44c3f816919fb05e5b5fcb1ce7e140640d54f58119f7f'],steps:[{op:'logic.delay',ms:200}]}));+ const result=a.installBuiltinTask(dir,file);+ assert.equal(result.status,'skipped');assert.equal(a.readAutomations(dir)[0].steps[0].ms,999);+ }finally{fs.rmSync(dir,{recursive:true,force:true});}}+});diff --git a/test/automation-cards-streak.test.js b/test/automation-cards-streak.test.jsindex b7e560c..22cacdc 100644--- a/test/automation-cards-streak.test.js+++ b/test/automation-cards-streak.test.js@@ -58,6 +58,7 @@ test('task cards render triggers separately, show start only for manual tasks, aconst rows=[];const list={innerHTML:'',scrollTop:37,appendChild:r=>rows.push(r.innerHTML)};const ctx={automationState:{tasks:[{id:'manual',name:'Manual',enabled:true,manualRunnable:true,trigger:{type:'manual'}},+ {id:'daily-account-checkin',name:'循环账号静默签到',enabled:true,manualRunnable:false,trigger:{types:['clientLoaded','panelOpened']}},{id:'event',name:'<img onerror=x>',description:'<script>bad</script>',enabled:true,manualRunnable:false,trigger:{types:['clientLoaded','panelOpened']},schedule:{type:'interval',minutes:60}},{id:'active',name:'Active',enabled:true,manualRunnable:false,trigger:{type:'pageReady'}},],runs:[{id:'run-active',taskId:'active',status:'running'}],selected:{},stopping:{}},@@ -67,15 +68,39 @@ test('task cards render triggers separately, show start only for manual tasks, aapplyI18n(){},AUTO_STOPPING_SVG:'',AUTO_STOP_SVG:'',MODEL_ENABLE_SVG:'',AUTO_LOG_SVG:'',MODEL_EDIT_SVG:'',MODEL_COPY_SVG:'',TRASH_SVG:''};ctx.WBS_I18N_EN = {};vm.createContext(ctx);- vm.runInContext(ui.slice(ui.indexOf(' function wbsBuiltinAutomationText('), ui.indexOf(' // ===== 全局错误钩子')), ctx);+ vm.runInContext(ui.slice(ui.indexOf(' function wbsIsBuiltinAutomation('), ui.indexOf(' // ===== 全局错误钩子')), ctx);vm.runInContext(ui.slice(start,end),ctx);ctx.render();assert.match(rows[0],/data-auto-run="manual"/);- assert.doesNotMatch(rows[1],/data-auto-run|data-auto-stop|<img|<script>/);- for(const label of ['客户端加载','打开面板','每 60 分钟','等待触发'])assert.ok(rows[1].includes(label));- assert.match(rows[2],/data-auto-stop="run-active"/);assert.match(rows[2],/执行中/);+ assert.doesNotMatch(rows[0],/wbs-auto-builtin-badge/);+ assert.match(rows[1],/wbs-auto-builtin-badge[^<]*>内置<\/span><div class="wbs-auto-name"/);+ assert.doesNotMatch(rows[2],/data-auto-run|data-auto-stop|<img|<script>|wbs-auto-builtin-badge/);+ for(const label of ['客户端加载','打开面板','每 60 分钟','等待触发'])assert.ok(rows[2].includes(label));+ assert.match(rows[3],/data-auto-stop="run-active"/);assert.match(rows[3],/执行中/);assert.equal(list.scrollTop,37);});+test('only the three bundled automation ids render a built-in badge and omit the editor save action',()=>{+ const helperStart=ui.indexOf(' function wbsIsBuiltinAutomation(');+ const helperEnd=ui.indexOf(' function wbsBuiltinAutomationText(',helperStart);+ assert.ok(helperStart>0&&helperEnd>helperStart);+ const ctx={};vm.createContext(ctx);vm.runInContext(ui.slice(helperStart,helperEnd),ctx);+ for(const id of ['buddy-fuel-station-close-on-account-switch','daily-account-checkin','keep-accounts-active-1-plus-1']){+ assert.equal(ctx.wbsIsBuiltinAutomation({id}),true);+ }+ assert.equal(ctx.wbsIsBuiltinAutomation({id:'user-created'}),false);+ assert.equal(ctx.wbsIsBuiltinAutomation({id:'user-created',name:'循环账号静默签到'}),false);++ const paneStart=ui.indexOf(' function buildAutomationPane()');+ const paneEnd=ui.indexOf(' // ===== 会话 pane',paneStart);+ const pane=ui.slice(paneStart,paneEnd);+ assert.match(pane,/wbs-auto-builtin-badge[^<]*>内置<\/span>/);+ assert.match(pane,/check \+ builtinBadge \+ '<div class="wbs-auto-name"/);+ assert.match(pane,/wbsIsBuiltinAutomation\(task\) \? '' : '<button class="wbs-modal-btn wbs-modal-ok" type="button" id="wbs-auto-save">保存<\/button>'/);+ assert.match(pane,/if \(saveButton\) saveButton\.addEventListener\('click', saveEditor\)/);+ assert.match(ui,/'内置': 'Built-in'/);+ assert.match(ui,/\.wbs-auto-builtin-badge\{[^}]*border-radius:999px[^}]*var\(--wb-/);+});+test('scrollable automation list never shrinks cards and clips their descriptions or footers',()=>{assert.match(ui,/\.wbs-auto-row\{[^}]*flex:0 0 auto/);});diff --git a/test/automation-popup-dismiss.test.js b/test/automation-popup-dismiss.test.jsindex d50e52c..f948e84 100644--- a/test/automation-popup-dismiss.test.js+++ b/test/automation-popup-dismiss.test.js@@ -12,6 +12,11 @@ function runPopupTask(appearAt, failedConfirmations = 0) {const probes = [];const notices = [];const closed = new Map();+ const popupKey = (selector) => {+ if (/home_growth|wb-slot--home-growth/.test(selector)) return 'growth';+ if (/activity-bubble|claw-welcome-activity|pointer-events: auto/.test(selector)) return 'activity';+ return selector;+ };const context = {require: require('node:module').createRequire(path.join(__dirname, '../scripts/automation.js')), module: { exports: {} },setTimeout: (callback, ms) => { now += ms; callback(); },@@ -20,47 +25,65 @@ function runPopupTask(appearAt, failedConfirmations = 0) {const task = JSON.parse(fs.readFileSync(path.join(__dirname, '../scripts/builtin/automations/close-buddy-popups.json'), 'utf8'));const execution = context.module.exports.executeTask(task, {domAction: async (op, locator) => {+ const candidates = Array.isArray(locator) ? locator : [locator];if (op === 'dom.wait') {if (failedConfirmations > 0) { failedConfirmations--; throw new Error('等待页面元素超时'); }- closed.set(locator.value, (closed.get(locator.value) || 0) + 1);+ const key = popupKey(candidates[0].value);+ closed.set(key, (closed.get(key) || 0) + 1);return { visible: false };}assert.equal(op, 'dom.click');- probes.push({ selector: locator.value, at: now });- const appearances = appearAt(locator.value);- const availableAt = (Array.isArray(appearances) ? appearances : [appearances])[closed.get(locator.value) || 0];- if (availableAt == null || now < availableAt) throw new Error('未找到页面元素');- clicks.push({ selector: locator.value, at: now });- // A click alone is not confirmation; dom.wait must confirm disappearance.- return { visible: true };+ for (const candidate of candidates) {+ probes.push({ selector: candidate.value, at: now });+ const appearances = appearAt(candidate.value);+ const availableAt = (Array.isArray(appearances) ? appearances : [appearances])[closed.get(popupKey(candidate.value)) || 0];+ if (availableAt == null || now < availableAt) continue;+ clicks.push({ selector: candidate.value, at: now });+ // A click alone is not confirmation; dom.wait must confirm disappearance.+ return { visible: true };+ }+ throw new Error('未找到页面元素');},notifyToast: (_, message) => notices.push(message),});return execution.then(() => ({ clicks, probes, notices, elapsed: now }));}-test('all three popup buttons are clicked immediately and only once', async () => {+test('all four popup groups are clicked immediately and only once', async () => {const result = await runPopupTask(() => 0);- assert.equal(result.clicks.length, 3);+ assert.equal(result.clicks.length, 4);assert.ok(result.clicks.every(click => click.at === 0));assert.ok(result.clicks.some(click => click.selector.includes('#fuel-compact-close')));assert.ok(result.clicks.some(click => click.selector.includes('wb-related-playbooks__dismiss-today')));+ assert.ok(result.clicks.some(click => click.selector.includes('home_growth_close')));assert.ok(result.clicks.some(click => click.selector.includes('activity-bubble__close')));- assert.equal(result.probes.length, 300);- assert.equal(result.notices.length, 3);+ assert.equal(result.notices.length, 4);assert.equal(result.elapsed, 30000, 'continue observing for re-created popups');});+test('activity fallbacks do not depend on localized text and broad popup selectors are rejected', () => {+ const task = JSON.parse(fs.readFileSync(path.join(__dirname, '../scripts/builtin/automations/close-buddy-popups.json'), 'utf8'));+ const clicks = task.steps[0].steps.filter(step => step.op === 'logic.catch').map(step => step.steps[0]);+ const values = clicks.flatMap(step => (step.locators || [step.locator]).map(locator => locator.value));+ assert.ok(values.includes('button[data-track-id="home_growth_close"]'));+ assert.ok(values.includes('.wb-slot--home-growth button.wb-slot--closable-close'));+ assert.ok(values.includes('button.claw-welcome-activity-card__close'));+ assert.ok(values.some(value => value.includes('pointer-events: auto') && value.includes('width: 213px')));+ assert.ok(values.every(value => !/关闭活动通知|activity notification/i.test(value)));+ assert.ok(values.every(value => value !== '.wb-slot--closable-close'));+ assert.ok(values.every(value => !value.startsWith('//*[')));+});+test('absent fuel popup does not delay other popups, including one rendered later', async () => {- const result = await runPopupTask(selector => selector.includes('fuel-compact') ? null : selector.includes('activity-bubble') ? 1100 : 0);- assert.deepEqual(result.clicks.map(click => click.at), [0, 1200]);- assert.equal(result.notices.length, 2);+ const result = await runPopupTask(selector => selector.includes('fuel-compact') ? null : /activity-bubble|claw-welcome-activity|pointer-events: auto/.test(selector) ? 1100 : 0);+ assert.deepEqual(result.clicks.map(click => click.at), [0, 0, 1200]);+ assert.equal(result.notices.length, 3);assert.equal(result.elapsed, 30000);});test('missing popup buttons finish quietly after the bounded detection window', async () => {const result = await runPopupTask(() => null);- assert.equal(result.probes.length, 300);+ assert.ok(result.probes.length >= 400);assert.equal(result.elapsed, 30000);assert.equal(result.clicks.length, 0);assert.equal(result.notices.length, 0);@@ -68,10 +91,10 @@ test('missing popup buttons finish quietly after the bounded detection window',test('an ineffective click is retried and only confirmed closes are announced', async () => {const result = await runPopupTask(() => 0, 1);- assert.equal(result.clicks.length, 4);+ assert.equal(result.clicks.length, 5);assert.equal(result.clicks.at(-1).at, 300);assert.equal(result.clicks.at(-1).selector, '#fuel-compact-close');- assert.equal(result.notices.length, 3);+ assert.equal(result.notices.length, 4);});test('a popup recreated after a successful close is detected and closed again', async () => {@@ -91,7 +114,7 @@ test('a newer navigation supersedes a running opt-in task instead of dropping itconst running = { taskId: 'popup', status: 'running', navigationSerial: 1 };const context = {taskMatchesEvent: require('../scripts/automation').taskMatchesEvent,- automationEventKeys: new Set(), mainFrameNavigationSerial: 2,+ automationEventKeys: new Set(), mainFrameNavigationSerial: 2, cdpPageSessionId: 'renderer-a',automationRuns: new Map([['run', running]]), DATA_DIR: '/test',readAutomations: () => [{ id: 'popup', enabled: true, trigger: { type: 'pageReady', restartOnNavigation: true } }],currentAccount: () => null, log() {},@@ -104,22 +127,43 @@ test('a newer navigation supersedes a running opt-in task instead of dropping itassert.equal(running.pendingEvent.navigationSerial, 3, 'retain only the latest navigation');});+test('pageReady is deduplicated per renderer page rather than per CDP connection', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+ const start = source.indexOf('function dispatchAutomationEvent(');+ const end = source.indexOf('\nfunction onCdpEvent(', start);+ const launched = [];+ const context = {+ taskMatchesEvent: () => true,+ automationEventKeys: new Set(), mainFrameNavigationSerial: 7, cdpPageSessionId: 'renderer-a',+ automationRuns: new Map(), DATA_DIR: '/test',+ readAutomations: () => [{ id: 'popup', enabled: true, trigger: { type: 'pageReady' } }],+ currentAccount: () => null, log() {}, startAutomationRun: (_, event) => launched.push(event),+ };+ vm.runInNewContext(source.slice(start, end), context);+ context.dispatchAutomationEvent('pageReady', { navigationSerial: 7, source: 'connect' });+ context.dispatchAutomationEvent('pageReady', { navigationSerial: 7, source: 'connect' });+ assert.equal(launched.length, 1, 'a transient reconnect to the same renderer stays deduplicated');+ context.cdpPageSessionId = 'renderer-b';+ context.dispatchAutomationEvent('pageReady', { navigationSerial: 7, source: 'connect' });+ assert.equal(launched.length, 2, 'a restarted renderer gets its own pageReady event');+});+test('queued detection resumes only for the latest page and an enabled task', () => {const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const start = source.indexOf('function resumeAutomationAfterNavigation(');const end = source.indexOf('\nfunction todayStr(', start);const launched = [];const task = { id: 'popup', enabled: true, trigger: { restartOnNavigation: true } };- const context = { mainFrameNavigationSerial: 3, DATA_DIR: '/test', readAutomations: () => [task], startAutomationRun: (...args) => launched.push(args) };+ const context = { mainFrameNavigationSerial: 3, cdpPageSessionId: 'renderer-a', DATA_DIR: '/test', readAutomations: () => [task], startAutomationRun: (...args) => launched.push(args) };vm.runInNewContext(source.slice(start, end), context);- context.resumeAutomationAfterNavigation({ taskId: 'popup', pendingEvent: { navigationSerial: 2 } });+ context.resumeAutomationAfterNavigation({ taskId: 'popup', pendingEvent: { navigationSerial: 2, pageSessionId: 'renderer-a' } });assert.equal(launched.length, 0);- const run = { taskId: 'popup', pendingEvent: { navigationSerial: 3 } };+ const run = { taskId: 'popup', pendingEvent: { navigationSerial: 3, pageSessionId: 'renderer-a' } };context.resumeAutomationAfterNavigation(run);assert.equal(launched.length, 1);assert.equal(run.pendingEvent, null);task.enabled = false;- context.resumeAutomationAfterNavigation({ taskId: 'popup', pendingEvent: { navigationSerial: 3 } });+ context.resumeAutomationAfterNavigation({ taskId: 'popup', pendingEvent: { navigationSerial: 3, pageSessionId: 'renderer-a' } });assert.equal(launched.length, 1);});@@ -136,7 +180,7 @@ test('a running cleanup stops before the next navigation begins its own cleanup'acquireAutomationInput: require('../scripts/automation-runtime').createRendererGate(),acquireAutomationRenderer: require('../scripts/automation-runtime').createRendererGate(), primaryAccountStore:{get:()=>null},crypto: require('node:crypto'), automationRuns: new Map(), automationEventKeys: new Set(),- mainFrameNavigationSerial: 1, DATA_DIR: '/test', cdp: {}, log: noop,+ mainFrameNavigationSerial: 1, cdpPageSessionId: 'renderer-a', DATA_DIR: '/test', cdp: {}, log: noop,readAutomations: () => [task], readAutomationState: () => ({}), writeAutomationState: noop,automationPanelIsOpen: async () => false, automationPanelSetOpen: open => restored.push(open),listAccounts: () => [], currentAccount: () => null, automationSwitchAccount: noop,@@ -195,11 +239,13 @@ test('automation DOM click dispatches the located button without undefined requeassert.equal(clicks.length, 1);assert.deepEqual(clicks[0].slice(0, 3), ['dom.click:button.activity-bubble__close', 20, 35]);assert.equal(clicks[0][4].skipMove, true);+ await context.automationDomAction('dom.click', [{ kind: 'css', value: '.old-close', visible: true }, { kind: 'css', value: '.new-close', visible: true }], {});+ assert.equal(clicks[1][4].skipMove, true, 'candidate popup locators keep the no-hover click path');found.blocked = true;await assert.rejects(context.automationDomAction('dom.click', { kind: 'css', value: '.close', visible: true }, {}), /遮挡/);- assert.equal(clicks.length, 1, 'do not click whatever is covering the close button');+ assert.equal(clicks.length, 2, 'do not click whatever is covering the close button');await assert.rejects(context.automationDomAction('dom.click', { kind: 'css', value: '.close' }, { isCancelled: () => true }), /已停止/);- assert.equal(clicks.length, 1);+ assert.equal(clicks.length, 2);});test('popup clicks bypass mouse-move acknowledgement while normal clicks retain hover', async () => {diff --git a/test/credit-history-sync.test.js b/test/credit-history-sync.test.jsnew file mode 100644index 0000000..78df8c5--- /dev/null+++ b/test/credit-history-sync.test.js@@ -0,0 +1,134 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const { createCreditHistorySync, historyRange } = require('../scripts/credit-history-sync.js');+const { fetchUsageSinceAnchor } = require('../scripts/credit-request-usage.js');+const now = new Date(2026, 8, 12, 12);+const settle = async (sync) => { while (sync.status().running) await new Promise(resolve => setImmediate(resolve)); return sync.status(); };++test('historical sync fetches all pages without today cache or anchor, limits to 90 days, reports progress and deduplicates active jobs', async () => {+ const requests = [], progress = [];+ let release;+ const gate = new Promise(resolve => { release = resolve; });+ const sync = createCreditHistorySync({ now: () => now, getAccessToken: async () => 'test',+ fetchUsage: options => fetchUsageSinceAnchor({ ...options, apiHost: 'https://usage.test', pageSize: 1,+ fetchImpl: async (_url, init) => {+ const body = JSON.parse(init.body); requests.push(body); if (requests.length === 1) await gate;+ return {ok:true, text:async () => JSON.stringify({code:0,data:{total:2,data:[{requestId:'r'+body.pageNum,requestTime: body.pageNum === 1 ? '2026-09-12 10:00:00' : '2026-07-01 10:00:00',credit:1}]}})};+ }, onProgress: value => { options.onProgress(value); progress.push(sync.status()); } })+ });+ const job = sync.start({accounts:[{uid:'one',nickname:'A'}],days:900});+ assert.equal(job.running, true);+ assert.equal(sync.start({accounts:[{uid:'one',nickname:'A'}],days:900}).id, job.id);+ assert.throws(() => sync.start({accounts:[{uid:'two'}],days:7}), /正在进行/);+ release();+ const end = await settle(sync);+ assert.equal(requests.length, 2);+ assert.deepEqual(requests.map(r => r.pageNum), [1,2]);+ assert.equal(requests[0].startTime, '2026-06-15 00:00:00');+ assert.equal(end.daily.reduce((n,d)=>n+d.count,0), 2);+ assert.equal(end.from, '2026-06-15');+ assert.equal(progress[0].page, 1); assert.equal(progress[0].pages, 2);+ assert.equal(end.completed, 1); assert.equal(end.synced, 1); assert.equal(end.percent, 100);+});++test('failed account does not block other accounts and raw server errors stay private', async () => {+ const sync=createCreditHistorySync({now:()=>now,getAccessToken:async uid=>uid,fetchUsage:async o=>{if(o.accessToken==='bad') throw Error('Bearer private-secret');return {records:[]}}});+ sync.start({days:7,accounts:[{uid:'bad'},{uid:'good'}]});+ const state=await settle(sync);+ assert.equal(state.completed,2);assert.equal(state.synced,1);assert.equal(state.failures.length,1);assert.ok(state.daily.every(d=>d.uid==='good'));+ assert.doesNotMatch(JSON.stringify(state),/private-secret/);+});++test('history date bounds reject invalid ranges and use local calendar days',()=>{+ for(const days of ['oops',0,-1,1.5,Infinity]) assert.throws(()=>historyRange(days,now));+ assert.equal(historyRange(7,now).from,'2026-09-06');+});++test('manual history route uses a background history job, separate from the today cache', () => {+ const fs=require('node:fs');+ const source=fs.readFileSync(require('node:path').join(__dirname,'../scripts/daemon.js'),'utf8');+ const route=source.slice(source.indexOf("if (req.method === 'POST' && p === '/api/credit-stats')"),source.indexOf('// Read-only per-account continuous activity'));+ assert.match(route,/creditHistorySync\.start/);+ assert.match(route,/json\(res, 202/);+ assert.doesNotMatch(route,/syncCurrentCreditUsage/);+ assert.match(route,/accounts\.filter/);+});++test('repeated credit queries reuse complete daily API results', async () => {+ let calls = 0;+ const sync = createCreditHistorySync({ now: () => now, getAccessToken: async () => 'test',+ fetchUsage: async () => { calls++; return { records: [{ usageDate: '2026-09-12', credit: calls, requestId: 'same' }] }; }+ });+ sync.start({ accounts: [{ uid: 'one' }] });+ const first = await settle(sync);+ assert.equal(first.source, 'server');+ assert.equal(first.from, '2026-09-06');+ assert.equal(first.daily.length, 7);+ assert.equal(first.daily.find(d => d.date === '2026-09-12').used, 1);+ assert.equal(first.daily.find(d => d.date === '2026-09-06').used, 0);+ sync.start({ accounts: [{ uid: 'one' }] });+ const second = await settle(sync);+ assert.equal(calls, 1);+ assert.equal(second.cacheHit, true);+ assert.equal(second.daily.find(d => d.date === '2026-09-12').used, 1);+});++test('failed account contributes no cached values or false zero records', async () => {+ const sync = createCreditHistorySync({ now: () => now, getAccessToken: async uid => uid,+ fetchUsage: async o => { if (o.accessToken === 'bad') throw Error('timeout'); return { records: [] }; }+ });+ sync.start({ accounts: [{ uid: 'bad' }, { uid: 'good' }], days: 7 });+ const result = await settle(sync);+ assert.equal(result.daily.length, 7);+ assert.ok(result.daily.every(d => d.uid === 'good' && d.complete && d.used === 0));+});++test('both credit statistics entry points are remote queries, not local database reads', () => {+ const fs=require('node:fs');+ const source=fs.readFileSync(require('node:path').join(__dirname,'../scripts/daemon.js'),'utf8');+ const routes=source.slice(source.indexOf("if (req.method === 'GET' && p === '/api/credit-stats')"),source.indexOf('// Read-only per-account continuous activity'));+ assert.doesNotMatch(routes,/CREDIT_USAGE_STORE|listDailyUsageRange/);+ assert.match(routes,/creditHistorySync\.wait/);+});++test('durable daily cache fills only gaps, including zero-use days, and survives restart', async t => {+ const fs=require('node:fs'),os=require('node:os'),path=require('node:path');+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wbs-credit-cache-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));+ const requests=[];+ const options={cacheFile:path.join(dir,'cache.json'),now:()=>now,getAccessToken:async uid=>uid,fetchUsage:async o=>{requests.push({uid:o.accessToken,from:o.startTime,to:o.endTime});return {records:[]};}};+ let sync=createCreditHistorySync(options);+ sync.start({accounts:[{uid:'a'},{uid:'b'}],days:7});await settle(sync);assert.equal(requests.length,2);+ sync=createCreditHistorySync(options);+ const cached=sync.start({accounts:[{uid:'a'}],days:7});+ assert.equal(cached.running,false);assert.equal(cached.cacheHit,true);assert.equal(cached.daily.length,7);assert.equal(requests.length,2);+ sync.start({accounts:[{uid:'a'}],days:30});await settle(sync);+ assert.equal(requests.length,3);assert.equal(requests[2].from.getTime(),new Date(2026,7,14).getTime());assert.equal(requests[2].to.getTime(),new Date(2026,8,6).getTime()-1000);+ assert.equal(sync.start({accounts:[{uid:'a'}],days:7}).cacheHit,true);assert.equal(requests.length,3);+});++test('expired today refreshes silently while historical days stay cached', async () => {+ let current=now;const requests=[];+ const sync=createCreditHistorySync({now:()=>current,todayTtlMs:60000,getAccessToken:async()=> 'a',fetchUsage:async o=>{requests.push(o);return {records:[]};}});+ sync.start({accounts:[{uid:'a'}],days:7});await settle(sync);+ current=new Date(now.getTime()+61000);+ const job=sync.start({accounts:[{uid:'a'}],days:7});assert.equal(job.hasCachedData,true);await settle(sync);+ assert.equal(requests.length,2);assert.equal(requests[1].startTime.getTime(),new Date(2026,8,12).getTime());+});++test('after midnight only yesterday snapshot and new day are fetched, not settled history', async () => {+ let current=now;const requests=[];+ const sync=createCreditHistorySync({now:()=>current,getAccessToken:async()=> 'a',fetchUsage:async o=>{requests.push(o);return {records:[]};}});+ sync.start({accounts:[{uid:'a'}],days:7});await settle(sync);+ current=new Date(2026,8,13,10);+ sync.start({accounts:[{uid:'a'}],days:7});await settle(sync);+ assert.equal(requests.length,2);assert.equal(requests[1].startTime.getTime(),new Date(2026,8,12).getTime());+});++test('failed gap remains missing and retry does not fetch successful accounts again', async () => {+ let failing=true;const calls=[];+ const sync=createCreditHistorySync({now:()=>now,getAccessToken:async uid=>uid,fetchUsage:async o=>{calls.push(o.accessToken);if(failing&&o.accessToken==='b')throw Error('timeout');return {records:[]};}});+ sync.start({accounts:[{uid:'a'},{uid:'b'}],days:7});await settle(sync);failing=false;+ sync.start({accounts:[{uid:'a'},{uid:'b'}],days:7});await settle(sync);+ assert.deepEqual(calls,['a','b','b']);+});diff --git a/test/credit-rotation.test.js b/test/credit-rotation.test.jsnew file mode 100644index 0000000..fb85aeb--- /dev/null+++ b/test/credit-rotation.test.js@@ -0,0 +1,62 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const path = require('path');+const {+ nearestExpiringSegment,+ wasNearestSegmentConsumed,+ selectRotationCandidate,+} = require('../scripts/credit-rotation.js');++const now = Date.parse('2026-09-11T10:00:00Z');++test('nearest expiring segment ignores exhausted and expired segments', () => {+ const segment = nearestExpiringSegment([+ { remaining: 0, expiresAt: now + 60_000 },+ { remaining: 20, expiresAt: now - 60_000 },+ { remaining: 80, expiresAt: now + 3_600_000 },+ { remaining: 100, expiresAt: null },+ ], now);+ assert.equal(segment.remaining, 80);+ assert.equal(segment.expiresAt, now + 3_600_000);+});++test('detects when the previously nearest segment disappears after a refresh', () => {+ const before = [{ remaining: 10, expiresAt: now + 3_600_000, packageCode: 'soon' }, { remaining: 500, expiresAt: null }];+ const after = [{ remaining: 500, expiresAt: null }];+ assert.equal(wasNearestSegmentConsumed(before, after, now), true);+ assert.equal(wasNearestSegmentConsumed(before, [{ remaining: 3, expiresAt: now + 3_600_000, packageCode: 'soon' }], now), false);+});++test('selects the non-current account with the earliest usable expiry', () => {+ const candidate = selectRotationCandidate([+ { uid: 'current', creditSegments: [{ remaining: 1, expiresAt: now + 10_000 }] },+ { uid: 'later', creditSegments: [{ remaining: 300, expiresAt: now + 86_400_000 }] },+ { uid: 'soon', creditSegments: [{ remaining: 80, expiresAt: now + 3_600_000 }] },+ ], 'current', now);+ assert.equal(candidate.account.uid, 'soon');+ assert.equal(candidate.segment.remaining, 80);+});++test('rotation completion request uses real segment detection and keeps the verified prompt behavior', () => {+ const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ assert.doesNotMatch(daemon, /forceSuggest|testMode/);+ assert.doesNotMatch(daemon, /wasNearestSegmentConsumed\(previousSegments/);+ assert.match(daemon, /const candidate = selectRotationCandidate\(cachedCreditRotationAccounts\(\), uid, Date\.now\(\)\)/);+ assert.match(daemon, /const candidate = selectRotationCandidate\(cachedCreditRotationAccounts\(\), uid, Date\.now\(\)\)/);+ assert.match(inject, /previousSegments: current\.creditSegments \}\)/);+ assert.doesNotMatch(inject, /previousSegments: current\.creditSegments, force: true/);+ const updateBaseline = inject.indexOf('current.creditSegments = Array.isArray(result && result.current && result.current.segments)');+ const suggestionGuard = inject.indexOf('if (!result || !result.shouldSuggest || !result.candidate) return;', updateBaseline);+ assert.ok(updateBaseline >= 0 && suggestionGuard > updateBaseline, 'current credit baseline must update even when no prompt is shown');+ assert.match(inject, /要切换账号吗?/);+ assert.match(inject, /关闭(10)/);+ assert.match(inject, /var remaining = 10/);+ assert.match(inject, /检测到积分到期时间最临近的账号/);+ assert.doesNotMatch(inject, /action === 'remove'[\s\S]{0,500}checkCreditRotationAfterSession/);+ assert.match(inject, /Account rotation must wait for an actual reply/);+ assert.match(inject, /Use the untransformed fixed position/);+});diff --git a/test/credit-usage-store.test.js b/test/credit-usage-store.test.jsindex 0067450..3235278 100644--- a/test/credit-usage-store.test.js+++ b/test/credit-usage-store.test.js@@ -107,3 +107,17 @@ test('persists verified daily check-in marks by profile, uid and date', async (t});assert.equal(await tmp.store.getDailyCheckin('u1', '2026-08-27'), null);});++test('history backfill preserves the today anchor, deduplicates, and distinguishes verified zero from missing days', async t => {+ const tmp=tempStore();t.after(()=>fs.rmSync(tmp.dir,{recursive:true,force:true}));+ await tmp.store.saveSuccessfulSync({uid:'u1',records:[],anchorRequestId:'today',syncedAt:9000});+ const input={uid:'u1',from:'2026-08-27',to:'2026-08-28',syncedAt:10000,records:[record('r1','2026-08-28',2.5,1000)]};+ await tmp.store.saveHistoryUsage(input);await tmp.store.saveHistoryUsage(input);+ assert.deepEqual(await tmp.store.getSyncState('u1'),{anchorRequestId:'today',lastSuccessAt:9000});+ const rows=await tmp.store.listDailyUsageRange(['u1','missing'],'2026-08-26','2026-08-28');+ assert.equal(rows.length,2);+ assert.equal(rows.find(r=>r.date==='2026-08-27').used,0);+ assert.equal(rows.find(r=>r.date==='2026-08-27').complete,true);+ assert.equal(rows.find(r=>r.date==='2026-08-28').used,2.5);+ assert.equal(rows.find(r=>r.date==='2026-08-28').count,1);+});diff --git a/test/macos-dock-identity.test.js b/test/macos-dock-identity.test.jsnew file mode 100644index 0000000..af27dbe--- /dev/null+++ b/test/macos-dock-identity.test.js@@ -0,0 +1,22 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { execFileSync } = require('node:child_process');+test('packaged macOS launcher starts the app through LaunchServices, not its Electron child', () => {+ const root = path.join(__dirname, '..');+ const build = fs.readFileSync(path.join(root, 'scripts/build-mac-dmg.sh'), 'utf8');+ const blocks = [...build.matchAll(/python3 - "\$PACKAGE_APP\/Contents\/MacOS\/launcher" <<'PY'\n([\s\S]*?)\nPY/g)];+ const os = require('node:os');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-dock-'));+ try {+ const launcher = path.join(dir, 'launcher');+ fs.copyFileSync(path.join(root, 'WorkDaddy.app/Contents/MacOS/launcher'), launcher);+ for (const block of blocks) execFileSync('python3', ['-', launcher], { input: block[1] });+ const source = fs.readFileSync(launcher, 'utf8');+ assert.doesNotMatch(source, /nohup "\$APP_BIN"/);+ assert.match(source, /\/usr\/bin\/open -a "\$TARGET_APP_BUNDLE" --args "--remote-debugging-port=\$PORT"/);+ execFileSync('bash', ['-n', launcher]);+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }+});diff --git a/test/macos-launch-services.test.js b/test/macos-launch-services.test.jsnew file mode 100644index 0000000..136769c--- /dev/null+++ b/test/macos-launch-services.test.js@@ -0,0 +1,52 @@+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++const repoRoot = path.join(__dirname, '..');+const read = (name) => fs.readFileSync(path.join(repoRoot, 'scripts', name), 'utf8');++const LSREGISTER_PATH =+ '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister';++test('macOS DMG declares an arm64 LaunchServices architecture priority', () => {+ const build = read('build-mac-dmg.sh');+ assert.match(build, /LS_ARCH_PRIORITY="arm64"/);+ assert.match(build, /Add :LSArchitecturePriority array/);+ assert.match(build, /Add :LSArchitecturePriority:0 string \$\{LS_ARCH_PRIORITY\}/);+ // 声明必须落在打包产物上,而不是只在仓库里的壳上。+ assert.match(build, /Print :LSArchitecturePriority:0' "\$PACKAGE_APP\/Contents\/Info\.plist"/);+});++test('macOS DMG build fails loudly when the arch priority is not written', () => {+ const build = read('build-mac-dmg.sh');+ const verify = build.indexOf('BUILT_ARCH_PRIORITY=');+ assert.notEqual(verify, -1);+ const guard = build.slice(verify, build.indexOf('echo "==> 架构优先级已声明'));+ assert.match(guard, /if \[ "\$BUILT_ARCH_PRIORITY" != "\$LS_ARCH_PRIORITY" \]; then/);+ assert.match(guard, /exit 3/);+});++test('macOS updater refreshes the LaunchServices registration before relaunching', () => {+ const script = read('apply-update.sh');+ assert.match(script, new RegExp(LSREGISTER_PATH.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));+ assert.match(script, /"\$LSREGISTER" -u "\$APP_PATH"/);+ assert.match(script, /"\$LSREGISTER" -f "\$APP_PATH"/);+ assert.match(script, /\/Volumes\/\*\/WorkDaddy\*\.app/);++ const xattr = script.indexOf('xattr -cr "$APP_PATH"');+ const refresh = script.indexOf('"$LSREGISTER" -u "$APP_PATH"');+ const relaunch = script.indexOf('open -n "$APP_PATH" || rollback 27');+ assert.notEqual(xattr, -1);+ assert.notEqual(refresh, -1);+ assert.notEqual(relaunch, -1);+ assert.ok(xattr < refresh, 'registration refresh must follow the bundle replacement');+ assert.ok(refresh < relaunch, 'registration refresh must happen before the relaunch');+});++test('macOS updater never fails the update because of registration cleanup', () => {+ const script = read('apply-update.sh');+ assert.match(script, /"\$LSREGISTER" -u "\$APP_PATH" >\/dev\/null 2>&1 \|\| log /);+ assert.match(script, /"\$LSREGISTER" -f "\$APP_PATH" >\/dev\/null 2>&1 \|\| log /);+ assert.match(script, /未找到 lsregister,跳过注册刷新/);+});diff --git a/test/macos-runtime-dependencies.test.js b/test/macos-runtime-dependencies.test.jsnew file mode 100644index 0000000..878a0b0--- /dev/null+++ b/test/macos-runtime-dependencies.test.js@@ -0,0 +1,15 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+test('macOS staging copies every top-level daemon module dependency', () => {+ const root = path.join(__dirname, '..', 'scripts');+ const daemon = fs.readFileSync(path.join(root, 'daemon.js'), 'utf8');+ const build = fs.readFileSync(path.join(root, 'build-mac-dmg.sh'), 'utf8');+ const list = build.match(/for f in ([^\n]+); do/)[1].split(/\s+/);+ for (const match of daemon.matchAll(/^.*require\(['"]\.\/([^'"]+\.js)['"]\).*$/gm)) {+ if (/^\s/.test(match[0])) continue; // Nested optional/platform-specific imports.+ assert.ok(list.includes(match[1]), `macOS staging missing ${match[1]}`);+ }+});diff --git a/test/message-navigation.test.js b/test/message-navigation.test.jsindex 86dcb8c..3aede57 100644--- a/test/message-navigation.test.js+++ b/test/message-navigation.test.js@@ -4,9 +4,37 @@ const assert = require('node:assert/strict');const fs = require('node:fs');const path = require('node:path');const test = require('node:test');+const vm = require('node:vm');const compat = require('../scripts/workbuddy-compat.js');+test('scroll events keep the last node selected when the last turn cannot align with the viewport top', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const frames = [{ index: 1, top: 28, bottom: 350 }, { index: 2, top: 350, bottom: 410 }, { index: 3, top: 410, bottom: 600 }];+ const scroll = { scrollTop: 1200, scrollHeight: 1800, clientHeight: 600 };+ let selected;+ const context = {+ turns: [{ id: 'first', messageIndex: 0 }, { id: 'last', messageIndex: 2 }],+ surface: { scrollElement: scroll, viewportElement: { getBoundingClientRect: () => ({ top: 0, bottom: 600 }) },+ conversationElement: { querySelectorAll: () => frames.map(f => ({ getBoundingClientRect: () => f, getAttribute: () => String(f.index) })) } },+ setActive: id => { selected = id; },+ };+ const start = source.indexOf(' function updateActive()');+ vm.runInNewContext(source.slice(start, source.indexOf('\n function scheduleActive()', start)), context);+ selected = 'last'; // navigateToTurn sets this before the official scroll event arrives.+ context.updateActive();+ assert.equal(selected, 'last');+ scroll.scrollTop = 1199.5;+ context.updateActive();+ assert.equal(selected, 'last', 'fractional scroll coordinates still count as the bottom');+ scroll.scrollTop = 900;+ context.updateActive();+ assert.equal(selected, 'first', 'scrolling up must release the last-node highlight');+ scroll.scrollTop = 0; scroll.scrollHeight = scroll.clientHeight;+ context.updateActive();+ assert.equal(selected, 'first', 'a non-scrollable conversation does not force the last node');+});+test('message navigation uses cr-message-list as the single stable surface seam', () => {const viewport = { name: 'viewport' };const messageList = { name: 'message-list', parentElement: viewport };@@ -150,9 +178,13 @@ test('injected navigation rail is theme-aware, glassy, accessible, and profile aassert.match(inject, /悬停预览,点击或拖动快速定位消息。/);});-test('robot pupils use the antenna glass treatment instead of opaque black', () => {+test('floating robot keeps the website shell and upright eyes', () => {const root = path.join(__dirname, '..');const inject = fs.readFileSync(path.join(root, 'scripts', 'inject.js'), 'utf8');- assert.match(inject, /\.wbs-fab \.eye:before\{[^\n]*background:rgba\(20,20,22,\.55\)[^\n]*backdrop-filter:blur\(14px\) saturate\(1\.3\)/);- assert.doesNotMatch(inject, /\.wbs-fab \.eye:before\{[^\n]*background:rgba\(20,20,22,\.92\)/);+ assert.match(inject, /--wbs-robot-shell:#fff;--wbs-robot-eye:#111/);+ assert.match(inject, /\.wbs-fab \.eye\{[^\n]*width:12px;height:18px[^\n]*background:var\(--wbs-robot-eye\)/);+ assert.match(inject, /\.wbs-fab:hover \.eye\{scale:1\.18\}/);+ assert.match(inject, /wbs-robot-blink 7s/);+ assert.match(inject, /\.wbs-fab \.button\{[^\n]*width:82px;height:64px/);+ assert.doesNotMatch(inject, /\.wbs-fab \.eye:before/);});diff --git a/test/no-disturb-match.test.js b/test/no-disturb-match.test.jsindex 7ab6131..5a5efb4 100644--- a/test/no-disturb-match.test.js+++ b/test/no-disturb-match.test.js@@ -1,7 +1,8 @@/**- * 免打扰「弹窗自动点允许」匹配逻辑回归测试(1.0.16)。- * 覆盖 WorkBuddy AI 拦截卡(选项按钮带序号前缀)+ 防御性校验(积分弹窗不误点、- * 中性按钮不误点、禁用按钮跳过、once 禁用时回退 always)。+ * 免打扰「弹窗自动点允许」匹配逻辑回归测试(1.0.16 + WorkBuddy 5.5.4)。+ * 覆盖 WorkBuddy AI 拦截卡(选项按钮带序号前缀)+ 敏感凭证保护卡(allow 文案为+ * 「允许访问」/「允许加密访问(推荐)」)+ 防御性校验(积分弹窗、凭证外发、批量删除放行、+ * 完全访问提权确认不误点、禁用按钮跳过、once 禁用时回退 always)。* 实现方式:从 scripts/inject.js 原样抽取扫描函数,用极简 DOM 桩驱动,* 保证测试对象与交付物完全同源(inject.js 是浏览器脚本,无 require/export)。* 运行:node test/no-disturb-match.test.js@@ -12,10 +13,15 @@ const fs = require('fs');const path = require('path');const injectSrc = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+// 文案表(ND_ALLOW_ONCE_LABELS 等)位于扫描代码段之外,属于同一份事实来源,需一并注入桩环境。+const constStart = injectSrc.indexOf('var ND_ALLOW_ONCE_LABELS');+const constEnd = injectSrc.indexOf('function classifyNoDisturbApprovalCandidate');+assert.ok(constStart > 0 && constEnd > constStart, 'inject.js 未找到免打扰文案表常量');+const labelConsts = injectSrc.slice(constStart, constEnd);const startM = injectSrc.indexOf('function ndVisible(el)');const endM = injectSrc.indexOf('function toNdAudit');assert.ok(startM > 0 && endM > startM, 'inject.js 未找到免打扰扫描代码段');-const scanCode = injectSrc+const scanCode = labelConsts + injectSrc.slice(startM, endM).replace('var doc = (window && window.document) || document;', 'var doc = __ND_DOC__;');@@ -145,4 +151,64 @@ function runCase(desc, labels, opts) {console.log('✓ once 禁用:回退自动点「2本次会话内始终允许」');}+// 8) WorkBuddy 5.5.4「敏感凭证保护」卡:ingress 的允许选项是「允许访问」(不是「允许」)+{+ const r = runCase('是否允许模型访问敏感凭证?', ['允许访问', '允许加密访问(推荐)', '禁止访问']);+ assert.strictEqual(r.acted, '1允许访问', '敏感凭证卡的「允许访问」应被识别为 once 允许');+ assert.strictEqual(r.clicked, true);+ console.log('✓ 敏感凭证卡-ingress:自动点「1允许访问」');+}+// 9) ingress-protect-only:没有「允许访问」,只有加密访问——过去完全点不到,任务会卡死+{+ const r = runCase('是否允许模型访问敏感凭证?', ['允许加密访问(推荐)', '禁止访问']);+ assert.strictEqual(r.acted, '1允许加密访问(推荐)');+ assert.strictEqual(r.clicked, true);+ console.log('✓ 敏感凭证卡-protect-only:自动点「1允许加密访问(推荐)」');+}+// 10) 凭证外发(egress):绝不自动点,必须人工判断目标是否可信+{+ const r = runCase('是否允许将敏感凭证发送到外部?', ['允许发送', '禁止发送']);+ assert.strictEqual(r.acted, null, '凭证外发弹窗不得自动放行');+ assert.deepStrictEqual(r.audit, []);+ console.log('✓ 敏感凭证卡-egress:不自动点(防凭证外泄)');+}+// 11) 批量删除放行:交给「大批量删除免确认」开关,不由本开关代劳+{+ const r = runCase('检测到批量删除操作,删除数量达到阈值', ['允许本次删除', '取消删除']);+ assert.strictEqual(r.acted, null);+ console.log('✓ 批量删除放行:不自动点(由专用开关控制)');+}+// 12) 开启「允许完全访问」的授权确认:属提权,必须人工+{+ const r = runCase('确认允许完全访问?', ['确认开启', '取消']);+ assert.strictEqual(r.acted, null);+ console.log('✓ 完全访问授权确认:不自动点(提权需人工)');+}++// 13) 祖先容器含扣费词不得污染弹窗判定。+// 历史故障:扣费词守卫会向上 8 层扫祖先文本,而弹窗外层就是整段会话/BODY,+// 只要那里出现「积分/费用」等词,所有层级都会被判成扣费弹窗 → 弹窗一个都点不动。+{+ const card = mkCard('检测到受保护文件修改', ['允许', '本次会话内始终允许', '拒绝']);+ const outer = mkNode('div', [mkText('本次会话共消耗 12 积分,剩余余额 380 点'), card]);+ const doc = { body: outer, querySelectorAll: (sel) => allButtons(outer) };+ const audit = [];+ makeScan(doc, audit)();+ const acted = allButtons(card).find((b) => b.getAttribute('data-nd-auto') === '1') || null;+ assert.ok(acted, '外层容器含「积分」时仍应命中弹窗');+ assert.strictEqual(acted._clicked, true);+ console.log('✓ 祖先含扣费词:弹窗仍被自动点(不被误判为扣费弹窗)');+}+// 14) 敏感凭证卡同样不得被外层扣费词污染+{+ const card = mkCard('是否允许模型访问敏感凭证?', ['允许访问', '允许加密访问(推荐)', '禁止访问']);+ const outer = mkNode('div', [mkText('本会话已消耗费用 0.41,余额充足'), card]);+ const doc = { body: outer, querySelectorAll: (sel) => allButtons(outer) };+ const audit = [];+ makeScan(doc, audit)();+ const acted = allButtons(card).find((b) => b.getAttribute('data-nd-auto') === '1') || null;+ assert.ok(acted, '外层含「费用」时敏感凭证卡仍应命中');+ console.log('✓ 祖先含费用词:敏感凭证卡仍被自动点');+}+console.log('\n免打扰弹窗匹配逻辑回归测试全部通过 ✅');diff --git a/test/oauth-platform.test.js b/test/oauth-platform.test.jsnew file mode 100644index 0000000..c500524--- /dev/null+++ b/test/oauth-platform.test.js@@ -0,0 +1,45 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const vm = require('node:vm');+const { PROFILES } = require('../scripts/profiles');+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+const route = source.slice(source.indexOf(" if (req.method === 'POST' && p === '/api/oauth/start')"), source.indexOf(' // 「无感登录」第二步'));++async function start(profile, returnedUrl) {+ let request;+ const context = {+ PROFILE: profile, WB_API_ENDPOINT: profile.apiHost, WB_API_PREFIX: '/v2/plugin',+ req: { method: 'POST' }, p: '/api/oauth/start', res: {},+ httpJson: async (url, method, body) => { request = { url, method, body }; return { data: { state: 'fixture+state', ...(returnedUrl ? { authUrl: returnedUrl } : {}) } }; },+ crypto: { randomUUID: () => 'fixture-login' }, oauthStates: new Map(),+ OAUTH_TIMEOUT_SECONDS: 600, OAUTH_RESULT_RETENTION_SECONDS: 300,+ setTimeout: () => ({ unref() {} }), log() {},+ json: (_res, status, data) => ({ status, ...data }),+ };+ const result = await vm.runInNewContext('(async()=>{' + route + '})()', context);+ return { result, request, context };+}+for (const [profile, platform] of [['workbuddy-ai', 'workbuddy-ai'], ['workbuddy-cn', 'workbuddy']]) {+ test(`${profile} requests OAuth state for its own app and preserves official authorization URL`, async () => {+ const official = PROFILES[profile].apiHost + '/login/started?platform=' + platform + '&state=fixture';+ const { request, result, context } = await start(PROFILES[profile], official);+ const url = new URL(request.url);+ assert.equal(url.origin, PROFILES[profile].apiHost);+ assert.equal(url.searchParams.get('platform'), platform);+ assert.equal(request.method, 'POST');+ assert.equal(result.status, 200);+ assert.equal(result.verificationUri, official);+ assert.equal(context.oauthStates.get(result.loginId).state, 'fixture+state');+ });+ test(`${profile} fallback authorization URL preserves platform and encodes state`, async () => {+ const { result } = await start(PROFILES[profile]);+ const url = new URL(result.verificationUri);+ assert.equal(url.origin, PROFILES[profile].apiHost);+ assert.equal(url.pathname, '/login/started');+ assert.equal(url.searchParams.get('platform'), platform);+ assert.equal(url.searchParams.get('state'), 'fixture+state');+ });+}diff --git a/test/panel-brand-robot.test.js b/test/panel-brand-robot.test.jsnew file mode 100644index 0000000..d03d619--- /dev/null+++ b/test/panel-brand-robot.test.js@@ -0,0 +1,93 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const vm = require('node:vm');+const { createBrandClickAction, createFabAppearance } = require('../scripts/inject.js');++function brandHarness() {+ const timers = new Map();+ let next = 0, opens = 0, debugs = 0;+ const action = createBrandClickAction({+ setTimeout(fn) { timers.set(++next, fn); return next; },+ clearTimeout(id) { timers.delete(id); },+ openWebsite() { opens++; }, unlockDebug() { debugs++; },+ });+ return { action, flush() { const jobs = [...timers.values()]; timers.clear(); jobs.forEach(fn => fn()); },+ get counts() { return { opens, debugs }; } };+}++test('single brand click opens once; five rapid clicks unlock debug without opening a browser', () => {+ const h = brandHarness();+ h.action.click();+ assert.deepEqual(h.counts, { opens: 0, debugs: 0 });+ h.flush();+ assert.deepEqual(h.counts, { opens: 1, debugs: 0 });+ for (let i = 0; i < 5; i++) h.action.click();+ assert.deepEqual(h.counts, { opens: 1, debugs: 1 });+ h.action.click(); // extra click within the same burst must not launch the site+ h.flush();+ assert.deepEqual(h.counts, { opens: 1, debugs: 1 });+ h.action.click(); h.action.destroy(); h.flush();+ assert.deepEqual(h.counts, { opens: 1, debugs: 1 }, 'reinjection cancels a pending website launch');+});++test('robot appearance restores per-profile preferences and rejects unknown styles', () => {+ const values = new Map(), attrs = new Map();+ const 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');+ 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');+ style.set('glass');+ assert.equal(createFabAppearance(options).get(), 'glass');+ style.set('invalid');+ assert.equal(style.get(), 'glass');+});++test('panel owns the brand and groups robot controls; message shadow is the last theme card', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ assert.doesNotMatch(source, /function syncWindowLogo|class="wbs-ghbtn"/);+ assert.match(source, /class="wbs-brand" id="wbs-title"/);+ assert.match(source, /https:\/\/www\.workdaddy\.dev/);+ const start = source.indexOf('function buildThemePane()');+ const pane = source.slice(start, source.indexOf('wireThemePane();', start));+ assert.ok(pane.indexOf('id="wbs-text-shadow-card"') > pane.indexOf('id="wbs-bg-blur-range"'));+ const 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/);+});++// Exercise the actual panel wiring: browser timers reject an options object as `this`.+test('panel five-click wiring preserves the browser timer receiver and reveals debug tools', () => {+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const start = source.indexOf(" var piTitle = root.querySelector('#wbs-title');");+ const end = source.indexOf(' if (piPickBtn) {', start);+ const button = {}, picker = { style: { display: 'none' } }, card = { style: { display: 'none' } };+ const context = vm.createContext({+ createBrandClickAction, button, picker, card,+ root: { querySelector: selector => selector === '#wbs-title' ? button : picker },+ aboutPane: { querySelector: () => card },+ hiddenToolsUnlocked: false,+ listen: (node, type, handler) => { node[type] = handler; },+ registerDisposer() {}, toast() {},+ });+ vm.runInContext(`+ var timers = new Map(), timerId = 0;+ function setBuildTimeout(fn) { timers.set(++timerId, fn); return timerId; }+ function clearTimeout(id) {+ if (this !== globalThis) throw new TypeError('Illegal invocation');+ timers.delete(id);+ }+ ` + source.slice(start, end) + `+ for (var i = 0; i < 5; i++) button.click({ preventDefault: function () {} });+ `, context);+ assert.equal(context.hiddenToolsUnlocked, true);+ assert.equal(picker.style.display, '');+ assert.equal(card.style.display, '');+});diff --git a/test/renderer-escaping.test.js b/test/renderer-escaping.test.jsindex 5b94411..54297f0 100644--- a/test/renderer-escaping.test.js+++ b/test/renderer-escaping.test.js@@ -49,7 +49,7 @@ test('session and account selectors escape every text and attribute sink', () =>assert.doesNotMatch(accountSelect, /'<option value="' \+ a\.uid/);assert.doesNotMatch(accountSelect, /\+ \(a\.nickname \|\|/);- const copyModal = sourceBetween('function openCopyModal(ids)', 'function openDeleteModal(ids)');+ const copyModal = sourceBetween('function openCopyModal(ids)', 'function openDeleteModal(ids, allAccounts)');assert.match(copyModal, /'<option value="' \+ escAttr\(a\.uid\) \+ '">' \+ esc\(a\.nickname \|\| a\.uid\)/);assert.match(copyModal, /a\.phone \? '[^']*' \+ esc\(a\.phone\)/);assert.doesNotMatch(copyModal, /'<option value="' \+ a\.uid/);diff --git a/test/session-delete-confinement.test.js b/test/session-delete-confinement.test.jsindex c218906..d08e34f 100644--- a/test/session-delete-confinement.test.js+++ b/test/session-delete-confinement.test.js@@ -164,6 +164,74 @@ test('unexpected filesystem removal errors are surfaced instead of reported as sassert.equal(fs.existsSync(target), true);});+test('session deletion removes only matching app cache entries and preserves its format', (t) => {+ const { deleteSessionFiles } = loadSessionDeleteHelpers();+ for (const wrapped of [false, true]) {+ const root = tempDir(t);+ fs.mkdirSync(path.join(root, 'app'));+ const file = path.join(root, 'app', 'sessions.json');+ const keep = { conversationId: 'keep', windowId: 7 };+ const entries = [{ conversationId: 'remove', windowId: 1 }, keep, { unknown: true }];+ fs.writeFileSync(file, JSON.stringify(wrapped ? { version: 2, sessions: entries } : entries), { mode: 0o600 });+ assert.equal(deleteSessionFiles(root, 'remove'), 1);+ assert.deepEqual(JSON.parse(fs.readFileSync(file, 'utf8')), wrapped ? { version: 2, sessions: [keep, { unknown: true }] } : [keep, { unknown: true }]);+ assert.equal(deleteSessionFiles(root, 'remove'), 0, 'retries must be idempotent');+ assert.deepEqual(fs.readdirSync(path.join(root, 'app')), ['sessions.json']);+ if (process.platform !== 'win32') assert.equal(fs.statSync(file).mode & 0o777, 0o600);+ }+});++test('unreadable app cache fails before deleting session files', (t) => {+ const { deleteSessionFiles } = loadSessionDeleteHelpers();+ const root = tempDir(t);+ fs.mkdirSync(path.join(root, 'app'));+ fs.mkdirSync(path.join(root, 'tasks', 'remove'), { recursive: true });+ for (const content of ['{broken', '{"sessions":{}}']) {+ fs.writeFileSync(path.join(root, 'app', 'sessions.json'), content);+ assert.throws(() => deleteSessionFiles(root, 'remove'), /会话缓存/);+ assert.ok(fs.existsSync(path.join(root, 'tasks', 'remove')));+ assert.equal(fs.readFileSync(path.join(root, 'app', 'sessions.json'), 'utf8'), content);+ }+});++test('a linked app cache cannot overwrite an outside file', (t) => {+ const { deleteSessionFiles } = loadSessionDeleteHelpers();+ const root = tempDir(t), outside = tempDir(t);+ const content = '[{"conversationId":"remove"}]';+ fs.mkdirSync(path.join(root, 'app'));+ fs.writeFileSync(path.join(outside, 'sessions.json'), content);+ try { fs.symlinkSync(path.join(outside, 'sessions.json'), path.join(root, 'app', 'sessions.json')); }+ catch (error) { if (['EPERM', 'EACCES'].includes(error.code)) return t.skip('symlinks unavailable'); throw error; }+ assert.throws(() => deleteSessionFiles(root, 'remove'), /会话缓存/);+ assert.equal(fs.readFileSync(path.join(outside, 'sessions.json'), 'utf8'), content);+});++test('a locked cache replacement preserves the original file and removes temporary staging', (t) => {+ const root = tempDir(t);+ fs.mkdirSync(path.join(root, 'app'));+ const file = path.join(root, 'app', 'sessions.json');+ const content = '[{"conversationId":"remove"}]';+ fs.writeFileSync(file, content);+ const fsImpl = Object.create(fs);+ fsImpl.renameSync = () => { throw Object.assign(new Error('locked'), { code: 'EPERM' }); };+ assert.throws(() => loadSessionDeleteHelpers(fsImpl).deleteSessionFiles(root, 'remove'), /locked/);+ assert.equal(fs.readFileSync(file, 'utf8'), content);+ assert.deepEqual(fs.readdirSync(path.join(root, 'app')), ['sessions.json']);+});++test('a concurrently updated app cache is not overwritten', (t) => {+ const root = tempDir(t);+ fs.mkdirSync(path.join(root, 'app'));+ const file = path.join(root, 'app', 'sessions.json');+ fs.writeFileSync(file, '[{"conversationId":"remove"}]');+ const updated = '[{"conversationId":"remove"},{"conversationId":"new"}]';+ const fsImpl = Object.create(fs);+ fsImpl.writeFileSync = (...args) => { fs.writeFileSync(...args); fs.writeFileSync(file, updated); };+ assert.throws(() => loadSessionDeleteHelpers(fsImpl).deleteSessionFiles(root, 'remove'), /已变化/);+ assert.equal(fs.readFileSync(file, 'utf8'), updated);+ assert.deepEqual(fs.readdirSync(path.join(root, 'app')), ['sessions.json']);+});+test('delete route validates before SQL and deletes the matched set only', () => {const source = fs.readFileSync(daemonPath, 'utf8');const routeStart = source.indexOf("p === '/api/sessions/delete'");@@ -186,3 +254,46 @@ test('delete route validates before SQL and deletes the matched set only', () =>assert.ok(filesAt >= 0 && filesAt < rulesAt && rulesAt < deleteAt,'filesystem and rule cleanup must succeed before the retry anchor is removed from the database');});++test('delete route removes recorded copies across accounts from both DB and files', async (t) => {+ const lib = require('../scripts/lib.js');+ const { createSessionDb, normalizeSessionIdBatch } = require('../scripts/session-db.js');+ const root = tempDir(t);+ const db = createSessionDb({ dbPath: path.join(root, 'sessions.db') });+ await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT)');+ const rows = [['session-a', 'source'], ['copy-a', 'target'], ['copy-third', 'third'], ['unrelated', 'target']];+ for (const [id, uid] of rows) {+ await db.run('INSERT INTO sessions (id, user_id) VALUES (?, ?)', [id, uid]);+ fs.mkdirSync(path.join(root, 'tasks', id), { recursive: true });+ fs.writeFileSync(path.join(root, 'tasks', id, 'messages.json'), '[]');+ }+ const original = lib.ensureAutoCopySession(root, 'source', 'session-a');+ lib.setAutoCopyMapping(root, original, 'target', { targetId: 'copy-a' });+ const split = lib.ensureAutoCopySession(root, 'target', 'copy-a');+ lib.addAutoCopySessionMember(root, split, 'third', 'copy-third');+ lib.ensureAutoCopySession(root, 'target', 'unrelated');++ const source = fs.readFileSync(daemonPath, 'utf8');+ const start = source.indexOf(" if (req.method === 'POST' && p === '/api/sessions/delete')");+ const end = source.indexOf(' // 恢复会话:', start);+ const ctx = vm.createContext({+ ...loadSessionDeleteHelpers(),+ normalizeSessionIdBatch,+ collectLineageMembersForDelete: lib.collectLineageMembersForDelete,+ removeAutoCopySession: lib.removeAutoCopySession,+ DATA_DIR: root, PROFILE: { dataRoot: root },+ req: { method: 'POST' }, res: {}, p: '/api/sessions/delete',+ readBody: async () => ({ ids: ['copy-a'] }),+ sqliteQuery: (sql, params) => db.all(sql, Array.from(params)),+ sqliteRun: (sql, params) => db.run(sql, Array.from(params)),+ sqlPlaceholders: ids => ids.map(() => '?').join(','),+ json: (_, status, body) => ({ status, body }), log() {},+ });+ const result = await vm.runInContext('(async function () {\n' + source.slice(start, end) + '\n})()', ctx);+ assert.equal(result.status, 200);+ assert.equal(result.body.deleted, 3);+ assert.equal(result.body.cascaded, 2);+ assert.deepEqual(await db.all('SELECT id FROM sessions'), [{ id: 'unrelated' }]);+ assert.deepEqual(fs.readdirSync(path.join(root, 'tasks')), ['unrelated']);+ assert.equal(lib.getAutoCopySession(root, 'target', 'unrelated').enabled, true);+});diff --git a/test/session-delete-ui.test.js b/test/session-delete-ui.test.jsnew file mode 100644index 0000000..cd6c030--- /dev/null+++ b/test/session-delete-ui.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 source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');+function harness() {+ const requests = [], nodes = {};+ for (const id of ['title', 'body', 'ok', 'cancel']) nodes['#wbs-sess-modal-' + id] = { textContent: '', focus() {}, disabled: false };+ const ctx = vm.createContext({+ sessionsPane: { querySelector: id => nodes[id] },+ sessionsState: {}, root: {}, toast() {}, loadSessions() {},+ showSessModal(show) { ctx.open = show; if (!show) nodes['#wbs-sess-modal-ok'].onclick = null; },+ api(route, options) { return new Promise((resolve, reject) => requests.push({ route, options, resolve, reject })); },+ });+ const start = source.indexOf(' function openDeleteModal(');+ vm.runInContext(source.slice(start, source.indexOf(' function selectedSessIds()', start)), ctx);+ return { ctx, requests, nodes, ok: nodes['#wbs-sess-modal-ok'] };+}++test('all-account deletion requires two confirmations and freezes the selected IDs', async () => {+ const h = harness(), selected = ['selected-session'];+ h.ctx.openDeleteModal(selected, true);+ selected.push('later-selection');+ assert.equal(h.requests.length, 0);+ h.ok.onclick();+ assert.equal(h.requests.length, 0, 'first confirmation must not delete');+ assert.match(h.nodes['#wbs-sess-modal-title'].textContent, /再次确认/);+ h.ok.onclick(); h.ok.onclick();+ assert.equal(h.requests.length, 1, 'ignore duplicate submission');+ assert.equal(h.requests[0].route, '/api/sessions/delete');+ assert.deepEqual(JSON.parse(h.requests[0].options.body).ids, ['selected-session']);+ h.requests[0].resolve({ deleted: 3, cascaded: 2 });+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(h.ctx.open, false);+});++test('cancelling the second confirmation sends no deletion request', () => {+ const h = harness(); h.ctx.openDeleteModal(['selected-session'], true);+ h.ok.onclick(); h.ctx.showSessModal(false);+ assert.equal(h.requests.length, 0);+ assert.equal(h.ok.onclick, null);+});++test('existing deletion retains its single confirmation and errors permit retry', async () => {+ const h = harness(); h.ctx.openDeleteModal(['selected-session']);+ h.ok.onclick(); assert.equal(h.requests.length, 1);+ h.requests[0].reject(Error('locked'));+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(h.ok.disabled, false);+ assert.equal(h.ctx.open, true);+ h.ok.onclick(); assert.equal(h.requests.length, 2);+});++test('all-account delete button follows the current session selection', () => {+ const button = { style: { display: '' } };+ const state = { list: [{ id: 'first' }, { id: 'second' }], selected: {} };+ const ctx = vm.createContext({+ sessionsState: state,+ sessionsPane: { querySelector: id => id === '#wbs-sess-delete-all' ? button : null },+ updateSessionSummary() {}, syncCheckAllBtn() {},+ });+ const start = source.indexOf(' function updateSessCount()');+ vm.runInContext(source.slice(start, source.indexOf(' // 全选按钮', start)), ctx);+ ctx.updateSessCount();+ assert.equal(button.style.display, 'none', 'hidden before checking a session');+ state.selected.first = true;+ ctx.updateSessCount();+ assert.equal(button.style.display, '', 'visible after checking a session');+ state.selected = {};+ ctx.updateSessCount();+ assert.equal(button.style.display, 'none', 'hidden after clearing selection');+ state.selected = { stale: true };+ ctx.updateSessCount();+ assert.equal(button.style.display, 'none', 'selection outside the current list does not show deletion');+});diff --git a/test/session-monitor.test.js b/test/session-monitor.test.jsindex bacbaa2..e7cde2c 100644--- a/test/session-monitor.test.js+++ b/test/session-monitor.test.js@@ -138,7 +138,8 @@ test('session resource subscription delivers non-active completion without contrtest('monitor log card stays hidden until the five-click logo unlock', () => {assert.match(injectSource, /id="wbs-monitor-log-card"' \+ \(hiddenToolsUnlocked \? '' : ' style="display:none"'\)/);- assert.match(injectSource, /if \(piClickCount >= 5\)[\s\S]*hiddenToolsUnlocked = true;[\s\S]*monitorLogCard\.style\.display = '';/);+ assert.match(injectSource, /if \(count === 5\) options\.unlockDebug\(\)/);+ assert.match(injectSource, /unlockDebug: function \(\) \{[\s\S]*hiddenToolsUnlocked = true;[\s\S]*monitorLogCard\.style\.display = '';/);});test('compat discovers multiple capability-shaped controllers and de-duplicates fibers', () => {diff --git a/test/theme-text-shadow.test.js b/test/theme-text-shadow.test.jsnew file mode 100644index 0000000..e7999a1--- /dev/null+++ b/test/theme-text-shadow.test.js@@ -0,0 +1,42 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const vm = require('node:vm');+const { createThemeTextShadow } = require('../scripts/theme-text-shadow.js');++test('message shadow defaults on, persists off and only affects frosted message documents', (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-shadow-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const file = path.join(dir, 'shadow.json');+ const store = createThemeTextShadow(file);+ assert.equal(store.read(), true);+ const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+ const context = { loadThemePatches: () => require('../scripts/theme-patches.js'), themeTextShadow: store };+ const start = daemon.indexOf('function themeExtrasCss(id)');+ vm.runInNewContext(daemon.slice(start, daemon.indexOf('\n/**', start)), context);+ const shadow = 'text-shadow:0 1px 2px';+ assert.ok(context.themeExtrasCss('nebula').includes(shadow));+ for (const id of ['default', 'eye-care', 'cyber-purple']) assert.ok(!context.themeExtrasCss(id).includes(shadow));+ store.save({ enabled: false });+ assert.equal(createThemeTextShadow(file).read(), false);+ assert.ok(!context.themeExtrasCss('nebula').includes(shadow));+ assert.ok(context.themeExtrasCss('nebula').includes(':is(.workbuddy-topbar--mac,.conversation-shell,.conversation-sidebar)'), 'disabling shadow preserves transparent backgrounds');+ for (const input of [null, {}, { enabled: 'false' }]) assert.throws(() => store.save(input));+ assert.equal(store.read(), false);+ store.save({ enabled: true });+ assert.ok(context.themeExtrasCss('nebula').includes(shadow));+ const patch = require('../scripts/theme-patches.js').find(p => p.id === 'patch-101');+ assert.ok(patch.css.includes('.conversation-timeline .cr-document *'));+ assert.ok(!patch.css.includes('.cr-input'));+});++test('text color controls and their backend overrides have been removed', () => {+ const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+ assert.doesNotMatch(inject + daemon, /wbs-text-colors|themeTextColors|api\/theme-text-colors/);+ assert.match(inject, /id="wbs-text-shadow" checked disabled/);+});diff --git a/test/third-party-model-ui.test.js b/test/third-party-model-ui.test.jsnew file mode 100644index 0000000..8160d81--- /dev/null+++ b/test/third-party-model-ui.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(conflicts = true) {+ const nodes = {};+ function node() { return { classList: { add() {} }, style: {}, textContent: '', innerHTML: '', disabled: false, checked: false, focus() {}, addEventListener() {}, remove() {}, querySelector: key => nodes[key], querySelectorAll: () => [] }; }+ for (const key of ['.wbs-modal', '.wbs-modal-body', '.wbs-modal-title', '[data-third-ok]', '[data-third-cancel]', '[data-third-all]', '[data-third-count]', '[data-third-app]', '[data-third-list]']) nodes[key] = node();+ const calls = [];+ const ctx = vm.createContext({ document: { createElement: node }, modelsPane: { querySelector() { return null; }, appendChild() {} }, esc: String, escAttr: String, root: {}, toast() {}, loadModels() {}, api(route, options) { calls.push({ route, body: JSON.parse(options.body) }); return Promise.resolve(conflicts && !JSON.parse(options.body).confirmed ? { confirmationRequired: true, replaced: 1, duplicateIds: 0 } : { imported: 1 }); } });+ const start = source.indexOf(' function openThirdPartyModels(');+ vm.runInContext(source.slice(start, source.indexOf(' function wireModelsPane()', start)), ctx);+ return { ctx, nodes, calls };+}++const rows = [+ { key: 'a', providerKey: 'provider-a', provider: 'A', appType: 'claude', id: 'a', apiKey: 'fixture-key' },+ { key: 'b', providerKey: 'provider-b', provider: 'B', appType: 'claude', id: 'b', apiKey: 'fixture-key' },+ { key: 'c1', providerKey: 'provider-c', provider: 'C', appType: 'opencode', id: 'c1', apiKey: 'fixture-key' },+ { key: 'c2', providerKey: 'provider-c', provider: 'C', appType: 'opencode', id: 'c2', apiKey: 'fixture-key' },+];+function change(h, attr, value, checked) {+ h.nodes['.wbs-modal-body'].onchange({ target: { value, checked, disabled: false, hasAttribute: name => name === attr, getAttribute: () => value } });+}++test('filtered backend rows without available flags drive selection, counts and both confirmation steps', async () => {+ const h = harness(); h.ctx.openThirdPartyModels({ snapshot: 'fixture', models: rows });+ assert.equal(h.nodes['[data-third-count]'].textContent, '已选 2 / 2');+ assert.equal(h.nodes['[data-third-ok]'].disabled, false);+ change(h, 'data-third-all', '', false);+ assert.equal(h.nodes['[data-third-count]'].textContent, '已选 0 / 2');+ assert.equal(h.nodes['[data-third-ok]'].disabled, true);+ change(h, 'data-third-key', 'provider-b', true);+ assert.equal(h.nodes['[data-third-count]'].textContent, '已选 1 / 2');+ h.nodes['[data-third-ok]'].onclick();+ assert.equal(h.calls.length, 1);+ assert.equal(h.calls[0].body.confirmed, false);+ await new Promise(resolve => setImmediate(resolve));+ h.nodes['[data-third-ok]'].onclick(); h.nodes['[data-third-ok]'].onclick();+ assert.equal(h.calls.length, 2);+ assert.equal(h.calls[1].body.confirmed, true);+ assert.deepEqual(h.calls[1].body.ids, ['b']);+ await new Promise(resolve => setImmediate(resolve));+});++test('client filter imports only that client immediately when there are no conflicts', async () => {+ const h = harness(false); h.ctx.openThirdPartyModels({ snapshot: 'fixture', models: rows });+ change(h, 'data-third-app', 'opencode');+ assert.equal(h.nodes['[data-third-count]'].textContent, '已选 1 / 1');+ h.nodes['[data-third-ok]'].onclick();h.nodes['[data-third-ok]'].onclick();+ assert.deepEqual(h.calls[0].body.ids, ['c1', 'c2']);+ assert.equal(h.calls.length, 1);+ assert.equal(h.calls[0].body.confirmed, false);+ await new Promise(resolve => setImmediate(resolve));+ assert.notEqual(h.nodes['.wbs-modal-title'].textContent, '确认覆盖同名模型?');+});++test('cancel after detected conflicts and empty lists never confirm a write', async () => {+ const h = harness(); h.ctx.openThirdPartyModels({ snapshot: 'fixture', models: rows });+ h.nodes['[data-third-ok]'].onclick();+ await new Promise(resolve => setImmediate(resolve));+ h.nodes['[data-third-cancel]'].onclick();+ assert.equal(h.calls.length, 1);+ assert.equal(h.calls[0].body.confirmed, false);+ h.ctx.openThirdPartyModels({ snapshot: 'empty', models: [] });+ assert.equal(h.nodes['[data-third-count]'].textContent, '已选 0 / 0');+ assert.equal(h.nodes['[data-third-ok]'].disabled, true);+});diff --git a/test/third-party-models.test.js b/test/third-party-models.test.jsnew file mode 100644index 0000000..f839322--- /dev/null+++ b/test/third-party-models.test.js@@ -0,0 +1,232 @@+'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 { createSessionDb } = require('../scripts/session-db');+const { convertProvider, discoverCCSwitch, readCCSwitch, createThirdPartyImport } = require('../scripts/third-party-models');++function fixture(t) {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-third-party-'));+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));+ fs.mkdirSync(path.join(home, '.cc-switch'));+ return { home, platform: 'darwin', env: {}, dir: path.join(home, '.cc-switch') };+}+function claude(overrides = {}) {+ return { id: 'provider-a', name: '供应商 A', app_type: 'claude', settings_config: {+ env: { ANTHROPIC_BASE_URL: 'https://relay.example/v1', ANTHROPIC_AUTH_TOKEN: 'test-secret',+ ANTHROPIC_MODEL: 'model-a', ANTHROPIC_DEFAULT_SONNET_MODEL: 'model-a', ANTHROPIC_DEFAULT_HAIKU_MODEL: 'model-b' },+ }, ...overrides };+}++test('Claude slots dedupe and generate WorkBuddy chat endpoints without losing model IDs', () => {+ const rows = convertProvider(claude());+ assert.deepEqual(rows.map(r => r.model.id), ['model-a']);+ assert.equal(rows[0].model.url, 'https://relay.example/v1/chat/completions');+ assert.equal(rows[0].model.apiKey, 'test-secret');+ assert.equal(rows[0].model.useCustomProtocol, false);+});++test('Codex reads the selected provider, profiles, quoted TOML keys and comments', () => {+ const rows = convertProvider({ id: 'codex', name: 'Codex', app_type: 'codex', settings_config: {+ auth: { OPENAI_API_KEY: 'test-secret' },+ config: `model_provider = "my.relay"\nmodel = 'gpt-test' # comment\n[model_providers."my.relay"]\nbase_url = "https://relay.example/api/v1"\nwire_api = "responses"\n[profiles.small]\nmodel = "gpt-small"\nmodel_provider = "my.relay"`,+ } });+ assert.deepEqual(rows.map(r => r.model.id), ['gpt-test', 'gpt-small']);+ assert.equal(rows[0].model.url, 'https://relay.example/api/v1/chat/completions');+});++test('Gemini official API uses its documented OpenAI-compatible endpoint', () => {+ const [row] = convertProvider({ id: 'g', name: 'Gemini', app_type: 'gemini', settings_config: {+ env: { GEMINI_API_KEY: 'test-secret', GEMINI_MODEL: 'gemini-test' },+ } });+ assert.equal(row.model.url, 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions');+});++test('OpenCode and OpenClaw enumerate model maps/lists and preserve declared limits', () => {+ const [row] = convertProvider({ id: 'o', name: 'OpenCode', app_type: 'opencode', settings_config: {+ npm: '@ai-sdk/openai-compatible', options: { baseURL: 'https://relay.example/v1', apiKey: 'test-secret' },+ models: { 'model-a': { name: 'A', limit: { context: 120000, output: 8000 }, modalities: { input: ['text', 'image'] } } },+ } });+ assert.equal(row.model.maxInputTokens, 120000);+ assert.equal(row.model.maxOutputTokens, 8000);+ assert.equal(row.model.supportsImages, true);+ const [claw] = convertProvider({ id: 'c', name: 'Claw', app_type: 'openclaw', settings_config: {+ baseUrl: 'https://relay.example/v1', apiKey: 'test-secret', api: 'openai-completions', models: [{ id: 'model-a', name: 'A' }],+ } });+ assert.equal(claw.model.id, 'model-a');+});++test('OAuth, native-only endpoints, unknown types and unresolved secrets are rejected', () => {+ for (const provider of [+ claude({ settings_config: { env: {} } }),+ claude({ settings_config: { env: { ANTHROPIC_BASE_URL: 'https://api.anthropic.com', ANTHROPIC_API_KEY: 'test', ANTHROPIC_MODEL: 'claude-test' } } }),+ claude({ app_type: 'unknown' }),+ claude({ settings_config: { env: { ANTHROPIC_BASE_URL: 'https://relay.example', ANTHROPIC_API_KEY: '${MISSING_KEY}', ANTHROPIC_MODEL: 'm' } } }),+ ]) {+ const rows = convertProvider(provider, {});+ assert.ok(rows.length);+ assert.ok(rows.every(r => !r.model && r.reason));+ }+});++test('preview filters rejected rows and preserves per-client provider grouping', async t => {+ const options = fixture(t);+ const opencode = { id: 'provider-a', name: 'OpenCode provider', settings_config: {+ npm: '@ai-sdk/openai-compatible', options: { baseURL: 'https://relay.example/v1', apiKey: 'test-secret' },+ models: { 'model-a': {}, 'model-b': {} },+ } };+ fs.writeFileSync(path.join(options.dir, 'config.json'), JSON.stringify({+ claude: { providers: { a: claude(), invalid: claude({ id: 'invalid', settings_config: { env: {} } }) } },+ opencode: { providers: { a: opencode } },+ }));+ const preview = await createThirdPartyImport({ ...options, targetFile: path.join(options.home, 'models.json') }).preview();+ assert.equal(preview.models.length, 3);+ assert.ok(preview.models.every(row => !Object.hasOwn(row, 'available') && !Object.hasOwn(row, 'reason')));+ const rows = preview.models.filter(row => row.appType === 'opencode');+ assert.equal(rows[0].providerKey, rows[1].providerKey);+ assert.notEqual(rows[0].key, rows[1].key);+ assert.notEqual(rows[0].providerKey, preview.models.find(row => row.appType === 'claude').providerKey);+});++test('discovery honors the CC Switch custom directory and never creates missing databases', async t => {+ const options = fixture(t);+ assert.equal(discoverCCSwitch(options), null);+ assert.deepEqual(fs.readdirSync(options.dir), []);+ const custom = path.join(options.home, 'custom'); fs.mkdirSync(custom);+ fs.writeFileSync(path.join(custom, 'config.json'), JSON.stringify({ claude: { providers: { a: claude() } } }));+ const store = path.join(options.home, 'Library/Application Support/com.ccswitch.desktop'); fs.mkdirSync(store, { recursive: true });+ fs.writeFileSync(path.join(store, 'app_paths.json'), JSON.stringify({ app_config_dir_override: custom }));+ assert.equal(discoverCCSwitch(options).file, path.join(custom, 'config.json'));+ assert.equal((await readCCSwitch(options)).rows.length, 1);+});++test('SQLite and legacy JSON sources produce equivalent results; DB is read-only and preferred', async t => {+ const options = fixture(t), p = claude();+ fs.writeFileSync(path.join(options.dir, 'config.json'), JSON.stringify({ claude: { providers: { a: p } } }));+ const legacy = await readCCSwitch(options);+ const db = createSessionDb({ dbPath: path.join(options.dir, 'cc-switch.db') });+ await db.run('CREATE TABLE providers (id TEXT, name TEXT, app_type TEXT, settings_config TEXT, meta TEXT)');+ await db.run('INSERT INTO providers VALUES (?, ?, ?, ?, ?)', [p.id, p.name, p.app_type, JSON.stringify(p.settings_config), '{}']);+ assert.deepEqual((await readCCSwitch(options)).rows, legacy.rows);+ assert.equal((await db.all('SELECT COUNT(*) AS count FROM providers'))[0].count, 1);+});++test('preview shows API keys locally; import freezes the selection, requires confirmation, and backs up overwritten models', async t => {+ const options = fixture(t), target = path.join(options.home, 'models.json');+ fs.writeFileSync(path.join(options.dir, 'config.json'), JSON.stringify({ claude: { providers: { a: claude() } } }));+ fs.writeFileSync(target, JSON.stringify({ extra: true, models: [{ id: 'model-a', name: 'old', apiKey: 'old-secret' }, { id: 'keep' }] }));+ const service = createThirdPartyImport({ ...options, targetFile: target });+ const preview = await service.preview();+ assert.equal(JSON.stringify(preview).includes('test-secret'), true);+ assert.equal(preview.models.length, 1);+ const before = fs.readFileSync(target, 'utf8');+ const check = await service.import({ snapshot: preview.snapshot, ids: [preview.models[0].key] });+ assert.equal(check.confirmationRequired, true);+ assert.equal(check.replaced, 1);+ assert.equal(check.duplicateIds, 0);+ assert.equal(fs.readFileSync(target, 'utf8'), before);+ assert.equal(fs.readdirSync(options.home).some(name => name.includes('before-cc-switch')), false);+ await assert.rejects(service.import({ snapshot: preview.snapshot, ids: ['forged'], confirmed: true }), /失效|无效/);+ const result = await service.import({ snapshot: preview.snapshot, ids: [preview.models[0].key], confirmed: true });+ assert.equal(result.imported, 1); assert.equal(result.replaced, 1);+ const actual = JSON.parse(fs.readFileSync(target));+ assert.equal(actual.extra, true);+ assert.deepEqual(actual.models.map(m => m.id), ['model-a', 'keep']);+ assert.equal(actual.models[0].apiKey, 'test-secret');+ assert.equal(JSON.parse(fs.readFileSync(result.backupFile)).models[0].apiKey, 'old-secret');+ await assert.rejects(service.import({ snapshot: preview.snapshot, ids: [preview.models[0].key], confirmed: true }), /失效/);+});++test('same-ID providers remain in backups; current config uses the last selected provider', async t => {+ const options = fixture(t), target = path.join(options.home, 'models.json');+ const p = claude(); p.settings_config.env.ANTHROPIC_DEFAULT_HAIKU_MODEL = 'model-a';+ const q = JSON.parse(JSON.stringify(p)); q.id = 'provider-b'; q.name = '供应商 B';+ q.settings_config.env.ANTHROPIC_AUTH_TOKEN = 'other-secret';+ fs.writeFileSync(path.join(options.dir, 'config.json'), JSON.stringify({ claude: { providers: { a: p, b: q } } }));+ fs.writeFileSync(target, JSON.stringify({ availableModels: ['keep'], models: [{ id: 'keep' }] }));+ const service = createThirdPartyImport({ ...options, targetFile: target });+ const preview = await service.preview();+ assert.equal(preview.models.length, 2);+ const check = await service.import({ snapshot: preview.snapshot, ids: preview.models.map(m => m.key) });+ assert.equal(check.confirmationRequired, true);+ assert.equal(check.replaced, 0);+ assert.equal(check.duplicateIds, 1);+ const result = await service.import({ snapshot: preview.snapshot, ids: preview.models.map(m => m.key), confirmed: true });+ assert.equal(result.imported, 1); assert.equal(result.sameIdSkipped, 1);+ const saved = JSON.parse(fs.readFileSync(target));+ assert.deepEqual(saved.availableModels, ['keep', 'model-a']);+ assert.equal(saved.models[1].apiKey, 'other-secret');+ const backups = require('../scripts/lib').listModelBackups(options.home);+ assert.equal(backups[0].items.length, 2);+});++test('non-conflicting selection imports immediately; conflicts added after preview are checked before writing', async t => {+ const options = fixture(t), target = path.join(options.home, 'models.json');+ fs.writeFileSync(path.join(options.dir, 'config.json'), JSON.stringify({ claude: { providers: { a: claude() } } }));+ const service = createThirdPartyImport({ ...options, targetFile: target });+ const first = await service.preview();+ const result = await service.import({ snapshot: first.snapshot, ids: [first.models[0].key], confirmed: false });+ assert.equal(result.imported, 1);+ assert.equal(result.replaced, 0);+ fs.writeFileSync(target, '[]');+ const second = await service.preview();+ fs.writeFileSync(target, JSON.stringify([{ id: 'model-a', name: 'newly changed' }]));+ const before = fs.readFileSync(target, 'utf8');+ const check = await service.import({ snapshot: second.snapshot, ids: [second.models[0].key], confirmed: false });+ assert.equal(check.confirmationRequired, true);+ assert.equal(fs.readFileSync(target, 'utf8'), before);+});++test('changed source cannot alter a reviewed snapshot and expired previews cannot write', async t => {+ const options = fixture(t), target = path.join(options.home, 'models.json');+ const file = path.join(options.dir, 'config.json');+ fs.writeFileSync(file, JSON.stringify({ claude: { providers: { a: claude() } } }));+ let clock = 100;+ const service = createThirdPartyImport({ ...options, targetFile: target, now: () => clock });+ const preview = await service.preview();+ const expiring = await service.preview();+ fs.writeFileSync(file, '{}');+ const request = { snapshot: preview.snapshot, ids: [preview.models[0].key], confirmed: true };+ await service.import(request);+ assert.equal(JSON.parse(fs.readFileSync(target))[0].id, 'model-a');+ const before = fs.readFileSync(target, 'utf8');+ clock += 10 * 60 * 1000 + 1;+ await assert.rejects(service.import({ ...request, snapshot: expiring.snapshot }), /失效/);+ assert.equal(fs.readFileSync(target, 'utf8'), before);+});++test('Windows discovery uses APPDATA overrides and supports the historical HOME database', async t => {+ const options = fixture(t);+ options.platform = 'win32';+ const appData = path.join(options.home, 'roaming'), oldHome = path.join(options.home, 'legacy');+ options.env = { APPDATA: appData, HOME: oldHome };+ fs.mkdirSync(path.join(oldHome, '.cc-switch'), { recursive: true });+ const legacyDb = path.join(oldHome, '.cc-switch/cc-switch.db'); fs.writeFileSync(legacyDb, 'fixture');+ assert.equal(discoverCCSwitch(options).file, legacyDb);+ const store = path.join(appData, 'com.ccswitch.desktop'); fs.mkdirSync(store, { recursive: true });+ fs.writeFileSync(path.join(options.dir, 'config.json'), '{}');+ fs.writeFileSync(path.join(store, 'app_paths.json'), JSON.stringify({ app_config_dir_override: '~/.cc-switch' }));+ assert.equal(discoverCCSwitch(options).file, path.join(options.dir, 'config.json'));+});++test('enabled shared config supplies missing Claude model routing', async t => {+ const options = fixture(t);+ const p = claude({ meta: { commonConfigEnabled: true }, settingsConfig: undefined, settings_config: { env: { ANTHROPIC_API_KEY: 'test-secret' } } });+ fs.writeFileSync(path.join(options.dir, 'config.json'), JSON.stringify({+ claude: { providers: { a: p } }, common_config_snippets: { claude: JSON.stringify({ env: { ANTHROPIC_MODEL: 'shared-model', ANTHROPIC_BASE_URL: 'https://relay.example/v1' } }) },+ }));+ const rows = (await readCCSwitch(options)).rows;+ assert.equal(rows[0].model.id, 'shared-model');+});++test('malformed configuration errors never include raw credential-bearing input', async t => {+ const options = fixture(t), secret = 'DO-NOT-PRINT-SECRET';+ fs.writeFileSync(path.join(options.dir, 'config.json'), '{"apiKey":"' + secret);+ await assert.rejects(readCCSwitch(options), e => !e.message.includes(secret));+ const rows = convertProvider(claude({ settings_config: '{"token":"' + secret }));+ assert.equal(JSON.stringify(rows).includes(secret), false);+ const unsupported = convertProvider({ id: 'c', name: 'Codex', app_type: 'codex', settings_config: { auth: { OPENAI_API_KEY: secret }, config: 'note = """\nmodel="not-a-real-model"\n"""' } });+ assert.ok(unsupported.every(r => !r.model));+});diff --git a/test/token-stats.test.js b/test/token-stats.test.jsnew file mode 100644index 0000000..09f6603--- /dev/null+++ b/test/token-stats.test.js@@ -0,0 +1,158 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');+const { scanTokenStats, scanTokenStatsCached, dateBounds, tokenStatsCacheReady } = require('../scripts/token-stats.js');++test('scans usage metadata without reading message semantics into the result', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-token-stats-'));+ fs.mkdirSync(path.join(root, 'project-a'), { recursive: true });+ fs.writeFileSync(path.join(root, 'project-a', 'session.jsonl'), [+ JSON.stringify({ timestamp: '2026-09-10T10:00:00Z', model: 'model-x', message: 'secret', usage: { input_tokens: 10, output_tokens: 4, cache_read_tokens: 2 } }),+ '{broken',+ ].join('\n'));+ const result = scanTokenStats(root, { now: Date.parse('2026-09-11T10:00:00Z'), days: 7 });+ assert.deepEqual(result.totals, { input: 10, output: 4, cacheRead: 2, cacheWrite: 0, calls: 1 });+ assert.equal(result.models[0].model, 'model-x');+ assert.equal(result.parseErrors, 1);+ assert.equal('message' in result, false);+});++test('cached scan reuses history and merges today without duplicate calls', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-token-cache-'));+ fs.mkdirSync(path.join(root, 'project-a'), { recursive: true });+ const now = Date.parse('2026-09-11T10:00:00Z');+ const file = path.join(root, 'project-a', 'session.jsonl');+ fs.writeFileSync(file, JSON.stringify({ timestamp: '2026-09-10T10:00:00Z', model: 'm', usage: { input_tokens: 3, output_tokens: 2 } }) + '\n');+ const ownership = { session: 'acct-a' };+ assert.equal(tokenStatsCacheReady(root, {now}), false);+ const first = scanTokenStatsCached(root, { now, days: 7, accountOptions: [{ uid: 'acct-a' }], sessionAccounts: ownership });+ assert.equal(first.totals.calls, 1);+ assert.equal(first.cacheHit, false);+ assert.equal(tokenStatsCacheReady(root, {now}), true);+ const cachePayload = JSON.parse(fs.readFileSync(path.join(root, '.workdaddy-token-stats-cache.json'), 'utf8'));+ assert.equal(Array.isArray(cachePayload.records), false);+ assert.equal(Array.isArray(cachePayload.historicalBuckets), true);+ assert.equal(typeof cachePayload.todayFiles, 'object');+ const filtered = scanTokenStatsCached(root, { now, days: 7, account: 'acct-a', accountOptions: [{ uid: 'acct-a' }], sessionAccounts: ownership });+ assert.equal(filtered.totals.calls, 1);+ assert.equal(filtered.cacheHit, true);+ fs.appendFileSync(file, JSON.stringify({ timestamp: '2026-09-11T10:01:00Z', model: 'm', usage: { input_tokens: 4, output_tokens: 1 } }) + '\n');+ const second = scanTokenStatsCached(root, { now: now + 2 * 60 * 1000, days: 7, accountOptions: [{ uid: 'acct-a' }], sessionAccounts: ownership });+ assert.equal(second.totals.calls, 2);+ const third = scanTokenStatsCached(root, { now: now + 3 * 60 * 1000, days: 7, accountOptions: [{ uid: 'acct-a' }], sessionAccounts: ownership });+ assert.equal(third.totals.calls, 2);+ assert.equal(third.cacheHit, true);+ assert.equal(third.accounts[0].account, 'acct-a');+});++test('date range is limited to 90 days', () => {+ const now = Date.parse('2026-09-11T10:00:00Z');+ assert.throws(() => dateBounds(now, { from: '2026-01-01', until: '2026-09-11' }), /不能超过 90 天/);+ assert.throws(() => dateBounds(now, { from: '2026-09-12', until: '2026-09-11' }), /不能晚于/);+});++test('today range starts at local midnight', () => {+ const now = new Date(2026, 8, 11, 10, 0, 0).getTime();+ const bounds = dateBounds(now, { days: 1 });+ const start = new Date(now); start.setHours(0, 0, 0, 0);+ assert.equal(bounds.from, start.getTime());+});++test('cached history and live buckets do not double count calls', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-token-overlap-'));+ const file = path.join(root, 'session.jsonl');+ const now = Date.parse('2026-09-11T10:00:00Z');+ fs.writeFileSync(file, JSON.stringify({ timestamp: '2026-09-10T10:00:00Z', usage: { input_tokens: 2 } }) + '\n');+ const first = scanTokenStatsCached(root, { now, days: 7 });+ assert.equal(first.totals.calls, 1);+ const second = scanTokenStatsCached(root, { now: now + 60_000, days: 7 });+ assert.equal(second.totals.calls, 1);+});++test('token statistics UI keeps results under an overlay and exposes presets through 90 days only', () => {+ const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ assert.match(source, /class="wbs-token-stats-content"/);+ assert.match(source, /class="wbs-token-stats-overlay"/);+ assert.match(source, /overlay\.hidden = false/);+ assert.doesNotMatch(source, /data-token-search|data-token-reset/);+ assert.doesNotMatch(source, /data-token-from|data-token-until|value="custom"/);+ assert.doesNotMatch(source, /wbs-token-stats-diagnostics/);+ assert.match(source, /api\('\/api\/token-stats\?cacheStatus=1'\)/);+ assert.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, /var tokenDays = \[\]/);+ assert.match(source, /data-token-days><option value="1">今天<\/option><option value="7" selected>/);+ assert.match(source, /data-credit-days><option value="1">今天<\/option><option value="7" selected>/);+});++test('token cache survives local day rollover without rereading unchanged JSONL files', t => {+ const root=fs.mkdtempSync(path.join(os.tmpdir(),'wbs-token-rollover-'));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));+ const file=path.join(root,'s.jsonl');+ const firstTime=new Date(2026,8,10,23,30).getTime();+ fs.writeFileSync(file,JSON.stringify({timestamp:firstTime,usage:{input_tokens:8}})+'\n');+ scanTokenStatsCached(root,{now:firstTime,days:7});+ const read=fs.readFileSync;let reads=0;+ fs.readFileSync=function(p,...args){if(p===file)reads++;return read.call(this,p,...args);};+ t.after(()=>{fs.readFileSync=read;});+ const second=scanTokenStatsCached(root,{now:new Date(2026,8,12,10).getTime(),days:30});+ assert.equal(second.cacheHit,true);assert.equal(reads,0);assert.equal(second.totals.input,8);+ fs.appendFileSync(file,JSON.stringify({timestamp:new Date(2026,8,11,15).getTime(),usage:{input_tokens:3}})+'\n');+ const third=scanTokenStatsCached(root,{now:new Date(2026,8,12,11).getTime(),days:30});+ assert.equal(third.totals.input,11);assert.equal(reads,1);+});++test('AI usage after local midnight is visible today and in seven days', t => {+ const previousTZ = process.env.TZ; process.env.TZ = 'Asia/Shanghai';+ t.after(() => { if (previousTZ === undefined) delete process.env.TZ; else process.env.TZ = previousTZ; });+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-ai-midnight-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'projects', 'p'), { recursive: true });+ const file = path.join(root, 'projects', 'p', 'session.jsonl');+ const now = Date.parse('2026-09-13T01:00:00+08:00');+ const records = [+ { timestamp: '2026-09-12T23:00:00+08:00', model: 'm', usage: { input_tokens: 9 } },+ ...[279, 110, 114, 124].map((output, i) => ({+ timestamp: Date.parse('2026-09-13T00:43:00+08:00') + i * 1000,+ type: i === 3 ? 'message' : 'function_call',+ providerData: { model: 'm', usage: { inputTokens: 100, outputTokens: output } },+ message: { usage: { input_tokens: 100, output_tokens: output, cache_read_input_tokens: 60 } }+ }))+ ];+ fs.writeFileSync(file, records.map(JSON.stringify).join('\n'));+ const options = { now, sessionAccounts: { session: 'acct' } };+ const today = scanTokenStatsCached(root, { ...options, days: 1 });+ assert.equal(today.totals.calls, 4);+ assert.equal(today.totals.input, 400);+ assert.equal(today.totals.cacheRead, 240);+ assert.deepEqual(today.daily.map(x => x.day), ['2026-09-13']);+ assert.equal(today.accounts[0].calls, 4);+ const read = fs.readFileSync; let reads = 0;+ fs.readFileSync = function(p, ...args) { if (p === file) reads++; return read.call(this, p, ...args); };+ t.after(() => { fs.readFileSync = read; });+ const week = scanTokenStatsCached(root, { ...options, days: 7 });+ assert.equal(week.totals.calls, 5);+ assert.deepEqual(week.daily.map(x => x.day), ['2026-09-12', '2026-09-13']);+ assert.equal(scanTokenStatsCached(root, { ...options, days: 1 }).totals.calls, 4);+ assert.equal(scanTokenStatsCached(root, { ...options, days: 30 }).totals.calls, 5);+ assert.equal(reads, 0, 'switching filters never reparses unchanged session files');+});++test('seven-day totals match calendar dates and ignore diagnostic copies', t => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-token-calendar-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'projects')); fs.mkdirSync(path.join(root, 'logs'));+ const now = new Date(2026, 8, 13, 1).getTime();+ const rows = [6, 7, 12, 13].map(day => ({timestamp: new Date(2026,8,day,0,30).getTime(),usage:{input_tokens:day}}));+ fs.writeFileSync(path.join(root, 'projects', 's.jsonl'), rows.map(JSON.stringify).join('\n'));+ fs.writeFileSync(path.join(root, 'logs', 'diagnostic.jsonl'), JSON.stringify(rows[3]));+ const stats = scanTokenStatsCached(root, { now, days: 7 });+ assert.equal(stats.totals.calls, 3);+ assert.equal(stats.totals.input, 32);+ assert.deepEqual(stats.daily.map(x => x.day), ['2026-09-07', '2026-09-12', '2026-09-13']);+});diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex 3d47438..6ee64e1 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -781,8 +781,9 @@ test('account cards keep the compact three-row layout', () => {// 账号页暂不展示“发起独立会话保持活跃”入口;daemon 接口保留供内部/后续流程使用。assert.doesNotMatch(script, /wbs-growth-activate/);assert.doesNotMatch(script, /api\('\/api\/growth\/activate'/);- assert.match(script, /expired \? '' : '<button class="wbs-icon-btn wbs-acc-switch"/);- assert.match(script, /switchBtn\.style\.display = hidden \|\| account\.creditExpired \? 'none' : ''/);+ assert.match(script, /expired \|\| a\.authValid === false \? '' : '<button class="wbs-icon-btn wbs-acc-switch"/);+ assert.match(script, /var invalidAuthBadge = a\.authValid === false/);+ assert.match(script, /switchBtn\.style\.display = hidden \|\| account\.creditExpired \|\| account\.authValid === false \? 'none' : ''/);assert.match(script, /height:5px;min-height:5px/);assert.match(script, /\.wbs-credit-segment:first-child\{border-radius:3px 0 0 3px\}/);assert.match(script, /\.wbs-credit-segment:last-child\{border-radius:0 3px 3px 0\}/);@@ -826,7 +827,7 @@ test('account cards sort by credit expiry without pinning the current account',assert.match(script, /state\.current = data\.current;\s*state\.accounts = mergeAccountSnapshot\(previous, data\.accounts \|\| \[\]\);/);// render():不再把当前账号置顶,统一按积分到期时间升序assert.doesNotMatch(script, /state\.accounts\.sort\(function \(left, right\) \{[\s\S]*left\.uid === state\.current\.uid[\s\S]*right\.uid === state\.current\.uid[\s\S]*return leftIsCurrent \? -1 : 1;[\s\S]*\}\);/);- assert.match(script, /function render\(data\) \{[\s\S]*if \(!previous\.length \|\| !state\.open\) sortAccountsByCreditExpiry\(\);/);+ assert.match(script, /function render\(data\) \{[\s\S]*if \(!previous\.length \|\| !state\.open \|\| currentChanged\) sortAccountsByCreditExpiry\(\);/);// sortAccountsByCreditExpiry:去掉当前账号置顶,仅按到期时间 + 稳定序assert.match(script, /function sortAccountsByCreditExpiry\(\) \{[\s\S]*isCurrent:[\s\S]*a\.expiresAt !== b\.expiresAt[\s\S]*a\.expiresAt - b\.expiresAt[\s\S]*a\.index - b\.index/);assert.doesNotMatch(script, /function sortAccountsByCreditExpiry\(\) \{[\s\S]*if \(a\.isCurrent !== b\.isCurrent\) return a\.isCurrent \? -1 : 1;/);@@ -857,9 +858,8 @@ test('robot button decorations remain visible alongside the eye states', () => {const script = read('inject.js');assert.match(script, /wbs-fab-antenna/);assert.doesNotMatch(script, /wbs-fab-ear/); // 用户 08-30 00:37 要求去掉双耳- assert.match(script, /\.wbs-fab-antenna\{[^}]*background:rgba\(20,20,22,\.55\)[^}]*mask-image:url\("data:image\/svg\+xml/);- assert.match(script, /\.wbs-fab-antenna-dot\{[^}]*background:transparent/);- assert.match(script, /viewBox=\\'0 0 14 24\\'>/);+ assert.match(script, /\.wbs-fab-antenna\{[^}]*background:var\(--wbs-robot-shell\)/);+ assert.match(script, /\.wbs-fab-antenna-dot\{[^}]*background:var\(--wbs-robot-shell\)/);assert.match(script, /#wbs-fab-sleep-light\.sleep-on\{background:rgba\(46,229,157,\.85\)/);assert.match(script, /\.wbs-fab \.click > span:not\(\.wbs-fab-antenna\)\{display:none\}/);assert.doesNotMatch(script, /\.wbs-fab \.click span\{display:none\}/);@@ -1087,6 +1087,8 @@ test('account export asks for a non-empty password and import supports an optionassert.match(secureTransfer, /randomBytes\(16\)/);assert.match(daemon, /version:\s*2/);assert.match(daemon, /EXPORT_PASSPHRASE/);+ assert.match(daemon, /const authRecord = parseAuthJson\(j\)/);+ assert.match(daemon, /if \(!authRecord \|\| authRecord\.uid !== uid\) continue/);assert.match(inject, /title:\s*'导出账号'[\s\S]*requirePassword:\s*true/);assert.match(inject, /旧版导出文件可留空/);assert.match(inject, /type="password"/);diff --git a/test/usage-activity.test.js b/test/usage-activity.test.jsnew file mode 100644index 0000000..c443645--- /dev/null+++ b/test/usage-activity.test.js@@ -0,0 +1,45 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { createUsageActivity } = require('../scripts/inject.js');++test('foreground activity is throttled, rolls over at Beijing midnight and cleans up', () => {+ const listeners = new Map();+ const doc = { visibilityState: 'visible', hasFocus: () => true,+ addEventListener: (name, fn) => listeners.set(name, fn),+ removeEventListener: name => listeners.delete(name) };+ let time = Date.parse('2026-09-10T15:59:00Z'), enabled = true, calls = 0;+ const activity = createUsageActivity({ document: doc, window: doc, now: () => time,+ enabled: () => enabled, send: (...args) => { assert.equal(args.length, 0); calls++; } });+ assert.equal(calls, 1);+ listeners.get('keydown')({ isTrusted: true, key: 'private' });+ assert.equal(calls, 1);+ time += 60000;+ listeners.get('keydown')({ isTrusted: false });+ assert.equal(calls, 1);+ listeners.get('keydown')({ isTrusted: true });+ assert.equal(calls, 2);+ time += 3600000;+ doc.visibilityState = 'hidden'; activity.notify();+ doc.visibilityState = 'visible'; doc.hasFocus = () => false; activity.notify();+ doc.hasFocus = () => true; enabled = false; activity.notify();+ assert.equal(calls, 2);+ enabled = true; activity.notify();+ assert.equal(calls, 3);+ activity.destroy();+ assert.equal(listeners.size, 0);+ time += 3600000; activity.notify();+ assert.equal(calls, 3);+});++test('usage route retains local authorization and About describes anonymous counts', () => {+ const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');+ const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');+ const publicPaths = daemon.match(/const PUBLIC_API_PATHS = new Set\(([\s\S]*?)\);/);+ assert.ok(publicPaths);+ assert.doesNotMatch(publicPaths[1], /\/api\/usage/);+ assert.match(inject, /registerDisposer\(function \(\) \{ usageActivity.destroy\(\); \}\)/);+ assert.match(inject, /匿名安装数和日活/);+});diff --git a/test/usage-report.test.js b/test/usage-report.test.jsnew file mode 100644index 0000000..95fdeec--- /dev/null+++ b/test/usage-report.test.js@@ -0,0 +1,95 @@+'use strict';+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { createUsageReporter, usageDay } = require('../scripts/usage-report.js');++function fixture(t, extra = {}) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-usage-test-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ let time = Date.parse('2026-09-10T04:00:00Z'), enabled = true;+ const calls = [];+ const options = { dataDir: dir, profile: 'workbuddy-cn', version: '1.2.9',+ now: () => time, enabled: () => enabled,+ installationId: () => '11111111-1111-4111-8111-111111111111',+ send: async (body) => { calls.push(body); return { status: 204 }; }, ...extra };+ return { options, calls, reporter: createUsageReporter(options),+ advance: (ms) => { time += ms; }, disable: () => { enabled = false; } };+}++test('usage uses Beijing day and survives restart without duplicate reports', async t => {+ assert.equal(usageDay(Date.parse('2026-09-10T16:00:00Z')), '2026-09-11');+ const f = fixture(t);+ await Promise.all([f.reporter.report(), f.reporter.report()]);+ await createUsageReporter(f.options).report();+ assert.equal(f.calls.length, 1);+ f.advance(86400000);+ await f.reporter.report();+ assert.equal(f.calls.length, 2);+ assert.deepEqual(Object.keys(f.calls[0]).sort(), ['arch', 'installationId', 'osRelease', 'platform', 'profile', 'version']);+});++test('disabled telemetry and missing persistent identity never send', async t => {+ const f = fixture(t); f.disable();+ await f.reporter.report();+ assert.equal(f.calls.length, 0);+ const missing = fixture(t, { installationId: () => null });+ await missing.reporter.report();+ assert.equal(missing.calls.length, 0);+});++test('failed reports back off across restart and stop after three daily attempts', async t => {+ let count = 0;+ const f = fixture(t, { send: async () => { count++; throw new Error('offline'); } });+ for (let i = 0; i < 8; i++) {+ await createUsageReporter(f.options).report();+ await f.reporter.report();+ f.advance(2 * 3600000);+ }+ assert.equal(count, 3);+});++test('only exact collector acknowledgement is success; static Pages 200 is not', async t => {+ let count = 0;+ const f = fixture(t, { send: async () => ({ status: ++count === 1 ? 200 : 204 }) });+ await f.reporter.report();+ f.advance(6 * 3600000);+ await f.reporter.report();+ await createUsageReporter(f.options).report();+ assert.equal(count, 2);+});++test('corrupt state fails closed instead of generating unbounded requests', async t => {+ const f = fixture(t);+ fs.writeFileSync(path.join(f.options.dataDir, 'usage-state.json'), '{broken');+ await f.reporter.report();+ assert.equal(f.calls.length, 0);+});++test('separate profile reporters share the daily lock and a crashed lock recovers', async t => {+ const f = fixture(t);+ const ai = createUsageReporter({ ...f.options, profile: 'workbuddy-ai' });+ const lock = path.join(f.options.dataDir, '.usage-report.lock');+ fs.mkdirSync(lock);+ await ai.report();+ assert.equal(f.calls.length, 0);+ const stale = new Date(Date.now() - 120000);+ fs.utimesSync(lock, stale, stale);+ await Promise.all([f.reporter.report(), ai.report()]);+ assert.equal(f.calls.length, 1);+ assert.equal(fs.existsSync(lock), false);+});++test('disabling telemetry can abort the pending request and release its lock', async t => {+ let aborted = false;+ const f = fixture(t, { send: (_body, signal) => new Promise(resolve => {+ signal.addEventListener('abort', () => { aborted = true; resolve({ status: 0 }); });+ }) });+ const pending = f.reporter.report();+ f.disable(); f.reporter.cancel();+ await pending;+ assert.equal(aborted, true);+ assert.equal(fs.existsSync(path.join(f.options.dataDir, '.usage-report.lock')), false);+});diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.jsindex 70aa035..39a4582 100644--- a/test/windows-native-flow.test.js+++ b/test/windows-native-flow.test.js@@ -207,6 +207,22 @@ test('native lifecycle cleanup accepts a PID that exits during exact inspection'assert.match(source.slice(exitedCheck, mismatch), /waitResult == waitObject0[\s\S]*return false, 0, nil/);});+test('native lifecycle cleanup clears an access-denied PID that is absent from the process snapshot', () => {+ const source = read('scripts/windows-native/main.go');+ const inspectStart = source.indexOf('func inspectExactProcess(');+ const inspectEnd = source.indexOf('\nfunc terminateExactProcess(', inspectStart);+ assert.ok(inspectStart >= 0 && inspectEnd > inspectStart);+ const inspect = source.slice(inspectStart, inspectEnd);+ const denied = inspect.indexOf('errors.Is(err, syscall.ERROR_ACCESS_DENIED)');+ const snapshot = inspect.indexOf('enumerateProcesses()', denied);+ const absent = inspect.indexOf('if !present', snapshot);+ const deniedResult = inspect.indexOf('return false, exitAccessDenied', absent);+ assert.ok(denied >= 0, 'access-denied inspection must stay fail-closed');+ assert.ok(snapshot > denied, 'access-denied inspection must refresh the process snapshot');+ assert.ok(absent > snapshot && deniedResult > absent, 'only a PID absent from the snapshot may be treated as stale');+ assert.match(inspect.slice(snapshot, deniedResult), /record\.PID == uint32\(pid\)[\s\S]*if !present[\s\S]*return false, 0, nil/);+});+test('elevated lifecycle cleanup inspects exact state before refusing active termination', () => {const source = read('scripts/windows-native/main.go');const stopStart = source.indexOf('func stopLifecycle(');