Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

docs(assets): README 的应用截图与功能 GIF,以及录制工具

dyk98be94f57d1bfd
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a6be611..766b22c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -46,9 +46,8 @@ jobs:
- run: npm run typecheck
- run: npm test
- run: npm run build
- # README 自检(scripts/check-readme.mjs)。--allow-missing:截图和录屏还没全部提交,缺的素材只报警告;
- # docs/assets/ 补齐后去掉这个参数。
- - run: npm run docs:check -- --allow-missing
+ # README 自检(scripts/check-readme.mjs):素材是否存在与体积、中英结构一致、链接与锚点、禁用词、alt
+ - run: npm run docs:check
# Does this change touch the agent host, the gateway or the desktop shell? Only then run the
# Windows end-to-end job below (it needs a Windows runner and ~6 minutes).
diff --git a/README.md b/README.md
index 93f649b..b9db0ea 100644
--- a/README.md
+++ b/README.md
@@ -136,10 +136,10 @@ docker exec amb cat /data/ui-token # 然后打开 http://<主机>:3600/?token=
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/screenshots/chat-dark.webp">
- <img src="docs/assets/screenshots/chat-light.webp" alt="聊天界面:流式回复里有 Markdown 和代码块,输入框里有模型按钮,左侧是机器人列表" width="100%">
+ <img src="docs/assets/screenshots/chat-light.webp" alt="聊天界面:一条带 Markdown 列表和代码块的回复,输入框旁有模型按钮,左侧是机器人列表" width="100%">
</picture>
-<p align="center"><i>和机器人聊天。回复逐字流出,输入框会显示当前用的模型。</i></p>
+<p align="center"><i>和机器人聊天。回复支持 Markdown 和代码块,输入框会显示当前用的模型。</i></p>
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/screenshots/agent-dark.webp">
@@ -164,7 +164,7 @@ docker exec amb cat /data/ui-token # 然后打开 http://<主机>:3600/?token=
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/screenshots/modelflare-dark.webp">
- <img src="docs/assets/screenshots/modelflare-light.webp" alt="设置的 Modelflare 页:已连接的账户、钱包余额、每日用量和默认模型" width="100%">
+ <img src="docs/assets/screenshots/modelflare-light.webp" alt="设置的 Modelflare 页打开了用量弹窗:近 7 天的每日用量,下面是默认模型,余额显示在左下角的账户按钮上" width="100%">
</picture>
<p align="center"><i>应用里的 Modelflare 账户:余额、用量和默认设置。</i></p>
@@ -203,7 +203,7 @@ docker exec amb cat /data/ui-token # 然后打开 http://<主机>:3600/?token=
</p>
<p align="center">
- <img src="docs/assets/features/media-generation.gif" alt="机器人给出带模型和提示词的生图方案,用户确认后,成图出现在聊天里" width="100%">
+ <img src="docs/assets/features/media-generation.gif" alt="机器人生图前先问用哪个模型,用户确认后,成图作为文件交付到聊天里,并在看图窗口中打开" width="100%">
</p>
## 🌐 任意模型,通过 Modelflare
@@ -234,7 +234,7 @@ docker exec amb cat /data/ui-token # 然后打开 http://<主机>:3600/?token=
</p>
<p align="center">
- <img src="docs/assets/features/channels-wechat.gif" alt="扫码连接微信,在手机上发出一个问题,机器人在手机和桌面应用里同时回答" width="100%">
+ <img src="docs/assets/features/channels-wechat.gif" alt="扫码连接微信,在手机上发出一个问题,机器人在手机上回答,同一段对话出现在桌面应用的「最近会话」里" width="100%">
</p>
## 🔒 本地优先,也好看
diff --git a/README_en.md b/README_en.md
index db7e076..ef859fd 100644
--- a/README_en.md
+++ b/README_en.md
@@ -136,10 +136,10 @@ The app UI is currently in Simplified Chinese.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/screenshots/chat-dark.webp">
- <img src="docs/assets/screenshots/chat-light.webp" alt="Chat screen: a streaming reply with Markdown and a code block, the model button in the composer, and the bot list on the left" width="100%">
+ <img src="docs/assets/screenshots/chat-light.webp" alt="Chat screen: a reply with a Markdown list and a code block, the model button in the composer, and the bot list on the left" width="100%">
</picture>
-<p align="center"><i>Chat with a bot. Replies stream in, and the composer shows which model it is using.</i></p>
+<p align="center"><i>Chat with a bot. Replies render Markdown and code, and the composer shows which model it is using.</i></p>
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/screenshots/agent-dark.webp">
@@ -164,7 +164,7 @@ The app UI is currently in Simplified Chinese.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/screenshots/modelflare-dark.webp">
- <img src="docs/assets/screenshots/modelflare-light.webp" alt="Settings, Modelflare tab: connected account, wallet balance, daily usage and the default model" width="100%">
+ <img src="docs/assets/screenshots/modelflare-light.webp" alt="Settings, Modelflare tab with the usage dialog open: daily usage for the last 7 days, the default model row below, and the balance on the account button" width="100%">
</picture>
<p align="center"><i>Your Modelflare account inside the app: balance, usage and defaults.</i></p>
@@ -203,7 +203,7 @@ A bot is more than a chat window: it has a persona, a default model, its own wor
</p>
<p align="center">
- <img src="docs/assets/features/media-generation.gif" alt="A bot proposes an image generation with model and prompt, the user confirms, and the finished image appears in the chat" width="100%">
+ <img src="docs/assets/features/media-generation.gif" alt="A bot asks which model to use for an image, the user confirms, and the finished image arrives in the chat as a file and opens in a viewer" width="100%">
</p>
## 🌐 Any model, through Modelflare
@@ -234,7 +234,7 @@ A bot is more than a chat window: it has a persona, a default model, its own wor
</p>
<p align="center">
- <img src="docs/assets/features/channels-wechat.gif" alt="Scanning a QR code to connect WeChat, sending a question from the phone, and watching the bot answer on the phone and in the desktop app" width="100%">
+ <img src="docs/assets/features/channels-wechat.gif" alt="Scanning a QR code to connect WeChat, sending a question from the phone, and the bot answering on the phone while the conversation shows up under Recent sessions in the desktop app" width="100%">
</p>
## 🔒 Local-first, and easy on the eyes
diff --git a/docs/assets/README.md b/docs/assets/README.md
index d01ba4a..60c6a34 100644
--- a/docs/assets/README.md
+++ b/docs/assets/README.md
@@ -3,9 +3,9 @@
[README.md](../../README.md)(中文)和 [README_en.md](../../README_en.md)(英文)共用这里的素材。应用界面目前只有简体中文,所以截图和录屏没有英文版。
- **脚本生成**:品牌、图表和机器人形象由 [`_src/make-assets.py`](./_src/make-assets.py) 生成,改了规格就重新运行它,不要手工修图。
-- **人工录制**:应用截图和功能录屏要在真实环境里录(录制环境与编码流程见下文)。录好后放到对应路径,跑 `npm run docs:check` 核对尺寸与体积。
+- **录制脚本**:应用截图和功能 GIF 由 [`_src/record/`](./_src/record/README.md) 录制:真实的 `ui/` 界面 + 演示数据的模拟后端 + 无头 Chromium,用法见文末。也可以换成实机录屏(录制环境与编码流程见下文),放到对应路径即可。
-素材全部到位之前,CI 用 `npm run docs:check -- --allow-missing`,缺的文件只报警告。全部提交后去掉 `--allow-missing`(见 `.github/workflows/ci.yml`)。
+改了素材之后跑 `npm run docs:check`(CI 也会跑)核对是否存在、尺寸与体积。
## 总表
@@ -16,18 +16,18 @@
| 3 | `brand/wordmark-light.svg` | SVG(文字转曲线) | viewBox 520×96 | — | — | 12 KB | 脚本 |
| 4 | `brand/wordmark-dark.svg` | SVG(文字转曲线) | viewBox 520×96 | — | — | 12 KB | 脚本 |
| 5 | `brand/social-preview.png` | PNG | 1280×640 | — | — | 400 KB | 脚本 |
-| 6 | `hero/hero-demo.gif` | GIF | 960×656 | 20 s | 12 | 5 MB | 录制 G1 |
+| 6 | `hero/hero-demo.gif` | GIF | 960×656 | 20 s | 12 | 5 MB | 录制脚本 G1(`_src/record`) |
| 7 | `modelflare/modelflare-logo.png` | PNG | 512×512(显示 120×120) | — | — | 40 KB | 原样取自 `https://modelflare.dev/logo.png` |
-| 8 | `download/install-windows.gif` | GIF | 960×540 | 12 s | 10 | 2.5 MB | 录制 G2 |
-| 9–18 | `screenshots/{chat,agent,models,memory,modelflare}-{light,dark}.webp` | 静态 WebP(质量 82) | 1600×1093 | — | — | 300 KB | 截图 |
+| 8 | `download/install-windows.gif` | GIF | 960×540 | 12 s | 10 | 2.5 MB | 录制脚本 G2(`_src/record`) |
+| 9–18 | `screenshots/{chat,agent,models,memory,modelflare}-{light,dark}.webp` | 静态 WebP(质量 82) | 1600×1093 | — | — | 300 KB | 录制脚本截图(`_src/record`) |
| 19–20 | `screenshots/bots-{light,dark}.webp` | 静态 WebP(质量 82) | 1600×480 | — | — | 300 KB | 脚本 |
-| 21 | `features/agent-files.gif` | GIF | 960×656 | 15 s | 10 | 3 MB | 录制 G3 |
-| 22 | `features/computer-use.gif` | GIF | 960×540 | 18 s | 10 | 3 MB | 录制 G4 |
-| 23 | `features/media-generation.gif` | GIF | 960×656 | 14 s | 10 | 3 MB | 录制 G5 |
-| 24 | `features/first-run.gif` | GIF | 960×656 | 16 s | 10 | 3 MB | 录制 G6 |
-| 25 | `features/model-switch.gif` | GIF | 960×656 | 12 s | 10 | 3 MB | 录制 G7 |
-| 26 | `features/memory.gif` | GIF | 960×656 | 16 s | 10 | 3 MB | 录制 G8 |
-| 27 | `features/channels-wechat.gif` | GIF | 960×540 | 18 s | 10 | 3 MB | 录制 G9 |
+| 21 | `features/agent-files.gif` | GIF | 960×656(体积超限,按下文顺序压到 800×547、8 fps) | 15 s | 10 | 3 MB | 录制脚本 G3(`_src/record`) |
+| 22 | `features/computer-use.gif` | GIF | 960×540 | 18 s | 10 | 3 MB | 录制脚本 G4(`_src/record`) |
+| 23 | `features/media-generation.gif` | GIF | 960×656 | 14 s | 10 | 3 MB | 录制脚本 G5(`_src/record`) |
+| 24 | `features/first-run.gif` | GIF | 960×656 | 16 s | 10 | 3 MB | 录制脚本 G6(`_src/record`) |
+| 25 | `features/model-switch.gif` | GIF | 960×656 | 12 s | 10 | 3 MB | 录制脚本 G7(`_src/record`) |
+| 26 | `features/memory.gif` | GIF | 960×656(体积超限,按下文顺序压到 800×547、8 fps) | 16 s | 10 | 3 MB | 录制脚本 G8(`_src/record`) |
+| 27 | `features/channels-wechat.gif` | GIF | 960×540 | 18 s | 10 | 3 MB | 录制脚本 G9(`_src/record`) |
| 28 | `features/characters-eyes.gif` | GIF | 960×300 | 6 s | 15 | 1.5 MB | 脚本 |
| 29–30 | `diagrams/data-flow-{light,dark}.svg` | SVG(文字转曲线) | viewBox 1200×520 | — | — | 60 KB | 脚本 |
| 31–32 | `diagrams/architecture-{light,dark}.svg` | SVG(文字转曲线) | viewBox 1200×520 | — | — | 60 KB | 脚本 |
@@ -161,3 +161,16 @@ cwebp -q 82 -resize 1600 1093 in.png -o chat-light.webp
| 文件 | 作用 |
|---|---|
| `make-assets.py` | 生成 Eyes 标志(SVG + 动画 WebP)、字标、社交预览图、数据流与架构图、机器人横排图和眼睛跟随 GIF,并下载 Modelflare 标志。用法见文件开头注释 |
+
+### `_src/record/`:截图与 GIF 的录制工具
+
+上表来源写着「录制脚本」的 19 个素材由 [`_src/record/`](./_src/record/README.md) 生成:加载仓库里真实的 `ui/` 界面,接一个用演示数据实现 `/amb/api/*` 的模拟后端,无头 Chromium 驱动鼠标键盘并逐帧录制,再用 Pillow 按上面的规格编码。依赖:Node.js ≥ 22、preact 与 htm(`npm ci`)、playwright-core 1.64 及对应的 Chromium、Python 3 + Pillow ≥ 10、Noto Sans SC 字体。
+
+```bash
+node docs/assets/_src/record/record.mjs # 录全部
+node docs/assets/_src/record/record.mjs model-switch # 只重录名字里含这段文字的素材
+node docs/assets/_src/record/record.mjs --list # 列出全部素材
+node docs/assets/_src/record/record.mjs --check # 不开浏览器,核对尺寸、帧数、时长、体积和空白帧
+```
+
+环境变量、每个文件的作用、和卡片不一致的画面(按应用的真实行为录)、哪些窗口是风格化示意,见 [`_src/record/README.md`](./_src/record/README.md)。
diff --git a/docs/assets/_src/record/README.md b/docs/assets/_src/record/README.md
new file mode 100644
index 0000000..ec25877
--- /dev/null
+++ b/docs/assets/_src/record/README.md
@@ -0,0 +1,97 @@
+# 录制工具:README 的应用截图和功能 GIF
+
+`docs/assets/` 里的 10 张应用截图(`screenshots/{chat,agent,models,memory,modelflare}-{light,dark}.webp`)和 9 个功能 GIF(G1–G9)由这里的脚本生成:
+
+- **界面是真的**:直接加载仓库里的 `ui/`(Preact + htm),不改任何应用代码;
+- **后端是模拟的**:`mock-server.mjs` 用演示数据实现界面实际调用的 `/amb/api/*` 接口,响应格式照抄 `src/web/server.ts`;代理回合(活动步骤、审批卡片、提问卡片、回复、文件卡片)按 `scenes.mjs` 里的脚本分段推送,审批卡片要等界面上点了允许才继续;
+- **录制**:无头 Chromium(playwright-core)驱动鼠标和键盘,`Page.startScreencast` 带时间戳收帧,`encode.py` 按目标帧率重采样,用 Pillow 编码 GIF / WebP;
+- **验证全靠程序**:DOM 断言、页面控制台、未实现的接口、尺寸、帧数、时长、体积、像素统计(有没有全空白或全黑的帧段)。
+
+## 依赖
+
+| 依赖 | 说明 |
+|---|---|
+| Node.js ≥ 22 | 模拟后端零依赖,只用内置模块 |
+| preact、htm | 界面的运行时。仓库根目录 `npm ci` 之后在 `node_modules` 里;或用 `AMB_NODE_MODULES` 指向任何装了这两个包的 `node_modules` |
+| playwright-core 1.64 + 对应的 Chromium | 默认找 `site/node_modules/playwright-core`(`cd site && npm install`);或用 `PLAYWRIGHT_CORE` 指定目录、`CHROMIUM_PATH` 指定浏览器(headless shell 156 / revision 1248) |
+| Python 3 + Pillow ≥ 10 | 编码与核对(`encode.py`)、生图演示的成图(`make-illustration.py`)。不需要 ffmpeg、gifski、cwebp |
+| 字体 | Noto Sans SC(`/usr/share/fonts/truetype/noto-cjk/`)和 DejaVu Sans Mono。录制时自动生成一份 fontconfig,把界面字体栈落到的 `system-ui` / `sans-serif` 指向 Noto Sans SC |
+
+## 用法
+
+在仓库根目录:
+
+```bash
+# 录全部(5 对截图 + 9 个 GIF,约 6 分钟)
+node docs/assets/_src/record/record.mjs
+
+# 只重录某几个:名字里含这段文字即可,可以给多个
+node docs/assets/_src/record/record.mjs model-switch
+node docs/assets/_src/record/record.mjs shot-chat shot-models hero
+
+# 列出全部素材的名字和输出路径
+node docs/assets/_src/record/record.mjs --list
+
+# 核对成品(不开浏览器):尺寸、帧数、时长、帧率、体积上限、空白 / 全黑帧段,以及上次录制留下的报错记录
+node docs/assets/_src/record/record.mjs --check
+python3 docs/assets/_src/record/encode.py --verify docs/assets/features/model-switch.gif # 单个文件的明细
+npm run docs:check
+```
+
+环境变量:`PLAYWRIGHT_CORE`、`CHROMIUM_PATH`、`AMB_NODE_MODULES`(见上表);`REC_TMP` 放帧和中间文件的目录(默认系统临时目录下的 `amb-record`);`REC_KEEP_FRAMES=1` 编码后保留原始帧。
+
+每个素材录完会在 `$REC_TMP/<名字>/report.json` 里留下:编码结果、时间线(每次点击、输入、关键画面出现的秒数,用来对照 GIF 卡片的时间点)、页面控制台的报错和警告、失败的请求、模拟后端收到的未实现接口。全部录完后汇总到 `$REC_TMP/summary.json`,并在终端打印这几类问题的条数。
+
+单独启动模拟后端,在浏览器里手动看演示数据:
+
+```bash
+node docs/assets/_src/record/mock-server.mjs --scene demo --port 4173 # 演示就绪:已登录、六个机器人
+node docs/assets/_src/record/mock-server.mjs --scene signed-out --port 4173 # 退出登录后(在终端按回车模拟浏览器里的授权)
+node docs/assets/_src/record/mock-server.mjs --scene fresh --port 4173 # 全新安装:只有「我的助手」
+```
+
+## 文件
+
+| 文件 | 作用 |
+|---|---|
+| `record.mjs` | 入口:起模拟后端和浏览器、跑 `scenes.mjs` 里的脚本、收帧、调 `encode.py` 编码并核对、汇总报错 |
+| `scenes.mjs` | 每个素材的数据场景、代理回合脚本(步骤、审批、回复)、鼠标与键盘动作和时间点 |
+| `mock-server.mjs` | 模拟后端:静态文件、`/amb/api/*`、流式回复(SSE)、审批等待、微信扫码与收消息 |
+| `demo-data.mjs` | 演示数据:六个机器人、模型目录与参考价、会话、记忆、账户(余额 12.40 美元)、用量 |
+| `stage/` | 录制舞台:应用窗口(iframe)、假鼠标,以及应用之外的示意窗口 |
+| `encode.py` | 重采样与编码(GIF / WebP),超出体积上限时按 `docs/assets/README.md` 的顺序压缩;`--verify` 核对成品 |
+| `make-illustration.py` | 生图演示的成图:用 `ui/design/bots/yellow.webp` 合成"黄色小机器人趴在键盘上打瞌睡"的扁平插画 |
+
+## 录制约定
+
+- 视口 1200×820(应用默认窗口大小,只录内容区);截图 `deviceScaleFactor` 2 截 2400×1640,缩到 1600×1093,WebP 质量 82;明暗两张是同一页面同一时刻,只切系统配色(界面「跟随系统」),截图时禁用动画、隐藏输入光标、鼠标停在窗口边缘的空白处。
+- GIF 一律深色。屏幕帧按卡片的尺寸和帧率重采样,最后一帧停 1 秒,无限循环;全局调色板、不抖动;第 2 帧起只存变化区域、区域里没变的像素记成透明,写完再解码一遍逐帧比对。超出体积上限时依次有损 → 帧率 8 → 宽度 800:`agent-files` 和 `memory` 走到了最后一档(800×547、8 fps),其余 7 个原样就在上限内。
+- 假鼠标是默认箭头,跟着 Playwright 的真实鼠标事件走(所以悬停效果是真的),按下时缩一下并出一圈淡环;每次移动不少于 0.6 秒,点击前停 0.3 秒;打字逐字输入,每条提示词不超过 4 秒。
+- 用户代理是 Windows 的 Chrome(界面会加上 `.win`),路径和命令按 Windows 写(代理用 `pwsh`)。
+
+## 和 GIF / 截图卡片不一致的地方(按应用的真实行为录)
+
+| 素材 | 卡片 | 实际画面与原因 |
+|---|---|---|
+| 所有回复 | "流式回复""看到回复开头" | 桌面版默认是代理模式(`agent.mode` 默认 `dsh`),代理回合的回复在结束时一次给出(`src/core/runtime.ts` handleAgent 只发 `stream.finish`),过程中是"思考中 · 等待 <模型> 回复"和活动步骤 |
+| `agent` 截图 | 活动列表的最后一步是审批卡片 | 审批卡片插在回复状态行的上方(`ui/screens/chat.js` 的 `card()`),活动列表在它下面,最后一步是"进行中"的那条 pwsh 命令;活动列表默认折叠,点状态行展开 |
+| `models` 截图 | 搜索框为空时列表至少 8 个模型 | 不筛选时模型按族折叠,只展开当前模型所在的族(Claude);脚本点开了 GPT 族,列表滚到 GPT 的第一个模型,视野里是 GPT 4 个 + Claude 4 个;悬停的是视野里的第三行 |
+| `modelflare` 截图 | 近 7 天用量 | 用量在「用量 → 查看」打开的弹窗里;弹窗只压暗不模糊,下面的「默认模型」行可见,余额显示在左下角账户按钮上(余额那一行大半被弹窗挡住) |
+| G1 | 全新启动的欢迎页,登录后"小黄被选中,模型已就绪" | 全新安装只有应用自建的「我的助手」(`src/app.ts` seedDefaultBot),所以录的是"退出登录后再登录":欢迎页是同一个;登录回来先到选模型页("已连接 · 找到 N 个模型"),点「开始对话」才进主界面 |
+| G1、G3 | 活动列表逐步出现 | 点一下回复上方的状态行把它展开(默认折叠),之后步骤逐条出现 |
+| G2 | 系统的未知应用提示 | 没有模拟系统的安全提示;安装向导按 `package.json` 的 NSIS 配置(`oneClick: false`、可改安装目录)走:安装选项 → 安装位置 → 进度 → 完成(勾选"运行") |
+| G5 | 成图出现在聊天里 | 聊天里成图是文件卡片(`present` 交付的文件,界面不预览图片);卡片出现后旁边弹出一个示意的看图窗口展示成图。确认卡片是生图前的提问卡片:鼠标在另一个模型选项上停 1 秒,再点默认模型确认 |
+| G6 | 欢迎页 → 授权 → 模型列表 → 对话 | 全新安装的机器人是「我的助手」(蓝色);登录回来的选模型页里点了 claude-sonnet-5-5 再点「开始对话」 |
+| G7 | 搜索 claude 后的列表 | 除了 4 个 Claude 模型,最后还有一行「使用「claude」 自定义模型 ID」(输入的不是现成 ID 时界面给的) |
+| G8 | 记忆区新条目高亮 1 秒 | 界面没有高亮效果,记忆行也不响应悬停;改为鼠标指着新条目停 1 秒。"新建对话"用的是对话顶栏的「开始新的一段对话」(发 `/new`),旧消息仍留在页面上 |
+| G9 | 桌面应用里同一段对话同步出现 | 微信会话出现在 信息面板 → 最近会话(每 8 秒刷新一次),点开是对话记录弹层;二维码到"已连接"之间是界面自己的刷新(每 1.5 秒),脚本把状态切换对齐到刷新前,没有剪辑 |
+
+## 风格化示意(不是真实界面)
+
+都在 `stage/`,中性的深色窗口,不仿任何系统或第三方产品:
+
+- G1、G6:浏览器窗口和 Modelflare 授权页(地址栏 modelflare.dev,一张"AnyModelBot 想连接你的 Modelflare 账户 / 继续"的卡片);
+- G2:桌面、下载文件夹窗口、安装向导;
+- G4:桌面、文本编辑器窗口(记事本)和它的另存为对话框、桌面图标;
+- G5:看图窗口;
+- G9:手机聊天界面(通用样式,没有腾讯标志,不照抄微信),以及信息面板里的二维码(装饰性图案,不能扫)。
diff --git a/docs/assets/_src/record/demo-data.mjs b/docs/assets/_src/record/demo-data.mjs
new file mode 100644
index 0000000..114c943
--- /dev/null
+++ b/docs/assets/_src/record/demo-data.mjs
@@ -0,0 +1,173 @@
+// 演示数据:机器人、模型目录、会话、记忆、账户。全部是虚构的演示内容,不含真实邮箱、姓名、Key。
+//
+// 模型 ID、上下文长度参照 Modelflare 公开价格目录(https://modelflare.dev/api/pricing)的格式与数值。参考价是演示数字:
+// 目录里的基础价(input_price × completion_ratio)× 各厂商 stable 分组的倍率,单位美元 / 百万 tokens,换算方式同 src/account/model-info.ts。
+
+/** 六个机器人:名字是演示用的,头像角色对应 ui/components/avatar.js 的 BOT_CHARS 键 */
+export const BOTS = [
+ { id: "a3f91c2e", name: "小黄", avatar: "yellow", systemPrompt: "你是一个乐于助人的中文助手,回答简洁准确。" },
+ { id: "5b7d04e9", name: "小蓝", avatar: "blue", systemPrompt: "你是会议纪要助手。把会议记录整理成结论、待办和待定问题。" },
+ { id: "c80e6f13", name: "小绿", avatar: "green", systemPrompt: "你是群聊日报助手。把群里的讨论整理成日报。" },
+ { id: "1d4a9b70", name: "小橙", avatar: "orange", systemPrompt: "你是翻译官。中英互译,保留语气、术语和格式。" },
+ { id: "e62c5a38", name: "小紫", avatar: "purple", systemPrompt: "你是写作助手。帮我起草和润色公告、邮件、周报。" },
+ { id: "97f3d2b4", name: "小红", avatar: "red", systemPrompt: "你是代码助手。阅读和修改工作区里的代码,编写脚本解决问题。" },
+];
+export const YELLOW = BOTS[0].id;
+
+/** 首次启动时应用自己建的默认机器人(src/app.ts seedDefaultBot) */
+export const DEFAULT_BOT = { id: "default", name: "我的助手", avatar: "blue", systemPrompt: "你是一个乐于助人的中文助手,回答简洁准确。" };
+
+/** 机器人默认模型:支持工具调用和图片输入的主流模型 */
+export const BOT_MODEL = "claude-sonnet-5-5";
+
+/**
+ * 对话模型(GET /models 的顺序,即 Modelflare /v1/models 返回的顺序;选择器会按模型族分组、族内按版本排序)。
+ * context:上下文长度;caps:v 视觉 / t 工具 / r 推理;price:[输入, 输出] 美元 / 百万 tokens。
+ */
+export const CHAT_MODELS = [
+ ["claude-opus-5-5", 1_000_000, "vtr", [1.26, 6.3]],
+ ["claude-sonnet-5-5", 1_000_000, "vtr", [0.63, 3.15]],
+ ["claude-opus-4-8", 1_000_000, "vtr", [1.575, 7.875]],
+ ["claude-haiku-4-5", 200_000, "vtr", [0.315, 1.575]],
+ ["gpt-6.1-terra", 1_050_000, "vtr", [0.08, 0.4]],
+ ["gpt-6-sol", 1_050_000, "vtr", [0.16, 0.8]],
+ ["gpt-6-luna", 1_050_000, "vtr", [0.02, 0.1]],
+ ["gpt-5.4", 1_000_000, "vtr", [0.2, 1.2]],
+ ["gemini-3.8-flash", 1_000_000, "vtr", [0.225, 1.125]],
+ ["gemini-3.1-pro-preview", 1_000_000, "vtr", [0.3, 1.8]],
+ ["grok-4.7", 500_000, "vtr", [0.22, 0.66]],
+ ["deepseek-v4-pro", 1_000_000, "tr", [0.771, 2.314]],
+ ["deepseek-v4.1-flash", 1_000_000, "tr", [0.194, 0.774]],
+ ["qwen3.8-max", 1_000_000, "tr", [1.371, 4.114]],
+ ["kimi-k3", 1_000_000, "vtr", [1.857, 9.286]],
+ ["glm-5.3", 200_000, "tr", [0.571, 2]],
+ ["glm-5.3-flash", 1_000_000, "tr", [0.057, 0.2]],
+];
+export const MODEL_IDS = CHAT_MODELS.map(([id]) => id);
+
+/** GET /models/info:{ id: { context, vision, tools, reasoning, price } } */
+export function modelInfo() {
+ const out = {};
+ for (const [id, context, caps, price] of CHAT_MODELS) {
+ out[id] = {
+ context,
+ vision: caps.includes("v"),
+ tools: caps.includes("t"),
+ reasoning: caps.includes("r"),
+ ...(price ? { price: { input: price[0], output: price[1] } } : {}),
+ endpoints: id.startsWith("claude") ? ["anthropic", "openai"] : ["openai", "openai-response"],
+ };
+ }
+ return out;
+}
+
+/** 图片 / 视频模型(GET /media/models,按推荐顺序)与生图确认卡里的参考价(src/agent/media.ts priceNote) */
+export const MEDIA = {
+ image: ["gemini-2.5-flash-image", "gpt-image-2", "seedream-5-0-lite-260128", "wan2.7-image"],
+ video: ["kling-3.0-turbo", "seedance-2.0-fast", "wan2.7-t2v"],
+ recommended: { image: "gemini-2.5-flash-image", video: "kling-3.0-turbo" },
+};
+export const MEDIA_PRICE = {
+ "gemini-2.5-flash-image": "$0.033/张",
+ "gpt-image-2": "按 token 计费",
+ "seedream-5-0-lite-260128": "$0.033/张",
+ "wan2.7-image": "$0.021/张",
+};
+
+/** 演示账户(登录后):不含真实姓名与邮箱 */
+export const ACCOUNT = { name: "演示账户", balanceUsd: 12.4, usedUsd: 7.62, keyTail: "a3f9" };
+
+/** 近 7 天用量(UsageSheet):按天的花费与按模型的合计 */
+export function usage(days = 7) {
+ const perDay = [0.42, 0.88, 0.31, 1.26, 0.67, 0.95, 0.53, 0.74, 0.22, 0.61, 1.08, 0.36, 0.58, 0.81];
+ const reqs = [38, 71, 26, 112, 54, 83, 47, 60, 19, 52, 91, 30, 49, 66];
+ const pad = (n) => String(n).padStart(2, "0");
+ const out = [];
+ const today = new Date();
+ for (let i = days - 1; i >= 0; i--) {
+ const d = new Date(today.getFullYear(), today.getMonth(), today.getDate() - i);
+ const k = (days - 1 - i) % perDay.length;
+ out.push({ date: `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`, usd: perDay[k], requests: reqs[k] });
+ }
+ const total = Math.round(out.reduce((s, x) => s + x.usd, 0) * 100) / 100;
+ const share = [
+ ["claude-sonnet-5-5", 0.58, 0.55],
+ ["claude-opus-5-5", 0.17, 0.08],
+ ["deepseek-v4.1-flash", 0.09, 0.25],
+ ["gemini-2.5-flash-image", 0.09, 0.03],
+ ["kimi-k3", 0.07, 0.09],
+ ];
+ const n = out.reduce((s, x) => s + x.requests, 0);
+ return {
+ days: out,
+ models: share.map(([model, u, r]) => ({ model, usd: Math.round(total * u * 100) / 100, requests: Math.max(1, Math.round(n * r)) })),
+ totalUsd: total,
+ };
+}
+
+/** 侧栏的历史会话:每个机器人一段网页对话([分钟前, 角色, 内容]) */
+export function history(botId) {
+ const H = {
+ [BOTS[0].id]: [
+ [190, "user", "下午三点的评审会,帮我列一下要准备的材料"],
+ [189, "assistant", "可以按这三类准备:\n\n- **背景**:需求来源、目标指标\n- **方案**:架构图、关键取舍、风险\n- **排期**:里程碑和需要协调的人\n\n需要的话我可以先起草方案部分的提纲。"],
+ ],
+ [BOTS[1].id]: [
+ [95, "user", "把今天站会的记录整理成纪要"],
+ [94, "assistant", "已整理:3 条结论、5 个待办(都标了负责人和截止时间),还有 1 个待定问题。"],
+ ],
+ [BOTS[2].id]: [
+ [150, "user", "总结一下产品群今天的讨论"],
+ [149, "assistant", "今天主要讨论了新版引导页:结论是先上线文案修改,动效下周再评估。"],
+ ],
+ [BOTS[3].id]: [
+ [240, "user", "把这段发布说明翻成英文"],
+ [239, "assistant", "Here is the English version, keeping the original bullet structure and terms."],
+ ],
+ [BOTS[4].id]: [
+ [320, "user", "帮我润色一下这封邀请邮件"],
+ [319, "assistant", "润色好了,语气更自然,开头直接说明时间和地点。"],
+ ],
+ [BOTS[5].id]: [
+ [420, "user", "写个脚本,把日志里的 ERROR 行按小时统计"],
+ [418, "assistant", "脚本放在工作区的 count_errors.py,用法:python count_errors.py app.log"],
+ ],
+ };
+ return H[botId] || [];
+}
+
+/** chat 截图:用户问 Raft,回复是一段 Markdown 列表加一个代码块 */
+export const RAFT_Q = "用三句话讲讲 Raft 为什么要选主";
+export const RAFT_A = [
+ "Raft 选主是为了让一致性问题变简单:",
+ "",
+ "1. **只有一个写入口**:所有写请求都交给 Leader,日志只从它流向 Follower,不会出现两份互相冲突的日志。",
+ "2. **顺序由 Leader 说了算**:Leader 给每条日志编号,多数派确认后才提交,大家按同一顺序执行。",
+ "3. **故障时能自动接班**:Leader 心跳中断后,Follower 超时发起投票,拿到多数票的节点成为新 Leader。",
+ "",
+ "核心规则可以写成几行伪代码:",
+ "",
+ "```go",
+ "if time.Since(lastHeartbeat) > electionTimeout {",
+ " term++ // 进入新任期",
+ " votes := requestVotes(term)",
+ " if votes > len(peers)/2 {",
+ " becomeLeader(term) // 拿到多数票才当选",
+ " }",
+ "}",
+ "```",
+].join("\n");
+
+/** memory 截图:信息面板里的 4 条偏好记忆 */
+export const MEMORY_PREFS = [
+ "先给结论,再给细节;列表不超过 5 条",
+ "代码示例默认用 TypeScript",
+ "日期统一写成 YYYY-MM-DD",
+ "称呼用「你」,不用「您」",
+];
+
+/** 演示用的渠道身份(虚构) */
+export const WEIXIN_BOT_ID = "[email protected]";
+export const WEIXIN_USER = "[email protected]";
+export const FEISHU_APP_ID = "cli_a5f3d9e0demo";
+export const FEISHU_PEER = "演示同事";
diff --git a/docs/assets/_src/record/encode.py b/docs/assets/_src/record/encode.py
new file mode 100644
index 0000000..ea78f34
--- /dev/null
+++ b/docs/assets/_src/record/encode.py
@@ -0,0 +1,247 @@
+#!/usr/bin/env python3
+"""把 record.mjs 录下的帧编码成 README 素材,并用程序核对(不看图)。依赖:Python 3 + Pillow ≥ 10。
+
+ python3 encode.py <job.json> 按任务文件编码一个 GIF 或 WebP,打印一行 JSON 结果
+ python3 encode.py --verify <文件…> 核对成品:尺寸、帧数、时长、体积,以及有没有全空白 / 全黑的帧段
+
+GIF 任务:
+ {"kind": "gif", "frames": [[时间戳秒, png 路径], …], "t0": 起点, "duration": 秒, "fps": 帧率, "size": [宽, 高],
+ "crop": [x, y, w, h] 或 null, "out": 输出路径, "limit": 体积上限字节, "hold": 最后一帧停留秒数(默认 1)}
+ 按目标帧率重采样:第 k 帧取时间戳 ≤ t0 + k/fps 的最后一张屏幕帧;最后一帧停 hold 秒,无限循环。
+ 全局调色板(从均匀抽样的若干帧里取 255 色,第 256 色留作透明),不抖动;第 2 帧起只存变化区域,区域里没变的像素记成透明,\n 相同的相邻帧合并;写完解码一遍逐帧比对。
+ 超出体积上限时按 docs/assets/README.md 的顺序处理:有损(相邻帧色差很小的像素沿用上一帧,减少到 192 色)→
+ 帧率降到 8 → 宽度降到 800;三步之后仍超就报错,不放宽上限、也不自动缩短时长。
+WebP 任务:
+ {"kind": "webp", "src": png 路径, "size": [1600, 1093], "quality": 82, "out": 输出路径, "limit": 体积上限字节}
+"""
+import bisect
+import json
+import os
+import sys
+
+from PIL import Image, ImageChops, ImageSequence, ImageStat
+
+
+def sample_times(duration, fps, hold):
+ n = round((duration - hold) * fps)
+ times = [k / fps for k in range(n)] + [duration - hold]
+ # GIF 的延时单位是 10 毫秒:按累计时间取整,12 fps 时 80 / 90 毫秒交替,平均 83.3
+ cum = [k * 1000 / fps for k in range(n + 1)]
+ durs = [int(round(cum[k + 1] / 10) * 10 - round(cum[k] / 10) * 10) for k in range(n)]
+ durs.append(int(round(hold * 1000)))
+ return times, durs
+
+
+def load_frames(job, fps, width):
+ stamps = [f[0] for f in job["frames"]]
+ times, durs = sample_times(job["duration"], fps, job.get("hold", 1.0))
+ w0, h0 = job["size"]
+ size = (width, round(h0 * width / w0)) if width != w0 else (w0, h0)
+ cache = {}
+ out = []
+ for t in times:
+ i = bisect.bisect_right(stamps, job["t0"] + t) - 1
+ if i < 0:
+ i = 0
+ path = job["frames"][i][1]
+ if path not in cache:
+ im = Image.open(path).convert("RGB")
+ if job.get("crop"):
+ x, y, w, h = job["crop"]
+ im = im.crop((x, y, x + w, y + h))
+ cache[path] = im.resize(size, Image.LANCZOS)
+ out.append(cache[path])
+ return out, durs
+
+
+def palette_for(frames, colors):
+ picks = frames[:: max(1, len(frames) // 24)][:24]
+ w, h = picks[0].size
+ sw, sh = w // 2, h // 2
+ cols = 6
+ rows = (len(picks) + cols - 1) // cols
+ mosaic = Image.new("RGB", (sw * cols, sh * rows))
+ for i, f in enumerate(picks):
+ mosaic.paste(f.resize((sw, sh), Image.BOX), ((i % cols) * sw, (i // cols) * sh))
+ pal = mosaic.quantize(colors=colors, method=Image.Quantize.MEDIANCUT, kmeans=1)
+ # 没用到的调色板项(含留给透明的 255)都填成第 0 色:映射时就算选中它们,颜色也和第 0 色一样,之后统一改回 0
+ used = len(pal.getcolors(256))
+ rgb = pal.getpalette()[: used * 3]
+ pal.putpalette(rgb + rgb[:3] * (256 - used))
+ pal.info["used"] = used
+ return pal
+
+
+def quantize(f, pal):
+ p = f.quantize(palette=pal, dither=Image.Dither.NONE)
+ used = pal.info["used"]
+ idx = as_index(p).point(lambda v: v if v < used else 0)
+ q = Image.frombytes("P", p.size, idx.tobytes())
+ q.putpalette(pal.getpalette())
+ return q
+
+
+def stabilize(prev_rgb, cur_rgb, prev_p, cur_p, thr):
+ """有损:和上一帧颜色差不到 thr 的像素直接沿用上一帧(GIF 里就成了没变化的区域)"""
+ diff = ImageChops.difference(prev_rgb, cur_rgb).convert("L")
+ keep = diff.point(lambda v: 255 if v < thr else 0)
+ out = cur_p.copy()
+ out.paste(prev_p, (0, 0), keep)
+ return out
+
+
+TRANSPARENT = 255 # 调色板只用 0–254,255 留给"和上一帧一样"的像素
+
+
+def as_index(p):
+ """把 P 图的调色板索引原样当成 L 图(用来比较两帧的索引是否相同)"""
+ return Image.frombytes("L", p.size, p.tobytes())
+
+
+def gif_bytes(pframes, durs, palette):
+ """自己写 GIF 容器:全局调色板 + 无限循环;第 2 帧起只写变化区域的外接矩形,矩形里没变的像素记成透明(disposal 1,叠在上一帧上)。
+ 每帧的 LZW 数据用 Pillow 的 GifImagePlugin.getdata() 编码。完全相同的相邻帧合并成一帧(延时相加)。"""
+ from PIL import GifImagePlugin
+
+ w, h = pframes[0].size
+ frames = [] # [图, 偏移, 延时, 是否用透明]
+ prev = None
+ for p, d in zip(pframes, durs):
+ if prev is None:
+ frames.append([p, (0, 0), d, False])
+ else:
+ diff = ImageChops.difference(as_index(prev), as_index(p))
+ box = diff.getbbox()
+ if not box:
+ frames[-1][2] += d
+ continue
+ crop = p.crop(box)
+ same = diff.crop(box).point(lambda v: 255 if v == 0 else 0)
+ crop.paste(TRANSPARENT, (0, 0), same)
+ frames.append([crop, box[:2], d, True])
+ prev = p
+ pal = (palette + [0] * 768)[:768]
+ out = [b"GIF89a", w.to_bytes(2, "little"), h.to_bytes(2, "little"), bytes([0xF7, 0, 0]), bytes(pal)]
+ out.append(b"!\xff\x0bNETSCAPE2.0\x03\x01\x00\x00\x00")
+ for im, off, d, tr in frames:
+ params = {"duration": d, "disposal": 1}
+ if tr:
+ params["transparency"] = TRANSPARENT
+ out.extend(GifImagePlugin.getdata(im, offset=off, **params))
+ out.append(b";")
+ return b"".join(out), len(frames)
+
+
+def write_gif(job, fps, width, lossy):
+ frames, durs = load_frames(job, fps, width)
+ pal = palette_for(frames, 192 if lossy else 255)
+ pframes = []
+ prev_rgb = prev_p = None
+ for f in frames:
+ p = quantize(f, pal)
+ if lossy and prev_p is not None:
+ p = stabilize(prev_rgb, f, prev_p, p, 10)
+ pframes.append(p)
+ prev_rgb, prev_p = f, p
+ data, _ = gif_bytes(pframes, durs, pal.getpalette()[:768])
+ out = job["out"]
+ os.makedirs(os.path.dirname(out), exist_ok=True)
+ with open(out, "wb") as fh:
+ fh.write(data)
+ roundtrip(out, pframes, pal)
+ return os.path.getsize(out)
+
+
+def roundtrip(path, pframes, pal):
+ """解码刚写出的 GIF,逐帧和编码前的画面比对,确认透明叠加没有出错"""
+ im = Image.open(path)
+ want = [f.convert("RGB") for f in pframes]
+ # 相同的相邻帧被合并了:解码出的第 i 帧对应去重后的序列
+ uniq = [want[0]]
+ for a, b in zip(pframes, pframes[1:]):
+ if ImageChops.difference(as_index(a), as_index(b)).getbbox():
+ uniq.append(b.convert("RGB"))
+ n = 0
+ for i, fr in enumerate(ImageSequence.Iterator(im)):
+ got = fr.convert("RGB")
+ if ImageChops.difference(got, uniq[i]).getbbox():
+ raise SystemExit(f"{path}: 第 {i} 帧解码后和编码前不一致")
+ n += 1
+ if n != len(uniq):
+ raise SystemExit(f"{path}: 帧数不对({n} ≠ {len(uniq)})")
+
+
+def encode_gif(job):
+ limit = job["limit"]
+ w0 = job["size"][0]
+ steps = [("原样", job["fps"], w0, False), ("有损", job["fps"], w0, True), ("帧率 8", min(8, job["fps"]), w0, True), ("宽度 800", min(8, job["fps"]), min(800, w0), True)]
+ tried = []
+ for name, fps, width, lossy in steps:
+ size = write_gif(job, fps, width, lossy)
+ tried.append(f"{name}: {size / 1048576:.2f} MB")
+ if size <= limit:
+ return {"out": job["out"], "steps": tried, "fps": fps, "width": width, "lossy": lossy, **inspect(job["out"])}
+ raise SystemExit(f"{job['out']} 三步压缩后仍超过上限 {limit / 1048576:.2f} MB:{';'.join(tried)}(按要求不放宽上限,请缩短时长)")
+
+
+def encode_webp(job):
+ im = Image.open(job["src"]).convert("RGB").resize(tuple(job["size"]), Image.LANCZOS)
+ os.makedirs(os.path.dirname(job["out"]), exist_ok=True)
+ im.save(job["out"], "WEBP", quality=job.get("quality", 82), method=6)
+ r = {"out": job["out"], **inspect(job["out"])}
+ if r["bytes"] > job["limit"]:
+ raise SystemExit(f"{job['out']} 超过上限:{r['bytes']} > {job['limit']}")
+ return r
+
+
+def frame_stats(im):
+ g = im.convert("L").resize((240, max(1, round(240 * im.size[1] / im.size[0]))), Image.BOX)
+ s = ImageStat.Stat(g)
+ return s.mean[0], s.stddev[0]
+
+
+def inspect(path):
+ """尺寸、帧数、总时长、体积,以及全空白 / 全黑的帧段(标准差 < 2 视为一片纯色)"""
+ im = Image.open(path)
+ n = getattr(im, "n_frames", 1)
+ total = 0
+ flat = []
+ run = 0
+ worst = []
+ for i, fr in enumerate(ImageSequence.Iterator(im)):
+ total += fr.info.get("duration", 0) or 0
+ mean, std = frame_stats(fr.convert("RGB"))
+ worst.append(std)
+ if std < 2:
+ run += 1
+ flat.append((i, round(mean)))
+ else:
+ run = 0
+ return {
+ "bytes": os.path.getsize(path),
+ "width": im.size[0],
+ "height": im.size[1],
+ "frames": n,
+ "duration_ms": total if n > 1 else 0,
+ "flat_frames": flat,
+ "min_std": round(min(worst), 1),
+ "black": any(m < 4 for _, m in flat),
+ "blank": any(m > 251 for _, m in flat),
+ }
+
+
+def main(argv):
+ if not argv:
+ sys.exit(__doc__)
+ if argv[0] == "--verify":
+ for p in argv[1:]:
+ print(json.dumps({"out": p, **inspect(p)}, ensure_ascii=False))
+ return
+ with open(argv[0], encoding="utf-8") as fh:
+ job = json.load(fh)
+ r = encode_gif(job) if job["kind"] == "gif" else encode_webp(job)
+ print(json.dumps(r, ensure_ascii=False))
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
diff --git a/docs/assets/_src/record/make-illustration.py b/docs/assets/_src/record/make-illustration.py
new file mode 100644
index 0000000..672a2e2
--- /dev/null
+++ b/docs/assets/_src/record/make-illustration.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python3
+"""G5 生图演示里的"成图":黄色小机器人趴在键盘上打瞌睡,扁平插画风格。
+
+只用仓库里的角色素材(ui/design/bots/yellow.webp,图层顺序和几何同 docs/assets/_src/make-assets.py 与
+ui/components/avatar.js),其余是几何形状;不用任何网上的图片。依赖:Python 3 + Pillow。
+
+用法:python3 make-illustration.py <输出.png> [边长,默认 1024]
+"""
+import math
+import os
+import sys
+
+from PIL import Image, ImageDraw, ImageFilter, ImageFont
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(HERE))))
+SPRITE = 448
+EYES = [(38.34, 63.5), (61.4, 63.48)] # avatar.js BOT_CHARS.yellow.eyes(方框的百分比)
+EYE_R = 3.57
+EYE, GLOW = (252, 252, 220), (255, 194, 26)
+FONT = os.environ.get("NOTO_SC", "/usr/share/fonts/truetype/noto-cjk/NotoSansSC.ttf")
+
+
+def sprite_base(key="yellow"):
+ s = Image.open(os.path.join(ROOT, "ui", "design", "bots", f"{key}.webp")).convert("RGBA")
+ base = Image.new("RGBA", (SPRITE, SPRITE), (0, 0, 0, 0))
+ for i in (1, 2, 3, 0): # 左耳、右耳、头顶配件、头(同 make-assets.py)
+ base.alpha_composite(s.crop((i * SPRITE, 0, (i + 1) * SPRITE, SPRITE)))
+ return base
+
+
+def sleepy_bot(n):
+ """n×n 的黄色机器人:闭着眼(avatar.js 的 e-closed 曲线)、脸颊微红"""
+ im = sprite_base().resize((n, n), Image.LANCZOS)
+ u = n / 100
+ lines = Image.new("L", (n, n), 0)
+ d = ImageDraw.Draw(lines)
+ blush = Image.new("RGBA", (n, n), (0, 0, 0, 0))
+ db = ImageDraw.Draw(blush)
+ for ex, ey in EYES:
+ r = EYE_R * u
+ cx, cy = ex * u, ey * u
+ # e-closed:M -1.05R,-0.15R Q 0,0.8R 1.05R,-0.15R
+ pts = []
+ for i in range(25):
+ t = i / 24
+ x = (1 - t) ** 2 * (-1.05 * r) + 2 * (1 - t) * t * 0 + t * t * (1.05 * r)
+ y = (1 - t) ** 2 * (-0.15 * r) + 2 * (1 - t) * t * (0.8 * r) + t * t * (-0.15 * r)
+ pts.append((cx + x, cy + y))
+ d.line(pts, fill=255, width=max(2, round(r * 0.55)), joint="curve")
+ bx = cx + (-5.6 * u if ex < 50 else 5.6 * u)
+ by = cy + 6.2 * u
+ db.ellipse([bx - 2.6 * u, by - 1.4 * u, bx + 2.6 * u, by + 1.4 * u], fill=(255, 120, 140, 120))
+ glow = Image.new("RGBA", (n, n), GLOW + (0,))
+ glow.putalpha(lines.filter(ImageFilter.GaussianBlur(n * 0.012)))
+ eye = Image.new("RGBA", (n, n), EYE + (0,))
+ eye.putalpha(lines)
+ im.alpha_composite(blush.filter(ImageFilter.GaussianBlur(n * 0.006)))
+ im.alpha_composite(glow)
+ im.alpha_composite(eye)
+ return im
+
+
+def rrect(d, box, r, fill):
+ d.rounded_rectangle(box, radius=r, fill=fill)
+
+
+def main(out, size=1024):
+ S = 2 # 先画两倍大再缩小,边缘更平滑
+ W = size * S
+ im = Image.new("RGBA", (W, W), (46, 58, 99, 255)) # 夜色的墙
+ d = ImageDraw.Draw(im)
+ k = W / 1024
+ # 月亮和几颗星
+ d.ellipse([735 * k, 120 * k, 875 * k, 260 * k], fill=(247, 231, 166))
+ d.ellipse([775 * k, 98 * k, 915 * k, 238 * k], fill=(46, 58, 99))
+ for x, y, r in [(170, 150, 7), (300, 92, 5), (560, 170, 6), (930, 360, 5), (120, 330, 4), (640, 70, 4)]:
+ d.ellipse([(x - r) * k, (y - r) * k, (x + r) * k, (y + r) * k], fill=(247, 231, 166))
+ # 桌面
+ d.rectangle([0, 700 * k, W, W], fill=(201, 138, 91))
+ d.rectangle([0, 700 * k, W, 724 * k], fill=(222, 162, 112))
+ # 键盘的影子和键盘
+ d.ellipse([170 * k, 838 * k, 870 * k, 900 * k], fill=(168, 111, 71))
+ rrect(d, [170 * k, 640 * k, 860 * k, 860 * k], 34 * k, (59, 66, 82))
+ keys_y = [668, 714, 760, 806]
+ for row, y in enumerate(keys_y):
+ n = 12 - (row == 3) * 3
+ x0, x1 = 196 + row * 8, 834 - row * 8
+ step = (x1 - x0) / n
+ for i in range(n):
+ if row == 3 and i == 4:
+ rrect(d, [(x0 + i * step) * k, y * k, (x0 + (i + 4) * step - 8) * k, (y + 36) * k], 8 * k, (91, 100, 117))
+ if row == 3 and 4 <= i < 8:
+ continue
+ rrect(d, [(x0 + i * step + 4) * k, y * k, (x0 + (i + 1) * step - 4) * k, (y + 36) * k], 8 * k, (91, 100, 117))
+ # 杯子
+ rrect(d, [880 * k, 616 * k, 968 * k, 724 * k], 18 * k, (240, 240, 232))
+ d.ellipse([948 * k, 640 * k, 1000 * k, 700 * k], outline=(240, 240, 232), width=round(14 * k))
+ d.rectangle([880 * k, 640 * k, 968 * k, 656 * k], fill=(215, 255, 0))
+ # 机器人:歪着头趴在键盘上
+ n = round(640 * k)
+ bot = sleepy_bot(n).rotate(14, resample=Image.BICUBIC, expand=True)
+ bx = round(512 * k - bot.width / 2 - 20 * k)
+ by = round(745 * k - bot.height * 0.78)
+ shadow = Image.new("RGBA", bot.size, (0, 0, 0, 0))
+ shadow.putalpha(bot.getchannel("A").point(lambda a: a * 0.28))
+ im.alpha_composite(shadow.filter(ImageFilter.GaussianBlur(10 * k)), (bx + round(10 * k), by + round(22 * k)))
+ im.alpha_composite(bot, (bx, by))
+ # 两只小手搭在键盘上
+ for cx in (330, 640):
+ rrect(d, [(cx - 52) * k, 690 * k, (cx + 52) * k, 742 * k], 26 * k, (255, 206, 64))
+ rrect(d, [(cx - 52) * k, 722 * k, (cx + 52) * k, 742 * k], 12 * k, (238, 178, 34))
+ # Zzz
+ try:
+ font = ImageFont.truetype(FONT, 10)
+ font.set_variation_by_name("Bold")
+ except Exception:
+ font = None
+ for (x, y, s) in [(740, 430, 54), (800, 350, 72), (870, 250, 96)]:
+ f = ImageFont.truetype(FONT, round(s * k)) if font else ImageFont.load_default()
+ try:
+ f.set_variation_by_name("Bold")
+ except Exception:
+ pass
+ d.text((x * k, y * k), "Z", font=f, fill=(247, 231, 166))
+ im = im.resize((size, size), Image.LANCZOS).convert("RGB")
+ os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
+ im.save(out, "PNG", optimize=True)
+ return im
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ sys.exit(__doc__)
+ img = main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 1024)
+ # 程序核对(不看图):尺寸、不是纯色、黄色角色确实画进去了
+ px = img.resize((64, 64)).getdata()
+ yellow = sum(1 for r, g, b in px if r > 200 and g > 150 and b < 90)
+ print(f"{sys.argv[1]}: {img.size[0]}×{img.size[1]},黄色像素占 {yellow / len(px):.1%}")
diff --git a/docs/assets/_src/record/mock-server.mjs b/docs/assets/_src/record/mock-server.mjs
new file mode 100644
index 0000000..e13795c
--- /dev/null
+++ b/docs/assets/_src/record/mock-server.mjs
@@ -0,0 +1,757 @@
+#!/usr/bin/env node
+// README 素材录制用的模拟后端:零依赖(只用 Node 内置模块)。
+//
+// - 提供 ui/ 的静态文件(与 src/web/server.ts 同样的路径:/、/amb/static/*、/amb/vendor/*),preact / htm 取自 node_modules;
+// - 用演示数据实现界面实际调用的 /amb/api/* 接口,响应格式照抄 src/web/server.ts;
+// - 网页对话的流式回复(POST /bots/:id/chat/stream,SSE)按场景脚本分段推送:activity / prompt / text / file / done;
+// 审批卡片会一直等到界面上点了允许或拒绝,脚本才继续;
+// - /__stage/* 提供录制用的舞台页面(stage/),/__gen/* 提供生成的图片,/__docs/* 与 /__repo-assets/* 提供仓库里的品牌素材和应用图标;
+// - 界面请求了没实现的接口时记日志(unimplemented),录制结束时由 record.mjs 汇总。
+//
+// 单独运行(在浏览器里手动看演示数据):
+// node docs/assets/_src/record/mock-server.mjs --scene demo --port 4173
+// 然后打开 http://127.0.0.1:4173/
+// 场景:fresh(全新安装)、signed-out(已退出登录,六个机器人还在)、demo(演示就绪)。
+
+import http from "node:http";
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { fileURLToPath } from "node:url";
+import { EventEmitter } from "node:events";
+import * as D from "./demo-data.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+export const REPO = path.resolve(HERE, "..", "..", "..", "..");
+
+const MIME = {
+ ".html": "text/html; charset=utf-8",
+ ".js": "text/javascript; charset=utf-8",
+ ".mjs": "text/javascript; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".svg": "image/svg+xml",
+ ".png": "image/png",
+ ".webp": "image/webp",
+ ".json": "application/json",
+ ".woff2": "font/woff2",
+};
+
+/** preact / htm 的 ESM 文件:AMB_NODE_MODULES > 仓库的 node_modules(npm ci 之后) */
+function vendorFiles() {
+ const dirs = [process.env.AMB_NODE_MODULES, path.join(REPO, "node_modules")].filter(Boolean);
+ const nm = dirs.find((d) => fs.existsSync(path.join(d, "preact", "dist", "preact.mjs")));
+ if (!nm) throw new Error(`找不到 preact:先在仓库根目录 npm ci,或用 AMB_NODE_MODULES 指向一个装了 preact 和 htm 的 node_modules(试过:${dirs.join("、")})`);
+ return {
+ "preact.mjs": path.join(nm, "preact", "dist", "preact.mjs"),
+ "hooks.mjs": path.join(nm, "preact", "hooks", "dist", "hooks.mjs"),
+ "htm.mjs": path.join(nm, "htm", "dist", "htm.mjs"),
+ };
+}
+
+class HttpError extends Error {
+ constructor(status, message) {
+ super(message);
+ this.status = status;
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const min = 60_000;
+
+/** 不可扫描的装饰性"二维码"(三个定位角 + 随机模块),只用来占位,不编码任何内容 */
+function fakeQrDataUrl() {
+ const n = 29;
+ const cell = 8;
+ let seed = 20261031;
+ const rnd = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff);
+ const finder = (x, y) =>
+ `<rect x="${x * cell}" y="${y * cell}" width="${7 * cell}" height="${7 * cell}" fill="#111"/>` +
+ `<rect x="${(x + 1) * cell}" y="${(y + 1) * cell}" width="${5 * cell}" height="${5 * cell}" fill="#fff"/>` +
+ `<rect x="${(x + 2) * cell}" y="${(y + 2) * cell}" width="${3 * cell}" height="${3 * cell}" fill="#111"/>`;
+ const inFinder = (x, y) => (x < 8 && y < 8) || (x > n - 9 && y < 8) || (x < 8 && y > n - 9);
+ let mods = "";
+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) if (!inFinder(x, y) && rnd() < 0.47) mods += `<rect x="${x * cell}" y="${y * cell}" width="${cell}" height="${cell}"/>`;
+ const s = n * cell;
+ const pad = 2 * cell;
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${-pad} ${-pad} ${s + 2 * pad} ${s + 2 * pad}" shape-rendering="crispEdges"><rect x="${-pad}" y="${-pad}" width="${s + 2 * pad}" height="${s + 2 * pad}" fill="#fff"/><g fill="#111">${mods}</g>${finder(0, 0)}${finder(n - 7, 0)}${finder(0, n - 7)}</svg>`;
+ return "data:image/svg+xml;base64," + Buffer.from(svg).toString("base64");
+}
+
+// ---------------------------------------------------------------------------
+// 场景状态
+// ---------------------------------------------------------------------------
+
+function botRecord(b, now, extra = {}) {
+ return {
+ id: b.id,
+ name: b.name,
+ systemPrompt: b.systemPrompt,
+ defaultModel: extra.defaultModel ?? D.BOT_MODEL,
+ feishuAppId: extra.feishuAppId ?? "",
+ feishuAppSecretMasked: extra.feishuAppId ? "••••7c1e" : "",
+ weixinEnabled: true,
+ settings: {
+ permission: "workspace",
+ memory: { enabled: true, review: true, teamWrite: false },
+ steward: { enabled: true },
+ computerUse: { enabled: true, backend: "cua", approval: extra.cuApproval ?? "auto" },
+ utilityModel: "",
+ avatar: b.avatar,
+ budget: { enabled: false, limitUsd: 5 },
+ },
+ createdAt: now - 30 * 86_400_000 + (extra.order ?? 0) * 60_000,
+ updatedAt: now - 2 * 86_400_000,
+ };
+}
+
+/**
+ * 场景:
+ * fresh 全新安装:未连接 Modelflare,只有应用自建的「我的助手」
+ * signed-out 退出登录后:六个机器人和会话都在,回到登录页
+ * demo 演示就绪:已登录、六个机器人、小黄的飞书 / 微信已连接
+ * opts:weixinBound(默认 true)、cuApproval(小黄的电脑操作审批 auto / ask-input)、memory(小黄的机器人记忆)、
+ * history(是否给六个机器人预置会话,默认 true)、extraConvs(小黄的微信 / 飞书会话,默认 true)
+ */
+export function createState(scene = "demo", opts = {}) {
+ const now = Date.now();
+ const connected = scene === "demo";
+ const st = {
+ scene,
+ mf: { connected, keyTail: connected ? D.ACCOUNT.keyTail : "", line: "auto" },
+ account: {
+ state: connected ? "signed_in" : "signed_out",
+ name: connected ? D.ACCOUNT.name : "",
+ source: connected ? "account" : "none",
+ balanceUsd: connected ? D.ACCOUNT.balanceUsd : null,
+ usedUsd: connected ? D.ACCOUNT.usedUsd : null,
+ billedToEnterprise: false,
+ updatedAt: connected ? now - 4 * min : 0,
+ error: "",
+ alerts: { lowBalanceUsd: opts.lowBalanceUsd ?? 1, push: false },
+ },
+ settings: { defaultModel: scene === "fresh" ? "" : D.BOT_MODEL, imageModel: "", videoModel: "", closeToTray: true, zoom: 1 },
+ bots: [],
+ channels: {},
+ convs: new Map(),
+ approvals: new Map(),
+ memory: {},
+ turns: new Map(), // 网页对话进行中的消息:convId → [LiveTurn]
+ agentTurns: new Map(), // 其它渠道进行中的回合:convId → { since, lastProgress, steps: Map }
+ msgSeq: 1000,
+ };
+ const list = scene === "fresh" ? [D.DEFAULT_BOT] : D.BOTS;
+ list.forEach((b, i) => {
+ const isYellow = b.id === D.YELLOW;
+ st.bots.push(botRecord(b, now, { order: i, defaultModel: scene === "fresh" ? "" : D.BOT_MODEL, cuApproval: isYellow ? opts.cuApproval : undefined, feishuAppId: isYellow && scene === "demo" && opts.feishu !== false ? D.FEISHU_APP_ID : "" }));
+ const weixinBound = isYellow && scene === "demo" && opts.weixinBound !== false;
+ st.channels[b.id] = {
+ feishu: isYellow && scene === "demo" && opts.feishu !== false ? { state: "connected", since: now - 3 * 3600_000 } : { state: "disabled", detail: "未配置凭据", since: 0 },
+ weixin: weixinBound ? { state: "connected", since: now - 3 * 3600_000 } : { state: "login_required", detail: "尚未扫码登录", since: 0 },
+ account: weixinBound ? { ilinkBotId: D.WEIXIN_BOT_ID, pausedUntil: 0 } : undefined,
+ login: undefined,
+ };
+ st.memory[b.id] = isYellow ? [...(opts.memory ?? [])] : [];
+ if (scene !== "fresh" && opts.history !== false) {
+ const conv = ensureConv(st, b.id, "web", "console", "控制台");
+ for (const [ago, role, content] of D.history(b.id)) addMessage(st, conv.id, role, content, role === "assistant" ? [] : undefined, now - ago * min);
+ }
+ });
+ // 小黄的另外两段会话(信息面板 → 最近会话)
+ if (scene === "demo" && opts.extraConvs !== false) {
+ const wx = ensureConv(st, D.YELLOW, "weixin", D.WEIXIN_USER, D.WEIXIN_USER, now - 300 * min);
+ addMessage(st, wx.id, "user", "明早 9 点提醒我交周报", undefined, now - 52 * min);
+ addMessage(st, wx.id, "assistant", "好的,周报的要点我先帮你列在这里:本周完成、下周计划、需要协调的事。", [], now - 51 * min);
+ const fs1 = ensureConv(st, D.YELLOW, "feishu", "ou_demo_7d8a", D.FEISHU_PEER, now - 400 * min);
+ addMessage(st, fs1.id, "user", "帮我看看这份需求文档有没有遗漏", undefined, now - 128 * min);
+ addMessage(st, fs1.id, "assistant", "整体完整,建议补充两点:异常流程和上线后的回滚方案。", [], now - 127 * min);
+ }
+ return st;
+}
+
+function ensureConv(st, botId, channel, peerId, title = "", at = Date.now()) {
+ const id = `${botId}:${channel}:${peerId}`;
+ let c = st.convs.get(id);
+ if (!c) {
+ c = { id, botId, channel, peerId, title, model: "", kind: "dm", createdAt: at, updatedAt: at, messages: [] };
+ st.convs.set(id, c);
+ }
+ return c;
+}
+
+function addMessage(st, convId, role, content, activity, at = Date.now()) {
+ const c = st.convs.get(convId);
+ const m = { id: ++st.msgSeq, conversationId: convId, role, content, createdAt: at, activity: activity || [] };
+ c.messages.push(m);
+ c.updatedAt = Math.max(c.updatedAt, at);
+ return m;
+}
+
+const publicMsg = (m) => ({ id: m.id, conversationId: m.conversationId, role: m.role, content: m.content, createdAt: m.createdAt, ...(m.activity.length ? { steps: m.activity.length } : {}) });
+const publicConv = (c) => ({
+ id: c.id, botId: c.botId, channel: c.channel, peerId: c.peerId, title: c.title, model: c.model, kind: c.kind, createdAt: c.createdAt, updatedAt: c.updatedAt,
+ messageCount: c.messages.length, lastMessage: (c.messages.at(-1)?.content ?? "").slice(0, 120),
+});
+function publicApproval(r) {
+ const { payload, result, ...rest } = r;
+ let questions;
+ if (r.kind === "question") {
+ try {
+ questions = JSON.parse(payload);
+ } catch {
+ questions = [];
+ }
+ }
+ return { ...rest, questions };
+}
+
+// ---------------------------------------------------------------------------
+// 进行中的一条网页消息(对应 src/web/live.ts 的 LiveTurn)
+// ---------------------------------------------------------------------------
+
+class LiveTurn {
+ constructor(convId, botId, userText, afterMessageId) {
+ this.id = crypto.randomUUID();
+ this.startedAt = Date.now();
+ this.convId = convId;
+ this.botId = botId;
+ this.userText = userText;
+ this.afterMessageId = afterMessageId;
+ this.text = "";
+ this.steps = new Map();
+ this.prompts = [];
+ this.files = [];
+ this.stopping = false;
+ this.done = false;
+ this.subs = new Set();
+ }
+ emit(ev, data) {
+ for (const fn of [...this.subs]) {
+ try {
+ fn(ev, data);
+ } catch {
+ /* 某个连接写失败不影响其它订阅者 */
+ }
+ }
+ }
+ snapshot() {
+ return { id: this.id, startedAt: this.startedAt, userText: this.userText, text: this.text, steps: [...this.steps.values()], prompts: [...this.prompts], files: [...this.files], stopping: this.stopping };
+ }
+}
+
+function sse(res) {
+ res.writeHead(200, { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-store", "x-accel-buffering": "no", connection: "keep-alive" });
+ let closed = false;
+ res.on("close", () => (closed = true));
+ return {
+ send(event, data) {
+ if (!closed && !res.writableEnded) res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ },
+ end(event, data) {
+ this.send(event, data);
+ if (!closed && !res.writableEnded) res.end();
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// 服务器
+// ---------------------------------------------------------------------------
+
+/**
+ * startMock({ port, host, scene, sceneOpts, genDir, log }) → controller
+ * controller:url、state、events(EventEmitter)、setScene()、authorize()、weixinConfirm()、weixinInbound()、
+ * onChat(网页对话脚本:async (turnApi, botId, text) => void)、onWeixin(微信回合脚本)、unimplemented、requests、close()
+ */
+export async function startMock({ port = 0, host = "127.0.0.1", scene = "demo", sceneOpts = {}, genDir = "", log = () => {} } = {}) {
+ const uiDir = path.join(REPO, "ui");
+ const stageDir = path.join(HERE, "stage");
+ const vendor = vendorFiles();
+ const events = new EventEmitter();
+ const ctl = {
+ url: "",
+ state: createState(scene, sceneOpts),
+ events,
+ unimplemented: [],
+ requests: [],
+ errors: [],
+ onChat: null,
+ onWeixin: null,
+ /** 某些接口的人为延迟(毫秒),模拟真实启动时的等待 */
+ delays: {},
+ };
+ ctl.setScene = (name, opts = {}) => {
+ ctl.state = createState(name, opts);
+ ctl.onChat = null;
+ ctl.onWeixin = null;
+ ctl.delays = {};
+ };
+
+ const S = () => ctl.state;
+ const bot = (id) => S().bots.find((b) => b.id === id);
+ const status = () => {
+ const a = S().account;
+ return { ...a, loginUrl: a.state === "signing_in" ? LOGIN_URL : "", lowBalance: a.balanceUsd !== null && a.alerts.lowBalanceUsd > 0 && a.balanceUsd < a.alerts.lowBalanceUsd, loginAvailable: true };
+ };
+ const mfStatus = () => ({ mode: "managed", connected: S().mf.connected, keyTail: S().mf.keyTail, line: S().mf.line, baseUrl: "https://api.modelflare.dev", gateway: "running" });
+ const channelStatus = (id) => {
+ const ch = S().channels[id];
+ return { feishu: ch.feishu, weixin: { ...ch.weixin, ...(ch.account ? { account: ch.account } : {}), login: ch.login, quota: [] } };
+ };
+ const LOGIN_URL = "https://modelflare.dev/oauth/authorize?client_id=anymodelbot&response_type=code&utm_source=anymodelbot";
+
+ /** 浏览器里点了「继续」:登录完成,本机 Key 已签发 */
+ ctl.authorize = () => {
+ const st = S();
+ st.account = { ...st.account, state: "signed_in", name: D.ACCOUNT.name, source: "account", balanceUsd: D.ACCOUNT.balanceUsd, usedUsd: D.ACCOUNT.usedUsd, updatedAt: Date.now(), error: "" };
+ st.mf = { ...st.mf, connected: true, keyTail: D.ACCOUNT.keyTail };
+ events.emit("authorized");
+ };
+ /** 微信扫码确认(二维码 → 已连接) */
+ ctl.weixinConfirm = (botId) => {
+ const ch = S().channels[botId];
+ ch.login = { state: "confirmed", message: "✅ 微信已连接", refreshCount: 0 };
+ ch.account = { ilinkBotId: D.WEIXIN_BOT_ID, pausedUntil: 0 };
+ ch.weixin = { state: "connected", since: Date.now() };
+ };
+
+ // —— 代理回合的脚本接口:网页对话和微信回合共用 ——
+ function turnApi(sink, botId) {
+ let seq = 0;
+ const steps = new Map();
+ const put = (s) => {
+ steps.set(s.id, s);
+ sink.activity({ ...s });
+ return s;
+ };
+ const st0 = S();
+ const b0 = bot(botId);
+ const api = {
+ botId,
+ steps,
+ sleep,
+ /** 这一轮用的模型:会话里切换过的 > 机器人默认 > 全局默认 */
+ modelId: st0.convs.get(sink.convId)?.model || b0?.defaultModel || st0.settings.defaultModel || D.BOT_MODEL,
+ /** remember 工具写进机器人记忆 */
+ remember: (text) => st0.memory[botId].push(text),
+ /** 模型请求一步:running → done(summary) */
+ model(title = api.modelId) {
+ const s = put({ id: `m1.${++seq}`, kind: "model", title, status: "running", at: Date.now() });
+ return {
+ done: (summary, more = {}) => put({ ...s, status: "ok", summary, ms: Date.now() - s.at, tokens: more.tokens ?? { input: 8000 + seq * 1700, output: 120 + seq * 40 }, ...(more.output ? { output: more.output } : {}) }),
+ };
+ },
+ /** 工具调用一步(title = 工具名,summary = 主要参数) */
+ tool(name, summary, input) {
+ const s = put({ id: `call_${crypto.randomBytes(4).toString("hex")}`, kind: "tool", title: name, ...(summary ? { summary } : {}), input: input ?? JSON.stringify(summary ? { command: summary } : {}, null, 2), status: "running", at: Date.now() });
+ return {
+ done: (output) => put({ ...s, status: "ok", ms: Date.now() - s.at, ...(output ? { output } : {}) }),
+ fail: (output) => put({ ...s, status: "error", ms: Date.now() - s.at, ...(output ? { output } : {}) }),
+ };
+ },
+ /** 审批:建一条 pending,推 prompt 事件,等界面决定;返回 "allowed" / "rejected" */
+ approval({ tool, detail, reason }) {
+ return createPrompt(sink, botId, { kind: "approval", tool, detail, reason, payload: "" });
+ },
+ /** 提问(生图确认等):返回回答 { answers: [{ id, selected, custom }] } */
+ question(questions, tool = "ask_user_question") {
+ return createPrompt(sink, botId, { kind: "question", tool, detail: questions.map((q) => q.question).join(" / "), reason: "", payload: JSON.stringify(questions) });
+ },
+ file: (name) => sink.files.push(name),
+ };
+ return api;
+ }
+
+ async function createPrompt(sink, botId, { kind, tool, detail, reason, payload }) {
+ const st = S();
+ const now = Date.now();
+ const pending = new Set([...st.approvals.values()].filter((r) => r.status === "pending").map((r) => r.code));
+ let code;
+ do code = String(crypto.randomInt(1000, 10000));
+ while (pending.has(code));
+ const row = { id: crypto.randomUUID(), code, kind, botId, conversationId: sink.convId, sessionId: "dsh-demo-session", tool, detail, reason, payload, status: "pending", result: "", decidedBy: "", createdAt: now, expiresAt: now + 10 * min, decidedAt: 0 };
+ st.approvals.set(row.id, row);
+ sink.prompt({ kind, prompt: kind === "approval" ? `需要你的批准 · ${code}` : "", requestId: row.id, code });
+ events.emit("prompt", row);
+ await new Promise((resolve) => {
+ const on = (r) => {
+ if (r.id !== row.id) return;
+ events.off("decided", on);
+ resolve();
+ };
+ events.on("decided", on);
+ });
+ return kind === "question" ? JSON.parse(row.result || "{}") : row.status;
+ }
+
+ /** 网页对话的一条消息:登记 LiveTurn(发消息的请求先订阅,再开始跑脚本,第一步不会漏掉) */
+ function startWebTurn(botId, text) {
+ const st = S();
+ const conv = ensureConv(st, botId, "web", "console", "控制台");
+ const t = new LiveTurn(conv.id, botId, text, conv.messages.at(-1)?.id ?? 0);
+ st.turns.set(conv.id, [...(st.turns.get(conv.id) ?? []), t]);
+ return t;
+ }
+ /** 跑场景脚本,结束时存消息、发 done */
+ async function runWebTurn(t) {
+ const st = S();
+ const { botId, userText: text } = t;
+ const conv = st.convs.get(t.convId);
+ const sink = {
+ convId: conv.id,
+ files: [],
+ activity: (s) => {
+ t.steps.set(s.id, s);
+ t.emit("activity", s);
+ },
+ prompt: (p) => {
+ t.prompts.push(p);
+ t.emit("prompt", p);
+ },
+ };
+ const api = turnApi(sink, botId);
+ let final = "";
+ api.reply = (s) => (final = s);
+ t.emit("typing", { on: true });
+ const script = ctl.onChat || defaultChat;
+ try {
+ await script(api, botId, text);
+ } catch (e) {
+ final = `⚠️ ${e.message}`;
+ ctl.errors.push(`脚本出错:${e.stack || e.message}`);
+ }
+ final ||= "(已完成,没有文字回复)";
+ const steps = [...api.steps.values()];
+ addMessage(st, conv.id, "user", text, undefined, t.startedAt);
+ addMessage(st, conv.id, "assistant", final, steps);
+ t.text = final;
+ t.emit("text", { text: final, final: true });
+ for (const name of sink.files) {
+ t.files.push(name);
+ t.emit("file", { name });
+ }
+ t.emit("typing", { on: false });
+ // 结束:先移出登记,再通知订阅者
+ const rest = (st.turns.get(conv.id) ?? []).filter((x) => x !== t);
+ if (rest.length) st.turns.set(conv.id, rest);
+ else st.turns.delete(conv.id);
+ t.done = true;
+ t.emit("done", { conversationId: conv.id });
+ t.subs.clear();
+ events.emit("turn-end", { botId, convId: conv.id, text: final });
+ }
+
+ /** 没有场景脚本时的回复:一步模型请求 + 一句话 */
+ async function defaultChat(t, botId, text) {
+ log(`(没有为「${text}」写脚本,用默认回复)`);
+ const m = t.model(bot(botId)?.defaultModel || D.BOT_MODEL);
+ await sleep(1500);
+ m.done("好的,我来处理。");
+ t.reply("好的,我来处理。这是演示环境里的默认回复。");
+ }
+
+ /** 微信发来一条消息:建会话、跑回合(信息面板的 /turn 能看到进度),结束时存消息并回给手机 */
+ ctl.weixinInbound = async (botId, userId, text) => {
+ const st = S();
+ const conv = ensureConv(st, botId, "weixin", userId, userId);
+ conv.updatedAt = Date.now();
+ const at = Date.now();
+ const turn = { since: at, lastProgress: 0, steps: new Map() };
+ st.agentTurns.set(conv.id, turn);
+ const sink = {
+ convId: conv.id,
+ files: [],
+ activity: (s) => {
+ turn.steps.set(s.id, s);
+ turn.lastProgress = Date.now();
+ },
+ prompt: () => {},
+ };
+ const api = turnApi(sink, botId);
+ let final = "";
+ api.reply = (s) => (final = s);
+ await (ctl.onWeixin || defaultChat)(api, botId, text);
+ addMessage(st, conv.id, "user", text, undefined, at);
+ addMessage(st, conv.id, "assistant", final, [...api.steps.values()]);
+ st.agentTurns.delete(conv.id);
+ events.emit("weixin-reply", { botId, userId, text: final });
+ return final;
+ };
+
+ async function readJson(req) {
+ let body = "";
+ for await (const c of req) body += c;
+ return body ? JSON.parse(body) : {};
+ }
+ function send(res, status, body) {
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
+ res.end(JSON.stringify(body));
+ }
+
+ async function api(req, res, url) {
+ const st = S();
+ const p = url.pathname.slice("/amb/api".length);
+ const m = req.method || "GET";
+ const seg = p.split("/").filter(Boolean).map(decodeURIComponent);
+ if ((m === "POST" || m === "PUT" || m === "PATCH") && !/^application\/json/i.test(String(req.headers["content-type"] || ""))) throw new HttpError(415, "需要 application/json");
+ const delay = ctl.delays[p];
+ if (delay) await sleep(delay);
+
+ if (p === "/status" && m === "GET")
+ return send(res, 200, { version: "0.1.13", dataDir: "C:\\Users\\demo\\AppData\\Roaming\\anymodel bot\\data", username: "demo", desktop: true, platform: "win32", gateway: { mode: "managed", state: "running", lastError: "", restarts: 0 }, notices: [] });
+ if (p === "/models" && m === "GET") return send(res, 200, { models: st.mf.connected ? D.MODEL_IDS : [] });
+ if (p === "/models/info" && m === "GET") return send(res, 200, { models: st.mf.connected ? D.modelInfo() : {} });
+ if (p === "/media/models" && m === "GET") return send(res, 200, st.mf.connected ? D.MEDIA : { image: [], video: [], recommended: { image: "", video: "" } });
+ if (p === "/modelflare" && m === "GET") return send(res, 200, mfStatus());
+ if (p === "/pwsh" && m === "GET") return send(res, 200, { applicable: false, checking: false, dismissed: false });
+ if (seg[0] === "account") {
+ const sub = seg.slice(1).join("/");
+ if (sub === "" && m === "GET") return send(res, 200, status());
+ if (sub === "refresh" && m === "POST") return send(res, 200, status());
+ if (sub === "login" && m === "POST") {
+ st.account = { ...st.account, state: "signing_in", error: "" };
+ events.emit("login-started");
+ return send(res, 200, { ...status(), loginUrl: LOGIN_URL, opened: true });
+ }
+ if (sub === "login/cancel" && m === "POST") {
+ st.account = { ...st.account, state: "signed_out" };
+ return send(res, 200, status());
+ }
+ if (sub === "usage" && m === "GET") return send(res, 200, D.usage(Math.min(30, Math.max(1, Number(url.searchParams.get("days") || 7)))));
+ if (sub === "notifications" && m === "GET") return send(res, 200, { data: { unread_count: 0, items: [] } });
+ if (sub === "invite" && m === "GET") return send(res, 200, { code: "DEMO26", url: "https://modelflare.dev/sign-up?aff=DEMO26&utm_source=anymodelbot&utm_medium=app&utm_campaign=invite" });
+ if (sub === "budgets" && m === "GET") return send(res, 200, { budgets: {} });
+ if (sub === "alerts" && m === "PUT") {
+ const b = await readJson(req);
+ if (b.lowBalanceUsd !== undefined) st.account.alerts.lowBalanceUsd = Number(b.lowBalanceUsd);
+ if (b.lowBalancePush !== undefined) st.account.alerts.push = !!b.lowBalancePush;
+ return send(res, 200, status());
+ }
+ }
+ if (p === "/settings") {
+ if (m === "PUT") {
+ const b = await readJson(req);
+ for (const k of ["defaultModel", "imageModel", "videoModel", "closeToTray", "zoom"]) if (b[k] !== undefined) st.settings[k] = b[k];
+ events.emit("settings", b);
+ }
+ return send(res, 200, {
+ ...st.settings,
+ autostart: { supported: true, on: true },
+ desktop: true,
+ listen: { host: "127.0.0.1", port: 52713, tokenRequired: true },
+ dataDir: "C:\\Users\\demo\\AppData\\Roaming\\anymodel bot\\data",
+ });
+ }
+ if (p === "/agent" && m === "GET") {
+ const busy = new Set([...st.turns.values()].flat().map((t) => t.botId));
+ for (const c of st.agentTurns.keys()) busy.add(c.split(":")[0]);
+ return send(res, 200, { enabled: true, runtime: "found", hosts: Object.fromEntries(st.bots.map((b) => [b.id, { state: "running", activeTurns: busy.has(b.id) ? 1 : 0 }])), busy: [...busy] });
+ }
+ if (seg[0] === "approvals") {
+ if (seg.length === 1 && m === "GET") {
+ const want = url.searchParams.get("status");
+ const b = url.searchParams.get("bot");
+ return send(res, 200, { approvals: [...st.approvals.values()].filter((r) => (!want || r.status === want) && (!b || r.botId === b)).map(publicApproval) });
+ }
+ const row = st.approvals.get(seg[1]);
+ if (!row) throw new HttpError(404, "请求不存在");
+ if (seg.length === 2 && m === "GET") return send(res, 200, { approval: publicApproval(row) });
+ if (seg.length === 3 && m === "POST" && (seg[2] === "approve" || seg[2] === "deny")) {
+ if (row.status !== "pending") throw new HttpError(409, "请求已处理或已过期");
+ Object.assign(row, { status: seg[2] === "approve" ? "allowed" : "rejected", decidedBy: "web", decidedAt: Date.now() });
+ events.emit("decided", row);
+ return send(res, 200, { approval: publicApproval(row) });
+ }
+ if (seg.length === 3 && m === "POST" && seg[2] === "answer") {
+ if (row.status !== "pending") throw new HttpError(409, "请求已处理或已过期");
+ const b = await readJson(req);
+ Object.assign(row, { status: "answered", result: JSON.stringify({ answers: b.answers || [] }), decidedBy: "web", decidedAt: Date.now() });
+ events.emit("decided", row);
+ return send(res, 200, { approval: publicApproval(row) });
+ }
+ }
+ if (seg[0] === "conversations") {
+ if (seg.length === 1 && m === "GET") {
+ const b = url.searchParams.get("bot");
+ const list = [...st.convs.values()].filter((c) => !b || c.botId === b).sort((x, y) => y.updatedAt - x.updatedAt);
+ return send(res, 200, { conversations: list.map(publicConv) });
+ }
+ const conv = st.convs.get(seg[1]);
+ if (seg.length === 3 && seg[2] === "messages" && m === "GET") {
+ if (!conv) throw new HttpError(404, "会话不存在");
+ return send(res, 200, { conversation: publicConv(conv), messages: conv.messages.map(publicMsg) });
+ }
+ if (seg.length === 5 && seg[2] === "messages" && seg[4] === "activity" && m === "GET") {
+ const msg = conv?.messages.find((x) => x.id === Number(seg[3]));
+ return send(res, 200, { steps: msg ? msg.activity : [] });
+ }
+ if (seg.length === 3 && seg[2] === "turn" && m === "GET") {
+ const t = st.agentTurns.get(seg[1]);
+ return send(res, 200, { turn: t ? { since: t.since, lastProgress: t.lastProgress, steps: [...t.steps.values()] } : null });
+ }
+ if (seg.length === 3 && seg[2] === "stop" && m === "POST") return send(res, 200, { stopped: false });
+ }
+ if (seg[0] === "bots") {
+ if (seg.length === 1 && m === "GET") return send(res, 200, { bots: st.bots });
+ const b = bot(seg[1]);
+ if (!b) throw new HttpError(404, "机器人不存在");
+ const sub = seg.slice(2).join("/");
+ if (seg.length === 2 && m === "GET") return send(res, 200, { bot: b, channels: channelStatus(b.id) });
+ if (seg.length === 2 && m === "PUT") {
+ const body = await readJson(req);
+ for (const k of ["name", "systemPrompt", "defaultModel"]) if (body[k] !== undefined) b[k] = String(body[k]);
+ return send(res, 200, { bot: b });
+ }
+ if (sub === "settings" && m === "GET") {
+ const cu = b.settings.computerUse;
+ return send(res, 200, {
+ settings: b.settings,
+ computerUse: { available: true, enabled: cu.enabled, active: cu.enabled, backend: "cua", selectedBackend: "cua", approval: cu.approval, reason: `Cua Driver: 可用(Windows);${cu.approval === "ask-input" ? "点击/输入前先问我" : "操作自动执行"}`, backends: [{ id: "cua", available: true, reason: "Cua Driver: 可用(Windows)" }] },
+ });
+ }
+ if (sub === "memory" && m === "GET") {
+ const entries = (st.memory[b.id] || []).map((text) => ({ text, meta: "source: web; added: 2026-10-20" }));
+ return send(res, 200, { scopes: [{ kind: "team", id: "", label: "团队记忆", entries: [], topics: [] }, { kind: "bot", id: b.id, label: "机器人记忆", entries, topics: [] }], journal: [], steward: [] });
+ }
+ if (sub === "channels" && m === "GET") return send(res, 200, channelStatus(b.id));
+ if (sub === "weixin/login" && m === "POST") {
+ const ch = st.channels[b.id];
+ ch.login = { state: "wait", message: "请用微信扫码", qrDataUrl: fakeQrDataUrl(), refreshCount: 0 };
+ events.emit("weixin-login", b.id);
+ return send(res, 200, ch.login);
+ }
+ if (sub === "weixin/login" && m === "GET") return send(res, 200, st.channels[b.id].login ?? { state: "idle" });
+ if (sub === "weixin/cancel" && m === "POST") {
+ st.channels[b.id].login = { state: "cancelled", message: "已取消", refreshCount: 0 };
+ return send(res, 200, { ok: true });
+ }
+ if (sub === "chat" && m === "GET") {
+ const conv = st.convs.get(`${b.id}:web:console`);
+ const turns = st.turns.get(`${b.id}:web:console`) ?? [];
+ const cut = turns[0]?.afterMessageId ?? Infinity;
+ return send(res, 200, {
+ conversationId: `${b.id}:web:console`,
+ model: conv?.model ?? "",
+ messages: conv ? conv.messages.filter((x) => x.id <= cut).map(publicMsg) : [],
+ pending: [...st.approvals.values()].filter((r) => r.status === "pending" && r.conversationId === `${b.id}:web:console`).map(publicApproval),
+ live: turns.map((t) => t.snapshot()),
+ });
+ }
+ if (sub === "chat/model" && m === "PUT") {
+ const body = await readJson(req);
+ const conv = ensureConv(st, b.id, "web", "console", "控制台");
+ conv.model = String(body.model ?? "");
+ events.emit("model", { botId: b.id, model: conv.model });
+ return send(res, 200, { conversationId: conv.id, model: conv.model });
+ }
+ if (sub === "chat/live" && m === "GET") {
+ const turns = st.turns.get(`${b.id}:web:console`) ?? [];
+ const want = url.searchParams.get("turn");
+ const t = want ? turns.find((x) => x.id === want) : turns[0];
+ const out = sse(res);
+ if (!t) return out.end("done", { conversationId: `${b.id}:web:console`, ended: true });
+ out.send("snapshot", t.snapshot());
+ const fn = (e, d) => (e === "done" || e === "error" ? out.end(e, d) : out.send(e, d));
+ t.subs.add(fn);
+ res.on("close", () => t.subs.delete(fn));
+ return;
+ }
+ if (sub === "chat/stream" && m === "POST") {
+ const body = await readJson(req);
+ const text = String(body.text ?? "").trim();
+ if (!text) throw new HttpError(400, "内容为空");
+ const out = sse(res);
+ events.emit("chat", { botId: b.id, text });
+ // 命令(/new 等)由运行时直接回一句,不进代理回合
+ if (text.startsWith("/")) {
+ const cmd = text.split(/\s+/)[0].toLowerCase();
+ const reply = cmd === "/new" ? "✅ 已开始新的一段对话(旧对话已归档并留下交接便条,长期记忆保留)" : cmd === "/help" ? "可用命令:/model /new /reset /status /stop /help" : `已执行 ${cmd}`;
+ await sleep(cmd === "/new" ? 700 : 200);
+ out.send("text", { text: reply, final: true });
+ events.emit("command", { botId: b.id, cmd });
+ return out.end("done", { conversationId: `${b.id}:web:console` });
+ }
+ const t = startWebTurn(b.id, text);
+ const fn = (e, d) => (e === "done" || e === "error" ? out.end(e, d) : out.send(e, d));
+ t.subs.add(fn);
+ res.on("close", () => t.subs.delete(fn));
+ await runWebTurn(t);
+ return;
+ }
+ }
+ ctl.unimplemented.push(`${m} ${url.pathname}${url.search}`);
+ log(`未实现的接口:${m} ${url.pathname}${url.search}`);
+ throw new HttpError(404, "not found");
+ }
+
+ function serveFile(res, file) {
+ fs.readFile(file, (err, data) => {
+ if (err) {
+ ctl.unimplemented.push(`静态文件缺失:${file}`);
+ return void res.writeHead(404).end("not found");
+ }
+ res.writeHead(200, { "content-type": MIME[path.extname(file)] ?? "application/octet-stream", "cache-control": "no-cache" });
+ res.end(data);
+ });
+ }
+ const safeJoin = (dir, rel) => path.join(dir, path.normalize(rel).replace(/^(\.\.[/\\])+/, ""));
+
+ const server = http.createServer((req, res) => {
+ const url = new URL(req.url || "/", "http://localhost");
+ ctl.requests.push({ at: Date.now(), method: req.method, path: url.pathname + url.search });
+ events.emit("request", { at: Date.now(), method: req.method, path: url.pathname });
+ if (url.pathname.startsWith("/amb/api/")) {
+ api(req, res, url).catch((e) => {
+ const status = e instanceof HttpError ? e.status : 500;
+ if (status === 500) ctl.errors.push(`${url.pathname}: ${e.stack || e.message}`);
+ if (!res.headersSent) send(res, status, { error: e.message });
+ });
+ return;
+ }
+ if (url.pathname === "/" || url.pathname === "/index.html") return serveFile(res, path.join(uiDir, "index.html"));
+ if (url.pathname.startsWith("/amb/static/")) return serveFile(res, safeJoin(uiDir, url.pathname.slice("/amb/static/".length)));
+ if (url.pathname.startsWith("/amb/vendor/")) {
+ const f = vendor[url.pathname.slice("/amb/vendor/".length)];
+ return f ? serveFile(res, f) : void res.writeHead(404).end();
+ }
+ if (url.pathname === "/__stage/" || url.pathname === "/__stage") return serveFile(res, path.join(stageDir, "index.html"));
+ if (url.pathname.startsWith("/__stage/")) return serveFile(res, safeJoin(stageDir, url.pathname.slice("/__stage/".length)));
+ if (url.pathname.startsWith("/__repo-assets/")) return serveFile(res, safeJoin(path.join(REPO, "assets"), url.pathname.slice("/__repo-assets/".length)));
+ if (url.pathname.startsWith("/__docs/")) return serveFile(res, safeJoin(path.join(REPO, "docs", "assets"), url.pathname.slice("/__docs/".length)));
+ if (url.pathname.startsWith("/__gen/") && genDir) return serveFile(res, safeJoin(genDir, url.pathname.slice("/__gen/".length)));
+ if (url.pathname === "/favicon.ico") return void res.writeHead(204).end();
+ ctl.unimplemented.push(`${req.method} ${url.pathname}`);
+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }).end("not found");
+ });
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(port, host, resolve);
+ });
+ ctl.url = `http://${host}:${server.address().port}/`;
+ ctl.close = () =>
+ new Promise((r) => {
+ server.closeAllConnections?.();
+ server.close(() => r());
+ });
+ return ctl;
+}
+
+// —— 命令行:单独启动,手动浏览演示数据 ——
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const arg = (k, d) => {
+ const i = process.argv.indexOf(k);
+ return i > 0 ? process.argv[i + 1] : d;
+ };
+ const scene = arg("--scene", "demo");
+ const port = Number(arg("--port", 4173));
+ // 场景脚本(录制工具的其余部分)还没写好时,所有提示词都用默认回复
+ const { scripts } = await import("./scenes.mjs").catch(() => ({ scripts: {} }));
+ const ctl = await startMock({ port, scene, sceneOpts: { memory: D.MEMORY_PREFS }, log: (s) => console.log(s) });
+ // 手动浏览时:已知的演示提示词都用 scenes.mjs 里的脚本回答
+ if (scripts[Object.keys(scripts)[0]]) ctl.onChat = (t, botId, text) => (scripts[text] || scripts.__default)(t, botId, text);
+ console.log(`模拟后端已启动:${ctl.url}(场景 ${scene})`);
+ if (scene !== "demo") console.log("登录页点「登录 / 注册 Modelflare」后,在这个终端按回车模拟浏览器里的授权。");
+ process.stdin.on("data", () => {
+ ctl.authorize();
+ console.log("已模拟授权");
+ });
+}
diff --git a/docs/assets/_src/record/record.mjs b/docs/assets/_src/record/record.mjs
new file mode 100644
index 0000000..84146c3
--- /dev/null
+++ b/docs/assets/_src/record/record.mjs
@@ -0,0 +1,413 @@
+#!/usr/bin/env node
+// 录制 README 的应用截图和功能 GIF:真实的 ui/ 界面 + 模拟后端(mock-server.mjs)+ 演示数据,
+// 用无头 Chromium(playwright-core)驱动,CDP 的 Page.startScreencast 带时间戳收帧,再交给 encode.py 按目标帧率重采样编码。
+//
+// 用法(在仓库根目录):
+// node docs/assets/_src/record/record.mjs # 录全部(截图 + GIF)
+// node docs/assets/_src/record/record.mjs model-switch # 只录名字里含这段文字的素材,可以给多个
+// node docs/assets/_src/record/record.mjs --list # 列出全部素材
+// node docs/assets/_src/record/record.mjs --check # 不开浏览器,核对全部成品的规格与上次录制的报错记录
+// 环境变量:
+// PLAYWRIGHT_CORE playwright-core 的目录(默认 site/node_modules/playwright-core)
+// CHROMIUM_PATH Chromium 可执行文件(默认用 playwright-core 自带的查找规则)
+// AMB_NODE_MODULES 装了 preact 和 htm 的 node_modules(默认仓库根目录的 node_modules)
+// REC_TMP 帧和中间文件放哪里(默认系统临时目录下的 amb-record)
+// REC_KEEP_FRAMES=1 编码后保留原始帧
+// 详见同目录的 README.md。
+
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { createRequire } from "node:module";
+import { execFileSync } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import { startMock, REPO } from "./mock-server.mjs";
+import { SCENES } from "./scenes.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const ASSETS = path.join(REPO, "docs", "assets");
+const TMP = path.resolve(process.env.REC_TMP || path.join(os.tmpdir(), "amb-record"));
+const sleep = (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)));
+const now = () => Date.now() / 1000;
+
+function loadPlaywright() {
+ const require = createRequire(import.meta.url);
+ const tries = [process.env.PLAYWRIGHT_CORE, path.join(REPO, "site", "node_modules", "playwright-core"), path.join(REPO, "node_modules", "playwright-core")].filter(Boolean);
+ for (const p of tries) {
+ try {
+ return require(p);
+ } catch {
+ /* 试下一个 */
+ }
+ }
+ throw new Error(`找不到 playwright-core:cd site && npm install,或用 PLAYWRIGHT_CORE 指定(试过:${tries.join("、")})`);
+}
+
+/** 字体:界面的字体栈在 Linux 上都落到 system-ui / sans-serif,统一指向 Noto Sans SC;等宽用 DejaVu Sans Mono */
+function fontConfig() {
+ const f = path.join(TMP, "fonts.conf");
+ fs.mkdirSync(TMP, { recursive: true });
+ fs.writeFileSync(
+ f,
+ `<?xml version="1.0"?>
+<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
+<fontconfig>
+ <include ignore_missing="yes">/etc/fonts/fonts.conf</include>
+ <alias binding="strong"><family>sans-serif</family><prefer><family>Noto Sans SC</family></prefer></alias>
+ <alias binding="strong"><family>system-ui</family><prefer><family>Noto Sans SC</family></prefer></alias>
+ <alias binding="strong"><family>monospace</family><prefer><family>DejaVu Sans Mono</family><family>Noto Sans SC</family></prefer></alias>
+</fontconfig>
+`,
+ );
+ return f;
+}
+
+/** 每个 frame 都注入:把鼠标事件换算成舞台(最外层页面)坐标,交给舞台上的假鼠标 */
+const CURSOR_HOOK = `(() => {
+ const fwd = (e) => {
+ try {
+ let x = e.clientX, y = e.clientY, w = window;
+ while (w !== w.parent) {
+ const r = w.frameElement.getBoundingClientRect();
+ x += r.left + w.frameElement.clientLeft;
+ y += r.top + w.frameElement.clientTop;
+ w = w.parent;
+ }
+ if (w.__cursor) w.__cursor(e.type, x, y);
+ } catch (_) {}
+ };
+ for (const t of ["mousemove", "mousedown", "mouseup"]) window.addEventListener(t, fwd, true);
+})();`;
+
+const UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36";
+
+/** 录制时可用的动作:鼠标(每次移动 ≥ 0.6 s、点击前停 0.3 s)、逐字输入、按时间点等待、舞台调用 */
+class Rec {
+ constructor(page, mock, spec, dir) {
+ this.page = page;
+ this.mock = mock;
+ this.spec = spec;
+ this.dir = dir;
+ this.pos = { x: -1, y: -1 };
+ this.t0 = 0;
+ this.marks = [];
+ this.frames = [];
+ this.frameDir = path.join(dir, "frames");
+ this.app = page.mainFrame();
+ }
+ /** 时间线上的秒数(从 start() 起) */
+ t() {
+ return this.t0 ? now() - this.t0 : 0;
+ }
+ start() {
+ this.t0 = now();
+ this.mark("start");
+ }
+ mark(name) {
+ if (this.t0) this.marks.push([+(now() - this.t0).toFixed(2), name]);
+ }
+ async until(t) {
+ await sleep((this.t0 + t - now()) * 1000);
+ }
+ /** 应用里的元素(舞台布局时在 iframe 里) */
+ $(sel) {
+ return this.app.locator(sel);
+ }
+ /** 在舞台上打开应用窗口(iframe),之后 $() 都在应用里找元素 */
+ async openApp(opts) {
+ await this.stage("openApp", opts);
+ this.app = this.page.frame({ name: "app" });
+ await this.app.waitForFunction(() => document.fonts.ready.then(() => true));
+ }
+ /** 舞台上的元素 */
+ s$(sel) {
+ return this.page.locator(sel);
+ }
+ stage(fn, ...args) {
+ return this.page.evaluate(([f, a]) => f.split(".").reduce((o, k) => o[k], window.stage)(...a), [fn, args]);
+ }
+ async wait(sel, opts = {}) {
+ const loc = typeof sel === "string" ? this.$(sel) : sel;
+ await loc.first().waitFor({ state: "visible", timeout: opts.timeout ?? 20000 });
+ return loc.first();
+ }
+ async waitFn(fn, arg, timeout = 20000) {
+ await this.app.waitForFunction(fn, arg, { timeout, polling: 50 });
+ }
+ async point(target, at = [0.5, 0.5]) {
+ if (target && typeof target.x === "number" && target.w === undefined) return target;
+ const loc = typeof target === "string" ? this.$(target).first() : target.first ? target.first() : target;
+ await loc.waitFor({ state: "visible", timeout: 20000 });
+ const b = await loc.boundingBox();
+ if (!b) throw new Error(`找不到元素的位置:${target}`);
+ return { x: b.x + b.width * at[0], y: b.y + b.height * at[1] };
+ }
+ /** 不动画,直接把鼠标放到某处(开始录之前用) */
+ async place(x, y) {
+ await this.page.mouse.move(x, y);
+ this.pos = { x, y };
+ }
+ /** 平滑移动:缓入缓出、略带弧度,dur 秒(不少于 0.6) */
+ async move(target, { dur = 0.7, at } = {}) {
+ const to = await this.point(target, at);
+ const from = this.pos.x < 0 ? to : this.pos;
+ const dist = Math.hypot(to.x - from.x, to.y - from.y);
+ if (dist < 1.5) return to;
+ dur = Math.max(0.6, dur);
+ const nx = -(to.y - from.y) / (dist || 1);
+ const ny = (to.x - from.x) / (dist || 1);
+ const bend = Math.min(60, dist * 0.08);
+ const cx = (from.x + to.x) / 2 + nx * bend;
+ const cy = (from.y + to.y) / 2 + ny * bend;
+ const t0 = performance.now();
+ for (;;) {
+ const k = Math.min(1, (performance.now() - t0) / (dur * 1000));
+ const e = k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;
+ const x = (1 - e) ** 2 * from.x + 2 * (1 - e) * e * cx + e * e * to.x;
+ const y = (1 - e) ** 2 * from.y + 2 * (1 - e) * e * cy + e * e * to.y;
+ await this.page.mouse.move(x, y);
+ if (k >= 1) break;
+ await sleep(14);
+ }
+ this.pos = to;
+ return to;
+ }
+ /** 移到目标、停 pause 秒、点击(double 时双击) */
+ async click(target, { dur = 0.7, pause = 0.3, double = false, at, label } = {}) {
+ await this.move(target, { dur, at });
+ await sleep(pause * 1000);
+ const n = double ? 2 : 1;
+ for (let i = 0; i < n; i++) {
+ await this.page.mouse.down({ clickCount: i + 1 });
+ await sleep(70);
+ await this.page.mouse.up({ clickCount: i + 1 });
+ if (i + 1 < n) await sleep(90);
+ }
+ this.mark(`click ${label ?? (typeof target === "string" ? target : "")}`.trim());
+ }
+ /** 逐字输入:总共 dur 秒(每条提示词不超过 4 秒),字间隔有自然的快慢 */
+ async type(text, { dur } = {}) {
+ const chars = [...text];
+ dur = Math.min(dur ?? chars.length * 0.11, 4);
+ const per = (dur * 1000) / chars.length;
+ const t0 = performance.now();
+ this.mark(`type「${text}」`);
+ for (let i = 0; i < chars.length; i++) {
+ await this.page.keyboard.type(chars[i]);
+ const target = per * (i + 1) * (0.85 + 0.3 * ((i * 7919) % 13) / 13);
+ await sleep(Math.min(per * 1.6, target - (performance.now() - t0)));
+ }
+ this.mark("typed");
+ }
+ async press(key) {
+ await this.page.keyboard.press(key);
+ this.mark(`press ${key}`);
+ }
+ /** 等到某个模拟后端事件 */
+ once(name, pred = () => true, timeout = 30000) {
+ return new Promise((resolve, reject) => {
+ const t = setTimeout(() => (this.mock.events.off(name, on), reject(new Error(`等 ${name} 超时`))), timeout);
+ const on = (d) => {
+ if (!pred(d)) return;
+ clearTimeout(t);
+ this.mock.events.off(name, on);
+ resolve(d);
+ };
+ this.mock.events.on(name, on);
+ });
+ }
+}
+
+/** 截屏流:每张帧写成 PNG,记下时间戳(秒) */
+async function startCapture(page, rec, everyNth = 2) {
+ const cdp = await page.context().newCDPSession(page);
+ fs.mkdirSync(rec.frameDir, { recursive: true });
+ let seq = 0;
+ const writes = [];
+ cdp.on("Page.screencastFrame", (f) => {
+ cdp.send("Page.screencastFrameAck", { sessionId: f.sessionId }).catch(() => {});
+ const file = path.join(rec.frameDir, String(++seq).padStart(6, "0") + ".png");
+ rec.frames.push([f.metadata.timestamp, file]);
+ writes.push(fs.promises.writeFile(file, Buffer.from(f.data, "base64")));
+ });
+ await cdp.send("Page.startScreencast", { format: "png", everyNthFrame: everyNth });
+ return async () => {
+ await cdp.send("Page.stopScreencast").catch(() => {});
+ await Promise.all(writes);
+ await cdp.detach().catch(() => {});
+ };
+}
+
+function python(args) {
+ return execFileSync("python3", [path.join(HERE, "encode.py"), ...args], { encoding: "utf8", maxBuffer: 64 << 20 }).trim();
+}
+
+/** 录一个素材:起模拟后端和浏览器上下文 → spec.run(R) → 编码 → 核对 */
+async function recordOne(chromium, spec, fontsConf, genDir) {
+ const dir = path.join(TMP, spec.id);
+ fs.rmSync(dir, { recursive: true, force: true });
+ fs.mkdirSync(dir, { recursive: true });
+ const logs = { console: [], pageErrors: [], failed: [] };
+ const mock = await startMock({ scene: spec.scene, sceneOpts: spec.sceneOpts || {}, genDir, log: (s) => logs.console.push(`[mock] ${s}`) });
+ if (spec.chat) mock.onChat = spec.chat;
+ if (spec.weixin) mock.onWeixin = spec.weixin;
+ if (spec.delays) mock.delays = spec.delays;
+ const browser = await chromium.launch({
+ headless: true,
+ executablePath: process.env.CHROMIUM_PATH || undefined,
+ env: { ...process.env, FONTCONFIG_FILE: fontsConf },
+ });
+ const shot = spec.kind === "webp";
+ const [vw, vh] = spec.viewport;
+ const ctx = await browser.newContext({
+ viewport: { width: vw, height: vh },
+ deviceScaleFactor: shot ? 2 : 1,
+ colorScheme: shot ? "light" : "dark",
+ locale: "zh-CN",
+ userAgent: UA,
+ });
+ await ctx.addInitScript(CURSOR_HOOK);
+ if (spec.storage)
+ await ctx.addInitScript((kv) => {
+ if (location.pathname !== "/" || sessionStorage.getItem("__seeded")) return;
+ sessionStorage.setItem("__seeded", "1");
+ for (const [k, v] of Object.entries(kv)) localStorage.setItem(k, v);
+ }, spec.storage);
+ const page = await ctx.newPage();
+ page.on("console", (m) => {
+ if (m.type() === "error" || m.type() === "warning") logs.console.push(`[${m.type()}] ${m.text()}`);
+ });
+ page.on("pageerror", (e) => logs.pageErrors.push(e.message));
+ page.on("requestfailed", (r) => {
+ const why = r.failure()?.errorText || "";
+ // 切走时中止的流式请求不算错
+ if (!/ERR_ABORTED/.test(why)) logs.failed.push(`${r.method()} ${r.url()} ${why}`);
+ });
+ const R = new Rec(page, mock, spec, dir);
+ let result;
+ try {
+ if (shot) {
+ await page.goto(mock.url + (spec.hash || ""));
+ await spec.run(R);
+ result = await shots(R, spec);
+ } else {
+ await page.goto(mock.url + "__stage/");
+ await page.evaluate(() => document.fonts.ready);
+ const stop = await startCapture(page, R);
+ await spec.run(R);
+ await R.until(spec.duration + 0.3);
+ R.mark("end");
+ await stop();
+ const job = { kind: "gif", frames: R.frames, t0: R.t0, duration: spec.duration, fps: spec.fps, size: spec.size, crop: spec.crop || null, out: path.join(ASSETS, spec.out), limit: spec.limit, hold: 1.0 };
+ fs.writeFileSync(path.join(dir, "job.json"), JSON.stringify(job));
+ result = JSON.parse(python([path.join(dir, "job.json")]));
+ if (!process.env.REC_KEEP_FRAMES) fs.rmSync(R.frameDir, { recursive: true, force: true });
+ }
+ } finally {
+ await browser.close().catch(() => {});
+ await mock.close();
+ }
+ const report = { id: spec.id, out: spec.out, result, marks: R.marks, logs, unimplemented: mock.unimplemented, mockErrors: mock.errors };
+ fs.writeFileSync(path.join(dir, "report.json"), JSON.stringify(report, null, 2));
+ return report;
+}
+
+/** 截图:同一时刻先浅色后深色(只切系统配色,界面跟随系统),鼠标的位置由 spec 决定 */
+async function shots(R, spec) {
+ const page = R.page;
+ const outs = [];
+ const texts = [];
+ for (const scheme of ["light", "dark"]) {
+ await page.emulateMedia({ colorScheme: scheme });
+ await sleep(900);
+ if (spec.blur !== false) await page.evaluate(() => document.activeElement?.blur?.());
+ const png = path.join(R.dir, `${scheme}.png`);
+ await page.screenshot({ path: png, animations: "disabled", caret: "hide" });
+ texts.push(await page.evaluate(() => [document.documentElement.dataset.theme, document.body.innerText]));
+ const out = path.join(ASSETS, spec.out.replace("{theme}", scheme));
+ const job = { kind: "webp", src: png, size: [1600, 1093], quality: 82, out, limit: spec.limit };
+ fs.writeFileSync(path.join(R.dir, `${scheme}.json`), JSON.stringify(job));
+ outs.push(JSON.parse(python([path.join(R.dir, `${scheme}.json`)])));
+ }
+ return { files: outs, themes: texts.map((t) => t[0]), sameText: texts[0][1] === texts[1][1] };
+}
+
+/** --check:不开浏览器,逐个核对成品是否符合规格(尺寸、时长、帧率、体积上限、空白 / 全黑帧段),并汇总上次录制留下的报错记录 */
+function check() {
+ const rows = [];
+ let bad = 0;
+ for (const spec of SCENES) {
+ const outs = spec.kind === "webp" ? ["light", "dark"].map((t) => spec.out.replace("{theme}", t)) : [spec.out];
+ for (const out of outs) {
+ const file = path.join(ASSETS, out);
+ if (!fs.existsSync(file)) {
+ rows.push(`✗ ${out}:不存在`);
+ bad++;
+ continue;
+ }
+ const r = JSON.parse(python(["--verify", file]));
+ const [w, h] = spec.kind === "webp" ? [1600, 1093] : spec.size;
+ const errs = [];
+ // 体积压缩的最后一档(encode.py:帧率 8、宽度 800)是规范允许的结果,见 docs/assets/README.md
+ const narrowed = spec.kind === "gif" && w > 800 && r.width === 800 && Math.abs(r.height - Math.round((h * 800) / w)) <= 1;
+ if ((r.width !== w || r.height !== h) && !narrowed) errs.push(`尺寸 ${r.width}×${r.height} ≠ ${w}×${h}`);
+ if (spec.kind === "gif" && Math.abs(r.duration_ms - spec.duration * 1000) > 50) errs.push(`时长 ${r.duration_ms} ms ≠ ${spec.duration * 1000}`);
+ if (spec.kind === "gif" && r.frames > spec.duration * spec.fps) errs.push(`帧数 ${r.frames} 超过 ${spec.duration}×${spec.fps}`);
+ if (r.bytes > spec.limit) errs.push(`体积 ${r.bytes} > ${spec.limit}`);
+ if (r.flat_frames.length) errs.push(`有 ${r.flat_frames.length} 帧是一片纯色(${r.black ? "黑" : r.blank ? "白" : "其他"})`);
+ const rep = path.join(TMP, spec.id, "report.json");
+ if (fs.existsSync(rep)) {
+ const j = JSON.parse(fs.readFileSync(rep, "utf8"));
+ const n = j.logs.console.filter((l) => !l.startsWith("[mock]")).length + j.logs.pageErrors.length + j.logs.failed.length + j.unimplemented.length + j.mockErrors.length;
+ if (n) errs.push(`录制时有 ${n} 条报错 / 未实现接口(${rep})`);
+ }
+ const size = r.bytes >= 1048576 ? `${(r.bytes / 1048576).toFixed(2)} MB` : `${(r.bytes / 1024).toFixed(0)} KB`;
+ const lim = spec.limit >= 1048576 ? `${(spec.limit / 1048576).toFixed(1)} MB` : `${spec.limit / 1024} KB`;
+ rows.push(`${errs.length ? "✗" : "✓"} ${out.padEnd(36)} ${`${r.width}×${r.height}`.padEnd(10)} ${spec.kind === "gif" ? `${r.frames} 帧 / ${(r.duration_ms / 1000).toFixed(1)} s / ${spec.fps} fps`.padEnd(22) : "静态".padEnd(22)} ${size.padStart(8)} / ${lim}${narrowed ? " (按规范压到 800 宽、8 fps)" : ""}${errs.length ? " " + errs.join(";") : ""}`);
+ if (errs.length) bad++;
+ }
+ }
+ console.log(rows.join("\n"));
+ console.log(bad ? `\n${bad} 个文件不合格` : `\n全部 ${rows.length} 个文件合格`);
+ if (bad) process.exitCode = 1;
+}
+
+async function main() {
+ const argv = process.argv.slice(2);
+ if (argv.includes("--check")) return check();
+ if (argv.includes("--list")) {
+ for (const s of SCENES) console.log(`${s.id.padEnd(18)} ${s.out}`);
+ return;
+ }
+ const want = argv.filter((a) => !a.startsWith("--"));
+ const list = SCENES.filter((s) => !want.length || want.some((w) => s.id.includes(w) || s.out.includes(w)));
+ if (!list.length) throw new Error(`没有匹配的素材:${want.join(" ")}(--list 查看全部)`);
+ const { chromium } = loadPlaywright();
+ const fontsConf = fontConfig();
+ const genDir = path.join(TMP, "gen");
+ if (list.some((s) => s.needsIllustration)) execFileSync("python3", [path.join(HERE, "make-illustration.py"), path.join(genDir, "sleepy-bot.png")], { stdio: "inherit" });
+ const reports = [];
+ for (const spec of list) {
+ process.stdout.write(`录制 ${spec.id} → ${spec.out} … `);
+ const t = Date.now();
+ try {
+ const r = await recordOne(chromium, spec, fontsConf, genDir);
+ reports.push(r);
+ const bad = r.logs.console.filter((l) => !l.startsWith("[mock]")).length + r.logs.pageErrors.length + r.logs.failed.length + r.unimplemented.length + r.mockErrors.length;
+ console.log(`${((Date.now() - t) / 1000).toFixed(0)} s${bad ? `,有 ${bad} 条问题,见 ${path.join(TMP, spec.id, "report.json")}` : ""}`);
+ } catch (e) {
+ console.log("失败");
+ console.error(e);
+ process.exitCode = 1;
+ }
+ }
+ // 汇总:控制台报错、页面异常、请求失败、未实现的接口
+ const sum = (k) => reports.flatMap((r) => (k === "unimplemented" ? r.unimplemented : k === "mockErrors" ? r.mockErrors : r.logs[k]).map((x) => `${r.id}: ${x}`));
+ const all = { console: sum("console"), pageErrors: sum("pageErrors"), failed: sum("failed"), unimplemented: sum("unimplemented"), mockErrors: sum("mockErrors") };
+ fs.writeFileSync(path.join(TMP, "summary.json"), JSON.stringify({ reports, ...all }, null, 2));
+ console.log(`\n控制台报错/警告 ${all.console.length},页面异常 ${all.pageErrors.length},请求失败 ${all.failed.length},未实现的接口 ${all.unimplemented.length},模拟后端错误 ${all.mockErrors.length}`);
+ for (const [k, v] of Object.entries(all)) for (const line of v) console.log(` ${k}: ${line}`);
+ console.log(`详细记录:${path.join(TMP, "summary.json")}`);
+}
+
+await main();
diff --git a/docs/assets/_src/record/scenes.mjs b/docs/assets/_src/record/scenes.mjs
new file mode 100644
index 0000000..b96a0da
--- /dev/null
+++ b/docs/assets/_src/record/scenes.mjs
@@ -0,0 +1,770 @@
+// 每个素材的录制脚本:数据场景、代理回合脚本(模拟后端按它推送活动步骤、审批、回复)、鼠标与键盘的动作和时间点。
+// 时间点对照 docs/assets/README.md 的「GIF 卡片」;卡片和应用的真实行为不一致时按真实行为录(见同目录 README.md)。
+import * as D from "./demo-data.mjs";
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const KB = 1024;
+const MB = 1024 * KB;
+const APP = { x: 0, y: 0, w: 1200, h: 820 };
+const Y = D.YELLOW;
+
+// —— 提示词 ——
+export const P = {
+ raft: D.RAFT_Q,
+ tidyShot: "整理桌面上的 demo-files",
+ tidyHero: "把桌面上 demo-files 文件夹里的文件按类型整理一下",
+ tidyFiles: "把 demo-files 里的文件按扩展名分到子文件夹,再把清单写到 整理清单.md 发给我",
+ notepad: "打开记事本,写一句『今天也要加油』,保存到桌面,文件名 note.txt",
+ draw: "画一只在键盘上打瞌睡的黄色小机器人,扁平插画",
+ hello: "你好,介绍一下你自己",
+ whichModel: "你现在是哪个模型?",
+ remember: "记住:我喜欢简短的回答,周报用中文",
+ weekly: "帮我起一个周报的开头",
+ wxIntro: "用一句话介绍你自己",
+};
+
+// —— 代理回合用到的命令(Windows 上代理用 pwsh)——
+const DEMO = "$HOME\\Desktop\\demo-files";
+const LIST_CMD = `Get-ChildItem -File "${DEMO}" | Group-Object Extension | Select-Object Name, Count`;
+const LIST_OUT = "Name Count\n---- -----\n.docx 4\n.mp3 4\n.pdf 4\n.png 4\n.xlsx 4\n.zip 4";
+const SIZE_CMD = `Get-ChildItem -File "${DEMO}" | Measure-Object Length -Sum`;
+const SIZE_OUT = "Count : 24\nSum : 3268412";
+const MOVE_CMD = `$d = "${DEMO}"; Get-ChildItem -File $d | ForEach-Object { $t = Join-Path $d $_.Extension.TrimStart('.'); New-Item -ItemType Directory -Force $t | Out-Null; Move-Item $_.FullName $t }`;
+// 越界写入的审批理由:DSH 沙箱提权的固定格式(dsh-sandbox:允许本次操作使用 <模式> 权限:<模型写的理由>)
+const MOVE_REASON = "允许本次操作使用 danger-full-access 权限:demo-files 在桌面上,不在工作区里,需要在里面建子文件夹并移动 24 个文件";
+const CHECK_CMD = `Get-ChildItem -Directory "${DEMO}" | ForEach-Object { "$($_.Name)/ $((Get-ChildItem $_.FullName).Count)" }`;
+const CHECK_OUT = "docx/ 4\nmp3/ 4\npdf/ 4\npng/ 4\nxlsx/ 4\nzip/ 4";
+const TREE = ["demo-files/", "├── docx/ 4 个文件", "├── mp3/ 4 个文件", "├── pdf/ 4 个文件", "├── png/ 4 个文件", "├── xlsx/ 4 个文件", "└── zip/ 4 个文件"].join("\n");
+const pw = (cmd) => JSON.stringify({ command: cmd }, null, 2);
+
+/** 录制时由 spec.run 填进来,回合脚本借它去摆舞台上的窗口(记事本等) */
+const ctx = { R: null, wxDelay: 2600 };
+
+/** 代理回合脚本:t 是模拟后端给的接口(model / tool / approval / question / file / reply …) */
+export const scripts = {
+ async [P.raft](t) {
+ const m = t.model();
+ await sleep(4200);
+ m.done("Raft 选主是为了让一致性问题变简单:", { output: D.RAFT_A });
+ t.reply(D.RAFT_A);
+ },
+
+ // agent 截图:五步做完,第六步(越界移动文件)等审批;截图时一直停在这里
+ async [P.tidyShot](t) {
+ let m = t.model();
+ await sleep(700);
+ m.done("调用 pwsh");
+ let c = t.tool("pwsh", LIST_CMD, pw(LIST_CMD));
+ await sleep(380);
+ c.done(LIST_OUT);
+ m = t.model();
+ await sleep(900);
+ m.done("24 个文件、6 种扩展名。先看一下总大小,再按扩展名建子文件夹,把文件移进去。");
+ c = t.tool("pwsh", SIZE_CMD, pw(SIZE_CMD));
+ await sleep(300);
+ c.done(SIZE_OUT);
+ m = t.model();
+ await sleep(600);
+ m.done("调用 pwsh");
+ t.tool("pwsh", MOVE_CMD, pw(MOVE_CMD));
+ await t.approval({ tool: "pwsh", detail: MOVE_CMD, reason: MOVE_REASON });
+ await sleep(60_000);
+ },
+
+ async [P.tidyHero](t) {
+ let m = t.model();
+ await sleep(900);
+ m.done("调用 pwsh");
+ let c = t.tool("pwsh", LIST_CMD, pw(LIST_CMD));
+ await sleep(450);
+ c.done(LIST_OUT);
+ m = t.model();
+ await sleep(1100);
+ m.done("24 个文件、6 种扩展名:按扩展名建子文件夹,再把文件移进去。");
+ c = t.tool("pwsh", MOVE_CMD, pw(MOVE_CMD));
+ await t.approval({ tool: "pwsh", detail: MOVE_CMD, reason: MOVE_REASON });
+ await sleep(800);
+ c.done();
+ c = t.tool("pwsh", CHECK_CMD, pw(CHECK_CMD));
+ await sleep(420);
+ c.done(CHECK_OUT);
+ m = t.model();
+ await sleep(1300);
+ m.done("整理好了,24 个文件按类型分进了 6 个子文件夹");
+ t.reply(`整理好了,24 个文件按类型分进了 6 个子文件夹:\n\n\`\`\`\n${TREE}\n\`\`\`\n\n文件名都没改,每个子文件夹 4 个文件。`);
+ },
+
+ async [P.tidyFiles](t) {
+ let m = t.model();
+ await sleep(1100);
+ m.done("调用 pwsh");
+ let c = t.tool("pwsh", LIST_CMD, pw(LIST_CMD));
+ await sleep(600);
+ c.done(LIST_OUT);
+ m = t.model();
+ await sleep(1500);
+ m.done("方案:建 docx、mp3、pdf、png、xlsx、zip 六个子文件夹,按扩展名移动 24 个文件,再把清单写进 整理清单.md。");
+ c = t.tool("pwsh", SIZE_CMD, pw(SIZE_CMD));
+ await sleep(500);
+ c.done(SIZE_OUT);
+ m = t.model();
+ await sleep(700);
+ m.done("调用 pwsh");
+ c = t.tool("pwsh", MOVE_CMD, pw(MOVE_CMD));
+ await t.approval({ tool: "pwsh", detail: MOVE_CMD, reason: MOVE_REASON });
+ await sleep(600);
+ c.done();
+ c = t.tool("write", "整理清单.md", JSON.stringify({ path: "整理清单.md", content: "# demo-files 整理清单\n…" }, null, 2));
+ await sleep(500);
+ c.done("已写入 整理清单.md(31 行)");
+ c = t.tool("present", "", JSON.stringify({ files: [{ path: "整理清单.md", description: "整理后的文件清单" }] }, null, 2));
+ await sleep(300);
+ c.done();
+ m = t.model();
+ await sleep(800);
+ m.done("整理好了:24 个文件分进 6 个子文件夹,清单在 整理清单.md。");
+ t.file("整理清单.md");
+ t.reply("整理好了:24 个文件按扩展名分进了 docx、mp3、pdf、png、xlsx、zip 六个子文件夹,每个 4 个。完整清单写在 **整理清单.md** 里,已经发给你。");
+ },
+
+ // G4:每个改变界面的操作都要审批(审批设为「改变界面前先问我」);记事本是舞台上的示意窗口
+ async [P.notepad](t) {
+ const R = ctx.R;
+ const CU = (a) => `mcp__computer-use__${a}`;
+ let m = t.model();
+ await sleep(700);
+ m.done(`调用 ${CU("launch_app")}`);
+ let c = t.tool(CU("launch_app"), "", JSON.stringify({ name: "notepad" }, null, 2));
+ await t.approval({ tool: CU("launch_app"), detail: JSON.stringify({ name: "notepad" }), reason: "电脑操作:launch_app" });
+ await sleep(250);
+ await R?.stage("notepad.open", NOTEPAD);
+ await sleep(250);
+ c.done("已启动 记事本(pid 4812)");
+ c = t.tool(CU("get_window_state"), "", JSON.stringify({ pid: 4812 }, null, 2));
+ await sleep(350);
+ c.done("窗口:无标题 - 记事本;文本框为空");
+ m = t.model();
+ await sleep(600);
+ m.done(`调用 ${CU("type_text")}`);
+ c = t.tool(CU("type_text"), "", JSON.stringify({ pid: 4812, text: "今天也要加油" }, null, 2));
+ await t.approval({ tool: CU("type_text"), detail: JSON.stringify({ pid: 4812, text: "今天也要加油" }), reason: "电脑操作:type_text" });
+ await sleep(200);
+ await R?.stage("notepad.type", "今天也要加油", 900);
+ c.done();
+ m = t.model();
+ await sleep(600);
+ m.done(`调用 ${CU("run_steps")}`);
+ const steps = { pid: 4812, steps: [{ action: "hotkey", keys: ["ctrl", "s"] }, { action: "type_text", text: "%USERPROFILE%\\Desktop\\note.txt" }, { action: "press_key", key: "enter" }] };
+ c = t.tool(CU("run_steps"), "", JSON.stringify(steps, null, 2));
+ await t.approval({ tool: CU("run_steps"), detail: JSON.stringify(steps), reason: "电脑操作:run_steps" });
+ await sleep(200);
+ await R?.stage("notepad.saveAs", "%USERPROFILE%\\Desktop\\note.txt", "note.txt", 1300);
+ await R?.stage("icon", "ic-note", "doc", "note.txt", NOTE_ICON.x, NOTE_ICON.y, true);
+ c.done("3 步都已执行");
+ c = t.tool(CU("get_window_state"), "", JSON.stringify({ pid: 4812 }, null, 2));
+ await sleep(600);
+ c.done("窗口:note.txt - 记事本");
+ m = t.model();
+ await sleep(1400);
+ m.done("已保存");
+ t.reply("已保存:记事本里写好了「今天也要加油」,存到了桌面,文件名 note.txt。");
+ },
+
+ // G5:生图前先确认模型(src/agent/manager.ts confirmMedia 的格式),成图用 present 交付成文件卡片
+ async [P.draw](t) {
+ let m = t.model();
+ await sleep(800);
+ m.done("调用 generate_image");
+ const prompt = "一只黄色的小机器人趴在电脑键盘上打瞌睡,闭着眼睛,旁边飘着几个 Z,扁平插画风格,配色柔和";
+ const c = t.tool("generate_image", "", JSON.stringify({ prompt, size: "1024x1024" }, null, 2));
+ const opt = (id, tag = "") => ({ label: id, description: [tag, D.MEDIA_PRICE[id]].filter(Boolean).join(" · ") || undefined });
+ const def = D.MEDIA.recommended.image;
+ await t.question(
+ [
+ {
+ id: "model",
+ header: "生成图片",
+ question: `这次用 ${def} 生成图片吗?`,
+ detail: `提示词:${prompt}\n参数:1024x1024\n参考价:${D.MEDIA_PRICE[def]}\n也可以直接回复其他模型名。`,
+ options: [opt(def, "默认"), ...D.MEDIA.image.filter((x) => x !== def).slice(0, 3).map((x) => opt(x)), { label: "取消", description: "这次不生成" }],
+ },
+ ],
+ "generate_image",
+ );
+ await sleep(2600);
+ c.done(`已用 ${def} 生成 1 张图片,保存在工作区:media/sleepy-bot.png。要发给用户,请用 present 工具交付这些文件。`);
+ const p = t.tool("present", "", JSON.stringify({ files: [{ path: "media/sleepy-bot.png" }] }, null, 2));
+ await sleep(300);
+ p.done();
+ m = t.model();
+ await sleep(700);
+ m.done("画好了");
+ t.file("sleepy-bot.png");
+ t.reply("画好了:一只趴在键盘上打瞌睡的黄色小机器人,扁平插画风格,图片发在下面。");
+ },
+
+ async [P.hello](t) {
+ const m = t.model();
+ await sleep(2000);
+ const a = "你好!我是你的 AI 助手,就住在这台电脑上。\n\n我可以陪你聊天、写东西,也能在工作区里读写文件、运行命令、帮你整理资料;连上微信或飞书之后,在手机上也能找到我。想先试试什么?";
+ m.done("你好!我是你的 AI 助手,就住在这台电脑上。");
+ t.reply(a);
+ },
+
+ async [P.whichModel](t) {
+ const m = t.model();
+ await sleep(550);
+ m.done(`我现在用的是 ${t.modelId}`);
+ t.reply(`我现在用的是 **${t.modelId}**,就是你刚才在这段对话里切换的模型。`);
+ },
+
+ async [P.remember](t) {
+ let m = t.model();
+ await sleep(700);
+ m.done("调用 remember");
+ const c = t.tool("remember", "", JSON.stringify({ text: "喜欢简短的回答;周报用中文", scope: "own" }, null, 2));
+ t.remember("喜欢简短的回答;周报用中文");
+ await sleep(300);
+ c.done("已记住(机器人记忆)");
+ m = t.model();
+ await sleep(600);
+ m.done("记住了");
+ t.reply("记住了:以后回答尽量简短,周报一律用中文写。");
+ },
+
+ async [P.weekly](t) {
+ const m = t.model();
+ await sleep(1300);
+ m.done("本周进展顺利");
+ t.reply("本周进展顺利:新版引导页已上线,支付回调的问题也修好了;下周重点推进灰度发布。");
+ },
+
+ async [P.wxIntro](t) {
+ const m = t.model();
+ await sleep(ctx.wxDelay);
+ const a = "我是小黄,住在你电脑上的 AI 助手:能聊天、整理文件、操作电脑,在微信里也随叫随到。";
+ m.done(a);
+ t.reply(a);
+ },
+
+ async __default(t, botId, text) {
+ const m = t.model();
+ await sleep(1200);
+ m.done("好的");
+ t.reply(`(演示环境没有为「${text}」准备回复)`);
+ },
+};
+const chat = (t, botId, text) => (scripts[text] || scripts.__default)(t, botId, text);
+
+// —— 舞台上的位置 ——
+const NOTEPAD = { x: 1258, y: 96, w: 516, h: 520 };
+const NOTE_ICON = { x: 1660, y: 840 };
+
+// —— 共用的几个动作 ——
+async function openChat(R, rect = APP, title = false) {
+ await R.openApp({ src: `/#/chat/${Y}`, rect, title });
+ await R.wait(".chat-col .msg-row");
+ return R.wait(".composer textarea");
+}
+/** 等审批卡片出现,移过去点「允许(仅本次)」,等它变成已批准 */
+async function allow(R, { pause = 0.35, dur = 0.65 } = {}) {
+ const b = await R.wait(".card:not(.done) .actions .btn.primary", { timeout: 30000 });
+ await R.click(b, { dur, pause, label: "允许" });
+ await R.waitFn(() => !document.querySelector(".card:not(.done) .actions .btn.primary"));
+}
+const lastReply = (R, text) => R.wait(R.$(".msg-row.assistant .msg").filter({ hasText: text }));
+const hhmm = () => {
+ const d = new Date();
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
+};
+/** 截图前鼠标停到窗口右边缘的空白处(不悬停任何控件) */
+const park = (R) => R.page.mouse.move(1196, 420);
+/** 断言:元素都在可视区域里(截图卡片要求「审批按钮可见」之类) */
+async function assertVisible(R, sels, within = ".chat-scroll") {
+ const res = await R.app.evaluate(
+ ([sels, within]) => {
+ const box = within ? document.querySelector(within).getBoundingClientRect() : { top: 0, bottom: innerHeight, left: 0, right: innerWidth };
+ return sels.map((s) => {
+ const el = [...document.querySelectorAll(s)].at(-1);
+ if (!el) return `${s}: 不存在`;
+ const r = el.getBoundingClientRect();
+ return r.top >= box.top - 1 && r.bottom <= box.bottom + 1 && r.width > 0 ? "" : `${s}: 不在可视区域(${Math.round(r.top)}–${Math.round(r.bottom)},区域 ${Math.round(box.top)}–${Math.round(box.bottom)})`;
+ });
+ },
+ [sels, within],
+ );
+ const bad = res.filter(Boolean);
+ if (bad.length) throw new Error("截图断言失败:" + bad.join(";"));
+}
+
+const shot = (id, extra) => ({ id: `shot-${id}`, out: `screenshots/${id}-{theme}.webp`, kind: "webp", viewport: [1200, 820], limit: 300 * KB, scene: "demo", storage: { "amb-bot": Y }, chat, ...extra });
+const gif = (id, out, extra) => ({ id, out, kind: "gif", viewport: [1200, 820], size: [960, 656], fps: 10, limit: 3 * MB, scene: "demo", storage: { "amb-bot": Y }, chat, ...extra });
+
+export const SCENES = [
+ // ---------------------------------------------------------------- 截图(明暗成对)
+ shot("chat", {
+ hash: `#/chat/${Y}`,
+ async run(R) {
+ const ta = await R.wait(".composer textarea");
+ await R.wait(".chat-col .msg-row");
+ await ta.click();
+ await R.page.keyboard.type(P.raft);
+ await R.page.keyboard.press("Enter");
+ await lastReply(R, "Raft 选主是为了");
+ await R.wait(".msg-row.assistant.last pre");
+ await park(R);
+ await sleep(2200);
+ await assertVisible(R, [".msg-row.user .msg", ".msg-row.assistant.last pre", ".msg-row.assistant.last ol"]);
+ if ((await R.$(".side-list .thread").count()) !== 6) throw new Error("侧栏不是六个机器人");
+ if (!/claude-sonnet-5-5/.test(await R.$(".composer .model-chip:not(.perm)").innerText())) throw new Error("模型按钮没显示模型名");
+ },
+ }),
+ shot("agent", {
+ hash: `#/chat/${Y}`,
+ async run(R) {
+ const ta = await R.wait(".composer textarea");
+ await R.wait(".chat-col .msg-row");
+ await ta.click();
+ await R.page.keyboard.type(P.tidyShot);
+ await R.page.keyboard.press("Enter");
+ await R.wait(".card:not(.done) .actions .btn.primary", { timeout: 30000 });
+ await (await R.wait("button.work-line.toggle.live")).click();
+ await R.wait(".act-list .act-step");
+ await sleep(400);
+ // 展开的步骤列表不会自动滚到底:像用户一样滚一下
+ await R.page.mouse.move(700, 400);
+ await R.page.mouse.wheel(0, 1600);
+ await park(R);
+ await sleep(1500);
+ const n = await R.$(".act-list .act-step.ok").count();
+ const running = await R.$(".act-list .act-step.running").count();
+ if (n < 4 || n > 5 || running !== 1) throw new Error(`步骤数不对:完成 ${n},进行中 ${running}`);
+ await assertVisible(R, [".card:not(.done) .actions .btn.primary", ".card:not(.done) .q", ".act-list .act-step.running"]);
+ },
+ }),
+ shot("models", {
+ hash: `#/chat/${Y}`,
+ async run(R) {
+ await R.wait(".chat-col .msg-row");
+ await R.$(".composer .model-chip:not(.perm)").click();
+ await R.wait(".model-picker li[role=option] .n");
+ await R.$(".model-picker li.fam").filter({ hasText: "GPT" }).click();
+ await sleep(300);
+ // 列表一屏放得下 9 行:滚到 GPT 的第一个模型在顶上,这样 GPT 4 个 + Claude 4 个都在视野里
+ const list = R.$(".model-picker ul");
+ const b = await list.boundingBox();
+ await R.page.mouse.move(b.x + b.width / 2, b.y + 60);
+ const off = await R.app.evaluate(() => {
+ const ul = document.querySelector(".model-picker ul");
+ const first = [...ul.querySelectorAll("li[role=option]")].find((li) => li.textContent.startsWith("gpt-"));
+ return first.getBoundingClientRect().top - ul.getBoundingClientRect().top - parseFloat(getComputedStyle(ul).paddingTop);
+ });
+ await R.page.mouse.wheel(0, off);
+ await sleep(500);
+ const third = R.$(".model-picker ul > li").nth(await R.app.evaluate(() => {
+ const ul = document.querySelector(".model-picker ul");
+ const top = ul.getBoundingClientRect().top;
+ const lis = [...ul.children];
+ return lis.findIndex((li) => li.getBoundingClientRect().top >= top - 1) + 2;
+ }));
+ const tb = await third.boundingBox();
+ await R.page.mouse.move(tb.x + tb.width * 0.4, tb.y + tb.height / 2);
+ await sleep(900);
+ // 断言:搜索框为空;可见的模型行至少 8 个,每行都有上下文、能力和参考价;第三行是悬停高亮
+ const info = await R.app.evaluate(() => {
+ const ul = document.querySelector(".model-picker ul").getBoundingClientRect();
+ const rows = [...document.querySelectorAll(".model-picker li[role=option]")].filter((li) => {
+ const r = li.getBoundingClientRect();
+ return r.top >= ul.top - 1 && r.bottom <= ul.bottom + 1 && !li.textContent.includes("跟随机器人默认");
+ });
+ return {
+ q: document.querySelector(".model-picker input").value,
+ rows: rows.map((li) => li.textContent),
+ third: (() => {
+ const lis = [...document.querySelectorAll(".model-picker ul > li")].filter((li) => li.getBoundingClientRect().top >= ul.top - 1);
+ return lis[2].className + " " + lis[2].textContent;
+ })(),
+ };
+ });
+ const priced = info.rows.filter((t) => /\d(K|M) · 视觉|工具/.test(t) && /\$/.test(t));
+ if (info.q || info.rows.length < 8 || priced.length !== info.rows.length || !/sel/.test(info.third)) throw new Error("模型选择器断言失败:" + JSON.stringify(info));
+ },
+ }),
+ shot("memory", {
+ hash: `#/chat/${Y}`,
+ sceneOpts: { memory: D.MEMORY_PREFS },
+ async run(R) {
+ await R.wait(".chat-col .msg-row");
+ await R.$('.chat-head button[aria-label^="信息面板"]').click();
+ await R.wait(".panel .row .badge.ok");
+ await R.waitFn(() => document.querySelectorAll(".panel .row.compact .selectable").length === 4);
+ await R.waitFn(() => [...document.querySelectorAll(".panel .row.compact.clickable")].length === 3);
+ await park(R);
+ await sleep(1500);
+ const ok = await R.$(".panel .badge.ok").count();
+ if (ok !== 2) throw new Error(`渠道没有都显示已连接:${ok}`);
+ await assertVisible(R, [".panel .row.compact.clickable"], ".panel-body");
+ },
+ }),
+ shot("modelflare", {
+ hash: "#/settings/modelflare",
+ async run(R) {
+ await R.wait("#set-balance");
+ await R.wait("#set-default-model .pick");
+ await R.$("#set-usage button").click();
+ await R.wait(".usage-days .bar i");
+ await park(R);
+ await sleep(1500);
+ const t = await R.app.evaluate(() => document.querySelector(".sheet").innerText);
+ if (!/合计 \$/.test(t)) throw new Error("用量弹窗没有数据");
+ if (!/\$12\.40/.test(await R.$("#set-balance").innerText())) throw new Error("余额不是 12.40");
+ },
+ }),
+
+ // ---------------------------------------------------------------- GIF(一律深色)
+ gif("hero-demo", "hero/hero-demo.gif", {
+ fps: 12,
+ duration: 20,
+ limit: 5 * MB,
+ scene: "signed-out",
+ async run(R) {
+ await R.openApp({ src: "/", rect: APP });
+ const login = await R.wait(".login-cta .btn.primary");
+ await R.place(640, 720);
+ await R.move(login, { dur: 0.8 });
+ await sleep(500);
+ R.start();
+ await R.until(1.2);
+ const started = R.once("login-started");
+ await R.click(login, { pause: 0.3, label: "登录 / 注册 Modelflare" });
+ await started;
+ await sleep(120);
+ await R.stage("browser.show", APP, { loading: 200 });
+ R.mark("浏览器授权页");
+ await sleep(300);
+ await R.click(R.s$("#auth-ok"), { dur: 0.6, pause: 0.3, label: "继续(授权)" });
+ R.mock.authorize();
+ await R.stage("browser.done");
+ await sleep(320);
+ await R.stage("browser.hide");
+ R.mark("回到应用");
+ const start = await R.wait(R.$(".onboard button").filter({ hasText: "开始对话" }));
+ await R.click(start, { dur: 0.6, pause: 0.3, label: "开始对话" });
+ const ta = await R.wait(".composer textarea");
+ R.mark("主界面");
+ await R.click(ta, { dur: 0.6, pause: 0.15, label: "输入框" });
+ await R.type(P.tidyHero, { dur: 2.2 });
+ await R.press("Enter");
+ const tog = await R.wait("button.work-line.toggle.live");
+ await R.click(tog, { dur: 0.6, pause: 0.3, label: "展开活动列表" });
+ await allow(R, { pause: 0.4 });
+ await R.move({ x: 760, y: 560 }, { dur: 0.8 });
+ await lastReply(R, "整理好了");
+ R.mark("回复完成");
+ },
+ }),
+
+ gif("install-windows", "download/install-windows.gif", {
+ viewport: [1920, 1080],
+ size: [960, 540],
+ duration: 12,
+ limit: 2.5 * MB,
+ scene: "fresh",
+ storage: {},
+ delays: { "/modelflare": 900 },
+ async run(R) {
+ await R.stage("init", { background: "wallpaper" });
+ await R.stage("explorer.show", { x: 300, y: 190, w: 980, h: 560 }, { name: "anymodel-bot-0.1.13-win-x64.exe", date: "2026-10-31 15:42", size: "187 MB" });
+ await R.place(1000, 820);
+ await sleep(500);
+ R.start();
+ await R.until(0.3);
+ await R.click(R.s$("#exe"), { dur: 0.8, pause: 0.3, double: true, label: "双击安装包" });
+ await sleep(260);
+ await R.stage("installer.show", { x: 640, y: 290, w: 640, h: 470 });
+ R.mark("安装向导");
+ await R.until(2.2);
+ await R.click(R.s$("#ins-next"), { dur: 0.7, pause: 0.3, label: "下一步" });
+ await R.stage("installer.page", 2);
+ await R.until(3.4);
+ await R.click(R.s$("#ins-next"), { dur: 0.6, pause: 0.5, label: "安装" });
+ await R.stage("installer.page", 3);
+ await R.stage("installer.progress", 2500);
+ await R.stage("installer.page", 4);
+ await R.until(6.8);
+ await R.click(R.s$("#ins-next"), { dur: 0.6, pause: 0.5, label: "完成" });
+ await R.stage("installer.close");
+ await R.move({ x: 1040, y: 1000 }, { dur: 0.8 });
+ await R.openApp({ src: "/", rect: { x: 360, y: 148, w: 1200, h: 820 }, title: true, enter: true });
+ R.mark("应用启动");
+ const login = await R.wait(".login-cta .btn.primary");
+ R.mark("欢迎页");
+ await R.until(10.0);
+ await R.move(login, { dur: 0.8 });
+ R.mark("停在登录按钮");
+ },
+ }),
+
+ gif("agent-files", "features/agent-files.gif", {
+ duration: 15,
+ async run(R) {
+ const ta = await openChat(R);
+ await R.place(700, 520);
+ await R.click(ta, { dur: 0.7, pause: 0.2 });
+ await sleep(600);
+ R.start();
+ await R.until(0.2);
+ await R.type(P.tidyFiles, { dur: 3.0 });
+ await R.press("Enter");
+ const tog = await R.wait("button.work-line.toggle.live");
+ await R.click(tog, { dur: 0.6, pause: 0.3, label: "展开活动列表" });
+ await allow(R, { pause: 0.5, dur: 0.7 });
+ await R.move({ x: 860, y: 600 }, { dur: 0.8 });
+ await R.wait(".file-card");
+ R.mark("文件卡片");
+ },
+ }),
+
+ gif("computer-use", "features/computer-use.gif", {
+ viewport: [1800, 1012],
+ size: [960, 540],
+ duration: 18,
+ sceneOpts: { cuApproval: "ask-input" },
+ async run(R) {
+ ctx.R = R;
+ await R.stage("init", { background: "wallpaper" });
+ await R.stage("icon", "ic-demo", "folder", "demo-files", 1660, 700);
+ const ta = await openChat(R, { x: 24, y: 70, w: 1200, h: 820 }, true);
+ await R.place(760, 600);
+ await R.click(ta, { dur: 0.7, pause: 0.2 });
+ await sleep(600);
+ R.start();
+ await R.until(0.15);
+ await R.type(P.notepad, { dur: 2.7 });
+ await R.press("Enter");
+ for (let i = 0; i < 3; i++) await allow(R, { pause: 0.35 });
+ await R.move({ x: 900, y: 560 }, { dur: 0.8 });
+ await lastReply(R, "已保存");
+ R.mark("回复已保存");
+ },
+ }),
+
+ gif("media-generation", "features/media-generation.gif", {
+ duration: 14,
+ needsIllustration: true,
+ async run(R) {
+ const ta = await openChat(R);
+ await R.place(700, 520);
+ await R.click(ta, { dur: 0.7, pause: 0.2 });
+ await sleep(600);
+ R.start();
+ await R.until(0.2);
+ await R.type(P.draw, { dur: 2.6 });
+ await R.press("Enter");
+ const opts = R.$(".card:not(.done) .opt");
+ await R.wait(opts);
+ R.mark("确认卡片");
+ await R.move(opts.nth(1), { dur: 0.7, at: [0.3, 0.5] });
+ R.mark("指向换模型的选项");
+ await sleep(1000);
+ await R.click(opts.nth(0), { dur: 0.6, pause: 0.3, at: [0.3, 0.5], label: "确认默认模型" });
+ await R.move({ x: 700, y: 640 }, { dur: 0.8 });
+ await R.wait(".file-card");
+ R.mark("文件卡片");
+ await sleep(500);
+ await R.stage("viewer.show", { x: 742, y: 96, w: 430, h: 470 }, { src: "/__gen/sleepy-bot.png", name: "sleepy-bot.png", info: "1024 × 1024 · PNG" });
+ R.mark("看图窗口(示意)");
+ },
+ }),
+
+ gif("first-run", "features/first-run.gif", {
+ duration: 16,
+ scene: "fresh",
+ storage: {},
+ async run(R) {
+ await R.openApp({ src: "/", rect: APP });
+ const login = await R.wait(".login-cta .btn.primary");
+ await R.place(620, 300);
+ await sleep(500);
+ R.start();
+ await R.until(0.6);
+ const started = R.once("login-started");
+ await R.click(login, { dur: 0.8, pause: 0.35, label: "登录 / 注册 Modelflare" });
+ await started;
+ await sleep(950);
+ await R.stage("browser.show", APP, { loading: 400 });
+ R.mark("浏览器授权页");
+ await R.until(4.6);
+ await R.click(R.s$("#auth-ok"), { dur: 0.8, pause: 0.35, label: "继续(授权)" });
+ R.mock.authorize();
+ await R.stage("browser.done");
+ await sleep(900);
+ await R.stage("browser.hide");
+ R.mark("回到应用");
+ const row = await R.wait(R.$(".picklist button[role=option]").filter({ hasText: "claude-sonnet-5-5" }));
+ R.mark("模型列表");
+ await R.until(Math.max(R.t(), 7.6));
+ await R.click(row, { dur: 0.7, pause: 0.3, label: "选默认模型" });
+ await R.click(R.$(".onboard button").filter({ hasText: "开始对话" }), { dur: 0.7, pause: 0.3, label: "开始对话" });
+ const ta = await R.wait(".composer textarea");
+ R.mark("对话页");
+ await R.click(ta, { dur: 0.7, pause: 0.2 });
+ await R.type(P.hello, { dur: 1.3 });
+ await R.press("Enter");
+ await R.move({ x: 860, y: 600 }, { dur: 0.8 });
+ await lastReply(R, "你好!我是");
+ R.mark("回复");
+ },
+ }),
+
+ gif("model-switch", "features/model-switch.gif", {
+ duration: 12,
+ async run(R) {
+ await openChat(R);
+ await R.place(760, 380);
+ await sleep(600);
+ R.start();
+ await R.until(0.6);
+ await R.click(".composer .model-chip:not(.perm)", { dur: 0.65, pause: 0.3, label: "模型按钮" });
+ const input = await R.wait(".model-picker .search input");
+ await R.until(1.9);
+ await R.type("claude", { dur: 0.8 });
+ // 筛选后是 4 个 Claude 模型,外加一行「使用「claude」」(输入的不是现成的模型 ID 时界面会给这一行)
+ await R.waitFn(() => [...document.querySelectorAll(".model-picker li[role=option]")].filter((li) => li.textContent.startsWith("claude-")).length === 4);
+ const row = (id) => R.$(".model-picker li[role=option]").filter({ hasText: id });
+ await R.until(3.8);
+ await R.move(row("claude-opus-5-5"), { dur: 0.7, at: [0.35, 0.5] });
+ R.mark("悬停 claude-opus-5-5");
+ await sleep(1000);
+ await R.move(row("claude-opus-4-8"), { dur: 0.7, at: [0.35, 0.5] });
+ R.mark("悬停 claude-opus-4-8");
+ await sleep(1000);
+ await R.click(row("claude-opus-5-5"), { dur: 0.6, pause: 0.3, at: [0.35, 0.5], label: "选 claude-opus-5-5" });
+ await R.waitFn(() => /claude-opus-5-5/.test(document.querySelector(".composer .model-chip:not(.perm)").textContent));
+ R.mark("按钮已更新");
+ await R.click(".composer textarea", { dur: 0.65, pause: 0.2 });
+ await R.type(P.whichModel, { dur: 0.9 });
+ await R.press("Enter");
+ await lastReply(R, "我现在用的是");
+ R.mark("回复");
+ void input;
+ },
+ }),
+
+ gif("memory", "features/memory.gif", {
+ duration: 16,
+ sceneOpts: { memory: D.MEMORY_PREFS.slice(0, 3) },
+ async run(R) {
+ const ta = await openChat(R);
+ await R.place(700, 520);
+ await R.click(ta, { dur: 0.7, pause: 0.2 });
+ await sleep(600);
+ R.start();
+ await R.until(0.2);
+ await R.type(P.remember, { dur: 2.0 });
+ await R.press("Enter");
+ await lastReply(R, "记住了");
+ R.mark("机器人确认");
+ await R.until(Math.max(R.t() + 0.2, 4.0));
+ await R.click('.chat-head button[aria-label^="信息面板"]', { dur: 0.7, pause: 0.3, label: "信息面板" });
+ await R.waitFn(() => [...document.querySelectorAll(".panel .row.compact .selectable")].some((e) => e.textContent.includes("周报用中文")));
+ const entry = R.$(".panel .row.compact").filter({ hasText: "周报用中文" });
+ await R.move(entry, { dur: 0.7, at: [0.45, 0.5] });
+ R.mark("指着新记忆");
+ await sleep(1100);
+ await R.click('.chat-head button[aria-label^="开始新的一段对话"]', { dur: 0.7, pause: 0.3, label: "新对话" });
+ await lastReply(R, "已开始新的一段对话");
+ R.mark("新对话");
+ await R.click(".composer textarea", { dur: 0.7, pause: 0.2 });
+ await R.type(P.weekly, { dur: 1.2 });
+ await R.press("Enter");
+ await lastReply(R, "本周进展顺利");
+ R.mark("回复");
+ },
+ }),
+
+ gif("channels-wechat", "features/channels-wechat.gif", {
+ viewport: [1600, 900],
+ size: [960, 540],
+ duration: 18,
+ sceneOpts: { weixinBound: false, extraConvs: false, memory: D.MEMORY_PREFS.slice(0, 2) },
+ async weixin(t, botId, text) {
+ await scripts[text](t, botId, text);
+ },
+ async run(R) {
+ ctx.R = R;
+ await R.stage("init", { background: "black" });
+ const rect = { x: 0, y: 40, w: 1200, h: 820 };
+ await openChat(R, rect);
+ await R.stage("phone.show", { x: 1200, y: 0, w: 400, h: 900 }, { title: "小黄", clock: hhmm() });
+ // 录制开始前:打开信息面板 → 微信 → 扫码登录,二维码出来
+ await R.place(760, 300);
+ const tPanel = Date.now();
+ await R.click('.chat-head button[aria-label^="信息面板"]', { dur: 0.6, pause: 0.2 });
+ const wxRow = R.$(".panel .row.clickable").filter({ hasText: "微信" });
+ await R.click(wxRow, { dur: 0.6, pause: 0.2 });
+ await R.click(R.$(".panel .row-edit .btn.primary").filter({ hasText: "扫码登录" }), { dur: 0.6, pause: 0.2 });
+ await R.wait(".panel-qr");
+ const tQr = Date.now();
+ await R.move(".panel-qr", { dur: 0.7, at: [0.5, 1.15] });
+ // 对齐两个轮询:信息面板每 8 秒取一次最近会话(新会话出现的时刻),微信这一行扫码时每 1.5 秒刷新一次("已连接"出现的时刻)
+ await sleep(3400);
+ const reqs = R.mock.requests;
+ const detail = new RegExp(`^/amb/api/bots/${Y}$`);
+ const convs = /^\/amb\/api\/conversations\?bot=/;
+ const conv0 = reqs.find((r) => r.at >= tPanel && convs.test(r.path)).at;
+ const panel0 = reqs.find((r) => r.at >= tPanel && detail.test(r.path)).at;
+ const fast = reqs.filter((r) => r.at > tQr + 200 && detail.test(r.path) && Math.abs(((r.at - panel0) % 5000) - 2500) < 2350).map((r) => r.at);
+ const phase = fast.at(-1);
+ let t0 = 0;
+ let convAt = 0;
+ for (let j = 1; j < 60 && !t0; j++) {
+ const cand = phase + 1500 * j - 3000;
+ if (cand < Date.now() + 500) continue;
+ for (let k = 1; k < 20; k++) {
+ const c = conv0 + 8000 * k - cand;
+ if (c >= 9000 && c <= 10600) {
+ t0 = cand;
+ convAt = c / 1000;
+ break;
+ }
+ }
+ }
+ if (!t0) throw new Error("对不齐轮询");
+ await sleep(t0 - Date.now());
+ R.t0 = t0 / 1000;
+ R.mark(`start(最近会话的轮询在 ${convAt.toFixed(1)} s)`);
+ await R.until(2.85);
+ R.mock.weixinConfirm(Y);
+ await R.waitFn(() => [...document.querySelectorAll(".panel .row.clickable")].some((r) => r.textContent.includes("微信") && r.textContent.includes("已连接")));
+ R.mark("微信已连接");
+ // 手机上发消息
+ const inp = await R.s$("#ph-in").boundingBox();
+ await R.until(3.4);
+ await R.stage("tap", inp.x + 80, inp.y + inp.height / 2);
+ await sleep(200);
+ await R.stage("phone.type", P.wxIntro, 1900);
+ const send = await R.s$("#ph-send").boundingBox();
+ await sleep(300);
+ await R.stage("tap", send.x + send.width / 2, send.y + send.height / 2);
+ await sleep(120);
+ await R.stage("phone.send");
+ R.mark("手机发出");
+ ctx.wxDelay = Math.max(1600, (convAt - 0.7 - R.t()) * 1000);
+ const reply = R.mock.weixinInbound(Y, D.WEIXIN_USER, P.wxIntro);
+ await sleep(500);
+ await R.stage("phone.typing");
+ const listY = await R.$(".panel .list-head").filter({ hasText: "最近会话" }).boundingBox();
+ await R.move({ x: listY.x + 120, y: listY.y + 60 }, { dur: 0.9 });
+ const text = await reply;
+ await R.stage("phone.add", "bot", text);
+ R.mark("手机收到回复");
+ const row = R.$(".panel .row.compact.clickable").filter({ hasText: "微信 ·" });
+ await R.wait(row);
+ R.mark("最近会话出现微信会话");
+ await R.click(row, { dur: 0.7, pause: 0.3, label: "打开微信会话" });
+ await R.waitFn(() => document.querySelectorAll(".sheet .transcript-msg").length >= 2);
+ R.mark("桌面端显示同一段对话");
+ },
+ }),
+];
diff --git a/docs/assets/_src/record/stage/index.html b/docs/assets/_src/record/stage/index.html
new file mode 100644
index 0000000..6e1fa71
--- /dev/null
+++ b/docs/assets/_src/record/stage/index.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+ <meta charset="utf-8" />
+ <title>录制舞台</title>
+ <!-- 录制舞台:真实的应用界面放在 iframe 里;应用外的画面(浏览器授权页、安装向导、文件窗口、文本编辑器、
+ 看图窗口、手机聊天)都是中性的风格化示意,不仿任何第三方产品的界面。假鼠标由 stage.js 画在最上层。 -->
+ <link rel="stylesheet" href="/__stage/stage.css" />
+</head>
+<body>
+ <div id="screen"></div>
+ <div id="touch" aria-hidden="true"></div>
+ <div id="cursor" aria-hidden="true">
+ <svg width="22" height="30" viewBox="0 0 22 30"><path d="M2 2 L2 24.5 L7.6 19.4 L11.4 27.6 L15.2 25.9 L11.5 17.9 L19 17.9 Z" fill="#fff" stroke="#000" stroke-width="1.6" stroke-linejoin="round" /></svg>
+ <i class="ring"></i>
+ </div>
+ <script src="/__stage/stage.js"></script>
+</body>
+</html>
diff --git a/docs/assets/_src/record/stage/stage.css b/docs/assets/_src/record/stage/stage.css
new file mode 100644
index 0000000..a0f963b
--- /dev/null
+++ b/docs/assets/_src/record/stage/stage.css
@@ -0,0 +1,174 @@
+/* 录制舞台的样式:所有应用外的窗口都是中性的深色示意窗,不照抄任何系统或第三方产品。 */
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; overflow: hidden; background: #000; }
+body { font: 14px/1.5 "Noto Sans SC", system-ui, sans-serif; color: #e8e8e6; -webkit-font-smoothing: antialiased; }
+#screen { position: absolute; inset: 0; overflow: hidden; }
+.wallpaper { position: absolute; inset: 0; background: radial-gradient(120% 90% at 20% 10%, #2b3445 0%, #1a2030 45%, #12151d 100%); }
+.blackout { position: absolute; inset: 0; background: #000; }
+
+/* —— 假鼠标:默认箭头,按下时缩一点并出一圈淡环 —— */
+#cursor { position: fixed; left: 0; top: 0; z-index: 2147483647; pointer-events: none; transform-origin: 2px 2px; opacity: 0; transition: opacity .15s; will-change: transform; }
+#cursor.on { opacity: 1; }
+#cursor svg { display: block; filter: drop-shadow(0 1px 1.5px rgba(0, 0, 0, .45)); transition: transform .08s ease-out; transform-origin: 2px 2px; }
+#cursor.down svg { transform: scale(.86); }
+#cursor .ring { position: absolute; left: -12px; top: -12px; width: 28px; height: 28px; border-radius: 50%; border: 2px solid rgba(255, 255, 255, .85); opacity: 0; transform: scale(.4); }
+#cursor.click .ring { animation: ring .42s ease-out; }
+@keyframes ring { 0% { opacity: .9; transform: scale(.4); } 100% { opacity: 0; transform: scale(1.25); } }
+/* 手机上的点按:一个淡淡的圆点 */
+#touch { position: fixed; z-index: 2147483646; width: 46px; height: 46px; margin: -23px 0 0 -23px; border-radius: 50%; background: rgba(255, 255, 255, .38); pointer-events: none; opacity: 0; transform: scale(.6); }
+#touch.tap { animation: tap .5s ease-out; }
+@keyframes tap { 0% { opacity: .9; transform: scale(.6); } 60% { opacity: .55; transform: scale(1); } 100% { opacity: 0; transform: scale(1.1); } }
+
+/* —— 窗口 —— */
+.win { position: absolute; display: flex; flex-direction: column; background: #1c1d20; border-radius: 10px; overflow: hidden;
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, .09), 0 18px 50px rgba(0, 0, 0, .55), 0 4px 14px rgba(0, 0, 0, .35); }
+.win.enter { animation: win-in .22s cubic-bezier(.2, .8, .2, 1); }
+.win.leave { animation: win-out .18s ease-in forwards; }
+@keyframes win-in { from { opacity: 0; transform: scale(.97) translateY(6px); } to { opacity: 1; transform: none; } }
+@keyframes win-out { to { opacity: 0; transform: scale(.98); } }
+.win.plain { border-radius: 0; box-shadow: none; }
+.titlebar { flex: none; height: 34px; display: flex; align-items: center; gap: 8px; padding: 0 0 0 12px; background: #26272b; color: #cfcfcc; font-size: 13px; user-select: none; }
+.titlebar img { width: 16px; height: 16px; border-radius: 4px; }
+.titlebar .t { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.titlebar .wb { width: 44px; height: 34px; display: grid; place-items: center; color: #9a9a96; }
+.titlebar .wb svg { width: 10px; height: 10px; }
+.win-body { position: relative; flex: 1; min-height: 0; }
+.win iframe { display: block; border: 0; background: #0c0c0c; }
+
+/* —— 浏览器(授权页):中性的地址栏 + 一张授权卡片 —— */
+.browser { background: #141518; }
+.browser .tabs { height: 38px; display: flex; align-items: flex-end; gap: 6px; padding: 0 10px; background: #1f2024; }
+.browser .tab { height: 30px; min-width: 220px; display: flex; align-items: center; gap: 8px; padding: 0 12px; border-radius: 8px 8px 0 0; background: #2a2b30; color: #d6d6d2; font-size: 12.5px; }
+.browser .tab i { width: 12px; height: 12px; border-radius: 3px; background: #d7ff00; }
+.browser .bar { height: 44px; display: flex; align-items: center; gap: 10px; padding: 0 12px; background: #2a2b30; border-bottom: 1px solid #111; }
+.browser .nav { display: flex; gap: 14px; color: #77777a; font-size: 15px; padding: 0 4px; }
+.browser .addr { flex: 1; height: 30px; display: flex; align-items: center; gap: 8px; padding: 0 14px; border-radius: 15px; background: #18191c; color: #a8a8a4; font-size: 13px; white-space: nowrap; overflow: hidden; }
+.browser .addr b { color: #ecece8; font-weight: 500; }
+.browser .addr svg { flex: none; }
+.browser .page { position: relative; flex: 1; display: grid; place-items: center; background: #101113; }
+.browser .page.loading > * { opacity: 0; }
+.auth-card { width: 440px; padding: 34px 36px 30px; border-radius: 16px; background: #1b1c1f; box-shadow: 0 0 0 1px rgba(255, 255, 255, .07); text-align: center; transition: opacity .2s; }
+.auth-card .marks { display: flex; align-items: center; justify-content: center; gap: 14px; margin-bottom: 20px; }
+.auth-card .marks img { width: 52px; height: 52px; }
+.auth-card .marks .mf { width: 52px; height: 52px; border-radius: 14px; background: #2a2b2f; display: grid; place-items: center; font-weight: 700; font-size: 22px; color: #f0f0ec; }
+.auth-card .marks .dots { color: #66665f; letter-spacing: 3px; }
+.auth-card h1 { margin: 0 0 6px; font-size: 20px; font-weight: 600; color: #f2f2ee; }
+.auth-card .who { color: #9c9c97; font-size: 13.5px; margin-bottom: 18px; }
+.auth-card ul { list-style: none; margin: 0 0 24px; padding: 14px 16px; border-radius: 10px; background: #151618; text-align: left; color: #c9c9c4; font-size: 13.5px; }
+.auth-card li { display: flex; gap: 10px; align-items: baseline; }
+.auth-card li + li { margin-top: 8px; }
+.auth-card li::before { content: ""; flex: none; width: 6px; height: 6px; margin-top: 8px; border-radius: 50%; background: #d7ff00; }
+.auth-card .btns { display: grid; gap: 10px; }
+.btn-s { height: 40px; border: 0; border-radius: 10px; font: inherit; font-size: 14.5px; font-weight: 600; cursor: default; }
+.btn-s.primary { background: #d7ff00; color: #161a00; }
+.btn-s.primary:hover { background: #e3ff4d; }
+.btn-s.ghost { background: transparent; color: #a3a39e; font-weight: 500; }
+.auth-done { position: absolute; display: grid; justify-items: center; gap: 10px; text-align: center; opacity: 0; transition: opacity .2s; }
+.auth-done .ok { width: 54px; height: 54px; border-radius: 50%; background: rgba(215, 255, 0, .14); display: grid; place-items: center; }
+.auth-done h2 { margin: 6px 0 0; font-size: 20px; font-weight: 600; color: #f2f2ee; }
+.auth-done p { margin: 0; color: #9c9c97; }
+.browser.done .auth-card { opacity: 0; }
+.browser.done .auth-done { opacity: 1; }
+
+/* —— 文件窗口(下载文件夹)—— */
+.explorer .body { display: flex; flex: 1; min-height: 0; background: #1a1b1e; }
+.explorer .tool { height: 44px; display: flex; align-items: center; gap: 10px; padding: 0 14px; background: #202125; border-bottom: 1px solid #111; color: #a4a4a0; font-size: 13px; }
+.explorer .crumb { flex: 1; height: 28px; display: flex; align-items: center; padding: 0 12px; border-radius: 6px; background: #17181b; color: #cfcfca; }
+.explorer nav { width: 180px; padding: 12px 8px; border-right: 1px solid #111; color: #b5b5b0; font-size: 13.5px; }
+.explorer nav div { height: 32px; display: flex; align-items: center; gap: 10px; padding: 0 10px; border-radius: 6px; }
+.explorer nav div.on { background: #2a2b30; color: #f0f0ec; }
+.explorer nav i { width: 14px; height: 11px; border-radius: 2px; background: #6b7280; }
+.explorer .list { flex: 1; padding: 8px 10px; font-size: 13.5px; }
+.explorer .head, .explorer .item { display: grid; grid-template-columns: 1fr 150px 100px 80px; align-items: center; gap: 10px; height: 34px; padding: 0 10px; }
+.explorer .head { color: #85857f; font-size: 12.5px; border-bottom: 1px solid #26272b; }
+.explorer .item { border-radius: 6px; color: #e2e2de; }
+.explorer .item:hover { background: #26272c; }
+.explorer .item.sel { background: #2e3240; }
+.explorer .item .n { display: flex; align-items: center; gap: 10px; white-space: nowrap; }
+.explorer .item img { width: 20px; height: 20px; }
+.explorer .item span:not(.n) { color: #9a9a95; font-size: 12.5px; }
+
+/* —— 安装向导 —— */
+.installer .head { height: 86px; display: flex; align-items: center; justify-content: space-between; padding: 0 26px; background: #232428; border-bottom: 1px solid #111; }
+.installer .head b { display: block; font-size: 16px; font-weight: 600; color: #f0f0ec; }
+.installer .head span { font-size: 13px; color: #9a9a95; }
+.installer .head img { width: 46px; height: 46px; }
+.installer .pg { flex: 1; padding: 26px 30px; font-size: 14px; color: #d4d4cf; display: none; }
+.installer .pg.on { display: block; }
+.installer .radio { display: flex; align-items: center; gap: 10px; margin: 14px 0 0 6px; }
+.installer .radio i { width: 16px; height: 16px; border-radius: 50%; border: 2px solid #77777a; }
+.installer .radio.on i { border-color: #d7ff00; box-shadow: inset 0 0 0 3px #1c1d20; background: #d7ff00; }
+.installer .path { display: flex; gap: 10px; margin-top: 18px; }
+.installer .path div { flex: 1; height: 32px; display: flex; align-items: center; padding: 0 10px; border-radius: 6px; background: #141517; border: 1px solid #34353a; font-size: 13px; color: #d8d8d3; white-space: nowrap; overflow: hidden; }
+.installer .path span { height: 32px; display: grid; place-items: center; padding: 0 14px; border-radius: 6px; background: #2c2d32; font-size: 13px; }
+.installer .hint { margin-top: 14px; color: #8e8e89; font-size: 12.5px; }
+.installer .prog { height: 10px; margin-top: 22px; border-radius: 5px; background: #141517; overflow: hidden; box-shadow: inset 0 0 0 1px #34353a; }
+.installer .prog i { display: block; height: 100%; width: 0; background: #d7ff00; border-radius: 5px; }
+.installer .file { margin-top: 10px; color: #8e8e89; font-size: 12.5px; font-family: "DejaVu Sans Mono", monospace; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.installer .check { display: flex; align-items: center; gap: 10px; margin-top: 22px; }
+.installer .check i { width: 16px; height: 16px; border-radius: 4px; background: #d7ff00; display: grid; place-items: center; }
+.installer .foot { height: 58px; display: flex; align-items: center; justify-content: flex-end; gap: 10px; padding: 0 20px; background: #202125; border-top: 1px solid #111; }
+.installer .foot .b { min-width: 96px; height: 32px; display: grid; place-items: center; padding: 0 16px; border-radius: 6px; background: #2c2d32; font-size: 13.5px; color: #e0e0dc; }
+.installer .foot .b.dis { color: #5f5f5b; }
+.installer .foot .b.primary { background: #d7ff00; color: #161a00; font-weight: 600; }
+.installer .foot .b.primary:hover { background: #e3ff4d; }
+
+/* —— 桌面图标 —— */
+.icon { position: absolute; width: 96px; display: grid; justify-items: center; gap: 6px; padding: 8px 4px; border-radius: 8px; color: #f2f2ee; font-size: 13px; text-align: center; text-shadow: 0 1px 3px rgba(0, 0, 0, .8); }
+.icon.enter { animation: win-in .3s cubic-bezier(.2, .8, .2, 1); }
+.icon .folder { width: 52px; height: 42px; border-radius: 5px; background: linear-gradient(#e9c46a, #d4a73c); position: relative; }
+.icon .folder::before { content: ""; position: absolute; left: 0; top: -6px; width: 22px; height: 10px; border-radius: 4px 4px 0 0; background: #d4a73c; }
+.icon .doc { width: 40px; height: 50px; border-radius: 4px; background: #f4f4f0; position: relative; box-shadow: 0 1px 2px rgba(0, 0, 0, .3); }
+.icon .doc::after { content: ""; position: absolute; left: 8px; right: 8px; top: 14px; height: 18px; background: repeating-linear-gradient(#a7a7a2 0 2px, transparent 2px 6px); }
+
+/* —— 文本编辑器(记事本)—— */
+.notepad .menu { height: 30px; display: flex; gap: 18px; align-items: center; padding: 0 14px; background: #202125; color: #b8b8b3; font-size: 13px; border-bottom: 1px solid #111; }
+.notepad .text { flex: 1; padding: 14px 16px; background: #161719; color: #ecece8; font: 18px/1.6 "DejaVu Sans Mono", "Noto Sans SC", monospace; white-space: pre-wrap; }
+.notepad .caret { display: inline-block; width: 2px; height: 1.15em; margin-left: 1px; vertical-align: -.2em; background: #ecece8; }
+.notepad .status { height: 28px; display: flex; gap: 22px; align-items: center; justify-content: flex-end; padding: 0 14px; background: #202125; color: #8e8e89; font-size: 12px; border-top: 1px solid #111; }
+.notepad .dlg { position: absolute; left: 50%; top: 46%; width: 400px; transform: translate(-50%, -50%); border-radius: 10px; background: #26272b; box-shadow: 0 0 0 1px rgba(255, 255, 255, .1), 0 18px 40px rgba(0, 0, 0, .6); overflow: hidden; }
+.notepad .dlg .dh { height: 34px; display: flex; align-items: center; padding: 0 14px; background: #2e2f34; font-size: 13px; color: #d0d0cb; }
+.notepad .dlg .db { padding: 16px 18px 6px; display: grid; gap: 12px; font-size: 13.5px; color: #c9c9c4; }
+.notepad .dlg .row2 { display: grid; grid-template-columns: 72px 1fr; align-items: center; gap: 10px; }
+.notepad .dlg .fld { height: 30px; display: flex; align-items: center; padding: 0 10px; border-radius: 6px; background: #17181b; border: 1px solid #3a3b40; color: #ecece8; }
+.notepad .dlg .df { display: flex; justify-content: flex-end; gap: 10px; padding: 12px 18px 16px; }
+.notepad .dlg .df span { min-width: 80px; height: 30px; display: grid; place-items: center; border-radius: 6px; background: #34353a; font-size: 13px; }
+.notepad .dlg .df span.primary { background: #d7ff00; color: #161a00; font-weight: 600; }
+
+/* —— 看图窗口(示意)—— */
+.viewer .img { flex: 1; display: grid; place-items: center; background: #111214; }
+.viewer .img img { width: 100%; height: 100%; object-fit: contain; display: block; }
+.viewer .vbar { height: 34px; display: flex; align-items: center; justify-content: space-between; padding: 0 14px; background: #202125; color: #8e8e89; font-size: 12.5px; border-top: 1px solid #111; }
+
+/* —— 手机聊天(通用示意,不仿任何即时通讯产品)—— */
+.phone-area { position: absolute; background: #000; display: grid; place-items: center; }
+.phone { position: relative; width: 372px; height: 808px; border-radius: 52px; background: #0b0b0c; box-shadow: 0 0 0 2px #2c2c2f, 0 0 0 9px #141416; padding: 14px; }
+.phone .scr { position: relative; height: 100%; border-radius: 40px; overflow: hidden; background: #121316; display: flex; flex-direction: column; }
+.phone .sb { height: 44px; flex: none; display: flex; align-items: center; justify-content: space-between; padding: 6px 28px 0 30px; font-size: 15px; font-weight: 600; color: #f2f2ee; }
+.phone .sb .ic { display: flex; gap: 6px; align-items: center; }
+.phone .sb .ic i { display: block; background: #f2f2ee; border-radius: 2px; }
+.phone .hd { height: 52px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 16px; border-bottom: 1px solid #222327; color: #f2f2ee; }
+.phone .hd .back { width: 10px; height: 10px; border-left: 2.5px solid #d6d6d2; border-bottom: 2.5px solid #d6d6d2; transform: rotate(45deg); margin-right: 6px; }
+.phone .hd b { flex: 1; text-align: center; font-size: 17px; font-weight: 600; margin-right: 22px; }
+.phone .msgs { flex: 1; min-height: 0; padding: 14px 12px; display: flex; flex-direction: column; gap: 14px; overflow: hidden; }
+.phone .stamp { align-self: center; padding: 2px 10px; border-radius: 6px; color: #8a8a86; font-size: 12.5px; }
+.phone .m { display: flex; gap: 9px; align-items: flex-start; animation: pop .22s ease-out; }
+.phone .m.me { flex-direction: row-reverse; }
+.phone .m .av { flex: none; width: 38px; height: 38px; border-radius: 8px; background: #3a3b40; display: grid; place-items: center; }
+.phone .m .av::before { content: ""; width: 16px; height: 16px; border-radius: 50%; background: #6f7076; box-shadow: 0 13px 0 4px #6f7076; transform: translateY(-4px); }
+.phone .m .av { overflow: hidden; }
+.phone .m .bb { max-width: 238px; padding: 9px 13px; border-radius: 12px; background: #26272c; color: #ecece8; font-size: 16px; line-height: 1.5; }
+.phone .m.me .bb { background: #3a6ff0; color: #fff; }
+@keyframes pop { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
+.phone .typing { align-self: flex-start; margin-left: 47px; padding: 10px 14px; border-radius: 12px; background: #26272c; display: flex; gap: 5px; }
+.phone .typing i { width: 7px; height: 7px; border-radius: 50%; background: #8a8a86; animation: dot 1s infinite; }
+.phone .typing i:nth-child(2) { animation-delay: .15s; }
+.phone .typing i:nth-child(3) { animation-delay: .3s; }
+@keyframes dot { 0%, 60%, 100% { opacity: .35; } 30% { opacity: 1; } }
+.phone .in { flex: none; display: flex; align-items: center; gap: 10px; padding: 10px 12px 30px; background: #18191c; border-top: 1px solid #222327; }
+.phone .in .f { flex: 1; min-height: 40px; display: flex; align-items: center; padding: 0 12px; border-radius: 10px; background: #26272c; color: #ecece8; font-size: 16px; }
+.phone .in .f.ph { color: #77777a; }
+.phone .in .f .caret { display: inline-block; width: 2px; height: 20px; margin-left: 1px; background: #3a6ff0; }
+.phone .in .send { width: 62px; height: 38px; border-radius: 10px; display: grid; place-items: center; background: #2f3036; color: #77777a; font-size: 15px; font-weight: 600; }
+.phone .in .send.on { background: #3a6ff0; color: #fff; }
+.phone .hb { position: absolute; left: 50%; bottom: 9px; width: 130px; height: 5px; margin-left: -65px; border-radius: 3px; background: #e8e8e6; }
diff --git a/docs/assets/_src/record/stage/stage.js b/docs/assets/_src/record/stage/stage.js
new file mode 100644
index 0000000..51ebcd3
--- /dev/null
+++ b/docs/assets/_src/record/stage/stage.js
@@ -0,0 +1,272 @@
+// 录制舞台:record.mjs 用 page.evaluate 调这里的 window.stage.*,按脚本的时间点摆出各个窗口。
+// 真实的应用界面在 iframe(同源)里;其余窗口都是风格化示意。假鼠标由 __cursor() 驱动:
+// record.mjs 在每个 frame 注入的脚本把 mousemove / mousedown / mouseup 换算成舞台坐标后转给它。
+(() => {
+ const screen = document.getElementById("screen");
+ const cursor = document.getElementById("cursor");
+ const touch = document.getElementById("touch");
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+ const el = (html) => {
+ const t = document.createElement("template");
+ t.innerHTML = html.trim();
+ return t.content.firstElementChild;
+ };
+ const APP_ICON = "/__repo-assets/icon.png";
+ const WB = `<span class="wb"><svg viewBox="0 0 10 10"><path d="M1 5h8" stroke="currentColor" stroke-width="1.2"/></svg></span>
+ <span class="wb"><svg viewBox="0 0 10 10"><rect x="1.5" y="1.5" width="7" height="7" fill="none" stroke="currentColor" stroke-width="1.2"/></svg></span>
+ <span class="wb"><svg viewBox="0 0 10 10"><path d="M1.5 1.5l7 7M8.5 1.5l-7 7" stroke="currentColor" stroke-width="1.2"/></svg></span>`;
+ const titlebar = (title, icon = "") => `<div class="titlebar">${icon ? `<img src="${icon}" alt="">` : ""}<span class="t">${title}</span>${WB}</div>`;
+ const place = (node, r) => Object.assign(node.style, { left: r.x + "px", top: r.y + "px", width: r.w + "px", height: r.h + "px" });
+
+ // —— 假鼠标 ——
+ let down = false;
+ window.__cursor = (type, x, y) => {
+ cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
+ cursor.classList.add("on");
+ if (type === "mousedown") {
+ down = true;
+ cursor.classList.add("down");
+ cursor.classList.remove("click");
+ void cursor.offsetWidth;
+ cursor.classList.add("click");
+ } else if (type === "mouseup" && down) {
+ down = false;
+ cursor.classList.remove("down");
+ }
+ };
+
+ const stage = {
+ sleep,
+ /** 背景:wallpaper(桌面)| black(黑底,G9 左侧留边)| none */
+ init({ background = "none" } = {}) {
+ screen.innerHTML = "";
+ if (background === "wallpaper") screen.append(el(`<div class="wallpaper"></div>`));
+ if (background === "black") screen.append(el(`<div class="blackout"></div>`));
+ },
+ hideCursor: () => cursor.classList.remove("on"),
+ /** 手机上的点按反馈 */
+ tap(x, y) {
+ Object.assign(touch.style, { left: x + "px", top: y + "px" });
+ touch.classList.remove("tap");
+ void touch.offsetWidth;
+ touch.classList.add("tap");
+ },
+
+ /** 应用窗口:rect 是内容区(iframe)的位置和大小;title 时上面加一条 34px 的示意标题栏 */
+ async openApp({ src = "/", rect, title = false, enter = false }) {
+ const h = rect.h + (title ? 34 : 0);
+ const w = el(`<div class="win app-win${title ? "" : " plain"}${enter ? " enter" : ""}" id="app-win">${title ? titlebar("AnyModelBot", APP_ICON) : ""}<div class="win-body"></div></div>`);
+ place(w, { x: rect.x, y: rect.y - (title ? 34 : 0), w: rect.w, h });
+ const f = document.createElement("iframe");
+ f.id = "app";
+ f.name = "app";
+ Object.assign(f, { width: rect.w, height: rect.h });
+ Object.assign(f.style, { width: rect.w + "px", height: rect.h + "px" });
+ w.querySelector(".win-body").append(f);
+ screen.append(w);
+ await new Promise((r) => {
+ f.onload = r;
+ f.src = src;
+ });
+ },
+
+ // —— 浏览器里的 Modelflare 授权页(G1、G6)——
+ browser: {
+ show(rect, { loading = 0 } = {}) {
+ const b = el(`<div class="win browser enter" id="browser">
+ <div class="tabs"><div class="tab"><i></i>授权 AnyModelBot</div></div>
+ <div class="bar"><span class="nav">‹ › ↻</span><div class="addr"><svg width="12" height="14" viewBox="0 0 12 14"><rect x="1" y="6" width="10" height="7" rx="1.5" fill="#9a9a95"/><path d="M3 6V4a3 3 0 0 1 6 0v2" fill="none" stroke="#9a9a95" stroke-width="1.6"/></svg><span><b>modelflare.dev</b>/oauth/authorize?client_id=anymodelbot&amp;response_type=code</span></div></div>
+ <div class="page${loading ? " loading" : ""}">
+ <div class="auth-card">
+ <div class="marks"><img src="/__docs/brand/logo-eyes.svg" alt=""><span class="dots">• • •</span><span class="mf">M</span></div>
+ <h1>AnyModelBot 想连接你的 Modelflare 账户</h1>
+ <div class="who">登录身份:演示账户</div>
+ <ul><li>读取账户名称和钱包余额</li><li>为这台电脑签发一把 API Key</li><li>可以随时在 Modelflare 网页上撤销</li></ul>
+ <div class="btns"><button class="btn-s primary" id="auth-ok">继续</button><button class="btn-s ghost">取消</button></div>
+ </div>
+ <div class="auth-done"><div class="ok"><svg width="26" height="26" viewBox="0 0 26 26"><path d="M6 13.5l4.5 4.5L20 8" fill="none" stroke="#d7ff00" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></svg></div>
+ <h2>已连接</h2><p>可以回到 AnyModelBot 了,这个页面可以关掉。</p></div>
+ </div></div>`);
+ place(b, rect);
+ screen.append(b);
+ if (loading) setTimeout(() => b.querySelector(".page").classList.remove("loading"), loading);
+ },
+ done: () => document.getElementById("browser")?.classList.add("done"),
+ async hide() {
+ const b = document.getElementById("browser");
+ if (!b) return;
+ b.classList.add("leave");
+ await sleep(190);
+ b.remove();
+ },
+ },
+
+ // —— 下载文件夹(G2)——
+ explorer: {
+ show(rect, file) {
+ const w = el(`<div class="win explorer" id="explorer">${titlebar("下载")}
+ <div class="tool"><span>‹ ›</span><div class="crumb">此电脑 › 下载</div></div>
+ <div class="body"><nav><div><i></i>桌面</div><div class="on"><i></i>下载</div><div><i></i>文档</div><div><i></i>图片</div></nav>
+ <div class="list"><div class="head"><span>名称</span><span>修改日期</span><span>类型</span><span>大小</span></div>
+ <div class="item" id="exe"><span class="n"><img src="${APP_ICON}" alt="">${file.name}</span><span>${file.date}</span><span>应用程序</span><span>${file.size}</span></div>
+ </div></div></div>`);
+ place(w, rect);
+ screen.append(w);
+ },
+ select: () => document.getElementById("exe")?.classList.add("sel"),
+ },
+
+ // —— 安装向导(G2):选项 → 位置 → 进度 → 完成 ——
+ installer: {
+ show(rect) {
+ const w = el(`<div class="win installer enter" id="installer">${titlebar("anymodel bot 安装")}
+ <div class="head"><div><b id="ins-title">安装选项</b><span id="ins-sub">为这台电脑上的哪些用户安装?</span></div><img src="${APP_ICON}" alt=""></div>
+ <div class="pg on" data-p="1"><div>请选择要为哪些用户安装 anymodel bot:</div>
+ <div class="radio"><i></i>为使用这台电脑的任何人安装</div><div class="radio on"><i></i>仅为我安装(demo)</div>
+ <div class="hint">仅为你安装时不需要管理员权限。</div></div>
+ <div class="pg" data-p="2"><div>安装程序会把 anymodel bot 安装到下面的文件夹。</div>
+ <div class="path"><div>C:\\Users\\demo\\AppData\\Local\\Programs\\anymodel bot</div><span>浏览…</span></div>
+ <div class="hint">所需空间:612 MB</div></div>
+ <div class="pg" data-p="3"><div>正在安装,请稍候…</div><div class="prog"><i id="ins-bar"></i></div><div class="file" id="ins-file">解压:resources\\app.asar</div></div>
+ <div class="pg" data-p="4"><div>anymodel bot 已经安装到你的电脑上。</div><div class="check"><i><svg width="10" height="10" viewBox="0 0 10 10"><path d="M2 5.2l2 2L8 3" fill="none" stroke="#161a00" stroke-width="1.8"/></svg></i>运行 anymodel bot</div></div>
+ <div class="foot"><span class="b dis" id="ins-back">上一步</span><span class="b primary" id="ins-next">下一步</span><span class="b" id="ins-cancel">取消</span></div></div>`);
+ place(w, rect);
+ screen.append(w);
+ },
+ page(n) {
+ const w = document.getElementById("installer");
+ w.querySelectorAll(".pg").forEach((p) => p.classList.toggle("on", p.dataset.p === String(n)));
+ const T = { 1: ["安装选项", "为这台电脑上的哪些用户安装?"], 2: ["选择安装位置", "选择 anymodel bot 的安装文件夹。"], 3: ["正在安装", "正在安装 anymodel bot。"], 4: ["安装完成", "anymodel bot 已安装完成。"] }[n];
+ w.querySelector("#ins-title").textContent = T[0];
+ w.querySelector("#ins-sub").textContent = T[1];
+ const next = w.querySelector("#ins-next");
+ next.textContent = { 1: "下一步", 2: "安装", 3: "下一步", 4: "完成" }[n];
+ next.classList.toggle("dis", n === 3);
+ next.classList.toggle("primary", n !== 3);
+ w.querySelector("#ins-back").classList.toggle("dis", n !== 2);
+ w.querySelector("#ins-cancel").classList.toggle("dis", n >= 3);
+ },
+ /** 进度条在 ms 毫秒内走完,下面滚动显示正在解压的文件 */
+ async progress(ms) {
+ const bar = document.getElementById("ins-bar");
+ const file = document.getElementById("ins-file");
+ const files = ["resources\\app.asar", "resources\\dsh\\dsh.asar", "resources\\bin\\magpie.exe", "resources\\cua-driver\\cua-driver.exe", "locales\\zh-CN.pak", "anymodel bot.exe", "Uninstall anymodel bot.exe"];
+ const t0 = performance.now();
+ for (;;) {
+ const k = Math.min(1, (performance.now() - t0) / ms);
+ bar.style.width = (100 * (1 - Math.pow(1 - k, 1.6))).toFixed(1) + "%";
+ file.textContent = "解压:" + files[Math.min(files.length - 1, Math.floor(k * files.length))];
+ if (k >= 1) break;
+ await sleep(30);
+ }
+ },
+ async close() {
+ const w = document.getElementById("installer");
+ w.classList.add("leave");
+ await sleep(190);
+ w.remove();
+ },
+ },
+
+ // —— 桌面图标(G4)——
+ icon(id, kind, label, x, y, enter = false) {
+ const i = el(`<div class="icon${enter ? " enter" : ""}" id="${id}"><div class="${kind}"></div><span>${label}</span></div>`);
+ Object.assign(i.style, { left: x + "px", top: y + "px" });
+ screen.append(i);
+ },
+
+ // —— 文本编辑器(G4):打开、逐字输入、另存为 ——
+ notepad: {
+ open(rect) {
+ const w = el(`<div class="win notepad enter" id="notepad">${titlebar("无标题 - 记事本")}
+ <div class="menu"><span>文件</span><span>编辑</span><span>格式</span><span>查看</span></div>
+ <div class="text"><span id="np-text"></span><i class="caret"></i></div>
+ <div class="status"><span id="np-pos">第 1 行,第 1 列</span><span>100%</span><span>UTF-8</span></div></div>`);
+ place(w, rect);
+ screen.append(w);
+ },
+ async type(text, ms) {
+ const t = document.getElementById("np-text");
+ const pos = document.getElementById("np-pos");
+ const step = ms / text.length;
+ for (const ch of text) {
+ t.textContent += ch;
+ pos.textContent = `第 1 行,第 ${t.textContent.length + 1} 列`;
+ await sleep(step * (0.7 + Math.random() * 0.6));
+ }
+ },
+ /** 另存为:弹出对话框,逐字填文件名,确认后标题变成 name */
+ async saveAs(folder, name, ms) {
+ const w = document.getElementById("notepad");
+ const d = el(`<div class="dlg"><div class="dh">另存为</div><div class="db">
+ <div class="row2"><span>保存位置</span><div class="fld">${folder}</div></div>
+ <div class="row2"><span>文件名</span><div class="fld" id="np-name"></div></div>
+ <div class="row2"><span>编码</span><div class="fld">UTF-8</div></div></div>
+ <div class="df"><span class="primary">保存</span><span>取消</span></div></div>`);
+ w.append(d);
+ await sleep(ms * 0.25);
+ const f = d.querySelector("#np-name");
+ for (const ch of name) {
+ f.textContent += ch;
+ await sleep((ms * 0.5) / name.length);
+ }
+ await sleep(ms * 0.25);
+ d.remove();
+ w.querySelector(".titlebar .t").textContent = `${name} - 记事本`;
+ },
+ },
+
+ // —— 看图窗口(G5,示意)——
+ viewer: {
+ show(rect, { src, name, info }) {
+ const w = el(`<div class="win viewer enter" id="viewer">${titlebar(name)}<div class="img"><img src="${src}" alt=""></div><div class="vbar"><span>${info}</span><span>100%</span></div></div>`);
+ place(w, rect);
+ screen.append(w);
+ },
+ },
+
+ // —— 手机聊天(G9,示意)——
+ phone: {
+ show(rect, { title, clock }) {
+ const a = el(`<div class="phone-area" id="phone-area"><div class="phone"><div class="scr">
+ <div class="sb"><span>${clock}</span><span class="ic"><i style="width:17px;height:10px"></i><i style="width:24px;height:11px;border-radius:3px"></i></span></div>
+ <div class="hd"><span class="back"></span><b>${title}</b></div>
+ <div class="msgs" id="ph-msgs"><div class="stamp">${clock}</div></div>
+ <div class="in"><div class="f ph" id="ph-in">发消息</div><div class="send" id="ph-send">发送</div></div>
+ <div class="hb"></div></div></div></div>`);
+ place(a, rect);
+ screen.append(a);
+ },
+ async type(text, ms) {
+ const f = document.getElementById("ph-in");
+ f.classList.remove("ph");
+ f.innerHTML = `<span></span><i class="caret"></i>`;
+ const s = f.firstChild;
+ for (const ch of text) {
+ s.textContent += ch;
+ await sleep((ms / text.length) * (0.7 + Math.random() * 0.6));
+ }
+ document.getElementById("ph-send").classList.add("on");
+ },
+ send() {
+ const f = document.getElementById("ph-in");
+ const text = f.textContent;
+ f.className = "f ph";
+ f.textContent = "发消息";
+ document.getElementById("ph-send").classList.remove("on");
+ stage.phone.add("me", text);
+ },
+ add(who, text) {
+ document.getElementById("ph-typing")?.remove();
+ const m = el(`<div class="m ${who}"><span class="av"></span><div class="bb"></div></div>`);
+ m.querySelector(".bb").textContent = text;
+ document.getElementById("ph-msgs").append(m);
+ },
+ /** 机器人正在输入(微信渠道会发"正在输入"状态) */
+ typing() {
+ if (!document.getElementById("ph-typing")) document.getElementById("ph-msgs").append(el(`<div class="typing" id="ph-typing"><i></i><i></i><i></i></div>`));
+ },
+ },
+ };
+ window.stage = stage;
+})();
diff --git a/docs/assets/download/install-windows.gif b/docs/assets/download/install-windows.gif
new file mode 100644
index 0000000..733cee5
Binary files /dev/null and b/docs/assets/download/install-windows.gif differ
diff --git a/docs/assets/features/agent-files.gif b/docs/assets/features/agent-files.gif
new file mode 100644
index 0000000..d77a327
Binary files /dev/null and b/docs/assets/features/agent-files.gif differ
diff --git a/docs/assets/features/channels-wechat.gif b/docs/assets/features/channels-wechat.gif
new file mode 100644
index 0000000..a8cb1be
Binary files /dev/null and b/docs/assets/features/channels-wechat.gif differ
diff --git a/docs/assets/features/computer-use.gif b/docs/assets/features/computer-use.gif
new file mode 100644
index 0000000..93d8eda
Binary files /dev/null and b/docs/assets/features/computer-use.gif differ
diff --git a/docs/assets/features/first-run.gif b/docs/assets/features/first-run.gif
new file mode 100644
index 0000000..fcd157e
Binary files /dev/null and b/docs/assets/features/first-run.gif differ
diff --git a/docs/assets/features/media-generation.gif b/docs/assets/features/media-generation.gif
new file mode 100644
index 0000000..df3d72b
Binary files /dev/null and b/docs/assets/features/media-generation.gif differ
diff --git a/docs/assets/features/memory.gif b/docs/assets/features/memory.gif
new file mode 100644
index 0000000..fb2ca16
Binary files /dev/null and b/docs/assets/features/memory.gif differ
diff --git a/docs/assets/features/model-switch.gif b/docs/assets/features/model-switch.gif
new file mode 100644
index 0000000..133e8b6
Binary files /dev/null and b/docs/assets/features/model-switch.gif differ
diff --git a/docs/assets/hero/hero-demo.gif b/docs/assets/hero/hero-demo.gif
new file mode 100644
index 0000000..f9904f8
Binary files /dev/null and b/docs/assets/hero/hero-demo.gif differ
diff --git a/docs/assets/screenshots/agent-dark.webp b/docs/assets/screenshots/agent-dark.webp
new file mode 100644
index 0000000..16d93a5
Binary files /dev/null and b/docs/assets/screenshots/agent-dark.webp differ
diff --git a/docs/assets/screenshots/agent-light.webp b/docs/assets/screenshots/agent-light.webp
new file mode 100644
index 0000000..84a1d77
Binary files /dev/null and b/docs/assets/screenshots/agent-light.webp differ
diff --git a/docs/assets/screenshots/chat-dark.webp b/docs/assets/screenshots/chat-dark.webp
new file mode 100644
index 0000000..e1c5afe
Binary files /dev/null and b/docs/assets/screenshots/chat-dark.webp differ
diff --git a/docs/assets/screenshots/chat-light.webp b/docs/assets/screenshots/chat-light.webp
new file mode 100644
index 0000000..db0fb85
Binary files /dev/null and b/docs/assets/screenshots/chat-light.webp differ
diff --git a/docs/assets/screenshots/memory-dark.webp b/docs/assets/screenshots/memory-dark.webp
new file mode 100644
index 0000000..e33be51
Binary files /dev/null and b/docs/assets/screenshots/memory-dark.webp differ
diff --git a/docs/assets/screenshots/memory-light.webp b/docs/assets/screenshots/memory-light.webp
new file mode 100644
index 0000000..adb1ade
Binary files /dev/null and b/docs/assets/screenshots/memory-light.webp differ
diff --git a/docs/assets/screenshots/modelflare-dark.webp b/docs/assets/screenshots/modelflare-dark.webp
new file mode 100644
index 0000000..05cc55f
Binary files /dev/null and b/docs/assets/screenshots/modelflare-dark.webp differ
diff --git a/docs/assets/screenshots/modelflare-light.webp b/docs/assets/screenshots/modelflare-light.webp
new file mode 100644
index 0000000..b1fe20a
Binary files /dev/null and b/docs/assets/screenshots/modelflare-light.webp differ
diff --git a/docs/assets/screenshots/models-dark.webp b/docs/assets/screenshots/models-dark.webp
new file mode 100644
index 0000000..6b3cca5
Binary files /dev/null and b/docs/assets/screenshots/models-dark.webp differ
diff --git a/docs/assets/screenshots/models-light.webp b/docs/assets/screenshots/models-light.webp
new file mode 100644
index 0000000..e1cdf37
Binary files /dev/null and b/docs/assets/screenshots/models-light.webp differ