Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Local work: premium preset previews, LM Studio/Unsloth local LLMs, Pixal3D image-to-3D route

Adarshf9457d0477d4
diff --git a/README.md b/README.md
index 1531d372..e636503f 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
**An open-source AI image, video and audio studio — a 1:1 alternative to Higgsfield.**
Use the same frontier paid models Higgsfield uses (Nano Banana Pro, Seedance 2.5, Kling 3.0, Veo 3.1, Seedream 5, GPT Image 2.5, FLUX.3, Gemini Omni, MiniMax, ElevenLabs…, and Higgsfield's own Soul and Cinema Studio) with your own fal.ai / Replicate / Higgsfield key, **or** run the equivalent open-weight workflows on your own GPU through **ComfyUI**. Same studio, same apps, same camera motions — flip one switch.
-- **Assist:** describe the whole job in a chat; the agent picks models, shows the plan and its cost, runs it when you approve, checks the results and chains the next step. Free / Smart / Manual modes, 20 built-in **skills** (SKILL.md playbooks, or upload your own), **projects** with instructions and up to 20 sources (links, files and PDFs, elements, notes), and **memory**. Runs on Claude, a local Ollama model, or an offline planner
+- **Assist:** describe the whole job in a chat; the agent picks models, shows the plan and its cost, runs it when you approve, checks the results and chains the next step. Free / Smart / Manual modes, 20 built-in **skills** (SKILL.md playbooks, or upload your own), **projects** with instructions and up to 20 sources (links, files and PDFs, elements, notes), and **memory**. Runs on Claude, a local model (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server), or an offline planner
- **MCP:** other agents (Claude Code, Claude Desktop, any MCP client) can drive the studio through `/api/mcp`, including whole studio jobs (layers, restyle, dub, faceless episode, ads, captions, Katana; they run as plain pipelines and don't open a studio session yet) and the skills as prompts
- **Create:** Image · Video (text, image, start/end frame, reference images and clips, multi-shot, draft mode) · Edit · **Layers** (split a flat image into editable layers, edit text, regional edits, cropped or positioned zips) · Inpaint & Draw to Edit · Color grading · Camera motions · Effects · Storyboard (and turn it into a film) · **Canvas** (wire prompts, files and models into node workflows; every template in a cloud and an open-source version) · Apps
- **Studios:**
@@ -47,9 +47,14 @@ The mode can also be set with `FUOBE_ENGINE_MODE=both|open|cloud`. Then connect
| A [Higgsfield API](https://console.higgsfield.ai) key | `Higgsfield API key` as `KEY_ID:KEY_SECRET` (or `HIGGSFIELD_API_KEY`, `HF_KEY`, or `HF_API_KEY` + `HF_API_SECRET`) | Soul 2.0 / Soul Cinema / Soul v1 with live presets, Soul ID training, Genjutsu, Cinema Studio 4.0, Marketing Studio, Ads Studio, plus extra routes for Seedance, Kling, Wan, MiniMax… |
| A GPU running ComfyUI | `ComfyUI server URL` (or `COMFYUI_URL`, default `http://127.0.0.1:8188`; `COMFYUI_TOKEN` if it sits behind a proxy) | Every open-source model, app, motion, effect and studio route |
| An Anthropic key | `Anthropic API key` (or `ANTHROPIC_API_KEY`) | The full **Assist** agent (Smart and Manual modes), text steps (translate, write, scripts, ad copy, brand research), prompt **Enhance** and storyboard splitting with Claude |
-| Ollama | `Prompt enhancement` → Ollama (`OLLAMA_URL`, `OLLAMA_MODEL`, default `qwen3:8b`; `FUOBE_ENHANCE_PROVIDER`) | The same text steps and the Assist agent on a local model (tool calling) |
+| [Ollama](https://ollama.com) | **AI helper** → Local model server → Ollama or Automatic (`OLLAMA_URL`, `OLLAMA_MODEL`, default `qwen3:8b`) | The same text steps and the Assist agent on a local model (tool calling) |
+| [LM Studio](https://lmstudio.ai) 0.4 or later | **AI helper** → LM Studio or Automatic (`LMSTUDIO_URL`, default `http://127.0.0.1:1234`; `LMSTUDIO_MODEL`, empty for the loaded model; `LMSTUDIO_API_TOKEN` only when its Require Authentication is on). In LM Studio, start the server (Developer → Start server, or `lms server start`) and download a model (`lms get qwen/qwen3-8b`) | The same on LM Studio. A model that isn't loaded yet is loaded with 16k context (`FUOBE_LLM_CONTEXT`), which Assist's tools need |
+| [Unsloth Studio](https://unsloth.ai/docs/new/studio/install) | **AI helper** → Unsloth Studio or Automatic (`UNSLOTH_URL`, default `http://127.0.0.1:8888`; `UNSLOTH_API_KEY`: an `sk-unsloth-…` key from avatar → Settings → API; `UNSLOTH_MODEL`, empty for the loaded model). Load a model on its Chat page | The same on the model loaded in Unsloth Studio. Its server-side tools (Python, terminal, web search) are always off for Fuobe's calls |
+| Another OpenAI-compatible server (llama.cpp's llama-server, vLLM, Jan…) | **AI helper** → Other (`FUOBE_LLM_URL`, the base URL such as `http://127.0.0.1:8080/v1`; `FUOBE_LLM_MODEL`; `FUOBE_LLM_API_KEY`) | The same on that server |
| AI-Toolkit (ostris) on your GPU | `AI_TOOLKIT_URL` (+ `AI_TOOLKIT_AUTH`, `AI_TOOLKIT_DATASET_DIR`) and `COMFYUI_LORAS_DIR` | Train character and style LoRAs from an element's photos or a moodboard; the result is copied into ComfyUI and used whenever you @mention it |
+**AI helper** picks who writes: Automatic (Claude when a key is set, else a local model, else the offline rewriter), Claude, a local model only, or offline (`FUOBE_ENHANCE_PROVIDER=auto|anthropic|local|none`; the old value `ollama` means `local`). Its local model server is Automatic by default (`FUOBE_LLM_PROVIDER=auto`): the first one that answers with a model, in the order Ollama, LM Studio, Unsloth Studio, then the Other URL. `FUOBE_LLM_PROVIDER=ollama|lmstudio|unsloth|custom` pins one. Settings → AI helper shows what each server answers (its models, whether one is loaded, what's missing) and has a **Test connection** button. The local model shares the GPU with ComfyUI, so a 4–8B model leaves room for generations.
+
Keys are stored in a local SQLite database (`data/fuobe.db`) and never sent to the browser. Generated media is saved under `data/files/`. Fuobe is single-user.
### Self-hosting and security
@@ -69,7 +74,8 @@ claude mcp add --transport http fuobe http://localhost:3000/api/mcp --header "Au
| `FUOBE_DATA_DIR` | Where the database, files and `auth.json` live (default `./data`) |
| `FUOBE_DEMO_MODE` | `auto` (default: demo outputs only when a model's provider isn't connected), `on` or `off` |
| `FUOBE_SKILLS_DIR` | Where Assist's built-in skills are read from (default `./skills`) |
-| `FUOBE_ENGINE_MODE`, `FUOBE_CLOUD_PROVIDER`, `FUOBE_ENHANCE_PROVIDER` | The Settings choices above |
+| `FUOBE_ENGINE_MODE`, `FUOBE_CLOUD_PROVIDER`, `FUOBE_ENHANCE_PROVIDER`, `FUOBE_LLM_PROVIDER` | The Settings choices above |
+| `FUOBE_LLM_CONTEXT` | Tokens of context for the local model (default `16384`): Ollama's `num_ctx`, and the context LM Studio loads a model with. `0` leaves it to the server |
| `OPENAI_API_KEY`, `GEMINI_API_KEY` | Read into Settings; no feature uses them yet |
Uploads up to 200 MB work with sign-in on. Inputs given as URLs are fetched only from public addresses unless `FUOBE_ALLOW_PRIVATE_URLS=1`.
@@ -98,6 +104,10 @@ pnpm dev &
pnpm test:e2e:comfyui http://localhost:3000 # runs the weight-free workflows through the full pipeline (mux, trim, segment, captions, meta-batch), checked with ffprobe when installed
```
+## To do
+
+- [ ] **Chunked uploads, so files over 100 MB work on fuobe.com.** Cloudflare (Free and Pro plans) refuses a request body over 100 MB, but Fuobe accepts 200 MB, so a 100–200 MB upload fails there. Send files over about 90 MB as 50 MB chunks and join them on the server before `saveFile()`: add a chunk endpoint next to `src/app/api/uploads/route.ts` and one client helper for its three callers (`src/components/studio/media-slot.tsx`, `src/lib/api.ts`, and `src/components/shorts/use-source-clip.ts`, which keeps its progress bar). Smaller files upload in one request, as now. See [docs/deploy.md](docs/deploy.md#cloudflare-limits).
+
## Development
```bash
@@ -106,6 +116,8 @@ pnpm build # production build
pnpm gen:catalog # regenerate cloud models, Higgsfield models and presets, LoRA map and icon map from docs/research/*.json
pnpm dev:clean # clear the Turbopack cache if the dev server gets stuck reloading or serves stale CSS
node scripts/gen-demo-3d.mjs # regenerate the demo GLB and turntable (needs ffmpeg)
+node scripts/model3d/finish-glb.mjs --in raw.glb --out web.glb # the server's GLB finish, by hand
+node scripts/model3d/render-turntable.mjs --glb web.glb --out spin.mp4 # the server's CPU turntable (needs ffmpeg and a Playwright Chromium: npx playwright-core install chromium-headless-shell)
```
Browser checks (the app must be running; demo mode is fine; Playwright and Chromium are picked up from the repo, a global install or `$CHROMIUM_PATH`):
@@ -124,12 +136,13 @@ node tests/e2e/assist-flows.mjs [url] # skills, memory, projects, skill
- `docs/ARCHITECTURE.md` — how requests flow from the composer to providers and back, pipelines, live updates, security, each studio's modules
- `docs/research/` — the research this is built on (Higgsfield inventory, studios, image studios, marketing and agents, API; paid model APIs parts 1–3; ComfyUI equivalents parts 1–3; workflow library; Liner UI language)
- `docs/workers/tribe-v2.md` — the optional, non-commercial TRIBE v2 worker contract for the Virality predictor
+- `docs/deploy.md` — how fuobe.com is hosted and auto-deployed from `main` (server files in `deploy/fuobe.com/`)
- `scripts/comfy/` — the pipeline that exports and validates the ComfyUI workflow library
- `skills/` — Assist's built-in skills (`<name>/SKILL.md` with frontmatter: name, title, description, when_to_use, icon, studio, tags, offline hints)
## Tech
-Next.js 16 (App Router, Cache Components) · React 19 · Tailwind CSS v4 · shadcn/ui (Radix) · TanStack Query · SQLite (better-sqlite3) · zod · fal.ai queue API · Replicate predictions API · Higgsfield API · ComfyUI HTTP + WebSocket API · Anthropic SDK (Claude) · Ollama · @xyflow/react (Canvas) · @google/model-viewer + three (3D) · unpdf (PDF text) · cmdk · WebGL · server-sent events · Vitest · Playwright.
+Next.js 16 (App Router, Cache Components) · React 19 · Tailwind CSS v4 · shadcn/ui (Radix) · TanStack Query · SQLite (better-sqlite3) · zod · fal.ai queue API · Replicate predictions API · Higgsfield API · ComfyUI HTTP + WebSocket API · Anthropic SDK (Claude) · Ollama, LM Studio, Unsloth Studio and OpenAI-compatible chat APIs · @xyflow/react (Canvas) · @google/model-viewer + three (3D) · unpdf (PDF text) · cmdk · WebGL · server-sent events · Vitest · Playwright.
## License notes
diff --git a/bin/lib/commands.mjs b/bin/lib/commands.mjs
index ebb6345d..90940e4b 100644
--- a/bin/lib/commands.mjs
+++ b/bin/lib/commands.mjs
@@ -373,6 +373,14 @@ async function status(ctx) {
ctx.print(`Fuobe at ${t.url}${t.urlFrom === "default" ? "" : ` (from ${t.urlFrom})`}`);
ctx.print(`Engine mode: ${s.engineMode} · Demo mode: ${s.demoMode} · Preferred cloud: ${s.cloudProvider}`);
ctx.print(`Providers: ${providers.join(", ")}`);
+ // Older servers don't say which local model server they use.
+ const local = s.llm?.local;
+ if (s.llm) {
+ // The servers it looked at: the pinned one, or all of them in Automatic.
+ const names = (s.llm.detected ?? []).map((d) => d.label);
+ const tried = names.length > 1 ? `${names.slice(0, -1).join(", ")} or ${names.at(-1)}` : (names[0] ?? "Ollama, LM Studio or Unsloth Studio");
+ ctx.print(`Local LLM: ${local ? `${local.label} at ${local.url}${local.model ? ` · ${local.model}` : ""}` : (s.llm.problem ?? `none answering (${tried})`)}`);
+ }
ctx.print(
t.token
? `API token: accepted (from ${t.tokenFrom})`
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 00d08b45..bd6bcb41 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -1,6 +1,6 @@
# Architecture
-Fuobe is a single Next.js 16 app. The browser talks only to Fuobe's own API; the server talks to providers (fal.ai, Replicate, Higgsfield, ComfyUI, and Claude or Ollama for text) and stores every input and output locally, so the library never depends on a provider's expiring URLs.
+Fuobe is a single Next.js 16 app. The browser talks only to Fuobe's own API; the server talks to providers (fal.ai, Replicate, Higgsfield, ComfyUI, and Claude or a local LLM server for text: Ollama, LM Studio, Unsloth Studio or any OpenAI-compatible one) and stores every input and output locally, so the library never depends on a provider's expiring URLs.
```
proxy.ts: hostAllowed() (no password set) → crossSite() → sign-in (session cookie or API token)
@@ -48,7 +48,7 @@ Feed, Library, studios (React Query caches patched by id; polls every 10 s while
| `higgsfield-models.generated.ts` | Higgsfield-only models (Soul, Genjutsu, Cinema Studio, Marketing Studio, Ads Studio…) and extra Higgsfield routes for models also on fal. **Generated** by `scripts/gen-higgsfield-models.py` from `docs/research/higgsfield-api.json` |
| `higgsfield-presets.generated.ts` | 106 Soul + 33 Soul 2.0 presets (ids, categories, descriptions), the 14 Photodump / Instadump packs and the 6 Fashion Factory templates. **Generated** by `scripts/gen-higgsfield-presets.py` from `higgsfield-image-studios.json`; the fallback for the style picker |
| `models.ts` | Open-source models (ComfyUI workflow ids), fal utility models (Join clips, and the hidden Extract frame, Crop to size, Mix voice and music, Level audio, Forced Alignment), the browser-only models (`local` provider: Color Grade, Ad compositor) + the generated cloud lists (whose hidden chain helpers include Trim video, Add soundtrack, Voice timeline and Extract soundtrack) |
-| `llm-models.ts` | `text-llm` (cloud: Claude, else Ollama) and `oss-text-llm` (open: Ollama only), kind `text`, ops `translate` and `write` |
+| `llm-models.ts` | `text-llm` (cloud: Claude, else a local model) and `oss-text-llm` (open: a local model only, route endpoint `ollama`), kind `text`, ops `translate` and `write` |
| `elements.ts` | Elements (character / location / prop / style / voice), `@handle` parsing and `applyMentions` |
| `sketch.ts` | `applySketch` (masks and drawings → the right operation and inputs) |
| `storyboard.ts` | Storyboard models per engine, scene splitting and frame prompts |
@@ -119,9 +119,24 @@ At launch the runner fills the slots (`slotsFor` pads short chains, `chainValue`
## LLM provider (`src/server/providers/llm.ts`)
-Text steps (`translate`, `write`) run inside the server and are polled like any job; cancel aborts the call and a restart fails the job as "Interrupted" (retryable). `llmBackends(route)` lists the backends in order: Claude (claude-opus-5-5, low effort, server-side fallback) when an Anthropic key is set and Prompt enhancement is Claude, or Auto on an install that isn't open-only; then Ollama when it answers, unless Prompt enhancement is pinned to Claude. Claude errors fall back to the next backend; endpoint `ollama` (`oss-text-llm`) never uses Claude; Prompt enhancement → Offline rewriter (`none`) turns text steps off. The first check for a new Ollama URL is a blocking worker-thread probe (`probeOllama`), later checks refresh a 15 s cache in the background. A text step on Ollama costs 0.
+Text steps (`translate`, `write`) run inside the server and are polled like any job; cancel aborts the call and a restart fails the job as "Interrupted" (retryable). `llmBackends(route)` lists the backends in order: Claude (claude-opus-5-5, low effort, server-side fallback) when an Anthropic key is set and AI helper is Claude, or Automatic on an install that isn't open-only; then the local model (`local`, see below) when a local server is ready, unless AI helper is pinned to Claude; for an open translation with none, ComfyUI's Qwen3.5 4B. Claude errors fall back to the next backend; endpoint `ollama` (`oss-text-llm`: the id predates the other servers and means "local only") never uses Claude; AI helper → Offline rewriter (`none`) turns text steps off. The job keeps the local server it started on (`payload.local`), polls as "Writing with LM Studio", and a text step on a local model costs 0. The provider's label is a getter, `Claude or <server>` (`llmLabel()`), so chain errors and `/api/status` name the server in use. `llmMissing()` adds the server's own reason (a key, no model loaded). `probeOllama` is kept as an alias of `probeLocal`.
-`translateCues()` translates JSON cue lists, SRT and WebVTT (`src/lib/cues.ts`) in numbered batches of 30 (multi-line cues kept together); a batch that comes back merged or short is redone in pieces of 10, then cue by cue through a pool (1 request in flight on Ollama, 4 on Claude). The output keeps `meta.cues`. `write` uses `params.extra.system` when given. Studios that need free text (brand research, the AI Director, storyboard splitting, ad copy, Click to Ad scripts) call `llmText()` in `src/server/enhance.ts`, with offline fallbacks. Faceless and Explainer names, topics and scripts go through the llm provider itself (`askLlm()` in `src/server/faceless.ts` submits and polls a `text-llm` / `oss-text-llm` job), so they follow the episode's engine.
+`translateCues()` translates JSON cue lists, SRT and WebVTT (`src/lib/cues.ts`) in numbered batches of 30 (multi-line cues kept together); a batch that comes back merged or short is redone in pieces of 10, then cue by cue through a pool (1 request in flight on a local model, 4 on Claude). The output keeps `meta.cues`. `write` uses `params.extra.system` when given. Studios that need free text (brand research, the AI Director, storyboard splitting, ad copy, Click to Ad scripts) call `llmText(system, user, { json?, timeoutMs? })` in `src/server/enhance.ts`, with offline fallbacks (60 s, or 3 minutes while the local model still has to load). Faceless and Explainer names, topics and scripts go through the llm provider itself (`askLlm()` in `src/server/faceless.ts` submits and polls a `text-llm` / `oss-text-llm` job, `extra.json` carrying the schema), so they follow the episode's engine. The callers that want JSON pass a JSON Schema next to their prompt (brand kit, manual kit and product facts in `brand.ts`, ad copy with exactly `count` ads and the brand chat in `ads.ts`, the Director's answer with its slug enums, Faceless topics, scripts and pictures in `lib/catalog/faceless.ts`, and a root array of exactly n frames for storyboards). Claude ignores it; the parsers stay tolerant of prose and fences either way.
+
+## Local LLM servers (`src/server/llm/`)
+
+One layer for every local model: `ollama` (its own `/api/chat`), `lmstudio`, `unsloth` and `custom` (any OpenAI-compatible server: llama.cpp's llama-server, vLLM, Jan…), the last three on `POST {base}/chat/completions`. Text steps, `llmText()` and the Assist agent all call `chatLocal(ready, request)`; nothing streams.
+
+| file | what |
+|---|---|
+| `servers.ts` | Settings → `LocalServer`s: `localServers()` is the pinned one (`llmProvider`) or, in Automatic, Ollama, LM Studio, Unsloth Studio and the custom URL when set, in that order. URLs lose a pasted `/v1`; a custom URL is an OpenAI base URL (a bare host gets `/v1`). `aiHelper()` reads the old `enhanceProvider` value `ollama` as `local`. LM Studio's token also comes from `LM_API_TOKEN`, Unsloth's key from `UNSLOTH_STUDIO_AUTH_TOKEN` |
+| `probe.ts` | Each server is asked with GETs sent at once (1.5 s): Ollama `/api/tags`; LM Studio `/api/v1/models` (loaded copies, context, `trained_for_tool_use`, reasoning) and `/v1/models` for versions before 0.4; Unsloth `/api/liveness` (its `service` must be "Unsloth UI Backend": Jupyter also likes :8888) and `/v1/models` (rows with a `task` are speech or image models); custom `{base}/models`. Answers are cached 15 s per kind, URL and key hash; `interpret()` turns them into a `LocalStatus` (up, auth, chat models without embeddings, the model a call uses, `loaded`, `context`, `problem` in the user's words, `warning`) with the current Settings, so a new model name needs no new probe. The blocking first look (`refreshSync`) runs every GET in one worker thread and reads the answers with `receiveMessageOnPort` |
+| `index.ts` | `probeLocal()`, `activeLocal()` (async) and `localReady()` (sync, for routing: the first look at a server waits, later looks refresh in the background) return the first ready server. `chatLocal()` loads an LM Studio model that isn't loaded yet with `llmContext` (`POST /api/v1/models/load`, shared by concurrent calls; the chat endpoint can't set the context and LM Studio's default is 4k–8k), sends the call with the request's signal and timeout, asks again without `response_format` when a server rejects structured output, and reads tool calls written as text. `reloadLmStudio()` unloads and reloads with the context; `testLocal()` times a tiny call; `localSummary()` feeds `/api/status` |
+| `wire.ts` | Pure request builders and parsers. Ollama: `think:false` for one-shot text, `format` (a schema, or `"json"`), `options.num_ctx`. OpenAI: string tool arguments, `tool_call_id` results, `response_format` json_schema (LM Studio without `strict`; `json_object` for "any object" except on LM Studio), Unsloth's `enable_tools:false` on every call and `enable_thinking:false` for one-shot text, and no `model` for Unsloth unless one is picked (its loaded model answers). Answers lose `<think>` blocks (also a lone closing tag, or a thought cut off); `reasoning_content` / `reasoning` only mark `thought`. Tool calls get Fuobe's own nine-character ids |
+| `messages.ts` | `toChatMessages()`: Assist's stored history for a local model. One system message first; for the OpenAI kinds a mid-chat context update joins the user's turn ("Context update from Fuobe (not the user):"), user turns in a row merge, and tool ids become nine letters and digits (a stable hash), as strict templates (Gemma, Mistral, some Qwen ones) need; Ollama keeps its old shape. `healToolCalls()` reads `<tool_call>{…}</tool_call>`, LM Studio's `[TOOL_REQUEST]{…}[END_TOOL_REQUEST]` and a reply that is only the call's JSON, for the offered tools only |
+| `errors.ts` | Failed calls in words that say what to do: start the server (the command for each), add or check the key (where each server makes them), download or load a model, reload with more context, or free GPU memory. `emptyReply()` says when a model spent its whole reply thinking |
+
+`GET /api/llm` (`?refresh=1` asks again) lists every server's status for Settings → AI helper, without keys; `POST /api/llm` runs `{action: "test", kind?}` or `{action: "load", model?}` (LM Studio reload). `GET /api/status` adds an `llm` block: the helper, whether Claude takes text steps, the pinned server, the local server in use (kind, label, URL, model, loaded, context, warning), the reason when none can run, and what each candidate answered. `fuobe status` prints it as "Local LLM: LM Studio at … · model".
## Live updates (`src/server/live.ts`, `src/lib/api.ts`)
@@ -176,12 +191,12 @@ A `trainings` row per job, polled by the same runner. Higgsfield Soul ID returns
## Assist agent (`src/server/assist/`)
-A manual tool-use loop over Claude (adaptive thinking with `block_binding` drop-block, betas `thinking-binding-controls-2026-08-01` and `server-side-fallback-2026-07-01` (not for Haiku), top-level `cache_control` and two cached system blocks, streamed with `client.beta.messages.stream(...).finalMessage()`, `max_tokens` 32k or 64k at Extra / Max effort). Modes: **Free** (Ollama, or the offline planner), **Smart** (Claude, needs a key), **Manual** (pick claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5 or claude-fable-5-1 and the effort). `resolveAgent()` picks one per chat.
+A manual tool-use loop over Claude (adaptive thinking with `block_binding` drop-block, betas `thinking-binding-controls-2026-08-01` and `server-side-fallback-2026-07-01` (not for Haiku), top-level `cache_control` and two cached system blocks, streamed with `client.beta.messages.stream(...).finalMessage()`, `max_tokens` 32k or 64k at Extra / Max effort). Modes: **Free** (a local model, or the offline planner), **Smart** (Claude, needs a key), **Manual** (pick claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5 or claude-fable-5-1 and the effort, or one of the local server's models). `resolveAgent()` picks one per chat. The agent ids are `claude`, `local` and `offline`; chats and browsers that saved the old `ollama` read as `local` (`normalizeAgent()`, the `ModeChoice` schema).
- **Context.** Each chat's context (date, engine, approval mode, project, sources, memory, skills index, active skills) is built once and frozen in `assist_thread_state`; later changes arrive as role `system` "Context update" messages, saved only after a reply succeeds, so preserved thinking stays valid.
- **Tools** (`tools.ts`, `context-tools.ts`, `studio-tools.ts`): `search_models` (kinds image, video, audio, text, model3d), `list_elements`, `list_recent`, `check_generations` (text inline, meta, images attached), `generate` (with `after`: the call becomes one `createPipeline`; not `strict`, zod-validated), `create_storyboard` (the only `strict` tool), `list_skills`, `load_skill`, `remember` (asks first), `read_source`, the studio tools `split_layers`, `restyle_footage`, `dub_video`, `faceless_episode`, `create_ads`, `add_captions`, and `katana`. Gated calls stop the loop with an approval card priced by `previewGeneration`; `PlannedJob.atomic` marks a pipeline's steps and `planRunnable()` keeps Run off while any step has an error. `answerApproval` claims the thread before its first await.
- **Studio tools** resolve through `STUDIO_ROUTES`, a registry a studio module can fill; while an entry is empty (all of them today) the tool builds the same job as a `createPipeline` of catalog models on either engine.
-- History is stored append-only exactly as the API returned it; local images are kept as URLs and converted to base64 per request. The same loop runs on Ollama's tool calling, or with no LLM on a rule-based planner (still → animate, N-shot films, N portraits, translations, skill hints, "remember that…").
+- History is stored append-only exactly as the API returned it; local images are kept as URLs and converted to base64 per request. The same loop runs on a local model's tool calling (`local` in `agent.ts`: the history through `toChatMessages()`, the answer back as `tool_use` blocks; a picked model the server doesn't list gives way to its default), or with no LLM on a rule-based planner (still → animate, N-shot films, N portraits, translations, skill hints, "remember that…").
## MCP server (`src/server/mcp.ts`, `/api/mcp`)
@@ -219,9 +234,9 @@ Liner-inspired shell (pale frame, rounded inset sheet, 13px sidebar rows, serif
- **Studio pages** render `<Studio config>` (`src/components/studio/studio.tsx`), a server component that passes `studioCatalog(config)` from `src/lib/studio-catalog.ts`: the studio's models without provider field maps. Inside, `CatalogProvider` / `useCatalog()` resolve models; `loadFullCatalog()` imports `@/lib/catalog` lazily for motions, effects, `?preset=` and unknown ids. Client components under `studio/` must not import `@/lib/catalog` or `@/lib/studios`. `StudioPage` renders the same tree in the static shell and after hydration; hand-off params merge into the draft with `mergeHandoff`. `StudioConfig` (`studio-context.tsx`) gained `pickerOps`, `anyOf`, `signature` and `extraModels`.
- **Hubs** (Audio, Video tools, Upscale) have one prerendered path per mode (`src/lib/hubs.ts`, `ModeSwitchStudio` in `mode-switch-studio.tsx`, `[mode]/page.tsx`); old `?mode=` links redirect in `next.config.ts`.
- **Composer** pieces: pure logic in `src/lib/composer.ts` (summary, blockers, `onImageChange`, `fitAttachments`, `firstMissingSlot`), `attachments.ts` (`useAttach`, `useUploadReaper`), `settings-panel.tsx`, `model-picker.tsx` (cmdk), `attach-menu.tsx`, `preset-chips.tsx` (lazy), `radio-keys.ts`.
-- **Galleries** get slim cards (`src/lib/preset-cards.ts`) with procedural previews (`preset-preview.tsx`, `move-glyphs.ts`, `preview-playback.ts`).
+- **Galleries** get slim cards (`src/lib/preset-cards.ts`, built on the server by `toPresetCard()` in `preset-card-data.ts`). A preset with rendered media carries only its hash (from `src/lib/catalog/preview-media.generated.json`, which only `preset-card-data.ts` reads so that client chunks don't carry it; file names in `src/lib/preview-media.ts`): `preview-media.tsx` shows the AVIF/WebP poster and mounts the muted loop only while it plays. The others, and any card whose files don't load, get procedural previews (`preset-preview.tsx`, `move-glyphs.ts`). `preview-playback.ts` plays one at a time: hover after a short rest, on phones the centred card once scrolling stops (not with Save-Data or on 2G).
- Stand-alone views: color grading (`color-grade-view.tsx`, `src/lib/grade.ts`), storyboard, elements + train dialog, library (`library-view.tsx` + `components/library/*`), Assist, and the studios above.
## Generators (`scripts/`)
-`pnpm gen:catalog` runs `gen-cloud-models.py`, `gen-higgsfield-models.py`, `gen-higgsfield-presets.py`, `gen-oss-loras.py` and the icon map. Each reads a research JSON in `docs/research/` and writes a `*.generated.ts` file; the catalog integrity tests catch broken references. `gen-preview-scenes.mjs` draws the gallery preview stills (`public/samples/previews/`), `gen-demo-3d.mjs` the demo GLB and turntable (needs ffmpeg).
+`pnpm gen:catalog` runs `gen-cloud-models.py`, `gen-higgsfield-models.py`, `gen-higgsfield-presets.py`, `gen-oss-loras.py` and the icon map. Each reads a research JSON in `docs/research/` and writes a `*.generated.ts` file; the catalog integrity tests catch broken references. `gen-preview-scenes.mjs` draws the gallery preview stills (`public/samples/previews/`), `gen-demo-3d.mjs` the demo GLB and turntable (needs ffmpeg). `build-previews.mjs --masters <dir>` turns rendered masters (kept outside the repo) into the preset cards' posters and loops in `public/previews/` plus their manifest (needs ffmpeg; unchanged masters are skipped).
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 83377bc3..5b39aa15 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -30,9 +30,9 @@ Checks on the merged branch `claude/fuobe-parity-3` (commit c522288):
| Live updates | ✅ in dev and production: a 3.5 s demo image shows 3.8 s after the POST (was 4.6–5.2 s with polling). One stream per browser, shared by tabs (Web Locks + BroadcastChannel) |
| Runner and security fixes | ✅ each with a regression test: provider timeouts (45 min running, 4 h queued) with poll-before-timeout, cancel during submit, boot-time runner, interrupted-submit sweep, demo/real mix refused, cross-site writes refused, Host allowlist on password-less installs, SSRF-safe remote fetch, login throttle, safe `?next=` redirect, matcher keeping only root SVGs public. The sign-in proxy's body limit is raised to 210 MB so 200 MB uploads pass; that is a config setting with no test (a 15 MB upload was checked live) |
| Demo-mode browser passes (each package branch, before the merge; headless Chromium, 1440 and 390 px, light and dark) | ✅ Layers: `tests/e2e/layers.mjs` (5 checks) plus scratch flows (Angles, Edit text, geometry, full-detail export, Compare after Expand, failures). Shorts + Mixed Media: 40 checks (one session per double-click, crop note, take picker keys, retry). Image studios: Photodump retry inside its batch, Fashion retry, signature routing and Reuse, `?create=1`, Save as character once. Marketing: Click to Ad kit progress and brand kit, @mentions, grid order, baked formats, auto-composited open posters. Faceless: channel in 678 ms, topics, script review autosave, render to the end, timeline change + Undo, delete stops 8 steps, Explainer 30 s render. av-tools: 112 page loads (14 pages × both engines × 2 widths × 2 themes), dub review flush, Katana cuts, captions per burner. Assist: 51 checks plus `tests/e2e/assist-flows.mjs` 6/6. Canvas: `tests/e2e/canvas-smoke.mjs` incl. 60 nodes at 19 ms keystroke → paint. Cinema: `tests/e2e/cinema-shortcuts.mjs`. Composer: `tests/e2e/composer-flows.mjs`. Shell: `tests/e2e/shell.mjs`. Phone layout: `tests/e2e/no-horizontal-scroll.mjs` fit 55 routes in light and dark |
-| LLM text steps (translate, write) | 🟢 tested against a stand-in Ollama server and a stubbed Claude API. No live Claude or Ollama run |
+| LLM text steps (translate, write) | 🟢 tested against stand-in Ollama, LM Studio, Unsloth Studio and llama-server servers (`tests/llm.test.ts`, `tests/local-llm.test.ts`) and a stubbed Claude API. No live Claude or local-model run: this machine has LM Studio 0.4.18 with no chat model downloaded and an Unsloth Studio whose Python environment needs a repair |
| Assist on Claude | 🟢 the streamed request (adaptive thinking, betas, cached system blocks, max_tokens per effort) is built through the SDK against an SSE fake. **No live Claude call yet**: needs an Anthropic key |
-| Assist on Ollama | 🟢 tested against a fake Ollama server (round 2). Model downloads aren't reachable from this environment |
+| Assist on a local model | 🟢 tested against a fake Ollama server (round 2) and a fake LM Studio (a tool call and its result under the same id). No live local model has run it yet |
| Cloud providers (fal / Replicate / Higgsfield) | 🟢 156 fal / Replicate / Higgsfield models (157 cloud models with the Claude text model, plus 10 hidden helpers used by chains) built from the providers' schemas; structured outputs tested on stubbed responses. **No live paid run yet** |
| MCP server | ✅ 1.1.0 tools and prompts by unit tests; the round-2 run with the official MCP Inspector CLI (initialize, tools/list, estimate_cost, generate, check_generations) still applies |
| AI-Toolkit training | 🟢 the job flow ran end to end against a fake AI-Toolkit job API (round 2); the new style-LoRA preset (moodboards) by unit tests. No real training run: it needs a GPU |
@@ -64,7 +64,7 @@ Model names are the defaults first, then the alternatives. "Demo" outputs are la
| Cinema Studio Extend (forward / backward) and Edit | 🟡 | Extend: Seedance 2.5 extension. Backward ("prequel"): extract frame → edit a still → start/end-frame clip. Edit: Seedance 2.5 edit (Kling O3 without a Higgsfield key) | Extend forward with Wan 2.2 Fun VACE extend; the prequel the same way on Wan 2.2; edit with Wan 2.2 Fun VACE restyle | The prequel is a 3-step approximation. Cinema Studio 4.0 is capped at 720p on the public API |
| Cinema Studio image mode and grid | 🟢 | Camera stills (camera, lens, focal length required) on Nano Banana Pro, Seedream 5.0 Pro, Soul Cinema; grids 2×2 / 3×3 / 4×4 (freeform, zooms, shots, next / previous shots) as one sheet | Z-Image Turbo / Qwen-Image stills; Z-Image Turbo · Grid sheet | The sheet is cut into tiles in the browser and stored as uploads |
| Cinema Studio 3D scene / recomposition | ⬜ | — | — | |
-| Cinema AI Director + Project Brief | 🟢 | Claude | Ollama, or an offline storyboard writer | Writes prompts and shot breakdowns into the prompt bar, answers craft questions; never starts a generation. The brief is prepended to every prompt |
+| Cinema AI Director + Project Brief | 🟢 | Claude | A local model (Ollama, LM Studio, Unsloth Studio…), or an offline storyboard writer | Writes prompts and shot breakdowns into the prompt bar, answers craft questions; never starts a generation. The brief is prepended to every prompt |
| Genjutsu (motion transfer, object swap, restyle) | 🟢 cloud · ⬜ open | Higgsfield Genjutsu models with their look picker | — (Motion control and Shorts restyle on Wan are the closest) | Genjutsu Restyle needs a look; the list comes live from Higgsfield |
| Motion Control | 🟢 | Kling 3.0 Motion Control, Genjutsu Motion Transfer | Wan Animate 2, Wan 2.2 Fun Control | `/motion-control` |
| Edit Video | 🟢 | Kling O3 / O1, Kling O3 4K Edit, Gemini Omni Flash 1.1, Seedance 2.5, Wan 2.7, Luma Ray 3.2, FLUX.3 Video, Happy Horse Video Edit, Lucy Edit Pro, Runway Aleph 2, Grok Imagine Video Edit, LTX 2.3 Reference Restyle, Genjutsu Object Swap / Restyle | Wan 2.2 Fun Control, Z-Image Mixed Media | `/video-edit`. Wan 2.2 Fun VACE restyle is a hidden model used by Shorts Studio and Cinema Studio's Edit, not offered here |
@@ -90,7 +90,7 @@ Model names are the defaults first, then the alternatives. "Demo" outputs are la
| Join clips, match colours of a video (Color Palette) | ✅ open · 🟢 cloud (join only) | fal FFmpeg merge; there is no cloud video colour match (the Match Colors app re-grades images with Nano Banana Pro) | ComfyUI concat and palette transfer, both run for real on CPU | Video tools tabs |
| Trim video | ✅ open · 🟢 cloud | fal `trim-video` | Trim Video (core nodes, keeps the audio) | Video tools → Trim: filmstrip + in/out picker. Ran on CPU through the production build |
| Captions (transcribe, edit, burn in) | ✅ open burn-in and cue editing · 🟢 transcription and cloud burn-in | Transcribe: ElevenLabs Scribe v2 (also Wizper, Whisper). Burn: VEED Subtitles (your edited lines as SRT) or Auto Subtitle (quick karaoke, ignores edits) | Transcribe: Qwen3-ASR 0.6B + ForcedAligner. Burn: Fuobe's chunked core-node burn-in (`oss-captions-burnin`); Whisper captions with `NC_PACKS=1` | Video tools → Captions: cue editor (text, timing, split / merge / insert / remove, undo), import .srt / .vtt, 6 styles incl. karaoke with a live preview, export .srt / .vtt. Each burner shows only the controls it supports |
-| Image to 3D / product spin | 🟢 | Hunyuan3D 3.1 Pro (default) / Rapid, TRELLIS.2, Tripo H3.1, Meshy 7.1 | TRELLIS.2 (textured GLB + turntable MP4, MIT), Hunyuan3D 2.1 (shape only, territory-restricted licence) | `/image-to-3d` and an app: orbitable GLB viewer, downloads, turntable (TRELLIS.2's, or recorded in the browser for mesh-only models), "Animate the spin" |
+| Image to 3D / product spin | 🟢 | Hunyuan3D 3.1 Pro (default) / Rapid, TRELLIS.2, Tripo H3.1, Meshy 7.1 | Pixal3D (default: MoGe-2 camera, ~250k-triangle textured GLB), TRELLIS.2 (the fallback, MIT), Hunyuan3D 2.1 (shape only, territory-restricted licence). Before the job shows as done the server finishes each GLB in about a second (`src/server/model3d-finish.ts`: roughness floor by material, pivot at the bottom, meshopt + WebP web GLB); after it, one at a time and at low priority, it renders a 96-frame 24 fps turntable on the CPU when Chromium and ffmpeg are there, and adds it to the result (the card shows its progress) | `/image-to-3d` and an app: cards play the turntable, the orbitable viewer (web GLB, meshopt decoder from `/vendor`) loads only when opened, downloads (the raw GLB), turntable (the server's, or recorded in the browser: 96 frames, 24 fps, WebCodecs), "Animate the spin" |
| Try-On, Angles, Product Shot apps | 🟢 | FASHN Try-On 1.6 (also Google, Leffa); Qwen Multiple Angles (rotate / tilt / zoom); Bria Product Shot | FLUX.2 [klein] 4B + try-on LoRA; Qwen-Image-Edit 2511 + Multiple-Angles LoRA; Qwen-Image-Edit 2509 + White_to_Scene LoRA | The old approximation notes are gone; the notes now say what the open route runs. Try-on needs the person and the garment |
| Relight, Skin Enhancer, Headshots, Packshot, Face/Character Swap, Transitions… | 🟢 | 123 apps: 121 on both engines, 2 open-only | Relight LoRA, ReActor, Qwen-Image-Edit… | Match Lighting, Match Colors, Hook Frame (formerly the Virality Predictor app; its old `/apps/app-virality-predictor` URL now redirects to `/virality`) |
| Approximated apps | 🟡 | — | — | 17 apps are marked as approximations on their page (e.g. one silent clip where Higgsfield beat-matches several), out of 41 with a parity note (what the Fuobe or open version does differently) |
@@ -113,16 +113,16 @@ Model names are the defaults first, then the alternatives. "Demo" outputs are la
| Music | 🟢 | Sonilo Music 1.1 (default, Higgsfield's model), Lyria 3 / Pro, MiniMax Music 2.5, Stable Audio 3 Music, Stable Audio 2.5, Mureka 9.5, ElevenLabs Music | ACE-Step 1.5 | Audio → Music |
| Sound for a video | 🟢 | Mirelo SFX 2.0 for video (default), MMAudio | HunyuanVideo-Foley fed the clip's frames (default; as long as the clip, ≤30 s), MMAudio | Audio → Sound for video. HunyuanVideo-Foley's licence excludes the EU, UK and South Korea |
| Transcription and voice separation | 🟢 | ElevenLabs Scribe v2, Wizper, Whisper; Demucs stems, ElevenLabs Voice Isolation | Qwen3-ASR; MelBand RoFormer + Qwen3-ASR | Text results carry timed cues (saved as .srt); stems carry `meta.stem`. Used by captions, dubbing and Faceless |
-| Text steps (translate, write) | 🟢 | Claude (`text-llm`) | A local model on Ollama (`oss-text-llm`, never calls Claude) | Translations keep the cue timing (numbered batches of 30, then 10, then line by line). Settings → Prompt enhancement → Offline rewriter (`FUOBE_ENHANCE_PROVIDER=none`) turns text steps off |
+| Text steps (translate, write) | 🟢 | Claude (`text-llm`) | A local model on Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server (`oss-text-llm`, never calls Claude) | Translations keep the cue timing (numbered batches of 30, then 10, then line by line). Settings → AI helper → Offline rewriter (`FUOBE_ENHANCE_PROVIDER=none`) turns text steps off |
### Studios & marketing
| Higgsfield feature | Fuobe | Cloud route | Open-source route | Notes |
|---|---|---|---|---|
-| Brand kit + products | 🟢 | Website research needs no model; Claude fills the soft fields (tone, audience, selling points) | Ollama, or offline heuristics | Reads HTML meta, OpenGraph, JSON-LD, Shopify `/products.json`, CSS colours, Google fonts, logo, hero images and socials through the SSRF-safe fetch; 14 rotating research labels, Cancel / Retry. Manual path with k-means colours. Products from a link or an upload. The scraper ran against local fixture shops, not real sites |
+| Brand kit + products | 🟢 | Website research needs no model; Claude fills the soft fields (tone, audience, selling points) | A local model, or offline heuristics | Reads HTML meta, OpenGraph, JSON-LD, Shopify `/products.json`, CSS colours, Google fonts, logo, hero images and socials through the SSRF-safe fetch; 14 rotating research labels, Cancel / Retry. Manual path with k-means colours. Products from a link or an upload. The scraper ran against local fixture shops, not real sites |
| Marketing Studio | 🟢 | Per format: Bria Product Shot / Nano Banana Pro / GPT Image 2.5 / Product Photography (product shots), GPT Image 2.5 / Ideogram 4.5 / 3.0 / Recraft V4.1 (ads, posters, listings), Marketing Studio Image (Higgsfield, with a key), Seedance 2.5 / Kling O3 / Gemini Omni (motion), OmniHuman 2 / Kling Avatar (UGC). UGC chain: ElevenLabs v4 → Nano Banana Pro still → OmniHuman 2 presenter → Auto Subtitle → Seedance 2.5 hook and b-roll → joined | Qwen-Image / Qwen-Image-Edit stills (words set in the browser), Wan 2.2 Lightning motion; UGC: Chatterbox (voice sample needed) → Qwen-Image-Edit → InfiniteTalk → caption burn-in → joins that keep the voice | `/marketing`: 84 Fuobe templates in 11 formats with procedural previews, 9 hooks and 14 settings, product / avatar / reference slots, brand kit chip, live price, Run again. Higgsfield's library has 1,074 templates; Fuobe ships its own set |
-| Click to Ad / Link to Video Ad | 🟢 | Same UGC models, or product-only shots; 9:16, ≤12 s, voiceover and captions | Same open UGC chain | `/marketing/click-to-ad`: link → "Building your product kit" → 10 styles → script (Claude, Ollama or an offline writer within the word budget). The product joins its site's brand kit, so logo and colours persist. The two old parity apps now open this flow. No logo end card in the video |
-| Ads Studio | 🟢 | Higgsfield Ads Studio one-shot (with a key), or Fuobe: Claude copy (angle, headline, body, CTA) + Nano Banana Pro visual + compositing in the browser | Qwen-Image-Edit / Qwen-Image visual + the same compositing; Ollama or rule-based copy | `/ads`, `/ads/[brandId]`: brands, up to 10 products × up to 20 ads, 1:1 / 4:5 / 9:16 with logo, colours and Google fonts, editor, Download all (zip built in the browser), brand chat with @product mentions and priced proposals |
+| Click to Ad / Link to Video Ad | 🟢 | Same UGC models, or product-only shots; 9:16, ≤12 s, voiceover and captions | Same open UGC chain | `/marketing/click-to-ad`: link → "Building your product kit" → 10 styles → script (Claude, a local model or an offline writer within the word budget). The product joins its site's brand kit, so logo and colours persist. The two old parity apps now open this flow. No logo end card in the video |
+| Ads Studio | 🟢 | Higgsfield Ads Studio one-shot (with a key), or Fuobe: Claude copy (angle, headline, body, CTA) + Nano Banana Pro visual + compositing in the browser | Qwen-Image-Edit / Qwen-Image visual + the same compositing; local-model or rule-based copy | `/ads`, `/ads/[brandId]`: brands, up to 10 products × up to 20 ads, 1:1 / 4:5 / 9:16 with logo, colours and Google fonts, editor, Download all (zip built in the browser), brand chat with @product mentions and priced proposals |
| Ad Multiplier | 🟢 | Seedance 2.5 edit (Higgsfield), Kling O3 edit, Gemini Omni Flash. Hook / CTA: first or last frame → image-to-video → joined around the original | Wan 2.2 Animate + the original sound muxed back; hook / CTA on Wan 2.2 Lightning, joined keeping the reference's sound | `/ads/multiplier`: 4–30 s reference, up to 20 @image_N, Prompt or Change hook / Change CTA, 480p / 720p / 1080p (open ≤720p), 1–4 versions, live estimate |
| Faceless Studio | 🟢 | Nano Banana Pro stills, Gemini Omni Flash clips (Seedance 2.5 in Advanced), ElevenLabs v4 / Multilingual v2 or a Chatterbox clone, ElevenLabs forced alignment, Sonilo music levelled to −28 LUFS and mixed by fal FFmpeg compose, Auto Subtitle; Upscale to 1080p with SeedVR2 | Z-Image Turbo or Qwen-Image-Edit Style Reference stills, Wan 2.2 Lightning, Chatterbox (voice sample needed), ACE-Step (≤240 s) mixed by the soundtrack workflow, Qwen3-ASR timings + caption burn-in | `/faceless`: channels (genre, idea, YouTube reference, saved look and sound, avatar), topics, 1–5 min, 12 styles or 3 style references, narrator, script review, then a two-stage render (stills + narration + word timings, then each scene cut to where its lines are spoken). Timeline editor: change a scene's picture, motion or the narration, see the price, Undo. Deleting stops the render |
| Higgsfield Explainer | 🟡 | Same pipeline as Faceless | Same; stills drawn from your source images with Qwen-Image-Edit | `/explainer`: 22 styles, up to 3 sources (images, .txt / .md, a summarised link), Auto / 20 s–10 min / Manual 15–600 s, History. PDF and Word sources aren't read (Higgsfield takes documents), hence 🟡 |
@@ -136,8 +136,8 @@ Model names are the defaults first, then the alternatives. "Demo" outputs are la
| Higgsfield feature | Fuobe | Cloud route | Open-source route | Notes |
|---|---|---|---|---|
-| Supercomputer / Assist agent | 🟢 | Claude (claude-opus-5-5 by default; Manual offers claude-sonnet-5-5, claude-haiku-5-5 and claude-fable-5-1 with an effort level) | Ollama tool calling, or the offline rule-based planner | `/assist`: plans, prices, asks first (or auto-runs), chains steps with `after`. Modes Free / Smart / Manual; each chat's context is frozen when it starts and later changes arrive as "Context update" messages |
-| Assist skills | ✅ app · 🟢 with an LLM | Loaded into Claude's context with `/name` or `load_skill` | Same on Ollama; the offline planner uses their hints | 20 built-in SKILL.md playbooks in `skills/`; create, edit, duplicate, download, turn on / off, upload .md / .zip / .skill (bounded unzip). Also offered as MCP prompts |
+| Supercomputer / Assist agent | 🟢 | Claude (claude-opus-5-5 by default; Manual offers claude-sonnet-5-5, claude-haiku-5-5 and claude-fable-5-1 with an effort level) | A local model's tool calling (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server), or the offline rule-based planner | `/assist`: plans, prices, asks first (or auto-runs), chains steps with `after`. Modes Free / Smart / Manual; each chat's context is frozen when it starts and later changes arrive as "Context update" messages |
+| Assist skills | ✅ app · 🟢 with an LLM | Loaded into Claude's context with `/name` or `load_skill` | Same on a local model; the offline planner uses their hints | 20 built-in SKILL.md playbooks in `skills/`; create, edit, duplicate, download, turn on / off, upload .md / .zip / .skill (bounded unzip). Also offered as MCP prompts |
| Assist projects | ✅ app · 🟢 with an LLM | — | — | Instructions, colour, up to 20 sources (links and PDFs fetched safely, files with PDF text, elements, notes), project skills, chats per project, an Assets tab |
| Assist memory | ✅ app · 🟢 with an LLM | — | — | 8 categories, add / edit / delete, import from other assistants, per project or across all chats; the `remember` tool asks first |
| Studio jobs from Assist and MCP | 🟡 | `split_layers`, `restyle_footage`, `dub_video`, `faceless_episode`, `create_ads`, `add_captions`, `katana` | Same on the open engine (`faceless_episode` needs a voice sample there) | Each runs as a `createPipeline` job and is priced on the approval card first. They don't open a studio session yet, so there is no dub review, Layers project or Shorts session to continue in (see §3) |
@@ -164,7 +164,7 @@ Most important first.
**Not run for real (no keys, no GPU)**
- **Paid providers are untested with real keys.** That now includes the round-3 response shapes Fuobe reads: Seedream layer boxes, Recraft's returned `style_id`, transcript cues, 3D files, Demucs stems, and the fal FFmpeg tools (compose `tracks`, loudnorm, forced alignment, `scale-video` crop, extract-audio). Two behaviours are assumptions from the docs: fal compose cuts an audio keyframe at its `duration`, and it renders an audio-only timeline over a still. Cloud `join-clips` is assumed to keep each clip's audio.
- **Open-source quality is unverified.** Round 3 added about 165 GB of new model files (plus about 9 GB that nodes download on first use) that have never run here. Whole open chains (a UGC presenter film, a Faceless episode, a dub with lip re-sync, a Shorts restyle) ran only on the demo provider. The try-on single-garment graph and the new InfiniteTalk sizing are checked by `/prompt` validation only; ThinkSound's packages are installed on the isolated worker but never ran.
-- **Assist hasn't talked to a live model.** The streamed Claude call is tested against an SSE fake and Ollama against a fake server. Skills, projects and memory work end to end with the offline planner only. Small local models follow tool instructions less reliably.
+- **Assist hasn't talked to a live model.** The streamed Claude call is tested against an SSE fake, and Ollama and LM Studio against fake servers. Skills, projects and memory work end to end with the offline planner only. Small local models follow tool instructions less reliably.
**Gaps that change what a user gets**
- **Assist / MCP studio tools always use their pipeline fallback.** `STUDIO_ROUTES` in `src/server/assist/studio-tools.ts` is empty, so a `dub_video` or `split_layers` job lands in the Library, not as a dub session or a Layers project. The `katana` tool is in the tool list but isn't named in Assist's system prompt or the MCP instructions. Several skills still link to stand-in pages: `faceless-video` → `/storyboard`, `katana` and `ad-multiplier` → `/video-edit`, `marketing-studio-cards` → `/apps/app-ad-creative`, `character-sheet` → `/elements`.
@@ -187,7 +187,7 @@ Most important first.
- Without Web Locks (plain `http://` on a LAN IP) each visible tab reads its own live stream; six or more visible windows on one host could hit the browser's connection limit.
- **Sign-in is off by default.** Without a password Fuobe answers only on local addresses and names in `FUOBE_ALLOWED_ORIGINS`, but anyone who can reach it can use it (and your keys). With a password, a page that rebinds DNS can still post password guesses; the throttle caps that at roughly 15–20 a minute. Without `FUOBE_TRUST_PROXY=1` behind a reverse proxy, all visitors share one throttle (slowed, never locked out). `comfyLorasDir` and `aiToolkitDatasetDir` make the server write files where you point them.
- `MAX_INLINE_TEXT` caps a result's inline text at 64,000 characters; `meta.cues` of a very long transcript stays inline.
-- The first routing check after the Ollama or ComfyUI URL changes can hold a request for up to 1.5 s when the host doesn't answer.
+- The first routing check after a local LLM server's or ComfyUI's URL changes can hold a request for up to 1.5 s when the host doesn't answer.
- Unknown Cinema, Canvas and Assist project ids show a not-found state with HTTP 200; only `/apps/<unknown>` returns a real 404.
**UI leftovers (small)**
diff --git a/docs/cli.md b/docs/cli.md
index a020673c..ce10b93a 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -149,7 +149,7 @@ Without `--wait` or `--out`, `generate` prints the job ids and returns at once.
### `fuobe status`, `fuobe wait`, `fuobe download`, `fuobe cancel`
```bash
-fuobe status # the server: engine mode, demo mode, providers, the token
+fuobe status # the server: engine mode, demo mode, providers, the local LLM, the token
fuobe status V1StGXR8_Z5j # one or more generations
fuobe wait V1StGXR8_Z5j 3Kp9x2LmQa7c # until each is done; prints the output URLs (text results inline)
fuobe wait V1StGXR8_Z5j --out renders/
diff --git a/next.config.ts b/next.config.ts
index 60b44f74..20332fd2 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -8,6 +8,16 @@ const nextConfig: NextConfig = {
// The sign-in proxy buffers request bodies (10 MB by default): uploads take up to 200 MB plus the form overhead.
proxyClientMaxBodySize: "210mb",
},
+ async headers() {
+ return [
+ // Preset preview media (scripts/build-previews.mjs) has its content hash in every file name,
+ // so it can be cached for good; the public folder's default is max-age=0.
+ { source: "/previews/:path*", headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }] },
+ // Vendored scripts (public/vendor: the 3D viewer's meshopt decoder) keep their name across upgrades:
+ // a day, then revalidated in the background.
+ { source: "/vendor/:path*", headers: [{ key: "Cache-Control", value: "public, max-age=86400, stale-while-revalidate=604800" }] },
+ ];
+ },
async redirects() {
return [
{ source: "/characters", destination: "/elements", permanent: true },
diff --git a/package.json b/package.json
index a659c6de..4c36d5ac 100644
--- a/package.json
+++ b/package.json
@@ -22,6 +22,9 @@
"dependencies": {
"@anthropic-ai/sdk": "^0.135.0",
"@fal-ai/client": "^1.10.1",
+ "@gltf-transform/core": "4.5.1",
+ "@gltf-transform/extensions": "4.5.1",
+ "@gltf-transform/functions": "4.5.1",
"@google/model-viewer": "4.3.1",
"@tanstack/react-query": "^5.104.3",
"@xyflow/react": "^12.12.0",
@@ -30,9 +33,11 @@
"cmdk": "^1.1.1",
"cn": "^0.5.0",
"lucide-react": "^1.58.0",
+ "meshoptimizer": "1.2.0",
"nanoid": "^6.0.2",
"next": "16.4.2",
"next-themes": "^0.4.6",
+ "playwright-core": "1.64.0",
"radix-ui": "^1.8.1",
"react": "19.3.0",
"react-dom": "19.3.0",
@@ -40,6 +45,7 @@
"remark-gfm": "^4.0.1",
"server-only": "^0.0.1",
"shadcn": "^4.22.0",
+ "sharp": "0.35.5",
"sonner": "^2.0.8",
"three": "0.183.2",
"tw-animate-css": "^1.4.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 30bb21f9..63725187 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -14,6 +14,15 @@ importers:
'@fal-ai/client':
specifier: ^1.10.1
version: 1.10.1
+ '@gltf-transform/core':
+ specifier: 4.5.1
+ version: 4.5.1
+ '@gltf-transform/extensions':
+ specifier: 4.5.1
+ version: 4.5.1
+ '@gltf-transform/functions':
+ specifier: 4.5.1
+ version: 4.5.1(@types/[email protected])
'@google/model-viewer':
specifier: 4.3.1
version: 4.3.1([email protected])
@@ -38,6 +47,9 @@ importers:
lucide-react:
specifier: ^1.58.0
version: 1.58.0(@types/[email protected])([email protected])
+ meshoptimizer:
+ specifier: 1.2.0
+ version: 1.2.0
nanoid:
specifier: ^6.0.2
version: 6.0.2
@@ -47,6 +59,9 @@ importers:
next-themes:
specifier: ^0.4.6
+ playwright-core:
+ specifier: 1.64.0
+ version: 1.64.0
radix-ui:
specifier: ^1.8.1
@@ -68,6 +83,9 @@ importers:
shadcn:
specifier: ^4.22.0
version: 4.22.0
+ sharp:
+ specifier: 0.35.5
+ version: 0.35.5(@types/[email protected])
sonner:
specifier: ^2.0.8
@@ -345,6 +363,15 @@ packages:
'@floating-ui/[email protected]':
resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==}
+ '@gltf-transform/[email protected]':
+ resolution: {integrity: sha512-OWgBYssKHKoXMIrMb2N20jXqWRnMP9HdtcTFQBEAJtz4P+OOxx5fozl5eAeK7nktIs5uDE/lu4NbkE5VCZaR9g==}
+
+ '@gltf-transform/[email protected]':
+ resolution: {integrity: sha512-3jTe+GWRy4fj1TU790LPsO+rpO/4byUWPTpNkjy6M6h8RvrUivRf12Mptc0770K4ZczibpJDNHXZFkFsFMRDLA==}
+
+ '@gltf-transform/[email protected]':
+ resolution: {integrity: sha512-rfm4nQY2DJ+ip1e15xp7YfQwhRno3kPLcGw4EZiRk1dVwMV3cdFMcF08glYcO/+oLyYkUEs3xXMJYXa0cPgcTg==}
+
'@google/[email protected]':
resolution: {integrity: sha512-GP+inXhAtY31E8rILVmByA6z8CZZjdlNajddppyI1/j1eIaSQiZcMRaUqTFe7+jv4mzRzwKIOiKBud0apiv+WQ==}
engines: {node: '>=6.0.0'}
@@ -1604,6 +1631,9 @@ packages:
resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-go+C6vHBUuO9jH6Tj6qEZ63JEGoMSxFdmd+6QAtthGD6xumBfIz3RbNDDs2aoRVLf9naH8lk5jnWy2UHHKgYQQ==}
+
resolution: {integrity: sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==}
@@ -2152,6 +2182,9 @@ packages:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
+ resolution: {integrity: sha512-WXlK/m+Di8DMMcCjcWr4i+XzcQra9eCdXIJrgh4TUgh0pIS/yJduLxS9JgefsHJ/YVLdgPtXm9r62W92MvanEQ==}
+
resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==}
engines: {node: '>=12'}
@@ -2822,6 +2855,9 @@ packages:
resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-pZ2xT+LOHckCatGQ3DcG/a+QuEqvoxqkiL7tvE8nn3uuu+f6i1TtpB5/FtWFbxUuVr5PZCx8KskuGatbJDXOWA==}
+
resolution: {integrity: sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==}
engines: {node: '>= 12'}
@@ -2852,6 +2888,9 @@ packages:
resolution: {integrity: sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==}
+
resolution: {integrity: sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==}
@@ -3100,6 +3139,9 @@ packages:
resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ==}
+
resolution: {integrity: sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==}
@@ -3370,6 +3412,9 @@ packages:
resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-davRZeIJbxJrE24cwQle7ZDsxjdk/OphNOV83oX+efQinyoHY9Jcyz3MHbaoG0qySZajldGztNZ1RN/T19PZsg==}
+
resolution: {integrity: sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==}
@@ -3512,6 +3557,18 @@ packages:
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
+ resolution: {integrity: sha512-5kBmmG3Zvyj77qxIAC4QFLKuYdDIBJwCG+DukT6jQHNa1Ft74/hPH1z5mbQXeHBt8yvGPBGVrr3wEOdJPYYZYg==}
+
+ resolution: {integrity: sha512-BppWAFRjMYF7N/r6Ie51q6D4fs0iiGmeXIACKY66fLpnwIui3Wc3CXiD/30mgLbDjPpSLrsqcp3Z62+IcHZsDw==}
+
+ resolution: {integrity: sha512-lTh4tFKziAatVTa9crIsidUyn+lqujVOQpzfdBWvdFu2wo9Uo6z261lVX7SgMyP89xGmj3TMTPbbxl9YDnV4SA==}
+
+ resolution: {integrity: sha512-AsE8w/M2MS+0pD3nP5qbRRtJFeJJJaJ+qXZaZr0XjVGXhy6LIj2TERTlkpdK2AI3WufoOP+pwPk3q2ilAJcZ9g==}
+
resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==}
engines: {node: '>=18'}
@@ -3717,6 +3774,11 @@ packages:
resolution: {integrity: sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==}
+ engines: {node: '>=20'}
+ hasBin: true
+
resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}
engines: {node: '>= 0.4'}
@@ -3755,6 +3817,9 @@ packages:
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
+ resolution: {integrity: sha512-AvPcP7XECNWy4LGmFQ77k7un4lSKM4eS29PTvW4ck95uYeLxXPWJM7hLuBqK91FaHqCcgJvIUCuNJjjxKE7VKQ==}
+
resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==}
@@ -4273,6 +4338,9 @@ packages:
resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
+ resolution: {integrity: sha512-Gw+zz50YNKPDKXs+9d+aKAjVwpjNwqzvNpLigIruT4HA9lMZNdMqs9x07kKHB/L9WRzqp4+DlTU5s4wG2esdoA==}
+
resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}
@@ -4848,6 +4916,26 @@ snapshots:
'@floating-ui/[email protected]': {}
+ '@gltf-transform/[email protected]':
+ dependencies:
+ property-graph: 4.1.0
+
+ '@gltf-transform/[email protected]':
+ dependencies:
+ '@gltf-transform/core': 4.5.1
+ ktx-parse: 1.1.0
+
+ '@gltf-transform/[email protected](@types/[email protected])':
+ dependencies:
+ '@gltf-transform/core': 4.5.1
+ '@gltf-transform/extensions': 4.5.1
+ ktx-parse: 1.1.0
+ ndarray: 1.1.1
+ ndarray-lanczos: 0.3.0
+ ndarray-pixels: 5.2.0(@types/[email protected])
+ transitivePeerDependencies:
+ - '@types/node'
+
dependencies:
'@monogrid/gainmap-js': 3.4.0([email protected])
@@ -4874,8 +4962,7 @@ snapshots:
'@humanwhocodes/[email protected]': {}
- optional: true
+ '@img/[email protected]': {}
optionalDependencies:
@@ -6074,6 +6161,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
dependencies:
undici-types: 6.21.0
@@ -6612,6 +6701,10 @@ snapshots:
+ dependencies:
+ uniq: 1.0.1
+
@@ -7450,6 +7543,8 @@ snapshots:
hasown: 2.0.4
side-channel: 1.1.1
+
@@ -7484,6 +7579,8 @@ snapshots:
call-bound: 1.0.4
has-tostringtag: 1.0.2
+
dependencies:
semver: 7.8.5
@@ -7692,6 +7789,8 @@ snapshots:
+
@@ -8028,6 +8127,8 @@ snapshots:
+
dependencies:
decode-named-character-reference: 1.3.0
@@ -8262,6 +8363,29 @@ snapshots:
+ dependencies:
+ '@types/ndarray': 1.1.0
+ ndarray: 1.1.1
+
+ dependencies:
+ cwise-compiler: 1.1.3
+
+ dependencies:
+ '@types/ndarray': 1.1.0
+ ndarray: 1.1.1
+ ndarray-ops: 1.2.2
+ sharp: 0.35.5(@types/[email protected])
+ transitivePeerDependencies:
+ - '@types/node'
+
+ dependencies:
+ iota-array: 1.0.0
+ is-buffer: 1.1.6
+
dependencies:
content-type: 2.1.0
@@ -8484,6 +8608,8 @@ snapshots:
dependencies:
find-up: 3.0.0
+
@@ -8527,6 +8653,8 @@ snapshots:
object-assign: 4.1.1
react-is: 16.13.1
+
@@ -8941,7 +9069,6 @@ snapshots:
'@img/sharp-win32-ia32': 0.35.5
'@img/sharp-win32-x64': 0.35.5
'@types/node': 20.19.43
- optional: true
dependencies:
@@ -9263,6 +9390,8 @@ snapshots:
trough: 2.2.0
vfile: 6.0.3
+
dependencies:
'@types/unist': 3.0.3
diff --git a/public/vendor/meshopt_decoder.js b/public/vendor/meshopt_decoder.js
new file mode 100644
index 00000000..f43e71a3
--- /dev/null
+++ b/public/vendor/meshopt_decoder.js
@@ -0,0 +1,199 @@
+// This file is part of meshoptimizer library and is distributed under the terms of MIT License.
+// Copyright (C) 2016-2026, by Arseny Kapoulkine ([email protected])
+var MeshoptDecoder = (function () {
+ // Built with clang version 22.1.0-wasi-sdk
+ // Built from meshoptimizer 1.2
+ var wasm_base =
+ 'b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuixkbeeeddddillviebeoweuecj:Gdkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WboY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbrl79IV9Rbwq1Zkdbk:kYi5ud9:du8Jjjjjbcjq9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxcj;abad9Uc;WFbGcjdadca0EhmaialfgPar9Rgoadfhsavaoadz:jjjjbgzceVhHcbhOdndninaeaO9nmeaPax9RaD6mdamaeaO9RaOamfgoae6EgAcsfglc9WGhCaAcethXaxaDfhiaOaeaoaeao6E9RhQalcl4cifcd4hLazcjdfaAfhKcbhYabaOad2fg8AhEaHh3incbh5dnawTmbaxaYcd4fRbbh5kcbh8Eazcjdfhqinaih8Fdndndndna5a8Ecet4ciGgoc9:fPdebdkaPa8F9RaA6mrazcjdfa8EaA2fa8FaAz:jjjjb8Aa8FaAfhixdkazcjdfa8EaA2fcbaAz:kjjjb8Aa8FhixekaPa8F9RaL6mva8FaLfhidnaCTmbaPai9RcK6mbaocdtc:q:G:cjbfcj:G:cjbawEhaczhrcbhlinargoc9Wfghaqfhrdndndndndndnaaa8Fahco4fRbbalcoG4ciGcdtfydbPDbedvivvvlvkar9cb83bwar9cb83bbxlkarcbaiRbdai8Xbb9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbaqaofgrcGfcbaicdfa8J9c8N1:NfghRbbag9cjjjjjw:dg8J9qE86bbarcVfcbaha8J9c8M1:NfghRbbag9cjjjjjl:dg8J9qE86bbarc7fcbaha8J9c8L1:NfghRbbag9cjjjjjd:dg8J9qE86bbarctfcbaha8J9c8K1:NfghRbbag9cjjjjje:dg8J9qE86bbarc91fcbaha8J9c8J1:NfghRbbag9cjjjj;ab:dg8J9qE86bbarc4fcbaha8J9cg1:NfghRbbag9cjjjja:dg8J9qE86bbarc93fcbaha8J9ch1:NfghRbbag9cjjjjz:dgg9qE86bbarc94fcbahag9ca1:NfghRbbai8Xbe9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbarc95fcbaha8J9c8N1:NfgiRbbag9cjjjjjw:dg8J9qE86bbarc96fcbaia8J9c8M1:NfgiRbbag9cjjjjjl:dg8J9qE86bbarc97fcbaia8J9c8L1:NfgiRbbag9cjjjjjd:dg8J9qE86bbarc98fcbaia8J9c8K1:NfgiRbbag9cjjjjje:dg8J9qE86bbarc99fcbaia8J9c8J1:NfgiRbbag9cjjjj;ab:dg8J9qE86bbarc9:fcbaia8J9cg1:NfgiRbbag9cjjjja:dg8J9qE86bbarcufcbaia8J9ch1:NfgiRbbag9cjjjjz:dgg9qE86bbaiag9ca1:NfhixikaraiRblaiRbbghco4g8Ka8KciSg8KE86bbaqaofgrcGfaiclfa8Kfg8KRbbahcl4ciGg8La8LciSg8LE86bbarcVfa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc7fa8Ka8Lfg8KRbbahciGghahciSghE86bbarctfa8Kahfg8KRbbaiRbeghco4g8La8LciSg8LE86bbarc91fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc4fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc93fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc94fa8Kahfg8KRbbaiRbdghco4g8La8LciSg8LE86bbarc95fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc96fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc97fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc98fa8KahfghRbbaiRbigico4g8Ka8KciSg8KE86bbarc99faha8KfghRbbaicl4ciGg8Ka8KciSg8KE86bbarc9:faha8KfghRbbaicd4ciGg8Ka8KciSg8KE86bbarcufaha8KfgrRbbaiciGgiaiciSgiE86bbaraifhixdkaraiRbwaiRbbghcl4g8Ka8KcsSg8KE86bbaqaofgrcGfaicwfa8Kfg8KRbbahcsGghahcsSghE86bbarcVfa8KahfghRbbaiRbeg8Kcl4g8La8LcsSg8LE86bbarc7faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarctfaha8KfghRbbaiRbdg8Kcl4g8La8LcsSg8LE86bbarc91faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc4faha8KfghRbbaiRbig8Kcl4g8La8LcsSg8LE86bbarc93faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc94faha8KfghRbbaiRblg8Kcl4g8La8LcsSg8LE86bbarc95faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc96faha8KfghRbbaiRbvg8Kcl4g8La8LcsSg8LE86bbarc97faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc98faha8KfghRbbaiRbog8Kcl4g8La8LcsSg8LE86bbarc99faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc9:faha8KfghRbbaiRbrgicl4g8Ka8KcsSg8KE86bbarcufaha8KfgrRbbaicsGgiaicsSgiE86bbaraifhixekarai8Pbw83bwarai8Pbb83bbaiczfhikdnaoaC9pmbalcdfhlaoczfhraPai9RcL0mekkaoaC6moaimexokaCmva8FTmvkaqaAfhqa8Ecefg8Ecl9hmbkdndndndnawTmbasaYcd4fRbbgociGPlbedrbkaATmdazaYfh8Fazcjdfhhcbh8EaEhaina8FRbbhraahocbhlinaoahalfRbbgqce4cbaqceG9R7arfgr86bbaoadfhoaAalcefgl9hmbkaacefhaa8Fcefh8FahaAfhha8Ecefg8Ecl9hmbxikkaATmeazaYfhaazcjdfhhcbhoceh8EaKh8FinaEaofhlaa8Vbbhrcbhoinala8FaofRbbcwtahaofRbbgqVc;:FiGce4cbaqceG9R7arfgr87bbaladfhlaQaocefgofmbka8FaXfh8FcdhoaacdfhaahaXfhha8EceGhlcbh8EalmbxdkkaATmbaocl4h8EazaYfRbbhqcwhoa3hlinalRbbaotaqVhqalcefhlaocwfgoca9hmbkcbhhaEh8FaKhainazcjdfahfRbbhrcwhoaahlinalRbbaotarVhralaAfhlaocwfgoca9hmbkara8E94aq7hqcbhoa8Fhlinalaqao486bbalcefhlaocwfgoca9hmbka8Fadfh8FaacefhaahcefghaA9hmbkkaEclfhEa3clfh3aYclfgYad6mbkaza8AaAcufad2fadz:jjjjb8AaAaOfhOaihxaimbkc9:hoxdkcbc99aPax9RakSEhoxekc9:hokavcjqf8Kjjjjbaok:ysezu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnalaeci9UgrcHf6mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:kjjjb8Aav9cu83iUav9cu83i8Wav9cu83iyav9cu83iaav9cu83iKav9cu83izav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbavaiaqaDcsGfRbbgscl4gP9RcsGcdtfydbaxcefgOaPEhDavaias9RcsGcdtfydbaOaPTgzfgOascsGgPEhsaPThPdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiazfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaPfhiaOaPfhxxekaxcbalRbbgsEgHaDc;:eSgDfhOascsGhAdndnascl4gCmbaOcefhzxekaOhzavaiaC9RcsGcdtfydbhOkdndnaAmbazcefhxxekazhxavaias9RcsGcdtfydbhzkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhHascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaHhDxekaDcefhDkasce4cbasceG9R7amfgmhHkdndnaCcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhOaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkaOhsxekascefhskaPce4cbaPceG9R7amfgmhOkdndnaAcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhzaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkazhlxekalcefhlkaPce4cbaPceG9R7amfgmhzkdndnadcd9hmbabarcetfgDaH87ebaDclfaz87ebaDcdfaO87ebxekabarcdtfgDaHBdbaDcwfazBdbaDclfaOBdbkavc;abfaocitfgDaOBdbaDaHBdlavaicdtfaHBdbavc;abfaocefcsGcitfgDazBdbaDaOBdlavaicefgicsGcdtfaOBdbavc;abfaocdfcsGcitfgDaHBdbaDazBdlavaiaCTaCcsSVfgicsGcdtfazBdbaiaATaAcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnalaecvf9pmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk:4ioiue99dud99dud99dnaeTmbcbhiabhlindndnal8Uebgv:YgoJ:ji:1Salcof8UebgrciVgw:Y:vgDNJbbbZJbbb:;avcu9kEMgq:lJbbb9p9DTmbaq:Ohkxekcjjjj94hkkalclf8Uebhvalcdf8UebhxalarcefciGcetfak87ebdndnax:YgqaDNJbbbZJbbb:;axcu9kEMgm:lJbbb9p9DTmbam:Ohxxekcjjjj94hxkabaiarciGgkfcd7cetfax87ebdndnav:YgmaDNJbbbZJbbb:;avcu9kEMgP:lJbbb9p9DTmbaP:Ohvxekcjjjj94hvkalarcufciGcetfav87ebdndnawaw2:ZgPaPMaoaoN:taqaqN:tamamN:tgoJbbbbaoJbbbb9GE:raDNJbbbZMgD:lJbbb9p9DTmbaD:Ohrxekcjjjj94hrkalakcetfar87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2gdTmbinababydbgecwtcw91:Yaece91cjjj98Gcjjj;8if::NUdbabclfhbadcufgdmbkkk:Tvirud99eudndnadcl9hmbaeTmeindndnabRbbgiabcefgl8Sbbgvabcdfgo8Sbbgrf9R:YJbbuJabcifgwRbbgdce4adVgDcd4aDVgDcl4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax86bbdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao86bbdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai86bbdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad86bbabclfhbaecufgembxdkkaeTmbindndnab8Vebgiabcdfgl8Uebgvabclfgo8Uebgrf9R:YJbFu9habcofgw8Vebgdce4adVgDcd4aDVgDcl4aDVgDcw4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax87ebdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao87ebdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai87ebdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad87ebabcwfhbaecufgembkkk9teiucbcbyd:K:G:cjbgeabcifc98GfgbBd:K:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkk83dbcj:Gdk8Kbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbc:K:Gdkl8W:qbb'; // embed! base
+ var wasm_simd =
+ 'b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuixkbbebeeddddilve9Weeeviebeoweuecj:Gdkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WbwY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbDl79IV9Rbqq:59Dklbzik94evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaeai86b:q:W:cjbaecitab8Piw83i:q:G:cjbaecefgecjd9hmbkk:SBlEud97dur978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaialfgxar9RhodnadTgmmbavaoad;8qbbkaicefhPcj;abad9Uc;WFbGcjdadca0EhsdndndnadTmbaoadfhzcbhHinaeaH9nmdaxaP9RaD6miabaHad2fgOavcjdfasaeaH9RaHasfae6EgAaAcsfgoc9WGgCSEhXaPaDfhQaocl4cifcd4hLavcj;cbfaCcetfhKavcj;cbfaCci2fhYavcj;cbfaCfh8AcbhEaoc;ab6h3incbh5dnawTmbaPaEcd4fRbbh5kcbh8Eavcj;cbfh8Findndndndna5a8Ecet4ciGgoc9:fPdebdkaxaQ9RaC6mwdnaCTmbavcj;cbfa8EaC2faQaC;8qbbkaQaAfhQxdkaCTmeavcj;cbfa8EaC2fcbaC;8kbxekaxaQ9RaL6moaoclVcbawEhraQaLfhocbhidna3mbaxao9Rc;Gb6mbcbhlina8FalfhidndndndndndnaQalco4fRbbgqciGarfPDbedibledibkaipxbbbbbbbbbbbbbbbbpklbxlkaiaopbblaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLgacdp:meaapmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9oghpxiiiiiiiiiiiiiiiip8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbagRb:q:W:cjbggpsaap5e9cjF;8;4;W;G;ab9:9cU1:Ng8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spklbagaoclffa8JRb:q:W:cjbfhoxikaiaopbbwaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLpxssssssssssssssssp9oghpxssssssssssssssssp8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbagRb:q:W:cjbggpsaap5e9cjF;8;4;W;G;ab9:9cU1:Ng8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spklbagaocwffa8JRb:q:W:cjbfhoxdkaiaopbbbpklbaoczfhoxekaiaopbbdaoRbbggcitpbi:q:G:cjbagRb:q:W:cjbggpsaoRbeg8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbagaocdffa8JRb:q:W:cjbfhokdndndndndndnaqcd4ciGarfPDbedibledibkaiczfpxbbbbbbbbbbbbbbbbpklbxlkaiczfaopbblaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLgacdp:meaapmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9oghpxiiiiiiiiiiiiiiiip8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbagRb:q:W:cjbggpsaap5e9cjF;8;4;W;G;ab9:9cU1:Ng8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spklbagaoclffa8JRb:q:W:cjbfhoxikaiczfaopbbwaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLpxssssssssssssssssp9oghpxssssssssssssssssp8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbagRb:q:W:cjbggpsaap5e9cjF;8;4;W;G;ab9:9cU1:Ng8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spklbagaocwffa8JRb:q:W:cjbfhoxdkaiczfaopbbbpklbaoczfhoxekaiczfaopbbdaoRbbggcitpbi:q:G:cjbagRb:q:W:cjbggpsaoRbeg8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbagaocdffa8JRb:q:W:cjbfhokdndndndndndnaqcl4ciGarfPDbedibledibkaicafpxbbbbbbbbbbbbbbbbpklbxlkaicafaopbblaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLgacdp:meaapmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9oghpxiiiiiiiiiiiiiiiip8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbagRb:q:W:cjbggpsaap5e9cjF;8;4;W;G;ab9:9cU1:Ng8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spklbagaoclffa8JRb:q:W:cjbfhoxikaicafaopbbwaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLpxssssssssssssssssp9oghpxssssssssssssssssp8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbagRb:q:W:cjbggpsaap5e9cjF;8;4;W;G;ab9:9cU1:Ng8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spklbagaocwffa8JRb:q:W:cjbfhoxdkaicafaopbbbpklbaoczfhoxekaicafaopbbdaoRbbggcitpbi:q:G:cjbagRb:q:W:cjbggpsaoRbeg8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbagaocdffa8JRb:q:W:cjbfhokdndndndndndnaqco4arfPDbedibledibkaic8Wfpxbbbbbbbbbbbbbbbbpklbxlkaic8Wfaopbblaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLgacdp:meaapmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9oghpxiiiiiiiiiiiiiiiip8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Ngicitpbi:q:G:cjbaiRb:q:W:cjbgipsaap5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spklbaiaoclffaqRb:q:W:cjbfhoxikaic8Wfaopbbwaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLpxssssssssssssssssp9oghpxssssssssssssssssp8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Ngicitpbi:q:G:cjbaiRb:q:W:cjbgipsaap5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spklbaiaocwffaqRb:q:W:cjbfhoxdkaic8Wfaopbbbpklbaoczfhoxekaic8WfaopbbdaoRbbgicitpbi:q:G:cjbaiRb:q:W:cjbgipsaoRbegqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbaiaocdffaqRb:q:W:cjbfhokalc;abfhialcjefaC0meaihlaxao9Rc;Fb0mbkkdnaiaC9pmbaici4hlinaxao9RcK6mwa8FaifhqdndndndndndnaQaico4fRbbalcoG4ciGarfPDbedibledibkaqpxbbbbbbbbbbbbbbbbpkbbxlkaqaopbblaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLgacdp:meaapmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9oghpxiiiiiiiiiiiiiiiip8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbagRb:q:W:cjbggpsaap5e9cjF;8;4;W;G;ab9:9cU1:Ng8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spkbbagaoclffa8JRb:q:W:cjbfhoxikaqaopbbwaopbbbgaclp:meaapmbzeHdOiAlCvXoQrLpxssssssssssssssssp9oghpxssssssssssssssssp8Jgap5b9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbagRb:q:W:cjbggpsaap5e9cjF;8;4;W;G;ab9:9cU1:Ng8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPahaap9spkbbagaocwffa8JRb:q:W:cjbfhoxdkaqaopbbbpkbbaoczfhoxekaqaopbbdaoRbbggcitpbi:q:G:cjbagRb:q:W:cjbggpsaoRbeg8Jcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpkbbagaocdffa8JRb:q:W:cjbfhokalcdfhlaiczfgiaC6mbkkaohQaoTmoka8FaCfh8Fa8Ecefg8Ecl9hmbkdndndndnawTmbazaEcd4fRbbglciGPlbedwbkaCTmdaXaEfhlavaEfpbdbh8Kcbhoinalavcj;cbfaofpblbg8La8Aaofpblbg8MpmbzeHdOiAlCvXoQrLg8NaKaofpblbgyaYaofpblbg8PpmbzeHdOiAlCvXoQrLgIpmbezHdiOAlvCXorQLgacep9Taapxeeeeeeeeeeeeeeeeghp9op9Hp9rgaa8Kp9Ug8Kp9Abbbaladfgla8Kaaaapmlvorlvorlvorlvorp9Ug8Kp9Abbbaladfgla8KaaaapmwDqkwDqkwDqkwDqkp9Ug8Kp9Abbbaladfgla8KaaaapmxmPsxmPsxmPsxmPsp9Ug8Kp9Abbbaladfgla8Ka8NaIpmwDKYqk8AExm35Ps8E8Fgacep9Taaahp9op9Hp9rgap9Ug8Kp9Abbbaladfgla8Kaaaapmlvorlvorlvorlvorp9Ug8Kp9Abbbaladfgla8KaaaapmwDqkwDqkwDqkwDqkp9Ug8Kp9Abbbaladfgla8KaaaapmxmPsxmPsxmPsxmPsp9Ug8Kp9Abbbaladfgla8Ka8La8MpmwKDYq8AkEx3m5P8Es8Fg8Laya8PpmwKDYq8AkEx3m5P8Es8Fg8MpmbezHdiOAlvCXorQLgacep9Taaahp9op9Hp9rgap9Ug8Kp9Abbbaladfgla8Kaaaapmlvorlvorlvorlvorp9Ug8Kp9Abbbaladfgla8KaaaapmwDqkwDqkwDqkwDqkp9Ug8Kp9Abbbaladfgla8KaaaapmxmPsxmPsxmPsxmPsp9Ug8Kp9Abbbaladfgla8Ka8La8MpmwDKYqk8AExm35Ps8E8Fgacep9Taaahp9op9Hp9rgap9Ughp9Abbbaladfglahaaaapmlvorlvorlvorlvorp9Ughp9AbbbaladfglahaaaapmwDqkwDqkwDqkwDqkp9Ughp9AbbbaladfglahaaaapmxmPsxmPsxmPsxmPsp9Ug8Kp9AbbbaladfhlaoczfgoaC6mbxikkaCTmeaXaEfhlavaEfpbdbh8Kcbhoinalavcj;cbfaofpblbg8La8Aaofpblbg8MpmbzeHdOiAlCvXoQrLg8NaKaofpblbgyaYaofpblbg8PpmbzeHdOiAlCvXoQrLgIpmbezHdiOAlvCXorQLgacep:neaapxebebebebebebebebghp9op:bep9rgaa8Kp:oeg8Kp9Abbbaladfgla8Kaaaapmlvorlvorlvorlvorp:oeg8Kp9Abbbaladfgla8KaaaapmwDqkwDqkwDqkwDqkp:oeg8Kp9Abbbaladfgla8KaaaapmxmPsxmPsxmPsxmPsp:oeg8Kp9Abbbaladfgla8Ka8NaIpmwDKYqk8AExm35Ps8E8Fgacep:neaaahp9op:bep9rgap:oeg8Kp9Abbbaladfgla8Kaaaapmlvorlvorlvorlvorp:oeg8Kp9Abbbaladfgla8KaaaapmwDqkwDqkwDqkwDqkp:oeg8Kp9Abbbaladfgla8KaaaapmxmPsxmPsxmPsxmPsp:oeg8Kp9Abbbaladfgla8Ka8La8MpmwKDYq8AkEx3m5P8Es8Fg8Laya8PpmwKDYq8AkEx3m5P8Es8Fg8MpmbezHdiOAlvCXorQLgacep:neaaahp9op:bep9rgap:oeg8Kp9Abbbaladfgla8Kaaaapmlvorlvorlvorlvorp:oeg8Kp9Abbbaladfgla8KaaaapmwDqkwDqkwDqkwDqkp:oeg8Kp9Abbbaladfgla8KaaaapmxmPsxmPsxmPsxmPsp:oeg8Kp9Abbbaladfgla8Ka8La8MpmwDKYqk8AExm35Ps8E8Fgacep:neaaahp9op:bep9rgap:oeghp9Abbbaladfglahaaaapmlvorlvorlvorlvorp:oeghp9AbbbaladfglahaaaapmwDqkwDqkwDqkwDqkp:oeghp9AbbbaladfglahaaaapmxmPsxmPsxmPsxmPsp:oeg8Kp9AbbbaladfhlaoczfgoaC6mbxdkkaCTmbaXaEfhrcbhocbalcl4gl9Rc8FGhiavaEfpbdbhhinaravcj;cbfaofpblbg8Ka8Aaofpblbg8LpmbzeHdOiAlCvXoQrLg8MaKaofpblbg8NaYaofpblbgypmbzeHdOiAlCvXoQrLg8PpmbezHdiOAlvCXorQLgaaip:Reaaalp:Tep9qgaahp9rghp9Abbbaradfgrahaaaapmlvorlvorlvorlvorp9rghp9AbbbaradfgrahaaaapmwDqkwDqkwDqkwDqkp9rghp9AbbbaradfgrahaaaapmxmPsxmPsxmPsxmPsp9rghp9Abbbaradfgraha8Ma8PpmwDKYqk8AExm35Ps8E8Fgaaip:Reaaalp:Tep9qgap9rghp9Abbbaradfgrahaaaapmlvorlvorlvorlvorp9rghp9AbbbaradfgrahaaaapmwDqkwDqkwDqkwDqkp9rghp9AbbbaradfgrahaaaapmxmPsxmPsxmPsxmPsp9rghp9Abbbaradfgraha8Ka8LpmwKDYq8AkEx3m5P8Es8Fg8Ka8NaypmwKDYq8AkEx3m5P8Es8Fg8LpmbezHdiOAlvCXorQLgaaip:Reaaalp:Tep9qgap9rghp9Abbbaradfgrahaaaapmlvorlvorlvorlvorp9rghp9AbbbaradfgrahaaaapmwDqkwDqkwDqkwDqkp9rghp9AbbbaradfgrahaaaapmxmPsxmPsxmPsxmPsp9rghp9Abbbaradfgraha8Ka8LpmwDKYqk8AExm35Ps8E8Fgaaip:Reaaalp:Tep9qgap9rghp9Abbbaradfgrahaaaapmlvorlvorlvorlvorp9rghp9AbbbaradfgrahaaaapmwDqkwDqkwDqkwDqkp9rghp9AbbbaradfgrahaaaapmxmPsxmPsxmPsxmPsp9rghp9AbbbaradfhraoczfgoaC6mbkkaEclfgEad6mbkdnaXavcjdf9hmbaAad2goTmbaOavcjdfao;8qbbkdnammbavaXaAcufad2fad;8qbbkaAaHfhHc9:hoaQhPaQmbxlkkaeTmbaDalfhrcbhocuhlinaralaD9RglfaD6mdasaeao9Raoasfae6Eaofgoae6mbkaial9RhPkcbc99axaP9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaokwbz:bjjjbkNsezu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnalaeci9UgrcHf6mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbav9cu83iUav9cu83i8Wav9cu83iyav9cu83iaav9cu83iKav9cu83izav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbavaiaqaDcsGfRbbgscl4gP9RcsGcdtfydbaxcefgOaPEhDavaias9RcsGcdtfydbaOaPTgzfgOascsGgPEhsaPThPdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiazfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaPfhiaOaPfhxxekaxcbalRbbgsEgHaDc;:eSgDfhOascsGhAdndnascl4gCmbaOcefhzxekaOhzavaiaC9RcsGcdtfydbhOkdndnaAmbazcefhxxekazhxavaias9RcsGcdtfydbhzkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhHascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaHhDxekaDcefhDkasce4cbasceG9R7amfgmhHkdndnaCcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhOaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkaOhsxekascefhskaPce4cbaPceG9R7amfgmhOkdndnaAcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhzaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkazhlxekalcefhlkaPce4cbaPceG9R7amfgmhzkdndnadcd9hmbabarcetfgDaH87ebaDclfaz87ebaDcdfaO87ebxekabarcdtfgDaHBdbaDcwfazBdbaDclfaOBdbkavc;abfaocitfgDaOBdbaDaHBdlavaicdtfaHBdbavc;abfaocefcsGcitfgDazBdbaDaOBdlavaicefgicsGcdtfaOBdbavc;abfaocdfcsGcitfgDaHBdbaDazBdlavaiaCTaCcsSVfgicsGcdtfazBdbaiaATaAcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnalaecvf9pmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk;Toio97eue97aec98Ghedndnadcl9hmbaeTmecbhdinababpbbbgicKp:RecKp:Sep;6eglaicwp:RecKp:Sep;6ealp;Geaiczp:RecKp:Sep;6egvp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egralpxbbbjbbbjbbbjbbbjgwp9op9rp;Keglpxbb;:9cbb;:9cbb;:9cbb;:9calalp;Meaoaop;Meavaravawp9op9rp;Keglalp;Mep;Kep;Kep;Jep;Negvp;Mepxbbn0bbn0bbn0bbn0grp;KepxFbbbFbbbFbbbFbbbp9oaipxbbbFbbbFbbbFbbbFp9op9qalavp;Mearp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaoavp;Mearp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbabczfhbadclfgdae6mbxdkkaeTmbcbhdinabczfgDaDpbbbgipxbbbbbbFFbbbbbbFFgwp9oabpbbbgoaipmbediwDqkzHOAKY8AEgvczp:Reczp:Sep;6eglaoaipmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eavczp:Sep;6egvp;Gealp;Gep;Kep;Legipxbbbbbbbbbbbbbbbbp:2egralpxbbbjbbbjbbbjbbbjgqp9op9rp;Keglpxb;:FSb;:FSb;:FSb;:FSalalp;Meaiaip;Meavaravaqp9op9rp;Keglalp;Mep;Kep;Kep;Jep;Negvp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbp9oaiavp;Mearp;Keczp:Rep9qgialavp;Mearp;KepxFFbbFFbbFFbbFFbbp9oglpmwDKYqk8AExm35Ps8E8Fp9qpkbbabaoawp9oaialpmbezHdiOAlvCXorQLp9qpkbbabcafhbadclfgdae6mbkkk;2ileue97euo97dnaec98GgiTmbcbheinabcKfpx:ji:1S:ji:1S:ji:1S:ji:1SabpbbbglabczfgvpbbbgopmlvorxmPsCXQL358E8Fgrczp:Segwpxibbbibbbibbbibbbp9qp;6egDp;NegqaDaDp;MegDaDp;KealaopmbediwDqkzHOAKY8AEgDczp:Reczp:Sep;6eglalp;MeaDczp:Sep;6egoaop;Mearczp:Reczp:Sep;6egrarp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gDp;KepxFFbbFFbbFFbbFFbbgkp9oaqaop;MeaDp;Keczp:Rep9qgoaqalp;MeaDp;Keakp9oaqarp;MeaDp;Keczp:Rep9qgDpmwDKYqk8AExm35Ps8E8Fglp5eawclp:RegqpEi:T:j83ibavalp5baqpEd:T:j83ibabcwfaoaDpmbezHdiOAlvCXorQLgDp5eaqpEe:T:j83ibabaDp5baqpEb:T:j83ibabcafhbaeclfgeai6mbkkkuee97dnadcd4ae2c98GgeTmbcbhdinababpbbbgicwp:Recwp:Sep;6eaicep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepkbbabczfhbadclfgdae6mbkkk:Sodw97euaec98Ghedndnadcl9hmbaeTmecbhdinabpxbbuJbbuJbbuJbbuJabpbbbgicKp:TeglaicYp:Tep9qgvcdp:Teavp9qgvclp:Teavp9qgop;6ep;Negvaicwp:RecKp:SegraipxFbbbFbbbFbbbFbbbgwp9ogDp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oavaDarp:Xeaiczp:RecKp:Segip:Uep;6ep;Meaqp;Keawp9op9qavaDaraip:Uep:Xep;6ep;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qavaoalcep:Rep9oalpxebbbebbbebbbebbbp9op9qp;6ep;Meaqp;KecKp:Rep9qpkbbabczfhbadclfgdae6mbxdkkaeTmbcbhdinabczfgkpxbFu9hbFu9hbFu9hbFu9habpbbbglakpbbbgrpmlvorxmPsCXQL358E8Fgvczp:TegqavcHp:Tep9qgicdp:Teaip9qgiclp:Teaip9qgicwp:Teaip9qgop;6ep;NegialarpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbglp9ograDczp:Segwp:Ueavczp:Reczp:SegDp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gvp;Kealp9oaiarawaDp:Uep:Xep;6ep;Meavp;Keczp:Rep9qgwaiaoaqcep:Rep9oaqpxebbbebbbebbbebbbp9op9qp;6ep;Meavp;Keczp:ReaiaDarp:Uep;6ep;Meavp;Kealp9op9qgipmwDKYqk8AExm35Ps8E8FpkbbabawaipmbezHdiOAlvCXorQLpkbbabcafhbadclfgdae6mbkkk9teiucbcbydj:G:cjbgeabcifc98GfgbBdj:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkxebcj:Gdklz:zbb'; // embed! simd
+
+ var detector = new Uint8Array([
+ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0,
+ 11, 7, 0, 65, 0, 253, 15, 26, 11,
+ ]);
+ var wasmpack = new Uint8Array([
+ 32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67,
+ 24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115,
+ ]);
+
+ if (typeof WebAssembly !== 'object') {
+ return {
+ supported: false,
+ };
+ }
+
+ var wasm = WebAssembly.validate(detector) ? unpack(wasm_simd) : unpack(wasm_base);
+
+ var instance;
+
+ var ready = WebAssembly.instantiate(wasm, {}).then(function (result) {
+ instance = result.instance;
+ instance.exports.__wasm_call_ctors();
+ });
+
+ function unpack(data) {
+ var result = new Uint8Array(data.length);
+ for (var i = 0; i < data.length; ++i) {
+ var ch = data.charCodeAt(i);
+ result[i] = ch > 96 ? ch - 97 : ch > 64 ? ch - 39 : ch + 4;
+ }
+ var write = 0;
+ for (var i = 0; i < data.length; ++i) {
+ result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
+ }
+ return result.buffer.slice(0, write);
+ }
+
+ function decode(instance, fun, target, count, size, source, filter) {
+ var sbrk = instance.exports.sbrk;
+ var count4 = (count + 3) & ~3;
+ var tp = sbrk(count4 * size);
+ var sp = sbrk(source.length);
+ var heap = new Uint8Array(instance.exports.memory.buffer);
+ heap.set(source, sp);
+ var res = fun(tp, count, size, sp, source.length);
+ if (res == 0 && filter) {
+ filter(tp, count4, size);
+ }
+ target.set(heap.subarray(tp, tp + count * size));
+ sbrk(tp - sbrk(0));
+ if (res != 0) {
+ throw new Error('Malformed buffer data: ' + res);
+ }
+ }
+
+ var filters = {
+ NONE: '',
+ OCTAHEDRAL: 'meshopt_decodeFilterOct',
+ QUATERNION: 'meshopt_decodeFilterQuat',
+ EXPONENTIAL: 'meshopt_decodeFilterExp',
+ COLOR: 'meshopt_decodeFilterColor',
+ };
+
+ var decoders = {
+ ATTRIBUTES: 'meshopt_decodeVertexBuffer',
+ TRIANGLES: 'meshopt_decodeIndexBuffer',
+ INDICES: 'meshopt_decodeIndexSequence',
+ };
+
+ var workers = [];
+ var requestId = 0;
+
+ function createWorker(url) {
+ var worker = {
+ object: new Worker(url),
+ pending: 0,
+ requests: {},
+ };
+
+ worker.object.onmessage = function (event) {
+ var data = event.data;
+
+ worker.pending -= data.count;
+ worker.requests[data.id][data.action](data.value);
+ delete worker.requests[data.id];
+ };
+
+ return worker;
+ }
+
+ function initWorkers(count) {
+ var source =
+ 'self.ready = WebAssembly.instantiate(new Uint8Array([' +
+ new Uint8Array(wasm) +
+ ']), {})' +
+ '.then(function(result) { result.instance.exports.__wasm_call_ctors(); return result.instance; });' +
+ 'self.onmessage = ' +
+ workerProcess.name +
+ ';' +
+ decode.toString() +
+ workerProcess.toString();
+
+ var blob = new Blob([source], { type: 'text/javascript' });
+ var url = URL.createObjectURL(blob);
+
+ for (var i = workers.length; i < count; ++i) {
+ workers[i] = createWorker(url);
+ }
+
+ for (var i = count; i < workers.length; ++i) {
+ workers[i].object.postMessage({});
+ }
+
+ workers.length = count;
+
+ URL.revokeObjectURL(url);
+ }
+
+ function decodeWorker(count, size, source, mode, filter) {
+ var worker = workers[0];
+
+ for (var i = 1; i < workers.length; ++i) {
+ if (workers[i].pending < worker.pending) {
+ worker = workers[i];
+ }
+ }
+
+ return new Promise(function (resolve, reject) {
+ var data = new Uint8Array(source);
+ var id = ++requestId;
+
+ worker.pending += count;
+ worker.requests[id] = { resolve: resolve, reject: reject };
+ worker.object.postMessage({ id: id, count: count, size: size, source: data, mode: mode, filter: filter }, [data.buffer]);
+ });
+ }
+
+ function workerProcess(event) {
+ var data = event.data;
+ self.ready.then(function (instance) {
+ if (!data.id) {
+ return self.close();
+ }
+ try {
+ var target = new Uint8Array(data.count * data.size);
+ decode(instance, instance.exports[data.mode], target, data.count, data.size, data.source, instance.exports[data.filter]);
+ self.postMessage({ id: data.id, count: data.count, action: 'resolve', value: target }, [target.buffer]);
+ } catch (error) {
+ self.postMessage({ id: data.id, count: data.count, action: 'reject', value: error });
+ }
+ });
+ }
+
+ return {
+ ready: ready,
+ supported: true,
+ useWorkers: function (count) {
+ initWorkers(count);
+ },
+ decodeVertexBuffer: function (target, count, size, source, filter) {
+ decode(instance, instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
+ },
+ decodeIndexBuffer: function (target, count, size, source) {
+ decode(instance, instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
+ },
+ decodeIndexSequence: function (target, count, size, source) {
+ decode(instance, instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
+ },
+ decodeGltfBuffer: function (target, count, size, source, mode, filter) {
+ decode(instance, instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
+ },
+ decodeGltfBufferAsync: function (count, size, source, mode, filter) {
+ if (workers.length > 0) {
+ return decodeWorker(count, size, source, decoders[mode], filters[filter]);
+ }
+
+ return ready.then(function () {
+ var target = new Uint8Array(count * size);
+ decode(instance, instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
+ return target;
+ });
+ },
+ };
+})();
+
+if (typeof exports === 'object' && typeof module === 'object') module.exports = MeshoptDecoder;
+else if (typeof define === 'function' && define['amd']) define([], function () { return MeshoptDecoder; });
+else if (typeof exports === 'object') exports['MeshoptDecoder'] = MeshoptDecoder;
+else (typeof self !== 'undefined' ? self : this).MeshoptDecoder = MeshoptDecoder;
diff --git a/scripts/build-previews.mjs b/scripts/build-previews.mjs
new file mode 100644
index 00000000..98bffa1d
--- /dev/null
+++ b/scripts/build-previews.mjs
@@ -0,0 +1,357 @@
+#!/usr/bin/env node
+/**
+ * Builds the preset cards' preview media (camera motions, effects, apps) from rendered masters: a
+ * poster still and a short muted loop per preset, with content-hashed names, plus the manifest the
+ * cards read them from (previewFor() in src/lib/preset-card-data.ts → `media` on each card's preview;
+ * src/lib/preview-media.ts names the files).
+ *
+ * Masters stay outside the repo, one folder per preset id:
+ * <masters>/<preset id>/clip.mp4 the rendered clip (any size, centre-cropped to 4:3; audio is dropped)
+ * <masters>/<preset id>/meta.json optional: {"posterTime": seconds, "kind": "wipe" | "motion" | …}
+ * Folders without a clip.mp4 (still rendering) are skipped; start.png, end.png and the other render
+ * inputs next to the clip aren't read. With --stills, a folder without a clip.mp4 but with a start.png
+ * gets a poster-only entry (a "still": the AVIF sizes and the WebP, no mp4), listed in the manifest as
+ * its hash plus "s" (isStill() in src/lib/preview-media.ts), so the site shows the picture until the clip lands.
+ *
+ * Output, for every id with a clip (kind = motions | effects | apps, from the id's prefix):
+ * public/previews/<kind>/<id>.<hash8>.<320|480|640>.avif the poster
+ * public/previews/<kind>/<id>.<hash8>.480.webp the poster for browsers without AVIF
+ * public/previews/<kind>/<id>.<hash8>.mp4 480×360 H.264, 24 fps, no audio, loops seamlessly
+ * src/lib/catalog/preview-media.generated.json { "<kind>": { "<id>": "<hash8>" } }, keys sorted
+ *
+ * The poster is the clip's frame at meta.posterTime (else at 62 % of the clip); the clip's last frames
+ * are crossfaded into its first ones, so the loop has no seam. hash8 is the first 8 hex digits of the
+ * SHA-256 of the master files read and of the encode recipe below (its settings and the code that
+ * applies them), so a new master or recipe gets new names (public/previews is served as immutable,
+ * see next.config.ts; a recipe change renames every preset's files). Unchanged masters are skipped, a
+ * rebuilt id loses its old files, and the manifest lists every id whose files are all in
+ * public/previews: delete an id's files and run again to drop it.
+ *
+ * Run: node scripts/build-previews.mjs --masters <dir> [--stills] (or set FUOBE_PREVIEW_MASTERS; --jobs N in parallel)
+ * Needs ffmpeg and ffprobe on PATH, built with libx264, libaom and libwebp.
+ */
+import { spawn } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseArgs } from "node:util";
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const OUT = path.join(root, "public", "previews");
+const MANIFEST = path.join(root, "src", "lib", "catalog", "preview-media.generated.json");
+
+/** Preset id prefix → folder under public/previews (kindOf() in src/lib/preview-media.ts is the same rule). */
+const KINDS = { motion: "motions", effect: "effects", app: "apps" };
+
+const FPS = 24;
+const W = 480;
+const H = 360;
+/** Poster widths (AVIF); the WebP fallback is 480 wide. previewSrc() in src/lib/preview-media.ts expects these. */
+const POSTER_WIDTHS = [320, 480, 640];
+const WEBP_WIDTH = 480;
+/** Frames at the end of the clip crossfaded into its first ones. */
+const LOOP_FADE = 6;
+/** Where the poster is taken when meta.json doesn't say, as a share of the clip. */
+const POSTER_AT = 0.62;
+/** Longer masters are cut here (cards loop 3–4 s). */
+const MAX_SECONDS = 6;
+/** The media spec's budget for one 4:3 card (posters + clip), for the summary. */
+const BUDGET_KB = 162;
+
+// The clip is BT.709 (limited range). AVIF posters are tagged sRGB with a BT.709 matrix (full range),
+// so they render like the WebP one, which is always BT.601 limited range.
+const X264 = ["-c:v", "libx264", "-preset", "veryslow", "-profile:v", "high", "-pix_fmt", "yuv420p", "-crf", "27", "-maxrate", "700k", "-bufsize", "1400k", "-g", "48"];
+const VIDEO_COLOR = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv"];
+const AVIF_SCALE = "out_color_matrix=bt709:out_range=pc,format=yuv420p,setparams=color_primaries=bt709:color_trc=iec61966-2-1";
+const WEBP_SCALE = "out_color_matrix=bt601:out_range=tv,format=yuv420p";
+const AVIF = ["-c:v", "libaom-av1", "-still-picture", "1", "-crf", "32", "-b:v", "0", "-cpu-used", "4"];
+const WEBP = ["-c:v", "libwebp", "-quality", "78", "-compression_level", "6"];
+/**
+ * Everything that shapes the files, hashed with the masters so a new recipe gets new names: the
+ * settings above and the functions that apply them (keep anything else that shapes the files in one
+ * of these). Their source is hashed with LF line ends, so a CRLF checkout gets the same names.
+ */
+const CODE = [probe, posterAt, posters, seamless, loop].map((f) => String(f).replace(/\r\n/g, "\n"));
+const RECIPE = JSON.stringify({ FPS, W, H, POSTER_WIDTHS, WEBP_WIDTH, LOOP_FADE, POSTER_AT, MAX_SECONDS, X264, VIDEO_COLOR, AVIF_SCALE, WEBP_SCALE, AVIF, WEBP, CODE });
+
+const USAGE = "usage: node scripts/build-previews.mjs --masters <dir> [--stills] [--jobs N] (or set FUOBE_PREVIEW_MASTERS)";
+let opts;
+try {
+ opts = parseArgs({ options: { masters: { type: "string" }, jobs: { type: "string" }, stills: { type: "boolean" } } }).values;
+} catch (e) {
+ console.error(`${e instanceof Error ? e.message : e}\n${USAGE}`);
+ process.exit(2);
+}
+const masters = opts.masters ?? process.env.FUOBE_PREVIEW_MASTERS;
+if (!masters || !fs.statSync(masters, { throwIfNoEntry: false })?.isDirectory()) {
+ console.error(`${USAGE}${masters ? `\nno such folder: ${masters}` : ""}`);
+ process.exit(2);
+}
+const jobs = Math.max(1, Number(opts.jobs) || Math.min(4, Math.ceil(os.availableParallelism() / 4)));
+
+/** The files of one preset's media (a still has no mp4). */
+const filesOf = (id, hash, still = false) => [...POSTER_WIDTHS.map((w) => `${id}.${hash}.${w}.avif`), `${id}.${hash}.${WEBP_WIDTH}.webp`, ...(still ? [] : [`${id}.${hash}.mp4`])];
+const sizeOf = (file) => fs.statSync(file, { throwIfNoEntry: false })?.size ?? 0;
+const kb = (bytes) => Math.round(bytes / 1024);
+
+/** Run a command; resolves with its stdout, rejects with the end of its stderr. */
+function run(cmd, args, input) {
+ return new Promise((resolve, reject) => {
+ const p = spawn(cmd, args, { stdio: [input ? "pipe" : "ignore", "pipe", "pipe"], windowsHide: true });
+ const out = [];
+ const err = [];
+ p.stdout.on("data", (d) => out.push(d));
+ p.stderr.on("data", (d) => err.push(d));
+ p.on("error", reject);
+ p.on("close", (code) => {
+ if (code === 0) resolve(Buffer.concat(out));
+ else reject(new Error(`${cmd} exited with ${code}: ${Buffer.concat(err).toString().trim().split(/\r?\n/).slice(-2).join(" | ")}`));
+ });
+ if (input) {
+ p.stdin.on("error", () => {}); // the close handler reports a failed run
+ p.stdin.end(input);
+ }
+ });
+}
+
+async function probe(file) {
+ const j = JSON.parse((await run("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=duration:format=duration", "-of", "json", file])).toString());
+ if (!j.streams?.length) throw new Error("no video stream");
+ const duration = Number(j.streams[0].duration ?? j.format?.duration);
+ if (!(duration > 0)) throw new Error("unknown duration");
+ return { duration: Math.min(duration, MAX_SECONDS), cut: duration > MAX_SECONDS + 0.05 };
+}
+
+/** Where the poster is taken, in seconds: meta.posterTime, else POSTER_AT of the clip, kept inside the clip. */
+function posterAt(meta, duration) {
+ const wanted = Number.isFinite(meta.posterTime) ? meta.posterTime : duration * POSTER_AT;
+ return Math.min(Math.max(0, wanted), Math.max(0, duration - 1 / FPS));
+}
+
+/** The poster at `at` seconds: one decode, split into the AVIF sizes and the WebP. */
+async function posters(clip, at, parts) {
+ const outs = [...POSTER_WIDTHS.map((w) => ["avif", w]), ["webp", WEBP_WIDTH]];
+ const scale = (fmt, w) => `scale=${w}:${(w * 3) / 4}:flags=lanczos:${fmt === "avif" ? AVIF_SCALE : WEBP_SCALE}`;
+ const graph = `[0:v]crop='min(iw,ih*4/3)':'min(ih,iw*3/4)',split=${outs.length}${outs.map((_, i) => `[s${i}]`).join("")};${outs.map(([fmt, w], i) => `[s${i}]${scale(fmt, w)}[o${i}]`).join(";")}`;
+ await run("ffmpeg", [
+ "-v", "error", "-y", "-ss", at.toFixed(3), "-i", clip, "-filter_complex", graph,
+ ...outs.flatMap(([fmt], i) => ["-map", `[o${i}]`, "-frames:v", "1", ...(fmt === "avif" ? AVIF : WEBP), "-map_metadata", "-1", "-f", fmt, parts[i]]),
+ ]);
+}
+
+/**
+ * A loop without a seam: the first `fade` frames are dropped from the start and blended into the
+ * last `fade` frames instead, so the clip's end runs into its new beginning.
+ */
+function seamless(raw, n, size, fade) {
+ if (!fade) return raw.subarray(0, n * size);
+ const out = Buffer.allocUnsafe((n - fade) * size);
+ raw.copy(out, 0, fade * size, (n - fade) * size);
+ for (let k = 0; k < fade; k++) {
+ const a = (k + 1) / (fade + 1);
+ const tail = (n - fade + k) * size;
+ const head = k * size;
+ const to = (n - 2 * fade + k) * size;
+ for (let i = 0; i < size; i++) out[to + i] = Math.round(raw[tail + i] * (1 - a) + raw[head + i] * a);
+ }
+ return out;
+}
+
+/** The clip: decoded to 480×360 frames at 24 fps, looped, encoded without audio. */
+async function loop(clip, part) {
+ const size = W * H * 1.5;
+ const raw = await run("ffmpeg", [
+ "-v", "error", "-i", clip, "-t", String(MAX_SECONDS), "-an", "-sn", "-dn",
+ "-vf", `fps=${FPS},scale=${W}:${H}:force_original_aspect_ratio=increase:flags=lanczos:out_color_matrix=bt709:out_range=tv,crop=${W}:${H},setsar=1,format=yuv420p`,
+ "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
+ ]);
+ const n = Math.floor(raw.length / size);
+ if (n < 2) throw new Error("the clip has no frames");
+ const fade = Math.min(LOOP_FADE, Math.floor(n / 4));
+ await run(
+ "ffmpeg",
+ ["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", `${W}x${H}`, "-r", String(FPS), ...VIDEO_COLOR, "-i", "-", ...X264, "-an", "-map_metadata", "-1", "-movflags", "+faststart", "-f", "mp4", part],
+ seamless(raw, n, size, fade),
+ );
+ return (n - fade) / FPS;
+}
+
+/** Remove an id's files other than `keep` (older hashes, parts of a run that died). */
+function removeStale(dir, id, keep) {
+ let removed = 0;
+ for (const f of fs.existsSync(dir) ? fs.readdirSync(dir) : []) {
+ if (f.startsWith(`${id}.`) && !keep.includes(f)) {
+ fs.rmSync(path.join(dir, f), { force: true });
+ removed++;
+ }
+ }
+ return removed;
+}
+
+/** The master files a preset's media is made from: the clip, and meta.json when there is one. */
+function readMaster(dir) {
+ const used = ["clip.mp4", "meta.json"].map((f) => path.join(dir, f)).filter((f) => fs.existsSync(f));
+ const meta = used.length > 1 ? JSON.parse(fs.readFileSync(used[1], "utf8").replace(/^/, "")) : {};
+ const sha = crypto.createHash("sha256").update(RECIPE);
+ for (const f of used) sha.update(`\0${path.basename(f)}\0`).update(fs.readFileSync(f));
+ return { clip: used[0], meta: meta && typeof meta === "object" ? meta : {}, hash: sha.digest("hex").slice(0, 8) };
+}
+
+/** A still's master: start.png, hashed with the recipe (and a marker, so a still never shares a clip's names). */
+function readStill(dir) {
+ const file = path.join(dir, "start.png");
+ const hash = crypto.createHash("sha256").update(RECIPE).update("\0still\0").update(fs.readFileSync(file)).digest("hex").slice(0, 8);
+ return { file, hash };
+}
+
+/** A poster-only entry from start.png (no clip yet). */
+async function buildStill({ id, kind, dir }) {
+ const outDir = path.join(OUT, kind);
+ let master;
+ try {
+ master = readStill(dir);
+ } catch (e) {
+ return { id, kind, hash: "--------", files: [], still: true, status: "failed", error: `can't read start.png: ${e instanceof Error ? e.message : e}` };
+ }
+ const names = filesOf(id, master.hash, true);
+ const files = names.map((f) => path.join(outDir, f));
+ const result = { id, kind, hash: master.hash, meta: {}, files, still: true };
+ if (files.every((f) => sizeOf(f) > 0)) return { ...result, status: "unchanged", stale: removeStale(outDir, id, names) };
+ fs.mkdirSync(outDir, { recursive: true });
+ const parts = files.map((f) => `${f}.part`);
+ try {
+ await posters(master.file, 0, parts);
+ for (const p of parts) if (!(sizeOf(p) > 0)) throw new Error(`ffmpeg wrote nothing to ${path.basename(p)}`);
+ parts.forEach((p, i) => fs.renameSync(p, files[i]));
+ return { ...result, status: "built", stale: removeStale(outDir, id, names) };
+ } catch (e) {
+ for (const p of parts) fs.rmSync(p, { force: true });
+ return { ...result, status: "failed", error: e instanceof Error ? e.message : String(e) };
+ }
+}
+
+async function build({ id, kind, dir }) {
+ const outDir = path.join(OUT, kind);
+ let master;
+ try {
+ master = readMaster(dir);
+ } catch (e) {
+ return { id, kind, hash: "--------", files: [], status: "failed", error: `can't read the master: ${e instanceof Error ? e.message : e}` };
+ }
+ const { clip, meta, hash } = master;
+ const names = filesOf(id, hash);
+ const files = names.map((f) => path.join(outDir, f));
+ const result = { id, kind, hash, meta, files };
+ if (files.every((f) => sizeOf(f) > 0)) return { ...result, status: "unchanged", stale: removeStale(outDir, id, names) };
+
+ fs.mkdirSync(outDir, { recursive: true });
+ const parts = files.map((f) => `${f}.part`);
+ try {
+ const { duration, cut } = await probe(clip);
+ const at = posterAt(meta, duration);
+ // Both ffmpeg runs end before the catch cleans up: when one fails, the other would still be writing
+ // its .part (left behind in public/previews, or on Windows still open, so removing it throws).
+ const [poster, clipRun] = await Promise.allSettled([posters(clip, at, parts.slice(0, -1)), loop(clip, parts.at(-1))]);
+ for (const r of [poster, clipRun]) if (r.status === "rejected") throw r.reason;
+ const seconds = clipRun.value;
+ for (const p of parts) if (!(sizeOf(p) > 0)) throw new Error(`ffmpeg wrote nothing to ${path.basename(p)}`);
+ parts.forEach((p, i) => fs.renameSync(p, files[i]));
+ return { ...result, status: "built", seconds, at, cut, stale: removeStale(outDir, id, names) };
+ } catch (e) {
+ for (const p of parts) fs.rmSync(p, { force: true });
+ return { ...result, status: "failed", error: e instanceof Error ? e.message : String(e) };
+ }
+}
+
+/** Every id whose files are all in public/previews, by kind; `prefer` picks between two complete sets. */
+function scan(prefer) {
+ const manifest = {};
+ for (const kind of Object.values(KINDS).sort()) {
+ const dir = path.join(OUT, kind);
+ if (!fs.existsSync(dir)) continue;
+ const hashes = new Map();
+ const stills = new Map();
+ const names = fs.readdirSync(dir);
+ for (const f of names) {
+ const m = /^([a-z0-9-]+)\.([0-9a-f]{8})\.mp4$/.exec(f);
+ if (m && kindOf(m[1]) === kind) hashes.set(m[1], [...(hashes.get(m[1]) ?? []), m[2]]);
+ const s = /^([a-z0-9-]+)\.([0-9a-f]{8})\.480\.webp$/.exec(f);
+ if (s && kindOf(s[1]) === kind && !names.includes(`${s[1]}.${s[2]}.mp4`)) stills.set(s[1], [...(stills.get(s[1]) ?? []), s[2]]);
+ }
+ const ids = {};
+ // Stills first; a preset with a complete clip set is listed below with it instead.
+ for (const id of [...stills.keys()].sort()) {
+ const complete = stills.get(id).filter((h) => filesOf(id, h, true).every((f) => sizeOf(path.join(dir, f)) > 0));
+ if (!complete.length) continue;
+ const mtime = (h) => fs.statSync(path.join(dir, `${id}.${h}.480.webp`)).mtimeMs;
+ const pick = complete.find((h) => `${h}s` === prefer(kind, id)) ?? complete.sort((a, b) => mtime(b) - mtime(a))[0];
+ ids[id] = `${pick}s`;
+ }
+ for (const id of [...hashes.keys()].sort()) {
+ const complete = hashes.get(id).filter((h) => filesOf(id, h).every((f) => sizeOf(path.join(dir, f)) > 0));
+ if (!complete.length) continue;
+ const mtime = (h) => fs.statSync(path.join(dir, `${id}.${h}.mp4`)).mtimeMs;
+ const pick = complete.find((h) => h === prefer(kind, id)) ?? complete.sort((a, b) => mtime(b) - mtime(a))[0];
+ if (complete.length > 1) console.warn(` note ${id}: ${complete.length} complete sets in public/previews/${kind}, listing ${pick}`);
+ ids[id] = pick;
+ }
+ if (Object.keys(ids).length) manifest[kind] = Object.fromEntries(Object.entries(ids).sort(([a], [b]) => (a < b ? -1 : 1)));
+ }
+ return manifest;
+}
+
+const folders = fs.readdirSync(masters, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
+const withClip = folders.filter((id) => fs.existsSync(path.join(masters, id, "clip.mp4")));
+const kindOf = (id) => KINDS[/^(motion|effect|app)-[a-z0-9-]+$/.exec(id)?.[1]];
+const stillOnly = opts.stills ? folders.filter((id) => !withClip.includes(id) && fs.existsSync(path.join(masters, id, "start.png"))) : [];
+const cards = [
+ ...withClip.filter(kindOf).map((id) => ({ id, kind: kindOf(id), dir: path.join(masters, id) })),
+ ...stillOnly.filter(kindOf).map((id) => ({ id, kind: kindOf(id), dir: path.join(masters, id), still: true })),
+];
+console.log(`${folders.length} master folders in ${masters}, ${withClip.length} with a clip.mp4${opts.stills ? `, ${stillOnly.length} stills (start.png only)` : ""} (${jobs} at a time)`);
+for (const id of withClip.filter((id) => !kindOf(id))) console.warn(` skipped ${id}: not a motion-, effect- or app- preset id`);
+
+const results = [];
+const queue = [...cards];
+await Promise.all(
+ Array.from({ length: jobs }, async () => {
+ for (let card = queue.shift(); card; card = queue.shift()) {
+ const r = await (card.still ? buildStill(card) : build(card));
+ results.push(r);
+ const sizes = r.files.map(sizeOf);
+ const sum = kb(sizes.reduce((a, b) => a + b, 0));
+ const detail =
+ r.status === "failed"
+ ? r.error
+ : `avif ${sizes.slice(0, 3).map(kb).join("/")} KB · webp ${kb(sizes[3])} KB${r.still ? " · still" : ` · mp4 ${kb(sizes[4])} KB`}` +
+ (r.seconds ? ` (${r.seconds.toFixed(2)} s loop, poster at ${r.at.toFixed(2)} s${r.cut ? `, cut to ${MAX_SECONDS} s` : ""})` : "") +
+ ` = ${sum} KB${sum > BUDGET_KB ? ` (over the ~${BUDGET_KB} KB budget)` : ""}`;
+ console.log(` ${r.status.padEnd(10)} ${r.id.padEnd(36)} ${r.hash}${r.meta?.kind ? ` ${r.meta.kind}` : ""} ${detail}`);
+ }
+ }),
+);
+
+const built = new Map(results.filter((r) => r.status !== "failed").map((r) => [`${r.kind}/${r.id}`, r.still ? `${r.hash}s` : r.hash]));
+let previous = {};
+try {
+ previous = JSON.parse(fs.readFileSync(MANIFEST, "utf8"));
+} catch {
+ // first run
+}
+const manifest = scan((kind, id) => built.get(`${kind}/${id}`) ?? previous[kind]?.[id]);
+const text = `${JSON.stringify(manifest, null, 2)}\n`;
+// A checkout may have turned the manifest's line ends into CRLF: that's not a change.
+const changed = !fs.existsSync(MANIFEST) || fs.readFileSync(MANIFEST, "utf8").replace(/\r\n/g, "\n") !== text;
+if (changed) fs.writeFileSync(MANIFEST, text);
+
+const count = (s) => results.filter((r) => r.status === s).length;
+const listed = Object.values(manifest).flatMap((ids) => Object.entries(ids));
+const total = Object.entries(manifest).reduce((sum, [kind, ids]) => sum + Object.entries(ids).reduce((s, [id, h]) => s + filesOf(id, h.slice(0, 8), h.length > 8).reduce((t, f) => t + sizeOf(path.join(OUT, kind, f)), 0), 0), 0);
+console.log(
+ `built ${count("built")}, unchanged ${count("unchanged")}, failed ${count("failed")}, removed ${results.reduce((s, r) => s + (r.stale ?? 0), 0)} stale files\n` +
+ `manifest ${changed ? "written" : "unchanged"}: ${Object.values(KINDS).map((k) => `${Object.keys(manifest[k] ?? {}).length} ${k}`).join(" · ")} → ${path.relative(root, MANIFEST)}\n` +
+ `public/previews: ${listed.length} presets, ${kb(total)} KB${listed.length ? ` (${kb(total / listed.length)} KB each on average, budget ~${BUDGET_KB} KB)` : ""}`,
+);
+if (count("failed")) process.exitCode = 1;
diff --git a/scripts/comfy/hand-built/image-to-3d-pixal3d.json b/scripts/comfy/hand-built/image-to-3d-pixal3d.json
new file mode 100644
index 00000000..8ab58da5
--- /dev/null
+++ b/scripts/comfy/hand-built/image-to-3d-pixal3d.json
@@ -0,0 +1,737 @@
+{
+ "3": {
+ "inputs": {
+ "seed": 56,
+ "steps": 12,
+ "cfg": 7.5,
+ "sampler_name": "euler",
+ "scheduler": "normal",
+ "denoise": 1,
+ "model": [
+ "108",
+ 0
+ ],
+ "positive": [
+ "298",
+ 0
+ ],
+ "negative": [
+ "298",
+ 1
+ ],
+ "latent_image": [
+ "87",
+ 0
+ ]
+ },
+ "class_type": "KSampler",
+ "_meta": {
+ "title": "KSampler"
+ }
+ },
+ "12": {
+ "inputs": {
+ "seed": 43,
+ "steps": 12,
+ "cfg": 1,
+ "sampler_name": "euler",
+ "scheduler": "normal",
+ "denoise": 1,
+ "model": [
+ "319",
+ 0
+ ],
+ "positive": [
+ "98",
+ 0
+ ],
+ "negative": [
+ "98",
+ 1
+ ],
+ "latent_image": [
+ "98",
+ 2
+ ]
+ },
+ "class_type": "KSampler",
+ "_meta": {
+ "title": "KSampler"
+ }
+ },
+ "15": {
+ "inputs": {
+ "clip_name": "dino_v3_L_naf_fp32.safetensors"
+ },
+ "class_type": "CLIPVisionLoader",
+ "_meta": {
+ "title": "Load CLIP Vision"
+ }
+ },
+ "18": {
+ "inputs": {
+ "seed": 42,
+ "steps": 20,
+ "cfg": 7.5,
+ "sampler_name": "euler",
+ "scheduler": "normal",
+ "denoise": 1,
+ "model": [
+ "126",
+ 0
+ ],
+ "positive": [
+ "91",
+ 0
+ ],
+ "negative": [
+ "91",
+ 1
+ ],
+ "latent_image": [
+ "91",
+ 2
+ ]
+ },
+ "class_type": "KSampler",
+ "_meta": {
+ "title": "KSampler"
+ }
+ },
+ "23": {
+ "inputs": {
+ "seed": 42,
+ "steps": 12,
+ "cfg": 7.5,
+ "sampler_name": "euler",
+ "scheduler": "simple",
+ "denoise": 1,
+ "model": [
+ "126",
+ 0
+ ],
+ "positive": [
+ "94",
+ 0
+ ],
+ "negative": [
+ "94",
+ 1
+ ],
+ "latent_image": [
+ "94",
+ 2
+ ]
+ },
+ "class_type": "KSampler",
+ "_meta": {
+ "title": "KSampler"
+ }
+ },
+ "55": {
+ "inputs": {
+ "model_name": "moge_2_vitl_normal_fp16.safetensors"
+ },
+ "class_type": "LoadMoGeModel",
+ "_meta": {
+ "title": "Load MoGe Model"
+ }
+ },
+ "56": {
+ "inputs": {
+ "resolution_level": 9,
+ "fov_x_degrees": 0,
+ "batch_size": 4,
+ "force_projection": true,
+ "apply_mask": true,
+ "refine_steps": 3,
+ "moge_model": [
+ "55",
+ 0
+ ],
+ "image": [
+ "312",
+ 0
+ ]
+ },
+ "class_type": "MoGeInference",
+ "_meta": {
+ "title": "Run MoGe Inference"
+ }
+ },
+ "87": {
+ "inputs": {
+ "batch_size": 1
+ },
+ "class_type": "EmptyTrellis2LatentStructure",
+ "_meta": {
+ "title": "Empty Trellis2 Latent Structure"
+ }
+ },
+ "91": {
+ "inputs": {
+ "positive": [
+ "298",
+ 0
+ ],
+ "negative": [
+ "298",
+ 1
+ ],
+ "voxel": [
+ "119",
+ 0
+ ]
+ },
+ "class_type": "Trellis2ShapeStage",
+ "_meta": {
+ "title": "Trellis2 Shape Stage"
+ }
+ },
+ "92": {
+ "inputs": {
+ "samples": [
+ "23",
+ 0
+ ],
+ "vae": [
+ "117",
+ 0
+ ]
+ },
+ "class_type": "VaeDecodeShapeTrellis",
+ "_meta": {
+ "title": "Trellis2 VAE Decode Shape"
+ }
+ },
+ "93": {
+ "inputs": {
+ "samples": [
+ "12",
+ 0
+ ],
+ "vae": [
+ "118",
+ 0
+ ],
+ "shape_subdivides": [
+ "92",
+ 1
+ ]
+ },
+ "class_type": "VaeDecodeTextureTrellis",
+ "_meta": {
+ "title": "Trellis2 VAE Decode Texture"
+ }
+ },
+ "94": {
+ "inputs": {
+ "target_resolution": 1536,
+ "positive": [
+ "91",
+ 0
+ ],
+ "negative": [
+ "91",
+ 1
+ ],
+ "shape_latent": [
+ "18",
+ 0
+ ],
+ "vae": [
+ "117",
+ 0
+ ]
+ },
+ "class_type": "Trellis2UpsampleStage",
+ "_meta": {
+ "title": "Trellis2 Upsample Stage"
+ }
+ },
+ "98": {
+ "inputs": {
+ "positive": [
+ "94",
+ 0
+ ],
+ "negative": [
+ "94",
+ 1
+ ],
+ "shape_latent": [
+ "23",
+ 0
+ ]
+ },
+ "class_type": "Trellis2TextureStage",
+ "_meta": {
+ "title": "Trellis2 Texture Stage"
+ }
+ },
+ "108": {
+ "inputs": {
+ "shift": 5,
+ "model": [
+ "125",
+ 0
+ ]
+ },
+ "class_type": "ModelSamplingSD3",
+ "_meta": {
+ "title": "ModelSamplingSD3"
+ }
+ },
+ "117": {
+ "inputs": {
+ "vae_name": "trellis_2_shape_vae_bf16.safetensors"
+ },
+ "class_type": "VAELoader",
+ "_meta": {
+ "title": "Load VAE"
+ }
+ },
+ "118": {
+ "inputs": {
+ "vae_name": "trellis_2_texture_vae_bf16.safetensors"
+ },
+ "class_type": "VAELoader",
+ "_meta": {
+ "title": "Load VAE"
+ }
+ },
+ "119": {
+ "inputs": {
+ "resolution": "32",
+ "samples": [
+ "3",
+ 0
+ ],
+ "vae": [
+ "117",
+ 0
+ ]
+ },
+ "class_type": "VaeDecodeStructureTrellis2",
+ "_meta": {
+ "title": "Trellis2 VAE Decode Structure"
+ }
+ },
+ "122": {
+ "inputs": {
+ "image": "product.png"
+ },
+ "class_type": "LoadImage",
+ "_meta": {
+ "title": "Load Image"
+ }
+ },
+ "125": {
+ "inputs": {
+ "multiplier": 0.7,
+ "model": [
+ "199",
+ 0
+ ]
+ },
+ "class_type": "RescaleCFG",
+ "_meta": {
+ "title": "RescaleCFG"
+ }
+ },
+ "126": {
+ "inputs": {
+ "multiplier": 0.5,
+ "model": [
+ "279",
+ 0
+ ]
+ },
+ "class_type": "RescaleCFG",
+ "_meta": {
+ "title": "RescaleCFG"
+ }
+ },
+ "147": {
+ "inputs": {
+ "texture_size": [
+ "288",
+ 0
+ ],
+ "mesh": [
+ "196",
+ 0
+ ],
+ "voxel_colors": [
+ "93",
+ 0
+ ],
+ "reference_mesh": [
+ "92",
+ 0
+ ]
+ },
+ "class_type": "BakeTextureFromVoxel",
+ "_meta": {
+ "title": "Bake Texture From Voxel"
+ }
+ },
+ "186": {
+ "inputs": {
+ "target_face_count": 250000,
+ "placement_mode": "midpoint",
+ "mesh": [
+ "241",
+ 0
+ ]
+ },
+ "class_type": "DecimateMesh",
+ "_meta": {
+ "title": "Decimate Mesh"
+ }
+ },
+ "192": {
+ "inputs": {
+ "bg_removal_model": [
+ "193",
+ 0
+ ],
+ "image": [
+ "122",
+ 0
+ ]
+ },
+ "class_type": "RemoveBackground",
+ "_meta": {
+ "title": "Remove Background"
+ }
+ },
+ "193": {
+ "inputs": {
+ "bg_removal_name": "birefnet.safetensors"
+ },
+ "class_type": "LoadBackgroundRemovalModel",
+ "_meta": {
+ "title": "Load Background Removal Model"
+ }
+ },
+ "196": {
+ "inputs": {
+ "segmenter": "pec",
+ "resolution": [
+ "288",
+ 0
+ ],
+ "padding": 1,
+ "weld_distance": 0.0002,
+ "mesh": [
+ "238",
+ 0
+ ]
+ },
+ "class_type": "UnwrapMesh",
+ "_meta": {
+ "title": "Unwrap Mesh UVs"
+ }
+ },
+ "199": {
+ "inputs": {
+ "cfg": 1,
+ "start_percent": 0.667,
+ "end_percent": 1,
+ "model": [
+ "319",
+ 0
+ ]
+ },
+ "class_type": "CFGOverride",
+ "_meta": {
+ "title": "CFG Override"
+ }
+ },
+ "202": {
+ "inputs": {
+ "mesh": [
+ "92",
+ 0
+ ]
+ },
+ "class_type": "GetMeshInfo",
+ "_meta": {
+ "title": "Get Mesh Info"
+ }
+ },
+ "210": {
+ "inputs": {
+ "mesh": [
+ "196",
+ 0
+ ],
+ "base_color": [
+ "147",
+ 0
+ ],
+ "metallic": [
+ "147",
+ 1
+ ],
+ "roughness": [
+ "147",
+ 2
+ ],
+ "occlusion": [
+ "233",
+ 0
+ ],
+ "normal_map": [
+ "224",
+ 0
+ ]
+ },
+ "class_type": "ApplyTextureToMesh",
+ "_meta": {
+ "title": "Apply Texture to Mesh"
+ }
+ },
+ "224": {
+ "inputs": {
+ "resolution": 2048,
+ "cage_distance": 0.05,
+ "ignore_backfaces": true,
+ "low_poly": [
+ "196",
+ 0
+ ],
+ "high_poly": [
+ "241",
+ 0
+ ]
+ },
+ "class_type": "BakeNormalMapFromMesh",
+ "_meta": {
+ "title": "Bake Normal Map from Mesh"
+ }
+ },
+ "233": {
+ "inputs": {
+ "resolution": 1024,
+ "samples": 64,
+ "max_distance": 0.71,
+ "strength": 1,
+ "bias": 0.01,
+ "low_poly": [
+ "196",
+ 0
+ ],
+ "high_poly": [
+ "241",
+ 0
+ ]
+ },
+ "class_type": "BakeAmbientOcclusion",
+ "_meta": {
+ "title": "Bake Ambient Occlusion"
+ }
+ },
+ "238": {
+ "inputs": {
+ "crease_angle": 180,
+ "mesh": [
+ "186",
+ 0
+ ]
+ },
+ "class_type": "MeshSmoothNormals",
+ "_meta": {
+ "title": "Smooth Mesh Normals"
+ }
+ },
+ "241": {
+ "inputs": {
+ "resolution": 768,
+ "sign_mode": "solid",
+ "sign_mode.fill": 20,
+ "sign_mode.qef": false,
+ "band": 1,
+ "project_back": 0,
+ "fix_poles": false,
+ "smooth_iters": 20,
+ "drop_small_components": 0.01,
+ "precluster_max_verts": 20000000,
+ "mesh": [
+ "202",
+ 0
+ ]
+ },
+ "class_type": "RemeshMesh",
+ "_meta": {
+ "title": "Remesh Mesh (Narrow-Band DC)"
+ }
+ },
+ "242": {
+ "inputs": {
+ "axis": "horizontal",
+ "unit": "degrees",
+ "moge_geometry": [
+ "56",
+ 0
+ ]
+ },
+ "class_type": "MoGeGeometryToFOV",
+ "_meta": {
+ "title": "Get FoV from MoGe Geometry"
+ }
+ },
+ "260": {
+ "inputs": {
+ "crease_angle": 180,
+ "mesh": [
+ "210",
+ 0
+ ]
+ },
+ "class_type": "MeshSmoothNormals",
+ "_meta": {
+ "title": "Smooth Mesh Normals"
+ }
+ },
+ "279": {
+ "inputs": {
+ "cfg": 1,
+ "start_percent": 0.769,
+ "end_percent": 1,
+ "model": [
+ "319",
+ 0
+ ]
+ },
+ "class_type": "CFGOverride",
+ "_meta": {
+ "title": "CFG Override"
+ }
+ },
+ "285": {
+ "inputs": {
+ "mesh": [
+ "260",
+ 0
+ ]
+ },
+ "class_type": "MeshToFile3D",
+ "_meta": {
+ "title": "Create 3D File (from Mesh)"
+ }
+ },
+ "288": {
+ "inputs": {
+ "value": 4096
+ },
+ "class_type": "PrimitiveInt",
+ "_meta": {
+ "title": "Texture Resolution"
+ }
+ },
+ "298": {
+ "inputs": {
+ "camera_angle_x": [
+ "242",
+ 0
+ ],
+ "clip_vision_model": [
+ "15",
+ 0
+ ],
+ "image": [
+ "312",
+ 0
+ ]
+ },
+ "class_type": "Pixal3DConditioning",
+ "_meta": {
+ "title": "Pixal3D Conditioning"
+ }
+ },
+ "312": {
+ "inputs": {
+ "width": 1024,
+ "height": 1024,
+ "pad_factor": 1.1,
+ "grow_mask": 0,
+ "background": "#000000",
+ "images": [
+ "122",
+ 0
+ ],
+ "masks": [
+ "192",
+ 0
+ ]
+ },
+ "class_type": "ImageCropToMask",
+ "_meta": {
+ "title": "Crop Image to Mask"
+ }
+ },
+ "319": {
+ "inputs": {
+ "unet_name": "pixal3d_int8_convrot.safetensors",
+ "weight_dtype": "default"
+ },
+ "class_type": "UNETLoader",
+ "_meta": {
+ "title": "Load Diffusion Model"
+ }
+ },
+ "322": {
+ "inputs": {
+ "filename_prefix": "fuobe/image-to-3d-pixal3d",
+ "viewport_state": {
+ "image": "",
+ "mask": "",
+ "normal": "",
+ "camera_info": {
+ "position": {
+ "x": 10,
+ "y": 10,
+ "z": 10.000000000000002
+ },
+ "target": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "zoom": 1,
+ "cameraType": "perspective",
+ "quaternion": {
+ "x": -0.2798481423331213,
+ "y": 0.3647051996310008,
+ "z": 0.11591689595929511,
+ "w": 0.8804762392171493
+ },
+ "fov": 35,
+ "aspect": 1,
+ "near": 0.01,
+ "far": 10000,
+ "frustum": {
+ "left": -5,
+ "right": 5,
+ "top": 5,
+ "bottom": -5
+ }
+ },
+ "recording": "",
+ "model_3d_info": []
+ },
+ "width": 1024,
+ "height": 1024,
+ "model_3d": [
+ "285",
+ 0
+ ]
+ },
+ "class_type": "Save3DAdvanced",
+ "_meta": {
+ "title": "Save 3D (Advanced)"
+ }
+ }
+}
diff --git a/scripts/comfy/hand-built/image-to-3d-trellis2.json b/scripts/comfy/hand-built/image-to-3d-trellis2.json
index 8f57c363..ef8f9076 100644
--- a/scripts/comfy/hand-built/image-to-3d-trellis2.json
+++ b/scripts/comfy/hand-built/image-to-3d-trellis2.json
@@ -205,7 +205,7 @@
},
"94": {
"inputs": {
- "target_resolution": "1536",
+ "target_resolution": 1536,
"positive": [
"91",
0
@@ -355,16 +355,18 @@
"title": "Bake Texture From Voxel"
}
},
- "164": {
+ "186": {
"inputs": {
- "images": [
- "147",
+ "target_face_count": 250000,
+ "placement_mode": "midpoint",
+ "mesh": [
+ "241",
0
]
},
- "class_type": "PreviewImage",
+ "class_type": "DecimateMesh",
"_meta": {
- "title": "Base Color"
+ "title": "Decimate Mesh"
}
},
"192": {
@@ -438,30 +440,6 @@
"title": "Get Mesh Info"
}
},
- "207": {
- "inputs": {
- "images": [
- "147",
- 1
- ]
- },
- "class_type": "PreviewImage",
- "_meta": {
- "title": "Metallic"
- }
- },
- "208": {
- "inputs": {
- "images": [
- "147",
- 2
- ]
- },
- "class_type": "PreviewImage",
- "_meta": {
- "title": "Roughness"
- }
- },
"210": {
"inputs": {
"mesh": [
@@ -469,23 +447,23 @@
0
],
"base_color": [
- "164",
+ "147",
0
],
"metallic": [
- "207",
- 0
+ "147",
+ 1
],
"roughness": [
- "208",
- 0
+ "147",
+ 2
],
"occlusion": [
- "235",
+ "233",
0
],
"normal_map": [
- "226",
+ "224",
0
]
},
@@ -513,18 +491,6 @@
"title": "Bake Normal Map from Mesh"
}
},
- "226": {
- "inputs": {
- "images": [
- "224",
- 0
- ]
- },
- "class_type": "PreviewImage",
- "_meta": {
- "title": "Normal"
- }
- },
"233": {
"inputs": {
"resolution": 1024,
@@ -546,23 +512,11 @@
"title": "Bake Ambient Occlusion"
}
},
- "235": {
- "inputs": {
- "images": [
- "233",
- 0
- ]
- },
- "class_type": "PreviewImage",
- "_meta": {
- "title": "Ambiant Occlusion"
- }
- },
"238": {
"inputs": {
"crease_angle": 180,
"mesh": [
- "241",
+ "186",
0
]
},
@@ -574,10 +528,9 @@
"241": {
"inputs": {
"resolution": 768,
- "sign_mode": "udf",
+ "sign_mode": "solid",
+ "sign_mode.fill": 20,
"sign_mode.qef": false,
- "sign_mode.drop_inverted_components": false,
- "sign_mode.drop_enclosed_components": false,
"band": 1,
"project_back": 0,
"fix_poles": false,
@@ -650,7 +603,7 @@
0
],
"image": [
- "302",
+ "312",
0
]
},
@@ -659,35 +612,11 @@
"title": "Trellis2 Conditioning"
}
},
- "302": {
- "inputs": {
- "images": [
- "312",
- 0
- ]
- },
- "class_type": "PreviewImage",
- "_meta": {
- "title": "Preview Image"
- }
- },
- "303": {
- "inputs": {
- "mask": [
- "192",
- 0
- ]
- },
- "class_type": "MaskPreview",
- "_meta": {
- "title": "Preview Mask"
- }
- },
"312": {
"inputs": {
"width": 1024,
"height": 1024,
- "pad_factor": 1.1,
+ "pad_factor": 1,
"grow_mask": 0,
"background": "#000000",
"images": [
@@ -695,7 +624,7 @@
0
],
"masks": [
- "303",
+ "192",
0
]
},
@@ -755,1341 +684,5 @@
"_meta": {
"title": "Save 3D (Advanced)"
}
- },
- "500": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 0.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "600": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "500",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "501": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 10.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "601": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "501",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "502": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 20.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "602": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "502",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "503": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 30.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "603": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "503",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "504": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 40.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "604": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "504",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "505": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 50.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "605": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "505",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "506": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 60.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "606": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "506",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "507": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 70.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "607": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "507",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "508": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 80.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "608": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "508",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "509": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 90.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "609": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "509",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "510": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 100.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "610": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "510",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "511": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 110.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "611": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "511",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "512": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 120.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "612": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "512",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "513": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 130.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "613": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "513",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "514": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 140.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "614": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "514",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "515": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 150.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "615": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "515",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "516": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 160.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "616": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "516",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "517": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 170.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "617": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "517",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "518": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 180.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "618": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "518",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "519": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 190.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "619": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "519",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "520": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 200.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "620": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "520",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "521": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 210.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "621": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "521",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "522": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 220.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "622": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "522",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "523": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 230.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "623": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "523",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "524": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 240.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "624": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "524",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "525": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 250.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "625": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "525",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "526": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 260.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "626": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "526",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "527": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 270.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "627": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "527",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "528": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 280.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "628": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "528",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "529": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 290.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "629": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "529",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "530": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 300.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "630": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "530",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "531": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 310.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "631": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "531",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "532": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 320.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "632": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "532",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "533": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 330.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "633": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "533",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "534": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 340.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "634": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "534",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "535": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0.0,
- "mode.angle_y": 350.0,
- "mode.angle_z": 0.0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "635": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "535",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "700": {
- "class_type": "BatchImagesNode",
- "inputs": {
- "images.image0": [
- "600",
- 0
- ],
- "images.image1": [
- "601",
- 0
- ],
- "images.image2": [
- "602",
- 0
- ],
- "images.image3": [
- "603",
- 0
- ],
- "images.image4": [
- "604",
- 0
- ],
- "images.image5": [
- "605",
- 0
- ],
- "images.image6": [
- "606",
- 0
- ],
- "images.image7": [
- "607",
- 0
- ],
- "images.image8": [
- "608",
- 0
- ],
- "images.image9": [
- "609",
- 0
- ],
- "images.image10": [
- "610",
- 0
- ],
- "images.image11": [
- "611",
- 0
- ],
- "images.image12": [
- "612",
- 0
- ],
- "images.image13": [
- "613",
- 0
- ],
- "images.image14": [
- "614",
- 0
- ],
- "images.image15": [
- "615",
- 0
- ],
- "images.image16": [
- "616",
- 0
- ],
- "images.image17": [
- "617",
- 0
- ],
- "images.image18": [
- "618",
- 0
- ],
- "images.image19": [
- "619",
- 0
- ],
- "images.image20": [
- "620",
- 0
- ],
- "images.image21": [
- "621",
- 0
- ],
- "images.image22": [
- "622",
- 0
- ],
- "images.image23": [
- "623",
- 0
- ],
- "images.image24": [
- "624",
- 0
- ],
- "images.image25": [
- "625",
- 0
- ],
- "images.image26": [
- "626",
- 0
- ],
- "images.image27": [
- "627",
- 0
- ],
- "images.image28": [
- "628",
- 0
- ],
- "images.image29": [
- "629",
- 0
- ],
- "images.image30": [
- "630",
- 0
- ],
- "images.image31": [
- "631",
- 0
- ],
- "images.image32": [
- "632",
- 0
- ],
- "images.image33": [
- "633",
- 0
- ],
- "images.image34": [
- "634",
- 0
- ],
- "images.image35": [
- "635",
- 0
- ]
- },
- "_meta": {
- "title": "BatchImagesNode"
- }
- },
- "701": {
- "class_type": "CreateVideo",
- "inputs": {
- "images": [
- "700",
- 0
- ],
- "fps": 12.0,
- "bit_depth": "auto",
- "color_space": "sRGB",
- "codec": "none"
- },
- "_meta": {
- "title": "CreateVideo"
- }
- },
- "702": {
- "class_type": "SaveVideo",
- "inputs": {
- "video": [
- "701",
- 0
- ],
- "filename_prefix": "fuobe/image-to-3d-trellis2-turntable",
- "format": "auto",
- "format.codec": "auto",
- "codec": "auto"
- },
- "_meta": {
- "title": "SaveVideo"
- }
}
}
diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjs
index f34366dd..0f22d221 100644
--- a/scripts/comfy/library.spec.mjs
+++ b/scripts/comfy/library.spec.mjs
@@ -2296,20 +2296,31 @@ export const SPEC = [
},
// ---- Product 3D, try-on --------------------------------------------------------
+ {
+ id: 'image-to-3d-pixal3d',
+ title: 'Image to textured 3D (Pixal3D, PBR GLB, ~250k triangles)',
+ capability: 'image-to-3d',
+ handBuilt: 'hand-built/image-to-3d-pixal3d.json',
+ bindings: {
+ image: [b('122', 'image')], seed: [b('3', 'seed'), b('12', 'seed'), b('18', 'seed'), b('23', 'seed')], textureSize: [b('288', 'value')],
+ },
+ outputs: [{ node: '322', kind: 'model3d' }],
+ vramGb: 16,
+ license: 'Pixal3D weights, DINOv3-NAF and TRELLIS VAEs as repackaged by Comfy-Org (licence not reviewed yet); MoGe-2 and BiRefNet as in their own entries',
+ notes: 'Template 3d_pixal3d_trellis2_image_to_model, Pixal3D branch (the default image-to-3D route): MoGe-2 (geometry_estimation/moge_2_vitl_normal_fp16, resolution_level 9) estimates the camera from the cut-out, MoGeGeometryToFOV (horizontal, degrees) -> Pixal3DConditioning (camera_angle_x) with the DINOv3 encoder, UNet pixal3d_int8_convrot; ImageCropToMask pad_factor 1.1 (as the node asks for Pixal3D). BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui "3d"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23 (RTX 5090, the same graph run end to end): 114-185 s per object, 25-35 MB raw GLB at ~250k triangles (was 8M triangles / 317 MB before the decimate step), web GLB 1.6-3.6 MB; more faithful to the photo than TRELLIS.2 (209-238 s). The origin is the camera-aligned volume centre, hence the pivot fix. Surfaces can show faint planar facets from the shape decode (no graph setting removes them).',
+ },
{
id: 'image-to-3d-trellis2',
- title: 'Image to textured 3D (TRELLIS.2, PBR GLB) + a 36-view turntable video',
+ title: 'Image to textured 3D (TRELLIS.2, PBR GLB, ~250k triangles; fallback to Pixal3D)',
capability: 'image-to-3d',
handBuilt: 'hand-built/image-to-3d-trellis2.json',
bindings: {
- image: [b('122', 'image')], seed: [b('3', 'seed'), b('12', 'seed'), b('18', 'seed'), b('23', 'seed')], textureSize: [b('288', 'value')], turntableFps: [b('701', 'fps')],
+ image: [b('122', 'image')], seed: [b('3', 'seed'), b('12', 'seed'), b('18', 'seed'), b('23', 'seed')], textureSize: [b('288', 'value')],
},
- outputs: [{ node: '322', kind: 'model3d' }, { node: '702', kind: 'video', role: 'turntable' }],
+ outputs: [{ node: '322', kind: 'model3d' }],
vramGb: 16,
license: 'MIT (TRELLIS.2 weights, DINOv3-NAF / TRELLIS VAEs as repackaged by Comfy-Org, BiRefNet)',
- notes:
- 'Template 3d_pixal3d_trellis2_image_to_model: BiRefNet cut-out -> crop to mask -> TRELLIS.2 structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> remesh -> UV unwrap -> ' +
- 'baked base colour / metallic / roughness / AO / normal at textureSize -> GLB (Save3DAdvanced, history ui "3d"). The graph adds a 36-view turntable (RotateMesh + RenderMesh, core) saved as MP4 at turntableFps.',
+ notes: 'Template 3d_pixal3d_trellis2_image_to_model, TRELLIS.2 branch (the fallback image-to-3D route; Pixal3D is the default): Trellis2Conditioning with the DINOv3 encoder, UNet trellis_2_int8_convrot; ImageCropToMask pad_factor 1.0. BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui "3d"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23: 209-238 s, 28-43 MB raw GLB at ~250k triangles. The 36-view RotateMesh + RenderMesh turntable (unlit, aliased, 12 fps) was removed.',
},
{
id: 'image-to-3d-hunyuan3d-21',
diff --git a/scripts/comfy/validation-state.json b/scripts/comfy/validation-state.json
index 7039d8e6..fb1f4565 100644
--- a/scripts/comfy/validation-state.json
+++ b/scripts/comfy/validation-state.json
@@ -161,11 +161,17 @@
"error": null,
"at": "2026-10-17T21:02:04.747Z"
},
+ "image-to-3d-pixal3d": {
+ "sha256": "581d29c7322dbb089db04cef398428c1ec3ba13208f020a39eaadb8d23ce5a6f",
+ "validated": true,
+ "error": null,
+ "at": "2026-10-23T16:54:45.150Z"
+ },
"image-to-3d-trellis2": {
- "sha256": "7bfa7ebe14aa128a4b9b513e653998c5293ddc9221ca1d668191d27dc52725f6",
+ "sha256": "71818818d7bec8ee685bcb5e3e6a81aa9abb9f60104c46900d2ce429a693dbb1",
"validated": true,
"error": null,
- "at": "2026-10-23T00:12:16.834Z"
+ "at": "2026-10-23T16:54:45.150Z"
},
"image-to-splat-triposplat": {
"sha256": "cb65f4660b4d5fef3c0544146ed51b7d3acf059f3190a102dccf8166908f5413",
diff --git a/scripts/model3d/finish-glb.mjs b/scripts/model3d/finish-glb.mjs
new file mode 100644
index 00000000..dff21aa0
--- /dev/null
+++ b/scripts/model3d/finish-glb.mjs
@@ -0,0 +1,166 @@
+#!/usr/bin/env node
+// Finish an image-to-3D GLB from ComfyUI (Pixal3D, TRELLIS.2, Hunyuan3D) for the web. The Fuobe server runs
+// this in a child process after the job (src/server/model3d-finish.ts); it also works by hand:
+//
+// node scripts/model3d/finish-glb.mjs --in raw.glb --out web.glb [--material auto|matte|metal|mixed] [--texture-size 2048]
+//
+// 1. Material: "auto" reads the baked metallic channel (B of the metallicRoughness texture). Mostly metal
+// (>= 25 % of texels at metallic >= 0.5) -> "metal"; almost none (< 2 % and mean < 0.05) -> "matte";
+// anything else -> "mixed". No texture (Hunyuan3D shapes) -> "unknown".
+// 2. Every texture sampler gets mipmapped minification; roughness gets a floor by material:
+// matte : roughness >= 0.8 everywhere and metallic zeroed (the bake reads ~0.25-0.4, glossy plastic on ceramic)
+// metal : no floor, metallic kept (chrome stays chrome)
+// mixed / unknown (the safe default): roughness >= 0.45 on non-metal texels only, metallic kept
+// A primitive with no material, or a material with no metallicRoughness texture still at the glTF defaults
+// (metallic 1, roughness 1: three.js shows dark, rough metal), becomes a matte dielectric (metallic 0,
+// roughness 0.8; for a material, in every class but metal): Hunyuan3D's shape-only GLBs, for one.
+// 3. center --pivot below: Pixal3D's origin is the camera-aligned volume centre, so the object orbits off-centre.
+// 4. optimize like `gltf-transform optimize --compress meshopt --texture-compress webp --texture-size 2048
+// --simplify false` (dedup, instance, palette, flatten, join, weld, prune, sparse, WebP, meshopt). No simplify:
+// the graph already decimated to ~250k triangles.
+//
+// Prints one JSON line: { material, metalFraction, roughFloor, noMetal, triangles, vertices, bytesIn, bytesOut, ms }.
+import fs from "node:fs";
+import { parseArgs } from "node:util";
+import { Logger, NodeIO, TextureInfo } from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+import { center, dedup, flatten, instance, join, meshopt, palette, prune, sparse, textureCompress, weld } from "@gltf-transform/functions";
+import { MeshoptDecoder, MeshoptEncoder } from "meshoptimizer";
+import sharp from "sharp";
+
+const { values: a } = parseArgs({
+ options: {
+ in: { type: "string" },
+ out: { type: "string" },
+ material: { type: "string", default: "auto" },
+ "texture-size": { type: "string", default: "2048" },
+ },
+});
+if (!a.in || !a.out) {
+ console.error("usage: finish-glb.mjs --in raw.glb --out web.glb [--material auto|matte|metal|mixed] [--texture-size 2048]");
+ process.exit(2);
+}
+// Run by the Fuobe server (src/server/model3d-finish.ts): stop when it goes away (its end of stdin closes).
+if (process.env.FUOBE_PARENT_PIPE === "1") {
+ process.stdin.on("end", () => process.exit(1));
+ process.stdin.on("error", () => process.exit(1));
+ process.stdin.resume();
+ process.stdin.unref?.();
+}
+
+/** Roughness floor and metal handling for each material class (see the header). */
+const FINISH = {
+ matte: { roughFloor: 0.8, noMetal: true, floorMetalTexels: true },
+ metal: { roughFloor: 0, noMetal: false, floorMetalTexels: false },
+ mixed: { roughFloor: 0.45, noMetal: false, floorMetalTexels: false },
+ unknown: { roughFloor: 0.45, noMetal: false, floorMetalTexels: false },
+};
+
+const t0 = Date.now();
+await Promise.all([MeshoptDecoder.ready, MeshoptEncoder.ready]);
+const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ "meshopt.decoder": MeshoptDecoder, "meshopt.encoder": MeshoptEncoder });
+const bytesIn = fs.statSync(a.in).size;
+const doc = await io.read(a.in);
+// stdout carries only the JSON result line.
+doc.setLogger(new Logger(Logger.Verbosity.ERROR));
+const root = doc.getRoot();
+
+// ---- 1. material class from the metallic channel
+const mrTextures = [...new Set(root.listMaterials().map((m) => m.getMetallicRoughnessTexture()).filter(Boolean))];
+const decoded = new Map();
+let metalTexels = 0;
+let metalSum = 0;
+let texels = 0;
+for (const tex of mrTextures) {
+ // 8-bit sRGB (a grey or 16-bit PNG too), stepped by the decoded pixels' own channel count (alpha or not).
+ const { data: raw, info } = await sharp(Buffer.from(tex.getImage())).toColourspace("srgb").raw().toBuffer({ resolveWithObject: true });
+ const { width, height, channels } = info;
+ decoded.set(tex, { raw, width, height, channels });
+ for (let i = 0; i < raw.length; i += channels) {
+ const m = raw[i + 2];
+ metalSum += m / 255;
+ if (m >= 128) metalTexels++;
+ texels++;
+ }
+}
+const metalFraction = texels ? metalTexels / texels : 0;
+const metalMean = texels ? metalSum / texels : 0;
+const auto = !texels ? "unknown" : metalFraction >= 0.25 ? "metal" : metalFraction < 0.02 && metalMean < 0.05 ? "matte" : "mixed";
+const material = ["matte", "metal", "mixed"].includes(a.material) ? a.material : auto;
+const rule = FINISH[material];
+
+// ---- 2. samplers + roughness floor
+for (const mat of root.listMaterials()) {
+ for (const info of [mat.getBaseColorTextureInfo(), mat.getMetallicRoughnessTextureInfo(), mat.getNormalTextureInfo(), mat.getOcclusionTextureInfo(), mat.getEmissiveTextureInfo()]) {
+ if (!info) continue;
+ info.setMinFilter(TextureInfo.MinFilter.LINEAR_MIPMAP_LINEAR);
+ info.setMagFilter(TextureInfo.MagFilter.LINEAR);
+ }
+ if (rule.noMetal && !mat.getMetallicRoughnessTexture()) mat.setMetallicFactor(0);
+ if (material !== "metal" && !mat.getMetallicRoughnessTexture() && mat.getMetallicFactor() === 1 && mat.getRoughnessFactor() === 1) {
+ mat.setMetallicFactor(0).setRoughnessFactor(0.8);
+ }
+}
+// Primitives with no material at all: one shared matte dielectric (three.js would make them dark metal).
+let plain = null;
+for (const mesh of root.listMeshes()) {
+ for (const prim of mesh.listPrimitives()) {
+ if (prim.getMaterial()) continue;
+ plain ??= doc.createMaterial("default").setMetallicFactor(0).setRoughnessFactor(0.8);
+ prim.setMaterial(plain);
+ }
+}
+if (rule.roughFloor > 0 || rule.noMetal) {
+ const floor = Math.round(rule.roughFloor * 255);
+ for (const [tex, { raw, width, height, channels }] of decoded) {
+ for (let i = 0; i < raw.length; i += channels) {
+ const metal = raw[i + 2] >= 128;
+ if (rule.floorMetalTexels || !metal) raw[i + 1] = Math.max(raw[i + 1], floor);
+ if (rule.noMetal) raw[i + 2] = 0;
+ }
+ const png = await sharp(raw, { raw: { width, height, channels } }).png({ compressionLevel: 6 }).toBuffer();
+ tex.setImage(new Uint8Array(png)).setMimeType("image/png");
+ }
+}
+
+// ---- 3 + 4. pivot at the bottom centre, then the web optimisation
+const size = Number(a["texture-size"]) || 2048;
+await doc.transform(
+ center({ pivot: "below" }),
+ dedup(),
+ instance({ min: 5 }),
+ palette({ min: 5 }),
+ flatten(),
+ join(),
+ weld(),
+ prune({ keepAttributes: true, keepIndices: false, keepLeaves: false, keepSolidTextures: true }),
+ sparse(),
+ textureCompress({ encoder: sharp, targetFormat: "webp", resize: [size, size] }),
+ meshopt({ encoder: MeshoptEncoder, level: "high" }),
+);
+
+let triangles = 0;
+let vertices = 0;
+for (const mesh of root.listMeshes()) {
+ for (const prim of mesh.listPrimitives()) {
+ const idx = prim.getIndices();
+ const pos = prim.getAttribute("POSITION");
+ vertices += pos?.getCount() ?? 0;
+ triangles += Math.floor((idx ? idx.getCount() : (pos?.getCount() ?? 0)) / 3);
+ }
+}
+await io.write(a.out, doc);
+const bytesOut = fs.statSync(a.out).size;
+console.log(
+ JSON.stringify({
+ material,
+ metalFraction: Math.round(metalFraction * 1000) / 1000,
+ roughFloor: rule.roughFloor,
+ noMetal: rule.noMetal,
+ triangles,
+ vertices,
+ bytesIn,
+ bytesOut,
+ ms: Date.now() - t0,
+ }),
+);
diff --git a/scripts/model3d/render-turntable.mjs b/scripts/model3d/render-turntable.mjs
new file mode 100644
index 00000000..6ac9e5c0
--- /dev/null
+++ b/scripts/model3d/render-turntable.mjs
@@ -0,0 +1,315 @@
+#!/usr/bin/env node
+// Turntable video of a GLB, rendered with <model-viewer> in headless Chromium on SwiftShader (CPU only: it
+// refuses to run on a GPU), composited on a soft studio backdrop and encoded to H.264 by ffmpeg. The Fuobe
+// server runs this in a child process after an image-to-3D job (src/server/model3d-finish.ts).
+//
+// node scripts/model3d/render-turntable.mjs --glb web.glb --out turntable.mp4 --poster poster.webp [options]
+//
+// Options (defaults in brackets):
+// --material auto matte -> studio HDR (scripts/model3d/studio_small_08-1k.hdr, Poly Haven CC0), exposure 1.15;
+// metal -> model-viewer's "neutral" environment, exposure 1.3 (chrome reads black in a studio HDR);
+// mixed / unknown -> neutral, exposure 1.15
+// --frames 96 --fps 24 one turn = 96 frames = 4 s; the model turns on the turntable, the lights stay put
+// --width 1024 --height 768 --dpr 2 rendered at 2x and downscaled with Lanczos (supersampling)
+// --phi 75 --fov 20 --radius 130% camera: 15 degrees above, long lens, a little room around the model
+// --chromium <exe> default: $FUOBE_CHROMIUM or $CHROMIUM_PATH, else the newest Playwright Chromium (headless shell first)
+// --ffmpeg <exe> default: $FFMPEG_PATH, else ffmpeg on the PATH
+//
+// Prints "frame i/N" after each frame, then one JSON line: { frames, fps, seconds, renderer, ms }. Exit code 3 = no
+// Chromium / no ffmpeg (not an error in the model: the page falls back to recording a turntable in the browser).
+// Every step has its own time limit (loading the model, each frame, the encode), so a stuck render fails in minutes.
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseArgs } from "node:util";
+import sharp from "sharp";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const root = path.resolve(here, "..", "..");
+const { values: a } = parseArgs({
+ options: {
+ glb: { type: "string" },
+ out: { type: "string" },
+ poster: { type: "string" },
+ material: { type: "string", default: "auto" },
+ frames: { type: "string", default: "96" },
+ fps: { type: "string", default: "24" },
+ width: { type: "string", default: "1024" },
+ height: { type: "string", default: "768" },
+ dpr: { type: "string", default: "2" },
+ phi: { type: "string", default: "75" },
+ fov: { type: "string", default: "20" },
+ radius: { type: "string", default: "130%" },
+ chromium: { type: "string" },
+ ffmpeg: { type: "string" },
+ },
+});
+if (!a.glb || !a.out) {
+ console.error("usage: render-turntable.mjs --glb model.glb --out turntable.mp4 [--poster poster.webp] [options]");
+ process.exit(2);
+}
+const unavailable = (msg) => {
+ console.error(msg);
+ process.exit(3);
+};
+
+// Run by the Fuobe server (src/server/model3d-finish.ts): stop when it goes away (its end of stdin closes) or
+// stops us. process.exit runs Playwright's exit handler, which kills the browser; ffmpeg ends with its input.
+if (process.env.FUOBE_PARENT_PIPE === "1") {
+ process.stdin.on("end", () => process.exit(1));
+ process.stdin.on("error", () => process.exit(1));
+ process.stdin.resume();
+ process.stdin.unref?.();
+}
+for (const sig of ["SIGTERM", "SIGINT"]) process.on(sig, () => process.exit(1));
+
+/** Fail a step that takes longer than `ms`. */
+function limit(promise, ms, what) {
+ let timer;
+ const timeout = new Promise((_, reject) => (timer = setTimeout(() => reject(new Error(`${what} took over ${Math.round(ms / 1000)} s`)), ms)));
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
+const LOAD_MS = 120_000;
+const FRAME_MS = 30_000;
+const ENCODE_MS = 120_000;
+
+/** Lighting by material class (see the header). */
+const LOOK = {
+ matte: { env: path.join(here, "studio_small_08-1k.hdr"), exposure: 1.15 },
+ metal: { env: "neutral", exposure: 1.3 },
+ mixed: { env: "neutral", exposure: 1.15 },
+ unknown: { env: "neutral", exposure: 1.15 },
+};
+const look = LOOK[a.material] ?? LOOK.unknown;
+const W = Number(a.width);
+const H = Number(a.height);
+const DPR = Number(a.dpr);
+const FRAMES = Number(a.frames);
+const FPS = Number(a.fps);
+
+function findChromium() {
+ // CHROMIUM_PATH is what the e2e checks (tests/e2e/_browser.mjs) read too.
+ const given = a.chromium || process.env.FUOBE_CHROMIUM || process.env.CHROMIUM_PATH;
+ if (given) return fs.existsSync(given) ? given : null;
+ const bases = [
+ process.env.PLAYWRIGHT_BROWSERS_PATH,
+ "/opt/pw-browsers",
+ process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, "ms-playwright"),
+ path.join(os.homedir(), ".cache", "ms-playwright"),
+ path.join(os.homedir(), "Library", "Caches", "ms-playwright"),
+ ].filter(Boolean);
+ const exes = [
+ ["chrome-headless-shell-win64", "chrome-headless-shell.exe"],
+ ["chrome-headless-shell-linux64", "chrome-headless-shell"],
+ ["chrome-headless-shell-mac-arm64", "chrome-headless-shell"],
+ ["chrome-headless-shell-mac-x64", "chrome-headless-shell"],
+ ["chrome-win64", "chrome.exe"],
+ ["chrome-win", "chrome.exe"],
+ ["chrome-linux64", "chrome"],
+ ["chrome-linux", "chrome"],
+ ];
+ for (const base of bases) {
+ let dirs = [];
+ try {
+ dirs = fs.readdirSync(base);
+ } catch {
+ continue;
+ }
+ // Headless shell first (no window, no GPU process surprises), newest revision first.
+ const rank = (d) => (d.startsWith("chromium_headless_shell-") ? 0 : 1);
+ const rev = (d) => Number(d.split("-").pop()) || 0;
+ dirs = dirs.filter((d) => /^chromium(_headless_shell)?-\d+$/.test(d)).sort((x, y) => rank(x) - rank(y) || rev(y) - rev(x));
+ for (const d of dirs) {
+ for (const [sub, exe] of exes) {
+ const p = path.join(base, d, sub, exe);
+ if (fs.existsSync(p)) return p;
+ }
+ }
+ }
+ return null;
+}
+
+const ffmpeg = a.ffmpeg || process.env.FFMPEG_PATH || "ffmpeg";
+function run(cmd, args, input) {
+ return new Promise((resolve, reject) => {
+ const p = spawn(cmd, args, { stdio: [input ? "pipe" : "ignore", "ignore", "pipe"], windowsHide: true });
+ let err = "";
+ p.stderr.on("data", (d) => (err = (err + d).slice(-4000)));
+ p.on("error", reject);
+ p.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`${path.basename(cmd)} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`))));
+ if (input) input(p.stdin);
+ });
+}
+try {
+ await run(ffmpeg, ["-hide_banner", "-version"]);
+} catch {
+ unavailable("ffmpeg not found (set FFMPEG_PATH)");
+}
+const chromiumExe = findChromium();
+if (!chromiumExe) unavailable("no Chromium found (install one with `npx playwright-core install chromium-headless-shell`, or set FUOBE_CHROMIUM)");
+const { chromium } = await import("playwright-core");
+
+// The backdrop: a warm seamless sweep (centre #F3ECE3 falling to #D8CBBB at the corners), at render size.
+async function backdrop(w, h) {
+ const px = Buffer.alloc(w * h * 3);
+ const cx = w / 2;
+ const cy = h * (700 / 1536);
+ const r = w * (1250 / 2048);
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const t = Math.pow(Math.min(1, Math.hypot(x - cx, (y - cy) * 1.25) / r), 1.6);
+ const i = (y * w + x) * 3;
+ px[i] = 243 - 27 * t;
+ px[i + 1] = 236 - 33 * t;
+ px[i + 2] = 227 - 40 * t;
+ }
+ }
+ return sharp(px, { raw: { width: w, height: h, channels: 3 } }).png().toBuffer();
+}
+
+const mvFile = path.join(root, "node_modules", "@google", "model-viewer", "dist", "model-viewer.min.js");
+const decoderFile = path.join(root, "public", "vendor", "meshopt_decoder.js");
+const envIsFile = look.env !== "neutral";
+const files = {
+ "/mv.js": [mvFile, "text/javascript"],
+ "/meshopt_decoder.js": [decoderFile, "text/javascript"],
+ "/model.glb": [a.glb, "model/gltf-binary"],
+ ...(envIsFile ? { "/env.hdr": [look.env, "application/octet-stream"] } : {}),
+};
+const attrs = {
+ "environment-image": envIsFile ? "/env.hdr" : "neutral",
+ exposure: String(look.exposure),
+ "tone-mapping": "neutral",
+ "shadow-intensity": "0.85",
+ "shadow-softness": "0.9",
+ // The default limits clamp what we ask for: min-field-of-view is 25deg and the max radius is the auto framing radius.
+ "min-field-of-view": "5deg",
+ "max-field-of-view": "90deg",
+ "max-camera-orbit": "Infinity 180deg 1000%",
+ "camera-orbit": `0deg ${a.phi}deg ${a.radius}`,
+ "field-of-view": `${a.fov}deg`,
+ "interaction-prompt": "none",
+ "interpolation-decay": "1",
+ loading: "eager",
+ reveal: "auto",
+};
+const page = `<!doctype html><html><head><meta charset="utf-8">
+<style>html,body{margin:0;background:transparent;overflow:hidden}model-viewer{display:block;width:${W}px;height:${H}px;background:transparent;--poster-color:transparent;--progress-bar-height:0}</style>
+</head><body><script type="module">
+import '/mv.js';
+const MV = customElements.get('model-viewer');
+MV.minimumRenderScale = 1;
+MV.meshoptDecoderLocation = '/meshopt_decoder.js';
+const mv = document.createElement('model-viewer');
+for (const [k, v] of Object.entries(${JSON.stringify(attrs)})) mv.setAttribute(k, v);
+window.__ready = new Promise((resolve, reject) => {
+ mv.addEventListener('load', () => resolve(true), { once: true });
+ mv.addEventListener('error', (e) => reject(new Error('model-viewer: ' + JSON.stringify(e.detail))), { once: true });
+});
+mv.src = '/model.glb';
+document.body.appendChild(mv);
+window.__mv = mv;
+</script></body></html>`;
+
+const server = http.createServer((req, res) => {
+ const url = new URL(req.url, "http://x").pathname;
+ if (url === "/") {
+ res.writeHead(200, { "content-type": "text/html" });
+ return res.end(page);
+ }
+ const f = files[url];
+ if (!f || !fs.existsSync(f[0])) {
+ res.writeHead(404);
+ return res.end();
+ }
+ res.writeHead(200, { "content-type": f[1], "content-length": fs.statSync(f[0]).size });
+ fs.createReadStream(f[0]).pipe(res);
+});
+await new Promise((r) => server.listen(0, "127.0.0.1", r));
+const origin = `http://127.0.0.1:${server.address().port}`;
+
+const t0 = Date.now();
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-turntable-"));
+let browser;
+try {
+ const plate = path.join(tmp, "backdrop.png");
+ fs.writeFileSync(plate, await backdrop(W * DPR, H * DPR));
+ browser = await chromium.launch({
+ executablePath: chromiumExe,
+ headless: true,
+ // CPU rendering: ANGLE on SwiftShader (WebGL on SwiftShader needs the explicit opt-in). Only this local page loads.
+ args: ["--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist", "--disable-gpu-compositing"],
+ });
+ const ctx = await browser.newContext({ viewport: { width: W, height: H }, deviceScaleFactor: DPR });
+ const tab = await ctx.newPage();
+ await tab.goto(origin + "/");
+ const renderer = await tab.evaluate(() => {
+ const c = document.createElement("canvas").getContext("webgl2");
+ if (!c) return "no webgl2";
+ const ext = c.getExtension("WEBGL_debug_renderer_info");
+ return String(ext ? c.getParameter(ext.UNMASKED_RENDERER_WEBGL) : c.getParameter(c.RENDERER));
+ });
+ if (!/swiftshader/i.test(renderer)) throw new Error(`not on SwiftShader (${renderer}); refusing to render on the GPU`);
+ await tab.waitForFunction(() => window.__mv && window.__ready, null, { timeout: LOAD_MS });
+ await limit(tab.evaluate(() => window.__ready), LOAD_MS, "loading the model");
+ // Let the environment (PMREM) and the contact shadow settle.
+ await limit(
+ tab.evaluate(() => new Promise((r) => { let n = 0; const f = () => (++n >= 8 ? r() : requestAnimationFrame(f)); requestAnimationFrame(f); })),
+ FRAME_MS,
+ "the first frames",
+ );
+
+ // Frames go straight into ffmpeg (no temp PNGs): backdrop + frame, composited at 2x, then Lanczos to the output size.
+ let feed;
+ const fed = new Promise((resolve) => (feed = resolve));
+ const encode = run(
+ ffmpeg,
+ [
+ "-hide_banner", "-v", "error", "-y",
+ "-loop", "1", "-framerate", String(FPS), "-i", plate,
+ "-f", "image2pipe", "-framerate", String(FPS), "-c:v", "png", "-i", "-",
+ "-filter_complex", `[0:v][1:v]overlay=format=auto:shortest=1,scale=${W}:${H}:flags=lanczos,format=yuv420p`,
+ "-frames:v", String(FRAMES), "-c:v", "libx264", "-preset", "slow", "-crf", "18", "-pix_fmt", "yuv420p",
+ "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv",
+ "-movflags", "+faststart", "-an", a.out,
+ ],
+ (stdin) => feed(stdin),
+ );
+ const stdin = await fed;
+ stdin.on("error", () => {}); // ffmpeg failing shows up as the encode error below
+ let first;
+ for (let i = 0; i < FRAMES; i++) {
+ const theta = (2 * Math.PI * i) / FRAMES;
+ const b64 = await limit(tab.evaluate(async (th) => {
+ const mv = window.__mv;
+ mv.resetTurntableRotation(th);
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(r))));
+ const blob = await mv.toBlob({ mimeType: "image/png" });
+ const buf = new Uint8Array(await blob.arrayBuffer());
+ let s = "";
+ for (let k = 0; k < buf.length; k += 0x8000) s += String.fromCharCode.apply(null, buf.subarray(k, k + 0x8000));
+ return btoa(s);
+ }, theta), FRAME_MS, `frame ${i + 1}`);
+ const png = Buffer.from(b64, "base64");
+ if (i === 0) first = png;
+ if (!stdin.write(png)) await limit(new Promise((r) => stdin.once("drain", r)), FRAME_MS, "ffmpeg taking a frame");
+ console.log(`frame ${i + 1}/${FRAMES}`);
+ }
+ stdin.end();
+ await limit(encode, ENCODE_MS, "encoding the video");
+ if (a.poster && first) {
+ // The first frame (the photo's own angle) on the same backdrop.
+ await sharp(plate)
+ .composite([{ input: first }])
+ .toBuffer()
+ .then((b) => sharp(b).resize(W, H, { kernel: "lanczos3" }).webp({ quality: 88 }).toFile(a.poster));
+ }
+ console.log(JSON.stringify({ frames: FRAMES, fps: FPS, seconds: FRAMES / FPS, renderer, material: a.material, ms: Date.now() - t0 }));
+} finally {
+ await limit(browser?.close() ?? Promise.resolve(), 15_000, "closing the browser").catch(() => {});
+ server.close();
+ fs.rmSync(tmp, { recursive: true, force: true });
+}
diff --git a/scripts/model3d/studio_small_08-1k.hdr b/scripts/model3d/studio_small_08-1k.hdr
new file mode 100644
index 00000000..fd9f69af
Binary files /dev/null and b/scripts/model3d/studio_small_08-1k.hdr differ
diff --git a/src/app/(studio)/apps/page.tsx b/src/app/(studio)/apps/page.tsx
index c95a5610..af6c7bad 100644
--- a/src/app/(studio)/apps/page.tsx
+++ b/src/app/(studio)/apps/page.tsx
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
import { PageHeader, PageShell } from "@/components/page-shell";
import { PresetGallery } from "@/components/preset-gallery";
import { APPS } from "@/lib/catalog";
-import { toPresetCard } from "@/lib/preset-cards";
+import { toPresetCard } from "@/lib/preset-card-data";
export const metadata: Metadata = { title: "Apps" };
diff --git a/src/app/(studio)/effects/page.tsx b/src/app/(studio)/effects/page.tsx
index cbe163ca..6510f263 100644
--- a/src/app/(studio)/effects/page.tsx
+++ b/src/app/(studio)/effects/page.tsx
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
import { PageHeader, PageShell } from "@/components/page-shell";
import { PresetGallery } from "@/components/preset-gallery";
import { EFFECTS } from "@/lib/catalog";
-import { toPresetCard } from "@/lib/preset-cards";
+import { toPresetCard } from "@/lib/preset-card-data";
export const metadata: Metadata = { title: "Effects" };
diff --git a/src/app/(studio)/motions/page.tsx b/src/app/(studio)/motions/page.tsx
index 28b07e82..bf9801bf 100644
--- a/src/app/(studio)/motions/page.tsx
+++ b/src/app/(studio)/motions/page.tsx
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
import { PageHeader, PageShell } from "@/components/page-shell";
import { PresetGallery } from "@/components/preset-gallery";
import { MOTIONS } from "@/lib/catalog";
-import { toPresetCard } from "@/lib/preset-cards";
+import { toPresetCard } from "@/lib/preset-card-data";
export const metadata: Metadata = { title: "Camera motions" };
diff --git a/src/app/(studio)/page.tsx b/src/app/(studio)/page.tsx
index b03a86c4..50d3ceb8 100644
--- a/src/app/(studio)/page.tsx
+++ b/src/app/(studio)/page.tsx
@@ -1,6 +1,7 @@
import { HomeView } from "@/components/home-view";
import { APPS, EFFECTS, MOTIONS } from "@/lib/catalog";
-import { homeEffects, toPresetCard } from "@/lib/preset-cards";
+import { toPresetCard } from "@/lib/preset-card-data";
+import { homeEffects } from "@/lib/preset-cards";
const HOME_MOTIONS = ["motion-crash-zoom-in", "motion-360-orbit", "motion-bullet-time", "motion-fpv-drone", "motion-dolly-zoom-in", "motion-snorricam"];
diff --git a/src/app/api/llm/route.ts b/src/app/api/llm/route.ts
new file mode 100644
index 00000000..79199a27
--- /dev/null
+++ b/src/app/api/llm/route.ts
@@ -0,0 +1,35 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { activeLocal, aiHelper, llmContext, localStatuses, pinnedKind, reloadLmStudio, testLocal } from "@/server/llm";
+
+/**
+ * The local LLM servers for Settings → AI helper. GET: each server's status (up, key, its chat
+ * models, the model a call would use, what's wrong), `?refresh=1` asks them again now. Keys never
+ * leave the server. POST {action: "test", kind?}: a tiny call, timed. POST {action: "load", model?}:
+ * reloads an LM Studio model with the context from Settings.
+ */
+export async function GET(request: Request) {
+ await connection();
+ const refresh = new URL(request.url).searchParams.get("refresh") === "1";
+ const servers = await localStatuses(refresh);
+ const active = await activeLocal();
+ return Response.json({ helper: aiHelper(), provider: pinnedKind() ?? "auto", context: llmContext(), active: active?.server.kind ?? null, servers });
+}
+
+const Action = z.discriminatedUnion("action", [
+ z.object({ action: z.literal("test"), kind: z.enum(["ollama", "lmstudio", "unsloth", "custom"]).nullish() }),
+ z.object({ action: z.literal("load"), model: z.string().trim().max(200).nullish() }),
+]);
+
+export async function POST(request: Request) {
+ const parsed = Action.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ ok: false, detail: "Unknown action" }, { status: 400 });
+ const a = parsed.data;
+ if (a.action === "test") return Response.json(await testLocal(a.kind));
+ try {
+ const r = await reloadLmStudio(a.model);
+ return Response.json({ ok: true, detail: `LM Studio loaded ${r.model}${r.context ? ` with ${r.context.toLocaleString("en-US")} tokens of context` : ""}${r.seconds ? ` in ${r.seconds.toFixed(1)} s` : ""}`, ...r });
+ } catch (e) {
+ return Response.json({ ok: false, detail: (e as Error).message });
+ }
+}
diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.ts
index c7a86605..34eb19ee 100644
--- a/src/app/api/status/route.ts
+++ b/src/app/api/status/route.ts
@@ -1,12 +1,15 @@
import { connection } from "next/server";
+import { aiHelper, localSummary } from "@/server/llm";
import { PROVIDERS } from "@/server/providers";
import { probeComfy } from "@/server/providers/comfyui";
+import { llmBackends } from "@/server/providers/llm";
import { getSetting } from "@/server/settings";
/** Which providers are usable right now — drives badges and the demo-mode banner. */
export async function GET() {
await connection();
- const comfy = await probeComfy(true);
+ // Both asked first, so the llm provider's label and routing read fresh answers without waiting.
+ const [comfy, local] = await Promise.all([probeComfy(true), localSummary()]);
const providers = Object.fromEntries(
Object.values(PROVIDERS).map((p) => [
p.id,
@@ -18,5 +21,7 @@ export async function GET() {
demoMode: getSetting("demoMode"),
engineMode: getSetting("engineMode"),
cloudProvider: getSetting("cloudProvider"),
+ // The text LLM: the AI helper setting, whether Claude takes text steps, and the local server (no keys).
+ llm: { helper: aiHelper(), claude: llmBackends({ endpoint: "auto" })[0] === "claude", ...local },
});
}
diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsx
index 83c829fb..22453929 100644
--- a/src/components/assist-view.tsx
+++ b/src/components/assist-view.tsx
@@ -35,8 +35,8 @@ const STARTER_SKILLS = ["product-photoshoot", "ugc-video", "thumbnail-generation
const AGENT_HINT: Record<AssistThread["agent"], string> = {
claude: "Claude plans the shoot, picks models and runs them with your approval.",
- ollama: "Runs on your local model through Ollama. Smaller local models follow instructions less reliably than Claude.",
- offline: "A simple rule-based planner. Add an Anthropic API key, or run Ollama, for the full assistant that picks models, chains steps and checks results.",
+ local: "Runs on your local model (Ollama, LM Studio or Unsloth Studio). Smaller local models follow instructions less reliably than Claude.",
+ offline: "A simple rule-based planner. Add an Anthropic API key, or run a local model (Ollama, LM Studio or Unsloth Studio), for the full assistant that picks models, chains steps and checks results.",
};
export function AskFirst({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {
diff --git a/src/components/assist/mode-picker.tsx b/src/components/assist/mode-picker.tsx
index 3393a425..370cb792 100644
--- a/src/components/assist/mode-picker.tsx
+++ b/src/components/assist/mode-picker.tsx
@@ -10,6 +10,7 @@ import {
CLAUDE_MODELS,
DEFAULT_CLAUDE_MODEL,
DEFAULT_EFFORT,
+ normalizeAgent,
type AssistAgent,
type AssistAvailability,
type AssistModeChoice,
@@ -47,7 +48,8 @@ export function useModeChoice(defaultMode?: AssistModeChoice["mode"]): [AssistMo
const choice = useMemo(() => {
try {
const saved = JSON.parse(raw ?? "null") as AssistModeChoice | null;
- if (saved?.mode) return saved;
+ // A choice saved when the local agent was called "ollama" reads as "local".
+ if (saved?.mode) return saved.agent ? { ...saved, agent: normalizeAgent(saved.agent) } : saved;
} catch {}
return defaultMode ? { mode: defaultMode } : null;
}, [raw, defaultMode]);
@@ -68,7 +70,7 @@ export function modeChipLabel(c: AssistModeChoice | null, can?: AssistAvailabili
if (can?.aiOff) return "Offline";
if (c.mode !== "manual") return c.mode === "smart" ? "Smart" : "Free";
if (c.agent === "offline") return "Offline planner";
- if (c.agent === "ollama") return c.model ?? can?.ollamaModel ?? "Local";
+ if (c.agent === "local") return c.model ?? can?.local.model ?? "Local";
const m = CLAUDE_MODELS.find((x) => x.id === (c.model ?? DEFAULT_CLAUDE_MODEL))?.label.replace("Claude ", "") ?? "Claude";
return `${m} · ${ASSIST_EFFORTS.find((e) => e.id === (c.effort ?? DEFAULT_EFFORT))?.label}`;
}
@@ -89,7 +91,8 @@ interface ModelOption {
}
/**
- * Supercomputer's Free / Smart / Manual, on Fuobe's agents (Claude, Ollama, the offline planner).
+ * Supercomputer's Free / Smart / Manual, on Fuobe's agents (Claude, a local model on Ollama, LM Studio,
+ * Unsloth Studio or another OpenAI-compatible server, the offline planner).
* With `applyOnClose` (an existing chat) choices are kept in the menu and sent once when it
* closes, so trying the tabs doesn't switch the chat at every click. Smart needs Claude: without
* an Anthropic key it can't be picked (and a saved Smart shows as the Free it runs as).
@@ -140,13 +143,13 @@ export function ModePicker({
title: <span className="block text-[13px] font-medium">{m.label}</span>,
hint: m.hint,
})),
- ...(can?.ollamaModels.length ? can.ollamaModels : can?.ollama ? [can.ollamaModel] : []).map((name) => ({
- key: `ollama:${name}`,
- on: agent === "ollama" && (shown?.model ?? can?.ollamaModel) === name,
- pick: { agent: "ollama" as const, model: name, effort: null },
+ ...(can?.local.models.length ? can.local.models : can?.local.ok && can.local.model ? [can.local.model] : []).map((name) => ({
+ key: `local:${name}`,
+ on: agent === "local" && (shown?.model ?? can?.local.model) === name,
+ pick: { agent: "local" as const, model: name, effort: null },
icon: Cpu,
title: <span className="block truncate font-mono text-[12px]">{name}</span>,
- hint: "Local, through Ollama · free",
+ hint: `Local, through ${can?.local.label ?? "your local server"} · free`,
})),
{ key: "offline", on: agent === "offline", pick: { agent: "offline", model: null, effort: null }, icon: Gauge, title: <span className="block text-[13px] font-medium">Offline planner</span>, hint: "Rules, no LLM — simple requests only" },
];
@@ -190,7 +193,7 @@ export function ModePicker({
tabIndex={radioTab(mode === m.id)}
disabled={off}
title={off ? "Needs an Anthropic API key (Settings)" : undefined}
- onClick={() => set({ mode: m.id, ...(m.id === "manual" && !shown?.agent && { agent: can?.claude ? "claude" : can?.ollama ? "ollama" : "offline" }) })}
+ onClick={() => set({ mode: m.id, ...(m.id === "manual" && !shown?.agent && { agent: can?.claude ? "claude" : can?.local.ok ? "local" : "offline" }) })}
className={cn("h-8 rounded-full text-[13px] font-medium transition-colors disabled:opacity-45", mode === m.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground enabled:hover:text-foreground")}
>
{m.label}
@@ -210,12 +213,14 @@ export function ModePicker({
)}
{mode === "free" && (
<p className="mt-2 px-1 text-[12px] text-muted-foreground">
- {can?.ollama ? (
+ {can?.local.ok ? (
<>
- Runs on <span className="font-mono">{can.ollamaModel}</span> through Ollama — free, on this machine.
+ Runs on <span className="font-mono">{can.local.model}</span> through {can.local.label} — free, on this machine.
</>
+ ) : can?.local.problem ? (
+ `${can.local.problem} Until then, the offline planner takes simple requests.`
) : (
- "Ollama isn't answering, so the offline planner takes simple requests. Start Ollama for a real local assistant."
+ "No local model is answering, so the offline planner takes simple requests. Start Ollama, LM Studio or Unsloth Studio for a real local assistant."
)}
</p>
)}
diff --git a/src/components/cinema/side-panel.tsx b/src/components/cinema/side-panel.tsx
index 8dd94b12..5779dc76 100644
--- a/src/components/cinema/side-panel.tsx
+++ b/src/components/cinema/side-panel.tsx
@@ -57,7 +57,7 @@ function Message({ m, onLoad, onBrief }: { m: DirectorMessage; onLoad: (s: Direc
</span>
<div className="min-w-0 flex-1">
<p className="text-[13.5px] leading-relaxed whitespace-pre-wrap">{m.text}</p>
- {m.source === "offline" && <p className="mt-0.5 text-[11px] text-muted-foreground">Offline breakdown — connect Claude or Ollama in Settings for a smarter Director.</p>}
+ {m.source === "offline" && <p className="mt-0.5 text-[11px] text-muted-foreground">Offline breakdown — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for a smarter Director.</p>}
</div>
</div>
{m.brief && (
diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsx
index 782d2f15..5a162bb8 100644
--- a/src/components/dub/dub-studio.tsx
+++ b/src/components/dub/dub-studio.tsx
@@ -31,7 +31,7 @@ const ONE_SHOT: Record<OneShotModel, { name: string; note: string }> = {
const ROUTE_LINE = {
open: "Open source: MelBand RoFormer splits the voice from the music and Qwen3-ASR times it → your local LLM translates → you review → Chatterbox speaks each line in the cloned voice, at its time → InfiniteTalk re-syncs the lips → mixed back over the music.",
- cloud: "Cloud: ElevenLabs isolates the voice and Demucs lifts out the music and effects → Scribe v2 times the voice → Claude (or Ollama) translates → you review → ElevenLabs speaks each line at its time and Chatterbox turns it into the speaker's voice → Sync Lipsync 3 → mixed back over the music and effects.",
+ cloud: "Cloud: ElevenLabs isolates the voice and Demucs lifts out the music and effects → Scribe v2 times the voice → Claude (or a local model) translates → you review → ElevenLabs speaks each line at its time and Chatterbox turns it into the speaker's voice → Sync Lipsync 3 → mixed back over the music and effects.",
};
const STAGE: Record<DubStage, { label: string; tone: string }> = {
diff --git a/src/components/faceless/episode-wizard.tsx b/src/components/faceless/episode-wizard.tsx
index 765e3c0b..da62b7b3 100644
--- a/src/components/faceless/episode-wizard.tsx
+++ b/src/components/faceless/episode-wizard.tsx
@@ -200,7 +200,7 @@ export function EpisodeWizard({ channelId, picker }: { channelId: string; picker
<section aria-label="Topic suggestions" className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
- <p className={cn("text-[13px] text-muted-foreground", loadingTopics && "shimmer-text animate-shimmer-text")}>{loadingTopics ? "Writing topic suggestions…" : offline ? "Suggestions written offline — connect Claude or Ollama in Settings for fresher ones." : "Tick one, or write your own below."}</p>
+ <p className={cn("text-[13px] text-muted-foreground", loadingTopics && "shimmer-text animate-shimmer-text")}>{loadingTopics ? "Writing topic suggestions…" : offline ? "Suggestions written offline — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for fresher ones." : "Tick one, or write your own below."}</p>
<Button
variant="outline"
size="sm"
diff --git a/src/components/home-view.tsx b/src/components/home-view.tsx
index 6ae0eedc..c40f729a 100644
--- a/src/components/home-view.tsx
+++ b/src/components/home-view.tsx
@@ -28,6 +28,7 @@ import { EngineSwitch } from "@/components/studio/engine-switch";
import type { Generation } from "@/lib/catalog/types";
import { userTitle } from "@/lib/library";
import type { PresetCardData } from "@/lib/preset-cards";
+import { PREVIEW_SIZES } from "@/lib/preview-media";
import { cn } from "@/lib/utils";
// The viewer is only needed once a recent result is opened.
@@ -130,7 +131,7 @@ function CardRow({ cards, href, engine }: { cards: PresetCardData[]; href: (c: P
return (
<div className="grid grid-cols-2 gap-1 sm:grid-cols-4 lg:grid-cols-6">
{cards.map((p) => (
- <PresetCard key={p.id} preset={p} href={href(p)} compact engine={engine} />
+ <PresetCard key={p.id} preset={p} href={href(p)} compact engine={engine} sizes={PREVIEW_SIZES.home} />
))}
</div>
);
diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsx
index e9f8f9ea..5709df5f 100644
--- a/src/components/marketing/click-to-ad.tsx
+++ b/src/components/marketing/click-to-ad.tsx
@@ -180,7 +180,7 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
try {
const r = await send<{ script: string; by: "llm" | "rules" }>("/api/marketing/script", "POST", { engine, productId, styleId, presenter: withPresenter, instructions: mode === "custom" ? instructions : undefined });
setScript(r.script);
- if (r.by === "rules") toast("Written from your product's facts — connect Claude or Ollama in Settings for livelier scripts", { duration: 4000 });
+ if (r.by === "rules") toast("Written from your product's facts — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for livelier scripts", { duration: 4000 });
} catch (e) {
toast.error((e as Error).message);
} finally {
diff --git a/src/components/model3d/model-viewer.ts b/src/components/model3d/model-viewer.ts
new file mode 100644
index 00000000..028ab1da
--- /dev/null
+++ b/src/components/model3d/model-viewer.ts
@@ -0,0 +1,78 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+/**
+ * One setup for every <model-viewer> in Fuobe (the 3D page, the result viewer): load the element on demand,
+ * point it at the same-origin meshopt decoder before the first model loads (the web GLBs are
+ * meshopt-compressed; model-viewer only enables its decoder when this is set) and keep full render
+ * resolution. The look matches the server turntable: neutral environment and tone mapping, a soft contact
+ * shadow, a long lens, the exposure the turntable used for that material.
+ */
+
+/** Copied from node_modules/meshoptimizer/meshopt_decoder.cjs (tests/model3d-finish.test.ts keeps it in sync). */
+export const MESHOPT_DECODER_URL = "/vendor/meshopt_decoder.js";
+
+type ModelViewerClass = CustomElementConstructor & { meshoptDecoderLocation?: string; minimumRenderScale?: number };
+
+let loading: Promise<void> | null = null;
+
+/** Import @google/model-viewer once and configure it before any model loads. */
+export function loadModelViewer(): Promise<void> {
+ loading ??= import("@google/model-viewer").then(
+ () => {
+ const MV = customElements.get("model-viewer") as ModelViewerClass | undefined;
+ if (MV) {
+ MV.meshoptDecoderLocation = MESHOPT_DECODER_URL;
+ // No dynamic resolution drop (model-viewer lowers it to 0.5 on a slow frame).
+ MV.minimumRenderScale = 1;
+ }
+ },
+ (e) => {
+ loading = null;
+ throw e;
+ },
+ );
+ return loading;
+}
+
+/**
+ * Attributes every viewer shares (lighting, shadow, lens). `material` is the class the server's finish read
+ * (meta.finish.material): the exposure the server turntable used with the neutral environment, so opening the
+ * 3D view doesn't change the model's look. Results without one keep model-viewer's default exposure.
+ */
+export function viewerLook(material?: string): Record<string, string> {
+ return {
+ "environment-image": "neutral",
+ "tone-mapping": "neutral",
+ exposure: material === "metal" ? "1.3" : material ? "1.15" : "1",
+ "shadow-intensity": "1",
+ "shadow-softness": "0.9",
+ // A long lens like a product photo; zooming narrows the field of view down to 5 degrees.
+ "field-of-view": "20deg",
+ "min-field-of-view": "5deg",
+ // The framing radius is computed for a 30 degree lens: step back so the model still fits at 20 degrees.
+ "camera-orbit": "0deg 75deg 130%",
+ "max-camera-orbit": "Infinity 157.5deg 200%",
+ };
+}
+
+/** The studio sweep behind the server's turntable (scripts/model3d/render-turntable.mjs), as a CSS background. */
+export const TURNTABLE_BACKDROP = "radial-gradient(61% 65% at 50% 45.6%, #f3ece3 0%, #f0e8df 25%, #eae1d6 50%, #e2d7ca 75%, #d8cbbb 100%)";
+
+/**
+ * The GLB a viewer should load: the web GLB, or the original once the web one fails to load (the decoder
+ * blocked, a bad file). `el` is the mounted <model-viewer>.
+ */
+export function useViewerSrc(el: HTMLElement | null, web: string | undefined, original: string | undefined): string | undefined {
+ const [failed, setFailed] = useState<string | null>(null);
+ useEffect(() => {
+ if (!el || !web || !original || web === original) return;
+ const onError = (e: Event) => {
+ if ((e as CustomEvent<{ type?: string }>).detail?.type === "loadfailure") setFailed(web);
+ };
+ el.addEventListener("error", onError);
+ return () => el.removeEventListener("error", onError);
+ }, [el, web, original]);
+ return failed && failed === web ? original : web;
+}
diff --git a/src/components/model3d/model3d-studio.tsx b/src/components/model3d/model3d-studio.tsx
index 4f98f23a..5b818240 100644
--- a/src/components/model3d/model3d-studio.tsx
+++ b/src/components/model3d/model3d-studio.tsx
@@ -1,8 +1,8 @@
"use client";
-import { Box, Clapperboard, Download, Loader2, Sparkles, Video } from "lucide-react";
+import { Box, Clapperboard, Download, Loader2, Pause, Play, Rotate3d, Sparkles, Video } from "lucide-react";
import Link from "next/link";
-import { createElement, useEffect, useState } from "react";
+import { createElement, useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
@@ -16,6 +16,7 @@ import { uploadFile, useCreateGeneration, useEngine, useGenerations, useHydrated
import { animateSpinHref, model3dRequest, model3dView, MODEL3D_FEATURE, MODELS_3D } from "@/lib/av/model3d";
import type { Generation } from "@/lib/catalog/types";
import { cn } from "@/lib/utils";
+import { loadModelViewer, TURNTABLE_BACKDROP, useViewerSrc, viewerLook } from "./model-viewer";
import { recordableType, recordTurntable } from "./turntable";
/** Image to 3D / Product spin: a product photo → a .glb to spin and download, a turntable video, and on to a video. */
@@ -63,7 +64,7 @@ export function Model3dStudio({ names }: { names: Record<string, string> }) {
{create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Box className="size-4" />} Make it 3D
</Button>
<p className="mt-2 text-[12px] text-muted-foreground">
- {engine === "open" ? "TRELLIS.2 also renders a turntable video on your GPU." : "Cloud models return the .glb; record a turntable right here in your browser."}
+ {engine === "open" ? "Open models also get a turntable video, rendered after the model is made." : "Cloud models return the .glb; record a turntable right here in your browser."}
</p>
</Panel>
</div>
@@ -99,71 +100,151 @@ function ResultCard({ g }: { g: Generation }) {
function ModelCard({ g }: { g: Generation }) {
const view = model3dView(g);
+ // The card plays the turntable (or shows the poster); the 3D viewer, and its GLB, load only when it's opened.
+ const [show, setShow] = useState<"preview" | "3d">("preview");
const [viewer, setViewer] = useState<HTMLElement | null>(null);
const [ready, setReady] = useState(false);
const [failed, setFailed] = useState(false);
+ const [loadedEl, setLoadedEl] = useState<HTMLElement | null>(null);
+ const loaded = !!viewer && loadedEl === viewer;
const [recording, setRecording] = useState<number | null>(null);
const [recorded, setRecorded] = useState<{ url: string; saved?: string } | null>(null);
+ const pendingRecord = useRef(false);
+ // "View in 3D" unmounts itself: focus moves to the viewer once it's there.
+ const focusViewer = useRef(false);
const hydrated = useHydrated();
const canRecord = hydrated && !!recordableType();
+ const open3d = show === "3d";
+ const src = useViewerSrc(viewer, view.web, view.glb);
+ const onOriginal = src === view.glb;
useEffect(() => {
+ if (!open3d) return;
let live = true;
- import("@google/model-viewer").then(
+ loadModelViewer().then(
() => live && setReady(true),
- () => live && setFailed(true),
+ () => {
+ if (!live) return;
+ pendingRecord.current = false;
+ setFailed(true);
+ },
);
return () => {
live = false;
};
- }, []);
+ }, [open3d]);
// The recorded clip's blob URL lives until another recording replaces it (saving it doesn't change it).
const recordedUrl = recorded?.url;
useEffect(() => () => void (recordedUrl && URL.revokeObjectURL(recordedUrl)), [recordedUrl]);
- // The turntable that came with the model (TRELLIS.2, demo) or the one recorded here, shown in place of the 3D view.
+ // The turntable the server rendered (open models, demo) or the one recorded here.
const clip = view.turntable ?? recordedUrl;
- const [show, setShow] = useState<"3d" | "video">("3d");
- const record = async () => {
+ const still = view.poster ?? view.photo;
+ const name = (g.modelName ?? "model").replace(/[^\w .-]+/g, "");
+ const label = g.modelName ?? "3D";
+ // Behind the viewer: the studio sweep the server's turntable and poster are on, so opening 3D doesn't jump.
+ const backdrop = view.material ? TURNTABLE_BACKDROP : undefined;
+ const startRecording = useCallback(
+ async (el: HTMLElement) => {
+ setRecording(0);
+ try {
+ const blob = await recordTurntable(el as Parameters<typeof recordTurntable>[0], { onProgress: setRecording });
+ const url = URL.createObjectURL(blob);
+ setRecorded({ url });
+ // Keep it in the Library (Uploads) so it can go on to Edit video.
+ const asset = await uploadFile(new File([blob], `${name} turntable.webm`, { type: "video/webm" }));
+ setRecorded({ url, saved: asset.url });
+ toast.success("Turntable recorded — saved to your uploads");
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setRecording(null);
+ }
+ },
+ [name],
+ );
+ useEffect(() => {
if (!viewer) return;
- setRecording(0);
- try {
- const blob = await recordTurntable(viewer as Parameters<typeof recordTurntable>[0], { onProgress: setRecording });
- const url = URL.createObjectURL(blob);
- setRecorded({ url });
- // Keep it in the Library (Uploads) so it can go on to Edit video.
- const asset = await uploadFile(new File([blob], `${g.modelName ?? "model"} turntable.webm`, { type: "video/webm" }));
- setRecorded({ url, saved: asset.url });
- toast.success("Turntable recorded — saved to your uploads");
- } catch (e) {
- toast.error((e as Error).message);
- } finally {
- setRecording(null);
+ if (focusViewer.current) {
+ focusViewer.current = false;
+ // Its keyboard-focusable part (camera controls) is inside the shadow root.
+ (viewer.shadowRoot?.querySelector<HTMLElement>(".userInput") ?? viewer).focus({ preventScroll: true });
}
+ const onLoad = () => {
+ setLoadedEl(viewer);
+ if (pendingRecord.current) {
+ pendingRecord.current = false;
+ void startRecording(viewer);
+ }
+ };
+ // A model that can't load won't record either. (A web GLB that fails falls back to the original first.)
+ const onError = () => void (onOriginal && (pendingRecord.current = false));
+ viewer.addEventListener("load", onLoad);
+ viewer.addEventListener("error", onError);
+ return () => {
+ viewer.removeEventListener("load", onLoad);
+ viewer.removeEventListener("error", onError);
+ };
+ }, [viewer, startRecording, onOriginal]);
+ const switchTo = (v: "preview" | "3d") => {
+ // A recording asked for before the model loaded is off once the 3D view is closed.
+ if (v === "preview") pendingRecord.current = false;
+ setShow(v);
+ };
+ // Recording needs the 3D view: open it and start once the model has loaded.
+ const record = () => {
+ if (viewer && loaded) return void startRecording(viewer);
+ pendingRecord.current = true;
+ setShow("3d");
};
const spin = animateSpinHref(view, recorded?.saved);
- const name = (g.modelName ?? "model").replace(/[^\w .-]+/g, "");
+ const placeholder = still ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={still} alt={`The ${label} model`} loading="lazy" decoding="async" className="size-full object-contain" />
+ ) : (
+ <div className="grid size-full place-items-center text-muted-foreground">
+ <Box className="size-8" />
+ </div>
+ );
return (
<article className="overflow-hidden rounded-2xl border bg-background shadow-soft">
- <div className="relative aspect-[4/3] bg-[radial-gradient(circle_at_50%_40%,var(--muted),var(--background))]">
- {show === "video" && clip ? (
- <video src={clip} controls loop muted playsInline autoPlay preload="metadata" aria-label={`Turntable of the ${g.modelName ?? "3D"} model`} className="size-full bg-media object-contain" />
+ <div className="relative aspect-[4/3] bg-[radial-gradient(circle_at_50%_40%,var(--muted),var(--background))]" style={open3d && backdrop ? { background: backdrop } : undefined}>
+ {!open3d ? (
+ <>
+ {clip ? <TurntableLoop src={clip} poster={still} label={`Turntable of the ${label} model`} /> : placeholder}
+ {view.glb && (
+ <Button
+ size="sm"
+ variant="secondary"
+ className="absolute bottom-3 left-1/2 -translate-x-1/2 rounded-full shadow-soft"
+ onClick={() => {
+ focusViewer.current = true;
+ switchTo("3d");
+ }}
+ >
+ <Rotate3d className="size-3.5" /> View in 3D
+ </Button>
+ )}
+ </>
) : failed ? (
<div className="grid size-full place-items-center p-6 text-center text-[13px] text-muted-foreground">Couldn&apos;t load the 3D viewer — download the .glb to open it.</div>
- ) : !ready || !view.glb ? (
- <div className="grid size-full place-items-center text-muted-foreground">
- <Box className="size-8 animate-pulse" />
+ ) : !ready || !src ? (
+ // The poster (or the photo) while the viewer loads: the same picture the viewer starts from.
+ <div className="relative size-full" role="status" aria-label="Loading the 3D viewer">
+ {placeholder}
+ <Loader2 className="absolute right-3 bottom-3 size-4 animate-spin text-muted-foreground" />
</div>
) : (
createElement("model-viewer", {
ref: setViewer,
- src: view.glb,
- poster: view.poster,
+ src,
+ poster: still,
alt: `3D model made with ${g.modelName ?? "a 3D model"}`,
+ loading: "lazy",
+ reveal: "auto",
"camera-controls": "",
"auto-rotate": "",
- "shadow-intensity": "1",
- exposure: "1",
"touch-action": "pan-y",
"interaction-prompt": "none",
+ ...viewerLook(view.material),
style: { width: "100%", height: "100%", background: "transparent" },
})
)}
@@ -173,18 +254,18 @@ function ModelCard({ g }: { g: Generation }) {
</div>
)}
{g.provider === "mock" && <span className="absolute top-3 left-3 rounded-full bg-highlight/40 px-2 py-0.5 text-[11px] font-medium">Demo</span>}
- {clip && recording === null && (
+ {view.glb && recording === null && (
<div role="radiogroup" aria-label="Show" className="absolute top-3 right-3 inline-flex rounded-full bg-background/85 p-0.5 shadow-soft backdrop-blur">
- {(["3d", "video"] as const).map((v) => (
+ {(["preview", "3d"] as const).map((v) => (
<button
key={v}
type="button"
role="radio"
aria-checked={show === v}
- onClick={() => setShow(v)}
+ onClick={() => switchTo(v)}
className={cn("h-6 rounded-full px-2.5 text-[11px] font-medium transition", show === v ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground")}
>
- {v === "3d" ? "3D" : "Turntable"}
+ {v === "3d" ? "3D" : clip ? "Turntable" : "Preview"}
</button>
))}
</div>
@@ -216,8 +297,13 @@ function ModelCard({ g }: { g: Generation }) {
<Video className="size-3.5" /> Turntable
</a>
</Button>
+ ) : view.rendering ? (
+ // The server renders it after the job (one at a time): it shows up here when it's done.
+ <Button variant="outline" size="sm" className="rounded-full" disabled>
+ <Loader2 className="size-3.5 animate-spin" /> {view.rendering.queued ? "Turntable queued" : `Rendering turntable… ${Math.round(view.rendering.progress * 100)}%`}
+ </Button>
) : (
- <Button variant="outline" size="sm" className="rounded-full" onClick={record} disabled={!ready || !canRecord || recording !== null}>
+ <Button variant="outline" size="sm" className="rounded-full" onClick={record} disabled={!view.glb || !canRecord || recording !== null || failed}>
<Clapperboard className="size-3.5" /> Record turntable
</Button>
)}
@@ -233,3 +319,58 @@ function ModelCard({ g }: { g: Generation }) {
</article>
);
}
+
+const REDUCED_MOTION = "(prefers-reduced-motion: reduce)";
+
+/** Whether the user prefers reduced motion (true until hydrated, so nothing moves before it's known). */
+function useReducedMotion(): boolean {
+ return useSyncExternalStore(
+ (cb) => {
+ const mq = window.matchMedia(REDUCED_MOTION);
+ mq.addEventListener("change", cb);
+ return () => mq.removeEventListener("change", cb);
+ },
+ () => window.matchMedia(REDUCED_MOTION).matches,
+ () => true,
+ );
+}
+
+/**
+ * A card's turntable loop: it loads and plays only while the card is on screen, not at all when the user
+ * prefers reduced motion (the poster shows instead), and has a pause / play button (WCAG 2.2.2).
+ */
+function TurntableLoop({ src, poster, label }: { src: string; poster?: string; label: string }) {
+ const ref = useRef<HTMLVideoElement>(null);
+ const [visible, setVisible] = useState(false);
+ const reduced = useReducedMotion();
+ // What the user chose with the button; until then, play unless they prefer reduced motion.
+ const [choice, setChoice] = useState<"play" | "pause" | null>(null);
+ const wanted = choice ? choice === "play" : !reduced;
+ const playing = visible && wanted;
+ useEffect(() => {
+ const el = ref.current;
+ if (!el || typeof IntersectionObserver === "undefined") return;
+ const io = new IntersectionObserver(([e]) => setVisible(e.isIntersecting), { threshold: 0.5 });
+ io.observe(el);
+ return () => io.disconnect();
+ }, []);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ if (playing) void el.play().catch(() => {});
+ else el.pause();
+ }, [playing]);
+ return (
+ <>
+ <video ref={ref} src={src} poster={poster} loop muted playsInline preload="none" aria-label={label} className="size-full bg-media object-contain" />
+ <button
+ type="button"
+ onClick={() => setChoice(wanted ? "pause" : "play")}
+ aria-label={wanted ? "Pause the turntable" : "Play the turntable"}
+ className="absolute right-3 bottom-3 grid size-7 place-items-center rounded-full bg-background/85 text-foreground shadow-soft backdrop-blur transition hover:bg-background"
+ >
+ {wanted ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}
+ </button>
+ </>
+ );
+}
diff --git a/src/components/model3d/turntable.ts b/src/components/model3d/turntable.ts
index bdd80b16..6cec2ce7 100644
--- a/src/components/model3d/turntable.ts
+++ b/src/components/model3d/turntable.ts
@@ -1,55 +1,218 @@
"use client";
+import { muxWebm, type WebmFrame } from "./webm";
+
/**
- * Record a turntable video of a <model-viewer> in the browser: one full turn of the camera around the
- * model, captured from its canvas with MediaRecorder (WebM). For cloud 3D models that return only a .glb.
+ * Record a turntable video of a <model-viewer> in the browser: one full turn of the model on its turntable
+ * (the lights stay put, as on the server's render), on the same studio backdrop. For models whose result came
+ * without a turntable (cloud 3D models, or a server without Chromium / ffmpeg).
+ *
+ * Frame by frame, like the server: the model turns to each of TURN_FRAMES angles, renders, and the frame is
+ * taken with viewer.toBlob() (model-viewer draws it from whichever canvas is on screen; its own canvases can be
+ * hidden) and drawn over the backdrop on a canvas of ours. Then:
+ * - with WebCodecs (VideoEncoder), each frame is encoded at its own timestamp (i / TURNTABLE_FPS s) and muxed to
+ * WebM here (webm.ts): exactly 4 s at 24 fps however long each frame took to render;
+ * - without it, the frames are collected first and then played into MediaRecorder at 24 fps.
*/
-/** The WebM codec the browser can record, or null. */
-export function recordableType(): string | null {
+/** Frames per second of the recording. */
+export const TURNTABLE_FPS = 24;
+/** Frames in one full turn (96 at 24 fps = 4 s, 3.75 degrees a frame). */
+export const TURN_FRAMES = 96;
+/** The recording's longest side, in pixels (the viewer's size at its pixel ratio, up to this). */
+const MAX_SIDE = 1280;
+
+/** The turntable angle (radians) of frame `i`. */
+export const turnAngle = (i: number, frames = TURN_FRAMES) => (2 * Math.PI * (i % frames)) / frames;
+
+/** The WebCodecs VP9 / VP8 encoder settings this browser takes for a w×h recording, or null. */
+async function encoderConfig(width: number, height: number): Promise<{ config: VideoEncoderConfig; codec: "V_VP9" | "V_VP8" } | null> {
+ if (typeof VideoEncoder === "undefined" || typeof VideoFrame === "undefined") return null;
+ for (const [codec, id] of [
+ ["vp09.00.10.08", "V_VP9"],
+ ["vp8", "V_VP8"],
+ ] as const) {
+ const config: VideoEncoderConfig = { codec, width, height, bitrate: 8_000_000, framerate: TURNTABLE_FPS, latencyMode: "quality" };
+ try {
+ if ((await VideoEncoder.isConfigSupported(config)).supported) return { config, codec: id };
+ } catch {}
+ }
+ return null;
+}
+
+/** The WebM type MediaRecorder can record, or null. */
+function mediaRecorderType(): string | null {
if (typeof MediaRecorder === "undefined") return null;
return ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)) ?? null;
}
-type ViewerElement = HTMLElement & { cameraOrbit: string; jumpCameraToGoal?: () => void; shadowRoot: ShadowRoot | null };
+/** Whether this browser can record a turntable (WebCodecs or MediaRecorder). */
+export function recordableType(): string | null {
+ if (typeof VideoEncoder !== "undefined" && typeof VideoFrame !== "undefined") return "video/webm";
+ return mediaRecorderType();
+}
+
+type ViewerElement = HTMLElement & { resetTurntableRotation?: (theta?: number) => void; toBlob?: (o?: { mimeType?: string }) => Promise<Blob> };
+
+const nextFrame = () => new Promise<void>((r) => requestAnimationFrame(() => r()));
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+const even = (n: number) => Math.max(2, 2 * Math.floor(n / 2));
-/** Degrees per second of the recorded turn; a full turn takes 360 / TURN_SPEED seconds. */
-export const TURN_SPEED = 60;
+/** The studio sweep the server's turntable is rendered on (scripts/model3d/render-turntable.mjs), on a 2D canvas. */
+export function paintBackdrop(ctx: CanvasRenderingContext2D, w: number, h: number): void {
+ const r = w * (1250 / 2048);
+ ctx.save();
+ ctx.translate(w / 2, h * (700 / 1536));
+ ctx.scale(1, 1 / 1.25);
+ const g = ctx.createRadialGradient(0, 0, 0, 0, 0, r);
+ // The server's falloff is t = d^1.6 from #F3ECE3 to #D8CBBB; five stops follow it closely.
+ for (const d of [0, 0.25, 0.5, 0.75, 1]) {
+ const t = d ** 1.6;
+ g.addColorStop(d, `rgb(${Math.round(243 - 27 * t)} ${Math.round(236 - 33 * t)} ${Math.round(227 - 40 * t)})`);
+ }
+ ctx.fillStyle = g;
+ ctx.fillRect(-w, -h * 2, w * 2, h * 4);
+ ctx.restore();
+}
export async function recordTurntable(viewer: ViewerElement, o: { onProgress?: (p: number) => void; signal?: AbortSignal } = {}): Promise<Blob> {
- const type = recordableType();
- if (!type) throw new Error("This browser can't record video — download the .glb instead");
- const canvas = viewer.shadowRoot?.querySelector("canvas");
- if (!canvas || !("captureStream" in canvas)) throw new Error("The 3D viewer isn't ready yet");
- const stream = (canvas as HTMLCanvasElement).captureStream(30);
- const rec = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: 6_000_000 });
- const chunks: Blob[] = [];
- rec.ondataavailable = (e) => e.data.size && chunks.push(e.data);
- const stopped = new Promise<void>((resolve) => (rec.onstop = () => resolve()));
- // Drive the camera ourselves: auto-rotate off, one turn at a steady speed.
+ if (!recordableType()) throw new Error("This browser can't record video — download the .glb instead");
+ const { resetTurntableRotation, toBlob } = viewer;
+ if (!resetTurntableRotation || !toBlob) throw new Error("The 3D viewer isn't ready yet");
+ const turn = (theta: number) => resetTurntableRotation.call(viewer, theta);
+ const stopped = () => {
+ if (o.signal?.aborted) throw new Error("Stopped");
+ };
+ // Drive the turntable ourselves: auto-rotate off, one turn in fixed steps.
const auto = viewer.hasAttribute("auto-rotate");
viewer.removeAttribute("auto-rotate");
- const parts = (viewer.cameraOrbit || "0deg 75deg 105%").split(/\s+/);
- const [, phi = "75deg", radius = "105%"] = parts;
- const seconds = 360 / TURN_SPEED;
- rec.start(250);
- const t0 = performance.now();
- await new Promise<void>((resolve) => {
- const tick = () => {
- const t = (performance.now() - t0) / 1000;
- const done = t >= seconds || o.signal?.aborted;
- viewer.cameraOrbit = `${Math.min(360, t * TURN_SPEED)}deg ${phi} ${radius}`;
- viewer.jumpCameraToGoal?.();
- o.onProgress?.(Math.min(1, t / seconds));
- if (done) resolve();
- else requestAnimationFrame(tick);
+ try {
+ /** Frame i on the backdrop, on our canvas (sized from the first frame). */
+ let canvas: HTMLCanvasElement | null = null;
+ let ctx: CanvasRenderingContext2D | null = null;
+ const grab = async (i: number) => {
+ turn(turnAngle(i));
+ // The new angle renders on the next frame; one more for the contact shadow.
+ for (let k = 0; k < 3; k++) await nextFrame();
+ const bitmap = await createImageBitmap(await toBlob.call(viewer, { mimeType: "image/png" }));
+ try {
+ if (!canvas) {
+ const scale = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height));
+ canvas = document.createElement("canvas");
+ canvas.width = even(bitmap.width * scale);
+ canvas.height = even(bitmap.height * scale);
+ ctx = canvas.getContext("2d");
+ if (!ctx) throw new Error("This browser can't record video — download the .glb instead");
+ }
+ paintBackdrop(ctx!, canvas.width, canvas.height);
+ ctx!.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
+ } finally {
+ bitmap.close();
+ }
+ return canvas;
};
- requestAnimationFrame(tick);
+
+ // Size the recording from the first frame, then pick the encoder.
+ const first = await grab(0);
+ stopped();
+ const enc = await encoderConfig(first.width, first.height);
+ if (enc) return await withWebCodecs(first, grab, enc, o, stopped);
+ // WebCodecs without VP9 / VP8 (Safari encodes H.264 only) and no WebM MediaRecorder either.
+ if (!mediaRecorderType()) throw new Error("This browser can't record video — download the .glb instead");
+ return await withMediaRecorder(first, grab, o, stopped);
+ } finally {
+ turn(0);
+ if (auto) viewer.setAttribute("auto-rotate", "");
+ }
+}
+
+/** Encode each frame at its own timestamp: the clip's timing never depends on how fast the frames rendered. */
+async function withWebCodecs(
+ canvas: HTMLCanvasElement,
+ grab: (i: number) => Promise<HTMLCanvasElement>,
+ enc: { config: VideoEncoderConfig; codec: "V_VP9" | "V_VP8" },
+ o: { onProgress?: (p: number) => void },
+ stopped: () => void,
+): Promise<Blob> {
+ const frames: WebmFrame[] = [];
+ let failure: Error | null = null;
+ const encoder = new VideoEncoder({
+ output: (chunk) => {
+ const data = new Uint8Array(chunk.byteLength);
+ chunk.copyTo(data);
+ frames.push({ data, timestamp: chunk.timestamp, key: chunk.type === "key" });
+ },
+ error: (e) => (failure = e instanceof Error ? e : new Error(String(e))),
});
- rec.stop();
- await stopped;
- stream.getTracks().forEach((t) => t.stop());
- if (auto) viewer.setAttribute("auto-rotate", "");
- if (o.signal?.aborted) throw new Error("Stopped");
- return new Blob(chunks, { type: "video/webm" });
+ encoder.configure(enc.config);
+ const us = 1e6 / TURNTABLE_FPS;
+ try {
+ for (let i = 0; i < TURN_FRAMES; i++) {
+ if (failure) throw failure;
+ stopped();
+ const c = i === 0 ? canvas : await grab(i);
+ const frame = new VideoFrame(c, { timestamp: Math.round(i * us), duration: Math.round(us) });
+ encoder.encode(frame, { keyFrame: i % TURNTABLE_FPS === 0 });
+ frame.close();
+ while (encoder.encodeQueueSize > 4) await sleep(5);
+ o.onProgress?.((i + 1) / TURN_FRAMES);
+ }
+ await encoder.flush();
+ if (failure) throw failure;
+ } finally {
+ if (encoder.state !== "closed") encoder.close();
+ }
+ if (frames.length < TURN_FRAMES) throw new Error("The recording came out empty — download the .glb instead");
+ frames.sort((a, b) => a.timestamp - b.timestamp);
+ return muxWebm({ codec: enc.codec, width: canvas.width, height: canvas.height, fps: TURNTABLE_FPS, frames });
+}
+
+/**
+ * Without WebCodecs: collect the frames first (PNG blobs), then play them into MediaRecorder at the frame rate.
+ * Drawing a decoded frame is quick, so the playback keeps time where rendering couldn't.
+ */
+async function withMediaRecorder(canvas: HTMLCanvasElement, grab: (i: number) => Promise<HTMLCanvasElement>, o: { onProgress?: (p: number) => void }, stopped: () => void): Promise<Blob> {
+ const type = mediaRecorderType()!;
+ const shot = (c: HTMLCanvasElement) => new Promise<Blob>((resolve, reject) => c.toBlob((b) => (b ? resolve(b) : reject(new Error("The 3D viewer isn't ready yet"))), "image/png"));
+ const stills: Blob[] = [await shot(canvas)];
+ for (let i = 1; i < TURN_FRAMES; i++) {
+ stopped();
+ stills.push(await shot(await grab(i)));
+ o.onProgress?.((0.8 * (i + 1)) / TURN_FRAMES);
+ }
+ const ctx = canvas.getContext("2d")!;
+ // Frame rate 0: a frame is captured only when requested.
+ const stream = canvas.captureStream(0);
+ const track = stream.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void };
+ const rec = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: 8_000_000 });
+ const chunks: Blob[] = [];
+ rec.ondataavailable = (e) => e.data.size && chunks.push(e.data);
+ const done = new Promise<void>((resolve) => (rec.onstop = () => resolve()));
+ const step = 1000 / TURNTABLE_FPS;
+ let next = createImageBitmap(stills[0]);
+ rec.start(250);
+ const t0 = performance.now();
+ try {
+ // One more than the frames: the last request only closes the last frame's duration.
+ for (let i = 0; i <= TURN_FRAMES; i++) {
+ stopped();
+ const bitmap = i < TURN_FRAMES ? await next : null;
+ if (i + 1 < TURN_FRAMES) next = createImageBitmap(stills[i + 1]);
+ const wait = t0 + i * step - performance.now();
+ if (wait > 0) await sleep(wait);
+ if (bitmap) {
+ ctx.drawImage(bitmap, 0, 0);
+ bitmap.close();
+ }
+ track.requestFrame?.();
+ o.onProgress?.(0.8 + (0.2 * Math.min(i, TURN_FRAMES)) / TURN_FRAMES);
+ }
+ } finally {
+ rec.stop();
+ await done;
+ stream.getTracks().forEach((t) => t.stop());
+ }
+ const blob = new Blob(chunks, { type: "video/webm" });
+ if (!blob.size) throw new Error("The recording came out empty — download the .glb instead");
+ return blob;
}
diff --git a/src/components/model3d/webm.ts b/src/components/model3d/webm.ts
new file mode 100644
index 00000000..525f8b67
--- /dev/null
+++ b/src/components/model3d/webm.ts
@@ -0,0 +1,160 @@
+/**
+ * A minimal WebM writer for the browser's turntable recording (turntable.ts): one VP8 or VP9 video track, every
+ * frame in memory (a few seconds), each at the timestamp it was given. Unlike MediaRecorder's WebM it has a
+ * duration and cues, so players and the frame sampler know its length and can seek.
+ *
+ * Layout: EBML header, then a Segment of Info (1 ms timestamps, duration), Tracks, Cues (before the clusters,
+ * so no SeekHead is needed) and one Cluster per key frame.
+ */
+
+export interface WebmFrame {
+ data: Uint8Array;
+ /** Microseconds from the start (WebCodecs' EncodedVideoChunk.timestamp). */
+ timestamp: number;
+ key: boolean;
+}
+
+type Part = Uint8Array;
+
+const concat = (parts: Part[]): Uint8Array => {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let at = 0;
+ for (const p of parts) {
+ out.set(p, at);
+ at += p.length;
+ }
+ return out;
+};
+
+/** An element ID: its bytes as written (the length marker is part of the ID). */
+function idBytes(id: number): Part {
+ const bytes: number[] = [];
+ for (let v = id; v > 0; v = Math.floor(v / 256)) bytes.unshift(v & 0xff);
+ return Uint8Array.from(bytes);
+}
+
+/** A data size as an EBML variable-length integer (the shortest that fits; all-ones is reserved). */
+function sizeBytes(n: number): Part {
+ let len = 1;
+ while (n >= 2 ** (7 * len) - 1) len++;
+ const out = new Uint8Array(len);
+ let v = n;
+ for (let i = len - 1; i >= 0; i--) {
+ out[i] = v % 256;
+ v = Math.floor(v / 256);
+ }
+ out[0] |= 0x80 >> (len - 1);
+ return out;
+}
+
+/** An unsigned integer, big-endian, in `width` bytes (or the fewest that hold it). */
+function uintBytes(n: number, width?: number): Part {
+ const bytes: number[] = [];
+ for (let v = n; v > 0; v = Math.floor(v / 256)) bytes.unshift(v % 256);
+ while (bytes.length < (width ?? 1)) bytes.unshift(0);
+ return Uint8Array.from(bytes);
+}
+
+const el = (id: number, ...body: Part[]): Part => {
+ const data = concat(body);
+ return concat([idBytes(id), sizeBytes(data.length), data]);
+};
+const uint = (id: number, n: number, width?: number) => el(id, uintBytes(n, width));
+const str = (id: number, s: string) => el(id, Uint8Array.from(s, (c) => c.charCodeAt(0) & 0x7f));
+const float = (id: number, n: number) => {
+ const b = new Uint8Array(8);
+ new DataView(b.buffer).setFloat64(0, n);
+ return el(id, b);
+};
+
+/** The EBML IDs used here (Matroska / WebM spec names). */
+export const WEBM_IDS = {
+ EBML: 0x1a45dfa3,
+ Segment: 0x18538067,
+ Info: 0x1549a966,
+ TimestampScale: 0x2ad7b1,
+ Duration: 0x4489,
+ Tracks: 0x1654ae6b,
+ TrackEntry: 0xae,
+ CodecID: 0x86,
+ Video: 0xe0,
+ PixelWidth: 0xb0,
+ PixelHeight: 0xba,
+ Cues: 0x1c53bb6b,
+ CuePoint: 0xbb,
+ CueTime: 0xb3,
+ CueTrackPositions: 0xb7,
+ CueClusterPosition: 0xf1,
+ Cluster: 0x1f43b675,
+ Timestamp: 0xe7,
+ SimpleBlock: 0xa3,
+} as const;
+const I = WEBM_IDS;
+
+/** Mux encoded frames (in order, the first a key frame) into a WebM file. */
+export function muxWebm(o: { codec: "V_VP8" | "V_VP9"; width: number; height: number; fps: number; frames: WebmFrame[] }): Blob {
+ if (!o.frames.length || !o.frames[0].key) throw new Error("A WebM needs frames, starting with a key frame");
+ const ms = (us: number) => Math.round(us / 1000);
+ const frameMs = 1000 / o.fps;
+ const header = el(
+ I.EBML,
+ uint(0x4286, 1), // EBMLVersion
+ uint(0x42f7, 1), // EBMLReadVersion
+ uint(0x42f2, 4), // EBMLMaxIDLength
+ uint(0x42f3, 8), // EBMLMaxSizeLength
+ str(0x4282, "webm"), // DocType
+ uint(0x4287, 2), // DocTypeVersion (SimpleBlock)
+ uint(0x4285, 2), // DocTypeReadVersion
+ );
+ const last = o.frames[o.frames.length - 1];
+ const info = el(I.Info, uint(I.TimestampScale, 1_000_000), float(I.Duration, ms(last.timestamp) + frameMs), str(0x4d80, "Fuobe"), str(0x5741, "Fuobe"));
+ const tracks = el(
+ I.Tracks,
+ el(
+ I.TrackEntry,
+ uint(0xd7, 1), // TrackNumber
+ uint(0x73c5, 1), // TrackUID
+ uint(0x9c, 0), // FlagLacing
+ str(I.CodecID, o.codec),
+ uint(0x83, 1), // TrackType: video
+ uint(0x23e383, Math.round(1e9 / o.fps)), // DefaultDuration (ns)
+ el(I.Video, uint(I.PixelWidth, o.width), uint(I.PixelHeight, o.height)),
+ ),
+ );
+ // One cluster per key frame; block times are relative to the cluster's (16-bit, so a cluster spans < 32 s).
+ const clusters: { time: number; bytes: Part }[] = [];
+ let group: WebmFrame[] = [];
+ const close = () => {
+ if (!group.length) return;
+ const time = ms(group[0].timestamp);
+ const blocks = group.map((f) => {
+ const head = new Uint8Array(4);
+ head[0] = 0x81; // track 1
+ new DataView(head.buffer).setInt16(1, ms(f.timestamp) - time);
+ head[3] = f.key ? 0x80 : 0;
+ return el(I.SimpleBlock, head, f.data);
+ });
+ clusters.push({ time, bytes: el(I.Cluster, uint(I.Timestamp, time), ...blocks) });
+ group = [];
+ };
+ for (const f of o.frames) {
+ if (f.key || (group.length && ms(f.timestamp) - ms(group[0].timestamp) > 30_000)) close();
+ group.push(f);
+ }
+ close();
+ // Cues sit before the clusters: positions are 8 bytes wide, so the cues' own size doesn't depend on them.
+ const cues = (positions: number[]) =>
+ el(
+ I.Cues,
+ ...clusters.map((c, i) => el(I.CuePoint, uint(I.CueTime, c.time), el(I.CueTrackPositions, uint(0xf7, 1), uint(I.CueClusterPosition, positions[i], 8)))),
+ );
+ const cuesSize = cues(clusters.map(() => 0)).length;
+ const positions: number[] = [];
+ let at = info.length + tracks.length + cuesSize;
+ for (const c of clusters) {
+ positions.push(at);
+ at += c.bytes.length;
+ }
+ const segment = el(I.Segment, info, tracks, cues(positions), ...clusters.map((c) => c.bytes));
+ return new Blob([concat([header, segment]) as Uint8Array<ArrayBuffer>], { type: "video/webm" });
+}
diff --git a/src/components/preset-gallery.tsx b/src/components/preset-gallery.tsx
index 33dfe530..b1242412 100644
--- a/src/components/preset-gallery.tsx
+++ b/src/components/preset-gallery.tsx
@@ -9,6 +9,7 @@ import { GALLERY_GRID } from "@/components/skeletons";
import { useProgressive } from "@/components/use-progressive";
import { useEngineMode } from "@/lib/api";
import { interleaveByCategory, previewFlip, searchText, type PresetCardData } from "@/lib/preset-cards";
+import { PREVIEW_SIZES } from "@/lib/preview-media";
import { cn } from "@/lib/utils";
/** A tiny label shown on hover/focus (CSS only: a gallery has hundreds of these). */
@@ -33,12 +34,18 @@ export const PresetCard = memo(function PresetCard({
href,
compact,
engine,
+ sizes,
+ priority,
}: {
preset: PresetCardData;
href: string;
compact?: boolean;
/** Settings → Engine mode: with one engine locked in, the other's chip would suggest a route the user turned off. */
engine?: "cloud" | "open";
+ /** How wide the card is drawn (PREVIEW_SIZES), for picking its poster's size. */
+ sizes?: string;
+ /** Load the poster at once, ahead of other images (a gallery's first row). */
+ priority?: boolean;
}) {
const Icon = PRESET_ICONS[preset.icon] ?? Sparkles;
const { ref, playing, handlers } = usePreviewPlayback<HTMLAnchorElement>(preset.id);
@@ -50,7 +57,7 @@ export const PresetCard = memo(function PresetCard({
className="group/card flex min-w-0 flex-col gap-2 rounded-xl p-1.5 transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"
>
<div className="relative aspect-[4/3] overflow-hidden rounded-lg bg-muted">
- <PresetPreview preview={preset.preview} hue={preset.hue} playing={playing} flip={previewFlip(preset)} />
+ <PresetPreview preview={preset.preview} hue={preset.hue} playing={playing} flip={previewFlip(preset)} card={preset} sizes={sizes} priority={priority} />
<span className="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-gradient-to-t from-black/40 to-transparent" />
<span className="pointer-events-none absolute bottom-1.5 left-1.5 grid size-6 place-items-center rounded-md bg-black/30 text-white">
<Icon className="size-3.5" />
@@ -155,6 +162,8 @@ function useFadeEdges<T extends HTMLElement>() {
const FIRST_PAGE = 30;
const PAGE = 40;
+/** Cards in the grid's widest first row (GALLERY_GRID): their posters load at once. */
+const FIRST_ROW = 5;
const GRID = GALLERY_GRID;
@@ -258,8 +267,8 @@ export function PresetGallery({
{list.length ? (
<>
<div ref={grid} className={cn(GRID, "transition-opacity", stale && "opacity-70")}>
- {list.slice(0, shown).map((p) => (
- <PresetCard key={p.id} preset={p} href={href.replace("{id}", p.id)} engine={locked} />
+ {list.slice(0, shown).map((p, i) => (
+ <PresetCard key={p.id} preset={p} href={href.replace("{id}", p.id)} engine={locked} sizes={PREVIEW_SIZES.gallery} priority={i < FIRST_ROW} />
))}
</div>
{hasMore && (
diff --git a/src/components/preset-header.tsx b/src/components/preset-header.tsx
index e4514565..279932ab 100644
--- a/src/components/preset-header.tsx
+++ b/src/components/preset-header.tsx
@@ -1,26 +1,14 @@
"use client";
import { Cloud, Cpu, Info, X } from "lucide-react";
-import { useSyncExternalStore } from "react";
-import { PresetPreview } from "@/components/preset-preview";
+import { PresetPreview, useAutoplay } from "@/components/preset-preview";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import type { Preset } from "@/lib/catalog/types";
-import { presetHowTo, presetRouteLines, previewFlip, toPresetCard } from "@/lib/preset-cards";
+import { toPresetCard } from "@/lib/preset-card-data";
+import { presetHowTo, presetRouteLines, previewFlip } from "@/lib/preset-cards";
+import { PREVIEW_SIZES } from "@/lib/preview-media";
import { cn } from "@/lib/utils";
-const REDUCED = "(prefers-reduced-motion: reduce)";
-function useReducedMotion() {
- return useSyncExternalStore(
- (cb) => {
- const mq = window.matchMedia(REDUCED);
- mq.addEventListener("change", cb);
- return () => mq.removeEventListener("change", cb);
- },
- () => window.matchMedia(REDUCED).matches,
- () => true,
- );
-}
-
/**
* The card a studio shows above its composer while a preset (app, camera motion, effect) is active
* and the feed is still empty: the preview looping, the name, one line on what to do, the models it
@@ -44,12 +32,12 @@ export function PresetHeader({
className?: string;
}) {
const card = toPresetCard(preset);
- const reduced = useReducedMotion();
+ const autoplay = useAutoplay();
const routes = presetRouteLines(preset, modelName);
return (
<div className={cn("mx-auto flex w-full max-w-[760px] items-center gap-3 rounded-2xl border bg-background p-2 pr-3 text-left shadow-soft", className)}>
<div className="relative aspect-[4/3] w-24 shrink-0 overflow-hidden rounded-xl bg-muted sm:w-32">
- <PresetPreview preview={card.preview} hue={card.hue} playing={!reduced} flip={previewFlip(card)} />
+ <PresetPreview preview={card.preview} hue={card.hue} playing={autoplay} flip={previewFlip(card)} card={card} sizes={PREVIEW_SIZES.header} priority />
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-heading text-[19px] leading-snug">{preset.name}</p>
diff --git a/src/components/preset-preview.tsx b/src/components/preset-preview.tsx
index a8facb5b..091f80af 100644
--- a/src/components/preset-preview.tsx
+++ b/src/components/preset-preview.tsx
@@ -1,20 +1,27 @@
"use client";
import { memo, useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { PreviewMedia } from "@/components/preview-media";
+import { useReducedMotion } from "@/hooks/use-reduced-motion";
import {
CAMERA_MOVES,
+ fallbackPreview,
LAYER_DEPTH,
LAYER_OFFSET,
moveVars,
PREVIEW_LAYERS,
sceneLayer,
scenePoster,
+ type CameraMove,
type MoveSpec,
+ type PresetCardData,
type PresetPreview as Preview,
type PreviewLayer,
type PreviewScene,
+ type ProceduralPreview,
} from "@/lib/preset-cards";
import { glyphFor } from "@/lib/move-glyphs";
+import { kindOf, PREVIEW_SIZES, previewSrc } from "@/lib/preview-media";
import { browserPlaybackEnv, createPlaybackStore } from "@/lib/preview-playback";
/** One preview plays at a time (rules in lib/preview-playback.ts). */
@@ -22,7 +29,8 @@ const store = createPlaybackStore(browserPlaybackEnv);
/**
* Wire a card element to the playback store. Returns whether its preview should play and the
- * handlers to spread on the card (hover and focus on desktop; touch devices use visibility).
+ * handlers to spread on the card (hover and keyboard focus on desktop, after a short rest; touch
+ * devices use visibility).
*/
export function usePreviewPlayback<T extends HTMLElement>(id: string) {
const ref = useRef<T | null>(null);
@@ -45,12 +53,25 @@ export function usePreviewPlayback<T extends HTMLElement>(id: string) {
handlers: {
onPointerEnter: (e: React.PointerEvent) => e.pointerType === "mouse" && on(),
onPointerLeave: (e: React.PointerEvent) => e.pointerType === "mouse" && off(),
- onFocus: on,
+ // Keyboard focus only: a tap (or click) focuses the card too, and would start (and download) its clip.
+ onFocus: (e: React.FocusEvent) => e.currentTarget.matches(":focus-visible") && on(),
onBlur: off,
},
};
}
+const noSubscribe = () => () => {};
+
+/**
+ * Whether a preview may play without being hovered (the preset header's loop): not when the user
+ * prefers reduced motion, nor with Save-Data or on a 2G connection.
+ */
+export function useAutoplay(): boolean {
+ const reduced = useReducedMotion();
+ const saveData = useSyncExternalStore(noSubscribe, store.saveData, () => true);
+ return !reduced && !saveData;
+}
+
const layerVars = (l: PreviewLayer) => ({ "--d": LAYER_DEPTH[l], "--o": LAYER_OFFSET[l] }) as React.CSSProperties;
/** The other still a transition wipes to. */
@@ -242,54 +263,27 @@ function Fx({ fx, scene }: { fx: NonNullable<Preview["fx"]>; scene: PreviewScene
}
}
+/** The line diagram of a camera move (move-glyphs.ts), over a motion's resting frame until it plays. */
+function MoveGlyph({ move }: { move: CameraMove }) {
+ return (
+ <svg className="pv-glyph" viewBox="0 0 48 36" aria-hidden>
+ {glyphFor(move).map((part, i) => (
+ <path key={i} d={part.d} data-dashed={part.dashed || undefined} />
+ ))}
+ </svg>
+ );
+}
+
/**
- * A preset's preview: a real clip when the catalog has one, otherwise the procedural version, a
- * camera move over a layered sample still (motions) or an animated treatment (effects, apps).
- * At rest it shows the poster frame (and the treatment's still frame); `playing` runs it. The depth
- * layers a camera move needs are only mounted once the card first plays.
+ * The procedural preview: a camera move over a layered sample still (motions) or an animated
+ * treatment (effects, apps). At rest it shows the poster frame (and the treatment's still frame);
+ * `playing` runs it. The depth layers a camera move needs are only mounted once the card first plays.
*/
-export const PresetPreview = memo(function PresetPreview({
- preview,
- hue,
- playing,
- flip,
-}: {
- preview: Preview;
- hue: number;
- playing: boolean;
- /** Mirror the still (see previewFlip). */
- flip?: boolean;
-}) {
- const video = useRef<HTMLVideoElement>(null);
+function Procedural({ preview, hue, playing, flip }: { preview: ProceduralPreview; hue: number; playing: boolean; flip?: boolean }) {
const [armed, setArmed] = useState(false);
if (playing && !armed) setArmed(true);
- useEffect(() => {
- const v = video.current;
- if (!v) return;
- if (playing) void v.play().catch(() => {});
- else {
- v.pause();
- v.currentTime = 0;
- }
- }, [playing]);
-
- if (preview.video)
- return (
- <video
- ref={video}
- src={preview.video}
- poster={preview.poster}
- muted
- loop
- playsInline
- preload="none"
- className="absolute inset-0 size-full object-cover"
- aria-hidden
- />
- );
const spec: MoveSpec | undefined = preview.move ? CAMERA_MOVES[preview.move] : undefined;
- const glyph = preview.move ? glyphFor(preview.move) : undefined;
const style = { "--pv-hue": hue, ...(spec ? moveVars(spec) : {}) } as React.CSSProperties;
return (
<div
@@ -328,13 +322,48 @@ export const PresetPreview = memo(function PresetPreview({
)}
</div>
</div>
- {glyph && (
- <svg className="pv-glyph" viewBox="0 0 48 36" aria-hidden>
- {glyph.map((part, i) => (
- <path key={i} d={part.d} data-dashed={part.dashed || undefined} />
- ))}
- </svg>
- )}
+ {preview.move && <MoveGlyph move={preview.move} />}
+ </div>
+ );
+}
+
+/**
+ * A preset's preview: its rendered media when it has some (a poster, and a clip while `playing`),
+ * otherwise the procedural version. A card whose media doesn't load falls back to the procedural
+ * version too, worked out from `card`.
+ */
+export const PresetPreview = memo(function PresetPreview({
+ preview,
+ hue,
+ playing,
+ flip,
+ card,
+ sizes = PREVIEW_SIZES.gallery,
+ priority,
+}: {
+ preview: Preview;
+ hue: number;
+ playing: boolean;
+ /** Mirror the still (see previewFlip). */
+ flip?: boolean;
+ /** The card it's for: the id names the media files, and id, name and category give the fallback (fallbackPreview). */
+ card?: Pick<PresetCardData, "id" | "name" | "category">;
+ /** How wide the card is drawn (PREVIEW_SIZES), for picking the poster's size. */
+ sizes?: string;
+ /** Load the poster at once, ahead of other images (a gallery's first row). */
+ priority?: boolean;
+}) {
+ // The media hash whose files didn't load.
+ const [failed, setFailed] = useState<string>();
+ const kind = card ? kindOf(card.id) : undefined;
+ const media = preview.media;
+ if (media === undefined) return <Procedural preview={preview} hue={hue} playing={playing} flip={flip} />;
+ if (!card) return null;
+ if (!kind || failed === media) return <Procedural preview={fallbackPreview(card)} hue={hue} playing={playing} flip={flip} />;
+ return (
+ <div className="pv" data-playing={playing || undefined} aria-hidden>
+ {/* No move glyph over real media: the clip itself shows the move, and the line diagram clutters a photograph. */}
+ <PreviewMedia src={previewSrc(kind, card.id, media)} playing={playing} sizes={sizes} priority={priority} onError={() => setFailed(media)} />
</div>
);
});
diff --git a/src/components/preview-media.tsx b/src/components/preview-media.tsx
new file mode 100644
index 00000000..494bf8bb
--- /dev/null
+++ b/src/components/preview-media.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useReducedMotion } from "@/hooks/use-reduced-motion";
+import { releaseVideo } from "@/lib/media-release";
+import type { PreviewSources } from "@/lib/preview-media";
+
+/** How long a stopped clip stays mounted: its fade-out, and a quick hover back resumes it instead of reloading. */
+const LINGER_MS = 250;
+
+/**
+ * A card's rendered preview (lib/preview-media.ts), filling its positioned parent: the poster as a
+ * <picture> (AVIF srcset with a WebP fallback, lazy unless `priority`) and, only while `playing`,
+ * the muted loop, which fades in over the poster once it actually plays and is unmounted shortly
+ * after it stops. One preview plays at a time (lib/preview-playback.ts), so a page keeps at most
+ * one video element alive, plus one fading out. With reduced motion only the poster shows.
+ * `onError` fires when the poster or the clip doesn't load, so the card can show something else.
+ */
+export function PreviewMedia({
+ src,
+ playing,
+ sizes,
+ priority,
+ onError,
+}: {
+ src: PreviewSources;
+ playing: boolean;
+ /** How wide the card is drawn (PREVIEW_SIZES), for picking from the AVIF srcset. */
+ sizes: string;
+ /** Load the poster at once, ahead of other images (a gallery's first row). */
+ priority?: boolean;
+ onError?: () => void;
+}) {
+ const reduced = useReducedMotion();
+ // A still (no clip yet) only ever shows its poster.
+ const play = playing && !reduced && src.mp4Src !== undefined;
+ const img = useRef<HTMLImageElement>(null);
+ const video = useRef<HTMLVideoElement>(null);
+ // The clip's element exists from the moment it should play until LINGER_MS after it stops…
+ const [mounted, setMounted] = useState(false);
+ // …and shows once it has started; until then the poster shows through.
+ const [started, setStarted] = useState(false);
+ if (play && !mounted) setMounted(true);
+
+ useEffect(() => {
+ if (play || !mounted) return;
+ // State only, the element is let go below once it's really gone: a hover back that lands before
+ // React commits this keeps the element, still playing and shown.
+ const t = setTimeout(() => setMounted(false), LINGER_MS);
+ return () => clearTimeout(t);
+ }, [play, mounted]);
+
+ const mp4 = src.mp4Src;
+ useEffect(() => {
+ if (!mounted || !mp4) return;
+ const v = video.current;
+ if (!v) return;
+ // A re-run after this effect's cleanup (Strict Mode, a page shown again from a hidden <Activity>) gets its source back.
+ if (!v.getAttribute("src")) v.setAttribute("src", mp4);
+ // autoPlay starts it as well; this covers browsers that hold the attribute back.
+ void v.play().catch(() => {});
+ return () => {
+ // Let go of the decoder and the connection when the element goes, not when it's garbage collected.
+ releaseVideo(v);
+ setStarted(false);
+ };
+ }, [mounted, mp4]);
+
+ // A poster that failed before hydration fired its error event before React was listening.
+ useEffect(() => {
+ const el = img.current;
+ if (el?.complete && !el.naturalWidth) onError?.();
+ }, [onError]);
+
+ return (
+ <>
+ <picture>
+ <source type="image/avif" srcSet={src.avifSrcSet} sizes={sizes} />
+ <img
+ ref={img}
+ src={src.webpSrc}
+ alt=""
+ loading={priority ? "eager" : "lazy"}
+ fetchPriority={priority ? "high" : undefined}
+ decoding="async"
+ draggable={false}
+ onError={onError}
+ className="absolute inset-0 size-full object-cover select-none"
+ />
+ </picture>
+ {mounted && mp4 && (
+ <video
+ ref={video}
+ src={mp4}
+ muted
+ playsInline
+ loop
+ autoPlay
+ disablePictureInPicture
+ disableRemotePlayback
+ preload="auto"
+ aria-hidden
+ onPlaying={() => setStarted(true)}
+ // Letting go of the source (above) isn't a failure.
+ onError={(e) => e.currentTarget.hasAttribute("src") && onError?.()}
+ data-shown={(play && started) || undefined}
+ className="absolute inset-0 size-full object-cover opacity-0 transition-opacity duration-200 data-shown:opacity-100"
+ />
+ )}
+ </>
+ );
+}
diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsx
index fc120e78..e683aa1a 100644
--- a/src/components/settings-form.tsx
+++ b/src/components/settings-form.tsx
@@ -1,7 +1,7 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { CheckCircle2, CircleAlert, Cloud, Cpu, ExternalLink, Layers, Loader2 } from "lucide-react";
+import { CheckCircle2, CircleAlert, Cloud, Cpu, ExternalLink, Layers, Loader2, RefreshCw } from "lucide-react";
import { useEffect, useId, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
@@ -12,6 +12,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import { NotificationSettings } from "@/components/notification-settings";
import { SecuritySettings } from "@/components/security-settings";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
interface PublicSetting {
name: string;
@@ -112,15 +113,16 @@ function EngineModePicker({ value, onChange }: { value: string; onChange: (v: st
);
}
-function TestButton({ provider }: { provider: string }) {
+/** A provider's connection check (`provider`), or another endpoint's (`url` and `body`) that answers {ok, detail}. */
+function TestButton({ provider, url = "/api/providers/test", body }: { provider?: string; url?: string; body?: Record<string, unknown> }) {
const [res, setRes] = useState<{ ok: boolean; detail: string } | null>(null);
const m = useMutation({
mutationFn: async () =>
(await (
- await fetch("/api/providers/test", {
+ await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ provider }),
+ body: JSON.stringify(body ?? { provider }),
})
).json()) as { ok: boolean; detail: string },
onSuccess: setRes,
@@ -145,12 +147,15 @@ function Field({
label,
hint,
placeholder,
+ options,
onSave,
}: {
setting?: PublicSetting;
label: string;
hint?: React.ReactNode;
placeholder?: string;
+ /** Suggestions to pick from (the models a server lists); any value can still be typed. */
+ options?: string[];
onSave: (v: string) => void;
}) {
const [v, setV] = useState("");
@@ -171,12 +176,20 @@ function Field({
type={setting?.secret ? "password" : "text"}
value={shown}
placeholder={setting?.secret && setting.isSet ? setting.value : placeholder}
+ list={options?.length ? `${id}-list` : undefined}
onChange={(e) => {
setEditing(true);
setV(e.target.value);
}}
className="font-mono text-[13px]"
/>
+ {!!options?.length && (
+ <datalist id={`${id}-list`}>
+ {options.map((o) => (
+ <option key={o} value={o} />
+ ))}
+ </datalist>
+ )}
<Button
size="sm"
className="h-9 shrink-0"
@@ -204,6 +217,220 @@ function Field({
);
}
+type LocalKind = "ollama" | "lmstudio" | "unsloth" | "custom";
+
+/** A local LLM server as GET /api/llm reports it (no keys). */
+interface LocalServerStatus {
+ kind: LocalKind;
+ label: string;
+ url: string;
+ up: boolean;
+ auth: "none" | "ok" | "missing" | "rejected";
+ models: { id: string; name?: string; loaded?: boolean; context?: number | null; maxContext?: number | null }[];
+ model: string | null;
+ loaded: boolean | null;
+ context: number | null;
+ problem: string | null;
+ warning: string | null;
+ native?: boolean;
+}
+
+interface LocalLlmInfo {
+ provider: "auto" | LocalKind;
+ /** Settings' context, in tokens (0: the server's own). */
+ context: number;
+ /** The server text steps and Assist use now. */
+ active: LocalKind | null;
+ servers: LocalServerStatus[];
+}
+
+const LOCAL_SERVERS: { value: "auto" | LocalKind; title: string }[] = [
+ { value: "auto", title: "Automatic" },
+ { value: "ollama", title: "Ollama" },
+ { value: "lmstudio", title: "LM Studio" },
+ { value: "unsloth", title: "Unsloth Studio" },
+ { value: "custom", title: "Other" },
+];
+
+const code = (s: string) => <code className="font-mono text-[11px]">{s}</code>;
+
+/** Each server's settings and how to get it running. */
+const LOCAL_FIELDS: Record<LocalKind, { url: string; urlPlaceholder: string; model: string; modelHint: string; key?: string; keyLabel?: string; keyPlaceholder?: string; setup: React.ReactNode }> = {
+ ollama: {
+ url: "ollamaUrl",
+ urlPlaceholder: "http://127.0.0.1:11434",
+ model: "ollamaModel",
+ modelHint: "A model with tool calling for Assist, such as qwen3:8b.",
+ setup: <>Install Ollama, then run {code("ollama pull qwen3:8b")}. Fuobe gives it the context below.</>,
+ },
+ lmstudio: {
+ url: "lmstudioUrl",
+ urlPlaceholder: "http://127.0.0.1:1234",
+ model: "lmstudioModel",
+ modelHint: "Empty: the loaded model, else one trained for tool use. A model that isn't loaded is loaded with the context below.",
+ key: "lmstudioToken",
+ keyLabel: "API token (only with Require Authentication on)",
+ setup: (
+ <>
+ In LM Studio, open Developer and start the server (or run {code("lms server start")}), and download a model in Discover (or {code("lms get qwen/qwen3-8b")}). Models without thinking (instruct models) answer faster. Without
+ Require Authentication, anyone on your network can use LM Studio&apos;s server.
+ </>
+ ),
+ },
+ unsloth: {
+ url: "unslothUrl",
+ urlPlaceholder: "http://127.0.0.1:8888",
+ model: "unslothModel",
+ modelHint: "Empty: the model loaded in Unsloth Studio.",
+ key: "unslothKey",
+ keyLabel: "API key",
+ keyPlaceholder: "sk-unsloth-…",
+ setup: (
+ <>
+ Start Unsloth Studio and load a model on its Chat page (Select model), then make a key: avatar → Settings → API → Create. Fuobe always turns Unsloth&apos;s server-side tools (Python, terminal, web search) off.
+ </>
+ ),
+ },
+ custom: {
+ url: "llmUrl",
+ urlPlaceholder: "http://127.0.0.1:8080/v1",
+ model: "llmModel",
+ modelHint: "Empty: the first model the server lists.",
+ key: "llmKey",
+ keyLabel: "API key (optional)",
+ setup: <>Any OpenAI-compatible server: llama.cpp&apos;s llama-server, vLLM, Jan… Give its base URL as its docs do (it usually ends in {code("/v1")}).</>,
+ },
+};
+
+const k = (n: number) => `${Math.round(n / 1024)}k`;
+
+/** One line per server: the model it would use, or what's wrong. */
+function serverLine(s: LocalServerStatus): string {
+ if (!s.url) return "Not set up";
+ if (s.problem) return s.up ? s.problem : `Not running at ${s.url}`;
+ return [s.model, s.loaded ? "loaded" : s.loaded === false ? "loads on first use" : null, s.context ? `${k(s.context)} context` : null].filter(Boolean).join(" · ");
+}
+
+/** Settings → AI helper → the local model server: pick one (or Automatic), see what each one answers, set its URL, model and key, and test it. */
+function LocalLlmSettings({ get, set }: { get: (n: string) => PublicSetting | undefined; set: (n: string) => (v: string) => void }) {
+ const qc = useQueryClient();
+ const llm = useQuery({
+ queryKey: ["llm"],
+ queryFn: async () => (await (await fetch("/api/llm")).json()) as LocalLlmInfo,
+ refetchInterval: 30_000,
+ });
+ const refresh = useMutation({
+ mutationFn: async () => (await (await fetch("/api/llm?refresh=1")).json()) as LocalLlmInfo,
+ onSuccess: (data) => qc.setQueryData(["llm"], data),
+ });
+ const reload = useMutation({
+ mutationFn: async (model: string | null) =>
+ (await (await fetch("/api/llm", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "load", model }) })).json()) as { ok: boolean; detail: string },
+ onSuccess: (r) => {
+ if (r.ok) toast.success(r.detail);
+ else toast.error(r.detail);
+ refresh.mutate();
+ },
+ });
+ const provider = (get("llmProvider")?.value || "auto") as "auto" | LocalKind;
+ const [picked, setPicked] = useState<LocalKind | null>(null);
+ // Pinned: that server's settings. Automatic: the one clicked below, else the one in use.
+ const editing: LocalKind = provider !== "auto" ? provider : (picked ?? llm.data?.active ?? "ollama");
+ const status = llm.data?.servers.find((s) => s.kind === editing);
+ const f = LOCAL_FIELDS[editing];
+ const need = llm.data?.context ?? 0;
+ // Compared with the model's most when that's less: a reload can't give more than it.
+ const maxContext = status?.models.find((m) => m.id === status.model)?.maxContext;
+ const want = Math.min(need, maxContext || need);
+ const smallContext = editing === "lmstudio" && status?.native && status.loaded && !!status.context && !!want && status.context < want;
+ const shown = llm.data?.servers.filter((s) => provider === "auto" || s.kind === provider) ?? [];
+
+ return (
+ <div className="space-y-4 rounded-xl border p-4">
+ <div className="space-y-1.5">
+ <p id="local-llm-label" className="text-[13px] font-medium">
+ Local model server
+ </p>
+ <div role="radiogroup" aria-labelledby="local-llm-label" onKeyDown={radioKeys} className="flex flex-wrap gap-1 rounded-xl bg-muted p-1">
+ {LOCAL_SERVERS.map((o) => (
+ <button
+ key={o.value}
+ type="button"
+ role="radio"
+ aria-checked={provider === o.value}
+ tabIndex={radioTab(provider === o.value)}
+ onClick={() => provider !== o.value && set("llmProvider")(o.value)}
+ className={cn("h-8 rounded-lg px-3 text-[13px] font-medium transition-colors", provider === o.value ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}
+ >
+ {o.title}
+ </button>
+ ))}
+ </div>
+ <p className="text-[12px] text-muted-foreground">
+ {provider === "auto" ? "Uses the first server that answers with a model, in this order: Ollama, LM Studio, Unsloth Studio, then the Other server." : "Only this server is used; the others are ignored."}
+ </p>
+ </div>
+
+ <div className="space-y-1">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[13px] font-medium">Found on this machine</p>
+ <Button variant="ghost" size="sm" className="h-7 px-2 text-[12px]" onClick={() => refresh.mutate()} disabled={refresh.isPending}>
+ {refresh.isPending ? <Loader2 className="animate-spin" /> : <RefreshCw />} Check again
+ </Button>
+ </div>
+ {llm.isLoading && <Skeleton className="h-16 w-full rounded-lg" />}
+ <ul className="space-y-0.5">
+ {shown.map((s) => (
+ <li key={s.kind}>
+ <button
+ type="button"
+ onClick={() => setPicked(s.kind)}
+ aria-pressed={editing === s.kind}
+ className={cn("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[12px] transition-colors hover:bg-accent", editing === s.kind && "bg-accent")}
+ >
+ <span className={cn("size-2 shrink-0 rounded-full", !s.problem ? "bg-success" : s.up ? "bg-warning" : "bg-subtle-foreground")} />
+ <span className="shrink-0 font-medium">{s.kind === "custom" ? "Other" : s.label}</span>
+ <span className="min-w-0 flex-1 truncate font-mono text-muted-foreground">{serverLine(s)}</span>
+ {llm.data?.active === s.kind && <span className="shrink-0 rounded-md bg-brand-faint px-1.5 py-0.5 text-[11px] text-brand-text">In use</span>}
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+
+ <div className="space-y-4 border-t pt-4">
+ <p className="text-[13px] font-medium">{editing === "custom" ? "Other server (OpenAI-compatible)" : (status?.label ?? LOCAL_SERVERS.find((o) => o.value === editing)?.title)}</p>
+ <p className="text-[12px] leading-relaxed text-muted-foreground">{f.setup}</p>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <Field key={`${editing}-url`} setting={get(f.url)} label="URL" placeholder={f.urlPlaceholder} onSave={set(f.url)} />
+ <Field key={`${editing}-model`} setting={get(f.model)} label="Model" hint={f.modelHint} options={status?.models.map((m) => m.id)} onSave={set(f.model)} />
+ </div>
+ {f.key && <Field key={`${editing}-key`} setting={get(f.key)} label={f.keyLabel ?? "API key"} placeholder={f.keyPlaceholder} onSave={set(f.key)} />}
+ {status?.problem && status.up && <p className="text-[12px] text-warning">{status.problem}</p>}
+ {status?.problem && !status.up && <p className="text-[12px] text-muted-foreground">{status.problem}</p>}
+ {status?.warning && !status.problem && <p className="text-[12px] text-warning">{status.warning}</p>}
+ <div className="flex flex-wrap items-center gap-2">
+ <TestButton url="/api/llm" body={{ action: "test", kind: editing }} />
+ {smallContext && (
+ <Button variant="outline" size="sm" onClick={() => reload.mutate(status?.model ?? null)} disabled={reload.isPending}>
+ {reload.isPending && <Loader2 className="animate-spin" />} Reload with {k(want)} context
+ </Button>
+ )}
+ </div>
+ </div>
+
+ <Field
+ setting={get("llmContext")}
+ label="Context (tokens)"
+ placeholder="16384"
+ hint="How much text the local model reads at once: Ollama gets it as num_ctx, and LM Studio loads models with it. Assist needs about 16,384. 0 leaves it to the server."
+ onSave={set("llmContext")}
+ />
+ <p className="text-[12px] text-muted-foreground">The local model shares the GPU with ComfyUI. A 4–8B model leaves room for generations.</p>
+ </div>
+ );
+}
+
export function SettingsForm() {
const qc = useQueryClient();
const settings = useSettings();
@@ -215,6 +442,7 @@ export function SettingsForm() {
toast.success("Saved");
void qc.invalidateQueries({ queryKey: ["settings"] });
void qc.invalidateQueries({ queryKey: ["status"] });
+ void qc.invalidateQueries({ queryKey: ["llm"] });
},
});
const get = (n: string) => settings.data?.find((s) => s.name === n);
@@ -335,30 +563,29 @@ export function SettingsForm() {
</Section>
<Section
- title="Prompt enhancement"
- description="The Enhance toggle rewrites short ideas into rich prompts, and storyboards split stories into frames. Use Claude, a local Ollama model (fully open source), or the built-in offline rewriter. Claude also powers the Assist agent. In Open source only mode, Automatic skips Claude."
+ id="ai"
+ title="AI helper"
+ description="The LLM that writes for Fuobe: the Enhance toggle, storyboards, translations and scripts, ad copy, brand research, and the Assist agent. Use Claude, a local model (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server: fully open source), or the built-in offline rewriter. In Open source only mode, Automatic skips Claude."
>
<div className="space-y-1.5">
<Label htmlFor="setting-enhancer" className="text-[13px]">
- Enhancer
+ Use
</Label>
- <Select value={get("enhanceProvider")?.value || "auto"} onValueChange={set("enhanceProvider")}>
- <SelectTrigger id="setting-enhancer" className="w-full max-w-72">
+ {/* "ollama" is the old name of "local". */}
+ <Select value={(get("enhanceProvider")?.value || "auto").replace(/^ollama$/, "local")} onValueChange={set("enhanceProvider")}>
+ <SelectTrigger id="setting-enhancer" className="w-full max-w-80">
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem value="auto">Automatic (Claude → Ollama → offline)</SelectItem>
+ <SelectItem value="auto">Automatic (Claude → local model → offline)</SelectItem>
<SelectItem value="anthropic">Claude (Anthropic API)</SelectItem>
- <SelectItem value="ollama">Ollama (local, open source)</SelectItem>
+ <SelectItem value="local">Local model only (open source)</SelectItem>
<SelectItem value="none">Offline rewriter</SelectItem>
</SelectContent>
</Select>
</div>
<Field setting={get("anthropicKey")} label="Anthropic API key" placeholder="sk-ant-…" onSave={set("anthropicKey")} />
- <div className="grid gap-4 sm:grid-cols-2">
- <Field setting={get("ollamaUrl")} label="Ollama URL" onSave={set("ollamaUrl")} />
- <Field setting={get("ollamaModel")} label="Ollama model" onSave={set("ollamaModel")} />
- </div>
+ <LocalLlmSettings get={get} set={set} />
</Section>
<Section
diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsx
index f2524134..ed845710 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -38,7 +38,9 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
const pct = g.progress != null ? Math.round(g.progress * 100) : null;
const label = g.status === "queued" ? (g.message ?? "Queued") : (g.message ?? "Generating…");
return (
- <div className="relative h-full overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }}>
+ // max-w-full: in a grid row stretched by a taller neighbour (a card with a footer), h-full + aspect-ratio would
+ // otherwise make the tile wider than its column and spill over the next card.
+ <div className="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }}>
<div className="skeleton-sweep absolute inset-0 animate-skeleton" />
<div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3">
<div className="min-w-0">
@@ -75,7 +77,7 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number; onRetry: () => void }) {
return (
- <div className="flex h-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style={{ aspectRatio: Math.max(ratio, 0.8) }}>
+ <div className="flex h-full max-w-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style={{ aspectRatio: Math.max(ratio, 0.8) }}>
<div className="min-h-0 space-y-1 overflow-hidden">
<p className="text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>
{g.error && <p className="line-clamp-5 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground">{g.error}</p>}
diff --git a/src/components/studio/result-media.tsx b/src/components/studio/result-media.tsx
index 63a6283e..b619acf0 100644
--- a/src/components/studio/result-media.tsx
+++ b/src/components/studio/result-media.tsx
@@ -2,6 +2,8 @@
import { AudioLines, Box, FileText, Layers } from "lucide-react";
import { createElement, useEffect, useState } from "react";
+import { loadModelViewer, useViewerSrc, viewerLook } from "@/components/model3d/model-viewer";
+import { viewerGlb } from "@/lib/av/model3d";
import type { Generation, OutputFile } from "@/lib/catalog/types";
import { cuesOf, cueTime, isLayered, layerInfo, modelPreview, textOf } from "@/lib/output-actions";
import { cn } from "@/lib/utils";
@@ -163,9 +165,13 @@ export function LayersStack({ g, className, bare }: { g: Generation; className?:
export function ModelViewer({ output, g }: { output: OutputFile; g: Generation }) {
const [ready, setReady] = useState(false);
const [failed, setFailed] = useState(false);
+ const [viewer, setViewer] = useState<HTMLElement | null>(null);
+ // The web GLB (meshopt, WebP) when the server made one, else (older results, or if it fails to load) the original.
+ const src = useViewerSrc(viewer, viewerGlb(output), output.url);
+ const material = (output.meta?.finish as { material?: unknown } | undefined)?.material;
useEffect(() => {
let live = true;
- import("@google/model-viewer").then(
+ loadModelViewer().then(
() => live && setReady(true),
() => live && setFailed(true),
);
@@ -184,14 +190,16 @@ export function ModelViewer({ output, g }: { output: OutputFile; g: Generation }
);
}
return createElement("model-viewer", {
- src: output.url,
+ ref: setViewer,
+ src,
poster,
alt: g.request.prompt || "3D model",
+ loading: "lazy",
+ reveal: "auto",
"camera-controls": "",
"auto-rotate": "",
- "shadow-intensity": "1",
- exposure: "1",
"touch-action": "pan-y",
+ ...viewerLook(typeof material === "string" ? material : undefined),
style: { width: "100%", height: "100%", background: "transparent" },
});
}
diff --git a/src/hooks/use-reduced-motion.ts b/src/hooks/use-reduced-motion.ts
new file mode 100644
index 00000000..7762bdf0
--- /dev/null
+++ b/src/hooks/use-reduced-motion.ts
@@ -0,0 +1,16 @@
+import { useSyncExternalStore } from "react";
+
+const QUERY = "(prefers-reduced-motion: reduce)";
+
+/** Whether the user prefers reduced motion. True while server rendering, so nothing starts moving before hydration. */
+export function useReducedMotion() {
+ return useSyncExternalStore(
+ (cb) => {
+ const mq = window.matchMedia(QUERY);
+ mq.addEventListener("change", cb);
+ return () => mq.removeEventListener("change", cb);
+ },
+ () => window.matchMedia(QUERY).matches,
+ () => true,
+ );
+}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index b2042884..c77ab591 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -772,6 +772,18 @@ export interface StatusInfo {
demoMode: string;
engineMode: EngineMode;
cloudProvider: string;
+ /** The text LLM: Settings → AI helper, whether Claude takes text steps, and the local model server in use. */
+ llm?: {
+ helper: "auto" | "anthropic" | "local" | "none";
+ claude: boolean;
+ /** Settings' local server: "auto" or the one pinned. */
+ provider: string;
+ context: number;
+ local: { kind: string; label: string; url: string; model: string | null; loaded: boolean | null; context: number | null; warning: string | null } | null;
+ /** Why no local server can run, when one says. */
+ problem: string | null;
+ detected: { kind: string; label: string; url: string; up: boolean; auth: string; models: number; model: string | null; problem: string | null }[];
+ };
}
export function useStatus() {
diff --git a/src/lib/assist.ts b/src/lib/assist.ts
index 2d2ac695..7cbb6e0c 100644
--- a/src/lib/assist.ts
+++ b/src/lib/assist.ts
@@ -46,13 +46,16 @@ export type AssistItem =
export type AssistStatus = "idle" | "running" | "waiting";
-export type AssistAgent = "claude" | "ollama" | "offline";
+export type AssistAgent = "claude" | "local" | "offline";
+
+/** Chats saved before LM Studio and Unsloth Studio came along call the local model "ollama". */
+export const normalizeAgent = (a: string | null | undefined): AssistAgent | undefined => (a === "ollama" ? "local" : a === "claude" || a === "local" || a === "offline" ? a : undefined);
export interface AssistThread {
id: string;
title: string;
status: AssistStatus;
- /** "claude" = Claude; "ollama" = a local model through Ollama; "offline" = a rule-based planner (no LLM). */
+ /** "claude" = Claude; "local" = a local model (Ollama, LM Studio, Unsloth Studio…); "offline" = a rule-based planner (no LLM). */
agent: AssistAgent;
engine: Engine;
/** Run plans without the approval card. */
@@ -64,7 +67,7 @@ export interface AssistThread {
projectId?: string | null;
/** How the LLM was chosen (Free / Smart / Manual). */
mode?: AssistMode;
- /** Claude model id, or the Ollama model name (null: the default). */
+ /** Claude model id, or the local model's name (null: the default). */
model?: string | null;
effort?: AssistEffort | null;
/** Skills loaded into this chat (by `/name` or by the agent). */
@@ -101,7 +104,7 @@ export type AssistEffort = "low" | "medium" | "high" | "xhigh" | "max";
export const ASSIST_MODES: { id: AssistMode; label: string; hint: string }[] = [
{ id: "smart", label: "Smart", hint: "Claude plans, picks models and checks results" },
- { id: "free", label: "Free", hint: "A local model through Ollama, or the offline planner — no API cost" },
+ { id: "free", label: "Free", hint: "A local model (Ollama, LM Studio or Unsloth Studio), or the offline planner — no API cost" },
{ id: "manual", label: "Manual", hint: "Pick the model and how hard it thinks" },
];
@@ -131,14 +134,28 @@ export interface AssistModeChoice {
effort?: AssistEffort | null;
}
+/** The local model server behind Free and Manual's local models (Ollama, LM Studio, Unsloth Studio, or another OpenAI-compatible one). */
+export interface AssistLocal {
+ /** "ollama" | "lmstudio" | "unsloth" | "custom"; null: Automatic found none. */
+ kind: string | null;
+ /** "LM Studio"; "a local model" when Automatic found none. */
+ label: string;
+ /** It answers and has a model to use. */
+ ok: boolean;
+ /** Its chat models (Manual mode lists them). */
+ models: string[];
+ /** The model a chat uses by default. */
+ model: string | null;
+ /** Why it can't run (needs a key, no model loaded…). */
+ problem?: string;
+}
+
/** What the server can run right now (GET /api/assist). */
export interface AssistAvailability {
/** An Anthropic key is set and Settings allows Claude here. */
claude: boolean;
- /** Ollama answered. */
- ollama: boolean;
- ollamaModels: string[];
- ollamaModel: string;
+ /** The local model server Free and Manual use. */
+ local: AssistLocal;
/** Settings → AI helper is "none": every chat runs the offline planner. */
aiOff: boolean;
/** Smart when Claude can run, else Free. */
@@ -147,7 +164,7 @@ export interface AssistAvailability {
export function modeLabel(t: Pick<AssistThread, "mode" | "agent" | "model" | "effort">): string {
if (t.agent === "offline") return "Offline planner";
- if (t.agent === "ollama") return t.model ? `Local · ${t.model}` : "Local LLM";
+ if (t.agent === "local") return t.model ? `Local · ${t.model}` : "Local LLM";
const m = CLAUDE_MODELS.find((x) => x.id === (t.model ?? DEFAULT_CLAUDE_MODEL));
const effort = ASSIST_EFFORTS.find((e) => e.id === (t.effort ?? DEFAULT_EFFORT))?.label;
if (t.mode === "manual") return `${m?.label.replace("Claude ", "") ?? t.model} · ${effort}`;
diff --git a/src/lib/av/dub.ts b/src/lib/av/dub.ts
index 9ba412d7..fc6b5a1b 100644
--- a/src/lib/av/dub.ts
+++ b/src/lib/av/dub.ts
@@ -22,7 +22,7 @@ import { timelineFor } from "./timeline";
* speaks each phrase in the cloned voice; the audio-timeline workflow lays them out; InfiniteTalk
* re-syncs the lips and the mux mixes the voice over the background stem.
* Cloud: ElevenLabs Voice Isolation (the clean voice to clone), Scribe v2 on it (transcript), Claude or
- * Ollama (translation), and in parallel the source's sound split by Demucs (drums, bass and other: the
+ * a local model (translation), and in parallel the source's sound split by Demucs (drums, bass and other: the
* music and effects). ElevenLabs v4 speaks each phrase, fal's compose lays them out over a blank still
* (its soundtrack is read back as audio), Chatterbox voice conversion turns the track into the speaker's
* voice and Sync Lipsync 3 re-syncs the lips; compose then mixes the new voice over the Demucs stems and
diff --git a/src/lib/av/model3d.ts b/src/lib/av/model3d.ts
index 5104e6cf..e557a600 100644
--- a/src/lib/av/model3d.ts
+++ b/src/lib/av/model3d.ts
@@ -1,9 +1,9 @@
import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
/**
- * Image to 3D / Product spin: which model, and what a finished job gives the viewer — the .glb, a
- * turntable video (TRELLIS.2 renders one; for models that return only a mesh the page records one in
- * the browser), a poster, the source photo — and where "Animate the spin" goes next.
+ * Image to 3D / Product spin: which model, and what a finished job gives the viewer — the .glb (and its
+ * lighter web GLB), a turntable video (the server renders one for open models when it can; otherwise the
+ * page records one in the browser), a poster, the source photo — and where "Animate the spin" goes next.
*/
export const MODEL3D_FEATURE = "image-to-3d";
@@ -16,20 +16,37 @@ export const MODELS_3D: Record<Engine, { id: string; note: string }[]> = {
{ id: "meshy-7-1", note: "Textured, optional rigging · ≈ $1.20" },
],
open: [
- { id: "oss-trellis2", note: "Textured GLB + turntable video · 16 GB GPU · MIT" },
+ { id: "oss-pixal3d", note: "Most faithful to the photo · textured GLB + turntable video · 16 GB GPU" },
+ { id: "oss-trellis2", note: "Fallback · textured GLB + turntable video · 16 GB GPU · MIT" },
{ id: "oss-hunyuan3d-21", note: "Shape only · 10 GB GPU" },
],
};
+/**
+ * The GLB a viewer should load: the web GLB the server made after the job (meshopt geometry, WebP
+ * textures, pivot at the bottom; meta.web), else the original — results made before that keep working.
+ */
+export function viewerGlb(o: { url: string; meta?: Record<string, unknown> }): string {
+ const web = o.meta?.web;
+ return typeof web === "string" && web ? web : o.url;
+}
+
export function model3dRequest(o: { engine: Engine; photo: string; modelId?: string }): GenerationRequest {
const id = o.modelId && MODELS_3D[o.engine].some((m) => m.id === o.modelId) ? o.modelId : MODELS_3D[o.engine][0].id;
return { feature: MODEL3D_FEATURE, modelId: id, op: "image-to-3d", inputs: { images: [o.photo] } };
}
export interface Model3dView {
+ /** The original GLB (the download). */
glb?: string;
- /** A rendered turntable that came with the model (TRELLIS.2 open, demo). */
+ /** The GLB to show in a viewer: the web GLB when there is one, else `glb`. */
+ web?: string;
+ /** A rendered turntable that came with the model (the server's render for open models, demo). */
turntable?: string;
+ /** The server is still rendering the turntable (after the job finished): waiting its turn, or how far (0-1). */
+ rendering?: { queued: boolean; progress: number };
+ /** The material class the server's finish read from the textures (matte, metal, mixed, unknown). */
+ material?: string;
poster?: string;
/** The product photo it was made from. */
photo?: string;
@@ -43,12 +60,17 @@ export function model3dView(g: Pick<Generation, "outputs" | "request">): Model3d
const str = (v: unknown) => (typeof v === "string" && v ? v : undefined);
const videos = g.outputs.filter((o) => o.kind === "video");
const video = videos.find((o) => o.meta?.role === "turntable" || o.meta?.turntable) ?? videos[0];
+ const finish = (meta.finish ?? {}) as { turntable?: unknown; turntableProgress?: unknown; material?: unknown };
+ const pending = finish.turntable === "queued" || finish.turntable === "rendering";
const formats: Record<string, string> = {};
const listed = meta.formats;
if (listed && typeof listed === "object") for (const [k, v] of Object.entries(listed as Record<string, unknown>)) if (typeof v === "string") formats[k.toLowerCase()] = v;
return {
glb: mesh?.url,
+ web: mesh ? viewerGlb(mesh) : undefined,
turntable: str(meta.turntable) ?? str(meta.video) ?? video?.url,
+ rendering: pending ? { queued: finish.turntable === "queued", progress: typeof finish.turntableProgress === "number" ? finish.turntableProgress : 0 } : undefined,
+ material: str(finish.material),
poster: str(meta.preview) ?? str(meta.poster) ?? g.outputs.find((o) => o.kind === "image")?.url,
photo: g.request.inputs?.images?.[0],
formats,
diff --git a/src/lib/catalog/apps.ts b/src/lib/catalog/apps.ts
index 95665391..1aa21d01 100644
--- a/src/lib/catalog/apps.ts
+++ b/src/lib/catalog/apps.ts
@@ -625,8 +625,8 @@ export const APPS: Preset[] = [
inputs: [product],
prompt: "",
cloud: { modelId: "hunyuan-3d-3-1-pro", op: "image-to-3d" },
- open: { modelId: "oss-trellis2", op: "image-to-3d" },
- parity: "The open version (TRELLIS.2) also renders a turntable video; for cloud models the 3D page records one in your browser",
+ open: { modelId: "oss-pixal3d", op: "image-to-3d" },
+ parity: "The open version (Pixal3D) also gets a turntable video rendered on the server; for cloud models the 3D page records one in your browser",
}),
videoApp({
name: "Billboard Ad",
diff --git a/src/lib/catalog/faceless.ts b/src/lib/catalog/faceless.ts
index 0ab8aeeb..25d17550 100644
--- a/src/lib/catalog/faceless.ts
+++ b/src/lib/catalog/faceless.ts
@@ -1343,6 +1343,16 @@ Reply with JSON only: {"topics": [{"title": string, "hook": string}]}.
- hook: one sentence on why someone would watch it.
- Every topic fits the channel and its genre, and they differ from each other.`;
+/**
+ * The answers' JSON as JSON Schemas, for local models that decode to one (Ollama, LM Studio,
+ * Unsloth Studio); they match the prompts, which still ask for the same JSON.
+ */
+const objectOf = (properties: Record<string, unknown>) => ({ type: "object", properties, required: Object.keys(properties), additionalProperties: false });
+const listOf = (items: unknown, min: number, max: number) => ({ type: "array", items, minItems: min, maxItems: max });
+const STRING = { type: "string" };
+
+export const topicsSchema = (count: number) => ({ name: "topics", schema: objectOf({ topics: listOf(objectOf({ title: STRING, hook: STRING }), count, count) }) });
+
export function topicsBrief(o: { idea: string; genre: GenreInfo; count: number; avoid?: string[]; reference?: string }): string {
return [
`Channel: ${o.idea}`,
@@ -1501,6 +1511,12 @@ Reply with JSON only: {"title": string, "scenes": [{"narration": string, "visual
- Keep each scene's narration within its word limit, so the voice fits the scene.
- Start with a hook in the first scene; end with a short, satisfying close.`;
+/** `scenes` null: the length decides itself (4 to 12 scenes, as the brief says). */
+export const scriptSchema = (scenes: number | null) => ({
+ name: "script",
+ schema: objectOf({ title: STRING, scenes: listOf(objectOf({ narration: STRING, visual: STRING, motion: STRING }), scenes ?? 4, scenes ?? 12) }),
+});
+
export interface ScriptBrief {
topic: string;
genre: GenreInfo;
@@ -1544,6 +1560,8 @@ Reply with JSON only: {"scenes": [{"n": number, "visual": string, "motion": stri
- visual: one or two sentences describing the illustration for that line: subject, setting, composition. No text in the picture.
- motion: a few words on what moves and how the camera moves.`;
+export const visualsSchema = (count: number) => ({ name: "visuals", schema: objectOf({ scenes: listOf(objectOf({ n: { type: "integer" }, visual: STRING, motion: STRING }), count, count) }) });
+
export const visualsBrief = (blocks: Pick<ScriptBlock, "narration">[], styleName: string, topic: string) =>
[`Topic: ${topic}`, `Style: ${styleName}`, ...blocks.map((b, i) => `[${i + 1}] ${b.narration}`)].join("\n");
@@ -1632,7 +1650,7 @@ export function offlineScript(topic: string, genre: FacelessGenre, scenes: numbe
);
}
-export const OFFLINE_NOTE = "Written offline — connect Claude or Ollama in Settings for a real script.";
+export const OFFLINE_NOTE = "Written offline — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for a real script.";
// ---------------------------------------------------------------------------
// Validation the wizard and the API share
diff --git a/src/lib/catalog/llm-models.ts b/src/lib/catalog/llm-models.ts
index ea78b4ba..eb59ae58 100644
--- a/src/lib/catalog/llm-models.ts
+++ b/src/lib/catalog/llm-models.ts
@@ -5,8 +5,9 @@ import type { ModelDef, ModelRoute, Operation } from "./types";
* server (src/server/providers/llm.ts). Kind "text": they only show up where a studio asks for
* text models (dubbing, scripts, ad copy) and in pipelines, never in the image/video/audio pickers.
* The route endpoint says which LLMs a model may use: "auto" = Claude when an Anthropic key is
- * set, else a local Ollama; "ollama" = Ollama only (open-source installs never call a paid API),
- * and its translations run on ComfyUI's Qwen3.5 4B workflow when Ollama isn't running.
+ * set, else a local model; "ollama" = a local model only, whichever server runs it (Ollama, LM Studio,
+ * Unsloth Studio or another OpenAI-compatible one; the id predates them): open-source installs never
+ * call a paid API, and its translations run on ComfyUI's Qwen3.5 4B workflow when no local model answers.
*/
const llm = (op: Operation, endpoint: "auto" | "ollama"): ModelRoute => ({ op, provider: "llm", endpoint });
@@ -26,21 +27,21 @@ export const LLM_MODELS: ModelDef[] = [
family: "llm",
engine: "cloud",
kind: "text",
- tagline: "Translates subtitles cue by cue and writes scripts, captions and ad copy (Ollama when no Anthropic key is set)",
+ tagline: "Translates subtitles cue by cue and writes scripts, captions and ad copy (a local model when no Anthropic key is set)",
badges: ["top"],
routes: [llm("translate", "auto"), llm("write", "auto")],
options: { languages: LLM_LANGUAGES },
// Claude Opus 5.5 at $4 / $20 per million tokens: a few cents for a page of text.
- pricing: { unit: "request", usd: 0.02, note: "≈ a page of text; free when it runs on Ollama" },
+ pricing: { unit: "request", usd: 0.02, note: "≈ a page of text; free when it runs on a local model" },
},
{
id: "oss-text-llm",
name: "Local LLM",
- vendor: "Ollama",
+ vendor: "Ollama · LM Studio · Unsloth",
family: "llm",
engine: "open",
kind: "text",
- tagline: "Translation and writing on your own machine with Ollama (qwen3, llama, mistral…); without Ollama, translations run on ComfyUI (Qwen3.5 4B)",
+ tagline: "Translation and writing on your own machine with Ollama, LM Studio or Unsloth Studio (qwen3, llama, gemma, mistral…); without one, translations run on ComfyUI (Qwen3.5 4B)",
badges: ["open"],
routes: [llm("translate", "ollama"), llm("write", "ollama")],
options: { languages: LLM_LANGUAGES },
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index 09929872..1ff72ec7 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -1040,16 +1040,29 @@ const open: ModelDef[] = [
options: {},
hidden: true,
}),
- // Product 3D, try-on
+ // Product 3D, try-on. Every image-to-3D route on ComfyUI (Pixal3D, TRELLIS.2, Hunyuan3D 2.1) ends in the
+ // server's finish (src/server/model3d-finish.ts): a web GLB and, when Chromium and ffmpeg are there, a
+ // CPU-rendered turntable video.
+ o({
+ id: "oss-pixal3d",
+ name: "Pixal3D",
+ vendor: "Pixal3D",
+ family: "trellis",
+ kind: "model3d",
+ tagline: "A textured 3D model (.glb) that stays true to your photo (camera-aware), plus a turntable video · 16 GB GPU",
+ badges: ["new", "top"],
+ routes: [comfy("image-to-3d", "image-to-3d-pixal3d", "MoGe-2 camera → Pixal3D; ~250k triangles; web GLB + turntable made after the job")],
+ options: { seed: true },
+ }),
o({
id: "oss-trellis2",
name: "TRELLIS.2",
vendor: "Microsoft",
family: "trellis",
kind: "model3d",
- tagline: "A textured 3D model (.glb) from one product photo, plus a turntable video · 16 GB GPU · MIT",
- badges: ["new", "top"],
- routes: [comfy("image-to-3d", "image-to-3d-trellis2", "PBR textures; second output = 36-view turntable MP4")],
+ tagline: "A textured 3D model (.glb) from one product photo, plus a turntable video; the fallback to Pixal3D · 16 GB GPU · MIT",
+ badges: ["new"],
+ routes: [comfy("image-to-3d", "image-to-3d-trellis2", "~250k triangles; web GLB + turntable made after the job")],
options: { seed: true },
}),
o({
diff --git a/src/lib/catalog/preview-media.generated.json b/src/lib/catalog/preview-media.generated.json
new file mode 100644
index 00000000..b2b10720
--- /dev/null
+++ b/src/lib/catalog/preview-media.generated.json
@@ -0,0 +1,488 @@
+{
+ "apps": {
+ "app-3d-figure": "a8c80e98s",
+ "app-3d-render": "d15efaafs",
+ "app-3d-rotation": "4df59547s",
+ "app-60s-cafe": "18359cf8s",
+ "app-ad-creative": "54fca4cfs",
+ "app-age-shift": "c4579086s",
+ "app-ai-influencer": "de45bd95s",
+ "app-ai-stylist": "efa19acds",
+ "app-angles": "7477e40ds",
+ "app-asmr-add-on": "87a22b13s",
+ "app-asmr-classic": "b0a67744s",
+ "app-asmr-host": "47d2deb1s",
+ "app-asmr-promo": "068129bas",
+ "app-banana-eating": "030d5e9es",
+ "app-behind-the-scenes": "b738f984s",
+ "app-billboard-ad": "744a02eds",
+ "app-breakdown": "a671f366s",
+ "app-brick-cube": "b87ae57es",
+ "app-bring-to-life": "acea0585s",
+ "app-bullet-time-scene": "c8f49a4cs",
+ "app-bullet-time-splash": "3701bdb6s",
+ "app-bullet-time-white": "502ccf3bs",
+ "app-burning-sunset": "548eee06s",
+ "app-chameleon": "9e8be68bs",
+ "app-change-background": "a74dd29as",
+ "app-character-swap": "9a7f3f03s",
+ "app-click-to-ad": "29a29eb9s",
+ "app-clipcut": "f68f5d5fs",
+ "app-cloud-surf": "28197334s",
+ "app-color-grading": "810a6bf8s",
+ "app-colorize": "22c798e9s",
+ "app-comic-book": "c2bd5a0fs",
+ "app-commercial-faces": "2cb4816ds",
+ "app-dance": "695e8c21s",
+ "app-expand-image": "da94acd4s",
+ "app-expression-edit": "da5fdea4s",
+ "app-face-swap": "62b187afs",
+ "app-figurine": "41fbb36ds",
+ "app-fridge-ad": "527d8d87s",
+ "app-game-dump": "574b3cb4s",
+ "app-ghoulgao": "bdbcc518s",
+ "app-giallo-horror": "3b1bf474s",
+ "app-giant-product": "030a13fds",
+ "app-glitter-sticker": "cd4b7751s",
+ "app-graffiti-ad": "ea883733s",
+ "app-gtai": "07c9e9cfs",
+ "app-hairstyle-try-on": "b7812874s",
+ "app-headshot-generator": "919fb7bb",
+ "app-hook-frame": "0fa7183es",
+ "app-hug": "d0419d1as",
+ "app-idol": "7998741cs",
+ "app-image-to-3d": "e3724051s",
+ "app-j-magazine": "6e81776es",
+ "app-j-poster": "20882792s",
+ "app-japanese-show": "0e704180s",
+ "app-kick-ad": "1443caads",
+ "app-latex": "ecef95dcs",
+ "app-link-to-video-ad": "11e1c1c2s",
+ "app-macro-scene": "c688e534s",
+ "app-macroshot-product": "11ee4435s",
+ "app-magic-button": "ec16c3dds",
+ "app-makeup-studio": "83aef4fas",
+ "app-mascot": "5756aa48s",
+ "app-match-colors": "4389fcc8s",
+ "app-match-lighting": "870dfdcfs",
+ "app-melting-doodle": "1040e9d4s",
+ "app-meme-generator": "2fd3ab16s",
+ "app-micro-beasts": "9d40eaf5s",
+ "app-mugshot": "72abe37ds",
+ "app-mukbang": "b32f857bs",
+ "app-nano-strike": "db86a8bfs",
+ "app-nano-theft": "b2fabb94s",
+ "app-object-remover": "6784e8f3s",
+ "app-outfit-shot": "88e0d26cs",
+ "app-outfit-swap": "0742a47as",
+ "app-outfit-vending": "f0621e27s",
+ "app-packshot": "6fdb0187s",
+ "app-paint-app": "c58a12a8s",
+ "app-pixel-game": "1a631ed7s",
+ "app-plushies": "f06b4e80s",
+ "app-poster": "eb2d2ddes",
+ "app-product-360": "1b2b6df7s",
+ "app-product-placement": "54fcf2ees",
+ "app-product-shot": "61d9a487s",
+ "app-rap-god": "9eb734b6s",
+ "app-recast": "7b3a0411s",
+ "app-relight": "5d7a7d1bs",
+ "app-remove-background": "6d808d94s",
+ "app-renaissance": "41d70caas",
+ "app-restore-photo": "9cefc3dcs",
+ "app-roller-coaster": "fffd1760s",
+ "app-sand-worm": "01140cbds",
+ "app-signboard": "2be7910es",
+ "app-similarity-score": "a1cd4c70s",
+ "app-simlife": "d280ddd3s",
+ "app-sketch-to-real": "973198e5s",
+ "app-skibidi": "909b9d37s",
+ "app-skin-enhancer": "dff79317s",
+ "app-social-media-icon": "cebdc446s",
+ "app-steal-the-look": "e69e29b7s",
+ "app-sticker-match-cut": "7a825ae3s",
+ "app-sticker-pack": "202cf558s",
+ "app-storm-creature": "44444760s",
+ "app-style-snap": "84e70cfcs",
+ "app-style-transfer": "dcb14321s",
+ "app-text-edit": "99538679s",
+ "app-this-is-fine": "c287635cs",
+ "app-transitions": "473d55e1s",
+ "app-truck-ad": "42b7643ds",
+ "app-unboxing-video": "8d64dc8bs",
+ "app-upscale": "9af9fff8s",
+ "app-urban-cuts": "505e472fs",
+ "app-vectorize": "01ee7c44s",
+ "app-victory-card": "1ea186d3s",
+ "app-video-background-remover": "5c0f3d63s",
+ "app-video-face-swap": "5e91d42as",
+ "app-virtual-try-on": "953d9c8as",
+ "app-volcano-ad": "21ab9ee4s",
+ "app-what-s-next": "7a8efd03s",
+ "app-yes-kiss": "c5c3552ds",
+ "app-zoom-out": "8e0352b8s",
+ "app-zooms": "d98b30dcs"
+ },
+ "effects": {
+ "effect-acid": "c8d514cfs",
+ "effect-act-natural": "2b961b71s",
+ "effect-agamemnon": "d9efd1f2s",
+ "effect-agent-reveal": "d1f176e7s",
+ "effect-air-bending": "973b2805s",
+ "effect-akrill": "275326d4s",
+ "effect-angel-wings": "ff278814s",
+ "effect-angry-mode": "0a8e81c1s",
+ "effect-animalization": "4e1c7d88s",
+ "effect-aquarium": "0e17db2bs",
+ "effect-architecture-wave": "c1792355s",
+ "effect-atomic": "254cccafs",
+ "effect-attack-of-clones": "07c83246s",
+ "effect-ballet": "3123ecd8s",
+ "effect-balloon": "152ea821s",
+ "effect-beach-ride": "66c54486s",
+ "effect-beast-appearance": "cda8e317s",
+ "effect-black-gloss": "0dc033b4s",
+ "effect-black-tears": "d0de0c66s",
+ "effect-bleach-bypass": "337d4702s",
+ "effect-bleached-warm": "283999dds",
+ "effect-bloom-mouth": "9fc4f172s",
+ "effect-blue-depth": "85163304s",
+ "effect-boarding-pass": "2ce4db17s",
+ "effect-boiling-point": "cb613c93s",
+ "effect-broken-mirror": "fcb90e1cs",
+ "effect-bubbles": "08b27f16s",
+ "effect-buddy": "e460d975s",
+ "effect-building-explosion": "d44ad355s",
+ "effect-burning-man": "6189e4c5s",
+ "effect-cakeify": "d203e84ds",
+ "effect-candy-pink": "de039091s",
+ "effect-cannabis": "e6c5258fs",
+ "effect-canvas": "f56d67eds",
+ "effect-car-drive": "520e7bd3s",
+ "effect-car-explosion": "27c8b3bds",
+ "effect-censorship": "fff70a90s",
+ "effect-classic-bw": "70f81568s",
+ "effect-clone-explosion": "a6f79e63s",
+ "effect-clones": "a17bb3d7s",
+ "effect-clothes-rain": "a29a4e91s",
+ "effect-cold-steel": "b5aea3e9s",
+ "effect-cold-vision": "54ab8b1as",
+ "effect-color-rain": "2451f0f1s",
+ "effect-column-wipe": "3d83703cs",
+ "effect-comic": "735a1816s",
+ "effect-contre-jour": "2146738fs",
+ "effect-cotton-cloud": "263b9f86s",
+ "effect-crimson-vigil": "6eef4b5bs",
+ "effect-crush": "76492668s",
+ "effect-crying": "072fcd82s",
+ "effect-cutout": "3c7b5728s",
+ "effect-cyborg": "6dc0ddd4s",
+ "effect-cyclope": "0b1ae207s",
+ "effect-datamosh": "6339455as",
+ "effect-deflate": "8ba46451s",
+ "effect-diamond": "1c9d75des",
+ "effect-dirty-lens": "d2f79ebbs",
+ "effect-disintegration": "270d4e15s",
+ "effect-display-transition": "86ea7b8bs",
+ "effect-dolphin-ride": "fdcf2030s",
+ "effect-dream-date": "fa023102s",
+ "effect-drunk-master": "c4b9112fs",
+ "effect-duplicate": "feeb555fs",
+ "effect-earth-element": "5bd23498s",
+ "effect-earth-wave": "7e067f4cs",
+ "effect-earth-zoom-out": "2c3bab43s",
+ "effect-eating": "84ecd36as",
+ "effect-exploded-view": "90ba2dd9s",
+ "effect-explosion": "e3203ff0s",
+ "effect-fairies-around": "070c0206s",
+ "effect-fairytale-castle": "85ace22bs",
+ "effect-fallen-angel": "da140e51s",
+ "effect-film-colors": "04e25e8es",
+ "effect-fire-breath": "cce43512s",
+ "effect-fire-element": "33f40fcbs",
+ "effect-firelava": "c68fad4fs",
+ "effect-firework": "d8470a63s",
+ "effect-fix-and-pose": "cbe65749s",
+ "effect-flame-on": "174af9ads",
+ "effect-flame-transition": "57e5be9as",
+ "effect-flash-comic": "5786ec99s",
+ "effect-flashback": "9a91104cs",
+ "effect-floating-fall": "b2b6667fs",
+ "effect-floating-fish": "c95b4457s",
+ "effect-flood": "cd15110as",
+ "effect-floral-eyes": "f81c8fafs",
+ "effect-fragments": "815633b2s",
+ "effect-freezing": "536d7eb7s",
+ "effect-frozen-in-motion": "925e9c3es",
+ "effect-garden-bloom": "ed51e5a5s",
+ "effect-gas-transformation": "4c954f9fs",
+ "effect-giant": "08416d63s",
+ "effect-giant-grab": "93eded14s",
+ "effect-giant-people": "e73bb4cfs",
+ "effect-glitch": "8bffd65ds",
+ "effect-glow-trace": "8338b5a1s",
+ "effect-glowing-fish": "d2b03caas",
+ "effect-glowshift": "30687dfcs",
+ "effect-gorilla-transfer": "7e280859s",
+ "effect-group-photo": "9a7e7c02s",
+ "effect-hair-style": "12ed2aacs",
+ "effect-hand-paint": "871fd471s",
+ "effect-hand-transition": "d82cac08s",
+ "effect-handheld-run": "dabdec77s",
+ "effect-happy": "638fb09fs",
+ "effect-happy-mode": "c76320ces",
+ "effect-head-explosion": "499b4867s",
+ "effect-head-off": "289d6ab9s",
+ "effect-helicopter-escape": "df59fe97s",
+ "effect-hero-flight": "c9b257b1s",
+ "effect-high-flip": "13740786s",
+ "effect-hole-transition": "adc91f0bs",
+ "effect-horror-face": "cc7fe748s",
+ "effect-hyper-neon": "cf2ce4b6s",
+ "effect-i-can-fly": "4545a980s",
+ "effect-ice-rose": "0f04f8f6s",
+ "effect-infinite-clones": "ea0474dbs",
+ "effect-inflate": "bc346382s",
+ "effect-innerlight": "faf271abs",
+ "effect-invisible": "fc136f18s",
+ "effect-jelly-drift": "4093d583s",
+ "effect-jump-transition": "4b095bbes",
+ "effect-lacewalker": "f1f5f512s",
+ "effect-lava": "021ff79es",
+ "effect-layer-mixed-media": "8e34e8cfs",
+ "effect-lens-crack": "7cf00a7cs",
+ "effect-lens-flare": "768aeaaas",
+ "effect-levitation": "9496c7a2s",
+ "effect-lidar-transition": "dbf30293s",
+ "effect-lime-jam": "d131dc61s",
+ "effect-live-concert": "129de0c5s",
+ "effect-look-boom": "9e808c83s",
+ "effect-lsd": "439ff60es",
+ "effect-luminous-gaze": "460db78fs",
+ "effect-magazine": "ff99d3ffs",
+ "effect-marble": "5bda2084s",
+ "effect-medusa-gorgona": "9b7b65a4s",
+ "effect-melt-transition": "86e9e232s",
+ "effect-melting": "30a3f751s",
+ "effect-mighty-fighter": "e2a86544s",
+ "effect-modern": "094aa3fbs",
+ "effect-monet-muse": "f0f6d182s",
+ "effect-money-rain": "ea743f95s",
+ "effect-monster-dab": "be333262s",
+ "effect-monstrosity": "33f275b9s",
+ "effect-moonwalk": "82cca2c6s",
+ "effect-morning-routine": "6bf023c0s",
+ "effect-morphskin": "67dc2b94s",
+ "effect-motor-ride": "2d2ff98ds",
+ "effect-multiverse": "68fd09d7s",
+ "effect-muscle-up": "e81aea00s",
+ "effect-mystification": "f8b9bc01s",
+ "effect-naturalistic-clean": "de321d72s",
+ "effect-nature-bloom": "2f388700s",
+ "effect-noir": "121b2271s",
+ "effect-northern-lights": "3cad29fds",
+ "effect-nostalgic-blue": "5b7da552s",
+ "effect-objects-around": "e8008dd5s",
+ "effect-ocean": "2c0521b1s",
+ "effect-oni-mask": "f4ecfeb6s",
+ "effect-origami": "ce53040es",
+ "effect-outfit-check": "e1cc8123s",
+ "effect-outfit-switch": "4c1c52ccs",
+ "effect-overexposed": "6c491813s",
+ "effect-overhead-fall": "7e3f052ds",
+ "effect-overtime": "dea403ees",
+ "effect-paint-splash": "550b3623s",
+ "effect-palette": "3f1a968es",
+ "effect-paparazzi": "1e28ed40s",
+ "effect-paper": "3a4746f2s",
+ "effect-particles": "3f959a96s",
+ "effect-peak-moment": "c78313b6s",
+ "effect-pearl-earring": "939de965s",
+ "effect-pigeons": "ab9c4012s",
+ "effect-pixelated-face": "61cf2c89s",
+ "effect-pizza-fall": "5ff7c780s",
+ "effect-plasma-explosion": "7db5a43fs",
+ "effect-plate-check": "5f201b9cs",
+ "effect-point-cloud": "6a7c3216s",
+ "effect-polygon": "05a94466s",
+ "effect-pool-jump": "ccf608b3s",
+ "effect-portal": "7ece76fbs",
+ "effect-powder-explosion": "bf32a6afs",
+ "effect-practicals": "c96f2321s",
+ "effect-push-to-glass": "9a26edb5s",
+ "effect-random-glow": "b8eb4cdds",
+ "effect-raven-transition": "77a6a4bas",
+ "effect-red-carpet": "16a0dbfds",
+ "effect-saint-glow": "f4867df7s",
+ "effect-sakura-petals": "39f5b3ebs",
+ "effect-sand-cut": "6fb2a29es",
+ "effect-sand-storm": "efc9f6bcs",
+ "effect-scrapbook-collage": "f4a9062cs",
+ "effect-seamless-transition": "77939fc1s",
+ "effect-selfception": "582c0523s",
+ "effect-selfie": "50327747s",
+ "effect-selfie-outfit": "da07170es",
+ "effect-selfie-posing": "0d1fb2cds",
+ "effect-set-on-fire": "ed4e7b28",
+ "effect-shadow-smoke": "52f93d62s",
+ "effect-shocked": "2550e4bfs",
+ "effect-silhouette": "6f80c626s",
+ "effect-skatedog": "ae124c86s",
+ "effect-sketch": "c0d19949s",
+ "effect-skin-surge": "a1543dfes",
+ "effect-smash-and-grab": "6ebf3fb2s",
+ "effect-smoke-transition": "f47d2459s",
+ "effect-sodium-decay": "d1492bc0s",
+ "effect-soft-cross": "b123152cs",
+ "effect-soft-palette": "a4fcb36fs",
+ "effect-soul-jump": "124cfc5es",
+ "effect-spiders-from-mouth": "31d7a15cs",
+ "effect-spirit-animal": "5a87f48bs",
+ "effect-splash-transition": "6c169d38s",
+ "effect-squish": "30dd25ces",
+ "effect-starship-troopers": "ca662496s",
+ "effect-static-posing": "fd33745cs",
+ "effect-stop-world": "86cf0901s",
+ "effect-street-colossus": "ba59897ds",
+ "effect-studio-slide": "78b856d8s",
+ "effect-sunglasses": "b93494fcs",
+ "effect-super-fast-run": "a50c422cs",
+ "effect-super-saiyan": "3df4e445s",
+ "effect-superstar": "639c22d4s",
+ "effect-tattoo-animation": "e7550394s",
+ "effect-teal-orange-epic": "f4545d7ds",
+ "effect-tentacles": "be641c04s",
+ "effect-thunder-god": "f14efc70s",
+ "effect-tiny-planet": "51626b4ds",
+ "effect-toxic": "afd91145s",
+ "effect-tracking": "8f9f47d1s",
+ "effect-train-rush": "283d0f97s",
+ "effect-trucksition": "0fd51505s",
+ "effect-turn-into-statue": "678d5733s",
+ "effect-turning-metal": "e5b7b072s",
+ "effect-turning-monkey": "e598aa76s",
+ "effect-two-color": "12de6f01s",
+ "effect-ultraviolet": "87e0c250s",
+ "effect-vanish": "8ef5c1cds",
+ "effect-vintage": "d460bbb8s",
+ "effect-visor-x": "a477b93as",
+ "effect-water-bending": "5705d8d2s",
+ "effect-water-element": "b83284e6s",
+ "effect-water-splash": "56eb710es",
+ "effect-werewolf": "51370b8ds",
+ "effect-wild-ride": "f8019627s",
+ "effect-wind-to-face": "b09a690as",
+ "effect-window": "803b4aafs",
+ "effect-windows": "7a20cec0s",
+ "effect-wireframe": "3d01f357s",
+ "effect-wonderland": "06efa17as",
+ "effect-world-morphing": "1c092963s",
+ "effect-x-ray": "d735b5ffs",
+ "effect-yacht": "a78c3379s"
+ },
+ "motions": {
+ "motion-360-orbit": "58535775s",
+ "motion-action-run": "099a237es",
+ "motion-aerial-pullback": "c6d2f763s",
+ "motion-arc-left": "1a4c3c30s",
+ "motion-arc-right": "1dfa5266s",
+ "motion-baseball-kick": "727c4abds",
+ "motion-basketball-dunks": "a91009bds",
+ "motion-boxing": "7ee6d5d3s",
+ "motion-bts": "0596693es",
+ "motion-bullet-time": "0ed03747",
+ "motion-car-chasing": "ac5240ebs",
+ "motion-car-grip": "bef6c9e4s",
+ "motion-catwalk": "a5801487s",
+ "motion-classic-static": "0a4734acs",
+ "motion-crane-down": "1ccff0afs",
+ "motion-crane-over-the-head": "0056e58es",
+ "motion-crane-up": "0c01e3a3s",
+ "motion-crash-zoom-in": "d38fb94c",
+ "motion-crash-zoom-out": "1395f710s",
+ "motion-documentary-snap": "3d8bdc13s",
+ "motion-dolly-in": "a3b5c344s",
+ "motion-dolly-left": "afa7b161s",
+ "motion-dolly-out": "50893bd6s",
+ "motion-dolly-right": "11b2e326s",
+ "motion-dolly-zoom-in": "4958cb37",
+ "motion-double-dolly": "39190d24s",
+ "motion-downhill-pov": "ad6df6f8s",
+ "motion-dreamy-flow": "443cdd73s",
+ "motion-drone-reveal": "e2134513s",
+ "motion-dutch-angle": "fbbd1ee0s",
+ "motion-earth-zoom-out": "efd00455s",
+ "motion-eating-zoom": "aba53489s",
+ "motion-epic-scale": "ff7271f7s",
+ "motion-eyes-in": "a5b6fab8s",
+ "motion-face-punch": "f6bd999es",
+ "motion-fisheye": "92676403s",
+ "motion-flying": "2938ff0as",
+ "motion-flying-cam-transition": "a213b8d0s",
+ "motion-focus-change": "f732ed9es",
+ "motion-fpv-drone": "4088df2a",
+ "motion-general": "ed962c9as",
+ "motion-glam": "bc9ad728s",
+ "motion-handheld": "9c6a8df9s",
+ "motion-head-tracking": "e7d399d1s",
+ "motion-helicopter-shot": "257edcb1s",
+ "motion-hero-cam": "caa36ed1s",
+ "motion-hyperlapse": "01984df2s",
+ "motion-impossible-camera": "35852accs",
+ "motion-incline": "f048ccc6s",
+ "motion-intimate-observer": "0c74e396s",
+ "motion-jib-down": "a7447f0bs",
+ "motion-jib-up": "8e158c67s",
+ "motion-kiss": "2f4dca6ds",
+ "motion-lazy-orbit": "88a8a775s",
+ "motion-lazy-susan": "f7442233s",
+ "motion-low-shutter": "4ca35560s",
+ "motion-moonwalk-left": "99de9030s",
+ "motion-moonwalk-right": "8d7a75ffs",
+ "motion-mouth-in": "2abc2adas",
+ "motion-object-pov": "cb626d6bs",
+ "motion-one-take": "166f8f5es",
+ "motion-overhead": "fb212cf4s",
+ "motion-pan": "31bdbe10s",
+ "motion-pan-left": "2155f0c5s",
+ "motion-pan-right": "824a1ae0s",
+ "motion-pov": "bd7a59efs",
+ "motion-rap-flex": "346e0400s",
+ "motion-rapid-zoom-in": "7ab6047ds",
+ "motion-rapid-zoom-out": "15ed09c1s",
+ "motion-raw-chaos": "586bedb4s",
+ "motion-road-rush": "c4544a40s",
+ "motion-robo-arm": "877f0cdbs",
+ "motion-robot-arm": "830cefc7s",
+ "motion-roll-transition": "b310e407s",
+ "motion-silent-machine": "232b3de2s",
+ "motion-skate-cruise": "fd2d1ebcs",
+ "motion-skateboard-glide": "879a7891s",
+ "motion-skateboard-ollie": "2c761fd0s",
+ "motion-ski-carving": "85827701s",
+ "motion-ski-powder": "36542e70s",
+ "motion-slow-motion": "652313d3s",
+ "motion-snorricam": "42eef661s",
+ "motion-snowboard-carving": "ced83f82s",
+ "motion-snowboard-powder": "0855c94fs",
+ "motion-static": "dff6669fs",
+ "motion-super-dolly-in": "c3275e3fs",
+ "motion-super-dolly-out": "17e0327bs",
+ "motion-through-object-in": "a01d192fs",
+ "motion-through-object-out": "1ddebc5es",
+ "motion-tilt-up": "1c4e94ecs",
+ "motion-timelapse": "d93b6d3as",
+ "motion-timelapse-glam": "f39be5c6s",
+ "motion-timelapse-human": "011e21fds",
+ "motion-timelapse-landscape": "f788694fs",
+ "motion-tracking": "f85c54fds",
+ "motion-truck-left": "3c6b27e1s",
+ "motion-truck-right": "4b7f695ds",
+ "motion-whip-pan": "a975c0abs",
+ "motion-wiggle": "8ffa1e1as",
+ "motion-yoyo-zoom": "47aee35as",
+ "motion-zoom": "a61c6834s",
+ "motion-zoom-in": "bf35229ds",
+ "motion-zoom-out": "2032d681s"
+ }
+}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 77daa214..82d3e498 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -235,7 +235,7 @@ export interface FocusPoint {
y: number;
}
-/** "llm" runs text steps (translate, write) on the configured LLM (Claude or Ollama) inside the server. */
+/** "llm" runs text steps (translate, write) on the configured LLM (Claude or a local model) inside the server. */
export type ProviderId = "fal" | "replicate" | "higgsfield" | "openai" | "google" | "comfyui" | "mock" | "local" | "llm";
/** Duration encodings differ between APIs ("5" vs 5 vs "5s"). */
diff --git a/src/lib/preset-card-data.ts b/src/lib/preset-card-data.ts
new file mode 100644
index 00000000..9a2aeba3
--- /dev/null
+++ b/src/lib/preset-card-data.ts
@@ -0,0 +1,40 @@
+/**
+ * A gallery card's data from a full catalog preset, rendered preview media included (the card
+ * types and procedural previews are in preset-cards.ts). This is the one module that reads the
+ * media manifest, so it's kept apart: whatever client code uses from a module ships in every client
+ * chunk that holds it, and preset-cards.ts is in the galleries', home's, shorts' and mixed media's
+ * chunks, which only need the hash on each card. Server pages (home, motions, effects, apps) import
+ * this; on the client only the preset header does, in its own lazily loaded chunk (studio-page.tsx).
+ */
+import PREVIEW_MEDIA from "./catalog/preview-media.generated.json";
+import type { Preset } from "./catalog/types";
+import { clip, lookHue, motionMove, proceduralPreview, type PresetCardData, type PresetPreview } from "./preset-cards";
+import { mediaHash, type PreviewManifest } from "./preview-media";
+
+const MEDIA: PreviewManifest = PREVIEW_MEDIA;
+
+/**
+ * A preset's card preview: its rendered media when the manifest lists it (just the hash, and a
+ * motion's move for its glyph), else the procedural one.
+ */
+export function previewFor(p: Pick<Preset, "id" | "type" | "name" | "category">): PresetPreview {
+ const media = mediaHash(MEDIA, p.id);
+ if (!media) return proceduralPreview(p);
+ return { media, ...(p.type === "motion" ? { move: motionMove(p) } : {}) };
+}
+
+/** What a gallery card needs, and nothing else. */
+export function toPresetCard(p: Preset): PresetCardData {
+ return {
+ id: p.id,
+ name: p.name,
+ description: clip(p.description, 100),
+ category: p.category,
+ icon: p.look.icon,
+ hue: lookHue(p.look),
+ ...(p.badges?.includes("top") ? { top: true as const } : {}),
+ cloud: !!p.cloud,
+ open: !!p.open,
+ preview: previewFor(p),
+ };
+}
diff --git a/src/lib/preset-cards.ts b/src/lib/preset-cards.ts
index bb3586ee..f693638e 100644
--- a/src/lib/preset-cards.ts
+++ b/src/lib/preset-cards.ts
@@ -1,11 +1,14 @@
/**
- * Slim preset card data for the galleries, and the procedural previews shown on each card.
+ * Slim preset card data for the galleries, and the previews shown on each card.
*
* Gallery pages are server components: they map the full catalog `Preset` (prompt templates,
- * routes, LoRA URLs, parity notes) to `PresetCardData` here, so only what a card shows reaches
- * the browser. Until real preview clips exist, every card gets a procedural preview: a camera
- * move over a bundled layered still for motions, a per-category animated treatment for effects
- * and apps. Pure module, safe on both sides.
+ * routes, LoRA URLs, parity notes) to `PresetCardData` with toPresetCard() (preset-card-data.ts),
+ * so only what a card shows reaches the browser. A preset with rendered media (public/previews, see
+ * preview-media.ts) sends only its hash; every other card gets a procedural preview: a camera move
+ * over a bundled layered still for motions, a per-category animated treatment for effects and apps.
+ * The procedural preview is also what a card with media falls back to when its files don't load.
+ * Pure module, safe on both sides. It doesn't import the media manifest: client code imports this
+ * module all over, so the manifest would ship in each of those chunks (tests/preview-media.test.ts).
*/
import type { Preset } from "./catalog/types";
@@ -171,16 +174,31 @@ export const FX = [
] as const;
export type PreviewFx = (typeof FX)[number];
-export interface PresetPreview {
+/** A camera move over a bundled layered still (motions), or an animated treatment over one (effects, apps). */
+export interface ProceduralPreview {
+ media?: undefined;
/** Still shown before (and under) the preview. */
poster: string;
- /** A real example clip, once one exists: played instead of the procedural preview. */
- video?: string;
scene: PreviewScene;
move?: CameraMove;
fx?: PreviewFx;
}
+/**
+ * Rendered media: a poster and a muted loop (public/previews, see preview-media.ts). Only the hash
+ * in their file names, plus a motion's move for the glyph drawn over its poster; the client works
+ * the procedural preview out again if the files don't load (fallbackPreview).
+ */
+export interface MediaPreview {
+ media: string;
+ move?: CameraMove;
+ poster?: undefined;
+ scene?: undefined;
+ fx?: undefined;
+}
+
+export type PresetPreview = ProceduralPreview | MediaPreview;
+
export interface PresetCardData {
id: string;
name: string;
@@ -379,7 +397,7 @@ export function previewScene(p: Pick<Preset, "type" | "name" | "category"> & { i
return pick(p.id, ["portrait", "landscape", "city", "portrait"] as const);
}
-export function previewFor(p: Pick<Preset, "id" | "type" | "name" | "category">): PresetPreview {
+export function proceduralPreview(p: Pick<Preset, "id" | "type" | "name" | "category">): ProceduralPreview {
const scene = previewScene(p);
return {
poster: scenePoster(scene),
@@ -388,6 +406,15 @@ export function previewFor(p: Pick<Preset, "id" | "type" | "name" | "category">)
};
}
+/**
+ * The procedural preview of a card whose media doesn't load. Card data only carries the media's
+ * hash, so the client works it out again from the id (which says the type), name and category.
+ */
+export function fallbackPreview(c: Pick<PresetCardData, "id" | "name" | "category">): ProceduralPreview {
+ const type: Preset["type"] = c.id.startsWith("motion-") ? "motion" : c.id.startsWith("effect-") ? "effect" : "app";
+ return proceduralPreview({ ...c, type });
+}
+
/**
* Whether a card shows its still mirrored, so neighbouring treatments on the same still differ.
* Never for camera moves (a pan left must still go left). Derived from the id on the client, so it
@@ -410,22 +437,6 @@ export function clip(s: string, max: number): string {
return `${cut.slice(0, Math.max(cut.lastIndexOf(" "), max * 0.6)).replace(/[\s,;:.–—-]+$/, "")}…`;
}
-/** What a gallery card needs, and nothing else. */
-export function toPresetCard(p: Preset): PresetCardData {
- return {
- id: p.id,
- name: p.name,
- description: clip(p.description, 100),
- category: p.category,
- icon: p.look.icon,
- hue: lookHue(p.look),
- ...(p.badges?.includes("top") ? { top: true as const } : {}),
- cloud: !!p.cloud,
- open: !!p.open,
- preview: previewFor(p),
- };
-}
-
/**
* A showcase row: one preset per category (its "top" one when it has one), in catalog order, so
* the row shows `n` different kinds of effect instead of the first category's six.
diff --git a/src/lib/preview-media.ts b/src/lib/preview-media.ts
new file mode 100644
index 00000000..049b6253
--- /dev/null
+++ b/src/lib/preview-media.ts
@@ -0,0 +1,69 @@
+/**
+ * Where a preset card's rendered preview lives (scripts/build-previews.mjs makes it from the masters):
+ * a poster still as AVIF in three widths plus a WebP fallback, and a short muted loop, all under
+ * public/previews/<kind>/ with the hash of their masters in the name. A new render gets new names,
+ * so the files are served as immutable (next.config.ts). Which presets have media, and their hashes,
+ * is the manifest src/lib/catalog/preview-media.generated.json, read only by previewFor() in
+ * preset-card-data.ts: card data only carries the 8-character hash. Pure module, safe on both sides.
+ */
+
+/** Folders under public/previews: the 4:3 preset cards (other surfaces add theirs here). */
+export type PreviewKind = "motions" | "effects" | "apps";
+
+/**
+ * `{ kind: { preset id: hash } }`, as the build script writes it. A hash with a trailing `s` is a still: the
+ * preset has its poster but no clip yet (the build's `--stills` mode, while clips are still rendering).
+ */
+export type PreviewManifest = Partial<Record<PreviewKind, Record<string, string>>>;
+
+/** Whether a manifest hash is a still (poster only, no clip). */
+export function isStill(hash: string): boolean {
+ return /^[0-9a-f]{8}s$/.test(hash);
+}
+
+const KIND_OF_PREFIX: Record<string, PreviewKind> = { motion: "motions", effect: "effects", app: "apps" };
+
+/** Which folder a preset's media is in, from its id's prefix (the build script uses the same rule). */
+export function kindOf(id: string): PreviewKind | undefined {
+ const prefix = /^(motion|effect|app)-[a-z0-9-]+$/.exec(id)?.[1];
+ return prefix ? KIND_OF_PREFIX[prefix] : undefined;
+}
+
+/** The poster comes as AVIF in each of these widths (a srcset), and as WebP in one. */
+export const POSTER_WIDTHS = [320, 480, 640] as const;
+export const WEBP_WIDTH = 480;
+
+export interface PreviewSources {
+ /** For `<source type="image/avif" srcSet>`. */
+ avifSrcSet: string;
+ /** The poster for browsers without AVIF. */
+ webpSrc: string;
+ /** The muted loop (480 × 360 H.264, no audio); none for a still. */
+ mp4Src?: string;
+}
+
+/** The URLs of a preset's media files (the files are named after the 8-digit hash, without a still's `s`). */
+export function previewSrc(kind: PreviewKind, id: string, hash: string): PreviewSources {
+ const base = `/previews/${kind}/${id}.${hash.slice(0, 8)}`;
+ return {
+ avifSrcSet: POSTER_WIDTHS.map((w) => `${base}.${w}.avif ${w}w`).join(", "),
+ webpSrc: `${base}.${WEBP_WIDTH}.webp`,
+ ...(isStill(hash) ? {} : { mp4Src: `${base}.mp4` }),
+ };
+}
+
+/** A preset's media hash, when the manifest lists it. */
+export function mediaHash(manifest: PreviewManifest, id: string): string | undefined {
+ const kind = kindOf(id);
+ return kind && manifest[kind]?.[id];
+}
+
+/** How wide each surface draws a preset card's preview: the poster's `sizes`, for picking from its srcset. */
+export const PREVIEW_SIZES = {
+ /** PresetGallery: 2, 3, 4 then 5 columns (GALLERY_GRID) in PageShell's 1200 px. */
+ gallery: "(min-width: 1280px) 212px, (min-width: 1024px) 165px, (min-width: 640px) 30vw, 46vw",
+ /** Home rows: 2, 4 then 6 columns. */
+ home: "(min-width: 1024px) 175px, (min-width: 640px) 25vw, 46vw",
+ /** PresetHeader: 96 px wide on phones, 128 px from sm up. */
+ header: "128px",
+} as const;
diff --git a/src/lib/preview-playback.ts b/src/lib/preview-playback.ts
index f1534d9c..d3b21141 100644
--- a/src/lib/preview-playback.ts
+++ b/src/lib/preview-playback.ts
@@ -1,7 +1,9 @@
/**
- * Which gallery preview plays (preset-preview.tsx). One at a time everywhere: the hovered or
- * focused card on devices that can hover, otherwise the card nearest the middle of the screen
- * while it's mostly in view (phones). Nothing plays when the user prefers reduced motion.
+ * Which gallery preview plays (preset-preview.tsx). One at a time everywhere: on devices that can
+ * hover, the hovered or focused card once the pointer has rested on it for a moment (a pointer
+ * crossing the grid doesn't start every card it passes); otherwise the card nearest the middle of
+ * the screen while it's mostly in view, once scrolling has stopped (phones; not with Save-Data or
+ * on a 2G connection). Nothing plays when the user prefers reduced motion.
*
* Pure apart from the environment it's given, so the rules are testable without a browser.
*/
@@ -11,14 +13,21 @@ export interface PlaybackEnv {
matches(query: string): boolean;
/** Undefined where IntersectionObserver doesn't exist (then nothing auto-plays). */
IntersectionObserver?: new (cb: IntersectionObserverCallback, opts?: IntersectionObserverInit) => Pick<IntersectionObserver, "observe" | "unobserve">;
- requestFrame(cb: () => void): number;
+ /** Run `cb` after `ms` milliseconds; returns what cancels it. */
+ delay(cb: () => void, ms: number): () => void;
viewportHeight(): number;
onScroll(cb: () => void): void;
offScroll(cb: () => void): void;
+ /** The user asked for less data (Save-Data), or the connection is 2G. */
+ saveData(): boolean;
}
/** A card must be at least this much in view to play on a phone. */
export const MIN_VISIBLE = 0.6;
+/** How long the pointer (or focus) rests on a card before it plays, in ms. */
+export const HOVER_INTENT = 120;
+/** On phones, how long scrolling must have stopped before the centred card plays, in ms. */
+export const SCROLL_SETTLE = 400;
export function createPlaybackStore(env: PlaybackEnv) {
const listeners = new Set<() => void>();
@@ -26,17 +35,24 @@ export function createPlaybackStore(env: PlaybackEnv) {
const watched = new Map<Element, string>();
const ratios = new Map<Element, number>();
let observer: Pick<IntersectionObserver, "observe" | "unobserve"> | null = null;
- let frame = 0;
+ /** The card a hover is about to play, and what calls that off. */
+ let pending: { id: string; cancel: () => void } | null = null;
+ let settle: (() => void) | null = null;
const setActive = (id: string | null) => {
if (active === id) return;
active = id;
listeners.forEach((l) => l());
};
+ const reducedMotion = () => env.matches("(prefers-reduced-motion: reduce)");
+ const cancelPending = () => {
+ pending?.cancel();
+ pending = null;
+ };
/** Phones: the most visible card closest to the viewport's middle plays. */
const pickCentered = () => {
- frame = 0;
+ settle = null;
const mid = env.viewportHeight() / 2;
let best: string | null = null;
let bestDist = Infinity;
@@ -51,8 +67,10 @@ export function createPlaybackStore(env: PlaybackEnv) {
}
setActive(best);
};
+ /** Pick once the page is still: every scroll (or visibility change) starts the wait over. */
const schedule = () => {
- frame ||= env.requestFrame(pickCentered);
+ settle?.();
+ settle = env.delay(pickCentered, SCROLL_SETTLE);
};
return {
@@ -65,22 +83,36 @@ export function createPlaybackStore(env: PlaybackEnv) {
getActive: () => active,
isActive: (id: string) => active === id,
canHover: () => env.matches("(hover: hover) and (pointer: fine)"),
- reducedMotion: () => env.matches("(prefers-reduced-motion: reduce)"),
- /** Hover / focus: play this one (unless motion is reduced). */
+ reducedMotion,
+ saveData: () => env.saveData(),
+ /** Hover / focus: play this one once it has had the pointer for HOVER_INTENT (unless motion is reduced). */
play(id: string) {
- if (!env.matches("(prefers-reduced-motion: reduce)")) setActive(id);
+ cancelPending();
+ if (reducedMotion()) return;
+ const cancel = env.delay(() => {
+ pending = null;
+ setActive(id);
+ }, HOVER_INTENT);
+ pending = { id, cancel };
},
- /** Stop this one, if it's the one playing. */
+ /** Stop this one, if it's the one playing (or about to). */
stop(id: string) {
+ if (pending?.id === id) cancelPending();
if (active === id) setActive(null);
},
/** Touch devices: let visibility decide whether `el` plays. Returns the cleanup. */
watch(el: Element, id: string): () => void {
const IO = env.IntersectionObserver;
- if (!IO) return () => {};
+ // Each card passing the middle of the screen would start a download: none with Save-Data or on 2G.
+ if (!IO || env.saveData()) return () => {};
observer ??= new IO(
(entries) => {
- for (const e of entries) ratios.set(e.target, e.isIntersecting ? e.intersectionRatio : 0);
+ for (const e of entries) {
+ const ratio = e.isIntersecting ? e.intersectionRatio : 0;
+ ratios.set(e.target, ratio);
+ // The playing card stops as soon as it's mostly out of view; the next one waits for the scroll to settle.
+ if (ratio < MIN_VISIBLE && active !== null && watched.get(e.target) === active) setActive(null);
+ }
schedule();
},
{ threshold: [0, MIN_VISIBLE, 0.85, 1] },
@@ -92,7 +124,11 @@ export function createPlaybackStore(env: PlaybackEnv) {
observer?.unobserve(el);
watched.delete(el);
ratios.delete(el);
- if (!watched.size) env.offScroll(schedule);
+ if (!watched.size) {
+ env.offScroll(schedule);
+ settle?.();
+ settle = null;
+ }
if (active === id) setActive(null);
};
},
@@ -103,14 +139,24 @@ export function createPlaybackStore(env: PlaybackEnv) {
export type PlaybackStore = ReturnType<typeof createPlaybackStore>;
+type Connection = { saveData?: boolean; effectiveType?: string };
+
/** The real browser; every member is safe to call during server rendering. */
export const browserPlaybackEnv: PlaybackEnv = {
matches: (q) => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(q).matches,
get IntersectionObserver() {
return typeof IntersectionObserver === "undefined" ? undefined : IntersectionObserver;
},
- requestFrame: (cb) => requestAnimationFrame(cb),
+ delay: (cb, ms) => {
+ const t = setTimeout(cb, ms);
+ return () => clearTimeout(t);
+ },
viewportHeight: () => window.innerHeight,
onScroll: (cb) => window.addEventListener("scroll", cb, { passive: true, capture: true }),
offScroll: (cb) => window.removeEventListener("scroll", cb, { capture: true }),
+ saveData: () => {
+ const c = typeof navigator === "undefined" ? undefined : (navigator as Navigator & { connection?: Connection }).connection;
+ // effectiveType is "slow-2g", "2g", "3g" or "4g" (Chromium only; elsewhere this is false).
+ return !!c && (c.saveData === true || !!c.effectiveType?.endsWith("2g"));
+ },
};
diff --git a/src/proxy.ts b/src/proxy.ts
index fd8877fb..3d776662 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -63,6 +63,7 @@ export function proxy(request: NextRequest) {
export const config = {
// Everything except build assets and the public folder's own files: the favicon, the demo
- // samples and the SVGs at the root. Generated SVGs under /api/files stay behind sign-in.
- matcher: ["/((?!_next/static|_next/image|favicon\\.ico$|samples/|[^/]+\\.svg$).*)"],
+ // samples, the preset cards' preview media, vendored scripts (the 3D viewer's meshopt decoder)
+ // and the SVGs at the root. Generated SVGs under /api/files stay behind sign-in.
+ matcher: ["/((?!_next/static|_next/image|favicon\\.ico$|samples/|previews/|vendor/|[^/]+\\.svg$).*)"],
};
diff --git a/src/server/ads.ts b/src/server/ads.ts
index 0c833bc9..86345cfc 100644
--- a/src/server/ads.ts
+++ b/src/server/ads.ts
@@ -66,6 +66,14 @@ Answer with ONE JSON object and nothing else:
{"ads": [{"angle": string (one of the angle ids given), "headline": string (at most 7 words), "body": string (at most 20 words), "cta": string (1–3 words), "visual": string (one sentence describing the photo to shoot; it must contain no text, words or logos)}]}
Write exactly the number of ads asked for. Vary the angles, headlines and pictures; never repeat a headline. Use the brand's tone and language. No hashtags, no emojis, no quotation marks in headlines.`;
+// The answers as JSON Schemas, for local models that decode to one; the prompts ask for the same JSON.
+const objectOf = (properties: Record<string, unknown>) => ({ type: "object", properties, required: Object.keys(properties), additionalProperties: false });
+const S = { type: "string" };
+const copySchema = (count: number) => ({
+ name: "ads",
+ schema: objectOf({ ads: { type: "array", minItems: count, maxItems: count, items: objectOf({ angle: { type: "string", enum: AD_ANGLES.map((a) => a.id) }, headline: S, body: S, cta: S, visual: S }) } }),
+});
+
const ctaFor: Record<string, string[]> = {
benefit: ["Shop now", "Discover more"],
"pain-point": ["Fix it today", "Try it"],
@@ -150,7 +158,7 @@ export async function writeConcepts(brand: BrandKit, product: Product, count: nu
]
.filter(Boolean)
.join("\n");
- return conceptsFrom(await llmText(COPY_SYSTEM, user), fallback);
+ return conceptsFrom(await llmText(COPY_SYSTEM, user, { json: copySchema(count) }), fallback);
}
// ---------------------------------------------------------------------------
@@ -549,6 +557,11 @@ Answer with ONE JSON object and nothing else:
{"reply": string (1–3 friendly sentences), "make": null or {"products": string[] (exact product names from the list; empty = all of them), "count": number (ads per product, 1–20), "direction": string (the creative direction in one sentence: theme, setting, offer, audience, language…)}}
Set "make" whenever the user asks for ads, variations, versions or changes to ads; otherwise answer the question and set "make" to null.`;
+const CHAT_SCHEMA = {
+ name: "reply",
+ schema: objectOf({ reply: S, make: { anyOf: [{ type: "null" }, objectOf({ products: { type: "array", items: S }, count: { type: "integer" }, direction: S })] } }),
+};
+
const mentionRe = (name: string) => new RegExp(`@${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "[\\s_]+")}`, "i");
/** Products named in a message with @ ("@Night Serum" or "@Night_Serum"), longest names first. */
@@ -631,7 +644,7 @@ export async function chat(brandId: string, text: string): Promise<ChatMessage[]
]
.filter(Boolean)
.join("\n");
- const j = parseJsonObject(await llmText(CHAT_SYSTEM, context));
+ const j = parseJsonObject(await llmText(CHAT_SYSTEM, context, { json: CHAT_SCHEMA }));
let reply: ChatMessage;
if (j && typeof j.reply === "string") {
const make = j.make && typeof j.make === "object" ? (j.make as Record<string, unknown>) : null;
@@ -663,7 +676,7 @@ export async function chat(brandId: string, text: string): Promise<ChatMessage[]
id: nanoid(8),
role: "assistant",
text: products.length
- ? `I can make ads for you — try “Make 4 ads for @${products[0].name} with a holiday theme”. Connect Claude or Ollama in Settings and I can talk through ideas too.`
+ ? `I can make ads for you — try “Make 4 ads for @${products[0].name} with a holiday theme”. Connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings and I can talk through ideas too.`
: "Add a product first, then ask me for ads — e.g. “Make 4 ads with a summer theme”.",
at: Date.now(),
proposal: null,
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index 30e581d4..1704ea4a 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -10,11 +10,13 @@ import {
DEFAULT_EFFORT,
factMap,
guessCategory,
+ normalizeAgent,
renderContext,
slashSkills,
threadTitle,
type AssistAgent,
type AssistAvailability,
+ type AssistLocal,
type AssistEffort,
type AssistItem,
type AssistMode,
@@ -27,6 +29,7 @@ import {
import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";
import { db } from "../db";
import { getGeneration } from "../generations";
+import { activeLocal, aiHelper, chatLocal, emptyReply, localLabel, localProblem, pinnedKind, toChatMessages, type Ready } from "../llm";
import { engineMode, getSetting } from "../settings";
import { getSkill } from "../skills";
import { readRef } from "../storage";
@@ -56,7 +59,7 @@ export interface ModelRequest {
messages: MessageParam[];
tools: Anthropic.Beta.BetaTool[];
ctx: ToolContext;
- /** The chat's model choice (Manual mode): a Claude model id or an Ollama model name, and the effort. */
+ /** The chat's model choice (Manual mode): a Claude model id or a local model's name, and the effort. */
settings?: { model?: string | null; effort?: AssistEffort | null };
/** Skills loaded in the chat (the offline planner uses their hints). */
skills?: SkillMeta[];
@@ -156,7 +159,8 @@ function load(id: string): State | null {
id: r.id,
title: r.title,
status: r.status,
- agent: r.agent,
+ // Chats from before LM Studio and Unsloth Studio support say "ollama".
+ agent: normalizeAgent(r.agent) ?? "offline",
engine: r.engine,
autoApprove: !!r.auto_approve,
items: JSON.parse(r.items_json) as AssistItem[],
@@ -328,45 +332,46 @@ export async function updateThread(id: string, patch: ThreadPatch): Promise<Assi
// ---------------------------------------------------------------------------
// Which LLM runs a chat: modes
-let ollamaProbe: { at: number; url: string; ok: boolean; models: string[] } | null = null;
-async function probeOllama(): Promise<{ ok: boolean; models: string[] }> {
- const url = getSetting("ollamaUrl").replace(/\/+$/, "");
- if (ollamaProbe && ollamaProbe.url === url && Date.now() - ollamaProbe.at < 30_000) return ollamaProbe;
- const res = await fetch(`${url}/api/tags`, { signal: AbortSignal.timeout(800) })
- .then(async (r) => (r.ok ? ((await r.json().catch(() => ({}))) as { models?: { name?: string }[] }) : null))
- .catch(() => null);
- ollamaProbe = { at: Date.now(), url, ok: !!res, models: (res?.models ?? []).map((m) => m.name ?? "").filter(Boolean).slice(0, 50) };
- return ollamaProbe;
+/** Why the local model can't take a chat, and what to do: the server's own reason, or which servers to start. */
+function localDownNote(): string {
+ const why = localProblem();
+ if (why) return `${why.replace(/\.$/, "")} — or pick another mode.`;
+ return `No local model server is answering (${pinnedKind() ? localLabel() : "Ollama, LM Studio or Unsloth Studio"}) — start one, or pick another mode.`;
}
-const ollamaReachable = async () => (await probeOllama()).ok;
/**
* Which LLM drives new chats by default: Claude when a key is set (on open-source-only installs only when
- * picked explicitly), else a reachable local Ollama, else the offline planner.
+ * picked explicitly), else a local model that answers (Ollama, LM Studio, Unsloth Studio…), else the offline planner.
*/
export async function resolveAgent(): Promise<AssistThread["agent"]> {
- const choice = getSetting("enhanceProvider");
+ const choice = aiHelper();
const key = !!getSetting("anthropicKey");
if (choice === "none") return "offline";
if (choice === "anthropic") return key ? "claude" : "offline";
- if (choice === "ollama") return "ollama";
+ if (choice === "local") return "local";
if (key && engineMode() !== "open") return "claude";
- return (await ollamaReachable()) ? "ollama" : "offline";
+ return (await activeLocal()) ? "local" : "offline";
}
-const claudeAllowed = () => !!getSetting("anthropicKey") && (engineMode() !== "open" || getSetting("enhanceProvider") === "anthropic");
+const claudeAllowed = () => !!getSetting("anthropicKey") && (engineMode() !== "open" || aiHelper() === "anthropic");
+
+/** The local server for the mode picker: its models (Unsloth only answers with the loaded one), or why it can't run. */
+function localInfo(ready: Ready | null): AssistLocal {
+ if (!ready) return { kind: pinnedKind(), label: localLabel(), ok: false, models: [], model: null, ...(localProblem() && { problem: localProblem()! }) };
+ const { server, status } = ready;
+ const models = status.models.filter((m) => server.kind !== "unsloth" || m.loaded || m.id === status.model).map((m) => m.id);
+ return { kind: server.kind, label: server.label, ok: true, models: models.slice(0, 50), model: status.model };
+}
export async function availability(): Promise<AssistAvailability> {
- const o = await probeOllama();
- const aiOff = getSetting("enhanceProvider") === "none";
+ const ready = await activeLocal();
+ const aiOff = aiHelper() === "none";
const claude = claudeAllowed();
return {
claude,
- ollama: o.ok,
- ollamaModels: o.models,
- ollamaModel: getSetting("ollamaModel"),
+ local: localInfo(ready),
aiOff,
- defaultMode: !aiOff && claude && getSetting("enhanceProvider") !== "ollama" ? "smart" : "free",
+ defaultMode: !aiOff && claude && aiHelper() !== "local" ? "smart" : "free",
};
}
@@ -379,17 +384,18 @@ export interface ResolvedMode {
note?: string;
}
-const OLLAMA_NAME = /^[\w.:/-]{1,100}$/;
+/** A local model's name: Ollama's "qwen3:8b", LM Studio's "qwen/qwen3-8b@q4_k_m", Unsloth's "unsloth/Qwen3-8B-GGUF:Q4_K_M". */
+const LOCAL_NAME = /^[\w.:/@+-]{1,200}$/;
/**
- * Supercomputer's modes on Fuobe's agents: Smart = Claude Opus 5.5; Free = a local model through
- * Ollama (or the offline planner when none answers); Manual = the model and effort you pick.
- * Without a choice, the default from Settings (resolveAgent).
+ * Supercomputer's modes on Fuobe's agents: Smart = Claude Opus 5.5; Free = a local model (Ollama,
+ * LM Studio, Unsloth Studio…; the offline planner when none answers); Manual = the model and effort
+ * you pick. Without a choice, the default from Settings (resolveAgent).
*/
export async function resolveMode(choice?: Partial<AssistModeChoice>): Promise<ResolvedMode> {
const free = async (note?: string): Promise<ResolvedMode> =>
- (await ollamaReachable()) ? { mode: "free", agent: "ollama", model: null, effort: null, note } : { mode: "free", agent: "offline", model: null, effort: null, note };
- if (getSetting("enhanceProvider") === "none") {
+ (await activeLocal()) ? { mode: "free", agent: "local", model: null, effort: null, note } : { mode: "free", agent: "offline", model: null, effort: null, note };
+ if (aiHelper() === "none") {
return { mode: choice?.mode ?? "free", agent: "offline", model: null, effort: null, ...(choice?.mode && choice.mode !== "free" && { note: "The AI helper is off in Settings, so this chat uses the offline planner." }) };
}
if (!choice?.mode) {
@@ -400,23 +406,24 @@ export async function resolveMode(choice?: Partial<AssistModeChoice>): Promise<R
if (choice.mode === "smart") return claudeAllowed() ? { mode: "smart", agent: "claude", model: DEFAULT_CLAUDE_MODEL, effort: DEFAULT_EFFORT } : free(noKey);
if (choice.mode === "free") return free();
// Manual
- const agent = choice.agent ?? "claude";
+ const agent = normalizeAgent(choice.agent) ?? "claude";
if (agent === "claude") {
if (!getSetting("anthropicKey")) return free(noKey);
const model = CLAUDE_MODELS.some((m) => m.id === choice.model) ? choice.model! : DEFAULT_CLAUDE_MODEL;
const effort = ASSIST_EFFORTS.some((e) => e.id === choice.effort) ? choice.effort! : DEFAULT_EFFORT;
return { mode: "manual", agent: "claude", model, effort };
}
- if (agent === "ollama") {
- const model = choice.model && OLLAMA_NAME.test(choice.model) ? choice.model : null;
- return { mode: "manual", agent: "ollama", model, effort: null, ...(!(await ollamaReachable()) && { note: `Ollama isn't answering at ${getSetting("ollamaUrl")} — start it, or pick another mode.` }) };
+ if (agent === "local") {
+ const model = choice.model && LOCAL_NAME.test(choice.model) ? choice.model : null;
+ return { mode: "manual", agent: "local", model, effort: null, ...(!(await activeLocal()) && { note: localDownNote() }) };
}
return { mode: "manual", agent: "offline", model: null, effort: null };
}
export function createThread(opts: {
engine: Engine;
- agent: AssistThread["agent"];
+ /** "ollama" is the local agent's old name. */
+ agent: AssistThread["agent"] | "ollama";
autoApprove?: boolean;
title?: string;
projectId?: string | null;
@@ -427,7 +434,7 @@ export function createThread(opts: {
const now = Date.now();
if (opts.projectId && !getProject(opts.projectId)) throw new Error("That project doesn't exist anymore");
const s: State = {
- thread: { id: nanoid(12), title: opts.title ?? "New chat", status: "idle", agent: opts.agent, engine: opts.engine, autoApprove: !!opts.autoApprove, items: [], createdAt: now, updatedAt: now },
+ thread: { id: nanoid(12), title: opts.title ?? "New chat", status: "idle", agent: normalizeAgent(opts.agent) ?? "offline", engine: opts.engine, autoApprove: !!opts.autoApprove, items: [], createdAt: now, updatedAt: now },
messages: [],
pending: null,
ext: { projectId: opts.projectId ?? null, mode: opts.mode ?? null, model: opts.model ?? null, effort: opts.effort ?? null, skills: [], context: null, sent: null },
@@ -566,77 +573,32 @@ export const claude: ModelCall = async ({ system, messages, tools, settings }) =
return stream.finalMessage();
};
-type OllamaMessage = { role: "system" | "user" | "assistant" | "tool"; content: string; tool_calls?: { function: { name: string; arguments: unknown } }[]; tool_name?: string };
-
-const blockText = (c: ToolResult["content"]): string =>
- typeof c === "string" ? c : (c ?? []).map((b) => (b.type === "text" ? b.text : b.type === "image" ? "[image omitted]" : "")).join("\n");
-
-/** The stored (Anthropic-shaped) history as Ollama chat messages. Images stay as their URLs in the text. */
-export function toOllamaMessages(system: ModelRequest["system"], messages: MessageParam[]): OllamaMessage[] {
- const names = new Map<string, string>();
- const out: OllamaMessage[] = [{ role: "system", content: `${system.stable}\n\n${system.turn}` }];
- for (const m of messages) {
- if (typeof m.content === "string") {
- out.push({ role: m.role, content: m.content });
- continue;
- }
- if (m.role === "system") {
- out.push({ role: "system", content: m.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n") });
- continue;
- }
- if (m.role === "assistant") {
- const text = m.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");
- const calls = m.content.flatMap((b) => {
- if (b.type !== "tool_use") return [];
- names.set(b.id, b.name);
- return [{ function: { name: b.name, arguments: b.input } }];
- });
- out.push({ role: "assistant", content: text, ...(calls.length && { tool_calls: calls }) });
- continue;
- }
- for (const b of m.content) if (b.type === "tool_result") out.push({ role: "tool", tool_name: names.get(b.tool_use_id), content: `${b.is_error ? "Error: " : ""}${blockText(b.content)}` });
- const text = m.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");
- if (text) out.push({ role: "user", content: text });
- }
- return out;
-}
-
-/** A local model through Ollama's tool calling (qwen3, llama3.x, mistral…), answering in the same shape as Claude. */
-export const ollama: ModelCall = async ({ system, messages, tools, settings }) => {
- const model = settings?.model || getSetting("ollamaModel");
- const res = await fetch(`${getSetting("ollamaUrl").replace(/\/+$/, "")}/api/chat`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- model,
- stream: false,
- messages: toOllamaMessages(system, messages),
- tools: tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.input_schema } })),
- options: { num_ctx: 16384 },
- }),
- signal: AbortSignal.timeout(300_000),
- }).catch((e: Error) => {
- throw new Error(`Couldn't reach Ollama at ${getSetting("ollamaUrl")} (${e.message}). Is it running?`);
+/**
+ * A local model through its server's tool calling (Ollama, LM Studio, Unsloth Studio or another
+ * OpenAI-compatible server; qwen3, llama3.x, mistral, gemma…), answering in the same shape as Claude.
+ * The history goes out as chat messages shaped for the server (src/server/llm/messages.ts).
+ */
+export const local: ModelCall = async ({ system, messages, tools, settings }) => {
+ const ready = await activeLocal();
+ if (!ready) throw new Error(localDownNote());
+ const { server, status } = ready;
+ // A model picked for this chat on another server gives way to this one's default.
+ const want = settings?.model;
+ const model = want && (!status.models.length || status.models.some((m) => m.id === want || m.id === `${want}:latest`)) ? want : null;
+ const r = await chatLocal(ready, {
+ messages: toChatMessages(system, messages, server.kind),
+ tools: tools.map((t) => ({ name: t.name, description: t.description, parameters: t.input_schema })),
+ model,
+ timeoutMs: 300_000,
});
- if (!res.ok) throw new Error(`Ollama returned ${res.status}: ${(await res.text()).slice(0, 300)}`);
- const j = (await res.json()) as { message?: { content?: string; tool_calls?: { function: { name: string; arguments: unknown } }[] }; done_reason?: string };
+ // A thinking model that ran out of room says so, rather than "the reply was cut short".
+ if (!r.text && !r.toolCalls.length && r.stop === "length") throw emptyReply(server, r);
const content: Anthropic.Beta.BetaContentBlock[] = [];
- const text = (j.message?.content ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim();
- if (text) content.push({ type: "text", text, citations: null } as Anthropic.Beta.BetaTextBlock);
- for (const c of j.message?.tool_calls ?? []) {
- let input = c.function.arguments;
- if (typeof input === "string") {
- try {
- input = JSON.parse(input);
- } catch {
- input = { INVALID_JSON: input };
- }
- }
- content.push({ type: "tool_use", id: `toolu_ollama_${nanoid(10)}`, name: c.function.name, input } as unknown as Anthropic.Beta.BetaToolUseBlock);
- }
- const stop: Anthropic.Beta.BetaStopReason = j.message?.tool_calls?.length ? "tool_use" : j.done_reason === "length" ? "max_tokens" : "end_turn";
+ if (r.text) content.push({ type: "text", text: r.text, citations: null } as Anthropic.Beta.BetaTextBlock);
+ for (const c of r.toolCalls) content.push({ type: "tool_use", id: c.id, name: c.name, input: c.input } as unknown as Anthropic.Beta.BetaToolUseBlock);
+ const stop: Anthropic.Beta.BetaStopReason = r.toolCalls.length ? "tool_use" : r.stop === "length" ? "max_tokens" : "end_turn";
if (!content.length) content.push({ type: "text", text: "…", citations: null } as Anthropic.Beta.BetaTextBlock);
- return { id: `msg_ollama_${nanoid(8)}`, type: "message", role: "assistant", model, content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null } as unknown as Anthropic.Beta.BetaMessage;
+ return { id: `msg_local_${nanoid(8)}`, type: "message", role: "assistant", model: r.model, content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null } as unknown as Anthropic.Beta.BetaMessage;
};
/** A rule-based planner with the same shape as a model reply, for installs without an LLM. */
@@ -667,7 +629,7 @@ export const offline: ModelCall = async ({ messages, ctx, skills }) => {
};
/** Under every offline plan: the rule-based planner is a fallback, not the assistant. */
-export const OFFLINE_NOTE = "Offline planner — connect Claude or Ollama in Settings for better plans.";
+export const OFFLINE_NOTE = "Offline planner — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for better plans.";
/** What to offer next, by what was just started. */
const FOLLOW_UP: Record<MediaKind, string> = {
@@ -952,7 +914,7 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {
return "continue";
}
-const MODELS: Record<AssistThread["agent"], ModelCall> = { claude, ollama, offline };
+const MODELS: Record<AssistThread["agent"], ModelCall> = { claude, local, offline };
/**
* Run the agent until it ends its turn or waits for approval. Call it right after addMessage or
diff --git a/src/server/assist/schemas.ts b/src/server/assist/schemas.ts
index 05e31362..739a74b9 100644
--- a/src/server/assist/schemas.ts
+++ b/src/server/assist/schemas.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { ASSIST_EFFORTS, ASSIST_MODES, MEMORY_CATEGORIES, PROJECT_COLORS } from "@/lib/assist";
+import { ASSIST_EFFORTS, ASSIST_MODES, MEMORY_CATEGORIES, normalizeAgent, PROJECT_COLORS } from "@/lib/assist";
export const AssistMessage = z.object({
text: z.string().trim().min(1).max(8000),
@@ -8,8 +8,13 @@ export const AssistMessage = z.object({
export const ModeChoice = z.object({
mode: z.enum(ASSIST_MODES.map((m) => m.id) as ["free", "smart", "manual"]),
- agent: z.enum(["claude", "ollama", "offline"]).optional(),
- model: z.string().max(100).nullish(),
+ // "ollama": the local agent's old name, from browsers that saved a choice before.
+ agent: z
+ .enum(["claude", "local", "ollama", "offline"])
+ .optional()
+ .transform((a) => normalizeAgent(a)),
+ // LM Studio ids can be long (publisher/model@quant).
+ model: z.string().max(200).nullish(),
effort: z.enum(ASSIST_EFFORTS.map((e) => e.id) as ["low", "medium", "high", "xhigh", "max"]).nullish(),
});
diff --git a/src/server/assist/studio-routes.ts b/src/server/assist/studio-routes.ts
index 26e960bc..08de2582 100644
--- a/src/server/assist/studio-routes.ts
+++ b/src/server/assist/studio-routes.ts
@@ -245,7 +245,7 @@ const ONE_SHOT_NAMES: Record<OneShotModel, string> = { "heygen-translate": "HeyG
/**
* Why the review flow's first stage (voice, transcript, translations) can't start as one pipeline, or
* null: a step no provider can run, or a demo step among real ones, which createPipeline refuses (a
- * fal key without Claude or Ollama: the translation would be a demo while the rest runs for real).
+ * fal key without Claude or a local model: the translation would be a demo while the rest runs for real).
*/
function prepareProblem(input: Pick<CreateDubInput, "engine" | "video" | "source" | "targets">): string | null {
const modes: { label: string; needs: string; demo: boolean }[] = [];
diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.ts
index 6f57ae0f..8aa829f8 100644
--- a/src/server/assist/tools.ts
+++ b/src/server/assist/tools.ts
@@ -10,7 +10,7 @@ import { createPipeline } from "../chains";
import { listElements } from "../elements";
import { createGenerations, getGeneration, listGenerations, outputKind, previewChained, previewGeneration } from "../generations";
import { provider } from "../providers";
-import { llmBackends } from "../providers/llm";
+import { llmBackends, llmLabel } from "../providers/llm";
import { engineMode } from "../settings";
import { readRef } from "../storage";
import { katanaTool } from "../katana";
@@ -39,7 +39,7 @@ function summarize(m: ModelDef) {
id: m.id,
name: m.name,
vendor: m.vendor,
- engine: m.engine === "open" ? (local ? "open source (Ollama, on this machine)" : "open source (ComfyUI)") : local ? "Claude (or Ollama when no key is set)" : "paid cloud API",
+ engine: m.engine === "open" ? (local ? `open source (${llmLabel({ endpoint: "ollama" })}, on this machine)` : "open source (ComfyUI)") : local ? `Claude (or ${llmLabel({ endpoint: "ollama" })} when no key is set)` : "paid cloud API",
about: m.tagline,
does: [...new Set(m.routes.map((r) => r.op))].map((op) => `${op} (${OPERATION_LABELS[op]})`),
price: m.engine === "open" ? (local ? "free (your machine)" : "free (your GPU)") : m.pricing ? `$${m.pricing.usd} per ${m.pricing.unit}${m.pricing.note ? ` — ${m.pricing.note}` : ""}` : "unknown",
diff --git a/src/server/brand.ts b/src/server/brand.ts
index dd530131..fa45729d 100644
--- a/src/server/brand.ts
+++ b/src/server/brand.ts
@@ -25,7 +25,7 @@ import { saveFile } from "./storage";
*
* Brand research: the site's HTML through the SSRF-safe fetch (remote-fetch.ts), then plain code
* reads what's machine-readable (OpenGraph, JSON-LD Organization/Product, Shopify /products.json,
- * CSS colour variables, font families, logo, hero images) and an LLM (llmText: Claude, else Ollama)
+ * CSS colour variables, font families, logo, hero images) and an LLM (llmText: Claude, else a local model)
* writes the soft fields (tagline, overview, tone, values, audience…). With no LLM, rule-based
* heuristics fill them, so a kit always comes back. Progress uses Higgsfield's 14 labels.
*/
@@ -741,6 +741,17 @@ export function mergeKit(base: BrandKitFields, facts: Partial<BrandKitFields>, h
};
}
+// The answers' JSON as JSON Schemas, for local models that decode to one (Ollama, LM Studio, Unsloth
+// Studio); the prompts ask for the same JSON, which Claude and any other model follow.
+const S = { type: "string" };
+const STRINGS = { type: "array", items: S };
+const objectOf = (properties: Record<string, unknown>) => ({ type: "object", properties, required: Object.keys(properties), additionalProperties: false });
+const PRODUCT_FACTS = { type: "array", items: objectOf({ name: S, audience: S, sellingPoints: STRINGS }) };
+const KIT_FIELDS = { name: S, tagline: S, overview: S, values: STRINGS, aesthetics: STRINGS, tone: STRINGS, audience: S, sellingPoints: STRINGS, competitors: STRINGS, language: S };
+const BRAND_SCHEMA = { name: "brand_kit", schema: objectOf({ ...KIT_FIELDS, products: PRODUCT_FACTS }) };
+const MANUAL_SCHEMA = { name: "brand_kit", schema: objectOf({ ...KIT_FIELDS, colors: STRINGS, fonts: objectOf({ heading: S, body: S }) }) };
+const PRODUCTS_SCHEMA = { name: "products", schema: objectOf({ products: PRODUCT_FACTS }) };
+
const BRAND_SYSTEM = `You are a brand strategist. You read a company's website and write its brand kit for an ad team.
Answer with ONE JSON object and nothing else:
{"name": string, "tagline": string (at most 12 words), "overview": string (2–3 sentences: what it sells, who it's for, what makes it different), "values": string[] (3–5), "aesthetics": string[] (3–5 short look-and-feel phrases, e.g. "Muted earth tones"), "tone": string[] (3–5 single words), "audience": string (one sentence), "sellingPoints": string[] (3–5 short reasons to buy), "competitors": string[] (2–4 brand names), "language": string (the site's language in English, e.g. "German"), "products": [{"name": string, "audience": string, "sellingPoints": string[] (up to 5)}] (only for the products listed, same names)}
@@ -1061,7 +1072,7 @@ async function research(id: string, signal: AbortSignal): Promise<void> {
if (found.length) products = found;
}
const heuristic = facts ? heuristicFields(facts, colors, fonts) : { name: brand.name, language: "English" };
- const llm = softFieldsFrom(parseJsonObject(await llmText(BRAND_SYSTEM, brandPrompt(facts, url, products))));
+ const llm = softFieldsFrom(parseJsonObject(await llmText(BRAND_SYSTEM, brandPrompt(facts, url, products), { json: BRAND_SCHEMA })));
if (signal.aborted) return;
step(11);
@@ -1123,7 +1134,7 @@ export function sellingPointsFrom(description: string | undefined): string[] {
export async function createManualBrand(input: { description: string; name?: string; images?: string[]; colors?: string[]; origin?: "assist" }): Promise<BrandKit> {
const description = input.description.trim();
if (!description && !input.images?.length) throw new Error("Add a description or upload images");
- const llm = description ? softFieldsFrom(parseJsonObject(await llmText(MANUAL_SYSTEM, `Business: ${description}`))) : {};
+ const llm = description ? softFieldsFrom(parseJsonObject(await llmText(MANUAL_SYSTEM, `Business: ${description}`, { json: MANUAL_SCHEMA }))) : {};
const heur = heuristicManualKit(description || input.name || "My brand");
const colors = (input.colors ?? []).filter(isHex);
const kit: StoredKit = {
@@ -1412,6 +1423,7 @@ export async function readProductLink(input: { url: string; brandId?: string | n
.slice(0, limit)
.map((p) => `${p.name}: ${(p.description ?? "").slice(0, 800)}`)
.join("\n"),
+ { json: PRODUCTS_SCHEMA },
),
),
);
diff --git a/src/server/chains.ts b/src/server/chains.ts
index 5560e45b..f87ef2e7 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -6,6 +6,7 @@ import type { ChainSlot, Engine, Generation, GenerationRequest, ModelDef, Operat
import { db } from "./db";
import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";
import { provider } from "./providers";
+import { llmLabel } from "./providers/llm";
/**
* Multi-step jobs built from chained generations: each step waits for the ones it needs and
@@ -23,8 +24,8 @@ interface ModeStep {
op: Operation;
}
-/** Who can run a model's operation, as Settings names them ("fal.ai", "Claude or Ollama"). */
-export const providerNames = (m: ModelDef, op: Operation) => [...new Set(routesFor(m, op).map((r) => (r.provider === "llm" ? "Claude or Ollama" : provider(r.provider).label)))].join(" or ");
+/** Who can run a model's operation, as Settings names them ("fal.ai", "Claude or LM Studio"). */
+export const providerNames = (m: ModelDef, op: Operation) => [...new Set(routesFor(m, op).map((r) => (r.provider === "llm" ? llmLabel(r) : provider(r.provider).label)))].join(" or ");
/**
* A chain must not mix paid and demo steps: a demo join of paid clips (or a paid step fed a demo
diff --git a/src/server/cinema-director.ts b/src/server/cinema-director.ts
index b223e435..947f91b2 100644
--- a/src/server/cinema-director.ts
+++ b/src/server/cinema-director.ts
@@ -25,7 +25,7 @@ import { llmText } from "./enhance";
/**
* The AI Director: turns an idea or a script into shots with Director settings, camera moves and
* prompts. It only proposes — every shot card has "Load into prompt bar" and nothing is generated
- * until the user presses Generate (Higgsfield's rule). Uses the configured LLM (Claude or Ollama)
+ * until the user presses Generate (Higgsfield's rule). Uses the configured LLM (Claude or a local model)
* and falls back to an offline breakdown so it always answers.
*/
@@ -53,6 +53,51 @@ Rules:
- Put shared look decisions (genre, era, camera, palette, lighting) in every shot's settings so each shot can be loaded on its own.
- Follow the project brief. No shots when the user only asks a question; then just reply.`;
+/** The answer's JSON as a JSON Schema, for local models that decode to one: settings left out stay Auto. */
+const oneOf = (values: string[]) => ({ type: "string", enum: values });
+const ANSWER_SCHEMA = {
+ name: "director",
+ schema: {
+ type: "object",
+ properties: {
+ reply: { type: "string" },
+ shots: {
+ type: "array",
+ maxItems: 12,
+ items: {
+ type: "object",
+ properties: {
+ title: { type: "string" },
+ prompt: { type: "string" },
+ duration: { type: "integer" },
+ moves: { type: "array", maxItems: 3, items: oneOf(CAMERA_MOVES.map((m) => m.slug)) },
+ settings: {
+ type: "object",
+ properties: {
+ genre: oneOf(slugs(GENRES)),
+ era: oneOf(slugs(ERAS)),
+ tempo: oneOf(slugs(TEMPOS)),
+ camera: oneOf(slugs(CAMERA_BODIES)),
+ lens: oneOf(slugs(LENSES)),
+ focal: oneOf(slugs(FOCAL_LENGTHS)),
+ aperture: oneOf(slugs(APERTURES)),
+ lighting: oneOf(slugs(LIGHTING_PRESETS)),
+ palette: oneOf(PALETTES.map((p) => p.slug)),
+ },
+ additionalProperties: false,
+ },
+ },
+ required: ["title", "prompt", "duration", "moves", "settings"],
+ additionalProperties: false,
+ },
+ },
+ brief: { type: "string" },
+ },
+ required: ["reply", "shots"],
+ additionalProperties: false,
+ },
+};
+
const Shot = z.object({
title: z.string().max(120).catch("Shot"),
prompt: z.string().min(1).max(2000),
@@ -314,7 +359,7 @@ export async function askDirector(projectId: string, text: string): Promise<Dire
]
.filter(Boolean)
.join("\n\n");
- const raw = (await llmText(SYSTEM, context).catch(() => null))?.trim() || null;
+ const raw = (await llmText(SYSTEM, context, { json: ANSWER_SCHEMA }).catch(() => null))?.trim() || null;
const parsed = raw ? parseDirectorAnswer(raw) : null;
const answer =
parsed && (parsed.reply || parsed.shots.length || parsed.brief)
diff --git a/src/server/enhance.ts b/src/server/enhance.ts
index 838cd29a..77852139 100644
--- a/src/server/enhance.ts
+++ b/src/server/enhance.ts
@@ -1,11 +1,12 @@
import "server-only";
import Anthropic from "@anthropic-ai/sdk";
import type { MediaKind, Operation } from "@/lib/catalog/types";
+import { activeLocal, aiHelper, chatLocal, type JsonSpec } from "./llm";
import { engineMode, getSetting } from "./settings";
/**
* "Enhance prompt": rewrite a short idea into a rich, model-friendly prompt.
- * Order: Claude (if an Anthropic key is set) → local Ollama (open-source mode) → offline heuristic.
+ * Order: Claude (if an Anthropic key is set) → a local model (Ollama, LM Studio, Unsloth Studio…) → offline heuristic.
*/
const SYSTEM = `You rewrite short creative ideas into prompts for image and video generation models.
@@ -48,37 +49,39 @@ async function viaClaude(system: string, user: string): Promise<string | null> {
return text || null;
}
-async function viaOllama(system: string, user: string): Promise<string | null> {
- const res = await fetch(`${getSetting("ollamaUrl").replace(/\/+$/, "")}/api/chat`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- model: getSetting("ollamaModel"),
- stream: false,
- think: false,
- messages: [
- { role: "system", content: system },
- { role: "user", content: user },
- ],
- }),
- signal: AbortSignal.timeout(60_000),
+export interface LlmTextOptions {
+ /** The JSON Schema the answer follows on a local model (Claude follows the prompt); see JsonSpec. */
+ json?: JsonSpec;
+ /** How long to wait (default: 60 s, or 3 minutes when the local model isn't loaded yet). */
+ timeoutMs?: number;
+}
+
+/** The local model in use, thinking off where the server allows it. */
+async function viaLocal(system: string, user: string, opts: LlmTextOptions): Promise<string | null> {
+ const ready = await activeLocal();
+ if (!ready) return null;
+ const r = await chatLocal(ready, {
+ messages: [
+ { role: "system", content: system },
+ { role: "user", content: user },
+ ],
+ think: false,
+ json: opts.json,
+ timeoutMs: opts.timeoutMs ?? (ready.status.loaded === false ? 180_000 : 60_000),
});
- if (!res.ok) throw new Error(`ollama ${res.status}`);
- const j = (await res.json()) as { message?: { content?: string } };
- return j.message?.content?.replace(/<think>[\s\S]*?<\/think>/g, "").trim() || null;
+ return r.text || null;
}
/**
* One-shot text from whichever LLM this install allows: Claude (when a key is set, and never
- * on "open source only" installs unless picked explicitly), else a local Ollama. Null when none.
+ * on "open source only" installs unless picked explicitly), else a local model. Null when none.
*/
-export async function llmText(system: string, user: string): Promise<string | null> {
- const choice = getSetting("enhanceProvider");
+export async function llmText(system: string, user: string, opts: LlmTextOptions = {}): Promise<string | null> {
+ const choice = aiHelper();
if (choice === "none") return null;
const useClaude = choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"));
if (useClaude) return viaClaude(system, user).catch(() => null);
- if (choice === "ollama" || choice === "auto") return viaOllama(system, user).catch(() => null);
- return null;
+ return viaLocal(system, user, opts).catch(() => null);
}
/** Deterministic fallback so the toggle always does something useful offline. */
diff --git a/src/server/faceless.ts b/src/server/faceless.ts
index 32ed583f..8a634fff 100644
--- a/src/server/faceless.ts
+++ b/src/server/faceless.ts
@@ -34,15 +34,18 @@ import {
sceneSpans,
sceneTiming,
scriptBrief,
+ scriptSchema,
scriptSystem,
splitScript,
spokenTimes,
styleRefLimit,
TIMING_PARTS,
topicsBrief,
+ topicsSchema,
topicsSystem,
totalSeconds,
visualsBrief,
+ visualsSchema,
visualsSystem,
withTiming,
wordsFor,
@@ -79,7 +82,8 @@ import { db } from "./db";
import { listElements } from "./elements";
import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";
import { provider } from "./providers";
-import { llmBackends, probeOllama } from "./providers/llm";
+import type { JsonSpec } from "./llm";
+import { llmBackends, probeLocal } from "./providers/llm";
import { fetchRemote } from "./remote-fetch";
import { engineMode, getSetting } from "./settings";
import { fileUrl, saveFile } from "./storage";
@@ -190,7 +194,7 @@ function mustEpisode(id: string): FacelessEpisode {
}
// ---------------------------------------------------------------------------
-// The LLM (the install's own: Claude or Ollama for the cloud engine, Ollama only for the open one)
+// The LLM (the install's own: Claude or a local model for the cloud engine, a local model only for the open one)
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
@@ -201,6 +205,8 @@ export interface AskOptions {
signal?: AbortSignal;
/** How long to wait for the answer (default 8 minutes: a script on a slow local model). */
timeoutMs?: number;
+ /** The JSON Schema the answer follows on a local model that supports it (the prompt asks for the same JSON). */
+ json?: JsonSpec;
}
/** Channel names and topic suggestions are waited for: a slow model gives way to the offline wording. */
@@ -213,11 +219,11 @@ export async function askLlm(engine: Engine, system: string, user: string, o: As
const model = getModel(ENGINE_MODELS[engine].write);
const route = model?.routes.find((r) => r.op === "write");
if (!model || !route) return null;
- await probeOllama();
+ await probeLocal();
if (!llmBackends(route).length) return null;
const llm = provider("llm");
try {
- const { externalId } = await llm.submit({ generationId: `faceless_${nanoid(6)}`, model, route, input: { prompt: user, extra: { system } } });
+ const { externalId } = await llm.submit({ generationId: `faceless_${nanoid(6)}`, model, route, input: { prompt: user, extra: { system, ...(o.json && { json: o.json }) } } });
const ctx = { externalId, meta: {}, route, model, createdAt: Date.now() };
const deadline = Date.now() + (o.timeoutMs ?? 8 * 60_000);
while (Date.now() < deadline) {
@@ -416,7 +422,7 @@ export function makeAvatar(id: string): Generation {
export async function suggestTopics(input: { idea: string; genre: FacelessGenre; engine: Engine; avoid?: string[]; count?: number; round?: number; reference?: string }): Promise<{ topics: TopicIdea[]; offline: boolean }> {
const count = Math.max(4, Math.min(6, input.count ?? 5));
const genre = genreInfo(input.genre);
- const answer = await askLlm(input.engine, topicsSystem, topicsBrief({ idea: input.idea, genre, count, avoid: input.avoid, reference: input.reference }), { timeoutMs: TOPICS_TIMEOUT_MS });
+ const answer = await askLlm(input.engine, topicsSystem, topicsBrief({ idea: input.idea, genre, count, avoid: input.avoid, reference: input.reference }), { timeoutMs: TOPICS_TIMEOUT_MS, json: topicsSchema(count) });
const topics = answer ? parseTopics(answer).slice(0, count) : [];
if (topics.length >= 3) return { topics, offline: false };
return { topics: offlineTopics(input.idea, genre.id, count, input.round ?? 0, input.avoid), offline: true };
@@ -562,12 +568,12 @@ async function writeScript(id: string, pasted: string, signal: AbortSignal): Pro
let script: EpisodeScript;
if (pasted) {
const blocks = splitScript(pasted);
- const answer = await askLlm(s.engine, visualsSystem, visualsBrief(blocks, style.name, ep.topic || pasted.slice(0, 200)), ask);
+ const answer = await askLlm(s.engine, visualsSystem, visualsBrief(blocks, style.name, ep.topic || pasted.slice(0, 200)), { ...ask, json: visualsSchema(blocks.length) });
const visuals = answer ? parseVisuals(answer, blocks.length) : null;
script = {
source: "pasted",
blocks: visuals ? blocks.map((b, i) => ({ ...b, visual: visuals[i].visual, motion: visuals[i].motion || b.motion })) : blocks,
- ...(!visuals && { offline: true, note: failure ? `Pictures planned offline (${failure}).` : "Pictures planned from your words — connect Claude or Ollama in Settings for better scenes." }),
+ ...(!visuals && { offline: true, note: failure ? `Pictures planned offline (${failure}).` : "Pictures planned from your words — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for better scenes." }),
};
} else {
const topic = ep.topic || textSources[0]?.slice(0, 300) || "this topic";
@@ -583,7 +589,7 @@ async function writeScript(id: string, pasted: string, signal: AbortSignal): Pro
sources: textSources,
auto,
});
- const answer = await askLlm(s.engine, scriptSystem, brief, ask);
+ const answer = await askLlm(s.engine, scriptSystem, brief, { ...ask, json: scriptSchema(auto ? null : scenes) });
const parsed = answer ? parseScript(answer) : null;
if (parsed?.blocks.length) {
script = { source: "ai", title: parsed.title ?? undefined, blocks: parsed.blocks };
diff --git a/src/server/generations.ts b/src/server/generations.ts
index aeb4fd54..1f6673f4 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -29,8 +29,9 @@ import { enhancePrompt } from "./enhance";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider } from "./providers";
import { probeComfy } from "./providers/comfyui";
-import { llmBackends, llmMissing, llmUsesClaude, probeOllama } from "./providers/llm";
+import { llmBackends, llmLabel, llmMissing, llmUsesClaude, probeLocal } from "./providers/llm";
import type { PollContext, PollResult, RemoteOutput } from "./providers/types";
+import { modelToFinish, startModelFinish, startTurntable, stopModelFinish, type OutputStore } from "./model3d-finish";
import { convertMask } from "./png";
import { engineMode, getSetting } from "./settings";
import { contentTypeFor, deleteAsset, readRef, saveFile } from "./storage";
@@ -336,6 +337,8 @@ export function assetInUse(assetId: string, exceptGeneration = ""): boolean {
* src/server/library.ts (they cancel running jobs first); moving to the Trash is trashGenerations.
*/
export function deleteGeneration(id: string): void {
+ // A 3D job's finish or turntable render stops with it.
+ stopModelFinish(id);
const assets = db().prepare("SELECT id FROM assets WHERE generation_id = ?").all(id) as { id: string }[];
db().transaction(() => {
db().prepare("DELETE FROM generations WHERE id = ?").run(id);
@@ -422,7 +425,7 @@ function prepare(original: GenerationRequest) {
plan = { ...plan, jobs: plan.jobs * plan.perJobOutputs, perJobOutputs: 1, params: { ...plan.params, numOutputs: 1 } };
}
const providerId: ProviderId = demo ? "mock" : route.provider;
- // A text step that runs on Ollama is free; only Claude costs money.
+ // A text step that runs on a local model is free; only Claude costs money.
const free = demo || (route.provider === "llm" && !llmUsesClaude(route));
return { req, plan, route, demo, providerId, cost: free ? 0 : estimateCost(plan.model, plan.params, 1) };
}
@@ -620,7 +623,7 @@ const submitting = (): Set<string> => (globalThis.__fuobeSubmitting ??= new Set<
function chainMode(p: { demo: boolean; plan: { model: { name: string } }; route: ModelRoute }, deps: Pick<Row, "provider">[]): { error?: string; forceDemo?: boolean } {
const demoDeps = deps.filter((d) => d.provider === "mock").length;
if (p.demo && demoDeps < deps.length) {
- const needs = p.route.provider === "llm" ? "Claude or Ollama" : provider(p.route.provider).label;
+ const needs = p.route.provider === "llm" ? llmLabel(p.route) : provider(p.route.provider).label;
return { error: `${p.plan.model.name} needs ${needs} to continue what the earlier steps made for real — connect it in Settings, then retry` };
}
if (!p.demo && demoDeps > 0) {
@@ -660,7 +663,7 @@ async function advanceDependents(): Promise<void> {
// Routing reads cached reachability: make sure it's fresh for local engines.
const model = getModel(request.modelId);
if (model?.routes.some((x) => x.provider === "comfyui")) await probeComfy();
- if (model?.routes.some((x) => x.provider === "llm")) await probeOllama();
+ if (model?.routes.some((x) => x.provider === "llm")) await probeLocal();
const original = withChainInputs(request, values as string[]);
const prepared = prepare(original);
const mode = chainMode(prepared, deps as Pick<Row, "provider">[]);
@@ -827,8 +830,9 @@ export function ensureRunner(): void {
state.fastTimer?.unref?.();
globalThis.__fuobeRunner = state;
void probeComfy().catch(() => false);
- void probeOllama().catch(() => false);
+ void probeLocal().catch(() => false);
sweepInterrupted();
+ resumeTurntables();
}
/** Jobs that never got an external id (the server died mid-submit) can't be recovered. Runs every tick. */
@@ -919,6 +923,8 @@ async function pollOne(r: Row): Promise<void> {
run = { submitted_at: now, started_at: null };
}
const ctx = pollContext(r, model);
+ // Its outputs are saved and the 3D finish runs (or ran until a restart): nothing more to ask the provider.
+ if (ctx.meta.finishing) return resumeFinish(r);
// Poll first: a job that finished while the server was asleep or down is collected, not timed out.
let res: PollResult | undefined;
let pollError: unknown;
@@ -964,6 +970,14 @@ async function pollOne(r: Row): Promise<void> {
console.warn(`[fuobe] could not save output for ${r.id}: ${(e as Error).message}`);
}
}
+ // An image-to-3D GLB from ComfyUI gets the server's finish first (the web GLB, seconds): the outputs are
+ // stored now and the row stays running until it's done, so a restart resumes it from them. The turntable
+ // is rendered after the job has succeeded (src/server/model3d-finish.ts).
+ if (modelToFinish(r, outputs) >= 0) {
+ update(r.id, { outputs_json: JSON.stringify(outputs), external_meta_json: JSON.stringify({ ...ctx.meta, finishing: true }), message: "Finishing the 3D model" });
+ resumeFinish({ ...r, outputs_json: JSON.stringify(outputs) });
+ return;
+ }
update(r.id, {
status: "succeeded",
outputs_json: JSON.stringify(outputs),
@@ -973,6 +987,47 @@ async function pollOne(r: Row): Promise<void> {
});
}
+/** Start (or keep running) the 3D finish of a job whose outputs are stored; it marks the job done when it ends. */
+function resumeFinish(r: Row): void {
+ const outputs = JSON.parse(r.outputs_json || "[]") as OutputFile[];
+ startModelFinish(r.id, outputs, {
+ op: r.op,
+ provider: r.provider,
+ onMessage: (message) => update(r.id, { message }),
+ done: (finished) => {
+ const now = db().prepare("SELECT status, external_meta_json FROM generations WHERE id = ?").get(r.id) as Pick<Row, "status" | "external_meta_json"> | undefined;
+ // Canceled or deleted meanwhile: leave it be.
+ if (!now || now.status !== "running") return;
+ const meta = JSON.parse(now.external_meta_json ?? "{}") as Record<string, unknown>;
+ delete meta.finishing;
+ update(r.id, { status: "succeeded", outputs_json: JSON.stringify(finished), external_meta_json: JSON.stringify(meta), progress: 1, message: null, completed_at: Date.now() });
+ // The model can be opened and downloaded now; its turntable is rendered after and added to the result.
+ startTurntable(r.id, outputStore(r.id));
+ },
+ });
+}
+
+/** A finished job's outputs, for the turntable render that adds to them later. */
+function outputStore(id: string): OutputStore {
+ return {
+ read: () => {
+ const row = db().prepare("SELECT outputs_json FROM generations WHERE id = ?").get(id) as Pick<Row, "outputs_json"> | undefined;
+ return row ? (JSON.parse(row.outputs_json || "[]") as OutputFile[]) : null;
+ },
+ write: (outputs) => update(id, { outputs_json: JSON.stringify(outputs) }),
+ };
+}
+
+/** Turntables the server stopped before rendering (meta.finish.turntable queued or rendering): render them now. */
+function resumeTurntables(): void {
+ const rows = db()
+ .prepare(
+ `SELECT id FROM generations WHERE status = 'succeeded' AND op = 'image-to-3d' AND provider = 'comfyui' AND (outputs_json LIKE '%"turntable":"queued"%' OR outputs_json LIKE '%"turntable":"rendering"%') ORDER BY created_at ASC`,
+ )
+ .all() as Pick<Row, "id">[];
+ for (const r of rows) startTurntable(r.id, outputStore(r.id));
+}
+
/** Outputs may carry text (transcripts, translations, scripts) and structured extras (layer boxes, cues, stems). */
type RichOutput = RemoteOutput & { text?: string; meta?: Record<string, unknown> };
@@ -1025,6 +1080,13 @@ async function persistOutput(o: RichOutput, generationId: string): Promise<Outpu
export async function cancelGeneration(id: string): Promise<void> {
const r = db().prepare("SELECT * FROM generations WHERE id = ?").get(id) as Row | undefined;
if (!r || (r.status !== "queued" && r.status !== "running")) return;
+ // Its outputs are in and the 3D finish runs: the provider's job is over. Stop the finish before anything
+ // awaits, so it can't mark the job done in between.
+ if ((JSON.parse(r.external_meta_json ?? "{}") as Record<string, unknown>).finishing) {
+ stopModelFinish(id);
+ update(id, { status: "canceled", completed_at: Date.now(), message: null });
+ return;
+ }
const model = getModel(r.model_id);
// Without an external id the job is still being handed over: submit() cancels it as soon as it lands.
if (r.external_id && model) {
@@ -1032,6 +1094,7 @@ export async function cancelGeneration(id: string): Promise<void> {
.cancel?.(pollContext(r, model))
.catch(() => {});
}
+ stopModelFinish(id);
update(id, { status: "canceled", completed_at: Date.now(), message: null });
}
diff --git a/src/server/llm/errors.ts b/src/server/llm/errors.ts
new file mode 100644
index 00000000..16b58faa
--- /dev/null
+++ b/src/server/llm/errors.ts
@@ -0,0 +1,117 @@
+import "server-only";
+import { cap, llmContext } from "./servers";
+import type { ChatResult, LocalKind, LocalServer } from "./types";
+
+/*
+ * What went wrong with a local server, in words that say how to fix it: start the server, add a key,
+ * load or download a model, or give it more context.
+ */
+
+/** How to get each server answering. */
+export const START_HINT: Record<LocalKind, string> = {
+ ollama: "Start it with `ollama serve` (or open the Ollama app).",
+ lmstudio: "Start LM Studio's local server and load a model: in LM Studio, Developer → Start server (or run `lms server start`).",
+ unsloth: "Start Unsloth Studio (the desktop app, or `unsloth studio -p 8888`) and load a model on its Chat page.",
+ custom: "Start it, or check its URL in Settings → AI helper.",
+};
+
+/** Why a fetch failed: ECONNREFUSED, ENOTFOUND… */
+function reason(e: unknown): string {
+ const err = e as { message?: string; cause?: { code?: string; message?: string } } | undefined;
+ return err?.cause?.code || err?.cause?.message || err?.message || "no answer";
+}
+
+export function unreachableError(s: LocalServer, e: unknown): Error {
+ if ((e as Error | undefined)?.name === "TimeoutError") return new Error(`${cap(s.label)} took too long to answer. Try again, or pick a smaller model.`);
+ return new Error(`Couldn't reach ${s.label} at ${s.url || "(no URL set)"} (${reason(e)}). ${START_HINT[s.kind]}`);
+}
+
+/**
+ * The message inside an error body: OpenAI's {error: {message}}, {error: "…"}, FastAPI's {detail: "…"}
+ * or {detail: {error: {message}}} (Unsloth Studio's context and pass-through errors), or the text.
+ */
+export function errorDetail(body: string): string {
+ const text = (v: unknown): string | null => (typeof v === "string" && v ? v : null);
+ type Err = { error?: string | { message?: unknown }; message?: unknown };
+ const of = (j: Err | undefined): string | null => {
+ const e = j?.error;
+ return text(e) ?? (e && typeof e === "object" ? text(e.message) : null) ?? text(j?.message);
+ };
+ try {
+ const j = JSON.parse(body) as Err & { detail?: unknown };
+ const d = j?.detail;
+ const msg = of(j) ?? text(d) ?? (d && typeof d === "object" ? of(d as Err) : null);
+ if (msg) return msg.replace(/\s+/g, " ").trim().slice(0, 300);
+ } catch {}
+ return body.replace(/\s+/g, " ").trim().slice(0, 200);
+}
+
+/** A server that can't do structured output says so; the call is then made again without it. */
+export const rejectsJson = (kind: LocalKind, status: number, body: string) =>
+ status >= 400 && (/response_format|json_schema|json_object|grammar|structured output/i.test(body) || (kind === "ollama" && status === 400 && /\bformat\b/i.test(body)));
+
+export function keyMessage(s: LocalServer): string {
+ if (s.kind === "lmstudio") {
+ return s.key
+ ? "LM Studio rejected the API token. Check it in Settings → AI helper (LM Studio makes them under Developer → Server Settings → Manage Tokens)."
+ : "LM Studio wants an API token (its Require Authentication setting is on): in LM Studio, Developer → Server Settings → Manage Tokens, then paste the token in Settings → AI helper.";
+ }
+ if (s.kind === "unsloth") {
+ return s.key
+ ? "Unsloth Studio rejected the API key. Create a new one in Unsloth Studio (avatar → Settings → API) and paste it in Settings → AI helper."
+ : "Unsloth Studio needs an API key: in Unsloth Studio, avatar → Settings → API → Create, then paste the sk-unsloth-… key in Settings → AI helper.";
+ }
+ return s.key ? `${cap(s.label)} rejected the API key. Check it in Settings → AI helper.` : `${cap(s.label)} wants an API key. Add it in Settings → AI helper.`;
+}
+
+const CONTEXT = /context_length_exceeded|context (?:length|window|size)|n_ctx|tokens to keep|context the overflows|exceeds? (?:the )?(?:context|maximum)|maximum context|prompt is too long|too many tokens/i;
+const NOT_LOADED = /no models? (?:is |are )?loaded|not loaded|no model is running/i;
+const NO_MODEL = /model[^.]{0,80}(?:not found|does not exist|doesn't exist|unknown|no such|invalid)|unknown model|model_not_found|no such model/i;
+const LOAD_FAILED = /failed to load|out of memory|insufficient (?:memory|vram)|not enough (?:memory|vram)|cuda error/i;
+
+function contextMessage(s: LocalServer, model: string | null, detail: string): string {
+ const n = /(?:context length of (?:only )?|n_ctx(?:_slot)?\s*[=:]?\s*)(\d[\d,]*)/i.exec(detail)?.[1];
+ const who = model ? `${model}'s context` : "the model's context";
+ const fix: Record<LocalKind, string> = {
+ ollama: "Raise the context in Settings → AI helper (FUOBE_LLM_CONTEXT)",
+ lmstudio: `Reload it with ${Math.round((llmContext() || 16384) / 1024)}k context (Settings → AI helper) or a larger one in LM Studio`,
+ unsloth: "Load it in Unsloth Studio with a larger context",
+ custom: "Start the server with a larger context",
+ };
+ return `This is longer than ${who}${n ? ` (${n} tokens)` : ""} on ${s.label}. ${fix[s.kind]}, or use shorter text.`;
+}
+
+function modelMessage(s: LocalServer, model: string | null, detail: string): string {
+ const m = model ?? "that model";
+ if (s.kind === "ollama") return `Ollama doesn't have ${m} yet — run \`ollama pull ${m}\``;
+ if (s.kind === "unsloth") {
+ return NOT_LOADED.test(detail) || !model
+ ? "Unsloth Studio has no model loaded — load one on its Chat page (Select model), or turn on Model auto-switch (avatar → Settings → API) so the model picked in Fuobe loads by itself."
+ : `Unsloth Studio has no model called ${m} — pick one it lists in Settings → AI helper, or leave the model empty to use the one loaded in Unsloth.`;
+ }
+ if (s.kind === "lmstudio") {
+ return NOT_LOADED.test(detail) && !NO_MODEL.test(detail)
+ ? `LM Studio has no model loaded — load one in LM Studio (or run \`lms load ${model ?? "<model>"}\`), or pick one in Settings → AI helper.`
+ : `LM Studio has no model called ${m} — download it in LM Studio (or run \`lms get ${m}\`), or pick another in Settings → AI helper.`;
+ }
+ return `${cap(s.label)} has no model called ${m} — pick one it lists in Settings → AI helper.`;
+}
+
+/** A non-2xx answer from a chat call. */
+export function httpError(s: LocalServer, status: number, body: string, model: string | null): Error {
+ const detail = errorDetail(body);
+ if (status === 401 || status === 403) return new Error(keyMessage(s));
+ // The OpenAI code may be all that says so: {error: {message: "…", code: "context_length_exceeded"}}.
+ if (CONTEXT.test(detail) || /"context_length_exceeded"/.test(body)) return new Error(contextMessage(s, model, detail));
+ if (LOAD_FAILED.test(detail)) return new Error(`${cap(s.label)} couldn't load ${model ?? "the model"}: ${detail}. Free some GPU memory (ComfyUI shares it) or pick a smaller model.`);
+ if (NOT_LOADED.test(detail) || NO_MODEL.test(detail) || (status === 404 && s.kind === "ollama")) return new Error(modelMessage(s, model, detail));
+ if (status === 404) return new Error(`${cap(s.label)} has no chat endpoint at ${s.url} (404${detail ? `: ${detail}` : ""}). Check its URL in Settings → AI helper.`);
+ return new Error(`${cap(s.label)} returned ${status}: ${detail}`);
+}
+
+/** A reply with no words in it. */
+export function emptyReply(s: LocalServer, r: ChatResult): Error {
+ if (r.stop === "length" && r.thought) return new Error(`${r.model} on ${s.label} spent its whole reply thinking. Turn thinking off for it, or pick a model that doesn't think first.`);
+ if (r.stop === "length") return new Error(`${r.model} on ${s.label} ran out of room before it answered. Give it more context, or use shorter text.`);
+ return new Error(`${cap(s.label)} returned no text`);
+}
diff --git a/src/server/llm/index.ts b/src/server/llm/index.ts
new file mode 100644
index 00000000..5198bb42
--- /dev/null
+++ b/src/server/llm/index.ts
@@ -0,0 +1,268 @@
+import "server-only";
+import { errorDetail, httpError, keyMessage, rejectsJson, unreachableError } from "./errors";
+import { healToolCalls } from "./messages";
+import { cached, forget, refresh, refreshSync, statusOf, tokens } from "./probe";
+import { allLocalServers, authHeaders, cap, LOCAL_LABELS, llmContext, localServer, localServers, openaiBase, pinnedKind } from "./servers";
+import type { ChatRequest, ChatResult, LocalKind, LocalServer, LocalStatus } from "./types";
+import { ollamaBody, openaiBody, parseOllama, parseOpenai } from "./wire";
+
+export { aiHelper, cap, llmContext, localServer, localServers, LOCAL_LABELS, pinnedKind } from "./servers";
+export { emptyReply } from "./errors";
+export { toChatMessages } from "./messages";
+export type * from "./types";
+
+/** A server that can take calls now, with what its probe found. */
+export interface Ready {
+ server: LocalServer;
+ status: LocalStatus;
+}
+
+/**
+ * The first server that can take calls. With more than one, a server that has the model comes first:
+ * Ollama answers (so counts as ready) even with nothing pulled, and mustn't take every call from an
+ * LM Studio that has a model.
+ */
+const pick = (servers: LocalServer[]): Ready | null => {
+ const need = llmContext();
+ const ready = servers.flatMap((server) => {
+ const status = statusOf(server, need);
+ return status && !status.problem ? [{ server, status }] : [];
+ });
+ return ready.find((r) => r.server.kind !== "ollama" || r.status.warning == null) ?? ready[0] ?? null;
+};
+
+/** Ask the local servers (answers kept 15 s; `force` asks now). True when one can take calls. */
+export async function probeLocal(force = false): Promise<boolean> {
+ const servers = localServers();
+ await refresh(servers, force);
+ return !!pick(servers);
+}
+
+/** The server a call goes to now: the first ready one in Settings' order (asks first when the answers are old). */
+export async function activeLocal(force = false): Promise<Ready | null> {
+ await probeLocal(force);
+ return pick(localServers());
+}
+
+/**
+ * The same, synchronously, for routing. The first look at a server waits for a real answer (a step
+ * posted right after boot must not fall back to demo text while the server is up); later looks use
+ * the cached one and refresh it in the background.
+ */
+export function localReady(): Ready | null {
+ const servers = localServers();
+ const unknown = servers.filter((s) => !cached(s));
+ if (unknown.length) refreshSync(unknown);
+ if (servers.some((s) => cached(s)?.stale)) void refresh(servers).catch(() => {});
+ return pick(servers);
+}
+
+/** What the local model is called in messages: the pinned server, the one in use, or "a local model". Never waits. */
+export function localLabel(): string {
+ const pinned = pinnedKind();
+ return pinned ? LOCAL_LABELS[pinned] : (pick(localServers())?.server.label ?? "a local model");
+}
+
+/** What to connect, in a sentence: the pinned server, or any of the three. */
+export const localWhat = (): string => {
+ const pinned = pinnedKind();
+ return pinned ? LOCAL_LABELS[pinned] : "a local model (Ollama, LM Studio or Unsloth Studio)";
+};
+
+/**
+ * Why no local model can run, when a server says (it needs a key, has no model loaded): the pinned
+ * server's reason, or in Automatic the first server that answers but can't run. Null otherwise.
+ */
+export function localProblem(): string | null {
+ const need = llmContext();
+ const pinned = pinnedKind();
+ for (const s of localServers()) {
+ const st = statusOf(s, need);
+ if (st?.problem && (st.up || pinned)) return st.problem;
+ }
+ return null;
+}
+
+/** Every server's status for Settings (all four, whatever is pinned). */
+export async function localStatuses(force = false): Promise<LocalStatus[]> {
+ const servers = allLocalServers();
+ await refresh(servers, force);
+ const need = llmContext();
+ return servers.map((s) => statusOf(s, need)!);
+}
+
+// ---------------------------------------------------------------------------
+// LM Studio: loading a model with the context Fuobe needs
+
+declare global {
+ var __fuobeLmLoads: Map<string, Promise<{ model: string; context: number | null; seconds: number | null }>> | undefined;
+}
+const loads = () => (globalThis.__fuobeLmLoads ??= new Map());
+
+/** POST /api/v1/models/load; concurrent calls for one model share the load. */
+function loadLmStudio(s: LocalServer, model: string, context: number) {
+ const key = `${s.url}|${model}`;
+ let p = loads().get(key);
+ if (!p) {
+ p = (async () => {
+ const res = await fetch(`${s.url}/api/v1/models/load`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...authHeaders(s) },
+ body: JSON.stringify({ model, context_length: context, echo_load_config: true }),
+ signal: AbortSignal.timeout(300_000),
+ }).catch((e: unknown) => {
+ throw unreachableError(s, e);
+ });
+ if (res.status === 401 || res.status === 403) throw new Error(keyMessage(s));
+ if (!res.ok) throw new Error(`LM Studio couldn't load ${model} with ${tokens(context)} tokens of context: ${errorDetail(await res.text())}. Free some GPU memory (ComfyUI shares it), pick a smaller model, or lower the context in Settings → AI helper.`);
+ const j = (await res.json().catch(() => ({}))) as { load_time_seconds?: number; load_config?: { context_length?: number } };
+ // The next status shows it loaded, so it isn't loaded twice.
+ await refresh([s], true);
+ return { model, context: j.load_config?.context_length ?? context, seconds: j.load_time_seconds ?? null };
+ })().finally(() => loads().delete(key));
+ loads().set(key, p);
+ }
+ return p;
+}
+
+/**
+ * LM Studio's chat endpoint can't set the context, and loading a model on demand (JIT) uses the
+ * app's default (often 4k–8k: too small for Assist's tools). So a model that isn't loaded yet is
+ * loaded first with the context from Settings. A model the user loaded is left as it is.
+ */
+async function prepareLmStudio(s: LocalServer, status: LocalStatus, model: string): Promise<void> {
+ const need = llmContext();
+ // The latest answers, not the caller's snapshot: a job that started before its first call loaded
+ // the model must not load it again for every later call.
+ const now = statusOf(s, need) ?? status;
+ if (!now.native || !need) return;
+ const m = now.models.find((x) => x.id === model) ?? now.models.find((x) => model.startsWith(`${x.id}@`));
+ if (!m || m.loaded) return;
+ await loadLmStudio(s, model, Math.min(need, m.maxContext || need));
+}
+
+/** Settings → "Reload with 16k context": unloads LM Studio's copies of the model, then loads it with the context from Settings. */
+export async function reloadLmStudio(model?: string | null): Promise<{ model: string; context: number | null; seconds: number | null }> {
+ const s = localServer("lmstudio");
+ await refresh([s], true);
+ const status = statusOf(s, llmContext());
+ if (!status?.up) throw new Error(status?.problem ?? "LM Studio isn't running");
+ if (!status.native) throw new Error("Loading a model from Fuobe needs LM Studio 0.4 or later. Load it in LM Studio with a larger context instead.");
+ const want = model || status.model;
+ const m = status.models.find((x) => x.id === want);
+ if (!want || !m) throw new Error(`LM Studio has no model called ${want ?? "that"}`);
+ for (const id of m.instances ?? []) {
+ await fetch(`${s.url}/api/v1/models/unload`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...authHeaders(s) },
+ body: JSON.stringify({ instance_id: id }),
+ signal: AbortSignal.timeout(60_000),
+ }).catch(() => null);
+ }
+ const need = llmContext() || 16384;
+ return loadLmStudio(s, want, Math.min(need, m.maxContext || need));
+}
+
+// ---------------------------------------------------------------------------
+// One call
+
+/**
+ * The model a call names: the request's, Settings', or the one the probe picked. Unsloth: none, so
+ * its loaded model answers. LM Studio: the probe's, which is the model's key when Settings names it
+ * by its display name.
+ */
+function modelFor(r: Ready, req: ChatRequest): string | null {
+ if (req.model) return req.model;
+ if (r.server.kind === "unsloth") return r.server.model || null;
+ if (r.server.kind === "lmstudio") return r.status.model || r.server.model || null;
+ return r.server.model || r.status.model;
+}
+
+/**
+ * One chat call to a local server (not streamed). With `json`, a server that rejects structured
+ * output is asked again without it (the prompts ask for JSON too). With `tools`, calls the model
+ * wrote as text are read back. Throws messages that say how to fix the server; a reply with no
+ * text is returned as it is (see emptyReply).
+ */
+export async function chatLocal(r: Ready, req: ChatRequest): Promise<ChatResult> {
+ const s = r.server;
+ const model = modelFor(r, req);
+ if (s.kind === "lmstudio" && model) await prepareLmStudio(s, r.status, model);
+ const signal = req.signal ? AbortSignal.any([req.signal, AbortSignal.timeout(req.timeoutMs)]) : AbortSignal.timeout(req.timeoutMs);
+ const url = s.kind === "ollama" ? `${s.url}/api/chat` : `${openaiBase(s)}/chat/completions`;
+ const send = (withJson: boolean) =>
+ fetch(url, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...authHeaders(s) },
+ body: JSON.stringify(s.kind === "ollama" ? ollamaBody(req, model ?? s.model, llmContext(), withJson) : openaiBody(s.kind, req, model, withJson)),
+ signal,
+ }).catch((e: unknown) => {
+ if (req.signal?.aborted) throw e;
+ // It was up a moment ago: look again before routing sends it more.
+ if ((e as Error)?.name !== "TimeoutError") forget(s);
+ throw unreachableError(s, e);
+ });
+ let res = await send(true);
+ if (!res.ok) {
+ const body = await res.text().catch(() => "");
+ if (req.json && rejectsJson(s.kind, res.status, body)) res = await send(false);
+ else throw httpError(s, res.status, body, model);
+ if (!res.ok) throw httpError(s, res.status, await res.text().catch(() => ""), model);
+ }
+ let j: unknown;
+ try {
+ j = await res.json();
+ } catch (e) {
+ if (req.signal?.aborted) throw e;
+ if ((e as Error)?.name === "TimeoutError") throw unreachableError(s, e);
+ throw new Error(`${cap(s.label)} sent an answer Fuobe couldn't read`);
+ }
+ const answer = model ?? r.status.model ?? s.label;
+ const out = s.kind === "ollama" ? parseOllama(j as Parameters<typeof parseOllama>[0], answer) : parseOpenai(j as Parameters<typeof parseOpenai>[0], answer);
+ if (req.tools?.length && !out.toolCalls.length && out.text) {
+ const healed = healToolCalls(out.text, new Set(req.tools.map((t) => t.name)));
+ if (healed.calls.length) return { ...out, text: healed.text, toolCalls: healed.calls, stop: "tool_use" };
+ }
+ return out;
+}
+
+/** Settings → Test: a tiny call to the server text steps would use (or the one named), timed. */
+export async function testLocal(kind?: LocalKind | null): Promise<{ ok: boolean; detail: string; ms?: number; model?: string }> {
+ const servers = kind ? [localServer(kind)] : localServers();
+ await refresh(servers, true);
+ const ready = pick(servers);
+ if (!ready) {
+ const need = llmContext();
+ const said = servers.map((s) => statusOf(s, need)).find((st) => st?.problem && (st.up || servers.length === 1));
+ return { ok: false, detail: said?.problem ?? "No local model server is answering. Start Ollama, LM Studio or Unsloth Studio, or set your server's URL." };
+ }
+ const t0 = Date.now();
+ try {
+ const r = await chatLocal(ready, { messages: [{ role: "user", content: "Reply with the word OK." }], think: false, maxTokens: 16, timeoutMs: 300_000 });
+ const ms = Date.now() - t0;
+ const note = r.text ? "" : " (it was still thinking: models that think first answer more slowly)";
+ return { ok: true, ms, model: r.model, detail: `${cap(ready.server.label)} answered in ${(ms / 1000).toFixed(1)} s with ${r.model}${note}` };
+ } catch (e) {
+ return { ok: false, detail: (e as Error).message };
+ }
+}
+
+/** What /api/status says about the local model (no keys). */
+export async function localSummary() {
+ const servers = localServers();
+ await refresh(servers);
+ const need = llmContext();
+ const ready = pick(servers);
+ return {
+ provider: pinnedKind() ?? "auto",
+ context: need,
+ local: ready
+ ? { kind: ready.server.kind, label: ready.server.label, url: ready.server.url, model: ready.status.model, loaded: ready.status.loaded, context: ready.status.context, warning: ready.status.warning }
+ : null,
+ problem: ready ? null : localProblem(),
+ detected: servers.map((s) => {
+ const st = statusOf(s, need)!;
+ return { kind: s.kind, label: s.label, url: s.url, up: st.up, auth: st.auth, models: st.models.length, model: st.model, problem: st.problem };
+ }),
+ };
+}
diff --git a/src/server/llm/messages.ts b/src/server/llm/messages.ts
new file mode 100644
index 00000000..b20de658
--- /dev/null
+++ b/src/server/llm/messages.ts
@@ -0,0 +1,124 @@
+import "server-only";
+import { createHash } from "node:crypto";
+import type Anthropic from "@anthropic-ai/sdk";
+import type { ChatMessage, ChatToolCall, LocalKind } from "./types";
+import { newToolId, toolInput } from "./wire";
+
+type MessageParam = Anthropic.Beta.BetaMessageParam;
+type ToolResult = Anthropic.Beta.BetaToolResultBlockParam;
+
+/*
+ * Assist keeps its history in Claude's shape. These turn it into chat messages a local model's chat
+ * template accepts, and read tool calls a model wrote as text.
+ */
+
+const B62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+
+/** A stored tool_use id as nine letters and digits, the same every time, so a call and its result still match. */
+export function wireId(id: string): string {
+ if (/^[A-Za-z0-9]{9}$/.test(id)) return id;
+ const h = createHash("sha256").update(id).digest();
+ let out = "";
+ for (let i = 0; i < 9; i++) out += B62[h[i] % 62];
+ return out;
+}
+
+const blockText = (c: ToolResult["content"]): string =>
+ typeof c === "string" ? c : (c ?? []).map((b) => (b.type === "text" ? b.text : b.type === "image" ? "[image omitted]" : "")).join("\n");
+
+/** How a mid-chat context update reads when it can't be a system message. */
+export const CONTEXT_UPDATE_LABEL = "Context update from Fuobe (not the user):";
+
+/**
+ * The stored history as chat messages: one system message first, then the turns. Images stay out
+ * (the user's text lists their URLs). Tool results follow the call they answer.
+ *
+ * Ollama gets the history as before: mid-chat context updates stay system messages and results carry
+ * the tool's name. The OpenAI-compatible servers get it shaped for strict chat templates (Gemma,
+ * Mistral, some Qwen ones), which reject a system message after the first and turns that don't
+ * alternate: a context update joins the user's turn (or follows the tool results as one), user turns
+ * in a row are merged, and tool-call ids are nine letters and digits.
+ */
+export function toChatMessages(system: { stable: string; turn: string }, history: MessageParam[], kind: LocalKind): ChatMessage[] {
+ const ollama = kind === "ollama";
+ const id = (x: string) => (ollama ? x : wireId(x));
+ const names = new Map<string, string>();
+ const out: ChatMessage[] = [{ role: "system", content: `${system.stable}\n\n${system.turn}` }];
+ for (const m of history) {
+ // Context updates are stored as role "system", which Claude's own message type doesn't name.
+ const role = m.role as "user" | "assistant" | "system";
+ const texts = typeof m.content === "string" ? [m.content] : m.content.flatMap((b) => (b.type === "text" ? [b.text] : []));
+ if (role === "system") {
+ const text = texts.join("\n");
+ out.push(ollama ? { role: "system", content: text } : { role: "user", content: `${CONTEXT_UPDATE_LABEL}\n${text}` });
+ continue;
+ }
+ if (role === "assistant") {
+ const calls: ChatToolCall[] =
+ typeof m.content === "string"
+ ? []
+ : m.content.flatMap((b) => {
+ if (b.type !== "tool_use") return [];
+ names.set(b.id, b.name);
+ return [{ id: id(b.id), name: b.name, input: b.input }];
+ });
+ out.push({ role: "assistant", content: texts.join("\n"), ...(calls.length && { toolCalls: calls }) });
+ continue;
+ }
+ if (typeof m.content !== "string") {
+ for (const b of m.content) {
+ if (b.type === "tool_result") out.push({ role: "tool", toolCallId: id(b.tool_use_id), toolName: names.get(b.tool_use_id), content: `${b.is_error ? "Error: " : ""}${blockText(b.content)}` });
+ }
+ }
+ const text = texts.join("\n");
+ if (text) out.push({ role: "user", content: text });
+ }
+ if (ollama) return out;
+ const merged: ChatMessage[] = [];
+ for (const m of out) {
+ const last = merged.at(-1);
+ if (m.role === "user" && last?.role === "user") last.content = `${last.content}\n\n${m.content}`;
+ else merged.push({ ...m });
+ }
+ return merged;
+}
+
+const MARKUP = [/<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/gi, /\[TOOL_REQUEST\]\s*([\s\S]*?)\s*\[END_TOOL_REQUEST\]/gi];
+
+/** {"name": …, "arguments" or "parameters": {…}}, naming one of the tools offered. */
+function asCall(body: string, names: Set<string>): ChatToolCall | null {
+ let j: unknown;
+ try {
+ j = JSON.parse(body.trim().replace(/^```(?:json)?\s*|\s*```$/g, ""));
+ } catch {
+ return null;
+ }
+ if (!j || typeof j !== "object" || Array.isArray(j)) return null;
+ const o = j as { name?: unknown; arguments?: unknown; parameters?: unknown; function?: { name?: unknown; arguments?: unknown } };
+ const name = typeof o.name === "string" ? o.name : typeof o.function?.name === "string" ? o.function.name : null;
+ if (!name || !names.has(name)) return null;
+ return { id: newToolId(), name, input: toolInput(o.arguments ?? o.parameters ?? o.function?.arguments ?? {}) };
+}
+
+/**
+ * Tool calls a model wrote as text instead of through the API: Hermes and Qwen's
+ * <tool_call>{…}</tool_call>, LM Studio's default [TOOL_REQUEST]{…}[END_TOOL_REQUEST], or a reply
+ * that is nothing but the call's JSON. Only the offered tools' names count; the markup leaves the text.
+ */
+export function healToolCalls(text: string, names: Set<string>): { text: string; calls: ChatToolCall[] } {
+ const calls: ChatToolCall[] = [];
+ let rest = text;
+ for (const re of MARKUP) {
+ rest = rest.replace(re, (whole, body: string) => {
+ const c = asCall(body, names);
+ if (!c) return whole;
+ calls.push(c);
+ return "";
+ });
+ }
+ if (!calls.length) {
+ const c = asCall(rest, names);
+ if (c) return { text: "", calls: [c] };
+ }
+ return { text: rest.trim(), calls };
+}
diff --git a/src/server/llm/probe.ts b/src/server/llm/probe.ts
new file mode 100644
index 00000000..263d68a8
--- /dev/null
+++ b/src/server/llm/probe.ts
@@ -0,0 +1,301 @@
+import "server-only";
+import { createHash } from "node:crypto";
+import { MessageChannel, receiveMessageOnPort, Worker } from "node:worker_threads";
+import { keyMessage, START_HINT } from "./errors";
+import { authHeaders, cap, openaiBase } from "./servers";
+import type { LocalModel, LocalServer, LocalStatus } from "./types";
+
+/*
+ * Is a local server usable, and with which model? Each server is asked with a few GETs sent at once
+ * (1.5 s each); the answers are kept for 15 s per server and read into a LocalStatus with the
+ * current Settings. Routing is synchronous, so the first look at a server (after boot, or after
+ * its URL or key changes in Settings) asks from a worker thread and waits for it; later looks
+ * refresh in the background.
+ */
+
+/** One GET's answer: the status and the JSON body, or why there was none. */
+export interface Raw {
+ status?: number;
+ body?: unknown;
+ error?: string;
+}
+export type Probe = Record<string, Raw>;
+
+interface ProbeRequest {
+ key: string;
+ url: string;
+ headers: Record<string, string>;
+}
+
+export const PROBE_MS = 15_000;
+const PROBE_TIMEOUT_MS = 1500;
+const EMBEDDING = /embed|rerank/i;
+
+/**
+ * Ollama: its model list. LM Studio: its own model list (loaded copies, context, tool training),
+ * and the OpenAI one for versions before 0.4. Unsloth Studio: its liveness check (which names the
+ * service: Jupyter also likes port 8888) and its model list. Any other server: the OpenAI model list.
+ */
+export function probeRequests(s: LocalServer): ProbeRequest[] {
+ if (!s.url) return [];
+ const auth = authHeaders(s);
+ if (s.kind === "ollama") return [{ key: "tags", url: `${s.url}/api/tags`, headers: {} }];
+ if (s.kind === "lmstudio") {
+ return [
+ { key: "native", url: `${s.url}/api/v1/models`, headers: auth },
+ { key: "openai", url: `${s.url}/v1/models`, headers: auth },
+ ];
+ }
+ if (s.kind === "unsloth") {
+ return [
+ { key: "live", url: `${s.url}/api/liveness`, headers: {} },
+ { key: "openai", url: `${s.url}/v1/models`, headers: auth },
+ ];
+ }
+ return [{ key: "openai", url: `${openaiBase(s)}/models`, headers: auth }];
+}
+
+const ok = (r?: Raw): r is Raw & { status: number } => !!r?.status && r.status >= 200 && r.status < 300;
+const denied = (r?: Raw) => r?.status === 401 || r?.status === 403;
+const rows = (v: unknown): Record<string, unknown>[] => (Array.isArray(v) ? v.filter((x): x is Record<string, unknown> => !!x && typeof x === "object") : []);
+const field = (v: unknown, k: string): unknown => (v && typeof v === "object" ? (v as Record<string, unknown>)[k] : undefined);
+const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null);
+const str = (v: unknown): string | null => (typeof v === "string" && v ? v : null);
+export const tokens = (n: number) => n.toLocaleString("en-US");
+
+function notRunning(s: LocalServer, r?: Raw): string {
+ if (r?.error === "TimeoutError") return `${cap(s.label)} didn't answer at ${s.url} within ${PROBE_TIMEOUT_MS / 1000} s. ${START_HINT[s.kind]}`;
+ if (r?.status) return `${cap(s.label)} answered ${r.status} at ${s.url}. Check its URL in Settings → AI helper.`;
+ return `${cap(s.label)} isn't running at ${s.url}. ${START_HINT[s.kind]}`;
+}
+
+/** A loaded model with less context than Fuobe asks for (or than the model's most, when that's less: a reload can't give more). */
+function smallContext(s: LocalServer, model: string, have: number | null, need: number, max?: number | null): string | null {
+ const want = Math.min(need, max ?? need);
+ if (!want || !have || have >= want) return null;
+ const fix = s.kind === "lmstudio" ? `Reload it with ${Math.round(want / 1024)}k context (Settings → AI helper)` : "Load it in Unsloth Studio with a larger context";
+ return `${model} is loaded with ${tokens(have)} tokens of context; Assist and long texts need about ${tokens(need)}. ${fix}.`;
+}
+
+/** What a probe's answers say about a server: up or not, its chat models, the model a call would use, and what's wrong. */
+export function interpret(s: LocalServer, probe: Probe, need: number, at: number): LocalStatus {
+ const base: LocalStatus = { kind: s.kind, label: s.label, url: s.url, up: false, auth: s.key ? "ok" : "none", models: [], model: null, loaded: null, context: null, problem: null, warning: null, at };
+ if (!s.url) return { ...base, problem: "Set the server's URL in Settings → AI helper (for example http://127.0.0.1:8080/v1)." };
+ const keyProblem = (): LocalStatus => ({ ...base, up: true, auth: s.key ? "rejected" : "missing", problem: keyMessage(s) });
+
+ if (s.kind === "ollama") {
+ const tags = probe.tags;
+ if (!ok(tags)) return { ...base, problem: notRunning(s, tags) };
+ const models = rows(field(tags.body, "models"))
+ .map((m) => ({ id: str(m.name) ?? str(m.model) ?? "" }))
+ .filter((m) => m.id && !EMBEDDING.test(m.id));
+ const have = models.some((m) => m.id === s.model || m.id === `${s.model}:latest`);
+ // Ollama is ready whenever it answers (as before): a missing model is named when a call needs it.
+ const warning = !models.length ? `Ollama has no models yet. Run \`ollama pull ${s.model}\`.` : have ? null : `${s.model} isn't downloaded. Run \`ollama pull ${s.model}\`, or pick one Ollama has.`;
+ return { ...base, up: true, auth: "none", models, model: s.model, context: need || null, warning };
+ }
+
+ if (s.kind === "lmstudio") {
+ const native = probe.native;
+ const openai = probe.openai;
+ if (denied(native) || denied(openai)) return keyProblem();
+ let models: LocalModel[];
+ const isNative = ok(native) && Array.isArray(field(native.body, "models"));
+ if (isNative) {
+ models = rows(field(native.body, "models"))
+ .filter((m) => m.type === "llm" && str(m.key))
+ .map((m) => {
+ const loaded = rows(m.loaded_instances);
+ const reasoning = field(field(m.capabilities, "reasoning"), "default");
+ return {
+ id: m.key as string,
+ name: str(m.display_name) ?? undefined,
+ loaded: loaded.length > 0,
+ tools: field(m.capabilities, "trained_for_tool_use") === true,
+ reasoning: typeof reasoning === "string" && reasoning !== "off",
+ context: num(field(loaded[0]?.config, "context_length")),
+ maxContext: num(m.max_context_length),
+ instances: loaded.flatMap((i) => (str(i.id) ? [i.id as string] : [])),
+ };
+ });
+ } else if (ok(openai) && Array.isArray(field(openai.body, "data"))) {
+ // LM Studio before 0.4: ids only (all downloaded models with JIT loading on, else the loaded ones).
+ models = rows(field(openai.body, "data"))
+ .flatMap((m) => (str(m.id) ? [{ id: m.id as string }] : []))
+ .filter((m) => !EMBEDDING.test(m.id));
+ } else return { ...base, problem: notRunning(s, native?.status ? native : openai) };
+ const up = { ...base, up: true, models, native: isNative };
+ if (!models.length) return { ...up, problem: "LM Studio has no chat models downloaded yet. Download one in LM Studio (Discover), or run `lms get qwen/qwen3-8b`." };
+ let pick: LocalModel | undefined;
+ if (s.model) {
+ pick = models.find((m) => m.id === s.model || m.name === s.model || s.model.startsWith(`${m.id}@`) || m.instances?.includes(s.model));
+ if (!pick && isNative) return { ...up, problem: `LM Studio has no model called ${s.model}. Download it in LM Studio (or run \`lms get ${s.model}\`), or pick another in Settings → AI helper.` };
+ } else {
+ // A loaded model, else one trained for tool calling (Assist needs it), else any.
+ pick = models.find((m) => m.loaded) ?? models.find((m) => m.tools) ?? models[0];
+ }
+ // A display name ("Qwen3 8B") finds the model, but calls and loads need its key.
+ const model = pick && pick.name === s.model && pick.id !== s.model ? pick.id : s.model || pick!.id;
+ const context = pick?.loaded ? (pick.context ?? null) : null;
+ const warning =
+ smallContext(s, model, context, need, pick?.maxContext) ??
+ (pick?.maxContext && need && pick.maxContext < need ? `${model} handles only ${tokens(pick.maxContext)} tokens of context; Assist and long texts need about ${tokens(need)}.` : null) ??
+ (pick?.reasoning ? `${model} thinks before it answers, which is slower. A model without thinking (an instruct model) suits Fuobe better.` : null);
+ return { ...up, model, loaded: isNative ? !!pick?.loaded : null, context, warning };
+ }
+
+ if (s.kind === "unsloth") {
+ const live = probe.live;
+ if (!ok(live) || field(live.body, "service") !== "Unsloth UI Backend") {
+ return { ...base, problem: ok(live) ? `Something else answers at ${s.url}, not Unsloth Studio. Check the URL (Unsloth Studio uses port 8888 unless you changed it).` : notRunning(s, live) };
+ }
+ const openai = probe.openai;
+ if (denied(openai)) return keyProblem();
+ if (!ok(openai)) return { ...base, up: true, problem: `Unsloth Studio didn't list its models (${openai?.status ?? openai?.error ?? "no answer"}). Try again in a moment.` };
+ // Rows with a task are speech, music or image models.
+ const models: LocalModel[] = rows(field(openai.body, "data"))
+ .filter((m) => str(m.id) && !m.task)
+ .map((m) => ({ id: m.id as string, name: str(m.display_name) ?? undefined, loaded: m.loaded === true, context: num(m.context_length), maxContext: num(m.max_context_length) }));
+ const up = { ...base, up: true, models };
+ if (s.model) {
+ const want = s.model.toLowerCase();
+ const pick = models.find((m) => m.id.toLowerCase() === want) ?? models.find((m) => want.startsWith(`${m.id.toLowerCase()}:`));
+ if (!pick) return { ...up, problem: `Unsloth Studio has no model called ${s.model}. Pick one it lists in Settings → AI helper, or leave the model empty to use the one loaded in Unsloth.` };
+ const warning = pick.loaded
+ ? smallContext(s, s.model, pick.context ?? null, need, pick.maxContext)
+ : `${s.model} isn't loaded in Unsloth Studio. It loads by itself only with Model auto-switch on (in Unsloth: avatar → Settings → API); otherwise load it on Unsloth's Chat page.`;
+ return { ...up, model: s.model, loaded: !!pick.loaded, context: pick.context ?? null, warning };
+ }
+ const loaded = models.find((m) => m.loaded);
+ if (!loaded) return { ...up, problem: `Unsloth Studio has no model loaded. Load one on its Chat page (Select model)${models.length ? "" : " after downloading one there"}.` };
+ return { ...up, model: loaded.id, loaded: true, context: loaded.context ?? null, warning: smallContext(s, loaded.id, loaded.context ?? null, need, loaded.maxContext) };
+ }
+
+ // Any other OpenAI-compatible server.
+ const openai = probe.openai;
+ if (denied(openai)) return keyProblem();
+ if (!ok(openai)) return { ...base, problem: notRunning(s, openai) };
+ const models: LocalModel[] = rows(field(openai.body, "data"))
+ .flatMap((m) => (str(m.id) ? [{ id: m.id as string }] : []))
+ .filter((m) => !EMBEDDING.test(m.id));
+ const up = { ...base, up: true, models };
+ const model = s.model || models[0]?.id;
+ if (!model) return { ...up, problem: `${cap(s.label)} lists no models. Load one in it, or name the model in Settings → AI helper.` };
+ const warning = s.model && models.length && !models.some((m) => m.id === s.model) ? `${s.model} isn't in the server's model list (${models.map((m) => m.id).slice(0, 4).join(", ")}).` : null;
+ return { ...up, model, warning };
+}
+
+// ---------------------------------------------------------------------------
+// Asking, and the cache
+
+declare global {
+ var __fuobeLocalProbes: Map<string, { at: number; probe: Probe }> | undefined;
+ var __fuobeLocalProbing: Map<string, Promise<void>> | undefined;
+}
+const probes = () => (globalThis.__fuobeLocalProbes ??= new Map());
+const probing = () => (globalThis.__fuobeLocalProbing ??= new Map());
+
+/** A server's cache key: its kind, URL and (a hash of) its key, so a new key is checked at once. */
+const sigOf = (s: LocalServer) => `${s.kind}|${s.url}|${s.key ? createHash("sha256").update(s.key).digest("hex").slice(0, 16) : ""}`;
+
+const parse = (text: string | undefined): unknown => {
+ try {
+ return text ? JSON.parse(text) : null;
+ } catch {
+ return null;
+ }
+};
+
+async function get(r: ProbeRequest): Promise<Raw> {
+ try {
+ const res = await fetch(r.url, { headers: r.headers, signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
+ return { status: res.status, body: parse(await res.text()) };
+ } catch (e) {
+ const err = e as { name?: string; cause?: { code?: string } };
+ return { error: err.name === "TimeoutError" ? "TimeoutError" : (err.cause?.code ?? err.name ?? "error") };
+ }
+}
+
+/** Ask the servers whose answers are older than 15 s (all of them with `force`), in parallel. */
+export async function refresh(servers: LocalServer[], force = false): Promise<void> {
+ await Promise.all(
+ servers.map(async (s) => {
+ const sig = sigOf(s);
+ const cur = probes().get(sig);
+ if (!force && cur && Date.now() - cur.at < PROBE_MS) return;
+ // `force` asks anew: an answer already on its way may predate what changed (a model just loaded).
+ const pending = force ? undefined : probing().get(sig);
+ if (pending) return pending;
+ const started = Date.now();
+ const p: Promise<void> = (async () => {
+ const reqs = probeRequests(s);
+ const raws = await Promise.all(reqs.map(get));
+ // An older question that answers late doesn't overwrite a newer answer.
+ const now = probes().get(sig);
+ if (!now || now.at <= started) probes().set(sig, { at: started, probe: Object.fromEntries(reqs.map((r, i) => [r.key, raws[i]])) });
+ })().finally(() => {
+ if (probing().get(sig) === p) probing().delete(sig);
+ });
+ probing().set(sig, p);
+ await p;
+ }),
+ );
+}
+
+const WORKER = `const { workerData } = require("node:worker_threads");
+const { port, sab, requests, timeout } = workerData;
+const flag = new Int32Array(sab);
+const one = (r) =>
+ fetch(r.url, { headers: r.headers, signal: AbortSignal.timeout(timeout) })
+ .then(async (res) => ({ status: res.status, text: (await res.text()).slice(0, 4000000) }))
+ .catch((e) => ({ error: e && e.name === "TimeoutError" ? "TimeoutError" : (e && e.cause && e.cause.code) || "error" }));
+Promise.all(requests.map(one))
+ .then((out) => port.postMessage(out))
+ .catch(() => port.postMessage([]))
+ .finally(() => {
+ Atomics.store(flag, 0, 1);
+ Atomics.notify(flag, 0);
+ });`;
+
+/**
+ * The blocking first look: every server's GETs in one worker thread, waited for (a few ms when
+ * nothing listens, at most 1.5 s + 1 s for a host that doesn't answer).
+ */
+export function refreshSync(servers: LocalServer[]): void {
+ const reqs = servers.flatMap((s, i) => probeRequests(s).map((r) => ({ ...r, server: i })));
+ const raws: Raw[] = reqs.map(() => ({ error: "TimeoutError" }));
+ if (reqs.length) {
+ try {
+ const sab = new SharedArrayBuffer(4);
+ const flag = new Int32Array(sab);
+ const { port1, port2 } = new MessageChannel();
+ const worker = new Worker(WORKER, {
+ eval: true,
+ workerData: { port: port2, sab, requests: reqs.map(({ url, headers }) => ({ url, headers })), timeout: PROBE_TIMEOUT_MS },
+ transferList: [port2],
+ });
+ Atomics.wait(flag, 0, 0, PROBE_TIMEOUT_MS + 1000);
+ const got = receiveMessageOnPort(port1)?.message as { status?: number; text?: string; error?: string }[] | undefined;
+ got?.forEach((g, i) => (raws[i] = g.status !== undefined ? { status: g.status, body: parse(g.text) } : { error: g.error }));
+ port1.close();
+ void worker.terminate();
+ } catch {}
+ }
+ const at = Date.now();
+ servers.forEach((s, i) => probes().set(sigOf(s), { at, probe: Object.fromEntries(reqs.flatMap((r, k) => (r.server === i ? [[r.key, raws[k]]] : []))) }));
+}
+
+/** The cached answers for a server (null: never asked), and whether they're older than 15 s. */
+export function cached(s: LocalServer): { at: number; probe: Probe; stale: boolean } | null {
+ const c = probes().get(sigOf(s));
+ return c ? { ...c, stale: Date.now() - c.at > PROBE_MS } : null;
+}
+
+/** The server's status from its cached answers and the current Settings (null: never asked). */
+export function statusOf(s: LocalServer, need: number): LocalStatus | null {
+ const c = probes().get(sigOf(s));
+ return c ? interpret(s, c.probe, need, c.at) : null;
+}
+
+/** Forget a server's answers (its next look asks again). */
+export const forget = (s: LocalServer) => void probes().delete(sigOf(s));
diff --git a/src/server/llm/servers.ts b/src/server/llm/servers.ts
new file mode 100644
index 00000000..c8b8a611
--- /dev/null
+++ b/src/server/llm/servers.ts
@@ -0,0 +1,65 @@
+import "server-only";
+import { getSetting, parseContext } from "../settings";
+import { LOCAL_KINDS, type LocalKind, type LocalServer } from "./types";
+
+export const LOCAL_LABELS: Record<LocalKind, string> = { ollama: "Ollama", lmstudio: "LM Studio", unsloth: "Unsloth Studio", custom: "your local server" };
+
+/** "your local server" at the start of a sentence. */
+export const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
+
+/** Settings → AI helper. The old value "ollama" means a local model only, whichever server runs it. */
+export function aiHelper(): "auto" | "anthropic" | "local" | "none" {
+ const v = getSetting("enhanceProvider");
+ return v === "ollama" ? "local" : (v as "auto" | "anthropic" | "local" | "none");
+}
+
+/** The local server Settings pins (null: Automatic). */
+export function pinnedKind(): LocalKind | null {
+ const v = getSetting("llmProvider");
+ return v === "auto" ? null : (v as LocalKind);
+}
+
+/** Tokens of context the local model should have; 0 leaves it to the server. A value that isn't a size gets 16384. */
+export function llmContext(): number {
+ return parseContext(getSetting("llmContext")) ?? 16384;
+}
+
+/** The server root: no trailing slash, and no /v1 (or Ollama's /api) pasted from an example. */
+const root = (url: string) =>
+ url
+ .trim()
+ .replace(/\/+$/, "")
+ .replace(/\/(?:api\/v[01]|v1|api)$/i, "");
+
+export function localServer(kind: LocalKind): LocalServer {
+ const label = LOCAL_LABELS[kind];
+ if (kind === "ollama") return { kind, label, url: root(getSetting("ollamaUrl")), model: getSetting("ollamaModel").trim(), key: "" };
+ if (kind === "lmstudio") return { kind, label, url: root(getSetting("lmstudioUrl")), model: getSetting("lmstudioModel").trim(), key: getSetting("lmstudioToken") };
+ if (kind === "unsloth") return { kind, label, url: root(getSetting("unslothUrl")), model: getSetting("unslothModel").trim(), key: getSetting("unslothKey") };
+ return { kind, label, url: getSetting("llmUrl").trim().replace(/\/+$/, ""), model: getSetting("llmModel").trim(), key: getSetting("llmKey") };
+}
+
+/** The servers text steps and Assist may use, in the order they're tried: the pinned one, or all (the custom one when it has a URL). */
+export function localServers(): LocalServer[] {
+ const pinned = pinnedKind();
+ if (pinned) return [localServer(pinned)];
+ return LOCAL_KINDS.map(localServer).filter((s) => s.kind !== "custom" || s.url);
+}
+
+/** Every server, for Settings (the custom one even without a URL). */
+export const allLocalServers = (): LocalServer[] => LOCAL_KINDS.map(localServer);
+
+/**
+ * Where the OpenAI-compatible API lives. LM Studio and Unsloth: {root}/v1. A custom URL is an OpenAI
+ * "base URL" as the server's docs give it (http://host:8080/v1); a bare host gets /v1 added.
+ */
+export function openaiBase(s: LocalServer): string {
+ if (s.kind !== "custom") return `${s.url}/v1`;
+ try {
+ return new URL(s.url).pathname.replace(/\/+$/, "") ? s.url : `${s.url}/v1`;
+ } catch {
+ return `${s.url}/v1`;
+ }
+}
+
+export const authHeaders = (s: LocalServer): Record<string, string> => (s.key ? { Authorization: `Bearer ${s.key}` } : {});
diff --git a/src/server/llm/types.ts b/src/server/llm/types.ts
new file mode 100644
index 00000000..4907237e
--- /dev/null
+++ b/src/server/llm/types.ts
@@ -0,0 +1,110 @@
+/**
+ * Local LLM servers: Ollama (its own API), LM Studio, Unsloth Studio, and any other
+ * OpenAI-compatible server (llama.cpp's llama-server, vLLM, Jan…). One layer serves text steps,
+ * llmText() and the Assist agent; the request and response shapes here are neutral (OpenAI-like).
+ */
+
+export type LocalKind = "ollama" | "lmstudio" | "unsloth" | "custom";
+
+/** The order Automatic tries them in: Ollama first, so installs that had it keep it. */
+export const LOCAL_KINDS: LocalKind[] = ["ollama", "lmstudio", "unsloth", "custom"];
+
+export interface LocalServer {
+ kind: LocalKind;
+ /** "Ollama", "LM Studio", "Unsloth Studio", or "your local server" for the custom one. */
+ label: string;
+ /** No trailing slash. Ollama, LM Studio and Unsloth: the server root (a pasted /v1 is dropped). Custom: as given. */
+ url: string;
+ /** The model picked in Settings ("" = Fuobe picks). */
+ model: string;
+ /** Bearer token; never leaves the server. */
+ key: string;
+}
+
+export interface LocalModel {
+ id: string;
+ name?: string;
+ /** In memory now (LM Studio, Unsloth). */
+ loaded?: boolean;
+ /** LM Studio: trained for tool calling. */
+ tools?: boolean;
+ /** LM Studio: thinks before answering by default. */
+ reasoning?: boolean;
+ /** Context of the loaded copy, in tokens. */
+ context?: number | null;
+ maxContext?: number | null;
+ /** LM Studio: ids of its loaded copies (to unload before a reload). */
+ instances?: string[];
+}
+
+export interface LocalStatus {
+ kind: LocalKind;
+ label: string;
+ url: string;
+ /** Something answered at the URL (for Unsloth: Unsloth Studio itself). */
+ up: boolean;
+ auth: "none" | "ok" | "missing" | "rejected";
+ /** Chat models only (no embedding, speech or image models). */
+ models: LocalModel[];
+ /** The model a call uses now (Unsloth: the loaded one; null: none to use). */
+ model: string | null;
+ /** Whether that model is in memory (null: the server doesn't say). */
+ loaded: boolean | null;
+ /** Its context window in tokens, when known. */
+ context: number | null;
+ /** Why it can't run, in the user's words (null = ready). */
+ problem: string | null;
+ /** Ready, but worth knowing: a small context, a model that thinks first, a model that may be missing. */
+ warning: string | null;
+ /** LM Studio's own API answered, so Fuobe can load a model with the context it needs. */
+ native?: boolean;
+ at: number;
+}
+
+export interface ChatToolCall {
+ id: string;
+ name: string;
+ input: unknown;
+}
+
+export interface ChatMessage {
+ role: "system" | "user" | "assistant" | "tool";
+ content: string;
+ toolCalls?: ChatToolCall[];
+ /** Tool results: the call they answer (OpenAI). */
+ toolCallId?: string;
+ /** Tool results: the tool's name (Ollama). */
+ toolName?: string;
+}
+
+/** A JSON Schema the answer must follow (root object or array), or "object" for any JSON object. */
+export type JsonSpec = { name: string; schema: Record<string, unknown> } | "object";
+
+export interface ChatTool {
+ name: string;
+ description?: string;
+ parameters: unknown;
+}
+
+export interface ChatRequest {
+ messages: ChatMessage[];
+ /** Overrides the server's model for this call (Assist's Manual mode). */
+ model?: string | null;
+ tools?: ChatTool[];
+ json?: JsonSpec;
+ /** false: ask the server not to think (one-shot text). Undefined: the server's default (Assist). */
+ think?: boolean;
+ maxTokens?: number;
+ timeoutMs: number;
+ signal?: AbortSignal;
+}
+
+export interface ChatResult {
+ /** The answer, with <think> blocks removed (reasoning fields are ignored). */
+ text: string;
+ toolCalls: ChatToolCall[];
+ stop: "end" | "tool_use" | "length";
+ model: string;
+ /** The reply carried reasoning (thinking) besides the answer. */
+ thought: boolean;
+}
diff --git a/src/server/llm/wire.ts b/src/server/llm/wire.ts
new file mode 100644
index 00000000..1cab5bd1
--- /dev/null
+++ b/src/server/llm/wire.ts
@@ -0,0 +1,143 @@
+import "server-only";
+import { customAlphabet } from "nanoid";
+import type { ChatMessage, ChatRequest, ChatResult, ChatToolCall, JsonSpec, LocalKind } from "./types";
+
+/*
+ * Request bodies and answers for the two wires, as pure functions: Ollama's own /api/chat (it has
+ * num_ctx, think and a schema in `format`), and OpenAI's /v1/chat/completions for LM Studio,
+ * Unsloth Studio and any other OpenAI-compatible server, with small differences per server.
+ */
+
+/** Tool-call ids as strict chat templates (Mistral's) want them: nine letters and digits. */
+export const newToolId = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 9);
+
+/** The answer without its thinking: <think>…</think>, a closing tag whose opening one was in the prompt, a thought cut off. */
+export function stripThink(s: string): string {
+ let t = s.replace(/<think>[\s\S]*?<\/think>/gi, "");
+ const close = t.search(/<\/think>/i);
+ if (close >= 0) t = t.slice(close + "</think>".length);
+ return t.replace(/<think>[\s\S]*$/i, "").trim();
+}
+
+/** Tool arguments: an object, or a JSON string (a broken one reaches the tool as INVALID_JSON, which tells the model what to fix). */
+export function toolInput(args: unknown): unknown {
+ if (typeof args !== "string") return args ?? {};
+ if (!args.trim()) return {};
+ try {
+ return JSON.parse(args);
+ } catch {
+ return { INVALID_JSON: args };
+ }
+}
+
+const toolList = (req: ChatRequest) => req.tools?.map((t) => ({ type: "function", function: { name: t.name, description: t.description ?? "", parameters: t.parameters } }));
+
+// ---------------------------------------------------------------------------
+// Ollama: POST {url}/api/chat
+
+export function ollamaBody(req: ChatRequest, model: string, context: number, withJson = true): Record<string, unknown> {
+ const tools = toolList(req);
+ return {
+ model,
+ stream: false,
+ ...(req.think === false && { think: false }),
+ messages: req.messages.map((m) => ({
+ role: m.role,
+ content: m.content,
+ ...(m.toolCalls?.length && { tool_calls: m.toolCalls.map((c) => ({ function: { name: c.name, arguments: c.input } })) }),
+ ...(m.toolName && { tool_name: m.toolName }),
+ })),
+ ...(tools?.length && { tools }),
+ ...(withJson && req.json && { format: req.json === "object" ? "json" : req.json.schema }),
+ ...((context > 0 || req.maxTokens) && { options: { ...(context > 0 && { num_ctx: context }), ...(req.maxTokens && { num_predict: req.maxTokens }) } }),
+ };
+}
+
+interface OllamaReply {
+ model?: string;
+ message?: { content?: string; thinking?: string; tool_calls?: { function?: { name?: string; arguments?: unknown } }[] };
+ done_reason?: string;
+}
+
+export function parseOllama(j: OllamaReply, model: string): ChatResult {
+ const raw = j.message?.content ?? "";
+ const toolCalls: ChatToolCall[] = (j.message?.tool_calls ?? []).flatMap((c) => (c.function?.name ? [{ id: newToolId(), name: c.function.name, input: toolInput(c.function.arguments) }] : []));
+ return {
+ text: stripThink(raw),
+ toolCalls,
+ stop: toolCalls.length ? "tool_use" : j.done_reason === "length" ? "length" : "end",
+ model: j.model || model,
+ thought: !!j.message?.thinking || /<\/think>/i.test(raw),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// OpenAI-compatible: POST {base}/chat/completions
+
+type WireMessage =
+ | { role: "system" | "user"; content: string }
+ | { role: "assistant"; content: string | null; tool_calls?: { id: string; type: "function"; function: { name: string; arguments: string } }[] }
+ | { role: "tool"; tool_call_id: string; content: string };
+
+function wireMessage(m: ChatMessage): WireMessage {
+ if (m.role === "assistant") {
+ const calls = m.toolCalls ?? [];
+ return calls.length
+ ? { role: "assistant", content: m.content || null, tool_calls: calls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.input ?? {}) } })) }
+ : { role: "assistant", content: m.content };
+ }
+ if (m.role === "tool") return { role: "tool", tool_call_id: m.toolCallId ?? "", content: m.content };
+ return { role: m.role, content: m.content };
+}
+
+/**
+ * `response_format` per server. A schema goes as json_schema everywhere, with `strict` except on
+ * LM Studio (its docs send `"strict": "true"`, a string; LM Studio builds a grammar from the schema
+ * either way, so it's left out); "any object" is json_object, except on LM Studio, which only documents
+ * json_schema, so it gets the schema of any object.
+ */
+export function responseFormat(kind: LocalKind, json: JsonSpec): Record<string, unknown> {
+ if (json === "object") return kind === "lmstudio" ? { type: "json_schema", json_schema: { name: "answer", schema: { type: "object" } } } : { type: "json_object" };
+ return { type: "json_schema", json_schema: { name: json.name, ...(kind !== "lmstudio" && { strict: true }), schema: json.schema } };
+}
+
+/**
+ * The request body. `model` null leaves the field out: Unsloth Studio then answers with the model
+ * loaded in it. Unsloth also gets enable_tools:false on every call, so a prompt never runs its
+ * server-side Python, shell or web search (Fuobe's prompts carry text from the web).
+ */
+export function openaiBody(kind: LocalKind, req: ChatRequest, model: string | null, withJson = true): Record<string, unknown> {
+ const tools = toolList(req);
+ return {
+ ...(model && { model }),
+ messages: req.messages.map(wireMessage),
+ stream: false,
+ ...(tools?.length && { tools, tool_choice: "auto" }),
+ ...(withJson && req.json && { response_format: responseFormat(kind, req.json) }),
+ ...(req.maxTokens && { max_tokens: req.maxTokens }),
+ ...(kind === "unsloth" && { enable_tools: false, ...(req.think === false && { enable_thinking: false }) }),
+ };
+}
+
+interface OpenAiReply {
+ model?: string;
+ choices?: {
+ finish_reason?: string | null;
+ message?: { content?: string | null; reasoning_content?: string | null; reasoning?: string | null; tool_calls?: { id?: string; function?: { name?: string; arguments?: unknown } }[] | null };
+ }[];
+}
+
+export function parseOpenai(j: OpenAiReply, model: string): ChatResult {
+ const choice = j.choices?.[0];
+ const msg = choice?.message;
+ const raw = typeof msg?.content === "string" ? msg.content : "";
+ // Fuobe makes its own ids: the server's may be any shape ("call_…", digits, or none).
+ const toolCalls: ChatToolCall[] = (msg?.tool_calls ?? []).flatMap((c) => (c?.function?.name ? [{ id: newToolId(), name: c.function.name, input: toolInput(c.function.arguments) }] : []));
+ return {
+ text: stripThink(raw),
+ toolCalls,
+ stop: toolCalls.length ? "tool_use" : choice?.finish_reason === "length" ? "length" : "end",
+ model: j.model || model,
+ thought: !!(msg?.reasoning_content || msg?.reasoning) || /<\/think>/i.test(raw),
+ };
+}
diff --git a/src/server/model3d-finish.ts b/src/server/model3d-finish.ts
new file mode 100644
index 00000000..59ad4180
--- /dev/null
+++ b/src/server/model3d-finish.ts
@@ -0,0 +1,333 @@
+import "server-only";
+import { spawn, type ChildProcess } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import type { OutputFile } from "@/lib/catalog/types";
+import { absolutePath, deleteAsset, getAsset, saveFile } from "./storage";
+
+/**
+ * The finish every image-to-3D GLB from ComfyUI gets on this server, in two steps:
+ *
+ * 1. finishModel, while the job still shows as running (seconds): scripts/model3d/finish-glb.mjs sets a
+ * roughness floor by material (read from the baked metallic channel), puts the pivot at the bottom centre
+ * (Pixal3D's origin is off-centre) and writes meshopt geometry + WebP textures at 2048. The result is the
+ * "web GLB" (meta.web on the model output); the raw GLB stays the download. Then the job succeeds.
+ * 2. startTurntable, after the job has succeeded: scripts/model3d/render-turntable.mjs renders a 96-frame,
+ * 24 fps turntable of the web GLB with <model-viewer> in headless Chromium on SwiftShader (CPU only, never
+ * the GPU), on a studio backdrop, encoded by ffmpeg; plus a poster. It's added to the finished job as a
+ * video output with meta.role "turntable". meta.finish.turntable says where it stands: "queued",
+ * "rendering" (with turntableProgress), "done", "skipped: …" (no Chromium or ffmpeg here: the 3D page
+ * records one in the browser) or "failed: …". A restart picks up the ones still queued or rendering.
+ *
+ * Both scripts run as child processes (the work is CPU-heavy and must not stall the server's event loop),
+ * one turntable at a time, at below-normal priority. Any failure keeps what was made: the raw GLB always.
+ */
+
+/** Bump when the finish changes what it writes. */
+export const MODEL_FINISH_VERSION = 2;
+
+const SCRIPTS = path.join(/*turbopackIgnore: true*/ process.cwd(), "scripts", "model3d");
+const FINISH_TIMEOUT_MS = 5 * 60_000;
+/** The whole render; the script also limits each step (loading the model, each frame, the encode). */
+const TURNTABLE_TIMEOUT_MS = 10 * 60_000;
+/** How often a render's progress is written to the job (each write reaches every open page). */
+const PROGRESS_EVERY_MS = 2_000;
+
+const isGlb = (o: OutputFile) => o.kind === "model3d" && (o.contentType === "model/gltf-binary" || /\.glb(\?|$)/i.test(o.url));
+
+/** Which output a finish works on: the first GLB of an image-to-3D job from ComfyUI (not a scene, splat or rig). */
+export function modelToFinish(r: { provider: string; op: string }, outputs: OutputFile[]): number {
+ if (r.provider !== "comfyui" || r.op !== "image-to-3d") return -1;
+ return outputs.findIndex((o) => isGlb(o) && !!o.assetId && !o.meta?.finish && !o.meta?.role);
+}
+
+export type FinishStats = { material: string; metalFraction: number; roughFloor: number; noMetal: boolean; triangles: number; vertices: number; bytesIn: number; bytesOut: number; ms: number };
+
+/** The last line of a script's stdout that parses as JSON. */
+export function lastJsonLine<T>(stdout: string): T | null {
+ for (const line of stdout.trim().split(/\r?\n/).reverse()) {
+ try {
+ return JSON.parse(line) as T;
+ } catch {}
+ }
+ return null;
+}
+
+/** End a script and everything it started (Chromium, ffmpeg). */
+function killTree(child: ChildProcess): void {
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null) return;
+ if (process.platform === "win32") {
+ // child.kill() ends only node on Windows: Chromium and ffmpeg under it would outlive it.
+ const tk = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
+ tk.on("error", () => child.kill());
+ return;
+ }
+ // The scripts close their browser on SIGTERM (Playwright's exit handler); SIGKILL if that hangs.
+ child.kill("SIGTERM");
+ setTimeout(() => {
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
+ }, 5_000).unref();
+}
+
+type Run = { code: number | null; stdout: string; stderr: string };
+
+function runScript(script: string, args: string[], o: { timeoutMs: number; signal: AbortSignal; lowPriority?: boolean; onLine?: (line: string) => void }): Promise<Run> {
+ return new Promise((resolve, reject) => {
+ if (o.signal.aborted) return reject(new Error("Stopped"));
+ // stdin stays open and unused: the script stops when it closes (this server went away).
+ const child = spawn(process.execPath, [path.join(SCRIPTS, script), ...args], {
+ cwd: /*turbopackIgnore: true*/ process.cwd(),
+ env: { ...process.env, FUOBE_PARENT_PIPE: "1" },
+ windowsHide: true,
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ child.stdin.on("error", () => {});
+ if (o.lowPriority && child.pid) {
+ // Below the next ComfyUI job (its remesh, decimate and bake use the CPU too); what it starts inherits it.
+ try {
+ os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL);
+ } catch {}
+ }
+ let stdout = "";
+ let stderr = "";
+ let partial = "";
+ child.stdout.on("data", (d) => {
+ stdout = (stdout + d).slice(-20_000);
+ if (!o.onLine) return;
+ const lines = (partial + d).split(/\r?\n/);
+ partial = lines.pop() ?? "";
+ for (const line of lines) o.onLine(line);
+ });
+ child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-4_000)));
+ let timedOut = false;
+ const kill = () => killTree(child);
+ const timer = setTimeout(() => {
+ timedOut = true;
+ kill();
+ }, o.timeoutMs);
+ o.signal.addEventListener("abort", kill, { once: true });
+ child.on("error", (e) => {
+ clearTimeout(timer);
+ o.signal.removeEventListener("abort", kill);
+ reject(e);
+ });
+ child.on("close", (code) => {
+ clearTimeout(timer);
+ o.signal.removeEventListener("abort", kill);
+ if (o.signal.aborted) return reject(new Error("Stopped"));
+ if (timedOut) return reject(new Error(`took over ${Math.round(o.timeoutMs / 60_000)} minutes`));
+ resolve({ code, stdout, stderr });
+ });
+ });
+}
+
+const tail = (s: string) => s.trim().split(/\r?\n/).slice(-2).join(" | ").slice(0, 300);
+
+/** Remove a temp folder; on Windows a file can stay locked for a moment, and a leftover folder is no reason to fail. */
+const removeDir = (dir: string) => fs.promises.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }).catch(() => {});
+
+declare global {
+ var __fuobeModelFinish: Map<string, AbortController> | undefined;
+ var __fuobeTurntableQueue: Promise<unknown> | undefined;
+}
+
+const running = () => (globalThis.__fuobeModelFinish ??= new Map());
+
+// One turntable render at a time (each keeps every CPU core busy for a minute or two); shared across hot reloads.
+function oneAtATime<T>(fn: () => Promise<T>): Promise<T> {
+ const next = (globalThis.__fuobeTurntableQueue ?? Promise.resolve()).then(fn, fn);
+ globalThis.__fuobeTurntableQueue = next.catch(() => {});
+ return next;
+}
+
+/**
+ * Step 1 (see the header): the web GLB. Returns the outputs to store: the model output with meta.web and
+ * meta.finish (turntable "queued" when there's a web GLB to render).
+ */
+export async function finishModel(
+ generationId: string,
+ outputs: OutputFile[],
+ o: { op: string; provider: string; onMessage?: (m: string) => void; signal?: AbortSignal },
+): Promise<OutputFile[]> {
+ const signal = o.signal ?? new AbortController().signal;
+ const i = modelToFinish(o, outputs);
+ if (i < 0) return outputs;
+ const mesh = outputs[i];
+ const asset = getAsset(mesh.assetId!);
+ if (!asset) return outputs;
+ const raw = absolutePath(asset.relPath);
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), "fuobe-3d-"));
+ const finish: Record<string, unknown> = { version: MODEL_FINISH_VERSION };
+ const meta: Record<string, unknown> = { ...mesh.meta };
+ try {
+ o.onMessage?.("Finishing the 3D model");
+ const webFile = path.join(tmp, "web.glb");
+ let stats: FinishStats | null = null;
+ try {
+ const run = await runScript("finish-glb.mjs", ["--in", raw, "--out", webFile], { timeoutMs: FINISH_TIMEOUT_MS, signal });
+ stats = run.code === 0 && fs.existsSync(webFile) ? lastJsonLine<FinishStats>(run.stdout) : null;
+ if (!stats) finish.error = `web GLB: ${tail(run.stderr) || `exit ${run.code}`}`;
+ } catch (e) {
+ if (signal.aborted) throw e;
+ finish.error = `web GLB: ${(e as Error).message}`;
+ }
+ if (stats) {
+ const web = saveFile({ data: await fs.promises.readFile(webFile), contentType: "model/gltf-binary", name: "model-web.glb", source: "derived", generationId });
+ meta.web = web.url;
+ Object.assign(finish, { material: stats.material, triangles: stats.triangles, rawBytes: stats.bytesIn, webBytes: stats.bytesOut, webAsset: web.id, turntable: "queued" });
+ }
+ } finally {
+ await removeDir(tmp);
+ }
+ if (finish.error) console.warn(`[fuobe] 3D finish for ${generationId}: ${finish.error}`);
+ return outputs.map((x, j) => (j === i ? { ...mesh, meta: { ...meta, finish } } : x));
+}
+
+/** Whether this process is finishing that job (either step) right now. */
+export function finishing(generationId: string): boolean {
+ return running().has(generationId);
+}
+
+/**
+ * Run finishModel (step 1) in the background, once per job, then `done` with the outputs to store. The job's
+ * row stays "running" meanwhile; a restart picks it up again from the stored outputs. Not called after a stop.
+ */
+export function startModelFinish(
+ generationId: string,
+ outputs: OutputFile[],
+ o: { op: string; provider: string; onMessage?: (m: string) => void; done: (outputs: OutputFile[]) => void },
+): void {
+ if (finishing(generationId)) return;
+ const ctl = new AbortController();
+ running().set(generationId, ctl);
+ void finishModel(generationId, outputs, { ...o, signal: ctl.signal })
+ .catch((e) => {
+ if (ctl.signal.aborted) return null;
+ console.warn(`[fuobe] 3D finish for ${generationId} failed: ${(e as Error).message}`);
+ return outputs;
+ })
+ .then((out) => {
+ if (running().get(generationId) === ctl) running().delete(generationId);
+ if (out && !ctl.signal.aborted) o.done(out);
+ });
+}
+
+/** Stop a finish or a turntable render (the job was canceled or deleted). */
+export function stopModelFinish(generationId: string): void {
+ running().get(generationId)?.abort();
+ running().delete(generationId);
+}
+
+// ---------------------------------------------------------------------------
+// Step 2: the turntable, after the job has succeeded.
+
+/** Where a finished job's outputs live: what they are now (null once the job is gone), and storing them. */
+export interface OutputStore {
+ read(): OutputFile[] | null;
+ write(outputs: OutputFile[]): void;
+}
+
+const turntableOf = (o: OutputFile) => (o.meta?.finish as { turntable?: unknown } | undefined)?.turntable;
+
+/** The model output whose turntable is still to be rendered (queued, or rendering when the server stopped), or -1. */
+export function pendingTurntable(outputs: OutputFile[]): number {
+ return outputs.findIndex((o) => o.kind === "model3d" && (turntableOf(o) === "queued" || turntableOf(o) === "rendering"));
+}
+
+/**
+ * The outputs with the turntable's state on the model output (`assetId`): meta.finish.turntable (+ progress
+ * while rendering), the poster, and the video, which replaces a turntable the job brought itself (an old graph).
+ */
+export function withTurntable(outputs: OutputFile[], assetId: string, r: { state: string; progress?: number; video?: OutputFile; poster?: string }): OutputFile[] {
+ const i = outputs.findIndex((o) => o.kind === "model3d" && o.assetId === assetId);
+ if (i < 0) return outputs;
+ const mesh = outputs[i];
+ const finish: Record<string, unknown> = { ...(mesh.meta?.finish as Record<string, unknown> | undefined), turntable: r.state };
+ if (r.progress !== undefined) finish.turntableProgress = r.progress;
+ else delete finish.turntableProgress;
+ const next = outputs.map((o, j) => (j === i ? { ...mesh, meta: { ...mesh.meta, ...(r.poster ? { poster: r.poster } : {}), finish } } : o));
+ return r.video ? [...next.filter((o) => !(o.kind === "video" && o.meta?.role === "turntable")), r.video] : next;
+}
+
+/** Render the turntable of a finished job whose model output has one queued (step 2), in the background. */
+export function startTurntable(generationId: string, store: OutputStore): void {
+ if (finishing(generationId)) return;
+ const outputs = store.read();
+ const i = outputs ? pendingTurntable(outputs) : -1;
+ if (i < 0) return;
+ const ctl = new AbortController();
+ running().set(generationId, ctl);
+ void renderTurntable(generationId, outputs![i], store, ctl)
+ .catch((e) => {
+ if (!ctl.signal.aborted) console.warn(`[fuobe] 3D turntable for ${generationId} failed: ${(e as Error).message}`);
+ })
+ .finally(() => {
+ if (running().get(generationId) === ctl) running().delete(generationId);
+ });
+}
+
+async function renderTurntable(generationId: string, mesh: OutputFile, store: OutputStore, ctl: AbortController): Promise<void> {
+ const { signal } = ctl;
+ const assetId = mesh.assetId!;
+ const finish = (mesh.meta?.finish ?? {}) as { webAsset?: string; material?: string };
+ /** Store the turntable's state; false (and stop) once the job is gone. */
+ const set = (r: Parameters<typeof withTurntable>[2]) => {
+ const now = store.read();
+ if (!now) {
+ ctl.abort();
+ return false;
+ }
+ store.write(withTurntable(now, assetId, r));
+ return true;
+ };
+ const web = finish.webAsset ? getAsset(finish.webAsset) : null;
+ if (!web) return void set({ state: "failed: the web GLB is missing" });
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), "fuobe-turntable-"));
+ try {
+ const video = path.join(tmp, "turntable.mp4");
+ const posterFile = path.join(tmp, "poster.webp");
+ let run: Run;
+ try {
+ run = await oneAtATime(() => {
+ if (signal.aborted || !set({ state: "rendering", progress: 0 })) throw new Error("Stopped");
+ let last = Date.now();
+ return runScript("render-turntable.mjs", ["--glb", absolutePath(web.relPath), "--out", video, "--poster", posterFile, "--material", finish.material ?? "auto"], {
+ timeoutMs: TURNTABLE_TIMEOUT_MS,
+ signal,
+ lowPriority: true,
+ // "frame 12/96" after each frame.
+ onLine: (line) => {
+ const m = /^frame (\d+)\/(\d+)$/.exec(line.trim());
+ if (!m || Date.now() - last < PROGRESS_EVERY_MS) return;
+ last = Date.now();
+ set({ state: "rendering", progress: Math.round((Number(m[1]) / Number(m[2])) * 100) / 100 });
+ },
+ });
+ });
+ } catch (e) {
+ if (signal.aborted) return;
+ set({ state: `failed: ${(e as Error).message}` });
+ return;
+ }
+ if (run.code !== 0 || !fs.existsSync(video)) {
+ // Exit 3: no Chromium or ffmpeg here; the 3D page records a turntable in the browser instead.
+ const state = run.code === 3 ? `skipped: ${tail(run.stderr)}` : `failed: ${tail(run.stderr) || `exit ${run.code}`}`;
+ if (run.code !== 3) console.warn(`[fuobe] 3D turntable for ${generationId}: ${state}`);
+ set({ state });
+ return;
+ }
+ if (!store.read()) return;
+ const clip = saveFile({ data: await fs.promises.readFile(video), contentType: "video/mp4", name: "turntable.mp4", source: "generation", generationId });
+ const poster = fs.existsSync(posterFile) ? saveFile({ data: await fs.promises.readFile(posterFile), contentType: "image/webp", name: "poster.webp", source: "derived", generationId }) : null;
+ const stored = set({
+ state: "done",
+ video: { url: clip.url, kind: "video", contentType: clip.contentType, assetId: clip.id, meta: { role: "turntable", fps: 24, frames: 96 } },
+ poster: poster?.url,
+ });
+ // Deleted while the files were saved: nothing points at them.
+ if (!stored) for (const a of [clip, poster]) if (a) deleteAsset(a.id);
+ } finally {
+ await removeDir(tmp);
+ }
+}
diff --git a/src/server/providers/llm.ts b/src/server/providers/llm.ts
index afd6f760..f8fd5fae 100644
--- a/src/server/providers/llm.ts
+++ b/src/server/providers/llm.ts
@@ -1,10 +1,10 @@
import "server-only";
-import { Worker } from "node:worker_threads";
import Anthropic from "@anthropic-ai/sdk";
import { nanoid } from "nanoid";
import { getModel } from "@/lib/catalog";
import { cueText, parseCues, toSrt, type Cue } from "@/lib/cues";
import type { GenInput, ModelRoute, Operation } from "@/lib/catalog/types";
+import { aiHelper, chatLocal, emptyReply, localLabel, localProblem, localReady, localWhat, probeLocal, type JsonSpec, type Ready } from "../llm";
import { engineMode, getSetting } from "../settings";
import { toDataUri } from "../storage";
import { comfyProvider } from "./comfyui";
@@ -13,14 +13,15 @@ import type { PollResult, ProviderAdapter, RemoteOutput } from "./types";
/**
* The "llm" provider: text steps (translate, write) run inside this server on the LLM the
* install is set up with — Claude when an Anthropic key is set (and the install isn't open
- * source only), else a local Ollama. Route endpoint "ollama" (the open model) never uses Claude;
- * when Ollama isn't running, its translations run on ComfyUI instead (Qwen3.5 4B through the
+ * source only), else a local model (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible
+ * server; see src/server/llm). Route endpoint "ollama" (the open model) never uses Claude;
+ * when no local model is running, its translations run on ComfyUI instead (Qwen3.5 4B through the
* translate-qwen35-textgen workflow, one prompt per batch of lines, so cue timing is kept the same way).
* Jobs run in the background of this process and are polled like any provider; a restart
* loses a job that was still writing (it fails as interrupted and can be retried).
*/
-type Backend = "claude" | "ollama" | "comfyui";
+type Backend = "claude" | "local" | "comfyui";
/** The ComfyUI model and workflow open-source translations fall back to without Ollama. */
export const COMFY_TRANSLATE_MODEL = "oss-qwen35-translate";
@@ -39,85 +40,51 @@ export function textOutput(text: string, cues?: Cue[] | null, meta: Record<strin
// Which LLM
declare global {
- var __fuobeOllamaReach: { ok: boolean; at: number; url: string } | undefined;
var __fuobeLlmJobs: Map<string, LlmJob> | undefined;
}
-const ollamaUrl = () => getSetting("ollamaUrl").replace(/\/+$/, "");
-const PROBE_MS = 15_000;
-
-/** Is Ollama answering? Cached for 15 s; routing reads the cached answer (see llmBackends). */
-export async function probeOllama(force = false): Promise<boolean> {
- const cur = globalThis.__fuobeOllamaReach;
- const url = ollamaUrl();
- if (!force && cur && cur.url === url && Date.now() - cur.at < PROBE_MS) return cur.ok;
- const ok = await fetch(`${url}/api/tags`, { signal: AbortSignal.timeout(1500) })
- .then((r) => r.ok)
- .catch(() => false);
- globalThis.__fuobeOllamaReach = { ok, at: Date.now(), url };
- return ok;
-}
-
-const PROBE_WORKER = `const { workerData } = require("node:worker_threads");
-const flag = new Int32Array(workerData.sab);
-fetch(workerData.url, { signal: AbortSignal.timeout(workerData.timeout) })
- .then((r) => Atomics.store(flag, 0, r.ok ? 1 : 2), () => Atomics.store(flag, 0, 2))
- .finally(() => Atomics.notify(flag, 0));`;
-
-/** Blocking check (a few ms for a refused port, at most `timeoutMs` for a host that doesn't answer). */
-function probeOllamaSync(url: string, timeoutMs = 1500): boolean {
- let ok = false;
- try {
- const sab = new SharedArrayBuffer(4);
- const flag = new Int32Array(sab);
- const worker = new Worker(PROBE_WORKER, { eval: true, workerData: { sab, url: `${url}/api/tags`, timeout: timeoutMs } });
- Atomics.wait(flag, 0, 0, timeoutMs + 1000);
- ok = Atomics.load(flag, 0) === 1;
- void worker.terminate();
- } catch {}
- globalThis.__fuobeOllamaReach = { ok, at: Date.now(), url };
- return ok;
-}
-
/**
- * Routing is synchronous, so it reads the cached answer, refreshed in the background. The first
- * check for an address (right after boot, or after the Ollama URL changes in Settings) waits for a
- * real answer instead: a translate posted then must not fall back to demo text while Ollama is up.
+ * Is a local model server ready? Asks them all (answers kept 15 s); routing reads the cached
+ * answer (see llmBackends), and the first look at a new server waits for a real one.
*/
-function ollamaReady(): boolean {
- const cur = globalThis.__fuobeOllamaReach;
- const url = ollamaUrl();
- if (!cur || cur.url !== url) return probeOllamaSync(url);
- if (Date.now() - cur.at > PROBE_MS) void probeOllama();
- return cur.ok;
-}
+export { probeLocal };
+/** @deprecated The old name: it now asks every local server (Ollama, LM Studio, Unsloth Studio, the custom URL). */
+export const probeOllama = probeLocal;
/** A route, or the part of one that decides its LLMs (the op: only translations fall back to ComfyUI). */
type LlmRoute = Pick<ModelRoute, "endpoint"> & { op?: Operation };
/**
* The LLMs a route may use right now, in the order they're tried. Follows Settings → AI helper
- * ("none" turns text steps off; "ollama" never calls Claude) and the engine mode. An open-source
- * translation with no Ollama answering runs on ComfyUI when that answers.
+ * ("none" turns text steps off; "local" never calls Claude) and the engine mode. An open-source
+ * translation with no local model answering runs on ComfyUI when that answers.
*/
export function llmBackends(route: LlmRoute): Backend[] {
- const choice = getSetting("enhanceProvider");
+ const choice = aiHelper();
if (choice === "none") return [];
const out: Backend[] = [];
const claude = route.endpoint !== "ollama" && !!getSetting("anthropicKey") && (choice === "anthropic" || (choice === "auto" && engineMode() !== "open"));
if (claude) out.push("claude");
- if ((route.endpoint === "ollama" || choice !== "anthropic") && ollamaReady()) out.push("ollama");
+ if ((route.endpoint === "ollama" || choice !== "anthropic") && localReady()) out.push("local");
else if (route.endpoint === "ollama" && route.op === "translate" && comfyProvider.isConfigured()) out.push("comfyui");
return out;
}
-/** What to tell the user when no LLM can run a route (demo mode off). */
-export const llmMissing = (route: LlmRoute) =>
- route.endpoint !== "ollama"
- ? "Connect Claude or Ollama in Settings to run this model"
- : route.op === "translate"
- ? "Connect Ollama, or start ComfyUI with Qwen3.5 4B, in Settings to translate on your own machine"
- : "Connect Ollama in Settings to run this model (open-source text runs on your own machine)";
+/** What to tell the user when no LLM can run a route (demo mode off), with the local server's own reason when it gives one. */
+export function llmMissing(route: LlmRoute): string {
+ const what = localWhat();
+ const base =
+ route.endpoint !== "ollama"
+ ? `Connect Claude or ${what} in Settings to run this model`
+ : route.op === "translate"
+ ? `Connect ${what}, or start ComfyUI with Qwen3.5 4B, in Settings to translate on your own machine`
+ : `Connect ${what} in Settings to run this model (open-source text runs on your own machine)`;
+ const why = localProblem();
+ return why ? `${base}. ${why}` : base;
+}
+
+/** Who runs a route's text, as Settings names them: "Claude or LM Studio"; the open model never uses Claude. */
+export const llmLabel = (route: Pick<ModelRoute, "endpoint">) => (route.endpoint === "ollama" ? localLabel() : `Claude or ${localLabel()}`);
/** Claude is the one that costs money. */
export const llmUsesClaude = (route: Pick<ModelRoute, "endpoint">) => llmBackends(route)[0] === "claude";
@@ -125,7 +92,8 @@ export const llmUsesClaude = (route: Pick<ModelRoute, "endpoint">) => llmBackend
// ---------------------------------------------------------------------------
// Calls
-const BACKEND_LABEL: Record<Backend, string> = { claude: "Claude", ollama: "Ollama", comfyui: "Qwen3.5 on ComfyUI" };
+const BACKEND_LABEL: Record<Exclude<Backend, "local">, string> = { claude: "Claude", comfyui: "Qwen3.5 on ComfyUI" };
+const backendLabel = (b: Backend, job?: LlmJob) => (b === "local" ? (job?.local?.server.label ?? localLabel()) : BACKEND_LABEL[b]);
async function viaClaude(system: string, user: string, signal: AbortSignal): Promise<string> {
const client = new Anthropic({ apiKey: getSetting("anthropicKey") });
@@ -160,33 +128,22 @@ async function viaClaude(system: string, user: string, signal: AbortSignal): Pro
return text;
}
-async function viaOllama(system: string, user: string, signal: AbortSignal): Promise<string> {
- const url = ollamaUrl();
- const model = getSetting("ollamaModel");
- const res = await fetch(`${url}/api/chat`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- model,
- stream: false,
- think: false,
- messages: [
- { role: "system", content: system },
- { role: "user", content: user },
- ],
- options: { num_ctx: 16384 },
- }),
- signal: AbortSignal.any([signal, AbortSignal.timeout(300_000)]),
- }).catch((e: Error) => {
- if (signal.aborted) throw e;
- throw new Error(`Couldn't reach Ollama at ${url} (${e.message}). Is it running?`);
+/** The local server the job started on (Ollama, LM Studio, Unsloth Studio or the custom one), thinking off where it can be. */
+async function viaLocal(system: string, user: string, job: LlmJob, json?: JsonSpec): Promise<string> {
+ const ready = (job.local ??= localReady());
+ if (!ready) throw new Error(llmMissing({ endpoint: "ollama" }));
+ const r = await chatLocal(ready, {
+ messages: [
+ { role: "system", content: system },
+ { role: "user", content: user },
+ ],
+ think: false,
+ json,
+ timeoutMs: 300_000,
+ signal: job.abort.signal,
});
- if (res.status === 404) throw new Error(`Ollama doesn't have ${model} yet — run \`ollama pull ${model}\``);
- if (!res.ok) throw new Error(`Ollama returned ${res.status}: ${(await res.text()).slice(0, 200)}`);
- const j = (await res.json()) as { message?: { content?: string } };
- const text = (j.message?.content ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim();
- if (!text) throw new Error("Ollama returned no text");
- return text;
+ if (!r.text) throw emptyReply(ready.server, r);
+ return r.text;
}
const COMFY_POLL_MS = 500;
@@ -237,15 +194,19 @@ async function viaComfy(system: string, user: string, signal: AbortSignal): Prom
}
}
-const CALL: Record<Backend, (system: string, user: string, signal: AbortSignal) => Promise<string>> = { claude: viaClaude, ollama: viaOllama, comfyui: viaComfy };
+const CALL: Record<Backend, (system: string, user: string, job: LlmJob, json?: JsonSpec) => Promise<string>> = {
+ claude: (system, user, job) => viaClaude(system, user, job.abort.signal),
+ local: viaLocal,
+ comfyui: (system, user, job) => viaComfy(system, user, job.abort.signal),
+};
-/** Ask the first backend; if it fails, the next (Claude → Ollama). Throws the first error when all fail. */
-async function complete(backends: Backend[], system: string, user: string, job: LlmJob): Promise<string> {
+/** Ask the first backend; if it fails, the next (Claude → the local model). Throws the first error when all fail. */
+async function complete(backends: Backend[], system: string, user: string, job: LlmJob, json?: JsonSpec): Promise<string> {
let first: Error | null = null;
for (const b of backends) {
try {
job.backend = b;
- return await CALL[b](system, user, job.abort.signal);
+ return await CALL[b](system, user, job, json);
} catch (e) {
if (job.abort.signal.aborted) throw e;
first ??= e as Error;
@@ -317,7 +278,7 @@ async function pool<T, R>(items: T[], limit: number, f: (item: T) => Promise<R>)
}
export interface TranslateCuesOptions {
- /** Requests in flight at once for cue-by-cue translation (1 for Ollama, which serves one at a time). */
+ /** Requests in flight at once for cue-by-cue translation (1 for a local model, which serves one at a time). */
concurrency?: number;
onProgress?: (done: number) => void;
}
@@ -355,6 +316,8 @@ interface LlmJob {
state: "running" | "succeeded" | "failed";
progress?: number;
backend?: Backend;
+ /** The local server the job runs on (chosen when it starts). */
+ local?: Ready | null;
outputs?: RemoteOutput[];
error?: string;
abort: AbortController;
@@ -363,13 +326,21 @@ interface LlmJob {
const jobs = (): Map<string, LlmJob> => (globalThis.__fuobeLlmJobs ??= new Map<string, LlmJob>());
+/** extra.json on a write: the JSON Schema the answer follows (Faceless topics and scripts), or "object". */
+function jsonSpec(v: unknown): JsonSpec | undefined {
+ if (v === "object") return "object";
+ if (!v || typeof v !== "object") return undefined;
+ const { name, schema } = v as { name?: unknown; schema?: unknown };
+ return typeof name === "string" && /^[\w-]{1,64}$/.test(name) && schema && typeof schema === "object" && !Array.isArray(schema) ? { name, schema: schema as Record<string, unknown> } : undefined;
+}
+
async function runJob(op: string, input: GenInput, backends: Backend[], job: LlmJob): Promise<RemoteOutput[]> {
- const ask = (system: string, user: string) => complete(backends, system, user, job);
+ const ask = (system: string, user: string, json?: JsonSpec) => complete(backends, system, user, job, json);
const source = (input.prompt ?? "").trim();
if (op === "write") {
const custom = typeof input.extra?.system === "string" ? input.extra.system.trim() : "";
if (!source) throw new Error("Write a brief first");
- return [textOutput(await ask(custom || WRITE_SYSTEM, source), null, { op: "write" })];
+ return [textOutput(await ask(custom || WRITE_SYSTEM, source, jsonSpec(input.extra?.json)), null, { op: "write" })];
}
if (op !== "translate") throw new Error(`The LLM can't do ${op}`);
const lang = input.targetLanguage ?? (typeof input.extra?.targetLanguage === "string" ? input.extra.targetLanguage : "");
@@ -378,7 +349,7 @@ async function runJob(op: string, input: GenInput, backends: Backend[], job: Llm
const from = input.sourceLanguage;
const cues = parseCues(source);
if (cues) {
- // Claude takes a few cues at once; Ollama works through requests one by one.
+ // Claude takes a few cues at once; a local model works through requests one by one.
const translated = await translateCues(cues, lang, from, ask, { concurrency: backends[0] === "claude" ? 4 : 1, onProgress: (done) => (job.progress = Math.min(0.95, done / cues.length)) });
return [textOutput(cueText(translated), translated, { language: lang })];
}
@@ -393,7 +364,10 @@ async function runJob(op: string, input: GenInput, backends: Backend[], job: Llm
export const llmProvider: ProviderAdapter = {
id: "llm",
- label: "Claude or Ollama",
+ /** "Claude or LM Studio": the local server in use (or pinned), "a local model" when none answers. */
+ get label() {
+ return llmLabel({ endpoint: "auto" });
+ },
isConfigured: () => llmBackends({ endpoint: "auto" }).length > 0,
// Text steps read their text from the prompt; files aren't sent anywhere.
@@ -407,19 +381,22 @@ export const llmProvider: ProviderAdapter = {
const all = jobs();
for (const [id, j] of all) if (Date.now() - j.at > 6 * 3_600_000) all.delete(id);
const id = `llm_${nanoid(10)}`;
- const job: LlmJob = { state: "running", abort: new AbortController(), at: Date.now(), backend: backends[0] };
+ // The local server is fixed when the job starts: its calls all go to the same one.
+ const local = backends.includes("local") ? localReady() : null;
+ const job: LlmJob = { state: "running", abort: new AbortController(), at: Date.now(), backend: backends[0], local };
all.set(id, job);
runJob(route.op, input, backends, job).then(
(outputs) => Object.assign(job, { state: "succeeded", outputs }),
(e: Error) => Object.assign(job, { state: "failed", error: e.message || "The LLM failed" }),
);
- return { externalId: id, meta: { backends }, payload: { op: route.op, backends, targetLanguage: input.targetLanguage, chars: input.prompt?.length ?? 0 } };
+ const server = local && { local: local.server.kind, model: local.server.model || local.status.model };
+ return { externalId: id, meta: { backends }, payload: { op: route.op, backends, ...server, targetLanguage: input.targetLanguage, chars: input.prompt?.length ?? 0 } };
},
async poll({ externalId }) {
const job = jobs().get(externalId);
if (!job) return { state: "failed", error: "Interrupted — the server restarted while this was being written. Try again." };
- if (job.state === "running") return { state: "running", progress: job.progress, message: `Writing with ${BACKEND_LABEL[job.backend ?? "claude"]}` };
+ if (job.state === "running") return { state: "running", progress: job.progress, message: `Writing with ${backendLabel(job.backend ?? "claude", job)}` };
jobs().delete(externalId);
return job.state === "succeeded" ? { state: "succeeded", outputs: job.outputs ?? [] } : { state: "failed", error: job.error ?? "The LLM failed" };
},
@@ -430,8 +407,8 @@ export const llmProvider: ProviderAdapter = {
},
async test() {
- await probeOllama(true);
+ await probeLocal(true);
const b = llmBackends({ endpoint: "auto" });
- return b.length ? { ok: true, detail: `Text steps run on ${b.map((x) => BACKEND_LABEL[x]).join(", then ")}` } : { ok: false, detail: "Add an Anthropic key or start Ollama" };
+ return b.length ? { ok: true, detail: `Text steps run on ${b.map((x) => backendLabel(x)).join(", then ")}` } : { ok: false, detail: llmMissing({ endpoint: "auto" }) };
},
};
diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.ts
index 2f547810..a98204d2 100644
--- a/src/server/providers/mock.ts
+++ b/src/server/providers/mock.ts
@@ -194,7 +194,7 @@ function demoTranslate(source: string, language: string): DemoOutput {
.map((l) => (l.trim() ? tag(l) : l))
.join("\n")
: tag("Demo translation");
- return textOutput(`${body}\n\n(Demo translation — connect Claude or Ollama in Settings to translate for real.)`, null, { language, demo: true });
+ return textOutput(`${body}\n\n(Demo translation — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings to translate for real.)`, null, { language, demo: true });
}
function demoWrite(brief: string): DemoOutput {
@@ -209,7 +209,7 @@ function demoWrite(brief: string): DemoOutput {
"BEAT 3 — A close-up detail that makes it feel real.",
"CLOSE — One line call to action.",
"",
- "(Demo text — connect Claude or Ollama in Settings to write for real.)",
+ "(Demo text — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings to write for real.)",
].join("\n"),
null,
{ demo: true },
diff --git a/src/server/settings.ts b/src/server/settings.ts
index eadd3061..e6ee4c9e 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -8,7 +8,8 @@ import { db } from "./db";
*/
export interface SettingDef {
key: string;
- env?: string;
+ /** Env var(s) that give the value when Settings has none; the first one set wins. */
+ env?: string | readonly string[];
secret?: boolean;
default?: string;
/** Allowed values (validated on save). */
@@ -40,17 +41,39 @@ export const SETTINGS = {
aiToolkitDatasetDir: { key: "aitk.datasetDir", env: "AI_TOOLKIT_DATASET_DIR" },
/** "auto" = demo outputs only when the chosen provider is not configured. */
demoMode: { key: "demo.mode", env: "FUOBE_DEMO_MODE", default: "auto", options: ["auto", "on", "off"] },
- enhanceProvider: { key: "enhance.provider", env: "FUOBE_ENHANCE_PROVIDER", default: "auto", options: ["auto", "anthropic", "ollama", "none"] },
+ /** Settings → AI helper: Claude, a local model, or offline. "ollama" is the old name of "local" and still means it. */
+ enhanceProvider: { key: "enhance.provider", env: "FUOBE_ENHANCE_PROVIDER", default: "auto", options: ["auto", "anthropic", "local", "ollama", "none"] },
+ /** Which local model server: "auto" uses the first that answers (Ollama, LM Studio, Unsloth Studio, then the custom URL). */
+ llmProvider: { key: "llm.provider", env: "FUOBE_LLM_PROVIDER", default: "auto", options: ["auto", "ollama", "lmstudio", "unsloth", "custom"] },
ollamaUrl: { key: "ollama.url", env: "OLLAMA_URL", default: "http://127.0.0.1:11434" },
ollamaModel: { key: "ollama.model", env: "OLLAMA_MODEL", default: "qwen3:8b" },
+ lmstudioUrl: { key: "lmstudio.url", env: "LMSTUDIO_URL", default: "http://127.0.0.1:1234" },
+ /** Empty: a loaded model, else one trained for tool use. */
+ lmstudioModel: { key: "lmstudio.model", env: "LMSTUDIO_MODEL" },
+ /** Only when LM Studio's "Require Authentication" is on (LM_API_TOKEN also works). */
+ lmstudioToken: { key: "lmstudio.token", env: ["LMSTUDIO_API_TOKEN", "LM_API_TOKEN"], secret: true },
+ unslothUrl: { key: "unsloth.url", env: "UNSLOTH_URL", default: "http://127.0.0.1:8888" },
+ /** Empty: the model loaded in Unsloth Studio. */
+ unslothModel: { key: "unsloth.model", env: "UNSLOTH_MODEL" },
+ /** An sk-unsloth-… key (UNSLOTH_STUDIO_AUTH_TOKEN also works); empty for keyless access. */
+ unslothKey: { key: "unsloth.key", env: ["UNSLOTH_API_KEY", "UNSLOTH_STUDIO_AUTH_TOKEN"], secret: true },
+ /** Any other OpenAI-compatible server (llama.cpp's llama-server, vLLM, Jan…): its base URL. */
+ llmUrl: { key: "llm.url", env: "FUOBE_LLM_URL" },
+ llmModel: { key: "llm.model", env: "FUOBE_LLM_MODEL" },
+ llmKey: { key: "llm.key", env: "FUOBE_LLM_API_KEY", secret: true },
+ /** Tokens of context the local model gets (Ollama's num_ctx; LM Studio loads models with it). 0 = the server's own setting. */
+ llmContext: { key: "llm.context", env: "FUOBE_LLM_CONTEXT", default: "16384" },
} satisfies Record<string, SettingDef>;
export type SettingName = keyof typeof SETTINGS;
+/** The first of a setting's env vars that is set. */
+const envValue = (def: SettingDef): string | undefined => [def.env ?? []].flat().map((n) => process.env[n]).find((v) => !!v);
+
export function getSetting(name: SettingName): string {
const def: SettingDef = SETTINGS[name];
const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(def.key) as { value: string } | undefined;
- const value = row && row.value !== "" ? row.value : def.env && process.env[def.env] ? process.env[def.env]! : (def.default ?? "");
+ const value = row && row.value !== "" ? row.value : (envValue(def) ?? def.default ?? "");
// An invalid env/db value falls back to the default instead of breaking routing.
if (def.options && !def.options.includes(value)) return def.default ?? "";
return value;
@@ -62,12 +85,26 @@ export function engineMode(): EngineMode {
return getSetting("engineMode") as EngineMode;
}
+/**
+ * A context size as people write it: 16384, "16,384" or "16k" (k = 1024 tokens). 0 leaves it to the
+ * server. Null: not a size, or under 2048 tokens (too small for any step; "16" was meant as 16k).
+ */
+export function parseContext(value: string): number | null {
+ const m = /^(\d+(?:\.\d+)?)(k?)$/i.exec(value.replace(/[,_\s]/g, ""));
+ if (!m) return null;
+ const n = Math.round(Number(m[1]) * (m[2] ? 1024 : 1));
+ return n === 0 ? 0 : n >= 2048 ? Math.min(n, 1_048_576) : null;
+}
+
/** Throws a user-facing message if the setting value isn't allowed. */
export function validateSetting(name: SettingName, value: string): void {
const def: SettingDef = SETTINGS[name];
if (value !== "" && def.options && !def.options.includes(value)) {
throw new Error(`${name} must be one of: ${def.options.join(", ")}`);
}
+ if (name === "llmContext" && value !== "" && parseContext(value) === null) {
+ throw new Error("llmContext must be a number of tokens of at least 2048 (such as 16384 or 16k), or 0 to leave it to the server");
+ }
}
export function setSetting(name: SettingName, value: string): void {
@@ -105,7 +142,7 @@ export function publicSettings(): PublicSetting[] {
name,
value: def.secret ? mask(value) : value,
secret: !!def.secret,
- fromEnv: !row && !!def.env && !!process.env[def.env],
+ fromEnv: !row && !!envValue(def),
isSet: !!value && value !== def.default,
};
});
diff --git a/src/server/storyboard.ts b/src/server/storyboard.ts
index 93016ba0..9765d386 100644
--- a/src/server/storyboard.ts
+++ b/src/server/storyboard.ts
@@ -23,7 +23,9 @@ export interface StoryboardRequest {
/** Split a story into scenes with the configured LLM, or a deterministic shot list offline. */
export async function splitStory(story: string, n: number): Promise<string[]> {
- const text = await llmText(SPLIT_SYSTEM, `Story: ${story}\nFrames: ${n}`);
+ // A local model that decodes to a schema gets exactly n strings (the prompt asks for the same array).
+ const json = { name: "frames", schema: { type: "array", items: { type: "string" }, minItems: n, maxItems: n } };
+ const text = await llmText(SPLIT_SYSTEM, `Story: ${story}\nFrames: ${n}`, { json });
return (text && parseScenes(text, n)) || heuristicScenes(story, n);
}
diff --git a/tests/assist-context.test.ts b/tests/assist-context.test.ts
index f028b4b3..1f1e7736 100644
--- a/tests/assist-context.test.ts
+++ b/tests/assist-context.test.ts
@@ -167,8 +167,17 @@ describe("modes", () => {
expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ mode: "free", agent: "offline", note: expect.stringMatching(/Anthropic API key/) });
expect(await agent.resolveMode({ mode: "manual", agent: "claude", model: "claude-haiku-5-5" })).toMatchObject({ agent: "offline", note: expect.any(String) });
expect(await agent.resolveMode({ mode: "manual", agent: "offline" })).toMatchObject({ mode: "manual", agent: "offline" });
- expect(await agent.resolveMode({ mode: "manual", agent: "ollama", model: "llama3.2:3b" })).toMatchObject({ agent: "ollama", model: "llama3.2:3b", note: expect.stringMatching(/Ollama isn't answering/) });
- expect(await agent.resolveMode({ mode: "manual", agent: "ollama", model: "bad name; rm -rf" })).toMatchObject({ model: null });
+ expect(await agent.resolveMode({ mode: "manual", agent: "local", model: "llama3.2:3b" })).toMatchObject({
+ agent: "local",
+ model: "llama3.2:3b",
+ note: expect.stringMatching(/No local model server is answering \(Ollama, LM Studio or Unsloth Studio\)/),
+ });
+ expect(await agent.resolveMode({ mode: "manual", agent: "local", model: "bad name; rm -rf" })).toMatchObject({ model: null });
+ // LM Studio names its models publisher/model@quant.
+ expect(await agent.resolveMode({ mode: "manual", agent: "local", model: "qwen/qwen3-8b@q4_k_m" })).toMatchObject({ model: "qwen/qwen3-8b@q4_k_m" });
+ // A choice saved by an older browser still says "ollama".
+ const { ModeChoice } = await import("@/server/assist/schemas");
+ expect(await agent.resolveMode(ModeChoice.parse({ mode: "manual", agent: "ollama", model: "llama3.2:3b" }))).toMatchObject({ mode: "manual", agent: "local", model: "llama3.2:3b" });
setSetting("enhanceProvider", "none");
expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ agent: "offline", note: expect.stringMatching(/AI helper is off/) });
setSetting("enhanceProvider", "auto");
diff --git a/tests/assist-runtime.test.ts b/tests/assist-runtime.test.ts
index 74e43b64..f0f7df58 100644
--- a/tests/assist-runtime.test.ts
+++ b/tests/assist-runtime.test.ts
@@ -82,7 +82,7 @@ describe("offline planner (U18)", () => {
expect(said.text).not.toContain(agent.OFFLINE_NOTE);
const at = v.thread.items.findIndex((i) => i.role === "approval");
expect(v.thread.items[at + 1]).toMatchObject({ role: "notice", tone: "info", text: agent.OFFLINE_NOTE });
- expect(agent.OFFLINE_NOTE).toBe("Offline planner — connect Claude or Ollama in Settings for better plans.");
+ expect(agent.OFFLINE_NOTE).toBe("Offline planner — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for better plans.");
const card = v.thread.items.find((i) => i.role === "approval") as { jobs: { kind: string; op: string; error?: string }[] };
expect(card.jobs.map((j) => [j.kind, j.op, j.error])).toEqual([
["image", "t2i", undefined],
@@ -169,7 +169,7 @@ describe("new kinds and operations in the tools", () => {
it("finds text models and runs chained jobs, returning text inline", async () => {
const found = await tools.executeTool("search_models", { kind: "text", task: "translate" }, { engine: "open" });
const models = JSON.parse(found.content as string).models as { id: string; engine: string }[];
- expect(models[0]).toMatchObject({ id: "oss-text-llm", engine: "open source (Ollama, on this machine)" });
+ expect(models[0]).toMatchObject({ id: "oss-text-llm", engine: "open source (a local model, on this machine)" });
expect(models.map((m) => m.id)).toContain("text-llm");
const out = await tools.executeTool(
diff --git a/tests/assist-studio-routes.test.ts b/tests/assist-studio-routes.test.ts
index fe29bc3c..e8f2b0e8 100644
--- a/tests/assist-studio-routes.test.ts
+++ b/tests/assist-studio-routes.test.ts
@@ -237,13 +237,13 @@ describe("Translate & dub", () => {
expect(gen(b.results[0])).toMatchObject({ modelId: "elevenlabs-dubbing", op: "dub" });
});
- it("with a fal key but no Claude or Ollama, dubs in one go rather than plan a review that can't start", async () => {
+ it("with a fal key but no Claude or local model, dubs in one go rather than plan a review that can't start", async () => {
// The review's translation would run as a demo among real steps, which createPipeline refuses.
const p = await priced(() => plan("dub_video", { video: clip, languages: ["Spanish"] }));
expect(p).toMatchObject({ studio: "Translate & dub", href: "/audio/translate" });
expect(p.jobs).toEqual([expect.objectContaining({ modelId: "heygen-translate", op: "dub", demo: false })]);
expect(p.jobs[0].error).toBeUndefined();
- expect(p.jobs[0].note).toMatch(/Reviewing the lines can't start: Translate · Spanish would run as a demo \(it needs Claude or Ollama\).*dubs in one go with HeyGen Translate/);
+ expect(p.jobs[0].note).toMatch(/Reviewing the lines can't start: Translate · Spanish would run as a demo \(it needs Claude or a local model\).*dubs in one go with HeyGen Translate/);
expect((await priced(() => estimate("dub_video", { video: clip, languages: ["Spanish"] }))).result.isError).toBe(false);
// A review asked for outright isn't swapped: the card says why it can't start, and nothing is made.
const asked = await priced(() => plan("dub_video", { video: clip, languages: ["Spanish"], review: true }));
diff --git a/tests/assist.test.ts b/tests/assist.test.ts
index 161ba7b7..cf801f0f 100644
--- a/tests/assist.test.ts
+++ b/tests/assist.test.ts
@@ -236,7 +236,7 @@ describe("claude request", () => {
});
});
-describe("ollama agent", () => {
+describe("local agent on Ollama", () => {
it("talks to Ollama's chat API with tools and maps its tool calls back", async () => {
const http = await import("node:http");
const seen: { messages: { role: string; content: string; tool_calls?: unknown[]; tool_name?: string }[]; tools: { function: { name: string } }[]; model: string }[] = [];
@@ -259,8 +259,10 @@ describe("ollama agent", () => {
setSetting("ollamaUrl", `http://127.0.0.1:${port}`);
setSetting("ollamaModel", "qwen3:8b");
try {
- expect(await agent.resolveAgent()).toBe("ollama");
+ expect(await agent.resolveAgent()).toBe("local");
+ // "ollama", the agent's old name, still makes a local chat.
const t = agent.createThread({ engine: "open", agent: "ollama" });
+ expect(t.agent).toBe("local");
agent.addMessage(t.id, "Which image model should I use?");
await agent.run(t.id);
expect(seen).toHaveLength(2);
diff --git a/tests/av-tools.test.ts b/tests/av-tools.test.ts
index ff188ca2..ed2d2c32 100644
--- a/tests/av-tools.test.ts
+++ b/tests/av-tools.test.ts
@@ -107,7 +107,7 @@ describe("caption style → burn params", () => {
describe("3D viewer data flow", () => {
it("asks the engine's 3D model for the photo; an unknown pick falls back to the default", () => {
expect(model3dRequest({ engine: "cloud", photo: "p.png" })).toEqual({ feature: "image-to-3d", modelId: "hunyuan-3d-3-1-pro", op: "image-to-3d", inputs: { images: ["p.png"] } });
- expect(model3dRequest({ engine: "open", photo: "p.png", modelId: "trellis-2" }).modelId).toBe("oss-trellis2");
+ expect(model3dRequest({ engine: "open", photo: "p.png", modelId: "trellis-2" }).modelId).toBe("oss-pixal3d");
expect(model3dRequest({ engine: "cloud", photo: "p.png", modelId: "tripo-h3-1" }).modelId).toBe("tripo-h3-1");
for (const m of [...MODELS_3D.cloud, ...MODELS_3D.open]) expect(getModel(m.id)?.routes.some((r) => r.op === "image-to-3d"), m.id).toBe(true);
});
@@ -118,7 +118,7 @@ describe("3D viewer data flow", () => {
"image-to-3d",
);
const view = model3dView({ outputs: outputs.map((o) => ({ ...o, meta: o.meta ?? {} })) as never, request: model3dRequest({ engine: "cloud", photo: "/api/files/p.png" }) });
- expect(view).toEqual({ glb: "https://cdn/x/model.glb", poster: "https://cdn/x/thumb.png", photo: "/api/files/p.png", turntable: undefined, formats: { glb: "https://cdn/x/model.glb", obj: "https://cdn/x/model.obj", usdz: "https://cdn/x/model.usdz" } });
+ expect(view).toEqual({ glb: "https://cdn/x/model.glb", web: "https://cdn/x/model.glb", poster: "https://cdn/x/thumb.png", photo: "/api/files/p.png", turntable: undefined, formats: { glb: "https://cdn/x/model.glb", obj: "https://cdn/x/model.obj", usdz: "https://cdn/x/model.usdz" } });
const href = animateSpinHref(view)!;
expect(href.startsWith("/video?")).toBe(true);
expect(new URLSearchParams(href.split("?")[1]).get("image")).toBe("/api/files/p.png");
@@ -128,7 +128,7 @@ describe("3D viewer data flow", () => {
expect(new URLSearchParams(recorded.split("?")[1]).get("video")).toBe("/api/files/turn.webm");
});
- it("a TRELLIS.2 / demo result brings its own turntable", () => {
+ it("an open (server-rendered) / demo result brings its own turntable", () => {
const view = model3dView({
outputs: [
{ url: "/api/files/m.glb", kind: "model3d", meta: { format: "glb" } },
@@ -175,7 +175,7 @@ describe("apps on the new models", () => {
expect(plan("app-product-shot", "cloud").model.id).toBe("bria-product-shot");
expect(plan("app-product-shot", "open").model.id).toBe("oss-product-shot");
expect(plan("app-image-to-3d", "cloud").model.id).toBe("hunyuan-3d-3-1-pro");
- expect(plan("app-image-to-3d", "open").model.id).toBe("oss-trellis2");
+ expect(plan("app-image-to-3d", "open").model.id).toBe("oss-pixal3d");
});
it("Angles: the choices set the camera sliders on the cloud and the LoRA's words on the open engine", () => {
diff --git a/tests/comfy-provider.test.ts b/tests/comfy-provider.test.ts
index 556c1f26..b012ddd7 100644
--- a/tests/comfy-provider.test.ts
+++ b/tests/comfy-provider.test.ts
@@ -242,18 +242,11 @@ describe("ComfyUI output mapping", () => {
expect(outs[3].meta?.cues).toBeUndefined();
});
- it("reads Save3D's ui['3d'] as a .glb model and the turntable as video", () => {
- const outs = collectOutputs(
- done({
- "322": { "3d": [file("product_00001_.glb", "fuobe")], camera_info: [{ position: { x: 1 } }], model_3d_info: [] },
- "702": { images: [file("turntable_00001_.mp4")], animated: [true] },
- }),
- manifestOf("image-to-3d-trellis2"),
- );
- expect(outs.map((o) => [o.kind, o.contentType, o.meta?.role])).toEqual([
- ["model3d", "model/gltf-binary", undefined],
- ["video", undefined, "turntable"],
- ]);
+ it("reads Save3D's ui['3d'] as a .glb model (the turntable is rendered after the job, not in the graph)", () => {
+ for (const id of ["image-to-3d-pixal3d", "image-to-3d-trellis2"]) {
+ const outs = collectOutputs(done({ "322": { "3d": [file("product_00001_.glb", "fuobe")], camera_info: [{ position: { x: 1 } }], model_3d_info: [] } }), manifestOf(id));
+ expect(outs.map((o) => [o.kind, o.contentType, o.meta?.role]), id).toEqual([["model3d", "model/gltf-binary", undefined]]);
+ }
});
it("returns layers back to front with z, name and a bounding box from alpha (one download each)", async () => {
@@ -381,7 +374,7 @@ const ROUND3 = [
"style-ref-uso-flux1", "palette-zimage-hex", "video-trim", "video-segment-resample", "video-restyle-wan22-fun-vace", "mixed-media-zimage-frames",
"sfx-stable-audio-3-small", "sfx-stable-audio-open", "sfx-hunyuan-foley", "sfx-mmaudio-t2a", "sfx-thinksound", "dub-prepare-separate-transcribe",
"captions-qwen3-asr", "captions-burnin", "captions-whisper-burnin", "translate-qwen35-textgen", "speech-translate-gemma4", "lipsync-v2v-infinitetalk",
- "lipsync-latentsync16", "video-mux-audio", "video-mux-audio-replace", "image-to-3d-trellis2", "image-to-3d-hunyuan3d-21", "tryon-flux2-klein-4b",
+ "lipsync-latentsync16", "video-mux-audio", "video-mux-audio-replace", "image-to-3d-pixal3d", "image-to-3d-trellis2", "image-to-3d-hunyuan3d-21", "tryon-flux2-klein-4b",
"grid-zimage-contact-sheet", "soul-cast-sheet-zimage",
];
const LOADERS: Record<string, string> = { LoadImage: "image", LoadImageMask: "image", LoadVideo: "file", VHS_LoadVideo: "video", LoadAudio: "audio" };
diff --git a/tests/llm.test.ts b/tests/llm.test.ts
index c88d71b1..f8f9a0fe 100644
--- a/tests/llm.test.ts
+++ b/tests/llm.test.ts
@@ -137,10 +137,10 @@ describe("LLM provider", () => {
it("uses Claude when a key is set (falling back to Ollama), never on the open model", async () => {
await useOllama(true);
setSetting("anthropicKey", "sk-ant-test");
- expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["claude", "ollama"]);
- expect(llm.llmBackends({ endpoint: "ollama" })).toEqual(["ollama"]);
+ expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["claude", "local"]);
+ expect(llm.llmBackends({ endpoint: "ollama" })).toEqual(["local"]);
setSetting("engineMode", "open");
- expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["ollama"]);
+ expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["local"]);
expect(() => gens.createGenerations({ feature: "dub", modelId: "text-llm", op: "translate", prompt: "x", params: { targetLanguage: "Spanish" } })).toThrow(/open source only/);
setSetting("engineMode", "");
setSetting("enhanceProvider", "none");
@@ -185,8 +185,8 @@ describe("LLM provider", () => {
const [w] = gens.createGenerations({ feature: "ads", modelId: "oss-text-llm", op: "write", prompt: "A tagline for a bakery" });
expect((await settle(w.id)).outputs[0].text).toMatch(/Demo script for: A tagline for a bakery/);
setSetting("demoMode", "off");
- expect(() => gens.createGenerations({ feature: "dub", modelId: "text-llm", op: "translate", prompt: "x", params: { targetLanguage: "Italian" } })).toThrow(/Connect Claude or Ollama in Settings/);
- expect(() => gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "write", prompt: "x" })).toThrow(/Connect Ollama in Settings/);
+ expect(() => gens.createGenerations({ feature: "dub", modelId: "text-llm", op: "translate", prompt: "x", params: { targetLanguage: "Italian" } })).toThrow(/Connect Claude or a local model \(Ollama, LM Studio or Unsloth Studio\) in Settings/);
+ expect(() => gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "write", prompt: "x" })).toThrow(/Connect a local model \(Ollama, LM Studio or Unsloth Studio\) in Settings/);
});
it("asks for a language before translating", () => {
@@ -373,7 +373,7 @@ describe("open translation without Ollama: Qwen3.5 on ComfyUI", () => {
expect((await settle(a.id)).outputs[0]).toMatchObject({ kind: "text", text: "(German·qwen) Good morning, friends." });
await useOllama(true);
prompts.length = 0;
- expect(llm.llmBackends({ endpoint: "ollama", op: "translate" })).toEqual(["ollama"]);
+ expect(llm.llmBackends({ endpoint: "ollama", op: "translate" })).toEqual(["local"]);
const [b] = gens.createGenerations({ feature: "captions", modelId: "oss-text-llm", op: "translate", prompt: "Good night.", params: { targetLanguage: "German" } });
expect((await settle(b.id)).outputs[0].text).toBe("(German) Good night.");
expect(prompts).toHaveLength(0);
@@ -390,6 +390,6 @@ describe("open translation without Ollama: Qwen3.5 on ComfyUI", () => {
await probeComfy(true);
expect(llm.llmBackends({ endpoint: "ollama", op: "translate" })).toEqual([]);
setSetting("demoMode", "off");
- expect(() => gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: "x", params: { targetLanguage: "French" } })).toThrow(/Connect Ollama, or start ComfyUI with Qwen3\.5 4B/);
+ expect(() => gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: "x", params: { targetLanguage: "French" } })).toThrow(/Connect a local model \(Ollama, LM Studio or Unsloth Studio\), or start ComfyUI with Qwen3\.5 4B/);
});
});
diff --git a/tests/local-llm.test.ts b/tests/local-llm.test.ts
new file mode 100644
index 00000000..f85e16d3
--- /dev/null
+++ b/tests/local-llm.test.ts
@@ -0,0 +1,748 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import type Anthropic from "@anthropic-ai/sdk";
+import type { Generation } from "@/lib/catalog/types";
+
+/*
+ * Local LLM servers besides Ollama: LM Studio, Unsloth Studio and any OpenAI-compatible server
+ * (llama.cpp's llama-server here). The wire builders and parsers are tested on their own; then
+ * stand-in servers on this machine answer Fuobe's real code paths (Enhance, a storyboard split, a
+ * text step, an Assist chat with a tool call, /api/status and /api/llm).
+ */
+
+vi.setConfig({ testTimeout: 60_000 });
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-local-llm-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+// Keys from this machine's environment must not reach the stand-ins.
+for (const k of ["LM_API_TOKEN", "LMSTUDIO_API_TOKEN", "UNSLOTH_API_KEY", "UNSLOTH_STUDIO_AUTH_TOKEN", "FUOBE_LLM_URL", "FUOBE_LLM_API_KEY", "FUOBE_LLM_PROVIDER", "FUOBE_ENHANCE_PROVIDER"]) delete process.env[k];
+
+const { parseContext, publicSettings, setSetting, validateSetting } = await import("@/server/settings");
+const local = await import("@/server/llm");
+const wire = await import("@/server/llm/wire");
+const messages = await import("@/server/llm/messages");
+const { interpret } = await import("@/server/llm/probe");
+const { httpError, rejectsJson } = await import("@/server/llm/errors");
+const llm = await import("@/server/providers/llm");
+const gens = await import("@/server/generations");
+const { enhancePrompt, llmText } = await import("@/server/enhance");
+const { splitStory } = await import("@/server/storyboard");
+const agent = await import("@/server/assist/agent");
+
+type Body = Record<string, unknown> & { messages?: { role: string; content: string | null; tool_calls?: { id: string; type: string; function: { name: string; arguments: string } }[]; tool_call_id?: string }[] };
+interface Seen {
+ method: string;
+ url: string;
+ auth?: string;
+ body: Body;
+}
+
+/** A stand-in HTTP server on a free port: `handle` answers each request (JSON), every request is kept in `seen`. */
+function stub(handle: (r: Seen, res: http.ServerResponse) => unknown) {
+ const seen: Seen[] = [];
+ const server = http.createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", async () => {
+ const r: Seen = { method: req.method ?? "GET", url: req.url ?? "/", auth: req.headers.authorization, body: raw ? (JSON.parse(raw) as Body) : {} };
+ seen.push(r);
+ const out = await handle(r, res);
+ if (out === undefined || res.writableEnded) return;
+ res.setHeader("content-type", "application/json");
+ res.end(JSON.stringify(out));
+ });
+ });
+ const s = {
+ seen,
+ url: "",
+ chats: () => seen.filter((r) => r.url.endsWith("/chat/completions") || r.url === "/api/chat").map((r) => r.body),
+ start: () => new Promise<void>((done) => server.listen(0, "127.0.0.1", () => ((s.url = `http://127.0.0.1:${(server.address() as { port: number }).port}`), done()))),
+ close: () => server.close(),
+ };
+ return s;
+}
+
+const fail = (res: http.ServerResponse, status: number, body: unknown) => {
+ res.statusCode = status;
+ return body;
+};
+
+/** An OpenAI chat.completion with one choice. */
+const completion = (message: Record<string, unknown>, finish = "stop", model = "qwen/qwen3-8b") =>
+ ({
+ id: "chatcmpl-1",
+ object: "chat.completion",
+ model,
+ choices: [{ index: 0, message: { role: "assistant", ...message }, finish_reason: finish }],
+ }) as unknown as Parameters<typeof wire.parseOpenai>[0];
+
+const lastUser = (b: Body) => (b.messages ?? []).filter((m) => m.role === "user").at(-1)?.content ?? "";
+const systemOf = (b: Body) => (b.messages?.[0]?.role === "system" ? (b.messages[0].content ?? "") : "");
+
+/** "[1] Hello" lines back as "[1] (lang) Hello", like the stand-in Ollama in llm.test.ts. */
+function translate(b: Body, tag: string): string {
+ const lang = /into (\w+)/.exec(systemOf(b))?.[1] ?? "??";
+ const user = lastUser(b);
+ return /^\[\d+\]/.test(user)
+ ? user
+ .split("\n")
+ .map((l) => l.replace(/^\[(\d+)\]\s*/, (_, n) => `[${n}] (${lang}·${tag}) `))
+ .join("\n")
+ : `(${lang}·${tag}) ${user}`;
+}
+
+/**
+ * A stand-in LM Studio 0.4: its own model list (one LLM trained for tool use, one embedding model),
+ * load and unload, the OpenAI model list and chat completions with tools, JSON schemas and thinking.
+ */
+function lmStudio(opts: { token?: string; loaded?: number } = {}) {
+ const state = { context: opts.loaded ?? null as number | null, loads: [] as Body[], unloads: [] as Body[], aborted: 0 };
+ const s = stub((r, res) => {
+ if (opts.token && r.auth !== `Bearer ${opts.token}`) return fail(res, 401, { error: "Unauthorized: this server requires an API token" });
+ if (r.url === "/api/v1/models") {
+ return {
+ models: [
+ {
+ type: "llm",
+ publisher: "qwen",
+ key: "qwen/qwen3-8b",
+ display_name: "Qwen3 8B",
+ loaded_instances: state.context ? [{ id: "qwen/qwen3-8b", config: { context_length: state.context } }] : [],
+ max_context_length: 32768,
+ format: "gguf",
+ capabilities: { vision: false, trained_for_tool_use: true },
+ },
+ { type: "embedding", publisher: "nomic-ai", key: "text-embedding-nomic-embed-text-v1.5", loaded_instances: [], max_context_length: 2048, format: "gguf" },
+ ],
+ };
+ }
+ if (r.url === "/v1/models") return { object: "list", data: [{ id: "qwen/qwen3-8b" }, { id: "text-embedding-nomic-embed-text-v1.5" }] };
+ if (r.url === "/api/v1/models/load") {
+ state.loads.push(r.body);
+ state.context = r.body.context_length as number;
+ return { type: "llm", instance_id: r.body.model, load_time_seconds: 2.5, status: "loaded", load_config: { context_length: r.body.context_length } };
+ }
+ if (r.url === "/api/v1/models/unload") {
+ state.unloads.push(r.body);
+ state.context = null;
+ return { instance_id: r.body.instance_id };
+ }
+ if (r.url !== "/v1/chat/completions") return fail(res, 404, { error: "Unexpected endpoint" });
+ const b = r.body;
+ const user = lastUser(b);
+ if (user.includes("OVERFLOW")) {
+ return fail(res, 400, { error: "Trying to keep the first 9000 tokens when context the overflows. However, the model is loaded with context length of only 4096 tokens, which is not enough. Try to load the model with a larger context length" });
+ }
+ if (user.includes("THINK FOREVER")) return completion({ content: "", reasoning_content: "Let me think about this for a very long time…" }, "length");
+ if (user.includes("SLOW")) {
+ res.on("close", () => !res.writableEnded && state.aborted++);
+ return undefined;
+ }
+ if (b.tools) {
+ // Assist: look up models first, answer once the tool's result is back.
+ if (!b.messages?.some((m) => m.role === "tool")) {
+ return completion({ content: "Let me look.", tool_calls: [{ id: "call_8f2", type: "function", function: { name: "search_models", arguments: '{"kind":"image"}' } }] }, "tool_calls");
+ }
+ return completion({ content: "Nano Banana Pro is a great pick.", reasoning_content: "The search found it." });
+ }
+ const format = b.response_format as { json_schema?: { name?: string; schema?: { minItems?: number } } } | undefined;
+ if (format?.json_schema?.name === "frames") {
+ const n = format.json_schema.schema?.minItems ?? 1;
+ return completion({ content: JSON.stringify(Array.from({ length: n }, (_, i) => `Frame ${i + 1}: the fox crosses the snowfield, wide shot, dusk light`)) });
+ }
+ if (systemOf(b).startsWith("You rewrite short creative ideas")) {
+ return completion({ content: "<think>Add light and lens.</think>A red fox trotting through deep snow at golden hour, low angle, 85mm lens, soft rim light.", reasoning_content: "hidden" });
+ }
+ return completion({ content: translate(b, "lms") });
+ });
+ return Object.assign(s, { state });
+}
+
+/** A stand-in Unsloth Studio: liveness without a key, everything under /v1 with one. */
+function unslothStudio(key = "sk-unsloth-test") {
+ return stub((r, res) => {
+ if (r.url === "/api/liveness") return { status: "alive", service: "Unsloth UI Backend", desktop_protocol_version: 1 };
+ if (r.auth !== `Bearer ${key}`) return fail(res, 401, { error: { message: "Invalid or missing API key", type: "invalid_request_error", code: "invalid_api_key" } });
+ if (r.url === "/v1/models") {
+ return {
+ object: "list",
+ data: [
+ { id: "unsloth/Qwen3-8B-GGUF", object: "model", owned_by: "unsloth", loaded: true, context_length: 16384, status: { value: "loaded" } },
+ { id: "unsloth/gemma-3-12b-it-GGUF", object: "model", owned_by: "unsloth", loaded: false, status: { value: "unloaded" } },
+ { id: "unsloth/orpheus-3b-0.1-ft-GGUF", object: "model", task: "text-to-speech", loaded: false },
+ ],
+ };
+ }
+ if (r.url === "/v1/chat/completions") return completion({ content: translate(r.body, "unsloth"), reasoning_content: null }, "stop", "unsloth/Qwen3-8B-GGUF");
+ return fail(res, 404, { detail: "Not Found" });
+ });
+}
+
+/** A stand-in llama-server: one model, and no structured output. */
+function llamaServer() {
+ return stub((r, res) => {
+ if (r.url === "/v1/models") return { object: "list", data: [{ id: "gemma-3-4b-it-Q4_K_M.gguf", object: "model", owned_by: "llamacpp" }] };
+ if (r.url !== "/v1/chat/completions") return fail(res, 404, { error: { code: 404, message: "File Not Found", type: "not_found_error" } });
+ if (r.body.response_format) return fail(res, 400, { error: { code: 400, message: "Unsupported response_format: json_schema", type: "invalid_request_error" } });
+ return completion({ content: '```json\n{"reply": "Sure — four ads coming up.", "make": null}\n```' }, "stop", "gemma-3-4b-it-Q4_K_M.gguf");
+ });
+}
+
+/** A stand-in Ollama (its own API), for the order Automatic picks servers in. */
+function ollama(models = [{ name: "qwen3:8b" }]) {
+ return stub((r) => (r.url === "/api/tags" ? { models } : { model: "qwen3:8b", message: { role: "assistant", content: "(ollama) ok" }, done_reason: "stop" }));
+}
+
+const servers: { close: () => void }[] = [];
+async function started<T extends { start: () => Promise<void>; close: () => void }>(s: T): Promise<T> {
+ await s.start();
+ servers.push(s);
+ return s;
+}
+
+async function settle(id: string, ms = 30_000): Promise<Generation> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+const SETTINGS = ["llmProvider", "lmstudioUrl", "lmstudioModel", "lmstudioToken", "unslothUrl", "unslothModel", "unslothKey", "llmUrl", "llmModel", "llmKey", "llmContext", "enhanceProvider", "anthropicKey", "engineMode"] as const;
+
+beforeAll(() => setSetting("demoMode", "off"));
+beforeEach(() => {
+ for (const k of SETTINGS) setSetting(k, "");
+ setSetting("ollamaUrl", "");
+});
+afterAll(() => {
+ for (const s of servers) s.close();
+ // Windows keeps the open SQLite file locked until the worker exits.
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+// ---------------------------------------------------------------------------
+
+describe("the OpenAI wire", () => {
+ const tools = [{ name: "search_models", description: "Find models", parameters: { type: "object", properties: { kind: { type: "string" } } } }];
+
+ it("sends tools, tool calls with string arguments and tool results with their call's id", () => {
+ const body = wire.openaiBody(
+ "lmstudio",
+ {
+ messages: [
+ { role: "system", content: "sys" },
+ { role: "user", content: "hi" },
+ { role: "assistant", content: "", toolCalls: [{ id: "Ab3dE5gH9", name: "search_models", input: { kind: "image" } }] },
+ { role: "tool", toolCallId: "Ab3dE5gH9", toolName: "search_models", content: '{"models":[]}' },
+ ],
+ tools,
+ timeoutMs: 1,
+ },
+ "qwen/qwen3-8b",
+ );
+ expect(body).toMatchObject({ model: "qwen/qwen3-8b", stream: false, tool_choice: "auto", tools: [{ type: "function", function: { name: "search_models", description: "Find models", parameters: tools[0].parameters } }] });
+ const msgs = body.messages as Record<string, unknown>[];
+ expect(msgs[2]).toEqual({ role: "assistant", content: null, tool_calls: [{ id: "Ab3dE5gH9", type: "function", function: { name: "search_models", arguments: '{"kind":"image"}' } }] });
+ expect(msgs[3]).toEqual({ role: "tool", tool_call_id: "Ab3dE5gH9", content: '{"models":[]}' });
+ // Nothing a server doesn't need: no JSON format, no token cap, no Unsloth extras.
+ expect(body).not.toHaveProperty("response_format");
+ expect(body).not.toHaveProperty("max_tokens");
+ expect(body).not.toHaveProperty("enable_tools");
+ });
+
+ it("asks each server for JSON the way it understands, and keeps Unsloth's server-side tools off", () => {
+ const schema = { name: "ads", schema: { type: "object", properties: { ads: { type: "array" } } } };
+ const req = { messages: [{ role: "user" as const, content: "x" }], json: schema, think: false, timeoutMs: 1 };
+ expect(wire.openaiBody("lmstudio", req, "m").response_format).toEqual({ type: "json_schema", json_schema: { name: "ads", schema: schema.schema } });
+ expect(wire.openaiBody("unsloth", req, null).response_format).toEqual({ type: "json_schema", json_schema: { name: "ads", strict: true, schema: schema.schema } });
+ expect(wire.responseFormat("lmstudio", "object")).toEqual({ type: "json_schema", json_schema: { name: "answer", schema: { type: "object" } } });
+ expect(wire.responseFormat("custom", "object")).toEqual({ type: "json_object" });
+ // A server that can't do it: the same call without.
+ expect(wire.openaiBody("custom", req, "m", false)).not.toHaveProperty("response_format");
+ // Unsloth: the loaded model answers (no model named), thinking off for one-shot text, server-side tools always off.
+ const unsloth = wire.openaiBody("unsloth", req, null);
+ expect(unsloth).not.toHaveProperty("model");
+ expect(unsloth).toMatchObject({ enable_tools: false, enable_thinking: false });
+ expect(wire.openaiBody("unsloth", { ...req, think: undefined }, null)).toMatchObject({ enable_tools: false });
+ expect(wire.openaiBody("unsloth", { ...req, think: undefined }, null)).not.toHaveProperty("enable_thinking");
+ });
+
+ it("reads answers: thinking dropped, tool calls parsed, the stop reason mapped", () => {
+ const a = wire.parseOpenai(completion({ content: "<think>plan</think>Done.", reasoning_content: "more" }), "m");
+ expect(a).toMatchObject({ text: "Done.", toolCalls: [], stop: "end", thought: true, model: "qwen/qwen3-8b" });
+ const b = wire.parseOpenai(
+ completion({ content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "generate", arguments: '{"summary":"x"}' } }, { id: "2", function: { name: "generate", arguments: "{jobs: [" } }] }, "tool_calls"),
+ "m",
+ );
+ expect(b.stop).toBe("tool_use");
+ expect(b.toolCalls.map((c) => c.input)).toEqual([{ summary: "x" }, { INVALID_JSON: "{jobs: [" }]);
+ // Fuobe's own ids, nine letters and digits (strict templates want them; Claude accepts them).
+ expect(b.toolCalls.every((c) => /^[A-Za-z0-9]{9}$/.test(c.id))).toBe(true);
+ expect(wire.parseOpenai(completion({ content: "", reasoning_content: "hmm" }, "length"), "m")).toMatchObject({ text: "", stop: "length", thought: true });
+ // A template that opened <think> in the prompt leaves only the closing tag; a cut-off thought leaves nothing.
+ expect(wire.stripThink("weighing options</think>\n\nThe answer.")).toBe("The answer.");
+ expect(wire.stripThink("Answer first.<think>and then a thought that never")).toBe("Answer first.");
+ });
+
+ it("keeps Ollama's own wire: num_ctx, think, a schema as `format`, tool names on results", () => {
+ const body = wire.ollamaBody(
+ {
+ messages: [
+ { role: "system", content: "s" },
+ { role: "assistant", content: "", toolCalls: [{ id: "x", name: "search_models", input: { kind: "image" } }] },
+ { role: "tool", toolName: "search_models", content: "{}" },
+ ],
+ json: { name: "t", schema: { type: "object" } },
+ think: false,
+ timeoutMs: 1,
+ },
+ "qwen3:8b",
+ 16384,
+ );
+ expect(body).toMatchObject({ model: "qwen3:8b", stream: false, think: false, format: { type: "object" }, options: { num_ctx: 16384 } });
+ expect((body.messages as Record<string, unknown>[])[1]).toEqual({ role: "assistant", content: "", tool_calls: [{ function: { name: "search_models", arguments: { kind: "image" } } }] });
+ expect((body.messages as Record<string, unknown>[])[2]).toEqual({ role: "tool", content: "{}", tool_name: "search_models" });
+ expect(wire.ollamaBody({ messages: [], json: "object", timeoutMs: 1 }, "m", 0)).toMatchObject({ format: "json" });
+ expect(wire.ollamaBody({ messages: [], timeoutMs: 1 }, "m", 0)).not.toHaveProperty("options");
+ const r = wire.parseOllama({ message: { content: "<think>x</think>Hi", tool_calls: [{ function: { name: "generate", arguments: { a: 1 } } }] }, done_reason: "stop" }, "qwen3:8b");
+ expect(r).toMatchObject({ text: "Hi", stop: "tool_use", toolCalls: [{ name: "generate", input: { a: 1 } }] });
+ });
+});
+
+describe("Assist history for strict chat templates", () => {
+ type Param = Anthropic.Beta.BetaMessageParam;
+ const system = { stable: "You are Fuobe Assist.", turn: "Today is Friday." };
+ const history = [
+ { role: "user", content: [{ type: "text", text: "Make a fox." }, { type: "image", source: { type: "url", url: "/api/files/a.png" } }] },
+ { role: "assistant", content: [{ type: "thinking", thinking: "…", signature: "s" }, { type: "text", text: "Looking." }, { type: "tool_use", id: "toolu_01AbCdEfGhIjKlMnOp", name: "search_models", input: { kind: "image" } }] },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_01AbCdEfGhIjKlMnOp", content: [{ type: "text", text: '{"models":[]}' }, { type: "image", source: { type: "base64", media_type: "image/png", data: "AA" } }] }] },
+ { role: "system", content: "Context update: auto-run is on." },
+ { role: "assistant", content: [{ type: "tool_use", id: "toolu_02", name: "generate", input: { summary: "x" } }] },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_02", is_error: true, content: "Invalid input: jobs" }, { type: "text", text: "Try again." }] },
+ { role: "system", content: "Context update: a memory was saved." },
+ ] as unknown as Param[];
+
+ it("has one system message, folds context updates into user turns and keeps call ids matched", () => {
+ const out = messages.toChatMessages(system, history, "lmstudio");
+ expect(out.map((m) => m.role)).toEqual(["system", "user", "assistant", "tool", "user", "assistant", "tool", "user"]);
+ expect(out.filter((m) => m.role === "system")).toHaveLength(1);
+ expect(out[0].content).toBe("You are Fuobe Assist.\n\nToday is Friday.");
+ // Images stay out (the user's text lists their URLs); a tool's image reads as a note.
+ expect(out[1].content).toBe("Make a fox.");
+ expect(out[3].content).toBe('{"models":[]}\n[image omitted]');
+ // After tool results, the update is a user turn of its own; after the user's words, it joins them.
+ expect(out[4].content).toBe(`${messages.CONTEXT_UPDATE_LABEL}\nContext update: auto-run is on.`);
+ expect(out[6]).toMatchObject({ role: "tool", content: "Error: Invalid input: jobs" });
+ expect(out[7].content).toBe(`Try again.\n\n${messages.CONTEXT_UPDATE_LABEL}\nContext update: a memory was saved.`);
+ // Thinking dropped; nine-character ids, the same on the call and its result, and stable.
+ expect(out[2]).toMatchObject({ content: "Looking.", toolCalls: [{ name: "search_models", input: { kind: "image" } }] });
+ const id = out[2].toolCalls![0].id;
+ expect(id).toMatch(/^[A-Za-z0-9]{9}$/);
+ expect(out[3].toolCallId).toBe(id);
+ expect(messages.wireId("toolu_01AbCdEfGhIjKlMnOp")).toBe(id);
+ expect(out[5].toolCalls![0].id).toBe(out[6].toolCallId);
+ expect(messages.wireId("Ab3dE5gH9")).toBe("Ab3dE5gH9");
+ });
+
+ it("gives Ollama the history as before: system context updates, tool names on results", () => {
+ const out = messages.toChatMessages(system, history, "ollama");
+ expect(out.map((m) => m.role)).toEqual(["system", "user", "assistant", "tool", "system", "assistant", "tool", "user", "system"]);
+ expect(out[3]).toMatchObject({ toolName: "search_models", toolCallId: "toolu_01AbCdEfGhIjKlMnOp" });
+ });
+
+ it("reads tool calls a model wrote as text, for the offered tools only", () => {
+ const names = new Set(["search_models", "generate"]);
+ const hermes = messages.healToolCalls('Sure.\n<tool_call>\n{"name": "search_models", "arguments": {"kind": "video"}}\n</tool_call>', names);
+ expect(hermes).toMatchObject({ text: "Sure.", calls: [{ name: "search_models", input: { kind: "video" } }] });
+ const lms = messages.healToolCalls('[TOOL_REQUEST]{"name": "generate", "arguments": {"summary": "fox"}}[END_TOOL_REQUEST]', names);
+ expect(lms).toMatchObject({ text: "", calls: [{ name: "generate", input: { summary: "fox" } }] });
+ // Llama 3 writes "parameters"; a fenced reply that is only the call counts too.
+ expect(messages.healToolCalls('```json\n{"name": "search_models", "parameters": {"kind": "audio"}}\n```', names).calls).toMatchObject([{ input: { kind: "audio" } }]);
+ // Not a tool we offered, or not a call at all: the text stays.
+ expect(messages.healToolCalls('<tool_call>{"name": "rm", "arguments": {}}</tool_call>', names)).toMatchObject({ calls: [], text: '<tool_call>{"name": "rm", "arguments": {}}</tool_call>' });
+ expect(messages.healToolCalls('{"name": "Fox", "colour": "red"}', names).calls).toEqual([]);
+ });
+});
+
+describe("reading a server's answers", () => {
+ const server = (kind: "ollama" | "lmstudio" | "unsloth" | "custom", over: Partial<{ url: string; model: string; key: string }> = {}) => ({ kind, label: local.LOCAL_LABELS[kind], url: "http://127.0.0.1:1234", model: "", key: "", ...over });
+
+ it("LM Studio: chat models only, a loaded one first, warnings for a small context, problems that say what to do", () => {
+ const models = (loaded: number | null, extra: unknown[] = []) => ({
+ native: {
+ status: 200,
+ body: {
+ models: [
+ { type: "embedding", key: "nomic-embed", loaded_instances: [{ id: "nomic-embed", config: { context_length: 2048 } }] },
+ { type: "llm", key: "google/gemma-3-12b", loaded_instances: [], max_context_length: 131072, capabilities: { trained_for_tool_use: false } },
+ { type: "llm", key: "qwen/qwen3-8b", loaded_instances: loaded ? [{ id: "qwen/qwen3-8b", config: { context_length: loaded } }] : [], max_context_length: 40960, capabilities: { trained_for_tool_use: true, reasoning: { allowed_options: ["off", "on"], default: "on" } } },
+ ...extra,
+ ],
+ },
+ },
+ });
+ const ready = interpret(server("lmstudio"), models(16384), 16384, 0);
+ expect(ready).toMatchObject({ up: true, problem: null, model: "qwen/qwen3-8b", loaded: true, context: 16384, native: true });
+ expect(ready.models.map((m) => m.id)).toEqual(["google/gemma-3-12b", "qwen/qwen3-8b"]);
+ expect(ready.warning).toMatch(/thinks before it answers/);
+ // Nothing loaded: the one trained for tool use.
+ expect(interpret(server("lmstudio"), models(null), 16384, 0)).toMatchObject({ model: "qwen/qwen3-8b", loaded: false, problem: null });
+ expect(interpret(server("lmstudio"), models(4096), 16384, 0).warning).toMatch(/loaded with 4,096 tokens of context; Assist and long texts need about 16,384\. Reload it with 16k context/);
+ expect(interpret(server("lmstudio", { model: "mistral/ministral-8b" }), models(null), 16384, 0).problem).toMatch(/LM Studio has no model called mistral\/ministral-8b.*lms get mistral\/ministral-8b/);
+ expect(interpret(server("lmstudio", { model: "qwen/qwen3-8b@q4_k_m" }), models(null), 16384, 0)).toMatchObject({ problem: null, model: "qwen/qwen3-8b@q4_k_m" });
+ expect(interpret(server("lmstudio"), { native: { status: 200, body: { models: [] } } }, 16384, 0).problem).toMatch(/no chat models downloaded yet.*lms get/);
+ expect(interpret(server("lmstudio"), { native: { status: 401, body: {} }, openai: { status: 401, body: {} } }, 16384, 0)).toMatchObject({ up: true, auth: "missing", problem: expect.stringMatching(/Manage Tokens/) });
+ expect(interpret(server("lmstudio", { key: "bad" }), { native: { status: 401, body: {} } }, 16384, 0)).toMatchObject({ auth: "rejected", problem: expect.stringMatching(/rejected the API token/) });
+ expect(interpret(server("lmstudio"), { native: { error: "ECONNREFUSED" }, openai: { error: "ECONNREFUSED" } }, 16384, 0).problem).toBe(
+ "LM Studio isn't running at http://127.0.0.1:1234. Start LM Studio's local server and load a model: in LM Studio, Developer → Start server (or run `lms server start`).",
+ );
+ // Before 0.4: the OpenAI list, embeddings dropped.
+ expect(interpret(server("lmstudio"), { native: { status: 404, body: {} }, openai: { status: 200, body: { data: [{ id: "text-embedding-x" }, { id: "llama-3.2-3b-instruct" }] } } }, 16384, 0)).toMatchObject({ problem: null, native: false, model: "llama-3.2-3b-instruct", loaded: null });
+ });
+
+ it("Unsloth Studio: itself (not Jupyter), its key, a loaded chat model", () => {
+ const live = { status: 200, body: { status: "alive", service: "Unsloth UI Backend" } };
+ const rows = { status: 200, body: { data: [{ id: "unsloth/tts", task: "text-to-speech", loaded: true }, { id: "unsloth/Qwen3-8B-GGUF", loaded: false }] } };
+ expect(interpret(server("unsloth"), { live: { status: 200, body: { status: "ok" } }, openai: rows }, 16384, 0).problem).toMatch(/Something else answers at .*not Unsloth Studio/);
+ expect(interpret(server("unsloth"), { live, openai: { status: 401, body: {} } }, 16384, 0)).toMatchObject({ auth: "missing", problem: expect.stringMatching(/avatar → Settings → API → Create.*sk-unsloth-/) });
+ expect(interpret(server("unsloth", { key: "sk-unsloth-x" }), { live, openai: rows }, 16384, 0)).toMatchObject({ up: true, problem: expect.stringMatching(/no model loaded.*Chat page/) });
+ const loaded = { status: 200, body: { data: [{ id: "unsloth/Qwen3-8B-GGUF", loaded: true, context_length: 8192 }] } };
+ expect(interpret(server("unsloth", { key: "sk-unsloth-x" }), { live, openai: loaded }, 16384, 0)).toMatchObject({ problem: null, model: "unsloth/Qwen3-8B-GGUF", loaded: true, warning: expect.stringMatching(/8,192 tokens.*Load it in Unsloth Studio with a larger context/) });
+ expect(interpret(server("unsloth", { model: "unsloth/Qwen3-8B-GGUF:Q4_K_M" }), { live, openai: loaded }, 16384, 0)).toMatchObject({ problem: null, model: "unsloth/Qwen3-8B-GGUF:Q4_K_M" });
+ });
+
+ it("another OpenAI-compatible server: its URL, its first model; Ollama: up whenever it answers", () => {
+ expect(interpret(server("custom", { url: "" }), {}, 16384, 0).problem).toMatch(/Set the server's URL/);
+ expect(interpret(server("custom"), { openai: { status: 200, body: { data: [{ id: "bge-embed" }, { id: "Qwen3-8B" }] } } }, 16384, 0)).toMatchObject({ problem: null, model: "Qwen3-8B" });
+ expect(interpret(server("custom"), { openai: { status: 200, body: { data: [] } } }, 16384, 0).problem).toMatch(/lists no models/);
+ expect(interpret(server("ollama", { model: "qwen3:8b" }), { tags: { status: 200, body: { models: [] } } }, 16384, 0)).toMatchObject({ up: true, problem: null, model: "qwen3:8b", warning: expect.stringMatching(/ollama pull qwen3:8b/) });
+ });
+
+ it("LM Studio: a display name finds the model and calls use its key; a model's most context ends the reload advice", () => {
+ const native = (loaded: number | null, max: number) => ({
+ native: {
+ status: 200,
+ body: { models: [{ type: "llm", key: "qwen/qwen3-8b", display_name: "Qwen3 8B", loaded_instances: loaded ? [{ id: "qwen/qwen3-8b", config: { context_length: loaded } }] : [], max_context_length: max }] },
+ },
+ });
+ expect(interpret(server("lmstudio", { model: "Qwen3 8B" }), native(null, 40960), 16384, 0)).toMatchObject({ problem: null, model: "qwen/qwen3-8b" });
+ // Loaded at its most (8k): no "Reload with 16k" (it would load 8k again), just what it can hold.
+ const full = interpret(server("lmstudio"), native(8192, 8192), 16384, 0);
+ expect(full.warning).toMatch(/handles only 8,192 tokens of context/);
+ expect(full.warning).not.toMatch(/Reload/);
+ expect(interpret(server("lmstudio"), native(4096, 8192), 16384, 0).warning).toMatch(/loaded with 4,096 tokens.*Reload it with 8k context/);
+ });
+
+ it("reads context sizes as people write them, and finds keys under their other env names", () => {
+ expect(["16384", "16,384", "16 384", "16_384", "16k", "16K"].map(parseContext)).toEqual([16384, 16384, 16384, 16384, 16384, 16384]);
+ expect(parseContext("0")).toBe(0);
+ for (const bad of ["16", "1000", "abc", "-1", ""]) expect(parseContext(bad)).toBeNull();
+ expect(() => validateSetting("llmContext", "16")).toThrow(/at least 2048/);
+ expect(() => validateSetting("llmContext", "16,384")).not.toThrow();
+ setSetting("llmContext", "32k");
+ expect(local.llmContext()).toBe(32768);
+ setSetting("llmContext", "");
+ expect(local.llmContext()).toBe(16384);
+ process.env.LM_API_TOKEN = "lm-alias-token-1234";
+ process.env.UNSLOTH_STUDIO_AUTH_TOKEN = "sk-unsloth-alias-5678";
+ try {
+ const shown = Object.fromEntries(publicSettings().map((s) => [s.name, s]));
+ expect(shown.lmstudioToken).toMatchObject({ isSet: true, fromEnv: true, value: "lm-a••••1234" });
+ expect(shown.unslothKey).toMatchObject({ isSet: true, fromEnv: true, value: "sk-u••••5678" });
+ expect(local.localServer("lmstudio").key).toBe("lm-alias-token-1234");
+ } finally {
+ delete process.env.LM_API_TOKEN;
+ delete process.env.UNSLOTH_STUDIO_AUTH_TOKEN;
+ }
+ });
+
+ it("reads Unsloth Studio's nested error bodies", () => {
+ const uns = server("unsloth");
+ const nested = (message: string, code?: string) => JSON.stringify({ detail: { error: { message, type: "invalid_request_error", ...(code && { code }) } } });
+ expect(httpError(uns, 400, nested("Request has 20000 tokens, more than the 8192 the model was loaded with.", "context_length_exceeded"), null).message).toBe(
+ "This is longer than the model's context on Unsloth Studio. Load it in Unsloth Studio with a larger context, or use shorter text.",
+ );
+ expect(httpError(uns, 400, nested("Too long", "context_length_exceeded"), null).message).toMatch(/^This is longer than the model's context/);
+ expect(httpError(uns, 502, nested("llama-server stopped"), null).message).toBe("Unsloth Studio returned 502: llama-server stopped");
+ expect(httpError(uns, 500, JSON.stringify({ detail: { message: "Backend busy" } }), null).message).toBe("Unsloth Studio returned 500: Backend busy");
+ });
+
+ it("turns failed calls into what to do about them", () => {
+ const lms = server("lmstudio");
+ expect(httpError(lms, 400, JSON.stringify({ error: "Trying to keep the first 9000 tokens when context the overflows. However, the model is loaded with context length of only 4096 tokens" }), "qwen/qwen3-8b").message).toBe(
+ "This is longer than qwen/qwen3-8b's context (4096 tokens) on LM Studio. Reload it with 16k context (Settings → AI helper) or a larger one in LM Studio, or use shorter text.",
+ );
+ expect(httpError(lms, 404, JSON.stringify({ error: { message: "Model 'x/y' not found" } }), "x/y").message).toMatch(/LM Studio has no model called x\/y — download it in LM Studio \(or run `lms get x\/y`\)/);
+ expect(httpError(server("unsloth"), 400, JSON.stringify({ detail: "No model loaded. Load a model first, or enable Model auto-switch (Settings > API)." }), null).message).toMatch(/^Unsloth Studio has no model loaded — load one on its Chat page/);
+ expect(httpError(server("unsloth"), 401, "{}", null).message).toMatch(/^Unsloth Studio needs an API key/);
+ expect(httpError(server("custom"), 500, "boom", "m").message).toBe("Your local server returned 500: boom");
+ expect(httpError(server("ollama"), 404, JSON.stringify({ error: "model 'qwen3:8b' not found" }), "qwen3:8b").message).toBe("Ollama doesn't have qwen3:8b yet — run `ollama pull qwen3:8b`");
+ expect(rejectsJson("custom", 400, "Unsupported response_format: json_schema")).toBe(true);
+ expect(rejectsJson("custom", 500, "model crashed")).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Against stand-in servers, through Fuobe's own code paths
+
+describe("LM Studio", () => {
+ it("runs Enhance on the model it loads with 16k context, once, and drops the thinking", async () => {
+ const lms = await started(lmStudio());
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", `${lms.url}/v1`); // a URL pasted from an example: /v1 is dropped
+ expect(await local.probeLocal(true)).toBe(true);
+ const text = await enhancePrompt("a fox in snow", "image", "t2i");
+ expect(text).toBe("A red fox trotting through deep snow at golden hour, low angle, 85mm lens, soft rim light.");
+ // Not loaded yet: loaded first with the context Assist needs (the chat endpoint can't set it).
+ expect(lms.state.loads).toEqual([{ model: "qwen/qwen3-8b", context_length: 16384, echo_load_config: true }]);
+ const [chat] = lms.chats();
+ expect(chat).toMatchObject({ model: "qwen/qwen3-8b", stream: false, messages: [{ role: "system" }, { role: "user", content: "Rewrite this as a text-to-image prompt:\n\na fox in snow" }] });
+ expect(chat).not.toHaveProperty("tools");
+ expect(lms.seen.every((r) => r.auth === undefined)).toBe(true);
+ // Loaded now: no second load.
+ await enhancePrompt("a cat on a roof", "image", "t2i");
+ expect(lms.state.loads).toHaveLength(1);
+ expect(lms.chats()).toHaveLength(2);
+ });
+
+ it("loads the model once for a whole text step, however many calls it makes", async () => {
+ const lms = await started(lmStudio());
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ // 35 cues: a batch of 30, then one of 5, on a model that isn't loaded when the step starts.
+ const cues = Array.from({ length: 35 }, (_, i) => ({ start: i * 2, end: i * 2 + 1.5, text: `Line ${i + 1}` }));
+ const [g] = gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: JSON.stringify(cues), params: { targetLanguage: "German" } });
+ const done = await settle(g.id);
+ expect(done.status, done.error ?? "").toBe("succeeded");
+ expect(done.outputs[0].meta?.cues).toEqual(cues.map((c) => ({ ...c, text: `(German·lms) ${c.text}` })));
+ expect(lms.chats()).toHaveLength(2);
+ expect(lms.state.loads).toHaveLength(1);
+ });
+
+ it("splits a storyboard with a JSON schema of exactly n frames", async () => {
+ const lms = await started(lmStudio({ loaded: 32768 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ const scenes = await splitStory("A fox crosses a snowfield at dusk and finds its den.", 3);
+ expect(scenes).toHaveLength(3);
+ expect(scenes[0]).toMatch(/^Frame 1: the fox crosses/);
+ expect(lms.chats()[0].response_format).toEqual({ type: "json_schema", json_schema: { name: "frames", schema: { type: "array", items: { type: "string" }, minItems: 3, maxItems: 3 } } });
+ expect(lms.state.loads).toHaveLength(0);
+ });
+
+ it("runs an Assist chat: tools offered, one tool call run, its result sent back under the same id", async () => {
+ const lms = await started(lmStudio({ loaded: 16384 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ expect(await agent.resolveAgent()).toBe("local");
+ const can = await agent.availability();
+ expect(can.local).toEqual({ kind: "lmstudio", label: "LM Studio", ok: true, models: ["qwen/qwen3-8b"], model: "qwen/qwen3-8b" });
+ const t = agent.createThread({ engine: "open", agent: "local" });
+ agent.addMessage(t.id, "Which image model should I use?");
+ await agent.run(t.id);
+ const [first, second] = lms.chats();
+ expect(lms.chats()).toHaveLength(2);
+ expect(first.model).toBe("qwen/qwen3-8b");
+ expect((first.tools as { function: { name: string } }[]).map((x) => x.function.name)).toEqual(expect.arrayContaining(["search_models", "generate"]));
+ expect(first.messages!.map((m) => m.role)).toEqual(["system", "user"]);
+ const sent = second.messages!;
+ expect(sent.map((m) => m.role)).toEqual(["system", "user", "assistant", "tool"]);
+ const call = sent[2].tool_calls![0];
+ expect(call).toMatchObject({ type: "function", function: { name: "search_models", arguments: '{"kind":"image"}' } });
+ expect(call.id).toMatch(/^[A-Za-z0-9]{9}$/);
+ expect(sent[3].tool_call_id).toBe(call.id);
+ expect(JSON.parse(sent[3].content!).models.length).toBeGreaterThan(0);
+ const items = agent.getThread(t.id)!.thread.items;
+ expect(items.find((i) => i.role === "assistant")).toMatchObject({ text: "Let me look." });
+ expect(items.at(-1)).toMatchObject({ role: "assistant", text: "Nano Banana Pro is a great pick." });
+ expect(agent.getThread(t.id)!.thread.status).toBe("idle");
+ });
+
+ it("sends its token when Require Authentication is on, and says what to do without one", async () => {
+ const lms = await started(lmStudio({ token: "lms-secret-1234", loaded: 16384 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ expect(await local.probeLocal(true)).toBe(false);
+ expect(llm.llmBackends({ endpoint: "ollama", op: "write" })).toEqual([]);
+ expect(llm.llmMissing({ endpoint: "ollama", op: "write" })).toMatch(/^Connect LM Studio in Settings to run this model \(open-source text runs on your own machine\)\. LM Studio wants an API token/);
+ setSetting("lmstudioToken", "lms-secret-1234");
+ expect(await local.probeLocal(true)).toBe(true);
+ expect(await llmText("Reply.", "hello")).toBe("(??·lms) hello");
+ expect(lms.seen.at(-1)!.auth).toBe("Bearer lms-secret-1234");
+ });
+
+ it("explains a context overflow and a model that spent its reply thinking; a dead server, how to start it", async () => {
+ const lms = await started(lmStudio({ loaded: 4096 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ const ready = (await local.activeLocal())!;
+ expect(ready.status.warning).toMatch(/4,096 tokens of context/);
+ const ask = (content: string) => local.chatLocal(ready, { messages: [{ role: "user", content }], timeoutMs: 10_000 });
+ await expect(ask("OVERFLOW")).rejects.toThrow(/longer than qwen\/qwen3-8b's context \(4096 tokens\) on LM Studio\. Reload it with 16k context/);
+ const r = await ask("THINK FOREVER");
+ expect(r).toMatchObject({ text: "", stop: "length", thought: true });
+ expect(local.emptyReply(ready.server, r).message).toBe("qwen/qwen3-8b on LM Studio spent its whole reply thinking. Turn thinking off for it, or pick a model that doesn't think first.");
+ // The text step says the same instead of "no text".
+ const [g] = gens.createGenerations({ feature: "ads", modelId: "oss-text-llm", op: "write", prompt: "THINK FOREVER" });
+ expect((await settle(g.id)).error).toMatch(/spent its whole reply thinking/);
+ lms.close();
+ await expect(ask("hello")).rejects.toThrow(/^Couldn't reach LM Studio at http:\/\/127\.0\.0\.1:\d+ \(ECONNREFUSED\)\. Start LM Studio's local server and load a model/);
+ });
+
+ it("reloads a model loaded with too little context (Settings → Reload) through /api/llm, without keys in the answers", async () => {
+ const lms = await started(lmStudio({ loaded: 4096 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ setSetting("lmstudioToken", "");
+ const route = await import("@/app/api/llm/route");
+ const before = (await (await route.GET(new Request("http://x/api/llm?refresh=1"))).json()) as { active: string; servers: { kind: string; context: number; warning: string }[] };
+ expect(before.active).toBe("lmstudio");
+ expect(before.servers.map((s) => s.kind)).toEqual(["ollama", "lmstudio", "unsloth", "custom"]);
+ expect(before.servers[1]).toMatchObject({ context: 4096, warning: expect.stringMatching(/Reload it with 16k context/) });
+ const res = (await (await route.POST(new Request("http://x/api/llm", { method: "POST", body: JSON.stringify({ action: "load" }) }))).json()) as { ok: boolean; detail: string };
+ expect(res).toMatchObject({ ok: true, detail: "LM Studio loaded qwen/qwen3-8b with 16,384 tokens of context in 2.5 s" });
+ expect(lms.state.unloads).toEqual([{ instance_id: "qwen/qwen3-8b" }]);
+ expect(lms.state.loads).toEqual([{ model: "qwen/qwen3-8b", context_length: 16384, echo_load_config: true }]);
+ const test = (await (await route.POST(new Request("http://x/api/llm", { method: "POST", body: JSON.stringify({ action: "test", kind: "lmstudio" }) }))).json()) as { ok: boolean; detail: string };
+ expect(test).toMatchObject({ ok: true, detail: expect.stringMatching(/^LM Studio answered in \d+\.\d s with qwen\/qwen3-8b/) });
+ expect(lms.chats().at(-1)).toMatchObject({ max_tokens: 16, messages: [{ role: "user", content: "Reply with the word OK." }] });
+ });
+
+ it("stops a text step's call when the step is canceled", async () => {
+ const lms = await started(lmStudio({ loaded: 16384 }));
+ setSetting("llmProvider", "lmstudio");
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ const [g] = gens.createGenerations({ feature: "ads", modelId: "oss-text-llm", op: "write", prompt: "SLOW please" });
+ for (let i = 0; i < 100 && !lms.chats().length; i++) await new Promise((r) => setTimeout(r, 50));
+ expect(lms.chats()).toHaveLength(1);
+ const { db } = await import("@/server/db");
+ const handedOver = () => !!(db().prepare("SELECT external_id FROM generations WHERE id = ?").get(g.id) as { external_id: string | null }).external_id;
+ for (let i = 0; i < 50 && !handedOver(); i++) await new Promise((r) => setTimeout(r, 50));
+ await gens.cancelGeneration(g.id);
+ for (let i = 0; i < 100 && !lms.state.aborted; i++) await new Promise((r) => setTimeout(r, 50));
+ expect(lms.state.aborted).toBe(1);
+ expect(gens.getGeneration(g.id)!.status).toBe("canceled");
+ });
+});
+
+describe("Unsloth Studio", () => {
+ it("needs its key; with it, translates subtitles on the loaded model with thinking and server-side tools off", async () => {
+ const un = await started(unslothStudio());
+ setSetting("llmProvider", "unsloth");
+ setSetting("unslothUrl", un.url);
+ expect(await local.probeLocal(true)).toBe(false);
+ expect(llm.llmMissing({ endpoint: "auto" })).toMatch(/^Connect Claude or Unsloth Studio in Settings to run this model\. Unsloth Studio needs an API key: in Unsloth Studio, avatar → Settings → API → Create/);
+ // Keyless at first (Unsloth's keyless access may be on): no Authorization header was sent.
+ expect(un.seen.find((r) => r.url === "/v1/models")?.auth).toBeUndefined();
+ const keyless = un.seen.length;
+ setSetting("unslothKey", "sk-unsloth-test");
+ expect(await local.probeLocal(true)).toBe(true);
+ expect(llm.llmProvider.label).toBe("Claude or Unsloth Studio");
+ const cues = JSON.stringify([
+ { start: 0, end: 1.5, text: "Hello there." },
+ { start: 2, end: 3.5, text: "Two\nlines." },
+ ]);
+ const [g] = gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: cues, params: { targetLanguage: "Spanish" } });
+ expect(g).toMatchObject({ provider: "llm", costUsd: 0 });
+ const done = await settle(g.id);
+ expect(done.status, done.error ?? "").toBe("succeeded");
+ expect(done.outputs[0].meta?.cues).toEqual([
+ { start: 0, end: 1.5, text: "(Spanish·unsloth) Hello there." },
+ { start: 2, end: 3.5, text: "(Spanish·unsloth) Two\nlines." },
+ ]);
+ const [chat] = un.chats();
+ expect(chat).toMatchObject({ enable_tools: false, enable_thinking: false, stream: false });
+ expect(chat).not.toHaveProperty("model");
+ // With the key, every call but the liveness check carries it.
+ expect(un.seen.slice(keyless).filter((r) => r.url !== "/api/liveness").map((r) => r.auth)).toEqual(expect.arrayContaining(["Bearer sk-unsloth-test"]));
+ expect(un.seen.slice(keyless).filter((r) => r.url !== "/api/liveness").every((r) => r.auth === "Bearer sk-unsloth-test")).toBe(true);
+ expect(un.seen.filter((r) => r.url === "/api/liveness").every((r) => r.auth === undefined)).toBe(true);
+ // The speech model isn't offered for chat.
+ expect((await local.activeLocal())!.status.models.map((m) => m.id)).toEqual(["unsloth/Qwen3-8B-GGUF", "unsloth/gemma-3-12b-it-GGUF"]);
+ });
+});
+
+describe("another OpenAI-compatible server (llama-server)", () => {
+ it("asks again without JSON when the server can't do it, and uses the model it lists", async () => {
+ const ls = await started(llamaServer());
+ setSetting("llmProvider", "custom");
+ setSetting("llmUrl", ls.url); // no /v1: added
+ expect(await local.probeLocal(true)).toBe(true);
+ const text = await llmText("You are an ad strategist. Answer with JSON.", "Make ads", { json: { name: "reply", schema: { type: "object" } } });
+ expect(text).toMatch(/"reply": "Sure — four ads coming up\."/);
+ const [withJson, without] = ls.chats();
+ expect(withJson).toMatchObject({ model: "gemma-3-4b-it-Q4_K_M.gguf", response_format: { type: "json_schema", json_schema: { name: "reply", strict: true } } });
+ expect(without).not.toHaveProperty("response_format");
+ expect(ls.seen.filter((r) => r.method === "POST").map((r) => r.url)).toEqual(["/v1/chat/completions", "/v1/chat/completions"]);
+ expect(llm.llmProvider.label).toBe("Claude or your local server");
+ });
+});
+
+describe("Automatic", () => {
+ it("uses the first ready server in order (Ollama first, as before), and /api/status says which, without secrets", async () => {
+ const ol = await started(ollama());
+ const lms = await started(lmStudio({ loaded: 16384 }));
+ setSetting("lmstudioUrl", lms.url);
+ setSetting("lmstudioToken", "lms-never-shown-5678");
+ setSetting("ollamaUrl", ol.url);
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("ollama");
+ expect(llm.llmProvider.label).toBe("Claude or Ollama");
+ // Ollama stops: LM Studio takes over.
+ setSetting("ollamaUrl", "http://127.0.0.1:9");
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("lmstudio");
+ expect(llm.llmProvider.label).toBe("Claude or LM Studio");
+ expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["local"]);
+ const [g] = gens.createGenerations({ feature: "ads", modelId: "text-llm", op: "write", prompt: "A tagline" });
+ expect(g.costUsd).toBe(0);
+ expect((await settle(g.id)).outputs[0].text).toBe("(??·lms) A tagline");
+ const { GET } = await import("@/app/api/status/route");
+ const raw = await (await GET()).text();
+ expect(raw).not.toContain("lms-never-shown-5678");
+ const status = JSON.parse(raw) as { providers: { llm: { label: string; configured: boolean } }; llm: { helper: string; local: { kind: string; model: string; context: number }; detected: { kind: string; up: boolean }[] } };
+ expect(status.providers.llm).toEqual({ label: "Claude or LM Studio", configured: true });
+ expect(status.llm).toMatchObject({ helper: "auto", claude: false, provider: "auto", local: { kind: "lmstudio", label: "LM Studio", model: "qwen/qwen3-8b", loaded: true, context: 16384 } });
+ expect(status.llm.detected.map((d) => [d.kind, d.up])).toEqual([
+ ["ollama", false],
+ ["lmstudio", true],
+ ["unsloth", false],
+ ]);
+ // The old "ollama" AI-helper value still means local-only.
+ setSetting("enhanceProvider", "ollama");
+ expect(local.aiHelper()).toBe("local");
+ expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["local"]);
+ });
+
+ it("passes over an Ollama with no models for an LM Studio that has one, and uses Ollama alone as before", async () => {
+ const empty = await started(ollama([]));
+ const lms = await started(lmStudio({ loaded: 16384 }));
+ setSetting("ollamaUrl", empty.url);
+ setSetting("lmstudioUrl", lms.url);
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("lmstudio");
+ // An Ollama without the configured model is passed over too.
+ const other = await started(ollama([{ name: "llama3.2:3b" }]));
+ setSetting("ollamaUrl", other.url);
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("lmstudio");
+ // No other server: Ollama still takes calls (and names the missing model when one fails).
+ setSetting("lmstudioUrl", "http://127.0.0.1:9");
+ await local.probeLocal(true);
+ expect((await local.activeLocal())!.server.kind).toBe("ollama");
+ });
+});
diff --git a/tests/model3d-finish.test.ts b/tests/model3d-finish.test.ts
new file mode 100644
index 00000000..ba64b219
--- /dev/null
+++ b/tests/model3d-finish.test.ts
@@ -0,0 +1,368 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { Document, getBounds, NodeIO } from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+import { MeshoptDecoder } from "meshoptimizer";
+import sharp from "sharp";
+import { describe, expect, it, vi } from "vitest";
+import { getModel, getPreset } from "@/lib/catalog";
+import { model3dRequest, model3dView, MODELS_3D, viewerGlb } from "@/lib/av/model3d";
+import { modelPreview } from "@/lib/output-actions";
+import type { OutputFile } from "@/lib/catalog/types";
+
+vi.setConfig({ testTimeout: 120_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-3d-finish-"));
+process.env.FUOBE_DATA_DIR = dir;
+const { saveFile } = await import("@/server/storage");
+const { finishModel, lastJsonLine, modelToFinish, pendingTurntable, startTurntable, withTurntable } = await import("@/server/model3d-finish");
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+async function until<T>(f: () => T | undefined | null | false, ms = 30_000): Promise<T> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = f();
+ if (v) return v;
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await sleep(50);
+ }
+}
+
+const root = process.cwd();
+type Graph = Record<string, { class_type: string; inputs: Record<string, unknown> }>;
+const graph = (id: string) => JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui", `${id}.json`), "utf8")) as Graph;
+const manifest = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/manifest.json"), "utf8")) as { workflows: { id: string; bindings: Record<string, unknown>; outputs: { node: string; kind: string }[]; defaults: Record<string, unknown>; validated: boolean }[] };
+const byClass = (g: Graph, c: string) => Object.entries(g).filter(([, n]) => n.class_type === c);
+const one = (g: Graph, c: string) => {
+ const found = byClass(g, c);
+ expect(found, c).toHaveLength(1);
+ return found[0];
+};
+const link = (v: unknown) => (Array.isArray(v) ? String(v[0]) : null);
+
+describe("image-to-3D graphs", () => {
+ for (const id of ["image-to-3d-pixal3d", "image-to-3d-trellis2"]) {
+ it(`${id}: remesh solid, decimate to 250k, bake from the dense mesh, no in-graph turntable`, () => {
+ const g = graph(id);
+ const [remeshId, remesh] = one(g, "RemeshMesh");
+ expect(remesh.inputs).toMatchObject({ resolution: 768, sign_mode: "solid", "sign_mode.fill": 20, band: 1, smooth_iters: 20 });
+ const [decId, dec] = one(g, "DecimateMesh");
+ expect(dec.inputs).toMatchObject({ target_face_count: 250000, placement_mode: "midpoint" });
+ expect(link(dec.inputs.mesh)).toBe(remeshId);
+ // DecimateMesh sits between RemeshMesh and MeshSmoothNormals; the UVs are unwrapped on the decimated mesh.
+ const [smoothId] = byClass(g, "MeshSmoothNormals").find(([, n]) => link(n.inputs.mesh) === decId)!;
+ const [unwrapId, unwrap] = one(g, "UnwrapMesh");
+ expect(link(unwrap.inputs.mesh)).toBe(smoothId);
+ const [, normal] = one(g, "BakeNormalMapFromMesh");
+ const [, ao] = one(g, "BakeAmbientOcclusion");
+ expect(normal.inputs).toMatchObject({ resolution: 2048 });
+ expect(ao.inputs).toMatchObject({ resolution: 1024 });
+ for (const bake of [normal, ao]) {
+ expect(link(bake.inputs.high_poly)).toBe(remeshId);
+ expect(link(bake.inputs.low_poly)).toBe(unwrapId);
+ }
+ for (const c of ["RotateMesh", "RenderMesh", "CreateVideo", "SaveVideo"]) expect(byClass(g, c), c).toHaveLength(0);
+ // Samplers as the template: structure 12, shape 20, upsample 12, texture 12; upsample to 1536.
+ expect(byClass(g, "KSampler").map(([, n]) => n.inputs.steps).sort()).toEqual([12, 12, 12, 20]);
+ expect(Number(one(g, "Trellis2UpsampleStage")[1].inputs.target_resolution)).toBe(1536);
+ // The BiRefNet cut-out feeds the crop.
+ const [cutId] = one(g, "RemoveBackground");
+ expect(link(one(g, "ImageCropToMask")[1].inputs.masks)).toBe(cutId);
+
+ const m = manifest.workflows.find((w) => w.id === id)!;
+ expect(m.validated).toBe(true);
+ expect(m.outputs).toEqual([{ node: "322", kind: "model3d" }]);
+ expect(Object.keys(m.bindings).sort()).toEqual(["filenamePrefix", "image", "seed", "textureSize"]);
+ expect(m.defaults).toEqual({ textureSize: 4096 });
+ });
+ }
+
+ it("Pixal3D: MoGe-2 camera -> horizontal FOV -> Pixal3D conditioning, crop pad 1.1", () => {
+ const g = graph("image-to-3d-pixal3d");
+ const [loaderId, loader] = one(g, "LoadMoGeModel");
+ expect(loader.inputs.model_name).toBe("moge_2_vitl_normal_fp16.safetensors");
+ const [mogeId, moge] = one(g, "MoGeInference");
+ expect(moge.inputs.resolution_level).toBe(9);
+ expect(link(moge.inputs.moge_model)).toBe(loaderId);
+ const [fovId, fov] = one(g, "MoGeGeometryToFOV");
+ expect(fov.inputs).toMatchObject({ axis: "horizontal", unit: "degrees" });
+ expect(link(fov.inputs.moge_geometry)).toBe(mogeId);
+ const [, cond] = one(g, "Pixal3DConditioning");
+ expect(link(cond.inputs.camera_angle_x)).toBe(fovId);
+ expect(one(g, "UNETLoader")[1].inputs.unet_name).toBe("pixal3d_int8_convrot.safetensors");
+ expect(one(g, "ImageCropToMask")[1].inputs).toMatchObject({ width: 1024, height: 1024, pad_factor: 1.1 });
+ expect(byClass(g, "Trellis2Conditioning")).toHaveLength(0);
+ });
+
+ it("TRELLIS.2 (the fallback): its own UNet and conditioning, crop pad 1.0", () => {
+ const g = graph("image-to-3d-trellis2");
+ expect(one(g, "UNETLoader")[1].inputs.unet_name).toBe("trellis_2_int8_convrot.safetensors");
+ expect(one(g, "ImageCropToMask")[1].inputs).toMatchObject({ width: 1024, height: 1024, pad_factor: 1 });
+ expect(byClass(g, "Pixal3DConditioning")).toHaveLength(0);
+ one(g, "Trellis2Conditioning");
+ });
+});
+
+describe("image-to-3D routes", () => {
+ it("Pixal3D is the default open model; TRELLIS.2 stays as the fallback", () => {
+ expect(MODELS_3D.open.map((m) => m.id).slice(0, 2)).toEqual(["oss-pixal3d", "oss-trellis2"]);
+ expect(model3dRequest({ engine: "open", photo: "p.png" }).modelId).toBe("oss-pixal3d");
+ expect(model3dRequest({ engine: "open", photo: "p.png", modelId: "oss-trellis2" }).modelId).toBe("oss-trellis2");
+ expect(getModel("oss-pixal3d")?.routes[0]).toMatchObject({ provider: "comfyui", endpoint: "image-to-3d-pixal3d", op: "image-to-3d" });
+ expect(getModel("oss-trellis2")?.routes[0]).toMatchObject({ provider: "comfyui", endpoint: "image-to-3d-trellis2", op: "image-to-3d" });
+ expect(getPreset("app-image-to-3d")?.open?.modelId).toBe("oss-pixal3d");
+ });
+
+ it("viewers load the web GLB; results made before it fall back to the original", () => {
+ expect(viewerGlb({ url: "/api/files/raw.glb", meta: { web: "/api/files/web.glb" } })).toBe("/api/files/web.glb");
+ expect(viewerGlb({ url: "/api/files/raw.glb" })).toBe("/api/files/raw.glb");
+ expect(viewerGlb({ url: "/api/files/raw.glb", meta: { web: "" } })).toBe("/api/files/raw.glb");
+ const request = model3dRequest({ engine: "open", photo: "/api/files/p.png" });
+ const finished = model3dView({
+ outputs: [
+ { url: "/api/files/raw.glb", kind: "model3d", meta: { web: "/api/files/web.glb", poster: "/api/files/poster.webp" } },
+ { url: "/api/files/turn.mp4", kind: "video", meta: { role: "turntable" } },
+ ],
+ request,
+ });
+ expect(finished).toMatchObject({ glb: "/api/files/raw.glb", web: "/api/files/web.glb", turntable: "/api/files/turn.mp4", poster: "/api/files/poster.webp" });
+ // An old TRELLIS.2 result: its own 12 fps turntable, no web GLB.
+ const old = model3dView({ outputs: [{ url: "/api/files/old.glb", kind: "model3d" }, { url: "/api/files/old.mp4", kind: "video", meta: { role: "turntable" } }], request });
+ expect(old).toMatchObject({ glb: "/api/files/old.glb", web: "/api/files/old.glb", turntable: "/api/files/old.mp4" });
+ // Gallery tiles play the turntable or show the poster, never the GLB.
+ const mesh: OutputFile = { url: "/api/files/raw.glb", kind: "model3d", meta: { web: "/api/files/web.glb", poster: "/api/files/poster.webp" } };
+ expect(modelPreview({ outputs: [mesh, { url: "/api/files/turn.mp4", kind: "video", meta: { role: "turntable" } }] }, mesh)).toEqual({
+ poster: "/api/files/poster.webp",
+ video: "/api/files/turn.mp4",
+ });
+ });
+
+ it("the meshopt decoder is served from this origin, the same file as the installed package", () => {
+ const vendored = fs.readFileSync(path.join(root, "public/vendor/meshopt_decoder.js"), "utf8");
+ expect(vendored).toBe(fs.readFileSync(path.join(root, "node_modules/meshoptimizer/meshopt_decoder.cjs"), "utf8"));
+ // A classic script (model-viewer loads it with a <script> tag): no ES module syntax.
+ expect(vendored).not.toMatch(/^\s*export\s/m);
+ });
+});
+
+describe("the server's 3D finish", () => {
+ const glbOut = (o: Partial<OutputFile> = {}): OutputFile => ({ url: "/api/files/outputs/x.glb", kind: "model3d", contentType: "model/gltf-binary", assetId: "a1", ...o });
+
+ it("finishes the GLB of image-to-3D jobs from ComfyUI only", () => {
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, [glbOut()])).toBe(0);
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, [{ url: "/v.mp4", kind: "video" }, glbOut()])).toBe(1);
+ expect(modelToFinish({ provider: "mock", op: "image-to-3d" }, [glbOut()])).toBe(-1);
+ expect(modelToFinish({ provider: "fal", op: "image-to-3d" }, [glbOut()])).toBe(-1);
+ expect(modelToFinish({ provider: "comfyui", op: "scene-3d" }, [glbOut()])).toBe(-1);
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, [glbOut({ meta: { finish: { version: 1 } } })])).toBe(-1);
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, [glbOut({ contentType: "model/ply", url: "/x.ply" })])).toBe(-1);
+ });
+
+ it("reads the scripts' JSON result line", () => {
+ expect(lastJsonLine("some log\n{\"a\":1}\n")).toEqual({ a: 1 });
+ expect(lastJsonLine("no json")).toBeNull();
+ });
+
+ /** A textured box whose origin is off-centre (like Pixal3D's), with a given baked roughness / metallic. */
+ async function boxGlb(file: string, rough: number, metal: number) {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const p: number[] = [];
+ const uv: number[] = [];
+ const idx: number[] = [];
+ // 6 faces, 4 vertices each, centred at (2, 3, -1), size 1.
+ const faces = [
+ [[0, 0, 1], [1, 0, 0], [0, 1, 0]],
+ [[0, 0, -1], [-1, 0, 0], [0, 1, 0]],
+ [[1, 0, 0], [0, 0, -1], [0, 1, 0]],
+ [[-1, 0, 0], [0, 0, 1], [0, 1, 0]],
+ [[0, 1, 0], [1, 0, 0], [0, 0, -1]],
+ [[0, -1, 0], [1, 0, 0], [0, 0, 1]],
+ ];
+ for (const [n, u, v] of faces) {
+ const base = p.length / 3;
+ for (const [su, sv] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
+ p.push(2 + 0.5 * (n[0] + su * u[0] + sv * v[0]), 3 + 0.5 * (n[1] + su * u[1] + sv * v[1]), -1 + 0.5 * (n[2] + su * u[2] + sv * v[2]));
+ uv.push((su + 1) / 2, (sv + 1) / 2);
+ }
+ idx.push(base, base + 1, base + 2, base, base + 2, base + 3);
+ }
+ const prim = doc
+ .createPrimitive()
+ .setAttribute("POSITION", doc.createAccessor().setType("VEC3").setArray(new Float32Array(p)).setBuffer(buffer))
+ .setAttribute("TEXCOORD_0", doc.createAccessor().setType("VEC2").setArray(new Float32Array(uv)).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType("SCALAR").setArray(new Uint32Array(idx)).setBuffer(buffer));
+ const png = (r: number, g: number, b: number) => sharp({ create: { width: 64, height: 64, channels: 3, background: { r, g, b } } }).png().toBuffer();
+ const material = doc
+ .createMaterial()
+ .setBaseColorTexture(doc.createTexture().setImage(new Uint8Array(await png(200, 150, 100))).setMimeType("image/png"))
+ .setMetallicRoughnessTexture(doc.createTexture().setImage(new Uint8Array(await png(255, Math.round(rough * 255), Math.round(metal * 255)))).setMimeType("image/png"))
+ .setMetallicFactor(1)
+ .setRoughnessFactor(1);
+ prim.setMaterial(material);
+ doc.createScene().addChild(doc.createNode().setMesh(doc.createMesh().addPrimitive(prim)));
+ await new NodeIO().write(file, doc);
+ }
+
+ async function readWeb(file: string) {
+ await MeshoptDecoder.ready;
+ const doc = await new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ "meshopt.decoder": MeshoptDecoder }).read(file);
+ const mat = doc.getRoot().listMaterials()[0];
+ const mr = mat.getMetallicRoughnessTexture()!;
+ const { data, info } = await sharp(Buffer.from(mr.getImage()!)).raw().toBuffer({ resolveWithObject: true });
+ const px = (k: number) => data[k];
+ return {
+ extensions: doc.getRoot().listExtensionsUsed().map((e) => e.extensionName).sort(),
+ mime: mr.getMimeType(),
+ bounds: getBounds(doc.getRoot().listScenes()[0]),
+ rough: px(1) / 255,
+ metal: px(2) / 255,
+ channels: info.channels,
+ };
+ }
+
+ const script = path.join(root, "scripts/model3d/finish-glb.mjs");
+ const finishCli = (input: string, output: string, ...extra: string[]) => {
+ const r = spawnSync(process.execPath, [script, "--in", input, "--out", output, ...extra], { encoding: "utf8" });
+ expect(r.status, r.stderr).toBe(0);
+ return lastJsonLine<{ material: string; triangles: number; roughFloor: number; noMetal: boolean }>(r.stdout)!;
+ };
+
+ it("matte: roughness floor 0.8, metal off, pivot at the bottom centre, meshopt + WebP", async () => {
+ const raw = path.join(dir, "matte.glb");
+ const web = path.join(dir, "matte-web.glb");
+ await boxGlb(raw, 0.25, 0);
+ const stats = finishCli(raw, web);
+ expect(stats).toMatchObject({ material: "matte", triangles: 12, roughFloor: 0.8, noMetal: true });
+ const out = await readWeb(web);
+ expect(out.extensions).toEqual(expect.arrayContaining(["EXT_meshopt_compression", "EXT_texture_webp"]));
+ expect(out.mime).toBe("image/webp");
+ expect(out.rough).toBeGreaterThanOrEqual(0.78);
+ expect(out.metal).toBeLessThan(0.02);
+ // center --pivot below: the bottom sits on y = 0, centred in x and z.
+ expect(out.bounds.min[1]).toBeCloseTo(0, 2);
+ expect((out.bounds.min[0] + out.bounds.max[0]) / 2).toBeCloseTo(0, 2);
+ expect((out.bounds.min[2] + out.bounds.max[2]) / 2).toBeCloseTo(0, 2);
+ });
+
+ it("metal: no roughness floor, metal kept; a material can be forced", async () => {
+ const raw = path.join(dir, "metal.glb");
+ await boxGlb(raw, 0.1, 1);
+ const web = path.join(dir, "metal-web.glb");
+ expect(finishCli(raw, web)).toMatchObject({ material: "metal", roughFloor: 0, noMetal: false });
+ const out = await readWeb(web);
+ expect(out.rough).toBeLessThan(0.15);
+ expect(out.metal).toBeGreaterThan(0.95);
+ expect(finishCli(raw, path.join(dir, "forced.glb"), "--material", "matte")).toMatchObject({ material: "matte" });
+ });
+
+ it("finishModel adds the web GLB, keeps the raw GLB as the download and queues the turntable; no Chromium skips it, not a failure", async () => {
+ const raw = path.join(dir, "job.glb");
+ await boxGlb(raw, 0.3, 0);
+ const asset = saveFile({ data: fs.readFileSync(raw), contentType: "model/gltf-binary", source: "generation", generationId: "g3d" });
+ const before: OutputFile[] = [{ url: asset.url, kind: "model3d", contentType: asset.contentType, assetId: asset.id }];
+ const messages: string[] = [];
+ const after = await finishModel("g3d", before, { op: "image-to-3d", provider: "comfyui", onMessage: (m) => messages.push(m) });
+ expect(after).toHaveLength(1);
+ expect(after[0].url).toBe(asset.url);
+ const meta = after[0].meta as { web: string; finish: { version: number; material: string; triangles: number; turntable: string; webAsset: string } };
+ expect(meta.web).toMatch(/^\/api\/files\/.+\.glb$/);
+ expect(meta.web).not.toBe(asset.url);
+ expect(meta.finish).toMatchObject({ version: 2, material: "matte", triangles: 12, turntable: "queued" });
+ expect(meta.finish.webAsset).toBeTruthy();
+ // The job succeeds now; the turntable is rendered after.
+ expect(messages).toEqual(["Finishing the 3D model"]);
+ // Not finished twice.
+ expect(modelToFinish({ provider: "comfyui", op: "image-to-3d" }, after)).toBe(-1);
+ expect(pendingTurntable(after)).toBe(0);
+
+ // The turntable step on a server without Chromium: skipped, stored on the finished job, nothing added.
+ const saved = process.env.FUOBE_CHROMIUM;
+ process.env.FUOBE_CHROMIUM = path.join(dir, "no-such-chromium.exe");
+ let stored: OutputFile[] = after;
+ const states: string[] = [];
+ try {
+ startTurntable("g3d", {
+ read: () => stored,
+ write: (o) => {
+ stored = o;
+ states.push(String((o[0].meta!.finish as { turntable: string }).turntable));
+ },
+ });
+ await until(() => states.some((w) => w.startsWith("skipped")));
+ } finally {
+ if (saved === undefined) delete process.env.FUOBE_CHROMIUM;
+ else process.env.FUOBE_CHROMIUM = saved;
+ }
+ expect(states[0]).toBe("rendering");
+ expect(stored).toHaveLength(1);
+ expect(stored[0].meta).toMatchObject({ web: meta.web });
+ expect(pendingTurntable(stored)).toBe(-1);
+ });
+
+ it("a turntable for a job deleted meanwhile stores nothing; a missing web GLB says so", async () => {
+ const writes: OutputFile[][] = [];
+ const queued: OutputFile[] = [{ url: "/api/files/x.glb", kind: "model3d", assetId: "m-x", meta: { finish: { version: 2, turntable: "queued", webAsset: "no-such-asset" } } }];
+ startTurntable("g-gone", { read: () => null, write: (o) => void writes.push(o) });
+ await sleep(200);
+ expect(writes).toEqual([]);
+ let stored = queued;
+ startTurntable("g-noweb", { read: () => stored, write: (o) => void (stored = o) });
+ await until(() => pendingTurntable(stored) < 0);
+ expect((stored[0].meta!.finish as { turntable: string }).turntable).toBe("failed: the web GLB is missing");
+ });
+
+ it("withTurntable: progress while rendering, then the video and the poster; an old in-graph turntable gives way", () => {
+ const request = model3dRequest({ engine: "open", photo: "p.png" });
+ const mesh: OutputFile = { url: "/api/files/raw.glb", kind: "model3d", assetId: "m1", meta: { web: "/api/files/web.glb", finish: { version: 2, material: "metal", turntable: "queued" } } };
+ const old: OutputFile = { url: "/api/files/old.mp4", kind: "video", meta: { role: "turntable" } };
+ expect(model3dView({ outputs: [mesh], request }).rendering).toEqual({ queued: true, progress: 0 });
+ const rendering = withTurntable([mesh, old], "m1", { state: "rendering", progress: 0.4 });
+ expect(rendering[0].meta).toMatchObject({ web: "/api/files/web.glb", finish: { version: 2, turntable: "rendering", turntableProgress: 0.4 } });
+ expect(pendingTurntable(rendering)).toBe(0);
+ expect(model3dView({ outputs: rendering, request }).rendering).toEqual({ queued: false, progress: 0.4 });
+ const video: OutputFile = { url: "/api/files/turn.mp4", kind: "video", meta: { role: "turntable", fps: 24, frames: 96 } };
+ const done = withTurntable(rendering, "m1", { state: "done", video, poster: "/api/files/poster.webp" });
+ expect(done).toEqual([{ ...mesh, meta: { web: "/api/files/web.glb", poster: "/api/files/poster.webp", finish: { version: 2, material: "metal", turntable: "done" } } }, video]);
+ expect(pendingTurntable(done)).toBe(-1);
+ expect(model3dView({ outputs: done, request })).toMatchObject({ turntable: "/api/files/turn.mp4", poster: "/api/files/poster.webp", rendering: undefined, material: "metal" });
+ // Another model output is left alone.
+ expect(withTurntable([mesh], "other", { state: "done" })).toEqual([mesh]);
+ });
+
+ it("a GLB with no material, or one at the glTF defaults, becomes a matte dielectric (not three.js's dark metal)", async () => {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const tri = () =>
+ doc
+ .createPrimitive()
+ .setAttribute("POSITION", doc.createAccessor().setType("VEC3").setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0])).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType("SCALAR").setArray(new Uint32Array([0, 1, 2])).setBuffer(buffer));
+ const bare = tri();
+ const defaults = tri().setMaterial(doc.createMaterial("defaults"));
+ const chosen = tri().setMaterial(doc.createMaterial("chosen").setMetallicFactor(1).setRoughnessFactor(0.2));
+ doc.createScene().addChild(doc.createNode().setMesh(doc.createMesh().addPrimitive(bare).addPrimitive(defaults).addPrimitive(chosen)));
+ const raw = path.join(dir, "shape.glb");
+ await new NodeIO().write(raw, doc);
+ const web = path.join(dir, "shape-web.glb");
+ expect(finishCli(raw, web)).toMatchObject({ material: "unknown" });
+ await MeshoptDecoder.ready;
+ const out = await new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ "meshopt.decoder": MeshoptDecoder }).read(web);
+ const prims = out.getRoot().listMeshes().flatMap((m) => m.listPrimitives());
+ expect(prims.every((p) => !!p.getMaterial())).toBe(true);
+ const mats = out.getRoot().listMaterials().map((m) => [m.getMetallicFactor(), m.getRoughnessFactor()]);
+ // The bare and default ones are matte; one that was set on purpose is kept.
+ expect(mats).toEqual(expect.arrayContaining([[0, 0.8], [1, 0.2]]));
+ expect(mats).not.toContainEqual([1, 1]);
+ });
+
+ it("a GLB the script can't read keeps the raw result", async () => {
+ const asset = saveFile({ data: Buffer.from("not a glb"), contentType: "model/gltf-binary", source: "generation", generationId: "g-bad" });
+ const before: OutputFile[] = [{ url: asset.url, kind: "model3d", contentType: asset.contentType, assetId: asset.id }];
+ const after = await finishModel("g-bad", before, { op: "image-to-3d", provider: "comfyui" });
+ expect(after[0].url).toBe(asset.url);
+ expect((after[0].meta as { web?: string }).web).toBeUndefined();
+ expect((after[0].meta as { finish: { error: string } }).finish.error).toMatch(/^web GLB/);
+ });
+});
diff --git a/tests/model3d-runner.test.ts b/tests/model3d-runner.test.ts
new file mode 100644
index 00000000..f01f6670
--- /dev/null
+++ b/tests/model3d-runner.test.ts
@@ -0,0 +1,176 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+import type { OutputFile } from "@/lib/catalog/types";
+
+// How the runner hands an image-to-3D result from ComfyUI to the server's 3D finish (src/server/model3d-finish.ts):
+// the outputs are stored, the job stays running until the web GLB is made (a restart resumes it, a cancel stops
+// it), then it succeeds and its turntable is rendered after (a restart picks that up too).
+// The finish itself is stubbed here (tests/model3d-finish.test.ts runs the real scripts).
+
+vi.setConfig({ testTimeout: 30_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-3d-runner-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+type Done = (outputs: OutputFile[]) => void;
+type Store = { read: () => OutputFile[] | null; write: (o: OutputFile[]) => void };
+const finishes = new Map<string, { outputs: OutputFile[]; done: Done }>();
+const turntables = new Map<string, Store>();
+const stopped: string[] = [];
+vi.mock("@/server/model3d-finish", async (importOriginal) => {
+ const real = await importOriginal<typeof import("@/server/model3d-finish")>();
+ return {
+ ...real,
+ startModelFinish: (id: string, outputs: OutputFile[], o: { done: Done }) => {
+ if (!finishes.has(id)) finishes.set(id, { outputs, done: o.done });
+ },
+ startTurntable: (id: string, store: Store) => void turntables.set(id, store),
+ stopModelFinish: (id: string) => void stopped.push(id),
+ };
+});
+
+const gens = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { provider } = await import("@/server/providers");
+
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+async function until<T>(f: () => T | undefined | null | false, ms = 15_000): Promise<T> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = f();
+ if (v) return v;
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await sleep(50);
+ }
+}
+
+type Row = { status: string; message: string | null; outputs_json: string; external_meta_json: string | null };
+const row = (id: string) => db().prepare("SELECT * FROM generations WHERE id = ?").get(id) as Row;
+
+/** A Pixal3D job at ComfyUI, as submit() leaves it (running), or a finished one. */
+function insertJob(id: string, o: { meta?: Record<string, unknown>; outputs?: OutputFile[]; status?: string } = {}) {
+ const now = Date.now();
+ db()
+ .prepare(
+ `INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, progress, message, request_json, external_id, external_meta_json, outputs_json, created_at, updated_at)
+ VALUES (?, 'image-to-3d', 'oss-pixal3d', 'open', 'comfyui', 'image-to-3d', 'model3d', ?, 0.5, NULL, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(
+ id,
+ o.status ?? "running",
+ JSON.stringify({ feature: "image-to-3d", modelId: "oss-pixal3d", op: "image-to-3d", inputs: { images: ["/api/files/p.png"] } }),
+ `prompt-${id}`,
+ JSON.stringify(o.meta ?? {}),
+ JSON.stringify(o.outputs ?? []),
+ now,
+ now,
+ );
+}
+
+const comfy = provider("comfyui");
+const realPoll = comfy.poll;
+const realCancel = comfy.cancel;
+const polledIds: string[] = [];
+const canceledIds: string[] = [];
+comfy.poll = async (ctx) => {
+ polledIds.push(ctx.externalId);
+ // A tiny stand-in for the GLB (the finish is stubbed, nothing parses it).
+ return { state: "succeeded", outputs: [{ url: `data:model/gltf-binary;base64,${Buffer.from("glTF").toString("base64")}`, kind: "model3d", contentType: "model/gltf-binary" }] };
+};
+comfy.cancel = async (ctx) => void canceledIds.push(ctx.externalId);
+afterAll(() => {
+ comfy.poll = realPoll;
+ comfy.cancel = realCancel;
+});
+
+const glb = (finish: Record<string, unknown>): OutputFile => ({
+ url: "/api/files/raw.glb",
+ kind: "model3d",
+ contentType: "model/gltf-binary",
+ assetId: "a1",
+ meta: { web: "/api/files/web.glb", finish: { version: 2, ...finish } },
+});
+
+describe("the runner and the 3D finish", () => {
+ // First: the runner starts with this file's first ensureRunner().
+ it("on start, picks up the turntables of finished jobs still queued or rendering", async () => {
+ insertJob("done-queued", { status: "succeeded", outputs: [glb({ turntable: "queued" })] });
+ insertJob("done-rendering", { status: "succeeded", outputs: [glb({ turntable: "rendering", turntableProgress: 0.3 })] });
+ insertJob("done-done", { status: "succeeded", outputs: [glb({ turntable: "done" })] });
+ insertJob("done-skipped", { status: "succeeded", outputs: [glb({ turntable: "skipped: no Chromium" })] });
+ gens.ensureRunner();
+ expect([...turntables.keys()].sort()).toEqual(["done-queued", "done-rendering"]);
+ // The store reads and writes the job's outputs, and reads null once the job is gone.
+ const store = turntables.get("done-queued")!;
+ expect(store.read()).toEqual([glb({ turntable: "queued" })]);
+ store.write([glb({ turntable: "done" })]);
+ expect(JSON.parse(row("done-queued").outputs_json)).toEqual([glb({ turntable: "done" })]);
+ expect(gens.getGeneration("done-queued")!.status).toBe("succeeded");
+ gens.deleteGeneration("done-queued");
+ expect(stopped).toContain("done-queued");
+ expect(store.read()).toBeNull();
+ });
+
+ it("stores the GLB, keeps the job running while the web GLB is made, then succeeds and starts the turntable", async () => {
+ insertJob("job-finish");
+ gens.ensureRunner();
+ const started = await until(() => finishes.get("job-finish"));
+ const r = row("job-finish");
+ expect(r.status).toBe("running");
+ expect(r.message).toBe("Finishing the 3D model");
+ expect(JSON.parse(r.external_meta_json!)).toMatchObject({ finishing: true });
+ const stored = JSON.parse(r.outputs_json) as OutputFile[];
+ expect(stored).toHaveLength(1);
+ expect(stored[0]).toMatchObject({ kind: "model3d", contentType: "model/gltf-binary" });
+ expect(stored[0].assetId).toBeTruthy();
+ expect(started.outputs).toEqual(stored);
+
+ // Polled again while finishing: the provider isn't asked again, the same finish keeps running.
+ const asked = polledIds.filter((x) => x === "prompt-job-finish").length;
+ await sleep(2_000);
+ expect(polledIds.filter((x) => x === "prompt-job-finish").length).toBe(asked);
+ expect(row("job-finish").status).toBe("running");
+ expect(turntables.has("job-finish")).toBe(false);
+
+ const finished: OutputFile[] = [{ ...stored[0], meta: { web: "/api/files/web.glb", finish: { version: 2, turntable: "queued" } } }];
+ started.done(finished);
+ const g = gens.getGeneration("job-finish")!;
+ expect(g.status).toBe("succeeded");
+ expect(g.outputs).toEqual(finished);
+ expect(JSON.parse(row("job-finish").external_meta_json!)).not.toHaveProperty("finishing");
+ // Done: the model can be opened now, and its turntable is on its way.
+ expect(turntables.get("job-finish")!.read()).toEqual(finished);
+ });
+
+ it("a restart resumes the finish from the stored outputs, without asking the provider again", async () => {
+ const outputs: OutputFile[] = [{ url: "/api/files/raw.glb", kind: "model3d", contentType: "model/gltf-binary", assetId: "a1" }];
+ insertJob("job-resume", { meta: { finishing: true }, outputs });
+ gens.ensureRunner();
+ const started = await until(() => finishes.get("job-resume"));
+ expect(started.outputs).toEqual(outputs);
+ expect(polledIds).not.toContain("prompt-job-resume");
+ started.done(outputs);
+ expect(gens.getGeneration("job-resume")!.status).toBe("succeeded");
+ });
+
+ it("a cancel while finishing stops the finish without asking the provider, and a late result doesn't bring the job back", async () => {
+ insertJob("job-cancel");
+ gens.ensureRunner();
+ const started = await until(() => finishes.get("job-cancel"));
+ await gens.cancelGeneration("job-cancel");
+ expect(stopped).toContain("job-cancel");
+ expect(canceledIds).not.toContain("prompt-job-cancel");
+ started.done(started.outputs);
+ expect(gens.getGeneration("job-cancel")!.status).toBe("canceled");
+ expect(turntables.has("job-cancel")).toBe(false);
+ });
+});
diff --git a/tests/model3d-webm.test.ts b/tests/model3d-webm.test.ts
new file mode 100644
index 00000000..2a2177b3
--- /dev/null
+++ b/tests/model3d-webm.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+import { muxWebm, WEBM_IDS as I, type WebmFrame } from "@/components/model3d/webm";
+
+// The browser turntable recorder's WebM writer (src/components/model3d/webm.ts), read back with a small EBML reader.
+
+type Node = { id: number; start: number; size: number; data: Uint8Array; children?: Node[] };
+const MASTERS = new Set<number>([I.EBML, I.Segment, I.Info, I.Tracks, I.TrackEntry, I.Video, I.Cues, I.CuePoint, I.CueTrackPositions, I.Cluster]);
+
+function vint(b: Uint8Array, at: number, keepMarker: boolean): { value: number; len: number } {
+ let len = 1;
+ while (len <= 8 && !(b[at] & (0x80 >> (len - 1)))) len++;
+ let value = keepMarker ? b[at] : b[at] & (0xff >> len);
+ for (let i = 1; i < len; i++) value = value * 256 + b[at + i];
+ return { value, len };
+}
+
+function parse(b: Uint8Array, from = 0, to = b.length, base = from): Node[] {
+ const out: Node[] = [];
+ let at = from;
+ while (at < to) {
+ const id = vint(b, at, true);
+ const size = vint(b, at + id.len, false);
+ const dataAt = at + id.len + size.len;
+ const node: Node = { id: id.value, start: at - base, size: size.value, data: b.subarray(dataAt, dataAt + size.value) };
+ if (MASTERS.has(id.value)) node.children = parse(b, dataAt, dataAt + size.value, id.value === I.Segment ? dataAt : base);
+ out.push(node);
+ at = dataAt + size.value;
+ }
+ return out;
+}
+
+const find = (nodes: Node[], id: number) => nodes.filter((n) => n.id === id);
+const one = (nodes: Node[], id: number) => {
+ const found = find(nodes, id);
+ expect(found, id.toString(16)).toHaveLength(1);
+ return found[0];
+};
+const uint = (n: Node) => n.data.reduce((v, x) => v * 256 + x, 0);
+const text = (n: Node) => String.fromCharCode(...n.data);
+
+describe("muxWebm", () => {
+ const fps = 24;
+ // 96 frames at fixed timestamps, a key frame every second, payloads of varying size.
+ const frames: WebmFrame[] = Array.from({ length: 96 }, (_, i) => ({ timestamp: Math.round((i * 1e6) / fps), key: i % fps === 0, data: new Uint8Array(10 + (i % 7) * 50).fill(i) }));
+
+ it("writes a WebM with the duration, the track, cues and every frame at its own time", async () => {
+ const blob = muxWebm({ codec: "V_VP9", width: 1024, height: 768, fps, frames });
+ expect(blob.type).toBe("video/webm");
+ const b = new Uint8Array(await blob.arrayBuffer());
+ const [ebml, segment, ...rest] = parse(b);
+ expect(rest).toEqual([]);
+ expect(ebml.id).toBe(I.EBML);
+ expect(text(one(ebml.children!, 0x4282))).toBe("webm");
+ expect(segment.id).toBe(I.Segment);
+ const seg = segment.children!;
+ // Info: 1 ms timestamps, 96 frames at 24 fps = 4000 ms.
+ const info = one(seg, I.Info).children!;
+ expect(uint(one(info, I.TimestampScale))).toBe(1_000_000);
+ const duration = one(info, I.Duration);
+ expect(new DataView(duration.data.buffer, duration.data.byteOffset, 8).getFloat64(0)).toBeCloseTo(4000, 0);
+ // The track.
+ const track = one(one(seg, I.Tracks).children!, I.TrackEntry).children!;
+ expect(text(one(track, I.CodecID))).toBe("V_VP9");
+ const video = one(track, I.Video).children!;
+ expect([uint(one(video, I.PixelWidth)), uint(one(video, I.PixelHeight))]).toEqual([1024, 768]);
+ // One cluster per key frame (4), each with its 24 frames; cues point at the clusters.
+ const clusters = find(seg, I.Cluster);
+ expect(clusters).toHaveLength(4);
+ const cues = find(one(seg, I.Cues).children!, I.CuePoint);
+ expect(cues.map((c) => uint(one(c.children!, I.CueTime)))).toEqual(clusters.map((c) => uint(one(c.children!, I.Timestamp))));
+ expect(cues.map((c) => uint(one(one(c.children!, I.CueTrackPositions).children!, I.CueClusterPosition)))).toEqual(clusters.map((c) => c.start));
+ const blocks = clusters.flatMap((c) => {
+ const t0 = uint(one(c.children!, I.Timestamp));
+ return find(c.children!, I.SimpleBlock).map((s) => ({
+ track: s.data[0],
+ time: t0 + new DataView(s.data.buffer, s.data.byteOffset + 1, 2).getInt16(0),
+ key: !!(s.data[3] & 0x80),
+ payload: s.data.subarray(4),
+ }));
+ });
+ expect(blocks).toHaveLength(96);
+ blocks.forEach((blk, i) => {
+ expect(blk.track).toBe(0x81);
+ expect(blk.time).toBe(Math.round((i * 1000) / fps));
+ expect(blk.key).toBe(i % fps === 0);
+ expect(blk.payload).toEqual(frames[i].data);
+ });
+ });
+
+ it("needs frames that start with a key frame", () => {
+ expect(() => muxWebm({ codec: "V_VP8", width: 2, height: 2, fps, frames: [] })).toThrow();
+ expect(() => muxWebm({ codec: "V_VP8", width: 2, height: 2, fps, frames: [{ ...frames[1] }] })).toThrow();
+ });
+});
diff --git a/tests/open-engine.test.ts b/tests/open-engine.test.ts
index a282f096..541cc9e6 100644
--- a/tests/open-engine.test.ts
+++ b/tests/open-engine.test.ts
@@ -70,6 +70,7 @@ const ROUND3_MODELS: Record<string, { op: Operation; kind: MediaKind; workflow:
"oss-infinitetalk-v2v": { op: "lipsync", kind: "video", workflow: "lipsync-v2v-infinitetalk" },
"oss-latentsync": { op: "lipsync", kind: "video", workflow: "lipsync-latentsync16" },
"oss-mux": { op: "mux", kind: "video", workflow: "video-mux-audio" },
+ "oss-pixal3d": { op: "image-to-3d", kind: "model3d", workflow: "image-to-3d-pixal3d" },
"oss-trellis2": { op: "image-to-3d", kind: "model3d", workflow: "image-to-3d-trellis2" },
"oss-hunyuan3d-21": { op: "image-to-3d", kind: "model3d", workflow: "image-to-3d-hunyuan3d-21" },
"oss-tryon-klein": { op: "edit", kind: "image", workflow: "tryon-flux2-klein-4b" },
diff --git a/tests/pipeline.test.ts b/tests/pipeline.test.ts
index 60933780..d6919e2d 100644
--- a/tests/pipeline.test.ts
+++ b/tests/pipeline.test.ts
@@ -68,9 +68,9 @@ describe("createPipeline validation", () => {
try {
// The fixtures run on fal (now "connected"); the LLM has nothing to run on.
expect(() => createPipeline([step("words", "test-transcribe", { inputs: { audio: "/api/files/uploads/voice.wav" } }), { ...step("es", "text-llm", { op: "translate", params: { targetLanguage: "Spanish" } }), after: "words", chain: [{ slot: "prompt" }] }])).toThrow(
- /Step “es” would run as a demo \(Claude needs Claude or Ollama\)/,
+ /Step “es” would run as a demo \(Claude needs Claude or a local model\)/,
);
- expect(() => assertOneMode([{ label: "Joining clips", modelId: "join-clips", op: "concat" }, { label: "Writing", modelId: "text-llm", op: "write" }])).toThrow(/Writing needs Claude or Ollama/);
+ expect(() => assertOneMode([{ label: "Joining clips", modelId: "join-clips", op: "concat" }, { label: "Writing", modelId: "text-llm", op: "write" }])).toThrow(/Writing needs Claude or a local model/);
} finally {
setSetting("falKey", "");
}
diff --git a/tests/preset-cards.test.ts b/tests/preset-cards.test.ts
index bf9b9cc3..62389cc2 100644
--- a/tests/preset-cards.test.ts
+++ b/tests/preset-cards.test.ts
@@ -1,9 +1,11 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { APPS, EFFECTS, MOTIONS } from "@/lib/catalog";
+import { previewFor, toPresetCard } from "@/lib/preset-card-data";
import {
appFx,
CAMERA_MOVES,
effectFx,
+ fallbackPreview,
FX,
LAYER_BLEED,
layerTransform,
@@ -13,15 +15,20 @@ import {
PREVIEW_LAYERS,
presetHowTo,
presetRouteLines,
- previewFor,
+ proceduralPreview,
searchText,
- toPresetCard,
type CameraMove,
type MoveSpec,
type PreviewLayer,
} from "@/lib/preset-cards";
import type { Preset } from "@/lib/catalog/types";
+// Rendered media here: every effect, and one camera motion. Apps and the other motions have none.
+vi.mock("@/lib/catalog/preview-media.generated.json", async () => {
+ const { EFFECTS } = await import("@/lib/catalog");
+ return { default: { effects: Object.fromEntries(EFFECTS.map((e) => [e.id, "0123abcd"])), motions: { "motion-crash-zoom-in": "89abcdef" } } };
+});
+
const byName = (list: Preset[], name: string) => {
const p = list.find((x) => x.name === name);
if (!p) throw new Error(`no preset named ${name}`);
@@ -225,8 +232,12 @@ describe("slim card DTOs", () => {
const slim = JSON.stringify(list.map(toPresetCard)).length;
expect(slim / full).toBeLessThan(0.45);
}
- // The 255-card effects gallery ships well under 80 KB of card data.
- expect(JSON.stringify(EFFECTS.map(toPresetCard)).length).toBeLessThan(80_000);
+ // The 255-card effects gallery ships well under 80 KB of card data: with media (here every effect
+ // has some) only its 8-character hash goes out, and the procedural previews fit as well.
+ const cards = EFFECTS.map(toPresetCard);
+ const procedural = cards.map((c, i) => ({ ...c, preview: proceduralPreview(EFFECTS[i]) }));
+ expect(JSON.stringify(procedural).length).toBeLessThan(80_000);
+ expect(JSON.stringify(cards).length).toBeLessThan(JSON.stringify(procedural).length - 10_000);
});
it("reads the hue back from the preset look", () => {
@@ -247,6 +258,24 @@ describe("slim card DTOs", () => {
});
});
+describe("rendered preview media", () => {
+ it("sends only the media's hash, and a motion's move for its glyph", () => {
+ expect(toPresetCard(byName(EFFECTS, "Set On Fire")).preview).toStrictEqual({ media: "0123abcd" });
+ expect(toPresetCard(byName(MOTIONS, "Crash Zoom In")).preview).toStrictEqual({ media: "89abcdef", move: "crash-in" });
+ });
+
+ it("keeps the procedural preview for presets without media", () => {
+ const faceSwap = toPresetCard(byName(APPS, "Face Swap"));
+ expect(faceSwap.preview).toEqual({ poster: "/samples/previews/portrait.svg", scene: "portrait", fx: "swap" });
+ expect(faceSwap.preview).not.toHaveProperty("media");
+ expect(previewFor(byName(MOTIONS, "Crash Zoom Out"))).toEqual(proceduralPreview(byName(MOTIONS, "Crash Zoom Out")));
+ });
+
+ it("lets the client work out each card's procedural preview again, for when its media doesn't load", () => {
+ for (const p of [...APPS, ...MOTIONS, ...EFFECTS]) expect(fallbackPreview(toPresetCard(p)), p.id).toEqual(proceduralPreview(p));
+ });
+});
+
describe("preset route lines (details popover)", () => {
it("names each engine's model, or says there is none", () => {
const names: Record<string, string> = { "nano-banana-pro": "Nano Banana Pro" };
diff --git a/tests/preview-media.test.ts b/tests/preview-media.test.ts
new file mode 100644
index 00000000..d91c2839
--- /dev/null
+++ b/tests/preview-media.test.ts
@@ -0,0 +1,102 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import nextConfig from "../next.config";
+import { APPS, EFFECTS, MOTIONS } from "@/lib/catalog";
+import MANIFEST from "@/lib/catalog/preview-media.generated.json";
+import { isStill, kindOf, mediaHash, POSTER_WIDTHS, previewSrc, WEBP_WIDTH, type PreviewKind, type PreviewManifest } from "@/lib/preview-media";
+
+const root = path.resolve(__dirname, "..");
+
+/** Every file of a preset's media, as URLs. */
+const urlsOf = (kind: PreviewKind, id: string, hash: string) => {
+ const src = previewSrc(kind, id, hash);
+ return [...src.avifSrcSet.split(", ").map((s) => s.split(" ")[0]), src.webpSrc, ...(src.mp4Src ? [src.mp4Src] : [])];
+};
+
+describe("preview media files", () => {
+ it("files each preset's media under its type", () => {
+ for (const p of MOTIONS) expect(kindOf(p.id), p.id).toBe("motions");
+ for (const p of EFFECTS) expect(kindOf(p.id), p.id).toBe("effects");
+ for (const p of APPS) expect(kindOf(p.id), p.id).toBe("apps");
+ for (const id of ["look-anime", "motion", "motion-", "Motion-Zoom", "app-../x", "constructor-x"]) expect(kindOf(id), id).toBeUndefined();
+ });
+
+ it("names the poster sizes and the clip after the preset and its hash", () => {
+ expect(previewSrc("effects", "effect-set-on-fire", "0123abcd")).toEqual({
+ avifSrcSet:
+ "/previews/effects/effect-set-on-fire.0123abcd.320.avif 320w, /previews/effects/effect-set-on-fire.0123abcd.480.avif 480w, /previews/effects/effect-set-on-fire.0123abcd.640.avif 640w",
+ webpSrc: "/previews/effects/effect-set-on-fire.0123abcd.480.webp",
+ mp4Src: "/previews/effects/effect-set-on-fire.0123abcd.mp4",
+ });
+ });
+
+ it("gives a still (hash + s) its poster files and no clip", () => {
+ expect(isStill("0123abcds")).toBe(true);
+ expect(isStill("0123abcd")).toBe(false);
+ expect(isStill("0123abcdx")).toBe(false);
+ expect(previewSrc("apps", "app-relight", "0123abcds")).toEqual({
+ avifSrcSet:
+ "/previews/apps/app-relight.0123abcd.320.avif 320w, /previews/apps/app-relight.0123abcd.480.avif 480w, /previews/apps/app-relight.0123abcd.640.avif 640w",
+ webpSrc: "/previews/apps/app-relight.0123abcd.480.webp",
+ });
+ });
+
+ it("names the files the build script writes", () => {
+ // scripts/build-previews.mjs can't import this module, so it repeats the rules: keep them in step.
+ const script = fs.readFileSync(path.join(root, "scripts/build-previews.mjs"), "utf8");
+ expect(/const POSTER_WIDTHS = \[([\d, ]+)\];/.exec(script)?.[1]).toBe(POSTER_WIDTHS.join(", "));
+ expect(/const WEBP_WIDTH = (\d+);/.exec(script)?.[1]).toBe(String(WEBP_WIDTH));
+ expect(script).toContain('const KINDS = { motion: "motions", effect: "effects", app: "apps" };');
+ });
+
+ it("reads the manifest only on the server and in the preset header's own chunk", () => {
+ // Client chunks keep whatever client code uses from a module. preset-cards.ts is in the galleries',
+ // home's, shorts' and mixed media's chunks, so importing the manifest there (or preset-card-data.ts,
+ // which does) would ship it to all of them. A new importer belongs here only if it's a server page
+ // or loaded on its own (next/dynamic), like the preset header.
+ const importers = (spec: RegExp) =>
+ fs
+ .readdirSync(path.join(root, "src"), { recursive: true, encoding: "utf8" })
+ .filter((f) => /\.tsx?$/.test(f) && spec.test(fs.readFileSync(path.join(root, "src", f), "utf8")))
+ .map((f) => f.replaceAll("\\", "/"))
+ .sort();
+ expect(importers(/from "[^"]*preview-media\.generated\.json"/)).toEqual(["lib/preset-card-data.ts"]);
+ expect(importers(/from "[^"]*preset-card-data"/)).toEqual([
+ "app/(studio)/apps/page.tsx",
+ "app/(studio)/effects/page.tsx",
+ "app/(studio)/motions/page.tsx",
+ "app/(studio)/page.tsx",
+ "components/preset-header.tsx",
+ ]);
+ });
+
+ it("looks a preset's hash up in the manifest", () => {
+ const manifest: PreviewManifest = { motions: { "motion-zoom-in": "89abcdef" } };
+ expect(mediaHash(manifest, "motion-zoom-in")).toBe("89abcdef");
+ expect(mediaHash(manifest, "motion-zoom-out")).toBeUndefined();
+ expect(mediaHash(manifest, "effect-zoom-in")).toBeUndefined();
+ expect(mediaHash({}, "app-relight")).toBeUndefined();
+ });
+
+ it("lists only catalog presets whose files are all in public/previews, sorted", () => {
+ const manifest: PreviewManifest = MANIFEST;
+ const ids = new Set([...MOTIONS, ...EFFECTS, ...APPS].map((p) => p.id));
+ const kinds = Object.keys(manifest);
+ expect(kinds).toEqual([...kinds].sort());
+ for (const [kind, entries] of Object.entries(manifest) as [PreviewKind, Record<string, string>][]) {
+ expect(Object.keys(entries)).toEqual(Object.keys(entries).sort());
+ for (const [id, hash] of Object.entries(entries)) {
+ expect(ids.has(id), `${id} is in the catalog`).toBe(true);
+ expect(kindOf(id), id).toBe(kind);
+ expect(hash, id).toMatch(/^[0-9a-f]{8}s?$/);
+ for (const url of urlsOf(kind, id, hash)) expect(fs.statSync(path.join(root, "public", url), { throwIfNoEntry: false })?.size, url).toBeGreaterThan(0);
+ }
+ }
+ });
+
+ it("serves the files as immutable (their names change with their content)", async () => {
+ const rules = await nextConfig.headers!();
+ expect(rules).toContainEqual({ source: "/previews/:path*", headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }] });
+ });
+});
diff --git a/tests/runtime-auth.test.ts b/tests/runtime-auth.test.ts
index 6455d5cc..b7bd0cc8 100644
--- a/tests/runtime-auth.test.ts
+++ b/tests/runtime-auth.test.ts
@@ -155,6 +155,8 @@ describe("proxy matcher (C13)", () => {
expect(matches("/library")).toBe(true);
expect(matches("/next.svg")).toBe(false);
expect(matches("/samples/demo-model.glb")).toBe(false);
+ expect(matches("/previews/effects/effect-set-on-fire.0123abcd.480.avif")).toBe(false);
+ expect(matches("/vendor/meshopt_decoder.js")).toBe(false);
expect(matches("/favicon.ico")).toBe(false);
expect(matches("/_next/static/chunks/a.js")).toBe(false);
});
diff --git a/tests/shell-logic.test.ts b/tests/shell-logic.test.ts
index c396a66e..179e3ba9 100644
--- a/tests/shell-logic.test.ts
+++ b/tests/shell-logic.test.ts
@@ -5,6 +5,7 @@ import { EFFECTS, MOTIONS } from "@/lib/catalog";
import { copyText, copyWithToast } from "@/lib/clipboard";
import { loseContext, releaseVideo } from "@/lib/media-release";
import { GLYPHS, MOVE_GLYPH, glyphFor } from "@/lib/move-glyphs";
+import { previewFor, toPresetCard } from "@/lib/preset-card-data";
import {
CAMERA_MOVES,
effectFx,
@@ -12,17 +13,17 @@ import {
interleaveByCategory,
motionMove,
previewFlip,
- previewFor,
stableHash,
- toPresetCard,
type CameraMove,
} from "@/lib/preset-cards";
-import { createPlaybackStore, MIN_VISIBLE, type PlaybackEnv } from "@/lib/preview-playback";
+import { browserPlaybackEnv, createPlaybackStore, HOVER_INTENT, MIN_VISIBLE, SCROLL_SETTLE, type PlaybackEnv } from "@/lib/preview-playback";
import { pageAfter, progressiveStart, syncProgressive } from "@/lib/progressive";
import { storyboardName } from "@/lib/storyboard-board";
const toasts = vi.hoisted(() => ({ ok: [] as string[], error: [] as string[] }));
vi.mock("sonner", () => ({ toast: Object.assign((m: string) => void toasts.ok.push(m), { error: (m: string) => void toasts.error.push(m) }) }));
+// The procedural previews are what these tests look at: no preset has rendered media here.
+vi.mock("@/lib/catalog/preview-media.generated.json", () => ({ default: {} }));
import { capabilityGroup, usedByIndex } from "@/lib/workflow-usage";
describe("workflow 'used by' index", () => {
@@ -79,13 +80,24 @@ describe("progressive list paging", () => {
});
});
-/** A fake browser for the playback store. */
-function fakeEnv({ hover = false, reduced = false, height = 800 } = {}) {
+/** A fake browser for the playback store, with a clock that only moves when `advance` says so. */
+function fakeEnv({ hover = false, reduced = false, height = 800, saveData = false } = {}) {
let ioCallback: IntersectionObserverCallback | null = null;
const observed = new Set<Element>();
const scroll = new Set<() => void>();
- const frames: (() => void)[] = [];
- const flush = () => frames.splice(0).forEach((f) => f());
+ let now = 0;
+ const timers = new Set<{ at: number; cb: () => void }>();
+ const next = () => [...timers].sort((a, b) => a.at - b.at)[0];
+ /** Move the clock on by `ms`, running the timers that come due, in order. */
+ const advance = (ms: number) => {
+ const end = now + ms;
+ for (let due = next(); due && due.at <= end; due = next()) {
+ timers.delete(due);
+ now = due.at;
+ due.cb();
+ }
+ now = end;
+ };
const env: PlaybackEnv = {
matches: (q) => (q.includes("reduced-motion") ? reduced : q.includes("hover") ? hover : false),
IntersectionObserver: class {
@@ -99,27 +111,33 @@ function fakeEnv({ hover = false, reduced = false, height = 800 } = {}) {
observed.delete(el);
}
},
- requestFrame: (cb) => frames.push(cb),
+ delay: (cb, ms) => {
+ const t = { at: now + ms, cb };
+ timers.add(t);
+ return () => void timers.delete(t);
+ },
viewportHeight: () => height,
onScroll: (cb) => scroll.add(cb),
offScroll: (cb) => scroll.delete(cb),
+ saveData: () => saveData,
};
const card = (top: number, h = 200) => ({ getBoundingClientRect: () => ({ top, height: h }) }) as unknown as Element;
- const intersect = (entries: [Element, number][]) => {
+ const intersect = (entries: [Element, number][]) =>
ioCallback!(entries.map(([target, ratio]) => ({ target, intersectionRatio: ratio, isIntersecting: ratio > 0 }) as IntersectionObserverEntry), null as never);
- flush();
- };
- return { env, card, intersect, observed, scroll };
+ const scrolled = () => scroll.forEach((f) => f());
+ return { env, card, intersect, scrolled, advance, observed, scroll, timers };
}
describe("preview playback store", () => {
it("plays one preview at a time and stops only the one playing", () => {
- const { env } = fakeEnv({ hover: true });
+ const { env, advance } = fakeEnv({ hover: true });
const store = createPlaybackStore(env);
const seen: (string | null)[] = [];
store.subscribe(() => seen.push(store.getActive()));
store.play("a");
+ advance(HOVER_INTENT);
store.play("b");
+ advance(HOVER_INTENT);
expect(store.isActive("a")).toBe(false);
expect(store.isActive("b")).toBe(true);
store.stop("a");
@@ -128,15 +146,39 @@ describe("preview playback store", () => {
expect(seen).toEqual(["a", "b", null]);
});
+ it("waits for the pointer to rest on a card before playing it", () => {
+ const { env, advance, timers } = fakeEnv({ hover: true });
+ const store = createPlaybackStore(env);
+ const seen: (string | null)[] = [];
+ store.subscribe(() => seen.push(store.getActive()));
+ // Crossing one card on the way to another starts neither until the pointer stops.
+ store.play("a");
+ advance(HOVER_INTENT - 20);
+ store.stop("a");
+ store.play("b");
+ advance(HOVER_INTENT - 1);
+ expect(store.getActive()).toBeNull();
+ advance(1);
+ expect(store.getActive()).toBe("b");
+ // Leaving before the intent is up calls it off.
+ store.play("c");
+ store.stop("c");
+ expect(timers.size).toBe(0);
+ advance(1000);
+ expect(seen).toEqual(["b"]);
+ });
+
it("plays nothing when the user prefers reduced motion", () => {
- const store = createPlaybackStore(fakeEnv({ reduced: true }).env);
+ const { env, advance } = fakeEnv({ reduced: true });
+ const store = createPlaybackStore(env);
store.play("a");
+ advance(HOVER_INTENT);
expect(store.getActive()).toBeNull();
expect(store.reducedMotion()).toBe(true);
});
- it("on phones plays the mostly visible card nearest the middle of the screen", () => {
- const { env, card, intersect } = fakeEnv({ height: 800 });
+ it("on phones plays the mostly visible card nearest the middle of the screen, once scrolling stops", () => {
+ const { env, card, intersect, scrolled, advance } = fakeEnv({ height: 800 });
const store = createPlaybackStore(env);
const top = card(0); // centre at 100
const mid = card(320); // centre at 420, nearest 400
@@ -149,14 +191,62 @@ describe("preview playback store", () => {
[mid, MIN_VISIBLE - 0.1],
[low, 1],
]);
+ // Still scrolling: nothing starts (or downloads) yet.
+ advance(SCROLL_SETTLE - 100);
+ scrolled();
+ advance(SCROLL_SETTLE - 1);
+ expect(store.getActive()).toBeNull();
+ advance(1);
// The middle card isn't visible enough yet.
expect(store.getActive()).toBe("low");
intersect([[mid, 0.9]]);
+ expect(store.getActive()).toBe("low");
+ advance(SCROLL_SETTLE);
expect(store.getActive()).toBe("mid");
});
+ it("stops the playing card as soon as it scrolls mostly out of view", () => {
+ const { env, card, intersect, advance } = fakeEnv();
+ const store = createPlaybackStore(env);
+ const a = card(300);
+ store.watch(a, "a");
+ intersect([[a, 1]]);
+ advance(SCROLL_SETTLE);
+ expect(store.getActive()).toBe("a");
+ intersect([[a, MIN_VISIBLE - 0.1]]);
+ expect(store.getActive()).toBeNull();
+ });
+
+ it("doesn't autoplay on phones with Save-Data or on a 2G connection (hover still plays)", () => {
+ const { env, card, advance, observed, scroll } = fakeEnv({ saveData: true });
+ const store = createPlaybackStore(env);
+ store.watch(card(300), "a")();
+ expect(store.watchedCount()).toBe(0);
+ expect(observed.size).toBe(0);
+ expect(scroll.size).toBe(0);
+ store.play("a");
+ advance(HOVER_INTENT);
+ expect(store.getActive()).toBe("a");
+ });
+
+ it("reads Save-Data and the connection type from the browser", () => {
+ const saveData = (connection?: object) => {
+ vi.stubGlobal("navigator", { connection });
+ return browserPlaybackEnv.saveData();
+ };
+ try {
+ expect(saveData()).toBe(false);
+ expect(saveData({ saveData: true, effectiveType: "4g" })).toBe(true);
+ expect(saveData({ saveData: false, effectiveType: "2g" })).toBe(true);
+ expect(saveData({ effectiveType: "slow-2g" })).toBe(true);
+ expect(saveData({ saveData: false, effectiveType: "3g" })).toBe(false);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
it("cleans up: unwatching stops the card and the last one removes the scroll listener", () => {
- const { env, card, intersect, observed, scroll } = fakeEnv();
+ const { env, card, intersect, advance, observed, scroll, timers } = fakeEnv();
const store = createPlaybackStore(env);
const a = card(300);
const b = card(900);
@@ -164,14 +254,18 @@ describe("preview playback store", () => {
const offB = store.watch(b, "b");
expect(scroll.size).toBe(1);
intersect([[a, 1]]);
+ advance(SCROLL_SETTLE);
expect(store.getActive()).toBe("a");
offA();
expect(store.getActive()).toBeNull();
expect(observed.has(a)).toBe(false);
expect(scroll.size).toBe(1);
+ intersect([[b, 1]]);
offB();
expect(store.watchedCount()).toBe(0);
expect(scroll.size).toBe(0);
+ // A pick still waiting for the scroll to settle goes with the last card.
+ expect(timers.size).toBe(0);
});
it("does nothing without IntersectionObserver", () => {
diff --git a/vitest.config.ts b/vitest.config.ts
index cc92f57f..a6c1a783 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -8,5 +8,11 @@ export default defineConfig({
"server-only": path.resolve(__dirname, "tests/stubs/server-only.ts"),
},
},
- test: { include: ["tests/**/*.test.ts"], environment: "node" },
+ test: {
+ include: ["tests/**/*.test.ts"],
+ environment: "node",
+ // Local LLM servers on this machine (LM Studio on :1234, Unsloth Studio on :8888) stay out of the
+ // tests: Automatic would find them. Tests that need one start a stand-in and point Settings at it.
+ env: { LMSTUDIO_URL: "http://127.0.0.1:9", UNSLOTH_URL: "http://127.0.0.1:9" },
+ },
});
diff --git a/workflows/comfyui/image-to-3d-pixal3d.json b/workflows/comfyui/image-to-3d-pixal3d.json
new file mode 100644
index 00000000..8ab58da5
--- /dev/null
+++ b/workflows/comfyui/image-to-3d-pixal3d.json
@@ -0,0 +1,737 @@
+{
+ "3": {
+ "inputs": {
+ "seed": 56,
+ "steps": 12,
+ "cfg": 7.5,
+ "sampler_name": "euler",
+ "scheduler": "normal",
+ "denoise": 1,
+ "model": [
+ "108",
+ 0
+ ],
+ "positive": [
+ "298",
+ 0
+ ],
+ "negative": [
+ "298",
+ 1
+ ],
+ "latent_image": [
+ "87",
+ 0
+ ]
+ },
+ "class_type": "KSampler",
+ "_meta": {
+ "title": "KSampler"
+ }
+ },
+ "12": {
+ "inputs": {
+ "seed": 43,
+ "steps": 12,
+ "cfg": 1,
+ "sampler_name": "euler",
+ "scheduler": "normal",
+ "denoise": 1,
+ "model": [
+ "319",
+ 0
+ ],
+ "positive": [
+ "98",
+ 0
+ ],
+ "negative": [
+ "98",
+ 1
+ ],
+ "latent_image": [
+ "98",
+ 2
+ ]
+ },
+ "class_type": "KSampler",
+ "_meta": {
+ "title": "KSampler"
+ }
+ },
+ "15": {
+ "inputs": {
+ "clip_name": "dino_v3_L_naf_fp32.safetensors"
+ },
+ "class_type": "CLIPVisionLoader",
+ "_meta": {
+ "title": "Load CLIP Vision"
+ }
+ },
+ "18": {
+ "inputs": {
+ "seed": 42,
+ "steps": 20,
+ "cfg": 7.5,
+ "sampler_name": "euler",
+ "scheduler": "normal",
+ "denoise": 1,
+ "model": [
+ "126",
+ 0
+ ],
+ "positive": [
+ "91",
+ 0
+ ],
+ "negative": [
+ "91",
+ 1
+ ],
+ "latent_image": [
+ "91",
+ 2
+ ]
+ },
+ "class_type": "KSampler",
+ "_meta": {
+ "title": "KSampler"
+ }
+ },
+ "23": {
+ "inputs": {
+ "seed": 42,
+ "steps": 12,
+ "cfg": 7.5,
+ "sampler_name": "euler",
+ "scheduler": "simple",
+ "denoise": 1,
+ "model": [
+ "126",
+ 0
+ ],
+ "positive": [
+ "94",
+ 0
+ ],
+ "negative": [
+ "94",
+ 1
+ ],
+ "latent_image": [
+ "94",
+ 2
+ ]
+ },
+ "class_type": "KSampler",
+ "_meta": {
+ "title": "KSampler"
+ }
+ },
+ "55": {
+ "inputs": {
+ "model_name": "moge_2_vitl_normal_fp16.safetensors"
+ },
+ "class_type": "LoadMoGeModel",
+ "_meta": {
+ "title": "Load MoGe Model"
+ }
+ },
+ "56": {
+ "inputs": {
+ "resolution_level": 9,
+ "fov_x_degrees": 0,
+ "batch_size": 4,
+ "force_projection": true,
+ "apply_mask": true,
+ "refine_steps": 3,
+ "moge_model": [
+ "55",
+ 0
+ ],
+ "image": [
+ "312",
+ 0
+ ]
+ },
+ "class_type": "MoGeInference",
+ "_meta": {
+ "title": "Run MoGe Inference"
+ }
+ },
+ "87": {
+ "inputs": {
+ "batch_size": 1
+ },
+ "class_type": "EmptyTrellis2LatentStructure",
+ "_meta": {
+ "title": "Empty Trellis2 Latent Structure"
+ }
+ },
+ "91": {
+ "inputs": {
+ "positive": [
+ "298",
+ 0
+ ],
+ "negative": [
+ "298",
+ 1
+ ],
+ "voxel": [
+ "119",
+ 0
+ ]
+ },
+ "class_type": "Trellis2ShapeStage",
+ "_meta": {
+ "title": "Trellis2 Shape Stage"
+ }
+ },
+ "92": {
+ "inputs": {
+ "samples": [
+ "23",
+ 0
+ ],
+ "vae": [
+ "117",
+ 0
+ ]
+ },
+ "class_type": "VaeDecodeShapeTrellis",
+ "_meta": {
+ "title": "Trellis2 VAE Decode Shape"
+ }
+ },
+ "93": {
+ "inputs": {
+ "samples": [
+ "12",
+ 0
+ ],
+ "vae": [
+ "118",
+ 0
+ ],
+ "shape_subdivides": [
+ "92",
+ 1
+ ]
+ },
+ "class_type": "VaeDecodeTextureTrellis",
+ "_meta": {
+ "title": "Trellis2 VAE Decode Texture"
+ }
+ },
+ "94": {
+ "inputs": {
+ "target_resolution": 1536,
+ "positive": [
+ "91",
+ 0
+ ],
+ "negative": [
+ "91",
+ 1
+ ],
+ "shape_latent": [
+ "18",
+ 0
+ ],
+ "vae": [
+ "117",
+ 0
+ ]
+ },
+ "class_type": "Trellis2UpsampleStage",
+ "_meta": {
+ "title": "Trellis2 Upsample Stage"
+ }
+ },
+ "98": {
+ "inputs": {
+ "positive": [
+ "94",
+ 0
+ ],
+ "negative": [
+ "94",
+ 1
+ ],
+ "shape_latent": [
+ "23",
+ 0
+ ]
+ },
+ "class_type": "Trellis2TextureStage",
+ "_meta": {
+ "title": "Trellis2 Texture Stage"
+ }
+ },
+ "108": {
+ "inputs": {
+ "shift": 5,
+ "model": [
+ "125",
+ 0
+ ]
+ },
+ "class_type": "ModelSamplingSD3",
+ "_meta": {
+ "title": "ModelSamplingSD3"
+ }
+ },
+ "117": {
+ "inputs": {
+ "vae_name": "trellis_2_shape_vae_bf16.safetensors"
+ },
+ "class_type": "VAELoader",
+ "_meta": {
+ "title": "Load VAE"
+ }
+ },
+ "118": {
+ "inputs": {
+ "vae_name": "trellis_2_texture_vae_bf16.safetensors"
+ },
+ "class_type": "VAELoader",
+ "_meta": {
+ "title": "Load VAE"
+ }
+ },
+ "119": {
+ "inputs": {
+ "resolution": "32",
+ "samples": [
+ "3",
+ 0
+ ],
+ "vae": [
+ "117",
+ 0
+ ]
+ },
+ "class_type": "VaeDecodeStructureTrellis2",
+ "_meta": {
+ "title": "Trellis2 VAE Decode Structure"
+ }
+ },
+ "122": {
+ "inputs": {
+ "image": "product.png"
+ },
+ "class_type": "LoadImage",
+ "_meta": {
+ "title": "Load Image"
+ }
+ },
+ "125": {
+ "inputs": {
+ "multiplier": 0.7,
+ "model": [
+ "199",
+ 0
+ ]
+ },
+ "class_type": "RescaleCFG",
+ "_meta": {
+ "title": "RescaleCFG"
+ }
+ },
+ "126": {
+ "inputs": {
+ "multiplier": 0.5,
+ "model": [
+ "279",
+ 0
+ ]
+ },
+ "class_type": "RescaleCFG",
+ "_meta": {
+ "title": "RescaleCFG"
+ }
+ },
+ "147": {
+ "inputs": {
+ "texture_size": [
+ "288",
+ 0
+ ],
+ "mesh": [
+ "196",
+ 0
+ ],
+ "voxel_colors": [
+ "93",
+ 0
+ ],
+ "reference_mesh": [
+ "92",
+ 0
+ ]
+ },
+ "class_type": "BakeTextureFromVoxel",
+ "_meta": {
+ "title": "Bake Texture From Voxel"
+ }
+ },
+ "186": {
+ "inputs": {
+ "target_face_count": 250000,
+ "placement_mode": "midpoint",
+ "mesh": [
+ "241",
+ 0
+ ]
+ },
+ "class_type": "DecimateMesh",
+ "_meta": {
+ "title": "Decimate Mesh"
+ }
+ },
+ "192": {
+ "inputs": {
+ "bg_removal_model": [
+ "193",
+ 0
+ ],
+ "image": [
+ "122",
+ 0
+ ]
+ },
+ "class_type": "RemoveBackground",
+ "_meta": {
+ "title": "Remove Background"
+ }
+ },
+ "193": {
+ "inputs": {
+ "bg_removal_name": "birefnet.safetensors"
+ },
+ "class_type": "LoadBackgroundRemovalModel",
+ "_meta": {
+ "title": "Load Background Removal Model"
+ }
+ },
+ "196": {
+ "inputs": {
+ "segmenter": "pec",
+ "resolution": [
+ "288",
+ 0
+ ],
+ "padding": 1,
+ "weld_distance": 0.0002,
+ "mesh": [
+ "238",
+ 0
+ ]
+ },
+ "class_type": "UnwrapMesh",
+ "_meta": {
+ "title": "Unwrap Mesh UVs"
+ }
+ },
+ "199": {
+ "inputs": {
+ "cfg": 1,
+ "start_percent": 0.667,
+ "end_percent": 1,
+ "model": [
+ "319",
+ 0
+ ]
+ },
+ "class_type": "CFGOverride",
+ "_meta": {
+ "title": "CFG Override"
+ }
+ },
+ "202": {
+ "inputs": {
+ "mesh": [
+ "92",
+ 0
+ ]
+ },
+ "class_type": "GetMeshInfo",
+ "_meta": {
+ "title": "Get Mesh Info"
+ }
+ },
+ "210": {
+ "inputs": {
+ "mesh": [
+ "196",
+ 0
+ ],
+ "base_color": [
+ "147",
+ 0
+ ],
+ "metallic": [
+ "147",
+ 1
+ ],
+ "roughness": [
+ "147",
+ 2
+ ],
+ "occlusion": [
+ "233",
+ 0
+ ],
+ "normal_map": [
+ "224",
+ 0
+ ]
+ },
+ "class_type": "ApplyTextureToMesh",
+ "_meta": {
+ "title": "Apply Texture to Mesh"
+ }
+ },
+ "224": {
+ "inputs": {
+ "resolution": 2048,
+ "cage_distance": 0.05,
+ "ignore_backfaces": true,
+ "low_poly": [
+ "196",
+ 0
+ ],
+ "high_poly": [
+ "241",
+ 0
+ ]
+ },
+ "class_type": "BakeNormalMapFromMesh",
+ "_meta": {
+ "title": "Bake Normal Map from Mesh"
+ }
+ },
+ "233": {
+ "inputs": {
+ "resolution": 1024,
+ "samples": 64,
+ "max_distance": 0.71,
+ "strength": 1,
+ "bias": 0.01,
+ "low_poly": [
+ "196",
+ 0
+ ],
+ "high_poly": [
+ "241",
+ 0
+ ]
+ },
+ "class_type": "BakeAmbientOcclusion",
+ "_meta": {
+ "title": "Bake Ambient Occlusion"
+ }
+ },
+ "238": {
+ "inputs": {
+ "crease_angle": 180,
+ "mesh": [
+ "186",
+ 0
+ ]
+ },
+ "class_type": "MeshSmoothNormals",
+ "_meta": {
+ "title": "Smooth Mesh Normals"
+ }
+ },
+ "241": {
+ "inputs": {
+ "resolution": 768,
+ "sign_mode": "solid",
+ "sign_mode.fill": 20,
+ "sign_mode.qef": false,
+ "band": 1,
+ "project_back": 0,
+ "fix_poles": false,
+ "smooth_iters": 20,
+ "drop_small_components": 0.01,
+ "precluster_max_verts": 20000000,
+ "mesh": [
+ "202",
+ 0
+ ]
+ },
+ "class_type": "RemeshMesh",
+ "_meta": {
+ "title": "Remesh Mesh (Narrow-Band DC)"
+ }
+ },
+ "242": {
+ "inputs": {
+ "axis": "horizontal",
+ "unit": "degrees",
+ "moge_geometry": [
+ "56",
+ 0
+ ]
+ },
+ "class_type": "MoGeGeometryToFOV",
+ "_meta": {
+ "title": "Get FoV from MoGe Geometry"
+ }
+ },
+ "260": {
+ "inputs": {
+ "crease_angle": 180,
+ "mesh": [
+ "210",
+ 0
+ ]
+ },
+ "class_type": "MeshSmoothNormals",
+ "_meta": {
+ "title": "Smooth Mesh Normals"
+ }
+ },
+ "279": {
+ "inputs": {
+ "cfg": 1,
+ "start_percent": 0.769,
+ "end_percent": 1,
+ "model": [
+ "319",
+ 0
+ ]
+ },
+ "class_type": "CFGOverride",
+ "_meta": {
+ "title": "CFG Override"
+ }
+ },
+ "285": {
+ "inputs": {
+ "mesh": [
+ "260",
+ 0
+ ]
+ },
+ "class_type": "MeshToFile3D",
+ "_meta": {
+ "title": "Create 3D File (from Mesh)"
+ }
+ },
+ "288": {
+ "inputs": {
+ "value": 4096
+ },
+ "class_type": "PrimitiveInt",
+ "_meta": {
+ "title": "Texture Resolution"
+ }
+ },
+ "298": {
+ "inputs": {
+ "camera_angle_x": [
+ "242",
+ 0
+ ],
+ "clip_vision_model": [
+ "15",
+ 0
+ ],
+ "image": [
+ "312",
+ 0
+ ]
+ },
+ "class_type": "Pixal3DConditioning",
+ "_meta": {
+ "title": "Pixal3D Conditioning"
+ }
+ },
+ "312": {
+ "inputs": {
+ "width": 1024,
+ "height": 1024,
+ "pad_factor": 1.1,
+ "grow_mask": 0,
+ "background": "#000000",
+ "images": [
+ "122",
+ 0
+ ],
+ "masks": [
+ "192",
+ 0
+ ]
+ },
+ "class_type": "ImageCropToMask",
+ "_meta": {
+ "title": "Crop Image to Mask"
+ }
+ },
+ "319": {
+ "inputs": {
+ "unet_name": "pixal3d_int8_convrot.safetensors",
+ "weight_dtype": "default"
+ },
+ "class_type": "UNETLoader",
+ "_meta": {
+ "title": "Load Diffusion Model"
+ }
+ },
+ "322": {
+ "inputs": {
+ "filename_prefix": "fuobe/image-to-3d-pixal3d",
+ "viewport_state": {
+ "image": "",
+ "mask": "",
+ "normal": "",
+ "camera_info": {
+ "position": {
+ "x": 10,
+ "y": 10,
+ "z": 10.000000000000002
+ },
+ "target": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "zoom": 1,
+ "cameraType": "perspective",
+ "quaternion": {
+ "x": -0.2798481423331213,
+ "y": 0.3647051996310008,
+ "z": 0.11591689595929511,
+ "w": 0.8804762392171493
+ },
+ "fov": 35,
+ "aspect": 1,
+ "near": 0.01,
+ "far": 10000,
+ "frustum": {
+ "left": -5,
+ "right": 5,
+ "top": 5,
+ "bottom": -5
+ }
+ },
+ "recording": "",
+ "model_3d_info": []
+ },
+ "width": 1024,
+ "height": 1024,
+ "model_3d": [
+ "285",
+ 0
+ ]
+ },
+ "class_type": "Save3DAdvanced",
+ "_meta": {
+ "title": "Save 3D (Advanced)"
+ }
+ }
+}
diff --git a/workflows/comfyui/image-to-3d-trellis2.json b/workflows/comfyui/image-to-3d-trellis2.json
index d09d12b5..ef8f9076 100644
--- a/workflows/comfyui/image-to-3d-trellis2.json
+++ b/workflows/comfyui/image-to-3d-trellis2.json
@@ -205,7 +205,7 @@
},
"94": {
"inputs": {
- "target_resolution": "1536",
+ "target_resolution": 1536,
"positive": [
"91",
0
@@ -355,6 +355,20 @@
"title": "Bake Texture From Voxel"
}
},
+ "186": {
+ "inputs": {
+ "target_face_count": 250000,
+ "placement_mode": "midpoint",
+ "mesh": [
+ "241",
+ 0
+ ]
+ },
+ "class_type": "DecimateMesh",
+ "_meta": {
+ "title": "Decimate Mesh"
+ }
+ },
"192": {
"inputs": {
"bg_removal_model": [
@@ -502,7 +516,7 @@
"inputs": {
"crease_angle": 180,
"mesh": [
- "241",
+ "186",
0
]
},
@@ -514,10 +528,9 @@
"241": {
"inputs": {
"resolution": 768,
- "sign_mode": "udf",
+ "sign_mode": "solid",
+ "sign_mode.fill": 20,
"sign_mode.qef": false,
- "sign_mode.drop_inverted_components": false,
- "sign_mode.drop_enclosed_components": false,
"band": 1,
"project_back": 0,
"fix_poles": false,
@@ -603,7 +616,7 @@
"inputs": {
"width": 1024,
"height": 1024,
- "pad_factor": 1.1,
+ "pad_factor": 1,
"grow_mask": 0,
"background": "#000000",
"images": [
@@ -671,1341 +684,5 @@
"_meta": {
"title": "Save 3D (Advanced)"
}
- },
- "500": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 0,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "501": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 10,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "502": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 20,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "503": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 30,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "504": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 40,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "505": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 50,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "506": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 60,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "507": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 70,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "508": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 80,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "509": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 90,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "510": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 100,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "511": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 110,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "512": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 120,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "513": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 130,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "514": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 140,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "515": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 150,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "516": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 160,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "517": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 170,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "518": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 180,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "519": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 190,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "520": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 200,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "521": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 210,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "522": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 220,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "523": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 230,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "524": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 240,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "525": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 250,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "526": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 260,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "527": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 270,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "528": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 280,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "529": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 290,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "530": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 300,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "531": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 310,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "532": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 320,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "533": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 330,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "534": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 340,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "535": {
- "class_type": "RotateMesh",
- "inputs": {
- "mesh": [
- "260",
- 0
- ],
- "mode": "euler_xyz",
- "mode.angle_x": 0,
- "mode.angle_y": 350,
- "mode.angle_z": 0
- },
- "_meta": {
- "title": "RotateMesh"
- }
- },
- "600": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "500",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "601": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "501",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "602": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "502",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "603": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "503",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "604": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "504",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "605": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "505",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "606": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "506",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "607": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "507",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "608": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "508",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "609": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "509",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "610": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "510",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "611": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "511",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "612": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "512",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "613": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "513",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "614": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "514",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "615": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "515",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "616": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "516",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "617": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "517",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "618": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "518",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "619": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "519",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "620": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "520",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "621": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "521",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "622": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "522",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "623": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "523",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "624": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "524",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "625": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "525",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "626": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "526",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "627": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "527",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "628": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "528",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "629": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "529",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "630": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "530",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "631": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "531",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "632": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "532",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "633": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "533",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "634": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "534",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "635": {
- "class_type": "RenderMesh",
- "inputs": {
- "mesh": [
- "535",
- 0
- ],
- "mode": "auto",
- "width": 768,
- "height": 768,
- "background": "#ffffff"
- },
- "_meta": {
- "title": "RenderMesh"
- }
- },
- "700": {
- "class_type": "BatchImagesNode",
- "inputs": {
- "images.image0": [
- "600",
- 0
- ],
- "images.image1": [
- "601",
- 0
- ],
- "images.image2": [
- "602",
- 0
- ],
- "images.image3": [
- "603",
- 0
- ],
- "images.image4": [
- "604",
- 0
- ],
- "images.image5": [
- "605",
- 0
- ],
- "images.image6": [
- "606",
- 0
- ],
- "images.image7": [
- "607",
- 0
- ],
- "images.image8": [
- "608",
- 0
- ],
- "images.image9": [
- "609",
- 0
- ],
- "images.image10": [
- "610",
- 0
- ],
- "images.image11": [
- "611",
- 0
- ],
- "images.image12": [
- "612",
- 0
- ],
- "images.image13": [
- "613",
- 0
- ],
- "images.image14": [
- "614",
- 0
- ],
- "images.image15": [
- "615",
- 0
- ],
- "images.image16": [
- "616",
- 0
- ],
- "images.image17": [
- "617",
- 0
- ],
- "images.image18": [
- "618",
- 0
- ],
- "images.image19": [
- "619",
- 0
- ],
- "images.image20": [
- "620",
- 0
- ],
- "images.image21": [
- "621",
- 0
- ],
- "images.image22": [
- "622",
- 0
- ],
- "images.image23": [
- "623",
- 0
- ],
- "images.image24": [
- "624",
- 0
- ],
- "images.image25": [
- "625",
- 0
- ],
- "images.image26": [
- "626",
- 0
- ],
- "images.image27": [
- "627",
- 0
- ],
- "images.image28": [
- "628",
- 0
- ],
- "images.image29": [
- "629",
- 0
- ],
- "images.image30": [
- "630",
- 0
- ],
- "images.image31": [
- "631",
- 0
- ],
- "images.image32": [
- "632",
- 0
- ],
- "images.image33": [
- "633",
- 0
- ],
- "images.image34": [
- "634",
- 0
- ],
- "images.image35": [
- "635",
- 0
- ]
- },
- "_meta": {
- "title": "BatchImagesNode"
- }
- },
- "701": {
- "class_type": "CreateVideo",
- "inputs": {
- "images": [
- "700",
- 0
- ],
- "fps": 12,
- "bit_depth": "auto",
- "color_space": "sRGB",
- "codec": "none"
- },
- "_meta": {
- "title": "CreateVideo"
- }
- },
- "702": {
- "class_type": "SaveVideo",
- "inputs": {
- "video": [
- "701",
- 0
- ],
- "filename_prefix": "fuobe/image-to-3d-trellis2",
- "format": "auto",
- "format.codec": "auto",
- "codec": "auto"
- },
- "_meta": {
- "title": "SaveVideo"
- }
}
}
diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.json
index 4e6a2275..00485977 100644
--- a/workflows/comfyui/manifest.json
+++ b/workflows/comfyui/manifest.json
@@ -10601,11 +10601,11 @@
"notes": "LoadVideo + LoadAudio -> Concatenate Video (complete_audio) -> SaveVideo: the picture is stream-copied, only the new soundtrack is encoded. The single-track variant of video-mux-audio (voice-over, narration, music). A soundtrack longer than the video is cut at the video's end. Runs on CPU (verified end to end through Fuobe)."
},
{
- "id": "image-to-3d-trellis2",
- "title": "Image to textured 3D (TRELLIS.2, PBR GLB) + a 36-view turntable video",
+ "id": "image-to-3d-pixal3d",
+ "title": "Image to textured 3D (Pixal3D, PBR GLB, ~250k triangles)",
"capability": "image-to-3d",
- "file": "image-to-3d-trellis2.json",
- "source": "hand-built (scripts/comfy/hand-built/image-to-3d-trellis2.json)",
+ "file": "image-to-3d-pixal3d.json",
+ "source": "hand-built (scripts/comfy/hand-built/image-to-3d-pixal3d.json)",
"bindings": {
"image": [
{
@@ -10637,19 +10637,107 @@
"input": "value"
}
],
- "turntableFps": [
- {
- "node": "701",
- "input": "fps"
- }
- ],
"filenamePrefix": [
{
"node": "322",
"input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "322",
+ "kind": "model3d"
+ }
+ ],
+ "defaults": {
+ "textureSize": 4096
+ },
+ "limits": {},
+ "models": [
+ {
+ "file": "moge_2_vitl_normal_fp16.safetensors",
+ "folder": "geometry_estimation",
+ "url": "https://huggingface.co/Comfy-Org/MoGe/resolve/main/geometry_estimation/moge_2_vitl_normal_fp16.safetensors",
+ "sizeGb": 0.66
+ },
+ {
+ "file": "dino_v3_L_naf_fp32.safetensors",
+ "folder": "clip_vision",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/clip_vision/dino_v3_L_naf_fp32.safetensors",
+ "sizeGb": 1.22
+ },
+ {
+ "file": "pixal3d_int8_convrot.safetensors",
+ "folder": "diffusion_models",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/diffusion_models/pixal3d_int8_convrot.safetensors",
+ "sizeGb": 5.58
+ },
+ {
+ "file": "trellis_2_shape_vae_bf16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_shape_vae_bf16.safetensors",
+ "sizeGb": 1.1
+ },
+ {
+ "file": "trellis_2_texture_vae_bf16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/Pixal3D/resolve/main/vae/trellis_2_texture_vae_bf16.safetensors",
+ "sizeGb": 0.95
+ },
+ {
+ "file": "birefnet.safetensors",
+ "folder": "background_removal",
+ "url": "https://huggingface.co/Comfy-Org/BiRefNet/resolve/main/background_removal/birefnet.safetensors",
+ "sizeGb": 0.44
+ }
+ ],
+ "customNodes": [],
+ "vramGb": 16,
+ "license": "Pixal3D weights, DINOv3-NAF and TRELLIS VAEs as repackaged by Comfy-Org (licence not reviewed yet); MoGe-2 and BiRefNet as in their own entries",
+ "validated": true,
+ "notes": "Template 3d_pixal3d_trellis2_image_to_model, Pixal3D branch (the default image-to-3D route): MoGe-2 (geometry_estimation/moge_2_vitl_normal_fp16, resolution_level 9) estimates the camera from the cut-out, MoGeGeometryToFOV (horizontal, degrees) -> Pixal3DConditioning (camera_angle_x) with the DINOv3 encoder, UNet pixal3d_int8_convrot; ImageCropToMask pad_factor 1.1 (as the node asks for Pixal3D). BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui \"3d\"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23 (RTX 5090, the same graph run end to end): 114-185 s per object, 25-35 MB raw GLB at ~250k triangles (was 8M triangles / 317 MB before the decimate step), web GLB 1.6-3.6 MB; more faithful to the photo than TRELLIS.2 (209-238 s). The origin is the camera-aligned volume centre, hence the pivot fix. Surfaces can show faint planar facets from the shape decode (no graph setting removes them)."
+ },
+ {
+ "id": "image-to-3d-trellis2",
+ "title": "Image to textured 3D (TRELLIS.2, PBR GLB, ~250k triangles; fallback to Pixal3D)",
+ "capability": "image-to-3d",
+ "file": "image-to-3d-trellis2.json",
+ "source": "hand-built (scripts/comfy/hand-built/image-to-3d-trellis2.json)",
+ "bindings": {
+ "image": [
+ {
+ "node": "122",
+ "input": "image"
+ }
+ ],
+ "seed": [
+ {
+ "node": "3",
+ "input": "seed"
},
{
- "node": "702",
+ "node": "12",
+ "input": "seed"
+ },
+ {
+ "node": "18",
+ "input": "seed"
+ },
+ {
+ "node": "23",
+ "input": "seed"
+ }
+ ],
+ "textureSize": [
+ {
+ "node": "288",
+ "input": "value"
+ }
+ ],
+ "filenamePrefix": [
+ {
+ "node": "322",
"input": "filename_prefix"
}
]
@@ -10658,16 +10746,10 @@
{
"node": "322",
"kind": "model3d"
- },
- {
- "node": "702",
- "kind": "video",
- "role": "turntable"
}
],
"defaults": {
- "textureSize": 4096,
- "turntableFps": 12
+ "textureSize": 4096
},
"limits": {},
"models": [
@@ -10706,7 +10788,7 @@
"vramGb": 16,
"license": "MIT (TRELLIS.2 weights, DINOv3-NAF / TRELLIS VAEs as repackaged by Comfy-Org, BiRefNet)",
"validated": true,
- "notes": "Template 3d_pixal3d_trellis2_image_to_model: BiRefNet cut-out -> crop to mask -> TRELLIS.2 structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> remesh -> UV unwrap -> baked base colour / metallic / roughness / AO / normal at textureSize -> GLB (Save3DAdvanced, history ui \"3d\"). The graph adds a 36-view turntable (RotateMesh + RenderMesh, core) saved as MP4 at turntableFps."
+ "notes": "Template 3d_pixal3d_trellis2_image_to_model, TRELLIS.2 branch (the fallback image-to-3D route; Pixal3D is the default): Trellis2Conditioning with the DINOv3 encoder, UNet trellis_2_int8_convrot; ImageCropToMask pad_factor 1.0. BiRefNet cut-out -> ImageCropToMask 1024 -> structure (12 steps) -> shape (20) -> upsample to 1536 (12) -> texture (12) -> RemeshMesh (768, sign_mode solid, fill 20, band 1, smooth 20) -> DecimateMesh (250,000 faces, midpoint) -> smooth normals -> UV unwrap -> base colour / metallic / roughness baked at textureSize, normal map 2048 and AO 1024 baked from the dense remeshed mesh onto the decimated one -> GLB (Save3DAdvanced, history ui \"3d\"). No turntable in the graph: after the job the Fuobe server finishes the GLB (scripts/model3d/finish-glb.mjs: roughness floor by material, pivot at the bottom centre, meshopt + WebP 2048 web GLB as meta.web; the raw GLB stays the download) and renders a 96-frame 24 fps turntable on the CPU (scripts/model3d/render-turntable.mjs, model-viewer on SwiftShader) when Chromium and ffmpeg are available (src/server/model3d-finish.ts). GPU validation 2026-10-23: 209-238 s, 28-43 MB raw GLB at ~250k triangles. The 36-view RotateMesh + RenderMesh turntable (unlit, aliased, 12 fps) was removed."
},
{
"id": "image-to-3d-hunyuan3d-21",
diff --git a/workflows/comfyui/object_info.subset.json b/workflows/comfyui/object_info.subset.json
index 6d8ff5b5..dc0e0fc0 100644
--- a/workflows/comfyui/object_info.subset.json
+++ b/workflows/comfyui/object_info.subset.json
@@ -12322,7 +12322,7 @@
"COMFY_DYNAMICCOMBO_V3",
{
"display_name": "sign_mode",
- "tooltip": "udf: robust to messy/non-manifold input. sdf: clean single surface with QEF (Quadratic Error Function) sharp-feature recovery, but needs consistent winding.",
+ "tooltip": "udf: robust to messy/non-manifold input. sdf: clean single surface with QEF (Quadratic Error Function) sharp-feature recovery, but needs consistent winding. solid: one watertight solid from messy input: a global inside/outside graph cut (CelloCut) removes double shells and closes small holes. Slower.",
"options": [
{
"key": "udf",
@@ -12331,7 +12331,7 @@
"qef": [
"BOOLEAN",
{
- "tooltip": "QEF (Quadratic Error Function) dual-vertex placement for sharper edges.",
+ "tooltip": "QEF (Quadratic Error Function) vertex placement: sharp edges on hard-surface input, jagged creases on organic input.",
"advanced": true,
"default": false
}
@@ -12375,6 +12375,31 @@
]
}
}
+ },
+ {
+ "key": "solid",
+ "inputs": {
+ "required": {
+ "fill": [
+ "FLOAT",
+ {
+ "tooltip": "Cost of closing an opening relative to following the surface. Lower closes larger openings (0 puts a lid on a cup); higher only closes small holes and cracks.",
+ "default": 20,
+ "min": 0,
+ "max": 1000,
+ "step": 1
+ }
+ ],
+ "qef": [
+ "BOOLEAN",
+ {
+ "tooltip": "QEF (Quadratic Error Function) vertex placement: sharp edges on hard-surface input, jagged creases on organic input.",
+ "advanced": true,
+ "default": false
+ }
+ ]
+ }
+ }
}
]
}
@@ -12382,7 +12407,7 @@
"band": [
"FLOAT",
{
- "tooltip": "Narrow-band width in voxel units. In UDF mode also offsets the surface.",
+ "tooltip": "Narrow-band width in voxel units. In udf mode also offsets the surface; in solid mode it is the closing radius: creases are filleted and gaps bridged at this size, the surface sits half a voxel out.",
"advanced": true,
"default": 1,
"min": 0.5,
@@ -23098,5 +23123,274 @@
"output_node": false,
"has_intermediate_output": false,
"search_aliases": []
+ },
+ "DecimateMesh": {
+ "input": {
+ "required": {
+ "mesh": [
+ "MESH",
+ {}
+ ],
+ "target_face_count": [
+ "INT",
+ {
+ "tooltip": "Target max faces. 0 disables.",
+ "default": 200000,
+ "min": 0,
+ "max": 50000000
+ }
+ ],
+ "placement_mode": [
+ "COMFY_DYNAMICCOMBO_V3",
+ {
+ "display_name": "placement_mode",
+ "tooltip": "midpoint: cumesh-faithful (recommended). qem: QEM-optimal placement.",
+ "options": [
+ {
+ "key": "midpoint",
+ "inputs": {
+ "required": {}
+ }
+ },
+ {
+ "key": "qem",
+ "inputs": {
+ "required": {
+ "line_quadric_weight": [
+ "FLOAT",
+ {
+ "tooltip": "Per-edge line-quadric weight; preserves sharp ridges/valleys. 0 = off.",
+ "default": 0,
+ "min": 0,
+ "max": 100,
+ "step": 0.1
+ }
+ ],
+ "feature_edge_quadric_weight": [
+ "FLOAT",
+ {
+ "tooltip": "Extra quadric weight on dihedral feature edges (creases). 0 = off.",
+ "default": 0,
+ "min": 0,
+ "max": 1000,
+ "step": 1
+ }
+ ],
+ "feature_edge_min_dihedral_deg": [
+ "FLOAT",
+ {
+ "tooltip": "Minimum dihedral angle (degree) to count an edge as a feature edge.",
+ "default": 30,
+ "min": 0,
+ "max": 180,
+ "step": 1
+ }
+ ],
+ "clamp_v_to_edge": [
+ "BOOLEAN",
+ {
+ "tooltip": "Project the QEM-optimal position onto the collapsed edge segment.",
+ "default": true
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "hidden": {
+ "unique_id": [
+ "UNIQUE_ID"
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "mesh",
+ "target_face_count",
+ "placement_mode"
+ ],
+ "hidden": [
+ "unique_id"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "MESH"
+ ],
+ "output_is_list": [
+ false
+ ],
+ "output_name": [
+ "mesh"
+ ],
+ "output_tooltips": [
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "DecimateMesh",
+ "display_name": "Decimate Mesh",
+ "description": "Simplifies a mesh to a target face count using QEM, on the active compute device. 'midpoint' is the cumesh-faithful preset (best quality, preserves thin features / hair); 'qem' places vertices at the QEM optimum with line/feature-edge controls. Output stays welded.",
+ "python_module": "comfy_extras.nodes_mesh_postprocess",
+ "category": "3d/mesh",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": null,
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
+ "MoGeGeometryToFOV": {
+ "input": {
+ "required": {
+ "moge_geometry": [
+ "MOGE_GEOMETRY",
+ {}
+ ],
+ "axis": [
+ "COMBO",
+ {
+ "tooltip": "'vertical' (fov_y), 'horizontal' (fov_x), or 'diagonal'.",
+ "default": "vertical",
+ "multiselect": false,
+ "options": [
+ "vertical",
+ "horizontal",
+ "diagonal"
+ ]
+ }
+ ],
+ "unit": [
+ "COMBO",
+ {
+ "tooltip": "Output unit for the FOV.",
+ "default": "degrees",
+ "multiselect": false,
+ "options": [
+ "degrees",
+ "radians"
+ ]
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "moge_geometry",
+ "axis",
+ "unit"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "FLOAT",
+ "FLOAT"
+ ],
+ "output_is_list": [
+ false,
+ false
+ ],
+ "output_name": [
+ "fov",
+ "focal_pixels"
+ ],
+ "output_tooltips": [
+ null,
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "MoGeGeometryToFOV",
+ "display_name": "Get FoV from MoGe Geometry",
+ "description": "Derive the field of view and focal length from MoGe intrinsics.",
+ "python_module": "comfy_extras.nodes_moge",
+ "category": "image/geometry estimation",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": [
+ "moge",
+ "fov",
+ "geometry",
+ "intrinsics",
+ "field of view"
+ ],
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
+ "Pixal3DConditioning": {
+ "input": {
+ "required": {
+ "clip_vision_model": [
+ "CLIP_VISION",
+ {
+ "tooltip": "DINOv3 ViT-L/16 ClipVision."
+ }
+ ],
+ "image": [
+ "IMAGE",
+ {
+ "tooltip": "Preprocessed image from ImageCropToMask (pad_factor=1.1 for Pixal3D)."
+ }
+ ],
+ "camera_angle_x": [
+ "FLOAT",
+ {
+ "display_name": "fov",
+ "tooltip": "Horizontal FOV in degrees. Wire a MoGeGeometryToFOV (axis='horizontal', unit='degrees') for a per-image FoV (matches upstream default).",
+ "default": 49.13,
+ "min": 1,
+ "max": 170,
+ "step": 0.01
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "clip_vision_model",
+ "image",
+ "camera_angle_x"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "CONDITIONING",
+ "CONDITIONING"
+ ],
+ "output_is_list": [
+ false,
+ false
+ ],
+ "output_name": [
+ "positive",
+ "negative"
+ ],
+ "output_tooltips": [
+ null,
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "Pixal3DConditioning",
+ "display_name": "Pixal3D Conditioning",
+ "description": "",
+ "python_module": "comfy_extras.nodes_trellis2",
+ "category": "model/conditioning/trellis",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": null,
+ "essentials_category": null,
+ "has_intermediate_output": false
}
}