diff --git a/docs/contracts.md b/docs/contracts.md index 27419500..b415bcbf 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -54,7 +54,7 @@ without a demonstrated consumer. See PLAN.md §5.1 for comparison rules and §8 | Tunnel probe: `GET /openapi.json`, `info.title` = `Atomic Chat API Server Endpoints` | `src/remote-access/probe.ts`, served by `src/server/public/static.ts` | `remote_access/probe.rs` | `probe.test.ts` asserts the marker against the document the public server really serves | | LAN addresses `GET /atomic/v1/lan-addresses` → `{addresses}` (IPv4, default route first, virtual adapters hidden, CGNAT kept) | `src/remote-access/{lan,lan-probe}.ts`, `src/server/control/routes/remote-access.ts` | image-generation line `remote_access/lan.rs` (`get_lan_addresses`) | ported `lan.rs` tables | | Image generation wire types (camelCase; absent vs `null` as the plugin's serde produced), the 23 `DiffusionErrorCode`s incl. `ENGINE_UPDATE_REQUIRED` (409) and `INVALID_OUTPUT` (500) (statuses informational: 400/404/409/429/507/500), `files.llmVision`, events `diffusion:{state,progress,job,error}` | `src/contracts/{diffusion,errors,events}.ts`, `src/diffusion/{parse,errors}.ts`, `src/server/http.ts` | image-generation line `web-app/src/services/diffusion/types.ts`, plugin `tauri-plugin-atomic-diffusion/src/{state,error,events}.rs` at `ec1fd3ea7` | `contracts/errors.test.ts` (code list), `diffusion/parse.test.ts`, `server/http.test.ts` | -| `sd-server` argv (`--llm_vision` after `--llm`) and environment (`GGML_METAL_TENSOR_DISABLE=1` on an M5 with Metal) and `POST /sdcpp/v1/img_gen` body; output parsing (records, step lines, tile passes, diagnostic tail, exit classification, GPU-fault markers); progress tracking; request validation (Qwen-Image on Metal ≤ 1 MP); per-family workflows and `workflowsForSpec`; engine gating (Qwen Image 2.1 and Krea 2 Turbo need build ≥ 883, FLUX.3 Klein ≥ 968, MiniMax-H3-Image and P-H3-Image ≥ 1088, `ENGINE_UPDATE_REQUIRED`) and install selection | `src/diffusion/{args,progress,tracker,validate,workflow,compat}.ts` | plugin `{args,progress,jobs,session}.rs` | the Rust `#[test]` tables ported by hand into the sibling tests; `test/fixtures/sdcpp/required-flags.txt` | +| `sd-server` argv (`--llm_vision` after `--llm`, a `qwen2vl` file as `--llm`; CPU modules as one `--backend te=cpu,vae=cpu`; `--flash-attn off,diffusion=on` and `--conv-direct auto,diffusion=on,controlnet=on` from build 982, `--diffusion-fa` and `--diffusion-conv-direct` before it or on a tag naming no build — ADR 2026-11-13-spell-the-sd-cpp-argv-for-the-installed-build) and environment (`GGML_METAL_TENSOR_DISABLE=1` on an M5 with Metal) and `POST /sdcpp/v1/img_gen` body; output parsing (records, step lines, tile passes, diagnostic tail, exit classification, GPU-fault markers); progress tracking; request validation (Qwen-Image on Metal ≤ 1 MP); per-family workflows and `workflowsForSpec`; engine gating (Qwen Image 2.1 and Krea 2 Turbo need build ≥ 883, FLUX.3 Klein ≥ 968, MiniMax-H3-Image and P-H3-Image ≥ 1088, `ENGINE_UPDATE_REQUIRED`) and install selection | `src/diffusion/{args,progress,tracker,validate,workflow,compat}.ts` | plugin `{args,progress,jobs,session}.rs` | the Rust `#[test]` tables ported by hand into the sibling tests; `test/fixtures/sdcpp/required-flags.txt` and `engine-contract.json` (`from_build`/`below_build`) | | Gallery files: `/-.png` with `tEXt` chunks `atomic` (the `ImageRecipe` JSON, every key, `null`s) and `parameters` (A1111 line) right after `IHDR`; `.thumb.png` (≤256 px); `.flags.json` `{id:{pinned,archived}}`. A PNG without a valid `atomic` recipe is foreign: never listed, never deleted. A batch with an all-black or all-white frame is refused before anything is saved (`INVALID_OUTPUT`); such an item an older build saved is hidden when its thumbnail (or PNG) is ≤ 128 KiB | `src/diffusion/{gallery,recipe,png}.ts` | plugin `gallery.rs` at `767ff6350` | ported `gallery.rs` tables; `test/fixtures/png/` (independent encoder, Pillow-checked); read-only run against images written by app v2.0.40 | | Engine installs `/diffusion/backends///` with `.atomic-owned` and `install.json` `{tag,backendId,backend,engine,sha256,installedAtMs}` (written by the core's engine-builds install; the app's `finalize` wrote the same before it); the `--help` probe markers `stable-diffusion.cpp` / `--cfg-scale`; model files under `/diffusion/models/` | `src/diffusion/{install,containment}.ts` | plugin `install.rs` | ported `install.rs` tables; read-only run against the engine installed by app v2.0.40 | | Engine builds (`engine` ∈ `ENGINE_BUILD_IDS`: `sd-cpp`, `audio-cpp`, `mlx`, `foundry-local`, `litert-lm`, `geniex`; change `move-sdcpp-mlx-install-to-core`, ADR 2026-10-07; audio.cpp: ADR 2026-10-29, conf `backends/audiocpp-manifest.json`, `ATOMIC_AUDIOCPP_MANIFEST_URL`, tags `vX.Y.Z[-a]`): `POST /atomic/v1/engine-builds/:engine/catalog {force?, proxy?}` → `{engine, manifest: {tag, published_at?, source: remote\|cache, fetched_at, error}\|null, manifest_error, host_backend_id, host_reason, host_download_bytes, installed[], active}` (`host_download_bytes`: every archive an install of the host build downloads, active build or not; `null` without one or with a size missing from the manifest), `POST …/updates {force?, proxy?}` → `{update_needed, current, target: {tag, backend_id, published_at?, download_bytes}\|null}`, `POST …/install {task_id, force?, proxy?}` (answers when done; `download:progress`/`download:stage` under `task_id`, cancel `POST /downloads/:task_id/cancel`) → `{installed, reason?: already-installed\|active-is-newer, build, retired[], kept_in_use[], failed_backend_ids?}`, `DELETE …/:tag/:backend_id` → `{removed}`; `engine` ∈ `sd-cpp`\|`mlx` (else `INVALID_ARGUMENT`), unknown body fields refused; errors `ENGINE_INSTALL_IN_PROGRESS`, `ENGINE_INSTALL_FAILED`, `BACKEND_INSUFFICIENT_DISK_SPACE` (< 3× the archives free), `CANCELLED`, `BACKEND_IN_USE`, `INVALID_REQUEST` (bundled or unmarked build), `UNSUPPORTED_BACKEND` (no build fits the host), `UPSTREAM_ERROR` (no manifest); event `engine-build:changed {engine, reason: install\|uninstall\|startup-cleanup}`. Manifests: conf `backends/sdcpp-manifest.json` and `backends/mlx-manifest.json`, overridable by `ATOMIC_SDCPP_MANIFEST_URL` / `ATOMIC_MLX_MANIFEST_URL` (`https://`, `file://`), cached at `/diffusion/sdcpp-manifest.cache.json` and `/mlx/mlx-manifest.cache.json`; probe failures remembered in `/diffusion/failed-backends.json`. MLX builds under `/mlx/backends//macos-arm64/` with `install.json {tag, backendId, sha256, installedAtMs, publishedAt}`; the installer's `/mlx-server` described by `mlx-server.json {tag, published_at}`; the newer by `published_at` runs, the installer on a tie | `src/engine-builds/`, `src/server/control/routes/engine-builds.ts`, `src/client/control-client.ts`, `src/contracts/engine-builds.ts` | app `web-app/src/services/diffusion/{install,backendMatrix}.ts` (branch `change/add-vllm-runtime`), conf `backends/{sdcpp,mlx}-schema.json` | `src/engine-builds/*.test.ts`, `routes/engine-builds.test.ts`, `control-client.test.ts`, `test/e2e/engine-builds.test.ts` | @@ -66,7 +66,7 @@ without a demonstrated consumer. See PLAN.md §5.1 for comparison rules and §8 | Image-generation control routes, one per `DiffusionService` operation; the engine binary's install, listing and removal are `/engine-builds/sd-cpp/…` (the three `…/backends` routes are gone) (bodies camelCase, paths only in bodies): `PUT /atomic/v1/diffusion/config` → status, `GET …/status`, `PUT …/output-dir {path}`, `GET …/model-files` → `{files}`, `POST …/model-files/delete {path}`, `POST …/model/load` (answers once served: minutes), `POST …/model/unload`, `GET …/capabilities`, `POST …/idle/touch`, `POST …/jobs` (64 MiB body) → `{jobId}`, `GET …/jobs/:id` → `{job\|null}`, `POST …/jobs/:id/cancel` → `{cancelled, serverStopped}`, `GET …/gallery?offset&limit&includeArchived`, `GET …/gallery/:id` → `{item\|null}`, `POST …/gallery/delete {ids}`, `PATCH …/gallery/:id/flags`, `POST …/gallery/:id/export {targetPath}`; a body that does not fit is 400 `INVALID_REQUEST` with the field in `details` | `src/server/control/routes/diffusion.ts`, `src/client/control-client.ts`, `src/core/{create,atomic-core}.ts` (`diffusion` on the facade; shutdown order public stop → sd-server → chat runtimes) | plugin `commands.rs` at `767ff6350`; app seam `web-app/src/services/diffusion/tauri.ts` (re-pointed in the app branch) | `routes/diffusion.test.ts`, `control-client.test.ts`, `src/core/create.test.ts` on a real core with the fake engine | | `POST /v1/images/generations` (local, never forwarded): `prompt`, `n` ≤ 4, `size` `WIDTHxHEIGHT` (256–2048, ×16) or `auto`, `seed`, `negative_prompt`, `model` (absent, the id or the display name), `response_format` only `b64_json`; answer `{created, data:[{b64_json}], atomic:{job_id, seed, paths}}`; errors in the OpenAI envelope with codes `invalid_request` 400, `model_not_loaded` 503, `busy` 429, `insufficient_memory` / `cancelled` / `server_error` 500, `timeout` 504 (30 min); trace `backend: atomic-diffusion`, endpoint `images/generations`; image models absent from `/v1/models` | `src/server/public/{images,images-params}.ts` | app `src-tauri/src/core/server/images_route.rs` at `767ff6350` | ported `images_route.rs` tables (`images-params.test.ts`), `images.test.ts` on a real listener, `src/core/create.test.ts` on a real core with the fake engine | | Video generation wire types (camelCase, absent vs `null` as the image ones): `VideoGenerateRequest` (`frames?`/`fps?` absent = the family's; `workflow` `create` served, `image-to-video` parsed and refused; `initImage`/`endImage` reserved), `VideoJob` (`estimate?` from the first event), `VideoJobProgress` (no batch fields; `etaSeconds` covers the whole job — encoding, the remaining steps and the decode, a tiled decode at its measured pace per tile once a tile finished — and is `null` when unknown, once every tile is done and while saving — a spent forecast is doubled rather than dropped; `fraction` never decreases and stays ≤ 0.99; `elapsedMs` from the runner's start; `decodeTiles? {done, total}` while a tiled decode runs, absent otherwise and from older cores; `slowdown` always sent by this core — steps or decode tiles — absent from older ones = `false`), `VideoEstimate {memory {requiredBytes, budgetBytes, pool: unified\|vram\|system, verdict: fits\|tight\|exceeds}, seconds {low, high}\|null, basis: heuristic\|history}`, `VideoRecipe`, `GalleryVideoItem`, `VideoCapabilities`; the LTX files `audioVae`/`embeddingsConnectors`; `defaults.video {fps, frames, frameStep, frameOffset, resolutionPresets}`, `defaults.sigmas`, `ranges.frames`; `DiffusionConfig.videoOutputDir`, `DiffusionStatus.{activeVideoJob, videoOutputDir}`; events `diffusion:{video-progress,video-job}` (`state`/`error` shared; `video-progress` at least once a second while a clip generates, besides every change); `MODEL_INCOMPATIBLE` is a 400; the estimate and the whole-job ETA: ADR 2026-09-28-estimate-video-generation-before-and-during-the-job; the decode's tiles: ADR 2026-09-29-report-the-tiled-decode-and-tile-it-by-memory; a job past its forecast: ADR 2026-09-30-keep-the-video-eta-past-its-forecast | `src/contracts/{diffusion,events}.ts`, `src/diffusion/{parse,validate,video-estimate,video-tiling,video-history,video-eta,tracker}.ts`, `src/server/http.ts` | app `web-app/src/services/diffusion/types.ts` on the video branch (mirrors these) | `parse.test.ts`, `validate.test.ts` (the frame lattice), `http.test.ts`, `video-estimate.test.ts`, `video-tiling.test.ts`, `video-history.test.ts`, `video-eta.test.ts`, `tracker.test.ts` | -| `sd-server` for video: `--audio-vae`, `--embeddings-connectors` after `--vae`; `-M vid_gen` only behind `ATOMIC_DIFFUSION_VID_GEN_MODE_FLAG`; `POST /sdcpp/v1/vid_gen` body (`video_frames`, `fps`, `output_format: webm`, `custom_sigmas` when the family's schedule has exactly the request's steps, closed by a 0 — sd.cpp runs `length - 1` steps, the `img_gen` body likewise (ADR 2026-10-09-a-distilled-schedule-closes-on-zero-and-qwen-image-2-1-turbo-joins-its-family), `init_image`/`end_image`; `vae_tiling_params` as the job's plan tiles the decode — tile counts under `rel_size_x/y` and `rel_size_w/h`, none for one graph — or `{enabled: true}` past 8 M pixel-frames without a plan); capabilities read per mode (`supported_modes`, `features_by_mode.vid_gen`, `output_formats_by_mode.vid_gen`), a mode the spec's modality needs but the engine lacks kills the server at load; a build that lists formats without `webm` is refused before submit (`UNSUPPORTED_BACKEND`); the result `{output_format, mime_type, fps, frame_count, b64_json}` | `src/diffusion/{args,server-process,video-job,job-kind,jobs}.ts` | upstream `examples/server/api.md` (build ≥ 883), `docs/ltx2.md`, `docs/wan.md` | `args.test.ts` against `test/fixtures/sdcpp/required-flags.txt`, `server-process.test.ts`, `video-job.test.ts`, `jobs.test.ts`; `test/e2e/video.test.ts` | +| `sd-server` for video: `--audio-vae`, `--embeddings-connectors` after `--vae`; no `-M` (sd-cli's only; sd-server takes its modes from the model); `POST /sdcpp/v1/vid_gen` body (`video_frames`, `fps`, `output_format: webm`, `custom_sigmas` when the family's schedule has exactly the request's steps, closed by a 0 — sd.cpp runs `length - 1` steps, the `img_gen` body likewise (ADR 2026-10-09-a-distilled-schedule-closes-on-zero-and-qwen-image-2-1-turbo-joins-its-family), `init_image`/`end_image`; `vae_tiling_params` as the job's plan tiles the decode — tile counts under `rel_size_x/y` and `rel_size_w/h`, none for one graph — or `{enabled: true}` past 8 M pixel-frames without a plan); capabilities read per mode (`supported_modes`, `features_by_mode.vid_gen`, `output_formats_by_mode.vid_gen`), a mode the spec's modality needs but the engine lacks kills the server at load; a build that lists formats without `webm` is refused before submit (`UNSUPPORTED_BACKEND`); the result `{output_format, mime_type, fps, frame_count, b64_json}` | `src/diffusion/{args,server-process,video-job,job-kind,jobs}.ts` | upstream `examples/server/api.md` (build ≥ 883), `docs/ltx2.md`, `docs/wan.md` | `args.test.ts` against `test/fixtures/sdcpp/required-flags.txt`, `server-process.test.ts`, `video-job.test.ts`, `jobs.test.ts`; `test/e2e/video.test.ts` | | Video files: `/.webm` (the engine's bytes as they came, EBML magic and `DocType` checked, never decoded), `.json` (the `VideoRecipe`, every key, `null`s, two-space indent), `.thumb.png` (the poster the app uploaded, kept verbatim), `.flags.json` as for images. A `.webm` without a parseable sidecar is foreign: never listed, never deleted. Default folder `/videos/` | `src/diffusion/{video-gallery,video-recipe}.ts` | app ADR `2026-09-10-store-generated-media-under-the-data-folder-with-recipes-in-png-chunks.md` (the reserved folder) | `video-gallery.test.ts`, `video-recipe.test.ts`; `test/fixtures/webm/tiny.webm` from ffmpeg (README beside it) | | Video control routes: `GET /atomic/v1/diffusion/video/capabilities`, `POST …/video/estimate` (the job body, 64 MiB) → `{estimate}` (the job's refusals; starts nothing; answers while a job runs), `POST …/video/jobs` (64 MiB) → `{jobId}`, `GET …/video/jobs/:id` → `{job\|null}`, `POST …/video/jobs/:id/cancel`, `GET …/video/gallery?offset&limit&includeArchived`, `GET …/video/gallery/:id` → `{item\|null}`, `POST …/video/gallery/delete {ids}`, `PATCH …/video/gallery/:id/flags`, `POST …/video/gallery/:id/export {targetPath}`, `PUT …/video/gallery/:id/poster {png}` (24 MiB, base64 PNG, data-URL prefix accepted) → the item; the image routes and their bodies unchanged; `POST …/jobs/:id/cancel` cancels a job of either kind | `src/server/control/routes/diffusion-video.ts`, `src/client/control-client.ts` | app seam `web-app/src/services/diffusion/tauri.ts` on the video branch | `routes/diffusion-video.test.ts`, `control-client.test.ts`, `src/core/create.test.ts` | | `/v1/videos` (local, never forwarded), the OpenAI Videos API shape: `POST /videos {prompt, model?, seconds?, size?, seed?, negative_prompt?}` → the video object at once (`{id, object:'video', model, status: queued\|in_progress\|completed\|failed, progress, created_at, completed_at, expires_at:null, seconds, size, prompt, remixed_from_video_id:null, error, atomic:{job_id, seed, path, poster_path}}`; `seconds` snapped to the family's frame lattice; `input_reference` refused), `GET /videos/{id}` (the runner's record, else the gallery's clip, else 404 `not_found`), `GET /videos/{id}/content[?variant=thumbnail]` (`video/webm` streamed, `Content-Disposition`), `DELETE /videos/{id}` (cancels a running clip, removes a finished one) → `{id, object:'video', deleted:true}`, `GET /videos?limit&after` → `{object:'list', data, first_id, last_id, has_more}`; 503 `model_not_loaded` without a video model; 405 with `Allow`; trace `backend: atomic-diffusion`, endpoint `videos`, `GET`s not reported; video models absent from `/v1/models` | `src/server/public/{videos,videos-params}.ts` | OpenAI Videos API; app ADR `2026-09-10-serve-openai-images-generations-from-the-local-api-server.md` | `videos-params.test.ts`, `videos.test.ts` on a real listener, `src/core/create.test.ts`; `test/e2e/videos-api.test.ts` | diff --git a/docs/decisions/2026-11-13-spell-the-sd-cpp-argv-for-the-installed-build.md b/docs/decisions/2026-11-13-spell-the-sd-cpp-argv-for-the-installed-build.md new file mode 100644 index 00000000..d3ddf998 --- /dev/null +++ b/docs/decisions/2026-11-13-spell-the-sd-cpp-argv-for-the-installed-build.md @@ -0,0 +1,47 @@ +--- +date: 2026-11-13 +title: "Spell the sd.cpp argv for the installed build" +--- + +# 2026-11-13 — Spell the sd.cpp argv for the installed build + +- **Context:** The engine candidate check of `master-1091-b9d7176` reported five flags core emits as + deprecated by `sd-server`, marked the same way in the pin `master-1088-32d516c`: `--clip-on-cpu` (use `--backend te=cpu`), + `--vae-on-cpu` (`--backend vae=cpu`), `--diffusion-fa` (`--flash-attn off,diffusion=on`), + `--diffusion-conv-direct` (`--conv-direct auto,diffusion=on,controlnet=on`) and `--qwen2vl` (`--llm`). + Nothing is removed yet, but conf's manifest has no `min_core_version`, so every core gets the next build. + The replacements are not equally old. `--backend` module assignments, `--llm` and the `te=cpu` entry that + `--clip-on-cpu` merely prepends are in every build conf has served (849 on). `--flash-attn` and + `--conv-direct` arrived on 2026-10-13 (leejet/stable-diffusion.cpp#2134), first tagged in 982; conf served + 849 and 883 before that, those trees stay installed (`selectModelInstall` keeps whatever engine a family + needs no update for), and an older `sd-server` exits on a flag it does not know. Separately, `-M vid_gen` + sat behind `ATOMIC_DIFFUSION_VID_GEN_MODE_FLAG` until a live run said whether `sd-server` wants it (ADR + 2026-09-23); `-M` is parsed by `sd-cli` only, and `sd-server` takes its modes from the model. +- **Decision:** `buildServerArgs` spells the argv for the build the install's tag names. The CPU modules go + in one `--backend te=cpu,vae=cpu` and a `qwen2vl` file as `--llm` on every build. Flash attention and + direct convolution are `--flash-attn off,diffusion=on --conv-direct auto,diffusion=on,controlnet=on` from + build 982 (`MODULE_ASSIGNMENT_FLAGS_BUILD`), the old two flags before it and on a tag that names no build. + `-M` and its switch are gone. The engine contract carries the bound per flag (`from_build`, + `below_build`); the candidate check and the live test read only the flags core emits to the build under + test. +- **Consequences:** No candidate from 982 on reports a deprecated flag, and older installs keep working + unchanged. The new spelling means what the old one did: `--diffusion-fa` itself sets `off,diffusion=on`, + and sd.cpp asks about direct convolution only for the diffusion model, the VAE and ControlNet, where + `--diffusion-conv-direct` meant on, auto and on. Only `sd-server`'s upscale route still reads the legacy + boolean, and core never calls it. A repeated `--backend` is joined with commas and a module's entry beats + the bare default, so the CPU recovery's `--backend cpu`, appended last, still runs everything on the CPU; + the launch log line shows the joined value (`backend=te=cpu` on macOS). The legacy spellings leave the + contract once no supported install predates 982. +- **Owner:** team +- **Links:** `src/diffusion/{args,compat}.ts`, + `test/fixtures/sdcpp/{engine-contract.json,required-flags.txt}`, + `test/fixtures/sdcpp/help/sd-server-master-1028-37bc88b.txt`, `scripts/lib/sdcpp-surface.mjs`, + `test/contract/sdcpp-{engine-contract,surface}.test.ts`, `test/e2e/{diffusion-engine,video}.test.ts`, + `test/live/diffusion.test.ts`; upstream `examples/common/common.cpp` (`prepare_backend_assignments`, the + deprecated handlers) at `master-1088-32d516c`; engine-candidate report of `master-1091-b9d7176` (Hatchet + run `350cd60d-91f7-4d77-ac46-5c4c08383cf6`). + + diff --git a/docs/decisions/INDEX.md b/docs/decisions/INDEX.md index 0295aaaa..a8af0842 100644 --- a/docs/decisions/INDEX.md +++ b/docs/decisions/INDEX.md @@ -257,3 +257,4 @@ add a new one that says which record it supersedes. - [Browser stack frames keep their served asset path](2026-11-12-keep-browser-asset-paths-in-stack-frames.md) - [An audio shutdown refusal is not an engine crash](2026-11-12-audio-shutdown-refusal-is-not-a-crash.md) - [Check MLX builds with the engine candidate workflow](2026-11-12-check-mlx-builds-with-the-engine-candidate.md) — `engine=mlx`: the fork's `vX.Y.Z`, conf's `mlxvlm-macos-arm64-` mirror; everything on macos-15, watched folders, folder live models +- [Spell the sd.cpp argv for the installed build](2026-11-13-spell-the-sd-cpp-argv-for-the-installed-build.md) — `--backend te=cpu,vae=cpu` and `--llm` everywhere; `--flash-attn`/`--conv-direct` from build 982, the deprecated pair before; no `-M` diff --git a/docs/testing-critical-flows.md b/docs/testing-critical-flows.md index 8363bb03..75fd2065 100644 --- a/docs/testing-critical-flows.md +++ b/docs/testing-critical-flows.md @@ -42,8 +42,8 @@ Line coverage alone never raises a grade. A PR may not lower a grade. | Server gates: host, api key, CORS, preflight | Strong (contract) | `test/contract/proxy-http.test.ts` (default and trusted hosts, `*`, missing Host, IPv6 loopback refused, Bearer/`X-Api-Key`, whitelisted docs, `/configs` hidden, origin reflection, preflight method/header/host rules), `src/server/public/gates.test.ts`, `http.test.ts` (control listener guards), `test/e2e/public-server.test.ts` (key, trusted hosts, missing Host, hidden `/configs`, 405, preflight and origin reflection configured through control on the compiled binary; Swagger assets served byte-identical from the binary) | maintained | | Dynamic trusted hosts: the tunnel name and the accepted socket's address (stage 7c) | Strong (core) | `src/server/public/dynamic-hosts.test.ts` (the five `dynamic_hosts.rs` tests against the core's `isValidHost`; `*`, URLs, ports and paths can never become the tunnel name; every socket-address spelling: mapped, hex-mapped, zone id, bracketed IPv6, loopback and unspecified in both families), `test/contract/dynamic-hosts.test.ts` on a real listener under Node and Bun (403 → 200 with the origin reflected → 403; another `*.trycloudflare.com` stays a stranger; the same keep-alive connection is refused before and accepted after; preflight; a listener on `0.0.0.0` trusts the dialled LAN address, refuses a rebinding name on that socket and the LAN literal over loopback; a loopback bind gains nothing), `src/core/public-server.test.ts` (a real core, and a repeated start stays idempotent), the `proxy-http` set unchanged | a phone on the same Wi-Fi reaching a running app | | Remote access: the Cloudflare quick tunnel (stage 7d) | Strong (core, fake cloudflared and a stand-in edge), Missing (live) | `src/remote-access/manager.test.ts` (the app's 19 state-machine tests plus: a stuck supervisor loses the state, a second stop joins the first, a process that came up after shutdown is not kept, the process-exit guard), `process.test.ts` on a real child (URL + registration, URL only, silence, early exit, exit after ready, SIGTERM ignored then killed, an exit that cannot be confirmed, Windows goes straight to the kill, a program that cannot start, real argv and no `TUNNEL_*`), `cloudflared-{args,output}.test.ts` (tables), `probe.test.ts` (ours / foreign / unreachable, the marker against the real public server, edge by SNI with certificate verification on the tunnel name, 1033 until the tunnel is there, two silent rounds give up the edge, hostname fallback, abort), `journal.test.ts` (write-then-enrich, never resurrected after a clear, identity *and* name before a kill, start-time fallback, a real child ended and a real non-tunnel spared), `spawner.test.ts`, `wiring.test.ts` (test hooks), `src/core/remote-access.test.ts` on a real core (Host gate 403 → 401 with the key → 403 as the tunnel comes and goes, tunnel ended before `server:stopped`, an unchanged start leaves it alone, HTTP/2 retry with real processes, shutdown kills it, no binary), `src/core/public-server.test.ts`, `routes/remote-access.test.ts`, `control-client.test.ts`; `test/runtime-compat/address-pin.test.ts` under Node and Bun (a Node edge process reports the SNI the client really sent); `test/e2e/remote-access.test.ts` on the compiled app-core binary (refusal, online through the stand-in edge, journal, stop, ordering over SSE, HTTP/2 retry with the real 15 s, missing binary, a crash's journal consumed by the next owner, shutdown), plus stage 7q: a tunnel that exits after coming up reported as `exited` with its name no longer trusted and the public server untouched, a tunnel that ignores SIGTERM killed after the 5 s grace before `stop` answers `off`, and the journal Atomic Chat 2.0.40 left at the data root consumed once with the process it named spared | a real `cloudflared` against Cloudflare from a running app; a phone opening the URL | -| Image generation on stable-diffusion.cpp (stages 7e–7l) | Strong (core, fake engine, compiled binary, real engine), Missing (desktop) | pure ports with the plugin's `#[test]` tables: `src/diffusion/{args,progress,tracker,workflow,parse,validate,errors,recipe}.test.ts` (`args.test.ts` holds the argv to `test/fixtures/sdcpp/required-flags.txt`); disk: `png.test.ts` (fixtures from an independent encoder, Pillow-checked; damaged and unsupported files refused), `gallery.test.ts` (foreign PNGs never listed or deleted, flags file, atomic writes, export), `install.test.ts` (finalize probes a real script, owned trees only, model files inside the root), `containment.test.ts` (symlinks out of and into the root); process and jobs: `server-process.test.ts` on the fake engine (journalled before ready, capabilities, early exit with marked lines first, OOM, timeout kills, foreign listener stopped, abandoned load stopped), `jobs.test.ts` against an HTTP stub (the `jobs.rs` runner tests: completion with outputs and every transition, failures explained by the output, queue full, forgotten job, cancel ladder incl. the second grace, cancel wins over a waiting respawn, crash mid-job with the spec kept, ggml-abort CPU retry, transport errors, ceiling), `session.test.ts`, `idle.test.ts`, `service.test.ts` (the real fake engine: finalize → load → generate with progress → gallery → cancel → respawn → idle unload → shutdown, child dead each time); wiring: `routes/diffusion.test.ts` (every route, envelopes, the 64 MiB job body, 400 with the field named), `control-client.test.ts`, `src/core/create.test.ts` (a real owner: refused foreign data folder, finalize → load → generate over the control API, `processes.json` entry under `diffusion`, no chat session, events on the bus, engine output kept out of the log, the server dead after `shutdown`, then `POST /v1/images/generations` on the public listener: a PNG back, the gallery grown, the image model absent from `/v1/models`, an abandoned request's job cancelled); app v2.0.42 additions (7k–7l): `compat.test.ts` (build ≥ 883 for Qwen Image 2.1 / Krea 2 Turbo, ≥ 968 for FLUX.3 Klein, ≥ 1088 for MiniMax-H3-Image and P-H3-Image, odd tags fail closed, install selection never switches backends), `workflow.test.ts` / `validate.test.ts` (per-family workflows, Qwen Image 2.1's references only with `llmVision`, Qwen-Image on Metal ≤ 1 MP), `session.test.ts` (a stale spec refused before spawn, `activateInstall`), `service.test.ts` on the fake engine (a Qwen Image 2.1 load blocked on 849 then served by an 883 tree, `llmVision` checked and protected, an engine finalized during a running job cancels it and unloads the old server), `jobs.test.ts` (a blank frame fails the batch before anything is saved, a GPU fault in the attempt's lines retires the server and one printed before the job does not, a respawn reads the spec under the lock), `gallery.test.ts` / `png.test.ts` (blank detection, hidden items, verdicts kept per file), `server-process.test.ts` (`GGML_METAL_TENSOR_DISABLE` reaches the child only on an M5 with Metal); facade: `server/public/images-params.test.ts` (the `images_route.rs` tables), `images.test.ts` (503 before a model, 400 before that, the OpenAI body with the atomic extras, refusals to start, failed jobs, client gone → cancel, 504 with cancel) ; `test/e2e/diffusion.test.ts` on the compiled binary (finalize → load → events over SSE → gallery, flags and export → the OpenAI facade → unload with the journal cleared; a cancel the engine ignores stops the process and the next job respawns it; a crashed owner's `sd-server` is reaped by the next owner); the 7k–7l behaviour on the compiled binary (stage 7o): `test/e2e/diffusion-engine.test.ts` (Qwen Image 2.1 refused on build 849 with `ENGINE_UPDATE_REQUIRED`, nothing spawned, `load-blocked` on the stream, then served by an 883 tree of the same backend; the projector as `--llm_vision` right after `--llm` in the real argv, `reference`/`edit` offered only with it, the projector undeletable while loaded, an edit without it named `SIDE_FILE_MISSING`; a finalized newer engine unloads the resident model with `engine-updated`, the old tree removable only then and its empty tag folder gone, an unowned tree and a path outside the root refused) and `test/e2e/diffusion-failures.test.ts` (a blank frame ends the batch with `INVALID_OUTPUT`, nothing on disk or in the gallery, the same process serving the next seed and the facade answering 500; a GPU fault printed during the job retires the still-running server with `gpu-fault`, the model kept, the next job on a fresh pid; a ggml unsupported-op abort retried once on `--backend cpu` — two pids, the second with `cpuFallback` in the recipe and the status); the rest of the failure modes and the facade on the compiled binary (stage 7p): `diffusion-engine.test.ts` (Qwen-Image past 1 MP refused on a Metal engine before anything runs and the M5 switch absent from the engine's environment on a non-M5, `MODEL_MISSING` / `SIDE_FILE_MISSING` naming the file before any spawn, an early exit read as `OUT_OF_MEMORY` and a foreign listener as `MODEL_LOAD_FAILED` with both engines gone, an unload during a load answering `CANCELLED` with the child gone first), `diffusion-failures.test.ts` (an engine dying mid-job explained by its output, `crashed` then a respawn; a full queue as `QUEUE_FULL` and a failed job as `OUT_OF_MEMORY` with the engine left running, the facade answering 429 `busy` and 500 `insufficient_memory`), `diffusion.test.ts` (the output folder moved with the next picture under it, gallery items deleted with their thumbnails and a foreign PNG never listed or touched, model files listed, protected while loaded and deleted with their empty family folder after; a generation body over 64 MiB refused with the envelope and one below it read whole; the idle unload on the next tick with the spec forgotten), `test/e2e/images-api.test.ts` (OpenAI's envelope: `response_format` refused before the model check, 503 `model_not_loaded`, a broken body and a missing prompt, `size` and `n` named, 429 `busy` behind an Images-page job; a client that hangs up cancels the job with the engine kept — the binary-level case that found Bun's silence, ADR 2026-09-22; the key and Host gates in front, the request reported as `atomic-diffusion` on `images/generations` and the prompt absent from the API events with or without the inspector), `public-server.test.ts` (`/openapi.json` from the binary documents `POST /images/generations`); `test/live/diffusion.test.ts` on a real engine and FLUX.2 Klein (`--help` holds every flag of `required-flags.txt`, load, a 256² generation with parsed sampling progress, PNG + thumbnail + recipe, the facade, a hard cancel, respawn, unload; passed 2026-09-18 on `master-849-d04e895` and again 2026-09-21 on `master-883-137f740`, the build app v2.0.42 ships, on macOS arm64 in ~5 min); `test/live/diffusion-install.test.ts` (a real build installed from a conf-shaped manifest: picked for the host, downloaded, sha256-checked, unpacked, probed; a tampered sha256 refused; `--version` naming the tag's commit); both run per build by `engine-candidate.yml` with `engine=sd-cpp` on linux-x64, linux-arm64 and macos-arm64 (CPU archives), with the surface held to `test/fixtures/sdcpp/engine-contract.json` (`test/contract/sdcpp-{engine-contract,surface}.test.ts`); `src/diffusion/{jobs,service}.test.ts` also checks cancellation during validation/input reads, active owner shutdown, and readiness racing an aborted spawn; `test/e2e/diffusion.test.ts` checks explicit shutdown with an active job and an empty child journal | desktop acceptance from the Images page on the compiled binary and `test/live/diffusion.test.ts` on a real engine (7j), desktop acceptance from the Images page | -| Video generation on stable-diffusion.cpp (stage 9a–9f) | Strong (core, fake engine, compiled binary), Missing (real engine, desktop) | pure: `src/diffusion/{parse,validate,args,workflow}.test.ts` (the video parsers, the frame lattice `k·step+offset` and the nearest-point snap, the fixed rate, `--audio-vae`/`--embeddings-connectors` in order, `-M vid_gen` behind its switch, the `vid_gen` body with `custom_sigmas` at the schedule's step count, image-to-video refused), `server-process.test.ts` (capabilities per mode, a mode the spec needs but the engine lacks kills the server: `MODEL_INCOMPATIBLE`), `session.test.ts` (video capabilities, image capabilities refused on a video model), `state.test.ts` (kind-aware records); the seam: `image-job.test.ts`, `video-job.test.ts` (decode, the WebM preflight, the recipe, the events, the plan's decode tiling in the body and the threshold again on the CPU fallback), `jobs.test.ts` (the image suite unchanged after the refactor; a video job through the HTTP stub on its own events with one clip, the wrong modality both ways, the preflight, a native cancel; the estimate on the first event and a failed one that does not stop the job; the plan's decode tiling in the body and the decode's tiles on the progress; the heartbeat through a ten-second step with `elapsedMs` from the job's start, images still on change only); the estimate: `video-estimate.test.ts` (latent tokens per family, the tiled decode and its peak and work per layout, the decode tiling planned by memory — one graph on 24 GB, three strips on 18 GB, the finest on 16 GB, none under `model` offload, on the CPU fallback or on unknown memory —, LTX-2 on a 16 GB Mac `exceeds` with `seconds: null`, memory growing with frames and size, the 80 %/100 % lines, the three pools and both sides of a discrete GPU, the speed table and unknown hardware, CFG passes, ×2/×3 ranges, the history band), `video-tiling.test.ts` (sd.cpp's tile count ported, tile counts to sides and back, the work of a layout, the body's tile counts under both spellings), `video-history.test.ts` (which clips count, a past clip re-planned at its own size, three clips at twice the heuristic double the middle, the median and its clamp, the cache), `video-eta.test.ts` (every ETA and fraction scenario of the progress spec, both slowdown rules and their stickiness; a tiled decode counted down per tile, stretched, restarted on a retried pass, and a stalled tile), `tracker.test.ts` (a lost tile pass ended by `generating video:`; the decode's tiles counted, a retried pass counted from zero); disk: `video-recipe.test.ts` (every key, `null`s, strict on the way back), `video-gallery.test.ts` (EBML/DocType sniff, save writes the sidecar first, foreign `.webm` never listed or deleted, the poster kept verbatim and refused when not a PNG, flags, delete, export); service: `service.test.ts` on the fake in `vid_gen` mode (`estimateVideo`: the job's refusals, an answer while a clip runs with no event, history after the first clip and gone after its delete, no hardware facts refused while the clip still runs; load with the side files, a clip into `/videos` with its sidecar, the poster, the gallery, `cancelVideoJob`, the `VideosBackend` view, a video model on an image-only engine refused with the child dead, a build without WebM refused before submit; the decode tiled by the memory of a 16 GB Mac — one graph for 1024²×9, three strips for 2048²×17 — and its tiles reported); routes: `routes/diffusion-video.test.ts` (the estimate route too), `control-client.test.ts`; facade: `videos-params.test.ts` (seconds → frames, the video object from a job and from a clip, the path matcher, the listing query), `videos.test.ts` on a real listener (503/400/405, the queued object, poll, content and poster streamed, 404s, DELETE cancels or removes, the list merge and cursor, polls not reported); owner: `src/core/create.test.ts` (`/v1/videos` queue → poll → content equals the fixture → gallery → delete; the video model absent from `/v1/models`; only the video events); binary: `test/e2e/video.test.ts` (argv, `videoOutputDir`, the events over SSE, the clip and sidecar on disk, the poster, gallery ops, a cancel the engine ignores stops it and the next clip respawns, wrong modality at load and at generate, a missing side file before any spawn, no-WebM before submit and an unreported build's own 400; the estimate route and its refusal, `job.estimate` on the first event, the heartbeat through a 3 s step, `slowdown` when a step drags past three medians and 20 s; one graph for a clip past the old threshold that fits, and a tiled decode counted down tile by tile), `test/e2e/videos-api.test.ts` (the OpenAI envelope, queue/poll/download/list/DELETE, a finished clip answered after a restart, key and Host gates, reported as `atomic-diffusion` on `videos` without the prompt); live: `test/live/diffusion.test.ts` video block, not run yet (the estimate's coefficients are unmeasured, ADR 2026-09-28); desktop: the app's Video page, not yet | +| Image generation on stable-diffusion.cpp (stages 7e–7l) | Strong (core, fake engine, compiled binary, real engine), Missing (desktop) | pure ports with the plugin's `#[test]` tables: `src/diffusion/{args,progress,tracker,workflow,parse,validate,errors,recipe}.test.ts` (`args.test.ts` holds the argv to `test/fixtures/sdcpp/required-flags.txt`, spelled per build: the module-assignment flags from 982, the old ones before; `test/contract/sdcpp-engine-contract.test.ts` holds the contract's per-build flags to `buildServerArgs`); disk: `png.test.ts` (fixtures from an independent encoder, Pillow-checked; damaged and unsupported files refused), `gallery.test.ts` (foreign PNGs never listed or deleted, flags file, atomic writes, export), `install.test.ts` (finalize probes a real script, owned trees only, model files inside the root), `containment.test.ts` (symlinks out of and into the root); process and jobs: `server-process.test.ts` on the fake engine (journalled before ready, capabilities, early exit with marked lines first, OOM, timeout kills, foreign listener stopped, abandoned load stopped), `jobs.test.ts` against an HTTP stub (the `jobs.rs` runner tests: completion with outputs and every transition, failures explained by the output, queue full, forgotten job, cancel ladder incl. the second grace, cancel wins over a waiting respawn, crash mid-job with the spec kept, ggml-abort CPU retry, transport errors, ceiling), `session.test.ts`, `idle.test.ts`, `service.test.ts` (the real fake engine: finalize → load → generate with progress → gallery → cancel → respawn → idle unload → shutdown, child dead each time); wiring: `routes/diffusion.test.ts` (every route, envelopes, the 64 MiB job body, 400 with the field named), `control-client.test.ts`, `src/core/create.test.ts` (a real owner: refused foreign data folder, finalize → load → generate over the control API, `processes.json` entry under `diffusion`, no chat session, events on the bus, engine output kept out of the log, the server dead after `shutdown`, then `POST /v1/images/generations` on the public listener: a PNG back, the gallery grown, the image model absent from `/v1/models`, an abandoned request's job cancelled); app v2.0.42 additions (7k–7l): `compat.test.ts` (build ≥ 883 for Qwen Image 2.1 / Krea 2 Turbo, ≥ 968 for FLUX.3 Klein, ≥ 1088 for MiniMax-H3-Image and P-H3-Image, odd tags fail closed, install selection never switches backends), `workflow.test.ts` / `validate.test.ts` (per-family workflows, Qwen Image 2.1's references only with `llmVision`, Qwen-Image on Metal ≤ 1 MP), `session.test.ts` (a stale spec refused before spawn, `activateInstall`), `service.test.ts` on the fake engine (a Qwen Image 2.1 load blocked on 849 then served by an 883 tree, `llmVision` checked and protected, an engine finalized during a running job cancels it and unloads the old server), `jobs.test.ts` (a blank frame fails the batch before anything is saved, a GPU fault in the attempt's lines retires the server and one printed before the job does not, a respawn reads the spec under the lock), `gallery.test.ts` / `png.test.ts` (blank detection, hidden items, verdicts kept per file), `server-process.test.ts` (`GGML_METAL_TENSOR_DISABLE` reaches the child only on an M5 with Metal); facade: `server/public/images-params.test.ts` (the `images_route.rs` tables), `images.test.ts` (503 before a model, 400 before that, the OpenAI body with the atomic extras, refusals to start, failed jobs, client gone → cancel, 504 with cancel) ; `test/e2e/diffusion.test.ts` on the compiled binary (finalize → load → events over SSE → gallery, flags and export → the OpenAI facade → unload with the journal cleared; a cancel the engine ignores stops the process and the next job respawns it; a crashed owner's `sd-server` is reaped by the next owner); the 7k–7l behaviour on the compiled binary (stage 7o): `test/e2e/diffusion-engine.test.ts` (Qwen Image 2.1 refused on build 849 with `ENGINE_UPDATE_REQUIRED`, nothing spawned, `load-blocked` on the stream, then served by an 883 tree of the same backend; the speed flags spelled for the tree's build — `--diffusion-fa`/`--diffusion-conv-direct` on 849, `--flash-attn`/`--conv-direct` on 1088 with no deprecated flag and a `qwen2vl` file as `--llm`; the projector as `--llm_vision` right after `--llm` in the real argv, `reference`/`edit` offered only with it, the projector undeletable while loaded, an edit without it named `SIDE_FILE_MISSING`; a finalized newer engine unloads the resident model with `engine-updated`, the old tree removable only then and its empty tag folder gone, an unowned tree and a path outside the root refused) and `test/e2e/diffusion-failures.test.ts` (a blank frame ends the batch with `INVALID_OUTPUT`, nothing on disk or in the gallery, the same process serving the next seed and the facade answering 500; a GPU fault printed during the job retires the still-running server with `gpu-fault`, the model kept, the next job on a fresh pid; a ggml unsupported-op abort retried once on `--backend cpu` — two pids, the second with `cpuFallback` in the recipe and the status); the rest of the failure modes and the facade on the compiled binary (stage 7p): `diffusion-engine.test.ts` (Qwen-Image past 1 MP refused on a Metal engine before anything runs and the M5 switch absent from the engine's environment on a non-M5, `MODEL_MISSING` / `SIDE_FILE_MISSING` naming the file before any spawn, an early exit read as `OUT_OF_MEMORY` and a foreign listener as `MODEL_LOAD_FAILED` with both engines gone, an unload during a load answering `CANCELLED` with the child gone first), `diffusion-failures.test.ts` (an engine dying mid-job explained by its output, `crashed` then a respawn; a full queue as `QUEUE_FULL` and a failed job as `OUT_OF_MEMORY` with the engine left running, the facade answering 429 `busy` and 500 `insufficient_memory`), `diffusion.test.ts` (the output folder moved with the next picture under it, gallery items deleted with their thumbnails and a foreign PNG never listed or touched, model files listed, protected while loaded and deleted with their empty family folder after; a generation body over 64 MiB refused with the envelope and one below it read whole; the idle unload on the next tick with the spec forgotten), `test/e2e/images-api.test.ts` (OpenAI's envelope: `response_format` refused before the model check, 503 `model_not_loaded`, a broken body and a missing prompt, `size` and `n` named, 429 `busy` behind an Images-page job; a client that hangs up cancels the job with the engine kept — the binary-level case that found Bun's silence, ADR 2026-09-22; the key and Host gates in front, the request reported as `atomic-diffusion` on `images/generations` and the prompt absent from the API events with or without the inspector), `public-server.test.ts` (`/openapi.json` from the binary documents `POST /images/generations`); `test/live/diffusion.test.ts` on a real engine and FLUX.2 Klein (`--help` holds every flag the contract names for the engine's build, load, a 256² generation with parsed sampling progress, PNG + thumbnail + recipe, the facade, a hard cancel, respawn, unload; passed 2026-09-18 on `master-849-d04e895` and again 2026-09-21 on `master-883-137f740`, the build app v2.0.42 ships, on macOS arm64 in ~5 min); `test/live/diffusion-install.test.ts` (a real build installed from a conf-shaped manifest: picked for the host, downloaded, sha256-checked, unpacked, probed; a tampered sha256 refused; `--version` naming the tag's commit); both run per build by `engine-candidate.yml` with `engine=sd-cpp` on linux-x64, linux-arm64 and macos-arm64 (CPU archives), with the surface held to `test/fixtures/sdcpp/engine-contract.json` (`test/contract/sdcpp-{engine-contract,surface}.test.ts`); `src/diffusion/{jobs,service}.test.ts` also checks cancellation during validation/input reads, active owner shutdown, and readiness racing an aborted spawn; `test/e2e/diffusion.test.ts` checks explicit shutdown with an active job and an empty child journal | desktop acceptance from the Images page on the compiled binary and `test/live/diffusion.test.ts` on a real engine (7j), desktop acceptance from the Images page | +| Video generation on stable-diffusion.cpp (stage 9a–9f) | Strong (core, fake engine, compiled binary), Missing (real engine, desktop) | pure: `src/diffusion/{parse,validate,args,workflow}.test.ts` (the video parsers, the frame lattice `k·step+offset` and the nearest-point snap, the fixed rate, `--audio-vae`/`--embeddings-connectors` in order, never `-M`, the `vid_gen` body with `custom_sigmas` at the schedule's step count, image-to-video refused), `server-process.test.ts` (capabilities per mode, a mode the spec needs but the engine lacks kills the server: `MODEL_INCOMPATIBLE`), `session.test.ts` (video capabilities, image capabilities refused on a video model), `state.test.ts` (kind-aware records); the seam: `image-job.test.ts`, `video-job.test.ts` (decode, the WebM preflight, the recipe, the events, the plan's decode tiling in the body and the threshold again on the CPU fallback), `jobs.test.ts` (the image suite unchanged after the refactor; a video job through the HTTP stub on its own events with one clip, the wrong modality both ways, the preflight, a native cancel; the estimate on the first event and a failed one that does not stop the job; the plan's decode tiling in the body and the decode's tiles on the progress; the heartbeat through a ten-second step with `elapsedMs` from the job's start, images still on change only); the estimate: `video-estimate.test.ts` (latent tokens per family, the tiled decode and its peak and work per layout, the decode tiling planned by memory — one graph on 24 GB, three strips on 18 GB, the finest on 16 GB, none under `model` offload, on the CPU fallback or on unknown memory —, LTX-2 on a 16 GB Mac `exceeds` with `seconds: null`, memory growing with frames and size, the 80 %/100 % lines, the three pools and both sides of a discrete GPU, the speed table and unknown hardware, CFG passes, ×2/×3 ranges, the history band), `video-tiling.test.ts` (sd.cpp's tile count ported, tile counts to sides and back, the work of a layout, the body's tile counts under both spellings), `video-history.test.ts` (which clips count, a past clip re-planned at its own size, three clips at twice the heuristic double the middle, the median and its clamp, the cache), `video-eta.test.ts` (every ETA and fraction scenario of the progress spec, both slowdown rules and their stickiness; a tiled decode counted down per tile, stretched, restarted on a retried pass, and a stalled tile), `tracker.test.ts` (a lost tile pass ended by `generating video:`; the decode's tiles counted, a retried pass counted from zero); disk: `video-recipe.test.ts` (every key, `null`s, strict on the way back), `video-gallery.test.ts` (EBML/DocType sniff, save writes the sidecar first, foreign `.webm` never listed or deleted, the poster kept verbatim and refused when not a PNG, flags, delete, export); service: `service.test.ts` on the fake in `vid_gen` mode (`estimateVideo`: the job's refusals, an answer while a clip runs with no event, history after the first clip and gone after its delete, no hardware facts refused while the clip still runs; load with the side files, a clip into `/videos` with its sidecar, the poster, the gallery, `cancelVideoJob`, the `VideosBackend` view, a video model on an image-only engine refused with the child dead, a build without WebM refused before submit; the decode tiled by the memory of a 16 GB Mac — one graph for 1024²×9, three strips for 2048²×17 — and its tiles reported); routes: `routes/diffusion-video.test.ts` (the estimate route too), `control-client.test.ts`; facade: `videos-params.test.ts` (seconds → frames, the video object from a job and from a clip, the path matcher, the listing query), `videos.test.ts` on a real listener (503/400/405, the queued object, poll, content and poster streamed, 404s, DELETE cancels or removes, the list merge and cursor, polls not reported); owner: `src/core/create.test.ts` (`/v1/videos` queue → poll → content equals the fixture → gallery → delete; the video model absent from `/v1/models`; only the video events); binary: `test/e2e/video.test.ts` (argv, `videoOutputDir`, the events over SSE, the clip and sidecar on disk, the poster, gallery ops, a cancel the engine ignores stops it and the next clip respawns, wrong modality at load and at generate, a missing side file before any spawn, no-WebM before submit and an unreported build's own 400; the estimate route and its refusal, `job.estimate` on the first event, the heartbeat through a 3 s step, `slowdown` when a step drags past three medians and 20 s; one graph for a clip past the old threshold that fits, and a tiled decode counted down tile by tile), `test/e2e/videos-api.test.ts` (the OpenAI envelope, queue/poll/download/list/DELETE, a finished clip answered after a restart, key and Host gates, reported as `atomic-diffusion` on `videos` without the prompt); live: `test/live/diffusion.test.ts` video block, not run yet (the estimate's coefficients are unmeasured, ADR 2026-09-28); desktop: the app's Video page, not yet | | Remote media: cloud and self-hosted providers' image and video models through the core (ADR 2026-10-13) | Strong (core, fake providers, compiled binary), Missing (live providers, desktop) | adapters: one `src/media/adapters/.test.ts` per provider API on a fake fetch (request shape, auth header, body, success parsing, error mapping, live listing; video submit/poll/download/cancel; key only on the provider origin, redirects off it bare), `registry.test.ts` (one adapter per dialect); pure: `src/media/{catalog,http,mask}.test.ts`, `remote-media.test.ts` (public params, inline images only, alpha masks), `parse.test.ts` (`target`/`remote`); I/O: `catalog-service.test.ts` (live → memory → disk → baseline, newest `catalog_version`, the `file://` hook), `remote-store.test.ts`; service: `src/media/service.test.ts` (catalog and registration adapters, refusals, live listing merged or failed), `src/diffusion/remote-job.test.ts` on the real `DiffusionService` (shared table and events, no busy slot, gallery PNG/JPEG/MP4, provider errors and `diffusion:error`, cancel without touching `sd-server`, the cap, a submit never retried, transient polls retried, a clip resumed after a restart without a second submit, a resumed clip past its ceiling timed out, shutdown keeps the stored job, the facades' `runImageJob`/`runVideoJob`); registry: `cloud/registry.test.ts` (media out of the key binding, absent keeps, `null` clears, other providers untouched), `router/resolve.test.ts`; routes: `routes/media.test.ts`, `control-client.test.ts`, `server/public/{images,videos}.test.ts` (remote generations and edits, 415/404/400, MP4 content), `src/core/create.test.ts` (owner: catalog and a live listing over control); binary: `test/e2e/remote-media.test.ts` (a self-hosted OpenAI-compatible stub registered over control: an image job over control into `/images`, `/v1/images/generations` by `/`, absent from `/v1/models`, a clip over `/v1/videos` saved as MP4, the key sent to the provider; an unconnected provider refused) | live runs against each provider (`test/live`), the app's Images/Video pages | | Audio generation on audio.cpp: builds, load, speech/music/effects jobs, cancel, gallery, `/v1/audio/speech` (ADRs 2026-10-29) | Strong (core, fake engine, compiled binary, real engine: upstream v0.9.3 on macOS Metal and CPU), Missing (fork builds, Windows/Linux real engine, desktop) | pure: `src/audio/{args,config,request,capabilities,wav,parse,output,recipe}.test.ts`, `src/server/public/audio-speech-params.test.ts`; process: `src/audio/server-process.test.ts` (fake `audiocpp_server`: ready, foreign listener, taken port, load failure, missing model), `jobs`/`session`/`service`/`idle` tests (cancel stops the server and keeps the spec, crash then respawn, a cancel under the load lock never deadlocks; replacement loads keep their state after an older teardown, reference reads reject a replaced model, shutdown waits for a loading child and journal cleanup), `gallery.test.ts` (foreign WAVs never listed or deleted); builds: `src/audio/install.test.ts` (probe `--version` + `--list-devices` on v0.9.3 fixtures), `src/engine-builds/{manifest,select,order,service}.test.ts` (shared ggml manifest, ladder without ROCm, failed rungs per engine); compiled binary: `test/e2e/{audio,audio-speech-api,engine-builds,engines}.test.ts` (including owner shutdown during an audio load); contract: `test/contract/audiocpp-*.test.ts` (flags and routes against `--help`, log strings the runtime reads); live: `test/live/audio-install.test.ts`, `test/live/audio.test.ts` (Stable Audio 3 Small SFX and Qwen3-TTS Base with a reference, Metal and CPU, 2026-10-29) | | Decision model: engine gate, supervision, fail-open calls, public passthrough (ADR 2026-09-30) | Partial (core, fake engine), Missing (compiled binary, real engine, desktop) | pure: `src/decision/{engine-version,engine-candidates,args,readiness,outcome,backoff,request}.test.ts`, `src/settings/decision.test.ts`, `src/models/gguf/classify.test.ts` (`isDecisionGguf` before `isEmbeddingGguf`); process: `src/decision/process.test.ts` on the fake `llama-server` in decision mode (readiness chain with the key, `/health` polled while loading, a slow `/props` and a 5xx `/v1/models` waited through instead of refused, API version 2 and a missing capability refused with the child killed, an older build's exit with its own lines, startup timeout, abort, a failed journal write), `engine.test.ts` (gate order, a dev build found after the newer tags failed, the probe cache per mtime, a build rejected at readiness skipped until its file changes or `forgetRejected`, the "refused at readiness" message instead of the install advice, an explicit engine, the real `-h` of the fake); service: `service.test.ts` (scores and answers through a real fake process, the 500 ms budget kept against a 2 s engine, the engine's refusal with its reason, the uncalibrated router, every refusal state, restart with backoff and giving up, a SIGKILLed process brought back, settings followed, a start in flight kept across a non-launch settings write and restarted by a launch one, the idle timer re-armed, idle unload held by a call in flight, a start aborted by unload, nothing left after shutdown, `not_calibrated` without a round trip and from a 501, an unserializable body, router scores out of order, a retry after an install and the rate-limited, quiet retry of `unsupported` (no transient `starting`), the refused builds forgotten on load, install and launch settings but not on a retry, the next engine after a readiness refusal, a public request waiting through a restart and released when the client leaves), `wiring.test.ts` (settings → installed pack → journal entry for the process's life; `backend:download-finished` for `llamacpp` bringing an `unsupported` module up while another provider or a failed install starts nothing; a refused build retried by an explicit load but not by a call; every build refused → the readiness message; a slow `/props` → ready on the first build); surface: `routes/decision.test.ts`, `server/public/decision.test.ts`; `test/contract/decision.test.ts` (the DECISION.md examples through the core's readers; public `/v1/systemone` and `/v1/router/score` to the real module and the fake engine byte for byte by SHA-256, the engine's `MALFORMED_JSON`, 503 when off; an upstream decision GGUF on the fake in upstream mode: the newest upstream pack at the floor picked over an older one and the fork, no `--decision`, `-ub` for laya, router 501 `UNSUPPORTED_ENDPOINT`, "Update llama.cpp to b11370" below the floor); upstream: `src/decision/{upstream-version,model-facts}.test.ts`, the upstream cases of `engine`, `engine-candidates`, `args`, `readiness`, `process` and `service` tests (floor by type and projector, the projector checked and the spec skipped, the router refused without a request, an install of the other provider ignored) | an e2e on the compiled binary; a live test against a real fork build (1.7.0) and a laya GGUF, and against upstream b11370+ with an upstream decision GGUF; the app's consumer | diff --git a/scripts/lib/sdcpp-surface.d.mts b/scripts/lib/sdcpp-surface.d.mts index 7083b6e8..dcfff42a 100644 --- a/scripts/lib/sdcpp-surface.d.mts +++ b/scripts/lib/sdcpp-surface.d.mts @@ -16,7 +16,16 @@ export interface SdcppContract { }> probe?: { bins: string[]; argv: string[]; markers: string[] } version?: { pattern: string } - flags: Array<{ flag: string; severity?: Severity; source?: string; note?: string }> + flags: Array<{ + flag: string + severity?: Severity + source?: string + note?: string + /** Emitted only to builds from this one on. */ + from_build?: number + /** Emitted only to builds before this one, and to a tag that names no build. */ + below_build?: number + }> strings?: Array<{ id: string text: string @@ -90,7 +99,18 @@ export declare const SDCPP_CHECKS: ReadonlyArray<{ id: string; title: string }> export declare const MIN_SD_HELP_OPTIONS: number export declare function parseSdHelp(text: string): SdHelpOption[] export declare function findSdOption(options: readonly SdHelpOption[], flag: string): SdHelpOption | undefined -export declare function checkSdHelp(contract: SdcppContract, options: readonly SdHelpOption[]): Finding[] +/** `master--` → the build number; any other tag → undefined. */ +export declare function sdcppBuildOf(tag: string | undefined): number | undefined +/** The contract's flags core emits to `build` (undefined: older than every bound). */ +export declare function sdFlagsForBuild( + contract: SdcppContract, + build: number | undefined +): SdcppContract['flags'] +export declare function checkSdHelp( + contract: SdcppContract, + options: readonly SdHelpOption[], + tag?: string +): Finding[] export declare function diffSdHelp( pinOptions: readonly SdHelpOption[], candidateOptions: readonly SdHelpOption[], diff --git a/scripts/lib/sdcpp-surface.mjs b/scripts/lib/sdcpp-surface.mjs index 72a2418b..511a1724 100644 --- a/scripts/lib/sdcpp-surface.mjs +++ b/scripts/lib/sdcpp-surface.mjs @@ -92,11 +92,33 @@ export function parseSdHelp(text) { export const findSdOption = (options, flag) => options.find((o) => o.aliases.includes(flag)) /** - * The build's `--help` against the flags core emits (the contract's `flags`): one it does not know - * fails the launch (`break`), or is a `warn` for a flag core emits only when opted in (`-M`); one it - * marks deprecated is a `warn`. + * `master--` → the build number, as `sdcppBuildOf` in src/diffusion/compat.ts reads an + * install's tag; any other tag → undefined. */ -export function checkSdHelp(contract, options) { +export function sdcppBuildOf(tag) { + const match = /^master-(\d+)-./.exec(tag ?? '') + return match ? Number(match[1]) : undefined +} + +/** + * The contract's flags core emits to `build`: a flag with `from_build` only from that build on, one + * with `below_build` only before it. `build` is undefined for a tag that names none, which core + * treats as older than every bound (`speedFlags` in src/diffusion/args.ts). + */ +export function sdFlagsForBuild(contract, build) { + return contract.flags.filter( + (f) => + (f.from_build === undefined || (build !== undefined && build >= f.from_build)) && + (f.below_build === undefined || build === undefined || build < f.below_build) + ) +} + +/** + * The build's `--help` against the flags core emits to it (the contract's `flags` for the build `tag` + * names): one it does not know fails the launch (`break`, or the flag's own severity); one it marks + * deprecated is a `warn`. + */ +export function checkSdHelp(contract, options, tag) { if (options.length < MIN_SD_HELP_OPTIONS) return [ finding( @@ -107,7 +129,7 @@ export function checkSdHelp(contract, options) { ), ] const findings = [] - for (const f of contract.flags) { + for (const f of sdFlagsForBuild(contract, sdcppBuildOf(tag))) { const option = findSdOption(options, f.flag) const severity = f.severity ?? 'break' if (!option) @@ -495,7 +517,7 @@ export function buildSdcppReport(contract, inputs, options = {}) { skipped['help.diff'] = 'the candidate was not run' } else { const options = parseSdHelp(candidate.help_text ?? '') - findings.push(...checkSdHelp(contract, options)) + findings.push(...checkSdHelp(contract, options, candidate.tag)) const pinOptions = pin?.help_text === undefined ? undefined : parseSdHelp(pin.help_text) if (!pin) skipped['help.diff'] = 'no pin' else if (pin.capture_error) diff --git a/src/diffusion/args.test.ts b/src/diffusion/args.test.ts index b77fb010..5a7817b0 100644 --- a/src/diffusion/args.test.ts +++ b/src/diffusion/args.test.ts @@ -18,10 +18,9 @@ import { buildImgGenRequest, buildServerArgs, buildVidGenRequest, - VID_GEN_MODE_FLAG_ENV, - videoModeFlags, commandSummaryForLog, cpuBackendExtraArgs, + cpuBackendFlags, DIFFUSION_BACKEND_ENV, hostEnv, imageVaeTilingArea, @@ -29,7 +28,9 @@ import { isM5Brand, loadExtraArgs, METAL_TE_GPU_ENV, - metalTextEncoderFlags, + metalTextEncoderCpuModules, + MODULE_ASSIGNMENT_FLAGS_BUILD, + offloadCpuModules, offloadFlags, speedFlags, VAE_TILING_AREA, @@ -42,6 +43,10 @@ import type { ResolvedInputs, ServerSpec } from './types.js' const MAC: ArgsHost = { platform: 'darwin', env: {} } const LINUX: ArgsHost = { platform: 'linux', env: {} } +/** The first build conf served, which knows only `--diffusion-fa` and `--diffusion-conv-direct`. */ +const LEGACY_TAG = 'master-849-d04e895' +/** The pin as conf's mirror tags it: `--flash-attn` and `--conv-direct`. */ +const MODERN_TAG = 'master-1088-32d516c-af0b1071' function spec(files: DiffusionModelFiles, offload: DiffusionOffloadPolicy): ServerSpec { return { @@ -49,7 +54,7 @@ function spec(files: DiffusionModelFiles, offload: DiffusionOffloadPolicy): Serv engine: 'sd-cpp', backend: 'metal', backendId: 'macos-arm64', - tag: 'master-849-d04e895', + tag: LEGACY_TAG, modelId: 'z-image:q4_k_m', family: 'z-image', modality: 'image', @@ -85,7 +90,6 @@ describe('buildServerArgs', () => { t5xxl: '/m/t5xxl.gguf', llm: '/m/qwen3.gguf', llmVision: '/m/qwen3-mmproj.gguf', - qwen2vl: '/m/qwen2vl.gguf', } const args = buildServerArgs(spec(files, 'none'), 4242, '/s', MAC) const idx = (flag: string) => args.indexOf(flag) @@ -94,7 +98,6 @@ describe('buildServerArgs', () => { expect(idx('--clip_l')).toBeLessThan(idx('--t5xxl')) expect(idx('--t5xxl')).toBeLessThan(idx('--llm')) expect(idx('--llm')).toBeLessThan(idx('--llm_vision')) - expect(idx('--llm_vision')).toBeLessThan(idx('--qwen2vl')) expect(valueAfter(args, '--llm_vision')).toBe('/m/qwen3-mmproj.gguf') expect(valueAfter(args, '--vae-format')).toBe('flux2') expect(idx('--vae-format')).toBeLessThan(idx('--listen-ip')) @@ -121,54 +124,93 @@ describe('buildServerArgs', () => { expect(empty).not.toContain('--vae-format') }) + it('hands a qwen2vl file over as --llm, the slot its deprecated alias names, and keeps it over an llm file', () => { + const qwenImage = { diffusionModel: '/m/qwen-image.gguf', qwen2vl: '/m/qwen2.5-vl.gguf' } + const args = buildServerArgs(spec(qwenImage, 'none'), 1, '/s', LINUX) + expect(valueAfter(args, '--llm')).toBe('/m/qwen2.5-vl.gguf') + expect(args).not.toContain('--qwen2vl') + // The old argv said `--llm` and then `--qwen2vl`; the second won. + const both = buildServerArgs(spec({ ...qwenImage, llm: '/m/qwen3.gguf' }, 'none'), 1, '/s', LINUX) + expect(both.filter((a) => a === '--llm')).toHaveLength(1) + expect(valueAfter(both, '--llm')).toBe('/m/qwen2.5-vl.gguf') + }) + it('passes threads when they are set', () => { const args = buildServerArgs({ ...spec(zImageFiles(), 'none'), threads: 6 }, 1, '/s', MAC) expect(valueAfter(args, '--threads')).toBe('6') }) - it('maps the offload policies to the documented flags', () => { + it('maps the offload policies to the documented flags and modules', () => { expect(offloadFlags('none')).toEqual([]) - expect(offloadFlags('group')).toEqual(['--offload-to-cpu', '--diffusion-fa']) - expect(offloadFlags('model')).toEqual([ - '--offload-to-cpu', - '--clip-on-cpu', - '--vae-on-cpu', - '--diffusion-fa', - '--vae-tiling', - ]) - expect(speedFlags()).toEqual(['--diffusion-fa', '--diffusion-conv-direct']) + expect(offloadFlags('group')).toEqual(['--offload-to-cpu']) + expect(offloadFlags('model')).toEqual(['--offload-to-cpu', '--vae-tiling']) + expect(offloadCpuModules('none')).toEqual([]) + expect(offloadCpuModules('group')).toEqual([]) + expect(offloadCpuModules('model')).toEqual(['te', 'vae']) + }) + + it('puts the CPU modules in one --backend, each once, the text encoder first', () => { + expect(cpuBackendFlags([])).toEqual([]) + expect(cpuBackendFlags(['te'])).toEqual(['--backend', 'te=cpu']) + expect(cpuBackendFlags(['vae'])).toEqual(['--backend', 'vae=cpu']) + expect(cpuBackendFlags(['vae', 'te', 'te'])).toEqual(['--backend', 'te=cpu,vae=cpu']) + }) + + it('spells the speed flags for the build: the module assignments from 982 on, the old flags before', () => { + const modern = ['--flash-attn', 'off,diffusion=on', '--conv-direct', 'auto,diffusion=on,controlnet=on'] + const legacy = ['--diffusion-fa', '--diffusion-conv-direct'] + expect(MODULE_ASSIGNMENT_FLAGS_BUILD).toBe(982) + expect(speedFlags(982)).toEqual(modern) + expect(speedFlags(1091)).toEqual(modern) + expect(speedFlags(981)).toEqual(legacy) + expect(speedFlags(849)).toEqual(legacy) + // A tag that names no build gets what every build up to the pin still reads. + expect(speedFlags(undefined)).toEqual(legacy) + expect(buildServerArgs({ ...spec(zImageFiles(), 'none'), tag: MODERN_TAG }, 1, '/s', LINUX)).toEqual( + expect.arrayContaining(modern) + ) + expect(buildServerArgs({ ...spec(zImageFiles(), 'none'), tag: 'unknown' }, 1, '/s', LINUX)).toEqual( + expect.arrayContaining(legacy) + ) }) - it('de-duplicates the speed flags against the offload flags', () => { - const args = buildServerArgs(spec(zImageFiles(), 'group'), 1, '/s', MAC) - expect(args.filter((a) => a === '--diffusion-fa')).toHaveLength(1) - expect(args).toContain('--diffusion-conv-direct') - expect(args).toContain('--offload-to-cpu') + it('says each hardware flag once, whatever the policy and the host', () => { + for (const tag of [LEGACY_TAG, MODERN_TAG]) + for (const offload of ['none', 'group', 'model'] as const) + for (const host of [MAC, LINUX]) { + const args = buildServerArgs({ ...spec(zImageFiles(), offload), tag }, 1, '/s', host) + const flags = args.filter((a) => a.startsWith('--')) + expect(new Set(flags).size, `${tag} ${offload} ${host.platform}`).toBe(flags.length) + } }) - it('says --clip-on-cpu once under model offload on macOS', () => { - const args = buildServerArgs(spec(zImageFiles(), 'model'), 1, '/s', MAC) - expect(args.filter((a) => a === '--clip-on-cpu')).toHaveLength(1) + it('moves the text encoder and the VAE in one --backend under model offload, on macOS too', () => { + const args = buildServerArgs({ ...spec(zImageFiles(), 'model'), tag: MODERN_TAG }, 1, '/s', MAC) + expect(args.filter((a) => a === '--backend')).toHaveLength(1) + expect(valueAfter(args, '--backend')).toBe('te=cpu,vae=cpu') + expect(valueAfter(args, '--flash-attn')).toBe('off,diffusion=on') + for (const flag of ['--clip-on-cpu', '--vae-on-cpu', '--diffusion-fa', '--diffusion-conv-direct']) + expect(args, flag).not.toContain(flag) }) it('pins the text encoder to the CPU on macOS unless overridden', () => { - expect(metalTextEncoderFlags(true, undefined)).toEqual(['--clip-on-cpu']) - expect(metalTextEncoderFlags(true, '0')).toEqual(['--clip-on-cpu']) - expect(metalTextEncoderFlags(true, '1')).toEqual([]) - expect(metalTextEncoderFlags(true, ' TRUE ')).toEqual([]) - expect(metalTextEncoderFlags(true, 'yes')).toEqual([]) - expect(metalTextEncoderFlags(true, 'on')).toEqual([]) - expect(metalTextEncoderFlags(false, undefined)).toEqual([]) + expect(metalTextEncoderCpuModules(true, undefined)).toEqual(['te']) + expect(metalTextEncoderCpuModules(true, '0')).toEqual(['te']) + expect(metalTextEncoderCpuModules(true, '1')).toEqual([]) + expect(metalTextEncoderCpuModules(true, ' TRUE ')).toEqual([]) + expect(metalTextEncoderCpuModules(true, 'yes')).toEqual([]) + expect(metalTextEncoderCpuModules(true, 'on')).toEqual([]) + expect(metalTextEncoderCpuModules(false, undefined)).toEqual([]) const onMac = buildServerArgs(spec(zImageFiles(), 'none'), 1, '/s', MAC) - expect(onMac).toContain('--clip-on-cpu') + expect(valueAfter(onMac, '--backend')).toBe('te=cpu') const elsewhere = buildServerArgs(spec(zImageFiles(), 'none'), 1, '/s', LINUX) - expect(elsewhere).not.toContain('--clip-on-cpu') + expect(elsewhere).not.toContain('--backend') const overridden = buildServerArgs(spec(zImageFiles(), 'none'), 1, '/s', { platform: 'darwin', env: { [METAL_TE_GPU_ENV]: '1' }, }) - expect(overridden).not.toContain('--clip-on-cpu') + expect(overridden).not.toContain('--backend') }) it('puts extra args last, so they win', () => { @@ -205,14 +247,16 @@ describe('buildServerArgs', () => { embeddingsConnectors: '/m/i', } const emitted = new Set() - for (const offload of ['none', 'group', 'model'] as const) { - const full = { ...spec(everything, offload), threads: 4, extraArgs: cpuBackendExtraArgs([]) } - for (const arg of buildServerArgs(full, 1, '/s', MAC)) if (arg.startsWith('-')) emitted.add(arg) - } + for (const tag of [LEGACY_TAG, MODERN_TAG]) + for (const offload of ['none', 'group', 'model'] as const) { + const full = { ...spec(everything, offload), tag, threads: 4, extraArgs: cpuBackendExtraArgs([]) } + for (const arg of buildServerArgs(full, 1, '/s', MAC)) if (arg.startsWith('-')) emitted.add(arg) + } expect([...emitted].filter((flag) => !required.has(flag))).toEqual([]) - // The video flags are in the list too; the mode flag is not, because it is off until proven. + // The video flags are in the list too; no mode flag, and none of the deprecated aliases. expect(required.has('--audio-vae') && required.has('--embeddings-connectors')).toBe(true) - expect(required.has('-M')).toBe(false) + for (const flag of ['-M', '--qwen2vl', '--clip-on-cpu', '--vae-on-cpu']) + expect(required.has(flag), flag).toBe(false) // And the list names nothing this module stopped emitting. required.delete('--verbose') expect([...required].filter((flag) => !emitted.has(flag))).toEqual([]) @@ -228,6 +272,20 @@ describe('the CPU-backend recovery', () => { expect(withoutDeviceBackendFlags(['-x', '--backend'])).toEqual(['-x']) }) + it('keeps the CPU modules’ --backend and appends the bare cpu after it, which sd.cpp joins into all-CPU', () => { + const recovered = { + ...spec(zImageFiles(), 'model'), + tag: MODERN_TAG, + extraArgs: cpuBackendExtraArgs([]), + cpuFallback: true, + } + const args = buildServerArgs(recovered, 1, '/s', MAC) + const values = args.flatMap((a, i) => (a === '--backend' ? [args[i + 1]] : [])) + // Joined: `te=cpu,vae=cpu,cpu`, the bare entry being the default for every other module. + expect(values).toEqual(['te=cpu,vae=cpu', 'cpu']) + expect(args.slice(-2)).toEqual(['--backend', 'cpu']) + }) + it('starts a load on the CPU only under ATOMIC_DIFFUSION_BACKEND=cpu', () => { expect(DIFFUSION_BACKEND_ENV).toBe('ATOMIC_DIFFUSION_BACKEND') for (const value of ['cpu', 'CPU', ' cpu ']) @@ -501,6 +559,13 @@ describe('commandSummaryForLog', () => { ) expect(commandSummaryForLog(['--diffusion-model'])).toBe('') }) + + it('names every --backend joined, as sd.cpp reads them', () => { + expect(commandSummaryForLog(['--backend', 'te=cpu,vae=cpu', '-v', '--backend', 'cpu'])).toBe( + 'backend=te=cpu,vae=cpu,cpu' + ) + expect(commandSummaryForLog(['--backend=te=cpu'])).toBe('backend=te=cpu') + }) }) describe('the host switches', () => { @@ -538,19 +603,11 @@ describe('the video argv', () => { expect(buildServerArgs(spec(zImageFiles(), 'none'), 1, '/s', MAC)).not.toContain('--audio-vae') }) - it('emits -M vid_gen only for a video model and only when the environment opts in', () => { - expect(videoModeFlags('video', undefined)).toEqual([]) - expect(videoModeFlags('video', '0')).toEqual([]) - expect(videoModeFlags('image', '1')).toEqual([]) - for (const on of ['1', 'true', 'YES', ' on ']) - expect(videoModeFlags('video', on), on).toEqual(['-M', 'vid_gen']) - const host: ArgsHost = { platform: 'linux', env: { [VID_GEN_MODE_FLAG_ENV]: '1' } } + it('never emits sd-cli’s -M, even under the switch that used to opt into it', () => { + const host: ArgsHost = { platform: 'linux', env: { ATOMIC_DIFFUSION_VID_GEN_MODE_FLAG: '1' } } const args = buildServerArgs({ ...sampleVideoSpec(), extraArgs: ['--x'] }, 1, '/s', host) - const at = args.indexOf('-M') - expect(args[at + 1]).toBe('vid_gen') - // Before -v and the caller's extras, after the hardware flags. - expect(at).toBeLessThan(args.indexOf('-v')) - expect(at).toBeGreaterThan(args.indexOf('--diffusion-fa')) + expect(args).not.toContain('-M') + expect(args).not.toContain('vid_gen') expect(args.slice(-1)).toEqual(['--x']) }) }) diff --git a/src/diffusion/args.ts b/src/diffusion/args.ts index 7935f555..5a006352 100644 --- a/src/diffusion/args.ts +++ b/src/diffusion/args.ts @@ -3,18 +3,18 @@ * tested without a binary or a model file. Port of `args.rs` in `tauri-plugin-atomic-diffusion` (app * commit `ec1fd3ea7`, and the host switch of `process.rs`), itself a port of Studio's `sd_cpp_args.py`. * - * Every flag emitted here is listed in `test/fixtures/sdcpp/required-flags.txt`, which the live test - * holds against the pinned binary's `--help`. + * Every flag emitted here is in `test/fixtures/sdcpp/engine-contract.json` with the builds that get it + * (and in `required-flags.txt`); the live test holds the binary's `--help` to the flags of its build. */ import type { DiffusionBackend, DiffusionFamilyDefaults, - DiffusionModality, DiffusionOffloadPolicy, ImageGenerateRequest, VideoGenerateRequest, } from '../contracts/index.js' +import { sdcppBuildOf } from './compat.js' import type { ResolvedInputs, ServerSpec } from './types.js' import { decodeTilingParams } from './video-tiling.js' import type { VideoDecodeTiling } from './video-tiling.js' @@ -24,11 +24,12 @@ import { defaultStrength, usesInitImage, usesMask, usesReferences, workflowOf } export const METAL_TE_GPU_ENV = 'ATOMIC_DIFFUSION_METAL_TE_GPU' /** - * Opt-in for `-M vid_gen` on a video load. `sd-server` infers its modes from the model, and the flag - * is documented for `sd-cli`; it is emitted only when this is `1`/`true`/`yes`/`on`, until the live - * test has shown whether the server wants it. + * The first build with `--flash-attn` and `--conv-direct` (leejet/stable-diffusion.cpp#2134 and the + * per-module flash attention next to it, both 2026-10-13). From it on `--diffusion-fa` and + * `--diffusion-conv-direct` are deprecated spellings of what {@link speedFlags} passes; the builds + * before it know only those, and conf served two of them (849 and 883), which stay installed. */ -export const VID_GEN_MODE_FLAG_ENV = 'ATOMIC_DIFFUSION_VID_GEN_MODE_FLAG' +export const MODULE_ASSIGNMENT_FLAGS_BUILD = 982 const truthy = (value: string | undefined): boolean => ['1', 'true', 'yes', 'on'].includes((value ?? '').trim().toLowerCase()) @@ -39,23 +40,47 @@ export interface ArgsHost { env: Record } -function dedup(flags: readonly string[]): string[] { - return [...new Set(flags)] -} +/** A module this core moves to the CPU backend: the text encoders (`te`) or the VAE. */ +export type CpuModule = 'te' | 'vae' /** - * The memory policy as sd.cpp offload flags. `group` streams the model (`--offload-to-cpu`) with - * flash attention; `model` also puts CLIP and the VAE on the CPU and tiles the VAE. + * The memory policy as sd.cpp flags. `group` streams the weights from RAM (`--offload-to-cpu`); + * `model` also tiles the VAE, and {@link offloadCpuModules} runs the text encoder and the VAE on the + * CPU. Flash attention, which both used to add, comes from {@link speedFlags} under every policy. */ export function offloadFlags(policy: DiffusionOffloadPolicy): string[] { - if (policy === 'group') return ['--offload-to-cpu', '--diffusion-fa'] - if (policy === 'model') - return ['--offload-to-cpu', '--clip-on-cpu', '--vae-on-cpu', '--diffusion-fa', '--vae-tiling'] + if (policy === 'group') return ['--offload-to-cpu'] + if (policy === 'model') return ['--offload-to-cpu', '--vae-tiling'] return [] } -/** Numerically exact speed-ups: flash attention, and direct convolution in the diffusion model. */ -export function speedFlags(): string[] { +/** The modules `policy` runs on the CPU backend: the text encoder and the VAE under `model`. */ +export function offloadCpuModules(policy: DiffusionOffloadPolicy): CpuModule[] { + return policy === 'model' ? ['te', 'vae'] : [] +} + +/** + * `modules` on the CPU backend as one `--backend te=cpu,vae=cpu`. `--clip-on-cpu` and `--vae-on-cpu`, + * deprecated for this spelling, did nothing but prepend the same entries to `--backend` on every build + * conf has served (849 on). sd.cpp joins a repeated `--backend` with commas and a module's own entry + * beats the bare default, so the CPU recovery's `--backend cpu`, appended later, still moves the rest. + */ +export function cpuBackendFlags(modules: readonly CpuModule[]): string[] { + const wanted = new Set(modules) + const entries = (['te', 'vae'] as const).filter((m) => wanted.has(m)).map((m) => `${m}=cpu`) + return entries.length === 0 ? [] : ['--backend', entries.join(',')] +} + +/** + * Numerically exact speed-ups: flash attention in the diffusion model only, direct convolution in the + * diffusion model and ControlNet. From {@link MODULE_ASSIGNMENT_FLAGS_BUILD} on they are the module + * assignments `--diffusion-fa` and `--diffusion-conv-direct` are deprecated for (the flash-attention + * one is byte for byte what `--diffusion-fa` sets); older builds, and a tag that names no build, get + * the old two flags. + */ +export function speedFlags(build: number | undefined): string[] { + if (build !== undefined && build >= MODULE_ASSIGNMENT_FLAGS_BUILD) + return ['--flash-attn', 'off,diffusion=on', '--conv-direct', 'auto,diffusion=on,controlnet=on'] return ['--diffusion-fa', '--diffusion-conv-direct'] } @@ -65,14 +90,9 @@ export function speedFlags(): string[] { * FLUX.2, T5 for FLUX.1) takes the whole server down on the first prompt. The encoder runs once per * prompt and the denoiser every step, so pinning only the encoder keeps Metal where it matters. */ -export function metalTextEncoderFlags(isMacos: boolean, envOverride: string | undefined): string[] { +export function metalTextEncoderCpuModules(isMacos: boolean, envOverride: string | undefined): CpuModule[] { if (!isMacos) return [] - return truthy(envOverride) ? [] : ['--clip-on-cpu'] -} - -/** `-M vid_gen` for a video model, only while the environment opts in. */ -export function videoModeFlags(modality: DiffusionModality, envOverride: string | undefined): string[] { - return modality === 'video' && truthy(envOverride) ? ['-M', 'vid_gen'] : [] + return truthy(envOverride) ? [] : ['te'] } /** An Apple M5 CPU brand string: `Apple M5`, `Apple M5 Max`. */ @@ -149,8 +169,9 @@ export function isGgmlUnsupportedOpAbort(text: string): boolean { /** * The `sd-server` argv, without the binary. Model files first, then the listener, the scratch - * directories sd-server insists on iterating, threads, the hardware flags (de-duplicated, stable - * order), `-v` so the per-step sampling lines are printed, and the caller's `extraArgs` last. + * directories sd-server insists on iterating, threads, the hardware flags (each once, stable order, + * spelled for the build `spec.tag` names), `-v` so the per-step sampling lines are printed, and the + * caller's `extraArgs` last. No mode flag: sd-server takes its modes from the model, and `-M` is sd-cli's. */ export function buildServerArgs( spec: ServerSpec, @@ -160,15 +181,16 @@ export function buildServerArgs( ): string[] { const { files } = spec const args = ['--diffusion-model', files.diffusionModel] + // `--qwen2vl` is a deprecated alias of `--llm`: one slot, the last flag wins. Qwen-Image's + // Qwen2.5-VL encoder goes in as `--llm`, and a spec naming both still gets its `qwen2vl` file. const optional: Array<[string, string | undefined]> = [ ['--vae', files.vae], ['--audio-vae', files.audioVae], ['--embeddings-connectors', files.embeddingsConnectors], ['--clip_l', files.clipL], ['--t5xxl', files.t5xxl], - ['--llm', files.llm], + ['--llm', files.qwen2vl || files.llm], ['--llm_vision', files.llmVision], - ['--qwen2vl', files.qwen2vl], ] for (const [flag, value] of optional) if (value) args.push(flag, value) if (files.vaeFormat) args.push('--vae-format', files.vaeFormat) @@ -176,13 +198,13 @@ export function buildServerArgs( for (const flag of ['--lora-model-dir', '--hires-upscalers-dir', '--embd-dir']) args.push(flag, scratchDir) if (spec.threads !== undefined) args.push('--threads', String(spec.threads)) args.push( - ...dedup([ - ...offloadFlags(spec.offload), - ...speedFlags(), - ...metalTextEncoderFlags(host.platform === 'darwin', host.env[METAL_TE_GPU_ENV]), - ]) + ...offloadFlags(spec.offload), + ...cpuBackendFlags([ + ...offloadCpuModules(spec.offload), + ...metalTextEncoderCpuModules(host.platform === 'darwin', host.env[METAL_TE_GPU_ENV]), + ]), + ...speedFlags(sdcppBuildOf(spec.tag)) ) - args.push(...videoModeFlags(spec.modality, host.env[VID_GEN_MODE_FLAG_ENV])) args.push('-v', ...spec.extraArgs) return args } @@ -342,20 +364,25 @@ export function buildVidGenRequest( return body } -function lastOptionValue(args: readonly string[], option: string): string | undefined { - let value: string | undefined +function optionValues(args: readonly string[], option: string): string[] { + const values: string[] = [] let i = 0 while (i < args.length) { const arg = args[i] as string if (arg === option) { - value = args[i + 1] ?? value + const value = args[i + 1] + if (value !== undefined) values.push(value) i += 2 continue } - if (arg.startsWith(`${option}=`)) value = arg.slice(option.length + 1) + if (arg.startsWith(`${option}=`)) values.push(arg.slice(option.length + 1)) i += 1 } - return value + return values +} + +function lastOptionValue(args: readonly string[], option: string): string | undefined { + return optionValues(args, option).at(-1) } function compact(value: string, limit: number): string { @@ -385,7 +412,8 @@ export function commandSummaryForLog(args: readonly string[]): string { const value = lastOptionValue(args, option) if (value !== undefined) fields.push(`${label}=${compact(value, 16)}`) } - const backend = lastOptionValue(args, '--backend') - if (backend !== undefined) fields.push(`backend=${compact(backend, 32)}`) + // sd.cpp joins a repeated `--backend` with commas: the CPU modules', then the recovery's `cpu`. + const backends = optionValues(args, '--backend') + if (backends.length > 0) fields.push(`backend=${compact(backends.join(','), 32)}`) return fields.join(' ') } diff --git a/src/diffusion/compat.test.ts b/src/diffusion/compat.test.ts index ee238f19..f4725e63 100644 --- a/src/diffusion/compat.test.ts +++ b/src/diffusion/compat.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import type { DiffusionBackendInstallRecord } from '../contracts/index.js' -import { checkEngineCompatibility, selectModelInstall } from './compat.js' +import { checkEngineCompatibility, sdcppBuildOf, selectModelInstall } from './compat.js' const record = (tag: string, backendId: string): DiffusionBackendInstallRecord => ({ tag, @@ -21,6 +21,15 @@ const codeOf = (fn: () => unknown): string | undefined => { } } +describe('sdcppBuildOf', () => { + it('reads the build of upstream, fork and mirror tags, and nothing else', () => { + expect(sdcppBuildOf('master-849-d04e895')).toBe(849) + expect(sdcppBuildOf('master-1088-32d516c-af0b1071')).toBe(1088) + for (const tag of ['unknown', 'master-883', 'master-883-', 'master-x83-abc', 'master-137f740', 'b1088-x']) + expect(sdcppBuildOf(tag), tag).toBeUndefined() + }) +}) + describe('checkEngineCompatibility', () => { // The tag table of `modern_families_require_a_compatible_engine_without_switching_backends` // (`session.rs`, app commit ec1fd3ea7). diff --git a/src/diffusion/compat.ts b/src/diffusion/compat.ts index 1c194640..dfb93150 100644 --- a/src/diffusion/compat.ts +++ b/src/diffusion/compat.ts @@ -29,8 +29,11 @@ const ENGINE_FLOORS: ReadonlyMap = new Map([ ['p-h3-image', H3_IMAGE], ]) -/** `master--` → the build number; anything else → undefined. */ -function buildOf(tag: string): number | undefined { +/** + * `master--` → the build number; anything else → undefined. Also the build the argv is + * spelled for (`buildServerArgs`), and `sdcppBuildOf` in `scripts/lib/sdcpp-surface.mjs` reads tags alike. + */ +export function sdcppBuildOf(tag: string): number | undefined { if (!tag.startsWith('master-')) return undefined const rest = tag.slice('master-'.length) const dash = rest.indexOf('-') @@ -47,7 +50,7 @@ function buildOf(tag: string): number | undefined { export function checkEngineCompatibility(family: string, tag: string): void { const floor = ENGINE_FLOORS.get(family) if (!floor) return - const build = buildOf(tag) + const build = sdcppBuildOf(tag) if (build !== undefined && build >= floor.build) return throw diffusionError( 'ENGINE_UPDATE_REQUIRED', diff --git a/src/diffusion/server-process.test.ts b/src/diffusion/server-process.test.ts index de3817d4..c00f1acb 100644 --- a/src/diffusion/server-process.test.ts +++ b/src/diffusion/server-process.test.ts @@ -99,7 +99,11 @@ describe.skipIf(!posix)('spawnServer', () => { expect(tail).toContain(' |#### | 40/100 - 637.50MB/s') expect(tail).toContain(' |##########| 100/100 - 637.50MB/s') expect(tail.at(-1)).toBe(`[INFO ] server.cpp:100 - listening on 127.0.0.1:${handle.port}`) - expect(log[0]).toMatch(/^info: starting sd-server: model=z-image-turbo-Q4_K_M.gguf port=\d+$/) + // On macOS the text encoder is pinned to the CPU, and the summary says so. + const pinned = process.platform === 'darwin' ? ' backend=te=cpu' : '' + expect(log[0]).toMatch( + new RegExp(`^info: starting sd-server: model=z-image-turbo-Q4_K_M.gguf port=\\d+${pinned}$`) + ) // A listener gets what the server prints from then on. handle.setLineListener((line) => seen.push(line)) diff --git a/test/contract/sdcpp-engine-contract.test.ts b/test/contract/sdcpp-engine-contract.test.ts index 74366835..7fb892a7 100644 --- a/test/contract/sdcpp-engine-contract.test.ts +++ b/test/contract/sdcpp-engine-contract.test.ts @@ -9,8 +9,10 @@ import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' import { + buildServerArgs, CAPABILITIES_PATH, classifyExit, + cpuBackendExtraArgs, cliBinaryName, GpuFaultWatch, IMG_GEN_PATH, @@ -21,12 +23,19 @@ import { parseTileAnnouncement, probeOutputIsSdcpp, READY_PATH, + sdcppBuildOf as coreBuildOf, serverBinaryName, VID_GEN_PATH, } from '../../src/diffusion/index.js' import { diffusionBackendLadder } from '../../src/engine-builds/index.js' import type { DiffusionBackendSelectionInput } from '../../src/engine-builds/index.js' -import { parseSdVersion, sdcppBackendArchives } from '../../scripts/lib/sdcpp-surface.mjs' +import { + parseSdVersion, + sdcppBackendArchives, + sdcppBuildOf, + sdFlagsForBuild, +} from '../../scripts/lib/sdcpp-surface.mjs' +import { sampleSpec } from '../helpers/diffusion-fixtures.js' import type { SdcppContract } from '../../scripts/lib/sdcpp-surface.mjs' interface Contract { @@ -60,13 +69,51 @@ describe('the sd.cpp engine contract: flags', () => { .map((line) => line.trim()) .filter((line) => line !== '' && !line.startsWith('#')) - it('breaks on exactly the flags of required-flags.txt and their -v, and only warns about -M', () => { + it('breaks on exactly the flags of required-flags.txt and their -v, and warns about none', () => { const breaks = contract.flags.filter((f) => f.severity === 'break').map((f) => f.flag) expect(new Set(breaks)).toEqual(new Set([...requiredFlags, '-v'])) expect(breaks).toHaveLength(requiredFlags.length + 1) - expect(contract.flags.filter((f) => f.severity !== 'break')).toEqual([ - expect.objectContaining({ flag: '-M', severity: 'warn' }), - ]) + expect(contract.flags.filter((f) => f.severity !== 'break')).toEqual([]) + }) + + it('names, for each build, exactly the flags buildServerArgs spells for it', () => { + const everything = { + diffusionModel: '/m/a.gguf', + vae: '/m/b', + vaeFormat: 'flux2', + clipL: '/m/c', + t5xxl: '/m/d', + llm: '/m/e', + llmVision: '/m/g', + qwen2vl: '/m/f', + audioVae: '/m/h', + embeddingsConnectors: '/m/i', + } + const tags = [ + 'master-849-d04e895', + 'master-981-0000000', + 'master-982-0518b34', + 'master-1088-32d516c-af0b1071', + ] + for (const tag of [...tags, 'unknown']) { + const emitted = new Set() + for (const offload of ['none', 'group', 'model'] as const) + for (const platform of ['darwin', 'linux'] as const) { + const spec = sampleSpec({ + tag, + files: everything, + offload, + threads: 4, + extraArgs: cpuBackendExtraArgs([]), + }) + for (const arg of buildServerArgs(spec, 1, '/s', { platform, env: {} })) + if (arg.startsWith('-')) emitted.add(arg) + } + // `--verbose` is the long spelling of the `-v` the argv says. + const named = sdFlagsForBuild(contract, sdcppBuildOf(tag)).map((f) => f.flag) + expect(emitted, tag).toEqual(new Set(named.filter((flag) => flag !== '--verbose'))) + expect(sdcppBuildOf(tag), tag).toBe(coreBuildOf(tag)) + } }) it('knows every flag literal of the argv builder', () => { diff --git a/test/contract/sdcpp-surface.test.ts b/test/contract/sdcpp-surface.test.ts index 483bf089..5be10205 100644 --- a/test/contract/sdcpp-surface.test.ts +++ b/test/contract/sdcpp-surface.test.ts @@ -19,8 +19,10 @@ import { diffSdHelp, findSdOption, parseSdHelp, + sdcppBuildOf, sdcppCompleteness, sdcppCoreAssets, + sdFlagsForBuild, } from '../../scripts/lib/sdcpp-surface.mjs' import type { ReleaseAssetInfo, SdcppContract } from '../../scripts/lib/sdcpp-surface.mjs' import { liveModelPath, sdcppHostArchive, sdcppInstallManifest } from '../../scripts/lib/sdcpp-fixtures.mjs' @@ -39,6 +41,8 @@ const FORK = release('master-883-137f740') const MIRROR = release('master-883-137f740-a36f1b1a') const names = (r: { assets: Array<{ name: string }> }) => r.assets.map((a) => a.name) const SERVER_HELP = fixture('help/sd-server-master-883-137f740.txt') +/** A build past 982, from the fork's macOS arm64 archive: `--flash-attn` and `--conv-direct` are there. */ +const SERVER_HELP_1028 = fixture('help/sd-server-master-1028-37bc88b.txt') const CLI_HELP = fixture('help/sd-cli-master-883-137f740.txt') const VERSION = fixture('help/sd-server-version-master-883-137f740.txt') const ids = (findings: Array<{ id: string; severity: string }>, severity: string) => @@ -72,15 +76,38 @@ describe('reading sd.cpp’s --help', () => { expect(ids(checkSdHelp(contract, parseSdHelp(help)), 'break')).toEqual(['help.required_flags/--vae']) }) - it('on master-883: three flags core emits are deprecated, -M is sd-cli’s only', () => { - const findings = checkSdHelp(contract, options) - expect(ids(findings, 'break')).toEqual([]) - expect(ids(findings, 'warn').sort()).toEqual([ - 'help.deprecated/--clip-on-cpu', - 'help.deprecated/--qwen2vl', - 'help.deprecated/--vae-on-cpu', - 'help.required_flags/-M', + it('on master-883: every flag core spells for the build is there, and none is deprecated', () => { + expect(checkSdHelp(contract, options, 'master-883-137f740-a36f1b1a')).toEqual([]) + }) + + it('from build 982 on: the module assignments are checked, the flags they replace are not', () => { + const modern = parseSdHelp(SERVER_HELP_1028) + expect(findSdOption(modern, '--diffusion-fa')?.deprecated).toBe(true) + expect(findSdOption(modern, '--clip-on-cpu')?.deprecated).toBe(true) + expect(checkSdHelp(contract, modern, 'master-1028-37bc88b-a5f9a63b')).toEqual([]) + // A tag that names no build gets the old flags from core, so the check reads those. + expect(ids(checkSdHelp(contract, modern, 'unknown'), 'warn').sort()).toEqual([ + 'help.deprecated/--diffusion-conv-direct', + 'help.deprecated/--diffusion-fa', + ]) + // A build that lost --flash-attn breaks the launch; 883 was never going to get it. + const lost = parseSdHelp(without(SERVER_HELP_1028, '--flash-attn')) + expect(ids(checkSdHelp(contract, lost, 'master-1091-b9d7176'), 'break')).toEqual([ + 'help.required_flags/--flash-attn', ]) + expect(ids(checkSdHelp(contract, options, 'master-883-137f740'), 'break')).toEqual([]) + }) + + it('reads the build from a tag and keeps each bounded flag to its side of the bound', () => { + expect(sdcppBuildOf('master-1088-32d516c-af0b1071')).toBe(1088) + expect(sdcppBuildOf('master-137f740')).toBeUndefined() + expect(sdcppBuildOf(undefined)).toBeUndefined() + const flags = (build: number | undefined) => sdFlagsForBuild(contract, build).map((f) => f.flag) + expect(flags(981)).toEqual(expect.arrayContaining(['--diffusion-fa', '--diffusion-conv-direct'])) + expect(flags(981)).not.toEqual(expect.arrayContaining(['--flash-attn'])) + expect(flags(982)).toEqual(expect.arrayContaining(['--flash-attn', '--conv-direct'])) + expect(flags(982)).not.toEqual(expect.arrayContaining(['--diffusion-fa'])) + expect(flags(undefined)).toEqual(flags(849)) }) it('fails closed on something that is not a help screen', () => { @@ -392,7 +419,7 @@ describe('the sd.cpp surface report', () => { }, }) - it('master-883 against its signed mirror: a warn for the deprecated flags, nothing else to fix', () => { + it('master-883 against its signed mirror: no deprecated flag left, nothing to fix', () => { const report = buildSdcppReport( contract, { @@ -404,12 +431,12 @@ describe('the sd.cpp surface report', () => { ) expect(report.schema).toBe('atomic-engine-surface-report') expect(report.engine).toBe('sd-cpp') - expect(report.status).toBe('warn') - expect(report.counts).toEqual({ break: 0, warn: 4, info: 5, error: 0 }) + expect(report.status).toBe('pass') + expect(report.counts).toEqual({ break: 0, warn: 0, info: 5, error: 0 }) expect(report.checks.map((c) => `${c.id}:${c.status}`)).toEqual([ 'help.parse:pass', - 'help.required_flags:warn', - 'help.deprecated:warn', + 'help.required_flags:pass', + 'help.deprecated:pass', 'help.diff:pass', 'invocations.exit:pass', 'install.probe:pass', diff --git a/test/e2e/diffusion-engine.test.ts b/test/e2e/diffusion-engine.test.ts index 8af4f60e..f6a4645e 100644 --- a/test/e2e/diffusion-engine.test.ts +++ b/test/e2e/diffusion-engine.test.ts @@ -161,6 +161,45 @@ describe.skipIf(!existsSync(BIN) || process.platform === 'win32')( expect((await sd.sdStatus(ctx, ready)).activeJob).toBeNull() }, 60_000) + it('spells the speed flags the way build 849 reads them: --diffusion-fa and --diffusion-conv-direct', async () => { + const argvFile = join(ctx.dataFolder, 'sd-argv.json') + await sd.loadedOwner(ctx, { tag: sd.OLD_TAG, env: { FAKE_SD_ARGV_FILE: argvFile } }) + const argv = sd.sdArgv(argvFile) + expect(argv).toContain('--diffusion-fa') + expect(argv).toContain('--diffusion-conv-direct') + for (const flag of ['--flash-attn', '--conv-direct', '--clip-on-cpu', '--vae-on-cpu']) + expect(argv, flag).not.toContain(flag) + }, 60_000) + + it('spells them as module assignments from build 982 on, with no deprecated flag left, and hands a qwen2vl file over as --llm', async () => { + const argvFile = join(ctx.dataFolder, 'sd-argv.json') + const encoder = await sd.writeSdFile( + ctx, + 'shared/Qwen--Qwen2.5-VL-7B/Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf' + ) + await sd.loadedOwner(ctx, { + tag: 'master-1088-32d516c-af0b1071', + env: { FAKE_SD_ARGV_FILE: argvFile }, + files: { qwen2vl: encoder }, + }) + const argv = sd.sdArgv(argvFile) + const valueOf = (flag: string) => argv[argv.indexOf(flag) + 1] + expect(valueOf('--flash-attn')).toBe('off,diffusion=on') + expect(valueOf('--conv-direct')).toBe('auto,diffusion=on,controlnet=on') + expect(valueOf('--llm')).toBe(encoder) + for (const flag of [ + '--diffusion-fa', + '--diffusion-conv-direct', + '--clip-on-cpu', + '--vae-on-cpu', + '--qwen2vl', + ]) + expect(argv, flag).not.toContain(flag) + // The text encoder leaves Metal through --backend now; elsewhere nothing is pinned. + if (process.platform === 'darwin') expect(valueOf('--backend')).toBe('te=cpu') + else expect(argv).not.toContain('--backend') + }, 60_000) + it('refuses Qwen-Image past one megapixel on a Metal engine before anything runs', async () => { const envFile = join(ctx.dataFolder, 'sd-env.json') const { ready, pid } = await sd.loadedOwner(ctx, { diff --git a/test/e2e/diffusion-failures.test.ts b/test/e2e/diffusion-failures.test.ts index ae52bcc1..2b3cb5f9 100644 --- a/test/e2e/diffusion-failures.test.ts +++ b/test/e2e/diffusion-failures.test.ts @@ -113,7 +113,10 @@ describe.skipIf(!existsSync(BIN) || process.platform === 'win32')('an image engi const { ready, pid } = await sd.loadedOwner(ctx, { env: { FAKE_SD_MODE: 'ggml-abort', FAKE_SD_ARGV_FILE: argvFile }, }) - expect(sd.sdArgv(argvFile)).not.toContain('--backend') + // The device process: only the CPU modules on macOS (the text encoder off Metal), no bare `cpu`. + const backends = (argv: string[]) => argv.flatMap((a, i) => (a === '--backend' ? [argv[i + 1]] : [])) + const moduleBackends = process.platform === 'darwin' ? ['te=cpu'] : [] + expect(backends(sd.sdArgv(argvFile))).toEqual(moduleBackends) const events = await sd.collectEvents(ctx, ready) const job = await sd.runJob(ctx, ready) expect(job.state).toBe('completed') @@ -127,6 +130,8 @@ describe.skipIf(!existsSync(BIN) || process.platform === 'win32')('an image engi expect(alive(pid)).toBe(false) const argv = sd.sdArgv(argvFile) expect(argv.slice(-2)).toEqual(['--backend', 'cpu']) + // sd.cpp joins them: the module entries stay, the bare `cpu` is the default for everything else. + expect(backends(argv)).toEqual([...moduleBackends, 'cpu']) const status = await sd.sdStatus(ctx, ready) expect(status.model.state).toBe('loaded') expect(status.model.loaded).toMatchObject({ pid: pids[1], cpuFallback: true }) diff --git a/test/e2e/video.test.ts b/test/e2e/video.test.ts index fd0e1eb2..4398be12 100644 --- a/test/e2e/video.test.ts +++ b/test/e2e/video.test.ts @@ -215,18 +215,19 @@ describe.skipIf(!existsSync(BIN) || process.platform === 'win32')( expect(existsSync(modelFile)).toBe(true) }, 60_000) - it('emits -M vid_gen only when the environment opts in, and honours a video output folder of its own', async () => { + it('loads a video model without sd-cli’s -M, and honours a video output folder of its own', async () => { const argvFile = join(ctx.dataFolder, 'sd-argv.json') const clips = join(ctx.dataFolder, 'Movies', 'Atomic') - const { ready } = await sd.loadedOwner(ctx, { + const { ready, modelFile } = await sd.loadedOwner(ctx, { video: true, env: { FAKE_SD_ARGV_FILE: argvFile }, + // The switch that used to add `-M vid_gen` is gone: sd-server takes its modes from the model. daemonEnv: { ATOMIC_DIFFUSION_VID_GEN_MODE_FLAG: '1' }, config: { videoOutputDir: clips }, }) const argv = sd.sdArgv(argvFile) - expect(argv[argv.indexOf('-M') + 1]).toBe('vid_gen') - expect(argv.indexOf('-M')).toBeLessThan(argv.indexOf('-v')) + expect(argv[argv.indexOf('--diffusion-model') + 1]).toBe(modelFile) + expect(argv).not.toContain('-M') expect((await sd.sdStatus(ctx, ready)).videoOutputDir).toBe(clips) expect((await sd.sdStatus(ctx, ready)).outputDir).toBe(join(ctx.dataFolder, 'images')) const clip = await sd.runVideoJob(ctx, ready) diff --git a/test/fixtures/sdcpp/engine-contract.json b/test/fixtures/sdcpp/engine-contract.json index b75d94e3..6120c386 100644 --- a/test/fixtures/sdcpp/engine-contract.json +++ b/test/fixtures/sdcpp/engine-contract.json @@ -52,13 +52,24 @@ { "flag": "--t5xxl", "severity": "break", "source": "src/diffusion/args.ts" }, { "flag": "--llm", "severity": "break", "source": "src/diffusion/args.ts" }, { "flag": "--llm_vision", "severity": "break", "source": "src/diffusion/args.ts" }, - { "flag": "--qwen2vl", "severity": "break", "source": "src/diffusion/args.ts" }, - { "flag": "--clip-on-cpu", "severity": "break", "source": "src/diffusion/args.ts" }, - { "flag": "--vae-on-cpu", "severity": "break", "source": "src/diffusion/args.ts" }, { "flag": "--vae-tiling", "severity": "break", "source": "src/diffusion/args.ts" }, { "flag": "--offload-to-cpu", "severity": "break", "source": "src/diffusion/args.ts" }, - { "flag": "--diffusion-fa", "severity": "break", "source": "src/diffusion/args.ts" }, - { "flag": "--diffusion-conv-direct", "severity": "break", "source": "src/diffusion/args.ts" }, + { + "flag": "--diffusion-fa", + "severity": "break", + "source": "src/diffusion/args.ts", + "below_build": 982, + "note": "Builds before --flash-attn; from 982 on it is a deprecated spelling of --flash-attn off,diffusion=on." + }, + { + "flag": "--diffusion-conv-direct", + "severity": "break", + "source": "src/diffusion/args.ts", + "below_build": 982, + "note": "Builds before --conv-direct; from 982 on it is deprecated for --conv-direct auto,diffusion=on,controlnet=on." + }, + { "flag": "--flash-attn", "severity": "break", "source": "src/diffusion/args.ts", "from_build": 982 }, + { "flag": "--conv-direct", "severity": "break", "source": "src/diffusion/args.ts", "from_build": 982 }, { "flag": "--listen-ip", "severity": "break", "source": "src/diffusion/args.ts" }, { "flag": "--listen-port", "severity": "break", "source": "src/diffusion/args.ts" }, { "flag": "--lora-model-dir", "severity": "break", "source": "src/diffusion/args.ts" }, @@ -67,13 +78,7 @@ { "flag": "--threads", "severity": "break", "source": "src/diffusion/args.ts" }, { "flag": "--backend", "severity": "break", "source": "src/diffusion/args.ts" }, { "flag": "--verbose", "severity": "break", "source": "src/diffusion/args.ts" }, - { "flag": "-v", "severity": "break", "source": "src/diffusion/args.ts" }, - { - "flag": "-M", - "severity": "warn", - "source": "src/diffusion/args.ts", - "note": "Emitted only under ATOMIC_DIFFUSION_VID_GEN_MODE_FLAG, until a live run shows sd-server wants it; sd-cli has it." - } + { "flag": "-v", "severity": "break", "source": "src/diffusion/args.ts" } ], "strings": [ { diff --git a/test/fixtures/sdcpp/help/sd-server-master-1028-37bc88b.txt b/test/fixtures/sdcpp/help/sd-server-master-1028-37bc88b.txt new file mode 100644 index 00000000..796da290 --- /dev/null +++ b/test/fixtures/sdcpp/help/sd-server-master-1028-37bc88b.txt @@ -0,0 +1,278 @@ +stable-diffusion.cpp version unknown, commit 37bc88b +Usage: ./sd-server [options] + +Svr Options: + -l, --listen-ip server listen ip (default: 127.0.0.1) + --serve-html-path path to HTML file to serve at root (optional) + --listen-port server listen port (default: 1234) + --color colors the logging tags according to level + -h, --help show this help message and exit + --model-dir model root; repeat to search multiple directories (default: models) + --log-level minimum log level, one of [debug, verbose, info, warn, error] (default: info) + -v, --verbose equivalent to --log-level verbose + +Context Options: + -m, --model path to full model + --clip_l path to the clip-l text encoder + --clip_g path to the clip-g text encoder + --clip_vision path to the clip-vision encoder + --t5xxl path to the t5xxl text encoder + --llm path to the llm text encoder. For example: (qwenvl2.5 for qwen-image, + mistral-small3.2 for flux2, ...) + --tokenizer tokenizer.json path, or comma-separated main=FILE,clip-l=FILE,clip-g=FILE + assignments; required for PiD and Lens + --llm_vision path to the llm vit + --qwen2vl alias of --llm. Deprecated. + --qwen2vl_vision alias of --llm_vision. Deprecated. + --diffusion-model path to the standalone diffusion model + --high-noise-diffusion-model path to the standalone high noise diffusion model + --uncond-diffusion-model path to the standalone unconditional diffusion model, currently used by + Ideogram4 CFG + --embeddings-connectors path to LTXAV embeddings connectors + --vae path to standalone vae model + --vae-format VAE latent format override: auto, flux, sd3, flux2, or wan (default: auto) + --audio-vae path to standalone LTX audio vae model + --audio-encoder path to wav2vec2 audio encoder model (Wan2.2 S2V) + --taesd path to taesd. Using Tiny AutoEncoder for fast decoding (low quality) + --tae alias of --taesd + --control-net path to control net model + --ip-adapter path to IP-Adapter model (requires --clip_vision) + --motion-module path to AnimateDiff motion module (SD 1.5); enables video generation on + --video-frames > 1 + --embd-dir embeddings directory + --lora-model-dir lora model directory + --hires-upscalers-dir highres fix upscaler model directory + --tensor-type-rules weight type per tensor pattern (example: "^vae\.=f16,model\.=q8_0") + --model-args extra model args, key=value list. Supports chroma_use_dit_mask, + chroma_use_t5_mask, chroma_t5_mask_pad, qwen_image_zero_cond_t, + qwen_image_2_1_prefix_cache, qwen_image_2_1_prefix_cache_type (auto or a type + name from --type) + --photo-maker path to PHOTOMAKER model + --pulid-weights path to PuLID Flux weights + --upscale-model path to esrgan model. + --backend runtime backend assignment, e.g. cpu or clip=cpu,vae=cuda0,diffusion=vulkan0 + --params-backend parameter backend assignment, e.g. disk, cpu, or diffusion=disk,clip=cpu + --split-mode weight distribution for modules assigned multiple devices (--backend + "diffusion=cuda0&cuda1"): layer (whole transformer blocks per device, + default) or row (matmul rows split across devices, CUDA only). Accepts a + single mode or per-module assignments, e.g. row or diffusion=row,te=layer + --rpc-servers comma-separated list of RPC servers to connect to for offloading, in the + format host:port, e.g. localhost:50052,192.168.1.3:50052 + --max-vram optional per-device budget in GiB for managed weights and runner buffers + during automatic graph-cut execution. Accepts a single value or assignments + by backend/device, e.g. 6 or cuda0=6,vulkan0=4. 0 uses live free VRAM without + an explicit budget; a negative value reserves that much free VRAM + -t, --threads number of threads to use during computation (default: -1). If threads <= 0, + then threads will be set to the number of CPU physical cores + --conditioning-cache-size maximum number of conditioning results cached per model context (default: 4, + 0 disables caching) + --list-devices list available ggml backend devices, including --rpc-servers (one + 'namedescription' per line), and exit; the names are the device names + accepted by --backend and --params-backend + --disable-prefetch disable asynchronous next-segment weight prefetch (defaults to false) + --disable-segmented-compute force monolithic graph execution even when automatic graph cutting is needed + (defaults to false) + --eager-load load all params into the params backend at model-load time instead of lazily + on first use (defaults to false) + --force-sdxl-vae-conv-scale force use of conv scale on sdxl vae + --offload-to-cpu place the weights in RAM to save VRAM, and automatically load them into VRAM + when needed + --mmap whether to memory-map model + --control-net-cpu deprecated; use --backend controlnet=cpu + --clip-on-cpu deprecated; use --backend te=cpu + --vae-on-cpu deprecated; use --backend vae=cpu + --sage-attn use native CUDA SageAttention in the diffusion model, with flash/default + attention fallback + --taesd-preview-only prevents usage of taesd for decoding the final image; the VAE keeps encoding + / decoding and taesd is only used for step previews + --linear-scale linear input scale override (float, default: 0 = model default, 1 = no + scaling) + --attn-scale flash-attention K/V scale override (float, default: 0 = model default, 1 = no + scaling); applies when flash attention is selected + --diffusion-conv-direct deprecated; use --conv-direct auto,diffusion=on,controlnet=on + --vae-conv-direct deprecated; use --conv-direct auto,vae=on + --conv-direct on|off|auto or diffusion/vae/controlnet assignments (default: auto), e.g. + auto,vae=off. Overrides legacy convolution flags + --flash-attn on|off|auto or module assignments (default: auto), e.g. auto,te=off,vae=on. + Last repeated option wins + --fa deprecated; use --flash-attn on + --diffusion-fa deprecated; use --flash-attn off,diffusion=on + --auto-fit on|off (default: on). Preserve --backend (otherwise select one GPU) and place + weights on the compute GPU, RAM, another GPU, or disk in that order, + according to available memory (--max-vram limits GPU budgets). Disabled by + explicit --params-backend; uses automatic graph segmentation when needed + --batched-cfg on|off (default: on). Run the conditional and unconditional CFG branches in + one batched UNet forward when supported + --type weight type (examples: f32, f16, q4_0, q4_1, q5_0, q5_1, q8_0, q2_K, q3_K, + q4_K). If not specified, the default is the type of the weight file + --rng RNG, one of [std_default, cuda, cpu], default: cuda(sd-webui), cpu(comfyui) + --sampler-rng sampler RNG, one of [std_default, cuda, cpu]. If not specified, use --rng + --prediction prediction type override, one of [eps, v, edm_v, sd3_flow, flux_flow, + sefi_flow, minit2i_flow, sensenova_u1_flow, flux3_flow, h3_av_flow, + ming_image_flow] + --lora-apply-mode the way to apply LoRA, one of [auto, immediately, at_runtime], default is + auto. In auto mode, if the model weights contain any quantized parameters, + the at_runtime mode will be used; otherwise, immediately will be used.The + immediately mode may have precision and compatibility issues with quantized + parameters, but it usually offers faster inference speed and, in some cases, + lower memory usage. The at_runtime mode, on the other hand, is exactly the + opposite. + +Default Generation Options: + -p, --prompt the prompt to render + -n, --negative-prompt the negative prompt (default: "") + --ad-model path to a converted YOLOv8 detection model for ADetailer + --ad-prompt ADetailer prompt; empty inherits the main prompt, supports [PROMPT], [SEP], + and [SKIP] + --ad-negative-prompt ADetailer negative prompt; empty inherits the main negative prompt, supports + [PROMPT] and [SEP] + --extra-ad-args extra ADetailer args, key=value list. Supports input_size, confidence, nms, + max_detections, mask_k_largest, mask_min_ratio, mask_max_ratio, dilate_erode, + x_offset, y_offset, mask_mode, merge_masks, invert_mask, mask_blur, + inpaint_padding, inpaint_width, inpaint_height, denoising_strength, steps, + cfg_scale, sample_method, scheduler, sort_by + -i, --init-img path to the init image + --end-img path to the end image, required by flf2v + --mask path to the mask image + --control-image path to control image, control net + --ip-adapter-image path to the IP-Adapter reference image + --control-video path to control video frames, It must be a directory path. The video frames + inside should be stored as images in lexicographical (character) order. For + example, if the control video path is `frames`, the directory contain images + such as 00.png, 01.png, ... etc. + --pm-id-images-dir path to PHOTOMAKER input id images dir + --pm-id-embed-path path to PHOTOMAKER v2 id embed + --pulid-id-embedding path to PuLID id embedding + --hires-upscaler highres fix upscaler, Lanczos, Nearest, Latent, Latent (nearest), Latent + (nearest-exact), Latent (antialiased), Latent (bicubic), Latent (bicubic + antialiased), or a model name under --hires-upscalers-dir (default: Latent) + --extra-sample-args extra sampler/scheduler/guidance args, key=value list. CFG supports + guidance_schedule; APG supports apg_eta, apg_momentum, apg_norm_threshold, + apg_norm_threshold_smoothing; SLG supports slg_uncond; lcm supports + noise_clip_std, noise_scale_start, noise_scale_end; flux supports base_shift, + max_shift; ltx2 supports max_shift, base_shift, stretch, terminal; euler_ge + supports gamma; beta scheduler supports alpha, beta; logit_normal supports + mu, std, logsnr_min, logsnr_max, resolution_aware; llada_image supports + uniform; lms supports lms_max_order, lms_shift, lms_divisions; + noise-injecting samplers support noise_sampler with value iid (default except + for dpm++2m_sde_bt) or brownian_tree; brownian_tree_rng supports cpu + (default), cuda, std_default or sampler_rng + --extra-tiling-args extra VAE tiling args, key=value list. Supported video VAEs accept + temporal_tile_frames/temporal_tile_size (default: 4), temporal_tile_overlap + (default: 1); Wan2.2 TI2V 5B accepts temporal_decode_frames (default: 1) + --ref-image-args Key-value list to set up the way the reference images are processed (empty = + auto-detect from model weigths) + --image-preprocess Image preprocessing rule: + target=init|end|mask|control|ref|ip-adapter|id|control-frame,index=N,mode=aut + o|none|stretch|crop|crop-resize|fit-pad,filter=auto|nearest|nearest-exact|bil + inear|bicubic|lanczos,antialias=auto|true|false,width=W,height=H,anchor=cente + r|top|bottom|left|right,pad_color=#RRGGBB[AA],canny=true|false. Repeat for + multiple rules. + -H, --height image height, in pixel space (default: 512) + -W, --width image width, in pixel space (default: 512) + --steps number of sample steps (default: 20) + --high-noise-steps (high noise) number of sample steps (default: -1 = auto) + --clip-skip ignore last layers of CLIP network; 1 ignores none, 2 ignores one layer + (default: -1). <= 0 represents unspecified, will be 1 for SD1.x, 2 for SD2.x + -b, --batch-count batch count + --qwen-image-layers number of Qwen Image Layered layers; latent/output count is layers + 1 + (default: 3) + --video-frames video frames (default: 1) + --fps fps (default: 24) + --timestep-shift shift timestep for NitroFusion models (default: 0). recommended N for + NitroSD-Realism around 250 and 500 for NitroSD-Vibrant + --upscale-repeats Run the ESRGAN upscaler this many times (default: 1) + --upscale-tile-size tile size for ESRGAN upscaling (default: 128) + --hires-width highres fix target width, 0 to use --hires-scale (default: 0) + --hires-height highres fix target height, 0 to use --hires-scale (default: 0) + --hires-steps highres fix second pass sample steps, 0 to reuse --steps (default: 0) + --hires-upscale-tile-size highres fix upscaler tile size, reserved for model-backed upscalers (default: + 128) + --cfg-scale unconditional guidance scale: (default: 7.0) + --img-cfg-scale image guidance scale for inpaint or image edit models: (default: same as + --cfg-scale) + --guidance distilled guidance scale for models with guidance input (default: 3.5) + --slg-scale skip layer guidance (SLG) scale, only for DiT models: (default: 0). 0 means + disabled, a value of 2.5 is nice for sd3.5 medium + --skip-layer-start SLG enabling point (default: 0.01) + --skip-layer-end SLG disabling point (default: 0.2) + --eta noise multiplier (default: 0 for ddim_trailing, tcd, res_multistep and + res_2s; 1 for euler_a, er_sde, dpm++2s_a, dpm++2m_sde and dpm++2m_sde_bt) + --flow-shift shift value for Flow models like SD3.x or WAN (default: auto) + --high-noise-cfg-scale (high noise) unconditional guidance scale: (default: 7.0) + --high-noise-img-cfg-scale (high noise) image guidance scale for inpaint or image edit models (default: + same as --cfg-scale) + --high-noise-guidance (high noise) distilled guidance scale for models with guidance input + (default: 3.5) + --high-noise-slg-scale (high noise) skip layer guidance (SLG) scale, only for DiT models: (default: + 0) + --high-noise-skip-layer-start (high noise) SLG enabling point (default: 0.01) + --high-noise-skip-layer-end (high noise) SLG disabling point (default: 0.2) + --high-noise-eta (high noise) noise multiplier (default: 0 for ddim_trailing, tcd, + res_multistep and res_2s; 1 for euler_a, er_sde, dpm++2s_a, dpm++2m_sde and + dpm++2m_sde_bt) + --strength strength for noising/unnoising (default: 0.75) + --pm-style-strength + --pulid-id-weight strength of PuLID identity injection + --control-strength strength to apply Control Net (default: 0.9). 1.0 corresponds to full + destruction of information in init image + --ip-adapter-strength strength to apply IP-Adapter (default: 1.0) + --moe-boundary timestep boundary for Wan2.2 MoE model. (default: 0.875). Only enabled if + `--high-noise-steps` is set to -1 + --vace-strength wan vace strength + --vae-tile-overlap tile overlap for vae tiling, in fraction of tile size (default: 0.5) + --hires-scale highres fix scale when target size is not set (default: 2.0) + --hires-denoising-strength highres fix second pass denoising strength (default: 0.7) + --increase-ref-index automatically increase the indices of references images based on the order + they are listed (starting with 1). + --circular enable circular padding on both axes for tileable output + --circularx enable circular padding on x-axis (width) only + --circulary enable circular padding on y-axis (height) only + --disable-image-metadata do not embed generation metadata on image files + --vae-tiling process vae encode and decode in spatial tiles to reduce memory usage + (default: 256x256 image pixels) + --temporal-tiling enable temporal tiling for supported video VAE decode + --hires enable highres fix + -s, --seed RNG seed (default: 42, use random seed for < 0) + --sampling-method sampling method, one of [euler, euler_a, heun, dpm2, dpm++2s_a, dpm++2m, + dpm++2mv2, ipndm, ipndm_v, lcm, ddim_trailing, tcd, res_multistep, res_2s, + er_sde, euler_cfg_pp, euler_a_cfg_pp, euler_ge, dpm++2m_sde, dpm++2m_sde_bt, + lms], default: euler for Flux/SD3/Wan, euler_a otherwise + --high-noise-sampling-method (high noise) sampling method, one of [euler, euler_a, heun, dpm2, dpm++2s_a, + dpm++2m, dpm++2mv2, ipndm, ipndm_v, lcm, ddim_trailing, tcd, res_multistep, + res_2s, er_sde, euler_cfg_pp, euler_a_cfg_pp, euler_ge, dpm++2m_sde, + dpm++2m_sde_bt, lms], default: euler for Flux/SD3/Wan, euler_a otherwise + --scheduler denoiser sigma scheduler, one of [discrete, karras, exponential, ays, gits, + sgm_uniform, simple, smoothstep, kl_optimal, lcm, bong_tangent, ltx2, + logit_normal, flux2, flux, beta, llada_image], alias: normal=discrete, + default: model-specific + --sigmas custom sigma values for the sampler, comma-separated (e.g., + "14.61,7.8,3.5,0.0") or preset: qwen-image-2.1-turbo. + --hires-sigmas custom sigma values for the highres fix second pass, comma-separated (e.g., + "0.85,0.725,0.421875,0.0") or preset: qwen-image-2.1-turbo. + --skip-layers layers to skip for SLG steps (default: [7,8,9]) + --high-noise-skip-layers (high noise) layers to skip for SLG steps (default: [7,8,9]) + -r, --ref-image reference image for Flux Kontext or MiniMax-H3 Ref2VA (can be used multiple + times) + --ref-video MiniMax-H3 Ref2VA reference video frame directory at 24 fps (can be used + multiple times) + --ref-video-audio WAV soundtrack paired by index with --ref-video (can be used multiple times) + --ref-audio standalone WAV reference for MiniMax-H3 Ref2VA (can be used multiple times) + --audio driving audio track (Wan2.2 S2V; can be used once) + --cache-mode caching method: 'easycache' (DiT), 'ucache' (UNET), + 'dbcache'/'taylorseer'/'cache-dit' (DiT block-level), 'spectrum' (UNET/DiT + Chebyshev+Taylor forecasting) + --cache-option named cache params (key=value format, comma-separated). easycache/ucache: + threshold=,start=,end=,decay=,relative=,reset=; dbcache/taylorseer/cache-dit: + Fn=,Bn=,threshold=,warmup=; spectrum: w=,m=,lam=,window=,flex=,warmup=,stop=. + Examples: "threshold=0.25" or "threshold=1.5,reset=0" + --scm-mask SCM steps mask for cache-dit: comma-separated 0/1 (e.g., + "1,1,1,0,0,1,0,0,1,0") - 1=compute, 0=can cache + --scm-policy SCM policy: 'dynamic' (default) or 'static' + --vae-tile-size tile size for vae encode and decode in image pixels, format [W]x[H] or [S] + (default: 256x256; requires --vae-tiling) + --vae-relative-tile-size relative tile size for vae encode and decode, format [W]x[H] or [S]: <=1 is a + dimension fraction, >1 a target tile count (overrides --vae-tile-size; + requires --vae-tiling) + --prompt-file path to the file containing the prompt to render + --negative-prompt-file path to the file containing the negative prompt diff --git a/test/fixtures/sdcpp/required-flags.txt b/test/fixtures/sdcpp/required-flags.txt index 56083e6f..d8276bb9 100644 --- a/test/fixtures/sdcpp/required-flags.txt +++ b/test/fixtures/sdcpp/required-flags.txt @@ -1,6 +1,8 @@ -# Every sd-server flag tauri-plugin-atomic-diffusion emits (src/args.rs). -# scripts/test-local-diffusion.py checks the pinned binary's --help against -# this list so a flag renamed upstream fails loudly before it ships. +# Every sd-server flag the core emits for some build (src/diffusion/args.ts). +# engine-contract.json says which builds get which: --diffusion-fa and +# --diffusion-conv-direct go only to builds before 982, --flash-attn and +# --conv-direct only from 982 on. The live test holds an engine's --help to +# the flags of its build, so a flag renamed upstream fails loudly before it ships. --diffusion-model --vae --vae-format @@ -10,13 +12,12 @@ --t5xxl --llm --llm_vision ---qwen2vl ---clip-on-cpu ---vae-on-cpu --vae-tiling --offload-to-cpu --diffusion-fa --diffusion-conv-direct +--flash-attn +--conv-direct --listen-ip --listen-port --lora-model-dir diff --git a/test/helpers/fake-sd-server.mjs b/test/helpers/fake-sd-server.mjs index e6d1b15f..39fbe3b1 100755 --- a/test/helpers/fake-sd-server.mjs +++ b/test/helpers/fake-sd-server.mjs @@ -7,7 +7,7 @@ * * Driven by argv plus env: * FAKE_SD_MODE ready | hang | exit-early | foreign | queue-full | fail-job | die-mid-job | - * ggml-abort (recovers when `--backend cpu` is in the argv) | + * ggml-abort (recovers when a `--backend` makes the CPU the default device) | * gpu-fault (a Metal address fault in the job's own output, then the job fails; * the process stays up, as the real one does) * FAKE_SD_ONCE_MARKER path; the mode applies only to the first process that creates the file, every @@ -94,7 +94,13 @@ const modes = (env.FAKE_SD_MODES ?? 'img_gen') .map((m) => m.trim()) .filter(Boolean) const vidFormats = env.FAKE_SD_VID_FORMATS ?? 'all' -const onCpu = argv.includes('--backend') && argv[argv.indexOf('--backend') + 1] === 'cpu' +// sd.cpp joins repeated `--backend` values with commas; an entry without `=` is the default device, +// so `--backend te=cpu ... --backend cpu` runs everything on the CPU. +const backendEntries = argv + .flatMap((arg, i) => (arg === '--backend' && i + 1 < argv.length ? [argv[i + 1]] : [])) + .join(',') + .split(',') +const onCpu = backendEntries.some((entry) => entry.trim().toLowerCase() === 'cpu') const effectiveMode = mode === 'ggml-abort' && onCpu ? 'ready' : mode // ── the loader, as sd.cpp prints it with -v ─────────────────────────────────── diff --git a/test/live/README.md b/test/live/README.md index fb2e22e3..fb325cde 100644 --- a/test/live/README.md +++ b/test/live/README.md @@ -84,7 +84,7 @@ Stage 5 providers, each opt-in on its own: The video block of the same file runs when `ATOMIC_LIVE_SD_VIDEO_MODEL` names a video model (LTX-2.3 distilled by default; `ATOMIC_LIVE_SD_VIDEO_VAE`, `ATOMIC_LIVE_SD_AUDIO_VAE`, `ATOMIC_LIVE_SD_VIDEO_LLM`, `ATOMIC_LIVE_SD_EMBEDDINGS_CONNECTORS`; `ATOMIC_LIVE_SD_VIDEO_FAMILY=wan2.2-ti2v-5b` with `ATOMIC_LIVE_SD_VIDEO_T5XXL` for - Wan; `ATOMIC_LIVE_SD_VIDEO_MODE_FLAG=1` also passes `-M vid_gen`): load → a nine-frame clip with parsed step progress, + Wan): load → a nine-frame clip with parsed step progress, the WebM and its sidecar → `/v1/videos` queue, poll and content → a hard cancel → respawn → unload. It prints the engine's capabilities and the clip's numbers, which is the evidence the ADR of 2026-09-23 leaves open. `test/live/diffusion-install.test.ts` takes `ATOMIC_LIVE_SD_MANIFEST` (a conf-shaped sd.cpp manifest, a path or an diff --git a/test/live/diffusion.test.ts b/test/live/diffusion.test.ts index cd1a1e53..e0b6fe79 100644 --- a/test/live/diffusion.test.ts +++ b/test/live/diffusion.test.ts @@ -28,7 +28,6 @@ * ATOMIC_LIVE_SD_VIDEO_LLM=/path/to/gemma-3-12b-it-qat-UD-Q4_K_XL.gguf (LTX; Wan takes ATOMIC_LIVE_SD_VIDEO_T5XXL) * ATOMIC_LIVE_SD_EMBEDDINGS_CONNECTORS=/path/to/connectors.safetensors (LTX-2.3) * ATOMIC_LIVE_SD_VIDEO_FAMILY=ltx-2 (optional; or wan2.2-ti2v-5b) - * ATOMIC_LIVE_SD_VIDEO_MODE_FLAG=1 (optional; also pass -M vid_gen to sd-server) * * The engine tree is copied into the temporary data folder (installs live under ``); the * model files are read where they are. Nothing is written outside the temporary folder. @@ -39,7 +38,7 @@ import { request } from 'node:http' import { join } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { prepareSdcppTree, writeInstallRecord } from '../../src/diffusion/install.js' -import { findSdOption, parseSdHelp } from '../../scripts/lib/sdcpp-surface.mjs' +import { findSdOption, parseSdHelp, sdcppBuildOf, sdFlagsForBuild } from '../../scripts/lib/sdcpp-surface.mjs' import type { SdcppContract } from '../../scripts/lib/sdcpp-surface.mjs' import { CoreClient } from '../../src/client/index.js' import type { CoreEvents, ImageJob, VideoJob } from '../../src/contracts/index.js' @@ -170,7 +169,10 @@ describe.skipIf(!ENABLED)('a real stable-diffusion.cpp engine', () => { const contract = JSON.parse( await readFile(new URL('../fixtures/sdcpp/engine-contract.json', import.meta.url), 'utf8') ) as SdcppContract - const required = contract.flags.filter((f) => f.severity === 'break').map((f) => f.flag) + // The flags the core spells for this build: --flash-attn from 982 on, --diffusion-fa before it. + const required = sdFlagsForBuild(contract, sdcppBuildOf(TAG)) + .filter((f) => f.severity === 'break') + .map((f) => f.flag) const missing = required.filter((flag) => !findSdOption(options, flag)) expect(missing, 'flags the pinned engine no longer knows').toEqual([]) }, 130_000) @@ -355,8 +357,6 @@ describe.skipIf(!VIDEO_ENABLED)('a real stable-diffusion.cpp engine serving vide const dir = join(videoData.layout.diffusion.backendsDir, TAG, 'live') await mkdir(dir, { recursive: true }) await cp(ENGINE, dir, { recursive: true }) - if (process.env['ATOMIC_LIVE_SD_VIDEO_MODE_FLAG'] === '1') - process.env['ATOMIC_DIFFUSION_VID_GEN_MODE_FLAG'] = '1' videoCore = await AtomicCore.create({ dataFolder: videoData.root, controlPort: 0, ...CORE_ENV }) videoClient = new CoreClient({ baseUrl: videoCore.control.url, token: videoCore.controlToken }) for (const name of [