master
Drew Owens pup render leg on current bridges: empty error, real screenshot path, full #hero (#78) a83d6e7
#!/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);