Skip to content

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.

test(view): capture movement when browser waits expire [N26,C7]

Corey Olson461c26e06a16
diff --git a/test/cockpit/fixture.js b/test/cockpit/fixture.js
index a4b4a386..423bb8a1 100644
--- a/test/cockpit/fixture.js
+++ b/test/cockpit/fixture.js
@@ -947,12 +947,7 @@ async function pressedInto(chrome, expression, timeoutMs = 10_000) {
/** Wait for a page condition that may span a page load, when the page asked may still be loading. */
async function settled(chrome, expression, timeoutMs = 15_000) {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- 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}`);
+ return chrome.waitFor(expression, timeoutMs);
}
/** A page expression for the Roadmap row showing an id, such as #3 or beacon#1. */
diff --git a/test/cockpit/fixture.test.js b/test/cockpit/fixture.test.js
index 1b64e5ae..1b9f0555 100644
--- a/test/cockpit/fixture.test.js
+++ b/test/cockpit/fixture.test.js
@@ -9,6 +9,7 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { test } from 'node:test';
+import { waitForStableBoxes } from './stable.js';
import { addItem, closeBoard, openBoard } from '../../src/board.js';
import { exportBoard, importBoard } from '../../src/exchange.js';
import { projectState } from '../../src/serve.js';
@@ -482,3 +483,76 @@ test('owned Chrome cleanup waits out a slow exit and still fails a real hang [C7
{ pid: -hung.child.pid, name: 'SIGKILL' },
], 'cleanup tries both signals against only its owned group');
});
+
+
+test('a timed-out wait names what moved [N26,C7]', { timeout: 60_000 }, async () => {
+ const executable = chromeExecutable();
+ assert.ok(executable, 'Chrome is required for the wait capture control');
+ const responses = new Set();
+ const server = createServer((request, response) => {
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ // Keep parsing open so the loading observation is from a real unfinished document.
+ response.write('<!doctype html><html><body class="loading switching" style="height:4000px">'
+ + '<button id="capture-target" style="position:fixed;top:100px;left:20px;width:100px;height:40px">private stand-in text</button>'
+ + '<div id="capture-noise" style="width:20px;height:10px"></div>');
+ responses.add(response);
+ response.once('close', () => responses.delete(response));
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ const profile = mkdtempSync(join(tmpdir(), 'pullboard-wait-capture-'));
+ let chrome;
+ try {
+ chrome = await openSnapshotChrome(executable, `http://127.0.0.1:${server.address().port}`, profile);
+ await chrome.waitFor("!!document.querySelector('#capture-target')");
+ const controls = [
+ ['target', "node.style.width = (100 + step % 2) + 'px'"],
+ ['replacement', "const next = node.cloneNode(true); node.replaceWith(next); node = next"],
+ ['text', "node.textContent = String(step % 2)"],
+ ['scroll', "scrollTo(0, 30 * (step % 2))"],
+ ];
+ for (const [kind, mutate] of controls) {
+ await chrome.stable('window.__captureStep = 0');
+ const find = `(() => {
+ const step = ++window.__captureStep;
+ let node = document.querySelector('#capture-target');
+ document.querySelector('#capture-noise').style.width = (20 + step % 2) + 'px';
+ ${mutate};
+ return node;
+ })()`;
+ let failure;
+ try { await waitForStableBoxes(chrome, find, 1000); } // budget: declared negative-control deadline for a deliberately moving stand-in page.
+ catch (error) { failure = error; }
+ assert.match(failure?.message ?? '', /shared wait: target missing, zero-sized or moving:/);
+ assert.ok(failure.message.includes('; wait capture '), 'timeout includes bounded wait capture');
+ const capture = JSON.parse(failure.message.split('; wait capture ')[1].split('\n')[0]);
+ assert.ok(capture.changes[kind] > 0, `${kind} is measured: ${JSON.stringify(capture)}`);
+ assert.ok(capture.samples.length > 0 && capture.samples.length <= 4, 'only the bounded tail is retained');
+ assert.ok(capture.samples.some(sample => sample.targets?.length), 'the actual target boxes are retained');
+ assert.ok(capture.frames > 0 && capture.maxFrameGapMs >= 0, 'frame count and gap are measured');
+ assert.ok(capture.samples.every(sample => sample.sampleMs >= 0), 'each layout sample records its duration');
+ assert.equal(capture.page.readyState, 'loading');
+ assert.equal(capture.page.loading, true);
+ assert.equal(capture.page.switching, true);
+ assert.ok(JSON.stringify(capture).length < 7000, 'the diagnostic is bounded independently of the page contents');
+ assert.ok(!JSON.stringify(capture).includes('private stand-in text'), 'text changes do not copy board contents');
+ if (kind !== 'target') assert.equal(capture.changes.target, 0, 'replacement, text and page scroll are distinct from target box movement');
+ }
+ await assert.rejects(chrome.waitFor('false', 1000), error => { // budget: declared negative-control deadline for a condition that never becomes true.
+ const capture = JSON.parse(error.message.split('; readiness capture ')[1]);
+ assert.ok(capture.polls > 0 && capture.falseResults === capture.polls);
+ assert.ok(capture.lastPollMs >= 0 && capture.maxPollMs >= capture.lastPollMs);
+ assert.equal(capture.lastStable.page.readyState, 'loading');
+ assert.equal(capture.lastStable.page.switching, true);
+ assert.ok(capture.lastStable.samples.length <= 4);
+ return true;
+ });
+ for (const response of responses) response.end('</body></html>');
+ await chrome.waitFor("document.readyState === 'complete'");
+ assert.deepEqual(chrome.exceptions, [], 'capture does not create a page exception');
+ } finally {
+ if (chrome) await closeSnapshotChrome(chrome);
+ server.closeAllConnections();
+ await new Promise(resolve => server.close(resolve));
+ rmSync(profile, { recursive: true, force: true });
+ }
+});
diff --git a/test/cockpit/stable.js b/test/cockpit/stable.js
index 8d51453a..4392dddd 100644
--- a/test/cockpit/stable.js
+++ b/test/cockpit/stable.js
@@ -2,6 +2,7 @@
import assert from 'node:assert/strict';
const clients = new WeakMap();
+const waitCaptures = new WeakMap();
/** Evaluate only inside the shared boundary; tests receive no raw page evaluator. */
async function rawChromeEvaluation(chrome, expression) {
@@ -24,36 +25,94 @@ export async function waitForStableBoxes(chrome, find = 'document.documentElemen
/** 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]; };
let lastSeen = 'no frame sampled';
+ const started = performance.now(), samples = [];
+ let frames = 0, previousAt = started, maxFrameGapMs = 0, priorSample = null;
+ let priorTexts = [], priorScroll = null;
+ const changes = { target: 0, replacement: 0, text: 0, scroll: 0, page: 0 };
+ let requiredNodes = [], pageNodes = [], priorRequired = [], priorPageNodes = [];
+ /** Name only geometry-bearing nodes, without copying page text or private attributes. */
+ const name = element => element ? (element.tagName.toLowerCase() + (element.id ? '#' + element.id : '')).slice(0, 120) : null;
+ /** Capture document readiness without addresses, board contents, or session keys. */
+ const pageState = () => ({ readyState: document.readyState,
+ loading: !!document.body?.classList.contains('loading'), switching: !!document.body?.classList.contains('switching') });
+ /** Return only the bounded tail, counters, and timing observations. */
+ const capture = () => ({ elapsedMs: Math.round(performance.now() - started), frames,
+ maxFrameGapMs: Math.round(maxFrameGapMs), changes, page: pageState(), samples });
+ /** Retain a bounded tail that separates target changes from unrelated page geometry. */
+ const record = (current, frame, sampleStarted) => {
+ const at = performance.now(), gapMs = at - previousAt;
+ if (frame) { frames++; maxFrameGapMs = Math.max(maxFrameGapMs, gapMs); }
+ let pageChange = null;
+ if (current && priorSample) {
+ const before = priorSample.page, after = current.page;
+ let index;
+ for (let i = 0; i < Math.max(before.length, after.length); i++) {
+ const left = before[i], right = after[i];
+ const same = Array.isArray(left) && Array.isArray(right)
+ ? left.length === right.length && left.every((value, n) => value === right[n]) : left === right;
+ if (!same) { index = i; break; }
+ }
+ if (index !== undefined) pageChange = {
+ index, before: before[index] ?? null, after: after[index] ?? null,
+ beforeNode: index >= 5 ? name(priorPageNodes[index - 5]) : null,
+ afterNode: index >= 5 ? name(pageNodes[index - 5]) : null,
+ };
+ }
+ const texts = requiredNodes.slice(0, 4).map(node => node instanceof Element ? node.textContent : null);
+ const targetChanged = current && priorSample ? JSON.stringify(current.targets) !== JSON.stringify(priorSample.targets) : null;
+ const targetReplaced = requiredNodes.some((node, i) => priorRequired[i] && node !== priorRequired[i]);
+ const textChanged = texts.some((text, i) => i < priorTexts.length && text !== priorTexts[i]);
+ const scroll = [scrollX, scrollY], scrolled = !!priorScroll && scroll.some((value, i) => value !== priorScroll[i]);
+ if (targetChanged) changes.target++;
+ if (targetReplaced) changes.replacement++;
+ if (textChanged) changes.text++;
+ if (scrolled) changes.scroll++;
+ if (pageChange) changes.page++;
+ samples.push({ atMs: Math.round(at - started), gapMs: Math.round(gapMs), sampleMs: Math.round(at - sampleStarted), frame,
+ targets: current?.targets.slice(0, 4) ?? null,
+ targetChanged, targetReplaced, textChanged, scrolled, pageChange, scroll, page: pageState(), error: current ? null : lastSeen.slice(0, 300),
+ });
+ if (samples.length > 4) samples.shift();
+ previousAt = at; priorSample = current; priorRequired = requiredNodes; priorPageNodes = pageNodes;
+ priorTexts = texts; priorScroll = scroll;
+ };
/** Capture required targets, descendants and page extents in one layout sample. */
const sample = () => {
+ requiredNodes = []; pageNodes = [];
const required = targets();
+ requiredNodes = required;
lastSeen = required.length ? JSON.stringify(required.map(element => element instanceof Element
? { tag: element.tagName, id: element.id, connected: element.isConnected, hidden: !!element.closest('[hidden]'), box: box(element) }
: { target: String(element) })) : 'no matching target';
if (!required.length || !required.every(element => element instanceof Element && element.isConnected && visible(element))) return null;
const elements = [...document.querySelectorAll('body, body *')].filter(visible);
+ pageNodes = elements;
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)} + '; last saw ' + lastSeen)); }, ${timeoutMs});
+ const timer = setTimeout(() => { cancelAnimationFrame(frameId); reject(Error('shared wait: target missing, zero-sized or moving: ' + ${JSON.stringify(find)} + '; last saw ' + lastSeen + '; wait capture ' + JSON.stringify(capture()))); }, ${timeoutMs});
/** Resolve only after two complete frame intervals have unchanged nonzero geometry. */
const frame = () => {
+ const sampleStarted = performance.now();
let current;
try { current = sample(); } catch (error) { current = null; lastSeen = error.name + ': ' + error.message; }
+ record(current, true, sampleStarted);
const signature = current ? JSON.stringify(current) : '';
unchanged = signature && signature === previous ? unchanged + 1 : 0;
previous = signature;
- if (unchanged >= 2) { clearTimeout(timer); resolve(current.targets); return; }
+ if (unchanged >= 2) { clearTimeout(timer); resolve({ targets: current.targets, capture: capture() }); return; }
frameId = requestAnimationFrame(frame);
};
// Sample synchronously before yielding so even an expired short timer has a real diagnostic.
- try { sample(); } catch (error) { lastSeen = error.name + ': ' + error.message; }
+ const sampleStarted = performance.now();
+ try { record(sample(), false, sampleStarted); } catch (error) { lastSeen = error.name + ': ' + error.message; record(null, false, sampleStarted); }
frameId = requestAnimationFrame(frame);
});
})()`);
- assert.ok(Array.isArray(result) && result.length > 0, `shared wait finds a rendered target: ${find}`);
- return result;
+ waitCaptures.set(chrome, { observedAt: Date.now(), ...result.capture });
+ assert.ok(Array.isArray(result.targets) && result.targets.length > 0, `shared wait finds a rendered target: ${find}`);
+ return result.targets;
}
/**
@@ -140,15 +199,20 @@ export async function stableChrome(raw) {
/** 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 = '';
+ const started = Date.now(), deadline = started + timeoutMs;
+ let lastError = '', polls = 0, falseResults = 0, lastPollMs = 0, maxPollMs = 0;
while (Date.now() < deadline) {
+ const pollStarted = Date.now();
+ polls++;
try {
if (await chrome.stable(expression)) return;
+ falseResults++;
} catch (error) { lastError = error.message; }
+ lastPollMs = Date.now() - pollStarted;
+ maxPollMs = Math.max(maxPollMs, lastPollMs);
await new Promise(resolve => setTimeout(resolve, 50));
}
- throw new Error(`Browser condition did not arrive: ${expression}${lastError ? `; it last threw: ${lastError}` : ''}`);
+ throw new Error(`Browser condition did not arrive: ${expression}${lastError ? `; it last threw: ${lastError}` : ''}; readiness capture ${JSON.stringify({ elapsedMs: Date.now() - started, polls, falseResults, lastPollMs, maxPollMs, lastStable: waitCaptures.get(chrome) ?? null })}`);
};
await chrome.send('Emulation.setEmulatedMedia', { features: [] });
return chrome;