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): load item details and retry searches [N26,A2]
Corey Olson6c16a5d630bc
diff --git a/src/cockpit.js b/src/cockpit.jsindex 7ce1d1c3..6dcf123d 100644--- a/src/cockpit.js+++ b/src/cockpit.js@@ -296,6 +296,10 @@ let seen = '';let addressReady = false;let heldClickPointer = null;let deferredClickRender = false;+// Detail replies stay with an unchanged summary, while search results are keyed by board and words.+const itemDetails = new Map();+const itemSearches = new Map();+let detailRead = null;const addressedShouts = new Map();const $ = (id) => document.getElementById(id);@@ -652,12 +656,14 @@ function replay(item) {/** A recorded merge, rather than an accept, is the end of the shipping pipeline. */function pipelineStage(item) {+ if (item.stage !== undefined) return item.stage;if (item.merged) return 'merged';return item.status === 'verified' ? 'accepted' : item.status;}/** The last arrival in this stage; edits, review reservations and renewals do not restart its age. */function pipelineSince(item) {+ if (item.since !== undefined) return item.since;if (item.merged) return item.history.findLast((event) => event.kind === 'merged')?.at || item.updatedAt;const arrival = replay(item).findLast((step) => step.move && step.from !== step.move.to);// Lapses are inferred, but the native claim receipt records the deadline that caused them.@@ -668,14 +674,28 @@ function pipelineSince(item) {return arrival ? arrival.at || item.updatedAt : item.history.find((event) => event.kind === 'add')?.at || item.updatedAt;}+/** Add the list and pipeline fields omitted from full snapshots, while leaving API summaries intact. */+function listFields(item, fresh = false) {+ if (!fresh && item.stage !== undefined) return item;+ const claim = item.status === 'claimed' && item.owner ? { by: item.owner, until: null }+ : item.status === 'submitted' && item.reviewer ? { by: item.reviewer, until: item.reviewUntil ?? null } : null;+ return { ...item, stage: pipelineStage(item), since: pipelineSince(item), claim,+ counts: { verdicts: item.verdicts.length, facts: (item.thread || []).filter((entry) => entry.type === 'fact').length } };+}++/** Resolve a builder from the full item's owner or the live claim in an API summary. */+const holderOf = (item) => item.status === 'claimed' ? item.claim?.by ?? item.owner ?? null : null;+/** Resolve a reviewer from the full item or the live claim in an API summary. */+const reviewerOf = (item) => item.status === 'submitted' ? item.claim?.by ?? item.reviewer ?? null : null;+/** Render the same board's items in lifecycle order, retaining every item as a detail link. */function pipelineCard(items) {const stages = [['open', 'Not started'], ['claimed', 'Building'], ['submitted', 'Waiting for review'], ['accepted', 'Accepted, waiting to merge'], ['merged', 'Merged']];return stages.map(([stage, label]) => {- const rows = items.filter((item) => pipelineStage(item) === stage).sort((a, b) => pipelineSince(a).localeCompare(pipelineSince(b)) || a.id - b.id);+ const rows = items.map((item) => listFields(item)).filter((item) => item.stage === stage).sort((a, b) => a.since.localeCompare(b.since) || a.id - b.id);const oldest = rows[0];return '<li class="card-panel pipeline-stage" data-pipeline-stage="' + stage + '"><header><h2>' + label + '</h2><b data-stage-count="' + stage + '">' + rows.length + '</b></header>'- + (oldest ? '<p class="pipeline-oldest">Oldest <a class="ref" href="' + esc(itemAddress(oldest.id)) + '" data-go="item:' + oldest.id + '">#' + oldest.id + '</a> · ' + age(pipelineSince(oldest)) + ' in this stage</p>' : '<p class="pipeline-oldest">No items</p>')+ + (oldest ? '<p class="pipeline-oldest">Oldest <a class="ref" href="' + esc(itemAddress(oldest.id)) + '" data-go="item:' + oldest.id + '">#' + oldest.id + '</a> · ' + age(oldest.since) + ' in this stage</p>' : '<p class="pipeline-oldest">No items</p>')+ '<ul>' + rows.map((item) => '<li><button class="pipeline-item' + (view.item === item.id ? ' on' : '') + '" type="button" data-item="' + item.id + '"><span>#' + item.id + '</span><span>' + esc(item.title) + '</span></button></li>').join('') + '</ul></li>';}).join('');}@@ -764,7 +784,8 @@ function timeline(item) {* none was. Words are wrapped and placed by a generous estimate of their width, so none overlaps.*/function flowSvg(p) {- const counts = moveCounts(p.items);+ // Summary states include board-wide tallies, so the lifecycle drawing needs no per-item histories.+ const counts = p.moveCounts ? new Map(Object.entries(p.moveCounts)) : moveCounts(p.items);const finals = FLOW.states.filter((s) => s.final).map((s) => s.id);const leads = (s) => FLOW.moves.filter((m) => m.from.includes(s) && m.to !== s).map((m) => m.to);let row = [];@@ -1105,7 +1126,7 @@ function boardSummary(board, state) {decisions: state.decisions.length,// What each item's state reads from, so another repo's roadmap can show it as this board's// Items tab does, sent back included, and open it here.- items: state.items.map((item) => ({ id: item.id, title: item.title, status: item.status, merged: Boolean(item.merged), verdict: item.verdict && { decision: item.verdict.decision } })),+ items: state.items.map((item) => ({ id: item.id, title: item.title, status: item.status, stage: item.stage ?? pipelineStage(item), verdict: item.verdict && { decision: item.verdict.decision } })),};}@@ -1241,6 +1262,63 @@ async function boardState(root, mark, fresh = null) {};}+/** Whether a board state already carries every item's detail, as exports and event replays do. */+const fullItems = (project) => project.items.every((item) => Array.isArray(item.history));++/** Text available locally for an item before the API searches criteria omitted from summaries. */+const searchedText = (item) => ('#' + item.id + ' ' + item.title + ' ' + item.lane + ' ' + item.specs.join(' ') + ' ' + (item.criterion || '')).toLowerCase();++/** Whether the board has a gap in its retained events or an item event newer than a detail read. */+function movedSince(project, id, cursor) {+ const events = project.events || [];+ if (!events.length || events[0].event_id <= cursor) return false;+ if (events.at(-1).event_id > cursor + 1) return true;+ return events.some((event) => event.event_id > cursor && event.item_id === id);+}++/** Load one opened item's omitted fields, retaining them only while its summary and event cursor stay current. */+function detailOf(project, item, ask) {+ if (Array.isArray(item.history)) return { item };+ const root = view.root, key = root + '\\n' + item.id, summary = JSON.stringify(item);+ const kept = itemDetails.get(key);+ /** Keep the prior detail visible during a refresh, or return the short initial loading state. */+ const waiting = (entry) => (entry?.shown ? { item: { ...item, ...entry.shown } } : { loading: true });+ if (kept?.loading) return waiting(kept);+ if (kept && kept.summary === summary && !movedSince(project, item.id, kept.cursor)) {+ return kept.error ? { error: kept.error } : { item: { ...item, ...kept.detail } };+ }+ if (!ask) return waiting(kept && { shown: kept.detail });+ const entry = { loading: true, summary, cursor: project.events?.[0]?.event_id ?? 0, detail: null, error: null, shown: kept?.detail ?? null };+ itemDetails.set(key, entry);+ detailRead = api(boardPath(root) + '/items/' + encodeURIComponent(String(item.id))).then((reply) => { entry.detail = reply.item; },+ (error) => { entry.error = String(error.message || error); }).finally(() => {+ entry.loading = false;+ if (view.root === root && view.item === item.id) render();+ });+ return waiting(entry);+}++/** Search full snapshots locally and summary states through the API, once per query and board. */+function searchIds(project, words) {+ const query = words.trim().toLowerCase();+ const local = new Set(project.items.filter((item) => searchedText(item).includes(query)).map((item) => item.id));+ if (!query || fullItems(project) || data.root !== view.root) return local;+ const root = view.root, key = root + '\\n' + query;+ const kept = itemSearches.get(key);+ if (kept) return kept.ids || local;+ const entry = { ids: null };+ itemSearches.set(key, entry);+ api(boardPath(root) + '/items?q=' + encodeURIComponent(query)).then((reply) => {+ entry.ids = new Set(reply.ids);+ if (view.root !== root || $('q').value.trim().toLowerCase() !== query) return;+ render();+ if (!$('find-results').hidden) showFound();+ }, () => {+ if (itemSearches.get(key) === entry) itemSearches.delete(key);+ });+ return local;+}+// Keep credential metadata apart from board snapshots and scoped to the selected project (H2,H9).const credentials = new Map();@@ -1336,7 +1414,10 @@ async function refresh(fresh = null) {seen = text;data = next;syncBoardMode(view.root);+ itemSearches.clear();+ const reading = detailRead;render();+ if (detailRead !== reading) await detailRead;}if (changed) {address(false);@@ -2132,8 +2213,8 @@ function render() {$('pipeline').hidden = !pipeline;// Each Show choice counts what it would show under the lane and the search. A search looks through every// state, withdrawn items included; browsing leaves those out.- const matching = (q ? p.items : items)- .filter((i) => !q || ('#' + i.id + ' ' + i.title + ' ' + i.lane + ' ' + i.specs.join(' ') + ' ' + (i.criterion || '')).toLowerCase().includes(q));+ const found = searchIds(p, q);+ const matching = (q ? p.items : items).filter((item) => !q || found.has(item.id));// Gated is one test, shared by the rows, the Gated filter and the status bar: open and waiting on an item or a held lane.const heldLanes = new Map(p.holds.map((h) => [h.hold_lane, h]));const gatedOf = (i) => stateOf(i) === 'open' && (i.blockedBy.length > 0 || heldLanes.has(i.lane));@@ -2188,8 +2269,9 @@ function render() {const waits = s === 'open' && i.blockedBy.length ? i.blockedBy : [];const gated = gatedOf(i);const pills = (waits.length ? '<span class="gate">' + waits.map((id, index) => '<span class="wait-unit">' + (index ? '' : 'waits on ') + '<a class="ref" href="' + esc(itemAddress(id)) + '" data-go="item:' + id + '">#' + id + '</a></span>').join(', ') + '</span>' : '') + (hold ? '<span class="gate">lane held: ' + linked(hold.hold_reason, titles) + '</span>' : '');- const tag = s === 'building' && i.owner ? '<span class="chip busy" title="building, held by ' + esc(agentName(i.owner)) + '">' + esc(agentName(i.owner)) + '</span>'- : s === 'verify' && i.reviewer ? '<span class="chip warn" title="reviewing until ' + esc(when(i.reviewUntil)) + '">' + esc(agentName(i.reviewer)) + ' reviewing</span>'+ const holder = holderOf(i), reviewer = reviewerOf(i);+ const tag = s === 'building' && holder ? '<span class="chip busy" title="building, held by ' + esc(agentName(holder)) + '">' + esc(agentName(holder)) + '</span>'+ : s === 'verify' && reviewer ? '<span class="chip warn" title="reviewing until ' + esc(when(i.claim?.until ?? i.reviewUntil)) + '">' + esc(agentName(reviewer)) + ' reviewing</span>': s === 'open' ? openChip(i) : chip(s);return recordRow({ classes: (view.item === i.id ? 'on ' : '') + (gated ? 'gated ' : ''), attributes: 'data-item="' + i.id + '"', title: i.title, state: s,primary: '<span>#' + i.id + '</span>' + rich(i.title, titles), rightTop: age(i.updatedAt), rightBottom: tag,@@ -2198,14 +2280,18 @@ function render() {: '<span>' + esc(i.lane) + '</span>' + (i.specs.length ? '<span class="specs" title="' + esc(i.specs.join(', ')) + '">' + esc(i.specs.slice(0, 3).join(', ') + (i.specs.length > 3 ? ' +' + (i.specs.length - 3) : '')) + '</span>' : '')) + pills });}).join('') : '<li class="empty">' + (items.length ? 'No items match.' : snapshot ? 'No items at this event.' : 'No items yet. Add the first one with New item.') + '</li>';- const item = p.items.find((i) => i.id === view.item);+ const selected = p.items.find((i) => i.id === view.item);// The form shows when asked for, or when the project has no item at all, withdrawn ones included.const adding = view.adding || (!p.items.length && !(view.tab === 'items' && view.addressDetail !== null && view.addressDetail !== 'pipeline'));$('add-form').hidden = !adding;$('add-cancel').hidden = !p.items.length;$('detail').hidden = adding;- if (!item) $('detail').innerHTML = '<div class="empty">' + (view.tab === 'items' && view.addressDetail !== null && view.addressDetail !== 'pipeline' ? 'No item #' + esc(view.addressDetail) + ' exists here.' : 'Pick an item to see its criterion, verdicts and history.') + '</div>';- if (item && !view.adding) {+ if (!selected) $('detail').innerHTML = '<div class="empty">' + (view.tab === 'items' && view.addressDetail !== null && view.addressDetail !== 'pipeline' ? 'No item #' + esc(view.addressDetail) + ' exists here.' : 'Pick an item to see its criterion, verdicts and history.') + '</div>';+ const opened = selected && !view.adding ? detailOf(p, selected, view.tab === 'items' && data.root === view.root) : null;+ if (opened && !opened.item) $('detail').innerHTML = '<div class="stack"><p class="detail-wait muted" role="status">'+ + (opened.error ? 'Could not load #' + selected.id + ': ' + esc(opened.error) : 'Loading #' + selected.id + '…') + '</p></div>';+ const item = opened?.item;+ if (item) {const s = stateOf(item);const cited = item.specs.map((id) => p.spec.find((r) => r.id === id) || { id, status: 'missing', text: '(not in SPEC.md)' });const baseline = item.checkBaseline;@@ -2309,11 +2395,11 @@ function render() {// Each agent with what it holds: its claim, then its work sent back, then its work waiting for a// verdict. The worktree path is there on hover; what the person reads is who is doing what.// A review an agent holds (V15) comes right after its claim.- const rank = (a, i) => i.status === 'claimed' ? 0 : i.reviewer === a.agent_id ? 1 : stateOf(i) === 'back' ? 2 : 3;- const holding = (a) => items.filter((i) => i.status === 'claimed' ? i.owner === a.agent_id : i.reviewer === a.agent_id || (i.builtBy === a.agent_id && ['back', 'verify'].includes(stateOf(i)))).sort((x, y) => rank(a, x) - rank(a, y));+ const rank = (a, i) => i.status === 'claimed' ? 0 : reviewerOf(i) === a.agent_id ? 1 : stateOf(i) === 'back' ? 2 : 3;+ const holding = (a) => items.filter((i) => i.status === 'claimed' ? holderOf(i) === a.agent_id : reviewerOf(i) === a.agent_id || (i.builtBy === a.agent_id && ['back', 'verify'].includes(stateOf(i)))).sort((x, y) => rank(a, x) - rank(a, y));// The agents at work: holding a claim or a review now, or moved in the last hour. Every agent is one click away;// work an idle agent left sent back or waiting stays on the Items tab.- const recent = (a) => p.items.some((i) => (i.status === 'claimed' && i.owner === a.agent_id) || (i.status === 'submitted' && i.reviewer === a.agent_id))+ const recent = (a) => p.items.some((i) => (i.status === 'claimed' && holderOf(i) === a.agent_id) || (i.status === 'submitted' && reviewerOf(i) === a.agent_id))|| (a.lastMoveAt && Date.now() - Date.parse(a.lastMoveAt) < 36e5);const listed = view.allAgents ? p.agents : p.agents.filter(recent);// As little room as the panel can take: an agent holding work is one row, with its avatar and colour from the feed,@@ -2322,7 +2408,7 @@ function render() {const busy = listed.filter((a) => holding(a).length), idle = listed.filter((a) => !holding(a).length);const face = (a) => lead(a.agent_id) ? '<span class="avatar">' + LEAD + '</span>' : '<span class="avatar' + (initials(a.agent_id).length > 3 ? ' wide' : '') + '" aria-hidden="true">' + esc(initials(a.agent_id)) + '</span>';const tip = (a) => 'Shouts with ' + agentName(a.agent_id) + ' · ' + a.agent_lane + ' · ' + a.agent_route + ' (' + a.agent_path + ')';- const state = (a, i) => i.reviewer === a.agent_id ? '<span class="chip warn">reviewing</span>' : chip(stateOf(i));+ const state = (a, i) => reviewerOf(i) === a.agent_id ? '<span class="chip warn">reviewing</span>' : chip(stateOf(i));const marks = (a) => ' h' + hue(a.agent_id) + (lead(a.agent_id) ? ' lead' : '') + (view.agent === a.agent_id ? ' on' : '');const row = (a) => {const mine = holding(a), first = mine[0];@@ -2692,8 +2778,9 @@ function findAll(words) {const p = data?.project, q = words.trim().toLowerCase();if (!p || !q) return [];const has = (...parts) => parts.join(' ').toLowerCase().includes(q);- const items = p.items.filter((i) => has('#' + i.id, i.title, i.lane, i.specs.join(' '), i.criterion || ''))- .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).map((i) => ({ go: 'item:' + i.id, id: '#' + i.id, text: i.title, note: stateLabel(i) }));+ const ids = searchIds(p, q);+ const items = p.items.filter((item) => ids.has(item.id))+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).map((item) => ({ go: 'item:' + item.id, id: '#' + item.id, text: item.title, note: stateLabel(item) }));// A Spec row or Doctrine rule is as new as the commit that added it (0 not yet committed; a standard rule, never added// here, last); rows one commit added together read newest first by their place in the file.const rows = (kind, list) => list.map((r, at) => ({ r, at })).filter(({ r }) => has(r.id, r.text))@@ -2734,6 +2821,7 @@ function openFound(target) {function pick(id, root = view.root) {view.adding = false;if (root !== view.root) return switchTo(root, id);+ if (itemDetails.get(root + '\\n' + id)?.error) itemDetails.delete(root + '\\n' + id);view.tab = 'items';keep('pb.tab', view.tab);view.item = id;diff --git a/src/serve.js b/src/serve.jsindex df76370a..dc6e7a17 100644--- a/src/serve.js+++ b/src/serve.js@@ -420,7 +420,7 @@ export async function serveView({ port = 0, secret = randomBytes(18).toString('b// initialize, and use the real CLI entry point without adding a second move implementation.const { createLocalApiHandler } = await import('./api.js');const { main } = await import('./cli.js');- const apiHandler = createLocalApiHandler({ secret, getPort: () => bound, runCommand: main,+ const apiHandler = createLocalApiHandler({ secret, getPort: () => bound, runCommand: main, stateDetail: 'summary',allowedOrigins: [HOSTED_ORIGIN], ...(projectRoot === undefined ? {} : { scope: { projectRoot } }) });const reply = (res, code, type, body) => {res.writeHead(code, {diff --git a/test/cockpit/addresses.test.js b/test/cockpit/addresses.test.jsindex e859f4bc..68d31c3a 100644--- a/test/cockpit/addresses.test.js+++ b/test/cockpit/addresses.test.js@@ -26,6 +26,8 @@ async function openAddress(chrome, server, address) {target.search = server.link.search;await chrome.send('Page.navigate', { url: target.href });await settled(chrome, SCRIPT);+ // An item address opens its item; the view reads its detail then, and its heading arrives with it.+ if (/\/items\/\d+$/.test(target.pathname)) await settled(chrome, "!!document.querySelector('#detail h2, #detail .empty')");}/** Assert the detail itself, so suppressing row rendering produces an assertion failure. */async function assertHeading(chrome, selector, id, text) {diff --git a/test/cockpit/agents.test.js b/test/cockpit/agents.test.jsindex 20aa4f35..444ca9d7 100644--- a/test/cockpit/agents.test.js+++ b/test/cockpit/agents.test.js@@ -218,14 +218,14 @@ test('agent model display names follow the API on phone and desktop [O8,N26]', {assert.equal(await text('#chain [data-item="1"] .chip'), expected.builder, `${at}: item row holder`);assert.equal(await text('#chain [data-item="3"] .chip'), expected.unknown, `${at}: unknown model row`);await press(chrome, 'document.querySelector("#chain [data-item=\\"1\\"]")');- await settled(chrome, 'view.item === 1');+ await settled(chrome, 'view.item === 1 && !!document.querySelector("#detail h2")');assert.ok((await text('#detail')).includes(expected.builder), `${at}: held item detail`);assert.equal(await text('#needs .row[data-go^="decide:"] .meta'), 'NEEDS YOU a decision, asked by ' + expected.reviewer, `${at}: Needs-you decision author`);assert.ok((await text('#needs .row[data-go="tab:shouts"] .meta')).includes('lane held by ' + expected.reviewer), `${at}: Needs-you lane holder`);await chooseFilter(chrome, 'state:verified');await settled(chrome, '!!document.querySelector("#chain [data-item=\\"2\\"]")');await press(chrome, 'document.querySelector("#chain [data-item=\\"2\\"]")');- await settled(chrome, 'view.item === 2');+ await settled(chrome, 'view.item === 2 && !!document.querySelector("#detail h2")');const detail = await text('#detail');assert.ok(detail.includes(expected.builder) && detail.includes(expected.reviewer), `${at}: builder and verifier detail`);assert.ok((await text('#detail .verdict .by')).startsWith(expected.reviewer), `${at}: verdict identity`);@@ -274,7 +274,7 @@ test('agent model display names follow the API on phone and desktop [O8,N26]', {await tab('roadmap');assert.doesNotMatch(await text('#roadmap'), /web-[12]|coordinator/, `${at}: roadmap rows name no agents`);await press(chrome, 'document.querySelector("#roadmap [data-go=\\"item:1\\"]")');- await settled(chrome, 'view.tab === "items" && view.item === 1');+ await settled(chrome, 'view.tab === "items" && view.item === 1 && !!document.querySelector("#detail h2")');assert.ok((await text('#detail')).includes(expected.builder), `${at}: roadmap item opens with the API identity`);assert.ok(await chrome.stable('document.documentElement.scrollWidth <= innerWidth'), `${at}: no sideways overflow`);}diff --git a/test/cockpit/demo.test.js b/test/cockpit/demo.test.jsindex a82cd66a..ce0355e9 100644--- a/test/cockpit/demo.test.js+++ b/test/cockpit/demo.test.js@@ -606,6 +606,7 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2assert.ok(await chrome.stable("[...document.querySelectorAll('#proj-list .pname')].some(e=>e.textContent==='phone-demo')"), `${width}: demo appears in the project list`);assert.ok(await chrome.stable("!!document.querySelector('#needs:not([hidden])')"), `${width}: Needs you is visible`);await click('#chain .row');+ await chrome.waitFor("!!document.querySelector('#detail h2')");assert.ok(await chrome.stable("!!document.querySelector('#detail h2')"), `${width}: selected item detail is visible`);await checkLayout(width, 'items, Needs you and detail');for (const tab of ['shouts', 'spec', 'doctrine', 'activity']) {diff --git a/test/cockpit/detail.test.js b/test/cockpit/detail.test.jsnew file mode 100644index 00000000..2e5467dd--- /dev/null+++ b/test/cockpit/detail.test.js@@ -0,0 +1,240 @@+/** Cockpit item detail checks: lists from summaries, detail on demand, using the shared real-board fixtures [N26,A2]. */+import assert from 'node:assert/strict';+import { join } from 'node:path';+import { test } from 'node:test';+import { machine, project, build, sendBack, accept, startView, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, press, searchFor, chooseFilter, serveFolder } from './fixture.js';++/**+ * Before the page loads, keep a count of its API reads, start it on the Shouts tab once, and let the+ * test hold item detail reads, so the loading line can be seen and released.+ */+const OBSERVE = `(() => {+ const nativeFetch = window.fetch.bind(window), held = [];+ window.__pbReads = [];+ window.__pbHold = false;+ window.__pbRelease = () => { window.__pbHold = false; while (held.length) held.shift()(); };+ window.fetch = (input, init) => {+ const url = new URL(typeof input === 'string' ? input : input.url, location.href);+ window.__pbReads.push(url.pathname + url.search);+ if (window.__pbHold && /\\/items\\/\\d+$/.test(url.pathname)) return new Promise((go) => held.push(go)).then(() => nativeFetch(input, init));+ return nativeFetch(input, init);+ };+ try { if (!localStorage.getItem('pb.tab')) localStorage.setItem('pb.tab', 'shouts'); } catch {}+})()`;++/** The item detail and search reads among a page's API reads, in order. */+const itemReads = (reads) => reads.filter((path) => /\/api\/v1\/boards\/[^/]+\/items(\/|\?|$)/.test(path))+ .map((path) => path.replace(/^.*\/items/, 'items'));++/** What the detail pane shows of an item: its heading, criterion, check, brief, verdicts, moves and facts. */+const DETAIL = `(() => {+ const detail = document.querySelector('#detail');+ const part = (name) => [...detail.querySelectorAll('h3')].find((heading) => heading.textContent === name)?.parentElement;+ return {+ title: detail.querySelector('h2')?.innerText ?? null,+ waiting: detail.querySelector('.detail-wait')?.textContent ?? null,+ criterion: part('Criterion')?.querySelector('.text').innerText ?? null,+ check: part('Check') ? [part('Check').querySelector('code').textContent, part('Check').querySelector('.chip').textContent] : null,+ brief: part('Brief')?.querySelector('.text').innerText ?? null,+ verdicts: [...detail.querySelectorAll('.verdict')].map((verdict) => [verdict.classList.contains('yes') ? 'ACCEPT' : 'REJECT', verdict.querySelector('.note').innerText]),+ moves: [...detail.querySelectorAll('.tl > li:not(.tl-fact) b')].map((move) => move.textContent),+ facts: [...detail.querySelectorAll('.tl > .tl-fact .tl-body')].map((fact) => fact.textContent),+ };+})()`;++test('opening an item loads its detail on demand [N26,A2]', { timeout: 150_000 }, // budget: hang-only ceiling for one live view and one export in a single Chrome, with two board polls.+ async () => {+ const executable = chromeExecutable();+ assert.ok(executable, 'Chrome is required to open items in the view');+ const box = machine();+ const alpha = project(box, 'detail-demand');+ box.run(alpha.repo, 'add', 'web', 'Offline greeting', '--specs', 'G1', '--criterion', 'The greeting renders from the snapshot alone.', '--brief', 'Keep the greeting short.', '--check', 'true');+ box.run(alpha.repo, 'add', 'web', 'Farewell page', '--specs', 'G1', '--criterion', 'The farewell mentions the zeppelin.');+ box.run(alpha.repo, 'add', 'web', 'Footer', '--specs', 'G1', '--criterion', 'The footer renders.');+ build(box, alpha, 1, 'greeting.html');+ sendBack(box, alpha, 1, 'the first greeting needs a correction');+ box.run(alpha.web, 'fact', '1', 'measurement', 'The corrected greeting renders offline.');+ build(box, alpha, 1, 'greeting-fix.html');+ accept(box, alpha, 1);+ build(box, alpha, 2, 'farewell.html');+ box.run(alpha.repo, 'milestone', 'add', 'Launch', '--items', '1,2');++ const view = await startView(box);+ let chrome, host;+ try {+ chrome = await openSnapshotChrome(executable, 'about:blank', join(box.dir, 'detail-chrome'));+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: OBSERVE });+ await chrome.send('Page.navigate', { url: view.link.href });+ await chrome.waitFor("typeof data === 'object' && !!data?.project && document.querySelectorAll('#chain .row').length === 2 && document.querySelectorAll('#roadmap .milestone-item').length === 2");++ // The page starts on Shouts. Its lists, roadmap and counts are drawn from summaries, with no item read.+ const listed = await chrome.stable(`({+ tab: view.tab,+ summaries: data.project.items.every((item) => !('history' in item) && !('criterion' in item) && !('thread' in item)),+ rows: [...document.querySelectorAll('#chain .row')].map((row) => row.dataset.item),+ roadmap: [...document.querySelectorAll('#roadmap .milestone-item')].map((row) => row.querySelector('.id').textContent + ' ' + row.querySelector('.chip').textContent),+ reads: window.__pbReads,+ })`);+ assert.equal(listed.tab, 'shouts');+ assert.equal(listed.summaries, true, 'the view sends item summaries: no history, criterion or thread');+ assert.deepEqual(listed.rows.sort(), ['2', '3'], 'the Active list shows the submitted and the open item');+ assert.deepEqual(listed.roadmap, ['#1 verified', '#2 to verify'], 'the roadmap reads each item state from its summary');+ assert.deepEqual(itemReads(listed.reads), [], 'the list renders with no item detail fetched');++ // Search asks the API, which matches the criterion the summaries leave out, and its result opens the item.+ await chrome.stable('window.__pbHold = true');+ await searchFor(chrome, 'zeppelin', 15_000); // budget: hang-only ceiling for one search answer from the local view.+ await chrome.waitFor("!!document.querySelector('#find-results [data-find=\"item:2\"]')");+ assert.deepEqual(itemReads(await chrome.stable('window.__pbReads')), ['items?q=zeppelin'], 'the search sends its words to the API once');+ await press(chrome, "document.querySelector('#find-results [data-find=\"item:2\"]')");+ await chrome.waitFor("view.tab === 'items' && view.item === 2 && !!document.querySelector('#detail .detail-wait')");+ const waiting = await chrome.stable(DETAIL);+ assert.equal(waiting.waiting, 'Loading #2…', 'a short loading line shows while the detail is on its way');+ assert.deepEqual([waiting.title, waiting.criterion], [null, null], 'and no part of the item until it arrives');+ await chrome.stable('window.__pbRelease()');+ await chrome.waitFor("view.item === 2 && !document.querySelector('#detail .detail-wait') && !!document.querySelector('#detail .tl')");+ const farewell = await chrome.stable(DETAIL);+ assert.equal(farewell.criterion, 'The farewell mentions the zeppelin.');+ assert.deepEqual(farewell.moves, ['add', 'claim', 'submit']);+ assert.deepEqual(itemReads(await chrome.stable('window.__pbReads')), ['items?q=zeppelin', 'items/2'], 'opening an item makes exactly one detail request');++ // The verified item opens with its criterion, check, brief, verdicts and thread from one more request.+ await chrome.stable("(() => { const q = document.querySelector('#q'); q.value = ''; q.dispatchEvent(new Event('input', { bubbles: true })); q.blur(); })()");+ await chooseFilter(chrome, 'state:all');+ await press(chrome, "document.querySelector('#chain .row[data-item=\"1\"]')");+ await chrome.waitFor("view.item === 1 && !document.querySelector('#detail .detail-wait') && !!document.querySelector('#detail .tl')");+ const greeting = await chrome.stable(DETAIL);+ assert.equal(greeting.waiting, null, 'the detail has arrived');+ delete greeting.waiting;+ assert.deepEqual(greeting, {+ title: '#1Offline greeting',+ criterion: 'The greeting renders from the snapshot alone.',+ check: ['true', 'green'],+ brief: 'Keep the greeting short.',+ verdicts: [['REJECT', 'the first greeting needs a correction'], ['ACCEPT', 'the page shows it']],+ moves: ['add', 'claim', 'submit', 'reject', 'claim', 'submit', 'accept'],+ facts: ['The corrected greeting renders offline.'],+ }, 'the detail carries what the summary leaves out');+ assert.deepEqual(itemReads(await chrome.stable('window.__pbReads')), ['items?q=zeppelin', 'items/2', 'items/1']);++ // Reopening an item, and refreshes while the board changes elsewhere, ask for nothing more.+ await press(chrome, "document.querySelector('#chain .row[data-item=\"2\"]')");+ await chrome.waitFor("view.item === 2 && document.querySelector('#detail h2')?.innerText.includes('Farewell page') && !!document.querySelector('#detail .tl')");+ const states = await chrome.stable("window.__pbReads.filter((path) => /\\/state(\\?|$)/.test(path)).length");+ box.run(alpha.web, 'claim', '3');+ await chrome.waitFor(`window.__pbReads.filter((path) => /\\/state(\\?|$)/.test(path)).length > ${states} && !!document.querySelector('#chain .row[data-item="3"] .chip.busy')`, 15_000); // budget: hang-only ceiling for the page's 3-second board poll.+ assert.deepEqual(itemReads(await chrome.stable('window.__pbReads')), ['items?q=zeppelin', 'items/2', 'items/1'], 'a refresh does not refetch items that have not changed');++ // A change to the opened item asks for its detail once more.+ box.run(alpha.repo, 'fact', '2', 'note', 'The farewell was checked after it opened.');+ await chrome.waitFor("[...document.querySelectorAll('#detail .tl-fact .tl-body')].some((fact) => fact.textContent === 'The farewell was checked after it opened.')", 15_000); // budget: hang-only ceiling for the page's 3-second board poll and one detail read.+ assert.deepEqual(itemReads(await chrome.stable('window.__pbReads')), ['items?q=zeppelin', 'items/2', 'items/1', 'items/2'], 'only the changed item is read again');++ // The pipeline counts each stage from the summaries, with no further read.+ await press(chrome, "document.querySelector('[data-items-view=\"pipeline\"]')");+ await chrome.waitFor("!!document.querySelector('#pipeline [data-stage-count=\"open\"]')");+ const stages = await chrome.stable("Object.fromEntries([...document.querySelectorAll('#pipeline [data-stage-count]')].map((count) => [count.dataset.stageCount, count.textContent]))");+ assert.deepEqual(stages, { open: '0', claimed: '1', submitted: '1', accepted: '1', merged: '0' });+ assert.deepEqual(itemReads(await chrome.stable('window.__pbReads')), ['items?q=zeppelin', 'items/2', 'items/1', 'items/2']);+ assert.deepEqual(chrome.exceptions, [], 'the live view opens items without browser exceptions');+ await view.stop();++ // An export holds every item in full: it opens an item and searches its criteria offline, asking nothing.+ const folder = join(box.dir, 'detail-export');+ box.run(alpha.repo, 'view', '--export', folder);+ host = await serveFolder(folder, '/demo/');+ await chrome.send('Page.navigate', { url: `${host.base}/demo/#items/1` });+ await chrome.waitFor("document.body.classList.contains('snapshot') && !!data?.project && snapshotReplay.index === snapshotReplay.events.length && view.item === 1 && !!document.querySelector('#detail .tl')");+ const exported = await chrome.stable(DETAIL);+ assert.equal(exported.criterion, 'The greeting renders from the snapshot alone.');+ assert.deepEqual(exported.verdicts, [['REJECT', 'the first greeting needs a correction'], ['ACCEPT', 'the page shows it']]);+ assert.deepEqual(exported.facts, ['The corrected greeting renders offline.']);+ await searchFor(chrome, 'zeppelin', 15_000); // budget: hang-only ceiling for a search the page answers itself.+ await chrome.waitFor("!!document.querySelector('#find-results [data-find=\"item:2\"]')");+ assert.deepEqual(itemReads(await chrome.stable('window.__pbReads')), [], 'the export asks for no item detail or search');+ assert.deepEqual(host.requests.filter((request) => request.path.includes('/items') || request.status !== 200), [],+ 'every export request is one of its own files');+ assert.deepEqual(chrome.exceptions, [], 'the export opens items without browser exceptions');+ } finally {+ if (chrome) await closeSnapshotChrome(chrome);+ await host?.close();+ await view.stop();+ }+ });+++test('a failed criterion-only search can be retried without changing the board [N26,A2]', { timeout: 150_000 }, // budget: hang-only ceiling for one live view and one real Chrome search retry.+ async () => {+ const executable = chromeExecutable();+ assert.ok(executable, 'Chrome is required to retry a criterion-only search');+ const box = machine();+ const alpha = project(box, 'detail-search-retry');+ box.run(alpha.repo, 'add', 'web', 'A searchable item', '--specs', 'G1', '--criterion', 'The moonstone appears only in this criterion.');++ const view = await startView(box);+ let chrome;+ try {+ chrome = await openSnapshotChrome(executable, 'about:blank', join(box.dir, 'detail-search-retry-chrome'));+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: `(() => {+ const nativeFetch = window.fetch.bind(window);+ window.__pbSearchAttempts = [];+ window.__pbFirstSearchFailureParsed = false;+ window.__pbFailSearchOnce = true;+ window.fetch = async (input, init) => {+ const url = new URL(typeof input === 'string' ? input : input.url, location.href);+ if (/\\/api\\/v1\\/boards\\/[^/]+\\/items$/.test(url.pathname) && url.searchParams.has('q')) {+ window.__pbSearchAttempts.push(url.pathname + url.search);+ const response = await nativeFetch(input, init);+ if (window.__pbFailSearchOnce) {+ window.__pbFailSearchOnce = false;+ const failed = new Response(JSON.stringify({ error: { code: 'TEMPORARY_SEARCH_FAILURE', message: 'temporary fixture failure' } }), {+ status: 503,+ headers: { 'content-type': 'application/json' },+ });+ const readJson = failed.json.bind(failed);+ failed.json = async () => {+ const value = await readJson();+ window.__pbFirstSearchFailureParsed = true;+ return value;+ };+ return failed;+ }+ return response;+ }+ return nativeFetch(input, init);+ };+ })()` });+ await chrome.send('Page.navigate', { url: view.link.href });+ await chrome.waitFor("typeof data === 'object' && !!data?.project && document.querySelectorAll('#chain .row').length === 1");+ const boardBefore = await chrome.stable(`JSON.stringify(data.project.items.map((item) => ({ id: item.id, title: item.title, status: item.status, updatedAt: item.updatedAt })))`);++ await searchFor(chrome, 'moonstone', 15_000); // budget: hang-only ceiling for the first search response.+ await chrome.waitFor('window.__pbFirstSearchFailureParsed === true');+ assert.equal(await chrome.stable("[...document.querySelectorAll('#find-results [data-find]')].filter((node) => node.dataset.find.startsWith('item:')).length"), 0,+ 'the first API response fails and the criterion-only match is not shown');+ assert.equal(await chrome.stable('window.__pbSearchAttempts.length'), 1, 'the first query made one real local API request');+ // Let the rejected API promise and its retry-cache cleanup finish before issuing the same query again.+ await chrome.stable('new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))');+ await chrome.stable("(() => { const q = document.querySelector('#q'); q.value = ''; q.dispatchEvent(new Event('input', { bubbles: true })); })()");++ await searchFor(chrome, 'moonstone', 15_000); // budget: hang-only ceiling after the retry is synchronously counted.+ const attempts = await chrome.stable('window.__pbSearchAttempts.length');+ assert.equal(attempts, 2, 'the same query starts a second API request after the first one failed');+ await chrome.waitFor("[...document.querySelectorAll('#find-results [data-find]')].some((node) => node.dataset.find === 'item:1')");+ const result = await chrome.stable(`JSON.stringify({+ attempts: window.__pbSearchAttempts,+ board: data.project.items.map((item) => ({ id: item.id, title: item.title, status: item.status, updatedAt: item.updatedAt })),+ hit: document.querySelector('#find-results [data-find="item:1"]')?.textContent.trim() ?? null,+ })`);+ const parsed = JSON.parse(result);+ assert.equal(parsed.attempts[1], parsed.attempts[0], 'retry repeats the identical criterion-only search URL');+ assert.match(parsed.attempts[0], /\/items\?q=moonstone$/u);+ assert.deepEqual(parsed.board, JSON.parse(boardBefore), 'search and retry leave the board state unchanged');+ assert.match(parsed.hit, /A searchable item/u);+ assert.deepEqual(chrome.exceptions, [], 'the failed search can be retried without a browser exception');+ await view.stop();+ } finally {+ if (chrome) await closeSnapshotChrome(chrome);+ await view.stop();+ }+ });diff --git a/test/cockpit/fixture.js b/test/cockpit/fixture.jsindex bf6c5cee..cc4b0ed2 100644--- a/test/cockpit/fixture.js+++ b/test/cockpit/fixture.js@@ -574,7 +574,7 @@ async function boardId(view, root) {/** The board as the shared API serves it for one project. */async function boardOf(view, root) {const id = await boardId(view, root);- const res = await fetchLive(`${view.base}/api/v1/boards/${id}/state`, { headers: { 'x-pullboard-key': view.key } });+ const res = await fetchLive(`${view.base}/api/v1/boards/${id}/state?detail=full`, { headers: { 'x-pullboard-key': view.key } });assert.equal(res.status, 200);return (await res.json()).state;}diff --git a/test/cockpit/fixture.test.js b/test/cockpit/fixture.test.jsindex 911b4388..c73de5bd 100644--- a/test/cockpit/fixture.test.js+++ b/test/cockpit/fixture.test.js@@ -197,7 +197,7 @@ test('the page uses only API v1 for state, code and every offered move [A3,N26,Nassert.equal(moves[2].body.args.as, 'person');assert.equal(moves[2].body.item, ask);assert.equal(moves[4].body.args.off, true);- assert.ok(page.requests.every((request) => /^\/api\/v1\/boards(?:$|\/[^/]+\/(?:state|code|moves)(?:\?|$))/.test(request.path)), 'every page request uses a public v1 path');+ assert.ok(page.requests.every((request) => /^\/api\/v1\/boards(?:$|\/[^/]+\/(?:state|code|moves|items\/\d+|items\?q=[^&]+)(?:\?|$))/.test(request.path)), 'every page request uses a public v1 path');assert.ok(page.requests.some((request) => request.path === '/api/v1/boards'));assert.ok(page.requests.some((request) => request.path === `/api/v1/boards/${id}/state`));assert.ok(page.requests.some((request) => request.path.startsWith(`/api/v1/boards/${id}/code?`)));diff --git a/test/cockpit/items.test.js b/test/cockpit/items.test.jsindex 3f2497dc..08bc105c 100644--- a/test/cockpit/items.test.js+++ b/test/cockpit/items.test.js@@ -55,7 +55,7 @@ test('a review in progress names its reviewer [N26]', async () => {assert.deepEqual(holds('web-2'), ['#1 Greeting: reviewing'], 'the reviewer holds it');assert.deepEqual(holds('web-1'), ['#1 Greeting: to verify'], 'the builder waits on it');// A name is board text, so it is escaped: give the board on hand a reviewer with markup and redraw.- page.run('data.project.items.find((i) => i.id === 1).reviewer = "web<b>"; render();');+ page.run('data.project.items.find((i) => i.id === 1).claim.by = "web<b>"; render();');assert.match(itemRow(page.show('chain'), 1), />web<b> reviewing<\/span><\/li>$/);await page.run('refresh()');@@ -799,7 +799,7 @@ test("item detail merges API facts and moves in one responsive timeline [B33,B29['note', 'capture', 'measurement', 'diff', 'decision', 'rejection', 'supersession', 'root-cause'],'the API provides every fact in append order');chrome = await openSnapshotChrome(executable, view.link.href, profile);- await chrome.waitFor('typeof data !== "undefined" && data?.project?.items?.find((item) => item.id === 1)?.thread?.length === ' + expected.length);+ await chrome.waitFor('typeof data !== "undefined" && !!data?.project?.items?.find((item) => item.id === 1)');await chrome.waitFor('document.querySelectorAll("#detail .tl [data-event-id]").length === ' + expected.length);const expectedIds = expected.map((entry) => entry.eventId);for (const width of [375, 1280]) {@@ -936,7 +936,7 @@ test('in-text item references stay inline and open their target at phone and desfor (const section of ['agents', 'spec', 'doctrine']) {if (section === 'agents') {await chrome.click(`document.querySelector('[data-tab="shouts"]')`);- const agent = await chrome.stable("(() => { const item=data.project.items.find(i => i.id===2); return item.owner || item.reviewer || item.builtBy; })()");+ const agent = await chrome.stable("(() => { const item=data.project.items.find(i => i.id===2); return item.claim?.by || item.builtBy; })()");if (!await chrome.stable(`!!document.querySelector('#agents .agent-card.on [data-agent="${agent}"]')`)) await chrome.click(`document.querySelector('#agents [data-agent="${agent}"]')`);await chrome.waitFor('document.querySelector("#agents [data-item=\\"2\\"]")');} else {diff --git a/test/cockpit/live.test.js b/test/cockpit/live.test.jsindex 0d529e9a..0427f59f 100644--- a/test/cockpit/live.test.js+++ b/test/cockpit/live.test.js@@ -139,7 +139,10 @@ test('the view shows a move as it happens [N26,A2]', { timeout: 120_000 }, asynct.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))}`);+ // The move is on the open item, so the page also reads that item's detail again (#548).+ const moveReads = sent(chrome, before);+ assert.ok(moveReads.some((line) => /^GET \/api\/v1\/boards\/[^/]+\/state$/.test(line)), `the page reread public state for the move: ${JSON.stringify(moveReads)}`);+ assert.ok(moveReads.every((line) => /^GET \/api\/v1\/boards(?:\/[^/]+\/(?:state|shouts\/\d+|items\/\d+))?$/.test(line)), `the page read the board for the move: ${JSON.stringify(moveReads)}`);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');diff --git a/test/cockpit/newcomer.test.js b/test/cockpit/newcomer.test.jsindex 8e43eebb..c32ec8c1 100644--- a/test/cockpit/newcomer.test.js+++ b/test/cockpit/newcomer.test.js@@ -108,7 +108,7 @@ test('the actual tour leaves a labelled demo visible at phone and desktop widthsawait chrome.waitFor(`innerWidth === ${width}`);assert.ok(await chrome.stable(`[...document.querySelectorAll('#proj-list [data-root]')].some(row => row.dataset.root === ${JSON.stringify(demo)} && /demo/.test(row.textContent))`), `${width}: the real tour board is listed and marked demo`);assert.equal(await chrome.stable('document.querySelector("#proj-name").textContent'), 'demo', `${width}: the selected board is the registered tour demo`);- assert.ok(await chrome.stable('data.project.items.some(item => item.status === "verified" && item.merged)'), `${width}: the tour\'s actual accepted history is visible`);+ assert.ok(await chrome.stable('data.project.items.some(item => item.status === "verified" && item.stage === "merged")'), `${width}: the tour\'s actual accepted history is visible`);await tab(chrome, 'items');await press(chrome, 'document.querySelector("#new-item")');assert.equal(await chrome.stable('document.querySelector("#add-lane").value'), 'app', `${width}: tour work also defaults to its building lane`);diff --git a/test/cockpit/references.test.js b/test/cockpit/references.test.jsindex 4e684f33..8c68b35d 100644--- a/test/cockpit/references.test.js+++ b/test/cockpit/references.test.js@@ -196,7 +196,7 @@ test('committed shout and fact references stay local, expand safely at phone andlet chrome;try {chrome = await openSnapshotChrome(executable, view.link.href, join(box.dir, 'local-code-chrome'));- await chrome.waitFor('typeof data === "object" && data?.project?.shouts?.length >= 3 && data?.project?.items?.[0]?.thread?.some((entry) => entry.type === "fact" && entry.ref)');+ await chrome.waitFor('typeof data === "object" && data?.project?.shouts?.length >= 3 && !!document.querySelector("#detail .fact-code button[data-code]")');for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 1000, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width}`);