Files
pipelines/web/test/run-copy-prompt-browser.mjs
T

210 lines
11 KiB
JavaScript

// Copy-prompt UI regression: real run-detail view with isolated fixture data.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { resolve, extname, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { launchChrome } from "./browser.mjs";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const out = resolve(process.argv[2] ?? "captures-copy-prompt");
await mkdir(out, { recursive: true });
const prompt = "\n Review the recorded prompt.\nKeep every line and both trailing spaces. \n";
const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
${["design/tokens/tokens", "base", "shell", "lists", "run-detail", "dialogs"].map((name) => `<link rel="stylesheet" href="/${name}.css">`).join("")}
<main id="fixture"></main>
<script type="module">
window.fixtureErrors = [];
addEventListener("error", event => fixtureErrors.push(event.message));
import { createRunDetailView } from "/src/views/runDetail.js";
const prompt = ${JSON.stringify(prompt)};
const baseRun = {
id: 73, title: "TITLE MUST NOT BE COPIED", name: "Copy fixture", pipeline_id: 8, version: 2,
status: "succeeded", input: { prompt }, output: { markdown: "OUTPUT MUST NOT BE COPIED" }, steps: [],
};
window.calls = { repo: [], fetch: [], scheduleEditor: [] };
window.clipboardWrites = [];
window.state = {
view: "runs", runDetail: { ...baseRun }, selectedRunId: 73, runTab: "summary",
runSections: new Set(), runStagePane: null, runStageSections: new Set(),
artifactView: "gallery", renameValue: null, url: "",
};
const repo = {
getPipeline: async (id, version) => {
calls.repo.push({ method: "getPipeline", id, version });
return { id, version, graph: { stages: [] } };
},
};
const rt = {
state, repo, modal: { reconcile() {}, stage() {}, closeAll() {} },
views: {
schedules: { openScheduleEditor: value => calls.scheduleEditor.push(value) },
dialogs: { renderConfirmDialog: () => null },
chat: { renderMarkdown: text => document.createTextNode(text) },
},
renderContent: () => paint(), selectRun: async () => {}, pushRoute: () => {},
};
const view = createRunDetailView(rt);
const nativeFetch = window.fetch.bind(window);
window.fetch = (...args) => { calls.fetch.push(String(args[0])); return nativeFetch(...args); };
window.paint = () => document.querySelector("#fixture").replaceChildren(view.renderRunDetail());
window.setClipboard = mode => {
clipboardWrites.length = 0;
if (mode === "missing") {
Object.defineProperty(navigator, "clipboard", { configurable: true, value: undefined });
return;
}
Object.defineProperty(navigator, "clipboard", { configurable: true, value: {
writeText: async text => {
clipboardWrites.push(text);
if (mode === "reject") throw new Error("permission denied");
if (mode === "pending") await new Promise(resolveWrite => { window.finishClipboardWrite = resolveWrite; });
},
}});
};
window.setRunInput = input => { state.runDetail = { ...baseRun, input }; paint(); };
window.basePrompt = prompt;
setClipboard("success");
paint();
</script>`;
const server = createServer(async (request, response) => {
try {
const pathname = new URL(request.url, "http://fixture").pathname;
if (pathname === "/") {
response.setHeader("Content-Type", "text/html");
response.end(html);
return;
}
const file = resolve(root, `.${pathname}`);
if (!file.startsWith(`${root}/`)) throw new Error("outside fixture root");
response.setHeader("Content-Type", extname(file) === ".css" ? "text/css" : "text/javascript");
response.end(await readFile(file));
} catch {
response.writeHead(404);
response.end();
}
});
await new Promise((resolveListen) => server.listen(0, "127.0.0.1", resolveListen));
let browser;
let page;
const measurements = [];
async function capture(name) {
await page.screenshot(resolve(out, `${name}.png`));
}
try {
browser = await launchChrome();
page = await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector(".run-actions .copy-prompt");
for (const width of [390, 420, 1100]) {
await page.resize(width, 844);
await page.evaluate('setRunInput({ prompt: basePrompt }); setClipboard("success")');
await page.waitForSelector('.run-actions .copy-prompt');
const geometry = await page.evaluate(`(() => {
const button = document.querySelector('.copy-prompt');
const rect = button.getBoundingClientRect();
const schedule = document.querySelector('.schedule-run');
return {
width: innerWidth,
button: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
scheduleY: schedule.getBoundingClientRect().y,
statusAfterActions: document.querySelector('.run-actions').lastElementChild === document.querySelector('.run-action-status'),
overflow: document.documentElement.scrollWidth > innerWidth,
buttonLabel: button.getAttribute('aria-label'),
statusRole: document.querySelector('.run-action-status').getAttribute('role'),
statusLive: document.querySelector('.run-action-status').getAttribute('aria-live'),
scheduleText: document.querySelector('.schedule-run')?.textContent,
scheduleTitle: document.querySelector('.schedule-run')?.title,
};
})()`);
measurements.push(geometry);
assert.ok(geometry.button.height >= 44, `${width}px Copy prompt target is at least 44px`);
assert.equal(geometry.overflow, false, `${width}px has no horizontal overflow`);
assert.equal(geometry.buttonLabel, "Copy prompt");
assert.equal(geometry.statusRole, "status");
assert.equal(geometry.statusLive, "polite");
assert.equal(geometry.statusAfterActions, true, "feedback follows the action buttons");
assert.equal(geometry.scheduleText, "Schedule this run");
assert.match(geometry.scheduleTitle, /independent timer/);
// Reach the native button by ordinary Tab navigation and activate with Enter.
await page.evaluate('document.querySelector(".run-detail-title").focus()');
await page.pressKey("Tab");
assert.equal(await page.evaluate('document.activeElement.classList.contains("copy-prompt")'), true);
assert.notEqual(await page.evaluate('getComputedStyle(document.activeElement).outlineStyle'), "none", "keyboard focus has the shared focus ring");
await page.pressKey("Enter");
await page.waitForText("Prompt copied to clipboard.");
assert.equal(await page.evaluate('document.querySelector(".schedule-run").getBoundingClientRect().y'), geometry.scheduleY,
"clipboard feedback does not move Schedule this run");
assert.deepEqual(await page.evaluate("clipboardWrites"), [prompt]);
assert.equal(await page.evaluate('document.querySelector(".run-action-status").dataset.state'), "success");
assert.deepEqual(await page.evaluate("calls.repo"), [], "copying makes no repository/run/schedule calls");
assert.deepEqual(await page.evaluate("calls.fetch"), [], "copying makes no fetch requests");
assert.match(await page.text(), /TITLE MUST NOT BE COPIED/);
assert.equal(await page.evaluate("state.runDetail.output.markdown"), "OUTPUT MUST NOT BE COPIED");
await capture(`copy-prompt-success-${width}`);
}
await page.resize(390, 844);
await page.evaluate('setRunInput({ prompt: basePrompt }); setClipboard("missing")');
await page.click(".copy-prompt");
await page.waitForText("Clipboard is unavailable in this browser.");
assert.equal(await page.evaluate('document.querySelector(".copy-prompt").disabled'), false);
assert.equal(await page.evaluate('document.querySelector(".run-action-status").dataset.state'), "error");
await capture("copy-prompt-clipboard-unavailable-390");
await page.evaluate('setRunInput({ prompt: basePrompt }); setClipboard("reject")');
await page.click(".copy-prompt");
await page.waitForText("Could not copy prompt to clipboard.");
assert.equal(await page.evaluate('document.querySelector(".copy-prompt").disabled'), false);
assert.equal(await page.evaluate('document.querySelector(".run-action-status").dataset.state'), "error");
assert.deepEqual(await page.evaluate("clipboardWrites"), [prompt]);
await capture("copy-prompt-write-rejected-390");
await page.resize(420, 844);
await page.evaluate('setRunInput({ prompt: basePrompt }); setClipboard("pending")');
await page.click(".copy-prompt");
await page.waitForText("Copying prompt…");
assert.equal(await page.evaluate('document.querySelector(".copy-prompt").disabled'), true, "button disables during clipboard write");
await capture("copy-prompt-writing-420");
await page.evaluate("finishClipboardWrite()");
await page.waitForText("Prompt copied to clipboard.");
assert.equal(await page.evaluate('document.querySelector(".copy-prompt").disabled'), false, "button re-enables after clipboard write");
await page.resize(1100, 844);
await page.evaluate('setRunInput({ prompt: "" }); setClipboard("success")');
assert.equal(await page.evaluate('!!document.querySelector(".copy-prompt")'), true, "empty prompt is present");
await page.click(".copy-prompt");
await page.waitForText("Prompt copied to clipboard.");
assert.deepEqual(await page.evaluate("clipboardWrites"), [""], "empty prompt is copied unchanged");
await capture("copy-prompt-empty-1100");
await page.evaluate('setRunInput({}); setClipboard("success")');
assert.equal(await page.evaluate('!!document.querySelector(".copy-prompt")'), false, "absent prompt has no copy control");
await capture("copy-prompt-absent-1100");
assert.deepEqual(await page.evaluate("calls.repo"), [], "copy path made no repository calls");
assert.deepEqual(await page.evaluate("calls.fetch"), [], "copy path made no network requests");
// The pre-existing Schedule this run action still opens its editor through the
// same pinned definition read; this mock never sends a schedule/run request.
await page.evaluate('setRunInput({ prompt: basePrompt })');
await page.click(".schedule-run");
await page.waitForSelector(".copy-prompt");
assert.deepEqual(await page.evaluate("calls.repo"), [{ method: "getPipeline", id: 8, version: 2 }]);
assert.equal(await page.evaluate("calls.scheduleEditor.length"), 1);
assert.deepEqual(await page.evaluate("fixtureErrors"), []);
await writeFile(resolve(out, "geometry.json"), `${JSON.stringify(measurements, null, 2)}\n`);
console.log(`PASS: exact original/empty prompt copies, missing and rejected clipboard feedback, absent prompt, keyboard use, preserved schedule editor and 390/420/1100px geometry. Captures: ${out}`);
} catch (error) {
if (page) {
await page.screenshot(resolve(out, "failure.png"));
console.error(await page.evaluate('JSON.stringify({ errors: fixtureErrors, text: document.body.innerText, writes: clipboardWrites, calls })'));
}
throw error;
} finally {
await browser?.close();
await new Promise((resolveClose) => server.close(resolveClose));
}