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(view): share stable Chrome waits [N26]
Corey Olson81544079e733
diff --git a/src/cockpit.js b/src/cockpit.jsindex 39996292..e49146ff 100644--- a/src/cockpit.js+++ b/src/cockpit.js@@ -1892,7 +1892,7 @@ function pick(id, root = view.root) {/** Where the list and the detail stack (under 900px), bring the detail into view. */function reveal() {- if (matchMedia('(max-width: 900px)').matches) $('detail').scrollIntoView({ block: 'start' });+ if (matchMedia('(max-width: 900px)').matches) $('detail').scrollIntoView({ block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth' });}/**@@ -2066,6 +2066,14 @@ async function decideRow(kind, command, args, anchor) {if (root === view.root && view.specFeedback === feedback) {render();window.scrollTo({ top: scroll, behavior: 'instant' });+ // A phone row click jumps to its detail. A later list-key decision returns the next pick to view,+ // instead of restoring that detail's scroll position with the focused list still offscreen.+ if (feedback.from === 'list' && feedback.tone === 'ok' && next && view.row[kind] === next) {+ const picked = [...$(kind + '-list').querySelectorAll('[data-row]')].find((row) => row.dataset.row === prefix + next);+ const rect = picked?.getBoundingClientRect();+ // Center an offscreen pick: nearest can round a half-pixel edge just outside the viewport.+ if (rect && (rect.top < 0 || rect.bottom > innerHeight)) picked.scrollIntoView({ block: 'center', behavior: 'instant' });+ }if (!requests || feedback.status === 'done') setTimeout(() => { if (view.specFeedback === feedback) { view.specFeedback = null; render(); } }, 6000);}return requests ? Boolean(feedback.requestId) && feedback.status !== 'refused' : feedback.tone === 'ok';@@ -2231,7 +2239,7 @@ document.addEventListener('click', (event) => {render();$(kind + '-list').focus({ preventScroll: true });// Where the list and the detail stack, the picked row's detail, with its buttons, comes into view.- if (matchMedia('(max-width: 900px)').matches) $(kind + '-detail').scrollIntoView({ block: 'start', behavior: 'smooth' });+ if (matchMedia('(max-width: 900px)').matches) $(kind + '-detail').scrollIntoView({ block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth' });}else if (t.dataset.codeAll) showAllCode(t.dataset.codeAll, t.dataset.before || '');else if (t.dataset.codeLess) showLessCode(t.dataset.codeLess, t.dataset.before || '');diff --git a/test/cockpit/activity.test.js b/test/cockpit/activity.test.jsindex b5fd17e7..91d28c4e 100644--- a/test/cockpit/activity.test.js+++ b/test/cockpit/activity.test.js@@ -318,14 +318,14 @@ test('activity rows say what each shout and answer said [N26]', { timeout: 120_0chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor('!!document.querySelector(\'[data-tab="activity"]\')');await chrome.waitFor("typeof data === 'object' && !!data && !!data.project");- await chrome.evaluate('document.querySelector(\'[data-tab="activity"]\').click()');+ await chrome.click('document.querySelector(\'[data-tab="activity"]\')');await chrome.waitFor(`[...document.querySelectorAll('#activity .act')].some((row) => row.textContent.startsWith('coordinator (unknown) answered'))`);for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });// Measure only laid-out previews: on Activity, at this width, each preview with a box of its own.const laidOut = `innerWidth === ${width} && !document.querySelector('[data-pane="activity"]').hidden && [...document.querySelectorAll('#activity .said')].every((said) => said.getBoundingClientRect().height > 0)`;- await chrome.waitFor(laidOut).catch(async (error) => { throw new Error(`${error.message}; showing ${await chrome.evaluate("[...document.querySelectorAll('[data-pane]')].filter((pane) => !pane.hidden).map((pane) => pane.dataset.pane).join()")}`); });- const rows = JSON.parse(await chrome.evaluate(`JSON.stringify([...document.querySelectorAll('#activity .act')].map((row) => {+ await chrome.waitFor(laidOut).catch(async (error) => { throw new Error(`${error.message}; showing ${await chrome.stable("[...document.querySelectorAll('[data-pane]')].filter((pane) => !pane.hidden).map((pane) => pane.dataset.pane).join()")}`); });+ const rows = JSON.parse(await chrome.stable(`JSON.stringify([...document.querySelectorAll('#activity .act')].map((row) => {const said = row.querySelector('.said');const lines = said ? Math.round(said.getBoundingClientRect().height / parseFloat(getComputedStyle(said).lineHeight)) : 0;return { text: row.textContent, said: said?.textContent ?? null, tip: said?.title ?? null, lines, refs: said ? said.querySelectorAll('button.ref').length : 0,diff --git a/test/cockpit/agents.test.js b/test/cockpit/agents.test.jsindex 53c14c27..a742fd6f 100644--- a/test/cockpit/agents.test.js+++ b/test/cockpit/agents.test.js@@ -12,6 +12,7 @@ import { relayClientFixture } from '../relay-client-fixture.js';import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../../src/person.js';import { runFixtureChildAsync } from '../fixture-child.js';import { startChrome } from '../relay-browser-fixture.js';+import { stableChrome } from './stable.js';import { BIN, tapTarget, SPEC, machine, project, build, sendBack, startView, openPage, agentEntries, accept, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, earlier, shoutsAt, press, settled } from './fixture.js';@@ -83,13 +84,13 @@ test('the agents panel is rows for work and pills for idle [N26]', { timeout: 12try {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor('typeof data !== "undefined" && data?.project?.agents?.length >= 4 && data.project.shouts.length >= 2');- await chrome.evaluate("document.querySelector('[data-tab=shouts]').click()");+ await chrome.click("document.querySelector('[data-tab=shouts]')");await chrome.waitFor('document.querySelector("[data-pane=shouts]:not([hidden]) #agents [data-agent]")');- assert.equal(await chrome.evaluate("document.querySelectorAll('#agents .agent-pill').length + ':' + document.querySelector('#agents .fold-line[data-fold=\"idle\"]').getAttribute('aria-expanded')"), '0:false', 'the idle agents start folded');- await chrome.evaluate("(() => { const fold = document.querySelector('.fold-line[data-fold=\"idle\"]'); if (fold && fold.getAttribute('aria-expanded') !== 'true') fold.click(); })()");- const agents = await chrome.evaluate('data.project.agents.length');+ assert.equal(await chrome.stable("document.querySelectorAll('#agents .agent-pill').length + ':' + document.querySelector('#agents .fold-line[data-fold=\"idle\"]').getAttribute('aria-expanded')"), '0:false', 'the idle agents start folded');+ await chrome.stable("(document.querySelector('.fold-line[data-fold=\"idle\"]'))?.getAttribute('aria-expanded') !== 'true' && !!(document.querySelector('.fold-line[data-fold=\"idle\"]'))").then(open => open ? chrome.click("document.querySelector('.fold-line[data-fold=\"idle\"]')") : undefined);+ const agents = await chrome.stable('data.project.agents.length');/** The panel as it reads: each row and pill, measured where it stands. */- const panel = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const panel = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const box = (e) => { const r = e.getBoundingClientRect(); return { height: r.height, width: r.width }; };const list = document.querySelector('#agents');return {@@ -130,18 +131,18 @@ test('the agents panel is rows for work and pills for idle [N26]', { timeout: 12// A row filters the feed to that agent and addresses the composer to it, and opens to each thing it holds.await shoutsAt(chrome, 1280, 'light');- await chrome.evaluate(`document.querySelector('#agents .agent-row[data-agent="web-1"]').click()`);+ await chrome.click(`document.querySelector('#agents .agent-row[data-agent="web-1"]')`);let p = await panel();assert.deepEqual([p.rows[0].on, p.rows[0].work.map(([id]) => id), p.chip, p.to, p.cards], [true, ['1', '2'], 'to web-1 (Test Model)×', 'web-1', [['web-1 (Test Model)', 'coordinator (unknown)']]],`the picked row opens to what it holds, the feed shows its shouts and the composer is addressed to it: ${JSON.stringify(p)}`);assert.ok(p.rows[0].work.every(([, height]) => height >= tapTarget(1280)), 'each thing it holds is a target');// A pill does the same.- await chrome.evaluate(`document.querySelector('#agents .agent-pill[data-agent="web-2"]').click()`);+ await chrome.click(`document.querySelector('#agents .agent-pill[data-agent="web-2"]')`);p = await panel();assert.deepEqual([p.pills.find((pill) => pill.id === 'web-2').on, p.chip, p.cards], [true, 'to web-2 (Test Model)×', [['web-2 (Test Model)', 'coordinator (unknown)']]], 'a pill filters and addresses too');// And a thing an agent holds opens its item.- await chrome.evaluate(`document.querySelector('#agents .agent-row[data-agent="web-1"]').click()`);- await chrome.evaluate(`document.querySelector('#agents .agent-work[data-item="2"]').click()`);+ await chrome.click(`document.querySelector('#agents .agent-row[data-agent="web-1"]')`);+ await chrome.click(`document.querySelector('#agents .agent-work[data-item="2"]')`);await chrome.waitFor(`!document.querySelector('[data-pane=items]').hidden && document.querySelector('#detail h2')?.textContent.includes('Footer')`);assert.deepEqual(chrome.exceptions, [], 'the page raises no uncaught exception');} finally {@@ -183,7 +184,7 @@ test('agent model display names follow the API on phone and desktop [O8,N26]', {const profile = mkdtempSync(join(tmpdir(), 'pullboard-model-names-chrome-'));let chrome;/** Read rendered text from the real browser without changing its API data. */- const text = (selector) => chrome.evaluate(`document.querySelector(${JSON.stringify(selector)})?.textContent || ''`);+ const text = (selector) => chrome.stable(`document.querySelector(${JSON.stringify(selector)})?.textContent || ''`);/** Press a real control and wait until its requested pane is drawn. */const tab = async (name) => {await press(chrome, `document.querySelector('[data-tab="${name}"]')`);@@ -200,12 +201,12 @@ test('agent model display names follow the API on phone and desktop [O8,N26]', {writeFileSync(configFile, JSON.stringify(config, null, 2));box.git(alpha.repo, 'add', 'pullboard.json');box.git(alpha.repo, 'commit', '-q', '-m', 'chore: use prefix names');- await chrome.evaluate('refresh()');+ await chrome.stable('refresh()');}const expected = style === 'suffix'? { builder: 'web-1 (' + model + ')', reviewer: 'coordinator (Claude)', unknown: 'web-2 (unknown)' }: { builder: 'gpt-6-with-a-very-long-model-declaration-for-readable-agent-names-web-1', reviewer: 'claude-coordinator', unknown: 'unknown-web-2' };- const apiNames = JSON.parse(await chrome.evaluate('JSON.stringify(Object.fromEntries(data.project.agents.map(a => [a.agent_id, a.displayName])))'));+ const apiNames = JSON.parse(await chrome.stable('JSON.stringify(Object.fromEntries(data.project.agents.map(a => [a.agent_id, a.displayName])))'));assert.deepEqual(apiNames, { coordinator: expected.reviewer, 'web-1': expected.builder, 'web-2': expected.unknown }, `${style}: authoritative API names`);for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });@@ -232,12 +233,12 @@ test('agent model display names follow the API on phone and desktop [O8,N26]', {for (const [id, label] of [['web-1', expected.builder], ['web-2', expected.unknown]]) {assert.equal(await text(`#agents [data-agent="${id}"] .agent-who b`), label, `${at}: agent panel ${id}`);}- if (!await chrome.evaluate('Boolean(view.open.idle)')) await press(chrome, 'document.querySelector("[data-fold=idle]")');+ if (!await chrome.stable('Boolean(view.open.idle)')) await press(chrome, 'document.querySelector("[data-fold=idle]")');assert.equal((await text('#agents [data-agent="coordinator"]')).trim(), expected.reviewer, `${at}: idle agent model`);const feed = await text('#feed');assert.ok(feed.includes(expected.builder) && feed.includes(expected.unknown) && feed.includes(expected.reviewer), `${at}: shout sender and recipient names`);assert.ok(feed.includes('→ all') && feed.includes('→ person'), `${at}: person and broadcast recipients keep their names`);- const headers = JSON.parse(await chrome.evaluate(`JSON.stringify([...document.querySelectorAll('#feed .shout header')].map(header => {+ const headers = JSON.parse(await chrome.stable(`JSON.stringify([...document.querySelectorAll('#feed .shout header')].map(header => {const rect = header.getBoundingClientRect();return { height: rect.height, line: parseFloat(getComputedStyle(header.querySelector('.who')).lineHeight),labels: [...header.querySelectorAll('.agent-label')].map(label => {@@ -265,7 +266,7 @@ test('agent model display names follow the API on phone and desktop [O8,N26]', {await press(chrome, 'document.querySelector("#agents [data-agent=\\"web-1\\"]")');await settled(chrome, 'view.agent === "web-1"');- assert.equal(await chrome.evaluate('view.agent'), 'web-1', `${at}: filtering retains the raw API id`);+ assert.equal(await chrome.stable('view.agent'), 'web-1', `${at}: filtering retains the raw API id`);await press(chrome, 'document.querySelector("[data-agent=\\"\\"]")');await tab('activity');const activity = await text('#activity');@@ -275,7 +276,7 @@ test('agent model display names follow the API on phone and desktop [O8,N26]', {await press(chrome, 'document.querySelector("#roadmap [data-go=\\"item:1\\"]")');await settled(chrome, 'view.tab === "items" && view.item === 1');assert.ok((await text('#detail')).includes(expected.builder), `${at}: roadmap item opens with the API identity`);- assert.ok(await chrome.evaluate('document.documentElement.scrollWidth <= innerWidth'), `${at}: no sideways overflow`);+ assert.ok(await chrome.stable('document.documentElement.scrollWidth <= innerWidth'), `${at}: no sideways overflow`);}}assert.deepEqual(chrome.exceptions, [], 'all model-name views run without browser exceptions');@@ -346,9 +347,9 @@ test('local agents panel inventories and phone-revokes a scoped credential [H2,Hconst pending = await waitFixture(() => existsSync(machineFile) && JSON.parse(readFileSync(machineFile, 'utf8')).pending,'foreground pairing publishes the one-use device enrollment');const phone = await box.phoneSession();- const phoneChrome = await startChrome();+ const phoneChrome = await stableChrome(await startChrome());t.after(() => phoneChrome.close());- const localChrome = await startChrome();+ const localChrome = await stableChrome(await startChrome());t.after(() => localChrome.close());assert.equal((await phoneChrome.send('Network.setCookie', {name: 'pb_session', value: phone.token, url: box.origin, httpOnly: true, sameSite: 'Lax',@@ -379,31 +380,18 @@ test('local agents panel inventories and phone-revokes a scoped credential [H2,Hawait localChrome.waitFor("typeof data === 'object' && !!data?.project");/** Deliver actual mouse input only after layout settles and the target is uncovered. */const tap = async (selector) => {- await localChrome.waitFor(`Boolean(document.querySelector(${JSON.stringify(selector)})?.getBoundingClientRect().width)`);- const point = JSON.parse(await localChrome.evaluate(`(async () => {- const find=()=>document.querySelector(${JSON.stringify(selector)}); const e=find();- e.scrollIntoView({block:'center',inline:'nearest'});- const frame=()=>new Promise(done=>requestAnimationFrame(()=>done())); let previous='', stable=0;- for(let i=0;i<120&&stable<2;i++){await frame();const n=find(),r=n?.getBoundingClientRect(),v=r?[r.x,r.y,r.width,r.height,scrollX,scrollY].join():'';stable=v&&v===previous?stable+1:0;previous=v;}- const n=find(),r=n?.getBoundingClientRect(); if(!n||!r||r.width<=0||r.height<=0)throw Error('control is not laid out');- const x=r.x+r.width/2,y=r.y+r.height/2,hit=document.elementFromPoint(x,y);- if(hit!==n&&!n.contains(hit))throw Error('the real mouse point is covered by another control');- return JSON.stringify({x,y});- })()`));- for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) await localChrome.send('Input.dispatchMouseEvent', {- type, ...point, ...(type === 'mouseMoved' ? {} : { button: 'left', clickCount: 1 }),- });+ await press(localChrome, `document.querySelector(${JSON.stringify(selector)})`);};await tap('[data-tab="shouts"]');for (const scheme of ['light', 'dark']) for (const width of [375, 1280]) {await localChrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await localChrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });await localChrome.waitFor(`innerWidth === ${width} && matchMedia('(prefers-color-scheme: ${scheme})').matches`);- if (!await localChrome.evaluate('Boolean(document.querySelector("[data-token-id]"))')) await tap('[data-credentials]');+ if (!await localChrome.stable('Boolean(document.querySelector("[data-token-id]"))')) await tap('[data-credentials]');for (const metadata of listed.document.tokens) {const selector = `[data-token-id="${metadata.id}"]`;await localChrome.waitFor(`Boolean(document.querySelector(${JSON.stringify(selector)}))`);- const row = JSON.parse(await localChrome.evaluate(`JSON.stringify((() => {+ const row = JSON.parse(await localChrome.stable(`JSON.stringify((() => {const e=document.querySelector(${JSON.stringify(selector)}),r=e.getBoundingClientRect();return {id:e.dataset.tokenId,text:e.innerText,overflow:document.documentElement.scrollWidth>document.documentElement.clientWidth,rowOverflow:r.right>document.documentElement.clientWidth};@@ -414,10 +402,10 @@ test('local agents panel inventories and phone-revokes a scoped credential [H2,H}assert.equal(row.text.includes(oldPA.token), false, 'the credential value never enters the DOM');for (const secret of [oldPA.token, otherPA.token, link.token, phone.token, readFileSync(box.keyFile, 'utf8').trim()]) {- assert.equal(await localChrome.evaluate(`document.documentElement.outerHTML.includes(${JSON.stringify(secret)}) || JSON.stringify(data).includes(${JSON.stringify(secret)}) || JSON.stringify([...credentials]).includes(${JSON.stringify(secret)})`), false,+ assert.equal(await localChrome.stable(`document.documentElement.outerHTML.includes(${JSON.stringify(secret)}) || JSON.stringify(data).includes(${JSON.stringify(secret)}) || JSON.stringify([...credentials]).includes(${JSON.stringify(secret)})`), false,'the local page, projected board and inventory retain no credential value or board key');}- assert.equal(await localChrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).querySelector('[data-revoke-token]').getBoundingClientRect().height >= 44`), true,+ assert.equal(await localChrome.stable(`document.querySelector(${JSON.stringify(selector)}).querySelector('[data-revoke-token]').getBoundingClientRect().height >= 44`), true,`${width}/${scheme}: revocation has a full touch target`);assert.equal(row.overflow || row.rowOverflow, false, `${width}/${scheme}: the inventory stays within the viewport`);@@ -436,18 +424,9 @@ test('local agents panel inventories and phone-revokes a scoped credential [H2,Hawait phoneChrome.navigate(`${box.origin}/#board=${board}&key=${encodedKey}`);await phoneChrome.waitFor("document.querySelector('#phone-approvals') !== null");await phoneChrome.waitFor(` [...document.querySelectorAll('.phone-approval')].some(node => node.textContent.includes(${JSON.stringify(expected.id)}))`);- const approvalPoint = JSON.parse(await phoneChrome.evaluate(`(() => {- const card=[...document.querySelectorAll('.phone-approval')].find(node=>node.textContent.includes(${JSON.stringify(expected.id)}));- const button=card?.querySelector('button'); button?.scrollIntoView({block:'center',behavior:'instant'});- const r=button?.getBoundingClientRect(); if(!r||r.width<=0||r.height<=0)throw Error('approval button is not visible');- const x=r.x+r.width/2,y=r.y+r.height/2,hit=document.elementFromPoint(x,y);- if(hit!==button&&!button.contains(hit))throw Error('approval mouse point is covered'); return JSON.stringify({x,y});- })()`));- for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) await phoneChrome.send('Input.dispatchMouseEvent', {- type, ...approvalPoint, ...(type === 'mouseMoved' ? {} : { button: 'left', clickCount: 1 }),- });+ await press(phoneChrome, `[...document.querySelectorAll('.phone-approval')].find(node => node.textContent.includes(${JSON.stringify(expected.id)}))?.querySelector('button')`);await localChrome.waitFor("document.querySelector('#credentials [role=status]')?.textContent.includes('Credential revoked.')");- assert.equal(await localChrome.evaluate(`document.querySelector('[data-token-id="${expected.id}"]')?.textContent.includes('Revoked')`), true, 'the acknowledged credential row is marked revoked');+ assert.equal(await localChrome.stable(`document.querySelector('[data-token-id="${expected.id}"]')?.textContent.includes('Revoked')`), true, 'the acknowledged credential row is marked revoked');assert.equal(box.calls.filter(call => call.path.endsWith('/authorize')).length, authorizationsBefore + 1,'one real phone tap authorizes exactly one revoke');diff --git a/test/cockpit/demo.test.js b/test/cockpit/demo.test.jsindex 1dcea8bd..9564b54e 100644--- a/test/cockpit/demo.test.js+++ b/test/cockpit/demo.test.js@@ -5,7 +5,8 @@ import { request } from 'node:http';import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';-import { tapTarget, machine, project, startView, boardOf, chromeExecutable, openSnapshotChrome, closeSnapshotChrome } from './fixture.js';+import { tapTarget, machine, project, startView, boardOf, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, press } from './fixture.js';+import { assertFirstStateDelay } from './stable.js';test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N26,N27]', { timeout: 120_000 }, async (t) => {@@ -46,30 +47,15 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2/** Click the actual control through Chrome input coordinates. */const click = async (selector) => {await waitRendered([selector]);- const point = JSON.parse(await chrome.evaluate(`(async () => {- const find=()=>document.querySelector(${JSON.stringify(selector)});- if(!find()) throw Error('missing '+${JSON.stringify(selector)});- find().scrollIntoView({block:'center'});- // Centering the sticky tab bar scrolls the page on for a few frames, so measure only once the- // target has held still for two frames; a point read mid-scroll lands on whatever slid under it.- // Find it afresh each frame: a refresh can redraw it, and a detached element measures as 0,0.- const frame=()=>new Promise((done)=>requestAnimationFrame(()=>done()));- let last='', still=0;- for (let n=0; n<120 && still<2; n++) { await frame(); const e=find(); const b=e?e.getBoundingClientRect():null, now=b?[b.x,b.y,b.width,b.height,scrollX,scrollY].join():''; still=now&&now===last?still+1:0; last=now; }- const e=find(); if(!e) throw Error('gone before the click: '+${JSON.stringify(selector)});- const r=e.getBoundingClientRect(); return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2});- })()`));- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...point });- await chrome.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...point, button: 'left', clickCount: 1 });- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...point, button: 'left', clickCount: 1 });+ await press(chrome, `document.querySelector(${JSON.stringify(selector)})`);};/** Fill a form field and deliver its input and change events. */- const fill = (selector, value) => chrome.evaluate(`(() => {+ const fill = (selector, value) => chrome.stable(`(() => {const e=document.querySelector(${JSON.stringify(selector)}); if(!e) throw Error('missing '+${JSON.stringify(selector)});e.value=${JSON.stringify(value)}; e.dispatchEvent(new Event('input',{bubbles:true})); e.dispatchEvent(new Event('change',{bubbles:true}));})()`);/** Submit a rendered form through native validation. */- const submit = (selector) => chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).requestSubmit()`);+ const submit = (selector) => chrome.stable(`document.querySelector(${JSON.stringify(selector)}).requestSubmit()`);/** Resize Chrome and wait for the board layout. */const setViewport = async (width) => {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });@@ -79,7 +65,7 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2/** Read actual visible target sizes and document geometry. */const snapshot = async () => {await waitRendered(['[data-pane]:not([hidden])']);- return JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ return JSON.parse(await chrome.stable(`JSON.stringify((() => {const visible=e=>{const s=getComputedStyle(e),r=e.getBoundingClientRect();return !e.disabled&&s.display!=='none'&&s.visibility!=='hidden'&&Number(s.opacity)!==0&&r.width>0&&r.height>0&&!e.closest('[hidden]')};const selector='button,a[href],input:not([type=hidden]),select,textarea,[role=button],[data-root],[data-tab],[data-go],[data-item],[data-state],[data-rows],[data-row],[data-release],[data-shout],[data-new],[data-code]';const controls=[...new Set(document.querySelectorAll(selector))].filter(visible).map(e=>{const r=e.getBoundingClientRect();return {tag:e.tagName,id:e.id||'',text:(e.innerText||e.getAttribute('aria-label')||'').trim().slice(0,60),x:r.x,y:r.y,right:r.right,bottom:r.bottom,width:r.width,height:r.height,inlineReference:e.matches('.feed button.ref, .shout button.ref, .shout .band a, .detail button.ref')||!!e.closest('#chain .meta .gate, #detail .kv dd.waits-on'),statusBar:(!!e.closest('.status')||(!!e.closest('.composer')&&innerWidth>=900))&&!matchMedia('(pointer: coarse)').matches,oneLine:!e.closest('.status')||getComputedStyle(e).whiteSpace==='nowrap'}});@@ -113,6 +99,16 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2await chrome.send('Emulation.setDeviceMetricsOverride', { width: 375, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor("document.readyState === 'complete' && !!document.querySelector('#chain .row')");+ await assertFirstStateDelay(chrome, t);+ await chrome.stable(`(() => {+ const probe=document.createElement('div'); probe.dataset.frameProbe='shared-wait';+ probe.style.cssText='position:fixed;left:0;top:0;width:1px;height:8px;background:transparent;pointer-events:none'; document.body.append(probe);+ let frame=0; const advance=()=>{ frame++; probe.dataset.frames=String(frame); probe.style.width=(frame+1)+'px'; if(frame<40)requestAnimationFrame(advance); };+ requestAnimationFrame(advance);+ })()`);+ const sampledFrames = Number(await chrome.stable("document.querySelector('[data-frame-probe]').dataset.frames", "document.querySelector('[data-frame-probe]')"));+ assert.equal(sampledFrames, 40, 'the shared real-Chrome wait does not measure a moving target before its box stops changing');+ await chrome.stable("document.querySelector('[data-frame-probe]').remove()");for (const width of [375, 1280]) {if (width === 1280) {box.run(demo.repo, 'shout', 'person', 'Should the desktop demo ship?', '--decision');@@ -130,21 +126,25 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2await click(`[data-root="${demo.repo}"]`);await chrome.waitFor("document.querySelector('#proj-name').textContent === 'phone-demo' && !!document.querySelector('#chain .row')");}- assert.ok(await chrome.evaluate("[...document.querySelectorAll('#proj-list .pname')].some(e=>e.textContent==='phone-demo')"), `${width}: demo appears in the project list`);- assert.ok(await chrome.evaluate("!!document.querySelector('#needs:not([hidden])')"), `${width}: Needs you is visible`);+ assert.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');- assert.ok(await chrome.evaluate("!!document.querySelector('#detail h2')"), `${width}: selected item detail is visible`);+ 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']) {await click(`[data-tab="${tab}"]`);await checkLayout(width, `${tab} tab`);if (tab === 'spec') {await waitRendered(['#spec-chips button']);- const chips = JSON.parse(await chrome.evaluate(`JSON.stringify([...document.querySelectorAll('#spec-chips button')].map(button => {- const clone=button.cloneNode(true); clone.style.cssText += ';position:fixed;visibility:hidden;width:max-content;flex:none'; button.parentElement.append(clone);- const naturalWidth=clone.getBoundingClientRect().width, actualWidth=button.getBoundingClientRect().width; clone.remove();- return {text:button.textContent.trim(),actualWidth,naturalWidth};- }))`));+ await chrome.stable(`document.querySelectorAll('#spec-chips button').forEach(button => {+ const clone=button.cloneNode(true); clone.dataset.naturalChip=''; clone.style.cssText += ';position:fixed;left:-10000px;opacity:0;width:max-content;flex:none'; button.parentElement.append(clone);+ })`);+ const chips = await chrome.stable(`(() => {+ const buttons=[...document.querySelectorAll('#spec-chips button:not([data-natural-chip])')];+ const clones=[...document.querySelectorAll('#spec-chips [data-natural-chip]')];+ return buttons.map((button,index) => ({text:button.textContent.trim(),actualWidth:button.getBoundingClientRect().width,naturalWidth:clones[index].getBoundingClientRect().width}));+ })()`, "document.querySelectorAll('#spec-chips button')");+ await chrome.stable("document.querySelectorAll('[data-natural-chip]').forEach(clone => clone.remove())");assert.ok(chips.length >= 2, `${width}: spec filters render as chips`);for (const chip of chips) assert.ok(Math.abs(chip.actualWidth - chip.naturalWidth) < 2, `${width}: ${chip.text} keeps its natural width: ${JSON.stringify(chip)}`);}@@ -153,7 +153,7 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2const element = [...document.querySelectorAll('#activity .what')].find(node => node.textContent === ${JSON.stringify(wrapTitle)});return element?.getBoundingClientRect().width > 0 && element.firstChild?.nodeType === Node.TEXT_NODE;})()`);- const wrap = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const wrap = JSON.parse(await chrome.stable(`JSON.stringify((() => {const element=[...document.querySelectorAll('#activity .what')].find(node=>node.textContent===${JSON.stringify(wrapTitle)});if(!element) return null;const text=element.firstChild, ranges=(word)=>{const start=text.textContent.indexOf(word),range=document.createRange();range.setStart(text,start);range.setEnd(text,start+word.length);return [...range.getClientRects()].map(rect=>({x:rect.x,y:rect.y,width:rect.width}));};@@ -165,9 +165,9 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2assert.ok(wrap.tokenLines > 1, `${width}: only the overflowing unbroken token splits: ${JSON.stringify(wrap)}`);}if (tab === 'shouts') {- await chrome.evaluate("(() => { const fold = document.querySelector('.asks-toggle[data-fold=\"waiting\"]'); if (fold && fold.getAttribute('aria-expanded') !== 'true') fold.click(); })()");+ await chrome.stable("(document.querySelector('.asks-toggle[data-fold=\"waiting\"]'))?.getAttribute('aria-expanded') !== 'true' && !!(document.querySelector('.asks-toggle[data-fold=\"waiting\"]'))").then(open => open ? chrome.click("document.querySelector('.asks-toggle[data-fold=\"waiting\"]')") : undefined);await waitRendered(['#decisions .shout:not(:has(.answer)) header', '#decisions .shout:not(:has(.answer)) .text', '#decisions .shout .answer']);- const asks = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const asks = JSON.parse(await chrome.stable(`JSON.stringify((() => {const waiting = document.querySelector('#decisions .shout:not(:has(.answer))');const waitingMeta = waiting?.querySelector('header');const waitingText = waiting?.querySelector('.text');@@ -212,7 +212,7 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2await chrome.waitFor(`document.querySelector('#feed').innerText.includes('Phone shout ${width}')`);await chrome.waitFor("!!document.querySelector('#decisions [data-go]')");- const decision = await chrome.evaluate("document.querySelector('#decisions [data-go]')?.getAttribute('data-go')");+ const decision = await chrome.stable("document.querySelector('#decisions [data-go]')?.getAttribute('data-go')");assert.ok(decision, `${width}: a decision is offered for answer`);await click(`#decisions [data-go="${decision}"]`);await checkLayout(width, 'answer form');@@ -228,7 +228,7 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2await chrome.waitFor("!document.querySelector('#lanes [data-release=web]')");}- const originalPointer = JSON.parse(await chrome.evaluate(`JSON.stringify({ fine:matchMedia('(pointer: fine)').matches, coarse:matchMedia('(pointer: coarse)').matches, none:matchMedia('(pointer: none)').matches })`));+ const originalPointer = JSON.parse(await chrome.stable(`JSON.stringify({ fine:matchMedia('(pointer: fine)').matches, coarse:matchMedia('(pointer: coarse)').matches, none:matchMedia('(pointer: none)').matches })`));await chrome.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 1 });await chrome.waitFor("matchMedia('(pointer: coarse)').matches");await setViewport(1280);@@ -240,7 +240,7 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2await chrome.send('Emulation.setTouchEmulationEnabled', { enabled: false });await chrome.waitFor(`matchMedia('(pointer: fine)').matches === ${originalPointer.fine} && matchMedia('(pointer: coarse)').matches === ${originalPointer.coarse} && matchMedia('(pointer: none)').matches === ${originalPointer.none}`);- await chrome.evaluate(`(() => {+ await chrome.stable(`(() => {const probe = document.createElement('div');probe.dataset.scrollbarProof = '';probe.style.cssText = 'position:absolute;left:0;top:0;width:2000px;height:1px;';@@ -251,7 +251,7 @@ test('real Chrome keeps the demo board usable at phone and desktop widths [H5,N2'the deliberate probe extends past the content viewport');assert.equal(fitsViewport(overflowingLayout), false,'the no-horizontal-overflow predicate detects deliberate content overflow');- await chrome.evaluate("document.querySelector('[data-scrollbar-proof]').remove()");+ await chrome.stable("document.querySelector('[data-scrollbar-proof]').remove()");await checkLayout(1280, 'after removing the deliberate overflow probe');const posts = chrome.requests.filter((request) => request.method === 'POST' && new URL(request.url).pathname.endsWith('/moves'));diff --git a/test/cockpit/fixture.js b/test/cockpit/fixture.jsindex 28806f52..0668a3ce 100644--- a/test/cockpit/fixture.js+++ b/test/cockpit/fixture.js@@ -7,6 +7,7 @@ import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { after, test } from 'node:test';import vm from 'node:vm';+import { stableChrome, press } from './stable.js';import { closeBoard, openBoard } from '../../src/board.js';import { fetchFresh } from '../http-fixture.js';@@ -664,41 +665,32 @@ async function openSnapshotChrome(executable, url, profile) {pending.set(key, { resolve, reject, timer });socket.send(JSON.stringify({ id: key, method, params }));});- /** Evaluate an expression in the page and return its by-value result. */- const evaluate = async (expression) => {- const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });- if (result.exceptionDetails) throw new Error(result.exceptionDetails.text);- return result.result.value;- };- /**- * Poll a page expression with a fixed deadline, without leaving a live interval behind. A condition that- * throws, as one does while the next document is still parsing, is not ready yet, so polling goes on; one- * that never holds fails at the deadline, naming the last error it threw. Exceptions the page throws by- * itself still reach exceptions: an evaluation's own exception is never reported there.- */- const waitFor = async (expression, timeoutMs = 10_000) => {- const deadline = Date.now() + timeoutMs;- let lastError = '';- while (Date.now() < deadline) {- try {- const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });- if (!result.exceptionDetails && result.result.value) return;- if (result.exceptionDetails) {- const details = result.exceptionDetails;- lastError = String(details.exception?.description ?? details.text).split('\n')[0];- }- } catch (error) {- lastError = error.message;- }- await browserPause(50);- }- throw new Error(`Browser condition did not arrive: ${expression}${lastError ? `; it last threw: ${lastError}` : ''}`);- };await send('Page.enable');await send('Runtime.enable');await send('Network.enable');- await send('Page.navigate', { url });- return { child, stopped, socket, send, evaluate, waitFor, requests, exceptions };+ const firstStateDelayMs = Number(process.env.PULLBOARD_CHROME_FIRST_STATE_DELAY_MS ?? 0);+ if (Number.isSafeInteger(firstStateDelayMs) && firstStateDelayMs > 0 && firstStateDelayMs <= 30_000) {+ await send('Page.addScriptToEvaluateOnNewDocument', { source: `(() => {+ const nativeFetch = window.fetch.bind(window); let delayed = false;+ window.fetch = (input, init) => {+ const url = typeof input === 'string' ? input : input.url;+ const path = new URL(url, location.href).pathname;+ if (!delayed && /^\\/api\\/v1\\/boards\\/[^/]+\\/state$/.test(path)) {+ delayed = true;+ const state = window.__pullboardFirstStateDelay = { started: performance.now(), ended: null };+ return new Promise((resolve, reject) => setTimeout(() => {+ state.ended = performance.now();+ nativeFetch(input, init).then(resolve, reject);+ }, ${firstStateDelayMs}));+ }+ return nativeFetch(input, init);+ };+ })()` });+ }+ const chrome = await stableChrome({ child, stopped, socket, send, requests, exceptions });+ await chrome.send('Page.navigate', { url });+ await chrome.waitFor("matchMedia('(prefers-reduced-motion: reduce)').matches");+ return chrome;} catch (error) {socket?.close();await stopOwnedChrome(child, stopped);@@ -745,7 +737,7 @@ async function watchSpecDecisionWait(chrome) {}};chrome.socket.addEventListener('message', onMessage);- await chrome.evaluate(`(() => {+ await chrome.stable(`(() => {if (window.__pullboardSpecKeys) return;window.__pullboardSpecKeys = [];const record = (event) => {@@ -767,7 +759,7 @@ async function watchSpecDecisionWait(chrome) {try {return timeoutMs === undefined ? await chrome.waitFor(expression) : await chrome.waitFor(expression, timeoutMs);} catch (error) {- const page = JSON.parse(await chrome.evaluate(`JSON.stringify({+ const page = JSON.parse(await chrome.stable(`JSON.stringify({selectedRow:typeof view === 'object' ? view.row?.spec ?? null : null,focusedElement:{tag:document.activeElement?.tagName||'',id:document.activeElement?.id||'',className:String(document.activeElement?.className||'')},lastKeyEvents:(window.__pullboardSpecKeys||[]).slice(-20)@@ -782,7 +774,7 @@ async function watchSpecDecisionWait(chrome) {async dispose() {chrome.socket.removeEventListener('message', onMessage);pending.clear();- await chrome.evaluate('window.__pullboardSpecKeysDispose?.()');+ await chrome.stable('window.__pullboardSpecKeysDispose?.()');},};}@@ -805,34 +797,16 @@ async function shoutsAt(chrome, width, scheme) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });await chrome.waitFor(`innerWidth === ${width} && matchMedia('(prefers-color-scheme: ${scheme})').matches && document.querySelector('#feed .shout')?.getBoundingClientRect().width > 0`);- await chrome.evaluate('new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)))');-}--/** Click what a page expression finds, through Chrome's own mouse input, as a person would. */-async function press(chrome, find) {- const point = JSON.parse(await chrome.evaluate(`(async () => {- const target = () => ${find};- if (!target()) throw new Error(${JSON.stringify(`nothing to press: ${find}`)});- target().scrollIntoView({ block: 'center' });- // Press where the target is when the press arrives: opening an item on a phone scrolls its detail into- // view, which moves the tab bar after it is measured (#255: measured at scroll 0, pressed at 32, landed on- // main). So measure once the target, found afresh each frame since a refresh can redraw it, has held still- // for two frames.- const frame = () => new Promise((done) => requestAnimationFrame(() => done()));- let last = '', still = 0;- for (let n = 0; n < 240 && still < 2; n++) { await frame(); const now = target() ? (({ x, y, width, height }) => [x, y, width, height, scrollX, scrollY].join())(target().getBoundingClientRect()) : ''; still = now && now === last ? still + 1 : 0; last = now; }- const element = target();- if (!element) throw new Error(${JSON.stringify(`gone before the press: ${find}`)});- const rect = element.getBoundingClientRect();- // Keep where the press really lands, so a wait that follows it can say so when it fails.- const name = (node) => node ? node.tagName.toLowerCase() + (node.id ? '#' + node.id : '') + (typeof node.className === 'string' && node.className ? '.' + node.className.trim().split(/\\s+/).join('.') : '') : 'nothing';- window.__pressed = { meant: name(element), at: Math.round(rect.y + rect.height / 2), scrollY: Math.round(scrollY) };- document.addEventListener('mousedown', (event) => Object.assign(window.__pressed, { landed: name(event.target), landedAt: Math.round(event.clientY), scrolledTo: Math.round(scrollY) }), { capture: true, once: true });- return JSON.stringify({ x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 });- })()`));- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...point });- await chrome.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...point, button: 'left', clickCount: 1 });- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...point, button: 'left', clickCount: 1 });+ await chrome.stable('new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)))');+}++/** Open the project picker when a phone hides it, then choose a rendered project or group. */+async function pickProject(chrome, find) {+ if (await chrome.stable("getComputedStyle(document.querySelector('#side .side-body')).display === 'none'")) {+ await chrome.click("document.querySelector('#proj-switch')");+ }+ await chrome.click(find);+ await chrome.waitFor("!document.body.classList.contains('switching') && data?.root === view.root");}/** Go back (-1) or forward (1) one entry in the tab's history, as the browser's own buttons do. */@@ -846,7 +820,7 @@ async function pressedInto(chrome, expression, timeoutMs = 10_000) {try {await chrome.waitFor(expression, timeoutMs);} catch (error) {- const shows = await chrome.evaluate(`JSON.stringify({ panes: [...document.querySelectorAll('[data-pane]')].filter((each) => !each.hidden).map((each) => each.dataset.pane), address: location.pathname + location.search + location.hash, lit: document.querySelector('.tab.on')?.dataset.tab ?? null, viewTab: typeof view === 'object' ? view.tab : null, item: typeof view === 'object' ? view.item : null, scrollY: Math.round(scrollY), pressed: window.__pressed ?? null, entries: history.length })`).catch((failure) => 'an unreadable page: ' + failure.message);+ const shows = await chrome.stable(`JSON.stringify({ panes: [...document.querySelectorAll('[data-pane]')].filter((each) => !each.hidden).map((each) => each.dataset.pane), address: location.pathname + location.search + location.hash, lit: document.querySelector('.tab.on')?.dataset.tab ?? null, viewTab: typeof view === 'object' ? view.tab : null, item: typeof view === 'object' ? view.item : null, scrollY: Math.round(scrollY), pressed: window.__pressed ?? null, entries: history.length })`).catch((failure) => 'an unreadable page: ' + failure.message);throw new Error(`${error.message}; the page shows ${shows}`, { cause: error });}}@@ -855,7 +829,7 @@ async function pressedInto(chrome, expression, timeoutMs = 10_000) {async function settled(chrome, expression, timeoutMs = 15_000) {const deadline = Date.now() + timeoutMs;while (Date.now() < deadline) {- try { if (await chrome.evaluate(expression)) return; } catch { /* The next page is still loading. */ }+ try { if (await chrome.stable(expression)) return; } catch { /* The next page is still loading. */ }await browserPause(50);}throw new Error(`Browser condition did not arrive: ${expression}`);@@ -878,7 +852,7 @@ function showing(pane, address) {* and how many lines the title takes and whether it is cut with an ellipsis.*/async function readRoadmap(chrome) {- return JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ return JSON.parse(await chrome.stable(`JSON.stringify((() => {const paint = (element) => getComputedStyle(element).color + ' on ' + getComputedStyle(element).backgroundColor;return {address: location.pathname + location.search + location.hash,@@ -916,20 +890,25 @@ async function readRoadmap(chrome) {* and the bar's edges. The tab picked now is picked again afterwards.*/async function tabBar(chrome) {- return JSON.parse(await chrome.evaluate(`JSON.stringify((() => {- const bar = document.querySelector('#tabs'), tabs = [...bar.querySelectorAll('.tab')], picked = tabs.find((tab) => tab.classList.contains('on'));- const layouts = tabs.map((on) => {- tabs.forEach((tab) => tab.classList.toggle('on', tab === on));- return { on: on.dataset.tab, bar: [bar.getBoundingClientRect().left, bar.getBoundingClientRect().right], tabs: tabs.map((tab) => {- const range = document.createRange();- range.selectNodeContents(tab.firstChild);- const box = tab.getBoundingClientRect(), label = range.getBoundingClientRect();- return { tab: tab.dataset.tab, left: box.left, right: box.right, labelLeft: label.left, labelRight: label.right };- }) };- });- tabs.forEach((tab) => tab.classList.toggle('on', tab === picked));- return { client: document.documentElement.clientWidth, layouts };- })())`));+ const tabs = await chrome.stable("[...document.querySelectorAll('#tabs .tab')].map(tab => tab.dataset.tab)");+ const picked = await chrome.stable("document.querySelector('#tabs .tab.on')?.dataset.tab");+ const layouts = [];+ try {+ for (const on of tabs) {+ await chrome.stable(`[...document.querySelectorAll('#tabs .tab')].forEach(tab => tab.classList.toggle('on', tab.dataset.tab === ${JSON.stringify(on)}))`);+ layouts.push(await chrome.stable(`(() => {+ const bar = document.querySelector('#tabs');+ return { on: ${JSON.stringify(on)}, bar: [bar.getBoundingClientRect().left, bar.getBoundingClientRect().right], tabs: [...bar.querySelectorAll('.tab')].map(tab => {+ const range = document.createRange(); range.selectNodeContents(tab.firstChild);+ const box = tab.getBoundingClientRect(), label = range.getBoundingClientRect();+ return { tab: tab.dataset.tab, left: box.left, right: box.right, labelLeft: label.left, labelRight: label.right };+ }) };+ })()`, "document.querySelectorAll('#tabs, #tabs .tab')"));+ }+ } finally {+ await chrome.stable(`[...document.querySelectorAll('#tabs .tab')].forEach(tab => tab.classList.toggle('on', tab.dataset.tab === ${JSON.stringify(picked)}))`);+ }+ return { client: await chrome.stable('document.documentElement.clientWidth'), layouts };}/** Serve a folder under a path prefix, as a static host does, recording each request and its status. */@@ -955,14 +934,14 @@ async function proofShot(chrome, name, width) {if (!process.env.PULLBOARD_ROADMAP_PROOF) return;mkdirSync(process.env.PULLBOARD_ROADMAP_PROOF, { recursive: true });for (const theme of ['light', 'dark']) {- await chrome.evaluate(`document.documentElement.dataset.theme = '${theme}'`);- const height = await chrome.evaluate('Math.ceil(document.documentElement.scrollHeight)');+ await chrome.stable(`document.documentElement.dataset.theme = '${theme}'`);+ const height = await chrome.stable('Math.ceil(document.documentElement.scrollHeight)');await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: Math.max(900, height), deviceScaleFactor: 2, mobile: false });await browserPause(150);const shot = await chrome.send('Page.captureScreenshot', { format: 'png' });writeFileSync(join(process.env.PULLBOARD_ROADMAP_PROOF, `${name}-${width}-${theme}.png`), Buffer.from(shot.data, 'base64'));}- await chrome.evaluate('delete document.documentElement.dataset.theme');+ await chrome.stable('delete document.documentElement.dataset.theme');await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });}@@ -972,12 +951,12 @@ async function proofShot(chrome, name, width) {* whether the results are hidden and what closed them (#394).*/async function searchFor(chrome, words, timeoutMs) {- await chrome.evaluate("document.querySelector('#q').focus(); document.querySelector('#q').select()");+ await chrome.stable("document.querySelector('#q').focus(); document.querySelector('#q').select()");await chrome.send('Input.insertText', { text: words });try {await chrome.waitFor(`document.querySelector('#q').value === ${JSON.stringify(words)} && !document.querySelector('#find-results').hidden`, timeoutMs);} catch (error) {- const state = await chrome.evaluate(`JSON.stringify((() => {+ const state = await chrome.stable(`JSON.stringify((() => {const q = document.querySelector('#q'), results = document.querySelector('#find-results'), at = document.activeElement;return { value: q.value, focused: at ? (at.id ? '#' + at.id : at.tagName.toLowerCase()) : null, windowFocus: document.hasFocus(), resultsHidden: results.hidden, closedBy: results.dataset.why || null };})())`);@@ -985,4 +964,4 @@ async function searchFor(chrome, words, timeoutMs) {}}-export { BIN, scratch, tapTarget, SPEC, machine, project, build, sendBack, fetchReason, fetchView, fetchLive, startView, styleOf, element, ageNodes, target, settle, storage, daysOn, openPage, projectRows, productEntries, timelineRows, agentEntries, drawing, textBoxes, meet, accept, needEntries, itemRow, boardId, boardOf, assertObservationAges, withoutObservationAges, assertObservationsEqual, shoutNameText, chromeExecutable, browserPause, startSnapshotChrome, openSnapshotChrome, stopOwnedChrome, closeSnapshotChrome, watchSpecDecisionWait, earlier, shoutsAt, press, travel, pressedInto, settled, roadmapRow, showing, readRoadmap, tabBar, serveFolder, proofShot, searchFor };+export { BIN, scratch, tapTarget, SPEC, machine, project, build, sendBack, fetchReason, fetchView, fetchLive, startView, styleOf, element, ageNodes, target, settle, storage, daysOn, openPage, projectRows, productEntries, timelineRows, agentEntries, drawing, textBoxes, meet, accept, needEntries, itemRow, boardId, boardOf, assertObservationAges, withoutObservationAges, assertObservationsEqual, shoutNameText, chromeExecutable, browserPause, startSnapshotChrome, openSnapshotChrome, stopOwnedChrome, closeSnapshotChrome, watchSpecDecisionWait, earlier, shoutsAt, press, pickProject, travel, pressedInto, settled, roadmapRow, showing, readRoadmap, tabBar, serveFolder, proofShot, searchFor };diff --git a/test/cockpit/item-waits.test.js b/test/cockpit/item-waits.test.jsindex 3b9bb689..825132bf 100644--- a/test/cockpit/item-waits.test.js+++ b/test/cockpit/item-waits.test.js@@ -6,7 +6,8 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';import { addItem, closeBoard, completeCheckBaseline, openBoard } from '../../src/board.js';-import { tapTarget, SPEC, machine, project, build, sendBack, startView, element, target, openPage, agentEntries, accept, itemRow, boardOf, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, settled } from './fixture.js';+import { tapTarget, SPEC, machine, project, build, sendBack, startView, element, target, openPage, agentEntries, accept, itemRow, boardOf, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, settled, press } from './fixture.js';+import { assertFirstStateDelay } from './stable.js';test('wait references stay on one line and link to every prerequisite at phone and desktop widths [N26]', { timeout: 90_000 }, async (t) => {@@ -23,74 +24,18 @@ test('wait references stay on one line and link to every prerequisite at phone achrome = await openSnapshotChrome(executable, view.link.href, join(box.dir, 'waits-chrome'));/** Pick a visible click target only after scrolling and its hit-test position have settled. */const click = async (selector) => {- const point = JSON.parse(await chrome.evaluate(`(async () => {- const element=document.querySelector(${JSON.stringify(selector)});- if (!element) throw Error('missing '+${JSON.stringify(selector)});- const visible=()=>{const style=getComputedStyle(element),rect=element.getBoundingClientRect();return style.display!=='none'&&style.visibility!=='hidden'&&rect.width>0&&rect.height>0&&!element.closest('[hidden]');};- if(!visible())throw Error('target is not visible: '+${JSON.stringify(selector)});- element.scrollIntoView({block:'center'});- const point=()=>{const currentElement=document.querySelector(${JSON.stringify(selector)});if(!currentElement)return null;const style=getComputedStyle(currentElement),rect=currentElement.getBoundingClientRect();if(style.display==='none'||style.visibility==='hidden'||rect.width<=0||rect.height<=0||currentElement.closest('[hidden]'))return null;const x=rect.x+rect.width/2,y=rect.y+rect.height/2,hit=document.elementFromPoint(x,y);return {x,y,scrollX,scrollY,rect:{x:rect.x,y:rect.y,width:rect.width,height:rect.height},hit:!!hit&&(hit===currentElement||currentElement.contains(hit))};};- const targets=[window,document,...(()=>{const nodes=[];for(let node=element.parentElement;node;node=node.parentElement)if(node.scrollHeight>node.clientHeight||node.scrollWidth>node.clientWidth)nodes.push(node);return nodes;})()];- let scrolled=false,scrollEnded=false;- const onScroll=()=>{scrolled=true;};- const onScrollEnd=()=>{scrollEnded=true;};- targets.forEach(target=>{target.addEventListener('scroll',onScroll,{passive:true});target.addEventListener('scrollend',onScrollEnd);});- try {- return JSON.stringify(await new Promise((resolve,reject)=>{- let previous=null,stable=0,frameId=0,finished=false;- const timeout=setTimeout(()=>{finished=true;cancelAnimationFrame(frameId);reject(Error('scroll did not settle for '+${JSON.stringify(selector)}+': '+JSON.stringify(previous)));},5000);- const frame=()=>{- if(finished)return;- const current=point();- if(!current){previous=null;stable=0;frameId=requestAnimationFrame(frame);return;}- const same=previous&&Math.abs(current.scrollX-previous.scrollX)<=.1&&Math.abs(current.scrollY-previous.scrollY)<=.1&&Math.abs(current.rect.x-previous.rect.x)<=.1&&Math.abs(current.rect.y-previous.rect.y)<=.1&&Math.abs(current.rect.width-previous.rect.width)<=.1&&Math.abs(current.rect.height-previous.rect.height)<=.1;- stable=same?stable+1:0;previous=current;- if(stable>=3&¤t.hit&&(!scrolled||scrollEnded||stable>=12)){finished=true;clearTimeout(timeout);resolve(current);return;}- frameId=requestAnimationFrame(frame);- };- frameId=requestAnimationFrame(frame);- }));- } finally { targets.forEach(target=>{target.removeEventListener('scroll',onScroll);target.removeEventListener('scrollend',onScrollEnd);}); }- })()`));- const deadline = Date.now() + 5000;- let ready;- let settled = false;- while (Date.now() < deadline) {- ready = JSON.parse(await chrome.evaluate(`(async()=>{- const sample=()=>{const element=document.querySelector(${JSON.stringify(selector)});if(!element)return null;const style=getComputedStyle(element),rect=element.getBoundingClientRect();if(style.display==='none'||style.visibility==='hidden'||rect.width<=0||rect.height<=0||element.closest('[hidden]'))return null;const x=rect.x+rect.width/2,y=rect.y+rect.height/2,hit=document.elementFromPoint(x,y);return {x,y,scrollX,scrollY,rect:{x:rect.x,y:rect.y,width:rect.width,height:rect.height},hit:!!hit&&(hit===element||element.contains(hit))};};- let previous=null,stable=0,current=null,frameId=0,finished=false;- await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{finished=true;cancelAnimationFrame(frameId);reject(Error('pointer target did not stabilize for '+${JSON.stringify(selector)}));},1500);const frame=()=>{if(finished)return;current=sample();const same=current&&previous&&Math.abs(current.scrollX-previous.scrollX)<=.1&&Math.abs(current.scrollY-previous.scrollY)<=.1&&Math.abs(current.rect.x-previous.rect.x)<=.1&&Math.abs(current.rect.y-previous.rect.y)<=.1&&Math.abs(current.rect.width-previous.rect.width)<=.1&&Math.abs(current.rect.height-previous.rect.height)<=.1;stable=same?stable+1:0;previous=current;if(stable>=2&¤t.hit){finished=true;clearTimeout(timeout);resolve();}else frameId=requestAnimationFrame(frame);};frameId=requestAnimationFrame(frame);});- return JSON.stringify(current);- })()`));- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: ready.x, y: ready.y });- const underPointer = JSON.parse(await chrome.evaluate(`(async()=>{- const sample=()=>{const element=document.querySelector(${JSON.stringify(selector)});if(!element)return null;const rect=element.getBoundingClientRect(),hit=document.elementFromPoint(${ready.x},${ready.y});return {scrollX,scrollY,rect:{x:rect.x,y:rect.y,width:rect.width,height:rect.height},hit:!!hit&&(hit===element||element.contains(hit))};};- let previous=null,stable=0,current=null,frameId=0,finished=false;- await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{finished=true;cancelAnimationFrame(frameId);reject(Error('pointer target did not stabilize for '+${JSON.stringify(selector)}));},1000);const frame=()=>{if(finished)return;current=sample();const same=current&&previous&&Math.abs(current.scrollX-previous.scrollX)<=.1&&Math.abs(current.scrollY-previous.scrollY)<=.1&&Math.abs(current.rect.x-previous.rect.x)<=.1&&Math.abs(current.rect.y-previous.rect.y)<=.1&&Math.abs(current.rect.width-previous.rect.width)<=.1&&Math.abs(current.rect.height-previous.rect.height)<=.1;stable=same?stable+1:0;previous=current;if(stable>=2&¤t.hit){finished=true;clearTimeout(timeout);resolve();}else frameId=requestAnimationFrame(frame);};frameId=requestAnimationFrame(frame);});return JSON.stringify({current,stable});- })()`));- if (underPointer?.current?.hit && underPointer.stable >= 2 && Math.abs(underPointer.current.scrollX-ready.scrollX)<=.1 && Math.abs(underPointer.current.scrollY-ready.scrollY)<=.1 && Math.abs(underPointer.current.rect.x-ready.rect.x)<=.1 && Math.abs(underPointer.current.rect.y-ready.rect.y)<=.1 && Math.abs(underPointer.current.rect.width-ready.rect.width)<=.1 && Math.abs(underPointer.current.rect.height-ready.rect.height)<=.1) {- point.x = ready.x;- point.y = ready.y;- point.scrollX = ready.scrollX;- point.scrollY = ready.scrollY;- point.rect = ready.rect;- settled = true;- break;- }- }- assert.ok(settled && ready && point.x === ready.x && point.y === ready.y,- `${selector}: scroll and target geometry settle under the pointer before press: ${JSON.stringify({ point, ready })}`);- await chrome.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 });- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 });+ await press(chrome, `document.querySelector(${JSON.stringify(selector)})`);};+ await chrome.waitFor("typeof data === 'object' && !!data?.project");+ await assertFirstStateDelay(chrome, t);for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width} && document.querySelector('#chain [data-item="3"] .meta .gate')?.getBoundingClientRect().width > 0`);await click('#chain [data-item="1"] .t');await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Prerequisite one')");- const itemIds = await chrome.evaluate('data.project.items.map(item => item.id + ":" + item.title + ":" + item.blockedBy.join(","))');- assert.ok(await chrome.evaluate('!!document.querySelector(\'#chain [data-item="3"]\')'), `${width}: blocked item appears among ${itemIds.join('; ')}`);- const list = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const itemIds = await chrome.stable('data.project.items.map(item => item.id + ":" + item.title + ":" + item.blockedBy.join(","))');+ assert.ok(await chrome.stable('!!document.querySelector(\'#chain [data-item="3"]\')'), `${width}: blocked item appears among ${itemIds.join('; ')}`);+ const list = JSON.parse(await chrome.stable(`JSON.stringify((() => {const gate=document.querySelector('#chain [data-item="3"] .meta .gate');const lineHeight=e=>parseFloat(getComputedStyle(e).lineHeight);const neighbors=[...gate.parentElement.children].filter(e=>e!==gate).map(lineHeight).filter(Number.isFinite);@@ -105,7 +50,7 @@ test('wait references stay on one line and link to every prerequisite at phone aawait click('#chain [data-item="3"] .t');await chrome.waitFor("!!document.querySelector('#detail .kv dd.waits-on')");- const detail = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const detail = JSON.parse(await chrome.stable(`JSON.stringify((() => {const waits=document.querySelector('#detail .kv dd.waits-on');const units=[...waits.querySelectorAll('.wait-unit')];return {height:waits.getBoundingClientRect().height,lineHeight:parseFloat(getComputedStyle(waits).lineHeight),unitWhiteSpaces:units.map(unit=>getComputedStyle(unit).whiteSpace),unitY:units.map(unit=>unit.getBoundingClientRect().y),diff --git a/test/cockpit/items.test.js b/test/cockpit/items.test.jsindex 1931083d..b49ff2d2 100644--- a/test/cockpit/items.test.js+++ b/test/cockpit/items.test.js@@ -281,9 +281,9 @@ test('a sent-back reason reads once [N26]', { timeout: 90_000 }, async () => {['1', 'Duplicate reason', 'BEHAVIOR_MISMATCH a78c361: selected-lane exception is unclear', 'a78c361: selected-lane exception is unclear'],['2', 'Plain note', 'BEHAVIOR_MISMATCH BEHAVIOR_MISMATCHED is a separate code-like prefix: the issue remains', 'BEHAVIOR_MISMATCHED is a separate code-like prefix: the issue remains'],]) {- await chrome.evaluate(`document.querySelector('#chain .row[data-item="${id}"]').click()`);+ await chrome.click(`document.querySelector('#chain .row[data-item="${id}"]')`);await chrome.waitFor(`document.querySelector('#detail h2')?.textContent.includes('${title}')`);- const rendered = JSON.parse(await chrome.evaluate(`JSON.stringify({+ const rendered = JSON.parse(await chrome.stable(`JSON.stringify({row: document.querySelector('#chain .row[data-item="${id}"] .why')?.textContent,card: document.querySelector('#detail .sentback .verdict .note')?.textContent,reason: document.querySelector('#detail .sentback .verdict b')?.textContent,@@ -576,7 +576,7 @@ test("item detail merges API facts and moves in one responsive timeline [B33,B29for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 1000, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width} && document.querySelector('#detail .tl')?.getBoundingClientRect().width > 0`);- const rendered = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const rendered = JSON.parse(await chrome.stable(`JSON.stringify((() => {const timeline = document.querySelector('#detail .tl');const old = document.querySelector('#detail #fact-${oldNote.id}');const replacement = document.querySelector('#detail #fact-${replacement.id}');@@ -622,10 +622,10 @@ test("item detail merges API facts and moves in one responsive timeline [B33,B29assert.equal(rendered.ref, `SPEC.md:1-2@${sourceHead}`, `${width}px: the committed code reference is actionable`);assert.equal(rendered.pageWidth, rendered.viewport, `${width}px: the timeline causes no sideways page scroll`);}- const scrollBefore = JSON.parse(await chrome.evaluate(`JSON.stringify({ page: document.documentElement.scrollTop, detail: document.querySelector('#detail').scrollTop })`));- await chrome.evaluate(`document.querySelector('#detail #fact-${oldNote.id} .thread-replacement').click()`);+ const scrollBefore = JSON.parse(await chrome.stable(`JSON.stringify({ page: document.documentElement.scrollTop, detail: document.querySelector('#detail').scrollTop })`));+ await chrome.click(`document.querySelector('#detail #fact-${oldNote.id} .thread-replacement')`);await chrome.waitFor(`location.hash === '#fact-${replacement.id}' && document.querySelector('#detail #fact-${replacement.id}')`);- const target = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const target = JSON.parse(await chrome.stable(`JSON.stringify((() => {const detail = document.querySelector('#detail'), fact = document.querySelector('#detail #fact-${replacement.id}');const box = fact.getBoundingClientRect(), panel = detail.getBoundingClientRect();return { item: view.item, id: fact.id, text: document.querySelector('#detail h2')?.textContent,@@ -638,10 +638,10 @@ test("item detail merges API facts and moves in one responsive timeline [B33,B29assert.ok(target.page > scrollBefore.page || target.detail > scrollBefore.detail,'following the replacement anchor scrolls to its existing target');assert.equal(target.visible, true, 'the replacement is visible after following its link');- await chrome.evaluate(`document.querySelector('#detail .tl-fact button[data-code]').click()`);+ await chrome.click(`document.querySelector('#detail .tl-fact button[data-code]')`);await chrome.waitFor(`document.querySelector('#detail .tl-fact button[data-code]')?.getAttribute('aria-expanded') === 'true'`);await chrome.waitFor(`document.querySelector('#detail .tl-fact .code')?.textContent.includes('Demo spec')`);- assert.match(await chrome.evaluate(`document.querySelector('#detail .tl-fact .code')?.textContent || ''`), /Demo spec/, 'the code reference opens the committed lines');+ assert.match(await chrome.stable(`document.querySelector('#detail .tl-fact .code')?.textContent || ''`), /Demo spec/, 'the code reference opens the committed lines');} finally {if (chrome) await closeSnapshotChrome(chrome);await view.stop();@@ -671,9 +671,9 @@ test('in-text item references stay inline and open their target at phone and desfor (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });// Needs you heads the Items list under Active; the steps below leave other tabs and filters open.- await chrome.evaluate("document.querySelector('[data-tab=items]').click(); document.querySelector('[data-state=active]').click()");+ await chrome.click("document.querySelector('[data-tab=items]')"); await chrome.click("document.querySelector('[data-state=active]')");// The row inlineReference stays on its title line beside the text.- const rendered = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const rendered = JSON.parse(await chrome.stable(`JSON.stringify((() => {const row = document.querySelector('#chain .row[data-item="2"]');const plain = document.querySelector('#chain .row[data-item="1"]');const titleRef = row?.querySelector('.t button.ref');@@ -706,24 +706,25 @@ 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.evaluate(`document.querySelector('[data-tab="shouts"]').click()`);- await chrome.evaluate("(() => { const item = data.project.items.find((i) => i.id === 2); const who = item.owner || item.reviewer || item.builtBy; if (!document.querySelector('#agents .agent-card.on [data-agent=\"' + who + '\"]')) document.querySelector('#agents [data-agent=\"' + who + '\"]').click(); })()");+ 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; })()");+ 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 {- await chrome.evaluate(`document.querySelector('[data-tab="${section}"]').click()`);- await chrome.evaluate(`document.querySelector('[data-rows="${section}:all"]').click()`);+ await chrome.click(`document.querySelector('[data-tab="${section}"]')`);+ await chrome.click(`document.querySelector('[data-rows="${section}:all"]')`);const citedRow = section === 'doctrine' ? 'R1' : 'G1';if (section === 'doctrine') {// Item citations normally point to SPEC ids; add the distinct practice id to the// browser projection to exercise the shared doctrine citing-item renderer.- await chrome.evaluate("data.project.items.find(item => item.id === 2).specs.push('R1'); render();");+ await chrome.stable("data.project.items.find(item => item.id === 2).specs.push('R1'); render();");}await chrome.waitFor(`document.querySelector('#${section}-list [data-row="${section}:${citedRow}"]')`);- await chrome.evaluate(`document.querySelector('#${section}-list [data-row="${section}:${citedRow}"]').click()`);+ await chrome.click(`document.querySelector('#${section}-list [data-row="${section}:${citedRow}"]')`);await chrome.waitFor(`document.querySelector('#${section}-detail [data-item="2"]')`);}const selector = section === 'agents' ? '#agents [data-item="2"] .ref' : `#${section}-detail .links [data-item="2"] .ref`;- const metrics = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const metrics = JSON.parse(await chrome.stable(`JSON.stringify((() => {const ref = document.querySelector(${JSON.stringify(selector)});const container = ref?.closest('[data-item="2"]');const r = ref?.getBoundingClientRect();@@ -737,29 +738,32 @@ test('in-text item references stay inline and open their target at phone and desassert.ok(Math.abs(metrics.refHeight - metrics.lineHeight) < 1, `${width}: ${section} reference keeps the text line height: ${JSON.stringify(metrics)}`);assert.ok(metrics.containerHeight >= tapTarget(width), `${width}: ${section} containing item keeps a target`);assert.equal(metrics.nestedButtons, 0, `${width}: ${section} title has no nested controls`);- await chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);+ await chrome.click(`document.querySelector(${JSON.stringify(selector)})`);await chrome.waitFor("document.querySelector('[data-tab=items].on') && document.querySelector('#detail h2')?.textContent.includes('Target item')");- await chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).closest('[data-item="2"]').click()`);+ await chrome.click(`document.querySelector('[data-tab="${section === 'agents' ? 'shouts' : section}"]')`);+ await chrome.click(`document.querySelector(${JSON.stringify(selector)}).closest('[data-item="2"]')`);await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Title links to #1')");}- await chrome.evaluate(`document.querySelector('#chain .row[data-item="2"] .t button.ref').click()`);+ await chrome.click(`document.querySelector('[data-tab="items"]')`);+ await chrome.click(`document.querySelector('#chain .row[data-item="2"] .t button.ref')`);await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Target item')");- await chrome.evaluate(`document.querySelector('#needs .row .t button.ref').click()`);+ await chrome.click("document.querySelector('[data-state=active]')");+ await chrome.click(`document.querySelector('#needs .row .t button.ref')`);await chrome.waitFor("document.querySelector('[data-tab=items].on') && document.querySelector('#detail h2')?.textContent.includes('Target item')");- await chrome.evaluate(`document.querySelector('[data-tab="activity"]').click()`);+ await chrome.click(`document.querySelector('[data-tab="activity"]')`);await chrome.waitFor("document.querySelector('#activity .what button.ref')");- await chrome.evaluate(`document.querySelector('#activity .what button.ref').click()`);+ await chrome.click(`document.querySelector('#activity .what button.ref')`);await chrome.waitFor("document.querySelector('[data-tab=items].on') && document.querySelector('#detail h2')?.textContent.includes('Target item')");- await chrome.evaluate(`document.querySelector('#chain .row[data-item="2"]').click()`);+ await chrome.click(`document.querySelector('#chain .row[data-item="2"]')`);await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Title links to #1') && document.querySelector('#detail .text button.ref') && document.querySelector('#detail .text.muted button.ref')");- await chrome.evaluate(`document.querySelector('#detail .text button.ref').click()`);+ await chrome.click(`document.querySelector('#detail .text button.ref')`);await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Target item')");- await chrome.evaluate(`document.querySelector('#chain .row[data-item="2"]').click()`);+ await chrome.click(`document.querySelector('#chain .row[data-item="2"]')`);await chrome.waitFor("document.querySelector('#detail .text.muted button.ref')");- await chrome.evaluate(`document.querySelector('#detail .text.muted button.ref').click()`);+ await chrome.click(`document.querySelector('#detail .text.muted button.ref')`);await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Target item')");}} finally {@@ -794,7 +798,7 @@ test('list rows hold their shape: one-line titles end in an ellipsis, every rowfor (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width}`);- const rows = JSON.parse(await chrome.evaluate(`JSON.stringify([...document.querySelectorAll('#chain .row')].map((row) => {+ const rows = JSON.parse(await chrome.stable(`JSON.stringify([...document.querySelectorAll('#chain .row')].map((row) => {const box = (node) => node.getBoundingClientRect();const lines = (node) => Math.round(box(node).height / parseFloat(getComputedStyle(node).lineHeight));const apart = (a, b) => a.right <= b.left + 0.5 || b.right <= a.left + 0.5 || a.bottom <= b.top + 0.5 || b.bottom <= a.top + 0.5;@@ -822,9 +826,9 @@ test('list rows hold their shape: one-line titles end in an ellipsis, every rowassert.match(chips[5], /^chip busy: web-\d+ \(Test Model\)$/, `${width}: a claimed item names who builds it, in the building colour`);// The same state wears the same chip in the item's detail as in its row.for (const row of rows) {- await chrome.evaluate(`document.querySelector('#chain .row[data-item="${row.id}"]').click()`);+ await chrome.click(`document.querySelector('#chain .row[data-item="${row.id}"]')`);await chrome.waitFor(`document.querySelector('#detail h2')?.textContent.startsWith('#${row.id}')`);- const detail = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const detail = JSON.parse(await chrome.stable(`JSON.stringify((() => {const chip = document.querySelector('#detail .meta.spaced .chip'), listed = document.querySelector('#chain .row[data-item="${row.id}"] > .chip');const paint = (node) => [getComputedStyle(node).backgroundColor, getComputedStyle(node).color, getComputedStyle(node).outlineStyle];return { chip: chip.className + ': ' + chip.textContent, samePaint: JSON.stringify(paint(chip)) === JSON.stringify(paint(listed)) };@@ -835,11 +839,11 @@ test('list rows hold their shape: one-line titles end in an ellipsis, every row}}// A builder's name can be long; its chip stops at its cap and ends in an ellipsis, leaving the title its line.- await chrome.evaluate("data.project.items.find((item) => item.id === 5).owner = 'claude-opus-designer-on-the-studio-7'; render();");+ await chrome.stable("data.project.items.find((item) => item.id === 5).owner = 'claude-opus-designer-on-the-studio-7'; render();");for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width} && document.querySelector('#chain .row[data-item="5"] > .chip')?.textContent.startsWith('claude-opus')`);- const named = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const named = JSON.parse(await chrome.stable(`JSON.stringify((() => {const row = document.querySelector('#chain .row[data-item="5"]'), chip = row.querySelector(':scope > .chip'), meta = row.querySelector('.meta');const a = chip.getBoundingClientRect(), b = meta.getBoundingClientRect();return { chipWidth: a.width, cap: 10 * parseFloat(getComputedStyle(document.documentElement).fontSize), cut: chip.scrollWidth > chip.clientWidth,@@ -885,17 +889,17 @@ test('Pipeline view shows every stage, status counts, stage ages, detail links achrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor(`data?.project?.root === ${JSON.stringify(alpha.repo)} && document.querySelector('#chain [data-item="5"]')`);const listRead = "JSON.stringify([...document.querySelectorAll('#chain > li[data-item]')].map(row => ({id:Number(row.dataset.item),title:row.title,meta:row.querySelector('.meta').textContent,tag:row.lastElementChild.textContent})))";- const listBefore = await chrome.evaluate(listRead);+ const listBefore = await chrome.stable(listRead);await press(chrome, "document.querySelector('[data-items-view=\"pipeline\"]')");- assert.equal(await chrome.evaluate('location.hash'), '#items/pipeline', 'Pipeline has its own shareable address');+ assert.equal(await chrome.stable('location.hash'), '#items/pipeline', 'Pipeline has its own shareable address');await chrome.waitFor("location.hash === '#items/pipeline' && !document.querySelector('#pipeline').hidden");const expectedCounts = [status.open, status.claimed, status.submitted, 1, 1];- const read = JSON.parse(await chrome.evaluate(`JSON.stringify([...document.querySelectorAll('[data-pipeline-stage]')].map(stage => ({ stage:stage.dataset.pipelineStage, label:stage.querySelector('h2').textContent, count:Number(stage.querySelector('[data-stage-count]').textContent), oldest:Number(stage.querySelector('.pipeline-oldest [data-item]')?.dataset.item || 0), since:stage.querySelector('.pipeline-oldest time')?.dataset.ago || null, age:stage.querySelector('.pipeline-oldest time')?.textContent || '', ids:[...stage.querySelectorAll('.pipeline-item')].map(item => Number(item.dataset.item)) })))`));+ const read = JSON.parse(await chrome.stable(`JSON.stringify([...document.querySelectorAll('[data-pipeline-stage]')].map(stage => ({ stage:stage.dataset.pipelineStage, label:stage.querySelector('h2').textContent, count:Number(stage.querySelector('[data-stage-count]').textContent), oldest:Number(stage.querySelector('.pipeline-oldest [data-item]')?.dataset.item || 0), since:stage.querySelector('.pipeline-oldest time')?.dataset.ago || null, age:stage.querySelector('.pipeline-oldest time')?.textContent || '', ids:[...stage.querySelectorAll('.pipeline-item')].map(item => Number(item.dataset.item)) })))`));assert.deepEqual(read.map(stage => stage.label), ['Not started', 'Building', 'Waiting for review', 'Accepted, waiting to merge', 'Merged']);assert.deepEqual(read.map(stage => stage.count), expectedCounts, 'open/claimed/submitted match status; accepted plus merged equals verified');assert.equal(read[3].count + read[4].count, status.verified);assert.deepEqual(read.map(stage => stage.ids), [[5, 6], [4], [3], [2], [1]], 'an accept without a merge remains waiting to merge');- const observedAt = await chrome.evaluate('Date.now()');+ const observedAt = await chrome.stable('Date.now()');for (const stage of read) {const [id, minute] = arrivals[stage.stage], since = new Date(base + minute * 60_000).toISOString();assert.equal(stage.oldest, id, stage.stage + ': oldest item');@@ -905,25 +909,26 @@ test('Pipeline view shows every stage, status counts, stage ages, detail links aconst elapsed = parseInt(stage.age, 10) * (stage.age.endsWith('h') ? 60 : 1);assert.ok(Math.abs(elapsed - (observedAt - Date.parse(since)) / 60_000) <= 1, stage.stage + ': elapsed time matches native fixture arrival');}- assert.equal(await chrome.evaluate("document.querySelector('#item-list').hidden"), true);+ assert.equal(await chrome.stable("document.querySelector('#item-list').hidden"), true);for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width}`);for (const scheme of ['light', 'dark']) {await chrome.send('Emulation.setEmulatedMedia', { features: [{name:'prefers-color-scheme',value:scheme}] });- await chrome.evaluate('(async()=>{await new Promise(requestAnimationFrame);await new Promise(requestAnimationFrame)})()');- assert.equal(await chrome.evaluate('document.documentElement.dataset.scheme'), scheme);+ await chrome.stable('(async()=>{await new Promise(requestAnimationFrame);await new Promise(requestAnimationFrame)})()');+ assert.equal(await chrome.stable('document.documentElement.dataset.scheme'), scheme);for (const id of [1, 2, 3, 4, 5, 6]) {await press(chrome, `document.querySelector('#pipeline .pipeline-item[data-item="${id}"]')`);- assert.equal(await chrome.evaluate('view.item'), id, `${width}: every item opens its detail`);+ await chrome.waitFor(`view.item === ${id}`);+ assert.equal(await chrome.stable('view.item'), id, `${width}: every item opens its detail`);await chrome.waitFor(`document.querySelector('#detail h2')?.textContent.includes('#${id}')`);}- const geometry = JSON.parse(await chrome.evaluate("JSON.stringify({ width:innerWidth, body:document.documentElement.scrollWidth, stages:[...document.querySelectorAll('.pipeline-stage')].map(node => ({left:node.getBoundingClientRect().left,right:node.getBoundingClientRect().right})) })"));+ const geometry = JSON.parse(await chrome.stable("JSON.stringify({ width:innerWidth, body:document.documentElement.scrollWidth, stages:[...document.querySelectorAll('.pipeline-stage')].map(node => ({left:node.getBoundingClientRect().left,right:node.getBoundingClientRect().right})) })"));assert.ok(geometry.body <= width, `${width}: no sideways scroll: ${JSON.stringify(geometry)}`);assert.ok(geometry.stages.every(stage => stage.left >= 0 && stage.right <= width), `${width}: the flow fits the screen`);if (process.env.PULLBOARD_PIPELINE_SHOTS) {mkdirSync(process.env.PULLBOARD_PIPELINE_SHOTS, {recursive:true});- await chrome.evaluate('scrollTo(0,0)');+ await chrome.stable('scrollTo(0,0)');const shot = await chrome.send('Page.captureScreenshot', {format:'png',captureBeyondViewport:true});writeFileSync(join(process.env.PULLBOARD_PIPELINE_SHOTS, `pipeline-${width}-${scheme}.png`), Buffer.from(shot.data,'base64'));}@@ -931,16 +936,16 @@ test('Pipeline view shows every stage, status counts, stage ages, detail links a}box.run(alpha.repo, 'merged', '2', box.git(alpha.repo, 'rev-parse', 'HEAD'));await chrome.waitFor("document.querySelector('[data-stage-count=accepted]').textContent === '0' && document.querySelector('[data-stage-count=merged]').textContent === '2'");- assert.equal(await chrome.evaluate("document.querySelector('[data-pipeline-stage=accepted] .pipeline-oldest').textContent"), 'No items', 'a recorded merge advances only the accepted item and leaves an honest empty stage');+ assert.equal(await chrome.stable("document.querySelector('[data-pipeline-stage=accepted] .pipeline-oldest').textContent"), 'No items', 'a recorded merge advances only the accepted item and leaves an honest empty stage');await press(chrome, "document.querySelector('[data-items-view=\"list\"]')");await chrome.waitFor("!location.hash && !document.querySelector('#item-list').hidden && document.querySelector('#pipeline').hidden");- assert.equal(await chrome.evaluate(listRead), listBefore, 'returning to List preserves its Active rows, metadata and ordering');+ assert.equal(await chrome.stable(listRead), listBefore, 'returning to List preserves its Active rows, metadata and ordering');assert.deepEqual(JSON.parse(listBefore).map(row => row.id).sort((a,b)=>a-b), [3,4,5,6]);await travel(chrome, -1);await settled(chrome, "location.hash === '#items/pipeline' && !document.querySelector('#pipeline').hidden");await chrome.send('Page.reload', {});await settled(chrome, "location.hash === '#items/pipeline' && data?.project && !document.querySelector('#pipeline').hidden");- assert.equal(await chrome.evaluate("document.querySelector('.tab.on').dataset.tab"), 'items', 'the Pipeline address reloads within Items');+ assert.equal(await chrome.stable("document.querySelector('.tab.on').dataset.tab"), 'items', 'the Pipeline address reloads within Items');await travel(chrome, 1);await settled(chrome, "!location.hash && !document.querySelector('#item-list').hidden");assert.deepEqual(chrome.exceptions, [], 'the pipeline has no uncaught page errors');diff --git a/test/cockpit/layout.test.js b/test/cockpit/layout.test.jsindex 000ea212..60ddd25f 100644--- a/test/cockpit/layout.test.js+++ b/test/cockpit/layout.test.js@@ -30,12 +30,12 @@ test('the view never scrolls sideways at 320px [N26]', { timeout: 120_000 }, asy// the room a 320px screen leaves beside a classic 15px scrollbar: Linux CI measured 324px of tabs there.for (const [width, font] of [[320, ''], [320, 'Verdana, "DejaVu Sans", sans-serif'], [305, 'Verdana, "DejaVu Sans", sans-serif']]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 800, deviceScaleFactor: 1, mobile: false });- await chrome.evaluate(`document.documentElement.style.setProperty('--sans', ${JSON.stringify(font || 'system-ui, sans-serif')})`);+ await chrome.stable(`document.documentElement.style.setProperty('--sans', ${JSON.stringify(font || 'system-ui, sans-serif')})`);await chrome.waitFor(`innerWidth === ${width}`);for (const tab of ['items', 'shouts', 'spec', 'doctrine', 'activity', 'roadmap']) {- await chrome.evaluate(`document.querySelector('[data-tab="${tab}"]').click()`);+ await chrome.click(`document.querySelector('[data-tab="${tab}"]')`);await chrome.waitFor(`!document.querySelector('[data-pane="${tab}"]').hidden`);- const seen = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const seen = JSON.parse(await chrome.stable(`JSON.stringify((() => {const edge = document.documentElement.clientWidth;// Name each element that runs past the edge with nothing above it to clip or scroll it.const clipped = (e) => { for (let p = e.parentElement; p && p !== document.body; p = p.parentElement) if (!['visible', ''].includes(getComputedStyle(p).overflowX)) return true; return false; };@@ -193,7 +193,7 @@ test('the status bar holds one line under no pointer [N26]', { timeout: 120_000chrome = await openSnapshotChrome(wrapper, view.link.href, profile);await chrome.waitFor("typeof data === 'object' && !!data && data.project?.items?.length === 3");await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });- const layout = JSON.parse(await chrome.evaluate(`JSON.stringify({+ const layout = JSON.parse(await chrome.stable(`JSON.stringify({pointer: { none: matchMedia('(pointer: none)').matches, fine: matchMedia('(pointer: fine)').matches, coarse: matchMedia('(pointer: coarse)').matches },parts: [...document.querySelectorAll('.status [data-status]')].filter((button) => !button.hidden && button.getBoundingClientRect().width > 0).map((button) => {const rects = [...button.childNodes].flatMap((node) => {@@ -208,7 +208,7 @@ test('the status bar holds one line under no pointer [N26]', { timeout: 120_000console.log('375 pointer none raw layout', JSON.stringify(layout));assert.deepEqual(layout.pointer, { none: true, fine: false, coarse: false }, `wrapper produces real pointer:none CSS state: ${JSON.stringify(layout.pointer)}`);assert.ok(layout.parts.some((part) => part.label === '3 items'), `the real board's Items status part is present: ${JSON.stringify(layout.parts)}`);- const audit = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const audit = JSON.parse(await chrome.stable(`JSON.stringify((() => {const visible=e=>{const s=getComputedStyle(e),r=e.getBoundingClientRect();return !e.disabled&&s.display!=='none'&&s.visibility!=='hidden'&&Number(s.opacity)!==0&&r.width>0&&r.height>0&&!e.closest('[hidden]')};const selector='button,a[href],input:not([type=hidden]),select,textarea,[role=button],[data-root],[data-tab],[data-go],[data-item],[data-state],[data-rows],[data-row],[data-release],[data-shout],[data-new],[data-code]';const controls=[...new Set(document.querySelectorAll(selector))].filter(visible).map(e=>{const r=e.getBoundingClientRect();return {text:(e.innerText||e.getAttribute('aria-label')||'').trim(),height:r.height,inlineReference:e.matches('.feed button.ref, .shout button.ref, .shout .band a, .detail button.ref')||!!e.closest('#chain .meta .gate, #detail .kv dd.waits-on'),statusBar:!!e.closest('.status')&&!matchMedia('(pointer: coarse)').matches,oneLine:!e.closest('.status')||getComputedStyle(e).whiteSpace==='nowrap'}});@@ -260,7 +260,7 @@ test('the board reads at a glance from the status bar [N26]', { timeout: 180_000const profile = mkdtempSync(join(tmpdir(), 'pullboard-glance-chrome-'));let chrome;/** The page as it reads: the header, the bar's parts, the list's rows and the toolbar, measured where they stand. */- const read = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const box = (e) => { if (!e) return null; const r = e.getBoundingClientRect(); return { left: r.left, right: r.right, top: r.top, bottom: r.bottom, width: r.width, height: r.height }; };const rgb = (css) => { const n = (css.match(/[\\d.]+/g) || []).map(Number); return css.startsWith('color(srgb') ? [n[0] * 255, n[1] * 255, n[2] * 255, n[3] ?? 1] : [n[0], n[1], n[2], n[3] ?? 1]; };const words = (e) => [...e.children].map((child) => child.textContent.replace(/\\s+/g, ' ').trim()).join(' ');@@ -295,10 +295,10 @@ test('the board reads at a glance from the status bar [N26]', { timeout: 180_000})())`));const part = (r, to) => r.bar.find((p) => p.to === to);const number = (p) => Number(/^(\d+)/.exec(p?.text ?? '')?.[1] ?? NaN);- const click = async (selector) => chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);- const settle = () => chrome.evaluate('new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)))');+ const click = async (selector) => chrome.click(`document.querySelector(${JSON.stringify(selector)})`);+ const settle = () => chrome.stable('new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)))');/** Pick a lane the way the picker does: its value, then its change event. */- const lane = async (name) => { await chrome.evaluate(`(() => { const pick = document.querySelector('#lane-pick'); pick.value = ${JSON.stringify(name)}; pick.dispatchEvent(new Event('change')); })()`); await settle(); };+ const lane = async (name) => { await chrome.stable(`(() => { const pick = document.querySelector('#lane-pick'); pick.value = ${JSON.stringify(name)}; pick.dispatchEvent(new Event('change')); })()`); await settle(); };try {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor("typeof data === 'object' && data?.project?.items?.length === 7 && !!document.querySelector('.status [data-status=\"items\"]')");@@ -308,6 +308,7 @@ test('the board reads at a glance from the status bar [N26]', { timeout: 180_000await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });await chrome.waitFor(`innerWidth === ${width} && matchMedia('(prefers-color-scheme: ${scheme})').matches`);await click('[data-tab=items]');+ await click('[data-tab=items]');await click('[data-state=active]');await settle();const at = `${width}px ${scheme}`;@@ -362,6 +363,7 @@ test('the board reads at a glance from the status bar [N26]', { timeout: 180_000await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'light' }] });await chrome.waitFor('innerWidth === 1280');+ await click('[data-tab=items]');await click('[data-state=all]');let r = await read();for (const [to, state, label] of [['verify', 'verify', 'To verify'], ['gated', 'gated', 'Gated'], ['items', 'active', 'Active']]) {@@ -374,6 +376,7 @@ test('the board reads at a glance from the status bar [N26]', { timeout: 180_000assert.deepEqual([on?.[0], Number(on?.[1]), r.rows.length], [label, n, n], `${to}: the bar's ${n} opens ${label}, which counts and lists the same ${n}: ${JSON.stringify(r.chips)}`);if (to === 'gated') assert.ok(r.rows.every((x) => x.gated), 'every row it opens is a gated row');}+ await click('[data-tab=items]');await click('[data-state=active]');await click('.status [data-status="agents"]');await chrome.waitFor("view.tab === 'shouts' && !document.querySelector('[data-pane=shouts]').hidden");@@ -390,8 +393,8 @@ test('the board reads at a glance from the status bar [N26]', { timeout: 180_000// The release part opens the Roadmap on that release alone: its rows are the ones it counts.await click('.status [data-status="release"]');await chrome.waitFor("view.tab === 'roadmap'");- const roadmapRows = () => chrome.evaluate("document.querySelectorAll('#roadmap .milestone-item').length");- assert.deepEqual([await chrome.evaluate("[...document.querySelectorAll('#roadmap .milestone h2')].map((h) => h.textContent).join()"), await roadmapRows()], ['1.0: first cut', 3],+ const roadmapRows = () => chrome.stable("document.querySelectorAll('#roadmap .milestone-item').length");+ assert.deepEqual([await chrome.stable("[...document.querySelectorAll('#roadmap .milestone h2')].map((h) => h.textContent).join()"), await roadmapRows()], ['1.0: first cut', 3],'the release the part counts, and only its three items');await click('#roadmap [data-roadmap-all]');assert.equal(await roadmapRows(), 6, 'show all brings back every release');@@ -402,16 +405,19 @@ test('the board reads at a glance from the status bar [N26]', { timeout: 180_000}// Lanes narrow the list as states do, each counting within the other's choice.+ await click('[data-tab=items]');await click('[data-state=active]');await lane('api');r = await read();assert.deepEqual([r.lane, r.rows.map((x) => x.id), r.chips.find(([name]) => name === 'Active')[1], r.chips.find(([name]) => name === 'Verified')[1]], ['api', ['4'], '1', '0'], 'api narrows the list and the state counts');await lane('');+ await click('[data-tab=items]');await click('[data-state=verified]');await lane('web');r = await read();assert.deepEqual([r.lane, r.rows.map((x) => x.id), r.lanes], ['web', ['7'], ['All lanes', 'web · 1']], 'under Verified the lanes count what is verified');await lane('');+ await click('[data-tab=items]');await click('[data-state=active]');// Shouts: asks waiting on others and idle agents each fold to one line, closed until opened.@@ -436,20 +442,20 @@ test('the board reads at a glance from the status bar [N26]', { timeout: 180_000// A shout that lands while Items is open counts as unread in the bar. The part opens exactly that shout, not the ones// already read beside it, and opening it reads it; show all brings the rest back.await click('[data-tab=items]');- const alreadyRead = await chrome.evaluate('data.project.shouts.length');+ const alreadyRead = await chrome.stable('data.project.shouts.length');assert.ok(alreadyRead >= 2, `shouts the person has already read: ${alreadyRead}`);box.run(alpha.web, 'shout', 'coordinator', 'web-1 is on it');await chrome.waitFor("!document.querySelector('#status-unread')?.hidden && document.querySelector('#status-unread')?.textContent === '1 unread'", 15_000);await click('#status-unread');await chrome.waitFor("view.tab === 'shouts' && document.querySelector('#status-unread')?.hidden === true");- const feed = async () => JSON.parse(await chrome.evaluate("JSON.stringify([...document.querySelectorAll('#feed .shout .text')].map((text) => text.textContent))"));- assert.deepEqual([await feed(), await chrome.evaluate("document.querySelector('#feed .feed-bar span').textContent")], [['web-1 is on it'], '1 unread show all'],+ const feed = async () => JSON.parse(await chrome.stable("JSON.stringify([...document.querySelectorAll('#feed .shout .text')].map((text) => text.textContent))"));+ assert.deepEqual([await feed(), await chrome.stable("document.querySelector('#feed .feed-bar span').textContent")], [['web-1 is on it'], '1 unread show all'],`1 unread opens that one shout, not the ${alreadyRead} already read`);await 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.evaluate("globalThis.fetch = () => Promise.reject(new TypeError('Failed to fetch'))");+ await chrome.stable("globalThis.fetch = () => Promise.reject(new TypeError('Failed to fetch'))");await chrome.waitFor("document.querySelector('#live').textContent.startsWith('offline')", 15_000);r = await read();const [red, green, blue] = r.barTint;@@ -479,7 +485,7 @@ test('the project corner and the theme read the same everywhere [N26]', { timeouconst profile = mkdtempSync(join(tmpdir(), 'pullboard-corner-chrome-'));let chrome;/** The corner, the project list and the theme button as they read. */- const read = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const box = (e) => { if (!e) return null; const r = e.getBoundingClientRect(); return { left: r.left, top: r.top, right: r.right, bottom: r.bottom, width: r.width, height: r.height }; };const shown = (e) => !!e && getComputedStyle(e).display !== 'none' && e.getBoundingClientRect().width > 0;const rgb = (css) => (css.match(/[\\d.]+/g) || []).map(Number);@@ -498,9 +504,9 @@ test('the project corner and the theme read the same everywhere [N26]', { timeoutheme: { scheme: document.documentElement.dataset.scheme || null, title: theme.title, box: box(theme), bar: box(bar), picked: document.documentElement.dataset.theme || null, side: box(side) },};})())`));- const click = (selector) => chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);+ const click = (selector) => chrome.click(`document.querySelector(${JSON.stringify(selector)})`);/** A drawn frame: the page hears of a colour-scheme change at its next one. */- const frame = () => chrome.evaluate('new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)))');+ const frame = () => chrome.stable('new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)))');const middle = (b) => b.top + b.height / 2;try {chrome = await openSnapshotChrome(executable, view.link.href, profile);@@ -562,7 +568,7 @@ test('the project corner and the theme read the same everywhere [N26]', { timeouawait click('#theme');assert.deepEqual(Object.values((await read()).theme).slice(0, 2), ['dark', 'Dark theme: switch to light'], 'a press switches to dark');await click('#theme');- assert.deepEqual([...Object.values((await read()).theme).slice(0, 2), await chrome.evaluate("localStorage.getItem('pb.theme')")], ['light', 'Light theme: switch to dark', 'light'], 'the next press is light again, never back to following the system');+ assert.deepEqual([...Object.values((await read()).theme).slice(0, 2), await chrome.stable("localStorage.getItem('pb.theme')")], ['light', 'Light theme: switch to dark', 'light'], 'the next press is light again, never back to following the system');await click('#theme');await chrome.send('Page.reload');await chrome.waitFor("document.readyState === 'complete' && !!document.querySelector('#theme')");@@ -591,7 +597,7 @@ test('targets are 44px for touch and compact under a mouse [N26]', { timeout: 15const profile = mkdtempSync(join(tmpdir(), 'pullboard-targets-chrome-'));let chrome;/** Every visible enabled action with its height, which references sit in running text, and the named compact ones. */- const audit = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const audit = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const visible = (e) => { const s = getComputedStyle(e), r = e.getBoundingClientRect(); return !e.disabled && s.display !== 'none' && s.visibility !== 'hidden' && r.width > 0 && r.height > 0 && !e.closest('[hidden]'); };const height = (s) => { const e = document.querySelector(s); return e && visible(e) ? Math.round(e.getBoundingClientRect().height) : null; };const selector = 'button,a[href],input:not([type=hidden]),select,textarea,[role=button],[data-tab],[data-go],[data-item],[data-state],[data-row],[data-new]';@@ -622,7 +628,7 @@ test('targets are 44px for touch and compact under a mouse [N26]', { timeout: 15composer: { text: height('#shout-text'), send: height('#shout-send') }, status: [...document.querySelectorAll('.status [data-status]')].filter(visible).map((b) => Math.round(b.getBoundingClientRect().height)),};})())`));- const tab = async (name) => { await chrome.evaluate(`document.querySelector('[data-tab=${name}]').click()`); await chrome.waitFor(`!document.querySelector('[data-pane=${name}]').hidden`); };+ const tab = async (name) => { await chrome.click(`document.querySelector('[data-tab=${name}]')`); await chrome.waitFor(`!document.querySelector('[data-pane=${name}]').hidden`); };try {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor("typeof data === 'object' && data?.project?.items?.length === 2 && data.project.shouts.length >= 2");diff --git a/test/cockpit/needs.test.js b/test/cockpit/needs.test.jsindex e13d9283..b94d7d4f 100644--- a/test/cockpit/needs.test.js+++ b/test/cockpit/needs.test.js@@ -182,7 +182,7 @@ test('needs you and the asks sit in their lists [N26]', { timeout: 180_000 }, asconst profile = mkdtempSync(join(tmpdir(), 'pullboard-asks-chrome-'));let chrome;/** Items' head and Shouts' card as they read. */- const read = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const box = (e) => { if (!e) return null; const r = e.getBoundingClientRect(); return { left: r.left, right: r.right, top: r.top, bottom: r.bottom, width: r.width, height: r.height }; };const shown = (e) => !!e && !e.closest('[hidden]') && e.getBoundingClientRect().height > 0;const probe = document.createElement('i'); probe.style.color = 'var(--warn)'; document.body.append(probe); const warn = getComputedStyle(probe).color; probe.remove();@@ -203,7 +203,7 @@ test('needs you and the asks sit in their lists [N26]', { timeout: 180_000 }, asokNote: (() => { const c = document.querySelector('#console'); return !!c && !c.hidden && getComputedStyle(c).display !== 'none' && c.classList.contains('ok'); })(),};})())`));- const click = (selector) => chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);+ const click = (selector) => chrome.click(`document.querySelector(${JSON.stringify(selector)})`);try {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor("typeof data === 'object' && data?.project?.decisions?.length === 1 && data.project.asked.length === 1 && data.project.holds.length === 1");@@ -214,6 +214,7 @@ test('needs you and the asks sit in their lists [N26]', { timeout: 180_000 }, asawait chrome.waitFor(`innerWidth === ${width} && matchMedia('(prefers-color-scheme: ${scheme})').matches`);const at = `${width}px ${scheme}`;await click('[data-tab=items]');+ await click('[data-tab=items]');await click('[data-state=active]');let r = await read();assert.ok(r.page.scroll <= r.page.width && r.page.body <= r.page.width, `${at}: no sideways scroll on Items`);@@ -260,7 +261,7 @@ test('needs you and the asks sit in their lists [N26]', { timeout: 180_000 }, asawait click('.asks-slot [data-agents-toggle]');assert.ok((await read()).panelShown, 'and brings the panel back');// A sent shout shows as its card; no note pushes into the composer's line.- await chrome.evaluate("document.querySelector('#shout-text').focus()");+ await chrome.stable("document.querySelector('#shout-text').focus()");await chrome.send('Input.insertText', { text: 'Footer after the greeting.' });await click('#shout-send');await chrome.waitFor("[...document.querySelectorAll('#feed .shout .text')].some((text) => text.textContent === 'Footer after the greeting.')", 15_000);@@ -273,18 +274,20 @@ test('needs you and the asks sit in their lists [N26]', { timeout: 180_000 }, asr = await read();assert.deepEqual([r.needs.length, r.needs.filter((need) => /^Ship part [1-6] today\?$/.test(need.words)).length, r.needs.every((need) => need.label)], [10, 6, true],`ten calls, ten rows, each with its kind in the warning colour: ${JSON.stringify(r.needs)}`);- assert.equal(await chrome.evaluate("document.querySelector('#needs').textContent.includes('more need you')"), false, 'no call is folded into a count');+ assert.equal(await chrome.stable("document.querySelector('#needs').textContent.includes('more need you')"), false, 'no call is folded into a count');// Narrowed to the unread shouts from the status bar, the feed carries its bar with show all; show all clears it.box.run(alpha.web, 'shout', 'coordinator', 'Greeting is half done.');await chrome.waitFor("!document.querySelector('#status-unread')?.hidden", 15_000);await click('#status-unread');await chrome.waitFor("view.tab === 'shouts' && !!document.querySelector('#feed .feed-bar')");- assert.match(await chrome.evaluate("document.querySelector('#feed .feed-bar').textContent"), /^\d+ unread\s*show all$/, 'narrowed to the unread shouts, the feed carries its bar with show all');+ assert.match(await chrome.stable("document.querySelector('#feed .feed-bar').textContent"), /^\d+ unread\s*show all$/, 'narrowed to the unread shouts, the feed carries its bar with show all');await click('#feed [data-unread]');assert.equal((await read()).feedBar, false, 'show all brings back every shout and clears the bar');// Under Verified, or a lane, the list is narrowed and Needs you steps aside.+ await click('[data-tab=items]');await click('[data-state=verified]');assert.equal((await read()).needsShown, false, 'under Verified, Needs you steps aside');+ await click('[data-tab=items]');await click('[data-state=active]');assert.deepEqual(chrome.exceptions, [], 'the page raises no uncaught exception');} finally {diff --git a/test/cockpit/projects.test.js b/test/cockpit/projects.test.jsindex 0af8dfbf..eccd7e59 100644--- a/test/cockpit/projects.test.js+++ b/test/cockpit/projects.test.js@@ -145,7 +145,7 @@ test('the project list collapses into the tab bar and stays collapsed [N26]', {const profile = mkdtempSync(join(tmpdir(), 'pullboard-collapse-chrome-'));let chrome;/** Read the sidebar, the tab bar and the board's columns as the person sees them. */- const read = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const box = (s) => { const e = document.querySelector(s); const r = e.getBoundingClientRect(); return { left: r.left, top: r.top, right: r.right, bottom: r.bottom, width: r.width, height: r.height, shown: getComputedStyle(e).display !== 'none' && r.width > 0 }; };const logo = document.querySelector('#side-toggle');return { width: document.documentElement.clientWidth, logo: box('#side-toggle'), side: box('.side'), top: box('.top'), main: box('main'), switcher: box('#proj-switch'), list: box('#side-body'), theme: box('#theme'), live: box('#live'),@@ -157,13 +157,13 @@ test('the project list collapses into the tab bar and stays collapsed [N26]', {await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor('innerWidth === 1280 && !!document.querySelector("#chain .row") && !!document.querySelector("#detail h2")');// A classic 15px scrollbar, as Linux draws one, so every edge is measured against the content width.- await chrome.evaluate("document.styleSheets[0].insertRule('html { overflow-y: scroll; }', 0); document.styleSheets[0].insertRule('::-webkit-scrollbar { width: 15px; }', 0)");+ await chrome.stable("document.styleSheets[0].insertRule('html { overflow-y: scroll; }', 0); document.styleSheets[0].insertRule('::-webkit-scrollbar { width: 15px; }', 0)");await chrome.waitFor('document.documentElement.clientWidth === innerWidth - 15');const open = await read();assert.ok(open.side.width >= 200 && open.side.height >= 800 && !open.collapsed && open.pressed === 'false', `the sidebar starts open: ${JSON.stringify(open)}`);assert.ok(open.theme.right >= open.width - 16 && open.theme.top < open.top.bottom && open.live.right <= open.theme.left, `the light/dark button sits at the right end of the tab bar, clear of the live status: ${JSON.stringify(open)}`);- await chrome.evaluate('document.querySelector("#side-toggle").click()');+ await chrome.click('document.querySelector("#side-toggle")');await chrome.waitFor('document.documentElement.dataset.side === "collapsed"');const collapsed = await read();assert.deepEqual([collapsed.pressed, collapsed.title], ['true', 'Show the project list'], 'the logo says it brings the list back');@@ -175,13 +175,13 @@ test('the project list collapses into the tab bar and stays collapsed [N26]', {`the board takes the whole width: the list and detail gain at least 200px: ${JSON.stringify({ open: open.columns, collapsed: collapsed.columns, main: collapsed.main })}`);assert.ok(collapsed.theme.right >= collapsed.width - 16 && collapsed.live.right <= collapsed.theme.left, 'the light/dark button stays at the right end');- await chrome.evaluate('document.querySelector("#proj-switch").click()');+ await chrome.click('document.querySelector("#proj-switch")');const dropdown = await read();assert.ok(dropdown.list.shown && dropdown.listPosition === 'absolute' && dropdown.list.top >= dropdown.top.bottom - 0.5 && dropdown.list.right <= dropdown.width, `the switcher opens the project list as a dropdown: ${JSON.stringify(dropdown.list)}`);- await chrome.evaluate('document.querySelector("main").click()');+ await chrome.click('document.querySelector("main")');assert.equal((await read()).list.shown, false, 'a click outside closes it');- await chrome.evaluate('document.querySelector("#proj-switch").click()');- await chrome.evaluate(`document.querySelector('#proj-list [data-root="${other.repo}"]').click()`);+ await chrome.click('document.querySelector("#proj-switch")');+ await chrome.click(`document.querySelector('#proj-list [data-root="${other.repo}"]')`);await chrome.waitFor(`document.querySelector('#proj-name').textContent === 'collapse-other'`);assert.equal((await read()).list.shown, false, 'a pick closes it and shows that project');@@ -189,16 +189,16 @@ test('the project list collapses into the tab bar and stays collapsed [N26]', {await chrome.waitFor('document.readyState === "complete" && !!document.querySelector("#proj-switch")');assert.equal((await read()).collapsed, 'collapsed', 'the choice is kept in this browser across a reload');- await chrome.evaluate('document.querySelector("#side-toggle").click()');+ await chrome.click('document.querySelector("#side-toggle")');await chrome.waitFor('!document.documentElement.dataset.side');const back = await read();assert.ok(back.side.width >= 200 && back.list.shown && back.pressed === 'false' && back.title === 'Collapse the project list', `the logo brings the sidebar back as it was: ${JSON.stringify(back)}`);- await chrome.evaluate('document.querySelector("#side-toggle").click()');+ await chrome.click('document.querySelector("#side-toggle")');await chrome.send('Emulation.setDeviceMetricsOverride', { width: 375, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor('innerWidth === 375');const phone = await read();- await chrome.evaluate('document.querySelector("#side-toggle").click()');+ await chrome.click('document.querySelector("#side-toggle")');const tapped = await read();assert.ok(phone.switcher.shown && !phone.list.shown && phone.theme.right >= phone.width - 16 && phone.theme.top < phone.side.bottom, `a phone keeps its switcher, the light/dark button at the right of its top row: ${JSON.stringify(phone)}`);assert.equal(tapped.collapsed, phone.collapsed, 'on a phone the logo is only the logo');@@ -448,7 +448,7 @@ test('the project switcher\'s arrow turns with the list [N26]', { timeout: 120_0const profile = mkdtempSync(join(tmpdir(), 'pullboard-arrow-chrome-'));let chrome;/** The switcher's arrow as it reads: shown, its size, which way it points, and whether it animates. */- const read = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const arrow = document.querySelector('#proj-switch small'), svg = arrow.querySelector('svg'), s = getComputedStyle(arrow), r = svg.getBoundingClientRect();return {page: { width: document.documentElement.clientWidth, scroll: document.documentElement.scrollWidth },@@ -456,9 +456,9 @@ test('the project switcher\'s arrow turns with the list [N26]', { timeout: 120_0turn: s.transform, motion: [s.transitionDuration, s.animationName], open: document.querySelector('#proj-switch').getAttribute('aria-expanded'),};})())`));- const click = (selector) => chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);+ const click = (selector) => chrome.click(`document.querySelector(${JSON.stringify(selector)})`);/** One drawn frame after a click: an arrow that animated would still be part way round. */- const frame = () => chrome.evaluate('new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)))');+ const frame = () => chrome.stable('new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)))');const DOWN = 'none', UP = 'matrix(-1, 0, 0, -1, 0, 0)';try {chrome = await openSnapshotChrome(executable, view.link.href, profile);@@ -471,7 +471,7 @@ test('the project switcher\'s arrow turns with the list [N26]', { timeout: 120_0const at = `${width}px ${scheme}`;if (width === 1280) {// Docked, the name opens no list, so there is no arrow; collapsed, the list drops from the name.- if (await chrome.evaluate("document.documentElement.dataset.side === 'collapsed'")) await click('#side-toggle');+ if (await chrome.stable("document.documentElement.dataset.side === 'collapsed'")) await click('#side-toggle');await chrome.waitFor("document.documentElement.dataset.side !== 'collapsed'");assert.equal((await read()).shown, false, `${at}: docked, with no list to drop, there is no arrow`);await click('#side-toggle');diff --git a/test/cockpit/prose.test.js b/test/cockpit/prose.test.jsindex abbaea23..617eb8d5 100644--- a/test/cockpit/prose.test.js+++ b/test/cockpit/prose.test.js@@ -151,7 +151,7 @@ test('real Chrome renders brief lists with inline paths [N26]', { timeout: 90_00for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width} && document.querySelector('#detail .text.muted ul') !== null`);- const seen = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const seen = JSON.parse(await chrome.stable(`JSON.stringify((() => {const text = document.querySelector('#detail .text.muted');const lists = [...text.querySelectorAll(':scope > ul.text-list')];const label = (list) => { let n = list.previousSibling; while (n && n.nodeType === 3 && !n.textContent.trim()) n = n.previousSibling; return n ? (n.nodeType === 3 ? n.textContent : n.textContent).trim().split('\\n').pop() : ''; };@@ -180,7 +180,7 @@ test('real Chrome renders brief lists with inline paths [N26]', { timeout: 90_00assert.ok(seen.gap > 0.4 && seen.gap < 1.6, `${width}: one blank line between a list and the next label, as written: ${seen.gap.toFixed(2)} lines`);assert.ok(!seen.overflow, `${width}: nothing runs off the screen`);}- await chrome.evaluate("document.querySelector('[data-tab=\"shouts\"]').click()");+ await chrome.click("document.querySelector('[data-tab=\"shouts\"]')");await chrome.waitFor("[...document.querySelectorAll('#feed code.block')].some((code) => code.textContent.includes('const greeting'))");} finally {if (chrome) await closeSnapshotChrome(chrome);diff --git a/test/cockpit/references.test.js b/test/cockpit/references.test.jsindex 9565ff64..13330ae5 100644--- a/test/cockpit/references.test.js+++ b/test/cockpit/references.test.js@@ -200,32 +200,35 @@ test('committed shout and fact references stay local, expand safely at phone andfor (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 1000, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width}`);- await chrome.evaluate(`document.querySelector('[data-tab="shouts"]').click()`);- await chrome.evaluate(`document.querySelector('#feed button[data-code^="web/reference.js:1-100@"]').click()`);+ await chrome.click(`document.querySelector('[data-tab="shouts"]')`);+ await chrome.click(`document.querySelector('#feed button[data-code^="web/reference.js:1-100@"]')`);await chrome.waitFor(`document.querySelector('#feed .code-wrap pre.code .tok-keyword')?.textContent === 'const'`);- assert.equal(await chrome.evaluate(`document.querySelector('#feed pre.code').textContent.includes('localOnlyFixture = 42')`), true, 'the open local preview reads the exact committed text');- assert.equal(await chrome.evaluate(`document.querySelector('#feed pre.code .tok-number')?.textContent`), '42', 'source tokens receive syntax highlighting');- assert.equal(await chrome.evaluate(`document.querySelectorAll('#feed pre.code > span').length`), 60, 'the initial preview stays bounded');- await chrome.evaluate(`document.querySelector('#feed button[data-code-all]').click()`);+ assert.equal(await chrome.stable(`document.querySelector('#feed pre.code').textContent.includes('localOnlyFixture = 42')`), true, 'the open local preview reads the exact committed text');+ assert.equal(await chrome.stable(`document.querySelector('#feed pre.code .tok-number')?.textContent`), '42', 'source tokens receive syntax highlighting');+ assert.equal(await chrome.stable(`document.querySelectorAll('#feed pre.code > span').length`), 60, 'the initial preview stays bounded');+ await chrome.click(`document.querySelector('#feed button[data-code-all]')`);await chrome.waitFor(`document.querySelectorAll('#feed pre.code > span').length === 100`);- assert.equal(await chrome.evaluate(`document.querySelector('#feed pre.code > span:last-child').textContent.includes('row99 = 99')`), true, 'show all lines fetches the end of the cited range');- await chrome.evaluate(`document.querySelector('#feed button[data-code-less]').click()`);+ assert.equal(await chrome.stable(`document.querySelector('#feed pre.code > span:last-child').textContent.includes('row99 = 99')`), true, 'show all lines fetches the end of the cited range');+ await chrome.click(`document.querySelector('#feed button[data-code-less]')`);await chrome.waitFor(`document.querySelectorAll('#feed pre.code > span').length === 60`);- assert.equal(await chrome.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${width}px page has no sideways overflow`);+ assert.equal(await chrome.stable('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${width}px page has no sideways overflow`);- assert.equal(await chrome.evaluate(`!!document.querySelector('#detail .fact-code .code-ref:not(.open) > button.ref.block[aria-expanded="false"]')`), true, 'a fact\'s reference is a collapsed block too');- await chrome.evaluate(`document.querySelector('#detail .fact-code button[data-code]').click()`);+ await chrome.click(`document.querySelector('[data-tab="items"]')`);+ await chrome.click(`document.querySelector('#chain [data-item="1"]')`);+ assert.equal(await chrome.stable(`!!document.querySelector('#detail .fact-code .code-ref:not(.open) > button.ref.block[aria-expanded="false"]')`), true, 'a fact\'s reference is a collapsed block too');+ await chrome.click(`document.querySelector('#detail .fact-code button[data-code]')`);await chrome.waitFor(`document.querySelector('#detail .fact-code pre.code .tok-keyword')?.textContent === 'const'`);- assert.equal(await chrome.evaluate(`document.querySelector('#detail .fact-code pre.code').textContent.includes('localOnlyFixture = 42')`), true, 'typed fact refs use the same local renderer');- assert.equal(await chrome.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${width}px thread ref has no sideways overflow`);- await chrome.evaluate(`document.querySelector('#detail .fact-code button[data-code]').click()`);- await chrome.evaluate(`document.querySelector('#feed button[data-code^=\"web/reference.js:1-100@\"]').click()`);+ assert.equal(await chrome.stable(`document.querySelector('#detail .fact-code pre.code').textContent.includes('localOnlyFixture = 42')`), true, 'typed fact refs use the same local renderer');+ assert.equal(await chrome.stable('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${width}px thread ref has no sideways overflow`);+ await chrome.click(`document.querySelector('#detail .fact-code button[data-code]')`);+ await chrome.click(`document.querySelector('[data-tab="shouts"]')`);+ await chrome.click(`document.querySelector('#feed button[data-code^=\"web/reference.js:1-100@\"]')`);await chrome.waitFor(`document.querySelector('#feed button[data-code^=\"web/reference.js:1-100@\"]').getAttribute('aria-expanded') === 'false'`);}- await chrome.evaluate(`document.querySelector('#feed button[data-code^="web/reference.js:1@deadbee"]').click()`);+ await chrome.click(`document.querySelector('#feed button[data-code^="web/reference.js:1@deadbee"]')`);await chrome.waitFor(`document.querySelector('#feed button[data-code^=\"web/reference.js:1@deadbee\"] + .code-ref .code, #feed button[data-code^=\"web/reference.js:1@deadbee\"] + .code')?.textContent.includes('[NO_COMMIT]')`);- assert.equal(await chrome.evaluate(`document.querySelector('#feed button[data-code^=\"web/reference.js:1@deadbee\"] + .code-ref .code, #feed button[data-code^=\"web/reference.js:1@deadbee\"] + .code').textContent.includes('deadbee')`), true, 'a missing commit produces its readable refusal');- assert.equal(await chrome.evaluate(`document.querySelector('#feed .ref-missing')?.textContent.includes('missing the repository path')`), true, 'a reference with no path gives a clear note');+ assert.equal(await chrome.stable(`document.querySelector('#feed button[data-code^=\"web/reference.js:1@deadbee\"] + .code-ref .code, #feed button[data-code^=\"web/reference.js:1@deadbee\"] + .code').textContent.includes('deadbee')`), true, 'a missing commit produces its readable refusal');+ assert.equal(await chrome.stable(`document.querySelector('#feed .ref-missing')?.textContent.includes('missing the repository path')`), true, 'a reference with no path gives a clear note');} finally {if (chrome) await closeSnapshotChrome(chrome);await view.stop();@@ -258,10 +261,10 @@ test('committed shout and fact references stay local, expand safely at phone andconst address = snapshotServer.address();snapshotChrome = await openSnapshotChrome(executable, `http://127.0.0.1:${address.port}/`, join(box.dir, 'relay-snapshot-chrome'));await snapshotChrome.waitFor(`document.querySelector('#feed button[data-code^=\"web/reference.js:1-100@\"]')`);- await snapshotChrome.evaluate(`document.querySelector('[data-tab="shouts"]').click()`);- await snapshotChrome.evaluate(`document.querySelector('#feed button[data-code^="web/reference.js:1-100@"]').click()`);+ await snapshotChrome.click(`document.querySelector('[data-tab="shouts"]')`);+ await snapshotChrome.click(`document.querySelector('#feed button[data-code^="web/reference.js:1-100@"]')`);await snapshotChrome.waitFor(`document.querySelector('#feed button[data-code^=\"web/reference.js:1-100@\"]')?.getAttribute('aria-expanded') === 'true'`);- assert.match(await snapshotChrome.evaluate(`document.querySelector('#feed button[data-code^=\"web/reference.js:1-100@\"] + .code-ref .code, #feed button[data-code^=\"web/reference.js:1-100@\"] + .code')?.textContent || ''`), /Source code is not included in this relay snapshot/);+ assert.match(await snapshotChrome.stable(`document.querySelector('#feed button[data-code^=\"web/reference.js:1-100@\"] + .code-ref .code, #feed button[data-code^=\"web/reference.js:1-100@\"] + .code')?.textContent || ''`), /Source code is not included in this relay snapshot/);assert.ok(snapshotChrome.requests.every((request) => !request.url.includes('/code?')), 'relay snapshot serves only the reference and sends no code read');} finally {if (snapshotChrome) await closeSnapshotChrome(snapshotChrome);diff --git a/test/cockpit/relay.test.js b/test/cockpit/relay.test.jsindex 33379dd1..62c4e5f8 100644--- a/test/cockpit/relay.test.js+++ b/test/cockpit/relay.test.js@@ -6,6 +6,7 @@ import { createServer, request } from 'node:http';import { tmpdir } from 'node:os';import { delimiter, join, relative, resolve, sep } from 'node:path';import { after, test } from 'node:test';+import { stableChrome } from './stable.js';import { cockpitPage } from '../../src/cockpit.js';import { relayClientFixture } from '../relay-client-fixture.js';import { findChromeExecutable, relayWorkBudgetMs, startChrome } from '../relay-browser-fixture.js';@@ -64,7 +65,7 @@ test('a paired relay reference explains that committed source is available onlyconst link = JSON.parse(readFileSync(box.linkFile, 'utf8'));const encoded = readFileSync(box.keyFile, 'utf8').trim();- const chrome = await startChrome();+ const chrome = await stableChrome(await startChrome());t.after(() => chrome.close());// Since person power stays on the paired phone, the browser reads the board with the phone's session, not the link's.assert.equal((await chrome.send('Network.setCookie', {@@ -72,24 +73,24 @@ test('a paired relay reference explains that committed source is available only})).success, true, 'the private browser receives the paired phone’s authenticated session');await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encoded);await chrome.waitFor(`document.querySelector('#chain')?.textContent.includes(${JSON.stringify(itemTitle)})`);- await chrome.evaluate(`document.querySelector('[data-tab="shouts"]').click()`);+ await chrome.click(`document.querySelector('[data-tab="shouts"]')`);await chrome.waitFor(`document.querySelector('#feed button[data-code^="${sourceRef}:1@"]')`);const beforeOpen = box.calls.length;for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width}`);const button = `document.querySelector('#feed button[data-code^="${sourceRef}:1@"]')`;- if (!await chrome.evaluate(`${button}.getAttribute('aria-expanded') === 'true'`)) await chrome.evaluate(`${button}.click()`);+ if (!await chrome.stable(`${button}.getAttribute('aria-expanded') === 'true'`)) await chrome.click(`${button}`);await chrome.waitFor(`${button}.nextElementSibling?.querySelector('.code')?.textContent.includes('local project view')`);- assert.equal(await chrome.evaluate(`document.body.textContent.includes(${JSON.stringify(sentinel)})`), false,+ assert.equal(await chrome.stable(`document.body.textContent.includes(${JSON.stringify(sentinel)})`), false,'the paired relay browser never receives committed source text');- assert.equal(await chrome.evaluate(`JSON.stringify(data).includes(${JSON.stringify(sentinel)})`), false,+ assert.equal(await chrome.stable(`JSON.stringify(data).includes(${JSON.stringify(sentinel)})`), false,'the decoded relay presentation contains only the reference, not source bytes');- assert.equal(await chrome.evaluate(`${button}.nextElementSibling.querySelector('.code').textContent`),+ assert.equal(await chrome.stable(`${button}.nextElementSibling.querySelector('.code').textContent`),'Source code is unavailable in a relay view; open this reference in the local project view.');- assert.equal(await chrome.evaluate(`document.querySelector('#feed button[data-code-all]') === null`), true,+ assert.equal(await chrome.stable(`document.querySelector('#feed button[data-code-all]') === null`), true,'a relay reference exposes no control that could request more source');- assert.equal(await chrome.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true,+ assert.equal(await chrome.stable('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true,`${width}px relay reference stays within the viewport`);}assert.equal(box.calls.slice(beforeOpen).some(call => /\/code(?:\?|$)/.test(call.path)), false,@@ -136,12 +137,12 @@ test('served connection reaches an authenticated API on another origin and pathchrome = await openSnapshotChrome(executable, `http://127.0.0.1:${pageServer.address().port}/phone/index.html`, join(box.dir, 'remote-phone-chrome'));await chrome.send('Emulation.setDeviceMetricsOverride', { width: 375, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor('typeof data === "object" && !!data?.project');- assert.equal(await chrome.evaluate('data.project.items[0].title'), 'Remote original');- await chrome.evaluate(`document.querySelector('#new-item').click(); document.querySelector('#add-title').value = 'Remote added'; document.querySelector('#add-form').requestSubmit()`);+ assert.equal(await chrome.stable('data.project.items[0].title'), 'Remote original');+ await chrome.click(`document.querySelector('#new-item')`); await chrome.stable(`document.querySelector('#add-title').value = 'Remote added'`); await chrome.stable(`document.querySelector('#add-form').requestSubmit()`);await chrome.waitFor('data.project.items.some(item => item.title === "Remote added")');assert.ok(seen.some((entry) => entry.method === 'POST' && entry.path.endsWith('/moves')), 'a real browser action reaches the configured API');assert.ok(seen.every((entry) => entry.authorization === `Bearer ${credential}` && entry.localKey === undefined && entry.path.startsWith('/mirror/api/v1/')), 'only the supplied credential and API base reach the stand-in');- assert.ok(await chrome.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'),+ assert.ok(await chrome.stable('document.documentElement.scrollWidth <= document.documentElement.clientWidth'),'the remote phone page fits the viewport content area');assert.deepEqual(chrome.exceptions, []);} finally {@@ -259,55 +260,55 @@ test('relay person requests stay explicit, read-only and visible [H12,H5]', { tichrome = await openSnapshotChrome(executable, `http://127.0.0.1:${pageServer.address().port}/`, profile);await chrome.waitFor("typeof data === 'object' && !!data?.project && typeof window.__setPersonRequest === 'function'");await chrome.send('Emulation.setDeviceMetricsOverride', { width: 375, height: 900, deviceScaleFactor: 1, mobile: false });- assert.equal(await chrome.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, 'the request view fits a phone viewport');- assert.equal(await chrome.evaluate("document.body.classList.contains('requests') && getComputedStyle(document.querySelector('#new-item')).display !== 'none' && document.querySelector('#new-item').getBoundingClientRect().height >= 44"), true, 'the explicit capability exposes usable person controls');- await chrome.evaluate("document.querySelector('[data-tab=\"shouts\"]').click(); document.querySelector('#shout-to').value = 'coordinator'; document.querySelector('#shout-text').value = 'Please review this item.'; document.querySelector('#shout-form').requestSubmit()");+ assert.equal(await chrome.stable('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, 'the request view fits a phone viewport');+ assert.equal(await chrome.stable("document.body.classList.contains('requests') && getComputedStyle(document.querySelector('#new-item')).display !== 'none' && document.querySelector('#new-item').getBoundingClientRect().height >= 44"), true, 'the explicit capability exposes usable person controls');+ await chrome.click("document.querySelector('[data-tab=\"shouts\"]')"); await chrome.stable("document.querySelector('#shout-to').value = 'coordinator'"); await chrome.stable("document.querySelector('#shout-text').value = 'Please review this item.'"); await chrome.stable("document.querySelector('#shout-form').requestSubmit()");await chrome.waitFor("data?.project?.personRequests?.length === 1");assert.deepEqual(intents.at(-1), { verb: 'shout', args: { to: 'coordinator', text: 'Please review this item.' } });- await chrome.evaluate("document.querySelector('[data-tab=\"spec\"]').click()");+ await chrome.click("document.querySelector('[data-tab=\"spec\"]')");await chrome.waitFor("document.querySelector('#spec-list [data-row=\"spec:G2\"]')");- await chrome.evaluate("document.querySelector('#spec-list [data-row=\"spec:G2\"]').scrollIntoView({ block: 'center' })");+ await chrome.stable("document.querySelector('#spec-list [data-row=\"spec:G2\"]').scrollIntoView({ block: 'center' })");await chrome.waitFor('window.scrollY > 0');- await chrome.evaluate("document.querySelector('#spec-list [data-row=\"spec:G2\"]').click()");+ await chrome.click("document.querySelector('#spec-list [data-row=\"spec:G2\"]')");await chrome.waitFor("view.row.spec === 'G2'");- const reading = JSON.parse(await chrome.evaluate(`JSON.stringify({ root: view.root, boardRoot: data.project.root, row: view.row.spec, scroll: window.scrollY })`));+ const reading = JSON.parse(await chrome.stable(`JSON.stringify({ root: view.root, boardRoot: data.project.root, row: view.row.spec, scroll: window.scrollY })`));assert.equal(reading.root, reading.boardRoot, 'the selected spec row belongs to the displayed board');assert.equal(reading.row, 'G2', 'G2 is the selected reading row before approval');await chrome.waitFor("document.querySelector('#spec-detail button[data-row-decision=\"approve\"]')");- assert.equal(await chrome.evaluate("document.querySelector('#spec-detail button[data-row-decision=\"approve\"]').getBoundingClientRect().height >= 44"), true, 'the real G2 approval control is usable at 375px');- await chrome.evaluate('window.__holdNextIntent = true');- await chrome.evaluate("document.querySelector('#spec-detail button[data-row-decision=\"approve\"]').click()");+ assert.equal(await chrome.stable("document.querySelector('#spec-detail button[data-row-decision=\"approve\"]').getBoundingClientRect().height >= 44"), true, 'the real G2 approval control is usable at 375px');+ await chrome.stable('window.__holdNextIntent = true');+ await chrome.click("document.querySelector('#spec-detail button[data-row-decision=\"approve\"]')");await chrome.waitFor("typeof window.__releaseHeldIntent === 'function' || document.querySelector('#spec-detail .spec-feedback.no')");- assert.equal(await chrome.evaluate("typeof window.__releaseHeldIntent"), 'function', 'the row decision reaches the sealed request transport instead of the refused generic API');+ assert.equal(await chrome.stable("typeof window.__releaseHeldIntent"), 'function', 'the row decision reaches the sealed request transport instead of the refused generic API');await chrome.waitFor("document.querySelector('#spec-detail .spec-feedback')?.textContent.trim() === 'Recording decision…'");- await chrome.evaluate('window.__releaseHeldIntent()');+ await chrome.stable('window.__releaseHeldIntent()');await chrome.waitFor("document.querySelector('#spec-detail .spec-feedback') && document.querySelector('#spec-detail .spec-feedback').textContent.trim() !== 'Recording decision…'");assert.deepEqual(intents.at(-1), { verb: 'spec-approve', args: { ids: 'G2' } }, 'the detail click creates the exact second literal intent');await chrome.waitFor("data?.project?.personRequests?.length === 2 && document.querySelector('[data-person-request=\"request-2\"] .request-status')?.textContent === 'Waiting'");- assert.match(await chrome.evaluate("document.querySelector('#spec-detail .spec-feedback')?.textContent.trim() || ''"), /G2/);- const afterApproval = JSON.parse(await chrome.evaluate(`JSON.stringify({ root: view.root, row: view.row.spec, scroll: window.scrollY, selected: document.querySelector('#spec-list [data-row=\"spec:G2\"]')?.classList.contains('on'), visible: (() => { const row = document.querySelector('#spec-list [data-row=\"spec:G2\"]')?.getBoundingClientRect(); return !!row && row.top >= 0 && row.bottom <= innerHeight; })() })`));+ assert.match(await chrome.stable("document.querySelector('#spec-detail .spec-feedback')?.textContent.trim() || ''"), /G2/);+ const afterApproval = JSON.parse(await chrome.stable(`JSON.stringify({ root: view.root, row: view.row.spec, scroll: window.scrollY, selected: document.querySelector('#spec-list [data-row=\"spec:G2\"]')?.classList.contains('on'), visible: (() => { const row = document.querySelector('#spec-list [data-row=\"spec:G2\"]')?.getBoundingClientRect(); return !!row && row.top >= 0 && row.bottom <= innerHeight; })() })`));assert.deepEqual([afterApproval.root, afterApproval.row, afterApproval.selected], [reading.root, 'G2', true], 'the request keeps the selected board and G2 row');assert.ok(Math.abs(afterApproval.scroll - reading.scroll) <= 1, 'the request keeps the page at the same reading position');assert.equal(afterApproval.visible, true, 'G2 remains visible beside its inline feedback');assert.deepEqual(intents.at(-1), { verb: 'spec-approve', args: { ids: 'G2' } });- assert.equal(await chrome.evaluate("data.project.spec.find(row => row.id === 'G2').decision === undefined"), true, 'waiting for a request never approves the row optimistically');- await chrome.evaluate("window.__setPersonRequest('request-2', 'done')");- assert.match(await chrome.evaluate("document.querySelector('#spec-detail .spec-feedback')?.textContent || ''"), /^Done/, 'the same row feedback follows a matched done receipt');- await chrome.evaluate("window.__setPersonRequest('request-2', 'refused', { code: 'REQUEST_DECLINED', message: 'Keep the row draft.', next: 'Ask the coordinator for the next step.' })");- assert.match(await chrome.evaluate("document.querySelector('#spec-detail .spec-feedback.no')?.textContent || ''"), /Refused[\s\S]*REQUEST_DECLINED[\s\S]*Keep the row draft\.[\s\S]*Ask the coordinator/, 'the same row retains the original refusal and next step');- await chrome.evaluate("window.__setPersonRequest('request-2', 'waiting')");+ assert.equal(await chrome.stable("data.project.spec.find(row => row.id === 'G2').decision === undefined"), true, 'waiting for a request never approves the row optimistically');+ await chrome.stable("window.__setPersonRequest('request-2', 'done')");+ assert.match(await chrome.stable("document.querySelector('#spec-detail .spec-feedback')?.textContent || ''"), /^Done/, 'the same row feedback follows a matched done receipt');+ await chrome.stable("window.__setPersonRequest('request-2', 'refused', { code: 'REQUEST_DECLINED', message: 'Keep the row draft.', next: 'Ask the coordinator for the next step.' })");+ assert.match(await chrome.stable("document.querySelector('#spec-detail .spec-feedback.no')?.textContent || ''"), /Refused[\s\S]*REQUEST_DECLINED[\s\S]*Keep the row draft\.[\s\S]*Ask the coordinator/, 'the same row retains the original refusal and next step');+ await chrome.stable("window.__setPersonRequest('request-2', 'waiting')");- const ids = JSON.parse(await chrome.evaluate('JSON.stringify(data.project.personRequests.map(row => row.id))'));+ const ids = JSON.parse(await chrome.stable('JSON.stringify(data.project.personRequests.map(row => row.id))'));assert.deepEqual(ids, ['request-1', 'request-2']);- assert.ok(await chrome.evaluate("[...document.querySelectorAll('[data-person-request]')].length === 2 && [...document.querySelectorAll('[data-person-request]')].every(node => node.querySelector('.request-status').textContent === 'Waiting')"), 'waiting receipts render from API state');+ assert.ok(await chrome.stable("[...document.querySelectorAll('[data-person-request]')].length === 2 && [...document.querySelectorAll('[data-person-request]')].every(node => node.querySelector('.request-status').textContent === 'Waiting')"), 'waiting receipts render from API state');// A generic write and an unknown action are refused before they reach the stand-in transport.const beforeRefused = intents.length;- const beforeTransport = await chrome.evaluate('window.__transportCalls.length');- assert.match(await chrome.evaluate(`(async () => { try { await api(boardPath(view.root) + '/moves', { verb: 'shout', args: { to: 'coordinator', text: 'direct writes stay refused' } }); return 'unexpected'; } catch (error) { return error.message; } })()`), /read-only view/i);- assert.equal(await chrome.evaluate(`(async () => act('exec', { command: 'true' }))()`), false);+ const beforeTransport = await chrome.stable('window.__transportCalls.length');+ assert.match(await chrome.stable(`(async () => { try { await api(boardPath(view.root) + '/moves', { verb: 'shout', args: { to: 'coordinator', text: 'direct writes stay refused' } }); return 'unexpected'; } catch (error) { return error.message; } })()`), /read-only view/i);+ assert.equal(await chrome.stable(`(async () => act('exec', { command: 'true' }))()`), false);assert.equal(intents.length, beforeRefused, 'refused shapes never reach the request server');- assert.equal(await chrome.evaluate('window.__transportCalls.length'), beforeTransport, 'refused writes never reach the browser transport');+ assert.equal(await chrome.stable('window.__transportCalls.length'), beforeTransport, 'refused writes never reach the browser transport');const longTitle = 'Requested item ' + 'abcdefghij'.repeat(24);const otherActions = [@@ -318,7 +319,7 @@ test('relay person requests stay explicit, read-only and visible [H12,H5]', { ti['spec-decline', { ids: 'G2', reason: 'Keep the present behavior' }, { verb: 'spec-decline', args: { ids: 'G2', reason: 'Keep the present behavior' } }],];for (const [action, args, expected] of otherActions) {- assert.equal(await chrome.evaluate(`act(${JSON.stringify(action)}, ${JSON.stringify(args)})`), true, `${action} is a permitted person request`);+ assert.equal(await chrome.stable(`act(${JSON.stringify(action)}, ${JSON.stringify(args)})`), true, `${action} is a permitted person request`);assert.deepEqual(intents.at(-1), expected, `${action} retains literal public CLI intent`);}const allActions = [['shout', { to: 'coordinator', text: 'must not send' }], ['spec-approve', { ids: 'G2' }], ...otherActions.map(([action, args]) => [action, args])];@@ -327,36 +328,36 @@ test('relay person requests stay explicit, read-only and visible [H12,H5]', { tiawait chrome.send('Page.navigate', { url: `http://127.0.0.1:${pageServer.address().port}/without-capability` });await chrome.waitFor("typeof data === 'object' && !!data?.project && document.body?.classList.contains('read-only')");const beforeDisabled = intents.length;- await chrome.evaluate("document.querySelector('[data-tab=\"spec\"]').click(); document.querySelector('#spec-list [data-row=\"spec:G2\"]').click()");+ await chrome.click("document.querySelector('[data-tab=\"spec\"]')"); await chrome.click("document.querySelector('#spec-list [data-row=\"spec:G2\"]')");await chrome.waitFor("view.row.spec === 'G2'");- assert.equal(await chrome.evaluate(`(async () => decideRow('spec', 'spec-approve', { ids: 'G2' }, document.querySelector('#spec-list [data-row=\"spec:G2\"]')))()`), false, 'the decision handler itself refuses without request capability');- assert.equal(await chrome.evaluate('!view.specFeedback'), true, 'a disabled decision refuses before creating decision feedback');+ assert.equal(await chrome.stable(`(async () => decideRow('spec', 'spec-approve', { ids: 'G2' }, document.querySelector('#spec-list [data-row=\"spec:G2\"]')))()`), false, 'the decision handler itself refuses without request capability');+ assert.equal(await chrome.stable('!view.specFeedback'), true, 'a disabled decision refuses before creating decision feedback');assert.equal(intents.length, beforeDisabled, 'a direct no-capability decision never reaches the request transport');- for (const [action, args] of allActions) assert.equal(await chrome.evaluate(`act(${JSON.stringify(action)}, ${JSON.stringify(args)})`), false, `${action} stays refused without the capability`);+ for (const [action, args] of allActions) assert.equal(await chrome.stable(`act(${JSON.stringify(action)}, ${JSON.stringify(args)})`), false, `${action} stays refused without the capability`);assert.equal(intents.length, beforeDisabled, 'read-only without the explicit request capability refuses every action');await chrome.send('Page.navigate', { url: `http://127.0.0.1:${pageServer.address().port}/snapshot` });await chrome.waitFor("typeof data === 'object' && !!data?.project && document.body?.classList.contains('snapshot')");- assert.equal(await chrome.evaluate(`(async () => decideRow('spec', 'spec-approve', { ids: 'G2' }, null))()`), false, 'the decision handler itself refuses in a snapshot');- for (const [action, args] of allActions) assert.equal(await chrome.evaluate(`act(${JSON.stringify(action)}, ${JSON.stringify(args)})`), false, `${action} stays refused in a snapshot`);- assert.match(await chrome.evaluate(`(async () => { try { await api('/api/v1/boards/demo/moves', { verb: 'shout' }); return 'unexpected'; } catch (error) { return error.message; } })()`), /read-only snapshot/i);+ assert.equal(await chrome.stable(`(async () => decideRow('spec', 'spec-approve', { ids: 'G2' }, null))()`), false, 'the decision handler itself refuses in a snapshot');+ for (const [action, args] of allActions) assert.equal(await chrome.stable(`act(${JSON.stringify(action)}, ${JSON.stringify(args)})`), false, `${action} stays refused in a snapshot`);+ assert.match(await chrome.stable(`(async () => { try { await api('/api/v1/boards/demo/moves', { verb: 'shout' }); return 'unexpected'; } catch (error) { return error.message; } })()`), /read-only snapshot/i);assert.equal(intents.length, beforeDisabled, 'snapshot mode cannot use the explicit request capability');// A later actual API read may update status; refusal text is safe text and preserves CLI guidance.await chrome.send('Page.navigate', { url: `http://127.0.0.1:${pageServer.address().port}/` });await chrome.waitFor("typeof window.__setPersonRequest === 'function' && !!data?.project");- await chrome.evaluate(`window.__setPersonRequest('request-1', 'done')`);+ await chrome.stable(`window.__setPersonRequest('request-1', 'done')`);await chrome.waitFor("document.querySelector('[data-person-request=\"request-1\"]')?.querySelector('.request-status')?.textContent === 'Done'");const refusal = '<img src=x onerror=globalThis.requestInjection=true> UNKNOWN_SPEC; run pullboard spec check';- await chrome.evaluate(`window.__setPersonRequest('request-2', 'refused', { code: 'UNKNOWN_SPEC', message: ${JSON.stringify(refusal)}, next: 'run pullboard spec check' })`);+ await chrome.stable(`window.__setPersonRequest('request-2', 'refused', { code: 'UNKNOWN_SPEC', message: ${JSON.stringify(refusal)}, next: 'run pullboard spec check' })`);await chrome.waitFor("document.querySelector('[data-person-request=\"request-2\"]')?.textContent.includes('UNKNOWN_SPEC')");- assert.equal(await chrome.evaluate("document.querySelector('[data-person-request=\"request-2\"] img') === null"), true, 'refusal guidance is escaped, not interpreted as markup');- assert.equal(await chrome.evaluate("document.querySelector('[data-person-request=\"request-2\"] .request-error')?.textContent"), 'UNKNOWN_SPEC ' + refusal, 'the original CLI refusal message stays intact');- assert.equal(await chrome.evaluate('globalThis.requestInjection === undefined'), true, 'refusal content cannot execute in the page');- assert.equal(await chrome.evaluate("document.querySelector('[data-person-request=\"request-2\"]')?.textContent.includes('run pullboard spec check')"), true);+ assert.equal(await chrome.stable("document.querySelector('[data-person-request=\"request-2\"] img') === null"), true, 'refusal guidance is escaped, not interpreted as markup');+ assert.equal(await chrome.stable("document.querySelector('[data-person-request=\"request-2\"] .request-error')?.textContent"), 'UNKNOWN_SPEC ' + refusal, 'the original CLI refusal message stays intact');+ assert.equal(await chrome.stable('globalThis.requestInjection === undefined'), true, 'refusal content cannot execute in the page');+ assert.equal(await chrome.stable("document.querySelector('[data-person-request=\"request-2\"]')?.textContent.includes('run pullboard spec check')"), true);for (const width of [375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });- assert.equal(await chrome.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${width}px refusal view has no horizontal overflow`);- const layout = JSON.parse(await chrome.evaluate(`JSON.stringify({+ assert.equal(await chrome.stable('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${width}px refusal view has no horizontal overflow`);+ const layout = JSON.parse(await chrome.stable(`JSON.stringify({statuses: [...document.querySelectorAll('.request-status')].map(node => node.textContent),listFits: document.querySelector('.request-list').scrollWidth <= document.querySelector('.request-list').clientWidth,readable: [...document.querySelectorAll('.request-label, .request-status, .request-error, .request-next')].every(node => {@@ -373,7 +374,7 @@ test('relay person requests stay explicit, read-only and visible [H12,H5]', { ti{ verb: 'spec-approve', args: { ids: 'G2' } },...otherActions.map(([, , expected]) => expected),]);- const privatePath = await chrome.evaluate('boardPath(view.root)');+ const privatePath = await chrome.stable('boardPath(view.root)');const privateState = await (await fetchLive(live.base + privatePath + '/state', { headers: { 'x-pullboard-key': live.key } })).json();assert.equal(privateState.state.items.length, 1, 'the stand-in request transport never executes an item move on the real board');assert.equal(privateState.state.holds.length, 0, 'the request transport never changes a real lane hold');@@ -465,7 +466,7 @@ test('read-only Needs-you preserves each entry as text while its transport stayschrome = await openSnapshotChrome(executable, live.link.href, profile);await chrome.waitFor("typeof data === 'object' && !!data?.project && document.querySelector('#needs .row')?.textContent.includes('Should the read-only fixture ship?')");/** Read Needs-you labels with absolute API age timestamps so the comparison survives minute ticks. */- const readNeedEntries = () => chrome.evaluate(`JSON.stringify([...document.querySelectorAll('#needs .row')].map((row) => {+ const readNeedEntries = () => chrome.stable(`JSON.stringify([...document.querySelectorAll('#needs .row')].map((row) => {const time = row.querySelector('.row-age time'), ref = row.querySelector('.t > span');return [ref?.textContent, row.querySelector('.t').textContent.slice((ref?.textContent ?? '').length),row.querySelector('.meta .why').textContent + (time ? ' @' + time.dataset.ago : '')];@@ -479,28 +480,28 @@ test('read-only Needs-you preserves each entry as text while its transport staysawait chrome.waitFor("document.querySelector('#needs .row')?.textContent.includes('Should the read-only fixture ship?')");const readOnlyEntries = JSON.parse(await readNeedEntries());assert.deepEqual(readOnlyEntries, normalEntries, 'read-only Needs-you preserves the normal entries and their API-provided asker and ages');- assert.equal(await chrome.evaluate("document.querySelectorAll('#needs button, #needs [data-go], #needs [data-new], #needs [data-shout], #needs [data-release]').length"), 0,+ assert.equal(await chrome.stable("document.querySelectorAll('#needs button, #needs [data-go], #needs [data-new], #needs [data-shout], #needs [data-release]').length"), 0,'read-only Needs-you entries contain no answer, approve, navigation, or other action controls');- const calls = JSON.parse(await chrome.evaluate('JSON.stringify(window.__transportCalls)'));+ const calls = JSON.parse(await chrome.stable('JSON.stringify(window.__transportCalls)'));assert.ok(calls.some((call) => call.path === '/api/v1/boards'));assert.ok(calls.some((call) => call.path.startsWith('/api/v1/boards/') && call.path.endsWith('/state')));- assert.equal(await chrome.evaluate("document.querySelector('#live').textContent"), '', 'read-only transport keeps the page live, which says nothing');+ assert.equal(await chrome.stable("document.querySelector('#live').textContent"), '', 'read-only transport keeps the page live, which says nothing');const actionSelectors = ['#new-item', '#add-form', '#shout-form', '#hold-form', '[data-release]', '[data-shout]', '[data-new]', '[data-go^="decide:"]'];- const actionMatches = JSON.parse(await chrome.evaluate(`JSON.stringify(${JSON.stringify(actionSelectors)}.map((selector) => ({ selector, count: document.querySelectorAll(selector).length, visible: [...document.querySelectorAll(selector)].some((node) => !node.hidden && getComputedStyle(node).display !== 'none') })))`));+ const actionMatches = JSON.parse(await chrome.stable(`JSON.stringify(${JSON.stringify(actionSelectors)}.map((selector) => ({ selector, count: document.querySelectorAll(selector).length, visible: [...document.querySelectorAll(selector)].some((node) => !node.hidden && getComputedStyle(node).display !== 'none') })))`));assert.ok(actionMatches.every((entry) => entry.count > 0), 'the seeded item, decision and hold exercise every action selector');assert.deepEqual(actionMatches.filter((entry) => entry.visible).map((entry) => entry.selector), [], 'read-only mode hides every match for every action control');- const refusedAction = JSON.parse(await chrome.evaluate(`(async () => JSON.stringify({ result: await act('shout', { to: 'all', text: 'blocked' }), message: document.querySelector('#console').textContent }))()`));+ const refusedAction = JSON.parse(await chrome.stable(`(async () => JSON.stringify({ result: await act('shout', { to: 'all', text: 'blocked' }), message: document.querySelector('#console').textContent }))()`));assert.equal(refusedAction.result, false);assert.match(refusedAction.message, /read-only/i);- const refusedApi = await chrome.evaluate(`(async () => { try { await api('/api/v1/boards/demo/moves', { verb: 'shout' }); return 'unexpected success'; } catch (error) { return error.message; } })()`);+ const refusedApi = await chrome.stable(`(async () => { try { await api('/api/v1/boards/demo/moves', { verb: 'shout' }); return 'unexpected success'; } catch (error) { return error.message; } })()`);assert.match(refusedApi, /read-only/i, 'direct API mutation calls are refused before transport');assert.ok(forwarded.every((method) => method === 'GET'), 'read-only action attempts send no write through the transport');- await chrome.evaluate(`window.__samePage = true; Object.defineProperty(document, 'hidden', { configurable: true, get: () => true })`);+ await chrome.stable(`window.__samePage = true; Object.defineProperty(document, 'hidden', { configurable: true, get: () => true })`);box.run(app.repo, 'add', 'web', 'Transport refresh item', '--specs', 'G1', '--criterion', 'appears after a transport update');- await chrome.evaluate('window.__transportUpdate()');- assert.equal(await chrome.evaluate("data?.project?.items.some((item) => item.title === 'Transport refresh item') && window.__samePage === true"), true, 'onUpdate refreshes state in the same page without relying on the poll');+ await chrome.stable('window.__transportUpdate()');+ assert.equal(await chrome.stable("data?.project?.items.some((item) => item.title === 'Transport refresh item') && window.__samePage === true"), true, 'onUpdate refreshes state in the same page without relying on the poll');assert.ok(forwarded.every((method) => method === 'GET'), 'transport update refreshed through reads only');} finally {@@ -590,10 +591,10 @@ test('a configured transport never falls back while loading or after import failconst origin = `http://127.0.0.1:${server.address().port}`;chrome = await openSnapshotChrome(executable, `${origin}/slow`, profile);await requested;- const loadingCall = await chrome.evaluate("api('/api/v1/boards').then(() => 'unexpected success', error => error.message)");+ const loadingCall = await chrome.stable("api('/api/v1/boards').then(() => 'unexpected success', error => error.message)");assert.match(loadingCall, /transport.*loading/i, 'direct API calls refuse while the configured module is loading');await browserPause(3200);- assert.equal(await chrome.evaluate('window.__transportReady === true'), false, 'the delayed module is still loading during the proof');+ assert.equal(await chrome.stable('window.__transportReady === true'), false, 'the delayed module is still loading during the proof');assert.deepEqual(localRequests, [], 'neither direct reads nor the poll fall back while loading');releaseSlowModule();@@ -604,7 +605,7 @@ test('a configured transport never falls back while loading or after import failawait chrome.send('Page.navigate', { url: `${origin}/failed` });await chrome.waitFor("document.querySelector('#live').textContent.includes('fixture transport import failed')");await browserPause(3200);- assert.match(await chrome.evaluate("document.querySelector('#live').textContent"), /cannot reach the view: fixture transport import failed/,+ assert.match(await chrome.stable("document.querySelector('#live').textContent"), /cannot reach the view: fixture transport import failed/,'the original module error remains visible after later poll intervals');assert.deepEqual(localRequests, [], 'a failed import also disables page-local polling');} finally {diff --git a/test/cockpit/roadmap.test.js b/test/cockpit/roadmap.test.jsindex 64a08343..b2e0308f 100644--- a/test/cockpit/roadmap.test.js+++ b/test/cockpit/roadmap.test.js@@ -4,7 +4,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';-import { tapTarget, SPEC, machine, project, build, sendBack, fetchLive, startView, target, accept, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, press, travel, pressedInto, settled, roadmapRow, showing, readRoadmap, tabBar, proofShot } from './fixture.js';+import { tapTarget, SPEC, machine, project, build, sendBack, fetchLive, startView, target, accept, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, press, travel, pressedInto, settled, roadmapRow, showing, readRoadmap, tabBar, proofShot, pickProject } from './fixture.js';test('Roadmap and rule prose references stay inline and open the item on their own board [N26,N38]', { timeout: 90_000 }, async (t) => {@@ -39,11 +39,11 @@ test('Roadmap and rule prose references stay inline and open the item on their o['doctrine', '#doctrine-list [data-row="doctrine:R1"] .ref', 'Local target'],];for (const [tab, selector, target] of contexts) {- await chrome.evaluate(`document.querySelector('[data-root=${JSON.stringify(demo.repo)}]').click();`);+ await pickProject(chrome, `document.querySelector('[data-root=${JSON.stringify(demo.repo)}]')`);await chrome.waitFor("data?.project?.root === view.root && !document.body.classList.contains('switching') && document.querySelector('#proj-name').textContent === 'a-inline-prose'");- await chrome.evaluate(`document.querySelector('[data-tab="${tab}"]').click()`);- if (tab !== 'roadmap') await chrome.evaluate(`document.querySelector('[data-rows="${tab}:all"]').click()`);- const metrics = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ await chrome.click(`document.querySelector('[data-tab="${tab}"]')`);+ if (tab !== 'roadmap') await chrome.click(`document.querySelector('[data-rows="${tab}:all"]')`);+ const metrics = JSON.parse(await chrome.stable(`JSON.stringify((() => {const ref = document.querySelector(${JSON.stringify(selector)});const row = ref?.closest('.milestone-item');const style = ref && getComputedStyle(ref);@@ -57,21 +57,22 @@ test('Roadmap and rule prose references stay inline and open the item on their oassert.ok(Math.abs(metrics.height - metrics.line) < 1, `${width}: ${selector} keeps the text line height`);assert.equal(metrics.nested, false, `${width}: ${selector} never nests buttons`);if (metrics.rowHeight !== undefined) assert.ok(metrics.rowHeight >= tapTarget(width), `${width}: the containing Roadmap control keeps its target`);- await chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);+ await chrome.click(`document.querySelector(${JSON.stringify(selector)})`);await chrome.waitFor("!document.body.classList.contains('switching') && document.querySelector('[data-tab=items].on') && document.querySelector('#detail h2 > span')?.textContent === '#1'");- assert.ok((await chrome.evaluate("document.querySelector('#detail h2').textContent")).includes(target), 'the reference opens its target title');- assert.equal(await chrome.evaluate('view.root'), target === 'Remote target' ? other.repo : demo.repo, 'duplicate item numbers stay bound to their own board');+ assert.ok((await chrome.stable("document.querySelector('#detail h2').textContent")).includes(target), 'the reference opens its target title');+ assert.equal(await chrome.stable('view.root'), target === 'Remote target' ? other.repo : demo.repo, 'duplicate item numbers stay bound to their own board');}- await chrome.evaluate(`document.querySelector('[data-tab="items"]').click(); document.querySelector('#chain .row[data-item="2"]').click()`);+ await chrome.click(`document.querySelector('[data-tab="items"]')`); await chrome.click(`document.querySelector('#chain .row[data-item="2"]')`);await chrome.waitFor("document.querySelector('#detail .verdict .note')");- assert.equal(await chrome.evaluate("document.querySelectorAll('#detail .verdict .note .ref').length"), 1, 'verdict prose keeps its item reference');- await chrome.evaluate("document.querySelector('#detail .verdict .note .ref').click()");+ assert.equal(await chrome.stable("document.querySelectorAll('#detail .verdict .note .ref').length"), 1, 'verdict prose keeps its item reference');+ await chrome.click("document.querySelector('#detail .verdict .note .ref')");await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Local target')");- await chrome.evaluate("document.querySelector('#needs .row[data-go^=\"decide:\"]').click()");- assert.equal(await chrome.evaluate("document.querySelectorAll('#answering-q .ref').length"), 1, 'the answering question keeps its inline item reference');- await chrome.evaluate("document.querySelector('#answering-q .ref').click()");+ await chrome.click("document.querySelector('[data-state=active]')");+ await chrome.click("document.querySelector('#needs .row[data-go^=\"decide:\"]')");+ assert.equal(await chrome.stable("document.querySelectorAll('#answering-q .ref').length"), 1, 'the answering question keeps its inline item reference');+ await chrome.click("document.querySelector('#answering-q .ref')");await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Local target') && document.querySelector('[data-tab=items].on')");- await chrome.evaluate("document.querySelector('[data-tab=roadmap]').click(); document.querySelector('#roadmap .milestone-item[role=button]:not([data-board])').dispatchEvent(new KeyboardEvent('keydown', {key:'Enter',bubbles:true}))");+ await chrome.click("document.querySelector('[data-tab=roadmap]')"); await chrome.stable("document.querySelector('#roadmap .milestone-item[role=button]:not([data-board])').dispatchEvent(new KeyboardEvent('keydown', {key:'Enter',bubbles:true}))");await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Local title links to #1') && document.querySelector('[data-tab=items].on')");}} finally {@@ -174,7 +175,7 @@ test('the roadmap reads every item as the Items tab does, opens each one, anothe// An item opens on the Items tab; Back shows the Roadmap at its address again, Forward the item.await press(chrome, roadmapRow('#3'));await pressedInto(chrome, `${showing('items', '/')} && document.querySelector('#detail h2')?.innerText.includes('Session timeout banner')`);- assert.equal(await chrome.evaluate('location.search'), view.link.search, `${width}: the address keeps the rest of itself`);+ assert.equal(await chrome.stable('location.search'), view.link.search, `${width}: the address keeps the rest of itself`);await travel(chrome, -1);await settled(chrome, `${showing('roadmap', '/roadmap')} && document.querySelector('.tab.on')?.dataset.tab === 'roadmap'`);await travel(chrome, 1);@@ -186,7 +187,7 @@ test('the roadmap reads every item as the Items tab does, opens each one, anothe// Another repo's item opens on its own board, and Back and Forward move between the two boards.await press(chrome, roadmapRow('beacon#1'));await chrome.waitFor(`document.querySelector('#proj-name').textContent === 'beacon' && ${showing('items', '/')} && document.querySelector('#detail h2')?.innerText.includes('Billing webhook retries')`);- const there = JSON.parse(await chrome.evaluate(`JSON.stringify((() => { const chip = document.querySelector('#detail .meta .chip'); return {+ const there = JSON.parse(await chrome.stable(`JSON.stringify((() => { const chip = document.querySelector('#detail .meta .chip'); return {id: document.querySelector('#detail h2 span').innerText, label: chip.innerText, chip: getComputedStyle(chip).color + ' on ' + getComputedStyle(chip).backgroundColor,dot: getComputedStyle(document.querySelector('#chain [data-item="1"] .dot')).backgroundColor }; })())`));const crossed = seen.cards[0].rows.find((row) => row.id === 'beacon#1');@@ -203,7 +204,7 @@ test('the roadmap reads every item as the Items tab does, opens each one, anothefor (const row of seen.cards.flatMap((card) => card.rows).filter((each) => each.id.startsWith('#'))) {await press(chrome, roadmapRow(row.id));await chrome.waitFor(`${showing('items', '/')} && document.querySelector('#detail h2 span')?.innerText === ${JSON.stringify(row.id)}`);- const here = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const here = JSON.parse(await chrome.stable(`JSON.stringify((() => {const chip = document.querySelector('#detail .meta .chip'), dot = document.querySelector('#chain [data-item="${row.id.slice(1)}"] .dot');return { label: chip.innerText, chip: getComputedStyle(chip).color + ' on ' + getComputedStyle(chip).backgroundColor, dot: dot ? getComputedStyle(dot).backgroundColor : 'not listed' };})())`));diff --git a/test/cockpit/search.test.js b/test/cockpit/search.test.jsindex 51cc9d3c..fe36f966 100644--- a/test/cockpit/search.test.js+++ b/test/cockpit/search.test.js@@ -4,7 +4,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';-import { SPEC, machine, project, startView, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, searchFor } from './fixture.js';+import { SPEC, machine, project, startView, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, searchFor, press } from './fixture.js';test('search in the top bar finds anything on the board [N26]', { timeout: 150_000 }, async (t) => {@@ -23,7 +23,7 @@ test('search in the top bar finds anything on the board [N26]', { timeout: 150_0const profile = mkdtempSync(join(tmpdir(), 'pullboard-finder-chrome-'));let chrome;/** The top bar's search and its results as they read. */- const read = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const box = (e) => { if (!e) return null; const r = e.getBoundingClientRect(); return { left: r.left, right: r.right, top: r.top, bottom: r.bottom, width: r.width, height: r.height }; };const results = document.querySelector('#find-results');return {@@ -42,8 +42,7 @@ test('search in the top bar finds anything on the board [N26]', { timeout: 150_0for (const type of ['keyDown', 'keyUp']) await chrome.send('Input.dispatchKeyEvent', { type, key: name, code, windowsVirtualKeyCode: keyCode, ...(type === 'keyDown' && text ? { text, unmodifiedText: text } : {}) });};const tap = async (selector) => {- const point = JSON.parse(await chrome.evaluate(`(() => { const r = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return JSON.stringify({ x: r.x + r.width / 2, y: r.y + r.height / 2 }); })()`));- for (const type of ['mousePressed', 'mouseReleased']) await chrome.send('Input.dispatchMouseEvent', { type, ...point, button: 'left', clickCount: 1 });+ await press(chrome, `document.querySelector(${JSON.stringify(selector)})`);};const search = (words) => searchFor(chrome, words);try {@@ -54,7 +53,7 @@ test('search in the top bar finds anything on the board [N26]', { timeout: 150_0await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });await chrome.waitFor(`innerWidth === ${width} && matchMedia('(prefers-color-scheme: ${scheme})').matches`);- await chrome.evaluate("document.querySelector('[data-tab=items]').click()");+ await chrome.click("document.querySelector('[data-tab=items]')");const at = `${width}px ${scheme}`;// The Items toolbar is one row: Active, Verified and All, the lane picker, New item at its end; on a phone Active// and Verified with New item, All and the lane picker dropped.@@ -88,11 +87,11 @@ test('search in the top bar finds anything on the board [N26]', { timeout: 150_0await search('greeting');await key('Escape', 'Escape', 27);await search('greeting');- await chrome.evaluate('new Promise((done) => setTimeout(done, 250))');- const kept = JSON.parse(await chrome.evaluate("JSON.stringify([document.querySelector('#q').value, document.activeElement.id, document.querySelector('#find-results').hidden])"));+ await chrome.stable('new Promise((done) => setTimeout(done, 250))');+ const kept = JSON.parse(await chrome.stable("JSON.stringify([document.querySelector('#q').value, document.activeElement.id, document.querySelector('#find-results').hidden])"));assert.deepEqual(kept, ['greeting', 'q', false], `a search straight after Esc keeps its results (words, focus, results hidden): ${JSON.stringify(kept)}`);await key('Escape', 'Escape', 27);- assert.equal(await chrome.evaluate("document.querySelector('#find-results').dataset.why"), 'escape', 'Esc closes the results and says so');+ assert.equal(await chrome.stable("document.querySelector('#find-results').dataset.why"), 'escape', 'Esc closes the results and says so');// The arrows move the highlight and Enter opens it: here the third item, the third newest.await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });@@ -121,7 +120,7 @@ test('search in the top bar finds anything on the board [N26]', { timeout: 150_0const opened = (await read()).bar;assert.deepEqual(opened.map((part) => [part.name, part.on]), [['active', false], ['verified', false], ['all', true], ['new-item', false]], `375px ${scheme}: a search that opens an item shows All, selected: ${JSON.stringify(opened)}`);assert.ok(opened.every((part) => Math.abs(part.middle - opened[0].middle) <= 2), `375px ${scheme}: still one row: ${JSON.stringify(opened)}`);- await chrome.evaluate("document.querySelector('[data-state=active]').click()");+ await chrome.click("document.querySelector('[data-state=active]')");assert.deepEqual((await read()).bar.map((part) => part.name), ['active', 'verified', 'new-item'], `375px ${scheme}: back on Active, All drops again`);}await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });@@ -156,25 +155,25 @@ test('search in the top bar finds anything on the board [N26]', { timeout: 150_0await chrome.waitFor(`view.tab === 'shouts' && document.getElementById('shout-${shout.slice(6)}')?.classList.contains('found')`);// "/" goes to the search from the page, never from a field.- await chrome.evaluate("document.activeElement.blur(); document.body.focus()");+ await chrome.stable("document.activeElement.blur(); document.body.focus()");await key('/', 'Slash', 191, '/');r = await read();- const selected = await chrome.evaluate("(() => { const q = document.querySelector('#q'); return q.selectionStart === 0 && q.selectionEnd === q.value.length; })()");+ const selected = await chrome.stable("(() => { const q = document.querySelector('#q'); return q.selectionStart === 0 && q.selectionEnd === q.value.length; })()");assert.deepEqual([r.focused, selected], ['q', true], '"/" puts the cursor in the search, its last words selected to type over');- await chrome.evaluate("document.querySelector('#shout-text').focus()");+ await chrome.stable("document.querySelector('#shout-text').focus()");await key('/', 'Slash', 191, '/');- assert.equal(await chrome.evaluate("document.querySelector('#shout-text').value"), '/', 'and in a field it is only a slash');+ assert.equal(await chrome.stable("document.querySelector('#shout-text').value"), '/', 'and in a field it is only a slash');// On a phone the lane picker shows while a lane narrows the list, so the person sees where they are and can leave// it; with every lane shown it drops again. A coordinator item makes a second lane to pick between.box.run(alpha.repo, 'add', 'coordinator', 'Plan the greeting release', '--criterion', 'planned');await chrome.waitFor('data.project.items.length === 9', 15_000);- const lane = (name) => chrome.evaluate(`(() => { const pick = document.querySelector('#lane-pick'); pick.value = ${JSON.stringify(name)}; pick.dispatchEvent(new Event('change', { bubbles: true })); })()`);+ const lane = (name) => chrome.stable(`(() => { const pick = document.querySelector('#lane-pick'); pick.value = ${JSON.stringify(name)}; pick.dispatchEvent(new Event('change', { bubbles: true })); })()`);for (const scheme of ['light', 'dark']) {await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });await chrome.waitFor(`innerWidth === 1280 && matchMedia('(prefers-color-scheme: ${scheme})').matches`);- await chrome.evaluate("document.querySelector('[data-tab=items]').click(); document.querySelector('[data-state=active]').click()");+ await chrome.click("document.querySelector('[data-tab=items]')"); await chrome.click("document.querySelector('[data-state=active]')");await lane('web');await chrome.waitFor("view.lane === 'web'");assert.ok((await read()).bar.some((part) => part.name === 'lane-pick'), `1280px ${scheme}: the lane picker is in the toolbar`);@@ -191,18 +190,18 @@ test('search in the top bar finds anything on the board [N26]', { timeout: 150_0const both = await read();assert.deepEqual(both.bar.map((part) => [part.name, part.on]), [['active', false], ['verified', false], ['all', true], ['lane-pick', false], ['new-item', false]], `375px ${scheme}: All and the picked lane both show: ${JSON.stringify(both.bar)}`);assert.ok(both.bar.every((part) => Math.abs(part.middle - both.bar[0].middle) <= 2) && both.page.scroll <= both.page.width && both.page.body <= both.page.width, `375px ${scheme}: both filters on one row, no sideways scroll: ${JSON.stringify(both)}`);- assert.deepEqual(JSON.parse(await chrome.evaluate("JSON.stringify((() => { const go = document.querySelector('#new-item'); return [go.textContent, getComputedStyle(go, '::before').content, Math.round(go.getBoundingClientRect().width)]; })())")), ['New item', '"+"', 44], `375px ${scheme}: New item is a 44px + that keeps its name`);+ assert.deepEqual(JSON.parse(await chrome.stable("JSON.stringify((() => { const go = document.querySelector('#new-item'); return [go.textContent, getComputedStyle(go, '::before').content, Math.round(go.getBoundingClientRect().width)]; })())")), ['New item', '"+"', 44], `375px ${scheme}: New item is a 44px + that keeps its name`);// A long lane name gives way rather than the row: with the coordinator lane picked, still one row.await lane('coordinator');await chrome.waitFor("view.lane === 'coordinator'");const long = await read();assert.deepEqual(long.bar.map((part) => part.name), ['active', 'verified', 'all', 'lane-pick', 'new-item'], `375px ${scheme}: a long lane keeps every control: ${JSON.stringify(long.bar)}`);assert.ok(long.bar.every((part) => Math.abs(part.middle - long.bar[0].middle) <= 2) && long.page.scroll <= long.page.width && long.page.body <= long.page.width, `375px ${scheme}: a long lane name gives way, not the row: ${JSON.stringify(long)}`);- await chrome.evaluate("document.querySelector('[data-state=active]').click()");+ await chrome.click("document.querySelector('[data-state=active]')");await lane('');await chrome.waitFor('view.lane === null');assert.deepEqual((await read()).bar.map((part) => part.name), ['active', 'verified', 'new-item'], `375px ${scheme}: every lane shown, the picker drops again`);- assert.equal(await chrome.evaluate("getComputedStyle(document.querySelector('#new-item'), '::before').content"), 'none', `375px ${scheme}: with only Active and Verified, New item has its words`);+ assert.equal(await chrome.stable("getComputedStyle(document.querySelector('#new-item'), '::before').content"), 'none', `375px ${scheme}: with only Active and Verified, New item has its words`);}await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'light' }] });@@ -230,18 +229,18 @@ test('the search step names its state on timeout [N26]', { timeout: 60_000 }, aschrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor("typeof data === 'object' && data?.project?.items?.length === 1");// A field that takes no typing: the step times out, and its message says how far the search got.- await chrome.evaluate("document.querySelector('#q').disabled = true");+ await chrome.stable("document.querySelector('#q').disabled = true");let stalled;await assert.rejects(searchFor(chrome, 'greeting', 1_500), (error) => { stalled = error; return true; });assert.match(stalled.message, /^the search for "greeting" did not show its results: \{/, 'the step says which search stalled');assert.deepEqual(Object.keys(record(stalled)), ['value', 'focused', 'windowFocus', 'resultsHidden', 'closedBy'], 'it records the value, the focus, the window focus, and the results with what closed them');assert.deepEqual([record(stalled).value, record(stalled).focused, typeof record(stalled).windowFocus, record(stalled).resultsHidden], ['', 'body', 'boolean', true], `no words reached the field, which never had focus: ${stalled.message}`);// Results that showed and were then closed say what closed them: here, leaving the field.- await chrome.evaluate("document.querySelector('#q').disabled = false");+ await chrome.stable("document.querySelector('#q').disabled = false");await searchFor(chrome, 'greeting');- await chrome.evaluate("document.querySelector('#q').blur()");+ await chrome.stable("document.querySelector('#q').blur()");await chrome.waitFor("document.querySelector('#find-results').hidden");- assert.equal(await chrome.evaluate("document.querySelector('#find-results').dataset.why"), 'left the field', 'leaving the field closes the results and says so');+ assert.equal(await chrome.stable("document.querySelector('#find-results').dataset.why"), 'left the field', 'leaving the field closes the results and says so');assert.deepEqual(chrome.exceptions, [], 'the page raises no uncaught exception');} finally {if (chrome) await closeSnapshotChrome(chrome);diff --git a/test/cockpit/shared-wait.test.js b/test/cockpit/shared-wait.test.jsnew file mode 100644index 00000000..e3a1d059--- /dev/null+++ b/test/cockpit/shared-wait.test.js@@ -0,0 +1,161 @@+import assert from 'node:assert/strict';+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, join, relative } from 'node:path';+import { fileURLToPath } from 'node:url';+import { test } from 'node:test';+import { machine, project, startView, chromeExecutable, openSnapshotChrome, closeSnapshotChrome } from './fixture.js';+import { press, waitForStableBoxes } from './stable.js';++const ROOT = fileURLToPath(new URL('../..', import.meta.url));+const COCKPIT = join(ROOT, 'test', 'cockpit');+const EXEMPT_FUNCTIONS = new Set(['rawChromeEvaluation', 'waitForStableBoxes', 'press']);++/** Find complete top-level exception bodies without exempting the rest of stable.js. */+function maskSharedChromeFunctions(source) {+ const lines = source.split('\n');+ for (let start = 0; start < lines.length; start += 1) {+ const declaration = /^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\b/.exec(lines[start]);+ if (!declaration || !EXEMPT_FUNCTIONS.has(declaration[1])) continue;+ let end = start + 1;+ while (end < lines.length && lines[end] !== '}') end += 1;+ if (end === lines.length) continue;+ for (let line = start; line <= end; line += 1) lines[line] = '';+ start = end;+ }+ return lines.join('\n');+}++/** Return every forbidden raw Chrome call with a cockpit-relative path and source line. */+function rawChromeBypasses(root = COCKPIT) {+ const patterns = [+ ['direct evaluate', new RegExp('(?<!Runtime)\\.\\s*' + 'evaluate' + '\\b')],+ ['computed evaluate', new RegExp('\\[\\s*[\'"]' + 'evaluate' + '[\'"]\\s*\\]')],+ ['unwaited DOM click', new RegExp('\\.\\s*' + 'click' + '\\s*\\(\\s*\\)')],+ ['raw protocol', new RegExp('[\'"](?:Runtime\\.(?:evaluate|callFunctionOn)|DOM\\.(?:getBoxModel|getContentQuads)|Page\\.getLayoutMetrics|Input\\.dispatch(?:Mouse|Touch)Event)[\'"]')],+ ];+ const files = [];+ /** Include future nested Chrome test files in the boundary check. */+ function walk(directory) {+ for (const entry of readdirSync(directory, { withFileTypes: true })) {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) walk(path);+ else if (entry.isFile() && /\.(?:js|mjs)$/u.test(entry.name)) files.push(path);+ }+ }+ walk(root);+ const violations = [];+ for (const path of files) {+ let source = readFileSync(path, 'utf8');+ if (basename(path) === 'stable.js' && relative(root, path) === 'stable.js') {+ source = maskSharedChromeFunctions(source);+ }+ const lines = source.split('\n');+ for (let index = 0; index < lines.length; index += 1) {+ for (const [kind, pattern] of patterns) {+ if (pattern.test(lines[index])) violations.push({ file: relative(root, path), line: index + 1, kind });+ }+ }+ }+ return violations;+}++test('real Chrome tests measure and click only through the shared wait [N26,C7]', () => {+ assert.deepEqual(rawChromeBypasses(), [], 'every cockpit test uses the stable API; raw CDP plumbing stays in the three named helpers');+});++test('the shared-wait guard reports a synthetic direct Chrome evaluation by file and line [N26,C7]', () => {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-shared-wait-guard-'));+ try {+ mkdirSync(join(root, 'nested'));+ const directCall = ['chrome', '.', 'evaluate', '(', JSON.stringify(["document.querySelector('.card')", ".", "click", "()"].join("")), ')'].join('');+ const alias = ['chrome', '[', JSON.stringify('evaluate'), ']'].join('');+ writeFileSync(join(root, 'nested', 'direct.test.js'), `const ready = true;\n${directCall};\nconst saved = ${alias};\n`);+ assert.deepEqual(rawChromeBypasses(root), [{ file: 'nested/direct.test.js', line: 2, kind: 'direct evaluate' }, { file: 'nested/direct.test.js', line: 2, kind: 'unwaited DOM click' }, { file: 'nested/direct.test.js', line: 3, kind: 'computed evaluate' }]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+});++test('raw protocol exceptions are limited to named stable helpers [N26,C7]', () => {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-shared-wait-scope-'));+ try {+ writeFileSync(join(root, 'stable.js'), [+ 'export async function rawChromeEvaluation(chrome) {',+ ' return chrome.send(' + JSON.stringify(['Runtime', 'evaluate'].join('.')) + ', {});',+ '}',+ 'export async function waitForStableBoxes(chrome) {',+ ' return chrome.send(' + JSON.stringify(['DOM', 'getBoxModel'].join('.')) + ', {});',+ '}',+ 'export async function press(chrome) {',+ ' return chrome.send(' + JSON.stringify(['Input', 'dispatchMouseEvent'].join('.')) + ', {});',+ '}',+ 'export async function accidentalBypass(chrome) {',+ ` return ${['chrome', '.', 'evaluate', '(', "'outside helper'", ')'].join('')};`,+ '}',+ ].join('\n') + '\n');+ assert.deepEqual(rawChromeBypasses(root), [{ file: 'stable.js', line: 11, kind: 'direct evaluate' }]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+});++test('the guard catches each low-level protocol bypass outside shared helpers [N26,C7]', () => {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-shared-wait-protocol-'));+ try {+ const forbiddenCalls = [+ ['Runtime', 'evaluate'], ['Runtime', 'callFunctionOn'], ['DOM', 'getBoxModel'],+ ['DOM', 'getContentQuads'], ['Page', 'getLayoutMetrics'], ['Input', 'dispatchMouseEvent'], ['Input', 'dispatchTouchEvent'],+ ].map(parts => `chrome.send(${JSON.stringify(parts.join('.'))}, {});`);+ writeFileSync(join(root, 'protocol.test.js'), forbiddenCalls.join('\n') + '\n');+ assert.deepEqual(rawChromeBypasses(root).map(({ file, line }) => [file, line]), forbiddenCalls.map((_, index) => ['protocol.test.js', index + 1]));+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+});+++test('real Chrome retains reduced motion and jumps both detail panes without animation [N26]', { timeout: 120_000 }, async (t) => {+ const executable = chromeExecutable();+ if (!executable) return t.skip('Install Chrome or set PULLBOARD_CHROME for motion checks.');+ const box = machine(), demo = project(box, 'motion-demo');+ box.run(demo.repo, 'add', 'web', 'Jump to this detail', '--specs', 'G1', '--criterion', 'visible');+ const view = await startView(box);+ let chrome;+ try {+ chrome = await openSnapshotChrome(executable, view.link.href, join(box.dir, 'motion-chrome'));+ await chrome.waitFor("typeof data === 'object' && !!data?.project");+ await chrome.send('Emulation.setDeviceMetricsOverride', { width: 375, height: 900, deviceScaleFactor: 1, mobile: false });+ for (const scheme of ['light', 'dark']) {+ await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });+ assert.equal(await chrome.stable("matchMedia('(prefers-reduced-motion: reduce)').matches"), true, `${scheme}: a later media override keeps reduced motion`);+ assert.equal(await chrome.stable(`matchMedia('(prefers-color-scheme: ${scheme})').matches`), true);+ }+ await chrome.stable(`(() => {+ const probe = document.createElement('div'); probe.id = 'motion-proof';+ probe.style.cssText = 'position:fixed;width:10px;height:10px;transition:width 2s;animation:proof-motion 2s infinite;scroll-behavior:smooth';+ document.body.append(probe);+ window.__detailScrolls = [];+ const original = Element.prototype.scrollIntoView;+ /** Record the actual navigation scroll while retaining Chrome behavior. */+ Element.prototype.scrollIntoView = function(options) { window.__detailScrolls.push({id:this.id,behavior:options?.behavior}); return original.call(this, options); };+ })()`);+ assert.deepEqual(await chrome.stable(`(() => {const style=getComputedStyle(document.querySelector('#motion-proof'));return [style.transitionDuration,style.animationName,style.scrollBehavior];})()`), ['0s', 'none', 'auto'], 'reduced motion disables transitions, animations and CSS smooth scrolling');+ await press(chrome, "document.querySelector('#chain .row')");+ await chrome.waitFor("document.querySelector('#detail h2')?.textContent.includes('Jump to this detail')");+ await press(chrome, "document.querySelector('[data-tab=spec]')");+ await press(chrome, `document.querySelector('#spec-chips [data-rows="spec:all"]')`);+ await press(chrome, `document.querySelector('#spec-list [data-row="spec:G2"]')`);+ const scrolls = await chrome.stable('window.__detailScrolls');+ for (const id of ['detail', 'spec-detail']) assert.ok(scrolls.some(entry => entry.id === id && entry.behavior === 'instant'), `${id} jumps immediately: ${JSON.stringify(scrolls)}`);+ await chrome.stable(`(() => {+ const probe=document.createElement('div'); probe.id='zero-box-proof'; probe.style.cssText='position:fixed;width:0;height:0'; document.body.append(probe);+ let frame=0; const grow=()=>{frame++;probe.dataset.frames=String(frame);if(frame===20){probe.style.width='10px';probe.style.height='10px';}else requestAnimationFrame(grow);};requestAnimationFrame(grow);+ })()`);+ await waitForStableBoxes(chrome, "document.querySelector('#zero-box-proof')");+ assert.equal(Number(await chrome.stable("document.querySelector('#zero-box-proof').dataset.frames")), 20, 'the shared wait does not accept an existing zero-size target');+ } finally {+ if (chrome) await closeSnapshotChrome(chrome);+ await view.stop();+ }+});diff --git a/test/cockpit/shouts.test.js b/test/cockpit/shouts.test.jsindex e153f0e1..ae20cd0b 100644--- a/test/cockpit/shouts.test.js+++ b/test/cockpit/shouts.test.js@@ -6,6 +6,7 @@ import { join } from 'node:path';import { after, test } from 'node:test';import { register, shout as shoutOnBoard } from '../../src/board.js';import { tapTarget, SPEC, machine, project, build, startView, styleOf, element, storage, openPage, boardId, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, earlier, shoutsAt, press, pressedInto } from './fixture.js';+import { assertFirstStateDelay, press as sharedPress } from './stable.js';test('the shouts tab counts shouts you have not seen [N26]', async () => {@@ -127,12 +128,12 @@ test('a short code chip at a line end stays whole, and long code stays one chiptry {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor('!!document.querySelector(\'[data-tab="shouts"]\')');- await chrome.evaluate('document.querySelector(\'[data-tab="shouts"]\').click()');+ await chrome.click('document.querySelector(\'[data-tab="shouts"]\')');await chrome.waitFor(`[...document.querySelectorAll('#feed code.inline')].some((code) => code.textContent === ${JSON.stringify(wide)})`);for (const width of [320, 375, 1280]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor(`innerWidth === ${width}`);- const seen = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const seen = JSON.parse(await chrome.stable(`JSON.stringify((() => {const chips = [...document.querySelectorAll('#feed code.inline')];const flag = chips.find((code) => code.textContent === '--flag'), path = chips.find((code) => code.textContent === ${JSON.stringify(long)});const text = flag.parentElement.closest('div');@@ -200,18 +201,19 @@ test('real Chrome styles shout code and item text without growing linked lines [});await chrome.send('Log.enable');await chrome.waitFor('typeof data !== "undefined" && data?.project?.shouts?.length >= 4 && document.querySelectorAll("#feed > .shout").length >= 4');+ await assertFirstStateDelay(chrome, t);await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor('innerWidth === 1280 && document.querySelector("#detail .text.muted code.inline")?.getBoundingClientRect().width > 0');- const desktopBrief = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const desktopBrief = JSON.parse(await chrome.stable(`JSON.stringify((() => {const code=document.querySelector('#detail .text.muted code.inline'), line=code?.parentElement;const rect=code?.getBoundingClientRect(), lineRect=line?.getBoundingClientRect();return {display:code&&getComputedStyle(code).display,width:rect?.width,lineWidth:lineRect?.width};})())`));assert.equal(desktopBrief.display, 'inline', `1280px brief code computes inline: ${JSON.stringify(desktopBrief)}`);assert.ok(desktopBrief.width > 0 && desktopBrief.width < desktopBrief.lineWidth / 2, `1280px brief code is a compact chip: ${JSON.stringify(desktopBrief)}`);- await chrome.evaluate("document.querySelector('#new-item').click()");+ await chrome.click("document.querySelector('#new-item')");await chrome.waitFor("!document.querySelector('#add-form').hidden && getComputedStyle(document.querySelector('#add-form')).display === 'grid'");- const desktopForm = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const desktopForm = JSON.parse(await chrome.stable(`JSON.stringify((() => {const form=document.querySelector('#add-form'), box=form.getBoundingClientRect();const fields=[...form.querySelectorAll('label')].map(field=>{const r=field.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom,width:r.width,height:r.height};});return {display:getComputedStyle(form).display,box:{left:box.left,right:box.right,top:box.top,bottom:box.bottom,width:box.width,height:box.height},fields,actions:getComputedStyle(form.querySelector('.actions')).display};@@ -220,11 +222,11 @@ test('real Chrome styles shout code and item text without growing linked lines [assert.equal(desktopForm.actions, 'flex', `1280px add-item actions keep their row: ${JSON.stringify(desktopForm)}`);assert.equal(desktopForm.fields.length, 5, '1280px add-item form keeps all five fields');assert.ok(desktopForm.fields.every((field, index, fields) => field.width > 0 && field.left >= desktopForm.box.left && field.right <= desktopForm.box.right && field.top >= desktopForm.box.top && field.bottom <= desktopForm.box.bottom && (index === 0 || field.top >= fields[index - 1].bottom)), `1280px add-item fields remain a non-overlapping grid: ${JSON.stringify(desktopForm)}`);- await chrome.evaluate("document.querySelector('#add-cancel').click()");+ await chrome.click("document.querySelector('#add-cancel')");await chrome.waitFor("document.querySelector('#add-form').hidden");- await chrome.evaluate(`document.querySelector('[data-tab="shouts"]').click()`);+ await chrome.click(`document.querySelector('[data-tab="shouts"]')`);- const rendered = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const rendered = JSON.parse(await chrome.stable(`JSON.stringify((() => {const shout = [...document.querySelectorAll('#feed > .shout')].find((row) => row.textContent.includes('Inline'));const shoutCode=[...(shout?.querySelectorAll('code.inline')||[])].find(code=>code.textContent==='--flag'), shoutLine=shout?.querySelector('.text');const shoutRect=shoutCode?.getBoundingClientRect(), shoutLineRect=shoutLine?.getBoundingClientRect();@@ -274,10 +276,10 @@ test('real Chrome styles shout code and item text without growing linked lines [assert.match(rendered.outsideHtml, /<script>alert\(2\)<\/script> outside code/, 'script text outside code is escaped too');assert.equal(rendered.previewLinks, 1, 'only a path:lines@SHA reference with the original whole-word boundaries becomes an actionable preview');assert.match(rendered.shoutHtml, /Invalid prefix:<code class="inline long" title="SPEC\.md:1-2@[0-9a-f]+">SPEC\.md:1-2@/, 'a path:lines@SHA suffix after a colon stays plain inline code');- await chrome.evaluate(`document.querySelector('#feed button[data-code^="SPEC.md:1-2@"]').click()`);+ await chrome.click(`document.querySelector('#feed button[data-code^="SPEC.md:1-2@"]')`);await chrome.waitFor(`document.querySelector('#feed button[data-code^="SPEC.md:1-2@"]').getAttribute('aria-expanded') === 'true'`);await chrome.waitFor(`document.querySelector('#feed button[data-code^="SPEC.md:1-2@"] + .code-ref .code-wrap > .code')?.textContent.includes('Demo spec')`);- assert.match(await chrome.evaluate(`document.querySelector('#feed button[data-code^="SPEC.md:1-2@"] + .code-ref .code-wrap > .code')?.textContent || ''`), /Demo spec/, 'the original code preview still opens its referenced lines');+ assert.match(await chrome.stable(`document.querySelector('#feed button[data-code^="SPEC.md:1-2@"] + .code-ref .code-wrap > .code')?.textContent || ''`), /Demo spec/, 'the original code preview still opens its referenced lines');assert.match(rendered.askHtml, /<code class="inline cmd(?: long" title="pullboard shout --decision)?">pullboard shout --decision<\/code>/, 'needs-you uses the same code renderer');assert.equal(rendered.askNestedButtons, 0, 'formatted text in an ask cannot nest interactive controls');assert.equal(rendered.needsNestedButtons, 0, 'needs-you keeps its button markup valid');@@ -294,18 +296,18 @@ test('real Chrome styles shout code and item text without growing linked lines [assert.ok(Math.abs(rendered.linkedMetrics.height - rendered.linkedMetrics.lineHeight) < 1, 'the linked desktop box equals one computed line-height');await chrome.send('Emulation.setDeviceMetricsOverride', { width: 375, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor('innerWidth === 375 && document.querySelector("#feed > .shout")?.getBoundingClientRect().width > 0');- await chrome.evaluate("document.querySelector('[data-tab=items]').click()");+ await chrome.click("document.querySelector('[data-tab=items]')");await chrome.waitFor('document.querySelector("[data-pane=items]:not([hidden])") && document.querySelector("#detail .text.muted code.inline")?.getBoundingClientRect().width > 0');- const phoneBrief = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const phoneBrief = JSON.parse(await chrome.stable(`JSON.stringify((() => {const code=document.querySelector('#detail .text.muted code.inline'), line=code?.parentElement;const rect=code?.getBoundingClientRect(), lineRect=line?.getBoundingClientRect();return {display:code&&getComputedStyle(code).display,width:rect?.width,lineWidth:lineRect?.width};})())`));assert.equal(phoneBrief.display, 'inline', `375px brief code computes inline: ${JSON.stringify(phoneBrief)}`);assert.ok(phoneBrief.width > 0 && phoneBrief.width < phoneBrief.lineWidth / 2, `375px brief code is a compact chip: ${JSON.stringify(phoneBrief)}`);- await chrome.evaluate("document.querySelector('#new-item').click()");+ await chrome.click("document.querySelector('#new-item')");await chrome.waitFor("!document.querySelector('#add-form').hidden && getComputedStyle(document.querySelector('#add-form')).display === 'grid'");- const phoneForm = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const phoneForm = JSON.parse(await chrome.stable(`JSON.stringify((() => {const form=document.querySelector('#add-form'), box=form.getBoundingClientRect();const fields=[...form.querySelectorAll('label')].map(field=>{const r=field.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom,width:r.width,height:r.height};});return {display:getComputedStyle(form).display,box:{left:box.left,right:box.right,top:box.top,bottom:box.bottom,width:box.width,height:box.height},fields,actions:getComputedStyle(form.querySelector('.actions')).display};@@ -314,11 +316,11 @@ test('real Chrome styles shout code and item text without growing linked lines [assert.equal(phoneForm.actions, 'flex', `375px add-item actions keep their row: ${JSON.stringify(phoneForm)}`);assert.equal(phoneForm.fields.length, 5, '375px add-item form keeps all five fields');assert.ok(phoneForm.fields.every((field, index, fields) => field.width > 0 && field.left >= phoneForm.box.left && field.right <= phoneForm.box.right && field.top >= phoneForm.box.top && field.bottom <= phoneForm.box.bottom && (index === 0 || field.top >= fields[index - 1].bottom)), `375px add-item fields remain a non-overlapping grid: ${JSON.stringify(phoneForm)}`);- await chrome.evaluate("document.querySelector('#add-cancel').click()");+ await chrome.click("document.querySelector('#add-cancel')");await chrome.waitFor("document.querySelector('#add-form').hidden");- await chrome.evaluate("document.querySelector('[data-tab=shouts]').click()");+ await chrome.click("document.querySelector('[data-tab=shouts]')");await chrome.waitFor('document.querySelector("[data-pane=shouts]:not([hidden])") && document.querySelector("#feed code.inline")?.getBoundingClientRect().width > 0');- const phoneMetrics = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const phoneMetrics = JSON.parse(await chrome.stable(`JSON.stringify((() => {/** Measure the complete rendered content line box, including its item link. */const lineMetrics = (message) => {const row = [...document.querySelectorAll('#feed > .shout')].find((entry) => {@@ -410,15 +412,15 @@ test('shouts read as cards [N26]', { timeout: 120_000 }, async (t) => {try {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor('typeof data !== "undefined" && data?.project?.shouts?.length >= 12');- await chrome.evaluate("document.querySelector('[data-tab=shouts]').click()");+ await chrome.click("document.querySelector('[data-tab=shouts]')");await chrome.waitFor('document.querySelector("[data-pane=shouts]:not([hidden]) #feed .shout")');- await chrome.evaluate("(() => { const fold = document.querySelector('.asks-toggle[data-fold=\"waiting\"]'); if (fold && fold.getAttribute('aria-expanded') !== 'true') fold.click(); })()");- const ids = JSON.parse(await chrome.evaluate('JSON.stringify(Object.fromEntries(data.project.shouts.map((s) => [s.shout_text, s.shout_id])))'));- const answerId = await chrome.evaluate(`data.project.shouts.find((s) => s.shout_answers === ${asked.shout_id}).shout_id`);- const stamps = JSON.parse(await chrome.evaluate('JSON.stringify(data.project.shouts.map((s) => [s.shout_id, s.shout_at]))'));+ await chrome.stable("(document.querySelector('.asks-toggle[data-fold=\"waiting\"]'))?.getAttribute('aria-expanded') !== 'true' && !!(document.querySelector('.asks-toggle[data-fold=\"waiting\"]'))").then(open => open ? chrome.click("document.querySelector('.asks-toggle[data-fold=\"waiting\"]')") : undefined);+ const ids = JSON.parse(await chrome.stable('JSON.stringify(Object.fromEntries(data.project.shouts.map((s) => [s.shout_text, s.shout_id])))'));+ const answerId = await chrome.stable(`data.project.shouts.find((s) => s.shout_answers === ${asked.shout_id}).shout_id`);+ const stamps = JSON.parse(await chrome.stable('JSON.stringify(data.project.shouts.map((s) => [s.shout_id, s.shout_at]))'));/** Everything a card shows, measured where it stands. */- const read = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const box = (e) => { if (!e) return null; const r = e.getBoundingClientRect(); return { left: r.left, right: r.right, top: r.top, bottom: r.bottom, width: r.width, height: r.height }; };const style = (e) => getComputedStyle(e);const card = (place, id) => {@@ -551,26 +553,26 @@ test('shouts read as cards [N26]', { timeout: 120_000 }, async (t) => {// Folding: more opens the whole shout, less closes it, and an open shout stays open across a refresh.await shoutsAt(chrome, 1280, 'light');- const foldOf = () => chrome.evaluate(`JSON.stringify((() => { const c = document.querySelector('#feed #shout-${ids[long]}'), t = c.querySelector('.text'); return [c.querySelector('.more').textContent, Math.round(t.clientHeight / parseFloat(getComputedStyle(t).lineHeight))]; })())`).then(JSON.parse);- await chrome.evaluate(`document.querySelector('#feed #shout-${ids[long]} .more').click()`);+ const foldOf = () => chrome.stable(`JSON.stringify((() => { const c = document.querySelector('#feed #shout-${ids[long]}'), t = c.querySelector('.text'); return [c.querySelector('.more').textContent, Math.round(t.clientHeight / parseFloat(getComputedStyle(t).lineHeight))]; })())`).then(JSON.parse);+ await chrome.click(`document.querySelector('#feed #shout-${ids[long]} .more')`);assert.deepEqual(await foldOf(), ['less', 12], 'more shows every line');box.run(alpha.web, 'shout', 'all', 'A later shout.');await chrome.waitFor(`data.project.shouts.some((s) => s.shout_text === 'A later shout.') && document.querySelector('#feed .shout .text')?.textContent === 'A later shout.'`, 15_000);assert.deepEqual(await foldOf(), ['less', 12], 'an open shout stays open across a refresh');- await chrome.evaluate(`document.querySelector('#feed #shout-${ids[long]} .more').click()`);+ await chrome.click(`document.querySelector('#feed #shout-${ids[long]} .more')`);assert.deepEqual(await foldOf(), ['more', 6], 'less folds it again');// The block opens on its header to the lines it names, in its own frame.const blockRef = `document.querySelector('#feed #shout-${ids[blockShout]} .code-ref > button.ref.block')`;- await chrome.evaluate(`${blockRef}.click()`);+ await chrome.click(`${blockRef}`);await chrome.waitFor(`${blockRef}.parentElement.classList.contains('open') && ${blockRef}.getAttribute('aria-expanded') === 'true' && ${blockRef}.parentElement.querySelector('.code-wrap .code')?.textContent.includes('Demo spec')`, 15_000);// The short label still opens the code it names, at that commit.const deepRef = `[...document.querySelectorAll('#feed #shout-${ids[refsShout]} button[data-code]')][1]`;- await chrome.evaluate(`${deepRef}.click()`);+ await chrome.click(`${deepRef}`);await chrome.waitFor(`${deepRef}.getAttribute('aria-expanded') === 'true' && ${deepRef}.nextElementSibling?.textContent.includes('Deep line one')`, 15_000);// An inline reference keeps its label in the sentence and opens the same block a reference on its own line is.- const opened = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const opened = JSON.parse(await chrome.stable(`JSON.stringify((() => {const inline = ${deepRef}, block = inline.nextElementSibling, header = block?.querySelector(':scope > button.ref.block');const standalone = document.querySelector('#feed #shout-${ids[blockShout]} .code-ref.open');return { label: !inline.classList.contains('block') && inline.textContent, next: block?.className, header: header && [header.dataset.code, header.textContent, header.getAttribute('aria-expanded')],@@ -615,13 +617,13 @@ test('the shout composer, agent filter and agents panel [N26]', { timeout: 120_0try {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor('typeof data !== "undefined" && data?.project?.shouts?.length >= 4');- await chrome.evaluate("document.querySelector('[data-tab=shouts]').click()");+ await chrome.click("document.querySelector('[data-tab=shouts]')");await chrome.waitFor('document.querySelector("[data-pane=shouts]:not([hidden]) #feed .shout")');- await chrome.evaluate("(() => { const fold = document.querySelector('.fold-line[data-fold=\"idle\"]'); if (fold && fold.getAttribute('aria-expanded') !== 'true') fold.click(); })()");- const agents = JSON.parse(await chrome.evaluate('JSON.stringify(data.project.agents.map((a) => [a.agent_id, a.agent_path]))'));+ await chrome.stable("(document.querySelector('.fold-line[data-fold=\"idle\"]'))?.getAttribute('aria-expanded') !== 'true' && !!(document.querySelector('.fold-line[data-fold=\"idle\"]'))").then(open => open ? chrome.click("document.querySelector('.fold-line[data-fold=\"idle\"]')") : undefined);+ const agents = JSON.parse(await chrome.stable('JSON.stringify(data.project.agents.map((a) => [a.agent_id, a.agent_path]))'));assert.deepEqual(agents.filter(([, path]) => [alpha.web, idle, fresh].includes(path)).map(([id]) => id).sort(), ['web-1', 'web-2', 'web-3'], 'three agents joined the web lane');- const total = await chrome.evaluate('data.project.shouts.length');- const state = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const total = await chrome.stable('data.project.shouts.length');+ const state = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const box = (e) => { if (!e) return null; const r = e.getBoundingClientRect(); return { left: r.left, right: r.right, top: r.top, bottom: r.bottom, width: r.width, height: r.height }; };const pane = document.querySelector('[data-pane=shouts]'), list = document.querySelector('#agents');return {@@ -636,7 +638,7 @@ test('the shout composer, agent filter and agents panel [N26]', { timeout: 120_0kept: (() => { try { return localStorage.getItem('pb.agents'); } catch { return 'unreadable'; } })(),};})())`));- const click = (selector) => chrome.evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);+ const click = (selector) => chrome.click(`document.querySelector(${JSON.stringify(selector)})`);const key = async (modifiers) => {for (const type of ['keyDown', 'keyUp']) await chrome.send('Input.dispatchKeyEvent', { type, key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13, modifiers, ...(type === 'keyDown' ? { text: '\r', unmodifiedText: '\r' } : {}) });};@@ -673,22 +675,22 @@ test('the shout composer, agent filter and agents panel [N26]', { timeout: 120_0await click('#agents .all-agents');// The message grows as it is typed; Shift+Enter starts a line, Enter sends.- await chrome.evaluate("document.querySelector('#shout-text').focus()");- const height = () => chrome.evaluate("document.querySelector('#shout-text').getBoundingClientRect().height");+ await chrome.stable("document.querySelector('#shout-text').focus()");+ const height = () => chrome.stable("document.querySelector('#shout-text').getBoundingClientRect().height");const one = await height();await chrome.send('Input.insertText', { text: 'First line' });await key(8);await chrome.send('Input.insertText', { text: 'second line' });await key(8);await chrome.send('Input.insertText', { text: 'third line' });- assert.equal(await chrome.evaluate("document.querySelector('#shout-text').value"), 'First line\nsecond line\nthird line', 'Shift+Enter starts a new line');+ assert.equal(await chrome.stable("document.querySelector('#shout-text').value"), 'First line\nsecond line\nthird line', 'Shift+Enter starts a new line');assert.ok(await height() > one + 20, 'the message grows as it is typed');- assert.equal(await chrome.evaluate('data.project.shouts.length'), total, 'and sends nothing');+ assert.equal(await chrome.stable('data.project.shouts.length'), total, 'and sends nothing');await key(0);await chrome.waitFor("data.project.shouts.some((s) => s.shout_text === 'First line\\nsecond line\\nthird line' && s.shout_to === 'coordinator')", 15_000);await chrome.waitFor("document.querySelector('#shout-text').value === ''");assert.ok(Math.abs(await height() - one) < 1, 'Enter sends, and the bar shrinks back to one line');- assert.ok(await chrome.evaluate("!document.querySelector('#console').hidden && !document.querySelector('.composer #console') && document.querySelector('#console').getBoundingClientRect().bottom <= document.querySelector('.composer').getBoundingClientRect().top"),+ assert.ok(await chrome.stable("!document.querySelector('#console').hidden && !document.querySelector('.composer #console') && document.querySelector('#console').getBoundingClientRect().bottom <= document.querySelector('.composer').getBoundingClientRect().top"),'the result stands above the bar, never inside it');// The panel hides and shows, and the browser remembers.@@ -698,7 +700,7 @@ test('the shout composer, agent filter and agents panel [N26]', { timeout: 120_0assert.deepEqual([s.bare, s.panel, s.toggle, s.kept], [true, false, 'Show agents', 'hidden'], 'Hide agents hides the panel and remembers it');await chrome.send('Page.reload');await chrome.waitFor('typeof data !== "undefined" && data?.project?.shouts?.length > 0 && !!document.querySelector("[data-tab=shouts]")');- await chrome.evaluate("document.querySelector('[data-tab=shouts]').click()");+ await chrome.click("document.querySelector('[data-tab=shouts]')");await chrome.waitFor('document.querySelector("[data-pane=shouts]:not([hidden]) #feed .shout")');s = await state();assert.deepEqual([s.bare, s.panel, s.toggle], [true, false, 'Show agents'], 'still hidden after a reload');@@ -735,11 +737,11 @@ test('the composer goes to the coordinator and says who heard [N26]', { timeout:try {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor('typeof data !== "undefined" && data?.project?.shouts?.length >= 1');- await chrome.evaluate("document.querySelector('[data-tab=shouts]').click()");+ await chrome.click("document.querySelector('[data-tab=shouts]')");await chrome.waitFor('document.querySelector("[data-pane=shouts]:not([hidden]) #feed .shout")');- await chrome.evaluate("document.querySelector('#agents .fold-line[data-fold=\"idle\"]').click()");+ await chrome.click("document.querySelector('#agents .fold-line[data-fold=\"idle\"]')");/** The composer and every shout of the person's, with what its Heard line says. */- const read = async () => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async () => JSON.parse(await chrome.stable(`JSON.stringify((() => {const chip = document.querySelector('#shout-to-chip'), clear = chip.querySelector('[data-to-clear]');return {page: { width: document.documentElement.clientWidth, scroll: document.documentElement.scrollWidth, body: document.body.scrollWidth },@@ -767,17 +769,17 @@ test('the composer goes to the coordinator and says who heard [N26]', { timeout:// A shout to a lane no agent has joined reached no one, so it has not been heard.assert.deepEqual(r.heard.find(([text]) => text === 'Docs, anyone?')?.slice(1), ['Not heard yet', 0, ''], `${at}: a shout that reached no agent says Not heard yet`);// A picked agent's chip has an x that is a 44px square target; picking the agent again puts it back.- await chrome.evaluate(`document.querySelector('#agents [data-agent="web-1"]').click()`);+ await chrome.click(`document.querySelector('#agents [data-agent="web-1"]')`);const picked = await read();assert.ok(picked.chip === 'to web-1 (Test Model)×' && picked.clear[0] >= tapTarget(width) && picked.clear[1] >= tapTarget(width), `${at}: the chip's x is a square target: ${JSON.stringify(picked.clear)}`);- await chrome.evaluate(`document.querySelector('#agents [data-agent="web-1"]').click()`);+ await chrome.click(`document.querySelector('#agents [data-agent="web-1"]')`);assert.equal((await read()).chip, null, `${at}: picking the agent again returns the composer to the coordinator`);}}// The person shouts with Enter: it goes to the coordinator, and says it is not heard until the coordinator reads it.await shoutsAt(chrome, 1280, 'light');- await chrome.evaluate("document.querySelector('#shout-text').focus()");+ await chrome.stable("document.querySelector('#shout-text').focus()");await chrome.send('Input.insertText', { text: 'Ship the greeting?' });await key();await chrome.waitFor("data.project.shouts.some((s) => s.shout_from === 'person' && s.shout_to === 'coordinator' && s.shout_text === 'Ship the greeting?')", 15_000);@@ -795,20 +797,20 @@ test('the composer goes to the coordinator and says who heard [N26]', { timeout:assert.deepEqual(all.slice(2), [2, 'Heard by coordinator (unknown), web-1 (Test Model)'], 'with their avatars, and every name on hover');// Picking an agent addresses the composer to it; the chip's x returns it to the coordinator.- await chrome.evaluate(`document.querySelector('#agents [data-agent="web-1"]').click()`);+ await chrome.click(`document.querySelector('#agents [data-agent="web-1"]')`);let r = await read();assert.deepEqual([r.chip, r.to, r.placeholder], ['to web-1 (Test Model)×', 'web-1', 'Shout to web-1 (Test Model)'], 'a picked agent shows as a chip');- const clearAt = tapTarget(await chrome.evaluate('innerWidth'));+ const clearAt = tapTarget(await chrome.stable('innerWidth'));assert.ok(r.clear[0] >= clearAt && r.clear[1] >= clearAt, 'whose x is a square target');- await chrome.evaluate(`document.querySelector('#shout-to-chip [data-to-clear]').click()`);+ await chrome.click(`document.querySelector('#shout-to-chip [data-to-clear]')`);r = await read();assert.deepEqual([r.chip, r.to, r.placeholder], [null, 'coordinator', 'Shout to the coordinator'], 'the x returns it to the coordinator');// An item's Shout button addresses its lane the same way.- await chrome.evaluate("document.querySelector('[data-tab=items]').click()");+ await chrome.click("document.querySelector('[data-tab=items]')");await chrome.waitFor('!!document.querySelector("#chain [data-item=\\"1\\"]")');- await chrome.evaluate(`document.querySelector('#chain [data-item="1"]').click()`);+ await chrome.click(`document.querySelector('#chain [data-item="1"]')`);await chrome.waitFor('!!document.querySelector("#detail [data-shout]")');- await chrome.evaluate(`document.querySelector('#detail [data-shout]').click()`);+ await chrome.click(`document.querySelector('#detail [data-shout]')`);await chrome.waitFor("!document.querySelector('[data-pane=shouts]').hidden");for (const width of [375, 1280]) {await shoutsAt(chrome, width, 'dark');@@ -843,8 +845,8 @@ test("a waiting ask's who and when stay on one line with wide fonts [N26]", { tiawait press(chrome, "document.querySelector('.asks-toggle')");await pressedInto(chrome, "!!document.querySelector('#decisions .shout:not(:has(.answer)) header')");// Change font metrics only: the production layout must fit the same real waiting ask.- await chrome.evaluate("(() => { const sheet = document.styleSheets[0]; sheet.insertRule('#decisions .shout header { font-family: monospace; letter-spacing: 1px; }', sheet.cssRules.length); })()");- const result = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ await chrome.stable("(() => { const sheet = document.styleSheets[0]; sheet.insertRule('#decisions .shout header { font-family: monospace; letter-spacing: 1px; }', sheet.cssRules.length); })()");+ const result = JSON.parse(await chrome.stable(`JSON.stringify((() => {const card = document.querySelector('#decisions .shout:not(:has(.answer))'), header = card.querySelector('header');const rect = (element) => { const r = element.getBoundingClientRect(); return { left:r.left, right:r.right, top:r.top, bottom:r.bottom, width:r.width, height:r.height }; };const who = header.querySelector('.who'), address = who.querySelector('.agent-id') || who, age = header.querySelector('time'), kind = header.querySelector('.mark');@@ -936,28 +938,19 @@ test('shout cards fit beside a classic scrollbar [N26]', { timeout: 120_000 }, aawait chrome.waitFor('typeof data !== "undefined" && data?.project?.shouts?.length >= 12');/** Press a real mouse at an uncovered control after layout settles. */const press = async (selector) => {- const point = await chrome.evaluate(`(async () => {- const e=document.querySelector(${JSON.stringify(selector)}); e.scrollIntoView({block:'center',behavior:'instant'});- await new Promise(done=>requestAnimationFrame(()=>requestAnimationFrame(done)));- const r=e.getBoundingClientRect(),x=r.x+r.width/2,y=r.y+r.height/2,hit=document.elementFromPoint(x,y);- if(!r.width||!r.height||(hit!==e&&!e.contains(hit)))throw Error('mouse target is hidden or covered');- return {x,y};- })()`);- for (const type of ['mouseMoved','mousePressed','mouseReleased']) await chrome.send('Input.dispatchMouseEvent', {- type,...point,...(type==='mouseMoved'?{}:{button:'left',clickCount:1}),- });+ await sharedPress(chrome, `document.querySelector(${JSON.stringify(selector)})`);};await press('[data-tab="shouts"]');await chrome.waitFor('document.querySelector("[data-pane=shouts]:not([hidden]) #feed .shout")');- if (await chrome.evaluate(`document.querySelector('.asks-toggle[data-fold="waiting"]')?.getAttribute('aria-expanded') === 'false'`)) await press('.asks-toggle[data-fold="waiting"]');+ if (await chrome.stable(`document.querySelector('.asks-toggle[data-fold="waiting"]')?.getAttribute('aria-expanded') === 'false'`)) await press('.asks-toggle[data-fold="waiting"]');for (const font of ['monospace', '']) for (const scheme of ['light','dark']) {// A portable fallback exercises the wider font metrics used by CI, alongside the native font.- await chrome.evaluate(`document.documentElement.style.setProperty('--sans', ${JSON.stringify(font)})`);+ await chrome.stable(`document.documentElement.style.setProperty('--sans', ${JSON.stringify(font)})`);await shoutsAt(chrome,375,scheme);- const gutter=await chrome.evaluate('innerWidth-document.documentElement.clientWidth');+ const gutter=await chrome.stable('innerWidth-document.documentElement.clientWidth');assert.ok(gutter>=0&&gutter<=30, 'the fixture measures the browser scrollbar before selecting the viewport');await shoutsAt(chrome,360+gutter,scheme);- const metrics=await chrome.evaluate(`(() => {+ const metrics=await chrome.stable(`(() => {const width=document.documentElement.clientWidth;const edge=e=>{const r=e.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom,width:r.width};};const cards=[...document.querySelectorAll('#feed .shout,#decisions .shout')];diff --git a/test/cockpit/snapshot.test.js b/test/cockpit/snapshot.test.jsindex c0300636..28492b32 100644--- a/test/cockpit/snapshot.test.js+++ b/test/cockpit/snapshot.test.js@@ -91,7 +91,7 @@ test('static export stays in its prefix and replays read-only in Chrome [A10,A3]let chrome;try {chrome = await openSnapshotChrome(executable, `${base}${prefix}`, profile);- const evaluate = chrome.evaluate;+ const evaluate = chrome.stable;await chrome.waitFor("document.body?.classList.contains('snapshot') && typeof snapshotReplay === 'object' && !!data?.project && snapshotReplay.events.length > 0 && snapshotReplay.index === snapshotReplay.events.length");await chrome.waitFor("!!document.querySelector('#replay-play') && !!document.querySelector('#replay-pause') && !!document.querySelector('#replay-speed') && !!document.querySelector('#replay-progress')");@@ -110,7 +110,7 @@ test('static export stays in its prefix and replays read-only in Chrome [A10,A3]assert.ok(shout.html.includes('<script>'), 'the snapshot escapes HTML in shout text');assert.equal(shout.scripts, 0, 'shout text never becomes an executable script element');- const firstPosition = JSON.parse(await evaluate(`(() => {+ await evaluate(`(() => {window.__snapshotRealAdvance = advanceReplay;window.__snapshotFirstPosition = null;window.advanceReplay = () => {@@ -118,9 +118,9 @@ test('static export stays in its prefix and replays read-only in Chrome [A10,A3]snapshotReplay.playing = false;replayControls();};- document.querySelector('#replay-play').click();- return JSON.stringify(window.__snapshotFirstPosition);- })()`));+ })()`);+ await chrome.click("document.querySelector('#replay-play')");+ const firstPosition = JSON.parse(await evaluate('JSON.stringify(window.__snapshotFirstPosition)'));assert.deepEqual(firstPosition, { index: 0, items: [] }, 'play starts from an empty board before its first event');await evaluate('window.advanceReplay = window.__snapshotRealAdvance');@@ -155,10 +155,10 @@ test('static export stays in its prefix and replays read-only in Chrome [A10,A3]if (status) window.__replayObserved.push({ index, status });}).observe(progress, { childList: true, characterData: true, subtree: true });})()`);- await evaluate("document.querySelector('#replay-play').click()");+ await chrome.click("document.querySelector('#replay-play')");await chrome.waitFor('snapshotReplay.playing && snapshotReplay.index > 0 && snapshotReplay.index < snapshotReplay.events.length');const beforePause = await evaluate('snapshotReplay.index');- await evaluate("document.querySelector('#replay-pause').click()");+ await chrome.click("document.querySelector('#replay-pause')");await chrome.waitFor('!snapshotReplay.playing');const pausedIndex = await evaluate('snapshotReplay.index');assert.equal(pausedIndex, beforePause, 'pause keeps the current replay event');@@ -170,7 +170,7 @@ test('static export stays in its prefix and replays read-only in Chrome [A10,A3]const speedStart = await evaluate('snapshotReplay.index');assert.ok(speedStart + 4 < initial.total, 'at least four events remain to measure 16x playback');const speedStartedAt = Date.now();- await evaluate("document.querySelector('#replay-play').click()");+ await chrome.click("document.querySelector('#replay-play')");await chrome.waitFor(`snapshotReplay.index >= ${speedStart + 4}`, 2_000);assert.ok(Date.now() - speedStartedAt < 2_000, '16x advances four replay events within two seconds');await chrome.waitFor('!snapshotReplay.playing', 20_000);diff --git a/test/cockpit/spec.test.js b/test/cockpit/spec.test.jsindex ba74958a..45ebf3a2 100644--- a/test/cockpit/spec.test.js+++ b/test/cockpit/spec.test.js@@ -50,7 +50,7 @@ test('Spec and Doctrine line up, open on a row and decide with quiet controls [Nconst profile = mkdtempSync(join(tmpdir(), 'pullboard-spec-layout-chrome-'));let chrome;/** Where the list and detail cards start, what is picked, and how a row's decision sits beside its text. */- const read = async (kind) => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async (kind) => JSON.parse(await chrome.stable(`JSON.stringify((() => {const pane = document.querySelector('[data-pane="${kind}"]');const box = (e) => { const r = e.getBoundingClientRect(); return { top: r.top, bottom: r.bottom, left: r.left, right: r.right, height: r.height }; };const row = document.querySelector('#${kind}-list .srow[data-row="${kind}:G1"]');@@ -70,7 +70,7 @@ test('Spec and Doctrine line up, open on a row and decide with quiet controls [Nawait chrome.waitFor("typeof data === 'object' && !!data && !!data.project");for (const width of [1280, 375]) {await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });- await chrome.evaluate("document.querySelector('[data-tab=spec]').click(); document.querySelector('#spec-chips [data-rows=\"spec:decide\"]').click(); view.row.spec = null; render();");+ await chrome.click("document.querySelector('[data-tab=spec]')"); await chrome.click("document.querySelector('#spec-chips [data-rows=\"spec:decide\"]')"); await chrome.stable("view.row.spec = null"); await chrome.stable("render()");await chrome.waitFor(`innerWidth === ${width} && !!document.querySelector('#spec-list [data-row="spec:G1"]')`);const spec = await read('spec');if (width === 1280) assert.ok(Math.abs(spec.list.top - spec.detail.top) < 0.5, `${width}: the list and the detail start on one line: ${JSON.stringify([spec.list, spec.detail])}`);@@ -83,13 +83,13 @@ test('Spec and Doctrine line up, open on a row and decide with quiet controls [N}assert.ok(!spec.overflow, `${width}: nothing runs off the screen`);// A filter that hides the pick moves it to the new first row; one that keeps it keeps it.- await chrome.evaluate("document.querySelector('#spec-list [data-row=\"spec:G2\"]').click()");- await chrome.evaluate("document.querySelector('#spec-chips [data-rows=\"spec:all\"]').click()");+ await chrome.click("document.querySelector('#spec-list [data-row=\"spec:G2\"]')");+ await chrome.click("document.querySelector('#spec-chips [data-rows=\"spec:all\"]')");assert.equal((await read('spec')).picked, 'spec:G2', `${width}: a filter that still shows the pick keeps it`);- await chrome.evaluate("document.querySelector('#spec-chips [data-rows=\"spec:approved\"]').click()");+ await chrome.click("document.querySelector('#spec-chips [data-rows=\"spec:approved\"]')");const moved = await read('spec');assert.deepEqual([moved.picked, moved.shown], ['spec:G3', 'G3'], `${width}: a filter that hides the pick moves it to the first row shown`);- await chrome.evaluate("document.querySelector('[data-tab=doctrine]').click(); view.row.doctrine = null; render();");+ await chrome.click("document.querySelector('[data-tab=doctrine]')"); await chrome.stable("view.row.doctrine = null"); await chrome.stable("render()");const doctrine = await read('doctrine');if (width === 1280) assert.ok(Math.abs(doctrine.list.top - doctrine.detail.top) < 0.5, `${width}: Doctrine's cards start on one line too`);assert.ok(doctrine.picked && doctrine.picked === doctrine.first && doctrine.shown === doctrine.first.split(':')[1], `${width}: and Doctrine opens on its first row: ${JSON.stringify([doctrine.picked, doctrine.shown])}`);@@ -122,7 +122,7 @@ test('spec rows read as a list, decided in the panel [N26]', { timeout: 300_000const profile = mkdtempSync(join(tmpdir(), 'pullboard-spec-list-chrome-'));let chrome;/** One tab's rows and detail as they read: each row's chip, gutter, words and lines, and the detail's decision. */- const read = async (kind) => JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const read = async (kind) => JSON.parse(await chrome.stable(`JSON.stringify((() => {const box = (e) => { const r = e.getBoundingClientRect(); return { left: r.left, right: r.right, top: r.top, bottom: r.bottom, width: r.width, height: r.height }; };const rows = [...document.querySelectorAll('#${kind}-list .srow')].map((row) => {const s = getComputedStyle(row), text = row.querySelector('.srow-text');@@ -141,16 +141,15 @@ test('spec rows read as a list, decided in the panel [N26]', { timeout: 300_000/** A tint is quiet when its colour channels sit close together: grey, not a hue. */const neutral = (css) => { const [r, g, b] = (css.match(/[\d.]+/g) || []).map(Number); return Math.max(r, g, b) - Math.min(r, g, b) <= 12; };/** Press a key the way a keyboard does, into whatever has focus. */- const press = async (key, code, keyCode) => {+ const pressKey = async (key, code, keyCode) => {for (const type of ['keyDown', 'keyUp']) await chrome.send('Input.dispatchKeyEvent', { type, key, code, windowsVirtualKeyCode: keyCode, ...(type === 'keyDown' && key.length === 1 ? { text: key, unmodifiedText: key } : {}) });};/** Tap an element through Chrome's input path at its centre. */const tap = async (selector) => {- const point = JSON.parse(await chrome.evaluate(`(() => { const e = document.querySelector(${JSON.stringify(selector)}); e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(); return JSON.stringify({ x: r.x + r.width / 2, y: r.y + r.height / 2 }); })()`));- for (const type of ['mousePressed', 'mouseReleased']) await chrome.send('Input.dispatchMouseEvent', { type, ...point, button: 'left', clickCount: 1 });+ await press(chrome, `document.querySelector(${JSON.stringify(selector)})`);};const filter = async (kind, name) => {- await chrome.evaluate(`document.querySelector('[data-tab=${kind}]').click(); document.querySelector('#${kind}-chips [data-rows="${kind}:${name}"]').click()`);+ await chrome.click(`document.querySelector('[data-tab=${kind}]')`); await chrome.click(`document.querySelector('#${kind}-chips [data-rows="${kind}:${name}"]')`);await chrome.waitFor(`!document.querySelector('[data-pane=${kind}]').hidden && !!document.querySelector('#${kind}-list .srow')`);};/** A row as the board records it: Spec rows by id, Doctrine rules by id among the merged rules. */@@ -166,7 +165,7 @@ test('spec rows read as a list, decided in the panel [N26]', { timeout: 300_000await chrome.waitFor("typeof data === 'object' && !!data?.project?.spec?.length && data.project.practice.some((r) => r.id === 'D8')");// Pullboard's own rules can wait on the person too; they list under Needs your decision, in the board's order, but are// changed in DOCTRINE.md rather than decided here.- const order = JSON.parse(await chrome.evaluate("JSON.stringify(data.project.practice.map((r) => [r.id, r.origin, r.status, !!r.decision]))"));+ const order = JSON.parse(await chrome.stable("JSON.stringify(data.project.practice.map((r) => [r.id, r.origin, r.status, !!r.decision]))"));const standardWaiting = order.filter(([, origin, status, decided]) => origin === 'standard' && ['pending', 'draft'].includes(status) && !decided).map(([id, , status]) => [id, status === 'draft' ? null : status]);expected.doctrine.decide = [...standardWaiting, ...expected.doctrine.decide].sort(([a], [b]) => order.findIndex(([id]) => id === a) - order.findIndex(([id]) => id === b));for (const scheme of ['light', 'dark']) {@@ -204,31 +203,31 @@ test('spec rows read as a list, decided in the panel [N26]', { timeout: 300_000const held = await read(kind);assert.deepEqual(held.decide.map((b) => b.word), ['Approve', 'Decline'], `${tab}: the picked row's detail holds its decision`);assert.ok(held.decide.every((b) => b.height >= tapTarget(width)), `${tab}: each a target, 44px where a finger taps`);- await press('ArrowDown', 'ArrowDown', 40);- assert.equal(await chrome.evaluate(`view.row['${kind}']`), undecidedNow[undecidedNow.findIndex(([id]) => id === first) + 1][0], `${tab}: down moves the pick`);- await press('ArrowUp', 'ArrowUp', 38);- assert.equal(await chrome.evaluate(`view.row['${kind}']`), first, `${tab}: and up moves it back`);- await press('a', 'KeyA', 65);+ await pressKey('ArrowDown', 'ArrowDown', 40);+ assert.equal(await chrome.stable(`view.row['${kind}']`), undecidedNow[undecidedNow.findIndex(([id]) => id === first) + 1][0], `${tab}: down moves the pick`);+ await pressKey('ArrowUp', 'ArrowUp', 38);+ assert.equal(await chrome.stable(`view.row['${kind}']`), first, `${tab}: and up moves it back`);+ await pressKey('a', 'KeyA', 65);const after = undecidedNow[undecidedNow.findIndex(([id]) => id === first) + 1][0];await chrome.waitFor(`!!document.querySelector('#${kind}-list .spec-feedback.ok') && view.row['${kind}'] === '${after}'`, 15_000);assert.deepEqual([await recorded(kind, first), await recorded(kind, second)], [{ stage: 'approved, pending apply', decided: 'approved' }, { stage: 'draft', decided: null }],`${tab}: A approved the picked ${first}, and only ${first}`);- assert.equal(await chrome.evaluate(`document.activeElement === document.querySelector('#${kind}-list')`), true, `${tab}: the list keeps focus for the next key`);+ assert.equal(await chrome.stable(`document.activeElement === document.querySelector('#${kind}-list')`), true, `${tab}: the list keeps focus for the next key`);// The pick moved on to the next row; when that is the open question, step past it to a draft.- if (after !== second) { await press('ArrowDown', 'ArrowDown', 40); await chrome.waitFor(`view.row['${kind}'] === '${second}'`); }- await press('d', 'KeyD', 68);+ if (after !== second) { await pressKey('ArrowDown', 'ArrowDown', 40); await chrome.waitFor(`view.row['${kind}'] === '${second}'`); }+ await pressKey('d', 'KeyD', 68);await chrome.waitFor(`!document.querySelector('#spec-decline-dialog').hidden && document.querySelector('#spec-decline-title').textContent === 'Decline ${second}'`);// Never while typing in a field: an a in the reason is a letter, not an approval.- await press('a', 'KeyA', 65);- assert.equal(await chrome.evaluate("document.querySelector('#spec-decline-reason').value"), 'a', `${tab}: the key types into the reason`);+ await pressKey('a', 'KeyA', 65);+ assert.equal(await chrome.stable("document.querySelector('#spec-decline-reason').value"), 'a', `${tab}: the key types into the reason`);assert.deepEqual(await recorded(kind, second), { stage: 'draft', decided: null }, `${tab}: and decides nothing`);await chrome.send('Input.insertText', { text: ' clearer outcome, please' });- await chrome.evaluate("document.querySelector('#spec-decline-submit').click()");+ await chrome.click("document.querySelector('#spec-decline-submit')");await chrome.waitFor(`document.querySelector('#spec-decline-dialog').hidden && !!document.querySelector('#${kind}-list .spec-feedback.ok')`, 15_000);assert.deepEqual(await recorded(kind, second), { stage: 'declined, pending apply', decided: 'a clearer outcome, please' }, `${tab}: D declined ${second} with its reason`);// The last layout decides the last two drafts, so only the earlier ones have a row after them to stay untouched.if (third) assert.deepEqual(await recorded(kind, third), { stage: 'draft', decided: null }, `${tab}: and nothing else`);- assert.equal(await chrome.evaluate(`document.activeElement === document.querySelector('#${kind}-list')`), true, `${tab}: the dialog returns to the list`);+ assert.equal(await chrome.stable(`document.activeElement === document.querySelector('#${kind}-list')`), true, `${tab}: the dialog returns to the list`);// The two decided rows leave Needs your decision.expected[kind].decide = undecidedNow.filter(([id]) => id !== first && id !== second);await chrome.waitFor(`![...document.querySelectorAll('#${kind}-list .srow')].some((row) => ['${kind}:${first}', '${kind}:${second}'].includes(row.dataset.row))`, 15_000);@@ -248,11 +247,11 @@ test('spec rows read as a list, decided in the panel [N26]', { timeout: 300_000await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });await chrome.waitFor('innerWidth === 1280');await filter('doctrine', 'all');- const standard = await chrome.evaluate("[...document.querySelectorAll('#doctrine-list .srow')].map((row) => row.dataset.row.slice(9)).find((id) => id.startsWith('PB'))");+ const standard = await chrome.stable("[...document.querySelectorAll('#doctrine-list .srow')].map((row) => row.dataset.row.slice(9)).find((id) => id.startsWith('PB'))");await tap(`#doctrine-list [data-row="doctrine:${standard}"]`);await chrome.waitFor(`view.row.doctrine === '${standard}' && document.activeElement === document.querySelector('#doctrine-list')`);- assert.equal(await chrome.evaluate("document.querySelectorAll('#doctrine-detail [data-row-decision]').length"), 0, `${standard}: a standard rule's detail offers no decision`);- await press('a', 'KeyA', 65);+ assert.equal(await chrome.stable("document.querySelectorAll('#doctrine-detail [data-row-decision]').length"), 0, `${standard}: a standard rule's detail offers no decision`);+ await pressKey('a', 'KeyA', 65);assert.equal((await recorded('doctrine', standard)).decided, null, `${standard}: A decides nothing on it`);assert.deepEqual(chrome.exceptions, [], 'the page raises no uncaught exception');} finally {@@ -268,17 +267,7 @@ test('real Chrome records Spec row decisions from the row, detail and confirmed/** Click a visible control through Chrome's input path without scrolling the result away. */const click = async (chrome, selector) => {- const point = JSON.parse(await chrome.evaluate(`(() => {- const e = document.querySelector(${JSON.stringify(selector)});- if (!e) throw Error('missing ' + ${JSON.stringify(selector)});- e.scrollIntoView({block:'center'});- const r = e.getBoundingClientRect();- if (r.width <= 0 || r.height <= 0 || r.top < 0 || r.bottom > innerHeight) throw Error('control is not visible: ' + ${JSON.stringify(selector)});- return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2});- })()`));- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...point });- await chrome.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...point, button: 'left', clickCount: 1 });- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...point, button: 'left', clickCount: 1 });+ await press(chrome, `document.querySelector(${JSON.stringify(selector)})`);};/** Run the full decision story in a fresh real board and browser at one viewport width. */@@ -295,11 +284,11 @@ test('real Chrome records Spec row decisions from the row, detail and confirmedchrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor("typeof data === 'object' && !!data && !!data.project");await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });- await chrome.evaluate("document.querySelector('[data-tab=spec]').click()");+ await chrome.click("document.querySelector('[data-tab=spec]')");await chrome.waitFor(`innerWidth === ${width} && !!document.querySelector('#spec-list [data-row="spec:G1"]')`);- await chrome.evaluate("document.querySelector('#spec-chips [data-rows=\"spec:all\"]').click()");+ await chrome.click("document.querySelector('#spec-chips [data-rows=\"spec:all\"]')");await chrome.waitFor("document.querySelector('#spec-list [data-row=\"spec:G2\"]') && document.querySelector('#spec-chips [data-rows=\"spec:decide\"] b')?.textContent === '31'");- const geometry = JSON.parse(await chrome.evaluate(`JSON.stringify({+ const geometry = JSON.parse(await chrome.stable(`JSON.stringify({overflow: document.documentElement.scrollWidth > document.documentElement.clientWidth,controls: [...document.querySelectorAll('#spec-list button[data-row-decision],#spec-list button[data-section-approve]')].map(e=>({height:e.getBoundingClientRect().height})),rows: [...document.querySelectorAll('#spec-list .srow')].map(row=>{@@ -316,9 +305,9 @@ test('real Chrome records Spec row decisions from the row, detail and confirmedassert.deepEqual(geometry.rows.filter((row) => row.missing), [], `${width}: row status and text are present for every fixture row`);if (width === 1280) assert.deepEqual(geometry.rows.filter((row) => row.intersects), [], '1280: stage chips never cover row text');- await chrome.evaluate("document.querySelector('#spec-list [data-row=\"spec:G2\"]').click()");+ await chrome.click("document.querySelector('#spec-list [data-row=\"spec:G2\"]')");await chrome.waitFor("document.querySelector('#spec-detail h2 span')?.textContent === 'G2'");- assert.ok(await chrome.evaluate("document.querySelector('#spec-detail [data-row-decision=approve]') && document.querySelector('#spec-detail [data-row-decision=decline]')"), `${width}: selected G2 has both detail decisions`);+ assert.ok(await chrome.stable("document.querySelector('#spec-detail [data-row-decision=approve]') && document.querySelector('#spec-detail [data-row-decision=decline]')"), `${width}: selected G2 has both detail decisions`);diagnostics = await watchSpecDecisionWait(chrome);// Picked from the list, A approves G1, and the pick moves on to the next row.await click(chrome, '#spec-list [data-row="spec:G1"]');@@ -330,9 +319,9 @@ test('real Chrome records Spec row decisions from the row, detail and confirmedassert.equal(state.spec.find((row) => row.id === 'G1')?.stage, 'approved, pending apply', `${width}: A approves the picked G1`);assert.equal(state.spec.find((row) => row.id === 'G2')?.decision, undefined, `${width}: and nothing else`);await chrome.waitFor("view.row.spec === 'G2' && document.querySelector('#spec-detail h2 span')?.textContent === 'G2'");- assert.ok(await chrome.evaluate(`(() => { const e=document.querySelector('#spec-list [data-row="spec:G2"]'); const r=e.getBoundingClientRect(); return r.top >= 0 && r.bottom <= innerHeight; })()`), `${width}: next undecided G2 stays in the viewport after G1 approval`);- assert.equal(await chrome.evaluate("document.querySelector('#spec-chips [data-rows=\"spec:decide\"] b').textContent"), '30', `${width}: Needs your decision excludes the decided row`);- if (width === 1280) assert.ok(await chrome.evaluate(`(() => {+ assert.ok(await chrome.stable(`(() => { const e=document.querySelector('#spec-list [data-row="spec:G2"]'); const r=e.getBoundingClientRect(); return r.top >= 0 && r.bottom <= innerHeight; })()`), `${width}: next undecided G2 stays in the viewport after G1 approval`);+ assert.equal(await chrome.stable("document.querySelector('#spec-chips [data-rows=\"spec:decide\"] b').textContent"), '30', `${width}: Needs your decision excludes the decided row`);+ if (width === 1280) assert.ok(await chrome.stable(`(() => {const row=document.querySelector('#spec-list [data-row="spec:G1"]');const chip=row.querySelector('.srow-text .chip').getBoundingClientRect();const words=[...row.querySelector('.srow-text').childNodes].find(n=>n.nodeType===3&&n.textContent.trim());@@ -340,37 +329,37 @@ test('real Chrome records Spec row decisions from the row, detail and confirmedreturn chip.right <= text.left || chip.bottom <= text.top || chip.top >= text.bottom;})()`), '1280: the approved pending stage does not cover row text');- await chrome.evaluate("document.querySelector('#spec-chips [data-rows=\"spec:decide\"]').click()");- assert.equal(await chrome.evaluate("!!document.querySelector('#spec-list [data-row=\"spec:G1\"]')"), false, `${width}: approval immediately leaves Needs your decision`);- await chrome.evaluate("document.querySelector('#spec-chips [data-rows=\"spec:all\"]').click()");+ await chrome.click("document.querySelector('#spec-chips [data-rows=\"spec:decide\"]')");+ assert.equal(await chrome.stable("!!document.querySelector('#spec-list [data-row=\"spec:G1\"]')"), false, `${width}: approval immediately leaves Needs your decision`);+ await chrome.click("document.querySelector('#spec-chips [data-rows=\"spec:all\"]')");await click(chrome, '#spec-detail [data-row-decision="decline"]');- assert.ok(await chrome.evaluate("!document.querySelector('#spec-decline-dialog').hidden && document.querySelector('#spec-decline-title').textContent === 'Decline G2'"), `${width}: G2 decline opens the reason form`);- assert.ok(await chrome.evaluate(`[...document.querySelectorAll('#spec-decline-dialog input,#spec-decline-dialog button')].every(e => e.getBoundingClientRect().height >= ${tapTarget(width)})`), `${width}: decline reason and controls meet the 44px target`);+ assert.ok(await chrome.stable("!document.querySelector('#spec-decline-dialog').hidden && document.querySelector('#spec-decline-title').textContent === 'Decline G2'"), `${width}: G2 decline opens the reason form`);+ assert.ok(await chrome.stable(`[...document.querySelectorAll('#spec-decline-dialog input,#spec-decline-dialog button')].every(e => e.getBoundingClientRect().height >= ${tapTarget(width)})`), `${width}: decline reason and controls meet the 44px target`);await click(chrome, '#spec-decline-cancel');state = await boardOf(view, demo.repo);assert.equal(state.events.filter((event) => event.event_kind === 'row_decision').length, 1, `${width}: cancelling decline records no event`);assert.equal(state.spec.find((row) => row.id === 'G2')?.decision, undefined, `${width}: cancelling leaves G2 undecided`);await click(chrome, '#spec-detail [data-row-decision="decline"]');- await chrome.evaluate("document.querySelector('#spec-decline-reason').value = 'Needs a clearer outcome'");+ await chrome.stable("document.querySelector('#spec-decline-reason').value = 'Needs a clearer outcome'");box.run(demo.repo, 'shout', 'person', `refresh probe ${width}`);await chrome.waitFor(`data.project.shouts.some(shout => shout.shout_text === 'refresh probe ${width}')`);- assert.equal(await chrome.evaluate("document.querySelector('#spec-decline-reason').value"), 'Needs a clearer outcome', `${width}: typed reason survives a live refresh`);+ assert.equal(await chrome.stable("document.querySelector('#spec-decline-reason').value"), 'Needs a clearer outcome', `${width}: typed reason survives a live refresh`);await click(chrome, '#spec-decline-submit');await chrome.waitFor("!!document.querySelector('#spec-detail .spec-feedback.ok,#spec-detail .spec-feedback.no')");- await chrome.evaluate("window.__sectionConfirm = null; window.confirm = message => { window.__sectionConfirm = message; return false; }");+ await chrome.stable("window.__sectionConfirm = null; window.confirm = message => { window.__sectionConfirm = message; return false; }");const sectionSelector = `#spec-list [data-section-approve]`;- await chrome.evaluate(`(() => { const button=[...document.querySelectorAll(${JSON.stringify(sectionSelector)})].find(e=>e.parentElement.querySelector('h4')?.textContent.includes('Follow-up')); if(!button) throw Error('missing K section approval'); button.click(); })()`);+ await chrome.click(`[...document.querySelectorAll(${JSON.stringify(sectionSelector)})].find(e=>e.parentElement.querySelector('h4')?.textContent.includes('Follow-up'))`);state = await boardOf(view, demo.repo);- assert.match(await chrome.evaluate('window.__sectionConfirm'), /Approve all 2 undecided rows in/, `${width}: section approval asks for confirmation`);- assert.equal(await chrome.evaluate("!!document.querySelector('#spec-list .spec-feedback')"), false, `${width}: dismissing the confirmation starts no move`);+ assert.match(await chrome.stable('window.__sectionConfirm'), /Approve all 2 undecided rows in/, `${width}: section approval asks for confirmation`);+ assert.equal(await chrome.stable("!!document.querySelector('#spec-list .spec-feedback')"), false, `${width}: dismissing the confirmation starts no move`);assert.equal(state.events.filter((event) => event.event_kind === 'row_decision').length, 2, `${width}: dismissing section confirmation records no events`);assert.equal(state.spec.find((row) => row.id === 'K1')?.decision, undefined, `${width}: dismissed section approval leaves K1 undecided`);- await chrome.evaluate("window.confirm = () => true");- await chrome.evaluate(`(() => { const button=[...document.querySelectorAll(${JSON.stringify(sectionSelector)})].find(e=>e.parentElement.querySelector('h4')?.textContent.includes('Follow-up')); if(!button) throw Error('missing K section approval'); button.click(); })()`);+ await chrome.stable("window.confirm = () => true");+ await chrome.click(`[...document.querySelectorAll(${JSON.stringify(sectionSelector)})].find(e=>e.parentElement.querySelector('h4')?.textContent.includes('Follow-up'))`);await chrome.waitFor("document.querySelector('#spec-list [data-row=\"spec:K1\"]').innerText.includes('approved, pending apply') && document.querySelector('#spec-list [data-row=\"spec:K2\"]').innerText.includes('approved, pending apply')");state = await boardOf(view, demo.repo);const decisions = state.events.filter((event) => event.event_kind === 'row_decision');@@ -382,16 +371,16 @@ test('real Chrome records Spec row decisions from the row, detail and confirmedassert.equal(state.spec.find((row) => row.id === 'K1')?.stage, 'approved, pending apply', `${width}: K1 was approved`);assert.equal(state.spec.find((row) => row.id === 'K2')?.stage, 'approved, pending apply', `${width}: K2 was approved`);assert.equal(state.spec.find((row) => row.id === 'G3')?.decision, undefined, `${width}: other section rows remain undecided`);- if (width === 1280) assert.ok(await chrome.evaluate(`['G1','G2','K1','K2'].every(id => {+ if (width === 1280) assert.ok(await chrome.stable(`['G1','G2','K1','K2'].every(id => {const row=document.querySelector('#spec-list [data-row="spec:'+id+'"]');const chip=row.querySelector('.srow-text .chip').getBoundingClientRect();const words=[...row.querySelector('.srow-text').childNodes].find(n=>n.nodeType===3&&n.textContent.trim());const range=document.createRange(); range.selectNodeContents(words); const text=range.getClientRects()[0];return chip.right <= text.left || chip.bottom <= text.top || chip.top >= text.bottom;})`), '1280: every pending decision stage has room beside its row text');- await chrome.evaluate("document.querySelector('#spec-chips [data-rows=\"spec:decide\"]').click()");+ await chrome.click("document.querySelector('#spec-chips [data-rows=\"spec:decide\"]')");await chrome.waitFor("document.querySelector('#spec-list [data-row=\"spec:G3\"]') && !document.querySelector('#spec-list [data-row=\"spec:G1\"]') && !document.querySelector('#spec-list [data-row=\"spec:G2\"]') && !document.querySelector('#spec-list [data-row=\"spec:K1\"]') && !document.querySelector('#spec-list [data-row=\"spec:K2\"]')");- assert.ok(await chrome.evaluate("document.querySelector('#spec-chips [data-rows=\"spec:decide\"]').innerText.includes('27')"), `${width}: Needs your decision excludes all four decided rows`);+ assert.ok(await chrome.stable("document.querySelector('#spec-chips [data-rows=\"spec:decide\"]').innerText.includes('27')"), `${width}: Needs your decision excludes all four decided rows`);assert.deepEqual(chrome.exceptions, [], `${width}: Chrome reports no uncaught exceptions`);} finally {try { await diagnostics?.dispose(); }@@ -424,18 +413,10 @@ test('the spec decision wait names its state on timeout [N26]', { timeout: 60_00chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor("typeof data === 'object' && !!data?.project");await chrome.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });- await chrome.evaluate("document.querySelector('[data-tab=spec]').click()");+ await chrome.click("document.querySelector('[data-tab=spec]')");await chrome.waitFor("!!document.querySelector('#spec-list [data-row=\"spec:G1\"]') && !!document.querySelector('#spec-list [data-row=\"spec:G2\"]')");diagnostics = await watchSpecDecisionWait(chrome);- const point = JSON.parse(await chrome.evaluate(`(() => {- const row=document.querySelector('#spec-list [data-row="spec:G1"]');- row.scrollIntoView({block:'center'});- const r=row.getBoundingClientRect();- return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2});- })()`));- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...point });- await chrome.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...point, button: 'left', clickCount: 1 });- await chrome.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...point, button: 'left', clickCount: 1 });+ await press(chrome, `document.querySelector('#spec-list [data-row="spec:G1"]')`);await chrome.waitFor("view.row.spec === 'G1' && document.activeElement === document.querySelector('#spec-list')");for (const type of ['keyDown', 'keyUp']) await chrome.send('Input.dispatchKeyEvent', { type, key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40 });await chrome.waitFor("view.row.spec === 'G2'");diff --git a/test/cockpit/stable.js b/test/cockpit/stable.jsnew file mode 100644index 00000000..85d25197--- /dev/null+++ b/test/cockpit/stable.js@@ -0,0 +1,135 @@+/** One real-Chrome measurement and pointer boundary for all cockpit stories [N26,C7]. */+import assert from 'node:assert/strict';++const clients = new WeakMap();++/** Evaluate only inside the shared boundary; tests receive no raw page evaluator. */+async function rawChromeEvaluation(chrome, expression) {+ const result = await clients.get(chrome).send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });+ if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text);+ return result.result.value;+}++/**+ * Wait for the visible page and each required target to exist with nonzero boxes unchanged over two frames.+ * Sampling descendants includes SVG progress bars and Range containers, not just the control's outer box.+ * The deadline only bounds a missing or perpetually moving target; it is not a rendering speed assertion.+ */+export async function waitForStableBoxes(chrome, find = 'document.documentElement', timeoutMs = 10_000) {+ const result = await rawChromeEvaluation(chrome, `(async () => {+ /** Resolve targets afresh because a board refresh can replace a matching node. */+ const targets = () => { const found = (${find}); return found instanceof Element ? [found] : Array.from(found || []); };+ /** Retain rendered boxes while ignoring deliberate hidden-pane visibility probes. */+ const visible = element => { const style = getComputedStyle(element), box = element.getBoundingClientRect(); return !element.closest('[hidden]') && style.display !== 'none' && style.visibility !== 'hidden' && box.width > 0 && box.height > 0; };+ /** Compare exact layout geometry without tolerances that hide movement. */+ const box = element => { const rect = element.getBoundingClientRect(); return [rect.x, rect.y, rect.width, rect.height]; };+ /** Capture required targets, descendants and page extents in one layout sample. */+ const sample = () => {+ const required = targets();+ if (!required.length || !required.every(element => element.isConnected && visible(element))) return null;+ const elements = [...document.querySelectorAll('body, body *')].filter(visible);+ return { targets: required.map(box), page: [scrollX, scrollY, document.documentElement.clientWidth, document.documentElement.scrollWidth, document.documentElement.scrollHeight, ...elements.map(box)] };+ };+ return await new Promise((resolve, reject) => {+ let previous = '', unchanged = 0, frameId = 0;+ const timer = setTimeout(() => { cancelAnimationFrame(frameId); reject(Error('shared wait: target missing, zero-sized or moving: ' + ${JSON.stringify(find)})); }, ${timeoutMs});+ /** Resolve only after two complete frame intervals have unchanged nonzero geometry. */+ const frame = () => {+ let current;+ try { current = sample(); } catch (error) { clearTimeout(timer); reject(error); return; }+ const signature = current ? JSON.stringify(current) : '';+ unchanged = signature && signature === previous ? unchanged + 1 : 0;+ previous = signature;+ if (unchanged >= 2) { clearTimeout(timer); resolve(current.targets); return; }+ frameId = requestAnimationFrame(frame);+ };+ frameId = requestAnimationFrame(frame);+ });+ })()`);+ assert.ok(Array.isArray(result) && result.length > 0, `shared wait finds a rendered target: ${find}`);+ return result;+}++/**+ * Press an uncovered, stable target through real Chrome input. A pointer move can change hover layout,+ * so wait again after it and refuse a changed point rather than retrying the action at another point.+ */+export async function press(chrome, find, { native = true } = {}) {+ await waitForStableBoxes(chrome, find);+ if (!native) return rawChromeEvaluation(chrome, `(${find}).click()`);+ await rawChromeEvaluation(chrome, `(${find}).scrollIntoView({ block: 'center', behavior: 'instant' })`);+ await waitForStableBoxes(chrome, find);+ const pointExpression = `(() => {+ const element = (${find}), rect = element.getBoundingClientRect(), x = rect.x + rect.width / 2, y = rect.y + rect.height / 2;+ const hit = document.elementFromPoint(x, y);+ if (!rect.width || !rect.height || !hit || (hit !== element && !element.contains(hit))) throw Error('shared press: target is hidden or covered: ' + ${JSON.stringify(find)});+ return { x, y, width: rect.width, height: rect.height, scrollX, scrollY };+ })()`;+ const point = await rawChromeEvaluation(chrome, pointExpression);+ const raw = clients.get(chrome);+ await raw.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: point.x, y: point.y });+ await waitForStableBoxes(chrome, find);+ const underPointer = await rawChromeEvaluation(chrome, pointExpression);+ assert.deepEqual(underPointer, point, `shared press: target stays under the pointer: ${find}`);+ await rawChromeEvaluation(chrome, `(() => {+ const element = (${find});+ const name = node => node ? node.tagName.toLowerCase() + (node.id ? '#' + node.id : '') + (typeof node.className === 'string' && node.className ? '.' + node.className.trim().split(/\\s+/).join('.') : '') : 'nothing';+ window.__pressed = { meant: name(element), at: ${Math.round(point.y)}, scrollY: Math.round(scrollY) };+ document.addEventListener('mousedown', event => Object.assign(window.__pressed, { landed: name(event.target), landedAt: Math.round(event.clientY), scrolledTo: Math.round(scrollY) }), { capture: true, once: true });+ })()`);+ await raw.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 });+ await raw.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 });+}++/**+ * Expose only waited page expressions. Every media override retains reduced motion, including the external+ * relay browser's pages. Polling observes readiness; it never retries a click or reruns an assertion.+ */+export async function stableChrome(raw) {+ const { evaluate: unusedEvaluate, waitFor: unusedWait, ...chrome } = raw;+ clients.set(chrome, raw);+ /** Send non-measuring protocol commands and retain reduced motion across colour-scheme changes. */+ chrome.send = async (method, params = {}) => {+ if (/^(?:Runtime\.(?:evaluate|callFunctionOn)|DOM\.(?:getBoxModel|getContentQuads)|Page\.getLayoutMetrics|Input\.dispatch(?:Mouse|Touch)Event)$/.test(method)) {+ throw new Error(`Use the shared stable wait or press instead of ${method}`);+ }+ if (method === 'Emulation.setEmulatedMedia') params = { ...params, features: [+ ...(params.features ?? []).filter(feature => feature.name !== 'prefers-reduced-motion'),+ { name: 'prefers-reduced-motion', value: 'reduce' },+ ] };+ return raw.send(method, params);+ };+ /** Deliver a DOM click only after its actual target has a stable, nonzero box. */+ chrome.click = find => press(chrome, find, { native: false });+ /** Run one expression after the visible page and its explicit targets have stopped moving. */+ chrome.stable = async (expression, find = 'document.documentElement') => {+ await waitForStableBoxes(chrome, find);+ return rawChromeEvaluation(chrome, expression);+ };+ /** Poll readiness through the same measurement boundary, with the last page error on a bounded failure. */+ chrome.waitFor = async (expression, timeoutMs = 10_000) => {+ // budget: a bounded readiness wait fails a missing page, not a rendering speed requirement.+ const deadline = Date.now() + timeoutMs;+ let lastError = '';+ while (Date.now() < deadline) {+ try {+ if (await chrome.stable(expression)) return;+ } catch (error) { lastError = error.message; }+ await new Promise(resolve => setTimeout(resolve, 50));+ }+ throw new Error(`Browser condition did not arrive: ${expression}${lastError ? `; it last threw: ${lastError}` : ''}`);+ };+ await chrome.send('Emulation.setEmulatedMedia', { features: [] });+ return chrome;+}++/** Assert the stress run delayed the real first board-state fetch, rather than merely delaying a test. */+export async function assertFirstStateDelay(chrome, t) {+ const expected = Number(process.env.PULLBOARD_CHROME_FIRST_STATE_DELAY_MS ?? 0);+ if (!Number.isSafeInteger(expected) || expected <= 0 || expected > 30_000) return;+ await chrome.waitFor('window.__pullboardFirstStateDelay?.ended !== null && !!window.__pullboardFirstStateDelay');+ const elapsed = await chrome.stable('window.__pullboardFirstStateDelay.ended - window.__pullboardFirstStateDelay.started');+ t.diagnostic(`first board-state request delayed ${Math.round(elapsed)}ms (requested ${expected}ms)`);+ // budget: declared first-state fetch delay is the opt-in stress input, not an operation speed limit.+ assert.ok(elapsed >= expected, `first board-state request waits at least ${expected}ms: ${elapsed}`);+}diff --git a/test/cockpit/stats.test.js b/test/cockpit/stats.test.jsindex 8b5efb18..e4f35597 100644--- a/test/cockpit/stats.test.js+++ b/test/cockpit/stats.test.js@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';import * as store from '../../src/board.js';-import { SPEC, machine, project, build, sendBack, startView, accept, boardOf, earlier, proofShot, chromeExecutable, openSnapshotChrome, closeSnapshotChrome } from './fixture.js';+import { SPEC, machine, project, build, sendBack, startView, accept, boardOf, earlier, proofShot, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, pickProject } from './fixture.js';/** Add a real joined worktree to the shared test board.* @param {ReturnType<typeof machine>} box@@ -48,14 +48,14 @@ test('[V2,N26] real Chrome shows matching proof stats at phone width and clearstry {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor("!!data?.project?.proofStats && document.querySelector('#proof-stats [data-stat=\"submissions\"]')");- await chrome.evaluate(`document.querySelector('[data-root=${JSON.stringify(alpha.repo)}]').click()`);+ await pickProject(chrome, `document.querySelector('[data-root=${JSON.stringify(alpha.repo)}]')`);await chrome.waitFor(`data?.project?.root === ${JSON.stringify(alpha.repo)} && !!document.querySelector('#proof-stats [data-stat="submissions"]')`);const keys = ['submissions', 'rejections', 'rejectionShare', 'merged', 'mergedWithoutAccept', 'agentCount', 'familyCount', 'firstEventAt', 'lastEventAt'];const expectedValues = Object.fromEntries(keys.map((key) => [key, key === 'rejectionShare' ? `${(expected[key] * 100).toFixed(1)}%` : String(expected[key] ?? '')]));for (const scheme of ['light', 'dark']) for (const width of [375, 1280]) {await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });- const actual = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ const actual = JSON.parse(await chrome.stable(`JSON.stringify((() => {const card = document.querySelector('#proof-stats'), rect = card.getBoundingClientRect();const grid = getComputedStyle(card.querySelector('.proof-stats-grid'));return { hidden:card.hidden || !!card.closest('[hidden]'), display:getComputedStyle(card).display,@@ -69,16 +69,16 @@ test('[V2,N26] real Chrome shows matching proof stats at phone width and clearsassert.ok(actual.width > 0 && actual.height > 0 && actual.right <= actual.viewport + 1, `${width}: card has visible bounds inside the viewport`);assert.equal(actual.columns, width < 480 ? 2 : 4, `${width}: compact stats grid adapts to the viewport`);assert.deepEqual(actual.values, expectedValues, `${width}: every visible value matches pullboard stats --json`);- const expectedText = JSON.parse(await chrome.evaluate(`JSON.stringify(Object.fromEntries(${JSON.stringify(keys)}.map(key => {+ const expectedText = JSON.parse(await chrome.stable(`JSON.stringify(Object.fromEntries(${JSON.stringify(keys)}.map(key => {const value = ${JSON.stringify(expected)}[key];const date = key === 'firstEventAt' || key === 'lastEventAt';return [key, date ? (value ? new Date(value).toLocaleDateString([], { year:'numeric', month:'short', day:'numeric' }) : 'none') : ${JSON.stringify(expectedValues)}[key]];})))`));assert.deepEqual(actual.text, expectedText, `${width}: visible text also matches the stats response`);}- await chrome.evaluate(`document.querySelector('[data-root="group:Proof project"]').click()`);+ await pickProject(chrome, `document.querySelector('[data-root="group:Proof project"]')`);await chrome.waitFor("data?.group?.name === 'Proof project' && document.querySelector('#group-view:not([hidden])') && document.querySelector('#proof-stats').hidden");- assert.equal(await chrome.evaluate("document.querySelector('#proof-stats').innerHTML"), '', 'a grouped view cannot retain a prior repo\'s stats');+ assert.equal(await chrome.stable("document.querySelector('#proof-stats').innerHTML"), '', 'a grouped view cannot retain a prior repo\'s stats');const { flow: currentFlow, ...currentTotals } = (await boardOf(view, alpha.repo)).proofStats;const { flow: expectedFlow, ...expectedTotals } = expected;assert.deepEqual(currentTotals, expectedTotals, 'the comparison reads the same live API stats source; queue ages may advance');@@ -120,9 +120,9 @@ test('[V2,N26] stats counts agree in number', { timeout: 90_000 }, async () => {try {chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor("!!data?.project?.proofStats && document.querySelector('#proof-stats .proof-stats-detail')");- await chrome.evaluate(`document.querySelector('[data-root=${JSON.stringify(alpha.repo)}]').click()`);+ await pickProject(chrome, `document.querySelector('[data-root=${JSON.stringify(alpha.repo)}]')`);await chrome.waitFor(`data?.project?.root === ${JSON.stringify(alpha.repo)} && !!document.querySelector('#proof-stats .proof-stats-detail')`);- const detail = await chrome.evaluate("document.querySelector('#proof-stats .proof-stats-detail').textContent");+ const detail = await chrome.stable("document.querySelector('#proof-stats .proof-stats-detail').textContent");assert.match(detail, /solo \(1 agent, 1 move\)/);assert.match(detail, /crew \(3 agents, 14 moves\)/);assert.match(detail, /web-5 \(unknown; 1 move\)/);@@ -182,14 +182,14 @@ test('the stats card shows API flow and bottleneck at 375 and 1280 [N26]', { timassert.equal(api.bottleneck.recommendation, 'review the oldest submission first (#4)');chrome = await openSnapshotChrome(executable, view.link.href, profile);await chrome.waitFor('!!data?.project?.proofStats');- await chrome.evaluate('document.querySelector(' + JSON.stringify('[data-root="' + alpha.repo + '"]') + ').click()');+ await pickProject(chrome, 'document.querySelector(' + JSON.stringify('[data-root="' + alpha.repo + '"]') + ')');await chrome.waitFor('data?.project?.root === ' + JSON.stringify(alpha.repo) + ' && !!document.querySelector("[data-stage=build]")');const backgrounds = {};for (const scheme of ['light', 'dark']) for (const width of [375, 1280]) {await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });await chrome.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });- await chrome.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true))))');- const actual = JSON.parse(await chrome.evaluate(`JSON.stringify((() => {+ await chrome.stable('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true))))');+ const actual = JSON.parse(await chrome.stable(`JSON.stringify((() => {const card=document.querySelector('#proof-stats');const statement=card.querySelector('.proof-stats-bottleneck');const nodes=selector => [...card.querySelectorAll(selector)].map(node => ({ key:node.dataset.stage ?? node.dataset.queue ?? node.dataset.oldest, value:node.dataset.value, text:node.textContent }));@@ -226,9 +226,9 @@ test('the stats card shows API flow and bottleneck at 375 and 1280 [N26]', { timif (scheme === 'dark') await proofShot(chrome, 'stats-flow', width);}assert.notEqual(backgrounds.light, backgrounds.dark, 'both color themes were rendered');- await chrome.evaluate('document.querySelector(' + JSON.stringify('[data-root="' + empty.repo + '"]') + ').click()');+ await pickProject(chrome, 'document.querySelector(' + JSON.stringify('[data-root="' + empty.repo + '"]') + ')');await chrome.waitFor('data?.project?.root === ' + JSON.stringify(empty.repo));- const blank = JSON.parse(await chrome.evaluate(`JSON.stringify({ stages:[...document.querySelectorAll('[data-stage]')].map(node => node.textContent), oldest:[...document.querySelectorAll('[data-oldest]')].map(node => node.textContent), action:document.querySelector('[data-flow=recommendation]')?.textContent ?? null, message:document.querySelector('[data-flow=bottleneck]')?.textContent, api:data.project.proofStats.flow })`));+ const blank = JSON.parse(await chrome.stable(`JSON.stringify({ stages:[...document.querySelectorAll('[data-stage]')].map(node => node.textContent), oldest:[...document.querySelectorAll('[data-oldest]')].map(node => node.textContent), action:document.querySelector('[data-flow=recommendation]')?.textContent ?? null, message:document.querySelector('[data-flow=bottleneck]')?.textContent, api:data.project.proofStats.flow })`));assert.deepEqual(blank.stages, Array(4).fill('unmeasured'), 'missing measurements are not invented zeroes');assert.deepEqual(blank.oldest, Array(4).fill('Oldest: none'));assert.equal(blank.action, null, 'no action is invented without an API recommendation');