Web target, plan 2: the browser page
This plan builds slice 3 of the spec: manifoldx export --web writes a page that any static server can serve, where three.js draws the exported glTF, the GUI is HTML, and browser input reaches the transpiled systems in the same frame form the replay uses. It ends with the first consumer's web build coming from export --web and its hand-written JavaScript deleted. run --web (slice 4) gets its own plan.
manifoldx export --web app.py OUT/, then python -m http.server -d OUT: the page loads with a progress bar, draws the scene as the desktop does within a measured colour threshold, shows the GUI, takes keyboard, mouse and pointer lock, runs the systems every animation frame, and names the Python file and line of an error.
architecturemanifoldx.js stays the engine core with no three.js and no DOM, so the Node replay keeps working; browser-only modules sit on it: input.js (DOM events to Frames, pointer lock), scene.js (glTF, extras, calibration, handles to three.js objects), gui.js (HTML panels), sourcemap.js (Python lines), progress.js, and browser.js, the bootstrap index.html loads. three.js 0.186.1 is vendored in the wheel.
techPython 3.13; plain ES modules; three.js 0.186.1 (vendored, minified); Node 20+ for node --test; Playwright for Python with Chromium for the browser tests, in a separate CI job.
spec.knowledge/analysis/2026-11-06-web-target-design.html (sections 06, 07, 10 slice 3, 11)
builds onplan 1, merged to main as #141. This plan's branch feat/web-target-2 starts from that merge; its PR targets main.
later plansplan 3: run --web (slice 4), with the overlay that quotes the Python source and the agent commands against the tab.
How the pieces fit
Solid arrows: browser imports. Dashed: Node imports the same core. browser.js imports manifoldx.js for loadApp, step and the trace helpers.
Open questions
Settled here with a recommendation each; the tasks follow the recommendation. A maintainer's different answer changes only the task named.
Q1 · The sky calibration factor
The spec says three.js's sky comes out 8 to 16% darker. The first consumer's viewer settled on scaling scene.environmentIntensity by 1.5, measured as bringing the mean colour within 1 to 6% per channel, with the sun uncorrected. The two statements do not give the same factor.
recommendStart from 1.5 for the environment and 1.0 for the sun, and let task 10's lit scene decide: if 1.5 misses the threshold, sweep the factor in steps of 0.05 and keep the one with the smallest worst channel error. Write the measured numbers in the comment beside CALIBRATION.
Q2 · Pointer lock in headless Chromium
Whether headless Chromium under Playwright grants requestPointerLock is not settled by the code; if it refuses, the runtime clears pointer_captured on the next frame and the browser trace diverges from Python's, where a capture always takes.
recommendTask 9 step 1 probes it. If the real lock is refused, the test installs an init script that replaces requestPointerLock/exitPointerLock with a fake that sets document.pointerLockElement and fires pointerlockchange, and records navigator.userActivation.isActive at each call; the test asserts every request came with an active user activation.
Q3 · Phones and touch
The first consumer's page supports touch: drag to look, tap to pick at the finger. The spec does not mention touch, and phones have no pointer lock.
recommendPointer events of any pointer type feed the mouse fields, as rendercanvas's own browser backend does (a touch is button 1, its motion is d, its position pos). capture_pointer(True) returns False where the canvas has no requestPointerLock or the last pointer was a touch, as the desktop returns False with no window. Add fov to engine.camera's surface so the consumer can build a ray at mouse_pos in Python and pick at a tap (task 1).
Q4 · The consumer's page features with no manifoldx counterpart
Its page has a menu of named views tied to the URL hash, a ?fps counter, a centred crosshair and a help list. The desktop GUI paints every anchor as top-left (render/passes/gui.py:398, manifoldx#13).
recommendThe HTML GUI honours all nine anchors as the widgets declare them; the desktop bug stays its own issue. The crosshair becomes a centred Panel with a Text("+"), the help list Text widgets, the views keys handled in the consumer's Python (as its desktop viewer does), the fps counter a ValueDisplay or nothing. The URL hash is dropped until slice 4 puts the view in engine.state.
Q5 · Widgets beyond Panel, Text and ValueDisplay
The spec defers Button, Slider and Toggle; Image is not mentioned.
recommendThe export fails on any of them in engine.gui with the GUI widget Button is not supported by export --web yet (panel 0, child 2), exit 1, nothing written: a silent drop would be a wrong app, the same rule as the subset.
Q6 · Where Playwright and the GPU come from in CI
The repo has no Playwright dependency. The visual check needs a headless Python frame, and tests/conftest.py:37 skips every adapter request on a runner without one.
recommendA browser dependency group with playwright, and a second CI job, browser, that installs it, runs playwright install --with-deps chromium and apt-get install mesa-vulkan-drivers (lavapipe gives wgpu a CPU adapter), then runs tests/web/browser only. The main job stays as it is, so the GPU tests do not start running there; without the group the browser tests skip with playwright not installed.
Q7 · Escape while the pointer is locked
While the pointer is locked, Chromium takes Escape to release it and does not deliver the keydown to the page. An app that releases on just_pressed("Escape"), as web_walk does, then never sees that frame.
recommendWhen the lock ends without the app asking, the next frame's just holds "Escape" (unless an Escape keydown already arrived) and pointer_captured reads False. The app's own branch runs, and its capture_pointer(False) is a no-op on an unlocked page.
Q8 · Plan 1's task 14
Plan 1's last task (the consumer replays in its own CI) is still pending. It needs the same pin and the same three API swaps as this plan's last task.
recommendFold it into task 12: one consumer branch pins manifoldx after both PRs merge, adds the replay test and CI, then moves the web build to export --web. If plan 1's task 14 lands first on its own, task 12 skips its first three steps.
settledPlan 1's task 14 runs on its own in the consumer's repo now that #141 is merged, so task 12 skips its first three steps.
Q9 · The GUI's font
The desktop measures and draws GUI text with DejaVu Sans Mono (viz/text.py:19). With the browser's default font, a fixed-width panel wraps or clips differently.
recommendCopy DejaVuSansMono.ttf (343 KB, already in the wheel) into the export as fonts/ and use it through @font-face, so the layout matches; the spec makes layout, not pixels, the goal.
Global constraints
- No app JavaScript: nothing here asks an app author to write JS. Every JS file lives in manifoldx.
- The headless runtime and the replay keep working:
manifoldx.jsimports neither three.js nor any DOM name, andtests/web/test_replay.pypasses after every task that touches it. - Same input, same frames: the browser builds
engine.inputonly throughScriptInput.setFrame(frame), the path the replay uses. There is no second input implementation. - Outside what the browser supports fails the export with the place and the reason; nothing is dropped silently.
- Works offline from a static server: no request leaves the export folder. three.js is vendored, pinned to 0.186.1, minified, with its LICENSE.
- The desktop renderer and ECS do not change. Python changes are additive (the frame form's optional fields, the state's GUI and camera fields).
- Colours: material colours reach three.js as the glTF's linear factors; background and fog colours are linear (as
scene_extraswrites them); GUI colours are sRGB hex, as CSS reads them. - Node and Playwright are test dependencies only. Tests skip with
node not foundorplaywright not installed/chromium not installed. - Shared hosts: each task's verify runs only the tests covering it.
make test, the browser tests and the visual check 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 the system temp dir via pytest's
tmp_path, never in the repo.
Review focus
- Shift released before the key (Shift+2 sends keydown
"@", then keyup"2"): the key must not stay held. Keys are tracked byevent.codeand named fromevent.keyat keydown. test in task 4 - Focus lost with a key held (alt-tab while walking): every held key and button is released on
blurand reported as released in the next frame, or the rig walks forever. test in task 4 - Pointer lock refused or ended by the browser (Escape, a second request inside Chromium's cooldown after an exit, a request with no user gesture):
pointer_capturedreadsFalsefrom the next frame and the app keeps running. tests in tasks 4 and 9 - The page opened as a file (
file://, double-clicked): module scripts do not load; the page shows "serve this folder over HTTP (python -m http.server)" instead of a blank canvas. test in task 9 - A high-density screen and a resize (devicePixelRatio 2, the window resized):
engine.w/handviewport_sizeare CSS pixels as the desktop's logical pixels, the canvas renders at up to 2× and the camera's aspect follows. test in task 9
File structure
| file | responsibility |
|---|---|
| src/manifoldx/web/js/manifoldx.js | the core, Node and browser: state loading, createEngine with scene hooks, ScriptInput over the widened frame, step, guiValues, and the trace helpers moved from replay.mjs (toJSON, pathValue, traceEntry) |
| src/manifoldx/web/js/input.js | FrameBuilder (DOM-like events to one Frame per animation frame), attachDom, PointerLock |
| src/manifoldx/web/js/scene.js | the glTF in three.js: extras (background, fog, environment, sun, shadows), CALIBRATION, BasicMaterial shading, handles to meshes and materials, the camera each frame |
| src/manifoldx/web/js/gui.js | the state's GUI description to HTML; panelCss as a pure function; text updates; pointer_over_gui |
| src/manifoldx/web/js/sourcemap.js | line mappings of the app's .js.map files; a JS stack to Python file:line |
| src/manifoldx/web/js/progress.js | the loading line (sizes, rate, time left) |
| src/manifoldx/web/js/browser.js | the bootstrap: fetch with progress, renderer, loadApp with hooks, the animation loop, the error panel, window.__mx |
| src/manifoldx/web/js/index.html | the page template: importmap, canvas, GUI layer, progress, fallback text |
| src/manifoldx/web/vendor/three/ | three.js 0.186.1: three.module.js, three.core.js (minified builds), addons/loaders/GLTFLoader.js, addons/utils/BufferGeometryUtils.js, LICENSE, VERSION, SOURCE |
| src/manifoldx/web/gui.py | gui_spec(engine): panels, anchors, offsets, resolved styles, getter indexes; the unsupported-widget error |
| src/manifoldx/web/replay.py | Python ScriptInput over the widened frame |
| src/manifoldx/web/types.py, snapshot.py | engine.gui.pointer_over_gui and engine.camera.fov in RUNTIME_SURFACE; fov and up in the state's camera |
| src/manifoldx/web/export.py | writes index.html, the browser modules, vendor/three/, fonts/, the state's gui |
| tests/web/js/*.test.mjs | Node tests of the pure browser modules, run by tests/web/test_node_suites.py |
| tests/web/browser/ | Playwright tests: replay parity in Chromium, the page's failure modes, visual parity |
| tests/web/apps/lit_yard.py | a test app with StandardMaterial, sun, shadows, the sky environment and fog, for the calibration |
| .github/workflows/test.yml, pyproject.toml | the browser job and dependency group |
Tasks
1The frame form grows; the engine surface gains gui and fovweb/replay.py · js/manifoldx.js · web/types.py · web/snapshot.py · tests/web/test_frames.py · tests/web/js/runtime.test.mjs
interfaces
"up": [str] keys released this frame · "released": [int] buttons released this frame · "pos": [x, y] pointer position in CSS pixels from the canvas's top-left · "wheel": [dx, dy] · "mods": [str] held modifiers among Alt, Control, Meta, Shift, sorted · both ScriptInputs answer just_released, just_mouse_released, mouse_pos, wheel_delta, modifiers from them · RUNTIME_SURFACE: engine.gui with pointer_over_gui: BOOL; engine.camera.fov: NUM · state.json engine.camera gains "fov" (degrees) and "up" · JS Camera holds fov and up (Float32Array)- Write the failing tests in
tests/web/test_frames.py: a small app whose system writesengine.state["r"] = [inp.just_released("w"), inp.just_mouse_released(1), list(inp.mouse_pos), list(inp.wheel_delta), list(inp.modifiers), engine.gui.pointer_over_gui, engine.camera.fov], replayed on both sides over the frames below;compareisNoneand the Python trace's frame 1 reads[True, True, [12.0, 30.0], [0.0, -3.0], ["Shift"], False, 50.0]for an engine whose camera hasfov=50. Also: the existing fixturetests/web/fixtures/web_walk_script.jsonstill replays with no mismatch (the fields are optional). - Run
uv run pytest tests/web/test_frames.py -v: fails (the app'sengine.guiandcamera.fovare unknown to the transpiler; the frame fields are ignored). - Implement: the optional fields in both
ScriptInput.set_frame/setFrame(the class docstrings and the module docstring ofreplay.pylist them); the two surface entries;fovandupinsnapshot.py'senginesection and in the JSCamera;engine.guiresolves to the objectcreateEnginealready makes. Add one case per new getter totests/web/js/runtime.test.mjs. - Run
uv run pytest tests/web/test_frames.py tests/web/test_replay.py tests/web/test_node_suites.py -v: pass. - Commit:
feat(web): releases, pointer position, wheel and modifiers in replay frames.
uv run pytest tests/web/test_frames.py tests/web/test_replay.py tests/web/test_node_suites.py -q: all pass, none skipped on a host with Node.
2The core takes scene hooks; trace helpers move into itjs/manifoldx.js · js/replay.mjs · tests/web/js/runtime.test.mjs
interfaces
createEngine({w, h, camera, materials, log, state, hooks}) with hooks = {setMaterial(entityIndex: number, materialId: number): void, capture(on: boolean): boolean}, both optional; headless defaults: no-op and () => true · engine.set_material logs ["material", entity, id] then calls hooks.setMaterial · input.capture_pointer(on) calls hooks.capture(on); on true sets the flag and logs ["capture", on], on false logs nothing and returns false · input.lockLost(): the flag reads false from now · loadApp(state, modules, options) passes options.hooks through · exported from manifoldx.js: toJSON(value), pathValue(app, path), traceEntry(app, paths, logStart) -> object; replay.mjs imports them- Write the failing Node tests: with hooks,
set_material(h, m)callssetMaterial(h.index, m.id)once and still logs; acapturehook returningfalseleavespointer_capturedfalse and the log unchanged;lockLost()clears the flag;traceEntryreturns the same objectreplay()built before, for one frame of the web_walk export (build it in the test withexport_webfrom a Python fixture that writes the folder once per session). And a static check:manifoldx.js's source contains noimportother than./pyrt.jsand nodocument,windoworthree. - Run
uv run pytest tests/web/test_node_suites.py -v: fails. - Implement. The
logstays the trace's record in the browser too; the hooks are where the browser acts. - Run
uv run pytest tests/web/test_node_suites.py tests/web/test_replay.py -v: pass, the replay unchanged. - Commit:
refactor(web): the runtime core takes scene hooks and owns the trace helpers.
uv run pytest tests/web/test_node_suites.py tests/web/test_replay.py -q: pass; node src/manifoldx/web/js/replay.mjs run in a fresh export prints the same JSON as before the change.
3Vendor three.js 0.186.1 into the wheelsrc/manifoldx/web/vendor/three/ · tests/web/test_vendor.py
interfaces
manifoldx.web.export.THREE_VERSION = "0.186.1" · VENDOR = Path(__file__).parent / "vendor" / "three" holding three.module.js, three.core.js, addons/loaders/GLTFLoader.js, addons/utils/BufferGeometryUtils.js, LICENSE, VERSION, SOURCE- Write the failing test
tests/web/test_vendor.py: every file above exists;VERSIONreadsTHREE_VERSION; each vendored JS file's import specifiers (from "...") are"three"or a relative path to a vendored file, so the folder makes no request outside itself;three.module.js's first 300 bytes hold the license header. - Run it: fails.
- Fetch the package once into scratch outside the repo:
npm pack three@0.186.1, check itsintegrityagainstnpm view three@0.186.1 dist.integrity, and copybuild/three.module.min.jsasthree.module.js,build/three.core.min.jsasthree.core.js(fix the one import./three.core.min.jsto./three.core.js), the two addons fromexamples/jsm/, andLICENSE. WriteSOURCE: the tarball name, its integrity string and the files taken, so the next upgrade repeats the step. Delete the scratch. - Run the test: pass. Then
uv build --wheel -o "$TMP/whl"andunzip -l "$TMP"/whl/*.whl | grep -c web/vendor/three: 7. - Commit:
chore(web): vendor three.js 0.186.1.
uv run pytest tests/web/test_vendor.py -q: pass; the wheel lists the seven vendored files.
4Browser input: DOM events to Frames, and pointer lockjs/input.js · tests/web/js/input.test.mjs
interfaces
class FrameBuilder: keyDown({key, code, repeat, altKey, ctrlKey, metaKey, shiftKey}), keyUp({code, ...mods}), pointerDown({button, x, y, pointerType}), pointerUp({button, x, y}), pointerMove({movementX, movementY, x, y}), wheel({deltaX, deltaY, deltaMode}), blur(), lockEnded(), take(viewport: [w, h]) -> Frame · attachDom(canvas, builder, {devicePixelRatio}) -> detach() · class PointerLock(canvas, doc, builder) with request(on) -> boolean (the capture hook), locked: boolean- Write the failing Node tests over plain objects (no DOM):
- Write the failing
PointerLocktests with a fake canvas and document:request(true)callscanvas.requestPointerLock()and returnstruewhendoc.userActivationis active; with no activation it arms a one-shotpointerdownlistener that makes the request, and returnstrue; with norequestPointerLockon the canvas, or the last pointer a touch, it returnsfalse(Q3); apointerlockerroror apointerlockchangeto unlocked that the app did not ask for callsbuilder.lockEnded(), which makes the next frame'sjusthold"Escape"unless an Escape keydown came (Q7), and calls the engine'sinput.lockLost();request(false)callsdoc.exitPointerLock()only when locked. - Run
uv run pytest tests/web/test_node_suites.py -v: fails. - Implement
input.js.attachDomlistens onwindowfor keys andblur, on the canvas forpointerdown(withsetPointerCapture), onwindowforpointermove/pointerup,wheel(passive false,preventDefault),contextmenu(prevented, so a right drag looks). It callspreventDefaulton Tab and on Space, so the page neither moves focus nor scrolls; it leaves Control+W and other browser shortcuts alone. Positions are CSS pixels relative to the canvas's bounding box. - Run: pass.
- Commit:
feat(web): DOM input to replay frames, and pointer lock.
node --test tests/web/js/input.test.mjs: all pass.
5The scene in three.js: extras, calibration, handlesjs/scene.js · tests/web/js/scene.test.mjs
interfaces
extras.mx = {entity, material}, scene extras.manifoldx = {background, fog?, shadows?, environment?, mx_materials}) · produces CALIBRATION = {environment: 1.5, sun: 1.0} · async buildScene(THREE, gltf, renderer) -> MxScene with .scene, .camera (PerspectiveCamera), .entities: Map<number, Mesh[]>, .materials: Map<number, Material>, .setMaterial(entity, id) (the hook), .sync(engine) (camera from engine.camera, aspect from engine.w/h), .materialOf(entity) -> id | null, .setCalibration(partial)- Write the failing Node tests in
tests/web/js/scene.test.mjs, over the web_walk export'sscene.glbparsed with the vendoredGLTFLoader.parseAsync(Node 20+ has the globals it needs for an untextured glb) and a stub renderer (capabilities.maxTextureSize4096;buildScenecalls the PMREM generator only when the scene has an environment). Assertions:entitiesholds everymx.entityin the glTF and each value lists the meshes under that node;materialsholds every id ofmx_materials, including the gold that no entity uses at export;setMaterial(box, goldId)makes each mesh of that entity usematerials.get(goldId)andmaterialOf(box) === goldId; a glTF material namedBasicMaterialorPhongMaterialbecomes the mx basic material (next step) with the same linear colour andfog: false;scene.backgroundequalsextras.backgroundas linear RGB; aftersync, the three camera's position, up, fov, near, far and aspect equal the engine's and its world direction equalsget_forward()within 1e-6. IfGLTFLoadercannot parse in Node after all, move these assertions into task 9's browser test and record it under "where this plan departs". - Run: fails.
- Implement
buildScene:- BasicMaterial and PhongMaterial: the desktop lights them with a fixed light,
0.3 + 0.7 * max(dot(n, normalize(1, 1, 1)), 0)in world space (resources.py:109-118; Phong uses Basic's shader,resources.py:1850). Draw them with aMeshBasicMaterialwhoseonBeforeCompilemultiplies the diffuse colour by that brightness from the world normal,fog: false(the desktop fogs only StandardMaterial). Without this an unlit scene such as web_walk renders black. - Background, fog (
THREE.Fogfrom start, end, colour), and the environment as the first consumer builds it: the float32 equirectangular buffer view, rows flipped, to a half-floatDataTexture, throughPMREMGenerator.fromEquirectangular,scene.environmentIntensity = env.intensity * CALIBRATION.environment. - The sun: the loader's directional light scaled by
CALIBRATION.sun; withshadows, every mesh casts and receives, and the light's orthographic shadow camera is fitted once to the scene's bounding sphere (the desktop'sauto_fit), map sizemin(resolution, maxTextureSize),bias -0.0005,normalBias 0.05,radius = pcf_radius; withauto_fit: falseusetarget,extent,near,far. - Renderer settings are
browser.js's (task 8):outputColorSpace = SRGBColorSpace,NoToneMapping,shadowMap.type = PCFShadowMap.
- BasicMaterial and PhongMaterial: the desktop lights them with a fixed light,
- Run: pass.
- Commit:
feat(web): the exported scene in three.js with manifoldx's calibration.
node --test tests/web/js/scene.test.mjs: pass.
6The GUI as HTMLweb/gui.py · web/export.py · js/gui.js · tests/web/test_gui_spec.py · tests/web/js/gui.test.mjs
interfaces
find_roots (getter roots in panel walk order) · produces gui_spec(engine) -> dict: {"scale": float, "design_height": float | None, "panels": [node]}, node {"kind": "Panel", "anchor", "offset": [x, y], "style": {resolved}, "children": [node]} · {"kind": "Text", "text", "style"} · {"kind": "ValueDisplay", "value": k, "min_width", "style"} where k is the index among the getter roots · GuiUnsupported(what) raised for Button, Slider, Toggle, Image (Q5) · state.json "gui" · JS panelCss(node, scale, isRoot) -> {[cssProperty]: string}, buildGui(layer, spec) -> Gui with .update(values: string[]), .rescale(engineH), .pointerOver: boolean- Write the failing Python tests:
gui_specof web_walk's engine equals the expected dict (one panel,top-left, offset[16, 16], the style withwidth 240,height 76,padding 8,bg "#1a1a1aC0"and the theme's other keys resolved, three ValueDisplays with values 0, 1, 2); a style class defined withstyle.defineis resolved into the spec; an engine with aButtonmakesexport_webreturn 1, printthe GUI widget Button is not supported by export --web yet (panel 0, child 1), and write nothing. - Write the failing Node tests of
panelCss:direction "v"isflex-direction: column,"h"row;padding "4 8"becomes four pixel values; every size, padding, gap, border, radius, font size and offset is multiplied by the scale; the nine anchors place a root panel (top-rightwith offset[16, 16]isright: 16px; top: 16px,centerisleft: 50%; top: 50%with atranslate(-50%, -50%)then the offset);bg "#1a1a1aC0"passes through as CSS hex;width: nullleaves the width to content; aflexvalue becomesflex-grow. - Run
uv run pytest tests/web/test_gui_spec.py tests/web/test_node_suites.py -v: fails. - Implement.
gui_speclives inweb/gui.pyand walksengine.gui._panelsasfind_rootsdoes;export_webwrites it under"gui"and turnsGuiUnsupportedinto exit 1.buildGuibuildsdivs in a layer over the canvas, text throughtextContentonly, the font"mx-gui"(DejaVu Sans Mono fromfonts/, Q9),white-space: pre,overflow: hiddenon sized panels;updatewrites a ValueDisplay's text only when it changed;rescalerecomputes whendesign_heightis set;pointerenter/pointerleaveon root panels keeppointerOver, whichbrowser.jscopies intoengine.gui.pointer_over_guieach frame. Panels take pointer events, so a click on a panel does not reach the canvas, as the desktop's bridge consumes it. - Run: pass.
- Commit:
feat(web): the GUI as HTML from the widgets' anchor, offset and style.
uv run pytest tests/web/test_gui_spec.py -q and node --test tests/web/js/gui.test.mjs: pass.
7Python lines for errors in the pagejs/sourcemap.js · tests/web/js/sourcemap.test.mjs · tests/web/test_node_suites.py
interfaces
sources rewritten to the app path by export.py) · produces lineTable(map) -> Int32Array (generated line to 1-based Python line, 0 where unmapped) · pythonFrames(stack: string, maps: {[jsUrlSuffix]: {source, lines}}) -> [{file, line, fn}], the JS frames under app/ mapped, others dropped · describe(error, maps) -> string: "app.py:57 in walk: TypeError: Cannot read properties of null (reading 'x')", the first Python frame, then the rest as " called from app.py:121 in tick"- Write the failing Node test, driven from
tests/web/test_node_suites.pywith a fixture: export a two-module app whose system calls a helper in the second module that reads an attribute ofNone; in Node, import the module, run the system, catch the error, and checkdescribe(err, maps)starts withhelper.py:LINE in helperwhere LINE is the line of the attribute read, and names the system's call line next. Use Chromium's and V8's stack form (at fn (url:line:col)); Firefox's form (fn@url:line:col) parses too. - Run: fails.
- Implement: base64 VLQ decoding of
mappings, keeping each generated line's first segment's source line. - Run: pass.
- Commit:
feat(web): Python file and line for a JS error from the source maps.
uv run pytest tests/web/test_node_suites.py -k sourcemap -q: pass.
8The page: index.html, the bootstrap and what export writesjs/index.html · js/browser.js · js/progress.js · web/export.py · tests/web/test_export_web.py · tests/web/js/progress.test.mjs
interfaces
index.html, browser.js, input.js, scene.js, gui.js, sourcemap.js, progress.js, vendor/three/, fonts/DejaVuSansMono.ttf · index.html carries <title> from engine.title, <meta name="scene-bytes"> and <meta name="scene-gzip-bytes"> · window.__mx = {ready: Promise, app, scene, gui, frames: Frame[], trace: object[], error: string | null, manual(on: boolean), tick(dt: number) -> {frame, entry}, loadStats: {bytes}} · progressLine({fraction, download, rate, received}), RateMeter, frameDt(now, last) = min((now - last) / 1000, 0.1)- Write the failing tests:
export_webof web_walk writes every file above;index.html's title isWeb walk, itsscene-bytesequals the size ofscene.glbandscene-gzip-bytesthe size ofgzip.compress(glb, 9); its importmap maps"three"to./vendor/three/three.module.jsand"three/addons/"to./vendor/three/addons/; it contains the fallback textserve this folder over HTTP (python -m http.server); no file in the folder names anhttp:orhttps:URL outside comments and the license. Node tests ofprogressLineandRateMeterported from the first consumer's tests (sizes in KB and MB, the rate over the last 3 s, "about N s left" under 90 s and "about N min left" above), and offrameDt(a 5 s gap from a background tab gives 0.1). - Run
uv run pytest tests/web/test_export_web.py tests/web/test_node_suites.py -v: fails. - Implement
browser.js, in this order: check WebGL2 (else the error panel says the browser has none); fetchstate.jsonand the app modules; fetchscene.glbstreamed, counting bytes againstscene-bytesand showingprogressLinein the progress element (wire bytes fromscene-gzip-byteswhen the response is gzip-encoded);GLTFLoader.parseAsync; the renderer (pixel ratiomin(devicePixelRatio, 2), the settings of task 5);buildScene;buildGui;loadApp(state, modules, {hooks: {setMaterial: mx.setMaterial, capture: lock.request}});attachDom; hide the progress element; thenrenderer.setAnimationLoop: each frameframe = builder.take([canvas.clientWidth, canvas.clientHeight]),engine.gui.pointer_over_gui = gui.pointerOver,engine.input.setFrame(frame),step(app, frameDt(now, last)),gui.update(guiValues(app)),scene.sync(engine), render. A resize of the canvas reaches the engine through the frame'svp(as the replay does) and the renderer throughsetSize(w, h, false). An error thrown by the app's code pauses the loop and showsdescribe(err, maps)in the error panel, also in__mx.errorandconsole.error; an error while loading shows its message and the HTTP hint.manual(true)stops the loop;tick(dt)runs one frame as the loop does, appends to__mx.framesand__mx.trace(traceEntrywith the paths given by__mx.paths), and returns them. - Implement the export side: copy the modules,
vendor/three/and the font; renderindex.htmlfrom the template withhtml.escapeon the title. - Run: pass. Then open it once by hand:
uv run manifoldx export --web examples/web_walk.py "$TMP/ww" && uv run python -m http.server -d "$TMP/ww" 8765and load it in a browser (aegis'sbrowser_openonhttp://127.0.0.1:8765works): the yard draws, the panel readspicked: nothing, a click captures, WASD walks. - Commit:
feat(web): export --web writes the browser page.
uv run pytest tests/web/test_export_web.py -q and node --test tests/web/js/progress.test.mjs: pass; the manual look shows the scene and the panel.
9Chromium replays web_walk as Python doespyproject.toml · tests/web/browser/conftest.py · tests/web/browser/test_page.py
interfaces
window.__mx, plan 1's replay_python and compare · produces dependency group browser = ["playwright>=1.55"] · fixtures served(folder) -> url (a python -m http.server subprocess on a free port of 127.0.0.1, stopped by PID at teardown), chromium (headless, args --enable-unsafe-swiftshader, --use-angle=swiftshader), web_walk_export (session-scoped export into tmp_path_factory)- Write
conftest.py: skip the folder withplaywright not installedwhenimport playwrightfails andchromium not installedwhen launching fails. Probe pointer lock (Q2): in a page served from the export, click the canvas and readdocument.pointerLockElementafterpointerlockchangeor 1 s. Keep the fake lock of Q2 as an init script, used only when the probe fails; the probe's result is printed in the test output. - Write the failing test
test_chromium_matches_python: open the page with viewport 800×500, await__mx.ready, set__mx.paths = ["rig.pos", "rig.yaw", "rig.mode", "selected"],__mx.manual(true). Drive a DOM-level script of about 200 ticks through Playwright's real input (page.keyboard.down/up,page.mouse.move/down/up,page.mouse.wheel,page.set_viewport_size), one__mx.tick(1/60)after each step's events: walk with W and D, a click that captures, mouse look, three clicks aimed at different boxes (aim them by setting the look first with mouse moves the test computes from the boxes' centres), Tab, Space and Shift in fly mode, a release byexitPointerLock(the Escape path of Q7), a right drag, a resize to 640×480. Then: Also assert the frames the page built hold what the script did: the tick afterkeyboard.down("w")has"w"injustandkeys; the tick after the resize hasvp == [640, 480]. - Write the failing page tests:
test_file_url_says_to_serve(openindex.htmlasfile://: the textserve this folder over HTTPis visible);test_error_names_the_python_line(a test apptests/web/apps/raises.pywhose system reads an attribute ofNoneafter 5 frames: after 6 ticks__mx.errorstarts withraises.py:LINE in, the error panel shows it, further ticks run nothing);test_high_density_and_resize(a context withdevice_scale_factor=2: after a tickengine.wis the CSS width, the canvas'swidthattribute is twice it,scene.camera.aspectisw / h);test_progress_counts_the_scene(__mx.loadStats.bytesequals thescene-bytesmeta and the progress element is hidden after ready);test_lock_lost_releases(capture, thendocument.exitPointerLock()from the test: the next tick's frame has"Escape"injustandpointer_capturedis false). - Write the breaking tests: swap two entries of
__mx.scene.entitiesbefore the script, and the material assertion fails; patch the page'sFrameBuilderso key names keep their case, andcomparereturns a mismatch. Each must fail for the reason named. - Run
uv sync --group browser && uv run pytest tests/web/browser/test_page.py -von a host with Chromium: fails before the fixes the run shows, then passes. On a shared host, reuse the Chromium already in~/.cache/ms-playwrightby pinningplaywrightto the version that cache matches, rather than downloading another. - Commit:
test(web): Chromium replays web_walk as Python does.
uv run pytest tests/web/browser/test_page.py -v: 8 passed (the replay, five page tests, two breaking cases); without the group, all skipped with playwright not installed.
10Visual parity: mean colour per channeltests/web/apps/lit_yard.py · tests/web/browser/test_visual.py · js/scene.js (CALIBRATION)
interfaces
CALIBRATION and setCalibration, task 9's fixtures, Engine.render_frame · produces mean_rgb(img: np.ndarray) -> tuple[float, float, float] in 0–255 · THRESHOLD = 0.08: for each channel, abs(web - py) <= max(THRESHOLD * py, 4.0)- Write
tests/web/apps/lit_yard.py: a ground and five boxes in StandardMaterial of different colours and roughness,set_sunwith a DirectionalLight,enable_shadows(),set_environment("sky"),enable_fog(20, 60), a fixed camera looking over the yard, no GUI, no systems. Keep it under 50 lines. - Write the failing test, parametrised over
web_walkandlit_yardat 320×200: the Python side captures the engine asreplay_pythondoes, removesengine.gui's panels, callsengine.render_frame()until the environment's precompute is done (not engine._loading(), so the loading panel is not in the frame), and takesmean_rgb; the browser side opens the export at 320×200 with device scale 1, hides#mx-gui, ticks once with an empty frame, screenshots the canvas, and takesmean_rgb. Each channel within the threshold. The test prints both means and the ratio per channel. - Write the breaking test:
setCalibration({environment: 1.0})on lit_yard, and swapping the mx basic material for plainMeshStandardMaterialon web_walk; each must exceed the threshold. If a break stays within it, the threshold is too loose: tighten it to the measured worst case plus 2 points and say so in the test's comment. - Run on a host with a wgpu adapter (lavapipe is enough):
uv run pytest tests/web/browser/test_visual.py -v -s. If lit_yard misses with 1.5, sweepCALIBRATION.environmentas Q1 says, keep the best, and write the measured means and the chosen factor in the comment besideCALIBRATION. - Commit:
test(web): visual parity of the browser page with the desktop frame.
uv run pytest tests/web/browser/test_visual.py -v -s: 4 passed (2 scenes, 2 breaks); the printed ratios are within the threshold.
11CI job, docs and the PR.github/workflows/test.yml · know-how/web-export.md · AGENTS.md · CHANGELOG.md
- Add the
browserjob to.github/workflows/test.yml, besidetest: - Update
know-how/web-export.md: the page replaces "there is no browser page yet"; serving the folder; what the page does (progress, input mapping with the frame's new fields, pointer lock and its user-gesture rule, Escape, touch, the GUI's supported widgets and anchors, the error panel); the calibration and how to re-measure it; the browser tests and thebrowsergroup; how to upgrade three.js (theSOURCEfile). Update the sub-projects line inAGENTS.mdto name this plan. Add the CHANGELOG entry under[Unreleased]. - Run
make lintand the tests oftests/weboutsidebrowser/; leavemake testand the browser tests to CI. - Push
feat/web-target-2, open the PR againstmainreferencing #140, and work it until every CI job is green. Then merge it.
CI: test and browser green on the PR; the browser job's log shows tasks 9 and 10's tests passed, none skipped.
12The first consumer's web build comes from export --webthe consumer's repository: app code, a replay test, its CI, its web build; its hand-written JS deleted
Runs in the first consumer's repository after both manifoldx PRs merge; its own issue, branch and PR. It folds in plan 1's task 14 (Q8): skip steps 1–3 if that task already landed.
- Pin manifoldx to the merge commit. Replace the three private workarounds with
engine.set_material,engine.input.capture_pointerandengine.input.viewport_size; its desktop tests and its screenshot command still pass. - Add a replay test:
manifoldx export --webof the app into a temp folder, its own 900-frame script,paths=["rig.pos", "rig.yaw", "rig.pitch", "rig.mode", "selected", "captured"],compareisNone. - CI: install
mesa-vulkan-driversso the startup's textures get a CPU device, then run the replay test. - Move what the hand-written page does into the Python app, as Q3 and Q4 recommend: the info panel, mode line and help as GUI widgets; the crosshair as a centred panel; views as keys; picking at a tap through
mouse_posandcamera.fovwhencapture_pointerreturnsFalse. Each change keeps its desktop tests passing. - Make its web build run
manifoldx export --webinto its output folder, and its deploy procedure publish that folder. The page loads, walks, picks and shows the panel on the deployed site, checked in a browser, and its visual check against the desktop screenshot stays within the threshold of task 10. - Delete the hand-written page: its viewer, HUD, rig, spatial and terrain modules, progress module,
index.html,vendor/three/, their JS tests andpackage.json, and the golden files that only fed them. Update its agent docs and its deploy know-how.git grep -l "three"in the consumer finds nothing outside lock files and docs that explain the move.
The consumer's CI runs the replay green; its deployed page is the export's; its repository holds no JavaScript of its own.
Where this plan departs from the spec
- The runtime is split in files. The spec's section 06 describes one
manifoldx.jsthat loads the glTF with three.js. Plan 1'sreplay.mjsimportsmanifoldx.jsin Node (src/manifoldx/web/js/replay.mjs:9), where neither three.js nor a DOM exists, somanifoldx.jsstays the shared core and the browser parts are their own modules. The spec's open question on where the runtime is developed keeps its answer: plain ES modules in the package. - BasicMaterial and PhongMaterial are shaded by the runtime. The spec names only the sky correction. The desktop draws those two with a fixed world light (
src/manifoldx/resources.py:109-118) that a glTF cannot carry; the writer exports them as rough PBR (src/manifoldx/gltf/writer.py:214-217), which renders black in a scene with no lights, as web_walk is. - The replay frame gains optional fields (
up,released,pos,wheel,mods). The spec's frame form came from plan 1 (src/manifoldx/web/replay.py:5-8), which answers releases, position and wheel as nothing; the browser produces all of them, and the parity test needs both sides to read them. Existing scripts stay valid. - Two surface additions:
engine.gui.pointer_over_gui, which the spec lists in the first consumer's surface butRUNTIME_SURFACElacks (src/manifoldx/web/types.py:452), andengine.camera.fov, for picking at a tap (Q3). - No meshopt compression and no precompressed files. Section 07 compresses
scene.glbwith meshopt when gltf-transform is present, and section 05 says the export gzips the snapshot. The first consumer does neither today, andpython -m http.servercannot serve.gzfiles transparently; the page writes both sizes so the progress bar works when a deployment's server gzips. Meshopt is left for when a scene needs it. - GUI anchors. The HTML GUI places all nine anchors as declared, while the desktop paints every anchor top-left (
src/manifoldx/render/passes/gui.py:398, manifoldx#13), so a non-top-left panel differs between the two until that issue is fixed. - Unsupported widgets fail the export (Q5) rather than being left out; the spec only defers them.
- The visual check runs in its own CI job with lavapipe and Chromium, since the main job skips every GPU request (
tests/conftest.py:37). - three.js is vendored unminified (task 3). The
three@0.186.1tarball ships no.min.jsbuilds: itsbuild/holdsthree.module.js,three.core.js,three.cjs,three.tsl.jsand the two WebGPU builds. The publishedbuild/three.module.jsandbuild/three.core.jsare copied unchanged (2.1 MB, 417 KB gzipped), so every vendored byte is under the registry's integrity hash, andthree.module.jsalready imports./three.core.js, so there is no import to fix (src/manifoldx/web/vendor/three/SOURCE:15). Minifying them here would add a tool to the upgrade and bytes no published hash covers. - Eight vendored files, not seven (task 3).
GLTFLoader.jsimports../utils/SkeletonUtils.js(src/manifoldx/web/vendor/three/addons/loaders/GLTFLoader.js:69), soaddons/utils/SkeletonUtils.jsis vendored too and the wheel lists eight files underweb/vendor/three; task 8 copies the whole folder. - PointerLock reaches the engine through a field (task 4). The lock is the capture hook
loadApptakes, so it exists before the engine whoseinput.lockLost()it calls:lock.inputstartsnulland browser.js sets it toapp.engine.inputafterloadApp(src/manifoldx/web/js/input.js:191). - The user activation is the navigator's (task 4). Browsers keep it at
navigator.userActivation, not on the document, soPointerLockreadsdoc.userActivation(the tests' fake) and falls back todoc.defaultView.navigator.userActivation; with neither it requests the lock at once (src/manifoldx/web/js/input.js:210-211). - FrameBuilder holds the device pixel ratio and the last pointer type (task 4). Pixel wheel deltas divide by it, so the builder takes
{devicePixelRatio}andattachDomrefreshes it at each wheel event;PointerLockrefuses after a touch by readingbuilder.lastPointerType(src/manifoldx/web/js/input.js:31-33). - buildScene switches the shadow map on (task 5). The scene's extras say whether there are shadows, so
buildScenesetsrenderer.shadowMap.enabledwhen they are on (src/manifoldx/web/js/scene.js:100); browser.js still sets the type, the colour space and the tone mapping. Every glTF material other than StandardMaterial getsfog: false, FlatMaterial's unlit one included (src/manifoldx/web/js/scene.js:40). - Node resolves the vendored
threewith a loader hook (task 5). The vendored GLTFLoader imports the bare"three", sotests/web/js/scene.test.mjs:21registers a resolve hook mapping"three"and"three/addons/"to the vendor folder, as the page's importmap will (module.register, Node 20.6+). The glb parses in Node, so the fallback to task 9 was not taken. web_walk has no fog, sun, shadows or environment, so those paths are tested on a lit scene built from three.js objects in the test, and the environment through its pureequirectTexturestep; the PMREM step and the GLSL of the basic material compile only in a browser (tasks 9 and 10). - Offsets of the other anchors, and an unsized root panel (task 6). The desktop applies the offset only from the top-left (
src/manifoldx/render/passes/gui.py:398), so the page defines the rest: an offset is measured inward from the anchored edges, and on a centred axis it moves right or down (src/manifoldx/web/js/gui.js:57-69). A root panel with no width or height sizes to its content, as the task says; the desktop gives it the whole viewport as its slot and paints its background over all of it, a difference only an unsized panel with a visible bg shows. - Leaves paint no background and do not shrink (task 6). As the desktop's painter, a Text or ValueDisplay draws only its text (
src/manifoldx/gui/painter.py:165-215); every child without flex keeps its size on the main axis (flex-shrink: 0,src/manifoldx/web/js/gui.js:38), and a sized panel clips the overflow, as the desktop layout gives intrinsic sizes and never shrinks them. - frameDt lives in progress.js (task 8). browser.js imports three.js by its bare name, which Node cannot resolve without the test's loader hook, so the frame clock sits beside the progress line, in a module with no imports, and
tests/web/js/progress.test.mjstests both (src/manifoldx/web/js/progress.js:54). - The page clears the engine's log every frame, and an error stops the ticks (task 8). The log only records one frame for the trace, so browser.js empties it before each frame instead of letting it grow for the page's life;
tickpasses 0 as traceEntry's start (src/manifoldx/web/js/browser.js:139). After the app's code throws, the loop stops and__mx.tickreturns null without running anything (src/manifoldx/web/js/browser.js:136). A load error, WebGL2 missing included, hides the progress element, shows the message (with the HTTP hint unless WebGL2 is the cause) and rejects__mx.ready(src/manifoldx/web/js/browser.js:190). browser.js creates the WebGL2 context itself, which is its WebGL2 check, and hands it to the renderer (src/manifoldx/web/js/browser.js:91). - A click while the pointer is locked (task 8, a fix to task 4). In Chromium,
setPointerCapturethrows InvalidStateError while the pointer is locked; attachDom called it before the builder heard of the click, so every click under the lock was lost and web_walk could not pick. The builder now hears the click first and the capture is skipped under a lock (src/manifoldx/web/js/input.js:159), with a test intests/web/js/input.test.mjs. The smoke run found it. - For task 9: headless Chromium grants the real pointer lock, but its synthetic motion under the lock nets zero (found in task 8's smoke run, Playwright 1.63, Chromium 1248, headless). A click on the canvas gets
document.pointerLockElementat once. Under the lock, eachpage.mouse.move(x, y)arrives as two pointermove events in the same frame, movement (+x, +y) and then (-x, -y), and engaging the lock adds one unpaired event with movement minus the click's position. Mouse look through Playwright's mouse therefore does not move the view, and the lock's first frame jumps it. Task 9 should either use Q2's fake lock even though the real one is granted, or dispatch its own pointermove events with the movement it wants. - The lock probe also moves the mouse, and the fake lock is what runs (task 9). A granted lock is not enough: the probe counts the lock as working only when a 10 px move under it nets 10 px (
tests/web/browser/conftest.py:165). Headless Chromium (Playwright 1.63) printsgranted=True, a 10 px move under it nets 0, so every page gets Q2's fake lock (tests/web/browser/conftest.py:33), and the replay test asserts each recorded request came with an active user activation. - The tests stop the page's loop before its first frame (task 9). The loop starts as
__mx.readyresolves, so amanual(true)sent after it lands one or two animation frames late, and those frames run the app (the raises app threw on its fifth tick). An init script setsmanual(true)in the same microtask turn asreadyresolves (tests/web/browser/conftest.py:55); the page's code is unchanged. - Chromium is one per test module, not per session (task 9). While Playwright's sync API is open it leaves its asyncio loop running in the test thread, and an engine adopts a running loop for its async startup handlers, so with a session-scoped browser
test_an_async_startup_handler_runs_before_the_snapshotfailed after the browser tests. Thechromiumfixture closes at the end of each module, and the lock probe runs once a session (tests/web/browser/conftest.py:115). - The key-case break fails the frame check, not
compare(task 9). The Python side replays the frames the page built, and bothsetFrameand Python's ScriptInput lowercase a key name again, so a FrameBuilder that keeps the case changes no trace. The script presses Shift+W (the DOM's key is "W") and the check asserts that frame'sjustis["w"]; the break fails there (tests/web/browser/test_page.py:231). For the same reason no FrameBuilder defect can show incompare; the frame assertions are its check. - The material check reads the glTF nodes, not the page's map (task 9).
materialOfreturns whatsetMaterialrecorded, which a swap of__mx.scene.entitiesleaves right. The check also finds the meshes under the node whose extras name the entity and asserts they draw the logged material (tests/web/browser/test_page.py:182). The swap pairs the blue crate, the script's last pick, with the ground. - The replay traces
rig.pitchtoo, and playwright is locked at 1.63.0 (task 9). The script aims each pick from the traced yaw and pitch (tests/web/browser/test_page.py:17).pyproject.tomlsaysplaywright>=1.55anduv.lockholds 1.63.0, the version whose Chromium this host has cached; CI'splaywright installfetches the Chromium the lock asks for. - The sky's factor is 1.45, measured (task 10). On lit_yard at 320×200 the desktop's mean colour is (131.7, 141.3, 157.9). 1.5 passes, worst channel 1.1%; a sweep from 1.30 to 1.70 in steps of 0.05 puts the smallest worst channel at 1.45, 0.3%, so CALIBRATION.environment is 1.45, with the numbers beside it (
src/manifoldx/web/js/scene.js:13). The sun stays 1.0. Each step of 0.05 moves the means by about 0.5%. - The threshold is 2.3%, not 8% (task 10). Uncalibrated (1.0), lit_yard is 4.0, 5.5 and 7.3% darker per channel, within 8%, so by the task's rule the threshold is the worst passing case plus 2 points: 0.3% + 2 = 2.3% (
tests/web/browser/test_visual.py:18). The 4.0 floor in 0–255 is then the bound for these scenes, about 3%. At 8%, raising the basic material's ambient term from 0.3 to 0.4 (4.6% brighter) also passed. - The basic-material break builds MeshStandardMaterial in the page (task 10). The test imports three by its bare name inside the page, which the importmap resolves, and puts a
MeshStandardMaterialwith the same colour and roughness 1 on every mesh that draws the mx basic material (tests/web/browser/test_visual.py:105): web_walk falls to (44.4, 44.4, 61.8) against (115.9, 124.8, 131.6). - An annotation the model cannot read gives way to the live type (manifoldx#142, a fix before the PR). Plan 1 says an annotation wins over a live type; a field annotated with what types as unknown (a bare
tuple) now takes the type of what setup left in it (src/manifoldx/web/types.py:620), and an attribute read whose receiver is still of unknown type fails the export, naming what to annotate (src/manifoldx/web/transpile.py:829), instead of leaving the field out of the snapshot.
Self-review
- Spec coverage, slice 3: three.js rendering (tasks 3, 5, 8), scene extras and calibration (5, 10), handles to glTF nodes and materials (5, 9), HTML GUI (6), browser input and pointer lock (1, 4, 9), progress bar (8), errors with Python lines (7, 8, 9), the export folder of section 07 (8), visual parity of section 11 (10), the first consumer's JS deleted (12).
- Names across tasks:
hooks.setMaterial/hooks.capture(2) areMxScene.setMaterial(5) andPointerLock.request(4);input.lockLost()(2) is called byPointerLock(4);traceEntry(2) feeds__mx.trace(8), read in 9;CALIBRATION/setCalibration(5) are used in 10.