Brickheart

Bench plan 09NOV2026

: Written by a human with AI assistance.

Written for a later session. Nothing here has been implemented. Names: the Build page is now bench (app/src/bench.ts, app/render-bench.mjs). The audit still says build.ts / render-build.mjs in places; those mean bench.

1. Goal

Several bench pages (touch, mouse, key, voice, button, API, CLI) share one core. Every page shows the 3D stage; there is no headless mode. A model saved on one page opens on any other, so switching mid-build works.

2. Constraints

  • Voice is a constraint only, not a deliverable. English only. Command sets must be small per mode (NeuDecide: at most about 10 tools, enum arguments, can fire on noise so needs a gate, 43 MB ONNX, model files gated on Hugging Face).
  • Static site on Cloudflare free plan. The app CSP already allows 'wasm-unsafe-eval'.
  • Each page declares whether it is accessibility-friendly. Click-and-drag modes are not.
  • The "stud" unit, LDraw frame and engine frame (y flipped) are both in use today (see 9).

3. Current state (read from bench.ts, 911 lines)

  • start() is about 670 lines of nested closures: data load, ops log and derive(), camera, UI refresh, palette filters and wall layout, actions, collision, picker, input wiring.
  • The Op log (place, move, rot, rotV, del, put) plus a cursor is the truth; everything shown is derived. This is the right core.
  • Row mixes data with DOM (li, labelEl, qtyEl) and THREE (tile). All tiles load before the UI is usable.
  • Actions return nothing and write text with msg(t(...)).
  • Palette selection is by list or arrow keys. No Raycaster anywhere, so placed parts can only be selected via the history list.
  • New parts always land at x=0, z=0 and are moved one stud per keypress.
  • The only persistence is the collision mode in localStorage. A reload loses the build.
  • attach-ui.ts (createPicker) is already a host-interface UI: selected(), active(), commit(), rank(), sceneKey(). Candidates come from jointCandidates and touchCandidates; ranking reorders them clear-first, which is why the first option gets used.
  • parts.ts renderParts draws placed parts with instancing and gives the selected part its own emissive mesh. It has a token to drop stale async renders.
  • The snap code has no tracking of taken connectors (a grep found nothing). BrickAgent's connectivity graph is said to give some; to verify.

4. Decisions

