web: connection banner, reconnect, foreground recovery and live badge (T3/T4/T5)

Close T3, T4 and T5 of web/PARITY.md (the "Transport and connection"
table). T1/T2/T6 are untouched beyond wiring.

- src/connection.js (new): the pure, DOM/socket/timer-free helpers behind
  every new state — `bannerState` (the persistent banner's copy and tone),
  `stateBadge` (the compact header indicator, which is also where the retry
  attempt is named), `foregroundAction` (the return-to-foreground policy
  from ConnectionRecovery.kt), `protocolMismatch`, `serverBuildLabel` and
  `liveBadgeState`. Wording and colour roles mirror ConnectionBanner.kt,
  LiveBadge.kt/RunStream.kt and SettingsScreen.kt.
- src/app.js: wiring only. The banner sits in normal document flow under
  the header (never overlaying content); a Reconnect control appears beside
  the URL field whenever `bannerState` offers one and re-opens the same
  validated endpoint through `client.connect`, resetting the backoff;
  `visibilitychange`/`online` drive the foreground recovery; the ping reply
  records the server build and protocol for the banner.
- src/protocol.js: `PROTOCOL_VERSION = 1`, citing internal/protocol/
  identity.go and Message.kt.
- styles.css: the .conn-* banner and .live-badge rules in the app's dark
  palette, on the existing :root variables.
- test/connection.test.mjs (new): 18 focused unit tests for the pure
  helpers, including source-parity assertions against the Android files.
- test/ui-smoke.mjs: assert the connected banner + build line + live badge
  and capture them, then point the page at a closed port to capture the
  disconnected retry banner and recover via the browser's `online` event.
- PARITY.md: T3/T4/T5 done with their captures.

Checks: `node --check` on all five touched JS/MJS files; `node --test
test/` 190 pass / 0 fail (18 new); `node test/ui-smoke.mjs --out ...
/web/captures` UI SMOKE PASS against ws://127.0.0.1:8080/connect, writing
28-connected-banner.png, 29-disconnected-banner.png and
30-reconnect-recovered.png.
This commit is contained in:
2026-10-19 04:06:18 +01:00
parent 2e9ff1704f
commit 71342fe027
7 changed files with 746 additions and 53 deletions
+236
View File
@@ -0,0 +1,236 @@
// 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,
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 is live only while executing on a connected socket", () => {
assert.deepEqual(liveBadgeState({ executing: true }, { kind: "connected" }), { tone: "live", label: "live" });
assert.deepEqual(liveBadgeState({ executing: true }, { kind: "disconnected" }), {
tone: "reconnecting",
label: "reconnecting",
});
assert.deepEqual(liveBadgeState({ executing: true }, { kind: "connecting" }), {
tone: "reconnecting",
label: "reconnecting",
});
assert.deepEqual(liveBadgeState({ executing: false }, { kind: "connected" }), { tone: "not-live", label: "not live" });
assert.deepEqual(liveBadgeState(null, { kind: "connected" }), { tone: "not-live", label: "not live" });
assert.deepEqual(liveBadgeState({ executing: true }, { kind: "idle" }), { 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}`);
}
});
+120 -8
View File
@@ -9,6 +9,7 @@
// or a scratch one) and the installed Chrome; it has no npm dependencies.
import { spawn } from "node:child_process";
import { mkdir, rm } from "node:fs/promises";
import net from "node:net";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -16,6 +17,17 @@ import { eventually, launchChrome } from "./browser.mjs";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
/** A port that is bound and immediately released, so nothing listens on it. */
async 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));
});
});
}
function flag(argv, name, fallback) {
const i = argv.indexOf(name);
return i !== -1 && argv[i + 1] ? argv[i + 1] : fallback;
@@ -54,6 +66,38 @@ async function shot(name) {
const text = (selector) =>
page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.textContent ?? ""`);
// The shared live server can drop a long-lived socket while the earlier screens
// are captured (observed as a spurious 1006 mid-run). A capture step must not
// depend on an unasserted connection, so this nudges the page's own recovery —
// its `online` handler resets the backoff — and waits for the green banner
// before the step reads anything.
async function ensureConnected(timeout = 25000) {
const ok = await page.evaluate(
`document.querySelector(".conn-banner")?.classList.contains("conn-ok") ?? false`,
);
if (!ok) await page.evaluate(`window.dispatchEvent(new Event("online"))`);
await page.waitForSelector(".conn-banner.conn-ok", { timeout });
}
// Open a run's detail. The connection is asserted first, and if the socket drops
// between steps the page's reconnect does not replay the detail request, so the
// click is retried once after re-establishing the connection.
async function openRunDetail(runId) {
const row = `.list.runs .run-row-meta[data-run-id="${runId}"]`;
for (let attempt = 0; attempt < 2; attempt += 1) {
await ensureConnected();
try {
await page.waitForSelector(row, { timeout: 20000 });
await page.click(row);
await page.waitForSelector(".detail .detail-tabs", { timeout: 20000 });
return;
} catch (error) {
if (attempt === 1) throw error;
console.log(` retrying run ${runId} after a dropped connection`);
}
}
}
// The mounted graph's current transform, read back so the pan/zoom clamp checks
// assert the real rendered state rather than a claim.
const graphState = () =>
@@ -388,6 +432,7 @@ try {
console.log(" a node with no stage reads: No details recorded for this node.");
step("switching to Runs: day-grouped list + usage roll-up");
await ensureConnected();
await page.clickText("nav.tabs button.tab", "Runs");
await page.waitForSelector(".list.runs .day-header", { timeout: 25000 });
await page.waitForSelector(".metrics .metric", { timeout: 25000 });
@@ -526,6 +571,7 @@ try {
console.log(` empty state: ${emptyMessage} (+ ${clearAction})`);
step("clearing the filters from the empty state and changing the sort");
await ensureConnected();
await page.click(".list.runs .empty-state button");
await page.waitForSelector(".list.runs .day-header", { timeout: 25000 });
const resetLabel = await page.evaluate(`document.querySelector("#runFilterBtn").textContent`);
@@ -587,8 +633,7 @@ try {
await page.fill("#url", artifactServerUrl);
await page.clickText("nav.tabs button.tab", "Runs");
await page.waitForSelector(".list.runs .run-row", { timeout: 25000 });
await page.click('.list.runs .run-row-meta[data-run-id="430"]');
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await openRunDetail(430);
// The run-detail tabs, in the app's order (the Graph body is the R5 item).
const runTabs = await page.evaluate(
@@ -749,8 +794,7 @@ try {
// The verdict-bearing stage pane on the failed run 440.
step("opening run 440 and capturing its verdict-bearing stage pane");
await page.click('.list.runs .run-row-meta[data-run-id="440"]');
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await openRunDetail(440);
await page.clickText(".detail .detail-tabs .detail-tab", "Timeline");
await page.waitForSelector(".detail .timeline-row", { timeout: 15000 });
await page.click(".detail .timeline-row");
@@ -771,8 +815,7 @@ try {
// The Timeline empty state, on a run that recorded no visits (R7).
step("opening run 428: the Timeline empty state");
await page.click('.list.runs .run-row-meta[data-run-id="428"]');
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await openRunDetail(428);
await page.clickText(".detail .detail-tabs .detail-tab", "Timeline");
await page.waitForSelector(".detail .run-tab-body .run-empty", { timeout: 15000 });
const emptyTimeline = await page.evaluate(
@@ -794,8 +837,7 @@ try {
if (runningId == null) {
console.log(" -- no running run available; skipped the output empty state");
} else {
await page.click(`.list.runs .run-row-meta[data-run-id="${runningId}"]`);
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await openRunDetail(runningId);
await page.clickText(".detail .detail-tabs .detail-tab", "Output");
await page.waitForSelector(".detail .run-tab-body .run-empty", { timeout: 15000 });
const emptyOutput = await page.evaluate(
@@ -808,6 +850,76 @@ try {
shots.push(await page.screenshot(`${out}/27-run-output-empty.png`));
}
// T5: the connected connection banner, the server build line and the live
// badge. The banner is in normal flow under the header, so scroll to the top.
step("capturing the connected banner, server build and live badge (T5)");
await page.clickText("nav.tabs button.tab", "Runs");
await page.waitForSelector(".list.runs .run-row", { timeout: 25000 });
// Assert the connection before this capture rather than trusting a long-lived
// socket that may have dropped while the earlier screens were captured.
await ensureConnected();
await page.evaluate(`window.scrollTo(0, 0)`);
const connectedText = await text(".conn-banner .conn-banner-text");
if (!connectedText.includes("Connected")) throw new Error(`connected banner text: ${connectedText}`);
const buildLabel = await text(".conn-banner .conn-build");
if (!buildLabel.startsWith("Server build ")) throw new Error(`missing server build line: ${buildLabel}`);
const live = await page.evaluate(`(() => {
const badge = document.querySelector(".list.runs .live-badge");
return badge ? { text: badge.textContent.trim(), cls: badge.className } : null;
})()`);
if (!live) throw new Error("no live badge rendered in the runs list");
console.log(` banner: ${connectedText} — ${buildLabel}; badge: ${live.text} (${live.cls})`);
await shot("28-connected-banner.png");
// T3/T4: the disconnected banner with the retry message. Point the page at a
// closed port, disconnect, then use the Reconnect control beside the URL field
// (T3) and let the attempt fail: a failed reconnect is expected here and must
// not fail the run.
step("capturing the disconnected banner with the retry message (T3/T4)");
const closedPort = await freePort();
await page.fill("#url", `ws://127.0.0.1:${closedPort}/connect`);
await page.click("#connectBtn"); // currently connected: this Disconnects
await page.waitForSelector("#reconnectBtn", { timeout: 15000 });
const idleText = await text(".conn-banner .conn-banner-text");
if (idleText !== "Not connected. Enter the server URL in Settings, then connect.") {
throw new Error(`idle banner text: ${idleText}`);
}
await page.click("#reconnectBtn"); // immediate reconnect to the closed port
await page.waitForSelector(".conn-banner.conn-error", { timeout: 15000 });
await page.waitForText("retrying with backoff", { timeout: 15000 });
const disconnectedText = await text(".conn-banner .conn-banner-text");
if (!/^Disconnected: .+ · retrying with backoff$/.test(disconnectedText)) {
throw new Error(`disconnected banner text: ${disconnectedText}`);
}
// The banner text is ConnectionBanner.kt verbatim (no attempt); the retry
// attempt is the header state badge's job, so the capture must show it there.
const badgeText = await text("#stateBadge");
if (!/disconnected .+ \(attempt \d+, retrying\)/.test(badgeText)) {
throw new Error(`disconnected state badge does not name the attempt: ${badgeText}`);
}
console.log(` disconnected banner: ${disconnectedText}`);
console.log(` disconnected badge: ${badgeText}`);
await shot("29-disconnected-banner.png");
// T4: return-to-foreground recovery. Point back at the live server and let the
// page's own `online` handler drive the socket back without a Reconnect click.
// The decision itself (foregroundAction) is unit-tested in
// test/connection.test.mjs; this proves the rendered recovery in the browser.
step("recovering via the browser's online event and capturing the banner (T4)");
await page.fill("#url", `ws://127.0.0.1:${port}/connect`);
const foregroundText = await text(".conn-banner .conn-banner-text");
if (!foregroundText.startsWith("Disconnected:")) {
throw new Error(`expected a disconnected state before the online event: ${foregroundText}`);
}
await page.evaluate(`window.dispatchEvent(new Event("online"))`);
await page.waitForSelector(".conn-banner.conn-ok", { timeout: 25000 });
await page.waitForSelector(".list.runs .run-row", { timeout: 25000 });
await page.evaluate(`window.scrollTo(0, 0)`);
const recoveredText = await text(".conn-banner .conn-banner-text");
if (!recoveredText.includes("Connected")) throw new Error(`recovered banner text: ${recoveredText}`);
console.log(` recovered banner after window online: ${recoveredText}`);
await shot("30-reconnect-recovered.png");
console.log("\nUI SMOKE PASS");
for (const shot of shots) console.log(` ${shot}`);
} catch (error) {