diff --git a/.dsh-version.json b/.dsh-version.json index 013d33a..3ec9d6c 100644 --- a/.dsh-version.json +++ b/.dsh-version.json @@ -48,6 +48,22 @@ "@deepseek-ai/dsh-client-ui-sidebar-files" ] }, + "dsh-deliverables": { + "version": "0.1.0-alpha.1", + "rows": [ + "deliverables" + ], + "disablesRows": [ + "ui-deliverables" + ], + "vendoredPatches": 7, + "role": "Deliverables and the turn Review tab: a GENERATED fork of @deepseek-ai/dsh-client-ui-deliverables (its Node half and its browser half) whose one behavior change is that a binary image change is drawn as the picture - in the Review tab and in the changed-files card's hover preview - instead of 'Binary file; changes cannot be shown', and counted as Image where the card said binary. The shipped row is disabled by this package's layer, so this is the copy that runs; six browser patches and one inlined import in the Node half, all in scripts/tools/sync-vendored.ps1. A text diff, a deleted image and every non-image binary keep the shipped behavior. See packages/dsh-deliverables/README.md.", + "uses": [ + "dsh-rightbar (the tab registry and the keyed pane seat)", + "@deepseek-ai/dsh-client-ui-deliverables (the package it forks; the core row is disabled, the vendored copy is the one that runs)", + "the harness's own /api/changes.* and /api/present.* routes (re-served by the fork's Node half) and /api/file for the picture" + ] + }, "dsh-editor": { "version": "0.1.0-alpha.16", "rows": [ @@ -418,6 +434,27 @@ "NOTHING is vendored, downloaded or installed: DeckCraft is the user's app, and this package ships the argv builder, the command-list parser and the output scope" ] }, + "dsh-hyperframes": { + "version": "0.1.0-alpha.1", + "rows": [ + "hyperframes" + ], + "rowOverrides": [], + "role": "Moving figures: six `anim_*` tools over the user's own HyperFrames CLI (heygen-com/hyperframes, Apache-2.0) - `anim_status` (the CLI, Node, a browser and ffmpeg, the four facts that fail independently, read BY NAME out of `doctor --json` because its top-level ok is false whenever an optional extra such as whisper or Docker is missing), `anim_new` (a project that lints clean as written: the root registers its own paused timeline, which is the `missing_timeline_registry` error otherwise), `anim_scene` (one scene from a figure the pack already produced - HyperFrames has no TeX, no chart library and no bundled math font), `anim_check` (lint, then a real browser audit, findings passed through as the CLI wrote them with the frames around them; a `browserSkipped: true` report is NOT a pass), `anim_snapshot` (stills and a contact sheet copied into the project, no encode) and `anim_render` (MP4/WebM/MOV/GIF, ffprobe facts, the CLI's provenance tags, and a refusal when this conversation's last check found errors). A rung ladder stated on every answer - a0-source, a1-lint, a2-checked, a3-stilled, a4-rendered - so 'it rendered' is never printed as 'it is correct'. Three worked UI examples (dashboard, chat, SaaS landing) and three skills. Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine. See packages/dsh-hyperframes/README.md.", + "uses": [ + "@deepseek-ai/dsh-tools (the registry the six tools are registered into)", + "the user's own HyperFrames CLI on PATH or `DSH_HYPERFRAMES_CLI`; a copy an earlier npx run already extracted into the npx cache is used as a fallback, run through this Node - the row never runs npx", + "ffmpeg, resolved by dsh-media's own rules (DSH_MEDIA_FFMPEG, then PATH, then $DSH_HOME/dsh-media/bin/-/) and PREPENDED to the child's PATH, because the CLI has no ffmpeg-path variable", + "a Chromium-family browser this host already has, named through HYPERFRAMES_BROWSER_PATH so none is downloaded" + ], + "requires": [ + "HyperFrames installed by the user (`npm install --global hyperframes`, Node >= 22) - `anim_status` names the line and stops; without it the tools answer a0-source and say why", + "a Chromium-family browser for anim_check, anim_snapshot and anim_render, and ffmpeg for the render - lint and authoring need neither" + ], + "vendors": [ + "NOTHING is vendored, downloaded or installed: HyperFrames is the user's program, and this package ships the resolver, the argv builder, the child env policy, the project template, the scene writer and the rung ladder. The three examples are this package's own HTML." + ] + }, "dsh-wsl": { "version": "0.1.0-alpha.1", "rows": [ diff --git a/AGENTS.md b/AGENTS.md index e5a3e32..497ab66 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,7 +68,9 @@ for its behaviour, `SECURITY.md` before touching credentials or the launcher, an - `packages//` — one standalone bundle per plugin, each with its own one-page README: `dsh-vn-master` (final layer), `dsh-rightbar` + - `dsh-rightbar-files` (the right bar and its Files tab), `dsh-editor`, + `dsh-rightbar-files` (the right bar and its Files tab), `dsh-deliverables` + (the turn's changed-files card and Review tab, forked so an image change is + drawn as the picture instead of the binary-diff sentence), `dsh-editor`, `dsh-gittree` (History), `dsh-image`, `dsh-image-upscale` (Real-ESRGAN over the Python and torch the machine already has: four `upscale_*` tools, a NEW file per image and never the original, a manifest batch that is a dry run by default, and a @@ -173,12 +175,12 @@ for its behaviour, `SECURITY.md` before touching credentials or the launcher, an - A package may carry its OWN checks under `packages//checks/`, run with `npm run check` in that folder. They travel with the package (which is what makes them useful outside this repository) and they are ADDITIONAL to - `scripts/checks/`, never a replacement for it: today twelve packages ship their + `scripts/checks/`, never a replacement for it: today thirteen packages ship their own (`dsh-supercollider` with four checks, `dsh-research` with seven, `dsh-rust-dev` with two, plus `dsh-diagrams`, `dsh-frontend-craft`, `dsh-proto-lab`, `dsh-ocr`, `dsh-wsl`, `dsh-docker`, `dsh-ollama`, - `dsh-image-upscale` and `dsh-comfyui`), and the pack-wide checks still own the - routes, the bundle and the manifest. + `dsh-deliverables`, `dsh-image-upscale` and `dsh-comfyui`), and the pack-wide + checks still own the routes, the bundle and the manifest. - `scripts/` — the launcher (`run-web.*`), and four folders: `console/` (the shared console layer), `setup/` (install and uninstall, which a fresh machine runs once), `tools/` (maintainer-only: the fork re-sync for the client bundles this pack vendors) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 1aa1a6e..e47bb01 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -78,6 +78,7 @@ disable/replace a core row **in its own layer** — a later layer wins per row. | `dsh-modal` | `modal` | the shared dialog surface (`modals` service) | | `dsh-skills` | `skills` | the Skills browser: list, read and edit the skills the harness loads | | `dsh-ui-state` | `ui-state` | UI state that outlives the process (column widths, dock height, zoom) | +| `dsh-hyperframes` | `hyperframes` | Moving figures: six `anim_*` tools over the user's own HyperFrames CLI (heygen-com/hyperframes, Apache-2.0) — `anim_status` (the CLI, Node, a browser and ffmpeg, the four facts that fail independently, read by name out of `doctor --json` because its top-level `ok` is false whenever an optional extra is missing), `anim_new` (a project that lints clean as written; the root registers its own paused timeline, which is `missing_timeline_registry` otherwise), `anim_scene` (one scene from a figure the pack already produced — HyperFrames has no TeX and no chart library), `anim_check` (lint, then a real browser audit, findings passed through with the frames around them; a `browserSkipped` report is NOT a pass), `anim_snapshot` (stills and a contact sheet copied into the project, no encode) and `anim_render` (MP4/WebM/MOV/GIF, ffprobe facts, provenance, and a refusal when the conversation's last check found errors) — over a rung ladder stated on every answer (`a0-source` → `a4-rendered`), with three worked UI examples and three skills. Never `npx`, never installs, and `HYPERFRAMES_NO_TELEMETRY` / `NO_AUTO_INSTALL` / `NO_UPDATE_CHECK` on every child. Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine | | `dsh-open-in-app` | `native-open-in-app` | the file-manager half of Open In | ## Rules that hold everywhere diff --git a/README.md b/README.md index c08ad35..b2339f2 100644 --- a/README.md +++ b/README.md @@ -61,12 +61,14 @@ way and what it touches. The exact versions are in | [`dsh-cmdbar`](packages/dsh-cmdbar/README.md) | The command bar: the agent's own commands in a bottom dock, as a read-only transcript of the conversation log. It follows whichever conversation is on screen. | | [`dsh-comfyui`](packages/dsh-comfyui/README.md) | ComfyUI as a surface the agent can build against: seven `comfy_*` tools turn a small readable project spec into the canvas the app opens and the prompt `/prompt` accepts, validate it against the server's own `/object_info` with ComfyUI's own error types, and report what a run produced. Every answer names the rung it reached (`v1-structural` to `v4-executed`), so a graph that compiles is never called one that runs, and with no server it still checks the files on disk and names a missing checkpoint beside the nearest one. `comfy_cli` drives comfy-cli as a second, independent path, and six skills teach the fundamentals, the two workflow formats and how to write a node class. | | [`dsh-deckcraft`](packages/dsh-deckcraft/README.md) | Slides from the chat: four `deck_*` tools over the DeckCraft CLI (MIT OR Apache-2.0). `deck_commands` lists the command ids the build offers, `deck_run` saves a `.deckcraft` in the workspace, `deck_export` renders the slides to PNG so you can look at them. Nothing is hardcoded: DeckCraft's "every button is a command" contract is the API. | +| [`dsh-deliverables`](packages/dsh-deliverables/README.md) | The turn's changed-files card and its Review tab, as a generated fork of the shipped deliverables bundle. Its one behavior change: a PNG/JPEG/GIF/WebP/SVG change is drawn as the picture in the Review tab and its hover preview, instead of "Binary file; changes cannot be shown". Text diffs, deleted files and non-image binaries keep the shipped view. | | [`dsh-diagrams`](packages/dsh-diagrams/README.md) | Mermaid, TikZ and the Diagram Design kit as tabs and as seven `diagram_*` tools. The kit 204 examples and 44 documented types are vendored at a pinned commit and browsable on the index page. Every write, including a self-contained HTML document, is validated before it is stored. A fourth kind, `figure`, goes further: a JSON spec is measured, laid out and routed on the host into one vector figure at a paper's column width, and `reference/figures/` rebuilds two published figures as its benchmark. | | [`dsh-docker`](packages/dsh-docker/README.md) | Docker or Podman as a surface: nine `docker_*` tools over the machine's own CLI, argv-only, with every removal confirmed by repeating the target. `docker_start` launches Docker Desktop or a podman machine and waits for the **daemon**. A Docker tab lists containers and images with their logs, and there is no `exec`, no `system prune` and no free-form `run`. | | [`dsh-editor`](packages/dsh-editor/README.md) | Text and code tabs over a vendored CodeMirror 6, with save/create and a Markdown preview. The preview exports the file as a PDF on the Desktop (the browser on the machine does the printing). Every extension is mapped through a guard, so an older engine opens the document unhighlighted instead of killing the tab. It also backs the `.scd`, diagram-source and research-document editors. | | [`dsh-frontend-craft`](packages/dsh-frontend-craft/README.md) | Front-end design craft: Impeccable's Apache-2.0 corpus vendored at a pinned commit, plus its 61-rule detector built to WebAssembly inside the package. Five `fe_*` tools include `fe_render`, which renders a page in headless Chrome or Edge and measures contrast, tap targets and overflow. There is no `npx impeccable`, no engine download and no network. A Frontend tab shows findings, artifacts and the direction round. | | [`dsh-gittree`](packages/dsh-gittree/README.md) | A read-only History tab: the workspace commits as a graph rail with lanes, merges and PR chips. Each commit lists the files it touched. It never runs a write. | | [`dsh-huggingface`](packages/dsh-huggingface/README.md) | The Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk. `hf_repo` gives one repo's licence, gated flag, weight (the Hub's `used_storage`, labelled as such) and whether this disk already has it — complete, metadata-only, stale or absent; `hf_status` counts the stubs that look cached and cannot load; `hf_cache` verifies and reclaims, with an unconfirmed removal being the CLI's own dry run; `hf_download` reports the weight, refuses over a ceiling, and needs the repo id repeated back. For a repo already cached it also sizes the LOAD — parameters from the weight bytes, the KV cache per token from the checkpoint's own attention heads, and a context table that says FITS against the `freeBytes` you pass — without loading the model. Two skills teach the CLI and the cache layout. Host-only, zero npm dependencies, no bundled engine. | +| [`dsh-hyperframes`](packages/dsh-hyperframes/README.md) | Moving figures: six `anim_*` tools author a composition as HTML, check it, look at its stills and render it to MP4 through the HyperFrames CLI (Apache-2.0). `anim_check` runs the linter and then a real browser audit, passing every finding through with the frames around it; a `browserSkipped` report is never reported as a pass. `anim_scene` places a figure the pack already produced, because HyperFrames has no TeX and no chart library. Every answer names the rung it reached (`a0-source` to `a4-rendered`), and a render that follows a failing check is refused. It never runs `npx` and never installs anything, and three worked UI examples ship as lint-clean projects with a caption file each. | | [`dsh-image`](packages/dsh-image/README.md) | An image viewer that fits, zooms and pans, and reads the source pixel under the pointer. It opens from the Files tab and the Media panel. | | [`dsh-image-upscale`](packages/dsh-image-upscale/README.md) | Four `upscale_*` tools over Real-ESRGAN, through the Python and torch this machine already has. It writes a NEW file and never the original, a manifest batch is a dry run by default, and the weight fetch refuses without `confirm`. Host-only, with no engine bundled. | | [`dsh-media`](packages/dsh-media/README.md) | The pack ffmpeg owner: `media_probe`, `media_run` and `media_frames` over a pinned, SHA-256-verified ffmpeg copy. It also serves the Range routes the video tab streams through. No other package ships ffmpeg. | diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 812a66d..296eb80 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -20,7 +20,7 @@ notice, not a replacement for the files it names. | **platform-design-skills** (upstream of part of the Impeccable corpus) | inside `packages/dsh-frontend-craft/lib/vendor/impeccable/NOTICE.md` | MIT | its notice travels in upstream's `NOTICE.md` | | **p5.js** 1.11.13 | `packages/dsh-proto-lab/lib/vendor/p5.min.js` | **LGPL-2.1** | shipped **unmodified**, with upstream's `LICENSE` beside the bytes and its source pointer in `VERSION.json`. Under LGPL-2.1 §6 you may obtain the corresponding source from at the tag recorded there, or from this repository's `vendor/` build, which copies the file byte for byte | | **CodeMirror 6** and `@codemirror/legacy-modes` | `packages/dsh-editor/lib/vendor/cm6.min.js` | MIT | built here from the pinned packages with the MIT notices kept in the generated banner | -| **Forked harness client bundles** — `@deepseek-ai/dsh-client-ui-sidebar-right`, `…-sidebar-files`, `…-open-in-app` | `packages/dsh-rightbar`, `dsh-rightbar-files`, `dsh-open-in-app` | MIT (DeepSeek) | generated forks carry a banner naming the upstream package, the pinned harness line and every patch; `scripts/tools/sync-vendored.ps1 -Check` proves the copy | +| **Forked harness client bundles** — `@deepseek-ai/dsh-client-ui-sidebar-right`, `…-sidebar-files`, `…-open-in-app`, `…-deliverables` (browser and Node halves) | `packages/dsh-rightbar`, `dsh-rightbar-files`, `dsh-open-in-app`, `dsh-deliverables` | MIT (DeepSeek) | generated forks carry a banner naming the upstream package, the pinned harness line and every patch; `scripts/tools/sync-vendored.ps1 -Check` proves the copy | | **Radiant** @ `59e9f48c` (106 pages, 79 extracted fragment sources) | `packages/dsh-shaders/lib/vendor/radiant/` | MIT | upstream `LICENSE` beside the tree; pages stored byte-identical, fragment sources extracted from them, and `catalog.json` records every file's bytes and sha256. `vendor/radiant/build.mjs --check` re-derives the catalogue from the committed pages **offline**. The 91 gallery previews (22.6 MB) are not vendored | | **shader-skills** @ `e09bc99` (20 GLSL modules, 11 templates, 11 gallery pieces, 14 references) | `packages/dsh-shaders/lib/vendor/shader-skills/` | MIT | upstream `LICENSE` **and `CREDITS.md`** beside the tree, the latter stating that all GLSL is an original implementation with techniques credited to their published sources. `vendor/shader-skills/build.mjs --check` re-derives the dependency closure offline. The gallery `.png` previews are not vendored | | **awesome-glsl** @ `287c2ea` (a curated link index) | `packages/dsh-shaders/lib/vendor/glsl-links/` | MIT | `README.md` and `LICENSE` verbatim, plus `links.json` derived from the markdown and checked against it. This tree contains **no shader code**: it is a list of links | diff --git a/assets/logo/BRAND.md b/assets/logo/BRAND.md index 95ad75c..3c07a6e 100644 --- a/assets/logo/BRAND.md +++ b/assets/logo/BRAND.md @@ -197,16 +197,19 @@ pixels rather than by a hash. Changing the mark means changing `marks.mjs`, then `npm run logo`: the committed SVG is a build product, like the PNGs, so the drawing exists in exactly one place. -The README banner next door (`assets/vncode-banner3.png`, 1280 × 320) is rendered by the same +The README banner next door (`assets/vncode-banner7.png`, 1280 × 320) is rendered by the same folder's `scripts/tools/logo/banner.mjs`: ```sh -npm run banner # rewrite assets/vncode-banner3.png +npm run banner # rewrite assets/vncode-banner7.png npm run banner -- --check # verify its size and the count it carries ``` -It reads the plugin count off `packages/` rather than a number someone has to remember, and -takes its glow, rings and headline colour from the same jade. +It reads the plugin count off `packages/` and the skill count off every bundle's +`skills/` folder rather than a number someone has to remember, and takes its glow, +rings and headline colour from the same jade. The headline's two counts are the only +part of the picture that changes when a plugin or a skill is added: run `npm run banner`, +then `npm run banner -- --check`. ## Licence diff --git a/assets/vncode-banner7.png b/assets/vncode-banner7.png index d6dd82a..e81e5c4 100644 Binary files a/assets/vncode-banner7.png and b/assets/vncode-banner7.png differ diff --git a/docs/PLAN-hyperframes.md b/docs/PLAN-hyperframes.md new file mode 100644 index 0000000..8819ec9 --- /dev/null +++ b/docs/PLAN-hyperframes.md @@ -0,0 +1,248 @@ +# PLAN — `dsh-hyperframes`: moving figures, not videos + +Status: **built.** The plan below was accepted and shipped as `packages/dsh-hyperframes` +(alpha.1): six tools, three skills, three worked UI examples, a 200-assertion check, and +a draft render verified against hyperframes 0.9.106 on this machine. The decisions it +left open were settled by the build — the CLI was exercised through the npx cache +(never `npx` at run time), the framing is product-UI animation with a citable still, and +the tools came first with no Frames tab. Kept as the decision record; the shipped +behaviour lives in `packages/dsh-hyperframes/README.md`. + +## 1. The verdict, in three sentences + +**Interesting — but not as a video feature.** This pack can already photograph a +page (`shot_url`), photograph a real window (`shot_window`), probe and play a video +(`media_probe`, `dsh-video`), and compile a publication figure (`diagram_*`, +`table_write`). What it cannot do is produce a **moving figure whose still frame is +citable, whose numbers come from the same data as the paper, and whose render is the +same bytes on Tuesday as it was on Monday**. That is a scientific artefact that +happens to play; "video" is the delivery format, not the point. + +**A recorder should NOT be built.** Still of an app: `shot_window` (exists). Motion +of an app: `media_run` + ffmpeg (exists, `dsh-media` owns it). Website → editable +scenes: `hyperframes capture` (the CLI's own command). A `rec_*` row would be the +third owner of one job, which is exactly what `ARCHITECTURE.md` forbids. + +**One new package, wrapping the user's own CLI**, the way `dsh-deckcraft` wraps +DeckCraft: no engine vendored, nothing installed, nothing started on its own, and a +`status` tool that is useful on a machine where the CLI is missing — which is this +machine today (§7). + +## 2. What the pack owns today, and what is genuinely missing + +| The job | Owner today | Verdict | +|---|---|---| +| Still of a web page / element | `dsh-screenshot` `shot_url` | done | +| Still of an application window / the screen | `dsh-screenshot` `shot_window` / `shot_screen` | done (Windows) | +| Probe, transcode, play, extract frames | `dsh-media`, `dsh-video` | done | +| A publication figure (TikZ, Mermaid, compiled spec) | `dsh-diagrams` | done | +| A paper table | `dsh-tables` | done (LaTeX PNG too) | +| An HTML page rendered and *measured* | `dsh-frontend-craft` `fe_render` | done | +| A deck, rendered to images | `dsh-deckcraft` | done | +| **An authored, seekable, deterministic render to MP4** | **nobody** | **the gap** | +| **One source that emits a still + a caption + N variants** | **nobody** | **the gap** | + +The gap is narrow and real. Every existing package produces a *picture*; ffmpeg can +only turn pictures into a *recording of something that already happened*. Nothing +here can author time. + +## 3. Why HyperFrames is the right engine to wrap + +Three facts from its own documentation, each of which matters more than "it renders +MP4": + +1. **It was built to be driven by a harness.** `HF_TOOL_CONTEXT` (v1) lets the caller + declare `events` (an NDJSON file the CLI appends `artifact.created` records to, + with absolute paths for every frame and contact sheet), `project-lock` (wait for a + concurrent browser command instead of racing it) and `check-review` + (`findingFrames`: one plain frame per finding, plus `inspect` snippets of the + source that caused it). So a tool can hand back *the picture that failed*, not a + log line. That is the editor's Preview loop, generalised to time. +2. **`snapshot` is the product.** `hyperframes snapshot --at 3,10.5 --json` writes + 1920×1080 PNGs and a contact sheet without rendering video. The review loop is + cheap; the expensive render is last. That is why the still can be the deliverable. +3. **Determinism is a first-class promise.** Every timeline is paused and seeked, + `time = floor(frame)/fps`, and the banned list is enforced by the linter + (`Date.now()`, `requestAnimationFrame`, unseeded `Math.random`, `repeat:-1`, CSS + transitions, network fetches). A figure that can be regenerated is a figure a + reviewer can check. `--docker` is the byte-exact path; we would not drive it. + +And two facts that shape the science layer: + +4. **No math, no chart library.** No LaTeX/KaTeX/MathJax anywhere in 135 docs pages + or the catalog, and no bundled math font. Charts are catalog blocks with the + series hardcoded, or hand-drawn SVG. +5. **The pack already owns both missing halves.** `dsh-diagrams` compiles TikZ and + the figure grammar to vectors; `dsh-tables` sets LaTeX tables and returns a PNG of + the real typesetting. So an equation or a mechanism diagram enters a composition + as **an SVG asset the pack produced**, and HyperFrames only has to move it. + +## 4. The thesis + +> The editor gives you a picture of what you wrote. This gives you a picture of what +> you wrote **at every frame**, and then a file that plays. + +Concretely, one source (`index.html` + `compositions/*.html` + `assets/`) produces: + +- a **poster frame** — a `snapshot --at` of the beat the author chose, citable; +- a **caption file** — alt text, duration, fps, engine version, and the scene list; +- **N variants** — `--variables '{"condition":"treated"}'` or `--batch rows.json`: + the same timing, one render per condition; +- the **MP4** — last, gated, with the check rung named beside it. + +## 5. The package + +Name `dsh-hyperframes`, row `hyperframes`, tools prefixed **`anim_`** — `hf_*` is +already `dsh-huggingface`'s (checked: `packages/dsh-huggingface/lib/tools.js`), and +`anim_` is free. Host half only in phases 0–3. + +| Tool | The CLI behind it | What it answers | Rung | +|---|---|---|---| +| `anim_status` | `--version`, `info`, `doctor --json` | the four facts that fail independently: the CLI, Node ≥ 22, a browser, ffmpeg — and the install line when the CLI is absent. Installs nothing | `a0` | +| `anim_new` | none (our template) | a project inside the workspace: `index.html`, `compositions/`, `assets/`, a README naming the rungs | `a0` | +| `anim_scene` | none (writes HTML) | one scene from a **figure file** (`svg`/`png`) with reveal timing, a caption variable and alt text — the bridge from `dsh-diagrams` / `dsh-tables` / `shot_url` | `a0` | +| `anim_check` | `lint --json`, then `check --json` | findings passed through verbatim, the frames around each finding, and the rung actually reached | `a1`/`a2` | +| `anim_snapshot` | `snapshot --at/--range --review --json` + `HF_TOOL_CONTEXT` | stills and a contact sheet as pictures in the conversation, read from the `events` stream | `a3` | +| `anim_render` | `render --format --quality --fps -o` | the file, its ffprobe facts (duration, fps, size, codec) and the provenance tags the CLI writes | `a4` | + +### The rung ladder (stated on every answer, never rounded up) + +``` +a0-source the project exists and passes the static contract check (no CLI needed) +a1-lint `lint --json` ran with no errors (no browser) +a2-checked `check --json` ran in a browser and is ok (layout / motion / contrast) +a3-stilled `snapshot` wrote frames and the pictures came back +a4-rendered `render` wrote the file, and ffprobe agrees with what was asked +``` + +`anim_render` reports the **last check rung it saw** in the same answer, so +"rendered" is never printed as "correct". A render with a failing check is refused +unless `force: true`, and the refusal names the findings. + +## 6. The science layer (the part no other package can do) + +- **Figures enter as vector assets.** `diagram_write` (figure/TikZ) → SVG in + `assets/`; `table_write` → the LaTeX PNG. A scene then reveals parts of a real + figure in order (`attr:{}` on SVG geometry, never `left`/`width` — the linter + rejects layout-property tweens). +- **Equations are pictures, and that is correct.** HyperFrames has no math support + and no math font. Set the equation with TikZ and place its SVG at the size it was + drawn. Say so in the limits: it will not reflow, and a figure's equation should not. +- **Variants are the methods figure.** One composition, `--variables` per condition, + identical timing — a supplementary figure set that differs only in the thing under + test. +- **Accessibility is a file, not a check.** Every `anim_new` project carries + `caption.md`: the poster's alt text, the transcript, the duration, and the scene + list. A reader without the video still gets the figure and its legend. +- **The numbers stay owned by the data.** A chart's series is written into the scene + at author time from a CSV or a JSON the paper already has; the composition never + becomes the source of a number. + +## 7. What this machine has, measured today + +| Fact | Value | +|---|---| +| Node | `v22.20.0` — meets the CLI's `>= 22` floor | +| `hyperframes` | **MISSING** — not on PATH, not in the npx cache | +| `ffmpeg` / `ffprobe` | `C:\ffmpeg\bin\ffmpeg.exe` — on PATH | +| Browser | `C:\Program Files\Google\Chrome\Application\chrome.exe` | +| `$DSH_HOME/dsh-media/bin` | nothing provisioned (the PATH copy is what would be used) | +| PowerShell | 5.1.26100 | + +So **every rung above `a0` is unproven here until the user installs the CLI.** The +package can be built, checked and shipped without it — the `dsh-deckcraft` precedent +is a 54-assertion check that needs no DeckCraft — but P3 has no honest acceptance +criterion until `npx hyperframes --version` answers on this box. That is a decision +for the user, not something this plan can assume. + +## 8. Policy the row would obey + +**Resolution.** A `hyperframes` binary on `PATH`, or `DSH_HYPERFRAMES_CLI`. **Never +`npx`** — `npx` downloads a package when it is missing, which is an install with a +different name. + +**Env set on every child** (so the row starts no network egress of its own): + +``` +HYPERFRAMES_NO_TELEMETRY=1 DO_NOT_TRACK=1 +HYPERFRAMES_NO_UPDATE_CHECK=1 +HYPERFRAMES_NO_OPTIONAL_INSTALL=1 HYPERFRAMES_NO_AUTO_INSTALL=1 +HYPERFRAMES_NO_CAPTURE_DOTENV=1 HYPERFRAMES_SKIP_SKILLS=1 +HYPERFRAMES_AGENT=1 +HYPERFRAMES_BROWSER_PATH= +``` + +**ffmpeg.** HyperFrames has **no** ffmpeg-path variable (confirmed: none in the CLI +reference). It uses `ffmpeg` from `PATH`, so the row resolves ffmpeg by +`dsh-media`'s rules — `DSH_MEDIA_FFMPEG`, then `PATH`, then +`$DSH_HOME/dsh-media/bin/-/` — and **prepends that directory to the +child's `PATH`**. It reads the same variables instead of importing `dsh-media`'s +files, because a bundle may not import another bundle's files. + +**Subcommands that are never run:** `skills`, `events`, `auth`, `share`, `publish`, +`cloud`, `lambda`, `cloudrun`, `tts`, `models`, `capture`, `browser ensure`, +`init` (it writes `AGENTS.md`/`CLAUDE.md` and installs skills). Renders run locally +only. + +**The rest of the house rules.** argv arrays, never a shell; `cwd` is the project; +a deadline with a tree kill; every output path resolves inside the session +workspace or an `allowRoot` given for that call; `HF_TOOL_CONTEXT` set per call and +its events read **after** exit; a JSON field this build renames is passed through +verbatim, never reconstructed. + +## 9. Risks, and what is done about each + +| Risk | Reality | Response | +|---|---|---| +| The CLI is absent | Measured today | `a0` works; `anim_status` names `npm install -g hyperframes` and stops | +| Render time | 10 s at 1080p30 = 300 headless seeks + an encode; `looks` is CRF 16 | `draft` for iteration, `looks` once, `delivery` for the master; 4K/60 are never defaults | +| A font fetch | The compiler fetches Google Fonts for weights its bundled families lack | name bundled families only; a local `woff2` for anything else; the answer says when a fetch could happen | +| Byte-exactness | "Fonts and Chrome versions differ, so a local render can shift by a pixel" | claim *deterministic given the same engine and fonts*, never "identical everywhere"; `--docker` named as the exact path, not driven | +| The 16 MB composition cap | Documented error `COMPOSITION_TOO_LARGE` | media and data live in `assets/`, referenced by path | +| JSON drift in a young CLI | Findings' inner keys are not documented | read `ok` + counts, pass the rest through; `anim_status` records the version | +| Node floor | `node_version_unsupported` below 22 | reported by `anim_status`, not retried | +| Two browser commands at once | The CLI takes `.hyperframes/project.lock` | `project-lock.waitMs` below our own deadline | + +## 10. Phases, each with an acceptance criterion + +| Phase | What | Accepted when | +|---|---|---| +| **P0** | package skeleton, `anim_status`, the tracked check | the check reaches `a0` / "CLI missing" **on this machine today**, with no CLI installed | +| **P1** | `anim_new`, `anim_scene`, three committed examples (a CSV bar reveal; an SVG mechanism from `dsh-diagrams`; an equation + labels from TikZ) | each example is `a0` offline and carries `caption.md` | +| **P2** | `anim_check`, `anim_snapshot`, `HF_TOOL_CONTEXT` | a real contact sheet comes back as a picture, and a deliberately broken scene returns its finding **with the frame and the source snippet** | +| **P3** | `anim_render`, ffprobe facts, provenance | needs the CLI installed; the MP4's duration/fps/size are read back with ffprobe and match | +| **P4** | the **Frames** tab (storyboard, findings, the still at any time), two reserved routes | the tab draws a contact sheet the agent just made | +| **P5** | skills (`hyperframes-composition`, `hyperframes-motion`, `scientific-animation`), `.dsh-version.json`, installers, README | `check-node-routes.mjs`, `check-client-bundles.mjs`, `check-no-secrets.mjs` green | + +**What is deliberately not built:** a screen recorder; a renderer; a vendored copy of +`@hyperframes/*` (a Node dependency tree plus a browser); a composition editor +(hyperframes' own `preview` is better than anything written here); cloud rendering; +sharing; auth; TTS. + +## 11. Decisions this plan needs from the user + +1. **Install the CLI?** `npm install --global hyperframes` on this machine would make + P3 provable. Without it the package ships honest and stops at `a2`. +2. **The framing** — is the deliverable a *scientific moving figure with a citable + still and variants* (this plan), or social/marketing clips (a different skill set)? +3. **The tab** — tools first and the Frames tab in a later pass (the `dsh-screenshot` + precedent), or the tab in the same pass? +4. **One package or two** — `dsh-hyperframes` recommended; a separate `dsh-recorder` + is the duplication argued against in §1. + +## 12. Files this would add + +``` +packages/dsh-hyperframes/package.json (zero dependencies, node >=22) +packages/dsh-hyperframes/cordis.patch.yml +packages/dsh-hyperframes/lib/index.js the row: one activation line, tools registered +packages/dsh-hyperframes/lib/cli.js resolve the binary, argv builder, spawn, deadlines +packages/dsh-hyperframes/lib/env.js the env policy of §8 + the ffmpeg PATH prepend +packages/dsh-hyperframes/lib/project.js anim_new / anim_scene: the template and the scene writer +packages/dsh-hyperframes/lib/report.js lint/check/snapshot/doctor JSON readers + the rung ladder +packages/dsh-hyperframes/lib/tools.js the six tools +packages/dsh-hyperframes/checks/check-hyperframes.mjs +packages/dsh-hyperframes/skills/… three skills, every example parsed by a check +packages/dsh-hyperframes/README.md one page +.dsh-version.json one entry +``` diff --git a/packages/dsh-deliverables/README.md b/packages/dsh-deliverables/README.md new file mode 100644 index 0000000..a40f75b --- /dev/null +++ b/packages/dsh-deliverables/README.md @@ -0,0 +1,48 @@ +# dsh-deliverables (alpha.1) + +**The turn's deliverables, with an image change drawn as the picture.** A GENERATED fork of the shipped `@deepseek-ai/dsh-client-ui-deliverables` package — its Node half (the `/api/changes.summary`, `/api/changes.diff`, `/api/changes.open` and `/api/present.*` routes) and its browser half (the changed-files card, the presented-file cards, and the right bar's Review tab). + +## Why it exists + +The shipped Review tab compares a turn's file at its start and at its end, and a binary change cannot be compared: it answers **"Binary file; changes cannot be shown"**. A PNG, a JPEG or a GIF is binary, so after a turn that regenerated a README banner the right panel showed that sentence where the picture belongs — with no way to see what changed short of leaving the Review tab and opening the file from Files. + +The fork changes exactly that: when the selected changed file is an image the browser draws, the Review tab renders the file at its turn-end path. The hover preview on the changed-files card does the same, and the counts label says **Image** instead of **binary**. A text diff, a deleted image and every non-image binary keep the shipped behavior. + +## What the patch does + +| Piece | Change | +|---|---| +| Review body | `file.binary === true` and an image suffix → the picture, loaded from the harness's own `/api/file?path=…` route at the workspace-resolved path; otherwise the shipped `FileDiff` | +| Hover preview | the same choice for a single-file card's 500 ms preview | +| Labels | `Counts` and the two stat chips say `Image` for an image suffix | + +The image is drawn at its own aspect inside the pane, with its true pixel size in the caption line; a file that is no longer at that path (a deleted image, a moved workspace) falls back to one sentence. The **open-file** control in the Review header is untouched: it still hands the file to the image tab, which is where the zoom/pan/pixel reader lives. + +## How it plugs in + +`cordis.patch.yml` disables the shipped `ui-deliverables` row and inserts `deliverables` (`dsh-deliverables`). `lib/index.js` and `lib/client.js` are generated by `scripts/tools/sync-vendored.ps1`: the Node half is the core file with its one harness import inlined (a linked package resolves imports from this repository, not from the profile, so a bare `@deepseek-ai/…` import would not load), and the browser half is the core bundle with the module-table id rewritten and the patch list applied. + +## Limits + +- The picture is the **turn-end** file. A deleted image has no bytes to draw and says so. +- Only the suffixes a browser draws are claimed (`png jpg jpeg gif webp avif bmp ico svg`); HEIC/RAW/PSD stay with the shipped sentence, as before. +- The Review tab is still a *comparison*: it does not show a before/after slider, a crop, or a size measurement. That is the image tab's job. +- Nothing here is hand-edited. Re-sync it after bumping the harness line; a patch whose anchor moved fails loudly rather than shipping a fork that silently lost the behavior. + +## Verify + +```sh +powershell -NoProfile -ExecutionPolicy Bypass -File scripts/tools/sync-vendored.ps1 -Check +node packages/dsh-deliverables/checks/check-deliverables.mjs +node scripts/checks/check-client-bundles.mjs +node scripts/checks/check-node-routes.mjs +``` + +## Layout + +``` +cordis.patch.yml bundle layer: disables 'ui-deliverables', inserts 'deliverables' +lib/index.js GENERATED Node half (routes), one import inlined +lib/client.js GENERATED browser half (card + review), image patch applied +checks/ the package's own check: the patch is present and it renders +``` diff --git a/packages/dsh-deliverables/checks/check-deliverables.mjs b/packages/dsh-deliverables/checks/check-deliverables.mjs new file mode 100644 index 0000000..59f252f --- /dev/null +++ b/packages/dsh-deliverables/checks/check-deliverables.mjs @@ -0,0 +1,139 @@ +// check-deliverables.mjs - dsh-deliverables' own contract, driven directly. +// +// This package is a GENERATED fork of the harness's deliverables bundle, so the +// check has two jobs a grep cannot do on its own: +// +// 1. the PATCH is present and is the one this package documents - a review +// body that renders a binary image with the picture, a hover preview that +// agrees, and a card that labels it "Image", with the shipped behaviour +// kept for everything else; +// 2. the ADDED LOGIC behaves: the suffix test, Windows/posix/relative path +// resolution and the `/api/file` URL are extracted from the committed +// bundle and run, so a patch that compiles but resolves `..` wrongly (or +// claims a text file as an image) fails here rather than in the GUI. +// +// It does not start a harness: the routes the fork serves are asserted by their +// presence, and the Review tab's React body needs the slot runtime the shell +// owns. The tracked check-client-bundles.mjs loads every browser bundle the way +// the app does; this check owns the fork's own text and helpers. +// +// Run: node checks/check-deliverables.mjs +import { readFileSync, existsSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import vm from 'node:vm' +import path from 'node:path' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const pkg = path.resolve(here, '..') +const read = (relative) => readFileSync(path.join(pkg, relative), 'utf8') + +let checks = 0 +let failures = 0 +const check = (label, actual, expected) => { + checks += 1 + const ok = expected === undefined ? Boolean(actual) : actual === expected + if (!ok) failures += 1 + console.log((ok ? 'ok ' : 'FAIL ') + label.padEnd(58) + (expected === undefined ? '' : ' ' + JSON.stringify(actual))) + return ok +} + +// -------------------------------------------------------------------------- +// The generated files and their banner +// -------------------------------------------------------------------------- +const clientPath = path.join(pkg, 'lib', 'client.js') +const hostPath = path.join(pkg, 'lib', 'index.js') +check('the generated browser half is committed', existsSync(clientPath)) +check('the generated Node half is committed', existsSync(hostPath)) +const client = read('lib/client.js') +const host = read('lib/index.js') + +check('the browser half carries the generated banner', client.startsWith('// GENERATED - do not edit by hand.')) +check('the Node half carries the generated banner', host.startsWith('// GENERATED - do not edit by hand.')) +check('...and the browser banner names the core it forked', client.includes('@deepseek-ai/dsh-client-ui-deliverables@')) +check('...and lists the image patches', client.includes('draw an image change as the picture')) +check('...including the review-tab patch', client.includes('the review tab shows the picture for a binary image')) +check('...and the hover-preview patch', client.includes('the changed-file hover preview shows the picture')) +check('the Node banner names its inlined import patch', host.includes('inline remoteErrorOf')) + +// -------------------------------------------------------------------------- +// The Node half: the five routes, no harness import, the inlined marker check +// -------------------------------------------------------------------------- +for (const route of ['/api/changes.summary', '/api/changes.diff', '/api/changes.open', '/api/present.open', '/api/present.host']) { + check('the Node half still serves ' + route, host.includes(route)) +} +check('the Node half imports no harness package', /^\s*import\s/m.test(host), false) +check('...because remoteErrorOf is inlined', host.includes('function remoteErrorOf(value)')) +check('...with the marker check the core used', host.includes('value.isDSHRemoteError === true')) +check('the Node half still injects the services the routes need', + ['connection', 'sessionQuery', 'sessionController', 'workspaceFiles', 'fs', 'sandboxPolicy', 'workspaceChanges'] + .every((name) => host.includes('"' + name + '"'))) + +// -------------------------------------------------------------------------- +// The browser half: the patch is wired where the review actually renders +// -------------------------------------------------------------------------- +check('the review body renders ReviewImage for a binary image', + client.includes('file.binary===true&&isReviewImagePath(file.path)?')) +check('...and passes the tab cwd so a relative path resolves', client.includes('(ReviewImage,{path:file.path,cwd:cwd})')) +check('the hover preview renders ReviewImage too', + client.includes('isReviewImagePath(display)')) +check('...and passes its already-resolved display path', client.includes('(ReviewImage,{path:display,cwd:void 0})')) +check('the review header counts an image as Image', client.includes('isReviewImagePath(file.path)?"Image":t(`changes.binary`)')) +check('a single-file card labels an image as Image', client.includes('isReviewImagePath(singleFile.path)?"Image"')) +check('the image body is an img over the harness file route', client.includes('"data-review-image":true') && client.includes('"api/file?path="')) +check('a failed load says so instead of a broken picture', client.includes('This image could not be read from that path.')) +check('the shipped comparison is still the fallback', client.includes('(FileDiff,{state:diffState,split,wrap,t,retry:')) +check('the shipped binary sentence is untouched for non-images', client.includes('t(`diff.binary`)')) + +// -------------------------------------------------------------------------- +// The bundle layer: the core row is off, this package is on +// -------------------------------------------------------------------------- +const layer = read('cordis.patch.yml') +check('the layer disables the shipped row', /-\s+id:\s*ui-deliverables\s*\n\s+disabled:\s*true/.test(layer)) +check('...and inserts this package', /name:\s*'dsh-deliverables'/.test(layer)) +const manifest = JSON.parse(read('package.json')) +check('the manifest carries the bundle layer', manifest.dsh && manifest.dsh.bundle && manifest.dsh.bundle.patch, './cordis.patch.yml') +check('...and is a web client module', manifest.dsh && manifest.dsh.client && manifest.dsh.client.platform, 'web') +check('...waiting for the right-bar service it registers into', + Array.isArray(manifest.dsh.client.inject) && manifest.dsh.client.inject.includes('@deepseek-ai/dsh-client-ui-sidebar-right')) + +// -------------------------------------------------------------------------- +// The added logic, RUN. Extract the helper block the patch inserted and give it +// a browser-shaped `document` to build URLs against. +// -------------------------------------------------------------------------- +const start = client.indexOf('const REVIEW_IMAGE_SUFFIXES=') +const end = client.indexOf('function ReviewImage({path,cwd}){') +check('the image helpers are a contiguous block in the bundle', start >= 0 && end > start) +const helpers = client.slice(start, end) +const sandbox = { URL, document: { baseURI: 'http://127.0.0.1:3080/' } } +const api = vm.runInNewContext( + helpers + '\n;({ isReviewImagePath, reviewImageAbsolute, reviewImageUrl, reviewImageSuffix })', + sandbox, +) + +for (const name of ['a.png', 'b.JPG', 'c.jpeg', 'd.gif', 'e.webp', 'f.avif', 'g.bmp', 'h.ico', 'i.svg', 'nested/dir/j.PNG']) { + check('claims an image: ' + name, api.isReviewImagePath(name), true) +} +for (const name of ['a.txt', 'b.md', 'c.psd', 'd.heic', 'e.raw', 'no-extension', 'dir.png/file.txt', '.png']) { + check('refuses a non-image: ' + name, api.isReviewImagePath(name), false) +} + +check('a Windows drive path is already absolute', + api.reviewImageAbsolute('D:/pictures/a.png', 'C:/work/repo'), 'D:/pictures/a.png') +check('a posix absolute path is left alone', + api.reviewImageAbsolute('/tmp/a.png', '/work/repo'), '/tmp/a.png') +check('a relative path joins the working directory', + api.reviewImageAbsolute('assets/a.png', 'C:/work/repo'), 'C:/work/repo/assets/a.png') +check('...with backslashes normalised on both sides', + api.reviewImageAbsolute('assets\\a.png', 'C:\\work\\repo\\'), 'C:/work/repo/assets/a.png') +check('a `..` segment walks up the working directory', + api.reviewImageAbsolute('../shared/a.png', 'C:/work/repo'), 'C:/work/shared/a.png') +check('a leading `./` is dropped', + api.reviewImageAbsolute('./assets/a.png', 'C:/work/repo'), 'C:/work/repo/assets/a.png') + +const url = api.reviewImageUrl('assets/vncode-banner6.png', 'C:/work/repo') +check('the image URL is the harness file route', url.startsWith('http://127.0.0.1:3080/api/file?path='), true) +check('...carrying the encoded absolute path', + url, 'http://127.0.0.1:3080/api/file?path=' + encodeURIComponent('C:/work/repo/assets/vncode-banner6.png')) + +console.log(failures === 0 ? 'all ' + checks + ' deliverables checks passed' : failures + ' of ' + checks + ' deliverables checks FAILED') +process.exitCode = failures === 0 ? 0 : 1 diff --git a/packages/dsh-deliverables/cordis.patch.yml b/packages/dsh-deliverables/cordis.patch.yml new file mode 100644 index 0000000..3601764 --- /dev/null +++ b/packages/dsh-deliverables/cordis.patch.yml @@ -0,0 +1,22 @@ +# dsh-deliverables bundle layer (alpha). +# +# The pack owns the surface that answers "what changed this turn": the +# changed-files card under a closing reply, the presented-file cards, and the +# Review tab in the right bar. This layer hard-disables the shipped +# `ui-deliverables` row - the Node half (the `/api/changes.*` and +# `/api/present.*` routes) and the browser half (the tab type, the card and the +# review body) - and inserts the pack's own row instead, which carries a +# generated fork of that package. +# +# WHY A FORK: the Review tab refuses a binary change with one sentence, +# "Binary file; changes cannot be shown", and a PNG or a JPEG is binary. The +# only way to draw the picture is to replace that body, and the body belongs to +# this package: disabling the row is what makes exactly one copy run. The patch +# list (and the re-sync command) live in scripts/tools/sync-vendored.ps1; the +# vendored files are generated and must never be hand-edited. +- id: ui-deliverables + disabled: true + +- insert: + - id: deliverables + name: 'dsh-deliverables' diff --git a/packages/dsh-deliverables/lib/client.js b/packages/dsh-deliverables/lib/client.js new file mode 100644 index 0000000..ea09d4d --- /dev/null +++ b/packages/dsh-deliverables/lib/client.js @@ -0,0 +1,25 @@ +// GENERATED - do not edit by hand. +// +// Fork of @deepseek-ai/dsh-client-ui-deliverables@0.2.2-rc.5 (lib/client.js): the module-table id is +// rewritten to "dsh-deliverables", and these patches from scripts\sync-vendored.ps1 +// are applied on top: +// - draw an image change as the picture: the review image helpers +// - the review tab shows the picture for a binary image, the shipped comparison otherwise +// - the changed-file hover preview shows the picture too, once the comparison says binary +// - the review header counts an image change as an image, not as a binary +// - a single-file changed-files card labels an image as an image +// - a changed-files row labels an image as an image +// The pack's bundle layer disables the core row, so this copy is the one that +// runs. Re-sync with: powershell -NoProfile -ExecutionPolicy Bypass -File scripts\sync-vendored.ps1 +// + +window.__ModuleLoader__.load({id:`dsh-deliverables`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _deepseek_ai_dsh_client_store=require("@deepseek-ai/dsh-client-store");let react_jsx_runtime=require("react/jsx-runtime");let react=require("react");let _deepseek_ai_dsh_client_ui_primitives=require("@deepseek-ai/dsh-client-ui-primitives");const CHANGED_FILES_PATH=`/api/changes.summary`;const CHANGES_DIFF_PATH=`/api/changes.diff`;const CHANGES_OPEN_PATH=`/api/changes.open`;const CHANGED_FILES_ROUTE=CHANGED_FILES_PATH.slice(1);const CHANGES_DIFF_ROUTE=CHANGES_DIFF_PATH.slice(1);const CHANGES_OPEN_ROUTE=CHANGES_OPEN_PATH.slice(1);const CHANGES_REVIEW_ADDRESS=`dsh-resource://changes-review/session/`;function isRecord$1(value){return typeof value===`object`&&value!==null&&!Array.isArray(value)}function isChangedFile(value){if(!isRecord$1(value))return false;const{path,display,added,deleted,binary,oversized}=value;return typeof path===`string`&&path.length>0&&typeof display===`string`&&display.length>0&&Number.isSafeInteger(added)&&Number.isSafeInteger(deleted)&&(binary===void 0||binary===true)&&(oversized===void 0||oversized===true)}function isChangesSummary(value){if(!isRecord$1(value))return false;const{turn,files,total,added,deleted}=value;return Number.isSafeInteger(turn)&&turn>=1&&Number.isSafeInteger(total)&&Number.isSafeInteger(added)&&Number.isSafeInteger(deleted)&&Array.isArray(files)&&files.every(isChangedFile)}function isHunk(value){if(!isRecord$1(value))return false;const{oldStart,oldLines,newStart,newLines,lines}=value;return[oldStart,oldLines,newStart,newLines].every(field=>Number.isSafeInteger(field)&&field>=0)&&Array.isArray(lines)&&lines.every(line=>typeof line===`string`&&/^[+ -]/.test(line))}function isChangesDiff(value){if(!isRecord$1(value))return false;const{kind,path,display}=value;if(typeof path!==`string`||path.length===0||typeof display!==`string`||display.length===0)return false;if(kind===`binary`||kind===`oversized`)return true;if(kind!==`text`)return false;const{before,after,hunks,coarse}=value;return typeof before===`boolean`&&typeof after===`boolean`&&typeof coarse===`boolean`&&Array.isArray(hunks)&&hunks.every(isHunk)}function isChangesEvent(value){return isRecord$1(value)&&Number.isSafeInteger(value.turn)&&value.turn>=1}function changesSummaryUrl(sessionId,seq){return`${CHANGED_FILES_ROUTE}?${new URLSearchParams({sessionId,seq:String(seq)})}`}function changesDiffUrl(sessionId,seq,index){return`${CHANGES_DIFF_ROUTE}?${new URLSearchParams({sessionId,seq:String(seq),index:String(index)})}`}function changedFileUrl(sessionId,seq,index){return`${CHANGES_OPEN_ROUTE}?${new URLSearchParams({sessionId,seq:String(seq),index:String(index)})}`}function changesReviewAddress(coordinates){const{sessionId,seq,turn}=coordinates;return`${CHANGES_REVIEW_ADDRESS}${encodeURIComponent(sessionId)}/${seq}/${turn}`}function parseChangesReviewAddress(address){if(!address.startsWith(`dsh-resource://changes-review/session/`))return void 0;const parts=address.slice(38).split(`/`);if(parts.length!==3)return void 0;const[sessionId,seq,turn]=parts;if(sessionId===``||!/^\d+$/.test(seq)||!/^[1-9]\d*$/.test(turn))return void 0;try{return{sessionId:decodeURIComponent(sessionId),seq:Number(seq),turn:Number(turn)}}catch{return}}var HostReadStore=class{policy;state=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)({});lifetime=new AbortController;generation=new AbortController;pending=new Set;constructor(policy){this.policy=policy}async loadUrl(url){const current=this.state.getSnapshot()[url];if(this.lifetime.signal.aborted||current!==void 0&&!this.policy.retryable(current))return;this.state.update(state=>{state[url]=this.policy.loading});const task=this.read(url,AbortSignal.any([this.lifetime.signal,this.generation.signal]));this.pending.add(task);try{await task}finally{this.pending.delete(task)}}reset(){this.generation.abort();this.generation=new AbortController;this.state.set({})}async dispose(){this.lifetime.abort();await Promise.all(this.pending)}async read(url,signal){let next;try{next=await this.policy.decode(await fetch(url,{signal}))}catch{next=this.policy.failed}if(!signal.aborted)this.state.update(state=>{state[url]=next})}};var ChangesDiffStore=class extends HostReadStore{constructor(){super({loading:`loading`,failed:`error`,retryable:state=>state===`error`,decode:async response=>{if(response.status===404)return`missing`;if(!response.ok)return`error`;const value=await response.json();return isChangesDiff(value)?value:`error`}})}load(sessionId,seq,index){return this.loadUrl(changesDiffUrl(sessionId,seq,index))}};var ChangesSummaryStore=class extends HostReadStore{constructor(){super({loading:`loading`,failed:`missing`,retryable:()=>false,decode:async response=>{if(!response.ok)return`missing`;const value=await response.json();return isChangesSummary(value)?value:`missing`}})}load(sessionId,seq){return this.loadUrl(changesSummaryUrl(sessionId,seq))}};const PRESENT_OPEN_PATH=`/api/present.open`;const PRESENT_HOST_PATH=`/api/present.host`;const PRESENT_OPEN_ROUTE=PRESENT_OPEN_PATH.slice(1);const PRESENT_HOST_ROUTE=PRESENT_HOST_PATH.slice(1);function isPresentedHost(value){if(typeof value!==`object`||value===null)return false;const host=value;return typeof host.name===`string`&&typeof host.available===`boolean`&&(host.fileManager===null||host.fileManager===`finder`||host.fileManager===`explorer`||host.fileManager===`directory`)}function isPresentedFile(value){if(typeof value!==`object`||value===null||Array.isArray(value))return false;const{path,description}=value;return typeof path===`string`&&path.trim().length>0&&(description===void 0||typeof description===`string`)}function presentedFileUrl(sessionId,seq,index){return`${PRESENT_OPEN_ROUTE}?${new URLSearchParams({sessionId,seq:String(seq),index:String(index)})}`}function isPresentedData(value){if(typeof value!==`object`||value===null||Array.isArray(value))return false;const{turn,callId,files}=value;return typeof turn===`number`&&Number.isSafeInteger(turn)&&turn>=1&&typeof callId===`string`&&callId.length>0&&Array.isArray(files)}function basename(path){const at=Math.max(path.lastIndexOf(`/`),path.lastIndexOf(`\\`));return at===-1?path:path.slice(at+1)}var PresentedOpenController=class{state=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)({});host=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(null);loading;metadata=new AbortController;lifetime=new AbortController;pending=new Set;open(sessionId,seq,index,action=`open`,application){return this.openUrl(presentedFileUrl(sessionId,seq,index),action,application)}openChanged(sessionId,seq,index,action=`open`,application){return this.openUrl(changedFileUrl(sessionId,seq,index),action,application)}async openUrl(url,action,application){const phase=this.state.getSnapshot()[url];if(this.lifetime.signal.aborted||phase===`opening`||phase===`revealing`)return{kind:`skipped`};this.state.update(state=>{state[url]=action===`open`?`opening`:`revealing`});const task=this.request(url,action,application);this.pending.add(task);try{return await task}finally{this.pending.delete(task)}}async loadHost(){if(this.lifetime.signal.aborted)return;if(this.loading!==void 0)return this.loading;this.host.set(null);const task=this.readHost(AbortSignal.any([this.lifetime.signal,this.metadata.signal]));this.loading=task;this.pending.add(task);try{await task}finally{if(this.loading===task)this.loading=void 0;this.pending.delete(task)}}resetHost(){const wasLoading=this.loading!==void 0;this.metadata.abort();this.metadata=new AbortController;this.loading=void 0;this.host.set(null);if(wasLoading)this.loadHost()}async readHost(signal){let host=`error`;try{const response=await fetch(PRESENT_HOST_ROUTE,{signal});if(response.ok){const value=await response.json();if(isPresentedHost(value))host=value}}catch{host=`error`}if(!signal.aborted)this.host.set(host)}async dispose(){this.lifetime.abort();await Promise.all(this.pending)}async request(url,action,application){const failure=action===`open`?`error`:`revealError`;let phase;try{const target=action===`reveal`?`${url}&action=reveal`:application===void 0?url:`${url}&application=${encodeURIComponent(application)}`;const response=await fetch(target,{method:`POST`,signal:this.lifetime.signal});if(!response.ok)phase=response.status===422?`nativeUnavailable`:failure}catch{phase=failure}if(!this.lifetime.signal.aborted)this.state.update(state=>{if(phase===void 0)Reflect.deleteProperty(state,url);else state[url]=phase});if(this.lifetime.signal.aborted)return{kind:`skipped`};if(phase===void 0)return{kind:action===`open`?`opened`:`revealed`};return{kind:`failed`,failure:action===`reveal`?`revealError`:`openError`}}};const css$4=`._93YTAG_summary{min-width:0;color:inherit;align-items:center;gap:8px;margin-left:8px;font-size:12px;display:flex}._93YTAG_summary>:first-child{flex-shrink:0}._93YTAG_paths{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}._93YTAG_output{border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary);white-space:pre-wrap;overflow-wrap:anywhere;margin:8px 0;padding:12px;font-size:12px}._93YTAG_inspect{color:var(--dsw-alias-link);font:inherit;cursor:pointer;background:0 0;border:none;align-self:flex-start;padding:4px 0;font-size:12px}`;const tagId$4=`@deepseek-ai/dsh-client-ui-deliverables/PresentRow.module.css`;if(typeof document!==`undefined`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(tagId$4)+`]`)===null){const tag=document.createElement(`style`);tag.dataset.plugin=`@deepseek-ai/dsh-client-ui-deliverables`;tag.dataset.pluginCss=tagId$4;tag.textContent=css$4;document.head.appendChild(tag)}var PresentRow_module_css_default={"inspect":`_93YTAG_inspect`,"output":`_93YTAG_output`,"paths":`_93YTAG_paths`,"summary":`_93YTAG_summary`};const noop=()=>void 0;function fileNames(raw){let args;try{args=JSON.parse(raw)}catch{return raw}if(typeof args!==`object`||args===null||!(`files`in args)||!Array.isArray(args.files))return raw;return args.files.flatMap(file=>typeof file===`object`&&file!==null&&`path`in file&&typeof file.path===`string`?[file.path]:[]).join(`, `)}function PresentRow(props){return props.phase===`preparing`?(0,react_jsx_runtime.jsx)(PreparingPresentRow,{...props}):(0,react_jsx_runtime.jsx)(StartedPresentRow,{...props})}function PreparingPresentRow({t}){return(0,react_jsx_runtime.jsx)(`div`,{"data-tool":`present`,"data-state":`preparing`,"aria-label":t(`row.preparing`),children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.DisclosureRow,{title:t(`row.title`),icon:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconDeliverDocRegular,{size:14}),open:false,expandable:false,onToggle:noop,running:true})})}function StartedPresentRow({block,inspect,t}){const settled=`kind`in block;const state=!settled?`running`:block.error?.code===`interrupted`?`stopped`:block.isError?`error`:`ok`;const args=(settled?block.call?.argsRaw:block.argsRaw)??``;const details=(settled?block.content.map(item=>item.type===`text`?item.text:JSON.stringify(item)).join(` +`):``)||(settled&&block.error?`${block.error.name}: ${block.error.code}`:``);const[expanded,setExpanded]=(0,react.useState)(false);return(0,react_jsx_runtime.jsx)(`div`,{"data-tool":`present`,"data-state":state,children:(0,react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.DisclosureRow,{title:t(`row.title`),icon:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconDeliverDocRegular,{size:14}),open:expanded&&details!==``,expandable:details!==``,expandOnRowClick:true,keepContentWhenOpen:true,onToggle:()=>{setExpanded(value=>!value)},collapsedContent:(0,react_jsx_runtime.jsxs)(`span`,{className:PresentRow_module_css_default.summary,children:[(0,react_jsx_runtime.jsx)(`span`,{children:t(`row.${state}`)}),(0,react_jsx_runtime.jsx)(`span`,{className:PresentRow_module_css_default.paths,children:fileNames(args)})]}),children:[(0,react_jsx_runtime.jsx)(`pre`,{className:PresentRow_module_css_default.output,children:details}),inspect&&(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:PresentRow_module_css_default.inspect,onClick:inspect,children:t(`row.inspect`)})]})})}const FILE_ADDRESS_PREFIX=`dsh-resource://file/`;function encodeSegment(segment){return encodeURIComponent(segment).replace(/%3A/gi,`:`)}function encodePath(path){return path.split(`/`).map(encodeSegment).join(`/`)}function sessionFileAddress(sessionId,path){const normalized=path.replace(/\\/g,`/`).replace(/^(?:\.\/)+/,``);return`${FILE_ADDRESS_PREFIX}session/${encodeSegment(sessionId)}/${encodePath(normalized)}`}function isWindowsStylePath(value){return/^[A-Za-z]:[/\\]/.test(value)||value.startsWith(`\\\\`)}function isAbsoluteWorkspacePath(path){return path.startsWith(`/`)||isWindowsStylePath(path)}function resolveWorkspacePath(cwd,path){if(isAbsoluteWorkspacePath(path))return path;if(cwd===void 0||cwd===``)return path;const separator=isWindowsStylePath(cwd)&&cwd.includes(`\\`)?`\\`:`/`;return`${cwd.replace(/[/\\]+$/,``)}${separator}${path.replace(/^(?:\.?[/\\])+/,``)}`}function fileAddressFor(sessionId,cwd,path){const normalized=path.replace(/\\/g,`/`);if(!isAbsoluteWorkspacePath(normalized))return sessionFileAddress(sessionId,normalized);const root=cwd===void 0?``:cwd.replace(/\\/g,`/`).replace(/\/+$/,``);if(root!==``&&normalized===root)return sessionFileAddress(sessionId,``);if(root!==``&&normalized.startsWith(`${root}/`))return sessionFileAddress(sessionId,normalized.slice(root.length+1));return sessionFileAddress(sessionId,normalized)}const css$3=`.IP6KhG_root{--diff-empty-fill:color-mix(in srgb, var(--dsw-alias-interactive-bg-hover) 50%, transparent);box-sizing:border-box;width:100%;min-height:0;color:var(--dsw-alias-label-primary);flex-direction:column;display:flex}.IP6KhG_header{box-sizing:border-box;border-bottom:.5px solid var(--dsw-alias-border-l3);flex:none;align-items:center;gap:6px;height:38px;padding:0 6px 0 8px;display:flex}.IP6KhG_status{color:var(--dsw-alias-label-secondary);align-items:center;gap:12px;margin:0;padding:16px;font-size:13px;display:flex}.IP6KhG_body{min-height:0;font:var(--dsw-font-markdown-code-block);flex-direction:column;flex:auto;padding:8px 0 16px;display:flex;overflow:auto}.IP6KhG_columns{flex:auto;grid-template-columns:minmax(0,1fr) minmax(0,1fr);min-height:0;display:grid}.IP6KhG_column,.IP6KhG_body[data-review-view=unified]:not([data-review-wrap]){grid-template-columns:minmax(max-content,100%);align-content:start;display:grid}.IP6KhG_column{overscroll-behavior:none;min-width:0;overflow-x:scroll}.IP6KhG_column+.IP6KhG_column{border-left:.5px solid var(--dsw-alias-border-l3)}.IP6KhG_sideLine{box-sizing:border-box;white-space:pre;grid-template-columns:3.5em max-content;width:max-content;min-width:100%;min-height:22px;line-height:22px;display:grid}.IP6KhG_note{font:var(--dsw-font-xs-13);color:var(--dsw-alias-label-tertiary);margin:0;padding:4px 16px 8px}.IP6KhG_hunk{margin-bottom:8px}.IP6KhG_hunkHeader{color:var(--dsw-alias-label-tertiary);white-space:pre;padding:4px 16px}.IP6KhG_line{box-sizing:border-box;white-space:pre;grid-template-columns:3.5em 3.5em 1.2em minmax(0,1fr);min-height:22px;line-height:22px;display:grid}.IP6KhG_splitLine{white-space:pre;grid-template-columns:minmax(0,1fr) minmax(0,1fr);min-height:22px;line-height:22px;display:grid}.IP6KhG_cell{box-sizing:border-box;grid-template-columns:3.5em minmax(0,1fr);min-width:0;display:grid}.IP6KhG_cell+.IP6KhG_cell{border-left:.5px solid var(--dsw-alias-border-l3)}.IP6KhG_number{color:var(--dsw-alias-label-tertiary);text-align:right;user-select:none;padding-right:8px}.IP6KhG_sign{text-align:center;user-select:none}.IP6KhG_text{padding-right:16px}.IP6KhG_body[data-review-wrap] .IP6KhG_line,.IP6KhG_body[data-review-wrap] .IP6KhG_splitLine{white-space:pre-wrap}.IP6KhG_body[data-review-wrap] .IP6KhG_text{overflow-wrap:anywhere}.IP6KhG_add{--diff-gutter-fill:var(--dsw-alias-file-diff-added-gutter);--diff-marker:var(--dsw-alias-file-diff-added-marker);background:var(--dsw-alias-file-diff-added-bg)}.IP6KhG_del{--diff-gutter-fill:var(--dsw-alias-file-diff-deleted-gutter);--diff-marker:var(--dsw-alias-file-diff-deleted-marker);background:var(--dsw-alias-file-diff-deleted-bg)}.IP6KhG_add .IP6KhG_number,.IP6KhG_del .IP6KhG_number{background:var(--diff-gutter-fill);color:var(--diff-marker)}.IP6KhG_add .IP6KhG_number:first-child,.IP6KhG_del .IP6KhG_number:first-child{box-shadow:inset 3px 0 0 var(--diff-marker)}.IP6KhG_add .IP6KhG_sign,.IP6KhG_del .IP6KhG_sign{color:var(--diff-marker)}.IP6KhG_context .IP6KhG_text{color:var(--dsw-alias-label-secondary)}.IP6KhG_empty{background:var(--diff-empty-fill)}`;const tagId$3=`@deepseek-ai/dsh-client-ui-deliverables/FileDiff.module.css`;if(typeof document!==`undefined`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(tagId$3)+`]`)===null){const tag=document.createElement(`style`);tag.dataset.plugin=`@deepseek-ai/dsh-client-ui-deliverables`;tag.dataset.pluginCss=tagId$3;tag.textContent=css$3;document.head.appendChild(tag)}var FileDiff_module_css_default={"add":`IP6KhG_add`,"body":`IP6KhG_body`,"cell":`IP6KhG_cell`,"column":`IP6KhG_column`,"columns":`IP6KhG_columns`,"context":`IP6KhG_context`,"del":`IP6KhG_del`,"empty":`IP6KhG_empty`,"header":`IP6KhG_header`,"hunk":`IP6KhG_hunk`,"hunkHeader":`IP6KhG_hunkHeader`,"line":`IP6KhG_line`,"note":`IP6KhG_note`,"number":`IP6KhG_number`,"root":`IP6KhG_root`,"sideLine":`IP6KhG_sideLine`,"sign":`IP6KhG_sign`,"splitLine":`IP6KhG_splitLine`,"status":`IP6KhG_status`,"text":`IP6KhG_text`};const MAX_RENDERED_LINES=5e3;function highlightedSide(rows,side,highlighter){const source=rows.flatMap(row=>{const no=row[side];return no===void 0?[]:[{no,text:row.text}]});if(source.length===0)return new Map;const highlighted=highlighter(source.map(line=>line.text).join(` +`));if(highlighted===void 0)return void 0;return new Map(source.map((line,index)=>{return[line.no,highlighted[index]??[]]}))}function hunkHighlights(hunk,highlighter){const rows=hunkRows(hunk);return{old:highlightedSide(rows,`old`,highlighter),new:highlightedSide(rows,`new`,highlighter)}}function DiffText({text,spans}){return(0,react_jsx_runtime.jsx)(`span`,{className:FileDiff_module_css_default.text,"data-diff-code":spans===void 0?void 0:``,children:spans===void 0?text:spans.map((span,index)=>(0,react_jsx_runtime.jsx)(`span`,{style:span.style,children:span.text},index))})}function hunkRows(hunk){let oldNo=hunk.oldStart;let newNo=hunk.newStart;return hunk.lines.map(line=>{const text=line.slice(1);switch(line[0]){case`+`:return{kind:`add`,old:void 0,new:newNo++,text};case`-`:return{kind:`del`,old:oldNo++,new:void 0,text};default:return{kind:`context`,old:oldNo++,new:newNo++,text}}})}function splitRows(hunk){const rows=[];let dels=[];let adds=[];const flush=()=>{for(let at=0;atkept[at]!==hunk)}}function noteOf(diff){if(!diff.before)return`diff.created`;if(!diff.after)return`diff.deleted`;if(diff.hunks.length===0)return`diff.unchanged`}const REVIEW_IMAGE_SUFFIXES=new Set(["png","jpg","jpeg","gif","webp","avif","bmp","ico","svg"]); +function reviewImageSuffix(path){const text=String(path===void 0?"":path).replace(/\\/g,"/");const at=text.lastIndexOf("/");const name=at<0?text:text.slice(at+1);const dot=name.lastIndexOf(".");return dot<=0?"":name.slice(dot+1).toLowerCase()} +function isReviewImagePath(path){return REVIEW_IMAGE_SUFFIXES.has(reviewImageSuffix(path))} +function reviewImageAbsolute(path,cwd){const raw=String(path===void 0?"":path).replace(/\\/g,"/");if(/^(?:[A-Za-z]:\/|\/)/.test(raw))return raw;const base=String(cwd===void 0?"":cwd).replace(/\\/g,"/").replace(/\/+$/,"");const joined=(base===""?raw:base+"/"+raw.replace(/^\.\//,"")).split("/");const parts=[];for(const part of joined){if(part===""&&parts.length===0){parts.push("");continue}if(part===".")continue;if(part===".."){if(parts.length>1)parts.pop();continue}parts.push(part)}return parts.join("/")} +function reviewImageUrl(path,cwd){const base=typeof document==="undefined"?"http://dsh.invalid/":document.baseURI;return new URL("api/file?path="+encodeURIComponent(reviewImageAbsolute(path,cwd)),base).href} +function ReviewImage({path,cwd}){const [isFailed,setFailed]=(0,react.useState)(false);const [size,setSize]=(0,react.useState)("");const url=reviewImageUrl(path,cwd);if(isFailed)return(0,react_jsx_runtime.jsx)("p",{className:FileDiff_module_css_default.status,children:"This image could not be read from that path."});return(0,react_jsx_runtime.jsxs)("div",{className:FileDiff_module_css_default.root,"data-review-image":true,style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"10px",minHeight:0,overflow:"auto",padding:"16px",flex:"1",width:"100%",boxSizing:"border-box"},children:[(0,react_jsx_runtime.jsx)("img",{src:url,alt:String(path===void 0?"":path),onLoad:event=>{const image=event.currentTarget;setSize(String(image.naturalWidth)+" x "+String(image.naturalHeight))},onError:()=>{setFailed(true)},style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 0 0 .5px rgba(0,0,0,.25)"}}),(0,react_jsx_runtime.jsx)("p",{className:FileDiff_module_css_default.status,style:{margin:0},children:(size===""?"":size+" \u00b7 ")+String(path===void 0?"":path)})]})} +function FileDiff({state,split,wrap,retry,t}){if(state===void 0||state===`loading`)return(0,react_jsx_runtime.jsx)(`p`,{className:FileDiff_module_css_default.status,role:`status`,children:t(`diff.loading`)});if(state===`missing`)return(0,react_jsx_runtime.jsx)(`p`,{className:FileDiff_module_css_default.status,children:t(`diff.missing`)});if(state===`error`)return(0,react_jsx_runtime.jsxs)(`div`,{className:FileDiff_module_css_default.status,children:[(0,react_jsx_runtime.jsx)(`span`,{children:t(`diff.error`)}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button,{size:`sm`,onClick:retry,children:t(`presented.retry`)})]});if(state.kind===`binary`)return(0,react_jsx_runtime.jsx)(`p`,{className:FileDiff_module_css_default.status,children:t(`diff.binary`)});if(state.kind===`oversized`)return(0,react_jsx_runtime.jsx)(`p`,{className:FileDiff_module_css_default.status,children:t(`diff.oversized`)});const oneSided=state.hunks.some(hunk=>hunk.lines.some(line=>line.startsWith(`+`)))!==state.hunks.some(hunk=>hunk.lines.some(line=>line.startsWith(`-`)));return(0,react_jsx_runtime.jsx)(TextDiff,{diff:state,split:split&&!oneSided,wrap,t})}function splitRowKind(row){return row.left?.kind===`del`?`del`:row.right?.kind===`add`?`add`:`context`}function hunkHeader(hunk){return`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`}function SplitColumns({hunks,highlights}){const paired=(0,react.useMemo)(()=>hunks.map(hunk=>({header:hunkHeader(hunk),rows:splitRows(hunk)})),[hunks]);const columns=(0,react.useRef)({left:null,right:null});const offsets=(0,react.useRef)({left:{scrollLeft:0,scrollTop:0},right:{scrollLeft:0,scrollTop:0}});const follow=side=>event=>{const peer=side===`left`?`right`:`left`;const other=columns.current[peer];if(other===null)return;for(const axis of[`scrollLeft`,`scrollTop`]){const value=event.currentTarget[axis];if(offsets.current[side][axis]===value)continue;offsets.current[side][axis]=value;other[axis]=value;offsets.current[peer][axis]=other[axis]}};return(0,react_jsx_runtime.jsx)(`div`,{className:FileDiff_module_css_default.columns,children:[`left`,`right`].map(side=>(0,react_jsx_runtime.jsx)(`div`,{className:FileDiff_module_css_default.column,"data-diff-side":side,ref:element=>{columns.current[side]=element},onScroll:follow(side),children:paired.map((hunk,position)=>(0,react_jsx_runtime.jsxs)(`section`,{className:FileDiff_module_css_default.hunk,children:[(0,react_jsx_runtime.jsx)(`div`,{className:FileDiff_module_css_default.hunkHeader,"data-diff-hunk-header":true,children:hunk.header}),hunk.rows.map((row,at)=>{const cell=row[side];const spans=cell===void 0?void 0:highlights[position]?.[side===`left`?`old`:`new`]?.get(cell.no);return(0,react_jsx_runtime.jsxs)(`div`,{className:`${FileDiff_module_css_default.sideLine} ${cell===void 0?FileDiff_module_css_default.empty:FileDiff_module_css_default[cell.kind]}`,"data-diff-line":splitRowKind(row),children:[(0,react_jsx_runtime.jsx)(`span`,{className:FileDiff_module_css_default.number,children:cell?.no??``}),(0,react_jsx_runtime.jsx)(DiffText,{text:cell?.text??``,spans})]},at)})]},position))},side))})}function TextDiff({diff,split,wrap,t}){const note=noteOf(diff);const{hunks,truncated}=(0,react.useMemo)(()=>renderedHunks(diff.hunks),[diff.hunks]);const highlighter=(0,_deepseek_ai_dsh_client_ui_primitives.useCodeHighlighter)((0,_deepseek_ai_dsh_client_ui_primitives.languageForPath)(diff.path));const highlights=(0,react.useMemo)(()=>hunks.map(hunk=>hunkHighlights(hunk,highlighter)),[hunks,highlighter]);return(0,react_jsx_runtime.jsxs)(`div`,{className:FileDiff_module_css_default.body,"data-review-view":split?`split`:`unified`,"data-review-wrap":wrap||void 0,children:[note!==void 0&&(0,react_jsx_runtime.jsx)(`p`,{className:FileDiff_module_css_default.note,"data-diff-note":hunks.length===0?`empty`:`metadata`,children:t(note)}),diff.coarse&&(0,react_jsx_runtime.jsx)(`p`,{className:FileDiff_module_css_default.note,"data-diff-coarse":true,children:t(`diff.coarse`)}),truncated&&(0,react_jsx_runtime.jsx)(`p`,{className:FileDiff_module_css_default.note,"data-diff-truncated":true,children:t(`diff.truncated`,{count:String(5e3)})}),split&&!wrap?(0,react_jsx_runtime.jsx)(SplitColumns,{hunks,highlights}):hunks.map((hunk,position)=>{const highlighted=highlights[position];return(0,react_jsx_runtime.jsxs)(`section`,{className:FileDiff_module_css_default.hunk,children:[(0,react_jsx_runtime.jsx)(`div`,{className:FileDiff_module_css_default.hunkHeader,"data-diff-hunk-header":true,children:hunkHeader(hunk)}),split?splitRows(hunk).map((row,at)=>(0,react_jsx_runtime.jsxs)(`div`,{className:FileDiff_module_css_default.splitLine,"data-diff-line":splitRowKind(row),children:[(0,react_jsx_runtime.jsxs)(`span`,{className:`${FileDiff_module_css_default.cell} ${row.left===void 0?FileDiff_module_css_default.empty:FileDiff_module_css_default[row.left.kind]}`,children:[(0,react_jsx_runtime.jsx)(`span`,{className:FileDiff_module_css_default.number,children:row.left?.no??``}),(0,react_jsx_runtime.jsx)(DiffText,{text:row.left?.text??``,spans:row.left===void 0?void 0:highlighted?.old?.get(row.left.no)})]}),(0,react_jsx_runtime.jsxs)(`span`,{className:`${FileDiff_module_css_default.cell} ${row.right===void 0?FileDiff_module_css_default.empty:FileDiff_module_css_default[row.right.kind]}`,children:[(0,react_jsx_runtime.jsx)(`span`,{className:FileDiff_module_css_default.number,children:row.right?.no??``}),(0,react_jsx_runtime.jsx)(DiffText,{text:row.right?.text??``,spans:row.right===void 0?void 0:highlighted?.new?.get(row.right.no)})]})]},at)):hunkRows(hunk).map((row,at)=>(0,react_jsx_runtime.jsxs)(`div`,{className:`${FileDiff_module_css_default.line} ${FileDiff_module_css_default[row.kind]}`,"data-diff-line":row.kind,children:[(0,react_jsx_runtime.jsx)(`span`,{className:FileDiff_module_css_default.number,children:row.old??``}),(0,react_jsx_runtime.jsx)(`span`,{className:FileDiff_module_css_default.number,children:row.new??``}),(0,react_jsx_runtime.jsx)(`span`,{className:FileDiff_module_css_default.sign,children:row.kind===`add`?`+`:row.kind===`del`?`-`:` `}),(0,react_jsx_runtime.jsx)(DiffText,{text:row.text,spans:row.kind===`add`?highlighted?.new?.get(row.new):highlighted?.old?.get(row.old)})]},at))]},position)})]})}const SURFACE_EVENT_TYPES=new Set([`system/message`,`developer/message`,`user/message`,`assistant/message`,`tool/result`]);function isSurfaceEvent(event){if(!SURFACE_EVENT_TYPES.has(event.type))return false;return event.surfaceOp!==void 0}function isAppendSurfaceEvent(event){return isSurfaceEvent(event)&&event.surfaceOp===`append`}function mutationPath(name,argsRaw){let args;try{args=JSON.parse(argsRaw)}catch{return null}if(!isRecord(args))return null;switch(name){case`write`:return typeof args.content===`string`?pathValue(args.file_path):null;case`edit`:return validEditArgs(args)?pathValue(args.file_path):null;case`str_replace_editor`:return editorMutationPath(args);default:return null}}function validEditArgs(args){return typeof args.old_string===`string`&&args.old_string.length>0&&typeof args.new_string===`string`&&args.old_string!==args.new_string&&(args.replace_all===void 0||typeof args.replace_all===`boolean`)}function editorMutationPath(args){const path=pathValue(args.path);if(path===null)return null;switch(args.command){case`create`:return typeof args.file_text===`string`?path:null;case`str_replace`:return typeof args.old_str===`string`&&args.old_str.length>0&&(args.new_str===void 0||typeof args.new_str===`string`)?path:null;case`insert`:return typeof args.insert_line===`number`&&Number.isInteger(args.insert_line)&&args.insert_line>=0&&typeof args.new_str===`string`?path:null;default:return null}}function pathValue(value){return typeof value===`string`&&value.trim().length>0?value:null}function mutationResultPath(argumentPath,meta){if(!isRecord(meta)||!Object.hasOwn(meta,`path`))return argumentPath;if(typeof meta.path===`string`&&isAbsoluteWorkspacePath(meta.path))return meta.path;return isAbsoluteWorkspacePath(argumentPath)?argumentPath:null}function isRecord(value){return typeof value===`object`&&value!==null&&!Array.isArray(value)}function producedForClosing(data){if(data===void 0)return[];const paths=[];const seen=new Set;for(const produced of data.produced){if(seen.has(produced.path))continue;seen.add(produced.path);paths.push(produced.path)}return paths}function selectProducedFiles(owner){const paths=producedForClosing(owner.turn.data.get(`deliverables`));return paths.length===0?null:paths}const deliverablesDefinition={kind:`deliverables`,match:event=>{if(event.type===`turn/start`)return{id:String(event.data.turn),role:`start`};if(event.type===`tool/call`)return{id:String(event.data.turn),role:`update`};if(event.type===`deliverables/presented`)return isPresentedData(event.data)?{id:String(event.data.turn),role:`update`}:null;if(event.type===`workspace/changes`)return isChangesEvent(event.data)?{id:String(event.data.turn),role:`update`}:null;if(event.type===`tool/result`&&isAppendSurfaceEvent(event))return{id:String(event.data.turn),role:`update`};return null},start:(_context,match)=>{if(match.event.type!==`turn/start`)throw new Error(`deliverables start requires turn/start`);return{turn:match.event.data.turn,calls:new Map,produced:[]}},update:(context,match)=>{if(match.event.type===`workspace/changes`)return{...context.state,changes:{seq:match.event.seq}};if(match.event.type===`deliverables/presented`){const{files}=match.event.data;const seq=match.event.seq;const presented=[];for(let index=0;index{if(scope!==`turn`||context.state===void 0)return null;if(previous?.kind===`turn`&&previous.turn===context.state.turn&&previous.key===`deliverables`&&previous.value.produced===context.state.produced&&previous.value.presented===context.state.presented&&previous.value.changes===context.state.changes)return previous;return{kind:`turn`,turn:context.state.turn,key:`deliverables`,value:{produced:context.state.produced,...context.state.presented===void 0?{}:{presented:context.state.presented},...context.state.changes===void 0?{}:{changes:context.state.changes}}}}};function changesForClosing(owner){return owner.turn.data.get(`deliverables`)?.changes??null}function presentedForClosing(owner){const files=new Map;for(const file of owner.turn.data.get(`deliverables`)?.presented??[])files.set(file.path,file);return[...files.values()]}function producedFileMentions(paths,openFile,label,operations=[],getFileTriggerProps){return{resolve(value){const matches=new Set(paths.filter(path=>path===value||basename(path)===value));for(const operation of operations)if(operation.argumentPath===value)matches.add(operation.path);const path=matches.size===1?matches.values().next().value:void 0;if(path===void 0)return void 0;const contextMenuProps=getFileTriggerProps?.(path);return{open:()=>{openFile(path)},label:label(path),title:path,...contextMenuProps===void 0?{}:{contextMenuProps}}}}}const css$2=`.hz8-rW_card{--changes-fill:var(--dsw-alias-card-fill);--changes-hover:var(--dsw-alias-card-fill-hover);border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-bg-layer-1);min-width:0;color:var(--dsw-alias-label-primary);flex-direction:column;margin-top:4px;display:flex;overflow:hidden}.hz8-rW_card[data-single=true]{border-color:var(--dsw-alias-border-l1)}.hz8-rW_header{box-sizing:border-box;background:var(--changes-fill);width:100%;min-width:0;height:60px;color:inherit;font:inherit;text-align:left;border:0;align-items:center;gap:10px;margin:0;padding:8px 10px;display:flex}button.hz8-rW_header{cursor:pointer;transition:background-color .12s}button.hz8-rW_header:focus-visible{background:var(--changes-hover)}@media (hover:hover){button.hz8-rW_header:hover:not(:disabled){background:var(--changes-hover)}}button.hz8-rW_header:focus-visible{box-shadow:inset 0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline:none}button.hz8-rW_header:disabled{cursor:progress}.hz8-rW_tile{box-sizing:border-box;border:.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-card-tile-fill);border-radius:10px;flex:none;place-items:center;width:40px;height:40px;display:grid}.hz8-rW_titles{flex-direction:column;flex:1;min-width:0;display:flex}.hz8-rW_title{text-overflow:ellipsis;white-space:nowrap;font-size:13px;font-weight:500;line-height:20px;overflow:hidden}.hz8-rW_stat{color:var(--dsw-alias-label-tertiary);font-size:10px;line-height:16px;display:inline-flex}.hz8-rW_statCounts{font-family:var(--ds-font-family-code);gap:6px;display:inline-flex}.hz8-rW_previewHint,.hz8-rW_header:focus-visible .hz8-rW_statCounts{display:none}@media (hover:hover){.hz8-rW_header:hover .hz8-rW_statCounts{display:none}}.hz8-rW_header:focus-visible .hz8-rW_previewHint{display:inline}@media (hover:hover){.hz8-rW_header:hover .hz8-rW_previewHint{display:inline}}.hz8-rW_stat[data-error=true],.hz8-rW_counts[data-error=true]{color:var(--dsw-alias-state-error-primary)}.hz8-rW_added{color:var(--dsw-alias-state-success-primary)}.hz8-rW_deleted{color:var(--dsw-alias-state-error-primary)}.hz8-rW_list{border-top:.5px solid var(--dsw-alias-border-l2);margin:0;padding:0;list-style:none}.hz8-rW_row{box-sizing:border-box;width:100%;min-width:0;min-height:24px;color:var(--dsw-alias-label-tertiary);cursor:pointer;font-family:var(--ds-font-family-code);text-align:left;background:0 0;border:0;justify-content:space-between;align-items:center;gap:10px;margin:0;padding:7px 18px 7px 14px;font-size:11px;line-height:18px;display:flex}.hz8-rW_row:focus-visible{background:var(--dsw-alias-interactive-bg-hover)}@media (hover:hover){.hz8-rW_row:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}}.hz8-rW_row:focus-visible{box-shadow:inset 0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline:none}.hz8-rW_row:disabled{cursor:progress}.hz8-rW_path{min-width:0;font-family:var(--dsw-font-family);text-overflow:ellipsis;white-space:nowrap;font-size:12px;overflow:hidden}.hz8-rW_counts{white-space:nowrap;color:var(--dsw-alias-label-tertiary);flex:none;gap:6px;display:inline-flex}.hz8-rW_toggle{box-sizing:border-box;width:100%;color:var(--dsw-alias-label-tertiary);cursor:pointer;font:inherit;text-align:left;background:0 0;border:0;justify-content:flex-start;align-items:center;gap:4px;margin:0;padding:10px 18px 10px 14px;font-size:12px;line-height:18px;display:inline-flex}@media (hover:hover){.hz8-rW_toggle:hover{background:var(--dsw-alias-interactive-bg-hover)}}.hz8-rW_toggle svg{flex:none;width:14px;height:14px}@media (pointer:coarse){.hz8-rW_row,.hz8-rW_toggle{min-height:44px}}.hz8-rW_preview{max-height:100%;overflow:hidden}.hz8-rW_previewPath{min-width:0;color:var(--dsw-alias-label-tertiary);font-family:var(--ds-font-family-code);white-space:nowrap;flex:auto;font-size:12px;line-height:20px;overflow:auto hidden}.hz8-rW_preview [data-diff-note=metadata],.hz8-rW_preview [data-diff-hunk-header]{display:none}`;const tagId$2=`@deepseek-ai/dsh-client-ui-deliverables/ChangedFiles.module.css`;if(typeof document!==`undefined`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(tagId$2)+`]`)===null){const tag=document.createElement(`style`);tag.dataset.plugin=`@deepseek-ai/dsh-client-ui-deliverables`;tag.dataset.pluginCss=tagId$2;tag.textContent=css$2;document.head.appendChild(tag)}var ChangedFiles_module_css_default={"added":`hz8-rW_added`,"card":`hz8-rW_card`,"counts":`hz8-rW_counts`,"deleted":`hz8-rW_deleted`,"header":`hz8-rW_header`,"list":`hz8-rW_list`,"path":`hz8-rW_path`,"preview":`hz8-rW_preview`,"previewHint":`hz8-rW_previewHint`,"previewPath":`hz8-rW_previewPath`,"row":`hz8-rW_row`,"stat":`hz8-rW_stat`,"statCounts":`hz8-rW_statCounts`,"tile":`hz8-rW_tile`,"title":`hz8-rW_title`,"titles":`hz8-rW_titles`,"toggle":`hz8-rW_toggle`};const COLLAPSED_ROWS=4;const GROUPED$1=new Intl.NumberFormat(`en-US`);function Counts$1({added,deleted,t}){return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ChangedFiles_module_css_default.added,children:t(`changes.added`,{count:GROUPED$1.format(added)})}),(0,react_jsx_runtime.jsx)(`span`,{className:ChangedFiles_module_css_default.deleted,children:t(`changes.deleted`,{count:GROUPED$1.format(deleted)})})]})}function ChangedFiles({changes,cwd,openReview,t,sessionId,useChangesDiff,loadChangesDiff}){const cardRef=(0,react.useRef)(null);const pathDescriptionId=(0,react.useId)();const[expanded,setExpanded]=(0,react.useState)(false);const singleFile=changes.total===1?changes.files[0]:void 0;const foldable=changes.files.length>COLLAPSED_ROWS;const rows=foldable&&!expanded?changes.files.slice(0,COLLAPSED_ROWS):changes.files;const header=(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:ChangedFiles_module_css_default.header,"aria-label":singleFile===void 0?t(`changes.openReview`):t(`changes.viewDiff`,{name:singleFile.display}),"aria-describedby":singleFile===void 0?void 0:pathDescriptionId,onClick:()=>{openReview(0)},children:[(0,react_jsx_runtime.jsx)(`span`,{className:ChangedFiles_module_css_default.tile,children:singleFile===void 0?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.FileTypeIcon,{kind:`code`,size:20}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.FileTypeIcon,{path:singleFile.path,size:20})}),(0,react_jsx_runtime.jsxs)(`span`,{className:ChangedFiles_module_css_default.titles,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ChangedFiles_module_css_default.title,children:singleFile===void 0?t(`changes.title`,{count:String(changes.total)}):t(`changes.singleTitle`,{name:basename(singleFile.path)})}),(0,react_jsx_runtime.jsxs)(`span`,{className:ChangedFiles_module_css_default.stat,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ChangedFiles_module_css_default.statCounts,children:singleFile?.binary===true?(isReviewImagePath(singleFile.path)?"Image":t(`changes.binary`)):singleFile?.oversized===true?t(`changes.oversized`):(0,react_jsx_runtime.jsx)(Counts$1,{t,added:changes.added,deleted:changes.deleted})}),(0,react_jsx_runtime.jsx)(`span`,{className:ChangedFiles_module_css_default.previewHint,children:t(`presented.preview`)})]})]})]});return(0,react_jsx_runtime.jsxs)(`div`,{ref:cardRef,className:ChangedFiles_module_css_default.card,"data-changed-files":true,"data-single":singleFile!==void 0||void 0,children:[singleFile===void 0?header:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.HoverCard,{variant:`preview`,widthAnchorRef:cardRef,openDelayMs:500,anchor:header,content:(0,react_jsx_runtime.jsx)(ChangedFilePreview,{sessionId,seq:changes.seq,index:0,display:resolveWorkspacePath(cwd,singleFile.path),useChangesDiff,loadChangesDiff,t})}),(0,react_jsx_runtime.jsx)(`span`,{id:pathDescriptionId,hidden:true,children:resolveWorkspacePath(cwd,singleFile.path)})]}),singleFile===void 0&&(0,react_jsx_runtime.jsx)(`ul`,{className:ChangedFiles_module_css_default.list,children:rows.map((file,index)=>(0,react_jsx_runtime.jsxs)(`li`,{children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.HoverCard,{variant:`preview`,widthAnchorRef:cardRef,openDelayMs:500,content:(0,react_jsx_runtime.jsx)(ChangedFilePreview,{sessionId,seq:changes.seq,index,display:resolveWorkspacePath(cwd,file.path),useChangesDiff,loadChangesDiff,t}),anchor:(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:ChangedFiles_module_css_default.row,"aria-label":t(`changes.viewDiff`,{name:file.display}),"aria-describedby":`${pathDescriptionId}-${index}`,onClick:()=>{openReview(index)},children:[(0,react_jsx_runtime.jsx)(`span`,{className:ChangedFiles_module_css_default.path,children:file.display}),(0,react_jsx_runtime.jsx)(`span`,{className:ChangedFiles_module_css_default.counts,children:file.binary===true?(isReviewImagePath(file.path)?"Image":t(`changes.binary`)):file.oversized===true?t(`changes.oversized`):(0,react_jsx_runtime.jsx)(Counts$1,{t,added:file.added,deleted:file.deleted})})]})}),(0,react_jsx_runtime.jsx)(`span`,{id:`${pathDescriptionId}-${index}`,hidden:true,children:resolveWorkspacePath(cwd,file.path)})]},file.display))}),foldable&&(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:ChangedFiles_module_css_default.toggle,"aria-expanded":expanded,"aria-label":t(expanded?`changes.collapseAria`:`changes.expandAria`,{count:String(changes.files.length)}),onClick:()=>{setExpanded(value=>!value)},children:[(0,react_jsx_runtime.jsx)(`span`,{children:t(expanded?`changes.collapse`:`changes.all`,{count:String(changes.files.length)})}),expanded?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconChevronUpOutlineRegular,{}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconChevronDownOutlineRegular,{})]})]})}function ChangedFilePreview({sessionId,seq,index,display,useChangesDiff,loadChangesDiff,t}){const state=useChangesDiff(value=>value[changesDiffUrl(sessionId,seq,index)]);(0,react.useEffect)(()=>{if(state===void 0)loadChangesDiff(sessionId,seq,index)},[state,sessionId,seq,index,loadChangesDiff]);return(0,react_jsx_runtime.jsxs)(`div`,{className:`${FileDiff_module_css_default.root} ${ChangedFiles_module_css_default.preview}`,"data-changes-hover-preview":true,children:[(0,react_jsx_runtime.jsx)(`div`,{className:FileDiff_module_css_default.header,children:(0,react_jsx_runtime.jsx)(`span`,{className:ChangedFiles_module_css_default.previewPath,"data-changes-preview-path":true,children:display})}),((state!==void 0&&state!=="loading"&&state!=="missing"&&state!=="error"&&state.kind==="binary"&&isReviewImagePath(display))?(0,react_jsx_runtime.jsx)(ReviewImage,{path:display,cwd:void 0}):(0,react_jsx_runtime.jsx)(FileDiff,{state,split:false,wrap:false,t,retry:()=>{loadChangesDiff(sessionId,seq,index)}}))]})}const css$1=`.nyYjTG_root{--deliverable-fill:var(--dsw-alias-card-fill);--deliverable-hover:var(--dsw-alias-card-fill-hover);flex-direction:column;gap:16px;min-width:0;margin-top:4px;display:flex;container-type:inline-size}.nyYjTG_root[data-after-changes=true]{margin-top:0}.nyYjTG_hostStatus{color:var(--dsw-alias-label-secondary);align-items:center;gap:8px;font-size:12px;line-height:18px;display:flex}.nyYjTG_presented{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;min-width:0;display:grid}.nyYjTG_presented[data-single=true]{grid-template-columns:minmax(0,1fr)}.nyYjTG_file{box-sizing:border-box;border:.5px solid var(--dsw-alias-border-l1);border-radius:var(--dsw-radius-lg);background:var(--deliverable-fill);min-width:0;height:60px;color:var(--dsw-alias-label-primary);align-items:center;gap:10px;padding:8px 10px;transition:background-color .12s;display:flex;position:relative;overflow:hidden}@media (hover:hover){.nyYjTG_file:hover{background:var(--deliverable-hover)}}.nyYjTG_cardPreview{z-index:1;border-radius:inherit;cursor:pointer;background:0 0;border:0;width:100%;padding:0;position:absolute;inset:0}.nyYjTG_cardPreview:focus-visible{box-shadow:inset 0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline:none}.nyYjTG_fileIcon{z-index:2;box-sizing:border-box;pointer-events:none;border:.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-card-tile-fill);width:40px;height:40px;color:var(--dsw-alias-link);border-radius:10px;flex:none;place-items:center;display:grid;position:relative;overflow:hidden}.nyYjTG_fileBody{z-index:2;pointer-events:none;flex:1;justify-content:space-between;align-items:center;gap:12px;min-width:0;display:flex;position:relative}.nyYjTG_details{flex-direction:column;flex:1;justify-content:center;gap:2px;min-width:0;display:flex}.nyYjTG_fileName{text-overflow:ellipsis;white-space:nowrap;font-size:13px;font-weight:500;line-height:20px;overflow:hidden}.nyYjTG_description{color:var(--dsw-alias-label-tertiary);text-overflow:ellipsis;white-space:nowrap;font-size:10px;font-weight:400;line-height:16px;overflow:hidden}.nyYjTG_description[data-error=true]{color:var(--dsw-alias-state-error-primary)}.nyYjTG_previewHint{display:none}@media (hover:hover){.nyYjTG_file:hover .nyYjTG_description:not([role=status]) .nyYjTG_secondaryText{display:none}.nyYjTG_file:hover .nyYjTG_description:not([role=status]) .nyYjTG_previewHint{display:inline}}.nyYjTG_toggle{border-radius:var(--dsw-radius-sm);min-width:0;color:var(--dsw-alias-label-tertiary);cursor:pointer;font:inherit;background:0 0;border:0;align-self:center;align-items:center;gap:4px;padding:1px 11px;font-size:12px;line-height:18px;display:inline-flex}@media (hover:hover){.nyYjTG_toggle:hover{background:var(--dsw-alias-interactive-bg-hover)}}.nyYjTG_toggle svg{flex:none;width:14px;height:14px}@container (width<=620px){.nyYjTG_presented{grid-template-columns:minmax(0,1fr)}}.nyYjTG_actions{pointer-events:auto;flex:none;display:inline-flex}`;const tagId$1=`@deepseek-ai/dsh-client-ui-deliverables/Deliverables.module.css`;if(typeof document!==`undefined`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(tagId$1)+`]`)===null){const tag=document.createElement(`style`);tag.dataset.plugin=`@deepseek-ai/dsh-client-ui-deliverables`;tag.dataset.pluginCss=tagId$1;tag.textContent=css$1;document.head.appendChild(tag)}var Deliverables_module_css_default={"actions":`nyYjTG_actions`,"cardPreview":`nyYjTG_cardPreview`,"description":`nyYjTG_description`,"details":`nyYjTG_details`,"file":`nyYjTG_file`,"fileBody":`nyYjTG_fileBody`,"fileIcon":`nyYjTG_fileIcon`,"fileName":`nyYjTG_fileName`,"hostStatus":`nyYjTG_hostStatus`,"presented":`nyYjTG_presented`,"previewHint":`nyYjTG_previewHint`,"root":`nyYjTG_root`,"secondaryText":`nyYjTG_secondaryText`,"toggle":`nyYjTG_toggle`};function cardDescription(description,fallback){const trimmed=description?.replace(/\s*(?:\([^()]*\)|([^()]*))\s*$/u,``).trim();return trimmed===void 0||trimmed===``?fallback:trimmed}function PresentedFileCard({file,cwd,phase,host,onPreview,contextMenuProps,actions,t}){const reveal=host?.fileManager??`directory`;const name=basename(file.path);const metadata=(0,_deepseek_ai_dsh_client_ui_primitives.fileExtension)(name).toUpperCase()||t(`presented.file`);const status=phase===void 0?cardDescription(file.description,metadata):t(reveal===`directory`&&phase===`revealing`?`presented.directoryOpening`:reveal===`directory`&&phase===`revealError`?`presented.directoryError`:`presented.${phase}`);return(0,react_jsx_runtime.jsxs)(`div`,{className:Deliverables_module_css_default.file,"data-presented-file":true,children:[(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:Deliverables_module_css_default.cardPreview,title:resolveWorkspacePath(cwd,file.path),"aria-label":t(`presented.previewCard`,{name:file.path}),onClick:onPreview,...contextMenuProps}),(0,react_jsx_runtime.jsx)(`span`,{className:Deliverables_module_css_default.fileIcon,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.FileTypeIcon,{path:file.path,size:20})}),(0,react_jsx_runtime.jsxs)(`div`,{className:Deliverables_module_css_default.fileBody,children:[(0,react_jsx_runtime.jsxs)(`div`,{className:Deliverables_module_css_default.details,children:[(0,react_jsx_runtime.jsx)(`span`,{className:Deliverables_module_css_default.fileName,children:name}),(0,react_jsx_runtime.jsxs)(`span`,{className:Deliverables_module_css_default.description,"data-presented-description":true,role:phase===void 0?void 0:`status`,"data-error":phase===`error`||phase===`revealError`||phase===`nativeUnavailable`?true:void 0,children:[(0,react_jsx_runtime.jsx)(`span`,{className:Deliverables_module_css_default.secondaryText,children:status}),(0,react_jsx_runtime.jsx)(`span`,{className:Deliverables_module_css_default.previewHint,children:t(`presented.preview`)})]})]}),(0,react_jsx_runtime.jsx)(`div`,{className:Deliverables_module_css_default.actions,children:actions})]})]})}const COLLAPSED_PRESENTED_COUNT=4;function selectDeliverables(owner){const changes=changesForClosing(owner);const presented=presentedForClosing(owner);return changes===null&&presented.length===0?null:{changes,presented}}function DeliverablesTail(props){const matched=selectDeliverables(props);return matched===null?null:(0,react_jsx_runtime.jsx)(Deliverables,{...props,matched})}function Deliverables({matched,openFile,useContextMenu,t,sessionId,useSessions,openPresented,openChangesReview,usePresentedOpen,usePresentedHost,useChangesDiff,loadChangesDiff,useChangesSummary,reloadPresentedHost,loadChangesSummary,useShowCodeDiff,renderSlot}){const{getTriggerProps}=useContextMenu();const[expanded,setExpanded]=(0,react.useState)(false);const showCodeDiff=useShowCodeDiff(value=>value);const cwd=useSessions(state=>state.byId[sessionId]?.cwd);const states=usePresentedOpen(value=>value);const host=usePresentedHost(value=>value);const announced=showCodeDiff?matched.changes:null;const summary=useChangesSummary(value=>announced===null?void 0:value[changesSummaryUrl(sessionId,announced.seq)]);(0,react.useEffect)(()=>{if(announced!==null&&summary===void 0)loadChangesSummary(sessionId,announced.seq)},[announced,summary,sessionId,loadChangesSummary]);const changes=announced!==null&&typeof summary===`object`&&summary.files.length>0?{seq:announced.seq,...summary}:null;const collapsible=matched.presented.length>COLLAPSED_PRESENTED_COUNT;const presented=collapsible&&!expanded?matched.presented.slice(0,COLLAPSED_PRESENTED_COUNT):matched.presented;(0,react.useEffect)(()=>{if(host===null)reloadPresentedHost()},[host,reloadPresentedHost]);return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[changes!==null&&(0,react_jsx_runtime.jsx)(ChangedFiles,{changes,cwd,t,sessionId,useChangesDiff,loadChangesDiff,openReview:index=>{openChangesReview({sessionId,seq:changes.seq,turn:changes.turn},index)}}),matched.presented.length>0&&(0,react_jsx_runtime.jsxs)(`div`,{className:Deliverables_module_css_default.root,"data-after-changes":changes!==null||void 0,children:[host===`error`&&(0,react_jsx_runtime.jsxs)(`div`,{className:Deliverables_module_css_default.hostStatus,children:[(0,react_jsx_runtime.jsx)(`span`,{children:t(`presented.hostError`)}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button,{size:`sm`,onClick:()=>{reloadPresentedHost()},children:t(`presented.retry`)})]}),host!==null&&host!==`error`&&!host.available&&(0,react_jsx_runtime.jsx)(`span`,{className:Deliverables_module_css_default.hostStatus,children:t(`presented.unavailable`)}),(0,react_jsx_runtime.jsx)(`div`,{className:Deliverables_module_css_default.presented,"data-presented-files-row":true,"data-single":matched.presented.length===1?true:void 0,children:presented.map(file=>(0,react_jsx_runtime.jsx)(PresentedFileCard,{file,cwd,phase:states[presentedFileUrl(sessionId,file.seq,file.index)],host:host===`error`?null:host,t,onPreview:()=>{openFile(file.path)},contextMenuProps:getTriggerProps({kind:`file`,value:{sessionId,path:file.path}}),actions:renderSlot(`deliverables.file.actions`,{actionUrl:presentedFileUrl(sessionId,file.seq,file.index),available:host!==null&&host!==`error`&&host.available,pending:states[presentedFileUrl(sessionId,file.seq,file.index)]===`opening`||states[presentedFileUrl(sessionId,file.seq,file.index)]===`revealing`,onAction:(action,application)=>openPresented(sessionId,file.seq,file.index,action,application)})},`${file.seq}:${file.index}`))}),collapsible&&(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:Deliverables_module_css_default.toggle,"aria-expanded":expanded,"aria-label":t(expanded?`presented.collapseAria`:`presented.expandAria`,{count:matched.presented.length}),onClick:()=>{setExpanded(value=>!value)},children:[(0,react_jsx_runtime.jsx)(`span`,{children:t(expanded?`presented.collapse`:`presented.all`,{count:matched.presented.length})}),expanded?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconChevronUpOutlineRegular,{}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconChevronDownOutlineRegular,{})]})]})]})}const css=`.ZDDmpq_root{height:100%}.ZDDmpq_selector{flex:0 auto;min-width:0}.ZDDmpq_selectorLabel{text-overflow:ellipsis;white-space:nowrap;flex:auto;min-width:0;font-size:12px;overflow:hidden}.ZDDmpq_selectorButton{box-sizing:border-box;border-radius:var(--dsw-radius-sm);max-width:100%;height:28px;color:var(--dsw-alias-label-primary);cursor:pointer;font:inherit;background:0 0;border:0;align-items:center;gap:4px;padding:0 6px 0 8px;font-size:12px;line-height:20px;display:inline-flex}.ZDDmpq_selectorButton[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover)}@media (hover:hover){.ZDDmpq_selectorButton:hover{background:var(--dsw-alias-interactive-bg-hover)}}.ZDDmpq_selectorButton svg{flex:none;display:block}.ZDDmpq_item{justify-content:space-between;align-items:center;gap:12px;min-width:0;display:flex}.ZDDmpq_itemPath{text-overflow:ellipsis;white-space:nowrap;min-width:0;line-height:20px;overflow:hidden}.ZDDmpq_itemCounts,.ZDDmpq_counts{font-family:var(--ds-font-family-code);color:var(--dsw-alias-label-tertiary);flex:none;align-items:center;gap:6px;font-size:12px;line-height:20px;display:inline-flex}.ZDDmpq_counts{min-width:0;margin-right:auto}.ZDDmpq_added{color:var(--dsw-alias-state-success-primary)}.ZDDmpq_deleted{color:var(--dsw-alias-state-error-primary)}.ZDDmpq_label{color:var(--dsw-alias-label-tertiary)}.ZDDmpq_tools{flex:none;align-items:center;gap:2px;margin-left:auto;display:inline-flex}.ZDDmpq_tool{border-radius:var(--dsw-radius-sm);width:28px;height:28px;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:0;flex:none;justify-content:center;align-items:center;padding:6px;display:inline-flex}.ZDDmpq_tool svg{width:15px;height:15px}@media (hover:hover){.ZDDmpq_tool:hover:not(:disabled){color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}}.ZDDmpq_tool[aria-pressed=true] .ZDDmpq_compareIcon{transform:rotate(90deg)}.ZDDmpq_tool:disabled{cursor:progress}.ZDDmpq_tool[data-error]{color:var(--dsw-alias-state-error-primary)}`;const tagId=`@deepseek-ai/dsh-client-ui-deliverables/ReviewTab.module.css`;if(typeof document!==`undefined`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(tagId)+`]`)===null){const tag=document.createElement(`style`);tag.dataset.plugin=`@deepseek-ai/dsh-client-ui-deliverables`;tag.dataset.pluginCss=tagId;tag.textContent=css;document.head.appendChild(tag)}var ReviewTab_module_css_default={"added":`ZDDmpq_added`,"compareIcon":`ZDDmpq_compareIcon`,"counts":`ZDDmpq_counts`,"deleted":`ZDDmpq_deleted`,"item":`ZDDmpq_item`,"itemCounts":`ZDDmpq_itemCounts`,"itemPath":`ZDDmpq_itemPath`,"label":`ZDDmpq_label`,"root":`ZDDmpq_root`,"selector":`ZDDmpq_selector`,"selectorButton":`ZDDmpq_selectorButton`,"selectorLabel":`ZDDmpq_selectorLabel`,"tool":`ZDDmpq_tool`,"tools":`ZDDmpq_tools`};const GROUPED=new Intl.NumberFormat(`en-US`);function navigatedIndex(params){const index=params?.index;return typeof index===`number`&&Number.isSafeInteger(index)&&index>=0?index:void 0}function Counts({file,t}){if(file.binary===true)return(0,react_jsx_runtime.jsx)(`span`,{className:ReviewTab_module_css_default.label,children:isReviewImagePath(file.path)?"Image":t(`changes.binary`)});if(file.oversized===true)return(0,react_jsx_runtime.jsx)(`span`,{className:ReviewTab_module_css_default.label,children:t(`changes.oversized`)});return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ReviewTab_module_css_default.added,children:t(`changes.added`,{count:GROUPED.format(file.added)})}),(0,react_jsx_runtime.jsx)(`span`,{className:ReviewTab_module_css_default.deleted,children:t(`changes.deleted`,{count:GROUPED.format(file.deleted)})})]})}function ReviewTab({useTabInfo,sessionId,useSessions,useStore,actions,useChangesSummary,useChangesDiff,usePresentedOpen,usePresentedHost,loadChangesSummary,loadChangesDiff,reloadPresentedHost,openChanged,t,renderSlot}){const{tab}=useTabInfo();const{navigation,signal}=tab;const coordinates=(0,react.useMemo)(()=>parseChangesReviewAddress(tab.contentId),[tab.contentId]);if(coordinates===void 0)throw new Error(`ui-deliverables: not a review address "${tab.contentId}"`);const{seq}=coordinates;const cwd=useSessions(sessions=>sessions.byId[sessionId]?.cwd);const summary=useChangesSummary(value=>value[changesSummaryUrl(sessionId,seq)]);const state=useStore(store=>store.byTab[tab.id]);const host=usePresentedHost(value=>value);(0,react.useEffect)(()=>{if(state?.navigated===navigation.revision)return;actions.navigated(tab.id,navigation.revision,navigatedIndex(navigation.params)??state?.index??0)},[state,navigation.revision,navigation.params,actions,tab.id]);(0,react.useEffect)(()=>{const forget=()=>{actions.forget(tab.id)};signal.addEventListener(`abort`,forget,{once:true});return()=>{signal.removeEventListener(`abort`,forget)}},[signal,actions,tab.id]);(0,react.useEffect)(()=>{if(summary===void 0)loadChangesSummary(sessionId,seq)},[summary,sessionId,seq,loadChangesSummary]);(0,react.useEffect)(()=>{if(host===null)reloadPresentedHost()},[host,reloadPresentedHost]);const files=typeof summary===`object`?summary.files:[];const index=state!==void 0&&files[state.index]!==void 0?state.index:0;const file=files[index];const diffState=useChangesDiff(value=>file===void 0?void 0:value[changesDiffUrl(sessionId,seq,index)]);(0,react.useEffect)(()=>{if(file!==void 0&&diffState===void 0)loadChangesDiff(sessionId,seq,index)},[file,diffState,sessionId,seq,index,loadChangesDiff]);const phase=usePresentedOpen(value=>file===void 0?void 0:value[changedFileUrl(sessionId,seq,index)]);const[menuOpen,setMenuOpen]=(0,react.useState)(false);const split=state?.split===true;const wrap=state?.wrap===true;const native=host!==null&&host!==`error`&&host.available&&phase!==`nativeUnavailable`;const summaryState=summary===void 0||summary===`loading`?`loading`:summary===`missing`?`missing`:`ready`;return(0,react_jsx_runtime.jsxs)(`div`,{className:`${FileDiff_module_css_default.root} ${ReviewTab_module_css_default.root}`,"data-changes-review":true,"data-review-state":summaryState,children:[(0,react_jsx_runtime.jsxs)(`div`,{className:FileDiff_module_css_default.header,children:[file===void 0?(0,react_jsx_runtime.jsx)(`span`,{className:ReviewTab_module_css_default.selectorLabel,children:t(`review.title`,{turn:String(coordinates.turn)})}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu,{className:ReviewTab_module_css_default.selector,open:menuOpen,autoFocus:true,portal:true,align:`start`,dense:true,onClose:()=>{setMenuOpen(false)},anchor:(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:ReviewTab_module_css_default.selectorButton,"aria-haspopup":`menu`,"aria-expanded":menuOpen,"aria-label":t(`review.selectFile`),title:file.display,"data-review-file":file.path,onClick:()=>{setMenuOpen(value=>!value)},children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.PathLabel,{path:file.display}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconChevronDownOutlineRegular,{size:12})]}),items:files.map((entry,at)=>({id:String(at),label:(0,react_jsx_runtime.jsxs)(`span`,{className:ReviewTab_module_css_default.item,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ReviewTab_module_css_default.itemPath,children:entry.display}),(0,react_jsx_runtime.jsx)(`span`,{className:ReviewTab_module_css_default.itemCounts,children:(0,react_jsx_runtime.jsx)(Counts,{file:entry,t})})]})})),selectedId:String(index),onSelect:id=>{actions.selected(tab.id,Number(id));setMenuOpen(false)}}),file!==void 0&&(0,react_jsx_runtime.jsx)(`span`,{className:ReviewTab_module_css_default.counts,children:(0,react_jsx_runtime.jsx)(Counts,{file,t})}),(0,react_jsx_runtime.jsxs)(`span`,{className:ReviewTab_module_css_default.tools,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip,{label:t(split?`review.unified`:`review.split`),side:`bottom`,delayMs:500,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:ReviewTab_module_css_default.tool,"aria-pressed":split,"aria-label":t(`review.splitAria`),"data-review-tool":`split`,onClick:()=>{actions.toggledSplit(tab.id)},children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconCompareSplitOutlineRegular,{className:ReviewTab_module_css_default.compareIcon})})}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip,{label:t(wrap?`review.nowrap`:`review.wrap`),side:`bottom`,delayMs:500,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:ReviewTab_module_css_default.tool,"aria-pressed":wrap,"aria-label":t(`review.wrapAria`),"data-review-tool":`wrap`,onClick:()=>{actions.toggledWrap(tab.id)},children:wrap?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconNowrapFillRegular,{}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconWrapFillRegular,{})})}),file!==void 0&&(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip,{label:t(`review.openFile`),side:`bottom`,delayMs:500,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:ReviewTab_module_css_default.tool,"aria-label":t(`review.openFileAria`,{name:file.display}),"data-review-tool":`open-file`,onClick:()=>{tab.actions.openResource(fileAddressFor(sessionId,cwd,file.path))},children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconInspectOutlineRegular,{})})}),file!==void 0&&renderSlot(`deliverables.review.file.actions`,{actionUrl:changedFileUrl(sessionId,seq,index),available:native,pending:phase===`opening`||phase===`revealing`,onAction:(action,application)=>openChanged(sessionId,seq,index,action,application)})]})]}),summaryState===`loading`&&(0,react_jsx_runtime.jsx)(`p`,{className:FileDiff_module_css_default.status,role:`status`,children:t(`diff.loading`)}),summaryState===`missing`&&(0,react_jsx_runtime.jsx)(`p`,{className:FileDiff_module_css_default.status,children:t(`diff.missing`)}),file!==void 0&&(file.binary===true&&isReviewImagePath(file.path)?(0,react_jsx_runtime.jsx)(ReviewImage,{path:file.path,cwd:cwd}):(0,react_jsx_runtime.jsx)(FileDiff,{state:diffState,split,wrap,t,retry:()=>{loadChangesDiff(sessionId,seq,index)}}))]})}const CHANGES_REVIEW_KIND=`changes-review`;const CHANGES_REVIEW_ID=`@deepseek-ai/dsh-client-ui-deliverables`;function changesReviewDefinition(t){return{id:CHANGES_REVIEW_ID,kind:CHANGES_REVIEW_KIND,patterns:[`dsh-resource://changes-review/**`],priority:`builtin`,canOpen:address=>parseChangesReviewAddress(address)!==void 0,title:address=>{const turn=parseChangesReviewAddress(address)?.turn;return turn===void 0?address:t(`review.title`,{turn:String(turn)})}}}function bucket(state,tabId){const tab=state.byTab[tabId];if(tab===void 0)throw new Error(`ui-deliverables: no review state for tab "${tabId}"`);return tab}function createReviewStore(){return(0,_deepseek_ai_dsh_client_store.defineStore)({init:()=>({byTab:{}}),actions:{navigated:(d,tabId,revision,index)=>{const tab=d.byTab[tabId];if(tab===void 0)d.byTab[tabId]={index,split:true,wrap:false,navigated:revision};else{tab.index=index;tab.navigated=revision}},selected:(d,tabId,index)=>{bucket(d,tabId).index=index},toggledSplit:(d,tabId)=>{const tab=bucket(d,tabId);tab.split=!tab.split},toggledWrap:(d,tabId)=>{const tab=bucket(d,tabId);tab.wrap=!tab.wrap},forget:(d,tabId)=>{d.byTab=Object.fromEntries(Object.entries(d.byTab).filter(([id])=>id!==tabId))}}})}const NS=`deliverables`;const zh={"presented.nativeUnavailable":`此文件没有可用的主机路径,请在侧边栏预览`,"presented.revealError":`无法在文件管理器中显示,请重试`,"presented.directoryError":`无法打开所在文件夹,请重试`,"presented.directoryOpening":`正在打开所在文件夹…`,"presented.revealing":`正在文件管理器中显示…`,"presented.unavailable":`此主机没有可用的桌面,无法使用外部程序打开文件或文件夹;文件仍可在侧边栏预览`,"presented.retry":`重试`,"presented.hostError":`无法读取主机桌面信息`,"presented.preview":`在侧边栏预览`,"presented.previewButton":`在侧边栏打开 {name}`,"presented.previewCard":`在侧边栏预览 {name}`,"presented.all":`全部 {count} 个文件`,"presented.expandAria":`展开全部 {count} 个交付文件`,"presented.collapse":`收起`,"presented.collapseAria":`收起交付文件列表`,"presented.opening":`正在打开…`,"presented.error":`打开失败,点击重试`,"presented.file":`文件`,"row.title":`交付文件`,"row.running":`正在交付`,"row.preparing":`准备交付`,"row.ok":`已交付`,"row.error":`交付失败`,"row.stopped":`已中断`,"row.inspect":`查看调用`,"changes.title":`已编辑 {count} 个文件`,"changes.singleTitle":`已编辑 {name}`,"changes.added":`+{count}`,"changes.deleted":`-{count}`,"changes.binary":`二进制`,"changes.openReview":`在侧边栏查看本轮改动`,"changes.all":`全部 {count} 个文件`,"changes.expandAria":`展开全部 {count} 个改动文件`,"changes.collapse":`收起`,"changes.collapseAria":`收起改动文件列表`,"changes.oversized":`过大`,"changes.viewDiff":`查看 {name} 的改动`,"review.title":`第 {turn} 轮改动`,"review.selectFile":`选择要查看的文件`,"review.split":`切换为左右对比`,"review.unified":`切换为单栏对比`,"review.splitAria":`左右对比`,"review.wrap":`开启自动换行`,"review.nowrap":`关闭自动换行`,"review.wrapAria":`自动换行`,"review.openFile":`在侧边栏打开整个文件`,"review.openFileAria":`在侧边栏打开 {name}`,"diff.loading":`正在读取改动…`,"diff.missing":`这轮改动的内容已不可用`,"diff.error":`无法读取改动`,"diff.binary":`二进制文件,无法显示改动`,"diff.oversized":`文件过大,无法显示改动`,"diff.created":`本轮新建的文件`,"diff.deleted":`本轮删除的文件`,"diff.unchanged":`两侧内容相同`,"diff.coarse":`逐行对比超时,按整个文件替换显示`,"diff.truncated":`只显示前 {count} 行`};const en={"presented.nativeUnavailable":`This file has no available Host path. Preview it in the sidebar.`,"presented.revealError":`Could not show in file manager. Try again.`,"presented.directoryError":`Could not open containing folder. Try again.`,"presented.directoryOpening":`Opening containing folder…`,"presented.revealing":`Showing in file manager…`,"presented.unavailable":`This Host has no desktop available to open files or folders in external apps. Files can still be previewed in the sidebar.`,"presented.retry":`Retry`,"presented.hostError":`Could not read the Host desktop information`,"presented.preview":`Preview in sidebar`,"presented.previewButton":`Open {name} in sidebar`,"presented.previewCard":`Preview {name} in sidebar`,"presented.all":`All {count} files`,"presented.expandAria":`Show all {count} delivered files`,"presented.collapse":`Collapse`,"presented.collapseAria":`Collapse delivered files`,"presented.opening":`Opening…`,"presented.error":`Could not open. Click to retry.`,"presented.file":`File`,"row.title":`Present files`,"row.running":`Delivering`,"row.preparing":`Preparing deliverables`,"row.ok":`Delivered`,"row.error":`Delivery failed`,"row.stopped":`Interrupted`,"row.inspect":`Inspect call`,"changes.title":`Edited {count} files`,"changes.singleTitle":`Edited {name}`,"changes.added":`+{count}`,"changes.deleted":`-{count}`,"changes.binary":`binary`,"changes.openReview":`Review this turn’s changes in the sidebar`,"changes.all":`All {count} files`,"changes.expandAria":`Show all {count} changed files`,"changes.collapse":`Collapse`,"changes.collapseAria":`Collapse changed files`,"changes.oversized":`too large`,"changes.viewDiff":`View changes to {name}`,"review.title":`Review · turn {turn}`,"review.selectFile":`Choose the file to review`,"review.split":`Switch to split view`,"review.unified":`Switch to unified view`,"review.splitAria":`Split view`,"review.wrap":`Enable line wrap`,"review.nowrap":`Disable line wrap`,"review.wrapAria":`Line wrap`,"review.openFile":`Open the whole file in the sidebar`,"review.openFileAria":`Open {name} in sidebar`,"diff.loading":`Reading changes…`,"diff.missing":`The contents of this turn’s changes are no longer available`,"diff.error":`Could not read the changes`,"diff.binary":`Binary file; changes cannot be shown`,"diff.oversized":`File too large; changes cannot be shown`,"diff.created":`Created in this turn`,"diff.deleted":`Deleted in this turn`,"diff.unchanged":`Both sides hold the same lines`,"diff.coarse":`Line comparison timed out; shown as a whole-file replacement`,"diff.truncated":`Showing the first {count} lines`};const ja={"presented.nativeUnavailable":`このファイルには利用可能なHostパスがありません。サイドバーでプレビューしてください。`,"presented.revealError":`ファイルマネージャーで表示できませんでした。再試行してください。`,"presented.directoryError":`含まれるフォルダーを開けませんでした。再試行してください。`,"presented.directoryOpening":`含まれるフォルダーを開いています…`,"presented.revealing":`ファイルマネージャーで表示しています…`,"presented.unavailable":`このHostには、外部アプリでファイルやフォルダーを開くためのデスクトップがありません。ファイルはサイドバーで引き続きプレビューできます。`,"presented.retry":`再試行`,"presented.hostError":`Hostのデスクトップ情報を読み取れませんでした`,"presented.preview":`サイドバーでプレビュー`,"presented.previewButton":`{name}をサイドバーで開く`,"presented.previewCard":`{name}をサイドバーでプレビュー`,"presented.all":`全{count}ファイル`,"presented.expandAria":`配信された全{count}ファイルを表示`,"presented.collapse":`折りたたむ`,"presented.collapseAria":`配信されたファイルを折りたたむ`,"presented.opening":`開いています…`,"presented.error":`開けませんでした。クリックして再試行してください。`,"presented.file":`ファイル`,"row.title":`ファイルを提示`,"row.running":`配信中`,"row.preparing":`成果物を準備中`,"row.ok":`配信済み`,"row.error":`配信に失敗しました`,"row.stopped":`中断されました`,"row.inspect":`呼び出しを検査`,"changes.title":`{count}ファイルを編集しました`,"changes.singleTitle":`{name}を編集しました`,"changes.added":`+{count}`,"changes.deleted":`-{count}`,"changes.binary":`バイナリ`,"changes.openReview":`このターンの変更をサイドバーで確認`,"changes.all":`全{count}ファイル`,"changes.expandAria":`変更された全{count}ファイルを表示`,"changes.collapse":`折りたたむ`,"changes.collapseAria":`変更されたファイルを折りたたむ`,"changes.oversized":`サイズが大きすぎます`,"changes.viewDiff":`{name}の変更を表示`,"review.title":`レビュー · ターン{turn}`,"review.selectFile":`レビューするファイルを選択`,"review.split":`分割ビューに切り替え`,"review.unified":`統合ビューに切り替え`,"review.splitAria":`分割ビュー`,"review.wrap":`行の折り返しを有効化`,"review.nowrap":`行の折り返しを無効化`,"review.wrapAria":`行の折り返し`,"review.openFile":`ファイル全体をサイドバーで開く`,"review.openFileAria":`{name}をサイドバーで開く`,"diff.loading":`変更を読み込んでいます…`,"diff.missing":`このターンの変更内容は利用できなくなりました`,"diff.error":`変更を読み取れませんでした`,"diff.binary":`バイナリファイルのため、変更を表示できません`,"diff.oversized":`ファイルが大きすぎるため、変更を表示できません`,"diff.created":`このターンで作成`,"diff.deleted":`このターンで削除`,"diff.unchanged":`両方の行内容が同一です`,"diff.coarse":`行比較がタイムアウトしたため、ファイル全体の置換として表示しています`,"diff.truncated":`最初の{count}行を表示`};const es={"presented.nativeUnavailable":`Este archivo no tiene una ruta de host disponible. Vista previa en la barra lateral.`,"presented.revealError":`No se pudo mostrar en el administrador de archivos. Intentar otra vez.`,"presented.directoryError":`No se pudo abrir la carpeta que lo contiene. Intentar otra vez.`,"presented.directoryOpening":`Abriendo la carpeta que contiene...`,"presented.revealing":`Mostrando en el administrador de archivos…`,"presented.unavailable":`Este Host no tiene un escritorio disponible para abrir archivos o carpetas en aplicaciones externas. Los archivos aún se pueden obtener una vista previa en la barra lateral.`,"presented.retry":`Reintentar`,"presented.hostError":`No se pudo leer la información del escritorio del host`,"presented.preview":`Vista previa en la barra lateral`,"presented.previewButton":`Abra {name} en la barra lateral`,"presented.previewCard":`Vista previa de {name} en la barra lateral`,"presented.all":`Todos los archivos {count}`,"presented.expandAria":`Mostrar todos los archivos entregados {count}`,"presented.collapse":`Contraer`,"presented.collapseAria":`Contraer archivos entregados`,"presented.opening":`Abriendo…`,"presented.error":`No se pudo abrir. Haga clic para volver a intentarlo.`,"presented.file":`Archivo`,"row.title":`Presentar archivos`,"row.running":`Entregando`,"row.preparing":`Preparando entregables`,"row.ok":`Entregado`,"row.error":`Entrega fallida`,"row.stopped":`interrumpido`,"row.inspect":`inspeccionar llamada`,"changes.title":`Archivos {count} editados`,"changes.singleTitle":`Editado {name}`,"changes.added":`+{count}`,"changes.deleted":`-{count}`,"changes.binary":`binario`,"changes.openReview":`Revisa los cambios de este turno en la barra lateral.`,"changes.all":`Todos los archivos {count}`,"changes.expandAria":`Mostrar todos los archivos modificados {count}`,"changes.collapse":`Contraer`,"changes.collapseAria":`Contraer archivos modificados`,"changes.oversized":`demasiado grande`,"changes.viewDiff":`Ver cambios en {name}`,"review.title":`Revisión · turno {turn}`,"review.selectFile":`Elija el archivo para revisar`,"review.split":`Cambiar a vista dividida`,"review.unified":`Cambiar a vista unificada`,"review.splitAria":`Vista dividida`,"review.wrap":`Habilitar ajuste de línea`,"review.nowrap":`Desactivar ajuste de línea`,"review.wrapAria":`Ajuste de línea`,"review.openFile":`Abra el archivo completo en la barra lateral.`,"review.openFileAria":`Abra {name} en la barra lateral`,"diff.loading":`Cambios de lectura…`,"diff.missing":`El contenido de los cambios de este turno ya no está disponible.`,"diff.error":`No se pudieron leer los cambios.`,"diff.binary":`Archivo binario; los cambios no se pueden mostrar`,"diff.oversized":`Archivo demasiado grande; los cambios no se pueden mostrar`,"diff.created":`Creado en este turno`,"diff.deleted":`Eliminado en este turno`,"diff.unchanged":`Ambos lados mantienen las mismas líneas.`,"diff.coarse":`Se agotó el tiempo de espera para la comparación de líneas; se muestra como un reemplazo de archivo completo`,"diff.truncated":`Mostrando las primeras líneas {count}`};const fr={"presented.nativeUnavailable":`Ce fichier n'a pas de chemin d'hôte disponible. Prévisualisez-le dans la barre latérale.`,"presented.revealError":`Impossible d'afficher dans le gestionnaire de fichiers. Essayer à nouveau.`,"presented.directoryError":`Impossible d'ouvrir le dossier contenant. Essayer à nouveau.`,"presented.directoryOpening":`Ouverture du dossier contenant…`,"presented.revealing":`Affichage dans le gestionnaire de fichiers…`,"presented.unavailable":`Cet hôte ne dispose pas de bureau disponible pour ouvrir des fichiers ou des dossiers dans des applications externes. Les fichiers peuvent toujours être prévisualisés dans la barre latérale.`,"presented.retry":`Réessayer`,"presented.hostError":`Impossible de lire les informations du bureau hôte`,"presented.preview":`Aperçu dans la barre latérale`,"presented.previewButton":`Ouvrir {name} dans la barre latérale`,"presented.previewCard":`Aperçu de {name} dans la barre latérale`,"presented.all":`Tous les fichiers {count}`,"presented.expandAria":`Afficher tous les fichiers livrés {count}`,"presented.collapse":`Réduire`,"presented.collapseAria":`Réduire les fichiers livrés`,"presented.opening":`Ouverture…`,"presented.error":`Impossible d'ouvrir. Cliquez pour réessayer.`,"presented.file":`Fichier`,"row.title":`Présenter des fichiers`,"row.running":`Livrer`,"row.preparing":`Préparation des livrables`,"row.ok":`Livré`,"row.error":`La livraison a échoué`,"row.stopped":`Interrompu`,"row.inspect":`Inspecter l'appel`,"changes.title":`Fichiers {count} modifiés`,"changes.singleTitle":`Modifié {name}`,"changes.added":`+{count}`,"changes.deleted":`-{count}`,"changes.binary":`binaire`,"changes.openReview":`Consultez les modifications de ce tour dans la barre latérale`,"changes.all":`Tous les fichiers {count}`,"changes.expandAria":`Afficher tous les fichiers modifiés {count}`,"changes.collapse":`Réduire`,"changes.collapseAria":`Réduire les fichiers modifiés`,"changes.oversized":`trop grand`,"changes.viewDiff":`Afficher les modifications apportées à {name}`,"review.title":`Révision · tour {turn}`,"review.selectFile":`Choisissez le fichier à examiner`,"review.split":`Passer à la vue fractionnée`,"review.unified":`Passer à la vue unifiée`,"review.splitAria":`Vue fractionnée`,"review.wrap":`Activer le retour à la ligne`,"review.nowrap":`Désactiver le retour à la ligne`,"review.wrapAria":`Retour à la ligne`,"review.openFile":`Ouvrez l'intégralité du fichier dans la barre latérale`,"review.openFileAria":`Ouvrir {name} dans la barre latérale`,"diff.loading":`La lecture change…`,"diff.missing":`Le contenu des modifications de ce tour n'est plus disponible`,"diff.error":`Impossible de lire les modifications`,"diff.binary":`Fichier binaire\xA0; les modifications ne peuvent pas être affichées`,"diff.oversized":`Fichier trop volumineux\xA0; les modifications ne peuvent pas être affichées`,"diff.created":`Créé à ce tour`,"diff.deleted":`Supprimé à ce tour`,"diff.unchanged":`Les deux côtés tiennent les mêmes lignes`,"diff.coarse":`La comparaison de lignes a expiré\xA0; affiché en remplacement de l'ensemble du fichier`,"diff.truncated":`Affichage des premières lignes {count}`};const de={"presented.nativeUnavailable":`Für diese Datei ist kein Hostpfad verfügbar. Sehen Sie sich die Vorschau in der Seitenleiste an.`,"presented.revealError":`Konnte im Dateimanager nicht angezeigt werden. Versuchen Sie es erneut.`,"presented.directoryError":`Der enthaltende Ordner konnte nicht geöffnet werden. Versuchen Sie es erneut.`,"presented.directoryOpening":`Öffnen des enthaltenden Ordners…`,"presented.revealing":`Wird im Dateimanager angezeigt…`,"presented.unavailable":`Auf diesem Host steht kein Desktop zum Öffnen von Dateien oder Ordnern in externen Apps zur Verfügung. Dateien können weiterhin in der Seitenleiste in der Vorschau angezeigt werden.`,"presented.retry":`Erneut versuchen`,"presented.hostError":`Die Host-Desktop-Informationen konnten nicht gelesen werden`,"presented.preview":`Vorschau in der Seitenleiste`,"presented.previewButton":`Öffnen Sie {name} in der Seitenleiste`,"presented.previewCard":`Vorschau von {name} in der Seitenleiste`,"presented.all":`Alle {count}-Dateien`,"presented.expandAria":`Alle von {count} gelieferten Dateien anzeigen`,"presented.collapse":`Einklappen`,"presented.collapseAria":`Gelieferte Dateien ausblenden`,"presented.opening":`Eröffnung…`,"presented.error":`Konnte nicht geöffnet werden. Klicken Sie, um es erneut zu versuchen.`,"presented.file":`Datei`,"row.title":`Vorhandene Akten`,"row.running":`Liefern`,"row.preparing":`Vorbereiten von Liefergegenständen`,"row.ok":`Geliefert`,"row.error":`Die Lieferung ist fehlgeschlagen`,"row.stopped":`Unterbrochen`,"row.inspect":`Aufruf prüfen`,"changes.title":`Bearbeitete {count}-Dateien`,"changes.singleTitle":`Bearbeitet {name}`,"changes.added":`+{count}`,"changes.deleted":`-{count}`,"changes.binary":`binär`,"changes.openReview":`Überprüfen Sie die Änderungen dieser Runde in der Seitenleiste`,"changes.all":`Alle {count}-Dateien`,"changes.expandAria":`Alle von {count} geänderten Dateien anzeigen`,"changes.collapse":`Einklappen`,"changes.collapseAria":`Geänderte Dateien reduzieren`,"changes.oversized":`zu groß`,"changes.viewDiff":`Änderungen an {name} anzeigen`,"review.title":`Überprüfung · Runde {turn}`,"review.selectFile":`Wählen Sie die zu überprüfende Datei aus`,"review.split":`Wechseln Sie zur geteilten Ansicht`,"review.unified":`Wechseln Sie zur einheitlichen Ansicht`,"review.splitAria":`Geteilte Ansicht`,"review.wrap":`Zeilenumbruch aktivieren`,"review.nowrap":`Zeilenumbruch deaktivieren`,"review.wrapAria":`Zeilenumbruch`,"review.openFile":`Öffnen Sie die gesamte Datei in der Seitenleiste`,"review.openFileAria":`Öffnen Sie {name} in der Seitenleiste`,"diff.loading":`Änderungen lesen…`,"diff.missing":`Der Inhalt der Änderungen dieser Runde ist nicht mehr verfügbar`,"diff.error":`Die Änderungen konnten nicht gelesen werden`,"diff.binary":`Binärdatei; Änderungen können nicht angezeigt werden`,"diff.oversized":`Datei zu groß; Änderungen können nicht angezeigt werden`,"diff.created":`In dieser Runde erstellt`,"diff.deleted":`In dieser Runde gelöscht`,"diff.unchanged":`Beide Seiten vertreten die gleichen Linien`,"diff.coarse":`Zeitüberschreitung beim Leitungsvergleich; wird als vollständige Dateiersetzung angezeigt`,"diff.truncated":`Zeigt die ersten {count}-Zeilen`};const ru={"presented.nativeUnavailable":`У этого файла нет доступного пути к хосту. Предварительный просмотр на боковой панели.`,"presented.revealError":`Не удалось отобразить в файловом менеджере. Попробуйте еще раз.`,"presented.directoryError":`Не удалось открыть содержащую папку. Попробуйте еще раз.`,"presented.directoryOpening":`Открытие папки, содержащей…`,"presented.revealing":`Отображается в файловом менеджере…`,"presented.unavailable":`У этого хоста нет рабочего стола, на котором можно было бы открывать файлы или папки во внешних приложениях. Файлы по-прежнему можно просматривать на боковой панели.`,"presented.retry":`Повторить`,"presented.hostError":`Не удалось прочитать информацию о рабочем столе хоста.`,"presented.preview":`Предварительный просмотр в боковой панели`,"presented.previewButton":`Откройте {name} на боковой панели.`,"presented.previewCard":`Предварительный просмотр {name} на боковой панели`,"presented.all":`Все файлы {count}`,"presented.expandAria":`Показать все доставленные файлы {count}`,"presented.collapse":`Свернуть`,"presented.collapseAria":`Свернуть доставленные файлы`,"presented.opening":`Открытие…`,"presented.error":`Не удалось открыть. Нажмите, чтобы повторить попытку.`,"presented.file":`Файл`,"row.title":`Представление файлов`,"row.running":`Доставка`,"row.preparing":`Подготовка результатов`,"row.ok":`Доставлено`,"row.error":`Доставка не удалась`,"row.stopped":`Прерванный`,"row.inspect":`Проверить вызов`,"changes.title":`Отредактированные файлы {count}.`,"changes.singleTitle":`Отредактировано {name}`,"changes.added":`+{count}`,"changes.deleted":`-{count}`,"changes.binary":`двоичный`,"changes.openReview":`Просмотрите изменения этого хода на боковой панели.`,"changes.all":`Все файлы {count}`,"changes.expandAria":`Показать все измененные файлы {count}`,"changes.collapse":`Свернуть`,"changes.collapseAria":`Свернуть измененные файлы`,"changes.oversized":`слишком большой`,"changes.viewDiff":`Посмотреть изменения в {name}`,"review.title":`Проверка · ход {turn}`,"review.selectFile":`Выберите файл для просмотра`,"review.split":`Переключиться на разделенный вид`,"review.unified":`Переключиться на единый вид`,"review.splitAria":`Разделенный вид`,"review.wrap":`Включить перенос строк`,"review.nowrap":`Отключить перенос строк`,"review.wrapAria":`Перенос строки`,"review.openFile":`Открыть весь файл на боковой панели`,"review.openFileAria":`Откройте {name} на боковой панели.`,"diff.loading":`Чтение изменений…`,"diff.missing":`Содержимое изменений этого хода больше не доступно.`,"diff.error":`Не удалось прочитать изменения`,"diff.binary":`Бинарный файл; изменения не могут быть показаны`,"diff.oversized":`Файл слишком большой; изменения не могут быть показаны`,"diff.created":`Создано в этом ходу`,"diff.deleted":`Удален на этом ходу`,"diff.unchanged":`Обе стороны держат одни и те же линии`,"diff.coarse":`Время сравнения строк истекло; отображается как замена всего файла`,"diff.truncated":`Показаны первые строки {count}`};const pt={"presented.nativeUnavailable":`Este arquivo não possui caminho de host disponível. Visualize-o na barra lateral.`,"presented.revealError":`Não foi possível mostrar no gerenciador de arquivos. Tente novamente.`,"presented.directoryError":`Não foi possível abrir a pasta que contém. Tente novamente.`,"presented.directoryOpening":`Abrindo a pasta que contém…`,"presented.revealing":`Mostrando no gerenciador de arquivos…`,"presented.unavailable":`Este Host não possui área de trabalho disponível para abrir arquivos ou pastas em aplicativos externos. Os arquivos ainda podem ser visualizados na barra lateral.`,"presented.retry":`Tentar novamente`,"presented.hostError":`Não foi possível ler as informações da área de trabalho do Host`,"presented.preview":`Pré-visualização na barra lateral`,"presented.previewButton":`Abra {name} na barra lateral`,"presented.previewCard":`Visualizar {name} na barra lateral`,"presented.all":`Todos os {count} arquivos`,"presented.expandAria":`Mostrar todos os {count} arquivos entregues`,"presented.collapse":`Recolher`,"presented.collapseAria":`Recolher arquivos entregues`,"presented.opening":`Abrindo…`,"presented.error":`Não foi possível abrir. Clique para tentar novamente.`,"presented.file":`Arquivo`,"row.title":`Apresentar arquivos`,"row.running":`Entregando`,"row.preparing":`Preparando resultados`,"row.ok":`Entregue`,"row.error":`Falha na entrega`,"row.stopped":`Interrompido`,"row.inspect":`Inspecionar chamada`,"changes.title":`{count} arquivos editados`,"changes.singleTitle":`Editado {name}`,"changes.added":`+{count}`,"changes.deleted":`-{count}`,"changes.binary":`binário`,"changes.openReview":`Revise as mudanças deste turno na barra lateral`,"changes.all":`Todos os {count} arquivos`,"changes.expandAria":`Mostrar todos os {count} arquivos alterados`,"changes.collapse":`Recolher`,"changes.collapseAria":`Recolher arquivos alterados`,"changes.oversized":`muito grande`,"changes.viewDiff":`Ver alterações em {name}`,"review.title":`Revisão · turno {turn}`,"review.selectFile":`Escolha o arquivo para revisar`,"review.split":`Mudar para visualização dividida`,"review.unified":`Mudar para visualização unificada`,"review.splitAria":`Visualização dividida`,"review.wrap":`Ativar quebra de linha`,"review.nowrap":`Desativar quebra de linha`,"review.wrapAria":`Quebra de linha`,"review.openFile":`Abra o arquivo inteiro na barra lateral`,"review.openFileAria":`Abra {name} na barra lateral`,"diff.loading":`A leitura muda…`,"diff.missing":`O conteúdo das alterações deste turno não está mais disponível`,"diff.error":`Não foi possível ler as alterações`,"diff.binary":`Arquivo binário; as alterações não podem ser mostradas`,"diff.oversized":`Arquivo muito grande; as alterações não podem ser mostradas`,"diff.created":`Criado neste turno`,"diff.deleted":`Excluído neste turno`,"diff.unchanged":`Ambos os lados mantêm as mesmas linhas`,"diff.coarse":`A comparação de linha expirou; mostrado como uma substituição de arquivo inteiro`,"diff.truncated":`Mostrando as primeiras {count} linhas`};const inject=[`slots`,`locale`,`uiConversation`,`remote`,`remote.session`,`sidebarRightTabs`,`sidebarRight`,`configForms`];function apply(ctx){const opener=new PresentedOpenController;const summaries=new ChangesSummaryStore;const diffs=new ChangesDiffStore;ctx.effect(()=>()=>Promise.all([opener.dispose(),summaries.dispose(),diffs.dispose()]));ctx.on(`connection/reset`,()=>{opener.resetHost();summaries.reset();diffs.reset()});ctx.uiConversation.events.register(deliverablesDefinition);ctx.effect(()=>ctx.locale.register(NS,{zh,en,ja,es,fr,de,ru,pt}),`ui-deliverables: dictionaries`);ctx.slots.inject(`conversation.chat.turnTail`,()=>ctx.slots.register({name:`conversation.chat.turnTail`,id:`@deepseek-ai/dsh-client-ui-deliverables`,locale:NS,children:{"deliverables.file.actions":{kind:`list`,scope:`session`}},inject:()=>({hooks:{changesDiff:diffs.state,presentedOpen:opener.state,presentedHost:opener.host,changesSummary:summaries.state,showCodeDiff:ctx.configForms.developerTools.enabled},loadChangesDiff:(sessionId,seq,index)=>diffs.load(sessionId,seq,index),reloadPresentedHost:()=>opener.loadHost(),loadChangesSummary:(sessionId,seq)=>summaries.load(sessionId,seq),openPresented:(sessionId,seq,index,action,application)=>opener.open(sessionId,seq,index,action,application),openChanged:(sessionId,seq,index,action,application)=>opener.openChanged(sessionId,seq,index,action,application),openChangesReview:(coordinates,index)=>{ctx.sidebarRight.openResource(changesReviewAddress(coordinates),{params:{index}})}})},DeliverablesTail));ctx.slots.inject(`tool.call.toolview`,()=>ctx.slots.register({name:`tool.call.toolview`,key:`present`,locale:NS},PresentRow));const t=ctx.locale.bind(NS);ctx.effect(()=>ctx.sidebarRightTabs.register(changesReviewDefinition(t)),`ui-deliverables: changes-review type`);ctx.effect(()=>ctx.slots.inject(`sidebar.right.pane.tab`,()=>ctx.slots.register({name:`sidebar.right.pane.tab`,key:CHANGES_REVIEW_ID,locale:NS,store:createReviewStore(),children:{"deliverables.review.file.actions":{kind:`list`,scope:`session`}},inject:()=>({hooks:{changesSummary:summaries.state,changesDiff:diffs.state,presentedOpen:opener.state,presentedHost:opener.host},loadChangesSummary:(sessionId,seq)=>summaries.load(sessionId,seq),loadChangesDiff:(sessionId,seq,index)=>diffs.load(sessionId,seq,index),reloadPresentedHost:()=>opener.loadHost(),openChanged:(sessionId,seq,index,action,application)=>opener.openChanged(sessionId,seq,index,action,application)})},ReviewTab)),`ui-deliverables: changes-review body`);ctx.provide(`chatFileMentions`,{forClosing(owner,_sessionId,getFileTriggerProps){const paths=selectProducedFiles(owner);const presented=presentedForClosing(owner);if(paths===null&&presented.length===0)return void 0;return producedFileMentions([...new Set([...paths??[],...presented.map(file=>file.path)])],owner.openFile,path=>t(`presented.previewButton`,{name:path}),owner.turn.data.get(`deliverables`)?.produced,getFileTriggerProps)}})}exports.apply=apply;exports.inject=inject;return module.exports}}); +//# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/packages/dsh-deliverables/lib/index.js b/packages/dsh-deliverables/lib/index.js new file mode 100644 index 0000000..11f0965 --- /dev/null +++ b/packages/dsh-deliverables/lib/index.js @@ -0,0 +1,274 @@ +// GENERATED - do not edit by hand. +// +// Fork of @deepseek-ai/dsh-client-ui-deliverables@0.2.2-rc.5 (lib/index.js, the Node half) with these +// patches from scripts\sync-vendored.ps1: +// - inline remoteErrorOf so the Node half imports no harness package +// Its browser half is lib/client.js. The pack's bundle layer disables the core +// row, so this copy is the one that runs. Re-sync with: +// powershell -NoProfile -ExecutionPolicy Bypass -File scripts\sync-vendored.ps1 +// +/** The marker check `remoteErrorOf` performs, inlined: this fork imports no harness package. */ +function remoteErrorOf(value) { + if (typeof value === "object" && value !== null && value.isDSHRemoteError === true && typeof value.code === "string") return value; +} +//#region lib/types/changes.js +/** Authenticated GET route serving one announced change summary while its Session lives. */ +const CHANGED_FILES_PATH = "/api/changes.summary"; +/** Authenticated GET route serving one listed file's turn-start and turn-end comparison while its Session lives. */ +const CHANGES_DIFF_PATH = "/api/changes.diff"; +/** Authenticated POST route for opening a changed file on the Host desktop. */ +const CHANGES_OPEN_PATH = "/api/changes.open"; +CHANGED_FILES_PATH.slice(1); +CHANGES_DIFF_PATH.slice(1); +CHANGES_OPEN_PATH.slice(1); +//#endregion +//#region lib/types/presented.js +/** Authenticated POST route for opening a workspace file on the Host desktop. */ +const PRESENT_OPEN_PATH = "/api/present.open"; +/** Authenticated desktop availability and destination metadata. */ +const PRESENT_HOST_PATH = "/api/present.host"; +PRESENT_OPEN_PATH.slice(1); +PRESENT_HOST_PATH.slice(1); +/** +* Validate a file declaration read from a Session log. +* @param value - decoded durable data. +* @returns whether the declaration contains a path and optional description. +*/ +function isPresentedFile(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const { path, description } = value; + return typeof path === "string" && path.trim().length > 0 && (description === void 0 || typeof description === "string"); +} +/** +* Validate a delivery event before reading its turn or file declarations. +* @param value - decoded durable event data. +* @returns whether the event identifies a turn, call, and file list. +*/ +function isPresentedData(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const { turn, callId, files } = value; + return typeof turn === "number" && Number.isSafeInteger(turn) && turn >= 1 && typeof callId === "string" && callId.length > 0 && Array.isArray(files); +} +//#endregion +//#region lib/types/present-open.js +/** +* Register the deliverables routes inside Connection's authentication fence: +* desktop metadata, change summaries and comparisons, declared-file actions, +* and changed-file opening. +* @param ctx - Session lookup, change summaries, native opener, and route lifetime. +*/ +function registerPresentOpen(ctx) { + ctx.connection.fetch.register({ + path: PRESENT_HOST_PATH, + methods: ["GET"], + requestBody: "buffered", + fetch: () => Promise.resolve(Response.json(ctx.sessionController.workspaceDesktop(), { headers: { "cache-control": "no-store" } })) + }); + ctx.connection.fetch.register({ + path: CHANGED_FILES_PATH, + methods: ["GET"], + requestBody: "buffered", + fetch: (request) => Promise.resolve(handleChangesSummary(ctx, request)) + }); + const lifetime = new AbortController(); + const pending = /* @__PURE__ */ new Set(); + ctx.effect(() => async () => { + lifetime.abort(); + await Promise.allSettled(pending); + }); + const routes = [ + [ + PRESENT_OPEN_PATH, + ["GET", "POST"], + handlePresentOpen + ], + [ + CHANGES_OPEN_PATH, + ["GET", "POST"], + handleChangesOpen + ], + [ + CHANGES_DIFF_PATH, + ["GET"], + handleChangesDiff + ] + ]; + for (const [path, methods, handler] of routes) ctx.connection.fetch.register({ + path, + methods: [...methods], + requestBody: "buffered", + fetch: (request) => { + const task = handler(ctx, new Request(request, { signal: AbortSignal.any([request.signal, lifetime.signal]) })); + pending.add(task); + task.then(() => { + pending.delete(task); + }, () => { + pending.delete(task); + }); + return task; + } + }); +} +const NUMERIC = /^\d+$/; +function coordinate(value) { + return value !== null && NUMERIC.test(value) && Number.isSafeInteger(Number(value)) ? Number(value) : void 0; +} +/** Translate lookup and filesystem failures into the not-found or failure status the browser retries from. */ +function failureStatus(error) { + const remote = remoteErrorOf(error); + return remote?.code === "session/not-found" || remote?.code === "workspace-file/not-found" || remote?.code === "workspace-file/not-regular-file" || error instanceof Error && "code" in error && (error.code === "SESSION_QUERY_SESSION_NOT_FOUND" || error.code === "SESSION_QUERY_EVENT_NOT_FOUND" || error.code === "ENOENT" || error.code === "ENOTDIR") ? 404 : 500; +} +/** +* Read the addressed event once the Host desktop is known to be available. +* @returns the event with its Session header, or the refusal to answer with. +*/ +async function readTarget(ctx, request, id, seq) { + request.signal.throwIfAborted(); + if (!ctx.sessionController.workspaceDesktop().available) return new Response("Host desktop unavailable.", { status: 409 }); + return ctx.sessionQuery.readEvent({ + sessionId: id, + seq, + before: 0, + after: 0 + }, request.signal); +} +/** +* Open one verified Host path. A file is verified through the Session +* filesystem; a directory is verified by the Host filesystem mapping alone. +* @returns the HTTP status to answer with. +*/ +async function openVerified(ctx, request, path, action) { + const { fs } = ctx; + const mapped = fs.processPathFromHostPath(path); + if (mapped === void 0 || fs.processPath(await fs.resolve(mapped, { signal: request.signal })) !== path) return new Response("Path has no verified Host path.", { status: 422 }); + request.signal.throwIfAborted(); + if (request.method === "GET") return Response.json(await ctx.sessionController.workspacePathApplications({ path }, request.signal), { headers: { "cache-control": "no-store" } }); + const application = new URL(request.url).searchParams.get("application"); + await ctx.sessionController.openWorkspacePath({ + path, + ...action === "reveal" ? { action } : application === null ? {} : { application } + }, request.signal); + return new Response(null, { + status: 204, + headers: { "cache-control": "no-store" } + }); +} +async function handlePresentOpen(ctx, request) { + const query = new URL(request.url).searchParams; + const action = query.get("action") ?? "open"; + if (action !== "open" && action !== "reveal") return new Response("Invalid file action.", { status: 400 }); + const id = query.get("sessionId"); + const seq = coordinate(query.get("seq")); + const index = coordinate(query.get("index")); + if (!id || seq === void 0 || index === void 0) return new Response("Invalid Presented file coordinates.", { status: 400 }); + try { + const read = await readTarget(ctx, request, id, seq); + if (read instanceof Response) return read; + const { target, session } = read; + const file = target.type === "deliverables/presented" && isPresentedData(target.data) ? target.data.files[index] : void 0; + if (!isPresentedFile(file)) return new Response("Presented file not found in this Session result.", { status: 404 }); + request.signal.throwIfAborted(); + const { absolutePath: path } = await ctx.workspaceFiles.stat({ + sessionId: id, + workspaceRoot: session.cwd ?? ctx.sandboxPolicy.workspaceRoot + }, file.path, request.signal); + return await openVerified(ctx, request, path, action); + } catch (error) { + request.signal.throwIfAborted(); + return new Response("Presented file unavailable.", { status: failureStatus(error) }); + } +} +/** The summary one `workspace/changes` event announced, without the Host working directory; 404 once the Host no longer serves it. */ +function handleChangesSummary(ctx, request) { + const query = new URL(request.url).searchParams; + const id = query.get("sessionId"); + const seq = coordinate(query.get("seq")); + if (!id || seq === void 0) return new Response("Invalid change summary coordinates.", { status: 400 }); + const summary = ctx.workspaceChanges.summary(id, seq); + if (summary === void 0) return new Response("Change summary unavailable.", { status: 404 }); + const { turn, files, total, added, deleted } = summary; + return Response.json({ + turn, + files, + total, + added, + deleted + }, { headers: { "cache-control": "no-store" } }); +} +/** A changed file's coordinates from a route query, or the 400 to answer with. */ +function changedFileCoordinates(request) { + const query = new URL(request.url).searchParams; + const id = query.get("sessionId"); + const seq = coordinate(query.get("seq")); + const index = coordinate(query.get("index")); + if (!id || seq === void 0 || index === void 0) return new Response("Invalid changed file coordinates.", { status: 400 }); + return { + id, + seq, + index + }; +} +/** One listed file's comparison; 404 once the Host no longer serves the summary or the index names no file. */ +async function handleChangesDiff(ctx, request) { + const coordinates = changedFileCoordinates(request); + if (coordinates instanceof Response) return coordinates; + const { id, seq, index } = coordinates; + try { + const diff = await ctx.workspaceChanges.diff(id, seq, index, request.signal); + if (diff === void 0) return new Response("Change comparison unavailable.", { status: 404 }); + return Response.json(diff, { headers: { "cache-control": "no-store" } }); + } catch (error) { + request.signal.throwIfAborted(); + return new Response("Change comparison unavailable.", { status: failureStatus(error) }); + } +} +async function handleChangesOpen(ctx, request) { + const action = new URL(request.url).searchParams.get("action") ?? "open"; + if (action !== "open" && action !== "reveal") return new Response("Invalid file action.", { status: 400 }); + const coordinates = changedFileCoordinates(request); + if (coordinates instanceof Response) return coordinates; + const { id, seq, index } = coordinates; + try { + request.signal.throwIfAborted(); + if (!ctx.sessionController.workspaceDesktop().available) return new Response("Host desktop unavailable.", { status: 409 }); + const changes = ctx.workspaceChanges.summary(id, seq); + if (changes === void 0) return new Response("Change summary unavailable.", { status: 404 }); + const workspaceRoot = changes.cwd; + const file = changes.files[index]; + if (file === void 0) return new Response("Changed file not found in this summary.", { status: 404 }); + const { absolutePath: path } = await ctx.workspaceFiles.stat({ + sessionId: id, + workspaceRoot + }, file.path, request.signal); + return await openVerified(ctx, request, path, action); + } catch (error) { + request.signal.throwIfAborted(); + return new Response("Changed file unavailable.", { status: failureStatus(error) }); + } +} +//#endregion +//#region lib/types/index.js +/** +* Deliverables plugin, node half. Serves authenticated native opens of declared files. The browser +* half ships via exports["./client"], discovered through the package.json +* dsh.client declaration. +*/ +/** Services required for change summaries and authenticated native opens. */ +const inject = [ + "connection", + "sessionQuery", + "sessionController", + "workspaceFiles", + "fs", + "sandboxPolicy", + "workspaceChanges" +]; +/** +* Register native opens for declared files. +* @param ctx - host context carrying file and connection services. +*/ +function apply(ctx) { + registerPresentOpen(ctx); +} +//#endregion +export { apply, inject }; diff --git a/packages/dsh-deliverables/package.json b/packages/dsh-deliverables/package.json new file mode 100644 index 0000000..8960df5 --- /dev/null +++ b/packages/dsh-deliverables/package.json @@ -0,0 +1,37 @@ +{ + "name": "dsh-deliverables", + "version": "0.1.0-alpha.1", + "description": "Deliverables and the turn Review tab: the changed-files card, the presented-file cards and the per-turn review. A GENERATED fork of @deepseek-ai/dsh-client-ui-deliverables (Node and browser halves) whose one patch draws an image change as the picture instead of 'Binary file; changes cannot be shown'. Its bundle layer disables the core row, so this is the copy that runs.", + "type": "module", + "main": "lib/index.js", + "exports": { + ".": "./lib/index.js", + "./client": "./lib/client.js", + "./package.json": "./package.json" + }, + "files": [ + "lib", + "cordis.patch.yml" + ], + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web", + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-connection", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-chat", + "@deepseek-ai/dsh-client-ui-conversation", + "@deepseek-ai/dsh-client-ui-renderer", + "@deepseek-ai/dsh-client-ui-sidebar-right", + "@deepseek-ai/dsh-client-ui-tool", + "@deepseek-ai/dsh-client-ui-settings", + "@deepseek-ai/dsh-client-ui-context-menu" + ] + } + }, + "license": "AGPL-3.0-only" +} diff --git a/packages/dsh-hyperframes/README.md b/packages/dsh-hyperframes/README.md new file mode 100644 index 0000000..0d7a722 --- /dev/null +++ b/packages/dsh-hyperframes/README.md @@ -0,0 +1,142 @@ +# dsh-hyperframes (alpha.1) + +**Moving figures.** Six `anim_*` tools over the user's own +[HyperFrames](https://github.com/heygen-com/hyperframes) CLI (Apache-2.0): write a +composition as HTML, check it, look at its stills, render it to MP4 — with the rung +that was actually reached stated on every answer. + +Host-only. One row, no route, no browser half: a project is a folder in the +workspace, and the player is `dsh-video`'s tab over `dsh-media`'s Range route. + +## Why this row exists + +This pack could already photograph a page (`shot_url`), photograph a real window +(`shot_window`), probe and play a video (`dsh-media`, `dsh-video`), and compile a +publication figure (`dsh-diagrams`, `dsh-tables`). It could not **author time**: +every picture it made was a picture of something that already existed. + +HyperFrames renders HTML to video by seeking a *paused* timeline frame by frame, so +the same input produces the same frames. That is the property worth a row, and its +CLI is the first renderer here built to be driven by an agent: `HF_TOOL_CONTEXT` +hands back the absolute paths of the frames and contact sheets a command produced, +`project-lock` waits its turn instead of racing another browser command, and +`check-review` saves a plain frame per finding. + +## What it adds + +| Tool | The CLI behind it | What comes back | Rung | +|---|---|---|---| +| `anim_status` | `--version`, `doctor --json` | the CLI, Node ≥ 22, a browser, ffmpeg — the four facts that fail independently — and the install line when the CLI is absent | `a0` | +| `anim_new` | none (this package's template) | a project in the workspace: `index.html`, `compositions/.html`, `assets/`, `caption.md` | `a0` | +| `anim_scene` | none (writes HTML) | one scene from a figure file — an SVG from `diagram_write`, a PNG from `table_write`, a still from `shot_url` — with a caption and alt text | `a0` | +| `anim_check` | `lint --json`, then `check --json` | findings passed through as the CLI wrote them, the frames around them, and whether the browser actually ran | `a1`/`a2` | +| `anim_snapshot` | `snapshot --at … --json` | stills and a contact sheet, copied into `/snapshots/`, with no encode | `a3` | +| `anim_render` | `render --output …` | the file, its ffprobe facts (duration, fps, size, codec) and the provenance tags — and it refuses when the last check found errors | `a4` | + +**The rung ladder is the contract:** + +``` +a0-source the structure holds and this package's own static check passed +a1-lint `lint --json` ran with no errors (a parser, no browser) +a2-checked `check --json` ran in a browser and is ok (layout / motion / contrast) +a3-stilled `snapshot` wrote frames and the pictures came back +a4-rendered `render` wrote a file and ffprobe agrees with what was asked +``` + +A `check` that reports `browserSkipped: true` is **not** a pass — its layout and +contrast sections are empty, not clean — so it does not reach `a2`. `anim_render` +names the last check it saw, because "it rendered" and "it is correct" are different +claims. + +## The policy it obeys + +- **Never `npx`.** npx downloads a package when it is missing, which is an install + with another name. The binary is `hyperframes` on PATH, `DSH_HYPERFRAMES_CLI`, or a + copy an earlier `npx` run already extracted into the npx cache — a file this + machine already has, run through `node`. +- **Nothing installed, no Chrome downloaded.** Every child gets + `HYPERFRAMES_NO_TELEMETRY=1`, `DO_NOT_TRACK=1`, `NO_UPDATE_CHECK`, + `NO_AUTO_INSTALL`, `NO_OPTIONAL_INSTALL`, `NO_CAPTURE_DOTENV`, `SKIP_SKILLS`, and + `HYPERFRAMES_BROWSER_PATH` pointing at the browser this host already has. +- **The subcommands it never runs:** `skills`, `events` (the usage beacon), `auth`, + `share`, `publish`, `cloud`, `lambda`, `tts`, `models`, `capture`, `browser ensure`, + `init`. +- **ffmpeg is resolved, not assumed.** HyperFrames has no ffmpeg-path variable, so + the row reads `dsh-media`'s own rules (`DSH_MEDIA_FFMPEG`, then PATH, then + `$DSH_HOME/dsh-media/bin/-/`) and **prepends that directory to the + child's PATH**. It reads the same variables instead of importing `dsh-media`'s + files, because a bundle may not import another bundle's files. +- **Argv only, outputs scoped.** A project, a render and a snapshot folder resolve + inside the session workspace, or inside an `allowRoot` for that call. + +## The science layer + +HyperFrames has no TeX, no chart library and no bundled math font — so an equation +or a mechanism diagram enters a composition as a **vector the pack already +produced**. That is what `anim_scene` is for, and it is why the caption file matters: +every project carries `caption.md` with the poster frame's alt text, the transcript, +the duration and the scene list, so a reader who cannot play the video still gets the +figure and its legend. + +## Three worked examples + +`examples/dashboard-ui` (an analytics console: count-ups, bars from a baseline, a +tooltip placed from the layout), `examples/chat-ui` (an assistant: staggered thread +rows, a deterministic token stream, a code block), `examples/saas-landing` (a product +page in a browser window: line-by-line headline, an auto-scrolling phone, SVG +draw-on). Each is lint-clean as written, each has a `SPEC.md` and a `caption.md`, and +each is checked at `a0` by this package's own check. + +## Limits + +- **The CLI is not installed by this row.** `anim_status` names + `npm install --global hyperframes` and stops. Without it the tools answer `a0` and + say why. +- **A render is minutes.** 12 s at 1080p30 is 360 browser seeks plus an encode; use + `quality: "draft"` while iterating and `snapshot` before either. +- **A font can be fetched.** The compiler fetches a missing weight of a bundled + family from Google Fonts on first use and caches it. Name only what the machine has, + or ship a `woff2` in `assets/fonts/`. +- **Byte-exactness is per engine.** Same composition, same Chrome, same fonts → + the same frames. A different Chrome or font resolution can shift a pixel; + `render --docker` pins all three, and this row does not drive Docker. +- **16 MB per composition file** (`COMPOSITION_TOO_LARGE`). Media, fonts and data + live in `assets/` and are referenced by path. +- A composition wider than 4096 px renders but cannot be inspected by `check` / + `snapshot`, which clamp to that viewport. + +## Verify + +```sh +cd packages/dsh-hyperframes && npm run check +``` + +About 130 assertions, offline: the resolver (including the `.cmd` shim trap and the +npx-cache fallback), the argv builder, the child env policy, `HF_TOOL_CONTEXT`, every +JSON reader against real 0.9.106 envelopes, the rung ladder, the project template, the +scene writer, the six tools' registration, and each example at `a0`. The **live half** +lints the three examples with the real CLI when it is on the machine, and says loudly +when it is not. + +Pack-wide: `node scripts/checks/check-node-routes.mjs`, +`check-client-bundles.mjs` (no client bundle, and it says so), +`check-no-secrets.mjs`. + +## Layout + +``` +lib/cli.js resolve the binary, the policy env, argv, deadlines, tree kill, HF_TOOL_CONTEXT +lib/project.js the template, the scene writer, the caption, a0-source +lib/report.js the four JSON readers, the rung ladder, finding formatting +lib/tools.js the six tools +examples/ dashboard-ui, chat-ui, saas-landing +skills/ hyperframes-composition, hyperframes-render, html-ui-animation +checks/ the tracked check +``` + +## Install + +The launcher (`scripts\setup\install.bat` / `./scripts/setup/install.sh`) auto-discovers +the package as a standard `dsh.bundle`. It is a live link in the web profile, so a +`lib/` change needs a restart of `npx @deepseek-ai/dsh web`; the examples and the +skills are read from disk. diff --git a/packages/dsh-hyperframes/checks/check-hyperframes.mjs b/packages/dsh-hyperframes/checks/check-hyperframes.mjs new file mode 100644 index 0000000..4656e78 --- /dev/null +++ b/packages/dsh-hyperframes/checks/check-hyperframes.mjs @@ -0,0 +1,562 @@ +/** + * dsh-hyperframes - the tracked check. + * + * WHAT IT PROVES, and what it deliberately cannot: + * + * It proves the parts that are this package's own: the resolver (including the + * `.cmd`-shim trap and the npx-cache fallback), the argv builder, the child env + * policy, the `HF_TOOL_CONTEXT` declaration, every JSON reader against REAL + * envelopes captured from hyperframes 0.9.106, the rung ladder, the project + * template and the scene writer, the six tools' registration, and that each of the + * three examples still passes `a0-source`. + * + * It CANNOT prove a render, because that needs the CLI and a browser. That is the + * live half: when `hyperframes` is on this machine the examples are linted too, and + * when it is not the check says so loudly and still passes - the same shape + * `dsh-deckcraft`'s check uses. + */ + +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { + DEFAULT_LOCK_WAIT_MS, + buildArgs, + buildToolContext, + childEnv, + entryFor, + parseJsonDocument, + parseResultLine, + readEvents, + resolveBrowser, + resolveCli, + resolveFfmpeg, + runCli, + times, +} from '../lib/cli.js' +import { addScene, assertInside, captionMarkdown, projectInfo, resolveProject, scaffoldProject, sourceCheck } from '../lib/project.js' +import { + RUNGS, + collectFindings, + formatFinding, + rungFor, + rungLine, + summariseCheck, + summariseDoctor, + summariseLint, + summariseSnapshot, +} from '../lib/report.js' +import { buildTools } from '../lib/tools.js' +import { PLUGIN_VERSION } from '../lib/index.js' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const pkgRoot = path.resolve(here, '..') + +let passed = 0 +const failures = [] +const skipped = [] + +function ok(condition, label, detail = '') { + if (condition) { + passed += 1 + return true + } + failures.push(label + (detail === '' ? '' : ' — ' + detail)) + return false +} + +function eq(actual, expected, label) { + return ok(actual === expected, label, 'expected ' + JSON.stringify(expected) + ', got ' + JSON.stringify(actual)) +} + +function section(title) { + process.stdout.write('\n' + title + '\n') +} + +function skip(label, reason) { + skipped.push(label + ' — ' + reason) + process.stdout.write(' SKIP ' + label + ' (' + reason + ')\n') +} + +/* ---------------------------------------------------------------- fixtures */ +/* Captured from hyperframes 0.9.106 on this machine, not invented. */ + +const LINT_OK = { + ok: true, + errorCount: 0, + warningCount: 0, + infoCount: 0, + findings: [], + filesScanned: 2, + unmountedCompositions: [], + _meta: { version: '0.9.106', updateAvailable: false }, +} + +const LINT_BAD = { + ok: false, + errorCount: 1, + warningCount: 0, + infoCount: 0, + findings: [ + { + code: 'missing_timeline_registry', + severity: 'error', + message: 'Missing `window.__timelines` registration.', + fixHint: 'Register each composition timeline on `window.__timelines[compositionId]`.', + file: 'C:\\proj\\index.html', + }, + ], + filesScanned: 2, + unmountedCompositions: [], + _meta: { version: '0.9.106' }, +} + +const SNAPSHOT_OK = { + ok: true, + outputDir: 'C:\\proj\\.hyperframes\\artifacts\\snapshots\\abc', + frames: [ + { path: 'C:\\proj\\.hyperframes\\artifacts\\snapshots\\abc\\frame-00-at-1s.png', time: 1 }, + { path: 'C:\\proj\\.hyperframes\\artifacts\\snapshots\\abc\\frame-01-at-3s.png', time: 3 }, + ], + contactSheets: ['C:\\proj\\.hyperframes\\artifacts\\snapshots\\abc\\contact-sheet.jpg'], + _meta: { version: '0.9.106' }, +} + +const DOCTOR_MIXED = { + ok: false, + platform: 'win32', + arch: 'x64', + checks: [ + { name: 'Node.js', ok: true, detail: 'v22.20.0 (win32 x64)' }, + { name: 'Chrome', ok: true, detail: 'system: C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe' }, + { name: 'FFmpeg', ok: true, detail: 'ffmpeg 2023-06-08 at C:\\ffmpeg\\bin\\ffmpeg.exe' }, + { name: 'FFprobe', ok: true, detail: 'ffprobe 2023-06-08 at C:\\ffmpeg\\bin\\ffprobe.exe' }, + { name: 'whisper-cpp', ok: false, detail: 'Not found (optional — needed for transcription)' }, + { name: 'Docker running', ok: false, detail: 'Not running' }, + ], + _meta: { version: '0.9.106' }, +} + +const CHECK_OK = { + ok: true, + browserSkipped: false, + lint: { findings: [] }, + layout: { findings: [] }, + motion: { findings: [] }, + contrast: { findings: [{ code: 'contrast_low', severity: 'error', message: 'text is 3.1:1', selector: '#doc-sub' }] }, + craft: { findings: [] }, + snapshots: [], + _meta: { version: '0.9.106' }, +} + +const CHECK_SKIPPED = { ok: false, browserSkipped: true, lint: { findings: [] }, layout: {}, contrast: {}, _meta: { version: '0.9.106' } } + +const scratch = mkdtempSync(path.join(tmpdir(), 'dsh-hyperframes-check-')) + +/* ---------------------------------------------------------------- 1. the row */ + +section('the row and its manifest') +{ + const pkg = JSON.parse(readFileSync(path.join(pkgRoot, 'package.json'), 'utf8')) + eq(pkg.name, 'dsh-hyperframes', 'package name') + eq(pkg.version, PLUGIN_VERSION, 'PLUGIN_VERSION is in step with package.json') + eq(pkg.engines.node, '>=22', 'the Node floor matches the CLI\'s own (>= 22)') + eq(Object.keys(pkg.dependencies ?? {}).length, 0, 'zero npm dependencies') + ok(Array.isArray(pkg.files) && pkg.files.includes('examples'), 'the examples ship in the package') + ok(existsSync(path.join(pkgRoot, 'cordis.patch.yml')), 'the bundle layer exists') + const patch = readFileSync(path.join(pkgRoot, 'cordis.patch.yml'), 'utf8') + ok(/id: hyperframes/.test(patch), 'the bundle layer inserts the hyperframes row') + ok(!/disablesRows:/.test(patch), 'the row disables no core row') +} + +/* ---------------------------------------------------------------- 2. resolver */ + +section('the CLI resolver') +{ + const home = path.join(scratch, 'home') + mkdirSync(home, { recursive: true }) + + const missing = resolveCli({ PATH: '', LOCALAPPDATA: path.join(scratch, 'no-npx') }, 'win32', home) + eq(missing.command, '', 'no CLI anywhere resolves to an empty command') + eq(missing.source, 'missing', 'and says so as `missing`') + + const emptyCache = resolveCli({ PATH: '', LOCALAPPDATA: path.join(scratch, 'local-empty') }, 'win32', home) + eq(emptyCache.source, 'missing', 'an npx cache with no hyperframes in it is not a candidate') + + // The cache this machine's own `npx` writes: %LOCALAPPDATA%\npm-cache\_npx\\node_modules\hyperframes + const localApp = path.join(scratch, 'local') + const hashDir = path.join(localApp, 'npm-cache', '_npx', 'abc123', 'node_modules', 'hyperframes', 'bin') + mkdirSync(hashDir, { recursive: true }) + writeFileSync(path.join(hashDir, 'hyperframes.mjs'), 'export {}\n', 'utf8') + writeFileSync(path.join(hashDir, '..', 'package.json'), '{"version":"0.9.107"}', 'utf8') + const fromCache = resolveCli({ PATH: '', LOCALAPPDATA: localApp }, 'win32', home) + eq(fromCache.source, 'npx-cache', 'a copy in the npx cache is found') + eq(fromCache.command, process.execPath, 'and is run through THIS node, never npx') + ok(typeof fromCache.prefixArgs?.[0] === 'string' && fromCache.prefixArgs[0].endsWith('hyperframes.mjs'), 'with the .mjs as its first argument') + eq(fromCache.version, '0.9.107', 'and its version read from the tree, without spawning') + + // A redirected cache (npm_config_cache) is asked FIRST: this repository's own + // harness moves it to /.vncode/npm-cache, so the platform default is not + // where an `npx hyperframes` run lands here. + const redirect = path.join(scratch, 'npmcache') + const redirectMjs = path.join(redirect, '_npx', 'zzz', 'node_modules', 'hyperframes', 'bin', 'hyperframes.mjs') + mkdirSync(path.dirname(redirectMjs), { recursive: true }) + writeFileSync(redirectMjs, 'export {}\n', 'utf8') + const redirected = resolveCli({ PATH: '', npm_config_cache: redirect }, 'win32', home) + eq(redirected.source, 'npx-cache', 'an npm_config_cache pointing elsewhere is honoured') + eq(redirected.path, redirectMjs, 'and that is the copy used') + + const binDir = path.join(scratch, 'bin') + mkdirSync(binDir, { recursive: true }) + const shim = path.join(binDir, 'hyperframes') + writeFileSync(shim, '#!/bin/sh\n', 'utf8') + const onPath = resolveCli({ PATH: binDir }, 'linux', home) + eq(onPath.source, 'PATH', 'a binary on PATH wins over the cache') + eq(onPath.command, shim, 'and is the command itself (POSIX)') + + const cmdShim = path.join(scratch, 'npm-shim', 'hyperframes.cmd') + mkdirSync(path.dirname(cmdShim), { recursive: true }) + writeFileSync(cmdShim, '@echo off\n', 'utf8') + eq(entryFor(cmdShim, 'win32'), null, 'a .cmd with no sibling .mjs is REFUSED rather than routed through cmd.exe') + const sibling = path.join(scratch, 'npm-shim', 'node_modules', 'hyperframes', 'bin', 'hyperframes.mjs') + mkdirSync(path.dirname(sibling), { recursive: true }) + writeFileSync(sibling, 'export {}\n', 'utf8') + const viaShim = entryFor(cmdShim, 'win32') + ok(viaShim !== null && viaShim.command === process.execPath, 'a .cmd WITH a sibling .mjs is resolved to node + .mjs') + eq(entryFor(path.join(scratch, 'nope'), 'win32'), null, 'a path that is not there is not an entry') + + const override = resolveCli({ PATH: '', DSH_HYPERFRAMES_CLI: path.join(scratch, 'gone') }, 'win32', home) + eq(override.source, 'missing-override', 'a bad DSH_HYPERFRAMES_CLI is reported by name') + const good = resolveCli({ PATH: '', DSH_HYPERFRAMES_CLI: sibling }, 'win32', home) + eq(good.source, 'DSH_HYPERFRAMES_CLI', 'a working DSH_HYPERFRAMES_CLI wins over everything') +} + +/* ---------------------------------------------------------------- 3. argv */ + +section('the argv builder') +{ + eq(JSON.stringify(buildArgs('version')), '["--version"]', 'version') + eq(JSON.stringify(buildArgs('doctor')), '["doctor","--json"]', 'doctor asks for JSON') + eq(JSON.stringify(buildArgs('lint', { dir: 'C:\\p' })), '["lint","C:\\\\p","--json"]', 'lint takes the project dir, not a file') + eq(times([3, 9.5, '12s']), '3,9.5,12', '`at` becomes one comma-separated argument') + ok(throws(() => times([Number.NaN])), 'a non-numeric time is refused') + ok(throws(() => times(new Array(25).fill(1))), 'more than 24 times is refused') + ok(throws(() => buildArgs('nope')), 'an unknown verb throws instead of reaching the CLI') + ok(throws(() => buildArgs('render', { dir: 'p' })), 'a render with no output throws') + ok(throws(() => buildArgs('lint', {})), 'a command with no project dir throws') + + const snap = buildArgs('snapshot', { dir: 'p', at: [3, 9], review: true }) + ok(snap.includes('--at') && snap.includes('3,9'), 'snapshot carries --at') + ok(snap.includes('--review'), 'snapshot carries --review when asked') + const check = buildArgs('check', { dir: 'p', range: '2,8' }) + ok(check.includes('--snapshots') && check.includes('--range'), 'check asks for snapshots and honours --range') + const render = buildArgs('render', { dir: 'p', out: 'C:\\p\\out.mp4', format: 'mp4', quality: 'draft', fps: 30, variables: { title: 'Q3' } }) + eq(render[0], 'render', 'render is the verb') + ok(render.includes('--output') && render.includes('C:\\p\\out.mp4'), 'render carries --output as ONE argv element') + ok(render.includes('--quality') && render.includes('draft'), 'render carries the quality tier') + ok(render.some((part) => part === '{"title":"Q3"}'), 'variables are passed as JSON, in one argument') +} + +function throws(fn) { + try { + fn() + return false + } catch { + return true + } +} + +/* ---------------------------------------------------------------- 4. env */ + +section('the child env policy') +{ + const env = childEnv({ PATH: 'C:\\a', ProgramFiles: 'C:\\Program Files' }, { browser: 'C:\\chrome.exe', ffmpegDir: 'C:\\ffmpeg\\bin' }) + eq(env.HYPERFRAMES_NO_TELEMETRY, '1', 'telemetry is off') + eq(env.DO_NOT_TRACK, '1', 'DO_NOT_TRACK is set too') + eq(env.HYPERFRAMES_NO_UPDATE_CHECK, '1', 'no update check') + eq(env.HYPERFRAMES_NO_OPTIONAL_INSTALL, '1', 'no optional install') + eq(env.HYPERFRAMES_NO_AUTO_INSTALL, '1', 'no auto-install (this is what keeps Chrome from being downloaded)') + eq(env.HYPERFRAMES_NO_CAPTURE_DOTENV, '1', 'no .env pickup') + eq(env.HYPERFRAMES_SKIP_SKILLS, '1', 'no skill install') + eq(env.HYPERFRAMES_AGENT, '1', 'declared as an agent run') + eq(env.HYPERFRAMES_BROWSER_PATH, 'C:\\chrome.exe', 'the browser this host already has is named, so none is fetched') + ok(env.PATH.startsWith('C:\\ffmpeg\\bin' + path.delimiter), 'the ffmpeg directory is PREPENDED to PATH (the CLI has no ffmpeg-path variable)') + ok(!('HF_TOOL_CONTEXT' in childEnv({}, {})), 'HF_TOOL_CONTEXT is not set globally - only per call') + + const ff = resolveFfmpeg({ PATH: 'C:\\a', ProgramFiles: 'C:\\Program Files' }, 'win32', scratch, 'x64') + eq(ff.source, 'missing', 'no ffmpeg on PATH and none provisioned resolves to missing') + const provDir = path.join(scratch, '.dsh', 'dsh-media', 'bin', 'win32-x64') + mkdirSync(provDir, { recursive: true }) + writeFileSync(path.join(provDir, 'ffmpeg.exe'), 'x', 'utf8') + const prov = resolveFfmpeg({ PATH: '', DSH_HOME: path.join(scratch, '.dsh') }, 'win32', scratch, 'x64') + eq(prov.source, 'dsh-media', 'the copy dsh-media provisioned is found by reading its own variables') + ok(resolveBrowser({ ProgramFiles: 'C:\\nope', 'ProgramFiles(x86)': 'C:\\nope' }, 'win32') === '', 'no browser is reported as an empty string, not guessed') +} + +/* ---------------------------------------------------------------- 5. context + json */ + +section('HF_TOOL_CONTEXT and the JSON readers') +{ + const context = JSON.parse(buildToolContext({ eventsPath: 'C:\\tmp\\e.ndjson', waitMs: 60000, checkReview: { findingFrames: true } })) + eq(context.version, 1, 'the declaration is version 1') + eq(context.capabilities.events.transport.type, 'ndjson-file', 'events travel as an ndjson file') + eq(context.capabilities.events.transport.path, 'C:\\tmp\\e.ndjson', 'with an absolute path') + eq(context.capabilities['project-lock'].waitMs, 60000, 'the project lock waits rather than racing') + eq(context.capabilities['check-review'].findingFrames, true, 'check-review asks for a frame per finding') + eq(buildToolContext({ waitMs: 0 }), '', 'no capabilities means no variable at all') + eq(DEFAULT_LOCK_WAIT_MS, 60000, 'the default lock wait is a minute') + + const noisy = '◆ Capturing 2 frames\n' + JSON.stringify(LINT_OK) + '\n[done]\n' + const parsed = parseJsonDocument(noisy) + ok(parsed !== null && parsed.ok === true, 'the JSON envelope is cut out of a noisy stream') + eq(parseJsonDocument('not json at all'), null, 'and nothing is invented when there is none') + const line = parseResultLine('noise\n@hf-result {"operation":"render","reference_background":{"kind":"solid"}}\n') + ok(line !== null && line.operation === 'render', 'the @hf-result line is read') + const eventsPath = path.join(scratch, 'events.ndjson') + writeFileSync(eventsPath, '{"version":1,"type":"artifact.created","artifact":{"role":"frame","path":"a.png"}}\nnot json\n', 'utf8') + eq(readEvents(eventsPath).length, 1, 'one bad event line does not lose the good one') + eq(readEvents(path.join(scratch, 'gone.ndjson')).length, 0, 'a missing event file is empty, not an error') +} + +/* ---------------------------------------------------------------- 6. report */ + +section('the report readers and the rung ladder') +{ + const lint = summariseLint(LINT_OK) + ok(lint.ok === true && lint.errors === 0, 'a clean lint envelope reads clean') + eq(lint.version, '0.9.106', 'and carries the CLI version') + const bad = summariseLint(LINT_BAD) + eq(bad.errors, 1, 'a lint error is counted') + const text = formatFinding(bad.findings[0], 0) + ok(text.includes('missing_timeline_registry'), 'the finding keeps its code') + ok(text.includes('Fix:'), 'and its fixHint') + + const doctor = summariseDoctor(DOCTOR_MIXED) + eq(doctor.ok, false, 'doctor\'s top-level ok is false here') + eq(doctor.ready, true, 'but the RENDER GATES are all green: an optional whisper or Docker is not a render gate') + eq(doctor.gates.chrome.ok, true, 'Chrome is a gate and it is read by name') + ok(doctor.others.some((row) => row.name === 'whisper-cpp' && row.ok === false), 'optional absences are kept apart from the gates') + + const checked = summariseCheck(CHECK_OK) + eq(checked.ran, true, 'a check with a browser ran') + eq(checked.findings.length, 1, 'and its nested finding is found') + eq(checked.findings[0].phase, 'contrast', 'with the phase it came from') + const skippedCheck = summariseCheck(CHECK_SKIPPED) + eq(skippedCheck.skipped, true, 'browserSkipped is reported as skipped') + eq(skippedCheck.ran, false, 'and NOT as ran') + ok(skippedCheck.reason.includes('EMPTY, not clean'), 'and the answer says what that means') + + const snap = summariseSnapshot(SNAPSHOT_OK) + eq(snap.frames.length, 2, 'two frames read') + eq(snap.frames[1].time, 3, 'with their times') + eq(snap.contactSheets.length, 1, 'and the contact sheet') + + const nested = collectFindings({ a: { findings: [{ code: 'x', message: 'm' }] }, b: [{ code: 'y', severity: 'error' }] }) + eq(nested.length, 2, 'findings are collected from any depth') + eq(nested[0].phase, 'a', 'with the key path they were found under') + + const r0 = rungFor({ sourceOk: true }) + eq(r0.rung.id, 'a0-source', 'source only reaches a0') + const rBad = rungFor({ sourceOk: true, lint: bad }) + eq(rBad.rung.id, 'a0-source', 'a lint error does NOT reach a1') + const r1 = rungFor({ sourceOk: true, lint }) + eq(r1.rung.id, 'a1-lint', 'a clean lint reaches a1') + const r2 = rungFor({ sourceOk: true, lint, check: checked }) + eq(r2.rung.id, 'a2-checked', 'a browser check reaches a2 even when it found problems') + const r2s = rungFor({ sourceOk: true, lint, check: skippedCheck }) + eq(r2s.rung.id, 'a1-lint', 'a SKIPPED browser check does not reach a2') + const r3 = rungFor({ sourceOk: true, lint, check: checked, stilled: 2 }) + eq(r3.rung.id, 'a3-stilled', 'stills reach a3') + const r4 = rungFor({ sourceOk: true, lint, check: checked, stilled: 2, rendered: { ok: true, file: 'x.mp4' } }) + eq(r4.rung.id, 'a4-rendered', 'a render reaches a4') + eq(RUNGS.length, 5, 'the ladder has five rungs') + ok(rungLine(r4).startsWith('Reached: a4-rendered'), 'the rung line names the rung') +} + +/* ---------------------------------------------------------------- 7. project */ + +section('the project template and the scene writer') +{ + const workspace = path.join(scratch, 'ws') + mkdirSync(workspace, { recursive: true }) + const root = path.join(workspace, 'videos', 'demo') + const made = scaffoldProject({ root, title: 'Demo', width: 1920, height: 1080, fps: 30, duration: 8, sceneId: 'title' }) + eq(made.files.length, 4, 'four files are written') + ok(existsSync(path.join(root, 'index.html')), 'index.html') + ok(existsSync(path.join(root, 'compositions', 'title.html')), 'the first scene') + ok(existsSync(path.join(root, 'assets', 'theme.css')), 'the theme') + ok(existsSync(path.join(root, 'caption.md')), 'the caption') + const source = sourceCheck(root) + eq(source.ok, true, 'the template passes a0-source as written: ' + source.problems.map((p) => p.message).join('; ')) + eq(source.hosts, 1, 'with one scene host') + + const html = readFileSync(path.join(root, 'index.html'), 'utf8') + ok(html.includes('window.__timelines["root"]'), 'the root registers its own timeline') + ok(html.includes('data-fps="30"'), 'the root carries the frame rate') + ok(html.includes('data-composition-variables'), 'the root declares its variables') + ok(!html.includes('Date.now('), 'no clock in the template') + + const info = projectInfo(root) + eq(info.duration, 8, 'the project reports its own duration') + eq(info.fps, 30, 'and its fps') + eq(info.scenes.length, 1, 'and its scenes') + + const figure = path.join(workspace, 'figure.svg') + writeFileSync(figure, '', 'utf8') + const added = addScene({ root, id: 'figure', figurePath: figure, duration: 4, caption: 'A blue rectangle.', alt: 'A flat blue rectangle.' }) + ok(existsSync(added.scene), 'a scene file is written') + ok(existsSync(added.asset), 'the figure is copied into assets/') + eq(added.start, 3.2, 'a new scene starts after the title scene ends (the template leaves room on purpose)') + const after = sourceCheck(root) + eq(after.ok, true, 'and the project still passes a0-source: ' + after.problems.map((p) => p.message).join('; ')) + eq(after.hosts, 2, 'with two hosts now') + const sceneText = readFileSync(added.scene, 'utf8') + ok(sceneText.includes(' addScene({ root, id: 'figure', figurePath: figure })), 'the same scene id twice is refused') + ok(throws(() => addScene({ root, id: 'too-long', figurePath: figure, start: 6, duration: 6 })), 'a scene that would overrun the composition is refused') + ok(throws(() => addScene({ root, id: 'Bad Id', figurePath: figure })), 'a scene id that is not a slug is refused') + + eq(resolveProject({ project: 'videos/demo', workspace }), path.resolve(root), 'a project resolves inside the workspace') + ok(throws(() => resolveProject({ project: 'videos/nope', workspace })), 'a missing project is refused') + ok(assertInside({ target: path.join(workspace, 'a.mp4'), workspace }).endsWith('a.mp4'), 'an output inside the workspace is allowed') + ok(throws(() => assertInside({ target: path.join(scratch, 'outside.mp4'), workspace })), 'an output outside the workspace is refused') + ok(throws(() => assertInside({ target: path.join(scratch, 'outside.mp4'), workspace: '' })), 'no workspace means no output at all') + + const caption = captionMarkdown({ title: 'Demo', width: 1920, height: 1080, fps: 30, duration: 8, scenes: ['title', 'figure'] }) + ok(caption.includes('| Duration | 8 s |'), 'the caption records the duration') + ok(caption.includes('`figure`'), 'and lists the scenes') + ok(caption.includes('poster frame'), 'and asks for a poster description') +} + +/* ---------------------------------------------------------------- 8. tools */ + +section('the six tools') +{ + const deps = { ctx: { get: () => undefined, logger: {} }, env: { PATH: '', LOCALAPPDATA: path.join(scratch, 'no-npx'), DSH_HOME: path.join(scratch, 'no-dsh') }, platform: 'win32' } + const tools = buildTools(deps) + eq(tools.length, 6, 'six tools') + const names = tools.map((tool) => tool.name) + eq(names.join(','), 'anim_status,anim_new,anim_scene,anim_check,anim_snapshot,anim_render', 'with the documented names') + ok(new Set(names).size === 6, 'the names are unique') + for (const tool of tools) { + ok(typeof tool.description === 'string' && tool.description.length > 80, tool.name + ' has a description that teaches something') + ok(tool.parameters && tool.parameters.type === 'object', tool.name + ' declares an object schema') + ok(typeof tool.execute === 'function', tool.name + ' has an execute') + } + const scene = tools.find((tool) => tool.name === 'anim_scene') + ok(scene.parameters.required.includes('project') && scene.parameters.required.includes('source'), 'anim_scene requires a project and a source') + const render = tools.find((tool) => tool.name === 'anim_render') + ok(render.parameters.properties.format.enum.includes('mp4'), 'anim_render offers the formats it can spell') + + const status = await tools[0].execute({ probe: false }, {}) + ok(status.text.includes('NOT installed'), 'anim_status with no CLI says so plainly') + ok(status.text.includes('npm install --global hyperframes'), 'and names the install line') + ok(status.text.includes('never runs `npx`'), 'and why it will not fetch it itself') + eq(status.view.ok, false, 'and does not claim the host is ready') + + const created = await tools.find((tool) => tool.name === 'anim_new').execute({ dir: 'videos/second', title: 'Second demo' }, { agent: { session: { id: 's1', header: { cwd: path.join(scratch, 'ws') } } } }) + eq(created.view.ok, true, 'anim_new writes into the workspace') + ok(created.text.includes('a0-source'), 'and reports the rung') + const escaped = await tools.find((tool) => tool.name === 'anim_new').execute({ dir: '..\\..\\outside', title: 'nope' }, { agent: { session: { id: 's1', header: { cwd: path.join(scratch, 'ws') } } } }) + eq(escaped.view.ok, false, 'anim_new refuses to write outside the workspace') +} + +/* ---------------------------------------------------------------- 9. examples */ + +section('the three examples') +{ + const examplesRoot = path.join(pkgRoot, 'examples') + const expected = ['dashboard-ui', 'chat-ui', 'saas-landing'] + for (const slug of expected) { + const dir = path.join(examplesRoot, slug) + if (!existsSync(dir)) { + ok(false, 'example ' + slug + ' exists') + continue + } + const source = sourceCheck(dir) + eq(source.ok, true, slug + ' passes a0-source: ' + source.problems.map((problem) => problem.message).join('; ')) + const captionPath = path.join(dir, 'caption.md') + ok(existsSync(captionPath), slug + ' has a caption.md') + ok(existsSync(path.join(dir, 'SPEC.md')), slug + ' has a SPEC.md') + if (existsSync(captionPath)) { + const caption = readFileSync(captionPath, 'utf8') + ok(caption.includes('## The poster frame'), slug + ' caption describes a poster frame') + ok(caption.includes('## Transcript'), slug + ' caption carries a transcript') + } + const rootPath = path.join(dir, 'index.html') + if (existsSync(rootPath)) { + const rootHtml = readFileSync(rootPath, 'utf8') + ok(rootHtml.includes('data-fps="30"'), slug + ' is authored at 30 fps') + ok(rootHtml.includes('data-composition-id="root"'), slug + ' has a root composition') + } + } + const all = existsSync(examplesRoot) ? readdirSync(examplesRoot).filter((name) => !name.startsWith('.')) : [] + eq(all.sort().join(','), expected.slice().sort().join(','), 'exactly three examples ship (no strays)') +} + +/* ---------------------------------------------------------------- 10. skills */ + +section('the skills') +{ + const skillsRoot = path.join(pkgRoot, 'skills') + const dirs = existsSync(skillsRoot) ? readdirSync(skillsRoot).filter((name) => !name.startsWith('.')) : [] + eq(dirs.length, 3, 'three skills ship') + for (const dir of dirs) { + const file = path.join(skillsRoot, dir, 'SKILL.md') + if (!existsSync(file)) { + ok(false, dir + ' has a SKILL.md') + continue + } + const text = readFileSync(file, 'utf8') + ok(/^---\n/.test(text), dir + ' starts with frontmatter') + ok(new RegExp('name: ' + dir).test(text), dir + ' names itself in the frontmatter') + ok(/description: .{80,}/.test(text), dir + ' has a real description') + ok(/whenToUse: /.test(text), dir + ' says when to use it') + const fences = (text.match(/^```/gm) ?? []).length + eq(fences % 2, 0, dir + ' has balanced code fences') + } +} + +/* ---------------------------------------------------------------- 11. the live half */ + +section('the live half (needs the CLI)') +{ + const cli = resolveCli(process.env, process.platform) + if (cli.command === '') { + skip('every example is linted by the real CLI', 'no `hyperframes` on this machine (npm install --global hyperframes)') + skip('a draft render of the dashboard example', 'no `hyperframes` on this machine') + } else { + for (const slug of ['dashboard-ui', 'chat-ui', 'saas-landing']) { + const dir = path.join(pkgRoot, 'examples', slug) + if (!existsSync(dir)) continue + // Judged by the CLI's own `ok`, not by its exit code: a lint WARNING (a scene + // file over ~300 lines) is advisory and still exits non-zero on some builds. + const run = await runCli(cli, ['lint', dir, '--json'], { env: childEnv(process.env, {}), timeoutMs: 180_000 }) + const parsed = parseJsonDocument(run.stdout) + ok( + parsed !== null && parsed.ok === true, + slug + ' lints clean with the real CLI', + parsed === null ? (run.stdout || run.stderr).slice(0, 400) : 'errors=' + parsed.errorCount + ' warnings=' + parsed.warningCount, + ) + } + } +} + +/* ---------------------------------------------------------------- summary */ + +rmSync(scratch, { recursive: true, force: true }) + +process.stdout.write('\n' + '-'.repeat(72) + '\n') +for (const line of skipped) process.stdout.write('SKIPPED: ' + line + '\n') +if (failures.length > 0) { + process.stdout.write('\nFAILED (' + failures.length + ' of ' + (passed + failures.length) + '):\n') + for (const failure of failures) process.stdout.write(' ✗ ' + failure + '\n') + process.exitCode = 1 +} else { + process.stdout.write('ok — ' + passed + ' assertions passed' + (skipped.length > 0 ? ', ' + skipped.length + ' skipped loudly' : '') + '\n') +} diff --git a/packages/dsh-hyperframes/cordis.patch.yml b/packages/dsh-hyperframes/cordis.patch.yml new file mode 100644 index 0000000..f04d685 --- /dev/null +++ b/packages/dsh-hyperframes/cordis.patch.yml @@ -0,0 +1,23 @@ +# dsh-hyperframes bundle layer (alpha). +# +# One row ('hyperframes') owns the whole plugin: its Node half registers SIX tools +# that drive the user's own HyperFrames CLI (heygen-com/hyperframes, Apache-2.0) - +# `anim_status`, `anim_new`, `anim_scene`, `anim_check`, `anim_snapshot` and +# `anim_render`. Host-only: a project is a folder in the workspace and the answer +# is prose plus paths, so there is no route to serve and no browser half to load. +# The player is `dsh-video`'s tab over `dsh-media`'s Range route, referred to, not +# re-implemented. +# +# Nothing shipped is patched and no core row is disabled: DSH has no video-authoring +# surface, and HyperFrames is a program the user installs, not an engine this +# package vendors or downloads. The row never runs `npx` (which downloads a package +# when it is missing) and sets HYPERFRAMES_NO_TELEMETRY / NO_AUTO_INSTALL / +# NO_UPDATE_CHECK / NO_OPTIONAL_INSTALL on every child, so a tool call starts no +# network egress of its own. +# +# Nothing for scripts/sync-vendored.ps1: no engine is vendored or forked. The +# `hyperframes` CLI is the user's, and this package ships the resolver, the argv +# builder, the project template, the scene writer and the rung ladder. +- insert: + - id: hyperframes + name: 'dsh-hyperframes' diff --git a/packages/dsh-hyperframes/examples/chat-ui/SPEC.md b/packages/dsh-hyperframes/examples/chat-ui/SPEC.md new file mode 100644 index 0000000..640b2e8 --- /dev/null +++ b/packages/dsh-hyperframes/examples/chat-ui/SPEC.md @@ -0,0 +1,15 @@ +# Chat UI — HyperFrames worked example + +Deterministic 12 s / 1920×1080 / 30 fps mockup of an AI assistant app: 300 px thread sidebar, streaming answer, SQL card, composer, toast. + +| Beat | Time | On screen | +| --- | --- | --- | +| Shell | 0.0–0.6 | app frame fades up from y:18 | +| Threads | 0.6–1.8 | 8 sidebar rows stagger from x:-8, row 1 active | +| Ask | 1.8–3.2 | user bubble rises from y:16 on the right | +| Typing | 3.2–4.4 | 3 dots pulse on finite staggered tweens | +| Stream | 4.4–8.0 | answer typed char by char, bubble grows | +| Code | 8.0–9.4 | SQL card + Copy pill fade in under the answer | +| Composer | 9.4–10.6 | input bar slides up, send button lights | +| Toast | 10.6–12.0 | "Reply generated · 1.2s" lands top-right, then holds | +Techniques to copy: (1) deterministic streaming — one tween on a plain `{ n: 0 }` whose `onUpdate` writes `ANSWER.slice(0, Math.floor(n))`, so the text is a function of the playhead and no callback order can change a frame; (2) staggered rows — one `fromTo` on `.thread-row` with `stagger: 0.12` while every row keeps its own stable id; (3) a finite pulse — three sequential scale/opacity tweens per dot instead of `repeat: -1`, so a cold worker seeking to 3.7 s and a warm one playing forward render the identical frame. diff --git a/packages/dsh-hyperframes/examples/chat-ui/assets/theme.css b/packages/dsh-hyperframes/examples/chat-ui/assets/theme.css new file mode 100644 index 0000000..3c3e6ed --- /dev/null +++ b/packages/dsh-hyperframes/examples/chat-ui/assets/theme.css @@ -0,0 +1,39 @@ +/* Base document reset for the Chat UI example. + Everything that belongs to the mockup lives in compositions/chat.html, + inside its