Architecture

  • Three layers: core (no DOM, no THREE: inventory, ops log, derive, commands), session/view (selection, filters, camera, settings), adapters (one per bench page).
  • Commands return structured results (ok, code, params). UI text is derived from the code. Commands have preview and commit as separate steps; many commands need a preview.
  • The scene can hold more than one assembly (a connected collection of parts). Mirror exists as a feature but is out of scope for now.
  • Orientation is one command: yaw, pitch and roll are variants of it, not three buttons.
  • Part IDs (#1234) stay, but are shown only in modes where they help. A selected part is highlighted in the scene (glow or halo, depending on accessibility). Grid cells are only for picking from the palette.

API and CLI (proposed, not yet confirmed by owner)

  • window.brickheart is a typed command object in the page. The CLI is a text bar calling the same object. A local LLM drives the page through browser automation. No server.

Camera

  • Four presets at floor level on the diagonals of the box (palette wall, set-image wall, floor), viewed from the user's seat facing the palette wall: 1 top/front/right (iso), 2 bottom/back/right, 3 top/back/left, 4 bottom/front/left. "Bottom" means floor level, not below the floor.
  • Each is a history entry, equal to part edits: undo and redo step over them. In history and MPD it is a plain comment (CAMERA 1 ... CAMERA 4).
  • The wall view is a preset that some actions trigger. It makes no history entry. Free orbit is not recorded.
  • Playback renders instructions by replaying the log, camera entries included.
  • MPD export keeps history in comments. One STEP per part for now. Smart step combining is a later post-processing feature of the instruction builder.

Palette wall

  • Grid A to Z columns, 1 to 9 rows, laid out from the current filtered list; it reflows when parts run out or filters change. Overflow goes into extra wall layers behind, visible so the user sees the depth, but not reachable for now (cycling layers could come later). Only 3 sets in subjects 1-3 exceed 234 rows (max 259).
  • Count shown on each tile.
  • Tile look comes from one shared function: jitter of plus or minus 15 degrees about X, Y and Z, seeded so a part looks the same across builds (assumed seed: part and colour; confirm); big parts tilted 45 degrees down-slope to fill the cell; small parts scaled down; the selected tile wobbles slowly like a top.
  • Touch: pick from the palette by raycast; the part moves from the wall into the scene and the tile count drops.
  • Command mode: pick with a letter dropdown and a number dropdown.
  • The tile renderer must live outside bench.ts so the details page can use it.

Placing and attaching

  • Default position for a new part: the first item in BrickAgent's candidate list after connectivity and collision checks. The location of the first part of a build is open (see 8).
  • Attach shows a preview (a ghost of the part in the scene) and lets the user cycle through candidates before committing. Other commands preview similarly.
  • Each part tracks which connection points are taken, and taking one can block others (a pin is unavailable if its hole is used). The source is BrickAgent's connectivity graph; verify what it provides.

Settings

  • A Settings link at the bottom right, after the legal disclaimer. Holds smart assemble, canvas size, show/hide toggles, and the shared language and theme (bh-theme) from the site.

Saving

  • One model per set, autosaved after every change. The ops log is the saved format; undo history survives.
  • A my-models page lists models with progress (parts remaining in the palette) and a rendered thumbnail of the built scene without the palette, with the set image.
  • Bulk backup and restore of all models, for browser reinstalls. Single-file LDR/MPD import is parked.

Set image (left wall of the box)

  • Needs no offline support. Local copies only, because the API and CDN may disappear. The Rebrickable CDN sends no CORS headers, so it cannot be fetched into IndexedDB or used as a texture directly.
  • Local copies are in shared/data/rebrickable/images, original filenames kept (e.g. 005-1.jpg).
  • Delivery format is undecided (per-set lazy files or a pack). Not needed for testing; the owner will handle the images.
  • Sets with no image (10 OMR sets returned 404, all 6xxx-1) need a no-image state.

OMR

  • Bundled as a pack per subject with a download button, like the DAT and collision packs. Matched to sets by set number only, using shared/data/rebrickable/rebrickable.db. The owner already normalised the data (no minifigs, 78 modern colours, mold variants merged, prints plain).
  • Uses: a dry run of saved sets; the set details page could render the completed OMR model instead of the set image; "explore/deconstruct the set" is a third idea (noted only).

Accessibility

  • Every bench mode declares whether it is accessible. Click-and-drag modes are flagged as not accessible.

Out of scope here

  • Details page (separate plan; depends on the set image and the parts pack), free orbit, import, mirror, navigating wall layers, voice implementation.

5. Data facts

  • Database: /home/chinapal/brickheart-web/shared/data/rebrickable/rebrickable.db. Sets in subjects 1-3: 3,377 with an image; rows per set (distinct part and colour): median 27, 23, 28; p90 87, 79, 103; max 245, 259, 232.
  • OMR file: /home/chinapal/brickheart/omr/sets_lego_omr_full.jsonl, 208 MB, 1,373 sets; 628 are in subjects 1-3 (477, 90, 61). Gzipped text: about 3.0, 0.2 and 0.4 MiB per subject. Sets with STEP lines: 348, 26, 55. Sets with submodels: 453, 90, 61.
  • Existing packs (app/data): LDraw 9.0, 4.4, 5.0 MB; collision 24, 11, 12 MB (subjects 1, 2, 3).
  • Images: 618 of 628 downloaded; averages about 176 KB originals (many 2134x1600 or 2880x2160). Test downscales to longest side 1024: avg 50 KB (166 MiB projected for 3,377); 1280: 63 KB (206 MiB); 1600: 78 KB (258 MiB).
  • Tests today: npm test -w app passes (snap tests). There are no browser tests and no Playwright.

6. Known problems in bench.ts to fix on the way

  • exempt is dead: the put op carries a boolean, derive never copies it into Placed, the collision worker expects the id of the part to exempt, so seated joints can be flagged as collisions.
  • rotV is not counted in turns and not shown in history; a put part starts at turns = 0 even if rotated.
  • The y/z sign flip between LDraw and engine frames is written four times (derive, poseOf, picker selected, exportMpd).
  • Undo and redo are bare z and y; Ctrl+Z is ignored.
  • Buttons use aria-disabled but still fire; an unknown data-act falls into moveSel silently.
  • onSceneChange is a late-assigned mutable hook.
  • ROWS_SQL sits in bench.ts instead of the tested query.ts.
  • t() and el() are duplicated with main.ts.

7. Proposed order (for owner to confirm)

  1. Safety net. There are no bench tests. Decide how to check each step (e.g. unit tests for derive and commands; a browser test tool would also serve the API).
  2. Behaviour-preserving split of bench.ts: core (rows as data, ops, derive), view, adapters. Fix the section 6 issues.
  3. Command layer with preview and commit, structured results, camera entries in the log.
  4. Autosave, my-models page, bulk backup.
  5. Palette wall: grid, counts, tile rule, overflow layers, raycast picking.
  6. Camera presets and playback.
  7. Attach preview, connectivity tracking, default placement.
  8. Settings page.
  9. One new bench page at a time on the shared core.
  10. OMR pack and the details-page plan.

8. Open questions

  • Where does the first part of a build go?
  • What does the bulk backup contain: models only, or also settings (language, theme, collision mode)?
  • Does Browse show a "solved" badge before the OMR pack is installed? That needs a small list of solved set numbers shipped with the database.
  • Confirm the seed for tile jitter (part and colour).
  • Confirm the API and CLI approach (window.brickheart plus browser automation).
  • Storage mechanism for saved models.
  • How the history list shows camera entries (it is keyed by part id today).
  • Verify what BrickAgent's connectivity graph already tracks, and how candidate ordering and collision checks combine.

9. Not verified

  • Behaviour of the live app beyond reading the source; nothing was run in a browser.
  • Whether the audit's other to-dos (shared worker client and store base, checkJs, data README, Python pipeline) belong here; they overlap only where the OMR pack needs a third store.

Addendum A: corrections and working agreement

How to work with the owner

  • Ask questions and don't assume. The owner corrected assumptions repeatedly (camera box, OMR, headless, import).
  • Gather data with terminal commands (Ubuntu, VS Code, repo at /home/chinapal/brickheart-web). Write no code until told. Short answers, one step at a time.

Mistakes made in the planning session (don't repeat)

  • Assumed API/CLI could be headless. Wrong: every user needs visual feedback.
  • Said the bottom cameras look at the floor's underside. Wrong: they are at floor level.
  • Said the CSP blocks WASM. Wrong: app/build.mjs already adds 'wasm-unsafe-eval'.
  • Estimated images at 36 KB each (one small file). Real average is about 176 KB.
  • Ran an OMR-vs-inventory comparison that ignored the owner's normalisation. Discard its numbers.

Addendum B: voice

  • English only. Voice is a constraint on the core, not a deliverable.
  • NeuDecide returns a tool call from audio plus tool schemas, with no transcript. The voice page must therefore show the interpreted command on screen and use the preview/commit contract before anything changes.
  • Keep tool lists to about 10 per context. Swap lists by mode (pick part, attach/orient, history/camera, system). Use enum arguments.
  • It can fire on noise: use push-to-talk or voice-activity detection, plus an explicit "no action" tool.
  • Treasure-map picking by voice is untested. Spoken letters are easily confused (B/D/E/P/T). Test before relying on A to Z, and keep a fallback of naming the part and colour.
  • Microphone access may be blocked by headers. Check for a Permissions-Policy in shared/assets/_headers.
  • A browser port needs onnxruntime-web, audio resampling to 16 kHz, a tokenizer and a decode loop (only a Python package exists). The 43 MB model would be an on-demand download like the packs. Its files are gated on Hugging Face, so hosting needs checking.

Addendum C: threads from the original audit that the plan missed

  • The audit's "Layouts workpack" is this work: separate bench layouts for touch, keyboard, voice, API and command line. The conversation added mouse and button. The final list of variants is unconfirmed.
  • Shared head() for the app renderers is still open. Do it before adding many bench renderers, which would multiply the duplication.
  • i18n: bench strings with counts need Intl.PluralRules; every new string must go through the hash/todo translation workflow, and each page is built per language.
  • Service worker and offline: new pages are only available offline once visited. The audit's gap (/zh/build/ fails offline) applies to every new page.
  • Settings: the audit says no app settings page exists. bh-theme is a cookie scoped to .brickheart.org plus localStorage. The planned settings link must decide what is shared with the site.
  • Data pipeline: the Python scripts are not in the repo (hardcoded /home/chinapal paths, no record of how app/data is copied from shared/data). OMR packs and images need a producer script, and the audit plans a TypeScript port.
  • The shared worker client and IndexedDB store base: the OMR pack would be a third near-copy of the stores.
  • Collision parity gap (84 of 6,000 cases outside tolerance): default placement and ranking depend on collision, so define behaviour when the pack is absent or a result is uncertain.

Addendum D: critique and risks

  • Saved models are fragile. Ops store row, an index into the SQL result order, and instance ids come from the set number plus that order. Rebuilding the database (the pipeline port is planned) would silently change them. Save part, colour and instance number instead, with a format version.
  • Wall addresses reflow. "C4" can mean a different part a moment later. For API and voice, address by part and colour or id, and show what C4 is in the preview before committing.
  • Variant pages multiply cost. app/build.mjs bundles each entry separately (outfile, no splitting), so seven benches could mean seven copies of three.js. Pages can stay separate while sharing code (esbuild splitting, or one bundle with a variant switch). Measure first.
  • Startup is slow (every tile loads first), and a mid-build switch is a full page load. Restore the saved model before first render and load tiles lazily.
  • The render loop never stops. With wobble, 234 tiles and extra layers, expect battery cost on touch. Consider rendering on demand.
  • A 26 by 9 wall on a phone has small touch targets. Make filtering the first step on touch.
  • Two tabs on the same set will overwrite each other's autosave. IndexedDB can also be evicted, which is why backup matters.
  • OMR models may contain minifigs, old colours, mold variants and prints that the normalised database removed. How OMR lines map onto it, and what "solved" means when they don't, is unresolved. The mapping lives in the Python pipeline.
  • Keep the page's existing accessibility (live regions, listboxes, aria-hidden canvas) in the key and button pages.

Addendum E: ideas to consider

  • One command registry feeding button labels, keyboard help, CLI help, API schemas, NeuDecide tool JSON, i18n keys, the accessibility flag and the preview/commit contract.
  • Derive connectivity from poses instead of recording it at attach time. graph.ts already has connectionsFor ("edges between one part and the rest, for placement"), exported only for tests. The same edges give taken and blocked connectors and the pairs allowed to overlap, which would replace the dead exempt flag. Verify against the code first.
  • Use OMR as test fixtures: replay a model through the commands, compare the result, and use its STEPs as ground truth for build order. The same models could benchmark an LLM through the API ("build this set") or serve as a ghost guide.
  • One box renderer also produces instruction pages, thumbnails and the palette image, and could run offscreen in CI.
  • Instruction builder inputs already exist in the plan: per-step parts (palette counts), camera entries, steps.
  • Write MPD history comments in a parseable form (CAMERA 1, plus command text) so import stays possible later at no cost.
  • Saved command logs could double as CLI scripts.

Addendum F: new open questions

  1. What is "smart assemble" in settings? (Step combining? Auto-placement?)
  2. Which bench page comes first to prove the core, and what is the final variant list?
  3. Is it OK to key saved parts by part, colour and instance number, with a format version?
  4. How do OMR lines map onto the normalised inventory, and what happens to lines that don't map?
  5. Should wall addresses stay stable per set (filters dim cells) or reflow? Reflow was chosen, but this is the API/voice risk above.
  6. Should MPD comments carry parseable command text?
  7. What should happen when the same set is open in two tabs?

Addendum G: findings from the header, bundle and graph checks

Headers and voice

  • shared/assets/_headers has no Permissions-Policy, so nothing in the repo blocks the microphone. Dashboard rules are unverified.
  • connect-src and worker-src fall back to 'self'. Voice model files must be same-origin. Whether the ONNX web runtime needs blob: workers is unchecked.
  • img-src allows data: but not blob:. Store my-models thumbnails as data URLs, or extend the CSP.

Bundles

  • dist/js/bench.js is 1,347,421 bytes, unminified (no minify in the esbuild call); sourcemaps are 3.3 MiB; sql-wasm is 685 KB.
  • Seven full bench bundles would be about 9.4 MB. Unverified: whether sw.js precaches every JS file, and whether .map files are included.

Connectivity (app/src/snap/graph.ts)

  • connectionsFor(parts, index, cat) returns edges between one part and the rest. buildGraph returns edges plus components (connected groups) but is not exported.
  • Edges name the connector on each side, so taken connectors and assemblies can be derived from poses instead of tracked at attach time.
  • Connectivity is geometric (touching), not authored. No blocking rule (pin vs hole) has been seen. Cost on large builds is unmeasured.
  • jointCandidates gets only the selected target part, so occupied connectors are caught only by collision ranking, which needs the collision pack.
  • Correction: attach ranking uses seatedOverlap(c) per candidate and works. The dead flag is Placed.exempt (never set from the put op's to/exempt).

Open

  • Does "taken" mean touching, or what the user attached?
  • Should every variant's JS be precached, or only the one in use?
  • Any Cloudflare dashboard header rules?

Addendum H: precache, minify, connectivity

Offline and precache (app/build.mjs)

  • The precache walk includes everything in dist except sw.js, _headers, _redirects, *.map, data/ldraw/ and data/collide/. Every variant's JS and HTML, per language, would be precached unless excluded.
  • Decision: only the variant the user has used is available offline. Variants are not precached. sw.js already stores visited same-origin responses.
  • New directories (OMR packs, set images) must be added to the exclusion list.

Bundles

  • esbuild: sourcemap on, minify off, no splitting. bench.js is 1,347,421 bytes. Measure the effect of minify (and of splitting shared code) before deciding.
  • Sourcemaps are deployed publicly (not precached).

Connectivity and taken connectors

  • graph.ts edges name connector pairs, so taken connectors can be derived from the scene. judge() has the mate rules but no blocking rule (pin blocks when its hole is used). Source of that rule is unknown (BrickAgent Python?).
  • jointCandidates considers only the target part, so occupied connectors are not excluded. It also stops at LIMIT candidates, which affects cycling in the preview. Value unchecked.

Header rules

  • Live headers must be compared with shared/assets/_headers to find dashboard rules.

Addendum I: minify, headers, candidate cap

  • Production build: minify on (measured: bench.js 1,347,433 -> 641,654 bytes raw, 255,734 -> 167,739 gzip). Sourcemaps generated for local dev only; not deployed (.map files are already excluded from precache).
  • Correction to Addendum D: bundle size is a minor cost. Users download one variant (about 170 KB gzip minified). Shared-code splitting helps mid-build switching only.
  • Live response headers match shared/assets/_headers plus the app's wasm-unsafe-eval; no Permissions-Policy, so the microphone is not blocked by the site's headers. A single / 404 response cannot rule out path-specific dashboard rules.
  • relate.ts: LIMIT = 400 candidates, 4 yaws, TOL = 8 LDU. The cap truncates in connector order before ranking, so the best candidate may never be ranked on large targets (unmeasured). Preview cycling over 400 items is likely too many; decide how many to expose.
  • BrickAgent Python: /home/chinapal/bricknet/src/brickagent (also www/brickagent, test-data/brickagent, ~/Downloads/BrickAgent-master). Which is canonical is unconfirmed.

Addendum J: BrickAgent source

  • Canonical: /home/chinapal/bricknet/src/brickagent (modules: catalog, check, export, joints, model, physics, pose, reflection, search, view; data in _data/v1: bounds, colors, ids, keywords, mirrors, seating).
  • A keyword grep (occupied/taken/blocked/busy/engaged/consumed/in use/already) found no taken-connector or blocking rule. Files were not read. The pin-vs-hole blocking rule probably has to be designed, not ported.
  • Not in the TS port's file list: physics, check, reflection, search, view, export. Contents unread. reflection.py and mirrors.json.xz relate to the parked mirror feature.
  • Preview cycling count: deferred to implementation.

Addendum K: written instructions and monochrome patterns

Decided by the owner

  • Written instructions are a byproduct of normal app use: the build history yields a draft that a person can refine for a blind builder to assemble physically.
  • Instructions follow the templates of about 500 Bricks for the Blind sets.
  • A monochrome mode uses patterns in place of colour. The 12 colours are the base_color families in the database.
  • Blind and low-vision users are therefore in scope, at least as readers of instructions. The app itself still requires visual feedback for every user (earlier decision).

What the history records today (bench.ts, relate.ts)

  • A put op stores id, row, pose, target id (to), joined, exempt. It does not store the relation chosen (above, below, beside) or the connector pair that mated. Both exist on the Candidate at commit time and are discarded.
  • relate.ts classify() can recompute a relation from two world boxes, but recording it at commit is cheaper and more reliable.
  • move, rot and rotV ops are user adjustments and undone ops sit past the cursor. A generator must drop undone ops and collapse adjustments into one line per part. This is the same post-processing step as the planned smart step combining; plan them as one feature.
  • Camera entries (CAMERA 1 to 4) are comments in the log; the generator can use them to choose viewpoint wording.
  • Part names in the database are English only (audit). Instructions in other languages need translated part names, or English names inside translated sentences. Decision needed.

Unverified (nothing seen yet)

  • The Bricks for the Blind templates: their location, structure (parts list per step? stud counting? orientation phrasing?) and overlap with the 628 OMR sets. Do not design the generator until two or three examples have been read.
  • The distribution of the 12 base_color families in subjects 1-3, and whether transparent and metallic finishes fall under them (a query was proposed but not run).
  • Whether the normalised parts (mold variants merged, some prints made plain, 78 modern colours) can be found by a physical builder, or whether substitutes are acceptable.

Monochrome patterns (design notes, untested)

  • LDraw geometry has no UV coordinates (to verify in geometry.ts). A pattern needs a shader using world or part-space coordinates. renderParts groups instances by part and colour, so a shared material per colour is the natural place.
  • Twelve patterns may be hard to tell apart on small, angled parts with edge lines. Test with real users; a smaller pattern set plus a text label may be needed.
  • Text remains the primary channel. Palette labels already carry the family name (e.g. red.4 plate 1x2). Pattern is a second channel for low vision and greyscale printing.
  • Open: on screen, in print, or both. Print needs patterns that survive greyscale and small sizes.

Open questions

  1. Is the physical builder expected to find the exact part and colour in their own set, or are substitutes acceptable?
  2. Which language(s) should the generated instructions support at first?
  3. Is the generated draft reviewed and edited by a person before a blind builder uses it? (The owner called it a draft.)
  4. Where are the 500 template sets, and which are in the OMR collection?
  5. Do the 12 families cover transparent and metallic finishes?
  6. Monochrome mode: screen, print, or both?

Suggested checks before work starts

  • Read two or three Bricks for the Blind instruction examples.

  • Run the base_color query below.

  • Check geometry.ts for UVs.

    python3 - <<'EOF' import sqlite3 c = sqlite3.connect('/home/chinapal/brickheart-web/shared/data/rebrickable/rebrickable.db') q = '''SELECT c.base_color, COUNT(DISTINCT c.id), SUM(ip.quantity) FROM inventory_parts ip JOIN inventories i ON i.id = ip.inventory_id JOIN sets s ON s.set_num = i.set_num JOIN colors c ON c.id = ip.color_id WHERE s.subject_id IN (1,2,3) AND ip.is_spare = 0 GROUP BY c.base_color ORDER BY 3 DESC''' for r in c.execute(q): print(r) EOF grep -n "uv|UV" /home/chinapal/brickheart-web/app/src/ldraw/geometry.ts | head