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(view): the view follows board events, not a timer [N26,A2]
Corey Olsona29dec4b8069
diff --git a/src/cockpit.js b/src/cockpit.jsindex 67f98ae6..31c54618 100644--- a/src/cockpit.js+++ b/src/cockpit.js@@ -24,7 +24,7 @@ function lifecycle() {/*** The page `pullboard view` serves (N26): one self-contained file, no assets from anywhere, that- * reads the board through the server's JSON and refreshes itself. The layout is the one the person+ * reads the board through the server's JSON and follows its events. The layout is the one the person* asked for: a sidebar listing every project on the machine with what needs them there, and a main* column with the tabs over two panes, a list and the selected thing's detail. Activity draws the* item lifecycle from src/machine.js with this board's counts. Under 900px wide the sidebar folds@@ -1039,8 +1039,142 @@ async function refresh() {snapshotReplay.index = snapshotReplay.events.length;replayControls();}- $('live').textContent = snapshot ? 'read-only snapshot' : '';+ if (!snapshot && !transportModule) follow();+ $('live').textContent = snapshot ? 'read-only snapshot' : liveLine();+}++// The local view follows each shown board's event stream instead of a timer (#545): it reads the board once, waits+// on the board's events after that read's latest one, and reads again only when an event or the stream's changed+// signal (#554) arrives, so a page whose board is quiet makes no requests. The relay transport keeps its own stream.+const streams = new Map();+let catching = null;+let catchAgain = false;+let catchWhenShown = false;+/** How often a page with no live stream reads its board instead, until the stream is back. */+const FALLBACK_MS = 15000;++/** Whether this browser reads a response as it arrives; one that cannot keeps only the fallback refresh. */+const canStream = () => typeof AbortController === 'function' && typeof ReadableStream === 'function' && typeof TextDecoderStream === 'function';++/** The latest event a board state already shows; its events are newest first. */+const latestEvent = (state) => Number(state?.events?.[0]?.event_id ?? 0);++/** Whether every board on screen has its stream up or opening, so nothing needs a timed read. */+const connected = () => streams.size > 0 && [...streams.values()].every((entry) => entry.status !== 'down');++/** Say nothing while every shown board's stream is up, and why the page is not live while one is down. */+function liveLine() {+ const down = [...streams.values()].filter((entry) => entry.status === 'down');+ if (!down.length) return '';+ if (down.some((entry) => entry.offline)) return 'offline: is pullboard view still running?';+ return (canStream() ? 'reconnecting' : 'no live stream in this browser') + ': refreshing every ' + FALLBACK_MS / 1000 + 's';+}++/** Follow each board the page shows and stop following the rest, starting a new stream after the state just read. */+function follow() {+ const shown = new Map(data.group ? data.group.repos.map((repo) => [repo.root, repo.board]) : data.project ? [[view.root, data.project]] : []);+ for (const [root, entry] of streams) {+ if (shown.has(root)) continue;+ entry.controller?.abort();+ clearTimeout(entry.retry);+ streams.delete(root);+ }+ for (const [root, state] of shown) {+ const board = data.projects.find((entry) => entry.root === root && entry.ok);+ const entry = streams.get(root);+ // A board's events after the latest one this page shows are what changed it since.+ if (entry && entry.id === board?.id) { entry.shown = Math.max(entry.shown, latestEvent(state)); continue; }+ if (entry) { entry.controller?.abort(); clearTimeout(entry.retry); streams.delete(root); }+ if (!board) continue;+ const next = { root, id: board.id, after: latestEvent(state), shown: latestEvent(state), status: 'opening', offline: false, failures: 0, controller: null, retry: 0 };+ streams.set(root, next);+ void listen(next);+ }+}++/** Read one server-sent message: its event name, its data and its numeric id. */+function streamMessage(block) {+ const message = { event: 'message', data: '', id: null };+ for (const line of block.split('\\n')) {+ if (!line || line.startsWith(':')) continue;+ const colon = line.indexOf(':');+ const field = colon < 0 ? line : line.slice(0, colon);+ const value = colon < 0 ? '' : line.slice(colon + 1).replace(/^ /, '');+ if (field === 'event') message.event = value;+ else if (field === 'data') message.data += (message.data ? '\\n' : '') + value;+ else if (field === 'id' && /^\\d+$/.test(value)) message.id = Number(value);+ }+ return message;+}++/** The rule and next step a stream's refusal carries. */+function streamRefusal(data) {+ try {+ const refusal = JSON.parse(data).error;+ return refusal && typeof refusal === 'object' ? '[' + refusal.code + '] ' + refusal.message : String(refusal || 'the board stream refused this view');+ } catch { return 'the board stream refused this view'; }+}++/**+ * Hold one board's event stream open, and read the board when its events say it changed. When the stream ends or+ * fails, try again with Last-Event-ID, waiting longer after each failure; the fallback refresh covers the gap.+ */+async function listen(entry) {+ const controller = canStream() ? new AbortController() : null;+ entry.controller = controller;+ try {+ if (!controller) throw new Error('this browser cannot read a stream');+ const res = await fetch(connection.base + '/api/v1/boards/' + encodeURIComponent(entry.id) + '/events', {+ headers: { ...connection.headers, accept: 'text/event-stream', 'last-event-id': String(entry.after) }, cache: 'no-store', signal: controller.signal,+ });+ if (!res.ok || !res.body) throw new Error('the board stream answered ' + res.status);+ entry.status = 'up';+ entry.offline = false;+ entry.failures = 0;+ $('live').textContent = liveLine();+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();+ let buffer = '';+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += value;+ let moved = false;+ for (let end = buffer.indexOf('\\n\\n'); end >= 0; end = buffer.indexOf('\\n\\n')) {+ const message = streamMessage(buffer.slice(0, end));+ buffer = buffer.slice(end + 2);+ if (message.event === 'error') throw new Error(streamRefusal(message.data));+ if (message.id !== null) entry.after = message.id;+ // An event after the latest one shown, or a signal with no id: a warning, or the board changed without a move.+ if (message.id !== null ? message.id > entry.shown : Boolean(message.data) || message.event !== 'message') moved = true;+ }+ // One read covers every event that arrived together.+ if (moved) catchUp();+ }+ throw new Error('the board stream ended');+ } catch (error) {+ if (controller?.signal.aborted || streams.get(entry.root) !== entry) return;+ entry.status = 'down';+ // A request that never reached the view is a TypeError; a refusal or an ended stream is not.+ entry.offline = error instanceof TypeError;+ entry.failures += 1;+ $('live').textContent = liveLine();+ if (controller) entry.retry = setTimeout(() => { if (streams.get(entry.root) === entry) void listen(entry); }, Math.min(FALLBACK_MS, 1000 * 2 ** Math.min(entry.failures - 1, 4)));+ }+}++/**+ * The one catch-up function: bring the page up to date after the events that arrived, one read at a time, by reading+ * the board's state again. A hidden page catches up when it is shown. #555 switches this read to #552's since=N delta.+ */+function catchUp() {+ if (document.hidden) { catchWhenShown = true; return; }+ if (catching) { catchAgain = true; return; }+ catching = refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }).finally(() => {+ catching = null;+ if (catchAgain) { catchAgain = false; catchUp(); }+ });}+document.addEventListener('visibilitychange', () => { if (!document.hidden && catchWhenShown) { catchWhenShown = false; catchUp(); } });/** Display the current event and make the replay's play, pause and end states explicit. */function replayControls() {@@ -2802,7 +2936,10 @@ async function startPage() {await refresh();}startPage().catch((error) => { document.body.classList.remove('loading'); $('live').textContent = 'cannot reach the view: ' + error.message; });-if (!snapshot) setInterval(() => { if (!document.hidden && (!transportModule || transport)) refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }); }, 3000);+// The relay transport keeps its own stream and timer. The local view reads on a timer only while it has no live+// stream, and its live line says so (#545).+if (!snapshot && transportModule) setInterval(() => { if (!document.hidden && transport) refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }); }, 3000);+if (!snapshot && !transportModule) setInterval(() => { if (!document.hidden && !connected()) refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }); }, FALLBACK_MS);setInterval(tickAges, 60000);</script></body>diff --git a/test/cockpit/layout.test.js b/test/cockpit/layout.test.jsindex 112c34f1..2348179e 100644--- a/test/cockpit/layout.test.js+++ b/test/cockpit/layout.test.js@@ -466,8 +466,8 @@ test('the board reads at a glance from the status bar [N26]', { timeout: 180_000await click('#feed [data-unread]');assert.equal((await feed()).length, alreadyRead + 1, 'show all brings back the shouts already read');- // Cut off from the board, the bar turns red and says why.- await chrome.stable("globalThis.fetch = () => Promise.reject(new TypeError('Failed to fetch'))");+ // Cut off from the board, the bar turns red and says why. Stopping the view drops the board's event stream for real.+ await view.stop();await chrome.waitFor("document.querySelector('#live').textContent.startsWith('offline')", 15_000); // budget: hang ceiling for the offline state after fetch rejection; no rendering-speed claim.r = await read();const [red, green, blue] = r.barTint;diff --git a/test/cockpit/live.test.js b/test/cockpit/live.test.jsnew file mode 100644index 00000000..f5d3d6b6--- /dev/null+++ b/test/cockpit/live.test.js@@ -0,0 +1,176 @@+/** The view follows the board's event stream instead of a timer, in real Chrome [N26,A2]. */+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync } from 'node:fs';+import { createServer, request as forward } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { browserPause, boardId, boardOf, chromeExecutable, closeSnapshotChrome, fetchLive, machine, openSnapshotChrome, project, startView } from './fixture.js';++/** The page's HTTP requests from a mark on, as method and path, leaving out data: URLs. */+function sent(chrome, mark = 0) {+ return chrome.requests.slice(mark).filter((request) => /^https?:/.test(request.url)).map((request) => request.method + ' ' + new URL(request.url).pathname);+}++/** One request header, whatever case Chrome reports it in. */+function header(request, name) {+ return Object.entries(request.headers).find(([key]) => key.toLowerCase() === name)?.[1] ?? null;+}++/** The event-stream reads the page opened, each with the event it asked to start after. */+function streamReads(chrome) {+ return chrome.requests.filter((request) => /^https?:/.test(request.url) && /\/api\/v1\/boards\/[^/]+\/events$/.test(new URL(request.url).pathname)+ && /text\/event-stream/.test(header(request, 'accept') ?? '')).map((request) => header(request, 'last-event-id'));+}++/**+ * A loopback HTTP proxy in front of the real view, so a test can cut every connection through it and refuse new ones+ * until it is restored, as a lost network does. It names the view's own host, which the view's secret check requires.+ */+async function cuttableProxy(view) {+ const target = new URL(view.base);+ const sockets = new Set(), upstreams = new Set();+ let down = false;+ const server = createServer((req, res) => {+ const upstream = forward({ host: target.hostname, port: target.port, method: req.method, path: req.url, headers: { ...req.headers, host: target.host } }, (answer) => {+ res.writeHead(answer.statusCode, answer.headers);+ answer.pipe(res);+ });+ upstreams.add(upstream);+ upstream.on('close', () => upstreams.delete(upstream));+ upstream.on('error', () => res.destroy());+ req.pipe(upstream);+ });+ server.on('connection', (socket) => {+ if (down) { socket.destroy(); return; }+ sockets.add(socket);+ socket.on('close', () => sockets.delete(socket));+ });+ await new Promise((ready) => server.listen(0, '127.0.0.1', ready));+ /** Drop every open connection, upstream and down. */+ const drop = () => { for (const socket of sockets) socket.destroy(); for (const upstream of upstreams) upstream.destroy(); };+ return {+ href: `http://127.0.0.1:${server.address().port}/?k=${encodeURIComponent(view.key)}`,+ cut() { down = true; drop(); },+ restore() { down = false; },+ close: () => new Promise((closed) => { down = true; drop(); server.close(() => closed()); }),+ };+}++/** A board with one open item, served by the real view and opened in real Chrome on the Items list. */+async function liveBoard(name, { proxied = false } = {}) {+ const executable = chromeExecutable();+ assert.ok(executable, 'Chrome is required for the live view checks');+ const box = machine();+ const alpha = project(box, name);+ box.run(alpha.repo, 'add', 'web', 'Header', '--specs', 'G1', '--criterion', 'renders');+ const view = await startView(box);+ const profile = mkdtempSync(join(tmpdir(), `pullboard-${name}-chrome-`));+ let chrome, proxy;+ try {+ proxy = proxied ? await cuttableProxy(view) : null;+ chrome = await openSnapshotChrome(executable, proxy?.href ?? view.link.href, profile);+ await chrome.waitFor('data?.project?.items?.some(item => item.id === 1) && !!document.querySelector(\'#chain [data-item="1"]\')');+ } catch (error) {+ if (chrome) await closeSnapshotChrome(chrome);+ await proxy?.close();+ rmSync(profile, { recursive: true, force: true });+ await view.stop();+ throw error;+ }+ /** Stop this test's Chrome, proxy and view, and remove its profile. */+ const close = async () => {+ await closeSnapshotChrome(chrome);+ await proxy?.close();+ rmSync(profile, { recursive: true, force: true });+ await view.stop();+ };+ return { box, alpha, view, chrome, proxy, close };+}++/** Record in the page when an expression first holds after a DOM change, on the page's own clock. */+async function watchFor(chrome, name, expression) {+ await chrome.stable(`(() => {+ window[${JSON.stringify(name)}] = null;+ const seen = () => { if (window[${JSON.stringify(name)}] === null && (${expression})) window[${JSON.stringify(name)}] = Date.now(); };+ new MutationObserver(seen).observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });+ return true;+ })()`);+}++/** When the board recorded its latest event of a kind for an item, read back through the API. */+async function eventAt(view, root, kind, item) {+ const id = await boardId(view, root);+ const response = await fetchLive(`${view.base}/api/v1/boards/${id}/events`, { headers: { 'x-pullboard-key': view.key } });+ assert.equal(response.status, 200);+ const event = (await response.json()).events.filter((row) => row.event_kind === kind && row.item_id === item).at(-1);+ assert.ok(event, `the board recorded a ${kind} event for #${item}`);+ return Date.parse(event.event_at);+}++test('the view shows a move as it happens [N26,A2]', { timeout: 120_000 }, async (t) => {+ const { box, alpha, view, chrome, close } = await liveBoard('live-move');+ try {+ // A quiet board draws no reads: the old view polled every 3000 ms, so any timer would show in this window.+ const quiet = chrome.requests.length;+ await browserPause(3_500); // budget: declared quiet window, longer than the 3000 ms timer the view used to read on.+ assert.deepEqual(sent(chrome, quiet), [], 'the page makes no request while the board is quiet');+ const latest = (await boardOf(view, alpha.repo)).events[0].event_id;+ assert.deepEqual(streamReads(chrome), [String(latest)], 'the page follows the board\'s event stream after the latest event it read');++ await watchFor(chrome, '__claimShownAt', 'document.querySelector(\'#chain [data-item="1"] .chip.busy\')');+ const before = chrome.requests.length;+ box.run(alpha.web, 'claim', '1');+ await chrome.waitFor('window.__claimShownAt !== null', 15_000); // budget: hang ceiling for the claim to arrive; the latency is judged below.+ const shownAt = await chrome.stable('window.__claimShownAt');+ const latency = shownAt - await eventAt(view, alpha.repo, 'claim', 1);+ t.diagnostic(`the claim appeared ${latency} ms after the board recorded it`);+ assert.ok(latency <= 2_000, `the claim appears ${latency} ms after the board recorded it`); // budget: declared by #545's frozen criterion: a move appears within 2000 ms.+ // What the page read for it came after the move, and the stream it follows stayed open.+ assert.ok(sent(chrome, before).length > 0 && sent(chrome, before).every((line) => /^GET \/api\/v1\/boards(?:\/[^/]+\/(?:state|shouts\/\d+))?$/.test(line)), `the page read the board for the move: ${JSON.stringify(sent(chrome, before))}`);+ assert.equal(streamReads(chrome).length, 1, 'the page kept the one stream it opened');+ assert.equal(await chrome.stable("document.querySelector('#live').textContent"), '', 'the live line says the page is live');+ assert.deepEqual(chrome.exceptions, [], 'the page raises no uncaught exception');+ } finally {+ await close();+ }+});++test('an idle view makes no requests [N26,A2]', { timeout: 150_000 }, async () => {+ const { box, alpha, chrome, close } = await liveBoard('live-idle');+ try {+ await chrome.waitFor('document.querySelector(\'#live\').textContent === \'\'');+ const mark = chrome.requests.length;+ await browserPause(30_000); // budget: declared by #545's frozen criterion: an unchanged board for 30 seconds.+ assert.deepEqual(sent(chrome, mark), [], 'the page makes no request while the board is unchanged for 30 seconds');+ assert.equal(await chrome.stable("document.querySelector('#live').textContent"), '', 'and it is still live');+ // The quiet was the stream waiting, not a page that stopped: a move after it still arrives.+ box.run(alpha.repo, 'add', 'web', 'After the quiet', '--specs', 'G1', '--criterion', 'renders');+ await chrome.waitFor('!!document.querySelector(\'#chain [data-item="2"]\')', 15_000); // budget: hang ceiling for the new item to arrive.+ assert.deepEqual(chrome.exceptions, [], 'the page raises no uncaught exception');+ } finally {+ await close();+ }+});++test('a dropped stream reconnects from its last event [N26,A2]', { timeout: 120_000 }, async () => {+ const { box, alpha, view, chrome, proxy, close } = await liveBoard('live-drop', { proxied: true });+ try {+ await chrome.waitFor('document.querySelector(\'#live\').textContent === \'\'');+ const latest = (await boardOf(view, alpha.repo)).events[0].event_id;+ // The connection drops and stays down: the live line says the page is not live.+ proxy.cut();+ await chrome.waitFor('/^(offline|reconnecting)/.test(document.querySelector(\'#live\').textContent)', 15_000); // budget: hang ceiling for the dropped stream to show.+ // A move while the page is cut off is one the reopened stream must bring.+ box.run(alpha.web, 'claim', '1');+ proxy.restore();+ await chrome.waitFor('!!document.querySelector(\'#chain [data-item="1"] .chip.busy\')', 30_000); // budget: hang ceiling for one reconnect after the stream's longest 15000 ms wait.+ await chrome.waitFor('document.querySelector(\'#live\').textContent === \'\'');+ const reads = streamReads(chrome);+ assert.ok(reads.length >= 2, `the page opened the stream again: ${JSON.stringify(reads)}`);+ assert.deepEqual([...new Set(reads)], [String(latest)], 'every reopened stream names the last event the page received, as Last-Event-ID');+ assert.deepEqual(chrome.exceptions, [], 'the page raises no uncaught exception');+ } finally {+ await close();+ }+});