Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Add the record-browser-gif skill, adapted from DeepSeek Harness

klarkxyb3170411bbcd
diff --git a/.agents/skills/record-browser-gif/SKILL.md b/.agents/skills/record-browser-gif/SKILL.md
new file mode 100644
index 00000000..75cecd4f
--- /dev/null
+++ b/.agents/skills/record-browser-gif/SKILL.md
@@ -0,0 +1,174 @@
+---
+name: record-browser-gif
+description: 把浏览器 / Web 界面操作录成优化过的 GIF:优先用当前可用的浏览器控制工作流(支持 recordVideo 时开 Playwright Videos 拿更高帧率),用随附编码器裁剪、变速、收尾定格并控制尺寸与体积;需要挂到 PR 时用 gh --attach,不可用时退回专用 assets 分支。触发词:录 GIF、录屏、界面演示、PR 演示证据、截图。改了用户可见界面行为的 PR 按模板需要截图证据,用本 skill 从该 PR 分支的真实服务与真实模型流程录 GIF 即满足。
+---
+
+# 录制浏览器演示 GIF
+
+产出一段简短、真实的界面演示 GIF;仅当任务包含「挂到 PR」时,才走文末的发布流程。优先使用当前可用的浏览器控制工作流;该工作流支持连续录像时用 [Playwright Videos](https://playwright.dev/docs/videos) 拿更高帧率。裁剪、变速、收尾定格、尺寸和体积用随附编码器(`scripts/encode_gif.py`)。
+
+两条纪律来自 DeepSeek Harness 的同名 skill(出处见 `NOTICE`):一个 storyboard 只来自一次隔离运行;发布前要重新校验产物和被演示 PR 的头提交。
+
+## 界面改动的 PR 附演示 GIF
+
+改了用户可见界面行为的 PR,按 PR 模板需要附截图证据;用本 skill 录的 GIF 满足该要求,嵌进 PR 正文或作为评论附件均可(见[发布 GIF](#发布-gif))。
+
+录屏本身是证据的一部分:从该 PR 分支的代码树启动真实服务、用真实 API key、跑真实模型回合。不要用 fixture 查询、mock transport、合成事件注入或测试钩子替代,除非用户明确要求录 fixture。在 GIF 旁边注明被演示的确切 commit SHA、服务它的代码树与来源、模式开关或浏览器状态例外、是否跑了真实模型回合,让评审知道这段录像证明了什么。
+
+## 录制与发布分开
+
+- 录制只产出本地视频或截图和一个 `.gif`,绝不动远端状态。
+- 发布——用 `gh --attach` 把 GIF 挂到 PR,或不可用时推到 assets 分支并嵌入 URL——是独立的最后一步,仅当任务包含挂到 PR 时执行。它绝不动 PR 自己的分支。
+- 保持约定的录制条件。真实服务 / 真实 API 的演示不得换成 fixture 查询、mock transport、合成事件注入或测试钩子。凭证或服务不可用时如实报告,不要拿 fixture 顶替。
+- 绝不读取或暴露凭证值。走应用正常的配置路径,用无害的演示提示词。截图和录像里同样不能有密钥、token 或个人信息(PR 模板硬性要求)。
+
+## 搭建被演示的应用
+
+为某个 PR 录的 GIF 演示的是该 PR 的代码树,按 PR 搭建:
+
+1. 工作树必须干净,用 `git rev-parse HEAD` 记录确切提交,并构建这棵记录过的树:界面改动在 `ds-bot/` 里跑 `npm run build`(`src/client` → `client.js`)。拿别的提交的构建产物录屏是错误归因。
+2. 用测试台架从该树启动 DSH Web:`dev/bench.sh <name> <web-port> <mock-port> reset`(台架需要一个 deepseek-harness 检出:`../deepseek-harness` 或 `DSH_HARNESS`,版本见 README)。台架把插件 link 到当前 checkout——host 代码改动重启生效,`src/client` 改动 `npm run build` 后刷新页面生效;数据全部落在 gitignored 的 `.dsh-test-<name>/`,`reset` 会先清空 Bot 团队和会话。每个端口只起一个服务。浏览器同样用全新隔离的 context 或 profile;浏览器工作流建不了隔离环境时,先清掉该 origin 的 cookie 和站点存储再导航,避免残留的客户端状态污染证据。
+3. 台架默认跑 mock 模型(`dev/mock-llm.mjs`)。要录真实模型回合,在该台架自己的数据目录里配置真实 provider(通过它的 Web 设置页);绝不要把台架或任何测试指向 `~/.dsh`、桌面应用的数据或用户正在跑的 DSH(仓库硬规则第 5 条)。演示桌面应用窗口(`app/ui` 或 Electron 行为)时改在 `app/` 里用一次性数据目录启动:`DS_BOT_HOME=<throwaway-dir> npm start`(见 `app/README.md`)。
+4. 一个 storyboard 算一次证据运行:发布的每一帧都来自同一个服务、同一组状态根、同一个工作区 / 会话和同一次模型场景运行。采集自动化失败就丢弃它的帧、从全新状态根重跑;绝不拼接不同运行的帧。
+5. 录制结束或切换 PR 时停掉自己起的服务:`dev/bench.sh <name> <web-port> <mock-port> stop`(台架按 pid 文件停进程组)。不要用宽泛的 `pkill -f`——它可能匹配并杀掉发起它的 shell,包括你自己的。
+
+## 录制流程
+
+遵循当前可用的浏览器控制工作流的设置、交互和清理说明。它暴露 `recordVideo` 时,在同一个受控 context 上开录像以捕获更多中间帧;否则在该工作流里用[截图采集](#截图采集)。录像是否可用不决定用哪个浏览器控制工作流。用户既有浏览器状态算显式的隔离例外。
+
+仅当浏览器控制不可用时,才在隔离的无头浏览器里用 Playwright 兜底,并在采集说明里声明用了兜底。本仓库没有声明 Playwright 依赖——从环境里已有的 Playwright 安装解析(如 agent 自带的 CLI / MCP),不要为了录屏往仓库加依赖,也不要打开用户的浏览器。
+
+录制前确认 origin、构建产物或开发服务器、传输方式和模式开关。当生产默认打开自动化无法驱动的原生界面时,通过正常的应用配置选择官方可在浏览器操作的生产后端,并披露该替代。
+
+把脚本、原始视频、计时笔记、QA 帧和 GIF 放在仓库已 gitignore 的 `.playwright-mcp/` 目录下。先建运行目录。
+
+### 采集视频
+
+显式让 `viewport` 和 `recordVideo.size` 一致:否则 Playwright 会把视频缩进 800×800,界面文字会糊。
+
+视频通过所选浏览器控制工作流配置。独立 Playwright 兜底用:
+
+```js
+import { chromium } from 'playwright' // 从环境解析;本仓库不带这个依赖
+const browser = await chromium.launch()
+const size = { width: 1440, height: 900 }
+const context = await browser.newContext({
+ viewport: size,
+ recordVideo: { dir: join(runDir, 'videos'), size },
+})
+try {
+ const page = await context.newPage()
+ const video = page.video()
+ // 在这里导航并操作真实应用。
+ await context.close()
+ await video.saveAs(join(runDir, 'demo.webm'))
+} finally {
+ await context.close()
+ await browser.close()
+}
+```
+
+`join` 从 `node:path` 导入;新建的 `runDir` 在录制脚本里写绝对路径。关掉页面前先留住它的 video 句柄;先 `await context.close()` 再 `video.saveAs()` 或编码——只关 browser 不保证视频落盘。每个 page 有自己的视频:明确选择被演示的 page,不串接无关 page 或运行。失败的运行只用于诊断。
+
+挑一个有三到六个有意义状态的短故事。操作前等唯一的语义定位器;accessible-name 相等判断用 `exact: true`,结束断言用不会误匹配 prompt 回显的精确文本。固定等待只能用于状态确认后的阅读停留,绝不能用来建立就绪。录像时保留动画和滚动。
+
+演示工具调用、拒绝或恢复时,展开它的详情或轨迹,让视频呈现工具身份、状态或稳定错误码和下游结果。瞬时运行态重要时,用一个慢前台操作触发并观察它的具体 DOM 标记;连续录像会捕获中间帧。给模型一个简短的收尾哨兵来锚定完成。真实 API 运行在被演示状态可见后即可停止,不必跑完全程。
+
+不要拍到密钥、个人数据、无关标签页或通知。浏览器视频只含页面内容、不含浏览器外壳;避免在应用里渲染带凭证的 URL。完整回看选中的区间,包括中间状态。全程保持一个 viewport。
+
+## 编码 GIF
+
+需要 `python3`、`ffmpeg`、`ffprobe`。缺媒体二进制时如实报告依赖,不要未经授权安装软件。`GIF_SKILL_DIR` 单独一行 export;同一命令里的内联赋值影响不了参数展开。
+
+```sh
+export GIF_SKILL_DIR=<repo>/.agents/skills/record-browser-gif
+python3 "$GIF_SKILL_DIR/scripts/encode_gif.py" \
+ /absolute/path/to/demo.webm \
+ /absolute/path/to/demo.gif \
+ --start 2 --end 32 --speed 2 --final-hold 3 \
+ --fps 10 --max-width 1200 --colors 128
+```
+
+`--start` 和 `--end` 以秒选一段连续的源区间。默认保留完整视频、1× 速度、加两秒收尾定格。`--speed` 改播放速度;在 GIF 旁边披露它及所选区间,避免演示暗示实测的响应延迟。用视频里观察到的时间,不要猜墙钟偏移;保留被演示行为完整的因与果。收尾定格重复最后一帧。`--fps` 是编码帧率;提高它补不回源录像没采到的运动。原始 WebM 留作 QA;不拼接不同运行,不合成缺失状态。
+
+编码器探测 WebM 容器时长,先裁剪变速再做调色板转换,并校验编码后的时长、动画、宽度和字节数。它会拒绝空区间或越界区间、不足两个输出帧的选择、模式不符的开关和意外覆盖。产物太大时先降 `--max-width`,再降 `--colors` 或 `--fps`;保持文字可读。确认输出路径无误后才用 `--force`。
+
+### 截图采集
+
+连续录像不可用、或用户要 storyboard 时,遵循可用的浏览器控制工作流,用浏览器的截图 API 从一次隔离运行采集三到六个已验证状态。返回的图像字节直接存进同一个运行目录:`00-initial.png`、`01-typed.png`……尺寸和裁剪保持一致。瞬时状态轮询它的 DOM 标记,并在同一次浏览器脚本调用内截图。
+
+```sh
+python3 "$GIF_SKILL_DIR/scripts/encode_gif.py" \
+ /absolute/path/to/frames /absolute/path/to/demo.gif \
+ --durations 1.5,1.5,1.5,3.5 --fps 10 --max-width 1200 --colors 128
+```
+
+一个时长作用于每张截图;否则给每帧一个正时长,并让落定状态停最久。目录输入拒绝少于两帧、尺寸不一致或时长数量不符。视频计时开关只适用于视频文件;`--durations` 和 `--pattern` 只适用于截图目录。
+
+## 校验产物
+
+1. 读编码器的 JSON 摘要,确认输出路径、源区间与速度(或截图张数)、编码帧数、尺寸、时长和字节数。
+2. 亲自看编码后的 GIF 本身,不只看源帧。确认过渡清晰可读、最后状态停得够久、没有敏感内容。查看器只渲染第一帧时,用 `ffmpeg` 从 GIF 解出代表帧检查;编码前的截图证明不了编码后的顺序、调色板或收尾定格。
+3. 跑 `git status --short`,确认原始视频、QA 帧和产物只落在 ignored 路径下。
+4. 返回 GIF 的绝对路径,客户端支持本地媒体就渲染出来,并说明录制用的是真实 API、fixture 还是别的 transport。任务不含挂到 PR 时到此为止。
+
+编码器维护:装好媒体依赖后跑 `python3 -m unittest discover -s "$GIF_SKILL_DIR/scripts" -p 'test_*.py' -v`。这些本地媒体测试不进仓库 CI。
+
+## 发布 GIF
+
+仅当任务包含把 GIF 挂到 PR 时执行本节。
+
+绝不把 GIF 提交进 PR 自己的分支或任何会合入长期分支的分支:二进制媒体进了历史会拖累未来的每一次克隆。优先 `gh --attach`——上传 GIF 到 GitHub 并在同一条命令里改写正文引用,任何分支都不用携带媒体。
+
+### 用 gh 挂附件
+
+`gh --attach` 需要 gh v2.99.0 或更新(`gh --version`)、github.com 上的仓库(不支持 GitHub Enterprise Server)、对仓库的写权限、不超过 10 MB 的 GIF。先确认校验过的产物在限内;超出就先按上文压缩再挂。
+
+把 GIF 作为普通的本地路径引用写进正文文件,路径与传给 `--attach` 的相同;`gh` 会原位把引用改写成上传后的 URL,保留位置和 alt 文本:
+
+```markdown
+![<alt 文本>](<path/to/demo.gif>)
+```
+
+被演示的 PR 通常就是发布目标。工具类 PR 也可以嵌入明确标注来自另一个 PR 的示例:指出该来源 PR,并在下面每个检查里比对它的实时头。绝不要把示例归到工具分支头上。
+
+挂上前一刻,重读被演示 PR 的实时头——新 PR 是已推送分支的尖端——与 GIF 旁记录的提交比对。动了就停下来重录。然后挂上:
+
+```sh
+gh pr create --body-file <body.md> --attach <path/to/demo.gif> # 新 PR
+gh pr edit <pr> --body-file <body.md> --attach <path/to/demo.gif> # 已有 PR 正文
+gh pr comment <pr> --body <text> --attach <path/to/demo.gif> # 只挂到评论
+```
+
+`--attach` 可重复,但拒绝同一个文件两次。正文没引用的 GIF 会追加到末尾,此时开关上的 alt 文本(`--attach '<path>#<alt 文本>'`)生效;被改写的引用保留正文里的 alt 文本。挂上后:重读实时头,确认仍在记录的提交;重读线上正文,确认引用指向上传后的 URL;用 GitHub 的 Markdown API 渲染正文,确认出现预期的 `<img>`;请求一次上传 URL,确认 `200` 和 `image/gif`。
+
+### 退回 assets 分支
+
+仅在 `gh --attach` 不可用时走 assets 分支:GIF 仍超 10 MB、gh 低于 v2.99.0、或仓库不在 github.com。GIF 放在专用的孤儿 assets 分支——没有父提交、只有媒体——一个 assets 分支服务整个 PR 系列(命名 `<series>-assets`;用 `git ls-remote --heads origin '*assets*'` 列出现有的)。
+
+两种流程推送前都要验证:assets 分支只有媒体,且待挂 GIF 的校验和与本地校验过的产物一致。
+
+已有 assets 分支时,在浅克隆单分支的临时 checkout 里操作,发布过程碰不到你的工作树:
+
+```sh
+git clone --branch <assets-branch> --single-branch --depth 1 <repo-url> /tmp/assets-checkout
+cp /absolute/path/to/demo.gif /tmp/assets-checkout/<name>.gif
+cd /tmp/assets-checkout
+git add <name>.gif
+git commit -m "assets: <what it shows> gif (#<pr>)"
+git push origin <assets-branch>
+```
+
+新系列则浅克隆临时 checkout(`git clone --depth 1 <repo-url> /tmp/assets-checkout`),用 `git switch --orphan <assets-branch>` 建孤儿分支,然后同样 add、commit、push。
+
+推送后用带认证的 GitHub API 或 raw 请求确认远端路径、字节数、校验和、`200` 响应和 `image/gif` 类型。匿名 `404` 不能证伪私有仓库的资产;用认证请求验证。这证明的是仓库成员的评审路径,不是公网可达。
+
+编辑 PR 正文前一刻,重读被演示 PR 的实时头并与 GIF 旁记录的提交比对;动了就停下来重录。编辑后重读实时头,确认仍在该提交。另外用 GitHub 的 Markdown API 渲染正文,确认预期的 `<img>` 出现。
+
+用 raw blob URL 把 GIF 嵌进 PR 正文;`?raw=true` 后缀必须带,普通 blob URL 渲染的是 GitHub 的文件页而不是图:
+
+```markdown
+![<alt 文本>](https://github.com/<owner>/<repo>/blob/<assets-branch>/<name>.gif?raw=true)
+```
+
+绝不删除或改写 assets 分支,绝不 force-push:已合并 PR 的正文永远引用它的 URL。只追加新提交。
diff --git a/.agents/skills/record-browser-gif/scripts/encode_gif.py b/.agents/skills/record-browser-gif/scripts/encode_gif.py
new file mode 100644
index 00000000..cfda42cc
--- /dev/null
+++ b/.agents/skills/record-browser-gif/scripts/encode_gif.py
@@ -0,0 +1,337 @@
+#!/usr/bin/env python3
+"""Encode a Playwright video or ordered browser screenshots into a verified GIF."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import NoReturn
+
+
+DEFAULT_MAX_BYTES = 5 * 1024 * 1024
+
+
+def fail(message: str) -> NoReturn:
+ """Exit with a concise user-correctable error."""
+ raise SystemExit(f"error: {message}")
+
+
+def positive_float(value: str) -> float:
+ """Parse one finite positive command-line number."""
+ try:
+ parsed = float(value)
+ except ValueError:
+ fail(f"expected a number, got {value!r}")
+ if not math.isfinite(parsed) or parsed <= 0:
+ fail(f"expected a positive finite number, got {value!r}")
+ return parsed
+
+
+def positive_int(value: str) -> int:
+ """Parse one positive command-line integer."""
+ try:
+ parsed = int(value)
+ except ValueError:
+ fail(f"expected an integer, got {value!r}")
+ if parsed <= 0:
+ fail(f"expected a positive integer, got {value!r}")
+ return parsed
+
+
+def nonnegative_float(value: str) -> float:
+ """Parse a finite nonnegative timestamp or hold duration."""
+ try:
+ parsed = float(value)
+ except ValueError:
+ fail(f"expected a number, got {value!r}")
+ if not math.isfinite(parsed) or parsed < 0:
+ fail(f"expected a nonnegative finite number, got {value!r}")
+ return parsed
+
+
+def parse_durations(value: str, frame_count: int) -> list[float]:
+ """Expand one hold duration or validate one duration per source frame."""
+ parts = [part.strip() for part in value.split(",")]
+ if not parts or any(not part for part in parts):
+ fail("--durations must be a number or a comma-separated list of numbers")
+ durations = [positive_float(part) for part in parts]
+ if len(durations) == 1:
+ return durations * frame_count
+ if len(durations) != frame_count:
+ fail(f"--durations supplied {len(durations)} values for {frame_count} frames")
+ return durations
+
+
+def require_binary(name: str) -> str:
+ """Resolve a required media binary or fail without attempting installation."""
+ path = shutil.which(name)
+ if path is None:
+ fail(f"required binary {name!r} is not available on PATH")
+ return path
+
+
+def run_json(command: list[str]) -> dict[str, object]:
+ """Run a media probe and parse its JSON object."""
+ try:
+ completed = subprocess.run(command, check=True, capture_output=True, text=True)
+ except subprocess.CalledProcessError as error:
+ detail = error.stderr.strip() or error.stdout.strip() or str(error)
+ fail(detail)
+ try:
+ value = json.loads(completed.stdout)
+ except json.JSONDecodeError as error:
+ fail(f"media probe returned invalid JSON: {error}")
+ if not isinstance(value, dict):
+ fail("media probe returned a non-object JSON value")
+ return value
+
+
+def probe_stream(ffprobe: str, path: Path) -> dict[str, object]:
+ """Read the first video stream's dimensions and timing metadata."""
+ result = run_json(
+ [
+ ffprobe,
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "stream=width,height,nb_frames,duration,r_frame_rate",
+ "-of",
+ "json",
+ str(path),
+ ]
+ )
+ streams = result.get("streams")
+ if not isinstance(streams, list) or len(streams) != 1 or not isinstance(streams[0], dict):
+ fail(f"expected one video stream in {path}")
+ return streams[0]
+
+
+def video_duration(ffprobe: str, path: Path) -> float:
+ """Read container duration because Playwright WebM omits stream duration."""
+ result = run_json([
+ ffprobe, "-v", "error", "-show_entries", "format=duration", "-of", "json", str(path),
+ ])
+ metadata = result.get("format")
+ if not isinstance(metadata, dict):
+ fail(f"missing format metadata for {path}")
+ return positive_float(str(metadata.get("duration")))
+
+
+def stream_int(stream: dict[str, object], key: str, path: Path) -> int:
+ """Read a positive integer stream field."""
+ try:
+ value = int(stream[key])
+ except (KeyError, TypeError, ValueError):
+ fail(f"missing integer {key!r} in media probe for {path}")
+ if value <= 0:
+ fail(f"non-positive {key!r} in media probe for {path}")
+ return value
+
+
+def ffconcat_quote(path: Path) -> str:
+ """Quote an ffconcat path while preserving literal backslashes."""
+ value = str(path)
+ if "\n" in value or "\r" in value:
+ fail(f"frame path contains a newline: {path}")
+ return "'" + value.replace("'", "'\\''") + "'"
+
+
+def write_concat_manifest(path: Path, frames: list[Path], durations: list[float]) -> None:
+ """Write an ffconcat manifest that materializes the final frame's hold."""
+ lines = ["ffconcat version 1.0"]
+ for frame, duration in zip(frames, durations):
+ lines.append(f"file {ffconcat_quote(frame)}")
+ lines.append(f"duration {duration:.6f}")
+ lines.append(f"file {ffconcat_quote(frames[-1])}")
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+
+def build_parser() -> argparse.ArgumentParser:
+ """Build the command-line contract."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("input", type=Path, help="video file or directory of ordered screenshots")
+ parser.add_argument("output", type=Path, help="output .gif path")
+ parser.add_argument("--pattern", help="screenshot glob (default: *.png; directory input only)")
+ parser.add_argument(
+ "--durations",
+ help="screenshot holds (default: 2 seconds each; directory input only)",
+ )
+ parser.add_argument("--start", type=nonnegative_float, help="video trim start in seconds (default: 0)")
+ parser.add_argument("--end", type=positive_float, help="video trim end in seconds (default: EOF)")
+ parser.add_argument("--speed", type=positive_float, help="video playback multiplier (default: 1)")
+ parser.add_argument("--final-hold", type=nonnegative_float, help="extra final video frame hold (default: 2 seconds)")
+ parser.add_argument("--fps", type=positive_int, default=10, help="encoded frames per second")
+ parser.add_argument(
+ "--max-width",
+ type=positive_int,
+ default=1200,
+ help="maximum output width",
+ )
+ parser.add_argument(
+ "--colors",
+ type=positive_int,
+ default=128,
+ help="palette colors, from 4 through 256",
+ )
+ parser.add_argument(
+ "--max-bytes",
+ type=positive_int,
+ default=DEFAULT_MAX_BYTES,
+ help="maximum output size",
+ )
+ parser.add_argument("--force", action="store_true", help="replace an existing output file")
+ return parser
+
+
+def main() -> None:
+ """Validate inputs, encode the GIF, verify it, and print a JSON summary."""
+ args = build_parser().parse_args()
+ source = args.input.resolve()
+ output = args.output.resolve()
+
+ if not source.exists():
+ fail(f"input does not exist: {source}")
+ is_video = source.is_file()
+ if not is_video and not source.is_dir():
+ fail(f"input must be a video file or frame directory: {source}")
+ if output.suffix.lower() != ".gif":
+ fail(f"output must end in .gif: {output}")
+ if output.exists() and not args.force:
+ fail(f"output already exists (pass --force to replace it): {output}")
+ if not 4 <= args.colors <= 256:
+ fail("--colors must be between 4 and 256")
+ if args.fps > 30:
+ fail("--fps must not exceed 30")
+
+ ffmpeg = require_binary("ffmpeg")
+ ffprobe = require_binary("ffprobe")
+ details: dict[str, object]
+ if is_video:
+ if args.pattern is not None or args.durations is not None:
+ fail("--pattern and --durations require a screenshot directory")
+ if source == output:
+ fail("output path must not match the input video")
+ probe_stream(ffprobe, source)
+ source_duration = video_duration(ffprobe, source)
+ start = args.start if args.start is not None else 0.0
+ end = args.end if args.end is not None else source_duration
+ speed = args.speed if args.speed is not None else 1.0
+ final_hold = args.final_hold if args.final_hold is not None else 2.0
+ if not start < end <= source_duration:
+ fail(f"video trim must satisfy 0 <= start < end <= {source_duration:.3f}")
+ if (end - start) / speed < 2 / args.fps:
+ fail("video selection must span at least two output frames before the final hold")
+ expected_duration = (end - start) / speed + final_hold
+ details = {
+ "sourceVideo": str(source), "sourceDurationSeconds": source_duration,
+ "startSeconds": start, "endSeconds": end, "speed": speed,
+ "finalHoldSeconds": final_hold,
+ }
+ else:
+ if any(value is not None for value in (args.start, args.end, args.speed, args.final_hold)):
+ fail("--start, --end, --speed and --final-hold require a video file")
+ pattern = args.pattern if args.pattern is not None else "*.png"
+ if not pattern:
+ fail("--pattern must not be empty")
+ frames = sorted(path.resolve() for path in source.glob(pattern) if path.is_file())
+ if len(frames) < 2:
+ fail(f"expected at least two frames in {source}")
+ if output in frames:
+ fail("output path must not match an input frame")
+ durations = parse_durations(args.durations if args.durations is not None else "2", len(frames))
+ expected_duration = sum(durations)
+ dimensions = {
+ (stream_int(stream, "width", frame), stream_int(stream, "height", frame))
+ for frame in frames
+ for stream in [probe_stream(ffprobe, frame)]
+ }
+ if len(dimensions) != 1:
+ fail(f"all frames must have identical dimensions, got {sorted(dimensions)}")
+ details = {"sourceFrames": len(frames)}
+
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix="record-browser-gif-") as temporary:
+ if is_video:
+ inputs = ["-i", str(source)]
+ timing = f"trim=start={start}:end={end},setpts=(PTS-STARTPTS)/{speed},"
+ hold = f",tpad=stop_mode=clone:stop_duration={final_hold}"
+ else:
+ manifest = Path(temporary) / "frames.ffconcat"
+ write_concat_manifest(manifest, frames, durations)
+ inputs = ["-f", "concat", "-safe", "0", "-i", str(manifest)]
+ timing = ""
+ hold = ""
+ scale = f"scale='min({args.max_width},iw)':-2:flags=lanczos"
+ palette = f"palettegen=max_colors={args.colors}:stats_mode=full"
+ filters = (
+ f"{timing}fps={args.fps},{scale}{hold},split[base][palette_input];"
+ f"[palette_input]{palette}[palette];"
+ "[base][palette]paletteuse=dither=bayer:bayer_scale=3:diff_mode=rectangle"
+ )
+ command = [
+ ffmpeg,
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ *inputs,
+ "-vf",
+ filters,
+ "-loop",
+ "0",
+ "-t",
+ f"{expected_duration:.6f}",
+ "-y" if args.force else "-n",
+ str(output),
+ ]
+ try:
+ subprocess.run(command, check=True)
+ except subprocess.CalledProcessError as error:
+ fail(f"ffmpeg failed with exit code {error.returncode}")
+
+ stream = probe_stream(ffprobe, output)
+ width = stream_int(stream, "width", output)
+ height = stream_int(stream, "height", output)
+ encoded_frames = stream_int(stream, "nb_frames", output)
+ try:
+ actual_duration = float(stream["duration"])
+ except (KeyError, TypeError, ValueError):
+ fail(f"missing duration in media probe for {output}")
+ tolerance = max(0.2, 2 / args.fps)
+ if abs(actual_duration - expected_duration) > tolerance:
+ fail(f"expected about {expected_duration:.3f}s, encoded {actual_duration:.3f}s")
+ if width > args.max_width:
+ fail(f"expected width at most {args.max_width}, encoded {width}")
+ if encoded_frames < 2:
+ fail(f"expected an animated GIF, encoded {encoded_frames} frame")
+
+ byte_size = output.stat().st_size
+ if byte_size > args.max_bytes:
+ fail(f"output is {byte_size} bytes, above --max-bytes {args.max_bytes}")
+
+ print(
+ json.dumps(
+ {
+ "output": str(output),
+ **details,
+ "encodedFrames": encoded_frames,
+ "width": width,
+ "height": height,
+ "durationSeconds": actual_duration,
+ "fps": args.fps,
+ "bytes": byte_size,
+ },
+ indent=2,
+ sort_keys=True,
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/record-browser-gif/scripts/test_encode_gif.py b/.agents/skills/record-browser-gif/scripts/test_encode_gif.py
new file mode 100644
index 00000000..3106ef9c
--- /dev/null
+++ b/.agents/skills/record-browser-gif/scripts/test_encode_gif.py
@@ -0,0 +1,103 @@
+"""Exercise GIF timing and rejection through real ffmpeg/ffprobe subprocesses."""
+
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+SCRIPT = Path(__file__).with_name('encode_gif.py')
+
+
+class EncodeGifTest(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory(prefix='gif-encoder-test-')
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.video = self.root / 'browser video.webm'
+ self.output = self.root / 'demo.gif'
+ subprocess.run([
+ 'ffmpeg', '-v', 'error',
+ '-f', 'lavfi', '-i', 'color=red:s=64x48:r=10:d=2',
+ '-f', 'lavfi', '-i', 'color=lime:s=64x48:r=10:d=2',
+ '-f', 'lavfi', '-i', 'color=blue:s=64x48:r=10:d=2',
+ '-filter_complex', '[0:v][1:v][2:v]concat=n=3:v=1:a=0',
+ '-c:v', 'libvpx', str(self.video),
+ ], check=True, capture_output=True)
+
+ def encode(self, source=None, *options):
+ return subprocess.run([
+ sys.executable, str(SCRIPT), str(source or self.video), str(self.output), *options,
+ ], capture_output=True, text=True)
+
+ def assert_color(self, seconds, channel):
+ result = subprocess.run([
+ 'ffmpeg', '-v', 'error', '-i', str(self.output), '-ss', str(seconds),
+ '-frames:v', '1', '-vf', 'scale=1:1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-',
+ ], check=True, capture_output=True)
+ pixel = result.stdout
+ self.assertEqual(len(pixel), 3)
+ self.assertGreater(pixel[channel], 200)
+ self.assertTrue(all(value < 40 for index, value in enumerate(pixel) if index != channel))
+
+ def test_video_trim_speed_final_hold_and_palette_order(self):
+ result = self.encode(None, '--start', '1', '--end', '5', '--speed', '2',
+ '--final-hold', '1', '--max-width', '32')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ summary = json.loads(result.stdout)
+ self.assertAlmostEqual(summary['durationSeconds'], 3, delta=0.2)
+ self.assertEqual((summary['width'], summary['height']), (32, 24))
+ self.assert_color(0.1, 0)
+ self.assert_color(0.8, 1)
+ self.assert_color(2.7, 2)
+
+ def test_video_defaults_keep_full_duration(self):
+ result = self.encode()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertAlmostEqual(json.loads(result.stdout)['durationSeconds'], 8, delta=0.2)
+ self.assert_color(7.7, 2)
+
+ def test_invalid_video_options_do_not_write_output(self):
+ for options in [
+ ['--start', '-1'], ['--speed', 'nan'], ['--final-hold', 'inf'],
+ ['--start', '3', '--end', '3'], ['--end', '7'],
+ ['--speed', '1000'], ['--durations', '2'], ['--pattern', '*.png'],
+ ]:
+ with self.subTest(options=options):
+ result = self.encode(None, *options)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn('error:', result.stderr)
+ self.assertFalse(self.output.exists())
+
+ def test_screenshot_durations_and_video_flag_rejection(self):
+ frames = self.root / 'frames'
+ frames.mkdir()
+ for index, color in enumerate([b'\xff\x00\x00', b'\x00\x00\xff']):
+ (frames / f'{index}.ppm').write_bytes(b'P6\n64 48\n255\n' + color * (64 * 48))
+ rejected = self.encode(frames, '--speed', '1')
+ self.assertNotEqual(rejected.returncode, 0)
+ self.assertIn('require a video file', rejected.stderr)
+ for options in [['--pattern', ''], ['--pattern', '*.ppm', '--durations', ''],
+ ['--pattern', '*.ppm', '--durations', '1,2,3']]:
+ with self.subTest(options=options):
+ self.assertNotEqual(self.encode(frames, *options).returncode, 0)
+ self.assertFalse(self.output.exists())
+ result = self.encode(frames, '--pattern', '*.ppm', '--durations', '0.5,1.5')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout)['sourceFrames'], 2)
+ self.assert_color(0.1, 0)
+ self.assert_color(1.8, 2)
+
+ def test_overwrite_and_size_limit(self):
+ self.output.write_bytes(b'keep')
+ rejected = self.encode()
+ self.assertNotEqual(rejected.returncode, 0)
+ self.assertEqual(self.output.read_bytes(), b'keep')
+ oversized = self.encode(None, '--force', '--max-bytes', '1', '--final-hold', '0.0')
+ self.assertNotEqual(oversized.returncode, 0)
+ self.assertIn('above --max-bytes', oversized.stderr)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.gitignore b/.gitignore
index 7ab1e5d9..35d16bbb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,3 +24,6 @@ node_modules/
/docker/.env
/.env
/docker-compose.override.yml
+
+# Bytecode from the record-browser-gif encoder's local media tests.
+__pycache__/
diff --git a/AGENTS.md b/AGENTS.md
index dd802059..5c52cb90 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -53,6 +53,7 @@ The full workflow is in [CONTRIBUTING.md](CONTRIBUTING.md#how-we-work). The part
- Before you change behavior, read the design for it in `docs/plans/` (and `docs/vision.md`). A change to a decided design needs the maintainer; a new large feature adds its design note to the same pull request.
- Do not close an issue without evidence: the pull request or commit that fixed it, the issue it duplicates, or the reason it will not be fixed.
- To triage issues, follow [.agents/skills/issue-triage/SKILL.md](.agents/skills/issue-triage/SKILL.md).
+- To record a demonstration GIF for an interface change, follow [.agents/skills/record-browser-gif/SKILL.md](.agents/skills/record-browser-gif/SKILL.md).
## Layout
diff --git a/NOTICE b/NOTICE
index 58ee2855..91cdcf91 100644
--- a/NOTICE
+++ b/NOTICE
@@ -30,6 +30,10 @@ MIT License, Copyright (c) 2026 DeepSeek
app/engine/preset-standard.patch.yml copies its standard preset
(presets/standard.patch.yml), including the plan-mode prompt text,
without the goal rows.
+ - .agents/skills/record-browser-gif/ comes from the skill of the same name
+ in DeepSeek Harness (.agents/skills/record-browser-gif/): SKILL.md is
+ adapted and translated for this repository; scripts/encode_gif.py and
+ scripts/test_encode_gif.py are copied unchanged.
Full license text: