master
Colby Knox Full test suite in the page repo: npm test runs here (the published package carries only test/brand.mjs) 625499c
#!/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);