← Commit history

pup render leg on current bridges: empty error, real screenshot path, full #hero (#78)

Drew Owens ·a83d6e7742 · ·parent 2aa6af7
Three bugs on the pup leg, each hiding the next, on a macOS host with pup 3.0.8: - Every successful reply carries "error": "", and render-pup.mjs, bridge.mjs bridgeTrouble() and pose.mjs looksOk treated the bare text '"error"' as a failure. bridge.mjs answeredError() counts only a non-empty error; all three use it. - pup_screenshot opens its reply with a _cacheHint whose example filename was the first .png in the text. bridge.mjs pngFromReply() reads the path fields first (localFullPath, localSafePath, filePath, fullPath, path), then the first .png in the text that exists. - window.resizeTo is ignored by pup windows and pup_screenshot captures only the real window's visible area (1568 px on a MacBook), clipping the 1600 px #hero. render-pup pins set_viewport 1720x1180 at 2x and shoots it with screenshot_full_res (3200x2000 crop), falling back to resizeTo and the plain screenshot on a bridge without them. Both verbs resolve through the adapter like the rest. - test/render-pup.mjs (npm run test:pup). Co-Authored-By: Claude Opus 5.5 <[email protected]>
5 files changed +231−21
bridge.mjs+43−3
@@ -7,6 +7,7 @@ // bridge_list output (manifests have claimed prefixes the box does not // answer, so never hardcode), and falls back to legacy adom-desktop. import { execFile } from 'child_process';+import fs from 'fs';  const run = (bin, args, timeout, target, thread) => new Promise((res) => {   let a = target ? [...args, '--target', target] : [...args];@@ -28,11 +29,13 @@ const which = (bin) => new Promise((res) => {  // The verbs the studio uses, by suffix; the adapter resolves each suffix to // the puppeteer bridge's name for it on this box (pup_*, or browser_* on older-// boxes). Only those two prefixes: bridge_list also lists altium_status,+// boxes). set_viewport and screenshot_full_res are what the pup render leg+// needs to capture the whole #hero on a macOS host (hero-studio#78); a box+// without them answers an error and the leg falls back. Only those two prefixes: bridge_list also lists altium_status, // fusion_status and the native-browser extension's nbrowser_open_window, and // taking the first name that ends in the suffix sent pose to the extension // and doctor to Fusion.-const SUFFIXES = ['open_window', 'navigate', 'screenshot', 'eval', 'status', 'alert_window'];+const SUFFIXES = ['open_window', 'navigate', 'screenshot', 'eval', 'status', 'alert_window', 'set_viewport', 'screenshot_full_res']; const PUP_PREFIXES = ['pup', 'browser'];  /// Pure: the verb name per suffix from bridge_list's text (exported for tests).@@ -45,12 +48,49 @@ export function resolveVerbs(listText) {   return verbs; } +/// Pure: whether a bridge reply carries an actual error (exported for tests).+/// Current bridges put `"error": ""` in every SUCCESSFUL reply, so the field+/// being present means nothing; only a non-empty value does. Matching the+/// bare text '"error"' failed every pup render on those bridges with "Adom+/// Desktop did not answer browser_status" (hero-studio#78).+export function answeredError(text) {+  return /"error"\s*:\s*(?=\S)(?!""|null\b|false\b)/.test(String(text || ''));+}++/// Pure: the readable PNG a screenshot reply points at, or null (exported for+/// tests). The path fields come first: newer bridges open the reply with a+/// `_cacheHint` whose example filenames (`<YYYY-MM-DD...>.png`) were the first+/// `.png` in the text, so taking the first match read a path that does not+/// exist (hero-studio#78). Full-resolution paths win over downscaled ones.+const SHOT_PATH_KEYS = ['localFullPath', 'localSafePath', 'filePath', 'fullPath', 'path'];+export function pngFromReply(text, exists = fs.existsSync) {+  const s = String(text || '');+  const objects = [];+  const a = s.indexOf('{');+  const b = s.lastIndexOf('}');+  if (a >= 0 && b > a) objects.push(s.slice(a, b + 1));+  for (const line of s.split('\n')) {+    const t = line.trim();+    if (t.startsWith('{') && t.endsWith('}')) objects.push(t);+  }+  for (const o of objects) {+    let j = null;+    try { j = JSON.parse(o); } catch { continue; }+    for (const at of [j, j && j.result, j && j.data]) {+      if (!at || typeof at !== 'object') continue;+      for (const k of SHOT_PATH_KEYS) if (typeof at[k] === 'string' && exists(at[k])) return at[k];+    }+  }+  for (const m of s.matchAll(/[^"\s`]+\.png/g)) if (exists(m[0])) return m[0];+  return null;+}+ /// The reason a bridge answer failed, in words, or '' when it did not. export function bridgeTrouble(r) {   const text = (r.out || '') + (r.errOut || '');   if (text.includes('ambiguous_target')) return 'several desktops are connected and none is primary: pass --target <machine> (or set ADOM_TARGET)';   if (!r.ok) return r.fail || 'failed';-  if (text.includes('"error"') || text.includes('_adom_use_cli_instead')) {+  if (answeredError(text) || text.includes('_adom_use_cli_instead')) {     const m = text.match(/"error"\s*:\s*"([^"]+)"/);     return m ? m[1] : 'the bridge answered with an error';   }
package.json+1
@@ -64,6 +64,7 @@   "scripts": {     "install": "./install.sh",     "uninstall": "./uninstall.sh",+    "test:pup": "node test/render-pup.mjs",     "test:brand": "node test/brand.mjs",     "test:render": "node test/render-view.mjs",     "test:renderer": "node test/renderer.mjs",
pose.mjs+3−2
@@ -19,7 +19,7 @@ import path from 'path'; import os from 'os'; import fs from 'fs'; import { runChecks, printReport, hintLine } from './doctor.mjs';-import { makeBridge, bridgeTrouble } from './bridge.mjs';+import { makeBridge, bridgeTrouble, answeredError } from './bridge.mjs';  const DIR = path.dirname(fileURLToPath(import.meta.url)); let BASE = 'http://localhost:8846/';@@ -430,7 +430,8 @@ if (surface === 'pup') {   const status = await bridge.call('status', {}, 15000);   steps.push([bridge.verbs.status, status]);   const hasSession = status.ok && status.out.includes(SESSION);-  const looksOk = (r) => r.ok && !r.out.includes('"error"') && !r.out.includes('_adom_use_cli_instead');+  // a non-empty error only: current bridges send "error": "" on success (#78)+  const looksOk = (r) => r.ok && !answeredError(r.out) && !r.out.includes('_adom_use_cli_instead');   let opened = hasSession     ? await bridge.call('navigate', { sessionId: SESSION, url: proxyBase }, 30000)     : await bridge.call('open_window', { sessionId: SESSION, profile: SESSION, url: proxyBase }, 60000);
render-pup.mjs+34−16
@@ -10,7 +10,7 @@ import { createRequire } from 'module'; // Exit 0 with the cropped PNG at out.png; nonzero with a plain message. import { execFile } from 'child_process'; import fs from 'fs';-import { makeBridge } from './bridge.mjs';+import { makeBridge, answeredError, pngFromReply } from './bridge.mjs';  const [,, url, out] = process.argv; if (!url || !out) { console.error('usage: render-pup.mjs <url> <out.png>'); process.exit(1); }@@ -30,7 +30,8 @@ const die = (msg) => { console.error('pup renderer: ' + msg); process.exit(1); }  // 1. is the desktop app there at all? const status = await sh(['browser_status', '{}'], 10000);-if (!status.ok || status.out.includes('"error"')) {+// a non-empty error only: current bridges send "error": "" on success (#78)+if (!status.ok || answeredError(status.out)) {   die('Adom Desktop did not answer browser_status; the host relay is not reachable from this container.'); } @@ -56,9 +57,18 @@ for (let i = 0; i < 30 && !ready; i++) { } if (!ready) die('render view never became ready (#hero not found at ' + url + ').'); -// 4. size the window up so the crop clears the gate's 1600px floor where the-// host allows it, then let fonts and images settle.-await evalIn('window.resizeTo(1720, 1180)');+// 4. size the render view so the crop clears the gate's 1600px floor, then+// let fonts and images settle. window.resizeTo does nothing in a pup window,+// and a plain screenshot captures only the real OS window's visible area: on+// a MacBook the window stayed 1450 pt wide, the capture came back 1568 px+// wide and clipped the 1600 px #hero (hero-studio#78). So pin an emulated+// viewport instead (it persists across navigations of this session) at 2x,+// which makes the crop 3200x2000, and shoot it below with screenshot_full_res,+// which captures the emulated viewport. resizeTo stays as the fallback for a+// bridge without set_viewport.+const vp = await bridge.call('set_viewport', { sessionId: SESSION, width: 1720, height: 1180, deviceScaleFactor: 2 }, 20000);+const viewportPinned = vp.ok && !answeredError(vp.out + vp.errOut) && /"ok"\s*:\s*true/.test(vp.out + vp.errOut);+if (!viewportPinned) await evalIn('window.resizeTo(1720, 1180)'); await sleep(2000); let tracesReady = false; for (let i = 0; i < 30 && !tracesReady; i++) {@@ -96,20 +106,28 @@ const [bx, by, bw, bh, dpr] = m[1].split(',').map(Number); if (!(bw > 50 && bh > 50)) die('#hero measured degenerate (' + bw + 'x' + bh + ').');  // 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);-if (!shot.ok) die('browser_screenshot failed.');+// (written where the container can read it) or as base64 in the JSON. With+// the viewport pinned, the full-resolution shot is the one that captures it+// whole; any failure there falls back to the plain screenshot.+const readShot = (text) => {+  const p = pngFromReply(text);+  if (p) return p;+  const b64 = text.match(/"(?:data|base64|image|png)"\s*:\s*"([A-Za-z0-9+/=]{200,})"/);+  if (!b64) return null;+  fs.writeFileSync(out + '.full.png', Buffer.from(b64[1], 'base64'));+  return out + '.full.png';+}; let srcPng = null;-const pathMatch = shot.out.match(/[^"\s]+\.png/);-if (pathMatch && fs.existsSync(pathMatch[0])) srcPng = pathMatch[0];+if (viewportPinned) {+  const full = await bridge.call('screenshot_full_res', { sessionId: SESSION }, 45000);+  if (full.ok && !answeredError(full.out + full.errOut)) srcPng = readShot(full.out + full.errOut);+} if (!srcPng) {-  const b64 = shot.out.match(/"(?:data|base64|image|png)"\s*:\s*"([A-Za-z0-9+/=]{200,})"/);-  if (b64) {-    srcPng = out + '.full.png';-    fs.writeFileSync(srcPng, Buffer.from(b64[1], 'base64'));-  }+  const shot = await sh(['browser_screenshot', JSON.stringify({ sessionId: SESSION })], 45000);+  if (!shot.ok) die('browser_screenshot failed.');+  srcPng = readShot(shot.out);+  if (!srcPng) die('browser_screenshot returned neither a readable path nor base64 (raw head: ' + shot.out.slice(0, 200) + ')'); }-if (!srcPng) die('browser_screenshot returned neither a readable path nor base64 (raw head: ' + shot.out.slice(0, 200) + ')');  // 7. verify the sentinel, then crop #hero out (viewport rect * dpr, clamped). // Both checks are HARD failures: a hero that would fail the registry gate
test/render-pup.mjsadded+150
@@ -0,0 +1,150 @@+#!/usr/bin/env node+// The pup render leg against current bridges (hero-studio#78): node test/render-pup.mjs+//+// On a macOS host with pup 3.0.8, Generate failed on the pup leg every time,+// three bugs deep, each hiding the next:+//   1. every successful reply carries "error": "", and three checks treated+//      the bare text '"error"' as a failure ("Adom Desktop did not answer+//      browser_status; the host relay is not reachable from this container");+//   2. pup_screenshot opens its reply with a _cacheHint whose example filename+//      was the first .png in the text, so render-pup read a path that does not+//      exist ("returned neither a readable path nor base64");+//   3. window.resizeTo is ignored by a pup window and pup_screenshot captures+//      only the real window's visible area, 1568 px wide on a MacBook, which+//      clips the 1600 px #hero ("cropped 1568x789, not 16:10 within 0.03").+//+// This needs no Chrome and no desktop. The pure helpers are checked directly;+// then render-pup.mjs runs for real against a stub `adom-bridge` first on+// PATH that answers the way that host did. The real bridge is never called.+import { spawn, execFileSync } from 'child_process';+import fs from 'fs';+import os from 'os';+import path from 'path';+import { fileURLToPath } from 'url';+import { createRequire } from 'module';+import { answeredError, pngFromReply, resolveVerbs, bridgeTrouble } from '../bridge.mjs';++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 : '')); } };++// 1. an empty error is not an error+for (const [text, want] of [+  ['{"ok":true,"error":""}', false], ['{"ok": true, "error": "" }', false], ['{"error":null}', false], ['{"error": false}', false],+  ['{"ok":true}', false], ['{"error":"no such session"}', true], ['{"error": {"code": 3}}', true], ['{"error":true}', true],+]) ok('answeredError(' + text + ') is ' + want, answeredError(text) === want);+ok('bridgeTrouble passes a successful reply with "error": ""', bridgeTrouble({ ok: true, out: '{"ok":true,"error":""}', errOut: '' }) === '');+ok('bridgeTrouble still names a real error', bridgeTrouble({ ok: true, out: '{"ok":false,"error":"no such session"}', errOut: '' }) === 'no such session');++// 2. the screenshot path comes from the reply's fields, not its help text+const real = '/shots/window/2026-11-22T10-26-44.419.png';+const has = (p) => p === real;+const hinted = JSON.stringify({ _cacheHint: 'Pulled screenshots live in /home/adom/project/screenshots/adom-bridge/window/ (bucketed by kind: window, desktop). Filenames are human: <YYYY-MM-DDThh-mm-ss.mmm>[-<hwnd>].png', ok: true, error: '', localSafePath: '/shots/window/small.png', localFullPath: real }, null, 1);+ok('pngFromReply skips the _cacheHint example and reads localFullPath', pngFromReply(hinted, has) === real, String(pngFromReply(hinted, has)));+ok('pngFromReply prefers localFullPath over localSafePath when both exist', pngFromReply(hinted, () => true) === real);+ok('pngFromReply reads a path nested under result', pngFromReply('deprecated: use adom-bridge\n{"ok":true,"result":{"filePath":"' + real + '"}}', has) === real);+ok('pngFromReply falls back to the first .png in the text that exists', pngFromReply('saved `' + real + '` (and a thumbnail /x/missing.png)', has) === real);+ok('pngFromReply answers null when nothing exists', pngFromReply(hinted, () => false) === null);++// 3. the viewport verbs resolve like the rest, per prefix+const v = resolveVerbs('pup_status pup_open_window pup_navigate pup_eval pup_screenshot pup_screenshot_full_res pup_set_viewport');+ok('resolveVerbs maps set_viewport and screenshot_full_res', v.set_viewport === 'pup_set_viewport' && v.screenshot_full_res === 'pup_screenshot_full_res' && v.screenshot === 'pup_screenshot', JSON.stringify(v));+ok('resolveVerbs keeps browser_* names on an older box', resolveVerbs('browser_status browser_screenshot').screenshot === 'browser_screenshot');++// 4. render-pup.mjs end to end against the macOS host's reply shapes+const PY = PLAT.pythonWithPillow();+if (!PY) {+  console.log('  SKIP render-pup end to end: no Python with Pillow, and render-pup.mjs crops with PIL');+} else {+  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hs-render-pup-'));+  const BIN = path.join(tmp, 'bin');+  fs.mkdirSync(BIN);+  const py = (code, ...args) => execFileSync(PY.cmd, [...PY.args, '-c', code, ...args], { stdio: 'pipe' });+  const shotPy = 'import sys\nfrom PIL import Image\nw, h, s = int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])\n' ++    'im = Image.new("RGB", (w, h), (20, 24, 40))\nim.paste((255, 0, 254), (0, 0, s, s))\nim.save(sys.argv[1])\n';+  // what captureVisibleTab gets of a 1450 pt MacBook window: 1568x1076, #hero clipped+  py(shotPy, path.join(BIN, 'visible.png'), '1568', '1076', '16');+  // what the full-res shot gets of the pinned 1720x1180 viewport at 2x+  py(shotPy, path.join(BIN, 'full.png'), '3440', '2360', '32');+  // an older desktop whose window really is 1720x1180 at 1x+  py(shotPy, path.join(BIN, 'roomy.png'), '1720', '1180', '16');+  fs.writeFileSync(path.join(BIN, 'adom-bridge'), `#!/usr/bin/env node+// Stub Adom Bridge for test/render-pup.mjs, replying as pup 3.0.8 on a macOS+// host did (hero-studio#78). STUB_MODE=mac: set_viewport and+// screenshot_full_res exist; old: they do not, and the window is roomy.+const fs = require('fs');+const DIR = __dirname;+const MODE = process.env.STUB_MODE || 'mac';+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 + '\\n');+const pinned = () => fs.existsSync(DIR + '/pinned');+const hint = 'Pulled screenshots live in ' + DIR + '/ (bucketed by kind: window, desktop). Filenames are human: <YYYY-MM-DDThh-mm-ss.mmm>[-<hwnd>].png';+const say = (o) => console.log(JSON.stringify(Object.assign({ ok: true, error: '' }, o), null, 1));+if (verb === 'bridge_list') {+  console.log(MODE === 'mac'+    ? 'pup 3.0.8: pup_status pup_open_window pup_navigate pup_eval pup_screenshot pup_screenshot_full_res pup_set_viewport'+    : 'pup 2.9.0: pup_status pup_open_window pup_navigate pup_eval pup_screenshot');+} else if (verb === 'pup_status') say({ sessions: [] });+else if (verb === 'pup_open_window' || verb === 'pup_navigate') say({ sessionId: args.sessionId });+else if (verb === 'pup_set_viewport' && MODE === 'mac') {+  fs.writeFileSync(DIR + '/pinned', String(args.deviceScaleFactor || 1));+  say({ sessionId: args.sessionId, width: args.width, height: args.height });+} else if (verb === 'pup_screenshot_full_res' && MODE === 'mac') {+  say(pinned() ? { _cacheHint: hint, localFullPath: DIR + '/full.png' } : { _cacheHint: hint, localFullPath: DIR + '/visible.png' });+} else if (verb === 'pup_screenshot') {+  say({ _cacheHint: hint, localSafePath: DIR + (MODE === 'mac' ? '/visible.png' : '/roomy.png') });+} else if (verb === 'pup_eval') {+  const e = String(args.expr || '');+  let result = null;+  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,' + (pinned() ? 2 : 1) + '@XOBSH';+  say({ result });+} else {+  console.log(JSON.stringify({ ok: false, error: 'unknown verb ' + verb }));+  process.exit(1);+}+`);+  fs.chmodSync(path.join(BIN, 'adom-bridge'), 0o755);+  const env = { ...process.env, HOME: tmp, USERPROFILE: tmp, PATH: BIN + path.delimiter + process.env.PATH, ADOM_TARGET: '' };+  delete env.ADOM_AI_THREAD;+  // the temporary HOME would hide a Pillow installed with pip --user+  try { env.PYTHONUSERBASE = env.PYTHONUSERBASE || execFileSync(PY.cmd, [...PY.args, '-m', 'site', '--user-base'], { encoding: 'utf8' }).trim(); } catch {}+  const runLeg = (mode) => new Promise((res) => {+    for (const f of ['pinned', 'calls.log']) { try { fs.unlinkSync(path.join(BIN, f)); } catch {} }+    const outPng = path.join(tmp, 'out-' + mode + '.png');+    const c = spawn(process.execPath, [path.join(ROOT, 'render-pup.mjs'), 'http://127.0.0.1:9/?render=1', outPng],+      { env: { ...env, STUB_MODE: mode }, cwd: ROOT, stdio: ['ignore', 'pipe', 'pipe'] });+    let out = '', err = '';+    c.stdout.on('data', (d) => { out += d; });+    c.stderr.on('data', (d) => { err += d; });+    const t = setTimeout(() => c.kill(), 120000);+    c.on('close', (code) => {+      clearTimeout(t);+      let calls = [];+      try { calls = fs.readFileSync(path.join(BIN, 'calls.log'), 'utf8').trim().split('\n'); } catch {}+      res({ code, out, err, calls, png: fs.existsSync(outPng) ? fs.readFileSync(outPng) : null });+    });+  });+  const size = (buf) => buf && buf.readUInt32BE(0) === 0x89504e47 ? buf.readUInt32BE(16) + 'x' + buf.readUInt32BE(20) : null;+  try {+    const mac = await runLeg('mac');+    ok('macOS host: render-pup succeeds although every reply carries "error": ""', mac.code === 0, (mac.err || mac.out).trim().split('\n').pop());+    ok('macOS host: it pins the viewport and shoots it at full resolution', mac.calls.includes('pup_set_viewport') && mac.calls.includes('pup_screenshot_full_res') && !mac.calls.includes('pup_screenshot'), mac.calls.join(','));+    ok('macOS host: the crop is the whole #hero at 2x, 3200x2000', size(mac.png) === '3200x2000' && /OK .* \(3200x2000 via host browser\)/.test(mac.out), size(mac.png) + ' ' + mac.out.trim());+    const old = await runLeg('old');+    ok('a bridge without set_viewport falls back to resizeTo and the plain screenshot', old.code === 0 && old.calls.includes('pup_screenshot') && !old.calls.includes('pup_screenshot_full_res'), old.calls.join(',') + ' ' + (old.err || '').trim().split('\n').pop());+    ok('the fallback still reads the path past the _cacheHint and crops the 1x #hero, 1600x1000', size(old.png) === '1600x1000', String(size(old.png)) + ' ' + (old.err || '').trim());+  } finally {+    fs.rmSync(tmp, { recursive: true, force: true });+  }+}+console.log('\n' + pass + ' passed, ' + fails.length + ' failed');+process.exit(fails.length ? 1 : 0);