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
fix(relay): a phone-approved link opens in the same run [H17,E16]
Corey Olsonc189b017e706
diff --git a/relay/browser-client.js b/relay/browser-client.jsindex 20644548..58e2bbfe 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -101,6 +101,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {const paired = new Map();let available = [];let waitingBoards = new Map();+ const approvedBoards = new Set();let warnings = [];let failure = '';let failureBoard = null;@@ -133,7 +134,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {try { state = storedOwnedRequestState(localStorage, key, entry.state?.personRequests); } catch { /* Missing device storage can only hide this device's own notice. */ }ownedRequestIds.set(id, state.owned);}- for (const text of noticeLines({ available, paired, ownedRequestIds, waitingBoards, warnings, failure })) {+ for (const text of noticeLines({ available, paired, ownedRequestIds, waitingBoards, approvedBoards, warnings, failure })) {const paragraph = document.createElement('p');paragraph.textContent = text;element.append(paragraph);@@ -508,6 +509,22 @@ export async function createTransport({ onUpdate = () => {} } = {}) {throw new Refused('RELAY_BUSY', 'Other clients kept winning the relay order. Retry this saved request.');}+ /**+ * After this phone approves a link, list again until the computer's sealed key arrives, so the+ * board opens here without another pairing. The wait ends at the approval's own expiry.+ */+ async function openApprovedBoard(context) {+ if (context?.action !== 'link') { await listing(); onUpdate(); return; }+ approvedBoards.add(context.board);+ try {+ while (!accessLost && Date.now() < context.expires) {+ await listing(); onUpdate();+ if (paired.has(context.board)) return;+ await new Promise(resolveWait => setTimeout(resolveWait, 500));+ }+ } finally { approvedBoards.delete(context.board); notice(); }+ }+/** Pair a link opened in this already-loaded page as well as one opened on a fresh visit. */async function pairingChanged() {try {@@ -521,7 +538,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {addEventListener('pagehide', () => { for (const entry of paired.values()) entry.stream?.close(); });if (await enrollPhone((path, options) => documentAt(path, denied, options))) keepPairingStorage();await listing();- await installPhoneApprovals((path, options) => documentAt(path, denied, options), keys, async () => { await listing(); onUpdate(); });+ await installPhoneApprovals((path, options) => documentAt(path, denied, options), keys, openApprovedBoard);return {/** Return decoded API state or seal narrow person intent; no board key or plaintext leaves the device. */async request(path, body) {diff --git a/relay/browser-devices.js b/relay/browser-devices.jsindex f894ff85..49912597 100644--- a/relay/browser-devices.js+++ b/relay/browser-devices.js@@ -157,7 +157,7 @@ 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();+ card.remove(); await onApproved(context);} catch (error) { text.textContent = 'Approval failed: ' + (error instanceof Refused ? error.message : 'Request the action again from the Mac.'); }finally { active.delete(context.id); }};diff --git a/relay/browser-notice.js b/relay/browser-notice.jsindex bb4fd1fa..6b9b3334 100644--- a/relay/browser-notice.js+++ b/relay/browser-notice.js@@ -32,7 +32,7 @@ export function storedOwnedRequestState(storage, key, requests) {}/** Build truthful device notices from authorized boards and their decrypted pending requests. */-export function noticeLines({ available, paired, ownedRequestIds = new Map(), waitingBoards = new Map(), warnings = [], failure = '' }) {+export function noticeLines({ available, paired, ownedRequestIds = new Map(), waitingBoards = new Map(), approvedBoards = new Set(), warnings = [], failure = '' }) {const lines = [];const waiting = [...paired.entries()].reduce((count, [id, entry]) => {const owned = ownedRequestIds.get(id) ?? new Set();@@ -41,6 +41,11 @@ export function noticeLines({ available, paired, ownedRequestIds = new Map(), waif (waiting) lines.push(`${waiting} request${waiting === 1 ? '' : 's'} from this device ${waiting === 1 ? 'is' : 'are'} waiting for a linked machine to run Pullboard.`);const pairedRepositories = new Set(available.filter(board => paired.has(board.id)).map(board => board.repository));for (const board of available.filter(value => !paired.has(value.id))) {+ // This phone just approved the link: its key is on the way, so asking to pair would be wrong.+ if (approvedBoards.has(board.id)) {+ lines.push(`${board.repository} · board ${board.id.slice(0, 8)}: approved; waiting for the computer to send this phone its key.`);+ continue;+ }if (waitingBoards.has(board.id)) {lines.push(`${board.repository} · board ${board.id.slice(0, 8)}: waiting for its first snapshot from a linked machine.`);continue;diff --git a/src/relay-setup.js b/src/relay-setup.jsindex ef931dbf..23eb07a3 100644--- a/src/relay-setup.js+++ b/src/relay-setup.js@@ -29,6 +29,20 @@ function projectBoard(root) {try { return store.boardId(board); } finally { store.closeBoard(board); }}+/**+ * Open the credential the phone sealed to this machine's reply key and link with it. relayOn+ * uploads the sealed snapshot, then wraps the board key to each paired phone, so the key leaves+ * this machine only sealed to the phone the person approved from.+ */+async function finishApprovedLink(project, pending, source, approval, io) {+ const privateKey = await restoreLinkReply(pending.replyKey);+ const result = await openApproval(privateKey, JSON.parse(Buffer.from(approval.response, 'base64url').toString('utf8')), pending.context, 'reply');+ const credential = { ...result.credential, account: pending.context.account, url: source.url };+ const linked = await relayOn(project, source.url, io, { credential, quiet: true, strict: true });+ updateRelayMachine(state => { state.approvals = state.approvals.filter(entry => entry.context.id !== pending.context.id); });+ return linked;+}+/** Link a new project only after the paired phone explicitly approves its one durable proposal. */export async function autoLinkProject(root, io) {const machine = readRelayMachine();@@ -65,11 +79,8 @@ export async function autoLinkProject(root, io) {if (document.approval.state !== 'approved') {io.err('waiting for phone approval: ' + name + '; expires ' + new Date(pending.context.expires).toISOString() + '; local work continues.'); return;}- const privateKey = await restoreLinkReply(pending.replyKey);- const result = await openApproval(privateKey, JSON.parse(Buffer.from(document.approval.response, 'base64url').toString('utf8')), pending.context, 'reply');- const credential = { ...result.credential, account: pending.context.account, url: source.url };- await relayOn(project, source.url, io, { credential, quiet: true, strict: true });- updateRelayMachine(state => { state.approvals = state.approvals.filter(entry => entry.context.id !== pending.context.id); });+ await finishApprovedLink(project, pending, source, document.approval, io);+ io.err('linked: ' + name);} catch (error) {if (pending) {warnPhoneApproval(pending, error, io, 'Local registration is complete; run pullboard relay on --all explicitly to link this project.');@@ -103,11 +114,13 @@ export async function revokeRelayDevice(deviceId, io) {}/** Link non-excluded registry entries and report an explicit outcome for every registered project. */-async function linkProjects(session, io, { onBoardOutcome } = {}) {+async function linkProjects(session, io, { onBoardOutcome, waiting = new Set() } = {}) {const machine = readRelayMachine();const linked = [];const failed = [];for (const project of listApiProjects()) {+ // A board whose link card is on the phone waits for that tap; see waitForLinkApprovals.+ if (waiting.has(project.root)) continue;if (machine.excluded.includes(project.root)) {onBoardOutcome?.({ root: project.root, name: project.name, outcome: 'skipped', reason: 'Excluded from automatic linking on this machine.' });continue;@@ -127,6 +140,67 @@ async function linkProjects(session, io, { onBoardOutcome } = {}) {return { linked, failed };}+/** Name the published, unexpired phone link cards this run can wait for on a phone already paired. */+function waitingLinkApprovals(session) {+ const machine = readRelayMachine();+ if (!machine.devices.some(device => device.account === session.account && device.url === session.url)) return [];+ const registered = new Set(listApiProjects().map(project => project.root));+ return machine.approvals.filter(entry => {+ if (!entry.published || Date.now() >= entry.context.expires || entry.context.account !== session.account) return false;+ if (machine.excluded.includes(entry.root) || !registered.has(entry.root)) return false;+ let source;+ try { source = relayMachineContext(entry.publisherRoot); } catch { return false; }+ return Boolean(source?.token?.startsWith('pm_')) && source.url === session.url;+ });+}++/**+ * Keep this foreground run open until the phone answers each waiting link card, then link that+ * board in the same run. Without this wait the phone that just approved sees a board it cannot+ * read until the computer happens to run another command (walkthrough-090 issue 15).+ */+async function waitForLinkApprovals(waiting, io, { signal } = {}) {+ const linked = [];+ const failed = [];+ const name = root => listApiProjects().find(project => project.root === root)?.name ?? root;+ let open = [...waiting];+ for (const pending of open) {+ io.say('waiting for phone approval: ' + name(pending.root) + '; tap Link project on your phone before ' + new Date(pending.context.expires).toISOString() + '.');+ }+ let interrupted = false;+ /** Stop waiting without undoing a link; the next command still finishes an approved card. */+ const stop = () => { interrupted = true; };+ process.once('SIGINT', stop);+ process.once('SIGTERM', stop);+ try {+ while (open.length && !signal?.aborted && !interrupted) {+ for (const pending of [...open]) {+ if (signal?.aborted || interrupted) break;+ const project = name(pending.root);+ try {+ if (Date.now() >= pending.context.expires) throw new Refused('PHONE_APPROVAL_EXPIRED', 'Link approval expired; run pullboard relay on --all to link this board.');+ const source = relayMachineContext(pending.publisherRoot);+ const document = await relayDeviceRequest(source, '/api/v1/devices/approvals/' + pending.context.id, { signal }, io);+ if (document.approval.state === 'expired') throw new Refused('PHONE_APPROVAL_EXPIRED', 'Link approval expired; run pullboard relay on --all to link this board.');+ if (document.approval.state !== 'approved') continue;+ const result = await finishApprovedLink(pending.root, pending, source, document.approval, io);+ linked.push({ project, root: pending.root, board: result.board });+ io.say('linked: ' + project);+ } catch (error) {+ if (signal?.aborted && error.code === 'OAUTH_CANCELLED') break;+ const reason = error instanceof Refused ? error.message.replace(/^\[[A-Z][A-Z0-9_]*\] /u, '') : 'Restore this registered project and retry.';+ failed.push({ project, root: pending.root, reason });+ io.err(`not linked: ${project}; ${reason}`);+ }+ open = open.filter(entry => entry !== pending);+ }+ if (open.length) await waitForPairingPoll(signal);+ }+ } finally { process.off('SIGINT', stop); process.off('SIGTERM', stop); }+ for (const pending of open) io.say('stopped waiting for phone approval: ' + name(pending.root) + '; after you tap Link project, the next pullboard command on this computer finishes the link.');+ return { linked, failed };+}+/** Wait for the next pairing poll or an abort without leaving an abort listener behind. */function waitForPairingPoll(signal) {return new Promise(resolve => {@@ -243,11 +317,17 @@ export async function relayOnAll(address, io, { signal, onPairingURL, onSignIn,// From this synchronous commit point onward the first board-link attempt is underway; later// cancellation must not claim that already-started link writes were rolled back.onLinking?.();- updateRelayMachine(state => { state.autoLink = true; state.owner = { account: session.account, url: session.url }; state.approvals = []; });- const result = await linkProjects(session, io, { onBoardOutcome });+ // The view's sign-in links every board itself; a terminal run waits for cards already on the phone.+ const waiting = onPairingURL ? [] : waitingLinkApprovals(session);+ const waitingIds = new Set(waiting.map(entry => entry.context.id));+ updateRelayMachine(state => { state.autoLink = true; state.owner = { account: session.account, url: session.url }; state.approvals = state.approvals.filter(entry => waitingIds.has(entry.context.id)); });+ const result = await linkProjects(session, io, { onBoardOutcome, waiting: new Set(waiting.map(entry => entry.root)) });const devices = readRelayMachine().devices.filter(device => device.account === session.account && device.url === session.url);const pairing = devices.length || !result.linked.length ? { paired: devices.length > 0 }: await pairFirstDevice(session, result.linked[0].board, result.linked, io, { signal, onPairingURL });+ const approved = await waitForLinkApprovals(waiting, io, { signal });+ result.linked.push(...approved.linked);+ result.failed.push(...approved.failed);return { ...result, ...pairing, autoLink: true };}diff --git a/test/relay-approval-delivery.test.js b/test/relay-approval-delivery.test.jsindex 7004de95..0f99feab 100644--- a/test/relay-approval-delivery.test.js+++ b/test/relay-approval-delivery.test.js@@ -597,3 +597,109 @@ test('elapsed fixture wall time never manufactures an approval expiry refusal [H'the live fixture clock accepts the actual native ten-minute expiry after elapsed work');await approve(chrome, request.context.id, request.command);});++/** Register one more committed project; its real init publishes a sealed link card to the phone. */+async function registerProject(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(spawnSync('git', args, { cwd: root, env: box.env }).status, 0);+ }+ const initialized = await cliCommand(root, box.env, ['init']).done;+ assert.equal(initialized.code, 0, 'the new project registers through the actual init command');+ return root;+}++let approvedLinkRun;++/**+ * Walkthrough-090 issue 15 once, shared by the two tests below: a paired phone, a new board+ * "notes" whose link card waits on it, relay on --all running, one tap. The snapshot upload is+ * held until the phone has rendered its notice, so the phone is observed before its key arrives.+ */+function approvedLinkScenario(t) {+ approvedLinkRun ??= (async () => {+ const box = await relayClientFixture(t);+ const { chrome, native, machineFile } = await pairPhone(box, t);+ const notes = await registerProject(box, 'notes');+ const proposal = JSON.parse(readFileSync(machineFile, 'utf8')).approvals.find(entry => entry.root === notes);+ assert.ok(proposal?.published, 'init publishes one sealed link card for notes');+ const board = proposal.context.board;+ const button = '#phone-approve-' + proposal.context.id;+ await chrome.waitFor(`document.querySelector(${JSON.stringify(button)}) !== null`);++ const run = cliCommand(box.root, box.env, ['relay', 'on', '--all', '--url', box.origin], 120_000, { json: false });+ native.push(run);+ let live = '';+ run.child.stdout.on('data', chunk => { live += chunk; });+ await waitFor(() => live.includes('waiting for phone approval: notes') || run.child.exitCode !== null,+ 'relay on --all reaches its wait for the phone or exits');+ const waited = live.includes('waiting for phone approval: notes');+ if (!waited) {+ const early = await run.done;+ return { waited, stdout: early.stdout, stderr: early.stderr, code: early.code };+ }++ await chrome.evaluate(`(() => {+ const notice = document.querySelector('#relay-notice');+ window.__noticeLog = [notice?.textContent ?? ''];+ new MutationObserver(() => window.__noticeLog.push(notice.textContent))+ .observe(notice, { childList: true, subtree: true, characterData: true });+ })()`);+ let held = false;+ let release;+ const released = new Promise(resolveRelease => { release = resolveRelease; });+ box.beforeNextSnapshot(async () => { held = true; await released; });+ const authorizeBefore = box.calls.filter(call => call.path.endsWith('/authorize')).length;+ await chrome.evaluate(`document.querySelector(${JSON.stringify(button)}).click()`);+ await waitFor(() => held, 'the computer starts linking notes in the same run once the phone approves');+ let noticeBeforeKey = null;+ try {+ await chrome.waitFor(`(document.querySelector('#relay-notice')?.textContent ?? '').includes(${JSON.stringify(board.slice(0, 8))})+ || (document.querySelector('#relay-notice')?.textContent ?? '').includes('pair this browser')`);+ noticeBeforeKey = await chrome.evaluate(`document.querySelector('#relay-notice').textContent`);+ } finally { release(); }+ const finished = await run.done;+ const linkedAtExit = existsSync(join(notes, '.git/pullboard/relay.json'));+ let opened = true;+ try {+ await chrome.waitFor(`document.querySelectorAll('#proj-list .proj.repo').length === 2+ && Object.hasOwn(JSON.parse(localStorage.getItem('pullboard.relay.keys.v1') ?? '{}'), ${JSON.stringify(board)})`);+ } catch { opened = false; }+ const rawKey = readFileSync(join(box.env.PULLBOARD_HOME, 'relay-keys', board + '.key'), 'utf8').trim();+ return {+ waited, code: finished.code, stdout: finished.stdout, stderr: finished.stderr, linkedAtExit, opened, noticeBeforeKey,+ noticeLog: await chrome.evaluate('window.__noticeLog'), rawKey,+ taps: box.calls.filter(call => call.path.endsWith('/authorize')).length - authorizeBefore,+ };+ })();+ return approvedLinkRun;+}++test('an approved link opens on the phone without another command [H17,E16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const run = await approvedLinkScenario(t);+ assert.equal(run.waited, true, `relay on --all waits for the phone's link card: ${run.stdout}`);+ assert.equal(run.taps, 1, 'one phone tap authorizes the link');+ assert.equal(run.code, 0, `the waiting run finishes cleanly: ${run.stderr}`);+ assert.equal(run.linkedAtExit, true, 'the same run links notes; no later command is needed');+ assert.equal(run.opened, true, 'the phone unwraps the notes key and lists the board with no other command');+ assert.match(run.noticeBeforeKey, /approved; waiting for the computer to send this phone its key\./u,+ 'before the key arrives the phone says it is on the way');+ assert.equal(run.noticeLog.some(text => text.includes('pair this browser')), false,+ `the phone that approved is never told to pair again: ${JSON.stringify(run.noticeLog)}`);+});++test('the computer prints linked with the board name [H17,E16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const run = await approvedLinkScenario(t);+ const lines = run.stdout.split('\n');+ const waiting = lines.findIndex(line => line.startsWith('waiting for phone approval: notes; '));+ assert.ok(waiting >= 0, `the run says which board waits for the phone: ${run.stdout}`);+ assert.equal(lines.filter(line => line === 'linked: notes').length, 1, `the run prints linked: notes once: ${run.stdout}`);+ assert.ok(lines.indexOf('linked: notes') > waiting, 'linked: notes follows the phone tap in the same run');+ assert.equal(run.stdout.includes(run.rawKey) || run.stderr.includes(run.rawKey), false, 'the board key is never printed');+});