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.

fix(view): a phone never waits without a deadline at startup [N26,H5]

Corey Olsonba783c40d150
diff --git a/src/cockpit.js b/src/cockpit.js
index db5a4653..ec8411b2 100644
--- a/src/cockpit.js
+++ b/src/cockpit.js
@@ -22,6 +22,10 @@ import {
hostedState,
} from './view/hosted.js';
import { staleChip } from './view/stale.js';
+import {
+ pageStartup,
+ validLocalSession,
+} from './view/page-startup.js';
import {
roadmapHeaders,
roadmapSummary,
@@ -256,14 +260,8 @@ function tabValue(name, value) {
} catch { return null; }
return value;
}
-/** Whether a value is a local session this page may use: version 1, a loopback origin with its port, and a secret. */
-function validLocalSession(value) {
- if (!value || value.version !== 1 || typeof value.key !== 'string' || !/^[\\x21-\\x7e]{1,256}$/.test(value.key) || typeof value.origin !== 'string') return false;
- try {
- const address = new URL(value.origin);
- return address.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(address.hostname) && address.port !== '' && address.origin === value.origin;
- } catch { return false; }
-}
+const validLocalSession = (${validLocalSession.toString()});
+const pageStartup = (${pageStartup.toString()});
// A relay pairing link carries its own fragment; that load stays the relay's, as before.
const relayPairing = hosted.local && ['board', 'key', 'device'].some((name) => new URLSearchParams(location.hash.slice(1)).has(name));
if (hosted.local && !relayPairing) {
@@ -434,6 +432,8 @@ let localReached = false;
* computer, so a later screen, such as signing in, stays.
*/
async function connectLocal(again = false) {
+ // A phone never runs Pullboard: it is unreachable at once, before a permission query or a fetch can wait (#900).
+ if (pageStartup(document.documentElement).phone) return 'unreachable';
if (localChecking) return 'busy';
localChecking = true;
try { return await lookLocal(again); }
@@ -3949,7 +3949,7 @@ let transportLoading = null;
async function loadTransport() {
if (transport) return transport;
if (!transportLoading) transportLoading = (async () => {
- const module = await import(configuredTransportModule);
+ const module = await pageStartup(document.documentElement).within(() => import(configuredTransportModule), 15_000, 'The relay client did not load within 15 seconds.');
if (typeof module.createTransport !== 'function') throw new Error('The browser transport must export createTransport({ onUpdate }).');
const configured = await module.createTransport({
onUpdate: () => transport ? refresh().catch((error) => { $('live').textContent = 'offline: ' + error.message; }) : Promise.resolve(),
@@ -3961,7 +3961,7 @@ async function loadTransport() {
return transport;
})();
try { return await transportLoading; }
- catch (error) { transportLoadError = error; throw error; }
+ catch (error) { transportLoadError = error; pageStartup(document.documentElement).say(error.message + ' Check your connection, then reload this page.'); throw error; }
finally { transportLoading = null; }
}
diff --git a/src/view/page-startup.js b/src/view/page-startup.js
new file mode 100644
index 00000000..9c23181d
--- /dev/null
+++ b/src/view/page-startup.js
@@ -0,0 +1,41 @@
+/**
+ * The hosted page's startup helpers. src/cockpit.js embeds each one's source text in the page, so each may use only
+ * its arguments and browser globals.
+ */
+
+/** Whether a value is a local session this page may use: version 1, a loopback origin with its port, and a secret. */
+export function validLocalSession(value) {
+ if (!value || value.version !== 1 || typeof value.key !== 'string' || !/^[\x21-\x7e]{1,256}$/.test(value.key) || typeof value.origin !== 'string') return false;
+ try {
+ const address = new URL(value.origin);
+ return address.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(address.hostname) && address.port !== '' && address.origin === value.origin;
+ } catch { return false; }
+}
+
+/**
+ * What the page's startup needs to know about this device, and its two safeguards (#900). A phone never runs
+ * Pullboard, so it never looks for this computer's view, and its relay shell is its only screen, so a startup failure
+ * is said there. No startup wait goes without a deadline.
+ *
+ * @param {HTMLElement} root - The document's root element, which the relay's page marks as a phone before first paint.
+ */
+export function pageStartup(root) {
+ const phone = root.dataset.relayDevice === 'phone';
+ return {
+ phone,
+ /** Put text in the phone shell's status line and keep the shell showing; false on a computer or without a shell. */
+ say(text) {
+ const status = phone ? root.querySelector('#relay-screen .relay-live span') : null;
+ if (!status) return false;
+ root.dataset.relayScreen ||= 'share';
+ status.textContent = text;
+ return true;
+ },
+ /** Await load(), failing with message after ms; the timer is cleared either way, so it never outlives the load. */
+ within(load, ms, message) {
+ let timer;
+ const late = new Promise((resolve, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); });
+ return Promise.race([load(), late]).finally(() => clearTimeout(timer));
+ },
+ };
+}
diff --git a/test/cockpit/local-origin.test.js b/test/cockpit/local-origin.test.js
index 5bbb28b6..92f8fd1b 100644
--- a/test/cockpit/local-origin.test.js
+++ b/test/cockpit/local-origin.test.js
@@ -921,3 +921,73 @@ test('the local view hands its secret only to the hosted page [N26,A2]', { timeo
await view.stop();
}
});
+
+test('a phone never waits without a deadline at startup [N26,H5]', { timeout: 90_000 }, async () => { // budget: hang ceiling for two hosted loads in Chrome, one waiting out the 15-second transport deadline.
+ const executable = chromeExecutable();
+ assert.ok(executable, 'the phone startup check needs real Chrome');
+ const profile = mkdtempSync(join(tmpdir(), 'pullboard-phone-startup-'));
+ const relay = createRelayBrowserHandler({ authenticate: async () => ({ kind: 'session' }) });
+ // The relay client fails at once (fail) or never answers (stall); this computer's view is counted and refused.
+ const stand = { client: 'fail', local: 0, held: [] };
+ let chrome, listener;
+ const failures = [];
+ try {
+ chrome = await openSnapshotChrome(executable, 'about:blank', profile);
+ listener = ({ data }) => {
+ const message = JSON.parse(String(data));
+ if (message.method !== 'Fetch.requestPaused') return;
+ const { requestId, request: asked } = message.params;
+ const address = new URL(asked.url);
+ (async () => {
+ if (address.origin === LOCAL) { stand.local += 1; return chrome.send('Fetch.failRequest', { requestId, errorReason: 'ConnectionRefused' }); }
+ if (address.pathname === '/relay/client.js') {
+ if (stand.client === 'stall') { stand.held.push(requestId); return; }
+ return chrome.send('Fetch.fulfillRequest', { requestId, responseCode: 500, responseHeaders: [{ name: 'Content-Type', value: 'text/plain' }], body: '' });
+ }
+ let head = {}, body = '';
+ const handled = await relay({ method: 'GET', url: address.pathname, headers: {} }, { writeHead: (status, headers) => { head = headers; }, end: (content) => { body = content ?? ''; } });
+ if (!handled) return chrome.send('Fetch.failRequest', { requestId, errorReason: 'Failed' });
+ return chrome.send('Fetch.fulfillRequest', { requestId, responseCode: 200, responseHeaders: Object.entries(head).map(([name, value]) => ({ name, value: String(value) })), body: Buffer.from(body).toString('base64') });
+ })().catch((error) => failures.push(error.message));
+ };
+ chrome.socket.addEventListener('message', listener);
+ await chrome.send('Fetch.enable', { patterns: [{ urlPattern: HOSTED + '/*', requestStage: 'Request' }, { urlPattern: LOCAL + '/*', requestStage: 'Request' }] });
+ // A phone, as the relay's page tells it (a coarse pointer and no hover), whose local-network permission asks are counted.
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: `(() => {
+ if (location.origin !== ${JSON.stringify(HOSTED)}) return;
+ const media = window.matchMedia.bind(window);
+ window.matchMedia = (query) => /pointer: coarse|hover: none/.test(query) ? { matches: true, media: query, addEventListener() {}, removeEventListener() {} } : media(query);
+ window.__permissionQueries = 0;
+ const query = navigator.permissions.query.bind(navigator.permissions);
+ navigator.permissions.query = (asked) => { window.__permissionQueries += 1; return query(asked); };
+ })()` });
+ const shell = `JSON.stringify({ device: document.documentElement.dataset.relayDevice, screen: document.documentElement.dataset.relayScreen,
+ line: document.querySelector('#relay-screen .relay-live span')?.textContent ?? null,
+ shown: (document.getElementById('relay-screen')?.getClientRects().length ?? 0) > 0, queries: window.__permissionQueries })`;
+
+ // A relay client that fails to load says so in the phone shell, and the page never looked for this computer.
+ await chrome.send('Page.navigate', { url: HOSTED + '/' });
+ await chrome.waitFor("document.querySelector('#relay-screen .relay-live span')?.textContent.includes('Check your connection')", 10_000); // budget: a failed import shows its guidance at once; ceiling for a loaded machine.
+ const failed = JSON.parse(await chrome.stable(shell));
+ assert.equal(failed.device, 'phone', 'the relay page took this browser for a phone');
+ assert.equal(failed.shown, true, 'the phone shell stays on screen');
+ assert.match(failed.line, /Failed to fetch dynamically imported module/, 'the shell names the failed load');
+ assert.equal(failed.queries, 0, 'a phone never asks for local-network permission');
+ assert.equal(stand.local, 0, 'a phone never requests this computer\'s view');
+
+ // A relay client that never answers is bounded: the phone shell says so once its 15-second deadline passes, and
+ // only that deadline writes this line, so it is the deadline that ended the wait.
+ stand.client = 'stall';
+ await chrome.send('Page.navigate', { url: HOSTED + '/' });
+ await chrome.waitFor("document.querySelector('#relay-screen .relay-live span')?.textContent.includes('did not load within 15 seconds')", 30_000); // budget: the page's 15-second import deadline plus a load ceiling.
+ const stalled = JSON.parse(await chrome.stable(shell));
+ assert.equal(stalled.shown, true, 'the phone shell stays on screen while the client never answers');
+ assert.equal(stalled.queries, 0);
+ assert.equal(stand.local, 0);
+ assert.ok(stand.held.length > 0, 'the stalled client request really was held');
+ assert.deepEqual(failures, []);
+ } finally {
+ try { if (chrome) { if (listener) chrome.socket.removeEventListener('message', listener); await closeSnapshotChrome(chrome); } }
+ finally { rmSync(profile, { recursive: true, force: true }); }
+ }
+});