Skip to content

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

feat: 合并 1.2.2 账号、主题、会话与兼容性更新

[email protected]8fbd63b9dc5d
diff --git a/AGENTS.md b/AGENTS.md
index f874dcb..100acd2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -24,7 +24,7 @@ The repository is deliberately lightweight:
6. When changing daemon behavior, increment `DAEMON_VERSION` and `DAEMON_BUILD_ID` in `scripts/daemon.js`. Launchers use these values to replace stale daemon processes that still have old code in memory.
7. Diagnostic telemetry defaults to enabled. The About-page 「发送错误诊断」 switch controls both remote Sentry events and local redacted renderer diagnostics; `WORKDADDY_TELEMETRY=0/1` is an explicit startup override. Do not restore the removed `WORKDADDY_DIAGNOSTIC_LOGS` or composer-capture interfaces.
8. The only telemetry override that may bypass the About-page switch is a user-initiated repair-agent run that has read `安装失败自主解决提示词.txt` and uses `--force-send --require-sent`. That report must remain redacted, and only `sent=true` is success; `queued=true` or a non-zero exit must never be presented as sent.
-9. WorkDaddy and WorkBuddy lifecycle control must run at standard user privilege. If WorkBuddy is elevated, launcher operations must fail closed with manual guidance; never reintroduce UAC helpers, broad image-name kills, or cross-integrity process termination.
+9. WorkDaddy and WorkBuddy lifecycle control defaults to standard user privilege. The only elevated-session exception requires a verified same-user elevated desktop with no linked standard token and explicit installer risk consent, persisted per user, profile, and installation directory. Recheck desktop eligibility on every elevated entry; silent installs may only reuse existing consent. Outside this exception, fail closed with manual guidance. Never reintroduce UAC helpers, broad image-name kills, or cross-user/session/integrity process termination. Native daemon status must report the actual verified privilege, never infer standard privilege from the native-launcher environment flag.
## UI Direction (Highest Priority)
diff --git a/README.md b/README.md
index 3391c48..c1e07a0 100644
--- a/README.md
+++ b/README.md
@@ -30,7 +30,7 @@
- **方便切换账号**:每个 WorkBuddy 账号独立备份,点一下就切,再也不用每次扫码。
- **无感登录新账号**:「登录新账号」支持免退出 OAuth 授权——不退出 WorkBuddy,在浏览器完成扫码后新账号自动加入列表;也可选传统的「假退出」方式回登录页扫码。
- **账号导入导出**:把全部账号备份加密导出,在另一台电脑安装 WorkDaddy 后一键导入,方便电脑之间迁移账号。
-- **自动领每日积分**:由自动化任务管理多账号每日签到,缓存已完成状态,不打断你。
+- **自动领每日积分**:由自动化任务管理多账号每日签到,默认停用。首次打开面板会提示账号风险,选择开启后启用任务;开启或取消的选择保存在本机,之后不再提醒,可随时在「自动化」中手动启停。
- **Token 和积分用量统计页面**:按天查看 Token 与积分消耗,支持按账号筛选,并显示模型和账号用量排行。
- **积分不足时的账号切换建议**:当前账号积分不足时提示可用账号,方便继续工作。
- **自动化任务**:用自然语言让 WorkBuddy 创建任务,或自行编辑步骤;支持手动、事件和定时触发,以及运行日志、停止任务和 JSON / ZIP 导入导出。
diff --git a/README_en.md b/README_en.md
index 7df0d03..18c9824 100644
--- a/README_en.md
+++ b/README_en.md
@@ -30,7 +30,7 @@ It injects UI components into the running WorkBuddy renderer without patching or
- **Fast account switching:** each WorkBuddy account has a separate backup, so you can switch without scanning a QR code every time.
- **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.
+- **Daily credits:** daily check-in automation is disabled by default. On the first panel opening, a risk notice lets you enable the task or cancel. Either choice is saved locally and dismisses future notices; you can later enable or disable the task under Automations.
- **Token and credit usage pages:** review daily token and credit consumption, filter by account, and view usage rankings by model and account.
- **Credit-aware account suggestions:** when an account is running low on credits, WorkDaddy suggests another account you can use.
- **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.
diff --git a/docs/1.2.2-account-session-changes.md b/docs/1.2.2-account-session-changes.md
new file mode 100644
index 0000000..988e2cc
--- /dev/null
+++ b/docs/1.2.2-account-session-changes.md
@@ -0,0 +1,66 @@
+# 1.2.2 分支:账号设置与会话产物兼容
+
+本分支按用户确认基于当前 main,daemon 从 1.2.36 递增到 1.2.39;分支名为 codex/1.2.2。未制作发行包。
+
+## 账号和主题
+
+- 保留历史 `default` 配置键,显示为「浅色」;新增 `dark` 显示为「深色」。两者同步 WorkBuddy 原生外观存储及根属性,移除自定义色板/壁纸,并保留重载恢复和单一主题 observer。
+- 账号页移除主账号设置按钮及徽标;既有自动化后台接口保留兼容。
+- 签到分别显示高亮的「今日已签到」和灰色的「今日未签到」,AI 客户端仍不显示国内签到功能。
+- 账号排序模式存于各 profile 的 `meta.json.accountOrderMode`,固定顺序存于 `accounts[uid].sort`。正整数升序,缺省/0 在最后;删除账号沿用原有元数据清理。拖拽或方向键调整后点击保存;取消不写入。
+- 总积分旁新增汇总图标,悬浮/聚焦展示按每个积分段的剩余天数聚合的条形图。剩余天数按 24 小时向上取整,已到期单列,未知有效期不展示;读取失败、登录过期和不限量账号不伪造余额,另显示数量。
+
+## 面板细节与头像
+
+- 汇总进度条与账号积分段共用浅色/深色颜色规则,透明度按剩余天数线性计算:≤1 天为 0.05,≥30 天为 1,中间为 0.05 + 0.95 × (天数 − 1) / 29。
+- 账号排序入口改为排序 SVG 图标;弹窗在插件面板内居中,固定列表显示明文账号,移除说明段落和序号,保留拖拽/键盘调整。
+- 主题按钮改用 `data-wbs-theme-option`,避免官方 `[data-theme="dark"]` 规则把单个按钮变为深色区域;悬浮机器人选项复用主题分段按钮样式。
+- 头像提供 WorkBuddy、WorkDaddy 预设,保留上传及旧自定义头像缓存,移除恢复默认按钮。用户提供的 WorkDaddy SVG 原样存于 `scripts/assets/workdaddy-app-icon-source.svg`。
+- 隔离 renderer 验证了汇总条与账号条计算颜色一致、主题/机器人分段样式一致、明文排序及面板居中、390px 布局、头像图片加载与重新注入后保留选择。
+
+## 删除目录兼容
+
+旧实现从配置的数据根开始逐级 lstat,根目录自身是 Windows junction 或目录符号链接时也会拒绝。删除边界先 realpath 配置根,再沿真实根逐级检查 managed parent;内部目录链接仍然拒绝,叶子链接只删除链接本身。会话 ID 校验和先文件后数据库的删除次序保持不变。
+
+回归覆盖真实目录链接作为配置根、内部链接拒绝、同源副本级联删除及缓存写入失败。此处在 macOS 用目录符号链接验证了同类失败,不代表已在用户 Windows junction 上实测。
+
+## 产物复制原因与修复
+
+只读检查本机 WorkBuddy.app 的官方代码发现:`main/conversations.js` 的 `ConversationImpl.filterArtifactsOwnedByConversation` 对工作目录外的 PresentFiles 产物要求 `_meta.ownerConversationId` 匹配当前会话。原先复制 `artifact-index/<id>.json` 只改文件名,内部 owner 仍为原会话,因此切号副本中的文件被官方过滤。
+
+复制时只把源会话或已记录同源 lineage 的 owner 改为目标 ID,保留 requestId、URI 和其他会话的 owner。已有副本作为最新来源时也修复自身旧 owner。读取失败或格式错误不覆盖目标,不在错误中输出索引正文;就地修复发现官方并发写入时保留新数据。
+
+同时保留所有复制载荷的原始文件时间。`selectLatestAutoCopyMember` 使用内容 mtime,原先复制动作会制造较新的 mtime,可能把旧副本选为下一轮同步来源。
+
+没有改变官方会话 RPC、打开顺序、官方安装文件或普通账号切换的 JSON 替换 + CDP reload 流程。
+
+## 验证范围
+
+使用临时目录和合成产物索引覆盖复制、归属恢复、原文件保留、往返同步、旧 lineage 修复和时间戳。UI 在可连接的 WorkBuddy renderer 中以隔离 iframe 注入完整脚本、复用官方 CSS、模拟账号/API/存储,检查浅色/深色、390px 窄视口、拖拽事件、键盘排序、焦点约束、保存/取消及重复注入清理;退出后移除验证 iframe。
+
+此前仅使用合成数据验证;2026-09-14 补充了下述 macOS 真实账号 CDP 往返验证。真实 Windows 删除和 Windows 账号切换仍需对应环境验收。
+
+最终检查:732 项测试中 724 通过、8 跳过、0 失败;daemon、inject、lib、win-launcher、watchdog 的 Node 语法检查通过。本次 scripts/test 改动的 diff 检查通过。工作期间 README.md 和 README_en.md 出现了其他并行修改,未改动这些内容;完整工作区 diff 检查报告 README.md:60 存在行尾空格。
+
+## 本机同步
+
+已同步 `/Applications/WorkDaddy.app/Contents/Resources/scripts/daemon.js`、`inject.js`、`assets/workdaddy-app-icon-source.svg`;`lib.js` 与源码已一致。Info.plist 两个版本字段均为 1.2.38。通过当前用户的 `com.workbuddy.workdaddy.workbuddy-cn` launchd 服务重载 daemon,状态返回 1.2.38,CDP 已连接,重新注入返回 `ok=true, mounted=true`。WorkBuddy 未由本次操作重启。实际面板检查确认浅色下深色选项为黑色文字、排序 SVG 已存在、两个头像图像均加载成功、恢复默认按钮已移除,只有一个插件根节点。
+
+## 1.2.39 界面修正
+
+用量统计原先读取机器人外观并添加 `wbs-token-stats-glass`,导致浅色 + 毛玻璃机器人时背景变为白色 68% 不透明。解除这个关联,统计弹窗只使用主题的 popover 背景;隔离 renderer 中验证浅色/深色 × 白色/黑色/毛玻璃机器人六种组合以及加载遮罩正常收起。
+
+头像列表与当前选择统一原子保存于 `wbsAvatarLibrary`,旧 `wbsAvatar` 上传图片首次修改时迁移。切换预设保留自定义图片;42px 加号按钮每次上传新增并选中;自定义头像悬浮或键盘聚焦出现删除按钮,删除后选中 WorkDaddy。存储失败保留原列表和选择。已验证两次真实 FileReader/图片转换上传、切换预设、重新注入保留、删除及存储失败。机器人选项只在键盘导航时展示中性色焦点提示,鼠标点击不出现蓝色框。
+
+1.2.39 已同步安装目录的 `daemon.js` 和 `inject.js`,Info.plist 两个版本同步更新。logo SVG 和 lib.js 与源码一致。仅重载当前用户的 WorkDaddy CN daemon 并重新注入,WorkBuddy 未重启。
+
+## 2026-09-14:真实账号 CDP 产物列表验证
+
+运行安装版 1.2.39,选取已开启自动复制、官方产物面板可见 2 项 PresentFiles 产物的真实会话(产物路径位于工作目录外)。通过 CDP 读取官方 `.cb-overview-artifact-item__title`,使用名称指纹比对;只记录数量和一致性,不在报告中保留账号身份、会话标题、文件名或内容。通过正常 `/api/switch` 的 JSON 替换 + CDP reload 流程完成账号 A → B → A;每次等待自动复制任务完成后,通过官方侧栏打开同一 lineage 的会话。
+
+- 切换前:2 项可见产物,索引 2 项 owner 均匹配源会话。
+- 切到 B:2 项可见产物,名称与切换前完全一致;索引 2 项 owner 均匹配目标副本,URI 未变化。
+- 切回 A:仍为 2 项,名称、URI 与切换前一致,owner 匹配原会话。
+- 两次自动复制任务都处理 110 个会话,均 partial=0、failed=0。验证后已恢复最初账号及最初打开的会话。
+
+结论:本次 macOS 实际账号往返抽查通过,产物列表没有在切号后消失。本次核验针对产物列表显示与索引归属,未打开或修改产物文件,未触发生成新内容,未重启 WorkBuddy。
diff --git a/docs/release-1.2.2-integration.md b/docs/release-1.2.2-integration.md
new file mode 100644
index 0000000..e01cdd5
--- /dev/null
+++ b/docs/release-1.2.2-integration.md
@@ -0,0 +1,42 @@
+# 1.2.2 集成与打包记录
+
+当前分支:`codex/1.2.2`。
+
+## 合并来源
+
+- `codex/windows-elevated-consent`:`04d0bee`,管理员桌面兼容模式的显式同意及逐次身份核验。
+- `codex/fix-import-token-double-count`:`9413b2f`,导入/复制会话的 Token 去重及真实客户端验证记录。
+- `codex/checkin-risk-consent`:`051dc14`,自动签到默认关闭、首次选择后持久化。
+
+三个分支均以 merge commit 合入;冲突仅发生在 daemon 版本与 build id。合并与头像打包修复此前已推送至 `4e38054`。本次后续修复的源码运行版本为 1.2.42,build id 为 `release-1.2.42-20260914-streaming-session-transfer`。按用户要求用 `WORKDADDY_BUILD_VERSION=1.2.2` 构建发行包,构建脚本把 staged daemon 与 app 元数据统一写为 1.2.2。修改均在 `codex/1.2.2` 分支进行,没有修改 main。
+
+另修复 macOS 打包脚本遗漏 `assets/workdaddy-app-icon-source.svg` 的问题,增加根据 `buildInjectScript()` 实际 SVG 依赖核对打包列表的回归测试。
+
+## 本轮修复
+
+- 匿名安装数/日活不再受错误诊断开关或 `WORKDADDY_TELEMETRY` 限制;错误诊断本身继续受控。前后端门控和关闭诊断时的请求取消均移除,仍保留持久标识、每日去重、失败退避及 CN/AI 共用配额。
+- 首次确认开启自动签到后,立即启动内置签到任务;重复选择不重跑,已运行的任务复用。缓存跳过结果及整个任务结束都通知面板更新标签,确认后也主动刷新。
+- 提示文案改为「开启后自动为已保存账号签到。请留意官方规则,自动操作可能影响账号使用。可随时在『自动化』中关闭。」
+- 移除会话附件 256 MiB 大小上限;改用 `.wds` 流式压缩加密、Blob 下载上传和先认证后恢复的导入链路,继续兼容旧 `.json` 导入。格式与约束见 `docs/session-transfer.md`。
+
+## 验证
+
+- 全套 Node 测试:769 项,761 通过、8 跳过、0 失败。
+- daemon、inject、usage-report、session-transfer、win-launcher、watchdog 的语法检查与 macOS 构建脚本语法检查通过。
+- 上轮 Windows/amd64 原生启动器交叉编译通过;本轮没有 Windows 运行环境,这不代表 Windows 安装/权限或大文件场景已实测。
+- scripts/test/docs 的 diff 检查通过。用户先前的两个 README 工作区修改未改动;README.md 的既有行尾空格不在本轮修改范围。
+- 257 MiB 单附件导出/导入及 SHA-256 对比通过,在 96 MiB JavaScript 堆限制下也通过。真实 HTTP 路由往返、密码错误不写库、原归属及目标账号覆盖、空文件、路径穿越/重复/损坏拒绝、旧 JSON 兼容均通过。
+- 本机 CDP 端口不可连接,未完成本轮实际面板签到和文件选择/下载交互验证;未因此重启 WorkBuddy。
+
+## macOS 产物
+
+两个 DMG 均通过 hdiutil 校验并只读挂载检查:daemon 版本、build id、Info.plist 两个版本字段、profile/品牌、可执行 launcher、Applications 链接、Finder 布局、新 SVG、签到默认关闭、安装/更新脚本均正确;包内没有 `安装失败自主解决提示词.txt`。daemon 除版本重写外与源码一致,必需模块与源码逐字节一致。包内 build id 为 `release-1.2.2-20260914-streaming-session-transfer`。
+
+按 `scripts/build-mac-dmg.sh` 完整清单同步源码;本轮变更的运行文件为 `scripts/daemon.js`、`scripts/inject.js`、`scripts/usage-report.js` 和新增 `scripts/session-transfer.js`,两个 DMG 均包含这四项。另更新了 Windows 自检清单 `scripts/verify-win.cmd`,Windows 构建时会随 scripts 整体复制。没有同步到 `/Applications/WorkDaddy.app`,没有重启运行中的 daemon 或 WorkBuddy。
+
+- `WorkDaddy-1.2.2.dmg`:profile `workbuddy-cn`,版本 `1.2.2`,SHA-256 `25af5f60018965a85735d7de894b21f8f2570655f54a43a892fafcc11f24b7c9`。
+- `WorkDaddy-AI-1.2.2.dmg`:profile `workbuddy-ai`,版本 `1.2.2`,SHA-256 `324f91bca51ef90b60e1e71b5b91d144650cbb1f63180d690ae4d33077942949`。
+
+## Windows 状态
+
+`win-admin`(192.168.101.9:22)多次 SSH 连接超时,已请求用户恢复构建机连接。本次尚未生成 Windows 1.2.2 Setup.exe;未将历史安装包重命名交付。两个 Windows 安装器的实际 payload、普通/管理员安装以及 CN/AI 同时运行验证仍待 Windows 构建环境恢复后完成。
diff --git a/docs/session-transfer.md b/docs/session-transfer.md
new file mode 100644
index 0000000..0bf3e00
--- /dev/null
+++ b/docs/session-transfer.md
@@ -0,0 +1,23 @@
+# 会话大附件导入导出
+
+会话导出曾在 `collectSessionArchiveFiles()` 和导入恢复处限制每个会话的附件总量为 256 MiB。旧链路同步读取所有附件并转为 Base64,再整体 JSON 序列化、gzip、加密以及前端文本下载,内存占用明显高于原文件大小。仅删除判断会暴露 V8 字符串长度和内存上限。
+
+当前会话导出使用 `.wds` v4 流式归档,不设置附件单文件或总字节数上限。磁盘可用空间、文件系统和浏览器下载能力仍是实际约束;单次会话数 100、每会话文件数 20000 及元数据校验继续保留。
+
+## 格式与传输
+
+- 52 字节头:8 字节 `WDS4\r\n\x1a\n`、16 字节随机 salt、12 字节随机 IV、16 字节 GCM 标签。scrypt 派生 AES-256-GCM 密钥,头部前 36 字节作为 AAD。
+- 加密内容是 gzip 流,内部用 4 字节大端长度加 JSON 元数据帧描述归档、会话和文件。文件帧后紧跟声明长度的原始字节,没有附件 Base64 或整体 JSON 字符串。单个元数据帧最多 1 MiB。
+- `/api/sessions/export` 保持路径不变,返回二进制响应;先在私有临时目录完成加密再下载,避免将未完成归档当作成功。面板使用 Blob 下载。
+- `/api/sessions/import` 的二进制请求先携带长度前缀 JSON(密码和可选目标账号),随后是原始归档。面板直接上传 File/Blob;密码不放进 URL 或日志。原有 API Token 和 Origin 校验不变。
+- 导入先流式解密到私有临时压缩文件,完整验证 GCM 标签后再解压。解压附件写到内部生成的数字文件名;受管路径映射、重复路径及元数据校验通过后复制到新会话 ID,并写入数据库。外部 JSON 不能提供可信暂存文件路径。
+- 失败时清理暂存目录;下载完成或中断后也清理导出目录。普通导入继续保留账号归属,指定目标账号时覆盖归属,不刷新或重启 WorkBuddy。
+- 旧 v2/v3 `.json` 加密导出继续支持导入;旧格式仍走原来的内存解析路径。新 `.wds` 需要带本次修复的 WorkDaddy 才能导入。
+
+## 验证
+
+`test/session-transfer.test.js` 覆盖 257 MiB 单附件往返与 SHA-256 一致性、错误密码/篡改/截断、源文件大小变化、分段上传、空文件与多会话、路径穿越/重复/超大元数据拒绝,以及真实 HTTP 导出/导入路由和账号归属。
+
+257 MiB 用例已在 `node --max-old-space-size=96` 下通过;这是 JavaScript 堆限制验证,不代表进程总内存只有 96 MiB。旧加密格式及历史 Token 去重回归测试仍通过。
+
+本机 WorkBuddy 的 CDP 端口不可用,未验证实际客户端中的下载/文件选择交互;Windows 构建机不可连接,Windows 文件读写及安装包运行验证未执行。
diff --git a/docs/token-statistics-import-dedup.md b/docs/token-statistics-import-dedup.md
new file mode 100644
index 0000000..d564814
--- /dev/null
+++ b/docs/token-statistics-import-dedup.md
@@ -0,0 +1,46 @@
+# 会话导入后的 Token 重复统计修复
+
+基于 `main` 的 `ad95beb`,分支 `codex/fix-import-token-double-count`。
+
+## 问题与修复范围
+
+导入会话会分配新 ID,跨账号复制也会生成消息文件副本。原统计按文件累加历史 usage,导致没有新模型请求也会增加输入、输出、缓存读写和调用次数。旧的逐文件日汇总缓存已丢失记录身份,不能在汇总后可靠去重。
+
+修复仅改变 `scripts/token-stats.js` 的扫描、缓存和归属解析;`scripts/daemon.js` 的版本从 main 的 1.2.36 升到 1.2.37,并更新 build ID,使启动器能替换旧进程。没有修改会话文件、导入/复制流程、账户切换、积分账单接口或 UI。
+
+## 统计规则
+
+- 对解析后的完整 JSON 记录计算 SHA-256。副本中相同历史记录跨文件只统计一次,不仅按请求 ID 或 Token 数值去重,因此一个请求的不同记录、相同用量的不同调用仍分别计数。
+- 相同记录在一个文件中出现多次时保留出现次数;其他文件的对应出现位置视为副本。这个规则针对当前导入/复制保留原消息内容的行为,不改变单文件内部的统计口径。
+- 副本新增的消息单独计数。先跨文件去重,再应用账号、模型和日期筛选。
+- 账号优先使用消息内明确的账号,其次使用原始 `sessionId` / `conversationId` 对应的账号。没有原始会话字段时保留文件归属回退;若同一记录的副本归属冲突,则只计入总量,不猜测归属。原始会话字段存在但该会话的归属已不可查时,也不把历史用量算到副本持有账号。
+- 缓存版本升为 8,旧版本自动全量重建。按文件保存摘要和用量元数据,未变更文件不会因切换筛选条件而重新读取;账号归属使用最新映射,不固化在旧缓存中。缓存和 API 结果不包含消息正文或原始请求/消息 ID。
+- 删除或更新副本后按现存文件重新合并;不保留已经没有任何文件承载的用量。没有时间戳的旧记录仍采用扫描时间回退,但重复导入优先保留较早的缓存观测日期。
+
+## 验证(2026-09-14)
+
+- 先写测试再修复:最初 8 项新增测试在 main 上有 7 项失败;修复后增加 AI 格式和无时间戳记录场景,共 10 项新增测试通过。原有 9 项 Token 测试全部通过。
+- 导入集成测试执行真实加密解包、附件恢复、SQL 构造和复制函数,仅将数据库执行替换为内存账号映射。连续导入三次再跨账号复制,原本 100 个输入 Token 始终为 100;所有导入文件和原文件逐字节一致。
+- 验证继续聊天、同请求多条记录、相同用量的不同调用、旧格式、删除副本、缓存重建、账号映射变化、快照与 subagents 排除、今天及 7/30/90 天、模型与账号筛选。
+- 用 12,000 条无副本的虚构调用做 24 组新旧差分比较,冷扫描和缓存扫描在 4 个日期范围及账号/模型筛选下结果一致。
+- 同一数据复制成 60,000 行,仍只统计 12,000 次;本机测得冷扫描约 263ms、缓存扫描约 106ms,缓存约 15.8MiB。身份元数据增加了缓存体积;这些数字是一次本机测量,不是所有设备的性能保证。
+- 纯 Git worktree 的全量测试因缺少被 Git 忽略的 `WorkDaddy.app/Contents/MacOS/launcher` 失败;未修改 main 的独立临时检出同样失败。随后在临时目录放入完全相同的修复源码及现有未修改 launcher 作为测试夹具,使用 Node 26.8.1:720 项中 712 通过、0 失败、8 项 Windows 环境相关跳过。
+- `node --check` 覆盖统计模块、daemon、inject、win-launcher、watchdog;`git diff --check` 通过。
+
+上述自动化验证阶段未执行真实 WorkBuddy 导入操作;后续实机验证见下节。Windows 实机安装/更新仍未验证。积分接口未发现由导入导致重复扣款的证据,本修复不修改官方账单。
+
+## macOS 真实客户端验证(2026-09-14)
+
+在正在运行的 `/Applications/WorkBuddy.app` 国内版执行,使用真实 SQLite 会话库、官方数据目录中的专用测试项目、本地 daemon HTTP API 和通过 CDP 操作的实际 WorkDaddy 面板。没有修改官方 app、账号认证或用户聊天内容。WorkBuddy 原进程全程保持运行;开始时发现输入框有未发送内容,因此没有切换其当前官方会话或发送真实模型请求。
+
+1. 原运行 daemon 为 1.2.39。用真实 `/api/sessions/import` 连续导入同一加密测试归档三次;归档只有一条虚构 usage(输入 100、输出 10、缓存读取 80、缓存写入 5)。实际统计面板筛选专用测试模型后显示 **3 次 / 300 / 30 / 240 / 15**,实机复现旧版重复计数。
+2. 暂停国内版原 launchd daemon,使用本 worktree 的完整 daemon 1.2.37 和统计模块接管同一 47832 端口及 9222 CDP。测试 daemon 使用独立临时 WorkDaddy 数据目录,内置自动化预置为关闭、遥测关闭;WorkBuddy 的实际会话库和测试消息文件仍为同一批。
+3. 主动 reinject 后,在实际 Token 面板筛选同一测试模型,显示 **1 次 / 100 / 10 / 80 / 5**。确认由旧缓存切换到修复版本时自动恢复正确值。保留了仅包含虚构统计计数的裁剪截图;没有截取账号、输入框或真实会话内容。
+4. 在实际「会话」面板的文件输入框选择同一加密归档,填写测试密码并点击「导入」。弹窗显示「导入完成:成功 1 个会话」,真实数据库中的测试会话增加到四个,统计仍为 **1 次 / 100 输入 Token**。
+5. 使用真实复制 API 将测试会话复制到另一已有账号,测试会话增加到五个,统计仍为 **1 次 / 100 输入 Token**。没有执行账号登录切换。
+6. 只向这个测试副本的真实 JSONL 文件追加一条虚构的新 usage(输入 20、输出 2、缓存读取 10),验证实际增量扫描:界面显示 **2 次 / 120 / 12 / 90 / 5**;目标账号 API 筛选只计新增的 20 输入 Token。今天、近 7/30/90 天均为 120。这一步模拟新增消息记录,不等同于真实模型生成或发送测试。
+7. 通过真实删除 API 仅删除已记录 ID 且符合专用模型和测试标题的五个会话。只查询测试记录确认数据库剩余数量为零,专用项目文件目录已移除,修复版统计中测试调用为零。
+8. 停止临时 daemon,恢复原 launchd 服务及原 1.2.39 daemon,并重新注入原面板。确认 CDP 连接正常、仅一个面板和一个浮动按钮、WorkBuddy 原 PID 未变、原未发送内容仍存在(只检查非空状态,不读取内容)、原浅色主题恢复;原 daemon 再次扫描后测试调用也为零。AI daemon 未停止。
+9. 删除临时 daemon 产生的账号备份、能力凭证、归档、测试密码状态和日志。日志仅检查 fatal 标记数量(0),未输出完整日志。截图在本机 `/Users/h/.codex/artifacts/workdaddy-token-live-20260914/{before,after}.png`,不纳入安装包。
+
+结论:在真实 macOS 国内版客户端中确认重复导入导致的计数虚高已修复,面板导入、跨账号复制、缓存重建、筛选和测试记录清理没有出现新增异常。未覆盖真实模型续聊、带未发送草稿的账号切换、AI 客户端和 Windows 实机流程;这些不能从此次验证推断为已经通过。
diff --git a/docs/usage-analytics.md b/docs/usage-analytics.md
index 44495ea..72d5e83 100644
--- a/docs/usage-analytics.md
+++ b/docs/usage-analytics.md
@@ -6,11 +6,11 @@
- 同一安装的 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` 的现有优先级不变,无绕过开关的采集选项。关闭开关会取消进行中的请求,但无法撤回已经送达的请求。
+- 匿名安装数和日活独立统计,不受 About 页「发送错误诊断」或 `WORKDADDY_TELEMETRY` 影响;关闭错误诊断不会取消匿名统计请求。错误诊断本身仍遵循原有开关和环境变量优先级,About 页说明同步展示这一区别。
- 每天最多成功一次;失败最少间隔 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/docs/windows-elevated-session-consent.md b/docs/windows-elevated-session-consent.md
new file mode 100644
index 0000000..d29892c
--- /dev/null
+++ b/docs/windows-elevated-session-consent.md
@@ -0,0 +1,36 @@
+# Windows 管理员会话兼容安装
+
+## 原因与行为
+
+旧版 Setup 的“继续管理员安装”只允许复制文件,并跳过进程清理和安装后启动;选择没有保存到启动器。内建 Administrator 或关闭 UAC 的桌面本身也可能是 elevated,快捷方式无法借用普通桌面令牌,最终仍以错误码 5 退出。
+
+新版本仍优先使用普通权限。仅在原生 helper 确认以下条件后,安装器才展示“我已了解风险,继续安装”:当前进程和桌面均为 elevated、桌面 Explorer 路径正确、桌面属于当前用户,且桌面令牌为 TokenElevationTypeDefault(无关联的标准令牌)。手动提权的 Explorer 如果还有关联标准令牌,不适用此例外;检测失败也不适用。
+
+风险说明明确告知:WorkDaddy、由它启动的 WorkBuddy,以及 WorkBuddy 中的命令、插件和自动操作将拥有更高权限,误操作可能影响系统文件和设置。窗口默认聚焦“取消安装”。
+
+## 选择如何生效
+
+- Setup 用自身实际权限运行只读检测 helper;用户明确点击继续后,才保存选择并进入精确进程清理、复制和安装后启动。
+- 同意记录保存在各 profile 数据目录的 `windows-elevated-consent.json`,绑定版本化的同意格式、Windows 用户 SID、profile 和安装目录;不会放进发行包。
+- 原生快捷方式和旧 `launcher.cmd` 入口共用原生 helper 验证。兼容模式下,旧脚本入口转入同一套原生启动流程。
+- 每次 elevated 启动或生命周期操作重新检测桌面,确认记录仍适用。恢复普通权限桌面后,优先恢复普通权限启动。
+- 静默安装只可沿用既有有效记录,不会显示或自动接受风险窗口。首次安装需要用户交互。
+- 后台服务通过原生 helper 检测实际权限;不能再把 `WBSWITCH_NATIVE_LAUNCHER=1` 当成普通权限证明。
+- 结束进程仍保留原有精确路径、PID、profile 和身份检查,并在实际终止句柄上核验用户、Windows 会话和提权状态一致;不请求 UAC、不按进程名批量结束,也不跨用户、会话或权限终止。
+
+可关闭 WorkDaddy 后删除对应同意记录以撤销兼容模式;再次以管理员会话启动时需要重新安装并确认。普通 Windows 上手动“以管理员身份运行”安装器的原有提示仍保留,不会因此自动获得兼容模式许可。
+
+## 验证边界
+
+自动测试覆盖安装确认与各入口的连接、原生权限查询的有效/无效响应、daemon 权限与版本匹配,以及直接编译运行原生同意策略函数的持久化、损坏文件、不同用户、不同 profile、不同安装路径、桌面恢复普通权限等拒绝场景。便携策略测试仅替换 Windows 系统探测,不替换同意判定函数。
+
+Windows/amd64 原生启动器可在 macOS 交叉编译。当前 Windows 测试主机连接超时,尚未完成 Inno Setup 编译、风险窗口视觉检查和真机安装/启动/升级;交叉编译及静态断言不能代替这些检查。
+
+发布前应在隔离的 Windows 测试环境完成:
+
+1. 普通 UAC 桌面:正常安装,以及手动提权启动后降回普通权限;不得出现管理员会话兼容提示。
+2. 内建 Administrator/关闭 UAC 桌面:取消风险窗口后不启动;明确同意后安装、首次启动及再次双击均成功,后台实际报告 elevated。
+3. 同一桌面分别安装 CN 和 AI:授权、数据、快捷方式、端口和进程清理各自独立,两客户端可同时运行。
+4. 已同意的安装运行中升级、旧脚本入口启动、卸载;同时验证外来用户/会话/权限的进程不会被终止。
+5. 无同意记录的静默安装必须停止;有匹配记录的静默更新可以继续。恢复普通桌面后旧记录不得让启动器保留 elevated。
+6. 检查长风险说明在常用 DPI 下完整显示,取消默认聚焦,Esc 可以取消;确认后续真实快捷方式使用本次编译的原生 EXE。
diff --git a/scripts/assets/workdaddy-app-icon-source.svg b/scripts/assets/workdaddy-app-icon-source.svg
new file mode 100644
index 0000000..01cae3f
--- /dev/null
+++ b/scripts/assets/workdaddy-app-icon-source.svg
@@ -0,0 +1,40 @@
+<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>
+ <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>
+</svg>
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index 5b3e2e0..9663237 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -56,12 +56,12 @@ 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 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
+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 session-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 checkin-consent.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/"
+cp scripts/assets/workdaddy-logo.svg scripts/assets/workdaddy-app-icon.svg scripts/assets/workdaddy-app-icon-source.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/"
@@ -95,6 +95,7 @@ chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \
"$APP/Contents/Resources/scripts/token-refresh.js" \
"$APP/Contents/Resources/scripts/workbuddy-target.js" \
"$APP/Contents/Resources/scripts/secure-transfer.js" \
+ "$APP/Contents/Resources/scripts/session-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" \
@@ -104,6 +105,7 @@ chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \
"$APP/Contents/Resources/scripts/atomic-file-write.js" \
"$APP/Contents/Resources/scripts/ui-port.js" \
"$APP/Contents/Resources/scripts/checkin-result.js" \
+ "$APP/Contents/Resources/scripts/checkin-consent.js" \
"$APP/Contents/Resources/scripts/workbuddy-compat.js" \
"$APP/Contents/Resources/scripts/inject.js" \
"$APP/Contents/Resources/scripts/theme-patches.js"
diff --git a/scripts/builtin/automations/daily-account-checkin.json b/scripts/builtin/automations/daily-account-checkin.json
index 9bf4cb4..6f58b21 100644
--- a/scripts/builtin/automations/daily-account-checkin.json
+++ b/scripts/builtin/automations/daily-account-checkin.json
@@ -3,7 +3,7 @@
"id": "daily-account-checkin",
"name": "循环账号静默签到",
"description": "使用各账号 token 签到,不切换当前账号;跳过今日已签到账号。每小时、客户端加载和打开面板时检查。",
- "enabled": true,
+ "enabled": false,
"trigger": {
"type": "clientLoaded",
"types": [
diff --git a/scripts/checkin-consent.js b/scripts/checkin-consent.js
new file mode 100644
index 0000000..dc135c8
--- /dev/null
+++ b/scripts/checkin-consent.js
@@ -0,0 +1,65 @@
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { readAutomations, writeAutomations } = require('./automation');
+const { replaceFileWithRetry } = require('./atomic-file-write');
+const TASK_ID = 'daily-account-checkin';
+const stateFile = dir => path.join(dir, 'checkin-consent.json');
+
+function readState(dir) {
+ try {
+ const value = JSON.parse(fs.readFileSync(stateFile(dir), 'utf8'));
+ return value && value.version === 1 ? value : {};
+ } catch (error) {
+ if (error.code === 'ENOENT' || error instanceof SyntaxError) return {};
+ throw error;
+ }
+}
+function saveState(dir, value) {
+ fs.mkdirSync(dir, { recursive: true });
+ replaceFileWithRetry(stateFile(dir), JSON.stringify({ version: 1, ...value }) + '\n', 0o600);
+}
+
+// Migrate before any startup events or schedules. Only this built-in is affected;
+// later manual task edits remain authoritative, including after cancellation.
+function initializeCheckinConsent(dir) {
+ const state = readState(dir);
+ if (state.initialized === true) return;
+ const tasks = readAutomations(dir);
+ const task = tasks.find(item => item.id === TASK_ID);
+ if (task && task.enabled !== false) {
+ task.enabled = false;
+ writeAutomations(dir, tasks);
+ }
+ saveState(dir, { initialized: true, decision: null });
+}
+
+function readCheckinConsent(dir) {
+ const state = readState(dir);
+ const task = readAutomations(dir).find(item => item.id === TASK_ID);
+ const decided = state.decision === 'enabled' || state.decision === 'cancelled';
+ return { ok: true, shouldPrompt: !!task && !decided, enabled: !!task && task.enabled !== false };
+}
+
+function decideCheckinConsent(dir, enabled) {
+ if (typeof enabled !== 'boolean') throw new Error('Invalid check-in choice');
+ initializeCheckinConsent(dir);
+ const state = readState(dir);
+ // First persisted decision wins, including requests from another renderer.
+ if (state.decision === 'enabled' || state.decision === 'cancelled') return readCheckinConsent(dir);
+ const tasks = readAutomations(dir);
+ const index = tasks.findIndex(item => item.id === TASK_ID);
+ if (enabled && index < 0) throw new Error('Check-in task no longer exists');
+ const next = tasks.map((task, i) => i === index ? { ...task, enabled } : task);
+ if (index >= 0) writeAutomations(dir, next);
+ try {
+ saveState(dir, { initialized: true, decision: enabled ? 'enabled' : 'cancelled', decidedAt: Date.now() });
+ } catch (error) {
+ if (index >= 0) writeAutomations(dir, tasks);
+ throw error;
+ }
+ return readCheckinConsent(dir);
+}
+
+module.exports = { initializeCheckinConsent, readCheckinConsent, decideCheckinConsent };
diff --git a/scripts/daemon.js b/scripts/daemon.js
index d653699..fe75e82 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -32,6 +32,7 @@ const { spawn, spawnSync } = require('child_process');
const {
assertSameProcessIdentity,
detectWindowsPrivilege,
+ detectNativeWindowsPrivilege,
buildNativeProcessQuery,
filterVerifiedWindowsProcesses,
filterVerifiedNodeProcesses,
@@ -42,7 +43,9 @@ const {
selectPreferredDiscoveredBinary,
} = require('./windows-process-boundary.js');
const DAEMON_PRIVILEGE = process.platform === 'win32'
- ? (process.env.WBSWITCH_NATIVE_LAUNCHER === '1' ? 'standard' : detectWindowsPrivilege())
+ ? (process.env.WBSWITCH_NATIVE_LAUNCHER === '1'
+ ? detectNativeWindowsPrivilege(path.resolve(__dirname, '..'), process.env.WBSWITCH_PROFILE || 'workbuddy-cn')
+ : detectWindowsPrivilege())
: 'standard';
// ws(WebSocketServer)用于 DevTools 代理:Electron 的 CDP server 拒绝带 Origin 的 WS 连接
// (浏览器必带 Origin → DevTools 前端 "websocket disconnected"),daemon 代理中转去掉 Origin
@@ -112,6 +115,8 @@ const {
enableModelBackup,
importModels,
checkinDisplayValue,
+ getAccountOrder,
+ setAccountOrder,
} = require('./lib.js');
const { createThirdPartyImport } = require('./third-party-models.js');
const { extractCreditSegments, sortCreditSegments, mergeCreditSegments, parseEnterpriseUsage, ENTERPRISE_EDITIONS } = require('./credit-segments.js');
@@ -120,6 +125,7 @@ const { fetchUsageSinceAnchor, startOfLocalDay } = require('./credit-request-usa
const { createCreditHistorySync, historyRange } = require('./credit-history-sync.js');
const { createCreditUsageStore } = require('./credit-usage-store.js');
const { scanTokenStatsCached, tokenStatsCacheReady } = require('./token-stats.js');
+const { initializeCheckinConsent, readCheckinConsent, decideCheckinConsent } = require('./checkin-consent.js');
const { classifyCheckinResult, checkinEndpointsForToken } = require('./checkin-result.js');
const {
DAY_MS: TOKEN_REFRESH_DAY_MS,
@@ -147,6 +153,8 @@ const {
requiredPassword,
resolveArchiveTarget,
} = require('./secure-transfer.js');
+const { writeSessionTransfer, readSessionTransfer, receiveSessionUpload } = require('./session-transfer.js');
+const { pipeline: transferPipeline } = require('node:stream/promises');
const { replaceFileWithRetry } = require('./atomic-file-write.js');
const { parseUiPortState, profileUiPortCandidates } = require('./ui-port.js');
const {
@@ -346,8 +354,8 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 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 DAEMON_VERSION = '1.2.42';
+const DAEMON_BUILD_ID = 'release-1.2.42-20260914-streaming-session-transfer';
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';
@@ -3086,7 +3094,7 @@ function startAutomationRun(task, event = null) {
if (!account || !account.uid) throw new Error('没有可用账号');
const result = await claimDailyForUid(account.uid);
appendRunLog('account:checkin:' + (result.skipped ? 'skipped' : result.ok ? 'success' : 'failed'));
- if (result.ok && !result.skipped && cdp.connected) cdpSend('Runtime.evaluate', { expression: "window.dispatchEvent(new CustomEvent('workdaddy:accounts-updated'))" }).catch(() => {});
+ if (cdp.connected) cdpSend('Runtime.evaluate', { expression: "window.dispatchEvent(new CustomEvent('workdaddy:accounts-updated'))" }).catch(() => {});
return result;
}, httpRequest: automationHttpRequest, domAction: (op, locator, detail) => ['dom.click','dom.type','dom.clear','dom.press'].includes(op) ? withInput(() => automationDomAction(op, locator, { ...detail, isCancelled })) : automationDomAction(op, locator, { ...detail, isCancelled }), sessionSendCurrent, sessionWaitReply, getState: runScopedState, setState: setRunState, isCancelled, notifyToast: async (level, message, detail) => { const result = await runNotifier.show(level, message, detail); appendRunLog('notify:toast:' + level); return result; }, notifySession: async () => { throw new Error('主账号会话通知尚未启用,请先验证 WorkBuddy 会话 API'); }, log: appendRunLog };
// 等「收起面板」完成后才开始执行任务(executeTask 内部第一步就点新建任务/聚焦 composer,
@@ -3095,7 +3103,14 @@ function startAutomationRun(task, event = null) {
.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 && 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); } });
+ .finally(async () => {
+ // Include cached/skipped results and refresh once after the whole run so an
+ // earlier account snapshot cannot leave the open panel with stale badges.
+ if (task.id === 'daily-account-checkin' && cdp.connected) {
+ cdpSend('Runtime.evaluate', { expression: "window.dispatchEvent(new CustomEvent('workdaddy:accounts-updated'))" }).catch(() => {});
+ }
+ try { await runNotifier.cleanup(); } finally { releaseRenderer(); resumeAutomationAfterNavigation(run); }
+ });
return run;
}
@@ -3412,6 +3427,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_AVATAR_LOGO__/g, 'data:image/svg+xml;base64,' + fs.readFileSync(path.join(__dirname, 'assets', 'workdaddy-app-icon-source.svg')).toString('base64'))
.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));
}
@@ -3638,7 +3654,7 @@ function sessionRangeMs(range) {
// tasks/<id>/、file-history/<id>/、artifact-index/<id>.json(全部以新 id 命名复制)
// 异步实现:切号复制大批会话时,同步 cpSync 会阻塞主线程几十秒,把注入定时器、
// 面板响应全部饿死(切号后 FAB 迟迟不出现的根因之一)。
-async function copySessionFiles(wbHome, oldId, newId) {
+async function copySessionFiles(wbHome, oldId, newId, lineageIds = []) {
const fsMod = fs;
const result = { copied: 0, failed: 0 };
const copyOne = async (from, to) => {
@@ -3646,6 +3662,7 @@ async function copySessionFiles(wbHome, oldId, newId) {
if (!fsMod.existsSync(from)) return;
const fromResolved = path.resolve(from);
const toResolved = path.resolve(to);
+ if (fromResolved === toResolved) return;
const relative = path.relative(fromResolved, toResolved);
const targetInsideSource = relative && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
if (targetInsideSource) {
@@ -3653,7 +3670,7 @@ async function copySessionFiles(wbHome, oldId, newId) {
return;
}
fsMod.mkdirSync(path.dirname(to), { recursive: true });
- await fsMod.promises.cp(from, to, { recursive: true, force: true });
+ await fsMod.promises.cp(from, to, { recursive: true, force: true, preserveTimestamps: true });
result.copied++;
} catch (e) {
result.failed++;
@@ -3680,7 +3697,49 @@ async function copySessionFiles(wbHome, oldId, newId) {
// 4) file-history/<id>/
await copyOne(path.join(wbHome, 'file-history', oldId), path.join(wbHome, 'file-history', newId));
// 5) artifact-index/<id>.json
- await copyOne(path.join(wbHome, 'artifact-index', oldId + '.json'), path.join(wbHome, 'artifact-index', newId + '.json'));
+ // 官方按 _meta.ownerConversationId 校验跨工作目录交付文件。仅重映射确属源会话的 owner,
+ // 保留 requestId/URI/其他会话归属;原样 cp 会让目标会话过滤掉这些产物。
+ const fromIndex = path.join(wbHome, 'artifact-index', oldId + '.json');
+ const toIndex = path.join(wbHome, 'artifact-index', newId + '.json');
+ if (fsMod.existsSync(fromIndex)) {
+ let temporary;
+ try {
+ const stat = await fsMod.promises.stat(fromIndex);
+ if (stat.size > 16 * 1024 * 1024) throw new Error('产物索引超过 16MB,未覆盖目标索引');
+ const original = await fsMod.promises.readFile(fromIndex, 'utf8');
+ let index;
+ try { index = JSON.parse(original); }
+ catch (_) { throw new Error('产物索引格式不受支持'); }
+ const artifacts = Array.isArray(index) ? index : index && index.artifacts;
+ if (!Array.isArray(artifacts)) throw new Error('产物索引格式不受支持');
+ const owners = new Set([oldId, ...lineageIds]);
+ let changed = false;
+ for (const artifact of artifacts) {
+ if (artifact && artifact._meta && owners.has(artifact._meta.ownerConversationId) && artifact._meta.ownerConversationId !== newId) {
+ changed = true;
+ artifact._meta.ownerConversationId = newId;
+ }
+ }
+ if (oldId === newId && !changed) return result;
+ await fsMod.promises.mkdir(path.dirname(toIndex), { recursive: true });
+ temporary = await fsMod.promises.mkdtemp(path.join(path.dirname(toIndex), '.wbs-artifact-'));
+ const staged = path.join(temporary, 'index.json');
+ await fsMod.promises.writeFile(staged, JSON.stringify(index), { mode: stat.mode & 0o777, flag: 'wx' });
+ // 复制时间不能伪装成新内容,否则下一次切号会错选较旧的副本为同步来源。
+ await fsMod.promises.utimes(staged, stat.atime, stat.mtime);
+ // 就地修复旧来源时,官方进程若已落盘新产物,保留它的新内容供下次同步。
+ if (oldId === newId && await fsMod.promises.readFile(fromIndex, 'utf8') !== original) {
+ throw new Error('产物索引已变化,请重试同步');
+ }
+ await fsMod.promises.rename(staged, toIndex);
+ result.copied++;
+ } catch (error) {
+ result.failed++;
+ log('[sessions-copy] 产物索引复制失败: ' + error.message);
+ } finally {
+ if (temporary) await fsMod.promises.rm(temporary, { recursive: true, force: true });
+ }
+ }
log('[sessions-copy] 已复制消息文件 ' + oldId + ' -> ' + newId);
return result;
}
@@ -3755,11 +3814,14 @@ async function syncAutoCopyLineage(lineageId, targetUid) {
if (!latest) return { members: live.length, synced: 0, failedFiles: 0, targetIds, targetPresent };
const sourceRow = latest.row;
let synced = 0;
- let failedFiles = 0;
+ const ownerIds = records.map((member) => member.id);
+ // 旧版副本可能仍挂着最初源会话的 owner;也修复作为最新来源的副本自身。
+ const repairedSource = await copySessionFiles(PROFILE.dataRoot, latest.id, latest.id, ownerIds);
+ let failedFiles = repairedSource.failed;
for (const target of live) {
if (target.id === latest.id) continue;
await yieldAutoCopyToRenderer();
- const files = await copySessionFiles(PROFILE.dataRoot, latest.id, target.id);
+ const files = await copySessionFiles(PROFILE.dataRoot, latest.id, target.id, ownerIds);
synced++;
failedFiles += files.failed;
try {
@@ -3776,7 +3838,6 @@ async function syncAutoCopyLineage(lineageId, targetUid) {
return { members: live.length, synced, failedFiles, sourceId: latest.id, targetIds, targetPresent };
}
-const MAX_SESSION_EXPORT_BYTES = 256 * 1024 * 1024;
const MAX_SESSION_EXPORT_FILES = 20000;
const MAX_SESSION_IMPORT_ERRORS = 20;
const MAX_SESSION_IMPORT_ERROR_LENGTH = 240;
@@ -3798,7 +3859,6 @@ function archiveRelativePath(wbHome, target) {
function collectSessionArchiveFiles(wbHome, sessionId) {
if (!isValidSessionId(sessionId)) throw new Error('无效的会话 ID');
const files = [];
- let totalBytes = 0;
const collect = (target) => {
let stat;
try { stat = fs.lstatSync(target); }
@@ -3814,14 +3874,10 @@ function collectSessionArchiveFiles(wbHome, sessionId) {
}
if (!stat.isFile()) return;
if (files.length >= MAX_SESSION_EXPORT_FILES) throw new Error('会话附件文件过多,无法导出');
- if (totalBytes + stat.size > MAX_SESSION_EXPORT_BYTES) throw new Error('会话附件超过 256 MB,无法导出');
const relative = archiveRelativePath(wbHome, target);
// Validate every exported path with the same mapper used during import.
remapSessionArchivePath(relative, sessionId, sessionId);
- const content = fs.readFileSync(target);
- totalBytes += content.length;
- if (totalBytes > MAX_SESSION_EXPORT_BYTES) throw new Error('会话附件超过 256 MB,无法导出');
- files.push({ path: relative, data: content.toString('base64') });
+ files.push({ path: relative, source: target, size: stat.size });
};
const projects = path.join(wbHome, 'projects');
@@ -3867,7 +3923,6 @@ function restoreSessionArchiveFiles(wbHome, sessionArchive, newId) {
if (!isValidSessionId(oldId) || !isValidSessionId(newId)) throw new Error('会话归档包含无效 ID');
const sourceFiles = Array.isArray(sessionArchive.files) ? sessionArchive.files : [];
if (sourceFiles.length > MAX_SESSION_EXPORT_FILES) throw new Error('会话归档附件文件过多');
- let totalBytes = 0;
const targets = new Set();
for (const entry of sourceFiles) {
if (!entry || typeof entry.path !== 'string' || typeof entry.data !== 'string' || entry.data.length % 4 === 1 || !/^[A-Za-z0-9+/]*={0,2}$/.test(entry.data)) {
@@ -3878,14 +3933,28 @@ function restoreSessionArchiveFiles(wbHome, sessionArchive, newId) {
if (targets.has(target)) throw new Error('会话归档包含重复附件路径');
targets.add(target);
const content = Buffer.from(entry.data, 'base64');
- totalBytes += content.length;
- if (totalBytes > MAX_SESSION_EXPORT_BYTES) throw new Error('会话归档附件超过 256 MB');
ensureArchiveParentNoFollow(wbHome, target);
fs.writeFileSync(target, content, { flag: 'wx', mode: 0o600 });
}
return sourceFiles.length;
}
+// Only readSessionTransfer creates these private staging paths. Never accept them
+// from a JSON API payload or an unverified archive entry.
+async function restoreStagedSessionArchiveFiles(wbHome, archive, newId) {
+ const oldId = String(archive.record.id);
+ const targets = new Set();
+ for (const entry of archive.files) {
+ const relative = remapSessionArchivePath(entry.path, oldId, newId);
+ const target = resolveArchiveTarget(wbHome, relative);
+ if (targets.has(target)) throw new Error('会话归档包含重复附件路径');
+ targets.add(target);
+ ensureArchiveParentNoFollow(wbHome, target);
+ await fs.promises.copyFile(entry.source, target, fs.constants.COPYFILE_EXCL);
+ await fs.promises.chmod(target, 0o600);
+ }
+}
+
const SESSION_COPY_COLUMNS = [
'id', 'cwd', 'user_id', 'title', 'custom_title', 'status', 'created_at', 'updated_at',
'last_activity_at', 'is_playground', 'source_mode', 'is_background_automation', 'mode', 'model',
@@ -3948,13 +4017,15 @@ async function exportSessions(ids, password) {
return { record, files: collectSessionArchiveFiles(wbHome, id) };
});
if (!sessions.length) throw new Error('没有可导出的会话');
- const payload = { exportType: 'WorkDaddy-sessions', version: 1, sessions };
- const content = createEncryptedExport('sessions', payload, password);
- return {
- filename: 'WorkDaddy-会话导出-' + new Date().toISOString().slice(0, 10) + '.json',
- content,
- count: sessions.length,
- };
+ const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'workdaddy-session-export-'));
+ const file = path.join(directory, 'sessions.wds');
+ try {
+ await writeSessionTransfer(file, sessions, password);
+ return { file, directory, count: sessions.length };
+ } catch (error) {
+ await fs.promises.rm(directory, { recursive: true, force: true });
+ throw error;
+ }
}
function validImportedSessionUid(value) {
@@ -3964,7 +4035,10 @@ function validImportedSessionUid(value) {
}
async function importSessions(content, password, targetUid) {
- const payload = openEncryptedExport(content, 'sessions', password);
+ return importSessionArchives(openEncryptedExport(content, 'sessions', password), targetUid);
+}
+
+async function importSessionArchives(payload, targetUid, staged = false) {
const archives = Array.isArray(payload.sessions) ? payload.sessions : [];
if (!archives.length) throw new Error('导入文件中没有会话数据');
if (archives.length > 100) throw new Error('单次最多导入 100 个会话');
@@ -3981,7 +4055,8 @@ async function importSessions(content, password, targetUid) {
catch (error) { errors.push(error.message); continue; }
const newId = crypto.randomUUID();
try {
- restoreSessionArchiveFiles(PROFILE.dataRoot, archive, newId);
+ if (staged) await restoreStagedSessionArchiveFiles(PROFILE.dataRoot, archive, newId);
+ else restoreSessionArchiveFiles(PROFILE.dataRoot, archive, newId);
await insertCopiedSession(record, ownerUid, newId);
imported.push({ sourceId: oldId, id: newId, uid: ownerUid });
} catch (error) {
@@ -4002,6 +4077,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
if (!lineageId && sourceLineage.enabled) lineageId = sourceLineage.lineageId;
if (auto && sourceUid && !lineageId) lineageId = ensureAutoCopySession(DATA_DIR, sourceUid, src.id);
const perform = async () => {
+ const ownerIds = lineageId ? getAutoCopySessionMemberRecords(DATA_DIR, lineageId).map((member) => member.id) : [];
if (sourceUid && lineageId) {
const mapping = getAutoCopyMapping(DATA_DIR, lineageId, targetUid);
if (mapping && mapping.targetId) {
@@ -4010,7 +4086,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
[mapping.targetId]
);
if (existing.length && String(existing[0].user_id || '') === String(targetUid)) {
- const files = await copySessionFiles(wbHome, src.id, mapping.targetId);
+ const files = await copySessionFiles(wbHome, src.id, mapping.targetId, ownerIds);
addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, mapping.targetId);
setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
targetId: mapping.targetId,
@@ -4049,7 +4125,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
});
if (candidates.length) {
const canonicalId = candidates[0].id;
- const files = await copySessionFiles(wbHome, src.id, canonicalId);
+ const files = await copySessionFiles(wbHome, src.id, canonicalId, ownerIds);
addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, canonicalId);
setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
targetId: canonicalId,
@@ -4063,7 +4139,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
const newId = crypto.randomUUID();
await insertCopiedSession(src, targetUid, newId);
- const files = await copySessionFiles(wbHome, src.id, newId);
+ const files = await copySessionFiles(wbHome, src.id, newId, ownerIds);
if (lineageId) {
addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, newId);
setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
@@ -4355,6 +4431,9 @@ function removeSessionAppCache(wbHome, id) {
// tasks/<id>/、file-history/<id>/、artifact-index/<id>.json(全部按会话 id 精确删除,不可恢复)
function deleteSessionFiles(wbHome, id) {
if (!isValidSessionId(id)) throw new Error('无效的会话 ID');
+ // 配置的数据根允许是 Windows junction;仅解析这一层,内部 managed parent 仍逐级拒绝链接。
+ try { wbHome = fs.realpathSync(wbHome); }
+ catch (error) { if (error.code === 'ENOENT') return 0; throw error; }
let removed = removeSessionAppCache(wbHome, id) ? 1 : 0;
const delOne = (parent, leaf) => {
let target;
@@ -5417,7 +5496,8 @@ function initBuiltinAssets() {
/** 内置主题(默认 + 3 套示例) */
const BUILTIN_THEMES = {
- default: { id: 'default', name: '默认(浅色)', author: 'WorkBuddy', dark: false, colors: {} },
+ default: { id: 'default', name: '浅色', author: 'WorkBuddy', dark: false, colors: {} },
+ dark: { id: 'dark', name: '深色', author: 'WorkBuddy', dark: true, colors: {} },
'oled-dark': {
id: 'oled-dark', name: 'OLED 纯黑', author: 'wbs', dark: true,
colors: {
@@ -5595,7 +5675,7 @@ function listThemes() {
if (!fs.statSync(flatPath).isDirectory() || !fs.existsSync(subPath)) continue;
try { t = JSON.parse(fs.readFileSync(subPath, 'utf8')); } catch (_) { continue; }
}
- if (!t || !t.id || !t.colors) continue;
+ if (!t || !t.id || !t.colors || t.id === 'default' || t.id === 'dark') continue;
const existing = themes.findIndex((x) => x.id === t.id);
const item = { id: t.id, name: t.name || t.id, author: t.author || 'unknown', dark: !!t.dark, builtin: false };
if (existing >= 0) themes[existing] = item; // 覆盖内置
@@ -5608,6 +5688,8 @@ function listThemes() {
/** 取主题完整定义(含 colors)。优先读 themes/ 目录的自定义文件(可覆盖内置同名主题),否则回退内置 */
function getTheme(id) {
+ // 浅色/深色始终对应官方外观,不允许同名自定义文件改变其语义。
+ if (id === 'default' || id === 'dark') return BUILTIN_THEMES[id];
// 先查文件(用户自定义或覆盖内置的完整版)——支持 themes/<id>.json 与 themes/<id>/theme.json 两种布局
try {
const safeId = id.replace(/[^A-Za-z0-9_-]/g, '_');
@@ -5841,7 +5923,7 @@ async function applyThemeByCdp(id) {
var WBS_UID = ${JSON.stringify(uid || null)};
// 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 === 'default' || id === 'dark' ? "'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 自己恢复该主题;
@@ -5884,12 +5966,12 @@ async function applyThemeByCdp(id) {
h.setAttribute('data-theme', mode);
}
var s = document.getElementById('wbs-theme-style');
- if (${id === 'default' ? 'true' : 'false'}) {
+ if (${id === 'default' || id === 'dark' ? 'true' : 'false'}) {
if (s) s.remove();
- // 默认主题:完全恢复官方浅色(移除 dark 标记,body 恢复官方浅色主题名)
- h.removeAttribute('data-theme'); h.classList.remove('cb-dark');
- b.setAttribute('data-vscode-theme-name', 'IDE Light'); b.classList.remove('vscode-dark');
- wbsSyncNativeTheme('light');
+ // 原生浅色/深色只同步官方外观,不注入 WorkDaddy 色板和壁纸。
+ h.classList.toggle('cb-dark', ${isDark ? 'true' : 'false'});
+ b.classList.toggle('vscode-dark', ${isDark ? 'true' : 'false'});
+ wbsSyncNativeTheme(${JSON.stringify(isDark ? 'dark' : 'light')});
} else {
if (${isDark ? 'true' : 'false'}) {
// 深色主题:切官方深色模式(局部硬编码变量随之变深)
@@ -6706,6 +6788,17 @@ function decryptLegacyExport(b64, password) {
return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8');
}
+function applyCheckinConsent(enabled) {
+ const pending = readCheckinConsent(DATA_DIR).shouldPrompt;
+ const choice = decideCheckinConsent(DATA_DIR, enabled);
+ if (!pending || !enabled || !choice.enabled) return choice;
+ const task = readAutomations(DATA_DIR).find((item) => item.id === 'daily-account-checkin' && item.enabled);
+ if (!task) return choice;
+ const running = Array.from(automationRuns.values()).find((run) => run.taskId === task.id && run.status === 'running');
+ const run = running || startAutomationRun(task);
+ return { ...choice, run: automationPublicRun(run) };
+}
+
function handleApi(req, res) {
const url = new URL(req.url, `http://${req.headers.host || HOST}`);
const p = url.pathname;
@@ -6826,6 +6919,21 @@ function handleApi(req, res) {
});
}
+ if (['GET', 'POST'].includes(req.method) && p === '/api/automations/checkin-consent') {
+ if (!PROFILE.capabilities.accounts || PROFILE.capabilities.checkin === false) {
+ return json(res, 200, { ok: true, shouldPrompt: false, enabled: false });
+ }
+ if (req.method === 'GET') {
+ try { return json(res, 200, readCheckinConsent(DATA_DIR)); }
+ catch (_) { return json(res, 500, { ok: false, error: 'Unable to read check-in choice' }); }
+ }
+ return readBody(req).then((body) => {
+ if (!body || typeof body.enabled !== 'boolean') return json(res, 400, { ok: false, error: 'Invalid check-in choice' });
+ try { return json(res, 200, applyCheckinConsent(body.enabled)); }
+ catch (_) { return json(res, 500, { ok: false, error: 'Unable to save check-in choice' }); }
+ });
+ }
+
if (req.method === 'GET' && p === '/api/automations') {
const imported = importAgentInbox(DATA_DIR, { profileId: PROFILE.id });
imported.forEach((item) => log(`[automation-agent] request=${item.requestId} ${item.ok ? 'imported=' + item.taskId : 'rejected=' + item.error}`));
@@ -7272,7 +7380,6 @@ 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) {
@@ -7296,6 +7403,13 @@ function handleApi(req, res) {
});
}
+ if (req.method === 'POST' && p === '/api/accounts/order') {
+ return readBody(req).then((body) => {
+ try { return json(res, 200, { ok: true, accountOrder: setAccountOrder(DATA_DIR, body) }); }
+ catch (error) { return json(res, 400, { ok: false, error: error.message }); }
+ });
+ }
+
if (req.method === 'GET' && p === '/api/accounts') {
const accounts = listAccounts(DATA_DIR);
const cache = loadCheckinCache();
@@ -7321,11 +7435,11 @@ function handleApi(req, res) {
const withUsage = enriched.map((account) => summaries[account.uid]
? Object.assign({}, account, { todayUsage: summaries[account.uid] })
: account);
- return json(res, 200, { ok: true, current: currentAccount(), primaryUid: primaryAccountStore.get(), accounts: withUsage });
+ return json(res, 200, { ok: true, current: currentAccount(), primaryUid: primaryAccountStore.get(), accountOrder: getAccountOrder(DATA_DIR), accounts: withUsage });
})
.catch((error) => {
log('[credits-usage] 读取本地今日用量失败: ' + error.message);
- return json(res, 200, { ok: true, current: currentAccount(), primaryUid: primaryAccountStore.get(), accounts: enriched });
+ return json(res, 200, { ok: true, current: currentAccount(), primaryUid: primaryAccountStore.get(), accountOrder: getAccountOrder(DATA_DIR), accounts: enriched });
});
});
}
@@ -8138,23 +8252,49 @@ function handleApi(req, res) {
const job = autoCopyJobs.get(url.searchParams.get('id') || '');
return job ? json(res, 200, { ok: true, job: publicAutoCopyJob(job) }) : json(res, 404, { ok: false, error: '自动复制任务不存在' });
}
- // 加密导出会话及其受管消息附件:POST /api/sessions/export { ids, password }
+ // Stream the completed encrypted archive; clean up even if the download disconnects.
if (req.method === 'POST' && p === '/api/sessions/export') {
return readBody(req).then(async (body) => {
+ let result;
try {
- const result = await exportSessions(body && body.ids, body && body.password);
+ result = await exportSessions(body && body.ids, body && body.password);
+ if (res.destroyed) return;
+ const headers = {
+ 'Content-Type': 'application/octet-stream',
+ 'Content-Length': fs.statSync(result.file).size,
+ 'Content-Disposition': 'attachment; filename="WorkDaddy-sessions.wds"',
+ 'X-WorkDaddy-Count': String(result.count),
+ 'Access-Control-Expose-Headers': 'X-WorkDaddy-Count',
+ 'Cache-Control': 'no-store',
+ };
+ if (res.__wbsCorsOrigin) { headers['Access-Control-Allow-Origin'] = res.__wbsCorsOrigin; headers.Vary = 'Origin'; }
+ res.writeHead(200, headers);
+ await transferPipeline(fs.createReadStream(result.file), res);
log(`[sessions-export] 已导出 ${result.count} 个会话`);
- return json(res, 200, { ok: true, ...result });
} catch (error) {
- return json(res, 400, { ok: false, error: error.message });
+ if (!res.headersSent && !res.destroyed) json(res, 400, { ok: false, error: error.message });
+ else res.destroy();
+ } finally {
+ if (result) await fs.promises.rm(result.directory, { recursive: true, force: true });
}
});
}
- // 加密导入会话;targetUid 缺省时保留归档中的账号归属。
+ // Binary uploads carry a small length-prefixed JSON request followed by the
+ // archive. Legacy v2/v3 JSON imports keep their existing authenticated API.
if (req.method === 'POST' && p === '/api/sessions/import') {
- return readBody(req).then(async (body) => {
+ return (async () => {
+ let directory;
try {
- const result = await importSessions(body && body.content, body && body.password, body && body.targetUid);
+ let result;
+ if (String(req.headers['content-type'] || '').split(';')[0] === 'application/octet-stream') {
+ directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'workdaddy-session-import-'));
+ const body = await receiveSessionUpload(req, directory);
+ const payload = await readSessionTransfer(body.file, body.password, path.join(directory, 'staged'));
+ result = await importSessionArchives(payload, body.targetUid, true);
+ } else {
+ const body = await readBody(req);
+ result = await importSessions(body && body.content, body && body.password, body && body.targetUid);
+ }
log(`[sessions-import] 已导入 ${result.imported.length} 个会话,失败 ${result.failed} 个`);
return json(res, 200, {
ok: true,
@@ -8165,8 +8305,10 @@ function handleApi(req, res) {
});
} catch (error) {
return json(res, 400, { ok: false, error: error.message });
+ } finally {
+ if (directory) await fs.promises.rm(directory, { recursive: true, force: true });
}
- });
+ })();
}
// 复制会话:POST /api/sessions/copy { ids, targetUid }(保留原会话,复制记录+消息文件到目标账号)
if (req.method === 'POST' && p === '/api/sessions/copy') {
@@ -9180,6 +9322,7 @@ for (const preset of ['close-buddy-popups.json', ...(PROFILE.capabilities.accoun
if (PROFILE.capabilities.accounts && PROFILE.capabilities.checkin !== false) {
try { installBuiltinTask(DATA_DIR, path.join(__dirname, 'builtin/automations/daily-account-checkin.json')); }
catch (_) { log('[automation] 初始化签到任务失败'); }
+ initializeCheckinConsent(DATA_DIR);
}
restoreSleepMode();
startServer();
diff --git a/scripts/inject.js b/scripts/inject.js
index 7cc11ab..d2c0ff2 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -18,7 +18,7 @@ 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 (!alive || 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);
@@ -723,6 +723,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var WBS_DIAGNOSTICS_ENABLED = __WBS_DIAGNOSTICS_ENABLED__;
var WBS_PLATFORM = __WBS_PLATFORM__; // 注入时替换为 JSON 字符串(如 "darwin"/"win32")
var WBS_LOGO = '__WBS_LOGO__';
+ var WBS_AVATAR_LOGO = '__WBS_AVATAR_LOGO__';
var WBS_COMPAT = window.__wbsWorkBuddyCompat;
if (!WBS_COMPAT) throw new Error('WorkBuddy 兼容层未加载');
// WorkBuddy 基于 Electron,持续会话模块在 macOS/Windows 使用同一套 CDP 逻辑。
@@ -736,6 +737,13 @@ 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 = {
+ '自动签到提醒': 'Automatic check-in',
+ '开启后自动为已保存账号签到。': 'Enable automatic check-in for your saved accounts.',
+ '请留意官方规则,自动操作可能影响账号使用。': 'Please follow the official rules; automated actions may affect your account access.',
+ '可随时在「自动化」中关闭。': 'You can turn this off at any time under Automations.',
+ '开启自动签到': 'Enable automatic check-in',
+ '保存失败,请重试。': 'Could not save. Please try again.',
+
'查询失败,请重新选择时间或账号重试': '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.',
@@ -857,11 +865,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
"请选择将来的执行日期和时间": "Choose a future date and time",
"请选择有效的执行日期和时间": "Choose a valid date and time",
"每月日期必须是 1–31": "Day of month must be 1\u201331",
- '今日签到': 'Daily check-in', '今日已签到': 'Checked in today', '今日尚未签到': 'Not checked in today', '客户端加载': 'Client loaded', '打开面板': 'Panel opened', '事件触发(可多选)': 'Event triggers (select any)', '定时间隔(分钟)': 'Interval (minutes)', '定时': 'Scheduled', '每 ': 'Every ', '定时间隔必须是 1–10080 分钟的整数': 'Interval must be an integer from 1 to 10080 minutes', '不支持的面板事件': 'Unsupported panel event', '无签到活动': 'No check-in activity', '登录身份过期': 'Login expired', '刚刚': 'Just now', '分钟前': ' minutes ago', '小时前': ' hours ago', '天前': ' days ago',
+ '产物索引已变化,请重试同步': 'Artifact index changed; retry synchronization', '已到期': 'Expired', ' 个未获取余额': ' balances unavailable', ' 个不限量': ' unlimited', '无效的账号排序设置': 'Invalid account order settings', '产物索引超过 16MB,未覆盖目标索引': 'Artifact index exceeds 16MB; target index was preserved', '产物索引格式不受支持': 'Unsupported artifact index format', '积分汇总': 'Credit summary', '更多账号设置': 'More account settings', '积分到期分布': 'Credit expiry distribution', '剩余天数 · 积分': 'Days left · Credits', '按剩余天数汇总积分': 'Credits by days remaining', '未知有效期': 'Unknown expiry', '暂无可汇总积分': 'No credits to summarize', '拖拽调整顺序,也可聚焦拖拽按钮后按 ↑ ↓ 调整。新增账号排在最后。': 'Drag to reorder, or focus a handle and press ↑ ↓. New accounts appear last.', '拖拽排序,或按上下方向键调整': 'Drag or use arrow keys to reorder', '调整账号顺序': 'Reorder account', '固定账号顺序': 'Fixed account order', '保存排序失败': 'Failed to save order', '暂无账号': 'No accounts', '{n} 个账号': '{n} accounts', '{n} 个未获取余额': '{n} balances unavailable', '{n} 个不限量': '{n} unlimited', '今日未签到': 'Not checked in today', '浅色': 'Light', '深色': 'Dark', '更多': 'More', '汇总': 'Summary', '账号排序': 'Account order', '按积分临近时间': 'Nearest credit expiry', '固定顺序': 'Fixed order', '今日签到': 'Daily check-in', '今日已签到': 'Checked in today', '今日尚未签到': 'Not checked in today', '客户端加载': 'Client loaded', '打开面板': 'Panel opened', '事件触发(可多选)': 'Event triggers (select any)', '定时间隔(分钟)': 'Interval (minutes)', '定时': 'Scheduled', '每 ': 'Every ', '定时间隔必须是 1–10080 分钟的整数': 'Interval must be an integer from 1 to 10080 minutes', '不支持的面板事件': 'Unsupported panel event', '无签到活动': 'No check-in activity', '登录身份过期': 'Login expired', '刚刚': 'Just now', '分钟前': ' minutes ago', '小时前': ' hours ago', '天前': ' days ago',
'发现新版本': 'New version available', '立即更新': 'Update now', '有新版本可用,点击更新。': 'A new version is available. Click Update.', '下载中…': '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;关闭后停止上报。': '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',
+ '发送错误诊断': 'Send error diagnostics', '推荐开启': 'Recommended', '由环境变量控制': 'Controlled by environment variable', '默认开启 · 设置读取失败': 'Enabled by default · failed to read setting', '保存中…': 'Saving…', '此开关控制脱敏错误诊断。匿名安装数和日活独立统计(随机安装标识、系统、架构、版本、客户端类型及出口国家),不受此开关影响。不包含账号、会话内容、Token 或 API Key。': 'This switch controls redacted error diagnostics. Anonymous installation and daily active counts are collected independently (random installation ID, system, architecture, version, client type, and network country). No accounts, session content, tokens, or API keys.', '查看错误诊断说明': 'View diagnostics details', '问题反馈': 'Report an issue', '会话监听日志': 'Session monitor log', '仅保存在当前页面内存': 'Stored only in this page memory',
'权限免打扰': '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',
@@ -993,7 +1001,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'删除后会直接修改官方 models.json,已备份到「备选模型」的配置不会受影响。': 'Deleting directly modifies the official models.json; configs backed up under “Backup models” remain unaffected.',
'当前模型已删除': 'Current model deleted', '删除模型备份?': 'Delete model backup?',
'删除后无法恢复,但不会影响官方 models.json。': 'Cannot be restored after deletion, but the official models.json is unaffected.',
- '删除模型备份失败:': 'Failed to delete model backup:', '头像预览': 'Avatar preview', '点击恢复官方头像': 'Click to restore the official avatar',
+ '删除模型备份失败:': 'Failed to delete model backup:', '头像预览': 'Avatar preview', '自定义头像': 'Custom avatar', '自定义': 'Custom', '无效的头像图片': 'Invalid avatar image', '添加头像': 'Add avatar', '删除头像': 'Delete avatar', '头像图片读取失败': 'Could not read avatar image', '头像保存失败,请清理存储空间后重试': 'Could not save avatar; free storage space and retry', '点击恢复官方头像': 'Click to restore the official avatar',
'未找到该账号已记录的登录文件名,拒绝猜测写入目标': 'No recorded login filename for this account; refusing to guess a write target',
'「': '“', '」': '”',
// —— 第七批:头像/主题/安装器/休眠等散落整句 ——
@@ -1106,10 +1114,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'CodeBuddy 会话库读取失败:': 'CodeBuddy session DB read failed:',
'拒绝在文件系统根目录创建会话空间': 'Refusing to create a session workspace at the filesystem root',
'无效的会话 ID': 'Invalid session ID', '无效的会话文件目标': 'Invalid session file target',
- '会话附件文件过多,无法导出': 'Too many session attachment files; cannot export', '会话附件超过 256 MB,无法导出': 'Session attachments exceed 256 MB; cannot export',
+ '会话附件发生变化,请重新导出': 'Session attachments changed; please export again',
+ '会话归档元数据过大': 'Session archive metadata is too large', '会话归档元数据无效': 'Invalid session archive metadata',
+ '会话归档不完整或已损坏': 'Session archive is incomplete or corrupted', '不是有效的 WorkDaddy 会话归档': 'Not a valid WorkDaddy session archive',
+ '会话归档包含多余数据': 'Session archive contains unexpected trailing data', '单次最多导出 100 个会话': 'Export at most 100 sessions at a time',
+ '无效的账号归属': 'Invalid account ownership',
+ '会话附件文件过多,无法导出': 'Too many session attachment files; cannot export',
'会话归档包含无效 ID': 'Session archive contains an invalid ID', '会话归档包含无效附件': 'Session archive contains an invalid attachment',
'会话归档附件文件过多': 'Session archive has too many attachment files', '会话归档包含重复附件路径': 'Session archive contains duplicate attachment paths',
- '会话归档附件超过 256 MB': 'Session archive attachments exceed 256 MB', '会话归档缺少有效的账号归属': 'Session archive is missing a valid account owner',
+ '会话归档缺少有效的账号归属': 'Session archive is missing a valid account owner',
'首次会话播种持久化失败': 'Initial session seeding failed to persist',
'导入文件中没有快捷短语': 'No quick phrases found in the import file', '单次最多导入 {n} 条快捷短语': 'Import at most {n} quick phrases at a time',
'没有可导入的快捷短语': 'No quick phrases to import', '暂存记录不存在:': 'Stashed record not found:', '暂存内容为空': 'Stash content is empty',
@@ -1339,7 +1352,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
})();
// 纯图标 SVG(stroke 跟随按钮 currentColor)
- var PRIMARY_ACCOUNT_SVG = '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3 7 4.5 4L12 4l4.5 7L21 7l-2 11H5L3 7Z"/><path d="M6 21h12"/></svg>';
var SWITCH_SVG =
'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<path d="M16 3l4 4-4 4"/><path d="M20 7H8"/><path d="M8 21l-4-4 4-4"/><path d="M4 17h12"/></svg>';
@@ -1400,6 +1412,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>' +
'<polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
+ var CREDIT_SUMMARY_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M4 20h16M7 16V9m5 7V4m5 12v-5"/></svg>';
var 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>';
@@ -1449,11 +1462,96 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function esc(t) { return String(t == null ? '' : t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
function escAttr(t) { return esc(t).replace(/"/g, '&quot;').replace(/'/g, '&#39;'); }
+ // 每个积分段只归入一个剩余天数桶;缺失有效期的余额不展示,不猜测到期日。
+ function summarizeCreditDays(accounts, now) {
+ var buckets = new Map(), unavailable = 0, unlimited = 0;
+ function add(days, credits) {
+ if (credits > 0 && isFinite(credits)) buckets.set(days, (buckets.get(days) || 0) + credits);
+ }
+ (accounts || []).forEach(function (account) {
+ if (account.creditUnlimited) { unlimited++; return; }
+ if (account.creditExpired || isIdentityExpired(account) || typeof account.credits !== 'number' || !isFinite(account.credits)) { unavailable++; return; }
+ var balance = Math.max(0, account.credits);
+ var segments = Array.isArray(account.creditSegments) ? account.creditSegments : [];
+ segments.forEach(function (segment) {
+ if (!segment || !isFinite(Number(segment.remaining))) return;
+ var amount = Math.min(balance, Math.max(0, Number(segment.remaining)));
+ var expiry = segment.expiresAt;
+ var days = expiry !== null && expiry !== undefined && expiry !== '' && isFinite(Number(expiry))
+ ? Math.max(0, Math.ceil((Number(expiry) - now) / 86400000)) : null;
+ add(days, amount); balance -= amount;
+ });
+ add(null, balance);
+ });
+ return { rows: Array.from(buckets, function (item) { return { days: item[0], credits: item[1] }; }).filter(function (row) { return row.days !== null; }).sort(function (a, b) {
+ if (a.days === b.days) return 0;
+ if (a.days === null) return 1;
+ if (b.days === null) return -1;
+ return a.days - b.days;
+ }), accountCount: (accounts || []).length, unavailable: unavailable, unlimited: unlimited };
+ }
+
+ function creditOpacity(days) {
+ if (days === null || days === undefined || !isFinite(Number(days))) return 1;
+ return 0.05 + 0.95 * Math.max(0, Math.min(29, Number(days) - 1)) / 29;
+ }
+
+ function createAvatarLibrary(storage) {
+ var key = 'wbsAvatarLibrary', state = { selected: 'workbuddy', items: [] };
+ function validImage(src) { return typeof src === 'string' && /^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(src); }
+ try {
+ var saved = JSON.parse(storage.getItem(key) || 'null');
+ if (saved && Array.isArray(saved.items)) {
+ var ids = new Set();
+ state.items = saved.items.filter(function (item) {
+ if (!item || typeof item.id !== 'string' || !/^custom-[a-z0-9-]+$/.test(item.id) || ids.has(item.id) || !validImage(item.src)) return false;
+ ids.add(item.id); return true;
+ }).map(function (item) { return { id: item.id, src: item.src }; });
+ if (saved.selected === 'workbuddy' || saved.selected === 'workdaddy' || ids.has(saved.selected)) state.selected = saved.selected;
+ } else {
+ var legacy = storage.getItem('wbsAvatar');
+ if (validImage(legacy)) { state.items = [{ id: 'custom-legacy', src: legacy }]; state.selected = 'custom-legacy'; }
+ else if (legacy === 'workdaddy') state.selected = 'workdaddy';
+ }
+ } catch (_) {}
+ function snapshot() { return { selected: state.selected, items: state.items.map(function (item) { return { id: item.id, src: item.src }; }) }; }
+ function commit(next) {
+ storage.setItem(key, JSON.stringify(next));
+ state = next;
+ try { storage.removeItem('wbsAvatar'); } catch (_) {}
+ }
+ return {
+ snapshot: snapshot,
+ select: function (id) {
+ if (id !== 'workbuddy' && id !== 'workdaddy' && !state.items.some(function (item) { return item.id === id; })) return;
+ var next = snapshot(); next.selected = id; commit(next);
+ },
+ add: function (src) {
+ if (!validImage(src)) throw new Error('无效的头像图片');
+ var next = snapshot(), id;
+ do { id = 'custom-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10); }
+ while (next.items.some(function (item) { return item.id === id; }));
+ next.items.push({ id: id, src: src }); next.selected = id; commit(next); return id;
+ },
+ remove: function (id) {
+ if (!state.items.some(function (item) { return item.id === id; })) return;
+ var next = snapshot(); next.items = next.items.filter(function (item) { return item.id !== id; });
+ next.selected = 'workdaddy'; commit(next);
+ },
+ };
+ }
+
+ function resolveAvatarChoice(saved, official, brand) {
+ if (saved === 'workdaddy') return { preset: 'workdaddy', src: brand };
+ if (typeof saved === 'string' && /^data:image\/(png|jpeg|webp);base64,/.test(saved)) return { preset: 'custom', src: saved };
+ return { preset: 'workbuddy', src: official };
+ }
+
function checkinHtml(a) {
if (WBS_PROFILE_IS_AI) return '';
var c = a && a.checkin;
var checked = !!(c && c.ok && !c.inactive);
- return '<span class="wbs-ck wbs-checkin-tag ' + (checked ? 'ok' : 'pending') + '" title="' + (checked ? '今日已签到' : '今日尚未签到') + '">今日签到</span>';
+ return '<span class="wbs-ck wbs-checkin-tag ' + (checked ? 'ok' : 'pending') + '" title="' + (checked ? '今日已签到' : '今日未签到') + '">' + (checked ? '今日已签到' : '今日未签到') + '</span>';
}
function activityStreakHtml(a) {
@@ -1509,7 +1607,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
headers['X-WorkDaddy-Token'] = WBS_API_TOKEN;
request.headers = headers;
+ delete request.responseType;
return fetch(API + path, request).then(function (r) {
+ if (r.ok && opts.responseType === 'blob') return r.blob().then(function (blob) {
+ return { content: blob, mimeType: 'application/octet-stream', count: Number(r.headers.get('X-WorkDaddy-Count') || 0) };
+ });
return r.json().then(function (j) {
if (!r.ok || j.ok === false) {
var error = new Error(j.error || '请求失败');
@@ -1693,7 +1795,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var lifecycle = createBuildLifecycle();
var registerDisposer = lifecycle.registerDisposer;
var usageActivity = createUsageActivity({ document: document, window: window,
- now: Date.now, enabled: function () { return WBS_DIAGNOSTICS_ENABLED; },
+ now: Date.now,
send: function () { return api('/api/usage', { method: 'POST' }); } });
registerDisposer(function () { usageActivity.destroy(); });
var alive = true;
@@ -4545,16 +4647,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<button class="wbs-acct-eye" type="button" title="隐藏敏感信息" aria-label="隐藏敏感信息">' + EYE_SVG + '</button>' +
'<span class="wbs-acct-stat-divider"></span>' +
'<div class="wbs-acct-stat"><span>总积分</span><strong id="wbs-acct-total">-</strong></div>' +
+ '<button class="wbs-acct-eye" type="button" data-act="credit-summary" title="汇总" aria-label="积分汇总" aria-expanded="false">' + CREDIT_SUMMARY_ICON + '</button>' +
'</div>' +
'<div class="wbs-acct-actions">' +
'<button class="wbs-acct-io wbs-acct-icon" type="button" data-act="token-stats" title="用量统计" aria-label="用量统计">' + TOKEN_STATS_ICON + '</button>' +
'<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>' +
+ '<button class="wbs-acct-io wbs-acct-icon" type="button" data-act="account-more" title="账号排序" aria-label="账号排序"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 4v16m-4-4 4 4 4-4M14 5h7m-7 5h5m-5 5h3"/></svg></button>' +
'</div>' +
'</div>' +
'<div class="wbs-acct-list"></div>' +
'<button class="wbs-logout-btn" type="button" data-act="logout">' + LOGOUT_SVG + '<span>登录新账号</span></button>' +
'<input type="file" id="wbs-import-file" accept=".json,application/json" style="display:none">';
+ root.querySelector('[data-act="account-more"]').addEventListener('click', openAccountOrderModal);
+ setupCreditSummary();
logoutBtn = root.querySelector('[data-act="logout"]');
var eyeBtn = root.querySelector('.wbs-acct-eye');
if (eyeBtn) eyeBtn.addEventListener('click', toggleAccountMask);
@@ -4566,6 +4672,171 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
root.querySelector('#wbs-import-file').addEventListener('change', onImportFile);
}
+ function openAccountOrderModal() {
+ var existing = root.querySelector('#wbs-account-order-mask');
+ if (existing) return;
+ var previousFocus = document.activeElement;
+ var mask = el('div', 'wbs-modal-mask wbs-modal-mask-panel');
+ mask.id = 'wbs-account-order-mask';
+ var mode = state.accountOrder && state.accountOrder.mode === 'fixed' ? 'fixed' : 'expiry';
+ var ordered = state.accounts.slice().sort(function (a, b) {
+ var left = Number(a.sort) > 0 ? Number(a.sort) : Infinity;
+ var right = Number(b.sort) > 0 ? Number(b.sort) : Infinity;
+ return left === right ? 0 : left - right;
+ });
+ mask.innerHTML = '<div class="wbs-modal wbs-account-order-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-account-order-title">' +
+ '<div class="wbs-modal-title" id="wbs-account-order-title">账号排序</div>' +
+ '<div class="wbs-account-order-modes"><label><input type="radio" name="wbs-account-order" value="expiry">按积分临近时间</label>' +
+ '<label><input type="radio" name="wbs-account-order" value="fixed">固定顺序</label></div>' +
+ '<div data-fixed-order>' +
+ '<div class="wbs-account-order-list" role="list" aria-label="固定账号顺序"></div></div>' +
+ '<div class="wbs-password-error" role="alert"></div><div class="wbs-modal-actions">' +
+ '<button class="wbs-modal-btn" type="button" data-order-cancel>取消</button>' +
+ '<button class="wbs-modal-btn wbs-modal-ok" type="button" data-order-save>保存</button></div></div>';
+ panel.appendChild(mask);
+ var list = mask.querySelector('.wbs-account-order-list');
+ var busy = false, dragged = null;
+ function close() {
+ if (busy) return;
+ mask.remove();
+ if (previousFocus && previousFocus.isConnected) previousFocus.focus();
+ }
+ function drawRows() {
+ list.innerHTML = ordered.map(function (a, index) {
+ var name = a.nickname || '未命名';
+ return '<div class="wbs-account-order-row" draggable="true" role="listitem" data-order-index="' + index + '">' +
+ '<button type="button" class="wbs-acct-eye" data-order-handle title="拖拽排序,或按上下方向键调整" aria-label="调整账号顺序">' +
+ '<svg width="14" height="16" viewBox="0 0 14 16" fill="currentColor" aria-hidden="true"><path d="M3 2h2v2H3zm6 0h2v2H9zM3 7h2v2H3zm6 0h2v2H9zM3 12h2v2H3zm6 0h2v2H9z"/></svg></button>' +
+ '<span data-wbs-i18n-skip>' + esc(name) + '</span></div>';
+ }).join('') || '<div class="wbs-empty">暂无账号</div>';
+ }
+ function move(from, to) {
+ if (busy || from === to || from < 0 || to < 0 || to >= ordered.length) return;
+ ordered.splice(to, 0, ordered.splice(from, 1)[0]);
+ drawRows();
+ list.querySelector('[data-order-index="' + to + '"] button').focus();
+ }
+ function syncMode() {
+ mask.querySelectorAll('input[name="wbs-account-order"]').forEach(function (radio) { radio.checked = radio.value === mode; });
+ mask.querySelector('[data-fixed-order]').hidden = mode !== 'fixed';
+ }
+ mask.addEventListener('change', function (event) {
+ if (!busy && event.target.name === 'wbs-account-order') { mode = event.target.value; syncMode(); }
+ });
+ list.addEventListener('dragstart', function (event) {
+ var row = event.target.closest('[data-order-index]');
+ if (busy || !row) { event.preventDefault(); return; }
+ dragged = Number(row.dataset.orderIndex);
+ event.dataTransfer.effectAllowed = 'move';
+ event.dataTransfer.setData('text/plain', String(dragged));
+ row.classList.add('dragging');
+ });
+ list.addEventListener('dragover', function (event) {
+ if (dragged === null || busy) return;
+ event.preventDefault(); event.dataTransfer.dropEffect = 'move';
+ list.querySelectorAll('.drop-target').forEach(function (row) { row.classList.remove('drop-target'); });
+ var row = event.target.closest('[data-order-index]');
+ if (row) row.classList.add('drop-target');
+ });
+ list.addEventListener('drop', function (event) {
+ event.preventDefault();
+ var row = event.target.closest('[data-order-index]');
+ if (row && dragged !== null) move(dragged, Number(row.dataset.orderIndex));
+ dragged = null;
+ });
+ list.addEventListener('dragend', function () {
+ dragged = null;
+ list.querySelectorAll('.dragging,.drop-target').forEach(function (row) { row.classList.remove('dragging', 'drop-target'); });
+ });
+ mask.addEventListener('keydown', function (event) {
+ event.stopPropagation();
+ if (event.key === 'Escape') { event.preventDefault(); close(); }
+ var row = event.target.closest('[data-order-index]');
+ if (row && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
+ event.preventDefault();
+ var from = Number(row.dataset.orderIndex);
+ move(from, from + (event.key === 'ArrowUp' ? -1 : 1));
+ }
+ if (event.key === 'Tab') {
+ var focusable = Array.from(mask.querySelectorAll('button,input')).filter(function (node) { return !node.disabled && node.getClientRects().length; });
+ var first = focusable[0], last = focusable[focusable.length - 1];
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
+ if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
+ }
+ });
+ ['click','dblclick','pointerdown','pointerup','mousedown','mouseup','keyup','keypress','wheel','touchstart','touchmove'].forEach(function (type) {
+ mask.addEventListener(type, function (event) { event.stopPropagation(); });
+ });
+ mask.addEventListener('click', function (event) { if (event.target === mask) close(); });
+ mask.querySelector('[data-order-cancel]').addEventListener('click', close);
+ mask.querySelector('[data-order-save]').addEventListener('click', function () {
+ if (busy) return;
+ busy = true;
+ mask.querySelectorAll('button,input').forEach(function (node) { node.disabled = true; });
+ mask.querySelector('[data-order-save]').textContent = '保存中…';
+ api('/api/accounts/order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mode: mode, uids: ordered.map(function (a) { return a.uid; }) }) })
+ .then(function (result) {
+ state.accountOrder = result.accountOrder;
+ var ranks = new Map(); ordered.forEach(function (a, index) { ranks.set(a.uid, index + 1); });
+ state.accounts.forEach(function (a) { a.sort = ranks.get(a.uid) || 0; });
+ sortAccountsByCreditExpiry(); reorderAccountCards();
+ busy = false; close();
+ }).catch(function (error) {
+ busy = false;
+ mask.querySelectorAll('button,input').forEach(function (node) { node.disabled = false; });
+ mask.querySelector('[data-order-save]').textContent = '保存';
+ mask.querySelector('[role="alert"]').textContent = error.message || '保存排序失败';
+ });
+ });
+ drawRows(); syncMode();
+ mask.querySelector('input:checked').focus();
+ }
+
+ function setupCreditSummary() {
+ var button = accountsPane.querySelector('[data-act="credit-summary"]');
+ var popup = el('div', 'wbs-credit-summary-popover');
+ popup.id = 'wbs-credit-summary-popover';
+ popup.setAttribute('role', 'region'); popup.setAttribute('aria-label', '按剩余天数汇总积分');
+ popup.hidden = true;
+ button.setAttribute('aria-controls', popup.id);
+ document.body.appendChild(popup);
+ var hideTimer;
+ function hide() { clearTimeout(hideTimer); popup.hidden = true; button.setAttribute('aria-expanded', 'false'); }
+ function deferHide() { clearTimeout(hideTimer); hideTimer = setBuildTimeout(hide, 160); }
+ function show() {
+ clearTimeout(hideTimer);
+ var summary = summarizeCreditDays(state.accounts, Date.now());
+ var max = Math.max.apply(null, summary.rows.map(function (row) { return row.credits; }).concat([1]));
+ popup.innerHTML = '<div class="wbs-credit-summary-head"><strong>积分到期分布</strong><span>剩余天数 · 积分</span></div>' +
+ '<div class="wbs-credit-summary-chart">' + (summary.rows.map(function (row) {
+ var label = row.days === 0 ? '已到期' : row.days + ' 天';
+ return '<div class="wbs-credit-summary-row"><span>' + esc(label) + '</span><div class="wbs-credit-summary-track"><i class="wbs-credit-summary-fill" style="--wbs-credit-alpha:' + creditOpacity(row.days).toFixed(5) + ';width:' + Math.max(1, row.credits / max * 100).toFixed(2) + '%"></i></div><b>' + esc(fmtCredits(row.credits)) + '</b></div>';
+ }).join('') || '<div class="wbs-empty">暂无可汇总积分</div>') + '</div>' +
+ '<div class="wbs-credit-summary-foot">' + summary.accountCount + ' 个账号' +
+ (summary.unavailable ? ' · ' + summary.unavailable + ' 个未获取余额' : '') +
+ (summary.unlimited ? ' · ' + summary.unlimited + ' 个不限量' : '') + '</div>';
+ popup.hidden = false; button.setAttribute('aria-expanded', 'true');
+ var rect = button.getBoundingClientRect();
+ popup.style.left = Math.max(8, Math.min(rect.left, window.innerWidth - popup.offsetWidth - 8)) + 'px';
+ popup.style.top = (rect.bottom + 6) + 'px';
+ popup.style.maxHeight = Math.max(80, window.innerHeight - rect.bottom - 14) + 'px';
+ applyI18n(popup);
+ }
+ listen(button, 'mouseenter', show); listen(button, 'mouseleave', deferHide);
+ listen(button, 'focus', show); listen(button, 'blur', deferHide);
+ listen(button, 'click', show);
+ listen(button, 'keydown', function (event) { if (event.key === 'Escape') { event.stopPropagation(); hide(); } });
+ listen(popup, 'mouseenter', function () { clearTimeout(hideTimer); });
+ listen(popup, 'mouseleave', deferHide);
+ listen(popup, 'wheel', function (event) { event.stopPropagation(); });
+ listen(popup, 'pointerdown', function (event) { event.stopPropagation(); });
+ listen(window, 'resize', hide);
+ listen(accountsPane, 'scroll', hide, true);
+ listen(document, 'keydown', function (event) { if (event.key === 'Escape') hide(); });
+ listen(root, 'click', function (event) { if (event.target !== button && !button.contains(event.target)) hide(); });
+ registerDisposer(function () { hide(); popup.remove(); });
+ }
+
function closeSecureTransferModal(mask) {
if (mask && mask.parentNode) mask.parentNode.removeChild(mask);
}
@@ -4886,8 +5157,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
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">' +
@@ -5145,8 +5414,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
for (var j = 0; j < panes.length; j++) panes[j].classList.toggle('active', panes[j].getAttribute('data-pane') === name);
if (name === 'theme') {
if (themePane && !themePane.dataset.built) buildThemePane();
- var themeBtn = themePane && themePane.querySelector('.wbs-theme-opt.active');
- syncWallpaperCardVisibility(themeBtn ? themeBtn.getAttribute('data-theme') : 'default');
+ var themeBtn = themePane && themePane.querySelector('#wbs-theme-seg .wbs-theme-opt.active');
+ syncWallpaperCardVisibility(themeBtn ? themeBtn.getAttribute('data-wbs-theme-option') : 'default');
}
if (name === 'sessions' && sessionsPane && !sessionsPane.dataset.built) buildSessionsPane();
if (name === 'models' && modelsPane && !modelsPane.dataset.built) buildModelsPane();
@@ -5671,7 +5940,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<button class="wbs-sess-bbtn wbs-sess-done" type="button" id="wbs-sess-done">取消</button>' +
'</div>' +
'</div>' +
- '<input type="file" id="wbs-sess-import-file" accept=".json,application/json" style="display:none">' +
+ '<input type="file" id="wbs-sess-import-file" accept=".wds,.json,application/json,application/octet-stream" style="display:none">' +
'<div class="wbs-sess-list" id="wbs-sess-list"></div>' +
'</div>' +
'<div class="wbs-modal-mask" id="wbs-sess-modal" style="display:none">' +
@@ -6117,11 +6386,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
confirmText: '导出',
hint: '将加密导出 ' + ids.length + ' 个会话及其本地消息附件。',
onConfirm: function (password) { return api('/api/sessions/export', {
+ responseType: 'blob',
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ ids: ids, password: password }),
}).then(function (result) {
- downloadTransfer(result, 'WorkDaddy-sessions.json');
+ downloadTransfer(result, 'WorkDaddy-sessions-' + new Date().toISOString().slice(0, 10) + '.wds');
toast('已导出 ' + result.count + ' 个会话(已加密)', false, root);
}); },
});
@@ -6134,7 +6404,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var file = event.target && event.target.files && event.target.files[0];
event.target.value = '';
if (!file) return;
- readTransferFile(file).then(function (content) {
+ file.slice(0, 8).text().then(function (magic) {
+ return magic === 'WDS4\r\n\x1a\n' ? file : readTransferFile(file);
+ }).then(function (content) {
var targetUid = sessionsState.uid === '' ? '' : (sessionsState.uid || sessionsState.currentUid || '');
var target = sessionsState.accounts.find(function (account) { return account.uid === targetUid; });
openSecureTransferModal({
@@ -6143,11 +6415,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
confirmText: '导入',
keepOpenOnSuccess: true,
hint: targetUid ? '会话将导入到「' + ((target && target.nickname) || '当前账号') + '」。' : '会话将保留导出时的账号归属。',
- onConfirm: function (password) { return api('/api/sessions/import', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ content: content, password: password, targetUid: targetUid }),
- }).then(function (result) {
+ onConfirm: function (password) {
+ var binary = content === file;
+ var body;
+ if (binary) {
+ var metadata = new TextEncoder().encode(JSON.stringify({ password: password, targetUid: targetUid }));
+ var prefix = new Uint8Array(4);
+ new DataView(prefix.buffer).setUint32(0, metadata.length);
+ body = new Blob([prefix, metadata, file], { type: 'application/octet-stream' });
+ } else body = JSON.stringify({ content: content, password: password, targetUid: targetUid });
+ return api('/api/sessions/import', {
+ method: 'POST',
+ headers: { 'content-type': binary ? 'application/octet-stream' : 'application/json' },
+ body: body,
+ }).then(function (result) {
var count = Number(result.count || (result.imported && result.imported.length) || 0);
var lines = ['导入完成:成功 ' + count + ' 个会话'];
if (result.failed) lines.push('失败:' + result.failed + ' 个');
@@ -6841,27 +7122,29 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-pcard">' +
'<div class="wbs-pcard-title">主题外观</div>' +
'<div class="wbs-theme-seg" id="wbs-theme-seg">' +
- '<button class="wbs-theme-opt active" type="button" data-theme="default">默认</button>' +
- '<button class="wbs-theme-opt" type="button" data-theme="eye-care">护眼绿</button>' +
- '<button class="wbs-theme-opt" type="button" data-theme="cyber-purple">赛博紫</button>' +
- '<button class="wbs-theme-opt" type="button" data-theme="nebula">毛玻璃</button>' +
+ '<button class="wbs-theme-opt active" type="button" data-wbs-theme-option="default">浅色</button>' +
+ '<button class="wbs-theme-opt" type="button" data-wbs-theme-option="dark">深色</button>' +
+ '<button class="wbs-theme-opt" type="button" data-wbs-theme-option="eye-care">护眼绿</button>' +
+ '<button class="wbs-theme-opt" type="button" data-wbs-theme-option="cyber-purple">赛博紫</button>' +
+ '<button class="wbs-theme-opt" type="button" data-wbs-theme-option="nebula">毛玻璃</button>' +
'</div>' +
'</div>' +
'<div class="wbs-pcard wbs-avatar-card">' +
'<div class="wbs-pcard-title">头像</div>' +
'<div class="wbs-avatar-row">' +
- '<img class="wbs-avatar-preview" id="wbs-avatar-preview" alt="头像预览" title="点击恢复官方头像">' +
- '<button class="wbs-theme-upload" id="wbs-avatar-upload" type="button" title="上传图片替换左下角头像">更换头像</button>' +
- '<button class="wbs-theme-upload" id="wbs-avatar-reset" type="button" title="恢复 WorkBuddy 官方头像">恢复默认</button>' +
+ '<label class="wbs-avatar-option" title="WorkBuddy"><input type="radio" name="wbs-avatar-preset" value="workbuddy"><img data-avatar-image="workbuddy" alt="WorkBuddy"><span>WorkBuddy</span></label>' +
+ '<label class="wbs-avatar-option" title="WorkDaddy"><input type="radio" name="wbs-avatar-preset" value="workdaddy"><img data-avatar-image="workdaddy" alt="WorkDaddy"><span>WorkDaddy</span></label>' +
+ '<div class="wbs-avatar-custom-list" id="wbs-avatar-custom-list"></div>' +
+ '<button class="wbs-avatar-add" id="wbs-avatar-upload" type="button" title="添加头像" aria-label="添加头像"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg></button>' +
'<input type="file" id="wbs-avatar-file" accept="image/png,image/jpeg,image/webp" style="display:none">' +
'</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 class="wbs-theme-seg wbs-robot-seg" role="radiogroup" aria-label="机器人外观">' +
+ '<label class="wbs-theme-opt wbs-robot-option" title="白底黑眼"><input type="radio" name="wbs-robot-style" value="white"><span>白色</span></label>' +
+ '<label class="wbs-theme-opt wbs-robot-option" title="黑底白眼"><input type="radio" name="wbs-robot-style" value="black"><span>黑色</span></label>' +
+ '<label class="wbs-theme-opt wbs-robot-option" title="毛玻璃底与镂空眼睛"><input type="radio" name="wbs-robot-style" value="glass"><span>毛玻璃</span></label>' +
'</div>' +
'<div class="wbs-ask-row">' +
'<label class="wbs-ask-label" for="wbs-fab-auto-dock">自动贴边<span class="wbs-ask-hint">闲置 5 秒后收起,鼠标靠近即展开</span></label>' +
@@ -6898,6 +7181,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<label class="wbs-switch"><input type="checkbox" id="wbs-text-shadow" checked disabled><span class="wbs-switch-slider"></span></label>' +
'</div></div>';
wireThemePane();
+ applyAvatar();
}
// 增强 pane(构建:决策弹窗 + 开发者工具[默认隐藏,连点标题5次呼出])
function buildEnhancePane() {
@@ -7097,7 +7381,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>' +
@@ -7510,8 +7794,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function wireThemePane() {
themePane.querySelectorAll('input[name="wbs-robot-style"]').forEach(function (input) {
input.checked = input.value === fabAppearance.get();
+ input.closest('.wbs-theme-opt').classList.toggle('active', input.checked);
input.addEventListener('change', function () {
if (input.checked) fabAppearance.set(input.value);
+ themePane.querySelectorAll('input[name="wbs-robot-style"]').forEach(function (radio) { radio.closest('.wbs-theme-opt').classList.toggle('active', radio.checked); });
});
});
var shadowSwitch = themePane.querySelector('#wbs-text-shadow');
@@ -7540,19 +7826,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 主题选择:segmented 按钮直接切换
themePane.addEventListener('click', function (e) {
var t = e.target;
- var segBtn = t.closest ? t.closest('.wbs-theme-opt') : null;
+ var segBtn = t.closest ? t.closest('#wbs-theme-seg .wbs-theme-opt') : null;
if (segBtn) {
- var id = segBtn.getAttribute('data-theme');
+ var id = segBtn.getAttribute('data-wbs-theme-option');
// 不做 active 拦截:即使当前已是该主题也强制重新应用(保证「切换到默认主题=强制浅色 / 切换到 WorkDaddy 主题=强制深色」始终生效,面板状态与真实主题不一致时也能纠正)
- var previous = themePane.querySelector('.wbs-theme-opt.active');
- themePane.querySelectorAll('.wbs-theme-opt').forEach(function (b) { b.classList.toggle('active', b === segBtn); });
+ var previous = themePane.querySelector('#wbs-theme-seg .wbs-theme-opt.active');
+ themePane.querySelectorAll('#wbs-theme-seg .wbs-theme-opt').forEach(function (b) { b.classList.toggle('active', b === segBtn); });
syncWallpaperCardVisibility(id);
applyTheme(id).then(function () {
- var names = { 'default': '默认', 'nebula': WBS_BRAND + ' 主题', 'eye-care': '护眼绿', 'cyber-purple': '赛博紫' };
+ var names = { 'default': '浅色', 'dark': '深色', 'nebula': WBS_BRAND + ' 主题', 'eye-care': '护眼绿', 'cyber-purple': '赛博紫' };
toast('已应用主题「' + (names[id] || id) + '」', false, root);
}).catch(function (er) {
- themePane.querySelectorAll('.wbs-theme-opt').forEach(function (b) { b.classList.toggle('active', b === previous); });
- syncWallpaperCardVisibility(previous ? previous.getAttribute('data-theme') : 'default');
+ themePane.querySelectorAll('#wbs-theme-seg .wbs-theme-opt').forEach(function (b) { b.classList.toggle('active', b === previous); });
+ syncWallpaperCardVisibility(previous ? previous.getAttribute('data-wbs-theme-option') : 'default');
toast('应用主题失败: ' + (er.message || er), true, root);
});
return;
@@ -7566,26 +7852,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
var up = t.closest ? t.closest('#wbs-bg-upload, #wbs-theme-upload') : null;
if (up) { var f = themePane.querySelector('#wbs-theme-file'); if (f) f.click(); return; }
- var av = t.closest ? t.closest('#wbs-avatar-upload') : null;
- if (av) { var af = themePane.querySelector('#wbs-avatar-file'); if (af) af.click(); return; }
- var rs = t.closest ? t.closest('#wbs-avatar-reset') : null;
- if (rs) {
- try { localStorage.removeItem(AVATAR_KEY); } catch (_) {}
- applyAvatar();
- toast('已恢复官方头像', false, root);
- return;
- }
- // 点击头像预览 = 应用官方头像
- var pvEl = t.closest ? t.closest('#wbs-avatar-preview') : null;
- if (pvEl) {
- try { localStorage.removeItem(AVATAR_KEY); } catch (_) {}
- applyAvatar();
- toast('已应用官方头像', false, root);
+ var removeAvatar = t.closest ? t.closest('[data-avatar-delete]') : null;
+ if (removeAvatar) {
+ e.preventDefault();
+ try { avatarLibrary.remove(removeAvatar.getAttribute('data-avatar-delete')); applyAvatar(); }
+ catch (_) { toast('头像保存失败,请清理存储空间后重试', true, root); }
return;
}
+ var av = t.closest ? t.closest('#wbs-avatar-upload') : null;
+ if (av) { var af = themePane.querySelector('#wbs-avatar-file'); if (af) af.click(); return; }
});
themePane.addEventListener('change', function (e) {
var t = e.target;
+ if (t && t.name === 'wbs-avatar-preset') {
+ try { avatarLibrary.select(t.value); }
+ catch (_) { toast('头像保存失败,请清理存储空间后重试', true, root); }
+ applyAvatar();
+ return;
+ }
if (t && t.id === 'wbs-theme-file') {
var file = t.files && t.files[0];
if (!file) return;
@@ -7607,15 +7891,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
c.width = 96; c.height = 96;
c.getContext('2d').drawImage(imgEl, (imgEl.width - size) / 2, (imgEl.height - size) / 2, size, size, 0, 0, 96, 96);
var dataUrl = c.toDataURL('image/webp', 0.85);
- try { localStorage.setItem(AVATAR_KEY, dataUrl); } catch (_) {}
+ if (!alive) return;
+ avatarLibrary.add(dataUrl);
applyAvatar();
toast('头像已更新 ✓', false, root);
} catch (e) {
- toast('头像处理失败:' + String(e).slice(0, 50), true, root);
+ toast('头像保存失败,请清理存储空间后重试', true, root);
}
};
+ imgEl.onerror = function () { if (alive) toast('头像图片读取失败', true, root); };
imgEl.src = reader2.result;
};
+ reader2.onerror = function () { if (alive) toast('头像图片读取失败', true, root); };
reader2.readAsDataURL(f2);
t.value = '';
}
@@ -7838,6 +8125,98 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
+ var checkinRiskLoading = false;
+ var checkinRiskDone = false;
+ var checkinRiskClose = null;
+ registerDisposer(function () { if (checkinRiskClose) checkinRiskClose(); });
+
+ function showCheckinRiskOnOpen() {
+ if (!CAPS.accounts || CAPS.checkin === false || checkinRiskDone || checkinRiskLoading || checkinRiskClose) return;
+ checkinRiskLoading = true;
+ api('/api/automations/checkin-consent').then(function (result) {
+ if (!alive) return;
+ if (!result.shouldPrompt) { checkinRiskDone = true; return; }
+ if (!state.open) return;
+ var previousFocus = document.activeElement;
+ var mask = document.createElement('div');
+ mask.className = 'wbs-modal-mask wbs-modal-mask-panel wbs-checkin-risk-mask';
+ mask.innerHTML = '<div class="wbs-modal wbs-checkin-risk-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-checkin-risk-title" aria-describedby="wbs-checkin-risk-copy">' +
+ '<div class="wbs-modal-title" id="wbs-checkin-risk-title">自动签到提醒</div>' +
+ '<div class="wbs-modal-body" id="wbs-checkin-risk-copy"><p>开启后自动为已保存账号签到。</p>' +
+ '<p>请留意官方规则,自动操作可能影响账号使用。</p>' +
+ '<p>可随时在「自动化」中关闭。</p></div>' +
+ '<div class="wbs-checkin-risk-error" role="alert" hidden></div>' +
+ '<div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" data-checkin-choice="cancel">取消</button>' +
+ '<button class="wbs-modal-btn wbs-modal-ok" type="button" data-checkin-choice="enable">开启自动签到</button></div></div>';
+ var cancel = mask.querySelector('[data-checkin-choice="cancel"]');
+ var enable = mask.querySelector('[data-checkin-choice="enable"]');
+ var error = mask.querySelector('[role="alert"]');
+ var busy = false;
+ var closed = false;
+ function blockOutside(event) {
+ if (!mask.contains(event.target)) { event.preventDefault(); event.stopImmediatePropagation(); }
+ }
+ function keepFocus(event) {
+ if (!mask.contains(event.target)) { event.stopImmediatePropagation(); cancel.focus(); }
+ }
+ function keydown(event) {
+ if (event.key === 'Escape') {
+ event.preventDefault(); event.stopImmediatePropagation(); choose(false);
+ } else if (event.key === 'Tab') {
+ event.preventDefault(); event.stopImmediatePropagation();
+ if (busy) mask.querySelector('[role="dialog"]').focus();
+ else if (document.activeElement === cancel) enable.focus();
+ else if (document.activeElement === enable) cancel.focus();
+ else (event.shiftKey ? enable : cancel).focus();
+ } else blockOutside(event);
+ }
+ function close() {
+ if (closed) return;
+ closed = true;
+ ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick', 'contextmenu', 'wheel', 'touchstart', 'touchmove'].forEach(function (type) {
+ document.removeEventListener(type, blockOutside, true);
+ });
+ document.removeEventListener('keydown', keydown, true);
+ document.removeEventListener('focusin', keepFocus, true);
+ mask.remove();
+ checkinRiskClose = null;
+ if (alive && state.open && previousFocus && previousFocus.isConnected) previousFocus.focus();
+ }
+ function choose(enabled) {
+ if (busy || closed) return;
+ busy = true; cancel.disabled = true; enable.disabled = true; error.hidden = true;
+ mask.querySelector('[role="dialog"]').focus();
+ api('/api/automations/checkin-consent', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled: enabled }) }).then(function (result) {
+ if (!alive) return;
+ checkinRiskDone = true;
+ close();
+ if (result.enabled) window.dispatchEvent(new CustomEvent('workdaddy:accounts-updated'));
+ }).catch(function () {
+ if (closed || !alive) return;
+ busy = false; cancel.disabled = false; enable.disabled = false;
+ error.textContent = '保存失败,请重试。'; error.hidden = false;
+ cancel.focus();
+ });
+ }
+ mask.querySelector('[role="dialog"]').tabIndex = -1;
+ cancel.addEventListener('click', function () { choose(false); });
+ enable.addEventListener('click', function () { choose(true); });
+ ['click', 'dblclick', 'pointerdown', 'pointerup', 'mousedown', 'mouseup', 'keydown', 'keyup', 'keypress', 'wheel', 'touchstart', 'touchmove', 'contextmenu'].forEach(function (type) {
+ mask.addEventListener(type, function (event) { event.stopPropagation(); });
+ });
+ checkinRiskClose = close;
+ panel.appendChild(mask);
+ ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick', 'contextmenu', 'wheel', 'touchstart', 'touchmove'].forEach(function (type) {
+ document.addEventListener(type, blockOutside, { capture: true, passive: false });
+ });
+ document.addEventListener('keydown', keydown, true);
+ document.addEventListener('focusin', keepFocus, true);
+ cancel.focus();
+ }).catch(function () {
+ // No acknowledgement on a failed read; retry at the next user opening.
+ }).finally(function () { checkinRiskLoading = false; });
+ }
+
function setOpen(open, options) {
if (open && typeof closeRotationNotice === 'function') closeRotationNotice();
if (open && window.__wbsAutomationInputActive) {
@@ -7856,12 +8235,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
fab.classList.toggle('hidden', open); // 打开时隐藏按钮
fabQuietMode.wake();
if (open) {
+ if (newlyOpened && CAPS.accounts && !(options && options.automation)) showCheckinRiskOnOpen();
if (newlyOpened && !(options && options.automation)) api('/api/automations/events', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ type: 'panelOpened' }) }).catch(function () {});
refresh();
checkForUpdate(); // 打开面板即检测更新(每次打开都强制查一次新版本)
try { acCheckPromptOnOpen(); } catch (e) {} // 每次打开面板:指令块丢失则请求 daemon 补写(无 toast)
try { syncSessionModule(); } catch (e) {} // 每次打开面板刷新会话模块(开关+快捷短语,含外部修改)
} else {
+ if (typeof checkinRiskClose === 'function') checkinRiskClose();
state.accountRefreshId = (state.accountRefreshId || 0) + 1;
state.activityRunId++;
state.creditRunId++;
@@ -8128,7 +8509,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 主题 = CSS 变量覆盖(--wb-* / --dc-*),daemon 通过 CDP 注入 <style>。
// 只提供四个入口:官方主题(default) 与 WorkDaddy 官方主题(nebula)、官方内置深色主题(eye-care/cyber-purple)
// 默认选中「WorkBuddy 默认主题」(default):未设置/异常时回退到 default 而非 nebula(用户要求)
- var ALLOWED_THEMES = ['default', 'nebula', 'eye-care', 'cyber-purple'];
+ var ALLOWED_THEMES = ['default', 'dark', 'nebula', 'eye-care', 'cyber-purple'];
function loadThemes() {
api('/api/themes')
.then(function (d) {
@@ -8136,7 +8517,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!seg) return;
var cur = d.current && ALLOWED_THEMES.indexOf(d.current) >= 0 ? d.current : 'default';
seg.querySelectorAll('.wbs-theme-opt').forEach(function (b) {
- b.classList.toggle('active', b.getAttribute('data-theme') === cur);
+ b.classList.toggle('active', b.getAttribute('data-wbs-theme-option') === cur);
});
syncWallpaperCardVisibility(cur);
// 列表展示不能更改已保存的主题;主题只能由用户明确选择。
@@ -8154,8 +8535,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function themeSelectValue() {
var seg = root.querySelector('.wbs-theme-seg');
var act = seg ? seg.querySelector('.wbs-theme-opt.active') : null;
- var id = act ? act.getAttribute('data-theme') : null;
- return id && id !== 'default' ? id : 'nebula';
+ var id = act ? act.getAttribute('data-wbs-theme-option') : null;
+ return id && id !== 'default' && id !== 'dark' ? id : 'nebula';
}
// 页面主题由 daemon 在早期注入/加载时恢复;不要延迟 POST 旧主题,
// 否则旧页面的异步请求可能覆盖用户刚选择的主题。
@@ -8196,8 +8577,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
// ===== 头像(官方 footer-brand-logo SVG / 自定义上传,localStorage 持久化,定时保持)=====
- var AVATAR_KEY = 'wbsAvatar';
- // WorkBuddy 官方品牌 logo(footer-brand-logo),作为「官方头像」预览/选择/恢复默认的目标
+ var avatarLibrary = createAvatarLibrary({
+ getItem: function (key) { return localStorage.getItem(key); },
+ setItem: function (key, value) { localStorage.setItem(key, value); },
+ removeItem: function (key) { localStorage.removeItem(key); },
+ });
+ // WorkBuddy 官方品牌 logo(footer-brand-logo),作为 WorkBuddy 预设头像
var OFFICIAL_LOGO_SVG =
'<svg xmlns="http://www.w3.org/2000/svg" width="161" height="161" viewBox="0 0 161 161" fill="none">' +
'<g clip-path="url(#c0)">' +
@@ -8255,13 +8640,30 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
applyAvatar();
});
function applyAvatar() {
- var dataUrl = null;
- try { dataUrl = localStorage.getItem(AVATAR_KEY); } catch (_) {}
- var pv = root.querySelector('#wbs-avatar-preview');
+ if (!avatarLibrary) return;
+ var saved = avatarLibrary.snapshot();
+ var customList = root.querySelector('#wbs-avatar-custom-list');
+ if (customList) {
+ var signature = saved.items.map(function (item) { return item.id; }).join(',');
+ if (customList.getAttribute('data-items') !== signature) {
+ customList.innerHTML = saved.items.map(function (item) {
+ return '<div class="wbs-avatar-custom"><label class="wbs-avatar-option" title="自定义头像"><input type="radio" name="wbs-avatar-preset" value="' + escAttr(item.id) + '"><img data-avatar-image="' + escAttr(item.id) + '" src="' + escAttr(item.src) + '" alt="自定义头像"><span>自定义</span></label>' +
+ '<button class="wbs-avatar-delete" type="button" data-avatar-delete="' + escAttr(item.id) + '" title="删除头像" aria-label="删除头像"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7"/></svg></button></div>';
+ }).join('');
+ customList.setAttribute('data-items', signature);
+ }
+ }
+ var selected = saved.items.find(function (item) { return item.id === saved.selected; });
+ var choice = resolveAvatarChoice(selected ? selected.src : saved.selected, OFFICIAL_AVATAR, WBS_AVATAR_LOGO);
+ var target = choice.src;
var wrap = document.querySelector('.user-menu-trigger-avatar');
- // 目标头像:自定义 or 官方 logo
- var target = dataUrl || OFFICIAL_AVATAR;
- if (wrap) {
+ root.querySelectorAll('input[name="wbs-avatar-preset"]').forEach(function (input) {
+ input.checked = input.value === saved.selected;
+ var image = input.parentNode.querySelector('img');
+ var src = input.value === 'workbuddy' ? OFFICIAL_AVATAR : input.value === 'workdaddy' ? WBS_AVATAR_LOGO : null;
+ if (src && image.getAttribute('src') !== src) image.src = src;
+ });
+ if (wrap && target) {
rememberAvatarWrapper(wrap);
// 官方默认头像图片改用 visibility:hidden(保留占位与布局,仅不可见):
// 不能 display:none——头像容器尺寸由这张 img 撑开,display:none 会让容器塌陷成 0×0,
@@ -8297,11 +8699,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (app2) app2.remove();
}
}
- // 面板内头像预览(始终显示:官方 logo 或自定义)
- if (pv) {
- if (target) { pv.setAttribute('src', target); pv.style.display = 'block'; }
- else { pv.style.display = 'none'; pv.removeAttribute('src'); }
- }
}
// 头像上传按钮/文件输入位于主题 pane(构建后由 wireThemePane 事件委托处理)
// 定时保持:WorkBuddy 渲染/切会话会重置头像 src,2s 检查一次(无条件运行,不依赖按钮)
@@ -11147,17 +11544,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return '剩余 ' + Math.ceil(diff / day) + ' 天';
}
- function creditTone(ts) {
- var day = 24 * 3600 * 1000;
- if (!ts || Number(ts) - Date.now() > 30 * day) return 'safe';
- var diff = Number(ts) - Date.now();
- if (diff <= day) return 'within1';
- if (diff <= 3 * day) return 'within3';
- if (diff <= 7 * day) return 'within7';
- if (diff <= 15 * day) return 'within15';
- return 'within30';
- }
-
function creditTip(segment) {
var amount = fmtCredits(segment.remaining) + ' 积分';
var source = segment.source === 'meter' ? '基础用量'
@@ -11182,7 +11568,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var weight = Math.max(0.008, amount / total);
var tip = creditTip(segment);
var attrTip = esc(tip).replace(/"/g, '&quot;');
- return '<span class="wbs-credit-segment ' + creditTone(segment.expiresAt) + '" style="flex:' + weight.toFixed(4) + ' 1 0" data-tip="' + attrTip + '" aria-label="' + attrTip + '"></span>';
+ return '<span class="wbs-credit-segment" style="--wbs-credit-alpha:' + creditOpacity(segment.expiresAt ? (Number(segment.expiresAt) - Date.now()) / 86400000 : null).toFixed(5) + ';flex:' + weight.toFixed(4) + ' 1 0" data-tip="' + attrTip + '" aria-label="' + attrTip + '"></span>';
}).join('');
return '<div class="wbs-credit-bar" role="img" aria-label="积分到期分布">' + cells + '</div>';
}
@@ -11247,7 +11633,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
expiresAt: nearestCreditExpiry(account),
};
}).sort(function (a, b) {
- // 不再置顶当前账号:统一按积分到期时间升序(最近到期最前),无到期信息排最后
+ if (state.accountOrder && state.accountOrder.mode === 'fixed') {
+ var left = Number(a.account.sort) > 0 ? Number(a.account.sort) : Infinity;
+ var right = Number(b.account.sort) > 0 ? Number(b.account.sort) : Infinity;
+ return left === right ? a.index - b.index : left - right;
+ }
+ // 按积分到期时间升序,无到期信息排最后
if (a.expiresAt !== b.expiresAt) return a.expiresAt - b.expiresAt;
return a.index - b.index;
}).map(function (item) { return item.account; });
@@ -11291,7 +11682,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var rows = state.accounts.map(function (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]);
+ return JSON.stringify([state.current && state.current.uid, rows]);
}
function pollAutoCopyJob(jobId, accountName) {
@@ -11337,7 +11728,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
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 || '';
+ state.accountOrder = data.accountOrder || state.accountOrder || { mode: 'expiry' };
// 页面重载后还没有积分缓存,或刚切换账号:等本轮积分齐备后校正一次顺序。
if (currentChanged || (!previous.length && state.accounts.some(function (account) { return !Array.isArray(account.creditSegments); }))) {
state.accountSortPending = true;
@@ -11369,18 +11760,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 版本标签:个人账号显示「个人版」;企业账号显示企业名称(enterpriseName),缺省回退「企业」。
var editionBadge = a.type === 'personal' ? '个人版' : (a.enterpriseName ? a.enterpriseName : (a.type ? '企业' : ''));
var badge = editionBadge ? '<span class="wbs-badge">' + esc(editionBadge) + '</span>' : '';
- var isPrimary = a.uid === state.primaryUid;
- 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
+ var ops = (isCur
? ''
: (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>';
+ ops = '<div class="wbs-ops"' + (isCur ? ' hidden' : '') + '>' + ops + '</div>';
// 国际版没有手机号:用 UIN(账号唯一数字标识)替代展示;国内版仍显示手机。
// UIN 与手机号共用同一标签和值间距,确保与“剩余”额度列对齐。
var isUinMode = !a.phone;
@@ -11391,7 +11779,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 + invalidAuthBadge + '</div>' + ops + '</div>' +
+ '<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + esc(nameVal) + '</span>' + 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>' +
@@ -11400,31 +11788,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</div>';
list.appendChild(card);
});
- list.querySelectorAll('[data-primary-uid]').forEach(function (button) {
- button.addEventListener('click', function (e) {
- e.preventDefault(); e.stopPropagation();
- if (state.primarySaving || button.dataset.primaryUid === state.primaryUid) return;
- state.primarySaving = true;
- api('/api/accounts/primary', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ uid: button.dataset.primaryUid }) }).then(function (result) {
- state.primaryUid = result.primaryUid;
- toast('已设为主账号,自动化任务可据此识别主账号', false, root);
- list.querySelectorAll('[data-primary-uid]').forEach(function (item) {
- var selected = item.dataset.primaryUid === state.primaryUid;
- item.hidden = selected;
- var card = item.closest('.wbs-card');
- var mark = card.querySelector('.wbs-primary-mark');
- if (!selected && mark) mark.remove();
- if (selected && !mark) {
- mark = el('span', 'wbs-primary-mark');
- mark.setAttribute('role', 'img'); mark.setAttribute('aria-label', wbsTranslateString('主账号', WBS_LANGUAGE)); mark.title = wbsTranslateString('主账号', WBS_LANGUAGE);
- mark.innerHTML = PRIMARY_ACCOUNT_SVG;
- card.querySelector('.wbs-name').after(mark);
- }
- item.parentElement.hidden = Array.from(item.parentElement.querySelectorAll('button')).every(function (btn) { return btn.hidden; });
- });
- }).catch(function (error) { toast(error.message || '设置主账号失败', true, root); }).finally(function () { state.primarySaving = false; });
- });
- });
applyAccountMask();
// 切换按钮:两击确认(第一次点击进入确认态,3s 内再点才真正切换,防止误触)
list.querySelectorAll('.wbs-acc-switch').forEach(function (btn) {
@@ -11799,12 +12162,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// Completion events update existing rows without replacing the account list or scroll position.
var accountRefreshPending = false;
listen(window, 'workdaddy:accounts-updated', function () {
- if (!state.open || accountRefreshPending) return;
+ if (!alive || !state.open || accountRefreshPending) return;
accountRefreshPending = true;
setBuildTimeout(function () {
accountRefreshPending = false;
if (!state.open) return;
- api('/api/accounts').then(function (data) { if (state.open) updateCheckinCells(data.accounts || []); }).catch(function () {});
+ api('/api/accounts').then(function (data) { if (alive && state.open) updateCheckinCells(data.accounts || []); }).catch(function () {});
}, 150);
});
@@ -12343,19 +12706,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-credit-segment:first-child:last-child{border-radius:3px}',
'.wbs-credit-segment:hover{z-index:3;filter:brightness(1.12);transform:scaleY(1.35)}',
/* 官方 WorkBuddy 主题:绿色梯度;越接近到期透明度越高,1 天内只保留很轻的颜色痕迹 */
- '.wbs-credit-segment.safe{background:rgba(34,197,94,.78);border-color:rgba(34,197,94,.78)}',
- '.wbs-credit-segment.within30{background:rgba(34,197,94,.62);border-color:rgba(34,197,94,.62)}',
- '.wbs-credit-segment.within15{background:rgba(34,197,94,.46);border-color:rgba(34,197,94,.46)}',
- '.wbs-credit-segment.within7{background:rgba(34,197,94,.32);border-color:rgba(34,197,94,.32)}',
- '.wbs-credit-segment.within3{background:rgba(34,197,94,.20);border-color:rgba(34,197,94,.20)}',
- '.wbs-credit-segment.within1{background:rgba(34,197,94,.10);border-color:rgba(34,197,94,.10)}',
- /* WorkDaddy 主题:蓝紫色梯度,保持深色背景上的柔和对比 */
- 'html.cb-dark .wbs-credit-segment.safe{background:rgba(126,134,255,.82);border-color:rgba(126,134,255,.82)}',
- 'html.cb-dark .wbs-credit-segment.within30{background:rgba(126,134,255,.68);border-color:rgba(126,134,255,.68)}',
- 'html.cb-dark .wbs-credit-segment.within15{background:rgba(126,134,255,.54);border-color:rgba(126,134,255,.54)}',
- 'html.cb-dark .wbs-credit-segment.within7{background:rgba(126,134,255,.40);border-color:rgba(126,134,255,.40)}',
- 'html.cb-dark .wbs-credit-segment.within3{background:rgba(126,134,255,.25);border-color:rgba(126,134,255,.25)}',
- 'html.cb-dark .wbs-credit-segment.within1{background:rgba(126,134,255,.12);border-color:rgba(126,134,255,.12)}',
+ '.wbs-credit-segment,.wbs-credit-summary-fill{background:rgba(34,197,94,var(--wbs-credit-alpha,1));border-color:rgba(34,197,94,var(--wbs-credit-alpha,1))}',
+ 'html.cb-dark :is(.wbs-credit-segment,.wbs-credit-summary-fill),html[data-theme="dark"] :is(.wbs-credit-segment,.wbs-credit-summary-fill),body[data-vscode-theme-name="IDE Night"] :is(.wbs-credit-segment,.wbs-credit-summary-fill){background:rgba(126,134,255,var(--wbs-credit-alpha,1));border-color:rgba(126,134,255,var(--wbs-credit-alpha,1))}',
'.wbs-credit-tooltip{display:none;position:fixed;z-index:2147483647;min-width:170px;max-width:260px;padding:8px 10px;border-radius:7px;background:#151518;color:#fff;font-size:11px;font-weight:500;line-height:1.55;white-space:pre-line;box-shadow:0 8px 22px rgba(0,0,0,.28);pointer-events:none}',
'.wbs-credit-empty{height:5px;border-radius:0;background:color-mix(in srgb,var(--wb-bg-tertiary,#e8e8eb) 70%,transparent);color:var(--wb-icon-tertiary,#999);font-size:10px;line-height:5px;text-align:center}',
'.wbs-credit-hint{color:var(--wb-icon-tertiary,#999);font-size:10px;line-height:1.4;margin-top:2px}',
@@ -12416,7 +12768,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-robot-option{position:relative;text-align:center;line-height:normal}.wbs-robot-option input{position:absolute;opacity:0;width:1px;height:1px}.wbs-robot-option:has(input:focus-visible){outline:2px solid var(--wb-icon-secondary);outline-offset:1px}',
'.wbs-fab-settings .wbs-switch-slider{background:var(--wb-bg-tertiary,#e5e5e5);box-shadow:inset 0 0 0 1px var(--wb-border-default,#d0d0d0)}.wbs-fab-settings .wbs-switch-slider:before{background:var(--wb-color-text-secondary,#777)}.wbs-fab-settings input:checked + .wbs-switch-slider{background:var(--wb-button-primary-bg,#1f1f1f)}.wbs-fab-settings input:checked + .wbs-switch-slider:before{background:var(--wb-button-primary-fg,#fff)}.wbs-fab-settings input:focus-visible + .wbs-switch-slider{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:3px}',
'.wbs-switch{position:relative;display:inline-block;width:36px;height:20px;flex-shrink:0;cursor:pointer}',
'.wbs-switch input{opacity:0;width:0;height:0}',
@@ -12534,7 +12886,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-pcard{background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 18%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:14px;padding:10px 12px;margin-bottom:8px;backdrop-filter:blur(16px) saturate(1.2);-webkit-backdrop-filter:blur(16px) saturate(1.2)}',
'.wbs-pcard-title{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);margin-bottom:8px}',
'.wbs-pcard-sub{font-size:11px;color:var(--wb-icon-tertiary,#999);font-weight:400}',
- '.wbs-primary-mark{display:inline-flex;align-items:center;justify-content:center;flex:0 0 20px;width:20px;height:20px;border-radius:6px;color:var(--wb-button-primary-bg,#1f1f1f);background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 10%,transparent)}.wbs-primary-mark svg{width:14px;height:14px}.wbs-set-primary[hidden],.wbs-ops[hidden]{display:none!important}.wbs-set-primary:hover{color:var(--wb-button-primary-bg,#1f1f1f);background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 12%,transparent)}.wbs-set-primary:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}',
'.wbs-auto-card{display:flex;flex:1;flex-direction:column;min-height:0;margin-bottom:0}',
'.wbs-auto-toolbar{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:6px;flex-shrink:0}.wbs-auto-toolbar .wbs-pcard-title{margin-bottom:0}.wbs-auto-toolbar>.wbs-auto-toolbar-actions{flex-basis:100%;justify-content:flex-start}.wbs-auto-toolbar .wbs-sess-bbtn{font-size:11px;padding:5px 8px}',
'.wbs-auto-toolbar-actions,.wbs-auto-editor-actions,.wbs-auto-normal-actions,.wbs-auto-batch-actions{display:flex;align-items:center;gap:6px;flex-wrap:wrap}.wbs-auto-toolbar-actions{justify-content:flex-end}.wbs-auto-log-head-actions{display:flex;align-items:center;gap:8px}',
@@ -12767,6 +13118,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'html.cb-dark .wbs-modal-btn.wbs-modal-danger,html[data-theme="dark"] .wbs-modal-btn.wbs-modal-danger{color:#fff;background:#e03d3d;border-color:#e03d3d}',
'html.cb-dark .wbs-modal-btn.wbs-modal-danger:hover,html[data-theme="dark"] .wbs-modal-btn.wbs-modal-danger:hover{background:#f04a4a}',
'html.cb-dark .wbs-modal-mask,html[data-theme="dark"] .wbs-modal-mask{background:rgba(0,0,0,.55)}',
+ '.wbs-checkin-risk-mask{padding:12px;box-sizing:border-box;pointer-events:auto}',
+ '.wbs-modal.wbs-checkin-risk-modal{box-sizing:border-box;width:360px;max-width:100%;max-height:100%;display:flex;flex-direction:column;min-height:0}',
+ '.wbs-checkin-risk-modal .wbs-modal-title,.wbs-checkin-risk-modal .wbs-modal-actions{flex-shrink:0}',
+ '.wbs-checkin-risk-modal .wbs-modal-body{min-height:0;max-height:none;line-height:1.65;font-size:12px;overflow-wrap:anywhere;overscroll-behavior:contain}',
+ '.wbs-checkin-risk-modal p{margin:0}.wbs-checkin-risk-modal .wbs-modal-actions{flex-wrap:wrap}',
+ '.wbs-checkin-risk-modal .wbs-modal-btn{line-height:1.4;white-space:normal;transition:background .15s,color .15s,border-color .15s}',
+ '.wbs-checkin-risk-modal .wbs-modal-btn.wbs-modal-ok{background:var(--wb-button-primary-bg,#141416);color:var(--wb-button-primary-fg,#fff);border-color:var(--wb-button-primary-bg,#141416)}',
+ '.wbs-checkin-risk-modal .wbs-modal-btn.wbs-modal-ok:hover{background:var(--wb-button-primary-hover-bg,var(--wb-button-primary-bg,#2a2a2e))}',
+ '.wbs-checkin-risk-modal .wbs-modal-btn:focus-visible{outline:2px solid var(--wb-color-text-primary,#1f1f1f);outline-offset:2px}',
+ '.wbs-checkin-risk-modal .wbs-modal-btn:disabled{opacity:.55;cursor:wait}',
+ '.wbs-checkin-risk-error{font-size:12px;line-height:1.5;overflow-wrap:anywhere;margin-bottom:10px;color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-modal-title{font-size:13px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);margin-bottom:10px}',
'.wbs-modal-body{display:flex;flex-direction:column;gap:6px;max-height:280px;overflow-y:auto;margin-bottom:12px}',
'.wbs-modal-action{display:block;width:100%;text-align:left;padding:8px 10px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font-size:12px;cursor:pointer;line-height:1;transition:all .15s}',
@@ -12891,19 +13253,30 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-bg-upload-ico{width:30px;height:30px;border-radius:50%;background:var(--wb-bg-hover,#e8e9eb);display:flex;align-items:center;justify-content:center;font-size:18px;line-height:1;font-weight:400}',
'.wbs-bg-upload-hint{font-size:11px;color:var(--wb-icon-tertiary,#999);font-weight:400}',
'.wbs-bg-preview{display:none;width:100%;max-height:140px;object-fit:cover;border-radius:10px;margin-top:8px;border:1px solid var(--wb-border-subtle,#eee)}',
- '.wbs-avatar-preview{width:32px;height:32px;border-radius:50%;object-fit:cover;border:1px solid var(--wb-border-subtle,#eee);display:none;flex-shrink:0;background:var(--wb-bg-tertiary,#f0f0f0);cursor:pointer;transition:transform .15s}',
- '.wbs-avatar-preview:hover{transform:scale(1.08)}',
+ '.wbs-avatar-option{position:relative;display:flex;flex-direction:column;align-items:center;gap:4px;cursor:pointer;font-size:10px;color:var(--wb-color-text-secondary)}.wbs-avatar-option input{position:absolute;opacity:0;width:1px;height:1px}.wbs-avatar-option img{box-sizing:border-box;width:42px;height:42px;padding:3px;object-fit:contain;border:1px solid var(--wb-border-subtle);border-radius:10px;background:var(--wb-bg-tertiary)}.wbs-avatar-option input:checked+img{border-color:var(--wb-button-primary-bg);box-shadow:0 0 0 1px var(--wb-button-primary-bg)}.wbs-avatar-option input:focus-visible+img{outline:2px solid var(--wb-accent-blue);outline-offset:3px}',
/* 背景蒙版滑块(黑色半透明遮罩,0~100%) */
'.wbs-mask-row{display:flex;align-items:center;gap:8px;margin-top:8px}',
'.wbs-mask-row input[type=range]{flex:1;min-width:0;accent-color:#f2f2f4;height:4px;cursor:pointer}',
'.wbs-mask-val{font-size:11px;color:var(--wb-icon-tertiary,#888);flex-shrink:0;min-width:28px;text-align:right;font-variant-numeric:tabular-nums}',
/* 头像/增强行 */
- '.wbs-avatar-row{display:flex;align-items:center;gap:8px;margin-bottom:10px}',
+ '.wbs-avatar-row{display:flex;align-items:flex-start;flex-wrap:wrap;gap:12px;margin-bottom:10px}.wbs-avatar-custom-list{display:contents}.wbs-avatar-custom{position:relative}.wbs-avatar-add{box-sizing:border-box;display:flex;align-items:center;justify-content:center;flex:0 0 42px;width:42px;height:42px;padding:3px;border:1px dashed var(--wb-border-default);border-radius:10px;background:var(--wb-bg-tertiary);color:var(--wb-icon-secondary);cursor:pointer}.wbs-avatar-add:hover{background:var(--wb-bg-hover)}.wbs-avatar-add:focus-visible,.wbs-avatar-delete:focus-visible{outline:2px solid var(--wb-icon-secondary);outline-offset:2px}.wbs-avatar-delete{position:absolute;top:-6px;right:-6px;display:flex;align-items:center;justify-content:center;width:20px;height:20px;padding:0;border:1px solid var(--wb-border-default);border-radius:50%;background:var(--wb-bg-popover);color:var(--wb-color-text-primary);cursor:pointer;opacity:0;pointer-events:none}.wbs-avatar-custom:hover .wbs-avatar-delete,.wbs-avatar-custom:focus-within .wbs-avatar-delete{opacity:1;pointer-events:auto}',
'.wbs-tab svg{flex-shrink:0}',
'.wbs-enh-row{display:flex;gap:8px;margin-bottom:8px}',
'.wbs-enh-tip{font-size:11px;color:var(--wb-icon-tertiary,#999);line-height:1.5;padding:4px 2px 0}',
/* 账号列表容器 + 退出按钮 */
'.wbs-acct-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 14px 9px;border-bottom:1px solid var(--wb-border-subtle,#f0f0f0);background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 25%,transparent);flex-shrink:0}',
+ '#wbs-account-order-mask{pointer-events:auto;overscroll-behavior:contain}',
+ '.wbs-account-order-modal{box-sizing:border-box;width:360px;max-width:calc(100% - 28px);max-height:calc(100% - 28px);display:flex;flex-direction:column;overflow:auto}',
+ '.wbs-account-order-modes{display:flex;flex-wrap:wrap;gap:10px 16px;font-size:12px}.wbs-account-order-modes label{display:flex;align-items:center;gap:5px;cursor:pointer}.wbs-account-order-modes input{margin:0;accent-color:var(--wb-button-primary-bg)}',
+
+ '.wbs-account-order-list{margin-top:12px;max-height:min(280px,40vh);overflow:auto;overscroll-behavior:contain;display:flex;flex-direction:column;gap:5px}',
+ '.wbs-account-order-row{display:flex;align-items:center;gap:8px;min-height:34px;padding:3px 8px;border:1px solid var(--wb-border-subtle);border-radius:8px;background:var(--wb-bg-secondary);font-size:12px}.wbs-account-order-row>span{flex:1;min-width:0;overflow-wrap:anywhere}.wbs-account-order-row button{cursor:grab}.wbs-account-order-row.dragging{opacity:.45}.wbs-account-order-row.drop-target{border-color:var(--wb-accent-blue);background:var(--wb-bg-hover)}',
+ '.wbs-account-order-modal :is(button,input):focus-visible{outline:2px solid var(--wb-accent-blue);outline-offset:2px}.wbs-account-order-modal button:disabled{opacity:.5;cursor:default}',
+ '.wbs-credit-summary-popover{position:fixed;z-index:2147483647;box-sizing:border-box;width:300px;max-width:calc(100vw - 16px);padding:12px;background:var(--wb-bg-popover,var(--wb-bg-primary));color:var(--wb-color-text-primary);border:1px solid var(--wb-border-default);border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.18);font:12px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overflow:auto;overscroll-behavior:contain;pointer-events:auto}',
+ '.wbs-credit-summary-head{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px}.wbs-credit-summary-head strong{font-size:13px}.wbs-credit-summary-head span,.wbs-credit-summary-foot{font-size:10px;color:var(--wb-color-text-secondary)}',
+ '.wbs-credit-summary-chart{max-height:230px;overflow:auto;overscroll-behavior:contain}.wbs-credit-summary-row{display:grid;grid-template-columns:68px minmax(30px,1fr) 58px;align-items:center;gap:8px;min-height:28px}.wbs-credit-summary-row>span{font-size:11px;color:var(--wb-color-text-secondary)}.wbs-credit-summary-row>b{text-align:right;font-size:11px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.wbs-credit-summary-track{height:8px;border-radius:4px;background:var(--wb-bg-tertiary);overflow:hidden}.wbs-credit-summary-track i{display:block;height:100%;border-radius:4px;}.wbs-credit-summary-foot{border-top:1px solid var(--wb-border-subtle);padding-top:8px;margin-top:8px}',
+ 'html.cb-dark .wbs-credit-summary-popover,html[data-theme="dark"] .wbs-credit-summary-popover,body[data-vscode-theme-name="IDE Night"] .wbs-credit-summary-popover{background:var(--wb-bg-popover,var(--wb-bg-primary));color:var(--wb-color-text-primary);border-color:var(--wb-border-default)}',
+ '@media(max-width:600px){.wbs-acct-toolbar{flex-wrap:wrap;gap:8px}.wbs-acct-summary{flex-wrap:wrap}.wbs-acct-actions{margin-left:auto}}',
'.wbs-acct-summary{display:flex;align-items:center;gap:12px;min-width:0}',
'.wbs-acct-eye{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;padding:0;border:none;border-radius:6px;background:transparent;color:var(--wb-icon-secondary,var(--wb-color-text-secondary,#666));cursor:pointer;flex-shrink:0;transition:color .15s,background-color .15s}',
'.wbs-acct-eye:hover{background:var(--wb-bg-hover,#f0f0f0);color:var(--wb-color-text,#222)}',
@@ -12947,7 +13320,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.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-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-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)}',
@@ -12956,7 +13329,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.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)}}',
/* 登录新账号二选一弹窗(方法一 假退出 / 方法二 无感登录) */
diff --git a/scripts/lib.js b/scripts/lib.js
index b29b48f..9ad6fb4 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -1215,6 +1215,7 @@ function updateMeta(dataDir, info, { preserveBinding = false } = {}) {
authFileName,
authDomain: info.authDomain || prev.authDomain || '',
authIssuer: info.authIssuer || prev.authIssuer || '',
+ sort: Number.isSafeInteger(prev.sort) && prev.sort > 0 ? prev.sort : 0,
firstSeen: prev.firstSeen || now,
lastSeen: now,
};
@@ -1298,6 +1299,30 @@ function resolveAuthTarget(dataDir, uid, authJson) {
throw new Error('账号缺少已确认的登录文件名,拒绝猜测写入目标');
}
+/** 账号展示顺序保存在 profile 元数据中,不改写登录备份格式。0 表示未排序,排在末尾。 */
+function getAccountOrder(dataDir) {
+ return { mode: readMeta(dataDir).accountOrderMode === 'fixed' ? 'fixed' : 'expiry' };
+}
+
+function setAccountOrder(dataDir, value) {
+ if (!value || !['expiry', 'fixed'].includes(value.mode) || !Array.isArray(value.uids) ||
+ value.uids.length > 10000 || value.uids.some(uid => typeof uid !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(uid)) ||
+ new Set(value.uids).size !== value.uids.length) throw new Error('无效的账号排序设置');
+ const current = new Set(listAccounts(dataDir).map(account => account.uid));
+ const meta = readMeta(dataDir);
+ for (const account of Object.values(meta.accounts)) {
+ if (account && typeof account === 'object') delete account.sort;
+ }
+ let sort = 0;
+ for (const uid of value.uids) {
+ if (!current.has(uid)) continue; // 弹窗打开后删除的账号不能复活。
+ meta.accounts[uid] = Object.assign({}, meta.accounts[uid], { sort: ++sort });
+ }
+ meta.accountOrderMode = value.mode;
+ writeMeta(dataDir, meta);
+ return getAccountOrder(dataDir);
+}
+
/** 列出所有已备份账号(直接读备份文件提取展示字段,按最近刷新时间倒序) */
function listAccounts(dataDir) {
if (!ACTIVE_PROFILE.capabilities.accounts) return [];
@@ -1311,10 +1336,13 @@ function listAccounts(dataDir) {
} catch (_) {
/* 目录不存在 */
}
+ const orderMeta = readMeta(dataDir);
const list = names.map((n) => {
const uid = n.replace(/\.info$/, '');
+ const savedSort = orderMeta.accounts[uid] && orderMeta.accounts[uid].sort;
const item = {
uid,
+ sort: Number.isSafeInteger(savedSort) && savedSort > 0 ? savedSort : 0,
nickname: '',
phone: '',
uin: '',
@@ -1494,6 +1522,8 @@ function switchTo(dataDir, uid, log = () => {}) {
}
module.exports = {
+ getAccountOrder,
+ setAccountOrder,
readModelsFile,
writeModelsFile,
writeModelBackup,
diff --git a/scripts/session-transfer.js b/scripts/session-transfer.js
new file mode 100644
index 0000000..a2c2888
--- /dev/null
+++ b/scripts/session-transfer.js
@@ -0,0 +1,189 @@
+'use strict';
+
+// v4 session archives: authenticated header + AES-GCM(gzip(framed records/files)).
+// Only small metadata is buffered. Attachment bytes never become a JS string.
+const fs = require('node:fs');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const zlib = require('node:zlib');
+const { Readable } = require('node:stream');
+const { pipeline } = require('node:stream/promises');
+const { requiredPassword, remapSessionArchivePath } = require('./secure-transfer');
+const MAGIC = Buffer.from('WDS4\r\n\x1a\n');
+const HEADER_SIZE = 52;
+const MAX_METADATA = 1024 * 1024;
+const MAX_FILES = 20000;
+
+function frame(value) {
+ const data = Buffer.from(JSON.stringify(value));
+ if (data.length > MAX_METADATA) throw new Error('会话归档元数据过大');
+ const prefix = Buffer.alloc(4); prefix.writeUInt32BE(data.length);
+ return Buffer.concat([prefix, data]);
+}
+
+// Exact reads and bounded copies over a single iterator, including HTTP uploads.
+class ChunkReader {
+ constructor(stream) { this.iterator = stream[Symbol.asyncIterator](); this.chunk = Buffer.alloc(0); this.offset = 0; }
+ async available() {
+ while (this.offset === this.chunk.length) {
+ const next = await this.iterator.next();
+ if (next.done) return false;
+ this.chunk = Buffer.from(next.value); this.offset = 0;
+ }
+ return true;
+ }
+ async *take(size) {
+ while (size > 0) {
+ if (!await this.available()) throw new Error('会话归档不完整或已损坏');
+ const length = Math.min(size, this.chunk.length - this.offset);
+ const data = this.chunk.subarray(this.offset, this.offset + length);
+ this.offset += length; size -= length;
+ yield data;
+ }
+ }
+ async read(size) {
+ const parts = [];
+ for await (const part of this.take(size)) parts.push(part);
+ return Buffer.concat(parts, size);
+ }
+ async metadata() {
+ const size = (await this.read(4)).readUInt32BE();
+ if (!size || size > MAX_METADATA) throw new Error('会话归档元数据无效');
+ try { return JSON.parse((await this.read(size)).toString('utf8')); }
+ catch (_) { throw new Error('会话归档元数据无效'); }
+ }
+ async *rest() {
+ while (await this.available()) {
+ const data = this.chunk.subarray(this.offset); this.offset = this.chunk.length;
+ yield data;
+ }
+ }
+ async close() { if (this.iterator.return) await this.iterator.return(); }
+}
+
+async function* archiveChunks(sessions) {
+ yield frame({ type: 'archive', version: 4, count: sessions.length });
+ for (const session of sessions) {
+ yield frame({ type: 'session', record: session.record, count: session.files.length });
+ for (const file of session.files) {
+ remapSessionArchivePath(file.path, session.record.id, session.record.id);
+ const handle = await fs.promises.open(file.source, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size !== file.size) throw new Error('会话附件发生变化,请重新导出');
+ yield frame({ type: 'file', path: file.path, size: stat.size });
+ let total = 0;
+ if (stat.size) {
+ for await (const chunk of handle.createReadStream({ autoClose: false, start: 0, end: stat.size - 1 })) {
+ total += chunk.length; yield chunk;
+ }
+ }
+ const after = await handle.stat();
+ if (total !== stat.size || after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) throw new Error('会话附件发生变化,请重新导出');
+ } finally { await handle.close(); }
+ }
+ }
+}
+
+async function writeSessionTransfer(file, sessions, password) {
+ requiredPassword(password);
+ if (!Array.isArray(sessions) || !sessions.length || sessions.length > 100) throw new Error('单次最多导出 100 个会话');
+ const header = Buffer.alloc(HEADER_SIZE); MAGIC.copy(header);
+ crypto.randomFillSync(header, 8, 28);
+ const key = crypto.scryptSync(password, header.subarray(8, 24), 32);
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, header.subarray(24, 36));
+ cipher.setAAD(header.subarray(0, 36));
+ let created = false;
+ try {
+ await fs.promises.writeFile(file, header, { flag: 'wx', mode: 0o600 }); created = true;
+ await pipeline(Readable.from(archiveChunks(sessions)), zlib.createGzip(), cipher,
+ fs.createWriteStream(file, { flags: 'r+', start: HEADER_SIZE }));
+ const handle = await fs.promises.open(file, 'r+');
+ try { await handle.write(cipher.getAuthTag(), 0, 16, 36); } finally { await handle.close(); }
+ } catch (error) {
+ if (created) await fs.promises.rm(file, { force: true });
+ throw error;
+ }
+}
+
+async function readSessionTransfer(file, password, staging) {
+ requiredPassword(password);
+ // Unique private staging is owned by this operation and removed on every failure.
+ await fs.promises.mkdir(staging, { mode: 0o700 });
+ const compressed = path.join(staging, 'authenticated.gz');
+ try {
+ const handle = await fs.promises.open(file, 'r');
+ const header = Buffer.alloc(HEADER_SIZE);
+ try {
+ const { bytesRead } = await handle.read(header, 0, HEADER_SIZE, 0);
+ if (bytesRead !== HEADER_SIZE || !header.subarray(0, 8).equals(MAGIC)) throw new Error('不是有效的 WorkDaddy 会话归档');
+ } finally { await handle.close(); }
+ const key = crypto.scryptSync(password, header.subarray(8, 24), 32);
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, header.subarray(24, 36));
+ decipher.setAAD(header.subarray(0, 36)); decipher.setAuthTag(header.subarray(36, 52));
+ // Verify the complete authentication tag before decompressing or restoring anything.
+ try {
+ await pipeline(fs.createReadStream(file, { start: HEADER_SIZE }), decipher,
+ fs.createWriteStream(compressed, { flags: 'wx', mode: 0o600 }));
+ } catch (error) {
+ if (['ENOSPC', 'EACCES', 'EIO'].includes(error.code)) throw error;
+ throw new Error('密码错误或导出文件已损坏');
+ }
+ const input = fs.createReadStream(compressed), gunzip = zlib.createGunzip();
+ const pumping = pipeline(input, gunzip);
+ // Attach rejection immediately; the reader also surfaces the stream failure.
+ pumping.catch(() => {});
+ const reader = new ChunkReader(gunzip), sessions = [];
+ try {
+ const root = await reader.metadata();
+ if (root.type !== 'archive' || root.version !== 4 || !Number.isInteger(root.count) || root.count < 1 || root.count > 100) throw new Error('会话归档元数据无效');
+ const ids = new Set();
+ for (let i = 0; i < root.count; i++) {
+ const meta = await reader.metadata();
+ const id = meta.record && meta.record.id;
+ if (meta.type !== 'session' || typeof id !== 'string' || !id || id.length > 200 || /[\x00-\x20/\\]/.test(id)
+ || ids.has(id) || !Number.isInteger(meta.count) || meta.count < 0 || meta.count > MAX_FILES) throw new Error('会话归档元数据无效');
+ ids.add(id);
+ const files = [], paths = new Set();
+ for (let j = 0; j < meta.count; j++) {
+ const entry = await reader.metadata();
+ if (entry.type !== 'file' || !Number.isSafeInteger(entry.size) || entry.size < 0) throw new Error('会话归档包含无效附件');
+ const relative = remapSessionArchivePath(entry.path, id, id);
+ if (paths.has(relative)) throw new Error('会话归档包含重复附件路径');
+ paths.add(relative);
+ const source = path.join(staging, `${i}-${j}.bin`);
+ await pipeline(Readable.from(reader.take(entry.size)), fs.createWriteStream(source, { flags: 'wx', mode: 0o600 }));
+ files.push({ path: relative, size: entry.size, source });
+ }
+ sessions.push({ record: meta.record, files });
+ }
+ if (await reader.available()) throw new Error('会话归档包含多余数据');
+ await pumping;
+ await fs.promises.unlink(compressed);
+ return { exportType: 'WorkDaddy-sessions', version: 4, sessions };
+ } finally {
+ gunzip.destroy(); input.destroy();
+ await reader.close(); await pumping.catch(() => {});
+ }
+ } catch (error) {
+ await fs.promises.rm(staging, { recursive: true, force: true });
+ throw error;
+ }
+}
+
+async function receiveSessionUpload(input, directory) {
+ const reader = new ChunkReader(input);
+ const meta = await reader.metadata();
+ requiredPassword(meta.password);
+ if (meta.targetUid !== undefined && typeof meta.targetUid !== 'string') throw new Error('无效的账号归属');
+ const file = path.join(directory, crypto.randomUUID() + '.wds');
+ try {
+ await pipeline(Readable.from(reader.rest()), fs.createWriteStream(file, { flags: 'wx', mode: 0o600 }));
+ return { file, password: meta.password, targetUid: meta.targetUid };
+ } catch (error) {
+ await fs.promises.rm(file, { force: true });
+ throw error;
+ }
+}
+
+module.exports = { writeSessionTransfer, readSessionTransfer, receiveSessionUpload };
diff --git a/scripts/token-stats.js b/scripts/token-stats.js
index aacbc94..b100e2b 100644
--- a/scripts/token-stats.js
+++ b/scripts/token-stats.js
@@ -2,6 +2,7 @@
const fs = require('fs');
const path = require('path');
+const { createHash } = require('node:crypto');
const TOKEN_FIELDS = {
input: ['input_tokens', 'prompt_tokens', 'inputTokens', 'promptTokens'],
@@ -86,7 +87,7 @@ function timestampValue(value, fallback) {
return fallback;
}
-const CACHE_VERSION = 7;
+const CACHE_VERSION = 8;
const MAX_CACHE_DAYS = 90;
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -111,7 +112,6 @@ function parseRecords(root, options = {}) {
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;
@@ -127,21 +127,21 @@ function parseRecords(root, options = {}) {
}
let text;
try { text = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }
- let lineIndex = 0;
+ const occurrences = new Map();
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)) {
+ if (options.legacyParseErrors ? /^\s*[\[{]/.test(line) :
+ /^\s*\{/.test(line) && /"(?:usage|input_tokens|output_tokens|model)"/i.test(line)) {
parseErrors++;
parseErrorFiles.add(relative);
}
continue;
}
- if (record.isSnapshotUpdate) continue;
+ if (!record || typeof record !== 'object' || 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);
@@ -152,19 +152,19 @@ function parseRecords(root, options = {}) {
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, '');
- }
+ const account = findText(record, ['accountUid', 'accountId', 'uid', 'userId']) || findText(usage, ['accountUid', 'accountId', 'uid', 'userId']);
+ // Imports/copies preserve the entire JSONL row. Hash the whole record,
+ // not just requestId or token totals: a request can have multiple usage
+ // rows, and different calls can have identical token counts. Only the
+ // digest and usage metadata enter the cache; never persist message text.
+ const digest = createHash('sha256').update(JSON.stringify(record)).digest('hex');
+ const occurrence = (occurrences.get(digest) || 0) + 1;
+ occurrences.set(digest, occurrence);
records.push({
- key: relative + ':' + lineIndex,
+ key: digest + ':' + occurrence,
+ file: relative,
+ sourceSession: (['sessionId', 'conversationId', 'session_id', 'conversation_id']
+ .map(field => record[field]).find(value => typeof value === 'string' && value.trim()) || '').trim(),
timestamp,
model: model || '',
account: account || '',
@@ -180,6 +180,44 @@ function parseRecords(root, options = {}) {
return { records, files: files.length, parsedLines, parseErrors, parseErrorFiles: Array.from(parseErrorFiles) };
}
+function sessionAccount(options, id) {
+ const accounts = options.sessionAccounts;
+ return String((accounts instanceof Map ? accounts.get(id) : accounts && accounts[id]) || '').trim();
+}
+
+function distinctRecords(records, options = {}) {
+ const accountIds = new Set((options.accountOptions || [])
+ .map(item => String(item && (item.uid || item.account) || '').trim()).filter(Boolean));
+ const distinct = new Map();
+ for (const record of records) {
+ // Resolve owners on every scan, including cache hits. An imported row's
+ // session ID still refers to its source, whereas newly appended rows refer
+ // to the destination. Missing/ambiguous provenance must not invent usage
+ // for whichever account happens to own the first copy in directory order.
+ let account = record.account;
+ if (!account && record.sourceSession) account = sessionAccount(options, record.sourceSession);
+ if (!account && !record.sourceSession) {
+ account = sessionAccount(options, path.posix.basename(record.file, '.jsonl'));
+ if (!account) account = record.file.split('/').map(part => part.replace(/\.jsonl$/i, ''))
+ .find(part => accountIds.has(part)) || '';
+ }
+ let item = distinct.get(record.key);
+ if (!item) {
+ item = { record, accounts: new Set() };
+ distinct.set(record.key, item);
+ }
+ // Undated legacy rows use scan time as a fallback. Prefer the earliest
+ // cached observation so importing them later does not move usage to today.
+ if (record.timestamp < item.record.timestamp) item.record = record;
+ if (account) item.accounts.add(account);
+ }
+ // Occurrence indices preserve multiple equal rows in one original file;
+ // matching occurrences in other files are copies, not extra model calls.
+ return Array.from(distinct.values(), ({ record, accounts }) => ({
+ ...record, account: accounts.size === 1 ? accounts.values().next().value : '',
+ }));
+}
+
function cacheFile(root, options = {}) {
return options.cacheFile || path.join(root, '.workdaddy-token-stats-cache.json');
}
@@ -188,6 +226,7 @@ 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;
+ if (Object.values(value.todayFiles).some(item => !item || !Array.isArray(item.entries))) return null;
return value;
} catch (_) { return null; }
}
@@ -338,8 +377,8 @@ function aggregateCachedBuckets(buckets, options = {}) {
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.
+ // Keep per-file usage metadata until cross-file deduplication. Daily buckets
+ // alone discard identity and cannot distinguish imported historical copies.
const cutoff = dateBounds(now, { days: MAX_CACHE_DAYS }).from;
const file = cacheFile(root, options);
const cache = readCache(file);
@@ -359,16 +398,17 @@ function scanTokenStatsCached(root, options = {}) {
} else {
const parsed = parseRecords(root, { ...options, now, lowerBound: cutoff, upperBound: now,
files: [currentFile] });
- item = { mtimeMs: stat.mtimeMs, size: stat.size, buckets: aggregateBuckets(parsed.records),
+ item = { mtimeMs: stat.mtimeMs, size: stat.size, entries: parsed.records,
parsedLines: parsed.parsedLines, parseErrors: parsed.parseErrors, parseErrorFiles: parsed.parseErrorFiles };
}
- item.buckets = item.buckets.filter(bucket => bucket.day >= localDayString(cutoff));
+ item.entries = item.entries.filter(entry => entry.timestamp >= 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 records = Object.values(todayFiles).flatMap(item => item.entries);
+ const buckets = aggregateBuckets(distinctRecords(records, options));
const cacheReady = writeCache(file, { version: CACHE_VERSION, generatedAt: now, cutoff,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
historicalBuckets: [], todayFiles });
@@ -380,84 +420,11 @@ function scanTokenStatsCached(root, options = {}) {
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)),
- };
+ const bounds = dateBounds(now, options);
+ const parsed = parseRecords(root, { ...options, now, lowerBound: bounds.from,
+ upperBound: bounds.until, legacyParseErrors: true });
+ const stats = aggregateRecords(distinctRecords(parsed.records, options), { ...options, now });
+ return { ...stats, files: parsed.files, parsedLines: parsed.parsedLines, parseErrors: parsed.parseErrors };
}
module.exports = { tokenStatsCacheReady, scanTokenStats, scanTokenStatsCached, findUsage, walkJsonl, dateBounds };
diff --git a/scripts/usage-report.js b/scripts/usage-report.js
index df435b4..1f3d516 100644
--- a/scripts/usage-report.js
+++ b/scripts/usage-report.js
@@ -1,11 +1,12 @@
'use strict';
-// Anonymous installation / daily-active counts only. No account or renderer data.
+// Anonymous installation / daily-active counts only. Independent of error diagnostics.
+// 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 { persistentInstallationId } = require('./sentry-report.js');
const { sharedDataDir } = require('./profiles.js');
const ENDPOINT = 'https://workdaddy.dev/api/track';
const RETRY_MS = 6 * 3600000;
@@ -36,13 +37,11 @@ function createUsageReporter(options) {
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 = '';
@@ -75,7 +74,6 @@ function createUsageReporter(options) {
};
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,
diff --git a/scripts/verify-win.cmd b/scripts/verify-win.cmd
index 714a350..a8cc756 100644
--- a/scripts/verify-win.cmd
+++ b/scripts/verify-win.cmd
@@ -20,7 +20,7 @@ set "FAIL=0"
rem ---- 1) 关键文件齐全 ----
echo.
echo [1/6] 检查关键文件...
-for %%F in (daemon.js session-db.js secure-transfer.js lib.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 windows-relaunch-standard.ps1 prepare-win-install.ps1 workbuddy-compat.js inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 uninstall-win.cmd uninstall-win.ps1 apply-update.ps1 win\setup.sed) do (
+for %%F in (daemon.js session-db.js secure-transfer.js lib.js session-transfer.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 windows-relaunch-standard.ps1 prepare-win-install.ps1 workbuddy-compat.js inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 uninstall-win.cmd uninstall-win.ps1 apply-update.ps1 win\setup.sed) do (
if not exist "%SCRIPT_DIR%%%F" (
echo 缺失: %%~F
set /a FAIL+=1
@@ -62,7 +62,7 @@ if errorlevel 1 (
rem ---- 3) 脚本语法静态检查(node --check,不执行)----
echo.
echo [3/6] 校验 JS 语法...
-for %%F in (daemon.js session-db.js secure-transfer.js lib.js watchdog.js win-launcher.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js) do (
+for %%F in (daemon.js session-db.js secure-transfer.js lib.js session-transfer.js watchdog.js win-launcher.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js) do (
"%NODE%" --check "%SCRIPT_DIR%%%F" >nul 2>&1
if errorlevel 1 (
echo 语法错误: %%~F
diff --git a/scripts/win-launcher.js b/scripts/win-launcher.js
index d79e8fe..2918c1f 100644
--- a/scripts/win-launcher.js
+++ b/scripts/win-launcher.js
@@ -9,7 +9,7 @@
*
* 由 launcher.cmd 调用(cmd 负责兜底找 node),也可 node win-launcher.js 直接运行。
* 默认按普通用户运行;用户明确以管理员身份启动时,先通过桌面 Shell
- * 重启为标准权限。若无法确认已降权,则 fail closed 并提示用户。
+ * 重启为标准权限。仅无标准桌面令牌且安装时明确同意的会话可用管理员兼容模式。
*/
'use strict';
@@ -25,6 +25,7 @@ const {
assertDaemonTerminationIdentity,
assertSameProcessIdentity,
detectWindowsPrivilege,
+ detectNativeWindowsPrivilege,
assertVerifiedNodeProcess,
buildNativeProcessQuery,
filterVerifiedNodeProcesses,
@@ -36,9 +37,11 @@ const {
selectPreferredDiscoveredBinary,
} = require('./windows-process-boundary.js');
let WINDOWS_PRIVILEGE = 'standard';
-if (process.platform === 'win32' && process.env.WBSWITCH_NATIVE_LAUNCHER !== '1') {
+if (process.platform === 'win32') {
try {
- WINDOWS_PRIVILEGE = detectWindowsPrivilege();
+ WINDOWS_PRIVILEGE = process.env.WBSWITCH_NATIVE_LAUNCHER === '1'
+ ? detectNativeWindowsPrivilege(path.resolve(__dirname, '..'), process.env.WBSWITCH_PROFILE || 'workbuddy-cn')
+ : detectWindowsPrivilege();
} catch (error) {
console.error(error.message);
process.exit(5);
@@ -1248,6 +1251,14 @@ async function injectNowOrPending() {
return true;
}
+function hasElevatedSessionConsent() {
+ try {
+ return runNativeHelper([
+ '--check-elevated-session', '--profile', PROFILE.id, '--app-dir', WORKDADDY_APP_DIR,
+ ]).status === 0;
+ } catch (_) { return false; }
+}
+
function nativeHelperPath() {
return path.join(WORKDADDY_APP_DIR, 'WorkDaddyLauncher.exe');
}
@@ -1486,7 +1497,7 @@ function nativeDaemonStatusMatches(status) {
status.dataDir && sameWindowsPath(status.dataDir, DATA_DIR) &&
status.version === identity.version &&
status.buildId === identity.buildId &&
- status.privilege === 'standard'
+ status.privilege === WINDOWS_PRIVILEGE
);
}
@@ -1513,7 +1524,7 @@ async function ensureDaemonNative(nodeBin) {
fs.mkdirSync(path.join(DATA_DIR, 'accounts'), { recursive: true });
let status = await readStatus();
if (status && nativeDaemonStatusMatches(status)) {
- log('daemon profile、版本、构建和标准权限均已验证,跳过启动');
+ log('daemon profile、版本、构建和实际权限均已验证,跳过启动 privilege=' + WINDOWS_PRIVILEGE);
return true;
}
if (status) {
@@ -1696,13 +1707,18 @@ if (require.main === module && process.env.WBSWITCH_NATIVE_LAUNCHER === '1') {
return;
}
if (process.platform === 'win32' && WINDOWS_PRIVILEGE === 'elevated') {
+ if (hasElevatedSessionConsent()) {
+ log('已验证管理员会话兼容安装选择,使用原生启动与精确进程管理');
+ process.env.WBSWITCH_NATIVE_LAUNCHER = '1';
+ process.exit(await nativeStartupMain());
+ }
if (!process.argv.includes(DESKTOP_RELAUNCH_ARG)) {
relaunchWithDesktopShell(nodeBin);
log('管理员入口已通过桌面 Shell 重新派发;当前 elevated launcher 退出');
process.exit(0);
}
log('桌面 Shell 仍返回 elevated token(可能已关闭 UAC),拒绝继续启动管理员权限 WorkDaddy');
- showWindowsMessageBox(WBS_BRAND, '无法自动降回普通用户权限,已拒绝启动管理员权限 WorkDaddy。请开启 UAC 后双击快捷方式重试。');
+ showWindowsMessageBox(WBS_BRAND, '无法自动降回普通用户权限,已拒绝启动管理员权限 WorkDaddy。请重新运行新版安装程序确认兼容安装;普通电脑请开启 UAC 后双击快捷方式重试。');
process.exit(5);
}
await configureCdpPort();
diff --git a/scripts/win/workdaddy.iss b/scripts/win/workdaddy.iss
index 2d9b2be..2d555d1 100644
--- a/scripts/win/workdaddy.iss
+++ b/scripts/win/workdaddy.iss
@@ -77,6 +77,7 @@ Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType:
[Run]
Filename: "{app}\WorkDaddyLauncher.exe"; Description: "{#StartDescription}"; WorkingDir: "{app}"; Flags: nowait postinstall skipifsilent runasoriginaluser; Check: ShouldAutoLaunch
+Filename: "{app}\WorkDaddyLauncher.exe"; Description: "{#StartDescription}"; WorkingDir: "{app}"; Flags: nowait postinstall skipifsilent runascurrentuser; Check: ShouldLaunchElevatedSession
[UninstallRun]
Filename: "{app}\WorkDaddyLauncher.exe"; Parameters: "--stop-lifecycle --profile ""{#ProfileId}"" --app-dir ""{app}"""; WorkingDir: "{app}"; Flags: runhidden waituntilterminated; RunOnceId: "StopWorkDaddyLifecycle"
@@ -88,6 +89,7 @@ Type: filesandordirs; Name: "{app}"
var
PreserveExistingLifecycle: Boolean;
ElevatedInstallConfirmed: Boolean;
+ ElevatedSessionConfirmed: Boolean;
ClientPage: TInputFileWizardPage;
ClientSourceLabel: TNewStaticText;
ClientVersionLabel: TNewStaticText;
@@ -109,12 +111,33 @@ begin
Result := not IsAdmin;
end;
+function ShouldLaunchElevatedSession(): Boolean;
+begin
+ Result := ElevatedSessionConfirmed;
+end;
+
+// Detection and consent run under the installer's actual token. No UAC request
+// or Explorer redispatch: this also works when no original standard user exists.
+function RunDesktopSessionHelper(const Mode: String; var ResultCode: Integer): Boolean;
+begin
+ ExtractTemporaryFile('WorkDaddyLauncher.exe');
+ Result := Exec(ExpandConstant('{tmp}\WorkDaddyLauncher.exe'),
+ Mode + ' --profile "{#ProfileId}"', ExpandConstant('{tmp}'),
+ SW_HIDE, ewWaitUntilTerminated, ResultCode);
+end;
+
function RunNativeHelper(const Mode: String; var ResultCode: Integer): Boolean;
var
Parameters: String;
begin
ExtractTemporaryFile('WorkDaddyLauncher.exe');
Parameters := Mode + ' --profile "{#ProfileId}"';
+ if ElevatedSessionConfirmed then
+ begin
+ Result := Exec(ExpandConstant('{tmp}\WorkDaddyLauncher.exe'), Parameters,
+ ExpandConstant('{tmp}'), SW_HIDE, ewWaitUntilTerminated, ResultCode);
+ exit;
+ end;
Result := ExecAsOriginalUser(
ExpandConstant('{tmp}\WorkDaddyLauncher.exe'),
Parameters,
@@ -533,7 +556,13 @@ begin
Parameters := '"' + ScriptPath + '" --configure --profile "{#ProfileId}"' +
' --binary "' + SelectedWorkBuddyPath + '" --version "' + SelectedWorkBuddyVersion + '"' +
' --data-dir "' + DataDir + '"';
- if not ExecAsOriginalUser(NodePath, Parameters, ExpandConstant('{app}\scripts'), SW_HIDE,
+ if ElevatedSessionConfirmed then
+ begin
+ if not Exec(NodePath, Parameters, ExpandConstant('{app}\scripts'), SW_HIDE,
+ ewWaitUntilTerminated, ResultCode) then
+ exit;
+ end
+ else if not ExecAsOriginalUser(NodePath, Parameters, ExpandConstant('{app}\scripts'), SW_HIDE,
ewWaitUntilTerminated, ResultCode) then
exit;
Result := ResultCode = 0;
@@ -725,7 +754,7 @@ begin
exit;
if Choice = mrYes then
begin
- if not RunNativeHelper('--terminate-workbuddy --binary "' + SelectedWorkBuddyPath + '"', ResultCode) then
+ if not RunNativeHelper('--terminate-workbuddy --binary "' + SelectedWorkBuddyPath + '" --app-dir "' + ExpandConstant('{app}') + '"', ResultCode) then
begin
MsgBox('无法启动 WorkBuddy 结束进程操作。请检查安全软件是否拦截安装程序。', mbError, MB_OK);
exit;
@@ -743,14 +772,105 @@ begin
end;
end;
+function ShowElevatedSessionConsent(): Boolean;
+var
+ Dialog: TSetupForm;
+ Description: TNewStaticText;
+ ContinueButton, CancelButton: TNewButton;
+begin
+ Dialog := CreateCustomForm();
+ try
+ Dialog.Caption := '管理员会话兼容安装';
+ Dialog.ClientWidth := ScaleX(500);
+ Dialog.ClientHeight := ScaleY(265);
+ Dialog.Position := poScreenCenter;
+ Description := TNewStaticText.Create(Dialog);
+ Description.Parent := Dialog;
+ Description.Left := ScaleX(20);
+ Description.Top := ScaleY(18);
+ Description.Width := ScaleX(460);
+ Description.Height := ScaleY(190);
+ Description.AutoSize := False;
+ Description.WordWrap := True;
+ Description.Caption :=
+ '这台电脑的 Windows 桌面本身使用管理员权限,无法通过桌面切换到普通权限。常见于内建 Administrator 账户或关闭 UAC 的电脑。' + #13#10 + #13#10 +
+ '继续后,WorkDaddy 和由它启动的 WorkBuddy 将以管理员权限运行。WorkBuddy 中的命令、插件和自动操作也会拥有更高权限,误操作可能影响系统文件和设置。' + #13#10 + #13#10 +
+ '更稳妥的做法是使用普通权限桌面后重新安装。若仍要继续,此选择仅保存到当前用户、当前客户端和安装目录,之后双击快捷方式也会沿用。恢复普通权限桌面后会自动按普通权限启动。';
+ Description.AdjustHeight();
+ ContinueButton := TNewButton.Create(Dialog);
+ ContinueButton.Parent := Dialog;
+ ContinueButton.Caption := '我已了解风险,继续安装';
+ ContinueButton.Left := ScaleX(20);
+ ContinueButton.Top := Description.Top + Description.Height + ScaleY(18);
+ ContinueButton.Width := ScaleX(260);
+ ContinueButton.Height := ScaleY(28);
+ ContinueButton.Default := False;
+ ContinueButton.ModalResult := mrYes;
+ CancelButton := TNewButton.Create(Dialog);
+ CancelButton.Parent := Dialog;
+ CancelButton.Caption := '取消安装';
+ CancelButton.Left := ScaleX(360);
+ CancelButton.Top := ContinueButton.Top;
+ CancelButton.Width := ScaleX(120);
+ CancelButton.Height := ScaleY(28);
+ CancelButton.Default := True;
+ CancelButton.Cancel := True;
+ CancelButton.ModalResult := mrCancel;
+ Dialog.ClientHeight := ContinueButton.Top + ContinueButton.Height + ScaleY(18);
+ Dialog.ActiveControl := CancelButton;
+ Result := Dialog.ShowModal() = mrYes;
+ finally
+ Dialog.Free();
+ end;
+end;
+
function ConfirmElevatedInstall(): Boolean;
+var
+ ResultCode: Integer;
begin
- if ElevatedInstallConfirmed then
+ if ElevatedInstallConfirmed or ElevatedSessionConfirmed then
begin
Result := True;
exit;
end;
+ Result := False;
+ if not RunDesktopSessionHelper('--desktop-token-status', ResultCode) then
+ begin
+ if not WizardSilent then
+ MsgBox('无法检测 Windows 桌面权限,安装已停止。请检查安全软件是否阻止安装程序。', mbError, MB_OK);
+ exit;
+ end;
+ if ResultCode = 5 then
+ begin
+ // Silent updates can reuse prior consent, but cannot create it.
+ if WizardSilent then
+ begin
+ ElevatedSessionConfirmed := RunDesktopSessionHelper(
+ '--check-elevated-session --app-dir "' + ExpandConstant('{app}') + '"', ResultCode);
+ ElevatedSessionConfirmed := ElevatedSessionConfirmed and (ResultCode = 0);
+ end
+ else
+ begin
+ if not ShowElevatedSessionConsent() then
+ exit;
+ ElevatedSessionConfirmed := RunDesktopSessionHelper(
+ '--accept-elevated-session --app-dir "' + ExpandConstant('{app}') + '"', ResultCode);
+ ElevatedSessionConfirmed := ElevatedSessionConfirmed and (ResultCode = 0);
+ if not ElevatedSessionConfirmed then
+ MsgBox('无法保存兼容安装选择,或桌面权限已经变化。安装已停止,请重新打开安装程序。', mbError, MB_OK);
+ end;
+ Result := ElevatedSessionConfirmed;
+ exit;
+ end;
+ if ResultCode <> 0 then
+ begin
+ if not WizardSilent then
+ MsgBox('无法确认桌面适用管理员兼容模式,安装已停止。请使用普通权限桌面后重新安装。', mbError, MB_OK);
+ exit;
+ end;
+ if WizardSilent then
+ exit;
Result := MsgBox(
'当前安装程序是以管理员权限运行的。' + #13#10 + #13#10 +
'仍可继续安装,但安装器不会自动启动或结束 WorkDaddy/WorkBuddy。请先手动退出它们,安装完成后再双击桌面快捷方式。' + #13#10 + #13#10 +
@@ -777,7 +897,7 @@ begin
Result := '你已选择不继续管理员安装。可以取消安装,或返回后重新选择继续。';
exit;
end;
- if IsAdmin then
+ if IsAdmin and not ElevatedSessionConfirmed then
exit;
if not EnsureWorkBuddyClosed() then
begin
diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.go
index 12b6596..c8b798d 100644
--- a/scripts/windows-native/main.go
+++ b/scripts/windows-native/main.go
@@ -38,6 +38,8 @@ const (
tokenDuplicate = 0x0002
tokenQuery = 0x0008
tokenElevation = 20 // TokenElevation
+ tokenElevationType = 18 // TokenElevationType
+ tokenSessionID = 12 // TokenSessionId
logonWithProfile = 0x00000001
createUnicodeEnvironment = 0x00000400
th32csSnapProcess = 0x00000002
@@ -206,31 +208,39 @@ func isElevated() (bool, error) {
return tokenIsElevated(token)
}
-func relaunchWithDesktopToken(appDir string) error {
+func openDesktopToken(access uint32) (syscall.Handle, error) {
shellWindow, _, callErr := procGetShellWindow.Call()
if shellWindow == 0 {
- return fmt.Errorf("cannot find desktop Explorer window: %w", callErr)
+ return 0, fmt.Errorf("cannot find desktop Explorer window: %w", callErr)
}
var shellPID uint32
procGetWindowThreadProcessID.Call(shellWindow, uintptr(unsafe.Pointer(&shellPID)))
if shellPID == 0 {
- return errors.New("cannot identify desktop Explorer process")
+ return 0, errors.New("cannot identify desktop Explorer process")
}
expectedExplorer := filepath.Join(os.Getenv("SystemRoot"), "explorer.exe")
if os.Getenv("SystemRoot") == "" || !strings.EqualFold(filepath.Clean(queryProcessPath(shellPID)), filepath.Clean(expectedExplorer)) {
- return errors.New("desktop shell process is not the expected explorer.exe")
+ return 0, errors.New("desktop shell process is not the expected explorer.exe")
}
shellProcess, err := openProcess(shellPID, processQueryLimitedInformation)
if err != nil {
- return fmt.Errorf("cannot open desktop Explorer process: %w", err)
+ return 0, fmt.Errorf("cannot open desktop Explorer process: %w", err)
}
defer syscall.CloseHandle(shellProcess)
var shellToken syscall.Handle
result, _, callErr := procOpenProcessToken.Call(
- uintptr(shellProcess), tokenAssignPrimary|tokenDuplicate|tokenQuery, uintptr(unsafe.Pointer(&shellToken)),
+ uintptr(shellProcess), uintptr(access), uintptr(unsafe.Pointer(&shellToken)),
)
if result == 0 {
- return fmt.Errorf("cannot open desktop Explorer token: %w", callErr)
+ return 0, fmt.Errorf("cannot open desktop Explorer token: %w", callErr)
+ }
+ return shellToken, nil
+}
+
+func relaunchWithDesktopToken(appDir string) error {
+ shellToken, err := openDesktopToken(tokenAssignPrimary | tokenDuplicate | tokenQuery)
+ if err != nil {
+ return err
}
defer syscall.CloseHandle(shellToken)
elevated, err := tokenIsElevated(shellToken)
@@ -238,7 +248,7 @@ func relaunchWithDesktopToken(appDir string) error {
return fmt.Errorf("cannot inspect desktop Explorer token: %w", err)
}
if elevated {
- return errors.New("desktop Explorer token is elevated")
+ return errDesktopTokenElevated
}
executable, err := os.Executable()
if err != nil {
@@ -248,7 +258,7 @@ func relaunchWithDesktopToken(appDir string) error {
return errors.New("native launcher path contains invalid characters")
}
var environment uintptr
- result, _, callErr = procCreateEnvironmentBlock.Call(
+ result, _, callErr := procCreateEnvironmentBlock.Call(
uintptr(unsafe.Pointer(&environment)), uintptr(shellToken), 0,
)
if result == 0 {
@@ -270,6 +280,170 @@ func relaunchWithDesktopToken(appDir string) error {
return nil
}
+// Consent is a per-user preference, not a privilege grant. It never creates a
+// token: every use rechecks the real desktop and process token before proceeding.
+var errDesktopTokenElevated = errors.New("desktop Explorer token is elevated")
+
+type elevatedConsent struct {
+ Version int `json:"version"`
+ Profile string `json:"profile"`
+ AppDir string `json:"appDir"`
+ UserSID string `json:"userSid"`
+}
+
+func tokenDword(token syscall.Handle, kind uint32) (uint32, error) {
+ var value, returned uint32
+ ok, _, err := procGetTokenInformation.Call(uintptr(token), uintptr(kind),
+ uintptr(unsafe.Pointer(&value)), unsafe.Sizeof(value), uintptr(unsafe.Pointer(&returned)))
+ if ok == 0 {
+ return 0, err
+ }
+ return value, nil
+}
+
+func currentUserSID() (string, error) {
+ token, err := syscall.OpenCurrentProcessToken()
+ if err != nil {
+ return "", err
+ }
+ defer token.Close()
+ user, err := token.GetTokenUser()
+ if err != nil {
+ return "", err
+ }
+ return user.User.Sid.String()
+}
+
+func verifySameProcessSecurity(handle syscall.Handle) error {
+ var target syscall.Token
+ if err := syscall.OpenProcessToken(handle, tokenQuery, &target); err != nil {
+ return err
+ }
+ defer target.Close()
+ current, err := syscall.OpenCurrentProcessToken()
+ if err != nil {
+ return err
+ }
+ defer current.Close()
+ targetUser, err := target.GetTokenUser()
+ if err != nil {
+ return err
+ }
+ currentUser, err := current.GetTokenUser()
+ if err != nil {
+ return err
+ }
+ targetSID, err := targetUser.User.Sid.String()
+ if err != nil {
+ return err
+ }
+ currentSID, err := currentUser.User.Sid.String()
+ if err != nil {
+ return err
+ }
+ if targetSID != currentSID {
+ return errors.New("process belongs to another user")
+ }
+ for _, kind := range []uint32{tokenElevation, tokenSessionID} {
+ left, err := tokenDword(syscall.Handle(target), kind)
+ if err != nil {
+ return err
+ }
+ right, err := tokenDword(syscall.Handle(current), kind)
+ if err != nil {
+ return err
+ }
+ if left != right {
+ return errors.New("process privilege or session differs from launcher")
+ }
+ }
+ return nil
+}
+
+func desktopSessionSupportsElevated() bool {
+ current, err := isElevated()
+ if err != nil || !current {
+ return false
+ }
+ token, err := openDesktopToken(tokenQuery)
+ if err != nil {
+ return false
+ }
+ defer syscall.CloseHandle(token)
+ elevated, err := tokenIsElevated(token)
+ if err != nil || !elevated {
+ return false
+ }
+ // A manually elevated Explorer with a linked standard token is NOT the
+ // built-in Administrator/UAC-disabled case. TokenElevationTypeDefault = 1.
+ elevationType, err := tokenDword(token, tokenElevationType)
+ if err != nil || elevationType != 1 {
+ return false
+ }
+ shellUser, err := syscall.Token(token).GetTokenUser()
+ if err != nil {
+ return false
+ }
+ shellSID, err := shellUser.User.Sid.String()
+ if err != nil {
+ return false
+ }
+ currentSID, err := currentUserSID()
+ return err == nil && shellSID == currentSID
+}
+
+func elevatedSessionAllowed(profile, appDir string) bool {
+ if !desktopSessionSupportsElevated() {
+ return false
+ }
+ dir, err := dataDir(profile)
+ if err != nil {
+ return false
+ }
+ data, err := os.ReadFile(filepath.Join(dir, "windows-elevated-consent.json"))
+ if err != nil {
+ return false
+ }
+ var consent elevatedConsent
+ if json.Unmarshal(data, &consent) != nil {
+ return false
+ }
+ sid, err := currentUserSID()
+ return err == nil && consent.Version == 1 && consent.Profile == profile &&
+ filepath.IsAbs(appDir) && samePath(consent.AppDir, appDir) && consent.UserSID == sid
+}
+
+func saveElevatedConsent(profile, appDir string) error {
+ if !filepath.IsAbs(appDir) || !desktopSessionSupportsElevated() {
+ return errors.New("desktop session is not eligible for elevated compatibility")
+ }
+ dir, err := dataDir(profile)
+ if err != nil {
+ return err
+ }
+ sid, err := currentUserSID()
+ if err != nil {
+ return err
+ }
+ data, err := json.Marshal(elevatedConsent{1, profile, filepath.Clean(appDir), sid})
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return err
+ }
+ // A partial write cannot grant consent: readers require complete valid JSON.
+ return os.WriteFile(filepath.Join(dir, "windows-elevated-consent.json"), data, 0600)
+}
+
+func helperAppDir() string {
+ if dir := argumentValue("--app-dir"); dir != "" {
+ return dir
+ }
+ dir, _ := executableDir()
+ return dir
+}
+
func acquireMutex(profile string) (syscall.Handle, bool, error) {
name := "Local\\WorkDaddyLauncher-" + profile
handle, _, callErr := procCreateMutexW.Call(0, 0, uintptr(unsafe.Pointer(utf16Ptr(name))))
@@ -608,6 +782,9 @@ func terminateExactProcess(pid int, expectedPath string, label string) (bool, in
return false, exitFailure, err
}
defer syscall.CloseHandle(handle)
+ if err := verifySameProcessSecurity(handle); err != nil {
+ return false, exitAccessDenied, err
+ }
result, _, callErr := procTerminateProcess.Call(uintptr(handle), 0)
if result == 0 {
if errors.Is(callErr, syscall.ERROR_ACCESS_DENIED) {
@@ -626,7 +803,7 @@ func terminateExactNode(pid int, expectedNode string) (bool, int, error) {
return terminateExactProcess(pid, expectedNode, "node")
}
-func stopInstalledLauncher(appDir string, elevated bool) int {
+func stopInstalledLauncher(profile, appDir string, elevated bool) int {
expectedLauncher := filepath.Join(appDir, "WorkDaddyLauncher.exe")
records, err := enumerateProcesses()
if err != nil {
@@ -652,7 +829,7 @@ func stopInstalledLauncher(appDir string, elevated bool) int {
if len(matches) == 0 {
return 0
}
- if elevated {
+ if elevated && !elevatedSessionAllowed(profile, appDir) {
fmt.Fprintln(os.Stderr, "installed WorkDaddy launcher is still running; lifecycle stop requires standard user privilege")
return exitAccessDenied
}
@@ -693,7 +870,7 @@ func terminateWorkBuddyTarget(profile string, target workBuddyTarget) int {
fmt.Fprintln(os.Stderr, "cannot determine helper privilege:", err)
return exitFailure
}
- if elevated {
+ if elevated && !elevatedSessionAllowed(profile, helperAppDir()) {
fmt.Fprintln(os.Stderr, "WorkBuddy termination requires standard user privilege")
return exitAccessDenied
}
@@ -823,8 +1000,8 @@ func stopLifecycle(profile, appDir string, elevated bool) int {
continue
}
seen[candidate.pid] = true
- // An elevated helper may clear a stale PID, but must refuse any active
- // lifecycle so it never becomes a cross-privilege process terminator.
+ // An elevated helper may clear a stale PID. Active lifecycle work
+ // additionally requires saved consent and same-token-security checks.
active, code, inspectErr := inspectExactProcess(candidate.pid, expectedNode, "node")
if inspectErr != nil {
fmt.Fprintln(os.Stderr, inspectErr)
@@ -833,7 +1010,7 @@ func stopLifecycle(profile, appDir string, elevated bool) int {
if !active {
continue
}
- if elevated {
+ if elevated && !elevatedSessionAllowed(profile, appDir) {
fmt.Fprintln(os.Stderr, "running WorkDaddy lifecycle requires standard user privilege")
return exitAccessDenied
}
@@ -848,7 +1025,7 @@ func stopLifecycle(profile, appDir string, elevated bool) int {
_ = os.Remove(candidate.path)
}
}
- if code := stopInstalledLauncher(appDir, elevated); code != 0 {
+ if code := stopInstalledLauncher(profile, appDir, elevated); code != 0 {
return code
}
return 0
@@ -1064,6 +1241,53 @@ func runNodeLauncher(appDir, profile string) int {
}
func helperMain(appDir, profile string) (bool, int) {
+ if hasArgument("--desktop-token-status") {
+ token, err := openDesktopToken(tokenQuery)
+ if err != nil {
+ return true, exitFailure
+ }
+ defer syscall.CloseHandle(token)
+ elevated, err := tokenIsElevated(token)
+ if err != nil {
+ return true, exitFailure
+ }
+ if !elevated {
+ return true, 0
+ }
+ if desktopSessionSupportsElevated() {
+ return true, exitElevated
+ }
+ return true, exitAccessDenied
+ }
+ if hasArgument("--accept-elevated-session") {
+ if err := saveElevatedConsent(profile, helperAppDir()); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return true, exitAccessDenied
+ }
+ return true, 0
+ }
+ if hasArgument("--check-elevated-session") {
+ if elevatedSessionAllowed(profile, helperAppDir()) {
+ return true, 0
+ }
+ return true, exitAccessDenied
+ }
+ if hasArgument("--launch-context") {
+ elevated, err := isElevated()
+ if err != nil {
+ return true, exitFailure
+ }
+ if elevated && !elevatedSessionAllowed(profile, helperAppDir()) {
+ return true, exitElevated
+ }
+ privilege := "standard"
+ if elevated {
+ privilege = "elevated"
+ }
+ _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"profile": profile, "privilege": privilege})
+ return true, 0
+ }
+
if hasArgument("--target-info") {
target := configuredTarget(profile)
output := argumentValue("--output")
@@ -1185,13 +1409,25 @@ func main() {
os.Exit(exitFailure)
}
if elevated {
+ var relaunchErr error
if !hasArgument("--desktop-shell-relaunch") {
- if err := relaunchWithDesktopToken(appDir); err == nil {
+ relaunchErr = relaunchWithDesktopToken(appDir)
+ if relaunchErr == nil {
os.Exit(0)
}
+ } else {
+ relaunchErr = errDesktopTokenElevated
+ }
+ allowed := errors.Is(relaunchErr, errDesktopTokenElevated) && elevatedSessionAllowed(profile, appDir)
+ if dir, dirErr := dataDir(profile); dirErr == nil {
+ if file := appendLog(dir, "desktop relaunch:", relaunchErr, "elevatedConsent="+strconv.FormatBool(allowed)); file != nil {
+ file.Close()
+ }
+ }
+ if !allowed {
+ messageBox(productName(profile), "无法自动切换到普通用户权限。\n\n请重新运行新版安装程序;若检测到桌面无法降权,可阅读风险提示并选择兼容安装。普通电脑请确认 UAC 已开启,然后直接双击快捷方式。", mbOK|mbIconWarning)
+ os.Exit(exitElevated)
}
- messageBox(productName(profile), "无法自动切换到普通用户权限。\n\n请确认 UAC 已开启,然后直接双击 WorkDaddy 快捷方式重试。", mbOK|mbIconWarning)
- os.Exit(exitElevated)
}
mutex, alreadyRunning, err := acquireMutex(profile)
diff --git a/scripts/windows-process-boundary.js b/scripts/windows-process-boundary.js
index 544fb4b..d87483e 100644
--- a/scripts/windows-process-boundary.js
+++ b/scripts/windows-process-boundary.js
@@ -33,6 +33,26 @@ function detectWindowsPrivilege(run = spawnSync) {
throw new Error('无法确认 Windows 进程是否为普通用户权限');
}
+// Native children inherit the real Windows token. Ask the installed helper to
+// verify it (including saved consent for elevated sessions), never an env flag.
+function detectNativeWindowsPrivilege(appDir, profile, run = spawnSync) {
+ const result = run(path.join(appDir, 'WorkDaddyLauncher.exe'), [
+ '--launch-context', '--profile', profile, '--app-dir', appDir,
+ ], { encoding: 'utf8', windowsHide: true, timeout: 10000 });
+ if (!result || result.error || result.status !== 0) {
+ throw new Error('无法验证 Windows 启动权限或兼容安装授权,请重新运行安装程序');
+ }
+ let context;
+ try { context = JSON.parse(result.stdout); } catch (_) {
+ throw new Error('Windows 启动权限检测返回无效数据');
+ }
+ if (!context || context.profile !== profile ||
+ !['standard', 'elevated'].includes(context.privilege)) {
+ throw new Error('Windows 启动权限或客户端身份不匹配');
+ }
+ return context.privilege;
+}
+
function assertStandardWindowsPrivilege(run = spawnSync) {
const privilege = detectWindowsPrivilege(run);
if (privilege !== 'standard') throw new Error('拒绝以管理员或 elevated 权限运行 WorkDaddy');
@@ -375,6 +395,7 @@ module.exports = {
assertDaemonTerminationIdentity,
assertSameProcessIdentity,
detectWindowsPrivilege,
+ detectNativeWindowsPrivilege,
assertStandardWindowsPrivilege,
assertVerifiedNodeProcess,
buildNativeProcessQuery,
diff --git a/test/account-list-stability.test.js b/test/account-list-stability.test.js
index 52bd656..c8c215f 100644
--- a/test/account-list-stability.test.js
+++ b/test/account-list-stability.test.js
@@ -173,3 +173,13 @@ test('account metadata refresh retains valid activity days while the server cach
h.ctx.render({ accounts: [{ uid: 'a', nickname: 'a', activityStreak: { days: 0, status: 'ready' } }] });
assert.equal(h.ctx.state.accounts[0].activityStreak.days, 0);
});
+
+test('fixed sort remains stable through credit refresh and appends new accounts without a sort', () => {
+ const h = harness();
+ const a = { ...account('a', 10), sort: 2 }, b = { ...account('b', 20), sort: 1 };
+ h.ctx.render({ accountOrder: { mode: 'fixed' }, accounts: [a,b,account('c', 1)] });
+ assert.deepEqual(h.order(), ['b','a','c']);
+ h.ctx.render({ accountOrder: { mode: 'fixed' }, accounts: [a,b,account('c', 1),account('d', 0)] });
+ h.ctx.sortAccountsByCreditExpiry();
+ assert.deepEqual(h.order(), ['b','a','c','d']);
+});
diff --git a/test/account-order.test.js b/test/account-order.test.js
new file mode 100644
index 0000000..64645e7
--- /dev/null
+++ b/test/account-order.test.js
@@ -0,0 +1,33 @@
+'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 lib = require('../scripts/lib.js');
+test('fixed order survives reload, appends unsorted accounts and prunes deleted accounts', t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-order-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const accounts = lib.accountsDir(dir); fs.mkdirSync(accounts, { recursive: true });
+ for (const uid of ['a','b','c']) fs.writeFileSync(path.join(accounts, uid + '.info'), '{}');
+ lib.setAccountOrder(dir, { mode: 'fixed', uids: ['b','a'] });
+ assert.equal(lib.getAccountOrder(dir).mode, 'fixed');
+ assert.deepEqual(Object.fromEntries(lib.listAccounts(dir).map(a => [a.uid, a.sort])), { a: 2, b: 1, c: 0 });
+ fs.unlinkSync(path.join(accounts, 'b.info'));
+ lib.setAccountOrder(dir, { mode: 'expiry', uids: ['b','a','c'] });
+ assert.equal(lib.getAccountOrder(dir).mode, 'expiry');
+ assert.equal(lib.listAccounts(dir).find(a => a.uid === 'a').sort, 1);
+ assert.throws(() => lib.setAccountOrder(dir, { mode: 'bad', uids: [] }), /排序/);
+ assert.throws(() => lib.setAccountOrder(dir, { mode: 'fixed', uids: ['a','a'] }), /排序/);
+});
+
+test('background auth backup and account switching preserve fixed sort metadata', t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-order-refresh-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ fs.mkdirSync(lib.accountsDir(dir), { recursive: true });
+ for (const uid of ['a','b']) fs.writeFileSync(path.join(lib.accountsDir(dir), uid + '.info'), '{}');
+ lib.setAccountOrder(dir, { mode: 'fixed', uids: ['b','a'] });
+ lib.updateMeta(dir, { uid: 'b', nickname: 'updated' }, { preserveBinding: true });
+ lib.updateMeta(dir, { uid: 'a', nickname: 'switched' });
+ assert.deepEqual(Object.fromEntries(lib.listAccounts(dir).map(a => [a.uid,a.sort])), { a: 2, b: 1 });
+});
diff --git a/test/agent-new-task-draft.test.js b/test/agent-new-task-draft.test.js
index dba02a9..135cfca 100644
--- a/test/agent-new-task-draft.test.js
+++ b/test/agent-new-task-draft.test.js
@@ -36,9 +36,9 @@ test('failed draft backup prevents clearing and sending', async () => {
test('a project composer cannot bypass navigation to New Task', async () => {
const h=harness({project:true,draft:false});await h.run();assert.equal(h.calls[0],'navigate');assert.equal(h.calls.at(-1),'send');
});
-test('current-account corner mark is removed and selecting primary explains its automation use',()=>{
+test('account corner and primary controls are absent',()=>{
const ui=fs.readFileSync(require('node:path').join(__dirname,'../scripts/inject.js'),'utf8');
- assert.ok(!ui.includes('wbs-cur-marker'));assert.ok(ui.includes("toast('已设为主账号,自动化任务可据此识别主账号'"));
+ assert.ok(!ui.includes('wbs-cur-marker'));assert.ok(!ui.includes('data-primary-uid'));
});
test('typing during draft backup cancels without clearing the new text', async () => {
diff --git a/test/automation-checkin.test.js b/test/automation-checkin.test.js
index e923892..6a50465 100644
--- a/test/automation-checkin.test.js
+++ b/test/automation-checkin.test.js
@@ -90,8 +90,8 @@ test('legacy implicit triggers and pending UI are removed; panel event is explic
assert.match(ui,/\/api\/automations\/events/);
const html=ui.slice(ui.indexOf('function checkinHtml'),ui.indexOf('function el(tag'));
const ctx={WBS_PROFILE_IS_AI:false};vm.createContext(ctx);vm.runInContext(html,ctx);
- assert.match(ctx.checkinHtml({}),/pending.*今日签到/);
- assert.match(ctx.checkinHtml({checkin:{ok:true}}),/tag ok.*今日签到/);
+ assert.match(ctx.checkinHtml({}),/pending.*今日未签到/);
+ assert.match(ctx.checkinHtml({checkin:{ok:true}}),/tag ok.*今日已签到/);
assert.doesNotMatch(ctx.checkinHtml({checkin:{ok:false,message:'bad'}}),/bad/);
});
@@ -135,7 +135,7 @@ test('fresh CN and AI profiles receive all three presets without reinstalling de
for (const id of ['workbuddy-cn', 'workbuddy-ai']) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-presets-'));
try {
- const context = { PROFILE: PROFILES[id], DATA_DIR: dir, path, __dirname: path.join(__dirname, '../scripts'), installBuiltinTask: automation.installBuiltinTask, log() {} };
+ const context = { initializeCheckinConsent: require('../scripts/checkin-consent').initializeCheckinConsent, PROFILE: PROFILES[id], DATA_DIR: dir, path, __dirname: path.join(__dirname, '../scripts'), installBuiltinTask: automation.installBuiltinTask, log() {} };
vm.runInNewContext(init, context);
assert.deepEqual(automation.readAutomations(dir).map(t => t.id).sort(), ['buddy-fuel-station-close-on-account-switch', 'daily-account-checkin', 'keep-accounts-active-1-plus-1']);
automation.writeAutomations(dir, []);
diff --git a/test/avatar-library-credit-opacity.test.js b/test/avatar-library-credit-opacity.test.js
new file mode 100644
index 0000000..c151b5d
--- /dev/null
+++ b/test/avatar-library-credit-opacity.test.js
@@ -0,0 +1,59 @@
+'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 load() {
+ const ctx = {};
+ vm.runInNewContext(source.slice(source.indexOf(' function creditOpacity('), source.indexOf(' function checkinHtml(')), ctx);
+ return ctx;
+}
+function storage(initial = {}) {
+ const values = new Map(Object.entries(initial));
+ return { getItem: k => values.get(k) || null, setItem: (k,v) => values.set(k,v), removeItem: k => values.delete(k) };
+}
+const png = 'data:image/png;base64,YQ==', webp = 'data:image/webp;base64,Yg==';
+test('credit opacity clamps at one and thirty days and interpolates continuously', () => {
+ const { creditOpacity } = load();
+ for (const days of [-10,0,0.5,1]) assert.equal(creditOpacity(days),0.05);
+ for (const days of [30,31,1000]) assert.equal(creditOpacity(days),1);
+ assert.equal(creditOpacity(15.5),0.525);
+ assert.ok(Math.abs(creditOpacity(2)- (0.05+0.95/29)) < 1e-12);
+ assert.equal(creditOpacity(null),1);
+});
+test('legacy upload survives selecting either preset and adding multiple avatars', () => {
+ const { createAvatarLibrary } = load(), cache = storage({wbsAvatar:png});
+ const lib = createAvatarLibrary(cache);
+ assert.equal(lib.snapshot().items[0].src,png);
+ lib.select('workbuddy'); lib.select('workdaddy');
+ const added = lib.add(webp);
+ assert.equal(lib.snapshot().items.length,2);
+ assert.equal(lib.snapshot().selected,added);
+ const restored = createAvatarLibrary(cache);
+ assert.equal(restored.snapshot().selected,added);
+ assert.equal(restored.snapshot().items[0].src,png);
+ restored.select('workbuddy');
+ restored.remove(added);
+ assert.equal(restored.snapshot().selected,'workdaddy');
+ assert.equal(restored.snapshot().items.length,1);
+ restored.remove(restored.snapshot().items[0].id);
+ assert.equal(createAvatarLibrary(cache).snapshot().items.length,0);
+});
+test('failed avatar persistence preserves all existing images and selection', () => {
+ const { createAvatarLibrary } = load(), cache = storage({wbsAvatar:png});
+ const lib = createAvatarLibrary(cache);lib.select('workbuddy');
+ const before = JSON.stringify(lib.snapshot());
+ cache.setItem = () => { throw Error('quota'); };
+ assert.throws(()=>lib.add(webp));
+ assert.equal(JSON.stringify(lib.snapshot()),before);
+ assert.throws(()=>lib.select('workdaddy'));
+ assert.equal(JSON.stringify(lib.snapshot()),before);
+});
+test('usage background does not follow robot appearance and pointer focus has no robot outline', () => {
+ const start=source.indexOf(' function onTokenStats()');
+ const stats=source.slice(start,source.indexOf(' // ===== Tab',start));
+ assert.doesNotMatch(stats,/glassFab|wbs-token-stats-glass|data-wbs-robot-style/);
+ assert.doesNotMatch(source,/\.wbs-robot-option:focus-within/);
+ assert.match(source,/\.wbs-robot-option:has\(input:focus-visible\)/);
+});
diff --git a/test/checkin-consent-start.test.js b/test/checkin-consent-start.test.js
new file mode 100644
index 0000000..df677a9
--- /dev/null
+++ b/test/checkin-consent-start.test.js
@@ -0,0 +1,40 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const os = require('node:os');
+const vm = require('node:vm');
+const automation = require('../scripts/automation');
+const consent = require('../scripts/checkin-consent');
+const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+function harness(t) {
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-checkin-start-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
+ automation.installBuiltinTask(dir,path.join(__dirname,'../scripts/builtin/automations/daily-account-checkin.json'));
+ consent.initializeCheckinConsent(dir);
+ const runs=new Map(),started=[];
+ const ctx={...consent,DATA_DIR:dir,readAutomations:automation.readAutomations,automationRuns:runs,
+ startAutomationRun: task=>{const run={id:'run-1',taskId:task.id,status:'running'};started.push(task);runs.set(run.id,run);return run;},
+ automationPublicRun:run=>({id:run.id,status:run.status})};
+ const start=daemon.indexOf('function applyCheckinConsent('),end=daemon.indexOf('function handleApi(',start);
+ assert.ok(start>=0&&end>start);vm.createContext(ctx);vm.runInContext(daemon.slice(start,end),ctx);
+ return {dir,runs,started,apply:ctx.applyCheckinConsent};
+}
+test('first opt-in starts the configured check-in immediately without another panel event',t=>{
+ const h=harness(t);const result=h.apply(true);assert.equal(result.enabled,true);assert.equal(h.started.length,1);
+ assert.equal(h.started[0].id,'daily-account-checkin');assert.equal(result.run.id,'run-1');
+ h.apply(true);h.apply(false);assert.equal(h.started.length,1);
+});
+test('cancellation never starts check-in; an overlapping scheduled run is reused',t=>{
+ const cancelled=harness(t);cancelled.apply(false);cancelled.apply(true);assert.equal(cancelled.started.length,0);
+ const running=harness(t);running.runs.set('active',{id:'active',taskId:'daily-account-checkin',status:'running'});
+ assert.equal(running.apply(true).run.id,'active');assert.equal(running.started.length,0);
+});
+test('check-in UI notifications include cached daily successes and task completion',async()=>{
+ const a=daemon.indexOf('accountCheckin: async (account) => {'),b=daemon.indexOf('}, httpRequest:',a);
+ const events=[];const ctx={claimDailyForUid:async()=>({ok:true,skipped:true}),appendRunLog:()=>{},cdp:{connected:true},cdpSend:async(...args)=>events.push(args)};
+ vm.createContext(ctx);vm.runInContext('var checkin = async (account) => {'+daemon.slice(a+'accountCheckin: async (account) => {'.length,b)+'};',ctx);
+ await ctx.checkin({uid:'sample'});assert.equal(events.length,1);
+ const run=daemon.slice(daemon.indexOf('function startAutomationRun('),daemon.indexOf('function resumeAutomationAfterNavigation('));
+ assert.match(run,/finally\(async \(\) => \{[\s\S]*daily-account-checkin[\s\S]*workdaddy:accounts-updated/);
+});
diff --git a/test/checkin-consent-ui.test.js b/test/checkin-consent-ui.test.js
new file mode 100644
index 0000000..fc95ff5
--- /dev/null
+++ b/test/checkin-consent-ui.test.js
@@ -0,0 +1,70 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+const block = source.slice(source.indexOf(' var checkinRiskLoading ='), source.indexOf(' function setOpen(open, options)'));
+const flush = () => new Promise(resolve => setImmediate(resolve));
+function harness() {
+ const documentListeners = new Map(), disposers = [], calls = [];
+ let children = [], pending = true, fail = false;
+ const events = [];
+ function element() {
+ return { listeners: {}, disabled: false, hidden: true, isConnected: true,
+ addEventListener(type, fn) { this.listeners[type] = fn; },
+ focus() { document.activeElement = this; },
+ contains(target) { return target === this || Object.values(this.nodes || {}).includes(target); },
+ querySelector(selector) { return this.nodes[selector]; },
+ remove() { children = children.filter(child => child !== this); this.isConnected = false; },
+ };
+ }
+ const document = {
+ activeElement: element(),
+ createElement() {
+ const mask = element();
+ mask.nodes = Object.fromEntries(['[data-checkin-choice="cancel"]', '[data-checkin-choice="enable"]', '[role="alert"]', '[role="dialog"]'].map(s => [s, element()]));
+ return mask;
+ },
+ addEventListener(type, fn) { documentListeners.set(type, fn); },
+ removeEventListener(type) { documentListeners.delete(type); },
+ };
+ const context = { window: { dispatchEvent: e => events.push(e.type) }, CustomEvent: function (type) { this.type = type; }, document, alive: true, CAPS: { accounts: true, checkin: true }, state: { open: true },
+ panel: { appendChild(mask) { children.push(mask); } }, registerDisposer: fn => disposers.push(fn),
+ api: async (route, options) => {
+ calls.push({ route, options });
+ if (fail) throw new Error('offline');
+ if (options) pending = false;
+ return { shouldPrompt: pending, enabled: options ? JSON.parse(options.body).enabled : false };
+ },
+ };
+ vm.createContext(context); vm.runInContext(block, context);
+ return { context, calls, events, documentListeners, disposers, masks: () => children, fail: value => { fail = value; } };
+}
+for (const choice of ['cancel', 'enable']) test(`${choice} saves once; reopening and double clicks do not repeat`, async () => {
+ const h = harness();
+ h.context.showCheckinRiskOnOpen(); h.context.showCheckinRiskOnOpen(); await flush();
+ assert.equal(h.masks().length, 1); assert.equal(h.calls.length, 1);
+ const button = h.masks()[0].querySelector(`[data-checkin-choice="${choice}"]`);
+ button.listeners.click(); button.listeners.click(); await flush();
+ assert.equal(JSON.parse(h.calls[1].options.body).enabled, choice === 'enable');
+ assert.deepEqual(h.events, choice === 'enable' ? ['workdaddy:accounts-updated'] : []);
+ assert.equal(h.calls.length, 2); assert.equal(h.masks().length, 0); assert.equal(h.documentListeners.size, 0);
+ h.context.showCheckinRiskOnOpen(); await flush(); assert.equal(h.calls.length, 2);
+});
+test('failed save stays retryable, Escape cancels, and reinjection removes listeners', async () => {
+ const h = harness(); h.context.showCheckinRiskOnOpen(); await flush(); h.fail(true);
+ h.masks()[0].querySelector('[data-checkin-choice="enable"]').listeners.click(); await flush();
+ assert.equal(h.masks().length, 1); assert.equal(h.masks()[0].querySelector('[role="alert"]').hidden, false);
+ h.fail(false); h.documentListeners.get('keydown')({ key: 'Escape', preventDefault() {}, stopImmediatePropagation() {} }); await flush();
+ assert.equal(JSON.parse(h.calls.at(-1).options.body).enabled, false); assert.equal(h.masks().length, 0);
+ const second = harness(); second.context.showCheckinRiskOnOpen(); await flush();
+ second.disposers.forEach(fn => fn()); assert.equal(second.masks().length, 0); assert.equal(second.documentListeners.size, 0);
+});
+test('late reads cannot show on closed panels, and unsupported clients skip the request', async () => {
+ const h = harness(); h.context.showCheckinRiskOnOpen(); h.context.state.open = false; await flush(); assert.equal(h.masks().length, 0);
+ h.context.state.open = true; h.context.showCheckinRiskOnOpen(); await flush(); assert.equal(h.masks().length, 1);
+ const unsupported = harness(); unsupported.context.CAPS.checkin = false;
+ unsupported.context.showCheckinRiskOnOpen(); await flush(); assert.equal(unsupported.calls.length, 0);
+});
diff --git a/test/checkin-consent.test.js b/test/checkin-consent.test.js
new file mode 100644
index 0000000..72232d5
--- /dev/null
+++ b/test/checkin-consent.test.js
@@ -0,0 +1,70 @@
+'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 automation = require('../scripts/automation');
+const consent = require('../scripts/checkin-consent');
+const preset = path.join(__dirname, '../scripts/builtin/automations/daily-account-checkin.json');
+function fixture(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-consent-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ automation.installBuiltinTask(dir, preset);
+ return dir;
+}
+test('fresh installs stay disabled through panel events and scheduled ticks until opt-in', t => {
+ const dir = fixture(t);
+ assert.equal(automation.readAutomations(dir)[0].enabled, false);
+ consent.initializeCheckinConsent(dir);
+ const task = automation.readAutomations(dir)[0];
+ for (const event of ['pageReady', 'panelOpened']) assert.equal(automation.taskMatchesEvent(task, event), false);
+ const tick = automation.createScheduleTicker();
+ tick([task], () => assert.fail('disabled check-in ran'), () => false, 0);
+ tick([task], () => assert.fail('disabled check-in ran'), () => false, 7200000);
+ assert.equal(consent.readCheckinConsent(dir).shouldPrompt, true);
+});
+test('migration disables legacy check-in once, preserving customized steps and other tasks', t => {
+ const dir = fixture(t);
+ const tasks = automation.readAutomations(dir);
+ tasks[0].enabled = true;
+ tasks[0].name = 'My check-in';
+ tasks[0].schedule.minutes = 120;
+ tasks.push(automation.normalizeTask({ id: 'other', enabled: true, steps: [] }));
+ automation.writeAutomations(dir, tasks);
+ consent.initializeCheckinConsent(dir);
+ const migrated = automation.readAutomations(dir);
+ assert.deepEqual(migrated[0], { ...tasks[0], enabled: false });
+ assert.deepEqual(migrated[1], tasks[1]);
+ migrated[0].enabled = true;
+ automation.writeAutomations(dir, migrated);
+ consent.initializeCheckinConsent(dir);
+ assert.equal(automation.readAutomations(dir)[0].enabled, true);
+});
+for (const enabled of [true, false]) test(`choice ${enabled} persists across restart and duplicate submissions`, t => {
+ const dir = fixture(t);
+ consent.initializeCheckinConsent(dir);
+ const result = consent.decideCheckinConsent(dir, enabled);
+ assert.equal(result.shouldPrompt, false);
+ assert.equal(automation.readAutomations(dir)[0].enabled, enabled);
+ consent.initializeCheckinConsent(dir);
+ assert.equal(consent.readCheckinConsent(dir).shouldPrompt, false);
+ const tasks = automation.readAutomations(dir);
+ tasks[0].enabled = !enabled;
+ automation.writeAutomations(dir, tasks);
+ consent.decideCheckinConsent(dir, enabled);
+ assert.equal(automation.readAutomations(dir)[0].enabled, !enabled, 'late response must not overwrite a later manual edit');
+});
+test('deleted tasks are not recreated, invalid choices do not dismiss the notice, profiles are isolated', t => {
+ const dir = fixture(t), other = fixture(t);
+ consent.initializeCheckinConsent(dir);
+ assert.throws(() => consent.decideCheckinConsent(dir, 'true'));
+ assert.equal(consent.readCheckinConsent(dir).shouldPrompt, true);
+ consent.decideCheckinConsent(dir, false);
+ consent.initializeCheckinConsent(other);
+ assert.equal(consent.readCheckinConsent(other).shouldPrompt, true);
+ automation.writeAutomations(other, []);
+ assert.equal(consent.readCheckinConsent(other).shouldPrompt, false);
+ assert.throws(() => consent.decideCheckinConsent(other, true));
+ assert.deepEqual(automation.readAutomations(other), []);
+});
diff --git a/test/credit-summary.test.js b/test/credit-summary.test.js
new file mode 100644
index 0000000..214537a
--- /dev/null
+++ b/test/credit-summary.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 vm = require('node:vm');
+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
+const ctx = { isIdentityExpired: a => !!a.expired };
+vm.runInNewContext(source.slice(source.indexOf(' function summarizeCreditDays('), source.indexOf(' function checkinHtml(')), ctx);
+test('summary counts credit segments once, grouping exact remaining days across accounts', () => {
+ const now = 100000, day = 86400000;
+ const result = ctx.summarizeCreditDays([
+ { credits: 100, creditSegments: [{ remaining: 30, expiresAt: now + day }, { remaining: 70, expiresAt: now + 7 * day }] },
+ { credits: 55, creditSegments: [{ remaining: 20, expiresAt: now + day }, { remaining: 5, expiresAt: null }] },
+ { credits: null }, { credits: 100, creditUnlimited: true }, { credits: 30, expired: true },
+ ], now);
+ assert.deepEqual(JSON.parse(JSON.stringify(result)), { rows: [{ days: 1, credits: 50 }, { days: 7, credits: 70 }], accountCount: 5, unavailable: 2, unlimited: 1 });
+});
+test('zero, expired, malformed and stale oversized segments cannot inflate the total', () => {
+ const result = ctx.summarizeCreditDays([{ credits: 12, creditSegments: [null, { remaining: 'bad' }, { remaining: -5 }, { remaining: 5, expiresAt: 1 }, { remaining: 100, expiresAt: 86400001 }] }], 2);
+ assert.deepEqual(JSON.parse(JSON.stringify(result.rows)), [{ days: 0, credits: 5 }, { days: 1, credits: 7 }]);
+ assert.equal(ctx.summarizeCreditDays([], 1).rows.length, 0);
+});
diff --git a/test/macos-dmg-layout.test.js b/test/macos-dmg-layout.test.js
index 2808513..c7d3ea6 100644
--- a/test/macos-dmg-layout.test.js
+++ b/test/macos-dmg-layout.test.js
@@ -64,3 +64,11 @@ test('macOS launcher keeps official WorkBuddy targets out of enterprise mode', (
assert.match(buildSource, /<key>WBSWITCH_PROFILE<\/key>/);
assert.match(buildSource, /PLIST_STALE/);
});
+
+test('macOS packages include every SVG loaded by the injected UI builder', () => {
+ const daemon = fs.readFileSync(path.join(repoRoot, 'scripts/daemon.js'), 'utf8');
+ const builder = daemon.slice(daemon.indexOf('function buildInjectScript()'), daemon.indexOf('function buildInjectScript()') + 5000);
+ const assets = Array.from(builder.matchAll(/path\.join\(__dirname, 'assets', '([^']+\.svg)'\)/g), m => m[1]);
+ assert.ok(assets.includes('workdaddy-app-icon-source.svg'));
+ for (const asset of assets) assert.ok(buildSource.includes('scripts/assets/' + asset), 'missing packaged injection asset: ' + asset);
+});
diff --git a/test/panel-theme-controls.test.js b/test/panel-theme-controls.test.js
new file mode 100644
index 0000000..3a5bce1
--- /dev/null
+++ b/test/panel-theme-controls.test.js
@@ -0,0 +1,35 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+const section = (a,b) => source.slice(source.indexOf(a),source.indexOf(b,source.indexOf(a)));
+test('theme choices do not activate official data-theme scopes and robot radios reuse their visual component', () => {
+ const pane = section('function buildThemePane()', 'function buildEnhancePane()');
+ assert.doesNotMatch(pane, /data-theme="/);
+ assert.match(pane, /data-wbs-theme-option="dark"/);
+ assert.match(pane, /class="wbs-theme-seg wbs-robot-seg"/);
+ assert.match(pane, /class="wbs-theme-opt wbs-robot-option"/);
+ assert.match(source, /closest\('#wbs-theme-seg \.wbs-theme-opt'\)/);
+});
+test('account order is centered in the panel and always shows names without numbered rows', () => {
+ const modal = section('function openAccountOrderModal()', 'function setupCreditSummary()');
+ assert.match(modal, /wbs-modal-mask wbs-modal-mask-panel/);
+ assert.match(modal, /panel\.appendChild\(mask\)/);
+ assert.doesNotMatch(modal, /maskAccountName|wbs-account-order-hint|<small>/);
+ assert.match(modal, /esc\(name\)/);
+});
+test('avatar presets retain legacy custom uploads and are safe before official conversion completes', () => {
+ const context = {};
+ vm.runInNewContext(section(' function resolveAvatarChoice(', ' function checkinHtml('), context);
+ const choose = context.resolveAvatarChoice;
+ assert.equal(choose(null, 'official', 'brand').src, 'official');
+ assert.equal(choose('workbuddy', 'official', 'brand').preset, 'workbuddy');
+ assert.equal(choose('workdaddy', 'official', 'brand').src, 'brand');
+ assert.equal(choose('data:image/png;base64,upload', 'official', 'brand').src, 'data:image/png;base64,upload');
+ assert.equal(choose(null, null, 'brand').src, null);
+ assert.equal(choose('javascript:bad', 'official', 'brand').src, 'official');
+ assert.doesNotMatch(source, /id="wbs-avatar-reset"/);
+});
diff --git a/test/primary-account.test.js b/test/primary-account.test.js
index 864af2b..054dd04 100644
--- a/test/primary-account.test.js
+++ b/test/primary-account.test.js
@@ -24,15 +24,7 @@ test('primary selection is unique, persistent, validated and cleared on deletion
assert.equal(store.get(), '', 'deleted selection cannot revive');
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
-test('primary account uses a theme-aware vector mark and a separate setting action', () => {
+test('account page no longer exposes primary selection or badges', () => {
const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
- assert.ok(!source.includes('wbs-auto-examples-card'));
- assert.ok(!source.includes('wbs-auto-protocol-copy'));
- assert.ok(source.includes('id="wbs-auto-create"'));
- assert.ok(source.includes('var PRIMARY_ACCOUNT_SVG ='));
- assert.ok(source.includes('wbs-primary-mark'));
- assert.ok(source.includes('var ops = primaryAction + (isCur'));
- assert.ok(source.includes('item.hidden = selected'));
- assert.match(source, /wbs-primary-mark\{[^}]*color:var\(--wb-button-primary-bg/);
- assert.ok(!source.includes('wbs-primary-account'));
+ assert.doesNotMatch(source, /PRIMARY_ACCOUNT_SVG|data-primary-uid|wbs-primary-mark|primaryAction/);
});
diff --git a/test/renderer-escaping.test.js b/test/renderer-escaping.test.js
index 54297f0..3f8e902 100644
--- a/test/renderer-escaping.test.js
+++ b/test/renderer-escaping.test.js
@@ -86,8 +86,8 @@ test('model, wallpaper, and account cards escape each dynamic HTML sink', () =>
assert.doesNotMatch(wallpapers, /(?:data-wp|title|data-src|alt)="' \+ (?:w\.|wallpaperUrl)/);
const accounts = sourceBetween('function render(data)', 'function updateAccountSummary()');
- assert.equal((accounts.match(/escAttr\(a\.uid\)/g) || []).length, 3);
- assert.match(accounts, /data-primary-uid="' \+ escAttr\(a\.uid\)/);
+ assert.equal((accounts.match(/escAttr\(a\.uid\)/g) || []).length, 2);
+ assert.doesNotMatch(accounts, /data-primary-uid/);
assert.equal((accounts.match(/escAttr\(a\.nickname \|\| '未命名'\)/g) || []).length, 2);
assert.match(accounts, /var nameVal = state\.mask \? maskAccountName\(rawName\) : rawName;/);
assert.match(accounts, /var idVal = state\.mask \? maskAccountId\(rawId\) : rawId;/);
diff --git a/test/session-artifact-copy.test.js b/test/session-artifact-copy.test.js
new file mode 100644
index 0000000..7df0fcf
--- /dev/null
+++ b/test/session-artifact-copy.test.js
@@ -0,0 +1,134 @@
+'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 source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+function helpers(fsImpl = fs, log = () => {}) {
+ const ctx = { fs: fsImpl, path, log };
+ vm.runInNewContext(source.slice(source.indexOf('async function copySessionFiles('), source.indexOf('// Reconcile every live member')), ctx);
+ return ctx;
+}
+test('copied delivered artifacts retain official ownership visibility and original timestamps', async t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-artifact-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ fs.mkdirSync(path.join(dir, 'artifact-index'));
+ const file = path.join(dir, 'artifact-index', 'source.json');
+ const artifact = { id: 'file-1', kind: 'media', uri: '/outside/report.pdf', requestId: 'protocol-42', _meta: { sourceTool: 'PresentFiles', ownerConversationId: 'source' } };
+ fs.writeFileSync(file, JSON.stringify({ version: 1, artifacts: [artifact, { ...artifact, id: 'foreign', _meta: { ...artifact._meta, ownerConversationId: 'foreign' } }] }));
+ const old = new Date('2026-01-01'); fs.utimesSync(file, old, old);
+ const { copySessionFiles, sessionContentMtime } = helpers();
+ const result = await copySessionFiles(dir, 'source', 'target');
+ assert.equal(result.failed, 0);
+ const copied = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-index', 'target.json'))).artifacts;
+ // Official ConversationImpl.filterArtifactsOwnedByConversation requires this exact owner
+ // for PresentFiles outside the workspace. Request IDs and file URIs must stay intact.
+ assert.equal(copied[0]._meta.ownerConversationId, 'target');
+ assert.equal(copied[0].requestId, artifact.requestId);
+ assert.equal(copied[0].uri, artifact.uri);
+ assert.equal(copied[1]._meta.ownerConversationId, 'foreign');
+ assert.equal(JSON.parse(fs.readFileSync(file)).artifacts[0]._meta.ownerConversationId, 'source');
+ assert.equal(sessionContentMtime(dir, 'target'), sessionContentMtime(dir, 'source'));
+ await copySessionFiles(dir, 'target', 'source');
+ assert.equal(JSON.parse(fs.readFileSync(file)).artifacts[0]._meta.ownerConversationId, 'source');
+});
+
+test('legacy copies repair owners from their known lineage, including the newest copy itself', async t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-artifact-legacy-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ fs.mkdirSync(path.join(dir, 'artifact-index'));
+ const file = path.join(dir, 'artifact-index', 'copy-b.json');
+ fs.writeFileSync(file, JSON.stringify({ version: 1, artifacts: [{ id: 'a', _meta: { ownerConversationId: 'original-a' } }, { id: 'foreign', _meta: { ownerConversationId: 'unrelated' } }] }));
+ const helpers_ = helpers();
+ assert.equal((await helpers_.copySessionFiles(dir, 'copy-b', 'copy-b', ['original-a', 'copy-b'])).failed, 0);
+ assert.equal(JSON.parse(fs.readFileSync(file)).artifacts[0]._meta.ownerConversationId, 'copy-b');
+ await helpers_.copySessionFiles(dir, 'copy-b', 'copy-c', ['original-a', 'copy-b']);
+ const copied = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-index', 'copy-c.json')));
+ assert.equal(copied.artifacts[0]._meta.ownerConversationId, 'copy-c');
+ assert.equal(copied.artifacts[1]._meta.ownerConversationId, 'unrelated');
+});
+
+test('malformed index preserves the target and reports a failed copy', async t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-artifact-invalid-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ fs.mkdirSync(path.join(dir, 'artifact-index'));
+ fs.writeFileSync(path.join(dir, 'artifact-index', 'source.json'), '{bad');
+ const target = path.join(dir, 'artifact-index', 'target.json');
+ fs.writeFileSync(target, '{"version":1,"artifacts":[]}');
+ const result = await helpers().copySessionFiles(dir, 'source', 'target');
+ assert.equal(result.failed, 1);
+ assert.equal(fs.readFileSync(target, 'utf8'), '{"version":1,"artifacts":[]}');
+ assert.deepEqual(fs.readdirSync(path.dirname(target)), ['source.json', 'target.json']);
+});
+
+test('copying messages retains source times so copying cannot become the freshest edit', async t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-copy-times-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ fs.mkdirSync(path.join(dir, 'projects', 'project'), { recursive: true });
+ const file = path.join(dir, 'projects', 'project', 'source.jsonl');
+ fs.writeFileSync(file, '{"fixture":true}\n');
+ const old = new Date('2026-01-01'); fs.utimesSync(file, old, old);
+ const h = helpers(); await h.copySessionFiles(dir, 'source', 'target');
+ assert.equal(h.sessionContentMtime(dir, 'source'), h.sessionContentMtime(dir, 'target'));
+});
+
+test('repairing a legacy source preserves a concurrent official artifact update', async t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-artifact-race-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ fs.mkdirSync(path.join(dir, 'artifact-index'));
+ const file = path.join(dir, 'artifact-index', 'copy.json');
+ fs.writeFileSync(file, JSON.stringify({ version: 1, artifacts: [{ id: 'old', _meta: { ownerConversationId: 'source' } }] }));
+ const updated = JSON.stringify({ version: 1, artifacts: [{ id: 'new', _meta: { ownerConversationId: 'copy' } }] });
+ const fsImpl = { ...fs, promises: { ...fs.promises, async utimes(...args) {
+ await fs.promises.utimes(...args); fs.writeFileSync(file, updated);
+ } } };
+ const result = await helpers(fsImpl).copySessionFiles(dir, 'copy', 'copy', ['source']);
+ assert.equal(result.failed, 1);
+ assert.equal(fs.readFileSync(file, 'utf8'), updated);
+ assert.deepEqual(fs.readdirSync(path.dirname(file)), ['copy.json']);
+});
+
+test('unparseable artifact contents never appear in copy diagnostics', async t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-artifact-redacted-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ fs.mkdirSync(path.join(dir, 'artifact-index'));
+ fs.writeFileSync(path.join(dir, 'artifact-index', 'source.json'), 'private-fixture-do-not-log');
+ const logs = [];
+ await helpers(fs, value => logs.push(value)).copySessionFiles(dir, 'source', 'target');
+ assert.doesNotMatch(logs.join('\n'), /private-fixture/);
+ assert.match(logs.join('\n'), /格式不受支持/);
+});
+
+test('switch lineage synchronization repairs every legacy copy using the newest content', async t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-artifact-lineage-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ fs.mkdirSync(path.join(dir, 'artifact-index'));
+ const members = [{ uid: 'account-a', id: 'source' }, { uid: 'account-b', id: 'copy' }, { uid: 'account-c', id: 'third' }];
+ for (const [index, member] of members.entries()) {
+ const file = path.join(dir, 'artifact-index', member.id + '.json');
+ fs.writeFileSync(file, JSON.stringify({ version: 1, artifacts: [{ id: index === 1 ? 'newest-artifact' : 'old-artifact', requestId: 'protocol-42', _meta: { ownerConversationId: 'source' } }] }));
+ const time = new Date(index === 1 ? '2026-02-01' : '2026-01-01');
+ fs.utimesSync(file, time, time);
+ }
+ const h = helpers();
+ Object.assign(h, {
+ PROFILE: { kind: 'workbuddy', dataRoot: dir }, DATA_DIR: dir, SESSION_COPY_COLUMNS: ['id','user_id'],
+ getAutoCopySessionMemberRecords: () => members,
+ selectLatestAutoCopyMember: require('../scripts/lib.js').selectLatestAutoCopyMember,
+ yieldAutoCopyToRenderer: async () => {},
+ sqliteQuery: async (_, params) => [{ id: params[0], user_id: params[1], updated_at: 1 }],
+ sqliteRun: async () => {},
+ });
+ vm.runInNewContext(source.slice(source.indexOf('async function syncAutoCopyLineage('), source.indexOf('const MAX_SESSION_EXPORT_FILES')), h);
+ const result = await h.syncAutoCopyLineage('known-lineage', 'account-c');
+ assert.equal(result.sourceId, 'copy');
+ assert.equal(result.failedFiles, 0);
+ for (const member of members) {
+ const artifact = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-index', member.id + '.json'))).artifacts[0];
+ assert.equal(artifact.id, 'newest-artifact');
+ assert.equal(artifact._meta.ownerConversationId, member.id);
+ assert.equal(artifact.requestId, 'protocol-42');
+ }
+});
diff --git a/test/session-delete-confinement.test.js b/test/session-delete-confinement.test.js
index d08e34f..9634848 100644
--- a/test/session-delete-confinement.test.js
+++ b/test/session-delete-confinement.test.js
@@ -297,3 +297,19 @@ test('delete route removes recorded copies across accounts from both DB and file
assert.deepEqual(fs.readdirSync(path.join(root, 'tasks')), ['unrelated']);
assert.equal(lib.getAutoCopySession(root, 'target', 'unrelated').enabled, true);
});
+
+test('configured data root may be a directory junction while child links still fail closed', (t) => {
+ const parent = tempDir(t), real = tempDir(t), outside = tempDir(t);
+ const root = path.join(parent, 'workbuddy');
+ try { fs.symlinkSync(real, root, process.platform === 'win32' ? 'junction' : 'dir'); }
+ catch (error) { if (['EPERM', 'EACCES'].includes(error.code)) return t.skip('symlinks unavailable'); throw error; }
+ fs.mkdirSync(path.join(real, 'tasks', 'remove'), { recursive: true });
+ fs.mkdirSync(path.join(real, 'tasks', 'keep'));
+ assert.equal(loadSessionDeleteHelpers().deleteSessionFiles(root, 'remove'), 1);
+ assert.ok(fs.lstatSync(root).isSymbolicLink());
+ assert.ok(fs.existsSync(path.join(real, 'tasks', 'keep')));
+ fs.mkdirSync(path.join(outside, 'remove'));
+ fs.symlinkSync(outside, path.join(real, 'workspace'), process.platform === 'win32' ? 'junction' : 'dir');
+ assert.throws(() => loadSessionDeleteHelpers().deleteSessionFiles(root, 'remove'), /managed/);
+ assert.ok(fs.existsSync(path.join(outside, 'remove')));
+});
diff --git a/test/session-transfer.test.js b/test/session-transfer.test.js
new file mode 100644
index 0000000..d006371
--- /dev/null
+++ b/test/session-transfer.test.js
@@ -0,0 +1,166 @@
+'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 crypto = require('node:crypto');
+const { writeSessionTransfer, readSessionTransfer, receiveSessionUpload } = require('../scripts/session-transfer');
+const { Readable } = require('node:stream');
+function fixture(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-stream-test-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ return dir;
+}
+const id = '11111111-1111-4111-8111-111111111111';
+function archive(file, size) { return [{ record: { id, user_id: 'fixture-owner', title: 'fixture' }, files: [{ path: `tasks/${id}/large.bin`, source: file, size }] }]; }
+async function hash(file) {
+ const digest = crypto.createHash('sha256');
+ for await (const chunk of fs.createReadStream(file)) digest.update(chunk);
+ return digest.digest('hex');
+}
+test('a single attachment above 256 MiB exports and imports with exact bytes', async t => {
+ const dir = fixture(t), file = path.join(dir, 'large.bin'), out = path.join(dir, 'export.wds');
+ const size = 257 * 1024 * 1024 + 17;
+ const fd = fs.openSync(file, 'w');
+ fs.ftruncateSync(fd, size);
+ fs.writeSync(fd, crypto.randomBytes(65536), 0, 65536, size - 65536); fs.closeSync(fd);
+ await writeSessionTransfer(out, archive(file, size), 'fixture password');
+ const restored = await readSessionTransfer(out, 'fixture password', path.join(dir, 'staged'));
+ assert.equal(restored.sessions.length, 1);
+ const entry = restored.sessions[0].files[0];
+ assert.equal(entry.size, size);
+ assert.equal(fs.statSync(entry.source).size, size);
+ assert.equal(await hash(entry.source), await hash(file));
+});
+test('wrong passwords, tampering and truncated archives publish no extracted files', async t => {
+ const dir = fixture(t), file = path.join(dir, 'file'), out = path.join(dir, 'export.wds');
+ fs.writeFileSync(file, 'private fixture');
+ await writeSessionTransfer(out, archive(file, fs.statSync(file).size), 'password');
+ await assert.rejects(readSessionTransfer(out, 'wrong', path.join(dir, 'wrong')), /密码|损坏/);
+ const original = fs.readFileSync(out), modified = Buffer.from(original); modified[modified.length - 1] ^= 1;
+ fs.writeFileSync(out, modified);
+ await assert.rejects(readSessionTransfer(out, 'password', path.join(dir, 'tampered')), /密码|损坏/);
+ fs.writeFileSync(out, original.subarray(0, original.length - 1));
+ await assert.rejects(readSessionTransfer(out, 'password', path.join(dir, 'truncated')), /密码|损坏/);
+ for (const name of ['wrong', 'tampered', 'truncated']) assert.equal(fs.existsSync(path.join(dir, name)), false);
+});
+test('stream transport accepts fragmented metadata and binary body without text decoding', async t => {
+ const dir = fixture(t), meta = Buffer.from(JSON.stringify({ password: '中文密码', targetUid: 'owner' }));
+ const prefix = Buffer.alloc(4); prefix.writeUInt32BE(meta.length);
+ const bytes = Buffer.from([0, 255, 128, 1]), wire = Buffer.concat([prefix, meta, bytes]);
+ const chunks = Array.from(wire, byte => Buffer.from([byte]));
+ const received = await receiveSessionUpload(Readable.from(chunks), dir);
+ assert.equal(received.password, '中文密码');
+ assert.deepEqual(fs.readFileSync(received.file), bytes);
+ await assert.rejects(receiveSessionUpload(Readable.from([Buffer.from([255,255,255,255])]), dir), /元数据/);
+});
+test('export detects files changed after collection and removes partial output', async t => {
+ const dir = fixture(t), file = path.join(dir, 'file'), out = path.join(dir, 'export.wds');
+ fs.writeFileSync(file, 'changed');
+ await assert.rejects(writeSessionTransfer(out, archive(file, 1), 'password'), /变化/);
+ assert.equal(fs.existsSync(out), false);
+});
+
+test('real session export/import routes round-trip binary archives and retain ownership', async t => {
+ const vm = require('node:vm'), http = require('node:http');
+ const dir = fixture(t), home = path.join(dir, 'home');
+ const original = path.join(home, 'tasks', id, '测试附件.bin');
+ fs.mkdirSync(path.dirname(original), { recursive: true });
+ fs.writeFileSync(original, crypto.randomBytes(100001));
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const stored = [], records = [{ id, user_id: 'original-owner', title: 'fixture' }];
+ const ctx = { fs, path, os, crypto, Buffer, ...require('../scripts/secure-transfer'),
+ writeSessionTransfer, readSessionTransfer, receiveSessionUpload,
+ transferPipeline: require('node:stream/promises').pipeline,
+ PROFILE: { dataRoot: home }, MAX_SESSION_ID_LENGTH: 200,
+ normalizeSessionIdBatch: require('../scripts/session-db').normalizeSessionIdBatch,
+ sqliteQuery: async () => records, sqliteRun: async (sql, values) => stored.push(values),
+ currentAccount: () => ({ uid: 'current-owner' }), log: () => {},
+ deleteSessionFiles: (root, sessionId) => fs.rmSync(path.join(root, 'tasks', sessionId), { recursive: true, force: true }),
+ readBody: async req => { const parts = []; for await (const c of req) parts.push(c); return JSON.parse(Buffer.concat(parts)); },
+ json: (res, code, value) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(value)); },
+ };
+ vm.createContext(ctx);
+ vm.runInContext(source.slice(source.indexOf('const MAX_SESSION_EXPORT_FILES'), source.indexOf('async function copySessionRecord(')), ctx);
+ const validStart = source.indexOf('function isValidSessionId(');
+ vm.runInContext(source.slice(validStart, source.indexOf('\n}\n', validStart) + 2), ctx);
+ const routeStart = source.indexOf("if (req.method === 'POST' && p === '/api/sessions/export')");
+ vm.runInContext('function serve(req, res) { const p = req.url; ' + source.slice(routeStart, source.indexOf(' // 复制会话:POST /api/sessions/copy', routeStart)) + '\n}', ctx);
+ const server = http.createServer((req, res) => ctx.serve(req, res));
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }));
+ const base = 'http://127.0.0.1:' + server.address().port;
+ const exported = await fetch(base + '/api/sessions/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids: [id], password: '密码' }) });
+ assert.equal(exported.status, 200);
+ assert.equal(exported.headers.get('X-WorkDaddy-Count'), '1');
+ assert.match(exported.headers.get('content-type'), /octet-stream/);
+ const bytes = new Uint8Array(await exported.arrayBuffer());
+ async function upload(password, targetUid) {
+ const meta = Buffer.from(JSON.stringify({ password, targetUid })), prefix = Buffer.alloc(4); prefix.writeUInt32BE(meta.length);
+ const response = await fetch(base + '/api/sessions/import', { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: new Blob([prefix, meta, bytes]) });
+ return { status: response.status, result: await response.json() };
+ }
+ assert.equal((await upload('wrong')).status, 400);
+ assert.equal(stored.length, 0);
+ const imported = await upload('密码');
+ assert.equal(imported.status, 200);
+ assert.equal(imported.result.count, 1);
+ const newId = imported.result.imported[0].id;
+ assert.notEqual(newId, id);
+ assert.equal(stored[0][2], 'original-owner');
+ assert.deepEqual(fs.readFileSync(path.join(home, 'tasks', newId, '测试附件.bin')), fs.readFileSync(original));
+ assert.equal((await upload('密码', 'override-owner')).status, 200);
+ assert.equal(stored[1][2], 'override-owner');
+});
+
+test('panel uses Blob responses/uploads and release includes the streaming module', () => {
+ const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+ const build = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');
+ assert.doesNotMatch(daemon, /MAX_SESSION_EXPORT_BYTES|附件超过 256/);
+ assert.match(inject, /opts\.responseType === 'blob'[\s\S]*r\.blob\(\)/);
+ assert.match(inject, /new Blob\(\[prefix, metadata, file\]/);
+ assert.match(build, /session-transfer\.js/);
+ const publicPaths = daemon.match(/const PUBLIC_API_PATHS = new Set\(([\s\S]*?)\);/);
+ assert.doesNotMatch(publicPaths[1], /sessions\/(export|import)/);
+});
+
+test('empty files and sessions retain framing across multiple sessions', async t => {
+ const dir = fixture(t), empty = path.join(dir, 'empty'), out = path.join(dir, 'export.wds');
+ fs.writeFileSync(empty, '');
+ const secondId = '22222222-2222-4222-8222-222222222222';
+ await writeSessionTransfer(out, [...archive(empty, 0), { record: { id: secondId }, files: [] }], 'password');
+ const restored = await readSessionTransfer(out, 'password', path.join(dir, 'staged'));
+ assert.equal(fs.statSync(restored.sessions[0].files[0].source).size, 0);
+ assert.equal(restored.sessions[1].record.id, secondId);
+ assert.deepEqual(restored.sessions[1].files, []);
+});
+
+test('authenticated archives still reject path traversal, duplicates and excess metadata', async t => {
+ const dir = fixture(t), out = path.join(dir, 'export.wds');
+ function frame(value) { const data = Buffer.from(JSON.stringify(value)), prefix = Buffer.alloc(4); prefix.writeUInt32BE(data.length); return Buffer.concat([prefix, data]); }
+ function encode(plain) {
+ const header = Buffer.alloc(52); Buffer.from('WDS4\r\n\x1a\n').copy(header); crypto.randomFillSync(header, 8, 28);
+ const key = crypto.scryptSync('password', header.subarray(8, 24), 32);
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, header.subarray(24, 36)); cipher.setAAD(header.subarray(0, 36));
+ const data = Buffer.concat([cipher.update(require('node:zlib').gzipSync(plain)), cipher.final()]); cipher.getAuthTag().copy(header, 36);
+ return Buffer.concat([header, data]);
+ }
+ const root = frame({ type: 'archive', version: 4, count: 1 });
+ const session = count => frame({ type: 'session', record: { id }, count });
+ const file = filePath => frame({ type: 'file', path: filePath, size: 0 });
+ const relative = `tasks/${id}/valid.bin`;
+ const cases = [
+ Buffer.concat([root, session(1), file('../outside')]),
+ Buffer.concat([root, session(2), file(relative), file(relative)]),
+ Buffer.from([255,255,255,255]),
+ ];
+ for (let i = 0; i < cases.length; i++) {
+ fs.writeFileSync(out, encode(cases[i]));
+ const staging = path.join(dir, 'staged-' + i);
+ await assert.rejects(readSessionTransfer(out, 'password', staging), /路径|重复|元数据/);
+ assert.equal(fs.existsSync(staging), false);
+ }
+ assert.equal(fs.existsSync(path.join(dir, 'outside')), false);
+});
diff --git a/test/theme-blur.test.js b/test/theme-blur.test.js
index b408c28..abf1fbc 100644
--- a/test/theme-blur.test.js
+++ b/test/theme-blur.test.js
@@ -35,7 +35,7 @@ test('theme pane keeps avatar controls visible and gates wallpaper controls to W
test('theme pane uses the requested blur labels and nebula tab', () => {
// 主题第 4 个 tab 文案为「毛玻璃」,且词典含英文 Frosted glass
- assert.match(inject, /data-theme="nebula">毛玻璃<\/button>/);
+ assert.match(inject, /data-wbs-theme-option="nebula">毛玻璃<\/button>/);
assert.match(inject, /'毛玻璃': 'Frosted glass'/);
assert.doesNotMatch(inject, /背景毛玻璃<span class="wbs-blur-hint">0% 不调节背景图<\/span>/);
assert.match(inject, /<label class="wbs-blur-label" for="wbs-bg-blur-range">背景毛玻璃<\/label>/);
diff --git a/test/theme-restore-stability.test.js b/test/theme-restore-stability.test.js
index 2bc6aec..df64e2c 100644
--- a/test/theme-restore-stability.test.js
+++ b/test/theme-restore-stability.test.js
@@ -96,3 +96,27 @@ test('manually changing theme replaces the prior guard and repeating a theme reu
flush();
assert.equal(document.documentElement.getAttribute('data-theme'), 'light');
});
+
+test('native dark removes custom styles and persists official dark appearance', async () => {
+ const { context, document, observers } = renderer();
+ vm.runInNewContext(await themeExpression('nebula'), context);
+ vm.runInNewContext(await themeExpression('dark'), context);
+ assert.equal(document.getElementById('wbs-theme-style'), null);
+ assert.equal(document.documentElement.getAttribute('data-wbs-theme'), '0');
+ assert.equal(document.documentElement.getAttribute('data-theme'), 'dark');
+ assert.equal(document.body.getAttribute('data-vscode-theme-name'), 'IDE Night');
+ assert.equal(JSON.parse(context.localStorage.getItem('agent-ui-theme')).theme, 'dark');
+ assert.equal(observers.filter(o => o.active).length, 1);
+});
+
+test('native theme choices cannot be shadowed by a custom theme file with the same id', () => {
+ const ctx = {
+ BUILTIN_THEMES: { default: { dark: false, colors: {} }, dark: { dark: true, colors: {} } },
+ THEMES_DIR: '/themes', path,
+ fs: { existsSync: () => true, readFileSync: () => '{"dark":false,"colors":{"--wb-bg-primary":"red"}}' },
+ };
+ const start = source.indexOf('function getTheme(id)');
+ vm.runInNewContext(source.slice(start, source.indexOf('\n/**', start)), ctx);
+ assert.equal(ctx.getTheme('dark'), ctx.BUILTIN_THEMES.dark);
+ assert.equal(ctx.getTheme('default'), ctx.BUILTIN_THEMES.default);
+});
diff --git a/test/token-stats-import.test.js b/test/token-stats-import.test.js
new file mode 100644
index 0000000..d8ac204
--- /dev/null
+++ b/test/token-stats-import.test.js
@@ -0,0 +1,203 @@
+'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 crypto = require('node:crypto');
+const transfer = require('../scripts/secure-transfer.js');
+const { scanTokenStats, scanTokenStatsCached, tokenStatsCacheReady } = require('../scripts/token-stats.js');
+
+const now = Date.parse('2026-09-14T12:00:00+08:00');
+function fixture(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-token-import-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const sessionAccounts = { source: 'account-A', copy: 'account-B', other: 'account-C' };
+ const options = { now, days: 7, sessionAccounts };
+ const file = id => path.join(root, 'projects', 'fixture', id + '.jsonl');
+ function write(id, rows) {
+ fs.mkdirSync(path.dirname(file(id)), { recursive: true });
+ fs.writeFileSync(file(id), rows.map(row => JSON.stringify(row)).join('\n') + '\n');
+ }
+ const row = { uuid: 'message-1', requestId: 'request-1', sessionId: 'source',
+ timestamp: '2026-09-13T12:00:00+08:00', model: 'model-a',
+ message: { content: 'PRIVATE-FIXTURE-CONTENT', usage: {
+ input_tokens: 100, output_tokens: 10, cache_read_input_tokens: 80, cache_creation_input_tokens: 5,
+ } } };
+ return { root, file, write, row, options, sessionAccounts };
+}
+
+// Execute the actual encrypted import / file restore / SQL construction / copy
+// functions. Only database execution is replaced with an in-memory owner map;
+// no running daemon, real account, model request or renderer is involved.
+function transferHelpers(root, sessionAccounts) {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const context = { fs, path, crypto, Buffer, ...transfer, PROFILE: { dataRoot: root },
+ MAX_SESSION_ID_LENGTH: 200, log: () => {}, currentAccount: () => ({ uid: 'account-A' }),
+ sqliteRun: async (sql, values) => { sessionAccounts[values[0]] = values[2]; },
+ deleteSessionFiles: () => { throw new Error('Unexpected import rollback'); } };
+ function load(start, end, suffix = '') {
+ const a = source.indexOf(start), b = source.indexOf(end, a);
+ assert.ok(a >= 0 && b > a, start);
+ vm.runInNewContext(source.slice(a, b) + suffix, context);
+ }
+ load('function isValidSessionId(', '\n}\n', '\n}');
+ load('const MAX_SESSION_EXPORT_FILES', '\nfunction collectSessionArchiveFiles(');
+ load('function ensureArchiveParentNoFollow(', '\nasync function copySessionRecord(');
+ load('async function copySessionFiles(', '\nfunction sessionContentMtime(');
+ return context;
+}
+
+test('repeated encrypted imports and account copies never multiply historical usage', async t => {
+ const f = fixture(t), helpers = transferHelpers(f.root, f.sessionAccounts);
+ f.write('source', [f.row]);
+ const original = fs.readFileSync(f.file('source'));
+ const content = transfer.createEncryptedExport('sessions', {
+ exportType: 'WorkDaddy-sessions', version: 1, sessions: [{
+ record: { id: 'source', user_id: 'account-A' },
+ files: [{ path: 'projects/fixture/source.jsonl', data: original.toString('base64') }],
+ }],
+ }, 'fixture-password');
+ const baseline = scanTokenStatsCached(f.root, f.options);
+ const importedIds = [];
+ for (let n = 0; n < 3; n++) {
+ const result = await helpers.importSessions(content, 'fixture-password', 'account-B');
+ assert.equal(result.failed, 0);
+ importedIds.push(result.imported[0].id);
+ assert.deepEqual(scanTokenStatsCached(f.root, f.options).totals, baseline.totals);
+ }
+ await helpers.copySessionFiles(f.root, 'source', 'copy');
+ for (const scan of [scanTokenStats, scanTokenStatsCached]) {
+ const result = scan(f.root, f.options);
+ assert.deepEqual(result.totals, baseline.totals);
+ assert.equal(scan(f.root, { ...f.options, account: 'account-A' }).totals.input, 100);
+ assert.equal(scan(f.root, { ...f.options, account: 'account-B' }).totals.calls, 0);
+ }
+ for (const id of ['source', 'copy', ...importedIds]) assert.deepEqual(fs.readFileSync(f.file(id)), original);
+});
+
+test('continued conversations count new calls once under the account that made them', t => {
+ const f = fixture(t);
+ f.write('source', [f.row]);
+ f.write('copy', [f.row]);
+ scanTokenStatsCached(f.root, f.options);
+ const next = { ...f.row, uuid: 'message-2', sessionId: 'copy', timestamp: now - 1000, model: 'model-b' };
+ f.write('copy', [f.row, next]);
+ f.write('other', [f.row, next]);
+ for (const scan of [scanTokenStats, scanTokenStatsCached]) {
+ assert.equal(scan(f.root, f.options).totals.input, 200);
+ assert.equal(scan(f.root, { ...f.options, account: 'account-B' }).totals.input, 100);
+ assert.equal(scan(f.root, { ...f.options, account: 'account-C' }).totals.input, 0);
+ assert.equal(scan(f.root, { ...f.options, model: 'model-b', days: 1 }).totals.calls, 1);
+ assert.equal(scan(f.root, { ...f.options, days: 1 }).totals.calls, 1);
+ }
+});
+
+test('equal token values and shared request IDs do not merge distinct real records', t => {
+ const f = fixture(t);
+ const rows = [f.row, { ...f.row, uuid: 'message-2' }, { ...f.row, type: 'function_call' },
+ { ...f.row, message: { ...f.row.message, content: 'different output' } }];
+ f.write('source', rows);
+ f.write('copy', rows);
+ for (const scan of [scanTokenStats, scanTokenStatsCached]) assert.equal(scan(f.root, f.options).totals.calls, 4);
+});
+
+test('legacy rows without IDs and repeated identical rows within one file retain multiplicity', t => {
+ const f = fixture(t);
+ const row = { timestamp: f.row.timestamp, usage: { input_tokens: 7 }, message: 'legacy fixture' };
+ f.write('source', [row, row]);
+ f.write('copy', [row, row]);
+ for (const scan of [scanTokenStats, scanTokenStatsCached]) {
+ assert.equal(scan(f.root, f.options).totals.input, 14);
+ assert.equal(scan(f.root, f.options).totals.calls, 2);
+ assert.equal(scan(f.root, f.options).accounts.length, 0, 'conflicting owners without provenance stay unattributed');
+ }
+});
+
+test('source deletion, changed copies and cache rebuilds retain only surviving distinct usage', t => {
+ const f = fixture(t);
+ f.write('source', [f.row]); f.write('copy', [f.row]);
+ assert.equal(scanTokenStatsCached(f.root, f.options).totals.calls, 1);
+ fs.unlinkSync(f.file('source'));
+ delete f.sessionAccounts.source;
+ const result = scanTokenStatsCached(f.root, f.options);
+ assert.equal(result.totals.calls, 1);
+ assert.equal(result.accounts.length, 0, 'missing original owner is not charged to the copy owner');
+ f.write('copy', [{ ...f.row, uuid: 'new-message', sessionId: 'copy' }]);
+ assert.equal(scanTokenStatsCached(f.root, f.options).totals.calls, 1);
+ fs.unlinkSync(path.join(f.root, '.workdaddy-token-stats-cache.json'));
+ assert.equal(scanTokenStatsCached(f.root, f.options).totals.calls, 1);
+ fs.unlinkSync(f.file('copy'));
+ assert.equal(scanTokenStatsCached(f.root, f.options).totals.calls, 0);
+});
+
+test('cached ownership changes resolve without rereading unchanged message files', t => {
+ const f = fixture(t);
+ f.write('source', [f.row]); f.write('copy', [f.row]);
+ scanTokenStatsCached(f.root, f.options);
+ const read = fs.readFileSync;
+ let reads = 0;
+ fs.readFileSync = function(file, ...args) { if (String(file).endsWith('.jsonl')) reads++; return read.call(this, file, ...args); };
+ t.after(() => { fs.readFileSync = read; });
+ f.sessionAccounts.source = 'account-D';
+ for (const days of [1, 7, 30, 90]) scanTokenStatsCached(f.root, { ...f.options, days });
+ const result = scanTokenStatsCached(f.root, { ...f.options, account: 'account-D' });
+ assert.equal(result.totals.input, 100);
+ assert.equal(reads, 0);
+});
+
+test('old inflated cache is invalidated and cache contains no message content', t => {
+ const f = fixture(t);
+ f.write('source', [f.row]); f.write('copy', [f.row]);
+ scanTokenStatsCached(f.root, f.options);
+ const file = path.join(f.root, '.workdaddy-token-stats-cache.json');
+ const cache = JSON.parse(fs.readFileSync(file, 'utf8'));
+ cache.version = 7;
+ fs.writeFileSync(file, JSON.stringify(cache));
+ assert.equal(tokenStatsCacheReady(f.root, f.options), false);
+ const result = scanTokenStatsCached(f.root, f.options);
+ assert.equal(result.cacheHit, false);
+ assert.equal(result.totals.calls, 1);
+ assert.doesNotMatch(fs.readFileSync(file, 'utf8'), /PRIVATE-FIXTURE-CONTENT|message-1|request-1/);
+ assert.doesNotMatch(JSON.stringify(result), /PRIVATE-FIXTURE-CONTENT|message-1|request-1/);
+});
+
+test('explicit account metadata wins, snapshots and subagent copies remain excluded', t => {
+ const f = fixture(t);
+ f.write('copy', [{ ...f.row, accountUid: 'account-original' }, { ...f.row, isSnapshotUpdate: true }]);
+ fs.mkdirSync(path.join(f.root, 'projects', 'fixture', 'subagents'));
+ fs.writeFileSync(path.join(f.root, 'projects', 'fixture', 'subagents', 'duplicate.jsonl'), JSON.stringify(f.row));
+ for (const scan of [scanTokenStats, scanTokenStatsCached]) {
+ const result = scan(f.root, f.options);
+ assert.equal(result.totals.calls, 1);
+ assert.equal(result.accounts[0].account, 'account-original');
+ }
+});
+
+test('AI providerData usage copies preserve all counters and newly appended calls', t => {
+ const f = fixture(t);
+ const row = { id: 'ai-1', conversationId: 'source', timestamp: now - 1000, type: 'function_call',
+ providerData: { model: 'ai-model', usage: { inputTokens: 42, outputTokens: 7, cacheReadTokens: 20, cacheWriteTokens: 3 } } };
+ f.write('source', [row]); f.write('copy', [row]);
+ for (const scan of [scanTokenStats, scanTokenStatsCached]) {
+ assert.deepEqual(scan(f.root, f.options).totals, { input: 42, output: 7, cacheRead: 20, cacheWrite: 3, calls: 1 });
+ }
+ f.write('copy', [row, { ...row, id: 'ai-2', conversationId: 'copy' }]);
+ for (const scan of [scanTokenStats, scanTokenStatsCached]) {
+ assert.equal(scan(f.root, f.options).totals.calls, 2);
+ assert.equal(scan(f.root, { ...f.options, account: 'account-B' }).totals.input, 42);
+ }
+});
+
+test('importing an undated legacy row does not move its cached usage to today', t => {
+ const f = fixture(t), row = { uuid: 'undated', usage: { input_tokens: 8 } };
+ f.write('source', [row]);
+ const first = scanTokenStatsCached(f.root, { ...f.options, now: now - 86400000 });
+ f.write('copy', [row]);
+ const later = scanTokenStatsCached(f.root, f.options);
+ assert.equal(later.totals.input, 8);
+ assert.deepEqual(later.daily, first.daily);
+ assert.equal(scanTokenStatsCached(f.root, { ...f.options, days: 1 }).totals.calls, 0);
+});
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index 6ee64e1..728e57b 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -210,7 +210,7 @@ test('WorkDaddy-triggered reload injects on the new main execution context befor
assert.match(yieldHelper, /await reloadPriority/);
assert.match(yieldHelper, /pendingReloadInjection/);
assert.match(yieldHelper, /await pending\.ready/);
- const syncEnd = script.indexOf('\nconst MAX_SESSION_EXPORT_BYTES', syncStart);
+ const syncEnd = script.indexOf('\nconst MAX_SESSION_EXPORT_FILES', syncStart);
const syncLineage = script.slice(syncStart, syncEnd);
assert.ok((syncLineage.match(/await yieldAutoCopyToRenderer\(\)/g) || []).length >= 2, 'lineage scans and copies must pause for renderer reloads');
assert.match(switchRoute, /const releaseRendererReload = body\.reload \? beginRendererReloadPriority\(\) : null/);
@@ -656,7 +656,7 @@ test('Windows Setup waits for WorkBuddy and stops only a native-verified profile
assert.match(installer, /if IsAdmin and not ConfirmElevatedInstall/);
assert.match(installer, /MB_YESNO/);
assert.match(installer, /IDYES/);
- assert.match(installer, /if IsAdmin then\s+exit;/);
+ assert.match(installer, /if IsAdmin and not ElevatedSessionConfirmed then\s+exit;/);
assert.doesNotMatch(installer, /if IsAdminInstallMode then/);
assert.match(installer, /当前安装程序是以管理员权限运行的/);
assert.match(installer, /仍然继续安装/);
@@ -789,19 +789,10 @@ test('account cards keep the compact three-row layout', () => {
assert.match(script, /\.wbs-credit-segment:last-child\{border-radius:0 3px 3px 0\}/);
assert.match(script, /cursor:default/);
assert.doesNotMatch(script, /data-tip="' \+ attrTip \+ '" title=/);
- assert.match(script, /diff <= day/);
- assert.match(script, /diff <= 3 \* day/);
- assert.match(script, /diff <= 7 \* day/);
- assert.match(script, /diff <= 15 \* day/);
- assert.match(script, /30 \* day/);
- assert.match(script, /\.wbs-credit-segment\.safe\{background:rgba\(34,197,94,\.78\)/);
- assert.match(script, /\.wbs-credit-segment\.within30\{background:rgba\(34,197,94,\.62\)/);
- assert.match(script, /\.wbs-credit-segment\.within15\{background:rgba\(34,197,94,\.46\)/);
- assert.match(script, /\.wbs-credit-segment\.within7\{background:rgba\(34,197,94,\.32\)/);
- assert.match(script, /\.wbs-credit-segment\.within3\{background:rgba\(34,197,94,\.20\)/);
- assert.match(script, /\.wbs-credit-segment\.within1\{background:rgba\(34,197,94,\.10\)/);
- assert.match(script, /html\.cb-dark \.wbs-credit-segment\.safe\{background:rgba\(126,134,255,\.82\)/);
- assert.match(script, /html\.cb-dark \.wbs-credit-segment\.within1\{background:rgba\(126,134,255,\.12\)/);
+ assert.match(script, /creditOpacity\(row\.days\)/);
+ assert.match(script, /creditOpacity\(segment\.expiresAt/);
+ assert.match(script, /background:rgba\(34,197,94,var\(--wbs-credit-alpha,1\)\)/);
+ assert.match(script, /background:rgba\(126,134,255,var\(--wbs-credit-alpha,1\)\)/);
assert.match(script, /\.wbs-checkin-tag\.ok\{background:#edf9ef/);
assert.match(script, /html\.cb-dark \.wbs-checkin-tag\.ok,html\[data-theme="dark"\] \.wbs-checkin-tag\.ok\{/);
assert.match(script, /今日签到/);
diff --git a/test/usage-activity.test.js b/test/usage-activity.test.js
index c443645..1b6f5a7 100644
--- a/test/usage-activity.test.js
+++ b/test/usage-activity.test.js
@@ -25,7 +25,7 @@ test('foreground activity is throttled, rolls over at Beijing midnight and clean
doc.visibilityState = 'hidden'; activity.notify();
doc.visibilityState = 'visible'; doc.hasFocus = () => false; activity.notify();
doc.hasFocus = () => true; enabled = false; activity.notify();
- assert.equal(calls, 2);
+ assert.equal(calls, 3);
enabled = true; activity.notify();
assert.equal(calls, 3);
activity.destroy();
@@ -43,3 +43,11 @@ test('usage route retains local authorization and About describes anonymous coun
assert.match(inject, /registerDisposer\(function \(\) \{ usageActivity.destroy\(\); \}\)/);
assert.match(inject, /匿名安装数和日活/);
});
+
+test('diagnostic settings do not gate activity signals or cancel usage requests', () => {
+ const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+ const setup = inject.slice(inject.indexOf('var usageActivity ='), inject.indexOf('var alive = true;', inject.indexOf('var usageActivity =')));
+ assert.doesNotMatch(setup, /WBS_DIAGNOSTICS_ENABLED/);
+ assert.doesNotMatch(daemon, /usageReporter\.cancel\(/);
+});
diff --git a/test/usage-report.test.js b/test/usage-report.test.js
index 95fdeec..dfb12c6 100644
--- a/test/usage-report.test.js
+++ b/test/usage-report.test.js
@@ -31,10 +31,10 @@ test('usage uses Beijing day and survives restart without duplicate reports', as
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 => {
+test('usage still sends with diagnostics disabled but requires persistent identity', async t => {
const f = fixture(t); f.disable();
await f.reporter.report();
- assert.equal(f.calls.length, 0);
+ assert.equal(f.calls.length, 1);
const missing = fixture(t, { installationId: () => null });
await missing.reporter.report();
assert.equal(missing.calls.length, 0);
@@ -82,7 +82,7 @@ test('separate profile reporters share the daily lock and a crashed lock recover
assert.equal(fs.existsSync(lock), false);
});
-test('disabling telemetry can abort the pending request and release its lock', async t => {
+test('explicit reporter cancellation can release its pending request lock', async t => {
let aborted = false;
const f = fixture(t, { send: (_body, signal) => new Promise(resolve => {
signal.addEventListener('abort', () => { aborted = true; resolve({ status: 0 }); });
diff --git a/test/windows-elevated-consent.test.js b/test/windows-elevated-consent.test.js
new file mode 100644
index 0000000..411b580
--- /dev/null
+++ b/test/windows-elevated-consent.test.js
@@ -0,0 +1,131 @@
+'use strict';
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const test = require('node:test');
+const boundary = require('../scripts/windows-process-boundary.js');
+const read = (name) => fs.readFileSync(path.join(__dirname, '..', name), 'utf8');
+
+// Windows APIs and Inno UI need Windows; lock down their integration here.
+test('installer obtains explicit consent before cleanup and enables subsequent shortcut launches', () => {
+ const src = read('scripts/win/workdaddy.iss');
+ assert.match(src, /--desktop-token-status/);
+ assert.match(src, /Caption := '我已了解风险,继续安装'/);
+ assert.match(src, /Button\.Default := False/);
+ assert.match(src, /CancelButton\.Default := True/);
+ assert.match(src, /WizardSilent[\s\S]*--check-elevated-session/);
+ assert.match(src, /--accept-elevated-session --app-dir/);
+ assert.match(src, /function ShouldLaunchElevatedSession[\s\S]*Result := ElevatedSessionConfirmed/);
+ assert.match(src, /if IsAdmin and not ElevatedSessionConfirmed then\s+exit/);
+ assert.match(src, /if ElevatedSessionConfirmed then[\s\S]*Result := Exec\(/);
+ const prepare = src.slice(src.indexOf('function PrepareToInstall'));
+ assert.ok(prepare.indexOf('ConfirmElevatedInstall') < prepare.indexOf('EnsureWorkBuddyClosed'));
+});
+
+test('elevated exception requires unsplit desktop token and persisted user/profile/install consent', () => {
+ const src = read('scripts/windows-native/main.go');
+ assert.match(src, /func desktopSessionSupportsElevated/);
+ assert.match(src, /tokenElevationType/);
+ assert.match(src, /elevationType != 1/);
+ assert.match(src, /shellSID == currentSID/);
+ assert.match(src, /windows-elevated-consent\.json/);
+ assert.match(src, /consent\.Version == 1/);
+ assert.match(src, /consent\.Profile == profile/);
+ assert.match(src, /samePath\(consent\.AppDir, appDir\)/);
+ assert.match(src, /consent\.UserSID == sid/);
+ assert.match(src, /func elevatedSessionAllowed[\s\S]*desktopSessionSupportsElevated/);
+ assert.match(src, /func terminateExactProcess[\s\S]*verifySameProcessSecurity\(handle\)/);
+ assert.match(src, /--launch-context/);
+ assert.match(src, /elevated && !elevatedSessionAllowed/);
+});
+
+test('native privilege query validates real helper response and never defaults errors to standard', () => {
+ for (const privilege of ['standard', 'elevated']) {
+ const actual = boundary.detectNativeWindowsPrivilege('C:\\Apps\\WorkDaddy', 'workbuddy-cn', (exe, args) => {
+ assert.match(exe, /WorkDaddyLauncher\.exe$/);
+ assert.deepEqual(args, ['--launch-context', '--profile', 'workbuddy-cn', '--app-dir', 'C:\\Apps\\WorkDaddy']);
+ return { status: 0, stdout: JSON.stringify({ profile: 'workbuddy-cn', privilege }) };
+ });
+ assert.equal(actual, privilege);
+ }
+ for (const result of [
+ { status: 5, stdout: '{"privilege":"elevated","profile":"workbuddy-cn"}' },
+ { status: 0, stdout: '{}' },
+ { status: 0, stdout: 'broken' },
+ { status: 0, stdout: '{"privilege":"unknown","profile":"workbuddy-cn"}' },
+ { status: 0, stdout: '{"privilege":"elevated","profile":"workbuddy-ai"}' },
+ { status: null, error: new Error('timeout') },
+ ]) assert.throws(() => boundary.detectNativeWindowsPrivilege('C:\\Apps\\WorkDaddy', 'workbuddy-cn', () => result));
+});
+
+test('native daemon reuse requires matching actual privilege as well as profile/build/data identity', () => {
+ const src = read('scripts/win-launcher.js');
+ const fn = src.slice(src.indexOf('function nativeDaemonStatusMatches('), src.indexOf('\nasync function waitForNativeDaemon'));
+ const baseline = { ok: true, profile: { id: 'workbuddy-cn' }, dataDir: 'data', version: '1', buildId: 'build', privilege: 'elevated' };
+ for (const privilege of ['elevated', 'standard']) {
+ const context = vm.createContext({ WINDOWS_PRIVILEGE: privilege, readDaemonIdentity: () => ({ version: '1', buildId: 'build' }), PROFILE: { id: 'workbuddy-cn' }, DATA_DIR: 'data', sameWindowsPath: (a, b) => a === b });
+ vm.runInContext(fn, context);
+ const status = { ...baseline, privilege };
+ assert.equal(context.nativeDaemonStatusMatches(status), true);
+ for (const delta of [{ privilege: privilege === 'standard' ? 'elevated' : 'standard' }, { version: 'old' }, { buildId: 'old' }, { dataDir: 'other' }, { profile: { id: 'workbuddy-ai' } }]) {
+ assert.equal(context.nativeDaemonStatusMatches({ ...status, ...delta }), false);
+ }
+ }
+ assert.match(read('scripts/daemon.js'), /detectNativeWindowsPrivilege/);
+ assert.doesNotMatch(read('scripts/daemon.js'), /WBSWITCH_NATIVE_LAUNCHER === '1' \? 'standard'/);
+ assert.match(src, /function hasElevatedSessionConsent[\s\S]*--check-elevated-session/);
+});
+
+test('native consent policy rejects missing, corrupt, foreign and no-longer-eligible consent', (t) => {
+ const { spawnSync } = require('node:child_process');
+ const os = require('node:os');
+ if (spawnSync('go', ['version']).status !== 0) return t.skip('Go compiler unavailable');
+ const source = read('scripts/windows-native/main.go');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-consent-policy-'));
+ try {
+ // Compile the actual policy functions unchanged. Only Win32 probes are
+ // substituted, so refusal and persistence can be tested on macOS/Linux.
+ const policy = source.slice(source.indexOf('func elevatedSessionAllowed('), source.indexOf('\nfunc helperAppDir('));
+ const structure = source.slice(source.indexOf('type elevatedConsent struct'), source.indexOf('\nfunc tokenDword('));
+ fs.writeFileSync(path.join(dir, 'policy.go'), `package main
+import ("encoding/json"; "errors"; "os"; "path/filepath"; "strings")
+var eligible = true
+var activeSID = "test-user"
+var root string
+func desktopSessionSupportsElevated() bool { return eligible }
+func currentUserSID() (string, error) { return activeSID, nil }
+func dataDir(profile string) (string, error) { return filepath.Join(root, profile), nil }
+func samePath(a, b string) bool { return strings.EqualFold(filepath.Clean(a), filepath.Clean(b)) }
+${structure}
+${policy}`);
+ fs.writeFileSync(path.join(dir, 'policy_test.go'), `package main
+import ("os"; "path/filepath"; "testing")
+func TestConsent(t *testing.T) {
+ root = t.TempDir()
+ app := filepath.Join(root, "install")
+ if elevatedSessionAllowed("cn", app) { t.Fatal("missing consent allowed") }
+ if err := saveElevatedConsent("cn", app); err != nil { t.Fatal(err) }
+ if !elevatedSessionAllowed("cn", app) { t.Fatal("accepted consent rejected") }
+ if elevatedSessionAllowed("ai", app) { t.Fatal("foreign profile allowed") }
+ if elevatedSessionAllowed("cn", app+"-other") { t.Fatal("foreign install allowed") }
+ if elevatedSessionAllowed("cn", "relative") { t.Fatal("relative path allowed") }
+ activeSID = "another-user"
+ if elevatedSessionAllowed("cn", app) { t.Fatal("foreign user allowed") }
+ activeSID = "test-user"
+ eligible = false
+ if elevatedSessionAllowed("cn", app) { t.Fatal("ordinary desktop bypassed downgrade") }
+ if err := saveElevatedConsent("ai", app); err == nil { t.Fatal("ineligible session saved consent") }
+ eligible = true
+ name := filepath.Join(root, "cn", "windows-elevated-consent.json")
+ for _, contents := range []string{"", "{", "null", "{}", "[]", "{\\\"version\\\":2}"} {
+ if err := os.WriteFile(name, []byte(contents), 0600); err != nil { t.Fatal(err) }
+ if elevatedSessionAllowed("cn", app) { t.Fatal("invalid consent accepted", contents) }
+ }
+ if err := saveElevatedConsent("cn", app); err != nil { t.Fatal(err) }
+ if !elevatedSessionAllowed("cn", app) { t.Fatal("repaired consent rejected") }
+}`);
+ const result = spawnSync('go', ['test', 'policy.go', 'policy_test.go'], { cwd: dir, encoding: 'utf8', timeout: 60000 });
+ assert.equal(result.status, 0, result.stderr + result.stdout);
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+});
diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.js
index 39a4582..33742db 100644
--- a/test/windows-native-flow.test.js
+++ b/test/windows-native-flow.test.js
@@ -81,7 +81,7 @@ test('WorkBuddy GUI startup stays visible while the watchdog stays hidden', () =
assert.match(watchdog, /spawn\(process\.execPath, args, \{ stdio: 'ignore', windowsHide: true/);
});
-test('installer confirms elevated setup but keeps lifecycle work and auto-launch standard-only', () => {
+test('installer keeps default lifecycle standard-only and gates the elevated session exception', () => {
const installer = read('scripts/win/workdaddy.iss');
assert.match(installer, /function EnsureWorkBuddyClosed/);
@@ -95,7 +95,7 @@ test('installer confirms elevated setup but keeps lifecycle work and auto-launch
assert.match(installer, /if IsAdmin and not ConfirmElevatedInstall/);
assert.match(installer, /MB_YESNO/);
assert.match(installer, /IDYES/);
- assert.match(installer, /if IsAdmin then\s+exit;/);
+ assert.match(installer, /if IsAdmin and not ElevatedSessionConfirmed then\s+exit;/);
assert.doesNotMatch(installer, /if IsAdminInstallMode then/);
assert.match(installer, /当前安装程序是以管理员权限运行的/);
assert.match(installer, /ExecAsOriginalUser\(/);