diff --git a/.agents/skills/formmorpheus/SKILL.md b/.agents/skills/formmorpheus/SKILL.md
index a9870fd..d3e1aa9 100644
--- a/.agents/skills/formmorpheus/SKILL.md
+++ b/.agents/skills/formmorpheus/SKILL.md
@@ -1,6 +1,6 @@
---
name: formmorpheus
-description: "Works with FormMorpheus, the Form family's animation studio (Vite interface in frontend/, FastAPI engine in backend/, Tauri 2 shell in src-tauri/, iPad build in ios/). Use when driving FormMorpheus through its MCP server (list, read, create, rename, duplicate, delete, restore, export, import), when reading or writing .fmo movie files or calling the engine's routes, when a question is about which exports the browser encodes or need the person's ffmpeg, when adding an AI voice (voice-over, text to speech, narration), when adding subtitles or captions, when building the iPad app, or when cutting a release (version sites, changelog, release commit). Trigger on FormMorpheus, formmorpheus, .fmo, ./formmorpheus, port 9494 or 5194, the formmorpheus MCP tools (get_context, list_movies, get_movie, get_movie_picture, manage_movie, export_movie, import_file, list_characters, add_character, list_voices, add_voice, list_subtitles, set_subtitles, list_commands, run_command), the window key, the dock, or ios/project.yml."
+description: "Works with FormMorpheus, the Form family's animation studio (Vite interface in frontend/, FastAPI engine in backend/, Tauri 2 shell in src-tauri/, iPad build in ios/). Use when driving FormMorpheus through its MCP server (list, read, create, rename, duplicate, delete, restore, export, import), when reading or writing .fmo movie files or calling the engine's routes, when a question is about which exports the browser encodes or need the person's ffmpeg, when adding an AI voice (voice-over, text to speech, narration), when adding subtitles or captions, when building the iPad app, or when cutting a release (version sites, changelog, release commit). Trigger on FormMorpheus, formmorpheus, .fmo, ./formmorpheus, port 9494 or 5194, the formmorpheus MCP tools (get_context, list_movies, get_movie, get_movie_picture, manage_movie, export_movie, import_file, list_characters, add_character, list_voices, add_voice, list_subtitles, set_subtitles, comfy_status, comfy_workflows, comfy_job, comfy_generate, list_commands, run_command), the window key, the dock, or ios/project.yml."
license: Apache-2.0
metadata:
author: nodemode-ai
diff --git a/.agents/skills/formmorpheus/sub-skills/mcp-tools/SUB-SKILL.md b/.agents/skills/formmorpheus/sub-skills/mcp-tools/SUB-SKILL.md
index a4d2113..a877863 100644
--- a/.agents/skills/formmorpheus/sub-skills/mcp-tools/SUB-SKILL.md
+++ b/.agents/skills/formmorpheus/sub-skills/mcp-tools/SUB-SKILL.md
@@ -18,9 +18,9 @@ Each tool's description starts with its class, and its annotations say it too (`
| Class | Tools | What happens |
| --- | --- | --- |
-| Reads | `get_context`, `list_movies`, `get_movie`, `get_movie_picture`, `list_characters`, `list_voices`, `list_subtitles`, `list_commands` | runs at once; refused only when the person blocked agents |
+| Reads | `get_context`, `list_movies`, `get_movie`, `get_movie_picture`, `list_characters`, `list_voices`, `list_subtitles`, `comfy_status`, `comfy_workflows`, `comfy_job`, `list_commands` | runs at once; refused only when the person blocked agents |
| Changes the library | `manage_movie`, and `run_command` for a command of that class | runs when the person allowed outside agents; otherwise asks in the window (deny, once, always), and with no window open it is refused |
-| Asks first | `export_movie`, `import_file`, `add_character`, `add_voice`, `set_subtitles` | always asks the person in the window (deny, once), then the window carries it out; with no window open it is refused at once with "Open FormMorpheus first" |
+| Asks first | `export_movie`, `import_file`, `add_character`, `add_voice`, `set_subtitles`, `comfy_generate` | always asks the person in the window (deny, once), then the window carries it out; with no window open it is refused at once with "Open FormMorpheus first" |
The rules live in `_gate` in `backend/app/routers/mcp.py`. The person's standing choice (ask, allowed, blocked) is `backend/app/services/agent_access.py`. An agent tab the person opened in the app's own dock carries an in-app token and is not asked for library changes; it is still asked before an export or an import.
@@ -34,7 +34,8 @@ The rules live in `_gate` in `backend/app/routers/mcp.py`. The person's standing
6. `list_characters {query?}` reads the Characters library (one `.fmo` per character in the data folder's `Characters` folder). `add_character {character, movie?, at?}` asks first, then the window opens `movie` (or uses the open one), places a copy of the character with fresh ids at `at` or the Playhead, and saves the movie; the answer gives `content`, `movie` and `saved`.
7. `list_voices {engine?}` reads which voice engines are ready (`builtin`, `local`, `online`) and their voices. `add_voice {text, engine?, voice?, language?, speed?, model?, movie?, at?}` asks first, then the window speaks the text, places the sound on the Timeline at `at` or the Playhead, and saves the movie. See `sub-skills/ai-voice`.
8. `list_subtitles {movie}` reads the movie's subtitles: whether the video shows them, the look, and each line in seconds and frames. `set_subtitles {movie?, lines?, srt?, mode?, show?, from_voices?, style?}` asks first, then the window changes the subtitles of the open movie (or `movie`, which it opens) and saves. See `sub-skills/subtitles`.
-9. `list_commands` shows the commands that are not tools (Recently Deleted, Exports, stacks, tags, fonts, ffmpeg's encoders); `run_command {id, params}` runs one.
+9. `comfy_status` reads the person's Comfy server (address, reachable, generation pack installed and recent enough, memory profile, device, whether a key is stored; never the key). `comfy_workflows` lists the workflows with their slots and whether each is ready. `comfy_generate {mode, prompt?, seed?, slots?, movie?}` asks first, then the window sends the blocks selected on its Timeline to Comfy (modes `fluid`, `animate`, `erase`, `add`, `relight`, `matte`, `upscale`), waits for the job, places the results on new tracks at the source's start and saves; the answer gives `blocks`, `movie` and `saved`. `comfy_job {job}` reads one job's state and result files. Check `comfy_status` and `comfy_workflows` first: the pack may be missing, and a workflow may lack models.
+10. `list_commands` shows the commands that are not tools (Recently Deleted, Exports, stacks, tags, fonts, ffmpeg's encoders); `run_command {id, params}` runs one.
## Refusals
@@ -42,7 +43,7 @@ Every refusal is one plain sentence. Pass it to the person as it is.
- Outside agents are off: ask the person to open FormMorpheus and allow outside agents.
- Blocked: the person turned agents off in Preferences; do not retry.
-- Open FormMorpheus first: export, import, add_character, add_voice and set_subtitles need the window.
+- Open FormMorpheus first: export, import, add_character, add_voice, set_subtitles and comfy_generate need the window.
- The person said no: do not ask again at once; a repeat within `DECLINE_PAUSE` seconds is refused without asking.
- Nobody answered within the wait: the question expired; ask the person to answer in the window.
diff --git a/.claude/skills/formmorpheus/SKILL.md b/.claude/skills/formmorpheus/SKILL.md
index a9870fd..d3e1aa9 100644
--- a/.claude/skills/formmorpheus/SKILL.md
+++ b/.claude/skills/formmorpheus/SKILL.md
@@ -1,6 +1,6 @@
---
name: formmorpheus
-description: "Works with FormMorpheus, the Form family's animation studio (Vite interface in frontend/, FastAPI engine in backend/, Tauri 2 shell in src-tauri/, iPad build in ios/). Use when driving FormMorpheus through its MCP server (list, read, create, rename, duplicate, delete, restore, export, import), when reading or writing .fmo movie files or calling the engine's routes, when a question is about which exports the browser encodes or need the person's ffmpeg, when adding an AI voice (voice-over, text to speech, narration), when adding subtitles or captions, when building the iPad app, or when cutting a release (version sites, changelog, release commit). Trigger on FormMorpheus, formmorpheus, .fmo, ./formmorpheus, port 9494 or 5194, the formmorpheus MCP tools (get_context, list_movies, get_movie, get_movie_picture, manage_movie, export_movie, import_file, list_characters, add_character, list_voices, add_voice, list_subtitles, set_subtitles, list_commands, run_command), the window key, the dock, or ios/project.yml."
+description: "Works with FormMorpheus, the Form family's animation studio (Vite interface in frontend/, FastAPI engine in backend/, Tauri 2 shell in src-tauri/, iPad build in ios/). Use when driving FormMorpheus through its MCP server (list, read, create, rename, duplicate, delete, restore, export, import), when reading or writing .fmo movie files or calling the engine's routes, when a question is about which exports the browser encodes or need the person's ffmpeg, when adding an AI voice (voice-over, text to speech, narration), when adding subtitles or captions, when building the iPad app, or when cutting a release (version sites, changelog, release commit). Trigger on FormMorpheus, formmorpheus, .fmo, ./formmorpheus, port 9494 or 5194, the formmorpheus MCP tools (get_context, list_movies, get_movie, get_movie_picture, manage_movie, export_movie, import_file, list_characters, add_character, list_voices, add_voice, list_subtitles, set_subtitles, comfy_status, comfy_workflows, comfy_job, comfy_generate, list_commands, run_command), the window key, the dock, or ios/project.yml."
license: Apache-2.0
metadata:
author: nodemode-ai
diff --git a/.claude/skills/formmorpheus/sub-skills/mcp-tools/SUB-SKILL.md b/.claude/skills/formmorpheus/sub-skills/mcp-tools/SUB-SKILL.md
index a4d2113..a877863 100644
--- a/.claude/skills/formmorpheus/sub-skills/mcp-tools/SUB-SKILL.md
+++ b/.claude/skills/formmorpheus/sub-skills/mcp-tools/SUB-SKILL.md
@@ -18,9 +18,9 @@ Each tool's description starts with its class, and its annotations say it too (`
| Class | Tools | What happens |
| --- | --- | --- |
-| Reads | `get_context`, `list_movies`, `get_movie`, `get_movie_picture`, `list_characters`, `list_voices`, `list_subtitles`, `list_commands` | runs at once; refused only when the person blocked agents |
+| Reads | `get_context`, `list_movies`, `get_movie`, `get_movie_picture`, `list_characters`, `list_voices`, `list_subtitles`, `comfy_status`, `comfy_workflows`, `comfy_job`, `list_commands` | runs at once; refused only when the person blocked agents |
| Changes the library | `manage_movie`, and `run_command` for a command of that class | runs when the person allowed outside agents; otherwise asks in the window (deny, once, always), and with no window open it is refused |
-| Asks first | `export_movie`, `import_file`, `add_character`, `add_voice`, `set_subtitles` | always asks the person in the window (deny, once), then the window carries it out; with no window open it is refused at once with "Open FormMorpheus first" |
+| Asks first | `export_movie`, `import_file`, `add_character`, `add_voice`, `set_subtitles`, `comfy_generate` | always asks the person in the window (deny, once), then the window carries it out; with no window open it is refused at once with "Open FormMorpheus first" |
The rules live in `_gate` in `backend/app/routers/mcp.py`. The person's standing choice (ask, allowed, blocked) is `backend/app/services/agent_access.py`. An agent tab the person opened in the app's own dock carries an in-app token and is not asked for library changes; it is still asked before an export or an import.
@@ -34,7 +34,8 @@ The rules live in `_gate` in `backend/app/routers/mcp.py`. The person's standing
6. `list_characters {query?}` reads the Characters library (one `.fmo` per character in the data folder's `Characters` folder). `add_character {character, movie?, at?}` asks first, then the window opens `movie` (or uses the open one), places a copy of the character with fresh ids at `at` or the Playhead, and saves the movie; the answer gives `content`, `movie` and `saved`.
7. `list_voices {engine?}` reads which voice engines are ready (`builtin`, `local`, `online`) and their voices. `add_voice {text, engine?, voice?, language?, speed?, model?, movie?, at?}` asks first, then the window speaks the text, places the sound on the Timeline at `at` or the Playhead, and saves the movie. See `sub-skills/ai-voice`.
8. `list_subtitles {movie}` reads the movie's subtitles: whether the video shows them, the look, and each line in seconds and frames. `set_subtitles {movie?, lines?, srt?, mode?, show?, from_voices?, style?}` asks first, then the window changes the subtitles of the open movie (or `movie`, which it opens) and saves. See `sub-skills/subtitles`.
-9. `list_commands` shows the commands that are not tools (Recently Deleted, Exports, stacks, tags, fonts, ffmpeg's encoders); `run_command {id, params}` runs one.
+9. `comfy_status` reads the person's Comfy server (address, reachable, generation pack installed and recent enough, memory profile, device, whether a key is stored; never the key). `comfy_workflows` lists the workflows with their slots and whether each is ready. `comfy_generate {mode, prompt?, seed?, slots?, movie?}` asks first, then the window sends the blocks selected on its Timeline to Comfy (modes `fluid`, `animate`, `erase`, `add`, `relight`, `matte`, `upscale`), waits for the job, places the results on new tracks at the source's start and saves; the answer gives `blocks`, `movie` and `saved`. `comfy_job {job}` reads one job's state and result files. Check `comfy_status` and `comfy_workflows` first: the pack may be missing, and a workflow may lack models.
+10. `list_commands` shows the commands that are not tools (Recently Deleted, Exports, stacks, tags, fonts, ffmpeg's encoders); `run_command {id, params}` runs one.
## Refusals
@@ -42,7 +43,7 @@ Every refusal is one plain sentence. Pass it to the person as it is.
- Outside agents are off: ask the person to open FormMorpheus and allow outside agents.
- Blocked: the person turned agents off in Preferences; do not retry.
-- Open FormMorpheus first: export, import, add_character, add_voice and set_subtitles need the window.
+- Open FormMorpheus first: export, import, add_character, add_voice, set_subtitles and comfy_generate need the window.
- The person said no: do not ask again at once; a repeat within `DECLINE_PAUSE` seconds is refused without asking.
- Nobody answered within the wait: the question expired; ask the person to answer in the window.
diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md
index 2fb5592..2ebd5c9 100644
--- a/.docs/wiki/Agents.md
+++ b/.docs/wiki/Agents.md
@@ -8,9 +8,9 @@ The server is `POST /mcp` on the engine: Streamable HTTP in stateless JSON, prot
| Class | Tools | What happens |
|---|---|---|
-| Reads | `get_context`, `list_movies`, `get_movie`, `get_movie_picture`, `list_characters`, `list_voices`, `list_subtitles`, `list_commands`, and through `run_command` the commands `list_deleted`, `list_exports`, `list_stacks`, `export_capabilities`, `list_fonts` | run at once; refused only when agents are blocked |
+| Reads | `get_context`, `list_movies`, `get_movie`, `get_movie_picture`, `list_characters`, `list_voices`, `list_subtitles`, `comfy_status`, `comfy_workflows`, `comfy_job`, `list_commands`, and through `run_command` the commands `list_deleted`, `list_exports`, `list_stacks`, `export_capabilities`, `list_fonts` | run at once; refused only when agents are blocked |
| Changes the library | `manage_movie` (create, rename, duplicate, delete, restore) and, through `run_command`, `set_tags` and `set_stack` | ask in the window under Ask; go ahead under Allowed |
-| Asks first | `export_movie`, `import_file`, `add_character`, `add_voice`, `set_subtitles` | ask every time, then the open window carries them out |
+| Asks first | `export_movie`, `import_file`, `add_character`, `add_voice`, `set_subtitles`, `comfy_generate` | ask every time, then the open window carries them out |
- A movie is found by name inside the library folder only. Delete moves a movie to Recently Deleted; nothing is erased.
- `import_file` takes an absolute path inside the library folder, a picture, video, sound, font or layered image file, up to 2 GB. The window opens the movie, imports the file and saves the movie.
@@ -18,7 +18,9 @@ The server is `POST /mcp` on the engine: Streamable HTTP in stateless JSON, prot
- `list_characters` reads the Characters library (one `.fmo` per character in `Characters/` of the data folder). `add_character {character, movie?, at?}` is carried out by the window: it opens `movie` (or uses the open one), places a copy of the character with fresh ids at `at` or the Playhead through the Characters panel's Add to Movie, and saves the movie.
- `list_voices {engine?}` reads, for `builtin`, `local` and `online`, whether each is ready, why not when it is not, and its voices when it is. `add_voice {text, engine?, voice?, language?, speed?, model?, movie?, at?}` is carried out by the window: it speaks the text (at most 10000 characters, 2000 online, and online sends the text to that service), places the sound on the Timeline of `movie` (or the open movie) at `at` or the Playhead, and saves the movie.
- `list_subtitles {movie}` reads the movie's subtitles from its file, without the window: whether the video shows them, the look, and each line with its id, start and end in seconds and frames (at most 500 lines, with a count of the rest). `set_subtitles {movie?, lines?, srt?, mode?, show?, from_voices?, style?}` is carried out by the window: `lines` (seconds) or `srt` (the text of a .srt or .vtt file) give the lines, `mode` is `replace` (default) or `add`, `from_voices` makes lines from every AI-voice sound, `show` turns them on or off and `style` sets font, size, position, color and band. It changes `movie` (or the open movie) and saves it. At most 2000 lines.
-- The server waits 2 minutes for an answer to a question, 10 minutes for an export or a spoken line and 2 minutes for an import or an added character.
+- `comfy_status` reads, in the engine and without the window, the Comfy server's address, whether it can be reached, whether Comfy-FormBridge-Suite is installed and recent enough, its memory profile and device, and only whether a sign-in key is saved. `comfy_workflows` reads the workflows the server offers, their slots and what each lacks. `comfy_job {job}` reads one job's state, progress, result files and failure reason. All three call `services/comfy_bridge.py` and turn its errors into plain tool errors.
+- `comfy_generate {mode, prompt?, seed?, slots?, movie?}` is carried out by the window. `mode` is fluid, animate, erase, add, relight, matte or upscale; the window's own mode-to-workflow map picks the workflow, and the sources are the blocks selected in the window, so the agent does not name files. The tool checks the handshake first, so a person is not asked when the pack is missing. After the yes the window sends the job, waits, places the results on new tracks at the source's start as one undo step, and saves the movie, as `add_voice` does (`runComfyFromAgent` in `app/features/comfy-generate.ts`, called from `app/agent-bridge.ts`).
+- The server waits 2 minutes for an answer to a question, 10 minutes for an export or a spoken line, 2 minutes for an import or an added character and 30 minutes for a Comfy job, which can be slow on a computer without a graphics card.
- No tool reads another file or folder on the computer, and none returns the window key, a socket ticket or a tab's token.
## The Outside agents choice
@@ -71,6 +73,7 @@ The engine queues the question, the window polls `/api/mcp/bridge/next` with its
| `FORMMORPHEUS_AGENT_DIR` | the working folder of the Claude Code, Codex and Cursor tabs (default `Agent` in the data folder) |
| `FORMMORPHEUS_MCP_URL` | for `./formmorpheus mcp`: the engine's `/mcp` address; no engine is started then |
| `FORMMORPHEUS_MCP_AUTOSTART` | for `./formmorpheus mcp`: `0` never starts an engine |
+| `FORMMORPHEUS_COMFY_URL` | the address of the Comfy server that `comfy_*` tools and Generate use; wins over the saved address (default `http://127.0.0.1:8188`) |
The engine sets `FORMMORPHEUS_TERMINAL`, `FORMMORPHEUS_URL` and `FORMMORPHEUS_MCP_URL` in every tab, and `FORMMORPHEUS_INAPP_TOKEN` in the Codex, Cursor and Antigravity tabs. The launcher sets `FORMMORPHEUS_CALLER_DIR`. None of these is set by hand.
diff --git a/.docs/wiki/Media-and-Export.md b/.docs/wiki/Media-and-Export.md
index f5d4e54..93c1a35 100644
--- a/.docs/wiki/Media-and-Export.md
+++ b/.docs/wiki/Media-and-Export.md
@@ -37,6 +37,26 @@ Files live in `voice/` of the data folder: `runtime/` and `models/` for the buil
- **Sources.** An AI voice's sound carries `spoken` (see AI Voice), and `cuesForSound` turns it into cues, estimating the timing by sentence length when the sound has none. A recording or a sound file is listened to by `media/speech-pcm.ts`, which makes a 16 kHz mono WAV of the whole asset, and the engine's `POST /api/voice/transcribe` (Whisper base in the built-in voice's runtime).
- **Files.** `io/subtitle-files.ts` reads `.srt` and `.vtt` (told apart by content, tags stripped) and writes either.
+## Generate with Comfy
+
+Desktop only. A person's Comfy server makes video from pictures of the movie, through the Comfy-FormBridge-Suite pack installed there. The engine is the only part that talks to the server; the window never does.
+
+| Part | Role |
+|---|---|
+| `backend/app/services/comfy_bridge.py` | the client of the pack's `/formbridge/v1` routes: handshake, workflows and their readiness, uploads, jobs, one websocket follower for progress and previews, result files |
+| `backend/app/routers/comfy.py` | `/api/comfy`: `GET /status`, `PUT /server`, `PUT` and `DELETE /key`, `GET /workflows`, `GET /workflows/{id}/readiness`, `POST /run`, `GET /jobs/{id}`, `GET /jobs/{id}/files/{n}`, `POST /jobs/{id}/cancel` |
+| `frontend/src/io/comfy-api.ts` | the window's calls to those routes, and the readiness sentences |
+| `frontend/src/ui/generate-panel.ts` | the card: mode, selection check, progress bar and preview, Retry with another seed, Cancel |
+| `frontend/src/ui/comfy-settings.ts` | the Comfy section of Preferences: address, Test, sign-in key |
+| `frontend/src/app/features/comfy-generate.ts` | collects the frames and keyframes, runs the job, places the results (`runComfyFromAgent` for agents) |
+
+- **Address and key.** The address is `comfy_url` in `settings.json`, default `http://127.0.0.1:8188`, and `FORMMORPHEUS_COMFY_URL` wins. An optional sign-in key is in the system keyring (account `comfy-key`), sent as a Bearer header to that one server, never stored in the settings and never returned by a route.
+- **Modes.** One map in the window turns a mode into a workflow: Fluid shot, `video.fluid`; Animate a drawing, `video.animate`; Erase, `video.clean`; Add and Relight, `video.shot`; Matte, `video.matte`; Upscale, `video.upscale`. Sources are the selected blocks. The paint-over is the selected Drawing or Flipbook, or the first one on a higher track that covers the video's start. Its alpha becomes the mask, white on black. Keyframes of a Flipbook snap to multiples of 8 within the block.
+- **Sending.** The window uploads the frames it drew in a multipart `POST /run`; for a movie slot the engine extracts the frames of a library asset with the app's ffmpeg. The engine reads the multipart body itself, one field at a time (1 MB per field, 8 GB in all).
+- **Jobs.** One client id per engine start and one websocket follower that keeps the latest progress, preview and state per job (up to 64), reconnects after 2 seconds and stops after 5 idle minutes; polling every 1.5 seconds is the fallback. Status calls time out after 3 seconds, transfers after 10 minutes. Results are in `Jobs/comfy-/` of the data folder and go with the engine's orphan sweep after 30 minutes idle.
+- **Landing.** The results are placed directly through the import path (`importMedia`, `importSequence`), so the video, its mask track and the provenance are one engine run named `Comfy: `, one undo step. The new asset carries an optional `generated` field (workflow and its version, mode, seed, job, and the prompt and source when there are any) that is saved in the `.fmo` and dropped by `normalize.ts` when malformed.
+- **Not on iPad.** The command, the card and the Preferences section are not registered there, and `/api/comfy/*` is desktop-only in the API contract check.
+
## Sync
The AudioContext is the clock while sound plays. Loop turns restart the sound from the new frame without a clock jump. Output latency leaves sound a constant frame or two behind the Playhead readout.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3a2f3b4..db68df0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,24 @@
Versions are `v*.*.*` with dots. Dates are US Eastern. Each section is written for the person using FormMorpheus; the reasons behind a change are in the `HASHOUT_LOG.md` beside the code.
+## 0.39.0 · 2026-11-29
+
+A Comfy server can now make video for your movie. Create · Generate with Comfy... sends pictures from the Timeline to it and brings the result back on new tracks. It is for the desktop; the iPad app does not have it.
+
+### New
+- Generate with Comfy... in the Create menu has seven modes: a fluid shot from the keyframes of a Flipbook, Animate a drawing, Erase on a video, Add to a video, Relight a video, Matte and Upscale. Erase, Add and Relight use a drawing painted over the video's first frame to say where to work. The card says in a sentence what to select until it fits.
+- The card shows the place in the queue, then a progress bar with a preview picture, with Cancel and Retry with another seed. The result lands on new tracks at the start of the source block, with a mask track when the mode makes one, in one undo step. A video made this way keeps a note of its workflow and seed in the movie file.
+- Preferences has a Comfy page: the server's address (a Comfy server on this computer by default, or `FORMMORPHEUS_COMFY_URL`), Test, and an optional sign-in key kept in this computer's keychain and sent only to that server.
+- When the server is not ready, the card lists what it lacks in plain words: the pack to install, the nodes, or each model with its size and the folder to put it in. Comfy-FormBridge-Suite must be installed in the server's `custom_nodes` folder.
+- Outside agents can check the server and follow its jobs, and `comfy_generate` makes video with your approval in the window, using the blocks you have selected. See Agents in the manual.
+- A long menu shows a soft fade and a small arrow at its bottom while more items are below, and they go once you reach the last item.
+
+### Improved
+- A movie file whose note of where a video came from is damaged still opens; the note is dropped and the video stays.
+
+### Fixed
+- Windows and Linux: menus from the menu bar, their submenus and right-click menus such as the Stage menu no longer cover the menu bar. They stay at most three quarters of the window tall and scroll; right-click menus still open at the pointer.
+
## 0.38.1 · 2026-11-29
A fix release: saving, importing, settings and outside agents are more careful, and outside agents keep asking on a computer with no system keyring.
diff --git a/CLAUDE.md b/CLAUDE.md
index 1ba8541..388ffba 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -9,7 +9,7 @@ The form family's animation studio: a Stage over a Timeline, drawn frame by fram
- `./formmorpheus desktop dev` and `./formmorpheus desktop build` (or `./build_app`) run and build the Tauri app.
- `cd frontend && npx tsc --noEmit` is the typecheck; `npm run build` typechecks and builds.
- Ports: interface http://localhost:5194 (Vite, `server.host` false, proxies `/api` to the engine), engine http://127.0.0.1:9494.
-- Configuration is environment variables only; no `.env` is read. For a person: `FORMMORPHEUS_DATA_DIR` (the data folder), `FORMMORPHEUS_LIBRARY_DIR` (the library), `FORMMORPHEUS_FFMPEG` (the ffmpeg to use), `FORMMORPHEUS_PORT` (the engine's port; 0 or unset picks one), `FORMMORPHEUS_PORTABLE` (1: data beside the app), `FORMMORPHEUS_SAFE_GRAPHICS` (Linux desktop: 1 or 2), `FORMMORPHEUS_CLAUDE_BIN`, `FORMMORPHEUS_CODEX_BIN`, `FORMMORPHEUS_CURSOR_BIN` and `FORMMORPHEUS_ANTIGRAVITY_BIN` (the path of that agent program for the terminal panel, tried before the search of PATH and the usual install folders), `FORMMORPHEUS_AGENT_DIR` (the folder the Claude Code, Codex and Cursor tabs work in; `Agent` in the data folder when unset), `FORMMORPHEUS_MCP_URL` and `FORMMORPHEUS_MCP_AUTOSTART` (for `./formmorpheus mcp`: the engine's `/mcp` address to forward to, in which case no engine is started; 0 stops it starting this source copy's engine when none answers). For development and builds: `FORMMORPHEUS_DEV_URL` (a debug desktop build loads this page), `FORMMORPHEUS_BACKEND_PORT` (the engine port Vite proxies to), `FORMMORPHEUS_DIST` (the built interface the engine serves), `FORMMORPHEUS_NO_SHELL` (1: a frozen engine serves without its app), `FORMMORPHEUS_TARGET` and `FORMMORPHEUS_PYI_ARCH` (the freeze's target), `FORMMORPHEUS_ENGINE_WINDOWED` (0: a Windows engine with a console). Set by the app for its own engine, never by hand: `FORMMORPHEUS_DESKTOP`, `FORMMORPHEUS_PORT_PREFER`, `FORMMORPHEUS_SHELL_PID`, `FORMMORPHEUS_WINDOW_KEY_STDOUT`. Set by the launcher, never by hand: `FORMMORPHEUS_CALLER_DIR` (the folder `./formmorpheus` was run from; `./formmorpheus agents install` sets up that folder too). Set by the engine in the terminal panel's tabs, never by hand: `FORMMORPHEUS_TERMINAL` (1), `FORMMORPHEUS_URL` (the engine's address), `FORMMORPHEUS_MCP_URL` (its `/mcp` address) and, in the Codex, Cursor and Antigravity tabs only, `FORMMORPHEUS_INAPP_TOKEN` (the tab's own token). The engine listens on 127.0.0.1 only; there is no variable to change that.
+- Configuration is environment variables only; no `.env` is read. For a person: `FORMMORPHEUS_DATA_DIR` (the data folder), `FORMMORPHEUS_LIBRARY_DIR` (the library), `FORMMORPHEUS_FFMPEG` (the ffmpeg to use), `FORMMORPHEUS_PORT` (the engine's port; 0 or unset picks one), `FORMMORPHEUS_PORTABLE` (1: data beside the app), `FORMMORPHEUS_SAFE_GRAPHICS` (Linux desktop: 1 or 2), `FORMMORPHEUS_CLAUDE_BIN`, `FORMMORPHEUS_CODEX_BIN`, `FORMMORPHEUS_CURSOR_BIN` and `FORMMORPHEUS_ANTIGRAVITY_BIN` (the path of that agent program for the terminal panel, tried before the search of PATH and the usual install folders), `FORMMORPHEUS_AGENT_DIR` (the folder the Claude Code, Codex and Cursor tabs work in; `Agent` in the data folder when unset), `FORMMORPHEUS_MCP_URL` and `FORMMORPHEUS_MCP_AUTOSTART` (for `./formmorpheus mcp`: the engine's `/mcp` address to forward to, in which case no engine is started; 0 stops it starting this source copy's engine when none answers), `FORMMORPHEUS_COMFY_URL` (the address of the Comfy server that Generate and the `comfy_*` agent tools use; it wins over the address saved in Preferences; `http://127.0.0.1:8188` when neither is set). For development and builds: `FORMMORPHEUS_DEV_URL` (a debug desktop build loads this page), `FORMMORPHEUS_BACKEND_PORT` (the engine port Vite proxies to), `FORMMORPHEUS_DIST` (the built interface the engine serves), `FORMMORPHEUS_NO_SHELL` (1: a frozen engine serves without its app), `FORMMORPHEUS_TARGET` and `FORMMORPHEUS_PYI_ARCH` (the freeze's target), `FORMMORPHEUS_ENGINE_WINDOWED` (0: a Windows engine with a console). Set by the app for its own engine, never by hand: `FORMMORPHEUS_DESKTOP`, `FORMMORPHEUS_PORT_PREFER`, `FORMMORPHEUS_SHELL_PID`, `FORMMORPHEUS_WINDOW_KEY_STDOUT`. Set by the launcher, never by hand: `FORMMORPHEUS_CALLER_DIR` (the folder `./formmorpheus` was run from; `./formmorpheus agents install` sets up that folder too). Set by the engine in the terminal panel's tabs, never by hand: `FORMMORPHEUS_TERMINAL` (1), `FORMMORPHEUS_URL` (the engine's address), `FORMMORPHEUS_MCP_URL` (its `/mcp` address) and, in the Codex, Cursor and Antigravity tabs only, `FORMMORPHEUS_INAPP_TOKEN` (the tab's own token). The engine listens on 127.0.0.1 only; there is no variable to change that.
## Where things live
diff --git a/README.md b/README.md
index 2e0227f..3e4e6a2 100644
--- a/README.md
+++ b/README.md
@@ -11,7 +11,7 @@
-
+
@@ -122,6 +122,7 @@
- **Agents:** an MCP server at `/mcp` with a small core tool list, and a terminal panel for Claude Code, Codex, Cursor and Antigravity. A change waits for your yes in the window unless you allow agents; see [`.docs/wiki/Agents.md`](.docs/wiki/Agents.md).
- **AI Voice:** type what to say and the spoken sound lands on the Timeline like any sound, ready for fades, pan, lip-sync and export. A built-in offline voice (Kokoro, 54 voices, set up once from the card), a voice app on this computer for a cloned voice, or an online voice with your own key. On iPad: the online voice, or a speech server on a computer on the same network; the built-in voice needs a computer. Each spoken sound keeps its words and sentence timing, and adds its subtitles by itself. See `docs/MANUAL.md`.
- **Subtitles:** tick one box and the lines are drawn on the Stage and in every export, in one look for all of them: font, size, position, color and a dark band. AI voices add theirs when they speak; for a recording or a sound file, listening runs on this computer with its own model, a one-time download of about 80 MB, and sends nothing anywhere (on iPad it uses the iPad's own speech recognition instead, with no download). Edit the lines in the card, and import or export `.srt` and `.vtt`. See `docs/MANUAL.md`.
+- **Generate with Comfy:** on the desktop, send the selected blocks to your own Comfy server with the Comfy-FormBridge-Suite pack: a fluid shot from flipbook keyframes, an animated drawing, or erase, add, relight, matte or upscale on a video block from a drawing over its first frame. Results come back as new tracks in one undo step, and the card says which models the server still lacks. See `docs/MANUAL.md`.
- **In your language:** the interface ships in 30 languages, right to left included, with a manual on F1.
- **iPad:** the iPad app in `ios/` wraps the same interface in a Swift shell with Apple Pencil, Files and AVFoundation export. It is built and runs on an iPad Pro 13-inch (M5) with Apple Pencil Pro on iPadOS 26.3, where drawing, squeeze, barrel roll and hover were checked. Version 0.38.0 adds AI Voice, listening for subtitles and My scenes to the iPad app; these are new there and wait for their check on the device (the list is in the build guide). The iPad app has no built-in voice, no Save to a chosen folder in Export, no outside agents or terminal panel and no Pen Link. It is a beta that you build yourself on a Mac with Xcode: see [`docs/ios/BUILD.md`](docs/ios/BUILD.md). An App Store version is planned only if the iPad app gets real adoption.
diff --git a/agents/manifest.json b/agents/manifest.json
index 5be1dd6..231ab5f 100644
--- a/agents/manifest.json
+++ b/agents/manifest.json
@@ -17,6 +17,10 @@
"add_voice",
"list_subtitles",
"set_subtitles",
+ "comfy_status",
+ "comfy_workflows",
+ "comfy_job",
+ "comfy_generate",
"list_commands",
"run_command"
],
@@ -28,6 +32,9 @@
"list_characters",
"list_voices",
"list_subtitles",
+ "comfy_status",
+ "comfy_workflows",
+ "comfy_job",
"list_commands"
],
"approval_gated": [
@@ -37,6 +44,7 @@
"add_character",
"add_voice",
"set_subtitles",
+ "comfy_generate",
"run_command"
],
"asks_first": [
@@ -44,7 +52,8 @@
"import_file",
"add_character",
"add_voice",
- "set_subtitles"
+ "set_subtitles",
+ "comfy_generate"
],
"commands": [
{
diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md
index c0d63ca..9b35880 100644
--- a/backend/HASHOUT_LOG.md
+++ b/backend/HASHOUT_LOG.md
@@ -43,6 +43,22 @@ Last updated: 2026-11-29 · the fixes of 0.38.1
- `_ring()` is the one place keyring is imported, so the tests swap in an in-memory keyring (tests/conftest.py, autouse) and never reach the system one.
- A keyring that answers but refuses the key or does not keep it counts as none: `_load(True)` then marks the seal unavailable. `set_choice("allowed")` first makes the key (`seal.ready()`) and raises `NeedsKeyring` when it cannot, so an unsealed yes is never written, and an Always answer in that case counts as Allow once.
+## unreleased · the engine reaches a Comfy server, and agents use it
+
+- refers-to: services/comfy_bridge.py; routers/comfy.py; routers/mcp.py :: COMFY_WAIT, COMFY_MODES, _comfy, t_comfy_status, t_comfy_workflows, t_comfy_job, t_comfy_generate; main.py; setup/api_contract_check
+- kind: decision
+- logged: 2026-11-29
+
+- The client uses stdlib `urllib` inside `asyncio.to_thread` and the pinned `websockets` client. Status calls time out after 3 seconds, transfers after 600. Redirects are followed only on the same host, and a loopback address never goes through a proxy.
+- `POST /api/comfy/run` is parsed by the engine's own streaming multipart reader because no multipart library is allowed: 1 MB per field, 8 GB in all, and it refuses a missing boundary, a truncated body, an unsafe slot name and more than 20000 parts.
+- One client id per engine start and one websocket follower keep the latest progress, preview and state for up to 64 jobs. It reconnects after 2 seconds and stops after 5 idle minutes; polling every 1.5 seconds is the fallback.
+- The address is `comfy_url` in the settings and `FORMMORPHEUS_COMFY_URL` wins. The optional sign-in key is in the keyring (account `comfy-key`) and goes out as a Bearer header to that one server; `PUT /key` answers 503 when there is no keyring, and no route or tool returns the key, only whether one is saved.
+- Results are kept in `Jobs/comfy-/` and go with the existing orphan sweep after 30 minutes idle.
+- "comfyui" appears only as a wire key and error code of the pack's contract. Our own code for a too-old server is `too_old`.
+- The `/api/comfy/*` routes are desktop-only in `setup/api_contract_check`, and `docs/api-contract.json` was regenerated.
+- The MCP reads call `comfy_bridge` in the engine and need no window. `comfy_generate` checks the handshake before asking, so a person is not asked when the pack is missing. The wait is 30 minutes for the work (a CPU Comfy is slow) and the consent wait stays 2 minutes. `services/bridge.py` is unchanged: its generic queue carries the new kind.
+- Review fixes: slot names cannot be `.` or `..`; keyframes must sit on multiples of 8; non-numeric start, frames or rate answer 400; the keyring key and the can-store probe are cached in memory and dropped on set or clear; a new host clears the saved key (`keyCleared` in the answer); uploads to Comfy stream from the slot files with no second copy; a run upload touches its folder every minute so the 30 minute sweep leaves it alone.
+
## v0.38.1 · a save never replaces a different movie
- refers-to: routers/library.py :: _all_movies, _lands_on_other_movie, write_project
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 53b39ad..e72781a 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -1 +1 @@
-__version__ = "0.38.1"
+__version__ = "0.39.0"
diff --git a/backend/app/main.py b/backend/app/main.py
index ced7776..624a1c5 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -14,6 +14,8 @@
from app.routers import agents, mcp, terminal
from app.routers import video_tools
from app.routers import voice
+from app.routers import comfy
+from app.services import comfy_bridge
from app.routers import scenes
from app.services import claude_code
from app.services import terminal as terminals
@@ -50,6 +52,8 @@
app.include_router(video_tools.router, prefix="/api/video-tools")
app.include_router(voice.router, prefix="/api/voice")
app.on_event("startup")(jobs.sweep)
+app.include_router(comfy.router, prefix="/api/comfy")
+app.on_event("shutdown")(comfy_bridge.stop_follow)
app.include_router(files.router, prefix="/api/files")
app.include_router(trash.router, prefix="/api/trash")
app.include_router(recovery.router, prefix="/api/recovery")
diff --git a/backend/app/routers/comfy.py b/backend/app/routers/comfy.py
new file mode 100644
index 0000000..ae3731d
--- /dev/null
+++ b/backend/app/routers/comfy.py
@@ -0,0 +1,232 @@
+"""Generation through the person's own Comfy server at /api/comfy; desktop only."""
+import asyncio
+import json
+import os
+import re
+import time
+import shutil
+from pathlib import Path
+
+from fastapi import APIRouter, HTTPException, Request
+from fastapi.responses import FileResponse
+from pydantic import BaseModel, Field
+
+from app.services import comfy_bridge as cb
+
+router = APIRouter(tags=["comfy"])
+
+MAX_FIELD = 1024 * 1024
+MAX_UPLOAD = 8 * 1024 * 1024 * 1024
+MAX_PARTS = 20000
+_SLOT = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$")
+_DISPO = re.compile(r'(\w+)="([^"]*)"')
+
+
+class ServerBody(BaseModel):
+ url: str = Field(default="", max_length=300)
+
+
+class KeyBody(BaseModel):
+ key: str = Field(min_length=1, max_length=2000)
+
+
+def _fail(exc: cb.ComfyError) -> HTTPException:
+ detail: dict = {"message": str(exc)}
+ if exc.code:
+ detail["code"] = exc.code
+ if exc.detail is not None:
+ detail["detail"] = exc.detail
+ return HTTPException(exc.status, detail)
+
+
+async def _run(fn, *args):
+ try:
+ return await asyncio.to_thread(fn, *args)
+ except cb.ComfyError as exc:
+ raise _fail(exc)
+
+
+def _status() -> dict:
+ url = cb.current_url()
+ return {"url": url, "source": cb.url_source(), "default": cb.DEFAULT_URL, "hasKey": cb._key() is not None,
+ "canStore": cb.can_store(), "client": cb.CLIENT, "handshake": cb.handshake(url)}
+
+
+@router.get("/status")
+async def status() -> dict:
+ return await _run(_status)
+
+
+@router.put("/server")
+async def server(body: ServerBody) -> dict:
+ cleared = await _run(cb.save_url, body.url)
+ return {**await _run(_status), "keyCleared": cleared}
+
+
+@router.put("/key")
+async def put_key(body: KeyBody) -> dict:
+ await _run(cb.set_key, body.key)
+ return {"hasKey": True}
+
+
+@router.delete("/key")
+async def delete_key() -> dict:
+ await _run(cb.clear_key)
+ return {"hasKey": False}
+
+
+@router.get("/workflows")
+async def workflows() -> dict:
+ return await _run(cb.workflows)
+
+
+@router.get("/workflows/{wid}/readiness")
+async def readiness(wid: str) -> dict:
+ return await _run(cb.readiness, wid)
+
+
+async def _read_multipart(request: Request, folder: Path) -> tuple[dict[str, str], dict[str, list[Path]]]:
+ ctype = request.headers.get("content-type", "")
+ m = re.search(r'boundary="?([^";]+)"?', ctype)
+ if not ctype.lower().startswith("multipart/form-data") or not m:
+ raise HTTPException(400, {"message": "Send the run as a multipart form."})
+ sep = b"\r\n--" + m.group(1).encode("latin-1")
+ fields: dict[str, str] = {}
+ media: dict[str, list[Path]] = {}
+ buf = b"\r\n"
+ total = 0
+ state = "preamble"
+ name = ""
+ sink = None
+ value = bytearray()
+ parts = 0
+ touched = time.monotonic()
+
+ def finish() -> None:
+ nonlocal sink, value
+ if sink is not None:
+ sink.close()
+ sink = None
+ elif state == "body":
+ fields[name] = value.decode("utf-8", "replace")
+ value = bytearray()
+
+ def start(head: bytes) -> None:
+ nonlocal name, sink, parts
+ parts += 1
+ if parts > MAX_PARTS:
+ raise HTTPException(413, {"message": "Too many files in one run."})
+ dispo = ""
+ for line in head.decode("utf-8", "replace").split("\r\n"):
+ if line.lower().startswith("content-disposition:"):
+ dispo = line
+ attrs = dict(_DISPO.findall(dispo))
+ name = attrs.get("name", "")
+ if "filename" in attrs:
+ if not _SLOT.match(name):
+ raise HTTPException(400, {"message": "A file is named for a slot that cannot exist."})
+ files = media.setdefault(name, [])
+ slot_dir = folder / name
+ slot_dir.mkdir(exist_ok=True)
+ path = slot_dir / f"{len(files):05d}-{cb.safe_name(attrs['filename'], 'file')}"
+ files.append(path)
+ sink = open(path, "wb")
+
+ try:
+ async for chunk in request.stream():
+ total += len(chunk)
+ if total > MAX_UPLOAD:
+ raise HTTPException(413, {"message": "The run is larger than 8 GB."})
+ buf += chunk
+ if time.monotonic() - touched > 60:
+ touched = time.monotonic()
+ os.utime(folder)
+ while True:
+ if state in ("preamble", "body"):
+ at = buf.find(sep)
+ if at < 0:
+ keep = len(sep) + 4
+ if state == "body" and len(buf) > keep:
+ data, buf = buf[:-keep], buf[-keep:]
+ if sink is not None:
+ sink.write(data)
+ else:
+ value.extend(data)
+ if len(value) > MAX_FIELD:
+ raise HTTPException(413, {"message": "A form field is too large."})
+ break
+ if state == "body":
+ if sink is not None:
+ sink.write(buf[:at])
+ else:
+ value.extend(buf[:at])
+ finish()
+ buf = buf[at + len(sep):]
+ state = "after"
+ if state == "after":
+ if len(buf) < 2:
+ break
+ if buf[:2] == b"--":
+ state = "end"
+ break
+ buf = buf[2:]
+ state = "head"
+ if state == "head":
+ at = buf.find(b"\r\n\r\n")
+ if at < 0:
+ if len(buf) > 16384:
+ raise HTTPException(400, {"message": "The form could not be read."})
+ break
+ start(buf[:at])
+ buf = buf[at + 4:]
+ state = "body"
+ if state == "end":
+ break
+ if state == "end":
+ break
+ finally:
+ if sink is not None:
+ sink.close()
+ if state != "end":
+ raise HTTPException(400, {"message": "The form ended early."})
+ return fields, media
+
+
+@router.post("/run", status_code=201)
+async def run(request: Request) -> dict:
+ folder = cb.new_upload_folder()
+ try:
+ fields, media = await _read_multipart(request, folder)
+ wid = fields.get("workflow", "").strip()
+ try:
+ slots = json.loads(fields.get("slots") or "{}")
+ sources = json.loads(fields.get("sources") or "{}")
+ except ValueError:
+ raise HTTPException(400, {"message": "The slot values are not valid JSON."})
+ if not isinstance(slots, dict) or not isinstance(sources, dict):
+ raise HTTPException(400, {"message": "The slot values must be an object."})
+ reuse = fields.get("reuse", "true").strip().lower() != "false"
+ job = await _run(cb.start_job, wid, slots, media, sources, folder, reuse)
+ finally:
+ shutil.rmtree(folder, ignore_errors=True)
+ cb.follow(cb.current_url())
+ return {"job": job}
+
+
+@router.get("/jobs/{job_id}")
+async def job(job_id: str) -> dict:
+ out = await _run(cb.job_status, job_id)
+ if out["job"].get("state") in ("queued", "running"):
+ cb.follow(cb.current_url())
+ return out
+
+
+@router.get("/jobs/{job_id}/files/{n}")
+async def job_file(job_id: str, n: int) -> FileResponse:
+ path, ctype = await _run(cb.fetch_file, job_id, n)
+ return FileResponse(path, media_type=ctype, filename=path.name.split("-", 1)[-1])
+
+
+@router.post("/jobs/{job_id}/cancel")
+async def cancel(job_id: str) -> dict:
+ return await _run(cb.cancel_job, job_id)
diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py
index fe7cae5..9d4cb4d 100644
--- a/backend/app/routers/mcp.py
+++ b/backend/app/routers/mcp.py
@@ -13,7 +13,7 @@
from app.core import config, window_key
from app.routers import characters, exports, fonts, jobs, library, trash, voice
-from app.services import agent_access, bridge, claude_code, movies, voice_remote, voice_runtime
+from app.services import agent_access, bridge, claude_code, comfy_bridge, movies, voice_remote, voice_runtime
from app.services import ffmpeg as ff
router = APIRouter()
@@ -29,6 +29,8 @@
IMPORT_WAIT = 120.0
VOICE_WAIT = 600.0
SUBTITLE_WAIT = 120.0
+COMFY_WAIT = 1800.0
+COMFY_MODES = ["fluid", "animate", "erase", "add", "relight", "matte", "upscale"]
MAX_SUBTITLE_LINES = 2000
MAX_SUBTITLE_TEXT = 500
MAX_SRT = 400_000
@@ -42,7 +44,8 @@
INSTRUCTIONS = ("FormMorpheus is an animation studio on this computer; its movies are .fmo files in the person's library folder. "
"Start with get_context. list_movies, get_movie and get_movie_picture read; manage_movie creates, renames, duplicates, "
"deletes (to Recently Deleted) and restores movies; list_characters reads the saved characters; list_voices reads the AI voices and "
- "whether each is ready; list_subtitles reads a movie's subtitles; export_movie, import_file, add_character, add_voice and set_subtitles are carried out by the open "
+ "whether each is ready; list_subtitles reads a movie's subtitles; comfy_status, comfy_workflows and comfy_job read the person's Comfy server, "
+ "and comfy_generate makes video with it; export_movie, import_file, add_character, add_voice, set_subtitles and comfy_generate are carried out by the open "
"FormMorpheus window after the person agrees there. list_commands lists the other commands and run_command runs one. Changes need the "
"person's yes: outside agents are off until they allow them in the window.")
NO_WINDOW = "Open FormMorpheus first: the FormMorpheus window does this ({what}), and none is open. Ask the person to open FormMorpheus, then retry."
@@ -152,6 +155,22 @@ def _command(name: str, kind: str, description: str, props: dict, required: list
"size": {"type": "number", "minimum": 2, "maximum": 15, "description": "Percent of the movie's height"},
"position": {"type": "string", "enum": ["top", "middle", "bottom"]}, "color": {"type": "string", "description": "#rrggbb"},
"band": {"type": "boolean", "description": "A dark band behind the words"}}}}),
+ _tool("comfy_status", "reads", "Reads the person's Comfy server without the window: its address, whether FormMorpheus can reach it, whether the "
+ "generation pack is installed and recent enough, its memory profile and device, and whether a sign-in key is stored. Nothing is changed.", {}),
+ _tool("comfy_workflows", "reads", "Reads the generation workflows the Comfy server offers: each one's id, title, what it makes, its slots (name, type, "
+ "default, limits) and whether everything it needs is installed there, with what is missing when not. Needs the pack installed.", {}),
+ _tool("comfy_job", "reads", "Reads one Comfy job by its id: its state (queued, running, done, failed, cancelled), progress, the result files when it is done, "
+ "and the reason when it failed. Nothing is changed.",
+ {"job": {"type": "string", "description": "A job id such as job_ followed by 24 hex digits"}}, ["job"]),
+ _tool("comfy_generate", "asks", "Asks first: the person approves in the FormMorpheus window, which then sends the blocks selected on its Timeline (and their "
+ "drawings or keyframes) to the Comfy server, waits for the job, and places the results on new tracks at the source's start, in the movie open there "
+ "(or in movie, which it opens), then saves the movie. mode: fluid (a shot from flipbook keyframes), animate (a drawing), erase, add or relight "
+ "(on a video block, from a drawing at its first frame), matte or upscale. prompt and seed are optional; slots sets other plain values of the workflow, "
+ "as comfy_workflows lists them. The Comfy server must be ready for that mode. Waits up to 2 minutes for the answer and 30 minutes for the work.",
+ {"mode": {"type": "string", "enum": COMFY_MODES}, "prompt": {"type": "string", "maxLength": 4000, "description": "What to make"},
+ "seed": {"type": "integer", "minimum": 0, "maximum": 2147483647}, "slots": {"type": "object", "description": "Other plain slot values by slot name"},
+ "movie": {"type": "string", "description": "A movie's name, as list_movies gives it (default the movie open in the window)"}},
+ ["mode"]),
_tool("list_commands", "reads", "Reads the commands that are not tools: id, class (reads, changes the library) and what each does; id returns one with its parameters.",
{"id": _S}),
_tool("run_command", "changes", "Changes the library or reads, as the command's class says: runs one command from list_commands with its params. "
@@ -729,6 +748,120 @@ async def t_set_subtitles(a: Agent, args: dict) -> dict:
{"movie": into or None, "lines": count, "show": shown, "saved": bool(out.get("saved"))})
+async def _comfy(fn, *a):
+ try:
+ return await asyncio.to_thread(fn, *a)
+ except comfy_bridge.ComfyError as exc:
+ raise ToolError(str(exc))
+
+
+def _device_name(raw) -> str:
+ if isinstance(raw, dict):
+ return str(raw.get("name") or "").strip()
+ return str(raw or "").strip()
+
+
+def _missing(ready: dict) -> list[str]:
+ out = []
+ for p in ready.get("packs") or []:
+ if isinstance(p, dict) and not p.get("present"):
+ out.append(f"node pack {p.get('name')}")
+ for n in ready.get("nodes") or []:
+ if isinstance(n, dict) and not n.get("present"):
+ out.append(f"node {n.get('class')}")
+ for m in ready.get("models") or []:
+ if isinstance(m, dict) and not m.get("present"):
+ out.append(f"model {m.get('file')}" + (f" (put it in {m['place']})" if m.get("place") else f" (folder {m.get('folder')})" if m.get("folder") else ""))
+ return out[:12]
+
+
+async def t_comfy_status(a: Agent, args: dict) -> dict:
+ url = comfy_bridge.current_url()
+ hs = await _comfy(comfy_bridge.handshake, url)
+ has_key = comfy_bridge._key() is not None
+ if not hs.get("installed"):
+ words = f"Comfy at {url}: " + str(hs.get("message") or "not available.")
+ elif not hs.get("supported"):
+ words = f"Comfy at {url}: " + str(hs.get("message") or "too old for this pack.")
+ else:
+ words = f"Comfy at {url} is ready: the generation pack is installed" + (f", memory profile {hs.get('memory_profile')}" if hs.get("memory_profile") else "") + (f", device {_device_name(hs.get('device'))}" if _device_name(hs.get("device")) else "") + "."
+ return _ok(words, {"url": url, "reachable": bool(hs.get("reachable")), "installed": bool(hs.get("installed")), "supported": bool(hs.get("supported")),
+ "memoryProfile": hs.get("memory_profile"), "device": _device_name(hs.get("device")) or None, "hasKey": has_key, "message": hs.get("message")})
+
+
+async def t_comfy_workflows(a: Agent, args: dict) -> dict:
+ found = await _comfy(comfy_bridge.workflows)
+ rows = []
+ lines = []
+ for w in found.get("workflows") or []:
+ slots = [{k: s.get(k) for k in ("name", "type", "required", "default", "min", "max", "choices") if s.get(k) is not None} for s in w.get("slots") or [] if isinstance(s, dict)]
+ lacks = [] if w.get("ready") else _missing(w.get("readiness") if isinstance(w.get("readiness"), dict) else {})
+ rows.append({"id": w.get("id"), "title": w.get("title"), "description": w.get("description"), "ready": bool(w.get("ready")), "missing": lacks, "slots": slots})
+ lines.append(f"{w.get('id')} · {w.get('title') or ''} · {'ready' if w.get('ready') else 'not ready' + (' (missing: ' + '; '.join(lacks) + ')' if lacks else '')} · slots: " + (", ".join(f"{s['name']} ({s['type']})" for s in slots) or "none"))
+ if not rows:
+ return _ok("The Comfy server offers no workflows.", {"workflows": []})
+ return _ok(f"{len(rows)} workflow{'s' if len(rows) != 1 else ''}:\n" + "\n".join(lines), {"workflows": rows, "memoryProfile": found.get("memory_profile")})
+
+
+async def t_comfy_job(a: Agent, args: dict) -> dict:
+ jid = str(args.get("job") or "").strip()
+ if not jid:
+ raise ToolError("Give job, a job id.")
+ out = await _comfy(comfy_bridge.job_status, jid)
+ job = out["job"]
+ files = comfy_bridge.result_files(job) if job.get("state") == "done" else []
+ state = str(job.get("state") or "unknown")
+ words = f"Job {jid} is {state}."
+ prog = job.get("progress")
+ if state == "running" and isinstance(prog, dict) and prog.get("max"):
+ words += f" Step {prog.get('value')} of {prog.get('max')}."
+ if state == "done":
+ words += f" {len(files)} result file{'s' if len(files) != 1 else ''}."
+ if state == "failed" and job.get("error"):
+ words += f" {job['error'] if isinstance(job['error'], str) else (job['error'].get('message') or '')}".rstrip()
+ return _ok(words, {"job": {"id": jid, "state": state, "progress": prog if isinstance(prog, dict) else None},
+ "files": [{"name": f.get("name"), "kind": f.get("kind"), "bytes": f.get("bytes")} for f in files]})
+
+
+async def t_comfy_generate(a: Agent, args: dict) -> dict:
+ mode = str(args.get("mode") or "").strip()
+ if mode not in COMFY_MODES:
+ raise ToolError("mode is one of " + ", ".join(COMFY_MODES) + ".")
+ payload: dict = {"mode": mode}
+ if args.get("prompt") is not None:
+ if not isinstance(args["prompt"], str):
+ raise ToolError("prompt is text.")
+ payload["prompt"] = args["prompt"].strip()[:4000]
+ if args.get("seed") is not None:
+ try:
+ seed = int(args["seed"])
+ except (TypeError, ValueError):
+ seed = -1
+ if not 0 <= seed <= 2147483647:
+ raise ToolError("seed is a whole number from 0 to 2147483647.")
+ payload["seed"] = seed
+ if args.get("slots") is not None:
+ if not isinstance(args["slots"], dict) or len(args["slots"]) > 64 or any(not isinstance(k, str) or len(k) > 64 for k in args["slots"]):
+ raise ToolError("slots is an object of plain values by slot name, as comfy_workflows lists them.")
+ payload["slots"] = args["slots"]
+ movie = str(args.get("movie") or "").strip()
+ if movie:
+ payload["movie"] = _movie(movie).stem
+ hs = await _comfy(comfy_bridge.handshake)
+ if not hs.get("installed") or not hs.get("supported"):
+ raise ToolError("Nothing was generated. " + str(hs.get("message") or "The Comfy server is not ready."))
+ where = f"the movie {payload['movie']}" if movie else "the movie open in the window"
+ out = await _window(a, "comfy_generate", payload, f"send the selected blocks to the Comfy server ({mode}) and add the results to {where}", COMFY_WAIT)
+ try:
+ blocks = int(out.get("blocks") or 0)
+ except (TypeError, ValueError):
+ blocks = 0
+ into = str(out.get("movie") or payload.get("movie") or "")
+ note = str(out.get("text") or "")
+ return _ok(f"Made {blocks} block{'s' if blocks != 1 else ''} with Comfy ({mode})" + (f" in {into}" if into else "") + (", and the movie was saved." if out.get("saved") else "; the movie is not saved yet.") + (f" {note}" if note else ""),
+ {"mode": mode, "blocks": blocks, "movie": into or None, "saved": bool(out.get("saved")), "text": note or None})
+
+
async def t_list_commands(a: Agent, args: dict) -> dict:
cid = str(args.get("id") or "").strip()
if cid:
diff --git a/backend/app/services/comfy_bridge.py b/backend/app/services/comfy_bridge.py
new file mode 100644
index 0000000..45ec5db
--- /dev/null
+++ b/backend/app/services/comfy_bridge.py
@@ -0,0 +1,627 @@
+"""Client for the person's own Comfy server through the FormBridge pack, contract 1."""
+import asyncio
+import json
+import logging
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import uuid
+import zipfile
+from pathlib import Path
+
+from app.core import config
+
+log = logging.getLogger("formmorpheus")
+
+SERVICE = "FormMorpheus"
+KEY_ACCOUNT = "comfy-key"
+URL_ENV = "FORMMORPHEUS_COMFY_URL"
+SETTING = "comfy_url"
+DEFAULT_URL = "http://127.0.0.1:8188"
+PREFIX = "/formbridge/v1"
+CONTRACT = "1"
+CLIENT = f"{config.APP_NAME}/{config.VERSION}"
+CLIENT_ID = "fm-" + uuid.uuid4().hex
+STATUS_TIMEOUT = 3
+LONG_TIMEOUT = 600
+MAX_JSON = 16 * 1024 * 1024
+MAX_FILE = 4 * 1024 * 1024 * 1024
+KEEP_EVENTS = 64
+FOLDER_PREFIX = "comfy-"
+_LOOPBACK = ("127.0.0.1", "localhost", "::1")
+_JOB_ID = re.compile(r"^job_[0-9a-f]{24}$")
+_FILE_ID = re.compile(r"^f_[0-9a-f]{32}$")
+_WORKFLOW_ID = re.compile(r"^[a-z0-9][a-z0-9_.-]{0,79}$")
+_ASSET_ID = re.compile(r"^[A-Za-z0-9_-]{1,80}$")
+_SAFE = re.compile(r"[^A-Za-z0-9_.-]+")
+MOVIE_EXT = (".mp4", ".mov", ".mkv", ".webm", ".m4v")
+STILL_KINDS = ("image", "mask")
+
+
+class ComfyError(Exception):
+ def __init__(self, message: str, status: int = 502, code: str = "", detail=None) -> None:
+ super().__init__(message)
+ self.status = status
+ self.code = code
+ self.detail = detail
+
+
+def _keyring():
+ if sys.platform.startswith("linux"):
+ import ctypes.util
+
+ if hasattr(ctypes.util, "_findLib_ld"):
+ ctypes.util._findLib_ld = lambda name: None
+ import keyring
+
+ return keyring
+
+
+_cache: dict = {}
+
+
+def _key() -> str | None:
+ if "key" not in _cache:
+ try:
+ _cache["key"] = _keyring().get_password(SERVICE, KEY_ACCOUNT) or None
+ except Exception:
+ _cache["key"] = None
+ return _cache["key"]
+
+
+def can_store() -> bool:
+ if "store" not in _cache:
+ try:
+ _keyring().get_password(SERVICE, "comfy-probe")
+ _cache["store"] = True
+ except Exception:
+ _cache["store"] = False
+ return _cache["store"]
+
+
+def set_key(key: str) -> None:
+ clean = (key or "").strip()
+ if not clean:
+ raise ComfyError("There is no key to save.", 422)
+ _cache.pop("key", None)
+ try:
+ _keyring().set_password(SERVICE, KEY_ACCOUNT, clean)
+ except Exception:
+ raise ComfyError("This computer has no safe place to keep a key, so it was not saved.", 503)
+
+
+def clear_key() -> None:
+ _cache.pop("key", None)
+ try:
+ _keyring().delete_password(SERVICE, KEY_ACCOUNT)
+ except Exception:
+ pass
+
+
+def normalize_url(url: str) -> str:
+ sorry = ComfyError("That is not a Comfy address. Use one such as http://127.0.0.1:8188.", 422)
+ text = (url or "").strip().rstrip("/")
+ try:
+ parts = urllib.parse.urlsplit(text)
+ host = (parts.hostname or "").lower()
+ port = parts.port
+ except ValueError:
+ raise sorry
+ if parts.scheme not in ("http", "https") or not host or parts.username or parts.password:
+ raise sorry
+ if parts.query or parts.fragment or parts.path not in ("", "/"):
+ raise sorry
+ shown = f"[{host}]" if ":" in host else host
+ return f"{parts.scheme}://{shown}" + (f":{port}" if port is not None else "")
+
+
+def url_source() -> str:
+ if os.environ.get(URL_ENV, "").strip():
+ return "env"
+ return "settings" if str(config.read_settings().get(SETTING) or "").strip() else "default"
+
+
+def current_url() -> str:
+ raw = os.environ.get(URL_ENV, "").strip() or str(config.read_settings().get(SETTING) or "").strip()
+ if not raw:
+ return DEFAULT_URL
+ try:
+ return normalize_url(raw)
+ except ComfyError:
+ return DEFAULT_URL
+
+
+def save_url(url: str) -> bool:
+ clean = normalize_url(url) if (url or "").strip() else DEFAULT_URL
+ before = urllib.parse.urlsplit(current_url()).netloc
+ config.update_settings(lambda s: {**s, SETTING: clean})
+ moved = urllib.parse.urlsplit(clean).netloc != before
+ if moved and _key() is not None:
+ clear_key()
+ return True
+ return False
+
+
+class _SameHost(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ old, new = urllib.parse.urlsplit(req.full_url), urllib.parse.urlsplit(newurl)
+ if (old.scheme, old.netloc) != (new.scheme, new.netloc):
+ return None
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
+
+
+def _opener(base: str) -> urllib.request.OpenerDirector:
+ host = (urllib.parse.urlsplit(base).hostname or "").lower()
+ handlers: list = [_SameHost()]
+ if host in _LOOPBACK:
+ handlers.insert(0, urllib.request.ProxyHandler({}))
+ return urllib.request.build_opener(*handlers)
+
+
+def _headers(extra: dict | None = None) -> dict:
+ out = {"X-FormBridge-Contract": CONTRACT, "X-FormBridge-Client": CLIENT, "Accept": "application/json"}
+ key = _key()
+ if key:
+ out["Authorization"] = "Bearer " + key
+ out.update(extra or {})
+ return out
+
+
+def _error_of(exc: urllib.error.HTTPError) -> ComfyError:
+ try:
+ body = json.loads(exc.read(MAX_JSON).decode("utf-8", "replace"))
+ except Exception:
+ body = None
+ err = body.get("error") if isinstance(body, dict) else None
+ if isinstance(err, dict) and err.get("code"):
+ code = str(err.get("code"))
+ message = str(err.get("message") or "Comfy refused the request.")
+ if code == "comfyui_too_old":
+ message = "This Comfy is too old for the FormBridge pack. Update Comfy and try again."
+ status = exc.code if exc.code in (400, 403, 404, 409, 413, 422, 503) else 502
+ return ComfyError(message, status, code, err.get("detail"))
+ if exc.code in (401, 403):
+ return ComfyError("Comfy asked for a sign-in that was not accepted. Check the key in Settings, Comfy.", 502, "sign_in")
+ if exc.code in (404, 405):
+ return ComfyError(missing_pack_message(), 404, "not_installed")
+ return ComfyError(f"Comfy answered with error {exc.code}.", 502)
+
+
+def missing_pack_message() -> str:
+ return ("Comfy answered, but the FormBridge pack is not installed there. Install Comfy-FormBridge-Suite "
+ "into Comfy's custom_nodes folder and restart Comfy.")
+
+
+def _unreachable(base: str) -> ComfyError:
+ return ComfyError(f"Comfy did not answer at {base}. Check that it is running and that the address is right.", 502, "unreachable")
+
+
+def _call(method: str, path: str, body=None, timeout: float = STATUS_TIMEOUT, headers: dict | None = None,
+ base: str | None = None) -> dict:
+ base = base or current_url()
+ data = None
+ extra = dict(headers or {})
+ if isinstance(body, (dict, list)):
+ data = json.dumps(body).encode("utf-8")
+ extra["Content-Type"] = "application/json"
+ elif body is not None:
+ data = body
+ req = urllib.request.Request(base + PREFIX + path, data=data, headers=_headers(extra), method=method)
+ try:
+ with _opener(base).open(req, timeout=timeout) as resp:
+ raw = resp.read(MAX_JSON + 1)
+ except urllib.error.HTTPError as exc:
+ raise _error_of(exc)
+ except (urllib.error.URLError, OSError):
+ raise _unreachable(base)
+ if len(raw) > MAX_JSON:
+ raise ComfyError("Comfy sent back an answer too large to read.", 502)
+ try:
+ out = json.loads(raw.decode("utf-8", "replace"))
+ except ValueError:
+ raise ComfyError("Comfy answered with something that is not FormBridge's reply. Check the address.", 502)
+ if not isinstance(out, dict):
+ raise ComfyError("Comfy answered with something unreadable.", 502)
+ return out
+
+
+def handshake(base: str | None = None) -> dict:
+ base = base or current_url()
+ try:
+ hs = _call("GET", "/handshake", base=base)
+ except ComfyError as exc:
+ if exc.code == "not_installed" or exc.status == 404:
+ return {"installed": False, "reachable": True, "message": missing_pack_message()}
+ return {"installed": False, "reachable": False, "message": str(exc)}
+ comfy = hs.get("comfyui") if isinstance(hs.get("comfyui"), dict) else {}
+ served = hs.get("contract") if isinstance(hs.get("contract"), list) else []
+ out = {"installed": True, "reachable": True, "pack": hs.get("pack"), "contract": served, "comfy": comfy,
+ "supported": bool(comfy.get("supported")), "memory_profile": hs.get("memory_profile"),
+ "device": hs.get("device"), "limits": hs.get("limits"), "nodes": hs.get("nodes")}
+ if 1 not in served:
+ out["supported"] = False
+ out["message"] = "This FormBridge pack does not speak contract 1. Update Comfy-FormBridge-Suite."
+ elif not out["supported"]:
+ out["message"] = (f"This Comfy is version {comfy.get('version') or 'unknown'}; the FormBridge pack needs "
+ f"{comfy.get('minimum') or 'a newer one'} or newer. Update Comfy.")
+ return out
+
+
+def _need_ready(base: str) -> dict:
+ hs = handshake(base)
+ if not hs["installed"]:
+ raise ComfyError(hs["message"], 503 if not hs.get("reachable") else 404, "not_installed")
+ if not hs["supported"]:
+ raise ComfyError(hs["message"], 409, "too_old")
+ return hs
+
+
+def _check_workflow(wid: str) -> str:
+ if not _WORKFLOW_ID.match(wid or ""):
+ raise ComfyError("That workflow name is not valid.", 400, "bad_request")
+ return wid
+
+
+def readiness(wid: str, base: str | None = None) -> dict:
+ return _call("GET", f"/workflows/{_check_workflow(wid)}/readiness", base=base)
+
+
+def workflow(wid: str, base: str | None = None) -> dict:
+ return _call("GET", f"/workflows/{_check_workflow(wid)}", base=base)
+
+
+def workflows() -> dict:
+ base = current_url()
+ hs = _need_ready(base)
+ listed = _call("GET", "/workflows", base=base).get("workflows")
+ items = [w for w in listed if isinstance(w, dict)] if isinstance(listed, list) else []
+ for item in items:
+ try:
+ ready = readiness(str(item.get("id") or ""), base)
+ item["ready"] = bool(ready.get("ready"))
+ item["readiness"] = ready
+ except ComfyError:
+ item["ready"] = False
+ return {"workflows": items, "memory_profile": hs.get("memory_profile")}
+
+
+_events: dict[str, dict] = {}
+_follow: dict = {"task": None, "base": None, "last": 0.0}
+
+
+def _remember(job: str, kind: str, data: dict) -> None:
+ entry = _events.setdefault(job, {})
+ entry[kind] = data
+ entry["at"] = time.time()
+ if len(_events) > KEEP_EVENTS:
+ for old in sorted(_events, key=lambda k: _events[k].get("at", 0))[: len(_events) - KEEP_EVENTS]:
+ _events.pop(old, None)
+
+
+def _ws_url(base: str) -> str:
+ parts = urllib.parse.urlsplit(base)
+ scheme = "wss" if parts.scheme == "https" else "ws"
+ return f"{scheme}://{parts.netloc}/ws?clientId={CLIENT_ID}"
+
+
+async def _follower(base: str) -> None:
+ from websockets.asyncio.client import connect
+
+ key = _key()
+ headers = {"X-FormBridge-Client": CLIENT}
+ if key:
+ headers["Authorization"] = "Bearer " + key
+ loopback = (urllib.parse.urlsplit(base).hostname or "").lower() in _LOOPBACK
+ while time.time() - _follow["last"] < 300:
+ try:
+ async with connect(_ws_url(base), additional_headers=headers, max_size=8 * 1024 * 1024,
+ open_timeout=STATUS_TIMEOUT, proxy=None if loopback else True) as ws:
+ async for message in ws:
+ if not isinstance(message, str):
+ continue
+ try:
+ msg = json.loads(message)
+ except ValueError:
+ continue
+ kind = msg.get("type") if isinstance(msg, dict) else None
+ data = msg.get("data") if isinstance(msg, dict) else None
+ if kind in ("formbridge.progress", "formbridge.preview", "formbridge.state") and isinstance(data, dict):
+ job = str(data.get("job") or "")
+ if _JOB_ID.match(job):
+ _remember(job, kind.split(".", 1)[1], data)
+ if time.time() - _follow["last"] > 300:
+ return
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ pass
+ await asyncio.sleep(2)
+
+
+def follow(base: str) -> None:
+ _follow["last"] = time.time()
+ task = _follow["task"]
+ if task is not None and not task.done() and _follow["base"] == base:
+ return
+ if task is not None and not task.done():
+ task.cancel()
+ _follow["base"] = base
+ _follow["task"] = asyncio.get_running_loop().create_task(_follower(base))
+
+
+def stop_follow() -> None:
+ task = _follow["task"]
+ if task is not None and not task.done():
+ task.cancel()
+
+
+def job_folder(name: str) -> Path:
+ path = config.jobs_dir() / (FOLDER_PREFIX + name)
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def new_upload_folder() -> Path:
+ return job_folder("up-" + uuid.uuid4().hex)
+
+
+def safe_name(name: str, fallback: str) -> str:
+ base = _SAFE.sub("-", Path(name or "").name).strip(".-")[:100]
+ return base or fallback
+
+
+def _sniff_ext(path: Path) -> str:
+ with open(path, "rb") as f:
+ head = f.read(16)
+ if head[:8] == b"\x89PNG\r\n\x1a\n":
+ return ".png"
+ if head[:3] == b"\xff\xd8\xff":
+ return ".jpg"
+ if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
+ return ".webp"
+ if head[:4] in (b"II*\x00", b"MM\x00*"):
+ return ".tif"
+ if head[:4] == b"\x76\x2f\x31\x01":
+ return ".exr"
+ if head[4:8] == b"ftyp":
+ return ".mov" if head[8:10] == b"qt" else ".mp4"
+ if head[:4] == b"\x1a\x45\xdf\xa3":
+ return ".webm"
+ return ""
+
+
+def upload_input(kind: str, files: list[Path], base: str, fps: float | None = None) -> dict:
+ boundary = "fmcomfy" + uuid.uuid4().hex
+ pieces: list = [f'--{boundary}\r\nContent-Disposition: form-data; name="kind"\r\n\r\n{kind}\r\n'.encode("utf-8")]
+ if fps:
+ pieces.append(f'--{boundary}\r\nContent-Disposition: form-data; name="fps"\r\n\r\n{float(fps)!r}\r\n'.encode("utf-8"))
+ for path in files:
+ pieces.append(f'--{boundary}\r\nContent-Disposition: form-data; name="files"; filename="{path.name}"\r\n'
+ f"Content-Type: application/octet-stream\r\n\r\n".encode("utf-8"))
+ pieces.append(path)
+ pieces.append(b"\r\n")
+ pieces.append(f"--{boundary}--\r\n".encode("utf-8"))
+ size = sum(p.stat().st_size if isinstance(p, Path) else len(p) for p in pieces)
+
+ def stream():
+ for p in pieces:
+ if isinstance(p, Path):
+ with open(p, "rb") as src:
+ while chunk := src.read(1024 * 1024):
+ yield chunk
+ else:
+ yield p
+
+ answer = _call("POST", "/inputs", body=stream(), timeout=LONG_TIMEOUT, base=base,
+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}", "Content-Length": str(size)})
+ found = answer.get("input")
+ if not isinstance(found, dict) or not found.get("id"):
+ raise ComfyError("Comfy did not take the uploaded picture.", 502)
+ return found
+
+
+def _kind_for(slot_type: str, files: list[Path]) -> str:
+ if slot_type in STILL_KINDS:
+ return "still"
+ if slot_type == "frames":
+ return "sequence"
+ if slot_type == "movie":
+ return "movie"
+ if len(files) == 1 and files[0].suffix.lower() in MOVIE_EXT:
+ return "movie"
+ return "sequence"
+
+
+def _named(files: list[Path]) -> list[Path]:
+ out = []
+ for path in files:
+ if not path.suffix:
+ ext = _sniff_ext(path)
+ if ext:
+ renamed = path.with_name(path.name + ext)
+ path.rename(renamed)
+ path = renamed
+ out.append(path)
+ return out
+
+
+def extract_source(slot: str, slot_type: str, spec: dict, folder: Path) -> list[Path]:
+ from app.routers.library import project_path
+ from app.services import ffmpeg as ff
+
+ movie = str(spec.get("movie") or "")
+ asset = str(spec.get("asset") or "")
+ if not movie or not _ASSET_ID.match(asset):
+ raise ComfyError(f"The source for {slot} names no movie and asset.", 400, "bad_request")
+ try:
+ path = project_path(movie)
+ except Exception:
+ raise ComfyError("That movie name cannot be used.", 400, "bad_request")
+ if not path.is_file():
+ raise ComfyError("That movie is not in the library.", 404, "not_found")
+ dest = folder / f"src-{safe_name(slot, 'slot')}"
+ dest.mkdir(exist_ok=True)
+ raw = dest / "source"
+ try:
+ with zipfile.ZipFile(path) as zin, zin.open(f"assets/{asset}") as src, open(raw, "wb") as out:
+ shutil.copyfileobj(src, out, 1024 * 1024)
+ except KeyError:
+ raise ComfyError("That picture or video is not in the movie.", 404, "not_found")
+ except (OSError, zipfile.BadZipFile):
+ raise ComfyError("The movie could not be read.", 409)
+ raw = _named([raw])[0]
+ if slot_type == "movie" or (slot_type == "video" and raw.suffix in MOVIE_EXT and not spec.get("frames")):
+ return [raw]
+ info = ff.probe()
+ if info is None:
+ raise ComfyError("Taking frames from a video needs ffmpeg. Add it in Preferences, Video Tools.", 409)
+ try:
+ start = max(0.0, float(spec.get("start") or 0))
+ count = 1 if slot_type in STILL_KINDS else max(1, min(int(spec.get("frames") or 0) or 2000, 10000))
+ fps = float(spec["fps"]) if spec.get("fps") else None
+ except (TypeError, ValueError, OverflowError):
+ raise ComfyError(f"The source for {slot} has a start, frame count or rate that is not a number.", 400, "bad_request")
+ frames = dest / "frames"
+ frames.mkdir(exist_ok=True)
+ args = [info.path, "-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file",
+ "-ss", f"{start:.6f}", "-i", str(raw), "-frames:v", str(count)]
+ if fps and slot_type not in STILL_KINDS:
+ args += ["-vf", f"fps={max(1.0, min(fps, 240.0)):.6f}"]
+ args += ["-y", str(frames / "frame_%05d.png")]
+ try:
+ done = subprocess.run(args, capture_output=True, timeout=LONG_TIMEOUT, check=False)
+ except (OSError, subprocess.SubprocessError):
+ raise ComfyError("ffmpeg could not take the frames.", 500)
+ out = sorted(frames.glob("frame_*.png"))
+ if done.returncode != 0 or not out:
+ raise ComfyError("ffmpeg could not take frames from that video.", 409)
+ return out
+
+
+def start_job(wid: str, slots: dict, media: dict[str, list[Path]], sources: dict, folder: Path, reuse: bool) -> dict:
+ base = current_url()
+ _need_ready(base)
+ entry = workflow(wid, base)
+ types = {str(s.get("name")): str(s.get("type")) for s in entry.get("slots", []) if isinstance(s, dict)}
+ values = dict(slots)
+ for slot, spec in sources.items():
+ if slot not in types or not isinstance(spec, dict):
+ raise ComfyError(f"The workflow has no picture slot named {slot}.", 400, "bad_slot")
+ media[slot] = extract_source(slot, types[slot], spec, folder)
+ for slot, files in media.items():
+ kind = types.get(slot)
+ if kind is None:
+ raise ComfyError(f"The workflow has no picture slot named {slot}.", 400, "bad_slot")
+ files = _named(files)
+ if kind == "keyframes":
+ at = values.get(slot)
+ frames = at if isinstance(at, list) and len(at) == len(files) else list(range(0, 8 * len(files), 8))
+ try:
+ numbers = [int(f if not isinstance(f, dict) else f.get("frame", 0)) for f in frames]
+ except (TypeError, ValueError, OverflowError):
+ raise ComfyError(f"The keyframes of {slot} must be frame numbers.", 400, "bad_slot")
+ if any(n < 0 or n % 8 for n in numbers):
+ raise ComfyError(f"The keyframes of {slot} must sit on frames 0, 8, 16 and so on.", 400, "bad_slot")
+ values[slot] = [{"frame": n, "input": upload_input("still", [p], base)["id"]} for n, p in zip(numbers, files)]
+ continue
+ upload_kind = _kind_for(kind, files)
+ if upload_kind == "still" and len(files) != 1:
+ raise ComfyError(f"The slot {slot} takes one picture.", 400, "bad_slot")
+ values[slot] = upload_input(upload_kind, files, base)["id"]
+ body = {"workflow": wid, "slots": values, "client_id": CLIENT_ID, "reuse": bool(reuse)}
+ answer = _call("POST", "/jobs", body=body, timeout=60, base=base)
+ job = answer.get("job")
+ if not isinstance(job, dict):
+ raise ComfyError("Comfy did not start the job.", 502)
+ return job
+
+
+def _check_job(job_id: str) -> str:
+ if not _JOB_ID.match(job_id or ""):
+ raise ComfyError("That job id is not valid.", 400, "bad_request")
+ return job_id
+
+
+def job_status(job_id: str) -> dict:
+ job = _call("GET", f"/jobs/{_check_job(job_id)}").get("job")
+ if not isinstance(job, dict):
+ raise ComfyError("Comfy answered without the job.", 502)
+ seen = _events.get(job_id, {})
+ out: dict = {"job": job}
+ if job.get("state") == "running" and isinstance(seen.get("progress"), dict):
+ p = seen["progress"]
+ job["progress"] = {"value": p.get("value"), "max": p.get("max"), "node": p.get("node")}
+ preview = seen.get("preview")
+ if job.get("state") in ("queued", "running") and isinstance(preview, dict) and preview.get("image"):
+ mime = str(preview.get("mime") or "image/jpeg")
+ out["preview"] = {"step": preview.get("step"), "steps": preview.get("steps"),
+ "image": f"data:{mime};base64,{preview['image']}"}
+ if job.get("state") in ("done", "failed", "cancelled"):
+ _events.pop(job_id, None)
+ return out
+
+
+def cancel_job(job_id: str) -> dict:
+ job = _call("POST", f"/jobs/{_check_job(job_id)}/cancel", body={}).get("job")
+ _events.pop(job_id, None)
+ return {"job": job}
+
+
+def result_files(job: dict) -> list[dict]:
+ out = []
+ for output in job.get("outputs") or []:
+ if not isinstance(output, dict):
+ continue
+ for f in output.get("files") or []:
+ if isinstance(f, dict) and _FILE_ID.match(str(f.get("file_id") or "")):
+ out.append({**f, "output": output.get("name"), "kind": output.get("kind")})
+ return out
+
+
+def fetch_file(job_id: str, n: int) -> tuple[Path, str]:
+ job = _call("GET", f"/jobs/{_check_job(job_id)}").get("job") or {}
+ if job.get("state") != "done":
+ raise ComfyError("That job has not finished yet.", 409, "not_ready")
+ files = result_files(job)
+ if n < 0 or n >= len(files):
+ raise ComfyError("That job has no such result file.", 404, "not_found")
+ item = files[n]
+ folder = job_folder(job_id)
+ dest = folder / f"{n:05d}-{safe_name(str(item.get('name') or ''), 'result')}"
+ meta = folder / (dest.name + ".type")
+ if dest.is_file() and meta.is_file():
+ os.utime(folder)
+ return dest, meta.read_text("utf-8") or "application/octet-stream"
+ base = current_url()
+ req = urllib.request.Request(f"{base}{PREFIX}/files/{item['file_id']}", headers=_headers({"Accept": "*/*"}))
+ part = dest.with_name(dest.name + ".part")
+ try:
+ with _opener(base).open(req, timeout=LONG_TIMEOUT) as resp, open(part, "wb") as out:
+ ctype = resp.headers.get("Content-Type", "") or "application/octet-stream"
+ size = 0
+ while True:
+ chunk = resp.read(1024 * 1024)
+ if not chunk:
+ break
+ size += len(chunk)
+ if size > MAX_FILE:
+ raise ComfyError("The result file is larger than 4 GB, so it was dropped.", 502)
+ out.write(chunk)
+ except urllib.error.HTTPError as exc:
+ part.unlink(missing_ok=True)
+ raise _error_of(exc)
+ except (urllib.error.URLError, OSError):
+ part.unlink(missing_ok=True)
+ raise _unreachable(base)
+ except ComfyError:
+ part.unlink(missing_ok=True)
+ raise
+ os.replace(part, dest)
+ meta.write_text(ctype.split(";")[0].strip(), "utf-8")
+ return dest, ctype.split(";")[0].strip()
diff --git a/docs/MANUAL.md b/docs/MANUAL.md
index 77ce90a..f345599 100644
--- a/docs/MANUAL.md
+++ b/docs/MANUAL.md
@@ -729,6 +729,40 @@ Each line is a row with its **start** and **end** in seconds (type `12.5` or `1:
Add Text from Create. Type the words, and the Text card opens: **font** (the bundled fonts and any you imported), **size**, **weight**, **color** and **alignment**. Double-click the block to edit again. Each change is one undo step.
+## Generate with Comfy
+
+Generate sends pictures from your movie to a Comfy server and brings the result back as video blocks on the Timeline. It is for the desktop only: on iPad the command and the Preferences section are not there. FormMorpheus does not run the generation itself. The Comfy server does the work, so it needs Comfy-FormBridge-Suite installed in the server's `custom_nodes` folder, the models its workflows use, and some patience on a computer without a graphics card.
+
+### Connect to a server
+
+1. Open Preferences (Ctrl+,) and choose **Comfy**. Type the server's address in **Comfy server address**. The default is `http://127.0.0.1:8188`, a Comfy server on this computer. The `FORMMORPHEUS_COMFY_URL` variable, when you set it, wins over the saved address.
+2. Press **Test**. The card says **Connected** with the address, or says in a sentence what is wrong: the server could not be reached, Comfy-FormBridge-Suite is not installed, or the server is too old and needs a newer version.
+3. A server that asks for a sign-in key takes it in **Sign-in key**. **Save key** keeps it in this computer's keychain, never in the settings file, and it is sent only to that server. **Forget key** removes it. A computer with no keychain FormMorpheus can use says so and keeps no key.
+
+### Make something
+
+Open the card from Create · **Generate with Comfy...**. Pick a **Mode**, select what it needs on the Timeline, and press **Generate**. The card tells you in a sentence what to select until the selection fits, and says when the Comfy server has no workflow for the mode or is not ready for it.
+
+| Mode | Select | What you get |
+|---|---|---|
+| **Fluid shot from flipbook keyframes** | a Flipbook whose frames are the painted keyframes | a video that moves through your keyframes |
+| **Animate a drawing** | a Drawing, a Flipbook or a picture | a video that brings it to life |
+| **Erase on a video** | a video block, and a Drawing above it painted over the first frame | the video with the painted area taken out |
+| **Add to a video** | a video block, and a Drawing above it painted over the first frame | the video with what you painted added |
+| **Relight a video** | a video block, and a Drawing above it painted over the first frame | the video lit the way you painted |
+| **Matte** | a video block | a matte of the subject |
+| **Upscale** | a video block | the video at a larger size |
+
+The painted area of the Drawing above the video is what the server is told to change. Keyframes of a Flipbook snap to every eighth frame within the block.
+
+While it works, **Progress** shows the place in the queue, then a bar with Step of steps and a preview picture, and **Cancel** stops the job. When it is done the results are placed as one undo step: a new video block on a new track at the start of the source block, a mask on its own track when the mode makes one, and a note of where it came from kept with the video. The seed used is shown, and **Retry with another seed** runs the same job again for a different result. A caption or prompt result adds its words to the prompt box instead.
+
+**Not ready.** When the server lacks something, the card lists it in plain words: a missing node pack, missing nodes, or a missing model with its size and the folder to put it in, and a reminder to accept a model's terms at its source first when it needs that. Generate stays off until the server has everything.
+
+### Where it keeps things
+
+Results received wait in `comfy-` folders inside the **Jobs** folder of the data folder until the window has placed them, and the engine removes them after they have been idle for 30 minutes. The results you placed are part of the movie and are saved in the `.fmo` like any video, with their origin.
+
## Export

@@ -791,6 +825,7 @@ Open with Ctrl+, (File or Edit menu). The pages:
- **Timeline**: undo steps, scrub speed (Precise, Medium or Fast, which also sets how fast scrubbing the frame strip moves), two and three-finger tap for undo and redo, and ask before deleting.
- **Pen and Tablet**: the test pad, the pressure curve and what the pen's eraser end and buttons do (see Pen tablets).
- **Video Tools** (desktop only): which ffmpeg FormMorpheus uses and what it can encode, and Download ffmpeg and Remove for the family's build (see Engine formats).
+- **Comfy** (desktop only): the Comfy server's address, Test, and the sign-in key (see Generate with Comfy).
- **Agents** (desktop only): whether outside agents may work on your movies, the address and command that connect a client, and a button that opens the terminal panel (see Agents).
- **Interface** (GPU): **GPU compositing** draws the Stage and exports on the graphics card. It is on when the card is faster and gives the same picture as the processor, and otherwise the processor does the work. Open the app with `?gpu=force` at the end of the address to skip the speed test.
@@ -837,6 +872,7 @@ An outside agent is a program on your computer, such as Claude Code, Codex, Curs
- **Reads** run at once: the version, the library folder and what your ffmpeg can encode (`get_context`), the movie list (`list_movies`), one movie's size, frame rate, length, tracks and content (`get_movie`), a movie's poster and preview (`get_movie_picture`), the saved characters in your Characters library (`list_characters`), which voices are ready on this computer and what each can speak with (`list_voices`), a movie's subtitles with their look and each line's start and end in seconds and frames (`list_subtitles`), and the other commands (`list_commands`). `run_command` also reads Recently Deleted, the Exports folder, stacks, fonts and the encoders your ffmpeg has.
- **Changes to the library** are made by `manage_movie`: create an empty movie, rename, duplicate, delete and restore. Delete moves a movie to Recently Deleted and never erases it. `run_command` also sets a movie's tags and its stack.
- **Five always ask first**: `export_movie` makes a file in the Exports folder, `import_file` brings a picture, video, sound or font file into a movie and saves it, `add_character` puts a copy of a saved character into a movie at the Playhead (or a frame the agent names), as Add to Movie in the Characters panel does, and saves the movie, and `add_voice` speaks a line with the built-in voice, a voice app on this computer or an online voice and puts the sound on the movie's Timeline at the Playhead (or a frame the agent names), as AI Voice does, and saves the movie, and `set_subtitles` changes a movie's subtitles (lines in seconds or the text of a .srt or .vtt file, replacing or adding to the lines, making lines from AI voices, showing or hiding them and their look), as the Subtitles card does, and saves the movie. All five need the FormMorpheus window open. You approve each one in it, and the window opens that movie to carry it out (`add_character`, `add_voice` and `set_subtitles` use the movie already open when the agent names none).
+- **Comfy**: `comfy_status` reads whether your Comfy server can be reached and is ready (it shows only whether a sign-in key is saved, never the key), `comfy_workflows` lists what the server can make and what it is missing, and `comfy_job` follows one job. `comfy_generate` always asks first: with your yes, the window sends the blocks selected on its Timeline to the Comfy server for a mode (fluid, animate, erase, add, relight, matte or upscale), waits for the job, places the results on new tracks and saves the movie. It waits up to 2 minutes for your answer and 30 minutes for the work, and it does not ask when the server cannot do the job anyway.
Agents work only on FormMorpheus's own data: your movie library, your Characters library (the Characters folder in the data folder), Recently Deleted, the Exports folder and the added fonts. None of these tools reads another file or folder on your computer, and an import takes only a file that is already inside the library folder. A program you run in the terminal panel can still do whatever it can do on its own, as in any terminal.
@@ -889,6 +925,12 @@ The terminal panel runs a shell and the agent programs beside the Stage and the
Closing FormMorpheus ends every tab.
+## New in 0.39.0
+
+**Generate with Comfy.** Create · Generate with Comfy... sends the selected blocks to a Comfy server and brings the result back on new tracks, in one undo step. It makes a fluid shot from the keyframes of a Flipbook, animates a drawing, erases, adds or relights something in a video from a drawing painted over its first frame, makes a matte, or upscales a video. It needs Comfy-FormBridge-Suite on the server. Preferences · Comfy holds the server's address, Test and the sign-in key. Desktop only. See Generate with Comfy.
+
+**Agents and Comfy.** `comfy_status`, `comfy_workflows` and `comfy_job` read, and `comfy_generate` asks first. See Agents.
+
## New in 0.38.0
**On iPad, AI Voice.** The Online tab works with your own key, kept in the iPad's Keychain. The built-in voice needs a computer; use Voice app with the address of a speech server on a computer on the same network, by number or by a `.local` name. Only an address on your own network is accepted, and the iPad asks once for local network access. See AI Voice.
diff --git a/docs/api-contract.json b/docs/api-contract.json
index c93c20f..f89b54b 100644
--- a/docs/api-contract.json
+++ b/docs/api-contract.json
@@ -1,5 +1,5 @@
{
-"info":{"title":"formmorpheus","version":"0.38.1"},
+"info":{"title":"formmorpheus","version":"0.39.0"},
"openapi":"3.1.0",
"paths":{
"/api/agent/claude/open":{"post":{"operationId":"claude_open_api_agent_claude_open_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClaudeBody"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Claude Open Api Agent Claude Open Post","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Claude Open","tags":["terminal"]}},
@@ -27,6 +27,15 @@
"/api/characters/{name}":{"delete":{"operationId":"delete_character_api_characters__name__delete","parameters":[{"in":"path","name":"name","required":true,"schema":{"title":"Name","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Delete Character Api Characters Name Delete","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Delete Character"},"get":{"operationId":"read_character_api_characters__name__get","parameters":[{"in":"path","name":"name","required":true,"schema":{"title":"Name","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Read Character"},"put":{"operationId":"write_character_api_characters__name__put","parameters":[{"in":"path","name":"name","required":true,"schema":{"title":"Name","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Write Character Api Characters Name Put","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Write Character"}},
"/api/characters/{name}/poster":{"get":{"operationId":"read_poster_api_characters__name__poster_get","parameters":[{"in":"path","name":"name","required":true,"schema":{"title":"Name","type":"string"}},{"in":"query","name":"v","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"V"}}],"responses":{"200":{"content":{"application/json":{"schema":{}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Read Poster"}},
"/api/characters/{name}/rename":{"post":{"operationId":"rename_character_api_characters__name__rename_post","parameters":[{"in":"path","name":"name","required":true,"schema":{"title":"Name","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RenameBody"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Rename Character Api Characters Name Rename Post","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Rename Character"}},
+"/api/comfy/jobs/{job_id}":{"get":{"operationId":"job_api_comfy_jobs__job_id__get","parameters":[{"in":"path","name":"job_id","required":true,"schema":{"title":"Job Id","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Job Api Comfy Jobs Job Id Get","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Job","tags":["comfy"]}},
+"/api/comfy/jobs/{job_id}/cancel":{"post":{"operationId":"cancel_api_comfy_jobs__job_id__cancel_post","parameters":[{"in":"path","name":"job_id","required":true,"schema":{"title":"Job Id","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Cancel Api Comfy Jobs Job Id Cancel Post","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Cancel","tags":["comfy"]}},
+"/api/comfy/jobs/{job_id}/files/{n}":{"get":{"operationId":"job_file_api_comfy_jobs__job_id__files__n__get","parameters":[{"in":"path","name":"job_id","required":true,"schema":{"title":"Job Id","type":"string"}},{"in":"path","name":"n","required":true,"schema":{"title":"N","type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Job File","tags":["comfy"]}},
+"/api/comfy/key":{"delete":{"operationId":"delete_key_api_comfy_key_delete","responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Delete Key Api Comfy Key Delete","type":"object"}}},"description":"Successful Response"}},"summary":"Delete Key","tags":["comfy"]},"put":{"operationId":"put_key_api_comfy_key_put","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/app__routers__comfy__KeyBody"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Put Key Api Comfy Key Put","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Put Key","tags":["comfy"]}},
+"/api/comfy/run":{"post":{"operationId":"run_api_comfy_run_post","responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Run Api Comfy Run Post","type":"object"}}},"description":"Successful Response"}},"summary":"Run","tags":["comfy"]}},
+"/api/comfy/server":{"put":{"operationId":"server_api_comfy_server_put","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerBody"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Server Api Comfy Server Put","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Server","tags":["comfy"]}},
+"/api/comfy/status":{"get":{"operationId":"status_api_comfy_status_get","responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Status Api Comfy Status Get","type":"object"}}},"description":"Successful Response"}},"summary":"Status","tags":["comfy"]}},
+"/api/comfy/workflows":{"get":{"operationId":"workflows_api_comfy_workflows_get","responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Workflows Api Comfy Workflows Get","type":"object"}}},"description":"Successful Response"}},"summary":"Workflows","tags":["comfy"]}},
+"/api/comfy/workflows/{wid}/readiness":{"get":{"operationId":"readiness_api_comfy_workflows__wid__readiness_get","parameters":[{"in":"path","name":"wid","required":true,"schema":{"title":"Wid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Readiness Api Comfy Workflows Wid Readiness Get","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Readiness","tags":["comfy"]}},
"/api/exports":{"get":{"operationId":"list_exports_api_exports_get","responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response List Exports Api Exports Get","type":"object"}}},"description":"Successful Response"}},"summary":"List Exports"}},
"/api/exports/{name}":{"delete":{"operationId":"delete_export_api_exports__name__delete","parameters":[{"in":"path","name":"name","required":true,"schema":{"title":"Name","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Delete Export Api Exports Name Delete","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Delete Export"},"get":{"operationId":"read_export_api_exports__name__get","parameters":[{"in":"path","name":"name","required":true,"schema":{"title":"Name","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Read Export"},"put":{"operationId":"write_export_api_exports__name__put","parameters":[{"in":"path","name":"name","required":true,"schema":{"title":"Name","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Write Export Api Exports Name Put","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Write Export"}},
"/api/files/read":{"get":{"description":"Streams a movie file from an absolute path the operating system handed the app (a double-click, Open With).","operationId":"read_file_api_files_read_get","parameters":[{"in":"query","name":"path","required":true,"schema":{"title":"Path","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Read File"}},
@@ -94,7 +103,7 @@
"/api/voice/builtin/voices":{"get":{"operationId":"builtin_voices_api_voice_builtin_voices_get","responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Builtin Voices Api Voice Builtin Voices Get","type":"object"}}},"description":"Successful Response"}},"summary":"Builtin Voices","tags":["voice"]}},
"/api/voice/local":{"put":{"operationId":"local_save_api_voice_local_put","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LocalBody"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Local Save Api Voice Local Put","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Local Save","tags":["voice"]}},
"/api/voice/local/probe":{"post":{"operationId":"local_probe_api_voice_local_probe_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProbeBody"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Local Probe Api Voice Local Probe Post","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Local Probe","tags":["voice"]}},
-"/api/voice/online/key":{"delete":{"operationId":"online_key_clear_api_voice_online_key_delete","responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Online Key Clear Api Voice Online Key Delete","type":"object"}}},"description":"Successful Response"}},"summary":"Online Key Clear","tags":["voice"]},"put":{"operationId":"online_key_api_voice_online_key_put","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyBody"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Online Key Api Voice Online Key Put","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Online Key","tags":["voice"]}},
+"/api/voice/online/key":{"delete":{"operationId":"online_key_clear_api_voice_online_key_delete","responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Online Key Clear Api Voice Online Key Delete","type":"object"}}},"description":"Successful Response"}},"summary":"Online Key Clear","tags":["voice"]},"put":{"operationId":"online_key_api_voice_online_key_put","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/app__routers__voice__KeyBody"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Online Key Api Voice Online Key Put","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Online Key","tags":["voice"]}},
"/api/voice/online/voices":{"get":{"operationId":"online_voices_api_voice_online_voices_get","responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Online Voices Api Voice Online Voices Get","type":"object"}}},"description":"Successful Response"}},"summary":"Online Voices","tags":["voice"]}},
"/api/voice/speak":{"post":{"operationId":"speak_api_voice_speak_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpeakBody"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Speak Api Voice Speak Post","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Speak","tags":["voice"]}},
"/api/voice/status":{"get":{"operationId":"status_api_voice_status_get","responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Status Api Voice Status Get","type":"object"}}},"description":"Successful Response"}},"summary":"Status","tags":["voice"]}},
@@ -115,7 +124,6 @@
"CopyToBody":{"properties":{"dir":{"title":"Dir","type":"string"}},"required":["dir"],"title":"CopyToBody","type":"object"},
"Entry":{"properties":{"dir":{"title":"Dir","type":"string"},"id":{"title":"Id","type":"string"}},"required":["id","dir"],"title":"Entry","type":"object"},
"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"},
-"KeyBody":{"properties":{"key":{"maxLength":400,"minLength":1,"title":"Key","type":"string"}},"required":["key"],"title":"KeyBody","type":"object"},
"LibraryBody":{"properties":{"copyMovies":{"default":false,"title":"Copymovies","type":"boolean"},"dir":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dir"}},"title":"LibraryBody","type":"object"},
"LocalBody":{"properties":{"base":{"default":"","maxLength":200,"title":"Base","type":"string"},"key":{"anyOf":[{"maxLength":400,"type":"string"},{"type":"null"}],"title":"Key"},"model":{"default":"","maxLength":120,"title":"Model","type":"string"},"voice":{"default":"","maxLength":120,"title":"Voice","type":"string"}},"title":"LocalBody","type":"object"},
"MakeBody":{"properties":{"lib":{"title":"Lib","type":"string"},"set":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Set"}},"required":["lib"],"title":"MakeBody","type":"object"},
@@ -124,6 +132,7 @@
"OpenBody":{"properties":{"cols":{"default":100,"maximum":500.0,"minimum":10.0,"title":"Cols","type":"integer"},"cwd":{"anyOf":[{"maxLength":4096,"type":"string"},{"type":"null"}],"title":"Cwd"},"rows":{"default":30,"maximum":200.0,"minimum":4.0,"title":"Rows","type":"integer"},"title":{"anyOf":[{"maxLength":60,"type":"string"},{"type":"null"}],"title":"Title"}},"title":"OpenBody","type":"object"},
"ProbeBody":{"properties":{"base":{"maxLength":200,"minLength":1,"title":"Base","type":"string"}},"required":["base"],"title":"ProbeBody","type":"object"},
"RenameBody":{"properties":{"to":{"title":"To","type":"string"}},"required":["to"],"title":"RenameBody","type":"object"},
+"ServerBody":{"properties":{"url":{"default":"","maxLength":300,"title":"Url","type":"string"}},"title":"ServerBody","type":"object"},
"SizeBody":{"properties":{"cols":{"maximum":500.0,"minimum":10.0,"title":"Cols","type":"integer"},"rows":{"maximum":200.0,"minimum":4.0,"title":"Rows","type":"integer"}},"required":["cols","rows"],"title":"SizeBody","type":"object"},
"SpeakBody":{"properties":{"engine":{"default":"builtin","title":"Engine","type":"string"},"language":{"default":"","title":"Language","type":"string"},"model":{"default":"","title":"Model","type":"string"},"speed":{"default":1.0,"maximum":2.0,"minimum":0.5,"title":"Speed","type":"number"},"text":{"maxLength":10000,"minLength":1,"title":"Text","type":"string"},"voice":{"default":"","title":"Voice","type":"string"}},"required":["text"],"title":"SpeakBody","type":"object"},
"StackBody":{"properties":{"items":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Items"},"name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Name"}},"title":"StackBody","type":"object"},
@@ -131,7 +140,9 @@
"TagsBody":{"properties":{"tags":{"items":{"type":"string"},"title":"Tags","type":"array"}},"required":["tags"],"title":"TagsBody","type":"object"},
"ValidationError":{"properties":{"ctx":{"title":"Context","type":"object"},"input":{"title":"Input"},"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"},
"app__routers__brushes__OrderBody":{"properties":{"active":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Active"},"deleted":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Deleted"},"ids":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Ids"},"items":{"anyOf":[{"items":{"$ref":"#/components/schemas/Entry"},"type":"array"},{"type":"null"}],"title":"Items"},"level":{"enum":["root","lib","set"],"title":"Level","type":"string"},"lib":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Lib"},"set":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Set"}},"required":["level"],"title":"OrderBody","type":"object"},
-"app__routers__library__OrderBody":{"properties":{"order":{"items":{"type":"string"},"title":"Order","type":"array"},"stack":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Stack"}},"required":["order"],"title":"OrderBody","type":"object"}
+"app__routers__comfy__KeyBody":{"properties":{"key":{"maxLength":2000,"minLength":1,"title":"Key","type":"string"}},"required":["key"],"title":"KeyBody","type":"object"},
+"app__routers__library__OrderBody":{"properties":{"order":{"items":{"type":"string"},"title":"Order","type":"array"},"stack":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Stack"}},"required":["order"],"title":"OrderBody","type":"object"},
+"app__routers__voice__KeyBody":{"properties":{"key":{"maxLength":400,"minLength":1,"title":"Key","type":"string"}},"required":["key"],"title":"KeyBody","type":"object"}
}},
"x-websockets":["/api/penlink/desk","/api/recovery/{session}/live","/api/terminal/{sid}/stream"]
}
diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md
index 0924877..024daa2 100644
--- a/frontend/HASHOUT_LOG.md
+++ b/frontend/HASHOUT_LOG.md
@@ -15,6 +15,26 @@ Last updated: 2026-11-29 · free library names compared the way the engine store
- Under Licenses, a Third-party notices button opens the full licence texts the engine serves from `/api/notices` (THIRD-PARTY-NOTICES.txt, over a megabyte). They are asked for the first time the button opens them and set once as the text of a `pre` built with the dialog; a failed load says the same file is installed with the app and asks again next time.
+## unreleased · Generate with Comfy
+
+- refers-to: ui/generate-panel.ts; ui/comfy-settings.ts; io/comfy-api.ts; app/features/comfy-generate.ts; app/app.ts (the `comfy-generate` command, `CREATE_MORE`); ui/settings-dialog.ts; engine/types.ts :: Asset.generated; engine/normalize.ts; app/agent-bridge.ts; styles/comfy-generate.css
+- kind: decision
+- logged: 2026-11-29
+
+- The card is made the first time it opens and nothing is fetched before. Its forms are built once and toggled with `hidden`; the progress bar and the preview keep their space so a result arriving moves nothing.
+- One mode-to-workflow map lives in the window (Fluid `video.fluid`, Animate `video.animate`, Erase `video.clean`, Add and Relight `video.shot`, Matte `video.matte`, Upscale `video.upscale`), so the card and the agent tool read one source of truth. Sources are the selected blocks. The paint-over is the selected Drawing or Flipbook, or the first one on a higher track that covers the video's start.
+- Keyframes snap to multiples of 8 within the block, as the workflows expect. The mask is the paint-over's alpha, white on black.
+- Results are placed directly (`importMedia`, `importSequence`, preload, `firstPictures`) inside one `engine.run` named `Comfy: `, so the shot, the mask and the provenance are one undo step. The agent path (`runComfyFromAgent`) uses the same code and saves the movie afterwards, as `add_voice` does.
+- `Asset.generated` is optional and passes through `.fmo` untouched; `normalize.ts` drops it when it has no workflow string, so a damaged note never blocks a movie from opening.
+- The command, the Create entry and the Preferences section are skipped when `platform.kind === 'ipad'`.
+- The mask track uses luminance mode, checked on a real run of `formbridge.selftest.matte` against a CPU Comfy: white keeps the result and black shows the source underneath. The shot and the matte land at the source's start, and one Undo removes both.
+- The error box, the readiness list and the slot-form area keep a reserved minimum height and switch with `visibility` (class `is-empty`), not `display: none`, so the card, which is anchored at the bottom, never jumps after a fetch.
+- The readiness that `GET /api/comfy/workflows` attaches to each workflow is used as is; `/readiness` is called only when it is missing.
+- Slot type `media` (a still, a sequence or a movie) is filled the same way as `video`, `movie` and `frames`: the source block's file.
+- The agent runs need the renderer and the video pool, which `BridgeDeps` does not carry, so the app registers them once through `setComfyDeps`.
+- The close button uses the repo's `icon('close')`.
+- The card stays anchored at the bottom like the other cards, but `place()` caps its height at the room below the menu bar (`innerHeight - barFloor() - 4`). When it would still reach above the bar, it raises its own `bottom`. It runs on show (before the first paint), on window resize and from a ResizeObserver, and changes only inline styles. The body scrolls inside the card; the header, error box, action row and status line stay outside the scroll.
+
## unreleased · free library names compared the way the engine stores them
## v0.38.1 · free library names compared the way the engine stores them
@@ -2359,3 +2379,22 @@ Found by painting through the real app (new movie, brush library, Color panel, C
Review fixes. A folder drop stops reading further batches once the 2000 file cap is reached (it only stopped adding before, so a huge tree was still enumerated). The zip sniffer keeps at most 20000 entry names (the name list had no bound). The unsupported message uses `--space-3` for its gap. Law 7: the curve preset label "iPad" is now "Linked tablet" (id unchanged), and the Pen Link and Pen and Tablet sentences no longer name a handwriting feature or a tablet product ("Turn off handwriting-to-text on the tablet ...", "Link a tablet or another browser ..."). The three changed sentences have no translations yet and show in English until added.
- Noted, not changed: the tracker now sees plain mouse strokes on the canvas, so Pen and Tablet shows the "looks like a mouse" line to a mouse-only person who painted before opening it; harmless. The pen settings page and the paste, GPU and engine encode paths were read and found sound.
+
+## menus under the bar · more-below hint
+
+### ui/menu.ts, ui/popover.ts, ui/content-menu.ts, styles/panels.css
+- refers-to: menu.ts :: menuCap, barFloor, PopupMenu.openUnder, PopupMenu.openAt, PopupMenu.openBeside, PopupMenu.showMore, MenuBar.open; popover.ts :: Popover.showAt, Popover.openSub, Popover.place, Popover.showMore; content-menu.ts :: constructor
+- kind: fix
+- logged: 2026-11-29
+
+Port of the FormVis 2.8.3 and 2.8.4 menu fix (FORM-MENU-OVERLAP-FIX 1.2.0). The bar called the right-click routine, which flips a long menu above its point and clamps it to 4 px from the window top, over the bar; submenus clamped to the window top too, and the CSS cap (`100vh - 48px`) was larger than the room under the bar. Removed:
+- `b.menu.openAt(r.left, r.bottom + 4);` (MenuBar.open), now `openUnder`: top fixed under the button, inline `max-height` = `menuCap(top)` (75 percent of the window, never past the bottom) set before measuring.
+- `const top = Math.max(4, Math.min(fitsBelow ? y : y - h, window.innerHeight - h - 4));` (openAt, the Stage's right-click menu), now floored at `barFloor()` (`.cv-menubar` bottom + 4, or 4 when the bar is hidden for the system menu) with the same cap.
+- `const y = Math.max(pad, Math.min(row.top - pad, window.innerHeight - h - pad));` (openBeside), now floored at the root menu's floor and capped.
+- `this.panel.addEventListener('scroll', () => { if (this.panel.scrollTop !== this.subTop) this.closeSub(); }, { passive: true });` and every `this.panel` row read (insertBefore, children, scrollTop): the rows now live in `.cv-menu-list`, which scrolls; the card keeps its glass and holds the `.cv-menu-more` pill. Nothing outside menu.ts read the panel's children.
+- panels.css `.cv-menu { ... scroll-padding-block: var(--space-1); }` moved to the list, and `.cv-menu:has(> .cv-menu-item:nth-child(n + 16))` (both rules) now reads `> .cv-menu-list > .cv-menu-item`, so long menus keep the compact rows.
+- popover.ts `place`: `Math.max(MARGIN, ...)` for the top, and `openSub`'s `const y = Math.max(MARGIN, ...)`: a card opened at a point (`showAt`: every right-click card) now has `barFloor()` as its floor and `menuCap` as an inline cap; its submenus keep under the same floor and cap. `showFor` (anchored to a button) clears the inline cap and keeps the old 8 px margin, so cards opened from a button are as before.
+- Hint: the FormVis rules verbatim (fade by a mask on the list, 56 x 12 pill, 160 ms out, 490 ms back, `no-fade` on opening, reduced motion has no fade). The `.has-more` and `.no-fade` rules are written without the `.cv-menu` prefix so a list card uses them too. Popover takes an opt-in third argument `list`: the rows go in a `.cv-menu-list` inside the card (`body` points at it) with the pill beside; only the Stage content menu (`fm-cm`, 36 rows, the longest right-click menu) opts in. Other popovers were not converted because several append to `pop.el` directly or lay out the card themselves (paint-feel, paint-tools, paint-clip, Movie Settings, the keyframe card); they get the floor and cap only.
+- Behaviour kept: Popover cards clamp into the window instead of flipping at the pointer (as before); the menu-bar grow origin (`--fm-ox`, `--fm-oy`) is set in `openUnder`. No colours, glass, spacing or z-index changed; the system menu code (native-menu.ts) is untouched.
+- Seen, not changed: the Generate with Comfy card (Create menu > More) opens with its top at -212 px in a 1280 x 800 window, over the bar, in the unchanged build as well; it is a fixed card, not a menu.
+- Verified: `npx tsc --noEmit`; `npm run build`; `npx vitest run` (3419 passed, includes tests/unit/ui/menu.test.ts); headless Chrome over the production build served by the engine as setup/window_check does (uvicorn with FORMMORPHEUS_DIST), CPU 4x: every bar menu and Content > Add at 1871x1080, 1280x720, 1000x480, 800x320 (top 38 under a bar bottom of 33.5 in every frame, height at most 75 percent, last row by scroll and End); right-click Stage menu and content menu at 1280x800, 1871x1080, 1000x480 against a build of HEAD; hint timings at 1871x1080 unthrottled.
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 7dd6f4e..c01f047 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "formmorpheus",
- "version": "0.38.1",
+ "version": "0.39.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "formmorpheus",
- "version": "0.38.1",
+ "version": "0.39.0",
"license": "Apache-2.0",
"dependencies": {
"@fontsource/anton": "5.3.0",
diff --git a/frontend/package.json b/frontend/package.json
index 95d8a86..3f47a32 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,7 +1,7 @@
{
"name": "formmorpheus",
"private": true,
- "version": "0.38.1",
+ "version": "0.39.0",
"description": "FormMorpheus · animation studio in the Form family",
"license": "Apache-2.0",
"type": "module",
diff --git a/frontend/src/app/agent-bridge.ts b/frontend/src/app/agent-bridge.ts
index db358c2..415f57e 100644
--- a/frontend/src/app/agent-bridge.ts
+++ b/frontend/src/app/agent-bridge.ts
@@ -15,6 +15,7 @@ import type { Movie, SubtitleStyle, Track } from '../engine/types';
import { placeCharacter, unpackCharacter } from '../ui/characters-panel';
import { t } from '../ui/i18n';
import type { SpokenOnTimeline } from './voice-commands';
+import { runComfyFromAgent } from './features/comfy-generate';
export interface BridgeDeps {
engine: Engine;
@@ -174,6 +175,27 @@ export function startAgentBridge(d: BridgeDeps): void {
return { ok: true, content: done.name, seconds: done.seconds, movie: d.engine.libraryName ?? d.engine.movie?.name ?? '', saved };
};
+ const generate = async (a: Args): Promise => {
+ const name = text(a.movie);
+ if (name) {
+ const blocked = await front(name);
+ if (blocked) return { ok: false, error: blocked };
+ }
+ if (!d.engine.movie) return { ok: false, error: t('FormMorpheus could not open that movie.') };
+ const seed = whole(a.seed);
+ const slots = a.slots && typeof a.slots === 'object' && !Array.isArray(a.slots) ? (a.slots as Record) : undefined;
+ let done: { blocks: number; text: string };
+ try {
+ done = await runComfyFromAgent({ mode: text(a.mode), ...(text(a.prompt) ? { prompt: text(a.prompt) } : {}), ...(seed === undefined ? {} : { seed }), ...(slots ? { slots } : {}) });
+ } catch (e) {
+ if (e instanceof ApiError) return { ok: false, error: e.message };
+ throw e;
+ }
+ if (!done.blocks) return { ok: false, error: done.text || t('Comfy made nothing to add.') };
+ const saved = await d.save();
+ return { ok: true, blocks: done.blocks, text: done.text, movie: d.engine.libraryName ?? d.engine.movie?.name ?? '', saved };
+ };
+
const setSubtitles = async (a: Args): Promise => {
const name = text(a.movie);
if (name) {
@@ -235,7 +257,7 @@ export function startAgentBridge(d: BridgeDeps): void {
else {
working = true;
try {
- result = item.kind === 'export_movie' ? await exportMovie(a) : item.kind === 'import_file' ? await importFile(item.id, a) : item.kind === 'add_character' ? await addCharacter(a) : item.kind === 'add_voice' ? await addVoice(a) : item.kind === 'set_subtitles' ? await setSubtitles(a) : { ok: false, error: t('This FormMorpheus window does not know that request.') };
+ result = item.kind === 'export_movie' ? await exportMovie(a) : item.kind === 'import_file' ? await importFile(item.id, a) : item.kind === 'add_character' ? await addCharacter(a) : item.kind === 'add_voice' ? await addVoice(a) : item.kind === 'set_subtitles' ? await setSubtitles(a) : item.kind === 'comfy_generate' ? await generate(a) : { ok: false, error: t('This FormMorpheus window does not know that request.') };
} catch (e) {
result = { ok: false, error: said(e, t('FormMorpheus could not do that.')) };
}
diff --git a/frontend/src/app/app.ts b/frontend/src/app/app.ts
index 62b680f..10d9072 100644
--- a/frontend/src/app/app.ts
+++ b/frontend/src/app/app.ts
@@ -37,6 +37,9 @@ import { ContentMenu } from '../ui/content-menu';
import { LipsyncDialog } from '../ui/lipsync-dialog';
import { VoicePanel } from '../ui/voice-panel';
import { AiVoicePanel } from '../ui/ai-voice-panel';
+import { GeneratePanel } from '../ui/generate-panel';
+import { COMFY_CHANGED, COMFY_SECTION } from '../ui/comfy-settings';
+import { setComfyDeps } from './features/comfy-generate';
import { SubtitlesPanel } from '../ui/subtitles-panel';
import type { SpeakRequest } from '../io/voice-api';
import { speakToTimeline } from './voice-commands';
@@ -142,7 +145,7 @@ const FLIP_RATES = [6, 8, 12, 15, 24, 30];
const FLIP_FPS_MENU = { label: 'Flipbook at frame rate', items: FLIP_RATES.map((n) => `add-flipbook-${n}`) };
/** The Create menu: what to make, then what to bring in. */
/** Under the card's More row: what the four tiles and three rows leave out. */
-const CREATE_MORE: CreateItem[] = [FLIP_FPS_MENU, ...SHAPE_CREATE_ITEMS, '-', 'import-audio', 'record-audio', 'ai-voice', 'subtitles', '-', 'create-opens-paint'];
+const CREATE_MORE: CreateItem[] = [FLIP_FPS_MENU, ...SHAPE_CREATE_ITEMS, '-', 'import-audio', 'record-audio', 'ai-voice', 'subtitles', ...(platform.kind === 'ipad' ? [] : ['-', 'comfy-generate']), '-', 'create-opens-paint'];
const CUSTOM_TITLE_KEY ='formmorpheus.customTitleBar';
const stored = (k: string): string | null => { try { return localStorage.getItem(k); } catch { return null; } };
const store = (k: string, v: string): void => { try { localStorage.setItem(k, v); } catch { /* this session only */ } };
@@ -728,6 +731,16 @@ export function startApp(): void {
{ id: 'record-audio', label: 'Record sound...', icon: 'audio', enabled: has, run: () => { aiVoice.close(); subtitlesPanel.close(); voicePanel.show(); } },
{ id: 'ai-voice', label: 'AI Voice...', icon: 'audio', enabled: () => has(), run: () => { voicePanel.close(); subtitlesPanel.close(); aiVoice.show(); } },
{ id: 'subtitles', label: 'Subtitles...', icon: 'text', enabled: has, run: () => { voicePanel.close(); aiVoice.close(); subtitlesPanel.show(); } },
+ ...(platform.kind === 'ipad' ? [] : [(() => {
+ let gen: GeneratePanel | null = null;
+ setComfyDeps({ engine, renderer, video });
+ document.addEventListener(COMFY_CHANGED, () => { if (gen?.isOpen) void gen.refresh(); });
+ return { id: 'comfy-generate', label: 'Generate with Comfy...', icon: 'genPlug', enabled: () => has(), run: () => {
+ voicePanel.close(); aiVoice.close(); subtitlesPanel.close();
+ gen ??= new GeneratePanel({ engine, renderer, video }, () => settings.show(COMFY_SECTION));
+ gen.show();
+ } };
+ })()]),
{ id: 'sound-card', label: 'Sound options...', enabled: () => engine.selected.some((c) => c.kind === 'audio'), run: () => soundCard.show() },
{ id: 'import-file', label: 'File...', icon: 'upload', enabled: has, run: () => pickFor(MEDIA_ACCEPT) },
{ id: 'import-font', label: 'Import font...', enabled: has, run: () => pickFor('.otf,.ttf,.ttc,.woff,.woff2') },
diff --git a/frontend/src/app/features/comfy-generate.ts b/frontend/src/app/features/comfy-generate.ts
new file mode 100644
index 0000000..acc2adc
--- /dev/null
+++ b/frontend/src/app/features/comfy-generate.ts
@@ -0,0 +1,250 @@
+import type { Engine } from '../../engine/engine';
+import * as ops from '../../engine/ops';
+import type { Renderer } from '../../engine/render';
+import type { Asset, Content, Movie, Track } from '../../engine/types';
+import { importMedia, importSequence, type ImportResult } from '../../media/import';
+import { firstPictures } from '../../media/plan';
+import type { VideoPool } from '../../media/video';
+import { comfyApi, type ComfyJob, type ComfyJobState, type ComfyWorkflow } from '../../io/comfy-api';
+
+export type ComfyMode = 'fluid' | 'animate' | 'erase' | 'add' | 'relight' | 'matte' | 'upscale';
+export const MODE_WORKFLOW: Record = {
+ fluid: 'video.fluid', animate: 'video.animate', erase: 'video.clean', add: 'video.shot', relight: 'video.shot', matte: 'video.matte', upscale: 'video.upscale',
+};
+export const MODE_LABEL: Record = {
+ fluid: 'Fluid shot from flipbook keyframes', animate: 'Animate a drawing', erase: 'Erase on a video', add: 'Add to a video', relight: 'Relight a video', matte: 'Matte', upscale: 'Upscale',
+};
+export const MODES = Object.keys(MODE_WORKFLOW) as ComfyMode[];
+
+export interface ComfyDeps { engine: Engine; renderer: Renderer; video: VideoPool }
+export interface Sources { video: Content | null; paint: Content | null; flip: Content | null; still: Content | null }
+export interface Placed { blocks: number; text: string }
+
+const PAINTED: ReadonlyArray = ['drawing', 'flipbook', 'image'];
+const isMedia = (type: string): boolean => ['image', 'mask', 'frames', 'movie', 'video', 'media', 'keyframes'].includes(type);
+export const plainSlot = (type: string): boolean => !isMedia(type) && type !== 'points';
+
+function find(tracks: Track[], id: string): { c: Content; row: number } | null {
+ for (let i = 0; i < tracks.length; i++) for (const c of tracks[i].content) if (c.id === id) return { c, row: i };
+ return null;
+}
+
+export function sources(engine: Engine): Sources {
+ const m = engine.movie;
+ const out: Sources = { video: null, paint: null, flip: null, still: null };
+ if (!m) return out;
+ const picked = engine.selection.content.map((id) => find(m.tracks, id)).filter((x): x is { c: Content; row: number } => !!x);
+ const vid = picked.find((x) => x.c.kind === 'video');
+ out.video = vid?.c ?? null;
+ out.flip = picked.find((x) => x.c.kind === 'flipbook')?.c ?? null;
+ const painted = picked.find((x) => PAINTED.includes(x.c.kind));
+ out.still = painted?.c ?? null;
+ if (vid) {
+ const over = picked.find((x) => x.c.kind === 'drawing' || x.c.kind === 'flipbook');
+ if (over) out.paint = over.c;
+ else for (let r = vid.row - 1; r >= 0 && !out.paint; r--) {
+ const hit = m.tracks[r].content.find((c) => (c.kind === 'drawing' || c.kind === 'flipbook') && c.start <= vid.c.start && c.start + c.duration > vid.c.start);
+ if (hit) out.paint = hit;
+ }
+ }
+ return out;
+}
+
+export function missing(mode: ComfyMode, s: Sources): string {
+ if (mode === 'fluid') return s.flip ? '' : 'Select a Flipbook with the painted keyframes.';
+ if (mode === 'animate') return s.still ? '' : 'Select a Drawing, Flipbook or picture to animate.';
+ if (!s.video) return 'Select a video block.';
+ if ((mode === 'erase' || mode === 'add' || mode === 'relight') && !s.paint) return 'Paint over the video\'s first frame on a Drawing above it.';
+ return '';
+}
+
+function canvas(m: Movie): HTMLCanvasElement {
+ const c = document.createElement('canvas');
+ c.width = m.width;
+ c.height = m.height;
+ return c;
+}
+
+const png = (c: HTMLCanvasElement, name: string): Promise => new Promise((res, rej) => c.toBlob((b) => (b ? res(new File([b], name, { type: 'image/png' })) : rej(new Error('The picture could not be made.'))), 'image/png'));
+
+function draw(d: ComfyDeps, m: Movie, c: Content, local: number, into: HTMLCanvasElement): void {
+ d.renderer.thumb(into.getContext('2d') as CanvasRenderingContext2D, m, c, local, m.width, m.height);
+}
+
+async function still(d: ComfyDeps, m: Movie, blocks: Array<{ c: Content; local: number }>, name: string): Promise {
+ await firstPictures(d.video, m, blocks.map((b) => b.c));
+ const cv = canvas(m);
+ for (const b of blocks) draw(d, m, b.c, b.local, cv);
+ return png(cv, name);
+}
+
+async function paintMask(d: ComfyDeps, m: Movie, paint: Content, local: number): Promise {
+ const cv = canvas(m);
+ draw(d, m, paint, local, cv);
+ const ctx = cv.getContext('2d') as CanvasRenderingContext2D;
+ const img = ctx.getImageData(0, 0, cv.width, cv.height);
+ const p = img.data;
+ for (let i = 0; i < p.length; i += 4) { const v = p[i + 3] > 8 ? 255 : 0; p[i] = v; p[i + 1] = v; p[i + 2] = v; p[i + 3] = 255; }
+ ctx.putImageData(img, 0, 0);
+ return png(cv, 'mask.png');
+}
+
+// the video workflows step on an 8k+1 grid
+function keyFrames(c: Content): number[] {
+ const row = c.flip.find((f) => !f.hidden) ?? c.flip[0];
+ if (!row) return [0];
+ const out = new Set();
+ let at = 0;
+ for (const f of row.frames) {
+ if (at >= c.duration) break;
+ out.add(Math.min(Math.round(at / 8) * 8, Math.floor((c.duration - 1) / 8) * 8));
+ at += Math.max(1, f.hold);
+ }
+ return [...out].sort((a, b) => a - b);
+}
+
+function videoFile(d: ComfyDeps, m: Movie, c: Content): File {
+ const a = c.asset ? m.assets[c.asset] : undefined;
+ const blob = c.asset ? d.engine.assets.get(c.asset) : undefined;
+ if (!a || !blob) throw new Error('The video block\'s file is not loaded.');
+ return new File([blob], a.name || 'source.mp4', { type: a.mime || blob.type });
+}
+
+export function anchor(mode: ComfyMode, s: Sources): Content | null {
+ return mode === 'fluid' ? s.flip : mode === 'animate' ? s.still : s.video;
+}
+
+export async function collect(d: ComfyDeps, mode: ComfyMode, wf: ComfyWorkflow, s: Sources): Promise<{ files: Array<{ slot: string; file: File }>; slots: Record }> {
+ const m = d.engine.movie;
+ if (!m) throw new Error('Open a movie first.');
+ const files: Array<{ slot: string; file: File }> = [];
+ const slots: Record = {};
+ for (const slot of wf.slots) {
+ const t = slot.type;
+ if (t === 'video' || t === 'movie' || t === 'frames' || t === 'media') {
+ if (s.video && mode !== 'fluid' && mode !== 'animate') files.push({ slot: slot.name, file: videoFile(d, m, s.video) });
+ } else if (t === 'mask') {
+ if (s.paint) files.push({ slot: slot.name, file: await paintMask(d, m, s.paint, Math.max(0, (s.video?.start ?? s.paint.start) - s.paint.start)) });
+ } else if (t === 'image') {
+ let blocks: Array<{ c: Content; local: number }> = [];
+ if (mode === 'fluid' && s.flip) blocks = [{ c: s.flip, local: 0 }];
+ else if (mode === 'animate' && s.still) blocks = [{ c: s.still, local: 0 }];
+ else if (s.video) {
+ blocks = [{ c: s.video, local: 0 }];
+ if (s.paint && (mode === 'add' || mode === 'relight')) blocks.push({ c: s.paint, local: Math.max(0, s.video.start - s.paint.start) });
+ }
+ if (blocks.length) files.push({ slot: slot.name, file: await still(d, m, blocks, 'first.png') });
+ } else if (t === 'keyframes' && s.flip) {
+ const list: number[] = [];
+ for (const f of keyFrames(s.flip)) {
+ const name = `key-${String(f).padStart(5, '0')}.png`;
+ files.push({ slot: slot.name, file: await still(d, m, [{ c: s.flip, local: f }], name) });
+ list.push(f);
+ }
+ slots[slot.name] = list;
+ }
+ }
+ return { files, slots };
+}
+
+const SLEEP = (ms: number, signal: AbortSignal): Promise => new Promise((res) => {
+ const id = window.setTimeout(res, ms);
+ signal.addEventListener('abort', () => { window.clearTimeout(id); res(); }, { once: true });
+});
+
+export async function follow(job: ComfyJob, tick: (s: ComfyJobState) => void, signal: AbortSignal): Promise {
+ let cur = job;
+ while (cur.state === 'queued' || cur.state === 'running') {
+ await SLEEP(600, signal);
+ if (signal.aborted) return cur;
+ try {
+ const s = await comfyApi.job(cur.id);
+ cur = s.job;
+ tick(s);
+ } catch (e) {
+ if (signal.aborted) return cur;
+ throw e;
+ }
+ }
+ return cur;
+}
+
+const EXT: Record = { 'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov', 'image/png': 'png', 'image/webp': 'webp', 'image/jpeg': 'jpg' };
+
+export async function land(d: ComfyDeps, mode: ComfyMode, wf: ComfyWorkflow, job: ComfyJob, s: Sources, prompt: string, signal: AbortSignal): Promise {
+ const m = d.engine.movie;
+ const at = anchor(mode, s);
+ if (!m || !at) return { blocks: 0, text: '' };
+ const fps = m.fps;
+ let n = 0;
+ let text = '';
+ const got: Array<{ r: ImportResult; mask: boolean }> = [];
+ for (const out of job.outputs ?? []) {
+ const blobs: File[] = [];
+ for (const f of out.files) {
+ const b = await comfyApi.file(job.id, n++, signal);
+ blobs.push(new File([b], f.name || `result.${EXT[b.type] ?? 'bin'}`, { type: b.type }));
+ }
+ if (out.kind === 'text') { text = out.text ?? (blobs[0] ? await blobs[0].text() : ''); continue; }
+ if (!blobs.length) continue;
+ const mask = out.kind === 'mask' || out.kind === 'matte';
+ const r = blobs.length > 1 || out.kind === 'frames'
+ ? await importSequence(blobs, m, at.start, out.fps || fps)
+ : await importMedia(blobs[0], m, at.start);
+ got.push({ r, mask });
+ }
+ if (!got.length) return { blocks: 0, text };
+ const all = got.flatMap((g) => g.r.assets);
+ const pics = new Map();
+ for (const { asset, blob } of all) { d.engine.assets.set(asset.id, blob); if (asset.kind === 'image' || asset.kind === 'pixels') pics.set(asset.id, blob); }
+ await d.renderer.preload(pics);
+ await firstPictures(d.video, m, got.flatMap((g) => g.r.contents));
+ const note: NonNullable = { workflow: wf.id, version: wf.version, mode, seed: job.seed_used ?? -1, job: job.id, ...(prompt ? { prompt } : {}), source: at.id };
+ const table = Object.fromEntries(all.map((a) => [a.asset.id, { ...a.asset, generated: note }]));
+ let blocks = 0;
+ d.engine.run(`Comfy: ${wf.title}`, (mv: Movie) => {
+ let next: Movie = { ...mv, assets: { ...mv.assets, ...table } };
+ const row = Math.max(0, next.tracks.findIndex((tr) => tr.content.some((c) => c.id === at.id)));
+ const ids: string[] = [];
+ // masks last so each sits directly over what it cuts
+ for (const g of [...got.filter((x) => !x.mask), ...got.filter((x) => x.mask)]) {
+ for (const c0 of g.r.contents) {
+ const c: Content = { ...c0, start: at.start, ...(g.mask ? { mask: 'luminance' as const } : {}) };
+ const added = ops.addTrack(next, row, c.name);
+ next = ops.placeContent(added.movie, added.track.id, c, row).movie;
+ ids.push(c.id);
+ }
+ }
+ blocks = ids.length;
+ return { movie: next, select: ids };
+ });
+ return { blocks, text };
+}
+
+export const randomSeed = (): number => Math.floor(Math.random() * 2 ** 31);
+
+let shared: ComfyDeps | null = null;
+// BridgeDeps carries no renderer or video pool
+export function setComfyDeps(d: ComfyDeps): void { shared = d; }
+
+export async function runComfyFromAgent(req: { mode: string; prompt?: string; seed?: number; slots?: Record }): Promise {
+ const d = shared;
+ if (!d || !d.engine.movie) return { blocks: 0, text: 'Open a movie first.' };
+ if (!(MODES as string[]).includes(req.mode)) return { blocks: 0, text: `Unknown mode. Use one of: ${MODES.join(', ')}.` };
+ const mode = req.mode as ComfyMode;
+ const wf = (await comfyApi.workflows()).find((w) => w.id === MODE_WORKFLOW[mode]);
+ if (!wf) return { blocks: 0, text: 'This Comfy server has no workflow for this mode.' };
+ const s = sources(d.engine);
+ const need = missing(mode, s);
+ if (need) return { blocks: 0, text: need };
+ const media = await collect(d, mode, wf, s);
+ const values: Record = { ...(req.slots ?? {}), ...media.slots };
+ for (const slot of wf.slots) {
+ if (req.prompt !== undefined && slot.type === 'text' && /prompt/i.test(slot.name) && !/neg/i.test(slot.name)) values[slot.name] = req.prompt;
+ if (req.seed !== undefined && slot.type === 'seed') values[slot.name] = req.seed;
+ }
+ const ctrl = new AbortController();
+ const job = await follow(await comfyApi.run(wf.id, values, media.files, true, ctrl.signal), () => undefined, ctrl.signal);
+ if (job.state !== 'done') return { blocks: 0, text: job.error?.message || 'The job did not finish.' };
+ return land(d, mode, wf, job, s, req.prompt ?? '', ctrl.signal);
+}
diff --git a/frontend/src/engine/normalize.ts b/frontend/src/engine/normalize.ts
index 75f86a8..b0accf2 100644
--- a/frontend/src/engine/normalize.ts
+++ b/frontend/src/engine/normalize.ts
@@ -231,6 +231,7 @@ export function normalizeMovie(raw: unknown): Movie {
m.onion = onion(isObj(m.onion) ? m.onion : {});
m.tracks = trackList(m.tracks);
m.assets = isObj(m.assets) ? m.assets : {};
+ for (const a of Object.values(m.assets as Obj)) if (isObj(a) && 'generated' in a && !(isObj(a.generated) && typeof a.generated.workflow === 'string')) delete a.generated;
if (isObj(m.camera)) { const cam: Obj = { ...m.camera }; laneSplit(cam); m.camera = cam; }
else delete m.camera;
// a guide line's role comes from the file: only the floor is known
diff --git a/frontend/src/engine/types.ts b/frontend/src/engine/types.ts
index 06980ad..77e77c2 100644
--- a/frontend/src/engine/types.ts
+++ b/frontend/src/engine/types.ts
@@ -426,6 +426,8 @@ export interface Asset {
spoken?: { text: string; engine: 'builtin' | 'local' | 'online'; voice: string; cues: Array<{ start: number; end: number; text: string }> };
/** Fonts: the family name registered for Text content. */
family?: string;
+ /** Made on a Comfy server: the workflow, the mode, the seed it used, the job, the prompt and the block it was made from. */
+ generated?: { workflow: string; version: number; mode: string; seed: number; job: string; prompt?: string; source?: string };
}
/** One subtitle line: shown from movie frame `start` up to, not including, `end`. `from` is the sound block it was made from, so making them again replaces only those. */
diff --git a/frontend/src/io/comfy-api.ts b/frontend/src/io/comfy-api.ts
new file mode 100644
index 0000000..dd0af25
--- /dev/null
+++ b/frontend/src/io/comfy-api.ts
@@ -0,0 +1,103 @@
+// the page never talks to Comfy directly: the CSP allows only the engine
+import { ApiError, serviceReady } from './api';
+
+export type SlotType = 'text' | 'int' | 'float' | 'bool' | 'seed' | 'choice' | 'image' | 'mask' | 'frames' | 'movie' | 'video' | 'points' | 'keyframes' | 'size' | 'media';
+export interface ComfySlot { name: string; type: SlotType; required: boolean; default?: unknown; min?: number; max?: number; step?: number; choices?: string[]; description?: string }
+export interface ComfyOutputDef { name: string; kind: 'image' | 'frames' | 'movie' | 'mask' | 'matte' | 'text'; description?: string }
+export interface ComfyWorkflow { id: string; version: number; title: string; task?: string; description?: string; media: 'still' | 'video' | 'text'; slots: ComfySlot[]; outputs: ComfyOutputDef[]; ready?: boolean; readiness?: ComfyReadiness }
+export interface ComfyModel { folder: string; file: string; role?: string; present: boolean; size_mb?: number; gated?: boolean; source?: string; place?: string }
+export interface ComfyReadiness { ready: boolean; nodes: Array<{ class: string; present: boolean }>; packs: Array<{ name: string; present: boolean }>; models: ComfyModel[] }
+export interface ComfyStatus {
+ url: string;
+ hasKey?: boolean;
+ canStore?: boolean;
+ reachable?: boolean;
+ installed: boolean;
+ supported?: boolean;
+ message?: string;
+ pack?: { name: string; version: string };
+ comfy?: { version: string; minimum: string; supported: boolean };
+ device?: { name: string; vram_mb: number; ram_mb: number };
+ memory_profile?: string;
+}
+export interface ComfyFile { file_id: string; name: string; bytes: number; frame?: number }
+export interface ComfyOutput { name?: string; kind: ComfyOutputDef['kind']; width: number; height: number; frames: number; fps: number; files: ComfyFile[]; text?: string }
+export interface ComfyJob {
+ id: string;
+ workflow: string;
+ state: 'queued' | 'running' | 'done' | 'failed' | 'cancelled';
+ queue_position?: number;
+ progress?: { value: number; max: number; node?: string };
+ seed_used?: number;
+ cached?: boolean;
+ retried?: boolean;
+ outputs?: ComfyOutput[];
+ error?: { code: string; message: string };
+}
+export interface ComfyPreview { step: number; steps: number; image: string }
+export interface ComfyJobState { job: ComfyJob; preview?: ComfyPreview }
+
+const NOT_RUNNING = 'The FormMorpheus engine service is not running. Start it with ./formmorpheus.';
+const json = { 'Content-Type': 'application/json' };
+
+async function call(path: string, init?: RequestInit): Promise {
+ if (!(await serviceReady())) throw new ApiError(NOT_RUNNING, 0);
+ let res: Response;
+ try { res = await fetch(`/api/comfy${path}`, init); } catch (e) {
+ if (e instanceof DOMException && e.name === 'AbortError') throw e;
+ throw new ApiError(NOT_RUNNING, 0);
+ }
+ if (!res.ok) {
+ let detail = '';
+ try {
+ const body = (await res.json()) as { detail?: unknown };
+ const d = body?.detail as { message?: unknown } | string | undefined;
+ if (typeof d === 'string') detail = d;
+ else if (d && typeof d.message === 'string') detail = d.message;
+ } catch { /* not JSON */ }
+ throw new ApiError(detail || res.statusText || `Request failed (${res.status})`, res.status);
+ }
+ return res;
+}
+
+const send = (method: string, body?: unknown, signal?: AbortSignal): RequestInit => ({ method, ...(body === undefined ? {} : { headers: json, body: JSON.stringify(body) }), ...(signal ? { signal } : {}) });
+const enc = encodeURIComponent;
+const flat = (raw: unknown): ComfyStatus => {
+ const r = raw as Omit & { handshake?: Partial };
+ return { ...r, ...(r.handshake ?? {}), url: r.url, installed: !!r.handshake?.installed } as ComfyStatus;
+};
+
+export const comfyApi = {
+ async status(): Promise { return flat(await (await call('/status')).json()); },
+ async setServer(url: string): Promise { return flat(await (await call('/server', send('PUT', { url }))).json()); },
+ async setKey(key: string): Promise { await call('/key', send('PUT', { key })); return comfyApi.status(); },
+ async clearKey(): Promise { await call('/key', send('DELETE')); return comfyApi.status(); },
+ async workflows(): Promise { return ((await (await call('/workflows')).json()) as { workflows: ComfyWorkflow[] }).workflows ?? []; },
+ async readiness(id: string): Promise { return (await (await call(`/workflows/${enc(id)}/readiness`)).json()) as ComfyReadiness; },
+ async run(workflow: string, slots: Record, files: Array<{ slot: string; file: File }>, reuse = true, signal?: AbortSignal): Promise {
+ const form = new FormData();
+ form.append('workflow', workflow);
+ form.append('slots', JSON.stringify(slots));
+ form.append('reuse', reuse ? 'true' : 'false');
+ for (const f of files) form.append(f.slot, f.file, f.file.name);
+ return ((await (await call('/run', { method: 'POST', body: form, ...(signal ? { signal } : {}) })).json()) as { job: ComfyJob }).job;
+ },
+ async job(id: string): Promise { return (await (await call(`/jobs/${enc(id)}`)).json()) as ComfyJobState; },
+ async file(id: string, n: number, signal?: AbortSignal): Promise { return (await call(`/jobs/${enc(id)}/files/${n}`, signal ? { signal } : undefined)).blob(); },
+ async cancel(id: string): Promise { return ((await (await call(`/jobs/${enc(id)}/cancel`, send('POST'))).json()) as { job: ComfyJob }).job; },
+};
+
+export function readinessWords(r: ComfyReadiness, tr: (s: string) => string): string[] {
+ if (r.ready) return [];
+ const out: string[] = [];
+ for (const p of r.packs ?? []) if (!p.present) out.push(tr('Missing node pack: {name}').replace('{name}', p.name));
+ const nodes = (r.nodes ?? []).filter((n) => !n.present).map((n) => n.class);
+ if (nodes.length) out.push(tr('Missing nodes: {names}').replace('{names}', nodes.join(', ')));
+ for (const m of r.models ?? []) {
+ if (m.present) continue;
+ const size = m.size_mb ? ` (${Math.round(m.size_mb)} MB)` : '';
+ out.push(tr('Missing model {file}{size}: put it in {place}').replace('{file}', m.file).replace('{size}', size).replace('{place}', m.place || m.folder) + (m.gated ? ` · ${tr('accept its terms at the source first')}` : ''));
+ }
+ if (!out.length) out.push(tr('This workflow is not ready on the Comfy server.'));
+ return out;
+}
diff --git a/frontend/src/styles/comfy-generate.css b/frontend/src/styles/comfy-generate.css
new file mode 100644
index 0000000..c26f9ea
--- /dev/null
+++ b/frontend/src/styles/comfy-generate.css
@@ -0,0 +1,79 @@
+/* The Generate card (ui/generate-panel.ts) and the Comfy part of Preferences (ui/comfy-settings.ts). */
+.fm-gen {
+ position: fixed;
+ inset-inline-end: var(--space-4);
+ bottom: calc(var(--space-4) + var(--cv-row-h) * 5.5);
+ z-index: var(--z-companion);
+ width: calc(var(--space-8) * 11);
+ max-width: calc(100vw - var(--space-8));
+ max-height: calc(100vh - var(--space-6));
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ padding: var(--space-3);
+ background: var(--glass-solid-bg);
+ border: 1px solid var(--glass-border);
+ border-radius: var(--radius-pop);
+ box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow);
+ -webkit-backdrop-filter: var(--glass-filter);
+ backdrop-filter: var(--glass-filter);
+ color: var(--text-primary);
+ font-size: var(--fs-13);
+ text-align: start;
+}
+.fm-gen[hidden], .fm-gen [hidden] { display: none; }
+
+.fm-gen-head, .fm-gen-err, .fm-gen > .fm-gen-acts, .fm-gen > .fm-gen-line { flex: none; }
+.fm-gen-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; }
+.fm-gen > .fm-gen-acts { margin-block-start: var(--space-2); }
+.fm-gen > .fm-gen-line { margin-block-end: 0; }
+.fm-gen-head { display: flex; align-items: center; gap: var(--space-2); margin-block-end: var(--space-2); font-weight: 600; }
+.fm-gen-icon { line-height: 0; color: var(--text-secondary); }
+.fm-gen-title { flex: 1; }
+.fm-gen-x { border: 0; background: transparent; color: var(--text-muted); cursor: pointer; padding: calc(var(--space-1) / 2); border-radius: var(--radius-sm); line-height: 0; }
+.fm-gen-x:hover { color: var(--text-primary); background: var(--surface-raised); }
+
+.fm-gen-err { margin: 0 0 var(--space-2); padding: var(--space-2); border: 1px solid var(--danger-fill); border-radius: var(--radius-md); color: var(--danger-text); font-size: var(--fs-12); line-height: 1.4; overflow-wrap: anywhere; min-height: calc(1.4em * 2 + var(--space-2) * 2); }
+.fm-gen-err.is-empty { visibility: hidden; }
+
+.fm-gen-server { display: flex; align-items: center; gap: var(--space-2); margin-block-end: var(--space-2); font-size: var(--fs-12); color: var(--text-secondary); }
+.fm-gen-servertext { flex: 1; min-width: 0; overflow-wrap: anywhere; }
+.fm-gen-dot { flex: none; width: var(--space-2); height: var(--space-2); border-radius: 50%; background: var(--text-muted); }
+.fm-gen-dot.is-up { background: var(--ok); }
+.fm-gen-dot.is-down { background: var(--danger-text); }
+
+.fm-gen-row { display: grid; grid-template-columns: calc(var(--space-8) * 2 + var(--space-5)) minmax(0, 1fr); gap: var(--space-2); align-items: center; margin-block-end: var(--space-2); }
+.fm-gen-lab { color: var(--text-secondary); font-size: var(--fs-12); overflow-wrap: anywhere; }
+.fm-gen-row .cv-input { width: 100%; min-width: 0; }
+.fm-gen-row input[type="checkbox"] { justify-self: start; accent-color: var(--accent-color); }
+.fm-gen-split { display: flex; gap: var(--space-2); min-width: 0; }
+.fm-gen-split .cv-input { flex: 1; min-width: 0; }
+.fm-gen-text { resize: vertical; }
+
+.fm-gen-line { min-height: 1.4em; margin-block-end: var(--space-2); color: var(--text-secondary); font-size: var(--fs-12); font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
+.fm-gen-line.is-warn { color: var(--warn); }
+.fm-gen-ready { margin: 0 0 var(--space-2); padding-inline-start: var(--space-4); color: var(--warn); font-size: var(--fs-12); line-height: 1.4; overflow-wrap: anywhere; min-height: calc(1.4em * 3); }
+.fm-gen-ready.is-empty { visibility: hidden; }
+.fm-gen-form { min-height: calc(var(--ctl-sm) * 6 + var(--space-2) * 6); }
+
+/* the bar and the preview keep their boxes while idle so a run moves nothing */
+.fm-gen-prog { position: relative; height: var(--space-2); margin-block: var(--space-2); border-radius: var(--radius-sm); background: var(--bg-input); border: 1px solid var(--border-light); overflow: hidden; }
+.fm-gen-prog.is-idle { visibility: hidden; }
+.fm-gen-fill { position: absolute; inset-block: 0; inset-inline-start: 0; width: calc(var(--p, 0) * 100%); background: var(--accent-color); transition: width var(--dur-fast) linear; }
+.fm-gen-prog.is-busy .fm-gen-fill { width: 30%; transition: none; animation: fm-gen-sweep 1.2s ease-in-out infinite; }
+@keyframes fm-gen-sweep { from { inset-inline-start: -30%; } to { inset-inline-start: 100%; } }
+@media (prefers-reduced-motion: reduce) { .fm-gen-prog.is-busy .fm-gen-fill { animation: none; width: 100%; opacity: 0.5; } }
+
+.fm-gen-preview { aspect-ratio: 16 / 9; margin-block-end: var(--space-2); border-radius: var(--radius-md); background: var(--surface-field); border: 1px solid var(--border-light); overflow: hidden; }
+.fm-gen-preview img { display: block; width: 100%; height: 100%; object-fit: contain; }
+.fm-gen-preview.is-empty img { visibility: hidden; }
+
+.fm-gen-acts { display: flex; flex-wrap: wrap; gap: var(--space-2); margin-block-end: var(--space-2); }
+.fm-gen-go { flex: 1; }
+.fm-gen-link { padding: 0; margin: 0; border: 0; background: transparent; color: var(--text-muted); font: inherit; font-size: var(--fs-12); cursor: pointer; white-space: nowrap; }
+.fm-gen-link:hover { color: var(--text-primary); text-decoration: underline; }
+
+.fm-comfy-split { display: flex; gap: var(--space-2); min-width: 0; }
+.fm-comfy-split .cv-input { flex: 1; min-width: 0; }
+.fm-comfy-split .cv-btn { flex: none; }
+.fm-comfy-line { min-height: 1.4em; color: var(--text-secondary); font-size: var(--fs-12); overflow-wrap: anywhere; }
diff --git a/frontend/src/styles/panels.css b/frontend/src/styles/panels.css
index 8c5b8c0..daaa051 100644
--- a/frontend/src/styles/panels.css
+++ b/frontend/src/styles/panels.css
@@ -503,11 +503,22 @@
.cv-menu-item:hover:not(:disabled), .cv-menu-item.is-focus:not(:disabled), .cv-menu-item:focus:not(:disabled) { background: color-mix(in srgb, var(--text-primary) 10%, transparent); color: var(--text-primary); outline: none; }
.cv-menu-item:hover:not(:disabled) .cv-menu-keys, .cv-menu-keys { color: color-mix(in srgb, var(--text-primary) 45%, transparent); font-size: 13px; letter-spacing: 0.04em; }
.cv-menu-sep { height: 1px; margin: 6px 10px; background: color-mix(in srgb, var(--text-primary) 12%, transparent); }
-/* A menu never runs past the window: it hangs from under the menu bar, scrolls inside itself (arrow keys focus a row, which scrolls into view),
- and one of sixteen or more rows takes the compact row height. */
-.cv-menu { max-height: calc(100vh - var(--ctl-xl) - var(--space-2)); scroll-padding-block: var(--space-1); }
-.cv-menu:has(> .cv-menu-item:nth-child(n + 16)) .cv-menu-item { height: var(--ctl-sm); font-size: var(--fs-13); }
-.cv-menu:has(> .cv-menu-item:nth-child(n + 16)) .cv-menu-sep { margin-block: var(--space-1); }
+/* A menu never runs past the window: it hangs from under the menu bar, its rows scroll inside the card (arrow keys focus a row, which scrolls into view),
+ and one of sixteen or more rows takes the compact row height. menu.ts sets the real cap inline (three quarters of the window). While rows
+ remain below, the bottom rows fade into the card's glass (a mask on the list, so no colour is painted on the glass) under a small pill;
+ both go at the last row (160ms) and come back when the rows are scrolled up (490ms). */
+.cv-menu { max-height: calc(100vh - var(--ctl-xl) - var(--space-2)); }
+.cv-menu:has(> .cv-menu-list > .cv-menu-item:nth-child(n + 16)) .cv-menu-item { height: var(--ctl-sm); font-size: var(--fs-13); }
+.cv-menu:has(> .cv-menu-list > .cv-menu-item:nth-child(n + 16)) .cv-menu-sep { margin-block: var(--space-1); }
+@property --menu-more { syntax: ''; inherits: false; initial-value: 0; }
+.cv-menu:not([hidden]), .fm-pop.fm-pop-scroll:not([hidden]) { display: flex; flex-direction: column; overflow: hidden; }
+.cv-menu-list { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; scroll-padding-block: var(--space-1); --menu-more: 0; -webkit-mask-image: linear-gradient(to bottom, #000 calc(100% - min(88px, 40%)), rgb(0 0 0 / calc(1 - var(--menu-more))) calc(100% - min(22px, 10%))); mask-image: linear-gradient(to bottom, #000 calc(100% - min(88px, 40%)), rgb(0 0 0 / calc(1 - var(--menu-more))) calc(100% - min(22px, 10%))); transition: --menu-more 160ms ease-out; }
+.cv-menu-more { position: absolute; left: 50%; bottom: 6px; width: 56px; height: 12px; margin-left: -28px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--glass-border); border-radius: 999px; background: var(--glass-bg); color: var(--text-secondary); pointer-events: none; opacity: 0; transition: opacity 160ms ease-out; }
+.cv-menu-more svg { width: 12px; height: 8px; }
+.has-more > .cv-menu-list { --menu-more: 1; scroll-padding-block-end: min(88px, 40%); transition-duration: 490ms; }
+.has-more > .cv-menu-more { opacity: 1; transition-duration: 490ms; }
+.no-fade > .cv-menu-list, .no-fade > .cv-menu-more { transition: none; }
+@media (prefers-reduced-motion: reduce) { .cv-menu-list, .cv-menu-more { transition: none; } }
.cv-brush-tip { cursor: grab; touch-action: none; }
.cv-brush-tip:active { cursor: grabbing; }
diff --git a/frontend/src/ui/comfy-settings.ts b/frontend/src/ui/comfy-settings.ts
new file mode 100644
index 0000000..d93275f
--- /dev/null
+++ b/frontend/src/ui/comfy-settings.ts
@@ -0,0 +1,106 @@
+import { ApiError } from '../io/api';
+import { comfyApi, type ComfyStatus } from '../io/comfy-api';
+import { el, setDisabled, setText, setValue } from './dom';
+import { onLanguage, t } from './i18n';
+import '../styles/comfy-generate.css';
+
+export const COMFY_SECTION = 'Comfy';
+export const COMFY_CHANGED = 'fm:comfy-changed';
+
+const message = (e: unknown): string => (e instanceof ApiError || e instanceof Error ? e.message : String(e));
+
+export class ComfySettingsPage {
+ readonly groups: HTMLElement[];
+ private st: ComfyStatus | null = null;
+ private readonly url = el('');
+ private readonly test = el('');
+ private readonly result = el('');
+ private readonly key = el('');
+ private readonly saveKey = el('');
+ private readonly forget = el('');
+ private readonly keyLine = el('');
+
+ constructor(group: (label: string, ...content: HTMLElement[]) => HTMLElement, note: (text: string) => HTMLElement) {
+ const urlRow = el('');
+ urlRow.append(this.url, this.test);
+ const keyRow = el('');
+ keyRow.append(this.key, this.saveKey, this.forget);
+ this.groups = [
+ group('Comfy server', urlRow, this.result, note(t('Generate sends pictures to this Comfy server and brings the results back. It needs Comfy-FormBridge-Suite in the server\'s custom_nodes folder.'))),
+ group('Sign-in key', keyRow, this.keyLine, note(t('Only for a server that asks for one. It is kept in this computer\'s keychain and sent only to that server.'))),
+ ];
+ this.test.addEventListener('click', () => void this.save());
+ this.url.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); void this.save(); } });
+ this.key.addEventListener('input', () => this.paint());
+ this.saveKey.addEventListener('click', () => void this.storeKey());
+ this.forget.addEventListener('click', () => void this.clearKey());
+ this.paint();
+ onLanguage(() => this.paint());
+ }
+
+ show(): void { void this.load(); }
+
+ private async load(): Promise {
+ try { this.take(await comfyApi.status()); } catch (e) { setText(this.result, message(e)); }
+ }
+
+ private take(st: ComfyStatus): void {
+ this.st = st;
+ setValue(this.url, st.url);
+ const pack = st.pack ? `${st.pack.name} ${st.pack.version}` : '';
+ let line: string;
+ if (st.installed && st.supported !== false) line = t('Connected') + (st.comfy ? ` · Comfy ${st.comfy.version}` : '') + (pack ? ` · ${pack}` : '') + (st.device ? ` · ${st.device.name}` : '');
+ else if (st.message) line = st.message;
+ else if (st.installed && st.comfy) line = t('This Comfy server is too old. It needs version {v} or newer.').replace('{v}', st.comfy.minimum);
+ else line = t('Comfy-FormBridge-Suite is not installed. Put it in the custom_nodes folder of your Comfy server and restart it.');
+ setText(this.result, line);
+ this.paint();
+ }
+
+ private async save(): Promise {
+ const url = this.url.value.trim();
+ if (!url) return;
+ setDisabled(this.test, true);
+ setText(this.result, t('Checking...'));
+ try {
+ this.take(await comfyApi.setServer(url));
+ document.dispatchEvent(new CustomEvent(COMFY_CHANGED));
+ } catch (e) {
+ setText(this.result, message(e));
+ } finally {
+ setDisabled(this.test, false);
+ }
+ }
+
+ private async storeKey(): Promise {
+ const key = this.key.value.trim();
+ if (!key) return;
+ try {
+ this.take(await comfyApi.setKey(key));
+ this.key.value = '';
+ document.dispatchEvent(new CustomEvent(COMFY_CHANGED));
+ } catch (e) { setText(this.keyLine, message(e)); }
+ this.paint();
+ }
+
+ private async clearKey(): Promise {
+ try {
+ this.take(await comfyApi.clearKey());
+ document.dispatchEvent(new CustomEvent(COMFY_CHANGED));
+ } catch (e) { setText(this.keyLine, message(e)); }
+ }
+
+ private paint(): void {
+ setText(this.test, t('Test'));
+ setText(this.saveKey, t('Save key'));
+ setText(this.forget, t('Forget key'));
+ this.url.setAttribute('aria-label', t('Comfy server address'));
+ this.key.setAttribute('aria-label', t('Sign-in key'));
+ const has = !!this.st?.hasKey;
+ const canStore = this.st?.canStore ?? true;
+ setText(this.keyLine, !canStore ? t('This computer has no keychain FormMorpheus can use, so a key cannot be kept here.') : has ? t('A key is saved.') : t('No key saved.'));
+ setDisabled(this.key, !canStore);
+ setDisabled(this.saveKey, !canStore || !this.key.value.trim());
+ setDisabled(this.forget, !has);
+ }
+}
diff --git a/frontend/src/ui/content-menu.ts b/frontend/src/ui/content-menu.ts
index ce20da4..b94fb76 100644
--- a/frontend/src/ui/content-menu.ts
+++ b/frontend/src/ui/content-menu.ts
@@ -83,7 +83,7 @@ export class ContentMenu {
private openX = 0;
private openY = 0;
constructor(private readonly engine: Engine) {
- this.pop = new Popover('fm-cm', 264);
+ this.pop = new Popover('fm-cm', 264, true);
const body = this.pop.body;
const tileRow = el('');
diff --git a/frontend/src/ui/generate-panel.ts b/frontend/src/ui/generate-panel.ts
new file mode 100644
index 0000000..324af87
--- /dev/null
+++ b/frontend/src/ui/generate-panel.ts
@@ -0,0 +1,398 @@
+import type { Engine } from '../engine/engine';
+import { ApiError } from '../io/api';
+import { comfyApi, readinessWords, type ComfyJob, type ComfyJobState, type ComfyReadiness, type ComfySlot, type ComfyStatus, type ComfyWorkflow } from '../io/comfy-api';
+import { MODES, MODE_LABEL, MODE_WORKFLOW, collect, follow, land, missing, plainSlot, randomSeed, sources, type ComfyDeps, type ComfyMode } from '../app/features/comfy-generate';
+import { el, patchList, q, setClass, setDisabled, setHidden, setStyleVar, setText } from './dom';
+import { enhanceSelect } from './dropdown';
+import { icon } from './icons';
+import { t } from './i18n';
+import { barFloor } from './menu';
+import '../styles/comfy-generate.css';
+
+const STORE = 'formmorpheus.comfygen';
+
+const isAbort = (e: unknown): boolean => e instanceof DOMException && e.name === 'AbortError';
+const message = (e: unknown): string => (e instanceof ApiError || e instanceof Error ? e.message : String(e));
+
+interface SlotForm { box: HTMLElement; read: () => Record; seeds: string[]; prompt: () => string }
+
+export class GeneratePanel {
+ private readonly root: HTMLElement;
+ private readonly err: HTMLElement;
+ private readonly server: HTMLElement;
+ private readonly mode: HTMLSelectElement;
+ private readonly source: HTMLElement;
+ private readonly ready: HTMLElement;
+ private readonly form: HTMLElement;
+ private readonly prog: HTMLElement;
+ private readonly step: HTMLElement;
+ private readonly preview: HTMLImageElement;
+ private readonly go: HTMLButtonElement;
+ private readonly retry: HTMLButtonElement;
+ private readonly cancel: HTMLButtonElement;
+ private readonly status: HTMLElement;
+ private readonly forms = new Map();
+ private readonly readiness = new Map();
+ private st: ComfyStatus | null = null;
+ private workflows: ComfyWorkflow[] | null = null;
+ private loading = false;
+ private picked: ComfyMode;
+ private ctrl: AbortController | null = null;
+ private job: ComfyJob | null = null;
+ private last: { mode: ComfyMode } | null = null;
+ private open = false;
+ private returnFocus: HTMLElement | null = null;
+
+ constructor(private readonly deps: ComfyDeps, private readonly openSettings: () => void, private readonly onText: (text: string) => void = () => undefined) {
+ const stored = (() => { try { return localStorage.getItem(STORE) ?? ''; } catch { return ''; } })();
+ this.picked = (MODES as string[]).includes(stored) ? (stored as ComfyMode) : 'animate';
+ const row = (label: string, control: HTMLElement): HTMLElement => {
+ const r = el('