chore: remove the JavaScript web client and the Kotlin Android app; the Flutter app replaces both

This commit is contained in:
2026-10-23 21:46:58 +01:00
parent 7958d1830e
commit 8527506da1
373 changed files with 105 additions and 107868 deletions
-260
View File
@@ -1,260 +0,0 @@
// Pure unit tests for the run-level action helpers (R11–R14): the pending human
// decision extracted from a waiting step (with the pinned-graph fallback), the
// option/target wording, the cancel/retry eligibility, the deliberate-confirm
// draft rule and the verbatim Android copy. No server, no DOM.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
ACTION_FAILED_OK,
ACTION_FAILED_TITLE,
CANCEL_CONFIRM,
CANCEL_DIALOG_MESSAGE,
DECISION_ACTION,
DECISION_CANCEL,
DECISION_CARD_TITLE,
DECISION_CONFIRM,
DECISION_SENDING,
DISMISS_KEEP,
DecisionDraft,
FEEDBACK_LABEL,
RESTART_CONFIRM,
RESTART_DIALOG_MESSAGE,
RETRY_CONFIRM,
RETRY_DIALOG_MESSAGE,
canCancel,
canRetry,
cancelDialogTitle,
decisionCardMeta,
decisionSheetMeta,
decisionSheetTitle,
decisionTargetLabel,
humanOptions,
lastWaitingStep,
optionTargetText,
pendingDecision,
retryDialogTitle,
retryModes,
retryRequestKey,
restartDialogTitle,
waitingOptions,
waitingPrompt,
} from "../src/actions.js";
/** A run with the fields pendingDecision reads; overridable per test. */
function run(overrides = {}) {
return {
id: 42,
title: "",
name: "Pipe",
status: "waiting",
current_stage: "review",
executing: false,
steps: [],
...overrides,
};
}
test("lastWaitingStep finds the last waiting step, null when none is waiting", () => {
const steps = [
{ stage: "plan", status: "completed" },
{ stage: "review", status: "waiting" },
{ stage: "review", status: "waiting" },
];
assert.equal(lastWaitingStep(steps)?.stage, "review");
assert.equal(lastWaitingStep(steps), steps[2]);
assert.equal(lastWaitingStep([{ stage: "plan", status: "completed" }]), null);
assert.equal(lastWaitingStep([]), null);
assert.equal(lastWaitingStep(undefined), null);
});
test("waitingPrompt returns the recorded instructions, else empty", () => {
assert.equal(waitingPrompt({ prompt: "Choose a path." }), "Choose a path.");
assert.equal(waitingPrompt({ prompt: 7 }), "");
assert.equal(waitingPrompt({}), "");
assert.equal(waitingPrompt(null), "");
});
test("waitingOptions keeps string entries in recorded order, dropping malformed and blank", () => {
assert.deepEqual(waitingOptions({ options: ["approve", "reject"] }), ["approve", "reject"]);
assert.deepEqual(waitingOptions({ options: ["a", 3, null, " ", "b"] }), ["a", "b"]);
assert.deepEqual(waitingOptions({ options: "approve" }), []);
assert.deepEqual(waitingOptions({}), []);
});
test("humanOptions are a stage's non-error edges, sorted", () => {
assert.deepEqual(humanOptions({ publish: "#success", error: "#failure", revise: "review" }), [
"publish",
"revise",
]);
assert.deepEqual(humanOptions({}), []);
assert.deepEqual(humanOptions(undefined), []);
});
test("decisionTargetLabel resolves declared edges and is blank otherwise", () => {
assert.equal(decisionTargetLabel("publish", "publish"), "publish");
assert.equal(decisionTargetLabel("publish", "#"), "SUCCESS");
assert.equal(decisionTargetLabel("error", "#"), "FAILURE");
assert.equal(decisionTargetLabel("approve", ""), "");
assert.equal(decisionTargetLabel("approve", null), "");
assert.equal(decisionTargetLabel("approve", undefined), "");
assert.equal(optionTargetText("publish"), "→ publish");
assert.equal(optionTargetText(""), "");
assert.equal(optionTargetText(null), "");
});
test("pendingDecision returns null unless the run is waiting", () => {
assert.equal(pendingDecision(null), null);
assert.equal(pendingDecision(run({ status: "failed" })), null);
assert.equal(pendingDecision(run({ status: "running", executing: true })), null);
assert.equal(pendingDecision(run({ status: "succeeded" })), null);
});
test("pendingDecision yields the recorded options in author order and the verbatim prompt", () => {
const decision = pendingDecision(
run({
title: "Review the plan",
current_stage: "review",
steps: [
{ stage: "plan", status: "completed" },
{
stage: "review",
status: "waiting",
output: { prompt: "Ship it or revise it?", options: ["revise", "approve"] },
},
],
graph: {
stages: [
{
key: "review",
prompt: "graph prompt",
edges: { approve: "publish", revise: "review", error: "#failure" },
},
],
},
}),
);
assert.deepEqual(decision.options.map((o) => o.key), ["revise", "approve"]);
assert.equal(decision.instructions, "Ship it or revise it?");
assert.equal(decision.stageKey, "review");
assert.equal(decision.runId, 42);
assert.equal(decision.runLabel, "Review the plan");
assert.deepEqual(decision.options, [
{ key: "revise", target: "review" },
{ key: "approve", target: "publish" },
]);
});
test("pendingDecision falls back to the pinned graph's sorted non-error edges", () => {
const decision = pendingDecision(
run({
current_stage: "review",
steps: [{ stage: "", status: "waiting", output: {} }],
graph: {
stages: [
{ key: "review", prompt: "Graph instructions.", edges: { publish: "#success", error: "#failure", revise: "review" } },
],
},
}),
);
assert.deepEqual(decision.options.map((o) => o.key), ["publish", "revise"]);
assert.equal(decision.instructions, "Graph instructions.");
assert.equal(decision.stageKey, "review");
});
test("pendingDecision keeps a recorded option whose edge is not declared, with a blank target", () => {
const decision = pendingDecision(
run({
steps: [{ stage: "review", status: "waiting", output: { options: ["approve", "legacy"] } }],
graph: { stages: [{ key: "review", edges: { approve: "publish" } }] },
}),
);
assert.deepEqual(decision.options, [
{ key: "approve", target: "publish" },
{ key: "legacy", target: "" },
]);
});
test("pendingDecision is null when no option can be derived", () => {
assert.equal(
pendingDecision(run({ steps: [{ stage: "review", status: "waiting", output: {} }], graph: { stages: [] } })),
null,
);
});
test("DecisionDraft: a blank selection cannot submit and selecting never sends", () => {
const blank = new DecisionDraft();
assert.equal(blank.canSubmit, false);
const selected = blank.select("approve");
assert.equal(selected.canSubmit, true);
assert.equal(selected.selected, "approve");
// Selecting is pure: the original draft is untouched and no side effect fires.
assert.equal(blank.selected, null);
assert.equal(blank.canSubmit, false);
// Feedback is carried verbatim and never changes the submit rule.
const withFeedback = selected.withFeedback(" looks good ");
assert.equal(withFeedback.feedback, " looks good ");
assert.equal(withFeedback.canSubmit, true);
assert.equal(new DecisionDraft(" ").canSubmit, false);
});
test("canCancel is true only while executing; canRetry only for a failed, idle run", () => {
assert.equal(canCancel(run({ executing: true })), true);
assert.equal(canCancel(run({ executing: false })), false);
assert.equal(canCancel(null), false);
assert.equal(canRetry(run({ status: "failed", executing: false })), true);
assert.equal(canRetry(run({ status: "failed", executing: true })), false);
assert.equal(canRetry(run({ status: "succeeded", executing: false })), false);
assert.equal(canRetry(run({ status: "waiting", executing: false })), false);
assert.equal(canRetry(null), false);
assert.equal(canRetry(undefined), false);
});
test("retryModes offers resume and restart for a retryable run, nothing otherwise", () => {
assert.deepEqual(retryModes(run({ status: "failed" })), ["resume", "restart"]);
assert.deepEqual(retryModes(run({ status: "succeeded" })), []);
assert.deepEqual(retryModes(run({ status: "failed", executing: true })), []);
});
test("retryRequestKey is unique, prefixed and within the server's 128-character bound", () => {
const key = retryRequestKey(440, 1_700_000_000_000, () => 0.5);
assert.match(key, /^web-retry-440-1700000000000-/);
assert.ok(key.length <= 128, `key too long: ${key.length}`);
assert.notEqual(
retryRequestKey(440, 1, () => 0.1),
retryRequestKey(440, 1, () => 0.2),
);
});
test("the decision/action copy matches the Android sources verbatim", () => {
assert.equal(DECISION_CARD_TITLE, "Waiting for your decision");
assert.equal(DECISION_ACTION, "Decide");
assert.equal(FEEDBACK_LABEL, "Feedback (optional)");
assert.equal(DECISION_CANCEL, "Cancel");
assert.equal(DECISION_CONFIRM, "Confirm decision");
assert.equal(DECISION_SENDING, "Sending…");
assert.equal(cancelDialogTitle(440), "Cancel run 440?");
assert.equal(CANCEL_DIALOG_MESSAGE, "This asks the server to stop the active run.");
assert.equal(CANCEL_CONFIRM, "Cancel run");
assert.equal(retryDialogTitle(440), "Retry run 440?");
assert.equal(
RETRY_DIALOG_MESSAGE,
"Only failed runs can be retried. The server starts a new run from the same input.",
);
assert.equal(RETRY_CONFIRM, "Retry");
assert.equal(DISMISS_KEEP, "Keep");
assert.equal(RESTART_CONFIRM, "Restart from start");
assert.ok(RESTART_DIALOG_MESSAGE.includes("replays the whole pipeline"));
assert.ok(RESTART_DIALOG_MESSAGE.includes("instead of resuming the failed stage"));
assert.equal(restartDialogTitle(440), "Restart run 440?");
assert.equal(ACTION_FAILED_TITLE, "Action failed");
assert.equal(ACTION_FAILED_OK, "OK");
});
test("the decision card and sheet meta/title render the app's exact shapes", () => {
const decision = { runId: 12, runLabel: "Ship it", stageKey: "review" };
assert.equal(decisionCardMeta(decision), "review · run 12 · Ship it");
assert.equal(decisionSheetTitle(decision.stageKey), "Decide review");
assert.equal(decisionSheetMeta(decision), "run 12 · Ship it");
});
-203
View File
@@ -1,203 +0,0 @@
// Browser-only regression. Real artifact views/helpers, isolated HTTP fixtures;
// Android intents are inspected, never mistaken for a real OS/browser hand-off.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname } from "node:path";
import { launchChrome, eventually } from "./browser.mjs";
const root = resolve(import.meta.dirname, "..");
const out = resolve(process.argv[2] ?? "captures-artifact-browser");
await mkdir(out, { recursive: true });
const artifactPath = "/artifacts/18/1/public/report.html";
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", "chat", "dialogs"].map(n => `<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main id="content" style="padding:16px"><h1>Artifact browser hand-off</h1></main></div>
<script type="module">
import { createModalController } from '/src/modal.js';
import { createRunDetailView } from '/src/views/runDetail.js';
import { createDialogsView } from '/src/views/dialogs.js';
import { createChatView } from '/src/views/chat.js';
import { createSearchView } from '/src/views/search.js';
import { SearchSequencer } from '/src/search.js';
const report={name:'public/report.html',url:'${artifactPath}',content_type:'text/html',size_bytes:70};
const documentFile={name:'public/evidence.md',url:'/artifacts/18/1/public/evidence.md',content_type:'text/markdown',size_bytes:50};
const session={name:'session.html',url:'/artifacts/18/1/session.html',content_type:'text/html',size_bytes:70};
const image={name:'public/pixel.png',url:'/artifacts/18/1/public/pixel.png',content_type:'image/png',size_bytes:68};
const step={stage:'research',sequence:1,status:'completed',outcome:'success',artifacts:[report,documentFile,image,session],session_id:'ses_fixture',session_export:{html:'session.html',messages:2,status:'complete'}};
const state={url:'ws://'+location.host+'/connect',selectedRunId:18,artifactView:'gallery',runDetail:{id:18,steps:[step]}};
window.routes=[];window.handoffs=[];window.copied=[];
window.shared=[];window.shareMode='success';window.fileReadyActivation=true;
Object.defineProperty(navigator,'userActivation',{configurable:true,value:{get isActive(){return fileReadyActivation;}}});
Object.defineProperty(navigator,'canShare',{configurable:true,value:({files})=>files?.length===1&&files[0] instanceof File});
Object.defineProperty(navigator,'share',{configurable:true,value:async data=>{
if(shareMode==='cancel')throw new DOMException('Canceled','AbortError');
if(shareMode==='deny')throw new DOMException('Denied','NotAllowedError');
const f=data.files[0];shared.push({keys:Object.keys(data),name:f.name,type:f.type,bytes:[...new Uint8Array(await f.arrayBuffer())]});
}});
const rt={state,modal:createModalController(),repo:{},views:{},renderContent:()=>{},selectRun:id=>routes.push(id)};
rt.views.chat=createChatView(rt);rt.views.dialogs=createDialogsView(rt);rt.views.runDetail=createRunDetailView(rt);
const host=document.querySelector('#content');
host.append(rt.views.runDetail.renderArtifactGallery([step]),rt.views.runDetail.renderSessionExport(step));
const chat=document.createElement('section');chat.id='chatFixture';chat.append(rt.views.chat.renderMarkdown('[Chat report](${artifactPath})\\n\\n[Unsafe](javascript:alert(1))'));host.append(chat);
history.replaceState({selectedRun:18},'', '/runs/18?pipeline=27');
document.addEventListener('click',e=>{const link=e.target.closest('a');if(link?.href.startsWith('intent:')){e.preventDefault();handoffs.push({href:link.href,target:link.target,rel:link.rel});}},true);
Object.defineProperty(navigator,'clipboard',{configurable:true,value:{writeText:async text=>copied.push(text)}});
window.ready=true;
window.showList=()=>{state.artifactView='list';const list=document.createElement('section');list.id='listFixture';list.append(rt.views.runDetail.renderArtifactGallery([step]));host.append(list);};
window.showVisit=()=>{const visit=document.createElement('section');visit.id='visitFixture';visit.append(rt.views.runDetail.renderVisitArtifacts(step));host.append(visit);};
window.showSearch=()=>{const target=document.createElement('div');document.body.append(target);Object.assign(state,{searchQuery:'',searchKind:'',searchSort:'relevance',searchResults:[],searchSequencer:new SearchSequencer(),searchActiveIndex:0});const search=createSearchView({...rt,searchHost:target,renderHeader:()=>{},repo:{search:async()=>({results:[{kind:'artifact',target:documentFile.url,artifact:{...documentFile,run_id:18,sequence:1}}]})}});search.openSearch();};
</script>`;
const server = createServer(async (req, res) => {
try {
const path = new URL(req.url, "http://fixture").pathname;
if (path === "/" || path.startsWith("/runs/")) {
res.setHeader("Content-Type", "text/html"); res.end(html); return;
}
if (path.startsWith("/artifacts/")) {
if (path.endsWith('.png')) {res.setHeader('Content-Type','image/png');res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=','base64'));return;}
res.setHeader("Content-Type", path.endsWith(".md") ? "text/markdown" : "text/html");
res.setHeader("Content-Security-Policy", "sandbox; default-src 'none'");
res.end(path.endsWith(".md") ? "# Fixture evidence\n\nA document preview remains inside the app." : "<!doctype html><title>Fixture report</title><h1>Fixture report</h1>"); return;
}
const file = resolve(root, `.${path}`);
if (!file.startsWith(root + "/")) throw Error("outside fixture");
res.setHeader("Content-Type", extname(file) === ".css" ? "text/css" : "text/javascript");
res.end(await readFile(file));
} catch { res.writeHead(404); res.end(); }
});
await new Promise(r => server.listen(0, "127.0.0.1", r));
const origin = `http://127.0.0.1:${server.address().port}`;
let browser;
try {
browser = await launchChrome({ width: 390, height: 844 });
const page = await browser.openPage(origin);
await page.waitForSelector(`[data-artifact-name="public/report.html"]`);
const appURL = await page.evaluate("location.href");
const historyLength = await page.evaluate("history.length");
await page.click('[data-artifact-name="public/report.html"]');
await eventually(async () => (await fetch(`http://127.0.0.1:${browser.port}/json/list`).then(r => r.json())).some(target => target.url === origin + artifactPath));
assert.equal(await page.evaluate("location.href"), appURL);
assert.equal(await page.evaluate("history.length"), historyLength);
await page.screenshot(resolve(out, "01-app-preserved-after-browser-open.png"));
const targets=()=>fetch(`http://127.0.0.1:${browser.port}/json/list`).then(r=>r.json());
const targetCount=(await targets()).length;
await page.click('[data-artifact-name="public/pixel.png"]');
await page.waitForSelector('.artifact-viewer');
assert.equal((await targets()).length,targetCount,'image preview must not create a browser tab');
await page.screenshot(resolve(out,'01-image-preview-normal-browser.png'));
await page.pressKey('Escape');
await page.click('[aria-label="Open in browser: public/pixel.png"]');
await eventually(async()=>(await targets()).some(t=>t.url===origin+'/artifacts/18/1/public/pixel.png'));
assert.equal(await page.evaluate('location.href'),appURL);
assert.equal(await page.evaluate("!!document.querySelector('.artifact-viewer')"),false);
const imageShare='[data-artifact-name="public/pixel.png"] + .artifact-actions [aria-label="Share"]';
await page.click(imageShare);
await eventually(()=>page.evaluate('shared.length===1'));
const file=await page.evaluate('shared[0]');
assert.deepEqual(file.keys,['files']);assert.equal(file.name,'pixel.png');assert.equal(file.type,'image/png');
assert.deepEqual(file.bytes,[...Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=','base64')]);
await page.evaluate("shareMode='cancel'");await page.click(imageShare);await page.waitForText('Sharing canceled.');
await page.evaluate("shareMode='deny'");await page.click(imageShare);await page.waitForText('Sharing was blocked.');
await page.screenshot(resolve(out,'06-file-share-blocked-mobile.png'));
await page.evaluate("shareMode='success';fileReadyActivation=false");await page.click(imageShare);await page.waitForText('File ready.');
await page.screenshot(resolve(out,'06-file-ready-retap-mobile.png'));
await page.evaluate('fileReadyActivation=true');await page.click(imageShare);await eventually(()=>page.evaluate('shared.length===2'));
await page.click('[data-artifact-name="public/pixel.png"]');await page.waitForSelector('.artifact-viewer');
await page.click('[data-viewer-focus=share]');await eventually(()=>page.evaluate('shared.length===3'));
assert.deepEqual(await page.evaluate('shared[2]'),file,'viewer shares the same file bytes and metadata');
await page.screenshot(resolve(out,'06-viewer-file-share-mobile.png'));
for (const width of [420,1100]) {
await page.resize(width,844);
assert.equal(await page.evaluate('document.documentElement.scrollWidth<=innerWidth'),true);
await page.screenshot(resolve(out,`06-viewer-file-share-${width}.png`));
}
await page.pressKey('Escape');
await page.evaluate('showList()');await page.click('#listFixture .artifact-list-row:last-child [aria-label=Share]');
await eventually(()=>page.evaluate('shared.length===4'));assert.deepEqual(await page.evaluate('shared[3]'),file);
await page.resize(390,844);
await page.evaluate("Object.defineProperty(navigator,'canShare',{configurable:true,value:undefined});showVisit()");
assert.equal(await page.evaluate("document.querySelector('#visitFixture [aria-label=Share]').disabled"),true);
await page.screenshot(resolve(out,'06-file-sharing-unsupported-mobile.png'));
const android = await browser.openPage("about:blank");
await android.emulateTouch(true);
await android.addInitScript(`(() => {
Object.defineProperty(navigator,'userAgent',{configurable:true,value:'Mozilla/5.0 (Linux; Android 14) Chrome/130 Mobile Safari/537.36'});
const native=window.matchMedia.bind(window);
window.matchMedia=q=>q==='(display-mode: standalone)'?{matches:true}:native(q);
})()`);
await android.goto(origin);
await android.waitForSelector('[data-artifact-name="public/report.html"]');
const original = await android.evaluate("location.href");
await android.click('[data-artifact-name="public/report.html"]');
await android.click('#chatFixture a.md-link');
await android.click('.session-link');
assert.equal(await android.evaluate("handoffs.length"), 3);
assert.equal(await android.evaluate("document.querySelectorAll('a[href^=javascript]').length"), 0);
assert.equal(await android.evaluate("location.href"), original);
await android.click('[data-artifact-name="public/evidence.md"]');
assert.equal(await android.evaluate("handoffs.length"), 4, "Markdown Open must request the browser too");
assert.equal(await android.evaluate("!!document.querySelector('.artifact-viewer')"), false);
await android.click('[data-artifact-name="public/pixel.png"]');
await android.waitForSelector('.artifact-viewer');
assert.equal(await android.evaluate("handoffs.length"), 4, "image clicks preview without external navigation");
await android.screenshot(resolve(out, '03-image-preview-mobile.png'));
await android.pressKey('Escape');
assert.equal(await android.evaluate("document.activeElement.dataset.artifactName"), 'public/pixel.png');
await android.click('[aria-label="Open in browser: public/pixel.png"]');
assert.equal(await android.evaluate("handoffs.length"), 5, "the external icon hands the image to the browser");
assert.equal(await android.evaluate("!!document.querySelector('.artifact-viewer')"), false, "the external action must not also open the viewer");
await android.click('[aria-label="Preview in app: public/evidence.md"]');
await android.waitForSelector('.viewer-markdown');
assert.equal(await android.evaluate("location.href"), original);
const props = await android.evaluate("(() => {const a=document.querySelector('[data-viewer-focus=open]');return {tag:a.tagName,text:a.textContent,href:a.href,target:a.target,rel:a.rel};})()");
assert.equal(props.tag, "A"); assert.equal(props.text, "Open in browser");
assert.match(props.href, /^intent:/); assert.equal(props.target, "_blank"); assert.ok(props.rel.includes("noopener"));
await android.click('[data-viewer-focus=open]');
await android.click('[data-viewer-focus=copy]');
assert.equal(await android.evaluate("handoffs.length"), 6);
assert.equal(await android.evaluate("copied[0]"), origin + "/artifacts/18/1/public/evidence.md");
assert.equal(await android.evaluate("location.href"), original);
for (const width of [390, 420]) {
await android.resize(width,844);
const fits = await android.evaluate("(() => {const p=document.querySelector('.viewer-panel').getBoundingClientRect();return [...document.querySelectorAll('.viewer-action')].every(a=>{const r=a.getBoundingClientRect();return r.left>=p.left && r.right<=p.right;}) && document.documentElement.scrollWidth<=innerWidth;})()");
assert.equal(fits,true,"viewer actions must stay reachable without widening the mobile app");
await android.screenshot(resolve(out, `02-installed-android-browser-action-${width}.png`));
}
await android.pressKey("Escape");
await android.evaluate('showList()');
await android.click('#listFixture .artifact-list-open[aria-label="Open public/evidence.md"]');
assert.equal(await android.evaluate("handoffs.length"), 7);
await android.click('#listFixture .artifact-list-open[aria-label="Open public/pixel.png"]');
await android.waitForSelector('.artifact-viewer');
assert.equal(await android.evaluate("handoffs.length"),7,'image list rows also preview');
await android.screenshot(resolve(out,'04-image-list-preview-mobile.png'));
await android.pressKey('Escape');
await android.click('#listFixture [aria-label="Open in browser: public/pixel.png"]');
assert.equal(await android.evaluate("handoffs.length"),8);
await android.evaluate('showVisit()');
await android.evaluate("document.querySelector('#visitFixture [data-artifact-name=\"public/pixel.png\"]').focus()");
await android.pressKey('Enter');await android.waitForSelector('.artifact-viewer');
assert.equal(await android.evaluate("handoffs.length"),8,'visit image keyboard activation previews without hand-off');
await android.pressKey('Escape');
await android.click('#visitFixture [aria-label="Open in browser: public/pixel.png"]');
assert.equal(await android.evaluate("handoffs.length"),9);
assert.equal(await android.evaluate("!!document.querySelector('[aria-label=\"Preview in app: public/pixel.png\"]')"),false,'images no longer have an eye preview action');
for(const width of [390,420,1100]) {
await android.resize(width,844);
await android.screenshot(resolve(out,`05-image-external-icon-${width}.png`));
assert.equal(await android.evaluate('document.documentElement.scrollWidth<=innerWidth'),true);
}
await android.evaluate('showSearch()');
await android.waitForSelector('#searchInput');await android.fill('#searchInput','evidence');
await android.waitForSelector('.search-row[data-kind=artifact]');await android.click('.search-row[data-kind=artifact]');
assert.equal(await android.evaluate("handoffs.length"), 10, "search results must use the same browser hand-off");
assert.equal(await android.evaluate("location.href"), original);
assert.deepEqual(await android.evaluate("routes"), []);
console.log("PASS: primary image previews, external hand-off, and exact named/typed file-byte sharing from gallery/list/viewer; cancellation, blocked/unsupported sharing and fresh-tap preparation are truthful. Real Chrome uses a stubbed Share API; native OS chooser/delivery and Android OS launch are not tested.");
} finally {
await browser?.close();
await new Promise(r => server.close(r));
}
-63
View File
@@ -1,63 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { artifactBrowserLinkProps, isLocalArtifactLink } from "../src/artifactNavigation.js";
const base = "https://pipelines.test/runs/18";
const environment = (userAgent, mode = "browser") => ({
location: { href: base }, navigator: { userAgent },
matchMedia: (query) => ({ matches: query === `(display-mode: ${mode})` }),
});
test("ordinary browsers and iOS request a separate isolated context", () => {
for (const env of [environment("Desktop Chrome"), environment("Android Chrome"),
{ ...environment("iPhone Safari"), navigator: { userAgent: "iPhone Safari", standalone: true } }]) {
const props = artifactBrowserLinkProps("/artifacts/18/2/public/report.html", env);
assert.equal(props.href, "https://pipelines.test/artifacts/18/2/public/report.html");
assert.equal(props.target, "_blank");
for (const relation of ["external", "noopener", "noreferrer"]) assert.ok(props.rel.includes(relation));
}
});
test("installed Android apps request a browser VIEW hand-off, not a captured app navigation", () => {
for (const mode of ["standalone", "fullscreen"]) {
const props = artifactBrowserLinkProps("/artifacts/18/2/public/report.html?download=0#section", environment("Android Chrome", mode));
assert.match(props.href, /^intent:\/\//);
const marker = props.href.lastIndexOf("#Intent;");
const fields = props.href.slice(marker);
assert.ok(fields.includes("action=android.intent.action.VIEW;"));
assert.ok(fields.includes("category=android.intent.category.BROWSABLE;"));
assert.ok(fields.includes("package=com.android.chrome;"), "do not resolve back into the installed WebAPK");
const original = "https:" + props.href.slice("intent:".length, marker);
assert.equal(original, "https://pipelines.test/artifacts/18/2/public/report.html?download=0#section");
const fallback = fields.match(/S\.browser_fallback_url=([^;]+);/)[1];
assert.equal(decodeURIComponent(fallback), original);
assert.equal(props.target, "_blank");
}
});
test("document fragments cannot inject intent actions or packages", () => {
const props = artifactBrowserLinkProps("/artifacts/a.html#Intent;package=bad.app;action=unsafe;end", environment("Android", "standalone"));
const fields = props.href.slice(props.href.lastIndexOf("#Intent;"));
assert.ok(fields.includes(";package=com.android.chrome;"));
assert.ok(!fields.includes(";package=bad.app;"));
assert.ok(!fields.includes(";action=unsafe;"));
assert.ok(fields.includes(";action=android.intent.action.VIEW;"));
});
test("identified Android browser families do not get sent into the WebAPK", () => {
for (const [agent,pkg] of [["Android EdgA/130","com.microsoft.emmx"],["Android SamsungBrowser/25","com.sec.android.app.sbrowser"],["Android OPR/80","com.opera.browser"],["Android Firefox/130","org.mozilla.firefox"]]) {
const props=artifactBrowserLinkProps("/artifacts/a.html",environment(agent,"standalone"));
assert.ok(props.href.includes(`;package=${pkg};`));
}
});
test("artifact hand-offs reject blank, executable and credential-bearing URLs", () => {
for (const url of [null, "", " ", "javascript:alert(1)", "data:text/html,bad", "file:///secret", "https://user:pass@pipelines.test/artifacts/a"]) {
assert.equal(artifactBrowserLinkProps(url, environment("Android", "standalone")), null);
}
});
test("chat recognizes only genuine same-origin artifact links", () => {
for (const url of ["/artifacts/18/2/public/report.html", "https://pipelines.test/artifacts/a.html"]) assert.equal(isLocalArtifactLink(url, base), true);
for (const url of ["/runs/18", "//evil.test/artifacts/a", "/artifacts/../../admin", "https://pipelines.test.evil/artifacts/a", "javascript:alert(1)"]) assert.equal(isLocalArtifactLink(url, base), false);
});
-68
View File
@@ -1,68 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { canShareFiles, shareArtifactFile } from "../src/artifactSharing.js";
function fixture() {
const calls = [], shares = [];
const env = { File, navigator: { userActivation: { isActive: true }, canShare: () => true,
share: async data => shares.push(data) },
fetch: async (...args) => { calls.push(args); return new Response(new Uint8Array([0, 1, 255, 42]), { headers: { "Content-Type": "image/png" } }); } };
return { env, calls, shares, owner: {} };
}
const url = "https://app.example/artifacts/20/1/public/capture.png";
test("shares exact downloaded bytes as a named typed File, never a URL", async () => {
const { env, calls, shares, owner } = fixture();
assert.equal((await shareArtifactFile(url, { name: "public/capture.png" }, owner, env)).state, "shared");
assert.equal(calls[0][0], url);
assert.deepEqual(calls[0][1], { credentials: "same-origin", redirect: "error" });
assert.deepEqual(Object.keys(shares[0]), ["files"]);
const file = shares[0].files[0];
assert.ok(file instanceof File); assert.equal(file.name, "capture.png"); assert.equal(file.type, "image/png");
assert.deepEqual([...new Uint8Array(await file.arrayBuffer())], [0, 1, 255, 42]);
});
test("unsupported browsers and file types never share links", async () => {
const { env, calls, shares, owner } = fixture();
env.navigator.canShare = undefined; assert.equal(canShareFiles(env), false);
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "error"); assert.equal(calls.length, 0);
env.navigator.canShare = () => false;
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "error"); assert.equal(shares.length, 0);
});
test("a slow fetch prepares for a fresh Share tap without another download", async () => {
const { env, calls, shares, owner } = fixture(); env.navigator.userActivation.isActive = false;
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "ready"); assert.equal(shares.length, 0);
env.navigator.userActivation.isActive = true;
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "shared");
assert.equal(shares.length, 1); assert.equal(calls.length, 1);
});
test("cancel and permission denial are truthful and allow a retry", async () => {
const { env, calls, shares, owner } = fixture();
env.navigator.share = async () => { throw new DOMException("Canceled", "AbortError"); };
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "canceled");
env.navigator.share = async () => { throw new DOMException("Denied", "NotAllowedError"); };
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "ready");
env.navigator.share = async data => shares.push(data);
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "shared"); assert.equal(calls.length, 1);
});
test("fetch/auth errors never invoke Share; navigation away cancels preparation", async () => {
const { env, shares, owner } = fixture();
env.fetch = async () => new Response("Unauthorized", { status: 401 });
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "error");
env.fetch = async () => { throw new TypeError("Failed to fetch"); };
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "error");
env.fetch = async () => new Response("file"); owner.isConnected = false;
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "canceled"); assert.equal(shares.length, 0);
});
test("concurrent clicks do not duplicate a fetch or share", async () => {
const { env, calls, shares, owner } = fixture(); let release;
const fetch = env.fetch;
env.fetch = async (...args) => { await new Promise(resolve => { release = resolve; }); return fetch(...args); };
const first = shareArtifactFile(url, {}, owner, env);
assert.equal((await shareArtifactFile(url, {}, owner, env)).state, "busy");
release(); assert.equal((await first).state, "shared"); assert.equal(calls.length, 1); assert.equal(shares.length, 1);
});
-422
View File
@@ -1,422 +0,0 @@
// Unit tests for the ported artifact derivation, run with `node --test`.
// Mirrors the cases in android/.../test/.../ArtifactGroupsTest.kt and the
// wording/formatting assertions around Format.kt, graph/ArtifactType.kt,
// graph/ArtifactViewer.kt and graph/SessionExport.kt.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
ArtifactKind,
isSystemArtifact,
stageArtifacts,
systemArtifacts,
visitArtifacts,
ARTIFACT_CAPTURE_PENDING,
LEGACY_SESSION_MARKDOWN_ARTIFACT,
artifactCaptureNotes,
artifactGroups,
artifactKind,
artifactKindLabel,
artifactsEmptyMessage,
artifactsHeader,
artifactsSummary,
artifactViewerPositionLabel,
displayVisit,
humanBytes,
isMarkdownArtifact,
isViewerArtifact,
pagedArtifacts,
pagedIndex,
presentedArtifacts,
sessionExportArtifact,
viewerIndexByUrl,
} from "../src/artifacts.js";
/** A minimal StageArtifact, named so tests read like the Android fixtures. */
function art(name, { contentType = "", sizeBytes = 0, url } = {}) {
return { name, content_type: contentType, size_bytes: sizeBytes, url: url ?? `/artifacts/1/1/${name}` };
}
/** A minimal RunStep with a recorded control visit and optional artifacts. */
function step(stage, sequence, { visit = 1, status = "completed", artifacts, skipped, truncated, exportHtml } = {}) {
const s = { stage, sequence, status, control: { visit, max_visits: 3 } };
if (artifacts !== undefined) s.artifacts = artifacts;
if (skipped !== undefined) s.artifacts_skipped = skipped;
if (truncated !== undefined) s.artifacts_truncated = truncated;
if (exportHtml !== undefined) s.session_export = { html: exportHtml };
return s;
}
test("the turn's own files are system evidence, not stage artifacts", () => {
const step = {
artifacts: [
{ name: "input.md", url: "/1" },
{ name: "memory.md", url: "/2" },
{ name: "output.md", url: "/3" },
{ name: "session.html", url: "/4" },
{ name: "public/notes.md", url: "/5" },
{ name: "screenshot.png", url: "/6" },
],
};
assert.deepEqual(
stageArtifacts(step).map((artifact) => artifact.name),
["public/notes.md", "screenshot.png"],
);
assert.deepEqual(
systemArtifacts(step).map((artifact) => artifact.name),
["input.md", "memory.md", "output.md", "session.html"],
);
assert.equal(isSystemArtifact({ name: "output.md" }), true);
assert.equal(isSystemArtifact({ name: "public/input.md" }), false);
});
test("presentedArtifacts hides the retired session.md and keeps everything else", () => {
const artifacts = [art("shot.png"), art(LEGACY_SESSION_MARKDOWN_ARTIFACT), art("session.html")];
const presented = presentedArtifacts({ artifacts });
assert.deepEqual(presented.map((a) => a.name), ["shot.png", "session.html"]);
assert.deepEqual(presentedArtifacts({}), []);
assert.deepEqual(presentedArtifacts({ artifacts: [] }), []);
assert.deepEqual(presentedArtifacts(undefined), []);
});
test("session.md is hidden from every listing: groups, header and summary", () => {
const onlyLegacy = [step("planner", 1, { artifacts: [art(LEGACY_SESSION_MARKDOWN_ARTIFACT)] })];
assert.deepEqual(artifactGroups(onlyLegacy), []);
assert.equal(artifactsHeader(onlyLegacy, false), "No artifacts recorded for this run.");
assert.equal(artifactsSummary(onlyLegacy[0]), "Artifacts · not recorded for this visit");
assert.deepEqual(artifactCaptureNotes(onlyLegacy[0]), []);
});
test("groups interleaved steps by stage then visit: [planner·1, planner·2, build·1]", () => {
const steps = [
step("planner", 1, { visit: 1, artifacts: [art("a.png")] }),
step("build", 2, { visit: 1, artifacts: [art("b.png")] }),
step("planner", 3, { visit: 2, artifacts: [art("c.png")] }),
];
const groups = artifactGroups(steps);
assert.deepEqual(
groups.map((g) => `${g.stageKey}·${g.visit}`),
["planner·1", "planner·2", "build·1"],
);
assert.deepEqual(groups[0].artifacts.map((a) => a.name), ["a.png"]);
});
test("duplicate names are kept, not deduped", () => {
const steps = [
step("planner", 1, {
artifacts: [
art("shot.png", { url: "/artifacts/1/1/shot-a.png" }),
art("shot.png", { url: "/artifacts/1/1/shot-b.png" }),
],
}),
];
const groups = artifactGroups(steps);
assert.equal(groups.length, 1);
assert.equal(groups[0].artifacts.length, 2);
assert.deepEqual(groups[0].artifacts.map((a) => a.url), [
"/artifacts/1/1/shot-a.png",
"/artifacts/1/1/shot-b.png",
]);
});
test("a shared public file is attributed to the visit that first recorded it", () => {
const steps = [
{ sequence: 1, stage: "a", artifacts: [{ name: "input.md" }, { name: "public/a.txt" }] },
{
sequence: 2,
stage: "b",
artifacts: [{ name: "output.md" }, { name: "public/a.txt" }, { name: "public/b.txt" }],
},
];
const groups = artifactGroups(steps);
assert.deepEqual(groups.map((g) => g.artifacts.map((a) => a.name)), [["public/a.txt"], ["public/b.txt"]]);
assert.equal(
visitArtifacts(steps[1], steps).map((a) => a.name).join(","),
"public/b.txt",
);
assert.equal(artifactsHeader(steps, false), "Artifacts · 2 recorded");
});
test("empty/null artifact visits and an empty run produce no group", () => {
assert.deepEqual(artifactGroups([]), []);
assert.deepEqual(artifactGroups(undefined), []);
const steps = [
step("planner", 1, {}), // no artifacts key
step("planner", 2, { artifacts: [] }), // empty capture
step("planner", 3, { artifacts: null }),
step("build", 4, { artifacts: [art("only.png")] }),
];
const groups = artifactGroups(steps);
assert.equal(groups.length, 1);
assert.equal(groups[0].stageKey, "build");
assert.equal(groups[0].visit, 1);
});
test("display visit number is control.visit when positive, else the position + 1", () => {
assert.equal(displayVisit(step("s", 1, { visit: 2 }), 0), 2);
assert.equal(displayVisit(step("s", 1, { visit: 0 }), 0), 1);
assert.equal(displayVisit(step("s", 1, { visit: 0 }), 4), 5);
assert.equal(displayVisit({ stage: "s", sequence: 1 }, 2), 3); // no control at all
const steps = [
step("planner", 1, { visit: 0, artifacts: [art("a")] }),
step("planner", 2, { visit: 0, artifacts: [art("b")] }),
];
assert.deepEqual(artifactGroups(steps).map((g) => g.visit), [1, 2]);
});
test("the run header counts exactly the tiles the gallery yields", () => {
const steps = [
step("planner", 1, { artifacts: [art("a.png"), art(LEGACY_SESSION_MARKDOWN_ARTIFACT)] }),
step("build", 2, { artifacts: [art("b.png"), art("c.png"), art("d.png")] }),
];
const tiles = artifactGroups(steps).reduce((n, g) => n + g.artifacts.length, 0);
assert.equal(tiles, 4);
assert.equal(artifactsHeader(steps, false), `Artifacts · ${tiles} recorded`);
assert.equal(artifactsHeader(steps, false), "Artifacts · 4 recorded");
});
test("the run header is singular for exactly one artifact and flags partial capture", () => {
assert.equal(artifactsHeader([step("s", 1, { artifacts: [art("one.png")] })], false), "Artifact · 1 recorded");
assert.equal(
artifactsHeader([step("s", 1, { artifacts: [art("a.png")], skipped: 2 })], false),
"Artifact · 1 recorded · partial capture",
);
assert.equal(
artifactsHeader([step("s", 1, { artifacts: [art("a.png")], truncated: 5 })], false),
"Artifact · 1 recorded · partial capture",
);
});
test("the run header empty wording matches running vs finished", () => {
assert.equal(artifactsHeader([], true), "Artifacts · capture pending");
assert.equal(artifactsHeader([], false), "No artifacts recorded for this run.");
assert.equal(artifactsEmptyMessage(true), `Artifacts · ${ARTIFACT_CAPTURE_PENDING}`);
assert.equal(artifactsEmptyMessage(false), "No artifacts recorded for this run.");
});
test("the per-visit summary uses the exact recorded/pending/not-recorded wording", () => {
assert.equal(
artifactsSummary(step("s", 1, { status: "completed", artifacts: [art("a"), art("b"), art("c")] })),
"Artifacts · 3 recorded",
);
assert.equal(
artifactsSummary(step("s", 1, { artifacts: [art("a")], truncated: 1 })),
"Artifacts · 1 recorded · partial capture",
);
assert.equal(
artifactsSummary(step("s", 1, { status: "running", artifacts: [] })),
"Artifacts · capture pending",
);
assert.equal(
artifactsSummary(step("s", 1, { status: "completed", artifacts: [] })),
"Artifacts · not recorded for this visit",
);
assert.equal(
artifactsSummary(step("s", 1, { status: "completed" })),
"Artifacts · not recorded for this visit",
);
});
test("capture notes use the exact wording and stay silent on an empty capture", () => {
const full = step("s", 1, { artifacts: [art("a")], skipped: 4, truncated: 7 });
assert.deepEqual(artifactCaptureNotes(full), [
"4 files excluded from artifact capture.",
"7 files omitted by artifact capture limits.",
]);
assert.deepEqual(artifactCaptureNotes(step("s", 1, { artifacts: [art("a")], skipped: 2 })), [
"2 files excluded from artifact capture.",
]);
assert.deepEqual(artifactCaptureNotes(step("s", 1, { artifacts: [art("a")] })), []);
assert.deepEqual(artifactCaptureNotes(step("s", 1, { artifacts: [], skipped: 4 })), []);
});
test("artifactKind classifies images, videos and every file kind", () => {
assert.equal(artifactKind("image/png", "shot.png"), ArtifactKind.Image);
assert.equal(artifactKind("video/mp4", "clip.mp4"), ArtifactKind.Video);
assert.equal(artifactKind("audio/mpeg", "sound.mp3"), ArtifactKind.Audio);
assert.equal(artifactKind("application/pdf", "report"), ArtifactKind.Pdf);
assert.equal(artifactKind("application/octet-stream", "data.pdf"), ArtifactKind.Pdf);
assert.equal(artifactKind("application/json", "payload"), ArtifactKind.Json);
assert.equal(artifactKind("text/plain", "config.json"), ArtifactKind.Json);
assert.equal(artifactKind("application/zip", "bundle"), ArtifactKind.Archive);
assert.equal(artifactKind("text/plain", "backup.tar.gz"), ArtifactKind.Archive);
assert.equal(artifactKind("text/csv", "rows"), ArtifactKind.Spreadsheet);
assert.equal(artifactKind("application/octet-stream", "sheet.xlsx"), ArtifactKind.Spreadsheet);
assert.equal(artifactKind("text/plain", "run.log"), ArtifactKind.Log);
assert.equal(artifactKind("application/xml", "layout"), ArtifactKind.Code);
assert.equal(artifactKind("text/plain", "main.go"), ArtifactKind.Code);
assert.equal(artifactKind("text/html; charset=utf-8", "session.html"), ArtifactKind.Document);
assert.equal(artifactKind("text/plain", "notes.txt"), ArtifactKind.Document);
assert.equal(artifactKind("application/octet-stream", "blob.bin"), ArtifactKind.Other);
assert.equal(artifactKind("", ""), ArtifactKind.Other);
});
test("artifactKindLabel names every kind in prose", () => {
assert.equal(artifactKindLabel(ArtifactKind.Image), "Image");
assert.equal(artifactKindLabel(ArtifactKind.Video), "Video");
assert.equal(artifactKindLabel(ArtifactKind.Audio), "Audio");
assert.equal(artifactKindLabel(ArtifactKind.Pdf), "PDF");
assert.equal(artifactKindLabel(ArtifactKind.Json), "JSON");
assert.equal(artifactKindLabel(ArtifactKind.Archive), "Archive");
assert.equal(artifactKindLabel(ArtifactKind.Spreadsheet), "Spreadsheet");
assert.equal(artifactKindLabel(ArtifactKind.Log), "Log");
assert.equal(artifactKindLabel(ArtifactKind.Code), "Code");
assert.equal(artifactKindLabel(ArtifactKind.Document), "Document");
assert.equal(artifactKindLabel(ArtifactKind.Other), "File");
assert.equal(artifactKindLabel("nonsense"), "File");
});
test("humanBytes matches the app's binary formatting", () => {
assert.equal(humanBytes(0), "0 B");
assert.equal(humanBytes(999), "999 B");
assert.equal(humanBytes(1024), "1.0 KiB");
assert.equal(humanBytes(1536), "1.5 KiB");
assert.equal(humanBytes(2 * 1024 * 1024), "2.0 MiB");
assert.equal(humanBytes(3 * 1024 * 1024 * 1024), "3.0 GiB");
});
test("viewer position label trims the subtype and falls back to 'artifact'", () => {
assert.equal(artifactViewerPositionLabel(0, 3, "image/png"), "1 of 3 · image/png");
assert.equal(artifactViewerPositionLabel(1, 3, "image/png; charset=binary"), "2 of 3 · image/png");
assert.equal(artifactViewerPositionLabel(4, 5, ""), "5 of 5 · artifact");
assert.equal(artifactViewerPositionLabel(0, 1, " "), "1 of 1 · artifact");
});
test("pagedArtifacts keeps only images and videos, in gallery order", () => {
const groups = [
{ stageKey: "reviewer", visit: 3, artifacts: [art("session.html", { contentType: "text/html" })] },
{
stageKey: "ui_reviewer",
visit: 2,
artifacts: [
art("shot.png", { contentType: "image/png" }),
art("shot.png.xml", { contentType: "application/xml" }),
art("clip.mp4", { contentType: "video/mp4" }),
art("second.png", { contentType: "image/png" }),
],
},
];
assert.deepEqual(pagedArtifacts(groups).map((a) => a.name), ["shot.png", "clip.mp4", "second.png"]);
assert.deepEqual(pagedArtifacts([]), []);
});
test("isMarkdownArtifact accepts markdown/text content types and md/txt names", () => {
for (const [contentType, name] of [
["text/markdown", "plan"],
["text/markdown; charset=utf-8", "plan"],
["text/plain", "notes"],
["application/octet-stream", "input.md"],
["", "memory.markdown"],
["", "output.txt"],
["text/html", "report.md"],
["text/plain", "run.log"],
]) {
assert.equal(isMarkdownArtifact(contentType, name), true, `${contentType} ${name}`);
}
for (const [contentType, name] of [
["text/html", "session.html"],
["text/csv", "rows.csv"],
["application/json", "payload.json"],
["text/x-python", "main.py"],
["application/xml", "shot.png.xml"],
["", ""],
[undefined, undefined],
]) {
assert.equal(isMarkdownArtifact(contentType, name), false, `${contentType} ${name}`);
}
});
test("isViewerArtifact includes media and markdown but not code, logs or other files", () => {
for (const [contentType, name] of [
["image/png", "shot.png"],
["video/mp4", "clip.mp4"],
["text/markdown", "input.md"],
["text/plain", "memory.txt"],
["", "output.md"],
]) {
assert.equal(isViewerArtifact(contentType, name), true, `${contentType} ${name}`);
}
for (const [contentType, name] of [
["text/html", "session.html"],
["text/csv", "rows.csv"],
["application/json", "payload.json"],
["text/x-python", "main.py"],
["text/plain", "run.log"],
["application/octet-stream", "blob.bin"],
["", ""],
]) {
assert.equal(isViewerArtifact(contentType, name), false, `${contentType} ${name}`);
}
});
test("pagedArtifacts keeps images, videos and markdown in gallery order", () => {
const groups = [
{ stageKey: "reviewer", visit: 1, artifacts: [art("session.html", { contentType: "text/html" })] },
{
stageKey: "implementer",
visit: 2,
artifacts: [
art("input.md", { contentType: "text/markdown" }),
art("run.log", { contentType: "text/plain" }),
art("shot.png", { contentType: "image/png" }),
art("main.py", { contentType: "text/x-python" }),
art("clip.mp4", { contentType: "video/mp4" }),
art("memory.txt", { contentType: "text/plain" }),
art("rows.csv", { contentType: "text/csv" }),
art("output.md", { contentType: "application/octet-stream" }),
],
},
];
assert.deepEqual(pagedArtifacts(groups).map((a) => a.name), [
"input.md",
"shot.png",
"clip.mp4",
"memory.txt",
"output.md",
]);
});
test("viewerIndexByUrl maps each viewer-selectable url, first occurrence wins", () => {
const groups = [
{
stageKey: "s",
visit: 1,
artifacts: [
art("a.png", { contentType: "image/png", url: "/artifacts/1/1/a.png" }),
art("note.txt", { contentType: "text/plain", url: "/artifacts/1/1/note.txt" }),
art("b.png", { contentType: "image/png", url: "/artifacts/1/1/b.png" }),
art("a.png", { contentType: "image/png", url: "/artifacts/1/1/a.png" }),
art("session.html", { contentType: "text/html", url: "/artifacts/1/1/session.html" }),
],
},
];
const index = viewerIndexByUrl(groups);
assert.equal(index.get("/artifacts/1/1/a.png"), 0);
assert.equal(index.get("/artifacts/1/1/note.txt"), 1);
assert.equal(index.get("/artifacts/1/1/b.png"), 2);
assert.equal(index.has("/artifacts/1/1/session.html"), false);
});
test("pagedIndex clamps at both ends and never wraps", () => {
assert.equal(pagedIndex(0, -1, 3), 0);
assert.equal(pagedIndex(1, -1, 3), 0);
assert.equal(pagedIndex(1, 1, 3), 2);
assert.equal(pagedIndex(2, 1, 3), 2);
assert.equal(pagedIndex(0, 0, 0), 0);
assert.equal(pagedIndex(0, 0, 1), 0);
});
test("sessionExportArtifact matches the export html to a step artifact by name", () => {
const exportStep = step("reviewer", 1, {
artifacts: [art("shot.png"), art("session.html")],
exportHtml: "session.html",
});
assert.equal(sessionExportArtifact(exportStep).name, "session.html");
// No session_export at all.
assert.equal(sessionExportArtifact(step("s", 1, { artifacts: [art("session.html")] })), null);
// Blank html.
assert.equal(sessionExportArtifact(step("s", 1, { artifacts: [art("session.html")], exportHtml: " " })), null);
// Export named but the file is missing from the listing.
assert.equal(sessionExportArtifact(step("s", 1, { artifacts: [art("shot.png")], exportHtml: "session.html" })), null);
assert.equal(sessionExportArtifact(undefined), null);
});
-306
View File
@@ -1,306 +0,0 @@
// Pure unit tests for the attention / "Needs you" model (R15): qualification,
// identity, wording, ordering and tie-breaks, dismissal filtering, the
// Clear-all snapshot semantics and the localStorage encoding. No server, no DOM.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
ATTENTION_STORAGE_KEY,
AttentionKind,
attentionBadgeLabel,
attentionDetail,
attentionDismiss,
attentionDismissAll,
attentionDismissalSnapshot,
attentionEntries,
startOfLocalDay,
attentionKey,
attentionKindOf,
attentionRowDescription,
decodeAttentionDismissals,
encodeAttentionDismissals,
} from "../src/attention.js";
/** A run summary with every field the attention model reads. */
function run(overrides = {}) {
return {
id: 1,
name: "Plan and land",
title: null,
status: "failed",
created_at: "2026-10-19T10:00:00Z",
finished_at: "2026-10-19T10:05:00Z",
diagnostic: "",
...overrides,
};
}
// ---------------------------------------------------------------------------
// Qualification
// ---------------------------------------------------------------------------
test("only waiting and failed qualify; every other status never produces an entry", () => {
assert.equal(attentionKindOf("waiting"), AttentionKind.Decision);
assert.equal(attentionKindOf("failed"), AttentionKind.Failed);
for (const status of [
"queued",
"running",
"succeeded",
"canceled",
"cancelled",
"interrupted",
"active",
"blocked",
"skipped",
"unknown",
"",
" ",
null,
undefined,
"FAILED?",
]) {
assert.equal(attentionKindOf(status), null, `status ${JSON.stringify(status)} should not qualify`);
}
});
test("qualification trims and lowercases the server's own words", () => {
assert.equal(attentionKindOf(" Waiting "), AttentionKind.Decision);
assert.equal(attentionKindOf("Failed\n"), AttentionKind.Failed);
assert.equal(attentionKindOf("WAITING"), AttentionKind.Decision);
});
test("ranks are Decision 0 then Failed 1", () => {
assert.equal(AttentionKind.Decision.rank, 0);
assert.equal(AttentionKind.Failed.rank, 1);
});
// ---------------------------------------------------------------------------
// Identity and wording
// ---------------------------------------------------------------------------
test("identity is exactly {runId}:{kind}", () => {
assert.equal(attentionKey(440, AttentionKind.Failed), "440:Failed");
assert.equal(attentionKey(12, AttentionKind.Decision), "12:Decision");
});
test("detail is the fixed decision line and the trimmed diagnostic else Run failed", () => {
assert.equal(attentionDetail(AttentionKind.Decision, run()), "Waiting for your decision");
assert.equal(
attentionDetail(AttentionKind.Failed, run({ diagnostic: " boom " })),
"boom",
);
assert.equal(attentionDetail(AttentionKind.Failed, run({ diagnostic: " " })), "Run failed");
assert.equal(attentionDetail(AttentionKind.Failed, run({ diagnostic: "" })), "Run failed");
assert.equal(attentionDetail(AttentionKind.Failed, run({ diagnostic: null })), "Run failed");
});
test("label is the trimmed title else the pipeline name", () => {
const [titled] = attentionEntries([run({ title: " My run " })], new Set());
assert.equal(titled.label, "My run");
assert.equal(titled.pipeline, "Plan and land");
const [untitled] = attentionEntries([run({ title: " " })], new Set());
assert.equal(untitled.label, "Plan and land");
const [missing] = attentionEntries([run({ title: null })], new Set());
assert.equal(missing.label, "Plan and land");
});
test("row description is exactly {pipeline} · {detail}", () => {
const [entry] = attentionEntries([run({ title: "T", diagnostic: "failed hard" })], new Set());
assert.equal(attentionRowDescription(entry), "Plan and land · failed hard");
});
test("the surface is today's work: older failures are history", () => {
const entries = [
run({ id: 1, status: "failed", finished_at: "2026-10-19T21:33:27Z" }),
run({ id: 2, status: "failed", finished_at: "2026-10-20T10:00:00Z" }),
];
const since = Date.parse("2026-10-20T00:00:00Z");
assert.deepEqual(
attentionEntries(entries, new Set(), { since }).map((entry) => entry.runId),
[2],
);
assert.equal(attentionEntries(entries, new Set()).length, 2);
});
test("startOfLocalDay is local midnight", () => {
const now = new Date(2026, 9, 20, 15, 4, 5).getTime();
const start = startOfLocalDay(now);
assert.equal(new Date(start).getHours(), 0);
assert.equal(new Date(start).getMinutes(), 0);
assert.ok(start < now);
});
test("badge label is bare Notifications when empty, else the count", () => {
assert.equal(attentionBadgeLabel(0), "Notifications");
assert.equal(attentionBadgeLabel(-3), "Notifications");
assert.equal(attentionBadgeLabel(1), "Notifications, 1 needing attention");
assert.equal(attentionBadgeLabel(171), "Notifications, 171 needing attention");
});
// ---------------------------------------------------------------------------
// Ordering
// ---------------------------------------------------------------------------
test("orders by kind rank, then recency descending, then run id descending", () => {
const runs = [
run({ id: 10, status: "failed", finished_at: "2026-10-19T10:00:00Z" }),
run({ id: 11, status: "waiting", finished_at: "2026-10-19T09:00:00Z" }),
run({ id: 12, status: "failed", finished_at: "2026-10-19T11:00:00Z" }),
run({ id: 13, status: "waiting", finished_at: "2026-10-19T08:00:00Z" }),
];
const entries = attentionEntries(runs, new Set());
assert.deepEqual(
entries.map((entry) => entry.runId),
[11, 13, 12, 10],
);
});
test("recency falls back to created_at when finished_at is blank", () => {
const runs = [
run({ id: 1, status: "failed", finished_at: "", created_at: "2026-10-19T12:00:00Z" }),
run({ id: 2, status: "failed", finished_at: "2026-10-19T11:00:00Z" }),
];
const entries = attentionEntries(runs, new Set());
assert.deepEqual(entries.map((entry) => entry.runId), [1, 2]);
});
test("equal kind and recency break ties by run id descending and stay stable", () => {
const runs = [
run({ id: 3, status: "failed", finished_at: "2026-10-19T10:00:00Z" }),
run({ id: 9, status: "failed", finished_at: "2026-10-19T10:00:00Z" }),
run({ id: 5, status: "failed", finished_at: "2026-10-19T10:00:00Z" }),
];
const first = attentionEntries(runs, new Set()).map((entry) => entry.runId);
const second = attentionEntries([...runs].reverse(), new Set()).map((entry) => entry.runId);
assert.deepEqual(first, [9, 5, 3]);
assert.deepEqual(second, [9, 5, 3]);
});
test("non-qualifying runs are dropped entirely", () => {
const runs = [
run({ id: 1, status: "succeeded" }),
run({ id: 2, status: "running" }),
run({ id: 3, status: "failed" }),
run({ id: 4, status: "queued" }),
];
assert.deepEqual(
attentionEntries(runs, new Set()).map((entry) => entry.runId),
[3],
);
assert.deepEqual(attentionEntries(null, new Set()), []);
});
// ---------------------------------------------------------------------------
// Dismissal filtering
// ---------------------------------------------------------------------------
test("a dismissed identity is filtered out; a still-waiting dismissed entry never returns", () => {
const runs = [run({ id: 7, status: "waiting", title: "Wait" })];
const dismissed = new Set(["7:Decision"]);
assert.deepEqual(attentionEntries(runs, dismissed), []);
// Re-deriving from the same live list stays empty.
assert.deepEqual(attentionEntries(runs, dismissed), []);
});
test("a different kind for the same run is a different identity and still appears", () => {
const waiting = run({ id: 7, status: "waiting" });
const dismissed = new Set(["7:Decision"]);
assert.deepEqual(attentionEntries([waiting], dismissed), []);
// The same run later fails: a new kind, a new identity, a new entry.
const failed = run({ id: 7, status: "failed", diagnostic: "later failure" });
const entries = attentionEntries([failed], dismissed);
assert.equal(entries.length, 1);
assert.equal(entries[0].key, "7:Failed");
assert.equal(entries[0].detail, "later failure");
});
test("dismissing one kind leaves the other kind of the same run", () => {
const runs = [
run({ id: 7, status: "waiting" }),
run({ id: 7, status: "failed" }),
];
// Two entries for one run id, one per kind.
const both = attentionEntries(runs, new Set());
assert.equal(both.length, 2);
const afterDismiss = attentionEntries(runs, new Set(["7:Failed"]));
assert.deepEqual(afterDismiss.map((entry) => entry.kind), [AttentionKind.Decision]);
});
// ---------------------------------------------------------------------------
// Dismissal bookkeeping and the Clear-all snapshot
// ---------------------------------------------------------------------------
test("attentionDismiss adds a key once and ignores a blank key", () => {
const one = attentionDismiss(new Set(), "1:Failed");
assert.deepEqual([...one], ["1:Failed"]);
const again = attentionDismiss(one, "1:Failed");
assert.deepEqual([...again], ["1:Failed"]);
const blank = attentionDismiss(one, "");
assert.deepEqual([...blank], ["1:Failed"]);
});
test("clear all applies only the identities in the open snapshot", () => {
const [a] = attentionEntries([run({ id: 1, status: "failed" })], new Set());
const snapshot = attentionDismissalSnapshot([a]);
// A later entry (arrived while the sheet was open) is not in the snapshot.
const [b] = attentionEntries([run({ id: 2, status: "failed" })], new Set());
const after = attentionDismissAll(new Set(), snapshot);
assert.deepEqual([...after].sort(), ["1:Failed"]);
assert.equal(after.has(b.key), false);
// And it does not retroactively appear from the live set either.
assert.deepEqual(
attentionEntries([run({ id: 1, status: "failed" }), run({ id: 2, status: "failed" })], after).map(
(entry) => entry.runId,
),
[2],
);
});
test("the dismissal snapshot is a defensive copy", () => {
const [a, b] = attentionEntries(
[run({ id: 1, status: "failed" }), run({ id: 2, status: "failed" })],
new Set(),
);
const live = [a, b];
const snapshot = attentionDismissalSnapshot(live);
live.push(run({ id: 3, status: "failed" }));
live.reverse();
assert.deepEqual(
snapshot.map((entry) => entry.runId),
[a.runId, b.runId],
);
assert.notEqual(snapshot, live);
});
// ---------------------------------------------------------------------------
// Persistence
// ---------------------------------------------------------------------------
test("the storage key is the one documented key", () => {
assert.equal(ATTENTION_STORAGE_KEY, "pipelines.web.attention.v1");
});
test("encoding is one sorted JSON array and round-trips", () => {
const encoded = encodeAttentionDismissals(new Set(["9:Failed", "1:Decision", "4:Failed"]));
assert.deepEqual(JSON.parse(encoded), ["1:Decision", "4:Failed", "9:Failed"]);
const decoded = decodeAttentionDismissals(encoded);
assert.deepEqual([...decoded].sort(), ["1:Decision", "4:Failed", "9:Failed"]);
assert.deepEqual(JSON.parse(encodeAttentionDismissals(new Set())), []);
});
test("blank or unreadable storage decodes to empty and never throws", () => {
for (const stored of ["", " ", null, undefined, "not json", "{", '"a string"', "{}", "42"]) {
assert.deepEqual([...decodeAttentionDismissals(stored)], []);
}
});
test("a JSON array with non-string members keeps only the strings", () => {
const decoded = decodeAttentionDismissals('["1:Failed", 2, null, {"a":1}, "3:Decision", ""]');
assert.deepEqual([...decoded].sort(), ["1:Failed", "3:Decision"]);
});
test("there is no expiry: a stored identity survives any timestamp", () => {
// The encoding is opaque to time; decoding never consults a clock or drops by age.
const stored = encodeAttentionDismissals(new Set(["7:Decision"]));
assert.deepEqual([...decodeAttentionDismissals(stored)], ["7:Decision"]);
});
-96
View File
@@ -1,96 +0,0 @@
// Compare two ui-smoke capture directories.
//
// node test/capture-manifest.mjs DIR # manifest: name, bytes, sha256
// node test/capture-manifest.mjs --compare BEFORE AFTER
//
// A refactor that must not change behaviour has to produce the SAME capture set:
// every screen the check drove before must still be captured after. Pixel bytes
// legitimately drift on a live server (durations, "x minutes ago", run counts), so
// the gate is the SET, with the differing files listed for a human to inspect:
//
// exit 0 same capture set (drift printed for review)
// exit 1 a capture is missing or unexpected (a screen stopped being driven)
//
// Zero dependencies, no server needed.
import { createHash } from "node:crypto";
import { readdir, readFile, stat } from "node:fs/promises";
import { basename, resolve } from "node:path";
async function manifest(directory) {
const dir = resolve(directory);
const entries = await readdir(dir).catch(() => {
throw new Error(`no such capture directory: ${dir}`);
});
const files = entries.filter((name) => name.toLowerCase().endsWith(".png")).sort();
const rows = [];
for (const name of files) {
const path = `${dir}/${name}`;
const info = await stat(path);
const bytes = await readFile(path);
rows.push({
name,
bytes: info.size,
sha: createHash("sha256").update(bytes).digest("hex").slice(0, 16),
});
}
return { dir, rows };
}
function printManifest({ dir, rows }) {
console.log(`# ${dir} — ${rows.length} capture(s)`);
for (const row of rows) console.log(`${row.name}\t${row.bytes}\t${row.sha}`);
}
async function compare(beforeDir, afterDir) {
const before = await manifest(beforeDir);
const after = await manifest(afterDir);
const beforeNames = new Set(before.rows.map((row) => row.name));
const afterNames = new Set(after.rows.map((row) => row.name));
const missing = [...beforeNames].filter((name) => !afterNames.has(name)).sort();
const extra = [...afterNames].filter((name) => !beforeNames.has(name)).sort();
const beforeByName = new Map(before.rows.map((row) => [row.name, row]));
const drift = [];
for (const row of after.rows) {
const prior = beforeByName.get(row.name);
if (!prior || prior.sha === row.sha) continue;
drift.push({ name: row.name, before: prior.bytes, after: row.bytes, delta: row.bytes - prior.bytes });
}
console.log(`before: ${before.dir} — ${before.rows.length} capture(s)`);
console.log(`after: ${after.dir} — ${after.rows.length} capture(s)`);
console.log(`same set: ${missing.length === 0 && extra.length === 0 ? "yes" : "NO"}`);
if (missing.length) console.log(`missing after: ${missing.join(", ")}`);
if (extra.length) console.log(`unexpected after: ${extra.join(", ")}`);
console.log(
`pixel drift: ${drift.length} capture(s)` +
(drift.length ? " — inspect these for real visual changes:" : ""),
);
for (const row of drift) console.log(` ${row.name} ${row.before} -> ${row.after} bytes (${row.delta >= 0 ? "+" : ""}${row.delta})`);
if (missing.length || extra.length) process.exitCode = 1;
}
import { pathToFileURL } from "node:url";
const runAsScript =
process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
const [first, second, third] = process.argv.slice(2);
if (!runAsScript) {
// Imported as a module (for example from a test): no CLI side effects.
} else if (first === "--compare") {
if (!second || !third) {
console.error("usage: node test/capture-manifest.mjs --compare BEFORE_DIR AFTER_DIR");
process.exit(2);
}
compare(second, third).catch((error) => {
console.error(error.message);
process.exit(2);
});
} else if (first) {
manifest(first).then(printManifest).catch((error) => {
console.error(error.message);
process.exit(2);
});
} else {
console.error("usage: node test/capture-manifest.mjs DIR | --compare BEFORE AFTER");
process.exit(2);
}
export { compare, manifest };
-690
View File
@@ -1,690 +0,0 @@
// Pure unit tests for the run summary's Changes section and its diff viewer:
// the kind mapping and labels, the unified-patch parser (hunks, line numbers,
// stat counts, the `\ No newline` marker and header closing), the cross-step
// final-state aggregation (last sequence wins every per-file fact, every
// touching stage retained), every header/note/detail wording variant and the
// row/viewer helpers.
// No server, no DOM.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
ChangeKind,
ChangeLineKind,
BINARY_DIFF_MESSAGE,
NO_LINE_CHANGES_MESSAGE,
TRUNCATED_PATCH_NOTE,
changeEntryTags,
changeKind,
changeKindLabel,
changeKindTitle,
changePositionLabel,
changeRowMeta,
changeStat,
changesListSummary,
diffLineClass,
diffLineSymbol,
entryHasPatch,
entryModeChanged,
gutterText,
gutterWidth,
noChangeDetail,
parseUnifiedPatch,
patchUnavailableReason,
runChanges,
runChangesHeader,
runChangesNote,
showRunChangesSummary,
} from "../src/changes.js";
// A step file-change with sane defaults, overridable per test.
function file(overrides = {}) {
return { path: "a.txt", kind: "modified", patch: "", ...overrides };
}
// A run step with a file_changes capture, overridable per test.
function step(overrides = {}) {
return { stage: "s", status: "completed", sequence: 1, file_changes: null, ...overrides };
}
// ---------------------------------------------------------------------------
// Kind mapping
// ---------------------------------------------------------------------------
test("changeKind trims and lowercases, never inventing a kind", () => {
assert.equal(changeKind("added"), ChangeKind.Added);
assert.equal(changeKind(" Deleted "), ChangeKind.Deleted);
assert.equal(changeKind("MODIFIED"), ChangeKind.Modified);
assert.equal(changeKind("copied"), ChangeKind.Other);
assert.equal(changeKind(""), ChangeKind.Other);
assert.equal(changeKind(null), ChangeKind.Other);
});
test("changeKindLabel and changeKindTitle spell the app's words", () => {
assert.equal(changeKindLabel(ChangeKind.Added), "added");
assert.equal(changeKindLabel(ChangeKind.Modified), "modified");
assert.equal(changeKindLabel(ChangeKind.Deleted), "deleted");
assert.equal(changeKindLabel(ChangeKind.Other), "changed");
assert.equal(changeKindTitle(ChangeKind.Added), "Added");
assert.equal(changeKindTitle(ChangeKind.Other), "Changed");
});
// ---------------------------------------------------------------------------
// changeStat and changesListSummary
// ---------------------------------------------------------------------------
test("changeStat omits a zero side and is blank when both are zero", () => {
assert.equal(changeStat(3, 2), "+3 -2");
assert.equal(changeStat(3, 0), "+3");
assert.equal(changeStat(0, 2), "-2");
assert.equal(changeStat(0, 0), "");
});
test("changesListSummary keeps the file(s) wording and appends the stat", () => {
const one = { files: [{}], added: 2, removed: 0 };
assert.equal(changesListSummary(one), "1 file changed · +2");
assert.equal(changesListSummary({ files: [{}, {}], added: 0, removed: 0 }), "2 files changed");
});
// ---------------------------------------------------------------------------
// parseUnifiedPatch
// ---------------------------------------------------------------------------
test("parseUnifiedPatch treats a blank patch as an empty diff", () => {
for (const blank of ["", " ", "\n", null, undefined]) {
assert.deepEqual(parseUnifiedPatch(blank), {
raw: "",
headerLines: [],
hunks: [],
added: 0,
removed: 0,
});
}
});
test("parseUnifiedPatch numbers a single hunk and counts the body", () => {
const patch = [
"--- a/x.txt",
"+++ b/x.txt",
"@@ -1,3 +1,3 @@",
" ctx",
"-old",
"+new",
" tail",
].join("\n");
const parsed = parseUnifiedPatch(patch);
assert.equal(parsed.raw, patch);
assert.deepEqual(parsed.headerLines, ["--- a/x.txt", "+++ b/x.txt"]);
assert.equal(parsed.hunks.length, 1);
const hunk = parsed.hunks[0];
assert.equal(hunk.header, "@@ -1,3 +1,3 @@");
assert.deepEqual([hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount], [1, 3, 1, 3]);
assert.deepEqual(
hunk.lines.map((line) => [line.kind, line.text, line.oldLine, line.newLine]),
[
[ChangeLineKind.Context, "ctx", 1, 1],
[ChangeLineKind.Remove, "old", 2, 0],
[ChangeLineKind.Add, "new", 0, 2],
[ChangeLineKind.Context, "tail", 3, 3],
],
);
assert.equal(parsed.added, 1);
assert.equal(parsed.removed, 1);
});
test("parseUnifiedPatch defaults a missing count to 1", () => {
const parsed = parseUnifiedPatch("@@ -5 +7 @@\n-old\n+new");
const hunk = parsed.hunks[0];
assert.deepEqual([hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount], [5, 1, 7, 1]);
assert.equal(parsed.added, 1);
assert.equal(parsed.removed, 1);
});
test("parseUnifiedPatch flags a `\\ No newline` marker without numbering it", () => {
const parsed = parseUnifiedPatch(
["@@ -1 +1 @@", "-one", "\\ No newline at end of file", "+two"].join("\n"),
);
const lines = parsed.hunks[0].lines;
assert.equal(lines[1].noNewlineMarker, true);
assert.equal(lines[1].text, "\\ No newline at end of file");
assert.equal(lines[1].oldLine, 0);
assert.equal(lines[1].newLine, 0);
assert.equal(lines[1].kind, ChangeLineKind.Context);
});
test("a `---`/`+++` header closes the current hunk instead of numbering into it", () => {
const parsed = parseUnifiedPatch(
[
"--- a/x",
"+++ b/x",
"@@ -1 +1 @@",
"-old",
"+new",
"--- a/y",
"+++ b/y",
"@@ -1 +1 @@",
"-alt",
"+neu",
].join("\n"),
);
assert.equal(parsed.hunks.length, 2);
assert.deepEqual(
parsed.hunks[0].lines.map((line) => line.text),
["old", "new"],
);
assert.deepEqual(
parsed.hunks[1].lines.map((line) => line.text),
["alt", "neu"],
);
assert.equal(parsed.headerLines.filter((line) => line.startsWith("--- ")).length, 2);
assert.equal(parsed.added, 2);
assert.equal(parsed.removed, 2);
});
test("an unrecognised tail is kept as unnumbered context and header lines before a hunk are kept", () => {
const parsed = parseUnifiedPatch(
["index abc..def 100644", "--- a/x", "+++ b/x", "@@ -1 +1 @@", "-old", "+new", "trailing junk"].join("\n"),
);
assert.equal(parsed.headerLines[0], "index abc..def 100644");
const tail = parsed.hunks[0].lines.at(-1);
assert.equal(tail.kind, ChangeLineKind.Context);
assert.equal(tail.text, "trailing junk");
assert.equal(tail.oldLine, 0);
assert.equal(tail.newLine, 0);
});
test("a trailing newline becomes a numbered empty context line", () => {
const parsed = parseUnifiedPatch("@@ -1 +1 @@\n ctx\n");
const lines = parsed.hunks[0].lines;
assert.equal(lines.length, 2);
assert.deepEqual([lines[1].text, lines[1].oldLine, lines[1].newLine], ["", 2, 2]);
});
// ---------------------------------------------------------------------------
// Aggregation
// ---------------------------------------------------------------------------
test("a null capture that is running/waiting is pending, otherwise a missing capture", () => {
const running = runChanges([step({ status: "running" }), step({ status: "waiting" })]);
assert.equal(running.pending, true);
assert.equal(running.missingCaptures, 0);
assert.equal(running.stepsWithChanges, 0);
const missing = runChanges([step({ status: "completed" }), step({ status: "failed" })]);
assert.equal(missing.pending, false);
assert.equal(missing.missingCaptures, 2);
});
test("a present capture with no files is a captured no-change", () => {
const changes = runChanges([
step({ stage: "a", file_changes: { status: "complete", files: [] } }),
]);
assert.equal(changes.stepsWithChanges, 1);
assert.deepEqual(changes.files, []);
assert.equal(changes.partial, false);
assert.equal(runChangesHeader(changes), "Changes · no changes observed");
assert.equal(noChangeDetail(changes), "The captured snapshots were identical: the workspace was unchanged.");
});
test("a later step's kind wins, including an unrecognised later kind", () => {
const changes = runChanges([
step({ stage: "a", file_changes: { status: "complete", files: [file({ path: "x", kind: "modified" })] } }),
step({ stage: "b", file_changes: { status: "complete", files: [file({ path: "x", kind: "added" })] } }),
]);
assert.equal(changes.files.length, 1);
assert.equal(changes.files[0].kind, ChangeKind.Added);
assert.deepEqual(changes.files[0].steps, ["a", "b"]);
const unknown = runChanges([
step({ stage: "a", file_changes: { status: "complete", files: [file({ path: "x", kind: "added" })] } }),
step({ stage: "b", file_changes: { status: "complete", files: [file({ path: "x", kind: "copied" })] } }),
]);
// No downgrade heuristic: the final visit recorded an unrecognised kind, so
// the row says `changed` rather than guessing from the earlier visit.
assert.equal(unknown.files[0].kind, ChangeKind.Other);
});
test("a path changed in three visits reports only the last visit's facts", () => {
const changes = runChanges([
step({
stage: "a",
sequence: 1,
file_changes: {
status: "complete",
files: [
file({
path: "x",
kind: "modified",
patch: "@@ -1 +1 @@\n-old\n+one",
before_mode: "0644",
after_mode: "0644",
}),
],
},
}),
step({
stage: "b",
sequence: 2,
file_changes: {
status: "complete",
files: [
file({
path: "x",
kind: "modified",
patch: "@@ -1 +1 @@\n-one\n+two",
before_mode: "0644",
after_mode: "0644",
}),
],
},
}),
step({
stage: "c",
sequence: 3,
file_changes: {
status: "complete",
files: [
file({
path: "x",
kind: "added",
patch: "@@ -1 +2 @@\n-two\n+three\n+four",
before_mode: "0755",
after_mode: "0600",
}),
],
},
}),
]);
const entry = changes.files[0];
assert.equal(entry.kind, ChangeKind.Added);
assert.equal(entry.added, 2);
assert.equal(entry.removed, 1);
assert.equal(entry.patch, "@@ -1 +2 @@\n-two\n+three\n+four");
assert.equal(entry.binary, false);
assert.equal(entry.truncated, false);
assert.equal(entry.beforeMode, "0755");
assert.equal(entry.afterMode, "0600");
assert.equal(entryModeChanged(entry), true);
assert.deepEqual(entry.steps, ["a", "b", "c"]);
assert.equal(changeRowMeta(entry), "changed by a → b → c · mode 0755→0600");
// The run total is the final state's stat, not the three visits summed.
assert.equal(changes.added, 2);
assert.equal(changes.removed, 1);
});
test("later binary/truncated flags and modes replace the earlier rows", () => {
const changes = runChanges([
step({
stage: "a",
file_changes: {
status: "complete",
files: [
file({
path: "x",
kind: "modified",
patch: "@@ -1 +1 @@\n-old\n+new",
binary: true,
truncated: true,
before_mode: "0644",
after_mode: "0755",
}),
],
},
}),
step({
stage: "b",
file_changes: {
status: "complete",
files: [
file({
path: "x",
kind: "modified",
patch: "",
binary: false,
truncated: false,
before_mode: "0755",
after_mode: "0755",
}),
],
},
}),
]);
const entry = changes.files[0];
assert.equal(entry.binary, false);
assert.equal(entry.truncated, false);
assert.equal(entry.patch, null);
assert.equal(entry.beforeMode, "0755");
assert.equal(entry.afterMode, "0755");
assert.equal(entryModeChanged(entry), false);
assert.equal(entry.added, 0);
assert.equal(entry.removed, 0);
// A truncated row anywhere in the run still makes the capture partial.
assert.equal(changes.partial, true);
});
test("an earlier-only path keeps its own values", () => {
const changes = runChanges([
step({
stage: "a",
file_changes: {
status: "complete",
files: [file({ path: "x", kind: "added", patch: "@@ -0,0 +1 @@\n+x" })],
},
}),
step({
stage: "b",
file_changes: {
status: "complete",
files: [file({ path: "y", kind: "deleted", patch: "@@ -1 +0,0 @@\n-y" })],
},
}),
]);
assert.deepEqual(changes.files.map((entry) => entry.path), ["x", "y"]);
assert.equal(changes.files[0].kind, ChangeKind.Added);
assert.equal(changes.files[0].added, 1);
assert.equal(changes.files[0].removed, 0);
assert.equal(changes.files[1].kind, ChangeKind.Deleted);
assert.equal(changes.files[1].added, 0);
assert.equal(changes.files[1].removed, 1);
});
test("ordering follows numeric sequence, not input order", () => {
const outOfOrder = runChanges([
step({ stage: "c", sequence: 3, file_changes: { status: "complete", files: [file({ path: "y", kind: "added" })] } }),
step({ stage: "a", sequence: 1, file_changes: { status: "complete", files: [file({ path: "y", kind: "modified" })] } }),
step({ stage: "b", sequence: 2, file_changes: { status: "complete", files: [file({ path: "x", kind: "added" })] } }),
]);
assert.deepEqual(outOfOrder.files.map((entry) => entry.path), ["y", "x"]);
const y = outOfOrder.files.find((entry) => entry.path === "y");
assert.equal(y.kind, ChangeKind.Added);
assert.deepEqual(y.steps, ["a", "c"]);
assert.equal(changeRowMeta(y), "changed by a → c");
});
test("changed-by lists the stage names in run order, deduped", () => {
const changes = runChanges([
step({ stage: "implementer", file_changes: { status: "complete", files: [file({ path: "x" })] } }),
step({ stage: "reviewer", file_changes: { status: "complete", files: [file({ path: "x" })] } }),
step({ stage: "implementer", file_changes: { status: "complete", files: [file({ path: "x" })] } }),
]);
assert.deepEqual(changes.files[0].steps, ["implementer", "reviewer"]);
assert.equal(changeRowMeta(changes.files[0]), "changed by implementer → reviewer");
});
test("a blank stage name falls back to `stage` and blank paths are skipped", () => {
const changes = runChanges([
step({ stage: " ", file_changes: { status: "complete", files: [file({ path: "x" }), file({ path: " " })] } }),
]);
assert.equal(changes.files.length, 1);
assert.deepEqual(changes.files[0].steps, ["stage"]);
});
test("partial is OR'd from the capture status, a truncated file or any omitted count", () => {
assert.equal(
runChanges([step({ file_changes: { status: "partial", files: [] } })]).partial,
true,
);
assert.equal(
runChanges([step({ file_changes: { status: "complete", files: [file({ truncated: true })] } })]).partial,
true,
);
assert.equal(
runChanges([step({ file_changes: { status: "complete", files: [], omitted: 2 } })]).partial,
true,
);
});
test("diagnostics from several captures are joined with a space, deduped", () => {
const changes = runChanges([
step({ file_changes: { status: "partial", files: [], diagnostic: "why one" } }),
step({ file_changes: { status: "partial", files: [], diagnostic: "why one" } }),
step({ file_changes: { status: "partial", files: [], diagnostic: "why two" } }),
]);
assert.equal(changes.diagnostic, "why one why two");
});
test("showRunChangesSummary is true only for a settled succeeded run", () => {
assert.equal(showRunChangesSummary("succeeded"), true);
assert.equal(showRunChangesSummary(" Succeeded "), true);
for (const status of ["failed", "running", "waiting", "canceled", "interrupted", "blocked", ""]) {
assert.equal(showRunChangesSummary(status), false, `${status} must not show an aggregate`);
}
assert.equal(showRunChangesSummary(null), false);
assert.equal(showRunChangesSummary(undefined), false);
});
// ---------------------------------------------------------------------------
// Header, note and detail wording
// ---------------------------------------------------------------------------
test("runChangesHeader covers every empty-capture variant", () => {
assert.equal(
runChangesHeader({ unavailable: true, files: [], partial: false, pending: false, stepsWithChanges: 0, missingCaptures: 0 }),
"Changes · capture unavailable",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: false, pending: true, stepsWithChanges: 0, missingCaptures: 0 }),
"Changes · capture pending",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: true, pending: false, stepsWithChanges: 1, missingCaptures: 0 }),
"Changes · partial capture",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: false, pending: false, stepsWithChanges: 0, missingCaptures: 0 }),
"Changes · not recorded for this run",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: false, pending: false, stepsWithChanges: 1, missingCaptures: 1 }),
"Changes · capture incomplete",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: false, pending: false, stepsWithChanges: 2, missingCaptures: 0 }),
"Changes · no changes observed",
);
});
test("runChangesHeader counts files, omits a zero stat side and appends the caveats", () => {
const one = { unavailable: false, partial: false, pending: false, stepsWithChanges: 1, missingCaptures: 0, added: 4, removed: 0, files: [{}] };
assert.equal(runChangesHeader(one), "1 file changed · +4");
const many = { ...one, added: 0, removed: 0, files: [{}, {}] };
assert.equal(runChangesHeader(many), "2 files changed");
const partial = { ...one, partial: true, added: 4, removed: 2, files: [{}, {}] };
assert.equal(runChangesHeader(partial), "2 files changed · +4 -2 · partial capture");
const incomplete = { ...one, added: 4, removed: 2, files: [{}, {}], missingCaptures: 1 };
assert.equal(runChangesHeader(incomplete), "2 files changed · +4 -2 · capture incomplete");
});
test("runChangesNote spells the partial, missing and unavailable notes", () => {
assert.equal(
runChangesNote({ unavailable: true, diagnostic: "" }),
"The workspace snapshot could not be compared; the changes below may be incomplete.",
);
assert.equal(
runChangesNote({ unavailable: true, diagnostic: "server says so" }),
"server says so",
);
assert.equal(
runChangesNote({
unavailable: false,
partial: true,
skipped: 8,
omitted: 0,
diagnostic: "Excluded protected files.",
files: [],
missingCaptures: 1,
}),
"Partial capture: some changes may be missing. (8 files skipped) Excluded protected files. " +
"Missing capture: 1 stage did not record changes.",
);
assert.equal(
runChangesNote({
unavailable: false,
partial: true,
skipped: 0,
omitted: 3,
diagnostic: "",
files: [{ truncated: true }, { truncated: true }],
missingCaptures: 2,
}),
"Partial capture: some changes may be missing. (3 omitted, 2 truncated) " +
"Missing capture: 2 stages did not record changes.",
);
assert.equal(runChangesNote({ unavailable: false, partial: false, missingCaptures: 0 }), "");
assert.equal(
runChangesNote({ unavailable: false, partial: false, missingCaptures: 1 }),
"Missing capture: 1 stage did not record changes.",
);
});
test("noChangeDetail distinguishes pending, unavailable, not-recorded and unchanged", () => {
assert.equal(
noChangeDetail({ pending: true }),
"The capture runs after the stage finishes; nothing is recorded yet.",
);
assert.equal(
noChangeDetail({ pending: false, unavailable: true }),
"The workspace snapshot could not be compared, so no changes can be shown.",
);
assert.equal(
noChangeDetail({ pending: false, unavailable: false, stepsWithChanges: 0 }),
"This run recorded no change capture (a historical step, or a stage that does not capture).",
);
assert.equal(
noChangeDetail({ pending: false, unavailable: false, stepsWithChanges: 2 }),
"The captured snapshots were identical: the workspace was unchanged.",
);
});
test("changeEntryTags and changeRowMeta spell the tags and mode exactly", () => {
const binary = { binary: true, truncated: false, otherModeChange: true, beforeMode: "0644", afterMode: "0755", steps: ["a"] };
assert.deepEqual(changeEntryTags(binary), ["binary"]);
assert.equal(changeRowMeta(binary), "changed by a · binary");
const truncated = { binary: false, truncated: true, otherModeChange: false, steps: ["a", "b"] };
assert.deepEqual(changeEntryTags(truncated), ["truncated"]);
assert.equal(changeRowMeta(truncated), "changed by a → b · truncated");
const modeOnly = { binary: false, truncated: false, otherModeChange: true, beforeMode: "0644", afterMode: "0755", steps: ["a"] };
assert.deepEqual(changeEntryTags(modeOnly), ["mode change"]);
assert.equal(changeRowMeta(modeOnly), "changed by a · mode change · mode 0644→0755");
});
test("patchUnavailableReason names the truncation, the mode-only change, else the bare record", () => {
assert.equal(
patchUnavailableReason({ truncated: true }),
"The server truncated this file's patch at its capture limit; no diff text was recorded.",
);
assert.equal(
patchUnavailableReason({ truncated: false, otherModeChange: true, beforeMode: "0644", afterMode: "0755" }),
"Only the file's mode changed (0644→0755); the server recorded no text diff.",
);
assert.equal(
patchUnavailableReason({ truncated: false, otherModeChange: false }),
"The server recorded this change without a patch.",
);
});
test("the viewer's honest messages are the app's exact wording", () => {
assert.equal(
BINARY_DIFF_MESSAGE,
"This is a binary file: the server recorded the change but has no textual diff to show.",
);
assert.equal(
TRUNCATED_PATCH_NOTE,
"The server truncated this patch at its capture limit; the raw text is the whole record.",
);
assert.equal(NO_LINE_CHANGES_MESSAGE, "no line changes recorded");
});
// ---------------------------------------------------------------------------
// Viewer helpers
// ---------------------------------------------------------------------------
test("changePositionLabel and gutterWidth line up", () => {
assert.equal(changePositionLabel(0, 3), "1 of 3");
assert.equal(changePositionLabel(2, 3), "3 of 3");
assert.equal(gutterWidth({ lines: [] }), 1);
assert.equal(gutterWidth({ lines: [{ oldLine: 9, newLine: 0 }, { oldLine: 0, newLine: 12 }] }), 2);
assert.equal(gutterText(0, 2), " ");
assert.equal(gutterText(7, 2), " 7");
});
test("diffLineSymbol and diffLineClass are the app's one diff language", () => {
assert.equal(diffLineSymbol(ChangeLineKind.Add), "+");
assert.equal(diffLineSymbol(ChangeLineKind.Remove), "-");
assert.equal(diffLineSymbol(ChangeLineKind.Context), " ");
assert.equal(diffLineClass(ChangeLineKind.Add), "diff-add");
assert.equal(diffLineClass(ChangeLineKind.Remove), "diff-remove");
assert.equal(diffLineClass(ChangeLineKind.Context), "diff-context");
});
// ---------------------------------------------------------------------------
// A full aggregate matches the section it renders
// ---------------------------------------------------------------------------
test("runChanges derives run 438's shape: 22 files, partial, one missing capture", () => {
// Six steps, 23 recorded file rows for 22 unique paths, one step without a
// capture, every capture partial with a diagnostic.
const diag = "Excluded protected, symlinked, oversized or unreadable files; this is not a complete workspace diff.";
const patch = "@@ -1 +1 @@\n-old\n+new";
const steps = [
step({
stage: "implementer",
file_changes: {
status: "partial",
skipped: 2,
diagnostic: diag,
files: [
file({ path: "docs/notes.md", kind: "added", patch }),
file({ path: "internal/server/retry_test.go", kind: "modified", patch }),
file({ path: "internal/server/runner.go", kind: "modified", patch }),
],
},
}),
step({ stage: "reviewer", file_changes: { status: "partial", skipped: 2, diagnostic: diag, files: [] } }),
step({
stage: "implementer",
file_changes: {
status: "partial",
skipped: 2,
diagnostic: diag,
files: [file({ path: "internal/server/retry_test.go", kind: "modified", patch })],
},
}),
step({ stage: "reviewer", file_changes: { status: "partial", skipped: 2, diagnostic: diag, files: [] } }),
step({ stage: "ui_reviewer" }),
step({
stage: "committer",
file_changes: {
status: "partial",
skipped: 2,
diagnostic: diag,
files: Array.from({ length: 19 }, (_, i) => file({ path: `android/file${i}.kt`, kind: "modified", patch })),
},
}),
];
const changes = runChanges(steps);
assert.equal(changes.files.length, 22);
assert.equal(changes.stepsWithChanges, 5);
assert.equal(changes.missingCaptures, 1);
assert.equal(changes.partial, true);
assert.equal(changes.unavailable, false);
assert.equal(changes.pending, false);
assert.equal(changes.skipped, 10);
// The retry test was modified by two implementer visits; only the last one's
// stat counts (the earlier patch must not be added to it).
assert.equal(changes.files.find((f) => f.path === "internal/server/retry_test.go").added, 1);
assert.equal(changes.files.find((f) => f.path === "internal/server/retry_test.go").removed, 1);
assert.equal(changes.added, 22);
assert.equal(changes.removed, 22);
assert.equal(
runChangesHeader(changes),
`22 files changed · +22 -22 · partial capture`,
);
assert.ok(runChangesNote(changes).startsWith("Partial capture: some changes may be missing. (10 files skipped)"));
assert.ok(runChangesNote(changes).endsWith("Missing capture: 1 stage did not record changes."));
});
-73
View File
@@ -1,73 +0,0 @@
// Native compaction fixture through the real chat fold/view; no harness calls.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } 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-chat-compaction");
await mkdir(out, {recursive:true});
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","chat","dialogs"].map(n=>`<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main class="workspace"><div class="pane-main"><div class="content" id="content"></div></div></main></div>
<script type="module">
import { createChatView } from '/src/views/chat.js';
import { newChatThread, applyChatEvent, resumedThread } from '/src/chat.js';
const id='scratch';
const state={view:'chat',connection:{kind:'connected'},chatSubscriptions:new Set(),chatActiveId:id,chatSessions:[{id,title:'Context compaction',backend:'opencode'}],chatOverrides:{},chatDrafts:{},chatThreads:new Map()};
const repo={subscribeChat:async()=>{event('running');},chatHistory:async()=>({messages:state.chatThreads.get(id).messages}),chatShells:async()=>[]};
const rt={state,repo,renderContent:()=>paint(),closeDetail:()=>{}};
const view=createChatView(rt);
window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation());
window.setup=(history)=>{
const messages=[{id:'user',role:'user',parts:[{type:'text',text:'Continue the task.'}]}];
if(history)messages.push({id:'assistant',role:'assistant',parts:[{id:'reason',type:'reasoning',text:'Inspecting the existing context.'},{id:'tool',type:'tool',name:'read',state:{status:'completed'}},{type:'text',text:'Continuing after checking the files.'}]});
state.chatThreads.set(id,{...newChatThread(id),loaded:true,messages});paint();};
window.event=(status)=>{state.chatThreads.set(id,applyChatEvent(state.chatThreads.get(id),{session_id:id,kind:'compaction',compaction:{id:'native-compaction',status}}));paint();};
window.end=()=>{state.chatThreads.set(id,applyChatEvent(state.chatThreads.get(id),{session_id:id,kind:'step',step:{status:'ended'}}));paint();};
window.drop=()=>{state.chatThreads.set(id,resumedThread(state.chatThreads.get(id)));paint();};
window.reconnect=()=>{state.chatSubscriptions.clear();return view.resyncOpenChat();};
window.messageCount=()=>state.chatThreads.get(id).messages.length;
setup(true);
</script>`;
const server=createServer(async(req,res)=>{try{
const path=new URL(req.url,"http://fixture").pathname;
if(path==="/"){res.setHeader("Content-Type","text/html");res.end(html);return;}
const file=resolve(root,`.${path}`);if(!file.startsWith(root+"/"))throw Error("outside fixture");
res.setHeader("Content-Type",extname(file)===".css"?"text/css":"text/javascript");res.end(await readFile(file));
}catch{res.writeHead(404);res.end();}});
await new Promise(r=>server.listen(0,"127.0.0.1",r));
let browser;
try {
browser=await launchChrome();
const page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector("#chatInput");
for(const width of [390,1100]) {
await page.resize(width,844);
for(const history of [false,true]) {
await page.evaluate(`setup(${history});event('running')`);
await page.waitForSelector(".chat-compaction-status");
assert.equal(await page.evaluate("document.querySelector('.chat-compaction-status').textContent"),"Compacting context…");
assert.equal(await page.evaluate("document.querySelector('.chat-compaction-status').getAttribute('role')"),"status");
assert.equal(await page.evaluate("messageCount()"),history?2:1);
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),1);
if(history) assert.equal(await page.evaluate("document.querySelector('.chat-reasoning-label').textContent"),"Reasoning");
assert.equal(await page.evaluate("document.documentElement.scrollWidth>innerWidth"),false);
await page.screenshot(resolve(out,`compacting-${history?'with-history':'before-answer'}-${width}.png`));
await page.evaluate("event('completed')");
assert.equal(await page.evaluate("document.querySelectorAll('.chat-compaction-status').length"),0);
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),1);
await page.evaluate("end()");
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),0);
}
}
await page.evaluate("setup(true);event('running');drop()");
assert.equal(await page.evaluate("document.querySelectorAll('.chat-compaction-status').length"),0);
await page.screenshot(resolve(out,"compaction-clears-on-disconnect.png"));
await page.evaluate("reconnect()");
assert.equal(await page.evaluate("document.querySelector('.chat-compaction-status')?.textContent"),"Compacting context…");
await page.screenshot(resolve(out,"compaction-replay-survives-history-refresh.png"));
console.log("PASS: native compaction is visible before/alongside answers, clears on completion/disconnect, survives reconnect history refresh, and creates no fake message or premature turn completion.");
} finally {await browser?.close();await new Promise(r=>server.close(r));}
-167
View File
@@ -1,167 +0,0 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { join } from "node:path";
import net from "node:net";
import { fileURLToPath } from "node:url";
import { eventually, launchChrome } from "./browser.mjs";
const [target, sessionId] = process.argv.slice(2);
assert.match(target ?? "", /^127\.0\.0\.1:\d+$/);
const reserve = net.createServer();
await new Promise((resolve) => reserve.listen(0, "127.0.0.1", resolve));
const port = reserve.address().port;
await new Promise((resolve) => reserve.close(resolve));
const serve = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--pipelines", target], {
cwd: fileURLToPath(new URL("..", import.meta.url)),
env: { ...process.env, PIPELINES_WEB_AUTH: "disabled" }, stdio: ["ignore", "pipe", "pipe"],
});
let logs = "";
serve.stdout.on("data", (data) => { logs += data; });
serve.stderr.on("data", (data) => { logs += data; });
let browser;
try {
await eventually(async () => {
if (serve.exitCode != null) throw Error(logs);
return fetch(`http://127.0.0.1:${port}/`).then((r) => r.ok).catch(() => false);
});
browser = await launchChrome({ width: 390, height: 844 });
const page = await browser.openPage("about:blank");
await page.addInitScript(`(() => {
window.__errors = [];
window.addEventListener('error', (event) => window.__errors.push(event.message));
window.addEventListener('unhandledrejection', (event) => window.__errors.push(String(event.reason)));
const Native = window.WebSocket;
window.WebSocket = class extends Native { constructor(...args) { super(...args); window.__socket = this; } };
// Controlled geometry, not a claim that desktop Chrome has an iOS keyboard.
const viewport = Object.assign(new EventTarget(), {height:844,width:390,scale:1,offsetTop:0});
Object.defineProperty(window, 'visualViewport', {value:viewport,configurable:true});
})()`);
await page.goto(`http://127.0.0.1:${port}/chat/${sessionId}`);
await page.waitForSelector("#chatTranscript .chat-reasoning-toggle");
await page.click(".chat-model-button");
await page.waitForSelector("#chatModelSearch");
await page.fill("#chatModelSearch", "beta");
assert.equal(await page.evaluate("document.querySelectorAll('.chat-model-option').length"), 1);
assert.equal(await page.evaluate("document.querySelector('.chat-model-option-name').textContent"), "Model Beta");
assert.equal(await page.evaluate("document.querySelector('.app-root').inert"), true);
if (process.env.PIPELINES_CAPTURE_DIR) {
await mkdir(process.env.PIPELINES_CAPTURE_DIR, { recursive: true });
await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR, "managed-model-search.png"));
}
await page.evaluate("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }))");
await eventually(() => page.evaluate("!document.querySelector('.confirm-chat-model')"));
const emit = (frame) => page.evaluate(`window.__socket.onmessage({data: JSON.stringify({type:'chat_event', chat_event: {session_id:${JSON.stringify(sessionId)}, ...${JSON.stringify(frame)}}})})`);
await emit({ message_id:"msg_answer",kind:"step",step:{status:"started"} });
await emit({ message_id:"msg_answer",kind:"step",step:{status:"ended",intermediate:true} });
await eventually(() => page.evaluate("!!document.querySelector('#chatStop') && !!document.querySelector('.chat-activity-spinner')"));
await page.click("#chatTranscript .chat-reasoning-toggle");
await page.waitForSelector(".chat-reasoning-viewer");
assert.equal(await page.evaluate("document.querySelector('.chat-reasoning-modal-body').textContent"), "Controlled reasoning evidence");
if (process.env.PIPELINES_CAPTURE_DIR) {
await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR, "stable-reasoning-popup.png"));
}
await page.evaluate("document.querySelector('.chat-reasoning-viewer .chat-tool-close').click()");
await emit({ message_id:"msg_answer",kind:"step",step:{status:"ended"} });
await eventually(() => page.evaluate("!document.querySelector('#chatStop') && !document.querySelector('.chat-activity-spinner')"));
await page.fill("#chatInput", "Keep this draft and caret");
await page.evaluate(`(() => {
const input = document.querySelector('#chatInput');
input.setSelectionRange(5, 9);
window.__composer = input;
window.visualViewport.height = 430;
window.visualViewport.dispatchEvent(new Event('resize'));
})()`);
await eventually(() => page.evaluate("document.documentElement.classList.contains('keyboard-open')"));
assert.equal(await page.evaluate("document.querySelector('#chatInput') === window.__composer && document.activeElement === window.__composer"), true);
assert.equal(await page.evaluate("document.querySelector('#chatInput').selectionStart"), 5);
assert.equal(await page.evaluate("getComputedStyle(document.querySelector('#chatInput')).fontSize"), "16px");
assert.equal(await page.evaluate("document.querySelector('#chatComposer').getBoundingClientRect().bottom <= 431"), true);
if (process.env.PIPELINES_CAPTURE_DIR) {
await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR, "keyboard-composer-visible.png"));
}
await page.evaluate("window.visualViewport.height = 844; window.visualViewport.dispatchEvent(new Event('resize'))");
await eventually(() => page.evaluate("!document.documentElement.classList.contains('keyboard-open')"));
await page.click(".chat-back");
await page.waitForSelector("#chatRows");
await page.evaluate("document.querySelector('#chatRows').scrollTop = 280");
const scroll = await page.evaluate("document.querySelector('#chatRows').scrollTop");
assert.ok(scroll > 0);
await page.evaluate("document.querySelector('#chatRows .chat-session-button').click()");
await page.waitForSelector(".chat-back");
await page.click(".chat-back");
await page.waitForSelector("#chatRows");
assert.equal(await page.evaluate("document.querySelector('#chatRows').scrollTop"), scroll);
// Activity changes color in place; it must not move the harness mark or add a
// Streaming label to the row.
const iconRect = await page.evaluate(`(() => { const icon=document.querySelector('#chatRows .chat-row[data-session="${sessionId}"] .chat-backend-logo'); window.__icon=icon; const r=icon.getBoundingClientRect(); return [r.x,r.y,r.width,r.height]; })()`);
await emit({ message_id:"msg_answer",kind:"step",step:{status:"started"} });
assert.equal(await page.evaluate("window.__icon.dataset.activity"), "streaming");
assert.equal(await page.evaluate("document.querySelectorAll('#chatRows .chat-activity-streaming').length"), 0);
assert.deepEqual(await page.evaluate("(() => { const r=window.__icon.getBoundingClientRect(); return [r.x,r.y,r.width,r.height]; })()"), iconRect);
await emit({ message_id:"msg_answer",kind:"step",step:{status:"ended"} });
await page.evaluate(`document.querySelector('#chatRows .chat-row[data-session="${sessionId}"] .chat-session-button').click()`);
await page.waitForSelector("#chatInput");
await page.waitForSelector("#chatTranscript");
await page.evaluate("(() => { const t=document.querySelector('#chatTranscript'); t.dispatchEvent(new WheelEvent('wheel',{deltaY:-240,bubbles:true})); t.scrollTop=0; t.dispatchEvent(new Event('scroll')); })()");
await page.fill("#chatInput", "New message must scroll into view");
await page.click("#chatSend");
await eventually(() => page.evaluate("(() => { const t=document.querySelector('#chatTranscript'); return t.textContent.includes('New message must scroll into view') && t.scrollHeight-t.scrollTop-t.clientHeight<3; })()"));
// These requests originate at the broker snapshot, not an injected browser
// frame. A reload must recover all of them, and each control reaches Go.
assert.equal((await fetch(`http://${target}/fixture-attention`,{method:'POST'})).status,204);
await eventually(() => page.evaluate("document.querySelectorAll('.chat-approval-pending').length===2 && document.querySelectorAll('.chat-question').length===2"));
await page.goto(`http://127.0.0.1:${port}/chat/${sessionId}`);
try {
await eventually(() => page.evaluate("document.querySelectorAll('.chat-approval-pending').length===2 && document.querySelectorAll('.chat-question').length===2"));
} catch(error) {
console.log(await page.evaluate("({approvals:document.querySelectorAll('.chat-approval-pending').length,questions:document.querySelectorAll('.chat-question').length,errors:window.__errors,text:document.body.innerText.slice(-2000)})"));
throw error;
}
assert.equal(await page.evaluate("!!document.querySelector('.chat-approval-jump')"),true);
await page.click('.chat-approval-jump');
if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'mobile-pending-interactions.png'));
await page.evaluate("document.querySelector('[data-request-id=per_first] .chat-approval-control').click()");
await eventually(() => page.evaluate("document.querySelectorAll('.chat-approval-pending').length===1"));
await page.evaluate("document.querySelector('[data-request-id=per_second] .chat-approval-control:last-child').click()");
await eventually(() => page.evaluate("document.querySelectorAll('.chat-approval-pending').length===0"));
for(const id of ['form_first','form_second']) {
await page.fill(`[data-form-id=${id}] .chat-question-input`,'Browser answer');
if(id==='form_second') {
await page.evaluate("(()=>{const s=document.querySelector('[data-form-id=form_second] select');s.value='true';s.dispatchEvent(new Event('change',{bubbles:true}));})()");
await page.fill('[data-form-id=form_second] input[aria-label="Only when enabled"]','must not leak');
await page.evaluate("(()=>{const s=document.querySelector('[data-form-id=form_second] select');s.value='false';s.dispatchEvent(new Event('change',{bubbles:true}));})()");
await page.fill('[data-form-id=form_second] input[type=number]','0');
assert.equal(await page.evaluate("document.querySelector('[data-form-id=form_second] input[aria-label=\"Only when enabled\"]').closest('.chat-question-field').getBoundingClientRect().height"),0);
assert.equal(await page.evaluate("document.querySelector('[data-form-id=form_second] input[aria-label=Secret]').type"),'password');
if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'typed-question-controls.png'));
}
await emit({message_id:'msg_answer',kind:'text',part:{id:'draft-check',type:'text',text:'unrelated frame'}});
await eventually(() => page.evaluate(`document.querySelector('[data-form-id=${id}] .chat-question-input')?.value==='Browser answer'`));
await page.evaluate(`document.querySelector('[data-form-id=${id}] .chat-question-submit').click()`);
await eventually(() => page.evaluate(`!document.querySelector('[data-form-id=${id}]')`));
}
await eventually(() => page.evaluate("!document.querySelector('.chat-approval-jump')"));
assert.equal((await fetch(`http://${target}/fixture-cancel`,{method:'POST'})).status,204);
await page.waitForSelector('[data-form-id=form_cancel]');
await page.evaluate("[...document.querySelectorAll('[data-form-id=form_cancel] button')].find(button=>button.textContent==='Cancel question').click()");
await eventually(()=>page.evaluate("!document.querySelector('[data-form-id=form_cancel]')"));
assert.equal((await fetch(`http://${target}/fixture-shell`,{method:'POST'})).status,204);
await page.goto(`http://127.0.0.1:${port}/chat/${sessionId}`);
await page.waitForSelector('.chat-bg-task');
await page.click('.chat-bg-task');
await eventually(()=>page.evaluate("document.querySelector('.chat-bg-task-output')?.textContent==='Controlled background output'"));
if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'harness-background-output.png'));
await page.fill('#chatInput','Keep this draft through readback');
await page.evaluate("window.__resyncComposer=document.querySelector('#chatInput')");
assert.equal((await fetch(`http://${target}/fixture-resync`,{method:'POST'})).status,204);
await emit({kind:'resync'});
await eventually(()=>page.evaluate("document.querySelector('#chatTranscript').textContent.includes('Authoritative resync evidence')"));
assert.equal(await page.evaluate("document.querySelector('#chatInput')===window.__resyncComposer && document.querySelector('#chatInput').value==='Keep this draft through readback'"),true);
assert.deepEqual(await page.evaluate("window.__errors"), []);
console.log("Model dialog, stable activity mark, keyboard/caret, Back restoration, send-to-bottom and all recovered approvals/questions passed.");
} finally {
await browser?.close();
serve.kill("SIGTERM");
await new Promise((resolve) => serve.exitCode != null ? resolve() : serve.once("exit", resolve));
}
-282
View File
@@ -1,282 +0,0 @@
// Focused UI-smoke extension: real createChatView + mock repository only.
// No native chats, provider calls, live server or framework.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir, 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-chat-row-actions");
await mkdir(out, { recursive: true });
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", "chat", "dialogs"].map(n => `<link rel="stylesheet" href="/${n}.css">`).join("")}
<style>body { margin: 0; } #fixture { display: flex; height: calc(100dvh - 80px); max-width: 540px; margin: 40px auto; } #fixture > .chat-list { flex: 1; }</style>
<div id="fixture"></div>
<div style="position:fixed;top:-1000px;left:0"><button id="ghostBaseline" class="ghost">Ordinary ghost</button><button id="rowBaseline" class="row">Ordinary row</button></div>
<script type="module">
import { createChatView } from '/src/views/chat.js';
import { newChatThread } from '/src/chat.js';
const long = 'Review a very long chat title that must never overlap any of its controls or backend mark';
const directory = '/Users/fixture/projects/a-very-long-project-directory/with/deeply/nested/worktrees';
const sessions = [
{ id:'selected', title:long, backend:'opencode', model:'openai/gpt-6.1-sol-with-a-very-long-model-name', starred:true },
{ id:'streaming', title:long, backend:'claude', model:'claude-sonnet' },
{ id:'new', title:long, backend:'codex', model:'gpt-5' },
{ id:'closed', title:long, backend:'opencode', model:'gpt-6.1', closed:true },
].map(s => ({ ...s, directory, updated_at:Date.now() }));
window.calls = { routes:[], stars:[] };
window.state = {
view:'chat', chatActiveId:'selected', chatSessions:sessions, chatQuery:'',
chatOverrides:{}, chatStars:new Set(['selected']), chatClosedOpen:true,
chatSeen:{}, chatThreads:new Map([
['selected',{...newChatThread('selected'),loaded:true}],
['streaming',{...newChatThread('streaming'),loaded:true,running:true}],
]), connection:{kind:'disconnected'}, chatSubscriptions:new Set(), chatDrafts:{}, chatScroll:{},
};
const repo = {
starChat:async(id,starred) => { calls.stars.push({id,starred}); return {starred}; },
chatHistory:async() => ({messages:[]}), chatShells:async() => [],
};
const rt = {state,repo,renderContent:() => paint(),focusDetailHeading:() => {},pushRoute:route => calls.routes.push(route)};
const view = createChatView(rt);
window.paint = () => document.querySelector('#fixture').replaceChildren(view.renderChatList());
window.reset = () => { state.chatMenu=null; state.chatActiveId='selected'; paint(); };
paint();
</script>`;
const server = createServer(async (req, res) => {
try {
const path = new URL(req.url, "http://fixture").pathname;
if (path === "/") { res.setHeader("Content-Type", "text/html"); res.end(html); return; }
const file = resolve(root, `.${path}`);
if (!file.startsWith(root + "/")) throw Error("outside fixture");
res.setHeader("Content-Type", extname(file) === ".css" ? "text/css" : "text/javascript");
res.end(await readFile(file));
} catch { res.writeHead(404); res.end(); }
});
await new Promise(r => server.listen(0, "127.0.0.1", r));
let browser, mouse;
const captures = [];
const measurements = [];
const styleComparisons = [];
try {
browser = await launchChrome();
const page = await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector('.chat-row-actions');
// A direct page CDP connection supplies actual pointer movement without clicks.
const target = (await (await fetch(`http://127.0.0.1:${browser.port}/json/list`)).json()).find(t => t.id === page.targetId);
mouse = new WebSocket(target.webSocketDebuggerUrl);
await new Promise(r => mouse.addEventListener('open', r, {once:true}));
let sequence = 0;
const command = (method, params = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const listener = event => {
const response = JSON.parse(event.data);
if (response.id !== id) return;
mouse.removeEventListener('message', listener);
response.error ? reject(Error(response.error.message)) : resolve(response.result);
};
mouse.addEventListener('message', listener);
mouse.send(JSON.stringify({id,method,params}));
});
const move = (x, y) => command('Input.dispatchMouseEvent', {type:'mouseMoved',x,y});
await command('DOM.enable');
await command('CSS.enable');
const {root:documentRoot} = await command('DOM.getDocument');
const force = async (selector, forcedPseudoClasses) => {
const {nodeId} = await command('DOM.querySelector', {nodeId:documentRoot.nodeId,selector});
await command('CSS.forcePseudoState', {nodeId,forcedPseudoClasses});
};
const styles = selector => page.evaluate(`(() => {
const s=getComputedStyle(document.querySelector(${JSON.stringify(selector)}));
return Object.fromEntries(['backgroundColor','borderTopColor','borderTopWidth','borderRadius','boxShadow','color',
'outlineColor','outlineWidth','outlineStyle','outlineOffset'].map(key=>[key,s[key]]));
})()`);
const compareStyles = async (width, coarse = false) => {
await move(1,1);
await page.evaluate('document.activeElement.blur()');
for (const state of [[],['hover'],['active'],['hover','active'],['focus-visible']]) {
const selectors=['#ghostBaseline','[data-session=streaming] .chat-star','[data-session=streaming] .chat-menu-button'];
for (const selector of selectors) await force(selector,state);
// Allow the shared background/border transitions to settle before comparing.
await page.evaluate('new Promise(r=>setTimeout(r,250))');
const baseline=await styles('#ghostBaseline');
for (const selector of selectors.slice(1)) assert.deepEqual(await styles(selector),baseline,`${selector}: ghost ${state}`);
await force('[data-session=selected] .chat-star',state);
await page.evaluate('new Promise(r=>setTimeout(r,250))');
const starred=await styles('[data-session=selected] .chat-star');
for (const key of ['backgroundColor','borderTopColor','borderTopWidth','borderRadius','boxShadow','outlineWidth','outlineStyle','outlineOffset']) assert.equal(starred[key],baseline[key],`starred ghost ${state}: ${key}`);
assert.equal(starred.color,await page.evaluate("(() => {const el=document.createElement('span');el.style.color='var(--color-accent)';document.body.append(el);const color=getComputedStyle(el).color;el.remove();return color;})()"),'starred state alone keeps its accent');
await force('[data-session=selected] .chat-star',[]);
for (const selector of selectors) await force(selector,[]);
for (const selected of [false,true]) {
const row=selected?'[data-session=selected]':'[data-session=streaming]';
await page.evaluate(`document.querySelector('#rowBaseline').classList.toggle('selected',${selected})`);
await force('#rowBaseline',state);
await force(row,state.includes('hover')?['hover']:[]);
await force(row+' .chat-session-button',state);
await page.evaluate('new Promise(r=>setTimeout(r,250))');
const expected=await styles('#rowBaseline'), actual=await styles(row);
// Container and native row inherit the same row surface/focus tokens.
for (const key of ['backgroundColor','borderTopColor','borderTopWidth','borderRadius','boxShadow','outlineColor','outlineWidth','outlineStyle','outlineOffset']) {
assert.equal(actual[key],expected[key],`row selected=${selected} ${state}: ${key}`);
}
const inner=await styles(row+' .chat-session-button');
assert.equal(inner.backgroundColor,'rgba(0, 0, 0, 0)','no inner hover/press fill');
assert.equal(inner.boxShadow,'none','no inner inset');
assert.equal(inner.outlineStyle,'none','focus ring belongs to outer row');
styleComparisons.push({width,coarse,state,selected,ghost:baseline,starred,row:actual,inner});
if (!selected && state.includes('active') && !state.includes('hover') && !coarse) await capture(`active-surface-${width}`);
await force(row+' .chat-session-button',[]);
await force(row,[]);
await force('#rowBaseline',[]);
}
}
};
const capture = async name => {
const file = `topright-leftlogo-bottomright-${name}.png`;
await page.screenshot(resolve(out, file));
captures.push(file);
};
const geometry = () => page.evaluate(`(() => {
const overlaps = (a,b) => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
return [...document.querySelectorAll('.chat-row')].map(row => {
const controls = [...row.querySelectorAll('.chat-star,.chat-menu-button')];
const content = [...row.querySelectorAll('.chat-session-button,.chat-backend-logo')];
const r=row.getBoundingClientRect(), s=getComputedStyle(row), logo=row.querySelector('.chat-backend-logo'), title=row.querySelector('.chat-row-title');
const star=controls[0].getBoundingClientRect(), more=controls[1].getBoundingClientRect();
return {id:row.dataset.session,
topRight:Math.abs(star.top-r.top-parseFloat(s.paddingTop))<1,
bottomRight:Math.abs(more.bottom-r.bottom+parseFloat(s.paddingBottom)+parseFloat(s.borderBottomWidth))<1,
sameRight:star.right===more.right && Math.abs(star.right-r.right+parseFloat(s.paddingRight))<1,
logoBeforeTitle:logo.parentElement===title.parentElement && logo.nextElementSibling===title && logo.getBoundingClientRect().right<=title.getBoundingClientRect().left,
logoNonshrink:getComputedStyle(logo).flexShrink==='0',
controls:controls.map(button => {
const r=button.getBoundingClientRect(), style=getComputedStyle(button);
return {width:r.width,height:r.height,x:r.x,y:r.y,opacity:getComputedStyle(button.parentElement).opacity,
transition:getComputedStyle(button.parentElement).transitionDuration,
visible:style.visibility==='visible' && style.display!=='none',
hit:document.elementFromPoint(r.x+r.width/2,r.y+r.height/2)===button,
overlap:content.some(node => overlaps(r,node.getBoundingClientRect())),
nested:!!button.parentElement.closest('button')};
})};
});
})()`);
for (const width of [390, 420, 1100]) {
await page.resize(width, 844);
await page.evaluate('reset()');
await move(1, 1);
const before = await geometry();
measurements.push({width, rows:before});
assert.equal(before.length, 4);
for (const row of before) for (const key of ['topRight','bottomRight','sameRight','logoBeforeTitle','logoNonshrink']) assert.equal(row[key],true,`${row.id}: ${key}`);
for (const row of before) for (const button of row.controls) {
assert.ok(button.width >= 44 && button.height >= 44, `${row.id}: touch target`);
assert.equal(button.opacity, '1');
assert.equal(button.transition, '0s');
assert.equal(button.visible, true);
assert.equal(button.hit, true, `${row.id}: control centre hit-test`);
assert.equal(button.overlap, false, `${row.id}: no text/logo overlay`);
assert.equal(button.nested, false);
}
assert.equal(await page.evaluate('document.documentElement.scrollWidth > innerWidth'), false);
assert.equal(await page.evaluate("document.querySelector('[data-session=streaming] .chat-backend-logo').dataset.activity"), 'streaming');
assert.equal(await page.evaluate("document.querySelector('[data-session=new] .chat-backend-logo').dataset.activity"), 'new');
await capture(`rows-visible-${width}`);
await compareStyles(width);
await page.evaluate("document.querySelector('[data-session=selected] .chat-session-button').style.minHeight='160px'");
assert.ok((await geometry()).every(row=>row.topRight && row.bottomRight && row.sameRight),'controls anchor to full row height, not two adjacent fixed rows');
await page.evaluate("document.querySelector('[data-session=selected] .chat-session-button').style.minHeight=''");
const first = before[0].controls[0];
await move(first.x + 22, first.y + 22);
assert.deepEqual(await geometry(), before, 'hover changes neither controls nor layout');
const more = before[0].controls[1];
await move(more.x + 22, more.y + 22);
assert.deepEqual(await geometry(), before, 'hovering Chat actions reveals no new controls');
assert.equal(await page.evaluate("document.querySelectorAll('.chat-menu-panel').length"), 0, 'hover never opens a menu');
await capture(`rows-hover-${width}`);
// Natural keyboard order: thread, star, menu. Focus must not open the menu.
await page.evaluate("document.querySelector('[data-session=selected] .chat-session-button').focus()");
await page.pressKey('Tab');
assert.equal(await page.evaluate("document.activeElement.classList.contains('chat-star')"), true);
await page.pressKey('Tab');
assert.equal(await page.evaluate("document.activeElement.classList.contains('chat-menu-button')"), true);
assert.equal(await page.evaluate("document.querySelectorAll('.chat-menu-panel').length"), 0);
await capture(`rows-keyboard-${width}`);
await page.pressKey('Enter');
assert.equal(await page.evaluate("document.activeElement.classList.contains('chat-menu-item')"), true);
assert.deepEqual(await page.evaluate("Array.from(document.querySelectorAll('.chat-menu-item'),n=>n.textContent)"), ['Rename…', 'Close chat…', 'Hide on this device']);
assert.equal(await page.evaluate('state.chatActiveId'), 'selected');
assert.deepEqual(await page.evaluate('calls.routes'), []);
await capture(`rows-menu-${width}`);
await page.evaluate('reset()');
await page.click('[data-session=streaming] .chat-menu-button');
assert.equal(await page.evaluate('state.chatMenu'), 'streaming');
assert.equal(await page.evaluate('state.chatActiveId'), 'selected');
assert.deepEqual(await page.evaluate('calls.routes'), []);
await capture(`rows-pointer-menu-${width}`);
await page.click('[data-session=streaming] .chat-menu-button');
assert.equal(await page.evaluate("document.querySelectorAll('.chat-menu-panel').length"), 0);
const stars = await page.evaluate('calls.stars.length');
await page.click('[data-session=streaming] .chat-star');
assert.deepEqual(await page.evaluate('calls.stars.at(-1)'), {id:'streaming',starred:true});
assert.equal(await page.evaluate('calls.stars.length'), stars + 1);
assert.equal(await page.evaluate('state.chatActiveId'), 'selected');
assert.deepEqual(await page.evaluate('calls.routes'), []);
await page.click('[data-session=streaming] .chat-star');
// Force the closed trigger against the actual list scroller bottom. Unlike
// click(selector), Enter does not silently scroll it to the viewport centre.
await page.resize(width, 500);
await page.evaluate(`(() => {
const rows=document.querySelector('#chatRows'), row=document.querySelector('[data-session=closed]');
rows.scrollTop += row.getBoundingClientRect().bottom - rows.getBoundingClientRect().bottom;
row.querySelector('.chat-menu-button').focus({preventScroll:true});
})()`);
assert.equal(await page.evaluate(`(() => {
const rows=document.querySelector('#chatRows'), row=document.querySelector('[data-session=closed]');
return Math.abs(row.getBoundingClientRect().bottom-rows.getBoundingClientRect().bottom)<2 && rows.scrollTop>0;
})()`), true, 'fixture must exercise a real scroller bottom edge');
await page.pressKey('Enter');
const items = await page.evaluate(`Array.from(document.querySelectorAll('.chat-menu-item'), node => {
const r=node.getBoundingClientRect();
return {text:node.textContent,inside:r.top>=0 && r.bottom<=innerHeight,
hit:node===document.elementFromPoint(r.x+r.width/2,r.y+r.height/2)};
})`);
assert.ok(items.some(item => item.text === 'Reopen'));
assert.ok(items.every(item => item.inside && item.hit), JSON.stringify(items));
await capture(`rows-bottom-menu-${width}`);
await page.evaluate('paint()');
assert.equal(await page.evaluate(`Array.from(document.querySelectorAll('.chat-menu-item')).every(node => {
const r=node.getBoundingClientRect();
return r.top>=0 && r.bottom<=innerHeight && document.elementFromPoint(r.x+r.width/2,r.y+r.height/2)===node;
})`), true, 'open menu re-anchors on a later render');
await page.click('.chat-menu-rename');
assert.equal(await page.evaluate('state.chatRename.id'), 'closed');
assert.equal(await page.evaluate('state.chatActiveId'), 'selected');
assert.deepEqual(await page.evaluate('calls.routes'), []);
await page.resize(width, 844);
await page.evaluate('reset()');
}
await page.emulateTouch();
await page.resize(390, 844);
measurements.push({width:390,coarse:true,rows:await geometry()});
assert.ok((await geometry()).every(row => row.controls.every(button => button.width >= 48 && button.height >= 48)));
assert.ok((await geometry()).every(row => row.topRight && row.bottomRight && row.sameRight && row.logoBeforeTitle && row.logoNonshrink));
await compareStyles(390,true);
await capture('rows-coarse-pointer-390');
// Exactly one route dispatch for a thread click (all action tests dispatched 0).
await page.click('[data-session=selected] .chat-session-button');
assert.deepEqual(await page.evaluate('calls.routes'), [{kind:'chatSession',id:'selected'}]);
await page.click('[data-session=selected] .chat-backend-logo');
assert.deepEqual(await page.evaluate('calls.routes'), [{kind:'chatSession',id:'selected'},{kind:'chatSession',id:'selected'}], 'logo inside native session button dispatches once too');
await writeFile(resolve(out, 'manifest.json'), JSON.stringify({captures, measurements, styleComparisons, widths:[390,420,1100],fixture:'actual createChatView, mock repo/rt, no native chat'}, null, 2));
console.log(`PASS: top-right star, left-before-title logo, bottom-right more, common ghost/row computed styles (${styleComparisons.length} states), no hover reveal, 44/48px targets, keyboard order, shared star API, selected thread retained, single thread/logo click dispatch, bottom menu hit-tests. Captures: ${out}`);
} finally {
mouse?.close();
await browser?.close();
await new Promise(r => server.close(r));
}
-109
View File
@@ -1,109 +0,0 @@
// Actual chat view/event handler with native-shaped usage fixtures. No backend
// connection, provider calls, production chats, or price estimates.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } 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-chat-usage");
await mkdir(out,{recursive:true});
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","chat","dialogs"].map(n=>`<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main class="workspace"><div class="pane-main"><div class="content" id="content"></div></div></main></div>
<script type="module">
import { createChatView } from '/src/views/chat.js';
import { newChatThread } from '/src/chat.js';
import { createModalController } from '/src/modal.js';
const id='scratch';
const state={view:'chat',chatActiveId:id,chatSessions:[{id,title:'Chat usage',backend:'opencode'}],chatOverrides:{},chatDrafts:{},chatThreads:new Map([[id,{...newChatThread(id),loaded:true,messages:[{id:'user',role:'user',parts:[{type:'text',text:'Inspect the results.'}]},{id:'assistant',role:'assistant',parts:[{type:'text',text:'Usage is reported by the harness, not inferred from this answer.'}]}]}]])};
const rt={state,modal:createModalController(),repo:{},renderContent:()=>paint(),closeDetail:()=>{}};
const view=createChatView(rt);
window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation());
window.usage=(snapshot)=>view.onChatEvent({session_id:id,kind:'usage',usage:snapshot});
window.messageCount=()=>state.chatThreads.get(id).messages.length;
window.busyHeader=()=>{const thread=state.chatThreads.get(id);state.chatThreads.set(id,{...thread,hasMore:true,permission:{session_id:id,request_id:'fixture-approval',action:'shell',resources:['echo fixture'],message:'Fixture approval'}});paint();};
paint();
</script>`;
const server=createServer(async(req,res)=>{try{
const path=new URL(req.url,"http://fixture").pathname;
if(path==="/"){res.setHeader("Content-Type","text/html");res.end(html);return;}
const file=resolve(root,`.${path}`);if(!file.startsWith(root+"/"))throw Error("outside fixture");
res.setHeader("Content-Type",extname(file)===".css"?"text/css":"text/javascript");res.end(await readFile(file));
}catch{res.writeHead(404);res.end();}});
await new Promise(r=>server.listen(0,"127.0.0.1",r));
let browser;
const known={scope:"session",total_tokens:132408,context_tokens:42000,context_window:200000,cost_usd:.1423,output_tokens_per_second:24.6,rate_basis:"generation"};
try {
browser=await launchChrome();
const page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector('#chatUsageInfo');
const values=()=>page.evaluate("Array.from(document.querySelectorAll('#chatUsageMetrics dd'),node=>node.textContent)");
for(const width of [390,420,1100]) {
await page.resize(width,844);
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageMetrics').length"),0,'metrics must not consume transcript space by default');
let height=await page.evaluate("document.querySelector('#chatTranscript').getBoundingClientRect().height");
await page.evaluate("usage({scope:'session'})");
await page.screenshot(resolve(out,`usage-collapsed-${width}.png`));
const button=await page.evaluate("(()=>{const b=document.querySelector('#chatUsageInfo').getBoundingClientRect(),bar=document.querySelector('.chat-bar').getBoundingClientRect();return{right:b.right,barRight:bar.right,width:b.width,height:b.height};})()");
assert.ok(button.width>=44&&button.height>=44&&Math.abs(button.right-button.barRight)<=2);
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
assert.deepEqual(await values(),Array(4).fill('Unavailable'));
await page.screenshot(resolve(out,`usage-unavailable-${width}.png`));
await page.pressKey('Escape');
await page.fill('#chatInput','Keep this draft and cursor.');
await page.evaluate("window.savedInput=document.querySelector('#chatInput');savedInput.focus();savedInput.setSelectionRange(5,10);window.savedTranscript=document.querySelector('#chatTranscript')");
height=await page.evaluate("document.querySelector('#chatTranscript').getBoundingClientRect().height");
await page.evaluate(`usage(${JSON.stringify(known)})`);
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageMetrics').length"),0,'hidden stats still update without mounting a rail');
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
await page.evaluate("window.savedClose=document.querySelector('.chat-usage-info-close')");
await page.pressKey('Tab');
assert.equal(await page.evaluate('document.activeElement===savedClose'),true,'keyboard focus stays in the Info panel');
assert.deepEqual(await values(),['24.6 tok/s','132,408','42,000 / 200,000','$0.1423']);
await page.evaluate(`usage(${JSON.stringify({...known,total_tokens:132409})})`);
const intact=await page.evaluate("savedInput===document.querySelector('#chatInput')&&savedClose===document.activeElement&&savedInput.value==='Keep this draft and cursor.'&&savedInput.selectionStart===5&&savedInput.selectionEnd===10&&savedTranscript===document.querySelector('#chatTranscript')");
assert.equal(intact,true,'usage updates must not repaint the composer/transcript');
assert.equal(await page.evaluate("document.querySelector('#chatTranscript').getBoundingClientRect().height"),height,'the overlay must not shrink the conversation');
assert.equal(await page.evaluate('messageCount()'),2);
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),0,'usage must not start a turn');
assert.equal(await page.evaluate('document.documentElement.scrollWidth>innerWidth'),false);
await page.screenshot(resolve(out,`usage-reported-${width}.png`));
await page.evaluate(`usage(${JSON.stringify(known)})`);
assert.deepEqual(await values(),['24.6 tok/s','132,408','42,000 / 200,000','$0.1423']);
await page.evaluate("usage({scope:'session',total_tokens:140000,context_tokens:3000,context_window:1048576})");
assert.deepEqual(await values(),['Unavailable','140,000','3,000 / 1,048,576','Unavailable']);
await page.screenshot(resolve(out,`usage-partial-native-${width}.png`));
await page.evaluate("usage({scope:'session',total_tokens:0,context_tokens:0,context_window:200000,cost_usd:0,output_tokens_per_second:0})");
assert.deepEqual(await values(),['0 tok/s','0','0 / 200,000','$0.0000']);
await page.screenshot(resolve(out,`usage-reported-zero-${width}.png`));
await page.pressKey('Escape');
assert.equal(await page.evaluate("document.activeElement.id"),'chatUsageInfo');
assert.equal(await page.evaluate("document.querySelector('#chatUsageInfo').getAttribute('aria-expanded')"),'false');
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
await page.evaluate('history.back()');
await page.evaluate('new Promise(r=>setTimeout(r,100))');
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageInfoPanel').length"),0);
assert.equal(await page.evaluate("document.querySelector('#chatUsageInfo').getAttribute('aria-expanded')"),'false');
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
await page.click('.chat-usage-info-close');
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageInfoPanel').length"),0);
}
await page.resize(390,500);
await page.evaluate(`usage(${JSON.stringify(known)})`);
assert.equal(await page.evaluate("document.querySelector('#chatComposer').getBoundingClientRect().bottom<=innerHeight"),true);
assert.equal(await page.evaluate('document.documentElement.scrollWidth>innerWidth'),false);
await page.screenshot(resolve(out,'usage-short-viewport-390.png'));
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
assert.equal(await page.evaluate("document.querySelector('.chat-usage-info-panel').getBoundingClientRect().right<=innerWidth"),true);
await page.screenshot(resolve(out,'usage-info-short-viewport-390.png'));
await page.evaluate("document.querySelector('#chatUsageInfoPanel').click()");
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageInfoPanel').length"),0);
await page.resize(390,844);await page.evaluate('busyHeader()');
const crowded=await page.evaluate("(()=>{const b=document.querySelector('#chatUsageInfo').getBoundingClientRect(),bar=document.querySelector('.chat-bar').getBoundingClientRect();return Math.abs(b.right-bar.right)<=2&&document.documentElement.scrollWidth<=innerWidth;})()");
assert.equal(crowded,true,'Info remains top-right with history and approval controls');
await page.screenshot(resolve(out,'usage-info-crowded-mobile-toolbar.png'));
console.log('PASS: metrics are hidden behind a top-right Info button, update live in a non-reflowing panel, preserve draft/cursor/transcript, and close via Escape, browser Back and backdrop with correct focus/state.');
} finally {await browser?.close();await new Promise(r=>server.close(r));}
File diff suppressed because it is too large Load Diff
-84
View File
@@ -1,84 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { applyChatEvent, newChatThread, threadPhase, turnPhaseLabel, settledThread, resumedThread, historyResync, runningAfterFrame, queuedAfterFrame } from "../src/chat.js";
const compact = (status, id="compact-1", session="session-1") => ({session_id:session,kind:"compaction",compaction:{status,id}});
test("silence or model-authored text never invents compaction activity", () => {
const thread={...newChatThread("session-1"),running:true,runningSince:1,messages:[{role:"assistant",parts:[{type:"text",text:"Compacting context"}]}]};
assert.equal(threadPhase(thread,10_000_000),"thinking");
});
test("native compaction shows an explicit phase without inventing a tool or message", () => {
const original={...newChatThread("session-1"),loaded:true,queued:true};
const current=applyChatEvent(original,compact("running"),100);
assert.equal(current.running,true);
assert.equal(current.queued,true);
assert.equal(threadPhase(current,200),"compacting");
assert.equal(turnPhaseLabel(threadPhase(current,200)),"Compacting context…");
assert.deepEqual(current.messages,[]);
assert.equal(runningAfterFrame(false,compact("running")),true);
assert.equal(queuedAfterFrame(true,compact("running")),true);
});
test("compaction takes priority over old reasoning and tool activity", () => {
const current=applyChatEvent({...newChatThread("session-1"),running:true,messages:[{role:"assistant",parts:[{type:"tool",state:{status:"running"}}]}]},compact("running"),100);
assert.equal(threadPhase(current,200),"compacting");
const completed=applyChatEvent(current,compact("completed"),300);
assert.equal(completed.compaction,null);
assert.equal(completed.running,true);
assert.equal(threadPhase(completed,400),"tool");
});
test("a terminal compaction update does not complete the surrounding model turn", () => {
for (const status of ["completed","failed"]) {
const current=applyChatEvent(newChatThread("session-1"),compact("running"),100);
const next=applyChatEvent(current,compact(status),200);
assert.equal(next.compaction,null);
assert.equal(next.running,true);
assert.equal(threadPhase(next,250),"thinking");
assert.equal(runningAfterFrame(true,compact(status)),true);
}
});
test("other-session events and late completions cannot clear a newer compaction", () => {
const current=applyChatEvent(newChatThread("session-1"),compact("running","new"),100);
assert.equal(applyChatEvent(current,compact("completed","old"),200),current);
assert.equal(applyChatEvent(current,compact("running","other","session-2"),200),current);
assert.equal(applyChatEvent(current,compact("unrecognised"),200),current);
});
test("turn completion, interruption, and reconnect clear stale compaction state", () => {
const current=applyChatEvent(newChatThread("session-1"),compact("running"),100);
for (const next of [settledThread(current),resumedThread(current),historyResync(current,{messages:[]}),applyChatEvent(current,{kind:"step",step:{status:"ended"}},200)]) {
assert.equal(next.compaction,null);
assert.equal(threadPhase(next,300),null);
}
const intermediate=applyChatEvent(current,{kind:"step",step:{status:"ended",intermediate:true}},200);
assert.equal(threadPhase(intermediate,300),"compacting");
});
test("authoritative history cannot erase fresh compaction replayed after reconnect reset", () => {
const old=applyChatEvent(newChatThread("session-1"),compact("running","old"),100);
const reset=resumedThread(old);
const replayed=applyChatEvent(reset,compact("running","fresh"),200);
const synced=historyResync(replayed,{messages:[{id:"native-history",role:"user",parts:[]}]},{preserveActivity:true});
assert.equal(threadPhase(synced,300),"compacting");
assert.equal(synced.compaction.id,"fresh");
assert.deepEqual(synced.messages,[{id:"native-history",role:"user",parts:[]}]);
assert.equal(historyResync(reset,{messages:[]},{preserveActivity:true}).compaction,null);
});
test("native turn identity protects compaction and allows the reattached turn to settle", () => {
const original={...newChatThread("session-1"),running:true,nativeTurnId:"new-turn"};
const old={...compact("running"),native_turn_id:"old-turn"};
assert.equal(applyChatEvent(original,old,100),original);
const reset=resumedThread(original);
assert.equal(reset.nativeTurnId,"");
const replay=applyChatEvent(reset,{...compact("running"),native_turn_id:"current-turn"},200);
assert.equal(replay.nativeTurnId,"current-turn");
assert.equal(applyChatEvent(replay,{...compact("completed"),native_turn_id:"old-turn"},300),replay);
const ended=applyChatEvent(replay,{kind:"step",step:{status:"ended",turn_id:"current-turn"}},400);
assert.equal(ended.running,false);
assert.equal(ended.compaction,null);
});
-26
View File
@@ -1,26 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {formFieldValue,formAnswerError,visibleFormAnswers,safeFormURL} from '../src/chatForms.js';
test('typed questions preserve false and zero, and reject invalid numeric answers',()=>{
const fields=[{key:'yes',type:'boolean',required:true},{key:'count',type:'integer',required:true,minimum:0,maximum:5}];
const answers={yes:formFieldValue(fields[0],'false'),count:formFieldValue(fields[1],'0')};
assert.deepEqual(answers,{yes:false,count:0});
assert.equal(formAnswerError(fields,answers),'');
assert.match(formAnswerError(fields,{...answers,count:1.5}),/integer/);
assert.match(formAnswerError(fields,{...answers,count:6}),/at most/);
assert.match(formAnswerError(fields,{...answers,count:NaN}),/valid/);
});
test('conditional and hidden fields never send stale answers',()=>{
const fields=[{key:'yes',type:'boolean'},{key:'extra',type:'string',required:true,when:[{key:'yes',op:'eq',value:true}]},{key:'hidden',hidden:true}];
const answers={yes:false,extra:'stale',hidden:'hidden'};
assert.deepEqual(visibleFormAnswers(fields,answers),{yes:false});
assert.equal(formAnswerError(fields,answers),'');
assert.match(formAnswerError(fields,{yes:true}),/extra/);
});
test('external question links accept only explicit HTTP(S) URLs',()=>{
assert.equal(safeFormURL('https://example.test/form'),'https://example.test/form');
for(const value of ['javascript:alert(1)','file:///etc/passwd','//example.test','bad'])assert.equal(safeFormURL(value),null);
});
-39
View File
@@ -1,39 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms, approvalCard, applyChatEvent } from '../src/chat.js';
test('parallel approvals stay independently actionable and resolve by identity',()=>{
let thread={};
for(const id of ['a','b']) thread=applyChatPermission(thread,{session_id:'s',request_id:id,action:'shell'});
assert.deepEqual(chatApprovalCards(thread).map(c=>c.requestId),['a','b']);
thread=applyChatPermission(thread,{session_id:'s',request_id:'a',resolved:true});
assert.deepEqual(chatApprovalCards(thread).map(c=>c.requestId),['b']);
thread=applyChatPermission(thread,{session_id:'s',request_id:'b',resolved:true});
assert.deepEqual(chatApprovalCards(thread),[]);
});
test('native turn identity rejects late completion and resync preserves queued intent',()=>{
let thread=applyChatEvent({messages:[],queued:true},{kind:'step',step:{status:'started',turn_id:'new'}},1);
thread={...thread,queued:true};
assert.equal(applyChatEvent(thread,{kind:'resync'}),thread);
thread=applyChatEvent(thread,{kind:'step',step:{status:'ended',turn_id:'old'}},2);
assert.equal(thread.running,true);
assert.equal(thread.queued,true);
thread=applyChatEvent(thread,{kind:'step',step:{status:'ended',turn_id:'new'}},3);
assert.equal(thread.running,false);
});
test('Codex session-scoped approval is never described as a permanent grant',()=>{
const card=approvalCard({request_id:'a',always_label:'Allow for session',resolved:true,decision:'always'},'');
assert.equal(card.headline,'Allowed for session');
});
test('parallel questions survive replies and cancellation of a different question',()=>{
let thread={};
for(const id of ['a','b']) thread=applyChatForm(thread,{id,session_id:'s',fields:[]});
assert.deepEqual(chatPendingForms(thread).map(f=>f.id),['a','b']);
thread=applyChatForm(thread,{id:'a',resolved:true});
assert.deepEqual(chatPendingForms(thread).map(f=>f.id),['b']);
thread=applyChatForm(thread,{id:'b',cancelled:true});
assert.deepEqual(chatPendingForms(thread),[]);
});
-29
View File
@@ -1,29 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { chatModelLabel, chatModelSelectionNote, supportsChatModels } from "../src/chatModels.js";
import { PipelinesRepository } from "../src/repository.js";
test("OpenCode, Codex and Claude expose model selection, unknown backends do not", () => {
for (const backend of [undefined, "", "opencode", "codex", "claude"]) assert.equal(supportsChatModels(backend), true);
for (const backend of ["unknown"]) assert.equal(supportsChatModels(backend), false);
});
test("model control distinguishes saved next-turn choice from remote current model", () => {
assert.equal(chatModelLabel({ model: "fixture-current" }), "fixture-current");
assert.equal(chatModelLabel({ model: "fixture-selected", model_selection: "next_turn" }), "fixture-selected · next turn");
assert.equal(chatModelLabel({ model: null }), "Model");
assert.match(chatModelSelectionNote("codex"), /Saved by Pipelines for the next turn/);
assert.match(chatModelSelectionNote("codex"), /Does not resume/);
assert.match(chatModelSelectionNote("claude"), /Does not edit your global Claude Code configuration/);
});
test("model switch reply preserves local next-turn acknowledgement", async () => {
let sent;
const repo = new PipelinesRepository({ call: async (request) => {
sent = request;
return { chat_model: { ...request.chat_model, selection: "next_turn" } };
} });
const selected = await repo.switchChatModel("fixture-thread", "fixture-provider", "fixture-model");
assert.deepEqual(sent.chat_model, { session_id: "fixture-thread", provider: "fixture-provider", model: "fixture-model" });
assert.equal(selected.selection, "next_turn");
});
-36
View File
@@ -1,36 +0,0 @@
// Starred chats are a local preference: a set of session ids, always at the top.
import { test } from "node:test";
import assert from "node:assert/strict";
import { CHAT_STARS_KEY, readChatStars, writeChatStars } from "../src/chatStars.js";
function fakeStorage(initial = {}) {
const values = new Map(Object.entries(initial));
return {
getItem: (key) => (values.has(key) ? values.get(key) : null),
setItem: (key, value) => values.set(key, String(value)),
values,
};
}
test("no stored stars is an empty set", () => {
assert.equal(readChatStars(fakeStorage()).size, 0);
});
test("stars survive a write and read", () => {
const storage = fakeStorage();
writeChatStars(new Set(["ses_a", "ses_b"]), storage);
assert.deepEqual([...readChatStars(storage)].sort(), ["ses_a", "ses_b"]);
assert.ok(storage.values.get(CHAT_STARS_KEY).includes("ses_a"));
});
test("malformed or non-string entries are ignored", () => {
assert.equal(readChatStars(fakeStorage({ [CHAT_STARS_KEY]: "{oops" })).size, 0);
const stars = readChatStars(fakeStorage({ [CHAT_STARS_KEY]: JSON.stringify(["a", 3, "", null]) }));
assert.deepEqual([...stars], ["a"]);
});
test("storage failures never break the list", () => {
const broken = { getItem() { throw new Error("denied"); }, setItem() { throw new Error("denied"); } };
assert.equal(readChatStars(broken).size, 0);
assert.doesNotThrow(() => writeChatStars(new Set(["a"]), broken));
});
-69
View File
@@ -1,69 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { chatUsageMetrics, normalizeChatUsage } from "../src/chatUsage.js";
import { newChatThread, applyChatEvent, settledThread, resumedThread, historyResync, queuedAfterFrame } from "../src/chat.js";
const snapshot = {scope:"session",total_tokens:132408,context_tokens:42000,context_window:200000,cost_usd:0.1423,output_tokens_per_second:24.6,rate_basis:"generation"};
const event = (usage) => ({session_id:"chat",kind:"usage",usage});
test("usage metrics format native counters without conflating context and processed totals", () => {
const rows=chatUsageMetrics(snapshot,"en-US");
assert.deepEqual(rows.map(row=>row.value),["24.6 tok/s","132,408","42,000 / 200,000","$0.1423"]);
assert.ok(rows.every(row=>row.available));
assert.match(rows[0].title,/native request-to-stream-completion/);
});
test("unreported values stay unavailable, including legacy zero or unsupported subscription costs", () => {
assert.ok(chatUsageMetrics(null).every(row=>row.value==="Unavailable"));
assert.ok(chatUsageMetrics({input_tokens:100,output_tokens:50,cost:0}).every(row=>!row.available));
const codex=chatUsageMetrics({scope:"session",total_tokens:1000,context_window:128000},"en-US");
assert.equal(codex[3].value,"Unavailable");
assert.equal(codex[2].value,"128,000 limit");
assert.equal(codex[0].value,"Unavailable");
});
test("reported zeros are not missing and tiny positive values are not displayed as zero", () => {
const zero=chatUsageMetrics({scope:"session",total_tokens:0,context_tokens:0,context_window:1000,cost_usd:0,output_tokens_per_second:0},"en-US");
assert.deepEqual(zero.map(row=>row.value),["0 tok/s","0","0 / 1,000","$0.0000"]);
const small=chatUsageMetrics({cost_usd:0.00000001,output_tokens_per_second:0.01},"en-US");
assert.equal(small[0].value,"<0.1 tok/s");
assert.equal(small[3].value,"<$0.000001");
});
test("invalid, fractional or unsafe counters are never turned into fabricated metrics", () => {
const invalid=normalizeChatUsage({scope:"session",total_tokens:1.5,context_tokens:-1,context_window:0,cost_usd:Infinity,output_tokens_per_second:"100"});
assert.ok(chatUsageMetrics(invalid).every(row=>!row.available));
assert.equal(normalizeChatUsage({total_tokens:Number.MAX_SAFE_INTEGER+1}),null);
assert.equal(normalizeChatUsage([]),null);
});
test("usage snapshots replace counters, preserve queue/turn state and do not create messages", () => {
const original={...newChatThread("chat"),queued:true};
const once=applyChatEvent(original,event(snapshot));
const twice=applyChatEvent(once,event(snapshot));
assert.equal(twice.usage.total_tokens,132408);
assert.equal(twice.queued,true);
assert.equal(twice.running,false);
assert.deepEqual(twice.messages,[]);
assert.equal(queuedAfterFrame(true,event(snapshot)),true);
const next=applyChatEvent(twice,event({...snapshot,total_tokens:133000,context_tokens:3000}));
assert.equal(next.usage.total_tokens,133000);
assert.equal(next.usage.context_tokens,3000);
assert.equal(applyChatEvent(next,{...event(snapshot),session_id:"other"}),next);
});
test("last reported metrics survive idle, history refresh and reconnect without being summed", () => {
const thread=applyChatEvent(newChatThread("chat"),event(snapshot));
for(const result of [settledThread(thread),resumedThread(thread),historyResync(thread,{messages:[]})]) {
assert.equal(result.usage.total_tokens,132408);
assert.equal(result.usage.cost_usd,0.1423);
}
const unknown=applyChatEvent(thread,event({scope:"session"}));
assert.ok(chatUsageMetrics(unknown.usage).every(row=>!row.available));
});
test("turn-wall-time averages are labeled rather than presented as pure model generation speed", () => {
const rate=chatUsageMetrics({...snapshot,rate_basis:"turn"})[0];
assert.equal(rate.label,"Avg output rate");
assert.match(rate.title,/including tools and waiting/);
});
-252
View File
@@ -1,252 +0,0 @@
// Client transport tests against a fake WebSocket: id matching, serialization,
// error replies, timeouts and the not-connected guard. No server required.
import { test } from "node:test";
import assert from "node:assert/strict";
import { PipelinesClient, ProtocolError, NotConnectedError } from "../src/client.js";
import { validateServerUrl } from "../src/serverUrl.js";
const VALID = validateServerUrl("ws://host:8080/connect");
class FakeWebSocket {
static instances = [];
constructor(url) {
this.url = url;
this.sent = [];
this.closed = null;
this.onopen = null;
this.onmessage = null;
this.onclose = null;
this.onerror = null;
/** @type {((frame: any) => any | undefined) | null} */
this.reply = null;
FakeWebSocket.instances.push(this);
}
send(data) {
const frame = JSON.parse(data);
this.sent.push(frame);
const response = this.reply?.(frame);
if (response !== undefined) {
this.onmessage?.({ data: JSON.stringify(response) });
}
}
close(code, reason) {
this.closed = { code, reason };
this.onclose?.({ code, reason });
}
// test hooks
open() {
this.onopen?.({});
}
push(obj) {
this.onmessage?.({ data: JSON.stringify(obj) });
}
drop(code = 1006) {
this.onclose?.({ code, reason: "test" });
}
}
/** Let the client's serialized call chain run to the point where it has sent. */
const flush = () => new Promise((resolve) => setImmediate(resolve));
function freshClient(options = {}) {
FakeWebSocket.instances = [];
return new PipelinesClient({ WebSocketImpl: FakeWebSocket, ...options });
}
function connectedClient(options = {}) {
const client = freshClient(options);
client.connect(VALID);
const ws = FakeWebSocket.instances.at(-1);
ws.open();
return { client, ws };
}
test("a call before connect is rejected as not connected", async () => {
const client = freshClient();
await assert.rejects(() => client.call({ type: "ping" }), NotConnectedError);
});
test("a call sends a JSON frame with a generated id and resolves the matching reply", async () => {
const { client, ws } = connectedClient();
ws.reply = (frame) => ({ id: frame.id, type: "pong" });
const reply = await client.call({ type: "ping" });
assert.equal(reply.type, "pong");
assert.equal(ws.sent.length, 1);
assert.equal(ws.sent[0].type, "ping");
assert.match(ws.sent[0].id, /^web-\d+$/);
});
test("an error reply surfaces the server text as a ProtocolError", async () => {
const { client, ws } = connectedClient();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "nope" });
await assert.rejects(() => client.call({ type: "get_run" }), ProtocolError);
});
test("an unsolicited envelope is surfaced as a frame event and not misattributed", async () => {
const { client, ws } = connectedClient();
ws.reply = undefined;
const frames = [];
client.addEventListener("frame", (event) => frames.push(event.detail));
const pending = client.call({ type: "ping" });
let settled = false;
pending.then(() => (settled = true), () => (settled = true));
await flush();
ws.push({ type: "pipelines", pipelines: [] }); // no id
await flush();
assert.equal(settled, false);
assert.deepEqual(frames, [{ type: "pipelines", pipelines: [] }]);
const frame = ws.sent.at(-1);
ws.push({ id: frame.id, type: "pong" });
assert.equal((await pending).type, "pong");
// A matched reply is not also broadcast as an unsolicited frame.
assert.equal(frames.length, 1);
});
test("a server-pushed chat_event frame reaches a frame listener", async () => {
const { client, ws } = connectedClient();
const frames = [];
client.addEventListener("frame", (event) => frames.push(event.detail));
ws.push({
type: "chat_event",
chat_event: { session_id: "ses_1", message_id: "a1", kind: "text", delta: "hi" },
});
await flush();
assert.equal(frames.length, 1);
assert.equal(frames[0].type, "chat_event");
assert.equal(frames[0].chat_event.session_id, "ses_1");
});
test("sendOnly sends a frame, returns its id and never waits for a reply", () => {
const { client, ws } = connectedClient();
const frames = [];
client.addEventListener("frame", (event) => frames.push(event.detail));
// No reply is scripted: a send-only frame must not hang the caller.
const id = client.sendOnly({ type: "subscribe", workspace: "" });
assert.match(id, /^web-\d+$/);
assert.deepEqual(ws.sent, [{ type: "subscribe", workspace: "", id }]);
// A server that does ack (or refuse) still reaches the app as an unsolicited
// frame carrying that id, not as a resolved request.
ws.push({ id, type: "subscribe" });
assert.equal(frames.length, 1);
assert.equal(frames[0].type, "subscribe");
});
test("sendOnly before connect is rejected as not connected", () => {
const client = freshClient();
assert.throws(() => client.sendOnly({ type: "subscribe" }), NotConnectedError);
});
test("back-to-back sendOnly frames keep their order on the wire", () => {
const { client, ws } = connectedClient();
client.sendOnly({ type: "unsubscribe" });
client.sendOnly({ type: "subscribe", workspace: "" });
assert.deepEqual(
ws.sent.map((frame) => frame.type),
["unsubscribe", "subscribe"],
);
});
test("a server-pushed run_event frame reaches a frame listener", async () => {
const { client, ws } = connectedClient();
const frames = [];
client.addEventListener("frame", (event) => frames.push(event.detail));
ws.push({ type: "run_event", run_event: { run_id: 7, status: "running" } });
await flush();
assert.equal(frames.length, 1);
assert.equal(frames[0].type, "run_event");
assert.equal(frames[0].run_event.run_id, 7);
});
test("a malformed frame is ignored and does not reject a pending call", async () => {
const { client, ws } = connectedClient();
const pending = client.call({ type: "ping" });
await flush();
ws.onmessage?.({ data: "{not json" });
const frame = ws.sent.at(-1);
ws.push({ id: frame.id, type: "pong" });
assert.equal((await pending).type, "pong");
});
test("a missing reply times out with a clear error", async () => {
const { client } = connectedClient({ requestTimeoutMs: 20 });
await assert.rejects(() => client.call({ type: "ping" }), /timed out after 20ms/);
});
test("concurrent calls are serialized in submission order", async () => {
const { client, ws } = connectedClient();
const order = [];
ws.reply = (frame) => {
order.push(frame.type);
return { id: frame.id, type: "ok" };
};
await Promise.all([client.call({ type: "a" }), client.call({ type: "b" })]);
assert.deepEqual(order, ["a", "b"]);
});
test("the state flow reports connecting then connected", async () => {
const seen = [];
const client = freshClient();
client.addEventListener("state", (e) => seen.push(e.detail.kind));
client.connect(VALID);
FakeWebSocket.instances.at(-1).open();
assert.deepEqual(seen, ["connecting", "connected"]);
});
test("an unexpected close fails pending calls and schedules a reconnect", async () => {
const { client, ws } = connectedClient({ backoffBaseMs: 1, backoffMaxMs: 5 });
const pending = client.call({ type: "ping" }); // never answered
await flush(); // let the call reach the socket before it is dropped
ws.drop(1006);
await assert.rejects(() => pending, /Connection closed/);
assert.equal(client.state.kind, "disconnected");
assert.equal(client.state.retrying, true);
client.disconnect(); // stop the reconnect timer before the test ends
});
test("disconnect goes idle and does not schedule a reconnect", () => {
const { client, ws } = connectedClient();
client.disconnect();
assert.equal(client.state.kind, "idle");
assert.equal(client.state.retrying, false);
assert.deepEqual(ws.closed, { code: 1000, reason: "client closing" });
});
test("connecting again replaces the socket and ignores the superseded one", async () => {
// The Settings `Connect` action is connect-only and must be safe to press while
// connected: it re-opens the endpoint (Android's connectLocked replaces the
// socket) instead of leaving two live sockets or letting the old one's late
// close mark the new connection disconnected.
const { client, ws } = connectedClient();
const pending = client.call({ type: "ping" }); // sent on the old socket
await flush();
client.connect(VALID);
const replacement = FakeWebSocket.instances.at(-1);
assert.notEqual(replacement, ws);
assert.equal(client.state.kind, "connecting");
await assert.rejects(() => pending, /Connection replaced/);
assert.deepEqual(ws.closed, { code: 1000, reason: "superseded" });
replacement.open();
assert.equal(client.state.kind, "connected");
// The superseded socket's late failure must not touch the live connection.
ws.drop(1006);
assert.equal(client.state.kind, "connected");
assert.equal(client.state.retrying, false);
});
-130
View File
@@ -1,130 +0,0 @@
// Scratch-only ui-smoke extension: real chat view/input handlers, no backend,
// workflows, services or devices. --before serves HEAD's CSS for comparison.
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { resolve, extname } from 'node:path';
import { launchChrome } from './browser.mjs';
const root = resolve(import.meta.dirname, '..');
const out = resolve(process.argv[2] || '.ui-composer-fit');
const before = process.argv.includes('--before');
await mkdir(out, { recursive: true });
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','chat','dialogs'].map(n => `<link rel="stylesheet" href="/${n}.css">`).join('')}
<div class="app-root"><main class="workspace"><div class="pane-main"><div class="content" id="content"></div></div></main></div>
<script type="module">
import { createChatView } from '/src/views/chat.js';
const id='scratch';
const state={view:'chat',chatActiveId:id,chatSessions:[{id,title:'Composer fit review',backend:'codex'}],
chatOverrides:{},chatDrafts:{},chatThreads:new Map([[id,{loaded:true,draft:'',messages:[{id:'m',role:'user',parts:[{type:'text',text:'Please review the composer alignment.'}]}],attachments:[],notices:[],running:false}]])};
const rt={state,repo:{},renderContent:()=>paint(),closeDetail:()=>{}};
const view=createChatView(rt);
window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation());
window.setRunning=(running)=>{state.chatThreads.get(id).running=running;document.querySelector('#chatInput').dispatchEvent(new Event('input',{bubbles:true}));};
window.setAttachment=()=>{state.chatThreads.get(id).attachments=[{id:'a',name:'draft-layout-reference-with-a-long-file-name.txt',size:1024,mime:'text/plain'}];paint();};
paint();window.fixtureState=state;
</script>`;
const server = createServer(async (req, res) => {
try {
if (req.url === '/') { res.setHeader('content-type','text/html'); res.end(html); return; }
const path = resolve(root, `.${new URL(req.url,'http://scratch').pathname}`);
if (!path.startsWith(root + '/')) throw new Error('outside root');
res.setHeader('content-type',extname(path)==='.css'?'text/css':'text/javascript');
res.end(before && path===resolve(root,'chat.css') ? execFileSync('git',['show','HEAD:web/chat.css'],{cwd:root}) : await readFile(path));
} catch { res.writeHead(404); res.end(); }
});
await new Promise(r=>server.listen(0,'127.0.0.1',r));
let browser;
const measurements=[];
try {
browser=await launchChrome();
const page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector('#chatInput');
const measure=()=>page.evaluate(`(() => {
const rect=s=>{const e=document.querySelector(s);if(!e)return null;const r=e.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height,bottom:r.bottom,right:r.right};};
const input=document.querySelector('#chatInput'),s=getComputedStyle(input);
return {input:rect('#chatInput'),attach:rect('#chatAttach'),send:rect('#chatSend'),stop:rect('#chatStop'),
header:rect('.chat-bar'),composer:rect('#chatComposer'),scroll:input.scrollHeight,client:input.clientHeight,
line:parseFloat(s.lineHeight),padding:parseFloat(s.paddingTop)+parseFloat(s.paddingBottom),
overflow:s.overflowY,documentWidth:document.documentElement.scrollWidth,viewport:innerWidth};
})()`);
const capture=async(name)=>{
await page.evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');
const m=await measure(); measurements.push({name,...m});
await page.screenshot(resolve(out,name+'.png'));
if (!before) {
assert.ok(m.documentWidth<=m.viewport,`${name}: document overflow`);
for(const b of [m.attach,m.send,m.stop].filter(Boolean)) {
assert.ok(b.width>=44 && b.height>=44,`${name}: touch target`);
const controlCenter=b.y+b.height/2;
const inputCenter=m.input.y+m.input.height/2;
assert.ok(Math.abs(controlCenter-inputCenter)<=1,`${name}: vertical center alignment`);
}
assert.equal(m.send.width,m.attach.width);
assert.ok(m.input.right+8<=m.send.x,`${name}: input/action overlap`);
assert.ok(m.composer.bottom<= (name.includes('keyboard') && m.viewport<600?500:900),`${name}: visible composer`);
}
return m;
};
for(const width of [390,420,1100]) {
await page.resize(width,900);
await page.goto(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector('#chatInput');
const empty=await capture(`empty-${width}`);
if(!before) assert.equal(empty.input.height,empty.send.height,'empty placeholder must fit one aligned line');
await page.fill('#chatInput','Review this draft');
await capture(`single-${width}`);
await page.fill('#chatInput','First draft line\nSecond draft line\nThird draft line');
const idle=await capture(`multiline-${width}`);
await page.evaluate('setRunning(true)');
const running=await capture(`running-${width}`);
if(!before) {
assert.deepEqual(running.input,idle.input,'running must not rewrap or move draft');
assert.equal(running.stop.width,running.send.width);
assert.deepEqual(running.header,idle.header,'header unchanged');
assert.ok(running.scroll<=running.client,'three full lines fit');
}
await page.evaluate('setRunning(false)');
const settled=await measure();
if(!before) {
assert.deepEqual(settled.input,idle.input,'settling must not move draft');
assert.equal(settled.stop,null);
assert.equal(await page.evaluate('document.activeElement.id'),'chatInput');
}
await page.evaluate('setRunning(true)');
await page.fill('#chatInput','Line one\nLine two\nLine three\nLine four\nLine five\nLine six');
const six=await capture(`six-lines-${width}`);
if(!before) assert.equal(six.input.height,6*six.line+six.padding+2,'six complete lines fit');
await page.fill('#chatInput',Array(10).fill('Long draft line').join('\n'));
const long=await capture(`long-draft-${width}`);
if(!before) { assert.equal(long.overflow,'auto');assert.equal(long.input.height,six.input.height); }
await page.fill('#chatInput','First draft line\nSecond draft line');
{
// Deterministic existing keyboard CSS geometry, not a real OS keyboard.
await page.evaluate(`document.documentElement.classList.add('keyboard-open');document.documentElement.style.setProperty('--keyboard-visible-height','500px');document.documentElement.style.setProperty('--keyboard-viewport-top','0px')`);
await capture(`keyboard-${width}`);
await page.evaluate(`document.documentElement.classList.remove('keyboard-open')`);
}
await page.evaluate('setAttachment()');
await capture(`attachment-${width}`);
}
if(!before) {
await page.emulateTouch(true);
for(const width of [390,420]) {
await page.resize(width,900);await page.goto(`http://127.0.0.1:${server.address().port}/`);await page.waitForSelector('#chatInput');
assert.equal(await page.evaluate("matchMedia('(any-pointer: coarse)').matches"),true);
const touch=await capture(`touch-empty-${width}`);
assert.equal(touch.send.width,48);assert.equal(touch.input.height,48);
await page.evaluate('setRunning(true)');
const running=await capture(`touch-running-${width}`);
assert.equal(running.stop.width,48);assert.deepEqual(running.input,touch.input);
}
}
await writeFile(resolve(out,'geometry.json'),JSON.stringify(measurements,null,2));
console.log(`${measurements.length} scratch captures and geometry: ${out}`);
} finally {
if(browser) await browser.close();
await new Promise(r=>server.close(r));
}
-232
View File
@@ -1,232 +0,0 @@
// Unit tests for the pure connection helpers (src/connection.js): the banner
// state derivation, the return-to-foreground policy, the ping-reply protocol
// comparison, the server build label and the live badge. No DOM, no socket, no
// timer: `node --test test/connection.test.mjs` proves the logic the page wires
// up, so the browser run only has to prove the rendering.
//
// The wording is asserted against the Android client's own strings
// (ConnectionBanner.kt, ConnectionRecovery.kt, SettingsScreen.kt,
// LiveBadge.kt/RunStream.kt); the last test reads those sources so a rename
// there cannot silently drift past this one.
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import {
ForegroundAction,
IDLE_BANNER_TEXT,
RETRYING_SUFFIX,
RunStream,
bannerState,
foregroundAction,
liveBadgeState,
protocolMismatch,
serverBuildLabel,
stateBadge,
} from "../src/connection.js";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
const source = (rel) => readFileSync(resolve(ROOT, rel), "utf8");
const androidSrc = (rel) =>
source(`android/app/src/main/java/net/awan/pipelines/${rel}`);
// ---------------------------------------------------------------------------
// bannerState
// ---------------------------------------------------------------------------
test("idle banner uses the app's settings wording and offers Reconnect with an endpoint", () => {
const withEndpoint = bannerState({ kind: "idle", attempt: 0, reason: "", retrying: false }, { hasEndpoint: true });
assert.equal(withEndpoint.tone, "idle");
assert.equal(withEndpoint.text, "Not connected. Enter the server URL in Settings, then connect.");
assert.equal(withEndpoint.action, "Reconnect");
const without = bannerState({ kind: "idle" }, { hasEndpoint: false });
assert.equal(without.text, IDLE_BANNER_TEXT);
assert.equal(without.action, null);
});
test("connecting banner names the attempt and offers no action", () => {
const banner = bannerState({ kind: "connecting", attempt: 4, reason: "", retrying: false }, { hasEndpoint: true });
assert.equal(banner.tone, "connecting");
assert.equal(banner.text, "Connecting (attempt 4)\u2026");
assert.equal(banner.action, null);
});
test("disconnected banner carries the reason, the retry suffix and Reconnect", () => {
const retrying = bannerState(
{ kind: "disconnected", attempt: 2, reason: "Connection closed (1006)", retrying: true },
{ hasEndpoint: true },
);
assert.equal(retrying.tone, "error");
assert.equal(retrying.text, `Disconnected: Connection closed (1006)${RETRYING_SUFFIX}`);
assert.equal(retrying.action, "Reconnect");
const settled = bannerState(
{ kind: "disconnected", reason: "Connection closed (1000)", retrying: false },
{ hasEndpoint: true },
);
assert.equal(settled.text, "Disconnected: Connection closed (1000)");
});
test("disconnected banner offers no action without a configured endpoint", () => {
const banner = bannerState({ kind: "disconnected", reason: "boom", retrying: false }, { hasEndpoint: false });
assert.equal(banner.action, null);
});
test("disconnected banner falls back when the reason is blank", () => {
const banner = bannerState({ kind: "disconnected", reason: " ", retrying: false }, { hasEndpoint: true });
assert.equal(banner.text, "Disconnected: connection closed");
});
test("connected banner is an explicit green state with no reconnect action", () => {
const banner = bannerState({ kind: "connected", attempt: 0, reason: "", retrying: false }, { hasEndpoint: true });
assert.equal(banner.tone, "ok");
assert.equal(banner.text, "Connected");
assert.equal(banner.action, null);
});
test("an unknown or missing connection state reads as idle", () => {
assert.equal(bannerState(undefined, { hasEndpoint: false }).tone, "idle");
assert.equal(bannerState({ kind: "something-else" }, { hasEndpoint: false }).tone, "idle");
});
// ---------------------------------------------------------------------------
// stateBadge — the header badge, which alone carries the retry attempt
// ---------------------------------------------------------------------------
test("stateBadge names the disconnected reason, retry and attempt", () => {
const retrying = stateBadge({ kind: "disconnected", attempt: 3, reason: "Connection closed (1006)", retrying: true });
assert.equal(retrying.tone, "bad");
assert.equal(retrying.text, "disconnected — Connection closed (1006) (attempt 3, retrying)");
const settled = stateBadge({ kind: "disconnected", attempt: 2, reason: "boom", retrying: false });
assert.equal(settled.text, "disconnected — boom (attempt 2)");
const attemptsZero = stateBadge({ kind: "disconnected", attempt: 0, reason: "boom", retrying: true });
assert.equal(attemptsZero.text, "disconnected — boom (retrying)");
const bare = stateBadge({ kind: "disconnected", reason: "", retrying: false });
assert.equal(bare.text, "disconnected");
});
test("stateBadge covers the other connection states", () => {
assert.deepEqual(stateBadge({ kind: "connected" }), { tone: "ok", text: "connected" });
assert.deepEqual(stateBadge({ kind: "connecting", attempt: 4 }), { tone: "warn", text: "connecting… (attempt 4)" });
assert.deepEqual(stateBadge({ kind: "idle" }), { tone: "idle", text: "idle" });
assert.deepEqual(stateBadge(undefined), { tone: "idle", text: "idle" });
});
// ---------------------------------------------------------------------------
// foregroundAction — the ConnectionRecovery.kt truth table
// ---------------------------------------------------------------------------
test("foregroundAction leaves Idle alone (a deliberate Disconnect)", () => {
assert.equal(foregroundAction({ kind: "idle" }, false), ForegroundAction.LeaveAlone);
assert.equal(foregroundAction({ kind: "idle" }, true), ForegroundAction.LeaveAlone);
});
test("foregroundAction leaves Connected alone only when confirmed alive", () => {
assert.equal(foregroundAction({ kind: "connected" }, true), ForegroundAction.LeaveAlone);
assert.equal(foregroundAction({ kind: "connected" }, false), ForegroundAction.Reconnect);
});
test("foregroundAction reconnects Connecting and Disconnected whatever the probe says", () => {
assert.equal(foregroundAction({ kind: "connecting", attempt: 2 }, false), ForegroundAction.Reconnect);
assert.equal(foregroundAction({ kind: "disconnected", reason: "x" }, false), ForegroundAction.Reconnect);
assert.equal(foregroundAction({ kind: "disconnected" }, true), ForegroundAction.Reconnect);
});
// ---------------------------------------------------------------------------
// protocolMismatch
// ---------------------------------------------------------------------------
test("protocolMismatch is silent when the server matches or omits the protocol", () => {
assert.equal(protocolMismatch(1, 1), null);
assert.equal(protocolMismatch(1, null), null);
assert.equal(protocolMismatch(1, undefined), null);
assert.equal(protocolMismatch(1, ""), null);
assert.equal(protocolMismatch(null, 2), null);
assert.equal(protocolMismatch(undefined, undefined), null);
});
test("protocolMismatch names both values when they differ", () => {
const warning = protocolMismatch(1, 2);
assert.equal(typeof warning, "string");
assert.ok(warning.includes("1"), warning);
assert.ok(warning.includes("2"), warning);
});
// ---------------------------------------------------------------------------
// serverBuildLabel
// ---------------------------------------------------------------------------
test("serverBuildLabel renders version and commit, SettingsScreen.kt's shape", () => {
assert.equal(serverBuildLabel({ version: "v1.2.3", commit: "abc123", dirty: false }), "Server build v1.2.3 (abc123)");
// A dirty tree is already folded into `version` by internal/buildinfo (-dirty),
// so there is deliberately no second `+dirty` marker on the commit.
assert.equal(serverBuildLabel({ version: "v1.2.3-dirty", commit: "abc123", dirty: true }), "Server build v1.2.3-dirty (abc123)");
assert.equal(serverBuildLabel({ version: "v1.2.3", commit: "abc123", dirty: true }), "Server build v1.2.3 (abc123)");
});
test("serverBuildLabel tolerates missing fields", () => {
assert.equal(serverBuildLabel({ version: "v1" }), "Server build v1");
assert.equal(serverBuildLabel({ commit: "abc" }), "Server build (abc)");
assert.equal(serverBuildLabel({ dirty: true }), "");
assert.equal(serverBuildLabel({}), "");
assert.equal(serverBuildLabel(null), "");
assert.equal(serverBuildLabel(undefined), "");
});
// ---------------------------------------------------------------------------
// liveBadgeState — RunStream.kt words
// ---------------------------------------------------------------------------
test("liveBadgeState maps the explicit stream state to RunStream.kt's words", () => {
// The badge says whether pushes are arriving, independent of any executing run.
assert.deepEqual(liveBadgeState(RunStream.Live), { tone: "live", label: "live" });
assert.deepEqual(liveBadgeState(RunStream.Connecting), { tone: "reconnecting", label: "reconnecting" });
assert.deepEqual(liveBadgeState(RunStream.Offline), { tone: "not-live", label: "not live" });
// An unknown/missing state is honestly not live.
assert.deepEqual(liveBadgeState(undefined), { tone: "not-live", label: "not live" });
assert.deepEqual(liveBadgeState("something-else"), { tone: "not-live", label: "not live" });
});
// ---------------------------------------------------------------------------
// Parity with the Android sources
// ---------------------------------------------------------------------------
test("the wording still matches the Android client's sources", () => {
const banner = androidSrc("ui/components/ConnectionBanner.kt");
assert.ok(banner.includes("Not connected. Enter the server URL in Settings, then connect."), banner.slice(0, 200));
assert.ok(banner.includes('"Connecting (attempt ${state.attempt}') && banner.includes("…"), "connecting copy");
assert.ok(banner.includes('append(" · retrying with backoff")'), "retry suffix");
assert.ok(banner.includes('"Reconnect"'), "reconnect label");
const settings = androidSrc("ui/screens/SettingsScreen.kt");
assert.ok(settings.includes('Text("Connected"'), "connected label");
assert.ok(settings.includes("Server build"), "build label");
// buildinfo folds a dirty tree into `version` via a `-dirty` suffix, which is
// why serverBuildLabel adds no separate dirty marker (SettingsScreen.kt does
// not render one either).
const buildinfo = source("internal/buildinfo/buildinfo.go");
assert.ok(buildinfo.includes('info.Version += "-dirty"'), "buildinfo -dirty suffix");
assert.ok(!settings.includes("dirty"), "SettingsScreen.kt renders no dirty marker");
const recovery = androidSrc("data/transport/ConnectionRecovery.kt");
for (const line of [
"ConnectionState.Idle -> ForegroundAction.LeaveAlone",
"if (confirmedAlive) ForegroundAction.LeaveAlone else ForegroundAction.Reconnect",
"is ConnectionState.Connecting -> ForegroundAction.Reconnect",
"is ConnectionState.Disconnected -> ForegroundAction.Reconnect",
]) {
assert.ok(recovery.includes(line), `ConnectionRecovery.kt is missing: ${line}`);
}
const stream = androidSrc("ui/RunStream.kt");
for (const label of ['Live("live")', 'Connecting("reconnecting")', 'Offline("not live")']) {
assert.ok(stream.includes(label), `RunStream.kt is missing: ${label}`);
}
});
-26
View File
@@ -1,26 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { canCancel } from "../src/actions.js";
import { runStatusLabel } from "../src/runs.js";
import { foldRunEvent, foldRunEventDetail } from "../src/runEvents.js";
test("stop intent stays nonterminal, disables Stop, and folds into live rows", () => {
const run = { id: 4, status: "running", executing: true, steps: [] };
const frame = { run_id: 4, status: "running", cancel_requested: true };
const updated = foldRunEvent([run], frame).runs[0];
assert.equal(updated.status, "running");
assert.equal(updated.executing, true);
assert.equal(canCancel(updated), false);
assert.match(runStatusLabel(updated), /Stopping/);
assert.equal(foldRunEventDetail(run, frame).cancel_requested, true);
});
test("cleanup uncertainty remains visible until a terminal observation", () => {
const run = { id: 4, status: "running", executing: true };
const pending = foldRunEvent([run], { run_id: 4, cleanup_unconfirmed: true }).runs[0];
assert.equal(canCancel(pending), false);
assert.match(runStatusLabel(pending), /Cleanup unconfirmed.*workspace reserved/);
const terminal = foldRunEvent([pending], { run_id: 4, status: "canceled" }).runs[0];
assert.equal(terminal.executing, false);
assert.equal(runStatusLabel(terminal), "canceled");
});
-43
View File
@@ -1,43 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { foldRunEventDetail, foldRunEvent, isTerminalRunStatus } from "../src/runEvents.js";
import { canCancel, canRetry, pendingDecision } from "../src/actions.js";
import { runStatusLabel } from "../src/runs.js";
import { attentionEntries, attentionKindOf } from "../src/attention.js";
import { createAlertLedger } from "../src/notify.js";
test("export waiting remains nonterminal and folds forward without reopening its computed visit", () => {
let run = { id: 7, status: "running", executing: true, steps: [{ sequence: 1, stage: "one", status: "running" }], graph: { stages: [{ key: "one", type: "model", edges: { success: "two", error: "#failure" } }] } };
const waiting = { run_id: 7, status: "waiting", export_pending_sequence: 1, current_stage: "one", step: { sequence: 1, stage: "one", status: "completed", outcome: "success", target: "two" } };
run = foldRunEventDetail(run, waiting);
assert.equal(run.status, "waiting");
assert.equal(run.export_pending_sequence, 1);
assert.equal(run.executing, false);
assert.equal(isTerminalRunStatus(run.status), false);
assert.equal(pendingDecision(run), null);
assert.equal(canCancel(run), true);
assert.equal(canRetry(run), false);
assert.equal(runStatusLabel(run), "Waiting for session export");
assert.equal(attentionKindOf(run.status, run.export_pending_sequence), null);
assert.deepEqual(attentionEntries([run], new Set()), []);
const ledger = createAlertLedger();
ledger.seed([{ id: 7, status: "running" }]);
assert.equal(ledger.observe(waiting), null);
const snapshot = foldRunEvent([], { ...waiting, pipeline_id: 3, name: "gate" }).runs[0];
assert.equal(snapshot.export_pending_sequence, 1);
// Repair-only frames must not clear the pending sequence.
run = foldRunEventDetail(run, { run_id: 7, session_export_updated: true });
assert.equal(run.export_pending_sequence, 1);
run = foldRunEventDetail(run, { run_id: 7, status: "running" });
assert.equal(run.export_pending_sequence, 0);
assert.equal(run.steps[0].status, "completed");
run = foldRunEventDetail(run, { run_id: 7, status: "succeeded", finished_at: "2026-10-20T20:00:00Z" });
assert.equal(run.status, "succeeded");
assert.equal(run.export_pending_sequence, 0);
assert.equal(run.executing, false);
assert.equal(foldRunEventDetail(run, waiting), run);
});
test("model stages never become human decisions via waiting fallback", () => {
assert.equal(pendingDecision({ id: 8, status: "waiting", current_stage: "one", steps: [], graph: { stages: [{ key: "one", type: "model", edges: { success: "two" } }] } }), null);
});
-7
View File
@@ -1,7 +0,0 @@
# Turn input
Plan the next small change.
```sh
go test ./...
```
-3
View File
@@ -1,3 +0,0 @@
# Memory
The previous turn landed the artifact viewer.
-6
View File
@@ -1,6 +0,0 @@
# Output
The change is ready for review.
- viewer renders markdown
- keyboard paging works
Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 B

-546
View File
@@ -1,546 +0,0 @@
// Unit tests for the pure workflow-graph helpers (src/graph.js): node order,
// the terminal row, edge label order and the `error*` fallback marker, lane
// assignment, the node-kind mapping, the stage-definition pane derivation and
// the viewport maths (fitScale/clampOffset/zoomAbout/hitTest). No DOM and no
// server: `node --test test/graph.test.mjs` proves the module's maths is pure.
// Wording is asserted against the Android app's own strings (WorkflowGraph.kt,
// GraphPalette.kt, GraphSemantics.kt, StageDetailPane.kt, RunGraphTab.kt).
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import {
MIN_SCALE,
MAX_SCALE,
PIPELINE_GRAPH_EMPTY,
RUN_GRAPH_MISSING,
NO_NODE_DETAILS,
STAGE_DEFINITION_TITLE,
configLabel,
edgeLabel,
graphEdges,
graphNodeKind,
labelWidthFor,
graphDescription,
hitTest,
layoutGraph,
mount,
nodeDisplayLabel,
nodeKindClass,
stageDefinitionFields,
stageOutcomes,
terminalFields,
toGraphPoint,
clampOffset,
fitScale,
zoomAbout,
stageIsExecuted,
edgeIsExecuted,
activeStage,
} from "../src/graph.js";
import { runGraphState } from "../src/runDetail.js";
// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------
/** A two-stage definition ending in both terminals. */
function twoStageGraph() {
return {
stages: [
{
key: "plan",
type: "model",
prompt: "plan the work",
output: "a plan",
edges: { success: "impl", error: "#" },
fallback_error: true,
configs: {},
},
{
key: "impl",
type: "ntfy",
edges: { success: "#success" },
configs: {},
},
],
};
}
// ---------------------------------------------------------------------------
// Edge derivation (GraphSemantics)
// ---------------------------------------------------------------------------
test("stageOutcomes orders success first, error last, others alphabetical", () => {
const stage = {
edges: { error: "#", rejected: "a", success: "b", approved: "b", retry: "a" },
};
assert.deepEqual(stageOutcomes(stage), ["success", "approved", "rejected", "retry", "error"]);
});
test("graphEdges builds every definition edge in stable id order", () => {
const graph = {
stages: [
{ key: "a", edges: { success: "b", error: "#", rejected: "a" }, fallback_error: true },
{ key: "b", edges: { success: "#success" } },
],
};
const edges = graphEdges(graph);
assert.deepEqual(
edges.map((edge) => edge.source),
["a", "a", "a", "b"],
);
assert.deepEqual(
edges.map((edge) => edge.id),
[1, 2, 3, 4],
);
// `#` resolves to the terminal on the error route; a stage target is kept.
assert.equal(edges[0].target, "b");
assert.equal(edges[1].target, "a");
assert.equal(edges[2].target, "#failure");
assert.equal(edges[3].target, "#success");
});
test("edgeLabel marks only an implicit fallback error route with error*", () => {
assert.equal(edgeLabel({ fallback_error: true }, "error"), "error*");
assert.equal(edgeLabel({ fallback_error: false }, "error"), "error");
assert.equal(edgeLabel({ fallback_error: true }, "success"), "success");
assert.equal(edgeLabel({}, "rejected"), "rejected");
});
test("nodeDisplayLabel keeps a stage key and reads Success/Failure for terminals", () => {
assert.equal(nodeDisplayLabel("#success"), "Success");
assert.equal(nodeDisplayLabel("#failure"), "Failure");
assert.equal(nodeDisplayLabel("ui_reviewer"), "ui_reviewer");
});
// ---------------------------------------------------------------------------
// Node kinds (GraphPalette)
// ---------------------------------------------------------------------------
test("graphNodeKind maps terminals and the effective stage type", () => {
assert.equal(graphNodeKind(true, "#failure", undefined), "TerminalFailure");
assert.equal(graphNodeKind(true, "#success", "model"), "TerminalSuccess");
assert.equal(graphNodeKind(false, "a", "ntfy"), "Ntfy");
assert.equal(graphNodeKind(false, "a", ""), "Model");
assert.equal(graphNodeKind(false, "a", undefined), "Model");
assert.equal(graphNodeKind(false, "a", "model"), "Model");
assert.equal(graphNodeKind(false, "a", "shell"), "Custom");
});
test("nodeKindClass names a distinct fill for every kind", () => {
const classes = ["TerminalSuccess", "TerminalFailure", "Model", "Ntfy", "Custom"].map(
nodeKindClass,
);
assert.equal(new Set(classes).size, classes.length);
assert.equal(nodeKindClass("Ntfy"), "graph-node-ntfy");
assert.equal(nodeKindClass("Custom"), "graph-node-custom");
});
// ---------------------------------------------------------------------------
// Layout
// ---------------------------------------------------------------------------
test("layoutGraph keeps stage nodes in declaration order on one row", () => {
const layout = layoutGraph(twoStageGraph());
const stages = layout.nodes.filter((node) => !node.terminal);
assert.deepEqual(
stages.map((node) => node.key),
["plan", "impl"],
);
assert.equal(stages[0].y, stages[1].y);
assert.ok(stages[0].x < stages[1].x);
assert.ok(layout.width > 0 && layout.height > 0);
});
test("layoutGraph puts the terminals on one lower row with Failure left of Success", () => {
const layout = layoutGraph(twoStageGraph());
const failure = layout.nodes.find((node) => node.key === "#failure");
const success = layout.nodes.find((node) => node.key === "#success");
const stage = layout.nodes.find((node) => node.key === "plan");
assert.ok(failure && success, "both terminals are laid out");
assert.equal(failure.y, success.y);
assert.ok(failure.y > stage.y, "the terminal row sits below the stage row");
assert.ok(failure.x < success.x, "Failure is left of Success");
assert.ok(failure.terminal && success.terminal);
assert.deepEqual(
layout.nodes.slice(-2).map((node) => node.key),
["#failure", "#success"],
);
});
test("layoutGraph spreads every non-forward edge onto its own lane in id order", () => {
const graph = {
stages: [
{ key: "a", edges: { success: "b", rejected: "#success" } },
{ key: "b", edges: { success: "#success", rejected: "a" } },
],
};
const layout = layoutGraph(graph);
const laned = layout.edges.filter((edge) => edge.laneIndex >= 0);
// a→#success, b→#success (top entries) and b→a (an across loop).
assert.equal(laned.length, 3);
assert.deepEqual(
laned.map((edge) => edge.laneIndex),
[0, 1, 2],
);
assert.equal(new Set(laned.map((edge) => edge.lane)).size, laned.length, "distinct lanes");
assert.deepEqual(
laned.map((edge) => edge.id),
[...laned.map((edge) => edge.id)].sort((x, y) => x - y),
"lanes are allocated in stable edge-id order",
);
// A straight forward route keeps a single horizontal segment.
const forward = layout.edges.find((edge) => edge.source === "a" && edge.outcome === "success");
assert.equal(forward.forward, true);
assert.equal(forward.laneIndex, -1);
assert.equal(forward.points.length, 2);
});
test("layoutGraph labels sit on the edge's own widest horizontal run", () => {
const layout = layoutGraph(twoStageGraph());
for (const edge of layout.edges) {
assert.ok(Number.isFinite(edge.labelPoint.x) && Number.isFinite(edge.labelPoint.y));
}
});
test("a gap is at least as wide as the widest straight-route label plus padding", () => {
const graph = {
stages: [
{ key: "a", edges: { success: "b", repair_attempt: "b", error: "#" }, fallback_error: true },
{ key: "b", edges: { success: "#success" } },
],
};
const layout = layoutGraph(graph);
const [a, b] = layout.nodes.filter((node) => !node.terminal);
const gap = b.x - (a.x + a.width);
const widest = Math.max(labelWidthFor("success"), labelWidthFor("repair_attempt"));
assert.ok(gap >= widest + 2 * 10, `gap ${gap} fits the ${widest}px chip`);
});
test("a source's straight routes fan across its side instead of one shared band", () => {
const graph = {
stages: [
{ key: "a", edges: { success: "b", repair_attempt: "b", error: "#" }, fallback_error: true },
{ key: "b", edges: { success: "#success" } },
],
};
const layout = layoutGraph(graph);
const ys = layout.edges
.filter((edge) => edge.forward && edge.source === "a")
.map((edge) => edge.from.y)
.sort((x, y) => x - y);
assert.equal(ys.length, 2);
assert.ok(ys[1] - ys[0] >= 18, "their chips (18px tall) cannot touch");
});
test("graphEdges marks only the parser's implicit error fallback", () => {
const graph = {
stages: [
{ key: "a", edges: { success: "b", error: "#" }, fallback_error: true },
{ key: "b", edges: { success: "#success", error: "#" }, fallback_error: false },
],
};
const edges = graphEdges(graph);
assert.equal(edges.filter((edge) => edge.fallback).length, 1);
assert.equal(edges.find((edge) => edge.fallback).source, "a");
const layout = layoutGraph(graph);
assert.equal(layout.edges.filter((edge) => edge.fallback).length, 1);
});
test("layoutGraph is empty and finite for a graph with no stages", () => {
const layout = layoutGraph({ stages: [] });
assert.deepEqual(layout.nodes, []);
assert.deepEqual(layout.edges, []);
assert.equal(layout.width, 0);
assert.equal(layout.height, 0);
});
test("hitTest returns the node key under a graph-space point, else null", () => {
const layout = layoutGraph(twoStageGraph());
const node = layout.nodes[0];
assert.equal(hitTest(layout, { x: node.x + 1, y: node.y + 1 }), node.key);
assert.equal(hitTest(layout, { x: -1000, y: -1000 }), null);
});
test("graphDescription names the stage count", () => {
assert.equal(graphDescription({ stages: [] }), "Empty workflow graph");
assert.equal(
graphDescription({ stages: [{ key: "a" }] }),
"Workflow graph with 1 stage. Stages can be opened for details.",
);
});
// ---------------------------------------------------------------------------
// Viewport maths (WorkflowGraph.kt)
// ---------------------------------------------------------------------------
test("fitScale shrinks oversized content, uses the tighter axis and never upscales", () => {
assert.equal(fitScale({ width: 1000, height: 400 }, { width: 2000, height: 400 }, 0), 0.5);
assert.equal(fitScale({ width: 1000, height: 800 }, { width: 2000, height: 2000 }, 0), 0.4);
assert.equal(fitScale({ width: 1000, height: 800 }, { width: 200, height: 100 }, 0), 1);
});
test("fitScale accounts for padding and floors no lower than MIN_SCALE", () => {
assert.equal(fitScale({ width: 1000, height: 400 }, { width: 2000, height: 400 }, 100), 0.4);
assert.equal(fitScale({ width: 100, height: 100 }, { width: 100000, height: 100000 }, 0), MIN_SCALE);
});
test("fitScale is finite for degenerate sizes", () => {
assert.equal(fitScale({ width: 0, height: 0 }, { width: 100, height: 100 }, 0), 1);
assert.equal(fitScale({ width: 100, height: 100 }, { width: 0, height: 0 }, 0), 1);
assert.equal(fitScale({ width: 100, height: 100 }, { width: -5, height: 10 }, 0), 1);
assert.ok(Number.isFinite(fitScale({ width: 100, height: 100 }, { width: 100, height: 100 }, 60)));
assert.ok(Number.isFinite(fitScale({}, {}, 0)));
});
test("clampOffset keeps content visible at every extreme", () => {
const content = { width: 400, height: 300 };
const viewport = { width: 1000, height: 800 };
const margin = 40;
const far = clampOffset({ x: -10000, y: -10000 }, content, viewport, margin);
assert.equal(far.x, margin - content.width);
assert.equal(far.y, margin - content.height);
const near = clampOffset({ x: 10000, y: 10000 }, content, viewport, margin);
assert.equal(near.x, viewport.width - margin);
assert.equal(near.y, viewport.height - margin);
});
test("clampOffset leaves a centred small graph unchanged", () => {
const content = { width: 400, height: 300 };
const viewport = { width: 1000, height: 800 };
const centred = { x: (viewport.width - content.width) / 2, y: (viewport.height - content.height) / 2 };
assert.deepEqual(clampOffset(centred, content, viewport, 40), centred);
});
test("clampOffset is symmetric and safe for degenerate sizes", () => {
const content = { width: 500, height: 500 };
const viewport = { width: 1000, height: 800 };
const left = clampOffset({ x: -99999, y: 0 }, content, viewport, 40).x;
const right = clampOffset({ x: 99999, y: 0 }, content, viewport, 40).x;
assert.equal(left, -content.width + 40);
assert.equal(right, viewport.width - 40);
assert.deepEqual(clampOffset({ x: 0, y: 0 }, { width: 0, height: 0 }, viewport, 40), {
x: 0,
y: 0,
});
assert.ok(Number.isFinite(clampOffset({ x: 1, y: 2 }, content, { width: 10, height: 10 }, 40).x));
assert.ok(Number.isFinite(clampOffset({ x: NaN, y: NaN }, content, viewport, 40).x));
});
test("zoomAbout keeps the content point under the centroid fixed", () => {
const result = zoomAbout({ x: 0, y: 0 }, 1, { x: 50, y: 100 }, 1.6);
assert.equal(result.scale, 1.6);
assert.equal(result.offset.x, 50 - 50 * 1.6);
assert.equal(result.offset.y, 100 - 100 * 1.6);
});
test("zoomAbout clamps the scale to [0.3, 3.0] at both extremes", () => {
assert.equal(zoomAbout({ x: 0, y: 0 }, 1, { x: 50, y: 50 }, 9).scale, MAX_SCALE);
assert.equal(zoomAbout({ x: 0, y: 0 }, 1, { x: 50, y: 50 }, 0.01).scale, MIN_SCALE);
assert.equal(MAX_SCALE, 3.0);
assert.equal(MIN_SCALE, 0.3);
});
test("zoomAbout is finite and unchanged for degenerate scale/zoom", () => {
const offset = { x: 20, y: 30 };
const degenerate = zoomAbout(offset, 0, { x: 100, y: 100 }, 1.5);
assert.deepEqual(degenerate.offset, offset);
assert.equal(degenerate.scale, 0);
const purePan = zoomAbout(offset, 0.5, { x: 80, y: 60 }, 1);
assert.ok(Number.isFinite(purePan.offset.x) && Number.isFinite(purePan.scale));
const negative = zoomAbout(offset, 0.5, { x: 80, y: 60 }, -2);
assert.deepEqual(negative.offset, offset);
assert.equal(negative.scale, 0.5);
});
test("toGraphPoint inverts the translate+scale transform", () => {
assert.deepEqual(toGraphPoint({ x: 150, y: 210 }, { x: 50, y: 10 }, 2), { x: 50, y: 100 });
assert.deepEqual(toGraphPoint({ x: 150, y: 210 }, { x: 50, y: 10 }, 0), { x: 0, y: 0 });
});
// ---------------------------------------------------------------------------
// Stage definition pane (StageDetailPane.kt)
// ---------------------------------------------------------------------------
test("stageDefinitionFields mirrors the app's labels and omits blanks", () => {
const fields = stageDefinitionFields({
type: "",
prompt: "",
output: "the result",
edges: { success: "#success", error: "#" },
fallback_error: true,
configs: { provider: "anthropic", empty: "" },
limits: { max_visits: 3, on: ["failed"] },
memory: { notes: "here" },
notify: { on: ["failed"], destination: "phone", artifacts: ["log"] },
blocks: { tools: "read, write" },
});
const labels = fields.map((entry) => entry.label);
assert.deepEqual(labels, [
"Type",
"Output",
"Outcomes",
"Provider",
"Tools",
"Max visits",
"Limit on",
"Memory",
"Notify on",
"Notify destination",
"Notify artifacts",
]);
assert.equal(fields[0].value, "model", "a blank type is the model stage");
const outcomes = fields.find((entry) => entry.label === "Outcomes");
assert.equal(outcomes.value, "success \u2192 SUCCESS (terminal)\nerror \u2192 FAILURE (terminal)");
assert.equal(outcomes.block, true);
assert.equal(fields.find((entry) => entry.label === "Memory").value, "notes: here");
assert.ok(!labels.includes("Empty"), "a blank config is omitted");
});
test("configLabel spells the app's config vocabulary", () => {
assert.equal(configLabel("provider"), "Provider");
assert.equal(configLabel("model"), "Model");
assert.equal(configLabel("retries"), "Retries");
assert.equal(configLabel("timeout"), "Timeout");
assert.equal(configLabel("budget_usd"), "Budget (USD)");
assert.equal(configLabel("budget_tokens"), "Budget (tokens)");
assert.equal(configLabel("harness"), "Harness");
assert.equal(configLabel("other"), "other");
});
test("terminalFields lists the incoming routes into a terminal", () => {
const fields = terminalFields(twoStageGraph(), "#success");
assert.equal(fields.length, 1);
assert.equal(fields[0].label, "Incoming routes");
assert.equal(fields[0].value, "impl \u00b7 success \u2192 SUCCESS");
assert.equal(fields[0].block, true);
assert.deepEqual(terminalFields(twoStageGraph(), "#nope"), []);
});
// ---------------------------------------------------------------------------
// Run-mode execution state (R5: GraphSemantics RunGraphState.from)
// ---------------------------------------------------------------------------
test("runGraphState resolves visited stages, taken routes and reached terminals", () => {
const run = {
executing: false,
current_stage: "committer",
steps: [
{ stage: "implementer", sequence: 1, status: "completed", outcome: "success", target: "reviewer" },
{ stage: "reviewer", sequence: 2, status: "completed", outcome: "rejected", target: "implementer" },
{ stage: "implementer", sequence: 3, status: "completed", outcome: "success", target: "reviewer" },
{ stage: "committer", sequence: 4, status: "completed", outcome: "success", target: "#success" },
],
};
const state = runGraphState(run);
assert.deepEqual(state.visitedStages, ["implementer", "reviewer", "committer", "#success"]);
assert.equal(state.currentStage, "committer");
assert.equal(state.executing, false);
assert.equal(state.currentStageStartedAt, null);
assert.deepEqual(state.takenRoutes, [
"implementer\u0000success\u0000reviewer",
"reviewer\u0000rejected\u0000implementer",
"committer\u0000success\u0000#success",
]);
});
test("runGraphState marks a terminal only when a visit resolved to it", () => {
// A `#` target resolves by outcome: error -> #failure, everything else -> #success.
const failed = runGraphState({
executing: false,
steps: [{ stage: "impl", outcome: "error", target: "#" }],
});
assert.deepEqual(failed.visitedStages, ["impl", "#failure"]);
assert.equal(stageIsExecuted("#failure", failed), true);
assert.equal(stageIsExecuted("#success", failed), false);
const midRun = runGraphState({
executing: false,
steps: [{ stage: "impl", outcome: "success", target: "review" }],
});
assert.equal(stageIsExecuted("#success", midRun), false);
assert.equal(stageIsExecuted("#failure", midRun), false);
assert.equal(stageIsExecuted("review", midRun), false, "a target is not visited until a step lands on it");
});
test("stageIsExecuted is true for a visited stage and for the definition view", () => {
const state = runGraphState({
executing: false,
steps: [{ stage: "impl", outcome: "success", target: "review" }],
});
assert.equal(stageIsExecuted("impl", state), true);
assert.equal(stageIsExecuted("review", state), false);
// The definition view passes no runState, so every stage is executed.
assert.equal(stageIsExecuted("review", null), true);
});
test("edgeIsExecuted is true only for a route a recorded visit produced", () => {
const state = runGraphState({
executing: false,
steps: [
{ stage: "impl", outcome: "success", target: "review" },
{ stage: "review", outcome: "error", target: "#" },
],
});
const taken = { source: "impl", outcome: "success", target: "review" };
const byFallback = { source: "review", outcome: "error", target: "#failure" };
const untaken = { source: "impl", outcome: "blocked", target: "#failure" };
assert.equal(edgeIsExecuted(taken, state), true);
assert.equal(edgeIsExecuted(byFallback, state), true, "a resolved fallback route counts");
assert.equal(edgeIsExecuted(untaken, state), false);
// The definition view draws every route executed.
assert.equal(edgeIsExecuted(untaken, null), true);
});
test("activeStage resolves only while the run is executing", () => {
const live = runGraphState({
executing: true,
current_stage: "review",
steps: [
{ stage: "review", status: "running", started_at: "2026-01-01T00:00:00Z" },
],
});
assert.equal(activeStage(live), "review");
assert.equal(live.currentStageStartedAt, "2026-01-01T00:00:00Z");
const settled = runGraphState({
executing: false,
current_stage: "review",
steps: [
{ stage: "review", status: "running", started_at: "2026-01-01T00:00:00Z" },
],
});
assert.equal(activeStage(settled), null, "a finished run has no active stage");
assert.equal(settled.currentStageStartedAt, null);
assert.equal(activeStage(null), null, "the definition view has no active stage");
});
test("runGraphState falls back to the last visit's stage, else null", () => {
const state = runGraphState({ executing: false, steps: [{ stage: "a" }, { stage: "b" }] });
assert.equal(state.currentStage, "b");
assert.equal(runGraphState({ executing: false, steps: [] }).currentStage, null);
assert.equal(runGraphState({}).currentStage, null);
});
// ---------------------------------------------------------------------------
// Wording, exports and the no-innerHTML contract
// ---------------------------------------------------------------------------
test("the empty-state and pane wording matches the app's sentences", () => {
assert.equal(RUN_GRAPH_MISSING, "This server did not include the run graph.");
assert.equal(PIPELINE_GRAPH_EMPTY, "This pipeline has no stages.");
assert.equal(NO_NODE_DETAILS, "No details recorded for this node.");
assert.equal(STAGE_DEFINITION_TITLE, "Stage definition");
});
test("mount is exported and returns an unmount handle", () => {
assert.equal(typeof mount, "function");
});
test("graph.js never uses innerHTML and writes server strings with textContent", () => {
const source = readFileSync(new URL("../src/graph.js", import.meta.url), "utf8");
assert.ok(!source.includes("innerHTML"), "the graph never assigns innerHTML");
assert.ok(!source.includes("outerHTML"), "the graph never assigns outerHTML");
assert.ok(!source.includes("insertAdjacentHTML"), "no HTML is parsed from a string");
});
-32
View File
@@ -1,32 +0,0 @@
// The graph expansion preference: expanded by default, a collapse remembered.
import { test } from "node:test";
import assert from "node:assert/strict";
import { GRAPH_EXPANDED_KEY, readGraphExpanded, writeGraphExpanded } from "../src/graphPrefs.js";
function fakeStorage(initial = {}) {
const values = new Map(Object.entries(initial));
return {
getItem: (key) => (values.has(key) ? values.get(key) : null),
setItem: (key, value) => values.set(key, String(value)),
values,
};
}
test("the graph is expanded when nothing was stored", () => {
assert.equal(readGraphExpanded(fakeStorage()), true);
});
test("a collapse survives and expands again on request", () => {
const storage = fakeStorage();
writeGraphExpanded(false, storage);
assert.equal(storage.values.get(GRAPH_EXPANDED_KEY), "0");
assert.equal(readGraphExpanded(storage), false);
writeGraphExpanded(true, storage);
assert.equal(readGraphExpanded(storage), true);
});
test("storage failures fall back to the expanded default", () => {
const broken = { getItem() { throw new Error("denied"); }, setItem() { throw new Error("denied"); } };
assert.equal(readGraphExpanded(broken), true);
assert.doesNotThrow(() => writeGraphExpanded(false, broken));
});
-32
View File
@@ -1,32 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { highlight } from "../src/highlight.js";
const kinds = (tokens) => tokens.map((token) => `${token.kind}:${token.text}`);
test("go strings, comments, numbers and keywords are separated", () => {
const tokens = highlight('func main() {\n // note\n x := 42\n s := "hi"\n}', "go");
assert.ok(kinds(tokens).includes("keyword:func"));
assert.ok(kinds(tokens).includes("comment:// note"));
assert.ok(kinds(tokens).includes("number:42"));
assert.ok(kinds(tokens).includes('string:"hi"'));
assert.ok(kinds(tokens).some((entry) => entry.startsWith("plain: ")));
});
test("shell uses hash comments and javascript-style sharing is avoided", () => {
const tokens = highlight("echo hi # note\ncd /tmp", "sh");
assert.ok(kinds(tokens).includes("keyword:echo"));
assert.ok(kinds(tokens).includes("comment:# note"));
});
test("unknown languages still colour strings and numbers safely", () => {
const tokens = highlight('x = "a" + 2', "nonsense");
assert.ok(kinds(tokens).includes('string:"a"'));
assert.ok(kinds(tokens).includes("number:2"));
});
test("the output is token text only, never markup", () => {
const tokens = highlight('<img src=x onerror=alert(1)>', "html");
assert.equal(tokens.map((token) => token.text).join(""), '<img src=x onerror=alert(1)>');
assert.ok(tokens.every((token) => !("html" in token)));
});
-33
View File
@@ -1,33 +0,0 @@
// The rail/list collapse choices are a local layout preference.
import { test } from "node:test";
import assert from "node:assert/strict";
import { LAYOUT_KEY, readLayoutPrefs, writeLayoutPrefs } from "../src/layoutPrefs.js";
function fakeStorage(initial = {}) {
const values = new Map(Object.entries(initial));
return {
getItem: (key) => (values.has(key) ? values.get(key) : null),
setItem: (key, value) => values.set(key, String(value)),
values,
};
}
test("both panes are expanded when nothing was stored", () => {
assert.deepEqual(readLayoutPrefs(fakeStorage()), { railCollapsed: false, listCollapsed: false });
});
test("the two choices survive a write and read independently", () => {
const storage = fakeStorage();
writeLayoutPrefs({ railCollapsed: true, listCollapsed: false }, storage);
assert.deepEqual(readLayoutPrefs(storage), { railCollapsed: true, listCollapsed: false });
assert.ok(storage.values.get(LAYOUT_KEY).includes("railCollapsed"));
});
test("malformed storage and failures fall back to expanded", () => {
assert.deepEqual(readLayoutPrefs(fakeStorage({ [LAYOUT_KEY]: "{oops" })), {
railCollapsed: false,
listCollapsed: false,
});
const broken = { getItem() { throw new Error("denied"); }, setItem() { throw new Error("denied"); } };
assert.doesNotThrow(() => writeLayoutPrefs({ railCollapsed: true }, broken));
});
-181
View File
@@ -1,181 +0,0 @@
// The markdown subset (C7), ported from ui/chat/Markdown.kt. The parser is pure,
// so the exact block/span shapes are asserted without a browser; anything outside
// the subset must render as plain text and never be dropped.
import { test } from "node:test";
import assert from "node:assert/strict";
import { codeBlockLabel, decodeHtmlEntities, parseInline, parseMarkdown } from "../src/markdown.js";
/** Every text run in a span tree, in order, so nothing dropped can hide. */
function spanText(spans) {
return spans
.map((span) => {
if (span.kind === "plain" || span.kind === "code") return span.text;
if (span.kind === "strong" || span.kind === "emphasis" || span.kind === "link") {
return spanText(span.spans);
}
return "";
})
.join("");
}
/** Every text run in a block list, so nothing dropped can hide. */
function blockText(blocks) {
return blocks
.map((block) => {
if (block.kind === "heading" || block.kind === "paragraph") return block.text;
if (block.kind === "code") return block.code;
if (block.kind === "quote") return block.lines.join("\n");
if (block.kind === "list") return block.items.join("\n");
if (block.kind === "table") return [...block.header, ...block.rows.flat()].join("|");
return "";
})
.join("\n");
}
// --- Entities ---------------------------------------------------------------
test("decodeHtmlEntities decodes the named, decimal and hex references", () => {
assert.equal(decodeHtmlEntities("a &amp; b &lt; c &gt; d &quot;e&quot; &#x27;f&#39;"), "a & b < c > d \"e\" 'f'");
assert.equal(decodeHtmlEntities("&#65;&#x42;"), "AB");
assert.equal(decodeHtmlEntities("&hellip;&mdash;&nbsp;"), "…—\u00A0");
});
test("decodeHtmlEntities is a single pass, so a decoded ampersand is not re-decoded", () => {
assert.equal(decodeHtmlEntities("&amp;lt;"), "&lt;");
assert.equal(decodeHtmlEntities("&amp;amp;"), "&amp;");
});
test("decodeHtmlEntities leaves an unknown or malformed reference literal", () => {
assert.equal(decodeHtmlEntities("&nope; &doesnotexist;"), "&nope; &doesnotexist;");
assert.equal(decodeHtmlEntities("&#xZZ; &#; &"), "&#xZZ; &#; &");
});
test("parseMarkdown decodes entities before parsing", () => {
const blocks = parseMarkdown("a &amp; b");
assert.deepEqual(blocks, [{ kind: "paragraph", text: "a & b" }]);
});
// --- Blocks -----------------------------------------------------------------
test("parseMarkdown parses headings, paragraphs and thematic rules", () => {
const blocks = parseMarkdown("# Title\n\nA paragraph\nspanning lines.\n\n---\n\n## Sub ##");
assert.deepEqual(blocks, [
{ kind: "heading", level: 1, text: "Title" },
{ kind: "paragraph", text: "A paragraph spanning lines." },
{ kind: "rule" },
{ kind: "heading", level: 2, text: "Sub " },
]);
});
test("parseMarkdown parses a fenced block and keeps its language", () => {
const blocks = parseMarkdown("```js\nconst x = 1;\n```");
assert.deepEqual(blocks, [{ kind: "code", language: "js", code: "const x = 1;" }]);
assert.equal(codeBlockLabel("js"), "js");
});
test("a fenced block with no language is labelled code", () => {
const blocks = parseMarkdown("```\nplain\n```");
assert.deepEqual(blocks, [{ kind: "code", language: "", code: "plain" }]);
assert.equal(codeBlockLabel(""), "code");
assert.equal(codeBlockLabel(" "), "code");
});
test("tilde fences are code fences too", () => {
const blocks = parseMarkdown("~~~python\nprint(1)\n~~~");
assert.deepEqual(blocks, [{ kind: "code", language: "python", code: "print(1)" }]);
});
test("parseMarkdown parses block quotes, bullet lists and ordered lists", () => {
assert.deepEqual(parseMarkdown("> one\n> two"), [{ kind: "quote", lines: ["one", "two"] }]);
assert.deepEqual(parseMarkdown("- a\n- b"), [{ kind: "list", ordered: false, items: ["a", "b"] }]);
assert.deepEqual(parseMarkdown("1. one\n2. two"), [{ kind: "list", ordered: true, items: ["one", "two"] }]);
});
test("parseMarkdown parses a table with a --- delimiter row", () => {
const blocks = parseMarkdown("| a | b |\n| --- | --- |\n| 1 | 2 |");
assert.deepEqual(blocks, [{ kind: "table", header: ["a", "b"], rows: [["1", "2"]] }]);
});
test("a table row shorter than the header is padded, never truncated", () => {
const blocks = parseMarkdown("| a | b |\n| --- | --- |\n| 1 |");
assert.deepEqual(blocks[0].rows, [["1", ""]]);
});
test("a nested list is flattened into its run, never dropped", () => {
const blocks = parseMarkdown("- a\n - b");
assert.deepEqual(blocks, [{ kind: "list", ordered: false, items: ["a", "b"] }]);
assert.equal(blockText(blocks), "a\nb");
});
test("more than six hashes is a paragraph, not a heading", () => {
assert.deepEqual(parseMarkdown("####### x"), [{ kind: "paragraph", text: "####### x" }]);
});
// --- Inline -----------------------------------------------------------------
test("snake_case is never italicised", () => {
assert.deepEqual(parseInline("snake_case_name"), [{ kind: "plain", text: "snake_case_name" }]);
assert.deepEqual(parseInline("a_b_c"), [{ kind: "plain", text: "a_b_c" }]);
});
test("underscore emphasis works only at word boundaries", () => {
assert.deepEqual(parseInline("_italic_"), [{ kind: "emphasis", spans: [{ kind: "plain", text: "italic" }] }]);
assert.deepEqual(parseInline("a _b_ c"), [
{ kind: "plain", text: "a " },
{ kind: "emphasis", spans: [{ kind: "plain", text: "b" }] },
{ kind: "plain", text: " c" },
]);
});
test("bold, italic and inline code become their spans", () => {
assert.deepEqual(parseInline("**bold**"), [{ kind: "strong", spans: [{ kind: "plain", text: "bold" }] }]);
assert.deepEqual(parseInline("__bold__"), [{ kind: "strong", spans: [{ kind: "plain", text: "bold" }] }]);
assert.deepEqual(parseInline("*it*"), [{ kind: "emphasis", spans: [{ kind: "plain", text: "it" }] }]);
assert.deepEqual(parseInline("`code`"), [{ kind: "code", text: "code" }]);
});
test("links and bare http(s) autolinks become link spans", () => {
assert.deepEqual(parseInline("[site](https://example.com)"), [
{ kind: "link", spans: [{ kind: "plain", text: "site" }], url: "https://example.com" },
]);
assert.deepEqual(parseInline("see https://example.com now"), [
{ kind: "plain", text: "see " },
{ kind: "link", spans: [{ kind: "plain", text: "https://example.com" }], url: "https://example.com" },
{ kind: "plain", text: " now" },
]);
});
test("autolinks trim trailing punctuation", () => {
const spans = parseInline("go to https://example.com.");
const link = spans.find((span) => span.kind === "link");
assert.equal(link.url, "https://example.com");
});
// --- Out-of-subset text is never dropped ------------------------------------
test("out-of-subset HTML renders as plain text and is never dropped", () => {
assert.deepEqual(parseInline("<b>hi</b>"), [{ kind: "plain", text: "<b>hi</b>" }]);
assert.equal(blockText(parseMarkdown("<div>x</div>")), "<div>x</div>");
});
test("reference links and strikethrough render as plain text", () => {
assert.deepEqual(parseInline("[label][ref]"), [{ kind: "plain", text: "[label][ref]" }]);
assert.deepEqual(parseInline("~~gone~~"), [{ kind: "plain", text: "~~gone~~" }]);
});
test("a malformed inline marker is kept literally", () => {
assert.deepEqual(parseInline("a * b ` c"), [{ kind: "plain", text: "a * b ` c" }]);
});
test("every out-of-subset paragraph's text survives the round trip", () => {
const source = "<section>\n[ref][id] and ~~strike~~\n</section>";
const blocks = parseMarkdown(source);
const text = blockText(blocks);
assert.ok(text.includes("[ref][id] and ~~strike~~"));
});
test("spanText of a mixed inline run keeps every character", () => {
const spans = parseInline("plain **bold** `code` [link](https://e.com) tail");
assert.equal(spanText(spans), "plain bold code link tail");
});
-45
View File
@@ -1,45 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { foldRunEvent } from "../src/runEvents.js";
import { miniatureModel } from "../src/miniGraph.js";
test("custom outcome names use the recorded success/failure terminal", () => {
const graph={stages:[{key:"research",edges:{success:"fix"}},{key:"fix",edges:{blocked:"#failure"}},{key:"never",edges:{}}]};
const model=miniatureModel(graph,{graph_evidence:{complete:true,visits:[
{sequence:1,stage:"research",status:"completed",outcome:"success",target:"fix"},
{sequence:2,stage:"fix",status:"completed",outcome:"blocked",target:"#failure"},
]}});
assert.deepEqual(model.nodes.map(node=>node.color),["var(--ok)","var(--bad)",null]);
assert.equal(model.nodes[2].untaken,true);
});
test("coalesced live visits update list nodes and routes without a detail fetch", () => {
const identity = { run_id: 1, pipeline_id: 7, name: "Run", version: 2 };
let runs = foldRunEvent([], { ...identity, status: "running", graph_evidence: { complete: true, visits: [] } }).runs;
const visits = [
{ sequence: 1, stage: "a", status: "completed", outcome: "success", target: "b" },
{ sequence: 2, stage: "b", status: "completed", outcome: "success", target: "c" },
{ sequence: 3, stage: "c", status: "running", diagnostic: "PRIVATE" },
];
runs = foldRunEvent(runs, { ...identity, status: "running", current_stage: "c", graph_visits: visits, step: visits[2] }).runs;
runs = foldRunEvent(runs, { ...identity, status: "failed", step: { sequence: 3, stage: "c", status: "failed" } }).runs;
const model = miniatureModel({ stages: [
{ key: "a", edges: { success: "b", error: "never" } },
{ key: "b", edges: { success: "c" } }, { key: "c", edges: {} }, { key: "never", edges: {} },
] }, runs[0]);
assert.deepEqual(model.nodes.map((n) => n.color), ["var(--ok)", "var(--ok)", "var(--status-failed)", null]);
assert.equal(model.edges.filter((e) => !e.untaken).length, 2);
assert.equal(JSON.stringify(runs[0].graph_evidence).includes("PRIVATE"), false);
const same = foldRunEvent(runs, { ...identity, status: "running", graph_visits: visits }).runs;
assert.equal(same, runs);
});
test("partial legacy deltas do not manufacture complete history; loops compact", () => {
let runs = [{ id: 1, status: "running" }];
for (let sequence = 1; sequence <= 100; sequence++) {
runs = foldRunEvent(runs, { run_id: 1, step: { sequence, stage: "a", status: "completed", outcome: "success", target: "a" } }).runs;
}
assert.equal(runs[0].graph_evidence.complete, false);
assert.equal(runs[0].graph_evidence.visits.length, 1);
assert.equal(runs[0].graph_evidence.visits[0].sequence, 100);
});
-71
View File
@@ -1,71 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { miniatureModel, miniatureColor, createMiniGraphCache } from "../src/miniGraph.js";
const graph = { stages: [
{ key: "a", edges: { success: "b", error: "c" } },
{ key: "b", edges: { success: "#success" } },
{ key: "c", edges: { error: "#failure" } },
] };
test("miniatures retain real stage routes, without terminals or fabricated visits", () => {
const model = miniatureModel(graph, { status: "failed" });
assert.deepEqual(model.nodes.map((n) => n.key).sort(), ["a", "b", "c"]);
assert.equal(model.edges.length, 2);
assert.equal(model.evidence, false);
assert.ok(model.nodes.every((n) => n.color === null && n.untaken));
});
test("compact list evidence preserves successes before failure and last loop status", () => {
const loopGraph = { stages: [
{ key: "a", edges: { success: "b", error: "never" } },
{ key: "b", edges: { success: "c" } },
{ key: "c", edges: { retry: "a", error: "never" } },
{ key: "never", edges: {} },
] };
const visits = [
{ sequence: 1, stage: "a", status: "completed", outcome: "success", target: "b" },
{ sequence: 2, stage: "b", status: "completed", outcome: "success", target: "c" },
{ sequence: 3, stage: "c", status: "completed", outcome: "retry", target: "a" },
{ sequence: 4, stage: "a", status: "failed", outcome: "", target: "" },
];
const model = miniatureModel(loopGraph, { status: "failed", graph_evidence: { complete: true, visits } });
assert.equal(model.nodes.find((n) => n.key === "a").color, "var(--status-failed)");
assert.equal(model.nodes.find((n) => n.key === "b").color, "var(--ok)");
assert.equal(model.nodes.find((n) => n.key === "never").color, null);
assert.equal(model.nodes.find((n) => n.key === "never").untaken, true);
assert.equal(model.edges.filter((e) => !e.untaken).length, 3);
assert.ok(model.edges.filter((e) => e.outcome === "error").every((e) => e.untaken));
for (const status of ["waiting", "running", "queued"]) {
const next = miniatureModel(loopGraph, { status, current_stage: "a", executing: status !== "waiting",
graph_evidence: { complete: true, visits: [...visits.slice(0, 3), { sequence: 4, stage: "a", status }] } });
assert.equal(next.nodes.find((n) => n.key === "a").color, miniatureColor(status));
}
});
test("visited stages/routes use evidence; unvisited branches remain hollow", () => {
const model = miniatureModel(graph, { status: "waiting", executing: true, current_stage: "b",
steps: [{ stage: "a", status: "completed", outcome: "success", target: "b" }] });
assert.equal(model.nodes.find((n) => n.key === "a").color, "var(--ok)");
assert.equal(model.nodes.find((n) => n.key === "b").color, "var(--warn)");
assert.equal(model.nodes.find((n) => n.key === "c").untaken, true);
assert.equal(model.edges.find((e) => e.outcome === "success").color, "var(--ok)");
assert.equal(model.edges.find((e) => e.outcome === "error").untaken, true);
for (const status of ["succeeded", "failed", "running", "waiting", "interrupted", "queued", "canceled"]) {
assert.equal(miniatureColor(status), status === "waiting" ? "var(--warn)" : status === "running" ? "var(--accent)" : `var(--status-${status})`);
}
});
test("cache deduplicates pinned reads, rejects latest mismatches and scopes by endpoint", async () => {
const calls = [];
const cached = createMiniGraphCache(async (id, version) => {
calls.push([id, version]); return { version, graph };
}, () => {});
const run = { pipeline_id: 8, version: 2 };
assert.equal(cached(run, [{ id: 8, version: 3, shape: graph }], "one"), null);
cached(run, [], "one");
await new Promise(setImmediate);
assert.deepEqual(calls, [[8, 2]]);
assert.equal(cached(run, [], "one"), graph);
assert.equal(cached(run, [], "two"), null);
assert.equal(cached({ pipeline_id: 8 }, []), null);
const mismatch = createMiniGraphCache(async () => ({ version: 3, graph }), () => {});
mismatch(run); await new Promise(setImmediate);
assert.equal(mismatch(run), null);
});
-179
View File
@@ -1,179 +0,0 @@
// Scratch-only extension of ui-smoke: real DOM/views, deterministic protocol-shaped
// evidence; no backend connection, production reads, workflow creation or devices.
import { createServer } from "node:http";
import { readFile, mkdir, writeFile } from "node:fs/promises";
import { resolve, extname } from "node:path";
import assert from "node:assert/strict";
import { launchChrome } from "./browser.mjs";
const root = resolve(import.meta.dirname, "..");
const out = resolve(process.argv[2] ?? "captures-miniatures");
await mkdir(out, { recursive: true });
const server = createServer(async (req, res) => {
try {
const path = resolve(root, `.${["/", "/fixture"].includes(req.url) ? "/index.html" : req.url.split("?")[0]}`);
if (!path.startsWith(root + "/")) throw new Error("outside root");
let data = await readFile(path);
if (req.url === '/fixture') data = data.toString().replace('<script type="module" src="./src/app.js"></script>',
'<div class="app-root"><main class="workspace"><div class="pane-main"><div id="content" class="content"></div></div></main></div>');
res.setHeader("Content-Type", ({ ".js": "text/javascript", ".css": "text/css", ".html": "text/html", ".svg": "image/svg+xml" })[extname(path)] ?? "application/octet-stream");
res.end(data);
} catch { res.writeHead(404); res.end(); }
});
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const browser = await launchChrome();
const results = [];
try {
const page = await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector("#content");
// Real shell controls, before replacing content with the list fixtures.
await page.resize(1100, 1000);
await page.click('#railCollapse');
const rail = await page.evaluate(`(() => {
const button=document.querySelector('#railCollapse');
const brand=document.querySelector('.rail-brand-icon').getBoundingClientRect();
const first=document.querySelector('.rail-item').getBoundingClientRect();
const b=button.getBoundingClientRect();
return {collapsed:document.querySelector('#appRail').classList.contains('collapsed'),
expanded:button.getAttribute('aria-expanded'),position:getComputedStyle(button).position,
bottom:b.bottom,brandTop:brand.top,firstTop:first.top,width:b.width,height:b.height};
})()`);
assert.equal(rail.collapsed,true);
assert.equal(rail.expanded,'false');
assert.equal(rail.position,'static');
assert.ok(rail.bottom<=rail.brandTop && rail.bottom<=rail.firstTop);
assert.equal(rail.width,40);
assert.equal(rail.height,40);
await page.screenshot(resolve(out,'rail-collapsed-1100.png'));
await page.click('#railCollapse');
assert.equal(await page.evaluate(`document.querySelector('#railCollapse').getAttribute('aria-expanded')`),'true');
await page.screenshot(resolve(out,'rail-expanded-1100.png'));
results.push({view:'rail',...rail});
for (const width of [390,420]) {
await page.resize(width,1000);
assert.equal(await page.evaluate(`getComputedStyle(document.querySelector('#appRail')).display`),'none');
}
await page.goto(`http://127.0.0.1:${server.address().port}/fixture`);
await page.evaluate(`(async () => {
const { createRunsView } = await import('/src/views/runs.js');
const { createPipelinesView } = await import('/src/views/pipelines.js');
const { defaultRunFilters } = await import('/src/runs.js');
const { EMPTY_PIPELINE_FILTERS } = await import('/src/pipelines.js');
const graph = { stages: [{ key:'plan', edges:{success:'build',error:'reject'} },
{key:'build',edges:{success:'finish'}},{key:'reject',edges:{error:'#failure'}},
{key:'finish',edges:{success:'#success'}}] };
const statuses = ['succeeded','failed','running','interrupted','waiting','queued','failed'];
const visits = (status) => status === 'queued' ? [] : [
{sequence:1,stage:'plan',status:'completed',outcome:'success',target:'build'},
{sequence:2,stage:'build',status:'completed',outcome:'success',target:'finish'},
{sequence:3,stage:'finish',status:status==='succeeded'?'completed':status,
outcome:status==='succeeded'?'success':'',target:status==='succeeded'?'#success':''}];
const state = { view:'runs', url:'scratch', loading:false, selectedRunId:1,
openMenu:null, runFilters:{...defaultRunFilters(),pipelineId:7}, runSort:'server_order',
pipelineFilters:{...EMPTY_PIPELINE_FILTERS},pipelineSort:'server_order', pipelinesLoaded:true,
runsLoaded:true, pipelines:[{id:7,name:'Pinned workflow',version:3,stages:4,shape:graph}],
runs:statuses.map((status,i)=>({id:i+1,pipeline_id:7,version:2,name:'Pinned workflow',
title:'A wrapped run title that preserves the complete task context across narrow screens '+status,
status,executing:['running','queued'].includes(status),current_stage:status==='queued'?'plan':'finish',
completed_steps:status==='queued'||i===6?0:status==='succeeded'?3:2,
created_at:new Date().toISOString(),
...(i===6?{current_stage:'',executing:false}:{graph_evidence:{complete:true,visits:visits(status)}})})) };
let runs, pipelines;
const renderContent=()=>document.querySelector('#content').replaceChildren(
state.view==='runs'?runs.renderRunList():pipelines.renderPipelineList());
const rt={state,repo:{getPipeline:async(id,version)=>{window.pinnedReads=(window.pinnedReads||0)+1;return {id,version,graph};}},
renderContent,renderAttentionBell:()=>document.createElement('span'),selectRun:()=>{},pushRoute:()=>{}};
runs=createRunsView(rt);pipelines=createPipelinesView(rt);
window.fixtureState=state;window.paintFixture=renderContent;renderContent();
})()`);
await page.waitForSelector(".run-mini");
for (const width of [390, 420, 1100]) {
await page.resize(width, 1000);
await page.evaluate(`new Promise(resolve=>setTimeout(resolve,150))`);
for (const view of ["runs", "pipelines"]) {
await page.evaluate(`fixtureState.view=${JSON.stringify(view)};paintFixture()`);
const geometry = await page.evaluate(`(() => {
const rows=[...document.querySelectorAll('#content .row')];
return { width:innerWidth, overflow:document.documentElement.scrollWidth>innerWidth,
rows:rows.map(row=>{const mini=row.querySelector('.pipeline-mini');const r=row.getBoundingClientRect();
const m=mini.getBoundingClientRect();const svg=mini.querySelector('svg');const node=svg.querySelector('rect');
const status=row.querySelector('.status-icon')?.dataset.status;
const swatch=document.createElement('span');swatch.style.color=status==='waiting'?'var(--warn)':status==='running'?'var(--accent)':'var(--status-'+status+')';mini.append(swatch);
const expectedColor=getComputedStyle(swatch).color;swatch.remove();
const nodes=[...svg.querySelectorAll('rect')].map(n=>({stage:n.dataset.stage,
color:getComputedStyle(n).color,fill:getComputedStyle(n).fill,untaken:n.classList.contains('mini-untaken')}));
const edges=[...svg.querySelectorAll('polyline')].map(n=>({route:n.dataset.route,
color:getComputedStyle(n).color,untaken:n.classList.contains('mini-untaken')}));
return {id:Number(row.dataset.runId),nodes,edges,evidence:mini.dataset.evidence,inset:r.right-m.right,align:svg.getAttribute('preserveAspectRatio'),status,expectedColor,
color:getComputedStyle(mini).color,nodeColor:getComputedStyle(node).color,
right:m.right,rowRight:r.right, rowWidth:r.width,parentWidth:row.parentElement.clientWidth,
selected:row.classList.contains('selected')};}),
reads:window.pinnedReads,filterSeparate:!document.querySelector('.run-toolbar .run-applied-filters'),
titleWrap:[...document.querySelectorAll('.run-row-title')].every(el=>getComputedStyle(el).whiteSpace!=='nowrap')};
})()`);
assert.equal(geometry.overflow, false);
assert.ok(geometry.rows.length > 0);
assert.ok(geometry.rows.every((r)=>r.inset>=6 && r.inset<40 && r.align==='xMaxYMid meet'));
assert.equal(geometry.reads, 1);
if (view === 'runs') {
assert.equal(geometry.titleWrap, true);
assert.equal(geometry.filterSeparate, true);
const node=(row,stage)=>row.nodes.find(n=>n.stage===stage);
const byId=(id)=>geometry.rows.find(row=>row.id===id);
const failed=byId(2);
assert.equal(node(failed,'plan').color,node(failed,'build').color);
assert.notEqual(node(failed,'build').color,node(failed,'finish').color);
assert.equal(node(failed,'finish').color,failed.expectedColor);
assert.equal(node(failed,'reject').fill,'none');
assert.equal(node(failed,'reject').untaken,true);
assert.equal(failed.edges.filter(e=>!e.untaken).length,2);
assert.ok(failed.edges.filter(e=>e.route.includes(':error:')).every(e=>e.untaken));
assert.equal(byId(7).evidence,'unknown');
assert.ok(byId(7).nodes.every(n=>n.untaken && n.fill==='none'));
for (const row of geometry.rows.filter(row=>row.id!==7)) {
assert.equal(row.evidence,'visits');
if (['running','waiting','queued'].includes(row.status)) {
assert.equal(node(row,row.status==='queued'?'plan':'finish').color,row.expectedColor);
}
}
assert.notEqual(node(byId(3),'finish').color,node(byId(5),'finish').color);
const selected=geometry.rows.find(row=>row.selected);
assert.equal(selected.rowWidth,selected.parentWidth);
}
results.push({view,...geometry});
await page.screenshot(resolve(out, `${view}-${width}.png`));
if (view === 'runs') {
await page.evaluate(`document.querySelector('.run-row[data-run-id="2"]').scrollIntoView({block:'center'})`);
await page.screenshot(resolve(out, `runs-evidence-${width}.png`));
}
}
for (const status of ['waiting','failed']) {
await page.evaluate(`(async () => {
const {foldRunEvent}=await import('/src/runEvents.js');
window.beforeLiveRuns??=fixtureState.runs;
fixtureState.view='runs';
fixtureState.runs=foldRunEvent(fixtureState.runs,{run_id:3,status:${JSON.stringify(status)},
current_stage:'finish',step:{sequence:3,stage:'finish',status:${JSON.stringify(status)}}}).runs;
paintFixture();
document.querySelector('.run-row[data-run-id="3"]').scrollIntoView({block:'center'});
})()`);
const live = await page.evaluate(`(() => {
const mini=document.querySelector('.run-row[data-run-id="3"] .run-mini');
const nodes=[...mini.querySelectorAll('rect')];
return {colors:nodes.map(n=>getComputedStyle(n).color),
taken:mini.querySelectorAll('polyline:not(.mini-untaken)').length,
unknown:mini.querySelectorAll('rect.mini-untaken').length};
})()`);
assert.equal(live.colors[0],live.colors[1]);
assert.equal(live.taken,2);
assert.equal(live.unknown,1);
assert.notEqual(live.colors[0],live.colors[3]);
await page.screenshot(resolve(out, `runs-live-${status}-${width}.png`));
results.push({view:'live-'+status,width,...live});
}
await page.evaluate(`fixtureState.runs=beforeLiveRuns;beforeLiveRuns=null;paintFixture()`);
}
await writeFile(resolve(out, 'geometry.json'), JSON.stringify(results,null,2));
await page.close();
} finally { await browser.close(); await new Promise((r)=>server.close(r)); }
console.log(`Scratch captures and geometry: ${out}`);
-18
View File
@@ -1,18 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mobileViewportState } from "../src/mobileViewport.js";
const base = { width: 390, height: 844, baselineHeight: 844, layoutHeight: 844, editing: true };
test("keyboard geometry follows the visual viewport without assuming dvh resizes", () => {
assert.deepEqual(mobileViewportState({ ...base, height: 430, offsetTop: 20 }), { keyboard: true, height: 430, top: 20 });
// Chromium's resizes-content can shrink both; the pre-focus baseline survives.
assert.equal(mobileViewportState({ ...base, height: 430, layoutHeight: 430 }).keyboard, true);
assert.equal(mobileViewportState({ ...base, height: 430, editing: false, wasOpen: true }).keyboard, true);
assert.equal(mobileViewportState(base).keyboard, false);
});
test("toolbar motion, desktop layouts and pinch zoom never trigger keyboard layout", () => {
assert.equal(mobileViewportState({ ...base, height: 780 }).keyboard, false);
assert.equal(mobileViewportState({ ...base, height: 430, scale: 2 }).keyboard, false);
assert.equal(mobileViewportState({ ...base, height: 430, width: 900 }).keyboard, false);
assert.equal(mobileViewportState({ ...base, height: 430, editing: false }).keyboard, false);
});
-351
View File
@@ -1,351 +0,0 @@
// Focused modal-focus probe: serves web/ on a free port against the live
// Pipelines server, then drives the real page in headless Chrome with trusted
// key events. It proves the shared controller's contract on the attention
// sheet, the retry confirm and the changes viewer, plus one replaced/stacked
// overlay (the artifact viewer over a stage pane).
//
// cd web && node test/modal-probe.mjs --out ../captures
//
// It is read-only: no run is retried/cancelled/decided, no chat or template is
// created or changed. The one PNG is an open state focused from the keyboard.
import { spawn } from "node:child_process";
import { mkdir } from "node:fs/promises";
import net from "node:net";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { eventually, launchChrome } from "./browser.mjs";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const pipelines = flag(process.argv, "--pipelines", process.env.PIPELINES_TARGET ?? "127.0.0.1:8080");
const out = resolve(flag(process.argv, "--out", process.env.WEB_MODAL_OUT ?? resolve(ROOT, "../captures")));
const port = flag(process.argv, "--port", process.env.WEB_MODAL_PORT);
const settle = (ms = 120) => new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
function flag(argv, name, fallback) {
const index = argv.indexOf(name);
return index !== -1 && argv[index + 1] ? argv[index + 1] : fallback;
}
function freePort() {
return new Promise((resolvePort) => {
const server = net.createServer();
server.listen(0, "127.0.0.1", () => {
const { port: bound } = server.address();
server.close(() => resolvePort(bound));
});
});
}
const FOCUSABLE = [
"a[href]",
"button:not([disabled])",
"input:not([disabled])",
"select:not([disabled])",
"textarea:not([disabled])",
"[tabindex]:not([tabindex='-1'])",
].join(",");
const focusableList = (selector) => `(() => {
const panel = document.querySelector(${JSON.stringify(selector)});
if (!panel) return [];
return [...panel.querySelectorAll(${JSON.stringify(FOCUSABLE)})].filter((node) =>
!node.hidden &&
node.getAttribute("aria-hidden") !== "true" &&
!node.closest("[inert]") &&
getComputedStyle(node).display !== "none" &&
getComputedStyle(node).visibility !== "hidden"
);
})()`;
const activeId = () =>
page.evaluate(`(() => {
const active = document.activeElement;
if (!active) return "";
return active.id || active.getAttribute("data-change-index") || active.className || active.tagName;
})()`);
const inertState = () =>
page.evaluate(`(() => ({
appRoot: document.querySelector(".app-root")?.hasAttribute("inert") ?? false,
skipHidden: document.querySelector(".skip-link")?.getAttribute("aria-hidden") ?? null,
skipTabindex: document.querySelector(".skip-link")?.getAttribute("tabindex") ?? null,
skipInert: document.querySelector(".skip-link")?.hasAttribute("inert") ?? false,
}))()`);
const insideDialog = (selector) =>
page.evaluate(`(() => {
const panel = document.querySelector(${JSON.stringify(selector)});
return Boolean(panel && panel.contains(document.activeElement));
})()`);
async function wrapCheck(selector, label) {
const count = await page.evaluate(`${focusableList(selector)}.length`);
if (!count) throw new Error(`${label}: no focusable control in the dialog`);
await page.evaluate(`(() => {
const list = ${focusableList(selector)};
list[list.length - 1].focus();
})()`);
await page.pressKey("Tab");
const afterTab = await page.evaluate(`(() => {
const list = ${focusableList(selector)};
return list.indexOf(document.activeElement);
})()`);
if (afterTab !== 0) throw new Error(`${label}: Tab from the last control landed on index ${afterTab}`);
await page.pressKey("Tab", { shift: true });
const afterShift = await page.evaluate(`(() => {
const list = ${focusableList(selector)};
return list.indexOf(document.activeElement);
})()`);
const last = count - 1;
if (afterShift !== last) {
throw new Error(`${label}: Shift+Tab from the first control landed on index ${afterShift}, expected ${last}`);
}
console.log(` ${label}: ${count} controls; Tab last->first and Shift+Tab first->last`);
}
async function assertInert(label) {
const state = await inertState();
if (!state.appRoot) throw new Error(`${label}: .app-root is not inert while the dialog is open`);
return state;
}
async function assertRestored(label, prior) {
const state = await inertState();
if (state.appRoot) throw new Error(`${label}: .app-root stayed inert after close`);
if (state.skipHidden !== prior.skipHidden || state.skipTabindex !== prior.skipTabindex) {
throw new Error(`${label}: skip-link state was not restored exactly: ${JSON.stringify({ before: prior, after: state })}`);
}
console.log(` ${label}: app root and skip link restored exactly`);
}
async function openRun(id) {
const detail = `.run-detail .run-identity`;
await eventually(() => page.evaluate(`document.querySelector(${JSON.stringify(detail)})?.textContent?.includes("run ${id} ") ?? false`), {
timeout: 25000,
what: `run ${id} detail`,
});
}
let serve = null;
let browser = null;
let page = null;
try {
await mkdir(out, { recursive: true });
const webPort = port ? Number(port) : await freePort();
console.log(`• serving web/ on 127.0.0.1:${webPort} (proxy /connect -> ${pipelines})`);
serve = spawn(process.execPath, ["serve.mjs", "--port", String(webPort), "--pipelines", pipelines], {
cwd: ROOT,
stdio: ["ignore", "pipe", "pipe"],
});
let serveLog = "";
serve.stdout.on("data", (chunk) => (serveLog += chunk.toString()));
serve.stderr.on("data", (chunk) => (serveLog += chunk.toString()));
await eventually(
async () => {
if (serve.exitCode != null) throw new Error(`serve.mjs exited: ${serveLog.trim().slice(-400)}`);
const response = await fetch(`http://127.0.0.1:${webPort}/`).catch(() => null);
return response?.ok;
},
{ what: "the page to be served" },
);
console.log("• launching headless Chrome");
browser = await launchChrome({ width: 1440, height: 900 });
page = await browser.openPage();
await page.addInitScript(`(() => {
localStorage.setItem("pipelines.web.serverUrl.v2", "ws://127.0.0.1:${webPort}/connect");
localStorage.removeItem("pipelines.web.attention.v1");
localStorage.removeItem("pipelines.web.workspace.v1");
})()`);
const pageUrl = `http://127.0.0.1:${webPort}/`;
await page.goto(pageUrl);
await page.waitForSelector('#shellStatus[data-state="connected"]', { timeout: 30000 });
const runsClicked = await page.evaluate(`(() => {
const all = [...document.querySelectorAll('[data-destination="runs"]')];
const control = all.find((node) => node.offsetParent !== null) ?? all[0];
if (!control) return false;
control.click();
return true;
})()`);
if (!runsClicked) throw new Error("no Runs destination control");
await page.waitForSelector(".list.runs .run-row", { timeout: 30000 });
const prior = await inertState();
console.log(`• attention sheet (prior app inert=${prior.appRoot}, skip aria-hidden=${prior.skipHidden})`);
await page.waitForSelector("#attentionBell", { timeout: 15000 });
const bellCount = await page.evaluate(
`Number(document.querySelector("#attentionBell .attention-badge")?.dataset.count ?? 0)`,
);
if (!(bellCount > 0)) throw new Error("the live server has no attention entries to open");
await page.evaluate(`document.querySelector("#attentionBell").focus()`);
await page.pressKey("Enter");
await page.waitForSelector(".attention-sheet", { timeout: 10000 });
await settle();
await assertInert("attention open");
if (!(await insideDialog(".attention-sheet"))) {
throw new Error("attention sheet: focus is outside the panel after open");
}
if (await page.evaluate(`!!document.querySelector(".attention-sheet [inert]")`)) {
throw new Error("attention sheet: its own controls are inert");
}
const capture = `${out}/86-modal-focus-attention.png`;
await page.screenshot(capture);
console.log(` capture ${capture}`);
await wrapCheck(".attention-sheet", "attention sheet");
await page.pressKey("Escape");
await eventually(() => page.evaluate(`!document.querySelector(".attention-sheet")`), {
timeout: 5000,
what: "the attention sheet to close",
});
const afterAttention = await activeId();
if (afterAttention !== "attentionBell") {
throw new Error(`attention sheet: Escape returned focus to ${afterAttention || "body"}, not #attentionBell`);
}
await assertRestored("attention close", prior);
console.log("• retry confirm (run 440)");
await page.goto(`${pageUrl}runs/440`);
await page.waitForSelector(".run-detail .run-actions .retry-run", { timeout: 25000 });
await openRun(440);
await page.evaluate(`document.querySelector(".run-detail .run-actions .retry-run").focus()`);
await page.pressKey("Enter");
await page.waitForSelector(".confirm-dialog.confirm-retry", { timeout: 10000 });
await settle();
await assertInert("retry confirm open");
if (!(await insideDialog(".confirm-dialog.confirm-retry"))) {
throw new Error("retry confirm: focus is outside the panel after open");
}
await wrapCheck(".confirm-dialog.confirm-retry", "retry confirm");
await page.pressKey("Escape");
await eventually(() => page.evaluate(`!document.querySelector(".confirm-dialog.confirm-retry")`), {
timeout: 5000,
what: "the retry confirm to close",
});
await settle();
const afterConfirm = await activeId();
if (!String(afterConfirm).includes("retry-run")) {
throw new Error(`retry confirm: Escape returned focus to ${afterConfirm || "body"}, not .retry-run`);
}
await assertRestored("retry confirm close", prior);
console.log("• changes viewer (run 438)");
await page.goto(`${pageUrl}runs/438`);
await page.waitForSelector("#detailTitle", { timeout: 25000 });
await openRun(438);
const expanded = await page.evaluate(`(() => {
const toggle = [...document.querySelectorAll(".run-detail .collapsible .section-toggle")]
.find((node) => /\\d+ files? changed/.test(node.querySelector(".section-title")?.textContent ?? ""));
if (!toggle) return false;
toggle.click();
return true;
})()`);
if (!expanded) throw new Error("changes viewer: no Changes section on run 438");
await page.waitForSelector(".run-detail .changes-list .change-row", { timeout: 15000 });
await page.evaluate(`(() => {
const row = document.querySelector(".run-detail .changes-list .change-row");
row.scrollIntoView({ block: "center" });
row.focus();
})()`);
await page.pressKey("Enter");
await page.waitForSelector(".change-viewer", { timeout: 10000 });
await settle();
await assertInert("changes viewer open");
if (!(await insideDialog(".change-viewer"))) {
throw new Error("changes viewer: focus is outside the panel after open");
}
await wrapCheck(".change-viewer", "changes viewer");
await page.pressKey("Escape");
await eventually(() => page.evaluate(`!document.querySelector(".change-viewer")`), {
timeout: 5000,
what: "the changes viewer to close",
});
const afterChanges = await activeId();
if (afterChanges !== "0") {
throw new Error(`changes viewer: Escape returned focus to ${afterChanges || "body"}, not change row 0`);
}
await assertRestored("changes viewer close", prior);
console.log("• stacking: artifact viewer over the stage pane (run 440)");
await page.goto(`${pageUrl}runs/440`);
await page.waitForSelector("#detailTitle", { timeout: 25000 });
await openRun(440);
const timelineClicked = await page.evaluate(`(() => {
const tab = [...document.querySelectorAll(".rail-tab, .strip-tab")]
.find((node) => node.offsetParent !== null && node.textContent.trim() === "Timeline");
if (!tab) return false;
tab.click();
return true;
})()`);
if (!timelineClicked) throw new Error("stacking: no Timeline tab");
await page.waitForSelector(".run-detail .timeline-row", { timeout: 15000 });
await page.evaluate(`document.querySelector(".run-detail .timeline-row").focus()`);
await page.pressKey("Enter");
await page.waitForSelector(".stage-pane", { timeout: 10000 });
const openedArtifacts = await page.evaluate(`(() => {
const toggle = [...document.querySelectorAll(".stage-pane .section-toggle")]
.find((node) => node.querySelector(".section-title")?.textContent?.trim().startsWith("Artifacts"));
if (!toggle) return false;
toggle.click();
return true;
})()`);
if (!openedArtifacts) throw new Error("stacking: no Artifacts section in the stage pane");
await page.waitForSelector(".stage-pane .artifact-grid button.artifact-tile", { timeout: 10000 });
await page.evaluate(`(() => {
const tiles = [...document.querySelectorAll(".stage-pane .artifact-grid button.artifact-tile")];
const tile = tiles.find((node) => node.querySelector("img")) ?? tiles[0];
tile.scrollIntoView({ block: "center" });
tile.focus();
})()`);
await page.pressKey("Enter");
await page.waitForSelector(".artifact-viewer", { timeout: 10000 });
await settle();
const stack = await page.evaluate(`(() => ({
lower: document.querySelector(".stage-pane")?.hasAttribute("inert") ?? false,
upper: document.querySelector(".artifact-viewer")?.hasAttribute("inert") ?? false,
activeInsideUpper: document.querySelector(".artifact-viewer")?.contains(document.activeElement) ?? false,
appRoot: document.querySelector(".app-root")?.hasAttribute("inert") ?? false,
}))()`);
if (!stack.lower) throw new Error("stacking: the lower stage pane is still tabbable while the viewer is open");
if (stack.upper) throw new Error("stacking: the top artifact viewer is inert");
if (!stack.activeInsideUpper) throw new Error("stacking: focus is not inside the top artifact viewer");
if (!stack.appRoot) throw new Error("stacking: the app root is not inert under both dialogs");
await page.pressKey("Escape");
await eventually(() => page.evaluate(`!document.querySelector(".artifact-viewer")`), {
timeout: 5000,
what: "the artifact viewer to close",
});
const lowerRestored = await page.evaluate(`(() => ({
lowerInert: document.querySelector(".stage-pane")?.hasAttribute("inert") ?? false,
activeInsideLower: document.querySelector(".stage-pane")?.contains(document.activeElement) ?? false,
appRoot: document.querySelector(".app-root")?.hasAttribute("inert") ?? false,
}))()`);
if (lowerRestored.lowerInert) throw new Error("stacking: the stage pane stayed inert after the viewer closed");
if (!lowerRestored.activeInsideLower) throw new Error("stacking: focus did not return into the stage pane");
if (!lowerRestored.appRoot) throw new Error("stacking: the app root lost inert while the stage pane remained open");
await page.pressKey("Escape");
await eventually(() => page.evaluate(`!document.querySelector(".stage-pane")`), {
timeout: 5000,
what: "the stage pane to close",
});
const afterStack = await page.evaluate(`(() => ({
activeRow: document.activeElement?.getAttribute("data-stage-key") ?? "",
appRoot: document.querySelector(".app-root")?.hasAttribute("inert") ?? false,
}))()`);
if (!afterStack.activeRow) throw new Error("stacking: focus was not returned to the timeline row");
if (afterStack.appRoot) throw new Error("stacking: the app root stayed inert after the last close");
console.log(` artifact viewer -> stage pane -> timeline row (${afterStack.activeRow}); app root restored`);
console.log("\nMODAL PROBE PASS");
} finally {
await page?.close().catch(() => {});
await browser?.close().catch(() => {});
if (serve) {
serve.kill("SIGTERM");
await eventually(async () => serve.exitCode != null || serve.signalCode != null, {
timeout: 5000,
what: "serve.mjs exit",
}).catch(() => {});
}
}
-448
View File
@@ -1,448 +0,0 @@
// Focused unit tests for the shared modal controller. A tiny DOM stub gives the
// controller the same surface it uses in the browser (attributes, children,
// focus and document listeners) without a test dependency or a live server.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
createModalController,
focusableElements,
initialFocusIndex,
isFocusable,
wrapFocusIndex,
} from "../src/modal.js";
class FakeElement {
constructor(tag = "div", document_ = null) {
this.tagName = tag.toUpperCase();
this.ownerDocument = document_;
this.nodeType = 1;
this.attributes = new Map();
this.children = [];
this.parentElement = null;
this.isConnected = false;
this.hidden = false;
this.disabled = false;
this.textContent = "";
}
getAttribute(name) {
return this.attributes.has(name) ? this.attributes.get(name) : null;
}
setAttribute(name, value) {
this.attributes.set(name, String(value));
}
hasAttribute(name) {
return this.attributes.has(name);
}
removeAttribute(name) {
this.attributes.delete(name);
}
append(...nodes) {
for (const node of nodes) {
if (node.parentElement) node.remove();
node.parentElement = this;
node.isConnected = true;
this.children.push(node);
}
}
replaceChildren(...nodes) {
for (const child of this.children) {
child.parentElement = null;
child.isConnected = false;
}
this.children = [];
this.append(...nodes);
}
replaceWith(next) {
const parent = this.parentElement;
if (!parent) return;
const index = parent.children.indexOf(this);
if (index === -1) return;
parent.children[index] = next;
next.parentElement = parent;
next.isConnected = true;
this.parentElement = null;
this.isConnected = false;
}
remove() {
const parent = this.parentElement;
if (!parent) return;
const index = parent.children.indexOf(this);
if (index !== -1) parent.children.splice(index, 1);
this.parentElement = null;
this.isConnected = false;
}
contains(node) {
if (node === this) return true;
return this.children.some((child) => child.contains(node));
}
querySelectorAll() {
const found = [];
const walk = (element) => {
for (const child of element.children) {
found.push(child);
walk(child);
}
};
walk(this);
return found;
}
querySelector(selector) {
return this.querySelectorAll(selector)[0] ?? null;
}
matches(selector) {
if (selector === "a[href]") return this.tagName === "A" && this.hasAttribute("href");
if (selector === "button") return this.tagName === "BUTTON";
if (selector === "[tabindex]") return this.hasAttribute("tabindex");
return false;
}
focus() {
this.ownerDocument.activeElement = this;
}
}
class FakeDocument {
constructor() {
this.body = new FakeElement("body", this);
this.body.isConnected = true;
this.activeElement = this.body;
this.byId = new Map();
this.bySelector = new Map();
this.listeners = new Map();
this.defaultView = { getComputedStyle: () => ({ display: "block", visibility: "visible" }) };
}
createElement(tag) {
return new FakeElement(tag, this);
}
register(selector, element) {
if (selector.startsWith("#")) this.byId.set(selector.slice(1), element);
this.bySelector.set(selector, element);
return element;
}
getElementById(id) {
return this.byId.get(id) ?? null;
}
querySelector(selector) {
return this.bySelector.get(selector) ?? null;
}
querySelectorAll(selector) {
const element = this.bySelector.get(selector);
return element ? [element] : [];
}
addEventListener(type, listener, capture = false) {
const key = `${type}:${capture ? "capture" : "bubble"}`;
const list = this.listeners.get(key) ?? [];
list.push(listener);
this.listeners.set(key, list);
}
removeEventListener(type, listener, capture = false) {
const key = `${type}:${capture ? "capture" : "bubble"}`;
const list = this.listeners.get(key) ?? [];
this.listeners.set(
key,
list.filter((candidate) => candidate !== listener),
);
}
listenerCount(type, capture = false) {
return (this.listeners.get(`${type}:${capture ? "capture" : "bubble"}`) ?? []).length;
}
dispatch(type, event, capture = false) {
for (const listener of [...(this.listeners.get(`${type}:${capture ? "capture" : "bubble"}`) ?? [])]) {
listener(event);
}
}
}
function harness({ fallback = false } = {}) {
const document_ = new FakeDocument();
const root = document_.register(".app-root", new FakeElement("div", document_));
document_.body.append(root);
const skip = document_.register(".skip-link", new FakeElement("a", document_));
skip.setAttribute("href", "#main");
document_.body.append(skip);
const layer = new FakeElement("div", document_);
document_.body.append(layer);
const title = document_.register("#detailTitle", new FakeElement("h1", document_));
title.setAttribute("tabindex", "-1");
root.append(title);
const pane = document_.register("#pane-main", new FakeElement("div", document_));
pane.setAttribute("tabindex", "-1");
root.append(pane);
const controller = createModalController({
document: document_,
layer,
background: root,
skipLinks: [skip],
supportsInert: () => !fallback,
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
return { document_, root, skip, layer, title, controller };
}
function button(document_, text, props = {}) {
const node = new FakeElement("button", document_);
node.textContent = text;
node.tagName = "BUTTON";
for (const [key, value] of Object.entries(props)) {
if (key === "disabled") node.disabled = value;
else if (key === "hidden") node.hidden = value;
else node.setAttribute(key, value);
}
return node;
}
function panelWith(document_, ...controls) {
const panel = new FakeElement("div", document_);
panel.setAttribute("role", "dialog");
panel.append(...controls);
return panel;
}
test("modal lifecycle cleanup runs once for direct close, closeAll and render-managed disappearance", () => {
const {document_,controller}=harness();
const closed=[];
controller.open("info",panelWith(document_,button(document_,"Close")),{history:false,onClosed:()=>closed.push("info")});
assert.equal(controller.close("info"),true);
assert.equal(controller.close("info"),false);
controller.open("again",panelWith(document_,button(document_,"Close")),{history:false,onClosed:()=>closed.push("again")});
controller.closeAll();
controller.stage("rendered",panelWith(document_,button(document_,"Close")),{history:false,onClosed:()=>closed.push("rendered")});
controller.reconcile();controller.reconcile();
assert.deepEqual(closed,["info","again","rendered"]);
assert.deepEqual(controller.stackIds(),[]);
});
test("focusable discovery keeps DOM order and excludes every unreachable form", () => {
const document_ = new FakeDocument();
const panel = new FakeElement("div", document_);
const first = button(document_, "first");
const disabled = button(document_, "disabled", { disabled: true });
const hidden = button(document_, "hidden", { hidden: true });
const ariaHidden = button(document_, "aria hidden", { "aria-hidden": "true" });
const inert = button(document_, "inert", { inert: "" });
const negative = button(document_, "negative", { tabindex: "-1" });
const nested = new FakeElement("div", document_);
nested.setAttribute("aria-hidden", "true");
nested.append(button(document_, "nested"));
const last = button(document_, "last");
panel.append(first, disabled, hidden, ariaHidden, inert, negative, nested, last);
assert.deepEqual(
focusableElements(panel).map((node) => node.textContent),
["first", "last"],
);
assert.equal(isFocusable(first, { root: panel }), true);
assert.equal(isFocusable(disabled, { root: panel }), false);
assert.equal(isFocusable(negative, { root: panel }), false);
});
test("Tab and Shift+Tab arithmetic wraps in both directions", () => {
assert.equal(wrapFocusIndex(2, 1, 3), 0);
assert.equal(wrapFocusIndex(0, -1, 3), 2);
assert.equal(wrapFocusIndex(1, 1, 3), 2);
assert.equal(wrapFocusIndex(1, -1, 3), 0);
assert.equal(wrapFocusIndex(-1, 1, 3), 0);
assert.equal(wrapFocusIndex(-1, -1, 3), 2);
assert.equal(wrapFocusIndex(0, 1, 0), -1);
assert.equal(initialFocusIndex(0), -1);
assert.equal(initialFocusIndex(2), 0);
});
test("a panel with no focusable control focuses the panel itself", () => {
const { document_, layer, controller } = harness();
const panel = panelWith(document_, button(document_, "disabled", { disabled: true }));
controller.open("empty", panel);
assert.equal(document_.activeElement, panel);
assert.equal(panel.getAttribute("tabindex"), "-1");
assert.equal(layer.children.includes(panel), true);
controller.close("empty");
assert.equal(document_.activeElement, document_.getElementById("detailTitle"));
});
test("opening the same id twice keeps one trigger and one set of listeners", () => {
const { document_, title, controller } = harness();
const trigger = button(document_, "open");
title.append(trigger);
trigger.focus();
const first = panelWith(document_, button(document_, "a"));
controller.open("same", first, { onClose: () => {} });
assert.equal(document_.listenerCount("keydown"), 1);
const second = panelWith(document_, button(document_, "b"));
const other = button(document_, "other");
title.append(other);
other.focus();
controller.open("same", second, { onClose: () => {} });
assert.equal(document_.listenerCount("keydown"), 1);
assert.equal(controller.stackIds().length, 1);
controller.close("same");
assert.equal(document_.activeElement, trigger, "the original opener is still the return target");
assert.equal(controller.listenerState().keydown, false);
});
test("a same-id re-render replaces the panel and keeps the focused control", () => {
const { document_, title, controller } = harness();
const trigger = button(document_, "trigger");
title.append(trigger);
trigger.focus();
const firstPanel = panelWith(document_, button(document_, "one"), button(document_, "two"));
controller.open("same", firstPanel, { onClose: () => {} });
const second = firstPanel.children[1];
second.focus();
const replacement = panelWith(document_, button(document_, "one again"), button(document_, "two again"));
controller.open("same", replacement, { onClose: () => {} });
assert.equal(controller.stackIds().length, 1);
assert.equal(document_.activeElement.textContent, "two again");
controller.close("same");
assert.equal(document_.activeElement, trigger);
});
test("a second overlay inerts the first and closing it restores the first", () => {
const { document_, root, skip, title, controller } = harness();
const firstTrigger = button(document_, "first trigger");
title.append(firstTrigger);
firstTrigger.focus();
const first = panelWith(document_, button(document_, "first control"));
controller.open("first", first);
assert.equal(root.getAttribute("inert"), "");
assert.equal(skip.getAttribute("aria-hidden"), "true");
const secondTrigger = button(document_, "second trigger");
title.append(secondTrigger);
secondTrigger.focus();
const second = panelWith(document_, button(document_, "second control"));
controller.open("second", second);
assert.equal(first.getAttribute("inert"), "");
assert.equal(second.hasAttribute("inert"), false);
assert.deepEqual(controller.stackIds(), ["first", "second"]);
controller.close("second");
assert.equal(first.hasAttribute("inert"), false, "the lower panel is interactive again");
assert.equal(root.getAttribute("inert"), "");
assert.equal(controller.isOpen("first"), true);
controller.close("first");
assert.equal(root.hasAttribute("inert"), false);
assert.equal(skip.hasAttribute("aria-hidden"), false);
assert.equal(controller.listenerState().keydown, false);
});
test("native inert and aria-hidden/tabindex restore the exact prior values", () => {
const { document_, root, skip, controller } = harness();
root.setAttribute("inert", "kept");
skip.setAttribute("aria-hidden", "false");
const trigger = button(document_, "trigger");
root.append(trigger);
trigger.focus();
controller.open("exact", panelWith(document_, button(document_, "ok")));
controller.close("exact");
assert.equal(root.getAttribute("inert"), "kept");
assert.equal(skip.getAttribute("aria-hidden"), "false");
});
test("the no-inert fallback hides the background, removes its tab stops and restores them", () => {
const { document_, root, skip, controller } = harness({ fallback: true });
const first = button(document_, "one", { tabindex: "3" });
const second = button(document_, "two");
const trigger = button(document_, "trigger");
root.append(first, second, trigger);
trigger.focus();
controller.open("fallback", panelWith(document_, button(document_, "inside")));
assert.equal(root.getAttribute("aria-hidden"), "true");
assert.equal(skip.getAttribute("aria-hidden"), "true");
assert.equal(first.getAttribute("tabindex"), "-1");
assert.equal(second.getAttribute("tabindex"), "-1");
assert.equal(document_.listenerCount("keydown"), 1);
assert.equal(document_.listenerCount("focusin", true), 1);
controller.close("fallback");
assert.equal(root.hasAttribute("aria-hidden"), false);
assert.equal(skip.hasAttribute("aria-hidden"), false);
assert.equal(first.getAttribute("tabindex"), "3");
assert.equal(second.hasAttribute("tabindex"), false);
assert.equal(document_.listenerCount("keydown"), 0);
assert.equal(document_.listenerCount("focusin", true), 0);
});
test("Tab from the last control wraps to the first; Shift+Tab wraps back", () => {
const { document_, title, controller } = harness();
const trigger = button(document_, "trigger");
title.append(trigger);
trigger.focus();
const first = button(document_, "first");
const last = button(document_, "last");
controller.open("trap", panelWith(document_, first, last));
last.focus();
const tab = {
key: "Tab",
shiftKey: false,
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
stopPropagation() {},
};
document_.dispatch("keydown", tab);
assert.equal(document_.activeElement, first);
const shiftTab = {
key: "Tab",
shiftKey: true,
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
stopPropagation() {},
};
document_.dispatch("keydown", shiftTab);
assert.equal(document_.activeElement, last);
});
test("Escape closes through the supplied callback and returns focus", () => {
const { document_, title, controller } = harness();
const trigger = button(document_, "trigger");
title.append(trigger);
trigger.focus();
let closed = 0;
controller.open("escape", panelWith(document_, button(document_, "ok")), {
onClose: () => {
closed += 1;
controller.close("escape");
},
});
const escape = {
key: "Escape",
defaultPrevented: false,
preventDefault() {},
stopPropagation() {},
};
document_.dispatch("keydown", escape);
assert.equal(closed, 1);
assert.equal(controller.isOpen("escape"), false);
assert.equal(document_.activeElement, trigger);
});
-39
View File
@@ -1,39 +0,0 @@
// Real authenticated proxy, private fixture credentials, no live server/ntfy.
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdtemp, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import net from "node:net";
import { eventually } from "./browser.mjs";
const scratch = await mkdtemp(join(process.argv[2] ?? tmpdir(), "notification-web-link-"));
const auth = join(scratch, "auth.json");
await writeFile(auth, JSON.stringify({ password: "fixture-password-only", secret: "fixture-secret-not-real-credentials-123456789" }), { mode: 0o600 });
const port = await new Promise(resolve => { const s = net.createServer(); s.listen(0, "127.0.0.1", () => { const p = s.address().port; s.close(() => resolve(p)); }); });
const child = spawn(process.execPath, ["web/serve.mjs", "--host", "127.0.0.1", "--port", String(port), "--pipelines", "127.0.0.1:1"], {
cwd: resolve(import.meta.dirname, "../.."), env: { ...process.env, PIPELINES_WEB_AUTH: "required", PIPELINES_WEB_AUTH_FILE: auth }, stdio: "ignore",
});
const origin = `http://127.0.0.1:${port}`;
try {
await eventually(async () => { try { return (await fetch(origin + "/login")).ok; } catch { return false; } }, { timeout: 8000 });
const target = "/runs/20";
const gated = await fetch(origin + target, { headers: { Accept: "text/html" }, redirect: "manual" });
assert.equal(gated.status, 302);
const login = new URL(gated.headers.get("location"), origin);
assert.equal(login.pathname, "/login"); assert.equal(login.searchParams.get("next"), target);
assert.match(await (await fetch(login)).text(), /name="next" value="\/runs\/20"/);
const denied = await fetch(origin + "/login", { method: "POST", body: new URLSearchParams({ password: "wrong", next: target }), redirect: "manual" });
assert.equal(denied.status, 401);
const signed = await fetch(origin + "/login", { method: "POST", body: new URLSearchParams({ password: "fixture-password-only", next: target }), redirect: "manual" });
assert.equal(signed.status, 303); assert.equal(signed.headers.get("location"), target);
const cookie = signed.headers.get("set-cookie").split(";")[0];
const run = await fetch(origin + target, { headers: { cookie }, redirect: "manual" });
assert.equal(run.status, 200); assert.match(run.headers.get("content-type"), /text\/html/);
console.log("PASS: notification web run link remains authenticated and returns to the exact run after login; no notification or provider calls.");
} finally {
if (child.exitCode === null && child.signalCode === null) {
const exited = new Promise(resolve => child.once("exit", resolve)); child.kill("SIGTERM"); await exited;
}
await rm(scratch, { recursive: true, force: true });
}
-234
View File
@@ -1,234 +0,0 @@
// The pure notification model (L5): qualifying transitions, exactly-once
// dedupe, pre-existing/dismissed suppression, the app's exact wording and the
// total permission/storage helpers. No DOM, no timer, no live server.
import { test } from "node:test";
import assert from "node:assert/strict";
import { AttentionKind, attentionKey } from "../src/attention.js";
import {
NOTIFICATION_DEFAULT,
NOTIFICATION_DEFAULT_ASKED,
NOTIFICATION_DENIED,
NOTIFICATION_GRANTED,
NOTIFICATION_INSECURE,
NOTIFICATION_UNSUPPORTED,
NOTIFY_STORAGE_KEY,
alertBody,
alertKey,
alertTitle,
createAlertLedger,
decodeNotificationSettings,
encodeNotificationSettings,
notificationEnvironment,
notificationPermissionState,
} from "../src/notify.js";
const frame = (runId, status, extra = {}) => ({
run_id: runId,
status,
name: "release",
title: "Ship it",
...extra,
});
test("off suppresses every browser alert from summaries and pushed modes", () => {
for (const status of ["waiting", "failed", "succeeded"]) {
const ledger = createAlertLedger();
ledger.seed([{ id: 1, status: "running", notify_mode: "off" }]);
assert.equal(ledger.observe(frame(1, status)), null);
ledger.seed([{ id: 1, status: "running", notify_mode: "on" }]);
assert.equal(ledger.observe(frame(1, status, { notify_mode: "off" })), null);
}
});
test("on adds final success once while auto retains attention-only semantics", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 1, status: "running", notify_mode: "on" }, { id: 2, status: "running", notify_mode: "auto" }]);
const alert = ledger.observe(frame(1, "succeeded"));
assert.equal(alert.title, "A run succeeded");
assert.equal(alert.key, "1:Succeeded");
assert.equal(ledger.observe(frame(1, "succeeded")), null);
assert.equal(ledger.observe(frame(2, "succeeded")), null);
});
test("headlines are exactly the app's two, and unknown kinds are blank", () => {
assert.equal(alertTitle(AttentionKind.Failed), "A run failed");
assert.equal(alertTitle(AttentionKind.Decision), "A run needs your decision");
assert.equal(alertTitle({ name: "Failed" }), "A run failed");
assert.equal(alertTitle({ name: "Other" }), "");
});
test("the alert identity is the attention identity", () => {
assert.equal(alertKey(7, AttentionKind.Failed), attentionKey(7, AttentionKind.Failed));
assert.equal(alertKey(7, AttentionKind.Decision), "7:Decision");
});
test("alert body is the title then the pipeline, with the pipeline fallback", () => {
assert.equal(alertBody({ label: "Ship it", pipeline: "release" }), "Ship it \u00b7 release");
assert.equal(alertBody({ title: " Ship it ", name: "release" }), "Ship it \u00b7 release");
assert.equal(alertBody({ title: " ", name: "release" }), "release");
assert.equal(alertBody({ label: "release", pipeline: "release" }), "release");
assert.equal(alertBody({ label: "Ship it", pipeline: "" }), "Ship it");
assert.equal(alertBody(frame(7, "failed")), "Ship it \u00b7 release");
});
test("queued -> failed raises one alert and duplicate frames never repeat it", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 4, status: "queued", name: "release", title: "Ship it" }]);
const alert = ledger.observe(frame(4, "failed"));
assert.equal(alert.title, "A run failed");
assert.equal(alert.body, "Ship it \u00b7 release");
assert.equal(alert.key, "4:Failed");
assert.equal(ledger.observe(frame(4, "failed")), null);
assert.equal(ledger.observe(frame(4, "failed")), null);
});
test("running -> waiting raises the decision alert; unchanged waiting raises none", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 9, status: "running", name: "release", title: "Ship it" }]);
const alert = ledger.observe(frame(9, "waiting"));
assert.equal(alert.title, "A run needs your decision");
assert.equal(alert.key, "9:Decision");
assert.equal(ledger.observe(frame(9, "waiting")), null);
});
test("succeeded, canceled, interrupted and unknown statuses raise nothing", () => {
for (const status of ["succeeded", "canceled", "interrupted", "mystery", ""]) {
const ledger = createAlertLedger();
ledger.seed([{ id: 11, status: "running" }]);
assert.equal(ledger.observe(frame(11, status)), null, `status ${status}`);
}
});
test("a first-seen failed/waiting run (a snapshot seed) raises nothing", () => {
const ledger = createAlertLedger();
assert.equal(ledger.observe(frame(21, "failed")), null);
assert.equal(ledger.observe(frame(22, "waiting")), null);
});
test("a run already failed/waiting in the seed raises nothing", () => {
const ledger = createAlertLedger();
ledger.seed([
{ id: 31, status: "failed" },
{ id: 32, status: "waiting" },
]);
assert.equal(ledger.observe(frame(31, "failed")), null);
assert.equal(ledger.observe(frame(32, "waiting")), null);
});
test("the subscribe snapshot is seeded, so a queued run that failed in the gap does not notify", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 41, status: "queued" }]);
ledger.beginSeed();
assert.equal(ledger.observe(frame(41, "failed")), null);
ledger.endSeed();
assert.equal(ledger.observe(frame(41, "failed")), null);
// A later real transition still raises exactly once.
assert.equal(ledger.observe(frame(41, "running")), null);
assert.equal(ledger.observe(frame(41, "failed")).key, "41:Failed");
});
test("leaving the qualifying state forgets the key for a genuinely new transition", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 51, status: "queued" }]);
assert.equal(ledger.observe(frame(51, "failed")).key, "51:Failed");
assert.equal(ledger.observe(frame(51, "running")), null);
assert.equal(ledger.observe(frame(51, "failed")).key, "51:Failed");
// And a failed -> waiting hand-off raises the other kind once.
assert.equal(ledger.observe(frame(51, "waiting")).key, "51:Decision");
assert.equal(ledger.observe(frame(51, "waiting")), null);
});
test("a dismissed attention key notifies nothing, even on a real transition", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 61, status: "queued" }]);
const alert = ledger.observe(frame(61, "failed"), {
dismissed: new Set([attentionKey(61, AttentionKind.Failed)]),
});
assert.equal(alert, null);
assert.deepEqual(ledger.notifiedKeys(), ["61:Failed"]);
});
test("reset drops the status baseline but keeps the page session's dedupe", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 71, status: "queued" }]);
assert.equal(ledger.observe(frame(71, "failed")).key, "71:Failed");
ledger.reset();
// Re-seeding the fresh (still failed) list is not a transition.
ledger.seed([{ id: 71, status: "failed" }]);
assert.equal(ledger.observe(frame(71, "failed")), null);
assert.deepEqual(ledger.notifiedKeys(), ["71:Failed"]);
});
test("a malformed frame is ignored, never crashed on", () => {
const ledger = createAlertLedger();
assert.equal(ledger.observe(null), null);
assert.equal(ledger.observe({}), null);
assert.equal(ledger.observe({ run_id: 0, status: "failed" }), null);
});
test("permission wording is honest for every browser state", () => {
assert.equal(notificationPermissionState({ supported: false }).body, NOTIFICATION_UNSUPPORTED);
assert.equal(
notificationPermissionState({ supported: true, secureContext: false }).body,
NOTIFICATION_INSECURE,
);
assert.equal(notificationPermissionState({ permission: "denied" }).body, NOTIFICATION_DENIED);
assert.equal(notificationPermissionState({ permission: "granted" }).body, NOTIFICATION_GRANTED);
assert.equal(notificationPermissionState({ asked: false }).body, NOTIFICATION_DEFAULT);
assert.equal(notificationPermissionState({ asked: true }).body, NOTIFICATION_DEFAULT_ASKED);
});
test("only a supported, secure default permission offers the request control", () => {
const defaultView = notificationPermissionState({ asked: false });
assert.equal(defaultView.state, "default");
assert.equal(defaultView.canRequest, true);
assert.equal(defaultView.actionLabel, "Enable notifications");
for (const options of [
{ supported: false },
{ supported: true, secureContext: false },
{ permission: "granted" },
{ permission: "denied" },
]) {
const view = notificationPermissionState(options);
assert.equal(view.canRequest, false, JSON.stringify(options));
assert.equal(view.actionLabel, null, JSON.stringify(options));
}
// Having been asked once does not remove the control while permission stays
// default (the browser itself decides whether it may prompt again).
assert.equal(notificationPermissionState({ asked: true }).canRequest, true);
});
test("the asked flag round-trips and malformed storage decodes safely", () => {
assert.equal(NOTIFY_STORAGE_KEY, "pipelines.web.notify.v1");
const stored = encodeNotificationSettings({ asked: true });
assert.deepEqual(JSON.parse(stored), { asked: true });
assert.equal(decodeNotificationSettings(stored).asked, true);
assert.equal(decodeNotificationSettings(encodeNotificationSettings({ asked: false })).asked, false);
for (const bad of ["", " ", "not json", "[]", "null", '"asked"', "{", '{"asked":"yes"}', "42"]) {
assert.deepEqual(decodeNotificationSettings(bad), { asked: false }, bad);
}
assert.deepEqual(decodeNotificationSettings(null), { asked: false });
});
test("notificationEnvironment reads the browser facts without guessing", () => {
const granted = notificationEnvironment({
Notification: Object.assign(function Notification() {}, { permission: "granted" }),
isSecureContext: true,
});
assert.deepEqual(granted, { supported: true, secureContext: true, permission: "granted" });
assert.deepEqual(notificationEnvironment({}), {
supported: false,
secureContext: false,
permission: "default",
});
const odd = notificationEnvironment({
Notification: Object.assign(function Notification() {}, { permission: "maybe" }),
isSecureContext: false,
});
assert.deepEqual(odd, { supported: true, secureContext: false, permission: "default" });
});
-397
View File
@@ -1,397 +0,0 @@
// Unit tests for the pure pipeline helpers (src/pipelines.js): timestamp and
// duration formatting, the last-run join, the sort comparators, the filter and
// the empty-state strings. No DOM and no server: `node --test test/` proves the
// module is pure. Wording is asserted against the Android app's own strings.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
PIPELINE_DETAIL_TABS,
PIPELINE_SORTS,
RUN_PRESENCES,
RUN_STATUS_FILTERS,
durationSeconds,
filterPipelines,
formatDuration,
formatLocalTimestamp,
formatRanAgo,
graphNote,
isMoreRecent,
latestRunByPipeline,
parseInstant,
pipelineComparator,
pipelineFilterCount,
pipelineListEmptyState,
pipelineMatchesLastRunStatus,
pipelineMatchesName,
pipelineMatchesPresence,
pipelineSubtitle,
pipelineUpdatedLine,
runBadge,
runBadgeMetaLine,
runDurationText,
runStateOf,
sortPipelines,
stageCountText,
summaryFields,
versionRow,
} from "../src/pipelines.js";
const LOCAL_STAMP = /^\d{1,2} [A-Z][a-z]{2} \d{2}:\d{2}$/;
// ---------------------------------------------------------------------------
// Timestamps, durations and stage counts
// ---------------------------------------------------------------------------
test("stageCountText spells 1 singular and everything else plural", () => {
assert.equal(stageCountText(0), "0 stages");
assert.equal(stageCountText(1), "1 stage");
assert.equal(stageCountText(2), "2 stages");
assert.equal(stageCountText(5), "5 stages");
});
test("parseInstant accepts RFC3339 and rejects blank/unparseable input", () => {
assert.equal(parseInstant("2026-10-17T21:57:31Z"), Date.parse("2026-10-17T21:57:31Z"));
assert.equal(parseInstant(""), null);
assert.equal(parseInstant(" "), null);
assert.equal(parseInstant("not a date"), null);
assert.equal(parseInstant(undefined), null);
});
test("formatLocalTimestamp renders 'd MMM HH:mm' and null on bad input", () => {
assert.equal(formatLocalTimestamp("2026-10-17T21:57:31Z", { timeZone: "UTC" }), "17 Oct 21:57");
assert.equal(formatLocalTimestamp("2026-01-05T00:00:00Z", { timeZone: "UTC" }), "5 Jan 00:00");
assert.equal(formatLocalTimestamp("2026-10-17T21:57:31Z", { timeZone: "Europe/London" }), "17 Oct 22:57");
assert.equal(formatLocalTimestamp("", { timeZone: "UTC" }), null);
assert.equal(formatLocalTimestamp("nope", { timeZone: "UTC" }), null);
});
test("formatDuration matches the app's s / m s / h m rhythm", () => {
assert.equal(formatDuration(0), "0s");
assert.equal(formatDuration(45), "45s");
assert.equal(formatDuration(59), "59s");
assert.equal(formatDuration(60), "1m 0s");
assert.equal(formatDuration(125), "2m 5s");
assert.equal(formatDuration(3599), "59m 59s");
assert.equal(formatDuration(3600), "1h 0m");
assert.equal(formatDuration(3725), "1h 2m");
assert.equal(formatDuration(-5), "0s");
});
test("durationSeconds is null when the end precedes the start or a timestamp is bad", () => {
assert.equal(durationSeconds("2026-10-17T21:00:00Z", "2026-10-17T21:02:05Z"), 125);
assert.equal(durationSeconds("2026-10-17T21:02:05Z", "2026-10-17T21:00:00Z"), null);
assert.equal(durationSeconds("", "2026-10-17T21:00:00Z"), null);
assert.equal(durationSeconds("2026-10-17T21:00:00Z", "nope"), null);
});
test("runDurationText is live while executing and stored once finished", () => {
const start = "2026-10-17T21:00:00Z";
const now = Date.parse(start) + 100_000;
assert.equal(runDurationText({ created_at: start, finished_at: "", executing: true }, now), "1m 40s");
assert.equal(
runDurationText({ created_at: start, finished_at: "2026-10-17T21:02:05Z", executing: false }, now),
"2m 5s",
);
assert.equal(runDurationText({ created_at: "", finished_at: "", executing: true }, now), null);
assert.equal(runDurationText({ created_at: start, finished_at: "", executing: false }, now), null);
});
test("a running run with a future start reads as 0s, never negative", () => {
const start = "2026-10-17T21:00:00Z";
const now = Date.parse(start) - 5_000;
assert.equal(runDurationText({ created_at: start, finished_at: "", executing: true }, now), "0s");
});
test("formatRanAgo buckets by minute/hour/day and nulls a bad start", () => {
const start = Date.parse("2026-10-17T21:00:00Z");
const ago = (seconds) => formatRanAgo("2026-10-17T21:00:00Z", start + seconds * 1000);
assert.equal(ago(0), "just now");
assert.equal(ago(59), "just now");
assert.equal(ago(60), "1m ago");
assert.equal(ago(90), "1m ago");
assert.equal(ago(3600), "1h ago");
assert.equal(ago(7200), "2h ago");
assert.equal(ago(86400), "1d ago");
assert.equal(ago(3 * 86400), "3d ago");
assert.equal(formatRanAgo("2026-10-17T21:00:00Z", start - 10_000), "just now");
assert.equal(formatRanAgo("", start), null);
assert.equal(formatRanAgo("nope", start), null);
});
// ---------------------------------------------------------------------------
// Run states and the last-run join
// ---------------------------------------------------------------------------
test("runStateOf accepts the server vocabulary and falls back to unknown", () => {
assert.equal(runStateOf("succeeded"), "succeeded");
assert.equal(runStateOf("RUNNING"), "running");
assert.equal(runStateOf("success"), "succeeded");
assert.equal(runStateOf("error"), "failed");
assert.equal(runStateOf("cancelled"), "canceled");
assert.equal(runStateOf("interrupted"), "interrupted");
assert.equal(runStateOf(""), "unknown");
assert.equal(runStateOf(undefined), "unknown");
});
test("latestRunByPipeline picks the newest run per pipeline independent of input order", () => {
const runs = [
{ id: 1, pipeline_id: 7, created_at: "2026-10-01T00:00:00Z" },
{ id: 3, pipeline_id: 7, created_at: "2026-10-03T00:00:00Z" },
{ id: 2, pipeline_id: 7, created_at: "2026-10-02T00:00:00Z" },
{ id: 5, pipeline_id: 9, created_at: "2026-10-01T00:00:00Z" },
];
const forward = latestRunByPipeline(runs);
const backward = latestRunByPipeline([...runs].reverse());
assert.equal(forward.get(7).id, 3);
assert.equal(backward.get(7).id, 3);
assert.equal(forward.get(9).id, 5);
assert.equal(forward.size, 2);
});
test("isMoreRecent breaks an exact timestamp tie (and a bad timestamp) with the higher id", () => {
const sameTime = { created_at: "2026-10-01T00:00:00Z" };
assert.equal(isMoreRecent({ id: 7, ...sameTime }, { id: 5, ...sameTime }), true);
assert.equal(isMoreRecent({ id: 5, ...sameTime }, { id: 7, ...sameTime }), false);
assert.equal(isMoreRecent({ id: 8, created_at: "bad" }, { id: 6, created_at: "also bad" }), true);
assert.equal(isMoreRecent({ id: 6, created_at: "bad" }, { id: 8, created_at: "bad" }), false);
});
test("runBadgeMetaLine omits missing fragments but always prints the run id", () => {
assert.equal(runBadgeMetaLine({ ranAgo: "2h ago", duration: "1m 5s", runId: 42 }), "2h ago · 1m 5s · run 42");
assert.equal(runBadgeMetaLine({ ranAgo: null, duration: "1m 5s", runId: 42 }), "1m 5s · run 42");
assert.equal(runBadgeMetaLine({ ranAgo: "2h ago", duration: null, runId: 42 }), "2h ago · run 42");
assert.equal(runBadgeMetaLine({ ranAgo: null, duration: null, runId: 42 }), "run 42");
assert.equal(runBadgeMetaLine({ ranAgo: "", duration: "", runId: 7 }), "run 7");
});
test("runBadge bundles the state, age, duration and run id", () => {
const start = "2026-10-17T21:00:00Z";
const badge = runBadge(
{ id: 12, status: "failed", created_at: start, finished_at: "2026-10-17T21:02:05Z", executing: false },
Date.parse(start) + 3600_000,
);
assert.deepEqual(badge, { runId: 12, state: "failed", ranAgo: "1h ago", duration: "2m 5s" });
});
// ---------------------------------------------------------------------------
// Sorting
// ---------------------------------------------------------------------------
const P = (id, name, stages) => ({ id, name, stages, version: 1 });
function ids(list) {
return list.map((p) => p.id);
}
test("the sort list matches the app's labels with Server order default", () => {
assert.deepEqual(
PIPELINE_SORTS.map((option) => option.label),
["Server order", "Name A\u2013Z", "Name Z\u2013A", "Most recent run", "Fewest stages", "Most stages"],
);
assert.equal(PIPELINE_SORTS[0].key, "server_order");
});
test("server order preserves the server's own ordering (and never mutates the input)", () => {
const pipelines = [P(3, "beta", 2), P(1, "Alpha", 3), P(2, "alpha", 1), P(4, "Gamma", 1)];
assert.deepEqual(ids(sortPipelines(pipelines, "server_order")), [3, 1, 2, 4]);
assert.deepEqual(ids(pipelines), [3, 1, 2, 4], "input list is untouched");
});
test("name comparators ignore case and tie-break on the exact name then the id", () => {
const pipelines = [P(3, "beta", 2), P(1, "Alpha", 3), P(2, "alpha", 1), P(4, "Gamma", 1)];
assert.deepEqual(ids(sortPipelines(pipelines, "name_asc")), [1, 2, 3, 4]);
assert.deepEqual(ids(sortPipelines(pipelines, "name_desc")), [4, 3, 1, 2]);
});
test("stage-count comparators tie-break on the name then the id", () => {
const pipelines = [P(3, "beta", 2), P(1, "Alpha", 3), P(2, "alpha", 1), P(4, "Gamma", 1)];
assert.deepEqual(ids(sortPipelines(pipelines, "fewest_stages")), [2, 4, 3, 1]);
assert.deepEqual(ids(sortPipelines(pipelines, "most_stages")), [1, 3, 2, 4]);
});
test("most-recent-run puts no-run pipelines last and orders by run recency then run id", () => {
const pipelines = [P(1, "One", 1), P(2, "Two", 1), P(3, "Three", 1), P(4, "Four", 1)];
const latestRuns = new Map([
[1, { id: 11, pipeline_id: 1, created_at: "2026-10-03T00:00:00Z" }],
[3, { id: 10, pipeline_id: 3, created_at: "2026-10-01T00:00:00Z" }],
[4, { id: 9, pipeline_id: 4, created_at: "not a date" }],
]);
assert.deepEqual(ids(sortPipelines(pipelines, "recent_run", latestRuns)), [1, 3, 4, 2]);
});
test("most-recent-run breaks an exact timestamp tie with the higher run id", () => {
const pipelines = [P(1, "One", 1), P(2, "Two", 1)];
const at = "2026-10-01T00:00:00Z";
const latestRuns = new Map([
[1, { id: 4, pipeline_id: 1, created_at: at }],
[2, { id: 9, pipeline_id: 2, created_at: at }],
]);
assert.deepEqual(ids(sortPipelines(pipelines, "recent_run", latestRuns)), [2, 1]);
});
test("every comparator ends in a deterministic id tie-break", () => {
// Identical names and stage counts: only the id can decide, whatever the input order.
const pipelines = [P(5, "same", 2), P(2, "same", 2), P(9, "same", 2)];
assert.deepEqual(ids(sortPipelines(pipelines, "name_asc")), [2, 5, 9]);
assert.deepEqual(ids(sortPipelines([...pipelines].reverse(), "name_asc")), [2, 5, 9]);
assert.deepEqual(ids(sortPipelines(pipelines, "fewest_stages")), [2, 5, 9]);
assert.equal(typeof pipelineComparator("server_order"), "function");
});
// ---------------------------------------------------------------------------
// Filtering and empty states
// ---------------------------------------------------------------------------
test("the status filter vocabulary is exactly the server's seven run states", () => {
assert.deepEqual(RUN_STATUS_FILTERS, [
"queued",
"running",
"waiting",
"succeeded",
"failed",
"canceled",
"interrupted",
]);
assert.deepEqual(
RUN_PRESENCES.map((p) => p.label),
["Any", "Has runs", "No runs"],
);
});
const FILTER_PIPELINES = [P(1, "Android", 3), P(2, "Beta", 2), P(3, "Gamma", 1)];
const FILTER_RUNS = new Map([
[1, { id: 1, pipeline_id: 1, status: "succeeded" }],
[2, { id: 2, pipeline_id: 2, status: "failed" }],
]);
const FILTERS = (overrides = {}) => ({ presence: "any", lastRunStatuses: [], name: "", ...overrides });
test("the name facet narrows case-insensitively and needs no run history", () => {
assert.ok(pipelineMatchesName("", "anything"));
assert.ok(pipelineMatchesName("and", "Android"));
assert.ok(!pipelineMatchesName("zzz", "Android"));
assert.deepEqual(
filterPipelines(FILTER_PIPELINES, FILTERS({ name: "and" }), FILTER_RUNS, false).map((p) => p.id),
[1],
);
});
test("run facets AND together and a no-run pipeline never matches a selected status", () => {
assert.ok(pipelineMatchesPresence("any", false));
assert.ok(pipelineMatchesPresence("has_runs", true));
assert.ok(!pipelineMatchesPresence("has_runs", false));
assert.ok(pipelineMatchesPresence("no_runs", false));
assert.ok(pipelineMatchesLastRunStatus(null, []));
assert.ok(!pipelineMatchesLastRunStatus(null, ["failed"]));
assert.deepEqual(
filterPipelines(FILTER_PIPELINES, FILTERS({ presence: "has_runs" }), FILTER_RUNS, true).map((p) => p.id),
[1, 2],
);
assert.deepEqual(
filterPipelines(FILTER_PIPELINES, FILTERS({ presence: "no_runs" }), FILTER_RUNS, true).map((p) => p.id),
[3],
);
assert.deepEqual(
filterPipelines(FILTER_PIPELINES, FILTERS({ lastRunStatuses: ["failed"] }), FILTER_RUNS, true).map((p) => p.id),
[2],
);
});
test("a run facet is skipped while the run history is unknown, and the name still applies", () => {
assert.deepEqual(
filterPipelines(FILTER_PIPELINES, FILTERS({ presence: "has_runs" }), FILTER_RUNS, false).map((p) => p.id),
[1, 2, 3],
);
assert.deepEqual(
filterPipelines(FILTER_PIPELINES, FILTERS({ presence: "has_runs", name: "Beta" }), FILTER_RUNS, false).map((p) => p.id),
[2],
);
});
test("pipelineFilterCount counts one per active facet", () => {
assert.equal(pipelineFilterCount(FILTERS()), 0);
assert.equal(pipelineFilterCount(FILTERS({ name: "a" })), 1);
assert.equal(pipelineFilterCount(FILTERS({ presence: "has_runs", lastRunStatuses: ["failed"], name: "a" })), 3);
});
test("empty states use the app's three exact sentences and only offer a reset when pipelines exist", () => {
assert.deepEqual(pipelineListEmptyState([], [], FILTERS()), {
message: "No pipelines are defined on this server.",
clearAction: null,
});
assert.deepEqual(pipelineListEmptyState(FILTER_PIPELINES, [], FILTERS({ name: "zzz" })), {
message: 'No pipelines match "zzz".',
clearAction: "Clear filters",
});
assert.deepEqual(pipelineListEmptyState(FILTER_PIPELINES, [], FILTERS({ presence: "has_runs" })), {
message: "No pipelines match the current filters.",
clearAction: "Clear filters",
});
// A name narrowing combined with a run facet is no longer name-only.
assert.equal(
pipelineListEmptyState(FILTER_PIPELINES, [], FILTERS({ name: "zzz", presence: "has_runs" })).message,
"No pipelines match the current filters.",
);
assert.equal(pipelineListEmptyState(FILTER_PIPELINES, FILTER_PIPELINES, FILTERS()), null);
});
// ---------------------------------------------------------------------------
// List row and detail text
// ---------------------------------------------------------------------------
test("pipelineSubtitle is 'id {id} · v{version} · {N stages}' with a singular stage", () => {
assert.equal(pipelineSubtitle({ id: 20, version: 10, stages: 5 }), "id 20 · v10 · 5 stages");
assert.equal(pipelineSubtitle({ id: 3, version: 1, stages: 1 }), "id 3 · v1 · 1 stage");
assert.equal(pipelineSubtitle({ id: 4, version: 2, graph: { stages: [{}, {}] } }), "id 4 · v2 · 2 stages");
});
test("pipelineUpdatedLine is 'updated d MMM HH:mm' or null for a bad timestamp", () => {
const line = pipelineUpdatedLine({ updated_at: "2026-10-17T21:57:31Z" });
assert.ok(LOCAL_STAMP.test(line.replace(/^updated /, "")), line);
assert.equal(pipelineUpdatedLine({ updated_at: "" }), null);
assert.equal(pipelineUpdatedLine({ updated_at: "nope" }), null);
});
test("the detail tabs are Summary / Graph / Source in order", () => {
assert.deepEqual(PIPELINE_DETAIL_TABS.map((tab) => tab.label), ["Summary", "Graph", "Source"]);
});
test("summaryFields render the app's rows; latest version is v{n} or blank, never a dash", () => {
const fields = summaryFields({
content_hash: "abc123",
latest_version: 10,
version_created_at: "2026-10-18T23:41:08Z",
created_at: "2026-10-17T21:57:31Z",
updated_at: "2026-10-18T23:41:08Z",
});
assert.deepEqual(fields.map((f) => f.key), [
"Content hash",
"Latest version",
"Version created",
"Pipeline created",
"Pipeline updated",
]);
assert.equal(fields[0].value, "abc123");
assert.equal(fields[0].monospace, true);
assert.equal(fields[1].value, "v10");
for (const field of fields.slice(2)) assert.ok(LOCAL_STAMP.test(field.value), field.value);
const blank = summaryFields({ content_hash: "", latest_version: 0 });
assert.equal(blank[1].value, "");
assert.equal(blank[2].value, "");
});
test("versionRow shows v{n} plus its stage count and created time", () => {
const row = versionRow({ version: 2, stages: 1, created_at: "2026-10-18T19:04:13Z" });
assert.equal(row.versionLabel, "v2");
assert.equal(row.stagesText, "1 stage");
assert.ok(LOCAL_STAMP.test(row.createdText));
assert.equal(versionRow({ version: 3, stages: 4 }).createdText, null);
});
test("the graph note is the browser wording and leaves the graph to P6", () => {
const note = graphNote();
assert.match(note, /Mouse wheel to zoom, drag to pan, click a stage for details/);
assert.match(note, /Edges are labelled with their outcome/);
});
-681
View File
@@ -1,681 +0,0 @@
// Repository request-shape tests: the templates catalogue and the validate
// command, driven through the real transport against a fake WebSocket so the
// exact frames sent (and the error-envelope handling) are proven, not assumed.
import { test } from "node:test";
import assert from "node:assert/strict";
import { PipelinesClient, ProtocolError, NotConnectedError } from "../src/client.js";
import { PipelinesRepository, SHELL_OUTPUT_LIMIT, nativeChatMessageId, newChatOperationId } from "../src/repository.js";
import { validateServerUrl } from "../src/serverUrl.js";
const VALID = validateServerUrl("ws://host:8080/connect");
/** The same minimal fake the client tests use (test files are not importable). */
class FakeWebSocket {
static instances = [];
constructor(url) {
this.url = url;
this.sent = [];
this.onopen = null;
this.onmessage = null;
this.onclose = null;
this.onerror = null;
this.reply = null;
FakeWebSocket.instances.push(this);
}
send(data) {
const frame = JSON.parse(data);
this.sent.push(frame);
const response = this.reply?.(frame);
if (response !== undefined) {
this.onmessage?.({ data: JSON.stringify(response) });
}
}
close(code, reason) {
this.onclose?.({ code, reason });
}
open() {
this.onopen?.({});
}
}
function connected() {
FakeWebSocket.instances = [];
const client = new PipelinesClient({ WebSocketImpl: FakeWebSocket });
const repo = new PipelinesRepository(client);
client.connect(VALID);
const ws = FakeWebSocket.instances.at(-1);
ws.open();
return { repo, ws, client };
}
/** The last frame without the client-generated id, for an exact shape assertion. */
function lastFrame(ws) {
const { id, ...frame } = ws.sent.at(-1);
assert.match(id, /^web-\d+$/);
return frame;
}
test("runPipeline sends an explicit output_format and leaves legacy launches unchanged", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "run_started", run_detail: { id: 1 } });
for (const outputFormat of ["", "html", "markdown"]) {
await repo.runPipeline({ pipelineId: 2, version: 1, prompt: "report", workspace: "/scratch", outputFormat });
const frame = lastFrame(ws);
assert.equal(frame.output_format, outputFormat || undefined);
assert.deepEqual(frame.input, { prompt: "report" });
}
});
test("listTemplates sends exactly {type:'list_templates'} and returns the catalogue", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({
id: frame.id,
type: "templates",
templates: [{ key: "task", name: "Complete a task" }],
});
const templates = await repo.listTemplates();
assert.deepEqual(lastFrame(ws), { type: "list_templates" });
assert.equal(templates.length, 1);
assert.equal(templates[0].key, "task");
});
test("listTemplates returns [] when the reply carries no templates", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "templates" });
assert.deepEqual(await repo.listTemplates(), []);
});
test("validate sends exactly {type:'validate', source} and returns response.graph", async () => {
const { repo, ws } = connected();
const graph = { stages: [{ key: "plan" }] };
ws.reply = (frame) => ({ id: frame.id, type: "validated", graph });
const result = await repo.validate("the source");
assert.deepEqual(lastFrame(ws), { type: "validate", source: "the source" });
assert.deepEqual(result, graph);
});
test("validate rejects a server error envelope with the server's text", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unexpected token" });
await assert.rejects(() => repo.validate("bad source"), {
name: "ProtocolError",
message: "unexpected token",
});
});
test("validate throws when the reply has no graph", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "validated" });
await assert.rejects(() => repo.validate("empty"), ProtocolError);
});
/** The new pipeline detail a `submitted` reply carries in these tests. */
const SUBMITTED_DETAIL = { id: 91, name: "Release helper", version: 1 };
test("submit sends exactly {type:'submit',name,source,create_only:true} and returns the detail", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "submitted", detail: SUBMITTED_DETAIL });
const detail = await repo.submit("Release helper", "the source");
assert.deepEqual(lastFrame(ws), {
type: "submit",
name: "Release helper",
source: "the source",
create_only: true,
});
assert.deepEqual(detail, SUBMITTED_DETAIL);
});
test("submit trims the name before sending it", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "submitted", detail: SUBMITTED_DETAIL });
await repo.submit(" Release helper ", "the source");
assert.deepEqual(lastFrame(ws), {
type: "submit",
name: "Release helper",
source: "the source",
create_only: true,
});
});
test("submit refuses a blank name without sending anything", async () => {
const { repo, ws } = connected();
ws.reply = () => ({ id: "unused", type: "submitted", detail: SUBMITTED_DETAIL });
await assert.rejects(() => repo.submit(" ", "the source"), {
name: "ProtocolError",
message: "Enter a pipeline name.",
});
assert.equal(ws.sent.length, 0);
});
test("submit rejects a server error envelope with the server's own text", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: 'a pipeline named "Release helper" already exists' });
await assert.rejects(() => repo.submit("Release helper", "the source"), {
name: "ProtocolError",
message: 'a pipeline named "Release helper" already exists',
});
});
test("submit throws when the reply has no pipeline detail", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "submitted", name: "Release helper" });
await assert.rejects(() => repo.submit("Release helper", "the source"), {
name: "ProtocolError",
message: "The server returned no pipeline detail.",
});
});
test("search sends exactly {type:'search',search:{query,kind:'',limit:0}} and returns search_results", async () => {
const { repo, ws } = connected();
const payload = { query: "release", results: [{ kind: "run" }], cap: 50, scanned_steps: 3 };
ws.reply = (frame) => ({ id: frame.id, type: "search_results", search_results: payload });
const reply = await repo.search("release");
assert.deepEqual(lastFrame(ws), {
type: "search",
search: { query: "release", kind: "", limit: 0 },
});
assert.deepEqual(reply, payload);
});
test("search sends the selected kind verbatim and never a limit above the cap", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "search_results", search_results: { results: [] } });
await repo.search("release", "run");
const { search } = lastFrame(ws);
assert.deepEqual(search, { query: "release", kind: "run", limit: 0 });
// limit 0 asks for the server's own default (SearchDefaultLimit 50); the client
// never asks for more than SearchMaxLimit (200), let alone sends a larger value.
assert.ok(search.limit <= 200);
});
test("search returns null when an older server replies without search_results", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "pong" });
assert.equal(await repo.search("release"), null);
});
test("search surfaces an explicit server error with the server's own text", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unknown command: search" });
await assert.rejects(() => repo.search("release"), {
name: "ProtocolError",
message: "unknown command: search",
});
});
/** The run detail a run.action reply carries in these tests. */
const RUN_DETAIL = { id: 440, status: "failed" };
test("decideRun sends exactly {type:'decide_run',run_id,option,feedback} and returns the run detail", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "run", run_detail: RUN_DETAIL });
const detail = await repo.decideRun(440, { stage: "review", option: "approve", feedback: " yes " });
assert.deepEqual(lastFrame(ws), {
type: "decide_run",
run_id: 440,
stage: "review",
option: "approve",
feedback: "yes",
});
assert.deepEqual(detail, RUN_DETAIL);
});
test("decideRun omits a blank stage and blank feedback", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "run", run_detail: RUN_DETAIL });
await repo.decideRun(12, { stage: " ", option: "publish", feedback: " " });
assert.deepEqual(lastFrame(ws), { type: "decide_run", run_id: 12, option: "publish" });
});
test("cancelRun sends exactly {type:'cancel_run',run_id} and returns the run detail", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "run", run_detail: RUN_DETAIL });
const detail = await repo.cancelRun(440);
assert.deepEqual(lastFrame(ws), { type: "cancel_run", run_id: 440 });
assert.deepEqual(detail, RUN_DETAIL);
});
test("retryRun always sends request_key and omits retry_mode for the default resume", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "run_started", run_detail: RUN_DETAIL });
await repo.retryRun(440, { requestKey: "key-1" });
assert.deepEqual(lastFrame(ws), { type: "retry_run", run_id: 440, request_key: "key-1" });
});
test("retryRun sends retry_mode only for an explicit restart", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "run_started", run_detail: RUN_DETAIL });
await repo.retryRun(440, { mode: "restart", requestKey: "key-2" });
assert.deepEqual(lastFrame(ws), {
type: "retry_run",
run_id: 440,
request_key: "key-2",
retry_mode: "restart",
});
});
test("setRunTitle sends exactly {type:'set_run_title',run_id,title} and returns the run detail", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "run", run_detail: RUN_DETAIL });
const detail = await repo.setRunTitle(440, "New title");
assert.deepEqual(lastFrame(ws), { type: "set_run_title", run_id: 440, title: "New title" });
assert.deepEqual(detail, RUN_DETAIL);
});
test("subscribeRuns sends exactly {type:'subscribe',workspace:''} with no run_ids", async () => {
const { repo, ws } = connected();
const id = repo.subscribeRuns();
assert.match(id, /^web-\d+$/);
assert.deepEqual(lastFrame(ws), { type: "subscribe", workspace: "" });
});
test("subscribeRuns includes run_ids only when ids are given and sends the workspace verbatim", () => {
const { repo, ws } = connected();
repo.subscribeRuns("", [3, 4]);
assert.deepEqual(lastFrame(ws), { type: "subscribe", workspace: "", run_ids: [3, 4] });
repo.subscribeRuns("/tmp/ws", []);
assert.deepEqual(lastFrame(ws), { type: "subscribe", workspace: "/tmp/ws" });
});
test("subscribeRuns is send-only: it returns the id and never awaits a reply", () => {
const { repo, ws } = connected();
// No reply is scripted; a send-only call must not hang or reject.
const id = repo.subscribeRuns();
assert.equal(ws.sent.at(-1).id, id);
});
test("unsubscribeRuns sends exactly {type:'unsubscribe'} and is send-only", () => {
const { repo, ws } = connected();
const id = repo.unsubscribeRuns();
assert.match(id, /^web-\d+$/);
assert.deepEqual(lastFrame(ws), { type: "unsubscribe" });
});
test("the run watch commands are refused before connect", () => {
FakeWebSocket.instances = [];
const client = new PipelinesClient({ WebSocketImpl: FakeWebSocket });
const repo = new PipelinesRepository(client);
assert.throws(() => repo.subscribeRuns(), NotConnectedError);
assert.throws(() => repo.unsubscribeRuns(), NotConnectedError);
});
test("each run action rejects a server error envelope instead of returning a detail", async () => {
const calls = [
(repo) => () => repo.decideRun(440, { option: "approve" }),
(repo) => () => repo.cancelRun(440),
(repo) => () => repo.retryRun(440, { requestKey: "key-3" }),
(repo) => () => repo.setRunTitle(440, ""),
];
for (const makeCall of calls) {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "a title with usable text is required" });
await assert.rejects(makeCall(repo), {
name: "ProtocolError",
message: "a title with usable text is required",
});
}
});
test("a run action throws when the reply has no run detail", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "run" });
await assert.rejects(() => repo.cancelRun(7), ProtocolError);
});
// ---- The composer's own commands (C8/C9) ----------------------------------
test("run retries preserve one admission key and can reconcile without execution", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "run", run_detail: { id: 42 } });
const intent = { pipelineId: 7, version: 1, prompt: "task", workspace: "/work", requestKey: "same-intent" };
await repo.runPipeline(intent);
await repo.runPipeline(intent);
assert.deepEqual(ws.sent.map((frame) => frame.request_key), ["same-intent", "same-intent"]);
assert.equal((await repo.runByRequestKey("same-intent")).id, 42);
assert.equal(lastFrame(ws).type, "get_run");
assert.equal(lastFrame(ws).request_key, "same-intent");
ws.reply = (frame) => ({ id: frame.id, type: "run" });
assert.equal(await repo.runByRequestKey("not-admitted"), null);
});
test("chatPrompt trims the text, sends the operation and native message ids, and omits files when empty", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_prompt" });
const queued = await repo.chatPrompt("s1", " hello ", [], "op-1");
assert.deepEqual(lastFrame(ws), {
type: "chat_prompt",
chat_prompt: {
session_id: "s1",
text: "hello",
operation_id: "op-1",
native_message_id: "msg_op1",
},
});
assert.equal(queued, false);
});
test("chatPrompt includes files when present and reads chat_queued", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_prompt", chat_queued: true });
const queued = await repo.chatPrompt("s1", "hi", ["a.txt", "b.txt"], "op-2");
assert.deepEqual(lastFrame(ws), {
type: "chat_prompt",
chat_prompt: {
session_id: "s1",
text: "hi",
operation_id: "op-2",
native_message_id: "msg_op2",
files: ["a.txt", "b.txt"],
},
});
assert.equal(queued, true);
});
test("chatModels and switchChatModel use the session-scoped wire shapes", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => {
if (frame.type === "chat_models") {
return { id: frame.id, type: "chat_models", chat_models: [{ id: "m1", provider: "p1", name: "Model One" }] };
}
return { id: frame.id, type: "chat_model", chat_model: frame.chat_model };
};
const models = await repo.chatModels("s1");
assert.deepEqual(lastFrame(ws), {
type: "chat_models",
chat_query: { session_id: "s1" },
});
assert.deepEqual(models, [{ id: "m1", provider: "p1", name: "Model One" }]);
const selected = await repo.switchChatModel("s1", "p1", "m1");
assert.deepEqual(lastFrame(ws), {
type: "chat_model",
chat_model: { session_id: "s1", provider: "p1", model: "m1" },
});
assert.equal(selected.model, "m1");
});
test("chatPrompt sends browser attachment bytes with their name and mime", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_prompt" });
await repo.chatPrompt("s1", "see attached", [], "op-3", [
{ name: "note.txt", mime: "text/plain", data: "aGVsbG8=" },
]);
assert.deepEqual(lastFrame(ws).chat_prompt.attachments, [
{ name: "note.txt", mime: "text/plain", data: "aGVsbG8=" },
]);
});
test("chatPrompt refuses a blank session or blank text without sending", async () => {
const { repo, ws } = connected();
await assert.rejects(() => repo.chatPrompt(" ", "hi", [], "op"), ProtocolError);
await assert.rejects(() => repo.chatPrompt("s1", " ", [], "op"), ProtocolError);
assert.equal(ws.sent.length, 0);
});
test("chatInterrupt sends the session as chat_query (not a chat_interrupt body)", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_interrupt" });
await repo.chatInterrupt("s1");
assert.deepEqual(lastFrame(ws), { type: "chat_interrupt", chat_query: { session_id: "s1" } });
});
test("chatDirectories sends exactly {type:'chat_directories'} and returns the list", async () => {
const { repo, ws } = connected();
const directories = ["/home/operator", "/repo/one", "/repo/two"];
ws.reply = (frame) => ({ id: frame.id, type: "chat_directories", chat_directories: directories });
assert.deepEqual(await repo.chatDirectories(), directories);
assert.deepEqual(lastFrame(ws), { type: "chat_directories" });
});
test("chatDirectories returns [] when the reply carries no directories", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_directories" });
assert.deepEqual(await repo.chatDirectories(), []);
});
test("chatDirectories surfaces a server refusal as a ProtocolError", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unknown command: chat_directories" });
await assert.rejects(() => repo.chatDirectories(), {
name: "ProtocolError",
message: "unknown command: chat_directories",
});
});
test("chatCreate sends home as ~ and carries the exact title/directory/operation_id body", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_create", chat_session: { id: "ses_new" } });
await repo.chatCreate("New chat", "~", "op-4");
assert.deepEqual(lastFrame(ws), {
type: "chat_create",
chat_create: { title: "New chat", directory: "~", operation_id: "op-4" },
});
});
test("chatCreate sends title/directory/operation_id and returns chat_session", async () => {
const { repo, ws } = connected();
const created = { id: "ses_new", title: "New chat" };
ws.reply = (frame) => ({ id: frame.id, type: "chat_create", chat_session: created });
const session = await repo.chatCreate("New chat", "/repo", "op-3");
assert.deepEqual(lastFrame(ws), {
type: "chat_create",
chat_create: { title: "New chat", directory: "/repo", operation_id: "op-3" },
});
assert.deepEqual(session, created);
});
test("chatCreate sends a preloaded behavior brief when provided", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_create", chat_session: { id: "s1" } });
await repo.chatCreate("New chat", "/repo", "op-5", { instructions: "be careful" });
assert.equal(lastFrame(ws).chat_create.instructions, "be careful");
});
test("chatCreate throws when the reply carries no chat_session", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_create" });
await assert.rejects(() => repo.chatCreate("t", "/d", "op"), ProtocolError);
});
test("nativeChatMessageId mirrors the Android id: msg_ + alphanumerics, capped", () => {
assert.equal(nativeChatMessageId("web-chat-abc-123"), "msg_webchatabc123");
assert.equal(nativeChatMessageId(""), "");
assert.equal(nativeChatMessageId("a".repeat(300)).length, "msg_".length + 120);
assert.match(newChatOperationId(), /^web-chat-[a-z0-9]+-[a-z0-9]+$/);
});
test("subscribeChat sends exactly {type:'chat_subscribe',chat_subscribe:{session_id}}", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_subscribe" });
await repo.subscribeChat("ses_eae413f50ffeLQDExlg8cYnscN");
assert.deepEqual(lastFrame(ws), {
type: "chat_subscribe",
chat_subscribe: { session_id: "ses_eae413f50ffeLQDExlg8cYnscN" },
});
});
test("subscribeChat rejects a blank session id without sending anything", async () => {
const { repo, ws } = connected();
await assert.rejects(() => repo.subscribeChat(" "), ProtocolError);
assert.equal(ws.sent.length, 0);
});
test("subscribeChat surfaces a server refusal as a ProtocolError", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unknown command: chat_subscribe" });
await assert.rejects(() => repo.subscribeChat("ses_1"), {
name: "ProtocolError",
message: "unknown command: chat_subscribe",
});
});
// ---- The approval reply (C10) ---------------------------------------------
test("chatReply sends exactly {type:'chat_reply', chat_reply:{session_id,request_id,decision,client}}", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_reply" });
await repo.chatReply("s1", "req-1", "once");
assert.deepEqual(lastFrame(ws), {
type: "chat_reply",
chat_reply: { session_id: "s1", request_id: "req-1", decision: "once", client: "Web" },
});
});
test("chatReply includes message only when non-blank", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_reply" });
await repo.chatReply("s1", "req-1", "always", { message: " looks fine " });
assert.deepEqual(lastFrame(ws), {
type: "chat_reply",
chat_reply: {
session_id: "s1",
request_id: "req-1",
decision: "always",
client: "Web",
message: "looks fine",
},
});
await repo.chatReply("s1", "req-1", "reject", { message: " " });
assert.deepEqual(lastFrame(ws), {
type: "chat_reply",
chat_reply: { session_id: "s1", request_id: "req-1", decision: "reject", client: "Web" },
});
});
test("chatReply refuses blank ids or a decision outside once/always/reject without sending", async () => {
const { repo, ws } = connected();
await assert.rejects(() => repo.chatReply(" ", "req-1", "once"), ProtocolError);
await assert.rejects(() => repo.chatReply("s1", " ", "once"), ProtocolError);
await assert.rejects(() => repo.chatReply("s1", "req-1", "maybe"), ProtocolError);
await assert.rejects(() => repo.chatReply("s1", "req-1", ""), ProtocolError);
assert.equal(ws.sent.length, 0);
});
// --- C11: background shells -------------------------------------------------
test("chatShells sends the session as chat_query and returns the list", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({
id: frame.id,
type: "chat_shells",
chat_shells: [{ id: "sh1", status: "running", command: "go test ./..." }],
});
const shells = await repo.chatShells("ses_eae413f50ffeLQDExlg8cYnscN");
assert.deepEqual(lastFrame(ws), {
type: "chat_shells",
chat_query: { session_id: "ses_eae413f50ffeLQDExlg8cYnscN" },
});
assert.deepEqual(shells, [{ id: "sh1", status: "running", command: "go test ./..." }]);
});
test("chatShells returns [] when the reply carries none", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_shells" });
assert.deepEqual(await repo.chatShells("ses_1"), []);
});
test("chatShells refuses a blank session id without sending anything", async () => {
const { repo, ws } = connected();
await assert.rejects(() => repo.chatShells(" "), {
name: "ProtocolError",
message: "Select a chat session first.",
});
assert.equal(ws.sent.length, 0);
});
test("chatShellOutput sends chat_shell_output_query with cursor 0 and the 64 KiB limit", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({
id: frame.id,
type: "chat_shell_output",
chat_shell_output: { shell: { id: "sh1", status: "running" }, output: "hello", cursor: 5, size: 5 },
});
const page = await repo.chatShellOutput("ses_1", "sh1");
assert.deepEqual(lastFrame(ws), {
type: "chat_shell_output",
chat_shell_output_query: { session_id: "ses_1", shell_id: "sh1", cursor: 0, limit: 64 << 10 },
});
assert.equal(SHELL_OUTPUT_LIMIT, 65536);
assert.equal(page.output, "hello");
});
test("a refresh always rereads from cursor 0, never appending", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({
id: frame.id,
type: "chat_shell_output",
chat_shell_output: { shell: { id: "sh1", status: "running" }, output: "full page", truncated: true },
});
await repo.chatShellOutput("ses_1", "sh1", { cursor: 0, limit: SHELL_OUTPUT_LIMIT });
await repo.chatShellOutput("ses_1", "sh1", { cursor: 0, limit: SHELL_OUTPUT_LIMIT });
const frames = ws.sent.filter((frame) => frame.type === "chat_shell_output");
assert.equal(frames.length, 2);
for (const frame of frames) {
assert.equal(frame.chat_shell_output_query.cursor, 0);
assert.equal(frame.chat_shell_output_query.limit, 65536);
}
});
test("chatShellOutput refuses blank ids and out-of-bounds reads", async () => {
const { repo, ws } = connected();
await assert.rejects(() => repo.chatShellOutput("", "sh1"), {
name: "ProtocolError",
message: "Select a shell first.",
});
await assert.rejects(() => repo.chatShellOutput("ses_1", " "), {
name: "ProtocolError",
message: "Select a shell first.",
});
await assert.rejects(() => repo.chatShellOutput("ses_1", "sh1", { cursor: -1 }), {
name: "ProtocolError",
message: "Shell output bounds are invalid.",
});
await assert.rejects(() => repo.chatShellOutput("ses_1", "sh1", { limit: 0 }), {
name: "ProtocolError",
message: "Shell output bounds are invalid.",
});
await assert.rejects(() => repo.chatShellOutput("ses_1", "sh1", { limit: SHELL_OUTPUT_LIMIT + 1 }), {
name: "ProtocolError",
message: "Shell output bounds are invalid.",
});
assert.equal(ws.sent.length, 0);
});
test("chatShellOutput throws when the reply carries no page", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_shell_output" });
await assert.rejects(() => repo.chatShellOutput("ses_1", "sh1"), {
name: "ProtocolError",
message: "The server returned no shell output page.",
});
});
-299
View File
@@ -1,299 +0,0 @@
// Unit tests for the pure URL route model (web/src/routes.js). No DOM and no
// server: every case here is a claim the live UI smoke relies on.
import test from "node:test";
import assert from "node:assert/strict";
import {
DEFAULT_ROUTE,
parseRoute,
sameRoute,
serializeRoute,
} from "../src/routes.js";
const defaultRoute = () => ({ ...DEFAULT_ROUTE });
test("pipeline-specific Runs links survive reload and ignore invalid filter ids", () => {
assert.deepEqual(parseRoute("/runs?pipeline=27"), { kind: "runs", pipelineId: 27 });
assert.equal(serializeRoute({ kind: "runs", pipelineId: 27 }), "/runs?pipeline=27");
assert.deepEqual(parseRoute("/runs?pipeline=bad"), { kind: "runs" });
assert.equal(serializeRoute({ kind: "runs", pipelineId: -1 }), "/runs");
});
test("default destination: empty, root, unknown and malformed paths", () => {
for (const path of [
undefined,
null,
"",
"/",
"///",
"/nope",
"/pipelinesx",
"/runs/abc",
"/runs/0",
"/runs/-1",
"/runs/1x",
"/pipelines/x",
"/pipelines/24/-1",
"/pipelines/24/1x",
"/pipelines/24/5/nope",
"/pipelines/24/5/stage",
"/runs/440/stage",
// A trailing segment on a versionless stage branch is malformed, not a
// dropped visit or an ignored extra: both stage branches require exactly
// four segments (the versioned pipeline branch already rejected extras).
"/runs/440/stage/planner/extra",
"/runs/440/stage/planner/2",
"/pipelines/24/stage/planner/extra",
"/pipelines/24/stage/planner/2",
"/runs/%E0%A4%A",
"/pipelines/%E0%A4%A",
"/templates/%E0%A4%A",
"/runs/440/stage/%E0%A4%A",
]) {
assert.deepEqual(parseRoute(path), defaultRoute(), `path ${JSON.stringify(path)}`);
}
});
test("top-level destinations", () => {
assert.deepEqual(parseRoute("/pipelines"), { kind: "pipelines" });
assert.deepEqual(parseRoute("/runs"), { kind: "runs" });
assert.deepEqual(parseRoute("/chat"), { kind: "chat" });
assert.deepEqual(parseRoute("/chat/ses_abc123"), { kind: "chatSession", id: "ses_abc123" });
assert.deepEqual(parseRoute("/chat/ses_a/b"), { kind: "pipelines" });
assert.deepEqual(parseRoute("/chat/"), { kind: "chat" });
assert.deepEqual(parseRoute("/settings"), { kind: "settings" });
assert.deepEqual(parseRoute("/templates"), { kind: "templates" });
});
test("trailing slashes are normalised and location-style strings accepted", () => {
assert.deepEqual(parseRoute("/runs/"), { kind: "runs" });
assert.deepEqual(parseRoute("/runs/440/"), { kind: "run", id: 440 });
assert.deepEqual(parseRoute("http://127.0.0.1:8090/runs/440?visit=2"), {
kind: "run",
id: 440,
});
assert.deepEqual(parseRoute("http://127.0.0.1:8090/runs/440"), { kind: "run", id: 440 });
assert.deepEqual(parseRoute("/runs/440?action=decide"), { kind: "run", id: 440, action: "decide" });
});
test("pipeline detail: absent and zero versions are the same latest route", () => {
const latest = { kind: "pipeline", id: 24, version: 0 };
assert.deepEqual(parseRoute("/pipelines/24"), latest);
assert.deepEqual(parseRoute("/pipelines/24/0"), latest);
assert.deepEqual(parseRoute("/pipelines/24/5"), { kind: "pipeline", id: 24, version: 5 });
assert.equal(serializeRoute(parseRoute("/pipelines/24")), "/pipelines/24");
assert.equal(serializeRoute(parseRoute("/pipelines/24/0")), "/pipelines/24");
assert.equal(serializeRoute(parseRoute("/pipelines/24/5")), "/pipelines/24/5");
});
test("run detail and the optional decide action", () => {
assert.deepEqual(parseRoute("/runs/440"), { kind: "run", id: 440 });
assert.deepEqual(parseRoute("/runs/440?action=decide"), { kind: "run", id: 440, action: "decide" });
assert.equal(serializeRoute({ kind: "run", id: 440 }), "/runs/440");
assert.equal(serializeRoute({ kind: "run", id: 440, action: "decide" }), "/runs/440?action=decide");
});
test("run stage: optional zero-based visit, invalid visit dropped", () => {
assert.deepEqual(parseRoute("/runs/440/stage/planner"), {
kind: "runStage",
id: 440,
stageKey: "planner",
});
assert.deepEqual(parseRoute("/runs/440/stage/planner", "?visit=2"), {
kind: "runStage",
id: 440,
stageKey: "planner",
visit: 2,
});
assert.deepEqual(parseRoute("/runs/440/stage/planner?visit=0"), {
kind: "runStage",
id: 440,
stageKey: "planner",
visit: 0,
});
// An invalid visit is dropped while the stage route is kept.
for (const query of ["?visit=-1", "?visit=x", "?visit=", "?visit=1.5"]) {
assert.deepEqual(parseRoute("/runs/440/stage/planner", query), {
kind: "runStage",
id: 440,
stageKey: "planner",
});
}
assert.equal(
serializeRoute({ kind: "runStage", id: 440, stageKey: "planner" }),
"/runs/440/stage/planner",
);
assert.equal(
serializeRoute({ kind: "runStage", id: 440, stageKey: "planner", visit: 0 }),
"/runs/440/stage/planner?visit=0",
);
assert.equal(
serializeRoute({ kind: "runStage", id: 440, stageKey: "planner", visit: -1 }),
"/runs/440/stage/planner",
);
});
test("pipeline stage routes, with and without an explicit version", () => {
assert.deepEqual(parseRoute("/pipelines/24/5/stage/planner"), {
kind: "pipelineStage",
id: 24,
version: 5,
stageKey: "planner",
});
assert.deepEqual(parseRoute("/pipelines/24/stage/planner"), {
kind: "pipelineStage",
id: 24,
version: 0,
stageKey: "planner",
});
assert.deepEqual(parseRoute("/pipelines/24/0/stage/planner"), {
kind: "pipelineStage",
id: 24,
version: 0,
stageKey: "planner",
});
assert.equal(
serializeRoute({ kind: "pipelineStage", id: 24, version: 5, stageKey: "planner" }),
"/pipelines/24/5/stage/planner",
);
assert.equal(
serializeRoute({ kind: "pipelineStage", id: 24, version: 0, stageKey: "planner" }),
"/pipelines/24/stage/planner",
);
});
test("templates gallery and detail, including the /settings aliases", () => {
assert.deepEqual(parseRoute("/templates"), { kind: "templates" });
assert.deepEqual(parseRoute("/settings/templates"), { kind: "templates" });
assert.deepEqual(parseRoute("/templates/plan"), { kind: "template", key: "plan" });
assert.deepEqual(parseRoute("/settings/templates/plan"), { kind: "template", key: "plan" });
assert.equal(serializeRoute({ kind: "template", key: "plan" }), "/templates/plan");
assert.equal(
serializeRoute(parseRoute("/settings/templates/plan")),
"/templates/plan",
);
});
test("unknown query state is ignored; only action and visit are read", () => {
assert.deepEqual(parseRoute("/runs/440", "?q=plan&kind=runs&sort=name"), {
kind: "run",
id: 440,
});
assert.deepEqual(parseRoute("/runs", "?q=plan&kind=pipelines&sort=newest"), { kind: "runs" });
assert.deepEqual(parseRoute("/runs/440?visit=2"), { kind: "run", id: 440 });
assert.deepEqual(parseRoute("/runs/440/stage/planner?visit=2&q=x"), {
kind: "runStage",
id: 440,
stageKey: "planner",
visit: 2,
});
});
test("stage and template keys are percent-encoded and round-trip", () => {
const stageKey = "plan/land & go";
const templateKey = "a b/c?d#e";
// A dotted key stays one path segment; serve.mjs must not mistake it for an
// asset when the shell is requested for a hard navigation.
assert.deepEqual(parseRoute(serializeRoute({ kind: "pipelineStage", id: 7, version: 2, stageKey: "plan.v2" })), {
kind: "pipelineStage",
id: 7,
version: 2,
stageKey: "plan.v2",
});
const stage = parseRoute(serializeRoute({ kind: "runStage", id: 7, stageKey, visit: 3 }));
assert.deepEqual(stage, { kind: "runStage", id: 7, stageKey, visit: 3 });
assert.equal(
serializeRoute({ kind: "pipelineStage", id: 7, version: 2, stageKey }),
"/pipelines/7/2/stage/plan%2Fland%20%26%20go",
);
assert.deepEqual(parseRoute(serializeRoute({ kind: "template", key: templateKey })), {
kind: "template",
key: templateKey,
});
assert.equal(serializeRoute({ kind: "template", key: templateKey }), "/templates/a%20b%2Fc%3Fd%23e");
});
test("serialisation is idempotent and parse(serialize(route)) preserves every route", () => {
const routes = [
{ kind: "pipelines" },
{ kind: "runs" },
{ kind: "chat" },
{ kind: "chatSession", id: "ses_abc123" },
{ kind: "settings" },
{ kind: "templates" },
{ kind: "template", key: "plan" },
{ kind: "pipeline", id: 24, version: 0 },
{ kind: "pipeline", id: 24, version: 5 },
{ kind: "pipelineStage", id: 24, version: 0, stageKey: "planner" },
{ kind: "pipelineStage", id: 24, version: 5, stageKey: "plan/land" },
{ kind: "run", id: 440 },
{ kind: "run", id: 440, action: "decide" },
{ kind: "runStage", id: 440, stageKey: "planner" },
{ kind: "runStage", id: 440, stageKey: "plan/land", visit: 0 },
];
for (const route of routes) {
const url = serializeRoute(route);
const parsed = parseRoute(url);
assert.equal(serializeRoute(parsed), url, `route ${JSON.stringify(route)}`);
assert.ok(sameRoute(parsed, route), `sameRoute ${JSON.stringify(route)}`);
}
});
test("sameRoute compares the canonical serialised form", () => {
assert.ok(sameRoute({ kind: "pipeline", id: 24 }, { kind: "pipeline", id: 24, version: 0 }));
assert.ok(
sameRoute(
parseRoute("/settings/templates/plan"),
{ kind: "template", key: "plan" },
),
);
assert.ok(!sameRoute({ kind: "run", id: 440 }, { kind: "run", id: 440, action: "decide" }));
assert.ok(!sameRoute({ kind: "runs" }, { kind: "pipelines" }));
});
test("a bad route object serialises to the default, never throws", () => {
assert.equal(serializeRoute(null), "/pipelines");
assert.equal(serializeRoute({}), "/pipelines");
assert.equal(serializeRoute({ kind: "unknown" }), "/pipelines");
assert.equal(serializeRoute({ kind: "pipeline" }), "/pipelines");
assert.equal(serializeRoute({ kind: "runStage", id: 1 }), "/runs");
});
test("the serialiser rejects ids/versions the parser would not accept", () => {
// An invalid id cannot name an entity; the nearest canonical route is the list.
for (const id of [0, -1, 1.5, NaN, Infinity, "abc", "", null]) {
assert.equal(serializeRoute({ kind: "pipeline", id }), "/pipelines", `pipeline id ${String(id)}`);
assert.equal(serializeRoute({ kind: "run", id }), "/runs", `run id ${String(id)}`);
assert.equal(
serializeRoute({ kind: "runStage", id, stageKey: "planner" }),
"/runs",
`runStage id ${String(id)}`,
);
}
// An invalid or negative version falls back to the latest form, which parses
// back to the same route instead of emitting a path the parser rejects.
for (const version of [-1, 1.5, NaN, "abc", ""]) {
assert.equal(
serializeRoute({ kind: "pipeline", id: 24, version }),
"/pipelines/24",
`pipeline version ${String(version)}`,
);
assert.equal(
serializeRoute({ kind: "pipelineStage", id: 24, version, stageKey: "planner" }),
"/pipelines/24/stage/planner",
`pipelineStage version ${String(version)}`,
);
assert.deepEqual(parseRoute(serializeRoute({ kind: "pipelineStage", id: 24, version, stageKey: "planner" })), {
kind: "pipelineStage",
id: 24,
version: 0,
stageKey: "planner",
});
}
// A blank or non-string key cannot describe a stage/template.
assert.equal(serializeRoute({ kind: "pipelineStage", id: 24, stageKey: "" }), "/pipelines");
assert.equal(serializeRoute({ kind: "runStage", id: 440, stageKey: "" }), "/runs");
assert.equal(serializeRoute({ kind: "template", key: "" }), "/templates");
// A canonical numeric string is emitted as the number the parser reads back.
assert.equal(serializeRoute({ kind: "run", id: "440" }), "/runs/440");
assert.equal(serializeRoute({ kind: "pipeline", id: "24", version: "5" }), "/pipelines/24/5");
});
-160
View File
@@ -1,160 +0,0 @@
// A real-page lost-ack regression driven only by a Go httptest server. The Go
// fixture supplies a fake executor and checks that precisely one run exists.
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { join } from "node:path";
import net from "node:net";
import { request } from "node:http";
import { fileURLToPath } from "node:url";
import { eventually, launchChrome } from "./browser.mjs";
const [target, pipelineId, workspace] = process.argv.slice(2);
assert.match(target ?? "", /^127\.0\.0\.1:\d+$/);
const reserve = net.createServer();
await new Promise((resolve) => reserve.listen(0, "127.0.0.1", resolve));
const port = reserve.address().port;
await new Promise((resolve) => reserve.close(resolve));
const serve = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--pipelines", target], {
cwd: fileURLToPath(new URL("..", import.meta.url)),
env: { ...process.env, PIPELINES_WEB_AUTH: "disabled" },
stdio: ["ignore", "pipe", "pipe"],
});
let logs = "";
serve.stdout.on("data", (data) => { logs += data; });
serve.stderr.on("data", (data) => { logs += data; });
let browser;
try {
await eventually(async () => {
if (serve.exitCode != null) throw Error(logs);
return fetch(`http://127.0.0.1:${port}/`).then((r) => r.ok).catch(() => false);
});
const refused = await new Promise((resolve, reject) => {
const req = request({ host: "127.0.0.1", port, path: "/connect", headers: { Connection: "Upgrade", Upgrade: "websocket", Origin: "https://untrusted.example", "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==" } });
req.on("response", (res) => { res.resume(); resolve(res.statusCode); });
req.on("upgrade", (_res, socket) => { socket.destroy(); resolve(101); });
req.on("error", reject);
req.end();
});
assert.equal(refused, 403, "proxy must reject foreign Origin before stripping it upstream");
browser = await launchChrome({ width: 390, height: 844 });
const page = await browser.openPage("about:blank");
await page.addInitScript(`(() => {
const Native = window.WebSocket;
window.WebSocket = class extends Native {
send(data) {
const frame = JSON.parse(data);
if (frame.type === 'run_pipeline') {
const keys = JSON.parse(sessionStorage.getItem('probe-launches') || '[]');
keys.push(frame.request_key);
sessionStorage.setItem('probe-launches', JSON.stringify(keys));
}
super.send(data);
}
set onmessage(handler) {
super.onmessage = (event) => {
const frame = JSON.parse(event.data);
if (frame.type === 'run_started' && !sessionStorage.getItem('probe-dropped')) {
sessionStorage.setItem('probe-dropped', 'yes');
this.close(4000, 'scratch lost ack');
return;
}
handler(event);
};
}
};
})()`);
const pipeline = `http://127.0.0.1:${port}/pipelines/${pipelineId}`;
await page.goto(pipeline);
await page.waitForSelector(".run-pipeline");
await page.click(".run-pipeline");
await page.waitForSelector("#runPrompt");
await page.fill("#runPrompt", "Scratch admission reconciliation with a deliberately long title that must wrap cleanly across the run list without clipping or widening the selected row");
await page.fill("#runWorkspace", workspace);
await page.click(".run-start-confirm");
await eventually(() => page.evaluate("sessionStorage.getItem('probe-dropped') === 'yes'"));
// Reload before any manual retry: the tab's launch identity must survive.
await page.goto(pipeline);
await page.waitForSelector(".run-pipeline");
await page.click(".run-pipeline");
await page.waitForSelector(".run-start-confirm");
assert.equal(await page.evaluate("document.querySelector('.run-start-confirm').textContent"), "Check / retry");
assert.equal(await page.evaluate("document.querySelector('#runPrompt').disabled"), true);
if (process.env.PIPELINES_CAPTURE_DIR) {
await mkdir(process.env.PIPELINES_CAPTURE_DIR, { recursive: true });
await eventually(() => page.evaluate("document.querySelector('.run-start-dialog').getAnimations({subtree:true}).every(a => a.playState !== 'running')"));
await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR, "uncertain-run-recovered.png"));
}
await page.click(".run-start-confirm");
await eventually(() => page.evaluate("/^\\/runs\\/\\d+$/.test(location.pathname)"));
assert.equal(await page.evaluate("JSON.parse(sessionStorage.getItem('probe-launches')).length"), 1);
if (process.env.PIPELINES_CAPTURE_DIR) {
await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR, "single-admitted-run.png"));
}
const runId = await page.evaluate("Number(location.pathname.split('/')[2])");
assert.equal((await fetch(`http://${target}/complete-fixture`, { method: "POST" })).status, 204);
await page.goto(`http://127.0.0.1:${port}/runs/${runId}/stage/work`);
await page.waitForSelector(".stage-pane-back");
const back = await page.evaluate("(() => { const b=document.querySelector('.stage-pane-back'); const r=b.getBoundingClientRect(); return {width:r.width,height:r.height,svg:!!b.querySelector('svg'),text:b.textContent}; })()");
assert.equal(Math.round(back.width), 48);
assert.equal(Math.round(back.height), 48);
assert.equal(back.svg, true);
assert.equal(back.text, "");
await page.click(".audit-open");
await page.waitForSelector(".audit-viewer");
for (const width of [390, 420]) {
await page.resize(width, 844);
await eventually(() => page.evaluate("document.querySelector('.audit-viewer').getAnimations({subtree:true}).every(a => a.playState !== 'running')"));
const measured = await page.evaluate("(() => { const v=document.querySelector('.audit-panel'); const tab=v.querySelector('.audit-tab.active'); const b=v.querySelector('.audit-back'); return {radius:getComputedStyle(tab).borderRadius,tabHeight:tab.getBoundingClientRect().height,backWidth:b.getBoundingClientRect().width,backHeight:b.getBoundingClientRect().height,panelWidth:v.getBoundingClientRect().width,pageWidth:document.documentElement.scrollWidth}; })()");
assert.equal(measured.radius, "0px");
assert.ok(Math.round(measured.tabHeight) >= 48);
assert.equal(Math.round(measured.backWidth), 48);
assert.equal(Math.round(measured.backHeight), 48);
assert.ok(measured.pageWidth <= width && measured.panelWidth <= width);
if (process.env.PIPELINES_CAPTURE_DIR) {
await eventually(() => page.evaluate("document.querySelector('.audit-viewer').getAnimations({subtree:true}).every(a => a.playState !== 'running')"));
await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR, `mobile-audit-${width}.png`));
}
}
await page.click(".audit-back");
await page.click(".stage-pane-back");
await page.goto(pipeline);
await page.waitForSelector(".pipeline-runs");
await page.click(".pipeline-runs");
await eventually(() => page.evaluate(`location.pathname === '/runs' && location.search === '?pipeline=${pipelineId}'`));
await page.waitForSelector(".pipeline-filter-chip");
assert.equal(await page.evaluate("document.querySelectorAll('.list.runs .run-row').length"), 1);
await page.goto(`http://127.0.0.1:${port}/runs?pipeline=${pipelineId}`);
await page.waitForSelector(".pipeline-filter-chip");
assert.equal(await page.evaluate("document.querySelectorAll('.list.runs .run-row').length"), 1);
if (process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR, "pipeline-filtered-runs.png"));
for(const width of [390,420]) {
await page.resize(width,844);
await eventually(() => page.evaluate("document.getAnimations().every(a=>a.playState!=='running')"));
const dimensions=await page.evaluate(`(() => {
const toolbar=document.querySelector('.run-toolbar').getBoundingClientRect();
const applied=document.querySelector('.run-applied-filters').getBoundingClientRect();
const title=document.querySelector('.run-row-title');
const row=document.querySelector('.run-row').getBoundingClientRect();
const scroll=document.querySelector('.run-scroll');
return {toolbarBottom:toolbar.bottom,filterTop:applied.top,titleHeight:title.getBoundingClientRect().height,lineHeight:parseFloat(getComputedStyle(title).lineHeight),whiteSpace:getComputedStyle(title).whiteSpace,rowWidth:row.width,listWidth:scroll.clientWidth,scrollWidth:scroll.scrollWidth,pageWidth:document.documentElement.scrollWidth};
})()`);
assert.ok(dimensions.filterTop>=dimensions.toolbarBottom-1);
assert.equal(dimensions.whiteSpace,'normal');
assert.ok(dimensions.titleHeight>dimensions.lineHeight*1.5);
assert.ok(Math.abs(dimensions.rowWidth-dimensions.listWidth)<1);
assert.ok(dimensions.scrollWidth<=dimensions.listWidth && dimensions.pageWidth<=width);
if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,`wrapped-run-title-${width}.png`));
}
await page.resize(1100,844);
await page.click('.run-row');
await page.waitForSelector('.run-row.selected');
await eventually(() => page.evaluate("document.getAnimations().every(a=>a.playState!=='running')"));
assert.equal(await page.evaluate("Math.round(document.querySelector('.run-row.selected').getBoundingClientRect().width)===document.querySelector('.run-scroll').clientWidth"),true);
if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'full-width-selected-run.png'));
console.log("Lost launch acknowledgement + reload reconciled to the single admitted run.");
} finally {
await browser?.close();
serve.kill("SIGTERM");
await new Promise((resolve) => serve.exitCode != null ? resolve() : serve.once("exit", resolve));
}
-209
View File
@@ -1,209 +0,0 @@
// 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));
}
-68
View File
@@ -1,68 +0,0 @@
// Run graph and Timeline must route to the identical recorded-visit pane.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } 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-run-graph-visit");await mkdir(out,{recursive:true});
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","chat","graph","dialogs"].map(n=>`<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main id="pane-main"></main></div>
<script type="module">
window.fixtureErrors=[];addEventListener('error',event=>fixtureErrors.push(event.message));
import {createModalController} from '/src/modal.js';
import {createDialogsView} from '/src/views/dialogs.js';
import {createRunDetailView} from '/src/views/runDetail.js';
import {createChatView} from '/src/views/chat.js';
const graph={stages:[{key:'plan',type:'model',prompt:'Plan',configs:{},edges:{success:'review'}},{key:'review',type:'model',prompt:'Review',configs:{},edges:{success:'#success',rejected:'plan',extra:'unvisited'}},{key:'unvisited',type:'model',prompt:'Unvisited',configs:{},edges:{success:'#success'}}]};
const steps=[{sequence:1,stage:'plan',status:'completed',outcome:'success',target:'review'},
{sequence:2,stage:'review',status:'completed',outcome:'rejected',target:'plan',session_id:'ses_old',control:{visit:1,max_visits:3}},
{sequence:3,stage:'plan',status:'completed',outcome:'success',target:'review'},
{sequence:4,stage:'review',status:'completed',outcome:'success',target:'#success',session_id:'ses_latest',control:{visit:2,max_visits:3}}];
const run={id:42,pipeline_id:7,version:3,name:'Review fixture',status:'succeeded',graph,steps};
const state={view:'runs',runDetail:run,selectedRunId:42,runTab:'graph',runStagePane:null,runStageSections:new Set()};
const modal=createModalController();window.routes=[];window.requests=[];
const rt={state,modal,views:{},pushRoute:r=>routes.push(r),repo:{getPipeline:async(id,version)=>{requests.push({id,version});return{id,version,graph,source:'# stage review\\n\\n~~~prompt\\nReview latest files.\\n~~~\\n'};}},renderContent:()=>paint()};
rt.views.chat=createChatView(rt);rt.views.dialogs=createDialogsView(rt);rt.views.runDetail=createRunDetailView(rt);
window.paint=()=>{state.runGraph?.unmount();document.querySelector('main').replaceChildren(rt.views.runDetail.renderRunDetail());modal.reconcile();};
window.tab=key=>{modal.closeAll();state.runStagePane=null;state.runTab=key;paint();};
window.visit=()=>state.runStagePane;paint();
</script>`;
const server=createServer(async(req,res)=>{try{const path=new URL(req.url,"http://fixture").pathname;if(path==="/"){res.setHeader("Content-Type","text/html");res.end(html);return;}const file=resolve(root,`.${path}`);if(!file.startsWith(root+"/"))throw Error("outside fixture");res.setHeader("Content-Type",extname(file)===".css"?"text/css":"text/javascript");res.end(await readFile(file));}catch{res.writeHead(404);res.end();}});
await new Promise(r=>server.listen(0,"127.0.0.1",r));let browser,page;
try {
browser=await launchChrome();page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
for(const width of [390,1100]) {
await page.resize(width,844);await page.evaluate("tab('graph')");
await page.waitForSelector('.graph-node[data-key="review"]');
await page.evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');
await page.click('.graph-node[data-key="review"]');await page.waitForSelector('.stage-pane');
assert.deepEqual(await page.evaluate('visit()'),{stageKey:'review',visitIndex:1});
const graphPane=await page.evaluate("document.querySelector('.stage-pane').textContent");
assert.match(graphPane,/ses_latest/);assert.doesNotMatch(graphPane,/ses_old/);
assert.equal(await page.evaluate('requests.length'),0,'graph click must not fetch the definition');
await page.screenshot(resolve(out,`run-graph-latest-visit-${width}.png`));
await page.pressKey('Escape');
await page.evaluate("tab('steps')");await page.click('.timeline-row[data-stage-key="review"][data-visit-index="1"]');await page.waitForSelector('.stage-pane');
assert.equal(await page.evaluate("document.querySelector('.stage-pane').textContent"),graphPane);
assert.deepEqual(await page.evaluate('routes.at(-1)'),{kind:'runStage',id:42,stageKey:'review',visit:1});
await page.screenshot(resolve(out,`timeline-same-visit-${width}.png`));
await page.pressKey('Escape');
}
await page.evaluate("tab('graph')");await page.evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');await page.click('.graph-node[data-key="unvisited"]');await page.waitForSelector('.stage-pane');
assert.equal(await page.evaluate("document.querySelectorAll('.stage-pane .audit-open').length"),0);
assert.equal(await page.evaluate('requests.length'),0);
await page.screenshot(resolve(out,'unvisited-stage-no-fabricated-visit.png'));
await page.pressKey('Escape');
await page.evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))');
await page.click('.graph-node[data-key="review"]');await page.waitForSelector('.audit-open');await page.click('.audit-open');await page.click('[data-audit-tab="definition"]');
await page.waitForText('Review latest files.');assert.deepEqual(await page.evaluate('requests'),[{id:7,version:3}]);
await page.screenshot(resolve(out,'definition-remains-an-explicit-audit-tab.png'));
console.log('PASS: run graph opens the same latest recorded visit as Timeline, route/identity match, unvisited stages fabricate nothing, and definition remains an explicit pinned-version audit tab.');
} catch(error) {
if(page){await page.screenshot(resolve(out,'failure.png'));console.error(await page.evaluate('JSON.stringify({errors:fixtureErrors,visit:visit(),text:document.body.innerText})'));}
throw error;
} finally {await browser?.close();await new Promise(r=>server.close(r));}
-658
View File
@@ -1,658 +0,0 @@
// Pure unit tests for the run-detail helpers: the tab set, the summary rows and
// identity line, input/output field display, the timeline derivation and its
// one-line text, the stage-pane section ordering and field split, the
// file-change/notification formatters and the verdict reason segmentation.
// No server, no DOM.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
RUN_DETAIL_TABS,
looksLikeMarkdown,
RENDERED_RUN_TABS,
EMPTY_INPUT_MESSAGE,
EMPTY_OUTPUT_MESSAGE,
EMPTY_TIMELINE_MESSAGE,
NO_STAGE_DETAILS_MESSAGE,
originalRunPrompt,
STAGE_SESSION_TITLE,
STAGE_EVIDENCE_TITLE,
STAGE_DEFINITION_TITLE,
displayText,
displayMap,
fieldSections,
fieldSectionTitle,
summaryRows,
resourceWaitLine,
runIdentityLine,
runDurationText,
runTimeline,
timelineDescription,
hasArtifacts,
nodeLabel,
resolveTarget,
stageOutcomes,
headlineFields,
evidenceFields,
runStepFields,
stageDefinitionFields,
terminalFields,
controlVisitLabel,
clampVisitIndex,
stageSectionSpecs,
referencedVerdictArtifacts,
verdictReasonSegments,
artifactBaseName,
fileChangeLine,
notificationLine,
fileChangesSummary,
outcomeColorToken,
stateGlyph,
} from "../src/runDetail.js";
import { showRunChangesSummary } from "../src/changes.js";
function step(overrides = {}) {
return {
sequence: 1,
stage: "implementer",
status: "completed",
outcome: "success",
target: "",
diagnostic: "",
started_at: "",
finished_at: "",
control: null,
artifacts: null,
...overrides,
};
}
const TIME_OPTS = { zone: "UTC", locale: "en-GB" };
// ---------------------------------------------------------------------------
// Tabs and empty states
// ---------------------------------------------------------------------------
test("RUN_DETAIL_TABS is the Android order, Summary first, Timeline keyed 'steps'", () => {
assert.deepEqual(
RUN_DETAIL_TABS.map((tab) => tab.key),
["summary", "graph", "input", "output", "steps"],
);
assert.deepEqual(
RUN_DETAIL_TABS.map((tab) => tab.label),
["Summary", "Graph", "Input", "Output", "Timeline"],
);
// The browser keeps the three surfaces that are genuinely views; Input and
// Output are run Summary sections now.
assert.deepEqual(
RENDERED_RUN_TABS.map((tab) => tab.label),
["Summary", "Graph", "Timeline"],
);
});
test("the empty-state strings are exactly the app's wording", () => {
assert.equal(EMPTY_INPUT_MESSAGE, "No input recorded.");
assert.equal(EMPTY_OUTPUT_MESSAGE, "No output recorded.");
assert.equal(EMPTY_TIMELINE_MESSAGE, "No visits recorded.");
assert.equal(NO_STAGE_DETAILS_MESSAGE, "No details recorded for this node.");
assert.equal(STAGE_SESSION_TITLE, "Session");
assert.equal(STAGE_EVIDENCE_TITLE, "This run");
assert.equal(STAGE_DEFINITION_TITLE, "Stage definition");
});
test("originalRunPrompt returns only the recorded string, including an empty prompt", () => {
const prompt = "\n original prompt\nwith lines \n";
assert.equal(originalRunPrompt({
input: { prompt },
title: "different title",
output: { markdown: "different output" },
}), prompt);
assert.equal(originalRunPrompt({ input: { prompt: "" }, title: "not a prompt" }), "");
assert.equal(originalRunPrompt({ input: {}, title: "not a prompt", output: { prompt: "also not" } }), undefined);
assert.equal(originalRunPrompt({ title: "not a prompt" }), undefined);
assert.equal(originalRunPrompt({ input: { prompt: null } }), undefined);
});
// ---------------------------------------------------------------------------
// Field display text
// ---------------------------------------------------------------------------
test("displayText renders primitives, arrays and objects like Format.kt", () => {
assert.equal(displayText("hello"), "hello");
assert.equal(displayText(42), "42");
assert.equal(displayText(true), "true");
assert.equal(displayText(null), "null");
assert.equal(displayText(["a", "b", "c"]), "a, b, c");
assert.equal(displayText({ a: 1, b: "x" }), "a=1, b=x");
assert.equal(displayText([{ k: 1 }, 2]), "k=1, 2");
});
test("displayMap renders one `key: value` line per entry in insertion order", () => {
assert.equal(displayMap({ prompt: "do it", files: ["a", "b"] }), "prompt: do it\nfiles: a, b");
assert.equal(displayMap(null), "");
assert.equal(displayMap({}), "");
});
test("fieldSections keeps insertion order and titles each entry", () => {
const sections = fieldSections({ prompt: "do it", pwd: "/tmp" }, "input");
assert.deepEqual(sections, [
{ key: "prompt", title: "prompt", value: "do it" },
{ key: "pwd", title: "pwd", value: "/tmp" },
]);
assert.deepEqual(fieldSections(null, "input"), []);
});
test("fieldSectionTitle falls back to the prefix and is never empty", () => {
assert.equal(fieldSectionTitle("plan", "input"), "plan");
assert.equal(fieldSectionTitle("", "input"), "input");
assert.equal(fieldSectionTitle(" ", "output"), "output");
});
// ---------------------------------------------------------------------------
// Summary
// ---------------------------------------------------------------------------
test("runIdentityLine carries recorded and completed visits in order", () => {
const run = { id: 430, steps: [step(), step(), step()], completed_steps: 3 };
assert.equal(runIdentityLine(run), "run 430 · 3 recorded visits · 3 completed visits");
assert.equal(
runIdentityLine({ id: 7, steps: [step()], completed_steps: 0 }),
"run 7 · 1 recorded visit · 0 completed visits",
);
});
test("resourceWaitLine appears only when the run is waiting on a resource", () => {
assert.equal(resourceWaitLine({ resource_wait: { resource: "pixel-9" } }), "Waiting for resource pixel-9");
assert.equal(resourceWaitLine({ resource_wait: null }), "");
assert.equal(resourceWaitLine({}), "");
});
test("summaryRows is the Android order, omitting blank values", () => {
const run = {
id: 430,
pipeline_id: 12,
version: 5,
status: "succeeded",
executing: false,
current_stage: "committer",
workspace: "/tmp/wt",
content_hash: "abc123",
created_at: "2026-10-19T09:30:00Z",
finished_at: "2026-10-19T09:32:05Z",
retry_of: 409,
diagnostic: "boom",
resource_wait: { resource: "phone" },
steps: [step(), step(), step()],
completed_steps: 3,
};
const rows = summaryRows(run, 0, TIME_OPTS);
assert.deepEqual(
rows.map((row) => row.key ?? row.kind),
["Pipeline", "Stage", "wait", "Workspace", "Content hash", "Started", "Finished", "Duration", "Retry of", "Diagnostic"],
);
assert.equal(rows[0].value, "id 12 · v5");
assert.equal(rows[2].value, "Waiting for resource phone");
assert.equal(rows[4].monospace, true);
assert.equal(rows[7].value, "2m 5s");
assert.equal(rows[8].value, "run 409");
assert.equal(rows[9].kind, "block");
});
test("the Pipeline summary row carries the pipeline and version for navigation", () => {
const rows = summaryRows({ pipeline_id: 24, name: "Plan and land", version: 6, status: "succeeded" }, 0, TIME_OPTS);
const row = rows.find((entry) => entry.kind === "pipeline");
assert.ok(row, "a pipeline row rather than plain text");
assert.equal(row.key, "Pipeline");
assert.equal(row.value, "id 24 · v6");
assert.equal(row.pipelineId, 24);
assert.equal(row.pipelineName, "Plan and land");
assert.equal(row.version, 6);
});
test("summaryRows omits blank values and the wait line when there is none", () => {
const rows = summaryRows(
{ id: 1, pipeline_id: 2, version: 1, status: "running", executing: false, steps: [], completed_steps: 0 },
0,
TIME_OPTS,
);
assert.ok(rows.every((row) => row.kind !== "wait"));
assert.ok(rows.every((row) => row.value.trim() !== ""));
assert.ok(!rows.some((row) => row.key === "Stage" || row.key === "Workspace"));
});
test("runDurationText is live while executing and stored at rest", () => {
assert.equal(
runDurationText({ executing: true, created_at: "2026-10-19T09:30:00Z" }, Date.parse("2026-10-19T09:31:05Z")),
"1m 5s",
);
assert.equal(runDurationText({ executing: false, created_at: "2026-10-19T09:30:00Z", finished_at: "2026-10-19T09:32:05Z" }, 0), "2m 5s");
assert.equal(runDurationText({ executing: false, created_at: "", finished_at: "" }, 0), null);
});
// ---------------------------------------------------------------------------
// Timeline
// ---------------------------------------------------------------------------
test("runTimeline is one entry per visit with the display visit and index", () => {
const { entries, visitsByStage } = runTimeline([
step({ sequence: 5, stage: "reviewer", outcome: "rejected", control: { visit: 2 } }),
step({ sequence: 2, stage: "reviewer", outcome: "success", control: { visit: 1 } }),
]);
assert.deepEqual(entries.map((entry) => entry.step.sequence), [5, 2]);
const bySeq = new Map(entries.map((entry) => [entry.step.sequence, entry]));
assert.equal(bySeq.get(2).visit, 1);
assert.equal(bySeq.get(2).visitIndex, 0);
assert.equal(bySeq.get(5).visit, 2);
assert.equal(bySeq.get(5).visitIndex, 1);
assert.deepEqual(visitsByStage.get("reviewer").map((s) => s.sequence), [2, 5]);
});
test("runTimeline falls back to the position when control is missing", () => {
const { entries } = runTimeline([step({ sequence: 1 }), step({ sequence: 2 })]);
assert.deepEqual(entries.map((entry) => entry.visit), [1, 2]);
assert.deepEqual(entries.map((entry) => entry.visitIndex), [0, 1]);
assert.deepEqual(runTimeline([]).entries, []);
});
test("timeline entry text prefers the first diagnostic line, else → target", () => {
const { entries } = runTimeline([
step({ diagnostic: "\n first line \nsecond" }),
step({ target: "#success" }),
step({ target: "reviewer" }),
step({}),
]);
assert.equal(entries[0].description, "first line");
assert.equal(entries[1].description, "→ SUCCESS");
assert.equal(entries[2].description, "→ reviewer");
assert.equal(entries[3].description, "");
});
test("timelineDescription mirrors nodeLabel for the terminals", () => {
assert.equal(timelineDescription(step({ target: "#failure" })), "→ FAILURE");
assert.equal(nodeLabel("#success"), "SUCCESS");
assert.equal(nodeLabel("#failure"), "FAILURE");
assert.equal(nodeLabel("reviewer"), "reviewer");
});
test("timeline entries carry the outcome label and the artifact flag", () => {
const { entries } = runTimeline([
step({ outcome: "", status: "running" }),
step({ outcome: "approved", status: "completed", artifacts: [{ name: "session.md" }] }),
step({ outcome: "approved", status: "completed", artifacts: [{ name: "shot.png" }] }),
]);
assert.equal(entries[0].outcomeLabel, "running");
assert.equal(entries[1].outcomeLabel, "approved");
assert.equal(entries[1].hasArtifacts, false);
assert.equal(entries[2].hasArtifacts, true);
assert.equal(hasArtifacts(step()), false);
});
test("timeline duration comes from the shared formatter", () => {
const { entries } = runTimeline([
step({ started_at: "2026-10-15T02:00:00Z", finished_at: "2026-10-15T02:02:05Z" }),
]);
assert.equal(entries[0].duration, "2m 5s");
});
// ---------------------------------------------------------------------------
// Stage pane
// ---------------------------------------------------------------------------
test("controlVisitLabel covers a missing max and the limit", () => {
assert.equal(controlVisitLabel({ visit: 2 }), "2");
assert.equal(controlVisitLabel({ visit: 2, max_visits: 4 }), "2 / 4");
assert.equal(controlVisitLabel({ visit: 2, max_visits: 4, limit_reached: true }), "2 / 4 (limit reached)");
});
test("clampVisitIndex keeps a valid visit and handles an empty list", () => {
assert.equal(clampVisitIndex(0, 3), 0);
assert.equal(clampVisitIndex(99, 3), 2);
assert.equal(clampVisitIndex(-4, 3), 0);
assert.equal(clampVisitIndex(5, 0), 0);
});
test("runStepFields skips blanks and formats the visit", () => {
assert.deepEqual(runStepFields({}), []);
const fields = runStepFields({
status: "completed",
outcome: "success",
target: "#success",
session_id: "sess-1",
agent_active: true,
control: { visit: 3, max_visits: 5, limit_reached: true, model_target: "gpt" },
});
assert.equal(fields.find((f) => f.label === "Visit").value, "3 / 5 (limit reached)");
assert.equal(fields.find((f) => f.label === "Agent").value, "active");
assert.ok(fields.every((f) => f.value.trim() !== ""));
});
test("a turn's input and output render as the document they carry", () => {
const body = "# Composition\n\n- one\n- two\n";
const fields = runStepFields({ input: { markdown: body }, output: { markdown: body } });
const input = fields.find((field) => field.label === "Input");
const output = fields.find((field) => field.label === "Output");
assert.equal(input.value, body);
assert.equal(output.value, body);
assert.equal(input.block, true);
const empty = runStepFields({ output: { markdown: "" } }).find((f) => f.label === "Output");
assert.equal(empty.value, "_(no output)_");
const map = runStepFields({ output: { summary: "ok", changed: "a.go" } }).find((f) => f.label === "Output");
assert.match(map.value, /summary: ok/);
});
test("runStepFields carries every evidence kind the timeline dropped", () => {
const fields = runStepFields({
status: "completed",
diagnostic: "why",
transcript: "said something",
input: { prompt: "do it" },
output: { result: "done" },
file_changes: { status: "partial", files: [{ kind: "modified", path: "a.kt" }], skipped: 2 },
notifications: [{ status: "delivered", destination: "ntfy" }],
});
const labels = fields.map((f) => f.label);
for (const label of ["Status", "Diagnostic", "Transcript", "Input", "Output", "File changes", "Changed files", "Notification"]) {
assert.ok(labels.includes(label), `missing ${label}`);
}
assert.equal(fields.find((f) => f.label === "Input").block, true);
});
test("each visit's pane formats its own capture, never the run aggregate", () => {
const first = step({
sequence: 1,
file_changes: {
status: "partial",
skipped: 2,
diagnostic: "Excluded protected files.",
files: [
{ kind: "added", path: "docs/one.md", patch: "@@ -0,0 +1 @@\n+one" },
{ kind: "modified", path: "src/runner.go", patch: "@@ -1 +1 @@\n-old\n+new" },
],
},
});
const second = step({
sequence: 2,
file_changes: {
status: "complete",
files: [{ kind: "modified", path: "src/retry_test.go", patch: "@@ -1 +3 @@\n-old\n+a\n+b\n+c" }],
},
});
const third = step({
sequence: 3,
file_changes: { status: "complete", files: [] },
});
const firstFields = runStepFields(first);
assert.equal(
firstFields.find((field) => field.label === "File changes").value,
"partial (2 files), 2 skipped · Excluded protected files.",
);
assert.equal(
firstFields.find((field) => field.label === "Changed files").value,
"added docs/one.md +1\nmodified src/runner.go +1 -1",
);
const secondFields = runStepFields(second);
assert.equal(secondFields.find((field) => field.label === "File changes").value, "complete (1 files)");
assert.equal(
secondFields.find((field) => field.label === "Changed files").value,
"modified src/retry_test.go +3 -1",
);
// A captured no-change still shows its honest summary but has no file rows.
const thirdFields = runStepFields(third);
assert.equal(thirdFields.find((field) => field.label === "File changes").value, "complete");
assert.equal(thirdFields.find((field) => field.label === "Changed files"), undefined);
});
test("a step that recorded no capture shows neither File changes nor Changed files", () => {
const fields = runStepFields(step({ file_changes: null }));
assert.ok(!fields.some((field) => field.label === "File changes"));
assert.ok(!fields.some((field) => field.label === "Changed files"));
});
test("showRunChangesSummary gates the Summary aggregate to succeeded only", () => {
assert.equal(showRunChangesSummary("succeeded"), true);
assert.equal(showRunChangesSummary(" SUCCEEDED "), true);
for (const status of ["failed", "running", "waiting", "canceled", "interrupted", ""]) {
assert.equal(showRunChangesSummary(status), false);
}
});
test("headline and evidence split the visit's facts without duplication", () => {
const fields = runStepFields({
status: "completed",
outcome: "success",
target: "cleanup",
session_id: "sess-1",
diagnostic: "why",
transcript: "said",
control: { visit: 2, max_visits: 4, model_target: "gpt" },
started_at: "2026-01-01T00:00:00Z",
finished_at: "2026-01-01T00:00:05Z",
input: { prompt: "x" },
});
const headline = headlineFields(fields).map((f) => f.label);
assert.deepEqual(headline, ["Status", "Outcome", "Duration", "Visit", "Model target", "Target", "Session"]);
const evidence = evidenceFields(fields).map((f) => f.label);
assert.ok(!evidence.some((label) => headline.includes(label)));
assert.ok(evidence.includes("Diagnostic") && evidence.includes("Transcript"));
assert.ok(!evidence.includes("Input") && !evidence.includes("Output"));
});
test("the stage pane shows the stage's artifacts and this visit's changes", () => {
const graph = { stages: [{ key: "implementer", type: "model" }] };
const step1 = step({
stage: "implementer",
input: { prompt: "do it" },
output: { result: "done" },
diagnostic: "why",
file_changes: {
status: "complete",
files: [{ path: "a.go", kind: "modified", patch: "@@ -1 +1 @@\n-old\n+new\n" }],
},
});
const specs = stageSectionSpecs("implementer", graph, [step1], 0, true);
assert.deepEqual(specs.map((spec) => spec.key), ["artifacts", "changes"]);
assert.equal(specs[0].title, "Artifacts · 0 recorded");
assert.equal(specs[0].artifacts, true);
assert.ok(specs[1].title.includes("1 file changed"), specs[1].title);
assert.equal(specs[1].changes, true);
});
test("the session export and definition stay out of the pane sections", () => {
const graph = { stages: [{ key: "reviewer", type: "model" }] };
const withSession = step({
stage: "reviewer",
session_export: { html: "session.html" },
artifacts: [{ name: "session.html", url: "/a" }],
});
const specs = stageSectionSpecs("reviewer", graph, [withSession], 0, true);
assert.deepEqual(specs.map((spec) => spec.key), ["artifacts"]);
assert.ok(!specs.some((spec) => spec.session || spec.key === "definition"));
});
test("a visit with no results still lists the artifacts section and no changes", () => {
const graph = { stages: [{ key: "s", type: "model" }] };
const specs = stageSectionSpecs("s", graph, [step({ stage: "s" })], 0, true);
assert.deepEqual(specs.map((spec) => spec.key), ["artifacts"]);
});
test("stageDefinitionFields labels outcomes with resolved terminals", () => {
const stage = {
key: "planner",
type: "model",
prompt: "do the thing",
output: "plan",
configs: { model: "gpt", provider: "" },
edges: { success: "#", error: "cleanup" },
blocks: { tools: "read\nwrite" },
limits: { max_visits: 3, on: ["exceeded"] },
memory: { notes: "notes.md" },
notify: { on: ["failure"], destination: "ntfy", artifacts: ["log"] },
};
const fields = stageDefinitionFields(stage);
const labels = fields.map((f) => f.label);
for (const label of ["Type", "Prompt", "Output", "Outcomes", "Model", "Tools", "Max visits", "Limit on", "Memory", "Notify on", "Notify destination", "Notify artifacts"]) {
assert.ok(labels.includes(label), `missing ${label}`);
}
assert.ok(fields.every((f) => f.value.trim() !== ""));
const outcomes = fields.find((f) => f.label === "Outcomes").value;
assert.ok(outcomes.includes("success → SUCCESS (terminal)"));
assert.ok(outcomes.includes("error → cleanup"));
assert.equal(stageDefinitionFields({ key: "p" }).map((f) => f.value)[0], "model");
});
test("terminalFields lists incoming routes only", () => {
const graph = { stages: [{ key: "a", edges: { success: "#success" } }] };
assert.deepEqual(terminalFields(graph, "a"), []);
const incoming = terminalFields(graph, "#success");
assert.deepEqual(incoming.map((f) => f.label), ["Incoming routes"]);
assert.ok(incoming[0].value.includes("a · success → SUCCESS"));
});
test("resolveTarget and stageOutcomes mirror the graph semantics", () => {
assert.equal(resolveTarget("error", "#"), "#failure");
assert.equal(resolveTarget("success", "#"), "#success");
assert.equal(resolveTarget("success", "reviewer"), "reviewer");
assert.deepEqual(stageOutcomes({ edges: { error: "x", success: "y", advisory: "z" } }), [
"success",
"advisory",
"error",
]);
});
// ---------------------------------------------------------------------------
// Verdict
// ---------------------------------------------------------------------------
test("verdictReasonSegments splits a reason around every referenced name", () => {
const png = { name: "review.png", url: "/review.png" };
const txt = { name: "report.txt", url: "/report.txt" };
assert.deepEqual(
verdictReasonSegments("Approved: review.png shows the fix; report.txt lists the checks.", [png, txt]),
[
{ text: "Approved: " },
{ text: "review.png", artifact: png },
{ text: " shows the fix; " },
{ text: "report.txt", artifact: txt },
{ text: " lists the checks." },
],
);
});
test("verdictReasonSegments matches a basename and prefers the longer token", () => {
const nested = { name: "shots/wide.png" };
assert.deepEqual(verdictReasonSegments("See wide.png for the wide layout.", [nested]), [
{ text: "See " },
{ text: "wide.png", artifact: nested },
{ text: " for the wide layout." },
]);
const bare = { name: "wide.png" };
assert.deepEqual(verdictReasonSegments("shots/wide.png is the shot", [bare, nested]), [
{ text: "shots/wide.png", artifact: nested },
{ text: " is the shot" },
]);
assert.deepEqual(verdictReasonSegments("nothing referenced here", [{ name: "x.png" }]), [
{ text: "nothing referenced here" },
]);
assert.deepEqual(verdictReasonSegments("", [{ name: "x.png" }]), []);
assert.equal(artifactBaseName("shots\\x.png"), "x.png");
});
test("referencedVerdictArtifacts resolves names to recorded files in recorded order", () => {
const a = { name: "a.png" };
const b = { name: "b.png" };
const verdict = { option: "approved → success", reason: "b.png then a.png", artifacts: ["b.png", "a.png", "invented.png"] };
assert.deepEqual(referencedVerdictArtifacts(verdict, [a, b]), [a, b]);
assert.deepEqual(referencedVerdictArtifacts(null, [a]), []);
assert.deepEqual(referencedVerdictArtifacts({ artifacts: [] }, [a]), []);
});
// ---------------------------------------------------------------------------
// Formatters and colours
// ---------------------------------------------------------------------------
test("fileChangeLine adds a parseable stat, never a fabricated one", () => {
assert.equal(fileChangeLine({ kind: "modified", path: "src/a.kt" }), "modified src/a.kt");
assert.equal(
fileChangeLine({ kind: "modified", path: "src/a.kt", binary: true, truncated: true }),
"modified src/a.kt (binary) (truncated)",
);
// A binary file keeps its marker and never gets a text stat, even if a patch
// string was recorded alongside it.
assert.equal(
fileChangeLine({ kind: "added", path: "shot.png", binary: true, patch: "@@ -1 +1 @@\n-a\n+b" }),
"added shot.png (binary)",
);
assert.equal(
fileChangeLine({
kind: "modified",
path: "src/a.kt",
patch: "@@ -1,2 +1,3 @@\n ctx\n-old\n+new\n+more",
}),
"modified src/a.kt +2 -1",
);
assert.equal(
fileChangeLine({
kind: "modified",
path: "src/a.kt",
truncated: true,
patch: "@@ -1 +1 @@\n-old\n+new",
}),
"modified src/a.kt +1 -1 (truncated)",
);
// Header-only/unparseable text is not a diff and earns no stat.
assert.equal(fileChangeLine({ kind: "modified", path: "src/a.kt", patch: "not a patch" }), "modified src/a.kt");
});
test("notificationLine appends a non-blank diagnostic only", () => {
assert.equal(notificationLine({ status: "delivered", destination: "ntfy" }), "delivered → ntfy");
assert.equal(
notificationLine({ status: "delivered", destination: "ntfy", diagnostic: "ok" }),
"delivered → ntfy · ok",
);
});
test("fileChangesSummary carries status, count, skipped, omitted and diagnostic", () => {
assert.equal(fileChangesSummary({ status: "partial", files: [{}, {}], skipped: 1 }), "partial (2 files), 1 skipped");
assert.equal(
fileChangesSummary({
status: "partial",
files: [{}, {}],
skipped: 1,
omitted: 3,
diagnostic: " Excluded protected files. ",
}),
"partial (2 files), 1 skipped, 3 omitted · Excluded protected files.",
);
assert.equal(
fileChangesSummary({ status: "unavailable", files: [], diagnostic: "snapshot unreadable" }),
"unavailable · snapshot unreadable",
);
assert.equal(fileChangesSummary({ status: "complete", files: [] }), "complete");
assert.equal(fileChangesSummary({}), "");
assert.equal(fileChangesSummary(null), "");
});
test("outcomeColorToken uses the status palette then the flow palette", () => {
assert.equal(outcomeColorToken("success"), "state succeeded");
assert.equal(outcomeColorToken("error"), "state failed");
assert.equal(outcomeColorToken("blocked"), "state blocked");
assert.equal(outcomeColorToken("approved"), "flow 3");
assert.equal(outcomeColorToken("rejected"), "flow 0");
assert.equal(outcomeColorToken("", "running"), "state running");
assert.equal(stateGlyph("succeeded"), "✓");
assert.equal(stateGlyph("nonsense"), "?");
});
test("looksLikeMarkdown recognises stage bodies and leaves legacy maps alone", () => {
assert.equal(looksLikeMarkdown("# outcome\nsuccess\n\n# notes\nDone."), true);
assert.equal(looksLikeMarkdown("Some text\n\n- one\n- two"), true);
assert.equal(looksLikeMarkdown("```js\nconst a = 1;\n```"), true);
assert.equal(looksLikeMarkdown("| a | b |\n| --- | --- |\n| 1 | 2 |"), true);
// Historical field text is a plain map, not markdown.
assert.equal(looksLikeMarkdown("summary: ok\nfindings: none"), false);
assert.equal(looksLikeMarkdown(""), false);
assert.equal(looksLikeMarkdown(null), false);
});
-405
View File
@@ -1,405 +0,0 @@
// The live-updates fold, exercised as a pure delta sequence so the client's
// correctness is pinned without a device or a socket: a created run, a step
// started, a step finished, a run finished, a delta for a run the list does not
// hold, an out-of-order/duplicate delta, and a reconnect resync.
//
// A direct port of android/.../ui/RunEventsTest.kt, so the browser fold and the
// app fold are proven against the same shape.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
TERMINAL_RUN_STATUSES,
executingFor,
foldRunEvent,
foldRunEventDetail,
isTerminalRunStatus,
isWaitingRunStatus,
newRunSummaryFromFrame,
runDetailNeedsFullSync,
runLifecycleRank,
stepLifecycleRank,
} from "../src/runEvents.js";
function summary(id, { status = "running", executing = true, currentStage = "", completedSteps = 0, finishedAt = "" } = {}) {
return {
id,
pipeline_id: 4,
name: "pipeline",
status,
executing,
current_stage: currentStage,
completed_steps: completedSteps,
created_at: "2026-10-17T09:00:00Z",
finished_at: finishedAt,
};
}
function detail({ id = 1, status = "queued", executing = true, currentStage = "", completedSteps = 0, finishedAt = "", steps = [] } = {}) {
return {
id,
pipeline_id: 4,
name: "pipeline",
status,
executing,
current_stage: currentStage,
completed_steps: completedSteps,
created_at: "2026-10-17T09:00:00Z",
finished_at: finishedAt,
steps,
};
}
function step({ sequence = 1, stage = "build", status = "running", outcome = "", target = "" } = {}) {
return { sequence, stage, status, outcome, target };
}
function frame({
runId = 1,
status = "",
currentStage = "",
outcome = "",
completedSteps = 0,
finishedAt = "",
step: stepDelta = null,
pipelineId = 0,
name = "",
title = "",
version = 0,
createdAt = "",
} = {}) {
return {
run_id: runId,
workspace: "/work",
pipeline_id: pipelineId,
name,
title,
version,
status,
outcome,
current_stage: currentStage,
completed_steps: completedSteps,
created_at: createdAt,
finished_at: finishedAt,
step: stepDelta,
};
}
// --- lifecycle vocabulary ----------------------------------------------------
test("run summaries and detail preserve notification mode from live frames", () => {
const incoming = { ...frame({ pipelineId: 4, name: "test", status: "queued" }), notify_mode: "off" };
assert.equal(newRunSummaryFromFrame(incoming).notify_mode, "off");
const runs = [summary(1)];
const folded = foldRunEvent(runs, { ...incoming, status: "running" });
assert.equal(folded.runs[0].notify_mode, "off");
const result = foldRunEventDetail(detail({status:"running"}), { ...incoming, status: "failed" });
assert.equal(result.notify_mode, "off");
});
test("the lifecycle ladders mirror RunEvents.kt", () => {
assert.deepEqual(TERMINAL_RUN_STATUSES, ["succeeded", "failed", "canceled", "interrupted"]);
assert.equal(runLifecycleRank("queued"), 0);
assert.equal(runLifecycleRank("running"), 1);
assert.equal(runLifecycleRank("waiting"), 1);
assert.equal(runLifecycleRank("succeeded"), 2);
assert.equal(runLifecycleRank("nonsense"), -1);
assert.equal(stepLifecycleRank("running"), 1);
assert.equal(stepLifecycleRank("completed"), 2);
assert.equal(stepLifecycleRank(""), -1);
assert.equal(isWaitingRunStatus(" waiting "), true);
assert.equal(isTerminalRunStatus("SUCCEEDED"), true);
assert.equal(isTerminalRunStatus("waiting"), false);
assert.equal(executingFor("queued", false), true);
assert.equal(executingFor("waiting", true), false);
assert.equal(executingFor("", true), true);
assert.equal(executingFor("", false), false);
});
// --- runs list ---------------------------------------------------------------
test("a delta updates a matching row in place without reordering", () => {
const runs = [summary(3, { status: "succeeded", executing: false }), summary(1)];
const fold = foldRunEvent(runs, frame({ runId: 1, status: "running", currentStage: "build", completedSteps: 1 }));
assert.equal(fold.needsResync, false);
assert.deepEqual(fold.runs.map((run) => run.id), [3, 1]);
const updated = fold.runs.find((run) => run.id === 1);
assert.equal(updated.status, "running");
assert.equal(updated.current_stage, "build");
assert.equal(updated.completed_steps, 1);
assert.equal(updated.executing, true);
assert.equal(fold.runs[0], runs[0], "the other row is shared, not copied");
});
test("a new run appears from its frame without a fetch", () => {
const runs = [summary(1, { status: "succeeded", executing: false })];
const fold = foldRunEvent(
runs,
frame({
runId: 9,
status: "queued",
pipelineId: 4,
name: "pipeline",
title: "a fresh run",
version: 3,
createdAt: "2026-10-17T09:30:00Z",
}),
);
assert.equal(fold.needsResync, false);
assert.deepEqual(fold.runs.map((run) => run.id), [9, 1]);
const added = fold.runs[0];
assert.equal(added.pipeline_id, 4);
assert.equal(added.name, "pipeline");
assert.equal(added.title, "a fresh run");
assert.equal(added.version, 3);
assert.equal(added.status, "queued");
assert.equal(added.executing, true);
assert.equal(added.created_at, "2026-10-17T09:30:00Z");
});
test("a frame for an unknown run without identity still asks for a resync", () => {
const runs = [summary(1)];
const fold = foldRunEvent(runs, frame({ runId: 9, status: "queued" }));
assert.equal(fold.needsResync, true);
assert.equal(fold.runs, runs);
});
test("an inserted run then advances in place", () => {
const created = foldRunEvent(
[],
frame({ runId: 9, status: "queued", pipelineId: 4, name: "pipeline", version: 1, createdAt: "2026-10-17T09:30:00Z" }),
).runs;
const running = foldRunEvent(created, frame({ runId: 9, status: "running", currentStage: "build", completedSteps: 1 }));
assert.equal(running.needsResync, false);
assert.equal(running.runs.length, 1);
assert.equal(running.runs[0].status, "running");
assert.equal(running.runs[0].current_stage, "build");
const done = foldRunEvent(
running.runs,
frame({ runId: 9, status: "succeeded", outcome: "success", completedSteps: 1, finishedAt: "2026-10-17T09:31:00Z" }),
);
assert.equal(done.runs.length, 1);
assert.equal(done.runs[0].status, "succeeded");
assert.equal(done.runs[0].executing, false);
});
test("a delta for an unknown run also asks for a resync", () => {
const runs = [summary(1, { status: "succeeded", executing: false })];
const fold = foldRunEvent(runs, frame({ runId: 42, status: "running", currentStage: "x" }));
assert.equal(fold.needsResync, true);
assert.deepEqual(fold.runs.map((run) => run.id), [1]);
});
test("a duplicate or out-of-order list delta never regresses a run", () => {
const settled = [summary(1, { status: "succeeded", executing: false, finishedAt: "2026-10-17T09:05:00Z" })];
const fold = foldRunEvent(settled, frame({ runId: 1, status: "running", currentStage: "build" }));
assert.equal(fold.needsResync, false);
assert.equal(fold.runs[0].status, "succeeded");
assert.equal(fold.runs[0].executing, false);
assert.equal(fold.runs, settled, "an unchanged fold keeps the original list");
});
test("a terminal run delta settles the row and stops executing", () => {
const fold = foldRunEvent(
[summary(1, { status: "running" })],
frame({ runId: 1, status: "failed", outcome: "error", finishedAt: "2026-10-17T09:06:00Z" }),
);
const run = fold.runs[0];
assert.equal(run.status, "failed");
assert.equal(run.outcome, "error");
assert.equal(run.executing, false);
assert.equal(run.finished_at, "2026-10-17T09:06:00Z");
});
test("a stale running frame after terminal leaves the list unchanged whole", () => {
const terminal = [summary(1, { status: "succeeded", executing: false, finishedAt: "2026-10-17T09:06:00Z" })];
const fold = foldRunEvent(terminal, frame({ runId: 1, status: "running", currentStage: "build", completedSteps: 3 }));
assert.equal(fold.runs, terminal, "the whole frame is dropped, not just its status");
assert.equal(fold.runs[0].current_stage, "");
assert.equal(fold.runs[0].completed_steps, 0);
});
test("a second, different terminal word is dropped", () => {
const failed = [summary(1, { status: "failed", executing: false })];
const fold = foldRunEvent(failed, frame({ runId: 1, status: "canceled" }));
assert.equal(fold.runs, failed);
assert.equal(fold.runs[0].status, "failed");
});
// --- run detail --------------------------------------------------------------
test("a step started delta adds the visit and runs the run", () => {
const folded = foldRunEventDetail(
detail(),
frame({ runId: 1, status: "running", currentStage: "build", step: { sequence: 1, stage: "build", status: "running" } }),
);
assert.equal(folded.status, "running");
assert.equal(folded.executing, true);
assert.equal(folded.current_stage, "build");
assert.equal(folded.steps.length, 1);
assert.equal(folded.steps[0].sequence, 1);
assert.equal(folded.steps[0].status, "running");
});
test("a step finished delta settles the visit and counts it", () => {
const started = detail({ status: "running", currentStage: "build", steps: [step()] });
const folded = foldRunEventDetail(
started,
frame({
runId: 1,
status: "running",
currentStage: "build",
completedSteps: 1,
step: { sequence: 1, stage: "build", status: "completed", outcome: "success", target: "#success" },
}),
);
assert.equal(folded.steps.length, 1);
assert.equal(folded.steps[0].status, "completed");
assert.equal(folded.steps[0].outcome, "success");
assert.equal(folded.steps[0].target, "#success");
assert.equal(folded.completed_steps, 1);
assert.equal(folded.executing, true, "the run is still going until the terminal frame");
});
test("a run finished delta settles the run with its terminal fields", () => {
const folded = foldRunEventDetail(
detail({ status: "running", executing: true, currentStage: "build" }),
frame({ runId: 1, status: "succeeded", outcome: "success", finishedAt: "2026-10-17T09:07:00Z", completedSteps: 2 }),
);
assert.equal(folded.status, "succeeded");
assert.equal(folded.outcome, "success");
assert.equal(folded.executing, false);
assert.equal(folded.finished_at, "2026-10-17T09:07:00Z");
assert.equal(folded.completed_steps, 2);
});
test("a duplicate step delta is idempotent", () => {
const started = foldRunEventDetail(
detail(),
frame({ runId: 1, status: "running", step: { sequence: 1, stage: "build", status: "running" } }),
);
const again = foldRunEventDetail(
started,
frame({ runId: 1, status: "running", step: { sequence: 1, stage: "build", status: "running" } }),
);
assert.equal(again.steps.length, 1);
assert.equal(again, started, "a duplicate changes nothing");
});
test("an out-of-order step delta never reopens a settled visit", () => {
const settled = detail({
status: "running",
steps: [step({ status: "completed", outcome: "success", target: "#success" })],
});
const folded = foldRunEventDetail(
settled,
frame({ runId: 1, status: "running", step: { sequence: 1, stage: "build", status: "running" } }),
);
assert.equal(folded.steps[0].status, "completed");
assert.equal(folded.steps[0].outcome, "success");
assert.equal(folded, settled);
});
test("a settled step keeps its word against another terminal delta", () => {
const settled = detail({
status: "running",
steps: [step({ status: "completed", outcome: "success", target: "#success" })],
});
const folded = foldRunEventDetail(
settled,
frame({ runId: 1, status: "running", step: { sequence: 1, stage: "build", status: "failed", outcome: "error" } }),
);
assert.equal(folded.steps[0].status, "completed");
assert.equal(folded.steps[0].outcome, "success");
assert.equal(folded, settled);
});
test("a later visit is inserted in sequence order", () => {
const started = detail({
status: "running",
steps: [step({ sequence: 1, status: "completed", outcome: "success", target: "#success" })],
});
const folded = foldRunEventDetail(
started,
frame({ runId: 1, status: "running", step: { sequence: 2, stage: "review", status: "running" } }),
);
assert.deepEqual(folded.steps.map((s) => s.sequence), [1, 2]);
const lower = foldRunEventDetail(
folded,
frame({ runId: 1, status: "running", step: { sequence: 0, stage: "plan", status: "running" } }),
);
assert.deepEqual(lower.steps.map((s) => s.sequence), [0, 1, 2]);
});
test("a frame for another run leaves the detail untouched", () => {
const mine = detail({ id: 1, status: "running" });
const folded = foldRunEventDetail(mine, frame({ runId: 2, status: "succeeded" }));
assert.equal(folded, mine);
});
test("resource_wait_set sets and clears the wait explicitly", () => {
const waiting = foldRunEventDetail(
detail({ status: "running" }),
{ ...frame({ runId: 1, status: "waiting" }), resource_wait_set: true, resource_wait: { resource: "gpu", stage: "build", sequence: 1, queued_since: "2026-10-17T09:00:00Z" } },
);
assert.deepEqual(waiting.resource_wait, { resource: "gpu", stage: "build", sequence: 1, queued_since: "2026-10-17T09:00:00Z" });
const cleared = foldRunEventDetail(waiting, { ...frame({ runId: 1 }), resource_wait_set: true });
assert.equal(cleared.resource_wait, null);
// A terminal status always clears it.
const terminal = foldRunEventDetail(waiting, frame({ runId: 1, status: "succeeded" }));
assert.equal(terminal.resource_wait, null);
});
// --- resync ------------------------------------------------------------------
test("a reconnect resync takes the server snapshot then ignores a late older delta", () => {
const stale = detail({ status: "running", currentStage: "build" });
const snapshot = foldRunEventDetail(
stale,
frame({
runId: 1,
status: "succeeded",
outcome: "success",
completedSteps: 1,
finishedAt: "2026-10-17T09:07:00Z",
step: { sequence: 1, stage: "build", status: "completed", outcome: "success", target: "#success" },
}),
);
const after = foldRunEventDetail(snapshot, frame({ runId: 1, status: "running", currentStage: "build" }));
assert.equal(after.status, "succeeded");
assert.equal(after.outcome, "success");
assert.equal(after.executing, false);
assert.equal(after.completed_steps, 1);
assert.equal(after.steps.length, 1);
assert.equal(after.steps[0].status, "completed");
});
// --- sync heuristic ----------------------------------------------------------
test("settled visits, terminal runs and pending decisions need a full detail sync", () => {
assert.equal(runDetailNeedsFullSync(frame({ runId: 1, step: { sequence: 1, status: "completed" } })), true);
assert.equal(runDetailNeedsFullSync(frame({ runId: 1, step: { sequence: 1, status: "failed" } })), true);
assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "succeeded" })), true);
assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "canceled" })), true);
assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "waiting" })), true);
assert.equal(runDetailNeedsFullSync(frame({ runId: 1, step: { sequence: 1, status: "waiting" } })), true);
assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "running", step: { sequence: 1, status: "running" } })), false);
assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "queued" })), false);
assert.equal(runDetailNeedsFullSync(frame({ runId: 1, status: "running" })), false);
});
test("a waiting human stage is not executing", () => {
assert.equal(isTerminalRunStatus("waiting"), false);
const fold = foldRunEvent([summary(1, { status: "running" })], frame({ runId: 1, status: "waiting", currentStage: "gate" }));
assert.equal(fold.runs[0].status, "waiting");
assert.equal(fold.runs[0].executing, false, "a parked human stage shows no spinner");
});
test("newRunSummaryFromFrame requires a pipeline identity and a name", () => {
assert.equal(newRunSummaryFromFrame(frame({ runId: 9, status: "queued" })), null);
assert.equal(newRunSummaryFromFrame(frame({ runId: 9, status: "queued", pipelineId: 4, name: " " })), null);
const built = newRunSummaryFromFrame(frame({ runId: 9, status: "queued", pipelineId: 4, name: "p", version: 2 }));
assert.equal(built.id, 9);
assert.equal(built.pipeline_id, 4);
assert.equal(built.title, null);
});
-22
View File
@@ -1,22 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { createRunIntent, saveRunIntent, pendingRun, clearRunIntent } from "../src/runIntent.js";
test("pending launch identity and payload survive reload and stay endpoint-scoped", () => {
const values = new Map();
const storage = { getItem: (key) => values.get(key), setItem: (key, value) => values.set(key, value), removeItem: (key) => values.delete(key) };
const payload = { pipelineId: 7, version: 3, prompt: "report", workspace: "/work", notifyMode: "off" };
const intent = createRunIntent(payload);
assert.ok(intent.requestKey);
saveRunIntent(storage, "ws://server/connect", intent);
assert.deepEqual(pendingRun(storage, "ws://server/connect", 7, 3), intent);
assert.equal(pendingRun(storage, "ws://other/connect", 7, 3), null);
assert.equal(pendingRun(storage, "ws://server/connect", 7, 4), null);
clearRunIntent(storage, "ws://server/connect", intent);
assert.equal(pendingRun(storage, "ws://server/connect", 7, 3), null);
});
test("malformed or unavailable pending-run storage never invents an intent", () => {
assert.equal(pendingRun({ getItem: () => "not json" }, "ws://s", 1, 1), null);
assert.equal(pendingRun({ getItem: () => { throw Error("disabled"); } }, "ws://s", 1, 1), null);
});
-393
View File
@@ -1,393 +0,0 @@
// Pure unit tests for the runs-list helpers: filtering (status/pipeline/time,
// AND-combined), every sort comparator with its id tie-break, day grouping,
// the wording helpers and the list's slot model. No server, no DOM.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
RUN_STATES,
RUN_TIME_RANGES,
RUN_SORTS,
runStateOf,
runIdentity,
versionLabel,
visitCount,
progressText,
metaText,
formatDuration,
secondsSince,
durationSeconds,
localDayKey,
dayLabel,
defaultRunFilters,
runFiltersActiveCount,
runMatchesTimeRange,
filterRuns,
pipelineFilterOptions,
runComparator,
sortRuns,
groupRunsByDay,
runListEntries,
NO_RUNS_MESSAGE,
NO_MATCH_MESSAGE,
} from "../src/runs.js";
/** A finished run on the Today of the tests, with every field the list reads. */
function run(overrides = {}) {
return {
id: 1,
pipeline_id: 1,
name: "Pipe",
title: null,
version: 1,
status: "succeeded",
executing: false,
current_stage: "",
completed_steps: 0,
created_at: "2026-10-19T10:00:00Z",
finished_at: "2026-10-19T10:01:00Z",
diagnostic: "",
resource_wait: null,
...overrides,
};
}
const TODAY = "2026-10-19";
const ZONE = "UTC";
const TIME_OPTS = { zone: ZONE, locale: "en-GB" };
// ---------------------------------------------------------------------------
// Vocabulary and wording
// ---------------------------------------------------------------------------
test("runStateOf maps the server vocabulary and the outcome synonyms", () => {
assert.equal(runStateOf("running"), "running");
assert.equal(runStateOf("succeeded"), "succeeded");
assert.equal(runStateOf("success"), "succeeded");
assert.equal(runStateOf("completed"), "succeeded");
assert.equal(runStateOf("done"), "succeeded");
assert.equal(runStateOf("error"), "failed");
assert.equal(runStateOf("cancelled"), "canceled");
assert.equal(runStateOf(" INTERRUPTED "), "interrupted");
assert.equal(runStateOf(""), "unknown");
assert.equal(runStateOf("nonsense"), "unknown");
});
test("RUN_STATES is exactly the server run vocabulary in display order", () => {
assert.deepEqual(RUN_STATES, [
"queued",
"running",
"waiting",
"succeeded",
"failed",
"canceled",
"interrupted",
]);
});
test("runIdentity falls back to the pipeline name and only splits when titled", () => {
assert.deepEqual(runIdentity(" Fix the thing ", "Plan and land"), {
label: "Fix the thing",
pipeline: "Plan and land",
});
assert.deepEqual(runIdentity(null, "Plan and land"), { label: "Plan and land", pipeline: null });
assert.deepEqual(runIdentity(" ", "Plan and land"), { label: "Plan and land", pipeline: null });
});
test("versionLabel and visitCount use the app's singular/plural spelling", () => {
assert.equal(versionLabel(5), "v5");
assert.equal(visitCount(1, "completed"), "1 completed visit");
assert.equal(visitCount(0, "completed"), "0 completed visits");
assert.equal(visitCount(3, "completed"), "3 completed visits");
});
test("progressText carries resource wait, completed visits and the stage", () => {
assert.equal(
progressText(run({ completed_steps: 2, current_stage: "implementer" })),
"2 completed visits · stage implementer",
);
assert.equal(
progressText(
run({ completed_steps: 1, current_stage: "reviewer", resource_wait: { resource: "pixel-9" } }),
),
"Waiting for resource pixel-9 · 1 completed visit · stage reviewer",
);
assert.equal(progressText(run({ completed_steps: 0 })), "0 completed visits");
});
test("metaText shows a live elapsed while executing and id/start/duration at rest", () => {
const executing = run({
id: 7,
executing: true,
created_at: "2026-10-19T09:30:00Z",
finished_at: "",
});
assert.equal(metaText(executing, Date.parse("2026-10-19T09:31:05Z"), TIME_OPTS), "run 7 · 1m 5s");
// A future start (clock skew) reads as 0s, never a negative.
assert.equal(metaText(executing, Date.parse("2026-10-19T09:00:00Z"), TIME_OPTS), "run 7 · 0s");
const done = run({
id: 7,
created_at: "2026-10-19T09:30:00Z",
finished_at: "2026-10-19T09:32:05Z",
});
assert.equal(metaText(done, 0, TIME_OPTS), "run 7 · 19 Oct 09:30 · 2m 5s");
});
test("formatDuration, secondsSince and durationSeconds mirror Format.kt", () => {
assert.equal(formatDuration(0), "0s");
assert.equal(formatDuration(59), "59s");
assert.equal(formatDuration(60), "1m 0s");
assert.equal(formatDuration(125), "2m 5s");
assert.equal(formatDuration(3725), "1h 2m");
assert.equal(formatDuration(-5), "0s");
assert.equal(secondsSince("2026-10-19T09:30:00Z", Date.parse("2026-10-19T09:31:05Z")), 65);
assert.equal(secondsSince("bad", 0), null);
assert.equal(durationSeconds("2026-10-19T09:30:00Z", "2026-10-19T09:32:05Z"), 125);
assert.equal(durationSeconds("2026-10-19T09:32:05Z", "2026-10-19T09:30:00Z"), null);
assert.equal(durationSeconds("", ""), null);
});
// ---------------------------------------------------------------------------
// Filters
// ---------------------------------------------------------------------------
test("default filters change nothing and count as zero active facets", () => {
const runs = [run({ id: 1 }), run({ id: 2, status: "failed" })];
const filters = defaultRunFilters();
assert.equal(runFiltersActiveCount(filters), 0);
assert.equal(filterRuns(runs, filters, TODAY, ZONE), runs);
});
test("status filter narrows to the selected states; an empty set is any status", () => {
const runs = [
run({ id: 1, status: "succeeded" }),
run({ id: 2, status: "failed" }),
run({ id: 3, status: "canceled" }),
];
const filters = { ...defaultRunFilters(), statuses: new Set(["failed"]) };
assert.deepEqual(
filterRuns(runs, filters, TODAY, ZONE).map((r) => r.id),
[2],
);
// "success" resolves to the succeeded state, so selecting it matches.
const succeeded = { ...defaultRunFilters(), statuses: new Set(["succeeded"]) };
assert.deepEqual(
filterRuns([run({ id: 9, status: "success" })], succeeded, TODAY, ZONE).map((r) => r.id),
[9],
);
assert.equal(runFiltersActiveCount(filters), 1);
});
test("pipeline filter is a single-select; null means any pipeline", () => {
const runs = [run({ id: 1, pipeline_id: 3 }), run({ id: 2, pipeline_id: 4 })];
const filters = { ...defaultRunFilters(), pipelineId: 4 };
assert.deepEqual(
filterRuns(runs, filters, TODAY, ZONE).map((r) => r.id),
[2],
);
assert.equal(runFiltersActiveCount(filters), 1);
});
test("time range is inclusive calendar days ending today and rejects future/blank", () => {
const at = (created_at) => run({ created_at });
assert.equal(runMatchesTimeRange(at("2026-10-19T00:00:00Z"), "today", TODAY, ZONE), true);
assert.equal(runMatchesTimeRange(at("2026-10-18T23:59:59Z"), "today", TODAY, ZONE), false);
// last 7 days covers today and the six days before it (>= 13 Oct).
assert.equal(runMatchesTimeRange(at("2026-10-13T00:00:00Z"), "last_7_days", TODAY, ZONE), true);
assert.equal(runMatchesTimeRange(at("2026-10-12T23:00:00Z"), "last_7_days", TODAY, ZONE), false);
// last 30 days covers >= 20 Sep.
assert.equal(runMatchesTimeRange(at("2026-09-20T00:00:00Z"), "last_30_days", TODAY, ZONE), true);
assert.equal(runMatchesTimeRange(at("2026-09-19T00:00:00Z"), "last_30_days", TODAY, ZONE), false);
// A future-dated run and a blank/unparseable timestamp never match a window.
assert.equal(runMatchesTimeRange(at("2026-10-20T00:00:00Z"), "today", TODAY, ZONE), false);
assert.equal(runMatchesTimeRange(at("not-a-date"), "today", TODAY, ZONE), false);
assert.equal(runMatchesTimeRange(at(""), "last_30_days", TODAY, ZONE), false);
// Any time matches everything, including blank.
assert.equal(runMatchesTimeRange(at(""), "any_time", TODAY, ZONE), true);
});
test("the three facets AND-combine and the count is one per facet", () => {
const runs = [
run({ id: 1, pipeline_id: 3, status: "failed", created_at: "2026-10-19T10:00:00Z" }),
run({ id: 2, pipeline_id: 3, status: "succeeded", created_at: "2026-10-19T10:00:00Z" }),
run({ id: 3, pipeline_id: 4, status: "failed", created_at: "2026-10-19T10:00:00Z" }),
run({ id: 4, pipeline_id: 3, status: "failed", created_at: "2026-08-01T10:00:00Z" }),
];
const filters = {
statuses: new Set(["failed"]),
pipelineId: 3,
timeRange: "last_7_days",
};
assert.equal(runFiltersActiveCount(filters), 3);
assert.deepEqual(
filterRuns(runs, filters, TODAY, ZONE).map((r) => r.id),
[1],
);
});
test("pipelineFilterOptions names each pipeline from its newest non-blank run and sorts by name then id", () => {
const options = pipelineFilterOptions([
run({ pipeline_id: 5, name: "beta" }),
run({ pipeline_id: 5, name: "" }),
run({ pipeline_id: 2, name: "Alpha" }),
run({ pipeline_id: 9, name: "" }),
]);
assert.deepEqual(options, [
{ id: 2, name: "Alpha" },
{ id: 5, name: "beta" },
{ id: 9, name: "Pipeline 9" },
]);
});
// ---------------------------------------------------------------------------
// Sort: every comparator plus an id tie-break
// ---------------------------------------------------------------------------
test("newest first orders by start descending, then id descending", () => {
const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z" });
const b = run({ id: 2, created_at: "2026-10-19T10:00:00Z" });
const c = run({ id: 3, created_at: "2026-10-19T11:00:00Z" });
assert.deepEqual(
sortRuns([a, b, c], "newest_first").map((r) => r.id),
[3, 2, 1],
);
});
test("oldest first orders by start ascending, then id ascending", () => {
const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z" });
const b = run({ id: 2, created_at: "2026-10-19T10:00:00Z" });
const c = run({ id: 3, created_at: "2026-10-19T11:00:00Z" });
assert.deepEqual(
sortRuns([a, b, c], "oldest_first").map((r) => r.id),
[1, 2, 3],
);
});
test("longest duration puts a missing duration last, then duration desc, created desc, id desc", () => {
const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z", finished_at: "2026-10-19T10:05:00Z" }); // 300
const b = run({ id: 2, executing: true, created_at: "2026-10-19T10:00:00Z", finished_at: "" }); // null
const c = run({ id: 3, created_at: "2026-10-19T09:00:00Z", finished_at: "2026-10-19T09:10:00Z" }); // 600
const d = run({ id: 4, created_at: "2026-10-19T08:00:00Z", finished_at: "2026-10-19T08:05:00Z" }); // 300
assert.deepEqual(
sortRuns([a, b, c, d], "longest_duration").map((r) => r.id),
[3, 1, 4, 2],
);
});
test("shortest duration puts a missing duration last, then duration asc, created desc, id desc", () => {
const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z", finished_at: "2026-10-19T10:05:00Z" }); // 300
const b = run({ id: 2, executing: true, created_at: "2026-10-19T10:00:00Z", finished_at: "" }); // null
const c = run({ id: 3, created_at: "2026-10-19T09:00:00Z", finished_at: "2026-10-19T09:10:00Z" }); // 600
const d = run({ id: 4, created_at: "2026-10-19T08:00:00Z", finished_at: "2026-10-19T08:05:00Z" }); // 300
assert.deepEqual(
sortRuns([a, b, c, d], "shortest_duration").map((r) => r.id),
[1, 4, 3, 2],
);
});
test("pipeline name sorts case-insensitively, then created desc, id desc", () => {
const x = run({ id: 1, name: "beta", created_at: "2026-10-19T10:00:00Z" });
const y = run({ id: 2, name: "Alpha", created_at: "2026-10-19T10:00:00Z" });
const z = run({ id: 3, name: "alpha", created_at: "2026-10-19T11:00:00Z" });
assert.deepEqual(
sortRuns([x, y, z], "pipeline_name").map((r) => r.id),
[3, 2, 1],
);
});
test("status sorts case-insensitively, then created desc, id desc", () => {
const p = run({ id: 1, status: "succeeded", created_at: "2026-10-19T10:00:00Z" });
const q = run({ id: 2, status: "failed", created_at: "2026-10-19T10:00:00Z" });
const r = run({ id: 3, status: "failed", created_at: "2026-10-19T11:00:00Z" });
assert.deepEqual(
sortRuns([p, q, r], "status").map((r) => r.id),
[3, 2, 1],
);
});
test("an unknown sort falls back to newest first", () => {
const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z" });
const b = run({ id: 2, created_at: "2026-10-19T11:00:00Z" });
assert.deepEqual(
sortRuns([a, b], "not_a_sort").map((r) => r.id),
[2, 1],
);
});
test("RUN_SORTS and RUN_TIME_RANGES carry the app's exact labels", () => {
assert.deepEqual(
RUN_SORTS.map((s) => s.label),
["Newest first", "Oldest first", "Longest duration", "Shortest duration", "Pipeline name", "Status"],
);
assert.deepEqual(
RUN_TIME_RANGES.map((r) => r.label),
["Any time", "Today", "Last 7 days", "Last 30 days"],
);
});
// ---------------------------------------------------------------------------
// Day grouping
// ---------------------------------------------------------------------------
test("dayLabel renders Today / Yesterday / d MMM yyyy / Unknown date", () => {
assert.equal(dayLabel("2026-10-19T01:00:00Z", TODAY, ZONE), "Today");
assert.equal(dayLabel("2026-10-18T23:00:00Z", TODAY, ZONE), "Yesterday");
assert.equal(dayLabel("2026-10-16T23:00:00Z", TODAY, ZONE), "16 Oct 2026");
assert.equal(dayLabel("", TODAY, ZONE), "Unknown date");
assert.equal(dayLabel("not-a-date", TODAY, ZONE), "Unknown date");
assert.equal(localDayKey("2026-10-19T01:00:00Z", ZONE), "2026-10-19");
assert.equal(localDayKey("", ZONE), null);
});
test("groupRunsByDay follows the sort order and preserves it within a day", () => {
const r1 = run({ id: 1, created_at: "2026-10-19T10:00:00Z" });
const r2 = run({ id: 2, created_at: "2026-10-19T09:00:00Z" });
const r3 = run({ id: 3, created_at: "2026-10-18T12:00:00Z" });
const r4 = run({ id: 4, created_at: "" });
const groups = groupRunsByDay([r2, r1, r4, r3], TODAY, ZONE, runComparator("newest_first"));
assert.deepEqual(
groups.map((g) => g.label),
["Today", "Yesterday", "Unknown date"],
);
assert.deepEqual(
groups[0].runs.map((r) => r.id),
[1, 2],
);
});
// ---------------------------------------------------------------------------
// The list's slots
// ---------------------------------------------------------------------------
test("runListEntries orders usage, the empty state, groups and the inline error", () => {
const usage = { total: 3 };
const recorded = runListEntries(usage, true, true, [], null);
assert.deepEqual(
recorded.map((e) => e.kind),
["usage", "empty"],
);
assert.equal(recorded[1].message, NO_RUNS_MESSAGE);
assert.equal(recorded[1].actionLabel, null);
const matched = runListEntries(null, false, true, [], "boom");
assert.deepEqual(
matched.map((e) => e.kind),
["empty", "error"],
);
assert.equal(matched[0].message, NO_MATCH_MESSAGE);
assert.equal(matched[0].actionLabel, "Clear filters");
const groups = [{ label: "Today", runs: [run({ id: 1 }), run({ id: 2 })] }];
const body = runListEntries(null, false, false, groups, null);
assert.deepEqual(
body.map((e) => e.kind),
["day", "run", "run"],
);
assert.equal(body[0].label, "Today");
assert.deepEqual(
body.filter((e) => e.kind === "run").map((e) => e.run.id),
[1, 2],
);
});
-116
View File
@@ -1,116 +0,0 @@
// End-to-end saved schedules against a throwaway Go server/database. Human-only
// workflows and explicit titles/notify=off prevent provider turns/notifications.
// Only this fixture's private SQLite NextDue is advanced to exercise dispatch.
import assert from "node:assert/strict";
import { spawn, execFileSync } from "node:child_process";
import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { resolve, join } from "node:path";
import net from "node:net";
import { PipelinesClient } from "../src/client.js";
import { PipelinesRepository } from "../src/repository.js";
import { validateServerUrl } from "../src/serverUrl.js";
import { launchChrome, eventually } from "./browser.mjs";
const arg=(name,fallback)=>{const i=process.argv.indexOf(name);return i<0?fallback:process.argv[i+1];};
const binary=arg('--server-binary');if(!binary)throw Error('--server-binary must name a current-source scratch binary');
const out=resolve(arg('--out','captures-schedule-integration'));await mkdir(out,{recursive:true});
const scratch=await mkdtemp(join(arg('--tmp-parent',tmpdir()),'schedule-integration-'));
const freePort=()=>new Promise(r=>{const s=net.createServer();s.listen(0,'127.0.0.1',()=>{const port=s.address().port;s.close(()=>r(port));});});
const serverPort=await freePort(),webPort=await freePort();
const source='# stage gate\n\n```prompt\nHuman-only scheduling fixture. Choose done.\n```\n\n```configs\ntype=human\n```\n\n```edges\ndone -> #success\nerror -> #failure\n```\n';
const fake=join(scratch,'opencode');await writeFile(fake,'#!/bin/sh\nprintf "%s\\n" "$*" >> "$PIPELINES_FAKE_LOG"\nexit 1\n',{mode:0o700});
for(const name of ['home','a','b','manual'])await mkdir(join(scratch,name));
const password=join(scratch,'endpoint-password');await writeFile(password,'fixture-only-password',{mode:0o600});
const env={...process.env,HOME:join(scratch,'home'),XDG_CONFIG_HOME:join(scratch,'config'),XDG_DATA_HOME:join(scratch,'data'),XDG_STATE_HOME:join(scratch,'state'),XDG_CACHE_HOME:join(scratch,'cache'),CODEX_HOME:join(scratch,'codex'),PIPELINES_OPENCODE:fake,PIPELINES_FAKE_LOG:join(scratch,'fake-cli.log'),PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE:password,PIPELINES_DEFAULT_MODEL:'fixture/model'};
env.PIPELINES_HARNESS_CONFIG=join(scratch,'no-operator-harness.json');
for(const key of Object.keys(env))if(key.startsWith('PIPELINES_NTFY')||key==='PIPELINES_PREFIX')delete env[key];
const db=join(scratch,'pipeline.db');
const server=spawn(resolve(binary),['-addr',`127.0.0.1:${serverPort}`,'-db',db,'-allow-authoring','-opencode-endpoint','http://127.0.0.1:1'],{cwd:scratch,env,stdio:['ignore','pipe','pipe']});
let serverLog='';server.stdout.on('data',d=>serverLog+=d);server.stderr.on('data',d=>serverLog+=d);
let proxy,browser,page,client;
const ownedRuns=[];
try {
await eventually(async()=>{try{return(await fetch(`http://127.0.0.1:${serverPort}/healthz`)).ok;}catch{return false;}},{timeout:15000,what:'scratch server'});
client=new PipelinesClient();
await new Promise((resolve,reject)=>{const timer=setTimeout(()=>reject(Error('scratch websocket timeout')),5000);client.addEventListener('state',e=>{if(e.detail.kind==='connected'){clearTimeout(timer);resolve();}});client.connect(validateServerUrl(`ws://127.0.0.1:${serverPort}/connect`));});
const repo=new PipelinesRepository(client);
const pipeline=await repo.submit('Reusable research fixture',source);
await repo.submit('No schedules fixture',source);
proxy=spawn(process.execPath,['web/serve.mjs','--host','127.0.0.1','--port',String(webPort),'--pipelines',`127.0.0.1:${serverPort}`],{cwd:resolve(import.meta.dirname,'../..'),env:{...env,PIPELINES_WEB_AUTH:'disabled'},stdio:'ignore'});
await eventually(async()=>{try{return(await fetch(`http://127.0.0.1:${webPort}/`)).ok;}catch{return false;}},{timeout:5000,what:'scratch browser proxy'});
browser=await launchChrome();page=await browser.openPage(`http://127.0.0.1:${webPort}/pipelines/${pipeline.id}`);
await page.waitForSelector('.schedule-add');
const add=async(name,prompt,workspace)=>{
await page.click('.schedule-add');await page.waitForSelector('.schedule-overlay[aria-label="Add schedule"]');
await page.fill('[name=name]',name);await page.fill('[name=prompt]',prompt);await page.fill('[name=workspace]',workspace);await page.fill('[name=timezone]','UTC');
await page.click('[name=enabled]');await page.click('.schedule-advanced summary');await page.fill('[name=notifyMode]','off');await page.fill('[name=title]',name+' future run');
await page.click('.schedule-footer button[type=submit]');
await eventually(()=>page.evaluate("!document.querySelector('.schedule-overlay[aria-label=\"Add schedule\"]')"),{timeout:5000,what:'saved schedule dialog'});
};
await add('Battery item','Research battery recycling',join(scratch,'a'));
await add('AI item','Research model evaluation',join(scratch,'b'));
let schedules=await repo.listSchedules(pipeline.id);assert.equal(schedules.length,2);
let a=schedules.find(s=>s.name==='Battery item'),b=schedules.find(s=>s.name==='AI item');
assert.notEqual(a.input.prompt,b.input.prompt);assert.equal(a.version,1);assert.equal(b.version,1);
await page.screenshot(join(out,'two-independent-items-desktop.png'));
await page.click('#filterToggle');await page.click('[data-pipeline-schedule=scheduled]');
assert.equal(await page.evaluate("document.querySelectorAll('#pipelineRows [data-pipeline-id]').length"),1);
await page.screenshot(join(out,'pipeline-has-schedules-filter.png'));
await page.click('#clearFilters');
await page.click(`[data-schedule-id="${a.id}"] button`);
await page.fill('[name=prompt]','Updated battery topic');
a=await repo.saveSchedule({...a,name:'Renamed externally'});
await page.click('.schedule-footer button[type=submit]');await page.waitForText('Your draft is preserved.');
assert.equal(await page.evaluate("document.querySelector('[name=prompt]').value"),'Updated battery topic');
await page.screenshot(join(out,'concurrent-edit-keeps-draft.png'));
await page.click('.schedule-footer button[type=button]');await page.click('.schedule-refresh');
await page.waitForText('Renamed externally');await page.click(`[data-schedule-id="${a.id}"] button`);await page.fill('[name=prompt]','Updated battery topic');await page.click('.schedule-footer button[type=submit]');
await eventually(()=>page.evaluate("!document.querySelector('.schedule-overlay[aria-label=\"Edit schedule\"]')"),{timeout:5000,what:'saved updated item'});
schedules=await repo.listSchedules(pipeline.id);a=schedules.find(s=>s.id===a.id);b=schedules.find(s=>s.id===b.id);
assert.equal(a.input.prompt,'Updated battery topic');assert.equal(b.input.prompt,'Research model evaluation');
const manualReply=await client.call({type:'run_pipeline',pipeline_id:pipeline.id,version:1,request_key:'manual-scope-fixture',input:{prompt:'Manual control'},workspace:join(scratch,'manual'),title:'Manual fixture run',notify_mode:'off',write_paths:['allowed.txt'],allow_tools:true});
const manual=manualReply.run_detail;ownedRuns.push(manual.id);
assert.equal(manual.scheduled,false);
await page.goto(`http://127.0.0.1:${webPort}/runs/${manual.id}`);await page.waitForSelector('.schedule-run');await page.click('.schedule-run');await page.waitForSelector('.schedule-overlay');
assert.equal(await page.evaluate("document.querySelector('[name=prompt]').value"),'Manual control');
assert.equal(await page.evaluate("document.querySelector('[name=title]').value"),'Manual fixture run');
assert.deepEqual(await page.evaluate("JSON.parse(document.querySelector('[name=writePaths]').value)"),['allowed.txt']);
await page.screenshot(join(out,'schedule-this-run-preserves-input-title-and-write-scope.png'));
await page.click('.schedule-footer button[type=button]');
assert.equal(await page.evaluate("document.activeElement.classList.contains('schedule-run')"),true);
const observed=[];
const scheduled=new Promise((resolve,reject)=>{
const timer=setTimeout(()=>reject(Error('fixture schedule did not dispatch')),12000);
client.addEventListener('frame',e=>{const f=e.detail.run_event;if(!f)return;observed.push(f);if(f.scheduled&&f.schedule_id===a.id){clearTimeout(timer);resolve(f.run_id);}});
});
repo.subscribeRuns();
a=await repo.saveSchedule({...a,enabled:true,notify_mode:'off',title:'Timer fixture run'});
// Fixture-only clock advancement: this database was created above and is
// never selected from a live URL, environment override or user data path.
execFileSync('python3',['-c',"import sqlite3,sys,datetime; d=sqlite3.connect(sys.argv[1]); due=(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(seconds=2)).replace(microsecond=0).strftime('%Y-%m-%dT%H:%M:%SZ'); d.execute('UPDATE saved_schedules SET next_due=? WHERE id=?',(due,int(sys.argv[2]))); d.commit()",db,String(a.id)]);
const runId=await scheduled;ownedRuns.push(runId);
const fired=await repo.getRun(runId);assert.equal(fired.scheduled,true);assert.equal(fired.schedule_id,a.id);assert.equal(fired.input.prompt,a.input.prompt);
assert.ok(observed.filter(f=>f.run_id===runId).every(f=>f.scheduled&&f.schedule_id===a.id),'origin must exist on the very first frame');
await page.resize(390,844);await page.goto(`http://127.0.0.1:${webPort}/runs`);await page.waitForSelector(`[data-run-id="${runId}"]`);
await page.click('#runFilterBtn');await page.click('[data-run-schedule=scheduled]');
assert.equal(await page.evaluate("document.querySelectorAll('.run-row').length"),1);assert.equal(await page.evaluate("document.querySelector('.run-row').dataset.runId"),String(runId));
await page.screenshot(join(out,'scheduled-run-filter-mobile.png'));
await page.click('#runFilterBtn');await page.click('[data-run-schedule=unscheduled]');
assert.equal(await page.evaluate("document.querySelectorAll('.run-row').length"),1);assert.equal(await page.evaluate("document.querySelector('.run-row').dataset.runId"),String(manual.id));
await page.screenshot(join(out,'manual-run-on-scheduled-pipeline-mobile.png'));
const beforeDelete=await repo.listSchedules(pipeline.id);for(const entry of beforeDelete)await repo.deleteSchedule(entry.id,entry.revision);
const history=await repo.getRun(runId);assert.equal(history.scheduled,true);assert.equal(history.schedule_id,a.id);
const detail=await repo.getPipeline(pipeline.id,1);assert.equal(detail.source,source);assert.equal(detail.schedule_count,0);assert.equal(detail.scheduled,false);
assert.equal((await repo.getRun(manual.id)).scheduled,false);
const cliLog=await readFile(join(scratch,'fake-cli.log'),'utf8').catch(()=> '');assert.doesNotMatch(cliLog,/prompt|generate/);
console.log('PASS: actual web/API integration, two independent saved items, CAS draft safety, genuine timer-origin first frames vs manual runs, both filters, immutable workflow source and history after deletion. Human-only fixture; no provider calls.');
for(const id of ownedRuns)await repo.cancelRun(id).catch(()=>{});
} catch(error) {
if(page){await page.screenshot(join(out,'failure.png'));console.error(await page.evaluate('document.body.innerText'));}
console.error(serverLog.slice(-5000));throw error;
} finally {
client?.disconnect();await browser?.close();
for(const process of [proxy,server])if(process&&process.exitCode===null&&process.signalCode===null){const exited=new Promise(resolve=>process.once('exit',resolve));process.kill('SIGTERM');await exited;}
await rm(scratch,{recursive:true,force:true});
}
-60
View File
@@ -1,60 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { pipelineScheduleState, runScheduleState, pipelineScheduleLabel, scheduledRunLabel } from "../src/scheduleOrigin.js";
import { filterPipelines, EMPTY_PIPELINE_FILTERS, pipelineFilterCount } from "../src/pipelines.js";
import { filterRuns, defaultRunFilters, runFiltersActiveCount } from "../src/runs.js";
import { foldRunEvent, foldRunEventDetail, newRunSummaryFromFrame } from "../src/runEvents.js";
test("pipeline schedule filters use independent configurations, including paused entries", () => {
const all=[{id:1,name:"Research",scheduled:true,schedule_count:2,enabled_schedule_count:0},{id:2,name:"Review",scheduled:false,schedule_count:0},{id:3,name:"Legacy",shape:{settings:{schedules:[{every:"24h"}]}}}];
assert.deepEqual(filterPipelines(all,{...EMPTY_PIPELINE_FILTERS,scheduled:"scheduled"},new Map(),false).map(x=>x.id),[1]);
assert.deepEqual(filterPipelines(all,{...EMPTY_PIPELINE_FILTERS,scheduled:"unscheduled"}).map(x=>x.id),[2]);
assert.equal(pipelineScheduleState(all[2]),null);
assert.equal(pipelineScheduleLabel(all[0]),"2 schedules");
});
test("a manual run of a scheduled pipeline is not a scheduled run", () => {
const all=[{id:1,pipeline_id:7,scheduled:true,schedule_id:9,schedule_name:"Batteries"},{id:2,pipeline_id:7,scheduled:false},{id:3,pipeline_id:7}];
assert.deepEqual(filterRuns(all,{...defaultRunFilters(),scheduled:"scheduled"}).map(x=>x.id),[1]);
assert.deepEqual(filterRuns(all,{...defaultRunFilters(),scheduled:"unscheduled"}).map(x=>x.id),[2]);
assert.equal(runScheduleState(all[2]),null);
assert.equal(scheduledRunLabel(all[0]),"Scheduled · Batteries");
assert.equal(scheduledRunLabel(all[1]),"");
});
test("schedule filtering is an independent AND facet and clears with the defaults", () => {
assert.equal(pipelineFilterCount({...EMPTY_PIPELINE_FILTERS,name:"x",presence:"has_runs",lastRunStatuses:["failed"],scheduled:"scheduled"}),4);
assert.equal(runFiltersActiveCount({...defaultRunFilters(),statuses:new Set(["failed"]),pipelineId:7,timeRange:"today",scheduled:"scheduled"}),4);
assert.equal(pipelineFilterCount(EMPTY_PIPELINE_FILTERS),0);
assert.equal(runFiltersActiveCount(defaultRunFilters()),0);
const all=[{id:1,pipeline_id:7,scheduled:true,status:"failed"},{id:2,pipeline_id:7,scheduled:true,status:"succeeded"},{id:3,pipeline_id:8,scheduled:true,status:"failed"}];
const filters={...defaultRunFilters(),pipelineId:7,statuses:new Set(["failed"]),scheduled:"scheduled"};
assert.deepEqual(filterRuns(all,filters).map(x=>x.id),[1]);
});
const start={run_id:12,pipeline_id:7,name:"Research",version:3,status:"queued",scheduled:true,schedule_id:9,schedule_name:"Batteries"};
test("a scheduled run appears from its first live frame and retains origin on sparse updates", () => {
const row=newRunSummaryFromFrame(start);
assert.equal(row.scheduled,true);assert.equal(row.schedule_id,9);
const next=foldRunEvent([row],{run_id:12,status:"running",scheduled:false}).runs[0];
assert.equal(next.scheduled,true);assert.equal(next.schedule_id,9);assert.equal(next.schedule_name,"Batteries");
const detail=foldRunEventDetail({...row,steps:[]},{run_id:12,status:"running"});
assert.equal(detail.scheduled,true);assert.equal(detail.schedule_id,9);
});
test("lifecycle events cannot retarget an established schedule provenance", () => {
const row=newRunSummaryFromFrame(start);
const next=foldRunEvent([row],{run_id:12,status:"running",scheduled:true,schedule_id:100,schedule_name:"Another item"}).runs[0];
assert.equal(next.schedule_id,9);assert.equal(next.schedule_name,"Batteries");
const terminal=foldRunEvent([next],{run_id:12,status:"succeeded",scheduled:false}).runs[0];
assert.equal(runScheduleState(terminal),true);
});
test("older frames without origin remain unknown rather than guessed as manual", () => {
const {scheduled,schedule_id,schedule_name,...old}=start;
const row=newRunSummaryFromFrame(old);
assert.equal(runScheduleState(row),null);
const manual=newRunSummaryFromFrame({...old,scheduled:false});
assert.equal(runScheduleState(manual),false);
});
-35
View File
@@ -1,35 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { PipelinesRepository } from "../src/repository.js";
test("schedule repository uses independent run-config commands, never definition publication", async () => {
const requests=[];
const record={id:8,revision:3,pipeline_id:4,version:2,input:{prompt:"Research batteries"},workspace:"/srv/research",enabled:true,rule:{every:"24h"}};
const repo=new PipelinesRepository({call:async request=>{
requests.push(request);
if(request.type==='list_schedules')return{type:'schedules',schedules:[record]};
if(request.type==='save_schedule')return{type:'schedule',schedule:record};
return{type:'schedule_deleted',schedule_id:8};
}});
assert.deepEqual(await repo.listSchedules(4),[record]);
assert.equal(await repo.saveSchedule(record,{requestKey:'schedule:stable-editor-key'}),record);
await repo.deleteSchedule(8,3);
assert.deepEqual(requests,[
{type:'list_schedules',pipeline_id:4},
{type:'save_schedule',schedule:record,request_key:'schedule:stable-editor-key'},
{type:'delete_schedule',schedule_id:8,expected_revision:3},
]);
});
test("an explicit empty schedules reply is different from missing server support", async () => {
const empty=new PipelinesRepository({call:async()=>({type:'schedules'})});
assert.deepEqual(await empty.listSchedules(),[]);
const old=new PipelinesRepository({call:async()=>({type:'pong'})});
await assert.rejects(old.listSchedules(),/no schedules response/);
});
test("schedule deletion refuses missing identity or revision before contacting the server", async () => {
let calls=0;const repo=new PipelinesRepository({call:async()=>{calls++;}});
for(const [id,revision] of [[0,1],[8,0],[8,undefined],[8,1.5]]) await assert.rejects(repo.deleteSchedule(id,revision));
assert.equal(calls,0);
});
-125
View File
@@ -1,125 +0,0 @@
// Local static fixture only: real view + modal controller, no RuntimeSocket/server/providers.
// node web/test/schedules-browser.mjs /approved/temp/capture-directory
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { resolve, extname } from 'node:path';
import { createHash } from 'node:crypto';
import { launchChrome, eventually } from './browser.mjs';
const root = fileURLToPath(new URL('../', import.meta.url));
const out = process.argv[2];
if (!out) throw new Error('Pass an approved capture directory.');
await mkdir(out, { recursive: true });
const fixture = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="/design/tokens/tokens.css"><link rel="stylesheet" href="/base.css"><link rel="stylesheet" href="/schedules.css">
<style>body{overflow:auto}.app-root{max-width:960px;margin:auto;padding:24px}#pane-main{min-width:0}</style>
<div class="app-root"><h1>Research</h1><main id="pane-main" tabindex="-1"></main></div><div id="modalLayer"></div>
<script type="module">
import { createSchedulesView } from '/src/views/schedules.js';
import { createModalController } from '/src/modal.js';
window.records=[]; window.calls={list:0,save:0,delete:0}; window.refuse=false; window.unsupported=false;
const pipeline={id:42,version:7,name:'Research'};
const rt={state:{workspace:'/srv/research'},modal:createModalController(),repo:{
async listSchedules(){calls.list++; if(window.holdRead)await new Promise(resolve=>window.releaseRead=resolve); if(window.unsupported)throw Error('Unknown message: list_schedules (old server)'); return structuredClone(records);},
async saveSchedule(record){calls.save++; if(window.refuse)throw Error('409 revision conflict');
if(record.id){const i=records.findIndex(x=>x.id===record.id);records[i]=structuredClone({...record,revision:record.revision+1});}
else records.push(structuredClone({...record,id:records.length+1,revision:1}));return record;},
async deleteSchedule(id,revision){calls.delete++; records=records.filter(x=>x.id!==id);}
},renderContent(){document.querySelector('#pane-main').replaceChildren(view.renderPipelineSchedules(pipeline));rt.modal.reconcile();}};
const view=createSchedulesView(rt); window.view=view;window.rt=rt;
window.seed=async()=>{records=[{id:1,revision:1,name:'AI news',pipeline_id:42,version:7,enabled:true,input:{prompt:'Research AI news',count:2},workspace:'/srv/research',rule:{every:'24h',timezone:'UTC'},next_due:'2026-10-22T09:00:00Z'},
{id:2,revision:1,name:'Battery news',pipeline_id:42,version:3,enabled:true,input:{prompt:'Research battery advances'},workspace:'/srv/batteries',rule:{times:['09:00'],days:['mon','fri'],timezone:'UTC'},next_due:'2026-10-23T09:00:00Z'}];await view.loadPipelineSchedules(42,{force:true});};
rt.renderContent();window.ready=true;
</script>`;
const server = createServer(async (req, res) => {
try {
if (req.url === '/') { res.setHeader('Content-Type', 'text/html'); res.end(fixture); return; }
const path = resolve(root, `.${new URL(req.url, 'http://fixture').pathname}`);
if (!path.startsWith(root)) { res.writeHead(403); res.end(); return; }
res.setHeader('Content-Type', ({ '.js': 'text/javascript', '.css': 'text/css' })[extname(path)] ?? 'text/plain');
res.end(await readFile(path));
} catch { res.writeHead(404); res.end(); }
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
let browser;
const manifest = [];
try {
browser = await launchChrome({ width: 1100, height: 900 });
const page = await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForText('No schedules yet');
const capture = async name => {
const path = resolve(out, `${name}.png`); await page.screenshot(path);
manifest.push({ path, sha256: createHash('sha256').update(await readFile(path)).digest('hex') });
};
const noOverflow = async () => assert.equal(await page.evaluate('document.documentElement.scrollWidth <= innerWidth'), true);
await capture('schedule-empty-1100');
await page.evaluate('seed()'); await page.waitForText('Battery news');
assert.equal(await page.evaluate('document.querySelectorAll(".schedule-card").length'), 2);
await capture('schedule-two-1100');
await page.clickText('[data-schedule-id="2"] button', 'Edit');
await capture('schedule-clock-editor-1100'); await noOverflow();
assert.equal(await page.evaluate('document.querySelector("[name=mode]").value'), 'clock');
await page.clickText('.schedule-panel button', 'Cancel');
await page.clickText('[data-schedule-id="1"] button', 'Edit');
await page.fill('[name="prompt"]', 'AI draft remains here');
assert.equal(await page.evaluate('document.activeElement.name'), 'prompt');
await page.evaluate('rt.renderContent()');
assert.equal(await page.evaluate('document.querySelector("[name=prompt]").value'), 'AI draft remains here');
assert.equal(await page.evaluate('document.activeElement.name'), 'prompt');
await page.evaluate('window.refuse=true'); await page.clickText('.schedule-panel button', 'Save schedule');
await page.waitForText('409 revision conflict');
assert.equal(await page.evaluate('document.querySelector("[name=prompt]").value'), 'AI draft remains here');
await capture('schedule-conflict-1100');
await page.evaluate('window.refuse=false'); await page.clickText('.schedule-panel button', 'Save schedule');
await eventually(() => page.evaluate('!rt.modal.isOpen("schedule-editor")'));
assert.equal(await page.evaluate('records[1].input.prompt'), 'Research battery advances');
assert.equal(await page.evaluate('records[0].input.count'), 2);
await page.clickText('[data-schedule-id="1"] button', 'Pause');
await eventually(() => page.evaluate('!records[0].enabled'));
await capture('schedule-paused-1100');
await page.clickText('[data-schedule-id="1"] button', 'Delete');
assert.equal(await page.evaluate('calls.delete'), 0);
await capture('schedule-delete-confirm-1100');
await page.clickText('.schedule-confirm button', 'Keep schedule');
assert.equal(await page.evaluate('document.activeElement.textContent'), 'Delete');
await page.clickText('[data-schedule-id="1"] button', 'Delete');
await page.clickText('.schedule-confirm button', 'Delete schedule');
await eventually(() => page.evaluate('records.length===1 && !rt.modal.isOpen("schedule-delete")'));
assert.equal(await page.evaluate('records[0].id'), 2);
await page.evaluate('seed()');
await page.resize(390, 844);
await capture('schedule-two-390'); await noOverflow();
await page.click('.schedule-add');
await page.fill('[name="name"]', 'Third independent topic'); await page.fill('[name="prompt"]', 'Mobile draft');
await page.click('.schedule-advanced summary');
await page.fill('[name="otherInput"]', 'null');
await page.clickText('.schedule-panel button', 'Save schedule');
await page.waitForText('Other input must be a JSON object');
assert.equal(await page.evaluate('document.querySelector("[name=prompt]").value'), 'Mobile draft');
await capture('schedule-invalid-json-390');
await page.fill('[name="otherInput"]', '{"count":3}');
await page.clickText('.schedule-panel button', 'Save schedule');
await eventually(() => page.evaluate('records.length===3 && !rt.modal.isOpen("schedule-editor")'));
await page.clickText('[data-schedule-id="3"] button', 'Edit');
await capture('schedule-editor-390'); await noOverflow();
await page.click('.schedule-advanced summary');
await page.fill('[name="model"]', 'provider/model');
assert.equal(await page.evaluate('document.activeElement.name'), 'model');
await capture('schedule-advanced-390'); await noOverflow();
await page.clickText('.schedule-panel button', 'Cancel');
assert.equal(await page.evaluate('document.activeElement.textContent'), 'Edit');
await page.evaluate('holdRead=true;view.clearScheduleCache();rt.renderContent()');
await page.waitForText('Loading schedules'); await capture('schedule-loading-390');
await page.evaluate('holdRead=false;releaseRead()'); await page.waitForText('Third independent topic');
await page.evaluate('unsupported=true;view.clearScheduleCache();rt.renderContent()');
await page.waitForText('old server'); await capture('schedule-old-server-390');
await page.evaluate('unsupported=false'); await page.clickText('.schedule-section button', 'Retry');
await page.waitForText('Third independent topic');
await page.close();
await writeFile(resolve(out, 'manifest.json'), JSON.stringify(manifest, null, 2));
console.log(JSON.stringify({ checks: 'passed', captures: manifest }, null, 2));
} finally {
await browser?.close(); await new Promise(resolve => server.close(resolve));
}
-115
View File
@@ -1,115 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { scheduleDraft, serializeSchedule, scheduleDueLabel, scheduleRuleLabel } from '../src/schedules.js';
import { createSchedulesView } from '../src/views/schedules.js';
const pipeline = { id: 42, version: 7 };
const make = () => ({ ...scheduleDraft({ pipeline, workspace: '/srv/research', timezone: 'UTC' }), name: 'AI news', prompt: 'Research AI news' });
const serialize = draft => serializeSchedule(draft, { pipelineId: 42 });
test('new schedules independently snapshot prompts and positive pinned versions', () => {
const a = serialize(make());
const b = serialize({ ...make(), prompt: 'Research batteries', every: '48h' });
assert.equal(a.id, 0); assert.equal(a.version, 7); assert.equal(a.pipeline_id, 42);
assert.notEqual(a.input.prompt, b.input.prompt); assert.equal(a.rule.every, '24h');
assert.equal(b.rule.every, '48h');
for (const version of ['0', '-1', '1.2', '7junk', 'Infinity']) assert.throws(() => serialize({ ...make(), version }), /pinned version/);
});
test('existing record roundtrip preserves CAS, unknown fields and typed extra inputs', () => {
const original = { ...serialize(make()), id: 9, revision: 13, server_extra: { keep: true },
input: { prompt: 'Topic', count: 4, flag: false, nested: { list: [null, 2] } },
rule: { times: ['09:00', '17:30'], days: ['mon', 'fri'], timezone: '', future: 'keep' },
model: 'provider/model', stage_models: { research: 'provider/other' }, title: 'Saved title', output_format: 'json', notify_mode: 'off' };
const draft = scheduleDraft({ pipeline, schedule: original });
const result = serializeSchedule(draft, { pipelineId: 42, schedule: original });
assert.equal(result.id, 9); assert.equal(result.revision, 13);
assert.deepEqual(result.input, original.input); assert.deepEqual(result.server_extra, original.server_extra);
assert.equal(result.rule.future, 'keep'); assert.equal(draft.timezone, '');
assert.deepEqual(result.stage_models, original.stage_models); assert.equal(result.title, 'Saved title');
draft.prompt = 'Changed';
assert.equal(original.input.prompt, 'Topic');
});
test('run seeding copies only RunSpec and never origin metadata or a locked title', () => {
const run = { version: 3, workspace: '/server/run', input: { prompt: 'Past run', count: 2 },
model: 'p/m', stage_models: { a: 'p/x' }, notify_mode: 'on', title: 'User title', title_source:'explicit', output_format: 'markdown',
id: 87, origin: { kind: 'schedule' }, request_key: 'no-copy' };
const draft = scheduleDraft({ pipeline, run, workspace: '/different', timezone: 'UTC' });
const saved = serialize({ ...draft, name: 'From run', prompt: 'Editable title and prompt', otherInput: '{"count":2,"prompt":"ignored","array":[1,false]}' });
assert.equal(saved.version, 3); assert.equal(saved.workspace, '/server/run');
assert.equal(saved.input.prompt, 'Editable title and prompt'); assert.deepEqual(saved.input.array, [1, false]);
assert.equal(saved.title, 'User title'); assert.equal(saved.model, 'p/m');
assert.equal(saved.origin, undefined); assert.equal(saved.request_key, undefined); assert.equal(saved.id, 0);
});
test('rule modes mutually exclude interval and clock, validate days, timezone and times', () => {
const old = { ...serialize(make()), id: 3, rule: { every: '24h', days: ['mon'] } };
const draft = { ...scheduleDraft({ pipeline, schedule: old }), mode: 'clock', times: '09:00, 23:59' };
const clock = serializeSchedule(draft, { schedule: old });
assert.equal(clock.rule.every, undefined); assert.deepEqual(clock.rule.times, ['09:00', '23:59']);
const interval = serializeSchedule({ ...draft, mode: 'interval', every: '1.5m' }, { schedule: clock });
assert.equal(interval.rule.times, undefined); assert.equal(interval.rule.every, '1.5m');
assert.equal(serialize({ ...make(), every: '.5h' }).rule.every, '.5h');
for (const times of ['', '24:00', '9:00', '09:60', '09:00,09:00']) assert.throws(() => serialize({ ...make(), mode: 'clock', times }), /24-hour/);
for (const every of ['59s', 'NaN', '-1h', '1.1x', 'Infinityh']) assert.throws(() => serialize({ ...make(), every }), /at least 1m/);
for (const days of [['Monday'], ['mon', 'mon']]) assert.throws(() => serialize({ ...make(), days }), /weekdays/);
assert.throws(() => serialize({ ...make(), timezone: 'Nowhere/Invalid' }), /IANA/);
});
test('invalid JSON, model and workspace reject without mutating the draft', () => {
for (const otherInput of ['null', '[]', '{bad']) assert.throws(() => serialize({ ...make(), otherInput }), /JSON/);
for (const stageModels of ['null', '[]', '{"a":2}', '{"a":"no-provider"}']) assert.throws(() => serialize({ ...make(), stageModels }), /JSON|provider\/model/);
for (const model of ['plain', '/model', 'p/', 'p/m x']) assert.throws(() => serialize({ ...make(), model }), /provider\/model/);
for (const workspace of ['', 'relative', '~/repo', '/srv\npath']) assert.throws(() => serialize({ ...make(), workspace }), /absolute workspace/);
const draft = { ...make(), otherInput: 'null' }; const copy = structuredClone(draft);
assert.throws(() => serialize(draft)); assert.deepEqual(draft, copy);
});
test('display is honest for invalid or absent next_due', () => {
assert.equal(scheduleDueLabel('invalid'), 'Next time unavailable');
assert.equal(scheduleDueLabel(null), 'Not scheduled');
assert.match(scheduleRuleLabel({ every: '24h' }), /Server timezone/);
assert.match(scheduleRuleLabel({ every: '24h', timezone:'Local' }), /Server timezone/);
assert.match(scheduleDueLabel('2026-10-21T09:00:00Z','Asia/Tokyo'), /Asia\/Tokyo/);
assert.match(scheduleDueLabel('2026-10-21T09:00:00Z'), /your local time/);
});
test('saved run-level write restrictions survive scheduling without widening edits', () => {
const run={version:3,input:{prompt:'Scoped change'},workspace:'/srv/research',write_paths:['src/file.go'],allow_tools:true,title:'Automatic title',title_source:'model'};
const draft=scheduleDraft({pipeline,run});
const result=serialize({...draft,name:'Scoped run'});
assert.deepEqual(result.write_paths,['src/file.go']);
assert.equal(result.allow_tools,true);
assert.equal(result.title,undefined,'generated titles must not become locked run titles');
for(const writePaths of ['null','{}','[1]','["../outside"]','["/absolute"]','["src/*.go"]']) {
assert.throws(()=>serialize({...make(),writePaths}),/Write paths/);
}
assert.equal(serialize({...make(),timezone:'Local'}).rule.timezone,'Local');
});
test('a prompt-only edit preserves the existing weekday order and timer rule', () => {
const original={...serialize(make()),id:4,revision:2,rule:{every:'24h',days:['fri','mon'],timezone:'UTC'}};
const draft={...scheduleDraft({pipeline,schedule:original}),prompt:'New topic',days:['mon','fri']};
const saved=serializeSchedule(draft,{schedule:original});
assert.deepEqual(saved.rule,original.rule);
});
test('view cache shares pending reads, refreshes explicitly and recovers after refusal', async () => {
let calls = 0; let resolveRead; let fail = false; let renders = 0;
const view = createSchedulesView({ repo: { listSchedules() {
calls++; if (fail) throw new Error('unknown command list_schedules');
return new Promise(resolve => { resolveRead = resolve; });
} }, renderContent() { renders++; } });
const a = view.loadPipelineSchedules(42);
const b = view.loadPipelineSchedules(42, { force: true });
assert.equal(a, b); await Promise.resolve(); assert.equal(calls, 1);
resolveRead([{ id: 1 }]); assert.deepEqual(await a, [{ id: 1 }]);
await view.loadPipelineSchedules(42); assert.equal(calls, 1);
fail = true; assert.equal(await view.loadPipelineSchedules(42, { force: true }), null);
fail = false; const retry = view.loadPipelineSchedules(42, { force: true });
await Promise.resolve(); resolveRead([]); assert.deepEqual(await retry, []);
view.clearScheduleCache(); const newRead = view.loadPipelineSchedules(42);
await Promise.resolve(); resolveRead([]); await newRead;
assert.equal(calls, 4); assert.equal(renders, 4);
});
-57
View File
@@ -1,57 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseSearchQuery, searchQuerySendable, searchPanelBody, SEARCH_KINDS } from "../src/search.js";
test("both type aliases and kinds are case insensitive", () => {
for (const { value } of SEARCH_KINDS.filter((kind) => kind.value)) {
for (const prefix of ["t", "type", "T", "TyPe"]) {
assert.deepEqual(parseSearchQuery(`${prefix}:${value.toUpperCase()} plan`), {
query: " plan", kind: value, hasType: true,
});
}
}
});
test("normal, quoted and unsupported text is preserved byte for byte", () => {
for (const query of [
' ordinary text\twith\nspacing ',
'"t:pipeline" "hello world"', "'type:artifact'",
'"escaped \\" t:run"', '"unclosed t:run',
"t:prompt type:unknown t: t:PIPELINES", "not:t:run t:run,",
"prefix\"t:run\"", "\\t:run",
]) {
assert.deepEqual(parseSearchQuery(query, "field"), { query, kind: "field", hasType: false });
}
assert.equal(parseSearchQuery('t:artifact "t:pipeline" report').query, ' "t:pipeline" report');
});
test("last supported token wins over selector; unknown tokens do not override it", () => {
assert.deepEqual(parseSearchQuery("t:run plan TYPE:artifact t:unknown", "pipeline"), {
query: " plan t:unknown", kind: "artifact", hasType: true,
});
assert.equal(parseSearchQuery("plan", "step").kind, "step");
});
test("type-only query is distinguishable from literal text and blank input", () => {
assert.deepEqual(parseSearchQuery("t:pipeline"), { query: "", kind: "pipeline", hasType: true });
assert.deepEqual(parseSearchQuery(""), { query: "", kind: "", hasType: false });
});
test("blank text is sendable only with a supported nonempty kind", () => {
for (const { value } of SEARCH_KINDS) {
assert.equal(searchQuerySendable(" \n\t ", value), value !== "");
}
assert.equal(searchQuerySendable("", "unknown"), false);
assert.equal(searchQuerySendable("plan"), true);
});
test("kind-only responses distinguish loading, honest empty state and cleared filters", () => {
assert.equal(searchPanelBody({ loading: true, query: "" }, [], "pipeline").kind, "searching");
assert.deepEqual(searchPanelBody({ loaded: true, query: "" }, [], "pipeline"), {
kind: "empty", message: "No pipelines yet.",
});
assert.equal(searchPanelBody({ loaded: false, query: "" }, [], "pipeline").kind, "idle");
assert.equal(searchPanelBody({ loaded: true, query: "" }, [], "").kind, "idle");
assert.equal(searchPanelBody({ loaded: true, query: "", truncated: true }, [], "field").message,
"No fields found within the server's scan limit.");
});
-519
View File
@@ -1,519 +0,0 @@
// Pure omni-search tests: the per-kind row text, the in-hand narrowing and
// ordering, the routing target/tab resolution, the debounce/stale-token sequencer
// and the failure copy. Everything here is DOM-free and needs no server, mirroring
// android/.../ui/OmniSearchResultsTest.kt and OmniSearchTest.kt.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
DEFAULT_SEARCH_KIND,
DEFAULT_SEARCH_SORT,
SEARCH_KINDS,
SEARCH_SORTS,
SEARCH_UNSUPPORTED,
SearchSequencer,
filterSearchResults,
resolveRunTarget,
searchControlsSummary,
searchFailureText,
searchFieldTab,
searchKindLabel,
searchPanelBody,
searchPanelEmptyMessage,
searchPanelProgress,
searchQuerySendable,
searchResultKindLabel,
searchRow,
searchTarget,
snippetSpans,
sortSearchResults,
} from "../src/search.js";
const UTC = { timeZone: "UTC" };
// ---------------------------------------------------------------------------
// Fixtures — the same shapes the Android test uses
// ---------------------------------------------------------------------------
function pipelineHit(overrides = {}) {
return {
kind: "pipeline",
target: "pipeline:7",
pipeline: { id: 7, name: "release", version: 3, stages: 4, ...overrides },
};
}
function versionHit(overrides = {}) {
return {
kind: "version",
target: "pipeline:9:v2",
version: {
pipeline_id: 9,
version: 2,
content_hash: "abc",
created_at: "2026-01-01T00:00:00Z",
...overrides,
},
};
}
function runHit(overrides = {}) {
return {
kind: "run",
target: "run:11",
run: {
id: 11,
pipeline_name: "release",
status: "succeeded",
created_at: "2026-01-01T00:00:00Z",
...overrides,
},
};
}
function stepHit(overrides = {}) {
return {
kind: "step",
target: "run:11:4",
step: { run_id: 11, sequence: 4, stage: "builder", visit: 2, outcome: "success", ...overrides },
};
}
function fieldHit(overrides = {}, matchedField = "output") {
return {
kind: "field",
target: "run:11:4:output",
matched_field: matchedField,
field: {
run_id: 11,
sequence: 4,
field: "output",
snippet: "the release is ready",
...overrides,
},
};
}
function artifactHit(overrides = {}) {
return {
kind: "artifact",
target: "/artifacts/11/4/notes.md",
artifact: {
run_id: 11,
sequence: 4,
name: "notes.md",
content_type: "text/markdown",
size_bytes: 2048,
url: "/artifacts/11/4/notes.md",
...overrides,
},
};
}
// ---------------------------------------------------------------------------
// Kind/sort vocabulary
// ---------------------------------------------------------------------------
test("the kind options are exactly the server vocabulary, All kinds first", () => {
assert.deepEqual(
SEARCH_KINDS.map((option) => [option.value, option.label]),
[
["", "All kinds"],
["pipeline", "Pipelines"],
["run", "Runs"],
["step", "Steps"],
["field", "Fields"],
["artifact", "Artifacts"],
["version", "Versions"],
],
);
assert.equal(DEFAULT_SEARCH_KIND, "");
assert.deepEqual(
SEARCH_SORTS.map((option) => [option.value, option.label]),
[
["relevance", "Relevance"],
["newest", "Newest first"],
["name", "Name"],
],
);
assert.equal(DEFAULT_SEARCH_SORT, "relevance");
// A stale/unknown value falls back rather than inventing an option.
assert.equal(searchKindLabel("prompts"), "All kinds");
assert.equal(searchKindLabel("run"), "Runs");
});
// ---------------------------------------------------------------------------
// Row text
// ---------------------------------------------------------------------------
test("pipeline rows carry the name (or the id fallback) and the version/stage line", () => {
assert.deepEqual(searchRow(pipelineHit(), "release", UTC), {
title: "release",
secondary: "pipeline 7 · v3 · 4 stages",
snippet: null,
});
const blank = searchRow(pipelineHit({ name: " " }), "release", UTC);
assert.equal(blank.title, "pipeline 7");
// The stage count keeps the app's singular form.
assert.equal(searchRow(pipelineHit({ stages: 1 }), "", UTC).secondary, "pipeline 7 · v3 · 1 stage");
});
test("version rows name the pipeline/version and omit blank content parts", () => {
assert.deepEqual(searchRow(versionHit(), "release", UTC), {
title: "pipeline 9 · v2",
secondary: "content abc · 1 Jan 00:00",
snippet: null,
});
const blankHash = searchRow(versionHit({ content_hash: " " }), "release", UTC);
assert.equal(blankHash.secondary, "1 Jan 00:00");
});
test("run rows join the non-blank status, workspace and timestamp", () => {
assert.deepEqual(searchRow(runHit(), "release", UTC), {
title: "run #11 · release",
secondary: "succeeded · 1 Jan 00:00",
snippet: null,
});
const withWorkspace = searchRow(runHit({ workspace: "/tmp/ws" }), "", UTC);
assert.equal(withWorkspace.secondary, "succeeded · /tmp/ws · 1 Jan 00:00");
const unnamed = searchRow(runHit({ pipeline_name: "" }), "", UTC);
assert.equal(unnamed.title, "run #11");
});
test("step rows carry outcome, route and the first non-blank diagnostic line", () => {
const withTarget = searchRow(stepHit({ target: "#success" }), "", UTC);
assert.deepEqual(withTarget, {
title: "run #11 · builder visit 2",
secondary: "success · → #success",
snippet: null,
});
const withDiagnostic = searchRow(
stepHit({ diagnostic: "\n the first line\nsecond line" }),
"",
UTC,
);
assert.equal(withDiagnostic.secondary, "success · the first line");
// Every part blank: the sequence is the honest fallback.
const allBlank = searchRow(stepHit({ outcome: "", target: "", diagnostic: "" }), "", UTC);
assert.equal(allBlank.secondary, "step 4");
// A blank stage falls back to the word "step".
assert.equal(searchRow(stepHit({ stage: "" }), "", UTC).title, "run #11 · step visit 2");
});
test("field rows carry the server snippet with the matched query span", () => {
const row = searchRow(fieldHit(), "release", UTC);
assert.equal(row.title, "run #11 · step 4 · output");
assert.equal(row.secondary, "the release is ready");
assert.deepEqual(row.snippet, [
{ text: "the ", matched: false },
{ text: "release", matched: true },
{ text: " is ready", matched: false },
]);
// No occurrence: one unmatched run, never dropped text.
assert.deepEqual(searchRow(fieldHit(), "absent", UTC).snippet, [
{ text: "the release is ready", matched: false },
]);
// A blank field falls back to the word "field".
assert.equal(searchRow(fieldHit({ field: " " }), "release", UTC).title, "run #11 · step 4 · field");
});
test("artifact rows join name, run, step, content type and human size", () => {
assert.deepEqual(searchRow(artifactHit(), "notes", UTC), {
title: "notes.md",
secondary: "run #11 · step 4 · text/markdown · 2.0 KiB",
snippet: null,
});
assert.equal(searchRow(artifactHit({ name: "", content_type: "" }), "", UTC).title, "artifact");
});
test("an unknown row is read-only and never dropped", () => {
const named = searchRow({ kind: "future_kind", target: "widget:7" }, "x", UTC);
assert.deepEqual(named, {
title: "widget:7",
secondary: 'kind "future_kind" · read-only',
snippet: null,
});
const anonymous = searchRow({ kind: "", target: "" }, "x", UTC);
assert.deepEqual(anonymous, { title: "Unrecognised result", secondary: "read-only", snippet: null });
});
test("snippetSpans splits only the first occurrence, case-insensitively", () => {
assert.deepEqual(snippetSpans("the Release notes mention it", "release"), [
{ text: "the ", matched: false },
{ text: "Release", matched: true },
{ text: " notes mention it", matched: false },
]);
// The FIRST occurrence is the emphasised one; a later one is left in the tail.
assert.deepEqual(snippetSpans("aXbXc", "x"), [
{ text: "a", matched: false },
{ text: "X", matched: true },
{ text: "bXc", matched: false },
]);
// A match at the very start/end needs no empty leading/trailing run.
assert.deepEqual(snippetSpans("release", "release"), [{ text: "release", matched: true }]);
assert.deepEqual(snippetSpans("nothing here", "release"), [{ text: "nothing here", matched: false }]);
assert.deepEqual(snippetSpans("nothing here", " "), [{ text: "nothing here", matched: false }]);
assert.deepEqual(snippetSpans("", "release"), []);
});
test("searchResultKindLabel names the kind in words, artifact by its content type", () => {
assert.equal(searchResultKindLabel(pipelineHit()), "Pipeline");
assert.equal(searchResultKindLabel(versionHit()), "Pipeline version");
assert.equal(searchResultKindLabel(runHit()), "Run");
assert.equal(searchResultKindLabel(stepHit()), "Step");
assert.equal(searchResultKindLabel(fieldHit()), "Field");
assert.equal(searchResultKindLabel(artifactHit({ content_type: "text/markdown" })), "Document artifact");
assert.equal(
searchResultKindLabel(artifactHit({ name: "shot.png", content_type: "image/png" })),
"Image artifact",
);
assert.equal(searchResultKindLabel({ kind: "future_kind", target: "x" }), "Unrecognised result");
});
// ---------------------------------------------------------------------------
// Kind filtering + in-hand sorting
// ---------------------------------------------------------------------------
test("the kind filter narrows the list, and All kinds keeps it whole", () => {
const mixed = [pipelineHit(), runHit(), stepHit(), fieldHit(), artifactHit(), versionHit()];
assert.deepEqual(filterSearchResults(mixed, ""), mixed);
assert.deepEqual(filterSearchResults(mixed, "run"), [mixed[1]]);
assert.deepEqual(filterSearchResults(mixed, "version"), [mixed[5]]);
assert.deepEqual(filterSearchResults(mixed, "nothing"), []);
});
function hitWithRecency(kind, recency) {
return { kind, target: `${kind}:1`, recency };
}
test("Relevance keeps the server's ranking untouched", () => {
const ordered = [
hitWithRecency("run", "2026-01-01T00:00:00Z"),
hitWithRecency("pipeline", "2026-03-01T00:00:00Z"),
];
assert.deepEqual(sortSearchResults(ordered, "relevance"), ordered);
assert.deepEqual(sortSearchResults(ordered, "stale-sort-value"), ordered);
});
test("Newest first orders by parsed recency, descending", () => {
const older = hitWithRecency("run", "2026-01-01T00:00:00Z");
const newer = hitWithRecency("pipeline", "2026-03-01T00:00:00Z");
assert.deepEqual(sortSearchResults([older, newer], "newest"), [newer, older]);
});
test("Newest first keeps ties stable, and puts a missing/invalid recency last", () => {
const first = hitWithRecency("run", "2026-01-01T00:00:00Z");
const second = hitWithRecency("pipeline", "2026-01-01T00:00:00Z");
assert.deepEqual(sortSearchResults([first, second], "newest"), [first, second]);
const dated = hitWithRecency("run", "2026-01-01T00:00:00Z");
const undated = hitWithRecency("run", null);
const invalid = hitWithRecency("run", "not-a-date");
assert.deepEqual(sortSearchResults([undated, invalid, dated], "newest"), [dated, undated, invalid]);
});
test("Name orders by the displayed title, case-insensitively, with ties stable", () => {
const alpha1 = pipelineHit({ id: 1, name: "alpha" });
const beta = pipelineHit({ id: 2, name: "Beta" });
const alpha2 = pipelineHit({ id: 3, name: "ALPHA" });
assert.deepEqual(sortSearchResults([beta, alpha1, alpha2], "name"), [alpha1, alpha2, beta]);
});
// ---------------------------------------------------------------------------
// Summary + empty state
// ---------------------------------------------------------------------------
test("the controls summary is exactly {Kind} · {Sort}, with no (in hand) suffix", () => {
assert.equal(searchControlsSummary("", "relevance"), "All kinds · Relevance");
assert.equal(searchControlsSummary("run", "newest"), "Runs · Newest first");
assert.equal(searchControlsSummary("field", "name"), "Fields · Name");
assert.equal(searchControlsSummary("bogus", "bogus"), "All kinds · Relevance");
});
test("the empty state names the query and the active filter, or nothing", () => {
const empty = { query: "release", loading: false, error: "" };
assert.equal(searchPanelEmptyMessage(empty, [], ""), 'No matches for "release".');
assert.equal(searchPanelEmptyMessage(empty, [], "run"), 'No runs match "release".');
assert.equal(searchPanelEmptyMessage(empty, [], "version"), 'No versions match "release".');
// Rows shown, still loading, a blank query or an error: no message at all.
assert.equal(searchPanelEmptyMessage(empty, [runHit()], ""), null);
assert.equal(searchPanelEmptyMessage({ ...empty, loading: true }, [], ""), null);
assert.equal(searchPanelEmptyMessage({ query: " " }, [], ""), null);
assert.equal(searchPanelEmptyMessage({ ...empty, error: "boom" }, [], ""), null);
});
test("a blank or whitespace query is never sent to the server", () => {
assert.equal(searchQuerySendable(""), false);
assert.equal(searchQuerySendable(" "), false);
assert.equal(searchQuerySendable(undefined), false);
assert.equal(searchQuerySendable("plan"), true);
assert.equal(searchQuerySendable(" plan "), true);
});
test("the refresh bar shows only when results are retained while a newer query loads", () => {
assert.equal(searchPanelProgress({ loading: true, results: [runHit()] }), true);
assert.equal(searchPanelProgress({ loading: true, results: [] }), false);
assert.equal(searchPanelProgress({ loading: false, results: [runHit()] }), false);
assert.equal(searchPanelProgress({}), false);
});
test("the panel body reports an error first, then rows, Searching…, the empty line or nothing", () => {
const loading = { query: "plan", loading: true, results: [], error: "" };
// The first load, nothing yet: the searching row.
assert.deepEqual(searchPanelBody(loading, [], ""), { kind: "searching", message: "" });
// A retained result set is still shown while a refresh is in flight.
const refresh = { query: "plan", loading: true, results: [runHit()], error: "" };
assert.deepEqual(searchPanelBody(refresh, [runHit()], ""), { kind: "results", message: "" });
// An error takes precedence over results.
assert.deepEqual(searchPanelBody({ ...refresh, error: "boom" }, [runHit()], ""), {
kind: "error",
message: "boom",
});
// A landed, empty reply: the empty-state sentence, naming the kind when set.
const landed = { query: "plan", loading: false, results: [], error: "" };
assert.deepEqual(searchPanelBody(landed, [], ""), { kind: "empty", message: 'No matches for "plan".' });
assert.deepEqual(searchPanelBody(landed, [], "run"), {
kind: "empty",
message: 'No runs match "plan".',
});
// A blank query, or a filter that emptied a list while a refresh is in flight:
// nothing at all.
assert.deepEqual(searchPanelBody({ query: " ", loading: false }, [], ""), { kind: "idle", message: "" });
assert.deepEqual(searchPanelBody(refresh, [], "run"), { kind: "idle", message: "" });
});
// ---------------------------------------------------------------------------
// Routing target + tab resolution
// ---------------------------------------------------------------------------
test("pipeline and version hits open the pipeline detail (version 0 = latest)", () => {
assert.deepEqual(searchTarget(pipelineHit()), { kind: "pipeline", pipelineId: 7, version: 3 });
assert.deepEqual(searchTarget(pipelineHit({ version: 0 })), {
kind: "pipeline",
pipelineId: 7,
version: 0,
});
assert.deepEqual(searchTarget(versionHit()), { kind: "pipeline", pipelineId: 9, version: 2 });
});
test("run, step, field and artifact hits open runs", () => {
assert.deepEqual(searchTarget(runHit()), { kind: "run", runId: 11, sequence: 0, matchedField: "" });
assert.deepEqual(searchTarget(stepHit()), { kind: "run", runId: 11, sequence: 4, matchedField: "" });
assert.deepEqual(searchTarget(fieldHit({}, "output")), {
kind: "run",
runId: 11,
sequence: 4,
matchedField: "output",
});
assert.deepEqual(searchTarget(artifactHit()), { kind: "run", runId: 11, sequence: 4, matchedField: "" });
});
test("an unknown result has no target and is never navigated", () => {
assert.equal(searchTarget({ kind: "future_kind", target: "widget:7" }), null);
});
test("the matched field resolves the run-detail tab, everything else Summary", () => {
assert.equal(searchFieldTab("input"), "input");
assert.equal(searchFieldTab("output"), "output");
assert.equal(searchFieldTab("transcript"), "summary");
assert.equal(searchFieldTab("evidence"), "summary");
assert.equal(searchFieldTab("other"), "summary");
assert.equal(searchFieldTab(""), "summary");
assert.equal(searchFieldTab(undefined), "summary");
});
const STEPS = [
{ sequence: 1, stage: "planner" },
{ sequence: 2, stage: "builder" },
{ sequence: 3, stage: "builder" },
];
test("a text-match target resolves to the run-detail tab holding it", () => {
assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, matchedField: "input" }, 11, STEPS), {
tab: "input",
});
assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, matchedField: "output" }, 11, STEPS), {
tab: "output",
});
assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, matchedField: "transcript" }, 11, STEPS), {
tab: "summary",
});
});
test("a step/artifact target resolves the visit index within its stage, not the visit number", () => {
// "builder" recorded two visits; sequence 3 is its second, index 1.
assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 3 }, 11, STEPS), {
stageKey: "builder",
visitIndex: 1,
});
assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 2 }, 11, STEPS), {
stageKey: "builder",
visitIndex: 0,
});
assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 1 }, 11, STEPS), {
stageKey: "planner",
visitIndex: 0,
});
});
test("a bare run target or a visit that cannot be located falls back to the run detail", () => {
assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 0 }, 11, STEPS), {});
assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 99 }, 11, STEPS), {});
assert.deepEqual(resolveRunTarget(null, 11, STEPS), {});
assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 1 }, 11, []), {});
});
// ---------------------------------------------------------------------------
// Debounce + stale-reply sequencing
// ---------------------------------------------------------------------------
test("a burst of keystrokes collapses to one request for the last query", () => {
const sequencer = new SearchSequencer();
const first = sequencer.edit("r");
const second = sequencer.edit("re");
const third = sequencer.edit("rel");
assert.equal(sequencer.begin(first), null);
assert.equal(sequencer.begin(second), null);
assert.deepEqual(sequencer.begin(third), { token: third.token, query: "rel" });
});
test("only the newest recorded edit is accepted, so a stale reply can never land", () => {
const sequencer = new SearchSequencer();
const sentOld = sequencer.begin(sequencer.edit("old"));
// A keystroke while the old reply is in flight invalidates it immediately.
const next = sequencer.edit("new");
assert.equal(sequencer.accepts(sentOld.token), false);
const sentNew = sequencer.begin(next);
assert.equal(sequencer.accepts(sentNew.token), true);
// A token that was never recorded is not accepted either.
assert.equal(sequencer.accepts(sentNew.token + 100), false);
// Closing records an empty edit, which invalidates the in-flight reply too.
sequencer.edit("");
assert.equal(sequencer.accepts(sentNew.token), false);
});
test("Enter sends the current query at once, skipping the debounce", () => {
const sequencer = new SearchSequencer();
sequencer.edit("release");
const sent = sequencer.begin(sequencer.edit("release"));
assert.deepEqual(sent, { token: sent.token, query: "release" });
assert.equal(sequencer.accepts(sent.token), true);
});
// ---------------------------------------------------------------------------
// Failure copy
// ---------------------------------------------------------------------------
test("a missing payload or an unknown command reports the unsupported sentence", () => {
assert.equal(searchFailureText(null), SEARCH_UNSUPPORTED);
assert.equal(searchFailureText(undefined), SEARCH_UNSUPPORTED);
assert.equal(searchFailureText(new Error("")), SEARCH_UNSUPPORTED);
assert.equal(searchFailureText(new Error("unknown command: search")), SEARCH_UNSUPPORTED);
assert.equal(searchFailureText(new Error("unsupported command")), SEARCH_UNSUPPORTED);
});
test("any other failure carries the server's own text", () => {
assert.equal(searchFailureText(new Error("boom")), "boom");
assert.equal(searchFailureText(new Error("request timed out after 30000ms")), "request timed out after 30000ms");
assert.equal(searchFailureText("plain string"), "plain string");
});
-85
View File
@@ -1,85 +0,0 @@
// Unit tests for the ported ServerUrl validation, run with `node --test`.
// Mirrors the cases in android/.../test/.../ServerUrlTest.kt.
import { test } from "node:test";
import assert from "node:assert/strict";
import { validateServerUrl, resolveArtifactUrl, ServerUrlKind } from "../src/serverUrl.js";
import { Protocol, resolveTarget, isTerminal } from "../src/protocol.js";
test("defaults a bare host to /connect over ws", () => {
const v = validateServerUrl("ws://192.168.1.20:8081");
assert.equal(v.valid, true);
assert.equal(v.wsUrl, "ws://192.168.1.20:8081/connect");
assert.equal(v.httpUrl, "http://192.168.1.20:8081/connect");
assert.equal(v.host, "192.168.1.20");
assert.equal(v.port, 8081);
assert.equal(v.secure, false);
});
test("treats a lone / as the default endpoint path", () => {
const v = validateServerUrl("ws://host:1234/");
assert.equal(v.valid, true);
assert.equal(v.wsUrl, "ws://host:1234/connect");
});
test("wss maps to https and defaults the port to 443", () => {
const v = validateServerUrl("wss://example.test/connect");
assert.equal(v.valid, true);
assert.equal(v.secure, true);
assert.equal(v.port, 443);
assert.equal(v.httpUrl, "https://example.test/connect");
});
test("rejects empty, non-ws schemes, userinfo and fragments", () => {
assert.equal(validateServerUrl("").kind, ServerUrlKind.EMPTY);
assert.equal(validateServerUrl(" ").kind, ServerUrlKind.EMPTY);
assert.equal(validateServerUrl("http://host:8080/connect").kind, ServerUrlKind.UNSUPPORTED_SCHEME);
assert.equal(validateServerUrl("ftp://host").kind, ServerUrlKind.UNSUPPORTED_SCHEME);
assert.equal(validateServerUrl("ws://user:pass@host:8080/connect").kind, ServerUrlKind.USER_INFO);
assert.equal(validateServerUrl("ws://host:8080/connect#frag").kind, ServerUrlKind.FRAGMENT);
});
test("rejects malformed and hostless input", () => {
assert.equal(validateServerUrl("not a url").kind, ServerUrlKind.MALFORMED);
const hostless = validateServerUrl("ws://");
assert.ok(hostless.kind === ServerUrlKind.MALFORMED || hostless.kind === ServerUrlKind.MISSING_HOST);
assert.equal(hostless.valid, false);
});
test("preserves a query string", () => {
const v = validateServerUrl("ws://host:8080/connect?token=abc");
assert.equal(v.valid, true);
assert.equal(v.wsUrl, "ws://host:8080/connect?token=abc");
});
test("resolveArtifactUrl maps ws to http and drops /connect", () => {
assert.equal(
resolveArtifactUrl("ws://10.0.0.249:8080/connect", "/artifacts/55/4/shot.png"),
"http://10.0.0.249:8080/artifacts/55/4/shot.png",
);
});
test("resolveArtifactUrl uses https and omits the default port for wss", () => {
assert.equal(
resolveArtifactUrl("wss://example.test/connect", "artifacts/1/1/a.png"),
"https://example.test/artifacts/1/1/a.png",
);
});
test("resolveArtifactUrl returns an absolute url unchanged and null when unconfigured", () => {
assert.equal(
resolveArtifactUrl("ws://host:8080/connect", "https://cdn.test/a.png"),
"https://cdn.test/a.png",
);
assert.equal(resolveArtifactUrl("", "/artifacts/1/1/a.png"), null);
assert.equal(resolveArtifactUrl("ws://host:8080/connect", " "), null);
});
test("protocol target resolution mirrors the server shorthand", () => {
assert.equal(resolveTarget("error", "#"), Protocol.FAILURE_END);
assert.equal(resolveTarget("success", "#"), Protocol.SUCCESS_END);
assert.equal(resolveTarget("error", "cleanup"), "cleanup");
assert.equal(isTerminal("#success"), true);
assert.equal(isTerminal("#failure"), true);
assert.equal(isTerminal("cleanup"), false);
});
-17
View File
@@ -1,17 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import vm from "node:vm";
test("shell updates retain unrelated caches and the current app cache", async () => {
const handlers = new Map();
const deleted = [];
let activation;
vm.runInNewContext(await readFile(new URL("../sw.js", import.meta.url), "utf8"), {
self: { addEventListener: (type, handler) => handlers.set(type, handler), clients: { claim: async () => {} } },
caches: { keys: async () => ["pipelines-shell-v15", "pipelines-shell-v16", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
});
handlers.get("activate")({ waitUntil: (promise) => { activation = promise; } });
await activation;
assert.deepEqual(deleted, ["pipelines-shell-v15"]);
});
-59
View File
@@ -1,59 +0,0 @@
// Isolated audit regression: session identity, verified repair selection and
// live modal refresh. Provider/session data is fixture-only; no production DB.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname } from "node:path";
import { launchChrome } from "./browser.mjs";
const root=resolve(import.meta.dirname,"..");
const out=resolve(process.argv[2]??"captures-session-audit");await mkdir(out,{recursive:true});
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","chat","dialogs"].map(n=>`<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main></main></div><script type="module">
import {createModalController} from '/src/modal.js';
import {createChatView} from '/src/views/chat.js';
import {createDialogsView} from '/src/views/dialogs.js';
import {createRunDetailView} from '/src/views/runDetail.js';
const step={sequence:1,stage:'Survey',status:'completed',outcome:'success',model:'fixture',session_id:'ses_exact',session_export:{session_id:'ses_exact',status:'failed',diagnostic:'native readback failed'},artifacts:[]};
const run={id:19,pipeline_id:25,version:6,status:'succeeded',name:'Audit fixture',graph:{stages:[{key:'Survey',type:'model',edges:{success:'#success'}}]},steps:[step]};
const state={url:'ws://'+location.host+'/connect',runDetail:run,runStageSections:new Set(),runStagePane:{stageKey:'Survey',visitIndex:0}};
window.repairRequests=[];
const rt={state,modal:createModalController(),views:{},repo:{repairSessionExport:async(id,sequence)=>{repairRequests.push({id,sequence});window.recordRepair();return state.runDetail;}},renderContent:()=>{}};
rt.views.chat=createChatView(rt);rt.views.dialogs=createDialogsView(rt);rt.views.runDetail=createRunDetailView(rt);
document.querySelector('main').append(rt.views.runDetail.renderStagePane(run));rt.modal.reconcile();
window.recordRepair=()=>{const updated={...step,session_export_repairs:[{session_id:'ses_exact',status:'complete',messages:14,html:'session-repair-1-fixed.html',html_bytes:100}],artifacts:[{name:'session-repair-1-fixed.html',url:'/artifacts/19/1/session-repair-1-fixed.html',content_type:'text/html',size_bytes:100}]};state.runDetail={...run,steps:[updated]};rt.views.dialogs.refreshStageAudit();};
window.parkForExport=()=>{state.runDetail={...run,status:'waiting',export_pending_sequence:1,steps:[{...step,session_export_recovery:{status:'pending'}}]};rt.views.dialogs.refreshStageAudit();};
</script>`;
const server=createServer(async(req,res)=>{try{
const pathname=new URL(req.url,"http://fixture").pathname;
if(pathname==="/"){res.setHeader('Content-Type','text/html');res.end(html);return;}
if(pathname.startsWith('/artifacts/')){res.setHeader('Content-Type','text/html');res.setHeader('Content-Security-Policy',"sandbox; default-src 'none'");res.end('<h1>Recorded session ses_exact</h1>');return;}
const file=resolve(root,`.${pathname}`);if(!file.startsWith(root+'/'))throw Error('outside fixture');
res.setHeader('Content-Type',extname(file)==='.css'?'text/css':'text/javascript');res.end(await readFile(file));
}catch{res.writeHead(404);res.end();}});
await new Promise(r=>server.listen(0,'127.0.0.1',r));
let browser;
try{
browser=await launchChrome({width:390,height:844});
const page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector('.audit-open');await page.click('.audit-open');await page.click('[data-audit-tab=session]');
assert.match(await page.evaluate("document.querySelector('.audit-body').textContent"),/ses_exact is recorded/);
assert.doesNotMatch(await page.evaluate("document.querySelector('.audit-body').textContent"),/Session not recorded|exported by model stages/);
await page.screenshot(resolve(out,'01-recorded-identity-export-failed.png'));
await page.evaluate('parkForExport()');
assert.match(await page.evaluate("document.querySelector('.audit-body').textContent"),/pending recovery/);
assert.equal(await page.evaluate("document.querySelector('.session-export-retry').disabled"),false);
assert.equal(await page.evaluate("document.querySelectorAll('.decision-card').length"),0);
await page.screenshot(resolve(out,'03-export-wait-is-not-a-human-decision.png'));
await page.click('.session-export-retry');await page.waitForSelector('.audit-session-frame');
assert.deepEqual(await page.evaluate('repairRequests'),[{id:19,sequence:1}]);
assert.match(await page.evaluate("document.querySelector('.audit-session-frame').src"),/session-repair-1-fixed.html$/);
assert.match(await page.evaluate("document.querySelector('.audit-body').textContent"),/Recorded session: ses_exact/);
assert.doesNotMatch(await page.evaluate("document.querySelector('.audit-body').textContent"),/native readback failed/);
assert.equal(await page.evaluate("document.querySelector('.audit-session-frame').getAttribute('sandbox')"),'');
const same=await page.evaluate("window.savedFrame=document.querySelector('.audit-session-frame');true");
await page.evaluate('recordRepair()');assert.equal(await page.evaluate("savedFrame===document.querySelector('.audit-session-frame')"),same);
await page.screenshot(resolve(out,'02-complete-repair-refreshes-open-audit.png'));
console.log('PASS: recorded identity remains visible; a verified repair refreshes the open Session tab without reopening or resetting an unchanged iframe.');
}finally{await browser?.close();await new Promise(r=>server.close(r));}
-76
View File
@@ -1,76 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { effectiveSessionExport, sessionExportArtifact, sessionCaptureState, stageArtifacts, systemArtifacts } from "../src/artifacts.js";
const file = (name) => ({name,size_bytes:100,content_type:"text/html",url:`/artifacts/19/1/${name}`});
const complete = (html, id="ses_stage") => ({session_id:id,backend:"v2",status:"complete",messages:14,html,html_bytes:100});
test("a missing export never hides a recorded session identity", () => {
const state=sessionCaptureState({session_id:"ses_stage",model:"fixture",status:"completed",session_export:{session_id:"ses_stage",status:"failed",diagnostic:"readback failed"}});
assert.equal(state.sessionId,"ses_stage");assert.equal(state.artifact,null);
assert.match(state.message,/ses_stage is recorded/);assert.match(state.message,/failed/);
assert.doesNotMatch(state.message,/not recorded|exported by model stages/);
});
test("the audit viewer selects a verified complete repair without changing original evidence", () => {
const original={session_id:"ses_stage",status:"failed",diagnostic:"original capture failed"};
const repaired=complete("session-repair-1-good.html");
const step={session_id:"ses_stage",session_export:original,session_export_repairs:[repaired,{session_id:"ses_stage",status:"failed"}],artifacts:[file(repaired.html)]};
assert.equal(effectiveSessionExport(step),repaired);
assert.equal(sessionExportArtifact(step).name,repaired.html);
assert.equal(sessionCaptureState(step).artifact.url,"/artifacts/19/1/session-repair-1-good.html");
assert.equal(step.session_export,original);assert.equal(original.status,"failed");
});
test("a wrong-session repair or an unlisted file cannot masquerade as the export", () => {
const original={session_id:"ses_stage",status:"failed"};
const wrong=complete("session-repair-wrong.html","ses_other");
const missing=complete("session-repair-missing.html");
const step={session_id:"ses_stage",session_export:original,session_export_repairs:[wrong,missing],artifacts:[file(wrong.html)]};
assert.equal(effectiveSessionExport({...step,session_export_repairs:[wrong]}),original);
assert.equal(sessionExportArtifact(step),null);
});
test("a partial repair does not replace a complete original export", () => {
const original=complete("session.html");
const partial={...complete("session-repair-partial.html"),status:"partial",truncated:true};
assert.equal(effectiveSessionExport({session_id:"ses_stage",session_export:original,session_export_repairs:[partial],artifacts:[file(original.html),file(partial.html)]}),original);
});
test("versioned private and historical public repairs remain audit evidence, not deliverables", () => {
const repairs=[complete("session-repair-1-good.html"),complete("public/session-repair-1-old.html")];
const step={session_export_repairs:repairs,artifacts:[...repairs.map(entry=>file(entry.html)),file("report.html")]};
assert.deepEqual(stageArtifacts(step).map(entry=>entry.name),["report.html"]);
assert.deepEqual(systemArtifacts(step).map(entry=>entry.name),repairs.map(entry=>entry.html));
});
test("an original export naming another session is not selected", () => {
const original=complete("session.html","ses_wrong");
assert.equal(sessionExportArtifact({session_id:"ses_stage",session_export:original,artifacts:[file("session.html")]}),null);
});
test("repairs must match the original backend and directory, not just its session ID", () => {
const original={session_id:"ses_stage",backend:"v2",directory:"/owned",status:"failed"};
for (const override of [{backend:"pi",directory:"/owned"},{backend:"v2",directory:"/other"}]) {
const repair={...complete("session-repair-other.html"),...override};
const step={session_id:"ses_stage",session_export:original,session_export_repairs:[repair],artifacts:[file(repair.html)]};
assert.equal(effectiveSessionExport(step),original);
assert.equal(sessionExportArtifact(step),null);
}
});
test("a repair's file bytes must match its export receipt", () => {
const original=complete("session.html");
const repair=complete("session-repair-mismatch.html");
const step={session_id:"ses_stage",session_export:original,session_export_repairs:[repair],artifacts:[file(original.html),{...file(repair.html),size_bytes:1}]};
assert.equal(effectiveSessionExport(step),original);
assert.equal(sessionExportArtifact({...step,session_export:null}),null);
});
test("pre-admission failure, starting session and export recovery have distinct states", () => {
assert.match(sessionCaptureState({model:"fixture",status:"running"}).message,/being created/);
assert.match(sessionCaptureState({model:"fixture",status:"failed",diagnostic:"provider unreachable"}).message,/did not create.*provider unreachable/);
assert.match(sessionCaptureState({model:"fixture",status:"completed"}).message,/Runtime error/);
assert.match(sessionCaptureState({model:"fixture",status:"completed",outcome:"skipped"}).message,/was skipped/);
assert.match(sessionCaptureState({session_id:"ses_stage",session_export_recovery:{status:"pending"}}).message,/pending recovery/);
});
-16
View File
@@ -1,16 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { PipelinesRepository } from "../src/repository.js";
test("web export retry names the exact recorded visit and sends no execution request", async () => {
const sent=[];const detail={id:19,status:"succeeded"};
const repo=new PipelinesRepository({call:async frame=>{sent.push(frame);return {run_detail:detail};}});
assert.equal(await repo.repairSessionExport(19,4),detail);
assert.deepEqual(sent,[{type:"repair_session_export",run_id:19,export_sequence:4}]);
});
test("web export retry refuses an unknown run or visit before any request", async () => {
let calls=0;const repo=new PipelinesRepository({call:async()=>{calls++;}});
for(const [id,sequence] of [[0,1],[19,0],[19,-1],[19,1.5]]) await assert.rejects(repo.repairSessionExport(id,sequence));
assert.equal(calls,0);
});
-357
View File
@@ -1,357 +0,0 @@
// Unit tests for the Settings destination's pure logic (src/settings.js): the
// workspace validation rules, the Save-enabled rule, the `Saved workspace:` line,
// the connection status card's four states and the two persisted keys. No DOM, no
// socket: `node --test test/settings.test.mjs` proves the logic the page wires up,
// so the browser run only has to prove the rendering.
//
// The wording is asserted against the Android client's own strings
// (ui/screens/SettingsScreen.kt, ui/AppViewModel.kt, data/SettingsRepository.kt);
// the last test reads those sources so a rename there cannot silently drift past
// this one.
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import {
SERVER_URL_HELPER,
SERVER_URL_PLACEHOLDER,
SERVER_URL_STORAGE_KEY,
TEMPLATES_CARD_LABEL,
TEMPLATES_CARD_SECONDARY,
TRUST_BODY,
TRUST_TITLE,
WORKSPACE_ERROR,
WORKSPACE_HELPER,
WORKSPACE_PLACEHOLDER,
WORKSPACE_STORAGE_KEY,
canSaveWorkspace,
connectionActionKind,
connectionActions,
connectionCard,
readServerUrl,
readWorkspace,
savedWorkspaceLine,
validateWorkspacePath,
workspaceErrorText,
writeServerUrl,
writeWorkspace,
} from "../src/settings.js";
import { bannerState, connectingLabel } from "../src/connection.js";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
const source = (rel) => readFileSync(resolve(ROOT, rel), "utf8");
const androidSrc = (rel) => source(`android/app/src/main/java/net/awan/pipelines/${rel}`);
/** A minimal in-memory Storage, plus a throwing one, for the persistence tests. */
function memoryStorage(seed = {}) {
const map = new Map(Object.entries(seed));
return {
getItem: (key) => (map.has(key) ? map.get(key) : null),
setItem: (key, value) => map.set(key, String(value)),
key: (i) => [...map.keys()][i] ?? null,
get length() {
return map.size;
},
};
}
// ---------------------------------------------------------------------------
// The exact copy constants
// ---------------------------------------------------------------------------
test("the settings copy is the Android strings verbatim", () => {
assert.equal(SERVER_URL_PLACEHOLDER, "ws://192.168.1.20:8081/connect");
assert.equal(
SERVER_URL_HELPER,
"ws:// on a trusted LAN/VPN, or wss:// through a proxy/VPN. No authentication is used.",
);
assert.equal(WORKSPACE_PLACEHOLDER, "/Users/you/repos/pipelines");
assert.equal(
WORKSPACE_HELPER,
"An absolute directory that already exists on the execution server. For Docker, " +
"mount the host directory at the same absolute path with its owner's UID/GID. " +
"This is not the phone's storage.",
);
assert.equal(
WORKSPACE_ERROR,
"The workspace must be an absolute path that exists on the execution server.",
);
assert.equal(TRUST_TITLE, "Trusted LAN/VPN only");
assert.equal(
TRUST_BODY,
"The Pipelines API has no authentication and is not internet-safe. Do not " +
"expose it to untrusted networks, and never enter provider credentials here \u2014 " +
"the app stores none.",
);
assert.equal(TEMPLATES_CARD_LABEL, "Browse templates");
assert.equal(TEMPLATES_CARD_SECONDARY, "Reusable pipeline definitions offered by the server.");
});
// ---------------------------------------------------------------------------
// validateWorkspacePath / workspaceErrorText — AppViewModel.validateWorkspace
// ---------------------------------------------------------------------------
test("validateWorkspacePath accepts a blank draft and an absolute path", () => {
assert.equal(validateWorkspacePath(""), null);
assert.equal(validateWorkspacePath(" "), null);
assert.equal(validateWorkspacePath(undefined), null);
assert.equal(validateWorkspacePath(null), null);
assert.equal(validateWorkspacePath("/Users/you/repos/pipelines"), null);
assert.equal(validateWorkspacePath(" /srv/pipelines "), null);
});
test("validateWorkspacePath names the failure for a relative or bare path", () => {
assert.equal(validateWorkspacePath("repos/pipelines"), WORKSPACE_ERROR);
assert.equal(validateWorkspacePath("~/pipelines"), WORKSPACE_ERROR);
assert.equal(validateWorkspacePath("C:\\pipelines"), WORKSPACE_ERROR);
assert.equal(validateWorkspacePath(" relative "), WORKSPACE_ERROR);
});
test("workspaceErrorText is the error or empty (Android's `workspaceError ?: helper`)", () => {
assert.equal(workspaceErrorText("repos/pipelines"), WORKSPACE_ERROR);
assert.equal(workspaceErrorText(""), "");
assert.equal(workspaceErrorText("/srv/pipelines"), "");
});
// ---------------------------------------------------------------------------
// canSaveWorkspace — the Save button's enabled state
// ---------------------------------------------------------------------------
test("canSaveWorkspace enables Save only for a trimmed absolute path", () => {
assert.equal(canSaveWorkspace("/srv/pipelines"), true);
assert.equal(canSaveWorkspace(" /srv/pipelines "), true);
// Deliberately stricter than Android (which also enables Save on a blank
// field): the browser has nothing to save for a blank path.
assert.equal(canSaveWorkspace(""), false);
assert.equal(canSaveWorkspace(" "), false);
assert.equal(canSaveWorkspace("repos/pipelines"), false);
assert.equal(canSaveWorkspace(undefined), false);
});
test("canSaveWorkspace derives from validateWorkspacePath, so the rule has one source", () => {
for (const value of ["", " ", "repos/pipelines", "~/x", "C:\\x", "/srv/x", " /srv/x ", "/", "/a/b"]) {
const trimmed = String(value).trim();
assert.equal(
canSaveWorkspace(value),
trimmed !== "" && validateWorkspacePath(value) === null,
`disagreement for ${JSON.stringify(value)}`,
);
}
});
// ---------------------------------------------------------------------------
// savedWorkspaceLine
// ---------------------------------------------------------------------------
test("savedWorkspaceLine reads the path, or (none) when unset", () => {
assert.equal(savedWorkspaceLine("/Users/you/repos/pipelines"), "Saved workspace: /Users/you/repos/pipelines");
assert.equal(savedWorkspaceLine(" /srv/x "), "Saved workspace: /srv/x");
assert.equal(savedWorkspaceLine(""), "Saved workspace: (none)");
assert.equal(savedWorkspaceLine(" "), "Saved workspace: (none)");
assert.equal(savedWorkspaceLine(null), "Saved workspace: (none)");
});
// ---------------------------------------------------------------------------
// connectionCard — SettingsScreen.kt's ConnectionStatusCard
// ---------------------------------------------------------------------------
test("connectionCard idle reads Not connected", () => {
assert.deepEqual(connectionCard({ kind: "idle" }), ["Not connected"]);
assert.deepEqual(connectionCard(undefined), ["Not connected"]);
assert.deepEqual(connectionCard({ kind: "something-else" }), ["Not connected"]);
});
test("connectionCard connecting names the attempt", () => {
assert.deepEqual(connectionCard({ kind: "connecting", attempt: 4 }), ["Connecting (attempt 4)\u2026"]);
assert.deepEqual(connectionCard({ kind: "connecting" }), ["Connecting (attempt 0)\u2026"]);
});
test("the connecting line is the banner's own, so the app sentence has one source", () => {
for (const attempt of [0, 1, 7]) {
const state = { kind: "connecting", attempt };
assert.deepEqual(connectionCard(state), [bannerState(state).text]);
}
assert.equal(connectingLabel(3), "Connecting (attempt 3)\u2026");
});
test("connectionCard connected shows the build and server time when present", () => {
assert.deepEqual(
connectionCard(
{ kind: "connected" },
{ version: "v1.2.3", commit: "abc123", serverTime: "2026-10-19T08:00:00Z" },
),
["Connected", "Server build v1.2.3 (abc123)", "Server time 2026-10-19T08:00:00Z"],
);
// Missing fields are tolerated: no build line, no time line.
assert.deepEqual(connectionCard({ kind: "connected" }, {}), ["Connected"]);
assert.deepEqual(connectionCard({ kind: "connected" }, { version: "v1", serverTime: " " }), [
"Connected",
"Server build v1",
]);
});
test("connectionCard disconnected carries the reason and the retry suffix", () => {
assert.deepEqual(
connectionCard({ kind: "disconnected", reason: "Connection closed (1006)", retrying: true }),
["Disconnected", "Connection closed (1006)", "Retrying with backoff\u2026"],
);
assert.deepEqual(
connectionCard({ kind: "disconnected", reason: "Connection closed (1000)", retrying: false }),
["Disconnected", "Connection closed (1000)"],
);
// A blank reason renders no empty line; retrying alone still shows.
assert.deepEqual(connectionCard({ kind: "disconnected", reason: " ", retrying: true }), [
"Disconnected",
"Retrying with backoff\u2026",
]);
});
// ---------------------------------------------------------------------------
// connectionActions — SettingsScreen.kt's `active` branch
// ---------------------------------------------------------------------------
test("connectionActions emphasises Disconnect while connected or connecting", () => {
assert.deepEqual(connectionActions({ kind: "connected" }), { primary: "Disconnect", secondary: "Connect" });
assert.deepEqual(connectionActions({ kind: "connecting", attempt: 2 }), {
primary: "Disconnect",
secondary: "Connect",
});
});
test("connectionActions emphasises Connect and offers Reconnect otherwise", () => {
assert.deepEqual(connectionActions({ kind: "idle" }), { primary: "Connect", secondary: "Reconnect" });
assert.deepEqual(connectionActions({ kind: "disconnected", reason: "x" }), {
primary: "Connect",
secondary: "Reconnect",
});
assert.deepEqual(connectionActions(undefined), { primary: "Connect", secondary: "Reconnect" });
});
test("connectionActionKind keeps Connect connect-only (never the header's toggle)", () => {
// Android's connect() validates + persists + opens; only disconnect() closes.
assert.equal(connectionActionKind("Connect"), "connect");
assert.equal(connectionActionKind("Reconnect"), "reconnect");
assert.equal(connectionActionKind("Disconnect"), "disconnect");
// Any unknown label is treated as a connect, never as a disconnect.
assert.equal(connectionActionKind(""), "connect");
assert.equal(connectionActionKind(undefined), "connect");
for (const state of [{ kind: "connected" }, { kind: "connecting" }, { kind: "idle" }]) {
const { primary, secondary } = connectionActions(state);
const kinds = [connectionActionKind(primary), connectionActionKind(secondary)];
assert.deepEqual(kinds, state.kind === "idle" ? ["connect", "reconnect"] : ["disconnect", "connect"]);
}
});
// ---------------------------------------------------------------------------
// Persisted keys round-trip
// ---------------------------------------------------------------------------
test("the two persisted keys are the exact, stable localStorage keys", () => {
assert.equal(SERVER_URL_STORAGE_KEY, "pipelines.web.serverUrl.v2");
assert.equal(WORKSPACE_STORAGE_KEY, "pipelines.web.workspace.v1");
});
test("writeWorkspace trims and reads back; readWorkspace is tolerant", () => {
const storage = memoryStorage();
assert.equal(writeWorkspace(storage, " /srv/pipelines "), "/srv/pipelines");
assert.equal(storage.getItem(WORKSPACE_STORAGE_KEY), "/srv/pipelines");
assert.equal(storage.length, 1, "only the workspace key is written");
assert.equal(readWorkspace(storage), "/srv/pipelines");
// Blank reads back as "" (the stored value), never throwing.
writeWorkspace(storage, " ");
assert.equal(readWorkspace(storage), "");
assert.equal(storage.length, 1);
});
test("the server-URL key round-trips trimmed, under its own key only", () => {
const storage = memoryStorage();
assert.equal(writeServerUrl(storage, " ws://127.0.0.1:8080/connect "), "ws://127.0.0.1:8080/connect");
assert.equal(storage.getItem(SERVER_URL_STORAGE_KEY), "ws://127.0.0.1:8080/connect");
assert.equal(readServerUrl(storage), "ws://127.0.0.1:8080/connect");
assert.equal(storage.length, 1, "only the server-URL key is written");
// The two keys are independent: writing one never disturbs the other.
writeWorkspace(storage, "/srv/pipelines");
assert.equal(storage.length, 2);
assert.equal(readServerUrl(storage), "ws://127.0.0.1:8080/connect");
assert.equal(readWorkspace(storage), "/srv/pipelines");
});
test("readServerUrl is blank on a missing/unreadable storage and never throws", () => {
assert.equal(readServerUrl(memoryStorage()), "");
assert.equal(readServerUrl(undefined), "");
assert.equal(readServerUrl(null), "");
const throwing = {
getItem() {
throw new Error("denied");
},
setItem() {
throw new Error("denied");
},
};
assert.equal(readServerUrl(throwing), "");
assert.equal(writeServerUrl(throwing, " ws://host:1/connect "), "ws://host:1/connect");
});
test("readWorkspace is blank on a missing/unreadable storage and never throws", () => {
assert.equal(readWorkspace(memoryStorage()), "");
assert.equal(readWorkspace(undefined), "");
assert.equal(readWorkspace(null), "");
const throwing = {
getItem() {
throw new Error("denied");
},
setItem() {
throw new Error("denied");
},
};
assert.equal(readWorkspace(throwing), "");
assert.equal(writeWorkspace(throwing, "/srv/x"), "/srv/x");
});
// ---------------------------------------------------------------------------
// Parity with the Android sources
// ---------------------------------------------------------------------------
test("the wording still matches the Android client's sources", () => {
const settings = androidSrc("ui/screens/SettingsScreen.kt");
for (const line of [
'Text("Connection"',
'Text("Server URL")',
'Text("ws://192.168.1.20:8081/connect")',
"ws:// on a trusted LAN/VPN, or wss:// through a proxy/VPN. No authentication is used.",
'Text("Workspace"',
'Text("Workspace path (on the server)")',
'Text("/Users/you/repos/pipelines")',
"An absolute directory that already exists on the execution server. For Docker, ",
"This is not the phone's storage.",
'Text("Save workspace")',
'"Trusted LAN/VPN only"',
"The Pipelines API has no authentication and is not internet-safe. Do not ",
"never enter provider credentials here \\u2014 ",
'Text("Browse templates"',
"Reusable pipeline definitions offered by the server.",
'Text("Disconnected"',
'Text("Retrying with backoff\\u2026")',
'Text("Connecting (attempt ${state.attempt})\\u2026")',
'Text("Connected"',
]) {
assert.ok(settings.includes(line), `SettingsScreen.kt is missing: ${line}`);
}
const vm = androidSrc("ui/AppViewModel.kt");
assert.ok(
vm.includes("The workspace must be an absolute path that exists on the execution server."),
"AppViewModel.kt workspace error",
);
assert.ok(vm.includes("!trimmed.startsWith(\"/\")"), "AppViewModel.kt absolute-path rule");
// The two Android preference keys the browser analogues stand in for.
const repo = androidSrc("data/SettingsRepository.kt");
assert.ok(repo.includes('const val KEY_SERVER_URL = "server_url"'), "KEY_SERVER_URL");
assert.ok(repo.includes('const val KEY_WORKSPACE = "workspace"'), "KEY_WORKSPACE");
// Only non-secret preferences are stored (no credentials).
assert.ok(repo.includes("No credentials or tokens are ever stored"), "no-secrets note");
});
-96
View File
@@ -1,96 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
DESTINATIONS,
destinationForView,
destinationIndex,
rovingTabindex,
sectionModel,
shellStatus,
tabIndexForKey,
} from "../src/shell.js";
test("the shell has exactly four destinations in order", () => {
assert.deepEqual(
DESTINATIONS.map((item) => item.key),
["pipelines", "runs", "chat", "settings"],
);
for (const item of DESTINATIONS) {
assert.equal(typeof item.label, "string");
assert.ok(item.label.length > 0);
assert.equal(item.path, `/${item.key}`);
}
});
test("views map onto the destination that owns them", () => {
assert.equal(destinationForView("pipelines"), "pipelines");
assert.equal(destinationForView("runs"), "runs");
assert.equal(destinationForView("chat"), "chat");
assert.equal(destinationForView("settings"), "settings");
// Templates is reached from Settings; it is a route but not a destination.
assert.equal(destinationForView("templates"), "settings");
assert.equal(destinationIndex("chat"), 2);
assert.equal(destinationIndex("missing"), 0);
});
test("roving tabindex keeps exactly one tab in the tab order", () => {
assert.equal(rovingTabindex(0, 0), "0");
assert.equal(rovingTabindex(0, 1), "-1");
assert.deepEqual(
[0, 1, 2, 3].map((index) => rovingTabindex(2, index)),
["-1", "-1", "0", "-1"],
);
});
test("tab keys move, wrap and jump to the ends", () => {
assert.equal(tabIndexForKey("ArrowRight", 0, 4), 1);
assert.equal(tabIndexForKey("ArrowRight", 3, 4), 0);
assert.equal(tabIndexForKey("ArrowLeft", 0, 4), 3);
assert.equal(tabIndexForKey("ArrowLeft", 2, 4), 1);
assert.equal(tabIndexForKey("Home", 2, 4), 0);
assert.equal(tabIndexForKey("End", 2, 4), 3);
// Vertical tablists accept Up/Down as well; horizontal ones ignore them.
assert.equal(tabIndexForKey("ArrowDown", 1, 4, { vertical: true }), 2);
assert.equal(tabIndexForKey("ArrowUp", 0, 4, { vertical: true }), 3);
assert.equal(tabIndexForKey("ArrowDown", 1, 4), -1);
assert.equal(tabIndexForKey("Enter", 1, 4), -1);
// A non-key or an impossible list never moves focus.
assert.equal(tabIndexForKey("ArrowRight", 0, 0), -1);
assert.equal(tabIndexForKey("ArrowRight", -1, 4), -1);
});
test("the shell status names every connection state without colour", () => {
assert.deepEqual(shellStatus({ kind: "connected" }), {
text: "Connected",
tone: "ok",
state: "connected",
});
assert.equal(shellStatus({ kind: "connecting", attempt: 2 }).text, "Connecting\u2026");
assert.equal(shellStatus({ kind: "disconnected", reason: "closed" }).text, "Disconnected");
assert.deepEqual(shellStatus({ kind: "idle" }, { hasEndpoint: true }), {
text: "Not connected",
tone: "idle",
state: "idle",
});
assert.deepEqual(shellStatus({ kind: "idle" }, { hasEndpoint: false }), {
text: "Not configured",
tone: "idle",
state: "unconfigured",
});
});
test("sectionModel keeps one active tab and no tablist without a detail", () => {
const model = {
tabs: [
{ key: "summary", label: "Summary" },
{ key: "graph", label: "Graph" },
],
active: "graph",
};
assert.deepEqual(sectionModel(model), { tabs: model.tabs, active: 1 });
assert.deepEqual(sectionModel({ tabs: [], active: "summary" }), { tabs: [], active: -1 });
assert.deepEqual(sectionModel({ tabs: model.tabs, active: "missing" }), {
tabs: model.tabs,
active: 0,
});
});
-102
View File
@@ -1,102 +0,0 @@
// Live end-to-end smoke test: drives the *real* client (src/client.js) against a
// running Pipelines server. Opt-in, because it needs a server:
//
// PIPELINES_WS_URL=ws://127.0.0.1:8080/connect node test/smoke.mjs
//
// Uses Node's built-in global WebSocket and fetch (Node >= 22). Exits non-zero
// on the first failed assertion so it is usable in a check.
import assert from "node:assert/strict";
import { PipelinesClient } from "../src/client.js";
import { PipelinesRepository } from "../src/repository.js";
import { validateServerUrl, resolveArtifactUrl } from "../src/serverUrl.js";
const raw = process.env.PIPELINES_WS_URL ?? process.argv[2] ?? "";
if (!raw) {
console.error("PIPELINES_WS_URL is required, e.g. ws://127.0.0.1:8080/connect");
process.exit(2);
}
const validated = validateServerUrl(raw);
if (!validated.valid) {
console.error(`invalid server URL: ${validated.message}`);
process.exit(2);
}
const client = new PipelinesClient();
const repo = new PipelinesRepository(client);
const checks = [];
const pass = (name) => {
checks.push(name);
console.log(` ok ${name}`);
};
try {
await connectWithTimeout(client, validated, 5000);
pass("websocket connected");
const pong = await repo.ping();
assert.equal(pong.type, "pong");
pass("ping -> pong");
const pipelines = await repo.listPipelines();
assert.ok(Array.isArray(pipelines));
pass(`list_pipelines -> ${pipelines.length} pipeline(s)`);
const { runs, usage } = await repo.listRuns();
assert.ok(Array.isArray(runs));
pass(`list_runs -> ${runs.length} run(s), usage.total=${usage?.total ?? "n/a"}`);
if (pipelines.length) {
const detail = await repo.getPipeline(pipelines[0].id, pipelines[0].version);
assert.equal(detail.id, pipelines[0].id);
assert.ok(Array.isArray(detail.graph?.stages));
pass(`get_pipeline #${detail.id} -> ${detail.graph.stages.length} stage(s)`);
} else {
console.log(" -- no pipelines; skipped get_pipeline");
}
if (runs.length) {
const run = await repo.getRun(runs[0].id);
assert.equal(run.id, runs[0].id);
assert.ok(Array.isArray(run.steps));
pass(`get_run #${run.id} -> status=${run.status} steps=${run.steps.length}`);
const artifact = run.steps.flatMap((s) => s.artifacts ?? []).find((a) => a.url);
if (artifact) {
const url = resolveArtifactUrl(raw, artifact.url);
assert.ok(url?.startsWith("http"));
const res = await fetch(url, { method: "HEAD" });
pass(`artifact HEAD ${url} -> ${res.status} ${res.headers.get("content-type") ?? ""}`.trim());
assert.ok(res.ok, `artifact HEAD was ${res.status}`);
} else {
console.log(" -- newest run has no artifacts; skipped artifact fetch");
}
} else {
console.log(" -- no runs; skipped get_run");
}
console.log(`\nSMOKE PASS (${checks.length} checks) against ${validated.wsUrl}`);
client.disconnect();
process.exit(0);
} catch (err) {
console.error(`\nSMOKE FAIL: ${err?.message ?? err}`);
console.error(`against ${validated.wsUrl}`);
client.disconnect();
process.exit(1);
}
function connectWithTimeout(c, validatedUrl, ms) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`connect timed out after ${ms}ms`)), ms);
const onState = (event) => {
if (event.detail.kind === "connected") {
clearTimeout(timer);
c.removeEventListener("state", onState);
resolve();
}
};
c.addEventListener("state", onState);
c.connect(validatedUrl);
});
}
-23
View File
@@ -1,23 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { stageSource } from "../src/stageDefinition.js";
test("source slices preserve authored CRLF, whitespace, custom blocks and shorthand", () => {
const first = " # stage one\r\n\r\n```custom\r\nhello\r\n```\r\n```edges\r\nsuccess -> #\r\n```\r\n\r\n";
const last = "# stage two\r\n```prompt\r\nlast\r\n```";
assert.equal(stageSource(first + last, "one"), first);
assert.equal(stageSource(first + last, "two"), last);
});
test("stage-like lines inside blocks do not terminate or create source ranges", () => {
const source = "# stage one\n```prompt\n# stage two\n```js\ntext\n```\n\n";
assert.equal(stageSource(source + "# stage two\n", "one"), source);
assert.equal(stageSource(source, "two"), null);
});
test("missing source, absent stages and terminals never produce guessed definitions", () => {
for (const source of [undefined, null, "", "# stage one\n"]) {
assert.equal(stageSource(source, "missing"), null);
assert.equal(stageSource(source, "#success"), null);
}
});
-151
View File
@@ -1,151 +0,0 @@
// Pure Templates helper tests: wording (singular/plural, placeholders), the
// card mapping and the stage-summary/graph-note derivations. No DOM, no server.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
CREATE_CANCEL,
CREATE_CLOSE,
CREATE_CONFIRM,
CREATE_NAME_LABEL,
CREATE_NOTE,
CREATE_SENDING,
createConfirmLabel,
createDismissLabel,
createFormTitle,
createFormValid,
createSuccessMessage,
createdPipelineName,
effectiveStageType,
stageCountText,
templateCard,
templateDetailName,
templateGalleryName,
templateGraphNote,
templateStageCountLabel,
templateStageSummary,
TEMPLATE_GRAPH_NOTE,
TEMPLATE_NO_STAGES_NOTE,
TEMPLATE_UNPARSED_GRAPH_NOTE,
TEMPLATE_UNPARSED_SUMMARY_NOTE,
} from "../src/templates.js";
test("stageCountText spells one stage and many stages", () => {
assert.equal(stageCountText(1), "1 stage");
assert.equal(stageCountText(2), "2 stages");
assert.equal(stageCountText(0), "0 stages");
});
test("templateStageCountLabel says unavailable for an unknown count, never zero", () => {
assert.equal(templateStageCountLabel(null), "stage count unavailable");
assert.equal(templateStageCountLabel(undefined), "stage count unavailable");
assert.equal(templateStageCountLabel(1), "1 stage");
assert.equal(templateStageCountLabel(3), "3 stages");
});
test("a blank gallery name becomes the unnamed placeholder", () => {
assert.equal(templateGalleryName(""), "(unnamed template)");
assert.equal(templateGalleryName(" "), "(unnamed template)");
assert.equal(templateGalleryName("Review a repository"), "Review a repository");
});
test("a blank detail name falls back to the template key", () => {
assert.equal(templateDetailName({ key: "task", name: "" }), "task");
assert.equal(templateDetailName({ key: "task", name: " " }), "task");
assert.equal(templateDetailName({ key: "task", name: "Complete a task" }), "Complete a task");
});
test("effectiveStageType defaults a blank type to model", () => {
assert.equal(effectiveStageType(""), "model");
assert.equal(effectiveStageType(null), "model");
assert.equal(effectiveStageType(" "), "model");
assert.equal(effectiveStageType("human"), "human");
});
test("templateCard takes the stage count from the parsed graph, null when absent", () => {
const entry = { key: "task", name: "Complete a task", description: "Do it." };
assert.equal(templateCard(entry, null).stageCount, null);
assert.equal(templateCard(entry, { stages: [] }).stageCount, 0);
assert.equal(templateCard(entry, { stages: [{ key: "a" }, { key: "b" }] }).stageCount, 2);
assert.deepEqual(templateCard(entry, null), {
key: "task",
name: "Complete a task",
description: "Do it.",
stageCount: null,
});
});
test("templateStageSummary distinguishes unparsed, empty and populated", () => {
assert.deepEqual(templateStageSummary(null), {
note: TEMPLATE_UNPARSED_SUMMARY_NOTE,
stages: [],
});
assert.deepEqual(templateStageSummary({ stages: [] }), {
note: TEMPLATE_NO_STAGES_NOTE,
stages: [],
});
const summary = templateStageSummary({ stages: [{ key: "plan", type: "" }, { key: "review", type: "human" }] });
assert.equal(summary.note, null);
assert.deepEqual(summary.stages, [
{ key: "plan", type: "model" },
{ key: "review", type: "human" },
]);
});
test("templateGraphNote picks the unparsed or parsed note", () => {
assert.equal(templateGraphNote(null), TEMPLATE_UNPARSED_GRAPH_NOTE);
assert.equal(templateGraphNote({ stages: [] }), TEMPLATE_GRAPH_NOTE);
});
test("createFormTitle names the template, a blank name falling back to the key", () => {
assert.equal(createFormTitle({ key: "task", name: "Complete a task" }), "Create from Complete a task");
assert.equal(createFormTitle({ key: "task", name: "" }), "Create from task");
assert.equal(createFormTitle({ key: "task", name: " " }), "Create from task");
});
test("createFormValid rejects blank/whitespace, sending and an existing creation", () => {
assert.equal(createFormValid("a pipeline"), true);
assert.equal(createFormValid(""), false);
assert.equal(createFormValid(" "), false);
assert.equal(createFormValid(null), false);
assert.equal(createFormValid("a pipeline", { sending: true }), false);
assert.equal(createFormValid("a pipeline", { created: "a pipeline" }), false);
assert.equal(createFormValid("a pipeline", { created: "" }), false);
// Defaults: a non-blank name with no options is valid.
assert.equal(createFormValid("a pipeline", {}), true);
});
test("createConfirmLabel switches Create / Creating…", () => {
assert.equal(createConfirmLabel(false), CREATE_CONFIRM);
assert.equal(createConfirmLabel(true), CREATE_SENDING);
});
test("createDismissLabel is Cancel until a creation, then Close", () => {
assert.equal(createDismissLabel(null), CREATE_CANCEL);
assert.equal(createDismissLabel(undefined), CREATE_CANCEL);
assert.equal(createDismissLabel("Made"), CREATE_CLOSE);
});
test("createSuccessMessage is the exact success line", () => {
assert.equal(createSuccessMessage("Release helper"), 'Created "Release helper". It is in the Pipelines list.');
});
test("createdPipelineName prefers the returned name, else the trimmed submitted name", () => {
assert.equal(createdPipelineName({ name: "Server name" }, "Typed name"), "Server name");
assert.equal(createdPipelineName({ name: " " }, " Typed name "), "Typed name");
assert.equal(createdPipelineName(null, " Typed name "), "Typed name");
assert.equal(createdPipelineName({}, ""), "");
});
test("the create dialog's fixed wording is the app's", () => {
assert.equal(CREATE_NAME_LABEL, "New pipeline name (required)");
assert.equal(
CREATE_NOTE,
"Creates a new draft pipeline on the server from this template's source; it is not run.",
);
assert.equal(CREATE_CONFIRM, "Create");
assert.equal(CREATE_SENDING, "Creating…");
assert.equal(CREATE_CANCEL, "Cancel");
assert.equal(CREATE_CLOSE, "Close");
});
-74
View File
@@ -1,74 +0,0 @@
// Scratch-only chat rendering: no provider, backend, or production sessions.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } 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-tool-summary");
await mkdir(out, { recursive: true });
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","chat","dialogs"].map(n=>`<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main class="workspace"><div class="pane-main"><div class="content" id="content"></div></div></main></div>
<script type="module">
import { createChatView } from '/src/views/chat.js';
import { createModalController } from '/src/modal.js';
const id='scratch';
const state={view:'chat',chatActiveId:id,chatSessions:[{id,title:'Tool summary regression',backend:'codex'}],
chatOverrides:{},chatDrafts:{},chatToolRows:new Set(),chatThreads:new Map([[id,{loaded:true,draft:'',messages:[],attachments:[],notices:[],running:false}]])};
const modal=createModalController();
const rt={state,modal,repo:{},renderContent:()=>paint(),closeDetail:()=>{}};
const view=createChatView(rt);
window.paint=()=>{document.querySelector('#content').replaceChildren(view.renderChatConversation());modal.reconcile();};
window.setErrors=(errors)=>{
state.chatThreads.get(id).messages=[{id:'user',role:'user',parts:[{type:'text',text:'Check the project.'}]},
{id:'assistant',role:'assistant',parts:[...Array.from({length:82},(_,i)=>({id:'tool-'+i,type:'tool',name:'read',state:{status:i<errors?'error':'completed',input:{path:'example.txt'},error:i<errors?'Fixture read failed':undefined}})),{type:'text',text:'Finished checking. The individual failed call remains visible in the tool details.'}]}];paint();};
setErrors(1);
</script>`;
const server = createServer(async (req, res) => {
try {
const path = new URL(req.url, "http://fixture").pathname;
if (path === "/") { res.setHeader("Content-Type", "text/html"); res.end(html); return; }
const file = resolve(root, `.${path}`);
if (!file.startsWith(root + "/")) throw Error("outside fixture");
res.setHeader("Content-Type", extname(file) === ".css" ? "text/css" : "text/javascript");
res.end(await readFile(file));
} catch { res.writeHead(404); res.end(); }
});
await new Promise(r => server.listen(0, "127.0.0.1", r));
let browser;
try {
browser = await launchChrome();
const page = await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
for (const width of [390, 1100]) {
await page.resize(width, 844);
for (const errors of [0, 1, 2]) {
await page.waitForSelector(".chat-tool-chip");
await page.evaluate(`setErrors(${errors})`);
const data = await page.evaluate(`(() => {
const chip=document.querySelector('.chat-tool-chip'), label=chip.querySelector('.chat-tool-label'), error=chip.querySelector('.chat-tool-error-count');
return {label:label.textContent,error:error?.textContent??'',color:getComputedStyle(label).color,bad:getComputedStyle(document.documentElement).getPropertyValue('--bad').trim(),border:getComputedStyle(chip).borderTopColor,outline:getComputedStyle(chip).outlineStyle,aria:chip.getAttribute('aria-label'),overflow:document.documentElement.scrollWidth>innerWidth};
})()`);
assert.equal(data.label, "82 tools");
assert.equal(data.error, errors ? `· ${errors} ${errors === 1 ? "error" : "errors"}` : "");
assert.equal(data.border, "rgba(0, 0, 0, 0)");
assert.equal(data.outline, "none");
assert.equal(data.overflow, false);
assert.equal(await page.evaluate("getComputedStyle(document.querySelector('.chat-tool-label')).color === getComputedStyle(document.querySelector('.chat-tool-chevron')).color"), true);
if (errors) assert.match(data.aria, new RegExp(`${errors} error`));
await page.screenshot(resolve(out, `tools-82-errors-${errors}-${width}.png`));
}
}
await page.evaluate("setErrors(1)");
await page.click(".chat-tool-chip");
await page.waitForSelector(".chat-tool-row-failed");
assert.equal(await page.evaluate("document.querySelectorAll('.chat-tool-row').length"), 82);
assert.equal(await page.evaluate("document.querySelectorAll('.chat-tool-row-failed').length"), 1);
await page.screenshot(resolve(out, "individual-error-in-tool-details.png"));
console.log("PASS: 82 tools stays neutral and borderless for zero/one/two errors; separate error counts and individual failures remain visible.");
} finally {
await browser?.close();
await new Promise(r => server.close(r));
}
-17
View File
@@ -1,17 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { toolFailureCount, toolCallCount } from "../src/chat.js";
test("one error among 82 calls is one failed call, not an entirely failed tool group", () => {
const parts = Array.from({ length: 82 }, (_, i) => ({type:"tool",state:{status:i===17?"error":"completed"}}));
assert.equal(toolCallCount(parts),82);
assert.equal(toolFailureCount(parts),1);
parts.push({type:"text",state:{status:"error"}});
assert.equal(toolFailureCount(parts),1);
});
test("error counts ignore running and missing states and keep multiple failures", () => {
assert.equal(toolFailureCount(null),0);
assert.equal(toolFailureCount([{type:"tool"},{type:"tool",state:{status:"running"}}]),0);
assert.equal(toolFailureCount([{type:"tool",state:{status:"error"}},{type:"tool",state:{status:"error"}}]),2);
});
-106
View File
@@ -1,106 +0,0 @@
// Isolated browser fixture: real view + repository, recorded wire frames; no
// connection to any Pipelines service and no production data or mutations.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname } from "node:path";
import { fileURLToPath } from "node:url";
import { launchChrome, eventually } from "./browser.mjs";
const root = fileURLToPath(new URL("../", import.meta.url));
const out = resolve(process.argv[2] || "captures/search-types-recent");
await mkdir(out, { recursive: true });
const server = createServer(async (req, res) => {
try {
if (req.url === "/") {
res.setHeader("Content-Type", "text/html; charset=utf-8");
const index = await readFile(resolve(root, "index.html"), "utf8");
const styles = index.match(/<link rel="stylesheet"[^>]+>/g).join("\n");
res.end(`<!doctype html><meta charset="utf-8">${styles}<body><p>Isolated search fixture — recorded requests, no live service</p><div id="host"></div>`);
return;
}
const path = resolve(root, `.${req.url}`);
if (!path.startsWith(root)) throw new Error("invalid path");
res.setHeader("Content-Type", extname(path) === ".js" ? "text/javascript" : "text/css");
res.end(await readFile(path));
} catch {
res.writeHead(404).end();
}
});
await new Promise((done) => server.listen(0, "127.0.0.1", done));
let browser;
try {
browser = await launchChrome();
const page = await browser.openPage(`http://127.0.0.1:${server.address().port}`);
await page.evaluate(`(async () => {
const { createSearchView } = await import('/src/views/search.js');
const { SearchSequencer } = await import('/src/search.js');
const { PipelinesRepository } = await import('/src/repository.js');
window.framesSent = [];
const repo = new PipelinesRepository({ call: async (frame) => {
framesSent.push(frame);
const fixtures = {
pipeline: [{ kind: 'pipeline', target: 'pipeline:12', pipeline: { id: 12, name: 'Recent fixture pipeline', version: 1, stages: 2 } }],
artifact: [{ kind: 'artifact', target: '/artifacts/12/1/report.txt', artifact: { run_id: 12, sequence: 1, name: 'Recent fixture report.txt', url: '/artifacts/12/1/report.txt', content_type: 'text/plain', size_bytes: 20 } }],
};
return { search_results: {
results: frame.search.query === '' ? fixtures[frame.search.kind] || [] : [],
truncated: frame.search.query === '' && ['field', 'pipeline'].includes(frame.search.kind),
} };
}});
const state = { searchQuery: '', searchKind: '', searchSort: 'relevance',
searchResults: [], searchSequencer: new SearchSequencer(), searchActiveIndex: 0 };
const view = createSearchView({ state, repo, searchHost: document.querySelector('#host'), renderHeader() {} });
view.openSearch();
})()`);
const last = () => page.evaluate("framesSent.at(-1)");
const search = async (text) => {
const before = await page.evaluate("framesSent.length");
await page.fill("#searchInput", text);
await eventually(async () => (await page.evaluate("framesSent.length")) > before);
};
await search("T:pipeline plan");
assert.deepEqual((await last()).search, { query: " plan", kind: "pipeline", limit: 0 });
assert.equal(await page.evaluate("document.querySelector('#searchKind').value"), "pipeline");
await page.screenshot(`${out}/01-type-filter.png`);
await search("t:run plan TYPE:artifact");
assert.equal((await last()).search.kind, "artifact");
await page.screenshot(`${out}/02-last-type-wins.png`);
await page.evaluate("document.querySelector('#searchKind').value = 'step'; document.querySelector('#searchKind').dispatchEvent(new Event('change'))");
await eventually(async () => (await last()).search.kind === "step");
assert.equal(await page.evaluate("document.querySelector('#searchInput').value"), " plan ");
await page.screenshot(`${out}/03-selector-replaces-token.png`);
await search('"t:run" t:unknown');
assert.equal((await last()).search.query, '"t:run" t:unknown');
await page.screenshot(`${out}/04-literal-tokens.png`);
await search("t:pipeline");
assert.deepEqual((await last()), { type: "search", search: { query: "", kind: "pipeline", limit: 0 } });
await eventually(() => page.evaluate("document.querySelector('#searchResults').textContent.includes('Recent fixture pipeline')"));
await page.screenshot(`${out}/05-type-only-pipelines.png`);
await search("type:ARTIFACT");
assert.deepEqual((await last()).search, { query: "", kind: "artifact", limit: 0 });
await eventually(() => page.evaluate("document.querySelector('#searchResults').textContent.includes('Recent fixture report.txt')"));
await page.screenshot(`${out}/06-type-only-artifacts.png`);
await page.evaluate("document.querySelector('#searchKind').value = 'step'; document.querySelector('#searchKind').dispatchEvent(new Event('change'))");
await eventually(() => page.evaluate("document.querySelector('#searchResults').textContent === 'No steps yet.'"));
assert.deepEqual((await last()).search, { query: "", kind: "step", limit: 0 });
await page.screenshot(`${out}/07-empty-kind.png`);
await page.evaluate("document.querySelector('#searchKind').value = 'field'; document.querySelector('#searchKind').dispatchEvent(new Event('change'))");
await eventually(() => page.evaluate("document.querySelector('#searchResults').textContent.includes(\"No fields found within the server's scan limit.\")"));
await page.screenshot(`${out}/08-scan-bound-empty.png`);
const beforeClear = await page.evaluate("framesSent.length");
await page.click("#searchClearFilter");
assert.equal(await page.evaluate("document.querySelector('#searchInput').value"), "");
assert.equal(await page.evaluate("document.querySelector('#searchKind').value"), "");
assert.equal(await page.evaluate("document.querySelector('#searchResults').textContent"), "");
assert.equal(await page.evaluate("framesSent.length"), beforeClear);
await page.screenshot(`${out}/09-cleared-filter.png`);
console.log(`PASS: type tokens, wire kind/query, precedence, selector replacement, literals, kind-only results/empty state and clear. Captures: ${out}`);
} finally {
await browser?.close();
await new Promise((done) => server.close(done));
}
File diff suppressed because it is too large Load Diff
-146
View File
@@ -1,146 +0,0 @@
// Scratch-only browser proof: real views/modal/graph, deterministic get_pipeline
// fixture. No deployed service, socket, workflow, model or device is contacted.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname } from "node:path";
import { fileURLToPath } from "node:url";
import { launchChrome } from "./browser.mjs";
const root = fileURLToPath(new URL("../", import.meta.url));
const out = resolve(process.argv[2] || ".ui-stage-definition");
await mkdir(out, { recursive: true });
const source = "# stage review\n\n```prompt\nReview **the change**.\n# stage not-a-node\n```\n\n```custom\nPreserve this authored block.\n```\n\n```edges\nsuccess -> #\n```\n\n";
const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Stage definition scratch proof</title>
${["design/tokens/tokens", "base", "shell", "lists", "run-detail", "chat", "graph", "dialogs"].map(name => `<link rel="stylesheet" href="/${name}.css">`).join("")}
<div class="app-root" id="root" style="display:block;padding:24px"><h1 id="detailTitle" tabindex="-1">Scratch stage definition proof</h1><main id="pane-main"></main></div><div id="modalLayer"></div>
<script type="module">
import { createModalController } from '/src/modal.js';
import { createDialogsView } from '/src/views/dialogs.js';
import { createRunDetailView } from '/src/views/runDetail.js';
import { createPipelinesView } from '/src/views/pipelines.js';
import { createChatView } from '/src/views/chat.js';
const source = ${JSON.stringify(source)};
const graph = {stages:[{key:'review', type:'model', prompt:'Review the change.', edges:{success:'#success'}, configs:{}}]};
const detail = {id:7,name:'Review pipeline',version:3,source,graph};
const run = {id:42,pipeline_id:7,version:3,name:'Review pipeline',status:'succeeded',graph,steps:[{stage:'review',sequence:1,status:'succeeded',outcome:'success'}]};
const state = {runDetail:run,pipelineDetail:detail,pipelineTab:'graph',runStageSections:new Set(),runStagePane:{stageKey:'review',visitIndex:0}};
const modal = createModalController();
window.requests = []; window.routes = [];
const rt = {state,modal,views:{},repo:{getPipeline:async(id,version)=>{requests.push({id,version}); if(window.fail) throw new Error('fixture refusal'); if(window.delay) await new Promise(resolve => window.release=resolve); return window.missing ? {...detail,source:null} : detail;}},pushRoute:(r)=>routes.push(r)};
rt.views.chat=createChatView(rt);rt.views.dialogs=createDialogsView(rt);rt.views.runDetail=createRunDetailView(rt);rt.views.pipelines=createPipelinesView(rt);
rt.renderContent=()=>{document.querySelectorAll('.stage-pane').forEach(node=>node.remove());if(state.runStagePane)document.querySelector('main').append(rt.views.runDetail.renderStagePane(run));modal.reconcile();};
window.show = (kind) => {
modal.closeAll();state.runStagePane=null;state.runGraph?.unmount();state.pipelineGraph?.unmount();
const host=document.querySelector('main');
host.replaceChildren(kind==='pipeline' ? rt.views.pipelines.renderPipelineDetail() : rt.views.runDetail.renderRunGraphTab(run));
};
window.pane = () => {state.runStagePane={stageKey:'review',visitIndex:0};document.querySelector('main').append(rt.views.runDetail.renderStagePane(run));modal.reconcile();};
window.expectedSource=source;window.rt=rt;show('run');
</script>`;
const server = createServer(async (req, res) => {
try {
if (req.url === "/") { res.setHeader("content-type", "text/html"); res.end(html); return; }
const path = resolve(root, `.${new URL(req.url, "http://scratch").pathname}`);
if (!path.startsWith(root)) { res.writeHead(403); res.end(); return; }
res.setHeader("content-type", extname(path) === ".css" ? "text/css" : "text/javascript");
res.end(await readFile(path));
} catch { res.writeHead(404); res.end(); }
});
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
let browser;
try {
browser = await launchChrome();
const page = await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
const capture = async (name) => {
await page.evaluate('Promise.all(document.getAnimations().filter(a => a.effect.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})))');
await page.screenshot(resolve(out, name));
};
await page.waitForSelector('.graph-node[data-key="review"]');
const openDefinition = async () => {
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
// Run nodes open visit evidence. Definition is explicit in its audit;
// workflow graph nodes still open authored source directly.
if (await page.evaluate('!!document.querySelector(".stage-pane")')) {
await page.click('.audit-open');
await page.click('[data-audit-tab="definition"]');
}
};
const clickNode = async () => {
await openDefinition();
await page.waitForSelector('.stage-definition-document .field-markdown');
};
await clickNode();
assert.deepEqual(await page.evaluate('requests'), [{ id: 7, version: 3 }]);
assert.equal(await page.evaluate('document.querySelector(".app-root").inert'), true);
await capture("01-run-definition-rendered.png");
await page.clickText('.audit-doc-mode', 'Raw');
assert.equal(await page.evaluate('document.querySelector(".stage-definition-document code").textContent === expectedSource'), true);
assert.equal(await page.evaluate('document.activeElement.textContent'), 'Raw');
await capture("02-run-definition-raw.png");
for (let i = 0; i < 8; i++) {
await page.pressKey('Tab');
assert.equal(await page.evaluate('document.querySelector(".audit-viewer").contains(document.activeElement)'), true);
}
await page.pressKey('Escape');
assert.equal(await page.evaluate('document.activeElement.classList.contains("audit-open")'), true);
await page.pressKey('Escape');
assert.equal(await page.evaluate('document.activeElement.dataset.key'), 'review');
assert.equal(await page.evaluate('location.pathname'), '/');
assert.deepEqual(await page.evaluate('routes'), []);
await page.evaluate("show('pipeline')");
await clickNode();
assert.deepEqual(await page.evaluate('routes'), []);
assert.equal(await page.evaluate('requests.length'), 1);
await capture("03-pipeline-definition-rendered.png");
await page.click('.audit-close');
await page.evaluate("show('run');pane()");
await page.click('.audit-open');
await page.click('[data-audit-tab="definition"]');
await page.waitForSelector('.stage-definition-document .field-markdown');
assert.deepEqual(await page.evaluate('rt.modal.stackIds()'), ['stage-pane','stage-audit']);
await capture("04-visit-definition-nested.png");
await page.pressKey('Escape');
assert.equal(await page.evaluate('!!document.querySelector(".stage-pane")'), true);
assert.equal(await page.evaluate('document.activeElement.classList.contains("audit-open")'), true);
await page.evaluate("show('run');window.missing=true");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await openDefinition();
await page.waitForText('No definition has been reconstructed.');
await capture("05-definition-missing-source.png");
await page.evaluate("show('run');window.missing=false;window.fail=true");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await openDefinition();
await page.waitForText('fixture refusal');
await capture("06-definition-load-failed.png");
await page.evaluate("show('pipeline');window.fail=false");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="#success"]');
await page.waitForText('Terminal nodes have no authored stage definition.');
await capture("07-definition-terminal.png");
await page.evaluate("show('run')");
await clickNode();
await page.resize(390, 844);
await capture("08-definition-narrow.png");
await page.resize(1440, 900);
await page.evaluate("show('run');window.delay=true");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await openDefinition();
await page.waitForText('Loading stage definition…');
await capture("09-definition-loading.png");
await page.clickText('.audit-doc-mode', 'Raw');
await page.evaluate('release()');
await page.waitForSelector('.stage-definition-document code');
assert.equal(await page.evaluate('document.querySelector(".stage-definition-document code").textContent === expectedSource'), true);
await page.evaluate("show('run');window.delay=false;rt.state.runDetail.version=0;window.beforeRequests=requests.length");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await openDefinition();
await page.waitForText('The run did not include its pipeline version.');
assert.equal(await page.evaluate('requests.length === beforeRequests'), true);
await capture("10-definition-missing-version.png");
console.log(`PASS: explicit run-visit audit / workflow definition popup, exact source, keyboard focus/escape, nested stage preservation, missing/error states; captures ${out}`);
} finally {
await browser?.close();
await new Promise(resolve => server.close(resolve));
}