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
← Commit history
Full test suite in the page repo: npm test runs here (the published package carries only test/brand.mjs)
10 files changed
+475
.gitignoreadded+4@@ -0,0 +1,4 @@+generated/+server.log+nohup.out+node_modules/
test/baseline-sha.jsonadded+17@@ -0,0 +1,17 @@+{+ "note": "sha256 of the 12 canonical parity poses at the 0.19 wizard baseline (post ink-anchor). Regenerate with test/parity.sh and compare with test/pixdiff.py; refresh this manifest ONLY on a sanctioned visual change. Refreshed 2026-08-17 at the 0.20 rename (rendering verified unchanged; the 2 import-based poses drifted only via generated/latest.png fixture content).",+ "poses": {+ "brand-slug.png": "139db6d912582c5445c2c9c0106eaf649b45686a13cdae027b68763b9180b8a5",+ "component-phong.png": "a4d61c2eea205c740a96a60a634083e21e20545e93c60ec790eea9ab7a4e5f2c",+ "fullimport-stamp.png": "47f5f75744484d1780e07368baf4903e205b45da7dcbfe6c212d3ae9da412ec3",+ "layout-bleed-bottom.png": "a7e3bc7052076c3aa7946a822dd93dff42d5afcb2e817cf23f0ec12439b22646",+ "layout-bleed-right.png": "39b0420db1b81d895e9d64177c723336a891d7c66b878b64fc4cb9c6319ec7ea",+ "layout-bleed-top.png": "3829b87475cefc5d649b9593c283c128fbdaad00ca0e755c292f4bc6a8734fed",+ "layout-contained.png": "132c35f40701ca34644a9a42678784a293902a2aae1d8f6e0fac117c3d33992d",+ "layout-mirror.png": "5877e9e332d927add11949a8c8ce5abce01278bae62f5806c7102c2036265578",+ "layout-showcase.png": "f4225a462b7fc3713526f9694c7ae66b76abc58f5b0eb4157295413955ef1e98",+ "theme-circuitry.png": "0e4eed9a67c04ebe8a19b8f0d40431a6fefadadf18e15d11c37cceab9c92b8f5",+ "theme-gradient-both.png": "238cca34b0dab25b1e1e46027dd5a4c0321119959699ab4ecf6b471a5e918018",+ "showcase-bare.png": "8a41da3bb34fddcbbca4fc7a6c76f4d8a87296a415444b84d04dd4be0700f7fa"+ }+}
test/batch.mjsadded+137@@ -0,0 +1,137 @@+#!/usr/bin/env node+// Batch tests: node test/batch.mjs+//+// Applying a style and a showcase moves the pose, and automated Generate+// refuses lint measured against an older pose. Batch has to re-measure for+// each part or every part fails with "state.lint is stale". This runs the real+// verb against a real server and a stub registry, with a saved style, and+// asserts:+// - every good part generates, and its provenance carries the attestation,+// - warnings come back in results[],+// - a part with a hard-fail finding is skipped with its findings, and the+// parts after it still generate,+// - a headline that would run onto the showcase image at the style's size+// is stepped down until it clears (reported as batch-title-fitted), and+// one that cannot clear at the legibility floor is skipped,+// - every hero's stamp carries the checks measured in its own render.+import http from 'http';+import { spawn, execFileSync } from 'child_process';+import fs from 'fs';+import net from 'net';+import os from 'os';+import path from 'path';+import { fileURLToPath } from 'url';++const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+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 freePort = () => new Promise((res) => { const s = net.createServer().listen(0, () => { const p = s.address().port; s.close(() => res(p)); }); });++const guide = (owner, status, errors) => ({+ owner, status, version: 1, sha: 'a'.repeat(40), can_edit: false, owner_kind: 'org', visibility: 'public',+ page: owner + '/brand', url: 'http://stub/' + owner + '/brand',+ editable_by: { rule: 'org-members', owner_kind: 'org', who: [owner], text: 'Any member of ' + owner + ' can edit ' + owner + '/brand.' },+ brand: { brand_manifest: '1.0', owner, name: owner, status, confirmed_by: 'someone', confirmed_at: '2026-01-01T00:00:00Z',+ colors: { primary: '#ff0000', background: '#101010', text: '#ffffff' },+ typography: { display: { family: 'Inter' }, body: { family: 'Inter' } }, logos: { mark: 'assets/mark.svg' } },+ assets: { mark: 'http://stub/' + owner + '/brand/files/assets/mark.svg', fonts: [] },+ hints: [], warnings: [], errors: errors || [],+});+const GUIDES = { goodco: guide('goodco', 'confirmed'), badco: guide('badco', 'invalid', [{ field: 'colors.primary', message: 'not a color' }]), nologo: guide('nologo', 'confirmed') };+const MARK_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="120" height="40"><rect width="120" height="40" fill="#ff0000"/></svg>';+const registry = http.createServer((req, res) => {+ // The guide's logo file: goodco's exists, nologo's is missing (hero-studio#76).+ if (/\/brand\/files\/assets\/mark\.svg$/.test(req.url)) {+ if (req.url.startsWith('/goodco/')) { res.writeHead(200, { 'Content-Type': 'image/svg+xml' }); return res.end(MARK_SVG); }+ res.writeHead(404); return res.end('not found');+ }+ const m = req.url.match(/^\/api\/owners\/([^/]+)\/brand/);+ const g = m && GUIDES[decodeURIComponent(m[1])];+ res.writeHead(g ? 200 : 404, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(g || { error: 'not found' }));+});+const regPort = await freePort();+await new Promise((r) => registry.listen(regPort, r));+for (const g of Object.values(GUIDES)) g.assets.mark = 'http://127.0.0.1:' + regPort + '/' + g.owner + '/brand/files/assets/mark.svg';++// The studio records every page it is told about in data/pages.json, and writes+// its exports next to the package. Put both back whatever happens.+const pagesFile = path.join(ROOT, 'data', 'pages.json');+const pagesBefore = fs.readFileSync(pagesFile);+const genDir = path.join(ROOT, 'generated');+const listGenerated = () => { try { return new Set(fs.readdirSync(genDir)); } catch { return new Set(); } };+const genBefore = listGenerated();++const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hs-batch-'));+const styleName = 'batch-test-' + process.pid;+const styleDir = path.join(os.homedir(), '.adom', 'instances', 'hero-studio', 'styles');+const styleFile = path.join(styleDir, styleName + '.json');+fs.mkdirSync(styleDir, { recursive: true });+fs.writeFileSync(styleFile, JSON.stringify({ name: styleName,+ style: { mode: 'app', guides: false, layout: 'bleed-right', fontSize: { title: 12 }, showcase: { chrome: '', cover: false } },+ gate: { page: 'goodco/gated', human: 'tester', ts: 1 } }));++const PORT = await freePort();+const env = { ...process.env, ADOM_WIKI_REGISTRY: 'http://127.0.0.1:' + regPort, HERO_STUDIO_PORT: String(PORT) };+const server = spawn(process.execPath, [path.join(ROOT, 'server.js'), '--port', String(PORT), '--ai-thread', 'batch test', '--ttl', '1'], { env, stdio: 'ignore' });+let code = 1;+try {+ let up = false;+ for (let i = 0; i < 50 && !up; i++) { try { up = (await fetch('http://localhost:' + PORT + '/state')).ok; } catch {} if (!up) await new Promise((r) => setTimeout(r, 200)); }+ ok('a studio answers', up);++ const partsFile = path.join(tmp, 'parts.json');+ // A plain 16:10 screenshot for the showcase image.+ const shot = path.join(tmp, 'shot.png');+ execFileSync('python3', ['-c', "from PIL import Image; Image.new('RGB', (1600, 1000), (40, 60, 90)).save('" + shot + "')"]);+ fs.writeFileSync(partsFile, JSON.stringify([+ { ref: 'goodco/batch-one', title: 'Batch One', type: 'app', headline: 'First part', subtitle: 'one' },+ { ref: 'badco/batch-bad', title: 'Batch Bad', type: 'app', headline: 'Broken guide', subtitle: 'two' },+ { ref: 'goodco/batch-two', title: 'Batch Two', type: 'app', headline: 'Second part', subtitle: 'three' },+ { ref: 'goodco/batch-long', title: 'Batch Long', type: 'app', headline: 'Soldermask lamination, simulated', subtitle: 'four', showcase: shot },+ { ref: 'goodco/batch-huge', title: 'Batch Huge', type: 'app', headline: 'Supercalifragilisticexpialidocious pneumonoultramicroscopic', subtitle: 'five', showcase: shot },+ { ref: 'nologo/batch-nologo', title: 'Batch No Logo', type: 'app', headline: 'Logo file missing', subtitle: 'six' },+ ]));+ const run = await new Promise((res) => {+ const c = spawn(process.execPath, [path.join(ROOT, 'drive.mjs'), '--ai-thread', 'batch test', '--port', String(PORT), 'batch',+ '--style', styleName, '--parts', partsFile, '--pace', '0.1', '--human', 'tester', '--quote', 'looks right'], { env, stdio: ['ignore', 'pipe', 'pipe'] });+ let out = ''; let err = '';+ c.stdout.on('data', (d) => { out += d; });+ c.stderr.on('data', (d) => { err += d; });+ c.on('close', (status) => res({ status, out, err }));+ });+ let results = [];+ try { results = JSON.parse(run.out).results; } catch {}+ const [one, bad, two, long, huge, nologo] = results;+ ok('nothing fails as stale', !/stale/.test(run.err), run.err.slice(-400));+ ok('the first good part generates', one && one.ok && one.file, JSON.stringify(one));+ ok(' and reports its warnings as a list', one && Array.isArray(one.warnings), JSON.stringify(one));+ ok('the hard-fail part is skipped, naming the finding', bad && !bad.ok && /brand-invalid/.test(bad.error), JSON.stringify(bad));+ ok(' and returns its findings', bad && (bad.lint || []).some((l) => l.level === 'fail' && l.id === 'brand-invalid'), JSON.stringify(bad));+ ok('the part after it still generates', two && two.ok && two.file && two.file !== (one && one.file), JSON.stringify(two));+ ok('a long headline is stepped down until it clears the showcase image', long && long.ok && (long.warnings || []).some((l) => l.id === 'batch-title-fitted'), JSON.stringify(long));+ ok(' and nothing it shipped touches the image', long && !(long.warnings || []).some((l) => /^showcase-/.test(l.id)), JSON.stringify(long));+ ok('a headline that cannot clear at the floor is skipped', huge && !huge.ok && /showcase-|clip-/.test(huge.error), JSON.stringify(huge));+ ok('a part whose logo file is missing is skipped, not exported with an empty slot', nologo && !nologo.ok && /owner-logo-missing/.test(nologo.error), JSON.stringify(nologo));+ const pngs = [one, two, long].filter((r) => r && r.file);+ for (const r of pngs) {+ const text = fs.readFileSync(path.join(genDir, r.file)).toString('latin1');+ ok(r.file.replace(/-\d+\.png$/, '') + ' carries the style and the attestation', text.includes(styleName) && text.includes('looks right'));+ ok(' and the checks from its own render', /"lint":\{"source":"render","findings":\[/.test(text));+ // The owner's logo (the stub's solid red mark) is painted in the top-left+ // wordmark slot of the exported file, not just set as a CSS background.+ const red = execFileSync('python3', ['-c', "import sys; from PIL import Image; im=Image.open(sys.argv[1]).convert('RGB'); w,h=im.size; px=im.crop((0,0,w*3//10,h*2//10)).getdata(); print(sum(1 for p in px if p[0]>230 and p[1]<40 and p[2]<40))", path.join(genDir, r.file)]).toString().trim();+ ok(' and wears the owner logo', Number(red) > 200, 'red pixels in the logo corner: ' + red);+ }+ code = fails.length ? 1 : 0;+} finally {+ server.kill();+ await new Promise((r) => setTimeout(r, 300));+ registry.close();+ fs.writeFileSync(pagesFile, pagesBefore);+ fs.rmSync(styleFile, { force: true });+ fs.rmSync(tmp, { recursive: true, force: true });+ for (const f of listGenerated()) if (!genBefore.has(f)) fs.rmSync(path.join(genDir, f), { recursive: true, force: true });+}+console.log('\n' + pass + ' passed, ' + fails.length + ' failed');+process.exit(code);
test/bind-and-tabs.mjsadded+93@@ -0,0 +1,93 @@+#!/usr/bin/env node+// Reaching the studio from Hydrogen on Windows (hero-studio#75):+// node test/bind-and-tabs.mjs+//+// - the server binds IPv4 (0.0.0.0) and a separate IPv6-only socket, not the+// dual-stack wildcard WSL2 mirrored networking reaches over IPv6 only, and+// answers on 127.0.0.1, [::1] and localhost;+// - a second pose on another --port under a thread that already holds a+// studio says so at once (POSE_THREAD_HAS_STUDIO), not "did not come up";+// - pose opens its own port's tab and never repoints another instance's.+import { spawn, execFileSync } from 'child_process';+import fs from 'fs';+import os from 'os';+import net from 'net';+import path from 'path';+import { fileURLToPath } from 'url';++const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+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 freePort = () => new Promise((res) => { const s = net.createServer().listen(0, () => { const p = s.address().port; s.close(() => res(p)); }); });+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+const get = async (url) => { try { const r = await fetch(url); return r.status; } catch { return 0; } };++const THREADS = ['bind test', 'bind test other'];+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hs-bind-'));+const fakeBin = path.join(tmp, 'bin'); fs.mkdirSync(fakeBin);+const calls = path.join(tmp, 'adom-cli.log');+const baseEnv = { ...process.env, PATH: fakeBin + ':' + (process.env.PATH || '') };+delete baseEnv.VSCODE_PROXY_URI; delete baseEnv.HERO_STUDIO_URL; delete baseEnv.HERO_STUDIO_PORT; delete baseEnv.HERO_STUDIO_HOST; delete baseEnv.ADOM_AI_THREAD;+const pose = (thread, args, ms = 60000) => new Promise((res) => {+ const t0 = Date.now();+ const p = spawn(process.execPath, [path.join(ROOT, 'pose.mjs'), ...args], { env: { ...baseEnv, ADOM_AI_THREAD: thread }, stdio: ['ignore', 'pipe', 'pipe'] });+ let err = '';+ p.stderr.on('data', (d) => { err += d; });+ const t = setTimeout(() => p.kill(), ms);+ p.on('close', (code) => { clearTimeout(t); res({ code, err, ms: Date.now() - t0 }); });+});++let server = null;+try {+ // --- the bind ---+ const port = await freePort();+ server = spawn(process.execPath, [path.join(ROOT, 'server.js'), '--port', String(port), '--ai-thread', THREADS[0]], { env: baseEnv, stdio: 'ignore' });+ for (let i = 0; i < 40 && (await get('http://127.0.0.1:' + port + '/version')) !== 200; i++) await sleep(250);+ ok('answers on 127.0.0.1', (await get('http://127.0.0.1:' + port + '/version')) === 200);+ ok('answers on [::1]', (await get('http://[::1]:' + port + '/version')) === 200);+ ok('answers on localhost', (await get('http://localhost:' + port + '/version')) === 200);+ // Listening sockets on this port from /proc/net: 0.0.0.0 in tcp, :: in tcp6.+ const hex = port.toString(16).toUpperCase().padStart(4, '0');+ const listeners = (f) => { try { return fs.readFileSync(f, 'utf8').split('\n').slice(1).map((l) => l.trim().split(/\s+/)).filter((c) => c[1] && c[1].endsWith(':' + hex) && c[3] === '0A').map((c) => c[1].split(':')[0]); } catch { return null; } };+ const v4 = listeners('/proc/net/tcp'), v6 = listeners('/proc/net/tcp6');+ if (v4 && v6) {+ ok('binds 0.0.0.0 explicitly (an IPv4 socket)', v4.includes('00000000'), JSON.stringify({ v4, v6 }));+ ok(' and a separate IPv6 socket', v6.includes('0'.repeat(32)), JSON.stringify({ v4, v6 }));+ } else console.log(' skip socket check (no /proc/net)');++ // --- a second port under the same thread ---+ fs.writeFileSync(path.join(fakeBin, 'adom-cli'), '#!/bin/sh\necho \'{"tabs":[]}\'\n', { mode: 0o755 });+ const other = await freePort();+ let r = await pose(THREADS[0], ['adom/hero-studio', '--surface', 'webview', '--no-local', '--port', String(other), '--url', 'http://127.0.0.1:' + other + '/', '--timeout', '3']);+ ok('same thread, another --port: POSE_THREAD_HAS_STUDIO, exit 1', r.code === 1 && r.err.includes('POSE_THREAD_HAS_STUDIO') && r.err.includes(':' + port), r.code + ' ' + r.err.slice(0, 300));+ ok(' at once, without waiting for a server that never comes', r.ms < 5000, r.ms + ' ms');+ ok(' and names the way out (another thread name, or stop)', r.err.includes('--ai-thread "<other name>"') && r.err.includes('stop --port ' + port));++ // --- tabs: another instance's tab is left alone ---+ fs.writeFileSync(path.join(fakeBin, 'adom-cli'),+ '#!/bin/sh\necho "$@" >> ' + JSON.stringify(calls) + '\n' ++ 'case "$*" in *"workspace tabs"*) echo \'{"tabs":[{"name":"Visual Studio Code","panelId":"vs"},{"name":"Hero Studio :' + port + '","panelId":"p1"}]}\' ;; esac\n', { mode: 0o755 });+ r = await pose(THREADS[1], ['adom/hero-studio', '--surface', 'webview', '--no-local', '--port', String(other), '--url', 'http://127.0.0.1:' + other + '/', '--timeout', '3']);+ const log = fs.existsSync(calls) ? fs.readFileSync(calls, 'utf8') : '';+ const opens = log.split('\n').filter((l) => l.includes('open-or-refresh'));+ ok('opens a tab named for its own port', opens.some((l) => l.includes('--name Hero Studio :' + other)), log);+ ok(' in the pane that already holds a studio', opens.some((l) => l.includes('--panel-id p1')), log);+ ok(' and never repoints the other instance\'s tab', !log.includes('Hero Studio :' + port + ' --url'), log);+ ok(' pose reports the new tab', r.err.includes('tab "Hero Studio :' + other + '"'), r.err.slice(-300));+} finally {+ if (server) server.kill();+ // stop the studios these poses started, by their instance files' exact pids+ const dir = path.join(os.homedir(), '.adom', 'instances', 'hero-studio');+ try {+ for (const f of fs.readdirSync(dir)) {+ if (!f.endsWith('.json')) continue;+ try {+ const e = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'));+ if (THREADS.includes(e.thread)) process.kill(e.pid);+ } catch {}+ }+ } catch {}+ fs.rmSync(tmp, { recursive: true, force: true });+}+console.log('\n' + pass + ' passed, ' + fails.length + ' failed');+process.exit(fails.length ? 1 : 0);
test/gate.mjsadded+12@@ -0,0 +1,12 @@+// hero-studio#77: a re-posed gate for a page generated earlier in the session+// is OPEN, so another thread's pose must not take it over.+import assert from 'assert';+import { gateOpen } from '../gate.mjs';++assert.equal(gateOpen(null), false);+assert.equal(gateOpen({ verify: false, page: 'adom/a' }), false, 'not posed');+assert.equal(gateOpen({ verify: true, page: 'adom/a', posedAt: 10 }), true, 'posed, never generated');+assert.equal(gateOpen({ verify: true, page: 'adom/a', posedAt: 10, approved: { page: 'adom/a', ts: 20 } }), false, 'generated after the pose: closed');+assert.equal(gateOpen({ verify: true, page: 'adom/a', posedAt: 30, approved: { page: 'adom/a', ts: 20 } }), true, 're-posed after a generate: open (the #77 case)');+assert.equal(gateOpen({ verify: true, page: 'adom/a', posedAt: 10, approved: { page: 'adom/b', ts: 20 } }), true, 'the approval was for another page');+console.log('gate: ok');
test/parity.shadded+34@@ -0,0 +1,34 @@+#!/bin/bash+# Pixel-parity harness for the wizard redesign: drives 12 canonical poses+# through a running studio server and composes each to a PNG.+#+# test/parity.sh <outdir> # server on $HERO_STUDIO_PORT or 8898+# python3 test/pixdiff.py <a> <b> # compare two runs; exit 1 on any diff+#+# The export view must stay pixel-identical across refactors: run once before+# a change, once after, and diff. Uses circuitSeed 424242 so the circuitry+# theme is deterministic.+set -e+OUT=$1+[ -z "$OUT" ] && { echo "usage: parity.sh <outdir>"; exit 2; }+mkdir -p "$OUT"+ROOT=$(cd "$(dirname "$0")/.." && pwd)+S=http://127.0.0.1:${HERO_STUDIO_PORT:-8898}+T='"aiThread":"parity harness"'+post() { curl -s -X POST "$S$1" -H 'Content-Type: application/json' -d "$2" > /dev/null; }+reset() {+ post /preset "{$T,\"name\":\"studio-default\"}"+ post /state "{$T,\"showcase\":{\"src\":\"\",\"full\":false,\"cover\":false,\"chrome\":\"\"},\"bgImage\":{\"src\":\"\",\"cover\":false},\"headline\":\"\",\"subtitle\":\"\",\"accentWords\":null,\"page\":\"adom/adom-tts\",\"guides\":false,\"marqueePreview\":false,\"verify\":false,\"tour\":false,\"circuitSeed\":424242}"+}+shoot() { curl -s -o "$OUT/$1.png" "$S/compose.png"; echo " $1: $(stat -c%s "$OUT/$1.png") bytes"; }++for L in bleed-bottom bleed-right bleed-top contained mirror showcase; do+ reset; post /state "{$T,\"layout\":\"$L\"}"; shoot "layout-$L"+done+reset; post /state "{$T,\"theme\":\"circuitry\",\"circuitSeed\":424242}"; shoot theme-circuitry+reset; post /state "{$T,\"theme\":\"gradient\",\"gradAngle\":200,\"titleMode\":\"both\",\"show\":{\"description\":true}}"; shoot theme-gradient-both+reset; post /showcase-file "{$T,\"path\":\"$ROOT/generated/latest.png\"}"; post /state "{$T,\"showcase\":{\"chrome\":\"bare\"},\"layout\":\"bleed-right\"}"; shoot showcase-bare+reset; post /showcase-file "{$T,\"path\":\"$ROOT/generated/latest.png\"}"; post /state "{$T,\"showcase\":{\"full\":true},\"overlay\":{\"logo\":true}}"; shoot fullimport-stamp+reset; post /state "{$T,\"page\":\"adom/adom-tts\",\"brand\":{\"accent\":\"#ff7a1e\",\"bg\":\"#101820\"},\"overlay\":{\"slug\":true}}"; shoot brand-slug+reset; post /state "{$T,\"mode\":\"component\",\"comp\":{\"id\":\"sm02b-srss-tb\",\"imgSrc\":\"phong\",\"layout\":\"photo-left\",\"mpn\":\"eyebrow\"},\"theme\":\"pcb\"}"; shoot component-phong+reset
test/pixdiff.pyadded+21@@ -0,0 +1,21 @@+# Compare two parity runs pixel by pixel. Exit 1 on any difference.+import sys, os+from PIL import Image, ImageChops+a_dir, b_dir = sys.argv[1], sys.argv[2]+bad = 0+for f in sorted(os.listdir(a_dir)):+ if not f.endswith('.png'):+ continue+ a = Image.open(os.path.join(a_dir, f)).convert('RGB')+ b = Image.open(os.path.join(b_dir, f)).convert('RGB')+ if a.size != b.size:+ print(f, 'SIZE MISMATCH', a.size, b.size)+ bad += 1+ continue+ bbox = ImageChops.difference(a, b).getbbox()+ if bbox is None:+ print(f, 'identical')+ else:+ print(f, 'DIFF bbox', bbox)+ bad += 1+sys.exit(1 if bad else 0)
test/platform.mjs+17@@ -66,6 +66,23 @@ ok('macOS: /Applications Chrome is a candidate', mac.includes('/Applications/Goo const lin = RP.chromeCandidates('linux', {}, home); ok('Linux: the cache layout and system Chrome are candidates', lin.some((c) => c.includes('chrome-linux64')) && lin.includes('/usr/bin/google-chrome')); +// --- CPU architecture (#69): an x86-64 Chrome on ARM64 looks installed and never runs ---+const elf = (machine) => { const b = Buffer.alloc(64); b.set([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1], 0); b.writeUInt16LE(machine, 18); return b; };+const x64Bin = path.join(tmp, 'chrome-x64'); fs.writeFileSync(x64Bin, elf(0x3e));+const armBin = path.join(tmp, 'chrome-arm64'); fs.writeFileSync(armBin, elf(0xb7));+const script = path.join(tmp, 'chrome-wrapper'); fs.writeFileSync(script, '#!/bin/sh\nexec chrome "$@"\n');+ok('an x86-64 ELF reads as x64', RP.binaryArch(x64Bin) === 'x64', RP.binaryArch(x64Bin));+ok('an ARM64 ELF reads as arm64', RP.binaryArch(armBin) === 'arm64', RP.binaryArch(armBin));+ok('a wrapper script has no architecture', RP.binaryArch(script) === null);+ok('an x86-64 Chrome is refused on arm64', !RP.archOk(x64Bin, 'arm64') && RP.archOk(armBin, 'arm64'));+ok('a wrapper script is never refused', RP.archOk(script, 'arm64'));+const pwHome = path.join(tmp, 'pwhome');+for (const v of ['chromium-999', 'chromium-1140', 'chromium-1187', 'chromium_headless_shell-1187']) fs.mkdirSync(path.join(pwHome, '.cache', 'ms-playwright', v, 'chrome-linux'), { recursive: true });+const linPw = RP.chromeCandidates('linux', {}, pwHome);+const pw = linPw.filter((c) => c.includes('ms-playwright'));+ok('Linux: Playwright Chromium builds are candidates, newest first, headless shells skipped',+ pw.length === 3 && pw[0].includes('chromium-1187') && pw[1].includes('chromium-1140') && pw[2].includes('chromium-999'), pw.join(' | '));+ // --- a real server: desktop identity, snapshot path, no stamp tools (#60 #64 #66) --- const port = await new Promise((r) => { const s = net.createServer().listen(0, () => { const p = s.address().port; s.close(() => r(p)); }); }); const binDir = path.join(tmp, 'bin'); fs.mkdirSync(binDir);
test/pose-surface.mjsadded+105@@ -0,0 +1,105 @@+#!/usr/bin/env node+// Posing from a plain terminal (hero-studio#72): node test/pose-surface.mjs+//+// A terminal on a cloud container has no VS Code proxy, the desktop bridge+// lists other bridges' verbs before pup's, and a surface can fail to open+// while the gate itself works. These checks pin each fix:+// - the bridge adapter picks pup_* (or browser_*) verbs, never altium_status,+// fusion_status or the native-browser extension's nbrowser_open_window;+// - an ambiguous desktop reads as "pass --target", not as "did not answer";+// - --url / HERO_STUDIO_URL outrank the VS Code proxy;+// - with no URL at all, pose refuses before anything is posed;+// - when no surface opens, pose keeps waiting with the URL, and with+// --no-fallback it closes the gate it opened and exits 3.+import { spawn } from 'child_process';+import fs from 'fs';+import os from 'os';+import net from 'net';+import path from 'path';+import { fileURLToPath } from 'url';+import { createRequire } from 'module';++const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const require = createRequire(import.meta.url);+const { resolveVerbs, bridgeTrouble } = await import(path.join(ROOT, 'bridge.mjs'));+const PLAT = require(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 : '')); } };++// --- verb resolution, in the order a real bridge_list prints them ---+const listed = 'altium_status altium_eval hd_status hd_open_url kicad_status fusion_status nbrowser_status nbrowser_open_window nbrowser_navigate nbrowser_screenshot nbrowser_eval pup_alert_window pup_status pup_open_window pup_navigate pup_eval pup_screenshot';+const v = resolveVerbs(listed);+ok('status resolves to pup_status, not altium_status or fusion_status', v.status === 'pup_status', v.status);+ok('open_window resolves to pup_open_window, not the extension', v.open_window === 'pup_open_window', v.open_window);+ok('navigate resolves to pup_navigate', v.navigate === 'pup_navigate', v.navigate);+const older = resolveVerbs('fusion_status nbrowser_open_window browser_open_window browser_status');+ok('an older box answers browser_*', older.open_window === 'browser_open_window' && older.status === 'browser_status', JSON.stringify(older));+ok('nothing listed falls back to pup_*', resolveVerbs('').open_window === 'pup_open_window');++// --- reading a bridge answer ---+const amb = { ok: false, out: '{"error":"ambiguous_target","connected":["A","B"]}', errOut: '', fail: 'exit 1' };+ok('ambiguous_target says to pass --target', /--target/.test(bridgeTrouble(amb)), bridgeTrouble(amb));+ok('a clean answer is no trouble', bridgeTrouble({ ok: true, out: '{"ok":true}', errOut: '' }) === '');+ok('an error answer names the error', bridgeTrouble({ ok: true, out: '{"error":"not_running"}', errOut: '' }) === 'not_running');++// --- the studio URL ---+const saved = { h: process.env.HERO_STUDIO_URL, v: process.env.VSCODE_PROXY_URI };+delete process.env.HERO_STUDIO_URL; delete process.env.VSCODE_PROXY_URI;+ok('no URL anywhere is null', PLAT.studioUrl(8846) === null);+process.env.VSCODE_PROXY_URI = 'https://x.example/proxy/{{port}}';+ok('the VS Code proxy template fills the port', PLAT.studioUrl(8846) === 'https://x.example/proxy/8846/', PLAT.studioUrl(8846));+process.env.HERO_STUDIO_URL = 'https://studio-abc.adom.cloud';+ok('HERO_STUDIO_URL outranks the proxy and gains a slash', PLAT.studioUrl(8846) === 'https://studio-abc.adom.cloud/', PLAT.studioUrl(8846));+if (saved.h === undefined) delete process.env.HERO_STUDIO_URL; else process.env.HERO_STUDIO_URL = saved.h;+if (saved.v === undefined) delete process.env.VSCODE_PROXY_URI; else process.env.VSCODE_PROXY_URI = saved.v;++// --- pose itself ---+const freePort = () => new Promise((res) => { const s = net.createServer().listen(0, () => { const p = s.address().port; s.close(() => res(p)); }); });+// A fake adom-cli with no Hydrogen panes, so no real webview tab is touched.+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hs-pose-'));+const fakeBin = path.join(tmp, 'bin'); fs.mkdirSync(fakeBin);+fs.writeFileSync(path.join(fakeBin, 'adom-cli'), '#!/bin/sh\necho \'{"tabs":[]}\'\n', { mode: 0o755 });+const baseEnv = { ...process.env, PATH: fakeBin + ':' + (process.env.PATH || ''), ADOM_AI_THREAD: 'pose-surface test' };+delete baseEnv.VSCODE_PROXY_URI; delete baseEnv.HERO_STUDIO_URL; delete baseEnv.HERO_STUDIO_PORT;+const pose = (args, env, ms = 120000) => new Promise((res) => {+ const p = spawn(process.execPath, [path.join(ROOT, 'pose.mjs'), ...args], { env, stdio: ['ignore', 'pipe', 'pipe'] });+ let err = '';+ p.stderr.on('data', (d) => { err += d; });+ const t = setTimeout(() => p.kill(), ms);+ p.on('close', (code) => { clearTimeout(t); res({ code, err }); });+});+const servers = [];+try {+ let r = await pose(['adom/hero-studio', '--surface', 'pup', '--no-local'], baseEnv, 20000);+ ok('no URL: pose refuses with NO_CONTAINER_PROXY and exit 1', r.code === 1 && /NO_CONTAINER_PROXY/.test(r.err), r.code + ' ' + r.err.slice(0, 200));+ ok(' and says nothing was posed, with the port-mapping recipe', /Nothing was posed/.test(r.err) && /port-add/.test(r.err) && /--url/.test(r.err));++ const port = await freePort(); servers.push(port);+ r = await pose(['adom/hero-studio', '--surface', 'webview', '--no-local', '--port', String(port), '--url', 'http://127.0.0.1:' + port + '/', '--timeout', '4'], baseEnv);+ ok('no surface opens: pose keeps waiting at the URL and times out (exit 2), not exit 1', r.code === 2, r.code + ' ' + r.err.slice(-300));+ ok(' and prints the URL to open', r.err.includes('NOT OPENED [NO_WEBVIEW_PANE]') && r.err.includes('http://127.0.0.1:' + port + '/'), r.err.slice(-400));+ let st = await (await fetch('http://127.0.0.1:' + port + '/state')).json();+ ok(' the gate stays open for whoever opens the URL', st.verify === true && st.page === 'adom/hero-studio', JSON.stringify({ verify: st.verify, page: st.page }));++ r = await pose(['adom/hero-studio', '--surface', 'webview', '--no-local', '--port', String(port), '--url', 'http://127.0.0.1:' + port + '/', '--steal', '--no-fallback'], baseEnv);+ ok('--no-fallback: exit 3 when no surface opens', r.code === 3, r.code + ' ' + r.err.slice(-300));+ st = await (await fetch('http://127.0.0.1:' + port + '/state')).json();+ ok(' and the gate it opened is closed again', st.verify === false, JSON.stringify({ verify: st.verify }));+ r = await pose(['adom/hero-studio', '--surface', 'webview', '--no-local', '--port', String(port), '--url', 'http://127.0.0.1:' + port + '/', '--timeout', '3'], baseEnv);+ ok(' so the next pose is not POSE_BUSY', r.code !== 4 && !/POSE_BUSY/.test(r.err), r.code + ' ' + r.err.slice(-200));+} finally {+ // stop the studios these poses started, by their instance files' exact pids+ const dir = path.join(os.homedir(), '.adom', 'instances', 'hero-studio');+ try {+ for (const f of fs.readdirSync(dir)) {+ if (!f.endsWith('.json')) continue;+ try {+ const e = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'));+ if (servers.includes(Number(e.port)) && e.thread === 'pose-surface test') process.kill(e.pid);+ } catch {}+ }+ } 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+35@@ -108,6 +108,41 @@ try { ok('the render view draws no outline around the title', !/solid/.test(ring.outline), JSON.stringify(ring)); ok('the page scripts parse and boot (app.js defines $ and render)', booted); + // Through a code-server style path prefix (hero-studio#68: localhost:1431/__cs/proxy/8846/?render=1):+ // every asset and data URL must resolve under the prefix, and the view must hold still while the+ // studio keeps changing state (it loads state once and never subscribes).+ const http = await import('http');+ const PREFIX = '/__cs/proxy/' + PORT;+ const prox = http.createServer((req, res) => {+ if (!req.url.startsWith(PREFIX + '/')) { res.writeHead(404); res.end('outside the proxy prefix: ' + req.url); return; }+ const up = http.request({ host: '127.0.0.1', port: PORT, path: req.url.slice(PREFIX.length), method: req.method, headers: req.headers },+ (ur) => { res.writeHead(ur.statusCode, ur.headers); ur.pipe(res); });+ up.on('error', () => { res.writeHead(502); res.end(); });+ req.pipe(up);+ });+ const PPORT = await new Promise((r) => prox.listen(0, '127.0.0.1', () => r(prox.address().port)));+ try {+ const pv = await browser.newPage();+ await pv.setViewport({ width: 1680, height: 1080, deviceScaleFactor: 1 });+ const bad = [];+ pv.on('response', (r) => { if (r.status() >= 400) bad.push(r.status() + ' ' + r.url()); });+ pv.on('requestfailed', (r) => { if (!/\/events$/.test(r.url())) bad.push('failed ' + r.url()); });+ await pv.goto('http://127.0.0.1:' + PPORT + PREFIX + '/?render=1', { waitUntil: 'load', timeout: 15000 });+ const marked = await pv.waitForFunction(() => document.body.dataset.rendered === '1', { timeout: 10000 }).then(() => true, () => false);+ ok('through a proxy prefix the render view boots and marks itself rendered', marked);+ ok(' every request resolves under the prefix (no 404s or failures)', bad.length === 0, bad.slice(0, 4).join(', '));+ const snap = () => pv.evaluate(() => { const h = document.getElementById('hero'); return h ? h.outerHTML.length + ':' + (document.getElementById('el-title') || {}).textContent : 'no hero'; });+ const before = await snap();+ for (let i = 0; i < 5; i++) {+ await fetch(base + '/state', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ aiThread: 'render-view test', headline: 'Studio edit ' + i }) });+ await new Promise(r => setTimeout(r, 300));+ }+ await new Promise(r => setTimeout(r, 1200));+ ok(' the render view holds still while the studio edits state', (await snap()) === before, before + ' -> ' + (await snap()));+ } finally {+ prox.close();+ }+ ctl.abort(); ok('no slotSize ping-pong with a surface that measures differently', otherPosts <= 2, otherPosts + ' corrective posts from the other surface');