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.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(relay): hydrate phone history beside live state [H15,H17]
Corey Olson6e3a230f040e
diff --git a/relay/browser-client.js b/relay/browser-client.jsindex ebce0a31..24f1f3dc 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -10,6 +10,8 @@ import { homeLineDismissed, homeScreenLine, noticeLines, nothingShared, rememberimport { registerApp, requestPairingPersistence } from './install.js';import { browserJSON, withBrowserDeadline } from './browser-deadline.js';import { phoneApprovalStatus, placePhoneApprovals } from './browser-approval-card.js';+import { phoneSnapshotPages } from './browser-pages.js';+import { createPhoneHistory } from './browser-history.js';const KEYS = 'pullboard.relay.keys.v1';const PENDING = 'pullboard.relay.pair.v1';@@ -126,6 +128,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>access.abort();for (const entry of paired.values()) {entry.stream?.close();+ entry.history?.close(); entry.pageCache?.clear(); entry.pages = null;// The cockpit holds this same projection. Clear its arrays before releasing our reference.if (entry.state) for (const [field, value] of Object.entries(entry.state)) {if (Array.isArray(value)) value.length = 0;@@ -182,7 +185,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>const root = document.documentElement;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(' ') : '');+ phoneWaiting && (failure || waitingBoards.size || warnings.some(value => value?.code === 'ACCOUNT_STORAGE_LIMIT')) ? lines.join(' ') : '');placePhoneApprovals(document);}@@ -201,6 +204,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>/** Keep one missing-snapshot board visible as waiting without clearing other authorized boards. */function waitForFirstSnapshot(entry) {entry.stream?.close();+ entry.history?.close(); entry.history = null; entry.pageCache?.clear(); entry.pages = null;entry.state = null;entry.shouts = null;paired.delete(entry.id);@@ -211,21 +215,53 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>/** Retain one warning per board without duplicating it on the next live poll. */function warning(value, boardId) {- if (!value || value.code !== 'BOARD_INACTIVE') return;- warnings = warnings.filter(entry => entry.board !== boardId);+ if (!value || !['BOARD_INACTIVE', 'ACCOUNT_STORAGE_LIMIT'].includes(value.code)) return;+ warnings = warnings.filter(entry => entry.board !== boardId || entry.code !== value.code);warnings.push({ ...value, board: boardId });notice();}+ /** Keep full history beside the live cursor; a completed old checkpoint never replaces newer current state. */+ function historyFor(entry) {+ entry.history ??= createPhoneHistory({+ active: () => !accessLost && paired.get(entry.id) === entry,+ current: () => ({ id: entry.pages?.id, sequence: entry.cursor }),+ install(full, details) {+ const state = presentationState(full, entry.id);+ if (details) state.items = state.items.map(item => details.get(item.id) ?? item);+ entry.state = { ...state, historyProgress: entry.history.status() };+ entry.historyChanged = true;+ },+ changed() {+ if (entry.state) entry.state.historyProgress = entry.history.status();+ // Progress itself is local state. Only new board data or completion asks the cockpit to refresh the relay.+ if (entry.historyChanged || entry.history.status().complete) { entry.historyChanged = false; onUpdate(); }+ },+ failed() {+ failure = 'Older history did not finish loading. Open this board again to retry.';+ failureBoard = entry.id; notice();+ },+ });+ return entry.history;+ }+/** Authenticate the latest native snapshot before installing its presentation in this device. */async function snapshot(entry) {- const { response, document } = await browserJSON('/api/v1/boards/' + entry.id + '/state', {+ let path = '/api/v' + (entry.snapshotApiVersion === 2 ? '2' : '1') + '/boards/' + entry.id + '/state';+ const settings = {credentials: 'same-origin', cache: 'no-store', redirect: 'error',- headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(entry.state && entry.snapshotTag ? { 'if-none-match': entry.snapshotTag } : {}) },- });+ signal: access.signal,+ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(entry.snapshotApiVersion !== 2 && entry.state && entry.snapshotTag ? { 'if-none-match': entry.snapshotTag } : {}) },+ };+ let { response, document } = await browserJSON(path, settings);+ if (!response.ok && document?.error?.code === 'RELAY_API_VERSION' && entry.snapshotApiVersion !== 2) {+ entry.snapshotApiVersion = 2; entry.snapshotTag = null;+ path = '/api/v2/boards/' + entry.id + '/state';+ ({ response, document } = await browserJSON(path, { ...settings, headers: { 'x-pullboard-engine': String(ENGINE_VERSION) } }));+ }if (response.status === 304 && entry.state) return;if (!response.ok) {- await checkAuthorization('/api/v1/boards/' + entry.id + '/state', response.status, denied, document.error);+ await checkAuthorization(path, response.status, denied, document.error);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.');}@@ -233,12 +269,34 @@ 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);+ if (row.apiVersion === 2) {+ entry.pageCache ??= new Map();+ const page = await phoneSnapshotPages(row, { boardId: entry.id, key: entry.key, maxEngine: ENGINE_VERSION, cache: entry.pageCache,+ read: target => documentAt(target, denied, { signal: access.signal }),+ bound: work => withBrowserDeadline(work, { signal: access.signal }),+ });+ if (accessLost) throw accessError;+ const unchanged = entry.pages?.id === page.id && entry.state;+ if (row.sequence >= entry.cursor && !unchanged) {+ const value = await page.presentation();+ if (accessLost) throw accessError;+ entry.state = presentationState(value, entry.id);+ entry.shouts = null; entry.cursor = row.sequence;+ }+ entry.pages = page;+ const history = historyFor(entry);+ history.queue(page, row.sequence);+ if (entry.state) entry.state.historyProgress = history.status();+ if (rendered) history.start();+ return;+ }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.');entry.snapshotTag = response.headers.get('etag');if (row.sequence >= entry.cursor) {+ entry.history?.close(); entry.history = null; entry.pages = null; entry.pageCache?.clear();entry.state = state;entry.shouts = Array.isArray(value.presentation?.shouts) ? value.presentation.shouts : null;entry.cursor = row.sequence;@@ -287,6 +345,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>if (move.version !== 1 || !Number.isSafeInteger(move.engine) || move.engine < 1) throw new Error('This sealed move has an unsupported format. Refresh it from a linked machine.');if (move.engine !== ENGINE_VERSION) throw new Refused('RELAY_ENGINE_VERSION', 'This board needs engine ' + move.engine + '; this browser reads engine ' + ENGINE_VERSION + '. Upgrade the browser client.');if (move.presentation) {+ entry.history?.close(); entry.history = null; entry.pages = null; entry.pageCache?.clear();entry.state = presentationState(move.presentation, entry.id);entry.shouts = Array.isArray(move.presentation.shouts) ? move.presentation.shouts : null;entry.cursor = row.event_id;@@ -405,7 +464,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>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); }+ for (const [id, entry] of paired) if (!visible.has(id)) { entry.stream?.close(); entry.history?.close(); entry.pageCache?.clear(); paired.delete(id); }for (const board of available) {const encoded = pair?.board === board.id ? pair.key : keys[board.id];if (paired.has(board.id) && pair?.board !== board.id && encodeBoardKey(paired.get(board.id).key) === encoded) continue;@@ -415,8 +474,9 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>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.get(board.id)?.stream?.close(); paired.get(board.id)?.history?.close(); paired.get(board.id)?.pageCache?.clear();paired.set(board.id, entry);+ if (rendered) entry.history?.start();waitingBoards.delete(board.id);keys[board.id] = encoded;try {@@ -493,14 +553,15 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>}/** Resolve one addressed shout from this paired device's complete sealed presentation. */- function addressedShout(entry, rawId) {+ async function addressedShout(entry, rawId) {if (!/^[1-9]\d*$/.test(rawId) || !Number.isSafeInteger(Number(rawId))) {throw new Refused('BAD_REQUEST', 'shout needs a positive integer id; use the id from the event or recent state');}+ const id = Number(rawId);+ if (entry.pages) return { version: 1, shout: entry.history?.shout(id) ?? await entry.pages.shout(id) };if (!Array.isArray(entry.shouts)) {throw new Refused('SHOUT_NOT_AVAILABLE', 'this snapshot does not include addressed shout history; refresh it with a current CLI');}- const id = Number(rawId);const found = entry.shouts.find(shout => shout.shout_id === id);if (!found) throw new Refused('NO_SHOUT', `no shout #${id}`);const answer = found.shout_decision ? entry.shouts.find(shout => shout.shout_answers === id) ?? null : null;@@ -583,7 +644,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>addEventListener('hashchange', pairingChanged);// A pairing link opened in another tab, as a scanned QR does, saves its key here: this page fills in by itself.addEventListener('storage', event => { if (event.key === KEYS && !accessLost) listing().then(onUpdate, notice); });- addEventListener('pagehide', () => { for (const entry of paired.values()) entry.stream?.close(); });+ addEventListener('pagehide', () => { access.abort(); for (const entry of paired.values()) { entry.stream?.close(); entry.history?.close(); entry.pageCache?.clear(); } });// Signed in with no board key saved and no pairing on its way, the one-command screen shows at once, while the// first listing is still on the network; the listing then fills the board in, or keeps this screen.let devicePairing = /(?:^#|&)device=/u.test(location.hash);@@ -604,7 +665,9 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>});return {/** Give the startup frame back only after an opted-in viewer has drawn a readable board. */- didRender() { rendered = true; notice(); },+ didRender() { rendered = true; notice(); for (const entry of paired.values()) entry.history?.start(); },+ /** The View can paint loading counts without making another relay request. */+ historyProgress(boardId) { return paired.get(boardId)?.history?.status() ?? { loaded: 0, total: 0, complete: true, sequence: paired.get(boardId)?.cursor ?? null }; },/** 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;@@ -613,11 +676,12 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>if (url.pathname === '/api/v1/boards') { if (body !== undefined && body !== null) throw new Refused('BAD_REQUEST', 'Send person intent to a paired board.'); return listing(); }const match = /^\/api\/v1\/boards\/([0-9a-f]{32})\/(state|events|moves|requests)$/.exec(url.pathname);const shoutMatch = /^\/api\/v1\/boards\/([0-9a-f]{32})\/shouts\/([^/]+)$/.exec(url.pathname);- const route = match ?? shoutMatch;+ const itemMatch = /^\/api\/v1\/boards\/([0-9a-f]{32})\/items(?:\/([^/]+))?$/.exec(url.pathname);+ const route = match ?? shoutMatch ?? itemMatch;const entry = route && paired.get(route[1]);if (!entry) throw new Error('Pair this browser to read that board.');if (body !== undefined && body !== null) {- if (shoutMatch) throw new Refused('BAD_REQUEST', 'read an addressed shout with GET; use a board move to create or answer shouts');+ if (shoutMatch || itemMatch) throw new Refused('BAD_REQUEST', 'Read item or shout detail with GET; send person intent to the board moves endpoint.');if (!['moves', 'requests'].includes(match[2])) throw new Refused('BAD_REQUEST', 'Send person intent to this board’s moves endpoint.');const value = preparePersonRequest(body);const send = enqueue(entry, async () => {@@ -629,6 +693,20 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>});return send;}+ if (itemMatch) return enqueue(entry, async () => {+ await flushOutbox(entry); await snapshot(entry); await catchUp(entry);+ if (!itemMatch[2]) {+ const query = (url.searchParams.get('q') ?? '').trim().toLowerCase();+ const ids = entry.pages ? await entry.pages.searchItems(query) : entry.state.items.filter(item =>+ ('#' + item.id + ' ' + item.title + ' ' + item.lane + ' ' + item.specs.join(' ') + ' ' + (item.criterion || '')).toLowerCase().includes(query)).map(item => item.id);+ return { version: 1, ids };+ }+ if (!/^[1-9]\d*$/u.test(itemMatch[2]) || !Number.isSafeInteger(Number(itemMatch[2]))) throw new Refused('BAD_REQUEST', 'Read an item by its positive integer id.');+ const id = Number(itemMatch[2]);+ const item = entry.pages ? entry.history?.item(id) ?? await entry.pages.item(id) : entry.state.items.find(value => value.id === id);+ if (!item) throw new Refused('NO_ITEM', `no item #${id}`);+ return { version: 1, item };+ });if (shoutMatch) {return enqueue(entry, async () => {await flushOutbox(entry);diff --git a/relay/browser-history.js b/relay/browser-history.jsnew file mode 100644index 00000000..4d473055--- /dev/null+++ b/relay/browser-history.js@@ -0,0 +1,92 @@+/** Stream history beside the current board, without owning or rewinding its live move cursor [H15,H17]. */++/** Hold one completed checkpoint plus the latest requested successor; old reads may finish while moves keep arriving. */+export function createPhoneHistory({ active, current, install, changed, failed }) {+ let pending = null, running = null, busy = false, closed = false, complete = null;+ let progress = { loaded: 0, total: null, complete: false, sequence: null };+ let lastPaint = 0;++ /** Publish progress only for the checkpoint the current screen actually uses. */+ function report(job, loaded, done = false, error = null) {+ if (closed || current().id !== job.page.id) return;+ progress = { loaded, total: job.page.total, complete: done, sequence: job.sequence, ...(error ? { error } : {}) };+ const now = Date.now();+ // Budget: coalesce background progress to at most five paints per second; completion is always immediate.+ if (done || error || now - lastPaint >= 200) { lastPaint = now; changed(); }+ }++ /** Consume one page iterator independently of the foreground per-board send/cursor queue. */+ async function consume() {+ try {+ while (pending && !closed && active()) {+ const job = pending; pending = null; running = job;+ const tables = new Map(), details = new Map();+ let loaded = 0, full = null, ended = false;+ try {+ for await (const chunk of job.page.history()) {+ if (closed || !active()) return;+ if (chunk.kind === 'presentation') {+ full = chunk.value;+ if (current().id === job.page.id && current().sequence === job.sequence) install(full, null);+ } else if (chunk.kind === 'table') {+ const rows = tables.get(chunk.name) ?? [];+ rows.push(...chunk.rows); tables.set(chunk.name, rows); loaded += chunk.rows.length;+ } else if (chunk.kind === 'items') {+ for (const item of chunk.rows) details.set(item.id, item);+ loaded += chunk.rows.length;+ } else if (chunk.kind === 'complete') ended = true;+ report(job, loaded);+ // Give first paint, live events and person actions a turn between bounded history batches.+ await new Promise(resolveTurn => setTimeout(resolveTurn, 0));+ }+ if (!ended || loaded !== job.page.total) throw new Error('The background history was incomplete. Open this board again to retry.');+ const ordered = new Map([...tables].map(([name, rows]) => [name, rows.reverse()]));+ const shouts = new Map((ordered.get('shout') ?? []).map(row => [row.shout_id, row]));+ const answers = new Map();+ for (const row of shouts.values()) if (row.shout_answers !== null && !answers.has(row.shout_answers)) answers.set(row.shout_answers, row);+ complete = { id: job.page.id, sequence: job.sequence, tables: ordered, details, shouts, answers };+ if (current().id === job.page.id && current().sequence === job.sequence) install(full, details);+ if (current().id === job.page.id) job.page.prune?.();+ report(job, loaded, true);+ } catch (error) {+ if (!closed && active()) { report(job, loaded, false, 'Older history did not finish loading. Open this board again to retry.'); failed(error); }+ } finally { running = null; }+ }+ } finally { busy = false; }+ }++ /** Start after the renderer has received its transport; at most one history consumer runs for a board. */+ function start() {+ if (busy || closed || !pending || !active()) return;+ busy = true;+ setTimeout(() => { if (closed) { busy = false; return; } void consume(); }, 0);+ }++ /** Supersede only a waiting job; the pinned current worker can finish without starving under live moves. */+ function queue(page, sequence) {+ if (closed) return;+ if (complete?.id === page.id) { report({ page, sequence }, page.total, true); return; }+ if (running?.page.id === page.id || pending?.page.id === page.id) return;+ pending = { page, sequence };+ progress = { loaded: 0, total: page.total, complete: false, sequence };+ }++ /** Return an already streamed item only when its exact snapshot still governs the screen. */+ function item(id) { return complete && complete.id === current().id ? complete.details.get(id) ?? null : null; }++ /** Resolve a streamed historical shout and its first answer without another network request. */+ function shout(id) {+ if (!complete || complete.id !== current().id) return null;+ const found = complete.shouts.get(id);+ if (!found) return null;+ const answer = found.shout_decision ? complete.answers.get(id) ?? null : null;+ return { ...found, decision_state: found.shout_decision ? (answer ? 'answered' : 'open') : null, decision_answer: answer };+ }++ /** Expose only counts and status to the View companion, never private table contents or keys. */+ function status() { return { ...progress }; }++ /** Access loss and pagehide discard decrypted history immediately and prevent late results from installing state. */+ function close() { closed = true; pending = null; complete = null; progress = { loaded: 0, total: null, complete: false, sequence: null }; }+ return { queue, start, item, shout, status, close };+}diff --git a/relay/browser-notice.js b/relay/browser-notice.jsindex 041ec20a..56218ee0 100644--- a/relay/browser-notice.js+++ b/relay/browser-notice.js@@ -65,6 +65,7 @@ export function noticeLines({ available, paired, ownedRequestIds = new Map(), wafor (const warning of warnings) if (warning?.code === 'BOARD_INACTIVE' && Number.isInteger(warning.daysLeft)) {lines.push('BOARD_INACTIVE: ' + warning.daysLeft + ' days left before this relay board is deleted. Make a board move from a linked machine to keep it.');}+ for (const warning of warnings) if (warning?.code === 'ACCOUNT_STORAGE_LIMIT' && typeof warning.message === 'string') lines.push(warning.message);if (failure) lines.push(failure);if (!available.length) lines.push('No linked boards are available for this account.');return lines;diff --git a/relay/browser-page.js b/relay/browser-page.jsindex 9f80fdc7..54c01815 100644--- a/relay/browser-page.js+++ b/relay/browser-page.js@@ -53,6 +53,10 @@ export function createRelayBrowserHandler({ authenticate }) {['/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/browser-pages.js', ['text/javascript', readFileSync(new URL('./browser-pages.js', import.meta.url), 'utf8').replaceAll("'../src/relay-page-layout.js'", "'./page-layout.js'").replaceAll("'../src/sealed-pages.js'", "'./sealed-pages.js'").replaceAll("'../src/refused.js'", "'./refused.js'")]],+ ['/relay/browser-history.js', ['text/javascript', readFileSync(new URL('./browser-history.js', import.meta.url), 'utf8')]],+ ['/relay/page-layout.js', ['text/javascript', readFileSync(new URL('../src/relay-page-layout.js', import.meta.url), 'utf8')]],+ ['/relay/sealed-pages.js', ['text/javascript', readFileSync(new URL('../src/sealed-pages.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']],['/relay/seal.js', ['text/javascript', readFileSync(new URL('../src/seal.js', import.meta.url), 'utf8')]],diff --git a/relay/browser-pages.js b/relay/browser-pages.jsindex 6ef58ae4..c7b5c486 100644--- a/relay/browser-pages.js+++ b/relay/browser-pages.js@@ -1,6 +1,6 @@/** Phone reads current state and selected history without restoring the native board's complete tables [H15,H17]. */import { openPagedSnapshot } from '../src/relay-page-layout.js';-import { PAGE_CIPHER_BYTES, pageReference } from '../src/sealed-pages.js';+import { PAGE_CIPHER_BYTES, pageDigest, pageReference } from '../src/sealed-pages.js';import { Refused } from '../src/refused.js';/** Decode canonical bounded ciphertext without including a response value in refusal guidance. */@@ -12,17 +12,23 @@ function cipher(value) {}/** Authenticate a fresh read pin and expose only individually bounded current/detail/search reads to the cockpit. */-export async function phoneSnapshotPages(row, { boardId, key, maxEngine, read, bound }) {+export async function phoneSnapshotPages(row, { boardId, key, maxEngine, read, bound, cache = new Map() }) {if (row?.apiVersion !== 2 || !Number.isSafeInteger(row.sequence) || row.sequence < 0 || typeof read !== 'function' || typeof bound !== 'function' ||!/^[A-Za-z0-9-]{1,128}$/u.test(row.read?.id ?? '')) throw new Refused('RELAY_RESPONSE', 'This paged board response is invalid. Refresh the board.');const root = pageReference(row.root);if (root.sequence !== row.sequence) throw new Refused('RELAY_RESPONSE', 'This board checkpoint has inconsistent coverage. Refresh the board.');+ const seen = new Set();const context = { boardId, key, sequence: row.sequence, bound,/** Every fetched object is authorized again under this read pin's authenticated parent path. */async get(id, parents) {+ seen.add(id);+ if (cache.has(id)) return cache.get(id);const document = await read('/api/v2/boards/' + boardId + '/objects/' + id + '?pin=' + encodeURIComponent(row.read.id) + '&via=' + parents.join(','));if (document.apiVersion !== 2 || document.page?.id !== id) throw new Refused('RELAY_RESPONSE', 'The relay returned another history page. Refresh the board.');- return cipher(document.page.sealed);+ const bytes = cipher(document.page.sealed);+ if (await pageDigest(bytes) !== id) throw new Refused('RELAY_RESPONSE', 'This sealed history page failed its content check. Refresh the board.');+ cache.set(id, bytes);+ return bytes;},};const page = await bound(() => openPagedSnapshot(root, context, { maxEngine }));@@ -39,5 +45,7 @@ export async function phoneSnapshotPages(row, { boardId, key, maxEngine, read, bsearchItems: query => bound(() => page.searchItems(query)),/** The board has no total background deadline: each underlying object I/O and crypto operation is independently bounded. */history: () => page.history(),+ /** A fully streamed current root no longer needs cipher objects from superseded checkpoints. */+ prune() { for (const id of cache.keys()) if (!seen.has(id)) cache.delete(id); },};}diff --git a/test/relay-browser-history.test.js b/test/relay-browser-history.test.jsnew file mode 100644index 00000000..9e1b2b56--- /dev/null+++ b/test/relay-browser-history.test.js@@ -0,0 +1,96 @@+/** Background checkpoints never rewind the live phone cursor or pretend partial history is complete [H15,H17]. */+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { createPhoneHistory } from '../relay/browser-history.js';++/** Expose one explicit transition instead of relying on a timing-based confidence wait. */+function deferred() {+ let resolve;+ const promise = new Promise(accept => { resolve = accept; });+ return { promise, resolve };+}++/** A controlled page iterator pauses after its current presentation and then yields real history-shaped records. */+function page(id, gate = null, total = 3) {+ const entered = deferred(), closed = deferred();+ let runs = 0, pruned = 0;+ return { id, total, entered: entered.promise, closed: closed.promise,+ /** Every message and detail remains tagged with the checkpoint that produced it. */+ async *history() {+ runs++;+ try {+ yield { kind: 'presentation', value: { state: { marker: id } } };+ entered.resolve();+ if (gate) await gate.promise;+ yield { kind: 'table', name: 'shout', rows: [{ shout_id: 2, shout_text: id + '-answer', shout_decision: 0, shout_answers: 1 }] };+ yield { kind: 'table', name: 'shout', rows: [{ shout_id: 1, shout_text: id + '-question', shout_decision: 1, shout_answers: null }] };+ yield { kind: 'items', rows: [{ id: 7, marker: id, history: [] }] };+ yield { kind: 'complete' };+ } finally { closed.resolve(); }+ },+ /** Count eviction only when the fully streamed graph still governs the screen. */+ prune() { pruned++; },+ counts() { return { runs, pruned }; },+ };+}++test('history finishes a pinned predecessor while newer moves keep their own current state [H15,H17]', async t => {+ const aGate = deferred(), bGate = deferred();+ const a = page('a', aGate), b = page('b', bGate);+ let current = { id: 'a', sequence: 7 }, alive = true;+ const installed = [], failures = [], done = deferred();+ let history;+ history = createPhoneHistory({ active: () => alive, current: () => current,+ install(value, details) { installed.push({ marker: value.state.marker, current: current.id, sequence: current.sequence, full: Boolean(details) }); },+ changed() { if (history.status().complete && history.status().sequence === 8) done.resolve(); },+ failed(error) { failures.push(error.message); },+ });+ t.after(() => { alive = false; history.close(); aGate.resolve(); bGate.resolve(); });+ history.queue(a, 7); history.start(); await a.entered;+ current = { id: 'b', sequence: 8 };+ history.queue(b, 8); history.start(); aGate.resolve(); await b.entered;+ assert.deepEqual(installed.map(value => value.marker), ['a', 'b'], 'the completed predecessor did not replace the successor');+ current.sequence = 9;+ bGate.resolve(); await done.promise;+ assert.equal(current.sequence, 9, 'the history consumer never owns or rewinds the live cursor');+ assert.deepEqual(installed.map(value => value.full), [false, false], 'a checkpoint behind a new live move cannot overwrite its current presentation at completion');+ assert.deepEqual(history.status(), { loaded: 3, total: 3, complete: true, sequence: 8 });+ assert.equal(history.item(7).marker, 'b');+ assert.equal(history.shout(1).decision_answer.shout_text, 'b-answer');+ assert.deepEqual(failures, []);+ assert.deepEqual(a.counts(), { runs: 1, pruned: 0 });+ assert.deepEqual(b.counts(), { runs: 1, pruned: 1 });+ history.queue(b, 8); history.start();+ assert.equal(b.counts().runs, 1, 'a completed checkpoint is not streamed repeatedly by foreground reads');+});++test('access loss discards held details and late background results cannot install or advertise completion [H15,H17]', async () => {+ const gate = deferred(), source = page('removed', gate);+ let alive = true, installs = 0, failures = 0;+ const current = { id: 'removed', sequence: 1 };+ const history = createPhoneHistory({ active: () => alive, current: () => current,+ install() { installs++; }, changed() {}, failed() { failures++; },+ });+ history.queue(source, 1); history.start(); await source.entered;+ alive = false; current.id = undefined; history.close(); gate.resolve(); await source.closed;+ assert.equal(installs, 1); assert.equal(failures, 0);+ assert.equal(history.item(7), null); assert.equal(history.shout(1), null);+ assert.deepEqual(history.status(), { loaded: 0, total: null, complete: false, sequence: null });+});++test('partial history retains a readable current board and reports a failed incomplete progress state [H15,H17]', async t => {+ const source = page('partial', null, 4), failed = deferred();+ let current = null, history;+ history = createPhoneHistory({ active: () => true, current: () => ({ id: 'partial', sequence: 2 }),+ install(value) { current = value; }, changed() {}, failed(error) { failed.resolve(error); },+ });+ t.after(() => history.close());+ history.queue(source, 2); history.start();+ assert.match((await failed.promise).message, /incomplete/u);+ assert.equal(current.state.marker, 'partial');+ assert.equal(history.status().complete, false);+ assert.equal(history.status().loaded, 3);+ assert.equal(history.status().total, 4);+ assert.match(history.status().error, /Older history/u);+ assert.equal(history.item(7), null, 'an incomplete stream never becomes completed detail authority');+});