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: draft mixed local and relay board transport [N40]
Corey Olson0564206b3f3c
diff --git a/src/cockpit.js b/src/cockpit.jsindex 4cea4c8f..7b8a9d42 100644--- a/src/cockpit.js+++ b/src/cockpit.js@@ -36,10 +36,10 @@ function lifecycle() {* The Roadmap tab has its own address (N38): /roadmap on a host that serves the page there too,* which `paths` declares, and a #roadmap fragment anywhere else, such as a snapshot hosted under a* folder, where a path the host does not serve would leave a reload with nothing.- * The hosted page at https://app.pullboard.dev passes hostedLocal (N26, #513): on the machine that runs pullboard- * view, the page reads that view straight, writable, and the relay transport is never loaded; on any other device it- * is the relay page as before when relaySession says the request has a relay session, and otherwise it says why it- * cannot read a board here and links signIn.+ * The hosted page at https://app.pullboard.dev passes hostedLocal (N26, #513): on this machine it reads the local view+ * and any linked relay boards through their own transports; local boards are writable, relay boards remain read-only.+ * On another device it uses the relay when relaySession says the request has a session, and otherwise explains how to+ * connect or sign in.** @param {string} [key] - The session's secret.* @param {{snapshot?: boolean, readOnly?: boolean, requests?: boolean, transportModule?: string|null, apiBase?: string, apiHeaders?: Record<string, string>, stylesheet?: string, paths?: boolean, hostedLocal?: boolean, relaySession?: boolean, signIn?: string|null}} [options] - Served connection and assets, optional person requests over a read-only transport, host routes, a static page with event replay, or the hosted page that reads this machine's view first.@@ -186,10 +186,20 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requconst snapshot = ${JSON.stringify(snapshot)};let readOnly = ${JSON.stringify(readOnly)};let requests = ${JSON.stringify(requestMode)};+const pageReadOnly = ${JSON.stringify(readOnly)};+const pageRequests = ${JSON.stringify(requestMode)};+const relayRequestsEnabled = requests;let transportModule = ${moduleOption};const connection = ${connection};let transport = null;let transportLoadError = null;+// Hosted pages can read two independent authorities at once. Local boards use the view's API; relay boards+// retain the relay client's device-only decryption and event stream. The board id, never a mutable global mode,+// selects the authority for each request.+const boardSources = new Map();+const localBoardIds = new Set();+let localReadBase = connection.base;+let localReadHeaders = { ...connection.headers };// The hosted page (N26, #513): at https://app.pullboard.dev, on the machine that runs pullboard view, the page reads// that view straight instead of the relay. The view hands it the session's secret by a round trip that ends back here// with the secret in the address's fragment, which no request carries; the page takes it out of the address before@@ -358,10 +368,10 @@ async function connectLocal() {if (!localSession) return localTrip(base) ? 'away' : 'unreachable';connection.base = localSession.origin;connection.headers = { 'x-pullboard-key': localSession.key };+ localReadBase = connection.base;+ localReadHeaders = { ...connection.headers };readOnly = false;requests = false;- transportModule = null;- transport = null;document.body.classList.remove('read-only', 'requests');hideRelayNotice();localNote(null);@@ -906,16 +916,31 @@ function flowSvg(p) {/** Read or move through API v1, retaining the rule and repair guidance in a refusal. */async function api(path, body) {- if (body && (snapshot || readOnly)) throw new Error(snapshot ? 'This is a read-only snapshot.' : 'This is a read-only view.');- if (transportModule) {- if (transport) return transport.request(path, body);- if (transportLoadError) throw transportLoadError;- throw new Error('The browser transport is still loading.');- }- path = snapshot ? path.split('?')[0].slice(1) + '.json' : connection.base + path;- const res = await fetch(path, { method: body ? 'POST' : 'GET', headers: snapshot ? {} : { ...connection.headers, ...(body ? { 'content-type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined });+ if (snapshot) {+ if (body !== undefined && body !== null) throw new Error('This is a read-only snapshot.');+ const res = await fetch(path.split('?')[0].slice(1) + '.json');+ const json = await res.json();+ if (!res.ok) throw new Error(json.error || res.status);+ return json;+ }+ if (path === '/api/v1/boards') return await listedBoards();+ const boardId = /^\\/api\\/v1\\/boards\\/([0-9a-f]{32})(?:\\/|$)/u.exec(path)?.[1];+ const source = boardId ? boardSources.get(boardId) : null;+ if (boardId && !source) throw new Error('This board is not available in the current view. Refresh the board list and retry.');+ if (boardId && source?.kind === 'relay') {+ if (body !== undefined && body !== null) throw new Error('Relay boards are read-only in this view.');+ if (!transport) throw transportLoadError || new Error('The relay transport is still loading.');+ const reply = await transport.request(path, body);+ if (path.includes('/state') && reply.state) return { ...reply, state: { ...reply.state, root: source.board.root } };+ return reply;+ }+ if (body && (hosted.local ? readOnly && source?.kind !== 'local' : pageReadOnly)) throw new Error('This is a read-only view.');+ const base = source?.kind === 'local' ? localReadBase : connection.base;+ const headers = source?.kind === 'local' ? localReadHeaders : connection.headers;+ path = base + path;+ const res = await fetch(path, { method: body ? 'POST' : 'GET', headers: { ...headers, ...(body ? { 'content-type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined });const json = await res.json();- if (localSession && connection.base === localSession.origin && !snapshot) {+ if (localSession && base === localSession.origin) {if (res.status === 401 || res.status === 403) localExpired();else if (res.ok && !localConfirmed) { localConfirmed = true; tabValue(LOCAL_TRIPS, null); }}@@ -927,9 +952,76 @@ async function api(path, body) {return json;}+/** Read this machine's API list and the signed-in relay list, preferring a local registration with the same id. */+async function listedBoards() {+ let local = { boards: [], warnings: [] };+ let relay = { boards: [], warnings: [] };+ const hasLocal = hosted.local ? Boolean(localReadBase) && Boolean(localSession) : transportModule === null;+ if (hasLocal) {+ try {+ const response = await fetch(localReadBase + '/api/v1/boards', { headers: localReadHeaders, cache: 'no-store' });+ const value = await response.json();+ if ((response.status === 401 || response.status === 403) && localSession && localReadBase === localSession.origin) {+ localExpired();+ throw new Error('The local view session expired; reconnecting to this machine.');+ }+ if (!response.ok) throw new Error(value.error?.message || String(response.status));+ if (localSession && localReadBase === localSession.origin && !localConfirmed) { localConfirmed = true; tabValue(LOCAL_TRIPS, null); }+ local = value;+ } catch (error) {+ if (!transport) throw error;+ localNote(String(error.message || error), true);+ }+ }+ if (!hasLocal && transportModule && !transport) throw transportLoadError || new Error('The browser transport is still loading.');+ if (transport) {+ try { relay = await transport.request('/api/v1/boards'); }+ catch (error) {+ if (!hosted.local || !hasLocal) throw error;+ localNote('Linked boards are unavailable: ' + String(error.message || error), true);+ }+ }+ boardSources.clear();+ localBoardIds.clear();+ const boards = [];+ for (const board of local.boards || []) {+ if (typeof board.id !== 'string') continue;+ const row = { ...board, source: 'local' };+ boardSources.set(row.id, { kind: 'local', board: row });+ localBoardIds.add(row.id);+ boards.push(row);+ }+ for (const board of relay.boards || []) {+ if (typeof board.id !== 'string' || boardSources.has(board.id)) continue;+ const row = { ...board, root: board.id, source: 'relay' };+ boardSources.set(row.id, { kind: 'relay', board: row });+ boards.push(row);+ }+ return { version: 1, boards, warnings: [...(local.warnings || []), ...(relay.warnings || [])] };+}++/** Set presentation controls for the selected board; API routing still checks the target board independently. */+function syncBoardMode(root) {+ if (snapshot) return;+ const board = data?.projects.find((entry) => entry.root === root && entry.ok);+ const source = board && boardSources.get(board.id);+ const relay = source?.kind === 'relay';+ readOnly = hosted.local ? relay || (transportModule !== null && !source) : pageReadOnly;+ requests = hosted.local ? Boolean(relay && relayRequestsEnabled) : pageRequests;+ document.body.classList.toggle('read-only', readOnly);+ document.body.classList.toggle('requests', requests);+}++/** Whether a selected project is backed by the read-only relay transport. */+function relayProject(root = view.root) {+ const board = data?.projects.find((entry) => entry.root === root && entry.ok);+ return boardSources.get(board?.id)?.kind === 'relay';+}+/** Send only literal person intent; the transport seals it and generic API writes stay refused. */async function sendPersonRequest(root, move) {if (!requests || snapshot || !readOnly) throw new Error('This view cannot send person requests.');+ if (!relayProject(root)) throw new Error('Person requests through the relay require a linked relay board.');if (!['add', 'shout', 'answer', 'hold', 'spec-approve', 'spec-decline'].includes(move.verb)) throw new Error('Choose a person action from the view controls.');if (!transport) throw transportLoadError || new Error('The browser transport is still loading.');return transport.request(boardPath(root) + '/moves', move);@@ -1140,7 +1232,7 @@ const credentials = new Map();/** Draw only allowlisted credential metadata; bearer values never enter page state or markup. */function renderCredentials() {const region = $('credentials');- region.hidden = snapshot || readOnly || Boolean(transportModule);+ region.hidden = snapshot || readOnly;if (region.hidden) { region.innerHTML = ''; return; }const state = credentials.get(view.root);/** Render an inventory timestamp without shortening its date or timezone. */@@ -1154,7 +1246,7 @@ function renderCredentials() {/** Load this board's public metadata on demand, without granting any person authority. */async function loadCredentials(root = view.root) {- if (snapshot || readOnly || transportModule) return;+ if (snapshot || relayProject(root) || (!hosted.local && pageReadOnly)) return;const state = credentials.get(root) || { tokens: [], message: '', busy: false };credentials.set(root, state);state.message = 'Loading agent credentials…';@@ -1169,7 +1261,7 @@ async function loadCredentials(root = view.root) {/** Revoke a listed id through the existing one-tap phone grant, then reread its public metadata. */async function revokeCredential(id) {- if (snapshot || readOnly || transportModule) return;+ if (snapshot || relayProject(view.root) || (!hosted.local && pageReadOnly)) return;const root = view.root, state = credentials.get(root);if (!state || state.busy || !state.tokens.some((row) => row.id === id && !row.revoked)) return;state.busy = true;@@ -1228,6 +1320,7 @@ async function refresh(fresh = null) {if (text !== seen) {seen = text;data = next;+ syncBoardMode(view.root);render();}if (changed) {@@ -1240,7 +1333,7 @@ async function refresh(fresh = null) {snapshotReplay.index = snapshotReplay.events.length;replayControls();}- if (!snapshot && !transportModule) follow();+ if (!snapshot) follow();$('live').textContent = snapshot ? 'read-only snapshot' : liveLine();}@@ -1293,7 +1386,7 @@ function follow() {const repos = data.group ? data.group.repos.map((repo) => [repo.root, repo.board]) : data.project ? [[view.root, data.project]] : [];const boards = repos.flatMap(([root, state]) => {const board = data.projects.find((entry) => entry.root === root && entry.ok);- return board ? [{ root, id: board.id, shown: latestEvent(state) }] : [];+ return board && localBoardIds.has(board.id) ? [{ root, id: board.id, shown: latestEvent(state) }] : [];});const key = boards.map((board) => board.id).join(',');// A board's events after the latest one this page shows are what changed it since.@@ -1365,16 +1458,16 @@ async function listen(entry) {entry.controller = controller;try {if (!controller) throw new Error('this browser cannot read a stream');- // The stream goes where every API read goes: the serving host's base, with its credential headers. One board has- // its own events; a group's repos share one multiplexed stream (#600).+ // Local board streams use the local view's base and credential, separate from the relay client's own streams.+ // One board has its own events; a group's local repos share one multiplexed stream (#600).const single = entry.boards.length === 1;- const path = connection.base + (single ? '/api/v1/boards/' + encodeURIComponent(entry.boards[0].id) + '/events'+ const path = localReadBase + (single ? '/api/v1/boards/' + encodeURIComponent(entry.boards[0].id) + '/events': '/api/v1/events?boards=' + entry.boards.map((board) => encodeURIComponent(board.id)).join(','));const res = await fetch(path, {- headers: { ...connection.headers, accept: 'text/event-stream', 'last-event-id': entry.cursor }, cache: 'no-store', signal: controller.signal,+ headers: { ...localReadHeaders, accept: 'text/event-stream', 'last-event-id': entry.cursor }, cache: 'no-store', signal: controller.signal,});// This machine's view refused the hosted page's secret, as after a restart with a new one: go round again (#513).- if ((res.status === 401 || res.status === 403) && localSession && connection.base === localSession.origin) { localExpired(); return; }+ if ((res.status === 401 || res.status === 403) && localSession && localReadBase === localSession.origin) { localExpired(); return; }if (!res.ok || !res.body) throw new Error('the board stream answered ' + res.status);entry.status = 'up';entry.offline = false;@@ -2447,7 +2540,7 @@ async function loadAddressedShout() {entry.shout = reply.shout;} catch (error) {const message = String(error.message || error);- entry.error = transportModule && !message.includes('NO_SHOUT')+ entry.error = relayProject(root) && !message.includes('NO_SHOUT')? 'This shout is older than the relay holds. Open its address in the local project view.': 'No shout #' + id + ' exists here. ' + message;}@@ -2668,7 +2761,7 @@ async function code(ref, before) {render();return;}- if (transportModule) {+ if (relayProject(view.root)) {c.error = 'Source code is unavailable in a relay view; open this reference in the local project view.';render();return;@@ -2688,7 +2781,7 @@ async function showAllCode(ref, before) {const c = view.code[root + '\\n' + before + '\\n' + ref];const parts = codeReferenceParts(ref);if (!c || c.allLoading) return;- if (transportModule) { c.error = 'Source code is unavailable in a relay view; open this reference in the local project view.'; render(); return; }+ if (relayProject(root)) { c.error = 'Source code is unavailable in a relay view; open this reference in the local project view.'; render(); return; }if (!parts) { c.error = 'Code reference has an invalid path, range or commit SHA.'; render(); return; }c.error = null;c.allLoading = true;@@ -2990,6 +3083,7 @@ function switchTo(root, target = null, record = true) {const generation = ++switchGeneration;answer(null);view.root = root;+ syncBoardMode(root);const item = typeof target === 'number' ? target : /^item:(\\d+)$/.exec(target || '');const requestedItem = typeof item === 'number' ? item : item ? Number(item[1]) : null;view.item = requestedItem;@@ -3287,7 +3381,7 @@ if (snapshot) {if (hosted.local) $('local-note-retry').addEventListener('click', () => {localProblem = null;tabValue(LOCAL_TRIPS, null);- // A page already on the relay starts again instead, so it never holds the relay's streams and the view's at once.+ // Reload both source-scoped connections together when relay streams are already active.if (transport) { location.reload(); return; }connectLocal().then((local) => local === 'local' ? refresh() : null).catch((error) => localNote(error.message, true));});@@ -3295,8 +3389,8 @@ if (hosted.local) $('local-note-retry').addEventListener('click', () => {async function startPage() {// The hosted page reads this machine's view when it can. When it cannot, it is the relay page as before, for a// person signed in to the relay; anyone else sees why, and the ways on.+ let local = 'unreachable';if (hosted.local && !relayPairing) {- let local = 'unreachable';if (localProblem) localNote(localProblem, true);else local = await connectLocal();if (local === 'away') return;@@ -3311,7 +3405,8 @@ async function startPage() {transport = configured;} catch (error) {transportLoadError = error;- throw error;+ if (hosted.local && local === 'local') localNote('Linked boards are unavailable: ' + String(error.message || error), true);+ else throw error;}}await refresh();diff --git a/test/cockpit/relay.test.js b/test/cockpit/relay.test.jsindex 7d7320b5..9bad6094 100644--- a/test/cockpit/relay.test.js+++ b/test/cockpit/relay.test.js@@ -8,6 +8,7 @@ import { delimiter, join, relative, resolve, sep } from 'node:path';import { after, test } from 'node:test';import { press, stableChrome } from './stable.js';import { cockpitPage } from '../../src/cockpit.js';+import { createRelayBrowserHandler } from '../../relay/browser-page.js';import { relayClientFixture } from '../relay-client-fixture.js';import { findChromeExecutable, relayWorkBudgetMs, startChrome } from '../relay-browser-fixture.js';import { BIN, scratch, SPEC, machine, project, fetchLive, startView, target, chromeExecutable, browserPause, openSnapshotChrome, stopOwnedChrome, closeSnapshotChrome } from './fixture.js';@@ -892,3 +893,193 @@ test('a configured transport never falls back while loading or after import failrmSync(profile, { recursive: true, force: true });}});++const JOURNEY_HOSTED = 'https://app.pullboard.dev';+const JOURNEY_LOCAL = 'http://127.0.0.1:4890';++/** Serve the relay's real browser page and proxy its API to the loopback relay fixture. */+async function journeyRelaySite(box, localOrigin) {+ const browser = createRelayBrowserHandler({+ async authenticate(req) {+ const token = /(?:^|;\s*)pb_session=([^;]+)/u.exec(req.headers.cookie || '')?.[1];+ if (!token) return { kind: 'anonymous' };+ try { return await box.auth.authenticate(token); } catch { return { kind: 'anonymous' }; }+ },+ });+ const server = createServer((req, res) => {+ const writeHead = res.writeHead.bind(res);+ res.writeHead = (status, headers, ...rest) => {+ if (headers && !Array.isArray(headers)) {+ const csp = Object.keys(headers).find((name) => name.toLowerCase() === 'content-security-policy');+ if (csp) headers[csp] = headers[csp].replace("connect-src 'self'", "connect-src 'self' " + localOrigin);+ }+ return writeHead(status, headers, ...rest);+ };+ void (async () => {+ if (await browser(req, res)) return;+ const headers = Object.fromEntries(Object.entries(req.headers).filter(([name]) => !['host', 'connection', 'content-length'].includes(name.toLowerCase())));+ const upstream = request(new URL(req.url, box.origin), { method: req.method, headers, agent: false }, (reply) => {+ const responseHeaders = Object.fromEntries(Object.entries(reply.headers).filter(([name]) => !['connection', 'transfer-encoding', 'keep-alive'].includes(name.toLowerCase())));+ res.writeHead(reply.statusCode || 502, responseHeaders);+ reply.pipe(res);+ });+ upstream.once('error', () => { if (!res.headersSent) res.writeHead(502); res.end(); });+ req.pipe(upstream);+ })().catch(() => { if (!res.headersSent) res.writeHead(500); res.end(); });+ });+ await new Promise((ready, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', ready); });+ return { server, base: 'http://127.0.0.1:' + server.address().port };+}++/** Route the hosted page and its fixed loopback discovery through owned fixture servers. */+async function interceptJourneyOrigins(chrome, site, view) {+ const failures = [];+ const tasks = [];+ const listener = ({ data }) => {+ const message = JSON.parse(String(data));+ if (message.method !== 'Fetch.requestPaused') return;+ tasks.push((async () => {+ const { requestId, request: asked } = message.params;+ const address = new URL(asked.url);+ const base = address.origin === JOURNEY_HOSTED ? site.base+ : [JOURNEY_LOCAL, view.base].includes(address.origin) ? view.base : null;+ if (!base) return chrome.send('Fetch.failRequest', { requestId, errorReason: 'ConnectionRefused' });+ const headers = Object.fromEntries(Object.entries(asked.headers).filter(([name]) => !['host', 'content-length'].includes(name.toLowerCase())));+ const response = await fetchLive(base + address.pathname + address.search, {+ method: asked.method, headers, redirect: 'manual',+ ...(asked.postData === undefined ? {} : { body: asked.postData }),+ signal: AbortSignal.timeout(10_000),+ });+ let body;+ if (response.headers.get('content-type')?.startsWith('text/event-stream')) {+ const reader = response.body.getReader();+ const first = await reader.read();+ await reader.cancel();+ body = Buffer.from(first.value || []);+ } else body = Buffer.from(await response.arrayBuffer());+ await chrome.send('Fetch.fulfillRequest', {+ requestId, responseCode: response.status,+ responseHeaders: [...response.headers].filter(([name]) => !['content-length', 'connection', 'transfer-encoding', 'keep-alive', 'date'].includes(name.toLowerCase())).map(([name, value]) => ({ name, value })),+ body: body.toString('base64'),+ });+ })().catch((error) => failures.push(error.message)));+ };+ chrome.socket.addEventListener('message', listener);+ await chrome.send('Fetch.enable', { patterns: [{ urlPattern: JOURNEY_HOSTED + '/*', requestStage: 'Request' }, { urlPattern: JOURNEY_LOCAL + '/*', requestStage: 'Request' }, { urlPattern: view.base + '/*', requestStage: 'Request' }] });+ return async () => {+ chrome.socket.removeEventListener('message', listener);+ try { await Promise.all(tasks); } finally { await chrome.send('Fetch.disable'); }+ assert.deepEqual(failures, [], 'the hosted and loopback fixture requests complete');+ };+}++test('the hosted page lists linked and local boards together [N26,H5]', {+ timeout: relayWorkBudgetMs() * 4 + 60_000,+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async (t) => {+ const executable = findChromeExecutable();+ if (!executable) return t.skip('Install Chrome or set PULLBOARD_CHROME to run the hosted mixed-board proof.');+ const linked = await relayClientFixture(t);+ const linkedId = linked.before.tables.board_meta.find((row) => row.meta_key === 'board_id').meta_value;+ const remoteTitle = 'linked machine A keeps its relay board';+ assert.equal((await linked.cli('add', linked.lane, remoteTitle)).code, 0, 'machine A creates a real relay fixture item');+ await linked.link();+ const linkedKey = readFileSync(linked.keyFile, 'utf8').trim();++ const local = machine();+ const localProject = project(local, 'local-machine-b');+ const localTitle = 'local machine B keeps its own view board';+ local.run(localProject.repo, 'add', 'web', localTitle);+ const duplicateProject = project(local, 'local-machine-c');+ const duplicateTitle = 'local machine C keeps its own view board';+ local.run(duplicateProject.repo, 'add', 'web', duplicateTitle);+ assert.equal((await linked.cliAt(duplicateProject.repo, 'relay', 'on', '--url', linked.origin)).code, 0,+ 'C links its actual local board to the relay as a second source for the same board identity');+ const localRelay = JSON.parse(readFileSync(join(duplicateProject.repo, '.git', 'pullboard', 'relay.json'), 'utf8'));+ const localRelayKey = readFileSync(join(linked.env.PULLBOARD_HOME, 'relay-keys', localRelay.board + '.key'), 'utf8').trim();+ assert.notEqual(localRelay.board, linkedId, 'the linked C board is distinct from A');+ const profile = join(linked.root, 'mixed-board-chrome');+ let localView;+ let site;+ let chrome;+ let stopOrigins;+ try {+ localView = await startView(local);+ site = await journeyRelaySite(linked, localView.base);+ chrome = await openSnapshotChrome(executable, 'about:blank', profile);+ stopOrigins = await interceptJourneyOrigins(chrome, site, localView);+ const session = await linked.phoneSession();+ assert.equal((await chrome.send('Network.setCookie', {+ name: 'pb_session', value: session.token, url: JOURNEY_HOSTED, httpOnly: true, sameSite: 'Lax',+ })).success, true, 'the fixture person session is installed only in this private browser');+ for (const permissions of [['loopbackNetwork', 'localNetwork', 'localNetworkAccess'], ['localNetworkAccess']]) {+ try { await chrome.send('Browser.grantPermissions', { origin: JOURNEY_HOSTED, permissions }); break; } catch { /* Chrome versions expose different local-network permission names. */ }+ }++ // Pair the real board key in the fragment; the relay client consumes it into device storage before local discovery.+ await chrome.send('Page.navigate', { url: JOURNEY_HOSTED + '/#board=' + linkedId + '&key=' + encodeURIComponent(linkedKey) });+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(remoteTitle) + ')', 30_000);+ await chrome.waitFor('location.hash === ""', 10_000);++ // C's real local board is also paired on the relay so this catches duplicate-ID source preference.+ await chrome.send('Page.navigate', { url: JOURNEY_HOSTED + '/#board=' + localRelay.board + '&key=' + encodeURIComponent(localRelayKey) });+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(duplicateTitle) + ')', 30_000);++ // The hosted page's real local-view handoff discovers B without a pasted key, URL or port.+ await chrome.send('Page.navigate', { url: JOURNEY_HOSTED + '/' });+ await chrome.waitFor("[...document.querySelectorAll('#proj-list .proj.repo')].some(row => row.textContent.includes('fixture/repository')) && [...document.querySelectorAll('#proj-list .proj.repo')].some(row => row.textContent.includes('local-machine-b')) && [...document.querySelectorAll('#proj-list .proj.repo')].some(row => row.textContent.includes('local-machine-c'))");+ const localList = await (await fetchLive(localView.base + '/api/v1/boards', { headers: { 'x-pullboard-key': localView.key } })).json();+ const localId = localList.boards.find((board) => board.name === 'local-machine-b').id;+ const duplicateId = localList.boards.find((board) => board.name === 'local-machine-c').id;+ assert.equal(duplicateId, localRelay.board, 'C has one real board identity at both sources');+ const localOrigin = await chrome.stable('localSession?.origin || null');+ assert.equal(localOrigin, localView.base, 'the page keeps the ephemeral local origin from its real handoff');+ const rows = JSON.parse(await chrome.stable('JSON.stringify({ projects: data.projects.map(({id,name,root,source}) => ({id,name,root: source === \"relay\" ? \"relay\" : \"local\",source})), labels: [...document.querySelectorAll(\"#proj-list .proj.repo .pname\")].map(node => node.textContent), secretInAddress: /key=|pullboard-local=/.test(location.href) })'));+ assert.deepEqual(rows.labels.sort(), ['fixture/repository', 'local-machine-b', 'local-machine-c'], 'the page shows unlinked B and linked C locally beside A from the relay');+ assert.deepEqual(rows.projects.map((row) => row.id).sort(), [linkedId, localId, duplicateId].sort(), 'the hosted view keeps A, B and C identities');+ assert.equal(rows.projects.find((row) => row.id === linkedId).root, 'relay', 'a remote board uses an opaque root, not A’s filesystem path');+ assert.equal(rows.projects.find((row) => row.id === localId).source, 'local', 'unlinked B remains a local board');+ assert.equal(rows.projects.find((row) => row.id === duplicateId).source, 'local', 'C wins when its actual identity is present through both sources');+ assert.equal(rows.secretInAddress, false, 'the hosted page removes pairing and local-session fragments');+ assert.equal(rows.projects.filter((row) => row.id === duplicateId).length, 1, 'the duplicate local/relay identity appears once in the composed list');++ const localRow = "Array.from(document.querySelectorAll('#proj-list .proj.repo')).find(row => row.textContent.includes('local-machine-b'))";+ await press(chrome, localRow);+ await chrome.waitFor("view.root === data.projects.find(row => row.name === 'local-machine-b').root && document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(localTitle) + ") && !readOnly && !requests");+ const duplicateRow = "Array.from(document.querySelectorAll('#proj-list .proj.repo')).find(row => row.textContent.includes('local-machine-c'))";+ await press(chrome, duplicateRow);+ await chrome.waitFor("view.root === data.projects.find(row => row.id === " + JSON.stringify(duplicateId) + ").root && document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(duplicateTitle) + ") && !readOnly && !requests");+ const remoteRow = "Array.from(document.querySelectorAll('#proj-list .proj.repo')).find(row => row.textContent.includes('fixture/repository'))";+ await press(chrome, remoteRow);+ await chrome.waitFor("view.root === data.projects.find(row => row.id === " + JSON.stringify(linkedId) + ").root && readOnly && requests");++ assert.ok(linked.calls.some((call) => call.method === 'GET' && call.path === '/api/v1/boards/' + linkedId + '/state'),+ 'the relay board state is read through its relay transport');+ assert.ok(linked.calls.some((call) => call.method === 'GET' && call.path.startsWith('/api/v1/boards/' + linkedId + '/events')),+ 'the relay board events use the relay client stream');+ const localReads = chrome.requests.filter((entry) => entry.url.startsWith(localOrigin + '/api/v1/boards/'));+ assert.ok(localReads.some((entry) => new URL(entry.url).pathname === '/api/v1/boards/' + localId + '/state'),+ 'B board state is read through B’s local view');+ assert.ok(localReads.some((entry) => new URL(entry.url).pathname === '/api/v1/boards/' + localId + '/events'),+ 'B board events use B’s local view stream');+ assert.ok(localReads.some((entry) => new URL(entry.url).pathname === '/api/v1/boards/' + duplicateId + '/state'),+ 'C board state uses C’s local view despite its paired relay copy');+ assert.ok(localReads.some((entry) => new URL(entry.url).pathname === '/api/v1/boards/' + duplicateId + '/events'),+ 'C board events use C’s local view despite its paired relay copy');+ assert.equal(localReads.some((entry) => new URL(entry.url).pathname.includes(linkedId)), false,+ 'the local view never receives A’s relay board id');+ assert.deepEqual(chrome.exceptions, [], 'the hosted mixed-board page reports no uncaught browser exceptions');+ } finally {+ try { if (stopOrigins) await stopOrigins(); }+ finally {+ try { if (chrome) await closeSnapshotChrome(chrome); }+ finally {+ try { if (localView) await localView.stop(); }+ finally {+ try { if (site?.server) { site.server.closeAllConnections(); if (site.server.listening) await new Promise((done) => site.server.close(done)); } }+ finally { rmSync(profile, { recursive: true, force: true }); }+ }+ }+ }+ }+});