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): approval cards name the computer and the board [H17,H5]
Corey Olsonf06ebc37b5b1
diff --git a/relay/browser-approval-card.js b/relay/browser-approval-card.jsnew file mode 100644index 00000000..12da6043--- /dev/null+++ b/relay/browser-approval-card.js@@ -0,0 +1,43 @@+/** The words on a paired phone's approval card: which computer asks, which board, and until when [H17,H5]. */++/** Keep one sealed display name only when it is a short single line; otherwise the card falls back. */+function displayName(value) {+ return typeof value === 'string' && value.trim() && value.length <= 200 && !/[\u0000-\u001f\u007f]/u.test(value) ? value.trim() : null;+}++/**+ * Read the computer and board names a native request sealed with its intent.+ * Why fall back: a request queued by an older pullboard carries no names, and the card must still read as words.+ */+export function approvalNames(intent, context) {+ const names = intent?.names ?? {};+ const repository = context.action === 'link' ? context.target.split('/').pop() : null;+ return { computer: displayName(names.computer) ?? 'your computer', board: displayName(names.board) ?? repository ?? 'this board' };+}++/** Show an expiry as a time in this phone's own time zone. */+export function localExpiry(expires) {+ return new Date(expires).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });+}++/** Write the card's question and its one line of detail, naming the computer and the board. */+export function approvalCardText(context, names) {+ const expires = 'expires ' + localExpiry(context.expires);+ if (context.action === 'link') return { title: 'Link ' + names.board + ' from ' + names.computer + '?', detail: context.target + ' · ' + expires };+ if (context.action === 'delete-board') return { title: 'Delete ' + names.board + ' from the relay?', detail: 'Asked from ' + names.computer + ' · ' + expires };+ return { title: context.command, detail: 'Asked from ' + names.computer + ' · ' + expires };+}++/** Confirm a finished delete in words once the relay reports the board gone. */+export function deletedText(names) {+ return names.board + ' was deleted from the relay.';+}++/** Card spacing for the relay page; served after the shared view styles. */+export const APPROVAL_CARD_STYLES = `+.phone-approval { display: grid; gap: 10px; padding: 14px 16px; }+.phone-approval p { margin: 0; overflow-wrap: anywhere; }+.phone-approval-title { font-weight: 600; }+.phone-approval-detail { color: var(--ink-muted); }+.phone-approval button { justify-self: start; }+`;diff --git a/relay/browser-devices.js b/relay/browser-devices.jsindex f894ff85..ed99c5de 100644--- a/relay/browser-devices.js+++ b/relay/browser-devices.js@@ -5,6 +5,7 @@ import { ENGINE_VERSION } from './engine.js';import { Refused } from './refused.js';import { approvalContext, openApproval, sealApproval, verifyApprovalIntent } from './relay-approval.js';import { devicePublicKey } from './device-keys.js';+import { approvalCardText, approvalNames, deletedText } from './browser-approval-card.js';const PENDING = 'pullboard.relay.device-pair.v1';@@ -127,7 +128,7 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved) {try {const response = await documentAt('/api/v1/devices/' + device.deviceId + '/approvals');const ids = new Set(response.approvals.map(value => value.context.id));- for (const child of [...panel.children]) if (!ids.has(child.dataset.request) && !active.has(child.dataset.request)) child.remove();+ for (const child of [...panel.children]) if (child.dataset.request && !ids.has(child.dataset.request) && !active.has(child.dataset.request)) child.remove();for (const row of response.approvals) {const context = approvalContext(row.context);if (context.device !== device.deviceId || context.account !== device.account || Date.now() >= context.expires ||@@ -140,8 +141,10 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved) {if (JSON.stringify(approvalContext(intent.context)) !== JSON.stringify(context)) throw new Refused('PHONE_APPROVAL_AUTH', 'The displayed request differs from its sealed action.');const replyKey = devicePublicKey(intent.replyKey);const card = document.createElement('div'); card.className = 'phone-approval'; card.dataset.request = context.id;- const text = document.createElement('p');- text.textContent = context.command + ' · board ' + context.board + ' · target ' + context.target + ' · machine ' + context.machine + ' · expires ' + new Date(context.expires).toISOString();+ const names = approvalNames(intent, context);+ const words = approvalCardText(context, names);+ const text = document.createElement('p'); text.className = 'phone-approval-title'; text.textContent = words.title;+ const detail = document.createElement('p'); detail.className = 'phone-approval-detail'; detail.textContent = words.detail;const button = document.createElement('button'); button.type = 'button'; button.id = 'phone-approve-' + context.id;button.textContent = context.action === 'link' ? 'Link project' : context.action === 'delete-board' ? 'Delete relay copy' : 'Approve revocation';/** Issue once on this tap, then encrypt the result to the native command's private RAM reply key. */@@ -157,11 +160,15 @@ export async function installPhoneApprovals(documentAt, boardKeys, onApproved) {await documentAt('/api/v1/devices/approvals/' + context.id + '/complete', {method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ response }),});- card.remove(); await onApproved();+ if (context.action === 'delete-board' && authorized.result?.deleted === context.board) {+ const done = document.createElement('p'); done.setAttribute('role', 'status'); done.textContent = deletedText(names);+ delete card.dataset.request; card.className = 'phone-approval phone-approval-done'; card.replaceChildren(done);+ } else card.remove();+ await onApproved();} catch (error) { text.textContent = 'Approval failed: ' + (error instanceof Refused ? error.message : 'Request the action again from the Mac.'); }finally { active.delete(context.id); }};- card.append(text, button); panel.append(card);+ card.append(text, detail, button); panel.append(card);}} catch (error) {if (error?.code !== 'DEVICE_NOT_ENROLLED') panel.setAttribute('data-error', 'Approval requests are unavailable. Retry from the Mac.');diff --git a/relay/browser-page.js b/relay/browser-page.jsindex 0847cfbe..7402ee78 100644--- a/relay/browser-page.js+++ b/relay/browser-page.js@@ -4,8 +4,9 @@ import { readFileSync } from 'node:fs';import { cockpitPage } from '../src/cockpit.js';import { ENGINE_VERSION } from '../src/machine.js';import { Refused } from '../src/refused.js';+import { APPROVAL_CARD_STYLES } from './browser-approval-card.js';-const STYLES = readFileSync(new URL('../src/view.css', import.meta.url), 'utf8');+const STYLES = readFileSync(new URL('../src/view.css', import.meta.url), 'utf8') + APPROVAL_CARD_STYLES;/** Refuse relay startup locally while the public shell has no relay session; keep its sign-in link and never reload. */const SIGN_IN_TRANSPORT = '/** Preserve device-only pairing before sign-in without starting relay reads. */\nimport { rememberPairing } from "./client.js";\nimport { registerApp } from "./install.js";\nexport function createTransport() {\n void registerApp();\n rememberPairing();\n throw new Error("Sign in with GitHub to open your linked boards.");\n}\n';@@ -34,6 +35,7 @@ export function createRelayBrowserHandler({ authenticate }) {['/relay/device-keys.js', ['text/javascript', readFileSync(new URL('../src/relay-device-keys.js', import.meta.url), 'utf8')]],['/relay/relay-approval.js', ['text/javascript', readFileSync(new URL('../src/relay-approval.js', import.meta.url), 'utf8').replace("'./relay-device-keys.js'", "'./device-keys.js'")]],['/relay/browser-devices.js', ['text/javascript', readFileSync(new URL('./browser-devices.js', import.meta.url), 'utf8')]],+ ['/relay/browser-approval-card.js', ['text/javascript', readFileSync(new URL('./browser-approval-card.js', import.meta.url), 'utf8')]],['/relay/client.js', ['text/javascript', readFileSync(new URL('./browser-client.js', import.meta.url), 'utf8')]],['/relay/sign-in.js', ['text/javascript', SIGN_IN_TRANSPORT]],['/relay/browser-notice.js', ['text/javascript', readFileSync(new URL('./browser-notice.js', import.meta.url), 'utf8')]],diff --git a/src/relay-phone.js b/src/relay-phone.jsindex 79d42250..dc7dff90 100644--- a/src/relay-phone.js+++ b/src/relay-phone.js@@ -1,9 +1,13 @@/** Native approval requests never retain a person grant or its reply key [H5,H16,H17,B26]. */import { randomUUID } from 'node:crypto';+import { hostname } from 'node:os';+import { basename } from 'node:path';import { approvalContext, createApprovalReply, openApproval, sealApproval, signApprovalIntent } from './relay-approval.js';import { readBoardKey } from './relay-key.js';import { readRelayMachine } from './relay-machine.js';import { requirePersonChannel } from './person.js';+import { repoInfo } from './git.js';+import { listApiProjects } from './projects.js';import { Refused } from './refused.js';/** Select only a phone whose public key was MAC-authenticated into this native machine's roster. */@@ -13,15 +17,25 @@ export function approvalPhone(state) {return device;}+/**+ * The words the phone shows for a request: this computer's host name and, given its folder, the board's own name.+ * Why sealed with the intent: the relay never sees them, and the board key's MAC stops it changing them.+ */+export function proposalNames(root) {+ if (!root) return { computer: hostname() };+ const project = repoInfo(root).root;+ return { computer: hostname(), board: listApiProjects().find(entry => entry.root === project)?.name ?? basename(project) };+}+/** Build a sealed immutable proposal; only new-board link replies can have a durable private key. */-export async function phoneProposal(state, action, target, { board = state.board, command, link = false } = {}) {+export async function phoneProposal(state, action, target, { board = state.board, command, link = false, root } = {}) {if (!/^pm_[A-Za-z0-9_-]{43}$/u.test(state.token ?? '')) throw new Refused('RELAY_SESSION', 'Run pullboard relay on --all to replace the old person session with board machine credentials.');const phone = approvalPhone(state);const reply = await createApprovalReply({ link });const context = approvalContext({ id: randomUUID(), account: state.account, publisher: state.board, board,device: phone.deviceId, action, target, machine: state.machine,command: command ?? 'pullboard relay ' + (action === 'revoke-device' || action === 'revoke-token' ? 'revoke ' + target : 'off'), expires: Date.now() + 600_000 });- const envelope = await sealApproval({ context, replyKey: reply.publicKey }, phone.publicKey, context, 'intent');+ const envelope = await sealApproval({ context, replyKey: reply.publicKey, names: proposalNames(root) }, phone.publicKey, context, 'intent');const mac = await signApprovalIntent(readBoardKey(state.board), envelope);return { context, sealed: Buffer.from(JSON.stringify({ envelope, mac })).toString('base64url'), reply };}diff --git a/src/relay-setup.js b/src/relay-setup.jsindex ef931dbf..c21e9a2a 100644--- a/src/relay-setup.js+++ b/src/relay-setup.js@@ -47,7 +47,7 @@ export async function autoLinkProject(root, io) {if (!candidate) throw new Refused('RELAY_SESSION', 'Run pullboard relay on --all to link this project and pair the phone.');source = candidate.state;const proposal = await phoneProposal(source, 'link', originRepository(project),- { board: projectBoard(project), command: 'Link ' + name + '? (pullboard init)', link: true });+ { board: projectBoard(project), command: 'Link ' + name + '? (pullboard init)', link: true, root: project });const value = { root: project, publisherRoot: candidate.root, context: proposal.context, sealed: proposal.sealed, replyKey: proposal.reply.storedKey, published: false };pending = updateRelayMachine(state => {const existing = state.approvals.find(entry => entry.root === project);diff --git a/src/relay.js b/src/relay.jsindex 6767a6df..d49d5306 100644--- a/src/relay.js+++ b/src/relay.js@@ -1396,7 +1396,7 @@ export async function relayOff(root, io) {if (!state) return summary(root, null);// Local unlink always completes, including agent shells, outages and a fenced remote baseline.let proposal;- try { proposal = await phoneProposal(state, 'delete-board', state.board); }+ try { proposal = await phoneProposal(state, 'delete-board', state.board, { root }); }catch { /* Missing key or pairing cannot stop local unlinking. */ }rmSync(file, { force: true });try { forgetBoardKey(state.board, state.keyStorage); }diff --git a/test/relay-browser.test.js b/test/relay-browser.test.jsindex 2b2653bd..259e8af2 100644--- a/test/relay-browser.test.js+++ b/test/relay-browser.test.js@@ -14,6 +14,7 @@ import { ENGINE_VERSION } from '../src/machine.js';import { addItem, answerDecision, closeBoard, openBoard, shout } from '../src/board.js';import { relayClientFixture } from './relay-client-fixture.js';import { findChromeExecutable, relayWorkBudgetMs, startChrome } from './relay-browser-fixture.js';+import { pairStudioPhone, phoneExpiry, readApprovalCard, studioCommand, studioProject } from './relay-studio-fixture.js';/** Read native gzip snapshots while retaining checks against historical uncompressed records. */function snapshotDocument(plain) {@@ -533,3 +534,66 @@ test('legacy queued presentations never disclose later unacknowledged moves [H5,const compacted = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });assert.equal(compacted.status, 409, 'the relay compacted the moves only after acknowledging their final checkpoint');});++test('the link approval card names the computer and the board [H17,H5]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const { chrome, machineFile } = await pairStudioPhone(t, box);+ const notes = await studioProject(box, 'notes');+ const proposal = JSON.parse(readFileSync(machineFile, 'utf8')).approvals.find(entry => entry.root === notes);+ assert.ok(proposal?.published, 'registering notes on studio publishes one link request to the phone');+ await chrome.navigate(box.origin);+ await chrome.waitFor(`document.querySelector('.phone-approval[data-request="${proposal.context.id}"] button') !== null`);+ const card = await readApprovalCard(chrome, proposal.context.id);+ assert.match(card.text, /^Link notes from studio\?$/mu, 'the card asks in words which computer links which board');+ assert.equal(card.text.includes('fixture/repository'), true, 'the card names the repository being linked');+ assert.equal(card.text.includes('expires ' + phoneExpiry(proposal.context.expires)), true, 'the expiry is in the phone\'s local time');+ assert.equal(card.text.includes(new Date(proposal.context.expires).toISOString()), false, 'no UTC timestamp on the card');+ assert.doesNotMatch(card.text, /[0-9a-f]{32}/u, 'no raw 32-hex board id on the card');+ assert.equal(card.text.includes(proposal.context.machine) || /machine-/u.test(card.text), false, 'no machine id on the card');+ assert.ok(card.pad.every(value => value > 0), 'the card has padding on every side');+ assert.equal(card.inside, true, 'every line of the card\'s text sits inside its padding');+ assert.equal(card.action, 'Link project');+});++test('the delete card names the board and confirms the delete [H17,H5]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const notes = await studioProject(box, 'notes');+ const { chrome } = await pairStudioPhone(t, box);+ await chrome.waitFor("document.querySelectorAll('#proj-list .proj.repo').length === 2");+ const board = JSON.parse(readFileSync(join(notes, '.git/pullboard/relay.json'), 'utf8')).board;+ const off = await studioCommand(box, notes, ['relay', 'off']).done;+ assert.equal(off.code, 0, 'relay off on studio removes the local link and asks the phone');+ const posted = box.transit.findLast(record => record.method === 'POST' && record.path === '/api/v1/devices/approvals');+ const context = JSON.parse(posted.request.toString('utf8')).context;+ assert.equal(context.action, 'delete-board');+ assert.equal(context.board, board);+ const selector = `.phone-approval[data-request="${context.id}"]`;+ await chrome.waitFor(`document.querySelector('${selector} button') !== null`);+ const card = await readApprovalCard(chrome, context.id);+ assert.match(card.text, /^Delete notes from the relay\?$/mu, 'the delete card names the board');+ assert.equal(card.text.includes('studio'), true, 'the delete card names the computer that asked');+ assert.doesNotMatch(card.text, /[0-9a-f]{32}/u, 'no raw board id on the delete card');+ assert.equal(card.inside, true, 'the delete card keeps its text inside its padding');+ assert.equal(card.action, 'Delete relay copy');+ await chrome.evaluate(`document.querySelector('${selector} button').click()`);+ await chrome.waitFor("[...document.querySelectorAll('#phone-approvals [role=status]')].some(node => node.textContent === 'notes was deleted from the relay.')");+ const phone = await box.phoneSession();+ const boards = await (await fetch(box.origin + '/auth/boards', { headers: { cookie: 'pb_session=' + phone.token } })).json();+ assert.equal(boards.boards.some(entry => entry.id === board), false, 'the confirmation follows the relay deleting the board');+ await chrome.evaluate(`(() => {+ const original = window.fetch.bind(window);+ window.__approvalLists = 0;+ window.fetch = async (input, init) => {+ const response = await original(input, init);+ if (new URL(typeof input === 'string' ? input : input.url, location.href).pathname.endsWith('/approvals')) window.__approvalLists += 1;+ return response;+ };+ })()`);+ await chrome.waitFor('window.__approvalLists >= 2');+ assert.equal(await chrome.evaluate(`document.querySelector('${selector}') === null && [...document.querySelectorAll('#phone-approvals [role=status]')]+ .some(node => node.textContent === 'notes was deleted from the relay.')`), true, 'the tapped card is gone and its confirmation stays after the next refresh');+});diff --git a/test/relay-setup-once.test.js b/test/relay-setup-once.test.jsindex 9f725e6d..ed75d9a4 100644--- a/test/relay-setup-once.test.js+++ b/test/relay-setup-once.test.js@@ -244,9 +244,10 @@ test('set up once links three registered boards, later registration and a persisawait pageWait(chrome, `link approval card ${linkProposal.context.id}`, `document.querySelector(${JSON.stringify(approveLinkButton)}) !== null`);const linkCard = await pageEvaluate(chrome, `read link approval card ${linkProposal.context.id}`, `({text: document.querySelector('.phone-approval[data-request="${linkProposal.context.id}"]').innerText,action: document.querySelector(${JSON.stringify(approveLinkButton)}).innerText})`);- assert.match(linkCard.text, /Link fourth-project\?/u);+ assert.match(linkCard.text, /Link fourth-project from /u, 'the link card names the board and the computer asking');assert.match(linkCard.text, /fixture\/repository/u);- assert.match(linkCard.text, new RegExp(new Date(linkProposal.context.expires).toISOString().replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')));+ assert.match(linkCard.text, /expires /u, 'the proposal shows its expiry');+ assert.equal(linkCard.text.includes(new Date(linkProposal.context.expires).toISOString()), false, 'the expiry is in the phone\'s local time');assert.equal(linkCard.action, 'Link project', 'the paired phone presents an explicit one-tap link action');const approvalsBeforeLinkTap = box.calls.filter(call => call.path.endsWith('/authorize')).length;await pageEvaluate(chrome, `tap link approval ${linkProposal.context.id}`, `document.querySelector(${JSON.stringify(approveLinkButton)}).click()`);@@ -296,7 +297,7 @@ test('set up once links three registered boards, later registration and a persisawait pageWait(chrome, `delete approval card ${deleteApproval.id}`, `document.querySelector('.phone-approval[data-request="${deleteApproval.id}"]') !== null`);const deleteCard = await pageEvaluate(chrome, `read delete approval card ${deleteApproval.id}`, `({text: document.querySelector('.phone-approval[data-request="${deleteApproval.id}"]').innerText,action: document.querySelector('.phone-approval[data-request="${deleteApproval.id}"] button').innerText})`);- assert.match(deleteCard.text, new RegExp(deleteApproval.target));+ assert.match(deleteCard.text, /Delete fourth-project from the relay\?/u, 'the delete card names the board');assert.equal(deleteCard.action, 'Delete relay copy');const phone = await box.phoneSession();const boardsBeforeDeleteTap = await fetch(box.origin + '/auth/boards', { headers: { cookie: 'pb_session=' + phone.token } });@@ -463,7 +464,7 @@ test('a set-up-once run stretched past 30 seconds still gets its approval card [assert.equal(proposal.published, true, 'the relay accepts the native approval after the elapsed delay');const card = await pageEvaluate(chrome, `read delayed project approval card ${proposal.context.id}`, `({text: document.querySelector('.phone-approval[data-request="${proposal.context.id}"]').innerText,action: document.querySelector(${JSON.stringify(button)}).innerText})`);- assert.match(card.text, /Link delayed-approval-project\?/u);+ assert.match(card.text, /Link delayed-approval-project from /u);assert.equal(card.action, 'Link project');await pageEvaluate(chrome, `tap delayed project approval ${proposal.context.id}`, `document.querySelector(${JSON.stringify(button)}).click()`);await pageWait(chrome, `delayed project approval completes ${proposal.context.id}`, `document.querySelector(${JSON.stringify(button)}) === null`);diff --git a/test/relay-studio-fixture.js b/test/relay-studio-fixture.jsnew file mode 100644index 00000000..bd0eecc5--- /dev/null+++ b/test/relay-studio-fixture.js@@ -0,0 +1,108 @@+/** A computer named studio pairs a phone through the loopback relay and asks it to approve [H17,H5]. */+import assert from 'node:assert/strict';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { startFixtureChild, runFixtureChild } from './fixture-child.js';+import { startChrome } from './relay-browser-fixture.js';++const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');++/** The phone's own clock and words: a time zone far from UTC, so a UTC time on the card shows. */+export const PHONE_TIME_ZONE = 'Pacific/Auckland';++/** Give every CLI child the host name studio by preloading a module, leaving the product code unchanged. */+function studioEnv(box) {+ const preload = join(dirname(box.root), 'studio-host.mjs');+ if (!existsSync(preload)) {+ writeFileSync(preload, "import os from 'node:os';\nimport { syncBuiltinESMExports } from 'node:module';\n" ++ "os.hostname = () => 'studio';\nsyncBuiltinESMExports();\n", { mode: 0o600 });+ }+ return { ...box.env, NODE_OPTIONS: [box.env.NODE_OPTIONS, '--import=' + pathToFileURL(preload).href].filter(Boolean).join(' ') };+}++/** Run the production CLI on studio and return its JSON document once it exits. */+export function studioCommand(box, cwd, args) {+ const child = startFixtureChild(process.execPath, [CLI, ...args, '--json'], { cwd, env: studioEnv(box), stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });+ const done = new Promise((resolveResult, reject) => {+ child.once('error', reject);+ child.once('close', (code, signal) => {+ if (signal) return reject(new Error(child.fixtureFailure ?? 'studio CLI child stopped by ' + signal));+ try { resolveResult({ code, document: JSON.parse(stdout) }); }+ catch { reject(new Error(child.fixtureFailure ?? 'studio CLI child printed no JSON (exit ' + code + ')')); }+ });+ });+ return { child, done };+}++/** Make a committed project folder with an origin and register it on studio through pullboard init. */+export async function studioProject(box, name) {+ const root = join(dirname(box.root), name);+ mkdirSync(root);+ 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/repository.git']]) {+ assert.equal(runFixtureChild('git', args, { cwd: root, env: box.env }).status, 0);+ }+ assert.equal((await studioCommand(box, root, ['init']).done).code, 0, 'pullboard init registers ' + name + ' on studio');+ return root;+}++/** Poll the machine file for a value the running setup writes, without retrying the setup itself. */+async function machineValue(file, read, message, timeoutMs = 20_000) {+ const until = Date.now() + timeoutMs;+ do {+ const value = existsSync(file) ? read(JSON.parse(readFileSync(file, 'utf8'))) : null;+ if (value) return value;+ await new Promise(resolveWait => setTimeout(resolveWait, 25));+ } while (Date.now() < until);+ assert.fail(message);+}++/** Set up relay on --all on studio and pair a phone-sized Chrome in the phone's own time zone. */+export async function pairStudioPhone(t, box) {+ const setup = studioCommand(box, box.root, ['relay', 'on', '--all', '--url', box.origin]);+ const chrome = await startChrome();+ t.after(async () => {+ await chrome.close();+ if (setup.child.exitCode === null) setup.child.kill('SIGTERM');+ await setup.done.catch(() => {});+ });+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');+ const pending = await machineValue(machineFile, state => state.pending, 'relay on --all on studio publishes a one-use phone pairing');+ await chrome.send('Emulation.setTimezoneOverride', { timezoneId: PHONE_TIME_ZONE });+ await chrome.send('Emulation.setLocaleOverride', { locale: 'en-US' });+ await chrome.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });+ assert.equal((await chrome.send('Network.setCookie', { name: 'pb_session', value: (await box.phoneSession()).token,+ url: box.origin, httpOnly: true, sameSite: 'Lax' })).success, true);+ await chrome.navigate(box.origin + '/#device=' + pending.locator + '.' + pending.secret);+ const paired = await setup.done;+ assert.equal(paired.code, 0, 'relay on --all on studio pairs the phone');+ await chrome.waitFor("document.querySelector('#phone-approvals') !== null");+ return { chrome, machineFile };+}++/** Read a card's words and whether every line of its text sits inside the card's padding. */+export function readApprovalCard(chrome, request) {+ return chrome.evaluate(`(() => {+ const card = document.querySelector('.phone-approval[data-request="${request}"]');+ const outer = card.getBoundingClientRect();+ const style = getComputedStyle(card);+ const pad = ['Left', 'Right', 'Top', 'Bottom'].map(side => parseFloat(style['padding' + side]));+ const inner = { left: outer.left + pad[0], right: outer.right - pad[1], top: outer.top + pad[2], bottom: outer.bottom - pad[3] };+ const lines = [...card.querySelectorAll('p')].flatMap(node => {+ const range = document.createRange(); range.selectNodeContents(node);+ return [...range.getClientRects()].map(rect => ({ left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom }));+ });+ return { text: card.innerText.replace(/[\\u00a0\\u202f]/gu, ' '), pad, lines,+ inside: lines.length > 0 && lines.every(rect => rect.left >= inner.left - 0.5 && rect.right <= inner.right + 0.5 &&+ rect.top >= inner.top - 0.5 && rect.bottom <= inner.bottom + 0.5),+ action: card.querySelector('button')?.innerText ?? null };+ })()`);+}++/** The expiry as the phone in PHONE_TIME_ZONE shows it. */+export function phoneExpiry(expires) {+ return new Date(expires).toLocaleTimeString('en-US', { timeZone: PHONE_TIME_ZONE, hour: 'numeric', minute: '2-digit' }).replace(/[ ]/gu, ' ');+}