ci(preview): link the snapshot diff page from the source chooser and harden it

Co-authored-by: yudshj <16971372+yudshj@users.noreply.github.com>
This commit is contained in:
Turtleandyudshj committed 2026-11-06 18:15:52 +08:00
1 parent ac96c518fb
commit 3aee25862d
18 files changed
+345 -138

No files matched your search

+2 -2
View File
@@ -15,8 +15,8 @@
en: 2374f332d040ece2
zh: 7f914fb83cfb5caa
/pr-preview-runner-sizing/publication-semantics:
en: 25ee2f4b26ef7770
zh: 788b7fb4bee6e159
en: 0d86702bcbbe23f4
zh: cd0041c917ac8c55
/pr-preview-runner-sizing/dev-note:
en: c3e8959997c4d5d0
zh: 109a391915c2bdfb
+1 -1
View File
@@ -26,7 +26,7 @@ A build-only benchmark does not deploy, access Cloudflare credentials, or post p
## Publication semantics
Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site to the PR branch alias. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines.
Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site and the snapshot diff page to the PR branch alias; that page embeds committed `snapshots/` diff text, never package sources. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines.
<a id="dev-note"></a>
+1 -1
View File
@@ -26,7 +26,7 @@
## 发布语义
运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点上传至 PR 分支别名。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。
运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点和 snapshot diff 页面上传至 PR 分支别名;该页面嵌入已提交的 `snapshots/` diff 文本,不含包源码。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。
<a id="dev-note"></a>
+24 -12
View File
@@ -2,7 +2,8 @@ name: Build PR preview
# Every push to a pull request publishes that pull request's preview to
# Cloudflare Pages under its own branch alias, behind Cloudflare Access. The
# upload carries build products only: the workflow never grants the deployment
# upload carries build products plus the snapshot diff page, which embeds
# committed `snapshots/` diff text: the workflow never grants the deployment
# platform access to this repository's sources. This lane also owns the
# aggregate test and script type checks that the required Linux consumers no
# longer repeat on every pull request.
@@ -102,9 +103,16 @@ jobs:
cp apps/web/dist/preview.html apps/web/dist/index.html
# Reviewers read snapshot changes at /snapshot-diff/, which opens on the
# SDK blank-Session catalog (system prompt and tool schemas).
# SDK blank-Session catalog (system prompt and tool schemas); the source
# chooser links to it. The page serves review only, so a failure warns
# like publication instead of failing the build.
- name: Render the snapshot diff page
run: pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html
id: snapshot-diff
continue-on-error: true
run: >-
pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD
--out apps/web/dist/snapshot-diff/index.html
--preview-manifest apps/web/dist/preview/fixtures.json
- name: Upload to Cloudflare Pages
id: upload
@@ -180,29 +188,33 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.number }}
SNAPSHOT_DIFF: ${{ steps.snapshot-diff.outcome }}
run: |
marker='<!-- dsh-preview-url -->'
url="https://pr-$PR.${CF_PROJECT}.pages.dev"
links="[Preview for #$PR]($url)"
if [ "$SNAPSHOT_DIFF" = success ]; then links="$links · [snapshot changes]($url/snapshot-diff/)"; fi
# The marker sits on its own line: markdown renders no link on a
# line that opens with a raw HTML comment.
body=$(printf '%s\n\n%s\n' \
"$marker" \
"[Preview for #$PR]($url) · [snapshot changes]($url/snapshot-diff/) (requires Cloudflare Access sign-in)")
body=$(printf '%s\n\n%s\n' "$marker" "$links (requires Cloudflare Access sign-in)")
existing=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate \
--jq "[.[] | select(.body | contains(\"$marker\"))] | first // empty | [.id, .body] | @json")
--jq "[.[] | select(.user.login == \"github-actions[bot]\" and (.body | contains(\"$marker\")))] | first // empty | [.id, .body] | @json")
if [ -z "$existing" ]; then
printf '%s\n' "$body" | gh pr comment "$PR" --body-file -
printf '%s' "$body" | gh pr comment "$PR" --body-file -
elif [ "$(jq -r '.[1]' <<< "$existing")" != "$body" ]; then
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$(jq -r '.[0]' <<< "$existing")" -f body="$body" > /dev/null
else
echo "preview URL already commented"
fi
# Publishing stays outside the required verdict: a Cloudflare, Access, or
# comment failure warns, while a build failure still fails this check.
# Publishing stays outside the required verdict: a snapshot diff page,
# Cloudflare, Access, or comment failure warns, while a build failure
# still fails this check.
- name: Report preview publication failures
if: steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'
if: >-
steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure'
|| steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'
run: |
message='preview publication failed; the build passed, see the upload, verify, and comment steps'
message='preview publication failed; the build passed, see the snapshot diff, upload, verify, and comment steps'
echo "::warning::$message"
echo "$message" >> "$GITHUB_STEP_SUMMARY"
+1
View File
@@ -200,6 +200,7 @@ function requireVfsAssets(): PreviewAssets {
version: PREVIEW_FIXTURE_MANIFEST_VERSION,
defaultFixture: fixtures[0]?.id ?? null,
fixtures,
links: [],
}
writeAsset(`preview/${PREVIEW_FIXTURE_MANIFEST_FILE}`, `${JSON.stringify(fixtureManifest, null, 2)}\n`)
return { overrides, manifest, cleanup: () => { rmSync(directory, { recursive: true, force: true }) } }
@@ -80,6 +80,7 @@ const manifest: PreviewFixtureManifest = {
version: PREVIEW_FIXTURE_MANIFEST_VERSION,
defaultFixture: fixtures[0]?.id ?? null,
fixtures,
links: [],
}
writeFileSync(
join(dirname(outputFile), PREVIEW_FIXTURE_MANIFEST_FILE),
@@ -15,8 +15,8 @@
en: 4e53164159b5ce41
zh: 89582dc0294d0776
/deepseek-ai-dsh-experimental-webworker-runtime/use-this-package:
en: 9f4c76d6c4391037
zh: c55611045f4667e2
en: 33c27e81e1e6212c
zh: 6e32be50142bdb44
/deepseek-ai-dsh-experimental-webworker-runtime/model-experience:
en: 61fce9b4c7dc96e6
zh: dc2d931063a38327
@@ -31,7 +31,7 @@ Three build artifacts and one source-owned process layer:
- **Lazy archives** — the manifest registers each page chunk the packer moved out of the base image by path and size, with its archive name relative to the image URL. Existence, stats, and listings answer at once; the first asynchronous read (`fs.promises.readFile`, `fs.promises.open`, `fs.createReadStream`, `fs.promises.cp`) fetches and inflates that archive once for every waiting reader, checks it against the registration, and mounts its files without publishing a mutation. A failed fetch rejects the read and leaves the files registered, so the next read fetches again. Until then, synchronous reads, writes, appends, truncation, chmod, rename, and link of a registered file fail with `ERR_DSH_VFS_DEFERRED` naming the archive; unlink and recursive removal drop the registration, and seeding the path replaces it. The archive name derives from its content digest, and the fetch checks only the registered paths and sizes, not the digest. An image that registers lazy archives must be passed as a URL.
- **`lib/worker.js` (worker bundle)** — the assembly plus this package's Node-compatibility layer as one self-contained ES module. The module proxy table (`module-proxies.ts`) is the only platform fork: `node:*` builtins over VFS/tunnel/browser primitives, structural stubs that fail loud on the console for what a browser cannot do, and native/binary package replacements. `node:module` supplies `createRequire().resolve` and `.resolve.paths()` over the image package root, so unchanged packages can discover manifests without evaluating their modules. `node-addon-require-builtin` answers the Node v24.18.0 internal modules that the vendored Loader, app-boot, and HMR read without `--expose-internals`: the cascaded ESM loader's `resolveSync` and `import` over the Worker loader, with Node's `ERR_MODULE_NOT_FOUND` and `ERR_PACKAGE_PATH_NOT_EXPORTED` codes, and an empty `loadCache`; and the CommonJS loader, package reader, `modules` binding, and resolve-cache members that HMR replaces, which refuse when called. `process.versions.node` reports `24.18.0`, so `ModuleLoader.fromInternal()` and the Loader's `internal` reach that cascaded loader. `node:path.win32.isAbsolute` and `node:util.inherits` follow Node; other `win32` members throw. The `node:util` JSON-data comparator compares own enumerable properties, preserving Node admission decisions for recorded fields such as `__proto__`. The global `process` shim carries Node detection fields including `title`, preventing Worker execution from entering DOM-only branches; Node’s `global` alias references the same `globalThis` object for image-loaded packages. The pack-time parser reports statically named module requests, including module-scope direct calls of the form `createRequire(import.meta.url)('pkg')` through a named `node:module` or `module` import, to the packer's reachability walk. Stored, CommonJS-obtained, and rebased `createRequire` calls require image entry seeds. Lowered bodies read named and default imports through the required module object at each reference, so a module in an import cycle observes a binding once the exporting module initializes it; in a module with such imports, an assignment to an imported binding, a direct `eval`, and a declaration using the reserved `__dsh$` prefix fail the pack. VFS mutations drive `node:fs` callback, polling, and promise watchers, whose listeners run in the async context where the watcher was created rather than that of the writing code; open descriptors retain file identity and access mode across rename, replacement, and unlink, `FileHandle.stat({ bigint: true })` reports the same device and inode identity as a path stat while the name still refers to that file, and `FileHandle.chmod()` updates the opened file identity; `readable-stream` supplies `node:stream/promises` completion and pipeline helpers and the stream state machine used by file streams and unchanged image packages such as Chokidar and readdirp. The maintained `string_decoder` package supplies `node:string_decoder`, retaining incomplete multibyte characters between chunks. AsyncLocalStorage carries sync-stack causality across `await` through the snapshot/restore faces the pack-time lowering injects. The worker holds no compiler: an image the packer did not lower is refused at mount. The callback `fs.realpath.native` alias resolves within the mounted VFS and supports `util.promisify`.
- **`src/shell/` (the worker's own process layer)** — a browser worker cannot fork, so `node:child_process` is not a stub but an implementation: `spawn` starts the command in its own Web Worker — this same bundle, told by its first frame to be a shell process — and reports it through the `ChildProcess` surface the subprocess service consumes. The command runs off the host's thread, `SIGKILL` terminates it whatever it is doing, and it reaches the VFS only by message (the host serves those frames). Worker platform executables preserve native-package protocols such as Landlock without replacing their JavaScript packages or coupling their implementations to `node:child_process`; `xdg-open` sends one VFS text file to the page's read-only viewer, so desktop-opener actions such as **Open configuration file** show the file in the page; ordinary commands use the package's evaluator and coreutils command table. The grammar is `@yarnpkg/parsers`' `parseShell`, while `execSync`/`fork` still refuse because they need a real process.
- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. Before the shell entry runs, the page reads `GET /__assets__`, which the tunnel answers with an uncompressed tar of every package asset in the image, and supplies `resolveAsset`, which maps each `plugins/<package>/assets/<path>` reference a bundle passes to `require.asset` to a Blob URL of those bytes. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream<Uint8Array>` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply.
- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. The manifest's optional `links` list of relative URLs renders beside the start button; the PR preview workflow adds one for its snapshot diff page. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. Before the shell entry runs, the page reads `GET /__assets__`, which the tunnel answers with an uncompressed tar of every package asset in the image, and supplies `resolveAsset`, which maps each `plugins/<package>/assets/<path>` reference a bundle passes to `require.asset` to a Blob URL of those bytes. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream<Uint8Array>` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply.
Callbacks and timers registered under an explicit root context retain its empty stores, so they cannot inherit an unrelated transaction.
@@ -31,7 +31,7 @@ kind: "package-library"
- **懒加载归档**——manifest 按路径和大小登记 packer 移出基础镜像的每个页面 chunk,并给出相对镜像 URL 的归档名。存在性、stat 和目录列表立即作答;第一次异步读取(`fs.promises.readFile`、`fs.promises.open`、`fs.createReadStream`、`fs.promises.cp`)为所有等待中的读取方只拉取并解压一次该归档,按登记内容校验后挂载其文件,不发布 mutation。拉取失败时本次读取被拒绝,文件保持登记状态,下次读取会重新拉取。在此之前,对已登记文件的同步读取、写入、追加、截断、chmod、rename 和 link 会以 `ERR_DSH_VFS_DEFERRED` 失败,错误中写明归档名;unlink 和递归删除会移除登记,再次 seed 该路径会替换登记。归档名由内容摘要派生,拉取时只校验登记的路径和大小,不校验摘要。登记了懒加载归档的镜像必须以 URL 传入。
- **`lib/worker.js`(worker 束)**——装配库加本包的 Node 兼容层,合成一个自含 ES module。模块代理表(`module-proxies.ts`)是唯一平台叉口:`node:*` 内建走 VFS、隧道和浏览器原语,浏览器做不到的走结构化 stub(调用即在 console 报错并抛出),native/binary 包则替换执行后端。`node:module` 在镜像 package 根之上提供 `createRequire().resolve` 与 `.resolve.paths()`,使未修改的包无需执行目标模块即可发现 manifest。`node-addon-require-builtin` 应答 vendor Loader、app-boot 和 HMR 在没有 `--expose-internals` 时读取的 Node v24.18.0 internal 模块:cascaded ESM loader 的 `resolveSync` 和 `import` 经 Worker 加载器完成,失败时带 Node 的 `ERR_MODULE_NOT_FOUND` 与 `ERR_PACKAGE_PATH_NOT_EXPORTED` 错误码,`loadCache` 为空;HMR 会替换的 CommonJS loader、package reader、`modules` binding 与 resolve cache 成员被调用时拒绝。`process.versions.node` 报告 `24.18.0`,因此 `ModuleLoader.fromInternal()` 和 Loader 的 `internal` 拿到的是这个 cascaded loader。`node:path.win32.isAbsolute` 与 `node:util.inherits` 与 Node 一致,其余 `win32` 成员抛出。`node:util` 的 JSON 数据比较器检查可枚举的自有属性,使 `__proto__` 等记录字段的准入判定与 Node 一致。全局 `process` shim 带有包括 `title` 在内的 Node 环境识别字段,避免 Worker 执行误入仅适用于 DOM 的分支;镜像中加载的包通过 Node 的 `global` 别名访问同一个 `globalThis` 对象。pack 期解析器会把名称静态可知的模块请求报告给 packer 的可达性遍历,其中包括通过 `node:module` 或 `module` 具名导入在模块作用域直接发起的 `createRequire(import.meta.url)('pkg')` 调用。保存、经 CommonJS 获取或另设基准的 `createRequire` 调用需要镜像入口种子。降低后的模块体在每次引用具名导入与 default 导入时,都经所 require 的模块对象读取,因此循环导入中的模块能在导出方完成初始化后读到该绑定;在含此类导入的模块中,对导入绑定赋值、直接调用 `eval`、声明使用保留前缀 `__dsh$` 的名字,都会使 pack 失败。VFS mutation 驱动 `node:fs` 的 callback、polling 和 promise watcher,监听回调运行在创建 watcher 时的异步上下文中,而不是写入方代码的上下文中;打开的 descriptor 在 rename、replacement 和 unlink 后仍保留文件身份与访问模式,只要文件名仍指向该文件,`FileHandle.stat({ bigint: true })` 报告的 device 与 inode 身份就与路径 stat 相同,`FileHandle.chmod()` 则更新打开文件身份的权限;`readable-stream` 提供 `node:stream/promises` 的完成等待与管道方法,以及文件流以及 Chokidar、readdirp 等未修改镜像包所用的流状态机。维护中的 `string_decoder` 包提供 `node:string_decoder`,在数据块之间保留不完整的多字节字符。AsyncLocalStorage 经 pack 时降低注入的 snapshot/restore 面在 `await` 间携带同步栈因果。worker 不带编译器:packer 未降低的镜像在挂载时被拒。回调式 `fs.realpath.native` 别名在已挂载的 VFS 内解析路径,并支持 `util.promisify`。
- **`src/shell/`(worker 自己的进程层)**——浏览器 worker 无法 fork,所以 `node:child_process` 不是 stub 而是实现:`spawn` 把命令放进它自己的 Web Worker——就是这同一个束,由首帧告诉它「你是 shell 进程」——并以 subprocess 服务消费的 `ChildProcess` 面报告结果。命令不占宿主线程,`SIGKILL` 不管它在干什么都能终止它,而它只能靠消息触达 VFS(由宿主应答这些帧)。Worker 平台 executable 在不替换 JavaScript 包、也不把具体实现耦合进 `node:child_process` 的情况下保持 Landlock 等 native 包协议;`xdg-open` 把一个 VFS 文本文件交给页面的只读查看器,因此 **打开配置文件** 等桌面打开操作会在页面内显示该文件;普通命令使用本包的求值器与 coreutils 命令表。语法来自 `@yarnpkg/parsers` 的 `parseShell`,而 `execSync`/`fork` 依然拒绝,因为它们需要真进程。
- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。在 shell 入口运行之前,页面读取 `GET /__assets__`(隧道以镜像中所有包资源组成的未压缩 tar 回答),并提供 `resolveAsset`,把 bundle 传给 `require.asset` 的每个 `plugins/<package>/assets/<path>` 引用映射为这些字节的 Blob URL。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream<Uint8Array>` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。
- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。manifest 中可选的 `links` 列表只接受相对 URL,显示在开始按钮旁;PR 预览工作流为它的 snapshot diff 页面加了一条。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。在 shell 入口运行之前,页面读取 `GET /__assets__`(隧道以镜像中所有包资源组成的未压缩 tar 回答),并提供 `resolveAsset`,把 bundle 传给 `require.asset` 的每个 `plugins/<package>/assets/<path>` 引用映射为这些字节的 Blob URL。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream<Uint8Array>` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。
在显式根上下文中登记的回调和定时器保留其空 store,避免继承无关事务。
@@ -20,7 +20,7 @@ export { applyIndexInjections } from './apply-injections.ts'
export { IMAGE_FILE_NAME } from '../image-layout.ts'
export {
parsePreviewFixtureManifest, PREVIEW_FIXTURE_MANIFEST_FILE, PREVIEW_FIXTURE_MANIFEST_VERSION,
type PreviewFixtureManifest, type PreviewFixtureManifestEntry,
type PreviewFixtureManifest, type PreviewFixtureManifestEntry, type PreviewLink,
} from '../fixture-manifest.ts'
/** Transport global the connection plugin reads instead of building an HTTP carrier. */
@@ -113,11 +113,23 @@ const CHOOSER_STYLE = `
font-size: 14px;
line-height: 24px;
}
[data-preview-source-footer] {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px 16px;
margin: 24px 0 0;
}
[data-preview-source-link] {
color: #61666b;
text-underline-offset: 3px;
}
[data-preview-source-link]:hover { color: #0f1115; }
[data-preview-source-submit] {
display: block;
min-width: 120px;
height: 36px;
margin: 24px 0 0 auto;
margin: 0 0 0 auto;
padding: 0 14px;
border: 0;
border-radius: 18px;
@@ -148,6 +160,8 @@ const CHOOSER_STYLE = `
[data-preview-source-option]:has(input:checked) { background: rgb(255 255 255 / 8%); }
[data-preview-source-option]:has(input:checked) { border-color: rgb(255 255 255 / 12%); }
[data-preview-source-option] input { accent-color: #f9fafb; }
[data-preview-source-link] { color: #cfd3d6; }
[data-preview-source-link]:hover { color: #f9fafb; }
[data-preview-source-submit] { color: #0f1115; background: #f9fafb; }
[data-preview-source-submit]:hover:not(:disabled) { background: #ebeef2; }
[data-preview-source-submit]:focus-visible { outline-color: rgb(255 255 255 / 20%); }
@@ -243,7 +257,10 @@ export async function choosePreviewSource(manifestUrl: URL): Promise<readonly UR
<legend>Filesystem source</legend>
${choices.map(choice => optionMarkup(choice, selected)).join('')}
</fieldset>
<button data-preview-source-submit type="submit">Start Preview</button>
<div data-preview-source-footer>
${manifest.links.map(link => `<a data-preview-source-link href="${escapeMarkup(new URL(link.href, manifestUrl).href)}">${escapeMarkup(link.label)}</a>`).join('')}
<button data-preview-source-submit type="submit">Start Preview</button>
</div>
</form>`
root.prepend(chooser)
const form = chooser.querySelector<HTMLFormElement>('[data-preview-source-card]')
@@ -14,12 +14,39 @@ export interface PreviewFixtureManifestEntry {
readonly overlays: readonly string[]
}
/** A page the source chooser links to, such as a report published beside the Preview. */
export interface PreviewLink {
readonly label: string
/** URL resolved against the manifest URL; one that resolves to another origin is rejected. */
readonly href: string
}
/** Complete built-in fixture catalog consumed before Worker startup. */
export interface PreviewFixtureManifest {
readonly version: number
/** Required default fixture id, or null when the chooser should default to an empty overlay. */
readonly defaultFixture: string | null
readonly fixtures: readonly PreviewFixtureManifestEntry[]
/** Links shown on the source chooser; the parser reads an absent list as empty. */
readonly links: readonly PreviewLink[]
}
/** Resolving against this base shows whether an href could leave the manifest's origin. */
const SAME_ORIGIN_PROBE = new URL('https://preview.invalid/')
function parseLinks(value: unknown): PreviewLink[] {
if (value === undefined) return []
if (!Array.isArray(value)) throw new Error('preview fixture manifest links must be an array')
return value.map((item) => {
const link = recordOf(item)
const label = link?.label
const href = link?.href
if (typeof label !== 'string' || label.length === 0
|| typeof href !== 'string' || href.length === 0 || new URL(href, SAME_ORIGIN_PROBE).origin !== SAME_ORIGIN_PROBE.origin) {
throw new Error('preview fixture manifest contains an invalid link')
}
return { label, href }
})
}
function recordOf(value: unknown): Record<string, unknown> | undefined {
@@ -31,7 +58,7 @@ function recordOf(value: unknown): Record<string, unknown> | undefined {
/**
* Validate the static fixture catalog before it controls Worker fetches.
* @param value - Parsed JSON response.
* @returns A detached manifest with unique ids and non-empty overlay lists.
* @returns A detached manifest with unique ids, non-empty overlay lists, and relative links.
*/
export function parsePreviewFixtureManifest(value: unknown): PreviewFixtureManifest {
const record = recordOf(value)
@@ -64,5 +91,5 @@ export function parsePreviewFixtureManifest(value: unknown): PreviewFixtureManif
if (defaultFixture !== null && (typeof defaultFixture !== 'string' || !ids.has(defaultFixture))) {
throw new Error('preview fixture manifest defaultFixture does not name a fixture')
}
return { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture, fixtures }
return { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture, fixtures, links: parseLinks(record.links) }
}
@@ -43,7 +43,7 @@ export {
} from './image-manifest.ts'
export {
parsePreviewFixtureManifest, PREVIEW_FIXTURE_MANIFEST_FILE, PREVIEW_FIXTURE_MANIFEST_VERSION,
type PreviewFixtureManifest, type PreviewFixtureManifestEntry,
type PreviewFixtureManifest, type PreviewFixtureManifestEntry, type PreviewLink,
} from './fixture-manifest.ts'
export { loadVfsImage, loadVfsOverlay, MemoryVfs } from './storage/memory.ts'
export { inflateImage, inflateImageStream } from './storage/image-gzip.ts'
@@ -15,6 +15,7 @@ const MANIFEST: PreviewFixtureManifest = {
description: 'A deterministic example.',
overlays: ['fixtures/base.tar.gz', 'fixtures/tail.tar.gz'],
}],
links: [],
}
function setLocation(search = ''): void {
@@ -108,6 +109,31 @@ describe('Preview source chooser', () => {
expect(document.querySelector('[data-preview-source-style]')).toBeNull()
})
it('shows manifest links resolved against the manifest URL', async () => {
installManifest({ ...MANIFEST, links: [{ label: 'Snapshot <changes>', href: '../snapshot-diff/' }] })
const selected = choosePreviewSource(MANIFEST_URL)
await vi.waitFor(() => {
expect(document.querySelector('[data-preview-source-link]')).not.toBeNull()
})
const link = document.querySelector<HTMLAnchorElement>('[data-preview-source-link]')
expect([link?.textContent, link?.href]).toEqual(['Snapshot <changes>', 'https://preview.test/snapshot-diff/'])
submitChooser()
await selected
})
it('shows no link when the manifest has none', async () => {
installManifest()
const selected = choosePreviewSource(MANIFEST_URL)
await vi.waitFor(() => {
expect(document.querySelector('[data-preview-source-chooser]')).not.toBeNull()
})
expect(document.querySelector('[data-preview-source-link]')).toBeNull()
submitChooser()
await selected
})
it('selects the empty source when the manifest has no default', async () => {
installManifest({ ...MANIFEST, defaultFixture: null })
@@ -23,9 +23,20 @@ describe('Preview fixture manifest', () => {
description: 'A deterministic example.',
overlays: ['fixtures/base.tar.gz', 'fixtures/tail.tar.gz'],
}],
links: [],
})
})
it('accepts relative links', () => {
const links = [{ label: 'Snapshot changes', href: '../snapshot-diff/' }, { label: 'Root', href: '/report/' }]
expect(parsePreviewFixtureManifest({ version: 1, defaultFixture: null, fixtures: [], links }).links).toEqual(links)
})
it.each(['https://example.test/', 'javascript:alert(1)', '//example.test/', '\\\\example.test/', '', ' //evil.test/x', '/\t/evil.test/x', '\njavascript:alert(1)'])('rejects the link href %j', (href) => {
expect(() => parsePreviewFixtureManifest({ version: 1, defaultFixture: null, fixtures: [], links: [{ label: 'L', href }] }))
.toThrow(/invalid link/)
})
it.each([
[{ version: 2, defaultFixture: null, fixtures: [] }, /must use version/],
[{ version: 1, defaultFixture: 'missing', fixtures: [] }, /defaultFixture/],
@@ -42,6 +53,8 @@ describe('Preview fixture manifest', () => {
defaultFixture: 'none',
fixtures: [{ id: 'none', label: 'None', description: 'Reserved.', overlays: ['none.tar.gz'] }],
}, /invalid fixture entry/],
[{ version: 1, defaultFixture: null, fixtures: [], links: {} }, /links must be an array/],
[{ version: 1, defaultFixture: null, fixtures: [], links: [{ label: '', href: 'a/' }] }, /invalid link/],
])('rejects malformed catalogs', (value, error) => {
expect(() => parsePreviewFixtureManifest(value)).toThrow(error)
})
+10 -5
View File
@@ -30,14 +30,15 @@ describe('PR preview workflow', () => {
it('fails the check only for build failures and warns about publication', () => {
const byName = (name: string) => preview.steps.find(step => step.name === name)
for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload', 'Render the snapshot diff page']) {
for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload']) {
expect(byName(name)?.['continue-on-error'], `${name} must stay blocking`).toBeUndefined()
}
for (const name of ['Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) {
for (const name of ['Render the snapshot diff page', 'Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) {
expect(byName(name)?.['continue-on-error'], `${name} must warn instead of failing`).toBe(true)
}
const report = byName('Report preview publication failures')
expect(report?.if).toBe("steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'")
expect(report?.if).toBe("steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure'"
+ " || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'")
expect(report?.run).toContain('::warning::')
})
@@ -78,15 +79,19 @@ describe('PR preview workflow', () => {
expect(verify.env?.CF_ACCESS_CLIENT_SECRET).toBe('${{ secrets.CF_ACCESS_CLIENT_SECRET }}')
const comment = preview.steps.find(step => step.name === 'Comment the preview URL')!
expect(comment.run).toContain('<!-- dsh-preview-url -->')
expect(comment.run).toContain('gh pr comment "$PR" --body-file -')
expect(comment.run).toContain('printf \'%s\' "$body" | gh pr comment "$PR" --body-file -')
expect(comment.run).toContain('[snapshot changes]($url/snapshot-diff/)')
expect(comment.env?.SNAPSHOT_DIFF).toBe('${{ steps.snapshot-diff.outcome }}')
expect(comment.run).toContain('if [ "$SNAPSHOT_DIFF" = success ]')
expect(comment.run).toContain('gh api -X PATCH')
expect(comment.run).toContain('select(.user.login == \\"github-actions[bot]\\"')
})
it('renders the snapshot diff page into the upload against the base branch tip', () => {
const steps = preview.steps.map(step => step.name)
const page = preview.steps.find(step => step.name === 'Render the snapshot diff page')!
expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html')
expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD'
+ ' --out apps/web/dist/snapshot-diff/index.html --preview-manifest apps/web/dist/preview/fixtures.json')
expect(steps.indexOf('Render the snapshot diff page')).toBeGreaterThan(steps.indexOf('Shape the upload'))
expect(steps.indexOf('Render the snapshot diff page')).toBeLessThan(steps.indexOf('Upload to Cloudflare Pages'))
})
+59 -31
View File
@@ -1,7 +1,5 @@
import { describe, expect, it } from 'vitest'
import { groupDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts'
const limits = { fileLines: 100, totalChars: 10_000 }
import { addPreviewLink, catalogFiles, groupDiffs, limitDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts'
const diff = `diff --git a/snapshots/sdk/text-turn/system-prompt.expected.md b/snapshots/sdk/text-turn/system-prompt.expected.md
index 1111111..2222222 100644
@@ -27,50 +25,80 @@ old mode 100644
new mode 100755
`
const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json']
const file = (path: string, hunks = '') => ({ path, hunks, binary: false, omitted: 0 })
describe('snapshot diff page', () => {
it('splits git diff output into files with their hunks', () => {
expect(parseUnifiedDiff(diff, limits)).toEqual([
{ path: 'snapshots/sdk/text-turn/system-prompt.expected.md', hunks: '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.', binary: false, omitted: 0 },
{ path: 'snapshots/web/ptc-round/session.jsonl', hunks: '@@ -1 +0,0 @@\n-{"type":"header"}', binary: false, omitted: 0 },
{ path: 'snapshots/web/ptc-round/image.png', hunks: '', binary: true, omitted: 0 },
{ path: 'snapshots/web/present/workspace.expected/a b/说明.txt', hunks: '', binary: false, omitted: 0 },
expect(parseUnifiedDiff(diff)).toEqual([
file('snapshots/sdk/text-turn/system-prompt.expected.md', '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.'),
file('snapshots/web/ptc-round/session.jsonl', '@@ -1 +0,0 @@\n-{"type":"header"}'),
{ ...file('snapshots/web/ptc-round/image.png'), binary: true },
file('snapshots/web/present/workspace.expected/a b/说明.txt'),
])
expect(parseUnifiedDiff('', limits)).toEqual([])
expect(parseUnifiedDiff('')).toEqual([])
})
it('rejects paths git still quotes', () => {
expect(() => parseUnifiedDiff('diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n', limits)).toThrow('unsupported quoted path')
it.each([
['a quoted path', 'diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n'],
['unequal header paths', 'diff --git a/snapshots/x b/snapshots/y\n'],
['a missing prefix', 'diff --git snapshots/x snapshots/x\n'],
])('rejects a header with %s', (_, text) => {
expect(() => parseUnifiedDiff(text)).toThrow('unsupported git diff header')
})
it('truncates long files and drops hunks once the total budget is spent', () => {
const section = (name: string, lines: number) => `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -1,${lines} +1,${lines} @@\n${'+x\n'.repeat(lines - 1)}`
const [long, fits, over] = parseUnifiedDiff(section('a', 150) + section('b', 10) + section('c', 10), { fileLines: 100, totalChars: 365 })
expect([long!.hunks.split('\n').length, long!.omitted]).toEqual([100, 50])
expect([fits!.hunks.split('\n').length, fits!.omitted]).toEqual([10, 0])
expect([over!.hunks, over!.omitted]).toEqual(['', 10])
it('truncates long sections and drops sections past the byte budget of the escaped JSON', () => {
const lines = (count: number, line = '+x') => file(`f${count}`, ['@@', ...Array.from({ length: count - 1 }, () => line)].join('\n'))
const [long, fits, over] = limitDiffs([lines(150), lines(10), lines(10)], { fileLines: 100, totalBytes: 445 })
expect([long?.hunks.split('\n').length, long?.omitted]).toEqual([100, 50])
expect([fits?.hunks.split('\n').length, fits?.omitted]).toEqual([10, 0])
expect([over?.hunks, over?.omitted]).toEqual(['', 10])
// Quotes, `@@`, and nine lines of an escaped newline, `+`, and two six-byte \u003c escapes: 139 bytes.
expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 138 })[0]?.omitted).toBe(10)
expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 139 })[0]?.omitted).toBe(0)
})
it('opens on the catalog, listing unchanged catalog files, then groups by scenario', () => {
const groups = groupDiffs(parseUnifiedDiff(diff, limits).slice(0, 3), catalog)
expect(groups.map(group => [group.title, group.paths, group.files.map(file => file.path)])).toEqual([
['SDK blank Session catalog', catalog, ['snapshots/sdk/text-turn/system-prompt.expected.md']],
['sdk/text-turn', ['snapshots/sdk/text-turn/system-prompt.expected.md'], ['snapshots/sdk/text-turn/system-prompt.expected.md']],
['web/ptc-round', ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl'], ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl']],
it('opens on the catalog, then groups scenarios and other files by directory in code point order', () => {
const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json']
const paths = ['snapshots/web/b/x', 'snapshots/sdk/sdk.snapshot.ts', 'snapshots/AGENTS.md', 'snapshots/web/B/x', 'snapshots/web/b/a/y']
expect(groupDiffs([...paths, 'snapshots/web/b/x'].map(path => file(path)), catalog)).toEqual([
{ title: 'SDK blank Session catalog', paths: catalog },
{ title: 'snapshots', paths: ['snapshots/AGENTS.md'] },
{ title: 'sdk', paths: ['snapshots/sdk/sdk.snapshot.ts'] },
{ title: 'web/B', paths: ['snapshots/web/B/x'] },
{ title: 'web/b', paths: ['snapshots/web/b/a/y', 'snapshots/web/b/x'] },
])
})
it('lists a path once when a type change splits it into two sections', () => {
const removed = { path: 'snapshots/acp/cancel/system-prompt.expected.md', hunks: '@@ -1 +0,0 @@\n-../x', binary: false, omitted: 0 }
const added = { ...removed, hunks: '@@ -0,0 +1 @@\n+text' }
expect(groupDiffs([removed, added], catalog)[1]).toEqual({ title: 'acp/cancel', paths: [removed.path], files: [removed, added] })
it.each([
['owns both sidecars', 'profile: sdk\n', 'sdk/text-turn', 'sdk/text-turn'],
['names a source in its own suite directory', 'profile: sdk-minimal\nheader:\n toolSchemasSource: other\n', 'sdk/text-turn', 'sdk/other'],
['names sources in another suite', 'profile: sdk\nheader:\n systemPromptSource: session/a\n toolSchemasSource: session/b\n', 'session/a', 'session/b'],
])('resolves catalog sidecars when the manifest %s', (_, text, prompt, schemas) => {
expect(catalogFiles(text)).toEqual({
systemPrompt: `snapshots/${prompt}/system-prompt.expected.md`,
toolSchemas: `snapshots/${schemas}/tool-schemas.expected.json`,
})
})
it.each([
['a non-string source', 'profile: sdk\nheader:\n toolSchemasSource: 1\n', 'header.toolSchemasSource must be a non-empty string'],
['an empty source', 'header:\n systemPromptSource: ""\n', 'header.systemPromptSource must be a non-empty string'],
])('rejects %s', (_, text, message) => {
expect(() => catalogFiles(text)).toThrow(message)
})
it('embeds the data so diff text cannot close the script element', () => {
const page = renderSnapshotDiffPage([{ title: 't', paths: ['p'], files: [{ path: 'p', hunks: '+</script><b>', binary: false, omitted: 0 }] }], 'a → b')
const files = [file('p', '+</script><b>')]
const page = renderSnapshotDiffPage(files, [{ title: 't', paths: ['p'] }], 'a → b')
expect(page).not.toContain('</script><b>')
const data = /<script type="application\/json" id="data">(.*)<\/script>/.exec(page)![1]!
expect(JSON.parse(data)).toEqual({ groups: [{ title: 't', paths: ['p'], files: [{ path: 'p', hunks: '+</script><b>', binary: false, omitted: 0 }] }], heading: 'a → b' })
const data = /<script type="application\/json" id="data">(.*)<\/script>/.exec(page)?.[1] ?? ''
expect(JSON.parse(data)).toEqual({ files, groups: [{ title: 't', paths: ['p'] }], heading: 'a → b' })
})
it('appends the page link to the Preview fixture manifest', () => {
const manifest = JSON.stringify({ version: 1, defaultFixture: null, fixtures: [] })
expect(JSON.parse(addPreviewLink(manifest, '../snapshot-diff/'))).toEqual({
version: 1, defaultFixture: null, fixtures: [], links: [{ label: 'Snapshot changes', href: '../snapshot-diff/' }],
})
})
})
+153 -76
View File
@@ -3,31 +3,35 @@
* listing every changed file under `snapshots/` between two revisions, grouped
* by scenario directory. The page opens on the SDK blank-Session catalog, the
* system prompt and tool schemas the `sdk/text-turn` scenario's first request
* carries, and shows "No change" when neither file changed.
* carries, and shows "No change" for a catalog file whose content is equal on
* both sides.
*
* Usage: `tsx scripts/snapshot-diff-page.ts --base <rev> --head <rev> --out <file>`
* Usage: `tsx scripts/snapshot-diff-page.ts --base <rev> --head <rev> --out <file> [--preview-manifest <fixtures.json>]`.
* `--preview-manifest` adds a link to the page in the Preview source chooser.
*/
import { execFileSync } from 'node:child_process'
import { mkdirSync, writeFileSync } from 'node:fs'
import { dirname } from 'node:path'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, posix, relative, sep } from 'node:path'
import { parseArgs } from 'node:util'
import * as yaml from 'js-yaml'
/** Scenario whose first request represents a blank SDK Session. */
const CATALOG_SCENARIO = 'snapshots/sdk/text-turn'
const CATALOG_SCENARIO = 'sdk/text-turn'
/** Per-file and total limits on embedded diff text; the page notes what it omits. */
/** Limits on embedded diff text; the page notes how many lines it omits. */
export interface DiffLimits {
/** Hunk lines kept per diff section. */
readonly fileLines: number
readonly totalChars: number
/** UTF-8 bytes of escaped JSON hunk text kept across the page. */
readonly totalBytes: number
}
/** Keeps the page well under the Cloudflare Pages 25 MiB per-file limit and responsive in a browser. */
const LIMITS: DiffLimits = { fileLines: 2000, totalChars: 8_000_000 }
/** Keeps the page well under the Cloudflare Pages 25 MiB per-file limit. */
const LIMITS: DiffLimits = { fileLines: 2000, totalBytes: 20 * 1024 * 1024 }
/** One `diff --git` section: a changed file and its unified diff text. */
export interface FileDiff {
/** Repository-relative path. */
/** Repository-relative path, or `old → new` for a catalog file whose source scenario changed. */
readonly path: string
/** Unified diff lines from the first `@@` hunk header, empty for binary or mode-only changes. */
readonly hunks: string
@@ -37,73 +41,126 @@ export interface FileDiff {
readonly omitted: number
}
/** A selectable group of file diffs on the page. */
/** A selectable entry on the page. */
export interface DiffGroup {
readonly title: string
/** Distinct paths the group covers, including unchanged ones. */
/** Distinct {@link FileDiff.path} values the group shows, including unchanged ones. */
readonly paths: readonly string[]
readonly files: readonly FileDiff[]
}
/** The two sidecars that make up a scenario's request catalog. */
export interface CatalogFiles {
readonly systemPrompt: string
readonly toolSchemas: string
}
function hunksOf(lines: readonly string[]): string[] {
const start = lines.findIndex(line => line.startsWith('@@'))
return start === -1 ? [] : lines.slice(start, lines.at(-1) === '' ? -1 : undefined)
}
function section(path: string, lines: readonly string[]): FileDiff {
const hunks = hunksOf(lines)
return { path, hunks: hunks.join('\n'), binary: lines.some(line => line.startsWith('Binary files ')), omitted: 0 }
}
/**
* Splits git diff output into per-file sections.
* @param text - Output of `git -c core.quotePath=false diff --no-color --no-renames`;
* a path git still quotes (one with `"`, `\\`, or a control character) is rejected.
* @param limits - Lines kept per file and characters kept across all files.
* @returns One entry per `diff --git` section, in output order. A path that
* changes between symlink and regular file has two sections.
* @param text - Output of `git -c core.quotePath=false diff --no-color --no-renames --no-ext-diff --src-prefix=a/ --dst-prefix=b/`.
* @returns One untruncated entry per `diff --git` section, in output order. A
* path that changes between symlink and regular file has two sections.
* @throws When a header does not read `diff --git a/<path> b/<path>`, as for a
* path git still quotes (one with `"`, `\\`, or a control character).
*/
export function parseUnifiedDiff(text: string, limits: DiffLimits = LIMITS): FileDiff[] {
export function parseUnifiedDiff(text: string): FileDiff[] {
const files: FileDiff[] = []
let budget = limits.totalChars
for (const section of text.split(/^(?=diff --git )/m)) {
if (!section.startsWith('diff --git ')) continue
const lines = section.split('\n')
// Without renames the header is `diff --git a/<path> b/<path>` with both paths equal.
const header = section.slice('diff --git '.length, section.indexOf('\n') === -1 ? undefined : section.indexOf('\n'))
if (header.startsWith('"')) throw new Error(`unsupported quoted path in git diff header: ${header}`)
const path = header.slice('a/'.length, (header.length - ' '.length) / 2)
const hunkStart = lines.findIndex(line => line.startsWith('@@'))
const all = hunkStart === -1 ? [] : lines.slice(hunkStart, lines.at(-1) === '' ? -1 : undefined)
let kept = all.slice(0, limits.fileLines)
let hunks = kept.join('\n')
if (hunks.length > budget) {
kept = []
hunks = ''
}
budget -= hunks.length
files.push({ path, hunks, binary: lines.some(line => line.startsWith('Binary files ')), omitted: all.length - kept.length })
for (const part of text.split(/^(?=diff --git )/m)) {
if (!part.startsWith('diff --git ')) continue
const lines = part.split('\n')
const header = /^diff --git a\/(.+) b\/\1$/.exec(lines[0] ?? '')
if (header?.[1] === undefined) throw new Error(`unsupported git diff header: ${lines[0] ?? ''}`)
files.push(section(header[1], lines))
}
return files
}
function embeddedBytes(text: string): number {
return Buffer.byteLength(JSON.stringify(text).replace(/</g, '\\u003c'))
}
/**
* Applies the limits in order: each section keeps at most `fileLines` hunk
* lines, and a section that would exceed the remaining byte budget keeps none.
* @param files - Sections in page order.
* @param limits - Per-section line and page byte limits.
* @returns Sections with `hunks` cut and `omitted` counting the dropped lines.
*/
export function limitDiffs(files: readonly FileDiff[], limits: DiffLimits = LIMITS): FileDiff[] {
let budget = limits.totalBytes
return files.map((file) => {
const all = file.hunks === '' ? [] : file.hunks.split('\n')
let hunks = all.slice(0, limits.fileLines).join('\n')
if (embeddedBytes(hunks) > budget) hunks = ''
budget -= embeddedBytes(hunks)
const kept = hunks === '' ? 0 : Math.min(all.length, limits.fileLines)
return { ...file, hunks, omitted: all.length - kept }
})
}
/**
* Groups changed files for the page: the catalog first, then one group per
* scenario directory (`snapshots/<suite>/<scenario>`) in path order.
* scenario directory (`snapshots/<suite>/<scenario>`) and one per directory
* holding other changed files, in code point order.
* @param files - Changed files under `snapshots/`.
* @param catalogPaths - Files that make up the SDK blank-Session catalog.
* @returns The catalog group followed by the scenario groups.
* @param catalogPaths - Paths the catalog group shows.
* @returns The catalog group followed by the directory groups.
*/
export function groupDiffs(files: readonly FileDiff[], catalogPaths: readonly string[]): DiffGroup[] {
const scenarios = new Map<string, FileDiff[]>()
for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
const key = file.path.split('/').slice(0, 3).join('/')
scenarios.set(key, [...scenarios.get(key) ?? [], file])
const groups = new Map<string, Set<string>>()
for (const { path } of files) {
const segments = path.split('/')
const key = segments.slice(0, segments.length >= 4 ? 3 : -1).join('/')
groups.set(key, (groups.get(key) ?? new Set()).add(path))
}
const byCodePoint = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
return [
{ title: 'SDK blank Session catalog', paths: catalogPaths, files: files.filter(file => catalogPaths.includes(file.path)) },
...[...scenarios].map(([key, group]) => ({ title: key.replace(/^snapshots\//, ''), paths: [...new Set(group.map(file => file.path))], files: group })),
{ title: 'SDK blank Session catalog', paths: catalogPaths },
...[...groups].sort(([a], [b]) => byCodePoint(a, b))
.map(([key, paths]) => ({ title: key.replace(/^snapshots\/?/, '') || 'snapshots', paths: [...paths].sort(byCodePoint) })),
]
}
function referencedScenario(source: unknown, field: string): string {
if (source === undefined) return CATALOG_SCENARIO
if (typeof source !== 'string' || source === '') throw new Error(`snapshots/${CATALOG_SCENARIO}/snapshot.yml: header.${field} must be a non-empty string`)
return source.includes('/') ? source : `${CATALOG_SCENARIO.split('/')[0] ?? ''}/${source}`
}
/**
* Resolves the catalog sidecars from the catalog scenario's `snapshot.yml`,
* following `header.systemPromptSource` and `header.toolSchemasSource`; a
* single-segment source names a scenario in the catalog scenario's suite directory.
* @param manifestText - The catalog scenario's `snapshot.yml` text.
* @returns Repository-relative sidecar paths.
*/
export function catalogFiles(manifestText: string): CatalogFiles {
const manifest = (yaml.load(manifestText, { schema: yaml.JSON_SCHEMA }) ?? {}) as { header?: Record<string, unknown> }
const header = manifest.header ?? {}
return {
systemPrompt: `snapshots/${referencedScenario(header.systemPromptSource, 'systemPromptSource')}/system-prompt.expected.md`,
toolSchemas: `snapshots/${referencedScenario(header.toolSchemasSource, 'toolSchemasSource')}/tool-schemas.expected.json`,
}
}
/**
* Renders the self-contained page.
* @param files - Limited sections from {@link limitDiffs}.
* @param groups - Groups from {@link groupDiffs}; the first one opens by default.
* @param heading - Revision description shown under the title.
* @returns HTML text.
*/
export function renderSnapshotDiffPage(groups: readonly DiffGroup[], heading: string): string {
const data = JSON.stringify({ groups, heading }).replace(/</g, '\\u003c')
export function renderSnapshotDiffPage(files: readonly FileDiff[], groups: readonly DiffGroup[], heading: string): string {
const data = JSON.stringify({ files, groups, heading }).replace(/</g, '\\u003c')
return `<!doctype html>
<html lang="en">
<head>
@@ -138,7 +195,7 @@ pre div { padding: 0 12px; }
<main id="view"></main>
<script type="application/json" id="data">${data}</script>
<script>
const { groups, heading } = JSON.parse(document.getElementById('data').textContent)
const { files, groups, heading } = JSON.parse(document.getElementById('data').textContent)
document.getElementById('heading').textContent = heading
const list = document.getElementById('list')
const view = document.getElementById('view')
@@ -148,7 +205,7 @@ function el(tag, props = {}, ...children) {
return node
}
const buttons = groups.map((group, index) => {
const button = el('button', { type: 'button', onclick: () => show(index) }, el('span', { textContent: group.title }), el('span', { textContent: String(group.files.length) }))
const button = el('button', { type: 'button', onclick: () => show(index) }, el('span', { textContent: group.title }), el('span', { textContent: String(group.paths.filter(path => files.some(file => file.path === path)).length) }))
list.append(button)
if (index === 0) list.append(el('hr'))
return button
@@ -172,7 +229,7 @@ function show(index) {
history.replaceState(null, '', '#' + encodeURIComponent(group.title))
view.replaceChildren(el('h2', { textContent: group.title }))
for (const path of group.paths) {
const sections = group.files.filter(candidate => candidate.path === path)
const sections = files.filter(candidate => candidate.path === path)
const bodies = sections.length === 0 ? [el('div', { className: 'empty', textContent: 'No change' })] : sections.flatMap(render)
view.append(el('section', {}, el('h3', { textContent: path }), ...bodies))
}
@@ -186,38 +243,58 @@ show(initial === -1 ? 0 : initial)
}
/**
* Reads the catalog files from the catalog scenario's `snapshot.yml`.
* @param rev - Revision to read.
* @returns The system prompt sidecar and the tool schema sidecar, which lives
* in the scenario named by `header.toolSchemasSource` when present.
* Appends a link to the page to a Preview fixture manifest.
* @param manifestText - `fixtures.json` text the packer wrote.
* @param href - Page URL relative to the manifest.
* @returns The updated manifest text.
*/
function catalogPaths(rev: string): string[] {
const spec = yaml.load(git('show', `${rev}:${CATALOG_SCENARIO}/snapshot.yml`), { schema: yaml.JSON_SCHEMA }) as { header?: { toolSchemasSource?: unknown } }
const source = spec.header?.toolSchemasSource
if (source !== undefined && typeof source !== 'string') throw new Error(`${CATALOG_SCENARIO}/snapshot.yml: header.toolSchemasSource must be a string`)
const paths = [`${CATALOG_SCENARIO}/system-prompt.expected.md`, `${source === undefined ? CATALOG_SCENARIO : `snapshots/${source}`}/tool-schemas.expected.json`]
for (const path of paths) {
try {
git('cat-file', '-e', `${rev}:${path}`)
} catch (error) {
throw new Error(`catalog file ${path} is missing at ${rev}`, { cause: error })
}
}
return paths
export function addPreviewLink(manifestText: string, href: string): string {
const manifest = JSON.parse(manifestText) as { links?: unknown[] }
return `${JSON.stringify({ ...manifest, links: [...manifest.links ?? [], { label: 'Snapshot changes', href }] }, null, 2)}\n`
}
function git(...args: string[]): string {
return execFileSync('git', args, { encoding: 'utf8', maxBuffer: 1 << 30 })
}
const DIFF = ['-c', 'core.quotePath=false', 'diff', '--no-color', '--no-renames', '--no-ext-diff', '--src-prefix=a/', '--dst-prefix=b/', '--unified=5']
/** Requires a regular file, because git diffs a symlink as its target path rather than the content it names. */
function assertRegularFile(rev: string, path: string): void {
const mode = git('ls-tree', rev, '--', path).split(' ')[0]
if (mode !== '100644' && mode !== '100755') throw new Error(`catalog file ${path} at ${rev} is not a regular file (mode ${mode || 'missing'})`)
}
/**
* Diffs one catalog sidecar. When its source scenario moved, the blobs are
* compared directly under an `old → new` label, because neither file changed.
*/
function catalogDiff(base: string, head: string, from: string, to: string): { path: string; extra?: FileDiff } {
assertRegularFile(base, from)
assertRegularFile(head, to)
if (from === to) return { path: to }
const path = `${from} → ${to}`
const text = git(...DIFF, `${base}:${from}`, `${head}:${to}`)
return text === '' ? { path } : { path, extra: section(path, text.split('\n')) }
}
if (import.meta.main) {
const { values } = parseArgs({ options: { base: { type: 'string' }, head: { type: 'string' }, out: { type: 'string' } } })
if (!values.base || !values.head || !values.out) throw new Error('usage: snapshot-diff-page.ts --base <rev> --head <rev> --out <file>')
const { values } = parseArgs({ options: { 'base': { type: 'string' }, 'head': { type: 'string' }, 'out': { type: 'string' }, 'preview-manifest': { type: 'string' } } })
const { base, head, out } = values
if (!base || !head || !out) throw new Error('usage: snapshot-diff-page.ts --base <rev> --head <rev> --out <file> [--preview-manifest <fixtures.json>]')
const short = (rev: string) => git('rev-parse', '--short', rev).trim()
const files = parseUnifiedDiff(git('-c', 'core.quotePath=false', 'diff', '--no-color', '--no-renames', '--unified=5', values.base, values.head, '--', 'snapshots/'))
// A PR that moves the tool schema source shows both the old and the new file.
const catalog = [...new Set([...catalogPaths(values.base), ...catalogPaths(values.head)])]
const page = renderSnapshotDiffPage(groupDiffs(files, catalog), `${short(values.base)} → ${short(values.head)}`)
mkdirSync(dirname(values.out), { recursive: true })
writeFileSync(values.out, page)
const changed = parseUnifiedDiff(git(...DIFF, base, head, '--', 'snapshots/'))
const manifestAt = (rev: string) => catalogFiles(git('show', `${rev}:snapshots/${CATALOG_SCENARIO}/snapshot.yml`))
const from = manifestAt(base)
const to = manifestAt(head)
const catalog = [catalogDiff(base, head, from.systemPrompt, to.systemPrompt), catalogDiff(base, head, from.toolSchemas, to.toolSchemas)]
const files = limitDiffs([...catalog.flatMap(entry => entry.extra ? [entry.extra] : []), ...changed])
const page = renderSnapshotDiffPage(files, groupDiffs(changed, catalog.map(entry => entry.path)), `${short(base)} → ${short(head)}`)
mkdirSync(dirname(out), { recursive: true })
writeFileSync(out, page)
const manifest = values['preview-manifest']
if (manifest) {
const href = `${relative(dirname(manifest), dirname(out)).split(sep).join(posix.sep)}/`
writeFileSync(manifest, addPreviewLink(readFileSync(manifest, 'utf8'), href))
}
}