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(relay): let phone boards render before approvals [H5,H16,H17]

Corey Olsone829f6c18535
diff --git a/relay/browser-approval-card.js b/relay/browser-approval-card.js
index 12da6043..8087ea88 100644
--- a/relay/browser-approval-card.js
+++ b/relay/browser-approval-card.js
@@ -35,9 +35,33 @@ export function deletedText(names) {
/** Card spacing for the relay page; served after the shared view styles. */
export const APPROVAL_CARD_STYLES = `
+#phone-approvals:empty { display: none; }
+.phone-approval-status { margin: 0; padding: 14px 16px; color: var(--ink-muted); }
.phone-approval { display: grid; gap: 10px; padding: 14px 16px; }
.phone-approval p { margin: 0; overflow-wrap: anywhere; }
.phone-approval-title { font-weight: 600; }
.phone-approval-detail { color: var(--ink-muted); }
.phone-approval button { justify-self: start; }
`;
+
+/** Show the requests feed's own progress without making it a prerequisite for reading a board. */
+export function phoneApprovalStatus(doc, message) {
+ let panel = doc.getElementById('phone-approvals');
+ if (!panel && message) {
+ const main = doc.querySelector('main');
+ if (!main) return null;
+ panel = doc.createElement('section');
+ panel.id = 'phone-approvals'; panel.className = 'card-panel';
+ panel.setAttribute('aria-label', 'Requests from your computer');
+ main.prepend(panel);
+ }
+ if (!panel) return null;
+ let status = panel.querySelector('.phone-approval-status');
+ if (!message) { status?.remove(); return panel; }
+ if (!status) {
+ status = doc.createElement('p'); status.className = 'phone-approval-status';
+ status.setAttribute('role', 'status'); panel.prepend(status);
+ }
+ status.textContent = message;
+ return panel;
+}
diff --git a/relay/browser-client.js b/relay/browser-client.js
index a6e067ec..6df52fcb 100644
--- a/relay/browser-client.js
+++ b/relay/browser-client.js
@@ -8,6 +8,8 @@ import { Refused } from './refused.js';
import { enqueueStream, followStream } from './browser-stream.js';
import { homeLineDismissed, homeScreenLine, noticeLines, nothingShared, rememberOwnedRequestId, showRelayScreen, storedOwnedRequestState } from './browser-notice.js';
import { registerApp, requestPairingPersistence } from './install.js';
+import { browserJSON, withBrowserDeadline } from './browser-deadline.js';
+import { phoneApprovalStatus } from './browser-approval-card.js';
const KEYS = 'pullboard.relay.keys.v1';
const PENDING = 'pullboard.relay.pair.v1';
@@ -59,7 +61,7 @@ async function snapshotDocument(plain) {
if (typeof DecompressionStream !== 'function') throw new Error('This browser cannot read gzip snapshots. Upgrade the browser client.');
try {
const stream = new Blob([plain]).stream().pipeThrough(new DecompressionStream('gzip'));
- return JSON.parse(await new Response(stream).text());
+ return JSON.parse(await withBrowserDeadline(() => new Response(stream).text()));
} catch { throw new Refused('SNAPSHOT_FORMAT', 'The sealed gzip snapshot is invalid. Refresh it from a linked machine.'); }
}
if (plain[0] !== 0x7b) {
@@ -82,8 +84,7 @@ async function checkAuthorization(path, status, onDenied, error) {
async function documentAt(path, onDenied, options = {}) {
const headers = new Headers(options.headers ?? {});
headers.set('x-pullboard-engine', String(ENGINE_VERSION));
- const response = await fetch(path, { ...options, headers, credentials: 'same-origin', cache: 'no-store', redirect: 'error' });
- const document = await response.json();
+ const { response, document } = await browserJSON(path, { ...options, headers, credentials: 'same-origin', cache: 'no-store', redirect: 'error' });
if (!response.ok) {
const error = document.error;
await checkAuthorization(path, response.status, onDenied, error);
@@ -95,7 +96,7 @@ async function documentAt(path, onDenied, options = {}) {
}
/** Build the API adapter the existing cockpit consumes; no board key enters an HTTP request. */
-export async function createTransport({ onUpdate = () => {}, onOpenBoard = () => {} } = {}) {
+export async function createTransport({ onUpdate = () => {}, onOpenBoard = () => {}, waitForRender = false } = {}) {
void registerApp();
const savedKeys = stored(localStorage, KEYS, {});
const keys = savedKeys && typeof savedKeys === 'object' && !Array.isArray(savedKeys) ? savedKeys : {};
@@ -110,6 +111,8 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
let accessError = null;
const access = new AbortController();
let persistenceRequest = null;
+ // New viewers acknowledge their first actual render; old viewers retain the prior transition contract.
+ let rendered = waitForRender !== true;
rememberPairing();
let pair = takePairing() ?? stored(sessionStorage, PENDING, null);
if (pair && (!BOARD.test(pair.board ?? '') || typeof pair.key !== 'string')) pair = null;
@@ -177,7 +180,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
}
// A phone has no local-view screen to fall back to: keep its shell and the real reason until a board is readable.
const root = document.documentElement;
- const phoneWaiting = root.dataset.relayDevice === 'phone' && paired.size === 0;
+ const phoneWaiting = root.dataset.relayDevice === 'phone' && (!rendered || paired.size === 0);
showRelayScreen(root, phoneWaiting || nothingShared({ paired, waitingBoards, failure }) ? 'share' : null,
phoneWaiting && (failure || waitingBoards.size) ? lines.join(' ') : '');
}
@@ -215,12 +218,11 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
/** Authenticate the latest native snapshot before installing its presentation in this device. */
async function snapshot(entry) {
- const response = await fetch('/api/v1/boards/' + entry.id + '/state', {
+ const { response, document } = await browserJSON('/api/v1/boards/' + entry.id + '/state', {
credentials: 'same-origin', cache: 'no-store', redirect: 'error',
headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(entry.state && entry.snapshotTag ? { 'if-none-match': entry.snapshotTag } : {}) },
});
if (response.status === 304 && entry.state) return;
- const document = await response.json();
if (!response.ok) {
await checkAuthorization('/api/v1/boards/' + entry.id + '/state', response.status, denied, document.error);
if (document.error?.code === 'NO_BOARD' || document.error?.code === 'NO_SNAPSHOT') waitForFirstSnapshot(entry);
@@ -230,7 +232,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
const row = document.state;
if (!row || !Number.isSafeInteger(row.sequence) || row.sequence < 0) throw new Error('The relay snapshot cursor is invalid. Refresh this board.');
warning(row.warning, entry.id);
- const plain = await unseal(entry.key, transportBytes(row.sealed), { boardId: entry.id, kind: 'snapshot', sequence: row.sequence });
+ const plain = await withBrowserDeadline(() => unseal(entry.key, transportBytes(row.sealed), { boardId: entry.id, kind: 'snapshot', sequence: row.sequence }));
const value = await snapshotDocument(plain);
const state = snapshotState(value, entry.id);
if (accessLost) throw new Error('Sign in again to read this board.');
@@ -263,7 +265,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
if (row.event_id <= entry.cursor) return;
if (row.event_id !== entry.cursor + 1) throw new Error('The relay event prefix is incomplete. Refresh this board.');
}
- const plain = await unseal(entry.key, transportBytes(row.sealed), { boardId: entry.id, kind: row.kind, sequence: row.event_id });
+ const plain = await withBrowserDeadline(() => unseal(entry.key, transportBytes(row.sealed), { boardId: entry.id, kind: row.kind, sequence: row.event_id }));
const move = JSON.parse(new TextDecoder().decode(plain));
if (accessLost) throw new Error('Sign in again to read this board.');
if (row.kind === 'request') {
@@ -430,7 +432,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
waitForFirstSnapshot({ id: board.id, repository: board.repository });
continue;
}
- failure = ['ENGINE_VERSION', 'RELAY_ENGINE_VERSION'].includes(error.code) || /^\[(?:ENGINE_VERSION|RELAY_ENGINE_VERSION)\]/u.test(error.message)
+ failure = ['ENGINE_VERSION', 'RELAY_ENGINE_VERSION', 'RELAY_UNAVAILABLE', 'DEVICE_STORAGE'].includes(error.code) || /^\[(?:ENGINE_VERSION|RELAY_ENGINE_VERSION)\]/u.test(error.message)
? error.message
: 'Could not open this board with its saved key. Pair this browser again from a linked machine.';
failureBoard = board.id;
@@ -508,7 +510,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
/** Seal an unchanged intent at its current public sequence after another client wins the order. */
async function requestEnvelope(entry, value, sequence) {
- const bytes = await seal(entry.key, new TextEncoder().encode(JSON.stringify(value)), { boardId: entry.id, kind: 'request', sequence });
+ const bytes = await withBrowserDeadline(() => seal(entry.key, new TextEncoder().encode(JSON.stringify(value)), { boardId: entry.id, kind: 'request', sequence }));
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return { id: value.id, sequence, sealed: btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '') };
@@ -518,7 +520,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
async function sendOutbox(entry) {
const pending = entry.outbox;
if (!pending) return null;
- const plain = await unseal(entry.key, transportBytes(pending.sealed), { boardId: entry.id, kind: 'request', sequence: pending.sequence });
+ const plain = await withBrowserDeadline(() => unseal(entry.key, transportBytes(pending.sealed), { boardId: entry.id, kind: 'request', sequence: pending.sequence }));
const value = validatePersonRequest(JSON.parse(new TextDecoder().decode(plain)));
if (value.id !== pending.id) throw new Refused('REQUEST_STORAGE', 'The saved request is inconsistent. Pair this browser again.');
for (let attempt = 0; attempt < 5; attempt += 1) {
@@ -586,10 +588,22 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>
let devicePairing = /(?:^#|&)device=/u.test(location.hash);
try { devicePairing ||= sessionStorage.getItem('pullboard.relay.device-pair.v1') !== null; } catch { /* No storage: no saved pairing. */ }
if (!pair && !devicePairing && !Object.keys(keys).length) showRelayScreen(document.documentElement, 'share');
- if (await enrollPhone((path, options) => documentAt(path, denied, options))) keepPairingStorage();
- await listing();
- await installPhoneApprovals((path, options) => documentAt(path, denied, options), keys, openApprovedBoard, access.signal);
+ try {
+ if (await enrollPhone((path, options) => documentAt(path, denied, options))) keepPairingStorage();
+ await listing();
+ } catch (error) {
+ failure = error.message || 'Your boards did not open. Try opening this page again.';
+ notice();
+ throw error;
+ }
+ // Requests are a separate background feed, not a prerequisite for handing a readable board to the cockpit.
+ void installPhoneApprovals((path, options) => documentAt(path, denied, { ...options, signal: access.signal }),
+ keys, openApprovedBoard, access.signal).catch(() => {
+ if (!accessLost) phoneApprovalStatus(document, 'Requests from your computer did not load. Open this page again to retry.');
+ });
return {
+ /** Give the startup frame back only after an opted-in viewer has drawn a readable board. */
+ didRender() { rendered = true; notice(); },
/** Return decoded API state or seal narrow person intent; no board key or plaintext leaves the device. */
async request(path, body) {
if (accessLost) throw accessError;
diff --git a/relay/browser-deadline.js b/relay/browser-deadline.js
new file mode 100644
index 00000000..759c0cec
--- /dev/null
+++ b/relay/browser-deadline.js
@@ -0,0 +1,49 @@
+/** Bound browser I/O independently of the first-paint promise [H5,H16,H17]. */
+import { Refused } from '../src/refused.js';
+
+// Budget: the existing snapshot catch-up window also bounds one browser I/O operation; first paint remains independent.
+export const BROWSER_IO_TIMEOUT_MS = 15_000;
+
+/**
+ * Reject even when a browser API ignores cancellation, and cancel any work that accepts a signal.
+ * Late results cannot resume the caller after its deadline. Optional parent cancellation retains
+ * its original reason, while a timeout supplies actionable guidance rather than private state.
+ */
+export async function withBrowserDeadline(work, {
+ timeoutMs = BROWSER_IO_TIMEOUT_MS, signal, code = 'RELAY_UNAVAILABLE',
+ message = 'This read did not answer. Open your boards again in a moment.',
+} = {}) {
+ const controller = new AbortController();
+ let timer;
+ let cancel;
+ try {
+ return await new Promise((resolve, reject) => {
+ cancel = () => {
+ const error = signal.reason ?? new Refused(code, message);
+ controller.abort(error);
+ reject(error);
+ };
+ if (signal?.aborted) { cancel(); return; }
+ signal?.addEventListener('abort', cancel, { once: true });
+ timer = setTimeout(() => {
+ const error = new Refused(code, message);
+ controller.abort(error);
+ reject(error);
+ }, timeoutMs);
+ Promise.resolve().then(() => work(controller.signal)).then(resolve, reject);
+ });
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', cancel);
+ }
+}
+
+/** Keep the response headers and JSON body under one deadline, including a stalled response body. */
+export function browserJSON(path, options = {}) {
+ const { signal, ...request } = options;
+ return withBrowserDeadline(async boundedSignal => {
+ const response = await fetch(path, { ...request, signal: boundedSignal });
+ const document = response.status === 304 ? null : await response.json();
+ return { response, document };
+ }, { signal });
+}
diff --git a/relay/browser-devices.js b/relay/browser-devices.js
index 15d75df6..26ac5b5f 100644
--- a/relay/browser-devices.js
+++ b/relay/browser-devices.js
@@ -5,7 +5,8 @@ import { ENGINE_VERSION } from './engine.js';
import { Refused } from './refused.js';
import { approvalContext, openApproval, sealApproval, verifyApprovalIntent } from './relay-approval.js';
import { devicePublicKey } from './device-keys.js';
-import { approvalCardText, approvalNames, deletedText } from './browser-approval-card.js';
+import { approvalCardText, approvalNames, deletedText, phoneApprovalStatus } from './browser-approval-card.js';
+import { withBrowserDeadline } from './browser-deadline.js';
const PENDING = 'pullboard.relay.device-pair.v1';
@@ -20,45 +21,62 @@ export function rememberDevicePairing() {
history.replaceState(null, '', location.pathname + location.search);
}
-/** Complete one IndexedDB transaction before its connection is closed or the page continues. */
-async function deviceStorage(value) {
- if (!globalThis.indexedDB) throw new Refused('DEVICE_STORAGE', 'Use a secure browser with IndexedDB enabled to pair this phone.');
- const db = await new Promise((resolve, reject) => {
+/** Close a late IndexedDB open instead of retaining a key connection after the caller timed out. */
+function openDeviceDatabase(signal) {
+ return new Promise((resolve, reject) => {
const request = indexedDB.open('pullboard-relay-device-v1', 1);
- request.onupgradeneeded = () => request.result.createObjectStore('keys');
- request.onsuccess = () => resolve(request.result);
- request.onerror = () => reject(new Refused('DEVICE_STORAGE', 'Enable IndexedDB before pairing this phone.'));
+ const abort = () => reject(signal.reason);
+ signal.addEventListener('abort', abort, { once: true });
+ request.onupgradeneeded = () => {
+ if (signal.aborted) request.transaction.abort();
+ else request.result.createObjectStore('keys');
+ };
+ request.onsuccess = () => {
+ signal.removeEventListener('abort', abort);
+ if (signal.aborted) { request.result.close(); reject(signal.reason); }
+ else resolve(request.result);
+ };
+ request.onerror = () => {
+ signal.removeEventListener('abort', abort);
+ reject(new Refused('DEVICE_STORAGE', 'Enable IndexedDB before pairing this phone.'));
+ };
});
- try {
- return await new Promise((resolve, reject) => {
- const transaction = db.transaction('keys', value === undefined ? 'readonly' : 'readwrite');
- const store = transaction.objectStore('keys');
- const request = value === undefined ? store.get('device') : store.put(value, 'device');
- let result;
- request.onsuccess = () => { result = request.result; };
- transaction.oncomplete = () => resolve(value === undefined ? result ?? null : value);
- transaction.onerror = transaction.onabort = () => reject(new Refused('DEVICE_STORAGE', 'The phone could not retain its private key. Enable device storage and pair again.'));
- });
- } finally { db.close(); }
}
-/** Erase this removed browser's non-extractable private key before its revoked board can be drawn again. */
+/** Bound opening and completing a private key transaction, aborting that transaction on expiry. */
+async function withDeviceStore(mode, action) {
+ if (!globalThis.indexedDB) throw new Refused('DEVICE_STORAGE', 'Use a secure browser with IndexedDB enabled to pair this phone.');
+ return withBrowserDeadline(async signal => {
+ const db = await openDeviceDatabase(signal);
+ try {
+ if (signal.aborted) throw signal.reason;
+ return await new Promise((resolve, reject) => {
+ const transaction = db.transaction('keys', mode);
+ const abort = () => { try { transaction.abort(); } catch (error) { if (error.name !== 'InvalidStateError') reject(error); } };
+ signal.addEventListener('abort', abort, { once: true });
+ const request = action(transaction.objectStore('keys'));
+ let result;
+ request.onsuccess = () => { result = request.result; };
+ transaction.oncomplete = () => { signal.removeEventListener('abort', abort); resolve(result); };
+ transaction.onerror = transaction.onabort = () => {
+ signal.removeEventListener('abort', abort);
+ reject(new Refused('DEVICE_STORAGE', 'Device storage did not finish. Open this page again to retry.'));
+ };
+ });
+ } finally { db.close(); }
+ }, { code: 'DEVICE_STORAGE', message: 'Device storage did not answer. Open this page again to retry.' });
+}
+
+/** Complete one bounded private key transaction before the connection is closed or the page continues. */
+async function deviceStorage(value) {
+ const result = await withDeviceStore(value === undefined ? 'readonly' : 'readwrite',
+ store => value === undefined ? store.get('device') : store.put(value, 'device'));
+ return value === undefined ? result ?? null : value;
+}
+
+/** Erase a removed browser's private key with the same bounded, abortable storage operation. */
export async function forgetDevice() {
- if (!globalThis.indexedDB) return;
- const db = await new Promise((resolve, reject) => {
- const request = indexedDB.open('pullboard-relay-device-v1', 1);
- request.onupgradeneeded = () => request.result.createObjectStore('keys');
- request.onsuccess = () => resolve(request.result);
- request.onerror = () => reject(new Refused('DEVICE_STORAGE', 'Clear this removed browser’s site data before pairing again.'));
- });
- try {
- await new Promise((resolve, reject) => {
- const transaction = db.transaction('keys', 'readwrite');
- transaction.objectStore('keys').delete('device');
- transaction.oncomplete = resolve;
- transaction.onerror = transaction.onabort = () => reject(new Refused('DEVICE_STORAGE', 'Clear this removed browser’s site data before pairing again.'));
- });
- } finally { db.close(); }
+ if (globalThis.indexedDB) await withDeviceStore('readwrite', store => store.delete('device'));
}
/** Send a public enrollment without exposing private material; return true once new pairing delivers keys. */
@@ -75,11 +93,11 @@ export async function enrollPhone(documentAt) {
const identity = await documentAt('/api/v1/devices/session');
let device = await deviceStorage();
if (device?.locator !== locator || device.account !== identity.account) {
- device = { ...await createDeviceKeys(), account: identity.account, locator };
+ device = { ...await withBrowserDeadline(() => createDeviceKeys()), account: identity.account, locator };
await deviceStorage(device);
}
- const body = await signDeviceEnrollment(secret, { v: 1, account: identity.account, locator,
- deviceId: device.deviceId, publicKey: device.publicKey, label: 'Phone browser', createdAt: new Date().toISOString() });
+ const body = await withBrowserDeadline(() => signDeviceEnrollment(secret, { v: 1, account: identity.account, locator,
+ deviceId: device.deviceId, publicKey: device.publicKey, label: 'Phone browser', createdAt: new Date().toISOString() }));
await documentAt('/api/v1/devices/enrollments/' + locator, {
method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
});
@@ -114,8 +132,8 @@ export async function deviceBoardKeys(documentAt) {
let envelope;
try { envelope = JSON.parse(atob(row.wrapped.replaceAll('-', '+').replaceAll('_', '/'))); }
catch { throw new Refused('DEVICE_WRAP_AUTH', 'The wrapped board key could not be authenticated. Pair again.'); }
- keys[row.board] = encodeBoardKey(await unwrapDeviceBoardKey(device.privateKey, envelope,
- { board: row.board, device: device.deviceId, engine: ENGINE_VERSION }));
+ keys[row.board] = encodeBoardKey(await withBrowserDeadline(() => unwrapDeviceBoardKey(device.privateKey, envelope,
+ { board: row.board, device: device.deviceId, engine: ENGINE_VERSION })));
}
return keys;
}
@@ -134,10 +152,8 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved, s
if (document.getElementById('phone-approvals')) return;
let device = await deviceStorage();
if (!device || signal?.aborted) return;
- const panel = document.createElement('section');
- panel.className = 'card-panel'; panel.id = 'phone-approvals';
- panel.setAttribute('aria-label', 'Requests from your Mac');
- document.querySelector('main').prepend(panel);
+ const panel = phoneApprovalStatus(document, 'Checking requests from your computer…');
+ if (!panel) return;
const active = new Set();
let stopped = false;
let timer;
@@ -150,6 +166,8 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved, s
try {
const response = await documentAt('/api/v1/devices/' + device.deviceId + '/approvals');
if (stopped) return;
+ phoneApprovalStatus(document, null);
+ delete panel.dataset.error;
const ids = new Set(response.approvals.map(value => value.context.id));
for (const child of [...panel.children]) if (child.dataset.request && !ids.has(child.dataset.request) && !active.has(child.dataset.request)) child.remove();
for (const row of response.approvals) {
@@ -159,8 +177,8 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved, s
const raw = boardKeys[context.publisher];
if (!raw) continue;
const key = Uint8Array.from(atob(raw.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - raw.length % 4) % 4)), char => char.charCodeAt(0));
- const envelope = await verifyApprovalIntent(key, approvalDocument(row.sealed));
- const intent = await openApproval(device.privateKey, envelope, context, 'intent');
+ const envelope = await withBrowserDeadline(() => verifyApprovalIntent(key, approvalDocument(row.sealed)), { signal });
+ const intent = await withBrowserDeadline(() => openApproval(device.privateKey, envelope, context, 'intent'), { signal });
if (stopped) return;
if (JSON.stringify(approvalContext(intent.context)) !== JSON.stringify(context)) throw new Refused('PHONE_APPROVAL_AUTH', 'The displayed request differs from its sealed action.');
const replyKey = devicePublicKey(intent.replyKey);
@@ -179,7 +197,7 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved, s
const authorized = await documentAt('/api/v1/devices/approvals/' + context.id + '/authorize', {
method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}',
});
- const encrypted = await sealApproval(authorized.result, replyKey, context, 'reply');
+ const encrypted = await withBrowserDeadline(() => sealApproval(authorized.result, replyKey, context, 'reply'), { signal });
const response = btoa(JSON.stringify(encrypted)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');
await documentAt('/api/v1/devices/approvals/' + context.id + '/complete', {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ response }),
@@ -195,7 +213,12 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved, s
card.append(text, detail, button); panel.append(card);
}
} catch (error) {
- if (error?.code !== 'DEVICE_NOT_ENROLLED') panel.setAttribute('data-error', 'Approval requests are unavailable. Retry from the Mac.');
+ if (stopped) return;
+ if (error?.code === 'DEVICE_NOT_ENROLLED') phoneApprovalStatus(document, null);
+ else {
+ panel.setAttribute('data-error', 'Approval requests are unavailable. Retry from the Mac.');
+ phoneApprovalStatus(document, 'Requests from your computer did not load. They will retry.');
+ }
} finally { if (!stopped) timer = setTimeout(refresh, 1000); }
}
addEventListener('pagehide', stop, { once: true });
diff --git a/relay/browser-page.js b/relay/browser-page.js
index 85d5c41c..9f80fdc7 100644
--- a/relay/browser-page.js
+++ b/relay/browser-page.js
@@ -51,6 +51,7 @@ export function createRelayBrowserHandler({ authenticate }) {
['/relay/client.js', ['text/javascript', readFileSync(new URL('./browser-client.js', import.meta.url), 'utf8')]],
['/relay/sign-in.js', ['text/javascript', SIGN_IN_TRANSPORT]],
['/relay/browser-notice.js', ['text/javascript', readFileSync(new URL('./browser-notice.js', import.meta.url), 'utf8')]],
+ ['/relay/browser-deadline.js', ['text/javascript', readFileSync(new URL('./browser-deadline.js', import.meta.url), 'utf8').replace("'../src/refused.js'", "'./refused.js'")]],
['/relay/browser-stream.js', ['text/javascript', readFileSync(new URL('./browser-stream.js', import.meta.url), 'utf8')]],
['/relay/model.js', ['text/javascript', readFileSync(new URL('./browser-model.js', import.meta.url), 'utf8').replace("'../src/refused.js'", "'./refused.js'")]],
['/relay/engine.js', ['text/javascript', 'export const ENGINE_VERSION = ' + ENGINE_VERSION + ';\n']],
diff --git a/test/relay-browser-deadline.test.js b/test/relay-browser-deadline.test.js
new file mode 100644
index 00000000..31733224
--- /dev/null
+++ b/test/relay-browser-deadline.test.js
@@ -0,0 +1,58 @@
+/** Browser reads have finite deadlines even when the underlying API ignores cancellation [H5,H16,H17]. */
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { setImmediate as nextTurn } from 'node:timers/promises';
+import { BROWSER_IO_TIMEOUT_MS, browserJSON, withBrowserDeadline } from '../relay/browser-deadline.js';
+
+test('a browser operation that ignores cancellation still ends at its deadline [H5,H16]', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ let owned;
+ const read = withBrowserDeadline(signal => { owned = signal; return new Promise(() => {}); });
+ const rejected = assert.rejects(read, error => error.code === 'RELAY_UNAVAILABLE' && /again/u.test(error.message));
+ await nextTurn();
+ assert.equal(owned.aborted, false);
+ t.mock.timers.tick(BROWSER_IO_TIMEOUT_MS);
+ await rejected;
+ assert.equal(owned.aborted, true, 'cooperative APIs receive cancellation too');
+});
+
+test('a browser response whose JSON body never arrives keeps the same read deadline [H5,H16]', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ let bodyStarted = false;
+ let owned;
+ t.mock.method(globalThis, 'fetch', async (_path, options) => {
+ owned = options.signal;
+ return { status: 200, json: () => { bodyStarted = true; return new Promise(() => {}); } };
+ });
+ const read = browserJSON('/fixture');
+ const rejected = assert.rejects(read, error => error.code === 'RELAY_UNAVAILABLE');
+ await nextTurn();
+ assert.equal(bodyStarted, true, 'headers alone do not complete the read');
+ t.mock.timers.tick(BROWSER_IO_TIMEOUT_MS);
+ await rejected;
+ assert.equal(owned.aborted, true);
+});
+
+test('completed browser reads remove their deadline and parent cancellation listener [H5,H16]', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const parent = new AbortController();
+ let owned;
+ assert.equal(await withBrowserDeadline(signal => { owned = signal; return 'ready'; }, { signal: parent.signal }), 'ready');
+ parent.abort(new Error('later unrelated cancellation'));
+ t.mock.timers.tick(BROWSER_IO_TIMEOUT_MS);
+ assert.equal(owned.aborted, false, 'neither a stale timer nor a detached parent can cancel completed work');
+});
+
+test('a browser read preserves an earlier parent cancellation reason [H5,H16]', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const parent = new AbortController();
+ const reason = new Error('fixture parent stopped');
+ let owned;
+ const read = withBrowserDeadline(signal => { owned = signal; return new Promise(() => {}); }, { signal: parent.signal });
+ const rejected = assert.rejects(read, error => error === reason);
+ await nextTurn();
+ parent.abort(reason);
+ await rejected;
+ assert.equal(owned.aborted, true);
+ assert.equal(owned.reason, reason);
+});
diff --git a/test/relay-person-page.test.js b/test/relay-person-page.test.js
index 780e847e..1a6af7c5 100644
--- a/test/relay-person-page.test.js
+++ b/test/relay-person-page.test.js
@@ -12,6 +12,77 @@ import { createRelayBrowserHandler } from '../relay/browser-page.js';
const chromeOptions = { skip: !findChromeExecutable() && 'Chrome is not installed' };
+test('a phone draws its saved board while the approvals read never answers [N26,H5,H17]', chromeOptions, async t => {
+ const box = await relayClientFixture(t);
+ const marker = 'READABLE_BOARD_WITH_PENDING_REQUESTS_899';
+ assert.equal((await box.cli('add', box.lane, marker)).code, 0);
+ await box.link();
+ const board = JSON.parse(readFileSync(box.linkFile, 'utf8')).board;
+ const encoded = readFileSync(box.keyFile, 'utf8').trim();
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ await chrome.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
+ await chrome.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
+ const cookie = await chrome.send('Network.setCookie', {
+ name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax',
+ });
+ assert.equal(cookie.success, true, 'the private fixture session is installed');
+ // Private fixture key material is passed only as a CDP argument, never in an assertion or diagnostic label.
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', {
+ source: `localStorage.setItem('pullboard.relay.keys.v1', ${JSON.stringify(JSON.stringify({ [board]: encoded }))});
+const nativeFetch = window.fetch;
+window.fetch = (input, options) => {
+ const url = new URL(typeof input === 'string' ? input : input.url, location.href);
+ if (url.origin === 'http://127.0.0.1:4890') return Promise.reject(new TypeError('Fixture has no local view'));
+ if (/^\\/api\\/v1\\/devices\\/[^/]+\\/approvals$/.test(url.pathname)) {
+ window.approvalsPending899 = true;
+ if (window.approvalsRecovered899) return Promise.resolve(new Response(JSON.stringify({ version: 1, approvals: [] }), {
+ headers: { 'content-type': 'application/json' },
+ }));
+ return new Promise(() => {});
+ }
+ return nativeFetch(input, options);
+};`,
+ });
+ await chrome.navigate(box.origin);
+ await chrome.waitFor("document.readyState === 'complete'");
+ // Seed a real non-extractable browser key without exporting it; the authenticated saved board is already readable.
+ const seeded = await chrome.send('Runtime.evaluate', { awaitPromise: true, returnByValue: true, expression: `(async () => {
+ const { createDeviceKeys } = await import('/relay/device-keys.js');
+ const { ENGINE_VERSION } = await import('/relay/engine.js');
+ const identity = await (await fetch('/api/v1/devices/session', { headers: { 'x-pullboard-engine': String(ENGINE_VERSION) } })).json();
+ const device = { ...await createDeviceKeys(), account: identity.account, locator: 'fixture-899' };
+ const db = await new Promise((resolve, reject) => {
+ const request = indexedDB.open('pullboard-relay-device-v1', 1);
+ request.onupgradeneeded = () => request.result.createObjectStore('keys');
+ request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error);
+ });
+ try { await new Promise((resolve, reject) => {
+ const transaction = db.transaction('keys', 'readwrite'); transaction.objectStore('keys').put(device, 'device');
+ transaction.oncomplete = resolve; transaction.onerror = transaction.onabort = () => reject(transaction.error);
+ }); } finally { db.close(); }
+ return true;
+ })()` });
+ assert.equal(Boolean(seeded.exceptionDetails), false, 'the synthetic private browser device is retained');
+ assert.equal(seeded.result?.value, true);
+ await chrome.navigate('about:blank');
+ await chrome.navigate(box.origin);
+ await chrome.waitFor('window.approvalsPending899 === true');
+ await chrome.waitFor(`document.querySelector('#chain')?.textContent.includes(${JSON.stringify(marker)})`, 3000, // budget: declared #899 three-second ceiling while the late request never answers.
+ 'readable board renders while approvals remain pending');
+ assert.equal(await chrome.evaluate('window.approvalsPending899 === true'), true);
+ assert.ok((await chrome.evaluate('document.body.innerText')).includes(marker));
+ assert.ok((await chrome.evaluate('document.body.innerText')).includes('Checking requests from your computer'),
+ 'the pending background read has visible guidance alongside the board');
+ await chrome.waitFor("document.body.innerText.includes('Requests from your computer did not load')", 20_000, // budget: product fifteen-second I/O ceiling plus five seconds for native fixture scheduling.
+ 'an uncooperative request still reports its deadline');
+ assert.ok((await chrome.evaluate('document.body.innerText')).includes(marker), 'the board survives the background failure');
+ await chrome.evaluate('window.approvalsRecovered899 = true');
+ await chrome.waitFor("!document.querySelector('.phone-approval-status')", 3000, // budget: derived from one-second approvals polling plus two seconds for fixture scheduling.
+ 'a later successful poll clears the failure guidance');
+ assert.ok((await chrome.evaluate('document.body.innerText')).includes(marker), 'the board survives recovery too');
+});
+
test('a signed-in phone shows its first screen before a local probe can answer [N26,H5,H17]', chromeOptions, async t => {
const handle = createRelayBrowserHandler({ authenticate: async () => ({ kind: 'session' }) });
const server = createServer(async (req, res) => {