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): compose bounded phone startup on trunk [N26,H5,H17]

Corey Olson768c43d72990
diff --cc relay/browser-approval-card.js
index 8087ea88,718788c1..5dc3c499
--- a/relay/browser-approval-card.js
+++ b/relay/browser-approval-card.js
@@@ -36,7 -36,7 +36,8 @@@ 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; }
+ .relay-panel #phone-approvals { margin-top: 20px; text-align: left; }
+.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; }
@@@ -44,24 -44,17 +45,40 @@@
.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;
++ placePhoneApprovals(doc);
+ 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;
+}
++
+ /** Keep the same authenticated cards and live handlers on the phone's visible screen until a board can draw. */
+ export function placePhoneApprovals(doc) {
+ const panel = doc.getElementById('phone-approvals');
+ if (!panel) return null;
+ const root = doc.documentElement;
+ const frame = root?.dataset.relayDevice === 'phone' && root.dataset.relayScreen === 'share'
+ ? doc.querySelector('#relay-screen .relay-panel[data-screen="share"]') : null;
+ const host = frame ?? doc.querySelector('main');
+ if (!host || panel.parentElement === host) return panel;
+ const mark = frame?.querySelector('.relay-mark');
+ if (mark) mark.after(panel);
+ else host.prepend(panel);
+ return panel;
+ }
diff --cc relay/browser-client.js
index 6df52fcb,670e467b..ebce0a31
--- a/relay/browser-client.js
+++ b/relay/browser-client.js
@@@ -8,8 -8,7 +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 { placePhoneApprovals } from './browser-approval-card.js';
+import { browserJSON, withBrowserDeadline } from './browser-deadline.js';
- import { phoneApprovalStatus } from './browser-approval-card.js';
++import { phoneApprovalStatus, placePhoneApprovals } from './browser-approval-card.js';
const KEYS = 'pullboard.relay.keys.v1';
const PENDING = 'pullboard.relay.pair.v1';
@@@ -180,9 -178,10 +180,10 @@@ export async function createTransport(
}
// 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(' ') : '');
+ placePhoneApprovals(document);
}
/** Ask once after pairing; a refusal leaves one dismissible line under the board, never above it. */
diff --cc test/relay-person-page.test.js
index 1a6af7c5,94254cc6..49178001
--- a/test/relay-person-page.test.js
+++ b/test/relay-person-page.test.js
@@@ -12,76 -13,103 +13,173 @@@ import { runFixtureGit } from './fixtur
const chromeOptions = { skip: !findChromeExecutable() && 'Chrome is not installed' };
+ /** Wait for a private native setup transition without repeating its command or weakening an assertion. */
+ async function phoneSetupState(read, message) {
+ const deadline = Date.now() + 20_000; // budget: declared hang ceiling for a private enrollment/approval metadata transition.
+ while (Date.now() < deadline) {
+ const value = read();
+ if (value) return value;
+ await new Promise(resolveWait => setTimeout(resolveWait, 25));
+ }
+ assert.fail(message);
+ }
+
+ test('a phone with no readable board can tap its pending link and open that board [N26,H5,H17]', chromeOptions, async t => {
+ const box = await relayClientFixture(t);
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ // Set the input device before navigation; resizing a page after its desktop startup cannot prove the phone path.
+ await chrome.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
+ await chrome.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: `const phoneFixtureFetch = window.fetch;
+ window.fetch = (input, options) => {
+ const url = new URL(typeof input === 'string' ? input : input.url, location.href);
+ if (['http://127.0.0.1:4890', 'http://localhost:4890'].includes(url.origin)) return Promise.reject(new TypeError('No local view in this private phone fixture'));
+ return phoneFixtureFetch(input, options);
+ };` });
+ assert.equal((await chrome.send('Network.setCookie', {
+ name: 'pb_session', value: (await box.phoneSession()).token, url: box.origin, httpOnly: true, sameSite: 'Lax',
+ })).success, true, 'only the synthetic fixture session is installed');
+ const setup = box.startCli(['relay', 'on', '--all', '--url', box.origin]);
+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');
+ const pending = await phoneSetupState(() => existsSync(machineFile) && JSON.parse(readFileSync(machineFile, 'utf8')).pending,
+ 'the native command publishes its one-time phone enrollment');
+ await chrome.navigate(box.origin + '/#device=' + pending.locator + '.' + pending.secret);
+ const paired = await setup.closed;
+ assert.equal(paired.code, 0, 'native setup authenticates this browser and delivers its original board key');
+ await chrome.waitFor("document.documentElement.dataset.relayDevice === 'phone' && document.querySelector('#phone-approvals') !== null");
+
+ const publisher = JSON.parse(readFileSync(box.linkFile, 'utf8')).board;
+ // Only the phone cannot read its publisher; keep native setup healthy and preserve each real authorization read.
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: `const authorizedPhoneFetch = window.fetch;
+ window.fetch = async (input, options) => {
+ const url = new URL(typeof input === 'string' ? input : input.url, location.href);
+ const response = await authorizedPhoneFetch(input, options);
+ if (url.pathname === ${JSON.stringify('/api/v1/boards/' + publisher + '/state')} && response.ok) {
+ return new Response(JSON.stringify({ version: 1, error: { code: 'NO_SNAPSHOT', message: 'This private phone snapshot is unavailable.' } }), {
+ status: 404, headers: { 'content-type': 'application/json' },
+ });
+ }
+ return response;
+ };` });
+ box.providerState.repositories.push('phone-first-link');
+ const target = join(dirname(box.root), 'phone-first-link');
+ mkdirSync(target);
+ for (const args of [['init', '-q', '-b', 'main'], ['-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-q', '-m', 'fixture base'],
+ ['remote', 'add', 'origin', '[email protected]:fixture/phone-first-link.git']]) {
+ runFixtureGit(args, { cwd: target, env: box.env, encoding: 'utf8' });
+ }
+ assert.equal((await box.cliAt(target, 'init')).code, 0, 'the actual new-project init publishes its sealed approval');
+ const marker = 'FIRST_READABLE_BOARD_AFTER_ONE_PHONE_TAP_901';
+ assert.equal((await box.cliAt(target, 'add', box.lane, marker)).code, 0);
+ const proposal = JSON.parse(readFileSync(machineFile, 'utf8')).approvals.find(entry => entry.root === target);
+ assert.equal(proposal?.published, true, 'the actual native proposal is waiting for this enrolled browser');
+ const selector = '#phone-approve-' + proposal.context.id;
+ const beforeForeground = box.calls.length;
+ const run = box.startCli(['relay', 'on', '--all', '--url', box.origin], {}, { json: false });
+ await phoneSetupState(() => box.calls.slice(beforeForeground).some(call => call.method === 'GET'
+ && call.path === '/api/v1/devices/approvals/' + proposal.context.id), 'the same foreground command is actually waiting for this approval');
+ await chrome.navigate('about:blank');
+ await chrome.navigate(box.origin);
+ await chrome.waitFor(`document.querySelector(${JSON.stringify(selector)}) !== null && Array.isArray(data?.projects)`);
+ const before = await chrome.evaluate(`(() => {
+ const button = document.querySelector(${JSON.stringify(selector)});
+ const rect = button.getBoundingClientRect();
+ return { phone: document.documentElement.dataset.relayDevice, screen: document.documentElement.dataset.relayScreen,
+ listed: data?.projects?.length ?? null, shown: rect.width > 0 && rect.height > 0, cards: document.querySelectorAll('.phone-approval').length };
+ })()`);
+ console.log(JSON.stringify({ firstPhoneApprovalControl: before }));
+ assert.equal(before.phone, 'phone');
+ assert.equal(before.listed, 0, 'no readable board can dismiss the first screen');
+ assert.equal(run.child.exitCode, null, 'the native foreground command is still waiting for the person');
+ assert.equal(before.shown, true, 'the pending native approval must be visible, not merely present under the hidden board shell');
+ await chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).scrollIntoView({ block: 'center' })`);
+ const point = await chrome.evaluate(`(() => {
+ const button = document.querySelector(${JSON.stringify(selector)}); const rect = button.getBoundingClientRect();
+ const x = rect.left + rect.width / 2, y = rect.top + rect.height / 2;
+ return { x, y, hit: button.contains(document.elementFromPoint(x, y)) };
+ })()`);
+ assert.equal(point.hit, true, 'the actual input target is the approval button');
+ const authorizations = box.calls.filter(call => call.path.endsWith('/authorize')).length;
+ await chrome.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: point.x, y: point.y }] }, 'touch the visible native approval');
+ await chrome.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }, 'release the single approval tap');
+ const linked = await run.closed;
+ assert.equal(linked.code, 0, 'the same foreground command finishes after one real phone tap');
+ await chrome.waitFor(`document.body.innerText.includes(${JSON.stringify(marker)}) && data?.root === ${JSON.stringify(proposal.context.board)}`);
+ assert.equal(await chrome.evaluate('document.documentElement.dataset.relayScreen ?? null'), null, 'the readable board replaces the first screen');
+ assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length - authorizations, 1, 'one tap authorizes exactly once');
+ });
+
+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' }) });