Merge: runs multi-select, delete and size sort
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { once } from 'node:events';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
import { startFixture } from './runs_probe_server.mjs';
|
||||
|
||||
// Browser evidence for the Runs list's multi-select, delete and size sort.
|
||||
//
|
||||
// The normal app composition (`flutter build web`) talks to the isolated
|
||||
// loopback fixture in runs_probe_server.mjs, which implements `delete_runs`
|
||||
// and broadcasts `runs_removed`. Run from app/:
|
||||
// flutter build web
|
||||
// node tool/runs_delete_probe.mjs build/web /tmp/runs-delete-evidence
|
||||
const root = resolve(process.argv[2] ?? 'build/web');
|
||||
const output = resolve(process.argv[3] ?? process.env.OPENCODE_ARTIFACT_DIR ?? 'build/runs-delete-evidence');
|
||||
await mkdir(output, { recursive: true });
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
const stamp = (daysAgo, hour) => {
|
||||
const now = new Date();
|
||||
return new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysAgo, hour).toISOString();
|
||||
};
|
||||
const run = (id, title, status, daysAgo, hour, size, extra = {}) => ({
|
||||
id, title, name: 'nightly-report', pipeline_id: 10, status,
|
||||
executing: ['running', 'queued'].includes(status),
|
||||
created_at: stamp(daysAgo, hour),
|
||||
finished_at: ['running', 'queued', 'waiting'].includes(status) ? undefined : stamp(daysAgo, hour + 1),
|
||||
...(size == null ? {} : { size_bytes: size }),
|
||||
...extra,
|
||||
});
|
||||
const runs = [
|
||||
run(31, 'Index rebuild', 'running', 0, 0, null),
|
||||
run(32, 'Model sweep', 'succeeded', 0, 0, Math.round(1.2 * 1024 * MB)),
|
||||
run(33, 'Docs refresh', 'failed', 0, 0, 340 * MB),
|
||||
run(34, 'Waiting review', 'waiting', 0, 0, 12 * MB),
|
||||
run(21, 'Screenshot capture', 'succeeded', 1, 9, 2600 * MB),
|
||||
run(22, 'Old import', 'canceled', 1, 8, null),
|
||||
run(11, 'Weekly digest', 'succeeded', 3, 10, 48 * MB),
|
||||
];
|
||||
|
||||
const fixture = await startFixture({ root, runs });
|
||||
const profile = await mkdtemp(join(tmpdir(), 'runs-delete-chrome-'));
|
||||
const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [
|
||||
'--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu',
|
||||
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank',
|
||||
], { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
let stderr = '';
|
||||
chrome.stderr.on('data', (data) => { stderr += data; });
|
||||
|
||||
const waitFor = async (fn, label, attempts = 150) => {
|
||||
for (let i = 0; i < attempts; i++) {
|
||||
const value = await fn();
|
||||
if (value) return value;
|
||||
await delay(100);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${label}`);
|
||||
};
|
||||
|
||||
let ws;
|
||||
const captures = [];
|
||||
const pageErrors = [];
|
||||
try {
|
||||
const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], 'Chrome DevTools');
|
||||
ws = new WebSocket(endpoint);
|
||||
await once(ws, 'open');
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.method === 'Runtime.exceptionThrown') {
|
||||
pageErrors.push(JSON.stringify(message.params?.exceptionDetails?.text));
|
||||
}
|
||||
if (message.id && pending.has(message.id)) {
|
||||
pending.get(message.id)(message);
|
||||
pending.delete(message.id);
|
||||
}
|
||||
});
|
||||
const send = (method, params = {}, sessionId) => new Promise((resolveCall) => {
|
||||
const callId = ++id;
|
||||
pending.set(callId, resolveCall);
|
||||
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
|
||||
});
|
||||
const target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId;
|
||||
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId;
|
||||
await send('Page.enable', {}, session);
|
||||
await send('Runtime.enable', {}, session);
|
||||
const evaluate = async (expression) => {
|
||||
const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session);
|
||||
if (response.result?.exceptionDetails) throw new Error(JSON.stringify(response.result.exceptionDetails));
|
||||
return response.result?.result?.value;
|
||||
};
|
||||
const labels = () => evaluate(`[...document.querySelectorAll('flt-semantics')]
|
||||
.map((el) => (el.getAttribute('aria-label') || (!el.children.length && el.innerText) || '').trim())
|
||||
.filter(Boolean)`);
|
||||
const expectText = async (text) => {
|
||||
try {
|
||||
await waitFor(async () => (await labels()).some((label) => label.includes(text)), JSON.stringify(text));
|
||||
} catch (error) {
|
||||
throw new Error(`${error.message}\nLabels: ${JSON.stringify(await labels())}`);
|
||||
}
|
||||
};
|
||||
const expectAbsent = async (text) => {
|
||||
await delay(400);
|
||||
if ((await labels()).some((label) => label.includes(text))) {
|
||||
throw new Error(`Unexpected ${JSON.stringify(text)}: ${JSON.stringify(await labels())}`);
|
||||
}
|
||||
};
|
||||
const click = async (text, { exact = true } = {}) => {
|
||||
let clicked = false;
|
||||
for (let attempt = 0; attempt < 30 && !clicked; attempt++) {
|
||||
if (attempt) await delay(200);
|
||||
clicked = await tryClick(text, exact);
|
||||
}
|
||||
if (!clicked) await capture(`failed-click`);
|
||||
if (!clicked) throw new Error(`Could not click ${JSON.stringify(text)}: ${JSON.stringify(await labels())}`);
|
||||
await delay(500);
|
||||
};
|
||||
const tryClick = async (text, exact) => {
|
||||
return evaluate(`(() => {
|
||||
const wanted = ${JSON.stringify(text)};
|
||||
const nodes = [...document.querySelectorAll('flt-semantics')].filter((el) => {
|
||||
const label = (el.getAttribute('aria-label') || el.innerText || '').trim();
|
||||
return ${exact} ? label === wanted : label.includes(wanted);
|
||||
});
|
||||
const target = nodes.find((el) => ['button', 'checkbox', 'menuitem', 'tab'].includes(el.getAttribute('role'))) ?? nodes[0];
|
||||
if (!target) return false;
|
||||
target.click();
|
||||
return true;
|
||||
})()`);
|
||||
};
|
||||
const capture = async (name) => {
|
||||
await delay(500);
|
||||
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
|
||||
const path = join(output, `${name}.png`);
|
||||
await writeFile(path, Buffer.from(data, 'base64'));
|
||||
captures.push(path);
|
||||
};
|
||||
// Dialog and bar text is canvas-rendered; OCR reads it from the capture.
|
||||
const expectOcr = async (texts) => {
|
||||
const path = captures[captures.length - 1];
|
||||
// Piped through stdin: some sandboxes deny tesseract direct file reads.
|
||||
const ocr = promisify(execFile)('tesseract', ['stdin', 'stdout']);
|
||||
ocr.child.stdin.end(await readFile(path));
|
||||
const { stdout } = await ocr;
|
||||
const read = stdout.replace(/\s+/g, ' ');
|
||||
for (const text of texts) {
|
||||
if (!read.includes(text)) throw new Error(`OCR of ${path} lacks ${JSON.stringify(text)}:\n${read}`);
|
||||
}
|
||||
};
|
||||
const setSize = async (width, height) => {
|
||||
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session);
|
||||
await delay(600);
|
||||
};
|
||||
|
||||
await setSize(560, 900);
|
||||
await send('Page.navigate', { url: `${fixture.url}/runs` }, session);
|
||||
await waitFor(() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), 'semantics placeholder');
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await expectText('Model sweep');
|
||||
await expectText('1.2 GB');
|
||||
await expectText('340 MB');
|
||||
|
||||
// 560 wide: select mode with Today selected, then the confirmation (kept).
|
||||
await click('Select');
|
||||
// The bar title (`N selected`) is canvas text; the Delete label carries N.
|
||||
await expectText('Delete selected runs');
|
||||
await click('Select all Today');
|
||||
await expectText('Delete 2 selected runs');
|
||||
await capture('runs-select-day-560');
|
||||
await expectOcr(['2 selected', 'Deselect all']);
|
||||
await click('Delete 2 selected runs');
|
||||
await expectText('Cancel');
|
||||
await capture('runs-confirm-560');
|
||||
await expectOcr(['Delete 2 runs?', 'frees about 1.5 GB', 'undone']);
|
||||
await click('Cancel');
|
||||
await expectAbsent('Cancel');
|
||||
if (fixture.deleteRequests.length) throw new Error('Cancel sent a delete');
|
||||
await click('Done');
|
||||
|
||||
await click('Sort runs: Newest first', { exact: false });
|
||||
await click('Largest first');
|
||||
await expectText('Screenshot capture');
|
||||
await capture('runs-largest-560');
|
||||
await expectAbsent('Select all Today');
|
||||
await click('Sort runs: Largest first', { exact: false });
|
||||
await click('Newest first');
|
||||
|
||||
// 1100 wide: the same with an open detail, then a confirmed delete.
|
||||
await setSize(1100, 800);
|
||||
await click('Docs refresh', { exact: false });
|
||||
await expectText('Summary');
|
||||
await click('Select');
|
||||
await click('Select all Today');
|
||||
await expectText('Delete 2 selected runs');
|
||||
await capture('runs-select-day-1100');
|
||||
await expectOcr(['2 selected']);
|
||||
await click('Delete 2 selected runs');
|
||||
await expectText('Cancel');
|
||||
// Checked by eye: OCR misses the dialog over the dimmed two-pane page.
|
||||
await capture('runs-confirm-1100');
|
||||
await click('Delete');
|
||||
await expectText('Dismiss');
|
||||
await expectAbsent('Docs refresh');
|
||||
await capture('runs-deleted-1100');
|
||||
await expectOcr(['Deleted 2 runs, freed 1.5 GB.']);
|
||||
const sent = fixture.deleteRequests;
|
||||
if (sent.length !== 1 || JSON.stringify(sent[0].run_ids) !== '[32,33]') {
|
||||
throw new Error(`Unexpected delete_runs: ${JSON.stringify(sent)}`);
|
||||
}
|
||||
await click('Sort runs: Newest first', { exact: false });
|
||||
await click('Largest first');
|
||||
await capture('runs-largest-1100');
|
||||
|
||||
if (pageErrors.length) throw new Error(`Page exceptions: ${pageErrors.join('\n')}`);
|
||||
const manifest = { fixture: 'tool/runs_probe_server.mjs', deleteRequests: sent, captures };
|
||||
await writeFile(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2));
|
||||
console.log(JSON.stringify(manifest, null, 2));
|
||||
} finally {
|
||||
ws?.close();
|
||||
chrome.kill('SIGTERM');
|
||||
await Promise.race([once(chrome, 'exit'), delay(3000)]);
|
||||
await fixture.close();
|
||||
// Chrome may still be flushing its profile; a leftover temp dir is harmless.
|
||||
await rm(profile, { recursive: true, force: true, maxRetries: 5 }).catch(() => {});
|
||||
}
|
||||
@@ -322,6 +322,10 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c
|
||||
let getRun = 0;
|
||||
const canceled = new Set();
|
||||
const cancelRequests = [];
|
||||
// `delete_runs` removes finished runs from later `list_runs` replies and
|
||||
// broadcasts `runs_removed`, as the server's contract describes.
|
||||
const deleted = new Set();
|
||||
const deleteRequests = [];
|
||||
let decisionAccepted = false;
|
||||
const decisionRequests = [];
|
||||
let chatSubscribed = 0;
|
||||
@@ -478,7 +482,7 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c
|
||||
}
|
||||
if (request.type === 'list_runs') {
|
||||
listRuns++;
|
||||
client.send({ id: request.id, type: 'runs', runs: runs.map((run) =>
|
||||
client.send({ id: request.id, type: 'runs', runs: runs.filter((run) => !deleted.has(run.id)).map((run) =>
|
||||
canceled.has(run.id) ? { ...run, status: 'canceled', executing: false }
|
||||
: run.id === 5 && decisionAccepted ? { ...run, status: 'succeeded' } : run), usage: null });
|
||||
return;
|
||||
@@ -510,6 +514,30 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c
|
||||
? humanDetail(decisionAccepted, runs) : detail(id, live, canceled.has(id), runs) });
|
||||
return;
|
||||
}
|
||||
if (request.type === 'delete_runs') {
|
||||
const ids = Array.isArray(request.run_ids) ? request.run_ids : [];
|
||||
deleteRequests.push({ run_ids: ids });
|
||||
const done = [];
|
||||
const refused = [];
|
||||
let freed = 0;
|
||||
for (const id of ids) {
|
||||
const run = runs.find((item) => item.id === id);
|
||||
if (!run || deleted.has(id)) {
|
||||
refused.push({ run_id: id, reason: 'run not found' });
|
||||
} else if (run.executing || ['running', 'waiting', 'queued', 'pending'].includes(run.status)) {
|
||||
refused.push({ run_id: id, reason: 'run is still active' });
|
||||
} else {
|
||||
deleted.add(id);
|
||||
done.push(id);
|
||||
freed += run.size_bytes ?? 0;
|
||||
}
|
||||
}
|
||||
client.send({ id: request.id, type: 'runs_deleted', runs_deleted: { deleted: done, refused, freed_bytes: freed } });
|
||||
if (done.length) {
|
||||
for (const other of connections) other.send({ type: 'runs_removed', run_ids: done });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (request.type === 'cancel_run' && request.run_id === 4) {
|
||||
cancelRequests.push({ run_id: request.run_id });
|
||||
canceled.add(4);
|
||||
@@ -670,6 +698,9 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c
|
||||
get subscribed() {
|
||||
return subscribed;
|
||||
},
|
||||
get deleteRequests() {
|
||||
return deleteRequests;
|
||||
},
|
||||
close: () =>
|
||||
new Promise((resolveClose) => {
|
||||
for (const connection of connections) connection.close();
|
||||
|
||||
Reference in New Issue
Block a user