diff --git a/.agents/skills/formrec-harness/SKILL.md b/.agents/skills/formrec-harness/SKILL.md
index 355382f..4262403 100644
--- a/.agents/skills/formrec-harness/SKILL.md
+++ b/.agents/skills/formrec-harness/SKILL.md
@@ -40,6 +40,22 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr
- `formrec_open_in_formcut` hands the recording to FormCut, the Form family video editor, when the person wants a full timeline edit (FormCut must be running).
- `formrec_delete` removes a recording and its folder for good: only when the person asked, and with `confirm` repeating the id.
+## The window: everything a person can do
+
+When a FormREC window is open, its whole command registry is yours: `formrec_window_commands` lists every command (id, label, `args` as `name?: type`, risk; `query` filters, `id` describes one in full with allowed values and whether it can run now), and `formrec_window_command_run` runs one with `args`, exactly as if the person chose it, and the window shows it at once.
+
+- Pages: `nav.go` with `page` (home, library and its tabs, studio, screen, camera, audio, the studio layouts, shared, notifications, insights, recently-watched, meetings, ask, tour, demo, recording, edit, annotate, clips, interactive, playlist; the last ones take `id`). `window.state` says what is open.
+- Menus: every File, View and Help row by its menu id (`file.new-audio`, `view.library`, `help.demo-self-tour`...).
+- The studio: `studio.configure` (layout, target, quality), `studio.start`, `studio.pause`, `studio.resume`, `studio.stop`, `studio.restart`, `studio.cancel`, `studio.rewind`, `studio.camera`, `studio.screenshot`, `studio.notes`; drawing with `annotate.*`; the camera bubble with `effects.*`.
+- The player: `player.play`, `player.pause`, `player.seek` (`ms`, `play?`), `player.panel` (chapters, transcripts, engage-comments, engage-tasks, voiceover, keycast, autozoom...).
+- A recording's menus: `recording.action` with `id` and `action` (share, edit, duplicate, documents-rename, documents-export, interactive, clips, library-trash...).
+- Preferences: `settings.open` (section), `prefs.get`, `prefs.set` (theme, defaultMode, countdownS, limitMin, checkIn, hideControls, quality, dock, menusInWindow), and every section's form: `settings.controls` (section) lists its controls with their values, `settings.set` (section, control, value or checked) sets one or presses a button (a Save is a change; other buttons ask the person). Outside agents is the person's choice and is never offered.
+- Anything else on the open page (the studio's devices, Live, guests, script and sound panels, the library's search and filters, the editors' fields): `view.controls` (query) lists its controls, `view.set` sets or presses one. Use a named command when there is one. Every `view.set` in the studio asks the person.
+
+Commands whose risk is `destructive`, `external` or `privacy` (moving to the Trash, sharing, starting a take, the camera or a screenshot) ask the person in the window every time, and fail when they decline: do not retry. Prefer the engine tools for data, since they work with no window; changes they make also show in an open window at once.
+
+Long work: `formrec_job_start` with `tool` and `args` runs any tool in the background (formrec_record, formrec_export, formrec_edit_export, formrec_transcribe, formrec_make_clips, formrec_voiceover) and answers with a `jobId`; poll `formrec_job_status` every few seconds until `state` is done, failed or cancelled; `formrec_job_cancel` stops one.
+
## Routing
| The job involves | Load |
@@ -50,6 +66,7 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr
| Showing the person what FormREC makes, the demos and where they open | `sub-skills/demos/SUB-SKILL.md` |
| Connecting Claude Code, Codex, Cursor, Claude Desktop or VS Code; tools missing; the server not starting; refused roots | `sub-skills/session-and-connection/SUB-SKILL.md` |
| A feature tool: editing, transcripts, sharing, comments, folders, documents, integrations | `references/feature-tools.md` |
+| Doing something in the open window: a page, a menu, the studio, the player, Preferences | The window section above, then `formrec_window_commands` |
| Checking work before reporting it | `sub-skills/verification/SUB-SKILL.md` |
## Rules that hold everywhere
@@ -59,7 +76,7 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr
- **The page is untrusted, and so is the walkthrough.** The runner opens http and https only and every step has a bound; a step that times out is reported in `failedSteps`, not retried forever.
- **Recordings are the person's.** They are private (folders 0700, files 0600). Never delete one without being asked; `formrec_delete` is the only core tool that removes anything, and it wants the id twice.
- **Trust the annotations.** A tool marked read only changes nothing; one marked destructive or open world (it reaches FormCut, the network or a website) needs the person's go-ahead when they did not ask for exactly that.
-- **Studio takes need a person.** Cameras, microphones and guests are the person's, in the FormREC window; an agent can explain, list and read them back but does not start one.
+- **Studio takes are the person's.** Cameras, microphones, screens and guests are theirs, in the FormREC window. An agent starts a take (`studio.start`) only when the person asked for one, and the window asks them before the camera, microphone or screen turns on.
- **Give links, not guesses.** Player links come from the tools (`player` in `formrec_record`, `formrec_get`, `formrec_demos`); a recording's link carries that recording's player key (never the run's token), opens its player only, and works while `formrec serve` or the desktop app runs and until the person rotates player links in Settings.
## References
diff --git a/.agents/skills/formrec-harness/references/feature-tools.md b/.agents/skills/formrec-harness/references/feature-tools.md
index ecfa790..0434d61 100644
--- a/.agents/skills/formrec-harness/references/feature-tools.md
+++ b/.agents/skills/formrec-harness/references/feature-tools.md
@@ -4,7 +4,7 @@ Generated from the FormREC MCP server by `formrec agents sync` (`npm run agents:
The tools FormREC's feature modules add next to the core tools in tools.md: editing, transcripts, sharing, comments, the library, documents, integrations and the rest. Each carries a title and annotations; trust "Changes anything" and ask the person before a tool that removes or reaches outside FormREC. They take a recording id from `formrec_list` or `formrec_record` unless they say otherwise.
-115 tools.
+120 tools.
## Tools
@@ -56,6 +56,9 @@ The tools FormREC's feature modules add next to the core tools in tools.md: edit
| `formrec_integrations` | List integrations | no | Which services are connected (Slack, Teams, Jira, Linear, GitHub, GitLab, form.md, Confluence, calendar), their non-secret settings and last test, the outgoing webhooks, the twelve integration apps (Slack, Google, Salesforce, HubSpot, Zendesk, Intercom, GitHub, GitLab, Jira, Linear, form.md, Figma): for each its install folder and INSTALL.md, whether it is configured, which fields are set, the public address it uses (relay or tunnel) and whether that address answers, and the recorder SDK apps (id, mode, allowed origins, key ids, guest limits, and the relay script address). Secrets are never shown. Read this before posting or creating issues. |
| `formrec_interactive_demo` | Build or read an interactive demo | yes | Make a click-through demo from a recording that has steps (a walkthrough): one picture per step, a hotspot over the element the step pointed at, the step's words as the callout, Back and Next, and an end card with the recording's call to action when it has one. Builds it when there is none (or when build is true; the owner's edits are kept), otherwise reads it. A person's recording with chapters gets its recorded clicks as hotspots, and one with only clicks gets a step per click. Returns the steps (id, title, text, hidden, hotspot in the picture's pixels), the viewers' insights (views, where they stop, hotspot against Next, call to action, completion; shown steps only), the languages it can be translated into and the demo links on the share servers (/i/[shareId], and ?embed=1 for an embed), which exist once the recording is shared. Needs FFmpeg. |
| `formrec_interactive_export` | Export an interactive demo as a zip | yes | Write the recording's demo as a zip with demo.html and its pictures. The page works offline, from a file or any static host. Hidden steps are left out. Build the demo first with formrec_interactive_demo. |
+| `formrec_job_cancel` | Cancel a background job | yes | Stop a running job, as cancelling the tool call would (formrec_record saves nothing when cancelled). A job that already ended is left as it is. |
+| `formrec_job_start` | Start a tool as a background job | yes | Run any other FormREC tool (for example formrec_record, formrec_export, formrec_edit_export, formrec_transcribe, formrec_make_clips, formrec_voiceover, formrec_walkthrough_rerecord) in the background and answer at once with a jobId. Poll formrec_job_status every few seconds until state is done, failed or cancelled; the result is then exactly what the tool would have answered. Use it for anything that can take more than a few seconds. |
+| `formrec_job_status` | Poll a background job | no | A job's state (running, done, failed, cancelled), its latest progress, and once it ended the tool's result or error. Without jobId: every job of this server, newest first, without results. |
| `formrec_keycast` | Keystrokes on screen | yes | Show or change the keys drawn over a recording: whether they are on, where (bottom-left, bottom-center, bottom-right, top-left, top-center, top-right), the size (1 to 5), how long each shows (400 to 6000 ms), and whether share pages show them (share). A walkthrough records its presses (Ctrl+K, Enter, Tab x3) and counts of typed characters (never the characters, nothing for a secret); a tab recorded with the browser extension with keystrokes on brings shortcuts and named keys. The reply has counts and the choices, not the keys themselves. Give only the recording to read. |
| `formrec_library_archive` | Archive or unarchive recordings | yes | Archived recordings leave the library's Videos tab for its Archive tab; unarchive returns them where they were. Nothing is deleted. |
| `formrec_library_export` | Export recordings to a folder | yes | Copy recordings (all of them when ids is omitted) with every file and a formrec-library.json manifest of their tags, folders and spaces into a new `formrec-export-
-
+
@@ -129,7 +129,7 @@ What FormREC does that Loom's own pages do not offer, each checked against Loom'
- **Keystrokes on screen.** Shortcuts and named keys over the picture, from walkthroughs and from tab recordings in the extension when you turn it on; never the characters typed, never a secret.
- **Scene chapters.** For recordings with little speech, chapters from where the screen changes, named from the page or the words at the top of the frame.
- **Voice-over.** A natural built-in voice, Kokoro (54 voices, Heart by default), set up once from Settings, Voice and offline after that, as in FormCut and FormMorpheus. Each chapter's text becomes a line at the chapter's time, made, heard and made again one line at a time in the player's Voice-over tab, and mixed into exports and share links with the recording lowered under it.
-- **Agents.** 124 MCP tools, among them object tools that read up to 20 recordings and meetings in one call, and a prompt for an agent sent to Jira as a work item assigned to an agent. Since 0.9.0 you choose what a remote agent reaching this computer through the bridge is offered: everything, no destructive tools or read only, plus tool names to withhold; the bridge never hands out the app's own token.
+- **Agents.** 129 MCP tools, among them the window's whole command registry (an agent can do anything you can do in the window, asking you before it deletes, publishes or turns on a camera, microphone or screen), background jobs for long work, object tools that read up to 20 recordings and meetings in one call, and a prompt for an agent sent to Jira as a work item assigned to an agent. Since 0.9.0 you choose what a remote agent reaching this computer through the bridge is offered: everything, no destructive tools or read only, plus tool names to withhold; the bridge never hands out the app's own token.
- **Variants.** A walkthrough that declares `{{variables}}` is recorded once for each row of a JSON or CSV file (`formrec variants`, the Variants panel, an MCP tool): one recording per set of values, each linked to its source, with the same redaction and no variable allowed to carry a secret. It is not Loom's personalised video, whose spoken variables Loom is deprecating; nothing here is spoken.
- **Linux.** On X11 the desktop app records the display you pick directly, with no system picker. 0.9.0 built the Linux app and ran that feed inside it; the same run found that the Linux app's window cannot yet use a microphone or camera, which is open.
@@ -163,15 +163,17 @@ To build it yourself: `setup/build_release --target ` (`aarch64-apple-da
## Demos
-Three demos ship inside FormREC, each a finished recording. Open them from Home (Demos), the sidebar (Learn) or Help > Demo. A demo opens in the player under a Demo bar with a way back to Home; it is never added to your library and cannot be deleted or sent to FormCut from there.
+Five demos ship inside FormREC, each a finished recording. Open them from Home (Demos), the sidebar (Learn) or Help > Demo. A demo opens in the player under a Demo bar with a way back to Home; it is never added to your library and cannot be deleted or sent to FormCut from there.
| Demo | What it shows |
|---|---|
+| [A FormVis walkthrough, narrated](demos/formvis-walkthrough/README.md) | FormVis's video as the screen track, a narrator in a camera bubble, the narration and the soundtrack on their own tracks, a chapter per tool, captions and viewer comments. |
+| [A FormPortal walkthrough, narrated](demos/formportal-walkthrough/README.md) | The same for FormPortal, the installer for the Form apps: install, update and go back, files with history, agents. |
| [A tour of FormREC](demos/self-tour/README.md) | A walkthrough an agent made with no person: Home, the library, the studio and the player, each chapter linked to the code that draws it. |
| [A studio take with a guest](demos/studio-guest/README.md) | A host and a guest on the same network, every camera and microphone on its own track at its offset. |
| [A podcast episode with two speakers](demos/podcast-episode/README.md) | A short show with a host and a guest: each voice and camera on its own track, captions naming who speaks, a chapter per part. |
-`npm run build && node scripts/make-demos.mjs` remakes the first two from nothing (generated pictures and voices, a real take in two browsers, the self tour recorded headless), and `node scripts/make-podcast-demo.mjs` remakes the podcast with ffmpeg alone; see each demo's CREDITS.md.
+`npm run build && node scripts/make-demos.mjs` remakes the first two from nothing (generated pictures and voices, a real take in two browsers, the self tour recorded headless), `node scripts/make-podcast-demo.mjs` remakes the podcast with ffmpeg alone, and `node scripts/make-walkthrough-demos.mjs` remakes the FormVis and FormPortal walkthroughs from their videos on formai.tools; see each demo's CREDITS.md. [demos/README.md](demos/README.md) says where to drop the full walkthrough videos so the next build uses them.
### Templates
@@ -246,6 +248,15 @@ Core tools, each with a title, annotations (read only, destructive, open world)
| `formrec_open_in_formcut` | hands a recording to FormCut as a new project |
| `formrec_demos` | the demos that ship with FormREC, with a player link for each |
+**Everything you can do, an agent can do.** While a FormREC window is open, an agent sees its whole command registry (every page of the sidebar, every menu row, the studio's start, pause and stop, the drawing tools, the player, each action of a recording's menu, every control of Preferences and of the open page) and runs any of it as if you had clicked. What it changes with any tool shows in the window at once: the library, Home and the open player are drawn again, the player keeping its moment. Moving a recording to the Trash, sharing or publishing, and turning on the camera, microphone or screen ask you in the window every time, whichever agent asks and whatever you chose for it before; an agent can never change Outside agents itself. These tools are offered by the app, `formrec mcp` and `formrec mcp --http`, not by the relay:
+
+| Tool | What it does |
+|---|---|
+| `formrec_window_commands` | every command of the open window, with its arguments and risk: pages, menus, the studio, the player, a recording's menus, Preferences, any control of the page |
+| `formrec_window_command_run` | runs one in the window, which shows it at once; deleting, publishing and the camera, microphone or screen ask you there every time |
+| `formrec_job_start` | runs any other tool in the background (record, export, transcribe, clips) and answers with a job id |
+| `formrec_job_status`, `formrec_job_cancel` | a job's state, progress and result; stop it |
+
The feature modules add their own tools (editing, transcripts, sharing, comments, folders and more), listed from the live server in `.claude/skills/formrec-harness/references/feature-tools.md`. Two skills ship in `.claude/skills/` (mirrored in `.agents/skills/`, each with `EVALS.json`): `formrec-harness` for using FormREC through its tools and `formrec-skillset` for changing FormREC's code. This checkout carries `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and `.cursor/rules/formrec.mdc`.
## Public links
diff --git a/demos/README.md b/demos/README.md
new file mode 100644
index 0000000..5cc5b97
--- /dev/null
+++ b/demos/README.md
@@ -0,0 +1,47 @@
+# Demos
+
+Each folder is a finished recording that ships with FormREC and opens in the player under a Demo bar, from Home (Demos), the sidebar (Learn) or Help > Demo; a demo is never added to the library. The media are committed here, at the sizes the player needs (a screen track is 1280x720 VP9, a camera 640x360, a microphone Opus), and `scripts/copy-web.mjs` copies every folder but `sources/` into the build.
+
+| Folder | Made by |
+|---|---|
+| `formvis-walkthrough/` | `scripts/make-walkthrough-demos.mjs` from FormVis's video on formai.tools |
+| `formportal-walkthrough/` | `scripts/make-walkthrough-demos.mjs` from FormPortal's video on formai.tools |
+| `self-tour/`, `studio-guest/` | `scripts/make-demos.mjs` |
+| `podcast-episode/` | `scripts/make-podcast-demo.mjs` |
+
+A demo is listed in `web/src/demos.ts`, `src/mcp/demos.ts`, `src/server/http.ts` `DEMO_IDS`, the sidebar's Learn rows in `web/index.html` and `DEMO_LABELS` in `web/src/menus.ts`; `tests/demos.test.ts` holds them together.
+
+## The FormVis and FormPortal walkthroughs
+
+`npm run build && node scripts/make-walkthrough-demos.mjs` remakes both (`formvis-walkthrough` or `formportal-walkthrough` as an argument makes one). It needs ffmpeg with libvpx and libopus, and the built-in voice (Kokoro, set up in Settings, Voice, or by the script on first run).
+
+By default the picture is the app's promo from formai.tools, downloaded once from media.formai.studio into `demos/sources/.promo/` and accepted only with the SHA-256 pinned in the script. It is narrated by the built-in voice (Juno, `af_heart`), a line per chapter, with the promo's own sound on a quieter track of its own.
+
+### Using the real walkthrough videos
+
+Drop the walkthrough video at the path below and run the script again. The next build uses it in place of the promo, with no code change.
+
+| Demo | Drop-in path | Video |
+|---|---|---|
+| `formvis-walkthrough` | `demos/sources/formvis-walkthrough.mp4` | https://www.youtube.com/watch?v=sKF7V_SQoF0 (FormVis Walkthrough: Relight, Fill, Pen Brush, Liquify, Timeline, Agents) |
+| `formportal-walkthrough` | `demos/sources/formportal-walkthrough.mp4` | https://www.youtube.com/watch?v=dlIOEhXRbxE (FormPortal Walkthrough: Installer for Form Apps) |
+
+`demos/sources/` is in `.gitignore`: the source videos are never committed, only the demo made from them.
+
+On your own Mac, from the checkout:
+
+```sh
+yt-dlp -f "bv*[height<=1080][ext=mp4]+ba[ext=m4a]" --merge-output-format mp4 -o demos/sources/formvis-walkthrough.mp4 https://www.youtube.com/watch?v=sKF7V_SQoF0
+yt-dlp -f "bv*[height<=1080][ext=mp4]+ba[ext=m4a]" --merge-output-format mp4 -o demos/sources/formportal-walkthrough.mp4 https://www.youtube.com/watch?v=dlIOEhXRbxE
+npm run build && node scripts/make-walkthrough-demos.mjs
+```
+
+A video you already have is one command: `node scripts/make-walkthrough-demos.mjs --use formvis-walkthrough=/path/to/video.mp4` copies it to the drop-in path and makes that demo.
+
+With a dropped-in video:
+- Its own sound is the narration track, and no voice-over is spoken over it.
+- Chapters come from `demos/sources/.json` (`{ "chapters": [{ "id": "relight", "title": "Relight", "at": 12.5 }] }`, seconds), else from the chapters in yt-dlp's info file `demos/sources/.info.json`, else from the walkthrough's named sections spread over the video and moved to the nearest cut. Add `--write-info-json` to the yt-dlp line to get the info file. Without a sidecar or chapters in the info file, check the times.
+- Captions come from `demos/sources/.en.vtt` or `.vtt` when present. Add `--write-subs --write-auto-subs --sub-langs en --sub-format vtt` to the yt-dlp line to get them. Without captions the Transcript tab says the demo has none.
+- The comments keep their chapter when the chapter has the same id.
+
+Commit the remade `demos//` files and check the sizes: the screen track grows with the video's length.
diff --git a/demos/formportal-walkthrough/CREDITS.md b/demos/formportal-walkthrough/CREDITS.md
new file mode 100644
index 0000000..60ff59b
--- /dev/null
+++ b/demos/formportal-walkthrough/CREDITS.md
@@ -0,0 +1,10 @@
+# Credits
+
+Made by `scripts/make-walkthrough-demos.mjs` for this repository.
+
+- The picture and the soundtrack are from FormPortal's promo video, the owner's own, published on formai.tools (https://formai.tools/formportal/walkthrough/, file https://media.formai.studio/media/formportal/promo/dbcdc2bf680b.1080p.mp4, SHA-256 dbcdc2bf680bd38a8228f2da4c54519a5cbe74528a5863780226e1c083a98975). It was scaled to 1280x720 and re-encoded as VP9 without sound. The sound was set to -27 LUFS on a track of its own. The full walkthrough on YouTube (dlIOEhXRbxE) is the same owner's and replaces the promo when dropped in (demos/README.md). FormPortal's video, its pictures and its music are Copyright 2026 NodeAgentc, Inc., from formai.tools, used with the owner's permission; they are not covered by Apache-2.0.
+- The narration is synthesised with Kokoro-82M (Apache-2.0, model files v1.0 from the kokoro-onnx release `model-files-v1.1`) through FormREC's built-in voice (`af_heart`, speed 1). It is evened by a gentle compressor and set to -16 LUFS integrated. Only the spoken audio is shipped; not the model, kokoro-onnx (MIT) or the eSpeak NG it phonemises with (GPL), which ran as a separate program.
+- The narrator's camera is generated with FFmpeg (`color`, `drawbox`, `drawtext` with DejaVu Sans Bold, not shipped, and `showwaves` drawn from the narration). "Juno", "Theo" and "Ada" are invented; the comments are written for this demo.
+- The narration, chapters and comments are written for this demo from what the video shows.
+
+The files FormREC wrote (`recording.json`, the captions, chapters and comments, the narration and the camera) are Apache-2.0, as the rest of the repository.
diff --git a/demos/formportal-walkthrough/README.md b/demos/formportal-walkthrough/README.md
new file mode 100644
index 0000000..b950a9d
--- /dev/null
+++ b/demos/formportal-walkthrough/README.md
@@ -0,0 +1,27 @@
+# Demo: a FormPortal walkthrough, narrated
+
+FormPortal, the installer for the Form apps, recorded as a FormREC screen take with a narrator. The screen track is FormPortal's own video from formai.tools. Juno narrates each section from a camera bubble over the picture. Her voice and the video's soundtrack are separate microphone tracks.
+
+Chapters follow what the video shows, at the seconds where each section's heading appears:
+
+- Meet FormPortal
+- Install every app (a signed catalogue, SHA-256 checked before unpacking)
+- Update, then go back
+- Files with history
+- Built for agents
+- Free and open source
+
+Captions carry every narrated sentence, and the Transcript tab lists them. The Comments tab holds a few viewer comments at their moments; their times seek the player.
+
+Open it in FormREC from Home (Demos), the sidebar (Learn) or Help > Demo: A FormPortal Walkthrough. It opens in the player under a Demo bar and is never added to your library.
+
+Files:
+- `recording.json`
+- `track-screen.webm` (1280x720 VP9, picture only)
+- `track-host-camera.webm` (the narrator's camera)
+- `track-host-mic.webm` (the narration)
+- `track-soundtrack-mic.webm` (the video's own sound)
+- `captions.vtt`, `chapters.vtt`, `comments.json`
+- `poster.png` (a frame of the screen)
+
+Remake it with `npm run build && node scripts/make-walkthrough-demos.mjs formportal-walkthrough`. To build it from the full walkthrough video in place of the promo, see [demos/README.md](../README.md).
diff --git a/demos/formportal-walkthrough/captions.vtt b/demos/formportal-walkthrough/captions.vtt
new file mode 100644
index 0000000..df32f20
--- /dev/null
+++ b/demos/formportal-walkthrough/captions.vtt
@@ -0,0 +1,41 @@
+WEBVTT
+
+1
+00:00:00.600 --> 00:00:04.065
+This is FormPortal, one installer for every Form app.
+
+2
+00:00:05.500 --> 00:00:08.136
+Install every app from one signed catalogue.
+
+3
+00:00:08.386 --> 00:00:14.006
+Each download is checked against its SHA-256 before it is unpacked.
+
+4
+00:00:15.500 --> 00:00:17.037
+Update, then go back.
+
+5
+00:00:17.287 --> 00:00:19.742
+Every update keeps the version it replaced.
+
+6
+00:00:23.500 --> 00:00:24.881
+Files with history.
+
+7
+00:00:25.131 --> 00:00:27.939
+A version each time you save, up to twenty.
+
+8
+00:00:31.500 --> 00:00:33.358
+And it is built for agents.
+
+9
+00:00:33.608 --> 00:00:39.090
+Claude Code, Codex and Cursor can install, update and manage the whole family for you.
+
+10
+00:00:44.500 --> 00:00:47.008
+FormPortal is free and open source.
diff --git a/demos/formportal-walkthrough/chapters.vtt b/demos/formportal-walkthrough/chapters.vtt
new file mode 100644
index 0000000..680857b
--- /dev/null
+++ b/demos/formportal-walkthrough/chapters.vtt
@@ -0,0 +1,25 @@
+WEBVTT
+
+intro
+00:00:00.000 --> 00:00:05.000
+Meet FormPortal
+
+install
+00:00:05.000 --> 00:00:15.000
+Install every app
+
+update
+00:00:15.000 --> 00:00:23.000
+Update, then go back
+
+files
+00:00:23.000 --> 00:00:31.000
+Files with history
+
+agents
+00:00:31.000 --> 00:00:44.000
+Built for agents
+
+outro
+00:00:44.000 --> 00:00:48.700
+Free and open source
diff --git a/demos/formportal-walkthrough/comments.json b/demos/formportal-walkthrough/comments.json
new file mode 100644
index 0000000..89bb128
--- /dev/null
+++ b/demos/formportal-walkthrough/comments.json
@@ -0,0 +1,22 @@
+{
+ "comments": [
+ {
+ "id": "c1",
+ "atMs": 10000,
+ "who": "Ada",
+ "text": "Checked against the SHA-256 before it unpacks. Good, that is what I look for in an installer."
+ },
+ {
+ "id": "c2",
+ "atMs": 18000,
+ "who": "Theo",
+ "text": "Going back to the version an update replaced, in one click, is the part I needed."
+ },
+ {
+ "id": "c3",
+ "atMs": 36000,
+ "who": "Ada",
+ "text": "I asked Claude Code to update the whole family and it did, one app at a time."
+ }
+ ]
+}
diff --git a/demos/formportal-walkthrough/poster.png b/demos/formportal-walkthrough/poster.png
new file mode 100644
index 0000000..60d6c2f
Binary files /dev/null and b/demos/formportal-walkthrough/poster.png differ
diff --git a/demos/formportal-walkthrough/recording.json b/demos/formportal-walkthrough/recording.json
new file mode 100644
index 0000000..eda0471
--- /dev/null
+++ b/demos/formportal-walkthrough/recording.json
@@ -0,0 +1,112 @@
+{
+ "formrec": 1,
+ "id": "formportal-walkthrough",
+ "title": "A FormPortal walkthrough, narrated",
+ "summary": "FormPortal, the one installer for the Form apps, shown section by section with a narrator: installing from a signed catalogue, updating and going back, files with history, and agents managing the family. The screen, the narrator's camera, the narration and the video's own sound are each their own track.",
+ "source": "person",
+ "createdAt": "2026-12-03T12:00:00.000Z",
+ "mode": "screen",
+ "video": "track-screen.webm",
+ "tracks": [
+ {
+ "id": "screen",
+ "kind": "screen",
+ "person": "FormPortal promo",
+ "host": true,
+ "file": "track-screen.webm",
+ "offsetMs": 0,
+ "durationMs": 48700,
+ "bytes": 1505566,
+ "complete": true
+ },
+ {
+ "id": "host-camera",
+ "kind": "camera",
+ "person": "Juno",
+ "host": true,
+ "file": "track-host-camera.webm",
+ "offsetMs": 0,
+ "durationMs": 48734,
+ "bytes": 513954,
+ "complete": true
+ },
+ {
+ "id": "host-mic",
+ "kind": "mic",
+ "person": "Juno",
+ "host": true,
+ "file": "track-host-mic.webm",
+ "offsetMs": 0,
+ "durationMs": 48708,
+ "bytes": 245873,
+ "complete": true
+ },
+ {
+ "id": "soundtrack-mic",
+ "kind": "mic",
+ "person": "FormPortal promo soundtrack",
+ "host": false,
+ "file": "track-soundtrack-mic.webm",
+ "offsetMs": 0,
+ "durationMs": 48603,
+ "bytes": 344371,
+ "complete": true
+ }
+ ],
+ "pauses": [],
+ "durationMs": 48700,
+ "viewport": {
+ "width": 1280,
+ "height": 720
+ },
+ "chapters": [
+ {
+ "stepId": "intro",
+ "title": "Meet FormPortal",
+ "say": "This is FormPortal, one installer for every Form app.",
+ "startMs": 0,
+ "endMs": 5000,
+ "code": []
+ },
+ {
+ "stepId": "install",
+ "title": "Install every app",
+ "say": "Install every app from one signed catalogue. Each download is checked against its SHA-256 before it is unpacked.",
+ "startMs": 5000,
+ "endMs": 15000,
+ "code": []
+ },
+ {
+ "stepId": "update",
+ "title": "Update, then go back",
+ "say": "Update, then go back. Every update keeps the version it replaced.",
+ "startMs": 15000,
+ "endMs": 23000,
+ "code": []
+ },
+ {
+ "stepId": "files",
+ "title": "Files with history",
+ "say": "Files with history. A version each time you save, up to twenty.",
+ "startMs": 23000,
+ "endMs": 31000,
+ "code": []
+ },
+ {
+ "stepId": "agents",
+ "title": "Built for agents",
+ "say": "And it is built for agents. Claude Code, Codex and Cursor can install, update and manage the whole family for you.",
+ "startMs": 31000,
+ "endMs": 44000,
+ "code": []
+ },
+ {
+ "stepId": "outro",
+ "title": "Free and open source",
+ "say": "FormPortal is free and open source.",
+ "startMs": 44000,
+ "endMs": 48700,
+ "code": []
+ }
+ ]
+}
diff --git a/demos/formportal-walkthrough/track-host-camera.webm b/demos/formportal-walkthrough/track-host-camera.webm
new file mode 100644
index 0000000..cde5cac
Binary files /dev/null and b/demos/formportal-walkthrough/track-host-camera.webm differ
diff --git a/demos/formportal-walkthrough/track-host-mic.webm b/demos/formportal-walkthrough/track-host-mic.webm
new file mode 100644
index 0000000..349cab8
Binary files /dev/null and b/demos/formportal-walkthrough/track-host-mic.webm differ
diff --git a/demos/formportal-walkthrough/track-screen.webm b/demos/formportal-walkthrough/track-screen.webm
new file mode 100644
index 0000000..408e3da
Binary files /dev/null and b/demos/formportal-walkthrough/track-screen.webm differ
diff --git a/demos/formportal-walkthrough/track-soundtrack-mic.webm b/demos/formportal-walkthrough/track-soundtrack-mic.webm
new file mode 100644
index 0000000..bfa45fc
Binary files /dev/null and b/demos/formportal-walkthrough/track-soundtrack-mic.webm differ
diff --git a/demos/formvis-walkthrough/CREDITS.md b/demos/formvis-walkthrough/CREDITS.md
new file mode 100644
index 0000000..58417a3
--- /dev/null
+++ b/demos/formvis-walkthrough/CREDITS.md
@@ -0,0 +1,10 @@
+# Credits
+
+Made by `scripts/make-walkthrough-demos.mjs` for this repository.
+
+- The picture and the soundtrack are from FormVis's promo video, the owner's own, published on formai.tools (https://formai.tools/formvis/walkthrough/, file https://media.formai.studio/media/formvis/promo/f12a8d835de1.1080p.mp4, SHA-256 f12a8d835de1dc6bf1f69c84eccc99f93a0d0f0e894a9d74c879c7d87385e74d). It was scaled to 1280x720 and re-encoded as VP9 without sound. The sound was set to -27 LUFS on a track of its own. The full walkthrough on YouTube (sKF7V_SQoF0) is the same owner's and replaces the promo when dropped in (demos/README.md). FormVis's video, its pictures and its music are Copyright 2026 NodeAgentc, Inc., from formai.tools, used with the owner's permission; they are not covered by Apache-2.0.
+- The narration is synthesised with Kokoro-82M (Apache-2.0, model files v1.0 from the kokoro-onnx release `model-files-v1.1`) through FormREC's built-in voice (`af_heart`, speed 1). It is evened by a gentle compressor and set to -16 LUFS integrated. Only the spoken audio is shipped; not the model, kokoro-onnx (MIT) or the eSpeak NG it phonemises with (GPL), which ran as a separate program.
+- The narrator's camera is generated with FFmpeg (`color`, `drawbox`, `drawtext` with DejaVu Sans Bold, not shipped, and `showwaves` drawn from the narration). "Juno", "Theo" and "Ada" are invented; the comments are written for this demo.
+- The narration, chapters and comments are written for this demo from what the video shows.
+
+The files FormREC wrote (`recording.json`, the captions, chapters and comments, the narration and the camera) are Apache-2.0, as the rest of the repository.
diff --git a/demos/formvis-walkthrough/README.md b/demos/formvis-walkthrough/README.md
new file mode 100644
index 0000000..f8d5042
--- /dev/null
+++ b/demos/formvis-walkthrough/README.md
@@ -0,0 +1,27 @@
+# Demo: a FormVis walkthrough, narrated
+
+FormVis, the Form family's image editor, recorded as a FormREC screen take with a narrator. The screen track is FormVis's own video from formai.tools. Juno narrates each tool from a camera bubble over the picture. Her voice and the video's soundtrack are separate microphone tracks, so either can be muted, cut or exported on its own.
+
+Chapters follow what the video shows, at the seconds where each section's heading appears:
+
+- Meet FormVis
+- Generative Fill
+- Relight
+- Remove background
+- Your agent finishes it (Claude Code, Codex and Cursor over MCP)
+- Free and open source
+
+Captions carry every narrated sentence, and the Transcript tab lists them. The Comments tab holds a few viewer comments at their moments; their times seek the player.
+
+Open it in FormREC from Home (Demos), the sidebar (Learn) or Help > Demo: A FormVis Walkthrough. It opens in the player under a Demo bar and is never added to your library.
+
+Files:
+- `recording.json`
+- `track-screen.webm` (1280x720 VP9, picture only)
+- `track-host-camera.webm` (the narrator's camera)
+- `track-host-mic.webm` (the narration)
+- `track-soundtrack-mic.webm` (the video's own sound)
+- `captions.vtt`, `chapters.vtt`, `comments.json`
+- `poster.png` (a frame of the screen)
+
+Remake it with `npm run build && node scripts/make-walkthrough-demos.mjs formvis-walkthrough`. To build it from the full walkthrough video in place of the promo, see [demos/README.md](../README.md).
diff --git a/demos/formvis-walkthrough/captions.vtt b/demos/formvis-walkthrough/captions.vtt
new file mode 100644
index 0000000..25ce22c
--- /dev/null
+++ b/demos/formvis-walkthrough/captions.vtt
@@ -0,0 +1,37 @@
+WEBVTT
+
+1
+00:00:00.600 --> 00:00:04.014
+This is FormVis, the image editor of the Form family.
+
+2
+00:00:05.500 --> 00:00:06.827
+Generative Fill.
+
+3
+00:00:07.077 --> 00:00:12.398
+Draw around what is missing, describe it, and it lands as a new layer with its own mask.
+
+4
+00:00:17.500 --> 00:00:19.401
+Relight lights the picture again.
+
+5
+00:00:19.651 --> 00:00:23.204
+Drag the lights and the wet street follows, all on your own computer.
+
+6
+00:00:29.500 --> 00:00:35.184
+Remove background finds the subject on your computer, and keeps it as a mask you can switch off.
+
+7
+00:00:38.500 --> 00:00:40.199
+And your agent can finish it.
+
+8
+00:00:40.449 --> 00:00:47.798
+Claude Code, Codex and Cursor work in FormVis over MCP. You allow it, and each change is one undo step.
+
+9
+00:00:51.500 --> 00:00:53.753
+FormVis is free and open source.
diff --git a/demos/formvis-walkthrough/chapters.vtt b/demos/formvis-walkthrough/chapters.vtt
new file mode 100644
index 0000000..11ffc3e
--- /dev/null
+++ b/demos/formvis-walkthrough/chapters.vtt
@@ -0,0 +1,25 @@
+WEBVTT
+
+intro
+00:00:00.000 --> 00:00:05.000
+Meet FormVis
+
+fill
+00:00:05.000 --> 00:00:17.000
+Generative Fill
+
+relight
+00:00:17.000 --> 00:00:29.000
+Relight
+
+remove-background
+00:00:29.000 --> 00:00:38.000
+Remove background
+
+agents
+00:00:38.000 --> 00:00:51.000
+Your agent finishes it
+
+outro
+00:00:51.000 --> 00:00:56.000
+Free and open source
diff --git a/demos/formvis-walkthrough/comments.json b/demos/formvis-walkthrough/comments.json
new file mode 100644
index 0000000..172664f
--- /dev/null
+++ b/demos/formvis-walkthrough/comments.json
@@ -0,0 +1,28 @@
+{
+ "comments": [
+ {
+ "id": "c1",
+ "atMs": 9000,
+ "who": "Theo",
+ "text": "The fill lands as its own layer with a mask, so the photo underneath is never touched. That is the part I wanted."
+ },
+ {
+ "id": "c2",
+ "atMs": 22000,
+ "who": "Ada",
+ "text": "Relight runs on this computer? No upload at all?"
+ },
+ {
+ "id": "c3",
+ "atMs": 24000,
+ "who": "Juno",
+ "text": "None. Relight runs on your computer, and the picture never leaves it."
+ },
+ {
+ "id": "c4",
+ "atMs": 44000,
+ "who": "Theo",
+ "text": "One undo step per agent change makes it safe to let Claude Code try things."
+ }
+ ]
+}
diff --git a/demos/formvis-walkthrough/poster.png b/demos/formvis-walkthrough/poster.png
new file mode 100644
index 0000000..1335b2e
Binary files /dev/null and b/demos/formvis-walkthrough/poster.png differ
diff --git a/demos/formvis-walkthrough/recording.json b/demos/formvis-walkthrough/recording.json
new file mode 100644
index 0000000..fcac745
--- /dev/null
+++ b/demos/formvis-walkthrough/recording.json
@@ -0,0 +1,112 @@
+{
+ "formrec": 1,
+ "id": "formvis-walkthrough",
+ "title": "A FormVis walkthrough, narrated",
+ "summary": "FormVis, the Form family's image editor, shown section by section with a narrator: Generative Fill, Relight, Remove background and an agent finishing the picture over MCP. The screen, the narrator's camera, the narration and the video's own sound are each their own track.",
+ "source": "person",
+ "createdAt": "2026-12-03T12:00:00.000Z",
+ "mode": "screen",
+ "video": "track-screen.webm",
+ "tracks": [
+ {
+ "id": "screen",
+ "kind": "screen",
+ "person": "FormVis promo",
+ "host": true,
+ "file": "track-screen.webm",
+ "offsetMs": 0,
+ "durationMs": 56000,
+ "bytes": 1457138,
+ "complete": true
+ },
+ {
+ "id": "host-camera",
+ "kind": "camera",
+ "person": "Juno",
+ "host": true,
+ "file": "track-host-camera.webm",
+ "offsetMs": 0,
+ "durationMs": 56000,
+ "bytes": 633236,
+ "complete": true
+ },
+ {
+ "id": "host-mic",
+ "kind": "mic",
+ "person": "Juno",
+ "host": true,
+ "file": "track-host-mic.webm",
+ "offsetMs": 0,
+ "durationMs": 56008,
+ "bytes": 276150,
+ "complete": true
+ },
+ {
+ "id": "soundtrack-mic",
+ "kind": "mic",
+ "person": "FormVis promo soundtrack",
+ "host": false,
+ "file": "track-soundtrack-mic.webm",
+ "offsetMs": 0,
+ "durationMs": 56008,
+ "bytes": 407657,
+ "complete": true
+ }
+ ],
+ "pauses": [],
+ "durationMs": 56000,
+ "viewport": {
+ "width": 1280,
+ "height": 720
+ },
+ "chapters": [
+ {
+ "stepId": "intro",
+ "title": "Meet FormVis",
+ "say": "This is FormVis, the image editor of the Form family.",
+ "startMs": 0,
+ "endMs": 5000,
+ "code": []
+ },
+ {
+ "stepId": "fill",
+ "title": "Generative Fill",
+ "say": "Generative Fill. Draw around what is missing, describe it, and it lands as a new layer with its own mask.",
+ "startMs": 5000,
+ "endMs": 17000,
+ "code": []
+ },
+ {
+ "stepId": "relight",
+ "title": "Relight",
+ "say": "Relight lights the picture again. Drag the lights and the wet street follows, all on your own computer.",
+ "startMs": 17000,
+ "endMs": 29000,
+ "code": []
+ },
+ {
+ "stepId": "remove-background",
+ "title": "Remove background",
+ "say": "Remove background finds the subject on your computer, and keeps it as a mask you can switch off.",
+ "startMs": 29000,
+ "endMs": 38000,
+ "code": []
+ },
+ {
+ "stepId": "agents",
+ "title": "Your agent finishes it",
+ "say": "And your agent can finish it. Claude Code, Codex and Cursor work in FormVis over MCP. You allow it, and each change is one undo step.",
+ "startMs": 38000,
+ "endMs": 51000,
+ "code": []
+ },
+ {
+ "stepId": "outro",
+ "title": "Free and open source",
+ "say": "FormVis is free and open source.",
+ "startMs": 51000,
+ "endMs": 56000,
+ "code": []
+ }
+ ]
+}
diff --git a/demos/formvis-walkthrough/track-host-camera.webm b/demos/formvis-walkthrough/track-host-camera.webm
new file mode 100644
index 0000000..825fd97
Binary files /dev/null and b/demos/formvis-walkthrough/track-host-camera.webm differ
diff --git a/demos/formvis-walkthrough/track-host-mic.webm b/demos/formvis-walkthrough/track-host-mic.webm
new file mode 100644
index 0000000..429c5f8
Binary files /dev/null and b/demos/formvis-walkthrough/track-host-mic.webm differ
diff --git a/demos/formvis-walkthrough/track-screen.webm b/demos/formvis-walkthrough/track-screen.webm
new file mode 100644
index 0000000..6832a5e
Binary files /dev/null and b/demos/formvis-walkthrough/track-screen.webm differ
diff --git a/demos/formvis-walkthrough/track-soundtrack-mic.webm b/demos/formvis-walkthrough/track-soundtrack-mic.webm
new file mode 100644
index 0000000..d4183cf
Binary files /dev/null and b/demos/formvis-walkthrough/track-soundtrack-mic.webm differ
diff --git a/docs/api.md b/docs/api.md
index 0e5b583..7f1a94b 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -860,6 +860,17 @@ From `src/server/player-link.ts`:
| GET | `/api/player/:id?key=` | the recording (what the player draws) |
| GET | `/api/player/:id/:file?key=` | its video, tracks, captions and chapters (the core media names, server/http.ts MEDIA) |
+From `src/window/bridge.ts`:
+
+| method | path | what it does |
+|---|---|---|
+| GET | `/api/window/stream` | the window's end: events hello, call (list, describe, run) and changed; the app's window takes the same events on `/api/mcp/consent/stream?window=1`, so it holds one long request |
+| POST | `/api/window/result` | { callId, ok, value?, error? } the window's answer to a call |
+| POST | `/api/window/focus` | { windowId } this window answers the next calls |
+| GET | `/api/window/commands?query=&id=` | the window's commands (id, label, args, risk), or one described in full |
+| POST | `/api/window/run` | { id, args?, agent? } runs one; destructive, external and privacy ones ask the person first |
+| POST | `/api/window/changed` | { ids, tool } an agent in another process (`formrec mcp`) changed these recordings |
+
## The guest listener
HTTPS on the local network, on only while guests are turned on in the studio. A guest pairs with a six-digit code
diff --git a/extension/manifest.json b/extension/manifest.json
index 750ac3e..7dd12ea 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -2,7 +2,7 @@
"manifest_version": 3,
"name": "FormREC",
"short_name": "FormREC",
- "version": "0.11.0",
+ "version": "0.12.0",
"description": "Record this tab, your screen, your camera or your voice into FormREC on this computer, and play FormREC links where you work.",
"minimum_chrome_version": "116",
"icons": { "16": "icons/icon-16.png", "32": "icons/icon-32.png", "48": "icons/icon-48.png", "128": "icons/icon-128.png" },
diff --git a/package-lock.json b/package-lock.json
index cf4166c..4c1565e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "formrec",
- "version": "0.11.0",
+ "version": "0.12.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "formrec",
- "version": "0.11.0",
+ "version": "0.12.0",
"license": "Apache-2.0",
"dependencies": {
"@lydell/node-pty": "1.2.0-beta.18",
diff --git a/package.json b/package.json
index c480ca9..0dcec19 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "formrec",
- "version": "0.11.0",
+ "version": "0.12.0",
"description": "Recording for walkthroughs, podcasts, corporate messages and live feeds, by a person or by an agent over MCP; walkthrough steps link to the UI and the code behind them.",
"license": "Apache-2.0",
"type": "module",
diff --git a/scripts/copy-web.mjs b/scripts/copy-web.mjs
index 2277101..e512e41 100644
--- a/scripts/copy-web.mjs
+++ b/scripts/copy-web.mjs
@@ -25,4 +25,5 @@ await cp('web/vendor', 'dist/web/vendor', { recursive: true })
// The official mark at the sizes the shell shows, and the favicon; the server serves only names on its fixed list.
await cp('web/brand', 'dist/web/brand', { recursive: true })
// The demos ship with the client: each demos// holds a finished recording, its poster, README and CREDITS.
-await cp('demos', 'dist/web/demos', { recursive: true, filter: (from) => !/\.md$/.test(from) })
+// demos/sources/ (the walkthrough videos make-walkthrough-demos.mjs reads, never committed) stays out.
+await cp('demos', 'dist/web/demos', { recursive: true, filter: (from) => !/\.md$/.test(from) && !/^demos[\\/]sources([\\/]|$)/.test(from) })
diff --git a/scripts/make-walkthrough-demos.mjs b/scripts/make-walkthrough-demos.mjs
new file mode 100644
index 0000000..e55b138
--- /dev/null
+++ b/scripts/make-walkthrough-demos.mjs
@@ -0,0 +1,293 @@
+// Makes the FormVis and FormPortal walkthrough demos in demos// with ffmpeg and the built-in Kokoro voice, no browser:
+// `npm run build && node scripts/make-walkthrough-demos.mjs [id ...]`. Each is a screen take as FormREC writes one: the
+// app's video as the screen track, a narrator's camera as the bubble, the narration and the video's own sound each on a
+// microphone track, captions, chapters at the sections the video shows, and a few viewer comments (comments.json).
+//
+// The picture comes from, in this order:
+// 1. demos/sources/.mp4, the owner's walkthrough video dropped in (see demos/README.md for the yt-dlp line);
+// chapters then come from demos/sources/.json ({ "chapters": [{ "id", "title", "at" }] }), else the chapters in
+// the yt-dlp info file demos/sources/.info.json, else the walkthrough's named sections spread over the video and
+// moved to the nearest cut; captions from demos/sources/.en.vtt or .vtt when present; the video's own
+// sound is the narration, so no voice-over is spoken over it.
+// 2. the app's promo from formai.tools (media.formai.studio), downloaded once into demos/sources/.promo/ and accepted
+// only with the SHA-256 pinned below; narrated with the built-in voice, a line per chapter.
+// `--use =` copies a file into the drop-in path first: one command to swap the promo for the real video.
+import { execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { existsSync, readFileSync } from 'node:fs'
+import { copyFile, mkdir, mkdtemp, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+
+const REPO = path.resolve(import.meta.dirname, '..')
+const SOURCES = path.join(REPO, 'demos', 'sources')
+const ff = (...args) => execFileSync('ffmpeg', ['-v', 'error', '-y', ...args], { stdio: 'inherit' })
+const seconds = (file) => Number(execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file]).toString().trim())
+const hasAudio = (file) => execFileSync('ffprobe', ['-v', 'error', '-select_streams', 'a', '-show_entries', 'stream=index', '-of', 'csv=p=0', file]).toString().trim() !== ''
+const font = execFileSync('fc-match', ['-f', '%{file}', 'DejaVu Sans:bold']).toString().trim()
+const NARRATOR = { name: 'Juno', voice: 'af_heart' }
+
+const DEMOS = {
+ 'formvis-walkthrough': {
+ app: 'FormVis',
+ title: 'A FormVis walkthrough, narrated',
+ summary: 'FormVis, the Form family\'s image editor, shown section by section with a narrator: Generative Fill, Relight, Remove background and an agent finishing the picture over MCP. The screen, the narrator\'s camera, the narration and the video\'s own sound are each their own track.',
+ youtube: 'https://www.youtube.com/watch?v=sKF7V_SQoF0',
+ page: 'https://formai.tools/formvis/walkthrough/',
+ promo: { url: 'https://media.formai.studio/media/formvis/promo/f12a8d835de1.1080p.mp4', sha256: 'f12a8d835de1dc6bf1f69c84eccc99f93a0d0f0e894a9d74c879c7d87385e74d' },
+ base: '0x17131f', tint: '0xa78bfa', posterAt: 22,
+ // Measured on the promo's frames: each section's heading is typed in at these seconds.
+ promoChapters: [
+ { id: 'intro', title: 'Meet FormVis', at: 0, say: ['This is FormVis, the image editor of the Form family.'] },
+ { id: 'fill', title: 'Generative Fill', at: 5, say: ['Generative Fill.', 'Draw around what is missing, describe it, and it lands as a new layer with its own mask.'] },
+ { id: 'relight', title: 'Relight', at: 17, say: ['Relight lights the picture again.', 'Drag the lights and the wet street follows, all on your own computer.'] },
+ { id: 'remove-background', title: 'Remove background', at: 29, say: ['Remove background finds the subject on your computer, and keeps it as a mask you can switch off.'] },
+ { id: 'agents', title: 'Your agent finishes it', at: 38, say: ['And your agent can finish it.', 'Claude Code, Codex and Cursor work in FormVis over MCP. You allow it, and each change is one undo step.'] },
+ { id: 'outro', title: 'Free and open source', at: 51, say: ['FormVis is free and open source.'] },
+ ],
+ // The full walkthrough's sections, as its YouTube title names them.
+ sections: [
+ { id: 'relight', title: 'Relight' }, { id: 'fill', title: 'Generative Fill' }, { id: 'pen-brush', title: 'Pen Brush' },
+ { id: 'liquify', title: 'Liquify' }, { id: 'timeline', title: 'Timeline' }, { id: 'agents', title: 'Agents' },
+ ],
+ comments: [
+ { chapter: 'fill', after: 4, who: 'Theo', text: 'The fill lands as its own layer with a mask, so the photo underneath is never touched. That is the part I wanted.' },
+ { chapter: 'relight', after: 5, who: 'Ada', text: 'Relight runs on this computer? No upload at all?' },
+ { chapter: 'relight', after: 7, who: 'Juno', text: 'None. Relight runs on your computer, and the picture never leaves it.' },
+ { chapter: 'agents', after: 6, who: 'Theo', text: 'One undo step per agent change makes it safe to let Claude Code try things.' },
+ ],
+ },
+ 'formportal-walkthrough': {
+ app: 'FormPortal',
+ title: 'A FormPortal walkthrough, narrated',
+ summary: 'FormPortal, the one installer for the Form apps, shown section by section with a narrator: installing from a signed catalogue, updating and going back, files with history, and agents managing the family. The screen, the narrator\'s camera, the narration and the video\'s own sound are each their own track.',
+ youtube: 'https://www.youtube.com/watch?v=dlIOEhXRbxE',
+ page: 'https://formai.tools/formportal/walkthrough/',
+ promo: { url: 'https://media.formai.studio/media/formportal/promo/dbcdc2bf680b.1080p.mp4', sha256: 'dbcdc2bf680bd38a8228f2da4c54519a5cbe74528a5863780226e1c083a98975' },
+ base: '0x12141f', tint: '0x818cf8', posterAt: 9,
+ promoChapters: [
+ { id: 'intro', title: 'Meet FormPortal', at: 0, say: ['This is FormPortal, one installer for every Form app.'] },
+ { id: 'install', title: 'Install every app', at: 5, say: ['Install every app from one signed catalogue.', 'Each download is checked against its SHA-256 before it is unpacked.'] },
+ { id: 'update', title: 'Update, then go back', at: 15, say: ['Update, then go back.', 'Every update keeps the version it replaced.'] },
+ { id: 'files', title: 'Files with history', at: 23, say: ['Files with history.', 'A version each time you save, up to twenty.'] },
+ { id: 'agents', title: 'Built for agents', at: 31, say: ['And it is built for agents.', 'Claude Code, Codex and Cursor can install, update and manage the whole family for you.'] },
+ { id: 'outro', title: 'Free and open source', at: 44, say: ['FormPortal is free and open source.'] },
+ ],
+ sections: [
+ { id: 'install', title: 'Install every app' }, { id: 'update', title: 'Update, then go back' },
+ { id: 'files', title: 'Files with history' }, { id: 'agents', title: 'Built for agents' },
+ ],
+ comments: [
+ { chapter: 'install', after: 5, who: 'Ada', text: 'Checked against the SHA-256 before it unpacks. Good, that is what I look for in an installer.' },
+ { chapter: 'update', after: 3, who: 'Theo', text: 'Going back to the version an update replaced, in one click, is the part I needed.' },
+ { chapter: 'agents', after: 5, who: 'Ada', text: 'I asked Claude Code to update the whole family and it did, one app at a time.' },
+ ],
+ },
+}
+
+// --use =: copy the owner's video into the drop-in path, then build that demo.
+const args = process.argv.slice(2)
+const wanted = []
+for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--use') {
+ const [id, file] = (args[++i] ?? '').split(/=(.*)/s)
+ if (!DEMOS[id] || !file || !existsSync(file)) throw new Error(`--use needs =, with id one of ${Object.keys(DEMOS).join(', ')}`)
+ await mkdir(SOURCES, { recursive: true })
+ await copyFile(file, path.join(SOURCES, `${id}.mp4`))
+ console.log(`${file} -> demos/sources/${id}.mp4`)
+ wanted.push(id)
+ } else if (DEMOS[args[i]]) wanted.push(args[i])
+ else throw new Error(`Unknown demo ${args[i]}: one of ${Object.keys(DEMOS).join(', ')}`)
+}
+
+const sha256 = (file) => createHash('sha256').update(readFileSync(file)).digest('hex')
+
+/** The promo, downloaded once and kept only when its SHA-256 matches. */
+async function promoFile(promo) {
+ const dir = path.join(SOURCES, '.promo')
+ const file = path.join(dir, `${promo.sha256.slice(0, 12)}.mp4`)
+ if (existsSync(file) && sha256(file) === promo.sha256) return file
+ await mkdir(dir, { recursive: true })
+ console.log(`Downloading ${promo.url}`)
+ const res = await fetch(promo.url)
+ if (!res.ok) throw new Error(`${promo.url}: ${res.status}`)
+ const part = `${file}.part`
+ await writeFile(part, Buffer.from(await res.arrayBuffer()))
+ if (sha256(part) !== promo.sha256) { await rm(part, { force: true }); throw new Error(`${promo.url} does not match its pinned SHA-256`) }
+ await rename(part, file)
+ return file
+}
+
+/** The cuts in a video (scene changes), for placing named sections when no times are given. */
+function cuts(file) {
+ const out = execFileSync('ffmpeg', ['-hide_banner', '-nostats', '-i', file, '-vf', "scale=320:-1,select='gt(scene,0.3)',showinfo", '-an', '-f', 'null', '-'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 << 20 }).toString()
+ return [...out.matchAll(/pts_time:([0-9.]+)/g)].map((m) => Number(m[1]))
+}
+
+/** Chapters for the owner's walkthrough: a sidecar, then the yt-dlp info file, then the named sections placed on cuts. */
+function walkthroughChapters(id, demo, total, video) {
+ const side = path.join(SOURCES, `${id}.json`)
+ if (existsSync(side)) return JSON.parse(readFileSync(side, 'utf8')).chapters.map((c, i) => ({ id: c.id ?? `part-${i + 1}`, title: c.title, at: Number(c.at) }))
+ const info = path.join(SOURCES, `${id}.info.json`)
+ const listed = existsSync(info) ? JSON.parse(readFileSync(info, 'utf8')).chapters ?? [] : []
+ if (listed.length > 0) {
+ // A chapter named like a known section keeps that section's id, so the comments land on it.
+ const used = new Set()
+ return listed.map((c, i) => {
+ const known = demo.sections.find((s) => !used.has(s.id) && c.title.toLowerCase().includes(s.title.toLowerCase().split(/[ ,]/)[0]))
+ if (known) used.add(known.id)
+ return { id: known ? known.id : `part-${i + 1}`, title: c.title, at: Number(c.start_time) }
+ })
+ }
+ console.warn(`${id}: no chapter times (demos/sources/${id}.json or .info.json); spreading the named sections over the video's cuts`)
+ const found = cuts(video)
+ const step = total / (demo.sections.length + 1)
+ return [{ id: 'intro', title: `Meet ${demo.app}`, at: 0 }, ...demo.sections.map((s, i) => {
+ const guess = step * (i + 1)
+ const near = found.reduce((best, t) => (Math.abs(t - guess) < Math.abs(best - guess) ? t : best), guess)
+ return { ...s, at: Math.abs(near - guess) < step / 3 ? near : guess }
+ })]
+}
+
+/** WebVTT cues from a file (YouTube's rolling auto captions are flattened: tags gone, repeats dropped). */
+function readVtt(file) {
+ const time = (s) => s.split(':').reduce((a, v) => a * 60 + Number(v), 0)
+ const cues = []
+ for (const block of readFileSync(file, 'utf8').replace(/\r/g, '').split(/\n\n+/)) {
+ const lines = block.split('\n')
+ const at = lines.findIndex((l) => l.includes('-->'))
+ if (at < 0) continue
+ const [a, b] = lines[at].split('-->').map((s) => time(s.trim().split(/\s/)[0]))
+ const text = lines.slice(at + 1).map((l) => l.replace(/<[^>]*>/g, '').trim()).filter(Boolean)
+ const last = cues.at(-1)?.text ?? ''
+ const fresh = text.filter((l) => !last.split('\n').includes(l)).join(' ').trim()
+ if (fresh && b - a > 0.05) cues.push({ start: a, end: b, text: fresh })
+ }
+ return cues
+}
+
+const stamp = (s) => {
+ const ms = Math.max(0, Math.round(s * 1000))
+ const p2 = (v, w = 2) => String(v).padStart(w, '0')
+ return `${p2(Math.floor(ms / 3600000))}:${p2(Math.floor(ms / 60000) % 60)}:${p2(Math.floor(ms / 1000) % 60)}.${p2(ms % 1000, 3)}`
+}
+
+async function make(id) {
+ const demo = DEMOS[id]
+ const OUT = path.join(REPO, 'demos', id)
+ const work = await mkdtemp(path.join(tmpdir(), `formrec-${id}-`))
+ const dropped = path.join(SOURCES, `${id}.mp4`)
+ const real = existsSync(dropped)
+ const video = real ? dropped : await promoFile(demo.promo)
+ const total = Math.floor(seconds(video) * 10) / 10
+ const label = real ? `${demo.app} walkthrough` : `${demo.app} promo`
+ console.log(`${id}: ${real ? 'the walkthrough dropped in at demos/sources' : 'the promo from formai.tools'}, ${total}s`)
+
+ // Chapters, and what is said in each.
+ const plan = (real ? walkthroughChapters(id, demo, total, video) : demo.promoChapters).filter((c) => c.at < total).sort((a, b) => a.at - b.at)
+ const chapters = plan.map((c, i) => ({ ...c, end: plan[i + 1]?.at ?? total }))
+
+ // The narration: Kokoro over the promo, a sentence per cue; the walkthrough's own voice otherwise.
+ const cues = []
+ const narration = path.join(work, 'narration.wav')
+ if (!real) {
+ const { normalise, speakTo } = await import('./demo-voice.mjs')
+ const lines = []
+ let n = 0
+ for (const c of chapters) {
+ let at = c.at + (c.at === 0 ? 0.6 : 0.5)
+ for (const sentence of c.say) {
+ const file = path.join(work, `line-${n++}.wav`)
+ const d = await speakTo(file, sentence, NARRATOR.voice)
+ if (at + d > c.end - 0.15) console.warn(`${id}: "${sentence}" runs ${(at + d - c.end).toFixed(2)}s past ${c.title}`)
+ lines.push({ file, at })
+ cues.push({ start: at, end: at + d, text: sentence, who: NARRATOR.name })
+ at += d + 0.25
+ }
+ }
+ const delays = lines.map((l, i) => `[${i}]adelay=${Math.round(l.at * 1000)}[d${i}]`).join(';')
+ const bed = path.join(work, 'bed.wav')
+ ff(...lines.flatMap((l) => ['-i', l.file]), '-filter_complex', `${delays};${lines.map((_, i) => `[d${i}]`).join('')}amix=inputs=${lines.length}:normalize=0,apad=whole_dur=${total}[a]`,
+ '-map', '[a]', '-t', String(total), '-ar', '48000', '-ac', '1', bed)
+ normalise(bed, narration)
+ } else {
+ const vtt = [`${id}.en.vtt`, `${id}.vtt`].map((f) => path.join(SOURCES, f)).find(existsSync)
+ if (vtt) cues.push(...readVtt(vtt).filter((c) => c.start < total))
+ }
+
+ await mkdir(OUT, { recursive: true })
+ for (const name of await readdir(OUT)) if (!name.endsWith('.md')) await rm(path.join(OUT, name), { recursive: true, force: true })
+
+ // The screen: 1280x720 VP9, picture only, as FormREC's screen tracks are.
+ ff('-i', video, '-an', '-vf', 'scale=1280:720:flags=lanczos,fps=30,format=yuv420p', '-t', String(total),
+ '-c:v', 'libvpx-vp9', '-crf', '38', '-b:v', '0', '-deadline', 'good', '-cpu-used', '4', '-row-mt', '1', '-g', '150', path.join(OUT, 'track-screen.webm'))
+
+ // The video's own sound on a microphone track: under the narration over the promo, the narration itself otherwise.
+ const own = hasAudio(video)
+ const soundtrack = path.join(work, 'soundtrack.wav')
+ if (own) {
+ const level = real ? -16 : -27
+ ff('-i', video, '-vn', '-t', String(total), '-af', `loudnorm=I=${level}:TP=-2:LRA=11,apad=whole_dur=${total}`, '-ar', '48000', '-ac', '2', soundtrack)
+ }
+
+ // The narrator's camera: a card with the narrator's name and the waveform of what is heard.
+ const heard = real ? (own ? soundtrack : null) : narration
+ const text = (t, size, y, colour) => `drawtext=fontfile=${font}:text='${t}':fontcolor=${colour}:fontsize=${size}:x=(w-tw)/2:y=${y}`
+ const who = real ? `${demo.app}` : NARRATOR.name
+ const role = real ? 'walkthrough' : `narrating . ${demo.app}`
+ const card = `[0]drawbox=x=0:y=0:w=640:h=360:color=${demo.tint}@0.16:t=fill,${text(who, 44, 70, 'white')},${text(role, 22, 130, '0xf7f7f7@0.75')}`
+ if (heard) {
+ ff('-f', 'lavfi', '-i', `color=c=${demo.base}:s=640x360:r=15:d=${total}`, '-i', heard, '-filter_complex',
+ `[1]aformat=channel_layouts=mono,showwaves=s=520x90:mode=cline:rate=15:colors=${demo.tint}[w];${card}[bg];[bg][w]overlay=60:220,format=yuv420p[v]`,
+ '-map', '[v]', '-t', String(total), '-c:v', 'libvpx-vp9', '-crf', '42', '-b:v', '0', '-deadline', 'good', '-cpu-used', '4', '-row-mt', '1', '-an', path.join(OUT, 'track-host-camera.webm'))
+ } else {
+ ff('-f', 'lavfi', '-i', `color=c=${demo.base}:s=640x360:r=15:d=${total}`, '-filter_complex', `${card},format=yuv420p[v]`,
+ '-map', '[v]', '-t', String(total), '-c:v', 'libvpx-vp9', '-crf', '42', '-b:v', '0', '-an', path.join(OUT, 'track-host-camera.webm'))
+ }
+ if (!real) ff('-i', narration, '-c:a', 'libopus', '-b:a', '48k', path.join(OUT, 'track-host-mic.webm'))
+ if (own) ff('-i', soundtrack, '-c:a', 'libopus', '-b:a', real ? '64k' : '56k', path.join(OUT, 'track-soundtrack-mic.webm'))
+
+ const tracks = []
+ const add = async (tid, kind, person, host, file) => {
+ if (!existsSync(path.join(OUT, file))) return
+ tracks.push({ id: tid, kind, person, host, file, offsetMs: 0, durationMs: Math.round(seconds(path.join(OUT, file)) * 1000), bytes: (await stat(path.join(OUT, file))).size, complete: true })
+ }
+ await add('screen', 'screen', label, true, 'track-screen.webm')
+ await add('host-camera', 'camera', real ? demo.app : NARRATOR.name, true, 'track-host-camera.webm')
+ await add('host-mic', 'mic', NARRATOR.name, true, 'track-host-mic.webm')
+ await add('soundtrack-mic', 'mic', real ? `${label} sound` : `${label} soundtrack`, false, 'track-soundtrack-mic.webm')
+
+ // A frame of the screen as the poster, 640x360 like the others, in 256 colours to stay small.
+ ff('-ss', String(Math.min(demo.posterAt, total - 1)), '-i', path.join(OUT, 'track-screen.webm'), '-frames:v', '1', '-filter_complex',
+ 'scale=640:360:flags=lanczos,split[a][b];[a]palettegen=max_colors=256[p];[b][p]paletteuse=dither=sierra2_4a', path.join(OUT, 'poster.png'))
+
+ const durationMs = Math.round(total * 1000)
+ const sayOf = (c) => (c.say ? c.say.join(' ') : cues.filter((q) => q.start >= c.at && q.start < c.end).map((q) => q.text).join(' ') || c.title)
+ await writeFile(path.join(OUT, 'captions.vtt'), `WEBVTT\n\n${cues.map((c, i) => `${i + 1}\n${stamp(c.start)} --> ${stamp(c.end)}\n${c.who ? `` : ''}${c.text}`).join('\n\n')}\n`)
+ await writeFile(path.join(OUT, 'chapters.vtt'), `WEBVTT\n\n${chapters.map((c) => `${c.id}\n${stamp(c.at)} --> ${stamp(c.end)}\n${c.title}`).join('\n\n')}\n`)
+ const comments = demo.comments.flatMap((m, i) => {
+ const c = chapters.find((x) => x.id === m.chapter)
+ return c ? [{ id: `c${i + 1}`, atMs: Math.round(Math.min(c.at + m.after, c.end - 0.5) * 1000), who: m.who, text: m.text }] : []
+ })
+ await writeFile(path.join(OUT, 'comments.json'), `${JSON.stringify({ comments }, null, 2)}\n`)
+ await writeFile(path.join(OUT, 'recording.json'), `${JSON.stringify({
+ formrec: 1,
+ id,
+ title: demo.title,
+ summary: demo.summary,
+ source: 'person',
+ createdAt: '2026-12-03T12:00:00.000Z',
+ mode: 'screen',
+ video: 'track-screen.webm',
+ tracks,
+ pauses: [],
+ durationMs,
+ viewport: { width: 1280, height: 720 },
+ chapters: chapters.map((c, i) => ({ stepId: c.id, title: c.title, say: sayOf(c), startMs: i === 0 ? 0 : Math.round(c.at * 1000), endMs: Math.min(durationMs, Math.round(c.end * 1000)), code: [] })),
+ }, null, 2)}\n`)
+ await rm(work, { recursive: true, force: true })
+ const bytes = (await Promise.all((await readdir(OUT)).map(async (f) => (await stat(path.join(OUT, f))).size))).reduce((a, b) => a + b, 0)
+ console.log(`demos/${id}: ${total}s, ${tracks.length} tracks, ${chapters.length} chapters, ${cues.length} captions, ${comments.length} comments, ${(bytes / 1048576).toFixed(2)} MB`)
+}
+
+for (const id of wanted.length > 0 ? [...new Set(wanted)] : Object.keys(DEMOS)) await make(id)
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 78d5adb..b6f2981 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -1071,7 +1071,7 @@ dependencies = [
[[package]]
name = "formrec-desktop"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"block2",
"objc2",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index a1bbaa6..146541c 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "formrec-desktop"
-version = "0.11.0"
+version = "0.12.0"
description = "FormREC desktop app: a window around formrec serve"
authors = ["NodeAgentc, Inc."]
license = "Apache-2.0"
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 24c4b5f..6f11ae1 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -2,7 +2,7 @@
"$schema": "https://schema.tauri.app/config/2",
"productName": "FormREC",
"mainBinaryName": "formrec-desktop",
- "version": "0.11.0",
+ "version": "0.12.0",
"identifier": "ai.nodemode.formrec",
"build": { "frontendDist": "splash" },
"app": {
diff --git a/src/HASHOUT_LOG.md b/src/HASHOUT_LOG.md
index 397e58c..63cc4ab 100644
--- a/src/HASHOUT_LOG.md
+++ b/src/HASHOUT_LOG.md
@@ -2,8 +2,8 @@
The server's decisions and why, newest last. Read before changing `src/`.
-Current build version: v0.11.0
-Last updated: 2026-12-01 · v0.11.0 the built-in voice (Kokoro), the voice-over and the MCP consent bridge
+Current build version: v0.12.0
+Last updated: 2026-12-03 · v0.12.0 finding agent programs on the login shell's PATH, the walkthrough demos and agent parity
## v0.2.0 · demo files and /api/info {#demo-files}
@@ -597,3 +597,55 @@ Checked under 4x CPU throttling in Chrome against a build served on port 5642, w
- the Preferences row followed a change made outside the window.
Layout shift was 0 throughout. Evidence: /home/claude/work/captures/formREC/0.11.0/consent-4x.json.
+
+## v0.12.0 · agent programs found on the login-shell PATH, as the family finds them {#agent-lookup}
+
+- refers-to: dock/lookup.ts (new: `find`, `folders`, `shellPath`, `askShell`, `loginShell`, `agentPath`, `forgetShell`, `LOOKUP_VERSION`), dock/programs.ts `PROGRAMS` (`lookup` per program), `locate`, `locateFound`, `agentEnv`, `warmLookup`, `programStatus`, `programLaunch` (env argument); dock/index.ts `openClaude`, `openAgent` (now async), `createDock` (warms the lookup); ../web/src/dock-adapter.ts `mountDock` (focus recheck)
+- logged: v0.12.0 · 2026-12-03 03:20 EST (rec-agent)
+
+The owner's Mac showed "Claude Code is not installed" in the dock's Ask tab while FormDeck, FormVis and FormPortal found it. The cause, read from the code: the engine (`formrec serve --desktop`, started by the Tauri shell, which passes its own environment on unchanged) looked for `claude` with `agents/clients.ts` `which` over `process.env.PATH`, and an app started from the Finder or the Dock has launchd's PATH, /usr/bin:/bin:/usr/sbin:/sbin. Nothing in FormREC read the login shell's PATH or looked in install folders. FormDeck and FormVis share `backend/app/services/agent_lookup.py` 1.1.0 (byte-identical in both), which looks in order: the engine's PATH, the known install folders, then the person's shell PATH asked once and kept. `dock/lookup.ts` is that file ported by hand to TypeScript, without the parts FormREC has no use for (a per-program path setting, override variables, the Windows shim parser, which `agents/win-launch.ts` already is).
+
+Choices, and why:
+- Shell: `$SHELL -l -i -c 'printf MARK$PATHMARK'`, else `-l` only, 5 s each (the family waits 10 s; the owner asked for a short wait), in its own session (`detached`) with stdin closed, so an interactive zsh with no terminal cannot stop on SIGTTOU, and the whole group is killed at the deadline. On Windows the user and system Path values from `reg query`.
+- Asked once at engine start (`warmLookup` in `createDock`), so the dock's first status rarely waits. An empty answer is re-asked after a minute in the background, never while a route waits: a .zshrc that hangs costs its 10 s once. Measured with a shell that sleeps 40 s: the first status 11.7 s with 6 s (now 5 s), none after, no `sleep` left running.
+- A missing program has the shell asked again in the background at most every 30 s (an install may have changed the PATH); the folders are looked in afresh on every status. Opening a tab for a missing program waits on a fresh ask first, since the person asked for it.
+- The tab's PATH: the program's own folder, the shell PATH, the known folders that exist, the engine's PATH. Shells (`$SHELL -l`) are unchanged: a login shell sets its own PATH.
+- The status keeps its shape and adds `path` and `how` (path, folder, shell) when found, `looked` when not, as the family's `answer` does. The shared dock module (2.2.1) is not edited; the focus recheck is in FormREC's adapter.
+
+Checked here (Linux; macOS was not available): the engine run with `env -i PATH=/usr/bin:/bin HOME=` and `claude` (a `#!/usr/bin/env node` script) only in `~/odd-npm/bin`, added to PATH in the scratch `~/.zshrc` (SHELL=/usr/bin/zsh) and `~/.profile` (no SHELL: bash). Main at 9fa578e: `installed: false`, opening Claude Code 409. This change: `installed: true`, `how: shell`, version read through the found node, and the tab printed the script's line with `--mcp-config`. In `~/.npm-global/bin` with no shell file: `how: folder`. Codex the same, and its tab opened. With a shell that adds nothing: `installed: false`, the install command, 409 on open. Playwright on the browser build: the Ask tab's note with `npm install -g @anthropic-ai/claude-code`; after installing into `~/.npm-global/bin` and a window focus event the note was gone, and the Claude Code button opened the tab with the program running; no page errors. No test was added (owner's rule); none existed for `src/dock`.
+
+Follow-up, Settings, Agents (`features/agents/index.ts`, `agents/clients.ts` `Env.toolEnv` and `claudeReplace`): it found claude and codex with `which` over the engine's PATH, so the Mac app's Connect said "the claude command is not installed here". It now passes the dock's lookup to `clientStatus` (as `find`) and to `installClient`, `installHttpClient` and `installRelayClient` (as `claudeBin`), and `claude mcp remove/add` runs with `toolEnv` (this process's environment, PATH as the dock's tabs get it), so an npm claude finds node. `formrec agents` from a terminal passes no `toolEnv` and is unchanged. Every other child process in `src/` was read: none runs an agent program by name. Checked with the same minimal environment: GET `/api/agents` listed claude as found, and Connect (stdio and HTTP) ran the fake claude's `mcp remove` and `mcp add`.
+
+## v0.12.0 · agent parity: the window's commands over MCP, jobs for long tools, and agents' changes shown live {#agent-parity}
+
+_src/window/bridge.ts, src/window/tools.ts, src/mcp/jobs.ts, src/mcp/server.ts (CORE_TOOLS, the wrapper), src/mcp/tools.ts (ToolDeps.window), src/mcp/http.ts, src/app.ts_
+
+The owner's rule (2 Dec): Claude Code and the other agents can do everything a person can do in FormREC. The audit (handoff r12-rec-parity.md) found 124 MCP tools covering most data work, but nothing that reached the window: the command registry had about 60 argument-less commands that only shortcuts, menus and the native menu ran; there was no list or run for agents as FormDeck's `list_commands` and `run_command` or FormCite's `window_commands`; long tools (record, export, transcribe, clips) held the call until done; and a change an agent made showed in the window only after the person navigated.
+
+The bridge is the consent stream's pattern again: the window keeps `GET /api/window/stream` open (fetch-read server-sent events, since an EventSource cannot send the token) and the engine sends it `call` events that it answers on `POST /api/window/result`, 15 s each. One stream per window; the one focused last answers, so a second window is a spare, not a second actor. The engine holds no copy of the catalogue: the window builds it on each list, so enums computed at run time (the open player's panels, the registered recording actions, Settings sections) are always current. `formrec mcp` over stdio and `formrec mcp --http` have no window in process, so `remoteCaller` finds the running app through its server file (store/server-file.ts) and calls `/api/window/commands`, `/api/window/run` and `/api/window/changed` with the run token, which those processes already read for consent (`remoteGate`). The relay's bridge gets no window caller, so neither the window tools nor the job tools exist there, and `bridgescope` holds.
+
+Approval. The existing gate asks outside agents (the MCP token) once per mutating tool and lets dock agents through, which is right for most commands but not for the ones the owner named: deleting, publishing outside this computer, the camera and the microphone. So `runWithApproval` describes the command first (the window says its risk for these arguments: a recording action's risk is the action's) and, for destructive, external and privacy, asks through the dock's `ConsentBroker.ask` every time, for every agent, dock ones included; a Blocked policy refuses them outright. "Always allow" in that dialog still settles the pending question as allowed (the broker's own rule); the next risky command asks again because the bridge calls `ask`, not the standing check. An outside agent on Ask can therefore see two questions for one risky command: the tool-level one and the command's. That was kept: the second names what will happen, and merging them would mean the gate reading command risks, a second source of truth. Read-only tokens stay read-only: `formrec_window_command_run` is UPDATES, so a read-only scope disables it.
+
+Jobs. `formrec_job_start` runs any other tool of the same server in the background and answers a job id; `formrec_job_status` polls (state, the last progress notification, and the tool's own result when it ends); `formrec_job_cancel` aborts its signal, which `formrec_record` already honours (nothing saved). The started tool's arguments are parsed with its own input schema before it starts, so a wrong argument fails at start, not later; it runs its raw handler plus the same `finish` (player keys, change notice) as a direct call, so the answer is identical. Consent is asked once, for `formrec_job_start` (WRITES, so outside agents are asked, with the tool name in the summary); running the gated wrapper inside would have asked twice. A job may run only what the server offers: a tool the core filter removed is not found, one the scope disabled is refused. The table is per process (the in-app HTTP server builds a server per session, so a job started in one session can be polled from another), at most 100, kept an hour after they end, 16 running at once.
+
+Not core tools. The five are registered right after the nine core tools but are not in `CORE_TOOLS` (they are `WINDOW_AND_JOB_TOOLS`): a server built with no window caller (the relay, Settings' tool count, the in-memory test servers) has none of them, and `CORE_TOOLS` promises tools every server has. A first version listed them there and three existing tests (mcp, mcp-tools, mcp-http-server) failed on window-less servers. `agents:sync` therefore lists them in feature-tools.md. mcp-http-server.test's `stdioToolNames` modelled stdio as a bare `buildServer`; real stdio (`serveMcp`) now adds the remote window caller, so the helper builds the same way and the existing assertion (stdio and --http offer the same tools in the same order) holds unchanged.
+
+Live. `buildServer`'s wrapper announces every successful non-read-only tool's recording ids (from `id`, `ids`, `recordingId`, `recordingIds` and the answer's `id` or `recording.id`) through `deps.window.changed`; the window's end turns it into `formrec:agent-change`. Library events were not used: they fire for the person's own saves too, and redrawing the studio or the library under them would undo what they just did.
+
+Checked live (a scratch build in /tmp, `formrec serve` on 18851 with a scratch data folder, Chromium through Playwright as the window, the MCP SDK client as an outside agent over `/mcp`, then over stdio): 129 tools listed; the first mutating call asked in the window; 87 commands listed, `nav.go` described with its 31 pages, a wrong page refused naming the values; Home, Shared, Notifications, Insights, Meetings, Ask, Screen, Camera, Audio only and the tour each opened; `player.seek` in the tour; `prefs.set` theme light changed `data-theme`; `settings.open agents` opened the dialog; File > New Audio Recording; `studio.configure` pressed the camera layout; `studio.start` asked (privacy) and, declined, failed with "declined"; an import, a rename shown in the open library within 1.2 s, a comment redrawing the open player at the same moment and still paused, `player.panel engage-comments` showing it; `formrec_export` as a job polled to done in 7 to 14 s; a job with a wrong argument refused by the tool's schema; `recording.action library-trash` asked (destructive), allowed once, ran. Over stdio: the studio commands listed, `nav.go insights` asked in the window and ran, an import and a rename showed in the open library at once. Later the same way: `settings.controls`/`settings.set` (hide controls and countdown stored, a value the select lacks refused, Trash after 45 days saved and read back from the engine, Outside agents absent and refused before any question) and `view.controls`/`view.set` (163 studio controls, studio quality set after an Allow once, library search typed with no question). 91 commands in a fresh window on Home: 44 read, 28 change, 13 privacy, 6 destructive. No test was added (owner's rule); one existing helper was updated (Not core tools, above).
+
+Under the build lock: `npm run check` passes; `npm run agents:sync` wrote 129 tools; the 14 agent and MCP test files pass (106 tests); the full `npm test` on the working tree with every role's work: 2621 passed, 50 skipped, 4 failed, all in tests/shell-reservations.test.ts, where the sidebar Learn row "A FormPortal walkthrough" (the demos work, not this) is 172 px of text in a 153 px slot; reported to rec-demos in r12-requests.md.
+
+## v0.12.0 HASHOUT · PR #13's CI: one stream a window, exports that tolerate a busy folder, the phone dot, Robolectric fetched first {#ci-pr13}
+
+_src/window/bridge.ts, src/dock/index.ts, src/app.ts, web/src/agent-bridge.ts, web/src/dock-adapter.ts, web/src/app.ts, src/features/library/transfer.ts, src/features/library/zip.ts, web/styles/phone.css, .github/workflows/ci.yml; tests live-audit3, live-link-e2e, keycast-walkthrough_
+
+The release was cut at 966a272 and PR #13's CI failed six ways. Each, compared with main 9fa578e on two cores with coverage:
+
+- The window stream (this branch). Every app window kept two long fetch streams to the engine, the consent stream and the new `/api/window/stream`. Chromium opens six connections to one host and the player's three media requests, the studio's uploads and the API calls share them. The bridge now rides on the consent stream: the window opens `/api/mcp/consent/stream?window=1` and the dock attaches the bridge to that response (`WindowBridge.attach`). One long request a window again, as on main; `/api/window/stream` stays for other clients. Checked in Chromium: one long request, the commands listed, `app.home` run in the window, close in 55 ms. The player and live failures (effects-noise-playback paused, live-link-e2e's afterAll past 10 s) did not reproduce here on either commit, so the stream is the branch's likely part in them, not a proven one.
+- library-routes, export with no count (pre-existing). A folder export listed a recording's files and then copied them; a file deleted in between (a rendition's progress file, a transcript rewritten) threw ENOENT. The listing leaves out `*.tmp` and `*.part` and files gone when looked at, the copy skips a file gone before it is read, and the zip writer opens each file before its header so a vanished entry (`mayVanish`) is left out whole. keycast-walkthrough's walk does the same (its ENOENT on `transcript.txt..tmp`).
+- phone-pwa-offline, shift 0.0000562 (pre-existing). A layout-shift observer at 6x throttling on one core named `.rv-phone-rec-core`: the dot's width and height transition, running past the tap's input window. It now turns to the stop square by `transform: scale`, radius scaled to match; 0 in three runs.
+- live-audit3, 0.952 s (pre-existing, timing). The restart took three connections on CI and the 60 s feed ran out. The feed is 120 s, the 1.5 s sleep is a wait for the port to listen, and the take stops once the second server has more than two seconds; the assertion is unchanged. live-link-e2e's afterAll has a 60 s timeout.
+- phone-android-e2e (pre-existing, network). Robolectric's download of its Android jar failed (MavenArtifactFetcher IOException) and main's CI is the same. Each shard restores the jar from the cache and fetches `org.robolectric:android-all-instrumented:14-robolectric-10818077-i7` with `mvn dependency:get`, four attempts; the test is not skipped. If apps/android's Robolectric version or the tests' sdk changes, change the coordinate and the cache key with it.
+
+Checked: the six affected files with library-e2e, studio-e2e and the agent and MCP HTTP tests under `taskset -c 0,1` with coverage, 11 files 69 tests passed (live-audit3's restart went live on connection 4 and still passed); `npm run check` and `npm run build` pass. The Gradle run could not be checked here (no Android SDK, and Maven Central answered this machine 429).
diff --git a/src/agents/clients.ts b/src/agents/clients.ts
index 3adc788..d5e0a63 100644
--- a/src/agents/clients.ts
+++ b/src/agents/clients.ts
@@ -46,6 +46,12 @@ export interface Env {
env: NodeJS.ProcessEnv
/** File existence (tests pass their own). */
exists?: (file: string) => boolean
+ /**
+ * The environment the claude command runs with, when it is not this process's (the app's Settings, Agents passes one
+ * whose PATH holds the login shell's and the known install folders, src/dock/lookup.ts, so an npm-installed claude
+ * finds node when the app was started from the Finder or the Dock). Default: this process's environment.
+ */
+ toolEnv?: NodeJS.ProcessEnv
}
/**
@@ -185,10 +191,12 @@ export function which(bin: string, env: NodeJS.ProcessEnv = process.env, platfor
* Connect runs this inside the server, which must never hang on a stuck claude command. Returns why the add failed.
*/
export function claudeReplace(bin: string, name: string, addArgs: string[], e: Env): string | undefined {
- const le: LaunchEnv = { platform: e.platform, env: e.env, exists: e.exists, which: (b) => which(b, e.env, e.platform) }
+ const runEnv = e.toolEnv ?? e.env
+ const le: LaunchEnv = { platform: e.platform, env: runEnv, exists: e.exists, which: (b) => which(b, runEnv, e.platform) }
+ const own = e.toolEnv ? { env: e.toolEnv } : {}
try {
- runTool(bin, ['mcp', 'remove', name, '--scope', 'user'], { encoding: 'utf8', timeout: 10_000 }, le)
- const add = runTool(bin, ['mcp', 'add', ...addArgs], { encoding: 'utf8', timeout: 15_000 }, le)
+ runTool(bin, ['mcp', 'remove', name, '--scope', 'user'], { encoding: 'utf8', timeout: 10_000, ...own }, le)
+ const add = runTool(bin, ['mcp', 'add', ...addArgs], { encoding: 'utf8', timeout: 15_000, ...own }, le)
return add.status === 0 ? undefined : (add.stderr || add.stdout || add.error?.message || '').trim()
} catch (err) {
if (err instanceof LaunchRefused) return err.message
diff --git a/src/app.ts b/src/app.ts
index a8dea77..8eb5928 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -17,6 +17,7 @@ import { mcpToken } from './mcp/token.js'
import { playerLinkGate } from './server/player-link.js'
import { version } from './version.js'
import { createDock } from './dock/index.js'
+import { localCaller, WindowBridge, windowRoutes } from './window/bridge.js'
export interface AppOptions {
dataDir: string
@@ -79,7 +80,11 @@ export function createApp(opts: AppOptions): App {
const port = ctx.port()
return port === undefined ? [] : [`http://127.0.0.1:${port}`, `http://localhost:${port}`]
}
- const dock = createDock({ dataDir: opts.dataDir, port: ctx.port, codebase: opts.codebase })
+ // The agent bridge to the open window (window/bridge.ts): its command registry, and live notices of agents' changes.
+ // The window takes its events on the dock's consent stream, so the dock is given the bridge.
+ const bridge = new WindowBridge()
+ const dock = createDock({ dataDir: opts.dataDir, port: ctx.port, codebase: opts.codebase, windows: bridge })
+ const windowCaller = localCaller(bridge, dock.consent, opts.dataDir)
const mcp = createMcpHttp({
build: () =>
buildServer(
@@ -88,6 +93,7 @@ export function createApp(opts: AppOptions): App {
// No run token: buildServer gives each recording's link its own player key (mcp/player-links.ts).
playerBase: async () => `${origin()[0] ?? 'http://127.0.0.1:8770'}/`,
allowedRoots: opts.codebase ? [opts.codebase.root] : undefined,
+ window: windowCaller,
},
version(),
{},
@@ -106,6 +112,7 @@ export function createApp(opts: AppOptions): App {
studioRoutes({ sessions, room, devices, guests, codebase: opts.codebase, engine: opts.engine }),
...FEATURES.flatMap((f) => (f.routes ? [f.routes(ctx)] : [])),
dock.routes,
+ windowRoutes(bridge, dock.consent, opts.dataDir),
],
mediaFile: featureFile,
gates: [playerLinkGate(library), extensionGate(ctx), mailGate()],
diff --git a/src/dock/index.ts b/src/dock/index.ts
index e582fe2..5470920 100644
--- a/src/dock/index.ts
+++ b/src/dock/index.ts
@@ -6,7 +6,7 @@ import { z } from 'zod'
import { readJsonBody } from '../server/files.js'
import { CONSENT_CHOICES, ConsentBroker, OUTSIDE_POLICIES, type ConsentEvent } from '../mcp/consent.js'
import { ptyMissing } from './pty.js'
-import { AGENT_TABS, childEnv, claudeConfig, locate, programLaunch, programStatus, PROGRAMS, removeFile, removeTabEntry, shellLaunch, tabToken, writeTabEntry, type AgentTab } from './programs.js'
+import { AGENT_TABS, agentEnv, childEnv, claudeConfig, locate, programLaunch, programStatus, PROGRAMS, removeFile, removeTabEntry, shellLaunch, tabToken, warmLookup, writeTabEntry, type AgentTab } from './programs.js'
import { originAllowed, TerminalSockets, Tickets } from './socket.js'
import { NoPty, Terminals, TooMany, type Session } from './terminals.js'
@@ -16,6 +16,8 @@ export interface DockServerOptions {
dataDir: string
port(): number | undefined
codebase?: { root: string }
+ /** The agent bridge (src/window/bridge.ts): a consent stream opened with `?window=1` carries its events too. */
+ windows?: { attach(req: IncomingMessage, res: ServerResponse): void }
}
export interface DockServer {
@@ -74,6 +76,7 @@ export function createDock(o: DockServerOptions): DockServer {
const mcpUrl = (): string => `http://127.0.0.1:${o.port() ?? 8770}/mcp`
const consent = new ConsentBroker(o.dataDir)
const streams = new Set()
+ warmLookup()
const consentStream = async (req: IncomingMessage, res: ServerResponse): Promise => {
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' })
@@ -85,6 +88,8 @@ export function createDock(o: DockServerOptions): DockServer {
beat.unref()
streams.add(res)
req.on('close', () => { off(); clearInterval(beat); streams.delete(res) })
+ // The app's window: one long request carries both, so it holds one of the browser's six connections to this host.
+ if (o.windows && new URL(req.url ?? '/', 'http://127.0.0.1').searchParams.get('window') === '1') o.windows.attach(req, res)
}
const consentRoutes = async (req: IncomingMessage, res: ServerResponse, b: string | undefined, method: string): Promise => {
@@ -137,24 +142,27 @@ export function createDock(o: DockServerOptions): DockServer {
const openShell = (cols?: number, rows?: number, title?: string): Session =>
open(() => terminals.open('shell', title || `Terminal ${terminals.shells() + 1}`, home(), shellLaunch(), childEnv(), cols ?? 100, rows ?? 30))
- const openClaude = (b: z.infer): Session => {
- const file = locate('claude')
+ const openClaude = async (b: z.infer): Promise => {
+ const file = await locate('claude')
if (!file) throw new Refusal(409, 'not-installed', 'Claude Code is not installed. Install it with npm install -g @anthropic-ai/claude-code, then sign in once by running claude in a terminal.')
+ const env = await agentEnv(file, { FORMREC_MCP_URL: mcpUrl() })
let config = ''
return withToken((token) => open(() => {
config = claudeConfig(path.join(tabsDir(), 'claude'), tabToken().slice(0, 12), mcpUrl(), token)
const args = ['--mcp-config', config, ...(b.resume ? ['--resume', b.resume] : []), ...(b.prompt ? [b.prompt] : [])]
- return terminals.open('claude', 'Claude Code', home(), programLaunch(file, args), childEnv({ FORMREC_MCP_URL: mcpUrl() }), b.cols ?? 100, b.rows ?? 30)
+ return terminals.open('claude', 'Claude Code', home(), programLaunch(file, args, env), env, b.cols ?? 100, b.rows ?? 30)
}), () => { if (config) removeFile(config) })
}
- const openAgent = (kind: AgentTab, cols?: number, rows?: number): Session => {
- const file = locate(kind)
+ const openAgent = async (kind: AgentTab, cols?: number, rows?: number): Promise => {
+ const file = await locate(kind)
if (!file) throw new Refusal(409, 'not-installed', `${PROGRAMS[kind].title} is not installed.${PROGRAMS[kind].install ? ` Install it with ${PROGRAMS[kind].install}.` : ''}`)
const own = kind === 'antigravity' ? path.join(tabsDir(), kind) : undefined
+ const base = await agentEnv(file, { FORMREC_MCP_URL: mcpUrl() })
return withToken((token) => open(() => {
if (own) writeTabEntry(own, mcpUrl(), token)
- return terminals.open(kind, PROGRAMS[kind].title, own ?? home(), programLaunch(file, []), childEnv({ FORMREC_MCP_URL: mcpUrl(), FORMREC_INAPP_TOKEN: token }), cols ?? 100, rows ?? 30)
+ const env = { ...base, FORMREC_INAPP_TOKEN: token }
+ return terminals.open(kind, PROGRAMS[kind].title, own ?? home(), programLaunch(file, [], env), env, cols ?? 100, rows ?? 30)
}), (token) => { if (own) removeTabEntry(own, token) })
}
@@ -184,10 +192,10 @@ export function createDock(o: DockServerOptions): DockServer {
return true
}
if (parts.length === 3 && a === 'ticket' && method === 'POST') { sendJson(res, 200, { ticket: tickets.issue() }); return true }
- if (parts.length === 3 && a === 'claude' && method === 'POST') { sendJson(res, 200, openClaude(await body(req, ClaudeBody)).describe()); return true }
+ if (parts.length === 3 && a === 'claude' && method === 'POST') { sendJson(res, 200, (await openClaude(await body(req, ClaudeBody))).describe()); return true }
if (parts.length === 3 && a === 'agent' && method === 'POST') {
const o2 = await body(req, AgentBody)
- sendJson(res, 200, openAgent(o2.kind, o2.cols, o2.rows).describe())
+ sendJson(res, 200, (await openAgent(o2.kind, o2.cols, o2.rows)).describe())
return true
}
if (!a) return false
diff --git a/src/dock/lookup.ts b/src/dock/lookup.ts
new file mode 100644
index 0000000..4b59665
--- /dev/null
+++ b/src/dock/lookup.ts
@@ -0,0 +1,328 @@
+/**
+ * Where an agent program (Claude Code, Codex, Cursor's agent, Antigravity) is, the Form family's way: the engine's PATH,
+ * then the known install folders, then the person's own shell PATH, asked once and kept. A port of the family's
+ * `agent_lookup.py` 1.1.0 (FormDeck and FormVis, `backend/app/services/agent_lookup.py`) to the engine's TypeScript.
+ *
+ * The reason: an app started from the Finder, the Dock, the Start menu or a desktop launcher gets the system's short
+ * PATH (launchd's /usr/bin:/bin:/usr/sbin:/sbin on macOS), not the one a terminal has, so a bare PATH search reports
+ * programs installed by Homebrew, npm, a version manager or into the home folder as missing. The same PATH is what a
+ * program needs when it starts: an npm-installed `claude` is a `#!/usr/bin/env node` script, so `agentPath` puts the
+ * program's own folder, the shell's PATH and the known folders in front of the engine's own.
+ */
+import { execFile, spawn } from 'node:child_process'
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { which } from '../agents/clients.js'
+
+export const LOOKUP_VERSION = '1.1.0'
+const MARK = '__FORM_AGENT_LOOKUP__'
+/** How long the person's shell may take to say its PATH (a slow .zshrc is common; the answer is kept). */
+export const SHELL_MS = 5000
+/** An empty answer is asked again after this long, so a fix to the person's shell files is picked up. */
+const RETRY_MS = 60_000
+
+export type How = 'path' | 'folder' | 'shell'
+export const HOW: Record = { path: "the engine's PATH", folder: 'a known install folder', shell: "your shell's PATH" }
+
+export interface Spec {
+ names: readonly string[]
+ /** Folders under the home folder on macOS and Linux; a * stands for version folders, newest first. */
+ home?: readonly string[]
+ /** Folders on Windows as local:, roaming: or home: and a path. */
+ windows?: readonly string[]
+ /** Files inside an application bundle in /Applications or ~/Applications (macOS). */
+ macFiles?: readonly string[]
+}
+
+export interface Found { file?: string; how?: How; looked: string[] }
+
+export interface LookupOptions {
+ env?: NodeJS.ProcessEnv
+ platform?: NodeJS.Platform
+ home?: string
+}
+
+let shellAnswer: { path: string[]; note: string; at: number } | undefined
+let shellAsking: Promise<{ path: string[]; note: string }> | undefined
+
+/** Forget the shell's answer (tests, and a refresh that must ask again). */
+export function forgetShell(): void {
+ shellAnswer = undefined
+ shellAsking = undefined
+}
+
+function isDir(p: string): boolean {
+ try {
+ return statSync(p).isDirectory()
+ } catch {
+ return false
+ }
+}
+
+function versionKey(name: string): number[] {
+ const n = name.match(/\d+/g)?.map(Number) ?? []
+ return n.length ? n : [0]
+}
+
+function newestFirst(a: string, b: string): number {
+ const x = versionKey(a)
+ const y = versionKey(b)
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
+ const d = (y[i] ?? 0) - (x[i] ?? 0)
+ if (d) return d
+ }
+ return 0
+}
+
+/** The version folders under base, newest first, each with tail joined. */
+function versions(base: string, tail = ''): string[] {
+ let names: string[]
+ try {
+ names = readdirSync(base).filter((n) => isDir(path.join(base, n)))
+ } catch {
+ return []
+ }
+ return names.sort(newestFirst).map((n) => (tail ? path.join(base, n, tail) : path.join(base, n)))
+}
+
+/** npm's global prefix from ~/.npmrc (`prefix=`), which a person sets instead of the variable. */
+function npmrcPrefix(home: string): string | undefined {
+ try {
+ const line = readFileSync(path.join(home, '.npmrc'), 'utf8').split(/\r?\n/).find((l) => /^\s*prefix\s*=/.test(l))
+ const value = line?.split('=').slice(1).join('=').trim().replace(/^["']|["']$/g, '')
+ return value ? value.replace(/^~(?=$|[\\/])/, home) : undefined
+ } catch {
+ return undefined
+ }
+}
+
+export function systemFolders(platform: NodeJS.Platform): string[] {
+ if (platform === 'win32') return []
+ if (platform === 'darwin') return ['/opt/homebrew/bin', '/usr/local/bin', '/opt/local/bin']
+ return ['/usr/local/bin', '/usr/bin', '/snap/bin', '/home/linuxbrew/.linuxbrew/bin']
+}
+
+/** The known install folders for a program on this system, in the family's order, whether or not they exist. */
+export function folders(spec: Spec, o: LookupOptions = {}): string[] {
+ const env = o.env ?? process.env
+ const platform = o.platform ?? process.platform
+ const home = o.home ?? os.homedir()
+ const win = platform === 'win32'
+ const p = win ? path.win32 : path.posix
+ const out: string[] = []
+ const prefix = env.NPM_CONFIG_PREFIX || env.npm_config_prefix || npmrcPrefix(home)
+ if (prefix) out.push(win ? prefix : p.join(prefix, 'bin'))
+ for (const [key, tail] of [['PNPM_HOME', ''], ['VOLTA_HOME', 'bin'], ['BUN_INSTALL', 'bin'], ['NVM_SYMLINK', '']] as const) {
+ const value = env[key]
+ if (value) out.push(tail ? p.join(value, tail) : value)
+ }
+ if (win) {
+ const roots: Record = { home, roaming: env.APPDATA || p.join(home, 'AppData', 'Roaming'), local: env.LOCALAPPDATA || p.join(home, 'AppData', 'Local') }
+ out.push(p.join(home, '.local', 'bin'), p.join(roots.roaming!, 'npm'), p.join(roots.local!, 'npm'), p.join(roots.local!, 'pnpm'), p.join(roots.local!, 'Volta', 'bin'),
+ p.join(home, '.bun', 'bin'), p.join(home, '.volta', 'bin'))
+ for (const place of spec.windows ?? []) {
+ const [root, ...rest] = place.split(':')
+ out.push(p.join(roots[root!] ?? home, ...rest.join(':').split('/')))
+ }
+ return [...new Set(out)]
+ }
+ out.push(p.join(home, '.local', 'bin'), p.join(home, '.npm-global', 'bin'), p.join(home, '.bun', 'bin'), p.join(home, '.volta', 'bin'), p.join(home, '.local', 'share', 'pnpm'))
+ if (platform === 'darwin') out.push(p.join(home, 'Library', 'pnpm'))
+ out.push(...versions(p.join(home, '.nvm', 'versions', 'node'), 'bin'))
+ out.push(...versions(p.join(home, '.local', 'share', 'fnm', 'node-versions'), 'installation/bin'))
+ out.push(...versions(p.join(home, 'Library', 'Application Support', 'fnm', 'node-versions'), 'installation/bin'))
+ out.push(...versions(p.join(home, '.asdf', 'installs', 'nodejs'), 'bin'))
+ out.push(...versions(p.join(home, '.local', 'share', 'mise', 'installs', 'node'), 'bin'))
+ out.push(p.join(home, '.asdf', 'shims'), p.join(home, '.local', 'share', 'mise', 'shims'))
+ for (const place of spec.home ?? []) {
+ const [base, tail] = place.split('*')
+ if (tail !== undefined) out.push(...versions(p.join(home, base!), tail.replace(/^\//, '')))
+ else out.push(p.join(home, place))
+ }
+ out.push(...systemFolders(platform))
+ return [...new Set(out)]
+}
+
+/** The shell the person logs in with: $SHELL, else zsh on macOS, else bash or sh. */
+export function loginShell(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string {
+ if (env.SHELL) return env.SHELL
+ if (platform === 'darwin' && existsSync('/bin/zsh')) return '/bin/zsh'
+ return which('bash', env, platform) ?? '/bin/sh'
+}
+
+/**
+ * Ask a shell for its PATH: started in its own session with no terminal (so an interactive start cannot stop on the
+ * terminal), stdin closed, killed with its whole group at the deadline. The PATH is read between two markers, so
+ * whatever the shell's start files print around it is ignored.
+ */
+export function askShell(shell: string, flags: string[], env: NodeJS.ProcessEnv, ms: number): Promise {
+ const script = path.basename(shell) === 'fish' ? `printf '%s%s%s' ${MARK} (string join : $PATH) ${MARK}` : `printf "%s%s%s" ${MARK} "$PATH" ${MARK}`
+ return new Promise((resolve) => {
+ let out = ''
+ let done = false
+ const finish = (value: string[] | null): void => {
+ if (done) return
+ done = true
+ clearTimeout(timer)
+ resolve(value)
+ }
+ let child: ReturnType
+ try {
+ child = spawn(shell, [...flags, '-c', script], { env, stdio: ['ignore', 'pipe', 'ignore'], detached: true, windowsHide: true })
+ } catch {
+ resolve(null)
+ return
+ }
+ const timer = setTimeout(() => {
+ try {
+ if (child.pid) process.kill(-child.pid, 'SIGKILL')
+ } catch {
+ child.kill('SIGKILL')
+ }
+ finish(null)
+ }, ms)
+ timer.unref()
+ child.stdout?.setEncoding('utf8')
+ child.stdout?.on('data', (chunk: string) => { if (out.length < 1_000_000) out += chunk })
+ child.on('error', () => finish(null))
+ child.on('close', () => {
+ const hit = new RegExp(`${MARK}([\\s\\S]*?)${MARK}`).exec(out)
+ const parts = hit ? hit[1]!.split(':').filter(Boolean) : []
+ finish(parts.length ? parts : null)
+ })
+ child.unref()
+ })
+}
+
+function expandWin(text: string, env: NodeJS.ProcessEnv): string {
+ return text.replace(/%([^%]+)%/g, (whole, name: string) => {
+ const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase())
+ return key ? env[key] ?? whole : whole
+ })
+}
+
+/** The user and system Path values in the registry (Windows), as a newly opened terminal would have them. */
+function registryPath(env: NodeJS.ProcessEnv, ms: number): Promise {
+ const keys = ['HKCU\\Environment', 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment']
+ return Promise.all(keys.map((key) => new Promise((resolve) => {
+ try {
+ execFile('reg', ['query', key, '/v', 'Path'], { timeout: ms, windowsHide: true, encoding: 'utf8' }, (error, stdout) => {
+ const line = String(stdout ?? '').split(/\r?\n/).find((l) => /^\s*Path\s+REG_/i.test(l))
+ const value = line?.replace(/^\s*Path\s+REG_\w+\s+/i, '') ?? ''
+ resolve(error && !value ? [] : expandWin(value, env).split(';').map((s) => s.trim()).filter(Boolean))
+ })
+ } catch {
+ resolve([])
+ }
+ }))).then((both) => [...new Set(both.flat())])
+}
+
+/**
+ * The person's own PATH: on macOS and Linux what their login, interactive shell ends up with (login only when the
+ * interactive start gives nothing), on Windows the Path values in the registry. Asked once and kept; an empty answer is
+ * asked again after a minute (in the background: the kept answer is returned meanwhile, so a shell that hangs costs
+ * its wait once, not on every question), or at once with fresh. Callers at the same time share one question.
+ */
+export function shellPath(o: LookupOptions & { fresh?: boolean; ms?: number } = {}): Promise<{ path: string[]; note: string }> {
+ const env = o.env ?? process.env
+ const platform = o.platform ?? process.platform
+ const ms = o.ms ?? SHELL_MS
+ if (shellAnswer && !o.fresh) {
+ const kept = { path: [...shellAnswer.path], note: shellAnswer.note }
+ if (!shellAnswer.path.length && Date.now() - shellAnswer.at >= RETRY_MS && !shellAsking) void shellPath({ ...o, fresh: true })
+ return Promise.resolve(kept)
+ }
+ if (shellAsking) return shellAsking
+ const asking = (async (): Promise<{ path: string[]; note: string }> => {
+ if (platform === 'win32') {
+ const found = await registryPath(env, ms)
+ return { path: found, note: found.length ? 'the Path values in the registry' : 'the Path values in the registry (none could be read)' }
+ }
+ const shell = loginShell(env, platform)
+ const name = path.basename(shell)
+ const seconds = `${ms / 1000} s`
+ const first = await askShell(shell, ['-l', '-i'], env, ms)
+ if (first) return { path: first, note: `your shell (${name}, login and interactive)` }
+ const second = await askShell(shell, ['-l'], env, ms)
+ if (second) return { path: second, note: `your shell (${name}, login only: the interactive start gave no PATH within ${seconds})` }
+ return { path: [], note: `your shell (${name} gave no PATH within ${seconds})` }
+ })()
+ shellAsking = asking
+ void asking.then((answer) => {
+ if (shellAsking === asking) {
+ shellAnswer = { ...answer, at: Date.now() }
+ shellAsking = undefined
+ }
+ })
+ return asking
+}
+
+function short(p: string, home: string): string {
+ return home && home !== path.sep && (p === home || p.startsWith(home + path.sep)) ? `~${p.slice(home.length)}` : p
+}
+
+function onPath(names: readonly string[], dirs: string[], env: NodeJS.ProcessEnv, platform: NodeJS.Platform): string | undefined {
+ if (!dirs.length) return undefined
+ const delimiter = platform === 'win32' ? ';' : ':'
+ for (const name of names) {
+ const hit = which(name, { ...env, PATH: dirs.join(delimiter), Path: undefined }, platform)
+ if (hit) return hit
+ }
+ return undefined
+}
+
+function appFile(spec: Spec, home: string, platform: NodeJS.Platform): string | undefined {
+ if (platform !== 'darwin') return undefined
+ for (const apps of ['/Applications', path.join(home, 'Applications')]) {
+ for (const inside of spec.macFiles ?? []) {
+ const file = path.join(apps, ...inside.split('/'))
+ try {
+ if (statSync(file).isFile()) return file
+ } catch {
+ // not here
+ }
+ }
+ }
+ return undefined
+}
+
+/**
+ * Where the program is, in the family's order: the engine's PATH, the known install folders, then the person's shell
+ * PATH. `looked` records where it was not, so a not-found message can say so.
+ */
+export async function find(spec: Spec, o: LookupOptions & { fresh?: boolean } = {}): Promise {
+ const env = o.env ?? process.env
+ const platform = o.platform ?? process.platform
+ const home = o.home ?? os.homedir()
+ const looked: string[] = []
+ const enginePath = env.PATH ?? env.Path ?? ''
+ const delimiter = platform === 'win32' ? ';' : ':'
+ const fromPath = onPath(spec.names, enginePath.split(delimiter).filter(Boolean), env, platform)
+ if (fromPath) return { file: fromPath, how: 'path', looked }
+ looked.push(`PATH (${enginePath || 'empty'})`)
+ const known = folders(spec, { env, platform, home })
+ const fromFolder = onPath(spec.names, known, env, platform) ?? appFile(spec, home, platform)
+ if (fromFolder) return { file: fromFolder, how: 'folder', looked }
+ looked.push(known.map((f) => short(f, home)).join(', '))
+ const shell = await shellPath({ env, platform, fresh: o.fresh })
+ const fromShell = onPath(spec.names, shell.path, env, platform)
+ if (fromShell) return { file: fromShell, how: 'shell', looked }
+ looked.push(shell.note)
+ return { looked }
+}
+
+/**
+ * The PATH an agent program starts with (and its `--version` check): its own folder first (so a node script finds the
+ * node beside it), the person's shell PATH, the known folders that exist for every program, then the engine's PATH.
+ */
+export async function agentPath(file: string | undefined, specs: readonly Spec[], o: LookupOptions = {}): Promise {
+ const env = o.env ?? process.env
+ const platform = o.platform ?? process.platform
+ const delimiter = platform === 'win32' ? ';' : ':'
+ const shell = await shellPath({ env, platform })
+ const known = specs.flatMap((spec) => folders(spec, { env, platform, home: o.home })).filter(isDir)
+ const own = file ? [(platform === 'win32' ? path.win32 : path.posix).dirname(file)] : []
+ const parts = [...own, ...shell.path, ...known, ...(env.PATH ?? env.Path ?? '').split(delimiter)]
+ return [...new Set(parts.filter(Boolean))].join(delimiter)
+}
diff --git a/src/dock/programs.ts b/src/dock/programs.ts
index 69142cb..9a0fcdd 100644
--- a/src/dock/programs.ts
+++ b/src/dock/programs.ts
@@ -4,37 +4,88 @@ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync }
import path from 'node:path'
import { which } from '../agents/clients.js'
import { launchArgv } from '../agents/win-launch.js'
+import { agentPath, find, shellPath, type Found, type How, type Spec } from './lookup.js'
import type { Launch } from './terminals.js'
export const PROGRAMS = {
- claude: { bin: 'claude', title: 'Claude Code', install: 'npm install -g @anthropic-ai/claude-code' },
- codex: { bin: 'codex', title: 'Codex', install: 'npm install -g @openai/codex' },
- cursor: { bin: 'cursor-agent', title: 'Cursor', install: 'curl https://cursor.com/install -fsS | bash' },
- antigravity: { bin: 'agy', title: 'Antigravity', install: '' },
-} as const
+ claude: { bin: 'claude', title: 'Claude Code', install: 'npm install -g @anthropic-ai/claude-code',
+ lookup: { names: ['claude'], home: ['.claude/local', '.claude/bin'], windows: ['home:.claude/local', 'home:.claude/bin', 'local:Programs/claude', 'roaming:Programs/claude'] } },
+ codex: { bin: 'codex', title: 'Codex', install: 'npm install -g @openai/codex',
+ lookup: { names: ['codex'], windows: ['local:Programs/OpenAI/Codex/bin'], macFiles: ['Codex.app/Contents/Resources/codex', 'Codex.app/Contents/Resources/bin/codex'] } },
+ cursor: { bin: 'cursor-agent', title: 'Cursor', install: 'curl https://cursor.com/install -fsS | bash',
+ lookup: { names: ['cursor-agent'], home: ['.local/share/cursor-agent/versions/*'], windows: ['local:cursor-agent'] } },
+ antigravity: { bin: 'agy', title: 'Antigravity', install: '', lookup: { names: ['agy'] } },
+} as const satisfies Record
export type ProgramKind = keyof typeof PROGRAMS
export const AGENT_TABS = ['codex', 'cursor', 'antigravity'] as const
export type AgentTab = (typeof AGENT_TABS)[number]
+const SPECS: Spec[] = Object.values(PROGRAMS).map((p) => p.lookup)
-export interface ProgramStatus { installed: boolean; version: string | null; install: string; signedIn: boolean | null; title: string; said?: string; finding: 'runs' | 'missing' }
+export interface ProgramStatus {
+ installed: boolean; version: string | null; install: string; signedIn: boolean | null; title: string; said?: string; finding: 'runs' | 'missing'
+ path?: string; how?: How; looked?: string[]
+}
export const TAB_ENTRY = 'formrec_tab'
const VERSION_MS = 4000
const VERSION_KEEP_MS = 10 * 60 * 1000
const versions = new Map }>()
-export function locate(kind: ProgramKind, env: NodeJS.ProcessEnv = process.env): string | undefined {
- return which(PROGRAMS[kind].bin, env)
+/**
+ * A missing program has the person's shell asked again (an install may have changed its PATH), at most this often and
+ * in the background, so the status route never waits on a slow shell twice; the next check (the window regaining
+ * focus, the dock's menu) sees the new answer. The folders themselves are looked in afresh on every check.
+ */
+const FRESH_MS = 30_000
+let freshAt = 0
+
+/** Ask the person's shell for its PATH now, at the engine's start, so the dock's first question does not wait on it. */
+export function warmLookup(): void {
+ freshAt = Date.now()
+ void shellPath().catch(() => undefined)
+}
+
+/** Where the program is (the engine's PATH, the known install folders, the person's shell PATH), and where it looked. */
+export async function locateFound(kind: ProgramKind): Promise {
+ const found = await find(PROGRAMS[kind].lookup)
+ if (!found.file && Date.now() - freshAt >= FRESH_MS) {
+ freshAt = Date.now()
+ void shellPath({ fresh: true }).catch(() => undefined)
+ }
+ return found
+}
+
+/** The program's file. Asked to start one, so worth a wait: when it is missing the shell is asked again first. */
+export async function locate(kind: ProgramKind): Promise {
+ const found = await find(PROGRAMS[kind].lookup)
+ if (found.file) return found.file
+ freshAt = Date.now()
+ return (await find(PROGRAMS[kind].lookup, { fresh: true })).file
+}
+
+/** The environment of an agent program: childEnv with the PATH it needs to start (see lookup.ts `agentPath`). */
+export async function agentEnv(file: string, extra: Record = {}): Promise> {
+ const env = childEnv(extra)
+ const PATH = await agentPath(file, SPECS)
+ if (process.platform === 'win32') for (const k of Object.keys(env)) if (k.toUpperCase() === 'PATH') delete env[k]
+ return { ...env, PATH }
+}
+
+/** base with the PATH an agent program needs to start (see lookup.ts `agentPath`); for Settings, Agents' claude runs. */
+export async function toolEnv(file: string | undefined, base: NodeJS.ProcessEnv = process.env): Promise {
+ const env: NodeJS.ProcessEnv = { ...base }
+ if (process.platform === 'win32') for (const k of Object.keys(env)) if (k.toUpperCase() === 'PATH') delete env[k]
+ return { ...env, PATH: await agentPath(file, SPECS, { env: base }) }
}
-function versionOf(file: string): Promise {
+function versionOf(file: string, env: Record): Promise {
const known = versions.get(file)
if (known && Date.now() - known.at < VERSION_KEEP_MS) return known.value
const value = new Promise((resolve) => {
try {
- const launch = launchArgv(file, ['--version'], { platform: process.platform, env: process.env, which: (b) => which(b) })
- execFile(launch.command, launch.args, { timeout: VERSION_MS, windowsHide: true, windowsVerbatimArguments: launch.verbatim, encoding: 'utf8' }, (error, stdout) => {
+ const launch = launchArgv(file, ['--version'], { platform: process.platform, env, which: (b) => which(b, env) })
+ execFile(launch.command, launch.args, { env, timeout: VERSION_MS, windowsHide: true, windowsVerbatimArguments: launch.verbatim, encoding: 'utf8' }, (error, stdout) => {
const line = String(stdout ?? '').trim().split('\n')[0] ?? ''
const found = /\d+\.\d+(?:\.\d+)?(?:[-+.][0-9A-Za-z.-]+)?/.exec(line)?.[0]
resolve(error && !found ? null : found ?? (line || null))
@@ -49,14 +100,15 @@ function versionOf(file: string): Promise {
export async function programStatus(kind: ProgramKind): Promise {
const p = PROGRAMS[kind]
- const file = locate(kind)
+ const found = await locateFound(kind)
+ const file = found.file
if (!file) {
const said = kind === 'antigravity'
? 'Antigravity was not found on this computer. Install it from antigravity.google, then open a new tab here.'
: `${p.title} was not found on this computer. Install it with the command below, then sign in once in a terminal.`
- return { installed: false, version: null, install: p.install, signedIn: null, title: p.title, said, finding: 'missing' }
+ return { installed: false, version: null, install: p.install, signedIn: null, title: p.title, said, finding: 'missing', looked: found.looked }
}
- return { installed: true, version: await versionOf(file), install: '', signedIn: null, title: p.title, finding: 'runs' }
+ return { installed: true, version: await versionOf(file, await agentEnv(file)), install: '', signedIn: null, title: p.title, finding: 'runs', path: file, how: found.how }
}
export function childEnv(extra: Record = {}): Record {
@@ -73,8 +125,8 @@ export function shellLaunch(): Launch {
return { command: process.env.SHELL || which('bash') || '/bin/sh', args: ['-l'] }
}
-export function programLaunch(file: string, args: string[]): Launch {
- const launch = launchArgv(file, args, { platform: process.platform, env: process.env, which: (b) => which(b) })
+export function programLaunch(file: string, args: string[], env: Record = process.env as Record): Launch {
+ const launch = launchArgv(file, args, { platform: process.platform, env, which: (b) => which(b, env) })
return { command: launch.command, args: launch.verbatim ? launch.args.join(' ') : launch.args }
}
diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts
index e25a336..d313843 100644
--- a/src/features/agents/index.ts
+++ b/src/features/agents/index.ts
@@ -19,7 +19,8 @@ import { z } from 'zod'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import type { Feature, FeatureContext } from '../types.js'
-import { CLIENT_IDS, clientStatus, currentEnv, findRoot, HTTP_CLIENT_IDS, installClient, installHttpClient, isHttpClient, serverEntry, type HttpEndpoint } from '../../agents/clients.js'
+import { CLIENT_IDS, clientStatus, currentEnv, findRoot, HTTP_CLIENT_IDS, installClient, installHttpClient, isHttpClient, serverEntry, which, type Env, type HttpEndpoint } from '../../agents/clients.js'
+import { locate, locateFound, toolEnv } from '../../dock/programs.js'
import { installRelayClient, relaySnippet, relayState } from '../../agents/relay-clients.js'
import { mcpToken, rotateMcpToken } from '../../mcp/token.js'
import { rotatePlayerLinks } from '../../server/player-link.js'
@@ -70,10 +71,30 @@ async function listTools(ctx: FeatureContext): Promise {
}
}
-function state(ep: HttpEndpoint) {
+interface Located { e: Env; find: (bin: string) => string | undefined; claudeBin: string | null }
+
+/**
+ * This account, with claude and codex found the way the dock finds them (src/dock/lookup.ts: the engine's PATH, the
+ * known install folders, the login shell's PATH), not by the engine's PATH alone: the desktop app started from the
+ * Finder or the Dock has launchd's short PATH. The claude command then runs with that PATH (Env.toolEnv). wait: a
+ * Connect press, which may wait for the shell to be asked again when claude is missing; a status read does not.
+ */
+async function located(wait: boolean): Promise {
const e = currentEnv()
+ const look = (kind: 'claude' | 'codex'): Promise => (wait ? locate(kind) : locateFound(kind).then((f) => f.file))
+ const [claude, codex] = await Promise.all([look('claude'), look('codex')])
+ const files: Record = { claude, codex }
+ return {
+ e: { ...e, toolEnv: await toolEnv(claude) },
+ find: (bin) => (bin in files ? files[bin] : which(bin)),
+ claudeBin: claude ?? null,
+ }
+}
+
+async function state(ep: HttpEndpoint, at?: Located) {
+ const { e, find } = at ?? (await located(false))
const entry = serverEntry({ root: findRoot(), e })
- return { entry, clients: clientStatus(entry, e, undefined, ep) }
+ return { entry, clients: clientStatus(entry, e, find, ep) }
}
export const feature: Feature = {
@@ -84,14 +105,14 @@ export const feature: Feature = {
if (parts.length === 2 && method === 'GET') {
toolNames ??= listTools(ctx).catch(() => [])
const http = await endpoint(ctx)
- const { entry, clients } = state(http)
+ const { entry, clients } = await state(http)
sendJson(res, 200, { server: entry, clients, tools: await toolNames, http, relay: await relayInfo(ctx) })
return true
}
if (parts.length === 4 && parts[2] === 'mcp-token' && parts[3] === 'rotate' && method === 'POST') {
await rotateMcpToken(ctx.dataDir)
const http = await endpoint(ctx)
- sendJson(res, 200, { http, clients: state(http).clients })
+ sendJson(res, 200, { http, clients: (await state(http)).clients })
return true
}
if (parts.length === 4 && parts[2] === 'player-links' && parts[3] === 'rotate' && method === 'POST') {
@@ -105,7 +126,7 @@ export const feature: Feature = {
sendJson(res, 400, { error: `send { "client": ${CLIENT_IDS.map((c) => `"${c}"`).join(' | ')} }` })
return true
}
- const e = currentEnv()
+ const { e, find, claudeBin } = await located(parsed.data.client === 'claude')
const entry = serverEntry({ root: findRoot(), e })
const http = await endpoint(ctx)
try {
@@ -115,8 +136,8 @@ export const feature: Feature = {
if (!relay.connected || !relay.url) sendJson(res, 409, { error: 'not connected to a relay; connect one in Settings, Relay' })
else if (!isHttpClient(id)) sendJson(res, 400, { error: `${id} cannot connect to a relay` })
else {
- const said = installRelayClient(id, { url: relay.url, e })
- sendJson(res, 200, { said, clients: clientStatus(entry, e, undefined, http), relay: await relayInfo(ctx) })
+ const said = installRelayClient(id, { url: relay.url, e, claudeBin })
+ sendJson(res, 200, { said, clients: clientStatus(entry, e, find, http), relay: await relayInfo(ctx) })
}
return true
}
@@ -124,8 +145,8 @@ export const feature: Feature = {
sendJson(res, 400, { error: `${id} cannot connect over HTTP` })
return true
}
- const said = parsed.data.transport === 'http' && isHttpClient(id) ? installHttpClient(id, { ep: http, e }) : installClient(id, { root: findRoot(), entry, e })
- sendJson(res, 200, { said, clients: clientStatus(entry, e, undefined, http) })
+ const said = parsed.data.transport === 'http' && isHttpClient(id) ? installHttpClient(id, { ep: http, e, claudeBin }) : installClient(id, { root: findRoot(), entry, e, claudeBin })
+ sendJson(res, 200, { said, clients: clientStatus(entry, e, find, http) })
} catch (error) {
sendJson(res, 500, { error: (error as Error).message })
}
diff --git a/src/features/library/transfer.ts b/src/features/library/transfer.ts
index ef48926..838fc0c 100644
--- a/src/features/library/transfer.ts
+++ b/src/features/library/transfer.ts
@@ -14,20 +14,29 @@ import { checkDirectory, LibraryError, type LibraryStore } from './store.js'
import { syncFolder, type FolderSync } from './sync-folder.js'
import type { ZipEntry } from './zip.js'
-/** The regular files of one recording folder (one level: recordings keep no subfolders). */
+const gone = (error: unknown): boolean => (error as NodeJS.ErrnoException)?.code === 'ENOENT'
+
+/**
+ * The regular files of one recording folder (one level: recordings keep no subfolders). A recording can be written
+ * to while it is exported (an atomic write's `..tmp`, a rendition's `.part`, a progress file deleted when
+ * the work ends): the work files are left out, and a file that is gone by the time it is looked at is not listed.
+ */
async function folderFiles(dir: string): Promise {
const out: string[] = []
for (const name of await readdir(dir).catch(() => [] as string[])) {
if (/\.(part|tmp)$/.test(name)) continue
- const info = await lstat(path.join(dir, name))
- if (info.isFile()) out.push(name)
+ const info = await lstat(path.join(dir, name)).catch((e: unknown) => { if (gone(e)) return undefined; throw e })
+ if (info?.isFile()) out.push(name)
}
return out.sort()
}
+/** Copies a recording's files; one deleted between the listing and its copy is skipped, as if listed a moment later. */
async function copyFolder(from: string, to: string): Promise {
await mkdir(to, { recursive: true, mode: 0o700 })
- for (const name of await folderFiles(from)) await cp(path.join(from, name), path.join(to, name))
+ for (const name of await folderFiles(from)) {
+ await cp(path.join(from, name), path.join(to, name)).catch((e: unknown) => { if (!gone(e)) throw e })
+ }
}
/** The ids to export: the ones asked for (each must exist), or every recording outside the Trash. */
@@ -49,7 +58,7 @@ export async function zipEntries(store: LibraryStore, ids?: string[]): Promise buildServer(o.deps, o.version, {}, remoteGate(o.dataDir)),
+ // Window commands reach the running app's window over its loopback API (window/bridge.ts remoteCaller).
+ build: () => buildServer({ ...o.deps, window: o.deps.window ?? remoteCaller(o.dataDir) }, o.version, {}, remoteGate(o.dataDir)),
tokens: async () => [await mcpToken(o.dataDir), ...(o.extraTokens ?? [])],
allowedOrigins: () => [],
allowedHosts: () => [wildcard ? '*' : host],
diff --git a/src/mcp/jobs.ts b/src/mcp/jobs.ts
new file mode 100644
index 0000000..849e3b2
--- /dev/null
+++ b/src/mcp/jobs.ts
@@ -0,0 +1,134 @@
+/**
+ * Long operations as jobs: formrec_job_start runs any other FormREC tool in the background and answers at once with a
+ * job id; formrec_job_status polls it (state, the tool's progress notifications, and its result once done);
+ * formrec_job_cancel stops it (the tool's cancellation signal, as an MCP cancel would). Recording a walkthrough,
+ * exporting, transcribing, making clips, rendering a voice-over or checking freshness can take minutes; a client with
+ * a short request timeout uses these instead of waiting on the tool itself.
+ *
+ * The started tool runs exactly as it would if called directly (same arguments, checked with its own schema, same
+ * answer shape and player links); the consent gate asks once, for formrec_job_start, naming the tool in its summary.
+ * Jobs live in this process's memory: an hour after they end they are dropped, and at most MAX_JOBS are kept.
+ */
+import { randomUUID } from 'node:crypto'
+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
+import { z } from 'zod'
+import { failure, READ_ONLY, reply, UPDATES, WRITES, type ToolReply } from './reply.js'
+
+export const JOB_TOOLS = ['formrec_job_start', 'formrec_job_status', 'formrec_job_cancel'] as const
+const MAX_JOBS = 100
+const KEEP_MS = 60 * 60 * 1000
+
+/** What a job needs from the tool it runs: its own argument check and its handler (with the server's link fixing). */
+export interface JobTarget {
+ check(args: unknown): { ok: true; value: unknown } | { ok: false; error: string }
+ run(args: unknown, extra: Record): Promise
+}
+
+interface Job {
+ id: string
+ tool: string
+ state: 'running' | 'done' | 'failed' | 'cancelled'
+ startedAt: string
+ endedAt?: string
+ progress?: { progress: number; total?: number; message?: string }
+ reply?: ToolReply
+ abort: AbortController
+ ended?: number
+}
+
+// One table per process, so a job started on one MCP session can be polled from another.
+const jobs = new Map()
+
+function prune(): void {
+ const now = Date.now()
+ for (const [id, j] of jobs) if (j.ended !== undefined && now - j.ended > KEEP_MS) jobs.delete(id)
+ if (jobs.size < MAX_JOBS) return
+ for (const [id, j] of [...jobs].filter(([, j]) => j.ended !== undefined).sort((a, b) => a[1].ended! - b[1].ended!)) {
+ if (jobs.size < MAX_JOBS) break
+ jobs.delete(id)
+ }
+}
+
+/** The compact view of a job: the result as the tool gave it (structured when it has one, else its text). */
+function view(j: Job, withResult: boolean): Record {
+ const out: Record = { jobId: j.id, tool: j.tool, state: j.state, startedAt: j.startedAt }
+ if (j.endedAt) out['endedAt'] = j.endedAt
+ if (j.progress) out['progress'] = j.progress
+ if (withResult && j.reply) {
+ if (j.reply.isError) out['error'] = j.reply.content.map((c) => c.text).join('\n')
+ else out['result'] = j.reply.structuredContent ?? j.reply.content.map((c) => c.text).join('\n')
+ }
+ return out
+}
+
+export function registerJobTools(server: McpServer, find: (tool: string) => JobTarget | string): void {
+ server.registerTool(
+ 'formrec_job_start',
+ {
+ title: 'Start a tool as a background job',
+ description:
+ 'Run any other FormREC tool (for example formrec_record, formrec_export, formrec_edit_export, formrec_transcribe, formrec_make_clips, formrec_voiceover, formrec_walkthrough_rerecord) in the background and answer at once with a jobId. Poll formrec_job_status every few seconds until state is done, failed or cancelled; the result is then exactly what the tool would have answered. Use it for anything that can take more than a few seconds.',
+ inputSchema: {
+ tool: z.string().min(1).max(80).describe('the tool to run, for example formrec_record'),
+ args: z.record(z.string(), z.unknown()).optional().describe('that tool\'s arguments'),
+ },
+ annotations: WRITES,
+ },
+ async (input, extra) => {
+ if (input.tool.startsWith('formrec_job_')) return failure(new Error('a job cannot start another job tool'))
+ const target = find(input.tool)
+ if (typeof target === 'string') return failure(new Error(target))
+ const checked = target.check(input.args ?? {})
+ if (!checked.ok) return failure(new Error(`${input.tool}: ${checked.error}`))
+ prune()
+ if ([...jobs.values()].filter((j) => j.state === 'running').length >= 16) return failure(new Error('16 jobs are running already; wait for one to end'))
+ const job: Job = { id: `job-${randomUUID().slice(0, 12)}`, tool: input.tool, state: 'running', startedAt: new Date().toISOString(), abort: new AbortController() }
+ jobs.set(job.id, job)
+ const inner: Record = {
+ signal: job.abort.signal,
+ requestId: job.id,
+ authInfo: (extra as { authInfo?: unknown }).authInfo,
+ _meta: { progressToken: job.id },
+ sendNotification: async (n: { method?: string; params?: { progress?: number; total?: number; message?: string } }) => {
+ if (n.method === 'notifications/progress' && n.params) job.progress = { progress: n.params.progress ?? 0, total: n.params.total, message: n.params.message }
+ },
+ sendRequest: async () => { throw new Error('a background job cannot ask the client') },
+ }
+ void target.run(checked.value, inner).then(
+ (r) => { job.reply = r; job.state = job.abort.signal.aborted ? 'cancelled' : r.isError ? 'failed' : 'done' },
+ (e: unknown) => { job.reply = failure(e); job.state = job.abort.signal.aborted ? 'cancelled' : 'failed' },
+ ).finally(() => { job.ended = Date.now(); job.endedAt = new Date(job.ended).toISOString() })
+ return reply(() => ({ jobId: job.id, tool: job.tool, state: job.state, poll: 'formrec_job_status' }))
+ },
+ )
+ server.registerTool(
+ 'formrec_job_status',
+ {
+ title: 'Poll a background job',
+ description: 'A job\'s state (running, done, failed, cancelled), its latest progress, and once it ended the tool\'s result or error. Without jobId: every job of this server, newest first, without results.',
+ inputSchema: { jobId: z.string().max(60).optional().describe('the id formrec_job_start answered') },
+ annotations: READ_ONLY,
+ },
+ (input) => reply(() => {
+ if (!input.jobId) return { jobs: [...jobs.values()].reverse().map((j) => view(j, false)) }
+ const j = jobs.get(input.jobId)
+ if (!j) throw new Error(`no job ${input.jobId} (jobs are kept for an hour after they end)`)
+ return view(j, true)
+ }),
+ )
+ server.registerTool(
+ 'formrec_job_cancel',
+ {
+ title: 'Cancel a background job',
+ description: 'Stop a running job, as cancelling the tool call would (formrec_record saves nothing when cancelled). A job that already ended is left as it is.',
+ inputSchema: { jobId: z.string().max(60).describe('the job to stop') },
+ annotations: UPDATES,
+ },
+ (input) => reply(() => {
+ const j = jobs.get(input.jobId)
+ if (!j) throw new Error(`no job ${input.jobId}`)
+ if (j.state === 'running') j.abort.abort()
+ return view(j, false)
+ }),
+ )
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 9aa48e0..760079a 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -21,6 +21,9 @@ import { DESTRUCTIVE, OPEN_WORLD, READ_ONLY, UPDATES, reply, type ToolReply } fr
import { keyReply } from './player-links.js'
import { DeleteOutput, DemosOutput, FormcutOutput, GetOutput, ListOutput, RecordOutput, RenameOutput, ValidateOutput } from './schemas.js'
import { FEATURES } from '../features/index.js'
+import { registerJobTools, JOB_TOOLS, type JobTarget } from './jobs.js'
+import { registerWindowTools, WINDOW_TOOLS } from '../window/tools.js'
+import { remoteCaller } from '../window/bridge.js'
const walkInput = {
walkthrough: z.record(z.string(), z.unknown()).optional().describe('the walkthrough object (see formrec_guide)'),
@@ -42,6 +45,24 @@ export const CORE_TOOLS = [
'formrec_demos',
] as const
+/**
+ * Registered right after the core tools, but only where the server has a window caller (the app's /mcp,
+ * `formrec mcp` and `formrec mcp --http`): the window's commands and background jobs. Not on the relay's bridge.
+ */
+export const WINDOW_AND_JOB_TOOLS = [...WINDOW_TOOLS, ...JOB_TOOLS] as const
+
+/** The ids a tool's arguments or answer name: the recordings a window should show again after an agent changed them. */
+function changedIds(args: unknown, out: ToolReply): string[] {
+ const ids: string[] = []
+ const take = (v: unknown): void => { if (typeof v === 'string') ids.push(v); else if (Array.isArray(v)) for (const x of v) if (typeof x === 'string') ids.push(x) }
+ const a = (args && typeof args === 'object' ? args : {}) as Record
+ for (const k of ['id', 'ids', 'recordingId', 'recordingIds']) take(a[k])
+ const s = out.structuredContent ?? {}
+ take(s['id'])
+ take((s['recording'] as { id?: unknown } | undefined)?.id)
+ return ids
+}
+
/**
* Which tools a server offers. Stdio, HTTP inside the app and `formrec mcp --http` offer all of them (no `ToolSet`);
* the relay passes the subset a remote agent may use. Names not listed are not registered at all.
@@ -72,19 +93,38 @@ export function buildServer(deps: ToolDeps, version: string, tools: ToolSet = {}
const registered = new Map()
const register = server.registerTool.bind(server)
const base = (): Promise => resolvePlayerBase(deps.playerBase)
+ // What a background job runs (jobs.ts): the tool's own handler, after the consent formrec_job_start already passed.
+ const runners = new Map()
server.registerTool = ((name: string, ...rest: unknown[]) => {
// Every answer's player links get their form in one place (player-links.ts): no run token, a player key per recording.
const handler = rest[rest.length - 1] as (...args: unknown[]) => unknown
- const config = rest[0] as { title?: string; annotations?: { readOnlyHint?: boolean } } | undefined
- const asks = consent !== undefined && config?.annotations?.readOnlyHint !== true
+ const config = rest[0] as { title?: string; inputSchema?: Record | z.ZodType; annotations?: { readOnlyHint?: boolean } } | undefined
+ const reads = config?.annotations?.readOnlyHint === true
+ const asks = consent !== undefined && !reads
+ const finish = async (args: unknown, out: ToolReply): Promise => {
+ const keyedOut = await keyReply(out, base, deps.library.dataDir)
+ // An agent's change shows in the open window at once (window/bridge.ts `changed`).
+ if (!reads && !keyedOut.isError && deps.window && !name.startsWith('formrec_window_') && !name.startsWith('formrec_job_')) deps.window.changed(changedIds(args, keyedOut), name)
+ return keyedOut
+ }
const keyed = async (...args: unknown[]): Promise => {
if (asks) {
const extra = args[args.length - 1] as { authInfo?: { token?: string } } | undefined
const why = await consent({ agent: server.server.getClientVersion()?.name ?? '', tool: name, title: config?.title, args: args.length > 1 ? args[0] : undefined, token: extra?.authInfo?.token })
if (why) return { content: [{ type: 'text', text: why }], isError: true }
}
- return keyReply((await handler(...args)) as ToolReply, base, deps.library.dataDir)
+ return finish(args.length > 1 ? args[0] : undefined, (await handler(...args)) as ToolReply)
}
+ const shape = config?.inputSchema
+ const schema = shape === undefined ? undefined : shape instanceof z.ZodType ? shape : z.object(shape)
+ runners.set(name, {
+ check: (args) => {
+ if (!schema) return { ok: true, value: undefined }
+ const parsed = schema.safeParse(args)
+ return parsed.success ? { ok: true, value: parsed.data } : { ok: false, error: parsed.error.issues.map((i) => `${i.path.join('.') || 'args'}: ${i.message}`).join('; ') }
+ },
+ run: async (args, extra) => finish(args, (await (schema ? handler(args, extra) : handler(extra))) as ToolReply),
+ })
const tool = (register as (n: string, ...r: unknown[]) => RegisteredTool)(name, ...rest.slice(0, -1), keyed)
registered.set(name, tool)
return tool
@@ -224,6 +264,17 @@ export function buildServer(deps: ToolDeps, version: string, tools: ToolSet = {}
},
() => reply(() => demosTool(deps), { structured: true }),
)
+ if (deps.window) {
+ registerWindowTools(server, deps.window, () => server.server.getClientVersion()?.name ?? '')
+ // A job may run only what this server offers: not a tool removed below, nor one its scope disabled.
+ registerJobTools(server, (tool) => {
+ const r = registered.get(tool)
+ const runner = runners.get(tool)
+ if (!r || !runner) return `no tool ${tool} on this server`
+ if (!r.enabled) return `${tool} is not offered on this server`
+ return runner
+ })
+ }
if (tools.core) {
for (const [name, tool] of [...registered]) {
if (tools.core.includes(name)) continue
@@ -246,5 +297,7 @@ export function buildServer(deps: ToolDeps, version: string, tools: ToolSet = {}
}
export async function serveMcp(deps: ToolDeps, version: string): Promise {
- await buildServer(deps, version, {}, remoteGate(deps.library.dataDir)).connect(new StdioServerTransport())
+ // Window commands reach the running app's window over its loopback API (window/bridge.ts remoteCaller).
+ const withWindow: ToolDeps = { ...deps, window: deps.window ?? remoteCaller(deps.library.dataDir) }
+ await buildServer(withWindow, version, {}, remoteGate(deps.library.dataDir)).connect(new StdioServerTransport())
}
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 0286c02..96f9983 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -30,6 +30,8 @@ export interface ToolDeps {
demosDir?: string
/** Open a recording in FormCut (tests); default: find FormCut's engine and call it over JSON-RPC. */
formcut?: (rec: Recording) => Promise<{ projectId: string; clips: number }>
+ /** The open window's commands (window/bridge.ts). Given: formrec_window_* and formrec_job_* are offered, and changes are announced. */
+ window?: import('../window/bridge.js').WindowCaller
}
export type PlayerBase = string | (() => Promise)
diff --git a/src/server/http.ts b/src/server/http.ts
index 98f0a60..cad112d 100644
--- a/src/server/http.ts
+++ b/src/server/http.ts
@@ -39,8 +39,8 @@ export const MEDIA = /^(video\.webm|captions\.vtt|chapters\.vtt|track-[a-z0-9][a
const CLIENT_FILE = /^(?:(?:features|styles|dock)\/)?[a-z0-9-]+\.(html|js|css)$/
const VENDOR_WASM = 'rnnoise.wasm'
/** The demos that ship in web/demos (the client's demos.ts lists the same ids). */
-export const DEMO_IDS = new Set(['self-tour', 'studio-guest', 'podcast-episode'])
-const DEMO_FILE = /^(recording\.json|poster\.png|video\.webm|captions\.vtt|chapters\.vtt|track-[a-z0-9][a-z0-9-]{0,40}\.webm)$/
+export const DEMO_IDS = new Set(['self-tour', 'studio-guest', 'podcast-episode', 'formvis-walkthrough', 'formportal-walkthrough'])
+const DEMO_FILE = /^(recording\.json|poster\.png|video\.webm|captions\.vtt|chapters\.vtt|comments\.json|track-[a-z0-9][a-z0-9-]{0,40}\.webm)$/
/** The official in-app mark at the sizes the shell shows, and the favicon (web/brand). Nothing else is served from there. */
export const BRAND_FILES = new Set([
...['dark', 'light'].flatMap((tone) => [40, 64, 128, 192].map((size) => `mark-${tone}-${size}.png`)),
diff --git a/src/window/bridge.ts b/src/window/bridge.ts
new file mode 100644
index 0000000..ba33874
--- /dev/null
+++ b/src/window/bridge.ts
@@ -0,0 +1,250 @@
+/**
+ * The agent bridge to the open window: the app's whole command registry (web/src/features/registry.ts `commands`,
+ * every menu item, sidebar page, recording action, player control and client preference) offered to agents, as
+ * FormDeck's list_commands and run_command and FormCite's window_commands do.
+ *
+ * The window keeps one event stream open (server-sent events read with fetch, since an EventSource cannot send the
+ * token): the app's window reads these events on the consent stream, `GET /api/mcp/consent/stream?window=1`, and
+ * `GET /api/window/stream` carries them alone for any other client. The engine sends it calls ({ type: 'call', callId, op, ... }) and the window
+ * answers each with `POST /api/window/result`. The window that last took focus answers; the others are spares. The
+ * same stream carries `changed` notices, sent after an agent's tool changed something, so the window shows the change
+ * at once (web/src/agent-bridge.ts).
+ *
+ * Routes (behind the run's token, like every /api route):
+ * GET /api/window/stream the window's end: events hello, call (list, describe, run) and changed
+ * (the app's window takes them on /api/mcp/consent/stream?window=1)
+ * POST /api/window/result { callId, ok, value?, error? } the window's answer to a call
+ * POST /api/window/focus { windowId } this window answers the next calls
+ * GET /api/window/commands?query=&id= the window's commands (id, label, args, risk), or one described in full
+ * POST /api/window/run { id, args?, agent? } runs one; destructive, external and privacy ones ask the person first
+ * POST /api/window/changed { ids, tool } an agent in another process (`formrec mcp`) changed these recordings
+ *
+ * Approval: a command whose risk is destructive, external or privacy (deleting, publishing outside this computer, the
+ * camera, microphone or screen) asks the person in the window every time an agent runs it, through the dock's consent
+ * dialog, whoever the agent is. Outside agents are also asked once for the tool itself by the MCP consent gate.
+ */
+import { randomUUID } from 'node:crypto'
+import http from 'node:http'
+import type { IncomingMessage, ServerResponse } from 'node:http'
+import { readJsonBody } from '../server/files.js'
+import { readConsent, type ConsentBroker } from '../mcp/consent.js'
+import { liveServers } from '../store/server-file.js'
+import { loadToken } from '../server/token.js'
+
+export const CALL_MS = 15_000
+const RISKY = new Set(['destructive', 'external', 'privacy'])
+
+export type WindowEvent =
+ | { type: 'hello'; windowId: string }
+ | { type: 'call'; callId: string; op: 'list' | 'describe' | 'run'; id?: string; args?: Record; query?: string }
+ | { type: 'changed'; ids: string[]; tool: string }
+
+/** What `describe` answers for one command (the window builds it, web/src/agent-bridge.ts). */
+export interface CommandInfo {
+ id: string
+ label: string
+ risk: string
+ unavailable?: string
+ params?: Record
+}
+
+/** What the MCP tools call: in the app the bridge itself, from `formrec mcp` the running app over HTTP. */
+export interface WindowCaller {
+ commands(input: { query?: string; id?: string; limit?: number }): Promise
+ run(input: { id: string; args?: Record; agent: string }): Promise
+ /** An agent changed these recordings (or the library, when ids is empty); open windows show it. Never throws. */
+ changed(ids: string[], tool: string): void
+}
+
+export class NoWindow extends Error {
+ constructor() {
+ super('No FormREC window is open, so window commands cannot run. Ask the person to open FormREC (formrec, or the desktop app), or use the engine tools, which work without a window.')
+ }
+}
+
+interface Win { send(event: WindowEvent): void; focusedAt: number }
+
+export class WindowBridge {
+ private readonly windows = new Map()
+ private readonly pending = new Map()
+
+ open(): number {
+ return this.windows.size
+ }
+
+ /** The window's end on its own event stream, which lives as long as the request. */
+ stream(req: IncomingMessage, res: ServerResponse): void {
+ res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' })
+ this.attach(req, res)
+ const beat = setInterval(() => { if (!res.writableEnded) res.write(': keep\n\n') }, 25_000)
+ beat.unref()
+ req.on('close', () => clearInterval(beat))
+ }
+
+ /**
+ * The window's end on an event stream that is already open: the app's window reads the consent stream with
+ * `?window=1` (src/dock/index.ts) and takes these events from it, so a window holds one long request, not two, of
+ * the six a browser opens to one host (the player's media and the studio's uploads need the rest).
+ */
+ attach(req: IncomingMessage, res: ServerResponse): void {
+ if (res.destroyed || res.writableEnded) return
+ const windowId = randomUUID()
+ const send = (event: WindowEvent): void => { if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`) }
+ this.windows.set(windowId, { send, focusedAt: Date.now() })
+ send({ type: 'hello', windowId })
+ req.on('close', () => { this.windows.delete(windowId) })
+ }
+
+ focus(windowId: string): boolean {
+ const w = this.windows.get(windowId)
+ if (w) w.focusedAt = Date.now()
+ return w !== undefined
+ }
+
+ result(body: { callId?: unknown; ok?: unknown; value?: unknown; error?: unknown }): boolean {
+ const p = typeof body.callId === 'string' ? this.pending.get(body.callId) : undefined
+ if (!p) return false
+ this.pending.delete(body.callId as string)
+ clearTimeout(p.timer)
+ if (body.ok === true) p.resolve(body.value)
+ else p.reject(new Error(typeof body.error === 'string' && body.error ? body.error.slice(0, 2000) : 'the window refused the command'))
+ return true
+ }
+
+ /** Ask the window that took focus last. */
+ call(op: 'list' | 'describe' | 'run', payload: { id?: string; args?: Record; query?: string }, ms = CALL_MS): Promise {
+ const front = [...this.windows.values()].sort((a, b) => b.focusedAt - a.focusedAt)[0]
+ if (!front) return Promise.reject(new NoWindow())
+ const callId = randomUUID()
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(callId)
+ reject(new Error(`The FormREC window did not answer within ${Math.round(ms / 1000)} seconds. It may be busy or hidden; if the command was started it may still finish there.`))
+ }, ms)
+ timer.unref()
+ this.pending.set(callId, { resolve, reject, timer })
+ front.send({ type: 'call', callId, op, ...payload })
+ })
+ }
+
+ changed(ids: string[], tool: string): void {
+ const clean = [...new Set(ids.filter((i) => typeof i === 'string' && /^[a-z0-9][a-z0-9-]{0,80}$/.test(i)))].slice(0, 50)
+ for (const w of this.windows.values()) w.send({ type: 'changed', ids: clean, tool })
+ }
+}
+
+/** Runs a command in the window, asking the person first when its risk calls for it. */
+export async function runWithApproval(bridge: WindowBridge, consent: ConsentBroker | undefined, dataDir: string, input: { id: string; args?: Record; agent: string }): Promise {
+ const info = (await bridge.call('describe', { id: input.id, args: input.args ?? {} })) as CommandInfo
+ if (info.unavailable) throw new Error(`${input.id} cannot run now: ${info.unavailable}`)
+ if (RISKY.has(info.risk)) {
+ if ((await readConsent(dataDir)).policy === 'blocked') throw new Error(`Outside agents are blocked in FormREC (Preferences, Agents), so ${input.id} did not run.`)
+ if (!consent) throw new Error(`${input.id} needs the person's approval and this server cannot ask; run it from the FormREC app's MCP.`)
+ const name = info.label.length <= 60 ? info.label : input.id
+ const verdict = await consent.ask({ agent: input.agent, tool: 'formrec_window_command_run', title: `Run ${name} (${info.risk})`, args: { command: input.id, ...(input.args ?? {}) } })
+ if (verdict !== 'allow') {
+ const why = verdict === 'deny' ? 'The person declined it' : verdict === 'timeout' ? 'The person did not answer in time' : 'No FormREC window could ask the person'
+ throw new Error(`${why}, so ${input.id} (${info.risk}) did not run. Do not retry without asking them.`)
+ }
+ }
+ const value = await bridge.call('run', { id: input.id, args: input.args ?? {} })
+ return { ok: true, id: input.id, risk: info.risk, ...(value === undefined || value === null ? {} : { value }) }
+}
+
+export function localCaller(bridge: WindowBridge, consent: ConsentBroker | undefined, dataDir: string): WindowCaller {
+ return {
+ commands: (input) => bridge.call(input.id ? 'describe' : 'list', input.id ? { id: input.id } : { query: input.query, args: { limit: input.limit ?? 200 } }),
+ run: (input) => runWithApproval(bridge, consent, dataDir, input),
+ changed: (ids, tool) => bridge.changed(ids, tool),
+ }
+}
+
+function request(port: number, token: string, method: string, path: string, payload?: unknown): Promise {
+ const body = payload === undefined ? '' : JSON.stringify(payload)
+ return new Promise((resolve, reject) => {
+ const req = http.request({ host: '127.0.0.1', port, path, method, headers: { Authorization: `Bearer ${token}`, ...(body ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } : {}) } }, (res) => {
+ const chunks: Buffer[] = []
+ res.on('data', (c: Buffer) => chunks.push(c))
+ res.on('end', () => {
+ let value: unknown
+ try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { value = undefined }
+ if ((res.statusCode ?? 500) >= 400) reject(new Error(typeof (value as { error?: unknown })?.error === 'string' ? (value as { error: string }).error : `the FormREC app answered ${res.statusCode}`))
+ else resolve(value)
+ })
+ res.on('error', reject)
+ })
+ req.setTimeout(200_000, () => req.destroy(new Error('the FormREC app did not answer')))
+ req.on('error', reject)
+ req.end(body)
+ })
+}
+
+/** For `formrec mcp` (stdio or --http on its own port): the running app's bridge, found through its server file. */
+export function remoteCaller(dataDir: string): WindowCaller {
+ const target = async (): Promise<{ port: number; token: string }> => {
+ const token = await loadToken(dataDir).catch(() => '')
+ const server = token ? (await liveServers(dataDir, token).catch(() => []))[0] : undefined
+ if (!server) throw new NoWindow()
+ return { port: server.port, token }
+ }
+ return {
+ async commands(input) {
+ const t = await target()
+ const q = new URLSearchParams()
+ if (input.query) q.set('query', input.query)
+ if (input.id) q.set('id', input.id)
+ if (input.limit) q.set('limit', String(input.limit))
+ return request(t.port, t.token, 'GET', `/api/window/commands?${q}`)
+ },
+ async run(input) {
+ const t = await target()
+ return request(t.port, t.token, 'POST', '/api/window/run', input)
+ },
+ changed(ids, tool) {
+ void target().then((t) => request(t.port, t.token, 'POST', '/api/window/changed', { ids, tool }), () => undefined).catch(() => undefined)
+ },
+ }
+}
+
+function sendJson(res: ServerResponse, status: number, body: unknown): void {
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }).end(JSON.stringify(body))
+}
+
+const obj = (v: unknown): Record => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : {})
+
+/** The /api/window routes. */
+export function windowRoutes(bridge: WindowBridge, consent: ConsentBroker | undefined, dataDir: string) {
+ return async (req: IncomingMessage, res: ServerResponse, parts: string[], url: URL): Promise => {
+ if (parts[1] !== 'window' || parts.length !== 3) return false
+ const what = parts[2]
+ const method = req.method ?? 'GET'
+ try {
+ if (what === 'stream' && method === 'GET') { bridge.stream(req, res); return true }
+ if (what === 'result' && method === 'POST') { sendJson(res, bridge.result(obj(await readJsonBody(req, 1024 * 1024))) ? 200 : 404, {}); return true }
+ if (what === 'focus' && method === 'POST') { const b = obj(await readJsonBody(req, 4096)); sendJson(res, 200, { ok: bridge.focus(String(b['windowId'] ?? '')) }); return true }
+ if (what === 'commands' && method === 'GET') {
+ const id = url.searchParams.get('id') ?? undefined
+ const limit = Number(url.searchParams.get('limit') ?? 200)
+ sendJson(res, 200, await localCaller(bridge, consent, dataDir).commands({ id, query: url.searchParams.get('query') ?? undefined, limit }))
+ return true
+ }
+ if (what === 'run' && method === 'POST') {
+ const b = obj(await readJsonBody(req, 256 * 1024))
+ if (typeof b['id'] !== 'string' || !b['id']) { sendJson(res, 400, { error: 'id is required' }); return true }
+ const agent = typeof b['agent'] === 'string' ? b['agent'] : ''
+ sendJson(res, 200, await runWithApproval(bridge, consent, dataDir, { id: b['id'], args: obj(b['args']), agent }))
+ return true
+ }
+ if (what === 'changed' && method === 'POST') {
+ const b = obj(await readJsonBody(req, 64 * 1024))
+ bridge.changed(Array.isArray(b['ids']) ? (b['ids'] as unknown[]).filter((i): i is string => typeof i === 'string') : [], typeof b['tool'] === 'string' ? b['tool'].slice(0, 80) : '')
+ sendJson(res, 200, {})
+ return true
+ }
+ } catch (error) {
+ sendJson(res, error instanceof NoWindow ? 409 : 400, { error: (error as Error).message })
+ return true
+ }
+ return false
+ }
+}
diff --git a/src/window/tools.ts b/src/window/tools.ts
new file mode 100644
index 0000000..d3326f2
--- /dev/null
+++ b/src/window/tools.ts
@@ -0,0 +1,42 @@
+/**
+ * formrec_window_commands and formrec_window_command_run: the open window's command registry for agents (bridge.ts).
+ * Registered by buildServer when it is given a WindowCaller; the relay's bridge is not (no window there).
+ */
+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
+import { z } from 'zod'
+import { READ_ONLY, reply, UPDATES } from '../mcp/reply.js'
+import type { WindowCaller } from './bridge.js'
+
+export const WINDOW_TOOLS = ['formrec_window_commands', 'formrec_window_command_run'] as const
+
+export function registerWindowTools(server: McpServer, caller: WindowCaller, agent: () => string): void {
+ server.registerTool(
+ 'formrec_window_commands',
+ {
+ title: 'List or describe the window\'s commands',
+ description:
+ 'Every action a person can take in the open FormREC window, as commands: pages (nav.go), menus (file.*, view.*, help.*), the studio (studio.*: start, pause, stop, camera...), drawing (annotate.*), the player (player.play, player.seek, player.panel), recording actions from the library card and player menus (recording.action), Preferences (settings.open, prefs.get, prefs.set) and each feature\'s commands. Without id: a compact list (id, label, args as `name?: type`, risk), filtered by query words. With id: that command\'s full arguments (types, allowed values, ranges) and whether it can run now. window says which page is open. Use the engine tools for data (they work without a window); use these to make the window do what the person would click.',
+ inputSchema: {
+ query: z.string().max(200).optional().describe('words that must all appear in the id or label, for example "studio" or "theme"'),
+ id: z.string().max(120).optional().describe('describe this one command'),
+ limit: z.number().int().min(1).max(500).optional().describe('at most this many (default 200)'),
+ },
+ annotations: READ_ONLY,
+ },
+ (input) => reply(() => caller.commands(input)),
+ )
+ server.registerTool(
+ 'formrec_window_command_run',
+ {
+ title: 'Run a window command',
+ description:
+ 'Run one command in the open FormREC window by id with its args (see formrec_window_commands), exactly as if the person chose it: the window shows the result at once. Commands that delete, publish outside this computer, or turn on the camera, microphone or screen ask the person in the window every time and fail if they decline. Returns { ok, id, risk, value? } with what the command reports (for example prefs.get\'s values, or the page it opened). Fails when no window is open or the command cannot run now (no studio open, no recording open), saying why.',
+ inputSchema: {
+ id: z.string().min(1).max(120).describe('the command id, for example nav.go, studio.start or recording.action'),
+ args: z.record(z.string(), z.unknown()).optional().describe('the command\'s arguments, for example { "page": "library" }'),
+ },
+ annotations: UPDATES,
+ },
+ (input) => reply(() => caller.run({ id: input.id, args: input.args, agent: agent() })),
+ )
+}
diff --git a/tests/keycast-walkthrough.test.ts b/tests/keycast-walkthrough.test.ts
index 95d02c4..17df5c0 100644
--- a/tests/keycast-walkthrough.test.ts
+++ b/tests/keycast-walkthrough.test.ts
@@ -50,11 +50,13 @@ async function owner(p: string, method = 'GET', body?: unknown): Promise<{ statu
return { status: res.status, body: await res.json().catch(() => ({})) }
}
+// The recording's features may still be writing (transcripts, AI outputs): an atomic write's `..tmp` or a
+// `.part` is renamed away at any moment, so it is not listed; the file it becomes is, and is read below.
async function* files(dir: string): AsyncGenerator {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) yield* files(full)
- else yield full
+ else if (!/\.(part|tmp)$/.test(entry.name)) yield full
}
}
@@ -114,8 +116,10 @@ describe('the runner records keys', () => {
const dir = app.features.library.folder(id)
const seen: string[] = []
for await (const file of files(dir)) {
+ // A file deleted between the listing and the read (a work file removed when the work ends) holds nothing now.
+ const bytes = await readFile(file).catch((e: NodeJS.ErrnoException) => { if (e.code === 'ENOENT') return undefined; throw e })
+ if (!bytes) continue
seen.push(path.relative(dir, file))
- const bytes = await readFile(file)
expect(bytes.includes(Buffer.from(SECRET)), `${file} holds the secret`).toBe(false)
expect(bytes.includes(Buffer.from(encodeURIComponent(SECRET))), `${file} holds the encoded secret`).toBe(false)
}
diff --git a/tests/live-audit3.test.ts b/tests/live-audit3.test.ts
index 33680c0..64a3221 100644
--- a/tests/live-audit3.test.ts
+++ b/tests/live-audit3.test.ts
@@ -7,7 +7,7 @@
*/
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { spawn, spawnSync, type ChildProcess } from 'node:child_process'
-import { existsSync, readdirSync } from 'node:fs'
+import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import https from 'node:https'
import net, { type AddressInfo } from 'node:net'
@@ -163,6 +163,18 @@ function dtsOf(file: string): Map {
return by
}
+/** The last dts (seconds) of any stream in a file an ingest server writes (0 while it has none). */
+const feedSeconds = (file: string): number => Math.max(0, ...[...dtsOf(file).values()].map((l) => l.length > 0 ? l[l.length - 1]! : 0))
+
+/** Whether something listens on this TCP port (from /proc/net/tcp, without connecting: FFmpeg's -listen 1 takes one). */
+function listening(port: number): boolean {
+ const hex = `:${port.toString(16).toUpperCase().padStart(4, '0')}`
+ return ['/proc/net/tcp', '/proc/net/tcp6'].some((f) => existsSync(f) && readFileSync(f, 'utf8').split('\n').some((l) => {
+ const [, local, , st] = l.trim().split(/\s+/)
+ return local?.endsWith(hex) === true && st === '0A'
+ }))
+}
+
/** The number of the newest segment the playlist lists (the media sequence only moves once the window is full). */
const sequenceOf = (playlist: string): number => Math.max(-1, ...[...playlist.matchAll(/seg-(\d+)\.m4s/g)].map((m) => Number(m[1])))
@@ -319,7 +331,10 @@ maybe('one take with an RTMP destination and a live link at once', () => {
}, 200_000)
it('starts the destinations again on a take whose link is on, after stopping them, and the link never stops', async () => {
- const made = { screen: webm('a3c-screen', 'screen', 60), camera: webm('a3c-camera', 'camera', 60), mic: webm('a3c-mic', 'mic', 60) }
+ // 120 seconds of feed, a second a chunk: on a slow runner the restarted destination took three connections and the
+ // feed ran out before the second server had more than a second of it.
+ const parts = 120
+ const made = { screen: webm('a3c-screen', 'screen', parts), camera: webm('a3c-camera', 'camera', parts), mic: webm('a3c-mic', 'mic', parts) }
const port = await freePort()
const first = rtmpServer(port, 'a3-d')
const dest = (await call('/api/live/destinations', 'PUT', { name: 'Local3', url: `rtmp://127.0.0.1:${port}/live`, key: KEY, enabled: true })).json.id as string
@@ -335,9 +350,9 @@ maybe('one take with an RTMP destination and a live link at once', () => {
let sent = 0
let running = true
const player = (async () => {
- while (running && sent < 60) {
+ while (running && sent < parts) {
for (const t of tracks) {
- const size = Math.ceil(t.data.length / 60)
+ const size = Math.ceil(t.data.length / parts)
await call(`/api/sessions/${id}/tracks/${t.id}/chunks?seq=${t.seq}`, 'POST', undefined, t.data.subarray(sent * size, (sent + 1) * size))
t.seq += 1
}
@@ -357,7 +372,7 @@ maybe('one take with an RTMP destination and a live link at once', () => {
const port2 = await freePort()
const second = rtmpIngest(port2, 'a3-e')
await call('/api/live/destinations', 'PUT', { id: dest, name: 'Local3', url: `rtmp://127.0.0.1:${port2}/live`, enabled: true })
- await new Promise((r) => setTimeout(r, 1500))
+ await until('the second server listening', () => listening(port2) || !second.alive(), 15_000)
expect(second.alive(), 'the second server listens').toBe(true)
const at = sequenceOf(await playlist())
const again = await call(`/api/live/${id}`, 'POST', {})
@@ -373,6 +388,8 @@ maybe('one take with an RTMP destination and a live link at once', () => {
expect(JSON.parse((await viewer(`/s-api/${liveId}/live/state`)).body).state).toBe('live')
// A second start while destinations run still says so.
expect((await call(`/api/live/${id}`, 'POST', {})).status).toBe(409)
+ // The feed runs on until the second server has more than two seconds of it (checked again from the whole file).
+ await until('the second server receiving the feed', () => feedSeconds(second.files().at(-1)!) > 2, 60_000)
// Stop on the take ends the destination server's stream cleanly with data in its file.
running = false
await player
@@ -381,8 +398,7 @@ maybe('one take with an RTMP destination and a live link at once', () => {
await until('no ffmpeg child', () => ffmpegChildren().length === 0, 40_000)
await Promise.race([second.done(), new Promise((r) => setTimeout(r, 15_000))])
second.kill()
- const seconds = Math.max(0, ...[...dtsOf(second.files().at(-1)!).values()].map((l) => l.length > 0 ? l[l.length - 1]! : 0))
- expect(seconds, 'the second server received the feed').toBeGreaterThan(2)
+ expect(feedSeconds(second.files().at(-1)!), 'the second server received the feed').toBeGreaterThan(2)
await call(`/api/live/destinations/${dest}`, 'DELETE')
}, 240_000)
})
diff --git a/tests/live-link-e2e.test.ts b/tests/live-link-e2e.test.ts
index f01e86e..02bbcc6 100644
--- a/tests/live-link-e2e.test.ts
+++ b/tests/live-link-e2e.test.ts
@@ -48,11 +48,13 @@ beforeAll(async () => {
args: ['--use-fake-ui-for-media-stream', '--use-fake-device-for-media-stream', '--auto-select-desktop-capture-source=Entire screen', '--autoplay-policy=no-user-gesture-required'],
})
}, 120_000)
+// Stopping ends the take's FFmpeg children, the share listener and the browser: on a two-core runner with coverage on
+// that took more than the default 10 s hook timeout.
afterAll(async () => {
await browser?.close()
if (app) await runtimeFor(app.features).stop()
await app?.close()
-})
+}, 60_000)
async function api(p: string, method = 'GET', body?: unknown): Promise {
const res = await fetch(`${base}${p}`, { method, headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) })
diff --git a/tests/mcp-http-server.test.ts b/tests/mcp-http-server.test.ts
index c664036..727f34c 100644
--- a/tests/mcp-http-server.test.ts
+++ b/tests/mcp-http-server.test.ts
@@ -16,6 +16,7 @@ import { buildServer, CORE_TOOLS } from '../src/mcp/server.js'
import { createMcpHttp, serveMcpHttp, type McpHttpServer } from '../src/mcp/http.js'
import { mcpToken, rotateMcpToken, mcpTokenFile } from '../src/mcp/token.js'
import { writeConsent } from '../src/mcp/consent.js'
+import { remoteCaller } from '../src/window/bridge.js'
import { Library } from '../src/store/library.js'
import type { Recording } from '../src/model/recording.js'
import { tempDir } from './helpers.js'
@@ -30,7 +31,8 @@ type Text = { content: { type: string; text: string }[]; isError?: boolean }
async function stdioToolNames(library: Library): Promise {
const [a, b] = InMemoryTransport.createLinkedPair()
- await buildServer({ library }, '0.5.0').connect(a)
+ // As serveMcp builds it: stdio reaches the running app's window (window/bridge.ts remoteCaller).
+ await buildServer({ library, window: remoteCaller(library.dataDir) }, '0.5.0').connect(a)
const client = new Client({ name: 'stdio-side', version: '1' })
await client.connect(b)
const names = (await client.listTools()).tools.map((t) => t.name)
diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md
index 88d4b07..6cc4026 100644
--- a/web/HASHOUT_LOG.md
+++ b/web/HASHOUT_LOG.md
@@ -2,8 +2,8 @@
The client's decisions and why, newest last. Read before changing `web/`.
-Current build version: v0.11.0
-Last updated: 2026-12-01 · v0.11.0 the voice-over, the Studio inspector, the Preferences dialog and the agent dock
+Current build version: v0.12.0
+Last updated: 2026-12-03 · v0.12.0 the walkthrough demos, the window command bridge and rechecking agent programs on focus
## v0.2.0 · the family shell, Home and the in-app demos {#shell-home-demos}
@@ -350,3 +350,51 @@ Checked at 4x CPU throttling in Chrome on a scratch build (port 5657), with line
- Settings, Voice, idle, at 1440 by 900 and 1280 by 800, dark and light: the bar is hidden, ends at x 1226 inside a card that ends at 1243 (1146 against 1163), sits inside its row, keeps its first-frame box, and there are no layout-shift entries. With `data-running="true"` it is visible in the same box.
- Player and editor, the picture's volume sampled every 70 ms while playing: 1 until 0.85 s, then 0.78 to 0.83 at 0.93 s, 0.25 from 1.1 s through 6.2 s, back up through 0.34, 0.48, 0.63 and 0.78 to 1 by 6.67 s, down again into 7.0 s, 0.25 until 9.6 s, then up to 1 by 10.0 s. On pause it is 1 again.
- The Studio panel is in the Voice tab, with one rail match for `[data-inspector-tab="voice"]`.
+
+## v0.12.0 · agent parity: every UI action is a typed command, and agents' changes are drawn at once {#agent-parity}
+
+_web/src/features/registry.ts (Command), web/src/agent-commands.ts, web/src/agent-bridge.ts, web/src/app.ts_
+
+Agents run the window through the command registry (the engine side is in src/HASHOUT_LOG.md, agent-parity), so the registry had to hold every action a person can take, with arguments an agent can see before it calls.
+
+`Command` gained `params` (string, number or boolean; an enum fixed or computed when asked; a range; optional), `risk` (read, change, destructive, external, privacy; a function when it depends on the arguments) and `unavailable()`, and `run` takes the arguments and may return a small value. Menus and shortcuts still call `run()` with none, so no existing command changed. Commands that other modules register without a risk get one from a table in agent-commands.ts rather than an edit in each feature file: studio.start, start-stop, restart, resume, toggle-pause, camera, screenshot and the desktop controls are privacy; studio.cancel and rewind, documents-clear-recent and agents.rotate-player-links are destructive; navigation is read; the rest change.
+
+What was not a command before and is now: `nav.go` (31 pages: Home, the Library and its tabs, Studio, Screen, Camera, Audio only, the studio layouts, effects, Shared, Notifications, Insights, Recently watched, Meetings, Ask, the tour, a demo, a recording, its editor, annotate, clips, interactive, a team recording, a playlist), `window.state`, `recording.action` (every `recordingActions` entry, which is what the library card menus and the player's More menu show; FormREC has no other right-click menus), `player.play`, `pause`, `seek`, `panel` (through a hidden player layer that keeps the open player's context, so no player code changed), `settings.open`, `prefs.get` and `prefs.set` (the window's own settings, which live in localStorage and so had no engine tool), `settings.controls` and `settings.set` (any control of any Preferences section by its data attribute, since most sections are forms and several have no engine tool: a field, select, checkbox or Save is a change, any other button is destructive and asks, and Outside agents is neither listed nor settable, refused before anyone is asked), `view.controls` and `view.set` (the same helpers over the open page, for what has no named command: the studio's inspector panels with its devices, Live, guests, script and sound, the library's search and filters, the editors' fields; in the studio every `view.set` is privacy and asks, because any control there may choose or turn on a device; a file picker is refused, since it needs the person), `studio.configure` (the layout buttons and the target and quality selects, set as a person would, with a change event), and every File, View and Help row that only had an `act`, under its menu id. Item rows are left to their commands where they already are ones.
+
+Arguments are checked in the window, against the same params the agent was shown: unknown names, missing ones, wrong types, out-of-range numbers and values outside an enum each fail with a message naming what is allowed. A command's value is cut at 16 KB. The list is compact (`args` as `name?: type`, enums inline up to eight values); `describe` gives the full spec.
+
+Drawing an agent's change: app.ts listens for `formrec:agent-change` and coalesces a burst for 150 ms, then counts again and draws the view again only when it shows what changed: Home, the Library, Shared, Notifications, Insights, Recently watched, a playlist, or the player of a named recording. The player keeps its moment and whether it was playing: `ctx.seek` always plays (it is the chapter click), so the hold remembers both and pauses after seeking when it was paused. A recording deleted under its player goes to the Library. The studio and the editors (edit, annotate, clips, interactive) are never drawn again under the person, since they can hold unsaved work. The redraw is the router's own `route()`: the new view is built off-screen and swapped in one `replaceChildren`, as every navigation is, so it adds no new flash or shift path.
+
+Checked live (see src/HASHOUT_LOG.md for the run): every sidebar page and the tour by `nav.go`, the player's seek and panels, the theme, Preferences, a menu row, the studio layout, and a rename, import and comment drawn at once in the open library and player (still paused at 3.0 s). No test was added (owner's rule).
+
+## v0.12.0 · FormVis and FormPortal walkthrough demos, and demo comments {#walkthrough-demos-0120}
+
+- refers-to: ../demos/formvis-walkthrough/, ../demos/formportal-walkthrough/, ../demos/README.md, ../scripts/make-walkthrough-demos.mjs, ../scripts/copy-web.mjs (demos/sources left out), src/demos.ts `DEMOS` (`comments`), src/features/engage.ts (`demo-comments` panel), styles/engage.css `.eg-demo-comments`, src/menus.ts `DEMO_LABELS`, index.html (Learn rows), ../src/server/http.ts `DEMO_IDS` `DEMO_FILE`, ../src/mcp/demos.ts `DEMOS`
+- logged: v0.12.0 · 2026-12-03 03:45 EST (rec-demos)
+
+The owner wants demos that are interesting, one on FormVis and one on FormPortal, from their walkthrough videos. YouTube refuses downloads from the sandbox, so both demos are made from the promo videos on the formai.tools walkthrough pages (media.formai.studio, the owner's own), pinned by SHA-256 in the script. The full walkthroughs replace them with no code change when dropped at `demos/sources/.mp4` (demos/README.md).
+
+Each demo is a screen take in the shape the studio writes:
+- `track-screen.webm`, 1280x720 VP9 CRF 38, picture only.
+- `track-host-camera.webm`, the narrator Juno's card with the waveform of her voice. The player draws it as the bubble because it is the host's camera on a screen take.
+- `track-host-mic.webm`, the Kokoro narration (`af_heart`, -16.5 LUFS measured), a sentence per caption cue.
+- `track-soundtrack-mic.webm`, the video's own sound at -27 LUFS.
+
+The chapters sit at the second where each section's heading starts typing on screen, read off 1 fps contact sheets and 0.2 s title strips:
+- FormVis: 0, 5, 17, 29, 38 and 51 s.
+- FormPortal: 0, 5, 15, 23, 31 and 44 s.
+
+Every narrated line ends before its chapter does (the script warns otherwise; it did not). The promo shows Generative Fill, Relight, Remove background and the agent over MCP. Pen Brush, Liquify and Timeline are only in the full walkthrough, so they are chapters only when that video is dropped in.
+
+Comments. Demos never had comments: engage's Comments panel talks to the owner's API and is not a demo panel. The new `demo-comments` panel (`demo: true`) shows only for demos with `comments: true` in demos.ts. It fetches `comments.json` through the demo route; `DEMO_FILE` gained that one fixed name. It draws each comment with engage's own classes (`eg-thread`, `eg-meta`, `eg-avatar`, `eg-time`, `eg-text`), inside an `eg-root` so the engage tokens apply. The time button seeks and plays. The tab's page is hidden until chosen, so the rows filling in after the fetch move nothing on screen.
+
+Zoom and cursor highlights were not added. The autozoom and keycast layers are not demo layers. A promo's picture already carries its own cursor and camera moves, and zooming into it again would crop the owner's framing.
+
+Checked on the production build in Chromium at 4x CPU throttling, dark and light, 1440x900 (captures in /home/claude/work/captures/formrec/0.12.0/demos/):
+- Home: five demo cards, every poster loaded at 640x360, and five Learn rows. Cumulative layout shift is 0.
+- Each new demo, layout shift 0 on open:
+ - Both videos reach readyState 4 and play in step after a chapter click (21.2 and 21.1 s).
+ - The bubble is drawn, the four tracks are listed and a caption shows.
+ - The tabs are Chapters, Transcript and Comments.
+ - A comment's time seeks (0:09 to 10.5 s after 1.5 s of play).
+- The only console errors are the existing 409 from `/api/relay/sso`, which Home and the podcast demo also give.
diff --git a/web/index.html b/web/index.html
index 7c3b579..0b91541 100644
--- a/web/index.html
+++ b/web/index.html
@@ -112,6 +112,8 @@