Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

feat(cockpit): show hosted release lag [N26,A2]

Corey Olsonb893d1f52e95
diff --git a/src/cockpit.js b/src/cockpit.js
index 43ca3b8a..d1d51248 100644
--- a/src/cockpit.js
+++ b/src/cockpit.js
@@ -1,9 +1,41 @@
import { effectiveGuards, IN_STATE, MACHINE } from './machine.js';
-import { commandPhrases } from './help.js';
+import { commandPhrases, VERSION } from './help.js';
+import { readFileSync } from 'node:fs';
/** The CLI's default phrases, ordered by depth for the existing prose inventory guard. */
export const PULLBOARD_COMMANDS = Object.freeze(commandPhrases().sort((left, right) => right.split(' ').length - left.split(' ').length));
+let hostedReleaseVersions;
+/** Return every shipped numeric release heading through the package version, including releases without headlines. */
+/**
+ * @param {string} changelog - Shipped changelog contents.
+ * @param {string} [currentVersion] - Highest package release to include.
+ * @returns {string[]} Numeric release versions in ascending order, without duplicates.
+ */
+export function releaseVersionsThrough(changelog, currentVersion = VERSION) {
+ const numeric = (version) => version.split('.').map(Number);
+ const compare = (left, right) => {
+ const a = numeric(left), b = numeric(right);
+ for (let index = 0; index < Math.max(a.length, b.length); index++) {
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
+ if (difference) return difference;
+ }
+ return 0;
+ };
+ return [...new Set([...changelog.matchAll(/^## \[(\d+\.\d+\.\d+)\](?:\s|$)/gmu)].map((match) => match[1]))]
+ .filter((version) => compare(version, currentVersion) <= 0)
+ .sort(compare);
+}
+
+/** Read and cache the shipped release ledger only when a hosted page needs its current version. */
+function shippedHostedReleaseVersions() {
+ if (!hostedReleaseVersions) {
+ const changelog = readFileSync(new URL('../CHANGELOG.md', import.meta.url), 'utf8');
+ hostedReleaseVersions = Object.freeze(releaseVersionsThrough(changelog));
+ }
+ return hostedReleaseVersions;
+}
+
/**
* The item lifecycle as the page draws it (M1): each state with what it means and, for a final
* state, what every way in checks; each move with who makes it, its command or the clock's
@@ -42,10 +74,10 @@ function lifecycle() {
* cannot read a board here and links signIn.
*
* @param {string} [key] - The session's secret.
- * @param {{snapshot?: boolean, readOnly?: boolean, requests?: boolean, transportModule?: string|null, apiBase?: string, apiHeaders?: Record<string, string>, stylesheet?: string, paths?: boolean, hostedLocal?: boolean, relaySession?: boolean, signIn?: string|null}} [options] - Served connection and assets, optional person requests over a read-only transport, host routes, a static page with event replay, or the hosted page that reads this machine's view first.
+ * @param {{snapshot?: boolean, readOnly?: boolean, requests?: boolean, transportModule?: string|null, apiBase?: string, apiHeaders?: Record<string, string>, stylesheet?: string, paths?: boolean, hostedLocal?: boolean, relaySession?: boolean, signIn?: string|null, hostedReleaseVersion?: string, hostedReleaseVersions?: string[]|null}} [options] - Served connection and assets, optional person requests over a read-only transport, host routes, a static page with event replay, or the hosted page that reads this machine's view first.
* @returns {string}
*/
-export function cockpitPage(key = '', { snapshot = false, readOnly = false, requests = false, transportModule = null, apiBase = '', apiHeaders = { 'x-pullboard-key': key }, stylesheet = null, paths = false, hostedLocal = false, relaySession = false, signIn = null } = {}) {
+export function cockpitPage(key = '', { snapshot = false, readOnly = false, requests = false, transportModule = null, apiBase = '', apiHeaders = { 'x-pullboard-key': key }, stylesheet = null, paths = false, hostedLocal = false, relaySession = false, signIn = null, hostedReleaseVersion = VERSION, hostedReleaseVersions: suppliedReleaseVersions = null } = {}) {
// Derive the current CLI inventory for every served, relay or exported page.
const COMMAND_SOURCE = 'pullboard (?:' + commandPhrases().join('|') + ')(?![\\w-])(?: (?:--?[\\w-]+|\\d+|#\\d+|"[^"\\n]*"|[A-Z][A-Z0-9_]*|[\\w-]*[\\/.:@][^\\s"]*|[a-z]+-\\d+)(?![\\w-]))*';
@@ -55,6 +87,8 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ
const requestMode = Boolean(readOnly && requests && !snapshot && transportModule);
if (signIn !== null && (typeof signIn !== 'string' || !signIn.startsWith('/') || signIn.startsWith('//'))) throw new TypeError('signIn must be a path on the hosting site, or null');
const hostedOptions = JSON.stringify({ local: Boolean(hostedLocal) && !snapshot, relaySession: Boolean(relaySession), signIn }).replace(/</g, '\\u003c');
+ const releaseVersions = suppliedReleaseVersions ?? (hostedLocal && !snapshot ? shippedHostedReleaseVersions() : []);
+ const releaseInfo = JSON.stringify({ version: hostedReleaseVersion, versions: releaseVersions }).replace(/</g, '\\u003c');
const css = stylesheet ?? (snapshot ? 'view.css' : transportModule ? '/view.css' : '/view.css?k=' + encodeURIComponent(key));
const cssAttribute = css.replace(/[&<>"']/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]);
return `<!doctype html>
@@ -101,6 +135,9 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ
<p id="local-note-text"></p>
<p id="local-note-links" hidden><a id="local-note-view" href="http://127.0.0.1:4890/local/view">Open the local view</a> <a id="local-note-sign-in" hidden>Sign in to see linked boards</a> <button class="ghost" id="local-note-retry" type="button">Try again</button></p>
</section>
+ <section class="card-panel" id="hosted-release-note" role="status" aria-label="Pullboard update" hidden>
+ <p><span id="hosted-release-text"></span> <code>npm i -g pullboard@latest</code> <a id="hosted-release-link" target="_blank" rel="noopener noreferrer">What changed</a> <button class="ghost" id="hosted-release-dismiss" type="button">Dismiss</button></p>
+ </section>
<section class="card-panel snapshot-controls" id="snapshot-controls" ${snapshot ? '' : 'hidden'} aria-label="Snapshot replay">
<span>Read-only snapshot</span>
<button class="ghost" id="replay-play" type="button">Play from first event</button>
@@ -194,6 +231,7 @@ let transportLoadError = null;
// with the secret in the address's fragment, which no request carries; the page takes it out of the address before
// anything else reads the address, and keeps it for this tab only. Every request then sends it in x-pullboard-key.
const hosted = ${hostedOptions};
+const hostedRelease = ${releaseInfo};
const LOCAL_VIEW = 'http://127.0.0.1:4890';
const LOCAL_TAB = 'pullboard.local.session';
const LOCAL_TRIPS = 'pullboard.local.trips';
@@ -240,6 +278,7 @@ if (hosted.local && !relayPairing) {
}
const snapshotReplay = { final: null, events: [], index: 0, playing: false, timer: null };
const keep = (name, value) => { name = snapshot ? 'snapshot.' + name : name; try { if (value === undefined) return localStorage.getItem(name); localStorage.setItem(name, value); } catch { return null; } return value; };
+const dismissedHostedReleases = new Set();
// Whether the host serves this page at /roadmap as well as at /, so the Roadmap's address is a path;
// anywhere else it is a #roadmap fragment on the page's own address (N38).
const routed = ${JSON.stringify(Boolean(paths) && !snapshot)};
@@ -293,6 +332,30 @@ function localNote(text, ways = false) {
if (hosted.signIn) $('local-note-sign-in').href = hosted.signIn;
}
+/** Count known, shipped release entries between the installed and hosted versions; unknown versions get no guessed count. */
+function hostedReleaseDistance(installed, current, releases) {
+ if (typeof installed !== 'string' || typeof current !== 'string' || !Array.isArray(releases)) return 0;
+ const installedAt = releases.indexOf(installed), currentAt = releases.indexOf(current);
+ return installedAt >= 0 && currentAt > installedAt ? currentAt - installedAt : 0;
+}
+
+/** Show one dismissable update line only after this hosted page has read a known older local release. */
+function renderHostedReleaseNote(project) {
+ const region = $('hosted-release-note');
+ region.hidden = true;
+ const source = project?.releaseNotes ? project : data?.projects?.find((entry) => entry.ok && entry.releaseNotes);
+ if (!hosted.local || !localConfirmed || !localSession || connection.base !== localSession.origin
+ || transportModule || transport || !source?.releaseNotes) return;
+ const installed = source.releaseNotes.version;
+ const distance = hostedReleaseDistance(installed, hostedRelease.version, hostedRelease.versions);
+ if (!distance) return;
+ const dismissedKey = 'pb.hosted-release-dismissed.' + hostedRelease.version;
+ if (dismissedHostedReleases.has(hostedRelease.version) || keep(dismissedKey) === '1') return;
+ $('hosted-release-text').textContent = 'Pullboard ' + installed + ' is installed; ' + hostedRelease.version + ' is current, ' + distance + ' ' + (distance === 1 ? 'release' : 'releases') + ' behind. Update with';
+ $('hosted-release-link').href = 'https://github.com/pullboard-dev/pullboard/blob/main/CHANGELOG.md';
+ region.hidden = false;
+}
+
/** Hide the relay's own banner, which speaks for the relay, on a page the relay does not serve this time. */
function hideRelayNotice() {
const banner = document.getElementById('relay-notice');
@@ -986,6 +1049,7 @@ function boardSummary(board, state) {
const count = (test) => state.items.filter(test).length;
return {
...board, ok: true,
+ releaseNotes: state.releaseNotes,
building: count((item) => item.status === 'claimed'),
awaiting: count((item) => item.status === 'submitted'),
sentBack: count((item) => item.status === 'open' && item.verdict && item.verdict.decision === 'REJECT'),
@@ -1932,6 +1996,7 @@ function render() {
document.querySelectorAll('[data-pane]').forEach((pane) => { pane.hidden = Boolean(group) || pane.dataset.pane !== view.tab; });
$('products').hidden = !p || !p.products.length;
renderReleaseNotes(group ? null : p);
+ renderHostedReleaseNote(p);
renderPersonRequests(p);
renderCredentials();
if (group) { renderGroup(group); return; }
@@ -3135,6 +3200,11 @@ $('upgrade-note').addEventListener('click', (event) => {
if (notice) notice.releases = [];
renderReleaseNotes(data.project);
});
+$('hosted-release-dismiss').addEventListener('click', () => {
+ dismissedHostedReleases.add(hostedRelease.version);
+ keep('pb.hosted-release-dismissed.' + hostedRelease.version, '1');
+ renderHostedReleaseNote(data.project);
+});
$('add-cancel').addEventListener('click', () => { view.adding = false; render(); });
$('spec-decline-cancel').addEventListener('click', () => { closeDecline(); });
$('spec-decline-form').addEventListener('keydown', trapFocus);
diff --git a/test/cockpit/local-origin.test.js b/test/cockpit/local-origin.test.js
index 00cf566c..8f3d91ef 100644
--- a/test/cockpit/local-origin.test.js
+++ b/test/cockpit/local-origin.test.js
@@ -2,11 +2,13 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createServer, request } from 'node:http';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { test } from 'node:test';
import { cockpitPage } from '../../src/cockpit.js';
+import { VERSION } from '../../src/help.js';
+import { createRelayBrowserHandler } from '../../relay/browser-page.js';
import { BIN, machine, project, startView, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, styleOf } from './fixture.js';
const HOSTED = 'https://app.pullboard.dev';
@@ -60,9 +62,9 @@ function onwardOf(page) {
/**
* Stand in for the hosted page at its real origin, and for this machine's default view address. Chrome answers every
* request for https://app.pullboard.dev with the cockpit the relay would serve there and the view's styles. A request
- * for http://127.0.0.1:4890 goes to the view the test runs on its own port, as if that view held the default one, or
- * meets a closed port when the test names none: the suite never binds the machine's 4890, where a person's own view
- * may run. Every other request, to the view's own port, is untouched and meets Chrome's own cross-origin rules.
+ * for http://127.0.0.1:4890 goes to the test view, as if it held the default address, or meets a closed port when the
+ * test names none: the suite never binds the machine's 4890, where a person's own view may run. The view's own state
+ * endpoint is also intercepted for the old-version simulation; its event stream and other requests remain direct.
*/
async function hostedStandIn(chrome, pages, styles, local) {
const failures = [];
@@ -70,36 +72,45 @@ async function hostedStandIn(chrome, pages, styles, local) {
const listener = ({ data }) => {
const message = JSON.parse(String(data));
if (message.method !== 'Fetch.requestPaused') return;
+ const { requestId, resourceType, request: asked } = message.params;
tasks.push((async () => {
- const { requestId, resourceType, request: asked } = message.params;
const address = new URL(asked.url);
- if (address.origin === LOCAL) {
- if (!local.target) return chrome.send('Fetch.failRequest', { requestId, errorReason: 'ConnectionRefused' });
+ const ownState = address.origin === local.own && address.pathname.startsWith('/api/v1/boards/') && address.pathname.endsWith('/state');
+ if (address.origin === LOCAL || ownState) {
+ const target = address.origin === LOCAL ? local.target : (local.relayTarget || local.target);
+ if (!target) return chrome.send('Fetch.failRequest', { requestId, errorReason: 'ConnectionRefused' });
const headers = Object.fromEntries(Object.entries(asked.headers).filter(([name]) => name.toLowerCase() !== 'host'));
- const reply = await call({ base: local.target }, address.pathname + address.search, { method: asked.method, headers, body: asked.postData ?? '' });
+ const reply = await call({ base: target }, address.pathname + address.search, { method: asked.method, headers, body: asked.postData ?? '' });
+ let responseBody = reply.body;
+ if (asked.method === 'GET' && reply.status === 200 && local.versionOverride && address.pathname.startsWith('/api/v1/boards/') && address.pathname.endsWith('/state')) {
+ const document = JSON.parse(responseBody);
+ document.state.releaseNotes.version = local.versionOverride;
+ responseBody = JSON.stringify(document);
+ }
return chrome.send('Fetch.fulfillRequest', {
requestId, responseCode: reply.status,
responseHeaders: Object.entries(reply.headers).filter(([name]) => !['content-length', 'transfer-encoding', 'connection', 'keep-alive', 'date'].includes(name)).map(([name, value]) => ({ name, value: String(value) })),
- body: Buffer.from(reply.body).toString('base64'),
+ body: Buffer.from(responseBody).toString('base64'),
});
}
const document = resourceType === 'Document';
- const page = address.search === '?relay' ? pages.relay : pages.anonymous;
+ const page = pages[address.search.slice(1)] ?? (address.search === '?relay' ? pages.relay : pages.anonymous);
+ const asset = pages.assets?.[address.pathname];
await chrome.send('Fetch.fulfillRequest', {
requestId, responseCode: 200,
responseHeaders: [
- { name: 'Content-Type', value: document ? 'text/html; charset=utf-8' : 'text/css; charset=utf-8' },
+ { name: 'Content-Type', value: document ? 'text/html; charset=utf-8' : address.pathname.endsWith('.js') ? 'text/javascript; charset=utf-8' : 'text/css; charset=utf-8' },
{ name: 'Cache-Control', value: 'no-store' },
// The connections #533's relay page allows, its own origin and the local view's default address, and here the
// test view's own port, which the round trip names.
...(document ? [{ name: 'Content-Security-Policy', value: `connect-src 'self' ${LOCAL} http://localhost:4890 ${local.own}; frame-ancestors 'none'` }] : []),
],
- body: Buffer.from(document ? page : styles).toString('base64'),
+ body: Buffer.from(document ? page : asset ?? styles).toString('base64'),
});
- })().catch((error) => failures.push(error.message)));
+ })().catch((error) => failures.push(`${asked.url} (${resourceType}, ${requestId}): ${error.message}`)));
};
chrome.socket.addEventListener('message', listener);
- await chrome.send('Fetch.enable', { patterns: [{ urlPattern: HOSTED + '/*', requestStage: 'Request' }, { urlPattern: LOCAL + '/*', requestStage: 'Request' }] });
+ await chrome.send('Fetch.enable', { patterns: [{ urlPattern: HOSTED + '/*', requestStage: 'Request' }, { urlPattern: LOCAL + '/*', requestStage: 'Request' }, { urlPattern: local.own + '/api/v1/boards/*/state*', requestStage: 'Request' }] });
return async () => {
chrome.socket.removeEventListener('message', listener);
try { await Promise.all(tasks); } finally { await chrome.send('Fetch.disable'); }
@@ -235,6 +246,157 @@ test('a pullboard.dev page reads the local board [N26,A2]', { timeout: 120_000 }
}
});
+test('the hosted page says how far behind this machine\'s Pullboard is [N26,A2]', { timeout: 120_000 }, async (t) => {
+ const executable = chromeExecutable();
+ assert.ok(executable, 'the hosted version notice needs real Chrome');
+ const box = machine();
+ const board = project(box, 'hosted-release');
+ box.run(board.repo, 'add', 'web', 'A board on an older Pullboard release', '--specs', 'G1');
+ const profile = mkdtempSync(join(tmpdir(), 'pullboard-release-lag-'));
+ let view, chrome, stopStandIn;
+ try {
+ view = await startView(box);
+ const local = { own: view.base, target: view.base, versionOverride: '0.8.20' };
+ chrome = await openSnapshotChrome(executable, 'about:blank', profile);
+ for (const permissions of [['loopbackNetwork', 'localNetwork', 'localNetworkAccess'], ['localNetworkAccess']]) {
+ try { await chrome.send('Browser.grantPermissions', { origin: HOSTED, permissions }); break; } catch { /* Chrome versions expose different permission names */ }
+ }
+ const changelog = readFileSync(new URL('../../CHANGELOG.md', import.meta.url), 'utf8');
+ const versionOrder = (version) => version.split('.').map(Number);
+ const compareVersions = (left, right) => {
+ const a = versionOrder(left), b = versionOrder(right);
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
+ };
+ const releaseVersions = [...new Set([...changelog.matchAll(/^## \[(\d+\.\d+\.\d+)\](?:\s|$)/gmu)].map((match) => match[1]))]
+ .filter((version) => compareVersions(version, VERSION) <= 0)
+ .sort(compareVersions);
+ /** Ask the production authenticated relay route to render its default hosted release page. */
+ const handler = createRelayBrowserHandler({ authenticate: async () => ({ kind: 'session' }) });
+ let productionPage = '';
+ let productionHeaders = {};
+ const response = { writeHead(_status, headers) { productionHeaders = headers; }, end(content) { productionPage = String(content); } };
+ assert.equal(await handler({ method: 'GET', url: '/', headers: {} }, response), true, 'the production relay route serves its authenticated page');
+ assert.match(productionHeaders['content-security-policy'], /connect-src[^;]*http:\/\/127\.0\.0\.1:4890[^;]*http:\/\/localhost:4890/u,
+ 'the production hosted page policy permits its local-view read');
+ /** Render the production hosted page for one release target, using only release entries shipped in this package. */
+ const pageFor = (version) => cockpitPage('', {
+ readOnly: true, requests: true, transportModule: '/relay/client.js', apiHeaders: {}, stylesheet: '/view.css',
+ hostedLocal: true, relaySession: true, signIn: '/auth/github/start', hostedReleaseVersion: version, hostedReleaseVersions: releaseVersions,
+ }).replace('<main>', '<main><section class="card-panel" id="relay-notice" role="status"><p>Pairing this browser…</p></section>');
+ let activePage = pageFor('0.8.21');
+ stopStandIn = await hostedStandIn(chrome, { get anonymous() { return activePage; }, get relay() { return activePage; } }, await styleOf(view), local);
+ const bannerText = () => chrome.stable("document.querySelector('#hosted-release-text')?.textContent || ''");
+ const bannerHidden = () => chrome.stable("document.querySelector('#hosted-release-note')?.hidden ?? true");
+ let visit = 0;
+ let visitPreload;
+ const open = async (version, production = false) => {
+ activePage = production ? productionPage : pageFor(version);
+ if (visitPreload) await chrome.send('Page.removeScriptToEvaluateOnNewDocument', { identifier: visitPreload });
+ const marker = ++visit;
+ const installed = await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: `window.__releaseVisit = ${marker};` });
+ visitPreload = installed.identifier;
+ await chrome.send('Page.navigate', { url: HOSTED + '/' });
+ await chrome.waitFor(`window.__releaseVisit === ${marker} && document.readyState === 'complete' && data?.project?.releaseNotes?.version === ${JSON.stringify(local.versionOverride)} && document.querySelector('#chain')?.textContent.includes('A board on an older Pullboard release')`, 25_000); // budget: hang ceiling for this navigation to finish the local state read before the next visit; no throughput claim.
+ };
+
+ // 0.8.21 is a shipped release in CHANGELOG.md, one actual release after the local 0.8.20 install.
+ await open('0.8.21');
+ assert.match(await bannerText(), /Pullboard 0\.8\.20 is installed; 0\.8\.21 is current, 1 release behind/u);
+ assert.equal(await chrome.stable("document.querySelector('#hosted-release-note code')?.textContent"), 'npm i -g pullboard@latest');
+ assert.equal(await chrome.stable("document.querySelector('#hosted-release-link')?.href"), 'https://github.com/pullboard-dev/pullboard/blob/main/CHANGELOG.md');
+ await chrome.click("document.querySelector('#hosted-release-dismiss')");
+ assert.equal(await bannerHidden(), true, 'dismiss hides the note for its current target release');
+ await open('0.8.21');
+ assert.equal(await bannerHidden(), true, 'the same target release stays dismissed after reload');
+
+ // The next shipped version gets its own dismissal key and its release count comes from actual release entries.
+ await open(VERSION, true);
+ const releasesBehind = releaseVersions.indexOf(VERSION) - releaseVersions.indexOf('0.8.20');
+ assert.ok(releasesBehind > 0, 'the hosted package has shipped releases after the simulated older install');
+ assert.equal(await bannerText(), `Pullboard 0.8.20 is installed; ${VERSION} is current, ${releasesBehind} ${releasesBehind === 1 ? 'release' : 'releases'} behind. Update with`);
+ assert.equal(await bannerHidden(), false, 'a new target release brings the note back');
+
+ // The production-generated page counts every numeric release heading, including 0.8.4's section with no headline.
+ local.versionOverride = '0.8.4';
+ await open(VERSION, true);
+ const legacyReleasesBehind = releaseVersions.indexOf(VERSION) - releaseVersions.indexOf('0.8.4');
+ assert.ok(legacyReleasesBehind > releasesBehind, 'the full shipped heading list includes releases without headlines');
+ assert.equal(await bannerText(), `Pullboard 0.8.4 is installed; ${VERSION} is current, ${legacyReleasesBehind} releases behind. Update with`);
+
+ local.versionOverride = VERSION;
+ await open(VERSION, true);
+ assert.equal(await bannerHidden(), true, 'matching local and hosted releases show no note');
+
+ local.versionOverride = '0.8.22-rc.1';
+ await open(VERSION);
+ assert.equal(await bannerHidden(), true, 'an unlisted prerelease does not get a guessed release count');
+ local.versionOverride = '0.8.23';
+ await open('0.8.21');
+ assert.equal(await bannerHidden(), true, 'a local version newer than this hosted page does not get a false warning');
+ assert.deepEqual(chrome.exceptions, [], 'Chrome reports no uncaught page exceptions');
+ } finally {
+ try { if (stopStandIn) await stopStandIn(); }
+ finally {
+ try { if (chrome) await closeSnapshotChrome(chrome); }
+ finally {
+ try { if (view) await view.stop(); }
+ finally { rmSync(profile, { recursive: true, force: true }); }
+ }
+ }
+ }
+});
+
+test('the hosted relay never treats a remote board version as this machine\'s version [N26,A2]', { timeout: 120_000 }, async (t) => {
+ const executable = chromeExecutable();
+ assert.ok(executable, 'the relay fallback version guard needs real Chrome');
+ const box = machine();
+ const board = project(box, 'hosted-relay-release');
+ box.run(board.repo, 'add', 'web', 'A board read through the relay transport', '--specs', 'G1');
+ const profile = mkdtempSync(join(tmpdir(), 'pullboard-relay-release-'));
+ let view, chrome, stopStandIn;
+ try {
+ view = await startView(box);
+ chrome = await openSnapshotChrome(executable, 'about:blank', profile);
+ for (const permissions of [['loopbackNetwork', 'localNetwork', 'localNetworkAccess'], ['localNetworkAccess']]) {
+ try { await chrome.send('Browser.grantPermissions', { origin: HOSTED, permissions }); break; } catch { /* Chrome versions expose different permission names */ }
+ }
+ /** The relay page uses an authorized read-only transport backed by this real view's public API. */
+ const transportSource = `export async function createTransport() {
+ return { async request(path) {
+ const response = await fetch(${JSON.stringify(view.base)} + path, { headers: { 'x-pullboard-key': ${JSON.stringify(view.key)} } });
+ const document = await response.json();
+ if (!response.ok) throw new Error(document.error?.message || String(response.status));
+ return document;
+ } };
+ }`;
+ const handler = createRelayBrowserHandler({ authenticate: async () => ({ kind: 'session' }) });
+ let relayPage = '';
+ const response = { writeHead() {}, end(content) { relayPage = String(content); } };
+ assert.equal(await handler({ method: 'GET', url: '/', headers: {} }, response), true, 'the production relay handler supplies the fallback page');
+ stopStandIn = await hostedStandIn(chrome, {
+ anonymous: relayPage, relay: relayPage, assets: { '/relay/client.js': transportSource },
+ }, await styleOf(view), { own: view.base, target: null, relayTarget: view.base, versionOverride: '0.8.20' });
+ const relayVisit = '?relay-release-visit=1';
+ await chrome.send('Page.navigate', { url: HOSTED + '/' + relayVisit });
+ await chrome.waitFor(`location.search === ${JSON.stringify(relayVisit)} && document.readyState === 'complete' && data?.project?.releaseNotes?.version === '0.8.20' && document.querySelector('#chain')?.textContent.includes('A board read through the relay transport')`, 25_000); // budget: hang ceiling for this navigation to finish the relayed state read; no throughput claim.
+ assert.equal(await chrome.stable("data.project.releaseNotes.version"), '0.8.20', 'the relayed API state carries its simulated remote install version');
+ assert.equal(await chrome.stable("hosted.local && !localSession && connection.base === '' && !!transport && transportModule === '/relay/client.js' && localConfirmed === false"), true,
+ 'local discovery failed, so the board remains on the relay transport without a confirmed local session');
+ assert.equal(await chrome.stable("document.querySelector('#hosted-release-note').hidden"), true,
+ 'remote board metadata does not describe this machine’s installed version');
+ assert.deepEqual(chrome.exceptions, [], 'Chrome reports no uncaught relay fallback exceptions');
+ } finally {
+ try { if (stopStandIn) await stopStandIn(); }
+ finally {
+ try { if (chrome) await closeSnapshotChrome(chrome); }
+ finally {
+ try { if (view) await view.stop(); }
+ finally { rmSync(profile, { recursive: true, force: true }); }
+ }
+ }
+ }
+});
+
test('a foreign origin or wrong Host is refused by the local view [N26,A2]', { timeout: 60_000 }, async () => { // budget: hang ceiling for one real view and a few local requests.
const box = machine();
project(box, 'local-origin-refusals');