by adom
The hero-image lab with a human gate: `hero-studio pose <owner/slug>` opens the studio in front of the human, posed for their package, and blocks until they click Generate, producing the provenance-stamped 2000x1250 PNG the registry's hero gate requires. The image carries the title and artwork; the exported image also bakes the type pill (top right) and full wiki slug (bottom right); the page shows the hero bare, and only the homepage marquee overlays its own dynamic info. Every hero wears its P
Compose through the renderer ladder (pup on boxes with no local Chrome); the surface posts its lint again #5
compose-pup-ladder → masterhero-studio 0.25.2 · adom-wiki 1.8.31 · Node v18.19.1 · aarch64 container with no local Chrome (Hydrogen workspace on a MacBook Air, macOS host), rendering through pup
@kyle: this hits Hydrogen Mac workspaces (aarch64, no local Chrome, every render goes through pup on the Mac), so please try it on a Mac before it ships.
Problem
On a container with no local Chrome, an attested re-generate is impossible:
POST /generatewithattestrefuses wheneverlintMeta.poseRev !== poseRev:{"ok":false,"errorCode":"HUMAN_GATE","error":"state.lint is stale: the pose changed after it was measured (or it was never measured)","hint":"GET /compose.png (hero-studio compose) re-measures lint server-side against the exact current pose, then retry"}The hint's way out does not work there.
/compose.pngonly spawnsrender-hero.mjs, the local Chrome leg, so it fails and never tries the pup leg that Generate uses:{"ok":false,"error":"Error: Chrome not found. Set CHROME to a Chrome/Chromium binary path, or: npx -y playwright install chromium && sudo npx -y playwright install-deps chromium # Linux ARM64: Chrome for Testing has no ARM64 build, Playwright ships one under ~/.cache/ms-playwright"}Even a pup render measures nothing:
render-pup.mjsprints noLINT_JSON, unlikerender-hero.mjs.The open studio surface does not refresh lint either. In
public/js/app.js,runLint()computes the findings and returns them, and nothing sends them. Sostate.linton such a box is never measured, and the gate's "Layout lint" box reads "No layout findings." for a pose nobody measured.state.fitPendingalso stays set whenever the surface answers a fit without moving the title, because it clears only on afontSizepost.
Workaround used today (Drew, drew715): in the studio's own pup render session, navigate to ?render=1, evaluate window.__computeLint(), and POST /state with just {aiThread, lint}. That stamps the findings at the current poseRev with source: 'surface'. The attested /generate then worked, and the pup leg produced a 2000x1250 hero.
Repro (a pup-only container)
- A container with no local Chrome (or no puppeteer-core), where
hero-studio doctorsays "renderer ready via pup fallback". - Pose a page, let the human Generate once, then change anything (
hero-studio set headline=...). POST /generate {"attest": {...}}gives the HUMAN_GATE refusal above.hero-studio composegives the Chrome-not-found error above, so there is no way back to an attested Generate.
Was dropping the surface's lint POST deliberate?
I checked the history before restoring it. It reads as an accidental casualty of the #51 refactor, not a decision:
- In 0.20.3,
runLint()ended withrenderLintBox(items)and a dedupedsend({ lint }). - 0.20.4 (the #51 fix) split
computeLint()out ofrunLint(). The send and therenderLintBoxcall did not survive the split:lastLintKeyis still declared and never used, andrenderLintBox()is still defined and never called. - The same release added the server branch that stamps surface posts,
lintMeta = {..., source: 'surface'}, and the #51 closing comment says "lint posts stamp the rev they measured", withsource: surface|compose. - SKILL.md still documents it: "Findings render in the gate and publish to
state.lint", "state.lint is computed by the OPEN studio page OR by a headless compose (whichever ran last)", "lintMeta.stale exposes a surface that stopped re-rendering".
What #51 did decide, and this PR keeps, is that the automated Generate refuses stale lint and that a lint post must not be stamped fresh for a pose that has moved on. So the surface post comes back with that guarantee built in (below). If it was dropped on purpose for a reason not written down, the app.js hunk and the lintPoseRev handling stand alone and can be dropped from this PR without touching the compose fix. I left renderLintBox() alone: the wizard's Layout lint box already renders state.lint.
Changes
server.js
- One renderer ladder for Generate and compose:
renderLadder(pinned)builds the legs (local headless Chrome first, skipped when it is known to be missing its pieces, then the host browser via pup), andrenderThroughLadder()walks them and returns{via, lint}from the leg that rendered./generatenow uses both, with no change in behaviour, and a leg that times out says "timed out after N s" instead of "render exited null". /compose.pngwalks that ladder. It takes?renderer=local|pup(the same pin asPOST /generate {renderer};HERO_RENDERERpins both), answers RENDERER_NOT_READY like Generate when nothing can render, and returnsX-Hero-Renderer: local|pup. It stores the lint that leg measured withlintMeta = {computedAt, poseRev, source: 'compose', renderer}. TheposeRevis the one the render started from, so a pose change during a slow pup render leaves the findings stale. A failure returns 500 JSON{ok:false, error, hint}with every leg's reason.- Compose and Generate never run at once: they share the pup leg's host render window (
hero-render). A second compose answers 503, and a Generate during a compose answers "a compose is running". - The stale-lint refusal hint names what works on this box. On a pup-only container it reads: "Run hero-studio compose (GET /compose.png). This box has no local renderer (...), so compose renders through the host browser via pup, the same leg Generate uses, and re-measures lint there. That can take a minute or two. An open studio surface also re-measures lint on its own about half a second after each change. Check that state.lintMeta.stale is false, then retry." The never-measured
lintMeta.reasonnow says the same. poseRevrides GET/stateand every SSE state push, so the surface knows which revision it rendered.POST /state:lint,lintPoseRev,fitAckand the caller'saiThreadare not pose, so they no longer bumpposeRev. Every POST carriesaiThread, so before this every lint post bumped the revision. Lint carrying alintPoseRevother than the current one is dropped, and the reply says so inlintDropped. A lint post without one (the workaround's{aiThread, lint}shape) is stamped at the current revision as before.fitAckclearsfitPending.lintPoseRevandfitAckare not merged into state.- A separate bug fixed along the way: the full-import passthrough (#36.1) never worked.
finalize()readsrenderLint, which was declared withletafter the passthrough block, so the passthrough threw inside its owntryand always fell back to re-rendering the import. The studio log shows:passthrough write failed (Cannot access 'renderLint' before initialization); falling back to the render ladder. The declaration moved above the passthrough.
render-pup.mjs: after measuring #hero, it evaluates window.__computeLint() in the render view and prints LINT_JSON [...] (or LINT_JSON_ERR <why>), as render-hero.mjs does. The JSON comes back hex-encoded between sentinels (HSLINT@...@TNILSH), so no quoting or slash escaping by the CLI can corrupt it. The lint also rides the provenance stamp of pup-rendered heroes as source: render.
public/js/app.js
runLint()posts{lint, lintPoseRev: state.poseRev}again. The post is deduped on (revision, findings), so it re-posts identical findings for a new revision, which keeps them fresh. It is held while a typed headline or subtitle is still unsaved, since that render shows a pose the server does not have yet. The render view still never posts, becausepost()is a no-op there.- Every optimistic send is debounced at 350 ms or less and lint at 450 ms, so a lint measured on a pose the surface itself just changed arrives after that change and is dropped. The echo then triggers a fresh measurement.
runFit()answers every fit request:{fitAck: true}when nothing fits or the size stays,fontSizewhen it moves.
drive.mjs / bin/hero-studio: hero-studio compose [out.png] [--renderer local|pup]. It prints which leg rendered, and on failure it prints the error and the hint. The push also gives bin/hero-studio its executable bit (mode 644 to 755); the manifest already mandates that, and clones set it anyway.
SKILL.md: compose walks the ladder, the ?renderer= pin, lintMeta.renderer, surface posts with poseRev, fit answers, the stamp's lint on the pup leg, and the new test.
Tests
npm run test:compose (new, test/compose-ladder.mjs) needs no Chrome and no desktop. It starts a real server on a spare port with a temporary HOME, a dead local renderer and a dead registry. It puts a stub adom-bridge first on PATH that answers the pup verbs render-pup.mjs uses and runs render-pup's own lint expression against a fake window, so the real bridge is never called. It checks:
- the refusal and its pup hint;
- compose via pup: a 1600x1000 crop,
X-Hero-Renderer: pup, and the findings stored exactly (quotes, a slash, a backslash and non-ASCII, through a CLI that escapes slashes); lintMetafresh, withsource: composeandrenderer: pup;- the attested Generate is no longer refused as stale;
- a pose change during a slow compose leaves the findings stale;
- a second compose answers 503, and a Generate during a compose is refused;
- a failing leg reports its reason and leaves
state.lintalone, and?renderer=localruns only the local leg; - the surface post contract (fresh, no
poseRevbump, outdated posts dropped, the legacy shape still accepted) andfitAck; runLintandrunFitlifted out of app.js with their collaborators stubbed;- the passthrough really passes through.
Results here (aarch64, Node 18, no Chrome):
| Suite | This PR | Unpatched 0.25.2 |
|---|---|---|
test:compose |
42 passed, 0 failed | 12 passed, 30 failed (compose dies with "puppeteer-core not found", the surface never posts, and the passthrough falls back) |
test:syntax |
25 passed | 24 passed |
test:renderer |
15 passed | 15 passed |
test:brand |
51 passed, 2 failed | the same 2 fail |
test:platform |
16 passed, 2 failed | the same 2 fail |
test:traces |
cannot run | cannot run |
test:render |
cannot run | cannot run |
- Skipped here because they need a real Chrome:
test:render(test/render-view.mjs), which now also opens a real interactive surface and checks that it posts its lint at the renderedposeRev, re-measures after a pose change, and then goes quiet;test:traces; and the "renders" cases intest:brandandtest:platform. Those fail with "Chrome not found", identically on unpatched master. - Not tested against a real pup on a Mac. On current bridges the pup leg also needs the #78 fixes, which are in a separate PR (PR 6, https://wiki.adom.inc/adom/hero-studio/prs/6), before compose can render through it end to end. The two branches merge cleanly together, and both new suites pass on the merged tree.
npm testitself stops attest/gate.mjs, which is not in the page repo (nor arepose-surface.mjs,bind-and-tabs.mjsandbatch.mjs), so I ran the suites one by one.test:composeis added to the aggregate as well.
No version bump. That is left for the publish.
🤖 Generated with Claude Code
(edited)
Diff Skip to comments (1)
SKILL.md+34−15@@ -349,9 +349,13 @@ rather than suggesting libraries. Re-run doctor until it passes, then pose. When doctor reports "ready via pup fallback", Generate works today through the host browser; installing the local runtime is an upgrade (sharper output, no-dependence on the desktop app running), not a blocker. To exercise or test a-specific leg: `POST /generate {"renderer":"pup"}` (or `"local"`) pins it for-one request; the `HERO_RENDERER` env on the server pins it globally.+dependence on the desktop app running), not a blocker. `hero-studio compose`+walks the same ladder, so on a box with no local Chrome (an aarch64 Hydrogen+Mac workspace, say) it renders through pup too and still re-measures lint. To+exercise or test a specific leg: `POST /generate {"renderer":"pup"}` (or+`"local"`) pins it for one request, as `GET /compose.png?renderer=pup`+(`hero-studio compose --renderer pup`) does for a compose; the+`HERO_RENDERER` env on the server pins both globally. If `hero-studio showcase|set|state|toast|reroll` dies with MODULE_NOT_FOUND, the install is hero-studio 0.10.0, which shipped without drive.mjs; update the@@ -413,12 +417,18 @@ between the lowest text and the marquee band). Findings render in the gate and publish to `state.lint` ([{id, level: warn|fail, msg}]); the AI should fix warns without being asked. `state.lintMeta` says whether those findings are TRUSTWORTHY (hero-studio#51):-{computedAt, poseRev, source: surface|compose, stale}. stale:true means the-pose changed after the findings were measured (or nothing measured them yet);-never act on stale findings, and never read an empty stale lint as all-clear.-`hero-studio compose` (GET /compose.png) re-measures lint SERVER-SIDE in the-same headless render, fresh by construction, with no dependency on an open-surface; the automated Generate path refuses stale lint outright. Text+{computedAt, poseRev, source: surface|compose, renderer (compose only: local+or pup), stale}. stale:true means the pose changed after the findings were+measured (or nothing measured them yet); never act on stale findings, and+never read an empty stale lint as all-clear. An open surface re-measures+about half a second after each render and posts the findings with the+`poseRev` it rendered (`state.poseRev`); the server drops a measurement the+pose has already moved past rather than stamp it fresh. `hero-studio compose`+(GET /compose.png) re-measures lint in its own render view through Generate's+renderer ladder (local Chrome, else the host browser via pup), stamped with+the pose it loaded, with no dependency on an open surface; the automated+Generate path refuses stale lint outright, and its hint names what can+re-measure on this box. Text geometry is measured from the RENDERED GLYPHS (Range rects), not element boxes, so a long word overflowing its column into the showcase is caught. FULL-HERO IMPORTS are never reported all-clear: the linter discloses that@@ -492,7 +502,7 @@ hero-studio preset bridge-family # apply a family design system in hero-studio showcase --file shot.png [--full] [--cover] [--chrome none|fake|bare] hero-studio bg --file tile.png [--cover] # YOUR brand texture as theme 'image'; composed text + linting still apply hero-studio state # read everything, incl. slotSize + enums-hero-studio compose preview.png # headless compose of the CURRENT pose: verify staging without a browser (no provenance stamp; never publishable)+hero-studio compose preview.png # compose the CURRENT pose through Generate's renderer ladder (local Chrome, else pup) and re-measure lint: verify staging without a browser (no provenance stamp; never publishable); --renderer local|pup pins a leg hero-studio toast "trying the showcase layout" --kind info hero-studio reroll # new procedural circuitry pattern hero-studio instances # every live studio on ports 8846-8866 (port, page, gate open?)@@ -512,7 +522,8 @@ ok:true means the value really landed. state.lint is computed by the OPEN studio page OR by a headless compose (whichever ran last; state.lintMeta.source says which, and .stale says whether the pose has moved since). A surface can be open yet unresponsive: state.fitPending stays set when a /fit request got-no answer, and lintMeta.stale exposes a surface that stopped re-rendering.+no answer (a surface answers every fit, even one that leaves the title where+it is), and lintMeta.stale exposes a surface that stopped re-rendering. When in doubt, `hero-studio compose` is the reliable measurement path. The showcase's FAKE titlebar is auto-off whenever an imported screenshot is@@ -642,9 +653,9 @@ Every generated PNG's provenance comment carries, at the top level: so a consumer reading a published hero can tell which guide, and which revision of it, produced those pixels. It also carries `lint: {source, findings: [{id, level, msg}]}`: the checks measured in the render that became-the hero (`source: render`), or the last measured set when the renderer did-not report them (the pup leg), so a published hero can be audited for what-was flagged when it was made.+the hero (`source: render`; both the local and the pup leg report them), or+the last measured set when the renderer did not, so a published hero can be+audited for what was flagged when it was made. A guide whose display face is a CSS generic family (`system-ui`, `sans-serif`, `ui-sans-serif` and the like) with no font file draws a@@ -673,7 +684,15 @@ reported instead of Node's version footer (hero-studio#57). The render view (`?render=1`) is a read-only consumer of the state it loaded: it never posts state and opens no event stream, so Generate and compose are unaffected by whichever studio tabs are open. It never runs the review tour either: the tour's spotlight on an unticked-title used to bake a teal ring into attested and compose renders.+title used to bake a teal ring into attested and compose renders. With a+Chrome it also opens a real interactive surface and checks that it publishes+its lint with the poseRev it rendered, re-measures after a pose change and+then goes quiet. `npm run test:compose` (node test/compose-ladder.mjs) needs+no Chrome and no desktop: it starts a server whose local leg is dead, puts a+stub `adom-bridge` first on PATH that answers the pup verbs, and checks that+compose renders via pup and stores the lint it measured fresh, that the+attested Generate then passes the stale-lint check, the surface lint and+fitAck contracts, and the full-import passthrough. ## Brand doctrine (what makes a hero look like the family)
bin/hero-studio+3−1@@ -55,7 +55,9 @@ conversation is calling. State-changing verbs refuse without it. hero-studio preset [name] apply a family design system; no name lists them hero-studio state print live state (includes enums + lint) hero-studio changes this review session's ledger (page + pose edits)- hero-studio compose [out.png] headless compose of the current pose (no stamp)+ hero-studio compose [out.png] [--renderer local|pup]+ compose the current pose through Generate's renderer+ ladder and re-measure lint (no stamp) hero-studio toast "text" [--kind info|success|warn] hero-studio reroll re-roll the circuitry theme pattern hero-studio instances list live studios on ports 8846-8866
drive.mjs+14−4@@ -321,9 +321,19 @@ try { // headless compose of the CURRENT pose (#36.2): verify staging without a // browser. Not the gate: no provenance stamp, never publishable. const fsm = await import('fs');+ // compose walks Generate's renderer ladder (local Chrome, else the host+ // browser via pup); --renderer local|pup pins one leg.+ const ri = args.indexOf('--renderer');+ const pin = ri >= 0 ? args.splice(ri, 2)[1] : ''; const outFile = path.resolve(args.find((a) => !a.startsWith('--')) || 'compose.png');- const r = await fetch(BASE + 'compose.png');- if (!r.ok) die('ERROR: compose render failed (' + r.status + '): ' + (await r.text()).slice(0, 300));+ const r = await fetch(BASE + 'compose.png' + (pin ? '?renderer=' + encodeURIComponent(pin) : ''));+ if (!r.ok) {+ const text = await r.text();+ let e = null;+ try { e = JSON.parse(text); } catch {}+ die('ERROR: compose render failed (' + r.status + '): ' + (e && e.error ? e.error + (e.hint ? '\n hint: ' + e.hint : '') : text.slice(0, 300)));+ }+ const renderer = r.headers.get('x-hero-renderer') || null; const buf = Buffer.from(await r.arrayBuffer()); fsm.writeFileSync(outFile, buf); // hero-studio#51: compose measures lint server-side in the same render;@@ -334,8 +344,8 @@ try { lint = st.lint || []; lintMeta = st.lintMeta || null; } catch {}- console.log(JSON.stringify({ ok: true, file: outFile, bytes: buf.length, lint, lintMeta }));- console.error('composed preview written (no provenance stamp; the pose gate + Generate remain the only publish path)');+ console.log(JSON.stringify({ ok: true, file: outFile, bytes: buf.length, renderer, lint, lintMeta }));+ console.error('composed preview written via ' + (renderer || 'the render ladder') + ' (no provenance stamp; the pose gate + Generate remain the only publish path)'); if (lint) { for (const l of lint) console.error('lint ' + l.level + ' [' + l.id + '] ' + l.msg); if (lintMeta && !lintMeta.stale) console.error('lint measured fresh by this compose (poseRev ' + lintMeta.poseRev + ')');
package.json+2−1@@ -67,8 +67,9 @@ "test:brand": "node test/brand.mjs", "test:render": "node test/render-view.mjs", "test:renderer": "node test/renderer.mjs",+ "test:compose": "node test/compose-ladder.mjs", "test:syntax": "node test/syntax.mjs",- "test": "node test/syntax.mjs && node test/gate.mjs && node test/brand.mjs && node test/render-view.mjs && node test/renderer.mjs && node test/platform.mjs && node test/pose-surface.mjs && node test/bind-and-tabs.mjs && node test/batch.mjs && node test/circuit-traces.mjs",+ "test": "node test/syntax.mjs && node test/gate.mjs && node test/brand.mjs && node test/render-view.mjs && node test/renderer.mjs && node test/compose-ladder.mjs && node test/platform.mjs && node test/pose-surface.mjs && node test/bind-and-tabs.mjs && node test/batch.mjs && node test/circuit-traces.mjs", "test:traces": "node test/circuit-traces.mjs", "prepublishOnly": "node test/syntax.mjs", "test:platform": "node test/platform.mjs"
public/js/app.js+22@@ -1004,6 +1004,23 @@ function runLint() { if (!state) return; const items = computeLint(); if (!items) return;+ // Publish what this surface measured, stamped with the pose revision it+ // rendered (hero-studio#51). 0.20.4 split computeLint() out of this+ // function and the send went with it, so an open surface stopped feeding+ // state.lint: only a compose could, and on a box with no local Chrome+ // nothing did (the gate's lint box read "No layout findings." and the+ // attested Generate refused as stale). The server drops findings whose+ // lintPoseRev the pose has moved past, so a measurement racing a newer+ // change is never stamped fresh. Not while a typed text is still unsaved:+ // that render shows a pose the server does not have yet. The render view+ // never posts (post() is a no-op there).+ if (Object.keys(textDrafts).length) return items;+ const lint = items.map(({ id, level, msg }) => ({ id, level, msg }));+ const key = JSON.stringify([state.poseRev, lint]);+ if (key !== lastLintKey) {+ lastLintKey = key;+ send({ lint, lintPoseRev: state.poseRev });+ } return items; } window.__computeLint = () => (computeLint() || []).map(({ id, level, msg }) => ({ id, level, msg }));@@ -1527,12 +1544,17 @@ function solveTitleFit(maxCqw) { } function runFit(maxCqw) { const r = solveTitleFit(maxCqw);+ // A fit that leaves the title where it is still answers the request:+ // state.fitPending used to clear only on a fontSize post, so "no size+ // fits" or "already the best size" read as "no surface is responding". if (r == null) {+ send({ fitAck: true }); handleToast({ text: 'fit: no title size in 5-13cqw keeps this headline inside the hero and clear of the showcase image for this layout; shorten the headline, or move or resize the showcase image', kind: 'warn', seq: Date.now() }); return; } const cur = (state.fontSize || {}).title || 8; if (Math.abs(r.size - cur) >= 0.05) send({ fontSize: { title: r.size } });+ else send({ fitAck: true }); if (r.loose) { handleToast({ text: 'fit: this headline cannot make 3 lines at any legible size; set ' + r.size + 'cqw (' + r.lines + ' lines, still clear of the band). SHORTER COPY READS BIGGER: the title is the one message, aim for a few words', kind: 'warn', seq: Date.now() }); } else if (Math.abs(r.size - cur) >= 0.05) {
render-pup.mjs+29@@ -8,6 +8,8 @@ import { createRequire } from 'module'; // // Usage: node render-pup.mjs <url-reachable-from-host> <out.png> // Exit 0 with the cropped PNG at out.png; nonzero with a plain message.+// Like render-hero.mjs it prints `LINT_JSON [...]` (or `LINT_JSON_ERR why`)+// on stdout: the findings window.__computeLint() measured in this render. import { execFile } from 'child_process'; import fs from 'fs'; import { makeBridge } from './bridge.mjs';@@ -95,6 +97,33 @@ if (!m) die('could not measure #hero (unexpected browser_eval output).'); const [bx, by, bw, bh, dpr] = m[1].split(',').map(Number); if (!(bw > 50 && bh > 50)) die('#hero measured degenerate (' + bw + 'x' + bh + ').'); +// 5b. measured lint from the SAME page code, in this render view, as+// render-hero.mjs does (hero-studio#51): the server parses the LINT_JSON+// line and stores the findings as measured against the pose this view+// loaded, so compose through pup refreshes stale lint too. The JSON is+// hex-encoded between sentinels: hex has no quote, backslash or slash, so+// whatever escaping the CLI applies to eval results cannot corrupt it.+const lintRaw = await evalIn(+ "(function(){try{if(typeof window.__computeLint!=='function')return 'HSLINT-NONE';" ++ "var b=new TextEncoder().encode(JSON.stringify(window.__computeLint()));var h='';" ++ "for(var i=0;i<b.length;i++)h+=(b[i]<16?'0':'')+b[i].toString(16);" ++ "return 'HSLINT@'+h+'@TNILSH';}catch(e){return 'HSLINT-ERR '+String(e&&e.message||e).replace(/[^A-Za-z0-9 .,:_-]/g,' ');}})()");+const lintHex = lintRaw && lintRaw.match(/HSLINT@([0-9a-f]*)@TNILSH/);+if (lintHex) {+ try {+ const lint = JSON.parse(Buffer.from(lintHex[1], 'hex').toString('utf8'));+ if (Array.isArray(lint)) console.log('LINT_JSON ' + JSON.stringify(lint));+ else console.log('LINT_JSON_ERR __computeLint returned ' + typeof lint + ', not a list');+ } catch (e) {+ console.log('LINT_JSON_ERR ' + e.message);+ }+} else {+ const why = lintRaw && lintRaw.match(/HSLINT-ERR ([A-Za-z0-9 .,:_-]*)/);+ console.log('LINT_JSON_ERR ' + (why ? why[1].trim()+ : lintRaw && lintRaw.includes('HSLINT-NONE') ? 'the render view has no window.__computeLint'+ : 'browser_eval returned no lint'));+}+ // 6. screenshot the host window. The CLI hands back a PNG either as a path // (written where the container can read it) or as base64 in the JSON. const shot = await sh(['browser_screenshot', JSON.stringify({ sessionId: SESSION })], 45000);
server.js+166−78@@ -89,6 +89,76 @@ function refreshRenderer() { if (changed) { try { broadcast('state', state); } catch {} } return next; }++// The renderer ladder, ONE definition for Generate and compose: local+// headless Chrome first (full fidelity), then the host browser via pup for+// containers that cannot run Chrome (#7). A local leg known to be missing+// its pieces is skipped, not tried (#58). `pinned` ('local' | 'pup') keeps+// one leg. Compose used to spawn render-hero.mjs only, so on a box with no+// local Chrome (an aarch64 Hydrogen Mac workspace, rendering through pup on+// the host) it died with "Chrome not found" and the stale-lint refusal of+// an attested Generate had no way out.+function renderLadder(pinned) {+ const attempts = [];+ const localKnownDead = !!(state.renderer && !state.renderer.local.ok);+ if (pinned !== 'pup' && (pinned === 'local' || !localKnownDead)) {+ attempts.push({ script: 'render-hero.mjs', url: 'http://localhost:' + PORT + '/?render=1', label: 'local', timeout: 60000 });+ }+ const proxyBase = PLAT.studioUrl(PORT) || '';+ if (pinned !== 'local' && proxyBase) {+ attempts.push({ script: 'render-pup.mjs', url: proxyBase + (proxyBase.endsWith('/') ? '' : '/') + '?render=1', label: 'pup', timeout: 150000 });+ }+ return attempts;+}++/// Walk the ladder into outFile. cb(null, {via, lint}) for the first leg that+/// renders, where lint is the LINT_JSON that leg measured in its own render+/// view (null when it printed none); cb(failures) with every leg's reason+/// joined when none did.+function renderThroughLadder(attempts, outFile, cb) {+ const failures = [];+ const next = () => {+ const a = attempts.shift();+ if (!a) return cb(failures.join(' | ') || 'no render leg ran');+ logLine('info', 'render via ' + a.label);+ try { fs.unlinkSync(outFile); } catch {}+ const child = spawn(process.execPath, [path.join(__dirname, a.script), a.url, outFile], {+ env: process.env, stdio: ['ignore', 'pipe', 'pipe'],+ });+ let errBuf = '';+ let outBuf = '';+ let timedOut = false;+ child.stdout.on('data', (c) => { outBuf += c; });+ child.stderr.on('data', (c) => { errBuf += c; });+ const timer = setTimeout(() => { timedOut = true; child.kill(); }, a.timeout);+ child.on('close', (code) => {+ clearTimeout(timer);+ let lint = null;+ const lm = outBuf.split('\n').find((l) => l.startsWith('LINT_JSON '));+ if (lm) { try { lint = JSON.parse(lm.slice('LINT_JSON '.length)); } catch {} }+ const le = outBuf.split('\n').find((l) => l.startsWith('LINT_JSON_ERR '));+ if (le) logLine('warn', a.label + ' render could not measure lint: ' + le.slice('LINT_JSON_ERR '.length));+ if (code === 0 && fs.existsSync(outFile)) return cb(null, { via: a.label, lint });+ failures.push(a.label + ': ' + (timedOut ? 'timed out after ' + Math.round(a.timeout / 1000) + ' s' : (renderError(errBuf) || a.label + ' render exited ' + code)));+ next();+ });+ };+ next();+}++/// What re-measures lint on THIS box, for the stale-lint refusal: compose+/// walks the ladder above, so on a pup-only container it renders on the host.+function lintRemeasureHint() {+ const rs = state.renderer || refreshRenderer();+ const surface = 'An open studio surface also re-measures lint on its own about half a second after each change. Check that state.lintMeta.stale is false, then retry.';+ if (rs.local.ok) {+ return 'Run hero-studio compose (GET /compose.png). It re-measures lint against the exact current pose in local headless Chrome. ' + surface;+ }+ if (rs.pup.ok) {+ return 'Run hero-studio compose (GET /compose.png). This box has no local renderer (' + rs.local.why + '), so compose renders through the host browser via pup, the same leg Generate uses, and re-measures lint there. That can take a minute or two. ' + surface;+ }+ return 'Nothing on this box can re-measure lint: ' + rs.local.why + '; pup fallback: ' + rs.pup.why + '. Open the studio (hero-studio pose) so the surface measures it, or fix a renderer with hero-studio doctor.';+} const COMPONENTS = JSON.parse(fs.readFileSync(path.join(__dirname, 'data', 'components.json'), 'utf8')); let state = {@@ -211,6 +281,9 @@ let lastToast = null; let genSeq = Date.now(); let lastGen = null; let generating = false;+// A compose renders through the same ladder (and, on the pup leg, the same+// host render window) as Generate, so the two never run at once.+let composing = false; // The page ROWS (title, brief, type) change while a surface is open: a live // refresh or an api/pages write can correct a page's type mid-session. The@@ -258,6 +331,9 @@ function leanState() { // rides every SSE state push, so an open surface can tell its page rows // went stale without polling out.pagesRev = PAGES_REV;+ // and the pose revision this state is, so the surface can stamp the lint+ // it measures with the revision it actually measured (hero-studio#51)+ out.poseRev = poseRev; if (state.showcase && state.showcase.src && state.showcase.src.startsWith('data:')) { out.showcase = Object.assign({}, state.showcase, { src: 'showcase.png?v=' + srcHash(state.showcase.src) }); }@@ -354,7 +430,7 @@ function removeWebviewTab() { // touch resets the clock; a slowly-finished pose survives days, an abandoned // one is gone in TTL_HOURS with a lossless snapshot (#39 restores it). function reap() {- if (generating) return; // finish pending renders; next tick reaps+ if (generating || composing) return; // finish pending renders; next tick reaps logLine('info', 'idle ' + TTL_HOURS + 'h: reaping (snapshot saved; restart with the same --ai-thread to resume)'); try { fs.writeFileSync(SNAP, JSON.stringify({ ts: Date.now(), state, changes })); } catch {} deregisterInstance();@@ -880,10 +956,10 @@ function route(req, res, url, p) { let body; if (cached && cached.rev === etag) body = cached.body; else {- body = JSON.stringify(Object.assign({}, lean ? leanState() : state, { _toast: lastToast, _gen: lastGen, enums: ENUMS, version: PKG_VERSION, aiThread: AI_THREAD, gatesDone: readGates(), seasoned: isSeasoned(), resolved: resolvedText(), pagesRev: PAGES_REV,+ body = JSON.stringify(Object.assign({}, lean ? leanState() : state, { _toast: lastToast, _gen: lastGen, enums: ENUMS, version: PKG_VERSION, aiThread: AI_THREAD, gatesDone: readGates(), seasoned: isSeasoned(), resolved: resolvedText(), pagesRev: PAGES_REV, poseRev, lintMeta: lintMeta ? Object.assign({}, lintMeta, { stale: lintMeta.poseRev !== poseRev })- : { stale: true, reason: 'no lint measured yet this session; GET /compose.png (hero-studio compose) measures it server-side' },+ : { stale: true, reason: 'no lint measured yet this session; an open studio surface measures it within a second, and GET /compose.png (hero-studio compose) measures it through the render ladder (local Chrome, else the host browser via pup)' }, fitPending })); stateBodyCache[variant] = { rev: etag, body }; }@@ -985,12 +1061,29 @@ function route(req, res, url, p) { logLine('info', 'full import: composed overlays auto-disabled (#32); re-enable explicitly to simulate them (they render amber-fenced)'); } const before = snapshotPose();+ // Measurement fields (hero-studio#51): an open surface posts+ // {lint, lintPoseRev} after every render it measures, and {fitAck}+ // when it answered a fit without moving the title. These, and the+ // caller's aiThread, are not pose: they never bump poseRev (a lint+ // post that bumped it would make its own findings stale, and the+ // surface would measure and post again forever). lintPoseRev is the+ // revision the surface rendered; findings for a pose that has moved+ // on are dropped, never stamped fresh against the newer one.+ const lintRev = Number.isInteger(body.lintPoseRev) ? body.lintPoseRev : null;+ const fitAck = 'fitAck' in body;+ delete body.lintPoseRev;+ delete body.fitAck;+ let lintDropped = null;+ if ('lint' in body && lintRev !== null && lintRev !== poseRev) {+ lintDropped = 'lint measured at poseRev ' + lintRev + ' but the pose is at ' + poseRev + ': dropped, a surface re-measures the current pose';+ delete body.lint;+ } merge(state, body);- if (Object.keys(body).some((k) => k !== 'lint')) poseRev += 1;+ if (Object.keys(body).some((k) => k !== 'lint' && k !== 'aiThread')) poseRev += 1; if ('lint' in body) {- lintMeta = { computedAt: new Date().toISOString(), poseRev, source: 'surface' };+ lintMeta = { computedAt: new Date().toISOString(), poseRev: lintRev !== null ? lintRev : poseRev, source: 'surface' }; }- if (body.fontSize && typeof body.fontSize.title === 'number') fitPending = null;+ if (fitAck || (body.fontSize && typeof body.fontSize.title === 'number')) fitPending = null; if (pageChanged) { refreshGuide().catch(() => {}); refreshPageLive(state.page)@@ -999,9 +1092,10 @@ function route(req, res, url, p) { } notePoseDiff(before); logLine('info', 'state <- ' + JSON.stringify(body).slice(0, 500));+ if (lintDropped) logLine('info', lintDropped); broadcast('state', state); res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify({ ok: true, state }));+ res.end(JSON.stringify(lintDropped ? { ok: true, lintDropped, state } : { ok: true, state })); }); } if (p === '/changes' && req.method === 'GET') {@@ -1180,35 +1274,54 @@ function route(req, res, url, p) { if (p === '/compose.png') { // Headless compose (#36.2): the current composed hero WITHOUT provenance, // so an agent can verify staging (slug bands, double pills, alignment)- // without driving a browser. Costs one headless render (~3s).+ // without driving a browser. Costs one render: ~3 s in local headless+ // Chrome, longer through the host browser on the pup leg. if (generating) { res.writeHead(503); return res.end('generate in progress'); }+ if (composing) { res.writeHead(503); return res.end('a compose is already running; wait for it, then retry'); }+ const fail = (payload) => {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(Object.assign({ ok: false }, payload)));+ };+ // ?renderer=local|pup pins one leg, as POST /generate {renderer} does;+ // HERO_RENDERER pins it server-wide.+ const pinned = url.searchParams.get('renderer') || process.env.HERO_RENDERER || '';+ if (!pinned) {+ const rs = refreshRenderer();+ if (!rs.local.ok && !rs.pup.ok) {+ return fail({ errorCode: 'RENDERER_NOT_READY', error: 'no renderer: ' + rs.local.why + '; pup fallback: ' + rs.pup.why,+ hint: (rs.local.fix || "run 'hero-studio doctor'") + '; then retry, the renderer is spawned per compose' });+ }+ }+ const attempts = renderLadder(pinned);+ if (!attempts.length) {+ return fail({ error: 'no renderer available (pinned to pup but neither HERO_STUDIO_URL nor VSCODE_PROXY_URI is set)', hint: 'drop the renderer pin, or give the host a URL it can reach the studio on (pose --url <port-mapping URL>)' });+ } const tmp = path.join(__dirname, 'generated', 'compose-preview.png'); fs.mkdirSync(path.dirname(tmp), { recursive: true });- const child = spawn(process.execPath, [path.join(__dirname, 'render-hero.mjs'), 'http://localhost:' + PORT + '/?render=1', tmp], { env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });- let eb = '';- let ob = '';- child.stdout.on('data', (c) => { ob += c; });- child.stderr.on('data', (c) => { eb += c; });- const t = setTimeout(() => child.kill(), 60000);- child.on('close', (code) => {- clearTimeout(t);- if (code !== 0 || !fs.existsSync(tmp)) {- res.writeHead(500, { 'Content-Type': 'application/json' });- return res.end(JSON.stringify({ ok: false, error: renderError(eb) || 'compose render failed' }));+ // The render view loads the state as it is now; a pose change while the+ // render runs (a pup render can take a minute) must leave the findings+ // stale, so they are stamped with the revision the render started from.+ const revAtStart = poseRev;+ composing = true;+ renderThroughLadder(attempts, tmp, (err, done) => {+ composing = false;+ if (err) {+ logLine('error', 'compose failed: ' + String(err).slice(-400));+ return fail({ error: err, hint: "run 'hero-studio doctor': it verifies the local renderer (puppeteer-core, Chrome, launch) and the pup fallback, and prints the exact fix for whatever is missing" }); }- // hero-studio#51: the headless render evaluated the SAME linter the- // surface runs; store its findings as fresh-by-construction, so the- // measured gate no longer depends on an open, responsive surface.- const lm = ob.split('\n').find((l) => l.startsWith('LINT_JSON '));- if (lm) {- try {- state.lint = JSON.parse(lm.slice('LINT_JSON '.length));- lintMeta = { computedAt: new Date().toISOString(), poseRev, source: 'compose' };- logLine('info', 'compose measured lint: ' + state.lint.length + ' finding(s) at poseRev ' + poseRev);- broadcast('state', state);- } catch {}+ // hero-studio#51: the render evaluated the SAME linter the surface+ // runs, in its own render view; store its findings as measured+ // against the pose it loaded, so the measured gate no longer depends+ // on an open, responsive surface. Both legs report them.+ if (Array.isArray(done.lint)) {+ state.lint = done.lint;+ lintMeta = { computedAt: new Date().toISOString(), poseRev: revAtStart, source: 'compose', renderer: done.via };+ logLine('info', 'compose via ' + done.via + ' measured lint: ' + state.lint.length + ' finding(s) at poseRev ' + revAtStart + (revAtStart !== poseRev ? ' (the pose moved to ' + poseRev + ' during the render, so they are stale)' : ''));+ broadcast('state', state);+ } else {+ logLine('warn', 'compose via ' + done.via + ' rendered but reported no lint; state.lint is unchanged'); }- res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-cache' });+ res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-cache', 'X-Hero-Renderer': done.via }); res.end(fs.readFileSync(tmp)); }); return;@@ -1446,6 +1559,10 @@ function route(req, res, url, p) { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ ok: false, error: 'a generate is already running', hint: 'wait for it to finish, then retry' })); }+ if (composing) {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ return res.end(JSON.stringify({ ok: false, error: 'a compose is running', hint: 'wait for it to finish (on the pup leg that can take a minute or two), then retry' }));+ } return readBody(req, (bodyErr, body) => { // body {"renderer":"local"|"pup"} pins one ladder leg for this request // (the test hook for the pup path); HERO_RENDERER env pins it server-wide.@@ -1477,8 +1594,7 @@ function route(req, res, url, p) { // against a pose that no longer exists. The human gate is exempt: human // eyes are at that gate by definition. if (!fromGate && (!lintMeta || lintMeta.poseRev !== poseRev)) {- return refuse('state.lint is stale: the pose changed after it was measured (or it was never measured)',- 'GET /compose.png (hero-studio compose) re-measures lint server-side against the exact current pose, then retry');+ return refuse('state.lint is stale: the pose changed after it was measured (or it was never measured)', lintRemeasureHint()); } if (!fromGate) { // Automated mode (#45, decided by Colby 2026-08-13): SAME-SESSION@@ -1588,6 +1704,13 @@ function route(req, res, url, p) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(payload)); };+ // The checks measured in the very render that becomes the hero; they ride+ // the stamp so a published hero can be audited for what was flagged.+ // Declared before the passthrough below, which calls finalize() (and so+ // reads it) before the ladder ever runs: declared after, the passthrough+ // threw "Cannot access 'renderLint' before initialization" into its own+ // catch and always fell back to re-rendering the import.+ let renderLint = null; // Passthrough (#36.1): a full-import with every overlay off composes // NOTHING in the browser, so a headless re-render can only recompress and // color-shift the author's pixels. Decode the import straight to disk and@@ -1607,55 +1730,20 @@ function route(req, res, url, p) { } } }- // Renderer ladder: local headless Chrome first (full fidelity), then the- // host browser via pup for containers that cannot run Chrome (#7).- const attempts = [];- // a local leg known to be missing its pieces is skipped, not tried (#58)- const localKnownDead = !!(state.renderer && !state.renderer.local.ok);- if (pinned !== 'pup' && (pinned === 'local' || !localKnownDead)) {- attempts.push({ script: 'render-hero.mjs', url: 'http://localhost:' + PORT + '/?render=1', label: 'local', timeout: 60000 });- }- const proxyBase = PLAT.studioUrl(PORT) || '';- if (pinned !== 'local' && proxyBase) {- attempts.push({ script: 'render-pup.mjs', url: proxyBase + (proxyBase.endsWith('/') ? '' : '/') + '?render=1', label: 'pup', timeout: 150000 });- }+ // Renderer ladder (renderLadder above, shared with compose): local+ // headless Chrome first (full fidelity), then the host browser via pup.+ const attempts = renderLadder(pinned); if (!attempts.length) { return finish({ ok: false, error: 'no renderer available (pinned to pup but neither HERO_STUDIO_URL nor VSCODE_PROXY_URI is set)', hint: 'drop the renderer pin, or give the host a URL it can reach the studio on (pose --url <port-mapping URL>)' }); }- const failures = [];- // The checks measured in the very render that becomes the hero; they ride- // the stamp so a published hero can be audited for what was flagged.- let renderLint = null;- const runRender = (a, cb) => {- const child = spawn(process.execPath, [path.join(__dirname, a.script), a.url, outFile], {- env: process.env, stdio: ['ignore', 'pipe', 'pipe'],- });- let errBuf = '';- let outBuf = '';- child.stdout.on('data', (c) => { outBuf += c; });- child.stderr.on('data', (c) => { errBuf += c; });- const timer = setTimeout(() => { child.kill(); }, a.timeout);- child.on('close', (code) => {- clearTimeout(timer);- const lm = outBuf.split('\n').find((l) => l.startsWith('LINT_JSON '));- if (lm) { try { renderLint = JSON.parse(lm.slice('LINT_JSON '.length)); } catch {} }- if (code === 0 && fs.existsSync(outFile)) return cb(null);- cb(renderError(errBuf) || a.label + ' render exited ' + code);- });- };- const tryNext = () => {- const a = attempts.shift();- if (!a) {- logLine('error', 'generate failed: ' + failures.join(' | ').slice(-400));- return finish({ ok: false, error: failures.join(' | '), hint: "run 'hero-studio doctor': it verifies the local renderer (puppeteer-core, Chrome, launch), the pup fallback, and the PIL stamp step, and prints the exact fix for whatever is missing" });+ renderThroughLadder(attempts, outFile, (err, done) => {+ if (err) {+ logLine('error', 'generate failed: ' + String(err).slice(-400));+ return finish({ ok: false, error: err, hint: "run 'hero-studio doctor': it verifies the local renderer (puppeteer-core, Chrome, launch), the pup fallback, and the PIL stamp step, and prints the exact fix for whatever is missing" }); }- logLine('info', 'render via ' + a.label);- runRender(a, (err) => {- if (err) { failures.push(a.label + ': ' + err); return tryNext(); }- finalize(a.label);- });- };- tryNext();+ renderLint = done.lint;+ finalize(done.via);+ }); return; function finalize(renderedVia) {
test/compose-ladder.mjsadded+312@@ -0,0 +1,312 @@+#!/usr/bin/env node+// Compose through the renderer ladder, and lint freshness: node test/compose-ladder.mjs+//+// On a container with no local Chrome (an aarch64 Hydrogen Mac workspace that+// renders through pup on the host), an attested re-generate was impossible:+// - POST /generate refused with HUMAN_GATE "state.lint is stale" whenever+// lintMeta.poseRev !== poseRev, and its hint said GET /compose.png;+// - /compose.png spawned render-hero.mjs only, the local Chrome leg, so it+// died with "Chrome not found" and never tried pup;+// - render-pup.mjs printed no LINT_JSON, so even a pup render measured+// nothing;+// - the open surface stopped posting its lint in 0.20.4, so nothing could+// refresh state.lint there at all.+//+// This needs no Chrome and no desktop. It starts a real server on a spare+// port with a temporary HOME and a dead local renderer, and puts a stub+// `adom-bridge` first on PATH that answers the pup verbs render-pup.mjs uses+// (and evaluates render-pup's own lint expression against a fake window). The+// real bridge is never called. It asserts:+// - the stale refusal's hint names compose through pup on this box,+// - GET /compose.png renders via pup (X-Hero-Renderer), and the findings it+// measured land in state.lint fresh, source compose, renderer pup, intact+// through a CLI that escapes slashes,+// - the attested Generate then gets past the stale-lint refusal,+// - a pose change during a compose leaves its findings stale; a second+// compose and a Generate are refused while one runs,+// - a failing leg reports its reason and leaves state.lint alone,+// - ?renderer=local pins the local leg,+// - surface lint posts: {lint, lintPoseRev} is fresh and does not bump+// poseRev, an outdated one is dropped, the legacy {lint} still lands,+// - {fitAck} clears state.fitPending without touching the pose,+// - the surface's runLint and runFit (lifted out of app.js) post exactly+// that: lint with its rev, deduped, held while a typed text is unsaved,+// and an answer to every fit,+// - the full-import passthrough really passes through (it used to throw on+// renderLint and fall back to re-rendering the import).+import { spawn, execFileSync } from 'child_process';+import net from 'net';+import fs from 'fs';+import os from 'os';+import path from 'path';+import { fileURLToPath } from 'url';+import { createRequire } from 'module';++const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const PLAT = createRequire(import.meta.url)(path.join(ROOT, 'platform.cjs'));+let pass = 0; const fails = [];+const ok = (name, cond, detail) => { if (cond) { pass++; console.log(' ok ' + name); } else { fails.push(name); console.log(' FAIL ' + name + (detail ? ': ' + detail : '')); } };+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// The surface's side, pure (no browser): runLint and runFit lifted out of+// public/js/app.js with their collaborators stubbed. test/render-view.mjs+// checks the same against a real page when a Chrome is available.+{+ const app = fs.readFileSync(path.join(ROOT, 'public/js/app.js'), 'utf8');+ const lintSrc = app.match(/\nfunction runLint\(\) \{[\s\S]*?\n\}\n/);+ const fitSrc = app.match(/\nfunction runFit\(maxCqw\) \{[\s\S]*?\n\}\n/);+ ok('app.js defines runLint and runFit', !!lintSrc && !!fitSrc);+ if (lintSrc && fitSrc) {+ const sent = [];+ const env = { state: { poseRev: 5, fontSize: { title: 8 } }, drafts: {}, items: null, fit: null };+ const mk = new Function('env', 'sent',+ 'let state = env.state; let lastLintKey = ""; const textDrafts = env.drafts;\n' ++ 'const computeLint = () => env.items; const send = (p) => sent.push(JSON.parse(JSON.stringify(p)));\n' ++ 'const solveTitleFit = () => env.fit; const handleToast = () => {};\n' ++ lintSrc[0] + fitSrc[0] + '\nreturn { runLint, runFit, setState: (s) => { state = s; } };');+ const s = mk(env, sent);+ env.items = [{ id: 'headroom', level: 'info', msg: 'published headroom: 40px', el: 'el-title' }];+ s.runLint();+ ok('surface runLint posts {lint, lintPoseRev} with the rev it rendered, el stripped', sent.length === 1 && JSON.stringify(sent[0]) === JSON.stringify({ lint: [{ id: 'headroom', level: 'info', msg: 'published headroom: 40px' }], lintPoseRev: 5 }), JSON.stringify(sent));+ s.runLint();+ ok('surface runLint does not repeat the same findings for the same rev', sent.length === 1, JSON.stringify(sent));+ s.setState({ poseRev: 6, fontSize: { title: 8 } });+ s.runLint();+ ok('surface runLint re-posts the same findings for a new rev (keeps them fresh)', sent.length === 2 && sent[1].lintPoseRev === 6, JSON.stringify(sent));+ env.drafts.headline = 'typed, not saved yet';+ s.setState({ poseRev: 7, fontSize: { title: 8 } });+ s.runLint();+ ok('surface runLint holds while a typed text is unsaved', sent.length === 2, JSON.stringify(sent));+ delete env.drafts.headline;+ s.runLint();+ ok('and posts once the draft has landed', sent.length === 3 && sent[2].lintPoseRev === 7, JSON.stringify(sent));+ env.items = null;+ s.runLint();+ ok('surface runLint posts nothing when the hero cannot be measured', sent.length === 3);+ sent.length = 0;+ env.fit = null; s.runFit(null);+ env.fit = { size: 8 }; s.runFit(null);+ env.fit = { size: 9.5 }; s.runFit(null);+ ok('surface runFit always answers: fitAck when nothing fits or the size stays, fontSize when it moves', JSON.stringify(sent) === JSON.stringify([{ fitAck: true }, { fitAck: true }, { fontSize: { title: 9.5 } }]), JSON.stringify(sent));+ }+}++const PY = PLAT.pythonWithPillow();+if (!PY) {+ console.log(' SKIP the server half: no Python with Pillow, and render-pup.mjs crops with PIL');+ console.log('\n' + pass + ' passed, ' + fails.length + ' failed');+ process.exit(fails.length ? 1 : 0);+}++const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hs-compose-'));+const BIN = path.join(tmp, 'bin');+fs.mkdirSync(BIN);+const STUB_DIR = BIN;+const py = (code, ...args) => execFileSync(PY.cmd, [...PY.args, '-c', code, ...args], { stdio: 'pipe' });++// What the stub host "screenshots": the render window at 1720x1180 with the+// 16px #ff00fe sentinel at viewport (0,0); #hero measures 1600x1000 at y=40.+py('import sys\nfrom PIL import Image\nim = Image.new("RGB", (1720, 1180), (20, 24, 40))\n' ++ 'im.paste((255, 0, 254), (0, 0, 16, 16))\nim.save(sys.argv[1])\n', path.join(STUB_DIR, 'shot.png'));+// What the surface's linter would measure. Quotes, a slash, a backslash and+// non-ASCII, so the transport has to be exact.+const LINT = [+ { id: 'headroom', level: 'info', msg: 'published headroom: 312px between the lowest image-zone text and the marquee band at export scale (2000x1250)' },+ { id: 'band-el-sub', level: 'warn', msg: 'subtitle "Adom / Hero" extends 5px into the band \\ café — shrink it' },+];+fs.writeFileSync(path.join(STUB_DIR, 'lint.json'), JSON.stringify(LINT));++fs.writeFileSync(path.join(BIN, 'adom-bridge'), `#!/usr/bin/env node+// Stub Adom Bridge for test/compose-ladder.mjs: the pup verbs render-pup.mjs+// calls, nothing else. Flag files in this directory steer it: slow (ms to+// stall the screenshot), fail (the screenshot fails).+const fs = require('fs');+const vm = require('vm');+const DIR = __dirname;+let a = process.argv.slice(2);+if (a[0] === '--ai-thread') a = a.slice(2);+const ti = a.indexOf('--target'); if (ti >= 0) a.splice(ti, 2);+const verb = a[0] || '';+let args = {}; try { args = a[1] ? JSON.parse(a[1]) : {}; } catch {}+fs.appendFileSync(DIR + '/calls.log', verb + (args.expr && String(args.expr).includes('__computeLint') ? ' lint' : '') + '\\n');+const say = (o) => console.log(JSON.stringify(o));+if (verb === 'bridge_list') {+ console.log('pup 3.0.8 running: pup_status pup_open_window pup_navigate pup_eval pup_screenshot pup_alert_window');+} else if (verb === 'pup_status') {+ say({ ok: true, sessions: [] });+} else if (verb === 'pup_open_window' || verb === 'pup_navigate') {+ say({ ok: true, sessionId: args.sessionId });+} else if (verb === 'pup_eval') {+ const e = String(args.expr || '');+ let result = null;+ if (e.includes('__computeLint')) {+ const lint = JSON.parse(fs.readFileSync(DIR + '/lint.json', 'utf8'));+ result = vm.runInNewContext(e, { window: { __computeLint: () => lint }, TextEncoder });+ } else if (e.includes('document.readyState')) result = 'HS-READY';+ else if (e.includes('__traceError')) result = 'HS-TRACE-READY';+ else if (e.includes("__hsAssets==='ready'")) result = 'HS-ASSETS-READY';+ else if (e.includes("__hsAssets='wait'")) result = 'HS-ASSETS-STARTED';+ else if (e.includes('HSBOX@')) result = 'HSBOX@0,40,1600,1000,1@XOBSH';+ // some CLIs escape forward slashes in their JSON: the lint must survive it+ console.log(JSON.stringify({ ok: true, result }).replace(/\\//g, '\\\\/'));+} else if (verb === 'pup_screenshot') {+ if (fs.existsSync(DIR + '/slow')) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(fs.readFileSync(DIR + '/slow', 'utf8')) || 1500);+ if (fs.existsSync(DIR + '/fail')) { console.error('stub: the host refused the screenshot'); process.exit(1); }+ say({ ok: true, path: DIR + '/shot.png' });+} else {+ console.error('stub: unknown verb ' + verb);+ process.exit(2);+}+`);+fs.chmodSync(path.join(BIN, 'adom-bridge'), 0o755);+const calls = () => { try { return fs.readFileSync(path.join(STUB_DIR, 'calls.log'), 'utf8').trim().split('\n').filter(Boolean); } catch { return []; } };+const clearCalls = () => { try { fs.unlinkSync(path.join(STUB_DIR, 'calls.log')); } catch {} };++const PORT = await new Promise((res) => { const s = net.createServer().listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => res(p)); }); });+const THREAD = 'compose ladder test';+// No local renderer (isolated renderer lookup, no Chrome), the host reaches+// the studio on HERO_STUDIO_URL, a dead registry (nothing leaves this box).+const env = { ...process.env, HOME: tmp, USERPROFILE: tmp, PATH: BIN + path.delimiter + process.env.PATH,+ HERO_STUDIO_RENDERER_HOME: path.join(tmp, 'rh'), HERO_STUDIO_RENDERER_ISOLATED: '1', CHROME: path.join(tmp, 'no-chrome'),+ HERO_STUDIO_URL: 'http://127.0.0.1:{{port}}/', ADOM_WIKI_REGISTRY: 'http://127.0.0.1:9', ADOM_TARGET: '', HERO_STUDIO_PORT: String(PORT) };+delete env.VSCODE_PROXY_URI; delete env.HERO_RENDERER; delete env.PUPPETEER_CORE; delete env.ADOM_AI_THREAD;+// The temporary HOME would hide a Pillow installed with pip --user; keep the+// real user site so the crop and the stamp find it.+try { env.PYTHONUSERBASE = env.PYTHONUSERBASE || execFileSync(PY.cmd, [...PY.args, '-m', 'site', '--user-base'], { encoding: 'utf8' }).trim(); } catch {}++const genDir = path.join(ROOT, 'generated');+const genBefore = new Set(fs.existsSync(genDir) ? fs.readdirSync(genDir) : []);+const server = spawn(process.execPath, [path.join(ROOT, 'server.js'), '--port', String(PORT), '--host', '127.0.0.1', '--ai-thread', THREAD, '--ttl', '1'],+ { env, cwd: ROOT, stdio: ['ignore', 'pipe', 'pipe'] });+let serverErr = '';+server.stderr.on('data', (c) => { serverErr += c; });+const base = 'http://127.0.0.1:' + PORT;+const getState = async () => (await fetch(base + '/state')).json();+const postJson = async (p, body) => (await fetch(base + p, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(Object.assign({ aiThread: THREAD }, body)) })).json();+const pngSize = (buf) => (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) ? [buf.readUInt32BE(16), buf.readUInt32BE(20)] : null;+const ATTEST = { human: 'drew', quote: 'looks good, ship it' };++let up = false;+for (let i = 0; i < 50 && !up; i++) { try { up = (await fetch(base + '/state')).ok; } catch {} if (!up) await sleep(200); }+ok('a hero-studio server answers on :' + PORT, up, serverErr.slice(-300));+if (!up) { server.kill(); fs.rmSync(tmp, { recursive: true, force: true }); console.log('\n' + pass + ' passed, ' + fails.length + ' failed'); process.exit(1); }++let sse = null;+try {+ const st0 = await getState();+ ok('the box under test is pup-only: local renderer dead, pup reachable', st0.renderer && !st0.renderer.local.ok && st0.renderer.pup.ok, JSON.stringify(st0.renderer));+ ok('GET /state carries poseRev', Number.isInteger(st0.poseRev), String(st0.poseRev));+ ok('never-measured lint reads stale, and the reason names the surface and pup', st0.lintMeta && st0.lintMeta.stale === true && /surface/.test(st0.lintMeta.reason || '') && /pup/.test(st0.lintMeta.reason || ''), JSON.stringify(st0.lintMeta));++ // 1. the refusal Drew hit, now with a hint that works on this box+ const g0 = await postJson('/generate', { attest: ATTEST });+ ok('attested Generate on stale lint refuses with HUMAN_GATE "state.lint is stale"', g0.ok === false && g0.errorCode === 'HUMAN_GATE' && /^state\.lint is stale/.test(g0.error || ''), JSON.stringify(g0).slice(0, 300));+ ok('the stale hint names compose through the host browser via pup on a box with no local renderer', /hero-studio compose/.test(g0.hint || '') && /via pup/.test(g0.hint || '') && /no local renderer/.test(g0.hint || ''), g0.hint);++ // 2. compose renders through pup and measures lint there+ clearCalls();+ const revBefore = (await getState()).poseRev;+ const c1 = await fetch(base + '/compose.png');+ const c1buf = Buffer.from(await c1.arrayBuffer());+ ok('GET /compose.png answers 200 image/png with no local Chrome', c1.status === 200 && /image\/png/.test(c1.headers.get('content-type') || ''), c1.status + ' ' + c1buf.toString('utf8', 0, 300));+ ok('compose says it rendered via pup (X-Hero-Renderer)', c1.headers.get('x-hero-renderer') === 'pup', String(c1.headers.get('x-hero-renderer')));+ const sz = pngSize(c1buf);+ ok('the composed PNG is the cropped #hero, 1600x1000', sz && sz[0] === 1600 && sz[1] === 1000, JSON.stringify(sz));+ ok('render-pup evaluated window.__computeLint in the render view', calls().includes('pup_eval lint'), calls().join(','));+ const st1 = await getState();+ ok('compose stored the measured findings exactly (quotes, slash, backslash, non-ASCII intact)', JSON.stringify(st1.lint) === JSON.stringify(LINT), JSON.stringify(st1.lint));+ ok('lintMeta: fresh, source compose, renderer pup, at the pose the render loaded', st1.lintMeta && st1.lintMeta.stale === false && st1.lintMeta.source === 'compose' && st1.lintMeta.renderer === 'pup' && st1.lintMeta.poseRev === revBefore, JSON.stringify(st1.lintMeta));+ ok('compose did not move the pose', st1.poseRev === revBefore, st1.poseRev + ' vs ' + revBefore);++ // 3. the attested Generate gets past the stale-lint refusal+ const g1 = await postJson('/generate', { attest: ATTEST });+ ok('after compose, the attested Generate is no longer refused as stale', !/stale/.test(g1.error || ''), JSON.stringify(g1).slice(0, 300));++ // 4. a pose change while a compose runs: findings stamped with the start rev+ fs.writeFileSync(path.join(STUB_DIR, 'slow'), '2500');+ const revStart = (await getState()).poseRev;+ const slowCompose = fetch(base + '/compose.png').then(async (r) => ({ status: r.status, renderer: r.headers.get('x-hero-renderer'), body: Buffer.from(await r.arrayBuffer()) }));+ await sleep(700);+ const busy = await fetch(base + '/compose.png');+ ok('a second compose while one runs answers 503', busy.status === 503, busy.status + ' ' + (await busy.text()).slice(0, 120));+ const gBusy = await postJson('/generate', { attest: ATTEST });+ ok('Generate while a compose runs is refused, naming the compose', gBusy.ok === false && /compose is running/.test(gBusy.error || ''), JSON.stringify(gBusy).slice(0, 200));+ const moved = await postJson('/state', { headline: 'Moved during the render' });+ ok('a pose change during the compose lands', moved.ok === true);+ const slow = await slowCompose;+ fs.unlinkSync(path.join(STUB_DIR, 'slow'));+ ok('the slow compose still renders via pup', slow.status === 200 && slow.renderer === 'pup', slow.status + ' ' + slow.body.toString('utf8', 0, 200));+ const st2 = await getState();+ ok('findings from a render that started before the change are stamped with its start rev, so they read stale', st2.lintMeta.poseRev === revStart && st2.poseRev > revStart && st2.lintMeta.stale === true, JSON.stringify({ meta: st2.lintMeta, poseRev: st2.poseRev, revStart }));++ // 5. a failing pup leg: reason reported, state.lint untouched+ fs.writeFileSync(path.join(STUB_DIR, 'fail'), '1');+ const lintBefore = JSON.stringify(st2.lint);+ const cf = await fetch(base + '/compose.png');+ const cfBody = await cf.json().catch(() => ({}));+ fs.unlinkSync(path.join(STUB_DIR, 'fail'));+ ok('a failed compose answers 500 with the leg and its reason, and a hint', cf.status === 500 && cfBody.ok === false && /^pup: /.test(cfBody.error || '') && /doctor/.test(cfBody.hint || ''), cf.status + ' ' + JSON.stringify(cfBody).slice(0, 300));+ ok('a failed compose leaves state.lint as it was', JSON.stringify((await getState()).lint) === lintBefore);++ // 6. ?renderer=local pins the local leg (dead here), like POST /generate {renderer}+ clearCalls();+ const cl = await fetch(base + '/compose.png?renderer=local');+ const clBody = await cl.json().catch(() => ({}));+ ok('?renderer=local runs only the local leg', cl.status === 500 && /^local: /.test(clBody.error || '') && !/pup:/.test(clBody.error || '') && calls().length === 0, cl.status + ' ' + JSON.stringify(clBody).slice(0, 300) + ' calls=' + calls().join(','));++ // 7. surface lint posts+ const s0 = await getState();+ const SURF = [{ id: 'headroom', level: 'info', msg: 'published headroom: 200px' }];+ const p1 = await postJson('/state', { lint: SURF, lintPoseRev: s0.poseRev });+ const s1 = await getState();+ ok('a surface post {lint, lintPoseRev} at the current rev lands fresh, source surface', p1.ok && JSON.stringify(s1.lint) === JSON.stringify(SURF) && s1.lintMeta.source === 'surface' && s1.lintMeta.stale === false && s1.lintMeta.poseRev === s0.poseRev, JSON.stringify(s1.lintMeta));+ ok('a lint post does not bump poseRev (no re-measure loop)', s1.poseRev === s0.poseRev, s1.poseRev + ' vs ' + s0.poseRev);+ ok('lintPoseRev is not merged into state', !('lintPoseRev' in s1));+ const p2 = await postJson('/state', { lint: [{ id: 'old', level: 'warn', msg: 'measured on an older pose' }], lintPoseRev: s0.poseRev - 1 });+ const s2 = await getState();+ ok('lint measured at an older poseRev is dropped and says so', p2.ok && /dropped/.test(p2.lintDropped || '') && JSON.stringify(s2.lint) === JSON.stringify(SURF) && s2.lintMeta.poseRev === s0.poseRev, JSON.stringify({ lintDropped: p2.lintDropped, lint: s2.lint }));+ await postJson('/state', { subtitle: 'a pose change' });+ const s3 = await getState();+ ok('a pose change makes the surface findings stale', s3.poseRev === s0.poseRev + 1 && s3.lintMeta.stale === true, JSON.stringify({ poseRev: s3.poseRev, meta: s3.lintMeta }));+ const LEGACY = [{ id: 'headroom', level: 'info', msg: 'posted by hand' }];+ await postJson('/state', { lint: LEGACY });+ const s4 = await getState();+ ok('the legacy {aiThread, lint} post still lands fresh without bumping poseRev', JSON.stringify(s4.lint) === JSON.stringify(LEGACY) && s4.lintMeta.stale === false && s4.poseRev === s3.poseRev, JSON.stringify({ poseRev: s4.poseRev, meta: s4.lintMeta }));++ // 8. fitAck: a surface that answered a fit without moving the title+ const ac = new AbortController();+ sse = ac;+ fetch(base + '/events', { signal: ac.signal }).then(async (r) => { try { for await (const _ of r.body) {} } catch {} }).catch(() => {});+ await sleep(300);+ const f0 = await postJson('/fit', {});+ const s5 = await getState();+ ok('POST /fit with a surface connected sets state.fitPending', f0.ok === true && !!s5.fitPending, JSON.stringify(f0).slice(0, 200));+ await postJson('/state', { fitAck: true });+ const s6 = await getState();+ ok('{fitAck} clears state.fitPending', s6.fitPending === null, JSON.stringify(s6.fitPending));+ ok('{fitAck} neither moves the pose nor lands in state', s6.poseRev === s5.poseRev && !('fitAck' in s6), s6.poseRev + ' vs ' + s5.poseRev);+ ac.abort(); sse = null;++ // 9. the full-import passthrough really passes through+ const imp = path.join(tmp, 'import.png');+ py('import sys\nfrom PIL import Image\nImage.new("RGB", (1600, 1000), (200, 40, 90)).save(sys.argv[1])\n', imp);+ const src = 'data:image/png;base64,' + fs.readFileSync(imp).toString('base64');+ await postJson('/state', { mode: 'component', showcase: { src, full: true, cover: false, chrome: '' }, overlay: { pill: false, scores: false, author: false, slug: false, logo: false }, lint: [] });+ clearCalls();+ const gp = await postJson('/generate', { fromGate: true });+ const con = await (await fetch(base + '/console')).text();+ ok('a full import with every overlay off generates', gp.ok === true && !!gp.file, JSON.stringify(gp).slice(0, 300));+ ok('it passed through: no render leg ran, no "passthrough write failed"', calls().length === 0 && !/passthrough write failed/.test(con), 'calls=' + calls().join(',') + ' ' + (con.match(/passthrough write failed[^"]*/) || [''])[0]);+ if (gp.file) {+ const meta = fs.readFileSync(path.join(genDir, gp.file)).toString('latin1');+ ok('its provenance says renderer passthrough', /"renderer":"passthrough"/.test(meta));+ }+} finally {+ if (sse) sse.abort();+ server.kill();+ // remove only what this run added to generated/+ try { for (const f of fs.readdirSync(genDir)) if (!genBefore.has(f)) fs.rmSync(path.join(genDir, f), { force: true }); } catch {}+ fs.rmSync(tmp, { recursive: true, force: true });+}+console.log('\n' + pass + ' passed, ' + fails.length + ' failed');+process.exit(fails.length ? 1 : 0);
test/render-view.mjs+33−1@@ -13,7 +13,9 @@ // - the render view makes no state-changing POST, // - it reaches networkidle2 while the other surface is open, // - no slotSize ping-pong: the server sees at most one slotSize POST per surface,-// - renderError() extracts the real error line, not the Node.js version footer.+// - renderError() extracts the real error line, not the Node.js version footer,+// - a real interactive surface publishes its lint again with the poseRev it+// rendered, re-measures after a pose change, and then stays quiet. import { spawn } from 'child_process'; import net from 'net'; import fs from 'fs';@@ -108,6 +110,36 @@ try { ctl.abort(); ok('no slotSize ping-pong with a surface that measures differently', otherPosts <= 2, otherPosts + ' corrective posts from the other surface');++ // A real open surface publishes its own lint again (hero-studio#51): stamped+ // with the poseRev it rendered, re-measured after a pose change, and quiet+ // once it has said it, since a lint post must not move the pose.+ const surf = await browser.newPage();+ await surf.setViewport({ width: 1440, height: 1000, deviceScaleFactor: 1 });+ let lintPosts = 0;+ surf.on('request', (r) => { if (r.method() === 'POST' && /\/state$/.test(r.url()) && /"lintPoseRev"/.test(r.postData() || '')) lintPosts++; });+ await surf.goto(base + '/', { waitUntil: 'load', timeout: 15000 }).catch(() => {});+ const waitState = async (pred, ms) => {+ const end = Date.now() + ms;+ let st = null;+ while (Date.now() < end) {+ st = await (await fetch(base + '/state')).json();+ if (pred(st)) return st;+ await new Promise(r => setTimeout(r, 250));+ }+ return st;+ };+ const freshSurface = (st) => st && st.lintMeta && st.lintMeta.source === 'surface' && st.lintMeta.stale === false;+ const sl0 = await waitState(freshSurface, 10000);+ ok('an open surface publishes its lint: fresh, source surface', freshSurface(sl0), JSON.stringify(sl0 && sl0.lintMeta));+ const rev0 = sl0 ? sl0.poseRev : 0;+ await fetch(base + '/state', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ aiThread: 'render-view test', headline: 'Surface lint follows the pose' }) });+ const sl1 = await waitState((st) => freshSurface(st) && st.poseRev > rev0, 10000);+ ok('after a pose change the surface re-measures at the new poseRev', freshSurface(sl1) && sl1.poseRev > rev0 && sl1.lintMeta.poseRev === sl1.poseRev, JSON.stringify(sl1 && { poseRev: sl1.poseRev, meta: sl1.lintMeta }));+ const settled = lintPosts;+ await new Promise(r => setTimeout(r, 2500));+ ok('the surface goes quiet once its lint is posted (no re-measure loop)', lintPosts - settled <= 1, (lintPosts - settled) + ' lint posts while idle');+ await surf.close(); } finally { await browser.close(); server.kill();
Comments
Log in to comment.