Web target, plan 3: manifoldx run --web, the dev loop
This plan builds slice 4 of the spec. manifoldx run --web app.py serves the export on 127.0.0.1, watches the app's sources, and on each save reruns setup, transpiles, snapshots and pushes the new version to the open tab. The tab imports the new modules and the new snapshot, keeps its three.js scene when the scene did not change, keeps engine.state as the desktop reloader does, and resumes without a page reload. The agent commands work against the tab. It ends with the first consumer's camera kept in engine.state, staying put across a save, and its reload time measured.
manifoldx run --web app.py and open the printed URL. A save shows in the tab with engine.state kept; an edit that fails to load or transpile leaves the running version with an overlay naming the Python line; an exception in a frame pauses with the Python traceback and the next save resumes; manifoldx look, state, set, emit, events and log answer from the tab.
architectureThe export splits into building a version in memory and writing it. A WebReloader (a HotReloader with no window) rebuilds on each change and writes numbered version folders beside shared static files under .manifoldx/web/, which the existing dev server now also serves. The server talks to the tab over Server-Sent Events, and the tab answers with POSTs. In the page, browser.js learns to load a version from a base path and to swap one in place, and a new dev.js holds the dev loop's browser side: the stream, the overlay and the agent commands. manifoldx.js stays free of the DOM and gains the state codec both ways.
techPython 3.13, stdlib only on the server (http.server, no websocket library); plain ES modules; Node 20+ for node --test; Playwright with Chromium for the browser tests, in the existing browser CI job on lavapipe.
spec.knowledge/analysis/2026-11-06-web-target-design.html (section 08, slice 4 of section 10, the first open question of section 13)
builds onplan 1 (#141) and plan 2 (#146), with the follow-ups of #150, all on main. This plan's branch is feat/web-target-3; its PR targets main.
code it changessrc/manifoldx/web/export.py, src/manifoldx/hot.py, src/manifoldx/devchannel.py, src/manifoldx/cli.py, src/manifoldx/engine.py (one parameter), the page's modules in src/manifoldx/web/js/. New: src/manifoldx/web/dev.py, src/manifoldx/web/devstate.py, src/manifoldx/web/js/dev.js.
The reload budget, measured
The spec leaves open how fast a save must show and asks this slice to measure the first consumer before tuning. Its export was timed by phase on the shared 4-core host with lavapipe, twice in one process (the second run drops the app's modules and reruns, as a reload does), with manifoldx at main plus #150:
| phase | first | second | under run --web |
|---|---|---|---|
| setup: module code until engine.run() | 0.18 s | 0.08 s | same |
| startup on a headless frame (textures, meshes) | 3.37 s | 0.97 s | same; the device is reused (1.43 s of the first run) |
| reach and types | 0.72 s | 0.95 s | same; the largest piece left to tune |
| snapshot, transpile, GUI spec | 0.09 s | 0.12 s | same |
| glb export | 0.07 s | 0.05 s | built and hashed; written only when the hash is new |
| writing, of which three.js, fonts and page files | 0.48 s | 0.46 s | static files written once at start: about 0.05 s per version |
The expected budget, from save to the new version drawn in the tab, about 2.5 s for a code-only edit on this host: up to 0.25 s until the poll sees the file, about 0.05 s to get the tab's state, 2.2 s to rebuild, then the push and a swap of about 0.1 to 0.2 s (fetch 236 KB of state, import 10 modules, rebuild the GUI). An edit that changes the scene adds the parse of a new 4.4 MB glb, estimated at 0.3 to 0.6 s. Task 10 measures the real numbers in a tab and reports them; tuning reach (cache per-module results by source hash) and the startup's textures (the app's own engine.state cache, as know-how/hot-reload.md advises) are left to follow-up issues unless a reload exceeds 3 s.
How the pieces fit
The orange path is one reload. The dashed blue paths are the agent commands, which the server forwards to the tab as calls over the same stream.
Open questions
None of these is settled by the code or the spec. Each has a recommendation, and the tasks follow it. A maintainer's different answer changes only the task named.
Q1 · What of the tab's engine.state crosses back to Python
The spec says the tab sends its engine.state and setup reruns with it. In the tab, the state is runtime values: a dict is a Map, a tuple and a list are both arrays, a float32 vector is a Float32Array, and a value may be an object of a transpiled class or a handle. Python's State may also hold keys that never crossed (report.json's state_left_out), such as the texture cache keyed by tuples that know-how/hot-reload.md recommends.
recommendThe tab encodes its state with the snapshot's own value forms (__dict, __set, __f32, __f64, __float) and marks what is not plain data as {"__skip": "<what>"}. Python decodes against its previous value: an array comes back a tuple where the old value at that path was a tuple; __f32 becomes a float32 numpy array. Only the keys that crossed in the last snapshot are replaced or deleted; left-out keys and keys whose value holds a __skip keep Python's value, and each kept key is logged once. Task 2.
Q2 · Frames that run while the reload builds
A reload of the first consumer takes about 2.5 s. If the tab keeps running while Python rebuilds from the state it sent, the camera motion of those seconds is lost when the new version loads, and the view jumps back.
recommendThe tab freezes when it answers the reload's state request: it stops running systems, keeps the last frame on screen and shows v3 · reloading. It resumes on the new version, or on failed, or after 30 s without either. The desktop reloader blocks its window for the same time (src/manifoldx/hot.py:175 reloads inside step()), so the two behave alike. Tasks 5 and 6.
Q3 · More than one tab
The spec speaks of "the open tab". A person may open two, or reload one, or an agent's Playwright page may sit beside a person's tab.
recommendEvery connected tab receives every version. The tab that connected last answers the calls (state, set, emit, look); when it disconnects, the previous one takes over. Each tab sends its id in the stream URL. Task 4.
Q4 · A tab that opens after the state moved on
A tab opened, or reloaded with F5, loads the current version, whose snapshot holds the state of the last save. The camera then returns to where it was at that save, though the spec keeps the state "without a tab" as the last one received.
recommendA tab sends its encoded state with navigator.sendBeacon on pagehide, and every reply to a call carries it too. When a tab connects and the state the server last received differs from the current version's, the server rebuilds as on a save (reason tab, no file changed) and the new tab swaps to it. Task 4.
Q5 · What manifoldx look shows, given an HTML GUI
The desktop look includes the GUI (know-how/agent-loop.md, the API table). In the tab the GUI is HTML over the canvas, which a canvas read does not include, and a page cannot screenshot its own DOM without a library.
recommendThe tab draws the WebGL frame into a 2D canvas of the same size, then paints each visible GUI element over it from its bounding box and computed style: background colour, then each text line in the GUI's font and colour. Pixel equality with the HTML is not a goal, as the spec says of the GUI; the text and the layout are. Task 7.
Q6 · Logging from frame code
The spec says log includes the tab's console. know-how/agent-loop.md tells apps to log what the person does with engine.log(text), usually from a system, but engine.log is not in RUNTIME_SURFACE (src/manifoldx/web/types.py:455), and in the runtime engine.log is already the trace's array of calls (src/manifoldx/web/js/manifoldx.js:238).
recommendAdd engine.log(text) to the surface. The runtime's call record is renamed engine.calls (the trace's JSON key stays log, so fixtures and replay.py do not change). In the tab, engine.log sends its line to the server's log as the desktop's does; in Node it collects lines in engine.lines. The tab's console warnings and errors go to the log with the prefix tab: . Task 7.
Q7 · The transport between server and tab
The dev server is a stdlib ThreadingHTTPServer (src/manifoldx/devchannel.py:342). A websocket needs a library or a hand-written framing layer.
recommendServer-Sent Events for server to tab (GET /api/web/stream, one blocked thread per tab, which the threading server already gives), POSTs for tab to server. EventSource reconnects by itself when the server restarts. Task 4.
Q8 · Where versions live and what the URLs are
The spec says "export into a new version folder". The page imports app modules by URL, and the browser caches an ES module by its URL for the page's life, so a new version needs new URLs. The dev page already owns /.
recommendUnder --web the server serves .manifoldx/web/: the app at /, the dev page at /dev, versions at /v{n}/ (app/, state.json, report.json), scenes at /scenes/<sha>.glb, and the static files (page modules, runtime, vendor/three/, fonts/) once at the root. A version's modules import ../../pyrt.js, so every version shares one runtime instance. The server keeps the last three versions and the scenes they name, and deletes the rest. Tasks 1 and 3.
Q9 · --debug with --web
--debug measures the window's frames in Python (src/manifoldx/devchannel.py:119). Under --web no Python frames run after startup.
recommendRefuse the pair: --debug measures the window's frames; under --web the tab runs them, exit 2. Frame metrics from the tab are a later step. Task 8.
Global constraints
- No app JavaScript: nothing here asks an app author to write JS.
manifoldx export --webwrites the same folder as before, file for file;tests/web/test_export_web.pypasses unchanged after task 1.- The desktop
manifoldx rundoes not change:tests/test_hot_reload.py(9 tests) andtests/test_dev_channel.py(14 tests) pass after every task that toucheshot.pyordevchannel.py. manifoldx.jsimports neither three.js nor a DOM name, so the Node replay keeps working; the dev loop's browser code lives indev.jsandbrowser.js.- Only
engine.statesurvives a reload, as underrun(the spec's decision, by the maintainer). - Every error the dev loop shows names the Python file and line where one exists: a transpile error as
TranspileErrorprints it, a load error from its traceback, a frame error from the source maps. - The server listens on 127.0.0.1 only; the server code uses the standard library only.
- Node and Playwright are test dependencies only; tests skip with
node not found,playwright not installedorchromium not installed. - Shared host: each task's verify runs only the tests covering it.
make testand the browser job run in CI. - manifoldx is public: no names of the consumer's repository, campus, people or machines in code, tests, commits or PR text. The consumer is "the first consumer".
- Commits are conventional; scratch goes under pytest's
tmp_path, never in the repo.
Review focus
- A save while a key is held or the pointer is locked (walking forward with W when the editor autosaves): after the swap the key is still held and
pointer_capturedis still true while the lock is on. The FrameBuilder and PointerLock outlive the version; the new input learns the lock. test in tasks 5 and 8 - Two saves close together (an editor that writes twice, a save during a reload): the tab ends on the newest version and never applies an older one after a newer; a save during a build starts one more reload after it. tests in tasks 3 and 5
- The tab closed or reloading when a save lands: the state request times out after 0.5 s, the build uses the last state received, and a tab that opens during the build loads the version it finds and then swaps. test in task 4
- Materials set at runtime in a kept scene (a highlighted building when the save lands): the kept scene first returns every entity to the glTF's material, so it matches a rebuilt scene, and the new version's code applies its own. test in task 5
- engine.state holding what cannot cross (a texture cache keyed by a tuple, a 2-d numpy array): those keys stay in Python untouched across any number of reloads, so the cache advice of
know-how/hot-reload.mdkeeps working under--web. tests in tasks 2 and 3
File structure
| file | responsibility |
|---|---|
| src/manifoldx/web/export.py | build_export (a version in memory, with per-phase timings), write_static, write_version, page_html; export_web composed from them |
| src/manifoldx/web/devstate.py | the tab's encoded state back to Python values; the merge into the shared State |
| src/manifoldx/web/dev.py | Tab (connected tabs, the stream, calls and replies) and WebReloader (the rebuild loop, version folders, pruning, error lines) |
| src/manifoldx/hot.py | _load also records the app's __main__ module; reload()'s module dropping becomes _drop_modules() |
| src/manifoldx/engine.py | _ensure_offscreen(supersample, gpu=None) passes gpu to _init_canvas |
| src/manifoldx/devchannel.py | under --web: static files, /api/web/*, and state, set, emit and look routed to the tab; the dev page moves to /dev |
| src/manifoldx/cli.py | run --web |
| src/manifoldx/web/types.py | engine.log in RUNTIME_SURFACE |
| src/manifoldx/web/js/manifoldx.js | encodeState, fromJSON, mergePatch, stateView, fire; engine.calls and engine.log(text) |
| src/manifoldx/web/js/browser.js | loadVersion(base, info) and swap(info); the frame loop over a replaceable app; dev mode when the page has <meta name="mx-dev"> |
| src/manifoldx/web/js/dev.js | the stream, the overlay's status, freeze and resume, calls answered, console forwarding, the look composite |
| src/manifoldx/web/js/scene.js, gui.js | resetMaterials(); destroy() |
| src/manifoldx/web/js/index.html | {{dev}} slot for the dev meta and the overlay element |
| tests/web/test_build_export.py, test_devstate.py, test_dev_web.py | Python tests: the split export, the codec, the reloader and the server against a scripted tab |
| tests/web/js/dev.test.mjs, runtime.test.mjs | Node tests of the codec, patches, events and the overlay's status |
| tests/web/apps/dev_orbit.py | a test app for the dev loop: an orbit camera in engine.state, a coloured box, a GUI Text, an event with a docstring |
| tests/web/browser/test_run_web.py | Chromium against a real manifoldx run --web: saves, errors, agent commands |
Tasks
1The export splits into building a version and writing itweb/export.py · engine.py · tests/web/test_build_export.py
interfaces
capture_engine, find_roots, reach_app, snapshot, transpile_app(sources, reach=, runtime=), gui_spec, export_engine as export_web uses them today (src/manifoldx/web/export.py:66-151) · produces build_export(engine, main, root, *, app_label, runtime="../pyrt.js", gpu=None) -> Built, raising TranspileError (with the file's real path, as export_web rewrites it today), SnapshotError or GuiUnsupported; @dataclass Built: modules: dict[str, tuple[str, str]] (name to code and source-map JSON with sources set), state: dict, report: dict, glb: bytes, scene_sha: str (sha256 hex, first 16), title: str, crossed: frozenset[str] (the engine.state keys the snapshot wrote), left_out: list[SnapshotError], timings: dict[str, float] (seconds, keys startup reach snapshot transpile gui scene) · write_static(out) (the page's modules, the runtime, vendor/three/, fonts/; with dev=True also dev.js) · write_version(built, out, scene_path="scene.glb") (app/, state.json, report.json, the glb at scene_path relative to out unless it exists) · page_html(title, scene_bytes, scene_gzip_bytes, dev=False) -> str · Engine._ensure_offscreen(supersample, gpu=None)- Write the failing tests in
tests/web/test_build_export.py, onexamples/web_walk.pythroughcapture_engine: - Run
uv run pytest tests/web/test_build_export.py -q: fails withImportError: cannot import name 'build_export'. - Move the body of
export_webaftercapture_engineintobuild_export(the_as_mainblock, startup withengine._ensure_offscreen(1, gpu=gpu), the error path rewrite, the report) and the writing intowrite_static,write_versionandpage_html.export_webbecomes capture, build,write_static(out),write_version(built, out),index.htmlfrompage_html, and theleft out of the statelines; its exit codes and messages stay.build_exportcallsexport_engineinto a temporary file in the system temp dir and reads its bytes;scene.export-report.jsonmoves intoBuilt.report["scene_report"]andwrite_versionwrites it beside the glb as today. Inengine.py,_ensure_offscreentakesgpu=Noneand passes it to_init_canvas.index.htmlgets a{{dev}}slot in the head, empty for the export. - Run the new tests and the export's:
uv run pytest tests/web/test_build_export.py tests/web/test_export_web.py -q: all pass. - Commit:
refactor(web): build an export in memory, then write it.
uv run pytest tests/web/test_build_export.py tests/web/test_export_web.py -q: all pass, the five new tests included; git diff main -- tests/web/test_export_web.py is empty.
2engine.state crosses back: the codec both waysweb/devstate.py · js/manifoldx.js · tests/web/test_devstate.py · tests/web/js/runtime.test.mjs
interfaces
src/manifoldx/web/snapshot.py:12-27), hot.State, Built.crossed (task 1) · produces JS: encodeState(map) -> value (plain JSON with {"__dict": [[k, v], ...]}, {"__set": [...]}, {"__f32": [...]}, {"__f64": [...]}, {"__float": "nan"|"inf"|"-inf"}, arrays as JSON arrays, and {"__skip": what} for an object of a transpiled class, a handle, a function or a cycle); fromJSON(value) (a JSON value to runtime values: objects to Map, recursively); mergePatch(map, patch) (RFC 7386 on a Map, patch already through fromJSON); stateView(map) -> plain JSON (for GET /api/state: a Map as an object, typed arrays and Sets as arrays, a skipped value as its what string, as the desktop's repr fallback) · Python: devstate.decode(value, like=None); devstate.merge_tab_state(state: State, tab: dict, crossed: frozenset[str]) -> list[str] (the keys it kept from Python, with why)- Write the failing Python tests in
tests/web/test_devstate.py: - Write the failing Node tests in
tests/web/js/runtime.test.mjs:encodeStateof a Map holding a Map, a Float32Array, a Set, NaN, anObject.createobject of a class and a cycle gives the forms above, the last two as__skipwith"an object of Viewer"and"a cycle";fromJSON({"cam": {"yaw": 1}})is a Map of a Map;mergePatchmerges nested Maps, deletes onnull, replaces arrays whole;stateViewshows a handle as"<material 3>". - Run
uv run pytest tests/web/test_devstate.py tests/web/test_node_suites.py -q: fails on the missing names. - Implement
devstate.pyand the four JS functions.decodewalkslikebeside the value: a dict decodes each key againstlike.get(key), a list againstlike[i]when lengths match.merge_tab_statedecodes the top level against the current state, then for each crossed key: absent in the tab's state deletes it, a value containing__skipanywhere keeps Python's whole key, anything else replaces it; a key not crossed keeps Python's value; a key new in the tab is added. - Run the same command: passes.
- Commit:
feat(web): engine.state from the tab back to Python.
uv run pytest tests/web/test_devstate.py tests/web/test_node_suites.py -q: all pass; the round-trip test fails if decode drops the like argument (try it once).
3WebReloader: rebuild on save into version foldersweb/dev.py · hot.py · tests/web/test_dev_web.py · tests/web/apps/dev_orbit.py
interfaces
HotReloader (src/manifoldx/hot.py:52), tasks 1 and 2 · produces HotReloader._load() also sets self.main (the app's __main__ module at engine.run()); HotReloader._drop_modules() (lines 141-149 of today's reload, unchanged behaviour) · class WebReloader(HotReloader): __init__(script=None, module=None, argv=(), poll=0.25, channel=True, port=PORT, web_root=None) (default <app root>/.manifoldx/web), tab: Tab (task 4; a stub with call and push until then), version: int, current: dict | None (the last version message), start(), reload(reason="edit"), step(), run() · version message {"type": "version", "version": n, "base": "v{n}/", "scene": "scenes/<sha>.glb", "scene_sha", "scene_bytes", "scene_gzip_bytes", "title", "state_sha"} · failure message {"type": "failed", "running": n, "text": "app.py:12: SyntaxError: invalid syntax"} · error_line(exc, root) -> str- Write
tests/web/apps/dev_orbit.py: an orbit camera whoseyaw,pitchanddistlive inengine.state.cam(a dict set withsetdefault), a system that turnsyawwith A and D and places the camera from the state every frame, one box whose colour is a module constantBOX = "#4080c0", a top-left Panel with aTextreadingSPEED = 1.0through aValueDisplay, an@engine.on("bump")handler with the docstringTurn the camera: {"by": degrees}.that adds toyaw, and anengine.statekey("cache", 1)holding a 2-d array that cannot cross. No startup handler, so it needs no device. - Write the failing tests in
tests/web/test_dev_web.py, with a scripted tab (FakeTab: records pushes, answersreload_statewith a value the test sets): - Run
uv run pytest tests/web/test_dev_web.py -q: fails withModuleNotFoundError: manifoldx.web.dev. - In
hot.py, recordself.mainin_load(the captured lambda appends(engine, sys.modules.get("__main__"))) and move the dropping into_drop_modules(). Runuv run pytest tests/test_hot_reload.py -q: 9 passed. - Implement
WebReloaderinsrc/manifoldx/web/dev.py.start():_load(),write_static(web_root, dev=True), build and write v1 withruntime="../../pyrt.js"andscene_path=f"../scenes/{sha}.glb", writeindex.htmlfrompage_html(..., dev=True), open the channel.reload(reason): ask the tab (tab.call("reload_state", timeout=0.5); onNoTabor timeout, keepself.state),merge_tab_statewith the lastBuilt.crossed, log each kept key once per run,_drop_modules(),_load(), detach the previous engine, build withgpu=the previous engine's(adapter, device, format)when it had a device, writev{n+1}, push the version message, prune to the last three versions and the scenes they name. A failure at any step pushesfailedwitherror_lineand keepsself.engine,self.currentand the version number.step(): poll, reload,channel.run_jobs();run()loopsstep()with a 0.05 s sleep until interrupted, then closes the channel.error_line: aTranspileErrororSnapshotErroras itsstr; aSyntaxErrorfrom itsfilenameandlineno; otherwise the innermost traceback frame in an app file; the path relative to the app's root, then: Type: message. - Log one line per reload with the timings:
reloaded v4 in 2.41 s (state 0.02, setup 0.08, startup 0.97, reach 0.95, snapshot 0.09, transpile 0.03, gui 0.00, scene kept 0.05, write 0.04),scene newin place ofscene keptwhen the sha changed; andreload failed, kept v3: <error line>. Print both to stderr asmanifoldx run --web: .... - Run
uv run pytest tests/web/test_dev_web.py tests/test_hot_reload.py -q: all pass. - Commit:
feat(web): WebReloader rebuilds the export on every save.
uv run pytest tests/web/test_dev_web.py tests/test_hot_reload.py -q: all pass. Break it once: make reload skip the tab's state, and test_code_edit_keeps_the_scene_and_takes_the_tab_state fails on yaw.
4The dev server talks to the tabweb/dev.py · devchannel.py · tests/web/test_dev_web.py
interfaces
Channel, _Handler, _bind (src/manifoldx/devchannel.py:179-349), WebReloader (task 3) · produces class Tab: connect(tab_id) -> queue, disconnect(tab_id), push(message) (to every tab), call(kind, body=None, timeout=5.0) (to the answering tab: the last connected; raises NoTab or TimeoutError), reply(call_id, payload), last_state (the last encoded state any reply or beacon carried) · Channel(root, hot, port, debug=False, web=None): with web (the WebReloader) it serves the routes below · call message {"type": "call", "id": n, "kind": "reload_state"|"state"|"patch"|"emit"|"look", "body": ...} · reply body {"ok": true, "value": ..., "state": encoded} or {"ok": false, "error": "..."}; a look's reply is the PNG with Content-Type: image/png| request (under --web) | does |
|---|---|
| GET /, /v{n}/..., /scenes/..., /vendor/... | files from the web root; Content-Type by suffix (.js and .mjs text/javascript, .json, .map, .glb model/gltf-binary, .ttf font/ttf, .html); a path that resolves outside the root is 404 |
| GET /dev | the dev page that GET / serves today |
| GET /api/web/current | the current version message |
| GET /api/web/stream?tab=ID | Server-Sent Events: the current version first, then every push and every call to this tab; a comment line every 15 s keeps it open |
| POST /api/web/reply/ID | the answer to call ID |
| POST /api/web/state | the tab's encoded state (the pagehide beacon) |
| POST /api/web/log | [{"level", "text"}], each line into the log |
| GET, PATCH /api/state; POST /api/events/NAME; GET /api/look | forwarded to the answering tab (state, patch, emit, look); with no tab, 503 no tab is open: open http://127.0.0.1:PORT/ |
| GET /api/events | from the Python engine, as today, without startup and shutdown, whose handlers do not run in the tab |
| GET /api/metrics | 404 metrics are not measured under --web |
- Write the failing tests, extending
tests/web/test_dev_web.pywith an HTTP tab client in Python (a thread that reads/api/web/streamline by line withurlliband posts replies):test_stream_starts_with_the_current_version;test_state_is_the_tabs(GET /api/statereturns what the client answers);test_set_and_emit_reach_the_tab(the client receivespatchwith the body andemitwith{"name": "bump", "payload": {"by": 10}}; an unknown event is 404 with the known ones, answered from the Python engine without a call);test_no_tab_is_503;test_the_last_tab_answers(two clients: the second answers; after it disconnects, the first);test_static_files_and_types(/browser.jsistext/javascript;/../pyproject.tomland/v1/../../xare 404);test_a_tab_with_a_newer_state_triggers_a_rebuild(Q4: a beacon with a state whose cam differs, then a new client connects: a version 2 withreason tabfollows);test_tab_gone_during_reload(the client stops answering: the reload completes after 0.5 s with the last state). - Run
uv run pytest tests/web/test_dev_web.py -q: the new tests fail. - Implement
Tabindev.pyand the routes indevchannel.py. Each stream is aqueue.SimpleQueueits handler thread drains, writingdata: <json>\n\nand flushing; a write error disconnects it.callholds aFutureper id. The forwarded state, set and emit answer as the desktop's do (the state asstateViewreturns it, a patch returning the new state, an emit{"emitted": name, "handlers": n}), and log the same lines (state patched: ...,event bump {...}). The Q4 check runs inconnect: whenlast_state's sha differs fromcurrent["state_sha"], the reloader's main loop gets areload("tab")job. - Run
uv run pytest tests/web/test_dev_web.py tests/test_dev_channel.py -q: all pass. - Commit:
feat(web): the dev server streams versions and calls to the tab.
uv run pytest tests/web/test_dev_web.py tests/test_dev_channel.py -q: all pass, the desktop channel's 14 unchanged.
5The tab swaps to a new version in placejs/browser.js · js/dev.js · js/scene.js · js/gui.js · js/index.html · tests/web/js/dev.test.mjs
interfaces
encodeState (task 2), loadApp, buildScene, buildGui, PointerLock · produces in browser.js: loadVersion(base, info) -> Version ({state, modules, maps, app}; fetches ${base}state.json, imports ${base}app/${name}.js, reads the maps) and swap(info) (the steps below); __mx.version (the running number), __mx.swaps ([{version, ms, scene: "kept"|"new"}]) · in dev.js: connect(mx, {url, onVersion, onFailed, onCall}); status(model, message) -> model (pure: {version, phase: "live"|"reloading"|"failed"|"paused"|"offline", text}) · scene.resetMaterials() (every entity back to the material the glTF gave it) · gui.destroy() (removes its elements and listeners)- Write the failing Node tests in
tests/web/js/dev.test.mjsforstatus: areloadingthenversion 4gives{version: 4, phase: "live"};version 3afterversion 4is ignored (two saves close together);failedkeeps the running version with its text; a stream error givesofflineand the next version clears it. Register the suite intests/web/test_node_suites.py. - Write the failing scene and GUI tests in
tests/web/js/scene.test.mjsandgui.test.mjs: aftersetMaterial(e, highlight),resetMaterials()puts the glTF's material back on every mesh ofeandmaterialOf(e)is its original id;destroy()leaves the layer empty. - Run
uv run pytest tests/web/test_node_suites.py -q: fails. - Implement.
browser.jskeeps the renderer, canvas, FrameBuilder, PointerLock and DOM listeners for the page's life, and holds the runningVersionin a variable thatrunFramereads. In dev mode (<meta name="mx-dev">, written bypage_html(dev=True)) it gets the version from/api/web/current, loads the scene frominfo.sceneand importsdev.js.swap(info): ignore a version not above the running one;loadVersion; ifinfo.scene_shaequals the running one,scene.resetMaterials(), else fetch, parse andbuildScenethe new glb and dispose the old one's geometries, materials and textures;gui.destroy()andbuildGuifrom the new state;loadAppwith the same hooks; setlock.inputto the new input and tell it the lock is on whenlock.locked; clearmx.errorand hide the error panel; resume the loop; record__mx.swaps; posttab: v4 in 84 ms (scene kept)to the log. The answer toreload_statefreezes the loop (Q2) and returnsencodeState(engine.state);failedor 30 s without a version unfreezes. A swap that throws (a module that fails to import) shows its error as a load error does and keeps the running version. - Run
uv run pytest tests/web/test_node_suites.py -q: passes. - Commit:
feat(web): the tab swaps to a new version without a page reload.
uv run pytest tests/web/test_node_suites.py -q: all pass. Task 8 checks the swap itself in Chromium.
6The overlay: reload status and errors with the Python linejs/dev.js · js/browser.js · js/index.html · tests/web/js/dev.test.mjs
interfaces
status (task 5), describe (src/manifoldx/web/js/sourcemap.js), the failed message (task 3) · produces #mx-dev (a status line at the bottom right, dev mode only) and the existing #mx-error panel; overlayText(model) -> {status, panel} (pure)The overlay's text, exact:
| when | status line | error panel |
|---|---|---|
| running | v3 · live | hidden |
| from the state request to the swap | v4 · reloading | unchanged |
| an edit failed to load or transpile | v3 · reload failed, running v3 | the failure's text, e.g. dev_orbit.py:12: SyntaxError: '(' was never closed, then Fix it and save: the tab keeps running v3. |
| an exception in a frame | v3 · paused until the next edit | describe's text, as today (raises.py:26 in tick: TypeError: ... and its callers) |
| the stream is down | v3 · dev server gone, retrying | unchanged |
- Write the failing Node tests of
overlayTextfor each row above, the strings exact. - Run
uv run pytest tests/web/test_node_suites.py -q: fails. - Implement. A frame exception in dev mode stops the loop as today, sets the phase to
pausedand postspaused until the next edit: <describe's first line>to the log, the line the desktop writes (src/manifoldx/hot.py:186). The next version clears the error and resumes. The overlay is placed so it does not cover a top-left GUI panel; it haspointer-events: none. - Run
uv run pytest tests/web/test_node_suites.py -q: passes. - Commit:
feat(web): the dev overlay names the reload's state and the Python line.
uv run pytest tests/web/test_node_suites.py -q: all pass. Task 8 checks each row in Chromium.
7Agent commands answered by the tabjs/dev.js · js/manifoldx.js · js/replay.mjs · web/types.py · tests/web/js/runtime.test.mjs · tests/web/test_state_access.py
interfaces
stateView, fromJSON, mergePatch (task 2) · produces fire(app, event, payload) in manifoldx.js (calls every handler root of that event with the payload, in registration order); engine.calls (today's engine.log array, renamed; traceEntry still writes it under the key log); engine.log(text) in the runtime (Node: appends to engine.lines; the tab: hooks.log(text)); "log": fn("manifoldx.Engine.log", NONE) in RUNTIME_SURFACE; lookPng(canvas, guiLayer, render) -> Promise<Blob> in dev.js- Write the failing tests. Parity (
tests/web/test_state_access.py): a system that callsengine.log(f"yaw {yaw:.1f}")transpiles, and in Node the lines areengine.lines. Runtime (runtime.test.mjs):fire(app, "bump", fromJSON({"by": 10}))runs the handler root once with a Map; an event no root handles does nothing;replay.mjs's output is unchanged by the rename (runtests/web/test_replay.py). - Run
uv run pytest tests/web/test_state_access.py tests/web/test_node_suites.py tests/web/test_replay.py -q: the new tests fail. - Implement the runtime and surface changes. Then the tab's answers in
dev.js:staterepliesstateView(engine.state);patchappliesmergePatch(engine.state, fromJSON(body))between frames and replies the new view;emitqueues[name, fromJSON(payload)]andrunFramefires the queue before the systems, as the desktop runs emitted events at the start of the next frame (know-how/agent-loop.md, Gotchas);lookrenders the current frame (also while paused or frozen), draws the WebGL canvas into a 2D canvas of the drawing buffer's size within the same task, paints the GUI per Q5 scaled by the device pixel ratio, and posts the PNG. Every reply carriesencodeState(engine.state)asstate(Q4).console.warn,console.error,window.onerrorand unhandled rejections posttab: ...lines, batched every 250 ms;hooks.logposts the app's lines without the prefix. - Run the same command: passes.
- Commit:
feat(web): look, state, set, emit and log against the tab.
uv run pytest tests/web/test_state_access.py tests/web/test_node_suites.py tests/web/test_replay.py -q: all pass, the replay fixture unchanged.
8manifoldx run --web, end to end in Chromiumcli.py · tests/test_cli.py · tests/web/browser/test_run_web.py · tests/web/browser/conftest.py
interfaces
chromium and open_page fixtures and the fake lock (tests/web/browser/conftest.py) · produces manifoldx run --web [-m module | app.py] [--port N] [-- app args], printing manifoldx run --web: open http://127.0.0.1:PORT/ (dev page at /dev); fixture run_web(app_path) -> url (a subprocess in a tmp_path copy of the app, stopped by PID, reading the URL from .manifoldx/server.json)- Write the failing CLI tests:
run --web --debugexits 2 with Q9's message;run --webwith neither script nor module is the existing usage error. - Write the failing Chromium tests in
tests/web/browser/test_run_web.py, each on a fresh copy ofdev_orbit.py: Intest_agent_commands, run the real CLI in the app's folder:manifoldx state camprints the tab's yaw;manifoldx set '{"cam": {"yaw": 0}}'moves the tab's camera on the next tick;manifoldx emit bump '{"by": 10}'adds 10 to yaw on the next tick;manifoldx eventsprintsbumpwith its docstring;manifoldx lookwrites a PNG of the canvas's drawing-buffer size whose pixel at the panel's centre is the panel's background within 8 per channel, and whose centre pixel is the box's colour within 8;manifoldx log --match 'tab: v2'finds the swap line after a save. - Write the breaking tests: with the tab's
reload_stateanswer replaced by an empty state (an init script),test_a_save_swaps_and_keeps_the_statefails on yaw; withresetMaterialsreplaced by a no-op,test_a_kept_scene_drops_runtime_materialsfails. - Run
uv run pytest tests/test_cli.py tests/web/browser/test_run_web.py -v: fails. - Add
--webtorunincli.py:WebReloader(script=..., module=..., argv=app_args, **port).run(). Fix what the Chromium run finds; record each fix in "where this plan departs" with the file and line. - Run the same command: passes.
- Commit:
feat(web): manifoldx run --web, the dev loop in the browser.
uv run pytest tests/test_cli.py tests/web/browser/test_run_web.py -v: all pass, the two breaking cases included, nothing skipped on a host with the browser group.
9Docs, changelog and the PRknow-how/hot-reload.md · know-how/web-export.md · know-how/agent-loop.md · AGENTS.md · CHANGELOG.md
know-how/hot-reload.md: a section "In the browser:run --web" with the command, what a save does (the steps of the flow above), what crosses back from the tab (Q1), the freeze (Q2), the overlay's lines, the layout of.manifoldx/web/, and the measured reload of the first consumer once task 10 has it.know-how/agent-loop.md: the commands under--web(which tab answers, look's GUI composite,engine.logfrom frame code, thetab:lines, no metrics, 503 without a tab).know-how/web-export.md: drop "run --webis not there yet", addengine.logto the surface list.AGENTS.md:run --webin Quick Commands, and the Web target line names plan 3 and drops the stale "plan 2 onfeat/web-target-2".CHANGELOG.mdunder[Unreleased]:manifoldx run --web,engine.login the web subset,build_export.- Commit
docs(web): run --web in the know-how, push the branch, open the PR againstmainwithClosesleft off (#140 stays open for the second consumer), and work it until CI'stest,webandbrowserjobs are green.
CI green on the PR, the browser job listing test_run_web.py with no skips; grep -rn "not there yet" know-how/ finds nothing about run --web.
10The first consumer: its camera in engine.state, its reload measuredthe consumer's repository: app code, a reload test, its docs
Runs in the first consumer's repository after this plan's PR merges; its own issue, branch and PR, as plan 2's task 12 did. Its web build already comes from export --web (on the consumer's web-export branch at the time of writing).
- Pin manifoldx to the merge commit. Move the camera rig's place into
engine.stateas plain data:engine.state.setdefault("camera", {"pos": [x, y, z], "yaw": ..., "pitch": ..., "mode": ...})from the default view; the rig starts from it at setup, and the frame system writes it back every frame (engine.state.camera = {...}, attribute form, floats from the rig), so a reload loses nothing (know-how/hot-reload.md, "keep the value in state"). The engine is created before the rig reads the state. Its desktop tests, its replay test and its screenshot command still pass, and the desktopmanifoldx runkeeps the camera across a save too. - Add a reload test in its browser tests (skipped where Chromium is missing):
manifoldx run --webof the app in a temp copy, walk for 60 ticks, readengine.state.camera, edit a constant the panel shows, wait for__mx.version === 2; the camera's pos, yaw, pitch and mode are equal to before the save to 1e-9,__mx.scene.scene.uuidis unchanged, and the panel shows the new text. - Measure: start
manifoldx run --webof the app, open the tab in Chromium, save five code-only edits and one edit that changes a material's colour, 10 s apart. Read thereloaded v{n} in ...andtab: v{n} in ...lines withmanifoldx log. Report on manifoldx #140, without naming the consumer: the median and worst save-to-swap time for code-only edits and the scene edit, the phase split, the host (cores, GPU or lavapipe) and whether 3 s held. Write the numbers inknow-how/hot-reload.md's run --web section (a docs PR in manifoldx), and open a follow-up issue for any phase that keeps a reload above 3 s. - Update the consumer's agent docs: its dev loop is
manifoldx run --web.
The consumer's reload test passes on its CI; #140 has the measured reload with its phases; the slice's "done when" of the spec holds: a save shows in the open tab with engine.state kept, and the camera stays where it was.
Where this plan departs from the spec
- The tab freezes during a reload (Q2). Section 08 says the server waits a short time for the tab's state; it does not say what the tab does meanwhile. Running on would throw away up to 2.5 s of motion at the swap; the desktop reloader blocks its window for the same time (
src/manifoldx/hot.py:175). - A kept scene drops the materials set at runtime. Section 08 keeps the three.js scene when the hash did not change. The scene remembers each
setMaterial(src/manifoldx/web/js/scene.js:180), so a kept scene would show a highlight the new version never set, where the desktop rebuilds the whole scene;resetMaterials()makes the kept scene equal a rebuilt one. - What crosses back from the tab is plain data (Q1). The spec has the tab send its
engine.state. Objects of transpiled classes, handles and functions do not come back; Python keeps its own value for those keys and for keys that never crossed. The desktop's own rule (know-how/hot-reload.md, "store plain data") is the same. - A newly opened tab may cause a rebuild (Q4). The spec uses the last state received only for the next save; a tab that opens after the state moved on gets a rebuild with that state, so an F5 keeps the camera.
- Static files are shared across versions (Q8). The spec exports "into a new version folder"; each version folder holds only
app/,state.jsonandreport.json, the glb lives underscenes/by hash, and the app's modules import../../pyrt.jsthroughtranspile_app'sruntimeargument (src/manifoldx/web/export.py:93). Copying three.js and the font per version cost 0.46 s of the measured 2.6 s. - The glb is still built on every save. The spec writes the glTF only when its hash changed; the hash is of the built bytes (
export_enginewrites a file,src/manifoldx/gltf/engine_export.py:110), so building it is not skipped, only writing it. It costs 0.05 s for the first consumer. engine.logjoins the subset (Q6). Section 08 names only the tab's console. The runtime's call record is renamedengine.callsto free the name (src/manifoldx/web/js/manifoldx.js:238).eventsanswers from Python, andmetricsdoes not exist under--web(Q9). The handlers' docstrings live in the Python engine, and the transpiled JS does not carry them; frame metrics are measured in the Python window (src/manifoldx/devchannel.py:119), which--webdoes not have.- The dev page moves to
/devunder--web(Q8): the app takes/, so the printed URL opens the app. - Task 2's round trip exports its own app, not
dev_orbit.py. Task 3 writesdev_orbit.py, after task 2, sotest_round_trip_of_the_snapshot_stateexportsORBIT(tests/web/test_devstate.py:16): a nested dict of floats, a tuple, a list of tuples, a set, a float32 array, an infinity and a tuple key that cannot cross. decodealso restores floats againstlike. The tab's JSON writes6.0as6, so without this rule the round trip came back with ints where Python had floats; a whole number decodes to a float where the previous value was a float (src/manifoldx/web/devstate.py:21).- The scene under
run --webhas no camera node (task 3). The glTF export writesengine.camerainto the glb, and the camera followsengine.state, so with it every save after the view moved hashed as a new scene. The page never reads the glTF's camera (it builds its own from the snapshot), sobuild_export(scene_camera=False)leaves it out through a newcameraflag ofexport_engine(src/manifoldx/web/export.py:86,src/manifoldx/gltf/engine_export.py:116);export --webstill writes it. - The old engine is detached after the new version is built (task 3). The plan detaches before the build; building first lets a failed build keep the running engine whole, with its shutdown handlers not yet fired (
src/manifoldx/web/dev.py:229). The device is shared either way. state_shais a hash both sides agree on (task 3, for Q4). The version message'sstate_shahashes Python's crossed state in the tab's encoded forms (devstate.encode), with numbers as floats, dict keys and set items sorted and every__skipalike, so the tab'sencodeStateof an unchanged state hashes the same (src/manifoldx/web/devstate.py:82,:116; the round-trip test asserts it).- A save during a reload is caught from the reload's start (task 3).
HotReloader._loadrecords mtimes after the app ran, which would miss a save during the tab's state request or the setup; the WebReloader records them before asking the tab (src/manifoldx/web/dev.py:190). dev_orbit.pyregistersbumpwithengine.on("bump")(bump)(task 3). The decorator form fails the export (the decorator @engine.on('bump') is outside the subset), so the test app uses the call form (tests/web/apps/dev_orbit.py:56). An app that decorates its handlers cannot export yet. Fixed by #157:@engine.on(...)and@engine.systemon a module function export as the call forms (src/manifoldx/web/types.py:687,src/manifoldx/web/transpile.py:389), anddev_orbit.pydecoratesorbitandbumpagain.error_lineprints aGuiUnsupportedas its text, like aTranspileError: it names the widget's place, and its traceback has no app frame (src/manifoldx/web/dev.py:57).- Without an answer, a reload takes the last state a tab sent (task 4). Task 3 kept
self.stateonNoTabor a timeout; the review focus asks for "the last state received", so the reload mergesTab.last_state(the last reply's or beacon's state) when the tab does not answer, and a rebuild for a newly opened tab (reasontab) takes it without asking, since the new tab holds the older state it opened on (src/manifoldx/web/dev.py:239). /api/eventsunder--webalso leaves out manifoldx's own handlers (task 4). The engine registers the GUI'spointer_down,pointer_moveandpointer_up; they are not roots, so the tab never runs them. The list and the emit check keep the app's handlers only (src/manifoldx/devchannel.py:263).- A tab's stream notices a closed tab within 0.25 s (task 4). The handler waits on its queue 0.25 s at a time and checks the socket for end of stream, so a call goes to the previous tab at once rather than after the next 15 s comment line (
src/manifoldx/devchannel.py:287,:402).Tab.disconnect(tab_id, q)takes the stream's queue, so an EventSource that reconnects under the same id is not dropped by its old stream (src/manifoldx/web/dev.py:75). - Forwarded requests fail as 504
the tab did not answerafter 5 s, and as 500 with the tab's text when its reply is{"ok": false}(src/manifoldx/devchannel.py:323). - A swap builds everything new before it touches the running version (task 5). The new modules, state and, when the hash changed, the new scene are loaded and built first; only then is the old scene disposed or reset and the GUI rebuilt, so a version that fails to load leaves the running one whole. A failed swap shows the error panel with
The tab keeps running v{n}.but does not setmx.error, so the running version keeps its loop (src/manifoldx/web/js/browser.js:218,:258). Swaps are chained, each after the one before, so versions apply in order (:271). - The scene frees itself (task 5).
dispose()is a method of the MxScene besideresetMaterials(), freeing each geometry, material, texture and the environment once, so the Node suite checks it (src/manifoldx/web/js/scene.js:187,:193). - The new input learns the lock through
ScriptInput.lockHeld()(task 5), a method besidelockLost()inmanifoldx.js, which stays free of the DOM (src/manifoldx/web/js/manifoldx.js:205). statusalso takesofflineandpausedmessages, and the running version again clearsoffline(task 5). An EventSource that reconnects gets the current version first, which is the running one; without this rule the tab would stay offline until the next save (src/manifoldx/web/js/dev.js:13). The model starts from the exportedINITIAL.- The tab's
pagehidebeacon lands in task 5, with thereload_stateanswer, since both sendencodeState(engine.state)(src/manifoldx/web/js/browser.js:293). Until task 7, the tab answers the other calls with{"ok": false, "error": "the tab does not answer <kind> yet"}(:289). dev.test.mjsneeds no registration:tests/web/test_node_suites.py:136runs every*.test.mjsin the folder.- The overlay's panel column says hidden, unchanged or a text (task 6).
overlayTextreturnspanel: nullto hide the error panel,undefinedto leave it, and a string to show it (src/manifoldx/web/js/dev.js:38). The reloading row names the next version, the running one plus one.#mx-devsits before#mx-error, which a sibling rule lifts above the status line while the overlay shows (src/manifoldx/web/js/index.html:27). - engine.log in an exported page goes nowhere (task 7). The page's
hooks.logsends to the dev server only in dev mode, so an export that logs every frame does not growengine.linesfor the page's life; as on the desktop outsiderun, the line is dropped (src/manifoldx/web/js/browser.js:142). Node still collects them inengine.lines. - A look's reply carries no state (task 7). It is the PNG body, so only the JSON replies carry
encodeState(engine.state)for Q4. Events an agent emitted wait in a queue that outlives a swap: the version running at the next frame fires them (src/manifoldx/web/js/browser.js:153). - dev_orbit.py gained a runtime material and a capture (task 8). The kept-scene and lock tests need the app itself to call
set_materialandcapture_pointer: H paints the box withLIT, a left click captures the pointer (tests/web/apps/dev_orbit.py:22,:44,:47). - The look's centre pixel is checked against the tab's own screenshot (task 8). The box is lit (ambient 0.3 plus Lambert), so its pixels are not its material colour within 8. The test compares look's centre and corner pixels with Playwright's screenshot of the same frame within 8, checks the centre is not the background, and checks the panel's centre against its
bgwithin 8, as the plan says (tests/web/browser/test_run_web.py:245). - The frame-error test names
orbit(task 8): dev_orbit's system isorbit, so the panel readsdev_orbit.py:N in orbit: ...(tests/web/browser/test_run_web.py:195). The tests tick once after a swap before reading the GUI's text or a held key: a ValueDisplay and the new input fill on the version's first frame. - The empty reload_state answer is a fetch wrapper (task 8). The tab's answers are closures, so the breaking test's init script rewrites the
stateof each reply the tab posts to{"__dict": []}(tests/web/browser/test_run_web.py:24).tests/test_cli.pyis new: no CLI test file existed. - The Chromium run found nothing to fix (task 8). Every test of
test_run_web.pypassed on its first run, so three mutations checked that they bite: no GUI paint in the look failstest_agent_commands, nolockHeld()after a swap failstest_lock_survives_a_save, and no pagehide beacon failstest_a_reopened_tab_keeps_the_camera.
Self-review
- Spec coverage, section 08 and slice 4: serve on 127.0.0.1 and print the URL (tasks 4, 8); the reloader's watching rules (3, through
HotReloader); the tab's state asked with a short wait, the last one without a tab (3, 4); setup rerun untilengine.run()with startup on a headless frame (3, reusing the device: 1); a new version folder, the glTF written only on a new hash (1, 3); the push, the import of new modules and snapshot, the scene kept on the same hash, no page reload (4, 5, 8); errors as underrunwith the overlay naming the Python line (3, 6, 8); look, state, set, emit, log against the tab (4, 7, 8); the first consumer's camera inengine.state, staying put (10); the reload measured and reported (3's timing line, 10). - Names across tasks:
build_export,Built.crossed,Built.scene_sha,Built.timings(1) are used in 3;encodeState,fromJSON,mergePatch,stateView(2) in 4, 5 and 7;merge_tab_state(2) in 3; the version and failure messages (3) in 4, 5 and 6;Tab.callkindsreload_state state patch emit look(4) answered in 5 and 7;status(5) feedsoverlayText(6);fireandengine.calls(7). - Proportion: code appears only for tests whose assertions carry values; the bodies are left to the implementer with their signatures and the algorithm's rules.