Skip to content

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

- 新增“自动化”Tab 页,预制了一些自动化任务包括:多账号静默签到、自动关闭首页活动弹窗,以及依次切换账号发送固定消息; - 账号页展示连续活跃天数; - 适配国内版新的登录认证域名; - 账号列表不再突然换位; - 机器人按钮支持自动收起; - 其他细节优化和问题修复;

[email protected]df71ec8f4842
diff --git a/.gitignore b/.gitignore
index 0af9da4..b9d5349 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,11 @@ npm-debug.log*
# 构建产物与安装包
WorkDaddy.app
+/release/**/*.dmg
+/release/**/*.exe
+/release/**/*.zip
+/release/**/*.pkg
+/release/**/*.tar.gz
# 本地运行数据与日志
*.log
@@ -19,5 +24,8 @@ scripts/picker-internal.js
.workbuddy/
.workbuddy-ai/
+# 本地维护文档与排查记录
+/.private-docs/
+
# 构建缓存(安装器临时产物)
release/.cache/
diff --git a/README.md b/README.md
index 2cfc55f..0e9fce6 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
**语言:** [简体中文](README.md) · [English](README_en.md)
-> **WorkDaddy 是 WorkBuddy 桌面端增强助手:多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能,账号与配置全部留在本机。**
+> **WorkDaddy 是 WorkBuddy 桌面端增强助手:多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;自动化任务按事件或定时执行;暂存/快捷提示词;毛玻璃主题与更多实用功能,账号与配置全部留在本机。**
> 本机回环 CDP 注入 · 不改官方安装包。
一个基于 **Chrome DevTools Protocol (CDP)** 的 [WorkBuddy](https://www.workbuddy.cn/)、[WorkBuddy AI](https://www.workbuddy.ai/) 桌面端增强工具。
@@ -12,20 +12,16 @@
![Platform](https://img.shields.io/badge/platform-macOS%2011%2B%20%7C%20Windows%2010%2F11-lightgrey)
![Node](https://img.shields.io/badge/node-%E2%89%A518-green)
-
---
## 演示
-**面板预览**
-![面板预览图](docs/images/accounts.png)
-
-**输入框预览**
-![输入框预览图](docs/images/input1.jpg)
-![输入框预览图](docs/images/input2.png)
+<img src="docs/images/accounts-light.jpg" width="440">
+<img src="docs/images/accounts-dark.jpg" width="440">
-**主题效果(非最新版)**
-![WorkDaddy 演示](docs/images/demo.gif)
+![界面预览图](docs/images/pannel-enhance.png)
+![界面预览图](docs/images/pannel-robot.png)
+![界面预览图](docs/images/pannel-theme.png)
---
@@ -34,7 +30,8 @@
- **方便切换账号**:每个 WorkBuddy 账号独立备份,点一下就切,再也不用每次扫码。
- **无感登录新账号**:「登录新账号」支持免退出 OAuth 授权——不退出 WorkBuddy,在浏览器完成扫码后新账号自动加入列表;也可选传统的「假退出」方式回登录页扫码。
- **账号导入导出**:把全部账号备份加密导出,在另一台电脑安装 WorkDaddy 后一键导入,方便电脑之间迁移账号。
-- **自动领每日积分**:打开面板即对全部账号静默签到,幂等缓存,不打断你。
+- **自动领每日积分**:由自动化任务管理多账号每日签到,缓存已完成状态,不打断你。
+- **自动化任务**:用自然语言让 WorkBuddy 创建任务,或自行编辑步骤;支持手动、事件和定时触发,以及运行日志、停止任务和 JSON / ZIP 导入导出。
- **权限弹窗免打扰**:真正的零决策弹窗弹出,可以放心开启任务后睡觉。
- **暂存提示词**:输入框边上一键把草稿「暂存」到待发送队列——图片 / 文件 / 引用原样保留,择机发送。
- **切换精美主题**:内置毛玻璃官方主题,多套预设壁纸,支持自定义壁纸。
@@ -44,25 +41,28 @@
- **异常中断会话自动继续**:AI 回复因网络波动、超时等原因中断时,自动让异常中断任务继续执行。
- **快捷短语**:常用语存进面板,输入框操作栏一键点发;
-
---
## 安装
->- 国内版 [WorkBuddy](https://www.workbuddy.cn/) 请下载 `WorkDaddy` 安装包
->- 国际版 [WorkBuddy AI](https://www.workbuddy.ai/) 请下载 `WorkDaddy AI` 安装包
+> - 国内版 [WorkBuddy](https://www.workbuddy.cn/) 请下载 `WorkDaddy` 安装包
+> - 国际版 [WorkBuddy AI](https://www.workbuddy.ai/) 请下载 `WorkDaddy AI` 安装包
### macOS
1. 在 [Releases](../../releases) 下载最新 `WorkDaddy-x.y.z.dmg`
+
2. 打开 dmg,把 `WorkDaddy.app` 拖进 **应用程序** 文件夹
+
3. 第一次打开如果遇到「无法打开,因为 Apple 无法检查恶意软件」:
+
1. 打开「系统设置 → 隐私与安全性」
2. 在「WorkDaddy 已被阻止」处点 **仍要打开**
3. 输入开机密码确认
- ![安装引导](docs/images/install-guide.png)
+ ![安装引导](docs/images/install-guide.png)
4. 双击 `WorkDaddy.app` 启动:它会自带守护进程并把组件注入到 WorkBuddy
+
5. 看到机器人按钮?**搞定**。
#### 企业专享版 / VPC 客户端
@@ -76,7 +76,6 @@ node scripts/workbuddy-target.js --configure --platform darwin \
--data-dir "$HOME/Library/Application Support/WorkDaddy"
```
-
### Windows
1. 在 [Releases](../../releases) 下载对应客户端的 `WorkDaddy-Setup-x.y.z.exe` 或 `WorkDaddy-AI-Setup-x.y.z.exe`
@@ -89,7 +88,6 @@ node scripts/workbuddy-target.js --configure --platform darwin \
选择结果保存在 WorkDaddy 的个人数据目录中。更新安装默认保留上次选择,也可以在安装向导中修改;需要改回官方客户端时,重新运行安装程序并选择自动识别出的官方 `.exe`。WorkDaddy 会锁定所选客户端版本,客户端升级或移动后同样通过安装程序重新确认。
-
### 从源码运行(开发者)
```bash
@@ -108,7 +106,7 @@ WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh
暂存提示词和主题功能在两个 WorkBuddy profile 开启。CodeBuddy profile 的适配暂缓,不进入当前发布包。
-当前发布脚本只打包两个 WorkBuddy 客户端,共 4 个包:`WorkDaddy-<version>.dmg`、`WorkDaddy-AI-<version>.dmg`,以及对应的 `-win64.zip`;传 `WORKDADDY_BUILD_PROFILE=workbuddy-cn` 或 `workbuddy-ai` 可单独重打一个客户端。CodeBuddy profile 代码暂不进入发布包。
+当前发布脚本只打包两个 WorkBuddy 客户端,共 4 个包:`WorkDaddy-<version>.dmg`、`WorkDaddy-AI-<version>.dmg`、`WorkDaddy-Setup-<version>.exe`、`WorkDaddy-AI-Setup-<version>.exe`。macOS 构建时传 `WORKDADDY_BUILD_PROFILE=workbuddy-cn` 或 `workbuddy-ai` 可单独重打一个客户端。Windows ZIP 仅作安装器构建的临时输入,不作为发布包。
`install.sh` 做了:
@@ -139,9 +137,9 @@ WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh
1. **不修改 WorkBuddy 二进制**:用 `launcher` 启动 WorkBuddy 时多带一个 `--remote-debugging-port=9222` 参数,**二进制与签名原封不动**。
2. **守护进程通过 CDP 连接 WorkBuddy**:监听登录/认证网络事件 + 文件监听兜底,每次登录/刷新令牌都把当前登录信息按 `account.uid` 备份到稳定目录。
-3. **注入界面组件**:`Runtime.evaluate` 把 `inject.js` 推到渲染进程执行,在右下角渲染机器人按钮和 7 标签页面板(账号 / 主题 / 会话 / 模型 / 增强 / 电脑 / 关于)。
+3. **注入界面组件**:`Runtime.evaluate` 把 `inject.js` 推到渲染进程执行,在右下角渲染机器人按钮和多标签页面板(账号 / 主题 / 会话 / 模型 / 增强 / 自动化 / 电脑 / 关于 / 设置)。
4. **本地 HTTP API**:daemon 在 `127.0.0.1:47832` 起服务,组件通过 fetch 调用(账号切换、主题应用、签到、决策弹窗开关、休眠控制等)。
-5. **数据边界清晰**:账号备份和本地配置保存在本机;按功能访问 WorkBuddy 官方 API(登录、积分)和 GitHub Releases(更新检查),显式执行模型连通测试时会向你配置的模型服务发送请求及对应 API Key;默认不发送诊断遥测。
+5. **数据边界清晰**:账号备份和本地配置保存在本机;按功能访问 WorkBuddy 官方 API(登录、积分)和 GitHub Releases(更新检查),显式执行模型连通测试时会向你配置的模型服务发送请求及对应 API Key;脱敏错误诊断默认开启,可在「关于」页关闭。
> 为什么用 CDP 而不是官方插件机制:直接面向运行中的应用实例,事件级感知登录变化,
> 主动注入界面与样式补丁,**官方升级 WorkBuddy 后只要界面没大改就照常工作**。
@@ -154,21 +152,34 @@ WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh
WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:
-| Tab | 能做什么 |
-| -------- | -------- |
-| **账号** | 查看账号数、积分、签到和登录状态;切换、删除或登录新账号,并加密导入导出账号备份 |
-| **主题** | 切换默认 / WorkDaddy 主题,选择或上传壁纸、更换头像,调整毛玻璃和背景蒙版 |
-| **会话** | 按账号和时间筛选会话,批量复制或删除,并设置会话 / 工作空间在切换账号时自动复制 |
-| **模型** | 管理当前模型和备选模型,支持备份、复制、编辑、启用、连通测试及批量删除 |
-| **增强** | 配置权限免打扰、异常中断自动续接、暂存提示词和快捷短语 |
-| **电脑** | 允许或持续禁止休眠,也可在所有 AI 任务结束后自动恢复休眠 |
-| **关于** | 查看版本和项目说明、检查并安装更新、控制脱敏错误诊断 |
-| **设置** | 选择中文或英语;首次打开按系统语言匹配,未匹配时使用英语 |
+| Tab | 能做什么 |
+| ------- | ---------------------------------------------------- |
+| **账号** | 查看账号数、积分、签到和登录状态;切换、删除或登录新账号,并加密导入导出账号备份 |
+| **主题** | 切换默认 / WorkDaddy 主题,选择或上传壁纸、更换头像,调整毛玻璃和背景蒙版 |
+| **会话** | 按账号和时间筛选会话,批量复制或删除,并设置会话 / 工作空间在切换账号时自动复制 |
+| **模型** | 管理当前模型和备选模型,支持备份、复制、编辑、启用、连通测试及批量删除 |
+| **增强** | 配置权限免打扰、异常中断自动续接、暂存提示词和快捷短语 |
+| **自动化** | 创建和管理任务,配置事件或定时触发,查看运行日志,停止运行中的任务,以及 JSON / ZIP 导入导出 |
+| **电脑** | 允许或持续禁止休眠,也可在所有 AI 任务结束后自动恢复休眠 |
+| **关于** | 查看版本和项目说明、检查并安装更新、控制脱敏错误诊断 |
+| **设置** | 选择中文或英语;首次打开按系统语言匹配,未匹配时使用英语 |
**输入框插件**:在「增强」页分别开启「暂存提示词」和「快捷短语」后,输入框操作栏会显示对应按钮。
暂存提示词可把当前草稿(文字、图片、文件、引用等**完整原样**)加入 WorkBuddy 自带的待发送队列,并暂停自动发送;
入队后输入框自动清空,内容按会话独立保存,可随时发送、编辑或删除。快捷短语可在增强页新增、编辑和批量管理,并从输入框操作栏一键发送,发送后不会自动删除。
+### 自动化
+
+把重复操作保存成任务,例如每日签到、查询账号积分、按条件显示提醒,或在指定会话发送消息并等待回复。
+
+1. 打开「自动化」页,通过「一键创建」选择示例,或使用「让 WorkBuddy 帮我创建」描述需求。WorkBuddy 会在新会话中生成任务,完成后自动加入列表;也可以用「新建任务」自行编辑步骤 JSON,「查看接口」提供当前支持的操作说明。
+2. 设置触发方式:手动运行,或在客户端加载、打开面板、页面就绪、账号切换等事件发生时执行;也支持按间隔、每日、每周、每月或指定时间调度。
+3. 在列表中启用、停用、编辑或复制任务。手动任务可立即运行,事件和定时任务按配置触发;执行过程中可停止,并通过「运行日志」查看结果和失败步骤。
+
+**任务导入导出**:点击「导入」选择 JSON 或 ZIP,预览后勾选需要的任务。导入后保持停用,不覆盖相同 ID 的已有任务;不兼容任务会提示原因。通过批量操作选择任务导出,单个保存为 JSON,多个保存为 ZIP,方便备份和分享。
+
+任务定义保存在本机,由 WorkDaddy 本地服务执行;定时和事件触发需要服务保持运行,涉及页面交互的步骤还需要对应 WorkBuddy 客户端可用。任务导出不包含账号备份或运行日志;当前支持本地文件导入导出,尚不支持在线任务市场和自动更新任务。
+
### 账号迁移到其他电脑
在账号页右上角使用「导出」和「导入」按钮即可迁移全部账号:
@@ -179,13 +190,12 @@ WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:
新版导出会使用你输入的密码、每次导出随机 salt 和 AES-256-GCM 加密;密码不会写入导出文件。文件中仍包含可恢复登录状态的 token,请像保护密码一样安全保存和传输,迁移完成后及时删除不再需要的副本。旧版 v1 导出仍可兼容导入。
-
## 安全与隐私
- **本地数据优先**:账号备份、主题和本地配置不会在后台上传;登录、积分等功能会访问 WorkBuddy 官方 API,自动更新会访问 GitHub Releases;显式执行模型连通测试时,会向你配置的第三方模型地址发送请求及对应 API Key。
- **发送错误诊断默认开启**:关于页的「发送错误诊断」开关同时控制 Sentry 远程错误诊断和本地脱敏渲染器日志,帮助定位版本和兼容性问题;处理内容经过脱敏、截断,远程上报不包含账号、会话内容、Token 或 API Key。随时可以在关于页关闭;`WORKDADDY_TELEMETRY=0`/`1` 可作为启动时的明确关闭/开启覆盖。
-完整威胁模型见 [`SECURITY.md`](SECURITY.md)(可选;未提供时本节即为完整说明)。
+独立的 `SECURITY.md` 可补充完整威胁模型;未提供时,本节即为安全与隐私说明。
---
diff --git a/README_en.md b/README_en.md
index 5fad5fd..6763959 100644
--- a/README_en.md
+++ b/README_en.md
@@ -2,111 +2,205 @@
**Language:** [简体中文](README.md) · [English](README_en.md)
-> **WorkDaddy is a local enhancement layer for the WorkBuddy desktop app:** manage independent account backups and switch accounts in one click; keep unattended AI tasks running with quiet mode; move sessions between accounts and resume interrupted tasks; stash prompts and quick phrases; use frosted-glass themes and other utilities. Accounts and configuration stay on your computer.
+> **WorkDaddy enhances the WorkBuddy desktop app: keep separate account backups and switch with a click; run unattended AI tasks with quiet approval mode; migrate sessions between accounts and resume interrupted tasks; run automations on events or schedules; stash prompts, send quick phrases, and customize frosted-glass themes. Accounts and configuration stay on your computer.**
> Local loopback CDP injection · the official installation is never modified.
-WorkDaddy is a [WorkBuddy](https://www.workbuddy.cn/) and [WorkBuddy AI](https://www.workbuddy.ai/) desktop enhancement tool based on **Chrome DevTools Protocol (CDP)**. It injects a small control panel into the running renderer without patching, re-signing, or replacing the official app.
+A desktop enhancement tool for [WorkBuddy](https://www.workbuddy.cn/) and [WorkBuddy AI](https://www.workbuddy.ai/), built on **Chrome DevTools Protocol (CDP)**.
+It injects UI components into the running WorkBuddy renderer without patching or re-signing the official app.
![License](https://img.shields.io/badge/license-AGPL--3.0-blueviolet)
![Platform](https://img.shields.io/badge/platform-macOS%2011%2B%20%7C%20Windows%2010%2F11-lightgrey)
![Node](https://img.shields.io/badge/node-%E2%89%A518-green)
+---
+
+## Preview
+
+<img src="docs/images/accounts-light.jpg" width="440">
+<img src="docs/images/accounts-dark.jpg" width="440">
+
+![界面预览图](docs/images/pannel-enhance.png)
+![界面预览图](docs/images/pannel-robot.png)
+![界面预览图](docs/images/pannel-theme.png)
+
+---
+
## What it does
-- **Fast account switching:** each WorkBuddy account has its own backup and can be restored with one click.
-- **Add a new account without quitting:** complete OAuth in your browser and the new account is added automatically; a traditional soft logout flow is also available.
-- **Encrypted account import/export:** move backups between computers with a password-protected file.
-- **Daily credits:** opening the panel silently checks all accounts with an idempotent daily cache.
+- **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.
+- **Automation tasks:** describe what you need and let WorkBuddy create a task, or edit the steps yourself. Supports manual, event, and scheduled triggers, run logs, stopping tasks, and JSON / ZIP import/export.
- **Quiet approval mode:** automatically handle supported permission prompts while you are away.
-- **Stash prompts:** put drafts, images, files, and quotes into WorkBuddy's message queue for later sending.
-- **Themes:** switch the built-in frosted-glass theme, wallpapers, and custom backgrounds.
-- **Session migration:** copy sessions across accounts and continue working where you left off.
-- **Model tools:** manage, back up, edit, test, and switch models more easily.
-- **Sleep control:** keep the computer awake until selected tasks finish, then restore normal sleep.
-- **Auto-continue:** resume replies that stop because of transient network or provider failures.
-- **Quick phrases:** save common prompts and send them from the composer toolbar.
+- **Stash prompts:** send drafts to WorkBuddy's pending message queue while preserving images, files, and quotes for later use.
+- **Themes:** use the built-in frosted-glass theme, preset wallpapers, or your own backgrounds.
+- **Session migration:** copy sessions between accounts automatically or manually and continue working where you left off.
+- **Model tools:** manage and switch models more easily, including multiple configurations with the same model name.
+- **Sleep control:** keep the computer awake while AI tasks run, then allow normal sleep when they finish.
+- **Auto-continue:** automatically continue tasks interrupted by network fluctuations, timeouts, or similar failures.
+- **Quick phrases:** save common prompts in the panel and send them from the composer toolbar.
+
+---
## Installation
-For the mainland client download **WorkDaddy**. For the international client download **WorkDaddy AI**.
+- For the mainland [WorkBuddy](https://www.workbuddy.cn/) client, download **WorkDaddy**.
+- For the international [WorkBuddy AI](https://www.workbuddy.ai/) client, download **WorkDaddy AI**.
### macOS
1. Download the latest `WorkDaddy-x.y.z.dmg` or `WorkDaddy-AI-x.y.z.dmg` from [Releases](../../releases).
2. Open the DMG and drag the app into **Applications**.
-3. If macOS says it cannot verify the developer, open **System Settings → Privacy & Security**, choose **Open Anyway**, and confirm with your login password.
+3. If macOS says Apple cannot check the app for malicious software:
+ 1. Open **System Settings → Privacy & Security**.
+ 2. Find the blocked WorkDaddy app and choose **Open Anyway**.
+ 3. Confirm with your login password.
+ ![Installation guide](docs/images/install-guide.png)
4. Launch the app. It starts its local daemon and injects the panel into WorkBuddy.
+5. Once the robot button appears, you are ready to go.
+
+#### Enterprise / VPC clients
+
+On macOS, WorkDaddy scans apps whose names start with `WorkBuddy` and that contain `Contents/MacOS/Electron`, such as `WorkBuddy企业定制版.app`. It filters candidates by the WorkDaddy or WorkDaddy AI profile. If several clients match, a system picker lets you choose one and remembers your selection. No manual configuration file lookup is needed. For an app with a completely custom name, run this advanced configuration command from the source directory:
+
+```bash
+node scripts/workbuddy-target.js --configure --platform darwin \
+ --profile workbuddy-cn \
+ --binary "/Applications/Enterprise Client.app/Contents/MacOS/Electron" \
+ --data-dir "$HOME/Library/Application Support/WorkDaddy"
+```
### Windows
-1. Download `WorkDaddy-Setup-x.y.z.exe` or `WorkDaddy-AI-Setup-x.y.z.exe` from [Releases](../../releases).
+1. Download `WorkDaddy-Setup-x.y.z.exe` or `WorkDaddy-AI-Setup-x.y.z.exe` for your client from [Releases](../../releases).
2. Run the installer.
3. Launch **WorkDaddy** or **WorkDaddy AI** from the desktop shortcut.
-Enterprise/VPC users can select their official WorkBuddy executable in the installer. The selection is stored in the WorkDaddy data directory and can be changed by running the installer again.
+#### Enterprise / VPC clients
+
+Install the WorkDaddy or WorkDaddy AI edition that most closely matches your client's interface. The installer detects the corresponding official client and shows its path and version. Enterprise users can choose **Browse** to select their own `.exe`; no configuration files or environment variables need to be edited.
+
+The selection is saved in WorkDaddy's personal data directory and preserved during updates. Run the installer again to change it or return to the detected official client. WorkDaddy pins the selected client version, so use the installer to confirm the client again after it is upgraded or moved.
-### Run from source
+### Run from source (developers)
```bash
git clone https://github.com/babygoton/WorkDaddy.git
cd WorkDaddy
-bash scripts/install.sh
-bash scripts/relaunch-with-cdp.sh
+bash scripts/install.sh # Create the backup directory and start the daemon
+bash scripts/relaunch-with-cdp.sh # Launch WorkBuddy with CDP on port 9222
```
-Use the profile environment variable when starting a specific client:
+WorkBuddy and WorkBuddy AI share the same daemon code. Profiles bind it to the intended client rather than guessing from the first available CDP port:
```bash
WBSWITCH_PROFILE=workbuddy-cn bash scripts/relaunch-with-cdp.sh
WBSWITCH_PROFILE=workbuddy-ai bash scripts/relaunch-with-cdp.sh
```
-The daemon listens on loopback (`127.0.0.1`) and binds the profile to its WorkBuddy target. No account data is deleted during migration; legacy backup directories remain in place.
+Prompt stashing and themes are enabled for both WorkBuddy profiles. CodeBuddy profile support is on hold and is outside the current release scope.
+
+The release scripts produce four packages for the two WorkBuddy clients: `WorkDaddy-<version>.dmg`, `WorkDaddy-AI-<version>.dmg`, `WorkDaddy-Setup-<version>.exe`, and `WorkDaddy-AI-Setup-<version>.exe`. For macOS builds, set `WORKDADDY_BUILD_PROFILE=workbuddy-cn` or `workbuddy-ai` to build only one client. Windows ZIPs are temporary installer build inputs, not release downloads.
+
+`install.sh`:
+
+- Creates the backup directory at `~/Library/Application Support/WorkDaddy`.
+- Migrates legacy backups from `~/Library/Application Support/HelloBuddy/accounts` on first launch, preserving the old directory.
+- Backs up the currently signed-in WorkBuddy account.
+- Removes old launchd registrations and starts the daemon manually; it no longer starts automatically at login.
+- Starts the background daemon immediately.
+- Opens the management interface at `http://127.0.0.1:47832`.
+
+> The installer starts the daemon once. After that, launch the appropriate WorkDaddy app when you need it.
+
+---
## How it works
-```
+**CDP injection · the official installation is never modified**
+
+```text
┌─────────────┐ --remote-debugging-port=9222 ┌──────────────┐
-│ WorkBuddy │ <───────────────────────────> │ WorkDaddy │
-│ renderer │ Chrome DevTools │ daemon.js │
-└─────────────┘ Runtime.evaluate └──────────────┘
+│ WorkBuddy │ <───────────────────────────> │ WorkDaddy │
+│ (Electron) │ Chrome DevTools │ daemon.js │
+│ │ Protocol (CDP) │ │
+│ Renderer │ ←── Runtime.evaluate ──── │ HTTP :47832 │
+│ Bottom │ inject.js │ Local API │
+│ right │ │ │
+└─────────────┘ └──────────────┘
```
-1. The launcher starts WorkBuddy with a loopback CDP port; the official binary and signature remain untouched.
-2. The daemon connects through CDP, watches authentication events, and stores account backups locally.
-3. `scripts/inject.js` renders the WorkDaddy panel and adapts to the active WorkBuddy profile.
-4. Local HTTP endpoints handle account switching, themes, sessions, sleep control, updates, and diagnostics.
+1. **Unmodified WorkBuddy binaries:** the launcher adds `--remote-debugging-port=9222` when starting WorkBuddy. Its binary and signature remain intact.
+2. **CDP connection:** the daemon watches login and authentication network events, with a file watcher as a fallback. Login and token refresh events back up the current account to a stable local directory using `account.uid`.
+3. **Injected UI:** `Runtime.evaluate` runs `inject.js` in the renderer, adding the robot button and the Accounts, Theme, Sessions, Models, Enhance, Automation, Computer, About, and Settings pages.
+4. **Local HTTP API:** the daemon listens on `127.0.0.1:47832`. The panel uses it for account switching, themes, check-ins, permission prompts, sleep control, and other features.
+5. **Data boundaries:** account backups and configuration stay local. Login and credit features call WorkBuddy's official APIs; update checks call GitHub Releases. Explicit model connectivity tests send requests and the corresponding API key to the model service you configured. Redacted error diagnostics are enabled by default and can be turned off in **About**.
+
+> Why CDP instead of an official plugin system? It connects directly to the running app, detects authentication changes, and injects the panel and style patches. WorkBuddy updates generally remain compatible as long as its interface does not change substantially.
+
+---
-## Panel
+## Usage
-Open the robot button in the lower-right corner and choose a tab:
+### Panel
+
+Click the robot button in the lower-right corner of WorkBuddy and choose a tab:
| Tab | Purpose |
| --- | --- |
-| Accounts | Account status, switching, deletion, and encrypted import/export |
-| Theme | Theme, wallpaper, avatar, blur, and overlay controls |
-| Sessions | Filter, copy, migrate, or delete sessions |
-| Models | Manage backups, model settings, tests, and bulk actions |
-| Enhance | Quiet approvals, auto-continue, stashed prompts, and quick phrases |
-| Computer | Sleep and wake policy |
-| About | Version, updates, and redacted diagnostics |
-| Settings | Choose Chinese or English; the first launch follows the system language and falls back to English |
+| **Accounts** | View account counts, credits, check-ins, and login status; switch, delete, or add accounts; import/export encrypted backups |
+| **Theme** | Switch between the default and WorkDaddy themes, choose or upload wallpapers, change avatars, and adjust blur and background overlays |
+| **Sessions** | Filter by account and date, copy or delete in bulk, and configure automatic session or workspace copying when switching accounts |
+| **Models** | Manage current and alternative models, including backups, copying, editing, enabling, connectivity tests, and bulk deletion |
+| **Enhance** | Configure quiet approvals, auto-continue, prompt stashing, and quick phrases |
+| **Automation** | Create and manage tasks, configure event or scheduled triggers, inspect run logs, stop running tasks, and import/export JSON or ZIP files |
+| **Computer** | Allow or prevent sleep, or restore normal sleep after all AI tasks finish |
+| **About** | View version and project information, check for and install updates, and control redacted error diagnostics |
+| **Settings** | Choose Chinese or English; the first launch follows the system language and falls back to English |
+
+**Composer tools:** enable **Stash prompts** and **Quick phrases** separately in **Enhance** to show their composer toolbar buttons. Stashing adds the current draft to WorkBuddy's own message queue with text, images, files, and quotes **preserved**, and pauses automatic sending. The composer is then cleared. Queued content is kept per conversation and can be sent, edited, or deleted. Quick phrases can be created, edited, and managed in bulk in Enhance, then sent from the composer toolbar; sending does not delete them.
+
+### Automation
+
+Save repetitive actions as tasks: daily check-ins, account credit queries, conditional reminders, or sending a message in a specific conversation and waiting for a reply.
-The language can be changed at any time from **Settings**. The choice is stored locally and applies immediately to the panel and its toasts.
+1. Open **Automation** and use **Quick create** to choose an example, or **Create with WorkBuddy** to describe what you need. WorkBuddy generates the task in a new conversation and adds it to the list when finished. You can also use **New task** to edit the step JSON yourself; **View capabilities** lists the currently supported operations.
+2. Choose a trigger: run manually, or respond to events such as client loading, panel opening, page readiness, and account switching. Schedules support intervals, daily, weekly, monthly, and a specific date and time.
+3. Enable, disable, edit, or copy tasks from the list. Manual tasks can run immediately; event and scheduled tasks run according to their configuration. Stop a running task when needed and inspect **Run logs** for results and failed steps.
+
+**Import and export:** choose **Import**, select a JSON or ZIP file, preview it, and select the tasks to import. Imported tasks remain disabled, existing tasks with the same ID are not overwritten, and incompatible tasks show the reason. Use bulk actions to select tasks for export: one task produces a JSON file, while multiple tasks produce a ZIP for backup or sharing.
+
+Task definitions are stored locally and executed by the WorkDaddy daemon. Scheduled and event triggers require the daemon to remain running; steps that interact with a page also require the corresponding WorkBuddy client to be available. Task exports exclude account backups and run logs. Local file import/export is supported; an online task marketplace and automatic task updates are not yet available.
+
+### Move accounts to another computer
+
+Use **Export** and **Import** at the top-right of the Accounts page:
+
+1. On the old computer, open WorkDaddy, choose **Export**, and save the generated `WorkDaddy-账号导出-YYYY-MM-DD.json` file.
+2. Transfer it securely to the new computer and install and launch WorkDaddy there.
+3. Choose **Import** on the Accounts page and select the file. The restored accounts will be available in the account list.
+
+Current exports use your password, a fresh random salt, and AES-256-GCM encryption. The password is not stored in the export. The encrypted file still contains tokens that can restore login sessions, so protect it like a password and remove unneeded copies after migration. Legacy v1 exports can still be imported.
## Security and privacy
-- Account backups, themes, and local configuration stay on the computer. Login, credit, update, and explicit model connectivity features call their respective official or configured services.
-- Error diagnostics are enabled by default and can be disabled in **About**. Reports are redacted and truncated and do not include accounts, session contents, tokens, or API keys.
-- The daemon binds to loopback only. WorkDaddy does not modify `app.asar`, terminate unrelated processes, or elevate lifecycle operations.
+- **Local data first:** account backups, themes, and local configuration are not uploaded in the background. Login and credit features access WorkBuddy's official APIs, and updates access GitHub Releases. Explicit model connectivity tests send requests and the corresponding API key to the third-party model service you configured.
+- **Error diagnostics are enabled by default:** the **Send error diagnostics** switch in About controls both remote Sentry error reporting and local redacted renderer logs to help diagnose version and compatibility issues. Reports are redacted and truncated; remote reports exclude accounts, session contents, tokens, and API keys. Turn diagnostics off at any time in About, or use `WORKDADDY_TELEMETRY=0` / `1` as an explicit startup override.
-See [`AGENTS.md`](AGENTS.md) for the engineering and release safety rules.
+A separate `SECURITY.md` may provide an expanded threat model; when it is not included, this section serves as the privacy and security overview.
+
+---
## License and disclaimer
This project is licensed under the **[GNU Affero General Public License v3.0](LICENSE)** (`SPDX-License-Identifier: AGPL-3.0-or-later`).
-WorkDaddy is an independent local enhancement tool and is not affiliated with or endorsed by WorkBuddy. WorkBuddy trademarks and official assets belong to their respective owners. Check rights before using third-party wallpapers or other materials commercially.
+- WorkDaddy provides local UI and usability enhancements for the WorkBuddy desktop app and **is not affiliated with WorkBuddy**.
+- WorkBuddy, its trademarks, and official assets belong to their respective owners. This project is not officially authorized or endorsed by WorkBuddy.
+- Third-party themes, wallpapers, and background images are provided for demonstration; check their rights before commercial use.
+
+---
## Community
diff --git a/docs/auto-continue-implementation.md b/docs/auto-continue-implementation.md
deleted file mode 100644
index 87a3dfe..0000000
--- a/docs/auto-continue-implementation.md
+++ /dev/null
@@ -1,284 +0,0 @@
-# 持续会话:会话异常中转(Auto-Continue)实施说明
-
-本文档是交给 WorkBuddy agent 的执行说明。目标是基于当前 WorkDaddy 项目实现功能,不新增独立插件协议,不修改 WorkBuddy 官方安装、签名或 app.asar。
-
-## 1. 目标
-
-在 WorkDaddy 面板的“增强”页增加“持续会话”卡片和“会话异常中转”开关。
-
-开启后:
-
-1. 将 WorkDaddy 专属英文指令块追加到 WorkBuddy 的全局自定义指令中。
-2. 只监控开关开启后、当前激活会话中新出现的助手回复。
-3. 回复及其异步 widget 连续静默 3 秒后,检查助手正文块末尾的完成标记。
-4. 正文没有完成标记时,自动通过当前会话输入框发送 “继续未完成的任务”。
-5. 同一条助手回复最多判定和触发一次,不设置总次数上限或冷却时间。
-
-## 2. 不可改变的边界
-
-- 仅支持 macOS。Windows 上 daemon 不注册此功能,inject UI 不展示此卡片。
-- 发送消息必须使用当前页面 DOM 的输入框和发送按钮模拟操作;禁止 WorkBuddy 私有 RPC。
-- 只处理当前激活会话。无法确认当前会话或无法确认输入框属于当前会话时,禁止自动发送。
-- 任何会话切换、页面导航、页面刷新、reinject 都必须清理旧 observer、timer 和临时状态。
-- 旧会话的异步回调不得修改新会话状态,也不得向新会话发送消息。
-- 不覆盖用户已有自定义指令,不删除用户已有配置,不记录或输出 token、cookie、备份内容。
-- 修改 scripts/daemon.js 后递增 DAEMON_VERSION 和 DAEMON_BUILD_ID。
-
-## 3. 配置文件
-
-### 3.1 WorkBuddy 自定义指令
-
-实际文件为当前 profile 的:
-
-```text
-<PROFILE.dataRoot>/app/app-config.json
-```
-
-例如国内版为 `~/.workbuddy/app/app-config.json`。不要复用现有 settings.json 中用于 WorkDaddy 状态的读写函数。
-
-文件不存在时创建父目录和文件,文件权限为 `0644`。写入采用临时文件加原子 rename,并在写入后立即重新读取校验。
-
-字段路径:
-
-```text
-personalization.customPrompt
-```
-
-### 3.2 指令块
-
-BlockId 为 `auto-continue`,版本为 `v1`。必须原样追加以下英文内容:
-
-```text
-[WorkDaddy-AutoContinue v1 - activate]
-Always append one invisible zero-width marker (U+200B U+200B U+2060) at the very end of the main text body of every reply, and only after the task has fully completed. Do NOT append the marker when the task failed or is unfinished. Write the actual invisible characters, never a visible placeholder such as text or escaped notation. Add nothing after the marker. Keep this active for all remaining replies in this conversation.
-[end WorkDaddy-AutoContinue]
-```
-
-追加规则:
-
-- 原有 customPrompt 保持原样,只在其后追加一个空行和本块。
-- 已存在完整本块时不得重复追加。
-- 关闭时只删除本 BlockId 的完整块,用户文本和其他 WorkDaddy 块保持不变。
-- 删除时清理由本块留下的多余空行,但不能 trim 或重排用户正文。
-- 如果存在多个本 BlockId 块,关闭时全部删除;开启时最终只保留一个最新 v1 块。
-- daemon 启动时若状态为开启但块缺失,自动补写;补写失败只记录脱敏错误并让 UI 显示弱提示。
-
-### 3.3 WorkDaddy 开关状态
-
-写入当前 profile 的:
-
-```text
-<PROFILE.dataRoot>/settings.json
-```
-
-建议键:`wbs.autoContinue.enabled`。使用现有读改写和原子替换惯例,保留 settings 中其他字段。
-
-## 4. daemon 接口
-
-沿用 scripts/inject.js 的 `api()`、`X-WorkDaddy-Token` 和现有本地 HTTP 鉴权。
-
-### GET /api/auto-continue
-
-返回:
-
-```json
-{ "ok": true, "enabled": false, "promptBlockPresent": true, "platformSupported": true }
-```
-
-### POST /api/auto-continue-set
-
-请求体:
-
-```json
-{ "enabled": true }
-```
-
-开启时先写入 app-config,再持久化开关状态;关闭时先停止前端监控,再删除指令块并持久化关闭状态。返回最新状态。
-
-现场确认 WorkBuddy 是否热加载 app-config.json:
-
-- 热加载:不刷新页面。
-- 不热加载:调用现有 reloadWorkBuddyPage(),返回 `reloaded: true`。
-- reload 后由现有 Page.loadEventFired 流程重新 inject;开关状态从 settings 恢复,已有消息建立 baseline,不得被重新判定。
-
-非 macOS 时接口返回 `platformSupported: false`,不写配置、不启动监控。
-
-## 5. 前端 UI
-
-在现有 `buildEnhancePane()` 中添加同级 `wbs-pcard`,放在“免打扰”卡片之后,复用现有开关和卡片 CSS。
-
-显示内容:
-
-- 卡片标题:`持续会话`
-- 开关名称:`会话异常中转`
-- 小标题:`检测到回复异常未输出完成标记时,自动发送「继续未完成的任务」`
-
-开启/关闭失败使用现有 toast 或卡片内弱提示,不弹模态框,不阻断 WorkBuddy。
-
-reinject 时必须通过现有 build lifecycle 销毁旧状态,不能叠加卡片、listener、MutationObserver 或 timer。
-
-## 6. 会话识别和切换隔离
-
-### 6.1 会话上下文
-
-每次监控都维护一个不可变上下文对象:
-
-```js
-{
- generation: Number,
- sessionRoot: Element,
- sessionKey: String,
- observer: MutationObserver,
- settleTimer: number | null,
- activeMessage: Element | null,
- judgedMessages: WeakSet
-}
-```
-
-`generation` 每次启动监控、会话切换、页面刷新、reinject 都递增。所有 timer、observer 回调和发送 Promise 开始及结束时都必须检查 generation;不匹配就直接放弃。
-
-### 6.2 当前激活会话
-
-由 agent 用 CDP 实测当前 WorkBuddy DOM,优先使用稳定的语义结构或属性,不把 CSS module hash 作为唯一选择器。候选范围是当前可见的 `.main-content.main-content--chat` / `.chat-container`,并通过 URL、选中会话项或容器身份生成 `sessionKey`。
-
-如果页面发生会话切换:
-
-1. 断开旧 sessionRoot 的 observer。
-2. 清除旧 settleTimer。
-3. 递增 generation。
-4. 清空 activeMessage 和临时状态。
-5. 定位新的 sessionRoot 和 sessionKey。
-6. 将新会话当前已有助手消息加入 baseline。
-7. 只等待之后新出现或开始增长的助手消息。
-
-如果 sessionKey 无法确定,则以 sessionRoot 元素身份作为临时 key;若 sessionRoot 被替换,必须按切换处理。无法定位 sessionRoot 时停止监控,绝不全页面扫描发送。
-
-### 6.3 baseline
-
-监控启动或切换到新会话时,收集当前会话中已有的助手消息内容容器,放入 `baselineMessages`。baseline 中的消息即使之后发生 widget 延迟渲染,也不能触发 Auto-Continue,因为需求只处理开关开启后新出现的回复。
-
-## 7. 助手消息和正文识别
-
-由 agent 用 CDP 确认当前实际类名和结构。实现不得依赖单个 hash 类名,使用以下语义策略:
-
-1. 在当前 sessionRoot 内定位助手消息行或带助手标识的消息容器。
-2. 定位其中的 `_assistantMessageContent` 等效内容容器。
-3. 遍历内容容器的直接子元素。
-4. 排除 class 或祖先标识含 `_widget`、`widgetRenderer` 的块。
-5. 取最后一个非 widget 子块作为正文块。
-6. 若没有直接子块,使用最后一个含文本节点的降级节点。
-
-绝不能使用整条助手消息的 `textContent` 判断标记,因为 widget 会在正文后异步渲染。
-
-## 8. 监控状态机
-
-状态:`IDLE`、`WATCHING`、`SETTLING`、`TRIGGERING`、`JUDGED`。
-
-固定常量:
-
-```js
-const AUTO_CONTINUE_SETTLE_MS = 3000;
-const AUTO_CONTINUE_RETRY_DELAY_MS = 300;
-const AUTO_CONTINUE_MAX_SEND_ATTEMPTS = 2;
-```
-
-流程:
-
-1. `IDLE`:发现非 baseline 的新助手消息或其文本首次增长,记录为 `activeMessage`,进入 `WATCHING`。
-2. `WATCHING`:监听当前消息容器的正文和 widget 变化,每次 mutation 更新 `lastMutationAt`,进入 `SETTLING` 并重置 3 秒 timer。
-3. timer 到期:确认当前 generation、sessionRoot、activeMessage 都仍有效,并再次确认 3 秒内无 mutation。
-4. 正文块末尾有完成标记:加入 `judgedMessages`,回到 `IDLE`。
-5. 没有完成标记:先加入 `judgedMessages`,进入 `TRIGGERING`,发送固定文案;发送流程结束后回到 `IDLE`。
-6. 任何旧 generation 的回调都不得改变状态机或触发发送。
-
-同一条消息只允许一次 `JUDGED`。没有次数上限和冷却时间,但自动发送出来的新助手回复必须是新的 DOM 消息,不能复用旧消息的判定记录。
-
-## 9. 完成标记判断
-
-严格标记:`\u200B\u200B\u2060`。
-
-判断正文块:
-
-```js
-const text = bodyBlock.textContent.trimEnd();
-```
-
-优先判断严格三连标记。为兼容模型变体,严格标记不存在时允许正文以单个 `U+200B`、`U+FEFF`、`U+2060` 或 `U+200D` 结尾。可见的 `\\u200B`、`&#8203;` 等转义/占位文本不算标记。
-
-## 10. 自动发送
-
-发送前必须连续执行以下检查:
-
-- 当前 generation 仍有效。
-- 当前 sessionRoot 仍是可见激活会话。
-- activeMessage 仍属于当前 sessionRoot。
-- 当前输入框可见、可编辑且属于当前 sessionRoot。
-- 输入框为空。若检测到用户正在输入,最多等待 2 秒轮询输入框;仍非空则放弃本次发送并显示弱提示,绝不覆盖用户内容。
-- 当前没有停止生成按钮或其他明确的 WorkBuddy 忙碌状态。
-
-输入框写入:
-
-- `textarea/input):使用对应原型的 native value setter,派发冒泡 `input` 和 `change` 事件。
-- `contenteditable` / Slate:聚焦后选中编辑区内容,使用编辑器可接受的原生插入方式,派发 `InputEvent`;不得直接改 React 内部状态。
-
-发送:
-
-1. 等待约 100ms 让官方按钮状态同步。
-2. 重新定位并点击当前会话最右侧官方发送按钮。
-3. 按钮不存在或点击失败时,重新定位 composer 并派发普通 Enter 作为兜底。
-4. 失败后 300ms 重试一次,每次都重新做会话和 generation 校验。
-5. 两次失败后显示卡片内弱提示,不抛窗、不循环重试。
-
-## 11. 关闭、刷新和异常恢复
-
-关闭开关时立即:
-
-1. 停止监控。
-2. 断开 observer。
-3. 清理所有 timer。
-4. 递增 generation,使旧回调失效。
-5. 删除 app-config 中自己的指令块。
-6. 保留 `wbs.autoContinue.enabled: false`。
-
-页面刷新或 reinject 时:
-
-- 旧 observer 和 timer 必须被 lifecycle disposer 清理。
-- 新 build 重新读取开关状态。
-- 开关开启时校验指令块,不存在则通过 daemon 补写。
-- 当前已有助手消息重新建立 baseline,不得因页面恢复而触发继续。
-
-## 12. 测试要求
-
-新增 `test/auto-continue.test.js`,沿用 `test/no-disturb.test.js` 的同源复制逻辑模式,至少覆盖:
-
-- 指令块追加、删除、重复开启、多块清理。
-- 用户原有 customPrompt 保留。
-- 严格标记、兼容单字符标记、可见转义文本。
-- 正文块与 widget 块分离。
-- 3 秒静默后完成/异常两条路径。
-- 同一消息只触发一次。
-- 会话切换后旧 timer/observer 回调不发送。
-- 页面刷新/reinject 后 baseline 消息不发送。
-- 用户正在输入时不覆盖内容。
-- 第一次发送失败后最多重试一次。
-- Windows 不展示和不注册功能。
-
-验证命令:
-
-```bash
-node --check scripts/daemon.js
-node --check scripts/inject.js
-node --test test/*.test.js
-git diff --check
-```
-
-## 13. CDP 现场确认
-
-实现前必须由 agent 在运行中的 WorkBuddy 中确认:
-
-- A:app-config 写入后是否热加载;不热加载时调用 Page.reload。
-- B:当前助手消息、正文块、widget 块的实际稳定选择器。
-- C:当前 composer 类型、React/Slate 输入事件方式、发送按钮定位方式。
-- D:会话切换时可用的 URL、选中项或容器身份信号。
-
-现场确认只用于适配当前 WorkBuddy DOM,不得改变本文档的行为规则:只处理激活会话、3 秒静默、正文标记判定、单消息去重和旧 generation 隔离。
diff --git "a/docs/css-vars-\345\270\270\351\207\217\346\270\205\345\215\225.md" "b/docs/css-vars-\345\270\270\351\207\217\346\270\205\345\215\225.md"
deleted file mode 100644
index 0bd0d82..0000000
--- "a/docs/css-vars-\345\270\270\351\207\217\346\270\205\345\215\225.md"
+++ /dev/null
@@ -1,171 +0,0 @@
-# WorkDaddy CSS 变量常量全量清单
-
-> 来源:`scripts/daemon.js`(内置主题 `BUILTIN_THEMES`)、`scripts/inject.js`(检查器/皮肤生成/样式)、`scripts/theme-patches.js`(深色化补丁)。
-> 变量分三大命名空间:**`--vscode-*`**(body 层,整体布局)、**`--wb-*`**(:root 层,组件 token)、**`--dc-*`**(WorkDaddy 自定义面板 token);另有一批 **`--cb-*`**(WorkBuddy 官方 CodeBuddy 变量,被深色化补丁二次赋值)。
-
----
-
-## 一、主题检查器使用的 9 个核心常量(用户示例出处,inject.js:5174)
-
-| 中文名 | 变量 | 官方深色值 |
-|---|---|---|
-| 背景-主 | `--wb-bg-primary` | `#0a0a0a` |
-| 背景-面板 | `--wb-bg-secondary` | `#111113` |
-| 侧边栏背景 | `--wb-sidebar-bg` | `#0c0c0e` |
-| 文字-主 | `--wb-color-text-primary` | `#f2f2f4` |
-| 文字-次 | `--wb-color-text-secondary` | `rgba(242,242,244,0.72)` |
-| 边框 | `--wb-border-default` | `rgba(255,255,255,0.12)` |
-| 按钮背景 | `--wb-button-primary-bg` | `rgba(255,255,255,0.92)` |
-| vscode背景 | `--vscode-editor-background` | `#0a0a0a` |
-| vscode文字 | `--vscode-editor-foreground` | `#f2f2f4` |
-
-> 这 9 个是主题检查器悬停检测用的最小集。完整主题文件需要下方全套变量。
-
----
-
-## 二、内置主题完整 Schema(daemon.js:4119 `BUILTIN_THEMES`,三套共用)
-
-### 2.1 `--vscode-*` 层(50 个)
-
-```
---vscode-editor-background --vscode-editor-foreground
---vscode-sideBar-background --vscode-sideBar-foreground --vscode-sideBar-border
---vscode-activityBar-background --vscode-activityBar-foreground
---vscode-activityBar-inactiveForeground
---vscode-activityBarBadge-background --vscode-activityBarBadge-foreground
---vscode-titleBar-activeBackground --vscode-titleBar-activeForeground
---vscode-tab-activeBackground --vscode-tab-activeForeground
---vscode-tab-inactiveBackground --vscode-tab-inactiveForeground
---vscode-tab-border
---vscode-input-background --vscode-input-foreground
---vscode-input-border --vscode-input-placeholderForeground
---vscode-button-background --vscode-button-foreground
---vscode-button-hoverBackground
---vscode-list-activeSelectionBackground --vscode-list-activeSelectionForeground
---vscode-list-hoverBackground --vscode-list-inactiveSelectionBackground
---vscode-menu-background --vscode-menu-foreground
---vscode-dropdown-background --vscode-dropdown-foreground --vscode-dropdown-border
---vscode-panel-background --vscode-panel-border
---vscode-badge-background --vscode-badge-foreground
---vscode-foreground --vscode-descriptionForeground
---vscode-focusBorder
---vscode-scrollbarSlider-background --vscode-scrollbarSlider-hoverBackground
---vscode-editorGroupHeader-tabsBackground --vscode-editorGroupHeader-tabsBorder
---vscode-editorGroup-border
---vscode-statusBar-background --vscode-statusBar-foreground
---vscode-checkbox-background --vscode-checkbox-border --vscode-checkbox-foreground
---vscode-editorWidget-background --vscode-editorWidget-border
-```
-
-### 2.2 `--wb-*` 组件层(44 个)
-
-**背景**
-```
---wb-bg-primary --wb-bg-secondary --wb-bg-tertiary --wb-bg-popover
---wb-bg-hover --wb-bg-active --wb-bg-overlay --wb-card-bg
-```
-
-**文字**
-```
---wb-text-strong --wb-text-medium --wb-text-muted --wb-text-weak
---wb-color-text-primary --wb-color-text-secondary --wb-color-text-tertiary
---wb-color-text-disabled
-```
-
-**边框**
-```
---wb-border-default --wb-border-subtle --wb-border-strong --wb-border-hover
-```
-
-**按钮**
-```
---wb-button-primary-bg --wb-button-primary-fg --wb-button-primary-bg-hover
-```
-
-**状态**
-```
---wb-status-success --wb-status-warning --wb-status-error --wb-status-info
-```
-
-**知识库(kb)**
-```
---wb-kb-tabs-container-bg --wb-kb-tabs-container-border
---wb-kb-card-bg --wb-kb-card-bg-soft --wb-kb-card-border
-```
-
-### 2.3 `--dc-*` 层(14 个,WorkDaddy 面板专用)
-
-```
---dc-bg-primary --dc-bg-secondary --dc-bg-tertiary --dc-bg-hover
---dc-text-primary --dc-text-secondary --dc-text-tertiary
---dc-border --dc-border-light --dc-card-bg
---dc-primary --dc-primary-hover --dc-primary-active --dc-btn-text
-```
-
-### 2.4 三套内置主题值
-
-- **default(默认浅色)**:`colors: {}` 空对象,即完全用 WorkBuddy 官方变量,不覆盖。
-- **oled-dark(OLED 纯黑,deep)**、**eye-care(护眼绿)**、**cyber-purple(赛博紫)**:同一 schema 三套值,见 daemon.js:4121-4278。
-- 示例值(oled-dark 深色):`--wb-bg-primary:#0a0a0c`、`--wb-bg-secondary:#131316`、`--wb-color-text-primary:#e6e6e9`、`--wb-border-subtle:#202025`、`--wb-button-primary-bg:rgba(255,255,255,0.92)`、`--dc-bg-primary:#0a0a0c`……
-
-> 注:内置主题的深色值与官方实际运行值(第一节表)是两套近似色,主题应用时直接覆盖页面变量。
-
----
-
-## 三、运行期读取/适配的其他变量(代码引用,未在内置主题 schema 中)
-
-### 3.1 图片皮肤生成(inject.js:5776-5800,随图生成主题时写入)
-
-背景系:`--wb-bg-modal` `--wb-bg-card` `--wb-bg-content` `--wb-main-area-background`
-`--wb-home-bg-secondary` `--wb-home-composer-card-bg` `--wb-sidebar-bg` `--wb-home-bg-primary`
-`--cb-colleagues-dashboard-bg`
-
-文字系:`--wb-color-text-solid` `--wb-voice-input-text-primary`(加 `--wb-text-strong`/`--wb-color-text-primary`)
-
-vscode 系:`--vscode-panel-background` `--vscode-tab-activeBackground` `--vscode-sideBar-background`
-`--vscode-activityBar-background` `--vscode-editorGroupHeader-tabsBackground`
-
-固定值:`--wb-border-strong` `--wb-border-subtle` `--wb-button-primary-bg-hover` `--wb-status-*`
-
-### 3.2 主题探测 selectors 映射(daemon.js:4353-4357)
-
-```
-.teams-container.is-mac → --wb-home-bg-primary --wb-home-bg-secondary
-.project-detail-view__chat-input → --wb-bg-primary
-.project-detail-view__chat-input--task → --wb-bg-primary --wb-color-border-secondary
-[class*="mainArea"] → --wb-bg-hover
-.workbuddy-collab → --wb-border-info --wb-bg-info --wb-bg-action
-```
-
-### 3.3 theme-patches.js 深色化补丁引用的官方变量
-
-**wb 扩展 token**:`--wb-bg-modal` `--wb-bg-card` `--wb-bg-input` `--wb-bg-pill-active`
-`--wb-accent`(fallback `#f53f3f`)`--wb-accent-blue` `--wb-color-link` `--wb-color-border-secondary`
-`--wb-icon-secondary` `--wb-icon-tertiary` `--wb-color-bg-primary-hover-strong`
-`--wb-palette-brand-8`(官方青绿 rgb(0,194,154))`--wb-palette-gray-3`
-
-**cb 系官方变量(深色化时被覆盖赋值)**:
-```
---cb-bg-secondary: var(--wb-bg-tertiary) --cb-border: var(--wb-border-subtle)
---wb-palette-gray-3: var(--wb-bg-primary)
---cb-markdown-table-cell-bg: var(--wb-bg-primary)
---cb-markdown-table-header-bg: var(--wb-bg-secondary)
---cb-markdown-table-border-color: var(--wb-border-strong)
---cb-markdown-border-color: var(--wb-border-strong)
-```
-其余引用(未赋值,仅 var() 读取):`--cb-colleagues-dashboard-bg` `--cb-hover-bg` `--cb-panel-bg-primary`
-`--cb-text-primary` `--cb-text-secondary` `--cb-text-tertiary` `--cb-vscode-sideBar-background`
-`--cb-markdown-code-block-*` `--cb-markdown-table-color-bg`
-
----
-
-## 四、全部变量清单速查(按命名空间计数)
-
-| 命名空间 | 数量 | 说明 |
-|---|---|---|
-| `--vscode-*` | 50 | body 层整体布局(内置主题 Schema) |
-| `--wb-*` | 44 | :root 组件 token(内置主题 Schema) |
-| `--dc-*` | 14 | WorkDaddy 面板 token(内置主题 Schema) |
-| `--wb-*` 扩展引用 | 21 | 皮肤生成/补丁/探测器引用(非 Schema) |
-| `--cb-*` | 15 | WorkBuddy 官方变量,补丁覆盖或引用 |
-| `--wb-palette-*` | 2 | `--wb-palette-brand-8`、`--wb-palette-gray-3` |
\ No newline at end of file
diff --git a/docs/images/accounts-dark.jpg b/docs/images/accounts-dark.jpg
new file mode 100644
index 0000000..ccdf3ff
Binary files /dev/null and b/docs/images/accounts-dark.jpg differ
diff --git a/docs/images/accounts-light.jpg b/docs/images/accounts-light.jpg
new file mode 100644
index 0000000..b971d13
Binary files /dev/null and b/docs/images/accounts-light.jpg differ
diff --git a/docs/images/accounts.png b/docs/images/accounts.png
deleted file mode 100644
index 5c77611..0000000
Binary files a/docs/images/accounts.png and /dev/null differ
diff --git a/docs/images/demo.gif b/docs/images/demo.gif
deleted file mode 100644
index dd382b6..0000000
Binary files a/docs/images/demo.gif and /dev/null differ
diff --git a/docs/images/pannel-enhance.png b/docs/images/pannel-enhance.png
new file mode 100644
index 0000000..b03880f
Binary files /dev/null and b/docs/images/pannel-enhance.png differ
diff --git a/docs/images/pannel-robot.png b/docs/images/pannel-robot.png
new file mode 100644
index 0000000..80dca8a
Binary files /dev/null and b/docs/images/pannel-robot.png differ
diff --git a/docs/images/pannel-theme.png b/docs/images/pannel-theme.png
new file mode 100644
index 0000000..5ab111c
Binary files /dev/null and b/docs/images/pannel-theme.png differ
diff --git a/examples/automation-packages/account-summary.workdaddy.json b/examples/automation-packages/account-summary.workdaddy.json
new file mode 100644
index 0000000..af1c551
--- /dev/null
+++ b/examples/automation-packages/account-summary.workdaddy.json
@@ -0,0 +1,105 @@
+{
+ "kind": "workdaddy.automation-package",
+ "formatVersion": 1,
+ "id": "org.example.account-summary",
+ "version": "1.0.0",
+ "name": "账号积分与活跃天数",
+ "description": "页面加载或账号切换后显示当前账号概况。",
+ "author": "Example author",
+ "license": "MIT",
+ "tags": [
+ "accounts",
+ "notification"
+ ],
+ "requires": {
+ "minWorkDaddyVersion": "1.1.91",
+ "taskSchemaVersion": 1,
+ "capabilities": [
+ "event.pageReady",
+ "account.getCurrent",
+ "account.status",
+ "vars.set",
+ "logic.if",
+ "notify.toast"
+ ],
+ "profiles": [
+ "workbuddy-cn"
+ ],
+ "platforms": [
+ "darwin",
+ "win32"
+ ]
+ },
+ "inputs": {
+ "label": {
+ "type": "string",
+ "title": "提示标题",
+ "default": "账号概况"
+ }
+ },
+ "task": {
+ "schemaVersion": 1,
+ "name": "账号积分与活跃天数",
+ "trigger": {
+ "type": "pageReady",
+ "oncePerNavigation": true,
+ "restartOnNavigation": true
+ },
+ "steps": [
+ {
+ "op": "account.getCurrent"
+ },
+ {
+ "op": "account.status",
+ "fields": [
+ "credits",
+ "activity.streak"
+ ],
+ "saveAs": "status"
+ },
+ {
+ "op": "vars.set",
+ "key": "creditsLabel",
+ "value": "{{vars.status.credits.total}}"
+ },
+ {
+ "op": "logic.if",
+ "condition": {
+ "left": "{{vars.status.credits.unlimited}}",
+ "operator": "truthy"
+ },
+ "then": [
+ {
+ "op": "vars.set",
+ "key": "creditsLabel",
+ "value": "不限量"
+ }
+ ]
+ },
+ {
+ "op": "vars.set",
+ "key": "daysLabel",
+ "value": "{{vars.status.activity.streak.days}} 天"
+ },
+ {
+ "op": "logic.if",
+ "condition": {
+ "left": "{{vars.status.activity.streak.days}}",
+ "operator": "equals",
+ "right": null
+ },
+ "then": [
+ {
+ "op": "vars.set",
+ "key": "daysLabel",
+ "value": "暂不可用"
+ }
+ ]
+ },
+ {
+ "op": "notify.toast",
+ "message": "{{vars.label}} · {{account.nickname}}:剩余积分 {{vars.creditsLabel}},连续活跃 {{vars.daysLabel}}"
+ }
+ ]
+ }
+}
diff --git a/examples/automation-packages/workdaddy-automations.json b/examples/automation-packages/workdaddy-automations.json
new file mode 100644
index 0000000..9ebed0c
--- /dev/null
+++ b/examples/automation-packages/workdaddy-automations.json
@@ -0,0 +1,12 @@
+{
+ "kind": "workdaddy.automation-index",
+ "formatVersion": 1,
+ "items": [
+ {
+ "id": "org.example.account-summary",
+ "version": "1.0.0",
+ "path": "account-summary.workdaddy.json",
+ "sha256": "0d349921360b293d5bf612476b03852a93badb5488cf03620b07b66c412fc837"
+ }
+ ]
+}
diff --git a/release/macos/WorkDaddy-1.1.9.dmg b/release/macos/WorkDaddy-1.1.9.dmg
deleted file mode 100644
index 56d0a77..0000000
Binary files a/release/macos/WorkDaddy-1.1.9.dmg and /dev/null differ
diff --git a/release/macos/WorkDaddy-AI-1.1.9.dmg b/release/macos/WorkDaddy-AI-1.1.9.dmg
deleted file mode 100644
index cc29d25..0000000
Binary files a/release/macos/WorkDaddy-AI-1.1.9.dmg and /dev/null differ
diff --git a/release/windows/WorkDaddy-AI-Setup-1.1.9.exe b/release/windows/WorkDaddy-AI-Setup-1.1.9.exe
deleted file mode 100644
index 72dbfd9..0000000
Binary files a/release/windows/WorkDaddy-AI-Setup-1.1.9.exe and /dev/null differ
diff --git a/release/windows/WorkDaddy-Setup-1.1.9.exe b/release/windows/WorkDaddy-Setup-1.1.9.exe
deleted file mode 100644
index bd885a5..0000000
Binary files a/release/windows/WorkDaddy-Setup-1.1.9.exe and /dev/null differ
diff --git a/schemas/automation-package.v1.schema.json b/schemas/automation-package.v1.schema.json
new file mode 100644
index 0000000..dd64fcb
--- /dev/null
+++ b/schemas/automation-package.v1.schema.json
@@ -0,0 +1,196 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "urn:workdaddy:automation-package:v1",
+ "title": "WorkDaddy automation package v1",
+ "$comment": "The executable task is also checked by validateTask; input defaults/enums are checked against their declared type. The preview runtime is authoritative for compatibility.",
+ "type": "object",
+ "required": [
+ "kind",
+ "formatVersion",
+ "id",
+ "version",
+ "name",
+ "requires",
+ "task"
+ ],
+ "properties": {
+ "kind": {
+ "const": "workdaddy.automation-package"
+ },
+ "formatVersion": {
+ "const": 1
+ },
+ "id": {
+ "type": "string",
+ "maxLength": 160,
+ "pattern": "^[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)+$"
+ },
+ "version": {
+ "type": "string",
+ "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$"
+ },
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 120
+ },
+ "description": {
+ "type": "string",
+ "maxLength": 1000
+ },
+ "author": {
+ "type": "string",
+ "maxLength": 200
+ },
+ "license": {
+ "type": "string",
+ "maxLength": 100
+ },
+ "tags": {
+ "type": "array",
+ "maxItems": 20,
+ "items": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 200
+ }
+ },
+ "requires": {
+ "type": "object",
+ "required": [
+ "minWorkDaddyVersion",
+ "taskSchemaVersion",
+ "capabilities"
+ ],
+ "properties": {
+ "minWorkDaddyVersion": {
+ "type": "string",
+ "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$"
+ },
+ "taskSchemaVersion": {
+ "type": "integer",
+ "minimum": 1
+ },
+ "capabilities": {
+ "type": "array",
+ "maxItems": 100,
+ "items": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 200
+ }
+ },
+ "profiles": {
+ "type": "array",
+ "maxItems": 100,
+ "items": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 200
+ }
+ },
+ "platforms": {
+ "type": "array",
+ "maxItems": 100,
+ "items": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 200
+ }
+ }
+ },
+ "patternProperties": {
+ "^x-[a-z0-9][a-z0-9.-]*$": {}
+ },
+ "additionalProperties": false
+ },
+ "inputs": {
+ "type": "object",
+ "maxProperties": 40,
+ "propertyNames": {
+ "allOf": [
+ {
+ "pattern": "^[A-Za-z_][\\w-]{0,79}$"
+ },
+ {
+ "not": {
+ "enum": [
+ "__proto__",
+ "constructor",
+ "prototype"
+ ]
+ }
+ }
+ ]
+ },
+ "additionalProperties": {
+ "type": "object",
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "type": {
+ "enum": [
+ "string",
+ "number",
+ "integer",
+ "boolean"
+ ]
+ },
+ "title": {
+ "type": "string",
+ "maxLength": 500
+ },
+ "description": {
+ "type": "string",
+ "maxLength": 500
+ },
+ "required": {
+ "type": "boolean"
+ },
+ "default": {
+ "type": [
+ "string",
+ "number",
+ "boolean"
+ ]
+ },
+ "enum": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 100,
+ "items": {
+ "type": [
+ "string",
+ "number",
+ "boolean"
+ ]
+ }
+ }
+ },
+ "patternProperties": {
+ "^x-[a-z0-9][a-z0-9.-]*$": {}
+ },
+ "additionalProperties": false
+ }
+ },
+ "task": {
+ "type": "object",
+ "properties": {
+ "schemaVersion": {
+ "type": "integer",
+ "minimum": 1
+ }
+ },
+ "not": {
+ "required": [
+ "requires"
+ ]
+ }
+ }
+ },
+ "patternProperties": {
+ "^x-[a-z0-9][a-z0-9.-]*$": {}
+ },
+ "additionalProperties": false
+}
diff --git a/scripts/automation-compatibility.js b/scripts/automation-compatibility.js
new file mode 100644
index 0000000..2eb77cf
--- /dev/null
+++ b/scripts/automation-compatibility.js
@@ -0,0 +1,39 @@
+'use strict';
+function stableVersion(value) {
+ if (typeof value !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value)) throw new Error('Expected a stable version: major.minor.patch');
+ const parts=value.split('.').map(Number);
+ if(!parts.every(Number.isSafeInteger))throw new Error('Version exceeds supported range');
+ return parts;
+}
+function versionAtLeast(actual, minimum) {
+ const a=stableVersion(actual),b=stableVersion(minimum);
+ for(let i=0;i<3;i++)if(a[i]!==b[i])return a[i]>b[i];
+ return true;
+}
+function validateRequirements(requires) {
+ if(!requires||typeof requires!=='object'||Array.isArray(requires))throw new Error('requires must be an object');
+ const allowed=new Set(['minWorkDaddyVersion','taskSchemaVersion','capabilities','profiles','platforms']);
+ for(const key of Object.keys(requires))if(!allowed.has(key)&&!/^x-[a-z0-9][a-z0-9.-]*$/.test(key))throw new Error('Unsupported requirement: '+key);
+ stableVersion(requires.minWorkDaddyVersion);
+ if(!Number.isSafeInteger(requires.taskSchemaVersion)||requires.taskSchemaVersion<1)throw new Error('Invalid taskSchemaVersion');
+ for(const key of ['capabilities','profiles','platforms']){
+ const value=requires[key];
+ if(key!=='capabilities'&&value==null)continue;
+ if(!Array.isArray(value)||value.length>100||value.some(v=>typeof v!=='string'||!v.trim()||v.length>200))throw new Error('Invalid requirement: '+key);
+ }
+ return requires;
+}
+function assessRequirements(requires, runtime, actualCapabilities=[]) {
+ const issues=[];
+ if(requires){
+ validateRequirements(requires);
+ if(!runtime.version||!versionAtLeast(runtime.version,requires.minWorkDaddyVersion))issues.push({code:'workdaddy_version',required:requires.minWorkDaddyVersion});
+ if(requires.taskSchemaVersion!==1)issues.push({code:'unsupported_task_schema'});
+ if(requires.profiles&&!requires.profiles.includes(runtime.profileId))issues.push({code:'profile',allowed:requires.profiles});
+ if(requires.platforms&&!requires.platforms.includes(runtime.platform))issues.push({code:'platform',allowed:requires.platforms});
+ }
+ const available=new Set(runtime.capabilities||[]);
+ for(const capability of new Set([...(requires&&requires.capabilities||[]),...actualCapabilities]))if(!available.has(capability))issues.push({code:'capability',capability});
+ return issues;
+}
+module.exports={stableVersion,versionAtLeast,validateRequirements,assessRequirements};
diff --git a/scripts/automation-packages.js b/scripts/automation-packages.js
new file mode 100644
index 0000000..c88ccfb
--- /dev/null
+++ b/scripts/automation-packages.js
@@ -0,0 +1,118 @@
+'use strict';
+
+// Provider-neutral, pure preview. This module never downloads, installs or runs a task.
+const crypto = require('node:crypto');
+const { validateTask, CAPABILITIES } = require('./automation');
+const { stableVersion, versionAtLeast, validateRequirements, assessRequirements } = require('./automation-compatibility');
+const PACKAGE_KIND = 'workdaddy.automation-package';
+const PACKAGE_FORMAT_VERSION = 1;
+const MAX_BYTES = 1024 * 1024;
+const KNOWN_FIELDS = new Set(['kind','formatVersion','id','version','name','description','author','license','tags','requires','inputs','task']);
+const NAME = /^[A-Za-z_][\w-]{0,79}$/;
+const unsafeName = value => ['__proto__','constructor','prototype'].includes(value);
+function object(value, label) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(label + ' must be an object');
+ return value;
+}
+function fields(value, allowed, label) {
+ for (const key of Object.keys(value)) if (!allowed.has(key) && !/^x-[a-z0-9][a-z0-9.-]*$/.test(key)) throw new Error(label + ': unsupported field ' + key);
+}
+function strings(value, label, max=100) {
+ if (!Array.isArray(value) || value.length>max || value.some(v=>typeof v!=='string'||!v.trim()||v.length>200)) throw new Error(label + ' must be a bounded string array');
+ return [...new Set(value)];
+}
+function readDocument(input) {
+ const bytes = Buffer.isBuffer(input) ? input : Buffer.from(typeof input === 'string' ? input : JSON.stringify(input));
+ if (!bytes.length || bytes.length>MAX_BYTES) throw new Error('Package must contain at most 1 MiB of JSON');
+ return { document: object(JSON.parse(bytes.toString('utf8').replace(/^\uFEFF/,'')), 'Package'), sha256: crypto.createHash('sha256').update(bytes).digest('hex') };
+}
+function analyzeTask(task) {
+ const capabilities = new Set(), effects = new Set(), origins = new Set();
+ const walk = value => {
+ if (Array.isArray(value)) value.forEach(walk);
+ else if (value && typeof value === 'object') {
+ const op = value.op;
+ if (typeof op === 'string') {
+ capabilities.add(op);
+ if (op === 'account.forEach' && (value.switch === true || value.switchAccounts === true)) effects.add('account-switch');
+ if (op === 'account.checkin') effects.add('account-checkin');
+ if (/^session\.(create|send|sendCurrent)$/.test(op) || op === 'notify.afterAllTasks') effects.add('send-message');
+ if (/^dom\.(click|type|clear|press)$/.test(op)) effects.add('page-input');
+ if (/^state\.(set|checkpoint)$/.test(op)) effects.add('write-state');
+ if (/^http\./.test(op)) {
+ effects.add('network');
+ if (op === 'http.requestAsAccount') effects.add('account-credentials');
+ try { origins.add(new URL(value.url).origin); } catch (_) { origins.add('dynamic'); }
+ }
+ }
+ if (['logic.sequence','logic.repeat','logic.retry','logic.catch','logic.forEach','logic.waitUntil','account.forEach'].includes(op)) walk(value.steps);
+ if (op === 'logic.catch') walk(value.onError);
+ if (op === 'logic.if') { walk(value.then); walk(value.else); }
+ if (op === 'logic.switch') { Object.values(value.cases || {}).forEach(walk); walk(value.default); }
+ }
+ };
+ walk([task.steps,task.onSuccess,task.onFailure]);
+ const trigger = task.trigger || {};
+ const types = Array.isArray(trigger.types) ? trigger.types : [trigger.type || 'manual'];
+ types.filter(t=>t!=='manual').forEach(t=>capabilities.add('event.'+t));
+ if (task.schedule && task.schedule.type !== 'manual') capabilities.add('event.schedule');
+ return {capabilities:[...capabilities].sort(),effects:[...effects].sort(),origins:[...origins].sort()};
+}
+function bindInputs(definitions = {}, supplied = {}) {
+ object(definitions,'inputs'); object(supplied,'values');
+ if (Object.keys(definitions).length>40) throw new Error('Too many inputs');
+ for (const key of Object.keys(supplied)) if (!Object.hasOwn(definitions,key)) throw new Error('Unknown input: '+key);
+ const values = {}, missing = [];
+ for (const [key,definition] of Object.entries(definitions)) {
+ if (!NAME.test(key) || unsafeName(key)) throw new Error('Invalid input name');
+ const d=object(definition,'input '+key);
+ fields(d,new Set(['type','title','description','required','default','enum']),'input '+key);
+ for(const key of ['title','description'])if(d[key]!=null&&(typeof d[key]!=='string'||d[key].length>500))throw new Error('Invalid input label');
+ if (!['string','number','integer','boolean'].includes(d.type)) throw new Error('Unsupported input type');
+ if (d.required != null && typeof d.required !== 'boolean') throw new Error('required must be boolean');
+ if (d.enum != null && (!Array.isArray(d.enum)||!d.enum.length||d.enum.length>100)) throw new Error('Invalid input enum');
+ const matches=v=>(d.type==='integer'?Number.isSafeInteger(v):d.type==='number'?typeof v==='number'&&Number.isFinite(v):typeof v===d.type) && (typeof v!=='string'||v.length<=6000);
+ if (d.enum && !d.enum.every(matches)) throw new Error('Invalid input enum type');
+ if (Object.hasOwn(d,'default') && (!matches(d.default)||d.enum&&!d.enum.includes(d.default))) throw new Error('Invalid input default');
+ const hasValue = Object.hasOwn(supplied,key)||Object.hasOwn(d,'default');
+ if (!hasValue) { if(d.required===true)missing.push(key); continue; }
+ const value=Object.hasOwn(supplied,key)?supplied[key]:d.default;
+ if(!matches(value)||d.enum&&!d.enum.includes(value))throw new Error('Invalid input value: '+key);
+ values[key]=value;
+ }
+ return {values,missing};
+}
+function previewPackage(input, options = {}) {
+ const {document,sha256} = readDocument(input);
+ const runtime = options.runtime || {};
+ const issues=[];
+ const packaged = document.kind != null;
+ const metadata = packaged ? {id:document.id,version:document.version} : null;
+ const incompatible = code => ({kind:packaged?'package':'legacy-task',compatible:false,issues:[{code}],sha256,package:metadata,task:null,executed:false});
+ if(packaged && document.kind!==PACKAGE_KIND)return incompatible('unsupported_package_kind');
+ if(packaged && document.formatVersion!==PACKAGE_FORMAT_VERSION)return incompatible('unsupported_package_format');
+ let task, requires={}, inputs={};
+ if(packaged){
+ fields(document,KNOWN_FIELDS,'package');
+ if(typeof document.id!=='string'||document.id.length>160||!/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/.test(document.id))throw new Error('Package id must be namespaced, e.g. org.example.task');
+ stableVersion(document.version);
+ if(typeof document.name!=='string'||!document.name.trim()||document.name.length>120)throw new Error('Package name is required');
+ for (const [key,max] of [['description',1000],['author',200],['license',100]]) if (document[key]!=null && (typeof document[key]!=='string'||document[key].length>max)) throw new Error('Invalid package metadata: '+key);
+ if(document.tags)strings(document.tags,'tags',20);
+ requires=validateRequirements(document.requires);
+ task=object(document.task,'task');
+ if((task.schemaVersion??1)!==requires.taskSchemaVersion)throw new Error('Task schema does not match requires');
+ if (task.requires != null) throw new Error('Package requirements belong in the envelope only');
+ inputs=document.inputs||{};
+ }else { task=object(document.task||document,'task'); requires=task.requires || null; }
+ if((task.schemaVersion??1)!==1)return incompatible('unsupported_task_schema');
+ const analysis=analyzeTask(task);
+ issues.push(...assessRequirements(requires,{...runtime,capabilities:runtime.capabilities || CAPABILITIES.filter(c=>c.available!==false).map(c=>c.id)},analysis.capabilities));
+ const bound=bindInputs(inputs,options.values||{});
+ bound.missing.forEach(name=>issues.push({code:'input_required',name}));
+ let candidate=null;
+ try{candidate=validateTask({...task,id:task.id||'package_preview',variables:{...(task.variables||{}),...bound.values},...(requires?{requires}:{}),enabled:false});}
+ catch(error){issues.push({code:'invalid_task',message:error.message});}
+ return {kind:packaged?'package':'legacy-task',compatible:issues.length===0,issues,sha256,package:metadata,inputs,analysis,task:candidate,executed:false};
+}
+module.exports={PACKAGE_KIND,PACKAGE_FORMAT_VERSION,previewPackage,analyzeTask,bindInputs,versionAtLeast};
diff --git a/scripts/automation-picker.js b/scripts/automation-picker.js
new file mode 100644
index 0000000..d12a71f
--- /dev/null
+++ b/scripts/automation-picker.js
@@ -0,0 +1,357 @@
+// 自动化页面的简化元素拾取器。由 daemon 始终拼入 inject.js 的 build() 闭包,
+// 与五连击 logo 打开的私有 debug 拾取器保持独立入口和 DOM 命名空间。
+var automationInspectState = { active: false, hoverEl: null, hoverOutline: null, hoverOutlineOffset: null, x: 0, y: 0 };
+ function buildAutomationSelector(el) {
+ if (!el || el === document.body) return 'body';
+ if (el.id) return '#' + el.id;
+ var cls = (el.className || '').toString().trim().split(/\s+/).filter(Boolean).slice(0, 2);
+ var sel = el.tagName.toLowerCase();
+ if (cls.length) sel += '.' + cls.join('.');
+ return sel;
+ }
+ // 元素 query 路径:从 body 到元素的完整 CSS 选择器(带 :nth-child 保证唯一,可直接 document.querySelector)
+ function buildAutomationQueryPath(el) {
+ if (el && el.id) return el.tagName.toLowerCase() + '#' + el.id;
+ var parts = [];
+ var node = el;
+ while (node && node !== document.body && node !== document.documentElement) {
+ var seg = node.tagName.toLowerCase();
+ if (node.id) { parts.unshift(seg + '#' + node.id); break; }
+ var cls = (node.className || '').toString().trim().split(/\s+/).filter(Boolean).slice(0, 2);
+ if (cls.length) seg += '.' + cls.join('.');
+ else if (node.parentElement) {
+ var idx = Array.prototype.indexOf.call(node.parentElement.children, node) + 1;
+ seg += ':nth-child(' + idx + ')';
+ }
+ parts.unshift(seg);
+ node = node.parentElement;
+ }
+ if (node === document.body) parts.unshift('body');
+ return parts.join(' > ');
+ }
+ function buildAutomationXPath(el) {
+ if (!el || el.nodeType !== 1) return '';
+ var parts = [];
+ var node = el;
+ while (node && node.nodeType === 1) {
+ var name = node.tagName.toLowerCase();
+ var index = 1;
+ var sibling = node.previousElementSibling;
+ while (sibling) {
+ if (sibling.tagName === node.tagName) index += 1;
+ sibling = sibling.previousElementSibling;
+ }
+ parts.unshift(name + '[' + index + ']');
+ node = node.parentElement;
+ }
+ return '/' + parts.join('/');
+ }
+ function showAutomationInspector(stack, fallbackEl) {
+ try {
+ var old = document.getElementById('wbs-auto-inspector');
+ if (old && old.__wbsInspectAt) { old.__wbsInspectAt(stack, fallbackEl); return; }
+ if (old && old.__wbsClose) old.__wbsClose();
+ else if (old) old.remove();
+ function filterPicked(nodesAtPoint, fallback) {
+ var items = (nodesAtPoint || []).filter(function (node) {
+ return node && node.nodeType === 1 && !(node.closest && (node.closest('.wbs-root') || node.closest('#wbs-auto-inspector') || node.id === 'wbs-auto-inspect-tip'));
+ });
+ if (!items.length && fallback) items = [fallback];
+ return items;
+ }
+ var picked = filterPicked(stack, fallbackEl);
+ var selected = picked[0];
+ if (!selected) throw new Error('未找到可检查元素');
+
+ var mask = document.createElement('div');
+ mask.id = 'wbs-auto-inspector';
+ mask.className = 'wbs-modal-mask wbs-auto-inspector-mask';
+ mask.innerHTML =
+ '<div class="wbs-auto-inspector-highlight" aria-hidden="true"></div>' +
+ '<div class="wbs-modal wbs-auto-inspector-modal" role="dialog" aria-modal="false" aria-label="DOM 元素检查器">' +
+ '<div class="wbs-auto-inspector-head wbs-auto-inspector-drag-handle"><div><strong>DOM 元素检查器</strong><span class="wbs-auto-inspector-current"></span></div>' +
+ '<div class="wbs-auto-ins-btns"><button class="wbs-auto-ins-copy-element" type="button">复制元素</button><button class="wbs-auto-ins-close" type="button" title="关闭" aria-label="关闭元素检查器"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></div></div>' +
+ '<div class="wbs-auto-inspector-main"><section class="wbs-auto-inspector-tree-pane"><div class="wbs-auto-inspector-pane-title">HTML</div><div class="wbs-auto-inspector-tree" role="tree"></div></section></div>' +
+ '</div>';
+ document.body.appendChild(mask);
+ applyI18n(mask);
+
+ var modal = mask.querySelector('.wbs-auto-inspector-modal');
+ var dragHandle = mask.querySelector('.wbs-auto-inspector-drag-handle');
+ var tree = mask.querySelector('.wbs-auto-inspector-tree');
+ var current = mask.querySelector('.wbs-auto-inspector-current');
+ var highlighter = mask.querySelector('.wbs-auto-inspector-highlight');
+ var nodeIds = new WeakMap();
+ var nodes = {};
+ var nextNodeId = 1;
+ var expanded = new WeakSet();
+
+ function nodeId(node) {
+ if (!nodeIds.has(node)) nodeIds.set(node, String(nextNodeId++));
+ var id = nodeIds.get(node);
+ nodes[id] = node;
+ return id;
+ }
+ function nodeChildren(node) {
+ var out = Array.prototype.slice.call(node && node.children || []);
+ if (node && node.shadowRoot) out = out.concat(Array.prototype.slice.call(node.shadowRoot.children || []));
+ return out.filter(function (child) { return !(child.closest && child.closest('.wbs-root')) && child !== mask; });
+ }
+ function nodeLabel(node) {
+ var label = node.tagName.toLowerCase();
+ if (node.id) label += '#' + node.id;
+ var cls = (node.className || '').toString().trim().split(/\s+/).filter(Boolean).slice(0, 3);
+ if (cls.length) label += '.' + cls.join('.');
+ return label;
+ }
+ function reveal(node) {
+ var parent = node && node.parentElement;
+ while (parent) { expanded.add(parent); parent = parent.parentElement; }
+ }
+ function highlight(node) {
+ if (!node || !node.isConnected) { highlighter.style.display = 'none'; return; }
+ var rect = node.getBoundingClientRect();
+ highlighter.style.display = rect.width || rect.height ? 'block' : 'none';
+ highlighter.style.left = rect.left + 'px';
+ highlighter.style.top = rect.top + 'px';
+ highlighter.style.width = Math.max(0, rect.width) + 'px';
+ highlighter.style.height = Math.max(0, rect.height) + 'px';
+ }
+ function renderNode(node, depth) {
+ var children = nodeChildren(node);
+ var open = expanded.has(node);
+ var id = nodeId(node);
+ var html = '<div class="wbs-auto-inspector-node' + (node === selected ? ' selected' : '') + '" role="treeitem" data-node-id="' + id + '" style="--depth:' + depth + '">' +
+ '<button class="wbs-auto-inspector-twisty" type="button" tabindex="-1">' + (children.length ? (open ? '▾' : '▸') : '') + '</button>' +
+ '<span class="wbs-auto-inspector-tag">&lt;' + esc(nodeLabel(node)) + '&gt;</span>' +
+ '</div>';
+ if (open) children.forEach(function (child) { html += renderNode(child, depth + 1); });
+ return html;
+ }
+ function renderTree() {
+ tree.innerHTML = renderNode(document.documentElement, 0);
+ var active = tree.querySelector('.wbs-auto-inspector-node.selected');
+ if (active) active.scrollIntoView({ block: 'center' });
+ }
+ function copyElement() {
+ if (!selected || !selected.isConnected) return;
+ var text = (selected.innerText || selected.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 500);
+ var payload = [
+ 'CSS: ' + buildAutomationQueryPath(selected),
+ 'XPath: ' + buildAutomationXPath(selected),
+ 'Text: ' + text,
+ 'HTML:',
+ selected.outerHTML,
+ ].join('\n');
+ copyPlainText(payload).then(function () {
+ try { toast('已复制元素', false, root); } catch (_) {}
+ }).catch(function () {
+ try { toast('复制失败', true, root); } catch (_) {}
+ });
+ }
+ function selectNode(node) {
+ if (!node || node.nodeType !== 1) return;
+ selected = node;
+ reveal(node);
+ current.textContent = nodeLabel(selected);
+ renderTree(); highlight(node);
+ }
+ function inspectAt(nodesAtPoint, fallback) {
+ var nextPicked = filterPicked(nodesAtPoint, fallback);
+ if (!nextPicked.length) return;
+ picked = nextPicked;
+ selected = picked[0];
+ selectNode(selected);
+ }
+ function clampModalPosition(left, top) {
+ var rect = modal.getBoundingClientRect();
+ var maxLeft = Math.max(8, window.innerWidth - rect.width - 8);
+ var maxTop = Math.max(8, window.innerHeight - rect.height - 8);
+ return {
+ left: Math.max(8, Math.min(maxLeft, left)),
+ top: Math.max(8, Math.min(maxTop, top)),
+ };
+ }
+ function onDragStart(event) {
+ if (event.button !== 0 || event.target.closest('button')) return;
+ var rect = modal.getBoundingClientRect();
+ var offsetX = event.clientX - rect.left;
+ var offsetY = event.clientY - rect.top;
+ modal.style.position = 'fixed';
+ modal.style.margin = '0';
+ modal.style.transform = 'none';
+ modal.style.left = rect.left + 'px';
+ modal.style.top = rect.top + 'px';
+ dragHandle.classList.add('dragging');
+ try { dragHandle.setPointerCapture(event.pointerId); } catch (_) {}
+ function onDragMove(moveEvent) {
+ var position = clampModalPosition(moveEvent.clientX - offsetX, moveEvent.clientY - offsetY);
+ modal.style.left = position.left + 'px';
+ modal.style.top = position.top + 'px';
+ }
+ function onDragEnd(endEvent) {
+ dragHandle.classList.remove('dragging');
+ dragHandle.removeEventListener('pointermove', onDragMove);
+ dragHandle.removeEventListener('pointerup', onDragEnd);
+ dragHandle.removeEventListener('pointercancel', onDragEnd);
+ try { dragHandle.releasePointerCapture(endEvent.pointerId); } catch (_) {}
+ }
+ dragHandle.addEventListener('pointermove', onDragMove);
+ dragHandle.addEventListener('pointerup', onDragEnd);
+ dragHandle.addEventListener('pointercancel', onDragEnd);
+ event.preventDefault();
+ }
+ function onInspectorResize() {
+ if (!modal.style.left || !modal.style.top) return;
+ var position = clampModalPosition(parseFloat(modal.style.left), parseFloat(modal.style.top));
+ modal.style.left = position.left + 'px';
+ modal.style.top = position.top + 'px';
+ }
+ function closeInspector() {
+ stopAutomationInspect();
+ document.removeEventListener('keydown', onInspectorKey, true);
+ window.removeEventListener('resize', onInspectorResize);
+ dragHandle.removeEventListener('pointerdown', onDragStart);
+ mask.remove();
+ }
+ function onInspectorKey(event) {
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeInspector(); }
+ }
+ mask.__wbsClose = closeInspector;
+ mask.__wbsInspectAt = inspectAt;
+ modal.addEventListener('click', function (event) { event.stopPropagation(); });
+ mask.querySelector('.wbs-auto-ins-close').addEventListener('click', closeInspector);
+ mask.querySelector('.wbs-auto-ins-copy-element').addEventListener('click', copyElement);
+ dragHandle.addEventListener('pointerdown', onDragStart);
+ window.addEventListener('resize', onInspectorResize);
+ tree.addEventListener('click', function (event) {
+ var row = event.target.closest('.wbs-auto-inspector-node');
+ if (!row) return;
+ var node = nodes[row.dataset.nodeId];
+ if (event.target.closest('.wbs-auto-inspector-twisty')) {
+ if (expanded.has(node)) expanded.delete(node); else expanded.add(node);
+ renderTree(); return;
+ }
+ selectNode(node);
+ });
+ tree.addEventListener('mouseover', function (event) {
+ var row = event.target.closest('.wbs-auto-inspector-node');
+ if (row) highlight(nodes[row.dataset.nodeId]);
+ });
+ tree.addEventListener('mouseleave', function () { highlight(selected); });
+ document.addEventListener('keydown', onInspectorKey, true);
+ selectNode(selected);
+ mask.querySelector('.wbs-auto-ins-close').focus();
+ } catch (err) {
+ try { toast('检查失败:' + String(err && err.message || err).slice(0, 80), true, root); } catch (_) {}
+ }
+ }
+ function stopAutomationInspect() {
+ automationInspectState.active = false;
+ document.removeEventListener('mousemove', onAutomationInspectMove, true);
+ document.removeEventListener('click', onAutomationInspectClick, true);
+ document.removeEventListener('keydown', onAutomationInspectKey, true);
+ if (automationInspectState.hoverEl) {
+ if (automationInspectState.hoverOutline && automationInspectState.hoverOutline.hadValue) automationInspectState.hoverEl.style.setProperty('outline', automationInspectState.hoverOutline.value, automationInspectState.hoverOutline.priority);
+ else automationInspectState.hoverEl.style.removeProperty('outline');
+ if (automationInspectState.hoverOutlineOffset && automationInspectState.hoverOutlineOffset.hadValue) automationInspectState.hoverEl.style.setProperty('outline-offset', automationInspectState.hoverOutlineOffset.value, automationInspectState.hoverOutlineOffset.priority);
+ else automationInspectState.hoverEl.style.removeProperty('outline-offset');
+ automationInspectState.hoverEl = null;
+ automationInspectState.hoverOutline = null;
+ automationInspectState.hoverOutlineOffset = null;
+ }
+ var tip = document.getElementById('wbs-auto-inspect-tip');
+ if (tip) tip.remove();
+ }
+ function onAutomationInspectMove(e) {
+ automationInspectState.x = e.clientX;
+ automationInspectState.y = e.clientY;
+ var eventPath = e.composedPath ? e.composedPath() : [];
+ var el = eventPath[0] && eventPath[0].nodeType === 1 ? eventPath[0] : e.target;
+ if (el.closest && (el.closest('.wbs-root') || el.closest('#wbs-auto-inspector'))) return;
+ if (automationInspectState.hoverEl && automationInspectState.hoverEl !== el) {
+ if (automationInspectState.hoverOutline && automationInspectState.hoverOutline.hadValue) automationInspectState.hoverEl.style.setProperty('outline', automationInspectState.hoverOutline.value, automationInspectState.hoverOutline.priority);
+ else automationInspectState.hoverEl.style.removeProperty('outline');
+ if (automationInspectState.hoverOutlineOffset && automationInspectState.hoverOutlineOffset.hadValue) automationInspectState.hoverEl.style.setProperty('outline-offset', automationInspectState.hoverOutlineOffset.value, automationInspectState.hoverOutlineOffset.priority);
+ else automationInspectState.hoverEl.style.removeProperty('outline-offset');
+ }
+ if (automationInspectState.hoverEl !== el) {
+ var outlineValue = el.style.getPropertyValue('outline');
+ var offsetValue = el.style.getPropertyValue('outline-offset');
+ automationInspectState.hoverOutline = { hadValue: outlineValue !== '', value: outlineValue, priority: el.style.getPropertyPriority('outline') };
+ automationInspectState.hoverOutlineOffset = { hadValue: offsetValue !== '', value: offsetValue, priority: el.style.getPropertyPriority('outline-offset') };
+ }
+ el.style.setProperty('outline', '2px solid #22d3ee', 'important');
+ el.style.setProperty('outline-offset', '-2px', 'important');
+ automationInspectState.hoverEl = el;
+ }
+ function onAutomationInspectClick(e) {
+ var eventPath = e.composedPath ? e.composedPath() : [];
+ var el = eventPath[0] && eventPath[0].nodeType === 1 ? eventPath[0] : e.target;
+ if (el.closest && (el.closest('.wbs-root') || el.closest('#wbs-auto-inspector'))) return;
+ e.preventDefault(); e.stopPropagation();
+ var stack = [];
+ function collectElementsAtPoint(surface) {
+ var hits = [];
+ try { hits = Array.prototype.slice.call(surface.elementsFromPoint(automationInspectState.x, automationInspectState.y) || []); } catch (_) {}
+ hits.forEach(function (node) {
+ if (stack.indexOf(node) < 0) stack.push(node);
+ if (node.shadowRoot && node.shadowRoot.elementsFromPoint) collectElementsAtPoint(node.shadowRoot);
+ });
+ }
+ collectElementsAtPoint(document);
+ var inspector = document.getElementById('wbs-auto-inspector');
+ if (inspector && inspector.__wbsInspectAt) inspector.__wbsInspectAt(stack, el);
+ else showAutomationInspector(stack, el);
+ }
+ function onAutomationInspectKey(e) {
+ if (e.key === 'Escape') stopAutomationInspect();
+ }
+ function startAutomationInspect() {
+ if (automationInspectState.active) return;
+ automationInspectState.active = true;
+ // 检查器与 WorkDaddy 面板保持可见;只忽略它们自身的 DOM。
+ document.addEventListener('mousemove', onAutomationInspectMove, true);
+ document.addEventListener('click', onAutomationInspectClick, true);
+ document.addEventListener('keydown', onAutomationInspectKey, true);
+ var tip = document.createElement('div');
+ tip.id = 'wbs-auto-inspect-tip';
+ tip.textContent = '拾取模式:移动鼠标高亮元素,点击选中(Esc 退出)';
+ document.body.appendChild(tip);
+ applyI18n(tip);
+ }
+ function toggleAutomationInspect() {
+ if (automationInspectState.active) { stopAutomationInspect(); return; }
+ startAutomationInspect();
+ }
+// 自动化页面的“拾取元素”按钮调用。
+window.__wbsStartAutomationPicker = function () {
+ ensureAutomationPickerCss();
+ toggleAutomationInspect();
+};
+window.__wbsStopAutomationPicker = function () {
+ try { stopAutomationInspect(); } catch (e) {}
+};
+
+
+
+// 每次调用重建样式,保证重注入或手动删除后仍使用当前版本。
+function ensureAutomationPickerCss() {
+ if (!document.body) return;
+ var old = document.getElementById('wbs-automation-picker-style');
+ if (old) old.remove();
+ var el = document.createElement('style');
+ el.id = 'wbs-automation-picker-style';
+ el.textContent = ".wbs-auto-inspector-mask{z-index:2147483647;padding:0;box-sizing:border-box;background:transparent!important;pointer-events:none}" +
+ ".wbs-modal.wbs-auto-inspector-modal{position:relative;z-index:2;box-sizing:border-box;width:50vw;height:50vh;min-width:0;min-height:0;max-width:calc(100vw - 16px);max-height:calc(100vh - 16px);padding:0;overflow:hidden;resize:both;pointer-events:auto;container-name:inspector;container-type:inline-size;display:grid;grid-template-rows:auto minmax(0,1fr);border:1px solid var(--wb-border-default,rgba(128,128,128,.25));background:var(--wb-bg-primary,#fff);font-size:12px}" +
+ ".wbs-auto-inspector-head{height:48px;display:flex;align-items:center;justify-content:space-between;padding:0 14px;border-bottom:1px solid var(--wb-border-default,rgba(128,128,128,.22));background:var(--wb-bg-secondary,#f7f7f8);cursor:grab;user-select:none;touch-action:none}.wbs-auto-inspector-head.dragging{cursor:grabbing}.wbs-auto-inspector-head button{cursor:pointer}" +
+ ".wbs-auto-inspector-head>div:first-child{display:flex;align-items:center;min-width:0;gap:10px}.wbs-auto-inspector-head strong{font-size:13px}.wbs-auto-inspector-current{font-family:ui-monospace,Menlo,monospace;color:var(--wb-color-text-secondary,#777);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" +
+ ".wbs-auto-ins-btns{display:flex;align-items:center;gap:6px;flex-shrink:0;margin-left:8px}.wbs-auto-ins-btns button{border:1px solid var(--wb-border-default,#ddd);background:var(--wb-bg-primary,#fff);border-radius:7px;padding:5px 9px;font-size:11px;cursor:pointer;color:var(--wb-color-text-secondary,#555);line-height:1}.wbs-auto-ins-btns button:hover{background:var(--wb-bg-hover,#eee);color:var(--wb-color-text-primary,#222)}.wbs-auto-ins-btns .wbs-auto-ins-copy-element{border-color:var(--wb-button-primary-bg,#1f1f1f);background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);font-weight:600}.wbs-auto-ins-btns .wbs-auto-ins-copy-element:hover{background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 86%,#fff);color:var(--wb-button-primary-fg,#fff)}.wbs-auto-ins-btns .wbs-auto-ins-close{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;border-color:transparent;background:transparent}.wbs-auto-ins-close svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round}" +
+ ".wbs-auto-inspector-main{display:grid;grid-template-columns:minmax(0,1fr);min-height:0}.wbs-auto-inspector-tree-pane{min-width:0;min-height:0;display:grid;grid-template-rows:32px minmax(0,1fr)}.wbs-auto-inspector-pane-title{display:flex;align-items:center;padding:0 12px;border-bottom:1px solid var(--wb-border-default,rgba(128,128,128,.18));font-size:11px;font-weight:600;color:var(--wb-color-text-secondary,#666);background:var(--wb-bg-secondary,#f7f7f8)}" +
+ ".wbs-auto-inspector-tree{overflow:auto;min-height:0;background:var(--wb-bg-primary,#fff)}.wbs-auto-inspector-node{height:25px;display:flex;align-items:center;padding-left:calc(8px + var(--depth)*14px);font-family:ui-monospace,Menlo,monospace;white-space:nowrap;cursor:default;color:var(--wb-color-text-primary,#222)}.wbs-auto-inspector-node:hover{background:var(--wb-bg-hover,#f0f0f2)}.wbs-auto-inspector-node.selected{background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 18%,transparent)}.wbs-auto-inspector-twisty{width:18px;height:22px;padding:0;border:0;background:transparent;color:var(--wb-color-text-secondary,#777);cursor:pointer}.wbs-auto-inspector-tag{color:#b45309}" +
+ "html.cb-dark .wbs-auto-inspector-tag,html[data-theme=\"dark\"] .wbs-auto-inspector-tag{color:#e5a85d}" +
+ ".wbs-auto-inspector-highlight{position:fixed;z-index:1;display:none;pointer-events:none;box-sizing:border-box;border:2px solid #22d3ee;background:rgba(34,211,238,.16);box-shadow:0 0 0 1px rgba(4,34,43,.55)}" +
+ "@container inspector (max-width:560px){.wbs-auto-inspector-head{padding:0 10px}.wbs-auto-inspector-head strong{font-size:12px}.wbs-auto-inspector-current{display:none}}" +
+ "#wbs-auto-inspect-tip{position:fixed;left:50%;top:12px;transform:translateX(-50%);background:rgba(34,211,238,.95);color:#04222b;padding:6px 16px;border-radius:20px;font-size:12px;z-index:2147483647;box-shadow:0 4px 12px rgba(0,0,0,.15);pointer-events:none;white-space:nowrap}";
+ (document.head || document.body).appendChild(el);
+}
diff --git a/scripts/automation-runtime.js b/scripts/automation-runtime.js
new file mode 100644
index 0000000..4e64aaf
--- /dev/null
+++ b/scripts/automation-runtime.js
@@ -0,0 +1,89 @@
+'use strict';
+
+// No credential is read until this policy has accepted the final request URL.
+function assertAccountRequestUrl(url, apiHost) {
+ const base = new URL(apiHost);
+ const allowed = new Set([base.origin]);
+ if (base.hostname === 'www.codebuddy.cn') {
+ allowed.add('https://www.workbuddy.cn');
+ allowed.add('https://workbuddy.cn');
+ allowed.add('https://codebuddy.cn');
+ }
+ if (url.protocol !== 'https:' || url.username || url.password || !allowed.has(url.origin)) {
+ throw new Error('账号请求仅允许当前客户端的官方 HTTPS 接口');
+ }
+}
+function createTaskState(taskId, read, write) {
+ const keyFor = (scope, uid, key) => {
+ if (!['task','account'].includes(scope) || !String(key || '').trim()) throw new Error('状态 scope 或 key 无效');
+ if (scope === 'account' && !uid) throw new Error('账号状态需要账号上下文');
+ return JSON.stringify(['v2', taskId, scope, scope === 'account' ? String(uid) : '', key]);
+ };
+ return {
+ get: async (scope,uid,key) => read()[keyFor(scope,uid,key)],
+ set: async (scope,uid,key,value) => {
+ // Each synchronous read/merge/write sees other runs' latest changes.
+ const state = read(); state[keyFor(scope,uid,key)] = value; write(state);
+ },
+ };
+}
+async function cancellableWait(ms, isCancelled = () => false) {
+ const end = Date.now() + ms;
+ do {
+ if (isCancelled()) throw new Error('任务已停止');
+ await new Promise(resolve => setTimeout(resolve, Math.min(100,Math.max(0,end-Date.now()))));
+ } while (Date.now() < end);
+ if (isCancelled()) throw new Error('任务已停止');
+}
+function createRendererGate() {
+ let busy = false;
+ const queue = [];
+ return async isCancelled => {
+ const ticket = {}; queue.push(ticket);
+ try {
+ while (busy || queue[0] !== ticket) await cancellableWait(50,isCancelled);
+ if (isCancelled()) throw new Error('任务已停止');
+ queue.shift(); busy = true;
+ let released = false;
+ return () => { if (!released) { released = true; busy = false; } };
+ } catch (error) { const index = queue.indexOf(ticket); if (index >= 0) queue.splice(index,1); throw error; }
+ };
+}
+
+// Executed read-only inside the renderer. Never returns composer or message text.
+function probeSessionReceipt() {
+ const compat = window.__wbsWorkBuddyCompat;
+ if (!compat) return null;
+ const selected = compat.getSelectedConversationId(document);
+ const controller = (compat.findConversationControllers(document) || []).find(c => String(c.conversationId) === String(selected));
+ if (!controller) return null;
+ try {
+ const state = controller.messageStore.getState();
+ const session = controller.getSessionViewState();
+ const messages = Array.isArray(state.messages) ? state.messages : [];
+ const users = messages.filter(m => (m.messageType || m.role) === 'user');
+ const user = users[users.length-1];
+ const last = [...messages].reverse().find(m => (m.messageType || m.role) === 'assistant' && !/^timeline:/.test(String(m.id || '')));
+ const error = typeof controller.getErrorViewState === 'function' ? controller.getErrorViewState() : {};
+ const extra = last && last.extra || {};
+ return {
+ conversationId:String(selected || ''),
+ userMessageId:String(user && (user.id || user.requestId) || ''),
+ requestId:String(state.streamingRequestId || user && user.requestId || ''),
+ assistantId:String(last && (last.id || last.requestId) || ''),
+ assistantRequestId:String(last && last.requestId || ''),
+ complete:!!(last && (Object.prototype.hasOwnProperty.call(extra,'isRequestTerminal') ? extra.isRequestTerminal === true : last.complete === true)),
+ cancelled:extra.isCancelled === true,
+ error:!!(error && (error.error || error.hasError)),
+ busy:!!(state.streamingRequestId || state.streamingMessageId || session && (session.isBusy || session.isRunActive || session.isTurnActive || session.isSending || session.isPending || session.isHydrating)),
+ };
+ } catch (_) { return null; }
+}
+function receiptComplete(receipt, snapshot) {
+ if (!snapshot || snapshot.conversationId !== receipt.conversationId) throw new Error('目标会话不再可见,已停止等待');
+ if (snapshot.userMessageId !== receipt.userMessageId) throw new Error('会话已有其他请求,已停止等待');
+ if (snapshot.error || snapshot.cancelled) throw new Error('会话回复失败或已取消');
+ if (receipt.requestId && snapshot.assistantRequestId && snapshot.assistantRequestId !== receipt.requestId) return false;
+ return !!snapshot.assistantId && snapshot.assistantId !== receipt.baselineAssistantId && snapshot.complete && !snapshot.busy;
+}
+module.exports = {assertAccountRequestUrl,createTaskState,cancellableWait,createRendererGate,probeSessionReceipt,receiptComplete};
diff --git a/scripts/automation-transfer.js b/scripts/automation-transfer.js
new file mode 100644
index 0000000..aa6bd23
--- /dev/null
+++ b/scripts/automation-transfer.js
@@ -0,0 +1,96 @@
+'use strict';
+
+const crypto = require('node:crypto');
+const { readAutomations, writeAutomations } = require('./automation');
+const { previewPackage } = require('./automation-packages');
+const { encodeZip, decodeZip, MAX_BYTES, MAX_ENTRY_BYTES } = require('./automation-zip');
+const MAX_TASKS = 200;
+function exportTasks(tasks, ids) {
+ if (!Array.isArray(ids) || !ids.length || ids.length > MAX_TASKS || ids.some(id => typeof id !== 'string')) throw new Error('请先勾选要导出的任务');
+ const selected = [...new Set(ids)].map(id => {
+ const task = tasks.find(t => t.id === id);
+ if (!task) throw new Error('所选任务不存在,请刷新后重试');
+ const { compatible, manualRunnable, ...definition } = task;
+ return definition;
+ });
+ const entries = selected.map((task, i) => {
+ const content = Buffer.from(JSON.stringify(task, null, 2) + '\n');
+ if (content.length > MAX_ENTRY_BYTES) throw new Error('单个任务不能超过 1 MiB');
+ return { name: String(i + 1).padStart(3, '0') + '-' + String(task.id).replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80) + '.json', content };
+ });
+ if (entries.length === 1) return { count: 1, filename: 'WorkDaddy-task-' + entries[0].name, encoding: 'utf8', content: entries[0].content.toString('utf8'), mimeType: 'application/json' };
+ return { count: entries.length, filename: 'WorkDaddy-tasks-' + new Date().toISOString().slice(0, 10) + '.zip', encoding: 'base64', content: encodeZip(entries).toString('base64'), mimeType: 'application/zip' };
+}
+function readFiles(payload) {
+ if (!payload || typeof payload.content !== 'string' || !payload.content.length) throw new Error('请选择 JSON 或 ZIP 任务文件');
+ const encoding = payload.encoding || 'utf8';
+ if (!['utf8', 'base64'].includes(encoding) || payload.content.length > Math.ceil(MAX_BYTES / 3) * 4) throw new Error('任务文件不能超过 8 MiB');
+ if (encoding === 'base64' && (payload.content.length % 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(payload.content))) throw new Error('任务文件编码无效');
+ const bytes = Buffer.from(payload.content, encoding);
+ if (bytes.length > MAX_BYTES) throw new Error('任务文件不能超过 8 MiB');
+ const files = bytes.length >= 2 && bytes.readUInt16LE(0) === 0x4b50 ? decodeZip(bytes) : [{ name: 'task.json', content: bytes }];
+ const documents = files.filter(f => !f.name.endsWith('/') && !f.name.startsWith('__MACOSX/') && !/(^|\/)\.DS_Store$/.test(f.name));
+ if (!documents.length || documents.length > MAX_TASKS) throw new Error('单次支持导入 1–200 个任务');
+ if (documents.some(f => !/\.json$/i.test(f.name) || f.content.length > MAX_ENTRY_BYTES)) throw new Error('ZIP 内只能包含任务 JSON,单个任务不能超过 1 MiB');
+ return documents;
+}
+function previewImport(payload, existingTasks, runtime) {
+ const seen = new Set(existingTasks.map(t => t.id));
+ const entries = readFiles(payload).map((file, index) => {
+ const key = String(index), sha256 = crypto.createHash('sha256').update(file.content).digest('hex');
+ let name = file.name;
+ try {
+ const doc = JSON.parse(file.content.toString('utf8').replace(/^\uFEFF/, ''));
+ const definition = doc && (doc.kind ? doc.task : doc.task || doc);
+ if (!definition || typeof definition !== 'object' || !Array.isArray(definition.steps)) throw new Error('文件不是自动化任务 JSON');
+ name = String(doc.name || definition.name || file.name).slice(0, 120);
+ const preview = previewPackage(file.content, { runtime });
+ if (!preview.compatible) return { key, name, compatible: false, existing: false, issues: preview.issues, task: null };
+ const task = preview.task;
+ if (preview.kind === 'package') {
+ // File content identity is local deduplication, never publisher verification.
+ task.id = 'import_' + sha256.slice(0, 32);
+ task['x-workdaddy-import'] = { kind: 'local-file', packageId: preview.package.id, packageVersion: preview.package.version, sha256 };
+ } else if (!definition.id) task.id = 'import_' + sha256.slice(0, 32);
+ const existing = seen.has(task.id); seen.add(task.id);
+ return { key, name, compatible: true, existing, issues: [], task };
+ } catch (_) {
+ return { key, name, compatible: false, existing: false, issues: [{ code: 'invalid_document' }], task: null };
+ }
+ });
+ return { entries, executed: false };
+}
+function importTasks(dataDir, payload, runtime) {
+ if (!Array.isArray(payload.selected) || !payload.selected.length || payload.selected.length > MAX_TASKS) throw new Error('请至少选择一项');
+ // Re-read, revalidate and write once, synchronously. Preview is not an authority
+ // to overwrite tasks added/edited while the import dialog was open.
+ const tasks = readAutomations(dataDir), preview = previewImport(payload, tasks, runtime);
+ const selected = [...new Set(payload.selected)].map(key => {
+ const entry = preview.entries.find(e => e.key === key);
+ if (!entry || !entry.compatible) throw new Error('所选任务不兼容或文件已损坏');
+ return entry;
+ });
+ const added = selected.filter(e => !e.existing).map(e => e.task);
+ if (added.length && tasks.length + added.length > MAX_TASKS) throw new Error('自动化任务数量已达到上限');
+ if (added.length) writeAutomations(dataDir, [...added, ...tasks]);
+ return { imported: added.length, skipped: selected.length - added.length, executed: false };
+}
+// These file endpoints use a bounded body reader instead of the legacy API reader.
+function readTransferBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = []; let size = 0, failed = false;
+ req.on('data', chunk => {
+ if (failed) return;
+ size += chunk.length;
+ if (size > 12 * 1024 * 1024) { failed = true; chunks.length = 0; reject(new Error('任务文件不能超过 8 MiB')); return; }
+ chunks.push(Buffer.from(chunk));
+ });
+ req.on('error', reject);
+ req.on('end', () => {
+ if (failed) return;
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }
+ catch (_) { reject(new Error('任务文件编码无效')); }
+ });
+ });
+}
+module.exports = { exportTasks, previewImport, importTasks, readTransferBody };
diff --git a/scripts/automation-zip.js b/scripts/automation-zip.js
new file mode 100644
index 0000000..725eeee
--- /dev/null
+++ b/scripts/automation-zip.js
@@ -0,0 +1,95 @@
+'use strict';
+
+// Small, bounded ZIP interchange for JSON tasks. No files are extracted to disk.
+// Writes standard UTF-8/store ZIPs; reads store/deflate with central-directory sizes
+// (including archives with data descriptors). ZIP64, encryption and split ZIPs fail closed.
+const { inflateRawSync } = require('node:zlib');
+const MAX_BYTES = 8 * 1024 * 1024;
+const MAX_ENTRY_BYTES = 1024 * 1024;
+const MAX_ENTRIES = 512; // Allows Finder metadata alongside at most 200 tasks.
+const fail = () => { throw new Error('ZIP 文件损坏、加密或格式不支持'); };
+const crcTable = Array.from({ length: 256 }, (_, n) => {
+ for (let bit = 0; bit < 8; bit++) n = n & 1 ? 0xedb88320 ^ (n >>> 1) : n >>> 1;
+ return n >>> 0;
+});
+function crc32(bytes) {
+ let crc = 0xffffffff;
+ for (const byte of bytes) crc = crcTable[(crc ^ byte) & 255] ^ (crc >>> 8);
+ return (crc ^ 0xffffffff) >>> 0;
+}
+function safeName(name) {
+ if (!name || /[\\\x00-\x1f:]/.test(name) || name.startsWith('/') || name.split('/').some(p => p === '..' || p === '.')) fail();
+ return name;
+}
+function checkExtra(bytes, start, size) {
+ const end = start + size;
+ if (end > bytes.length) fail();
+ while (start < end) {
+ if (start + 4 > end || bytes.readUInt16LE(start) === 1) fail(); // ZIP64
+ const length = bytes.readUInt16LE(start + 2);
+ start += 4 + length;
+ if (start > end) fail();
+ }
+}
+function encodeZip(entries) {
+ if (!entries.length || entries.length > MAX_ENTRIES) fail();
+ const files = [], directory = [], names = new Set();
+ let offset = 0, total = 0;
+ for (const entry of entries) {
+ const name = Buffer.from(safeName(entry.name)), content = Buffer.from(entry.content);
+ if (names.has(entry.name) || name.length > 1024 || content.length > MAX_ENTRY_BYTES || (total += content.length) > MAX_BYTES) fail();
+ names.add(entry.name);
+ const local = Buffer.alloc(30), central = Buffer.alloc(46), crc = crc32(content);
+ local.writeUInt32LE(0x04034b50); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x800, 6);
+ local.writeUInt16LE(33, 12); // 1980-01-01
+ local.writeUInt32LE(crc, 14); local.writeUInt32LE(content.length, 18); local.writeUInt32LE(content.length, 22); local.writeUInt16LE(name.length, 26);
+ central.writeUInt32LE(0x02014b50); central.writeUInt16LE(20, 4); local.copy(central, 6, 4, 30); central.writeUInt32LE(offset, 42);
+ files.push(local, name, content); directory.push(central, name); offset += local.length + name.length + content.length;
+ }
+ const index = Buffer.concat(directory), end = Buffer.alloc(22);
+ end.writeUInt32LE(0x06054b50); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10);
+ end.writeUInt32LE(index.length, 12); end.writeUInt32LE(offset, 16);
+ const result = Buffer.concat([...files, index, end]);
+ if (result.length > MAX_BYTES) throw new Error('任务文件不能超过 8 MiB');
+ return result;
+}
+function decodeZip(bytes) {
+ if (!Buffer.isBuffer(bytes) || bytes.length < 22 || bytes.length > MAX_BYTES) fail();
+ let end = -1;
+ for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 65557); i--) {
+ if (bytes.readUInt32LE(i) === 0x06054b50 && i + 22 + bytes.readUInt16LE(i + 20) === bytes.length) { end = i; break; }
+ }
+ if (end < 0 || bytes.readUInt16LE(end + 4) || bytes.readUInt16LE(end + 6)) fail();
+ const count = bytes.readUInt16LE(end + 10), directorySize = bytes.readUInt32LE(end + 12), directoryStart = bytes.readUInt32LE(end + 16);
+ if (!count || count > MAX_ENTRIES || bytes.readUInt16LE(end + 8) !== count || directoryStart + directorySize !== end) fail();
+ const entries = [], names = new Set(), ranges = [];
+ let cursor = directoryStart, total = 0;
+ for (let i = 0; i < count; i++) {
+ if (cursor + 46 > end || bytes.readUInt32LE(cursor) !== 0x02014b50) fail();
+ const flags = bytes.readUInt16LE(cursor + 8), method = bytes.readUInt16LE(cursor + 10), crc = bytes.readUInt32LE(cursor + 16);
+ const compressedSize = bytes.readUInt32LE(cursor + 20), size = bytes.readUInt32LE(cursor + 24);
+ const nameSize = bytes.readUInt16LE(cursor + 28), extraSize = bytes.readUInt16LE(cursor + 30), commentSize = bytes.readUInt16LE(cursor + 32), local = bytes.readUInt32LE(cursor + 42);
+ const next = cursor + 46 + nameSize + extraSize + commentSize;
+ if (next > end || nameSize > 1024 || flags & ~0x80e || ![0, 8].includes(method) || bytes.readUInt16LE(cursor + 34) || size > MAX_ENTRY_BYTES || (total += size) > MAX_BYTES) fail();
+ checkExtra(bytes, cursor + 46 + nameSize, extraSize);
+ // Reject symlinks even though this parser never extracts paths.
+ if ((bytes.readUInt32LE(cursor + 38) >>> 16 & 0xf000) === 0xa000) fail();
+ const nameBytes = bytes.subarray(cursor + 46, cursor + 46 + nameSize), name = safeName(nameBytes.toString('utf8'));
+ if (names.has(name)) fail();
+ names.add(name);
+ if (local + 30 > directoryStart || bytes.readUInt32LE(local) !== 0x04034b50 || bytes.readUInt16LE(local + 6) !== flags || bytes.readUInt16LE(local + 8) !== method) fail();
+ const localNameSize = bytes.readUInt16LE(local + 26), dataStart = local + 30 + localNameSize + bytes.readUInt16LE(local + 28), dataEnd = dataStart + compressedSize;
+ if (dataEnd > directoryStart || !bytes.subarray(local + 30, local + 30 + localNameSize).equals(nameBytes) || ranges.some(([a, b]) => local < b && dataEnd > a)) fail();
+ checkExtra(bytes, local + 30 + localNameSize, bytes.readUInt16LE(local + 28));
+ ranges.push([local, dataEnd]);
+ if (!(flags & 8) && (bytes.readUInt32LE(local + 14) !== crc || bytes.readUInt32LE(local + 18) !== compressedSize || bytes.readUInt32LE(local + 22) !== size)) fail();
+ const compressed = bytes.subarray(dataStart, dataEnd);
+ let content;
+ try { content = method === 0 ? compressed : inflateRawSync(compressed, { maxOutputLength: Math.max(1, size) }); } catch (_) { fail(); }
+ if (content.length !== size || crc32(content) !== crc) fail();
+ entries.push({ name, content }); cursor = next;
+ }
+ if (cursor !== end) fail();
+ return entries;
+}
+module.exports = { encodeZip, decodeZip, MAX_BYTES, MAX_ENTRY_BYTES };
diff --git a/scripts/automation.js b/scripts/automation.js
new file mode 100644
index 0000000..aa6bc27
--- /dev/null
+++ b/scripts/automation.js
@@ -0,0 +1,856 @@
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+const crypto = require('crypto');
+const { validateRequirements, assessRequirements } = require('./automation-compatibility');
+const { normalizeToastOptions } = require('./toast-options.js');
+
+const SCHEMA_VERSION = 1;
+const MAX_TASKS = 200;
+const MAX_STEPS = 200;
+const MAX_DEPTH = 12;
+const MAX_TEXT = 20000;
+const MAX_AGENT_FILE_BYTES = 1024 * 1024;
+
+const AGENT_EXAMPLES = [
+ {
+ id: 'page-loaded-notice',
+ titleZh: '账号积分与活跃天数', titleEn: 'Account credits and active streak',
+ descriptionZh: '每次切换账号或页面加载完成后,显示当前账号的剩余积分和连续活跃天数。',
+ descriptionEn: 'Show the current account credits and consecutive active days after account switching or page load.',
+ promptZh: '每次切换账号或 WorkBuddy 页面加载完成后,立即从窗口底部弹出 toast,展示当前账号的名称、剩余积分和连续活跃天数。同一次加载只提示一次,快速切换时不要显示上一个账号的过时结果。积分不限量时显示“不限量”,天数查询失败时显示“暂不可用”。把这个任务添加到 WorkDaddy 的自动化列表。',
+ promptEn: 'After each account switch or WorkBuddy page load, immediately show a toast at the window bottom with the current account name, remaining credits and consecutive active days. Show it once per load, and discard stale results when accounts change quickly. Display Unlimited for unlimited credits, and Unavailable if active days cannot be retrieved. Add this task to WorkDaddy Automation.',
+
+ },
+];
+
+const CAPABILITIES = [
+ { id: 'event.pageReady', zh: '页面就绪触发', en: 'Run when the page is ready', descriptionZh: 'WorkBuddy 首次打开、导航完成或账号切换后的页面刷新完成后运行任务。', descriptionEn: 'Run after WorkBuddy opens, finishes navigation, or completes the refresh after an account switch.', example: { trigger: { type: 'pageReady', oncePerNavigation: true }, steps: [{ op: 'logic.delay', ms: 3000 }, { op: 'dom.click', locator: { kind: 'xpath', value: "//button[contains(normalize-space(.), '关闭')]" } }] } },
+ { id: 'event.pageLoaded', zh: '页面加载完成触发', en: 'Run when page loads', descriptionZh: 'WorkBuddy 页面首次打开或导航完成后运行任务。可配合等待和 DOM 点击处理弹窗。', descriptionEn: 'Run after WorkBuddy first opens or finishes a navigation. Combine with waits and DOM clicks to handle dialogs.', example: { trigger: { type: 'pageLoaded', oncePerNavigation: true }, steps: [{ op: 'logic.delay', ms: 3000 }, { op: 'dom.click', locator: { kind: 'xpath', value: "//button[contains(normalize-space(.), '关闭')]" } }] } },
+ { id: 'event.accountSwitched', zh: '账号切换完成触发', en: 'Run after account switch', descriptionZh: '账号切换并完成页面刷新后运行任务。', descriptionEn: 'Run after an account switch and the resulting page refresh completes.', example: { trigger: { type: 'accountSwitched' }, steps: [] } },
+ { id: 'event.clientLoaded', zh: '客户端加载触发', en: 'Client loaded', descriptionZh: '客户端页面加载完成时触发,可与打开面板和定时组合。', descriptionEn: 'Run after the client page loads; combine with panel-open and interval triggers.', example: { trigger: { types: ['clientLoaded', 'panelOpened'] } } },
+ { id: 'event.panelOpened', zh: '打开面板触发', en: 'Panel opened', descriptionZh: '用户打开 WorkDaddy 面板时触发;自动化恢复面板不会触发。', descriptionEn: 'Run when the user opens the panel, excluding automatic panel restoration.', example: { trigger: { type: 'panelOpened' } } },
+ { id: 'event.schedule', zh: '定时触发', en: 'Schedule', descriptionZh: '支持间隔、每天、每周、每月和指定时间一次;使用电脑本地时区,错过不补跑,运行中跳过。', descriptionEn: 'Interval, daily, weekly, monthly or once in local computer time. Missed or overlapping runs are skipped.', example: { schedule: { type: 'interval', minutes: 60 } } },
+ { id: 'logic.sequence', zh: '顺序执行', en: 'Run a sequence', descriptionZh: '按顺序执行嵌套步骤。', descriptionEn: 'Run nested steps in order.', example: { op: 'logic.sequence', steps: [] } },
+ { id: 'logic.delay', zh: '等待指定时间', en: 'Wait for a duration', descriptionZh: '暂停任务若干秒或毫秒。', descriptionEn: 'Pause the task for seconds or milliseconds.', example: { op: 'logic.delay', ms: 3000 } },
+ { id: 'logic.if', zh: '条件判断', en: 'Conditional branch', descriptionZh: '根据两个值是否相等、包含或匹配来选择分支。', descriptionEn: 'Choose a branch using equality, containment, or regular expressions.', example: { op: 'logic.if', condition: { left: '{{response.status}}', operator: 'equals', right: 200 }, then: [], else: [] } },
+ { id: 'logic.switch', zh: '多分支判断', en: 'Switch branch', descriptionZh: '根据值选择 cases 中的分支,未匹配时运行 default。', descriptionEn: 'Select a branch from cases by value, or run default when unmatched.', example: { op: 'logic.switch', value: '{{response.status}}', cases: { 200: [] }, default: [] } },
+ { id: 'logic.repeat', zh: '重复执行', en: 'Repeat steps', descriptionZh: '按次数重复一组步骤。', descriptionEn: 'Repeat a group of steps a bounded number of times.', example: { op: 'logic.repeat', times: 3, steps: [] } },
+ { id: 'logic.retry', zh: '失败重试', en: 'Retry on failure', descriptionZh: '失败后按次数和间隔重试。', descriptionEn: 'Retry failed steps with a bounded delay.', example: { op: 'logic.retry', times: 3, delayMs: 1000, steps: [] } },
+ { id: 'logic.catch', zh: '捕获错误', en: 'Catch an error', descriptionZh: '执行 steps;失败时把错误写入 vars.error 并运行 onError。', descriptionEn: 'Run steps; on failure, write the error to vars.error and run onError.', example: { op: 'logic.catch', steps: [], onError: [] } },
+ { id: 'logic.assert', zh: '条件断言', en: 'Assert a condition', descriptionZh: '条件不成立时终止任务并给出错误信息。', descriptionEn: 'Stop the task with an error when a condition is false.', example: { op: 'logic.assert', condition: { left: '{{response.ok}}', operator: 'truthy' }, message: '请求失败' } },
+ { id: 'account.forEach', zh: '循环账号', en: 'Iterate accounts', descriptionZh: '对全部或指定账号依次执行步骤;switch:true 会真实切换登录账号,并在循环结束后恢复原账号。', descriptionEn: 'Run steps for all or selected accounts; switch:true physically switches the logged-in account and restores the original account when the loop ends.', example: { op: 'account.forEach', accounts: 'all', switch: true, steps: [] } },
+ { id: 'account.status', zh: '查询账号状态', en: 'Read account status', descriptionZh: '查询今日签到、今日活跃和积分等只读状态。', descriptionEn: 'Read check-in, activity, and credit status.', example: { op: 'account.status', fields: ['checkin.today', 'activity.today'] } },
+ { id: 'account.checkin', zh: '账号静默签到', en: 'Check in as account', descriptionZh: '使用循环账号的 token 签到,不切换客户端。当天已确认签到时跳过所有请求;返回 ok、skipped、code 等状态。', descriptionEn: 'Check in using the context account token without switching accounts. Confirmed daily records skip all requests. Returns ok, skipped and code.', example: { op: 'account.checkin', saveAs: 'checkin' } },
+ { id: 'http.request', zh: 'HTTP 请求', en: 'HTTP request', descriptionZh: '调用 HTTP/HTTPS 接口并保存响应。', descriptionEn: 'Call an HTTP/HTTPS endpoint and retain its response.', example: { op: 'http.request', method: 'GET', url: 'https://example.com/api', saveAs: 'response' } },
+ { id: 'http.requestAsAccount', zh: '使用账号请求', en: 'HTTP request as account', descriptionZh: '使用当前循环账号的登录态请求,任务中不会出现 Token。', descriptionEn: 'Call an endpoint with the current account session without exposing a token in the task.', example: { op: 'http.requestAsAccount', method: 'GET', url: 'https://example.com/api' } },
+ { id: 'dom.find', zh: '查找页面元素', en: 'Find DOM element', descriptionZh: '使用 CSS、XPath 或文字查找页面元素。', descriptionEn: 'Find an element using CSS, XPath, or text.', example: { op: 'dom.find', locator: { kind: 'xpath', value: "//button[contains(., '领取')]" }, saveAs: 'element' } },
+ { id: 'dom.click', zh: '点击页面元素', en: 'Click DOM element', descriptionZh: '查找并真实点击页面元素。', descriptionEn: 'Find and click an element using a trusted input event.', example: { op: 'dom.click', locator: { kind: 'xpath', value: "//button[contains(., '领取')]" } } },
+ { id: 'dom.type', zh: '输入文字', en: 'Type text', descriptionZh: '向页面输入框写入文字。', descriptionEn: 'Type text into a page input.', example: { op: 'dom.type', locator: { kind: 'css', value: 'input[name="q"]' }, text: 'hello' } },
+ { id: 'dom.clear', zh: '清空输入框', en: 'Clear an input', descriptionZh: '使用 Chromium 编辑命令清空普通或富文本输入框,并验证结果。', descriptionEn: 'Clear a plain or rich text editor using Chromium editing commands and verify the result.', example: { op: 'dom.clear', locator: { kind: 'css', value: 'input[name="q"]' } } },
+ { id: 'dom.press', zh: '按下按键', en: 'Press a key', descriptionZh: '聚焦元素后发送一个键盘按键。', descriptionEn: 'Focus an element and dispatch one keyboard key.', example: { op: 'dom.press', locator: { kind: 'css', value: 'input[name="q"]' }, key: 'Enter' } },
+ { id: 'dom.readText', zh: '读取页面文字', en: 'Read DOM text', descriptionZh: '读取页面元素的可见文字。', descriptionEn: 'Read visible text from an element.', example: { op: 'dom.readText', locator: { kind: 'css', value: '.result' }, saveAs: 'resultText' } },
+ { id: 'dom.readAttribute', zh: '读取元素属性', en: 'Read an attribute', descriptionZh: '读取页面元素的指定属性。', descriptionEn: 'Read a named attribute from a page element.', example: { op: 'dom.readAttribute', locator: { kind: 'css', value: 'a.result' }, attribute: 'href', saveAs: 'href' } },
+ { id: 'dom.wait', zh: '等待页面变化', en: 'Wait for DOM', descriptionZh: '等待固定时间或等待元素达到指定状态。', descriptionEn: 'Wait for a duration or an element state.', example: { op: 'dom.wait', seconds: 2 } },
+ { id: 'session.sendCurrent', zh: '发送当前会话消息', en: 'Send in current session', descriptionZh: '向当前 WorkBuddy 会话发送文字。', descriptionEn: 'Send text in the current WorkBuddy session.', example: { op: 'session.sendCurrent', message: '你好' } },
+ { id: 'session.waitReply', zh: '等待会话回复', en: 'Wait for session reply', descriptionZh: '等待当前会话产生新回复。', descriptionEn: 'Wait for a new reply in the current session.', example: { op: 'session.waitReply', timeoutMs: 120000 } },
+ { id: 'state.get', zh: '读取任务状态', en: 'Read task state', descriptionZh: '读取任务或账号范围内的持久化值。', descriptionEn: 'Read a persisted value scoped to a task or account.', example: { op: 'state.get', key: 'lastRun' } },
+ { id: 'state.set', zh: '保存任务状态', en: 'Write task state', descriptionZh: '保存任务或账号范围内的持久化值。', descriptionEn: 'Persist a value scoped to a task or account.', example: { op: 'state.set', key: 'lastRun', value: '{{now}}' } },
+ { id: 'notify.toast', zh: '显示提示', en: 'Show notification', descriptionZh: '使用 react-hot-toast 从窗口底部弹出提示。level 支持 info/success/warning/error/loading;duration 为 1000–60000 毫秒,默认 4200(loading 默认持续显示)。同一 id 更新原提示;saveAs 保存返回的 id。', descriptionEn: 'Show a react-hot-toast notification at the window bottom. Levels: info/success/warning/error/loading. duration: 1000–60000 ms, default 4200 (loading persists). Reuse id to update; saveAs stores the returned id.', example: { op: 'notify.toast', level: 'success', message: '任务完成', duration: 4200, id: 'progress' } },
+ { id: 'notify.dismiss', zh: '关闭通知', en: 'Dismiss notification', descriptionZh: '按 id 关闭本次运行创建的提示,不影响其他任务或界面通知。任务结束时自动清理未结束的 loading 提示。', descriptionEn: 'Dismiss a notification by id within this run. Unfinished loading notifications are cleared when the run ends.', example: { op: 'notify.dismiss', id: 'progress' } },
+ { id: 'notify.afterAllTasks', zh: '全部任务完成后汇报主账号', en: 'Report completion to primary account', descriptionZh: '手动监听当前账号的全部 WorkBuddy 会话,连续确认完成后用主账号 token 新建云端汇报会话;不切换账号。未设置主账号或当前即主账号时跳过;账号变化、失败、状态不明时不发送。最长等待 24 小时。', descriptionEn: 'Manually wait for all current-account WorkBuddy conversations, then create a cloud report conversation as the primary account without switching. Skip if no primary or already primary. Abort on changed account, failure or unknown status. Maximum 24 hours.', example: { op: 'notify.afterAllTasks', timeoutMs: 86400000 } },
+];
+
+// Additive v1 contract. Deprecated operations remain executable for saved tasks.
+for (const [id, zh, en, example, descriptionZh, descriptionEn] of [
+ ['account.list', '列出账号', 'List accounts', {op:'account.list',saveAs:'accounts'}, '返回账号公开信息数组,不包含凭据。', 'Return public account records without credentials.'],
+ ['account.getCurrent', '当前账号', 'Current account', {op:'account.getCurrent',saveAs:'current'}, '返回实际登录账号,同时更新 account 上下文。', 'Return the logged-in account and update account context.'],
+ ['account.getPrimary', '主账号', 'Primary account', {op:'account.getPrimary',saveAs:'primary'}, '返回主账号公开信息;未设置时为 null。', 'Return the primary public record, or null.'],
+ ['vars.set', '设置变量', 'Set variable', {op:'vars.set',key:'count',value:1}, '设置 vars 下的单个变量,值支持递归模板。', 'Set one variable in vars with recursive templates.'],
+ ['logic.forEach', '循环列表', 'Iterate list', {op:'logic.forEach',items:'{{vars.items}}',steps:[]}, '遍历最多 1000 项,使用 vars.item 和 vars.index,退出后恢复上下文。', 'Iterate up to 1000 entries via vars.item and vars.index; restore context on exit.'],
+ ['logic.break', '退出循环', 'Break loop', {op:'logic.break'}, '退出最近一层列表、重复或账号循环。', 'Exit the nearest list, repeat or account loop.'],
+ ['logic.waitUntil', '等待条件', 'Wait for condition', {op:'logic.waitUntil',timeoutMs:10000,intervalMs:250,steps:[],condition:{left:'{{vars.ready}}',operator:'truthy'}}, '立即执行查询步骤并检查条件;超时失败,可取消。', 'Immediately run polling steps and check a condition; cancellable with timeout.'],
+ ['session.create', '新建会话并发送', 'Create and send', {op:'session.create',message:'你好',saveAs:'receipt'}, '保存现有新建页草稿后发送第一条消息,返回绑定账号、会话和请求的回执。', 'Preserve a New Task draft, send the first message and return an account/conversation/request receipt.'],
+ ['session.send', '向指定可见会话发送', 'Send to visible session', {op:'session.send',conversationId:'{{vars.receipt.conversationId}}',message:'继续',saveAs:'receipt'}, '仅发送到已挂载且选中的指定会话;草稿非空时拒绝,未确认发送不会自动重发。', 'Only send to the selected mounted conversation; reject occupied drafts and never automatically resend unconfirmed sends.'],
+ ['session.wait', '等待指定回复完成', 'Wait for bound reply', {op:'session.wait',receipt:'{{vars.receipt}}',timeoutMs:180000}, '按回执绑定账号、会话和请求等待完成;失败、取消或身份变化时退出。', 'Wait by account/conversation/request receipt; fail on errors, cancellation or identity changes.'],
+ ['state.checkpoint', '保存检查点', 'Save checkpoint', {op:'state.checkpoint',key:'progress',value:{done:'{{vars.done}}'}}, '显式保存进度,使用 state.get 恢复;不会自动重放发送或其他副作用。', 'Explicitly save progress; restore with state.get. Never automatically replay sends or other side effects.'],
+]) CAPABILITIES.push({id,zh,en,example,descriptionZh,descriptionEn});
+for (const item of CAPABILITIES) {
+ if (['session.sendCurrent','session.waitReply','notify.afterAllTasks','event.clientLoaded'].includes(item.id)) item.deprecated = true;
+ if (item.id === 'session.sendCurrent') { item.descriptionZh = '兼容旧任务:实际进入新建任务后发送。新任务使用 session.create。'; item.descriptionEn = 'Legacy: navigates to New Task and sends. Use session.create for new tasks.'; }
+ if (item.id === 'session.waitReply') { item.descriptionZh = '兼容旧任务:等待本轮发送绑定的会话回复。新任务使用 session.wait。'; item.descriptionEn = 'Legacy: wait for this run’s bound send. Use session.wait for new tasks.'; }
+ if (item.id === 'http.requestAsAccount') item.example.url = 'https://www.workbuddy.cn/api/example';
+}
+
+const SUPPORTED_OPS = new Set(CAPABILITIES.filter((item) => !item.id.startsWith('event.') && item.available !== false).map((item) => item.id));
+
+function storePath(dataDir) { return path.join(dataDir, 'automations.json'); }
+
+function clone(value) { return value == null ? value : JSON.parse(JSON.stringify(value)); }
+
+function safeId(value) {
+ const id = String(value || '').trim();
+ return /^[A-Za-z0-9][A-Za-z0-9_-]{0,79}$/.test(id) ? id : '';
+}
+
+function readAutomations(dataDir) {
+ try {
+ const raw = JSON.parse(fs.readFileSync(storePath(dataDir), 'utf8'));
+ const list = Array.isArray(raw) ? raw : raw && Array.isArray(raw.items) ? raw.items : [];
+ return list.filter(Boolean).map((item) => isSupportedTaskSchema(item) ? normalizeTask(item) : clone(item));
+ } catch (_) { return []; }
+}
+
+function writeAutomations(dataDir, items) {
+ fs.mkdirSync(dataDir, { recursive: true });
+ const file = storePath(dataDir);
+ const tmp = file + '.tmp-' + process.pid;
+ fs.writeFileSync(tmp, JSON.stringify(items, null, 2) + '\n', { mode: 0o600 });
+ fs.renameSync(tmp, file);
+}
+
+let automationRuntime = {};
+function configureAutomationRuntime(runtime) { automationRuntime = {...runtime}; }
+function isTaskCompatible(task) {
+ try { validateTask(task); return !task.requires || assessRequirements(task.requires, {...automationRuntime,capabilities:CAPABILITIES.filter(c=>c.available!==false).map(c=>c.id)}).length === 0; } catch (_) { return false; }
+}
+
+function isSupportedTaskSchema(task) { return !!task && (task.schemaVersion == null || task.schemaVersion === SCHEMA_VERSION); }
+
+function normalizeTask(input) {
+ const src = input && typeof input === 'object' ? input : {};
+ if (!isSupportedTaskSchema(src)) return clone(src);
+ const { manualRunnable, compatible, ...preserved } = clone(src);
+ const id = safeId(src.id) || ('task_' + crypto.randomBytes(5).toString('hex'));
+ const steps = Array.isArray(src.steps) ? src.steps.slice(0, MAX_STEPS) : [];
+ return {
+ ...preserved,
+ schemaVersion: SCHEMA_VERSION,
+ id,
+ name: String(src.name || id).slice(0, 120),
+ description: String(src.description || '').slice(0, 500),
+ enabled: src.enabled !== false,
+ trigger: normalizeTrigger(src.trigger),
+ schedule: src.schedule && typeof src.schedule === 'object' ? clone(src.schedule) : { type: 'manual' },
+ variables: src.variables && typeof src.variables === 'object' ? clone(src.variables) : {},
+ steps,
+ onSuccess: Array.isArray(src.onSuccess) ? src.onSuccess.slice(0, 40) : [],
+ onFailure: Array.isArray(src.onFailure) ? src.onFailure.slice(0, 40) : [],
+ updatedAt: Number(src.updatedAt) || Date.now(),
+ };
+}
+
+function normalizeTrigger(input) {
+ const src = input && typeof input === 'object' ? input : {};
+ const type = String(src.type || 'manual').trim();
+ return {
+ ...clone(src),
+ type,
+ ...(Array.isArray(src.types) ? { types: [...new Set(src.types.filter((v) => v !== 'manual'))] } : {}),
+ oncePerNavigation: src.oncePerNavigation !== false,
+ // 仅幂等的页面清理任务主动启用:换页时结束旧轮,再检测新页面。
+ ...(src.restartOnNavigation === true ? { restartOnNavigation: true } : {}),
+ };
+}
+
+
+// Legacy single triggers remain valid; a types array explicitly selects multiple events.
+function canManuallyRunTask(task) {
+ if (!isTaskCompatible(task)) return false;
+ const trigger = task.trigger || {};
+ const types = Array.isArray(trigger.types) ? trigger.types : [trigger.type || 'manual'];
+ return !types.some((type) => type && type !== 'manual') && !(task.schedule && task.schedule.type !== 'manual');
+}
+
+function taskMatchesEvent(task, type, detail = {}) {
+ if (!isTaskCompatible(task) || !task.enabled) return false;
+ const trigger = task.trigger || {};
+ const types = Array.isArray(trigger.types) ? trigger.types : [trigger.type];
+ return types.some((t) => t === type || type === 'pageReady' && (t === 'pageLoaded' || t === 'accountSwitched' && /account-switch/.test(detail.source || '') || t === 'clientLoaded' && detail.source === 'connect'));
+}
+
+function validateSchedule(schedule) {
+ if (!schedule || !['manual', 'interval', 'daily', 'weekly', 'monthly', 'once'].includes(schedule.type)) throw new Error('不支持的定时方式');
+ if (schedule.type === 'interval' && (!Number.isInteger(schedule.minutes) || schedule.minutes < 1 || schedule.minutes > 10080)) throw new Error('定时间隔必须是 1–10080 分钟的整数');
+ if (['daily', 'weekly', 'monthly'].includes(schedule.type) && !/^([01]\d|2[0-3]):[0-5]\d$/.test(schedule.time || '')) throw new Error('请选择有效的执行时间');
+ if (schedule.type === 'weekly' && (!Array.isArray(schedule.days) || !schedule.days.length || schedule.days.some(d => !Number.isInteger(d) || d < 0 || d > 6))) throw new Error('请至少选择一个星期');
+ if (schedule.type === 'monthly' && (!Number.isInteger(schedule.day) || schedule.day < 1 || schedule.day > 31)) throw new Error('每月日期必须是 1–31');
+ if (schedule.type === 'once') {
+ const value = String(schedule.at || '');
+ const date = new Date(value);
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value) || !Number.isFinite(date.getTime()) || localScheduleSlot(date) !== value) throw new Error('请选择有效的执行日期和时间');
+ }
+ return schedule;
+}
+
+function localScheduleSlot(date) {
+ const pad = n => String(n).padStart(2, '0');
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
+}
+
+function createScheduleTicker(dataDir) {
+ const due = new Map();
+ const stateFile = dataDir && path.join(dataDir, 'automation-schedule-state.json');
+ let marks = {};
+ try { if (stateFile) marks = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch (_) {}
+ if (!marks || typeof marks !== 'object' || Array.isArray(marks)) marks = {};
+ return (tasks, start, isRunning, now = Date.now()) => {
+ const ids = new Set();
+ for (const task of tasks) {
+ const schedule = task.schedule;
+ if (!isTaskCompatible(task) || !task.enabled || !schedule || schedule.type === 'manual') continue;
+ try { validateSchedule(schedule); } catch (_) { continue; }
+ ids.add(task.id);
+ if (schedule.type === 'interval') {
+ const interval = schedule.minutes * 60000;
+ let entry = due.get(task.id);
+ if (!entry || entry.interval !== interval) {
+ entry = { interval, next: now + interval };
+ due.set(task.id, entry);
+ }
+ if (now < entry.next) continue;
+ entry.next = now + interval;
+ } else {
+ due.delete(task.id);
+ const date = new Date(now), slot = localScheduleSlot(date);
+ const time = slot.slice(11);
+ const matches = schedule.type === 'once' ? slot === schedule.at : time === schedule.time &&
+ (schedule.type !== 'weekly' || schedule.days.includes(date.getDay())) &&
+ (schedule.type !== 'monthly' || schedule.day === date.getDate());
+ if (!matches || marks[task.id] && marks[task.id] >= slot) continue;
+ // Persist before dispatch: restarts, DST fallback and a busy task must
+ // not repeat the same wall-clock slot. Missed slots are never replayed.
+ marks[task.id] = slot;
+ if (stateFile) {
+ try { atomicWriteText(stateFile, JSON.stringify(marks) + '\n'); }
+ catch (_) { continue; }
+ }
+ }
+ if (!isRunning(task.id)) start(task, { type: 'schedule', source: schedule.type });
+ }
+ for (const id of due.keys()) if (!ids.has(id)) due.delete(id);
+ };
+}
+
+// Navigation-scoped click-only observers must keep dismissing late popups while
+// an account loop waits for a reply. They share the short input gate instead of
+// monopolizing the renderer for their entire observation window.
+function taskIsPassiveCleanup(task) {
+ if (!(task.trigger && task.trigger.restartOnNavigation)) return false;
+ const allowed = new Set(['logic.sequence','logic.repeat','logic.retry','logic.catch','logic.delay','logic.if','logic.assert','logic.switch','dom.find','dom.click','dom.wait','dom.readText','dom.readAttribute','notify.toast','notify.dismiss']);
+ let clicks = 0, valid = true;
+ const walk = value => {
+ if (Array.isArray(value)) value.forEach(walk);
+ else if (value && typeof value === 'object') {
+ if (value.op) { if (!allowed.has(value.op)) valid = false; if (value.op === 'dom.click') { clicks++; const locators = value.locators || [value.locator]; if (!locators.every(l=>l && l.visible === true && /close|dismiss|关闭|不再展示/i.test(l.value || ''))) valid = false; } }
+ Object.values(value).forEach(walk);
+ }
+ };
+ walk([task.steps,task.onSuccess,task.onFailure]);
+ return valid && clicks > 0;
+}
+
+function taskNeedsPanelClosed(task) {
+ const walk = (value) => {
+ if (Array.isArray(value)) return value.some(walk);
+ if (!value || typeof value !== 'object') return false;
+ if (/^(dom\.|session\.)/.test(value.op || '') || value.op === 'account.forEach' && (value.switch === true || value.switchAccounts === true)) return true;
+ return Object.values(value).some(walk);
+ };
+ return walk([task.steps, task.onSuccess, task.onFailure]);
+}
+
+function installBuiltinTask(dataDir, file) {
+ const task = validateTask(JSON.parse(fs.readFileSync(file, 'utf8')));
+ const markerFile = path.join(dataDir, 'automation-builtins.json');
+ let markers = {};
+ try { markers = JSON.parse(fs.readFileSync(markerFile, 'utf8')); } catch (_) {}
+ if (markers[task.id]) return;
+ const tasks = readAutomations(dataDir);
+ if (!tasks.some((t) => t.id === task.id)) {
+ if (tasks.length >= MAX_TASKS) return;
+ writeAutomations(dataDir, tasks.concat(task));
+ }
+ atomicWriteText(markerFile, JSON.stringify({ ...markers, [task.id]: true }) + '\n');
+}
+
+function validateLocator(locator) {
+ if (!locator || typeof locator !== 'object') throw new Error('缺少 locator');
+ const kind = String(locator.kind || '').trim();
+ const value = String(locator.value || '').trim();
+ if (!['css', 'xpath', 'text', 'role', 'ariaLabel', 'placeholder', 'attribute', 'coordinates'].includes(kind)) {
+ throw new Error('不支持的定位方式: ' + kind);
+ }
+ if (!value && kind !== 'coordinates') throw new Error('locator.value 不能为空');
+ if (kind === 'coordinates' && (!Number.isFinite(Number(locator.x)) || !Number.isFinite(Number(locator.y)))) throw new Error('坐标定位无效');
+}
+
+function validateSteps(steps, depth = 0) {
+ if (!Array.isArray(steps)) throw new Error('steps 必须是数组');
+ if (depth > MAX_DEPTH) throw new Error('任务嵌套层级过深');
+ if (steps.length > MAX_STEPS) throw new Error('步骤数量超过限制');
+ steps.forEach((step, index) => {
+ if (!step || typeof step !== 'object') throw new Error(`第 ${index + 1} 步不是对象`);
+ const op = String(step.op || '').trim();
+ if (op === 'notify.toast' || op === 'notify.dismiss') {
+ const id = typeof step.id === 'string' && /\{\{[\w. -]+\}\}/.test(step.id) ? 'template-id' : step.id;
+ normalizeToastOptions({ ...step, id }, op === 'notify.dismiss');
+ }
+ if (/^state\./.test(op) && (!['task','account'].includes(step.scope || 'task') || typeof step.key !== 'string' || !step.key.trim())) throw new Error('状态需要有效的 scope 和 key');
+ if (step.saveAs && (!/^[A-Za-z_][\w-]{0,79}$/.test(step.saveAs) || ['__proto__','prototype','constructor'].includes(step.saveAs))) throw new Error('saveAs 必须是变量名');
+ if (step.locators) { if (!Array.isArray(step.locators) || !step.locators.length || step.locators.length > 10) throw new Error('候选定位器需要 1–10 项'); step.locators.forEach(validateLocator); }
+ if (!SUPPORTED_OPS.has(op)) throw new Error(`第 ${index + 1} 步不支持能力: ${op || '(空)'}`);
+ if (['logic.sequence', 'logic.repeat', 'logic.retry', 'logic.catch', 'logic.forEach', 'logic.waitUntil', 'account.forEach'].includes(op)) validateSteps(step.steps || [], depth + 1);
+ if (op === 'logic.retry' && /\"op\"\s*:\s*\"session\.(create|send|sendCurrent)\"/.test(JSON.stringify(step.steps || []))) throw new Error('会话发送不能放入 retry,避免重复发送');
+ if (op === 'logic.catch') validateSteps(step.onError || [], depth + 1);
+ if (op === 'logic.if') { validateSteps(step.then || [], depth + 1); validateSteps(step.else || [], depth + 1); }
+ if (op === 'logic.switch') {
+ Object.values(step.cases || {}).forEach((value) => validateSteps(value || [], depth + 1));
+ validateSteps(step.default || [], depth + 1);
+ }
+ if (['dom.find', 'dom.click', 'dom.type', 'dom.clear', 'dom.press', 'dom.readText', 'dom.readAttribute', 'dom.wait'].includes(op) && step.locator) validateLocator(step.locator);
+ if (op === 'http.request' || op === 'http.requestAsAccount') {
+ const url = String(step.url || '').trim();
+ if (!/^https?:\/\//i.test(url) && !/^\{\{\s*[\w.-]+\s*\}\}$/.test(url)) throw new Error(`第 ${index + 1} 步 URL 仅支持 http(s)`);
+ if (url.length > 2048) throw new Error(`第 ${index + 1} 步 URL 过长`);
+ }
+ });
+}
+
+function validateTask(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('任务必须是 JSON 对象');
+ if (input.kind != null) throw new Error('任务包或索引不能作为本地任务执行');
+ if (input.schemaVersion != null && input.schemaVersion !== 1) throw new Error('不支持的任务协议版本');
+ if (input.id != null && !safeId(input.id)) throw new Error('任务 ID 无效');
+ if (input.requires) { validateRequirements(input.requires); if(input.requires.taskSchemaVersion !== (input.schemaVersion || 1)) throw new Error('任务协议与兼容要求不一致'); }
+ for(const [key,limit] of [['steps',MAX_STEPS],['onSuccess',40],['onFailure',40]]) if(input[key]!=null && (!Array.isArray(input[key]) || input[key].length>limit)) throw new Error('任务步骤不是数组或超过数量限制');
+ if (input.trigger) {
+ const allowed = ['manual','pageReady','pageLoaded','accountSwitched','clientLoaded','panelOpened'];
+ if (input.trigger.type && !allowed.includes(input.trigger.type) || input.trigger.types != null && (!Array.isArray(input.trigger.types) || input.trigger.types.some(t=>!allowed.includes(t)))) throw new Error('不支持的触发方式');
+ }
+ const task = normalizeTask(input);
+ if (!safeId(task.id)) throw new Error('任务 ID 必须是字母、数字、下划线或短横线');
+ if (!task.name.trim()) throw new Error('任务名称不能为空');
+ if (!['manual', 'pageReady', 'pageLoaded', 'accountSwitched', 'clientLoaded', 'panelOpened'].includes(task.trigger.type)) throw new Error('不支持的触发方式: ' + task.trigger.type);
+ validateSchedule(task.schedule);
+ validateSteps(task.steps);
+ validateSteps(task.onSuccess || []);
+ validateSteps(task.onFailure || []);
+ return task;
+}
+
+function interpolate(value, ctx) {
+ if (typeof value !== 'string') return value;
+ return value.replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (_, key) => {
+ const parts = key.split('.');
+ let cur = ctx;
+ for (const part of parts) cur = cur == null ? undefined : cur[part];
+ return cur == null ? '' : String(cur);
+ });
+}
+
+function resolveValue(value, ctx) {
+ if (Array.isArray(value)) return value.map(item => resolveValue(item, ctx));
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k,v]) => [k, resolveValue(v, ctx)]));
+ if (typeof value !== 'string') return value;
+ const exact = value.match(/^\{\{\s*([\w.-]+)\s*\}\}$/);
+ if (!exact) return interpolate(value, ctx);
+ const parts = exact[1].split('.');
+ let cur = ctx;
+ for (const part of parts) cur = cur == null ? undefined : cur[part];
+ return cur;
+}
+
+function getPath(ctx, key) { return resolveValue('{{' + String(key || '') + '}}', ctx); }
+
+function compare(left, operator, right) {
+ if (['gt','gte','lt','lte'].includes(operator)) {
+ if (left == null || right == null || left === '' || right === '' || !Number.isFinite(Number(left)) || !Number.isFinite(Number(right))) return false;
+ return ({gt: (a,b)=>a>b, gte:(a,b)=>a>=b, lt:(a,b)=>a<b, lte:(a,b)=>a<=b})[operator](Number(left),Number(right));
+ }
+ if (operator === 'equals') return left === right || String(left) === String(right);
+ if (operator === 'notEquals') return !(left === right || String(left) === String(right));
+ if (operator === 'contains') return String(left == null ? '' : left).includes(String(right == null ? '' : right));
+ if (operator === 'matches') { try { return new RegExp(String(right)).test(String(left == null ? '' : left)); } catch (_) { return false; } }
+ if (operator === 'truthy') return !!left;
+ if (operator === 'falsy') return !left;
+ throw new Error('不支持的判断运算符: ' + operator);
+}
+
+function capabilityText(language = 'zh') {
+ const zh = language !== 'en';
+ const available = CAPABILITIES.filter((item) => item.available !== false);
+ const reserved = CAPABILITIES.filter((item) => item.available === false);
+ const triggers = available.filter((item) => item.id.startsWith('event.'));
+ const executable = available.filter((item) => !item.id.startsWith('event.'));
+ const groups = {};
+ CAPABILITIES.filter(item => item.available !== false).forEach((item) => {
+ const group = item.id.split('.')[0];
+ if (!groups[group]) groups[group] = [];
+ groups[group].push(item.id + (item.available === false ? (zh ? '(预留)' : ' (reserved)') : ''));
+ });
+ const lines = zh ? [
+ 'WorkDaddy 自动化任务协议 v1',
+ '',
+ '任务 JSON:',
+ JSON.stringify({ schemaVersion: 1, id: 'example-task', name: '任务名称', description: '', enabled: true, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [], onSuccess: [], onFailure: [] }, null, 2),
+ '',
+ '任务字段:schemaVersion 固定为 1;id 在全部任务中唯一;name 必填;description 可空;enabled 控制生命周期触发;variables 是任务初始变量;steps 是主步骤;onSuccess/onFailure 分别在成功/失败后执行。',
+ '约束:最多 200 个任务;每组最多 200 个步骤;最多嵌套 12 层;单次重复最多 100 次;重试最多 10 次;单次等待最多 300 秒。任务中不要保存 Token、Cookie 或密码。',
+ '触发器:manual 仅手动运行;pageReady 在首次打开、导航完成或账号切换后的页面刷新完成后运行。pageReady 默认同一次页面导航只触发一次;pageLoaded 同样覆盖页面加载(包括切换刷新);accountSwitched 仅账号切换;clientLoaded 仅 daemon 连接已加载客户端时触发(兼容名,不建议新任务使用)。组合事件同一导航只执行一次。',
+ '组合触发:trigger.types:["clientLoaded","panelOpened"] 可多选,存在时替代 trigger.type;空数组仅手动。schedule:{type:"interval",minutes:60} 每小时触发(1–10080 分钟);也支持 {type:"daily",time:"09:00"}、{type:"weekly",days:[1,2,3,4,5],time:"09:00"}(0=周日)、{type:"monthly",day:15,time:"09:00"}、{type:"once",at:"2026-12-01T09:00"}。均为电脑本地时区,每月不存在的日期跳过,指定时间任务不会重复,可与事件组合;enabled:false 停止所有自动触发。自动任务不提供立即运行;需要测试时在编辑器清空自动触发条件并关闭定时,再手动运行。运行中的同一任务不会重入,错过的定时不会补跑。POST /api/automations/events {type:"panelOpened"} 在面板从关闭变为打开时调用,需标准本地 API 认证。',
+ '签到:account.checkin 使用循环账号的 token,先检查本地今日已验证记录,成功则跳过(包括 token 刷新);失败返回 ok:false,单账号异常可用 logic.catch 捕获。无需 switch:true。',
+ '通用步骤字段:op 必填;saveAs 可把该步骤返回值保存到 {{vars.<name>}};每个步骤的返回值也会覆盖 {{step.*}}。嵌套步骤仍按顺序执行。',
+ '模板变量:{{now}}、{{event.type}}、{{event.account.uid}}、{{account.uid}}、{{account.nickname}}、{{vars.name}}、{{response.status}}、{{response.text}}、{{response.json}}、{{step.*}}。对象与数组递归展开模板;完整字符串模板保留原始数值/对象/数组类型,混合文本模板会转成字符串。',
+ '条件运算符:equals、notEquals、contains、matches、truthy、falsy、gt、gte、lt、lte。matches 的 right 是正则表达式字符串。',
+ '账号作用域:account.forEach 默认只改变嵌套步骤的账号上下文;设置 switch:true 才会真实切换登录账号,并在循环结束后恢复原账号。account.status 和 http.requestAsAccount 使用当前上下文;DOM 与当前会话步骤操作切换后的可见 WorkBuddy 页面。',
+ '元素定位 locator:{kind,value}。kind 支持 css、xpath、text、role、ariaLabel、placeholder、attribute。coordinates 仅保留协议格式,当前不可用于 DOM 步骤。',
+ 'DOM 等待:dom.wait 可使用 seconds 做固定等待;或使用 locator、until:{state:"visible"|"hidden"|"attached"|"detached"|"clickable"}、timeoutMs 等待元素状态。until 还支持 text 包含匹配或 attribute/value 相等。locators 数组提供依次回退的定位器;readText 最多 100000 字符。iframe 内目前只支持读取,不支持点击与输入。DOM 读取结果可用 saveAs 保存。',
+ 'HTTP 输入:method、url、query、headers、body、timeoutMs(500-60000)、saveAs。响应:{ok,status,headers,text,json},正文最多 1 MiB。http.request 不允许自定义 Authorization/Cookie;http.requestAsAccount 只对当前客户端官方 HTTPS origin 注入账号登录态;禁止跨域、非默认端口、URL 用户名密码。重定向不会自动跟随。body/query/headers 支持递归模板。默认非 2xx 返回 ok:false 供分支判断;throwOnHttpError:true 抛错以配合 retry(支持 backoff,默认 1)。停止会中止 HTTP 和等待。',
+ '会话:session.create 新建并发送第一条消息;session.send 仅向选中且无草稿的指定 conversationId 发送;返回 {accountUid,conversationId,userMessageId,requestId,baselineAssistantId} 回执,saveAs 保存。session.wait 接受 receipt(默认 vars.session)、timeoutMs(最长 300000)、contains,按回执监听。未知发送结果不会自动重发;发送不能嵌套 retry。session.sendCurrent/waitReply 是兼容别名,前者实际上新建会话。仅支持挂载的可见会话,不支持后台任意会话发送。',
+ '状态作用域:state.get/state.set 的 scope 支持 task(默认)或 account;所有状态首先按任务 ID 隔离;task scope 不随账号变化,account scope 再按 uid 隔离;写入合并最新状态。旧版本无任务 ID 的歧义状态不会自动归入任何任务。key 必填;state.get 可配 saveAs。',
+ '通知:notify.toast 使用 react-hot-toast,从窗口底部向上弹出;level 支持 info、success、warning、error、loading。可选 duration(1000–60000 毫秒)、id、saveAs;相同 id 更新提示,notify.dismiss 用 id 关闭。id 按本次运行隔离,任务结束自动清理 loading。notify.afterAllTasks 已废弃,仅兼容旧任务;新任务不要使用。',
+ '失败语义:未捕获错误会停止主步骤并执行 onFailure;logic.catch 捕获局部错误并把消息写入 {{vars.error.message}};logic.retry 只重试其嵌套步骤。',
+ '',
+ '基础接口总目录:',
+ ] : [
+ 'WorkDaddy Automation Task Protocol v1',
+ '',
+ 'Task JSON:',
+ JSON.stringify({ schemaVersion: 1, id: 'example-task', name: 'Task name', description: '', enabled: true, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [], onSuccess: [], onFailure: [] }, null, 2),
+ '',
+ 'Task fields: schemaVersion is 1; id is unique; name is required; description may be empty; enabled controls lifecycle triggers; variables contains initial values; steps is the main sequence; onSuccess/onFailure run after success/failure.',
+ 'Limits: 200 tasks; 200 steps per group; nesting depth 12; 100 repeat iterations; 10 retry attempts; 300 seconds per wait. Never store tokens, cookies, or passwords in a task.',
+ 'Triggers: manual only runs on demand; pageReady runs after initial load, navigation, or the page refresh following an account switch. pageReady runs once per navigation by default; pageLoaded includes all page loads; accountSwitched only matches switches; clientLoaded is a legacy connection-only trigger. Combined events run once per navigation.',
+ 'Combined triggers: trigger.types:["clientLoaded","panelOpened"] overrides trigger.type. Empty types means manual only. schedule:{type:"interval",minutes:60} adds an interval of 1–10080 minutes. Also supported: {type:"daily",time:"09:00"}, {type:"weekly",days:[1,2,3,4,5],time:"09:00"} (0=Sunday), {type:"monthly",day:15,time:"09:00"}, {type:"once",at:"2026-12-01T09:00"}. All use local computer time; nonexistent month dates and missed slots are skipped, and calendar slots are not repeated after restart. Only tasks without automatic triggers or a schedule can run manually. Disabled tasks do not auto-run; running tasks skip overlapping triggers. POST /api/automations/events {type:"panelOpened"} requires local API authentication. account.checkin uses the context account token and skips all requests for a confirmed daily check-in; use logic.catch to handle individual account errors.',
+ 'Common step fields: op is required; saveAs stores the returned value at {{vars.<name>}}; each result also replaces {{step.*}}. Nested steps execute sequentially.',
+ 'Template values: {{now}}, {{event.type}}, {{event.account.uid}}, {{account.uid}}, {{account.nickname}}, {{vars.name}}, {{response.status}}, {{response.text}}, {{response.json}}, {{step.*}}. Objects and arrays recursively resolve templates. A whole-value template preserves numbers/objects/arrays; interpolation inside text produces a string.',
+ 'Condition operators: equals, notEquals, contains, matches, truthy, falsy, gt, gte, lt, lte. matches treats right as a regular-expression string.',
+ 'Account scope: account.forEach only changes nested context by default. Set switch:true to physically switch the logged-in account and restore the original account after the loop. account.status and http.requestAsAccount use the current context; DOM and current-session steps operate the visible WorkBuddy page after switching.',
+ 'Locator: {kind,value}. kind supports css, xpath, text, role, ariaLabel, placeholder, and attribute. coordinates is reserved and unavailable to current DOM steps.',
+ 'DOM waits: use seconds for a fixed delay, or locator plus until:{state:"visible"|"hidden"|"attached"|"detached"|"clickable"} and timeoutMs. until also accepts text containment or attribute/value equality. locators supplies ordered fallbacks; readText is capped at 100000 characters. Iframes support reads only, not clicks or input. DOM read results can be stored with saveAs.',
+ 'HTTP input: method, url, query, headers, body, timeoutMs (500-60000), saveAs. Response: {ok,status,headers,text,json}; body is capped at 1 MiB. http.request rejects Authorization/Cookie; http.requestAsAccount injects credentials only for current-profile official HTTPS origins, rejecting foreign origins, ports and URL credentials. Redirects are not followed. body/query/headers resolve recursive templates. Non-2xx returns ok:false by default; throwOnHttpError:true enables retry (backoff defaults to 1). Cancellation aborts HTTP and waits.',
+ 'Sessions: session.create creates by sending the first message; session.send targets only a selected conversationId with an empty composer. Returns {accountUid,conversationId,userMessageId,requestId,baselineAssistantId}; saveAs persists the receipt in variables. session.wait accepts receipt (default vars.session), timeoutMs (up to 300000), contains. Unconfirmed sends are never automatically retried; sends cannot be nested in retry. sendCurrent/waitReply are legacy aliases; sendCurrent creates a new conversation. Only mounted visible sessions are supported.',
+ 'State scope: state.get/state.set scope is task (default) or account. all state is isolated by task ID first, with an additional uid dimension for account scope. Writes merge the latest state. Ambiguous legacy state without task IDs is not automatically assigned to any task. key is required; state.get accepts saveAs.',
+ 'Notifications: notify.toast uses react-hot-toast at bottom-center. level is info, success, warning, error, or loading. Optional duration (1000–60000 ms), id, and saveAs; reuse id to update, notify.dismiss with id to dismiss. IDs are scoped to a run; unfinished loading notifications are cleared when the run ends. notify.afterAllTasks is deprecated and retained only for saved tasks. Do not generate it for new tasks.',
+ 'Failure behavior: an uncaught error stops main steps and runs onFailure. logic.catch writes a local error to {{vars.error.message}}. logic.retry retries only its nested steps.',
+ '',
+ 'Capability index:',
+ ];
+ lines.push(zh
+ ? `${CAPABILITIES.length} 项:${triggers.length} 个触发事件,${executable.length} 个可执行 op,${reserved.length} 个预留接口。event.* 只能写入 trigger.type;只有可执行 op 能写入任务步骤。`
+ : `${CAPABILITIES.length} entries: ${triggers.length} trigger events, ${executable.length} executable ops, ${reserved.length} reserved interface. event.* belongs in trigger.type; only executable ops may be used in task steps.`);
+ Object.keys(groups).forEach((group) => lines.push(group + ': ' + groups[group].join(', ')));
+ lines.push('', zh ? '逐项说明与最小示例:' : 'Per-operation reference and minimal examples:');
+ CAPABILITIES.filter(item => item.available !== false).forEach((item) => {
+ const availability = item.deprecated ? (zh ? ' [兼容旧任务,新任务勿用]' : ' [legacy, avoid in new tasks]') : '';
+ lines.push('', item.id + availability, (zh ? item.zh + ':' + item.descriptionZh : item.en + ': ' + item.descriptionEn), JSON.stringify(item.example, null, 2));
+ });
+ lines.push('', zh ? '账号状态字段:checkin.today、activity.today、activity.streak、credits。返回 uid、isPrimary、checkin、activity、credits;activity.streak={days,status},days=null 表示不可用;credits={total,unlimited,cycleResetTime}。活跃天数是连续活跃天数,不是注册天数。' : 'Account fields: checkin.today, activity.today, activity.streak, credits. Returns uid,isPrimary,checkin,activity,credits. activity.streak={days,status}; null means unavailable. credits={total,unlimited,cycleResetTime}. Streak means consecutive active days, not registration age.');
+ lines.push(zh ? '预检:POST /api/automations/validate 或 /api/automations/dry-run,body={task},需本地认证。仅静态校验并返回操作计划/弃用警告,executed:false,不发请求、不切账号、不发送消息,不保证运行时 DOM/API 可用。state.checkpoint 显式保存业务进度,state.get 读取;不会自动恢复或重放副作用。修改同一渲染器的任务排队串行,静默 API 任务可并发;restartOnNavigation 的只读/关闭按钮监听不占用整轮锁,但点击与输入仍互斥,避免关闭弹窗任务阻塞发送;取消不代表已发送消息或已完成服务器操作可撤销。' : 'Preflight: authenticated POST /api/automations/validate or /api/automations/dry-run with {task}. Static validation and operation plan/deprecation warnings only; executed:false. No HTTP, switches or messages. Does not guarantee runtime DOM/API availability. state.checkpoint explicitly saves progress for state.get; never automatically resumes or replays side effects. Renderer tasks queue serially; silent API tasks can run concurrently. Navigation-scoped read/click-only observers share a short input lock so popup cleanup can run between sends. Cancellation cannot undo messages or completed server operations.');
+ lines.push(zh ? '共享任务兼容:本地任务继续使用 schemaVersion:1,可选 requires={minWorkDaddyVersion,taskSchemaVersion,capabilities,profiles?,platforms?};不满足依赖时不会执行。外部分发使用独立的 workdaddy.automation-package 包(formatVersion:1、独立 id/version、requires、inputs、task)。POST /api/automations/packages/preview {document,values?} 只预检,需检查 compatible:true;不会安装或执行。为本面板生成任务时仍输出本地任务 JSON,不要向 Agent 收件箱写入包或索引。' : 'Sharing compatibility: local tasks remain schemaVersion:1 and may declare requires={minWorkDaddyVersion,taskSchemaVersion,capabilities,profiles?,platforms?}; incompatible tasks never execute. Distribution uses a separate workdaddy.automation-package envelope with formatVersion:1, independent id/version, requires, inputs and task. POST /api/automations/packages/preview {document,values?} is preview-only; check compatible:true. No installation or execution. When creating tasks for this panel, keep generating local task JSON, never a package or index in the Agent inbox.');
+ return lines.join('\n');
+}
+
+function agentBridgePaths(dataDir) {
+ const root = path.join(dataDir, 'automation-agent');
+ return {
+ root,
+ protocolZh: path.join(root, 'PROTOCOL.zh-CN.txt'),
+ protocolEn: path.join(root, 'PROTOCOL.en.txt'),
+ guide: path.join(root, 'README.txt'),
+ inboxDir: path.join(root, 'inbox'),
+ resultsDir: path.join(root, 'results'),
+ };
+}
+
+function atomicWriteText(file, text) {
+ const content = String(text);
+ try {
+ if (fs.readFileSync(file, 'utf8') === content) return;
+ } catch (_) {}
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
+ const tmp = file + '.tmp-' + process.pid + '-' + crypto.randomBytes(4).toString('hex');
+ fs.writeFileSync(tmp, content, { mode: 0o600 });
+ try { fs.renameSync(tmp, file); }
+ catch (error) {
+ try { fs.rmSync(file, { force: true }); fs.renameSync(tmp, file); }
+ catch (_) { try { fs.rmSync(tmp, { force: true }); } catch (_) {} throw error; }
+ }
+}
+
+function agentGuideText(paths, profileId) {
+ return [
+ 'WorkDaddy automation agent bridge',
+ '',
+ 'Profile: ' + String(profileId || 'unknown'),
+ 'Chinese protocol: ' + paths.protocolZh,
+ 'English protocol: ' + paths.protocolEn,
+ 'Task inbox: ' + paths.inboxDir,
+ 'Import results: ' + paths.resultsDir,
+ '',
+ 'Read the protocol, then write exactly one task JSON object to the requested .json file in inbox.',
+ 'The daemon validates the task and writes a same-name result JSON file in results.',
+ 'Do not place tokens, cookies, passwords, or executable code in a task.',
+ 'Do not edit automations.json directly.',
+ '不要直接修改 automations.json。',
+ '',
+ ].join('\n');
+}
+
+function ensureAgentBridge(dataDir, options = {}) {
+ const paths = agentBridgePaths(dataDir);
+ fs.mkdirSync(paths.inboxDir, { recursive: true, mode: 0o700 });
+ fs.mkdirSync(paths.resultsDir, { recursive: true, mode: 0o700 });
+ atomicWriteText(paths.protocolZh, capabilityText('zh') + '\n');
+ atomicWriteText(paths.protocolEn, capabilityText('en') + '\n');
+ atomicWriteText(paths.guide, agentGuideText(paths, options.profileId));
+ return paths;
+}
+
+function safeRequestId(value) {
+ const id = String(value || '').trim();
+ return /^[A-Za-z0-9][A-Za-z0-9_-]{0,95}$/.test(id) ? id : '';
+}
+
+function createAgentRequest(dataDir, options = {}) {
+ const example = AGENT_EXAMPLES.find((item) => item.id === String(options.exampleId || ''));
+ const custom = options.prompt !== undefined && options.prompt !== null;
+ if (custom && (typeof options.prompt !== 'string' || !options.prompt.trim() || options.prompt.length > 6000)) throw new Error('自动化需求必须是 1–6000 字的文本');
+ if (!custom && !example) throw new Error('未知的自动化示例');
+ const language = options.language === 'en' ? 'en' : 'zh';
+ const paths = ensureAgentBridge(dataDir, { profileId: options.profileId });
+ const timestamp = Number(options.now) || Date.now();
+ const requestId = safeRequestId('agent-' + timestamp.toString(36) + '-' + crypto.randomBytes(4).toString('hex'));
+ const inboxFile = path.join(paths.inboxDir, requestId + '.json');
+ const resultFile = path.join(paths.resultsDir, requestId + '.json');
+ const protocolPath = language === 'en' ? paths.protocolEn : paths.protocolZh;
+ const taskPrompt = custom ? options.prompt.trim() : language === 'en' ? example.promptEn : example.promptZh;
+ const instructions = language === 'en' ? [
+ 'WorkDaddy has prepared a restricted local bridge for this request.',
+ '1. Read the complete automation protocol at: ' + protocolPath,
+ '2. Design one declarative task using only supported capabilities. Do not include tokens, cookies, passwords, shell commands, or JavaScript.',
+ '3. Use your file-writing tool to write the final task JSON object, and nothing else, to this exact path: ' + inboxFile,
+ '4. Do not edit automations.json directly and do not merely paste the JSON into your reply.',
+ '5. Wait for WorkDaddy to create this result file and read it: ' + resultFile,
+ '6. Only report success when that result contains "ok": true. If rejected, fix the task and write it again using a new id in the task JSON.',
+ ] : [
+ 'WorkDaddy 已为本次请求准备了受约束的本地桥接通道。',
+ '1. 先读取完整自动化协议:' + protocolPath,
+ '2. 只使用协议支持的声明式能力设计一个任务。不要写入 Token、Cookie、密码、Shell 命令或 JavaScript。',
+ '3. 使用你的文件写入工具,把最终的单个任务 JSON 对象(不要附带 Markdown)写入这个精确路径:' + inboxFile,
+ '4. 不要直接修改 automations.json,也不要只在回复中粘贴 JSON。',
+ '5. 等待 WorkDaddy 生成并读取结果文件:' + resultFile,
+ '6. 只有结果包含 "ok": true 才算完成;如果被拒绝,请修正任务,并在任务 JSON 中使用新的 id 后重新写入。',
+ ];
+ return {
+ requestId,
+ exampleId: custom ? '' : example.id,
+ title: custom ? (language === 'en' ? 'Create automation task' : '创建自动化任务') : language === 'en' ? example.titleEn : example.titleZh,
+ prompt: taskPrompt + '\n\n' + instructions.join('\n'),
+ protocolPath,
+ inboxFile,
+ resultFile,
+ };
+}
+
+function importAgentInbox(dataDir, options = {}) {
+ const paths = agentBridgePaths(dataDir);
+ fs.mkdirSync(paths.inboxDir, { recursive: true, mode: 0o700 });
+ fs.mkdirSync(paths.resultsDir, { recursive: true, mode: 0o700 });
+ const now = Number(options.now) || Date.now();
+ const settleMs = options.settleMs == null ? 750 : Math.max(0, Number(options.settleMs) || 0);
+ const outcomes = [];
+ let entries = [];
+ try { entries = fs.readdirSync(paths.inboxDir, { withFileTypes: true }); } catch (_) { return outcomes; }
+ for (const entry of entries.slice(0, 50)) {
+ if (!entry.isFile() || !/^([A-Za-z0-9][A-Za-z0-9_-]{0,95})\.json$/.test(entry.name)) continue;
+ const requestId = entry.name.slice(0, -5);
+ const inboxFile = path.join(paths.inboxDir, entry.name);
+ const resultFile = path.join(paths.resultsDir, entry.name);
+ try {
+ const stat = fs.lstatSync(inboxFile);
+ if (!stat.isFile() || stat.isSymbolicLink()) continue;
+ if (settleMs > 0 && now - stat.mtimeMs < settleMs) continue;
+ if (fs.existsSync(resultFile)) {
+ let previous = null;
+ try { previous = JSON.parse(fs.readFileSync(resultFile, 'utf8')); } catch (_) {}
+ if (previous && previous.ok === true) { fs.unlinkSync(inboxFile); continue; }
+ }
+ if (stat.size <= 0 || stat.size > MAX_AGENT_FILE_BYTES) throw new Error('任务文件必须是 1 MiB 以内的非空 JSON');
+ const parsed = JSON.parse(fs.readFileSync(inboxFile, 'utf8'));
+ if (parsed && parsed.kind) throw new Error('外部任务包需要独立预检与安装,不能通过 Agent 收件箱自动启用');
+ const task = validateTask(parsed && parsed.task ? parsed.task : parsed);
+ const tasks = readAutomations(dataDir);
+ if (tasks.some((item) => item.id === task.id)) throw new Error('自动化任务 ID 已存在,请使用新的 id');
+ if (tasks.length >= MAX_TASKS) throw new Error('自动化任务数量已达到上限');
+ writeAutomations(dataDir, [task].concat(tasks));
+ const result = { ok: true, requestId, taskId: task.id, importedAt: Date.now() };
+ atomicWriteText(resultFile, JSON.stringify(result, null, 2) + '\n');
+ fs.unlinkSync(inboxFile);
+ outcomes.push(result);
+ } catch (error) {
+ const result = { ok: false, requestId, error: String(error && error.message || error).slice(0, 500), rejectedAt: Date.now() };
+ try { atomicWriteText(resultFile, JSON.stringify(result, null, 2) + '\n'); } catch (_) {}
+ try { fs.unlinkSync(inboxFile); } catch (_) {}
+ outcomes.push(result);
+ }
+ }
+ return outcomes;
+}
+
+function locatorExpression(locator) {
+ const kind = String(locator.kind || 'css');
+ const value = String(locator.value || '');
+ const q = JSON.stringify(value);
+ if (kind === 'xpath') return `document.evaluate(${q},document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue`;
+ if (kind === 'text') return `Array.from(document.querySelectorAll('button,a,[role="button"],input,textarea,[contenteditable="true"]')).find(e=>(e.innerText||e.textContent||e.value||'').trim().includes(${q}))`;
+ if (kind === 'ariaLabel') return `document.querySelector('[aria-label="'+${q}+'"]')`;
+ if (kind === 'placeholder') return `document.querySelector('[placeholder="'+${q}+'"]')`;
+ if (kind === 'role') return `document.querySelector('[role="'+${q}+'"]')`;
+ if (kind === 'attribute') return `document.querySelector('['+${q}+']')`;
+ if (kind === 'coordinates') return 'null';
+ return `document.querySelector(${q})`;
+}
+
+async function executeTask(taskInput, options = {}) {
+ const task = validateTask(taskInput);
+ if (!isTaskCompatible(task)) throw new Error('任务与当前 WorkDaddy 不兼容,请升级或使用适配版本');
+ const ctx = { task, account: options.event && options.event.account ? clone(options.event.account) : null, event: clone(options.event) || null, vars: clone(task.variables) || {}, response: null, step: {}, state: {}, now: new Date().toISOString() };
+ if (!ctx.account && options.currentAccount) ctx.account = await options.currentAccount();
+ if (ctx.event) ctx.vars.event = clone(ctx.event);
+ if (ctx.account) ctx.vars.account = clone(ctx.account);
+ const getState = options.getState || (async () => undefined);
+ const setState = options.setState || (async () => {});
+ const log = typeof options.log === 'function' ? options.log : () => {};
+ const isCancelled = typeof options.isCancelled === 'function' ? options.isCancelled : () => false;
+ const assertActive = () => { if (isCancelled()) throw new Error('任务已停止'); };
+ const wait = async ms => { let remaining = ms; do { assertActive(); const chunk = Math.min(100, Math.max(0,remaining)); await new Promise(r => setTimeout(r,chunk)); remaining -= chunk; } while(remaining>0); assertActive(); };
+ const BREAK = Symbol('break');
+ let loopDepth = 0;
+ const withLoop = async fn => { loopDepth++; try { return await fn(); } finally { loopDepth--; } };
+ let stepSerial = 0;
+ const runSteps = async (steps) => {
+ let last;
+ for (const step of steps) {
+ if (isCancelled()) throw new Error('任务已停止');
+ const serial = ++stepSerial;
+ const op = String(step && step.op || '');
+ log('step:start:' + serial + ':' + op);
+ try {
+ last = await runStep(step);
+ if (step.saveAs) ctx.vars[String(step.saveAs)] = last;
+ log('step:complete:' + serial + ':' + op);
+ } catch (error) {
+ log('step:error:' + serial + ':' + op + ':' + String(error && error.message || error).slice(0, 300));
+ throw error;
+ }
+ ctx.step = last == null ? {} : last;
+ }
+ return last;
+ };
+ const runStep = async (step) => {
+ const op = String(step.op || '');
+ if (op === 'logic.sequence') return runSteps(step.steps || []);
+ if (op === 'logic.delay' || op === 'dom.wait' && step.seconds != null && !step.until && !step.locator) {
+ const ms = Math.min(300000, Math.max(0, Number(step.ms != null ? step.ms : Number(step.seconds || 0) * 1000) || 0));
+ await wait(ms);
+ return { ok: true, waitedMs: ms };
+ }
+ if (op === 'logic.if') {
+ const c = step.condition || {};
+ const ok = compare(resolveValue(c.left, ctx), c.operator || 'truthy', resolveValue(c.right, ctx));
+ return { ok, branch: ok ? 'then' : 'else', result: await runSteps(ok ? (step.then || []) : (step.else || [])) };
+ }
+ if (op === 'logic.switch') {
+ const value = resolveValue(step.value, ctx);
+ const key = String(value == null ? '' : value);
+ const cases = step.cases && typeof step.cases === 'object' ? step.cases : {};
+ const matched = Object.prototype.hasOwnProperty.call(cases, key);
+ return { ok: true, key, matched, result: await runSteps(matched ? cases[key] : (step.default || [])) };
+ }
+ if (op === 'vars.set') { const key = String(step.key || ''); if (!/^[A-Za-z_][\w-]{0,79}$/.test(key) || ['__proto__','constructor','prototype'].includes(key)) throw new Error('变量名无效'); return (ctx.vars[key] = resolveValue(step.value, ctx)); }
+ if (op === 'logic.break') { if (!loopDepth) throw new Error('break 只能用于循环'); throw BREAK; }
+ if (op === 'logic.waitUntil') {
+ const end = Date.now() + Math.min(300000, Math.max(100, Number(step.timeoutMs) || 10000));
+ do {
+ await runSteps(step.steps || []);
+ const c = step.condition || {};
+ if (compare(resolveValue(c.left,ctx), c.operator || 'truthy', resolveValue(c.right,ctx))) return {ok:true};
+ if (Date.now() >= end) throw new Error('等待条件超时');
+ await wait(Math.min(end-Date.now(), Math.max(100, Number(step.intervalMs)||250)));
+ } while (true);
+ }
+ if (op === 'logic.repeat' || op === 'logic.forEach') {
+ const items = op === 'logic.repeat' ? Array.from({length:Math.min(100,Math.max(0,Number(resolveValue(step.times,ctx))||0))},(_,i)=>i) : resolveValue(step.items,ctx);
+ if (!Array.isArray(items) || items.length>1000) throw new Error('循环需要最多 1000 项的数组');
+ const previous = {item:ctx.vars.item,index:ctx.vars.index}, results=[];
+ try { await withLoop(async()=>{ for(let i=0;i<items.length;i++){ctx.vars.item=items[i];ctx.vars.index=i;results.push(await runSteps(step.steps||[]));} }); }
+ catch(e){if(e!==BREAK)throw e;} finally {Object.assign(ctx.vars,previous);}
+ return {ok:true,count:results.length,results};
+ }
+ if (op === 'logic.retry') {
+ const times = Math.min(10, Math.max(1, Number(step.times) || 1));
+ let error;
+ for (let attempt = 1; attempt <= times; attempt++) {
+ try { return await runSteps(step.steps || []); } catch (e) { if (e === BREAK) throw e; assertActive(); error = e; if (attempt < times) await wait(Math.min(60000, (Number(step.delayMs) || 500) * Math.pow(Math.max(1,Number(step.backoff)||1),attempt-1))); }
+ }
+ throw error;
+ }
+ if (op === 'logic.catch') {
+ try {
+ return { ok: true, result: await runSteps(step.steps || []) };
+ } catch (error) {
+ if (error === BREAK) throw error; assertActive();
+ ctx.vars.error = { message: String(error && error.message || error) };
+ return { ok: false, error: ctx.vars.error.message, result: await runSteps(step.onError || []) };
+ }
+ }
+ if (op === 'account.list') return options.listAccounts ? options.listAccounts() : [];
+ if (op === 'account.getPrimary') return options.primaryAccount ? options.primaryAccount() : null;
+ if (op === 'account.getCurrent') { ctx.account = options.currentAccount ? await options.currentAccount() : null; ctx.vars.account = ctx.account; return ctx.account; }
+ if (op === 'account.forEach') {
+ const all = typeof options.listAccounts === 'function' ? await options.listAccounts() : [];
+ const wanted = step.accounts === 'all' || !step.accounts ? all : all.filter((account) => (Array.isArray(step.accounts) ? step.accounts : [step.accounts]).includes(account.uid));
+ const results = [];
+ const physicallySwitch = step.switch === true || step.switchAccounts === true;
+ const original = physicallySwitch && typeof options.currentAccount === 'function' ? await options.currentAccount() : null;
+ if (physicallySwitch && (!original || !original.uid || typeof options.accountSwitch !== 'function')) throw new Error('账号切换循环不可用:无法确定当前账号或切换能力未启用');
+ let failure = null;
+ const previousAccount = ctx.account, previousVar = ctx.vars.account;
+ loopDepth++;
+ try {
+ for (const account of wanted) {
+ assertActive();
+ ctx.account = account;
+ ctx.vars.account = account;
+ if (physicallySwitch) await options.accountSwitch(account);
+ results.push(await runSteps(step.steps || []));
+ }
+ } catch (error) {
+ failure = error;
+ if (error !== BREAK) throw error;
+ } finally {
+ loopDepth--; ctx.account = previousAccount; ctx.vars.account = previousVar;
+ if (physicallySwitch && original && original.uid) {
+ try {
+ const active = typeof options.currentAccount === 'function' ? await options.currentAccount() : null;
+ if (!active || active.uid !== original.uid) await options.accountSwitch(original, { restore: true });
+ } catch (restoreError) {
+ if (!failure) throw restoreError;
+ log('account:restore:error:' + String(restoreError && restoreError.message || restoreError).slice(0, 300));
+ }
+ }
+ }
+ return { ok: true, count: results.length, results };
+ }
+ if (op === 'account.checkin') {
+ if (typeof options.accountCheckin !== 'function') throw new Error('账号签到能力不可用');
+ const account = ctx.account || (typeof options.currentAccount === 'function' ? await options.currentAccount() : null);
+ const result = await options.accountCheckin(account);
+ if (step.saveAs) ctx.vars[String(step.saveAs)] = result;
+ return result;
+ }
+ if (op === 'account.status') {
+ if (typeof options.accountStatus !== 'function') throw new Error('账号状态能力不可用');
+ const account = ctx.account || (typeof options.currentAccount === 'function' ? await options.currentAccount() : null);
+ const result = await options.accountStatus(account, step.fields || []);
+ ctx.accountStatus = result;
+ return result;
+ }
+ if (op === 'http.request' || op === 'http.requestAsAccount') {
+ if (typeof options.httpRequest !== 'function') throw new Error('HTTP 能力不可用');
+ const req = { method: String(step.method || 'GET').toUpperCase(), url: interpolate(step.url, ctx), query: resolveValue(step.query,ctx), headers: resolveValue(step.headers,ctx), body: resolveValue(step.body,ctx), timeoutMs: step.timeoutMs, isCancelled };
+ const account = op === 'http.requestAsAccount' ? ctx.account || (options.currentAccount ? await options.currentAccount() : null) : null;
+ if (op === 'http.requestAsAccount' && (!account || !account.uid)) throw new Error('没有可用账号');
+ const result = await options.httpRequest(req, account);
+ if (step.throwOnHttpError === true && !result.ok) throw new Error('HTTP ' + result.status);
+ ctx.response = result;
+ if (step.saveAs) ctx.vars[String(step.saveAs)] = result;
+ return result;
+ }
+ if (op === 'dom.find' || op === 'dom.click' || op === 'dom.type' || op === 'dom.clear' || op === 'dom.press' || op === 'dom.readText' || op === 'dom.readAttribute' || op === 'dom.wait') {
+ if (typeof options.domAction !== 'function') throw new Error('DOM 能力不可用');
+ const locator = resolveValue(step.locators || step.locator,ctx);
+ const result = await options.domAction(op, locator, { text: interpolate(step.text || '', ctx), attribute: step.attribute, key: step.key, timeoutMs: step.timeoutMs, seconds: step.seconds, until: resolveValue(step.until,ctx) });
+ if (step.saveAs) ctx.vars[String(step.saveAs)] = result;
+ return result;
+ }
+ if (op === 'session.create' || op === 'session.send') {
+ if (typeof options.sessionAction !== 'function') throw new Error('会话能力不可用');
+ const receipt = await options.sessionAction(op, resolveValue(step,ctx)); ctx.vars.session = receipt; return receipt;
+ }
+ if (op === 'session.wait') { if (typeof options.sessionAction !== 'function') throw new Error('会话能力不可用'); return options.sessionAction(op, {...resolveValue(step,ctx),receipt:resolveValue(step.receipt,ctx)||ctx.vars.session}); }
+ if (op === 'session.sendCurrent') {
+ if (typeof options.sessionSendCurrent !== 'function') throw new Error('当前会话发送能力不可用');
+ return options.sessionSendCurrent(interpolate(step.message || '', ctx));
+ }
+ if (op === 'session.waitReply') {
+ if (typeof options.sessionWaitReply !== 'function') throw new Error('会话回复监听能力不可用');
+ return options.sessionWaitReply({ timeoutMs: step.timeoutMs, contains: interpolate(step.contains || '', ctx) });
+ }
+ if (op === 'state.get') { const result = await getState(step.scope || 'task', ctx.account && ctx.account.uid, String(step.key || '')); if (step.saveAs) ctx.vars[String(step.saveAs)] = result; return result; }
+ if (op === 'state.set' || op === 'state.checkpoint') { const value = resolveValue(step.value, ctx); await setState(step.scope || 'task', ctx.account && ctx.account.uid, String(step.key || ''), value); return { ok: true, value }; }
+ if (op === 'notify.toast') {
+ if (typeof options.notifyToast !== 'function') throw new Error('通知能力不可用');
+ const detail = normalizeToastOptions({ ...step, id: step.id == null ? undefined : interpolate(step.id, ctx) });
+ const result = await options.notifyToast(detail.level, interpolate(step.message || '', ctx), detail);
+ if (step.saveAs) ctx.vars[String(step.saveAs)] = result;
+ return result || { ok: true };
+ }
+ if (op === 'notify.dismiss') {
+ if (typeof options.dismissToast !== 'function') throw new Error('关闭通知能力不可用');
+ const detail = normalizeToastOptions({ id: interpolate(step.id || '', ctx) }, true);
+ return options.dismissToast(detail.id);
+ }
+ if (op === 'notify.afterAllTasks') {
+ if (typeof options.completionReport !== 'function') throw new Error('完成汇报能力不可用');
+ return options.completionReport({ timeoutMs: step.timeoutMs });
+ }
+ if (op === 'notify.session') { if (typeof options.notifySession !== 'function') throw new Error('会话通知能力不可用'); return options.notifySession(interpolate(step.message || '', ctx), ctx.account); }
+ if (op === 'logic.assert') { const c = step.condition || {}; if (!compare(resolveValue(c.left, ctx), c.operator || 'truthy', resolveValue(c.right, ctx))) throw new Error(String(step.message || '任务断言失败')); return { ok: true }; }
+ throw new Error('不支持的能力: ' + op);
+ };
+ log('task:start:' + task.id);
+ try {
+ const result = await runSteps(task.steps);
+ if (task.onSuccess.length) await runSteps(task.onSuccess);
+ log('task:complete:' + task.id);
+ return { ok: true, result, context: { account: ctx.account ? { uid: ctx.account.uid, nickname: ctx.account.nickname } : null, vars: ctx.vars } };
+ } catch (error) {
+ ctx.vars.error = { message: String(error && error.message || error) };
+ if (task.onFailure.length) {
+ try { await runSteps(task.onFailure); } catch (handlerError) { log('task:onFailure:' + String(handlerError && handlerError.message || handlerError)); }
+ }
+ throw error;
+ }
+}
+
+module.exports = {
+ isSupportedTaskSchema,
+ isTaskCompatible,
+ configureAutomationRuntime,
+ canManuallyRunTask,
+ taskMatchesEvent,
+ createScheduleTicker,
+ validateSchedule,
+ taskNeedsPanelClosed,
+ taskIsPassiveCleanup,
+ installBuiltinTask,
+ SCHEMA_VERSION,
+ CAPABILITIES,
+ SUPPORTED_OPS,
+ AGENT_EXAMPLES,
+ capabilityText,
+ agentBridgePaths,
+ ensureAgentBridge,
+ createAgentRequest,
+ importAgentInbox,
+ storePath,
+ readAutomations,
+ writeAutomations,
+ normalizeTask,
+ validateTask,
+ executeTask,
+};
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index 07ebb5d..76992b7 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -56,9 +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 token-refresh.js session-db.js secure-transfer.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-usage-store.js growth-active.js atomic-file-write.js ui-port.js checkin-result.js lib.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
+for f in daemon.js toast-runtime.js toast-options.js primary-account.js completion-report.js automation-runtime.js automation-packages.js automation-compatibility.js automation-transfer.js automation-zip.js automation.js automation-picker.js token-refresh.js session-db.js secure-transfer.js windows-process-boundary.js workbuddy-compat.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-usage-store.js growth-active.js atomic-file-write.js ui-port.js checkin-result.js lib.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"
done
+# Presets are runtime source, independent of the reusable wallpaper/theme shell.
+mkdir -p "$APP/Contents/Resources/scripts/builtin/automations"
+cp scripts/builtin/automations/*.json "$APP/Contents/Resources/scripts/builtin/automations/"
if [ -f "scripts/picker-internal.js" ]; then
cp "scripts/picker-internal.js" "$APP/Contents/Resources/scripts/picker-internal.js"
chmod 644 "$APP/Contents/Resources/scripts/picker-internal.js"
@@ -80,6 +83,8 @@ chmod 755 "$APP/Contents/Resources/scripts/daemon.js" \
"$APP/Contents/Resources/scripts/uninstall.sh" \
"$APP/Contents/Resources/scripts/apply-update.sh"
chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \
+ "$APP/Contents/Resources/scripts/automation.js" \
+ "$APP/Contents/Resources/scripts/automation-picker.js" \
"$APP/Contents/Resources/scripts/token-refresh.js" \
"$APP/Contents/Resources/scripts/workbuddy-target.js" \
"$APP/Contents/Resources/scripts/secure-transfer.js" \
diff --git a/scripts/build-win-zip.sh b/scripts/build-win-zip.sh
index 3cb6ca8..fef4ed3 100644
--- a/scripts/build-win-zip.sh
+++ b/scripts/build-win-zip.sh
@@ -149,6 +149,9 @@ cp -R scripts "$STAGE/scripts"
rm -rf "$STAGE/scripts/builtin"
mkdir -p "$STAGE/scripts/builtin"
cp -R "$BUILTIN_SRC/." "$STAGE/scripts/builtin/"
+# The asset fallback may be an older app shell; always use current task presets.
+mkdir -p "$STAGE/scripts/builtin/automations"
+cp scripts/builtin/automations/*.json "$STAGE/scripts/builtin/automations/"
if [ -f "$WALLPAPER_OVERRIDE" ]; then
mkdir -p "$STAGE/scripts/builtin/wallpapers" "$STAGE/scripts/builtin/nebula"
cp "$WALLPAPER_OVERRIDE" "$STAGE/scripts/builtin/wallpapers/wallpaper-06.webp"
diff --git a/scripts/builtin/automations/close-buddy-popups.json b/scripts/builtin/automations/close-buddy-popups.json
new file mode 100644
index 0000000..6565da4
--- /dev/null
+++ b/scripts/builtin/automations/close-buddy-popups.json
@@ -0,0 +1,126 @@
+{
+ "schemaVersion": 1,
+ "id": "buddy-fuel-station-close-on-account-switch",
+ "name": "页面就绪后自动关闭首页弹窗",
+ "description": "页面就绪后立即检查三类弹窗,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。",
+ "enabled": true,
+ "trigger": {
+ "type": "pageReady",
+ "types": [
+ "pageReady"
+ ],
+ "oncePerNavigation": true,
+ "restartOnNavigation": true
+ },
+ "schedule": {
+ "type": "manual"
+ },
+ "variables": {},
+ "steps": [
+ {
+ "op": "logic.repeat",
+ "times": 100,
+ "steps": [
+ {
+ "op": "logic.catch",
+ "steps": [
+ {
+ "op": "dom.click",
+ "locator": {
+ "kind": "css",
+ "value": "#fuel-compact-close",
+ "visible": true
+ }
+ },
+ {
+ "op": "dom.wait",
+ "locator": {
+ "kind": "css",
+ "value": "#fuel-compact-close",
+ "visible": true
+ },
+ "until": {
+ "state": "hidden"
+ },
+ "timeoutMs": 750
+ },
+ {
+ "op": "notify.toast",
+ "level": "success",
+ "message": "识别到 Buddy 加油站弹窗,已关闭"
+ }
+ ],
+ "onError": []
+ },
+ {
+ "op": "logic.catch",
+ "steps": [
+ {
+ "op": "dom.click",
+ "locator": {
+ "kind": "css",
+ "value": "button.wb-related-playbooks__dismiss-today",
+ "visible": true
+ }
+ },
+ {
+ "op": "dom.wait",
+ "locator": {
+ "kind": "css",
+ "value": "button.wb-related-playbooks__dismiss-today",
+ "visible": true
+ },
+ "until": {
+ "state": "hidden"
+ },
+ "timeoutMs": 750
+ },
+ {
+ "op": "notify.toast",
+ "level": "success",
+ "message": "已关闭相关玩法推荐,今日不再展示"
+ }
+ ],
+ "onError": []
+ },
+ {
+ "op": "logic.catch",
+ "steps": [
+ {
+ "op": "dom.click",
+ "locator": {
+ "kind": "css",
+ "value": "button.activity-bubble__close",
+ "visible": true
+ }
+ },
+ {
+ "op": "dom.wait",
+ "locator": {
+ "kind": "css",
+ "value": "button.activity-bubble__close",
+ "visible": true
+ },
+ "until": {
+ "state": "hidden"
+ },
+ "timeoutMs": 750
+ },
+ {
+ "op": "notify.toast",
+ "level": "success",
+ "message": "已关闭首页活动弹窗"
+ }
+ ],
+ "onError": []
+ },
+ {
+ "op": "logic.delay",
+ "ms": 300
+ }
+ ]
+ }
+ ],
+ "onSuccess": [],
+ "onFailure": []
+}
diff --git a/scripts/builtin/automations/daily-account-checkin.json b/scripts/builtin/automations/daily-account-checkin.json
new file mode 100644
index 0000000..9bf4cb4
--- /dev/null
+++ b/scripts/builtin/automations/daily-account-checkin.json
@@ -0,0 +1,62 @@
+{
+ "schemaVersion": 1,
+ "id": "daily-account-checkin",
+ "name": "循环账号静默签到",
+ "description": "使用各账号 token 签到,不切换当前账号;跳过今日已签到账号。每小时、客户端加载和打开面板时检查。",
+ "enabled": true,
+ "trigger": {
+ "type": "clientLoaded",
+ "types": [
+ "clientLoaded",
+ "panelOpened"
+ ],
+ "oncePerNavigation": true
+ },
+ "schedule": {
+ "type": "interval",
+ "minutes": 60
+ },
+ "variables": {},
+ "steps": [
+ {
+ "op": "account.forEach",
+ "accounts": "all",
+ "switch": false,
+ "steps": [
+ {
+ "op": "logic.catch",
+ "steps": [
+ {
+ "op": "account.checkin",
+ "saveAs": "checkin"
+ },
+ {
+ "op": "logic.if",
+ "condition": {
+ "left": "{{vars.checkin.skipped}}",
+ "operator": "falsy"
+ },
+ "then": [
+ {
+ "op": "logic.delay",
+ "ms": 250
+ }
+ ]
+ },
+ {
+ "op": "logic.assert",
+ "condition": {
+ "left": "{{vars.checkin.ok}}",
+ "operator": "truthy"
+ },
+ "message": "该账号签到未成功,请检查登录状态或签到活动"
+ }
+ ],
+ "onError": []
+ }
+ ]
+ }
+ ],
+ "onSuccess": [],
+ "onFailure": []
+}
diff --git a/scripts/builtin/automations/keep-accounts-active.json b/scripts/builtin/automations/keep-accounts-active.json
new file mode 100644
index 0000000..d8edd51
--- /dev/null
+++ b/scripts/builtin/automations/keep-accounts-active.json
@@ -0,0 +1,53 @@
+{
+ "schemaVersion": 1,
+ "id": "keep-accounts-active-1-plus-1",
+ "name": "逐账号例行发送固定提示词消息",
+ "description": "依次切换所有账号,新建会话发送 1+1=,按会话回执等待回复完成,最后恢复开始时的账号。",
+ "enabled": true,
+ "trigger": {
+ "type": "manual",
+ "types": [],
+ "oncePerNavigation": true
+ },
+ "schedule": {
+ "type": "manual"
+ },
+ "variables": {},
+ "steps": [
+ {
+ "op": "account.forEach",
+ "accounts": "all",
+ "switch": true,
+ "steps": [
+ {
+ "op": "logic.delay",
+ "ms": 1500
+ },
+ {
+ "op": "session.create",
+ "message": "1+1=",
+ "saveAs": "receipt"
+ },
+ {
+ "op": "session.wait",
+ "timeoutMs": 180000,
+ "receipt": "{{vars.receipt}}"
+ }
+ ]
+ }
+ ],
+ "onSuccess": [
+ {
+ "op": "notify.toast",
+ "level": "success",
+ "message": "所有账号已按序处理完毕,已恢复开始时的账号"
+ }
+ ],
+ "onFailure": [
+ {
+ "op": "notify.toast",
+ "level": "error",
+ "message": "存在账号未完成处理,已尝试恢复开始时的账号"
+ }
+ ]
+}
diff --git a/scripts/completion-report.js b/scripts/completion-report.js
new file mode 100644
index 0000000..0f8b1bd
--- /dev/null
+++ b/scripts/completion-report.js
@@ -0,0 +1,88 @@
+'use strict';
+
+// Runs in the renderer through CDP. Read the official, account-scoped list rather
+// than the virtualized sidebar or visible stop button. This does not load/switch
+// sessions or mutate their state. The list requires userId (5.5 desktop adapter).
+async function probeAccountCompletion(userId) {
+ const compat = window.__wbsWorkBuddyCompat;
+ const found = compat && compat.findQueueAdapter(document);
+ const adapter = found && found.adapter;
+ const resource = adapter && adapter.sessionsResource;
+ if (!userId || !resource || typeof resource.list !== 'function') return { known: false };
+ const result = await resource.list({ userId });
+ if (!result || !Array.isArray(result.agents) || !result.agents.length || result.pagination && (result.pagination.hasNext || Number(result.pagination.total) > result.agents.length)) return { known: false };
+ const sessions = result.agents.map(record => ({ id: String(record.id || ''), status: String(record.status || '').toLowerCase(), busy: false }));
+ // Inspect mounted controllers too: list status can lag behind a just-started
+ // turn. Return only lifecycle flags; message contents never cross CDP here.
+ const controllers = compat.findConversationControllers(document) || [];
+ for (const controller of controllers) {
+ const id = String(controller.conversationId || '');
+ let record = sessions.find(item => item.id === id);
+ if (!record) { record = { id, status: '', busy: false }; sessions.push(record); }
+ try {
+ const state = controller.getSessionViewState();
+ const messages = controller.messageStore.getState();
+ record.busy = !!(state.isBusy || state.isRunActive || state.isTurnActive || state.isSending || state.isPending || state.isHydrating || messages.streamingRequestId || messages.streamingMessageId);
+ } catch (_) { return { known: false }; }
+ }
+ // Queue snapshots are optional for sessions with no persisted queue. A queued
+ // item, even paused, prevents claiming that every task has completed.
+ if (typeof resource.getConversationMessageQueue === 'function') {
+ let cursor = 0;
+ await Promise.all(Array.from({ length: Math.min(4, sessions.length) }, async () => {
+ while (cursor < sessions.length) {
+ const record = sessions[cursor++];
+ const queue = await resource.getConversationMessageQueue(record.id);
+ if (queue && (Array.isArray(queue.items) && queue.items.length || queue.inflightItemId || queue.runtime && (queue.runtime.inflightItemId || queue.runtime.pendingItemCount || queue.runtime.sendingItemCount))) record.busy = true;
+ }
+ }));
+ }
+ return { known: sessions.every(record => !!record.id && !!record.status), sessions };
+}
+
+async function runCompletionReport(options) {
+ const source = options.currentAccount();
+ const primary = options.primaryUid();
+ if (!primary) return { ok: true, skipped: true, reason: '未设置主账号' };
+ if (!source || !source.uid) throw new Error('当前没有登录账号');
+ if (primary === source.uid) return { ok: true, skipped: true, reason: '当前账号就是主账号' };
+ const now = options.now || Date.now;
+ const wait = options.wait || (ms => new Promise(resolve => setTimeout(resolve, ms)));
+ const started = now();
+ const timeout = Math.min(86400000, Math.max(1000, Number(options.timeoutMs) || 86400000));
+ const observed = new Set();
+ let idleSince = null;
+ const check = () => {
+ if (options.isCancelled && options.isCancelled()) throw new Error('用户停止任务');
+ if (options.primaryUid() !== primary || (options.currentAccount() || {}).uid !== source.uid) throw new Error('账号已变化,本次完成汇报已终止');
+ };
+ const done = new Set(['completed', 'done']);
+ const ended = new Set([...done, 'terminated', 'cancelled', 'canceled', 'failed', 'error', 'archived', 'deleted', 'killed']);
+ if (options.log) options.log('等待当前账号的全部 WorkBuddy 会话完成(待确认和队列未清空时继续等待)');
+ while (now() - started < timeout) {
+ check();
+ const snapshot = await options.snapshot(source.uid);
+ check();
+ if (!snapshot || !snapshot.known || !Array.isArray(snapshot.sessions) || !snapshot.sessions.length) throw new Error('无法确认全部会话状态,未发送汇报');
+ let busy = false;
+ const present = new Set();
+ for (const record of snapshot.sessions) {
+ present.add(record.id);
+ if (observed.has(record.id) && ended.has(record.status) && !done.has(record.status)) throw new Error('监听中的会话被停止或失败,未发送完成汇报');
+ if (record.busy || !ended.has(record.status)) { busy = true; observed.add(record.id); }
+ }
+ if ([...observed].some(id => !present.has(id))) throw new Error('监听中的会话状态丢失,未发送汇报');
+ if (busy) idleSince = null;
+ else if (idleSince === null) idleSince = now();
+ else if (now() - idleSince >= 2000) {
+ check();
+ const timestamp = new Date(now()).toLocaleString('zh-CN', { hour12: false });
+ const name = String(source.nickname || source.uid).replace(/[\r\n\t]/g, ' ').slice(0, 120);
+ const delivery = await options.send(primary, `${name} 账号于 ${timestamp} 完成所有任务`);
+ return { ok: true, conversationId: delivery.conversationId };
+ }
+ await wait(1000);
+ }
+ throw new Error('等待全部会话完成超时,未发送汇报');
+}
+module.exports = { runCompletionReport, probeAccountCompletion };
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 9aab1c7..eab493b 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -67,6 +67,7 @@ const {
listAuthRecords,
currentAuthFile,
resolveCurrentAuth,
+ resolveLogoutAuth,
defaultDataDir,
logFile,
ensureDirs,
@@ -122,7 +123,7 @@ const {
shouldRefreshAccessToken,
normalizeTimestamp: normalizeTokenTimestamp,
} = require('./token-refresh.js');
-const { fetchGrowthTodayActive, activateGrowthAccount } = require('./growth-active.js');
+const { fetchGrowthTodayActive, activateGrowthAccount, fetchGrowthStreak, createGrowthStreakCache } = require('./growth-active.js');
const {
captureException,
captureMessage,
@@ -143,9 +144,43 @@ const {
} = require('./secure-transfer.js');
const { replaceFileWithRetry } = require('./atomic-file-write.js');
const { parseUiPortState, profileUiPortCandidates } = require('./ui-port.js');
-
+const {
+ CAPABILITIES: AUTOMATION_CAPABILITIES,
+ AGENT_EXAMPLES: AUTOMATION_AGENT_EXAMPLES,
+ capabilityText: automationCapabilityText,
+ agentBridgePaths,
+ ensureAgentBridge,
+ createAgentRequest,
+ importAgentInbox,
+ readAutomations,
+ writeAutomations,
+ validateTask,
+ executeTask,
+ canManuallyRunTask,
+ taskMatchesEvent,
+ createScheduleTicker,
+ taskNeedsPanelClosed,
+ taskIsPassiveCleanup,
+ isSupportedTaskSchema,
+ isTaskCompatible,
+ configureAutomationRuntime,
+ installBuiltinTask,
+} = require('./automation.js');
+
+const { assertAccountRequestUrl, createTaskState, cancellableWait, createRendererGate, probeSessionReceipt, receiptComplete } = require('./automation-runtime.js');
+const acquireAutomationRenderer = createRendererGate();
+const acquireAutomationInput = createRendererGate();
+let automationInputActive = false;
+
+const { previewPackage, PACKAGE_FORMAT_VERSION } = require('./automation-packages.js');
+const { exportTasks, previewImport, importTasks, readTransferBody } = require('./automation-transfer.js');
+
+const { createAutomationNotifier } = require('./toast-options.js');
+const { runCompletionReport, probeAccountCompletion } = require('./completion-report.js');
+const { createPrimaryAccountStore } = require('./primary-account.js');
const PROFILE = getProfile();
const DATA_DIR = defaultDataDir();
+const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.existsSync(accountBackupFile(uid)));
// 版本号:改动 daemon/inject/theme-patches/builtin 资产后递增,launcher 检测到运行中版本不一致会强制用 app 内置代码重启
// 0.6.6:品牌 HelloBuddy→WorkDaddy 期间版本号未递增,旧 HelloBuddy daemon 会被 launcher 误判为"同版本"而不重启,导致旧代码继续注入;递增后强制升级
// 0.6.7:新增「关于」tab(/api/about + __WBS_VERSION__ 注入);必须递增,否则旧 daemon 不重启、面板看不到关于页
@@ -279,8 +314,25 @@ const DATA_DIR = defaultDataDir();
// 类 UI 拒绝 isTrusted=false 的 click(),仅原生输入可触发;供自动批准等链路使用。
// 1.1.51:Rule1/Auto-Continue 完成标记由零宽字符改为 Markdown 引用定义 [wbs-reply-done]: #
// (零宽会被官方存储链路转义成字面 \u200b 显形);inject 完成检测同步兼容。
-const DAEMON_VERSION = '1.1.51';
-const DAEMON_BUILD_ID = 'release-1.1.51-20260906-rule1-markdown-marker';
+// 1.1.52:新增声明式自动化任务中心、任务执行器和 DOM/HTTP 基础能力路由。
+// 1.1.53:自动化复用内部 DOM 检查器,补齐可执行能力协议并扩宽面板与接口说明。
+// 1.1.54:修复接口协议弹窗宽度被通用样式覆盖,并补全 agent 使用的纯文本协议参考。
+// 1.1.55:自动化协议落盘到 profile 持久目录;新增受校验的 Agent 任务收件箱和示例任务创建入口。
+// 1.1.56:欢迎页 Agent 输入检测忽略 Slate 占位节点;自动化拾取器与私有 debug 拾取器完全隔离。
+// 1.1.57:自动化 DOM 能力支持开放 Shadow DOM;新增逐步骤运行日志和任务编辑弹窗。
+// 1.1.58:自动化页面加载和账号切换统一为 pageReady 生命周期触发。
+// 1.1.59:自动化日志支持按任务清除已结束运行记录。
+// 1.1.60:账号循环支持真实切换账号并在结束后恢复原账号。
+// 1.1.61:自动化发送复用官方发送按钮链路,避免仅输入未提交。
+// 1.1.62:自动化任务运行中显示停止按钮并可中断等待回复。
+// 1.1.63:快捷短语/自动化发送优先命中新版官方 cr-send-button,避免输入后未提交。
+// 1.1.64:发送按钮定位的国际化选择器与 daemon 保持一致,避免源码检查误判。
+// 1.1.65:自动化会话发送前确保进入新版 WorkBuddy 新建任务页。
+// 1.1.66:新版侧栏 tab 共用 conversation-list-tab-button-box,改用文字确认新建任务。
+// 1.1.67:项目页存在普通 composer 时仍强制定位并点击新建任务 tab。
+const DAEMON_VERSION = '1.2.4';
+const DAEMON_BUILD_ID = 'release-1.2.4-20260908-send-button-poll-200ms';
+configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
@@ -1525,6 +1577,8 @@ let manualInjectPromise = null; // launcher 超时重试时复用同一轮注入
let pendingReloadInjection = null; // 仅对 WorkDaddy 主动触发的页面重载做一次主 frame 早期注入
let mainFrameNavigationSerial = 0;
let suppressPageLoadInjectionForNavigation = 0;
+const automationEventKeys = new Set();
+let pendingAutomationAccountSwitch = null;
function settlePendingReloadInjection(pending, mounted) {
if (!pending || pendingReloadInjection !== pending || pending.settled) return;
@@ -1570,6 +1624,7 @@ function runPendingReloadInjection(reason, executionContextId) {
if (pendingReloadInjection !== pending || pending.settled) return;
pending.injecting = false;
if (info && info.mounted) {
+ restoreSavedTheme().catch((e) => log('[theme] 早期恢复失败: ' + e.message));
settlePendingReloadInjection(pending, true);
return;
}
@@ -1689,6 +1744,30 @@ async function cleanupForeignInjectedTarget(target) {
});
}
+function cdpFocusDiagnostics(label, extra = {}) {
+ if (!cdp.connected || !cdp.ws || cdp.ws.readyState !== 1) return Promise.resolve(null);
+ const expression = `(function(){try{
+ var a=document.activeElement;
+ var r=a&&a.getBoundingClientRect?a.getBoundingClientRect():null;
+ return {href:location.href,title:document.title,readyState:document.readyState,viewport:{w:window.innerWidth,h:window.innerHeight,dpr:window.devicePixelRatio},active:a?{tag:a.tagName,id:a.id||'',cls:typeof a.className==='string'?a.className.slice(0,180):'',editable:a.isContentEditable===true||a.tagName==='TEXTAREA'||a.tagName==='INPUT',rect:r?{x:r.x,y:r.y,w:r.width,h:r.height}:null}:null,hasSelection:!!(window.getSelection&&!window.getSelection().isCollapsed)}
+ }catch(e){return {error:String(e)}}})()`;
+ return cdpSend('Runtime.evaluate', { expression, returnByValue: true }).then((r) => {
+ const data = r && r.result && r.result.value;
+ log('[cdp-focus-diagnostics] ' + label + ' ' + JSON.stringify({ targetUrl: cdp.targetUrl, targetTitle: cdp.targetTitle, extra, page: data }));
+ return data;
+ }).catch((e) => { log('[cdp-focus-diagnostics] ' + label + ' failed=' + e.message); return null; });
+}
+
+async function cdpMouseClick(source, x, y, extra = {}, options = {}) {
+ await cdpFocusDiagnostics('mouse-click:before', { source, x, y, ...extra });
+ log('[cdp-focus-diagnostics] mouse-click:dispatch ' + JSON.stringify({ source, x, y, extra, targetUrl: cdp.targetUrl, targetTitle: cdp.targetTitle }));
+ // 页面未产出绘制帧时,mouseMoved 的 ACK 可卡约 5 秒,期间坐标可能已过期。
+ // 明确定位的弹窗关闭按钮不依赖 hover,直接按下/松开即可。
+ if (!options.skipMove) await cdpSend('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y });
+ await cdpSend('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 });
+ await cdpSend('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 });
+}
+
function cdpSend(method, params = {}, _retry = 0) {
if (!cdp.ws || cdp.ws.readyState !== 1) return Promise.reject(new Error('CDP 未连接'));
const id = ++cdp.id;
@@ -1751,9 +1830,17 @@ async function connectCdp() {
setTimeout(() => scheduleBackup('cdp-connect'), 800);
setTimeout(() => {
injectWidget('connect').catch((e) => log(`[cdp] 注入失败: ${e.message}`));
+ // 清理可能残留的历史「运行期间隐藏面板」临时样式(1.1.73 及更早用 wbs-auto-hide-ui;
+ // 上次运行被中断/重启可能没清掉,会导致页面一直收不起面板的兄弟状态)。只删 tag,不误开面板。
+ automationClearStaleHideTag();
// 恢复已保存的主题(页面刷新/WorkBuddy 重启后 WorkBuddy 回到官方浅色,
// 这里重新应用,保证「WorkDaddy 主题=深色 / WorkBuddy 默认主题=浅色」在重启后仍生效)
restoreSavedTheme().catch((e) => log(`[theme] 恢复主题失败: ${e.message}`));
+ // 某些旧版 renderer 在 daemon 连接后不会再发送 loadEventFired;
+ // readyState 已完成时补发一次首屏生命周期事件,按导航序号去重。
+ cdpSend('Runtime.evaluate', { expression: 'document.readyState', returnByValue: true }).then((r) => {
+ if (r && r.result && r.result.value === 'complete') dispatchAutomationEvent('pageReady', { navigationSerial: mainFrameNavigationSerial, source: 'connect' });
+ }).catch(() => {});
}, 1200);
resolve(true);
};
@@ -1789,6 +1876,38 @@ async function connectCdp() {
});
}
+function dispatchAutomationEvent(type, detail = {}) {
+ const eventType = String(type || '').trim();
+ if (!['pageReady', 'pageLoaded', 'accountSwitched', 'panelOpened'].includes(eventType)) return;
+ const canonicalType = eventType === 'pageReady' ? 'pageReady' : eventType;
+ const key = canonicalType + ':' + String(detail.navigationSerial == null ? mainFrameNavigationSerial : detail.navigationSerial);
+ if (canonicalType === 'pageReady' && automationEventKeys.has(key)) return;
+ if (canonicalType === 'pageReady') {
+ automationEventKeys.add(key);
+ while (automationEventKeys.size > 40) automationEventKeys.delete(automationEventKeys.values().next().value);
+ }
+ const tasks = readAutomations(DATA_DIR).filter((task) => taskMatchesEvent(task, canonicalType, detail));
+ if (!tasks.length) return;
+ const account = detail.account || currentAccount();
+ tasks.forEach((task) => {
+ try {
+ const event = { type: canonicalType, navigationSerial: detail.navigationSerial == null ? mainFrameNavigationSerial : detail.navigationSerial, source: detail.source || 'cdp', account: account ? { uid: account.uid, nickname: account.nickname } : null };
+ const run = Array.from(automationRuns.values()).find((item) => item.taskId === task.id && item.status === 'running');
+ if (run) {
+ if (task.trigger.restartOnNavigation && run.navigationSerial !== event.navigationSerial) {
+ run.superseded = true;
+ run.pendingEvent = event;
+ }
+ return;
+ }
+ startAutomationRun(task, event);
+ log(`[automation] 生命周期 ${canonicalType} 已启动任务 ${task.id}`);
+ } catch (error) {
+ log(`[automation] 生命周期 ${canonicalType} 启动任务失败: ${error.message}`);
+ }
+ });
+}
+
function onCdpEvent(method, params) {
switch (method) {
case 'Network.requestWillBeSent': {
@@ -1833,6 +1952,7 @@ function onCdpEvent(method, params) {
}
case 'Page.loadEventFired': {
scheduleBackup('cdp-page-load');
+ const loadedNavigationSerial = mainFrameNavigationSerial;
if (pendingReloadInjection) {
pendingReloadInjection.loadFired = true;
runPendingReloadInjection('reload-page-load');
@@ -1846,6 +1966,12 @@ function onCdpEvent(method, params) {
}
// 页面刷新后 WorkBuddy 回到官方浅色,重新应用已保存主题(WorkDaddy=深色 / 默认=浅色)
restoreSavedTheme().catch((e) => log(`[theme] 页面刷新恢复主题失败: ${e.message}`));
+ const switchEvent = pendingAutomationAccountSwitch;
+ if (switchEvent) {
+ pendingAutomationAccountSwitch = null;
+ dispatchAutomationEvent('pageReady', { navigationSerial: loadedNavigationSerial, source: 'account-switch', account: switchEvent.account });
+ }
+ dispatchAutomationEvent('pageReady', { navigationSerial: loadedNavigationSerial, source: 'load' });
break;
}
case 'Page.frameNavigated': {
@@ -2413,10 +2539,10 @@ async function clickByText(text, { tag = null, exact = false } = {}) {
const found = r.result && r.result.value;
if (!found) throw new Error('未找到元素');
if (found.error) throw new Error('查找异常: ' + found.error);
+ // 记录点击前的页面焦点、视口和目标坐标;不改变点击行为。
+ await cdpFocusDiagnostics('clickByText:before-mouse', { text: String(text), tag, exact, found });
// 用 Input 事件模拟真实鼠标点击(trusted)
- await cdpSend('Input.dispatchMouseEvent', { type: 'mouseMoved', x: found.x, y: found.y });
- await cdpSend('Input.dispatchMouseEvent', { type: 'mousePressed', x: found.x, y: found.y, button: 'left', clickCount: 1 });
- await cdpSend('Input.dispatchMouseEvent', { type: 'mouseReleased', x: found.x, y: found.y, button: 'left', clickCount: 1 });
+ await cdpMouseClick('clickByText:' + String(text), found.x, found.y, { tag, exact, found });
return found;
}
@@ -2495,14 +2621,441 @@ async function waitPageLoaded(timeoutMs = 6000) {
const CHECKIN_CACHE_FILE = path.join(DATA_DIR, 'checkin-cache.json');
const CHECKIN_REQUEST_TIMEOUT_MS = 12000;
-const CHECKIN_QUEUE_DELAY_MS = 250;
-const CHECKIN_STARTUP_DELAY_MS = 30 * 1000;
-const CHECKIN_INTERVAL_MS = 60 * 60 * 1000;
-let claimInFlight = false;
-let checkinState = { running: false, total: 0, done: 0, startedAt: 0, finishedAt: 0 };
+// 声明式自动化任务:任务 JSON 只保存步骤,不保存账号 Token;运行时按账号上下文
+// 读取受管备份并把凭据限制在一次 HTTP 请求内。第三方代码执行不在此模块范围内。
+const growthStreakCache = createGrowthStreakCache(async (uid) => {
+ const raw = JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'));
+ const auth = raw && raw.auth || {};
+ return fetchGrowthStreak(auth.accessToken || auth.access_token || auth.token, { apiHost: PROFILE.apiHost });
+});
+const automationRuns = new Map();
+let completionReportRunning = false;
+const automationStateFile = () => path.join(DATA_DIR, 'automation-state.json');
+function readAutomationState() {
+ try { const value = JSON.parse(fs.readFileSync(automationStateFile(), 'utf8')); return value && typeof value === 'object' ? value : {}; } catch (_) { return {}; }
+}
+function writeAutomationState(value) {
+ const file = automationStateFile();
+ const tmp = file + '.tmp-' + process.pid;
+ fs.writeFileSync(tmp, JSON.stringify(value || {}, null, 2) + '\n', { mode: 0o600 });
+ fs.renameSync(tmp, file);
+}
+async function automationAccountStatus(account, fields) {
+ const target = account || currentAccount();
+ if (!target || !target.uid) throw new Error('没有可用账号');
+ const file = accountBackupFile(target.uid);
+ if (!fs.existsSync(file)) throw new Error('账号备份不存在');
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
+ const auth = raw && raw.auth && typeof raw.auth === 'object' ? raw.auth : {};
+ const result = { uid: target.uid, isPrimary: primaryAccountStore.get() === target.uid, checkin: {}, activity: {}, credits: {} };
+ const wanted = Array.isArray(fields) && fields.length ? fields : ['checkin.today', 'activity.today'];
+ if (wanted.includes('checkin.today')) {
+ const today = todayStr();
+ let mark = null;
+ try { mark = await CREDIT_USAGE_STORE.getDailyCheckin(target.uid, today); } catch (_) {}
+ const cache = loadCheckinCache();
+ const hit = mark || cache[target.uid];
+ result.checkin = { today: !!(hit && hit.date === today && hit.ok && (hit.verified === true || classifyCheckinResult({ httpOk: true, code: hit.code, message: hit.message }).ok)), verified: !!(hit && hit.date === today && hit.verified === true), source: mark ? 'sqlite' : 'cache' };
+ }
+ if (wanted.includes('activity.today')) {
+ const token = auth.accessToken || auth.access_token || auth.token;
+ if (!token) throw new Error('备份中无 accessToken');
+ result.activity = Object.assign({ source: 'server' }, await fetchGrowthTodayActive(token, { apiHost: PROFILE.apiHost }));
+ }
+ if (wanted.includes('activity.streak')) {
+ const streak = await growthStreakCache.get(target.uid);
+ result.activity.streak = { days: Number.isFinite(streak && streak.days) ? streak.days : null, status: streak && streak.status || 'unavailable' };
+ }
+ if (wanted.includes('credits')) {
+ const token = auth.accessToken || auth.access_token || auth.token;
+ if (!token) throw new Error('备份中无 accessToken');
+ const credits = await fetchCredits(token, raw.account || {});
+ result.credits = { total: credits.credits, unlimited: !!credits.unlimited, cycleResetTime: credits.cycleResetTime || null };
+ }
+ return result;
+}
+function automationDeepLocatorExpression(locator) {
+ if (Array.isArray(locator)) return `(function(){var candidates=[${locator.map(automationDeepLocatorExpression).join(',')}].filter(Boolean);return candidates.find(function(el){var r=el.getBoundingClientRect();var cs=el.ownerDocument.defaultView.getComputedStyle(el);return r.width>0&&r.height>0&&cs.display!=='none'&&cs.visibility!=='hidden'})||candidates[0]||null})()`;
+ const l = locator && typeof locator === 'object' ? locator : {};
+ const kind = JSON.stringify(String(l.kind || 'css'));
+ const value = JSON.stringify(String(l.value || ''));
+ return `(function(){
+ var kind=${kind};var value=${value};var preferVisible=${l.visible === true};var roots=[document];var seen=new Set(roots);
+ for(var ri=0;ri<roots.length&&ri<200;ri++){
+ var root=roots[ri];var elements=[];try{elements=Array.from(root.querySelectorAll('*'))}catch(_){}
+ for(var ei=0;ei<elements.length;ei++){
+ var element=elements[ei];
+ if(element.shadowRoot&&!seen.has(element.shadowRoot)){seen.add(element.shadowRoot);roots.push(element.shadowRoot)}
+ if(element.tagName==='IFRAME'){try{var frameDocument=element.contentDocument;if(frameDocument&&!seen.has(frameDocument)){seen.add(frameDocument);roots.push(frameDocument)}}catch(_){}}
+ }
+ }
+ function first(selector){var fallback=null;for(var i=0;i<roots.length;i++){try{
+ if(!preferVisible){var found=roots[i].querySelector(selector);if(found)return found;continue}
+ var matches=roots[i].querySelectorAll(selector);
+ for(var j=0;j<matches.length;j++){var el=matches[j];if(!fallback)fallback=el;var r=el.getBoundingClientRect();var cs=getComputedStyle(el);if(r.width>0&&r.height>0&&cs.display!=='none'&&cs.visibility!=='hidden')return el}
+ }catch(_){}}return fallback}
+ function choose(matches){if(!preferVisible)return matches[0]||null;return matches.find(function(el){var r=el.getBoundingClientRect();var cs=el.ownerDocument.defaultView.getComputedStyle(el);return r.width>0&&r.height>0&&cs.display!=='none'&&cs.visibility!=='hidden'})||matches[0]||null}
+ function firstByAttribute(name){var matches=[];for(var i=0;i<roots.length;i++){var all=[];try{all=roots[i].querySelectorAll('['+name+']')}catch(_){}for(var j=0;j<all.length;j++){if((all[j].getAttribute(name)||'')===value)matches.push(all[j])}}return choose(matches)}
+ if(kind==='xpath'){var matches=[];for(var xi=0;xi<roots.length;xi++){try{var doc=roots[xi].ownerDocument||roots[xi];var match=doc.evaluate(value,roots[xi],null,7,null);for(var xj=0;xj<match.snapshotLength;xj++)matches.push(match.snapshotItem(xj))}catch(_){}}return choose(matches)}
+ if(kind==='text'){var matches=[];for(var ti=0;ti<roots.length;ti++){var candidates=[];try{candidates=roots[ti].querySelectorAll('button,a,[role="button"],input,textarea,[contenteditable="true"]')}catch(_){}for(var ci=0;ci<candidates.length;ci++){var text=(candidates[ci].innerText||candidates[ci].textContent||candidates[ci].value||'').trim();if(text.includes(value))matches.push(candidates[ci])}}return choose(matches)}
+ if(kind==='ariaLabel')return firstByAttribute('aria-label');
+ if(kind==='placeholder')return firstByAttribute('placeholder');
+ if(kind==='role')return firstByAttribute('role');
+ if(kind==='attribute')return first('['+value+']');
+ return first(value);
+ })()`;
+}
+async function automationDomAction(op, locator, detail) {
+ const assertActive = () => { if (detail && detail.isCancelled && detail.isCancelled()) throw new Error('任务已停止'); };
+ assertActive();
+ if (!cdp.connected) throw new Error('CDP 未连接');
+ const expr = automationDeepLocatorExpression(locator);
+ const attribute = JSON.stringify(String(detail && (detail.attribute || detail.until && detail.until.attribute) || ''));
+ const inspect = `(function(){var el=${expr};if(!el)return null;var r=el.getBoundingClientRect();var cs=getComputedStyle(el);var blocked=false;
+ if(${op === 'dom.click' || op === 'dom.wait'}){var root=el.getRootNode();var hit=root.elementFromPoint(r.x+r.width/2,r.y+r.height/2);blocked=!hit||!(hit===el||el.contains(hit))||el.disabled===true||el.getAttribute('aria-disabled')==='true';}
+ return {inFrame:el.ownerDocument!==document,editable:el.isContentEditable||/^(INPUT|TEXTAREA)$/.test(el.tagName),x:r.x,y:r.y,w:r.width,h:r.height,blocked:blocked,visible:cs.display!=='none'&&cs.visibility!=='hidden'&&r.width>0&&r.height>0,text:(el.innerText||el.textContent||el.value||'').trim().slice(0,100000),value:el.value||'',attribute:el.getAttribute(${attribute})}})()`;
+ const read = async () => {
+ assertActive();
+ const r = await cdpSend('Runtime.evaluate', { expression: inspect, returnByValue: true });
+ assertActive();
+ if (r && r.exceptionDetails) throw new Error('DOM locator evaluation failed: ' + String(r.exceptionDetails.text || 'unknown error'));
+ return r && r.result && r.result.value;
+ };
+ if (op === 'dom.wait' && detail && detail.until) {
+ const timeout = Math.min(300000, Math.max(100, Number(detail.timeoutMs) || 10000)); const started = Date.now();
+ while (Date.now() - started < timeout) {
+ const item = await read();
+ // 关闭后节点通常直接移除;不存在同样满足 hidden,不能一直等到超时。
+ const until = detail.until;
+ const matched = until.state === 'hidden' ? !item || !item.visible : until.state === 'attached' ? !!item : until.state === 'detached' ? !item : !!item && item.visible &&
+ (until.state !== 'clickable' || !item.blocked) && (until.text == null || item.text.includes(String(until.text))) && (until.attribute == null || item.attribute === String(until.value == null ? '' : until.value));
+ if (matched) return item || { visible: false };
+ await cancellableWait(100, detail.isCancelled);
+ }
+ throw new Error('等待页面元素超时');
+ }
+ if (op === 'dom.wait') { await new Promise((resolve) => setTimeout(resolve, Math.min(300000, Math.max(0, Number(detail && detail.seconds) * 1000 || 0)))); return { ok: true }; }
+ const found = await read();
+ if (!found) throw new Error('未找到页面元素');
+ if (op === 'dom.find') return found;
+ if (op === 'dom.readText') return found.text;
+ if (op === 'dom.readAttribute') return found.attribute;
+ if (found.inFrame) throw new Error('暂不支持 iframe 内的输入或点击,请使用主页面定位器');
+ if (op === 'dom.clear' && !found.editable) throw new Error('目标不是可编辑输入框');
+ if (!found.visible) throw new Error('页面元素不可见');
+ if (op === 'dom.click') {
+ assertActive();
+ if (found.blocked) throw new Error('页面元素被遮挡或禁用,稍后重试');
+ const x = found.x + found.w / 2; const y = found.y + found.h / 2;
+ await cdpMouseClick('dom.click:' + String(locator && locator.value || ''), x, y, { op, found }, { skipMove: locator && locator.visible === true });
+ return found;
+ }
+ const focus = `(function(){var el=${expr};if(!el)return false;el.focus();return true})()`;
+ const focused = await cdpSend('Runtime.evaluate', { expression: focus, returnByValue: true });
+ assertActive();
+ if (!(focused && focused.result && focused.result.value)) throw new Error('无法聚焦页面元素');
+ if (op === 'dom.clear') {
+ // Chromium editing commands support input, textarea and rich contenteditable,
+ // without synthesizing macOS menu shortcuts (the historical About-window bug).
+ await cdpSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'a', commands: ['selectAll'] });
+ assertActive();
+ await cdpSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Backspace', code: 'Backspace' });
+ await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace' });
+ const empty = await read();
+ if (empty && (empty.value || empty.text)) throw new Error('输入框未确认清空');
+ }
+ if (op === 'dom.type') await cdpSend('Input.insertText', { text: String(detail && detail.text || '') });
+ if (op === 'dom.press') { const key = String(detail && detail.key || 'Enter'); await cdpSend('Input.dispatchKeyEvent', { type: 'keyDown', key, code: key }); await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp', key, code: key }); }
+ return { ok: true };
+}
+async function automationHttpRequest(request, account) {
+ const url = new URL(String(request.url || ''));
+ if (!/^https?:$/.test(url.protocol)) throw new Error('HTTP URL 仅支持 http(s)');
+ if (request.query && typeof request.query === 'object') Object.keys(request.query).forEach((key) => url.searchParams.set(key, String(request.query[key])));
+ const headers = {};
+ if (request.headers && typeof request.headers === 'object') Object.keys(request.headers).slice(0, 40).forEach((key) => { if (!/^(authorization|cookie|proxy-authorization)$/i.test(key)) headers[key] = String(request.headers[key]).slice(0, 2000); });
+ if (account && account.uid) {
+ assertAccountRequestUrl(url, PROFILE.apiHost);
+ const raw = JSON.parse(fs.readFileSync(accountBackupFile(account.uid), 'utf8')); const auth = raw && raw.auth && typeof raw.auth === 'object' ? raw.auth : {};
+ const token = auth.accessToken || auth.access_token || auth.token; if (!token) throw new Error('账号没有 accessToken'); headers.authorization = 'Bearer ' + token;
+ }
+ if (request.isCancelled && request.isCancelled()) throw new Error('任务已停止');
+ if (request.body && typeof request.body === 'object' && !Object.keys(headers).some(k => k.toLowerCase() === 'content-type')) headers['content-type'] = 'application/json';
+ const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), Math.min(60000, Math.max(500, Number(request.timeoutMs) || 15000)));
+ const cancelTimer = setInterval(() => { if (request.isCancelled && request.isCancelled()) controller.abort(); }, 100);
+ try {
+ const response = await fetch(url, { method: request.method || 'GET', headers, body: request.body == null ? undefined : (typeof request.body === 'string' ? request.body : JSON.stringify(request.body)), signal: controller.signal, redirect: 'manual' });
+ let text = ''; const chunks = []; let size = 0;
+ if (response.body) { const reader = response.body.getReader(); try { while (true) { const part = await reader.read(); if (part.done) break; size += part.value.byteLength; if (size > 1024 * 1024) { await reader.cancel(); throw new Error('HTTP 响应超过 1 MiB'); } chunks.push(Buffer.from(part.value)); } } finally { reader.releaseLock(); } text = Buffer.concat(chunks).toString('utf8'); }
+ let jsonBody = null; try { jsonBody = text ? JSON.parse(text) : null; } catch (_) {}
+ return { ok: response.ok, status: response.status, headers: { 'content-type': response.headers.get('content-type') || '' }, text, json: jsonBody };
+ } catch (e) { if (request.isCancelled && request.isCancelled()) throw new Error('任务已停止'); if (e && e.name === 'AbortError') throw new Error('HTTP 请求超时'); throw new Error(e && e.message === 'HTTP 响应超过 1 MiB' ? e.message : 'HTTP 请求失败'); } finally { clearTimeout(timer); clearInterval(cancelTimer); }
+}
+function automationPublicRun(run) { return { id: run.id, taskId: run.taskId, status: run.status, phase: run.phase || 'executing', startedAt: run.startedAt, finishedAt: run.finishedAt || 0, error: run.error || '', logs: run.logs.slice(-80), result: run.result || null }; }
+
+// 自动化运行前收拢 WorkDaddy 面板「窗口」,避免其 contenteditable/悬浮层与 WorkBuddy 原生
+// composer 抢焦点或遮挡,导致任务把提示词键入到 WorkDaddy 面板输入框 / 点不到官方发送按钮
+// (用户实测:面板开着任务发不出去,关了才行)。
+// 实现:不注入 <style> 硬改 display(老板 09-07:旧法会连 FAB 一起藏 / 破坏面板 DOM 状态),
+// 而是 dispatch 事件让 inject 走「点关闭按钮」同一条 setOpen(false) —— 等价于点一次面板关闭。
+// 运行结束若运行前面板本是展开的,再走「点机器人按钮」同一条 setOpen(true) 恢复。全程可逆。
+function automationPanelSetInputActive(active) {
+ automationInputActive = !!active;
+ if (!cdp.connected) return active ? Promise.reject(new Error('CDP 未连接')) : Promise.resolve();
+ return cdpSend('Runtime.evaluate', {
+ expression: `window.__wbsAutomationInputActive=${!!active};${active ? "window.dispatchEvent(new CustomEvent('workdaddy:panel-open',{detail:{open:false,automation:true}}));" : ''}`,
+ returnByValue: false,
+ }).then((result) => {
+ if (result && result.exceptionDetails) throw new Error('无法关闭面板,请重试');
+ });
+}
+
+function automationPanelSetOpen(open) {
+ if (!cdp.connected) return Promise.resolve(false);
+ return cdpSend('Runtime.evaluate', {
+ expression: `window.dispatchEvent(new CustomEvent('workdaddy:panel-open',{detail:{open:${!!open},automation:true}}))`,
+ returnByValue: false,
+ }).then(() => true).catch(() => false);
+}
+// 读当前面板是否展开(.wbs-panel 是否带 .show,且视觉可见)
+function automationPanelIsOpen() {
+ if (!cdp.connected) return Promise.resolve(false);
+ return cdpSend('Runtime.evaluate', {
+ expression: `(function(){try{var p=document.querySelector('.wbs-root .wbs-panel');if(!p)return false;var r=p.getBoundingClientRect();return p.classList.contains('show')&&r.width>0&&r.height>0;}catch(e){return false}})()`,
+ returnByValue: true,
+ }).then((r) => !!(r && r.result && r.result.value)).catch(() => false);
+}
+// 清理历史遗留的「运行期间隐藏面板」临时 <style>(1.1.73 及更早版本用过 wbs-auto-hide-ui;
+// daemon 重启/运行中断可能残留,页面会一直面板不可见)。无 tag 时是 no-op,不影响面板开合状态。
+function automationClearStaleHideTag() {
+ if (!cdp.connected) return Promise.resolve();
+ return cdpSend('Runtime.evaluate', {
+ expression: `(function(){var h=document.getElementById('wbs-auto-hide-ui');if(h){h.remove();return true}return false})()`,
+ returnByValue: false,
+ }).catch(() => {});
+}
-function checkinSnapshot() {
- return Object.assign({}, checkinState, { running: !!claimInFlight });
+/** CDP 探测当前会话「最后一条完整 assistant 回复」:
+ * 用不可见完成标记(结尾零宽字符 / [wbs-reply-done] 行)判定回复是否真正结束,
+ * 不再依赖 5.5.3 已删除的 .cb-assistant-message。消息列表容器取 5.5.3 的
+ * .cr-message-list / .cr-conversation-timeline,assistant 块过滤 loading。
+ * 返回值 { lastText, lastDone, rowCount } */
+function automationMarkerProbeExpression() {
+ return '(function(){try{' +
+ 'function visible(e){if(!e)return false;var r=e.getBoundingClientRect();return r.width>0&&r.height>0}' +
+ 'function hasMarker(t){if(!t)return false;var ts=t.replace(/[ \\t\\r\\n\\f\\v\\u00A0]+$/,\'\');if(!ts)return false;' +
+ 'if(ts.slice(-3)===\'\\u200B\\u200B\\u2060\')return true;' +
+ 'if(/[\\u200B\\u200C\\u200D\\u2060\\uFEFF]$/.test(ts))return true;' +
+ 'if(/(^|\\n)\\s*\\[wbs-reply-done\\]:/im.test(ts))return true;return false}' +
+ 'var list=document.querySelector(\'.cr-message-list,.cr-conversation-timeline,.conversation-timeline\')||document;' +
+ 'var rows=[];try{rows=Array.from(list.querySelectorAll(\'[class*="assistant-message"],[class*="_assistantMessage_"]\')).filter(visible)}catch(e){}' +
+ 'var last=null;for(var i=rows.length-1;i>=0;i--){var c=typeof rows[i].className===\'string\'?rows[i].className:\'\';if(/loading/i.test(c))continue;' +
+ 'var t=\'\';try{t=(rows[i].innerText||rows[i].textContent||\'\').replace(/[\\s\\u00A0]+$/,\'\')}catch(e){continue}if(!t)continue;last={text:t};break}' +
+ 'return {lastText:last?last.text:\'\',lastDone:last?hasMarker(last.text):false,rowCount:rows.length}' +
+ '}catch(e){return {err:String(e&&e.message||e)}}})()';
+}
+
+async function automationNotifyToast(detail) {
+ if (!cdp.connected) throw new Error('WorkBuddy 未连接,无法显示通知');
+ const response = await cdpSend('Runtime.evaluate', {
+ expression: `typeof window.__wbsNotifyToast === 'function' ? window.__wbsNotifyToast(${JSON.stringify(detail)}) : null`,
+ returnByValue: true,
+ });
+ if (response.exceptionDetails || !response.result || !response.result.value || !response.result.value.ok) throw new Error('WorkBuddy 通知组件未就绪');
+ return response.result.value;
+}
+let automationAccountSwitchTail = Promise.resolve();
+function automationSwitchAccount(account) {
+ const target = account && typeof account === 'object' ? account : { uid: String(account || '').trim() };
+ const run = automationAccountSwitchTail.then(async () => {
+ const uid = String(target.uid || '').trim();
+ if (!uid) throw new Error('账号切换缺少 uid');
+ const active = currentAccount();
+ if (active && active.uid === uid) return { ok: true, uid, switched: false };
+ const releaseRendererReload = beginRendererReloadPriority();
+ try {
+ const acct = switchTo(DATA_DIR, uid, log);
+ pendingAutomationAccountSwitch = { account: { uid: acct.uid, nickname: acct.nickname } };
+ await reloadWorkBuddyPage();
+ if (pendingAutomationAccountSwitch) {
+ const switchEvent = pendingAutomationAccountSwitch;
+ pendingAutomationAccountSwitch = null;
+ dispatchAutomationEvent('pageReady', { navigationSerial: mainFrameNavigationSerial, source: 'automation-account-switch', account: switchEvent.account });
+ }
+ return { ok: true, uid: acct.uid, nickname: acct.nickname, switched: true };
+ } catch (error) {
+ pendingAutomationAccountSwitch = null;
+ throw error;
+ } finally {
+ releaseRendererReload();
+ }
+ });
+ automationAccountSwitchTail = run.catch(() => {});
+ return run;
+}
+function startAutomationRun(task, event = null) {
+ if (event && event.navigationSerial == null) event = { ...event, navigationSerial: mainFrameNavigationSerial };
+ if (automationRuns.size > 200) {
+ for (const [key, value] of automationRuns) {
+ if (value.status !== 'running') automationRuns.delete(key);
+ if (automationRuns.size <= 160) break;
+ }
+ }
+ const id = 'run_' + Date.now().toString(36) + '_' + crypto.randomBytes(3).toString('hex');
+ const run = { id, taskId: task.id, status: 'running', startedAt: Date.now(), finishedAt: 0, error: '', logs: [], result: null, navigationSerial: event && event.navigationSerial };
+ const isCancelled = () => run.status === 'cancelled' || run.superseded === true ||
+ (task.trigger.restartOnNavigation && event && event.navigationSerial !== mainFrameNavigationSerial);
+ log('[automation-focus-diagnostics] automation:start ' + JSON.stringify({ runId: id, taskId: task.id, source: event && event.source || '', account: event && event.account || null, cdpTargetUrl: cdp.targetUrl, cdpTargetTitle: cdp.targetTitle }));
+ const appendRunLog = (message) => {
+ run.logs.push({ at: Date.now(), message: String(message || '').slice(0, 300) });
+ if (run.logs.length > 200) run.logs.splice(0, run.logs.length - 200);
+ };
+ automationRuns.set(id, run);
+ run.wasPanelOpen = false;
+ const requiresLease = taskNeedsPanelClosed(task) && !taskIsPassiveCleanup(task);
+ run.phase = requiresLease ? 'queued' : 'executing';
+ // 运行前若面板正展开,先「点一下关闭按钮」把它收起(走 inject 同一 setOpen,等价于点面板 ✕),
+ // 避免面板 contenteditable/悬浮层干扰官方 composer 键入与发送(用户实测:面板开着发不出去)。
+ // 结束时会按 wasPanelOpen 恢复。机器人按钮 .wbs-fab 始终保留可见。
+ let releaseRenderer = () => {};
+ const panelPrepare = (requiresLease ? acquireAutomationRenderer(isCancelled).then(release => { releaseRenderer = release; run.phase = 'executing'; return automationPanelIsOpen(); }) : Promise.resolve(false)).then((open) => {
+ if (isCancelled()) return;
+ run.wasPanelOpen = open;
+ log('[automation-focus-diagnostics] automation:panel-state ' + JSON.stringify({ runId: id, open }));
+ if (open) return automationPanelSetOpen(false).then((result) => {
+ log('[automation-focus-diagnostics] automation:panel-close ' + JSON.stringify({ runId: id, result }));
+ return result;
+ });
+ return undefined;
+ });
+ const scopedState = createTaskState(task.id, readAutomationState, writeAutomationState);
+ const runScopedState = scopedState.get, setRunState = scopedState.set;
+ const withInput = async (fn, restoring = false) => {
+ const release = await acquireAutomationInput(restoring ? () => false : isCancelled);
+ try {
+ if (requiresLease) {
+ if (await automationPanelIsOpen()) run.wasPanelOpen = true;
+ await automationPanelSetInputActive(true);
+ }
+ return await fn();
+ } finally {
+ try { if (requiresLease) await automationPanelSetInputActive(false).catch(() => {}); }
+ finally { release(); }
+ }
+ };
+ let lastReceipt = null;
+ const readSession = async () => {
+ if (isCancelled()) throw new Error('任务已停止');
+ const response = await cdpSend('Runtime.evaluate', { expression: '(' + probeSessionReceipt.toString() + ')()', returnByValue: true });
+ return response && response.result && response.result.value || null;
+ };
+ const sessionAction = async (op, detail) => {
+ if (isCancelled()) throw new Error('任务已停止');
+ if (op === 'session.wait') {
+ const receipt = detail.receipt || lastReceipt;
+ if (!receipt || !receipt.userMessageId || !receipt.conversationId || !receipt.accountUid) throw new Error('需要本轮发送返回的会话回执');
+ const end = Date.now() + Math.min(300000,Math.max(1000,Number(detail.timeoutMs)||120000));
+ while (Date.now() < end) {
+ if ((currentAccount() || {}).uid !== receipt.accountUid) throw new Error('账号已变化,已停止等待');
+ const snapshot = await readSession();
+ if (receiptComplete(receipt,snapshot)) {
+ if (detail.contains) {
+ const response = await cdpSend('Runtime.evaluate', {expression: `(function(){var c=window.__wbsWorkBuddyCompat.findConversationControllers(document).find(c=>String(c.conversationId)===${JSON.stringify(receipt.conversationId)});if(!c)return false;var m=c.messageStore.getState().messages.find(m=>String(m.id||m.requestId||'')===${JSON.stringify(snapshot.assistantId)});return !!m&&JSON.stringify(m.content||[]).includes(${JSON.stringify(String(detail.contains))});})()`,returnByValue:true});
+ if (!(response && response.result && response.result.value)) throw new Error('回复已完成但不包含指定内容');
+ }
+ return {ok:true,conversationId:receipt.conversationId,requestId:receipt.requestId,assistantId:snapshot.assistantId};
+ }
+ await cancellableWait(250,isCancelled);
+ }
+ throw new Error('等待会话回复超时');
+ }
+ const accountUid = (currentAccount() || {}).uid;
+ if (!accountUid) throw new Error('没有可用账号');
+ if (op === 'session.create') await withInput(() => ensureAutomationNewTask({ guard: () => {
+ if (isCancelled() || (currentAccount() || {}).uid !== accountUid) throw new Error('发送前账号或运行状态已变化');
+ } }));
+ const before = await readSession();
+ if (op === 'session.send') {
+ if (!detail.conversationId || !before || before.conversationId !== detail.conversationId) throw new Error('只能发送到已选中的指定会话');
+ if (before.busy) throw new Error('目标会话正在运行');
+ // The common sender checks the exact editor immediately before typing.
+ // New Task surface discovery cannot identify a conversation composer.
+ }
+ if (isCancelled() || (currentAccount() || {}).uid !== accountUid) throw new Error('发送前账号或运行状态已变化');
+ await withInput(() => acSendPhrase(String(detail.message || ''), { requireEmpty: true, isCancelled, guard: async () => {
+ if (isCancelled() || (currentAccount() || {}).uid !== accountUid) throw new Error('账号或运行状态已变化,停止发送');
+ const selected = await readSession();
+ if (op === 'session.send' ? !selected || selected.conversationId !== detail.conversationId : selected && (!before || selected.conversationId !== before.conversationId)) throw new Error('会话已变化,停止发送');
+ } }));
+ // Do not retry an unconfirmed send: it may already have reached WorkBuddy.
+ const end = Date.now() + 12000;
+ while (Date.now() < end) {
+ if ((currentAccount() || {}).uid !== accountUid) throw new Error('发送后账号已变化,请检查会话;不会自动重发');
+ const snapshot = await readSession();
+ if (snapshot && snapshot.userMessageId && (!before || snapshot.conversationId !== before.conversationId || snapshot.userMessageId !== before.userMessageId)) {
+ if (op === 'session.send' && snapshot.conversationId !== detail.conversationId) throw new Error('发送后会话发生变化,请检查发送结果');
+ lastReceipt = {ok:true,accountUid,conversationId:snapshot.conversationId,userMessageId:snapshot.userMessageId,requestId:snapshot.requestId,baselineAssistantId:before && before.conversationId===snapshot.conversationId ? before.assistantId : ''};
+ return lastReceipt;
+ }
+ await cancellableWait(100,isCancelled);
+ }
+ throw new Error('未确认会话发送回执,请检查 WorkBuddy;不会自动重发');
+ };
+ // Compatibility aliases retain the historical New Task send behavior.
+ const sessionSendCurrent = async message => sessionAction('session.create',{message});
+ const sessionWaitReply = async detail => sessionAction('session.wait',{...detail,receipt:lastReceipt});
+ const completionReport = async ({ timeoutMs }) => {
+ if (PROFILE.id !== 'workbuddy-cn') throw new Error('主账号云端汇报目前仅支持 WorkBuddy 国内版');
+ if (completionReportRunning) throw new Error('已有主账号完成汇报任务正在监听');
+ completionReportRunning = true;
+ try {
+ const result = await runCompletionReport({ timeoutMs, currentAccount, primaryUid: () => primaryAccountStore.get(), isCancelled, log: appendRunLog,
+ snapshot: async (uid) => {
+ if (!cdp.connected) throw new Error('WorkBuddy 未连接,未发送汇报');
+ const response = await cdpSend('Runtime.evaluate', { expression: '(' + probeAccountCompletion.toString() + ')(' + JSON.stringify(uid) + ')', awaitPromise: true, returnByValue: true });
+ return response && response.result && response.result.value;
+ },
+ send: async (uid, message) => {
+ if (isCancelled()) throw new Error('用户停止任务');
+ const raw = JSON.parse(fs.readFileSync(accountBackupFile(uid), 'utf8'));
+ const auth = raw.auth || {};
+ const token = auth.accessToken || auth.access_token || auth.token;
+ if (!token) throw new Error('主账号凭据不可用');
+ try { return await activateGrowthAccount(token, { apiHost: PROFILE.apiHost, prompt: message, purpose: 'completion-report', timeoutMs: 60000 }); }
+ catch (_) { throw new Error('云端汇报未确认成功,请检查主账号云端会话;不会自动重试,避免重复发送'); }
+ },
+ });
+ appendRunLog(result.skipped ? result.reason : '已向主账号发送云端汇报会话');
+ return result;
+ } finally { completionReportRunning = false; }
+ };
+ const runNotifier = createAutomationNotifier(automationNotifyToast, 'automation:' + id);
+ run.cleanupNotifications = runNotifier.cleanup;
+ const publicAccounts = () => listAccounts(DATA_DIR).map(a => ({uid:a.uid,nickname:a.nickname,isPrimary:primaryAccountStore.get()===a.uid}));
+ const publicCurrent = () => { const a = currentAccount(); return a ? {uid:a.uid,nickname:a.nickname,isPrimary:primaryAccountStore.get()===a.uid} : null; };
+ const runDeps = { sessionAction, primaryAccount: async () => publicAccounts().find(a=>a.isPrimary) || null, dismissToast: runNotifier.dismiss, completionReport, event, listAccounts: async () => publicAccounts(), currentAccount: publicCurrent, accountSwitch: (account, detail) => withInput(() => automationSwitchAccount(account), !!(detail && detail.restore)), accountStatus: automationAccountStatus, accountCheckin: async (account) => {
+ 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(() => {});
+ 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,
+ // 若面板还没收会抢焦点)。结束按 run.wasPanelOpen 恢复展开,若运行前本就收起则保持收起。
+ run.completion = panelPrepare
+ .then(() => executeTask(task, runDeps))
+ .then(async (result) => { if (isCancelled()) throw new Error('任务已停止'); if (run.wasPanelOpen) await automationPanelSetOpen(true); if (run.status === 'running') { run.status = 'success'; run.result = result; run.finishedAt = Date.now(); } log('[automation-focus-diagnostics] automation:finish ' + JSON.stringify({ runId: id, status: run.status, error: run.error })); })
+ .catch(async (error) => { if (run.wasPanelOpen && !run.superseded && (!task.trigger.restartOnNavigation || !event || event.navigationSerial === mainFrameNavigationSerial)) await automationPanelSetOpen(true); run.status = isCancelled() ? 'cancelled' : 'failed'; run.error = run.superseded ? '页面已切换,重新检测新页面' : String(error && error.message || error); run.finishedAt = Date.now(); appendRunLog(run.error); log('[automation-focus-diagnostics] automation:finish ' + JSON.stringify({ runId: id, status: run.status, error: run.error })); })
+ .finally(async () => { try { await runNotifier.cleanup(); } finally { releaseRenderer(); resumeAutomationAfterNavigation(run); } });
+ return run;
+}
+
+function resumeAutomationAfterNavigation(run) {
+ const next = run.pendingEvent;
+ run.pendingEvent = null;
+ if (!next || next.navigationSerial !== mainFrameNavigationSerial) return;
+ const task = readAutomations(DATA_DIR).find((item) => item.id === run.taskId && item.enabled && item.trigger.restartOnNavigation);
+ if (task) startAutomationRun(task, next);
}
function todayStr(d) {
@@ -2614,24 +3167,31 @@ async function dailyCheckin(accessToken, account = {}) {
}
/** 对单个账号签到(带每日缓存,幂等:今日已成功过则跳过) */
-async function claimDailyForUid(uid) {
+const checkinClaims = new Map();
+function claimDailyForUid(uid) {
+ if (!PROFILE.capabilities.accounts || PROFILE.capabilities.checkin === false) throw new Error('当前客户端不支持账号签到');
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(String(uid || ''))) throw new Error('账号 ID 无效');
+ if (checkinClaims.has(uid)) return checkinClaims.get(uid);
+ const promise = performAccountCheckin(uid).finally(() => checkinClaims.delete(uid));
+ checkinClaims.set(uid, promise);
+ return promise;
+}
+
+async function performAccountCheckin(uid) {
const today = todayStr();
- const refreshed = await refreshAccountBackupToken(uid);
- const accountRoot = refreshed.root;
- const refreshError = refreshed.error || '';
let dbHit = null;
try { dbHit = await CREDIT_USAGE_STORE.getDailyCheckin(uid, today); } catch (e) {
log('[checkin] 读取 SQLite 标记失败: ' + e.message);
}
- if (!refreshError && dbHit && dbHit.ok === true && dbHit.verified === true) {
+ if (dbHit && dbHit.date === today && dbHit.ok === true && dbHit.verified === true) {
return { uid, skipped: true, ...dbHit };
}
const cache = loadCheckinCache();
const hit = cache[uid];
- const cachedResult = hit && hit.date === today
+ const cachedResult = hit && hit.date === today && hit.ok === true && hit.verified !== false
? classifyCheckinResult({ httpOk: true, code: hit.code, message: hit.message })
: null;
- if (!refreshError && cachedResult && cachedResult.ok) {
+ if (cachedResult && cachedResult.ok) {
const migrated = { uid, skipped: true, date: today, ...cachedResult, at: Number(hit.at) || Date.now(), verified: true };
try {
await CREDIT_USAGE_STORE.saveDailyCheckin({ uid, date: today, checkedAt: migrated.at, code: migrated.code, message: migrated.message });
@@ -2640,6 +3200,9 @@ async function claimDailyForUid(uid) {
}
return migrated;
}
+ const refreshed = await refreshAccountBackupToken(uid);
+ const accountRoot = refreshed.root;
+ const refreshError = refreshed.error || '';
if (!accountRoot) return { uid, ok: false, reason: refreshed.error || 'no-backup' };
const auth = accountRoot.auth && typeof accountRoot.auth === 'object' ? accountRoot.auth : {};
const tk = auth.accessToken || auth.access_token || auth.token;
@@ -2647,8 +3210,8 @@ async function claimDailyForUid(uid) {
const account = { uid, domain: auth.domain || '' };
const r = await dailyCheckin(tk, account);
const rec = { date: today, ok: !!r.ok, already: !!r.already, inactive: !!r.inactive, code: r.code, message: r.message, at: Date.now(), verified: !!r.ok };
- cache[uid] = rec;
- saveCheckinCache(cache);
+ // Merge with the latest cache: different automation tasks may finish different accounts concurrently.
+ saveCheckinCache(Object.assign(loadCheckinCache(), { [uid]: rec }));
if (rec.ok) {
try {
await CREDIT_USAGE_STORE.saveDailyCheckin({ uid, date: today, checkedAt: rec.at, code: rec.code, message: rec.message });
@@ -2659,39 +3222,6 @@ async function claimDailyForUid(uid) {
return { uid, ...(refreshError ? { refreshError } : {}), ...rec };
}
-/** 对所有账号执行每日签到(自动跳过今日已成功过的,带并发保护) */
-async function claimDailyForAll() {
- if (!PROFILE.capabilities.accounts) return { skipped: true, reason: 'profile-no-account-files' };
- if (claimInFlight) return { skipped: true, reason: 'in-flight', checkin: checkinSnapshot() };
- claimInFlight = true;
- try {
- const list = listAccounts(DATA_DIR).map((a) => a.uid);
- checkinState = { running: true, total: list.length, done: 0, startedAt: Date.now(), finishedAt: 0 };
- const results = [];
- for (let i = 0; i < list.length; i++) {
- const uid = list[i];
- // 即使 access token 尚未临期,也每天主动刷新一次,避免 refresh token 因长期闲置失效。
- await refreshAccountBackupToken(uid, { dailyKeepalive: true });
- let result;
- try {
- result = await claimDailyForUid(uid);
- } catch (e) {
- result = { uid, ok: false, reason: e.message };
- }
- results.push(result);
- checkinState.done = i + 1;
- // 账号之间留一点间隔,避免多个账号同时触发服务端限流/连接排队。
- if (i < list.length - 1 && !result.skipped) await sleep(CHECKIN_QUEUE_DELAY_MS);
- }
- log('[checkin] 本轮回检 ' + results.length + ' 个账号');
- return { total: results.length, results };
- } finally {
- checkinState.running = false;
- checkinState.finishedAt = Date.now();
- claimInFlight = false;
- }
-}
-
/** 通过 CDP 把右下角组件注入到 WorkBuddy 渲染进程(幂等,可反复调用) */
function injectWidget(reason, executionContextId) {
if (!cdp.connected) {
@@ -2749,6 +3279,9 @@ function injectWidget(reason, executionContextId) {
...runtimeContext,
})
)
+ // Reinjection and daemon replacement must reflect the current input lease,
+ // including a reset after an interrupted run. Reply-waiting never locks UI.
+ .then(async (r) => { await automationPanelSetInputActive(automationInputActive); return r; })
// 注入脚本若在页面抛错,CDP 协议不报错(无 protocol error),会被误判为"已注入";
// 显式检查 exceptionDetails 让失败可见、留痕,便于定位 WorkBuddy 版本差异导致的挂载失败。
.then((r) => {
@@ -2800,8 +3333,15 @@ function injectWidget(reason, executionContextId) {
}
function buildInjectScript() {
+ const toastScript = fs.readFileSync(path.join(__dirname, 'toast-runtime.js'), 'utf8');
const compatScript = fs.readFileSync(path.join(__dirname, 'workbuddy-compat.js'), 'utf8');
let injectScript = fs.readFileSync(path.join(__dirname, 'inject.js'), 'utf8');
+ const anchor = 'return { destroy: lifecycle.destroy, alive: lifecycle.alive };';
+ if (!injectScript.includes(anchor)) {
+ throw new Error('自动化拾取器注入锚点不存在');
+ }
+ const automationPickerCode = fs.readFileSync(path.join(__dirname, 'automation-picker.js'), 'utf8');
+ injectScript = injectScript.replace(anchor, automationPickerCode + '\n' + anchor);
// 内部调试模块(元素检查/DevTools):picker-internal.js 存在才注入(git 不跟踪,
// 他人环境无此文件 → 隐藏入口的拾取按钮点击会报错,符合预期,不影响面板其他功能)。
// 注入位置:放进 build() 函数体末尾(与面板共享闭包作用域:root/toast/esc 等),
@@ -2809,14 +3349,13 @@ function buildInjectScript() {
const pickerPath = path.join(__dirname, 'picker-internal.js');
if (fs.existsSync(pickerPath)) {
const pickerCode = fs.readFileSync(pickerPath, 'utf8');
- const anchor = 'return { destroy: lifecycle.destroy, alive: lifecycle.alive };';
if (!injectScript.includes(anchor)) {
throw new Error('picker-internal.js 注入锚点不存在');
}
injectScript = injectScript.replace(anchor, pickerCode + '\n' + anchor);
}
// 组件内通过 fetch 调用本机 API,注入时写入实际端口
- return (compatScript + '\n' + injectScript)
+ return (toastScript + '\n' + compatScript + '\n' + injectScript)
.replace(/__WBS_API__/g, `http://${HOST}:${ACTUAL_PORT}`)
.replace(/__WBS_VERSION__/g, DAEMON_VERSION)
// 注入本地 API 能力凭证;旧版面板不会携带该 header,但新版 daemon 会在启动时重新注入新版面板。
@@ -4377,17 +4916,131 @@ function importQuickPhrases(content, password) {
return { state: readSessionState(), imported, skipped };
}
/** 通过 CDP 发送指定短语:聚焦 composer → 全选 → 真实输入短语 → 真实 Enter(replace 式发送,多行短语按段落插入) */
-async function acSendPhrase(text) {
+async function acSendPhrase(text, options = {}) {
if (!cdp.connected) throw new Error('CDP 未连接');
- const r = await cdpSend('Runtime.evaluate', {
- expression: `(()=>{const ce=document.querySelector('.chat-container [contenteditable="true"]')||document.querySelector('[contenteditable="true"]');if(!ce)return 'no-composer';ce.focus();var sel=window.getSelection();var r=document.createRange();r.selectNodeContents(ce);sel.removeAllRanges();sel.addRange(r);return 'ok'})()`,
+ const message = String(text || '').trim();
+ if (!message) throw new Error('发送内容为空');
+ // 新版 toolbar 的 Enter 行为会受输入法/多行模式影响;复用快捷短语的完整
+ // Slate 输入链路,并在提交阶段优先点击官方 cr-send-button。
+ return sendStashToComposer({ content: { text: message, items: [] }, ...options });
+}
+
+function automationAgentSurfaceExpression(focusComposer) {
+ return `(function(){
+ function visible(el){if(!el||el.closest('.wbs-root'))return false;var r=el.getBoundingClientRect();var s=getComputedStyle(el);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'}
+ function isNewTask(el){var aria=(el.getAttribute('aria-label')||'').trim();var text=(el.innerText||el.textContent||'').trim();return /^(新建任务|New Task)$/i.test(aria)||/^(新建任务|New Task)$/i.test(text)}
+ function composerText(el){
+ if(!el)return '';
+ if(el.tagName==='TEXTAREA')return String(el.value||'').replace(/[\\uFEFF\\u200B]/g,'').trim();
+ var clone=el.cloneNode(true);
+ clone.querySelectorAll('[data-slate-placeholder="true"],[data-slate-zero-width]').forEach(function(node){node.remove()});
+ return String(clone.innerText||clone.textContent||'').replace(/[\\uFEFF\\u200B]/g,'').trim();
+ }
+ var activeNewTask=Array.from(document.querySelectorAll('button.conversation-list-tab-button.active,button.conversation-list-tab-button.conversation-list-tab-button-box')).some(function(el){return visible(el)&&isNewTask(el)&&(/\\bactive\\b/.test(typeof el.className==='string'?el.className:'')||el.getAttribute('aria-selected')==='true')});
+ var composers=Array.from(document.querySelectorAll('[contenteditable="true"],textarea')).filter(visible);
+ var composer=composers.find(function(el){return !!el.closest('.wb-home-composer')})||(activeNewTask?composers[0]:null);
+ var ready=!!composer&&(activeNewTask||!!composer.closest('.wb-home-composer'));
+ var newTaskReady=!!composer&&activeNewTask;
+ var button=null;
+ // 普通项目页也可能有 composer;自动化发送必须以 newTaskReady 为准,不能被 ready 短路。
+ if(!newTaskReady){
+ var candidates=Array.from(document.querySelectorAll('button.workspace-new-task-button,button.conversation-list-tab-button.conversation-list-tab-button-box,button.conversation-list-tab-button,button[aria-label="新建任务"],button[aria-label="New Task"]'));
+ var target=candidates.find(function(el){return visible(el)&&isNewTask(el)});
+ if(target){var b=target.getBoundingClientRect();button={x:b.left+b.width/2,y:b.top+b.height/2}}
+ }
+ if(ready&&composer&&${focusComposer ? 'true' : 'false'}){
+ composer.focus();
+ if(composer.tagName!=='TEXTAREA'){var selection=window.getSelection();var range=document.createRange();range.selectNodeContents(composer);selection.removeAllRanges();selection.addRange(range)}
+ }
+ return {ready:ready,newTaskReady:newTaskReady,activeNewTask:activeNewTask,hasComposer:!!composer,composerText:composerText(composer),button:button};
+ })()`;
+}
+
+async function readAutomationAgentSurface(focusComposer = false) {
+ const response = await cdpSend('Runtime.evaluate', {
+ expression: automationAgentSurfaceExpression(focusComposer),
returnByValue: true,
});
- if (!(r && r.result && r.result.value === 'ok')) throw new Error('no-composer');
- await cdpSend('Input.insertText', { text: String(text || '') });
- await new Promise((r) => setTimeout(r, 260)); // 等待 React/Slate 落定
- await cdpSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 });
- await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 });
+ return response && response.result && response.result.value;
+}
+
+async function ensureAutomationNewTask(options = {}) {
+ if (!cdp.connected) throw new Error('CDP 未连接');
+ let surface = null;
+ let clicked = false;
+ let readySince = null;
+ let settled = false;
+ const started = Date.now();
+ // Injection can finish before WorkBuddy's account route mounts its sidebar.
+ // Wait for both the entry and destination; never send into a project composer.
+ while (Date.now() - started < 15000) {
+ if (options.guard) await options.guard();
+ try {
+ surface = await readAutomationAgentSurface(false);
+ } catch (error) {
+ if (!/Execution context was destroyed|Cannot find (?:default execution context|context with specified id)/i.test(String(error && error.message || error))) throw error;
+ surface = null;
+ }
+ if (surface && surface.newTaskReady && surface.hasComposer) {
+ // Allow route initialization to settle before focusing a newly mounted editor.
+ if (readySince === null) readySince = Date.now();
+ if (Date.now() - readySince >= 400) { settled = true; break; }
+ } else {
+ readySince = null;
+ if (!clicked && surface && surface.button) {
+ await cdpMouseClick('automation:ensureNewTask', surface.button.x, surface.button.y);
+ clicked = true;
+ }
+ }
+ await sleep(200);
+ }
+ if (options.guard) await options.guard();
+ if ((!surface || !surface.newTaskReady) && !clicked) throw new Error('未找到 WorkBuddy 的新建任务入口');
+ if (!settled) throw new Error('新建任务页面未准备完成,拒绝发送到当前会话');
+ const originalDraftText = surface.composerText;
+ // WorkBuddy retains the home draft. Preserve it through the existing local
+ // stash before trusted editor commands replace it; never log the contents.
+ const backup = await cdpSend('Runtime.evaluate', {
+ expression: `(async function(){var s=${automationAgentSurfaceExpression(false)};if(!s.newTaskReady||typeof window.__wbsSaveAutomationDraft!=='function')return {saved:false};return window.__wbsSaveAutomationDraft()})()`,
+ returnByValue: true, awaitPromise: true,
+ });
+ const saved = backup && backup.result && backup.result.value;
+ if (!saved || !saved.saved) throw new Error('未能安全保存新建任务草稿,请重试');
+ if (options.guard) await options.guard();
+ surface = await readAutomationAgentSurface(true);
+ if (!surface || !surface.newTaskReady || surface.composerText !== originalDraftText) throw new Error('页面或草稿已变化,已保留草稿并取消发送');
+ // The renderer helper already verified the saved draft. These
+ // commands go to the editor directly, avoiding native macOS menu shortcuts.
+ if (surface.composerText) {
+ await cdpSend('Input.dispatchKeyEvent', { type: 'rawKeyDown', commands: ['selectAll'] });
+ await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp' });
+ await cdpSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
+ await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
+ await sleep(150);
+ }
+ surface = await readAutomationAgentSurface(false);
+ if (!surface || !surface.newTaskReady || surface.composerText) throw new Error('新建任务输入框尚未清空,原草稿已保留在暂存');
+ return surface;
+}
+
+let automationAgentCreating = false;
+async function openNewAutomationAgentTask(prompt) {
+ if (!cdp.connected) throw new Error('CDP 未连接');
+ if (automationAgentCreating) throw new Error('正在创建 Agent 任务,请稍候');
+ const text = String(prompt || '').trim();
+ if (!text || text.length > 50000) throw new Error('Agent 提示词为空或过长');
+ automationAgentCreating = true;
+ try {
+ await ensureAutomationNewTask();
+ // Reuse the tested Slate multiline input and official send-button path.
+ await sendStashToComposer({ content: { text, items: [] } });
+ for (let attempt = 0; attempt < 25; attempt++) {
+ await sleep(200);
+ const after = await readAutomationAgentSurface(false);
+ if (after && (!after.newTaskReady || !after.composerText)) return { sent: true };
+ }
+ throw new Error('Agent 提示词未发送,请重试');
+ } finally { automationAgentCreating = false; }
}
function currentAccount() {
@@ -4546,20 +5199,28 @@ function buildBusyExpr() {
}
/** 等待 AI 空闲;超时返回 false */
-async function waitAiIdle(maxMs = 60000, pollMs = 500) {
+async function waitAiIdle(maxMs = 60000, pollMs = 500, isCancelled = () => false) {
if (!cdp.connected) return true; // CDP 未连接时不等待(后续会报错)
+ log('[quick-phrase-diagnostics] wait-idle:start ' + JSON.stringify({ maxMs, pollMs, targetUrl: cdp.targetUrl }));
const expr = buildBusyExpr();
const t0 = Date.now();
+ let probes = 0;
+ if (isCancelled()) throw new Error('任务已停止');
while (Date.now() - t0 < maxMs) {
+ if (isCancelled()) throw new Error('任务已停止');
try {
const r = await cdpSend('Runtime.evaluate', { expression: expr, returnByValue: true });
const busy = (r.result && r.result.value) === true;
- if (!busy) return true;
- } catch (_) {
+ probes++;
+ log('[quick-phrase-diagnostics] wait-idle:probe ' + JSON.stringify({ probe: probes, elapsedMs: Date.now() - t0, busy, active: await cdpFocusDiagnostics('wait-idle:probe', { probe: probes, busy }) }));
+ if (!busy) { log('[quick-phrase-diagnostics] wait-idle:finish ' + JSON.stringify({ ok: true, probes, elapsedMs: Date.now() - t0 })); return true; }
+ } catch (error) {
+ log('[quick-phrase-diagnostics] wait-idle:finish ' + JSON.stringify({ ok: true, reason: 'evaluate-error', error: error.message, probes, elapsedMs: Date.now() - t0 }));
return true; // evaluate 异常按空闲处理
}
await new Promise((res) => setTimeout(res, pollMs));
}
+ log('[quick-phrase-diagnostics] wait-idle:finish ' + JSON.stringify({ ok: false, reason: 'timeout', probes, elapsedMs: Date.now() - t0 }));
return false;
}
@@ -4890,7 +5551,6 @@ async function restoreSavedTheme() {
const f = path.join(DATA_DIR, 'current-theme.json');
if (fs.existsSync(f)) id = String(JSON.parse(fs.readFileSync(f, 'utf8')).id || 'default');
} catch (_) {}
- if (id === 'default') return; // 默认主题 = 官方浅色,无需处理
await applyThemeByCdp(id);
}
@@ -5092,6 +5752,7 @@ async function applyThemeByCdp(id) {
const expr = `(function(){
var h = document.documentElement, b = document.body;
if (!h || !b) return { pending: true };
+ if (window.__wbsThemeGuard) window.__wbsThemeGuard.disconnect();
var WBS_UID = ${JSON.stringify(uid || null)};
// WorkDaddy 自定义主题已应用标记:theme-patches 里部分规则用 html[data-wbs-theme] 限定
// 只在 WorkDaddy 内置自定义主题下生效(官方默认主题不激活)。
@@ -5137,8 +5798,8 @@ async function applyThemeByCdp(id) {
h.setAttribute('data-theme', mode);
}
var s = document.getElementById('wbs-theme-style');
- if (s) s.remove();
if (${id === 'default' ? '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');
@@ -5162,10 +5823,33 @@ async function applyThemeByCdp(id) {
${JSON.stringify(localCssStr)} +
${JSON.stringify(themeVarsCss(isDark))} +
${JSON.stringify(extrasCss)} + ${JSON.stringify(bgCssStr)};
- var st = document.createElement('style');
+ var st = s || document.createElement('style');
st.id = 'wbs-theme-style';
- st.textContent = css;
- (document.head || document.documentElement).appendChild(st);
+ if (st.textContent !== css) st.textContent = css;
+ if (!s) (document.head || document.documentElement).appendChild(st);
+ }
+ // 账号外观在 React 加载后可能再次写入深浅色;只守住已选主题的根属性,
+ // 不扫描会话 DOM。手动切主题时上方会断开旧 observer,避免多份守护互相争抢。
+ var wantedMode = ${JSON.stringify(id === 'default' || !isDark ? 'light' : 'dark')};
+ var wantedDark = wantedMode === 'dark';
+ var wantedKind = wantedDark ? 'vscode-dark' : 'vscode-light';
+ var wantedName = wantedDark ? 'IDE Night' : 'IDE Light';
+ function keepSelectedTheme() {
+ if (h.getAttribute('data-theme') === wantedMode &&
+ h.classList.contains('cb-dark') === wantedDark &&
+ b.getAttribute('data-vscode-theme-kind') === wantedKind &&
+ b.getAttribute('data-vscode-theme-name') === wantedName &&
+ b.classList.contains('vscode-dark') === wantedDark) return;
+ h.classList.toggle('cb-dark', wantedDark);
+ b.classList.toggle('vscode-dark', wantedDark);
+ wbsSyncNativeTheme(wantedMode);
+ }
+ keepSelectedTheme();
+ if (typeof MutationObserver !== 'undefined') {
+ var guard = new MutationObserver(keepSelectedTheme);
+ guard.observe(h, { attributes: true, attributeFilter: ['class', 'data-theme'] });
+ guard.observe(b, { attributes: true, attributeFilter: ['class', 'data-vscode-theme-kind', 'data-vscode-theme-name'] });
+ window.__wbsThemeGuard = guard;
}
var cs = getComputedStyle(b);
return { applied: ${id === 'default' ? 'false' : 'true'}, dark: ${isDark ? 'true' : 'false'}, bg: cs.getPropertyValue('--vscode-editor-background').trim(), text: cs.getPropertyValue('--vscode-editor-foreground').trim() };
@@ -5262,8 +5946,11 @@ async function clearComposerByCdp() {
*/
async function sendStashToComposer(record) {
if (!cdp.connected) throw new Error('CDP 未连接,无法发送');
+ log('[quick-phrase-diagnostics] composer:start ' + JSON.stringify({ targetUrl: cdp.targetUrl, itemCount: record && record.content && Array.isArray(record.content.items) ? record.content.items.length : 0 }));
// 等待 AI 空闲:若正在回复,最多等 60 秒;期间前端会提示"等待空闲"
- const idle = await waitAiIdle();
+ const idle = await waitAiIdle(60000, record.isCancelled ? 100 : 500, record.isCancelled);
+ if (record.guard) await record.guard();
+ const guardedSend = async (method, params) => { if (record.guard) await record.guard(); return cdpSend(method, params); };
if (!idle) throw new Error('对话持续回复中(等待 60 秒仍未空闲),已取消发送,请稍后再试');
const content = record.content || {};
const allItems = (content.items || []).filter((it) => it && typeof it === 'object');
@@ -5325,14 +6012,14 @@ async function sendStashToComposer(record) {
return { ok: true };
} catch (e) { return { ok: false, error: String(e) }; }
})()`;
- const fr = await cdpSend('Runtime.evaluate', { expression: focusExpr, returnByValue: true });
+ const fr = await guardedSend('Runtime.evaluate', { expression: focusExpr, returnByValue: true });
const fv = fr.result && fr.result.value;
if (!fv || !fv.ok) throw new Error((fv && fv.error) || '无法聚焦输入框');
// 1.5) 清空输入框已有内容(避免与暂存内容拼接)。
// 关键:不能用 document.execCommand('delete') —— execCommand 绕过 Slate 的 model 同步,
// 会破坏编辑器内部 selection 状态,导致之后「退格/全选失效、只能追加文字」。
- // 改用 CDP 真实键盘事件:Cmd+A 全选 + Backspace 删除,Slate 完全感知(onKeyDown -> beforeinput 链路)。
+ // 使用 CDP 编辑命令全选 + 真实 Backspace 删除,让 Slate 感知 selection / beforeinput。
const clearExpr = `(function(){
try {
var mic = document.querySelector('.voice-mic-wrap');
@@ -5351,19 +6038,25 @@ async function sendStashToComposer(record) {
}
if (!ed) return { ok: false, error: 'no editor' };
ed.focus();
- return { ok: true, hasContent: ((ed.innerText || '').replace(/[\\uFEFF\\u200B\\u00A0]/g, '').trim().length > 0) || !!ed.querySelector('[data-contentblock]') };
+ // Slate renders its placeholder inside the editor. It is not a draft;
+ // inspect a detached clone so the live editor and its selection stay intact.
+ var clone = ed.cloneNode(true);
+ clone.querySelectorAll('[data-slate-placeholder="true"],[data-slate-zero-width]').forEach(function(node){ node.remove(); });
+ return { ok: true, hasContent: ((clone.innerText || clone.textContent || '').replace(/[\\uFEFF\\u200B\\u00A0]/g, '').trim().length > 0) || !!ed.querySelector('[data-contentblock]') };
} catch (e) { return { ok: false, error: String(e) }; }
})()`;
- const clr = await cdpSend('Runtime.evaluate', { expression: clearExpr, returnByValue: true });
+ const clr = await guardedSend('Runtime.evaluate', { expression: clearExpr, returnByValue: true });
const clrV = clr.result && clr.result.value;
if (!clrV || !clrV.ok) throw new Error((clrV && clrV.error) || '无法聚焦输入框');
+ if (record.requireEmpty && clrV.hasContent) throw new Error('会话输入框非空,未覆盖草稿、未发送');
if (clrV.hasContent) {
- // Cmd+A 全选(macOS meta=4)→ Backspace 删除
- await cdpSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'a', code: 'KeyA', modifiers: 4, windowsVirtualKeyCode: 65, nativeVirtualKeyCode: 65 });
- await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp', key: 'a', code: 'KeyA', modifiers: 4, windowsVirtualKeyCode: 65, nativeVirtualKeyCode: 65 });
+ // 直接执行 renderer 编辑命令,不经过 macOS 原生菜单快捷键。
+ // 旧 Cmd+A 把 Windows 的 65 当作 macOS 原生键码,会误弹“关于 WorkBuddy”并阻塞 CDP。
+ await guardedSend('Input.dispatchKeyEvent', { type: 'rawKeyDown', commands: ['selectAll'] });
+ await guardedSend('Input.dispatchKeyEvent', { type: 'keyUp' });
await new Promise((r) => setTimeout(r, 120));
- await cdpSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8, nativeVirtualKeyCode: 8 });
- await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8, nativeVirtualKeyCode: 8 });
+ await guardedSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
+ await guardedSend('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
await new Promise((r) => setTimeout(r, 300));
}
@@ -5374,13 +6067,13 @@ async function sendStashToComposer(record) {
if (lines[li]) {
const CHUNK = 4000;
for (let i = 0; i < lines[li].length; i += CHUNK) {
- await cdpSend('Input.insertText', { text: lines[li].slice(i, i + CHUNK) });
+ await guardedSend('Input.insertText', { text: lines[li].slice(i, i + CHUNK) });
if (i + CHUNK < lines[li].length) await new Promise((r) => setTimeout(r, 40));
}
}
if (li < lines.length - 1) {
- await cdpSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', modifiers: 8 }); // Shift+Enter
- await cdpSend('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', modifiers: 8 });
+ await guardedSend('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', modifiers: 8 }); // Shift+Enter
+ await guardedSend('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', modifiers: 8 });
}
}
@@ -5402,7 +6095,7 @@ async function sendStashToComposer(record) {
return ed ? ed.querySelectorAll('[data-contentblock]').length : 0;
})()`;
const countBlocks = async () => {
- const r = await cdpSend('Runtime.evaluate', { expression: countExpr, returnByValue: true });
+ const r = await guardedSend('Runtime.evaluate', { expression: countExpr, returnByValue: true });
return (r.result && r.result.value) || 0;
};
let imagesRestored = 0;
@@ -5435,7 +6128,7 @@ async function sendStashToComposer(record) {
return { ok: true };
} catch (e) { return { ok: false, error: String(e) }; }
})()`;
- const ir = await cdpSend('Runtime.evaluate', { expression: pasteExpr, returnByValue: true });
+ const ir = await guardedSend('Runtime.evaluate', { expression: pasteExpr, returnByValue: true });
const iv = ir.result && ir.result.value;
if (!iv || !iv.ok) return false;
// 轮询验证(最多 ~3 秒)contentblock 数量是否增加
@@ -5479,11 +6172,41 @@ async function sendStashToComposer(record) {
if (blockText) text = text ? text + '\n' + blockText : blockText;
blocksFailed = blockItems.length;
- // 等 React 重渲染使发送按钮可用
- await new Promise((r) => setTimeout(r, 250));
-
const sendExpr = `(function(){
try {
+ // WorkBuddy 新版输入框有稳定的官方发送按钮;优先使用它,避免把增强/语音
+ // 等同样是圆形的 toolbar 控件误判为发送。
+ var sendLabel = '\\u53d1\\u9001';
+ function visible(button) {
+ var r = button.getBoundingClientRect(), s = getComputedStyle(button);
+ return r.width >= 16 && r.height >= 16 && r.bottom > 0 && s.display !== 'none' && s.visibility !== 'hidden';
+ }
+ var active = document.activeElement;
+ var inputBox = active && active.closest ? active.closest('.cr-input-box') : null;
+ if (!inputBox) {
+ var boxes = Array.from(document.querySelectorAll('.cr-input-box')).filter(visible);
+ if (boxes.length > 1) return { ok: false, retryable: true, error: '未找到发送按钮' };
+ inputBox = boxes[0] || null;
+ }
+ var officialButtons = Array.from((inputBox || document).querySelectorAll('button.cr-send-button,button[aria-label="' + sendLabel + '"],[role="button"][aria-label="' + sendLabel + '"],button[aria-label="Send"],[role="button"][aria-label="Send"]'));
+ var official = officialButtons.find(function(button) {
+ return visible(button) && !button.closest('.wbs-root') && !button.classList.contains('cr-send-button--stop');
+ });
+ if (official) {
+ var or = official.getBoundingClientRect(), os = getComputedStyle(official);
+ var od = official.disabled === true || official.hasAttribute('disabled') || official.getAttribute('aria-disabled') === 'true';
+ if (or.width >= 16 && or.height >= 16 && or.bottom > 0 && os.display !== 'none' && os.visibility !== 'hidden') {
+ // A disabled official button is still the correct target. Account/model
+ // startup may enable it later; never fall through to another control.
+ if (od || os.pointerEvents === 'none') return { ok: false, retryable: true, error: '发送按钮禁用(输入内容未被识别)' };
+ official.scrollIntoView({ block: 'center', inline: 'center' });
+ or = official.getBoundingClientRect();
+ return { ok: true, x: or.x + or.width / 2, y: or.y + or.height / 2, selector: 'official-send-button' };
+ }
+ }
+ // The modern toolbar may still be mounting. Keep waiting within this
+ // composer instead of guessing a different toolbar's circular control.
+ if (inputBox || officialButtons.length) return { ok: false, retryable: true, error: '未找到发送按钮' };
var mic = document.querySelector('.voice-mic-wrap');
var row = mic ? mic.parentElement : null;
if (!row) {
@@ -5518,19 +6241,30 @@ async function sendStashToComposer(record) {
if (!matches.length) return { ok: false, error: '未找到发送按钮' };
var btn = matches[matches.length - 1];
var dis = btn.disabled === true || (btn.hasAttribute && btn.hasAttribute('disabled'));
- if (dis) return { ok: false, error: '发送按钮禁用(输入内容未被识别)' };
+ if (dis) return { ok: false, retryable: true, error: '发送按钮禁用(输入内容未被识别)' };
btn.scrollIntoView({ block: 'center', inline: 'center' });
var b = btn.getBoundingClientRect();
return { ok: true, x: b.x + b.width / 2, y: b.y + b.height / 2 };
} catch (e) { return { ok: false, error: String(e) }; }
})()`;
- const sr = await cdpSend('Runtime.evaluate', { expression: sendExpr, returnByValue: true });
- const sv = sr.result && sr.result.value;
+ // Only retry the readiness probe, never typing or submitting: after a switch
+ // React may need more than one frame to enable the official send button.
+ const sendDeadline = Date.now() + 5000;
+ let sv;
+ while (Date.now() < sendDeadline) {
+ if (record.isCancelled && record.isCancelled()) throw new Error('任务已停止');
+ const sr = await guardedSend('Runtime.evaluate', { expression: sendExpr, returnByValue: true });
+ sv = sr.result && sr.result.value;
+ if (!sv || sv.ok || !sv.retryable || Date.now() >= sendDeadline) break;
+ await new Promise((resolve) => setTimeout(resolve, Math.min(200, sendDeadline - Date.now())));
+ }
+ if (Date.now() >= sendDeadline) throw new Error('等待发送按钮可点击超时(5 秒),未发送');
if (!sv || !sv.ok) throw new Error((sv && sv.error) || '未找到发送按钮');
- await cdpSend('Input.dispatchMouseEvent', { type: 'mouseMoved', x: sv.x, y: sv.y });
- await cdpSend('Input.dispatchMouseEvent', { type: 'mousePressed', x: sv.x, y: sv.y, button: 'left', clickCount: 1 });
- await cdpSend('Input.dispatchMouseEvent', { type: 'mouseReleased', x: sv.x, y: sv.y, button: 'left', clickCount: 1 });
- return { sent: true, textLen: text.length, itemCount: allItems.length, imagesRestored, imagesFailed, blocksRestored, blocksFailed };
+ if (record.guard) await record.guard();
+ await cdpMouseClick('automation:sendPhrase', sv.x, sv.y, { textLen: text.length, button: sv });
+ const result = { sent: true, textLen: text.length, itemCount: allItems.length, imagesRestored, imagesFailed, blocksRestored, blocksFailed };
+ log('[quick-phrase-diagnostics] composer:finish ' + JSON.stringify({ ok: true, result: { sent: result.sent, textLen: result.textLen, itemCount: result.itemCount } }));
+ return result;
}
/**
@@ -5898,6 +6632,183 @@ function handleApi(req, res) {
);
}
+ if (req.method === 'GET' && p === '/api/automations/capabilities') {
+ return json(res, 200, { ok: true, schemaVersion: 1, capabilities: AUTOMATION_CAPABILITIES.filter(item => item.available !== false), protocolZh: automationCapabilityText('zh'), protocolEn: automationCapabilityText('en') });
+ }
+
+ if (req.method === 'POST' && ['/api/automations/export', '/api/automations/import/preview', '/api/automations/import'].includes(p)) {
+ return readTransferBody(req).then(body => {
+ const runtime = { version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform };
+ if (p === '/api/automations/export') return exportTasks(readAutomations(DATA_DIR), body && body.ids);
+ if (p === '/api/automations/import/preview') return previewImport(body, readAutomations(DATA_DIR), runtime);
+ return importTasks(DATA_DIR, body, runtime);
+ }).then(result => json(res, 200, { ok: true, ...result }))
+ .catch(error => json(res, 400, { ok: false, error: error.message }));
+ }
+
+ if (req.method === 'POST' && p === '/api/automations/packages/preview') {
+ return readBody(req).then(body => {
+ try {
+ const preview = previewPackage(body && body.document, { values: body && body.values, runtime: { version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform } });
+ return json(res,200,{ok:true,packageFormatVersion:PACKAGE_FORMAT_VERSION,...preview});
+ } catch(error) { return json(res,400,{ok:false,error:error.message}); }
+ });
+ }
+
+ if (req.method === 'POST' && ['/api/automations/validate','/api/automations/dry-run'].includes(p)) {
+ return readBody(req).then(body => {
+ try {
+ if (body && body.kind != null) throw new Error('任务包或索引不能作为本地任务执行');
+ const task = validateTask(body && body.task ? body.task : body);
+ const operations = [];
+ const walk = value => { if (Array.isArray(value)) value.forEach(walk); else if (value && typeof value === 'object') { if (value.op) operations.push(value.op); Object.values(value).forEach(walk); } };
+ walk([task.steps,task.onSuccess,task.onFailure]);
+ return json(res,200,{ok:true,taskId:task.id,mode:'static',executed:false,requiresRenderer:taskNeedsPanelClosed(task),operations,warnings:[...new Set(operations.filter(op=>AUTOMATION_CAPABILITIES.some(c=>c.id===op&&c.deprecated)).map(op=>'Deprecated: '+op))]});
+ } catch(error) { return json(res,400,{ok:false,error:error.message}); }
+ });
+ }
+
+ if (req.method === 'GET' && p === '/api/automations/agent-info') {
+ try {
+ const paths = ensureAgentBridge(DATA_DIR, { profileId: PROFILE.id });
+ const examples = AUTOMATION_AGENT_EXAMPLES.map((item) => ({
+ id: item.id,
+ titleZh: item.titleZh,
+ titleEn: item.titleEn,
+ descriptionZh: item.descriptionZh,
+ descriptionEn: item.descriptionEn,
+ promptZh: item.promptZh,
+ promptEn: item.promptEn,
+ }));
+ return json(res, 200, { ok: true, profileId: PROFILE.id, examples, protocolZh: paths.protocolZh, protocolEn: paths.protocolEn });
+ } catch (error) { return json(res, 500, { ok: false, error: error.message }); }
+ }
+
+ if (req.method === 'POST' && p === '/api/automations/agent-generate') {
+ return readBody(req).then(async (body) => {
+ try {
+ const request = createAgentRequest(DATA_DIR, {
+ exampleId: body && body.exampleId,
+ prompt: body && body.prompt,
+ language: body && body.language,
+ profileId: PROFILE.id,
+ });
+ await openNewAutomationAgentTask(request.prompt);
+ log(`[automation-agent] 已发送自动化创建请求 example=${request.exampleId} request=${request.requestId}`);
+ return json(res, 202, {
+ ok: true,
+ requestId: request.requestId,
+ exampleId: request.exampleId,
+ title: request.title,
+ resultFile: request.resultFile,
+ });
+ } catch (error) {
+ return json(res, 409, { ok: false, error: error.message });
+ }
+ });
+ }
+
+ if (req.method === 'POST' && p === '/api/automations/events') {
+ return readBody(req).then((body) => {
+ if (!body || body.type !== 'panelOpened') return json(res, 400, { ok: false, error: '不支持的面板事件' });
+ dispatchAutomationEvent('panelOpened', { source: 'panel' });
+ return json(res, 200, { ok: true });
+ });
+ }
+
+ 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}`));
+ const tasks = readAutomations(DATA_DIR);
+ const runs = Array.from(automationRuns.values()).slice(-50).map(automationPublicRun);
+ return json(res, 200, { ok: true, tasks: tasks.map((task) => ({ ...task, manualRunnable: canManuallyRunTask(task), compatible: isTaskCompatible(task) })), runs });
+ }
+
+ if (req.method === 'POST' && p === '/api/automations/logs/clear') {
+ return readBody(req).then((body) => {
+ const taskId = String(body && body.taskId || '').trim();
+ if (!taskId) return json(res, 400, { ok: false, error: '自动化任务 ID 不能为空' });
+ let cleared = 0;
+ for (const [runId, run] of automationRuns) {
+ if (run.taskId === taskId && run.status !== 'running') {
+ automationRuns.delete(runId);
+ cleared += 1;
+ }
+ }
+ return json(res, 200, { ok: true, taskId, cleared });
+ });
+ }
+
+ if (req.method === 'POST' && p === '/api/automations') {
+ return readBody(req).then((body) => {
+ try {
+ if (body && body.kind != null) throw new Error('任务包或索引不能作为本地任务执行');
+ const task = validateTask(body && body.task ? body.task : body);
+ const tasks = readAutomations(DATA_DIR);
+ const index = tasks.findIndex((item) => item.id === task.id);
+ if (index >= 0 && !isSupportedTaskSchema(tasks[index])) throw new Error('任务使用更新的协议,请升级 WorkDaddy 后再编辑');
+ if (index < 0 && tasks.length >= 200) throw new Error('自动化任务数量已达到上限');
+ if (index >= 0) tasks[index] = task; else tasks.unshift(task);
+ writeAutomations(DATA_DIR, tasks);
+ return json(res, 200, { ok: true, task });
+ } catch (error) { return json(res, 400, { ok: false, error: error.message }); }
+ });
+ }
+
+ if (req.method === 'POST' && p === '/api/automations/run') {
+ return readBody(req).then((body) => {
+ try {
+ const id = String(body && body.id || '').trim();
+ const task = readAutomations(DATA_DIR).find((item) => item.id === id);
+ if (!task) return json(res, 404, { ok: false, error: '自动化任务不存在' });
+ if (!canManuallyRunTask(task)) return json(res, 409, { ok: false, error: '此任务由事件或定时自动触发,无需手动运行' });
+ const running = Array.from(automationRuns.values()).find((run) => run.taskId === id && run.status === 'running');
+ if (running) return json(res, 409, { ok: false, error: '任务正在运行', run: automationPublicRun(running) });
+ const run = startAutomationRun(task);
+ return json(res, 202, { ok: true, run: automationPublicRun(run) });
+ } catch (error) { return json(res, 400, { ok: false, error: error.message }); }
+ });
+ }
+
+ if (req.method === 'GET' && p === '/api/automations/run-status') {
+ const run = automationRuns.get(String(url.searchParams.get('id') || ''));
+ return run ? json(res, 200, { ok: true, run: automationPublicRun(run) }) : json(res, 404, { ok: false, error: '运行记录不存在' });
+ }
+
+ if (req.method === 'POST' && p === '/api/automations/stop') {
+ return readBody(req).then(async (body) => {
+ const run = automationRuns.get(String(body && body.runId || ''));
+ if (!run) return json(res, 404, { ok: false, error: '运行记录不存在' });
+ // 当前执行器的网络/CDP调用由超时控制;停止请求先标记状态,避免新的批量运行进入。
+ if (run.status === 'running') { run.pendingEvent = null; run.status = 'cancelled'; run.finishedAt = Date.now(); run.error = '用户停止任务'; }
+ if (run.cleanupNotifications) await run.cleanupNotifications();
+ return json(res, 200, { ok: true, run: automationPublicRun(run) });
+ });
+ }
+
+ if (req.method === 'POST' && p === '/api/automations/bulk') {
+ return readBody(req).then((body) => {
+ try {
+ const ids = Array.isArray(body && body.ids) ? body.ids.map((id) => String(id || '').trim()).filter(Boolean).slice(0, 200) : [];
+ const action = String(body && body.action || '').trim();
+ const tasks = readAutomations(DATA_DIR);
+ const selected = tasks.filter((task) => ids.includes(task.id));
+ if (!selected.length) return json(res, 400, { ok: false, error: '未选择自动化任务' });
+ if (action === 'delete') {
+ writeAutomations(DATA_DIR, tasks.filter((task) => !ids.includes(task.id)));
+ } else if (action === 'enable' || action === 'disable') {
+ if (selected.some(task => !isTaskCompatible(task))) throw new Error('任务使用更新的协议,请升级 WorkDaddy 后再编辑');
+ selected.forEach((task) => { task.enabled = action === 'enable'; task.updatedAt = Date.now(); });
+ writeAutomations(DATA_DIR, tasks);
+ } else if (action === 'run') {
+ if (selected.some((task) => !canManuallyRunTask(task))) return json(res, 409, { ok: false, error: '此任务由事件或定时自动触发,无需手动运行' });
+ selected.forEach((task) => { if (!Array.from(automationRuns.values()).some((run) => run.taskId === task.id && run.status === 'running')) startAutomationRun(task); });
+ } else return json(res, 400, { ok: false, error: '不支持的批量操作' });
+ return json(res, 200, { ok: true, action, count: selected.length, tasks: readAutomations(DATA_DIR) });
+ } catch (error) { return json(res, 400, { ok: false, error: error.message }); }
+ });
+ }
+
if (req.method === 'GET' && p === '/api/ask-mode') {
return json(res, 200, { ok: true, ...getAskModeState() });
}
@@ -6051,11 +6962,13 @@ function handleApi(req, res) {
}
// 会话模块:POST /api/quick-phrase-send { text }(CDP 替换输入框内容并发送)
if (req.method === 'POST' && p === '/api/quick-phrase-send') {
- return readBody(req).then((body) =>
- acSendPhrase(body.text)
- .then(() => json(res, 200, { ok: true }))
- .catch((e) => json(res, 500, { ok: false, error: e.message }))
- );
+ log('[quick-phrase-diagnostics] api:received ' + JSON.stringify({ method: req.method, path: p }));
+ return readBody(req).then((body) => {
+ log('[quick-phrase-diagnostics] send:start ' + JSON.stringify({ textLen: String(body && body.text || '').length }));
+ return acSendPhrase(body.text)
+ .then((result) => { log('[quick-phrase-diagnostics] send:finish ' + JSON.stringify({ ok: true, result: result && { sent: result.sent, textLen: result.textLen } })); return json(res, 200, { ok: true }); })
+ .catch((e) => { log('[quick-phrase-diagnostics] send:finish ' + JSON.stringify({ ok: false, error: e.message })); return json(res, 500, { ok: false, error: e.message }); });
+ });
}
if (req.method === 'POST' && p === '/api/click') {
@@ -6080,7 +6993,9 @@ function handleApi(req, res) {
if (!uid) return json(res, 400, { ok: false, error: '缺少 uid' });
if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return json(res, 400, { ok: false, error: 'uid 格式无效' });
try {
+ const wasPrimary = primaryAccountStore.get() === uid;
const r = deleteAccount(DATA_DIR, uid, log);
+ if (wasPrimary) primaryAccountStore.set('');
const rulesRemoved = removeAutoCopyAccount(DATA_DIR, uid);
log(`[delete] 已永久删除账号备份 ${uid}(auth 存档清理 ${r.authFilesRemoved} 个)`);
return json(res, 200, { ok: true, deleted: r.deleted, uid, rulesRemoved, authFilesRemoved: r.authFilesRemoved });
@@ -6096,7 +7011,7 @@ function handleApi(req, res) {
return (async () => {
let quit = false;
let relaunched = false;
- const resolution = resolveCurrentAuth();
+ const resolution = resolveLogoutAuth();
if (!resolution.file || resolution.ambiguous) {
return json(res, 409, { ok: false, quit, relaunched, error: '当前登录文件无法唯一确认,已拒绝退出登录' });
}
@@ -6254,16 +7169,17 @@ function handleApi(req, res) {
return writeDiagnosticsSnapshot('api-post').then((snapshot) => json(res, 200, { ok: true, file: DIAGNOSTICS_FILE, diagnostics: snapshot }));
}
+ if (req.method === 'POST' && p === '/api/accounts/primary') {
+ return readBody(req).then((body) => {
+ try { return json(res, 200, { ok: true, primaryUid: primaryAccountStore.set(body.uid) }); }
+ catch (error) { return json(res, 400, { ok: false, error: error.message }); }
+ });
+ }
+
if (req.method === 'GET' && p === '/api/accounts') {
- // 面板打开即自动对全部账号签到(带每日缓存,幂等,不阻塞响应)
- // checkinStatus=1 仅回读缓存和队列状态,不重复触发一轮签到,供面板轮询使用。
- if (url.searchParams.get('checkinStatus') !== '1') {
- claimDailyForAll().catch((e) => log('[checkin] 自动签到失败: ' + e.message));
- }
const accounts = listAccounts(DATA_DIR);
const cache = loadCheckinCache();
const today = todayStr();
- const checkinPending = !!claimInFlight;
return CREDIT_USAGE_STORE.listDailyCheckins(accounts.map((a) => a.uid), today)
.catch((error) => {
log('[checkin] 读取 SQLite 标记失败: ' + error.message);
@@ -6276,7 +7192,8 @@ function handleApi(req, res) {
? c
: null;
return Object.assign({}, a, {
- checkin: checkinDisplayValue(checked, today, checkinPending),
+ checkin: checkinDisplayValue(checked, today),
+ activityStreak: growthStreakCache.peek(a.uid),
});
});
return listDailyUsage(enriched, today)
@@ -6284,11 +7201,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(), accounts: withUsage, checkin: checkinSnapshot() });
+ return json(res, 200, { ok: true, current: currentAccount(), primaryUid: primaryAccountStore.get(), accounts: withUsage });
})
.catch((error) => {
log('[credits-usage] 读取本地今日用量失败: ' + error.message);
- return json(res, 200, { ok: true, current: currentAccount(), accounts: enriched, checkin: checkinSnapshot() });
+ return json(res, 200, { ok: true, current: currentAccount(), primaryUid: primaryAccountStore.get(), accounts: enriched });
});
});
}
@@ -6341,6 +7258,18 @@ function handleApi(req, res) {
});
}
+ // Read-only per-account continuous activity count; never creates a conversation or changes accounts.
+ if (req.method === 'POST' && p === '/api/growth/streak') {
+ return readBody(req).then(async (body) => {
+ const uid = String(body && body.uid || '').trim();
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return json(res, 400, { ok: false, error: 'uid 格式无效' });
+ if (PROFILE.id !== 'workbuddy-cn') return json(res, 400, { ok: false, error: '当前客户端不支持成长活跃查询' });
+ if (!fs.existsSync(accountBackupFile(uid))) return json(res, 404, { ok: false, error: '账号备份不存在' });
+ const activityStreak = await growthStreakCache.get(uid);
+ return json(res, 200, { ok: true, uid, activityStreak });
+ });
+ }
+
// 查询指定账号今日是否活跃(成长中心热力墙 is_active)
if (req.method === 'POST' && p === '/api/growth/today-active') {
return readBody(req).then(async (body) => {
@@ -6652,7 +7581,7 @@ function handleApi(req, res) {
if (req.method === 'GET' && p === '/api/sleep-mode') {
let st = { mode: 'allow', displaySleep: false };
try { st = Object.assign(st, JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'sleep-mode.json'), 'utf8'))); } catch (_) {}
- return json(res, 200, { ok: true, mode: st.mode, displaySleep: !!st.displaySleep, preventing: st.mode === 'keep' || st.mode === 'until-done', active: !!sleepCaffeinate, antiLock: !!sleepUserActivityTimer });
+ return json(res, 200, { ok: true, mode: st.mode, displaySleep: !!st.displaySleep, preventing: st.mode === 'keep' || st.mode === 'until-done', active: !!(IS_WIN ? sleepPowershell : sleepCaffeinate), antiLock: !!sleepUserActivityTimer });
}
if (req.method === 'POST' && p === '/api/sleep-mode') {
return readBody(req).then((body) => {
@@ -7607,17 +8536,21 @@ function handleApi(req, res) {
}
} catch (_) { /* 读不到就跳过自动聚焦会话 */ }
try {
+ pendingAutomationAccountSwitch = { account: { uid: acct.uid, nickname: acct.nickname } };
await reloadWorkBuddyPage();
reloaded = true;
log('[switch] 已通过 CDP 刷新 WorkBuddy 窗口');
- // 切换后通过接口自动签到(带每日缓存,幂等)
- claimDailyForUid(uid)
- .then((r) => log('[checkin] 切换后自动签到 ' + uid + ': ' + (r.ok ? '已领取' : '失败 ' + (r.reason || r.message))))
- .catch((e) => log('[checkin] 切换后签到异常: ' + e.message));
+ // 某些 renderer 不发送 Page.loadEventFired;刷新流程已返回且新页面已挂载时兜底。
+ if (pendingAutomationAccountSwitch) {
+ const switchEvent = pendingAutomationAccountSwitch;
+ pendingAutomationAccountSwitch = null;
+ dispatchAutomationEvent('pageReady', { navigationSerial: mainFrameNavigationSerial, source: 'account-switch-fallback', account: switchEvent.account });
+ }
if (sourceSessionTitle) {
autoFocusSessionByTitle(sourceSessionTitle, log);
}
} catch (e) {
+ pendingAutomationAccountSwitch = null;
log(`[switch] CDP 刷新失败: ${e.message}`);
}
}
@@ -7724,7 +8657,7 @@ function applySleepMode(mode, displaySleep) {
return true;
}
const wantArgs = displaySleep ? '-i-s-m' : '-d-i-s-m';
- const curArgs = sleepCaffeinate ? sleepCaffeinate.spawnargs.slice(1).join('-') : null;
+ const curArgs = sleepCaffeinate ? sleepCaffeinate.spawnargs.slice(1).join('') : null;
const wantLock = !displaySleep; // 防锁屏仅在显示器保持唤醒时有效
const curLock = !!sleepUserActivityTimer;
if (curArgs === wantArgs && curLock === wantLock) return true; // 已按同样参数在防休眠(含防锁屏状态),无需重启
@@ -7734,7 +8667,7 @@ function applySleepMode(mode, displaySleep) {
log('[sleep] 禁止休眠已开启(模式=' + mode + (displaySleep ? ',允许显示器休眠,防锁屏关闭' : ',显示器保持唤醒,防锁屏开启') + ')');
} catch (e) { log('[sleep] 开启失败: ' + e.message); return false; }
} else {
- if (!sleepCaffeinate && !sleepUserActivityTimer) return true;
+ if (!sleepCaffeinate && !sleepPowershell && !sleepUserActivityTimer) return true;
stopCaffeinate();
log('[sleep] 禁止休眠已解除(允许电脑休眠)');
}
@@ -7924,6 +8857,12 @@ process.on('unhandledRejection', (reason) => {
ensureDirs(DATA_DIR, log);
if (!acquireDaemonLock()) process.exit(0);
+ensureAgentBridge(DATA_DIR, { profileId: PROFILE.id });
+const automationAgentInboxTimer = setInterval(() => {
+ 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}`));
+}, 1000);
+automationAgentInboxTimer.unref && automationAgentInboxTimer.unref();
CREDIT_USAGE_STORE.initialize().catch((error) => log('[credits-usage] 初始化数据库失败: ' + error.message));
// 首次启动初始化(新电脑 / 数据目录为空时):内置壁纸 + WorkDaddy 主题 + 默认蒙版 10%
initBuiltinAssets();
@@ -7941,18 +8880,26 @@ log(`登录信息文件: ${currentAuthFile() || '(未唯一确认)'}`);
log(`备份目录: ${DATA_DIR}`);
updateDebug('daemon-start', { authFile: currentAuthFile(), dataDir: DATA_DIR, appPath: IS_WIN ? WORKDADDY_DIR_WIN : macWorkDaddyAppPath(), apiPort: UI_PORT_BASE });
+for (const preset of ['close-buddy-popups.json', ...(PROFILE.capabilities.accounts ? ['keep-accounts-active.json'] : [])]) {
+ try { installBuiltinTask(DATA_DIR, path.join(__dirname, 'builtin/automations', preset)); }
+ catch (_) { log('[automation] 初始化内置任务失败'); }
+}
+if (PROFILE.capabilities.accounts && PROFILE.capabilities.checkin !== false) {
+ try { installBuiltinTask(DATA_DIR, path.join(__dirname, 'builtin/automations/daily-account-checkin.json')); }
+ catch (_) { log('[automation] 初始化签到任务失败'); }
+}
restoreSleepMode();
startServer();
cdpLoop();
-// 启动后给网络和本地存储留出就绪时间,再补一轮;之后每小时兜底。
-const startupCheckinTimer = setTimeout(() => {
- claimDailyForAll().catch((e) => log('[checkin] 启动签到失败: ' + e.message));
-}, CHECKIN_STARTUP_DELAY_MS);
-startupCheckinTimer.unref && startupCheckinTimer.unref();
-const periodicCheckinTimer = setInterval(() => {
- claimDailyForAll().catch((e) => log('[checkin] 定时签到失败: ' + e.message));
-}, CHECKIN_INTERVAL_MS);
-periodicCheckinTimer.unref && periodicCheckinTimer.unref();
+// All automatic check-in entry points are owned by the visible automation task.
+const tickAutomationSchedules = createScheduleTicker(DATA_DIR);
+function runAutomationSchedules() {
+ tickAutomationSchedules(readAutomations(DATA_DIR), startAutomationRun,
+ (id) => Array.from(automationRuns.values()).some((run) => run.taskId === id && run.status === 'running'));
+}
+runAutomationSchedules();
+const automationScheduleTimer = setInterval(runAutomationSchedules, 1000);
+automationScheduleTimer.unref && automationScheduleTimer.unref();
// 自动更新:启动时检查一次(延迟 8s 等网络就绪),之后每 6 小时一次
setTimeout(() => { checkUpdate(true).catch(() => {}); }, 8000);
updateTimer = setInterval(() => { checkUpdate(false).catch(() => {}); }, UPDATE_CHECK_INTERVAL);
diff --git a/scripts/growth-active.js b/scripts/growth-active.js
index 91fdfed..d2f401f 100644
--- a/scripts/growth-active.js
+++ b/scripts/growth-active.js
@@ -101,7 +101,7 @@ async function activateGrowthAccount(accessToken, options = {}) {
if (!accessToken || typeof fetchImpl !== 'function') throw new Error('成长活跃发起参数不完整');
const prompt = typeof options.prompt === 'string' && options.prompt.trim()
- ? options.prompt.trim().slice(0, 100)
+ ? options.prompt.trim().slice(0, options.purpose === 'completion-report' ? 2000 : 100)
: DEFAULT_GROWTH_PROMPT;
const model = typeof options.model === 'string' && options.model.trim()
? options.model.trim()
@@ -190,7 +190,7 @@ async function activateGrowthAccount(accessToken, options = {}) {
body: JSON.stringify({
prompt,
model,
- plugins: [{ name: 'weixinpay', marketplace: 'codebuddy-builtin' }],
+ plugins: options.purpose === 'completion-report' ? [] : [{ name: 'weixinpay', marketplace: 'codebuddy-builtin' }],
}),
});
const createdSession = created && created.session && typeof created.session === 'object' ? created.session : null;
@@ -241,7 +241,7 @@ async function activateGrowthAccount(accessToken, options = {}) {
}
await sendRpc(endpoint, { jsonrpc: '2.0', id: nextRpcId++, method: 'initialize', params: {
protocolVersion: 1,
- clientInfo: { name: 'workdaddy-growth', version: '1.1.31' },
+ clientInfo: { name: options.purpose === 'completion-report' ? 'workdaddy-report' : 'workdaddy-growth', version: '1.1.31' },
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
_meta: { 'codebuddy.ai': { question: false, terminalOutput: false } },
@@ -259,6 +259,7 @@ async function activateGrowthAccount(accessToken, options = {}) {
if (connectionId && runtimeToken) {
await fetchImpl(endpoint, {
method: 'DELETE',
+ signal: AbortSignal.timeout(3000),
headers: requestHeaders(apiHost, runtimeToken, { 'acp-connection-id': connectionId }),
}).catch(() => {});
}
@@ -326,4 +327,57 @@ async function fetchGrowthTodayActive(accessToken, options = {}) {
}
}
-module.exports = { fetchGrowthTodayActive, activateGrowthAccount };
+/** Official growth-center calendar reads data.streak.days (not monthly totals or heatmap score). */
+async function fetchGrowthStreak(accessToken, options = {}) {
+ const apiHost = String(options.apiHost || 'https://www.workbuddy.cn').replace(/\/+$/, '');
+ const fetchImpl = options.fetchImpl || globalThis.fetch;
+ if (!accessToken || typeof fetchImpl !== 'function') throw new Error('成长活跃查询参数不完整');
+ const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : GROWTH_ACTIVE_TIMEOUT_MS;
+ const { controller, timer } = timeoutSignal(timeoutMs);
+ try {
+ const response = await fetchImpl(`${apiHost}/activity/growth/streak`, {
+ method: 'GET', redirect: 'error', signal: controller.signal,
+ headers: requestHeaders(apiHost, accessToken, { referer: `${apiHost}/profile/growth-center` }),
+ });
+ const data = await readJsonResponse(response, '成长活跃');
+ const days = data && data.streak && data.streak.days;
+ if (!Number.isSafeInteger(days) || days < 0) throw new Error('成长活跃接口缺少有效连续天数');
+ return { days };
+ } catch (error) {
+ if (error && error.name === 'AbortError') throw new Error('成长活跃接口请求超时');
+ throw error;
+ } finally { clearTimeout(timer); }
+}
+
+function createGrowthStreakCache(load, options = {}) {
+ const now = options.now || Date.now;
+ const entries = new Map();
+ const pending = new Map();
+ const day = (at) => new Date(at).toDateString();
+ const peek = (uid) => {
+ const entry = entries.get(uid);
+ const at = now();
+ return entry && at < entry.expiresAt && day(at) === day(entry.fetchedAt)
+ ? { days: entry.days, status: entry.status, fetchedAt: entry.fetchedAt } : null;
+ };
+ const get = (uid) => {
+ const hit = peek(uid);
+ if (hit) return Promise.resolve(hit);
+ if (pending.has(uid)) return pending.get(uid);
+ const startedAt = now();
+ const request = Promise.resolve().then(() => load(uid)).then((result) => {
+ if (!result || !Number.isSafeInteger(result.days) || result.days < 0) throw new Error('Invalid streak');
+ return { days: result.days, status: 'ready' };
+ }).catch(() => ({ days: null, status: 'unavailable' })).then((result) => {
+ const value = { ...result, fetchedAt: startedAt };
+ entries.set(uid, { ...value, expiresAt: startedAt + (result.status === 'ready' ? 300000 : 30000) });
+ if (entries.size > 500) entries.delete(entries.keys().next().value);
+ return value;
+ }).finally(() => pending.delete(uid));
+ pending.set(uid, request);
+ return request;
+ };
+ return { get, peek };
+}
+
+module.exports = { fetchGrowthTodayActive, activateGrowthAccount, fetchGrowthStreak, createGrowthStreakCache };
diff --git a/scripts/inject.js b/scripts/inject.js
index 89de442..83df11c 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -7,7 +7,7 @@
* 3. 账号列表展示 昵称 / 手机(明文) / Token 过期时间(<7 天红字);不展示 uid/uin/上次登录
* 4. 每账号右侧为「发起会话」「切换」「删除」纯图标按钮;发起会话使用备份 token,不切换当前账号
* 5. 面板底部「退出登录」(假退出:仅退回登录页,token 不过期,可随时切回)
- * 6. 每日签到改为打开面板即自动调接口(见 daemon 的 claimDailyForAll),带每日缓存,无需按钮
+ * 6. 每日签到由自动化任务管理,账号页只显示当天已确认的签到状态
* 6. 备份由守护进程自动完成,面板不提供备份按钮
*
* 与后端通信:fetch 本地 daemon(__WBS_API__ 占位符在注入时替换为实际地址)
@@ -44,6 +44,78 @@ function createBuildLifecycle() {
};
}
+// 机器人闲置吸边:只监听指针位置,不拦截 WorkBuddy 事件;由 build lifecycle 清理。
+function createFabQuietMode(options) {
+ var fab = options.fab;
+ var win = options.window;
+ var doc = options.document;
+ var timer = null;
+ var near = false;
+ var alive = true;
+ var IDLE_MS = 5000;
+ var enabled = false;
+ try { enabled = options.storage.getItem(options.settingKey) === '1'; } catch (_) {}
+
+ // 用未变换的尺寸计算,避免旋转/过渡中的包围盒让靠近区域来回跳动。
+ function geometry() {
+ var width = fab.offsetWidth * 0.5;
+ var height = fab.offsetHeight * 0.5;
+ var right = parseFloat(fab.style.right) || 22;
+ var bottom = parseFloat(fab.style.bottom) || 22;
+ return { width: width, height: height, right: right,
+ left: win.innerWidth - right - width, centerY: win.innerHeight - bottom - height / 2 };
+ }
+ function cancel() {
+ if (timer !== null) clearTimeout(timer);
+ timer = null;
+ }
+ function wake() {
+ if (!alive) return;
+ cancel();
+ fab.classList.remove('is-quiet');
+ if (fab.classList.contains('hidden')) near = false;
+ if (!enabled || near || fab.classList.contains('hidden') || options.isDragging()) return;
+ timer = setTimeout(function () {
+ timer = null;
+ if (!alive || near || fab.classList.contains('hidden') || options.isDragging() || fab.contains(doc.activeElement)) return;
+ var box = geometry();
+ // 左转后头顶朝左:头部只露 4px;停靠时 CSS 隐藏天线。
+ fab.style.setProperty('--wbs-fab-quiet-shift', (box.right + box.width / 2 + box.height / 2 - 4) + 'px');
+ fab.classList.add('is-quiet');
+ }, IDLE_MS);
+ }
+ options.listen(win, 'pointermove', function (event) {
+ if (!enabled || event.pointerType === 'touch' || fab.classList.contains('hidden') || options.isDragging()) return;
+ var box = geometry();
+ var docked = fab.classList.contains('is-quiet');
+ // 停靠时只响应露出的头部附近;恢复后扩大保活范围,方便移向按钮点击。
+ var next = event.clientX >= (docked ? win.innerWidth - 18 : box.left - 24) &&
+ Math.abs(event.clientY - box.centerY) <= box.width / 2 + (docked ? 12 : 24);
+ if (next !== near) { near = next; wake(); }
+ }, { capture: true, passive: true });
+ options.listen(win, 'pointerout', function (event) {
+ if (!event.relatedTarget && near) { near = false; wake(); }
+ }, { passive: true });
+ options.listen(win, 'resize', function () { near = false; wake(); });
+ options.listen(fab, 'pointerenter', function (event) {
+ if (event.pointerType !== 'touch') near = true;
+ wake();
+ });
+ options.listen(fab, 'focusin', wake);
+ options.listen(fab, 'focusout', wake);
+ wake();
+ return {
+ wake: wake,
+ isEnabled: function () { return enabled; },
+ setEnabled: function (value) {
+ enabled = !!value;
+ try { options.storage.setItem(options.settingKey, enabled ? '1' : '0'); } catch (_) {}
+ wake();
+ },
+ destroy: function () { alive = false; cancel(); fab.classList.remove('is-quiet'); },
+ };
+}
+
// Keep the decision logic independent from DOM selectors so it can be regression-tested.
// `suspected` is intentionally conservative: it asks for human review instead of sending
// another prompt automatically when a provider stops without an explicit error.
@@ -556,15 +628,69 @@ 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 = {
- '账号': 'Accounts', '主题': 'Theme', '会话': 'Sessions', '模型': 'Models', '增强': 'Enhance', '电脑': 'Computer', '关于': 'About', '设置': 'Settings',
- '导出': 'Export', '导入': 'Import', '删除': 'Delete', '编辑': 'Edit', '保存': 'Save', '取消': 'Cancel', '确定': 'Confirm', '确认': 'Confirm', '复制': 'Copy', '切换': 'Switch', '启用': 'Enable', '停止': 'Stop',
+ '等待发送按钮可点击超时(5 秒),未发送': 'The send button was not ready within 5 seconds. Nothing was sent.',
+ '无法关闭面板,请重试': 'Could not close the panel. Please try again.',
+ '正在输入或切换账号,请稍后打开面板': 'Typing or switching accounts. Please open the panel in a moment.',
+ "逐账号例行发送固定提示词消息": "Send a fixed prompt with each account",
+ "依次切换所有账号,新建会话发送 1+1=,按会话回执等待回复完成,最后恢复开始时的账号。": "Switch through all accounts, send 1+1= in a new conversation, wait for each reply to finish, then restore the starting account.",
+ "依次切换所有账号,等待当前会话输入框出现后发送 1+1=,等待回复完成,最后恢复开始时的账号。": "Switch through all accounts, wait for the composer, send 1+1=, wait for each reply to finish, then restore the starting account.",
+ "页面就绪后自动关闭首页弹窗": "Close home popups when the page is ready",
+ "页面就绪后立即检查三类弹窗,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。": "Check for three types of home popups every 300 ms for about 30 seconds. Close any that reappear and restart detection after account switches.",
+ "循环账号静默签到": "Check in all accounts in the background",
+ "使用各账号 token 签到,不切换当前账号;跳过今日已签到账号。每小时、客户端加载和打开面板时检查。": "Check in with each account without switching the active account. Skip accounts already checked in today. Check hourly, on client load, and when the panel opens.",
+ "所有账号已按序处理完毕,已恢复开始时的账号": "All accounts have been processed. The starting account has been restored.",
+ "存在账号未完成处理,已尝试恢复开始时的账号": "Some accounts could not be processed. An attempt was made to restore the starting account.",
+ "该账号签到未成功,请检查登录状态或签到活动": "Check-in failed for this account. Check its login status and check-in availability.",
+ "识别到 Buddy 加油站弹窗,已关闭": "Buddy Fuel Station popup detected and closed.",
+ "已关闭相关玩法推荐,今日不再展示": "Related playbook recommendations dismissed for today.",
+ "已关闭首页活动弹窗": "Home activity popup closed.",
+ "会话输入框非空,未覆盖草稿、未发送": "The composer contains a draft. Nothing was overwritten or sent.",
+ '页面就绪': 'Page ready', '删除选中的': 'Delete selected', '删除该自动化任务?': 'Delete this automation task?', '删除选中的自动化任务?': 'Delete selected automation tasks?', '删除后无法恢复。': 'This cannot be undone.', '清除': 'Clear', '清除日志': 'Clear logs', '清除运行日志?': 'Clear run logs?', '仅清除已结束的运行记录。': 'Only completed run records will be cleared.', '清除日志失败': 'Failed to clear logs', '任务已启用': 'Task enabled', '任务已停用': 'Task disabled', '发送中': 'Sending',
+ '账号': 'Accounts', '主题': 'Theme', '会话': 'Sessions', '模型': 'Models', '增强': 'Enhance', '自动化': 'Automation', '电脑': 'Computer', '关于': 'About', '设置': 'Settings',
+ '导出': 'Export', '导入': 'Import', '删除': 'Delete', '编辑': 'Edit', '保存': 'Save', '取消': 'Cancel', '确定': 'Confirm', '确认': 'Confirm', '复制': 'Copy', '切换': 'Switch', '启用': 'Enable', '停用': 'Disable', '停止': 'Stop', '立即运行': 'Run now', '新建任务': 'New task', '刷新': 'Refresh', '步骤 JSON': 'Steps JSON', '任务说明': 'Task description', '任务名称': 'Task name', '调度': 'Schedule', '手动运行': 'Manual', '手动': 'Manual', '每小时': 'Hourly', '每天': 'Daily', '选择任务': 'Select tasks', '查看接口': 'View capabilities', '拾取元素': 'Pick element', '复制 XPath': 'Copy XPath', '运行中': 'Running', '已成功': 'Succeeded', '失败': 'Failed', '未运行': 'Not run', '页面加载完成': 'Page loaded', '账号切换完成': 'Account switched', '新自动化任务': 'New automation task', '任务已保存': 'Task saved', '任务已开始运行': 'Task started', '步骤 JSON 格式无效': 'Invalid steps JSON', '步骤 JSON 必须是数组': 'Steps JSON must be an array', '查看接口说明': 'View interface docs', '自动化接口协议': 'Automation interface protocol', '复制全部': 'Copy all', '接口协议已复制': 'Interface protocol copied', '暂无自动化任务,点击“新建任务”开始。': 'No automation tasks yet. Click “New task” to start.', '编辑任务': 'Edit task', '触发方式': 'Trigger', '插入点击步骤': 'Insert click step', 'XPath 已复制': 'XPath copied', '点击步骤已插入': 'Click step inserted', '请先拾取元素': 'Pick an element first', '加载自动化失败': 'Failed to load automations', '读取接口失败': 'Failed to read interfaces', '批量操作失败': 'Batch operation failed', '删除失败': 'Delete failed', '确认删除该任务?': 'Delete this task?', '执行': 'Apply', '已拾取': 'Picked', '运行失败': 'Run failed', '(副本)': ' (copy)', '查看提示词': 'View prompt', '交给 WorkBuddy 创建': 'Ask WorkBuddy to create', '正在打开新任务…': 'Opening a new task…', '已创建新会话,WorkBuddy 完成后任务会自动出现': 'New session created. The task will appear after WorkBuddy finishes.', 'WorkBuddy 创建失败': 'WorkBuddy creation failed', '加载示例失败': 'Failed to load examples', '暂无示例': 'No examples available', '运行日志': 'Run logs', '暂无运行日志': 'No run logs yet', '开始时间': 'Started', '结束时间': 'Finished', '捕获错误': 'Caught error', '暂无执行日志': 'No execution log entries', '执行日志': 'Execution log', '尚未结束': 'Still running',
'暂存提示词': 'Stash prompt', '暂存': 'Stashed', '引用文本': 'Quote text', '快捷短语': 'Quick phrases', '点击后发送': 'Send on click', '编辑 →': 'Edit →', '新增': 'Add', '批量操作': 'Batch actions', '批量管理': 'Batch manage', '全选': 'Select all', '取消全选': 'Deselect all', '已选 0': 'Selected 0',
'账号汇总': 'Account summary', '账号数': 'Accounts', '总积分': 'Total credits', '手机': 'Phone', '有效期至': 'Expires', '当前使用中': 'Currently active', '隐藏敏感信息': 'Mask sensitive info', '显示明文': 'Show plaintext', '登录新账号': 'Log in a new account', '没有可导出的账号备份': 'No account backups to export', '还没有备份账号。打开/登录一次 WorkBuddy 后会自动备份,稍后再来查看。': 'No account backups yet. Open or log in to WorkBuddy once and check again later.',
'语言': 'Language', '中文': 'Chinese', '英语': 'English', 'English': 'English', '跟随系统': 'Follow system', '设置语言': 'Language', '首次打开时自动跟随系统语言;未匹配时使用英语。': 'The first launch follows your system language. English is used when no match is found.', '语言设置已更新': 'Language updated',
'默认': 'Default', 'WorkDaddy 主题': 'WorkDaddy theme', '毛玻璃': 'Frosted glass', '护眼绿': 'Eye-care green', '赛博紫': 'Cyber purple', '主题外观': 'Theme appearance', '壁纸': 'Wallpaper', '头像': 'Avatar', '自定义壁纸': 'Custom wallpaper', '背景蒙版': 'Background overlay', '背景毛玻璃': 'Background blur', '恢复默认': 'Restore default', '恢复官方头像': 'Restore official avatar',
'加载中…': 'Loading…', '读取中…': 'Reading…', '正在读取设置…': 'Reading settings…', '查询中…': 'Checking…', '暂无快捷短语': 'No quick phrases', '暂无快捷短语,点击「+ 新增」添加': 'No quick phrases. Click “+ Add” to create one.', '当前还未添加模型': 'No models added yet', '还没有模型备份': 'No model backups yet', '当前筛选下没有会话': 'No sessions match the current filter', '暂无进行中的会话': 'No active sessions', '暂无官方壁纸': 'No built-in wallpapers', '还没有自定义壁纸,先上传一张': 'No custom wallpapers yet. Upload one to start.', '壁纸加载中…': 'Loading wallpapers…', '壁纸加载失败(daemon 不可达)': 'Wallpaper loading failed (daemon unavailable)',
'发送失败: ': 'Send failed: ', '发送失败': 'Send failed', '打开面板失败: ': 'Could not open panel: ', '设置失败: ': 'Settings failed: ', '设置失败': 'Settings failed', '请求失败': 'Request failed', '操作失败': 'Operation failed', '读取文件失败': 'Could not read file', '复制失败': 'Copy failed', '复制失败: ': 'Copy failed: ', '删除失败: ': 'Delete failed: ', '删除失败': 'Delete failed', '切换失败: ': 'Switch failed: ', '应用主题失败: ': 'Could not apply theme: ', '蒙版设置失败: ': 'Overlay setting failed: ', '毛玻璃设置失败: ': 'Blur setting failed: ', '诊断设置保存失败: ': 'Could not save diagnostics setting: ', '无法连接本地服务: ': 'Cannot connect to local service: ', '请确认守护进程已运行': 'Make sure the daemon is running',
- '签到中': 'Checking in', '今日已签到✓': 'Checked in today ✓', '无签到活动': 'No check-in activity', '登录身份过期': 'Login expired', '刚刚': 'Just now', '分钟前': ' minutes ago', '小时前': ' hours ago', '天前': ' days ago',
+ '执行中': 'Running', '已停用': 'Disabled', '示例': 'Examples', '手动触发': 'Manual trigger', '等待触发': 'Waiting for trigger', '上次已完成': 'Last completed', '上次失败': 'Last failed', '上次已停止': 'Last stopped', '停止本次执行': 'Stop this run', '手动任务无需自动触发': 'Manual tasks do not need automatic triggers', '启用自动触发': 'Enable automatic triggers', '成长计划连续活跃天数': 'Consecutive active days in Growth Plan', '活跃天数读取失败': 'Unable to read active days', '正在读取活跃天数': 'Loading active days', '活跃 ': 'Active ', '此任务由事件或定时自动触发,无需手动运行': 'This task runs automatically on its event or schedule', '当前客户端不支持成长活跃查询': 'Growth activity is unavailable in this client',
+ "天": "days", " 日": " day",
+ "定时已结束": "Schedule ended",
+ "定时方式": "Schedule",
+ "不定时": "No schedule",
+ "按间隔": "Interval",
+ "每天": "Daily",
+ "每周": "Weekly",
+ "每月": "Monthly",
+ "指定时间一次": "Once",
+ "单次": "Once",
+ "日期": "Date",
+ "时间": "Time",
+ "日期时间": "Date and time",
+ "执行时间": "Run time",
+ "账号刷新失败,已保留上次结果": "Account refresh failed; previous results kept",
+ "活跃读取失败": "Activity unavailable",
+ "每月日期": "Day of month",
+ "间隔数值": "Interval value",
+ "间隔单位": "Interval unit",
+ "执行日期和时间": "Run date and time",
+ "周一": "Mon",
+ "周二": "Tue",
+ "周三": "Wed",
+ "周四": "Thu",
+ "周五": "Fri",
+ "周六": "Sat",
+ "周日": "Sun",
+ "工作日": "Weekdays",
+ "按电脑本地时间执行;错过不补跑,运行中跳过。": "Uses local computer time. Missed or overlapping runs are skipped.",
+ "当月没有该日期时跳过。": "Skipped in months without this date.",
+ "请选择有效的执行时间": "Choose a valid run time",
+ "请至少选择一个星期": "Select at least one weekday",
+ "请选择将来的执行日期和时间": "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',
'发现新版本': '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',
@@ -572,13 +698,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'权限免打扰': 'Permission quiet mode', '异常中断会话': 'Continue interrupted sessions', '决策弹窗': 'Decision prompts', '用弹窗提问': 'Ask with a dialog', '确认弹窗自动允许': 'Auto-allow confirmation dialogs', '自动复制所有会话': 'Auto-copy all sessions', '会话消息索引': 'Message index', '引用消息文本': 'Quote message text', '选择登录方式': 'Choose a login method', '假退出': 'Soft logout', '无感登录': 'Seamless login',
'未设置': 'Not set', '当前使用中': 'Currently active', '停止生成': 'Stop generating', '正常重启': 'Restart normally', '清空日志': 'Clear log', '开发者工具': 'Developer tools', '隐藏功能': 'Hidden feature', '卡死': 'Stuck', '任务': 'Task', '空间': 'Workspace', '全部': 'All', '今天': 'Today', '近 7 天': 'Last 7 days', '近 30 天': 'Last 30 days', '企业配额': 'Enterprise quota', '积分到期分布': 'Credit expiry distribution',
'连接新服务…': 'Connecting to service…', '等待中': 'Waiting', '运行中': 'Running', '空闲': 'Idle', '已中断': 'Interrupted', '已停止': 'Stopped', '未确认': 'Unconfirmed', '等待确认': 'Waiting for confirmation', '等待新回复': 'Waiting for a new reply', '等待会话': 'Waiting for session', '等待允许': 'Waiting for approval', '整理中': 'Organizing', '恢复中': 'Restoring', '即将完成…': 'Finishing…', '已继续': 'Continued', '检测到会话异常中断,即将自动发送「': 'An interrupted session was detected. Sending “', '自动发送失败,请手动点击发送': 'Automatic send failed. Please click Send manually', '底层发送失败,请手动发送': 'Underlying send failed. Please send manually',
+ '导入中…': 'Importing…', ' 个任务': ' task(s)', '导入任务': 'Import tasks', '导出任务': 'Export tasks', '请先勾选要导出的任务': 'Select tasks to export first', '选择 JSON 或 ZIP 任务文件': 'Choose a JSON or ZIP task file', '读取任务文件…': 'Reading task file…', '任务导出成功': 'Tasks exported', '导入失败': 'Import failed', '导出失败': 'Export failed', '可导入': 'Ready to import', '已存在,将跳过': 'Already exists; skipped', '不兼容,无法导入': 'Incompatible; cannot import', '导入后保持停用,可在任务列表中启用。相同 ID 的任务会跳过。': 'Imported tasks stay disabled until you enable them. Existing task IDs are skipped.', '任务文件不能超过 8 MiB': 'Task files must not exceed 8 MiB', '缺少必填参数': 'Required inputs are missing', '需要更新 WorkDaddy': 'Requires a newer WorkDaddy version', '不支持当前客户端或系统': 'Unsupported client or platform', '文件不是自动化任务 JSON': 'Not an automation task JSON file', '任务格式或能力不受支持': 'Unsupported task format or capabilities',
'导出账号': 'Export accounts', '导入账号': 'Import accounts', '导出会话': 'Export sessions', '导入会话': 'Import sessions', '导出快捷短语': 'Export quick phrases', '导入快捷短语': 'Import quick phrases', '复制选中到其他账号': 'Copy selected to another account', '删除选中': 'Delete selected', '操作会话': 'Session actions', '连通测试': 'Test connection', '编辑模型': 'Edit model', '模型已保存': 'Model saved', '模型已启用': 'Model enabled', '模型已复制': 'Model copied', '模型配置已共用': 'Model configuration shared', '当前模型': 'Current model', '备选模型': 'Backup models', '模型加载失败:': 'Failed to load models: ', '保存模型失败:': 'Failed to save model: ', '删除当前模型失败:': 'Failed to delete current model: ', '启用模型失败:': 'Failed to enable model: ', '连通测试失败:': 'Connection test failed: ',
'选择要查看的账号': 'Choose an account to view', '选择账号并输入密码后导出备份': 'Choose accounts and enter a password to export backups', '从加密导出文件导入账号备份': 'Import account backups from an encrypted export', '使用密码导出选中会话': 'Export selected sessions with a password', '使用密码导出选中快捷短语': 'Export selected quick phrases with a password', '从加密文件导入会话': 'Import sessions from an encrypted file', '从加密文件导入快捷短语': 'Import quick phrases from an encrypted file', '仅支持 PNG / JPG / WebP': 'PNG / JPG / WebP only', '点击或拖拽上传壁纸': 'Click or drag to upload a wallpaper', '点击选择图片,或拖拽到此处': 'Click to choose an image, or drag it here', '支持 PNG / JPG / WebP,自动压缩;可添加多张': 'PNG / JPG / WebP supported; images are compressed automatically',
'未命名账号': 'Unnamed account', '未命名模型': 'Unnamed model', '未命名': 'Unnamed', '未知错误': 'Unknown error', '未知': 'Unknown', '有效期未知': 'Expiry unknown', '未找到输入框': 'Composer not found', '输入框内容为空': 'Composer is empty', '当前输入框暂不支持引用插入': 'The current composer does not support quote insertion', '引用插入失败,请重试': 'Could not insert quote. Please try again', '已引用选中文字': 'Selected text quoted', '短语不能为空': 'Quick phrase cannot be empty', '请输入快捷短语': 'Enter a quick phrase', '删除快捷短语': 'Delete quick phrase', '编辑快捷短语': 'Edit quick phrase', '新增快捷短语': 'Add quick phrase', '确定删除': 'Confirm deletion', '确认永久删除': 'Confirm permanent deletion',
'本机回环 CDP 注入 · 不改官方安装包': 'Local CDP injection · official app untouched', '一个基于 ': 'A ', ' 的 WorkBuddy 桌面端增强工具。零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。': ' WorkBuddy desktop enhancement tool using Chrome DevTools Protocol (CDP). No intrusion or re-signing; UI components are injected into the running renderer.', '问题反馈': 'Report an issue',
// —— 覆盖度补齐(分区域,模板条目支持 {name} 占位,匹配时最长优先)——
'(无标题)': 'Untitled', 'GitHub 仓库': 'GitHub repository', '去 GitHub Issues 反馈问题': 'Report an issue on GitHub', '在 GitHub 上给 WorkDaddy 点 Star': 'Star WorkDaddy on GitHub', 'WorkDaddy,点击打开面板,可拖动': 'WorkDaddy – click to open the panel, draggable', '如果 WorkDaddy 对你有帮助,欢迎在 GitHub 点个 Star。你的支持会让这个小项目持续更新。': 'If WorkDaddy helps you, please star it on GitHub. Your support keeps this small project alive.',
- '元素检查': 'Inspect element', '元素检查不可用:内部模块未加载': 'Element inspector unavailable: internal module not loaded',
+ '元素检查': 'Inspect element', '元素检查不可用:内部模块未加载': 'Element inspector unavailable: internal module not loaded', '元素拾取器尚未加载': 'Element picker is not loaded',
+ 'DOM 元素检查器': 'DOM element inspector', '复制元素': 'Copy element', '关闭元素检查器': 'Close element inspector', '已复制元素': 'Element copied', '未找到可检查元素': 'No inspectable element found', '检查失败:': 'Inspection failed: ', '拾取模式:移动鼠标高亮元素,点击选中(Esc 退出)': 'Pick mode: move to highlight an element, click to select (Esc to exit)',
'到期时间': 'Expiry', '剩余': 'Remaining', '剩余时间计算中': 'Calculating remaining time', '积分': 'Credits', '积分查询超时': 'Credit query timed out', '个人版': 'Personal', '企业': 'Enterprise', '基础用量': 'Base usage', '赠送与加量包': 'Gift & bonus packs', '其他积分': 'Other credits', '即将过期': 'Expiring soon', '已过期': 'Expired',
'昨天': 'Yesterday', '分钟': ' min', '小时': ' h', '定位到第': 'Jump to message ', '条用户消息': ' user message', '发送中': 'Sending', '附件': 'Attachment', '疑似未完成': 'Possibly incomplete',
'已开启': 'Enabled', '已关闭': 'Disabled', '已领取': 'Claimed', '立即领取,今日可领': 'Claim now, available today', '继续执行': 'Continue',
@@ -601,7 +729,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'正在解包新应用…': 'Unpacking new app…', '挂载 dmg 失败:': 'Failed to mount dmg:', '缺少解包后的新应用': 'Unpacked new app missing', '解包应用失败': 'Failed to unpack app', '缺少 apply-update.sh': 'apply-update.sh missing', '(仓库暂无 Release)': ' (no Releases in the repository yet)', 'auth/state 响应缺少 state': 'auth/state response is missing state',
'WBSWITCH_WORKBUDDY_BIN 不是可验证的当前 profile 主程序;登录信息未修改': 'WBSWITCH_WORKBUDDY_BIN is not a verified main program for the current profile; login info unchanged', '无法以普通用户权限安全退出 WorkBuddy。请手动关闭该程序;若它以管理员身份运行,请先退出后再重试。登录信息未修改': 'Cannot safely quit WorkBuddy at standard user privilege. Please close it manually; if it runs as admin, quit it first and retry. Login info unchanged', '未找到 WorkBuddy 可执行文件,无法安全退出;登录信息未修改': 'WorkBuddy executable not found; cannot quit safely. Login info unchanged', 'workbuddy-target.json 指定的路径不是可验证的当前 profile 主程序;登录信息未修改': 'The path in workbuddy-target.json is not a verified main program for the current profile; login info unchanged', '存在当前 profile 进程,但没有进程属于已验证安装目录;登录信息未修改': 'A current profile process exists, but none belongs to a verified install directory; login info unchanged', '检测到当前 profile 正从另一安装目录运行,登录信息未修改': 'The current profile is running from another install directory; login info unchanged', '检测到多个 dormant WorkBuddy 安装目录,按发现优先级选择:': 'Multiple dormant WorkBuddy installs found; selecting by discovery priority:', 'WorkBuddy 数据目录不是受管目录': 'WorkBuddy data directory is not managed', 'WorkBuddy 页面尚未完成加载': 'WorkBuddy page has not finished loading', '刷新 WorkBuddy 页面': 'Refresh WorkBuddy page', '注入脚本页面抛错': 'Injected script page threw an error', '读取注入脚本失败:': 'Failed to read the injected script:', '运行时桥接文件未生成': 'Runtime bridge file was not created',
// —— 第三批:daemon 端口/路径校验/发送链路错误(可能进入 toast/API 返回)——
- '9222-9232、9333 均被占用,无法为 WorkBuddy 分配 CDP 端口': 'Ports 9222-9232 and 9333 are all occupied; cannot allocate a CDP port for WorkBuddy', 'cwd 不是绝对路径': 'cwd is not an absolute path', 'cwd 路径包含符号链接或普通文件': 'cwd path contains a symlink or regular file', '发送按钮禁用(输入内容未被识别)': 'Send button disabled (input not recognized)', '无法清空输入框': 'Could not clear the composer', '无法聚焦输入框': 'Could not focus the composer', '未找到发送按钮': 'Send button not found', '未找到操作栏': 'Toolbar not found',
+ '9222-9232、9333 均被占用,无法为 WorkBuddy 分配 CDP 端口': 'Ports 9222-9232 and 9333 are all occupied; cannot allocate a CDP port for WorkBuddy', 'cwd 不是绝对路径': 'cwd is not an absolute path', 'cwd 路径包含符号链接或普通文件': 'cwd path contains a symlink or regular file', '发送按钮禁用(输入内容未被识别)': 'Send button disabled (input not recognized)', '无法清空输入框': 'Could not clear the composer', '无法聚焦输入框': 'Could not focus the composer', '未找到发送按钮': 'Send button not found', '未找到操作栏': 'Toolbar not found', 'Agent 提示词为空或过长': 'Agent prompt is empty or too long', 'Agent 提示词未发送,请重试': 'Agent prompt was not sent; try again',
+ '发送内容为空': 'Message is empty',
// —— 第四批:真机扫描发现的整句/半动态拼接(杜绝中英混合)——
'全部开': 'Enable all', '一键批量开启/关闭全部免打扰开关': 'Toggle all quiet-mode switches at once',
'沙箱外写文件免确认': 'Write outside the sandbox without confirmation', '工作区外文件直接读写': 'Direct read/write of files outside the workspace',
@@ -620,13 +749,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'在会话左侧显示消息索引': 'Show the message index on the left side of sessions', '选中会话消息中的文字后显示引用按钮': 'Show the quote button after selecting session message text',
'状态机日志': 'state machine log', '监控激活会话中': 'Monitoring active sessions',
'更换头像': 'Change avatar', '黑色半透明遮罩,压暗背景图': 'Black translucent overlay that dims the wallpaper',
+ '机器人自动停靠': 'Auto-dock robot', '闲置 5 秒后收起到窗口右侧,鼠标靠近边缘展开': 'Tuck into the right edge after 5 idle seconds; move near the edge to reveal',
'时间': 'Time', '自动复制': 'Auto-copy', '模型名': 'Model name', '自定义名称': 'Custom name', '确认操作': 'Confirm operation', '小贴士': 'Tip',
'解决 WorkBuddy 不支持多个同名模型的问题。': 'Solves WorkBuddy not supporting multiple models with the same name.',
'清空': 'Clear', '继续': 'Continue', '更换': 'Change',
'共 {n} 个': 'Total: {n} ', '展开 {n} 条(': 'Show {n} (', '从 {src} 导入': 'Import from {src}',
'(': '(', ')': ')',
// —— 第五批:基础高频词(杜绝词根缺失造成的半句混合)+ 会话/模型/账号错误整句 ——
- '错误': 'Error', '状态': 'Status', '导航': 'navigation', '消息': 'message', '当前': 'Current', '配置': 'config', '无效': 'invalid', '接口': 'API', '队列': 'queue', '不可用': 'unavailable', '缺少': 'Missing',
+ '错误': 'Error', '状态': 'Status', '导航': 'navigation', '消息': 'message', '当前': 'Current', '配置': 'config', '无效': 'invalid', '接口': 'API', '队列': 'queue', '不可用': 'unavailable', '缺少': 'Missing', '未找到页面元素': 'Page element not found', '页面元素不可见': 'Page element is not visible', '无法聚焦页面元素': 'Could not focus page element', 'HTTP URL 仅支持 http(s)': 'HTTP URL must use http(s)', '运行记录不存在': 'Run record not found',
'会话错误': 'Session error', '会话状态': 'Session status', '会话消息导航': 'Session message navigation', '未获取到当前会话': 'Could not get the current session',
'回复已停止,但没有发现明确完成证据': 'Reply stopped without clear completion evidence',
'会话正在等待决策确认': 'Session awaiting a decision confirmation', '会话出现模型或网络错误': 'Session hit a model or network error',
@@ -761,6 +891,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'单次最多导入 {n} 个会话': 'Import at most {n} sessions at a time', '单次最多处理 {n} 条快捷短语': 'Process at most {n} quick phrases at a time',
'快捷短语标识不能为空': 'Quick phrase id cannot be empty', '未选择快捷短语': 'No quick phrase selected', '没有可导出的快捷短语': 'No quick phrases to export',
'没有可导出的会话': 'No sessions to export', '未选择会话': 'No session selected', '导入文件中没有会话数据': 'No session data found in the import file',
+ 'WorkBuddy 通知组件未就绪': 'WorkBuddy notification component is not ready',
+ '通知组件未加载': 'Notification component not loaded', '通知组件已关闭': 'Notification component closed',
+ '暂不支持 iframe 内的输入或点击,请使用主页面定位器': 'Input and clicks inside iframes are unsupported; use a main-page locator', 'HTTP 响应超过 1 MiB': 'HTTP response exceeds 1 MiB', '任务不兼容': 'Incompatible task', '任务与当前 WorkDaddy 不兼容,请升级或使用适配版本': 'This task is incompatible with this WorkDaddy. Update or use a compatible version.', '排队中': 'Queued', '页面加载': 'Page load', '账号切换后': 'After account switch', '让 WorkBuddy 帮我创建': 'Create with WorkBuddy', '自动化需求': 'Automation requirements', '描述触发时机和需要执行的操作,WorkBuddy 会生成任务并添加到自动化列表。': 'Describe when to trigger and what to do. WorkBuddy will create the task in your automation list.', '例如:每次打开面板时,显示一条欢迎提示。': 'For example: show a welcome notification whenever the panel opens.', '将在新的 WorkBuddy 会话中创建': 'Creates in a new WorkBuddy conversation', '自动化需求必须是 1–6000 字的文本': 'Automation requirements must contain 1–6000 characters',
+ '一键创建': 'Quick create', '主账号': 'Primary', '设为主账号': 'Set as primary account', '已设为主账号,自动化任务可据此识别主账号': 'Primary account set. Automations can use it to identify your primary account.',
+ '原输入框草稿已保存到暂存': 'Your previous draft was saved to Stash.',
+ '设置主账号失败': 'Failed to set primary account',
'无效会话记录': 'Invalid session record', '没有可导入的会话': 'No sessions to import', '会话文件目标不在 managed parent 内': 'Session file target is outside the managed parent',
'无法确认 WorkBuddy 已退出': 'Could not confirm WorkBuddy has quit',
'未找到 WorkBuddy 可执行文件,无法验证运行中的进程': 'WorkBuddy executable not found; cannot verify the running process',
@@ -782,6 +918,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'导入文件中没有快捷短语': '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',
'默认(浅色)': 'Default (light)', '对话持续回复中(等待 {n} 秒仍未空闲),已取消发送,请稍后再试': 'The conversation is still replying (not idle after {n}s); send cancelled, please retry later',
+ '页面元素被遮挡或禁用,稍后重试': 'The element is covered or disabled; retry later',
+ '页面已切换,重新检测新页面': 'Page changed; checking the new page',
'导出数据不完整或已损坏': 'Export data is incomplete or corrupted', '文件不是有效的导出 JSON': 'The file is not a valid export JSON',
'不是 WorkDaddy 的账号导出文件': 'Not a WorkDaddy account export file', '导入文件中没有账号数据': 'No account data found in the import file',
'未读取到有效内容,请选择导出文件': 'No valid content read; please choose an export file', '密码不能超过 1024 个字符': 'Password cannot exceed 1024 characters',
@@ -894,6 +1032,49 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return out;
}
+ function wbsBuiltinAutomationText(task, field) {
+ var defaults = {
+ "daily-account-checkin": {
+ "name": [
+ "循环账号静默签到"
+ ],
+ "description": [
+ "使用各账号 token 签到,不切换当前账号;跳过今日已签到账号。每小时、客户端加载和打开面板时检查。"
+ ]
+ },
+ "keep-accounts-active-1-plus-1": {
+ "name": [
+ "逐账号例行发送固定提示词消息"
+ ],
+ "description": [
+ "依次切换所有账号,新建会话发送 1+1=,按会话回执等待回复完成,最后恢复开始时的账号。",
+ "依次切换所有账号,等待当前会话输入框出现后发送 1+1=,等待回复完成,最后恢复开始时的账号。"
+ ]
+ },
+ "buddy-fuel-station-close-on-account-switch": {
+ "name": [
+ "页面就绪后自动关闭首页弹窗"
+ ],
+ "description": [
+ "页面就绪后立即检查三类弹窗,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。"
+ ]
+ }
+ };
+ var values = task && defaults[task.id] && defaults[task.id][field];
+ return !!values && values.indexOf(task[field]) >= 0;
+ }
+
+ function wbsAutomationText(task, field) {
+ var text = String(task && task[field] || '');
+ return WBS_LANGUAGE === 'en' && wbsBuiltinAutomationText(task, field) ? WBS_I18N_EN[text] : text;
+ }
+
+ function wbsAutomationEditedText(task, field, value) {
+ var text = String(value || '').trim();
+ // Saving only a schedule edit must not persist the English display translation.
+ return task && text === wbsAutomationText(task, field) ? task[field] : text;
+ }
+
// ===== 全局错误钩子:捕获渲染进程不可捕获的 error / unhandledrejection,把完整消息+栈
// 打到 daemon 日志。渲染进程级崩溃(如 An object could not be cloned)虽非 try/catch 能拦,
// 但很多是经 promise/microtask 抛出的可拦异常——这里统一兜住并留痕。
@@ -921,11 +1102,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var accountMaskEnabled = false;
try { accountMaskEnabled = localStorage.getItem(WBS_ACCOUNT_MASK_KEY) === '1'; } catch (_) {}
- var state = { accounts: [], current: null, open: false, batchRunning: false, creditRunId: 0, creditRemaining: 0, creditSummaryValue: null, checkinPollId: null, mask: accountMaskEnabled };
+ var state = { accounts: [], current: null, open: false, batchRunning: false, creditRunId: 0, activityRunId: 0, creditRemaining: 0, creditSummaryValue: null, mask: accountMaskEnabled };
var currentBuild = null;
// 当前注入的 daemon 版本号(由 daemon.js 注入时把 __WBS_VERSION__ 替换为 DAEMON_VERSION)
// 「关于」tab 直接展示,升级 daemon 后这里自动同步
var WBS_VERSION = '__WBS_VERSION__';
+ function wbsClientVersion(userAgent) {
+ // Electron UA 带宿主版本;不能把 Chrome/Electron 版本当作 WorkBuddy 版本。
+ var product = WBS_PROFILE_IS_AI ? /(?:^|\s)WorkBuddy(?:AI|[- ]AI)\/(\d+(?:\.\d+){1,3})(?=\s|$)/i : /(?:^|\s)WorkBuddy\/(\d+(?:\.\d+){1,3})(?=\s|$)/i;
+ var match = product.exec(String(userAgent || ''));
+ // 一些国际版仍使用 WorkBuddy 作为 UA 产品名。
+ if (!match && WBS_PROFILE_IS_AI) match = /(?:^|\s)WorkBuddy\/(\d+(?:\.\d+){1,3})(?=\s|$)/i.exec(String(userAgent || ''));
+ return match ? match[1] : '';
+ }
var WBS_LANGUAGE = (function () {
try {
var saved = localStorage.getItem(WBS_LANGUAGE_KEY);
@@ -935,6 +1124,7 @@ 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>';
@@ -956,9 +1146,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m4 16-.8 4.8L8 20l11.5-11.5a2.1 2.1 0 0 0-3-3L5 17z"/><path d="m14.5 7.5 2 2"/></svg>';
var MODEL_ENABLE_SVG =
'<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor"><path d="M8 5.2a1 1 0 0 1 1.55-.83l9.6 6.8a1 1 0 0 1 0 1.66l-9.6 6.8A1 1 0 0 1 8 18.8V5.2Z"/></svg>';
+ var AUTO_STOP_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="1.5"/></svg>';
+ // 停止中:loading 转圈(弧线 + 缺口,配合 .wbs-auto-stopping 的旋转动画)
+ var AUTO_STOPPING_SVG =
+ '<svg class="wbs-auto-stopping-svg" viewBox="0 0 24 24" width="15" height="15" fill="none" aria-hidden="true"><circle cx="12" cy="12" r="8" stroke="currentColor" stroke-width="2.2" opacity="0.25"/><path d="M20 12a8 8 0 0 0-8-8" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>';
// 小贴士提示图标(灯泡,tips 通知风格)
var MODEL_TIP_SVG =
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18h6"/><path d="M10 22h4"/><path d="M12 2a7 7 0 0 0-4 12.7c.6.5 1 1.4 1 2.3h6c0-.9.4-1.8 1-2.3A7 7 0 0 0 12 2Z"/></svg>';
+ var AUTO_LOG_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 3h8l4 4v14H7z"/><path d="M15 3v5h5"/><path d="M10 12h6M10 16h6"/></svg>';
+ var AUTO_PICK_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 4h6M4 4v6M20 4h-6M20 4v6M4 20h6M4 20v-6M20 20h-6M20 20v-6"/><circle cx="12" cy="12" r="2.5"/></svg>';
var GIFT_SVG =
'<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<rect x="3" y="8" width="18" height="4" rx="1"/>' +
@@ -970,10 +1169,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>' +
'<polyline points="16 17 21 12 16 7"/>' +
'<line x1="21" y1="12" x2="9" y2="12"/></svg>';
- // 当前使用中角标:回复/右转箭头(用户指定图形,颜色跟随昵称文字色)
- var CUR_MARK_SVG =
- '<svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true">' +
- '<path fill="currentColor" d="M4.472 4.75c-.597 0-1.293.166-1.862.519c-.58.358-1.11.974-1.11 1.856v9.75c0 .882.53 1.497 1.11 1.856c.57.353 1.265.519 1.862.519H14.77a2.75 2.75 0 0 0 1.92-.781l5.35-5.216a1.75 1.75 0 0 0 0-2.506l-5.35-5.216a2.75 2.75 0 0 0-1.92-.781z"/></svg>';
// 积分余额图标:AI 四芒星线条矢量(无背景色,currentColor 跟随文字色)
var CREDIT_ICON =
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">' +
@@ -1037,21 +1232,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function escAttr(t) { return esc(t).replace(/"/g, '&quot;').replace(/'/g, '&#39;'); }
function checkinHtml(a) {
- // 国际版不开放签到活动:积分卡上的签到标签整体不展示(CN 版保留完整逻辑)
- if (PROFILE_ID === 'workbuddy-ai') return '';
+ if (WBS_PROFILE_IS_AI) return '';
var c = a && a.checkin;
- if (!c) return '<span class="wbs-ck wbs-checkin-tag pending">签到中</span>';
- var msg = c.message || '';
- // 国际版/活动空窗期:接口 code 10001 且文案表明「活动未开启/未开始/已过期」时,
- // 并不是“今日已签到”,不应展示绿色成功标签,改为中性「无签到活动」。
- if (c.inactive || (c.ok && /未开启|未开始|未开放|已过期|无.*活动|活动.*(结束|关闭|暂停)/i.test(msg))) {
- return '<span class="wbs-ck wbs-checkin-tag pending">无签到活动</span>';
- }
- // “本轮刚领取”和“今天已领取过”都是成功态,统一展示避免同一页面出现两套文案。
- if (c.ok) return '<span class="wbs-ck wbs-checkin-tag ok">今日已签到✓</span>';
- // 认证类错误(401/未授权)统一显示友好文案(daemon 已产出,缓存残留旧文案时兜底)
- if (/401|Unauthorized|未授权|登录身份过期/.test(msg)) msg = '登录身份过期';
- return '<span class="wbs-ck wbs-checkin-tag fail">' + esc(msg) + '</span>';
+ var checked = !!(c && c.ok && !c.inactive);
+ return '<span class="wbs-ck wbs-checkin-tag ' + (checked ? 'ok' : 'pending') + '" title="' + (checked ? '今日已签到' : '今日尚未签到') + '">今日签到</span>';
+ }
+
+ function activityStreakHtml(a) {
+ if (WBS_PROFILE_IS_AI) return '';
+ var value = a && a.activityStreak;
+ if (!isKnownActivityStreak(value)) {
+ if (!value || value.status !== 'unavailable') return '';
+ return '<span class="wbs-ck wbs-checkin-tag wbs-activity-tag pending" title="活跃天数读取失败">活跃读取失败</span>';
+ }
+ return '<span class="wbs-ck wbs-checkin-tag wbs-activity-tag ' + (value.days > 0 ? 'ok' : 'pending') + '" title="成长计划连续活跃天数">活跃 ' + value.days + ' 天</span>';
+ }
+
+ function isKnownActivityStreak(value) {
+ return !!(value && value.status === 'ready' && Number.isSafeInteger(value.days) && value.days >= 0);
}
function el(tag, cls, text) {
@@ -1327,17 +1525,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
target.addEventListener(type, handler, options);
registerDisposer(function () { target.removeEventListener(type, handler, options); });
}
+ var toastRuntime = window.__wbsToastRuntime;
+ if (!toastRuntime) throw new Error('通知组件未加载');
+ registerDisposer(function () { toastRuntime.destroy(); });
function toast(msg, isErr, targetRoot) {
if (!alive) return;
- var t = el('div', 'wbs-toast' + (isErr ? ' err' : ''));
- t.textContent = String(msg == null ? '' : msg);
- (targetRoot || document.body).appendChild(t);
- applyI18n(t);
- setBuildTimeout(function () {
- t.classList.add('out');
- setBuildTimeout(function () { t.remove(); }, 300);
- }, 4200);
+ return toastRuntime.show({ message: wbsTranslateString(String(msg == null ? '' : msg), WBS_LANGUAGE), level: isErr ? 'error' : 'info' });
+ }
+ function receiveToast(detail) {
+ if (!alive) throw new Error('通知组件已关闭');
+ if (detail.action === 'dismiss') { toastRuntime.dismiss(detail.id); return { ok: true, id: detail.id }; }
+ var id = toastRuntime.show(Object.assign({}, detail, { message: wbsTranslateString(String(detail.message || ''), WBS_LANGUAGE) }));
+ return { ok: true, id: id };
}
+ window.__wbsNotifyToast = receiveToast;
+ registerDisposer(function () { if (window.__wbsNotifyToast === receiveToast) delete window.__wbsNotifyToast; });
function isVisibleHealthNode(node) {
if (!node || !node.isConnected || (node.closest && node.closest('.wbs-root'))) return false;
@@ -1650,7 +1852,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function applyInjectedI18n() {
applyI18n(root);
- var nodes = document.querySelectorAll('.wbs-stash-inline,.wbs-selection-quote-btn,.wbs-queue-tag,.wbs-message-nav-root');
+ var nodes = document.querySelectorAll('.wbs-stash-inline,.wbs-selection-quote-btn,.wbs-queue-tag,.wbs-message-nav-root,#wbs-auto-inspector,#wbs-auto-inspect-tip');
for (var i = 0; i < nodes.length; i++) applyI18n(nodes[i]);
}
window.__wbsSetLanguage = setLanguage;
@@ -1683,12 +1885,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-panel">',
'<div class="wbs-head">',
'<div class="wbs-head-left">',
- '<div class="wbs-title" id="wbs-title" title="WorkDaddy">' + WBS_BRAND + '</div>',
+ '<div class="wbs-title-wrap"><div class="wbs-title-row"><div class="wbs-title" id="wbs-title" title="WorkDaddy">' + WBS_BRAND + '</div>',
'<button class="wbs-pick-btn" id="wbs-pick-btn" type="button" style="display:none" title="元素检查">🔍</button>',
'<span class="wbs-health-status" id="wbs-health-status" aria-live="polite"></span>',
'<a class="wbs-ghbtn" href="https://github.com/babygoton/WorkDaddy" target="_blank" rel="noopener" title="GitHub 仓库">',
'<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M12 .3a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.03c-3.34.73-4.04-1.61-4.04-1.61-.55-1.39-1.33-1.76-1.33-1.76-1.09-.74.08-.73.08-.73 1.2.09 1.84 1.24 1.84 1.24 1.07 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.66-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.11-3.18 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 0 1 6.01 0c2.29-1.55 3.3-1.23 3.3-1.23.65 1.66.24 2.88.12 3.18.77.84 1.23 1.91 1.23 3.22 0 4.61-2.81 5.62-5.49 5.92.43.37.82 1.1.82 2.22v3.29c0 .32.22.7.83.58A12 12 0 0 0 12 .3z"/></svg>',
'</a>',
+ '</div><div class="wbs-version-line" id="wbs-version-line"></div></div>',
'</div>',
'<button class="wbs-btn-close" type="button" data-act="close">✕</button>',
'</div>',
@@ -1698,6 +1901,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<button class="wbs-tab" type="button" data-tab="sessions"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg><span>会话</span></button>',
'<button class="wbs-tab" type="button" data-tab="models"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 2 9 5-9 5-9-5 9-5Z"/><path d="m3 12 9 5 9-5"/><path d="m3 17 9 5 9-5"/></svg><span>模型</span></button>',
'<button class="wbs-tab" type="button" data-tab="enhance"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg><span>增强</span></button>',
+ '<button class="wbs-tab" type="button" data-tab="automations"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 8V4H9"/><rect x="4" y="8" width="16" height="12" rx="3"/><path d="M2 12v4M22 12v4M9 12v2M15 12v2M9 17h6"/></svg><span>自动化</span></button>',
'<button class="wbs-tab" type="button" data-tab="pc"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg><span>电脑</span></button>',
'<button class="wbs-tab" type="button" data-tab="about"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg><span>关于</span></button>',
'</div>',
@@ -1707,12 +1911,23 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-pane" data-pane="sessions"></div>',
'<div class="wbs-pane" data-pane="models"></div>',
'<div class="wbs-pane" data-pane="enhance"></div>',
+ '<div class="wbs-pane" data-pane="automations"></div>',
'<div class="wbs-pane" data-pane="pc"></div>',
'<div class="wbs-pane" data-pane="about"></div>',
'</div>',
'</div>',
].join('');
document.body.appendChild(root);
+ var versionLine = root.querySelector('#wbs-version-line');
+ if (versionLine) {
+ var wbVersion = wbsClientVersion(navigator.userAgent);
+ var pluginVersion = WBS_VERSION && WBS_VERSION.indexOf('__WBS_') !== 0 ? WBS_VERSION : '';
+ versionLine.textContent = wbVersion ? wbVersion + (pluginVersion ? ' (' + pluginVersion + ')' : '') : (pluginVersion ? '(' + pluginVersion + ')' : '');
+ }
+ listen(window, 'workdaddy:automation-toast', function (event) {
+ var detail = event && event.detail && typeof event.detail === 'object' ? event.detail : {};
+ if (detail.message || detail.action === 'dismiss') receiveToast(detail);
+ });
try {
document.documentElement.setAttribute('data-wbs-language', WBS_LANGUAGE);
document.documentElement.setAttribute('lang', WBS_LANGUAGE === 'zh' ? 'zh-CN' : 'en');
@@ -1763,6 +1978,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 这样无需自己去扫描 Slate 编辑器,和官方发送按钮行为完全一致。
var stashBtn = document.createElement('div');
stashBtn.className = 'wbs-stash-inline';
+ stashBtn.style.display = 'none';
stashBtn.setAttribute('role', 'button');
stashBtn.setAttribute('tabindex', '0');
stashBtn.title = '暂存提示词';
@@ -1826,12 +2042,25 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
// 面板关闭/重开:点击选项(发送/编辑/任意项)后关闭面板;重新进入按钮区恢复 hover 可展示
+ function qpDiag(event, extra) {
+ if (!WBS_DIAGNOSTICS_ENABLED) return;
+ try {
+ var a = document.activeElement;
+ var r = a && a.getBoundingClientRect ? a.getBoundingClientRect() : null;
+ var payload = { event: event, href: location.href, title: document.title, active: a ? { tag: a.tagName, id: a.id || '', cls: typeof a.className === 'string' ? a.className.slice(0, 160) : '', text: (a.innerText || a.textContent || '').trim().slice(0, 100), rect: r ? { x: r.x, y: r.y, w: r.width, h: r.height } : null } : null };
+ if (extra) payload.extra = extra;
+ console.log('[quick-phrase-diagnostics]', JSON.stringify(payload));
+ fetch(API + '/api/breadcrumb', { method: 'POST', headers: { 'content-type': 'application/json', 'X-WorkDaddy-Token': WBS_API_TOKEN }, body: JSON.stringify({ msg: '[quick-phrase-diagnostics] ' + JSON.stringify(payload) }) }).catch(function () {});
+ } catch (_) {}
+ }
function acMenuClose() {
+ qpDiag('menu:close:before', { menuClass: exploreBtn.className });
exploreBtn.classList.add('wbs-menu-closed');
+ qpDiag('menu:close:after', { menuClass: exploreBtn.className });
}
exploreBtn.addEventListener('mouseenter', function () { exploreBtn.classList.remove('wbs-menu-closed'); });
exploreBtn.addEventListener('mouseleave', function () { exploreBtn.classList.remove('wbs-menu-closed'); });
- if (isWelcomePage()) exploreBtn.style.display = 'none'; // 欢迎页无操作栏,定位没意义;其余情况由 syncStash 常驻显示
+ exploreBtn.style.display = 'none'; // 找到可见会话输入区并完成定位后才显示,避免登录页出现悬空按钮。
/* ———— 会话模块(session):暂存提示词、会话消息索引、选中文字引用 & 快捷短语 ————
* 暂存提示词/快捷短语由 daemon 持久化;消息索引开关保存在渲染器 localStorage。
@@ -2153,6 +2382,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
tipK.addEventListener('mouseleave', hideTipDelayed);
}
itemK.addEventListener('click', function (eve) {
+ qpDiag('click:start', { phraseId: itemK.getAttribute('data-qp-send'), target: eve.target && eve.target.className || '' });
eve.stopPropagation();
var pid = itemK.getAttribute('data-qp-send');
var ph2 = null;
@@ -2161,6 +2391,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
if (!ph2) return;
acMenuClose();
+ qpDiag('api:send', { phraseId: pid });
api('/api/quick-phrase-send', {
method: 'POST',
headers: { 'content-type': 'application/json' },
@@ -2280,6 +2511,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 必须命中右侧 _gapLarge_ 组,排除 _selector_ 组)
// 操作栏最右侧的「圆形可点击」元素才是发送按钮(左侧还可能有增强提示词/停止等圆形按钮)
function findSendButton() {
+ // Keep the localized label out of the selector literal for internationalized source checks.
+ var sendLabel = '\u53d1\u9001';
+ var official = document.querySelector('button.cr-send-button[aria-label="' + sendLabel + '"],button.cr-send-button:not(.cr-send-button--stop),button[aria-label="' + sendLabel + '"],[role="button"][aria-label="' + sendLabel + '"]');
+ if (official && official.getBoundingClientRect) {
+ var or = official.getBoundingClientRect(), os = getComputedStyle(official);
+ if (or.width >= 16 && or.height >= 16 && or.bottom > 0 && os.display !== 'none' && os.visibility !== 'hidden') return official;
+ }
var row = findActionRow();
if (!row || !row.children) return null;
var kids = row.children;
@@ -2321,7 +2559,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!mic0) {
var toolbarMatch = WBS_COMPAT.findComposerToolbar(document);
var row0 = toolbarMatch && toolbarMatch.element;
- if (row0) {
+ if (isComposerAnchorVisible(row0)) {
stashBtn.classList.add('wbs-stash-inline-inline');
exploreBtn.classList.add('wbs-stash-inline-inline');
exploreBtn.style.right = 'auto';
@@ -2329,19 +2567,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (stashBtn.parentElement !== row0) row0.insertBefore(stashBtn, row0.firstChild);
// 探索按钮贴暂存按钮右侧
if (exploreBtn.parentElement !== row0) row0.insertBefore(exploreBtn, stashBtn.nextSibling);
- } else {
- // 容器暂不可用:回落到 body + fixed 定位
- stashBtn.classList.remove('wbs-stash-inline-inline');
- exploreBtn.classList.remove('wbs-stash-inline-inline');
- if (!stashBtn.parentElement) document.body.appendChild(stashBtn);
- if (!exploreBtn.parentElement) document.body.appendChild(exploreBtn);
- positionStash();
+ return true;
}
- return;
}
- if (!stashBtn.parentElement) document.body.appendChild(stashBtn);
- if (!exploreBtn.parentElement) document.body.appendChild(exploreBtn);
- positionStash();
+ // 固定定位只在可见会话锚点存在时启用;页面切换后不能沿用旧工具栏。
+ if (!positionStash()) return false;
+ stashBtn.classList.remove('wbs-stash-inline-inline');
+ exploreBtn.classList.remove('wbs-stash-inline-inline');
+ if (stashBtn.parentElement !== document.body) document.body.appendChild(stashBtn);
+ if (exploreBtn.parentElement !== document.body) document.body.appendChild(exploreBtn);
+ return true;
+ }
+ function isComposerAnchorVisible(element) {
+ if (!element || !element.isConnected) return false;
+ var rect = element.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) return false;
+ if (element.checkVisibility && !element.checkVisibility({ checkVisibilityCSS: true })) return false;
+ var css = getComputedStyle(element);
+ return css.display !== 'none' && css.visibility !== 'hidden' && css.visibility !== 'collapse';
}
// 探索菜单按钮:位于暂存提示词按钮右侧(与暂存同款圆钮、发送图标,hover 悬浮菜单弹窗)
function positionExplore() {
@@ -2386,7 +2629,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var mic = document.querySelector('.voice-mic-wrap');
if (!mic) {
var ed0 = findComposer();
- if (!ed0) { stashBtn.style.display = 'none'; return false; }
+ // 通用 composer 查找有宽松兜底;插件显隐必须限定在会话输入区内。
+ if (!isComposerAnchorVisible(ed0) || !ed0.closest('.conversation-input, .cr-input-box, [class*="_input-area-container_"]')) return false;
var er0 = ed0.getBoundingClientRect();
if (er0.width <= 0 || er0.height <= 0) { stashBtn.style.display = 'none'; return false; }
var rowLeft = Infinity, rowTop = Infinity, rowH = 0, found = false;
@@ -2433,6 +2677,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
// 锚点:操作栏最左元素(row.children[0]),定位到它的左边——整个操作栏最左。
// 用 right 锚定(CSS left:auto):hover 时 width 增大 → 左边向左展开(参考 wbs-fab)。
+ if (!isComposerAnchorVisible(mic)) return false;
var row = mic.parentElement;
if (!row || !row.children || !row.children.length) { stashBtn.style.display = 'none'; return false; }
var firstChild = row.children[0]; // 操作栏最左元素("上下文用量"按钮)
@@ -2470,10 +2715,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
clearTimeout(stashSyncThrottle);
// 节流 30ms:比 120ms 响应更快(接近原生 React 按钮的体感),仍能合并快速连续触发
stashSyncThrottle = setBuildTimeout(function () {
- // 欢迎页强制隐藏
- if (isWelcomePage()) { stashBtn.style.display = 'none'; exploreBtn.style.display = 'none'; return; }
+ // 登录、设置等页面没有会话锚点时隐藏两个按钮;不保留上个页面的固定坐标。
+ if (isWelcomePage() || !insertStash()) {
+ stashBtn.style.display = 'none';
+ exploreBtn.style.display = 'none';
+ exploreBtn.classList.add('wbs-menu-closed');
+ return;
+ }
// 探索按钮常驻(若「快捷短语」开关开着):不等输入框有内容,只要定位到操作栏就常显
- insertStash();
exploreBtn.style.display = sessState.phrase ? 'flex' : 'none';
applyThemeButtonColors(); // 主题色按钮(浅色黑底白图 / 深色白底黑图)
renderExploreOptions(); // 面板选项 = 快捷短语列表(增删改后同步刷新)
@@ -3816,6 +4065,25 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
} catch (e) {}
}
+ // Preserve an occupied New Task draft locally before Agent creation. Keep
+ // rich blocks in the existing stash format; only status crosses CDP.
+ async function saveAutomationDraft() {
+ var editor = findComposer();
+ var newTask = Array.from(document.querySelectorAll('button.conversation-list-tab-button')).some(function (b) { return b.getAttribute('aria-selected') === 'true' && /^(新建任务|New Task)$/i.test((b.innerText || '').trim()); });
+ if (!alive || !editor || (!editor.closest('.wb-home-composer') && !newTask)) return { saved: false };
+ var content = getComposerContent();
+ if (!content) return { saved: false };
+ var uid = (state.current && state.current.uid) || null;
+ if (content.textLen || content.items.length) {
+ await api('/api/stash', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ uid: uid, conversationId: 'automation-home-draft', content: content }) });
+ if (!alive || editor !== findComposer() || !document.contains(editor) ||
+ uid !== ((state.current && state.current.uid) || null) || !stashContentMatches(content, getComposerContent())) return { saved: false };
+ toast('原输入框草稿已保存到暂存', false, root);
+ }
+ return { saved: true };
+ }
+ window.__wbsSaveAutomationDraft = saveAutomationDraft;
+ registerDisposer(function () { if (window.__wbsSaveAutomationDraft === saveAutomationDraft) delete window.__wbsSaveAutomationDraft; });
// 队列操作超时包装:WorkBuddy 内部 Promise 可能永不 settle,超时后走本地暂存兜底,避免"卡死"
function withQueueTimeout(promise, ms) {
return new Promise(function (resolve, reject) {
@@ -3978,6 +4246,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var sessionsPane = root.querySelector('[data-pane="sessions"]');
var modelsPane = root.querySelector('[data-pane="models"]');
var enhancePane = root.querySelector('[data-pane="enhance"]');
+ var automationPane = root.querySelector('[data-pane="automations"]');
var pcPane = root.querySelector('[data-pane="pc"]');
var aboutPane = root.querySelector('[data-pane="about"]');
var hiddenToolsUnlocked = false;
@@ -4233,7 +4502,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function downloadTransfer(result, fallbackName) {
- var blob = new Blob([result.content], { type: 'application/json' });
+ var content = result.content;
+ if (result.encoding === 'base64') {
+ var binary = atob(content);
+ content = new Uint8Array(binary.length);
+ for (var i = 0; i < binary.length; i++) content[i] = binary.charCodeAt(i);
+ }
+ var blob = new Blob([content], { type: result.mimeType || 'application/json' });
var url = URL.createObjectURL(blob);
var anchor = document.createElement('a');
anchor.href = url;
@@ -4339,6 +4614,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (name === 'sessions' && sessionsPane && !sessionsPane.dataset.built) buildSessionsPane();
if (name === 'models' && modelsPane && !modelsPane.dataset.built) buildModelsPane();
if (name === 'enhance' && enhancePane && !enhancePane.dataset.built) buildEnhancePane();
+ if (name === 'automations' && automationPane && !automationPane.dataset.built) buildAutomationPane();
if (name === 'pc' && pcPane && !pcPane.dataset.built) buildPcPane();
if (name === 'about' && aboutPane && !aboutPane.dataset.built) buildAboutPane();
if (name === 'settings' && settingsPane && !settingsPane.dataset.built) buildSettingsPane();
@@ -4350,6 +4626,456 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
})(tabBtns[ti]);
}
+ function buildAutomationPane() {
+ if (!automationPane) return;
+ automationPane.dataset.built = '1';
+ var automationState = { tasks: [], runs: [], examples: [], selected: {}, batchMode: false, editingId: null, pollTimer: null, stopping: {}, agentDraft: '', agentCreating: false };
+ function defaultTask() {
+ return { schemaVersion: 1, id: 'task_' + Date.now().toString(36), name: '新自动化任务', description: '', enabled: true, trigger: { type: 'manual', oncePerNavigation: true }, variables: {}, steps: [] };
+ }
+ function triggerBadgesHtml(task) {
+ var trigger = task.trigger || {};
+ var types = Array.isArray(trigger.types) ? trigger.types : [trigger.type || 'manual'];
+ var names = types.filter(function (type) { return type !== 'manual'; }).map(function (type) { return ({ pageReady: '页面就绪', pageLoaded: '页面加载', accountSwitched: '账号切换后', clientLoaded: '客户端加载', panelOpened: '打开面板' })[type] || type; });
+ var schedule = task.schedule || {};
+ if (schedule.type === 'interval') names.push('每 ' + schedule.minutes + ' 分钟');
+ if (schedule.type === 'daily') names.push('每天 ' + schedule.time);
+ if (schedule.type === 'weekly') names.push((schedule.days || []).map(function (day) { return ['周日','周一','周二','周三','周四','周五','周六'][day]; }).join('、') + ' ' + schedule.time);
+ if (schedule.type === 'monthly') names.push('每月 ' + schedule.day + ' 日 ' + schedule.time);
+ if (schedule.type === 'once') names.push('单次 ' + String(schedule.at || '').replace('T', ' '));
+ if (!names.length) names.push('手动触发');
+ return names.map(function (name) { return '<span class="wbs-auto-trigger-chip">' + esc(name) + '</span>'; }).join('');
+ }
+ function taskStatusLabel(task, run, stopping) {
+ if (task.compatible === false) return '任务不兼容';
+ if (stopping) return '正在停止…';
+ if (run && run.status === 'running') return run.phase === 'queued' ? '排队中' : '执行中';
+ if (!task.enabled && !task.manualRunnable) return '已停用';
+ var events = task.trigger && (Array.isArray(task.trigger.types) ? task.trigger.types : [task.trigger.type]) || [];
+ if (task.schedule && task.schedule.type === 'once' && new Date(task.schedule.at).getTime() + 60000 <= Date.now() && !events.some(function (type) { return type && type !== 'manual'; })) return '定时已结束';
+ return task.manualRunnable ? '手动运行' : '等待触发';
+ }
+ function lastRunLabel(run) {
+ if (!run || run.status === 'running') return '';
+ var label = ({ success: '上次已完成', failed: '上次失败', cancelled: '上次已停止' })[run.status] || '';
+ var at = Number(run.finishedAt || run.startedAt);
+ return label + (at ? ' · ' + new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '');
+ }
+ function runFor(taskId) { var latest = null; for (var i = 0; i < automationState.runs.length; i++) { var item = automationState.runs[i]; if (item.taskId !== taskId) continue; if (item.status === 'running') return item; if (!latest || Number(item.startedAt || 0) > Number(latest.startedAt || 0)) latest = item; } return latest; }
+ function selectedIds() { return Object.keys(automationState.selected).filter(function (id) { return automationState.selected[id]; }); }
+ function allSelected() { return automationState.tasks.length > 0 && automationState.tasks.every(function (task) { return automationState.selected[task.id]; }); }
+ function syncBatchControls() {
+ var count = automationPane.querySelector('#wbs-auto-batch-count');
+ var selectAll = automationPane.querySelector('#wbs-auto-select-all');
+ if (count) count.textContent = '已选 ' + selectedIds().length;
+ if (selectAll) selectAll.textContent = allSelected() ? '取消全选' : '全选';
+ var exportButton = automationPane.querySelector('#wbs-auto-export');
+ if (exportButton) exportButton.disabled = !selectedIds().length || !!automationState.exporting;
+ }
+ function render() {
+ var list = automationPane.querySelector('#wbs-auto-list');
+ var count = automationPane.querySelector('#wbs-auto-count');
+ if (!list) return;
+ if (count) count.textContent = automationState.tasks.length ? String(automationState.tasks.length) : '';
+ var scrollTop = list.scrollTop;
+ list.innerHTML = '';
+ if (!automationState.tasks.length) { list.innerHTML = '<div class="wbs-auto-empty">暂无自动化任务,点击“新建任务”开始。</div>'; syncBatchControls(); return; }
+ automationState.tasks.forEach(function (task) {
+ var row = document.createElement('div'); row.className = 'wbs-auto-row'; row.setAttribute('data-task-id', task.id);
+ var run = runFor(task.id);
+ var running = !!(run && run.status === 'running');
+ // 清理已结束的“停止中”标记:run 不再 running 即视为停止完成
+ if (automationState.stopping && Object.keys(automationState.stopping).length) {
+ Object.keys(automationState.stopping).forEach(function (rid) {
+ var still = automationState.runs.some(function (r2) { return r2.id === rid && r2.status === 'running'; });
+ if (!still) delete automationState.stopping[rid];
+ });
+ }
+ var stopping = running && run && !!automationState.stopping[run.id]; // 已点停止、等待 daemon 确认结束
+ var active = running || stopping;
+ var check = automationState.batchMode ? '<label class="wbs-auto-check"><input type="checkbox" data-auto-select="' + escAttr(task.id) + '"' + (automationState.selected[task.id] ? ' checked' : '') + '><span></span></label>' : '';
+ var stateClass = active ? 'running' : !task.enabled && !task.manualRunnable ? 'off' : 'idle';
+ var action = running ? '<button type="button" class="wbs-auto-icon is-running' + (stopping ? ' is-stopping' : '') + '" data-auto-stop="' + escAttr(run.id) + '" title="' + (stopping ? '正在停止…' : '停止本次执行') + '" aria-label="' + (stopping ? '正在停止…' : '停止本次执行') + '" aria-busy="true"' + (stopping ? ' disabled' : '') + '>' + (stopping ? AUTO_STOPPING_SVG : AUTO_STOP_SVG) + '</button>'
+ : task.manualRunnable ? '<button type="button" class="wbs-auto-icon" data-auto-run="' + escAttr(task.id) + '" title="立即运行" aria-label="立即运行">' + MODEL_ENABLE_SVG + '</button>' : '';
+ row.innerHTML = '<div class="wbs-auto-row-head">' + check + '<div class="wbs-auto-name"' + (wbsBuiltinAutomationText(task, 'name') ? '' : ' data-wbs-i18n-skip="1"') + ' title="' + escAttr(task.name) + '">' + esc(task.name) + '</div>' +
+ '<label class="wbs-switch wbs-auto-enabled" title="' + (task.manualRunnable ? '手动任务无需自动触发' : '启用自动触发') + '"' + (task.manualRunnable || task.compatible === false ? ' hidden' : '') + '><input type="checkbox" data-auto-enabled="' + escAttr(task.id) + '" aria-label="启用自动触发"' + (task.enabled ? ' checked' : '') + '><span class="wbs-switch-slider"></span></label></div>' +
+ (task.description ? '<div class="wbs-auto-description"' + (wbsBuiltinAutomationText(task, 'description') ? '' : ' data-wbs-i18n-skip="1"') + ' title="' + escAttr(task.description) + '">' + esc(task.description) + '</div>' : '') +
+ '<div class="wbs-auto-row-foot"><div class="wbs-auto-details"><div class="wbs-auto-triggers" aria-label="触发方式">' + triggerBadgesHtml(task) + '</div><div class="wbs-auto-state-line"><span class="wbs-auto-state ' + stateClass + '">' + esc(taskStatusLabel(task, run, stopping)) + '</span>' +
+ (lastRunLabel(run) ? '<span class="wbs-auto-last-run' + (run.status === 'failed' ? ' failed' : '') + '">' + esc(lastRunLabel(run)) + '</span>' : '') + '</div></div><div class="wbs-auto-actions">' + action +
+ '<button type="button" class="wbs-auto-icon" data-auto-logs="' + escAttr(task.id) + '" title="运行日志" aria-label="运行日志">' + AUTO_LOG_SVG + '</button><button type="button" class="wbs-auto-icon" data-auto-edit="' + escAttr(task.id) + '" title="编辑" aria-label="编辑">' + MODEL_EDIT_SVG + '</button><button type="button" class="wbs-auto-icon" data-auto-copy="' + escAttr(task.id) + '" title="复制" aria-label="复制">' + MODEL_COPY_SVG + '</button><button type="button" class="wbs-auto-icon danger" data-auto-delete="' + escAttr(task.id) + '" title="删除" aria-label="删除">' + TRASH_SVG + '</button></div></div>';
+ list.appendChild(row);
+ });
+ list.scrollTop = scrollTop;
+ applyI18n(list);
+ syncBatchControls();
+ }
+ function load() {
+ return api('/api/automations').then(function (result) { automationState.tasks = result.tasks || []; automationState.runs = result.runs || []; render(); }).catch(function (e) { toast(e.message || '加载自动化失败', true, root); });
+ }
+ function renderExamples() {
+ var list = (panel || root).querySelector('#wbs-auto-examples');
+ if (!list) return;
+ list.innerHTML = '';
+ automationState.examples.forEach(function (example) {
+ var title = WBS_LANGUAGE === 'en' ? example.titleEn : example.titleZh;
+ var button = document.createElement('button'); button.type = 'button'; button.className = 'wbs-auto-textbtn wbs-auto-example-fill';
+ button.setAttribute('data-auto-example-fill', example.id);
+ button.title = title;
+ button.textContent = automationState.examples.length === 1 ? '示例' : title;
+ list.appendChild(button);
+ });
+ applyI18n(list);
+ }
+ function loadAgentInfo() {
+ return api('/api/automations/agent-info').then(function (result) { automationState.examples = result.examples || []; renderExamples(); }).catch(function (e) {
+ var list = (panel || root).querySelector('#wbs-auto-examples');
+ if (list) list.innerHTML = '<div class="wbs-auto-example-empty">' + esc(e.message || '加载示例失败') + '</div>';
+ });
+ }
+ function exampleById(id) {
+ return automationState.examples.filter(function (item) { return item.id === id; })[0] || null;
+ }
+ function generateAgentTask(mask) {
+ if (automationState.agentCreating) return;
+ var input = mask.querySelector('#wbs-auto-agent-prompt');
+ var prompt = input.value.trim();
+ if (!prompt || prompt.length > 6000) { input.focus(); return; }
+ automationState.agentDraft = input.value;
+ automationState.agentCreating = true;
+ closePanelModal(mask);
+ setOpen(false);
+ api('/api/automations/agent-generate', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ prompt: prompt, language: WBS_LANGUAGE }) }).then(function () {
+ automationState.agentCreating = false; automationState.agentDraft = '';
+ toast('已创建新会话,WorkBuddy 完成后任务会自动出现', false, root);
+ }).catch(function (error) {
+ automationState.agentCreating = false;
+ setOpen(true, { automation: true }); switchTab('automations'); showExamples();
+ toast('WorkBuddy 创建失败:' + (error.message || error), true, root);
+ });
+ }
+ function closePanelModal(mask) {
+ if (!mask) return;
+ if (mask.__wbsKeyHandler) document.removeEventListener('keydown', mask.__wbsKeyHandler, true);
+ mask.remove();
+ }
+ function showAutomationConfirm(title, bodyText, onConfirm, confirmText) {
+ var mask = document.createElement('div');
+ mask.className = 'wbs-modal-mask wbs-modal-mask-panel';
+ mask.innerHTML = '<div class="wbs-modal" role="dialog" aria-modal="true"><div class="wbs-modal-title"></div><div class="wbs-modal-body"></div><div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" data-auto-confirm="cancel">取消</button><button class="wbs-modal-btn wbs-modal-danger" type="button" data-auto-confirm="ok">删除</button></div></div>';
+ mask.querySelector('.wbs-modal-title').textContent = title;
+ mask.querySelector('.wbs-modal-body').textContent = bodyText;
+ mask.querySelector('[data-auto-confirm="ok"]').textContent = confirmText || '删除';
+ (panel || root).appendChild(mask);
+ function close() { closePanelModal(mask); }
+ mask.addEventListener('click', function (event) {
+ if (event.target === mask || (event.target.getAttribute && event.target.getAttribute('data-auto-confirm') === 'cancel')) { close(); return; }
+ if (event.target.getAttribute && event.target.getAttribute('data-auto-confirm') === 'ok') { close(); onConfirm(); }
+ });
+ mask.__wbsKeyHandler = function (event) { if (event.key === 'Escape') close(); };
+ document.addEventListener('keydown', mask.__wbsKeyHandler, true);
+ applyI18n(mask);
+ }
+ function showAutomationLogs(task) {
+ if (!task) return;
+ var runs = automationState.runs.filter(function (run) { return run.taskId === task.id; }).sort(function (a, b) { return Number(b.startedAt || 0) - Number(a.startedAt || 0); });
+ var mask = document.createElement('div');
+ mask.className = 'wbs-modal-mask wbs-modal-mask-panel';
+ mask.innerHTML = '<div class="wbs-modal wbs-auto-log-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-log-title"><div class="wbs-auto-modal-head"><div><div class="wbs-modal-title" id="wbs-auto-log-title">运行日志</div><div class="wbs-auto-modal-subtitle"></div></div><div class="wbs-auto-log-head-actions"><button class="wbs-auto-textbtn" type="button" id="wbs-auto-clear-logs">清除日志</button><button class="wbs-auto-modal-close" type="button" title="关闭" aria-label="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></div></div><div class="wbs-auto-log-list"></div></div>';
+ mask.querySelector('.wbs-auto-modal-subtitle').textContent = task.name || '';
+ if (!wbsBuiltinAutomationText(task, 'name')) mask.querySelector('.wbs-auto-modal-subtitle').setAttribute('data-wbs-i18n-skip', '1');
+ var list = mask.querySelector('.wbs-auto-log-list');
+ if (!runs.length) {
+ var empty = document.createElement('div'); empty.className = 'wbs-auto-log-empty'; empty.textContent = '暂无运行日志'; list.appendChild(empty);
+ } else {
+ runs.forEach(function (run) {
+ var item = document.createElement('section'); item.className = 'wbs-auto-log-run';
+ var head = document.createElement('div'); head.className = 'wbs-auto-log-head';
+ var status = document.createElement('span'); status.className = 'wbs-auto-log-status ' + String(run.status || ''); status.textContent = ({ running: '运行中', success: '已成功', failed: '失败', cancelled: '已停止' })[run.status] || run.status || '未运行';
+ var time = document.createElement('span'); time.className = 'wbs-auto-log-time'; time.textContent = new Date(Number(run.startedAt || 0)).toLocaleString(WBS_LANGUAGE === 'en' ? 'en-US' : 'zh-CN');
+ head.appendChild(status); head.appendChild(time); item.appendChild(head);
+ var facts = document.createElement('div'); facts.className = 'wbs-auto-log-facts';
+ var started = document.createElement('span'); started.textContent = (WBS_LANGUAGE === 'en' ? 'Started: ' : '开始时间:') + new Date(Number(run.startedAt || 0)).toLocaleString(WBS_LANGUAGE === 'en' ? 'en-US' : 'zh-CN'); facts.appendChild(started);
+ var finished = document.createElement('span'); finished.textContent = (WBS_LANGUAGE === 'en' ? 'Finished: ' : '结束时间:') + (run.finishedAt ? new Date(Number(run.finishedAt)).toLocaleString(WBS_LANGUAGE === 'en' ? 'en-US' : 'zh-CN') : (WBS_LANGUAGE === 'en' ? 'Still running' : '尚未结束')); facts.appendChild(finished);
+ item.appendChild(facts);
+ var pre = document.createElement('pre'); pre.className = 'wbs-auto-log-output'; pre.textContent = (run.logs || []).map(function (entry) { return new Date(Number(entry.at || 0)).toLocaleTimeString(WBS_LANGUAGE === 'en' ? 'en-US' : 'zh-CN') + ' ' + String(entry.message || ''); }).join('\n') || (WBS_LANGUAGE === 'en' ? 'No execution log entries' : '暂无执行日志'); item.appendChild(pre);
+ list.appendChild(item);
+ });
+ }
+ (panel || root).appendChild(mask);
+ function close() { closePanelModal(mask); }
+ mask.__wbsKeyHandler = function (event) { if (event.key === 'Escape') close(); };
+ document.addEventListener('keydown', mask.__wbsKeyHandler, true);
+ mask.querySelector('.wbs-auto-modal-close').addEventListener('click', close);
+ mask.querySelector('#wbs-auto-clear-logs').addEventListener('click', function () {
+ showAutomationConfirm('清除运行日志?', '仅清除已结束的运行记录。', function () {
+ api('/api/automations/logs/clear', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ taskId: task.id }) }).then(function () {
+ automationState.runs = automationState.runs.filter(function (run) { return run.taskId !== task.id || run.status === 'running'; });
+ close();
+ showAutomationLogs(task);
+ }).catch(function (error) { toast(error.message || '清除日志失败', true, root); });
+ }, '清除');
+ });
+ mask.addEventListener('click', function (event) { if (event.target === mask) close(); });
+ applyI18n(mask);
+ }
+ function showEditor(task) {
+ if (task && task.compatible === false) { toast('任务与当前 WorkDaddy 不兼容,请升级或使用适配版本', true, root); return; }
+ hideEditor();
+ var mask = document.createElement('div');
+ mask.id = 'wbs-auto-editor-mask';
+ mask.className = 'wbs-modal-mask wbs-modal-mask-panel';
+ mask.innerHTML = '<div class="wbs-modal wbs-auto-editor-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-editor-title"><div class="wbs-auto-modal-head"><div class="wbs-modal-title" id="wbs-auto-editor-title">编辑任务</div><button class="wbs-auto-modal-close" type="button" title="关闭" aria-label="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></div><div class="wbs-auto-editor-body"><label class="wbs-auto-field"><span>任务名称</span><input data-auto-field="name" type="text" maxlength="120"></label><label class="wbs-auto-field"><span>任务说明</span><textarea data-auto-field="description" rows="3" maxlength="500"></textarea></label><div class="wbs-auto-field"><span>事件触发(可多选)</span><div class="wbs-auto-trigger-options" data-auto-field="trigger" role="group" aria-label="触发方式"><label><input type="checkbox" value="pageReady"><span>页面就绪</span></label><label><input type="checkbox" value="pageLoaded"><span>页面加载</span></label><label><input type="checkbox" value="accountSwitched"><span>账号切换后</span></label><label><input type="checkbox" value="clientLoaded"><span>客户端加载</span></label><label><input type="checkbox" value="panelOpened"><span>打开面板</span></label></div><div class="wbs-auto-schedule"><label>定时方式 <select data-auto-field="scheduleType" aria-label="定时方式"><option value="manual">不定时</option><option value="interval">按间隔</option><option value="daily">每天</option><option value="weekly">每周</option><option value="monthly">每月</option><option value="once">指定时间一次</option></select></label><label data-schedule-for="interval">每 <input type="number" data-auto-field="intervalValue" min="1" max="10080" step="1" aria-label="间隔数值"><select data-auto-field="intervalUnit" aria-label="间隔单位"><option value="1">分钟</option><option value="60">小时</option><option value="1440">天</option></select></label><label data-schedule-for="monthly">日期 <input type="number" data-auto-field="monthDay" min="1" max="31" aria-label="每月日期"></label><label data-schedule-for="daily weekly monthly">时间 <input type="time" data-auto-field="time" aria-label="执行时间"></label><label data-schedule-for="once">日期时间 <input type="datetime-local" data-auto-field="onceAt" aria-label="执行日期和时间"></label><div class="wbs-auto-weekdays" data-schedule-for="weekly"><label><input type="checkbox" data-auto-weekday="1"><span>周一</span></label><label><input type="checkbox" data-auto-weekday="2"><span>周二</span></label><label><input type="checkbox" data-auto-weekday="3"><span>周三</span></label><label><input type="checkbox" data-auto-weekday="4"><span>周四</span></label><label><input type="checkbox" data-auto-weekday="5"><span>周五</span></label><label><input type="checkbox" data-auto-weekday="6"><span>周六</span></label><label><input type="checkbox" data-auto-weekday="0"><span>周日</span></label><button type="button" class="wbs-auto-textbtn" data-auto-workdays>工作日</button></div><div class="wbs-auto-schedule-hint" data-schedule-for="interval daily weekly monthly once">按电脑本地时间执行;错过不补跑,运行中跳过。</div><div class="wbs-auto-schedule-hint" data-schedule-for="monthly">当月没有该日期时跳过。</div></div></div><label class="wbs-auto-field wbs-auto-steps-field"><span>步骤 JSON</span><textarea data-auto-field="steps" spellcheck="false"></textarea></label></div><div class="wbs-modal-actions wbs-auto-editor-actions"><button class="wbs-modal-btn" type="button" id="wbs-auto-cancel">取消</button><button class="wbs-modal-btn wbs-modal-ok" type="button" id="wbs-auto-save">保存</button></div></div>';
+ (panel || root).appendChild(mask);
+ var editor = mask.querySelector('.wbs-auto-editor-modal');
+ automationState.editingId = task && task.id || null;
+ editor.querySelector('[data-auto-field="name"]').value = wbsAutomationText(task, 'name');
+ editor.querySelector('[data-auto-field="description"]').value = wbsAutomationText(task, 'description');
+ var trigger = task && task.trigger || {};
+ var triggerTypes = Array.isArray(trigger.types) ? trigger.types : [trigger.type || 'manual'];
+ editor.querySelectorAll('[data-auto-field="trigger"] input').forEach(function (input) { input.checked = triggerTypes.indexOf(input.value) >= 0; });
+ var schedule = task && task.schedule || { type: 'manual' };
+ var scheduleType = editor.querySelector('[data-auto-field="scheduleType"]');
+ scheduleType.value = schedule.type;
+ var interval = Number(schedule.minutes) || 60;
+ var unit = interval % 1440 === 0 ? 1440 : interval % 60 === 0 ? 60 : 1;
+ editor.querySelector('[data-auto-field="intervalValue"]').value = interval / unit;
+ editor.querySelector('[data-auto-field="intervalUnit"]').value = String(unit);
+ editor.querySelector('[data-auto-field="time"]').value = schedule.time || '09:00';
+ editor.querySelector('[data-auto-field="monthDay"]').value = schedule.day || 1;
+ editor.querySelector('[data-auto-field="onceAt"]').value = schedule.at || '';
+ editor.querySelectorAll('[data-auto-weekday]').forEach(function (input) { input.checked = (schedule.days || [1,2,3,4,5]).indexOf(Number(input.dataset.autoWeekday)) >= 0; });
+ function syncScheduleFields() {
+ editor.querySelectorAll('[data-schedule-for]').forEach(function (field) { field.hidden = field.dataset.scheduleFor.split(' ').indexOf(scheduleType.value) < 0; });
+ }
+ scheduleType.addEventListener('change', syncScheduleFields); syncScheduleFields();
+ editor.querySelector('[data-auto-workdays]').addEventListener('click', function () { editor.querySelectorAll('[data-auto-weekday]').forEach(function (input) { input.checked = Number(input.dataset.autoWeekday) > 0 && Number(input.dataset.autoWeekday) < 6; }); });
+ editor.querySelector('[data-auto-field="steps"]').value = JSON.stringify(task ? task.steps : [], null, 2);
+ mask.__wbsKeyHandler = function (event) { if (event.key === 'Escape') hideEditor(); };
+ document.addEventListener('keydown', mask.__wbsKeyHandler, true);
+ mask.querySelector('#wbs-auto-save').addEventListener('click', saveEditor);
+ mask.querySelector('#wbs-auto-cancel').addEventListener('click', hideEditor);
+ mask.querySelector('.wbs-auto-modal-close').addEventListener('click', hideEditor);
+ mask.addEventListener('click', function (event) { if (event.target === mask) hideEditor(); });
+ applyI18n(mask);
+ editor.querySelector('[data-auto-field="name"]').focus();
+ }
+ function hideEditor() { closePanelModal((panel || root).querySelector('#wbs-auto-editor-mask')); automationState.editingId = null; }
+ function saveEditor() {
+ var editor = (panel || root).querySelector('.wbs-auto-editor-modal');
+ if (!editor) return;
+ var steps;
+ try { steps = JSON.parse(editor.querySelector('[data-auto-field="steps"]').value || '[]'); } catch (_) { toast('步骤 JSON 格式无效', true, root); return; }
+ if (!Array.isArray(steps)) { toast('步骤 JSON 必须是数组', true, root); return; }
+ var existing = automationState.tasks.filter(function (item) { return item.id === automationState.editingId; })[0];
+ var task = existing ? JSON.parse(JSON.stringify(existing)) : defaultTask();
+ var selectedTriggers = Array.from(editor.querySelectorAll('[data-auto-field="trigger"] input:checked')).map(function (input) { return input.value; });
+ var scheduleType = editor.querySelector('[data-auto-field="scheduleType"]').value;
+ var schedule = { type: scheduleType };
+ if (scheduleType === 'interval') {
+ schedule.minutes = Number(editor.querySelector('[data-auto-field="intervalValue"]').value) * Number(editor.querySelector('[data-auto-field="intervalUnit"]').value);
+ if (!Number.isInteger(schedule.minutes) || schedule.minutes < 1 || schedule.minutes > 10080) { toast('定时间隔必须是 1–10080 分钟的整数', true, root); return; }
+ }
+ if (['daily', 'weekly', 'monthly'].indexOf(scheduleType) >= 0) {
+ schedule.time = editor.querySelector('[data-auto-field="time"]').value;
+ if (!schedule.time) { toast('请选择有效的执行时间', true, root); return; }
+ }
+ if (scheduleType === 'weekly') {
+ schedule.days = Array.from(editor.querySelectorAll('[data-auto-weekday]:checked')).map(function (input) { return Number(input.dataset.autoWeekday); });
+ if (!schedule.days.length) { toast('请至少选择一个星期', true, root); return; }
+ }
+ if (scheduleType === 'monthly') schedule.day = Number(editor.querySelector('[data-auto-field="monthDay"]').value);
+ if (scheduleType === 'once') {
+ schedule.at = editor.querySelector('[data-auto-field="onceAt"]').value;
+ if (!schedule.at || (new Date(schedule.at).getTime() <= Date.now() && (!existing || !existing.schedule || existing.schedule.at !== schedule.at))) { toast('请选择将来的执行日期和时间', true, root); return; }
+ }
+ task.schedule = schedule;
+ task.id = automationState.editingId || task.id; task.name = wbsAutomationEditedText(existing, 'name', editor.querySelector('[data-auto-field="name"]').value) || '未命名任务'; task.description = wbsAutomationEditedText(existing, 'description', editor.querySelector('[data-auto-field="description"]').value); task.enabled = existing ? existing.enabled !== false : true; task.trigger = Object.assign({}, task.trigger || {}, { type: selectedTriggers[0] || 'manual', types: selectedTriggers, oncePerNavigation: true }); task.steps = steps;
+ api('/api/automations', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ task: task }) }).then(function () { hideEditor(); toast('任务已保存', false, root); return load(); }).catch(function (e) { toast(e.message || '保存失败', true, root); });
+ }
+ function mountAutomationModal(mask) {
+ (panel || root).appendChild(mask);
+ var close = function () { closePanelModal(mask); };
+ mask.querySelector('[data-auto-close]').addEventListener('click', close);
+ mask.addEventListener('click', function (e) { if (e.target === mask) close(); });
+ mask.__wbsKeyHandler = function (e) {
+ if (e.key === 'Escape' && mask === (panel || root).querySelector('.wbs-auto-dialog-mask:last-child')) { e.preventDefault(); e.stopImmediatePropagation(); close(); }
+ };
+ document.addEventListener('keydown', mask.__wbsKeyHandler, true);
+ applyI18n(mask);
+ mask.querySelector('[data-auto-close]').focus();
+ }
+ function showCapabilities() {
+ api('/api/automations/capabilities').then(function (result) {
+ closePanelModal((panel || root).querySelector('#wbs-auto-protocol-mask'));
+ var protocol = WBS_LANGUAGE === 'zh' ? result.protocolZh : result.protocolEn;
+ var mask = document.createElement('div'); mask.id = 'wbs-auto-protocol-mask'; mask.className = 'wbs-modal-mask wbs-modal-mask-panel wbs-auto-dialog-mask';
+ mask.innerHTML = '<div class="wbs-modal wbs-auto-cap-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-protocol-title"><div class="wbs-modal-title" id="wbs-auto-protocol-title">自动化接口协议</div><pre class="wbs-auto-protocol"></pre><div class="wbs-modal-actions"><button class="wbs-modal-btn" data-auto-close type="button">关闭</button></div></div>';
+ mask.querySelector('.wbs-auto-protocol').textContent = String(protocol || '');
+ mountAutomationModal(mask);
+ }).catch(function (e) { toast(e.message || '读取接口失败', true, root); });
+ }
+ function showExamples() {
+ if (automationState.agentCreating) { toast('正在打开新任务…', false, root); return; }
+ closePanelModal((panel || root).querySelector('#wbs-auto-examples-mask'));
+ var mask = document.createElement('div'); mask.id = 'wbs-auto-examples-mask'; mask.className = 'wbs-modal-mask wbs-modal-mask-panel wbs-auto-dialog-mask';
+ mask.innerHTML = '<div class="wbs-modal wbs-auto-agent-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-examples-title"><div class="wbs-modal-title" id="wbs-auto-examples-title">让 WorkBuddy 帮我创建</div><p class="wbs-auto-agent-intro">描述触发时机和需要执行的操作,WorkBuddy 会生成任务并添加到自动化列表。</p><div class="wbs-auto-agent-input-head"><label for="wbs-auto-agent-prompt">自动化需求</label><div id="wbs-auto-examples"></div></div><textarea id="wbs-auto-agent-prompt" class="wbs-auto-agent-prompt" maxlength="6000" placeholder="例如:每次打开面板时,显示一条欢迎提示。"></textarea><div class="wbs-auto-agent-hint">将在新的 WorkBuddy 会话中创建</div><div class="wbs-modal-actions"><button class="wbs-modal-btn" data-auto-close type="button">取消</button><button class="wbs-modal-btn wbs-modal-ok" id="wbs-auto-agent-submit" type="button" disabled>交给 WorkBuddy 创建</button></div></div>';
+ mountAutomationModal(mask); renderExamples();
+ var input = mask.querySelector('#wbs-auto-agent-prompt');
+ var submit = mask.querySelector('#wbs-auto-agent-submit');
+ input.value = automationState.agentDraft;
+ function syncDraft() { automationState.agentDraft = input.value; submit.disabled = !input.value.trim(); }
+ input.addEventListener('input', syncDraft); syncDraft(); input.focus();
+ mask.querySelector('#wbs-auto-examples').addEventListener('click', function (e) {
+ var button = e.target.closest('[data-auto-example-fill]');
+ if (!button) return;
+ var example = exampleById(button.getAttribute('data-auto-example-fill'));
+ if (!example) return;
+ input.value = WBS_LANGUAGE === 'en' ? example.promptEn : example.promptZh;
+ syncDraft(); input.focus();
+ });
+ submit.addEventListener('click', function () { generateAgentTask(mask); });
+ }
+ function exportAutomationTasks() {
+ var ids = selectedIds();
+ if (!ids.length || automationState.exporting) return;
+ automationState.exporting = true; syncBatchControls();
+ api('/api/automations/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids: ids }) }).then(function (result) {
+ downloadTransfer(result, 'WorkDaddy-tasks.zip');
+ toast('任务导出成功', false, root);
+ }).catch(function (error) { toast(error.message || '导出失败', true, root); }).finally(function () { automationState.exporting = false; syncBatchControls(); });
+ }
+ function importIssueLabel(entry) {
+ if (entry.existing) return '已存在,将跳过';
+ if (entry.compatible) return '可导入';
+ var codes = (entry.issues || []).map(function (issue) { return issue.code; });
+ if (codes.indexOf('input_required') >= 0) return '缺少必填参数';
+ if (codes.indexOf('workdaddy_version') >= 0) return '需要更新 WorkDaddy';
+ if (codes.indexOf('profile') >= 0 || codes.indexOf('platform') >= 0) return '不支持当前客户端或系统';
+ if (codes.indexOf('invalid_document') >= 0) return '文件不是自动化任务 JSON';
+ return '任务格式或能力不受支持';
+ }
+ function showTaskImport(payload, filename, preview) {
+ closePanelModal((panel || root).querySelector('#wbs-auto-import-mask'));
+ var mask = document.createElement('div'); mask.id = 'wbs-auto-import-mask'; mask.className = 'wbs-modal-mask wbs-modal-mask-panel wbs-auto-dialog-mask';
+ mask.innerHTML = '<div class="wbs-modal wbs-auto-import-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-auto-import-title"><div class="wbs-modal-title" id="wbs-auto-import-title">导入任务</div><div class="wbs-auto-import-file" data-wbs-i18n-skip="1"></div><p class="wbs-auto-agent-intro">导入后保持停用,可在任务列表中启用。相同 ID 的任务会跳过。</p><div class="wbs-auto-import-list"></div><div class="wbs-auto-import-error" role="alert"></div><div class="wbs-modal-actions"><span class="wbs-auto-import-count"></span><button class="wbs-modal-btn" data-auto-close type="button">取消</button><button class="wbs-modal-btn wbs-modal-ok" data-auto-import-confirm type="button">导入</button></div></div>';
+ mask.querySelector('.wbs-auto-import-file').textContent = filename;
+ var list = mask.querySelector('.wbs-auto-import-list');
+ preview.entries.forEach(function (entry) {
+ var row = document.createElement('label'); row.className = 'wbs-auto-import-item';
+ var available = entry.compatible && !entry.existing;
+ row.innerHTML = '<span class="wbs-auto-check"><input type="checkbox" data-import-key="' + escAttr(entry.key) + '"' + (available ? ' checked' : ' disabled') + '></span><span class="wbs-auto-import-info"><span class="wbs-auto-import-name" data-wbs-i18n-skip="1"></span><span class="wbs-auto-import-status"></span></span>';
+ row.querySelector('.wbs-auto-import-name').textContent = entry.name;
+ row.querySelector('.wbs-auto-import-status').textContent = importIssueLabel(entry);
+ list.appendChild(row);
+ });
+ mountAutomationModal(mask);
+ var confirm = mask.querySelector('[data-auto-import-confirm]'), error = mask.querySelector('.wbs-auto-import-error');
+ function selected() { return Array.from(list.querySelectorAll('input:checked:not(:disabled)')).map(function (input) { return input.dataset.importKey; }); }
+ function syncSelection() { var count = selected().length; confirm.disabled = !count; mask.querySelector('.wbs-auto-import-count').textContent = WBS_LANGUAGE === 'en' ? 'Selected ' + count : '已选 ' + count; }
+ list.addEventListener('change', syncSelection); syncSelection();
+ confirm.addEventListener('click', function () {
+ var keys = selected(); if (!keys.length) return;
+ confirm.disabled = true; confirm.textContent = WBS_LANGUAGE === 'en' ? 'Importing…' : '导入中…'; error.textContent = '';
+ list.querySelectorAll('input').forEach(function (input) { input.disabled = true; });
+ api('/api/automations/import', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(Object.assign({}, payload, { selected: keys })) }).then(function (result) {
+ closePanelModal(mask);
+ toast(WBS_LANGUAGE === 'en' ? 'Imported ' + result.imported + ' task(s)' + (result.skipped ? '; skipped ' + result.skipped : '') : '已导入 ' + result.imported + ' 个任务' + (result.skipped ? ',跳过 ' + result.skipped + ' 个' : ''), false, root);
+ return load();
+ }).catch(function (err) {
+ error.textContent = err.message || '导入失败';
+ preview.entries.forEach(function (entry) { list.querySelector('[data-import-key="' + entry.key + '"]').disabled = !entry.compatible || entry.existing; });
+ confirm.textContent = WBS_LANGUAGE === 'en' ? 'Import' : '导入'; syncSelection();
+ });
+ });
+ }
+ function readAutomationImport(event) {
+ var file = event.target.files && event.target.files[0]; event.target.value = '';
+ if (!file) return;
+ if (file.size > 8 * 1024 * 1024) { toast('任务文件不能超过 8 MiB', true, root); return; }
+ var button = automationPane.querySelector('#wbs-auto-import'); button.disabled = true;
+ var reader = new FileReader();
+ reader.onerror = function () { button.disabled = false; toast('读取文件失败', true, root); };
+ reader.onload = function () {
+ var payload = { content: String(reader.result || '').split(',')[1] || '', encoding: 'base64' };
+ api('/api/automations/import/preview', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }).then(function (preview) {
+ showTaskImport(payload, file.name, preview);
+ }).catch(function (err) { toast(err.message || '导入失败', true, root); }).finally(function () { button.disabled = false; });
+ };
+ reader.readAsDataURL(file);
+ }
+ function startPicker() {
+ if (typeof window.__wbsStartAutomationPicker === 'function') window.__wbsStartAutomationPicker();
+ else toast('元素拾取器尚未加载', true, root);
+ }
+ automationPane.innerHTML = '<div class="wbs-pcard wbs-auto-card"><div class="wbs-auto-toolbar"><div class="wbs-pcard-title">自动化<span class="wbs-pcard-sub" id="wbs-auto-count"></span></div><button type="button" class="wbs-auto-textbtn" id="wbs-auto-cap">查看接口说明</button><div class="wbs-auto-toolbar-actions"><div class="wbs-auto-normal-actions" id="wbs-auto-normal-actions"><button class="wbs-sess-bbtn wbs-auto-pick-btn" type="button" id="wbs-auto-pick">' + AUTO_PICK_SVG + '<span>拾取元素</span></button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-create">让 WorkBuddy 帮我创建</button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-new">新建任务</button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-import" title="选择 JSON 或 ZIP 任务文件">' + IMPORT_ICON + '<span>导入</span></button><input type="file" id="wbs-auto-import-file" accept=".json,.zip,application/json,application/zip" hidden><button class="wbs-sess-bbtn" type="button" id="wbs-auto-batch">批量操作</button></div><div class="wbs-auto-batch-actions" id="wbs-auto-batch-actions" style="display:none"><span class="wbs-auto-batch-count" id="wbs-auto-batch-count">已选 0</span><button class="wbs-sess-bbtn" type="button" id="wbs-auto-select-all">全选</button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-export" disabled>' + EXPORT_ICON + '<span>导出</span></button><button class="wbs-sess-bbtn wbs-sess-delbtn" type="button" id="wbs-auto-batch-apply">' + TRASH_SVG + '<span>删除选中</span></button><button class="wbs-sess-bbtn" type="button" id="wbs-auto-batch-cancel">取消</button></div></div></div><div class="wbs-auto-list" id="wbs-auto-list"></div></div>';
+ automationPane.querySelector('#wbs-auto-import').addEventListener('click', function () { automationPane.querySelector('#wbs-auto-import-file').click(); });
+ automationPane.querySelector('#wbs-auto-import-file').addEventListener('change', readAutomationImport);
+ automationPane.querySelector('#wbs-auto-export').addEventListener('click', exportAutomationTasks);
+ automationPane.querySelector('#wbs-auto-new').addEventListener('click', function () { showEditor(defaultTask()); });
+ automationPane.querySelector('#wbs-auto-pick').addEventListener('click', startPicker);
+ automationPane.querySelector('#wbs-auto-cap').addEventListener('click', showCapabilities);
+ automationPane.querySelector('#wbs-auto-create').addEventListener('click', showExamples);
+ automationPane.querySelector('#wbs-auto-batch').addEventListener('click', function () { automationState.batchMode = true; automationPane.querySelector('#wbs-auto-normal-actions').style.display = 'none'; automationPane.querySelector('#wbs-auto-batch-actions').style.display = 'flex'; syncBatchControls(); render(); });
+ automationPane.querySelector('#wbs-auto-select-all').addEventListener('click', function () { var shouldSelect = !allSelected(); automationState.tasks.forEach(function (task) { automationState.selected[task.id] = shouldSelect; }); render(); syncBatchControls(); });
+ automationPane.querySelector('#wbs-auto-batch-cancel').addEventListener('click', function () { automationState.batchMode = false; automationState.selected = {}; automationPane.querySelector('#wbs-auto-normal-actions').style.display = 'flex'; automationPane.querySelector('#wbs-auto-batch-actions').style.display = 'none'; render(); });
+ automationPane.querySelector('#wbs-auto-batch-apply').addEventListener('click', function () { var ids = selectedIds(); if (!ids.length) { toast('请至少选择一项', true, root); return; } showAutomationConfirm('删除选中的自动化任务?', '删除后无法恢复。', function () { api('/api/automations/bulk', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ids: ids, action: 'delete' }) }).then(function () { automationState.selected = {}; automationState.batchMode = false; automationPane.querySelector('#wbs-auto-normal-actions').style.display = 'flex'; automationPane.querySelector('#wbs-auto-batch-actions').style.display = 'none'; return load(); }).catch(function (e) { toast(e.message || '批量操作失败', true, root); }); }); });
+ automationPane.querySelector('#wbs-auto-list').addEventListener('change', function (e) {
+ var id = e.target.getAttribute('data-auto-select');
+ if (id) {
+ automationState.selected[id] = !!e.target.checked;
+ syncBatchControls();
+ return;
+ }
+ var enabledId = e.target.getAttribute('data-auto-enabled');
+ if (!enabledId) return;
+ e.stopPropagation();
+ var next = !!e.target.checked;
+ e.target.disabled = true;
+ api('/api/automations/bulk', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ids: [enabledId], action: next ? 'enable' : 'disable' }) })
+ .then(function () { toast(next ? '任务已启用' : '任务已停用', false, root); return load(); })
+ .catch(function (err) { e.target.checked = !next; toast(err.message || '设置失败', true, root); })
+ .finally(function () { e.target.disabled = false; });
+ });
+ automationPane.querySelector('#wbs-auto-list').addEventListener('click', function (e) {
+ var button = e.target.closest && e.target.closest('button[data-auto-run],button[data-auto-stop],button[data-auto-logs],button[data-auto-edit],button[data-auto-copy],button[data-auto-delete]');
+ if (!button || !automationPane.querySelector('#wbs-auto-list').contains(button)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ var id = button.getAttribute('data-auto-run') || button.getAttribute('data-auto-stop') || button.getAttribute('data-auto-logs') || button.getAttribute('data-auto-edit') || button.getAttribute('data-auto-copy') || button.getAttribute('data-auto-delete');
+ if (!id) return;
+ var task = automationState.tasks.filter(function (item) { return item.id === id; })[0];
+ if (button.hasAttribute('data-auto-stop')) {
+ if (button.dataset.autoActionPending) return;
+ button.dataset.autoActionPending = '1';
+ var stopRunId = String(button.getAttribute('data-auto-stop') || '');
+ if (stopRunId) automationState.stopping[stopRunId] = true;
+ render(); // 立即进入“正在停止”转圈 + 置灰态
+ api('/api/automations/stop', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ runId: id }) })
+ .then(function () { toast('任务已停止', false, root); return load(); })
+ .catch(function (err) { toast(err.message || '停止失败', true, root); })
+ .finally(function () {
+ // 保持转圈至少一小段可感知窗口,再撤掉“停止中”标记,让按钮回到“运行”
+ setTimeout(function () { if (stopRunId) delete automationState.stopping[stopRunId]; render(); }, 900);
+ delete button.dataset.autoActionPending;
+ });
+ } else if (button.hasAttribute('data-auto-run')) {
+ if (button.dataset.autoActionPending) return;
+ button.dataset.autoActionPending = '1';
+ api('/api/automations/run', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: id }) })
+ .then(function (result) { if (result && result.run) automationState.runs.unshift(result.run); toast('任务已开始运行', false, root); render(); return load(); })
+ .catch(function (err) { toast(err.message || '运行失败', true, root); })
+ .finally(function () { delete button.dataset.autoActionPending; });
+ } else if (button.hasAttribute('data-auto-logs')) showAutomationLogs(task);
+ else if (button.hasAttribute('data-auto-edit')) showEditor(task);
+ else if (button.hasAttribute('data-auto-copy')) { var copy = JSON.parse(JSON.stringify(task)); copy.id = 'task_' + Date.now().toString(36); copy.name = task.name + '(副本)'; showEditor(copy); }
+ else if (button.hasAttribute('data-auto-delete')) showAutomationConfirm('删除该自动化任务?', '删除后无法恢复。', function () { api('/api/automations/bulk', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ids: [id], action: 'delete' }) }).then(load).catch(function (err) { toast(err.message || '删除失败', true, root); }); });
+ });
+ registerDisposer(function () { if (automationState.pollTimer) clearInterval(automationState.pollTimer); hideEditor(); (panel || root).querySelectorAll('.wbs-auto-dialog-mask').forEach(closePanelModal); });
+ load();
+ loadAgentInfo();
+ automationState.pollTimer = setInterval(load, 2500);
+ }
+
// ===== 会话 pane(构建:账号/时间筛选 + 按空间分组[默认2条/展开10条] + 刷新 + 批量操作[迁移/删除])=====
var sessionsState = { uid: undefined, currentUid: '', range: 'all', list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null, autoCopyAll: false };
function isTaskSessionRecordUI(s) {
@@ -5381,6 +6107,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<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-ask-row">' +
+ '<label class="wbs-ask-label" for="wbs-fab-auto-dock">机器人自动停靠<span class="wbs-ask-hint">闲置 5 秒后收起到窗口右侧,鼠标靠近边缘展开</span></label>' +
+ '<label class="wbs-switch"><input type="checkbox" id="wbs-fab-auto-dock"><span class="wbs-switch-slider"></span></label>' +
+ '</div></div>' +
'<div class="wbs-pcard wbs-wallpaper-card" id="wbs-wallpaper-card" style="display:none">' +
'<div class="wbs-pcard-title">壁纸</div>' +
'<div class="wbs-bg-source">' +
@@ -6013,6 +6744,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 主题 pane 事件绑定(元素在 buildThemePane 之后才存在,延迟到首次切换时绑定)
function wireThemePane() {
+ var dockSwitch = themePane.querySelector('#wbs-fab-auto-dock');
+ if (dockSwitch) {
+ dockSwitch.checked = fabQuietMode.isEnabled();
+ dockSwitch.addEventListener('change', function () { fabQuietMode.setEnabled(this.checked); });
+ }
// 主题选择:segmented 按钮直接切换
themePane.addEventListener('click', function (e) {
var t = e.target;
@@ -6314,17 +7050,31 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
- function setOpen(open) {
+ function setOpen(open, options) {
+ if (open && window.__wbsAutomationInputActive) {
+ toast('正在输入或切换账号,请稍后打开面板', false, root);
+ return;
+ }
+ var newlyOpened = open && !state.open;
+ // 面板还不可见时应用最新到期顺序;本次打开期间只更新数值,不移动账号。
+ if (newlyOpened && CAPS.accounts) {
+ state.activityRetryUsed = false;
+ sortAccountsByCreditExpiry();
+ reorderAccountCards();
+ }
state.open = open;
panel.classList.toggle('show', open);
fab.classList.toggle('hidden', open); // 打开时隐藏按钮
+ fabQuietMode.wake();
if (open) {
+ 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 {
- stopCheckinPolling();
+ state.accountRefreshId = (state.accountRefreshId || 0) + 1;
+ state.activityRunId++;
state.creditRunId++;
}
}
@@ -6337,6 +7087,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
handle.style.touchAction = 'none';
listen(handle, 'pointerdown', function (e) {
if (e.button !== undefined && e.button !== 0) return;
+ fab.classList.add('is-dragging');
+ fabQuietMode.wake();
var rect = fab.getBoundingClientRect();
fabDrag = {
pointerId: e.pointerId,
@@ -6347,7 +7099,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
};
fabDragMoved = false;
fabDragSuppressClick = false;
- fab.classList.add('is-dragging');
try { handle.setPointerCapture(e.pointerId); } catch (_) {}
if (e.preventDefault) e.preventDefault();
});
@@ -6376,6 +7127,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
applyFabPosition(fab, FAB_EDGE_GAP, bottom);
try { localStorage.setItem(FAB_POSITION_KEY, String(Math.round(bottom))); } catch (_) {}
fabDrag = null;
+ fabQuietMode.wake();
fabSnapTimer = setBuildTimeout(function () {
fabSnapTimer = null;
fab.classList.remove('is-snapping');
@@ -6388,6 +7140,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
+ var fabQuietMode = createFabQuietMode({
+ fab: fab, window: window, document: document, listen: listen,
+ storage: localStorage, settingKey: 'wbs-fab-auto-dock-' + PROFILE_ID,
+ isDragging: function () { return !!fabDrag; },
+ });
+ registerDisposer(fabQuietMode.destroy);
setupFabDrag();
fab.addEventListener('click', function (e) {
if (fabDragSuppressClick || fabDragMoved) {
@@ -6401,6 +7159,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
root.querySelector('[data-act="close"]').addEventListener('click', function () { setOpen(false); });
+ // 供 daemon 程序化开合面板:等价于「点机器人按钮/点关闭按钮」,复用同一 setOpen,
+ // 保证 DOM(.show/.hidden) 与 state.open 始终一致、完全可逆,不做任何 display 硬改。
+ // daemon 经 CDP dispatch: window.dispatchEvent(new CustomEvent('workdaddy:panel-open',{detail:{open:boolean}}))
+ var panelOpenBridge = function (event) {
+ var detail = event && event.detail && typeof event.detail === 'object' ? event.detail : {};
+ var open = !!detail.open;
+ if (open !== state.open) setOpen(open, detail);
+ };
+ listen(window, 'workdaddy:panel-open', panelOpenBridge);
+ registerDisposer(function () { try { window.removeEventListener('workdaddy:panel-open', panelOpenBridge); } catch (_) {} });
// 登录新账号:弹窗二选一 —— 方法一 假退出当前账号 / 方法二 无感登录
logoutBtn.addEventListener('click', function () {
@@ -6582,10 +7350,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
b.classList.toggle('active', b.getAttribute('data-theme') === cur);
});
syncWallpaperCardVisibility(cur);
- // 若当前主题不在允许列表(如之前应用了自定义主题),回退到默认主题
- if (d.current && ALLOWED_THEMES.indexOf(d.current) < 0 && cur === 'default') {
- applyTheme('default').catch(function () {});
- }
+ // 列表展示不能更改已保存的主题;主题只能由用户明确选择。
})
.catch(function () {});
}
@@ -6603,14 +7368,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var id = act ? act.getAttribute('data-theme') : null;
return id && id !== 'default' ? id : 'nebula';
}
- // 页面加载时应用已保存的主题(daemon 侧通过 CDP 注入,reload 后需重新应用)
- setBuildTimeout(function () {
- api('/api/themes').then(function (d) {
- if (d && d.current && d.current !== 'default') {
- applyTheme(d.current).catch(function () {});
- }
- }).catch(function () {});
- }, 1500);
+ // 页面主题由 daemon 在早期注入/加载时恢复;不要延迟 POST 旧主题,
+ // 否则旧页面的异步请求可能覆盖用户刚选择的主题。
// ===== 元素检查(隐藏入口,实现抽离在 picker-internal.js,git 不跟踪)=====
// 连续点击面板标题 5 次 → 在标题右侧显示「🔍 拾取」按钮;点击进入拾取模式。
@@ -8585,8 +9344,39 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 切换必须走 daemon /api/cdp-click 真实鼠标点击(官方拒绝 isTrusted=false 的 click())。
// 已知边界:已停住且官方不渲染「允许/拒绝」按钮的 pending 会话,激活后无弹窗可点,
// 3s 内判 approval-no-dialog 立即切回。
- var acAutoApprove = { busy: false, lastRunAt: 0, timer: null, gateLogAt: 0 };
+ var acAutoApprove = { busy: false, lastRunAt: 0, timer: null, gateLogAt: 0, episodes: {} };
+ // 侧栏后台「待确认」会话的自动批准链路(acAutoApprovePendingOnce→真实鼠标切过去看有无弹窗)。
+ // 之前曾因每心跳反复切、把指针从当前会话强行挪开导致“鼠标自己动+等待允许刷屏”(2026-09-07)而整体关闭。
+ // 现改为**按会话 id 的“待确认 episodes 缓存”**恢复并抑制重复切换(用户方案 2026-09-07):
+ // 每个会话进入一次“待确认”episode,最多切过去 1 次看详情;
+ // 若该会话实际无「允许/拒绝」弹窗可点(no-dialog)→ 记为 episodes[sid].noAction,
+ // 在其**持续待确认期间不再切换**;直到它离开待确认(状态恢复/被处理)才清掉该标记,
+ // 下次它再待确认时允许再切 1 次。前台会话的允许弹窗仍由 ndAutoObserver(弹窗自动点允许开关)照常处理。
var AC_AUTO_APPROVE_ENABLED = true;
+ // 解析侧栏待确认 .conversation-item → 官方会话 id(title 匹配 acMulti.sessions,key 需稳定 id)
+ function acPendingItemSessionId(item) {
+ if (!item) return '';
+ try {
+ var own = item.getAttribute && (item.getAttribute('data-conversation-id') || item.getAttribute('data-id') || item.getAttribute('data-root-id'));
+ if (own) return own;
+ } catch (_) {}
+ var title = '';
+ try {
+ var te = item.querySelector('[class*="title"],[class*="name"],[class*="agentName"],[class*="agent-name"]');
+ if (te) title = (te.textContent || '').replace(/\s+/g, ' ').trim();
+ } catch (_) {}
+ if (title) {
+ var hit = null;
+ Object.keys(acMulti.sessions).forEach(function (id) {
+ if (hit) return;
+ var s = acMulti.sessions[id];
+ var st = String(s.title || '').replace(/\s+/g, ' ').trim();
+ if (st && (st === title || st.indexOf(title) !== -1 || title.indexOf(st) !== -1)) hit = id;
+ });
+ if (hit) return hit;
+ }
+ return 'title:' + title; // 无 id 时退化按标题做 episode key(防重复至少能覆盖同会话)
+ }
function acCdpClick(x, y) {
if (!Number.isFinite(x) || !Number.isFinite(y)) return Promise.resolve(false);
return api('/api/cdp-click', {
@@ -8635,6 +9425,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
window.__wbsAutoApproveGate = {
nd: !!ndAutoObserver, busy: !!acAutoApprove.busy, running: !!acRunning,
mode: acMulti.mode, at: new Date().toISOString(),
+ episodes: acAutoApprove.episodes ? Object.keys(acAutoApprove.episodes).length : 0,
tags: (function () { try { return document.querySelectorAll('.cb-agent-card__status-tag, .conversation-item [class*="status-tag"]').length; } catch (_) { return -1; } })(),
};
} catch (_) {}
@@ -8660,6 +9451,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
break;
}
if (!target) { try { window.__wbsAutoApproveGateTarget = { found: false, at: new Date().toISOString() }; } catch (_) {} return; }
+ // —— episodes 缓存去重(用户方案):同一会话“本次待确认”只切过去 1 次 ——
+ var sid = acPendingItemSessionId(target);
+ var ep = sid ? (acAutoApprove.episodes[sid] || null) : null;
+ // 若该会话在本次待确认 episode 内已被“看过一次”(无论判 noAction 还是 timeout)→ 直接跳过,
+ // 严格保证同一待确认 episode 只切过去 1 次。该标记由 acAutoApproveReleaseStale()
+ //(每次 discover 时,依据实时待确认信号)在会话离开待确认后清除,下次再待确认可再切。
+ if (ep && ep.visited) {
+ try { window.__wbsAutoApproveSkip = { sid: sid, reason: 'episode-visited', noAction: !!ep.noAction, at: new Date().toISOString() }; } catch (_) {}
+ return;
+ }
+ // 首次进入该会话的待确认 episode → 标记后切过去看详情
+ if (sid) acAutoApprove.episodes[sid] = { seenPending: true, noAction: false, visited: false, since: Date.now(), title: targetTitle.slice(0, 40) };
// 记录原会话:优先官方激活会话 id → registry title;回退取 selected 侧栏项标题
var originTitle = '';
var originItemRef = null;
@@ -8721,8 +9524,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (still && !noDialog && waited < 15000) return;
if (acAutoApprove.timer) { clearInterval(acAutoApprove.timer); acAutoApprove.timer = null; }
acMonitorLog('(auto-approve)', still ? (noDialog ? 'approval-no-dialog' : 'approval-timeout') : 'approval-resolved', { title: tTitle.slice(0, 40), waitedMs: waited * 1000 });
- // no-dialog(官方不渲染按钮)场景拉长冷却,避免反复激活/切回造成页面闪烁
- if (still && noDialog) acAutoApprove.lastRunAt = Date.now() + 10000;
+ // —— episodes 结果落账:本次 episode 已切过去看过一次,记 visited;no-dialog 额外记 noAction ——
+ if (sid) {
+ var ecur = acAutoApprove.episodes[sid] || { seenPending: true, since: Date.now() };
+ ecur.seenPending = true;
+ if (still) {
+ ecur.visited = true; // 本次 episode 已切过去看过一次(无论 no-dialog 还是 timeout)→ 之后不再切,直到离开待确认
+ if (noDialog) ecur.noAction = true;
+ } else {
+ delete acAutoApprove.episodes[sid]; ecur = null; // 已离开待确认 → episode 结束并释放
+ }
+ if (ecur) acAutoApprove.episodes[sid] = ecur;
+ }
+ // visited 已挡住本 episode 的反复切换,冷却短一些即可
+ acAutoApprove.lastRunAt = Date.now() + 3000;
// 切回原会话:优先复用激活前捕获的 DOM 引用,其次按标题(包含匹配)重查,
// 全部走真实点击(daemon CDP)。结果写入 window.__wbsAutoApproveRestored 供诊断。
var originItem = (originItemRef && originItemRef.isConnected) ? originItemRef : null;
@@ -8736,6 +9551,53 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}, 1000);
}
+ // 每次 discover 心跳调用:释放已“离开待确认”的会话 episode,使下次它再待确认时允许重新切过去。
+ // “仍待确认”只认**当拍仍可见的 pending 信号**(侧栏 tag 实时扫 + controller 数据层 resourcePendingInputKind),
+ // 不依赖易滞留的 session.status(sidebar 途径可能残留 awaiting-approval)。只有仍待确认的会话才保留 episodes。
+ function acAutoApproveReleaseStale() {
+ try {
+ var stillPending = {};
+ // a) 侧栏实时 tag → 匹配到会话 id
+ var tags;
+ try {
+ tags = document.querySelectorAll('.cb-agent-card__status-tag, .conversation-item [class*="status-tag"], .conversation-item [class*="statusTag"]');
+ } catch (_) { tags = []; }
+ for (var i = 0; i < tags.length; i++) {
+ var label = (tags[i].textContent || '').replace(/\s+/g, ' ').trim();
+ if (!/(待确认|等待确认|等待允许|待处理|待审批|等待批准|待用户确认|待人工确认|awaiting|pending.*approval|waiting.*approval|needs approval|requires approval)/i.test(label)) continue;
+ var item = tags[i].closest('.conversation-item');
+ if (!item) continue;
+ var sid2 = acPendingItemSessionId(item);
+ if (sid2) stillPending[sid2] = true;
+ }
+ // b) controller 数据层:resourcePendingInputKind 仍置位 → 视为待确认
+ Object.keys(acMulti.sessions).forEach(function (id) {
+ var s = acMulti.sessions[id];
+ if (s && s.resourcePendingInputKind) stillPending[id] = true;
+ });
+ // c) 清理:不在 stillPending 的 episode 一律释放;title 退化 key 若其标题会话不在 stillPending 也释放
+ Object.keys(acAutoApprove.episodes).forEach(function (key) {
+ var isId = acMulti.sessions[key];
+ if (isId) {
+ if (!stillPending[key]) delete acAutoApprove.episodes[key];
+ return;
+ }
+ if (key.indexOf('title:') === 0) {
+ var t = key.slice(6);
+ var alive = false;
+ if (t) {
+ Object.keys(acMulti.sessions).forEach(function (id) {
+ if (alive || !stillPending[id]) return;
+ var st2 = String(acMulti.sessions[id].title || '').replace(/\s+/g, ' ').trim();
+ if (st2 && (st2 === t || st2.indexOf(t) !== -1 || t.indexOf(st2) !== -1)) alive = true;
+ });
+ }
+ if (!alive) delete acAutoApprove.episodes[key];
+ }
+ });
+ } catch (_) {}
+ }
+
var acAutoApproveFastTimer = null;
function acAutoApproveFastStart() {
if (acAutoApproveFastTimer) return;
@@ -8754,6 +9616,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function acMultiDiscover() {
if (!acRunning || acMulti.mode !== 'multi') return;
acMultiProbeSidebarApproval();
+ acAutoApproveReleaseStale(); // 释放已离开待确认的会话 episode(在切换决策前)
acAutoApprovePendingOnce();
var controllers = [];
try {
@@ -9527,7 +10390,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function checkinBadgeHtml(a) {
- var tag = checkinHtml(a);
+ var tag = checkinHtml(a) + activityStreakHtml(a);
return tag ? '<span class="wbs-checkin-slot">' + tag + '</span>' : '';
}
@@ -9592,6 +10455,34 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
+ function mergeAccountSnapshot(previous, incoming) {
+ var byUid = new Map();
+ (incoming || []).forEach(function (account) { byUid.set(account.uid, Object.assign({}, account)); });
+ var merged = [];
+ previous.forEach(function (cached) {
+ var account = byUid.get(cached.uid);
+ if (!account) return; // 删除的账号不能被缓存复活。
+ ['credits', 'creditSegments', 'creditUnlimited', 'creditExpired'].forEach(function (key) {
+ if (account[key] === undefined && cached[key] !== undefined) account[key] = cached[key];
+ });
+ if (!isKnownActivityStreak(account.activityStreak) && isKnownActivityStreak(cached.activityStreak)) {
+ account.activityStreak = cached.activityStreak;
+ }
+ merged.push(account);
+ byUid.delete(cached.uid);
+ });
+ byUid.forEach(function (account) { merged.push(account); });
+ return merged;
+ }
+
+ function accountCardLayoutKey() {
+ // 积分/签到刷新不应重建切换按钮,保留焦点和两击确认状态。
+ var rows = state.accounts.map(function (a) {
+ return [a.uid, a.nickname, a.phone, a.uin, a.type, a.enterpriseName, a.tokenExpiresAt, isIdentityExpired(a)];
+ }).sort(function (a, b) { return String(a[0]).localeCompare(String(b[0])); });
+ return JSON.stringify([state.current && state.current.uid, state.primaryUid, rows]);
+ }
+
function pollAutoCopyJob(jobId, accountName) {
if (!jobId) return;
var attempts = 0;
@@ -9631,18 +10522,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function render(data) {
+ var previous = state.accounts;
state.current = data.current;
- state.accounts = (data.accounts || []).slice();
- // 账号排序:按积分到期时间升序(最近到期最前),不再把当前账号置顶
- state.accounts.sort(function (left, right) {
- var le = nearestCreditExpiry(left);
- var re = nearestCreditExpiry(right);
- if (le !== re) return le - re;
- return 0;
- });
+ state.accounts = mergeAccountSnapshot(previous, data.accounts || []);
+ state.primaryUid = data.primaryUid || '';
+ if (!previous.length || !state.open) sortAccountsByCreditExpiry();
state.creditRemaining = state.accounts.length;
updateAccountSummary();
var list = accountsPane.querySelector('.wbs-acct-list');
+ var layoutKey = accountCardLayoutKey();
+ if (list && state.accountLayoutKey === layoutKey) {
+ updateCheckinCells(state.accounts);
+ state.accounts.forEach(function (account) { updateCreditCell(account.uid, account.credits, account.creditSegments); });
+ return;
+ }
+ state.accountLayoutKey = layoutKey;
if (!list) { list = el('div', 'wbs-acct-list'); accountsPane.insertBefore(list, accountsPane.firstChild); }
list.innerHTML = '';
if (!state.accounts.length) {
@@ -9658,16 +10552,17 @@ 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 curMark = isCur ? '<span class="wbs-cur-marker" title="当前使用中">' + CUR_MARK_SVG + '</span>' : '';
// 当前登录账号隐藏操作;认证已过期的账号保留删除,但隐藏切换,避免进入登录页。
var expired = isIdentityExpired(a);
- var ops = (isCur
+ var ops = primaryAction + (isCur
? ''
: (expired ? '' : '<button class="wbs-icon-btn wbs-acc-switch" type="button" title="切换" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(a.nickname || '未命名') + '">' + SWITCH_SVG + '</button>') +
'<button class="wbs-icon-btn wbs-del" type="button" title="删除" data-uid="' + escAttr(a.uid) + '" data-name="' + escAttr(a.nickname || '未命名') + '">' + TRASH_SVG + '</button>');
- ops = ops ? '<div class="wbs-ops">' + ops + '</div>' : '';
+ ops = '<div class="wbs-ops"' + (isCur && isPrimary ? ' hidden' : '') + '>' + ops + '</div>';
// 国际版没有手机号:用 UIN(账号唯一数字标识)替代展示;国内版仍显示手机。
// UIN 与手机号共用同一标签和值间距,确保与“剩余”额度列对齐。
var isUinMode = !a.phone;
@@ -9677,9 +10572,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var nameVal = state.mask ? maskAccountName(rawName) : rawName;
var idVal = state.mask ? maskAccountId(rawId) : rawId;
card.innerHTML =
- curMark +
'<div class="wbs-info">' +
- '<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + esc(nameVal) + '</span>' + badge + checkinBadge + '</div>' + ops + '</div>' +
+ '<div class="wbs-row1"><div class="wbs-name-group"><span class="wbs-name">' + esc(nameVal) + '</span>' + primaryBadge + badge + checkinBadge + '</div>' + ops + '</div>' +
'<div class="wbs-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>' +
@@ -9688,6 +10582,31 @@ 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) {
@@ -9829,17 +10748,27 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (sessionsPane && !sessionsPane.dataset.built) buildSessionsPane();
return;
}
- stopCheckinPolling();
state.creditRunId++;
- api('/api/accounts')
+ state.activityRunId++;
+ var requestId = state.accountRefreshId = (state.accountRefreshId || 0) + 1;
+ return api('/api/accounts')
.then(function (data) {
+ if (!alive || requestId !== state.accountRefreshId) return;
render(data);
- watchCheckin(data.checkin);
fetchCreditsForAccounts();
+ fetchActivityForAccounts();
})
.catch(function (e) {
+ if (!alive || requestId !== state.accountRefreshId) return;
+ if (state.accounts.length) {
+ toast('账号刷新失败,已保留上次结果', true, root);
+ return;
+ }
var msg = '<div class="wbs-empty">无法连接本地服务: ' + esc(e.message || e) + '<br>请确认守护进程已运行</div>';
- accountsPane.innerHTML = msg;
+ var list = accountsPane.querySelector('.wbs-acct-list');
+ if (!list) { list = el('div', 'wbs-acct-list'); accountsPane.insertBefore(list, accountsPane.firstChild); }
+ list.innerHTML = msg;
+ state.accountLayoutKey = null;
});
}
@@ -9875,6 +10804,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
for (var j = 0; j < state.accounts.length; j++) {
if (state.accounts[j].uid === a.uid) {
state.accounts[j].checkin = a.checkin;
+ if (Object.prototype.hasOwnProperty.call(a, 'activityStreak') &&
+ (isKnownActivityStreak(a.activityStreak) || !isKnownActivityStreak(state.accounts[j].activityStreak))) {
+ state.accounts[j].activityStreak = a.activityStreak;
+ }
if (Object.prototype.hasOwnProperty.call(a, 'todayUsage')) state.accounts[j].todayUsage = a.todayUsage;
byUid[a.uid] = state.accounts[j];
break;
@@ -9908,35 +10841,65 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
}
- function stopCheckinPolling() {
- if (state.checkinPollId !== null) {
- clearTimeout(state.checkinPollId);
- state.checkinPollId = null;
- }
- }
+ // 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;
+ accountRefreshPending = true;
+ setBuildTimeout(function () {
+ accountRefreshPending = false;
+ if (!state.open) return;
+ api('/api/accounts').then(function (data) { if (state.open) updateCheckinCells(data.accounts || []); }).catch(function () {});
+ }, 150);
+ });
- function watchCheckin(status) {
- stopCheckinPolling();
- if (!status || !status.running || !state.open) return;
- var startedAt = Date.now();
- function poll() {
- state.checkinPollId = null;
- if (!state.open || Date.now() - startedAt > 45000) return;
- api('/api/accounts?checkinStatus=1')
- .then(function (data) {
- updateCheckinCells(data.accounts || []);
- if (data.checkin && data.checkin.running && state.open) {
- state.checkinPollId = setBuildTimeout(poll, 800);
- } else if (state.open) {
- // 签到请求完成后再查询积分,避免第一次打开面板显示签到前余额。
- fetchCreditsForAccounts();
+ var activityBatchPromise = null;
+ var activityBatchPending = false;
+ var activityRetryTimer = null;
+ function fetchActivityForAccounts() {
+ if (!alive || WBS_PROFILE_IS_AI || !state.open || !CAPS.accounts) return;
+ clearTimeout(activityRetryTimer);
+ var runId = ++state.activityRunId;
+ // 快速重开时先让上一批在途请求结束,跨批次也最多两个并发。
+ if (activityBatchPromise) { activityBatchPending = true; return; }
+ var accounts = state.accounts.slice();
+ var next = 0;
+ var retryAt = 0;
+ function worker() {
+ if (!alive || !state.open || runId !== state.activityRunId || next >= accounts.length) return Promise.resolve();
+ var account = accounts[next++];
+ return api('/api/growth/streak', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ uid: account.uid }) })
+ .then(function (result) { return result.activityStreak; })
+ .catch(function () { return { days: null, status: 'unavailable' }; })
+ .then(function (value) {
+ if (!alive || !state.open || runId !== state.activityRunId) return;
+ var current = state.accounts.filter(function (a) { return a.uid === account.uid; })[0];
+ if (!current) return;
+ if (!isKnownActivityStreak(value)) {
+ // daemon 对失败退避 30 秒:到期后再重试,避免重开面板时反复命中失败缓存。
+ retryAt = Math.max(retryAt, (Number(value && value.fetchedAt) || Date.now()) + 30100);
}
- })
- .catch(function () {
- if (state.open) state.checkinPollId = setBuildTimeout(poll, 1200);
- });
+ if (isKnownActivityStreak(value) || !isKnownActivityStreak(current.activityStreak)) current.activityStreak = value;
+ accountsPane.querySelectorAll('.wbs-card').forEach(function (card) {
+ if (card.getAttribute('data-uid') !== current.uid) return;
+ var slot = card.querySelector('.wbs-checkin-slot');
+ if (slot) slot.outerHTML = checkinBadgeHtml(current);
+ });
+ }).then(worker);
}
- state.checkinPollId = setBuildTimeout(poll, 500);
+ activityBatchPromise = Promise.all([worker(), worker()]).finally(function () {
+ activityBatchPromise = null;
+ if (activityBatchPending) {
+ activityBatchPending = false;
+ fetchActivityForAccounts();
+ return;
+ }
+ if (!alive || !state.open || runId !== state.activityRunId || !retryAt || state.activityRetryUsed) return;
+ state.activityRetryUsed = true;
+ activityRetryTimer = setBuildTimeout(function () {
+ if (alive && state.open && runId === state.activityRunId) fetchActivityForAccounts();
+ }, Math.max(0, retryAt - Date.now()));
+ });
}
// 积分查询按 200ms 节奏发起,允许请求重叠,避免前一个账号的慢接口阻塞后续账号。
@@ -9947,8 +10910,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
state.creditRemaining = accounts.length;
function settleBatch() {
if (runId !== state.creditRunId || state.creditRemaining !== 0) return;
- sortAccountsByCreditExpiry();
- reorderAccountCards();
+ // 到期信息留在缓存,下次打开前排序,避免响应回来时点到另一账号。
var sum = 0;
state.accounts.forEach(function (account) {
if (typeof account.credits === 'number' && isFinite(account.credits)) sum += account.credits;
@@ -9996,6 +10958,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
state.accounts[i].credits = credits;
state.accounts[i].creditSegments = segments;
state.accounts[i].creditUnlimited = unlimited;
+ state.accounts[i].creditExpired = false;
if (hasTodayUsage) state.accounts[i].todayUsage = r.todayUsage;
break;
}
@@ -10009,6 +10972,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var accountExpired = !!(e && e.payload && e.payload.expired);
for (var i = 0; i < state.accounts.length; i++) {
if (state.accounts[i].uid === a.uid) {
+ if (!accountExpired && state.accounts[i].credits !== undefined) return;
state.accounts[i].credits = null;
state.accounts[i].creditSegments = [];
state.accounts[i].creditUnlimited = false;
@@ -10168,6 +11132,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (bodyObserver) { try { bodyObserver.disconnect(); } catch (e) {} bodyObserver = null; }
sessionHealthTimer = null;
});
+ registerDisposer(function () {
+ try { if (typeof window.__wbsStopAutomationPicker === 'function') window.__wbsStopAutomationPicker(); } catch (e) {}
+ var automationInspector = document.getElementById('wbs-auto-inspector');
+ if (automationInspector && automationInspector.__wbsClose) automationInspector.__wbsClose();
+ else if (automationInspector) automationInspector.remove();
+ var automationPickerStyle = document.getElementById('wbs-automation-picker-style');
+ if (automationPickerStyle) automationPickerStyle.remove();
+ });
registerDisposer(function () {
try { if (typeof window.__wbsStopPicked === 'function') window.__wbsStopPicked(); } catch (e) {}
var inspector = document.getElementById('wbs-inspector');
@@ -10285,7 +11257,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'html.cb-dark .wbs-message-nav-tooltip,html[data-theme="dark"] .wbs-message-nav-tooltip,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-tooltip{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 70%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.14));color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 14px 38px rgba(0,0,0,.42),inset 0 1px 0 rgba(255,255,255,.08)}',
'@media (prefers-reduced-motion:reduce){.wbs-message-nav-marker,.wbs-message-nav-dot,.wbs-message-nav-tooltip{transition:none!important}.wbs-message-nav-highlight{animation:none!important}}',
/* 机器人悬浮按钮(bitter-dragon-16 移植):静态版 0.5 倍 · 无头顶尖角 · 眼睛双眨 */
- '.wbs-fab{position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;will-change:right,bottom}',
+ '.wbs-fab{position:fixed;right:22px;bottom:22px;z-index:2147483647;transform:scale(0.5);transform-origin:bottom right;cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;will-change:transform;transition:transform .22s cubic-bezier(.22,1,.36,1)}',
'.wbs-fab-health-dot{position:absolute;top:-5px;left:-5px;width:14px;height:14px;border-radius:50%;background:#8b8f98;border:2px solid #141416;box-shadow:0 1px 3px rgba(0,0,0,.5);z-index:3}',
'.wbs-fab-health-dot.running{background:#4da3ff}.wbs-fab-health-dot.blocked{background:#ffb03a}.wbs-fab-health-dot.error{background:#ef6262}.wbs-fab-health-dot.suspected{background:#f08a3c}.wbs-fab-health-dot.stopped{background:#9ca3af}',
'.wbs-health-status{display:none;align-items:center;min-height:18px;padding:2px 7px;border-radius:999px;font-size:10px;line-height:14px;white-space:nowrap;color:var(--wb-color-text-secondary,#666);background:var(--wb-bg-tertiary,#f2f2f2)}',
@@ -10296,7 +11268,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'@keyframes wbs-sleep-pulse{0%,100%{box-shadow:0 0 5px 1px rgba(46,229,157,.6)}50%{box-shadow:0 0 13px 4px rgba(46,229,157,.95)}}',
'@keyframes wbs-sleep-pulse-amber{0%,100%{box-shadow:0 0 5px 1px rgba(255,176,58,.6)}50%{box-shadow:0 0 13px 4px rgba(255,176,58,.95)}}',
'.wbs-fab.hidden{display:none}',
- '.wbs-fab .click{position:relative}',
+ '.wbs-fab .click{position:relative;transition:transform .22s cubic-bezier(.22,1,.36,1)}',
'.wbs-fab .click > span:not(.wbs-fab-antenna){display:none}',
'.wbs-fab .button.shadow{display:none}',
'.wbs-fab .button{position:relative;left:0;top:0;transform:none;cursor:pointer;border:solid 4px rgba(255,255,255,0);background-color:rgba(20,20,22,.55);backdrop-filter:blur(14px) saturate(1.3);-webkit-backdrop-filter:blur(14px) saturate(1.3);font-size:20px;color:#fff;border-color:rgba(255,255,255,0);box-shadow:0 4px 14px rgba(0,0,0,.45),inset 0 0 0 1px rgba(255,255,255,.08);border-radius:50px;display:flex;align-items:center;justify-content:center;width:100px;height:48px;box-sizing:content-box;padding:0;margin:0;outline:none;transition:background-color .2s,color .2s}',
@@ -10327,14 +11299,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'@keyframes wbs-cc-upb{0%,10%{top:0;left:0%}20%,40%{top:-50%;left:0%}50%,100%{top:0;left:0%}}',
'.wbs-fab:hover{transform:scale(0.5)}',
'.wbs-fab:active{transform:scale(0.5) translate(2px,2px)}',
+ '.wbs-fab.is-quiet{transform:translateX(var(--wbs-fab-quiet-shift,59px)) scale(0.5)}',
+ '.wbs-fab.is-quiet .click{transform:rotate(-90deg)}',
+ '.wbs-fab.is-quiet .wbs-fab-health-dot{visibility:hidden}',
+ '.wbs-fab.is-quiet .wbs-fab-antenna,.wbs-fab.is-quiet .wbs-fab-antenna-dot{visibility:hidden}',
+ '.wbs-fab .button:focus-visible{outline:3px solid var(--wb-accent-blue,#4f86ff);outline-offset:5px}',
+ '@media(prefers-reduced-motion:reduce){.wbs-fab,.wbs-fab .click{transition:none!important}}',
'.wbs-fab.is-dragging{cursor:grabbing;transition:none !important}',
+ '.wbs-fab.is-dragging .click{transition:none}',
'.wbs-fab.is-dragging .button{cursor:grabbing}',
'.wbs-fab.is-snapping{transition:right .56s cubic-bezier(.22,1.35,.36,1),bottom .56s cubic-bezier(.22,1.35,.36,1)}',
/* 面板:毛玻璃主题(半透明 + 模糊,背景图透出) */
- '.wbs-panel{position:absolute;right:0;bottom:0;width:520px;max-width:94vw;height:650px;max-height:650px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden;backdrop-filter:blur(28px) saturate(1.25);-webkit-backdrop-filter:blur(28px) saturate(1.25)}',
+ '.wbs-panel{position:absolute;right:0;bottom:0;width:720px;max-width:94vw;height:650px;max-height:650px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden;backdrop-filter:blur(28px) saturate(1.25);-webkit-backdrop-filter:blur(28px) saturate(1.25)}',
'.wbs-panel.show{display:flex}',
- // 英文文案更长:EN 模式面板宽度放大 1.35 倍(520px -> 702px),配合 label 自适应避免挤压
- 'html[data-wbs-language="en"] .wbs-panel{width:702px}',
+ // 英文文案更长:英文面板额外加宽,配合 label 自适应避免挤压
+ 'html[data-wbs-language="en"] .wbs-panel{width:880px}',
// EN 下固定宽度 label 容易溢出:phone/credit/token 列的 label 释放为自适应宽度
'html[data-wbs-language="en"] .wbs-phone-cell .wbs-lbl,html[data-wbs-language="en"] .wbs-credit-left .wbs-lbl{width:auto;max-width:84px}',
'html[data-wbs-language="en"] .wbs-token-cell .wbs-lbl{width:auto;max-width:96px}',
@@ -10345,7 +11324,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-lang-seg .wbs-sess-seg-btn{padding:6px 14px}',
'.wbs-head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px 12px;border-bottom:1px solid var(--wb-border-subtle,#f0f0f0);background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 30%,transparent)}',
'.wbs-head-left{display:flex;align-items:center;gap:9px;min-width:0}',
+ '.wbs-title-wrap{display:flex;flex-direction:column;align-items:flex-start;min-width:0}',
+ '.wbs-title-row{display:flex;align-items:center;gap:9px;min-width:0}',
'.wbs-title{font-size:16px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);letter-spacing:.3px;cursor:pointer;user-select:none}',
+ '.wbs-version-line{margin-top:1px;color:var(--wb-color-text-tertiary,#a3a6ad);font-size:10px;font-weight:400;line-height:1.2;letter-spacing:0;font-variant-numeric:tabular-nums;white-space:nowrap}',
/* 元素检查拾取按钮(隐藏入口,连点标题 5 次显示) */
'.wbs-pick-btn{flex:0 0 auto;width:22px;height:22px;border:none;border-radius:7px;background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 14%,transparent);color:var(--wb-accent-blue,#4f86ff);font-size:12px;line-height:1;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:background .15s}',
'.wbs-pick-btn:hover{background:color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 24%,transparent)}',
@@ -10362,7 +11344,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-ava{width:34px;height:34px;border-radius:50%;background:var(--wb-bg-tertiary,#f0f0f0);color:var(--wb-icon-secondary,#555);display:flex;align-items:center;justify-content:center;font-weight:600;flex-shrink:0;font-size:14px}',
'.wbs-info{min-width:0}',
'.wbs-row1{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:7px;min-height:26px}',
- '.wbs-name-group{display:flex;align-items:center;gap:6px;min-width:0}',
+ '.wbs-name-group{display:flex;align-items:center;flex-wrap:wrap;gap:6px;min-width:0}.wbs-checkin-slot{display:inline-flex;align-items:center;flex-wrap:wrap;gap:5px}.wbs-activity-tag{min-width:74px;justify-content:center;box-sizing:border-box;font-variant-numeric:tabular-nums}',
'.wbs-name{font-size:14px;font-weight:600;color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-meta{display:flex;flex-direction:column;gap:2px}',
'.wbs-secondary-row{flex-direction:row;align-items:center;justify-content:space-between;gap:12px;margin-bottom:8px}',
@@ -10418,10 +11400,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-credit-loading{color:var(--wb-icon-tertiary,#999);font-size:12px}',
'.wbs-credit-na{color:var(--wb-icon-tertiary,#999);font-size:12px}',
'.wbs-ck{font-size:11px;font-weight:600}',
- '.wbs-checkin-tag{display:inline-flex;align-items:center;min-height:18px;padding:1px 7px;border-radius:999px;white-space:nowrap}',
+ '.wbs-checkin-tag{display:inline-flex;align-items:center;min-height:18px;padding:1px 7px;border:1px solid transparent;border-radius:999px;white-space:nowrap}',
'.wbs-checkin-tag.pending{background:var(--wb-bg-tertiary,#f0f0f0);color:var(--wb-icon-tertiary,#999)}',
'.wbs-checkin-tag.ok{background:#edf9ef;border:1px solid #b9e8c0;color:#28753a;box-shadow:inset 0 0 0 1px rgba(255,255,255,.55)}',
- 'html.cb-dark .wbs-checkin-tag.ok{background:rgba(19,24,33,.78);border-color:rgba(214,220,232,.24);color:#f3f5fa;box-shadow:inset 0 0 0 1px rgba(255,255,255,.06)}',
+ 'html.cb-dark .wbs-checkin-tag.ok,html[data-theme="dark"] .wbs-checkin-tag.ok{background:rgba(19,24,33,.78);border-color:rgba(214,220,232,.24);color:#f3f5fa;box-shadow:inset 0 0 0 1px rgba(255,255,255,.06)}',
'.wbs-checkin-tag.fail{background:rgba(239,68,68,.1);color:#dc2626}',
'.wbs-ck.ok{color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-ck.pending{color:var(--wb-icon-tertiary,#999)}',
@@ -10442,8 +11424,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-badge{display:inline-flex;align-items:center;font-size:10px;line-height:1;padding:2px 7px;border-radius:999px;flex-shrink:1;min-width:0;max-width:112px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;background:var(--wb-bg-tertiary,#eef0f3);color:var(--wb-color-text-secondary,#5f6368);border:1px solid transparent}',
'html.cb-dark .wbs-badge,html[data-theme="dark"] .wbs-badge{background:rgba(255,255,255,.07);color:rgba(235,236,240,.68);border-color:rgba(255,255,255,.08)}',
/* 当前使用中角标:无底图形,颜色跟随昵称(text-primary),深色随变量自动适配 */
- '.wbs-cur-marker{position:absolute;top:9px;right:12px;display:inline-flex;color:var(--wb-icon-secondary,#555);opacity:.9}',
- '.wbs-cur-marker svg{display:block}',
'.wbs-empty{text-align:center;color:var(--wb-icon-tertiary,#999);padding:28px 12px;font-size:13px;line-height:1.8}',
/* 底部 */
'.wbs-foot{padding:12px 14px;border-top:1px solid var(--wb-border-subtle,#f0f0f0);display:flex;flex-direction:column;gap:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 30%,transparent)}',
@@ -10467,6 +11447,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-ask-row{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:8px}',
'.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-fab-settings .wbs-switch-slider{background:var(--wb-bg-tertiary,#e5e5e5);box-shadow:inset 0 0 0 1px var(--wb-border-default,#d0d0d0)}.wbs-fab-settings .wbs-switch-slider:before{background:var(--wb-color-text-secondary,#777)}.wbs-fab-settings input:checked + .wbs-switch-slider{background:var(--wb-button-primary-bg,#1f1f1f)}.wbs-fab-settings input:checked + .wbs-switch-slider:before{background:var(--wb-button-primary-fg,#fff)}.wbs-fab-settings input:focus-visible + .wbs-switch-slider{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:3px}',
'.wbs-switch{position:relative;display:inline-block;width:36px;height:20px;flex-shrink:0;cursor:pointer}',
'.wbs-switch input{opacity:0;width:0;height:0}',
'.wbs-switch-slider{position:absolute;inset:0;border-radius:20px;background:rgba(255,255,255,.16);box-shadow:inset 0 0 0 1px rgba(255,255,255,.22);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);transition:background .18s}',
@@ -10565,9 +11547,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-stash-item .cb-message-queue-item-left .content{opacity:.55}',
'.wbs-spin{display:inline-block;width:13px;height:13px;border:2px solid rgba(255,255,255,.35);border-top-color:#fff;border-radius:50%;animation:wbs-spin-rotate .8s linear infinite;vertical-align:-2px}',
'@keyframes wbs-spin-rotate{to{transform:rotate(360deg)}}',
- '.wbs-toast{position:fixed;left:50%;bottom:100px;transform:translateX(-50%);background:#1f1f1f;color:#fff;padding:9px 16px;border-radius:10px;font-size:12px;z-index:2147483647;opacity:1;transition:opacity .3s;max-width:80vw;pointer-events:none;box-shadow:0 6px 20px rgba(0,0,0,.18)}',
- '.wbs-toast.err{background:#f53f3f}',
- '.wbs-toast.out{opacity:0}',
/* ===== 新版 Tab 布局(账号/主题/增强)===== */
'.wbs-tabs{display:flex;gap:6px;padding:10px 14px 0;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 25%,transparent);overflow-x:auto;scrollbar-width:none}',
'.wbs-tabs::-webkit-scrollbar{display:none}',
@@ -10586,6 +11565,33 @@ 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}',
+ '.wbs-auto-normal-actions .wbs-auto-pick-btn{border-color:var(--wb-button-primary-bg,#1f1f1f);background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}.wbs-auto-normal-actions .wbs-auto-pick-btn:hover,.wbs-auto-normal-actions .wbs-auto-pick-btn:focus-visible{background:var(--wb-button-primary-hover-bg,var(--wb-button-primary-bg,#1f1f1f));color:var(--wb-button-primary-fg,#fff)}',
+ '.wbs-auto-list{display:flex;flex:1;min-height:0;flex-direction:column;gap:5px;overflow:auto;padding-right:2px;margin-top:10px}',
+ '.wbs-auto-row{display:flex;flex:0 0 auto;flex-direction:column;align-items:stretch;gap:7px;min-height:48px;padding:10px;border:1px solid var(--wb-border-subtle,#ececec);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 22%,transparent)}',
+ '.wbs-auto-row-head{display:flex;align-items:center;gap:8px;min-width:0}.wbs-auto-enabled{flex-shrink:0}.wbs-auto-enabled[hidden]{display:none!important}.wbs-auto-description{color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.5;overflow-wrap:anywhere;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden}.wbs-auto-row-foot{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px}.wbs-auto-details{min-width:0}.wbs-auto-triggers{display:flex;flex-wrap:wrap;gap:4px}.wbs-auto-trigger-chip{display:inline-flex;max-width:100%;padding:2px 6px;border:1px solid var(--wb-border-subtle,#e7e7e7);border-radius:6px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font-size:10px;line-height:1.4;overflow-wrap:anywhere}.wbs-auto-state-line{display:flex;align-items:center;flex-wrap:wrap;gap:4px 8px;min-height:16px;margin-top:5px;color:var(--wb-icon-tertiary,#888);font-size:10px}.wbs-auto-state{display:inline-flex;align-items:center;gap:4px}.wbs-auto-state:before{content:"";width:4px;height:4px;flex:0 0 4px;border-radius:50%;background:currentColor}.wbs-auto-state.running{color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-auto-state.off{opacity:.65}.wbs-auto-last-run.failed{color:var(--wb-color-text-primary,#222)}.wbs-auto-icon:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:1px}',
+ '.wbs-auto-row:hover{background:var(--wb-bg-hover,#f5f5f5)}',
+ '.wbs-auto-check{display:flex;align-items:center;justify-content:center;flex:0 0 20px;cursor:pointer}.wbs-auto-check input{accent-color:var(--wb-button-primary-bg,#1f1f1f)}',
+ '.wbs-auto-main{min-width:0;flex:1}.wbs-auto-name{display:block;flex:1;min-width:0;font-size:12px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
+ '.wbs-auto-status{flex:0 0 auto;padding:2px 6px;border-radius:999px;font-size:10px;font-weight:500}.wbs-auto-status.on{color:#1b7f56;background:rgba(46,190,126,.14)}.wbs-auto-status.off{color:var(--wb-icon-tertiary,#888);background:var(--wb-bg-tertiary,#f1f1f1)}',
+ '.wbs-auto-meta{margin-top:3px;color:var(--wb-icon-tertiary,#999);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
+ '.wbs-auto-enabled{flex:0 0 auto;margin-left:4px}.wbs-auto-actions{display:flex;gap:2px;flex:0 0 auto}.wbs-auto-icon{display:inline-flex;align-items:center;justify-content:center;width:27px;height:27px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--wb-icon-secondary,#666);cursor:pointer;line-height:27px}.wbs-auto-icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round}.wbs-auto-icon:hover,.wbs-auto-icon:focus-visible{background:var(--wb-bg-hover,#f0f0f0);color:var(--wb-color-text-primary,#1f1f1f);outline:none}.wbs-auto-icon.danger:hover{color:#d04a4a}.wbs-auto-icon.is-running,.wbs-auto-icon.is-running:hover{opacity:1;filter:none;background:transparent;color:var(--wb-icon-secondary,#666);cursor:pointer}.wbs-auto-icon:disabled{opacity:.45;cursor:wait}',
+ '.wbs-auto-icon.is-stopping,.wbs-auto-icon.is-stopping:hover{opacity:.5;background:transparent;color:var(--wb-icon-secondary,#999);cursor:wait}.wbs-auto-icon.is-stopping svg{fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round}.wbs-auto-icon.is-stopping .wbs-auto-stopping-svg{transform-origin:center;animation:wbs-auto-spin .9s linear infinite}@keyframes wbs-auto-spin{to{transform:rotate(360deg)}}',
+ '.wbs-auto-empty{padding:18px 8px;text-align:center;color:var(--wb-icon-tertiary,#999);font-size:12px}',
+ '.wbs-auto-cap-link{display:flex;justify-content:flex-end;margin-top:7px}.wbs-auto-textbtn{padding:3px 4px;border:0;background:transparent;color:var(--wb-color-text-secondary,#666);font:inherit;font-size:11px;cursor:pointer}.wbs-auto-textbtn:hover{color:var(--wb-color-text-primary,#1f1f1f);text-decoration:underline}',
+ '.wbs-modal.wbs-auto-import-modal{width:calc(100% - 24px);max-width:480px;max-height:min(560px,calc(100% - 28px));display:flex;flex-direction:column;box-sizing:border-box}.wbs-auto-import-file{color:var(--wb-color-text-secondary,#666);font-size:11px;overflow-wrap:anywhere;margin-bottom:8px}.wbs-auto-import-list{min-height:0;overflow:auto;flex:1;scrollbar-width:thin;scrollbar-color:var(--wb-border-default,#bbb) transparent;border:1px solid var(--wb-border-subtle,#e5e5e5);border-radius:9px}.wbs-auto-import-item{display:flex;align-items:center;gap:10px;padding:10px 12px;cursor:pointer}.wbs-auto-import-item+.wbs-auto-import-item{border-top:1px solid var(--wb-border-subtle,#e5e5e5)}.wbs-auto-import-item:has(input:disabled){cursor:default}.wbs-auto-import-item:hover{background:var(--wb-bg-tertiary,#f5f5f5)}.wbs-auto-import-info{display:flex;flex-direction:column;gap:3px;min-width:0}.wbs-auto-import-name{font-size:12px;color:var(--wb-color-text-primary,#222);overflow-wrap:anywhere}.wbs-auto-import-status,.wbs-auto-import-count{font-size:11px;color:var(--wb-color-text-secondary,#666)}.wbs-auto-import-count{margin-right:auto}.wbs-auto-import-error{font-size:11px;color:var(--wb-status-error,var(--wb-color-text-primary,#1f1f1f));overflow-wrap:anywhere;margin-top:8px}.wbs-auto-import-modal .wbs-modal-actions{flex-shrink:0}.wbs-auto-import-item input:disabled{opacity:.4}',
+ '.wbs-auto-batchbar{display:flex;align-items:center;gap:6px;margin:4px 0 7px}.wbs-auto-batch-count{margin-right:auto;color:var(--wb-icon-tertiary,#888);font-size:11px}.wbs-auto-field input,.wbs-auto-field textarea{box-sizing:border-box;width:100%;border:1px solid var(--wb-border-default,#dedede);border-radius:7px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:12px;outline:none}.wbs-auto-field{display:flex;flex-direction:column;gap:4px;margin-bottom:8px;color:var(--wb-icon-secondary,#666);font-size:11px}.wbs-auto-field input{height:30px;padding:5px 8px}.wbs-auto-field textarea{min-height:72px;padding:8px;resize:vertical;line-height:1.45}.wbs-auto-field textarea[data-auto-field="steps"]{min-height:150px;resize:none;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.wbs-auto-field input:focus,.wbs-auto-field textarea:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 20%,transparent)}.wbs-auto-trigger-seg{display:flex;gap:3px;padding:3px;border-radius:9px;background:var(--wb-bg-tertiary,#f0f0f0)}.wbs-auto-trigger-seg label{flex:1;display:flex;align-items:center;justify-content:center;min-height:28px;padding:0 8px;border-radius:7px;color:var(--wb-icon-secondary,#666);cursor:pointer}.wbs-auto-trigger-seg input{position:absolute;opacity:0;pointer-events:none}.wbs-auto-trigger-seg label:has(input:checked){background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.16)}',
+ '.wbs-modal.wbs-auto-agent-modal{display:flex;flex-direction:column;width:calc(100% - 24px);max-width:520px;max-height:calc(100% - 28px);box-sizing:border-box}.wbs-auto-agent-intro{margin:0 0 14px;color:var(--wb-color-text-secondary,#666);font-size:12px;line-height:1.6;overflow-wrap:anywhere}.wbs-auto-agent-input-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:7px;font-size:12px;font-weight:600}.wbs-auto-agent-input-head #wbs-auto-examples{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:5px}.wbs-auto-example-fill{border:1px solid var(--wb-border-subtle,#ddd);border-radius:6px;padding:3px 8px;background:var(--wb-bg-tertiary,#f5f5f5);font-weight:400}.wbs-auto-agent-prompt{display:block;box-sizing:border-box;flex:1 1 160px;min-height:60px;width:100%;height:160px;max-height:26vh;resize:none;overflow:auto;padding:10px 12px;border:1px solid var(--wb-border-default,#ddd);border-radius:9px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);font-family:inherit;font-size:12px;line-height:1.65;white-space:pre-wrap;overflow-wrap:anywhere}.wbs-auto-agent-prompt:focus{outline:2px solid color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 30%,transparent);outline-offset:1px;border-color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-auto-agent-prompt::placeholder{color:var(--wb-icon-tertiary,#888)}.wbs-auto-agent-hint{margin:8px 0 14px;font-size:11px;color:var(--wb-color-text-secondary,#666)}.wbs-auto-agent-modal .wbs-modal-actions{flex-shrink:0;margin-top:0}.wbs-auto-agent-modal .wbs-modal-ok:disabled{opacity:.4;cursor:default}',
+ '.wbs-auto-modal-head{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;padding:0 0 10px}.wbs-auto-modal-head .wbs-modal-title{margin:0}.wbs-auto-modal-subtitle{max-width:360px;margin-top:3px;color:var(--wb-icon-tertiary,#888);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.wbs-auto-modal-close{display:inline-flex;align-items:center;justify-content:center;flex:0 0 26px;width:26px;height:26px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--wb-icon-secondary,#666);cursor:pointer}.wbs-auto-modal-close:hover,.wbs-auto-modal-close:focus-visible{background:var(--wb-bg-hover,#eee);color:var(--wb-color-text-primary,#222);outline:none}.wbs-auto-modal-close svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round}',
+ '.wbs-modal.wbs-auto-editor-modal{display:grid;grid-template-rows:auto minmax(0,1fr) auto;width:calc(100% - 32px);max-width:720px;height:min(600px,calc(100% - 32px));box-sizing:border-box;overflow:hidden}.wbs-auto-editor-body{display:flex;flex-direction:column;min-height:0;overflow:hidden;padding:2px}.wbs-auto-editor-body>.wbs-auto-field{flex:0 0 auto}.wbs-auto-editor-body>.wbs-auto-steps-field{flex:1 1 0;min-height:0;margin-bottom:0}.wbs-auto-editor-body .wbs-auto-steps-field textarea[data-auto-field="steps"]{flex:1 1 0;height:0;min-height:0;resize:none;overflow:auto}.wbs-auto-editor-body textarea[data-auto-field="description"]{height:44px;min-height:0;resize:none;overflow:auto}.wbs-auto-trigger-options,.wbs-auto-schedule{display:flex;align-items:center;flex-wrap:wrap;gap:4px 12px}.wbs-auto-trigger-options label,.wbs-auto-schedule label{display:flex;align-items:center;gap:5px;cursor:pointer;min-height:22px}.wbs-auto-trigger-options input[type="checkbox"],.wbs-auto-schedule input[type="checkbox"]{width:13px;height:13px;margin:0;accent-color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-auto-schedule input[type="number"]{width:68px;height:25px;padding:3px 6px}.wbs-auto-schedule input:disabled{opacity:.5;cursor:not-allowed}.wbs-auto-editor-modal .wbs-modal-actions{margin-top:10px}',
+ '.wbs-modal.wbs-auto-log-modal{display:grid;grid-template-rows:auto minmax(0,1fr);width:calc(100% - 32px);max-width:680px;height:min(560px,calc(100% - 32px));box-sizing:border-box}.wbs-auto-log-list{display:flex;flex-direction:column;gap:8px;min-height:0;overflow:auto;padding-right:2px}.wbs-auto-log-empty{display:flex;align-items:center;justify-content:center;min-height:160px;color:var(--wb-icon-tertiary,#888);font-size:12px}.wbs-auto-log-run{padding:9px;border:1px solid var(--wb-border-subtle,#ededed);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 30%,transparent)}.wbs-auto-log-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.wbs-auto-log-status{font-size:11px;font-weight:650;color:var(--wb-icon-secondary,#666)}.wbs-auto-log-status.running{color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-auto-log-status.success,.wbs-auto-log-status.failed{color:var(--wb-icon-secondary,#666)}.wbs-auto-log-time{color:var(--wb-icon-tertiary,#888);font-size:10px}.wbs-auto-log-facts{display:flex;flex-wrap:wrap;gap:4px 12px;margin-top:5px;color:var(--wb-icon-tertiary,#888);font-size:10px}.wbs-auto-log-note{margin-top:7px;padding:6px 8px;border-radius:7px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-secondary,#666);font-size:11px;line-height:1.45;white-space:pre-wrap;overflow-wrap:anywhere}.wbs-auto-log-output{max-height:180px;margin:7px 0 0;padding:7px 8px;overflow:auto;border:1px solid var(--wb-border-subtle,#ededed);border-radius:7px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;overflow-wrap:anywhere;user-select:text}',
+ '.wbs-modal.wbs-auto-cap-modal{display:flex;flex-direction:column;width:calc(100% - 24px);max-width:none;height:min(560px,calc(100% - 28px));box-sizing:border-box}.wbs-auto-protocol{flex:1;min-height:0;margin:0 0 12px;padding:10px;overflow:auto;border:1px solid var(--wb-border-subtle,#ededed);border-radius:8px;background:var(--wb-bg-tertiary,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f);font:10.5px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;overflow-wrap:anywhere;user-select:text}',
+ 'html.cb-dark .wbs-auto-row,html[data-theme="dark"] .wbs-auto-row,body[data-vscode-theme-name*="dark" i] .wbs-auto-row{background:color-mix(in srgb,var(--wb-bg-secondary,#202126) 50%,transparent)}html.cb-dark .wbs-auto-status.off,html[data-theme="dark"] .wbs-auto-status.off,body[data-vscode-theme-name*="dark" i] .wbs-auto-status.off{background:rgba(255,255,255,.08)}html.cb-dark .wbs-auto-protocol,html[data-theme="dark"] .wbs-auto-protocol,body[data-vscode-theme-name*="dark" i] .wbs-auto-protocol,html.cb-dark .wbs-auto-log-output,html[data-theme="dark"] .wbs-auto-log-output,body[data-vscode-theme-name*="dark" i] .wbs-auto-log-output{background:rgba(255,255,255,.06)}html.cb-dark .wbs-auto-log-run,html[data-theme="dark"] .wbs-auto-log-run,body[data-vscode-theme-name*="dark" i] .wbs-auto-log-run{background:color-mix(in srgb,var(--wb-bg-secondary,#202126) 50%,transparent)}html.cb-dark .wbs-auto-field input,html.cb-dark .wbs-auto-field select,html.cb-dark .wbs-auto-field textarea,html[data-theme="dark"] .wbs-auto-field input,html[data-theme="dark"] .wbs-auto-field select,html[data-theme="dark"] .wbs-auto-field textarea,body[data-vscode-theme-name*="dark" i] .wbs-auto-field input,body[data-vscode-theme-name*="dark" i] .wbs-auto-field select,body[data-vscode-theme-name*="dark" i] .wbs-auto-field textarea{background:var(--wb-bg-popover,#202126);border-color:var(--wb-border-subtle,rgba(255,255,255,.18));color:var(--wb-color-text-primary,#f2f3f5)}',
+ '.wbs-auto-schedule{margin-top:5px}.wbs-auto-schedule [hidden]{display:none!important}.wbs-auto-weekdays{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;flex-basis:100%}.wbs-auto-schedule select{width:auto;max-width:100%;height:28px;padding:3px 7px;border:1px solid var(--wb-border-default,#ddd);border-radius:7px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit}.wbs-auto-schedule input[type="time"]{width:106px;height:28px;padding:3px 6px}.wbs-auto-schedule input[type="datetime-local"]{width:205px;max-width:100%;height:28px;padding:3px 6px}.wbs-auto-schedule label{max-width:100%}.wbs-auto-schedule-hint{flex-basis:100%;font-size:10px;color:var(--wb-color-text-secondary,#666);line-height:1.45}.wbs-auto-schedule select:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:1px}',
+ '.wbs-auto-check input,.wbs-auto-trigger-options input[type="checkbox"],.wbs-auto-schedule input[type="checkbox"]{appearance:none;-webkit-appearance:none;display:inline-grid;place-content:center;flex:0 0 14px;width:14px;height:14px;margin:0;padding:0;border:1px solid var(--wb-border-default,#bbb);border-radius:4px;background:var(--wb-bg-popover,#fff);cursor:pointer}.wbs-auto-check input:checked,.wbs-auto-trigger-options input[type="checkbox"]:checked,.wbs-auto-schedule input[type="checkbox"]:checked{background:var(--wb-button-primary-bg,#1f1f1f);border-color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-auto-check input:checked:after,.wbs-auto-trigger-options input[type="checkbox"]:checked:after,.wbs-auto-schedule input[type="checkbox"]:checked:after{content:"";width:6px;height:3px;border-left:1.5px solid var(--wb-button-primary-fg,#fff);border-bottom:1.5px solid var(--wb-button-primary-fg,#fff);transform:translateY(-1px) rotate(-45deg)}.wbs-auto-check input:focus-visible,.wbs-auto-trigger-options input[type="checkbox"]:focus-visible,.wbs-auto-schedule input[type="checkbox"]:focus-visible{outline:2px solid var(--wb-button-primary-bg,#1f1f1f);outline-offset:2px}',
/* 免打扰:标题行右置批量开关 + 三列 grid 对齐(标题/小标题/开关,所有小标题左对齐) */
'.wbs-nd-head{display:flex;align-items:center;gap:6px}',
'.wbs-nd-head #wbs-nd-count{margin-left:2px}',
diff --git a/scripts/lib.js b/scripts/lib.js
index ac426c6..4e29da9 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -101,6 +101,8 @@ function allowedAuthOrigins(profile = ACTIVE_PROFILE) {
if (profile.region === 'cn') {
origins.add('https://www.workbuddy.cn');
origins.add('https://www.codebuddy.cn');
+ // 国内版新版 Keycloak issuer;保留旧域名以兼容已有账号备份。
+ origins.add('https://copilot.tencent.com');
} else if (profile.region === 'intl') {
origins.add('https://www.workbuddy.ai');
origins.add('https://www.codebuddy.ai');
@@ -180,6 +182,19 @@ function currentAuthFile() {
return resolveCurrentAuth().file;
}
+function resolveLogoutAuth() {
+ const resolution = resolveCurrentAuth();
+ if (resolution.file || resolution.ambiguous || !DYNAMIC_AUTH_DISCOVERY) return resolution;
+ // 假退出已删掉登录文件,扫码取消后可以再次打开登录页。仅在认证目录
+ // 可读且没有任何 info 文件时使用官方固定路径;未知/损坏文件仍拒绝猜测。
+ try {
+ if (!fs.readdirSync(authDir()).some(safeAuthFileName)) {
+ return { file: AUTH_FILE, record: null, ambiguous: false };
+ }
+ } catch (_) { /* 不把权限或路径错误当成未登录 */ }
+ return resolution;
+}
+
function defaultDataDir() {
// 旧版 launchd 可能把 WBSWITCH_DATA_DIR 设成 HelloBuddy;新版本始终落到 WorkDaddy,
// 避免旧服务被新 daemon 拉起后继续写入旧目录。
@@ -265,10 +280,8 @@ function sanitizeModel(model, opts) {
};
}
-function checkinDisplayValue(record, today, pending) {
- if (!record || record.date !== today) return null;
- // 正在签到时保留已确认的成功标记;只有失败/未完成记录才暂不展示,避免首屏把已签到账号误显示为“签到中”。
- if (pending && !record.ok) return null;
+function checkinDisplayValue(record, today) {
+ if (!record || record.date !== today || !record.ok) return null;
return { ok: !!record.ok, already: !!record.already, code: record.code, message: record.message };
}
@@ -1454,6 +1467,7 @@ module.exports = {
parseAuthFile,
listAuthRecords,
resolveCurrentAuth,
+ resolveLogoutAuth,
currentAuthFile,
resolveAuthTarget,
ACTIVE_PROFILE,
diff --git a/scripts/primary-account.js b/scripts/primary-account.js
new file mode 100644
index 0000000..9a732a7
--- /dev/null
+++ b/scripts/primary-account.js
@@ -0,0 +1,26 @@
+'use strict';
+const fs = require('node:fs');
+const path = require('node:path');
+
+// Profile-local preference, separate from the account backup format.
+function createPrimaryAccountStore(dataDir, accountExists) {
+ const file = path.join(dataDir, 'primary-account.json');
+ function set(uid) {
+ if (typeof uid !== 'string' || (uid && !/^[A-Za-z0-9_-]{1,128}$/.test(uid))) throw new Error('账号 uid 无效');
+ if (uid && !accountExists(uid)) throw new Error('账号备份不存在');
+ fs.mkdirSync(dataDir, { recursive: true });
+ const tmp = file + '.tmp-' + process.pid;
+ fs.writeFileSync(tmp, JSON.stringify({ uid }) + '\n', { mode: 0o600 });
+ fs.renameSync(tmp, file);
+ return uid;
+ }
+ function get() {
+ let uid;
+ try { uid = JSON.parse(fs.readFileSync(file, 'utf8')).uid; } catch (_) { return ''; }
+ if (typeof uid !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return '';
+ if (!accountExists(uid)) { set(''); return ''; }
+ return uid;
+ }
+ return { get, set };
+}
+module.exports = { createPrimaryAccountStore };
diff --git a/scripts/toast-options.js b/scripts/toast-options.js
new file mode 100644
index 0000000..b380436
--- /dev/null
+++ b/scripts/toast-options.js
@@ -0,0 +1,50 @@
+'use strict';
+const TOAST_LEVELS = ['info', 'success', 'warning', 'error', 'loading'];
+function normalizeToastOptions(input = {}, dismiss = false) {
+ const result = {};
+ if (input.id != null) {
+ if (typeof input.id !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,159}$/.test(input.id)) throw new Error('通知 id 格式无效');
+ result.id = input.id;
+ }
+ if (dismiss && !result.id) throw new Error('关闭通知需要 id');
+ if (!dismiss) {
+ result.level = input.level == null ? 'info' : input.level;
+ if (!TOAST_LEVELS.includes(result.level)) throw new Error('不支持的通知类型');
+ if (input.duration != null) {
+ if (!Number.isInteger(input.duration) || input.duration < 1000 || input.duration > 60000) throw new Error('通知 duration 必须是 1000–60000 毫秒的整数');
+ result.duration = input.duration;
+ }
+ }
+ return result;
+}
+module.exports = { normalizeToastOptions };
+
+// Each run owns a namespace: identical task ids cannot update/dismiss another
+// run's notifications or ordinary WorkDaddy UI notifications.
+function createAutomationNotifier(send, namespace) {
+ const active = new Map();
+ let nextId = 0;
+ let closed = false;
+ const dismiss = async (id) => {
+ const value = normalizeToastOptions({ id }, true);
+ await send({ action: 'dismiss', id: namespace + ':' + value.id });
+ active.delete(value.id);
+ return { ok: true, id: value.id };
+ };
+ const show = async (level, message, options = {}) => {
+ if (closed) throw new Error('通知所属任务已结束');
+ const value = normalizeToastOptions({ ...options, level });
+ const id = value.id || 'notice-' + (++nextId);
+ await send({ ...value, message: String(message || '').slice(0, 2000), id: namespace + ':' + id });
+ active.set(id, value.level);
+ if (closed) await dismiss(id);
+ return { ok: true, id };
+ };
+ const cleanup = async () => {
+ closed = true;
+ await Promise.allSettled([...active].filter(([, level]) => level === 'loading').map(([id]) => dismiss(id)));
+ active.clear();
+ };
+ return { show, dismiss, cleanup };
+}
+module.exports.createAutomationNotifier = createAutomationNotifier;
diff --git a/scripts/toast-runtime.js b/scripts/toast-runtime.js
new file mode 100644
index 0000000..ac0fd33
--- /dev/null
+++ b/scripts/toast-runtime.js
@@ -0,0 +1,342 @@
+/* Generated by tools/toast-runtime/build.mjs; React 18.3.1 / react-hot-toast 2.6.0. */
+window.__wbsToastRuntime?.destroy();
+(()=>{var hf=Object.create;var gu=Object.defineProperty;var vf=Object.getOwnPropertyDescriptor;var yf=Object.getOwnPropertyNames;var gf=Object.getPrototypeOf,wf=Object.prototype.hasOwnProperty;var zt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var kf=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of yf(t))!wf.call(e,l)&&l!==n&&gu(e,l,{get:()=>t[l],enumerable:!(r=vf(t,l))||r.enumerable});return e};var tt=(e,t,n)=>(n=e!=null?hf(gf(e)):{},kf(t||!e||!e.__esModule?gu(n,"default",{value:e,enumerable:!0}):n,e));var Lu=zt(N=>{"use strict";var Nn=Symbol.for("react.element"),Sf=Symbol.for("react.portal"),xf=Symbol.for("react.fragment"),Ef=Symbol.for("react.strict_mode"),Cf=Symbol.for("react.profiler"),_f=Symbol.for("react.provider"),Nf=Symbol.for("react.context"),Pf=Symbol.for("react.forward_ref"),zf=Symbol.for("react.suspense"),Tf=Symbol.for("react.memo"),Lf=Symbol.for("react.lazy"),wu=Symbol.iterator;function Rf(e){return e===null||typeof e!="object"?null:(e=wu&&e[wu]||e["@@iterator"],typeof e=="function"?e:null)}var xu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Eu=Object.assign,Cu={};function Kt(e,t,n){this.props=e,this.context=t,this.refs=Cu,this.updater=n||xu}Kt.prototype.isReactComponent={};Kt.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Kt.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _u(){}_u.prototype=Kt.prototype;function Yl(e,t,n){this.props=e,this.context=t,this.refs=Cu,this.updater=n||xu}var Xl=Yl.prototype=new _u;Xl.constructor=Yl;Eu(Xl,Kt.prototype);Xl.isPureReactComponent=!0;var ku=Array.isArray,Nu=Object.prototype.hasOwnProperty,Gl={current:null},Pu={key:!0,ref:!0,__self:!0,__source:!0};function zu(e,t,n){var r,l={},o=null,i=null;if(t!=null)for(r in t.ref!==void 0&&(i=t.ref),t.key!==void 0&&(o=""+t.key),t)Nu.call(t,r)&&!Pu.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(u===1)l.children=n;else if(1<u){for(var s=Array(u),c=0;c<u;c++)s[c]=arguments[c+2];l.children=s}if(e&&e.defaultProps)for(r in u=e.defaultProps,u)l[r]===void 0&&(l[r]=u[r]);return{$$typeof:Nn,type:e,key:o,ref:i,props:l,_owner:Gl.current}}function Of(e,t){return{$$typeof:Nn,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function Zl(e){return typeof e=="object"&&e!==null&&e.$$typeof===Nn}function Df(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var Su=/\/+/g;function Kl(e,t){return typeof e=="object"&&e!==null&&e.key!=null?Df(""+e.key):t.toString(36)}function Sr(e,t,n,r,l){var o=typeof e;(o==="undefined"||o==="boolean")&&(e=null);var i=!1;if(e===null)i=!0;else switch(o){case"string":case"number":i=!0;break;case"object":switch(e.$$typeof){case Nn:case Sf:i=!0}}if(i)return i=e,l=l(i),e=r===""?"."+Kl(i,0):r,ku(l)?(n="",e!=null&&(n=e.replace(Su,"$&/")+"/"),Sr(l,t,n,"",function(c){return c})):l!=null&&(Zl(l)&&(l=Of(l,n+(!l.key||i&&i.key===l.key?"":(""+l.key).replace(Su,"$&/")+"/")+e)),t.push(l)),1;if(i=0,r=r===""?".":r+":",ku(e))for(var u=0;u<e.length;u++){o=e[u];var s=r+Kl(o,u);i+=Sr(o,t,n,s,l)}else if(s=Rf(e),typeof s=="function")for(e=s.call(e),u=0;!(o=e.next()).done;)o=o.value,s=r+Kl(o,u++),i+=Sr(o,t,n,s,l);else if(o==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return i}function kr(e,t,n){if(e==null)return e;var r=[],l=0;return Sr(e,r,"","",function(o){return t.call(n,o,l++)}),r}function If(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var ne={current:null},xr={transition:null},Mf={ReactCurrentDispatcher:ne,ReactCurrentBatchConfig:xr,ReactCurrentOwner:Gl};function Tu(){throw Error("act(...) is not supported in production builds of React.")}N.Children={map:kr,forEach:function(e,t,n){kr(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return kr(e,function(){t++}),t},toArray:function(e){return kr(e,function(t){return t})||[]},only:function(e){if(!Zl(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};N.Component=Kt;N.Fragment=xf;N.Profiler=Cf;N.PureComponent=Yl;N.StrictMode=Ef;N.Suspense=zf;N.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Mf;N.act=Tu;N.cloneElement=function(e,t,n){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=Eu({},e.props),l=e.key,o=e.ref,i=e._owner;if(t!=null){if(t.ref!==void 0&&(o=t.ref,i=Gl.current),t.key!==void 0&&(l=""+t.key),e.type&&e.type.defaultProps)var u=e.type.defaultProps;for(s in t)Nu.call(t,s)&&!Pu.hasOwnProperty(s)&&(r[s]=t[s]===void 0&&u!==void 0?u[s]:t[s])}var s=arguments.length-2;if(s===1)r.children=n;else if(1<s){u=Array(s);for(var c=0;c<s;c++)u[c]=arguments[c+2];r.children=u}return{$$typeof:Nn,type:e.type,key:l,ref:o,props:r,_owner:i}};N.createContext=function(e){return e={$$typeof:Nf,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:_f,_context:e},e.Consumer=e};N.createElement=zu;N.createFactory=function(e){var t=zu.bind(null,e);return t.type=e,t};N.createRef=function(){return{current:null}};N.forwardRef=function(e){return{$$typeof:Pf,render:e}};N.isValidElement=Zl;N.lazy=function(e){return{$$typeof:Lf,_payload:{_status:-1,_result:e},_init:If}};N.memo=function(e,t){return{$$typeof:Tf,type:e,compare:t===void 0?null:t}};N.startTransition=function(e){var t=xr.transition;xr.transition={};try{e()}finally{xr.transition=t}};N.unstable_act=Tu;N.useCallback=function(e,t){return ne.current.useCallback(e,t)};N.useContext=function(e){return ne.current.useContext(e)};N.useDebugValue=function(){};N.useDeferredValue=function(e){return ne.current.useDeferredValue(e)};N.useEffect=function(e,t){return ne.current.useEffect(e,t)};N.useId=function(){return ne.current.useId()};N.useImperativeHandle=function(e,t,n){return ne.current.useImperativeHandle(e,t,n)};N.useInsertionEffect=function(e,t){return ne.current.useInsertionEffect(e,t)};N.useLayoutEffect=function(e,t){return ne.current.useLayoutEffect(e,t)};N.useMemo=function(e,t){return ne.current.useMemo(e,t)};N.useReducer=function(e,t,n){return ne.current.useReducer(e,t,n)};N.useRef=function(e){return ne.current.useRef(e)};N.useState=function(e){return ne.current.useState(e)};N.useSyncExternalStore=function(e,t,n){return ne.current.useSyncExternalStore(e,t,n)};N.useTransition=function(){return ne.current.useTransition()};N.version="18.3.1"});var nt=zt((zm,Ru)=>{"use strict";Ru.exports=Lu()});var $u=zt(L=>{"use strict";function eo(e,t){var n=e.length;e.push(t);e:for(;0<n;){var r=n-1>>>1,l=e[r];if(0<Er(l,t))e[r]=t,e[n]=l,n=r;else break e}}function Pe(e){return e.length===0?null:e[0]}function _r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;e:for(var r=0,l=e.length,o=l>>>1;r<o;){var i=2*(r+1)-1,u=e[i],s=i+1,c=e[s];if(0>Er(u,n))s<l&&0>Er(c,u)?(e[r]=c,e[s]=n,r=s):(e[r]=u,e[i]=n,r=i);else if(s<l&&0>Er(c,n))e[r]=c,e[s]=n,r=s;else break e}}return t}function Er(e,t){var n=e.sortIndex-t.sortIndex;return n!==0?n:e.id-t.id}typeof performance=="object"&&typeof performance.now=="function"?(Ou=performance,L.unstable_now=function(){return Ou.now()}):(Jl=Date,Du=Jl.now(),L.unstable_now=function(){return Jl.now()-Du});var Ou,Jl,Du,Me=[],rt=[],Ff=1,we=null,J=3,Nr=!1,Tt=!1,zn=!1,Fu=typeof setTimeout=="function"?setTimeout:null,ju=typeof clearTimeout=="function"?clearTimeout:null,Iu=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function to(e){for(var t=Pe(rt);t!==null;){if(t.callback===null)_r(rt);else if(t.startTime<=e)_r(rt),t.sortIndex=t.expirationTime,eo(Me,t);else break;t=Pe(rt)}}function no(e){if(zn=!1,to(e),!Tt)if(Pe(Me)!==null)Tt=!0,lo(ro);else{var t=Pe(rt);t!==null&&oo(no,t.startTime-e)}}function ro(e,t){Tt=!1,zn&&(zn=!1,ju(Tn),Tn=-1),Nr=!0;var n=J;try{for(to(t),we=Pe(Me);we!==null&&(!(we.expirationTime>t)||e&&!Vu());){var r=we.callback;if(typeof r=="function"){we.callback=null,J=we.priorityLevel;var l=r(we.expirationTime<=t);t=L.unstable_now(),typeof l=="function"?we.callback=l:we===Pe(Me)&&_r(Me),to(t)}else _r(Me);we=Pe(Me)}if(we!==null)var o=!0;else{var i=Pe(rt);i!==null&&oo(no,i.startTime-t),o=!1}return o}finally{we=null,J=n,Nr=!1}}var Pr=!1,Cr=null,Tn=-1,Uu=5,Au=-1;function Vu(){return!(L.unstable_now()-Au<Uu)}function ql(){if(Cr!==null){var e=L.unstable_now();Au=e;var t=!0;try{t=Cr(!0,e)}finally{t?Pn():(Pr=!1,Cr=null)}}else Pr=!1}var Pn;typeof Iu=="function"?Pn=function(){Iu(ql)}:typeof MessageChannel<"u"?(bl=new MessageChannel,Mu=bl.port2,bl.port1.onmessage=ql,Pn=function(){Mu.postMessage(null)}):Pn=function(){Fu(ql,0)};var bl,Mu;function lo(e){Cr=e,Pr||(Pr=!0,Pn())}function oo(e,t){Tn=Fu(function(){e(L.unstable_now())},t)}L.unstable_IdlePriority=5;L.unstable_ImmediatePriority=1;L.unstable_LowPriority=4;L.unstable_NormalPriority=3;L.unstable_Profiling=null;L.unstable_UserBlockingPriority=2;L.unstable_cancelCallback=function(e){e.callback=null};L.unstable_continueExecution=function(){Tt||Nr||(Tt=!0,lo(ro))};L.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Uu=0<e?Math.floor(1e3/e):5};L.unstable_getCurrentPriorityLevel=function(){return J};L.unstable_getFirstCallbackNode=function(){return Pe(Me)};L.unstable_next=function(e){switch(J){case 1:case 2:case 3:var t=3;break;default:t=J}var n=J;J=t;try{return e()}finally{J=n}};L.unstable_pauseExecution=function(){};L.unstable_requestPaint=function(){};L.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=J;J=e;try{return t()}finally{J=n}};L.unstable_scheduleCallback=function(e,t,n){var r=L.unstable_now();switch(typeof n=="object"&&n!==null?(n=n.delay,n=typeof n=="number"&&0<n?r+n:r):n=r,e){case 1:var l=-1;break;case 2:l=250;break;case 5:l=1073741823;break;case 4:l=1e4;break;default:l=5e3}return l=n+l,e={id:Ff++,callback:t,priorityLevel:e,startTime:n,expirationTime:l,sortIndex:-1},n>r?(e.sortIndex=n,eo(rt,e),Pe(Me)===null&&e===Pe(rt)&&(zn?(ju(Tn),Tn=-1):zn=!0,oo(no,n-r))):(e.sortIndex=l,eo(Me,e),Tt||Nr||(Tt=!0,lo(ro))),e};L.unstable_shouldYield=Vu;L.unstable_wrapCallback=function(e){var t=J;return function(){var n=J;J=t;try{return e.apply(this,arguments)}finally{J=n}}}});var Hu=zt((Lm,Bu)=>{"use strict";Bu.exports=$u()});var Yc=zt(ye=>{"use strict";var jf=nt(),he=Hu();function y(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var Zs=new Set,Jn={};function Bt(e,t){mn(e,t),mn(e+"Capture",t)}function mn(e,t){for(Jn[e]=t,e=0;e<t.length;e++)Zs.add(t[e])}var Ye=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),To=Object.prototype.hasOwnProperty,Uf=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Wu={},Qu={};function Af(e){return To.call(Qu,e)?!0:To.call(Wu,e)?!1:Uf.test(e)?Qu[e]=!0:(Wu[e]=!0,!1)}function Vf(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function $f(e,t,n,r){if(t===null||typeof t>"u"||Vf(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function oe(e,t,n,r,l,o,i){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=i}var Z={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Z[e]=new oe(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Z[t]=new oe(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Z[e]=new oe(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Z[e]=new oe(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Z[e]=new oe(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Z[e]=new oe(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Z[e]=new oe(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Z[e]=new oe(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Z[e]=new oe(e,5,!1,e.toLowerCase(),null,!1,!1)});var Si=/[\-:]([a-z])/g;function xi(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Si,xi);Z[t]=new oe(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Si,xi);Z[t]=new oe(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Si,xi);Z[t]=new oe(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Z[e]=new oe(e,1,!1,e.toLowerCase(),null,!1,!1)});Z.xlinkHref=new oe("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Z[e]=new oe(e,1,!1,e.toLowerCase(),null,!0,!0)});function Ei(e,t,n,r){var l=Z.hasOwnProperty(t)?Z[t]:null;(l!==null?l.type!==0:r||!(2<t.length)||t[0]!=="o"&&t[0]!=="O"||t[1]!=="n"&&t[1]!=="N")&&($f(t,n,l,r)&&(n=null),r||l===null?Af(t)&&(n===null?e.removeAttribute(t):e.setAttribute(t,""+n)):l.mustUseProperty?e[l.propertyName]=n===null?l.type===3?!1:"":n:(t=l.attributeName,r=l.attributeNamespace,n===null?e.removeAttribute(t):(l=l.type,n=l===3||l===4&&n===!0?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}var Je=jf.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,zr=Symbol.for("react.element"),Gt=Symbol.for("react.portal"),Zt=Symbol.for("react.fragment"),Ci=Symbol.for("react.strict_mode"),Lo=Symbol.for("react.profiler"),Js=Symbol.for("react.provider"),qs=Symbol.for("react.context"),_i=Symbol.for("react.forward_ref"),Ro=Symbol.for("react.suspense"),Oo=Symbol.for("react.suspense_list"),Ni=Symbol.for("react.memo"),ot=Symbol.for("react.lazy");Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");var bs=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden");Symbol.for("react.cache");Symbol.for("react.tracing_marker");var Ku=Symbol.iterator;function Ln(e){return e===null||typeof e!="object"?null:(e=Ku&&e[Ku]||e["@@iterator"],typeof e=="function"?e:null)}var U=Object.assign,io;function Un(e){if(io===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);io=t&&t[1]||""}return`
+`+io+e}var uo=!1;function so(e,t){if(!e||uo)return"";uo=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(c){var r=c}Reflect.construct(e,[],t)}else{try{t.call()}catch(c){r=c}e.call(t.prototype)}else{try{throw Error()}catch(c){r=c}e()}}catch(c){if(c&&r&&typeof c.stack=="string"){for(var l=c.stack.split(`
+`),o=r.stack.split(`
+`),i=l.length-1,u=o.length-1;1<=i&&0<=u&&l[i]!==o[u];)u--;for(;1<=i&&0<=u;i--,u--)if(l[i]!==o[u]){if(i!==1||u!==1)do if(i--,u--,0>u||l[i]!==o[u]){var s=`
+`+l[i].replace(" at new "," at ");return e.displayName&&s.includes("<anonymous>")&&(s=s.replace("<anonymous>",e.displayName)),s}while(1<=i&&0<=u);break}}}finally{uo=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Un(e):""}function Bf(e){switch(e.tag){case 5:return Un(e.type);case 16:return Un("Lazy");case 13:return Un("Suspense");case 19:return Un("SuspenseList");case 0:case 2:case 15:return e=so(e.type,!1),e;case 11:return e=so(e.type.render,!1),e;case 1:return e=so(e.type,!0),e;default:return""}}function Do(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Zt:return"Fragment";case Gt:return"Portal";case Lo:return"Profiler";case Ci:return"StrictMode";case Ro:return"Suspense";case Oo:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case qs:return(e.displayName||"Context")+".Consumer";case Js:return(e._context.displayName||"Context")+".Provider";case _i:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ni:return t=e.displayName||null,t!==null?t:Do(e.type)||"Memo";case ot:t=e._payload,e=e._init;try{return Do(e(t))}catch{}}return null}function Hf(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Do(t);case 8:return t===Ci?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function wt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ea(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Wf(e){var t=ea(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(i){r=""+i,o.call(this,i)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Tr(e){e._valueTracker||(e._valueTracker=Wf(e))}function ta(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ea(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function rl(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Io(e,t){var n=t.checked;return U({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Yu(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=wt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function na(e,t){t=t.checked,t!=null&&Ei(e,"checked",t,!1)}function Mo(e,t){na(e,t);var n=wt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Fo(e,t.type,n):t.hasOwnProperty("defaultValue")&&Fo(e,t.type,wt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Xu(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Fo(e,t,n){(t!=="number"||rl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var An=Array.isArray;function sn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l<n.length;l++)t["$"+n[l]]=!0;for(n=0;n<e.length;n++)l=t.hasOwnProperty("$"+e[n].value),e[n].selected!==l&&(e[n].selected=l),l&&r&&(e[n].defaultSelected=!0)}else{for(n=""+wt(n),t=null,l=0;l<e.length;l++){if(e[l].value===n){e[l].selected=!0,r&&(e[l].defaultSelected=!0);return}t!==null||e[l].disabled||(t=e[l])}t!==null&&(t.selected=!0)}}function jo(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(y(91));return U({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function Gu(e,t){var n=t.value;if(n==null){if(n=t.children,t=t.defaultValue,n!=null){if(t!=null)throw Error(y(92));if(An(n)){if(1<n.length)throw Error(y(93));n=n[0]}t=n}t==null&&(t=""),n=t}e._wrapperState={initialValue:wt(n)}}function ra(e,t){var n=wt(t.value),r=wt(t.defaultValue);n!=null&&(n=""+n,n!==e.value&&(e.value=n),t.defaultValue==null&&e.defaultValue!==n&&(e.defaultValue=n)),r!=null&&(e.defaultValue=""+r)}function Zu(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==""&&t!==null&&(e.value=t)}function la(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Uo(e,t){return e==null||e==="http://www.w3.org/1999/xhtml"?la(t):e==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var Lr,oa=(function(e){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(t,n,r,l){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,l)})}:e})(function(e,t){if(e.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in e)e.innerHTML=t;else{for(Lr=Lr||document.createElement("div"),Lr.innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=Lr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function qn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Bn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Qf=["Webkit","ms","Moz","O"];Object.keys(Bn).forEach(function(e){Qf.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Bn[t]=Bn[e]})});function ia(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Bn.hasOwnProperty(e)&&Bn[e]?(""+t).trim():t+"px"}function ua(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=ia(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Kf=U({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Ao(e,t){if(t){if(Kf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(y(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(y(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(y(61))}if(t.style!=null&&typeof t.style!="object")throw Error(y(62))}}function Vo(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var $o=null;function Pi(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Bo=null,an=null,cn=null;function Ju(e){if(e=vr(e)){if(typeof Bo!="function")throw Error(y(280));var t=e.stateNode;t&&(t=Rl(t),Bo(e.stateNode,e.type,t))}}function sa(e){an?cn?cn.push(e):cn=[e]:an=e}function aa(){if(an){var e=an,t=cn;if(cn=an=null,Ju(e),t)for(e=0;e<t.length;e++)Ju(t[e])}}function ca(e,t){return e(t)}function fa(){}var ao=!1;function da(e,t,n){if(ao)return e(t,n);ao=!0;try{return ca(e,t,n)}finally{ao=!1,(an!==null||cn!==null)&&(fa(),aa())}}function bn(e,t){var n=e.stateNode;if(n===null)return null;var r=Rl(n);if(r===null)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(e=e.type,r=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!r;break e;default:e=!1}if(e)return null;if(n&&typeof n!="function")throw Error(y(231,t,typeof n));return n}var Ho=!1;if(Ye)try{Yt={},Object.defineProperty(Yt,"passive",{get:function(){Ho=!0}}),window.addEventListener("test",Yt,Yt),window.removeEventListener("test",Yt,Yt)}catch{Ho=!1}var Yt;function Yf(e,t,n,r,l,o,i,u,s){var c=Array.prototype.slice.call(arguments,3);try{t.apply(n,c)}catch(p){this.onError(p)}}var Hn=!1,ll=null,ol=!1,Wo=null,Xf={onError:function(e){Hn=!0,ll=e}};function Gf(e,t,n,r,l,o,i,u,s){Hn=!1,ll=null,Yf.apply(Xf,arguments)}function Zf(e,t,n,r,l,o,i,u,s){if(Gf.apply(this,arguments),Hn){if(Hn){var c=ll;Hn=!1,ll=null}else throw Error(y(198));ol||(ol=!0,Wo=c)}}function Ht(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,(t.flags&4098)!==0&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function pa(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function qu(e){if(Ht(e)!==e)throw Error(y(188))}function Jf(e){var t=e.alternate;if(!t){if(t=Ht(e),t===null)throw Error(y(188));return t!==e?null:e}for(var n=e,r=t;;){var l=n.return;if(l===null)break;var o=l.alternate;if(o===null){if(r=l.return,r!==null){n=r;continue}break}if(l.child===o.child){for(o=l.child;o;){if(o===n)return qu(l),e;if(o===r)return qu(l),t;o=o.sibling}throw Error(y(188))}if(n.return!==r.return)n=l,r=o;else{for(var i=!1,u=l.child;u;){if(u===n){i=!0,n=l,r=o;break}if(u===r){i=!0,r=l,n=o;break}u=u.sibling}if(!i){for(u=o.child;u;){if(u===n){i=!0,n=o,r=l;break}if(u===r){i=!0,r=o,n=l;break}u=u.sibling}if(!i)throw Error(y(189))}}if(n.alternate!==r)throw Error(y(190))}if(n.tag!==3)throw Error(y(188));return n.stateNode.current===n?e:t}function ma(e){return e=Jf(e),e!==null?ha(e):null}function ha(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=ha(e);if(t!==null)return t;e=e.sibling}return null}var va=he.unstable_scheduleCallback,bu=he.unstable_cancelCallback,qf=he.unstable_shouldYield,bf=he.unstable_requestPaint,V=he.unstable_now,ed=he.unstable_getCurrentPriorityLevel,zi=he.unstable_ImmediatePriority,ya=he.unstable_UserBlockingPriority,il=he.unstable_NormalPriority,td=he.unstable_LowPriority,ga=he.unstable_IdlePriority,Pl=null,Ae=null;function nd(e){if(Ae&&typeof Ae.onCommitFiberRoot=="function")try{Ae.onCommitFiberRoot(Pl,e,void 0,(e.current.flags&128)===128)}catch{}}var Oe=Math.clz32?Math.clz32:od,rd=Math.log,ld=Math.LN2;function od(e){return e>>>=0,e===0?32:31-(rd(e)/ld|0)|0}var Rr=64,Or=4194304;function Vn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function ul(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,o=e.pingedLanes,i=n&268435455;if(i!==0){var u=i&~l;u!==0?r=Vn(u):(o&=i,o!==0&&(r=Vn(o)))}else i=n&~l,i!==0?r=Vn(i):o!==0&&(r=Vn(o));if(r===0)return 0;if(t!==0&&t!==r&&(t&l)===0&&(l=r&-r,o=t&-t,l>=o||l===16&&(o&4194240)!==0))return t;if((r&4)!==0&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0<t;)n=31-Oe(t),l=1<<n,r|=e[n],t&=~l;return r}function id(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ud(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,o=e.pendingLanes;0<o;){var i=31-Oe(o),u=1<<i,s=l[i];s===-1?((u&n)===0||(u&r)!==0)&&(l[i]=id(u,t)):s<=t&&(e.expiredLanes|=u),o&=~u}}function Qo(e){return e=e.pendingLanes&-1073741825,e!==0?e:e&1073741824?1073741824:0}function wa(){var e=Rr;return Rr<<=1,(Rr&4194240)===0&&(Rr=64),e}function co(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function mr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Oe(t),e[t]=n}function sd(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<n;){var l=31-Oe(n),o=1<<l;t[l]=0,r[l]=-1,e[l]=-1,n&=~o}}function Ti(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-Oe(n),l=1<<r;l&t|e[r]&t&&(e[r]|=t),n&=~l}}var T=0;function ka(e){return e&=-e,1<e?4<e?(e&268435455)!==0?16:536870912:4:1}var Sa,Li,xa,Ea,Ca,Ko=!1,Dr=[],ft=null,dt=null,pt=null,er=new Map,tr=new Map,ut=[],ad="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function es(e,t){switch(e){case"focusin":case"focusout":ft=null;break;case"dragenter":case"dragleave":dt=null;break;case"mouseover":case"mouseout":pt=null;break;case"pointerover":case"pointerout":er.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":tr.delete(t.pointerId)}}function Rn(e,t,n,r,l,o){return e===null||e.nativeEvent!==o?(e={blockedOn:t,domEventName:n,eventSystemFlags:r,nativeEvent:o,targetContainers:[l]},t!==null&&(t=vr(t),t!==null&&Li(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,l!==null&&t.indexOf(l)===-1&&t.push(l),e)}function cd(e,t,n,r,l){switch(t){case"focusin":return ft=Rn(ft,e,t,n,r,l),!0;case"dragenter":return dt=Rn(dt,e,t,n,r,l),!0;case"mouseover":return pt=Rn(pt,e,t,n,r,l),!0;case"pointerover":var o=l.pointerId;return er.set(o,Rn(er.get(o)||null,e,t,n,r,l)),!0;case"gotpointercapture":return o=l.pointerId,tr.set(o,Rn(tr.get(o)||null,e,t,n,r,l)),!0}return!1}function _a(e){var t=Ot(e.target);if(t!==null){var n=Ht(t);if(n!==null){if(t=n.tag,t===13){if(t=pa(n),t!==null){e.blockedOn=t,Ca(e.priority,function(){xa(n)});return}}else if(t===3&&n.stateNode.current.memoizedState.isDehydrated){e.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Yr(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var n=Yo(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(n===null){n=e.nativeEvent;var r=new n.constructor(n.type,n);$o=r,n.target.dispatchEvent(r),$o=null}else return t=vr(n),t!==null&&Li(t),e.blockedOn=n,!1;t.shift()}return!0}function ts(e,t,n){Yr(e)&&n.delete(t)}function fd(){Ko=!1,ft!==null&&Yr(ft)&&(ft=null),dt!==null&&Yr(dt)&&(dt=null),pt!==null&&Yr(pt)&&(pt=null),er.forEach(ts),tr.forEach(ts)}function On(e,t){e.blockedOn===t&&(e.blockedOn=null,Ko||(Ko=!0,he.unstable_scheduleCallback(he.unstable_NormalPriority,fd)))}function nr(e){function t(l){return On(l,e)}if(0<Dr.length){On(Dr[0],e);for(var n=1;n<Dr.length;n++){var r=Dr[n];r.blockedOn===e&&(r.blockedOn=null)}}for(ft!==null&&On(ft,e),dt!==null&&On(dt,e),pt!==null&&On(pt,e),er.forEach(t),tr.forEach(t),n=0;n<ut.length;n++)r=ut[n],r.blockedOn===e&&(r.blockedOn=null);for(;0<ut.length&&(n=ut[0],n.blockedOn===null);)_a(n),n.blockedOn===null&&ut.shift()}var fn=Je.ReactCurrentBatchConfig,sl=!0;function dd(e,t,n,r){var l=T,o=fn.transition;fn.transition=null;try{T=1,Ri(e,t,n,r)}finally{T=l,fn.transition=o}}function pd(e,t,n,r){var l=T,o=fn.transition;fn.transition=null;try{T=4,Ri(e,t,n,r)}finally{T=l,fn.transition=o}}function Ri(e,t,n,r){if(sl){var l=Yo(e,t,n,r);if(l===null)go(e,t,r,al,n),es(e,r);else if(cd(l,e,t,n,r))r.stopPropagation();else if(es(e,r),t&4&&-1<ad.indexOf(e)){for(;l!==null;){var o=vr(l);if(o!==null&&Sa(o),o=Yo(e,t,n,r),o===null&&go(e,t,r,al,n),o===l)break;l=o}l!==null&&r.stopPropagation()}else go(e,t,r,null,n)}}var al=null;function Yo(e,t,n,r){if(al=null,e=Pi(r),e=Ot(e),e!==null)if(t=Ht(e),t===null)e=null;else if(n=t.tag,n===13){if(e=pa(t),e!==null)return e;e=null}else if(n===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return al=e,null}function Na(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(ed()){case zi:return 1;case ya:return 4;case il:case td:return 16;case ga:return 536870912;default:return 16}default:return 16}}var at=null,Oi=null,Xr=null;function Pa(){if(Xr)return Xr;var e,t=Oi,n=t.length,r,l="value"in at?at.value:at.textContent,o=l.length;for(e=0;e<n&&t[e]===l[e];e++);var i=n-e;for(r=1;r<=i&&t[n-r]===l[o-r];r++);return Xr=l.slice(e,1<r?1-r:void 0)}function Gr(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function Ir(){return!0}function ns(){return!1}function ve(e){function t(n,r,l,o,i){this._reactName=n,this._targetInst=l,this.type=r,this.nativeEvent=o,this.target=i,this.currentTarget=null;for(var u in e)e.hasOwnProperty(u)&&(n=e[u],this[u]=n?n(o):o[u]);return this.isDefaultPrevented=(o.defaultPrevented!=null?o.defaultPrevented:o.returnValue===!1)?Ir:ns,this.isPropagationStopped=ns,this}return U(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=Ir)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=Ir)},persist:function(){},isPersistent:Ir}),t}var Sn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Di=ve(Sn),hr=U({},Sn,{view:0,detail:0}),md=ve(hr),fo,po,Dn,zl=U({},hr,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Ii,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==Dn&&(Dn&&e.type==="mousemove"?(fo=e.screenX-Dn.screenX,po=e.screenY-Dn.screenY):po=fo=0,Dn=e),fo)},movementY:function(e){return"movementY"in e?e.movementY:po}}),rs=ve(zl),hd=U({},zl,{dataTransfer:0}),vd=ve(hd),yd=U({},hr,{relatedTarget:0}),mo=ve(yd),gd=U({},Sn,{animationName:0,elapsedTime:0,pseudoElement:0}),wd=ve(gd),kd=U({},Sn,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Sd=ve(kd),xd=U({},Sn,{data:0}),ls=ve(xd),Ed={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Cd={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},_d={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Nd(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=_d[e])?!!t[e]:!1}function Ii(){return Nd}var Pd=U({},hr,{key:function(e){if(e.key){var t=Ed[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=Gr(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?Cd[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Ii,charCode:function(e){return e.type==="keypress"?Gr(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Gr(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),zd=ve(Pd),Td=U({},zl,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),os=ve(Td),Ld=U({},hr,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Ii}),Rd=ve(Ld),Od=U({},Sn,{propertyName:0,elapsedTime:0,pseudoElement:0}),Dd=ve(Od),Id=U({},zl,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),Md=ve(Id),Fd=[9,13,27,32],Mi=Ye&&"CompositionEvent"in window,Wn=null;Ye&&"documentMode"in document&&(Wn=document.documentMode);var jd=Ye&&"TextEvent"in window&&!Wn,za=Ye&&(!Mi||Wn&&8<Wn&&11>=Wn),is=" ",us=!1;function Ta(e,t){switch(e){case"keyup":return Fd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function La(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Jt=!1;function Ud(e,t){switch(e){case"compositionend":return La(t);case"keypress":return t.which!==32?null:(us=!0,is);case"textInput":return e=t.data,e===is&&us?null:e;default:return null}}function Ad(e,t){if(Jt)return e==="compositionend"||!Mi&&Ta(e,t)?(e=Pa(),Xr=Oi=at=null,Jt=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return za&&t.locale!=="ko"?null:t.data;default:return null}}var Vd={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function ss(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!Vd[e.type]:t==="textarea"}function Ra(e,t,n,r){sa(r),t=cl(t,"onChange"),0<t.length&&(n=new Di("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var Qn=null,rr=null;function $d(e){Ba(e,0)}function Tl(e){var t=en(e);if(ta(t))return e}function Bd(e,t){if(e==="change")return t}var Oa=!1;Ye&&(Ye?(Fr="oninput"in document,Fr||(ho=document.createElement("div"),ho.setAttribute("oninput","return;"),Fr=typeof ho.oninput=="function"),Mr=Fr):Mr=!1,Oa=Mr&&(!document.documentMode||9<document.documentMode));var Mr,Fr,ho;function as(){Qn&&(Qn.detachEvent("onpropertychange",Da),rr=Qn=null)}function Da(e){if(e.propertyName==="value"&&Tl(rr)){var t=[];Ra(t,rr,e,Pi(e)),da($d,t)}}function Hd(e,t,n){e==="focusin"?(as(),Qn=t,rr=n,Qn.attachEvent("onpropertychange",Da)):e==="focusout"&&as()}function Wd(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Tl(rr)}function Qd(e,t){if(e==="click")return Tl(t)}function Kd(e,t){if(e==="input"||e==="change")return Tl(t)}function Yd(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Ie=typeof Object.is=="function"?Object.is:Yd;function lr(e,t){if(Ie(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var l=n[r];if(!To.call(t,l)||!Ie(e[l],t[l]))return!1}return!0}function cs(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function fs(e,t){var n=cs(e);e=0;for(var r;n;){if(n.nodeType===3){if(r=e+n.textContent.length,e<=t&&r>=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=cs(n)}}function Ia(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ia(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ma(){for(var e=window,t=rl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=rl(e.document)}return t}function Fi(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Xd(e){var t=Ma(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Ia(n.ownerDocument.documentElement,n)){if(r!==null&&Fi(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,o=Math.min(r.start,l);r=r.end===void 0?o:Math.min(r.end,l),!e.extend&&o>r&&(l=r,r=o,o=l),l=fs(n,o);var i=fs(n,r);l&&i&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n<t.length;n++)e=t[n],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var Gd=Ye&&"documentMode"in document&&11>=document.documentMode,qt=null,Xo=null,Kn=null,Go=!1;function ds(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Go||qt==null||qt!==rl(r)||(r=qt,"selectionStart"in r&&Fi(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Kn&&lr(Kn,r)||(Kn=r,r=cl(Xo,"onSelect"),0<r.length&&(t=new Di("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=qt)))}function jr(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var bt={animationend:jr("Animation","AnimationEnd"),animationiteration:jr("Animation","AnimationIteration"),animationstart:jr("Animation","AnimationStart"),transitionend:jr("Transition","TransitionEnd")},vo={},Fa={};Ye&&(Fa=document.createElement("div").style,"AnimationEvent"in window||(delete bt.animationend.animation,delete bt.animationiteration.animation,delete bt.animationstart.animation),"TransitionEvent"in window||delete bt.transitionend.transition);function Ll(e){if(vo[e])return vo[e];if(!bt[e])return e;var t=bt[e],n;for(n in t)if(t.hasOwnProperty(n)&&n in Fa)return vo[e]=t[n];return e}var ja=Ll("animationend"),Ua=Ll("animationiteration"),Aa=Ll("animationstart"),Va=Ll("transitionend"),$a=new Map,ps="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function St(e,t){$a.set(e,t),Bt(t,[e])}for(Ur=0;Ur<ps.length;Ur++)Ar=ps[Ur],ms=Ar.toLowerCase(),hs=Ar[0].toUpperCase()+Ar.slice(1),St(ms,"on"+hs);var Ar,ms,hs,Ur;St(ja,"onAnimationEnd");St(Ua,"onAnimationIteration");St(Aa,"onAnimationStart");St("dblclick","onDoubleClick");St("focusin","onFocus");St("focusout","onBlur");St(Va,"onTransitionEnd");mn("onMouseEnter",["mouseout","mouseover"]);mn("onMouseLeave",["mouseout","mouseover"]);mn("onPointerEnter",["pointerout","pointerover"]);mn("onPointerLeave",["pointerout","pointerover"]);Bt("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Bt("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Bt("onBeforeInput",["compositionend","keypress","textInput","paste"]);Bt("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Bt("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Bt("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var $n="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Zd=new Set("cancel close invalid load scroll toggle".split(" ").concat($n));function vs(e,t,n){var r=e.type||"unknown-event";e.currentTarget=n,Zf(r,t,void 0,e),e.currentTarget=null}function Ba(e,t){t=(t&4)!==0;for(var n=0;n<e.length;n++){var r=e[n],l=r.event;r=r.listeners;e:{var o=void 0;if(t)for(var i=r.length-1;0<=i;i--){var u=r[i],s=u.instance,c=u.currentTarget;if(u=u.listener,s!==o&&l.isPropagationStopped())break e;vs(l,u,c),o=s}else for(i=0;i<r.length;i++){if(u=r[i],s=u.instance,c=u.currentTarget,u=u.listener,s!==o&&l.isPropagationStopped())break e;vs(l,u,c),o=s}}}if(ol)throw e=Wo,ol=!1,Wo=null,e}function D(e,t){var n=t[ei];n===void 0&&(n=t[ei]=new Set);var r=e+"__bubble";n.has(r)||(Ha(t,e,2,!1),n.add(r))}function yo(e,t,n){var r=0;t&&(r|=4),Ha(n,e,r,t)}var Vr="_reactListening"+Math.random().toString(36).slice(2);function or(e){if(!e[Vr]){e[Vr]=!0,Zs.forEach(function(n){n!=="selectionchange"&&(Zd.has(n)||yo(n,!1,e),yo(n,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[Vr]||(t[Vr]=!0,yo("selectionchange",!1,t))}}function Ha(e,t,n,r){switch(Na(t)){case 1:var l=dd;break;case 4:l=pd;break;default:l=Ri}n=l.bind(null,t,n,e),l=void 0,!Ho||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(l=!0),r?l!==void 0?e.addEventListener(t,n,{capture:!0,passive:l}):e.addEventListener(t,n,!0):l!==void 0?e.addEventListener(t,n,{passive:l}):e.addEventListener(t,n,!1)}function go(e,t,n,r,l){var o=r;if((t&1)===0&&(t&2)===0&&r!==null)e:for(;;){if(r===null)return;var i=r.tag;if(i===3||i===4){var u=r.stateNode.containerInfo;if(u===l||u.nodeType===8&&u.parentNode===l)break;if(i===4)for(i=r.return;i!==null;){var s=i.tag;if((s===3||s===4)&&(s=i.stateNode.containerInfo,s===l||s.nodeType===8&&s.parentNode===l))return;i=i.return}for(;u!==null;){if(i=Ot(u),i===null)return;if(s=i.tag,s===5||s===6){r=o=i;continue e}u=u.parentNode}}r=r.return}da(function(){var c=o,p=Pi(n),m=[];e:{var h=$a.get(e);if(h!==void 0){var g=Di,w=e;switch(e){case"keypress":if(Gr(n)===0)break e;case"keydown":case"keyup":g=zd;break;case"focusin":w="focus",g=mo;break;case"focusout":w="blur",g=mo;break;case"beforeblur":case"afterblur":g=mo;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":g=rs;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":g=vd;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":g=Rd;break;case ja:case Ua:case Aa:g=wd;break;case Va:g=Dd;break;case"scroll":g=md;break;case"wheel":g=Md;break;case"copy":case"cut":case"paste":g=Sd;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":g=os}var S=(t&4)!==0,O=!S&&e==="scroll",d=S?h!==null?h+"Capture":null:h;S=[];for(var a=c,f;a!==null;){f=a;var v=f.stateNode;if(f.tag===5&&v!==null&&(f=v,d!==null&&(v=bn(a,d),v!=null&&S.push(ir(a,v,f)))),O)break;a=a.return}0<S.length&&(h=new g(h,w,null,n,p),m.push({event:h,listeners:S}))}}if((t&7)===0){e:{if(h=e==="mouseover"||e==="pointerover",g=e==="mouseout"||e==="pointerout",h&&n!==$o&&(w=n.relatedTarget||n.fromElement)&&(Ot(w)||w[Xe]))break e;if((g||h)&&(h=p.window===p?p:(h=p.ownerDocument)?h.defaultView||h.parentWindow:window,g?(w=n.relatedTarget||n.toElement,g=c,w=w?Ot(w):null,w!==null&&(O=Ht(w),w!==O||w.tag!==5&&w.tag!==6)&&(w=null)):(g=null,w=c),g!==w)){if(S=rs,v="onMouseLeave",d="onMouseEnter",a="mouse",(e==="pointerout"||e==="pointerover")&&(S=os,v="onPointerLeave",d="onPointerEnter",a="pointer"),O=g==null?h:en(g),f=w==null?h:en(w),h=new S(v,a+"leave",g,n,p),h.target=O,h.relatedTarget=f,v=null,Ot(p)===c&&(S=new S(d,a+"enter",w,n,p),S.target=f,S.relatedTarget=O,v=S),O=v,g&&w)t:{for(S=g,d=w,a=0,f=S;f;f=Xt(f))a++;for(f=0,v=d;v;v=Xt(v))f++;for(;0<a-f;)S=Xt(S),a--;for(;0<f-a;)d=Xt(d),f--;for(;a--;){if(S===d||d!==null&&S===d.alternate)break t;S=Xt(S),d=Xt(d)}S=null}else S=null;g!==null&&ys(m,h,g,S,!1),w!==null&&O!==null&&ys(m,O,w,S,!0)}}e:{if(h=c?en(c):window,g=h.nodeName&&h.nodeName.toLowerCase(),g==="select"||g==="input"&&h.type==="file")var x=Bd;else if(ss(h))if(Oa)x=Kd;else{x=Wd;var E=Hd}else(g=h.nodeName)&&g.toLowerCase()==="input"&&(h.type==="checkbox"||h.type==="radio")&&(x=Qd);if(x&&(x=x(e,c))){Ra(m,x,n,p);break e}E&&E(e,h,c),e==="focusout"&&(E=h._wrapperState)&&E.controlled&&h.type==="number"&&Fo(h,"number",h.value)}switch(E=c?en(c):window,e){case"focusin":(ss(E)||E.contentEditable==="true")&&(qt=E,Xo=c,Kn=null);break;case"focusout":Kn=Xo=qt=null;break;case"mousedown":Go=!0;break;case"contextmenu":case"mouseup":case"dragend":Go=!1,ds(m,n,p);break;case"selectionchange":if(Gd)break;case"keydown":case"keyup":ds(m,n,p)}var C;if(Mi)e:{switch(e){case"compositionstart":var _="onCompositionStart";break e;case"compositionend":_="onCompositionEnd";break e;case"compositionupdate":_="onCompositionUpdate";break e}_=void 0}else Jt?Ta(e,n)&&(_="onCompositionEnd"):e==="keydown"&&n.keyCode===229&&(_="onCompositionStart");_&&(za&&n.locale!=="ko"&&(Jt||_!=="onCompositionStart"?_==="onCompositionEnd"&&Jt&&(C=Pa()):(at=p,Oi="value"in at?at.value:at.textContent,Jt=!0)),E=cl(c,_),0<E.length&&(_=new ls(_,e,null,n,p),m.push({event:_,listeners:E}),C?_.data=C:(C=La(n),C!==null&&(_.data=C)))),(C=jd?Ud(e,n):Ad(e,n))&&(c=cl(c,"onBeforeInput"),0<c.length&&(p=new ls("onBeforeInput","beforeinput",null,n,p),m.push({event:p,listeners:c}),p.data=C))}Ba(m,t)})}function ir(e,t,n){return{instance:e,listener:t,currentTarget:n}}function cl(e,t){for(var n=t+"Capture",r=[];e!==null;){var l=e,o=l.stateNode;l.tag===5&&o!==null&&(l=o,o=bn(e,n),o!=null&&r.unshift(ir(e,o,l)),o=bn(e,t),o!=null&&r.push(ir(e,o,l))),e=e.return}return r}function Xt(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function ys(e,t,n,r,l){for(var o=t._reactName,i=[];n!==null&&n!==r;){var u=n,s=u.alternate,c=u.stateNode;if(s!==null&&s===r)break;u.tag===5&&c!==null&&(u=c,l?(s=bn(n,o),s!=null&&i.unshift(ir(n,s,u))):l||(s=bn(n,o),s!=null&&i.push(ir(n,s,u)))),n=n.return}i.length!==0&&e.push({event:t,listeners:i})}var Jd=/\r\n?/g,qd=/\u0000|\uFFFD/g;function gs(e){return(typeof e=="string"?e:""+e).replace(Jd,`
+`).replace(qd,"")}function $r(e,t,n){if(t=gs(t),gs(e)!==t&&n)throw Error(y(425))}function fl(){}var Zo=null,Jo=null;function qo(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var bo=typeof setTimeout=="function"?setTimeout:void 0,bd=typeof clearTimeout=="function"?clearTimeout:void 0,ws=typeof Promise=="function"?Promise:void 0,ep=typeof queueMicrotask=="function"?queueMicrotask:typeof ws<"u"?function(e){return ws.resolve(null).then(e).catch(tp)}:bo;function tp(e){setTimeout(function(){throw e})}function wo(e,t){var n=t,r=0;do{var l=n.nextSibling;if(e.removeChild(n),l&&l.nodeType===8)if(n=l.data,n==="/$"){if(r===0){e.removeChild(l),nr(t);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=l}while(n);nr(t)}function mt(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function ks(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="$"||n==="$!"||n==="$?"){if(t===0)return e;t--}else n==="/$"&&t++}e=e.previousSibling}return null}var xn=Math.random().toString(36).slice(2),Ue="__reactFiber$"+xn,ur="__reactProps$"+xn,Xe="__reactContainer$"+xn,ei="__reactEvents$"+xn,np="__reactListeners$"+xn,rp="__reactHandles$"+xn;function Ot(e){var t=e[Ue];if(t)return t;for(var n=e.parentNode;n;){if(t=n[Xe]||n[Ue]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=ks(e);e!==null;){if(n=e[Ue])return n;e=ks(e)}return t}e=n,n=e.parentNode}return null}function vr(e){return e=e[Ue]||e[Xe],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function en(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(y(33))}function Rl(e){return e[ur]||null}var ti=[],tn=-1;function xt(e){return{current:e}}function I(e){0>tn||(e.current=ti[tn],ti[tn]=null,tn--)}function R(e,t){tn++,ti[tn]=e.current,e.current=t}var kt={},te=xt(kt),se=xt(!1),jt=kt;function hn(e,t){var n=e.type.contextTypes;if(!n)return kt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},o;for(o in n)l[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function ae(e){return e=e.childContextTypes,e!=null}function dl(){I(se),I(te)}function Ss(e,t,n){if(te.current!==kt)throw Error(y(168));R(te,t),R(se,n)}function Wa(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(y(108,Hf(e)||"Unknown",l));return U({},n,r)}function pl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kt,jt=te.current,R(te,e),R(se,se.current),!0}function xs(e,t,n){var r=e.stateNode;if(!r)throw Error(y(169));n?(e=Wa(e,t,jt),r.__reactInternalMemoizedMergedChildContext=e,I(se),I(te),R(te,e)):I(se),R(se,n)}var He=null,Ol=!1,ko=!1;function Qa(e){He===null?He=[e]:He.push(e)}function lp(e){Ol=!0,Qa(e)}function Et(){if(!ko&&He!==null){ko=!0;var e=0,t=T;try{var n=He;for(T=1;e<n.length;e++){var r=n[e];do r=r(!0);while(r!==null)}He=null,Ol=!1}catch(l){throw He!==null&&(He=He.slice(e+1)),va(zi,Et),l}finally{T=t,ko=!1}}return null}var nn=[],rn=0,ml=null,hl=0,ke=[],Se=0,Ut=null,We=1,Qe="";function Lt(e,t){nn[rn++]=hl,nn[rn++]=ml,ml=e,hl=t}function Ka(e,t,n){ke[Se++]=We,ke[Se++]=Qe,ke[Se++]=Ut,Ut=e;var r=We;e=Qe;var l=32-Oe(r)-1;r&=~(1<<l),n+=1;var o=32-Oe(t)+l;if(30<o){var i=l-l%5;o=(r&(1<<i)-1).toString(32),r>>=i,l-=i,We=1<<32-Oe(t)+l|n<<l|r,Qe=o+e}else We=1<<o|n<<l|r,Qe=e}function ji(e){e.return!==null&&(Lt(e,1),Ka(e,1,0))}function Ui(e){for(;e===ml;)ml=nn[--rn],nn[rn]=null,hl=nn[--rn],nn[rn]=null;for(;e===Ut;)Ut=ke[--Se],ke[Se]=null,Qe=ke[--Se],ke[Se]=null,We=ke[--Se],ke[Se]=null}var me=null,pe=null,M=!1,Re=null;function Ya(e,t){var n=xe(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)}function Es(e,t){switch(e.tag){case 5:var n=e.type;return t=t.nodeType!==1||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,me=e,pe=mt(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,me=e,pe=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(n=Ut!==null?{id:We,overflow:Qe}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=xe(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,me=e,pe=null,!0):!1;default:return!1}}function ni(e){return(e.mode&1)!==0&&(e.flags&128)===0}function ri(e){if(M){var t=pe;if(t){var n=t;if(!Es(e,t)){if(ni(e))throw Error(y(418));t=mt(n.nextSibling);var r=me;t&&Es(e,t)?Ya(r,n):(e.flags=e.flags&-4097|2,M=!1,me=e)}}else{if(ni(e))throw Error(y(418));e.flags=e.flags&-4097|2,M=!1,me=e}}}function Cs(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;me=e}function Br(e){if(e!==me)return!1;if(!M)return Cs(e),M=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!=="head"&&t!=="body"&&!qo(e.type,e.memoizedProps)),t&&(t=pe)){if(ni(e))throw Xa(),Error(y(418));for(;t;)Ya(e,t),t=mt(t.nextSibling)}if(Cs(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(y(317));e:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="/$"){if(t===0){pe=mt(e.nextSibling);break e}t--}else n!=="$"&&n!=="$!"&&n!=="$?"||t++}e=e.nextSibling}pe=null}}else pe=me?mt(e.stateNode.nextSibling):null;return!0}function Xa(){for(var e=pe;e;)e=mt(e.nextSibling)}function vn(){pe=me=null,M=!1}function Ai(e){Re===null?Re=[e]:Re.push(e)}var op=Je.ReactCurrentBatchConfig;function In(e,t,n){if(e=n.ref,e!==null&&typeof e!="function"&&typeof e!="object"){if(n._owner){if(n=n._owner,n){if(n.tag!==1)throw Error(y(309));var r=n.stateNode}if(!r)throw Error(y(147,e));var l=r,o=""+e;return t!==null&&t.ref!==null&&typeof t.ref=="function"&&t.ref._stringRef===o?t.ref:(t=function(i){var u=l.refs;i===null?delete u[o]:u[o]=i},t._stringRef=o,t)}if(typeof e!="string")throw Error(y(284));if(!n._owner)throw Error(y(290,e))}return e}function Hr(e,t){throw e=Object.prototype.toString.call(t),Error(y(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function _s(e){var t=e._init;return t(e._payload)}function Ga(e){function t(d,a){if(e){var f=d.deletions;f===null?(d.deletions=[a],d.flags|=16):f.push(a)}}function n(d,a){if(!e)return null;for(;a!==null;)t(d,a),a=a.sibling;return null}function r(d,a){for(d=new Map;a!==null;)a.key!==null?d.set(a.key,a):d.set(a.index,a),a=a.sibling;return d}function l(d,a){return d=gt(d,a),d.index=0,d.sibling=null,d}function o(d,a,f){return d.index=f,e?(f=d.alternate,f!==null?(f=f.index,f<a?(d.flags|=2,a):f):(d.flags|=2,a)):(d.flags|=1048576,a)}function i(d){return e&&d.alternate===null&&(d.flags|=2),d}function u(d,a,f,v){return a===null||a.tag!==6?(a=Po(f,d.mode,v),a.return=d,a):(a=l(a,f),a.return=d,a)}function s(d,a,f,v){var x=f.type;return x===Zt?p(d,a,f.props.children,v,f.key):a!==null&&(a.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===ot&&_s(x)===a.type)?(v=l(a,f.props),v.ref=In(d,a,f),v.return=d,v):(v=nl(f.type,f.key,f.props,null,d.mode,v),v.ref=In(d,a,f),v.return=d,v)}function c(d,a,f,v){return a===null||a.tag!==4||a.stateNode.containerInfo!==f.containerInfo||a.stateNode.implementation!==f.implementation?(a=zo(f,d.mode,v),a.return=d,a):(a=l(a,f.children||[]),a.return=d,a)}function p(d,a,f,v,x){return a===null||a.tag!==7?(a=Ft(f,d.mode,v,x),a.return=d,a):(a=l(a,f),a.return=d,a)}function m(d,a,f){if(typeof a=="string"&&a!==""||typeof a=="number")return a=Po(""+a,d.mode,f),a.return=d,a;if(typeof a=="object"&&a!==null){switch(a.$$typeof){case zr:return f=nl(a.type,a.key,a.props,null,d.mode,f),f.ref=In(d,null,a),f.return=d,f;case Gt:return a=zo(a,d.mode,f),a.return=d,a;case ot:var v=a._init;return m(d,v(a._payload),f)}if(An(a)||Ln(a))return a=Ft(a,d.mode,f,null),a.return=d,a;Hr(d,a)}return null}function h(d,a,f,v){var x=a!==null?a.key:null;if(typeof f=="string"&&f!==""||typeof f=="number")return x!==null?null:u(d,a,""+f,v);if(typeof f=="object"&&f!==null){switch(f.$$typeof){case zr:return f.key===x?s(d,a,f,v):null;case Gt:return f.key===x?c(d,a,f,v):null;case ot:return x=f._init,h(d,a,x(f._payload),v)}if(An(f)||Ln(f))return x!==null?null:p(d,a,f,v,null);Hr(d,f)}return null}function g(d,a,f,v,x){if(typeof v=="string"&&v!==""||typeof v=="number")return d=d.get(f)||null,u(a,d,""+v,x);if(typeof v=="object"&&v!==null){switch(v.$$typeof){case zr:return d=d.get(v.key===null?f:v.key)||null,s(a,d,v,x);case Gt:return d=d.get(v.key===null?f:v.key)||null,c(a,d,v,x);case ot:var E=v._init;return g(d,a,f,E(v._payload),x)}if(An(v)||Ln(v))return d=d.get(f)||null,p(a,d,v,x,null);Hr(a,v)}return null}function w(d,a,f,v){for(var x=null,E=null,C=a,_=a=0,Q=null;C!==null&&_<f.length;_++){C.index>_?(Q=C,C=null):Q=C.sibling;var z=h(d,C,f[_],v);if(z===null){C===null&&(C=Q);break}e&&C&&z.alternate===null&&t(d,C),a=o(z,a,_),E===null?x=z:E.sibling=z,E=z,C=Q}if(_===f.length)return n(d,C),M&&Lt(d,_),x;if(C===null){for(;_<f.length;_++)C=m(d,f[_],v),C!==null&&(a=o(C,a,_),E===null?x=C:E.sibling=C,E=C);return M&&Lt(d,_),x}for(C=r(d,C);_<f.length;_++)Q=g(C,d,_,f[_],v),Q!==null&&(e&&Q.alternate!==null&&C.delete(Q.key===null?_:Q.key),a=o(Q,a,_),E===null?x=Q:E.sibling=Q,E=Q);return e&&C.forEach(function(et){return t(d,et)}),M&&Lt(d,_),x}function S(d,a,f,v){var x=Ln(f);if(typeof x!="function")throw Error(y(150));if(f=x.call(f),f==null)throw Error(y(151));for(var E=x=null,C=a,_=a=0,Q=null,z=f.next();C!==null&&!z.done;_++,z=f.next()){C.index>_?(Q=C,C=null):Q=C.sibling;var et=h(d,C,z.value,v);if(et===null){C===null&&(C=Q);break}e&&C&&et.alternate===null&&t(d,C),a=o(et,a,_),E===null?x=et:E.sibling=et,E=et,C=Q}if(z.done)return n(d,C),M&&Lt(d,_),x;if(C===null){for(;!z.done;_++,z=f.next())z=m(d,z.value,v),z!==null&&(a=o(z,a,_),E===null?x=z:E.sibling=z,E=z);return M&&Lt(d,_),x}for(C=r(d,C);!z.done;_++,z=f.next())z=g(C,d,_,z.value,v),z!==null&&(e&&z.alternate!==null&&C.delete(z.key===null?_:z.key),a=o(z,a,_),E===null?x=z:E.sibling=z,E=z);return e&&C.forEach(function(mf){return t(d,mf)}),M&&Lt(d,_),x}function O(d,a,f,v){if(typeof f=="object"&&f!==null&&f.type===Zt&&f.key===null&&(f=f.props.children),typeof f=="object"&&f!==null){switch(f.$$typeof){case zr:e:{for(var x=f.key,E=a;E!==null;){if(E.key===x){if(x=f.type,x===Zt){if(E.tag===7){n(d,E.sibling),a=l(E,f.props.children),a.return=d,d=a;break e}}else if(E.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===ot&&_s(x)===E.type){n(d,E.sibling),a=l(E,f.props),a.ref=In(d,E,f),a.return=d,d=a;break e}n(d,E);break}else t(d,E);E=E.sibling}f.type===Zt?(a=Ft(f.props.children,d.mode,v,f.key),a.return=d,d=a):(v=nl(f.type,f.key,f.props,null,d.mode,v),v.ref=In(d,a,f),v.return=d,d=v)}return i(d);case Gt:e:{for(E=f.key;a!==null;){if(a.key===E)if(a.tag===4&&a.stateNode.containerInfo===f.containerInfo&&a.stateNode.implementation===f.implementation){n(d,a.sibling),a=l(a,f.children||[]),a.return=d,d=a;break e}else{n(d,a);break}else t(d,a);a=a.sibling}a=zo(f,d.mode,v),a.return=d,d=a}return i(d);case ot:return E=f._init,O(d,a,E(f._payload),v)}if(An(f))return w(d,a,f,v);if(Ln(f))return S(d,a,f,v);Hr(d,f)}return typeof f=="string"&&f!==""||typeof f=="number"?(f=""+f,a!==null&&a.tag===6?(n(d,a.sibling),a=l(a,f),a.return=d,d=a):(n(d,a),a=Po(f,d.mode,v),a.return=d,d=a),i(d)):n(d,a)}return O}var yn=Ga(!0),Za=Ga(!1),vl=xt(null),yl=null,ln=null,Vi=null;function $i(){Vi=ln=yl=null}function Bi(e){var t=vl.current;I(vl),e._currentValue=t}function li(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function dn(e,t){yl=e,Vi=ln=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(ue=!0),e.firstContext=null)}function Ce(e){var t=e._currentValue;if(Vi!==e)if(e={context:e,memoizedValue:t,next:null},ln===null){if(yl===null)throw Error(y(308));ln=e,yl.dependencies={lanes:0,firstContext:e}}else ln=ln.next=e;return t}var Dt=null;function Hi(e){Dt===null?Dt=[e]:Dt.push(e)}function Ja(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Hi(t)):(n.next=l.next,l.next=n),t.interleaved=n,Ge(e,r)}function Ge(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var it=!1;function Wi(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function qa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ke(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ht(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(P&2)!==0){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Ge(e,n)}return l=r.interleaved,l===null?(t.next=t,Hi(r)):(t.next=l.next,l.next=t),r.interleaved=t,Ge(e,n)}function Zr(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ti(e,n)}}function Ns(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var i={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?l=o=i:o=o.next=i,n=n.next}while(n!==null);o===null?l=o=t:o=o.next=t}else l=o=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function gl(e,t,n,r){var l=e.updateQueue;it=!1;var o=l.firstBaseUpdate,i=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var s=u,c=s.next;s.next=null,i===null?o=c:i.next=c,i=s;var p=e.alternate;p!==null&&(p=p.updateQueue,u=p.lastBaseUpdate,u!==i&&(u===null?p.firstBaseUpdate=c:u.next=c,p.lastBaseUpdate=s))}if(o!==null){var m=l.baseState;i=0,p=c=s=null,u=o;do{var h=u.lane,g=u.eventTime;if((r&h)===h){p!==null&&(p=p.next={eventTime:g,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var w=e,S=u;switch(h=t,g=n,S.tag){case 1:if(w=S.payload,typeof w=="function"){m=w.call(g,m,h);break e}m=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=S.payload,h=typeof w=="function"?w.call(g,m,h):w,h==null)break e;m=U({},m,h);break e;case 2:it=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[u]:h.push(u))}else g={eventTime:g,lane:h,tag:u.tag,payload:u.payload,callback:u.callback,next:null},p===null?(c=p=g,s=m):p=p.next=g,i|=h;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;h=u,u=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(p===null&&(s=m),l.baseState=s,l.firstBaseUpdate=c,l.lastBaseUpdate=p,t=l.shared.interleaved,t!==null){l=t;do i|=l.lane,l=l.next;while(l!==t)}else o===null&&(l.shared.lanes=0);Vt|=i,e.lanes=i,e.memoizedState=m}}function Ps(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;t<e.length;t++){var r=e[t],l=r.callback;if(l!==null){if(r.callback=null,r=n,typeof l!="function")throw Error(y(191,l));l.call(r)}}}var yr={},Ve=xt(yr),sr=xt(yr),ar=xt(yr);function It(e){if(e===yr)throw Error(y(174));return e}function Qi(e,t){switch(R(ar,t),R(sr,e),R(Ve,yr),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Uo(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Uo(t,e)}I(Ve),R(Ve,t)}function gn(){I(Ve),I(sr),I(ar)}function ba(e){It(ar.current);var t=It(Ve.current),n=Uo(t,e.type);t!==n&&(R(sr,e),R(Ve,n))}function Ki(e){sr.current===e&&(I(Ve),I(sr))}var F=xt(0);function wl(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if((t.flags&128)!==0)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var So=[];function Yi(){for(var e=0;e<So.length;e++)So[e]._workInProgressVersionPrimary=null;So.length=0}var Jr=Je.ReactCurrentDispatcher,xo=Je.ReactCurrentBatchConfig,At=0,j=null,B=null,K=null,kl=!1,Yn=!1,cr=0,ip=0;function q(){throw Error(y(321))}function Xi(e,t){if(t===null)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!Ie(e[n],t[n]))return!1;return!0}function Gi(e,t,n,r,l,o){if(At=o,j=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,Jr.current=e===null||e.memoizedState===null?cp:fp,e=n(r,l),Yn){o=0;do{if(Yn=!1,cr=0,25<=o)throw Error(y(301));o+=1,K=B=null,t.updateQueue=null,Jr.current=dp,e=n(r,l)}while(Yn)}if(Jr.current=Sl,t=B!==null&&B.next!==null,At=0,K=B=j=null,kl=!1,t)throw Error(y(300));return e}function Zi(){var e=cr!==0;return cr=0,e}function je(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return K===null?j.memoizedState=K=e:K=K.next=e,K}function _e(){if(B===null){var e=j.alternate;e=e!==null?e.memoizedState:null}else e=B.next;var t=K===null?j.memoizedState:K.next;if(t!==null)K=t,B=e;else{if(e===null)throw Error(y(310));B=e,e={memoizedState:B.memoizedState,baseState:B.baseState,baseQueue:B.baseQueue,queue:B.queue,next:null},K===null?j.memoizedState=K=e:K=K.next=e}return K}function fr(e,t){return typeof t=="function"?t(e):t}function Eo(e){var t=_e(),n=t.queue;if(n===null)throw Error(y(311));n.lastRenderedReducer=e;var r=B,l=r.baseQueue,o=n.pending;if(o!==null){if(l!==null){var i=l.next;l.next=o.next,o.next=i}r.baseQueue=l=o,n.pending=null}if(l!==null){o=l.next,r=r.baseState;var u=i=null,s=null,c=o;do{var p=c.lane;if((At&p)===p)s!==null&&(s=s.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),r=c.hasEagerState?c.eagerState:e(r,c.action);else{var m={lane:p,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};s===null?(u=s=m,i=r):s=s.next=m,j.lanes|=p,Vt|=p}c=c.next}while(c!==null&&c!==o);s===null?i=r:s.next=u,Ie(r,t.memoizedState)||(ue=!0),t.memoizedState=r,t.baseState=i,t.baseQueue=s,n.lastRenderedState=r}if(e=n.interleaved,e!==null){l=e;do o=l.lane,j.lanes|=o,Vt|=o,l=l.next;while(l!==e)}else l===null&&(n.lanes=0);return[t.memoizedState,n.dispatch]}function Co(e){var t=_e(),n=t.queue;if(n===null)throw Error(y(311));n.lastRenderedReducer=e;var r=n.dispatch,l=n.pending,o=t.memoizedState;if(l!==null){n.pending=null;var i=l=l.next;do o=e(o,i.action),i=i.next;while(i!==l);Ie(o,t.memoizedState)||(ue=!0),t.memoizedState=o,t.baseQueue===null&&(t.baseState=o),n.lastRenderedState=o}return[o,r]}function ec(){}function tc(e,t){var n=j,r=_e(),l=t(),o=!Ie(r.memoizedState,l);if(o&&(r.memoizedState=l,ue=!0),r=r.queue,Ji(lc.bind(null,n,r,e),[e]),r.getSnapshot!==t||o||K!==null&&K.memoizedState.tag&1){if(n.flags|=2048,dr(9,rc.bind(null,n,r,l,t),void 0,null),Y===null)throw Error(y(349));(At&30)!==0||nc(n,t,l)}return l}function nc(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},t=j.updateQueue,t===null?(t={lastEffect:null,stores:null},j.updateQueue=t,t.stores=[e]):(n=t.stores,n===null?t.stores=[e]:n.push(e))}function rc(e,t,n,r){t.value=n,t.getSnapshot=r,oc(t)&&ic(e)}function lc(e,t,n){return n(function(){oc(t)&&ic(e)})}function oc(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Ie(e,n)}catch{return!0}}function ic(e){var t=Ge(e,1);t!==null&&De(t,e,1,-1)}function zs(e){var t=je();return typeof e=="function"&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:fr,lastRenderedState:e},t.queue=e,e=e.dispatch=ap.bind(null,j,e),[t.memoizedState,e]}function dr(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},t=j.updateQueue,t===null?(t={lastEffect:null,stores:null},j.updateQueue=t,t.lastEffect=e.next=e):(n=t.lastEffect,n===null?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e)),e}function uc(){return _e().memoizedState}function qr(e,t,n,r){var l=je();j.flags|=e,l.memoizedState=dr(1|t,n,void 0,r===void 0?null:r)}function Dl(e,t,n,r){var l=_e();r=r===void 0?null:r;var o=void 0;if(B!==null){var i=B.memoizedState;if(o=i.destroy,r!==null&&Xi(r,i.deps)){l.memoizedState=dr(t,n,o,r);return}}j.flags|=e,l.memoizedState=dr(1|t,n,o,r)}function Ts(e,t){return qr(8390656,8,e,t)}function Ji(e,t){return Dl(2048,8,e,t)}function sc(e,t){return Dl(4,2,e,t)}function ac(e,t){return Dl(4,4,e,t)}function cc(e,t){if(typeof t=="function")return e=e(),t(e),function(){t(null)};if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function fc(e,t,n){return n=n!=null?n.concat([e]):null,Dl(4,4,cc.bind(null,t,e),n)}function qi(){}function dc(e,t){var n=_e();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Xi(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function pc(e,t){var n=_e();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Xi(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)}function mc(e,t,n){return(At&21)===0?(e.baseState&&(e.baseState=!1,ue=!0),e.memoizedState=n):(Ie(n,t)||(n=wa(),j.lanes|=n,Vt|=n,e.baseState=!0),t)}function up(e,t){var n=T;T=n!==0&&4>n?n:4,e(!0);var r=xo.transition;xo.transition={};try{e(!1),t()}finally{T=n,xo.transition=r}}function hc(){return _e().memoizedState}function sp(e,t,n){var r=yt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},vc(e))yc(t,n);else if(n=Ja(e,t,n,r),n!==null){var l=le();De(n,e,r,l),gc(n,t,r)}}function ap(e,t,n){var r=yt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(vc(e))yc(t,l);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var i=t.lastRenderedState,u=o(i,n);if(l.hasEagerState=!0,l.eagerState=u,Ie(u,i)){var s=t.interleaved;s===null?(l.next=l,Hi(t)):(l.next=s.next,s.next=l),t.interleaved=l;return}}catch{}finally{}n=Ja(e,t,l,r),n!==null&&(l=le(),De(n,e,r,l),gc(n,t,r))}}function vc(e){var t=e.alternate;return e===j||t!==null&&t===j}function yc(e,t){Yn=kl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function gc(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Ti(e,n)}}var Sl={readContext:Ce,useCallback:q,useContext:q,useEffect:q,useImperativeHandle:q,useInsertionEffect:q,useLayoutEffect:q,useMemo:q,useReducer:q,useRef:q,useState:q,useDebugValue:q,useDeferredValue:q,useTransition:q,useMutableSource:q,useSyncExternalStore:q,useId:q,unstable_isNewReconciler:!1},cp={readContext:Ce,useCallback:function(e,t){return je().memoizedState=[e,t===void 0?null:t],e},useContext:Ce,useEffect:Ts,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,qr(4194308,4,cc.bind(null,t,e),n)},useLayoutEffect:function(e,t){return qr(4194308,4,e,t)},useInsertionEffect:function(e,t){return qr(4,2,e,t)},useMemo:function(e,t){var n=je();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=je();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=sp.bind(null,j,e),[r.memoizedState,e]},useRef:function(e){var t=je();return e={current:e},t.memoizedState=e},useState:zs,useDebugValue:qi,useDeferredValue:function(e){return je().memoizedState=e},useTransition:function(){var e=zs(!1),t=e[0];return e=up.bind(null,e[1]),je().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=j,l=je();if(M){if(n===void 0)throw Error(y(407));n=n()}else{if(n=t(),Y===null)throw Error(y(349));(At&30)!==0||nc(r,t,n)}l.memoizedState=n;var o={value:n,getSnapshot:t};return l.queue=o,Ts(lc.bind(null,r,o,e),[e]),r.flags|=2048,dr(9,rc.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=je(),t=Y.identifierPrefix;if(M){var n=Qe,r=We;n=(r&~(1<<32-Oe(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=cr++,0<n&&(t+="H"+n.toString(32)),t+=":"}else n=ip++,t=":"+t+"r"+n.toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},fp={readContext:Ce,useCallback:dc,useContext:Ce,useEffect:Ji,useImperativeHandle:fc,useInsertionEffect:sc,useLayoutEffect:ac,useMemo:pc,useReducer:Eo,useRef:uc,useState:function(){return Eo(fr)},useDebugValue:qi,useDeferredValue:function(e){var t=_e();return mc(t,B.memoizedState,e)},useTransition:function(){var e=Eo(fr)[0],t=_e().memoizedState;return[e,t]},useMutableSource:ec,useSyncExternalStore:tc,useId:hc,unstable_isNewReconciler:!1},dp={readContext:Ce,useCallback:dc,useContext:Ce,useEffect:Ji,useImperativeHandle:fc,useInsertionEffect:sc,useLayoutEffect:ac,useMemo:pc,useReducer:Co,useRef:uc,useState:function(){return Co(fr)},useDebugValue:qi,useDeferredValue:function(e){var t=_e();return B===null?t.memoizedState=e:mc(t,B.memoizedState,e)},useTransition:function(){var e=Co(fr)[0],t=_e().memoizedState;return[e,t]},useMutableSource:ec,useSyncExternalStore:tc,useId:hc,unstable_isNewReconciler:!1};function Te(e,t){if(e&&e.defaultProps){t=U({},t),e=e.defaultProps;for(var n in e)t[n]===void 0&&(t[n]=e[n]);return t}return t}function oi(e,t,n,r){t=e.memoizedState,n=n(r,t),n=n==null?t:U({},t,n),e.memoizedState=n,e.lanes===0&&(e.updateQueue.baseState=n)}var Il={isMounted:function(e){return(e=e._reactInternals)?Ht(e)===e:!1},enqueueSetState:function(e,t,n){e=e._reactInternals;var r=le(),l=yt(e),o=Ke(r,l);o.payload=t,n!=null&&(o.callback=n),t=ht(e,o,l),t!==null&&(De(t,e,l,r),Zr(t,e,l))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var r=le(),l=yt(e),o=Ke(r,l);o.tag=1,o.payload=t,n!=null&&(o.callback=n),t=ht(e,o,l),t!==null&&(De(t,e,l,r),Zr(t,e,l))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=le(),r=yt(e),l=Ke(n,r);l.tag=2,t!=null&&(l.callback=t),t=ht(e,l,r),t!==null&&(De(t,e,r,n),Zr(t,e,r))}};function Ls(e,t,n,r,l,o,i){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(r,o,i):t.prototype&&t.prototype.isPureReactComponent?!lr(n,r)||!lr(l,o):!0}function wc(e,t,n){var r=!1,l=kt,o=t.contextType;return typeof o=="object"&&o!==null?o=Ce(o):(l=ae(t)?jt:te.current,r=t.contextTypes,o=(r=r!=null)?hn(e,l):kt),t=new t(n,o),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=Il,e.stateNode=t,t._reactInternals=e,r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=o),t}function Rs(e,t,n,r){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(n,r),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&Il.enqueueReplaceState(t,t.state,null)}function ii(e,t,n,r){var l=e.stateNode;l.props=n,l.state=e.memoizedState,l.refs={},Wi(e);var o=t.contextType;typeof o=="object"&&o!==null?l.context=Ce(o):(o=ae(t)?jt:te.current,l.context=hn(e,o)),l.state=e.memoizedState,o=t.getDerivedStateFromProps,typeof o=="function"&&(oi(e,t,o,n),l.state=e.memoizedState),typeof t.getDerivedStateFromProps=="function"||typeof l.getSnapshotBeforeUpdate=="function"||typeof l.UNSAFE_componentWillMount!="function"&&typeof l.componentWillMount!="function"||(t=l.state,typeof l.componentWillMount=="function"&&l.componentWillMount(),typeof l.UNSAFE_componentWillMount=="function"&&l.UNSAFE_componentWillMount(),t!==l.state&&Il.enqueueReplaceState(l,l.state,null),gl(e,n,l,r),l.state=e.memoizedState),typeof l.componentDidMount=="function"&&(e.flags|=4194308)}function wn(e,t){try{var n="",r=t;do n+=Bf(r),r=r.return;while(r);var l=n}catch(o){l=`
+Error generating stack: `+o.message+`
+`+o.stack}return{value:e,source:t,stack:l,digest:null}}function _o(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function ui(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var pp=typeof WeakMap=="function"?WeakMap:Map;function kc(e,t,n){n=Ke(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){El||(El=!0,yi=r),ui(e,t)},n}function Sc(e,t,n){n=Ke(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var l=t.value;n.payload=function(){return r(l)},n.callback=function(){ui(e,t)}}var o=e.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(n.callback=function(){ui(e,t),typeof r!="function"&&(vt===null?vt=new Set([this]):vt.add(this));var i=t.stack;this.componentDidCatch(t.value,{componentStack:i!==null?i:""})}),n}function Os(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new pp;var l=new Set;r.set(t,l)}else l=r.get(t),l===void 0&&(l=new Set,r.set(t,l));l.has(n)||(l.add(n),e=Pp.bind(null,e,t,n),t.then(e,e))}function Ds(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Is(e,t,n,r,l){return(e.mode&1)===0?(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=Ke(-1,1),t.tag=2,ht(n,t,1))),n.lanes|=1),e):(e.flags|=65536,e.lanes=l,e)}var mp=Je.ReactCurrentOwner,ue=!1;function re(e,t,n,r){t.child=e===null?Za(t,null,n,r):yn(t,e.child,n,r)}function Ms(e,t,n,r,l){n=n.render;var o=t.ref;return dn(t,l),r=Gi(e,t,n,r,o,l),n=Zi(),e!==null&&!ue?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,Ze(e,t,l)):(M&&n&&ji(t),t.flags|=1,re(e,t,r,l),t.child)}function Fs(e,t,n,r,l){if(e===null){var o=n.type;return typeof o=="function"&&!iu(o)&&o.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=o,xc(e,t,o,r,l)):(e=nl(n.type,null,r,t,t.mode,l),e.ref=t.ref,e.return=t,t.child=e)}if(o=e.child,(e.lanes&l)===0){var i=o.memoizedProps;if(n=n.compare,n=n!==null?n:lr,n(i,r)&&e.ref===t.ref)return Ze(e,t,l)}return t.flags|=1,e=gt(o,r),e.ref=t.ref,e.return=t,t.child=e}function xc(e,t,n,r,l){if(e!==null){var o=e.memoizedProps;if(lr(o,r)&&e.ref===t.ref)if(ue=!1,t.pendingProps=r=o,(e.lanes&l)!==0)(e.flags&131072)!==0&&(ue=!0);else return t.lanes=e.lanes,Ze(e,t,l)}return si(e,t,n,r,l)}function Ec(e,t,n){var r=t.pendingProps,l=r.children,o=e!==null?e.memoizedState:null;if(r.mode==="hidden")if((t.mode&1)===0)t.memoizedState={baseLanes:0,cachePool:null,transitions:null},R(un,de),de|=n;else{if((n&1073741824)===0)return e=o!==null?o.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,R(un,de),de|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=o!==null?o.baseLanes:n,R(un,de),de|=r}else o!==null?(r=o.baseLanes|n,t.memoizedState=null):r=n,R(un,de),de|=r;return re(e,t,l,n),t.child}function Cc(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function si(e,t,n,r,l){var o=ae(n)?jt:te.current;return o=hn(t,o),dn(t,l),n=Gi(e,t,n,r,o,l),r=Zi(),e!==null&&!ue?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,Ze(e,t,l)):(M&&r&&ji(t),t.flags|=1,re(e,t,n,l),t.child)}function js(e,t,n,r,l){if(ae(n)){var o=!0;pl(t)}else o=!1;if(dn(t,l),t.stateNode===null)br(e,t),wc(t,n,r),ii(t,n,r,l),r=!0;else if(e===null){var i=t.stateNode,u=t.memoizedProps;i.props=u;var s=i.context,c=n.contextType;typeof c=="object"&&c!==null?c=Ce(c):(c=ae(n)?jt:te.current,c=hn(t,c));var p=n.getDerivedStateFromProps,m=typeof p=="function"||typeof i.getSnapshotBeforeUpdate=="function";m||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(u!==r||s!==c)&&Rs(t,i,r,c),it=!1;var h=t.memoizedState;i.state=h,gl(t,r,i,l),s=t.memoizedState,u!==r||h!==s||se.current||it?(typeof p=="function"&&(oi(t,n,p,r),s=t.memoizedState),(u=it||Ls(t,n,u,r,h,s,c))?(m||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount()),typeof i.componentDidMount=="function"&&(t.flags|=4194308)):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=s),i.props=r,i.state=s,i.context=c,r=u):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{i=t.stateNode,qa(e,t),u=t.memoizedProps,c=t.type===t.elementType?u:Te(t.type,u),i.props=c,m=t.pendingProps,h=i.context,s=n.contextType,typeof s=="object"&&s!==null?s=Ce(s):(s=ae(n)?jt:te.current,s=hn(t,s));var g=n.getDerivedStateFromProps;(p=typeof g=="function"||typeof i.getSnapshotBeforeUpdate=="function")||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(u!==m||h!==s)&&Rs(t,i,r,s),it=!1,h=t.memoizedState,i.state=h,gl(t,r,i,l);var w=t.memoizedState;u!==m||h!==w||se.current||it?(typeof g=="function"&&(oi(t,n,g,r),w=t.memoizedState),(c=it||Ls(t,n,c,r,h,w,s)||!1)?(p||typeof i.UNSAFE_componentWillUpdate!="function"&&typeof i.componentWillUpdate!="function"||(typeof i.componentWillUpdate=="function"&&i.componentWillUpdate(r,w,s),typeof i.UNSAFE_componentWillUpdate=="function"&&i.UNSAFE_componentWillUpdate(r,w,s)),typeof i.componentDidUpdate=="function"&&(t.flags|=4),typeof i.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof i.componentDidUpdate!="function"||u===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||u===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=w),i.props=r,i.state=w,i.context=s,r=c):(typeof i.componentDidUpdate!="function"||u===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||u===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),r=!1)}return ai(e,t,n,r,o,l)}function ai(e,t,n,r,l,o){Cc(e,t);var i=(t.flags&128)!==0;if(!r&&!i)return l&&xs(t,n,!1),Ze(e,t,o);r=t.stateNode,mp.current=t;var u=i&&typeof n.getDerivedStateFromError!="function"?null:r.render();return t.flags|=1,e!==null&&i?(t.child=yn(t,e.child,null,o),t.child=yn(t,null,u,o)):re(e,t,u,o),t.memoizedState=r.state,l&&xs(t,n,!0),t.child}function _c(e){var t=e.stateNode;t.pendingContext?Ss(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Ss(e,t.context,!1),Qi(e,t.containerInfo)}function Us(e,t,n,r,l){return vn(),Ai(l),t.flags|=256,re(e,t,n,r),t.child}var ci={dehydrated:null,treeContext:null,retryLane:0};function fi(e){return{baseLanes:e,cachePool:null,transitions:null}}function Nc(e,t,n){var r=t.pendingProps,l=F.current,o=!1,i=(t.flags&128)!==0,u;if((u=i)||(u=e!==null&&e.memoizedState===null?!1:(l&2)!==0),u?(o=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(l|=1),R(F,l&1),e===null)return ri(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?((t.mode&1)===0?t.lanes=1:e.data==="$!"?t.lanes=8:t.lanes=1073741824,null):(i=r.children,e=r.fallback,o?(r=t.mode,o=t.child,i={mode:"hidden",children:i},(r&1)===0&&o!==null?(o.childLanes=0,o.pendingProps=i):o=jl(i,r,0,null),e=Ft(e,r,n,null),o.return=t,e.return=t,o.sibling=e,t.child=o,t.child.memoizedState=fi(n),t.memoizedState=ci,e):bi(t,i));if(l=e.memoizedState,l!==null&&(u=l.dehydrated,u!==null))return hp(e,t,i,r,u,l,n);if(o){o=r.fallback,i=t.mode,l=e.child,u=l.sibling;var s={mode:"hidden",children:r.children};return(i&1)===0&&t.child!==l?(r=t.child,r.childLanes=0,r.pendingProps=s,t.deletions=null):(r=gt(l,s),r.subtreeFlags=l.subtreeFlags&14680064),u!==null?o=gt(u,o):(o=Ft(o,i,n,null),o.flags|=2),o.return=t,r.return=t,r.sibling=o,t.child=r,r=o,o=t.child,i=e.child.memoizedState,i=i===null?fi(n):{baseLanes:i.baseLanes|n,cachePool:null,transitions:i.transitions},o.memoizedState=i,o.childLanes=e.childLanes&~n,t.memoizedState=ci,r}return o=e.child,e=o.sibling,r=gt(o,{mode:"visible",children:r.children}),(t.mode&1)===0&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function bi(e,t){return t=jl({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function Wr(e,t,n,r){return r!==null&&Ai(r),yn(t,e.child,null,n),e=bi(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function hp(e,t,n,r,l,o,i){if(n)return t.flags&256?(t.flags&=-257,r=_o(Error(y(422))),Wr(e,t,i,r)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(o=r.fallback,l=t.mode,r=jl({mode:"visible",children:r.children},l,0,null),o=Ft(o,l,i,null),o.flags|=2,r.return=t,o.return=t,r.sibling=o,t.child=r,(t.mode&1)!==0&&yn(t,e.child,null,i),t.child.memoizedState=fi(i),t.memoizedState=ci,o);if((t.mode&1)===0)return Wr(e,t,i,null);if(l.data==="$!"){if(r=l.nextSibling&&l.nextSibling.dataset,r)var u=r.dgst;return r=u,o=Error(y(419)),r=_o(o,r,void 0),Wr(e,t,i,r)}if(u=(i&e.childLanes)!==0,ue||u){if(r=Y,r!==null){switch(i&-i){case 4:l=2;break;case 16:l=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:l=32;break;case 536870912:l=268435456;break;default:l=0}l=(l&(r.suspendedLanes|i))!==0?0:l,l!==0&&l!==o.retryLane&&(o.retryLane=l,Ge(e,l),De(r,e,l,-1))}return ou(),r=_o(Error(y(421))),Wr(e,t,i,r)}return l.data==="$?"?(t.flags|=128,t.child=e.child,t=zp.bind(null,e),l._reactRetry=t,null):(e=o.treeContext,pe=mt(l.nextSibling),me=t,M=!0,Re=null,e!==null&&(ke[Se++]=We,ke[Se++]=Qe,ke[Se++]=Ut,We=e.id,Qe=e.overflow,Ut=t),t=bi(t,r.children),t.flags|=4096,t)}function As(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),li(e.return,t,n)}function No(e,t,n,r,l){var o=e.memoizedState;o===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:l}:(o.isBackwards=t,o.rendering=null,o.renderingStartTime=0,o.last=r,o.tail=n,o.tailMode=l)}function Pc(e,t,n){var r=t.pendingProps,l=r.revealOrder,o=r.tail;if(re(e,t,r.children,n),r=F.current,(r&2)!==0)r=r&1|2,t.flags|=128;else{if(e!==null&&(e.flags&128)!==0)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&As(e,n,t);else if(e.tag===19)As(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(R(F,r),(t.mode&1)===0)t.memoizedState=null;else switch(l){case"forwards":for(n=t.child,l=null;n!==null;)e=n.alternate,e!==null&&wl(e)===null&&(l=n),n=n.sibling;n=l,n===null?(l=t.child,t.child=null):(l=n.sibling,n.sibling=null),No(t,!1,l,n,o);break;case"backwards":for(n=null,l=t.child,t.child=null;l!==null;){if(e=l.alternate,e!==null&&wl(e)===null){t.child=l;break}e=l.sibling,l.sibling=n,n=l,l=e}No(t,!0,n,null,o);break;case"together":No(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function br(e,t){(t.mode&1)===0&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Ze(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Vt|=t.lanes,(n&t.childLanes)===0)return null;if(e!==null&&t.child!==e.child)throw Error(y(153));if(t.child!==null){for(e=t.child,n=gt(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=gt(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function vp(e,t,n){switch(t.tag){case 3:_c(t),vn();break;case 5:ba(t);break;case 1:ae(t.type)&&pl(t);break;case 4:Qi(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,l=t.memoizedProps.value;R(vl,r._currentValue),r._currentValue=l;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated!==null?(R(F,F.current&1),t.flags|=128,null):(n&t.child.childLanes)!==0?Nc(e,t,n):(R(F,F.current&1),e=Ze(e,t,n),e!==null?e.sibling:null);R(F,F.current&1);break;case 19:if(r=(n&t.childLanes)!==0,(e.flags&128)!==0){if(r)return Pc(e,t,n);t.flags|=128}if(l=t.memoizedState,l!==null&&(l.rendering=null,l.tail=null,l.lastEffect=null),R(F,F.current),r)break;return null;case 22:case 23:return t.lanes=0,Ec(e,t,n)}return Ze(e,t,n)}var zc,di,Tc,Lc;zc=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};di=function(){};Tc=function(e,t,n,r){var l=e.memoizedProps;if(l!==r){e=t.stateNode,It(Ve.current);var o=null;switch(n){case"input":l=Io(e,l),r=Io(e,r),o=[];break;case"select":l=U({},l,{value:void 0}),r=U({},r,{value:void 0}),o=[];break;case"textarea":l=jo(e,l),r=jo(e,r),o=[];break;default:typeof l.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=fl)}Ao(n,r);var i;n=null;for(c in l)if(!r.hasOwnProperty(c)&&l.hasOwnProperty(c)&&l[c]!=null)if(c==="style"){var u=l[c];for(i in u)u.hasOwnProperty(i)&&(n||(n={}),n[i]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(Jn.hasOwnProperty(c)?o||(o=[]):(o=o||[]).push(c,null));for(c in r){var s=r[c];if(u=l?.[c],r.hasOwnProperty(c)&&s!==u&&(s!=null||u!=null))if(c==="style")if(u){for(i in u)!u.hasOwnProperty(i)||s&&s.hasOwnProperty(i)||(n||(n={}),n[i]="");for(i in s)s.hasOwnProperty(i)&&u[i]!==s[i]&&(n||(n={}),n[i]=s[i])}else n||(o||(o=[]),o.push(c,n)),n=s;else c==="dangerouslySetInnerHTML"?(s=s?s.__html:void 0,u=u?u.__html:void 0,s!=null&&u!==s&&(o=o||[]).push(c,s)):c==="children"?typeof s!="string"&&typeof s!="number"||(o=o||[]).push(c,""+s):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(Jn.hasOwnProperty(c)?(s!=null&&c==="onScroll"&&D("scroll",e),o||u===s||(o=[])):(o=o||[]).push(c,s))}n&&(o=o||[]).push("style",n);var c=o;(t.updateQueue=c)&&(t.flags|=4)}};Lc=function(e,t,n,r){n!==r&&(t.flags|=4)};function Mn(e,t){if(!M)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function b(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags&14680064,r|=l.flags&14680064,l.return=e,l=l.sibling;else for(l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function yp(e,t,n){var r=t.pendingProps;switch(Ui(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return b(t),null;case 1:return ae(t.type)&&dl(),b(t),null;case 3:return r=t.stateNode,gn(),I(se),I(te),Yi(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(Br(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&(t.flags&256)===0||(t.flags|=1024,Re!==null&&(ki(Re),Re=null))),di(e,t),b(t),null;case 5:Ki(t);var l=It(ar.current);if(n=t.type,e!==null&&t.stateNode!=null)Tc(e,t,n,r,l),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(y(166));return b(t),null}if(e=It(Ve.current),Br(t)){r=t.stateNode,n=t.type;var o=t.memoizedProps;switch(r[Ue]=t,r[ur]=o,e=(t.mode&1)!==0,n){case"dialog":D("cancel",r),D("close",r);break;case"iframe":case"object":case"embed":D("load",r);break;case"video":case"audio":for(l=0;l<$n.length;l++)D($n[l],r);break;case"source":D("error",r);break;case"img":case"image":case"link":D("error",r),D("load",r);break;case"details":D("toggle",r);break;case"input":Yu(r,o),D("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!o.multiple},D("invalid",r);break;case"textarea":Gu(r,o),D("invalid",r)}Ao(n,o),l=null;for(var i in o)if(o.hasOwnProperty(i)){var u=o[i];i==="children"?typeof u=="string"?r.textContent!==u&&(o.suppressHydrationWarning!==!0&&$r(r.textContent,u,e),l=["children",u]):typeof u=="number"&&r.textContent!==""+u&&(o.suppressHydrationWarning!==!0&&$r(r.textContent,u,e),l=["children",""+u]):Jn.hasOwnProperty(i)&&u!=null&&i==="onScroll"&&D("scroll",r)}switch(n){case"input":Tr(r),Xu(r,o,!0);break;case"textarea":Tr(r),Zu(r);break;case"select":case"option":break;default:typeof o.onClick=="function"&&(r.onclick=fl)}r=l,t.updateQueue=r,r!==null&&(t.flags|=4)}else{i=l.nodeType===9?l:l.ownerDocument,e==="http://www.w3.org/1999/xhtml"&&(e=la(n)),e==="http://www.w3.org/1999/xhtml"?n==="script"?(e=i.createElement("div"),e.innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(n,{is:r.is}):(e=i.createElement(n),n==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,n),e[Ue]=t,e[ur]=r,zc(e,t,!1,!1),t.stateNode=e;e:{switch(i=Vo(n,r),n){case"dialog":D("cancel",e),D("close",e),l=r;break;case"iframe":case"object":case"embed":D("load",e),l=r;break;case"video":case"audio":for(l=0;l<$n.length;l++)D($n[l],e);l=r;break;case"source":D("error",e),l=r;break;case"img":case"image":case"link":D("error",e),D("load",e),l=r;break;case"details":D("toggle",e),l=r;break;case"input":Yu(e,r),l=Io(e,r),D("invalid",e);break;case"option":l=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},l=U({},r,{value:void 0}),D("invalid",e);break;case"textarea":Gu(e,r),l=jo(e,r),D("invalid",e);break;default:l=r}Ao(n,l),u=l;for(o in u)if(u.hasOwnProperty(o)){var s=u[o];o==="style"?ua(e,s):o==="dangerouslySetInnerHTML"?(s=s?s.__html:void 0,s!=null&&oa(e,s)):o==="children"?typeof s=="string"?(n!=="textarea"||s!=="")&&qn(e,s):typeof s=="number"&&qn(e,""+s):o!=="suppressContentEditableWarning"&&o!=="suppressHydrationWarning"&&o!=="autoFocus"&&(Jn.hasOwnProperty(o)?s!=null&&o==="onScroll"&&D("scroll",e):s!=null&&Ei(e,o,s,i))}switch(n){case"input":Tr(e),Xu(e,r,!1);break;case"textarea":Tr(e),Zu(e);break;case"option":r.value!=null&&e.setAttribute("value",""+wt(r.value));break;case"select":e.multiple=!!r.multiple,o=r.value,o!=null?sn(e,!!r.multiple,o,!1):r.defaultValue!=null&&sn(e,!!r.multiple,r.defaultValue,!0);break;default:typeof l.onClick=="function"&&(e.onclick=fl)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return b(t),null;case 6:if(e&&t.stateNode!=null)Lc(e,t,e.memoizedProps,r);else{if(typeof r!="string"&&t.stateNode===null)throw Error(y(166));if(n=It(ar.current),It(Ve.current),Br(t)){if(r=t.stateNode,n=t.memoizedProps,r[Ue]=t,(o=r.nodeValue!==n)&&(e=me,e!==null))switch(e.tag){case 3:$r(r.nodeValue,n,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&$r(r.nodeValue,n,(e.mode&1)!==0)}o&&(t.flags|=4)}else r=(n.nodeType===9?n:n.ownerDocument).createTextNode(r),r[Ue]=t,t.stateNode=r}return b(t),null;case 13:if(I(F),r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(M&&pe!==null&&(t.mode&1)!==0&&(t.flags&128)===0)Xa(),vn(),t.flags|=98560,o=!1;else if(o=Br(t),r!==null&&r.dehydrated!==null){if(e===null){if(!o)throw Error(y(318));if(o=t.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(y(317));o[Ue]=t}else vn(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;b(t),o=!1}else Re!==null&&(ki(Re),Re=null),o=!0;if(!o)return t.flags&65536?t:null}return(t.flags&128)!==0?(t.lanes=n,t):(r=r!==null,r!==(e!==null&&e.memoizedState!==null)&&r&&(t.child.flags|=8192,(t.mode&1)!==0&&(e===null||(F.current&1)!==0?H===0&&(H=3):ou())),t.updateQueue!==null&&(t.flags|=4),b(t),null);case 4:return gn(),di(e,t),e===null&&or(t.stateNode.containerInfo),b(t),null;case 10:return Bi(t.type._context),b(t),null;case 17:return ae(t.type)&&dl(),b(t),null;case 19:if(I(F),o=t.memoizedState,o===null)return b(t),null;if(r=(t.flags&128)!==0,i=o.rendering,i===null)if(r)Mn(o,!1);else{if(H!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(i=wl(e),i!==null){for(t.flags|=128,Mn(o,!1),r=i.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),t.subtreeFlags=0,r=n,n=t.child;n!==null;)o=n,e=r,o.flags&=14680066,i=o.alternate,i===null?(o.childLanes=0,o.lanes=e,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=i.childLanes,o.lanes=i.lanes,o.child=i.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=i.memoizedProps,o.memoizedState=i.memoizedState,o.updateQueue=i.updateQueue,o.type=i.type,e=i.dependencies,o.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return R(F,F.current&1|2),t.child}e=e.sibling}o.tail!==null&&V()>kn&&(t.flags|=128,r=!0,Mn(o,!1),t.lanes=4194304)}else{if(!r)if(e=wl(i),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Mn(o,!0),o.tail===null&&o.tailMode==="hidden"&&!i.alternate&&!M)return b(t),null}else 2*V()-o.renderingStartTime>kn&&n!==1073741824&&(t.flags|=128,r=!0,Mn(o,!1),t.lanes=4194304);o.isBackwards?(i.sibling=t.child,t.child=i):(n=o.last,n!==null?n.sibling=i:t.child=i,o.last=i)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=V(),t.sibling=null,n=F.current,R(F,r?n&1|2:n&1),t):(b(t),null);case 22:case 23:return lu(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(de&1073741824)!==0&&(b(t),t.subtreeFlags&6&&(t.flags|=8192)):b(t),null;case 24:return null;case 25:return null}throw Error(y(156,t.tag))}function gp(e,t){switch(Ui(t),t.tag){case 1:return ae(t.type)&&dl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return gn(),I(se),I(te),Yi(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return Ki(t),null;case 13:if(I(F),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(y(340));vn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return I(F),null;case 4:return gn(),null;case 10:return Bi(t.type._context),null;case 22:case 23:return lu(),null;case 24:return null;default:return null}}var Qr=!1,ee=!1,wp=typeof WeakSet=="function"?WeakSet:Set,k=null;function on(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){A(e,t,r)}else n.current=null}function pi(e,t,n){try{n()}catch(r){A(e,t,r)}}var Vs=!1;function kp(e,t){if(Zo=sl,e=Ma(),Fi(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var i=0,u=-1,s=-1,c=0,p=0,m=e,h=null;t:for(;;){for(var g;m!==n||l!==0&&m.nodeType!==3||(u=i+l),m!==o||r!==0&&m.nodeType!==3||(s=i+r),m.nodeType===3&&(i+=m.nodeValue.length),(g=m.firstChild)!==null;)h=m,m=g;for(;;){if(m===e)break t;if(h===n&&++c===l&&(u=i),h===o&&++p===r&&(s=i),(g=m.nextSibling)!==null)break;m=h,h=m.parentNode}m=g}n=u===-1||s===-1?null:{start:u,end:s}}else n=null}n=n||{start:0,end:0}}else n=null;for(Jo={focusedElem:e,selectionRange:n},sl=!1,k=t;k!==null;)if(t=k,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,k=e;else for(;k!==null;){t=k;try{var w=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var S=w.memoizedProps,O=w.memoizedState,d=t.stateNode,a=d.getSnapshotBeforeUpdate(t.elementType===t.type?S:Te(t.type,S),O);d.__reactInternalSnapshotBeforeUpdate=a}break;case 3:var f=t.stateNode.containerInfo;f.nodeType===1?f.textContent="":f.nodeType===9&&f.documentElement&&f.removeChild(f.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(y(163))}}catch(v){A(t,t.return,v)}if(e=t.sibling,e!==null){e.return=t.return,k=e;break}k=t.return}return w=Vs,Vs=!1,w}function Xn(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var o=l.destroy;l.destroy=void 0,o!==void 0&&pi(t,n,o)}l=l.next}while(l!==r)}}function Ml(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function mi(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Rc(e){var t=e.alternate;t!==null&&(e.alternate=null,Rc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Ue],delete t[ur],delete t[ei],delete t[np],delete t[rp])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Oc(e){return e.tag===5||e.tag===3||e.tag===4}function $s(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Oc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function hi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=fl));else if(r!==4&&(e=e.child,e!==null))for(hi(e,t,n),e=e.sibling;e!==null;)hi(e,t,n),e=e.sibling}function vi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(vi(e,t,n),e=e.sibling;e!==null;)vi(e,t,n),e=e.sibling}var X=null,Le=!1;function lt(e,t,n){for(n=n.child;n!==null;)Dc(e,t,n),n=n.sibling}function Dc(e,t,n){if(Ae&&typeof Ae.onCommitFiberUnmount=="function")try{Ae.onCommitFiberUnmount(Pl,n)}catch{}switch(n.tag){case 5:ee||on(n,t);case 6:var r=X,l=Le;X=null,lt(e,t,n),X=r,Le=l,X!==null&&(Le?(e=X,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):X.removeChild(n.stateNode));break;case 18:X!==null&&(Le?(e=X,n=n.stateNode,e.nodeType===8?wo(e.parentNode,n):e.nodeType===1&&wo(e,n),nr(e)):wo(X,n.stateNode));break;case 4:r=X,l=Le,X=n.stateNode.containerInfo,Le=!0,lt(e,t,n),X=r,Le=l;break;case 0:case 11:case 14:case 15:if(!ee&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var o=l,i=o.destroy;o=o.tag,i!==void 0&&((o&2)!==0||(o&4)!==0)&&pi(n,t,i),l=l.next}while(l!==r)}lt(e,t,n);break;case 1:if(!ee&&(on(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){A(n,t,u)}lt(e,t,n);break;case 21:lt(e,t,n);break;case 22:n.mode&1?(ee=(r=ee)||n.memoizedState!==null,lt(e,t,n),ee=r):lt(e,t,n);break;default:lt(e,t,n)}}function Bs(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new wp),t.forEach(function(r){var l=Tp.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function ze(e,t){var n=t.deletions;if(n!==null)for(var r=0;r<n.length;r++){var l=n[r];try{var o=e,i=t,u=i;e:for(;u!==null;){switch(u.tag){case 5:X=u.stateNode,Le=!1;break e;case 3:X=u.stateNode.containerInfo,Le=!0;break e;case 4:X=u.stateNode.containerInfo,Le=!0;break e}u=u.return}if(X===null)throw Error(y(160));Dc(o,i,l),X=null,Le=!1;var s=l.alternate;s!==null&&(s.return=null),l.return=null}catch(c){A(l,t,c)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)Ic(t,e),t=t.sibling}function Ic(e,t){var n=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(ze(t,e),Fe(e),r&4){try{Xn(3,e,e.return),Ml(3,e)}catch(S){A(e,e.return,S)}try{Xn(5,e,e.return)}catch(S){A(e,e.return,S)}}break;case 1:ze(t,e),Fe(e),r&512&&n!==null&&on(n,n.return);break;case 5:if(ze(t,e),Fe(e),r&512&&n!==null&&on(n,n.return),e.flags&32){var l=e.stateNode;try{qn(l,"")}catch(S){A(e,e.return,S)}}if(r&4&&(l=e.stateNode,l!=null)){var o=e.memoizedProps,i=n!==null?n.memoizedProps:o,u=e.type,s=e.updateQueue;if(e.updateQueue=null,s!==null)try{u==="input"&&o.type==="radio"&&o.name!=null&&na(l,o),Vo(u,i);var c=Vo(u,o);for(i=0;i<s.length;i+=2){var p=s[i],m=s[i+1];p==="style"?ua(l,m):p==="dangerouslySetInnerHTML"?oa(l,m):p==="children"?qn(l,m):Ei(l,p,m,c)}switch(u){case"input":Mo(l,o);break;case"textarea":ra(l,o);break;case"select":var h=l._wrapperState.wasMultiple;l._wrapperState.wasMultiple=!!o.multiple;var g=o.value;g!=null?sn(l,!!o.multiple,g,!1):h!==!!o.multiple&&(o.defaultValue!=null?sn(l,!!o.multiple,o.defaultValue,!0):sn(l,!!o.multiple,o.multiple?[]:"",!1))}l[ur]=o}catch(S){A(e,e.return,S)}}break;case 6:if(ze(t,e),Fe(e),r&4){if(e.stateNode===null)throw Error(y(162));l=e.stateNode,o=e.memoizedProps;try{l.nodeValue=o}catch(S){A(e,e.return,S)}}break;case 3:if(ze(t,e),Fe(e),r&4&&n!==null&&n.memoizedState.isDehydrated)try{nr(t.containerInfo)}catch(S){A(e,e.return,S)}break;case 4:ze(t,e),Fe(e);break;case 13:ze(t,e),Fe(e),l=e.child,l.flags&8192&&(o=l.memoizedState!==null,l.stateNode.isHidden=o,!o||l.alternate!==null&&l.alternate.memoizedState!==null||(nu=V())),r&4&&Bs(e);break;case 22:if(p=n!==null&&n.memoizedState!==null,e.mode&1?(ee=(c=ee)||p,ze(t,e),ee=c):ze(t,e),Fe(e),r&8192){if(c=e.memoizedState!==null,(e.stateNode.isHidden=c)&&!p&&(e.mode&1)!==0)for(k=e,p=e.child;p!==null;){for(m=k=p;k!==null;){switch(h=k,g=h.child,h.tag){case 0:case 11:case 14:case 15:Xn(4,h,h.return);break;case 1:on(h,h.return);var w=h.stateNode;if(typeof w.componentWillUnmount=="function"){r=h,n=h.return;try{t=r,w.props=t.memoizedProps,w.state=t.memoizedState,w.componentWillUnmount()}catch(S){A(r,n,S)}}break;case 5:on(h,h.return);break;case 22:if(h.memoizedState!==null){Ws(m);continue}}g!==null?(g.return=h,k=g):Ws(m)}p=p.sibling}e:for(p=null,m=e;;){if(m.tag===5){if(p===null){p=m;try{l=m.stateNode,c?(o=l.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none"):(u=m.stateNode,s=m.memoizedProps.style,i=s!=null&&s.hasOwnProperty("display")?s.display:null,u.style.display=ia("display",i))}catch(S){A(e,e.return,S)}}}else if(m.tag===6){if(p===null)try{m.stateNode.nodeValue=c?"":m.memoizedProps}catch(S){A(e,e.return,S)}}else if((m.tag!==22&&m.tag!==23||m.memoizedState===null||m===e)&&m.child!==null){m.child.return=m,m=m.child;continue}if(m===e)break e;for(;m.sibling===null;){if(m.return===null||m.return===e)break e;p===m&&(p=null),m=m.return}p===m&&(p=null),m.sibling.return=m.return,m=m.sibling}}break;case 19:ze(t,e),Fe(e),r&4&&Bs(e);break;case 21:break;default:ze(t,e),Fe(e)}}function Fe(e){var t=e.flags;if(t&2){try{e:{for(var n=e.return;n!==null;){if(Oc(n)){var r=n;break e}n=n.return}throw Error(y(160))}switch(r.tag){case 5:var l=r.stateNode;r.flags&32&&(qn(l,""),r.flags&=-33);var o=$s(e);vi(e,o,l);break;case 3:case 4:var i=r.stateNode.containerInfo,u=$s(e);hi(e,u,i);break;default:throw Error(y(161))}}catch(s){A(e,e.return,s)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function Sp(e,t,n){k=e,Mc(e,t,n)}function Mc(e,t,n){for(var r=(e.mode&1)!==0;k!==null;){var l=k,o=l.child;if(l.tag===22&&r){var i=l.memoizedState!==null||Qr;if(!i){var u=l.alternate,s=u!==null&&u.memoizedState!==null||ee;u=Qr;var c=ee;if(Qr=i,(ee=s)&&!c)for(k=l;k!==null;)i=k,s=i.child,i.tag===22&&i.memoizedState!==null?Qs(l):s!==null?(s.return=i,k=s):Qs(l);for(;o!==null;)k=o,Mc(o,t,n),o=o.sibling;k=l,Qr=u,ee=c}Hs(e,t,n)}else(l.subtreeFlags&8772)!==0&&o!==null?(o.return=l,k=o):Hs(e,t,n)}}function Hs(e){for(;k!==null;){var t=k;if((t.flags&8772)!==0){var n=t.alternate;try{if((t.flags&8772)!==0)switch(t.tag){case 0:case 11:case 15:ee||Ml(5,t);break;case 1:var r=t.stateNode;if(t.flags&4&&!ee)if(n===null)r.componentDidMount();else{var l=t.elementType===t.type?n.memoizedProps:Te(t.type,n.memoizedProps);r.componentDidUpdate(l,n.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var o=t.updateQueue;o!==null&&Ps(t,o,r);break;case 3:var i=t.updateQueue;if(i!==null){if(n=null,t.child!==null)switch(t.child.tag){case 5:n=t.child.stateNode;break;case 1:n=t.child.stateNode}Ps(t,i,n)}break;case 5:var u=t.stateNode;if(n===null&&t.flags&4){n=u;var s=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":s.autoFocus&&n.focus();break;case"img":s.src&&(n.src=s.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(t.memoizedState===null){var c=t.alternate;if(c!==null){var p=c.memoizedState;if(p!==null){var m=p.dehydrated;m!==null&&nr(m)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(y(163))}ee||t.flags&512&&mi(t)}catch(h){A(t,t.return,h)}}if(t===e){k=null;break}if(n=t.sibling,n!==null){n.return=t.return,k=n;break}k=t.return}}function Ws(e){for(;k!==null;){var t=k;if(t===e){k=null;break}var n=t.sibling;if(n!==null){n.return=t.return,k=n;break}k=t.return}}function Qs(e){for(;k!==null;){var t=k;try{switch(t.tag){case 0:case 11:case 15:var n=t.return;try{Ml(4,t)}catch(s){A(t,n,s)}break;case 1:var r=t.stateNode;if(typeof r.componentDidMount=="function"){var l=t.return;try{r.componentDidMount()}catch(s){A(t,l,s)}}var o=t.return;try{mi(t)}catch(s){A(t,o,s)}break;case 5:var i=t.return;try{mi(t)}catch(s){A(t,i,s)}}}catch(s){A(t,t.return,s)}if(t===e){k=null;break}var u=t.sibling;if(u!==null){u.return=t.return,k=u;break}k=t.return}}var xp=Math.ceil,xl=Je.ReactCurrentDispatcher,eu=Je.ReactCurrentOwner,Ee=Je.ReactCurrentBatchConfig,P=0,Y=null,$=null,G=0,de=0,un=xt(0),H=0,pr=null,Vt=0,Fl=0,tu=0,Gn=null,ie=null,nu=0,kn=1/0,Be=null,El=!1,yi=null,vt=null,Kr=!1,ct=null,Cl=0,Zn=0,gi=null,el=-1,tl=0;function le(){return(P&6)!==0?V():el!==-1?el:el=V()}function yt(e){return(e.mode&1)===0?1:(P&2)!==0&&G!==0?G&-G:op.transition!==null?(tl===0&&(tl=wa()),tl):(e=T,e!==0||(e=window.event,e=e===void 0?16:Na(e.type)),e)}function De(e,t,n,r){if(50<Zn)throw Zn=0,gi=null,Error(y(185));mr(e,n,r),((P&2)===0||e!==Y)&&(e===Y&&((P&2)===0&&(Fl|=n),H===4&&st(e,G)),ce(e,r),n===1&&P===0&&(t.mode&1)===0&&(kn=V()+500,Ol&&Et()))}function ce(e,t){var n=e.callbackNode;ud(e,t);var r=ul(e,e===Y?G:0);if(r===0)n!==null&&bu(n),e.callbackNode=null,e.callbackPriority=0;else if(t=r&-r,e.callbackPriority!==t){if(n!=null&&bu(n),t===1)e.tag===0?lp(Ks.bind(null,e)):Qa(Ks.bind(null,e)),ep(function(){(P&6)===0&&Et()}),n=null;else{switch(ka(r)){case 1:n=zi;break;case 4:n=ya;break;case 16:n=il;break;case 536870912:n=ga;break;default:n=il}n=Hc(n,Fc.bind(null,e))}e.callbackPriority=t,e.callbackNode=n}}function Fc(e,t){if(el=-1,tl=0,(P&6)!==0)throw Error(y(327));var n=e.callbackNode;if(pn()&&e.callbackNode!==n)return null;var r=ul(e,e===Y?G:0);if(r===0)return null;if((r&30)!==0||(r&e.expiredLanes)!==0||t)t=_l(e,r);else{t=r;var l=P;P|=2;var o=Uc();(Y!==e||G!==t)&&(Be=null,kn=V()+500,Mt(e,t));do try{_p();break}catch(u){jc(e,u)}while(!0);$i(),xl.current=o,P=l,$!==null?t=0:(Y=null,G=0,t=H)}if(t!==0){if(t===2&&(l=Qo(e),l!==0&&(r=l,t=wi(e,l))),t===1)throw n=pr,Mt(e,0),st(e,r),ce(e,V()),n;if(t===6)st(e,r);else{if(l=e.current.alternate,(r&30)===0&&!Ep(l)&&(t=_l(e,r),t===2&&(o=Qo(e),o!==0&&(r=o,t=wi(e,o))),t===1))throw n=pr,Mt(e,0),st(e,r),ce(e,V()),n;switch(e.finishedWork=l,e.finishedLanes=r,t){case 0:case 1:throw Error(y(345));case 2:Rt(e,ie,Be);break;case 3:if(st(e,r),(r&130023424)===r&&(t=nu+500-V(),10<t)){if(ul(e,0)!==0)break;if(l=e.suspendedLanes,(l&r)!==r){le(),e.pingedLanes|=e.suspendedLanes&l;break}e.timeoutHandle=bo(Rt.bind(null,e,ie,Be),t);break}Rt(e,ie,Be);break;case 4:if(st(e,r),(r&4194240)===r)break;for(t=e.eventTimes,l=-1;0<r;){var i=31-Oe(r);o=1<<i,i=t[i],i>l&&(l=i),r&=~o}if(r=l,r=V()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*xp(r/1960))-r,10<r){e.timeoutHandle=bo(Rt.bind(null,e,ie,Be),r);break}Rt(e,ie,Be);break;case 5:Rt(e,ie,Be);break;default:throw Error(y(329))}}}return ce(e,V()),e.callbackNode===n?Fc.bind(null,e):null}function wi(e,t){var n=Gn;return e.current.memoizedState.isDehydrated&&(Mt(e,t).flags|=256),e=_l(e,t),e!==2&&(t=ie,ie=n,t!==null&&ki(t)),e}function ki(e){ie===null?ie=e:ie.push.apply(ie,e)}function Ep(e){for(var t=e;;){if(t.flags&16384){var n=t.updateQueue;if(n!==null&&(n=n.stores,n!==null))for(var r=0;r<n.length;r++){var l=n[r],o=l.getSnapshot;l=l.value;try{if(!Ie(o(),l))return!1}catch{return!1}}}if(n=t.child,t.subtreeFlags&16384&&n!==null)n.return=t,t=n;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function st(e,t){for(t&=~tu,t&=~Fl,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-Oe(t),r=1<<n;e[n]=-1,t&=~r}}function Ks(e){if((P&6)!==0)throw Error(y(327));pn();var t=ul(e,0);if((t&1)===0)return ce(e,V()),null;var n=_l(e,t);if(e.tag!==0&&n===2){var r=Qo(e);r!==0&&(t=r,n=wi(e,r))}if(n===1)throw n=pr,Mt(e,0),st(e,t),ce(e,V()),n;if(n===6)throw Error(y(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Rt(e,ie,Be),ce(e,V()),null}function ru(e,t){var n=P;P|=1;try{return e(t)}finally{P=n,P===0&&(kn=V()+500,Ol&&Et())}}function $t(e){ct!==null&&ct.tag===0&&(P&6)===0&&pn();var t=P;P|=1;var n=Ee.transition,r=T;try{if(Ee.transition=null,T=1,e)return e()}finally{T=r,Ee.transition=n,P=t,(P&6)===0&&Et()}}function lu(){de=un.current,I(un)}function Mt(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;if(n!==-1&&(e.timeoutHandle=-1,bd(n)),$!==null)for(n=$.return;n!==null;){var r=n;switch(Ui(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&dl();break;case 3:gn(),I(se),I(te),Yi();break;case 5:Ki(r);break;case 4:gn();break;case 13:I(F);break;case 19:I(F);break;case 10:Bi(r.type._context);break;case 22:case 23:lu()}n=n.return}if(Y=e,$=e=gt(e.current,null),G=de=t,H=0,pr=null,tu=Fl=Vt=0,ie=Gn=null,Dt!==null){for(t=0;t<Dt.length;t++)if(n=Dt[t],r=n.interleaved,r!==null){n.interleaved=null;var l=r.next,o=n.pending;if(o!==null){var i=o.next;o.next=l,r.next=i}n.pending=r}Dt=null}return e}function jc(e,t){do{var n=$;try{if($i(),Jr.current=Sl,kl){for(var r=j.memoizedState;r!==null;){var l=r.queue;l!==null&&(l.pending=null),r=r.next}kl=!1}if(At=0,K=B=j=null,Yn=!1,cr=0,eu.current=null,n===null||n.return===null){H=1,pr=t,$=null;break}e:{var o=e,i=n.return,u=n,s=t;if(t=G,u.flags|=32768,s!==null&&typeof s=="object"&&typeof s.then=="function"){var c=s,p=u,m=p.tag;if((p.mode&1)===0&&(m===0||m===11||m===15)){var h=p.alternate;h?(p.updateQueue=h.updateQueue,p.memoizedState=h.memoizedState,p.lanes=h.lanes):(p.updateQueue=null,p.memoizedState=null)}var g=Ds(i);if(g!==null){g.flags&=-257,Is(g,i,u,o,t),g.mode&1&&Os(o,c,t),t=g,s=c;var w=t.updateQueue;if(w===null){var S=new Set;S.add(s),t.updateQueue=S}else w.add(s);break e}else{if((t&1)===0){Os(o,c,t),ou();break e}s=Error(y(426))}}else if(M&&u.mode&1){var O=Ds(i);if(O!==null){(O.flags&65536)===0&&(O.flags|=256),Is(O,i,u,o,t),Ai(wn(s,u));break e}}o=s=wn(s,u),H!==4&&(H=2),Gn===null?Gn=[o]:Gn.push(o),o=i;do{switch(o.tag){case 3:o.flags|=65536,t&=-t,o.lanes|=t;var d=kc(o,s,t);Ns(o,d);break e;case 1:u=s;var a=o.type,f=o.stateNode;if((o.flags&128)===0&&(typeof a.getDerivedStateFromError=="function"||f!==null&&typeof f.componentDidCatch=="function"&&(vt===null||!vt.has(f)))){o.flags|=65536,t&=-t,o.lanes|=t;var v=Sc(o,u,t);Ns(o,v);break e}}o=o.return}while(o!==null)}Vc(n)}catch(x){t=x,$===n&&n!==null&&($=n=n.return);continue}break}while(!0)}function Uc(){var e=xl.current;return xl.current=Sl,e===null?Sl:e}function ou(){(H===0||H===3||H===2)&&(H=4),Y===null||(Vt&268435455)===0&&(Fl&268435455)===0||st(Y,G)}function _l(e,t){var n=P;P|=2;var r=Uc();(Y!==e||G!==t)&&(Be=null,Mt(e,t));do try{Cp();break}catch(l){jc(e,l)}while(!0);if($i(),P=n,xl.current=r,$!==null)throw Error(y(261));return Y=null,G=0,H}function Cp(){for(;$!==null;)Ac($)}function _p(){for(;$!==null&&!qf();)Ac($)}function Ac(e){var t=Bc(e.alternate,e,de);e.memoizedProps=e.pendingProps,t===null?Vc(e):$=t,eu.current=null}function Vc(e){var t=e;do{var n=t.alternate;if(e=t.return,(t.flags&32768)===0){if(n=yp(n,t,de),n!==null){$=n;return}}else{if(n=gp(n,t),n!==null){n.flags&=32767,$=n;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{H=6,$=null;return}}if(t=t.sibling,t!==null){$=t;return}$=t=e}while(t!==null);H===0&&(H=5)}function Rt(e,t,n){var r=T,l=Ee.transition;try{Ee.transition=null,T=1,Np(e,t,n,r)}finally{Ee.transition=l,T=r}return null}function Np(e,t,n,r){do pn();while(ct!==null);if((P&6)!==0)throw Error(y(327));n=e.finishedWork;var l=e.finishedLanes;if(n===null)return null;if(e.finishedWork=null,e.finishedLanes=0,n===e.current)throw Error(y(177));e.callbackNode=null,e.callbackPriority=0;var o=n.lanes|n.childLanes;if(sd(e,o),e===Y&&($=Y=null,G=0),(n.subtreeFlags&2064)===0&&(n.flags&2064)===0||Kr||(Kr=!0,Hc(il,function(){return pn(),null})),o=(n.flags&15990)!==0,(n.subtreeFlags&15990)!==0||o){o=Ee.transition,Ee.transition=null;var i=T;T=1;var u=P;P|=4,eu.current=null,kp(e,n),Ic(n,e),Xd(Jo),sl=!!Zo,Jo=Zo=null,e.current=n,Sp(n,e,l),bf(),P=u,T=i,Ee.transition=o}else e.current=n;if(Kr&&(Kr=!1,ct=e,Cl=l),o=e.pendingLanes,o===0&&(vt=null),nd(n.stateNode,r),ce(e,V()),t!==null)for(r=e.onRecoverableError,n=0;n<t.length;n++)l=t[n],r(l.value,{componentStack:l.stack,digest:l.digest});if(El)throw El=!1,e=yi,yi=null,e;return(Cl&1)!==0&&e.tag!==0&&pn(),o=e.pendingLanes,(o&1)!==0?e===gi?Zn++:(Zn=0,gi=e):Zn=0,Et(),null}function pn(){if(ct!==null){var e=ka(Cl),t=Ee.transition,n=T;try{if(Ee.transition=null,T=16>e?16:e,ct===null)var r=!1;else{if(e=ct,ct=null,Cl=0,(P&6)!==0)throw Error(y(331));var l=P;for(P|=4,k=e.current;k!==null;){var o=k,i=o.child;if((k.flags&16)!==0){var u=o.deletions;if(u!==null){for(var s=0;s<u.length;s++){var c=u[s];for(k=c;k!==null;){var p=k;switch(p.tag){case 0:case 11:case 15:Xn(8,p,o)}var m=p.child;if(m!==null)m.return=p,k=m;else for(;k!==null;){p=k;var h=p.sibling,g=p.return;if(Rc(p),p===c){k=null;break}if(h!==null){h.return=g,k=h;break}k=g}}}var w=o.alternate;if(w!==null){var S=w.child;if(S!==null){w.child=null;do{var O=S.sibling;S.sibling=null,S=O}while(S!==null)}}k=o}}if((o.subtreeFlags&2064)!==0&&i!==null)i.return=o,k=i;else e:for(;k!==null;){if(o=k,(o.flags&2048)!==0)switch(o.tag){case 0:case 11:case 15:Xn(9,o,o.return)}var d=o.sibling;if(d!==null){d.return=o.return,k=d;break e}k=o.return}}var a=e.current;for(k=a;k!==null;){i=k;var f=i.child;if((i.subtreeFlags&2064)!==0&&f!==null)f.return=i,k=f;else e:for(i=a;k!==null;){if(u=k,(u.flags&2048)!==0)try{switch(u.tag){case 0:case 11:case 15:Ml(9,u)}}catch(x){A(u,u.return,x)}if(u===i){k=null;break e}var v=u.sibling;if(v!==null){v.return=u.return,k=v;break e}k=u.return}}if(P=l,Et(),Ae&&typeof Ae.onPostCommitFiberRoot=="function")try{Ae.onPostCommitFiberRoot(Pl,e)}catch{}r=!0}return r}finally{T=n,Ee.transition=t}}return!1}function Ys(e,t,n){t=wn(n,t),t=kc(e,t,1),e=ht(e,t,1),t=le(),e!==null&&(mr(e,1,t),ce(e,t))}function A(e,t,n){if(e.tag===3)Ys(e,e,n);else for(;t!==null;){if(t.tag===3){Ys(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(vt===null||!vt.has(r))){e=wn(n,e),e=Sc(t,e,1),t=ht(t,e,1),e=le(),t!==null&&(mr(t,1,e),ce(t,e));break}}t=t.return}}function Pp(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),t=le(),e.pingedLanes|=e.suspendedLanes&n,Y===e&&(G&n)===n&&(H===4||H===3&&(G&130023424)===G&&500>V()-nu?Mt(e,0):tu|=n),ce(e,t)}function $c(e,t){t===0&&((e.mode&1)===0?t=1:(t=Or,Or<<=1,(Or&130023424)===0&&(Or=4194304)));var n=le();e=Ge(e,t),e!==null&&(mr(e,t,n),ce(e,n))}function zp(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$c(e,n)}function Tp(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(y(314))}r!==null&&r.delete(t),$c(e,n)}var Bc;Bc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||se.current)ue=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return ue=!1,vp(e,t,n);ue=(e.flags&131072)!==0}else ue=!1,M&&(t.flags&1048576)!==0&&Ka(t,hl,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;br(e,t),e=t.pendingProps;var l=hn(t,te.current);dn(t,n),l=Gi(null,t,r,e,l,n);var o=Zi();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ae(r)?(o=!0,pl(t)):o=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Wi(t),l.updater=Il,t.stateNode=l,l._reactInternals=t,ii(t,r,e,n),t=ai(null,t,r,!0,o,n)):(t.tag=0,M&&o&&ji(t),re(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(br(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Rp(r),e=Te(r,e),l){case 0:t=si(null,t,r,e,n);break e;case 1:t=js(null,t,r,e,n);break e;case 11:t=Ms(null,t,r,e,n);break e;case 14:t=Fs(null,t,r,Te(r.type,e),n);break e}throw Error(y(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Te(r,l),si(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Te(r,l),js(e,t,r,l,n);case 3:e:{if(_c(t),e===null)throw Error(y(387));r=t.pendingProps,o=t.memoizedState,l=o.element,qa(e,t),gl(t,r,null,n);var i=t.memoizedState;if(r=i.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){l=wn(Error(y(423)),t),t=Us(e,t,r,n,l);break e}else if(r!==l){l=wn(Error(y(424)),t),t=Us(e,t,r,n,l);break e}else for(pe=mt(t.stateNode.containerInfo.firstChild),me=t,M=!0,Re=null,n=Za(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(vn(),r===l){t=Ze(e,t,n);break e}re(e,t,r,n)}t=t.child}return t;case 5:return ba(t),e===null&&ri(t),r=t.type,l=t.pendingProps,o=e!==null?e.memoizedProps:null,i=l.children,qo(r,l)?i=null:o!==null&&qo(r,o)&&(t.flags|=32),Cc(e,t),re(e,t,i,n),t.child;case 6:return e===null&&ri(t),null;case 13:return Nc(e,t,n);case 4:return Qi(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=yn(t,null,r,n):re(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Te(r,l),Ms(e,t,r,l,n);case 7:return re(e,t,t.pendingProps,n),t.child;case 8:return re(e,t,t.pendingProps.children,n),t.child;case 12:return re(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,o=t.memoizedProps,i=l.value,R(vl,r._currentValue),r._currentValue=i,o!==null)if(Ie(o.value,i)){if(o.children===l.children&&!se.current){t=Ze(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var u=o.dependencies;if(u!==null){i=o.child;for(var s=u.firstContext;s!==null;){if(s.context===r){if(o.tag===1){s=Ke(-1,n&-n),s.tag=2;var c=o.updateQueue;if(c!==null){c=c.shared;var p=c.pending;p===null?s.next=s:(s.next=p.next,p.next=s),c.pending=s}}o.lanes|=n,s=o.alternate,s!==null&&(s.lanes|=n),li(o.return,n,t),u.lanes|=n;break}s=s.next}}else if(o.tag===10)i=o.type===t.type?null:o.child;else if(o.tag===18){if(i=o.return,i===null)throw Error(y(341));i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),li(i,n,t),i=o.sibling}else i=o.child;if(i!==null)i.return=o;else for(i=o;i!==null;){if(i===t){i=null;break}if(o=i.sibling,o!==null){o.return=i.return,i=o;break}i=i.return}o=i}re(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,dn(t,n),l=Ce(l),r=r(l),t.flags|=1,re(e,t,r,n),t.child;case 14:return r=t.type,l=Te(r,t.pendingProps),l=Te(r.type,l),Fs(e,t,r,l,n);case 15:return xc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Te(r,l),br(e,t),t.tag=1,ae(r)?(e=!0,pl(t)):e=!1,dn(t,n),wc(t,r,l),ii(t,r,l,n),ai(null,t,r,!0,e,n);case 19:return Pc(e,t,n);case 22:return Ec(e,t,n)}throw Error(y(156,t.tag))};function Hc(e,t){return va(e,t)}function Lp(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function xe(e,t,n,r){return new Lp(e,t,n,r)}function iu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Rp(e){if(typeof e=="function")return iu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===_i)return 11;if(e===Ni)return 14}return 2}function gt(e,t){var n=e.alternate;return n===null?(n=xe(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function nl(e,t,n,r,l,o){var i=2;if(r=e,typeof e=="function")iu(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case Zt:return Ft(n.children,l,o,t);case Ci:i=8,l|=8;break;case Lo:return e=xe(12,n,t,l|2),e.elementType=Lo,e.lanes=o,e;case Ro:return e=xe(13,n,t,l),e.elementType=Ro,e.lanes=o,e;case Oo:return e=xe(19,n,t,l),e.elementType=Oo,e.lanes=o,e;case bs:return jl(n,l,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Js:i=10;break e;case qs:i=9;break e;case _i:i=11;break e;case Ni:i=14;break e;case ot:i=16,r=null;break e}throw Error(y(130,e==null?e:typeof e,""))}return t=xe(i,n,t,l),t.elementType=e,t.type=r,t.lanes=o,t}function Ft(e,t,n,r){return e=xe(7,e,r,t),e.lanes=n,e}function jl(e,t,n,r){return e=xe(22,e,r,t),e.elementType=bs,e.lanes=n,e.stateNode={isHidden:!1},e}function Po(e,t,n){return e=xe(6,e,null,t),e.lanes=n,e}function zo(e,t,n){return t=xe(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Op(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=co(0),this.expirationTimes=co(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=co(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function uu(e,t,n,r,l,o,i,u,s){return e=new Op(e,t,n,u,s),t===1?(t=1,o===!0&&(t|=8)):t=0,o=xe(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Wi(o),e}function Dp(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Gt,key:r==null?null:""+r,children:e,containerInfo:t,implementation:n}}function Wc(e){if(!e)return kt;e=e._reactInternals;e:{if(Ht(e)!==e||e.tag!==1)throw Error(y(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(ae(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(t!==null);throw Error(y(171))}if(e.tag===1){var n=e.type;if(ae(n))return Wa(e,n,t)}return t}function Qc(e,t,n,r,l,o,i,u,s){return e=uu(n,r,!0,e,l,o,i,u,s),e.context=Wc(null),n=e.current,r=le(),l=yt(n),o=Ke(r,l),o.callback=t??null,ht(n,o,l),e.current.lanes=l,mr(e,l,r),ce(e,r),e}function Ul(e,t,n,r){var l=t.current,o=le(),i=yt(l);return n=Wc(n),t.context===null?t.context=n:t.pendingContext=n,t=Ke(o,i),t.payload={element:e},r=r===void 0?null:r,r!==null&&(t.callback=r),e=ht(l,t,i),e!==null&&(De(e,l,i,o),Zr(e,l,i)),i}function Nl(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function Xs(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var n=e.retryLane;e.retryLane=n!==0&&n<t?n:t}}function su(e,t){Xs(e,t),(e=e.alternate)&&Xs(e,t)}function Ip(){return null}var Kc=typeof reportError=="function"?reportError:function(e){console.error(e)};function au(e){this._internalRoot=e}Al.prototype.render=au.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(y(409));Ul(e,t,null,null)};Al.prototype.unmount=au.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;$t(function(){Ul(null,e,null,null)}),t[Xe]=null}};function Al(e){this._internalRoot=e}Al.prototype.unstable_scheduleHydration=function(e){if(e){var t=Ea();e={blockedOn:null,target:e,priority:t};for(var n=0;n<ut.length&&t!==0&&t<ut[n].priority;n++);ut.splice(n,0,e),n===0&&_a(e)}};function cu(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function Vl(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==" react-mount-point-unstable "))}function Gs(){}function Mp(e,t,n,r,l){if(l){if(typeof r=="function"){var o=r;r=function(){var c=Nl(i);o.call(c)}}var i=Qc(t,r,e,0,null,!1,!1,"",Gs);return e._reactRootContainer=i,e[Xe]=i.current,or(e.nodeType===8?e.parentNode:e),$t(),i}for(;l=e.lastChild;)e.removeChild(l);if(typeof r=="function"){var u=r;r=function(){var c=Nl(s);u.call(c)}}var s=uu(e,0,!1,null,null,!1,!1,"",Gs);return e._reactRootContainer=s,e[Xe]=s.current,or(e.nodeType===8?e.parentNode:e),$t(function(){Ul(t,s,n,r)}),s}function $l(e,t,n,r,l){var o=n._reactRootContainer;if(o){var i=o;if(typeof l=="function"){var u=l;l=function(){var s=Nl(i);u.call(s)}}Ul(t,i,e,l)}else i=Mp(n,t,e,l,r);return Nl(i)}Sa=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var n=Vn(t.pendingLanes);n!==0&&(Ti(t,n|1),ce(t,V()),(P&6)===0&&(kn=V()+500,Et()))}break;case 13:$t(function(){var r=Ge(e,1);if(r!==null){var l=le();De(r,e,1,l)}}),su(e,1)}};Li=function(e){if(e.tag===13){var t=Ge(e,134217728);if(t!==null){var n=le();De(t,e,134217728,n)}su(e,134217728)}};xa=function(e){if(e.tag===13){var t=yt(e),n=Ge(e,t);if(n!==null){var r=le();De(n,e,t,r)}su(e,t)}};Ea=function(){return T};Ca=function(e,t){var n=T;try{return T=e,t()}finally{T=n}};Bo=function(e,t,n){switch(t){case"input":if(Mo(e,n),t=n.name,n.type==="radio"&&t!=null){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var l=Rl(r);if(!l)throw Error(y(90));ta(r),Mo(r,l)}}}break;case"textarea":ra(e,n);break;case"select":t=n.value,t!=null&&sn(e,!!n.multiple,t,!1)}};ca=ru;fa=$t;var Fp={usingClientEntryPoint:!1,Events:[vr,en,Rl,sa,aa,ru]},Fn={findFiberByHostInstance:Ot,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},jp={bundleType:Fn.bundleType,version:Fn.version,rendererPackageName:Fn.rendererPackageName,rendererConfig:Fn.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Je.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=ma(e),e===null?null:e.stateNode},findFiberByHostInstance:Fn.findFiberByHostInstance||Ip,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&(jn=__REACT_DEVTOOLS_GLOBAL_HOOK__,!jn.isDisabled&&jn.supportsFiber))try{Pl=jn.inject(jp),Ae=jn}catch{}var jn;ye.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Fp;ye.createPortal=function(e,t){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!cu(t))throw Error(y(200));return Dp(e,t,null,n)};ye.createRoot=function(e,t){if(!cu(e))throw Error(y(299));var n=!1,r="",l=Kc;return t!=null&&(t.unstable_strictMode===!0&&(n=!0),t.identifierPrefix!==void 0&&(r=t.identifierPrefix),t.onRecoverableError!==void 0&&(l=t.onRecoverableError)),t=uu(e,1,!1,null,null,n,!1,r,l),e[Xe]=t.current,or(e.nodeType===8?e.parentNode:e),new au(t)};ye.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(y(188)):(e=Object.keys(e).join(","),Error(y(268,e)));return e=ma(t),e=e===null?null:e.stateNode,e};ye.flushSync=function(e){return $t(e)};ye.hydrate=function(e,t,n){if(!Vl(t))throw Error(y(200));return $l(null,e,t,!0,n)};ye.hydrateRoot=function(e,t,n){if(!cu(e))throw Error(y(405));var r=n!=null&&n.hydratedSources||null,l=!1,o="",i=Kc;if(n!=null&&(n.unstable_strictMode===!0&&(l=!0),n.identifierPrefix!==void 0&&(o=n.identifierPrefix),n.onRecoverableError!==void 0&&(i=n.onRecoverableError)),t=Qc(t,null,e,1,n??null,l,!1,o,i),e[Xe]=t.current,or(e),r)for(e=0;e<r.length;e++)n=r[e],l=n._getVersion,l=l(n._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[n,l]:t.mutableSourceEagerHydrationData.push(n,l);return new Al(t)};ye.render=function(e,t,n){if(!Vl(t))throw Error(y(200));return $l(null,e,t,!1,n)};ye.unmountComponentAtNode=function(e){if(!Vl(e))throw Error(y(40));return e._reactRootContainer?($t(function(){$l(null,null,e,!1,function(){e._reactRootContainer=null,e[Xe]=null})}),!0):!1};ye.unstable_batchedUpdates=ru;ye.unstable_renderSubtreeIntoContainer=function(e,t,n,r){if(!Vl(n))throw Error(y(200));if(e==null||e._reactInternals===void 0)throw Error(y(38));return $l(e,t,n,!1,r)};ye.version="18.3.1-next-f1338f8080-20240426"});var fu=zt((Om,Gc)=>{"use strict";function Xc(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Xc)}catch(e){console.error(e)}}Xc(),Gc.exports=Yc()});var Jc=zt(du=>{"use strict";var Zc=fu();du.createRoot=Zc.createRoot,du.hydrateRoot=Zc.hydrateRoot;var Dm});var Nt=tt(nt()),cf=tt(Jc()),ff=tt(fu());var Cn=tt(nt(),1),Ne=tt(nt(),1),be=tt(nt(),1);var Up={data:""},Ap=e=>{if(typeof window=="object"){let t=(e?e.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return t.nonce=window.__nonce__,t.parentNode||(e||document.head).appendChild(t),t.firstChild}return e||Up};var Vp=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,$p=/\/\*[^]*?\*\/| +/g,qc=/\n+/g,Ct=(e,t)=>{let n="",r="",l="";for(let o in e){let i=e[o];o[0]=="@"?o[1]=="i"?n=o+" "+i+";":r+=o[1]=="f"?Ct(i,o):o+"{"+Ct(i,o[1]=="k"?"":t)+"}":typeof i=="object"?r+=Ct(i,t?t.replace(/([^,])+/g,u=>o.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,s=>/&/.test(s)?s.replace(/&/g,u):u?u+" "+s:s)):o):i!=null&&(o=/^--/.test(o)?o:o.replace(/[A-Z]/g,"-$&").toLowerCase(),l+=Ct.p?Ct.p(o,i):o+":"+i+";")}return n+(t&&l?t+"{"+l+"}":l)+r},qe={},bc=e=>{if(typeof e=="object"){let t="";for(let n in e)t+=n+bc(e[n]);return t}return e},Bp=(e,t,n,r,l)=>{let o=bc(e),i=qe[o]||(qe[o]=(s=>{let c=0,p=11;for(;c<s.length;)p=101*p+s.charCodeAt(c++)>>>0;return"go"+p})(o));if(!qe[i]){let s=o!==e?e:(c=>{let p,m,h=[{}];for(;p=Vp.exec(c.replace($p,""));)p[4]?h.shift():p[3]?(m=p[3].replace(qc," ").trim(),h.unshift(h[0][m]=h[0][m]||{})):h[0][p[1]]=p[2].replace(qc," ").trim();return h[0]})(e);qe[i]=Ct(l?{["@keyframes "+i]:s}:s,n?"":"."+i)}let u=n&&qe.g?qe.g:null;return n&&(qe.g=qe[i]),((s,c,p,m)=>{m?c.data=c.data.replace(m,s):c.data.indexOf(s)===-1&&(c.data=p?s+c.data:c.data+s)})(qe[i],t,r,u),i},Hp=(e,t,n)=>e.reduce((r,l,o)=>{let i=t[o];if(i&&i.call){let u=i(n),s=u&&u.props&&u.props.className||/^go/.test(u)&&u;i=s?"."+s:u&&typeof u=="object"?u.props?"":Ct(u,""):u===!1?"":u}return r+l+(i??"")},"");function En(e){let t=this||{},n=e.call?e(t.p):e;return Bp(n.unshift?n.raw?Hp(n,[].slice.call(arguments,1),t.p):n.reduce((r,l)=>Object.assign(r,l&&l.call?l(t.p):l),{}):n,Ap(t.target),t.g,t.o,t.k)}var ef,pu,mu,Mm=En.bind({g:1}),Fm=En.bind({k:1});function hu(e,t,n,r){Ct.p=t,ef=e,pu=n,mu=r}function tf(e,t){let n=this||{};return function(){let r=arguments;function l(o,i){let u=Object.assign({},o),s=u.className||l.className;n.p=Object.assign({theme:pu&&pu()},u),n.o=/ *go\d+/.test(s),u.className=En.apply(n,r)+(s?" "+s:""),t&&(u.ref=i);let c=e;return e[0]&&(c=u.as||e,delete u.as),mu&&c[0]&&mu(u),ef(c,u)}return t?t(l):l}}var Wt=document.createElement("div");Wt.hidden=!0;Wt.id="wbs-toast-library-styles";var nf=En.bind({target:Wt}),fe=En.bind({target:Wt,k:1}),ge=tf.bind({target:Wt});var Qt=tt(nt(),1);var _t=tt(nt(),1),Wp=e=>typeof e=="function",Wl=(e,t)=>Wp(e)?e(t):e,Qp=(()=>{let e=0;return()=>(++e).toString()})(),rf=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})(),Kp=20,vu="default",lf=(e,t)=>{let{toastLimit:n}=e.settings;switch(t.type){case 0:return{...e,toasts:[t.toast,...e.toasts].slice(0,n)};case 1:return{...e,toasts:e.toasts.map(i=>i.id===t.toast.id?{...i,...t.toast}:i)};case 2:let{toast:r}=t;return lf(e,{type:e.toasts.find(i=>i.id===r.id)?1:0,toast:r});case 3:let{toastId:l}=t;return{...e,toasts:e.toasts.map(i=>i.id===l||l===void 0?{...i,dismissed:!0,visible:!1}:i)};case 4:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(i=>i.id!==t.toastId)};case 5:return{...e,pausedAt:t.time};case 6:let o=t.time-(e.pausedAt||0);return{...e,pausedAt:void 0,toasts:e.toasts.map(i=>({...i,pauseDuration:i.pauseDuration+o}))}}},Hl=[],of={toasts:[],pausedAt:void 0,settings:{toastLimit:Kp}},$e={},uf=(e,t=vu)=>{$e[t]=lf($e[t]||of,e),Hl.forEach(([n,r])=>{n===t&&r($e[t])})},sf=e=>Object.keys($e).forEach(t=>uf(e,t)),Yp=e=>Object.keys($e).find(t=>$e[t].toasts.some(n=>n.id===e)),Ql=(e=vu)=>t=>{uf(t,e)},Xp={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},Gp=(e={},t=vu)=>{let[n,r]=(0,Cn.useState)($e[t]||of),l=(0,Cn.useRef)($e[t]);(0,Cn.useEffect)(()=>(l.current!==$e[t]&&r($e[t]),Hl.push([t,r]),()=>{let i=Hl.findIndex(([u])=>u===t);i>-1&&Hl.splice(i,1)}),[t]);let o=n.toasts.map(i=>{var u,s,c;return{...e,...e[i.type],...i,removeDelay:i.removeDelay||((u=e[i.type])==null?void 0:u.removeDelay)||e?.removeDelay,duration:i.duration||((s=e[i.type])==null?void 0:s.duration)||e?.duration||Xp[i.type],style:{...e.style,...(c=e[i.type])==null?void 0:c.style,...i.style}}});return{...n,toasts:o}},Zp=(e,t="blank",n)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:t,ariaProps:{role:"status","aria-live":"polite"},message:e,pauseDuration:0,...n,id:n?.id||Qp()}),gr=e=>(t,n)=>{let r=Zp(t,e,n);return Ql(r.toasterId||Yp(r.id))({type:2,toast:r}),r.id},W=(e,t)=>gr("blank")(e,t);W.error=gr("error");W.success=gr("success");W.loading=gr("loading");W.custom=gr("custom");W.dismiss=(e,t)=>{let n={type:3,toastId:e};t?Ql(t)(n):sf(n)};W.dismissAll=e=>W.dismiss(void 0,e);W.remove=(e,t)=>{let n={type:4,toastId:e};t?Ql(t)(n):sf(n)};W.removeAll=e=>W.remove(void 0,e);W.promise=(e,t,n)=>{let r=W.loading(t.loading,{...n,...n?.loading});return typeof e=="function"&&(e=e()),e.then(l=>{let o=t.success?Wl(t.success,l):void 0;return o?W.success(o,{id:r,...n,...n?.success}):W.dismiss(r),l}).catch(l=>{let o=t.error?Wl(t.error,l):void 0;o?W.error(o,{id:r,...n,...n?.error}):W.dismiss(r)}),e};var Jp=1e3,qp=(e,t="default")=>{let{toasts:n,pausedAt:r}=Gp(e,t),l=(0,Ne.useRef)(new Map).current,o=(0,Ne.useCallback)((m,h=Jp)=>{if(l.has(m))return;let g=setTimeout(()=>{l.delete(m),i({type:4,toastId:m})},h);l.set(m,g)},[]);(0,Ne.useEffect)(()=>{if(r)return;let m=Date.now(),h=n.map(g=>{if(g.duration===1/0)return;let w=(g.duration||0)+g.pauseDuration-(m-g.createdAt);if(w<0){g.visible&&W.dismiss(g.id);return}return setTimeout(()=>W.dismiss(g.id,t),w)});return()=>{h.forEach(g=>g&&clearTimeout(g))}},[n,r,t]);let i=(0,Ne.useCallback)(Ql(t),[t]),u=(0,Ne.useCallback)(()=>{i({type:5,time:Date.now()})},[i]),s=(0,Ne.useCallback)((m,h)=>{i({type:1,toast:{id:m,height:h}})},[i]),c=(0,Ne.useCallback)(()=>{r&&i({type:6,time:Date.now()})},[r,i]),p=(0,Ne.useCallback)((m,h)=>{let{reverseOrder:g=!1,gutter:w=8,defaultPosition:S}=h||{},O=n.filter(f=>(f.position||S)===(m.position||S)&&f.height),d=O.findIndex(f=>f.id===m.id),a=O.filter((f,v)=>v<d&&f.visible).length;return O.filter(f=>f.visible).slice(...g?[a+1]:[0,a]).reduce((f,v)=>f+(v.height||0)+w,0)},[n]);return(0,Ne.useEffect)(()=>{n.forEach(m=>{if(m.dismissed)o(m.id,m.removeDelay);else{let h=l.get(m.id);h&&(clearTimeout(h),l.delete(m.id))}})},[n,o]),{toasts:n,handlers:{updateHeight:s,startPause:u,endPause:c,calculateOffset:p}}},bp=fe`
+from {
+ transform: scale(0) rotate(45deg);
+ opacity: 0;
+}
+to {
+ transform: scale(1) rotate(45deg);
+ opacity: 1;
+}`,em=fe`
+from {
+ transform: scale(0);
+ opacity: 0;
+}
+to {
+ transform: scale(1);
+ opacity: 1;
+}`,tm=fe`
+from {
+ transform: scale(0) rotate(90deg);
+ opacity: 0;
+}
+to {
+ transform: scale(1) rotate(90deg);
+ opacity: 1;
+}`,nm=ge("div")`
+ width: 20px;
+ opacity: 0;
+ height: 20px;
+ border-radius: 10px;
+ background: ${e=>e.primary||"#ff4b4b"};
+ position: relative;
+ transform: rotate(45deg);
+
+ animation: ${bp} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
+ forwards;
+ animation-delay: 100ms;
+
+ &:after,
+ &:before {
+ content: '';
+ animation: ${em} 0.15s ease-out forwards;
+ animation-delay: 150ms;
+ position: absolute;
+ border-radius: 3px;
+ opacity: 0;
+ background: ${e=>e.secondary||"#fff"};
+ bottom: 9px;
+ left: 4px;
+ height: 2px;
+ width: 12px;
+ }
+
+ &:before {
+ animation: ${tm} 0.15s ease-out forwards;
+ animation-delay: 180ms;
+ transform: rotate(90deg);
+ }
+`,rm=fe`
+ from {
+ transform: rotate(0deg);
+ }
+ to {
+ transform: rotate(360deg);
+ }
+`,lm=ge("div")`
+ width: 12px;
+ height: 12px;
+ box-sizing: border-box;
+ border: 2px solid;
+ border-radius: 100%;
+ border-color: ${e=>e.secondary||"#e0e0e0"};
+ border-right-color: ${e=>e.primary||"#616161"};
+ animation: ${rm} 1s linear infinite;
+`,om=fe`
+from {
+ transform: scale(0) rotate(45deg);
+ opacity: 0;
+}
+to {
+ transform: scale(1) rotate(45deg);
+ opacity: 1;
+}`,im=fe`
+0% {
+ height: 0;
+ width: 0;
+ opacity: 0;
+}
+40% {
+ height: 0;
+ width: 6px;
+ opacity: 1;
+}
+100% {
+ opacity: 1;
+ height: 10px;
+}`,um=ge("div")`
+ width: 20px;
+ opacity: 0;
+ height: 20px;
+ border-radius: 10px;
+ background: ${e=>e.primary||"#61d345"};
+ position: relative;
+ transform: rotate(45deg);
+
+ animation: ${om} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
+ forwards;
+ animation-delay: 100ms;
+ &:after {
+ content: '';
+ box-sizing: border-box;
+ animation: ${im} 0.2s ease-out forwards;
+ opacity: 0;
+ animation-delay: 200ms;
+ position: absolute;
+ border-right: 2px solid;
+ border-bottom: 2px solid;
+ border-color: ${e=>e.secondary||"#fff"};
+ bottom: 6px;
+ left: 6px;
+ height: 10px;
+ width: 6px;
+ }
+`,sm=ge("div")`
+ position: absolute;
+`,am=ge("div")`
+ position: relative;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ min-width: 20px;
+ min-height: 20px;
+`,cm=fe`
+from {
+ transform: scale(0.6);
+ opacity: 0.4;
+}
+to {
+ transform: scale(1);
+ opacity: 1;
+}`,fm=ge("div")`
+ position: relative;
+ transform: scale(0.6);
+ opacity: 0.4;
+ min-width: 20px;
+ animation: ${cm} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275)
+ forwards;
+`,dm=({toast:e})=>{let{icon:t,type:n,iconTheme:r}=e;return t!==void 0?typeof t=="string"?Qt.createElement(fm,null,t):t:n==="blank"?null:Qt.createElement(am,null,Qt.createElement(lm,{...r}),n!=="loading"&&Qt.createElement(sm,null,n==="error"?Qt.createElement(nm,{...r}):Qt.createElement(um,{...r})))},pm=e=>`
+0% {transform: translate3d(0,${e*-200}%,0) scale(.6); opacity:.5;}
+100% {transform: translate3d(0,0,0) scale(1); opacity:1;}
+`,mm=e=>`
+0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;}
+100% {transform: translate3d(0,${e*-150}%,-1px) scale(.6); opacity:0;}
+`,hm="0%{opacity:0;} 100%{opacity:1;}",vm="0%{opacity:1;} 100%{opacity:0;}",ym=ge("div")`
+ display: flex;
+ align-items: center;
+ background: #fff;
+ color: #363636;
+ line-height: 1.3;
+ will-change: transform;
+ box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05);
+ max-width: 350px;
+ pointer-events: auto;
+ padding: 8px 10px;
+ border-radius: 8px;
+`,gm=ge("div")`
+ display: flex;
+ justify-content: center;
+ margin: 4px 10px;
+ color: inherit;
+ flex: 1 1 auto;
+ white-space: pre-line;
+`,wm=(e,t)=>{let n=e.includes("top")?1:-1,[r,l]=rf()?[hm,vm]:[pm(n),mm(n)];return{animation:t?`${fe(r)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${fe(l)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},yu=be.memo(({toast:e,position:t,style:n,children:r})=>{let l=e.height?wm(e.position||t||"top-center",e.visible):{opacity:0},o=be.createElement(dm,{toast:e}),i=be.createElement(gm,{...e.ariaProps},Wl(e.message,e));return be.createElement(ym,{className:e.className,style:{...l,...n,...e.style}},typeof r=="function"?r({icon:o,message:i}):be.createElement(be.Fragment,null,o,i))});hu(_t.createElement);var km=({id:e,className:t,style:n,onHeightUpdate:r,children:l})=>{let o=_t.useCallback(i=>{if(i){let u=()=>{let s=i.getBoundingClientRect().height;r(e,s)};u(),new MutationObserver(u).observe(i,{subtree:!0,childList:!0,characterData:!0})}},[e,r]);return _t.createElement("div",{ref:o,className:t,style:n},l)},Sm=(e,t)=>{let n=e.includes("top"),r=n?{top:0}:{bottom:0},l=e.includes("center")?{justifyContent:"center"}:e.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:rf()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${t*(n?1:-1)}px)`,...r,...l}},xm=nf`
+ z-index: 9999;
+ > * {
+ pointer-events: auto;
+ }
+`,Bl=16,af=({reverseOrder:e,position:t="top-center",toastOptions:n,gutter:r,children:l,toasterId:o,containerStyle:i,containerClassName:u})=>{let{toasts:s,handlers:c}=qp(n,o);return _t.createElement("div",{"data-rht-toaster":o||"",style:{position:"fixed",zIndex:9999,top:Bl,left:Bl,right:Bl,bottom:Bl,pointerEvents:"none",...i},className:u,onMouseEnter:c.startPause,onMouseLeave:c.endPause},s.map(p=>{let m=p.position||t,h=c.calculateOffset(p,{reverseOrder:e,gutter:r,defaultPosition:t}),g=Sm(m,h);return _t.createElement(km,{id:p.id,key:p.id,onHeightUpdate:c.updateHeight,className:p.visible?xm:"",style:g},p.type==="custom"?Wl(p.message,p):l?l(p):_t.createElement(yu,{toast:p,position:m}))}))},_n=W;var Pt,wr,Em="var(--wb-color-text-primary,#1f1f1f)";function df(){if(Pt?.isConnected)return;pf(),Pt=document.createElement("div"),Pt.id="wbs-toast-root",Pt.style.cssText="position:fixed;inset:0;z-index:2147483647;pointer-events:none;";let e=Pt.attachShadow({mode:"open"}),t=document.createElement("style");t.textContent=':host{font:12px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:var(--wb-color-text-primary,#1f1f1f)}*{box-sizing:border-box}.wbs-hot-message{white-space:pre-wrap;overflow-wrap:anywhere;min-width:0;max-height:min(35vh,200px);overflow:auto}.wbs-hot-close{width:22px;height:22px;flex:0 0 22px;border:0;border-radius:6px;background:transparent;color:var(--wb-color-text-secondary,#666);font:18px/1 sans-serif;cursor:pointer;margin-left:4px}.wbs-hot-close:hover{background:var(--wb-bg-hover,#eee)}.wbs-hot-close:focus-visible{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:1px}',e.append(t,Wt);let n=document.createElement("div");e.appendChild(n);for(let r of["click","pointerdown","pointerup","keydown","keyup"])e.addEventListener(r,l=>l.stopPropagation());document.body.appendChild(Pt),wr=(0,cf.createRoot)(n),(0,ff.flushSync)(()=>wr.render(Nt.default.createElement(af,{position:"bottom-center",gutter:8,containerStyle:{bottom:24,top:16,left:16,right:16},toastOptions:{duration:4200,removeDelay:250,style:{fontSize:12,lineHeight:1.5,maxWidth:"min(440px,calc(100vw - 32px))",padding:"9px 12px",borderRadius:10,background:"var(--wb-bg-popover,var(--wb-bg-secondary,#fff))",color:Em,border:"1px solid var(--wb-border-default,#e6e6e6)",boxShadow:"0 6px 24px rgb(0 0 0 / 14%)"}}},r=>Nt.default.createElement(yu,{toast:r},({icon:l,message:o})=>Nt.default.createElement(Nt.default.Fragment,null,l,Nt.default.createElement("div",{className:"wbs-hot-message"},o),Nt.default.createElement("button",{className:"wbs-hot-close","aria-label":"Dismiss notification",title:"\u5173\u95ED / Close",onClick:()=>_n.dismiss(r.id)},"\xD7"))))))}function Cm(e={}){df();let t=["info","success","warning","error","loading"].includes(e.level)?e.level:"info",n=String(e.message??"").slice(0,2e3),r={id:e.id||void 0,position:"bottom-center",duration:Number.isFinite(e.duration)?Math.min(6e4,Math.max(1e3,e.duration)):t==="loading"?1/0:4200,ariaProps:{role:t==="error"?"alert":"status","aria-live":t==="error"?"assertive":"polite"}};return t==="warning"&&(r.icon=Nt.default.createElement("span",{"aria-hidden":"true",style:{color:"var(--wb-accent-orange,#b96b00)",fontWeight:700,fontSize:16}},"!")),(_n[t]||_n)(n,r)}function _m(e){_n.dismiss(e)}function pf(){_n.remove(),wr&&(wr.unmount(),wr=null),Pt?.remove(),Pt=null}window.__wbsToastRuntime={mount:df,show:Cm,dismiss:_m,destroy:pf,version:"[email protected]"};})();
+/*! Bundled license information:
+
+react/cjs/react.production.min.js:
+ (**
+ * @license React
+ * react.production.min.js
+ *
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *)
+
+scheduler/cjs/scheduler.production.min.js:
+ (**
+ * @license React
+ * scheduler.production.min.js
+ *
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *)
+
+react-dom/cjs/react-dom.production.min.js:
+ (**
+ * @license React
+ * react-dom.production.min.js
+ *
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *)
+*/
+
+/* Third-party licenses:
+react
+MIT License
+
+Copyright (c) Facebook, Inc. and its affiliates.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
+react-dom
+MIT License
+
+Copyright (c) Facebook, Inc. and its affiliates.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
+scheduler
+MIT License
+
+Copyright (c) Facebook, Inc. and its affiliates.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
+react-hot-toast
+MIT License
+
+Copyright (c) 2020 Timo Lins
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+goober
+MIT License
+
+Copyright (c) 2019 Cristian Bote
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+*/
diff --git a/test/account-list-stability.test.js b/test/account-list-stability.test.js
new file mode 100644
index 0000000..86ceae5
--- /dev/null
+++ b/test/account-list-stability.test.js
@@ -0,0 +1,146 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
+const section = (start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start)));
+const tick = () => new Promise(resolve => setImmediate(resolve));
+const account = (uid, expiry) => ({ uid, nickname: uid, credits: 10, creditSegments: [{ remaining: 10, expiresAt: expiry }] });
+
+function harness() {
+ const requests = [];
+ function el(tag, className) {
+ return {
+ className, children: [], attrs: {}, dataset: {}, classList: { toggle() {}, add() {}, remove() {} },
+ setAttribute(k, v) { this.attrs[k] = v; }, getAttribute(k) { return this.attrs[k]; },
+ appendChild(child) { this.children = this.children.filter(value => value !== child); this.children.push(child); },
+ insertBefore(child) { this.appendChild(child); },
+ querySelector(selector) { return selector === '.wbs-acct-list' ? this.children.find(c => c.className === 'wbs-acct-list') : null; },
+ querySelectorAll(selector) { return selector === '.wbs-card' ? this.children.filter(c => c.className.startsWith('wbs-card')) : []; },
+ set innerHTML(value) { this.children = []; this.html = value; }, get innerHTML() { return this.html || ''; },
+ };
+ }
+ const pane = el('div', 'pane');
+ const ctx = vm.createContext({
+ window: {},
+ state: { accounts: [], current: null, open: true, creditRunId: 0, activityRunId: 0, creditRemaining: 0 },
+ alive: true, CAPS: { accounts: true }, accountsPane: pane, panel: el(), fab: el(), fabQuietMode: { wake() {} },
+ api(route, options) { return new Promise((resolve, reject) => requests.push({ route, options, resolve, reject })); },
+ el, esc: String, escAttr: String, tokenState: () => ({ label: '-' }), isIdentityExpired: a => !!a.identityExpired,
+ checkinBadgeHtml: () => '', creditBlockHtml: () => '', applyAccountMask() {}, updateAccountSummary() {},
+ updateCheckinCells() {}, updateCreditCell() {}, fetchActivityForAccounts() {}, toast() {}, root: {},
+ PRIMARY_ACCOUNT_SVG: '', SWITCH_SVG: '', TRASH_SVG: '',
+ setBuildTimeout: fn => fn(), setTimeout: () => 1, clearTimeout() {},
+ checkForUpdate() {}, acCheckPromptOnOpen() {}, syncSessionModule() {},
+ });
+ vm.runInContext([
+ section(' function isKnownActivityStreak(', ' function el(tag'),
+ section(' function nearestCreditExpiry(', ' function pollAutoCopyJob('),
+ section(' function render(data)', ' function maskAccountName('),
+ section(' function refresh()', ' function updateAccountSummary('),
+ section(' function fetchCreditsForAccounts()', ' function updateCreditCell('),
+ section(' function setOpen(', ' function setupFabDrag('),
+ ].join('\n'), ctx);
+ return { ctx, requests, pane, order: () => Array.from(ctx.state.accounts, a => a.uid), cards: () => pane.querySelector('.wbs-acct-list').children.slice() };
+}
+
+test('metadata refresh retains cached credits, sorted order and the actual buttons/cards', () => {
+ const h = harness();
+ h.ctx.render({ accounts: [account('later', 200), account('soon', 100)] });
+ const before = h.cards();
+ h.ctx.render({ accounts: [{ uid: 'later', nickname: 'later' }, { uid: 'soon', nickname: 'soon' }] });
+ assert.deepEqual(h.order(), ['soon', 'later']);
+ assert.equal(h.ctx.state.accounts[0].credits, 10);
+ assert.equal(h.cards()[0], before[0]);
+});
+
+test('credit responses never move a visible account; next opening applies expiry order', async () => {
+ const h = harness();
+ h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
+ const before = h.cards();
+ h.ctx.fetchCreditsForAccounts();
+ await tick();
+ h.requests.find(r => JSON.parse(r.options.body).uid === 'b').resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 50 }] });
+ h.requests.find(r => JSON.parse(r.options.body).uid === 'a').resolve({ credits: 10, segments: [{ remaining: 10, expiresAt: 300 }] });
+ await tick();
+ assert.deepEqual(h.order(), ['a', 'b']);
+ assert.deepEqual(h.cards(), before);
+ h.ctx.setOpen(false);
+ h.ctx.setOpen(true, { automation: true });
+ assert.deepEqual(h.order(), ['b', 'a']);
+ assert.equal(h.cards()[0], before[1]);
+});
+
+test('older overlapping account responses cannot restore stale accounts', async () => {
+ const h = harness();
+ h.ctx.refresh(); h.ctx.refresh();
+ h.requests[1].resolve({ accounts: [account('new', 100)] }); await tick();
+ h.requests[0].resolve({ accounts: [account('old', 100)] }); await tick();
+ assert.deepEqual(h.order(), ['new']);
+});
+
+test('temporary credit failures retain the cached value but expired identity clears it', async () => {
+ const h = harness();
+ h.ctx.render({ accounts: [account('network', 100), account('expired', 200)] });
+ h.ctx.fetchCreditsForAccounts(); await tick();
+ h.requests[0].reject(new Error('temporary network failure'));
+ h.requests[1].reject({ payload: { expired: true } }); await tick();
+ assert.equal(h.ctx.state.accounts.find(a => a.uid === 'network').credits, 10);
+ assert.equal(h.ctx.state.accounts.find(a => a.uid === 'expired').credits, null);
+ assert.equal(h.ctx.state.accounts.find(a => a.uid === 'expired').creditExpired, true);
+});
+
+test('account refresh errors retain the cached list', async () => {
+ const h = harness(); h.ctx.render({ accounts: [account('a', 100)] });
+ const before = h.cards()[0];
+ h.ctx.refresh(); h.requests[0].reject(new Error('offline')); await tick();
+ assert.ok(h.pane.querySelector('.wbs-acct-list'));
+ assert.equal(h.cards()[0], before);
+});
+
+test('deleted accounts stay removed and new accounts append without moving survivors', () => {
+ const h = harness(); h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
+ h.ctx.render({ accounts: [account('new', 1), { uid: 'b', nickname: 'b' }] });
+ assert.deepEqual(h.order(), ['b', 'new']);
+});
+
+test('closing the panel invalidates pending account responses', async () => {
+ const h = harness(); h.ctx.render({ accounts: [account('cached', 100)] });
+ const before = h.cards()[0];
+ h.ctx.refresh(); h.ctx.setOpen(false);
+ h.requests[0].resolve({ accounts: [account('stale', 10)] }); await tick();
+ assert.deepEqual(h.order(), ['cached']);
+ assert.equal(h.cards()[0], before);
+});
+
+test('account refresh after re-opening keeps the newly sorted card nodes', async () => {
+ const h = harness(); h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
+ h.ctx.state.accounts[1].creditSegments = [{ remaining: 10, expiresAt: 50 }];
+ h.ctx.setOpen(false); h.ctx.setOpen(true, { automation: true });
+ const before = h.cards();
+ h.requests[0].resolve({ accounts: [{ uid: 'a', nickname: 'a' }, { uid: 'b', nickname: 'b' }] }); await tick();
+ assert.deepEqual(h.order(), ['b', 'a']);
+ assert.equal(h.cards()[0], before[0]);
+ assert.equal(h.cards()[1], before[1]);
+});
+
+test('fresh current-account and identity changes update card controls', () => {
+ const h = harness(); h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
+ const before = h.cards();
+ h.ctx.render({ current: { uid: 'b' }, accounts: [{ ...account('a', 100), identityExpired: true }, account('b', 200)] });
+ assert.deepEqual(h.order(), ['a', 'b']);
+ assert.notEqual(h.cards()[0], before[0]);
+ assert.equal(h.cards()[1].className, 'wbs-card cur');
+});
+
+test('account metadata refresh retains valid activity days while the server cache is missing or failed', () => {
+ const h = harness();
+ h.ctx.render({ accounts: [{ ...account('a', 100), activityStreak: { days: 5, status: 'ready' } }] });
+ for (const activityStreak of [null, { days: null, status: 'unavailable' }]) {
+ h.ctx.render({ accounts: [{ uid: 'a', nickname: 'a', activityStreak }] });
+ assert.equal(h.ctx.state.accounts[0].activityStreak.days, 5);
+ }
+ h.ctx.render({ accounts: [{ uid: 'a', nickname: 'a', activityStreak: { days: 0, status: 'ready' } }] });
+ assert.equal(h.ctx.state.accounts[0].activityStreak.days, 0);
+});
diff --git a/test/account-sort.test.js b/test/account-sort.test.js
index f200563..2c679c2 100644
--- a/test/account-sort.test.js
+++ b/test/account-sort.test.js
@@ -21,5 +21,6 @@ test('account list sorts by credit expiry without pinning the current account',
const renderStart = inject.indexOf('function render(data)');
const renderBody = inject.slice(renderStart, inject.indexOf('state.creditRemaining', renderStart));
assert.ok(renderBody.indexOf('leftIsCurrent ? -1 : 1') === -1, 'render must not pin current account');
- assert.match(renderBody, /nearestCreditExpiry\(left\)/, 'render must order by credit expiry');
-});
\ No newline at end of file
+ assert.match(renderBody, /if \(!previous\.length \|\| !state\.open\) sortAccountsByCreditExpiry\(\)/,
+ 'initial or hidden render sorts by expiry; visible cached rows retain their order');
+});
diff --git a/test/activity-refresh.test.js b/test/activity-refresh.test.js
new file mode 100644
index 0000000..1b6db7a
--- /dev/null
+++ b/test/activity-refresh.test.js
@@ -0,0 +1,67 @@
+'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 tick = () => new Promise(resolve => setImmediate(resolve));
+function harness() {
+ const requests = [], timers = [];
+ const start = source.includes(' var activityBatchPromise') ? source.indexOf(' var activityBatchPromise') : source.indexOf(' function fetchActivityForAccounts()');
+ const end = source.indexOf(' // 积分查询按', start);
+ const badgeStart = source.indexOf(' function activityStreakHtml(');
+ const ctx = vm.createContext({
+ alive: true, WBS_PROFILE_IS_AI: false, CAPS: { accounts: true },
+ state: { open: true, activityRunId: 0, accounts: [{ uid: 'a' }, { uid: 'b' }, { uid: 'c' }] },
+ api() { return new Promise((resolve, reject) => requests.push({ resolve, reject })); },
+ accountsPane: { querySelectorAll: () => [] },
+ setBuildTimeout(fn, delay) { const timer = { fn, delay }; timers.push(timer); return timer; },
+ clearTimeout(timer) { if (timer) timer.cancelled = true; },
+ Date: class extends Date { static now() { return 100000; } },
+ });
+ vm.runInContext(source.slice(badgeStart, source.indexOf(' function el(tag', badgeStart)) + source.slice(start, end), ctx);
+ return { ctx, requests, timers };
+}
+
+test('an activity failure retains the last valid count and schedules one delayed retry', async () => {
+ const h = harness(); h.ctx.state.accounts = [{ uid: 'a', activityStreak: { days: 5, status: 'ready' } }];
+ h.ctx.fetchActivityForAccounts();
+ h.requests[0].resolve({ activityStreak: { days: null, status: 'unavailable', fetchedAt: 100000 } }); await tick();
+ assert.equal(h.ctx.state.accounts[0].activityStreak.days, 5);
+ assert.equal(h.timers.length, 1);
+ assert.ok(h.timers[0].delay >= 30000);
+ h.timers[0].fn(); await tick();
+ assert.equal(h.requests.length, 2);
+ h.requests[1].reject(new Error('still offline')); await tick();
+ assert.equal(h.timers.length, 1, 'never retry indefinitely');
+});
+
+test('reopening while activity requests are pending never starts more than two requests', async () => {
+ const h = harness(); h.ctx.fetchActivityForAccounts();
+ assert.equal(h.requests.length, 2);
+ h.ctx.state.activityRunId++; h.ctx.fetchActivityForAccounts();
+ assert.equal(h.requests.length, 2);
+ h.requests[0].resolve({ activityStreak: { days: 99, status: 'ready' } });
+ h.requests[1].resolve({ activityStreak: { days: 99, status: 'ready' } }); await tick();
+ assert.equal(h.requests.length, 4);
+ assert.equal(h.ctx.state.accounts[0].activityStreak, undefined, 'old responses must not update the new run');
+});
+
+test('closing the panel prevents the delayed retry', async () => {
+ const h = harness(); h.ctx.state.accounts = [{ uid: 'a' }];
+ h.ctx.fetchActivityForAccounts(); h.requests[0].reject(new Error('offline')); await tick();
+ assert.equal(h.timers.length, 1);
+ h.ctx.state.open = false; h.ctx.state.activityRunId++;
+ h.timers[0].fn(); await tick();
+ assert.equal(h.requests.length, 1);
+});
+
+test('reinjection stops the old activity queue after its in-flight requests finish', async () => {
+ const h = harness(); h.ctx.fetchActivityForAccounts();
+ h.ctx.alive = false;
+ for (const request of h.requests) request.resolve({ activityStreak: { days: 5, status: 'ready' } });
+ await tick();
+ assert.equal(h.requests.length, 2);
+ assert.equal(h.ctx.state.accounts[0].activityStreak, undefined);
+ assert.equal(h.timers.length, 0);
+});
diff --git a/test/agent-create-dialog.test.js b/test/agent-create-dialog.test.js
new file mode 100644
index 0000000..34215c7
--- /dev/null
+++ b/test/agent-create-dialog.test.js
@@ -0,0 +1,28 @@
+'use strict';
+const test=require('node:test');
+const assert=require('node:assert/strict');
+const fs=require('node:fs');
+const os=require('node:os');
+const path=require('node:path');
+const {createAgentRequest}=require('../scripts/automation');
+test('custom agent requirement retains exact text and guarded bridge instructions',()=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-agent-prompt-'));
+ try {
+ const prompt='每小时检查一次\n完成后显示通知,不切换账号。';
+ const result=createAgentRequest(dir,{prompt,profileId:'workbuddy-cn'});
+ assert.ok(result.prompt.startsWith(prompt+'\n\n'));
+ assert.ok(result.prompt.includes(result.protocolPath));assert.ok(result.prompt.includes(result.inboxFile));assert.ok(result.prompt.includes(result.resultFile));
+ assert.equal(result.exampleId,'');
+ for(const invalid of ['', ' ', {}, 'x'.repeat(6001)])assert.throws(()=>createAgentRequest(dir,{prompt:invalid}),/需求/);
+ } finally {fs.rmSync(dir,{recursive:true,force:true});}
+});
+test('agent dialog offers an editable requirement, example fill and one submit action',()=>{
+ const s=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');
+ assert.ok(s.includes('id="wbs-auto-agent-prompt"'));assert.ok(s.includes('data-auto-example-fill'));
+ assert.ok(!s.includes('data-auto-example-generate'));assert.ok(!s.includes('data-auto-example-preview'));
+ assert.ok(s.includes('让 WorkBuddy 帮我创建'));
+ const toolbar=s.slice(s.indexOf('id="wbs-auto-normal-actions"'),s.indexOf('id="wbs-auto-batch-actions"'));
+ assert.ok(toolbar.indexOf('id="wbs-auto-pick"')<toolbar.indexOf('id="wbs-auto-create"'));
+ const daemon=fs.readFileSync(path.join(__dirname,'../scripts/daemon.js'),'utf8');
+ assert.ok(!daemon.includes("installBuiltinTask(DATA_DIR, path.join(__dirname, 'builtin/automations/report-to-primary.json'))"));
+});
diff --git a/test/agent-new-task-draft.test.js b/test/agent-new-task-draft.test.js
new file mode 100644
index 0000000..dba02a9
--- /dev/null
+++ b/test/agent-new-task-draft.test.js
@@ -0,0 +1,57 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/daemon.js'), 'utf8');
+const functions = source.slice(source.indexOf('async function ensureAutomationNewTask('), source.indexOf('\nfunction currentAccount()'));
+function harness(options = {}) {
+ let sessionSent = false; let clock = 0;
+ const calls = []; let draft = options.draft === false ? '' : 'existing draft'; let ready = !options.project;
+ const context = { automationAgentSurfaceExpression: () => '({newTaskReady:true})', cdp: { connected: true }, sleep: async ms => { clock += ms; }, Date: { now: () => clock },
+ readAutomationAgentSurface: async () => ({ ready: true, newTaskReady: ready, hasComposer: true, composerText: draft, button: {x:1,y:1} }),
+ cdpMouseClick: async () => { calls.push('navigate'); ready = true; },
+ cdpSend: async (method, params) => {
+ if (method === 'Runtime.evaluate' && params.expression.includes('probeSessionReceipt')) return {result:{value:sessionSent?{conversationId:'c',userMessageId:'u',requestId:'r'}:null}};
+ calls.push(method);
+ if (method === 'Runtime.evaluate') { if (options.draftChanges) draft = 'newly typed draft'; return { result: { value: { saved: !options.backupFails } } }; }
+ if (params.key === 'Backspace' && params.type === 'keyDown') draft = '';
+ return {};
+ },
+ sendStashToComposer: async () => { calls.push('send'); return { sent: true }; },
+ };
+ vm.createContext(context);vm.runInContext(functions,context);
+ const callback = source.slice(source.indexOf(' let lastReceipt = null;'), source.indexOf(' const completionReport =', source.indexOf(' let lastReceipt = null;')));
+ Object.assign(context,require('../scripts/automation-runtime'),{withInput:async fn=>fn(),isCancelled:()=>false,currentAccount:()=>({uid:'a'})});
+ context.acSendPhrase = async () => { calls.push('session-send'); sessionSent=true; return {sent:true}; };
+ vm.runInContext(callback + '\nthis.sessionSend = sessionSendCurrent; this.sessionAction = sessionAction;', context);
+ return { run: () => context.openNewAutomationAgentTask('Agent requirement'), session: () => context.sessionSend('1+1='), calls };
+}
+test('Agent creation saves a new-task draft before clearing and sending', async () => {
+ const h=harness();await h.run();assert.ok(h.calls.indexOf('Runtime.evaluate')<h.calls.indexOf('Input.dispatchKeyEvent'));assert.equal(h.calls.at(-1),'send');
+});
+test('failed draft backup prevents clearing and sending', async () => {
+ const h=harness({backupFails:true});await assert.rejects(h.run());assert.ok(!h.calls.includes('Input.dispatchKeyEvent'));assert.ok(!h.calls.includes('send'));
+});
+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',()=>{
+ 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('已设为主账号,自动化任务可据此识别主账号'"));
+});
+
+test('typing during draft backup cancels without clearing the new text', async () => {
+ const h=harness({draftChanges:true});await assert.rejects(h.run(),/草稿已变化/);assert.ok(!h.calls.includes('Input.dispatchKeyEvent'));assert.ok(!h.calls.includes('send'));
+});
+
+test('automation session.sendCurrent preserves occupied New Task draft before baseline and send',async()=>{
+ const h=harness();await h.session();
+ assert.ok(h.calls.indexOf('Runtime.evaluate')<h.calls.indexOf('Input.dispatchKeyEvent'));
+ assert.equal(h.calls.at(-1),'session-send');
+});
+test('automation session.sendCurrent refuses to send if saving fails or the draft changes',async()=>{
+ for(const options of [{backupFails:true},{draftChanges:true}]){
+ const h=harness(options);await assert.rejects(h.session());assert.ok(!h.calls.includes('session-send'));assert.ok(!h.calls.includes('Input.dispatchKeyEvent'));
+ }
+});
diff --git a/test/auth-discovery.test.js b/test/auth-discovery.test.js
index b472f23..f915fce 100644
--- a/test/auth-discovery.test.js
+++ b/test/auth-discovery.test.js
@@ -405,3 +405,56 @@ test('AI profile does not claim a domestic Tencent/CodeBuddy auth file', () => {
fs.rmSync(f.root, { recursive: true, force: true });
}
});
+
+for (const issuerOnly of [false, true]) {
+ test(`CN discovers, backs up and switches the Tencent issuer (issuerOnly=${issuerOnly})`, () => {
+ const f = fixture();
+ try {
+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');
+ const fresh = auth('new-cn', 'https://copilot.tencent.com/auth/realms/copilot');
+ if (issuerOnly) delete fresh.auth.domain;
+ fs.writeFileSync(canonical, JSON.stringify(fresh));
+ const current = run(f.root, f.dataDir, 'const r=lib.resolveCurrentAuth(); process.stdout.write(JSON.stringify({file:r.file,ambiguous:r.ambiguous,uid:r.record&&r.record.uid}))');
+ assert.deepEqual(current, { file: canonical, ambiguous: false, uid: 'new-cn' });
+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');
+ assert.equal(fs.existsSync(path.join(f.dataDir, 'accounts', 'new-cn.info')), true);
+ fs.writeFileSync(canonical, JSON.stringify(auth('old-cn', 'https://www.workbuddy.cn/auth/realms/copilot')));
+ const switched = run(f.root, f.dataDir, 'const r=lib.switchTo(process.env.WBSWITCH_DATA_DIR,"new-cn"); process.stdout.write(JSON.stringify({uid:r.uid}))');
+ assert.equal(switched.uid, 'new-cn');
+ assert.equal(JSON.parse(fs.readFileSync(canonical, 'utf8')).account.uid, 'new-cn');
+ } finally { fs.rmSync(f.root, { recursive: true, force: true }); }
+ });
+}
+
+test('Tencent CN issuer is excluded from AI and lookalike origins stay rejected', () => {
+ const f = fixture();
+ try {
+ const canonical = path.join(f.authDir, 'workbuddy-desktop-ai.info');
+ fs.writeFileSync(canonical, JSON.stringify(auth('cn', 'https://copilot.tencent.com/auth/realms/copilot')));
+ assert.deepEqual(run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.listAuthRecords().map(r=>r.uid)))', 'workbuddy-ai'), []);
+ for (const origin of ['https://copilot.tencent.com.attacker.example', 'http://copilot.tencent.com', 'https://other.tencent.com']) {
+ fs.writeFileSync(canonical, JSON.stringify(auth('unknown', origin + '/auth/realms/copilot')));
+ assert.deepEqual(run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.listAuthRecords().map(r=>r.uid)))'), []);
+ }
+ } finally { fs.rmSync(f.root, { recursive: true, force: true }); }
+});
+
+test('soft logout can be retried after the login file was removed and login was cancelled', () => {
+ const f = fixture();
+ try {
+ const canonical = path.join(f.authDir, 'workbuddy-desktop.info');
+ fs.writeFileSync(canonical, JSON.stringify(auth('cn', 'https://copilot.tencent.com/auth/realms/copilot')));
+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write("null")');
+ fs.unlinkSync(canonical); // First soft logout succeeded, subsequent login did not.
+ const resolution = run(f.root, f.dataDir, 'const r=lib.resolveLogoutAuth(); process.stdout.write(JSON.stringify({file:r.file,ambiguous:r.ambiguous}))');
+ assert.deepEqual(resolution, { file: canonical, ambiguous: false });
+ assert.equal(fs.existsSync(path.join(f.dataDir, 'accounts', 'cn.info')), true);
+ fs.writeFileSync(canonical, '{incomplete');
+ const invalid = run(f.root, f.dataDir, 'const r=lib.resolveLogoutAuth(); process.stdout.write(JSON.stringify({file:r.file}))');
+ assert.equal(invalid.file, null);
+ fs.unlinkSync(canonical);
+ fs.writeFileSync(path.join(f.authDir, 'unknown.info'), '{incomplete');
+ const unknown = run(f.root, f.dataDir, 'const r=lib.resolveLogoutAuth(); process.stdout.write(JSON.stringify({file:r.file}))');
+ assert.equal(unknown.file, null);
+ } finally { fs.rmSync(f.root, { recursive: true, force: true }); }
+});
diff --git a/test/auto-copy-rules.test.js b/test/auto-copy-rules.test.js
index 21fc342..ae75c20 100644
--- a/test/auto-copy-rules.test.js
+++ b/test/auto-copy-rules.test.js
@@ -404,14 +404,12 @@ test('api keys keep their full masked length without exposing the middle', () =>
assert.equal(masked.includes('abcdef'), false);
});
-test('checkin display keeps a confirmed result while the current claim is still running', () => {
+test('checkin display exposes only today’s confirmed result', () => {
const record = { date: '2026-08-23', ok: true, already: false, code: 0, message: 'ok' };
- assert.deepEqual(checkinDisplayValue(record, '2026-08-23', true), {
+ assert.deepEqual(checkinDisplayValue(record, '2026-08-23'), {
ok: true, already: false, code: 0, message: 'ok',
});
- assert.equal(checkinDisplayValue({ date: '2026-08-23', ok: false }, '2026-08-23', true), null);
- assert.deepEqual(checkinDisplayValue(record, '2026-08-23', false), {
- ok: true, already: false, code: 0, message: 'ok',
- });
- assert.equal(checkinDisplayValue(record, '2026-08-22', false), null);
+ assert.equal(checkinDisplayValue({ date: '2026-08-23', ok: false }, '2026-08-23'), null);
+ assert.equal(checkinDisplayValue(null, '2026-08-23'), null);
+ assert.equal(checkinDisplayValue(record, '2026-08-24'), null);
});
diff --git a/test/automation-calendar.test.js b/test/automation-calendar.test.js
new file mode 100644
index 0000000..451d626
--- /dev/null
+++ b/test/automation-calendar.test.js
@@ -0,0 +1,46 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
+const a=require('../scripts/automation');
+const at=(s)=>new Date(s).getTime();
+const task=(schedule)=>a.validateTask({id:'calendar',steps:[],schedule});
+test('calendar schedules validate times, weekdays, dates and manual eligibility',()=>{
+ for(const schedule of [{type:'daily',time:'09:30'},{type:'weekly',time:'18:00',days:[1,3,5]},{type:'monthly',time:'10:00',day:31},{type:'once',at:'2026-09-09T08:30'}])assert.equal(a.canManuallyRunTask(task(schedule)),false);
+ for(const schedule of [{type:'daily',time:'25:00'},{type:'weekly',time:'08:00',days:[]},{type:'weekly',time:'08:00',days:[7]},{type:'monthly',time:'08:00',day:0},{type:'once',at:'2026-02-30T08:00'}])assert.throws(()=>task(schedule));
+});
+test('daily schedule runs once per local time slot, including after restart',()=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-calendar-'));try{
+ const t=task({type:'daily',time:'09:30'}),calls=[];let tick=a.createScheduleTicker(dir);const run=x=>calls.push(x.id);
+ tick([t],run,()=>false,at('2026-09-08T09:29:59'));assert.equal(calls.length,0);
+ tick([t],run,()=>false,at('2026-09-08T09:30:00'));tick([t],run,()=>false,at('2026-09-08T09:30:30'));assert.equal(calls.length,1);
+ tick=a.createScheduleTicker(dir);tick([t],run,()=>false,at('2026-09-08T09:30:50'));assert.equal(calls.length,1);
+ tick([t],run,()=>false,at('2026-09-09T10:00:00'));assert.equal(calls.length,1,'missed slot is not replayed');
+ tick([t],run,()=>false,at('2026-09-10T09:30:00'));assert.equal(calls.length,2);
+ }finally{fs.rmSync(dir,{recursive:true,force:true});}
+});
+test('weekly/monthly/once match local calendar, skip overlap and nonexistent month dates',()=>{
+ for(const [schedule,miss,match] of [
+ [{type:'weekly',days:[1,5],time:'08:00'},'2026-09-08T08:00','2026-09-11T08:00'],
+ [{type:'monthly',day:31,time:'08:00'},'2026-09-30T08:00','2026-10-31T08:00'],
+ [{type:'once',at:'2026-09-09T08:00'},'2026-09-08T08:00','2026-09-09T08:00']]){
+ const tick=a.createScheduleTicker(),t=task(schedule),calls=[];const run=x=>calls.push(x.id);
+ tick([t],run,()=>false,at(miss));assert.equal(calls.length,0);tick([t],run,()=>true,at(match));tick([t],run,()=>false,at(match)+10000);assert.equal(calls.length,0);
+ const fresh=a.createScheduleTicker();fresh([t],run,()=>false,at(match));assert.equal(calls.length,1);
+ }
+});
+test('all three builtins preserve existing edits and deletion across updates',()=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-builtins-'));try{
+ const files=fs.readdirSync(path.join(__dirname,'../scripts/builtin/automations')).filter(f=>f.endsWith('.json'));assert.equal(files.length,3);
+ const install=()=>files.forEach(f=>a.installBuiltinTask(dir,path.join(__dirname,'../scripts/builtin/automations',f)));
+ install();const original=a.readAutomations(dir);assert.equal(new Set(original.map(t=>t.id)).size,3);
+ const edited=original.slice(1).map(t=>({...t,name:'用户修改',enabled:false}));a.writeAutomations(dir,edited);install();assert.deepEqual(a.readAutomations(dir),edited);
+ }finally{fs.rmSync(dir,{recursive:true,force:true});}
+});
+
+test('existing builtin IDs are adopted without replacing definitions when markers are absent',()=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-adopt-'));try{
+ const file=path.join(__dirname,'../scripts/builtin/automations/keep-accounts-active.json');
+ const t=a.validateTask({...JSON.parse(fs.readFileSync(file)),name:'用户自定义',steps:[],enabled:false});
+ a.writeAutomations(dir,[t]);a.installBuiltinTask(dir,file);assert.deepEqual(a.readAutomations(dir),[t]);
+ a.writeAutomations(dir,[]);a.installBuiltinTask(dir,file);assert.deepEqual(a.readAutomations(dir),[]);
+ }finally{fs.rmSync(dir,{recursive:true,force:true});}
+});
diff --git a/test/automation-cards-streak.test.js b/test/automation-cards-streak.test.js
new file mode 100644
index 0000000..b7e560c
--- /dev/null
+++ b/test/automation-cards-streak.test.js
@@ -0,0 +1,81 @@
+'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 {canManuallyRunTask,AGENT_EXAMPLES}=require('../scripts/automation');
+const {fetchGrowthStreak,createGrowthStreakCache}=require('../scripts/growth-active');
+const ui=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');
+
+test('only manual tasks expose a direct run action, including disabled automatic tasks',()=>{
+ for(const task of [{},{trigger:{type:'manual'}},{trigger:{type:'pageReady',types:[]}}])assert.equal(canManuallyRunTask(task),true);
+ for(const task of [{trigger:{type:'pageReady'}},{trigger:{type:'panelOpened'},enabled:false},{trigger:{types:['clientLoaded','panelOpened']}},{schedule:{type:'interval',minutes:60}}])assert.equal(canManuallyRunTask(task),false);
+ assert.equal(AGENT_EXAMPLES.some(e=>e.id==='close-buddy-fuel'),false);
+});
+
+test('streak uses the official endpoint and exact continuous-day field, including zero',async()=>{
+ for(const days of [0,5]){
+ const r=await fetchGrowthStreak('sample-token',{fetchImpl:async(url,init)=>{
+ assert.equal(url,'https://www.workbuddy.cn/activity/growth/streak');assert.equal(init.method,'GET');assert.equal(init.redirect,'error');
+ assert.equal(init.headers.authorization,'Bearer sample-token');
+ return {ok:true,status:200,text:async()=>JSON.stringify({code:0,data:{streak:{days,month_total_days:20},today:{score:99}}})};
+ }});
+ assert.deepEqual(r,{days});
+ }
+});
+
+test('unknown streak responses never become a confirmed zero',async()=>{
+ for(const payload of [{code:0,data:{}},{code:0,data:{streak:{days:null}}},{code:0,data:{streak:{days:-1}}},{code:0,data:{streak:{days:'5'}}},{code:401,data:{streak:{days:5}}}]){
+ await assert.rejects(fetchGrowthStreak('sample-token',{fetchImpl:async()=>({ok:true,status:200,text:async()=>JSON.stringify(payload)})}));
+ }
+});
+
+test('streak cache isolates accounts, coalesces requests, expires at midnight and backs off failures',async()=>{
+ let at=new Date(2026,8,8,23,59,0).getTime();let count=0;let fail=false;
+ const cache=createGrowthStreakCache(async uid=>{count++;if(fail)throw Error('offline');return {days:uid==='a'?5:0};},{now:()=>at});
+ const both=await Promise.all([cache.get('a'),cache.get('a')]);assert.equal(count,1);assert.equal(both[0].days,5);
+ assert.equal((await cache.get('b')).days,0);assert.equal(count,2);
+ await cache.get('a');assert.equal(count,2);
+ at+=61000;assert.equal(cache.peek('a'),null);await cache.get('a');assert.equal(count,3);
+ fail=true;at+=300001;const failed=await cache.get('a');assert.equal(failed.days,null);assert.equal(failed.status,'unavailable');
+ await cache.get('a');assert.equal(count,4);at+=30001;await cache.get('a');assert.equal(count,5);
+});
+
+test('activity badge distinguishes zero, positive, and unavailable data and escapes invalid values',()=>{
+ const start=ui.indexOf(' function activityStreakHtml(');const end=ui.indexOf(' function el(tag',start);assert.ok(start>0);
+ const ctx={WBS_PROFILE_IS_AI:false};vm.createContext(ctx);vm.runInContext(ui.slice(start,end),ctx);
+ assert.match(ctx.activityStreakHtml({activityStreak:{days:0,status:'ready'}}),/pending[^>]*>活跃 0 天/);
+ assert.match(ctx.activityStreakHtml({activityStreak:{days:5,status:'ready'}}),/ ok[^>]*>活跃 5 天/);
+ assert.equal(ctx.activityStreakHtml({}), '');
+ assert.match(ctx.activityStreakHtml({activityStreak:{days:null,status:'unavailable'}}),/活跃读取失败/);
+ assert.doesNotMatch(ctx.activityStreakHtml({activityStreak:{days:'<img>',status:'ready'}}),/<img>/);
+ ctx.WBS_PROFILE_IS_AI=true;assert.equal(ctx.activityStreakHtml({}), '');
+});
+
+test('task cards render triggers separately, show start only for manual tasks, and keep stop for active runs',()=>{
+ const start=ui.indexOf(' function triggerBadgesHtml('),end=ui.indexOf(' function load()',start);
+ const rows=[];const list={innerHTML:'',scrollTop:37,appendChild:r=>rows.push(r.innerHTML)};
+ const ctx={automationState:{tasks:[
+ {id:'manual',name:'Manual',enabled:true,manualRunnable:true,trigger:{type:'manual'}},
+ {id:'event',name:'<img onerror=x>',description:'<script>bad</script>',enabled:true,manualRunnable:false,trigger:{types:['clientLoaded','panelOpened']},schedule:{type:'interval',minutes:60}},
+ {id:'active',name:'Active',enabled:true,manualRunnable:false,trigger:{type:'pageReady'}},
+ ],runs:[{id:'run-active',taskId:'active',status:'running'}],selected:{},stopping:{}},
+ automationPane:{querySelector:s=>s==='#wbs-auto-list'?list:null},
+ document:{createElement:()=>({setAttribute(){}})},
+ esc:s=>String(s).replaceAll('<','&lt;').replaceAll('>','&gt;'),escAttr:s=>String(s).replaceAll('<','&lt;').replaceAll('"','&quot;'),
+ applyI18n(){},AUTO_STOPPING_SVG:'',AUTO_STOP_SVG:'',MODEL_ENABLE_SVG:'',AUTO_LOG_SVG:'',MODEL_EDIT_SVG:'',MODEL_COPY_SVG:'',TRASH_SVG:''};
+ ctx.WBS_I18N_EN = {};
+ vm.createContext(ctx);
+ vm.runInContext(ui.slice(ui.indexOf(' function wbsBuiltinAutomationText('), ui.indexOf(' // ===== 全局错误钩子')), ctx);
+ vm.runInContext(ui.slice(start,end),ctx);ctx.render();
+ assert.match(rows[0],/data-auto-run="manual"/);
+ assert.doesNotMatch(rows[1],/data-auto-run|data-auto-stop|<img|<script>/);
+ for(const label of ['客户端加载','打开面板','每 60 分钟','等待触发'])assert.ok(rows[1].includes(label));
+ assert.match(rows[2],/data-auto-stop="run-active"/);assert.match(rows[2],/执行中/);
+ assert.equal(list.scrollTop,37);
+});
+
+test('scrollable automation list never shrinks cards and clips their descriptions or footers',()=>{
+ assert.match(ui,/\.wbs-auto-row\{[^}]*flex:0 0 auto/);
+});
diff --git a/test/automation-checkin.test.js b/test/automation-checkin.test.js
new file mode 100644
index 0000000..e923892
--- /dev/null
+++ b/test/automation-checkin.test.js
@@ -0,0 +1,146 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const path = require('node:path');
+const os = require('node:os');
+const automation = require('../scripts/automation');
+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+const presetPath = path.join(__dirname, '../scripts/builtin/automations/daily-account-checkin.json');
+
+test('multiple event triggers survive validation and match independently', () => {
+ const task = automation.validateTask({id:'multi', trigger:{type:'manual',types:['clientLoaded','panelOpened']}, schedule:{type:'interval',minutes:60},steps:[]});
+ assert.deepEqual(task.trigger.types,['clientLoaded','panelOpened']);
+ for(const event of ['pageReady','panelOpened']) assert.equal(automation.taskMatchesEvent(task,event,{source:"connect"}),true);
+ assert.equal(automation.taskMatchesEvent(task,'accountSwitched'),false);
+ assert.equal(automation.taskMatchesEvent({...task,enabled:false},'panelOpened'),false);
+ assert.throws(()=>automation.validateTask({...task,schedule:{type:'interval',minutes:0}}));
+});
+
+test('interval scheduler handles edits, disabled tasks and overlapping runs without catch-up storms', () => {
+ const tick = automation.createScheduleTicker(); const calls=[];
+ const task=automation.normalizeTask({id:'hourly',schedule:{type:'interval',minutes:60},steps:[]});
+ const run=t=>calls.push(t.id);
+ tick([task],run,()=>false,0);tick([task],run,()=>false,3599999);assert.equal(calls.length,0);
+ tick([task],run,()=>false,3600000);assert.equal(calls.length,1);
+ tick([task],run,()=>true,7200000);assert.equal(calls.length,1);
+ tick([task],run,()=>false,7200001);assert.equal(calls.length,1);
+ tick([{...task,enabled:false}],run,()=>false,10800000);
+ tick([task],run,()=>false,10800001);assert.equal(calls.length,1);
+ tick([task],run,()=>false,14400001);assert.equal(calls.length,2);
+ tick([{...task,schedule:{type:'interval',minutes:5}}],run,()=>false,14400002);
+ tick([{...task,schedule:{type:'interval',minutes:5}}],run,()=>false,14700002);assert.equal(calls.length,3);
+});
+
+test('built-in task is installed once and respects edits, disabling and deletion', () => {
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-checkin-'));
+ try {
+ automation.installBuiltinTask(dir,presetPath);
+ const tasks=automation.readAutomations(dir);assert.equal(tasks.length,1);
+ tasks[0].enabled=false;automation.writeAutomations(dir,tasks);
+ automation.installBuiltinTask(dir,presetPath);assert.equal(automation.readAutomations(dir)[0].enabled,false);
+ automation.writeAutomations(dir,[]);automation.installBuiltinTask(dir,presetPath);assert.equal(automation.readAutomations(dir).length,0);
+ } finally {fs.rmSync(dir,{recursive:true,force:true});}
+});
+
+test('preset silently iterates accounts, continues after failures and leaves the panel open', async () => {
+ const preset=JSON.parse(fs.readFileSync(presetPath));
+ assert.equal(automation.taskNeedsPanelClosed(preset),false);
+ assert.equal(automation.taskNeedsPanelClosed({...preset,onFailure:[{op:'session.sendCurrent',message:'test'}]}),true);
+ const calls=[];
+ await automation.executeTask(preset,{
+ listAccounts:async()=>[{uid:'a'},{uid:'b'},{uid:'c'}],
+ accountCheckin:async a=>{calls.push(a.uid);if(a.uid==='b')throw Error('offline');return {ok:true,skipped:true};},
+ accountSwitch:()=>assert.fail('must not switch accounts'),
+ });
+ assert.deepEqual(calls,['a','b','c']);
+});
+
+function claimHarness({stored=null,cached=null}={}) {
+ const start=source.indexOf('const checkinClaims = new Map()');
+ const end=source.indexOf('/** 通过 CDP 把右下角组件',start);
+ assert.ok(start>0 && end>start);
+ let requests=0,refreshes=0;const records={};
+ const ctx={Map,Promise,Date,PROFILE:{capabilities:{accounts:true,checkin:true}},todayStr:()=> '2026-09-08',
+ CREDIT_USAGE_STORE:{getDailyCheckin:async()=>stored,saveDailyCheckin:async()=>{}},
+ loadCheckinCache:()=>cached?{a:cached}:records,saveCheckinCache:()=>{},
+ classifyCheckinResult:require('../scripts/checkin-result').classifyCheckinResult,
+ refreshAccountBackupToken:async()=>{refreshes++;return {root:{auth:{accessToken:'test-token'}}};},
+ dailyCheckin:async()=>{requests++;await Promise.resolve();return {ok:true,code:0,message:'ok'};},log:()=>{},
+ };
+ vm.createContext(ctx);vm.runInContext(source.slice(start,end),ctx);
+ return {claim:ctx.claimDailyForUid,counts:()=>({requests,refreshes})};
+}
+test('confirmed daily check-in skips even token refresh; concurrent claims share one request',async()=>{
+ for(const record of [{date:'2026-09-08',ok:true,verified:true},null]){
+ const h=claimHarness({stored:record,cached:record?null:{date:'2026-09-08',ok:true,code:0,message:'ok'}});
+ assert.equal((await h.claim('a')).skipped,true);assert.deepEqual(h.counts(),{requests:0,refreshes:0});
+ }
+ const h=claimHarness();await Promise.all([h.claim('a'),h.claim('a')]);assert.deepEqual(h.counts(),{requests:1,refreshes:1});
+ await h.claim('a');assert.deepEqual(h.counts(),{requests:1,refreshes:1});
+});
+
+test('legacy implicit triggers and pending UI are removed; panel event is explicit',()=>{
+ assert.doesNotMatch(source,/claimDailyForAll|CHECKIN_STARTUP_DELAY_MS|CHECKIN_INTERVAL_MS|checkinSnapshot/);
+ const route=source.slice(source.indexOf("if (req.method === 'GET' && p === '/api/accounts')"),source.indexOf('// 查询指定账号的剩余积分'));
+ assert.doesNotMatch(route,/claimDailyForUid|refreshAccountBackupToken/);
+ const ui=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');
+ assert.doesNotMatch(ui,/签到中|watchCheckin|stopCheckinPolling/);
+ 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.doesNotMatch(ctx.checkinHtml({checkin:{ok:false,message:'bad'}}),/bad/);
+});
+
+test('failed or stale cache records never suppress today\'s check-in request', async () => {
+ for (const cached of [
+ {date:'2026-09-08',ok:false,verified:false,code:0,message:'HTTP 500'},
+ {date:'2026-09-07',ok:true,verified:true,code:0,message:'ok'},
+ {date:'2026-09-08',ok:true,code:10001,message:'活动未开启'},
+ ]) {
+ const h=claimHarness({cached}); await h.claim('a');
+ assert.deepEqual(h.counts(),{requests:1,refreshes:1});
+ }
+});
+
+test('panel-open emits once per user opening and excludes automation restoration', () => {
+ const ui=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');
+ const start=ui.indexOf(' function setOpen(open, options)');
+ const end=ui.indexOf(' function setupFabDrag()',start);
+ const calls=[];const noop=()=>{};
+ const ctx={window:{},state:{open:false,creditRunId:0},panel:{classList:{toggle:noop}},fab:{classList:{toggle:noop}},
+ api:(route,options)=>{calls.push([route,JSON.parse(options.body).type]);return Promise.resolve();},
+ CAPS:{accounts:false},refresh:noop,checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,fabQuietMode:{wake:noop}};
+ vm.createContext(ctx);vm.runInContext(ui.slice(start,end),ctx);
+ ctx.setOpen(true);ctx.setOpen(true);assert.equal(calls.length,1);
+ ctx.setOpen(false);ctx.setOpen(true,{automation:true});assert.equal(calls.length,1);
+ ctx.setOpen(false);ctx.setOpen(true);assert.deepEqual(calls,[['/api/automations/events','panelOpened'],['/api/automations/events','panelOpened']]);
+});
+
+test('automation editor assigns remaining height to the code field without an outer scroll area', () => {
+ const ui=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');
+ const rules=ui.slice(ui.indexOf("'.wbs-modal.wbs-auto-editor-modal"),ui.indexOf("'.wbs-modal.wbs-auto-log-modal"));
+ assert.match(rules,/\.wbs-auto-editor-body\{[^}]*display:flex[^}]*min-height:0[^}]*overflow:hidden/);
+ assert.match(rules,/\.wbs-auto-steps-field\{[^}]*flex:1 1 0;min-height:0/);
+ assert.match(rules,/textarea\[data-auto-field="steps"\]\{[^}]*height:0;min-height:0;resize:none;overflow:auto/);
+ assert.doesNotMatch(rules,/height:calc\(100% - 164px\)|min-height:190px/);
+});
+
+test('fresh CN and AI profiles receive all three presets without reinstalling deleted tasks', () => {
+ const init = source.slice(source.indexOf("for (const preset of ['close-buddy-popups.json'"), source.indexOf('\nrestoreSleepMode();'));
+ const { PROFILES } = require('../scripts/profiles');
+ 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() {} };
+ 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, []);
+ vm.runInNewContext(init, context);
+ assert.equal(automation.readAutomations(dir).length, 0);
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+ }
+});
diff --git a/test/automation-contract.test.js b/test/automation-contract.test.js
new file mode 100644
index 0000000..e9dc91f
--- /dev/null
+++ b/test/automation-contract.test.js
@@ -0,0 +1,56 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const {executeTask,taskMatchesEvent,validateTask}=require('../scripts/automation');
+const run=(steps,options={})=>executeTask({id:'contract',steps},options);
+test('HTTP recursively resolves typed templates, status saveAs and account fallback',async()=>{
+ let request,account;
+ await run([{op:'account.status',saveAs:'status'},{op:'http.requestAsAccount',url:'https://www.workbuddy.cn/api',body:{count:'{{vars.status.days}}',nested:['{{vars.status.days}}']}}],{
+ currentAccount:()=>({uid:'fake'}),accountStatus:async()=>({days:5}),httpRequest:async(r,a)=>{request=r;account=a;return{ok:true}}});
+ assert.deepEqual(request.body,{count:5,nested:[5]});assert.equal(account.uid,'fake');
+});
+test('HTTP error opt-in throws and retries; default preserves response branching',async()=>{
+ let count=0;
+ await run([{op:'logic.retry',times:2,delayMs:1,steps:[{op:'http.request',url:'https://example.com',throwOnHttpError:true}]}],{httpRequest:async()=>({ok:++count>1,status:count===1?500:200})});
+ assert.equal(count,2);
+});
+test('lifecycle distinguishes actual switch and connection from ordinary reload',()=>{
+ const t=type=>({enabled:true,trigger:{type}});
+ assert.equal(taskMatchesEvent(t('accountSwitched'),'pageReady',{source:'load'}),false);
+ assert.equal(taskMatchesEvent(t('accountSwitched'),'pageReady',{source:'account-switch'}),true);
+ assert.equal(taskMatchesEvent(t('clientLoaded'),'pageReady',{source:'load'}),false);
+ assert.equal(taskMatchesEvent(t('clientLoaded'),'pageReady',{source:'connect'}),true);
+ assert.equal(taskMatchesEvent(t('pageLoaded'),'pageReady',{source:'load'}),true);
+});
+test('stop interrupts a long delay promptly even inside catch/retry',async()=>{
+ let stopped=false;const timer=setTimeout(()=>{stopped=true},30),start=Date.now();
+ await assert.rejects(run([{op:'logic.retry',times:5,steps:[{op:'logic.catch',steps:[{op:'logic.delay',ms:20000}]}]}],{isCancelled:()=>stopped}),/停止/);
+ clearTimeout(timer);assert.ok(Date.now()-start<1000);
+});
+test('forEach/break and numeric comparisons preserve loop context',async()=>{
+ const r=await run([{op:'logic.forEach',items:[1,2,3],steps:[{op:'vars.set',key:'last',value:'{{vars.item}}'},{op:'logic.if',condition:{left:'{{vars.item}}',operator:'gte',right:2},then:[{op:'logic.break'}]}]}]);
+ assert.equal(r.context.vars.last,2);assert.equal(r.context.vars.item,undefined);
+});
+test('account loops restore outer context and expose public account helpers',async()=>{
+ const r=await run([{op:'account.getCurrent',saveAs:'current'},{op:'account.forEach',steps:[{op:'account.status',saveAs:'s'}]},{op:'account.status',saveAs:'after'}],{currentAccount:()=>({uid:'a'}),listAccounts:async()=>[{uid:'b'}],accountStatus:async a=>({uid:a.uid})});
+ assert.equal(r.context.vars.after.uid,'a');assert.equal(r.context.vars.current.uid,'a');
+});
+test('unknown state scope and missing key fail validation',()=>{
+ assert.throws(()=>validateTask({steps:[{op:'state.set',scope:'global',key:'x'}]}));
+ assert.throws(()=>validateTask({steps:[{op:'state.get'}]}));
+});
+test('popup observers can run between sends; typing and account loops retain renderer lease',()=>{
+ const {taskIsPassiveCleanup}=require('../scripts/automation');
+ const popup=require('../scripts/builtin/automations/close-buddy-popups.json');
+ assert.equal(taskIsPassiveCleanup(popup),true);
+ for(const step of [{op:'dom.type'},{op:'session.create'},{op:'account.forEach',switch:true}])assert.equal(taskIsPassiveCleanup({...popup,steps:[...popup.steps,step]}),false);
+ assert.equal(taskIsPassiveCleanup({...popup,trigger:{type:'manual'}}),false);
+});
+test('cancellation restores original account with an explicit restoration flag',async()=>{
+ let current={uid:'a'},stopped=false;const switches=[];
+ await assert.rejects(run([{op:'account.forEach',switch:true,steps:[{op:'logic.delay',ms:10000}]}],{
+ currentAccount:()=>current,listAccounts:async()=>[{uid:'b'}],isCancelled:()=>stopped,
+ accountSwitch:async(a,detail)=>{switches.push({uid:a.uid,restore:!!detail?.restore});current=a;if(a.uid==='b')stopped=true;}
+ }),/停止/);
+ assert.deepEqual(switches,[{uid:'b',restore:false},{uid:'a',restore:true}]);
+});
diff --git a/test/automation-new-task-readiness.test.js b/test/automation-new-task-readiness.test.js
new file mode 100644
index 0000000..6068cf6
--- /dev/null
+++ b/test/automation-new-task-readiness.test.js
@@ -0,0 +1,34 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'),path=require('node:path');
+const source=fs.readFileSync(path.join(__dirname,'../scripts/daemon.js'),'utf8');
+const begin=source.indexOf('async function ensureAutomationNewTask('),end=source.indexOf('let automationAgentCreating =',begin);
+function harness({buttonAfter=4,readyAfter=7,transientAt=0,cancelAt=Infinity,missing=false,accountChanges=false}={}){
+ let clock=0,reads=0;const calls=[];
+ const ctx={cdp:{connected:true},Date:{now:()=>clock},sleep:async ms=>{clock+=ms},automationAgentSurfaceExpression:()=> '({newTaskReady:true})',
+ readAutomationAgentSurface:async()=>{reads++;if(reads===transientAt)throw Error('Execution context was destroyed');return {newTaskReady:!missing&&reads>=readyAfter,hasComposer:!missing&&reads>=readyAfter,composerText:'',button:!missing&&reads>=buttonAfter?{x:1,y:1}:null}},
+ cdpMouseClick:async()=>calls.push('navigate'),cdpSend:async()=>{calls.push('backup');return {result:{value:{saved:true}}}},
+ };
+ vm.runInNewContext(source.slice(begin,end),ctx);
+ return {calls,time:()=>clock,run:()=>ctx.ensureAutomationNewTask({guard:()=>{if(reads>=cancelAt)throw Error(accountChanges?'account changed':'cancelled')}})};
+}
+test('second account can render the New Task entry after several empty page probes',async()=>{
+ const first=harness({buttonAfter:1,readyAfter:1});await first.run();assert.deepEqual(first.calls,['backup']);
+ const next=harness();await next.run();assert.deepEqual(next.calls,['navigate','backup']);assert.ok(next.time()>=1000);
+});
+test('a transient navigation context loss is retried before touching the composer',async()=>{
+ const h=harness({transientAt:2});await h.run();assert.deepEqual(h.calls,['navigate','backup']);
+});
+test('cancellation and account changes during page readiness abort without draft operations',async()=>{
+ for(const accountChanges of [false,true]){const h=harness({cancelAt:2,accountChanges});await assert.rejects(h.run(),accountChanges?/account changed/:/cancelled/);assert.deepEqual(h.calls,[])}
+});
+test('a login or unsupported page without a New Task entry times out without typing or clicking',async()=>{
+ const h=harness({missing:true});await assert.rejects(h.run(),/未找到 WorkBuddy 的新建任务入口/);assert.ok(h.time()>=10000&&h.time()<=20000);assert.deepEqual(h.calls,[]);
+});
+test('the New Task entry is clicked once even while the destination composer stays unavailable',async()=>{
+ const h=harness({buttonAfter:1,readyAfter:Infinity});await assert.rejects(h.run(),/新建任务页面未准备完成/);assert.deepEqual(h.calls,['navigate']);
+});
+
+test('a briefly ready composer that remounts must settle before draft backup',async()=>{
+ const h=harness({readyAfter:1,buttonAfter:Infinity,transientAt:2});
+ await h.run();assert.deepEqual(h.calls,['backup']);assert.ok(h.time()>=600);
+});
diff --git a/test/automation-packages.test.js b/test/automation-packages.test.js
new file mode 100644
index 0000000..3e3efe5
--- /dev/null
+++ b/test/automation-packages.test.js
@@ -0,0 +1,105 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
+const automation=require('../scripts/automation');
+test('editing another task preserves future-schema documents without executing them',()=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-package-'));
+ try {
+ const future={schemaVersion:2,id:'future',name:'Future task',enabled:true,trigger:{type:'panelOpened'},schedule:{type:'interval',minutes:1},steps:[],futureConfig:{value:1}};
+ fs.writeFileSync(path.join(dir,'automations.json'),JSON.stringify([future]));
+ const tasks=automation.readAutomations(dir);
+ assert.deepEqual(tasks[0],future);
+ assert.equal(automation.canManuallyRunTask({...future,trigger:{type:'manual'},schedule:{type:'manual'}}),false);
+ assert.equal(automation.taskMatchesEvent(future,'panelOpened'),false);
+ const tick=automation.createScheduleTicker(),calls=[];tick(tasks,t=>calls.push(t),()=>false,0);tick(tasks,t=>calls.push(t),()=>false,60000);assert.equal(calls.length,0);
+ automation.writeAutomations(dir,[...tasks,automation.validateTask({id:'local',steps:[]})]);
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir,'automations.json')))[0],future);
+ }finally{fs.rmSync(dir,{recursive:true,force:true});}
+});
+test('v1 task extension metadata survives normalization and validation',()=>{
+ const task={id:'metadata',steps:[],'x-example':{nested:[1,2]}};
+ assert.deepEqual(automation.validateTask(task)['x-example'],task['x-example']);
+});
+
+const {previewPackage,versionAtLeast}=require('../scripts/automation-packages');
+const runtime={version:'1.1.91',profileId:'workbuddy-cn',platform:'darwin'};
+const example=()=>({kind:'workdaddy.automation-package',formatVersion:1,id:'org.example.account-notice',version:'1.0.0',name:'Account notice',requires:{minWorkDaddyVersion:'1.1.90',taskSchemaVersion:1,capabilities:['account.status'],profiles:['workbuddy-cn'],platforms:['darwin','win32']},inputs:{message:{type:'string',title:'Message',default:'Hello'}},task:{schemaVersion:1,name:'Notice',trigger:{type:'panelOpened'},steps:[{op:'account.status',saveAs:'status'},{op:'notify.toast',message:'{{vars.message}}'}]}});
+test('package preview binds inputs, derives capabilities and stays disabled without mutating input',()=>{
+ const input=example(),before=JSON.stringify(input);const p=previewPackage(input,{runtime,values:{message:'Custom'}});
+ assert.equal(p.compatible,true);assert.equal(p.executed,false);assert.equal(p.task.enabled,false);assert.equal(p.task.variables.message,'Custom');
+ assert.ok(p.analysis.capabilities.includes('event.panelOpened'));assert.ok(p.analysis.capabilities.includes('notify.toast'));assert.equal(JSON.stringify(input),before);assert.match(p.sha256,/^[a-f0-9]{64}$/);
+});
+test('package compatibility rejects newer versions, other profiles/platforms and undeclared missing capabilities',()=>{
+ const input=example();input.requires.minWorkDaddyVersion='2.0.0';input.task.steps.push({op:'future.send'});
+ const p=previewPackage(input,{runtime:{...runtime,profileId:'workbuddy-ai',platform:'linux'}});
+ assert.equal(p.compatible,false);for(const code of ['workdaddy_version','profile','platform','capability'])assert.ok(p.issues.some(i=>i.code===code));
+});
+test('future formats are not silently reinterpreted as legacy tasks',()=>{
+ for(const patch of [{formatVersion:2},{kind:'other-package'}])assert.equal(previewPackage({...example(),...patch},{runtime}).compatible,false);
+ const p=example();p.requires.taskSchemaVersion=2;p.task.schemaVersion=2;assert.equal(previewPackage(p,{runtime}).task,null);
+});
+test('legacy JSON remains previewable; hashes identify bytes, not publisher trust',()=>{
+ const text='{"id":"legacy","steps":[]}';const p=previewPackage(text,{runtime});assert.equal(p.kind,'legacy-task');assert.equal(p.compatible,true);
+ assert.notEqual(p.sha256,previewPackage(text+'\n',{runtime}).sha256);
+});
+test('input requirements and types cannot silently coerce or inject extra variables',()=>{
+ const p=example();p.inputs.message={type:'string',required:true};assert.ok(previewPackage(p,{runtime}).issues.some(i=>i.code==='input_required'));
+ assert.throws(()=>previewPackage(p,{runtime,values:{message:3}}));assert.throws(()=>previewPackage(p,{runtime,values:{extra:'x'}}));
+ p.inputs.message.default=123;assert.throws(()=>previewPackage(p,{runtime}));
+});
+test('unknown behavioral fields require a new contract; x- metadata is accepted',()=>{
+ assert.throws(()=>previewPackage({...example(),shell:'echo hi'},{runtime}));assert.equal(previewPackage({...example(),'x-author-notes':'metadata only'},{runtime}).compatible,true);
+ assert.throws(()=>previewPackage({...example(),id:'unscoped'},{runtime}));assert.throws(()=>previewPackage({...example(),version:'latest'},{runtime}));
+ assert.equal(versionAtLeast('1.10.0','1.9.9'),true);assert.equal(versionAtLeast('1.1.91','2.0.0'),false);
+});
+test('preview refuses oversized documents and collects onFailure side effects',()=>{
+ assert.throws(()=>previewPackage(' '.repeat(1024*1024+1)));
+ const p=example();p.task.onFailure=[{op:'account.forEach',switch:true,steps:[{op:'session.create',message:'hello'}]}];
+ const result=previewPackage(p,{runtime});assert.ok(result.analysis.effects.includes('account-switch'));assert.ok(result.analysis.effects.includes('send-message'));
+});
+test('same-schema tasks also stop on version downgrade or missing capabilities',async()=>{
+ automation.configureAutomationRuntime(runtime);
+ const task=previewPackage(example(),{runtime}).task;assert.equal(automation.isTaskCompatible(task),true);
+ automation.configureAutomationRuntime({...runtime,version:'1.0.0'});
+ assert.equal(automation.isTaskCompatible(task),false);assert.equal(automation.taskMatchesEvent({...task,enabled:true},'panelOpened'),false);
+ await assert.rejects(automation.executeTask(task),/不兼容/);
+ automation.configureAutomationRuntime({});
+});
+test('unknown events are preserved and blocked instead of becoming manual tasks',()=>{
+ const task=automation.normalizeTask({id:'future-event',trigger:{type:'futureEvent'},steps:[]});
+ assert.equal(task.trigger.type,'futureEvent');assert.equal(automation.isTaskCompatible(task),false);assert.equal(automation.canManuallyRunTask(task),false);
+});
+test('JSON request data is not mistaken for executable steps',()=>{
+ const p=example();p.task.steps=[{op:'http.request',url:'https://example.com',body:{op:'future.send'}}];
+ const result=previewPackage(p,{runtime});assert.equal(result.compatible,true);assert.ok(!result.analysis.capabilities.includes('future.send'));assert.deepEqual(result.analysis.effects,['network']);
+});
+test('published example previews successfully and never enables itself',()=>{
+ const p=previewPackage(fs.readFileSync(path.join(__dirname,'../examples/automation-packages/account-summary.workdaddy.json')),{runtime});
+ assert.equal(p.compatible,true);assert.equal(p.task.enabled,false);assert.equal(p.task.requires.minWorkDaddyVersion,'1.1.91');
+});
+test('a future larger task list is not truncated by editing another task',()=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-task-list-'));
+ try{
+ const tasks=Array.from({length:201},(_,i)=>({schemaVersion:2,id:'future_'+i,steps:[]}));
+ fs.writeFileSync(path.join(dir,'automations.json'),JSON.stringify(tasks));
+ const read=automation.readAutomations(dir);assert.equal(read.length,201);automation.writeAutomations(dir,read);
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir,'automations.json'))),tasks);
+ }finally{fs.rmSync(dir,{recursive:true,force:true});}
+});
+test('a package cannot be silently unwrapped by the executable task or Agent inbox',()=>{
+ assert.throws(()=>automation.validateTask(example()),/不能作为本地任务/);
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-package-inbox-'));
+ try{
+ const paths=automation.agentBridgePaths(dir);fs.mkdirSync(paths.inboxDir,{recursive:true});
+ fs.writeFileSync(path.join(paths.inboxDir,'external.json'),JSON.stringify(example()));
+ const results=automation.importAgentInbox(dir,{settleMs:0});assert.equal(results[0].ok,false);assert.deepEqual(automation.readAutomations(dir),[]);
+ }finally{fs.rmSync(dir,{recursive:true,force:true});}
+});
+test('example index pins the exact package bytes',()=>{
+ const dir=path.join(__dirname,'../examples/automation-packages');const index=JSON.parse(fs.readFileSync(path.join(dir,'workdaddy-automations.json')));
+ const item=index.items[0],p=previewPackage(fs.readFileSync(path.join(dir,item.path)),{runtime});
+ assert.equal(item.sha256,p.sha256);assert.equal(item.id,p.package.id);assert.equal(item.version,p.package.version);
+});
+test('UTF-8 BOM files from Windows retain their byte hash and preview correctly',()=>{
+ const text=JSON.stringify(example()),a=previewPackage(text,{runtime}),b=previewPackage('\uFEFF'+text,{runtime});
+ assert.equal(b.compatible,true);assert.notEqual(a.sha256,b.sha256);
+});
diff --git a/test/automation-panel-input.test.js b/test/automation-panel-input.test.js
new file mode 100644
index 0000000..52f35a6
--- /dev/null
+++ b/test/automation-panel-input.test.js
@@ -0,0 +1,34 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'),path=require('node:path');
+const daemon=fs.readFileSync(path.join(__dirname,'../scripts/daemon.js'),'utf8');
+const ui=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');
+
+test('panel opening is blocked only during input; waiting for a reply still allows access',()=>{
+ const calls=[];const noop=()=>{};
+ const ctx={window:{__wbsAutomationInputActive:true},state:{open:false},root:{},panel:{classList:{toggle:noop}},fab:{classList:{toggle:noop}},CAPS:{accounts:false},fabQuietMode:{wake:noop},toast:()=>calls.push('blocked'),refresh:()=>calls.push('refresh'),checkForUpdate:noop,acCheckPromptOnOpen:noop,syncSessionModule:noop,api:()=>Promise.resolve()};
+ const start=ui.indexOf(' function setOpen(open, options)');
+ vm.runInNewContext(ui.slice(start,ui.indexOf(' function setupFabDrag()',start)),ctx);
+ ctx.setOpen(true);assert.equal(ctx.state.open,false);assert.deepEqual(calls,['blocked']);
+ ctx.window.__wbsAutomationInputActive=false;ctx.setOpen(true);assert.equal(ctx.state.open,true);assert.deepEqual(calls,['blocked','refresh']);
+});
+
+for(const fails of [false,true])test('input lease closes an opened panel and releases protection on '+(fails?'failure':'success'),async()=>{
+ const calls=[];
+ const ctx={requiresLease:true,run:{wasPanelOpen:false},isCancelled:()=>false,acquireAutomationInput:async()=>()=>calls.push('release'),automationPanelIsOpen:async()=>true,automationPanelSetInputActive:async active=>calls.push(active?'lock':'unlock')};
+ const start=daemon.indexOf(' const withInput = async');
+ vm.runInNewContext(daemon.slice(start,daemon.indexOf(' let lastReceipt',start))+'this.withInput=withInput;',ctx);
+ const fn=async()=>{calls.push('input');if(fails)throw Error('input failure');return 42};
+ if(fails)await assert.rejects(ctx.withInput(fn),/input failure/);else assert.equal(await ctx.withInput(fn),42);
+ assert.deepEqual(calls,['lock','input','unlock','release']);assert.equal(ctx.run.wasPanelOpen,true);
+});
+
+test('reinjection synchronizes input protection and an interrupted run can unlock the same renderer',async()=>{
+ const events=[];const renderer={window:{__wbsAutomationInputActive:true,dispatchEvent:e=>events.push(e)},CustomEvent:function(type,options){this.type=type;this.detail=options.detail}};
+ const ctx={cdp:{connected:true},automationInputActive:false,cdpSend:async(_,params)=>{vm.runInNewContext(params.expression,renderer);return {}}};
+ const start=daemon.indexOf('function automationPanelSetInputActive(');
+ vm.runInNewContext(daemon.slice(start,daemon.indexOf('function automationPanelSetOpen(',start)),ctx);
+ await ctx.automationPanelSetInputActive(false);assert.equal(renderer.window.__wbsAutomationInputActive,false);
+ await ctx.automationPanelSetInputActive(true);assert.equal(renderer.window.__wbsAutomationInputActive,true);assert.equal(events.at(-1).detail.open,false);
+ await ctx.automationPanelSetInputActive(false);assert.equal(renderer.window.__wbsAutomationInputActive,false);
+ assert.match(daemon,/await automationPanelSetInputActive\(automationInputActive\)/);
+});
diff --git a/test/automation-popup-dismiss.test.js b/test/automation-popup-dismiss.test.js
new file mode 100644
index 0000000..d50e52c
--- /dev/null
+++ b/test/automation-popup-dismiss.test.js
@@ -0,0 +1,235 @@
+'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');
+
+function runPopupTask(appearAt, failedConfirmations = 0) {
+ let now = 0;
+ const clicks = [];
+ const probes = [];
+ const notices = [];
+ const closed = new Map();
+ const context = {
+ require: require('node:module').createRequire(path.join(__dirname, '../scripts/automation.js')), module: { exports: {} },
+ setTimeout: (callback, ms) => { now += ms; callback(); },
+ };
+ vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../scripts/automation.js'), 'utf8'), context);
+ const task = JSON.parse(fs.readFileSync(path.join(__dirname, '../scripts/builtin/automations/close-buddy-popups.json'), 'utf8'));
+ const execution = context.module.exports.executeTask(task, {
+ domAction: async (op, locator) => {
+ if (op === 'dom.wait') {
+ if (failedConfirmations > 0) { failedConfirmations--; throw new Error('等待页面元素超时'); }
+ closed.set(locator.value, (closed.get(locator.value) || 0) + 1);
+ return { visible: false };
+ }
+ assert.equal(op, 'dom.click');
+ probes.push({ selector: locator.value, at: now });
+ const appearances = appearAt(locator.value);
+ const availableAt = (Array.isArray(appearances) ? appearances : [appearances])[closed.get(locator.value) || 0];
+ if (availableAt == null || now < availableAt) throw new Error('未找到页面元素');
+ clicks.push({ selector: locator.value, at: now });
+ // A click alone is not confirmation; dom.wait must confirm disappearance.
+ return { visible: true };
+ },
+ notifyToast: (_, message) => notices.push(message),
+ });
+ return execution.then(() => ({ clicks, probes, notices, elapsed: now }));
+}
+
+test('all three popup buttons are clicked immediately and only once', async () => {
+ const result = await runPopupTask(() => 0);
+ assert.equal(result.clicks.length, 3);
+ assert.ok(result.clicks.every(click => click.at === 0));
+ assert.ok(result.clicks.some(click => click.selector.includes('#fuel-compact-close')));
+ assert.ok(result.clicks.some(click => click.selector.includes('wb-related-playbooks__dismiss-today')));
+ assert.ok(result.clicks.some(click => click.selector.includes('activity-bubble__close')));
+ assert.equal(result.probes.length, 300);
+ assert.equal(result.notices.length, 3);
+ assert.equal(result.elapsed, 30000, 'continue observing for re-created popups');
+});
+
+test('absent fuel popup does not delay other popups, including one rendered later', async () => {
+ const result = await runPopupTask(selector => selector.includes('fuel-compact') ? null : selector.includes('activity-bubble') ? 1100 : 0);
+ assert.deepEqual(result.clicks.map(click => click.at), [0, 1200]);
+ assert.equal(result.notices.length, 2);
+ assert.equal(result.elapsed, 30000);
+});
+
+test('missing popup buttons finish quietly after the bounded detection window', async () => {
+ const result = await runPopupTask(() => null);
+ assert.equal(result.probes.length, 300);
+ assert.equal(result.elapsed, 30000);
+ assert.equal(result.clicks.length, 0);
+ assert.equal(result.notices.length, 0);
+});
+
+test('an ineffective click is retried and only confirmed closes are announced', async () => {
+ const result = await runPopupTask(() => 0, 1);
+ assert.equal(result.clicks.length, 4);
+ assert.equal(result.clicks.at(-1).at, 300);
+ assert.equal(result.clicks.at(-1).selector, '#fuel-compact-close');
+ assert.equal(result.notices.length, 3);
+});
+
+test('a popup recreated after a successful close is detected and closed again', async () => {
+ const result = await runPopupTask(selector => selector.includes('fuel-compact') ? [0, 900] : 0);
+ assert.deepEqual(result.clicks.filter(c => c.selector.includes('fuel-compact')).map(c => c.at), [0, 900]);
+});
+
+test('a popup arriving after the old 15-second window is still handled', async () => {
+ const result = await runPopupTask(selector => selector.includes('activity-bubble') ? 18000 : null);
+ assert.deepEqual(result.clicks.map(c => c.at), [18000]);
+});
+
+test('a newer navigation supersedes a running opt-in task instead of dropping its trigger', () => {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const start = source.indexOf('function dispatchAutomationEvent(');
+ const end = source.indexOf('\nfunction onCdpEvent(', start);
+ const running = { taskId: 'popup', status: 'running', navigationSerial: 1 };
+ const context = {
+ taskMatchesEvent: require('../scripts/automation').taskMatchesEvent,
+ automationEventKeys: new Set(), mainFrameNavigationSerial: 2,
+ automationRuns: new Map([['run', running]]), DATA_DIR: '/test',
+ readAutomations: () => [{ id: 'popup', enabled: true, trigger: { type: 'pageReady', restartOnNavigation: true } }],
+ currentAccount: () => null, log() {},
+ startAutomationRun: () => { throw Error('must let the old run settle before starting the next'); },
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ context.dispatchAutomationEvent('pageReady', { navigationSerial: 2 });
+ context.dispatchAutomationEvent('pageReady', { navigationSerial: 3 });
+ assert.equal(running.superseded, true);
+ assert.equal(running.pendingEvent.navigationSerial, 3, 'retain only the latest navigation');
+});
+
+test('queued detection resumes only for the latest page and an enabled task', () => {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const start = source.indexOf('function resumeAutomationAfterNavigation(');
+ const end = source.indexOf('\nfunction todayStr(', start);
+ const launched = [];
+ const task = { id: 'popup', enabled: true, trigger: { restartOnNavigation: true } };
+ const context = { mainFrameNavigationSerial: 3, DATA_DIR: '/test', readAutomations: () => [task], startAutomationRun: (...args) => launched.push(args) };
+ vm.runInNewContext(source.slice(start, end), context);
+ context.resumeAutomationAfterNavigation({ taskId: 'popup', pendingEvent: { navigationSerial: 2 } });
+ assert.equal(launched.length, 0);
+ const run = { taskId: 'popup', pendingEvent: { navigationSerial: 3 } };
+ context.resumeAutomationAfterNavigation(run);
+ assert.equal(launched.length, 1);
+ assert.equal(run.pendingEvent, null);
+ task.enabled = false;
+ context.resumeAutomationAfterNavigation({ taskId: 'popup', pendingEvent: { navigationSerial: 3 } });
+ assert.equal(launched.length, 1);
+});
+
+test('a running cleanup stops before the next navigation begins its own cleanup', async () => {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const task = { id: 'popup', enabled: true, trigger: { type: 'pageReady', restartOnNavigation: true } };
+ let release;
+ const active = new Promise(resolve => { release = resolve; });
+ const executions = [], restored = [];
+ const noop = () => {};
+ const context = {
+ taskIsPassiveCleanup: require('../scripts/automation').taskIsPassiveCleanup, taskMatchesEvent: require('../scripts/automation').taskMatchesEvent, taskNeedsPanelClosed: require('../scripts/automation').taskNeedsPanelClosed,
+ ...require('../scripts/automation-runtime'),
+ acquireAutomationInput: require('../scripts/automation-runtime').createRendererGate(),
+ acquireAutomationRenderer: require('../scripts/automation-runtime').createRendererGate(), primaryAccountStore:{get:()=>null},
+ crypto: require('node:crypto'), automationRuns: new Map(), automationEventKeys: new Set(),
+ mainFrameNavigationSerial: 1, DATA_DIR: '/test', cdp: {}, log: noop,
+ readAutomations: () => [task], readAutomationState: () => ({}), writeAutomationState: noop,
+ automationPanelIsOpen: async () => false, automationPanelSetOpen: open => restored.push(open),
+ listAccounts: () => [], currentAccount: () => null, automationSwitchAccount: noop,
+ automationAccountStatus: noop, automationHttpRequest: noop, automationDomAction: noop,
+ automationNotifyToast: noop, createAutomationNotifier: require('../scripts/toast-options').createAutomationNotifier,
+ executeTask: async (_, deps) => { executions.push(deps); if (executions.length === 1) await active; return {}; },
+ };
+ const dispatchStart = source.indexOf('function dispatchAutomationEvent(');
+ const dispatchEnd = source.indexOf('\nfunction onCdpEvent(', dispatchStart);
+ const runStart = source.indexOf('function startAutomationRun(');
+ const runEnd = source.indexOf('\nfunction todayStr(', runStart);
+ vm.runInNewContext(source.slice(dispatchStart, dispatchEnd) + '\n' + source.slice(runStart, runEnd), context);
+ const first = context.startAutomationRun(task, { type: 'pageReady', navigationSerial: 1 });
+ await Promise.resolve(); await Promise.resolve();
+ assert.equal(executions.length, 1);
+ context.mainFrameNavigationSerial = 2;
+ context.dispatchAutomationEvent('pageReady', { navigationSerial: 2 });
+ assert.equal(executions[0].isCancelled(), true);
+ assert.equal(executions.length, 1);
+ release();
+ await first.completion;
+ await Promise.resolve(); await Promise.resolve();
+ assert.equal(first.status, 'cancelled');
+ assert.equal(executions.length, 2);
+ assert.equal(executions[1].event.navigationSerial, 2);
+ assert.equal(restored.length, 0, 'old cleanup must not reopen a panel on the new page');
+});
+
+test('popup selectors prefer a visible replacement over an old hidden node', () => {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const start = source.indexOf('function automationDeepLocatorExpression(');
+ const end = source.indexOf('\nasync function automationDomAction(', start);
+ const builder = {};
+ vm.runInNewContext(source.slice(start, end), builder);
+ const hidden = { getBoundingClientRect: () => ({ width: 0, height: 0 }) };
+ const visible = { getBoundingClientRect: () => ({ width: 24, height: 24 }) };
+ const document = { querySelectorAll: () => [hidden, visible], querySelector: () => hidden };
+ const result = vm.runInNewContext(builder.automationDeepLocatorExpression({ kind: 'css', value: '.close', visible: true }), { document, getComputedStyle: () => ({ display: 'block', visibility: 'visible' }) });
+ assert.equal(result, visible);
+});
+
+test('automation DOM click dispatches the located button without undefined request state', async () => {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const start = source.indexOf('async function automationDomAction(');
+ const end = source.indexOf('\nasync function automationHttpRequest(', start);
+ const clicks = [];
+ const found = { x: 10, y: 20, w: 20, h: 30, visible: true };
+ const context = {
+ cdp: { connected: true },
+ automationDeepLocatorExpression: () => 'null',
+ cdpSend: async () => ({ result: { value: found } }),
+ cdpMouseClick: async (...args) => clicks.push(args),
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ await context.automationDomAction('dom.click', { kind: 'css', value: 'button.activity-bubble__close', visible: true }, {});
+ assert.equal(clicks.length, 1);
+ assert.deepEqual(clicks[0].slice(0, 3), ['dom.click:button.activity-bubble__close', 20, 35]);
+ assert.equal(clicks[0][4].skipMove, true);
+ found.blocked = true;
+ await assert.rejects(context.automationDomAction('dom.click', { kind: 'css', value: '.close', visible: true }, {}), /遮挡/);
+ assert.equal(clicks.length, 1, 'do not click whatever is covering the close button');
+ await assert.rejects(context.automationDomAction('dom.click', { kind: 'css', value: '.close' }, { isCancelled: () => true }), /已停止/);
+ assert.equal(clicks.length, 1);
+});
+
+test('popup clicks bypass mouse-move acknowledgement while normal clicks retain hover', async () => {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const start = source.indexOf('async function cdpMouseClick(');
+ const end = source.indexOf('\nfunction cdpSend(', start);
+ const events = [];
+ const context = {
+ cdp: {}, log() {}, cdpFocusDiagnostics: async () => {},
+ cdpSend: async (_, params) => events.push(params.type),
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ await context.cdpMouseClick('popup', 20, 30, {}, { skipMove: true });
+ assert.deepEqual(events, ['mousePressed', 'mouseReleased']);
+ events.length = 0;
+ await context.cdpMouseClick('normal', 20, 30);
+ assert.deepEqual(events, ['mouseMoved', 'mousePressed', 'mouseReleased']);
+});
+
+test('waiting for a dismissed button succeeds immediately when its DOM node was removed', async () => {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const start = source.indexOf('async function automationDomAction(');
+ const end = source.indexOf('\nasync function automationHttpRequest(', start);
+ const context = {
+ cdp: { connected: true },
+ automationDeepLocatorExpression: () => 'null',
+ cdpSend: async () => ({ result: { value: null } }),
+ setTimeout: () => { throw new Error('removed node must not wait'); },
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ const result = await context.automationDomAction('dom.wait', { kind: 'css', value: '#fuel-compact-close' }, { until: { state: 'hidden' }, timeoutMs: 750 });
+ assert.equal(result.visible, false);
+});
diff --git a/test/automation-preset-distribution.test.js b/test/automation-preset-distribution.test.js
new file mode 100644
index 0000000..bf04e41
--- /dev/null
+++ b/test/automation-preset-distribution.test.js
@@ -0,0 +1,29 @@
+'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 { spawnSync } = require('node:child_process');
+
+test('release staging copies source presets even when the reusable asset shell has none', { skip: process.platform === 'win32' }, () => {
+ const repo = path.join(__dirname, '..');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-preset-stage-'));
+ try {
+ fs.mkdirSync(path.join(dir, 'scripts/builtin/automations'), { recursive: true });
+ const presets = fs.readdirSync(path.join(repo, 'scripts/builtin/automations')).filter(f => f.endsWith('.json'));
+ for (const file of presets) fs.copyFileSync(path.join(repo, 'scripts/builtin/automations', file), path.join(dir, 'scripts/builtin/automations', file));
+ for (const [script, variable, destination] of [
+ ['build-mac-dmg.sh', 'APP', 'Contents/Resources/scripts/builtin/automations'],
+ ['build-win-zip.sh', 'STAGE', 'scripts/builtin/automations'],
+ ]) {
+ const source = fs.readFileSync(path.join(repo, 'scripts', script), 'utf8');
+ const block = source.match(/mkdir -p "\$(?:APP|STAGE)\/[^"\n]*builtin\/automations"\ncp scripts\/builtin\/automations\/\*\.json [^\n]+/);
+ assert.ok(block, script + ' must stage presets from source');
+ const stage = path.join(dir, variable + ' with spaces');
+ const result = spawnSync('bash', ['-eu', '-c', block[0]], { cwd: dir, env: { ...process.env, [variable]: stage }, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ for (const file of presets) assert.equal(fs.readFileSync(path.join(stage, destination, file), 'utf8'), fs.readFileSync(path.join(repo, 'scripts/builtin/automations', file), 'utf8'));
+ }
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+});
diff --git a/test/automation-runtime.test.js b/test/automation-runtime.test.js
new file mode 100644
index 0000000..9d5c124
--- /dev/null
+++ b/test/automation-runtime.test.js
@@ -0,0 +1,57 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict');
+const {assertAccountRequestUrl,createTaskState,createRendererGate,receiptComplete}=require('../scripts/automation-runtime');
+test('account tokens never go to foreign origins, ports, credentials or HTTP',()=>{
+ for(const url of ['http://www.codebuddy.cn/a','https://www.codebuddy.cn.evil.test/a','https://www.codebuddy.cn:444/a','https://x:[email protected]/a','https://www.workbuddy.ai/a']) assert.throws(()=>assertAccountRequestUrl(new URL(url),'https://www.codebuddy.cn'));
+ assertAccountRequestUrl(new URL('https://www.workbuddy.cn/api'),'https://www.codebuddy.cn');
+});
+test('state isolates tasks/accounts and does not lose interleaved writes',async()=>{
+ let db={};const make=id=>createTaskState(id,()=>JSON.parse(JSON.stringify(db)),v=>{db=v});const a=make('a'),b=make('b');
+ await a.set('task','1','x',1);await b.set('task','1','x',2);await a.set('account','1','x',3);
+ assert.equal(await a.get('task','different','x'),1);assert.equal(await b.get('task','1','x'),2);assert.equal(await a.get('account','2','x'),undefined);
+ assert.equal(await a.get('account','1','x'),3);
+});
+test('renderer gate queues tasks and cancellation does not leak the lock',async()=>{
+ const acquire=createRendererGate();const release=await acquire(()=>false);let cancelled=false;
+ const waiting=acquire(()=>cancelled);cancelled=true;await assert.rejects(waiting,/停止/);release();
+ const next=await acquire(()=>false);next();
+});
+test('completion is bound to user request, conversation and assistant identity',()=>{
+ const receipt={conversationId:'c',userMessageId:'u',requestId:'r',baselineAssistantId:'a0'};
+ const snap={conversationId:'c',userMessageId:'u',assistantId:'a1',assistantRequestId:'r',complete:true,busy:false};
+ assert.equal(receiptComplete(receipt,snap),true);
+ assert.equal(receiptComplete(receipt,{...snap,assistantId:'a0'}),false);
+ assert.equal(receiptComplete(receipt,{...snap,busy:true}),false);
+ assert.throws(()=>receiptComplete(receipt,{...snap,userMessageId:'u2'}));
+ assert.throws(()=>receiptComplete(receipt,{...snap,conversationId:'other'}));
+ assert.throws(()=>receiptComplete(receipt,{...snap,cancelled:true}));
+});
+
+const fs=require('node:fs'),vm=require('node:vm');
+const daemon=fs.readFileSync(require('node:path').join(__dirname,'../scripts/daemon.js'),'utf8');
+function httpHarness(fetchImpl,read=()=>'{"auth":{"accessToken":"fake-test-token"}}') {
+ const scope={URL,Buffer,AbortController,setTimeout,clearTimeout,setInterval,clearInterval,fetch:fetchImpl,fs:{readFileSync:read},accountBackupFile:()=>'/fake',PROFILE:{apiHost:'https://www.codebuddy.cn'},assertAccountRequestUrl};
+ vm.runInNewContext(daemon.slice(daemon.indexOf('async function automationHttpRequest('),daemon.indexOf('\nfunction automationPublicRun(')),scope);return scope.automationHttpRequest;
+}
+test('HTTP daemon denies token access before reading backups; aborts fetch on stop',async()=>{
+ let reads=0;const blocked=httpHarness(()=>{throw Error('must not fetch')},()=>{reads++;return '{}'});
+ await assert.rejects(blocked({url:'https://untrusted.test'}, {uid:'fake'}));assert.equal(reads,0);
+ let stopped=false,aborted=false;
+ const request=httpHarness((_,{signal})=>new Promise((resolve,reject)=>signal.addEventListener('abort',()=>{aborted=true;reject(Object.assign(Error(),{name:'AbortError'}))})));
+ const pending=request({url:'https://example.com',isCancelled:()=>stopped},null);stopped=true;await assert.rejects(pending,/停止/);assert.equal(aborted,true);
+});
+test('HTTP daemon bounds streamed responses and supplies JSON content type',async()=>{
+ let headers;
+ const request=httpHarness(async(_,options)=>{headers=options.headers;return new Response(JSON.stringify({ok:true}),{status:200,headers:{'content-type':'application/json'}})});
+ const r=await request({url:'https://www.workbuddy.cn/api',body:{n:5},method:'POST'},{uid:'fake'});
+ assert.equal(r.json.ok,true);assert.equal(headers.authorization,'Bearer fake-test-token');assert.equal(headers['content-type'],'application/json');
+ const huge=httpHarness(async()=>new Response(new Uint8Array(1024*1024+1)));await assert.rejects(huge({url:'https://example.com'},null),/1 MiB/);
+});
+test('renderer receipt probe uses real messageType shape without returning private content',()=>{
+ const {probeSessionReceipt}=require('../scripts/automation-runtime');
+ const state={messages:[{messageType:'user',id:'u',requestId:'r',content:'private'},{messageType:'assistant',id:'a',requestId:'r',complete:true,extra:{isRequestTerminal:false},content:'private response'}]};
+ const compat={getSelectedConversationId:()=> 'c',findConversationControllers:()=>[{conversationId:'c',messageStore:{getState:()=>state},getSessionViewState:()=>({})}]};
+ const result=vm.runInNewContext('('+probeSessionReceipt.toString()+')()',{window:{__wbsWorkBuddyCompat:compat},document:{}});
+ assert.equal(result.userMessageId,'u');assert.equal(result.requestId,'r');assert.equal(result.complete,false,'explicit non-terminal wins over interim complete');
+ assert.ok(!JSON.stringify(result).includes('private'));
+});
diff --git a/test/automation-transfer.test.js b/test/automation-transfer.test.js
new file mode 100644
index 0000000..629654b
--- /dev/null
+++ b/test/automation-transfer.test.js
@@ -0,0 +1,86 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
+const {exportTasks,previewImport,importTasks}=require('../scripts/automation-transfer');
+const {encodeZip,decodeZip}=require('../scripts/automation-zip');
+const {readAutomations,writeAutomations}=require('../scripts/automation');
+const runtime={version:'1.1.93',profileId:'workbuddy-cn',platform:'darwin'};
+const task=(id='one')=>({schemaVersion:1,id,name:'测试任务',enabled:true,trigger:{type:'panelOpened'},schedule:{type:'daily',time:'09:00'},steps:[{op:'notify.toast',message:'Hello'}],'x-note':{keep:true}});
+function input(result){return {content:result.content,encoding:result.encoding};}
+test('single JSON and multi-task unencrypted ZIP round-trip definitions and stable IDs',()=>{
+ const tasks=[task(),task('two')];
+ const one=exportTasks(tasks,['one']);assert.match(one.filename,/\.json$/);assert.equal(one.encoding,'utf8');assert.deepEqual(JSON.parse(one.content),tasks[0]);
+ const many=exportTasks(tasks,['one','two']);assert.match(many.filename,/\.zip$/);const zip=Buffer.from(many.content,'base64');assert.equal(zip.readUInt16LE(6)&1,0);
+ const entries=decodeZip(zip);assert.equal(entries.length,2);
+ for(const result of [one,many]){const p=previewImport(input(result),[],runtime);assert.equal(p.entries.length,result.count);for(const e of p.entries){assert.equal(e.compatible,true);assert.equal(e.task.enabled,false);assert.equal(e.task.schedule.time,'09:00');assert.deepEqual(e.task['x-note'],{keep:true});}}
+});
+test('duplicate IDs skip existing tasks without overwriting or re-enabling them, including races',()=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-transfer-'));
+ try{
+ const local={...task(),name:'用户改过',enabled:false};writeAutomations(dir,[local]);
+ const payload=input(exportTasks([task(),task('two')],['one','two']));
+ const p=previewImport(payload,readAutomations(dir),runtime);assert.equal(p.entries[0].existing,true);
+ const result=importTasks(dir,{...payload,selected:['0','1']},runtime);assert.equal(result.imported,1);assert.equal(result.skipped,1);
+ assert.equal(readAutomations(dir).find(t=>t.id==='one').name,'用户改过');assert.equal(readAutomations(dir).find(t=>t.id==='two').enabled,false);
+ const before=fs.readFileSync(path.join(dir,'automations.json'));assert.equal(importTasks(dir,{...payload,selected:['1']},runtime).imported,0);assert.deepEqual(fs.readFileSync(path.join(dir,'automations.json')),before);
+ }finally{fs.rmSync(dir,{recursive:true,force:true});}
+});
+test('invalid selected task and capacity failures do not partially save',()=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-transfer-'));
+ try{
+ writeAutomations(dir,[task('existing')]);const before=fs.readFileSync(path.join(dir,'automations.json'));
+ const bytes=encodeZip([{name:'good.json',content:Buffer.from(JSON.stringify(task()))},{name:'bad.json',content:Buffer.from('{"id":"bad","steps":[{"op":"future.op"}]}')}]);
+ const payload={content:bytes.toString('base64'),encoding:'base64',selected:['0','1']};
+ assert.equal(previewImport(payload,[],runtime).entries[1].compatible,false);assert.throws(()=>importTasks(dir,payload,runtime));assert.deepEqual(fs.readFileSync(path.join(dir,'automations.json')),before);
+ writeAutomations(dir,Array.from({length:200},(_,i)=>task('existing_'+i)));assert.throws(()=>importTasks(dir,{...input(exportTasks([task()],['one'])),selected:['0']},runtime),/上限/);
+ }finally{fs.rmSync(dir,{recursive:true,force:true});}
+});
+test('JSON imports reject unrelated documents and block future schema, dependencies and missing package inputs',()=>{
+ for(const doc of [{hello:'world'},[],{kind:'workdaddy.automation-index',items:[]}]){const p=previewImport({content:JSON.stringify(doc)},[],runtime);assert.equal(p.entries[0].compatible,false);}
+ for(const doc of [{...task(),schemaVersion:2},{...task(),requires:{minWorkDaddyVersion:'9.0.0',taskSchemaVersion:1,capabilities:[]}}])assert.equal(previewImport({content:JSON.stringify(doc)},[],runtime).entries[0].compatible,false);
+ const pkg=JSON.parse(fs.readFileSync(path.join(__dirname,'../examples/automation-packages/account-summary.workdaddy.json')));
+ const p=previewImport({content:JSON.stringify(pkg)},[],runtime);assert.equal(p.entries[0].compatible,true);assert.notEqual(p.entries[0].task.id,'package_preview');assert.equal(p.entries[0].task.enabled,false);
+ pkg.inputs.requiredValue={type:'string',required:true};assert.equal(previewImport({content:JSON.stringify(pkg)},[],runtime).entries[0].compatible,false);
+});
+test('ZIP rejects traversal, encryption, corrupt CRC and zip bombs; accepts deflate and harmless Mac metadata',()=>{
+ const good=encodeZip([{name:'one.json',content:Buffer.from(JSON.stringify(task()))}]);
+ const corrupt=Buffer.from(good);corrupt[30+Buffer.byteLength('one.json')]^=1;assert.throws(()=>decodeZip(corrupt));
+ const encrypted=Buffer.from(good);encrypted.writeUInt16LE(1,6);assert.throws(()=>decodeZip(encrypted));
+ const central=good.indexOf(Buffer.from('504b0102','hex'));const bomb=Buffer.from(good);bomb.writeUInt32LE(0x7fffffff,central+24);assert.throws(()=>decodeZip(bomb));
+ assert.throws(()=>encodeZip([{name:'../x.json',content:Buffer.from('{}')}]));
+ const meta=encodeZip([{name:'__MACOSX/._one.json',content:Buffer.from('metadata')},{name:'one.json',content:Buffer.from(JSON.stringify(task()))}]);assert.equal(previewImport({content:meta.toString('base64'),encoding:'base64'},[],runtime).entries.length,1);
+ assert.throws(()=>previewImport({content:'a'.repeat(12*1024*1024),encoding:'base64'},[],runtime));
+ const zlib=require('node:zlib');const plain=Buffer.from(JSON.stringify(task()));const compressed=zlib.deflateRawSync(plain);const stored=encodeZip([{name:'one.json',content:plain}]);const offset=30+8,cd=offset+plain.length;
+ const head=Buffer.from(stored.subarray(0,offset)),tail=Buffer.from(stored.subarray(cd));head.writeUInt16LE(8,8);head.writeUInt32LE(compressed.length,18);tail.writeUInt16LE(8,10);tail.writeUInt32LE(compressed.length,20);tail.writeUInt32LE(offset+compressed.length,tail.length-6);
+ assert.deepEqual(decodeZip(Buffer.concat([head,compressed,tail]))[0].content,plain);
+});
+test('export requires exact selected IDs and excludes UI-only flags',()=>{
+ assert.throws(()=>exportTasks([task()],[]));assert.throws(()=>exportTasks([task()],['missing']));
+ const output=JSON.parse(exportTasks([{...task(),manualRunnable:true,compatible:true}],['one']).content);assert.equal(output.compatible,undefined);assert.equal(output.manualRunnable,undefined);
+});
+test('file request reader bounds payloads and rejects malformed JSON',async()=>{
+ const {readTransferBody}=require('../scripts/automation-transfer'),{PassThrough}=require('node:stream');
+ const valid=new PassThrough(),parsed=readTransferBody(valid);valid.end('{"content":"{}"}');assert.deepEqual(await parsed,{content:'{}'});
+ const bad=new PassThrough(),invalid=readTransferBody(bad);bad.end('{');await assert.rejects(invalid,/编码/);
+ const large=new PassThrough(),oversize=readTransferBody(large);large.end(Buffer.alloc(12*1024*1024+1));await assert.rejects(oversize,/8 MiB/);
+});
+test('transfer endpoints preserve atomic import and remain separate from task execution routes',async()=>{
+ const source=fs.readFileSync(path.join(__dirname,'../scripts/daemon.js'),'utf8');
+ const begin=source.indexOf(" if (req.method === 'POST' && ['/api/automations/export'");
+ const end=source.indexOf(" if (req.method === 'POST' && p === '/api/automations/packages/preview')",begin);
+ const route=new Function('req','p','res','readTransferBody','exportTasks','previewImport','importTasks','readAutomations','DATA_DIR','DAEMON_VERSION','PROFILE','json',source.slice(begin,end));
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wd-transfer-route-'));
+ const call=(p,body)=>route({method:'POST'},p,{},async()=>body,exportTasks,previewImport,importTasks,readAutomations,dir,runtime.version,{id:runtime.profileId},(_,status,data)=>({status,...data}));
+ try{
+ writeAutomations(dir,[task()]);
+ const file=await call('/api/automations/export',{ids:['one']});assert.equal(file.status,200);
+ const preview=await call('/api/automations/import/preview',input(file));assert.equal(preview.executed,false);assert.equal(preview.entries[0].existing,true);
+ const saved=await call('/api/automations/import',{...input(file),selected:['0']});assert.equal(saved.imported,0);assert.equal(saved.skipped,1);
+ const invalid=await call('/api/automations/export',{ids:['missing']});assert.equal(invalid.status,400);
+ }finally{fs.rmSync(dir,{recursive:true,force:true});}
+});
+test('import dialog preserves user-authored names in English and overrides generic modal width',()=>{
+ const source=fs.readFileSync(path.join(__dirname,'../scripts/inject.js'),'utf8');
+ assert.match(source,/class="wbs-auto-import-name" data-wbs-i18n-skip="1"/);
+ assert.match(source,/class="wbs-auto-import-file" data-wbs-i18n-skip="1"/);
+ assert.match(source,/\.wbs-modal\.wbs-auto-import-modal\{width:calc\(100% - 24px\);max-width:480px/);
+});
diff --git a/test/automation.test.js b/test/automation.test.js
new file mode 100644
index 0000000..13a4d27
--- /dev/null
+++ b/test/automation.test.js
@@ -0,0 +1,300 @@
+'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 {
+ normalizeTask,
+ validateTask,
+ executeTask,
+ CAPABILITIES,
+ SUPPORTED_OPS,
+ AGENT_EXAMPLES,
+ capabilityText,
+ agentBridgePaths,
+ ensureAgentBridge,
+ createAgentRequest,
+ importAgentInbox,
+ readAutomations,
+ writeAutomations,
+} = require('../scripts/automation.js');
+
+test('automation tasks normalize lifecycle triggers and expose examples', () => {
+ const task = normalizeTask({ id: 'demo', name: 'demo', trigger: { type: 'pageLoaded' }, steps: [] });
+ assert.equal(task.trigger.type, 'pageLoaded');
+ assert.equal(task.trigger.oncePerNavigation, true);
+ assert.equal(normalizeTask({ id: 'ready', name: 'ready', trigger: { type: 'pageReady' }, steps: [] }).trigger.type, 'pageReady');
+ assert.ok(CAPABILITIES.some((item) => item.id === 'event.pageReady'));
+ assert.ok(CAPABILITIES.some((item) => item.id === 'event.pageLoaded'));
+ assert.ok(CAPABILITIES.some((item) => item.id === 'event.accountSwitched'));
+});
+
+test('automation execution exposes lifecycle event and account context to steps', async () => {
+ const seen = [];
+ const task = validateTask({
+ id: 'event-context', name: 'event-context', trigger: { type: 'accountSwitched' },
+ steps: [{ op: 'state.set', key: 'eventType', value: '{{event.type}}' }, { op: 'state.set', key: 'uid', value: '{{account.uid}}' }],
+ });
+ const result = await executeTask(task, {
+ event: { type: 'accountSwitched', account: { uid: 'u1', nickname: 'Demo' } },
+ setState: async (_scope, _uid, key, value) => seen.push([key, value]),
+ });
+ assert.deepEqual(seen, [['eventType', 'accountSwitched'], ['uid', 'u1']]);
+ assert.equal(result.context.account.uid, 'u1');
+});
+
+test('account loops can physically switch each account and restore the original', async () => {
+ const accounts = [{ uid: 'a', nickname: 'A' }, { uid: 'b', nickname: 'B' }];
+ const switched = [];
+ let active = accounts[0];
+ const task = validateTask({
+ id: 'physical-account-loop', name: 'physical-account-loop', steps: [{
+ op: 'account.forEach', accounts: 'all', switch: true,
+ steps: [{ op: 'state.set', scope: 'account', key: 'visited', value: '{{account.uid}}' }],
+ }],
+ });
+ await executeTask(task, {
+ listAccounts: async () => accounts,
+ currentAccount: async () => active,
+ accountSwitch: async (account) => { switched.push(account.uid); active = account; },
+ setState: async () => {},
+ });
+ assert.deepEqual(switched, ['a', 'b', 'a']);
+ assert.equal(active.uid, 'a');
+});
+
+test('capability protocol documents every supported step and rejects event ids as steps', () => {
+ const documented = new Set(CAPABILITIES.map((item) => item.id));
+ for (const op of SUPPORTED_OPS) assert.equal(documented.has(op), true, `missing capability documentation for ${op}`);
+ assert.match(capabilityText('zh'), /WorkDaddy 自动化任务协议 v1/);
+ assert.match(capabilityText('en'), /WorkDaddy Automation Task Protocol v1/);
+ assert.match(capabilityText('zh'), /基础接口总目录:[\s\S]*logic:[\s\S]*account:[\s\S]*http:[\s\S]*dom:[\s\S]*session:[\s\S]*state:[\s\S]*notify:/);
+ assert.match(capabilityText('zh'), /HTTP 输入:[\s\S]*响应:\{ok,status,headers,text,json\}/);
+ assert.match(capabilityText('en'), /Capability index:[\s\S]*Per-operation reference and minimal examples:/);
+ assert.throws(() => validateTask({ id: 'bad-event-step', name: 'bad', steps: [{ op: 'event.pageLoaded' }] }), /不支持能力/);
+ assert.throws(() => validateTask({ id: 'reserved-step', name: 'bad', steps: [{ op: 'notify.session', message: 'done' }] }), /不支持能力/);
+});
+
+test('switch and catch capabilities execute their documented branches', async () => {
+ const values = [];
+ const task = {
+ id: 'logic-branches', name: 'logic-branches', variables: { code: 200 },
+ steps: [
+ { op: 'logic.switch', value: '{{vars.code}}', cases: { 200: [{ op: 'state.set', key: 'branch', value: 'ok' }] }, default: [] },
+ { op: 'logic.catch', steps: [{ op: 'logic.assert', condition: { left: false, operator: 'truthy' }, message: 'expected' }], onError: [{ op: 'state.set', key: 'caught', value: '{{vars.error.message}}' }] },
+ ],
+ };
+ await executeTask(task, { setState: async (_scope, _uid, key, value) => values.push([key, value]) });
+ assert.deepEqual(values, [['branch', 'ok'], ['caught', 'expected']]);
+});
+
+test('automation execution records step-level failures even when logic.catch handles them', async () => {
+ const logs = [];
+ const result = await executeTask({
+ id: 'step-logs', name: 'step logs',
+ steps: [{ op: 'logic.catch', steps: [{ op: 'logic.assert', condition: { left: false, operator: 'truthy' }, message: 'expected failure' }], onError: [] }],
+ }, { log: (message) => logs.push(message) });
+ assert.equal(result.result.ok, false);
+ assert.ok(logs.some((line) => /step:start:\d+:logic\.assert/.test(line)));
+ assert.ok(logs.some((line) => /step:error:\d+:logic\.assert:expected failure/.test(line)));
+ assert.ok(logs.some((line) => /step:complete:\d+:logic\.catch/.test(line)));
+});
+
+test('automation panel uses its published picker and wider protocol surfaces', () => {
+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ const paneStart = inject.indexOf('function buildAutomationPane()');
+ const paneEnd = inject.indexOf('// ===== 会话 pane', paneStart);
+ const pane = inject.slice(paneStart, paneEnd);
+ assert.match(pane, /window\.__wbsStartAutomationPicker\(\)/);
+ assert.doesNotMatch(pane, /window\.__wbsStartPicked\(\)/);
+ assert.doesNotMatch(pane, /document\.addEventListener\('mousemove'/);
+ assert.match(pane, /wbs-auto-protocol/);
+ assert.match(inject, /\.wbs-modal\.wbs-auto-cap-modal\{[^}]*width:calc\(100% - 24px\)/);
+ assert.doesNotMatch(inject, /['"]\.wbs-auto-cap-modal\{/);
+ assert.match(inject, /\.wbs-panel\{[^}]*width:720px/);
+ assert.match(inject, /data-wbs-language="en"\] \.wbs-panel\{width:880px/);
+});
+
+test('automation panel uses compact controls and preserves page-ready editing', () => {
+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ const paneStart = inject.indexOf('function buildAutomationPane()');
+ const paneEnd = inject.indexOf('// ===== 会话 pane', paneStart);
+ const pane = inject.slice(paneStart, paneEnd);
+ assert.match(pane, /data-auto-enabled=/);
+ assert.match(pane, /wbs-auto-pick-btn/);
+ assert.match(pane, /data-auto-field="trigger"/);
+ assert.match(pane, /value="pageReady"/);
+ assert.doesNotMatch(pane, /id="wbs-auto-refresh"/);
+ assert.doesNotMatch(pane, /wbs-auto-runstate/);
+ assert.match(pane, /id="wbs-auto-batch-apply"/);
+ assert.match(pane, /id="wbs-auto-select-all"/);
+ assert.match(pane, /id="wbs-auto-clear-logs"/);
+ assert.doesNotMatch(pane, /wbs-auto-log-note/);
+ assert.match(pane, /任务已启用/);
+ assert.match(pane, /is-running/);
+ assert.match(pane, /aria-busy="true"/);
+ assert.match(pane, /item\.status === 'running'/);
+});
+
+test('agent bridge materializes complete bilingual protocol files in the persistent profile directory', () => {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-automation-agent-'));
+ try {
+ const paths = ensureAgentBridge(dataDir, { profileId: 'workbuddy-cn' });
+ assert.deepEqual(paths, agentBridgePaths(dataDir));
+ assert.equal(fs.readFileSync(paths.protocolZh, 'utf8'), capabilityText('zh') + '\n');
+ assert.equal(fs.readFileSync(paths.protocolEn, 'utf8'), capabilityText('en') + '\n');
+ assert.match(fs.readFileSync(paths.guide, 'utf8'), /inbox[\s\S]*results[\s\S]*不要直接修改 automations\.json/);
+ assert.equal(fs.statSync(paths.inboxDir).isDirectory(), true);
+ assert.equal(fs.statSync(paths.resultsDir).isDirectory(), true);
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('agent inbox validates and imports one task without overwriting an existing id', () => {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-automation-inbox-'));
+ try {
+ const paths = ensureAgentBridge(dataDir, { profileId: 'workbuddy-cn' });
+ writeAutomations(dataDir, [{ id: 'existing', name: 'Existing', steps: [] }]);
+ fs.writeFileSync(path.join(paths.inboxDir, 'request-ok.json'), JSON.stringify({
+ id: 'agent-created', name: 'Agent created', trigger: { type: 'manual' }, steps: [{ op: 'logic.delay', ms: 1 }],
+ }));
+ const imported = importAgentInbox(dataDir, { settleMs: 0 });
+ assert.deepEqual(imported.map((item) => [item.requestId, item.ok, item.taskId]), [['request-ok', true, 'agent-created']]);
+ assert.equal(readAutomations(dataDir).some((task) => task.id === 'agent-created'), true);
+ assert.equal(JSON.parse(fs.readFileSync(path.join(paths.resultsDir, 'request-ok.json'), 'utf8')).ok, true);
+ assert.equal(fs.existsSync(path.join(paths.inboxDir, 'request-ok.json')), false);
+
+ fs.writeFileSync(path.join(paths.inboxDir, 'request-duplicate.json'), JSON.stringify({ id: 'existing', name: 'Overwrite', steps: [] }));
+ const duplicate = importAgentInbox(dataDir, { settleMs: 0 });
+ assert.equal(duplicate[0].ok, false);
+ assert.match(duplicate[0].error, /已存在/);
+ assert.equal(readAutomations(dataDir).find((task) => task.id === 'existing').name, 'Existing');
+
+ fs.writeFileSync(path.join(paths.inboxDir, 'request-duplicate.json'), JSON.stringify({ id: 'retry-with-new-id', name: 'Fixed', steps: [] }));
+ const retried = importAgentInbox(dataDir, { settleMs: 0 });
+ assert.equal(retried[0].ok, true);
+ assert.equal(retried[0].taskId, 'retry-with-new-id');
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('agent examples produce a one-time prompt with exact local protocol, inbox and result paths', () => {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-automation-prompt-'));
+ try {
+ const request = createAgentRequest(dataDir, { exampleId: 'page-loaded-notice', language: 'zh', profileId: 'workbuddy-cn', now: 1700000000000 });
+ assert.equal(AGENT_EXAMPLES.length >= 1, true);
+ assert.match(request.prompt, /剩余积分和连续活跃天数/);
+ assert.equal(AGENT_EXAMPLES.some((example) => example.id === 'close-buddy-fuel'), false);
+ assert.match(request.prompt, new RegExp(request.protocolPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
+ assert.match(request.prompt, new RegExp(request.inboxFile.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
+ assert.match(request.prompt, new RegExp(request.resultFile.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
+ assert.equal(path.dirname(request.inboxFile), agentBridgePaths(dataDir).inboxDir);
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ }
+});
+
+test('automation storage is profile-isolated and uninstallers preserve it by default', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-automation-profiles-'));
+ try {
+ const cnDir = path.join(root, 'WorkDaddy');
+ const aiDir = path.join(root, 'WorkDaddy', 'profiles', 'workbuddy-ai');
+ writeAutomations(cnDir, [{ id: 'cn-only', name: 'CN', steps: [] }]);
+ writeAutomations(aiDir, [{ id: 'ai-only', name: 'AI', steps: [] }]);
+ assert.deepEqual(readAutomations(cnDir).map((task) => task.id), ['cn-only']);
+ assert.deepEqual(readAutomations(aiDir).map((task) => task.id), ['ai-only']);
+ const macUninstall = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'uninstall.sh'), 'utf8');
+ const winUninstall = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'uninstall-win.ps1'), 'utf8');
+ assert.match(macUninstall, /备份数据保留在/);
+ assert.match(winUninstall, /默认保留备份数据/);
+ assert.match(winUninstall, /if \(\$RemoveData\)/);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('automation examples use the guarded new-agent-task route and refresh imported tasks continuously', () => {
+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+ assert.match(inject, /wbs-auto-examples/);
+ assert.match(inject, /\/api\/automations\/agent-generate/);
+ assert.match(inject, /automationState\.pollTimer = setInterval\(load, 2500\)/);
+ assert.match(daemon, /async function openNewAutomationAgentTask/);
+ assert.match(daemon, /conversation-list-tab-button\.active/);
+ assert.match(daemon, /workspace-new-task-button/);
+ assert.match(daemon, /拒绝发送到当前会话/);
+ assert.match(daemon, /data-slate-placeholder/);
+ assert.match(daemon, /data-slate-zero-width/);
+ assert.match(daemon, /await sendStashToComposer\(\{ content: \{ text, items: \[\] \} \}\)/);
+ assert.match(daemon, /window\.__wbsNotifyToast/);
+ assert.match(inject, /workdaddy:automation-toast/);
+});
+
+test('automation session sends only after entering the WorkBuddy new-task surface', () => {
+ const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ assert.match(daemon, /conversation-list-tab-button-box/);
+ assert.match(daemon, /async function ensureAutomationNewTask\(options = \{\}\)/);
+ assert.match(daemon, /if \(op === 'session.create'\) await withInput\(\(\) => ensureAutomationNewTask\(\{ guard:/);
+ assert.match(daemon, /newTaskReady/);
+ assert.match(daemon, /if\(!newTaskReady\)\{/);
+ assert.match(inject, /data-auto-stop/);
+ assert.match(inject, /autoActionPending/);
+ assert.match(inject, /\.wbs-auto-icon\.is-running[^}]*opacity:1/);
+});
+
+test('automation DOM locators traverse open shadow roots and task rows expose logs', () => {
+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+ assert.match(daemon, /function automationDeepLocatorExpression/);
+ assert.match(daemon, /element\.shadowRoot/);
+ assert.match(daemon, /element\.contentDocument/);
+ assert.match(inject, /data-auto-logs/);
+ assert.match(inject, /function showAutomationLogs/);
+ assert.match(inject, /wbs-auto-log-modal/);
+ assert.match(inject, /api\('\/api\/automations\/logs\/clear'/);
+ assert.match(daemon, /p === '\/api\/automations\/logs\/clear'/);
+ assert.match(daemon, /async function acSendPhrase\(text, options = \{\}\)/);
+});
+
+test('automation send uses a trusted Enter submit path and running rows expose stop actions', () => {
+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+ assert.match(daemon, /async function acSendPhrase\(text, options = \{\}\)[\s\S]*sendStashToComposer/);
+ assert.match(daemon, /button\.cr-send-button/);
+ assert.match(daemon, /sessionWaitReply = async detail => sessionAction\('session.wait'/);
+ assert.match(inject, /AUTO_STOP_SVG/);
+ assert.match(inject, /data-auto-stop/);
+ assert.match(inject, /\/api\/automations\/stop/);
+});
+
+test('automation deep locator expression compiles and finds an element inside an open shadow root', () => {
+ const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+ const match = daemon.match(/function automationDeepLocatorExpression\(locator\) \{([\s\S]*?)\n\}\nasync function automationDomAction/);
+ assert.ok(match, 'missing automationDeepLocatorExpression');
+ const buildExpression = new Function('locator', match[1]);
+ const expression = buildExpression({ kind: 'css', value: '#fuel-compact-close' });
+ assert.doesNotThrow(() => new vm.Script(expression));
+
+ const target = { id: 'fuel-compact-close' };
+ const shadowRoot = { querySelectorAll: () => [], querySelector: (selector) => selector === '#fuel-compact-close' ? target : null };
+ const document = { querySelectorAll: () => [{ tagName: 'DIV', shadowRoot }], querySelector: () => null };
+ assert.equal(vm.runInNewContext(expression, { document }), target);
+});
+
+test('automation task editor is a modal and is not rendered below example prompts', () => {
+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+ const paneStart = inject.indexOf('function buildAutomationPane()');
+ const paneEnd = inject.indexOf('// ===== 会话 pane', paneStart);
+ const pane = inject.slice(paneStart, paneEnd);
+ assert.match(pane, /mask\.id = 'wbs-auto-editor-mask'/);
+ assert.match(pane, /wbs-modal wbs-auto-editor-modal/);
+ const htmlStart = pane.indexOf('automationPane.innerHTML =');
+ const htmlEnd = pane.indexOf("automationPane.querySelector('#wbs-auto-new')", htmlStart);
+ assert.doesNotMatch(pane.slice(htmlStart, htmlEnd), /wbs-auto-editor/);
+});
diff --git a/test/cdp-focus-diagnostics.test.js b/test/cdp-focus-diagnostics.test.js
new file mode 100644
index 0000000..72ac4ec
--- /dev/null
+++ b/test/cdp-focus-diagnostics.test.js
@@ -0,0 +1,25 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+
+test('CDP diagnostics capture target, viewport, focus and mouse coordinates before clicks', () => {
+ assert.match(daemon, /function cdpFocusDiagnostics\(/);
+ assert.match(daemon, /document\.activeElement/);
+ assert.match(daemon, /window\.innerWidth/);
+ assert.match(daemon, /cdp-focus-diagnostics/);
+ assert.match(daemon, /clickByText:before-mouse/);
+ assert.match(daemon, /Input\.dispatchMouseEvent/);
+ assert.match(daemon, /async function cdpMouseClick\(/);
+ assert.match(daemon, /automation:ensureNewTask/);
+ assert.match(daemon, /automation:sendPhrase/);
+});
+
+test('automation lifecycle diagnostics record panel and task boundaries', () => {
+ assert.match(daemon, /automation-focus-diagnostics/);
+ assert.match(daemon, /automation:start/);
+ assert.match(daemon, /automation:panel-close/);
+ assert.match(daemon, /automation:finish/);
+});
diff --git a/test/checkin-schedule.test.js b/test/checkin-schedule.test.js
index 31668f0..9556f1e 100644
--- a/test/checkin-schedule.test.js
+++ b/test/checkin-schedule.test.js
@@ -1,30 +1,22 @@
'use strict';
-
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
-
const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
-const refresh = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'token-refresh.js'), 'utf8');
-
-test('daemon checks in shortly after startup and hourly thereafter', () => {
- assert.match(daemon, /const CHECKIN_STARTUP_DELAY_MS = 30 \* 1000;/);
- assert.match(daemon, /const CHECKIN_INTERVAL_MS = 60 \* 60 \* 1000;/);
- assert.match(daemon, /startupCheckinTimer = setTimeout\([\s\S]*?CHECKIN_STARTUP_DELAY_MS\);/);
- assert.match(daemon, /periodicCheckinTimer = setInterval\([\s\S]*?CHECKIN_INTERVAL_MS\);/);
- assert.doesNotMatch(daemon, /claimDailyForAll[\s\S]{0,180}3 \* 60 \* 60 \* 1000/);
-});
-test('check-in timers do not keep the daemon alive', () => {
- assert.match(daemon, /startupCheckinTimer\.unref && startupCheckinTimer\.unref\(\);/);
- assert.match(daemon, /periodicCheckinTimer\.unref && periodicCheckinTimer\.unref\(\);/);
+test('automation task owns startup, panel-open and hourly check-in triggers', () => {
+ const preset = require('../scripts/builtin/automations/daily-account-checkin.json');
+ assert.deepEqual(preset.trigger.types, ['clientLoaded', 'panelOpened']);
+ assert.deepEqual(preset.schedule, { type: 'interval', minutes: 60 });
+ assert.match(daemon, /installBuiltinTask\(DATA_DIR/);
+ assert.match(daemon, /automationScheduleTimer\.unref && automationScheduleTimer\.unref\(\)/);
+ assert.doesNotMatch(daemon, /startupCheckinTimer|periodicCheckinTimer|claimDailyForAll/);
});
-test('check-in path refreshes backup tokens lazily and runs daily keepalive', () => {
- assert.match(daemon, /refreshAccountBackupToken\(uid\)/);
- assert.match(daemon, /refreshAccountBackupToken\(uid, \{ dailyKeepalive: true \}\)/);
- assert.match(refresh, /auth\/token\/refresh/);
- assert.match(daemon, /lastRefreshTime/);
- assert.match(daemon, /1\.1\.34/);
+test('check-in refreshes expired credentials only after checking confirmed daily records', () => {
+ const body = daemon.slice(daemon.indexOf('async function performAccountCheckin'), daemon.indexOf('/** 通过 CDP 把右下角组件'));
+ assert.ok(body.indexOf('getDailyCheckin') < body.indexOf('refreshAccountBackupToken(uid)'));
+ assert.ok(body.indexOf('return migrated') < body.indexOf('refreshAccountBackupToken(uid)'));
+ assert.doesNotMatch(body, /dailyKeepalive/);
});
diff --git a/test/completion-report.test.js b/test/completion-report.test.js
new file mode 100644
index 0000000..65c03b7
--- /dev/null
+++ b/test/completion-report.test.js
@@ -0,0 +1,60 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { runCompletionReport } = require('../scripts/completion-report');
+function fixture(overrides = {}) {
+ let time = 0, sends = [];
+ return { sends, options: { primaryUid: () => 'primary', currentAccount: () => ({ uid: 'worker', nickname: '测试' }),
+ snapshot: async () => ({ known: true, sessions: [{ id: 'one', status: 'completed', busy: false }] }),
+ send: async (uid, message) => { sends.push({ uid, message }); return { conversationId: 'cloud' }; },
+ now: () => time, wait: async ms => { time += ms; }, isCancelled: () => false, ...overrides } };
+}
+test('missing primary and current primary skip without inspection or sending', async () => {
+ for (const uid of ['', 'worker']) {
+ const f = fixture({ primaryUid: () => uid, snapshot: () => { throw Error('must not inspect'); } });
+ assert.equal((await runCompletionReport(f.options)).skipped, true); assert.equal(f.sends.length, 0);
+ }
+});
+test('waits for pending/background work, then sends once to captured primary', async () => {
+ let scans = 0;
+ const f = fixture({ snapshot: async () => ({ known: true, sessions: [{ id: 'one', status: ++scans < 3 ? 'pending' : 'completed', busy: scans < 3 }] }) });
+ assert.equal((await runCompletionReport(f.options)).ok, true);
+ assert.ok(scans >= 4); assert.equal(f.sends.length, 1);
+ assert.equal(f.sends[0].uid, 'primary'); assert.match(f.sends[0].message, /^测试 账号于 .* 完成所有任务$/);
+});
+test('unknown, lost or failed running sessions cannot produce completion reports', async () => {
+ for (const next of [ { known: false }, { known: true, sessions: [] }, { known: true, sessions: [{ id: 'one', status: 'failed', busy: false }] } ]) {
+ let scans=0;
+ const f=fixture({snapshot:async()=> ++scans === 1 ? {known:true,sessions:[{id:'one',status:'running',busy:true}]} : next});
+ await assert.rejects(runCompletionReport({...f.options,timeoutMs:5000})); assert.equal(f.sends.length,0);
+ }
+});
+test('account/primary changes and cancellation never send', async () => {
+ for (const mode of ['account', 'primary', 'cancel']) {
+ let scans=0;const f=fixture({ snapshot:async()=> {scans++;return {known:true,sessions:[{id:'one',status:'completed',busy:false}]};},
+ currentAccount:()=>({uid:mode==='account'&&scans?'other':'worker'}),primaryUid:()=>mode==='primary'&&scans?'other':'primary',isCancelled:()=>mode==='cancel'&&scans>0 });
+ await assert.rejects(runCompletionReport(f.options));assert.equal(f.sends.length,0);
+ }
+});
+test('report task is manual and dispatched through bounded completion capability', async () => {
+ const {validateTask,executeTask,canManuallyRunTask}=require('../scripts/automation');
+ const task={schemaVersion:1,id:'report-to-primary',name:'Completion report capability',trigger:{type:'manual'},steps:[{op:'notify.afterAllTasks'}]};
+ assert.equal(validateTask(task).id,'report-to-primary');assert.equal(canManuallyRunTask(task),true);
+ let n=0; await executeTask(task,{completionReport:async()=>{n++;return {ok:true};}});assert.equal(n,1);
+});
+test('renderer probe uses account scope and preserves pending, streaming and queued work', async () => {
+ const { probeAccountCompletion } = require('../scripts/completion-report');
+ const vm = require('node:vm');
+ let options;
+ const resource = {
+ list: async o => { options=o; return {agents:[{id:'one',status:'completed'},{id:'two',status:'pending'}],pagination:null}; },
+ getConversationMessageQueue: async id => id==='one'?{items:[{id:'queued'}]}:undefined,
+ };
+ const context={window:{__wbsWorkBuddyCompat:{findQueueAdapter:()=>({adapter:{sessionsResource:resource}}),findConversationControllers:()=>[]}},document:{}};
+ const result = await vm.runInNewContext('('+probeAccountCompletion.toString()+')("worker")', context);
+ assert.equal(options.userId,'worker'); assert.equal(result.known,true); assert.equal(result.sessions[0].busy,true); assert.equal(result.sessions[1].status,'pending');
+ resource.list=async()=>({agents:[],pagination:null});
+ assert.equal((await vm.runInNewContext('('+probeAccountCompletion.toString()+')("worker")',context)).known,false);
+ resource.list=async()=>({agents:[{id:'one',status:'completed'}],pagination:{hasNext:true}});
+ assert.equal((await vm.runInNewContext('('+probeAccountCompletion.toString()+')("worker")',context)).known,false);
+});
diff --git a/test/composer-button-visibility.test.js b/test/composer-button-visibility.test.js
new file mode 100644
index 0000000..66026f1
--- /dev/null
+++ b/test/composer-button-visibility.test.js
@@ -0,0 +1,145 @@
+'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 compat = require('../scripts/workbuddy-compat.js');
+const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+
+// Run the real placement + visibility chain, including a conversation being removed.
+function harness() {
+ function element() {
+ const classes = new Set();
+ return {
+ style: {}, children: [], isConnected: true, parentElement: null,
+ classList: { add: value => classes.add(value), remove: value => classes.delete(value), contains: value => classes.has(value) },
+ getBoundingClientRect() { return this.hidden ? { width: 0, height: 0 } : { width: 200, height: 32, left: 400, top: 600, bottom: 632 }; },
+ closest() { return this.scope || null; },
+ querySelectorAll() { return []; },
+ appendChild(child) { this.insertBefore(child, null); },
+ insertBefore(child) {
+ if (child.parentElement) child.parentElement.children = child.parentElement.children.filter(value => value !== child);
+ child.parentElement = this;
+ this.children.push(child);
+ },
+ };
+ }
+ const page = { toolbar: null, mic: null, editor: null, welcome: false };
+ const document = {
+ body: element(),
+ querySelector(selector) {
+ if (selector === '.voice-mic-wrap') return page.mic;
+ if (selector === 'div.cr-input-toolbar__right') return page.toolbar;
+ if (selector === '.wb-home-page') return page.welcome ? {} : null;
+ return null;
+ },
+ querySelectorAll() { return []; },
+ };
+ const context = vm.createContext({
+ document, window: { innerWidth: 1000, innerHeight: 800 }, WBS_COMPAT: compat,
+ stashBtn: element(), exploreBtn: element(), alive: true,
+ sessState: { phrase: true, stash: true },
+ findComposer: () => page.editor,
+ composerHasContent: editor => !!editor?.hasContent,
+ getComputedStyle: el => ({ visibility: el.visibility || 'visible', display: 'block' }),
+ clearTimeout() {}, setBuildTimeout(fn) { fn(); }, renderExploreOptions() {},
+ });
+ const start = inject.indexOf(' function insertStash()');
+ const end = inject.indexOf(' // 监听发送按钮自身', start);
+ vm.runInContext(inject.slice(start, end) + '\napplyThemeButtonColors = function () {};', context);
+ return { page, document, context, element, sync: () => context.syncStash() };
+}
+
+for (const route of ['login', 'settings with an unrelated editable', 'welcome']) {
+ test(`composer buttons stay hidden on ${route}`, () => {
+ const h = harness();
+ if (route.includes('editable')) h.page.editor = h.element();
+ if (route === 'welcome') h.page.welcome = true;
+ h.sync();
+ assert.equal(h.context.exploreBtn.style.display, 'none');
+ assert.equal(h.context.stashBtn.style.display, 'none');
+ });
+}
+
+test('conversation → login → conversation hides and restores the same buttons', () => {
+ const h = harness();
+ h.page.toolbar = h.element();
+ h.page.editor = h.element();
+ h.sync();
+ assert.equal(h.context.exploreBtn.style.display, 'flex');
+ assert.equal(h.context.stashBtn.style.display, 'none');
+ h.page.toolbar.isConnected = false;
+ h.page.toolbar = h.page.editor = null;
+ h.sync();
+ assert.equal(h.context.exploreBtn.style.display, 'none');
+ h.page.toolbar = h.element();
+ h.page.editor = h.element();
+ h.page.editor.hasContent = true;
+ h.sync();
+ assert.equal(h.context.exploreBtn.style.display, 'flex');
+ assert.equal(h.context.stashBtn.style.display, 'flex');
+ assert.equal(h.context.exploreBtn.parentElement, h.page.toolbar);
+});
+
+for (const visibility of ['zero size', 'hidden', 'detached']) {
+ test(`a ${visibility} conversation composer cannot leave a floating button`, () => {
+ const h = harness();
+ h.page.editor = h.element();
+ h.page.editor.scope = h.element();
+ if (visibility === 'zero size') h.page.editor.hidden = true;
+ if (visibility === 'hidden') h.page.editor.visibility = 'hidden';
+ if (visibility === 'detached') h.page.editor.isConnected = false;
+ h.sync();
+ assert.equal(h.context.exploreBtn.style.display, 'none');
+ });
+}
+
+test('a visible conversation composer retains fixed fallback and respects phrase switch', () => {
+ const h = harness();
+ h.page.editor = h.element();
+ h.page.editor.scope = h.element();
+ h.sync();
+ assert.equal(h.context.exploreBtn.style.display, 'flex');
+ assert.equal(h.context.exploreBtn.style.top, '599px');
+ h.context.sessState.phrase = false;
+ h.sync();
+ assert.equal(h.context.exploreBtn.style.display, 'none');
+});
+
+for (const hidden of [false, true]) {
+ test(`legacy microphone layout ${hidden ? 'hides with its anchor' : 'keeps fixed placement'}`, () => {
+ const h = harness();
+ const row = h.element();
+ row.appendChild(h.element());
+ h.page.mic = h.element();
+ row.appendChild(h.page.mic);
+ h.page.mic.hidden = hidden;
+ h.sync();
+ assert.equal(h.context.exploreBtn.style.display, hidden ? 'none' : 'flex');
+ if (!hidden) assert.equal(h.context.exploreBtn.parentElement, h.document.body);
+ });
+}
+
+test('switching from an inline toolbar to fixed layout reparents both buttons', () => {
+ const h = harness();
+ h.page.toolbar = h.element();
+ h.sync();
+ h.page.toolbar = null;
+ h.page.editor = h.element();
+ h.page.editor.scope = h.element();
+ h.sync();
+ for (const button of [h.context.stashBtn, h.context.exploreBtn]) {
+ assert.equal(button.parentElement, h.document.body);
+ assert.equal(button.classList.contains('wbs-stash-inline-inline'), false);
+ }
+});
+
+test('visibility-hidden toolbar does not count as a conversation anchor', () => {
+ const h = harness();
+ h.page.toolbar = h.element();
+ h.page.toolbar.visibility = 'hidden';
+ h.sync();
+ assert.equal(h.context.exploreBtn.style.display, 'none');
+});
diff --git a/test/element-inspector.test.js b/test/element-inspector.test.js
index b29d2f8..4826bf7 100644
--- a/test/element-inspector.test.js
+++ b/test/element-inspector.test.js
@@ -6,92 +6,98 @@ const fs = require('node:fs');
const path = require('node:path');
const injectSource = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+const automationPickerPath = path.join(__dirname, '../scripts/automation-picker.js');
+const automationPickerSource = fs.readFileSync(automationPickerPath, 'utf8');
// 拾取实现随内部模块抽离(picker-internal.js 不入库);文件存在才测试,缺失则整文件跳过
const pickerPath = path.join(__dirname, '../scripts/picker-internal.js');
const pickerSource = fs.existsSync(pickerPath) ? fs.readFileSync(pickerPath, 'utf8') : null;
const daemonSource = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
const macBuildSource = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');
-if (!pickerSource) {
- test('picker-internal.js 未就绪(内部模块不入库)', (t) => t.skip());
-} else {
- function functionSource(name, nextName) {
- const start = pickerSource.indexOf('function ' + name + '(');
- const end = pickerSource.indexOf('function ' + nextName + '(', start + 1);
+function functionSource(name, nextName) {
+ const start = automationPickerSource.indexOf('function ' + name + '(');
+ const end = automationPickerSource.indexOf('function ' + nextName + '(', start + 1);
assert.ok(start >= 0 && end > start, `missing picker function ${name}`);
- return pickerSource.slice(start, end);
+ return automationPickerSource.slice(start, end);
}
test('拾取点击直接打开插件内 DOM 检查器', () => {
- const handler = functionSource('onInspectClick', 'onInspectKey');
- assert.match(handler, /showInspector\(stack, el\)/);
+ const handler = functionSource('onAutomationInspectClick', 'onAutomationInspectKey');
+ assert.match(handler, /showAutomationInspector\(stack, el\)/);
assert.doesNotMatch(handler, /window\.open|api\(|element-inspector-url|open-url/);
});
-test('插件内检查器包含 DOM 树、重叠元素栈、节点详情和 HTML', () => {
- const handler = functionSource('showInspector', 'stopInspect');
- assert.match(handler, /wbs-inspector-tree/);
- assert.match(handler, /wbs-inspector-stack/);
- assert.match(handler, /wbs-inspector-detail/);
- assert.match(handler, /wbs-inspector-html/);
+test('插件内检查器只保留 DOM 树并移除重叠元素栈和节点详情', () => {
+ const handler = functionSource('showAutomationInspector', 'stopAutomationInspect');
+ assert.match(handler, /wbs-auto-inspector-tree/);
+ assert.doesNotMatch(handler, /wbs-auto-inspector-stack|此坐标下的元素/);
+ assert.doesNotMatch(handler, /wbs-auto-inspector-detail|节点详情/);
assert.match(handler, /mouseover/);
- assert.match(pickerSource, /document\.elementsFromPoint/);
+ assert.match(automationPickerSource, /collectElementsAtPoint\(document\)/);
+ assert.match(automationPickerSource, /surface\.elementsFromPoint/);
});
test('再次拾取时保留检查器和 WorkDaddy 面板并原地刷新节点', () => {
- const handler = functionSource('onInspectClick', 'onInspectKey');
- assert.doesNotMatch(handler, /setOpen\(false\)|stopInspect\(\)/);
+ const handler = functionSource('onAutomationInspectClick', 'onAutomationInspectKey');
+ assert.doesNotMatch(handler, /setOpen\(false\)|stopAutomationInspect\(\)/);
assert.match(handler, /inspector\.__wbsInspectAt\(stack, el\)/);
- assert.match(handler, /showInspector\(stack, el\)/);
- const startHandler = functionSource('startInspect', 'toggleInspect');
+ assert.match(handler, /showAutomationInspector\(stack, el\)/);
+ const startHandler = functionSource('startAutomationInspect', 'toggleAutomationInspect');
assert.doesNotMatch(startHandler, /root\.style\.display\s*=\s*'none'/);
- const inspector = functionSource('showInspector', 'stopInspect');
+ const inspector = functionSource('showAutomationInspector', 'stopAutomationInspect');
assert.match(inspector, /mask\.__wbsInspectAt = inspectAt/);
- assert.doesNotMatch(inspector, /wbs-ins-repick[^\n]+closeInspector\(\)/);
+ assert.doesNotMatch(inspector, /wbs-ins-repick|重新拾取/);
});
-test('检查器默认严格保持 80% 高 60% 并允许手动缩放', () => {
- assert.match(pickerSource, /\.wbs-modal\.wbs-inspector-modal\{[^}]*width:80vw;height:60vh/);
- assert.match(pickerSource, /resize:both/);
- assert.match(pickerSource, /overflow:hidden/);
- assert.doesNotMatch(pickerSource, /@media\(max-width:900px\)\{\.wbs-inspector-modal/);
- assert.doesNotMatch(pickerSource, /@media\(max-width:600px\)\{\.wbs-inspector-modal/);
+test('检查器默认使用 WorkBuddy 窗口一半宽高并允许手动缩放', () => {
+ assert.match(automationPickerSource, /\.wbs-modal\.wbs-auto-inspector-modal\{[^}]*width:50vw;height:50vh/);
+ assert.match(automationPickerSource, /resize:both/);
+ assert.match(automationPickerSource, /overflow:hidden/);
+ assert.doesNotMatch(automationPickerSource, /@media\(max-width:900px\)\{\.wbs-auto-inspector-modal/);
+ assert.doesNotMatch(automationPickerSource, /@media\(max-width:600px\)\{\.wbs-auto-inspector-modal/);
});
test('检查器浮窗外不遮罩不模糊并允许页面接收指针', () => {
- assert.match(pickerSource, /\.wbs-inspector-mask\{[^}]*background:transparent[^}]*pointer-events:none/);
- assert.match(pickerSource, /\.wbs-inspector-modal\{[^}]*pointer-events:auto/);
- assert.doesNotMatch(pickerSource, /\.wbs-inspector-mask\{[^}]*backdrop-filter/);
+ assert.match(automationPickerSource, /\.wbs-auto-inspector-mask\{[^}]*background:transparent[^}]*pointer-events:none/);
+ assert.match(automationPickerSource, /\.wbs-auto-inspector-modal\{[^}]*pointer-events:auto/);
+ assert.doesNotMatch(automationPickerSource, /\.wbs-auto-inspector-mask\{[^}]*backdrop-filter/);
});
-test('节点详情眼睛按钮切换 opacity 0 并精确恢复原内联值', () => {
- const inspector = functionSource('showInspector', 'stopInspect');
- assert.match(inspector, /wbs-ins-visibility/);
- assert.match(pickerSource, /opacityStates = new WeakMap\(\)/);
- assert.match(inspector, /style\.setProperty\('opacity', '0', 'important'\)/);
- assert.match(inspector, /style\.setProperty\('opacity', state\.value, state\.priority\)/);
- assert.match(inspector, /style\.removeProperty\('opacity'\)/);
- assert.match(inspector, /state = \{ hadValue: value !== '', value: value, priority:/);
- assert.doesNotMatch(inspector, /if \(!state\) \{\s*var value = selected\.style\.getPropertyValue\('opacity'\)/);
+test('顶部主按钮复制可供 agent 使用的完整元素信息', () => {
+ const inspector = functionSource('showAutomationInspector', 'stopAutomationInspect');
+ assert.match(inspector, /wbs-auto-ins-copy-element/);
+ assert.match(inspector, /'CSS: ' \+ buildAutomationQueryPath\(selected\)/);
+ assert.match(inspector, /'XPath: ' \+ buildAutomationXPath\(selected\)/);
+ assert.match(inspector, /selected\.outerHTML/);
+ assert.match(inspector, /copyPlainText\(payload\)/);
+ assert.match(automationPickerSource, /\.wbs-auto-ins-copy-element\{[^}]*var\(--wb-button-primary-bg/);
+});
+
+test('拾取器为带 id 的 Shadow DOM 元素生成可深度查询的选择器', () => {
+ const queryPath = functionSource('buildAutomationQueryPath', 'buildAutomationXPath');
+ assert.match(queryPath, /if \(el && el\.id\) return/);
+ assert.match(automationPickerSource, /e\.composedPath\(\)/);
+ assert.match(automationPickerSource, /shadowRoot\.elementsFromPoint/);
});
test('重注入通过检查器关闭入口清理监听器且拾取高亮恢复原样', () => {
- assert.match(injectSource, /if \(inspector && inspector\.__wbsClose\) inspector\.__wbsClose\(\)/);
- const stopHandler = functionSource('stopInspect', 'onInspectMove');
- assert.match(stopHandler, /style\.setProperty\('outline', inspectState\.hoverOutline\.value, inspectState\.hoverOutline\.priority\)/);
- assert.match(stopHandler, /style\.setProperty\('outline-offset', inspectState\.hoverOutlineOffset\.value, inspectState\.hoverOutlineOffset\.priority\)/);
+ assert.match(injectSource, /if \(automationInspector && automationInspector\.__wbsClose\) automationInspector\.__wbsClose\(\)/);
+ const stopHandler = functionSource('stopAutomationInspect', 'onAutomationInspectMove');
+ assert.match(stopHandler, /style\.setProperty\('outline', automationInspectState\.hoverOutline\.value, automationInspectState\.hoverOutline\.priority\)/);
+ assert.match(stopHandler, /style\.setProperty\('outline-offset', automationInspectState\.hoverOutlineOffset\.value, automationInspectState\.hoverOutlineOffset\.priority\)/);
});
-test('检查器内部使用容器查询跟随自身尺寸响应式', () => {
- assert.match(pickerSource, /container-type:inline-size/);
- assert.match(pickerSource, /@container inspector \(max-width:760px\)/);
- assert.match(pickerSource, /grid-template-columns:1fr/);
+test('检查器单列 DOM 树跟随自身尺寸响应式', () => {
+ assert.match(automationPickerSource, /container-type:inline-size/);
+ assert.match(automationPickerSource, /\.wbs-auto-inspector-main\{[^}]*grid-template-columns:minmax\(0,1fr\)/);
+ assert.doesNotMatch(automationPickerSource, /grid-template-columns:minmax\(360px/);
});
-test('检查器标题栏可拖拽且具有明确关闭按钮', () => {
- const handler = functionSource('showInspector', 'stopInspect');
- assert.match(handler, /wbs-inspector-drag-handle/);
- assert.match(handler, />关闭<\/button>/);
+test('检查器标题栏可拖拽且使用图标关闭按钮', () => {
+ const handler = functionSource('showAutomationInspector', 'stopAutomationInspect');
+ assert.match(handler, /wbs-auto-inspector-drag-handle/);
+ assert.match(handler, /wbs-auto-ins-close[^>]+title="关闭"[^>]+aria-label="关闭元素检查器"><svg/);
+ assert.doesNotMatch(handler, />关闭<\/button>/);
assert.match(handler, /pointerdown/);
assert.match(handler, /pointermove/);
assert.match(handler, /pointerup/);
@@ -104,5 +110,20 @@ test('daemon 不再暴露 localhost 元素检查器页面与 bridge', () => {
test('macOS 打包不再携带外部元素检查器文件', () => {
assert.doesNotMatch(macBuildSource, /element-inspector\.js|element-inspector\.html/);
+ assert.match(macBuildSource, /automation-picker\.js/);
+});
+
+test('自动化拾取器与五连击 debug 拾取器使用独立入口和 DOM 命名空间', () => {
+ assert.match(injectSource, /window\.__wbsStartAutomationPicker\(\)/);
+ assert.doesNotMatch(injectSource.slice(injectSource.indexOf('function buildAutomationPane()'), injectSource.indexOf('// ===== 会话 pane')), /window\.__wbsStartPicked\(\)/);
+ assert.match(automationPickerSource, /window\.__wbsStartAutomationPicker/);
+ assert.doesNotMatch(automationPickerSource, /window\.__wbsStartPicked/);
+ assert.match(daemonSource, /automation-picker\.js/);
+ if (pickerSource) {
+ assert.match(pickerSource, /wbs-inspector-stack/);
+ assert.match(pickerSource, /wbs-inspector-detail/);
+ assert.match(pickerSource, /width:80vw;height:60vh/);
+ assert.match(pickerSource, /window\.__wbsStartPicked/);
+ assert.doesNotMatch(pickerSource, /window\.__wbsStartAutomationPicker/);
+ }
});
-}
diff --git a/test/fab-quiet-mode.test.js b/test/fab-quiet-mode.test.js
new file mode 100644
index 0000000..9a11126
--- /dev/null
+++ b/test/fab-quiet-mode.test.js
@@ -0,0 +1,110 @@
+'use strict';
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const test = require('node:test');
+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
+
+function harness(enabled = true) {
+ const start = source.indexOf('function createFabQuietMode(');
+ assert.notEqual(start, -1);
+ const end = source.indexOf('// Keep the decision logic', start);
+ const timers = new Map(), listeners = [], classes = new Set();
+ let timerId = 0, dragging = false;
+ const win = { innerWidth: 1000, innerHeight: 700 };
+ const doc = { activeElement: null };
+ const button = {};
+ const saved = new Map(enabled ? [['dock-test', '1']] : []);
+ const storage = { getItem: key => saved.get(key) || null, setItem: (key, value) => saved.set(key, value) };
+ const fab = {
+ offsetWidth: 108, offsetHeight: 56,
+ style: { right: '22px', bottom: '22px', setProperty(k, v) { this[k] = v; } },
+ classList: { contains: k => classes.has(k), add: k => classes.add(k), remove: k => classes.delete(k) },
+ contains: el => el === button,
+ };
+ const context = {
+ setTimeout(fn) { timers.set(++timerId, fn); return timerId; },
+ clearTimeout(id) { timers.delete(id); },
+ };
+ vm.createContext(context);
+ vm.runInContext(source.slice(start, end), context);
+ const mode = context.createFabQuietMode({ fab, window: win, document: doc,
+ storage, settingKey: 'dock-test',
+ isDragging: () => dragging,
+ listen: (target, type, fn) => listeners.push({ target, type, fn }),
+ });
+ return { mode, fab, doc, button, classes, timers, win, saved,
+ drag(value) { dragging = value; },
+ fire(target, type, event = {}) { listeners.filter(l => l.target === target && l.type === type).forEach(l => l.fn(event)); },
+ tick() { const pending = [...timers.values()]; timers.clear(); pending.forEach(fn => fn()); },
+ };
+}
+
+test('idle robot tucks to the edge and approaching pointer restores it without a click', () => {
+ const h = harness();
+ h.tick();
+ assert(h.classes.has('is-quiet'));
+ assert.equal(h.fab.style['--wbs-fab-quiet-shift'], '59px');
+ h.fire(h.win, 'pointermove', { clientX: 940, clientY: 658 });
+ assert(h.classes.has('is-quiet'), 'the old robot position must not wake the docked robot');
+ h.fire(h.win, 'pointermove', { clientX: 990, clientY: 658 });
+ assert(!h.classes.has('is-quiet'));
+ h.tick();
+ assert(!h.classes.has('is-quiet'), 'stationary pointer nearby keeps robot awake');
+ h.fire(h.win, 'pointermove', { clientX: 200, clientY: 200 });
+ h.tick();
+ assert(h.classes.has('is-quiet'));
+});
+
+test('auto docking defaults off and a changed preference persists and cancels pending docking', () => {
+ const h = harness(false);
+ h.tick();
+ assert(!h.classes.has('is-quiet'));
+ assert.equal(h.timers.size, 0);
+ h.mode.setEnabled(true);
+ assert.equal(h.saved.get('dock-test'), '1');
+ h.tick();
+ assert(h.classes.has('is-quiet'));
+ h.mode.setEnabled(false);
+ assert.equal(h.saved.get('dock-test'), '0');
+ assert(!h.classes.has('is-quiet'));
+ assert.equal(h.timers.size, 0);
+});
+
+test('closing a panel opened from the robot starts a fresh idle period', () => {
+ const h = harness();
+ h.fire(h.fab, 'pointerenter', {pointerType:'mouse'});
+ h.classes.add('hidden'); h.mode.wake();
+ h.classes.delete('hidden'); h.mode.wake();
+ h.tick();
+ assert(h.classes.has('is-quiet'));
+});
+
+test('panel, dragging and keyboard focus prevent tucking; close rearms idle timer', () => {
+ for (const reason of ['hidden', 'drag', 'focus']) {
+ const h = harness();
+ if (reason === 'hidden') h.classes.add('hidden');
+ if (reason === 'drag') h.drag(true);
+ if (reason === 'focus') h.doc.activeElement = h.button;
+ h.tick();
+ assert(!h.classes.has('is-quiet'), reason);
+ h.classes.delete('hidden'); h.drag(false); h.doc.activeElement = null;
+ h.mode.wake(); h.tick();
+ assert(h.classes.has('is-quiet'), reason + ' ends');
+ }
+});
+
+test('resize uses the new viewport and saved vertical position; disposal cancels timer', () => {
+ const h = harness();
+ h.tick();
+ h.win.innerWidth = 600; h.fab.style.bottom = '200px';
+ h.fire(h.win, 'resize');
+ h.fire(h.win, 'pointermove', { clientX: 590, clientY: 480 });
+ assert(!h.classes.has('is-quiet'));
+ h.fire(h.win, 'pointerout', { relatedTarget: null });
+ assert.equal(h.timers.size, 1);
+ h.mode.destroy();
+ assert.equal(h.timers.size, 0);
+ h.tick();
+ assert(!h.classes.has('is-quiet'));
+});
diff --git a/test/growth-active.test.js b/test/growth-active.test.js
index a8c112e..15b74b4 100644
--- a/test/growth-active.test.js
+++ b/test/growth-active.test.js
@@ -154,3 +154,19 @@ test('独立会话结束时会中止长连接 SSE,不会卡在清理阶段', a
await activateGrowthAccount('account-token', { apiHost: 'https://api.test', fetchImpl, timeoutMs: 1000 });
assert.equal(sseAborted, true);
});
+
+test('completion report preserves full message, uses target token and requests no plugins', async () => {
+ const prompt = '长账号'.repeat(40) + ' 账号于 2026/9/8 18:00:00 完成所有任务';
+ const calls=[];
+ const fetchImpl=async (url, init={})=> {
+ calls.push({url,init});
+ if(url.endsWith('/console/as/conversations/')) return jsonResponse({data:{id:'report',session:{sessionId:'session',link:'https://acp.test/api/v1/acp',token:'runtime-token'}}});
+ if(init.method==='GET') return jsonResponse({}, {headers:{'acp-connection-id':'conn'}});
+ if(init.method==='DELETE') return jsonResponse({});
+ const rpc=JSON.parse(init.body); return jsonResponse({jsonrpc:'2.0',id:rpc.id,result:{stopReason:'end_turn'}});
+ };
+ const r=await activateGrowthAccount('primary-token',{purpose:'completion-report',prompt,fetchImpl});
+ assert.equal(r.conversationId,'report');assert.equal(calls[0].init.headers.authorization,'Bearer primary-token');
+ assert.deepEqual(JSON.parse(calls[0].init.body).plugins,[]);assert.equal(JSON.parse(calls[0].init.body).prompt,prompt);
+ assert.equal(JSON.parse(calls.find(c=>c.init.body?.includes('session/prompt')).init.body).params.prompt[0].text,prompt);
+});
diff --git a/test/i18n-coverage.test.js b/test/i18n-coverage.test.js
index e599d83..936868d 100644
--- a/test/i18n-coverage.test.js
+++ b/test/i18n-coverage.test.js
@@ -12,6 +12,7 @@ const path = require('node:path');
const vm = require('node:vm');
const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+const automationPicker = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'automation-picker.js'), 'utf8');
const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
const lib = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib.js'), 'utf8');
@@ -96,16 +97,18 @@ function extractKeys() {
return keys.sort((a, b) => b.length - a.length);
}
-test('every Chinese UI literal in inject.js translates at runtime with zero Chinese residue', () => {
+test('every Chinese UI literal in injected UI modules translates at runtime with zero Chinese residue', () => {
const t = buildTranslator();
const missed = [];
- for (const lit of chineseLiterals(stripComments(inject))) {
- if (LOG_LIKE.test(lit)) continue;
- if (FRAGMENT_LIKE.test(lit)) continue;
- const text = uiText(lit);
- if (text.length < 2) continue;
- const out = t(text, 'en');
- if (/[\u4e00-\u9fff]/.test(out)) missed.push(`「${lit}」-> ${out}`);
+ for (const source of [inject, automationPicker]) {
+ for (const lit of chineseLiterals(stripComments(source))) {
+ if (LOG_LIKE.test(lit)) continue;
+ if (FRAGMENT_LIKE.test(lit)) continue;
+ const text = uiText(lit);
+ if (text.length < 2) continue;
+ const out = t(text, 'en');
+ if (/[\u4e00-\u9fff]/.test(out)) missed.push(`「${lit}」-> ${out}`);
+ }
}
assert.deepEqual(missed, [], `运行时仍产中文(中英混合):\n${missed.map((m, i) => ` ${i + 1}. ${m}`).join('\n')}`);
});
@@ -186,4 +189,25 @@ test('variant keys: error prefixes with and without trailing space both translat
test('zh mode leaves text untouched', () => {
const t = buildTranslator();
assert.equal(t('已切换为「h」,开始领取积分…', 'zh'), '已切换为「h」,开始领取积分…');
-});
\ No newline at end of file
+});
+
+test('all built-in task names, descriptions and feedback have full English translations', () => {
+ const translate = buildTranslator();
+ const directory = path.join(__dirname, '../scripts/builtin/automations');
+ const inspect = value => {
+ if (!value || typeof value !== 'object') return;
+ for (const [key, text] of Object.entries(value)) {
+ if (['name', 'description', 'message'].includes(key) && typeof text === 'string' && /[\u4e00-\u9fff]/.test(text)) {
+ assert.doesNotMatch(translate(text, 'en'), /[\u4e00-\u9fff]/, text);
+ assert.equal(translate(text, 'zh'), text);
+ } else if (text && typeof text === 'object') inspect(text);
+ }
+ };
+ for (const filename of fs.readdirSync(directory).filter(f => f.endsWith('.json'))) inspect(JSON.parse(fs.readFileSync(path.join(directory, filename), 'utf8')));
+});
+
+test('previously installed fixed-prompt task descriptions also switch to English', () => {
+ const original = '依次切换所有账号,等待当前会话输入框出现后发送 1+1=,等待回复完成,最后恢复开始时的账号。';
+ assert.doesNotMatch(buildTranslator()(original, 'en'), /[\u4e00-\u9fff]/);
+ assert.equal(buildTranslator()(original, 'zh'), original);
+});
diff --git a/test/i18n.test.js b/test/i18n.test.js
index 4a96f4f..6f3777f 100644
--- a/test/i18n.test.js
+++ b/test/i18n.test.js
@@ -23,7 +23,7 @@ test('injected panel exposes persisted bilingual language selection', () => {
test('all dynamic panel text and toast nodes pass through the translator', () => {
assert.match(source, /function applyI18n\(scope\)/);
- assert.match(source, /applyI18n\(t\);/);
+ assert.match(source, /toastRuntime\.show\(\{ message: wbsTranslateString/);
assert.match(source, /i18nObserver\.observe\(root/);
assert.match(source, /'账号': 'Accounts'/);
assert.match(source, /'设置语言': 'Language'/);
@@ -35,3 +35,30 @@ test('README language switch links are reciprocal', () => {
assert.match(readme, /\[English\]\(README_en\.md\)/);
assert.match(english, /\[简体中文\]\(README\.md\)/);
});
+
+test('built-in editor translates defaults but preserves stored text and user edits', () => {
+ const vm = require('node:vm');
+ const dict = source.match(/var WBS_I18N_EN = \{([\s\S]*?)\n \};/)[0];
+ const helpers = source.slice(source.indexOf(' function wbsBuiltinAutomationText('), source.indexOf(' // ===== 全局错误钩子'));
+ const context = { WBS_LANGUAGE: 'en' };
+ vm.runInNewContext(dict + helpers, context);
+ const directory = path.join(__dirname, '../scripts/builtin/automations');
+ for (const filename of fs.readdirSync(directory).filter(f => f.endsWith('.json'))) {
+ const task = JSON.parse(fs.readFileSync(path.join(directory, filename), 'utf8'));
+ for (const field of ['name', 'description']) {
+ const displayed = context.wbsAutomationText(task, field);
+ assert.doesNotMatch(displayed, /[\u4e00-\u9fff]/);
+ assert.equal(context.wbsAutomationEditedText(task, field, displayed), task[field]);
+ assert.equal(context.wbsAutomationEditedText(task, field, 'My custom text'), 'My custom text');
+ const edited = { ...task, [field]: '账号' };
+ assert.equal(context.wbsAutomationText(edited, field), edited[field]);
+ assert.equal(context.wbsBuiltinAutomationText(edited, field), false);
+ const custom = { ...task, id: 'user-created' };
+ assert.equal(context.wbsAutomationText(custom, field), task[field]);
+ assert.equal(context.wbsBuiltinAutomationText(custom, field), false);
+ context.WBS_LANGUAGE = 'zh';
+ assert.equal(context.wbsAutomationText(task, field), task[field]);
+ context.WBS_LANGUAGE = 'en';
+ }
+ }
+});
diff --git a/test/logout-route.test.js b/test/logout-route.test.js
new file mode 100644
index 0000000..d11b29b
--- /dev/null
+++ b/test/logout-route.test.js
@@ -0,0 +1,36 @@
+'use strict';
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+const begin = source.indexOf(" if (req.method === 'POST' && p === '/api/logout')");
+const end = source.indexOf(' // /api/batch-claim', begin);
+const route = new Function('req', 'p', 'res', 'resolveLogoutAuth', 'quitWorkBuddy', 'relaunchWorkBuddy', 'fs', 'log', 'json', source.slice(begin, end));
+async function run(resolution, exists, quitError) {
+ const actions = [];
+ const result = await route({ method: 'POST' }, '/api/logout', {}, () => resolution,
+ async () => { actions.push('quit'); if (quitError) throw new Error(quitError); },
+ async () => { actions.push('relaunch'); },
+ { existsSync: () => exists, unlinkSync: () => { actions.push('unlink'); exists = false; } },
+ () => {}, (_, status, body) => ({ status, body }));
+ return { actions, ...result };
+}
+test('logout retry with no file still restarts the login page without unlinking data', async () => {
+ const result = await run({ file: '/fixture/auth.info', ambiguous: false }, false);
+ assert.deepEqual(result.actions, ['quit', 'relaunch']);
+ assert.equal(result.status, 200);
+ assert.equal(result.body.relaunched, true);
+});
+test('logout refuses ambiguity and never deletes auth when stopping the host fails', async () => {
+ for (const resolution of [{ file: null }, { file: '/fixture/auth.info', ambiguous: true }]) {
+ const result = await run(resolution, true);
+ assert.equal(result.status, 409);
+ assert.deepEqual(result.actions, []);
+ }
+ const denied = await run({ file: '/fixture/auth.info' }, true, 'standard privilege required');
+ assert.equal(denied.status, 502);
+ assert.deepEqual(denied.actions, ['quit']);
+ const success = await run({ file: '/fixture/auth.info' }, true);
+ assert.deepEqual(success.actions, ['quit', 'unlink', 'relaunch']);
+});
diff --git a/test/panel-version.test.js b/test/panel-version.test.js
new file mode 100644
index 0000000..534b0a8
--- /dev/null
+++ b/test/panel-version.test.js
@@ -0,0 +1,31 @@
+'use strict';
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+const start = source.indexOf('function wbsClientVersion(');
+const end = source.indexOf(' var WBS_LANGUAGE', start);
+function clientVersion(ua, ai = false) {
+ return new Function('WBS_PROFILE_IS_AI', 'ua', source.slice(start, end) + '\nreturn wbsClientVersion(ua);')(ai, ua);
+}
+test('header reads running client version instead of Chrome or Electron versions', () => {
+ assert.equal(clientVersion('Mozilla/5.0 WorkBuddy/5.5.3 Chrome/138.0.0.0 Electron/37.10.3'), '5.5.3');
+ assert.equal(clientVersion('Mozilla/5.0 WorkBuddy/5.5.3.0 Chrome/138.0.0.0'), '5.5.3.0');
+ assert.equal(clientVersion('Mozilla/5.0 WorkBuddyAI/5.5.3 Chrome/138.0.0.0', true), '5.5.3');
+ assert.equal(clientVersion('WorkBuddy/5.5.3', true), '5.5.3');
+ assert.equal(clientVersion('WorkBuddyAI/5.5.3'), '');
+ assert.equal(clientVersion('Chrome/138.0.0.0 Electron/37.10.3'), '');
+ assert.equal(clientVersion('WorkBuddy/5.5.3<script>'), '');
+});
+test('header writes version subtitle as text with a safe unknown-version fallback', () => {
+ const begin = source.indexOf("var versionLine = root.querySelector('#wbs-version-line')");
+ const finish = source.indexOf(" listen(window, 'workdaddy:automation-toast'", begin);
+ const render = new Function('root', 'navigator', 'WBS_VERSION', 'wbsClientVersion', source.slice(begin, finish));
+ const label = { textContent: '' };
+ const root = { querySelector: () => label };
+ render(root, { userAgent: 'WorkBuddy/5.5.3' }, '1.2.0', clientVersion);
+ assert.equal(label.textContent, '5.5.3 (1.2.0)');
+ render(root, { userAgent: 'Chrome/138.0.0.0' }, '1.2.0', clientVersion);
+ assert.equal(label.textContent, '(1.2.0)');
+});
diff --git a/test/primary-account.test.js b/test/primary-account.test.js
new file mode 100644
index 0000000..864af2b
--- /dev/null
+++ b/test/primary-account.test.js
@@ -0,0 +1,38 @@
+'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 { createPrimaryAccountStore } = require('../scripts/primary-account');
+test('primary selection is unique, persistent, validated and cleared on deletion', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-primary-'));
+ const accounts = new Set(['a', 'b']);
+ try {
+ const store = createPrimaryAccountStore(dir, uid => accounts.has(uid));
+ assert.equal(store.get(), '');
+ assert.equal(store.set('a'), 'a');
+ assert.equal(createPrimaryAccountStore(dir, uid => accounts.has(uid)).get(), 'a');
+ store.set('b');
+ assert.equal(store.get(), 'b');
+ assert.throws(() => store.set('../x'), /无效/);
+ assert.throws(() => store.set('missing'), /不存在/);
+ assert.equal(store.get(), 'b');
+ accounts.delete('b');
+ assert.equal(store.get(), '');
+ accounts.add('b');
+ 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', () => {
+ 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'));
+});
diff --git a/test/quick-phrase-composer.test.js b/test/quick-phrase-composer.test.js
new file mode 100644
index 0000000..09daa53
--- /dev/null
+++ b/test/quick-phrase-composer.test.js
@@ -0,0 +1,204 @@
+'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', 'daemon.js'), 'utf8');
+const start = source.indexOf('async function sendStashToComposer(record) {');
+const end = source.indexOf('\n/**', start);
+assert.ok(start >= 0 && end > start);
+
+function harness(hasContent, failSelect = false) {
+ const calls = [];
+ let evaluations = 0;
+ const context = {
+ cdp: { connected: true },
+ log() {},
+ waitAiIdle: async () => true,
+ setTimeout: (callback) => callback(),
+ cdpSend: async (method, params) => {
+ calls.push({ method, params });
+ if (method === 'Runtime.evaluate') {
+ evaluations++;
+ const value = evaluations === 1 ? { ok: true }
+ : evaluations === 2 ? { ok: true, hasContent }
+ : { ok: true, x: 100, y: 100 };
+ return { result: { value } };
+ }
+ if (failSelect && params.commands?.includes('selectAll')) throw new Error('selection failed');
+ return {};
+ },
+ cdpMouseClick: async () => calls.push({ method: 'submit' }),
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ return { calls, send: (text) => context.sendStashToComposer({ content: { text, items: [] } }) };
+}
+
+test('quick phrase replaces a draft using a renderer edit command without macOS menu shortcuts', async () => {
+ const { calls, send } = harness(true);
+ assert.equal((await send('replacement')).sent, true);
+ const inputs = calls.filter(({ method }) => method.startsWith('Input.') || method === 'submit');
+ assert.deepEqual(Array.from(inputs[0].params.commands || []), ['selectAll']);
+ assert.equal(inputs[0].params.type, 'rawKeyDown');
+ assert.equal(inputs[0].params.modifiers || 0, 0, 'must not invoke Cmd+A through native menus');
+ assert.equal(inputs[0].params.nativeVirtualKeyCode, undefined);
+ const deletion = inputs.findIndex(({ params }) => params?.key === 'Backspace' && params.type === 'keyDown');
+ const insertion = inputs.findIndex(({ method }) => method === 'Input.insertText');
+ assert.ok(deletion > 0 && insertion > deletion, 'select, delete, then insert');
+ for (const { params } of inputs.filter(({ params }) => params?.key === 'Backspace')) {
+ assert.notEqual(params.nativeVirtualKeyCode, 8, 'Windows Backspace is macOS C, not Delete');
+ }
+ assert.equal(inputs[insertion].params.text, 'replacement');
+ assert.equal(inputs.at(-1).method, 'submit');
+});
+
+test('empty composer skips clearing and multiline phrases retain Shift+Enter', async () => {
+ const { calls, send } = harness(false);
+ await send('first\nsecond');
+ assert.equal(calls.some(({ params }) => params?.commands || params?.key === 'Backspace'), false);
+ assert.deepEqual(calls.filter(({ method }) => method === 'Input.insertText').map(({ params }) => params.text), ['first', 'second']);
+ const enter = calls.filter(({ params }) => params?.key === 'Enter');
+ assert.deepEqual(enter.map(({ params }) => [params.type, params.modifiers]), [['keyDown', 8], ['keyUp', 8]]);
+});
+
+test('failed selection aborts before deleting, inserting or submitting', async () => {
+ const { calls, send } = harness(true, true);
+ await assert.rejects(send('replacement'), /selection failed/);
+ assert.equal(calls.some(({ method, params }) => method === 'submit' || method === 'Input.insertText' || params?.key === 'Backspace'), false);
+});
+
+function guardedComposerHarness({ draft = '', attachment = false } = {}) {
+ const calls = [];
+ const editor = {
+ innerText: 'Ask WorkBuddy anything\u200b' + draft,
+ focus() {}, scrollIntoView() {},
+ getBoundingClientRect: () => ({ width: 400, height: 80, bottom: 400 }),
+ querySelector: () => attachment ? {} : null,
+ cloneNode() {
+ const clone = { textContent: this.innerText };
+ clone.querySelectorAll = () => [{ remove: () => { clone.textContent = draft; } }];
+ return clone;
+ },
+ };
+ const dom = { document: { querySelector: () => null, querySelectorAll: () => [editor] }, window: { getSelection: () => null } };
+ const context = { cdp: { connected: true }, log() {}, waitAiIdle: async () => true, setTimeout: fn => fn(),
+ cdpSend: async (method, params) => {
+ calls.push(method);
+ if (method !== 'Runtime.evaluate') return {};
+ // Execute both real composer expressions; only the final send-button lookup is stubbed.
+ const value = params.expression.includes('official-send-button') ? { ok: true, x: 1, y: 1 }
+ : vm.runInNewContext(params.expression, dom);
+ return { result: { value } };
+ }, cdpMouseClick: async () => calls.push('submit'),
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ return { calls, send: () => context.sendStashToComposer({ requireEmpty: true, content: { text: '1+1=', items: [] } }) };
+}
+
+test('automation sends from an empty Slate editor containing a visible placeholder', async () => {
+ const h = guardedComposerHarness();
+ assert.equal((await h.send()).sent, true);
+ assert.ok(h.calls.includes('Input.insertText'));
+ assert.equal(h.calls.at(-1), 'submit');
+ assert.ok(!h.calls.includes('Input.dispatchKeyEvent'), 'placeholder must not trigger draft deletion');
+});
+
+test('automation still rejects real drafts and attachment-only editors before input', async () => {
+ for (const options of [{ draft: 'my unsent draft' }, { attachment: true }]) {
+ const h = guardedComposerHarness(options);
+ await assert.rejects(h.send(), /会话输入框非空/);
+ assert.ok(!h.calls.some(method => method.startsWith('Input.') || method === 'submit'));
+ }
+});
+
+function delayedButtonHarness({ enableAfter = 3, cancelAfter = Infinity, disabledBy = 'property', probeCost = 0, scoped = false, missing = false, stop = false } = {}) {
+ const calls = [];
+ let probes = 0, evaluations = 0, guardChecks = 0, clock = 0;
+ const waits = [], probeTimes = [];
+ const button = {
+ tagName: 'BUTTON',
+ get disabled() { return disabledBy === 'property' && probes < enableAfter; },
+ hasAttribute: name => name === 'disabled' && disabledBy === 'attribute' && probes < enableAfter,
+ getAttribute: name => name === 'aria-disabled' && disabledBy === 'aria' && probes < enableAfter ? 'true' : null,
+ classList: { contains: name => name === 'cr-send-button--stop' && stop },
+ closest: () => null,
+ getBoundingClientRect: () => ({ x: 10, y: 10, width: 32, height: 32, bottom: 42 }),
+ scrollIntoView() {},
+ };
+ button.parentElement = { children: [button] };
+ const box = { querySelectorAll: () => missing ? [] : [button] };
+ const context = { cdp: { connected: true }, log() {}, waitAiIdle: async () => true, Date: { now: () => clock }, setTimeout: (fn, ms) => { waits.push(ms); clock += ms; fn(); },
+ cdpSend: async (method, params) => {
+ calls.push(method);
+ if (method !== 'Runtime.evaluate') return {};
+ evaluations++;
+ if (evaluations <= 2) return { result: { value: { ok: true, hasContent: false } } };
+ probes++; probeTimes.push(clock); clock += probeCost;
+ const foreign = { ...button, disabled: false, hasAttribute: () => false, getAttribute: () => null };
+ const dom = {
+ document: { activeElement: scoped ? { closest: () => box } : null, querySelector: () => button, querySelectorAll: selector => selector === '.cr-input-box' ? [] : scoped ? [foreign] : [button] },
+ getComputedStyle: () => ({ display: 'block', visibility: 'visible', borderRadius: '50%' }),
+ };
+ return { result: { value: vm.runInNewContext(params.expression, dom) } };
+ }, cdpMouseClick: async () => calls.push('submit'),
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ return { calls, waits, probeTimes, elapsed: () => clock, probes: () => probes, send: () => context.sendStashToComposer({ requireEmpty: true, content: { text: '1+1=', items: [] }, guard: async () => { if (++guardChecks >= cancelAfter) throw Error('account changed'); } }) };
+}
+
+test('after an account switch, delayed official send readiness is awaited without retyping', async () => {
+ // The first account is already ready; the next account needs several UI updates.
+ for (const enableAfter of [1, 4]) {
+ const h = delayedButtonHarness({ enableAfter });
+ assert.equal((await h.send()).sent, true);
+ assert.equal(h.probes(), enableAfter);
+ assert.equal(h.calls.filter(m => m === 'Input.insertText').length, 1);
+ assert.equal(h.calls.filter(m => m === 'submit').length, 1);
+ }
+});
+
+test('a disabled official send button never falls through to an unrelated toolbar control', async () => {
+ const h = delayedButtonHarness({ enableAfter: Infinity });
+ await assert.rejects(h.send(), /发送按钮.*超时/);
+ assert.equal(h.elapsed(), 5000);
+ assert.ok(h.probes() > 1 && h.probes() <= 26);
+ assert.ok(h.waits.every(ms => ms === 200));
+ assert.equal(h.calls.filter(m => m === 'Input.insertText').length, 1);
+ assert.ok(!h.calls.includes('submit'));
+});
+
+test('changing account during readiness polling aborts without submitting or retyping', async () => {
+ const h = delayedButtonHarness({ enableAfter: Infinity, cancelAfter: 7 });
+ await assert.rejects(h.send(), /account changed/);
+ assert.equal(h.calls.filter(m => m === 'Input.insertText').length, 1);
+ assert.ok(!h.calls.includes('submit'));
+});
+
+test('disabled property, disabled attribute and aria-disabled all gate the official send button', async () => {
+ for (const disabledBy of ['property', 'attribute', 'aria']) {
+ const h = delayedButtonHarness({ enableAfter: 3, disabledBy, scoped: true });
+ await h.send();
+ assert.deepEqual(h.probeTimes, [0, 200, 400]);
+ assert.equal(h.calls.filter(m => m === 'submit').length, 1);
+ }
+});
+
+test('a missing or stopped current composer button never uses another composer send button', async () => {
+ for (const options of [{ missing: true }, { stop: true }]) {
+ const h = delayedButtonHarness({ scoped: true, enableAfter: 1, ...options });
+ await assert.rejects(h.send());
+ assert.equal(h.elapsed(), 5000);
+ assert.ok(!h.calls.includes('submit'));
+ }
+});
+
+test('the five-second deadline includes slow CDP probes and rejects a late ready response', async () => {
+ const h = delayedButtonHarness({ enableAfter: 3, probeCost: 1800 });
+ await assert.rejects(h.send());
+ assert.ok(!h.calls.includes('submit'));
+ assert.equal(h.calls.filter(m => m === 'Input.insertText').length, 1);
+ assert.ok(h.probeTimes.every(at => at < 5000));
+});
diff --git a/test/quick-phrase-diagnostics.test.js b/test/quick-phrase-diagnostics.test.js
new file mode 100644
index 0000000..81c6dad
--- /dev/null
+++ b/test/quick-phrase-diagnostics.test.js
@@ -0,0 +1,22 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+
+test('quick phrase click diagnostics record menu close and API lifecycle without phrase text', () => {
+ assert.match(inject, /qpDiag\('click:start'/);
+ assert.match(inject, /qpDiag\('menu:close:before'/);
+ assert.match(inject, /qpDiag\('menu:close:after'/);
+ assert.match(inject, /qpDiag\('api:send'/);
+ assert.match(daemon, /quick-phrase-diagnostics.*api:received/);
+ assert.match(daemon, /quick-phrase-diagnostics.*send:start/);
+ assert.match(daemon, /quick-phrase-diagnostics.*send:finish/);
+ assert.match(daemon, /quick-phrase-diagnostics.*wait-idle:start/);
+ assert.match(daemon, /quick-phrase-diagnostics.*wait-idle:probe/);
+ assert.match(daemon, /quick-phrase-diagnostics.*wait-idle:finish/);
+ assert.match(daemon, /quick-phrase-diagnostics.*composer:start/);
+ assert.match(daemon, /quick-phrase-diagnostics.*composer:finish/);
+});
diff --git a/test/renderer-escaping.test.js b/test/renderer-escaping.test.js
index 6e6b08f..5b94411 100644
--- a/test/renderer-escaping.test.js
+++ b/test/renderer-escaping.test.js
@@ -6,6 +6,7 @@ const path = require('node:path');
const test = require('node:test');
const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
+const automationPicker = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'automation-picker.js'), 'utf8');
// 内部调试模块(git 不跟踪):存在才测试,缺失(他人环境)则跳过
const pickerPath = path.join(__dirname, '..', 'scripts', 'picker-internal.js');
const picker = fs.existsSync(pickerPath) ? fs.readFileSync(pickerPath, 'utf8') : null;
@@ -32,7 +33,10 @@ test('HTML and attribute escaping cover markup and quoted attributes', () => {
test('toast content is always written as text', () => {
const toast = sourceBetween('function toast(msg', 'registerDisposer(function () {');
- assert.match(toast, /textContent\s*=\s*String\(msg/);
+ assert.match(toast, /toastRuntime\.show\(\{ message: wbsTranslateString\(String\(msg/);
+ const runtime = fs.readFileSync(path.join(__dirname, '../tools/toast-runtime/entry.jsx'), 'utf8');
+ assert.doesNotMatch(runtime, /dangerouslySetInnerHTML|innerHTML/);
+ assert.match(runtime, /const message = String\(detail\.message/);
assert.doesNotMatch(toast, /el\([^\n]+,\s*msg\s*\)/);
const elementHelper = sourceBetween('function el(tag', 'function maskPhone');
assert.match(elementHelper, /textContent\s*=\s*String\(text\)/);
@@ -71,7 +75,7 @@ test('model, wallpaper, and account cards escape each dynamic HTML sink', () =>
assert.doesNotMatch(models, /data-model-(?:backup|test|delete-official)="' \+ model\.index/);
assert.doesNotMatch(models, /data-model-(?:copy|edit|enable)="' \+ model\.backupId/);
- const wallpapers = sourceBetween('function loadWallpapers(force)', 'function setOpen(open)');
+ const wallpapers = sourceBetween('function loadWallpapers(force)', 'function setOpen(open, options)');
assert.match(wallpapers, /data-wp="' \+ escAttr\(w\.name\)/);
assert.match(wallpapers, /title="' \+ escAttr\(w\.title\)/);
assert.match(wallpapers, /data-src="' \+ escAttr\(wallpaperUrl\)/);
@@ -82,7 +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, 2);
+ 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\.nickname \|\| '未命名'\)/g) || []).length, 2);
assert.match(accounts, /var nameVal = state\.mask \? maskAccountName\(rawName\) : rawName;/);
assert.match(accounts, /var idVal = state\.mask \? maskAccountId\(rawId\) : rawId;/);
@@ -100,24 +105,19 @@ test('account masking preference persists per WorkDaddy profile', () => {
assert.match(toggle, /localStorage\.setItem\(WBS_ACCOUNT_MASK_KEY, state\.mask \? '1' : '0'\)/);
});
-test('dynamic error and check-in messages are escaped before HTML insertion', () => {
- assert.match(source, /wbs-checkin-tag fail[^\n]+esc\(msg\)/);
+test('dynamic errors are escaped and check-in messages never enter badge HTML', () => {
+ assert.doesNotMatch(sourceBetween('function checkinHtml', 'function el(tag'), /c\.message|esc\(msg\)/);
assert.match(source, /会话加载失败: ' \+ esc\(e\.message \|\| e\)/);
assert.match(source, /模型加载失败:' \+ esc\(e\.message \|\| e\)/);
assert.match(source, /无法连接本地服务: ' \+ esc\(e\.message \|\| e\)/);
assert.doesNotMatch(source, /innerHTML\s*=\s*'[^\n]*'\s*\+\s*\(e\.message \|\| e\)/);
});
-test('inspector escapes page-controlled labels, attributes, paths and computed style values', (t) => {
- if (!picker) return t.skip('picker-internal.js 未就绪(内部模块不入库)');
- const inspector = sourceBetween('function showInspector(stack, fallbackEl)', 'function stopInspect()', picker);
+test('automation inspector escapes page-controlled tree labels and copies element details as plain text', () => {
+ const inspector = sourceBetween('function showAutomationInspector(stack, fallbackEl)', 'function stopAutomationInspect()', automationPicker);
assert.match(inspector, /esc\(nodeLabel\(node\)\)/);
- assert.match(inspector, /esc\(queryPath\)/);
- assert.match(inspector, /esc\(attr\.name\)/);
- assert.match(inspector, /esc\(attr\.value\)/);
- assert.match(inspector, /esc\(value \|\| '未定义'\)/);
- assert.match(inspector, /textContent = selected\.outerHTML/);
+ assert.match(inspector, /copyPlainText\(payload\)/);
+ assert.match(inspector, /selected\.outerHTML/);
assert.doesNotMatch(inspector, /\+ nodeLabel\(node\) \+/);
- assert.doesNotMatch(inspector, /\+ queryPath \+/);
assert.doesNotMatch(inspector, /innerHTML = selected\.outerHTML/);
});
diff --git a/test/sleep-mode.test.js b/test/sleep-mode.test.js
new file mode 100644
index 0000000..dd50635
--- /dev/null
+++ b/test/sleep-mode.test.js
@@ -0,0 +1,83 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const { EventEmitter } = require('node:events');
+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/daemon.js'), 'utf8');
+function harness(windows = false) {
+ const children = [], timers = new Set();
+ const ctx = { IS_WIN: windows, log() {},
+ spawn(command, args) {
+ const child = new EventEmitter();
+ Object.assign(child, { spawnargs: [command, ...args], killed: false,
+ kill() { this.killed = true; this.emit('exit'); },
+ });
+ children.push(child);
+ return child;
+ },
+ setInterval(fn) { const timer = { fn, unref() {} }; timers.add(timer); return timer; },
+ clearInterval(timer) { timers.delete(timer); },
+ };
+ vm.createContext(ctx);
+ vm.runInContext(source.slice(source.indexOf('let sleepCaffeinate ='), source.indexOf('function sleepNow()')), ctx);
+ return { ctx, children, timers };
+}
+test('Windows allow releases the exact keep-awake process', () => {
+ const h = harness(true);
+ assert(h.ctx.applySleepMode('keep', false));
+ assert.equal(h.children.length, 1);
+ h.ctx.applySleepMode('allow', false);
+ assert(h.children[0].killed, 'switching to allow must release the Windows power request');
+});
+test('macOS unchanged mode reuses assertions; display sleep removes display and user-active assertions', () => {
+ const h = harness();
+ h.ctx.applySleepMode('keep', false);
+ const first = h.children[0];
+ assert.deepEqual(first.spawnargs, ['caffeinate', '-d', '-i', '-s', '-m']);
+ assert.equal(h.timers.size, 1);
+ h.ctx.applySleepMode('keep', false);
+ assert.equal(h.children[0].killed, false, 'same settings should keep existing assertion');
+ assert.equal(h.children.length, 2);
+ h.ctx.applySleepMode('keep', true);
+ assert(first.killed);
+ assert.equal(h.timers.size, 0);
+ assert.deepEqual(h.children.at(-1).spawnargs, ['caffeinate', '-i', '-s', '-m']);
+ h.ctx.applySleepMode('allow', false);
+ assert(h.children.every(c => c.killed));
+});
+
+test('sleep status reports the Windows power process as active', () => {
+ const block = source.slice(source.indexOf(" if (req.method === 'GET' && p === '/api/sleep-mode')"), source.indexOf(" if (req.method === 'POST' && p === '/api/sleep-mode')"));
+ const readStatus = new Function('req', 'p', 'fs', 'path', 'DATA_DIR', 'res', 'json', 'IS_WIN', 'sleepPowershell', 'sleepCaffeinate', 'sleepUserActivityTimer', block);
+ const result = readStatus({method:'GET'}, '/api/sleep-mode', {readFileSync:()=>'{"mode":"keep"}'}, {join:()=>''}, '', {}, (res, code, body)=>body, true, {}, null, null);
+ assert.equal(result.active, true);
+});
+
+test('until-done waits for every discovered session, including blocked and recently hidden sessions', async () => {
+ const ui = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
+ let now = 100000, poll, controllers = [
+ {conversationId:'a', busy:true}, {conversationId:'b', blocked:true},
+ ];
+ const posts = [];
+ const ctx = {
+ Date: {now:()=>now}, document:{}, alive:true, sleepMode:'until-done',
+ acMulti:{sessions:{}}, sleepSessionCache:Object.create(null), sleepUntilDoneCheck:null,
+ WBS_COMPAT:{findConversationControllers:()=>controllers},
+ acControllerSnapshot:c=>c, isSessionBusy:()=>({busy:false}),
+ setBuildInterval:fn=>{poll=fn;return 1;}, clearInterval(){},
+ api:(route, options)=>{posts.push(JSON.parse(options.body));return Promise.resolve();},
+ toast(){}, syncSleepState(){}, root:{},
+ };
+ vm.createContext(ctx);
+ vm.runInContext(ui.slice(ui.indexOf(' function discoverSleepSessionBusy()'), ui.indexOf(' // 同步防休眠状态:三模式')), ctx);
+ ctx.startUntilDoneCheck();
+ poll(); assert.equal(posts.length, 0);
+ controllers[0].busy = false;
+ poll(); assert.equal(posts.length, 0, 'blocked background session still needs awake system');
+ controllers = [controllers[0]];
+ now += 10000; poll(); assert.equal(posts.length, 0, 'brief virtualization gap is not completion');
+ controllers.push({conversationId:'b', busy:false});
+ poll(); await Promise.resolve();
+ assert.deepEqual(posts, [{mode:'allow', displaySleep:false}]);
+});
diff --git a/test/theme-restore-stability.test.js b/test/theme-restore-stability.test.js
new file mode 100644
index 0000000..2bc6aec
--- /dev/null
+++ b/test/theme-restore-stability.test.js
@@ -0,0 +1,98 @@
+'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/daemon.js'), 'utf8');
+
+test('default theme is restored after navigation just like a custom theme', async () => {
+ const start = source.indexOf('async function restoreSavedTheme()');
+ const end = source.indexOf('\n/**', start);
+ const applied = [];
+ const context = {
+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },
+ DATA_DIR: '/test', path, fs: { existsSync: () => true, readFileSync: () => '{"id":"default"}' },
+ applyThemeByCdp: async id => applied.push(id),
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ await context.restoreSavedTheme();
+ assert.deepEqual(applied, ['default']);
+});
+
+async function themeExpression(id) {
+ const start = source.indexOf('async function applyThemeByCdp(id)');
+ const end = source.indexOf('\n/**', start);
+ let expression;
+ const context = {
+ PROFILE: { capabilities: { theme: true } }, cdp: { connected: true },
+ currentAccount: () => null, getTheme: () => ({ dark: id !== 'default', colors: {} }),
+ LOCAL_THEME_OVERRIDES: [], themeExtrasCss: () => '', themeVarsCss: () => '',
+ cdpSend: async (_, params) => { expression = params.expression; return { result: { value: { applied: true } } }; },
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ await context.applyThemeByCdp(id);
+ return expression;
+}
+
+function renderer() {
+ const observers = [];
+ function element(tag) {
+ const attrs = new Map(), classes = new Set();
+ const el = {
+ tagName: tag,
+ getAttribute: k => attrs.get(k) || null,
+ setAttribute(k, v) { attrs.set(k, v); }, removeAttribute: k => attrs.delete(k),
+ classList: { contains: k => classes.has(k), add: k => classes.add(k), remove: k => classes.delete(k), toggle(k, v) { if (v) classes.add(k); else classes.delete(k); } },
+ remove() { delete nodes[el.id]; },
+ };
+ return el;
+ }
+ const nodes = {};
+ const document = { documentElement: element('HTML'), body: element('BODY'),
+ getElementById: id => nodes[id] || null, createElement: element,
+ head: { appendChild: el => { nodes[el.id] = el; } },
+ };
+ const storage = new Map();
+ const context = { window: {}, document,
+ localStorage: { get length() { return storage.size; }, key: i => [...storage.keys()][i], getItem: k => storage.get(k) || null, setItem: (k, v) => storage.set(k, v) },
+ getComputedStyle: () => ({ getPropertyValue: () => '' }),
+ MutationObserver: class {
+ constructor(callback) { this.callback = callback; this.active = false; observers.push(this); }
+ observe() { this.active = true; } disconnect() { this.active = false; }
+ },
+ };
+ return { context, document, observers, flush: () => observers.filter(o => o.active).forEach(o => o.callback([])) };
+}
+
+test('late account appearance cannot override the chosen light or dark theme', async () => {
+ for (const id of ['default', 'nebula']) {
+ const { context, document, flush } = renderer();
+ vm.runInNewContext(await themeExpression(id), context);
+ const mode = id === 'default' ? 'light' : 'dark';
+ const opposite = mode === 'light' ? 'dark' : 'light';
+ document.documentElement.setAttribute('data-theme', opposite);
+ document.documentElement.classList.toggle('cb-dark', opposite === 'dark');
+ document.body.setAttribute('data-vscode-theme-kind', opposite === 'dark' ? 'vscode-dark' : 'vscode-light');
+ document.body.setAttribute('data-vscode-theme-name', opposite === 'dark' ? 'IDE Night' : 'IDE Light');
+ flush();
+ assert.equal(document.documentElement.getAttribute('data-theme'), mode);
+ assert.equal(document.documentElement.classList.contains('cb-dark'), mode === 'dark');
+ assert.equal(document.body.getAttribute('data-vscode-theme-kind'), mode === 'dark' ? 'vscode-dark' : 'vscode-light');
+ }
+});
+
+test('manually changing theme replaces the prior guard and repeating a theme reuses its style', async () => {
+ const { context, document, observers, flush } = renderer();
+ const dark = await themeExpression('nebula');
+ vm.runInNewContext(dark, context);
+ const style = document.getElementById('wbs-theme-style');
+ vm.runInNewContext(dark, context);
+ assert.equal(document.getElementById('wbs-theme-style'), style);
+ vm.runInNewContext(await themeExpression('default'), context);
+ assert.equal(document.getElementById('wbs-theme-style'), null);
+ assert.equal(observers.filter(o => o.active).length, 1);
+ flush();
+ assert.equal(document.documentElement.getAttribute('data-theme'), 'light');
+});
diff --git a/test/toast-runtime.test.js b/test/toast-runtime.test.js
new file mode 100644
index 0000000..558cbfa
--- /dev/null
+++ b/test/toast-runtime.test.js
@@ -0,0 +1,55 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { validateTask, executeTask } = require('../scripts/automation');
+const { normalizeToastOptions } = require('../scripts/toast-options');
+const source = name => fs.readFileSync(path.join(__dirname, '../', name), 'utf8');
+const task = steps => ({schemaVersion:1,id:'toast-test',name:'Toast test',steps});
+test('toast validates levels, duration and id before execution', () => {
+ assert.deepEqual(normalizeToastOptions({level:'loading',id:'progress',duration:5000}),{level:'loading',id:'progress',duration:5000});
+ for(const step of [{op:'notify.toast',duration:-1},{op:'notify.toast',duration:60001},{op:'notify.toast',level:'bad'},{op:'notify.dismiss'},{op:'notify.dismiss',id:'<bad>'}]) assert.throws(()=>validateTask(task([step])));
+});
+test('automation waits for toast delivery and passes id, duration, level and dismissal', async () => {
+ const calls=[];
+ await executeTask(task([{op:'notify.toast',level:'loading',message:'处理 {{vars.item}}',id:'progress',duration:9000,saveAs:'notice'},{op:'notify.toast',level:'success',message:'完成',id:'{{vars.notice.id}}'},{op:'notify.dismiss',id:'{{vars.notice.id}}'}]),{
+ notifyToast:async (level,message,options)=>{await new Promise(r=>setTimeout(r,5));calls.push({level,message,...options});return {ok:true,id:options.id};},
+ dismissToast:async id=>{calls.push({dismiss:id});return {ok:true};},
+ });
+ assert.equal(calls[0].duration,9000);assert.equal(calls[1].id,'progress');assert.equal(calls[1].level,'success');assert.equal(calls[2].dismiss,'progress');
+});
+test('toast delivery errors fail automation instead of silently succeeding', async () => {
+ await assert.rejects(executeTask(task([{op:'notify.toast',message:'hello'}]),{notifyToast:async()=>{throw Error('disconnected');}}),/disconnected/);
+ await assert.rejects(executeTask(task([{op:'notify.toast',message:'hello'}]),{}),/通知/);
+});
+test('local official library, shadow styles and viewport host are included in injection and packaging', () => {
+ assert.match(source('scripts/toast-runtime.js'),/react-hot-toast.*2\.6\.0/);
+ assert.match(source('tools/toast-runtime/entry.jsx'),/position="bottom-center"/);
+ assert.match(source('tools/toast-runtime/entry.jsx'),/attachShadow/);
+ assert.match(source('tools/toast-runtime/goober-scoped.js'),/target: styleTarget/);
+ assert.match(source('scripts/daemon.js'),/'toast-runtime.js'/);
+ assert.match(source('scripts/build-mac-dmg.sh'),/toast-runtime.js/);
+ assert.doesNotMatch(source('scripts/inject.js'),/var t = el\('div', 'wbs-toast'/);
+ assert.match(source('scripts/inject.js'),/toastRuntime\.destroy\(\)/);
+});
+test('run notification ids are isolated and cleanup dismisses only unfinished loading toasts', async () => {
+ const { createAutomationNotifier } = require('../scripts/toast-options');
+ const calls=[];const send=async detail=>{calls.push(detail);return {ok:true};};
+ const a=createAutomationNotifier(send,'run-a'),b=createAutomationNotifier(send,'run-b');
+ await a.show('loading','work',{id:'progress'});
+ await a.show('success','done',{id:'progress'});
+ await b.show('loading','work',{id:'progress'});
+ await a.cleanup();assert.equal(calls.length,3);
+ await b.cleanup();assert.deepEqual(calls[3],{action:'dismiss',id:'run-b:progress'});
+ await a.dismiss('progress');assert.equal(calls[4].id,'run-a:progress');
+});
+test('cleanup immediately dismisses a loading toast whose delivery finishes after cancellation', async () => {
+ const { createAutomationNotifier } = require('../scripts/toast-options');
+ let release;const pending=new Promise(resolve=>{release=resolve;});const calls=[];
+ const notifier=createAutomationNotifier(async detail=>{calls.push(detail);if(detail.action!=='dismiss')await pending;},'cancelled');
+ const showing=notifier.show('loading','waiting',{id:'pending'});
+ await notifier.cleanup();release();await showing;
+ assert.equal(calls[1].action,'dismiss');assert.equal(calls[1].id,'cancelled:pending');
+ await assert.rejects(notifier.show('loading','late'),/结束/);
+});
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index e1d1cde..3d47438 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -772,7 +772,7 @@ test('account cards keep the compact three-row layout', () => {
assert.match(script, /var idLbl = a\.phone \? '手机' : \(a\.uin \? 'UIN' : '账号'\)/);
assert.match(script, /\.wbs-phone-cell\.wbs-uin-cell\{gap:4px\}/);
// 国际版:签到标签不展示;新版布局按能力把暂存按钮内联进操作栏按钮组第一位。
- assert.match(script, /if \(PROFILE_ID === 'workbuddy-ai'\) return '';/);
+ assert.match(script, /if \(WBS_PROFILE_IS_AI\) return '';/);
assert.match(script, /WBS_COMPAT\.findComposerToolbar\(document\)/);
assert.match(script, /wbs-stash-inline-inline/);
assert.match(script, /row0\.insertBefore\(stashBtn, row0\.firstChild\)/);
@@ -802,8 +802,8 @@ test('account cards keep the compact three-row layout', () => {
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, /\.wbs-checkin-tag\.ok\{background:#edf9ef/);
- assert.match(script, /html\.cb-dark \.wbs-checkin-tag\.ok\{/);
- assert.match(script, /今日已签到✓/);
+ assert.match(script, /html\.cb-dark \.wbs-checkin-tag\.ok,html\[data-theme="dark"\] \.wbs-checkin-tag\.ok\{/);
+ assert.match(script, /今日签到/);
assert.match(script, /function accountStatusTagsHtml\(a\)/);
assert.match(script, /function checkinBadgeHtml\(a\)/);
assert.match(script, /badge \+ checkinBadge/);
@@ -823,10 +823,10 @@ test('account cards keep the compact three-row layout', () => {
test('account cards sort by credit expiry without pinning the current account', () => {
const script = read('inject.js');
- assert.match(script, /state\.current = data\.current;\s*state\.accounts = \(data\.accounts \|\| \[\]\)\.slice\(\);/);
+ assert.match(script, /state\.current = data\.current;\s*state\.accounts = mergeAccountSnapshot\(previous, data\.accounts \|\| \[\]\);/);
// render():不再把当前账号置顶,统一按积分到期时间升序
assert.doesNotMatch(script, /state\.accounts\.sort\(function \(left, right\) \{[\s\S]*left\.uid === state\.current\.uid[\s\S]*right\.uid === state\.current\.uid[\s\S]*return leftIsCurrent \? -1 : 1;[\s\S]*\}\);/);
- assert.match(script, /function render\(data\) \{[\s\S]*state\.accounts\.sort\(function \(left, right\) \{[\s\S]*nearestCreditExpiry\(left\)[\s\S]*nearestCreditExpiry\(right\)[\s\S]*le - re[\s\S]*\}\);/);
+ assert.match(script, /function render\(data\) \{[\s\S]*if \(!previous\.length \|\| !state\.open\) sortAccountsByCreditExpiry\(\);/);
// sortAccountsByCreditExpiry:去掉当前账号置顶,仅按到期时间 + 稳定序
assert.match(script, /function sortAccountsByCreditExpiry\(\) \{[\s\S]*isCurrent:[\s\S]*a\.expiresAt !== b\.expiresAt[\s\S]*a\.expiresAt - b\.expiresAt[\s\S]*a\.index - b\.index/);
assert.doesNotMatch(script, /function sortAccountsByCreditExpiry\(\) \{[\s\S]*if \(a\.isCurrent !== b\.isCurrent\) return a\.isCurrent \? -1 : 1;/);
@@ -1224,11 +1224,11 @@ test('session summary counts effective sessions and models tab only exposes sani
assert.match(inject, /data-model-tab="mine">备选模型/);
assert.match(inject, /data-model-import=/);
assert.match(inject, /\/api\/models\/import/);
- assert.match(inject, /签到请求完成后再查询积分/);
+ assert.match(inject, /workdaddy:accounts-updated/);
assert.match(inject, /fetchCreditsForAccounts\(\);/);
- assert.match(read('lib.js'), /function checkinDisplayValue\(record, today, pending\)/);
+ assert.match(read('lib.js'), /function checkinDisplayValue\(record, today\)/);
assert.match(daemon, /CREDIT_USAGE_STORE\.listDailyCheckins/);
- assert.match(daemon, /checkin: checkinDisplayValue\(checked, today, checkinPending\)/);
+ assert.match(daemon, /checkin: checkinDisplayValue\(checked, today\)/);
assert.doesNotMatch(inject, /id="wbs-model-refresh"/);
assert.match(inject, /wbs-model-group-title/);
assert.match(inject, /delete-official/);
diff --git a/tools/toast-runtime/README.md b/tools/toast-runtime/README.md
new file mode 100644
index 0000000..e98fbc7
--- /dev/null
+++ b/tools/toast-runtime/README.md
@@ -0,0 +1,24 @@
+# Local react-hot-toast runtime
+
+WorkDaddy bundles react-hot-toast 2.6.0, React / React DOM 18.3.1 and goober 2.1.18 in `scripts/toast-runtime.js`. Runtime startup needs no npm install, CDN, or React object from WorkBuddy. Production dependencies and their MIT licenses are embedded in that generated file.
+
+To rebuild after editing this directory:
+
+```sh
+npm ci --ignore-scripts --prefix tools/toast-runtime
+node tools/toast-runtime/build.mjs
+```
+
+The adapter uses the upstream `Toaster` / `ToastBar` with `bottom-center` placement and an isolated React root. goober's supported `target` binding directs its styles and keyframes into the toast shadow root. WorkBuddy theme variables inherit through the host. Reinjection unmounts the React tree, clears the toast store, and removes the host and styles. React is bundled privately; official WorkBuddy components and state are never modified.
+
+Automation protocol:
+
+```json
+[
+ { "op": "notify.toast", "level": "loading", "message": "正在处理…", "id": "progress" },
+ { "op": "logic.delay", "ms": 1500 },
+ { "op": "notify.toast", "level": "success", "message": "任务完成", "id": "progress", "duration": 4200 }
+]
+```
+
+Levels: `info`, `success`, `warning`, `error`, `loading`. `duration` is an integer in milliseconds, 1000–60000; ordinary notifications default to 4200 ms and loading notifications persist until updated, dismissed, or the run ends. Reusing an `id` updates that notification. `{ "op": "notify.dismiss", "id": "progress" }` dismisses it. `saveAs` retains `{ok,id}` for interpolation as `{{vars.<name>.id}}`. IDs are isolated per run. Delivery is acknowledged by the renderer; disconnected or missing notification components cause the step to fail. User-facing message content is not added to automation logs.
diff --git a/tools/toast-runtime/build.mjs b/tools/toast-runtime/build.mjs
new file mode 100644
index 0000000..f1e5e27
--- /dev/null
+++ b/tools/toast-runtime/build.mjs
@@ -0,0 +1,11 @@
+import { build } from 'esbuild';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+const dir = path.dirname(fileURLToPath(import.meta.url));
+const notices = ['react','react-dom','scheduler','react-hot-toast','goober'].map(name => `${name}\n${fs.readFileSync(path.join(dir,'node_modules',name,'LICENSE'),'utf8')}`).join('\n\n');
+const output = path.resolve(dir,'../../scripts/toast-runtime.js');
+await build({ absWorkingDir:dir,entryPoints:['entry.jsx'],outfile:output,bundle:true,minify:true,format:'iife',platform:'browser',target:['chrome110'],define:{'process.env.NODE_ENV':'"production"'},alias:{goober:path.join(dir,'goober-scoped.js')},legalComments:'eof',
+ banner:{js:'/* Generated by tools/toast-runtime/build.mjs; React 18.3.1 / react-hot-toast 2.6.0. */\nwindow.__wbsToastRuntime?.destroy();'},
+});
+fs.appendFileSync(output,'\n/* Third-party licenses:\n'+notices.replaceAll('*/','* /')+'\n*/\n');
diff --git a/tools/toast-runtime/entry.jsx b/tools/toast-runtime/entry.jsx
new file mode 100644
index 0000000..58a088b
--- /dev/null
+++ b/tools/toast-runtime/entry.jsx
@@ -0,0 +1,47 @@
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { flushSync } from 'react-dom';
+import hotToast, { Toaster, ToastBar } from 'react-hot-toast';
+import { styleTarget } from './goober-scoped';
+
+let host, reactRoot;
+const textColor = 'var(--wb-color-text-primary,#1f1f1f)';
+function mount() {
+ if (host?.isConnected) return;
+ destroy();
+ host = document.createElement('div');
+ host.id = 'wbs-toast-root';
+ host.style.cssText = 'position:fixed;inset:0;z-index:2147483647;pointer-events:none;';
+ const shadow = host.attachShadow({ mode: 'open' });
+ const style = document.createElement('style');
+ style.textContent = ':host{font:12px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:var(--wb-color-text-primary,#1f1f1f)}*{box-sizing:border-box}.wbs-hot-message{white-space:pre-wrap;overflow-wrap:anywhere;min-width:0;max-height:min(35vh,200px);overflow:auto}.wbs-hot-close{width:22px;height:22px;flex:0 0 22px;border:0;border-radius:6px;background:transparent;color:var(--wb-color-text-secondary,#666);font:18px/1 sans-serif;cursor:pointer;margin-left:4px}.wbs-hot-close:hover{background:var(--wb-bg-hover,#eee)}.wbs-hot-close:focus-visible{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:1px}';
+ shadow.append(style, styleTarget);
+ const node = document.createElement('div');
+ shadow.appendChild(node);
+ // Toast interaction cannot reach WorkBuddy's composer or overlay handlers.
+ for (const type of ['click', 'pointerdown', 'pointerup', 'keydown', 'keyup']) shadow.addEventListener(type, e => e.stopPropagation());
+ document.body.appendChild(host);
+ reactRoot = createRoot(node);
+ flushSync(() => reactRoot.render(<Toaster position="bottom-center" gutter={8} containerStyle={{ bottom: 24, top: 16, left: 16, right: 16 }} toastOptions={{
+ duration: 4200,
+ removeDelay: 250,
+ style: { fontSize: 12, lineHeight: 1.5, maxWidth: 'min(440px,calc(100vw - 32px))', padding: '9px 12px', borderRadius: 10, background: 'var(--wb-bg-popover,var(--wb-bg-secondary,#fff))', color: textColor, border: '1px solid var(--wb-border-default,#e6e6e6)', boxShadow: '0 6px 24px rgb(0 0 0 / 14%)' },
+ }}>{t => <ToastBar toast={t}>{({ icon, message }) => <>{icon}<div className="wbs-hot-message">{message}</div><button className="wbs-hot-close" aria-label="Dismiss notification" title="关闭 / Close" onClick={() => hotToast.dismiss(t.id)}>×</button></>}</ToastBar>}</Toaster>));
+}
+function show(detail = {}) {
+ mount();
+ const level = ['info','success','warning','error','loading'].includes(detail.level) ? detail.level : 'info';
+ const message = String(detail.message ?? '').slice(0, 2000);
+ const options = { id: detail.id || undefined, position: 'bottom-center', duration: Number.isFinite(detail.duration) ? Math.min(60000, Math.max(1000, detail.duration)) : level === 'loading' ? Infinity : 4200,
+ ariaProps: { role: level === 'error' ? 'alert' : 'status', 'aria-live': level === 'error' ? 'assertive' : 'polite' } };
+ if (level === 'warning') options.icon = <span aria-hidden="true" style={{color:'var(--wb-accent-orange,#b96b00)',fontWeight:700,fontSize:16}}>!</span>;
+ const handler = hotToast[level] || hotToast;
+ return handler(message, options);
+}
+function dismiss(id) { hotToast.dismiss(id); }
+function destroy() {
+ hotToast.remove();
+ if (reactRoot) { reactRoot.unmount(); reactRoot = null; }
+ host?.remove(); host = null;
+}
+window.__wbsToastRuntime = { mount, show, dismiss, destroy, version: '[email protected]' };
diff --git a/tools/toast-runtime/goober-scoped.js b/tools/toast-runtime/goober-scoped.js
new file mode 100644
index 0000000..4190677
--- /dev/null
+++ b/tools/toast-runtime/goober-scoped.js
@@ -0,0 +1,10 @@
+// Use goober's documented target binding so upstream Toaster animations and
+// icons stay inside our shadow root, without touching WorkBuddy's stylesheet.
+import { css as baseCss, styled as baseStyled, setup } from './node_modules/goober/dist/goober.modern.js';
+export const styleTarget = document.createElement('div');
+styleTarget.hidden = true;
+styleTarget.id = 'wbs-toast-library-styles';
+export const css = baseCss.bind({ target: styleTarget });
+export const keyframes = baseCss.bind({ target: styleTarget, k: 1 });
+export const styled = baseStyled.bind({ target: styleTarget });
+export { setup };
diff --git a/tools/toast-runtime/package-lock.json b/tools/toast-runtime/package-lock.json
new file mode 100644
index 0000000..3eac8c2
--- /dev/null
+++ b/tools/toast-runtime/package-lock.json
@@ -0,0 +1,587 @@
+{
+ "name": "workdaddy-toast-runtime",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "workdaddy-toast-runtime",
+ "dependencies": {
+ "goober": "2.1.18",
+ "react": "18.3.1",
+ "react-dom": "18.3.1",
+ "react-hot-toast": "2.6.0"
+ },
+ "devDependencies": {
+ "esbuild": "0.25.9"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.9.tgz",
+ "integrity": "sha512-OaGtL73Jck6pBKjNIe24BnFE6agGl+6KxDtTfHhy1HmhthfKouEcOhqpSL64K4/0WCtbKFLOdzD/44cJ4k9opA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.9.tgz",
+ "integrity": "sha512-5WNI1DaMtxQ7t7B6xa572XMXpHAaI/9Hnhk8lcxF4zVN4xstUgTlvuGDorBguKEnZO70qwEcLpfifMLoxiPqHQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.9.tgz",
+ "integrity": "sha512-IDrddSmpSv51ftWslJMvl3Q2ZT98fUSL2/rlUXuVqRXHCs5EUF1/f+jbjF5+NG9UffUDMCiTyh8iec7u8RlTLg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.9.tgz",
+ "integrity": "sha512-I853iMZ1hWZdNllhVZKm34f4wErd4lMyeV7BLzEExGEIZYsOzqDWDf+y082izYUE8gtJnYHdeDpN/6tUdwvfiw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.9.tgz",
+ "integrity": "sha512-XIpIDMAjOELi/9PB30vEbVMs3GV1v2zkkPnuyRRURbhqjyzIINwj+nbQATh4H9GxUgH1kFsEyQMxwiLFKUS6Rg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.9.tgz",
+ "integrity": "sha512-jhHfBzjYTA1IQu8VyrjCX4ApJDnH+ez+IYVEoJHeqJm9VhG9Dh2BYaJritkYK3vMaXrf7Ogr/0MQ8/MeIefsPQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.9.tgz",
+ "integrity": "sha512-z93DmbnY6fX9+KdD4Ue/H6sYs+bhFQJNCPZsi4XWJoYblUqT06MQUdBCpcSfuiN72AbqeBFu5LVQTjfXDE2A6Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.9.tgz",
+ "integrity": "sha512-mrKX6H/vOyo5v71YfXWJxLVxgy1kyt1MQaD8wZJgJfG4gq4DpQGpgTB74e5yBeQdyMTbgxp0YtNj7NuHN0PoZg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.9.tgz",
+ "integrity": "sha512-HBU2Xv78SMgaydBmdor38lg8YDnFKSARg1Q6AT0/y2ezUAKiZvc211RDFHlEZRFNRVhcMamiToo7bDx3VEOYQw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.9.tgz",
+ "integrity": "sha512-BlB7bIcLT3G26urh5Dmse7fiLmLXnRlopw4s8DalgZ8ef79Jj4aUcYbk90g8iCa2467HX8SAIidbL7gsqXHdRw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.9.tgz",
+ "integrity": "sha512-e7S3MOJPZGp2QW6AK6+Ly81rC7oOSerQ+P8L0ta4FhVi+/j/v2yZzx5CqqDaWjtPFfYz21Vi1S0auHrap3Ma3A==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.9.tgz",
+ "integrity": "sha512-Sbe10Bnn0oUAB2AalYztvGcK+o6YFFA/9829PhOCUS9vkJElXGdphz0A3DbMdP8gmKkqPmPcMJmJOrI3VYB1JQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.9.tgz",
+ "integrity": "sha512-YcM5br0mVyZw2jcQeLIkhWtKPeVfAerES5PvOzaDxVtIyZ2NUBZKNLjC5z3/fUlDgT6w89VsxP2qzNipOaaDyA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.9.tgz",
+ "integrity": "sha512-++0HQvasdo20JytyDpFvQtNrEsAgNG2CY1CLMwGXfFTKGBGQT3bOeLSYE2l1fYdvML5KUuwn9Z8L1EWe2tzs1w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.9.tgz",
+ "integrity": "sha512-uNIBa279Y3fkjV+2cUjx36xkx7eSjb8IvnL01eXUKXez/CBHNRw5ekCGMPM0BcmqBxBcdgUWuUXmVWwm4CH9kg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.9.tgz",
+ "integrity": "sha512-Mfiphvp3MjC/lctb+7D287Xw1DGzqJPb/J2aHHcHxflUo+8tmN/6d4k6I2yFR7BVo5/g7x2Monq4+Yew0EHRIA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.9.tgz",
+ "integrity": "sha512-iSwByxzRe48YVkmpbgoxVzn76BXjlYFXC7NvLYq+b+kDjyyk30J0JY47DIn8z1MO3K0oSl9fZoRmZPQI4Hklzg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.9.tgz",
+ "integrity": "sha512-9jNJl6FqaUG+COdQMjSCGW4QiMHH88xWbvZ+kRVblZsWrkXlABuGdFJ1E9L7HK+T0Yqd4akKNa/lO0+jDxQD4Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.9.tgz",
+ "integrity": "sha512-RLLdkflmqRG8KanPGOU7Rpg829ZHu8nFy5Pqdi9U01VYtG9Y0zOG6Vr2z4/S+/3zIyOxiK6cCeYNWOFR9QP87g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.9.tgz",
+ "integrity": "sha512-YaFBlPGeDasft5IIM+CQAhJAqS3St3nJzDEgsgFixcfZeyGPCd6eJBWzke5piZuZ7CtL656eOSYKk4Ls2C0FRQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.9.tgz",
+ "integrity": "sha512-1MkgTCuvMGWuqVtAvkpkXFmtL8XhWy+j4jaSO2wxfJtilVCi0ZE37b8uOdMItIHz4I6z1bWWtEX4CJwcKYLcuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.9.tgz",
+ "integrity": "sha512-4Xd0xNiMVXKh6Fa7HEJQbrpP3m3DDn43jKxMjxLLRjWnRsfxjORYJlXPO4JNcXtOyfajXorRKY9NkOpTHptErg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.9.tgz",
+ "integrity": "sha512-WjH4s6hzo00nNezhp3wFIAfmGZ8U7KtrJNlFMRKxiI9mxEK1scOMAaa9i4crUtu+tBr+0IN6JCuAcSBJZfnphw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.9.tgz",
+ "integrity": "sha512-mGFrVJHmZiRqmP8xFOc6b84/7xa5y5YvR1x8djzXpJBSv/UsNK6aqec+6JDjConTgvvQefdGhFDAs2DLAds6gQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.9.tgz",
+ "integrity": "sha512-b33gLVU2k11nVx1OhX3C8QQP6UHQK4ZtN56oFWvVXvz2VkDoe6fbG8TOgHFxEvqeqohmRnIHe5A1+HADk4OQww==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.9.tgz",
+ "integrity": "sha512-PPOl1mi6lpLNQxnGoyAfschAodRFYXJ+9fs6WHXz7CSWKbOqiMZsubC+BQsVKuul+3vKLuwTHsS2c2y9EoKwxQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.25.9",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.9.tgz",
+ "integrity": "sha512-CRbODhYyQx3qp7ZEwzxOk4JBqmD/seJrzPa/cGjY1VtIn5E09Oi9/dB4JwctnfZ8Q8iT7rioVv5k/FNT/uf54g==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.9",
+ "@esbuild/android-arm": "0.25.9",
+ "@esbuild/android-arm64": "0.25.9",
+ "@esbuild/android-x64": "0.25.9",
+ "@esbuild/darwin-arm64": "0.25.9",
+ "@esbuild/darwin-x64": "0.25.9",
+ "@esbuild/freebsd-arm64": "0.25.9",
+ "@esbuild/freebsd-x64": "0.25.9",
+ "@esbuild/linux-arm": "0.25.9",
+ "@esbuild/linux-arm64": "0.25.9",
+ "@esbuild/linux-ia32": "0.25.9",
+ "@esbuild/linux-loong64": "0.25.9",
+ "@esbuild/linux-mips64el": "0.25.9",
+ "@esbuild/linux-ppc64": "0.25.9",
+ "@esbuild/linux-riscv64": "0.25.9",
+ "@esbuild/linux-s390x": "0.25.9",
+ "@esbuild/linux-x64": "0.25.9",
+ "@esbuild/netbsd-arm64": "0.25.9",
+ "@esbuild/netbsd-x64": "0.25.9",
+ "@esbuild/openbsd-arm64": "0.25.9",
+ "@esbuild/openbsd-x64": "0.25.9",
+ "@esbuild/openharmony-arm64": "0.25.9",
+ "@esbuild/sunos-x64": "0.25.9",
+ "@esbuild/win32-arm64": "0.25.9",
+ "@esbuild/win32-ia32": "0.25.9",
+ "@esbuild/win32-x64": "0.25.9"
+ }
+ },
+ "node_modules/goober": {
+ "version": "2.1.18",
+ "resolved": "https://registry.npmjs.org/goober/-/goober-2.1.18.tgz",
+ "integrity": "sha512-2vFqsaDVIT9Gz7N6kAL++pLpp41l3PfDuusHcjnGLfR6+huZkl6ziX+zgVC3ZxpqWhzH6pyDdGrCeDhMIvwaxw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "csstype": "^3.0.10"
+ }
+ },
+ "node_modules/js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
+ "license": "MIT"
+ },
+ "node_modules/loose-envify": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "license": "MIT",
+ "dependencies": {
+ "js-tokens": "^3.0.0 || ^4.0.0"
+ },
+ "bin": {
+ "loose-envify": "cli.js"
+ }
+ },
+ "node_modules/react": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
+ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
+ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "scheduler": "^0.23.2"
+ },
+ "peerDependencies": {
+ "react": "^18.3.1"
+ }
+ },
+ "node_modules/react-hot-toast": {
+ "version": "2.6.0",
+ "resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.0.tgz",
+ "integrity": "sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==",
+ "license": "MIT",
+ "dependencies": {
+ "csstype": "^3.1.3",
+ "goober": "^2.1.16"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "peerDependencies": {
+ "react": ">=16",
+ "react-dom": ">=16"
+ }
+ },
+ "node_modules/scheduler": {
+ "version": "0.23.2",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
+ "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ }
+ }
+ }
+}
diff --git a/tools/toast-runtime/package.json b/tools/toast-runtime/package.json
new file mode 100644
index 0000000..2d4c411
--- /dev/null
+++ b/tools/toast-runtime/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "workdaddy-toast-runtime",
+ "private": true,
+ "scripts": { "build": "node build.mjs" },
+ "dependencies": { "react": "18.3.1", "react-dom": "18.3.1", "react-hot-toast": "2.6.0", "goober": "2.1.18" },
+ "devDependencies": { "esbuild": "0.25.9" }
+}