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): wait for boards without snapshots [H5,H16]

Corey Olson498714c849d1
diff --git a/relay/browser-client.js b/relay/browser-client.js
index 26b42cb1..dbf85056 100644
--- a/relay/browser-client.js
+++ b/relay/browser-client.js
@@ -1,4 +1,4 @@
-/** Device-only relay transport: cookie authorization, local keys and authenticated ciphertext [H5,H15]. */
+/** Device-only relay transport: cookie authorization, local keys and authenticated ciphertext [H5,H15,H16]. */
import { rememberDevicePairing, enrollPhone, deviceBoardKeys } from './browser-devices.js';
import { decodeBoardKey, encodeBoardKey, seal, unseal } from './seal.js';
import { preparePersonRequest, validatePersonRequest } from './person-request.js';
@@ -41,6 +41,13 @@ function transportBytes(value) {
return Uint8Array.from(binary, character => character.charCodeAt(0));
}
+/** Confirm session authorization before treating a board-local refusal as global access loss. */
+async function checkAuthorization(path, status, onDenied) {
+ if (![401, 403].includes(status) || !onDenied) return;
+ if (['/api/v1/boards', '/api/v1/devices/session'].includes(new URL(path, location.origin).pathname)) onDenied();
+ else await documentAt('/api/v1/devices/session', onDenied);
+}
+
/** Fetch only same-origin API documents, retaining stable refusal guidance and no provider details. */
async function documentAt(path, onDenied, options = {}) {
const headers = new Headers(options.headers ?? {});
@@ -49,7 +56,7 @@ async function documentAt(path, onDenied, options = {}) {
const document = await response.json();
if (!response.ok) {
const error = document.error;
- if ([401, 403].includes(response.status) || error?.code === 'NO_BOARD') onDenied?.();
+ await checkAuthorization(path, response.status, onDenied);
if (error) throw new Refused(error.code, error.message);
throw new Refused('RELAY_UNAVAILABLE', 'The relay did not answer. Sign in again or retry.');
}
@@ -63,6 +70,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
const keys = savedKeys && typeof savedKeys === 'object' && !Array.isArray(savedKeys) ? savedKeys : {};
const paired = new Map();
let available = [];
+ let waitingBoards = new Map();
let warnings = [];
let failure = '';
let accessLost = false;
@@ -92,13 +100,23 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
try { state = storedOwnedRequestState(localStorage, key, entry.state?.personRequests); } catch { /* Missing device storage can only hide this device's own notice. */ }
ownedRequestIds.set(id, state.owned);
}
- for (const text of noticeLines({ available, paired, ownedRequestIds, warnings, failure })) {
+ for (const text of noticeLines({ available, paired, ownedRequestIds, waitingBoards, warnings, failure })) {
const paragraph = document.createElement('p');
paragraph.textContent = text;
element.append(paragraph);
}
}
+ /** Keep one missing-snapshot board visible as waiting without clearing other authorized boards. */
+ function waitForFirstSnapshot(entry) {
+ entry.stream?.close();
+ entry.state = null;
+ paired.delete(entry.id);
+ const board = available.find(value => value.id === entry.id);
+ waitingBoards.set(entry.id, board?.repository ?? entry.repository ?? 'This board');
+ notice();
+ }
+
/** Retain one warning per board without duplicating it on the next live poll. */
function warning(value, boardId) {
if (!value || value.code !== 'BOARD_INACTIVE') return;
@@ -116,7 +134,8 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
if (response.status === 304 && entry.state) return;
const document = await response.json();
if (!response.ok) {
- if ([401, 403].includes(response.status) || document.error?.code === 'NO_BOARD') denied();
+ await checkAuthorization('/api/v1/boards/' + entry.id + '/state', response.status, denied);
+ if (document.error?.code === 'NO_BOARD' || document.error?.code === 'NO_SNAPSHOT') waitForFirstSnapshot(entry);
throw new Error(document.error ? '[' + document.error.code + '] ' + document.error.message : 'The relay snapshot is unavailable. Retry.');
}
if (document.version !== 1) throw new Error('This relay API version is unsupported. Upgrade this browser client.');
@@ -185,14 +204,24 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
}
}
+ /** Read board events without turning board-local snapshot loss into a session redirect. */
+ async function boardEvents(entry) {
+ try {
+ return await documentAt('/api/v1/boards/' + entry.id + '/events?after=' + entry.cursor, denied);
+ } catch (error) {
+ if (['NO_BOARD', 'NO_SNAPSHOT'].includes(error?.code)) waitForFirstSnapshot(entry);
+ throw error;
+ }
+ }
+
/** Read any durable prefix before attaching the live stream, including compaction repair. */
async function catchUp(entry) {
let document;
- try { document = await documentAt('/api/v1/boards/' + entry.id + '/events?after=' + entry.cursor, denied); }
+ try { document = await boardEvents(entry); }
catch (error) {
if (!error.message.includes('[SNAPSHOT_REQUIRED]')) throw error;
await snapshot(entry);
- document = await documentAt('/api/v1/boards/' + entry.id + '/events?after=' + entry.cursor, denied);
+ document = await boardEvents(entry);
}
warning(document.warning, entry.id);
for (const row of document.events) await receive(entry, row, true);
@@ -212,7 +241,11 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
subscribe(entry);
onUpdate();
} else {
- if (['AUTH_REQUIRED', 'NO_REPO_ACCESS', 'TOKEN_BOARD', 'NO_BOARD'].includes(error?.code)) denied();
+ if (['NO_BOARD', 'NO_SNAPSHOT'].includes(error?.code)) {
+ waitForFirstSnapshot(entry);
+ return;
+ }
+ if (['AUTH_REQUIRED', 'NO_REPO_ACCESS', 'TOKEN_BOARD'].includes(error?.code)) await documentAt('/api/v1/devices/session', denied);
failure = error ? '[' + error.code + '] ' + error.message : 'The relay stream ended. Refresh this board.';
notice();
}
@@ -245,7 +278,8 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
if (!response.ok) {
let document;
try { document = await response.json(); } catch { document = null; }
- if ([401, 403].includes(response.status) || document?.error?.code === 'NO_BOARD') denied();
+ await checkAuthorization(url, response.status, denied);
+ if (document?.error?.code === 'NO_BOARD' || document?.error?.code === 'NO_SNAPSHOT') waitForFirstSnapshot(entry);
const refusal = new Refused(document?.error?.code ?? 'RELAY_UNAVAILABLE', document?.error?.message ?? 'The relay stream ended. Refresh this board.');
if (refusal.code === 'ENGINE_VERSION') refusal.fatal = true;
throw refusal;
@@ -255,6 +289,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
onMessage: message => enqueueStream(entry, () => streamMessage(entry, message, stream)),
onFailure: (error, { fatal }) => {
if (controller.signal.aborted || accessLost) return;
+ if (['NO_BOARD', 'NO_SNAPSHOT'].includes(error?.code)) { waitForFirstSnapshot(entry); return; }
failure = error.message;
notice();
if (fatal) stream.close();
@@ -268,6 +303,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
Object.assign(keys, stored(localStorage, KEYS, {}));
Object.assign(keys, await deviceBoardKeys((path, options) => documentAt(path, denied, options)));
available = document.boards.filter(board => BOARD.test(board.id) && typeof board.repository === 'string');
+ waitingBoards = new Map();
warnings = document.warnings ?? [];
const visible = new Set(available.map(board => board.id));
for (const [id, entry] of paired) if (!visible.has(id)) { entry.stream?.close(); paired.delete(id); }
@@ -276,12 +312,13 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
if (paired.has(board.id) && pair?.board !== board.id && encodeBoardKey(paired.get(board.id).key) === encoded) continue;
if (!encoded) continue;
try {
- const entry = { id: board.id, key: decodeBoardKey(encoded), cursor: -1, state: null, outbox: null };
+ const entry = { id: board.id, repository: board.repository, key: decodeBoardKey(encoded), cursor: -1, state: null, outbox: null };
await snapshot(entry);
await catchUp(entry);
if (accessLost) throw new Error('Sign in again to read this board.');
paired.get(board.id)?.stream?.close();
paired.set(board.id, entry);
+ waitingBoards.delete(board.id);
keys[board.id] = encoded;
try { localStorage.setItem(KEYS, JSON.stringify({ ...stored(localStorage, KEYS, {}), [board.id]: encoded })); } catch { failure = 'This browser cannot save pairing. Use the pairing link again on your next visit.'; }
if (pair?.board === board.id) {
@@ -290,6 +327,10 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
}
subscribe(entry);
} catch (error) {
+ if (['NO_BOARD', 'NO_SNAPSHOT'].includes(error?.code) || /\[(?:NO_BOARD|NO_SNAPSHOT)\]/u.test(error.message)) {
+ 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)
? error.message
: 'Could not open this board with its saved key. Pair this browser again from a linked machine.';
diff --git a/relay/browser-notice.js b/relay/browser-notice.js
index 91a93b46..bb4fd1fa 100644
--- a/relay/browser-notice.js
+++ b/relay/browser-notice.js
@@ -32,7 +32,7 @@ export function storedOwnedRequestState(storage, key, requests) {
}
/** Build truthful device notices from authorized boards and their decrypted pending requests. */
-export function noticeLines({ available, paired, ownedRequestIds = new Map(), warnings = [], failure = '' }) {
+export function noticeLines({ available, paired, ownedRequestIds = new Map(), waitingBoards = new Map(), warnings = [], failure = '' }) {
const lines = [];
const waiting = [...paired.entries()].reduce((count, [id, entry]) => {
const owned = ownedRequestIds.get(id) ?? new Set();
@@ -41,6 +41,10 @@ export function noticeLines({ available, paired, ownedRequestIds = new Map(), wa
if (waiting) lines.push(`${waiting} request${waiting === 1 ? '' : 's'} from this device ${waiting === 1 ? 'is' : 'are'} waiting for a linked machine to run Pullboard.`);
const pairedRepositories = new Set(available.filter(board => paired.has(board.id)).map(board => board.repository));
for (const board of available.filter(value => !paired.has(value.id))) {
+ if (waitingBoards.has(board.id)) {
+ lines.push(`${board.repository} · board ${board.id.slice(0, 8)}: waiting for its first snapshot from a linked machine.`);
+ continue;
+ }
if (!pairedRepositories.has(board.repository)) {
lines.push(board.repository + ': pair this browser using a link or QR from a linked machine.');
continue;
diff --git a/test/relay-browser.test.js b/test/relay-browser.test.js
index bd34273a..d501928a 100644
--- a/test/relay-browser.test.js
+++ b/test/relay-browser.test.js
@@ -196,6 +196,63 @@ test('real Chrome pairs, retains its device key, declares its engine on every re
await chrome.waitFor("document.body.textContent.includes('Sign in with GitHub') && !document.body.textContent.includes(" + JSON.stringify(liveTitle) + ')');
});
+test('a board without a snapshot waits without reloading the page [H5,H16]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ const healthyTitle = 'NO_BOARD_HEALTHY_BOARD_339';
+ const healthyUpdate = 'NO_BOARD_HEALTHY_BOARD_UPDATE_339';
+ const missingTitle = 'NO_BOARD_WAITING_BOARD_339';
+ const missingEventsTitle = 'NO_BOARD_WAITING_EVENTS_339';
+ assert.equal((await box.cli('add', box.lane, healthyTitle)).code, 0);
+ await box.link();
+ const healthy = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const healthyKey = readFileSync(box.keyFile, 'utf8').trim();
+ const waiting = await box.additionalBoard(missingTitle);
+ const waitingEvents = await box.additionalBoard(missingEventsTitle);
+ box.noBoardOnReads(waiting.id, ['state']);
+ box.noBoardOnReads(waitingEvents.id, ['events']);
+
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', {
+ source: 'sessionStorage.setItem("pullboard.test.page-starts", String(Number(sessionStorage.getItem("pullboard.test.page-starts") || 0) + 1)); localStorage.setItem("pullboard.relay.keys.v1", ' +
+ JSON.stringify(JSON.stringify({ [healthy.board]: healthyKey, [waiting.id]: waiting.encoded, [waitingEvents.id]: waitingEvents.encoded })) + ');',
+ });
+ await signIn(chrome, box);
+ await chrome.navigate(box.origin);
+ const pageStarts = await chrome.evaluate("Number(sessionStorage.getItem('pullboard.test.page-starts'))");
+ await chrome.waitFor("(document.querySelector('#relay-notice')?.textContent.includes(" + JSON.stringify(waiting.id.slice(0, 8)) + ") && document.querySelector('#relay-notice')?.textContent.includes(" + JSON.stringify(waitingEvents.id.slice(0, 8)) + ") && document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(healthyTitle) + ")) || Number(sessionStorage.getItem('pullboard.test.page-starts')) > " + pageStarts);
+ assert.equal(await chrome.evaluate("document.querySelector('#relay-notice')?.textContent.includes(" + JSON.stringify(waiting.id.slice(0, 8)) + ') ?? false'), true,
+ 'the notice identifies the board whose first snapshot is missing');
+ assert.equal(await chrome.evaluate("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(healthyTitle) + ')'), true,
+ 'the other linked board still renders its actual snapshot');
+ assert.equal(await chrome.evaluate("document.querySelector('#relay-notice')?.textContent.includes(" + JSON.stringify(waitingEvents.id.slice(0, 8)) + ') ?? false'), true,
+ 'an events endpoint with no board snapshot also gets its own waiting notice');
+ const healthySelector = '#proj-list .proj.repo[data-root="' + healthy.board + '"]';
+ await chrome.evaluate('document.querySelector(' + JSON.stringify(healthySelector) + ').click()');
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(healthyTitle) + ')');
+ assert.equal(box.calls.some(call => call.method === 'GET' && call.path === '/api/v1/boards/' + waiting.id + '/state'), true,
+ 'the real browser requests the listed board snapshot over HTTP');
+ assert.equal(box.calls.some(call => call.method === 'GET' && call.path.startsWith('/api/v1/boards/' + waitingEvents.id + '/events')), true,
+ 'the real browser requests the other listed board event stream over HTTP');
+
+ assert.equal((await box.cli('add', box.lane, healthyUpdate)).code, 0);
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(healthyUpdate) + ')');
+
+ const pageLoads = () => box.calls.filter(call => call.method === 'GET' && call.path === '/').length;
+ const beforeWait = pageLoads();
+ await new Promise(resolveWait => setTimeout(resolveWait, 10_000));
+ assert.equal(pageLoads(), beforeWait, 'the missing snapshot does not reload the real page during ten seconds');
+
+ const listingsBeforeRevocation = box.calls.filter(call => call.method === 'GET' && call.path === '/api/v1/boards').length;
+ box.revokeSessionOnNextListing();
+ await chrome.evaluate("location.hash = '#refresh-listing'");
+ await chrome.waitFor("document.body.textContent.includes('Sign in with GitHub')");
+ assert.ok(box.calls.filter(call => call.method === 'GET' && call.path === '/api/v1/boards').length > listingsBeforeRevocation,
+ 'a real unauthorized listing still sends the page back to sign in');
+});
+
/** Append an authenticated synthetic sealed move without writing it to the private local board. */
async function appendEngineMove(box, link, key, sequence, engine, presentation) {
const event = { event_id: sequence, event_kind: 'add', event_by: 'fixture', event_at: new Date().toISOString(), event_detail: '{}' };
diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.js
index 6e50e882..be9a90d8 100644
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@ -80,6 +80,8 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
let override = null;
let mintFailures = 0;
let refuseEventReads = false;
+ let revokeOnNextListing = false;
+ const boardsWithoutSnapshots = new Map();
const injectedSnapshotWriteDelayMs = Number(process.env.PULLBOARD_TEST_SNAPSHOT_WRITE_DELAY_MS ?? 0);
assert.ok(Number.isSafeInteger(injectedSnapshotWriteDelayMs) && injectedSnapshotWriteDelayMs >= 0 && injectedSnapshotWriteDelayMs <= 15000,
'injected snapshot delay is within the product wait bound');
@@ -129,7 +131,18 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
res.once('finish', () => transit.push({ method: req.method, path: req.url,
request: Buffer.concat(requestChunks), response: Buffer.concat(responseChunks) }));
calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '', engine: req.headers['x-pullboard-engine'] });
+ if (revokeOnNextListing && req.method === 'GET' && req.url === '/api/v1/boards') {
+ revokeOnNextListing = false;
+ const state = JSON.parse(readFileSync(linkFile, 'utf8'));
+ await auth.revoke(state.token, state.tokenId);
+ }
if ([...privateKeys].some(key => JSON.stringify({ url: req.url, headers: req.headers }).includes(key))) keyLeaked = true;
+ const missingSnapshot = /^\/api\/v1\/boards\/([0-9a-f]{32})\/(state|events)(?:\?|$)/u.exec(req.url ?? '');
+ if (req.method === 'GET' && missingSnapshot && boardsWithoutSnapshots.get(missingSnapshot[1])?.has(missingSnapshot[2])) {
+ res.writeHead(404, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ version: 1, error: { code: 'NO_BOARD', message: 'upload the sealed snapshot for this linked board first' } }));
+ return;
+ }
if (mintFailures > 0 && req.method === 'POST' && req.url === '/auth/tokens') {
mintFailures -= 1;
req.resume();
@@ -311,10 +324,8 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
}
/** Link another independently initialized synthetic board through the same real person account. */
async function additionalBoard(title) {
- const nextRoot = join(scratch, 'additional-board');
- const nextHome = join(scratch, 'additional-home');
- mkdirSync(nextRoot);
- mkdirSync(nextHome, { mode: 0o700 });
+ const nextRoot = mkdtempSync(join(scratch, 'additional-board-'));
+ const nextHome = mkdtempSync(join(scratch, 'additional-home-'));
const nextEnv = { ...env, HOME: nextHome, PULLBOARD_HOME: join(nextHome, '.pullboard') };
/** Run this separate board without retaining credentials in diagnostic output. */
const run = (...args) => childResult(nextRoot, nextEnv, [CLI, ...args, '--json']);
@@ -362,6 +373,12 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
keyInRequest() { return keyLeaked; },
/** Revoke the actual synthetic person session, including its current live streams. */
revokeSession() { const state = JSON.parse(readFileSync(linkFile, 'utf8')); return auth.revoke(state.token, state.tokenId); },
+ /** Revoke the real session when the next listing arrives so its HTTP authorization refusal is exercised. */
+ revokeSessionOnNextListing() { revokeOnNextListing = true; },
refuseReads(value) { refuseEventReads = value; },
+ /** Return a selected listed-board read's missing-snapshot refusal over real HTTP. */
+ noBoardOnReads(id, paths = ['state']) {
+ boardsWithoutSnapshots.set(id, new Set(paths));
+ },
};
}