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): stop polling terminal device confirmation [P6,H5]
Corey Olson461152eb3c1a
diff --git a/relay/auth-http.js b/relay/auth-http.jsindex d40af8c6..ffaf5fff 100644--- a/relay/auth-http.js+++ b/relay/auth-http.js@@ -37,25 +37,26 @@ function deviceConfirmationPage() {'<p id="intent"></p><button id="confirm" hidden>Confirm link</button> <button id="decline" hidden>Decline</button></main>' +'<script>let ticket=decodeURIComponent(location.hash.slice(1));history.replaceState(null,"",location.pathname);const status=document.querySelector("#status");' +'const intent=document.querySelector("#intent");const confirmButton=document.querySelector("#confirm");const declineButton=document.querySelector("#decline");' ++ 'let terminal=false;let pollTimer=null;/** Stop polling and make earlier status responses inert after a final decision. */function stopPolling(){terminal=true;if(pollTimer!==null){clearInterval(pollTimer);pollTimer=null;}}' +'/** Bind this browser tab to the one-use ticket without putting it in a request URL. */ async function openConfirmation(){' +'const response=await fetch("/auth/device/confirmation/open",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},body:JSON.stringify({ticket})});' +'const value=await response.json();if(!response.ok)throw new Error(value.error?.message||"This confirmation expired.");}' +- '/** Read the current grant without exposing a session credential to the page. */ async function refresh(){try{' ++ '/** Read the current grant without exposing a session credential to the page. */ async function refresh(){if(terminal)return;try{' +'const response=await fetch("/auth/device/confirmation/status",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},body:JSON.stringify({ticket})});' +- 'const value=await response.json();if(!response.ok)throw new Error(value.error?.message||"This confirmation expired.");' +- 'if(value.declined){status.textContent="You declined this board link. Nothing was linked.";return;}' +- 'if(value.confirmed){status.textContent="The board is linked. You can return to the terminal.";return;}' ++ 'if(terminal)return;const value=await response.json();if(terminal)return;if(!response.ok)throw new Error(value.error?.message||"This confirmation expired.");' ++ 'if(value.declined){stopPolling();status.textContent="You declined this board link. Nothing was linked.";return;}' ++ 'if(value.confirmed){stopPolling();status.textContent="The board is linked. You can return to the terminal.";return;}' +'if(!value.ready){status.textContent="Finish GitHub sign-in in the other tab, then this page will ask you to confirm.";return;}' +'status.textContent="Signed in as @"+value.account+". Confirm only if this is the board and machine you intended.";' +'intent.textContent="Link "+value.intent.boardName+" from "+value.intent.host+"?";confirmButton.hidden=false;declineButton.hidden=false;' +- '}catch(error){status.textContent=error.message;confirmButton.hidden=true;declineButton.hidden=true;}}' ++ '}catch(error){if(terminal)return;status.textContent=error.message;confirmButton.hidden=true;declineButton.hidden=true;}}' +'/** Send an exact-origin, cookie-bound confirmation decision. */ async function decide(decision){confirmButton.disabled=true;declineButton.disabled=true;try{' +'const response=await fetch("/auth/device/confirmation",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},' +- 'body:JSON.stringify({ticket,decision})});const value=await response.json();if(!response.ok)throw new Error(value.error?.message||"The relay could not confirm this link.");' ++ 'body:JSON.stringify({ticket,decision})});const value=await response.json();if(!response.ok)throw new Error(value.error?.message||"The relay could not confirm this link.");stopPolling();' +'status.textContent=value.confirmed?"The board is linked. You can return to the terminal.":"You declined this board link. Nothing was linked.";' +'confirmButton.hidden=true;declineButton.hidden=true;}catch(error){status.textContent=error.message;confirmButton.disabled=false;declineButton.disabled=false;}}' +'confirmButton.onclick=()=>decide("confirm");declineButton.onclick=()=>decide("decline");' +- 'void openConfirmation().then(refresh).catch(error=>{status.textContent=error.message;});setInterval(()=>{if(confirmButton.hidden)void refresh();},2000);</script></html>';+ 'void openConfirmation().then(refresh).catch(error=>{if(!terminal)status.textContent=error.message;});pollTimer=setInterval(()=>{if(!terminal&&confirmButton.hidden)void refresh();},2000);</script></html>';}/** Use a configured public origin, never a client-controlled Host or proxy header. */diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex de5c2d74..a28c1bff 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -221,6 +221,8 @@ globalThis.fetch = function tracedFetch(input, init) {const responseWaiters = [];const moveAcks = [];const privateKeys = new Set();+ let nextConfirmationStatusHold = null;+ const confirmationStatusHolds = new Set();let keyLeaked = false;/** Wait until a named relay request has fully returned to its caller. */function waitForResponse(path) {@@ -239,6 +241,27 @@ globalThis.fetch = function tracedFetch(input, init) {}}}+ /** Hold one real confirmation-status request before the production auth handler for race tests. */+ function holdNextConfirmationStatus() {+ assert.equal(nextConfirmationStatusHold, null, 'only one confirmation-status hold is armed at a time');+ let resolveStarted;+ let resolveFinished;+ let resolveGate;+ const started = new Promise(resolve => { resolveStarted = resolve; });+ const finished = new Promise(resolve => { resolveFinished = resolve; });+ const gate = new Promise(resolve => { resolveGate = resolve; });+ const control = { started, finished, gate, resolveStarted, resolveFinished, resolveGate, released: false };+ confirmationStatusHolds.add(control);+ /** Release the held request once so it can continue through the real auth handler. */+ function release() {+ if (control.released) return;+ control.released = true;+ control.resolveGate();+ }+ control.release = release;+ nextConfirmationStatusHold = control;+ return { started, finished, release };+ }const server = createServer(async (req, res) => {const snapshotWrite = req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '');if (snapshotWrite) snapshotWriteCount += 1;@@ -307,6 +330,18 @@ globalThis.fetch = function tracedFetch(input, init) {request: Buffer.concat(requestChunks), response: Buffer.concat(responseChunks) }));calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '', engine: req.headers['x-pullboard-engine'],browser: String(req.headers.cookie ?? '').includes('pb_session=') });+ if (req.method === 'POST' && req.url === '/auth/device/confirmation/status' && nextConfirmationStatusHold) {+ const hold = nextConfirmationStatusHold;+ nextConfirmationStatusHold = null;+ hold.resolveStarted();+ /** Mark completion after the held request returns from the real auth handler. */+ function heldStatusFinished() {+ hold.resolveFinished({ status: res.statusCode, response: Buffer.concat(responseChunks) });+ confirmationStatusHolds.delete(hold);+ }+ res.once('finish', heldStatusFinished);+ await hold.gate;+ }if (revokeOnNextListing && req.method === 'GET' && req.url === '/api/v1/boards') {revokeOnNextListing = false;const session = await phoneSession();@@ -403,6 +438,8 @@ globalThis.fetch = function tracedFetch(input, init) {return phone;}t.after(async () => {+ nextConfirmationStatusHold = null;+ for (const hold of confirmationStatusHolds) hold.release();api.close();server.closeAllConnections();if (server.listening) await new Promise(ready => server.close(ready));@@ -640,7 +677,7 @@ globalThis.fetch = function tracedFetch(input, init) {}return {transit, relayDirectory: join(scratch, 'relay'), authDatabase, otherDeviceJoin,- root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, cliWithSnapshotTrace, startCli, waitForResponse, link, phoneSession, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,+ root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, cliWithSnapshotTrace, startCli, waitForResponse, holdNextConfirmationStatus, link, phoneSession, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,/** Assert the test consumed every declared child budget, with no hidden CLI calls. */assertCliChildrenComplete() {if (cliChildren) assert.equal(cliChildIndex, cliChildren.length, 'every planned private CLI child ran exactly once');diff --git a/test/relay-device-confirmation.test.js b/test/relay-device-confirmation.test.jsindex 0ebf1ca3..f25aeef3 100644--- a/test/relay-device-confirmation.test.js+++ b/test/relay-device-confirmation.test.js@@ -8,6 +8,12 @@ import { relayClientFixture } from './relay-client-fixture.js';import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';const CONFIRMATION_PROMPT = 'After sign-in, confirm the link in your browser: ';+const CONFIRMATION_POLL_INTERVAL_MS = 2000;++/** Count real browser status requests without retaining their tickets or request bodies. */+function confirmationStatusRequestCount(box) {+ return box.calls.filter(call => call.method === 'POST' && call.path === '/auth/device/confirmation/status').length;+}/** Count linked boards through a read-only connection to the private relay database. */function linkedBoardCount(database) {@@ -16,9 +22,18 @@ function linkedBoardCount(database) {finally { db.close(); }}-/** Exercise the shipped page, cookie boundary and CLI session release in isolated Chrome. */-async function confirmDisplayedSshIntent(t) {+/** Click a visible production confirmation button through real Chrome mouse input. */+async function clickConfirmationButton(chrome, selector, label) {+ const point = await chrome.evaluate(`(() => { const rect = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; })()`);+ await chrome.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: point.x, y: point.y }, `move to ${label}`);+ await chrome.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, `press ${label}`);+ await chrome.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, `release ${label}`);+}++/** Exercise a real terminal decision while a pre-decision status request remains in flight. */+async function keepTerminalConfirmation(t, decision) {const box = await relayClientFixture(t);+ const heldStatus = box.holdNextConfirmationStatus();const chrome = await startChrome();let running;try {@@ -33,6 +48,7 @@ async function confirmDisplayedSshIntent(t) {await box.waitForResponse('/auth/device/poll');await chrome.navigate(confirmationURL);+ await heldStatus.started;await chrome.waitFor('document.querySelector("#confirm")?.hidden === false && document.querySelector("#decline")?.hidden === false',undefined, 'the real page enables the decision after GitHub sign-in');assert.equal(await chrome.evaluate('location.hash === ""'), true, 'the page removes the one-use nonce from browser history');@@ -40,21 +56,41 @@ async function confirmDisplayedSshIntent(t) {`Link ${basename(box.root)} from ${hostname()}?`, 'the real page displays the bound board and machine');assert.equal(linkedBoardCount(box.authDatabase), 0, 'opening the browser confirmation does not link a board');- const point = await chrome.evaluate('(() => { const rect = document.querySelector("#confirm").getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; })()');- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: point.x, y: point.y }, 'move to confirm button');- await chrome.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, 'press confirm button');- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, 'release confirm button');- await chrome.waitFor('document.querySelector("#status")?.textContent.includes("The board is linked.")',- undefined, 'the real page reports the completed approval');+ await clickConfirmationButton(chrome, decision === 'confirm' ? '#confirm' : '#decline', `${decision} button`);+ const terminalText = decision === 'confirm'+ ? 'The board is linked. You can return to the terminal.'+ : 'You declined this board link. Nothing was linked.';+ await chrome.waitFor(`document.querySelector("#status")?.textContent === ${JSON.stringify(terminalText)}`,+ undefined, 'the real page reports the completed terminal decision');const completed = await running.closed;assert.equal(completed.signal, null);- assert.equal(completed.code, 0, 'the SSH CLI receives the confirmed session');- assert.equal(JSON.parse(completed.stdout).linked, true);- assert.equal(linkedBoardCount(box.authDatabase), 1, 'the browser click links the displayed board');+ if (decision === 'confirm') {+ assert.equal(completed.code, 0, 'the SSH CLI receives the confirmed session');+ assert.equal(JSON.parse(completed.stdout).linked, true);+ assert.equal(linkedBoardCount(box.authDatabase), 1, 'the browser click links the displayed board');+ } else {+ assert.notEqual(completed.code, 0, 'the SSH CLI receives the declined-flow refusal');+ assert.equal(linkedBoardCount(box.authDatabase), 0, 'declining leaves the board unlinked');+ }++ heldStatus.release();+ const lateStatus = await heldStatus.finished;+ const lateResponse = JSON.parse(lateStatus.response.toString('utf8'));+ assert.equal(lateResponse.error?.code, 'OAUTH_EXPIRED', 'the in-flight request reaches the real handler after CLI flow consumption');+ const statusRequestsAfterLateResponse = confirmationStatusRequestCount(box);+ await chrome.evaluate(`new Promise(resolve => setTimeout(resolve, ${CONFIRMATION_POLL_INTERVAL_MS * 2}))`,+ 'wait through one full confirmation polling cadence after CLI flow consumption');+ assert.equal(await chrome.evaluate('document.querySelector("#status").textContent'), terminalText,+ 'a late expired-flow status response and later polling cadence preserve the terminal message');+ assert.equal(await chrome.evaluate('document.querySelector("#confirm").hidden && document.querySelector("#decline").hidden'), true,+ 'terminal decisions leave both buttons hidden');+ assert.equal(confirmationStatusRequestCount(box), statusRequestsAfterLateResponse,+ 'the terminal page sends no more status requests after the next polling cadence');for (const path of ['/auth/device/confirmation/open', '/auth/device/confirmation/status', '/auth/device/confirmation']) {assert.ok(box.calls.some((call) => call.path === path), `the real browser called ${path}`);}} finally {+ heldStatus.release();if (running && running.child.exitCode === null && running.child.signalCode === null) {running.child.kill('SIGKILL');await running.closed;@@ -63,6 +99,20 @@ async function confirmDisplayedSshIntent(t) {}}+/** Confirm from the real page and keep it alive after the CLI consumes its flow. */+async function confirmTerminalIntent(t) {+ await keepTerminalConfirmation(t, 'confirm');+}++/** Decline from the real page and keep it alive after the CLI consumes its flow. */+async function declineTerminalIntent(t) {+ await keepTerminalConfirmation(t, 'decline');+}+test('real Chrome confirms the displayed SSH board intent [P6,H5]', {skip: !findChromeExecutable() && 'Chrome is not installed',-}, confirmDisplayedSshIntent);+}, confirmTerminalIntent);++test('real Chrome keeps a declined SSH board intent terminal after CLI consumption [P6,H5]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, declineTerminalIntent);